-
Notifications
You must be signed in to change notification settings - Fork 1
/
pxtsim.js
1 lines (1 loc) · 176 KB
/
pxtsim.js
1
var pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(e){let t;e.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},e.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},e.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},e.setLiveContent=function(e){if(!t){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";t=document.createElement("div"),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-hidden","false"),t.setAttribute("style",e),document.body.appendChild(t)}t.textContent!==e&&(t.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",s="orange";const i=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function r(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(e,t,n){let s=[];const i=(e,t,s,i)=>{let r=[];for(let t=0;t<e.numberOfPins;t++){let i,o=e.pinDefinitions[t];if("string"==typeof o.target)i=o.target;else{let e=o.target.pinInstantiationIdx;if(!s||void 0===s[e])return void console.log(`error: parts no pin found for PinInstantiationIdx: ${e}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);i=s[e]}let a=e.visual.pinLocations[t],l=n.yOffset+a.y,u=Math.round(l/e.visual.pinDistance),c=l-u*e.visual.pinDistance,h=n.xOffset+a.x,d=Math.round(h/e.visual.pinDistance),p={partRelativeRowIdx:u,partRelativeColIdx:d,xOffset:h-d*e.visual.pinDistance,yOffset:c};r.push({def:o,loc:a,target:i,bbFit:p})}return{name:t,def:e,pins:r,partParams:i||{},bbFit:n}},r=e.instantiations||[];return e.instantiation&&r.push(e.instantiation),r.forEach((n=>{if("singleton"===n.kind)s.push(i(e,t));else if("function"===n.kind){let r=n,a=r.fullyQualifiedName.split(","),l={};a.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{l[e]=1}))}));let u=Object.keys(l);if(!u||!u.length)return void console.log(`error: parts failed to read pin(s) from callsite for: ${a}`);u.forEach((n=>{const l=n.split(",");if(l.length!=r.argumentRoles.length)return void console.log(`error: parts mismatch between number of arguments at callsite (function name: ${a}) vs number of argument roles in part definition (part: ${t}).`);let u=[],c={};l.forEach(((e,t)=>{let n=r.argumentRoles[t];if(void 0!==n.partParameter&&(c[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,s=o(e);u[t]=s}})),s.push(i(e,t,u,c))}))}})),s.filter((e=>!!e))}computePartDimensions(t,n){let s=t.visual.pinLocations,i=t.pinDefinitions,o=t.numberOfPins;e.U.assert(s.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,u,c,h=s.map(((e,t)=>{return n={idx:t},s=e,o=i[t],r(r(n,s),o);var n,s,o})).filter((e=>"-Z"===e.orientation)),d=h.length>0,p=t.visual.pinDistance;if(d){let e=h[0],n=Math.ceil(e.x/p),s=Math.ceil(e.y/p);a=n*p-e.x,l=s*p-e.y,u=Math.ceil((a+t.visual.width)/p)+1,c=Math.ceil((l+t.visual.height)/p)+1}else u=Math.ceil(t.visual.width/p),c=Math.ceil(t.visual.height/p),a=u*p-t.visual.width,l=c*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:c,colCount:u}}allocColumns(t){let n=t.length;let s=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);s<=0&&console.log("Not enough breadboard space!");let i=Math.floor(s/(n-1+2)),r=s-i*(n-1),o=Math.floor(r/2),a=(Math.ceil(r/2),1+o);return t.map((e=>{let t=a;return a+=e.colCount+i,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let s=this.allocColumns(t.map((e=>e.bbFit))),i=t.map((e=>{let t=n-e.bbFit.rowCount,s=Math.floor(t/2);return s>4&&(s=4),s<1&&(s=1),s}));return t.map(((e,t)=>{let n=i[t];return r({startColumnIdx:s[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(i){let o=[],l=i.pins.map(((r,l)=>{let u,c,h=r.target,d=i.startColumnIdx+r.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(d),m=i.startRowIdx+r.bbFit.partRelativeRowIdx;if(m>=7&&(m-=2),a(r.def)){u={type:"breadboard",row:m<5?"j":"a",col:p,style:r.def.style}}else{u={type:"breadboard",row:e.visuals.getRowName(m),col:p,xOffset:r.bbFit.xOffset/i.def.visual.pinDistance,yOffset:r.bbFit.yOffset/i.def.visual.pinDistance,style:r.def.style}}return c="ground"===h?t:"threeVolt"===h?n:"fiveVolt"===h?s:"number"==typeof r.def.colorGroup?o[r.def.colorGroup]?o[r.def.colorGroup]:o[r.def.colorGroup]=this.nextColor():this.nextColor(),{start:u,end:h,color:c,pinIdx:l}}));return r(i,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let s=this.opts.getBBCoord(n.referenceBBPin),i=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));i[0]&&i[1]||console.debug(`No more available "${t}" locations!`);let r,o=0==e.visuals.findClosestCoordIdx(s,i);o?"ground"===t?r=this.availablePowerPins.top.ground:"threeVolt"===t?r=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.top.fiveVolt):"ground"===t?r=this.availablePowerPins.bottom.ground:"threeVolt"===t?r=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.bottom.fiveVolt);let a=r.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(s,a),u=r[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),u}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||console.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||console.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,s=this.opts.boardDef.gpioPinMap[n]||n;return s?{type:"dalboard",pin:s}:void console.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let e=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return e||console.debug("No available ground pin on board!"),e}getBoardThreeVoltPin(){let e=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return e||console.debug("No available 3.3V pin on board!"),e}getBoardFiveVoltPin(){let e=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return e||console.debug("No available 5V pin on board!"),e}allocPowerWires(e){let i=this.getBoardGroundPin(),r=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},u={type:"breadboard",row:"-",col:"50"},c={type:"breadboard",row:"-",col:"25"};let h,d;this.opts.boardDef.attachPowerOnRight?(h=u,d=c):(h=a,d=l);let p=[],m=[],f=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:this.allocLocation("ground",{referenceBBPin:d}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:i},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:i},color:t}),e.bottomThreeVolt&&e.bottomGround?m.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:this.allocLocation("threeVolt",{referenceBBPin:d}),color:n}):e.bottomFiveVolt&&e.bottomGround&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:this.allocLocation("fiveVolt",{referenceBBPin:d}),color:s}),e.topThreeVolt?m.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:n}):e.bottomThreeVolt&&m.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:s}),e.topFiveVolt&&!e.topThreeVolt?f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:s});let g=[];p.length>0&&g.push({wireIndices:p.map(((e,t)=>t))});let b=p.length;return m.length>0&&g.push({wireIndices:m.map(((e,t)=>t+b))}),f.length>0&&g.push({wireIndices:m.map(((e,t)=>t+b+m.length))}),{wires:p.concat(m).concat(f),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let s=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(s=s.map(((e,n)=>{if(e)return e;const i=s[1-n];return this.allocLocation(t[n],{referenceBBPin:i})})),s[0]&&s[1])return{start:s[0],end:s[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let s=t.startRowIdx+n.bbFit.partRelativeRowIdx;s>=7&&(s-=2);let i=e.visuals.getRowName(s),r=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:i,col:e.visuals.getColumnName(r)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,s)=>{let i=t[s],r=this.allocPartIRs(e.def,e.name,i);n=n.concat(r)}));const s=this.placeParts(n).map((e=>this.allocWireIRs(e))),r=s.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),s=t.map((e=>"threeVolt"===e)),r=t.map((e=>"fiveVolt"===e)),o=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=i(n),l=i(s),u=i(r),c=i(o);return{topGround:a&&!c,topThreeVolt:l&&!c,topFiveVolt:u&&!c,bottomGround:a&&c,bottomThreeVolt:l&&c,bottomFiveVolt:u&&c,singleGround:a,singleThreeVolt:l,singleFiveVolt:u}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(r);const o=this.allocPowerWires(this.powerUsage),a=s.map(((e,t)=>{const n=this.allocPart(e),s=e.wires.map((e=>this.allocWire(e)));if(s.some((e=>!e)))return;const i=[];e.wires.forEach(((e,t)=>{i[e.pinIdx]=t}));return{part:n,wires:s,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>i[e]))})))}})).filter((e=>!!e)),l=[o].concat(a).filter((e=>e.assembly&&e.assembly.length)),u=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:u}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e){this.seq=0,this.type=e}}e.Message=t;e.Response=class extends t{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class n extends t{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}e.Event=n;e.Source=class{constructor(e,t,n=0,s,i){this.name=e,this.path=t,this.sourceReference=n,s&&(this.origin=s),i&&(this.adapterData=i)}};e.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};e.StackFrame=class{constructor(e,t,n,s=0,i=0){this.id=e,this.source=n,this.line=s,this.column=i,this.name=t}};e.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};e.Variable=class{constructor(e,t,n=0,s,i){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof i&&(this.namedVariables=i),"number"==typeof s&&(this.indexedVariables=s)}};e.Breakpoint=class{constructor(e,t,n,s){this.verified=e;const i=this;"number"==typeof t&&(i.line=t),"number"==typeof n&&(i.column=n),s&&(i.source=s)}};e.Module=class{constructor(e,t){this.id=e,this.name=t}};e.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};e.StoppedEvent=class extends n{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};e.ContinuedEvent=class extends n{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};e.InitializedEvent=class extends n{constructor(){super("initialized")}};e.TerminatedEvent=class extends n{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};e.OutputEvent=class extends n{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};e.ThreadEvent=class extends n{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};e.BreakpointEvent=class extends n{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};e.ModuleEvent=class extends n{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class s{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(e){e.seq>0?console.error(`attempt to send more than one response for command ${e.command}`):this.send("response",e)}sendRequest(t,n,s,i){const r={command:t};if(n&&Object.keys(n).length>0&&(r.arguments=n),this.send("request",r),i){this._pendingRequests[r.seq]=i;const t=setTimeout((()=>{clearTimeout(t);const n=this._pendingRequests[r.seq];n&&(delete this._pendingRequests[r.seq],n(new e.Response(r,"timeout")))}),s)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}e.ProtocolServer=s;class i extends s{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(t){const n=new e.Response(t);try{if("initialize"===t.command){let e=t.arguments;if("boolean"==typeof e.linesStartAt1&&(this._clientLinesStartAt1=e.linesStartAt1),"boolean"==typeof e.columnsStartAt1&&(this._clientColumnsStartAt1=e.columnsStartAt1),"path"!==e.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const t=n;t.body={},this.initializeRequest(t,e)}}else"launch"===t.command?this.launchRequest(n,t.arguments):"attach"===t.command?this.attachRequest(n,t.arguments):"disconnect"===t.command?this.disconnectRequest(n,t.arguments):"setBreakpoints"===t.command?this.setBreakPointsRequest(n,t.arguments):"setFunctionBreakpoints"===t.command?this.setFunctionBreakPointsRequest(n,t.arguments):"setExceptionBreakpoints"===t.command?this.setExceptionBreakPointsRequest(n,t.arguments):"configurationDone"===t.command?this.configurationDoneRequest(n,t.arguments):"continue"===t.command?this.continueRequest(n,t.arguments):"next"===t.command?this.nextRequest(n,t.arguments):"stepIn"===t.command?this.stepInRequest(n,t.arguments):"stepOut"===t.command?this.stepOutRequest(n,t.arguments):"stepBack"===t.command?this.stepBackRequest(n,t.arguments):"restartFrame"===t.command?this.restartFrameRequest(n,t.arguments):"goto"===t.command?this.gotoRequest(n,t.arguments):"pause"===t.command?this.pauseRequest(n,t.arguments):"stackTrace"===t.command?this.stackTraceRequest(n,t.arguments):"scopes"===t.command?this.scopesRequest(n,t.arguments):"variables"===t.command?this.variablesRequest(n,t.arguments):"setVariable"===t.command?this.setVariableRequest(n,t.arguments):"source"===t.command?this.sourceRequest(n,t.arguments):"threads"===t.command?this.threadsRequest(n):"evaluate"===t.command?this.evaluateRequest(n,t.arguments):"stepInTargets"===t.command?this.stepInTargetsRequest(n,t.arguments):"gotoTargets"===t.command?this.gotoTargetsRequest(n,t.arguments):"completions"===t.command?this.completionsRequest(n,t.arguments):this.customRequest(t.command,n,t.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,s){let r;"number"==typeof t?(r={id:t,format:n},s&&(r.variables=s),r.showUser=!0):r=t,e.success=!1,i.formatPII(r.format,!0,r.variables),e.body||(e.body={}),e.body.error=r,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?i.uri2path(e):i.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?i.uri2path(e):i.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(i._formatPIIRegexp,(function(e,s){return t&&s.length>0&&"_"!==s[0]?e:n[s]&&n.hasOwnProperty(s)?n[s]:e}))}}i._formatPIIRegexp=/{([^}]+)}/g,e.DebugSession=i}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,s=arguments[1],i=s>>0,r=i<0?Math.max(n+i,0):Math.min(i,n),o=arguments[2],a=void 0===o?n:o>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;r<l;)t[r]=e,r++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const s=arguments[1];let i=0;for(;i<n;){const n=t[i];if(e.call(s,n,i,t))return n;i++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,s=65535&t;return n*s+((e>>>16&65535)*s+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const s=t(e),i=t(n);let r=0;for(;s[r]===i[r]&&(r++,r!==s.length&&r!==i.length););const o=s.slice(r),a=i.slice(r);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},s=e.runtime.currFrame;for(;null!=s;)n.breakpointIds.push(s.lastBrkId),s=s.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let s=e.RefObject.toDebugString(t),i=s.startsWith("[")?"array":s;return{id:t.id,preview:s,hasFields:null!==t.fields||s.startsWith("["),type:i}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(e,n,i,r){return function(e,i){const o={};for(let s of Object.keys(e))/^__/.test(s)||!/___\d+$/.test(s)||r&&-1===r.indexOf(s)||(o[s]=t(e[s],n));if(e.fields&&i)for(let r of i)r=r.substring(r.lastIndexOf(".")+1),o[r]=t(s(e.vtable.iface[r],e),n);if(e.fields)for(let s of Object.keys(e.fields).filter((e=>!e.startsWith("_"))))o[s]=t(e.fields[s],n);else Array.isArray(e.data)&&e.data.forEach(((e,s)=>{o[s]=t(e,n)}));return o}(e,i)}function s(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function i(e,s){let i=e.fn?e.fn.info:null;if(i){let r={thisParam:t(e.argL,s),params:[]};if(i.argumentNames){const n=i.argumentNames;r.params=n.map(((n,i)=>({name:n,value:t(e["arg"+i],s)})))}return{locals:n(e,s),funcInfo:i,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:r}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let s;if(n)for(const[e,i]of n)i.line<=t.line&&i.endLine>=t.line&&(s=[e,i]);return s?(s[1].verified=!0,s):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,s){const i=e.runtime.environmentGlobals;if(!Object.keys(i).length)return;const r=n.environmentGlobals={};Object.keys(i).forEach((n=>r[n]=t(e.runtime.environmentGlobals[n],s)))},e.getBreakpointMsg=function(t,s,r){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:s,globals:n(e.runtime.globals,o,void 0,r),stackframes:[]};for(;null!=t;){let e=i(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class r extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,s,i,r){this.breakpoints=i,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:s,boardDefinition:r})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const s=[];n.breakpoints.forEach((i=>{if(this.breakpoints){const[r,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),i);t.body.breakpoints.push(o),o.verified&&s.push(r)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(s),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:r.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",r.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",r.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}r.THREAD_ID=1,e.SimDebugSession=r;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const s=this.nextId();this._vars[s]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:s,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const s=t[n];let i,r=0;null===s?i="null":void 0===s?i="undefined":"object"==typeof s?(i="(object)",r=this.nextId(),this._vars[r]=this.getVariableValues(s)):i=s.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:i,variablesReference:r})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){let t,n;function s(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}function i(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function o(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}!function(e){let t;!function(e){e[e.Player=0]="Player",e[e.Reaction=1]="Reaction"}(t=e.IconType||(e.IconType={}))}(t=e.multiplayer||(e.multiplayer={})),e.print=s,function(t){function n(t){t.origin;let n=t.data||{},o=n.type;if(o)switch(o){case"run":l(n);break;case"instructions":e.instructions.renderInstructions(n);break;case"stop":a();break;case"mute":u(n.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":s();break;case"recorder":!function(e){if(!r)return;switch(e.action){case"start":r.startRecording(e.width);break;case"stop":r.stopRecording()}}(n);break;case"screenshot":e.Runtime.postScreenshotAsync(n);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(n);break;case"pxteditor":break;case"debugger":r&&r.handleDebuggerMsg(n);break;case"simulator":let t=n;switch(t.command){case"focus":i("simulator.focus",{timestamp:t.timestamp});break;case"blur":i("simulator.blur",{timestamp:t.timestamp})}default:!function(e){if(!r||r.dead)return;r.board.receiveMessage(e)}(n)}}let r;function a(){r&&(r.kill(),r.board&&r.board.kill())}function l(t){a(),t.mute&&u(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);r=n,n.board.initAsync(t).then((()=>{n===r&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function u(t){e.AudioContextManager.mute(t)}t.start=function(){window.addEventListener("message",n,!1),t.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const e=window.location.pathname,t=e.substring(1,e.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const n=e.data;n&&"serviceworker"===n.type&&"activated"===n.state&&n.ref===t&&o()}));const n=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(n).then((function(e){console.log("Simulator ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("Simulator ServiceWorker registration failed: ",e)}))}}(),e.Runtime.postMessage({type:"ready",frameid:t.frameid})},t.stop=a,t.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=i,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=o}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,s=.95,[i,r]=[816*s,1056*s],o=i-86.4,a=r-86.4,[l,u]=[1,1],c=24,h=o/u-48*u,d=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${h}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(h-465)/2+c}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function p(t,n){let s=document.createElementNS("http://www.w3.org/2000/svg","svg"),i={l:0,t:0,w:0,h:0},r=document.createElementNS("http://www.w3.org/2000/svg","svg");s.appendChild(r),r.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};i.w=t.w,i.h=t.h;let a=e=>{i.h*=e,i.w*=e,o.width=i.w,o.height=i.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<i.w?a(n.cmpWidth/i.w):n.cmpHeight&&n.cmpHeight<i.h&&a(n.cmpHeight/i.h),e.svg.hydrate(r,o);let l=i.l,u=i.t,c=i.w,h=i.h,d=e=>{if(e<i.l){let t=i.l-e;i.l=e,i.w+=t}},p=e=>{let t=i.l+i.w;if(t<e){let n=e-t;i.w+=n}},m=e=>{if(e<i.t){let t=i.t-e;i.t=e,i.h+=t}},f=e=>{let t=i.t+i.h;if(t<e){let n=e-t;i.h+=n}},[g,b]=[-.3,.3];const v=[1.4,1];if(n&&n.top){let t=n.topSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u-3-r/2],h=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(h,"cmp-lbl"),s.appendChild(h);let f=i*n.top.length;m(a-r/2),d(o-f/2),p(o+f/2)}if(n&&n.bot){let t=n.botSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u+h+3+r/2],m=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(m,"cmp-lbl"),s.appendChild(m);let y=i*n.bot.length;f(a+r/2),d(o-y/2),p(o+y/2)}if(n&&n.right){let t=n.rightSize,i=t/v[1],r=t/v[0]*n.right.length,[o,a]=[l+c+5+r/2,u+h/2],d=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(d,"cmp-lbl"),s.appendChild(d),m(a-i/2),p(o+r/2),f(a+i/2)}if(n&&n.left){let t=n.leftSize,i=t/v[1],r=t/v[0]*n.left.length,[o,a]=[l-5-r/2,u+h/2],c=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(c,"cmp-lbl"),s.appendChild(c),m(a-i/2),d(o-r/2),f(a+i/2)}let y={viewBox:`${i.l} ${i.t} ${i.w} ${i.h}`,width:1.7*i.w,height:1.7*i.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(s,y);let w=document.createElement("div");return w.appendChild(s),w}function m(t,n){let s,i=e.runtime.board;if("wire"==t)s=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){s=(0,i.builtinPartVisuals[n.builtIn])([0,0])}else s=e.visuals.mkGenericPartSVG(n)}return p(s,n)}function f(t,n,s=!1){const i={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:s,partsList:[]};let r=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:i.boardDef.visual,boardDef:i.boardDef,wireframe:i.wireframe}),i),o=r.getView();return e.U.addClass(o,"board-svg"),r}function g(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function b(t){let s=g();var i;let r=p((i=t.boardDef,e.visuals.mkBoardView({visual:i.visual,boardDef:i}).getView()),{left:n(1),leftSize:30,cmpScale:.17});s.appendChild(r);let o=p(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return s.appendChild(o),t.allCmps.forEach((t=>{let i=1;"buttonpair"===t.visual.builtIn&&(i=2);let r=m(t.visual,{left:n(i),leftSize:30,cmpScale:.3});e.U.addClass(r,"partslist-cmp"),s.appendChild(r)})),t.allWireColors.forEach((i=>{let r=t.colorToWires[i].length,o=t.boardDef.pinStyles[i]||"female",a=m("wire",{left:n(r),leftSize:20,wireClr:i,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),s.appendChild(a)})),s}function v(t,n){let s=g(),i=f(n,465,!0);!function(t,n,s){let i=t.getView();n>0&&e.U.addClass(i,"grayed");for(let i=0;i<=n;i++){let r=s.stepToCmps[i];r&&r.forEach((s=>{let r=t.addPart(s);i===n&&(s.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(r.element,"notgrayed"))}));let o=s.stepToWires[i];o&&o.forEach((e=>{let s=t.addWire(e);s&&i===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(s))}))}}(i,t,n),s.appendChild(i.getView());let r=document.createElement("div");e.U.addClass(r,"panel-num-outer"),e.U.addClass(r,"noselect"),s.appendChild(r);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",r.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),s.appendChild(a);let l=n.stepToWires[t]||[],u=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let s=!1;"dalboard"==t.end.type&&(s="croc"==n.boardDef.pinStyles[t.end.pin]);let i=m("wire",{top:u(t.end),topSize:10,bot:u(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:s});e.U.addClass(i,"cmp-div"),a.appendChild(i)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,s)=>{let i;if(n){let{row:e,col:t}=n;i=`(${e},${t})`}else i="";let r=1.5;"buttonpair"===t.visual.builtIn&&(r*=.5);let o=m(t.visual,{top:i,topSize:10,cmpHeight:50,cmpScale:r});e.U.addClass(o,"cmp-div"),a.appendChild(o)}))})),s}function y(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const s={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(s),e.runtime.board=null,e.initCurrentRuntime(s);let i=document.createElement("style");i.textContent+=d,document.head.appendChild(i);const r=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),s=[],i=[],r=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,o)=>{e.part&&t&&(i[r+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(s[r+o]=e.wireIndices.map((e=>n[e])))})),r+=e.assembly.length}));let o=r-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),u={},c=[];return l.forEach((e=>{u[e.color]||(u[e.color]=[],c.push(e.color)),u[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:s,stepToCmps:i,allWires:l,allCmps:a,lastStep:o,colorToWires:u,allWireColors:c}}({boardDef:n.boardDef,partDefs:r,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=f(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=b(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=v(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=y,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",y(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,s,i,r,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class u{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?e.vtable.name:e.toDebugString?e.toDebugString():"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=u;class c{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=c;class h extends u{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRecord id:${this.id} (${this.vtable.name})`)}}e.RefRecord=h;class d extends u{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=d,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new d;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let s=e.getResume();s(t instanceof d?new c(t.func,t.fields,n):new c(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(e){let t="";const s=(e,n)=>{t+=e.length>=n?e:(" "+e).slice(-n)},i=e=>s(""+Math.round(e),6),r=(e,n)=>{s(Math.round(n)+"",8),t+=" /",i(e),t+=" =",i(n/e)};for(let s of e.split(/\n/)){if(!s)continue;if(!/^\d/.test(s))continue;const e=s.split(/,/);let l=n[e[2]];l||(n[e[2]]=l={stops:0,us:0,meds:[]}),o=e[2],a=25,t+=o.length>=a?o:(o+" ").slice(0,a);const u=parseInt(e[0]),c=parseInt(e[1]);r(u,c),t+=" |",r(u-l.stops,c-l.us),t+=" ~";const h=parseInt(e[3]);i(h),l.meds.length>10&&l.meds.shift(),l.meds.push(h);const d=l.meds.slice();d.sort(((e,t)=>e-t));const p=d[d.length>>1];t+=" ~~",i(p),l.stops=u,l.us=c,t+="\n"}var o,a;console.log(t)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends u{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class m extends u{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefMap id:${this.id} size:${this.data.length}`)}toAny(){const e={};return this.data.forEach((t=>{e[t.key]=u.toAny(t.val)})),e}}function f(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=m,e.dumpLivePointers=f,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(s=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(i=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){f()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let s=e.getConfig(t);return null==s?n:s},t.toInt=function(e){return e>>0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function s(e,t){if(t+="",e instanceof h){return e.fields[t]}let n=e.findIdx(t);if(!(n<0))return e.data[n].val}function i(e,t,n){if(t+="",e instanceof h){return void(e.fields[t]=n)}let s=e.findIdx(t);s<0?e.data.push({key:t,val:n}):e.data[s].val=n}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new p},n.stclo=function(e,n,s){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=s,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new m},n.mapGet=function(e,t){return s(e,n.mapKeyNames[t])},n.mapSet=function(e,t,s){return i(e,n.mapKeyNames[t],s)},n.mapGetByString=s,n.mapDeleteByString=function(e,t){e instanceof m||n.panic(923);let s=e.findIdx(t);return s>=0&&e.data.splice(s,1),!0},n.mapSetGeneric=i,n.mapGetGeneric=s,n.mapSetByString=i,n.keysOf=function(t){let n=new e.RefCollection;if(t instanceof m)for(let e of t.data)n.push(e.key);return n}}(r=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new h;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){t.panic=r.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule((()=>{n()}),t)},t.runInBackground=function(t){e.runtime.runFiberAsync(t)},t.forever=function(t){r.nullCheck(t),function n(){e.runtime.runFiberAsync(t).then((()=>e.U.delay(20))).then(n)}()}}(o=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map((t=>e.RefObject.toAny(t)))}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let s=e.RefObject.toDebugString(this.data[n]);if(t.length+s.length>100){0==n&&(t+=s.substr(0,100)),t+="...";break}t+=s}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,s,i,r,o,a,l,u;e.RefCollection=t,function(n){function s(t,n){if(e.pxtrt.nullCheck(t),t.isValidIndex(n))return t.removeAt(n)}function i(t,n,s){return e.pxtrt.nullCheck(t),t.indexOf(n,s)}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(t){return e.pxtrt.nullCheck(t),t.getLength()},n.setLength=function(t,n){e.pxtrt.nullCheck(t),t.setLength(n)},n.push=function(t,n){e.pxtrt.nullCheck(t),t.push(n)},n.pop=function(t,n){return e.pxtrt.nullCheck(t),t.pop()},n.getAt=function(t,n){return e.pxtrt.nullCheck(t),t.getAt(n)},n.removeAt=s,n.insertAt=function(t,n,s){e.pxtrt.nullCheck(t),t.insertAt(n,s)},n.setAt=function(t,n,s){e.pxtrt.nullCheck(t),t.setAt(n,s)},n.indexOf=i,n.removeElement=function(t,n){e.pxtrt.nullCheck(t);let r=i(t,n,0);return r>=0?(s(t,r),1):0}}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,s=65535&t;return n*s+((e>>>16&65535)*s+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const s=Math.pow(10,t++);n=Math.round(e*s+Number.EPSILON)/s}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(s=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(i=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return s.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(r=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(s.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(o=e.avr||(e.avr={})),function(t){t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then((()=>{n(e.runtime.currFrame.retval+"")})):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return parseFloat(e)},t.concat=function(e,t){return e+t},t.substring=function(t,n,s){return e.pxtrt.nullCheck(t),t.slice(n,n+s)},t.equals=function(e,t){return e==t},t.compare=function(e,t){return e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return e==t?0:e<t?-1:1},t.length=function(e){return e.length},t.substr=function(e,t,n){return e.substr(t,n)},t.charAt=function(e,t){return e.charAt(t)},t.charCodeAt=function(t,n){return e.pxtrt.nullCheck(t),function(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.length}(t,n)?t.charCodeAt(n):0},t.indexOf=function(t,n,s){return e.pxtrt.nullCheck(t),null==n?-1:t.indexOf(n,s)},t.lastIndexOf=function(t,n,s){return e.pxtrt.nullCheck(t),null==n?-1:t.lastIndexOf(n,s)},t.includes=function(t,n,s){return e.pxtrt.nullCheck(t),null!=n&&t.includes(n,s)}}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class c extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return u.toHex(this)}}e.RefBuffer=c,function(t){let n;function s(t){let s=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),i=!1;s<0&&(i=!0,s=-s);let r=!1;return s>=10&&(r=!0,s/=10),{size:s,signed:i,swap:r,isFloat:t>=n.Float32LE}}function i(e){return new c(new Uint8Array(e))}function r(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.data.length}function o(e,t){return r(e,t)?e.data[t]:0}function a(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function l(e,t,n){r(e,t)&&(a(e),e.data[t]=n)}function u(e,t,n=0,s=-1){n<0||n>e.data.length||(s<0&&(s=e.data.length),s=Math.min(s,e.data.length-n),a(e),e.data.fill(t,n,n+s))}function h(e,t,n,s,i){if(n.buffer===e.buffer)h(e,t,n.slice(s,s+i),0,i);else for(let r=0;r<i;++r)e[t+r]=n[s+r]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.getNumber=function(e,t,n){let i=s(t);if(i.isFloat){let t=e.data.buffer.slice(n,n+i.size);if(i.swap){new Uint8Array(t).reverse()}return 4==i.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let r=0;for(let t=0;t<i.size;++t){r<<=8;let s=i.swap?n+t:n+i.size-t-1;r|=e.data[s]}if(i.signed){let e=32-8*i.size;r=r<<e>>e}else r>>>=0;return r},t.setNumber=function(e,t,n,i){let r=s(t);if(r.isFloat){let t=new Uint8Array(r.size);4==r.size?new Float32Array(t.buffer)[0]=i:new Float64Array(t.buffer)[0]=i,r.swap&&t.reverse();for(let s=0;s<r.size;++s)e.data[n+s]=t[s]}else for(let t=0;t<r.size;++t){let s=r.swap?n+r.size-t-1:n+t;e.data[s]=255&i,i>>=8}},t.createBuffer=i,t.createBufferFromHex=function(e){let t=i(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return e.isStatic},t.getBytes=function(e){return e.data},t.getUint8=function(e,t){return o(e,t)},t.getByte=o,t.setUint8=function(e,t,n){l(e,t,n)},t.setByte=l,t.length=function(e){return e.data.length},t.fill=u,t.slice=function(e,t,n){return t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new c(e.data.slice(t,t+n))},t.toHex=function(e){const t="0123456789abcdef";let n="";for(let s=0;s<e.data.length;++s)n+=t[e.data[s]>>4],n+=t[15&e.data[s]];return n},t.toString=function(t){return e.U.fromUTF8Array(t.data)};const d=-2147483648;t.shift=function(e,t,n,s){s<0&&(s=e.data.length-n),n<0||n+s>e.data.length||n+s<n||0==s||0==t||t==d||0!=s&&0!=t&&t!=d&&(t<=-s||t>=s?u(e,0):(a(e),t<0?(t=-t,h(e.data,n+t,e.data,n,s-t),e.data.fill(0,n,n+t)):(s-=t,h(e.data,n,e.data,n+t,s),e.data.fill(0,n+s,n+s+t))))},t.rotate=function(e,t,n,s){if(s<0&&(s=e.data.length-n),n<0||n+s>e.data.length||n+s<n||0==s||0==t||t==d)return;a(e),t<0&&(t+=s<<8),(t%=s)<0&&(t+=s);let i=e.data,r=t,o=0,l=r,u=s;for(;o!=l;){let e=i[o+n];i[o+++n]=i[l+n],i[l+++n]=e,l==u?l=r:o==r&&(r=l)}},t.write=function(e,t,n,s=0,i=-1){i<0&&(i=n.data.length),s<0||t<0||t>e.data.length||(i=Math.min(n.data.length-s,e.data.length-t))<0||(a(e),h(e.data,t,n.data,s,i))}}(u=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(e,n,r){let o=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(r);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",s=o.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;s.length<t;)s=n+s;a=s}else a=":x"==r?"0x"+o.toString(16):void 0===o?"(undef)":null===o?"(null)":o.toString?o.toString():o+"";return":a"==r?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==r?a=1==o?"":"s":":q"==r?a=s(a):":jq"==r?a=i(a):":uri"==r?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==r?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==r&&(a=(100*o).toFixed(1).toString()+"%"),a}))}function s(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e}function i(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.lf=function(e,...s){let i=t[e]||e;return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),n(i,s)},e.fmt_va=n,e.htmlEscape=s,e.jsStringQuote=i}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,U,pxtcore;!function(e){function t(e){return e.split(/\s+/).filter((e=>!!e))}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let s;e.containsClass=function(e,n){return t(n).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},e.addClass=function(e,n){t(n).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},e.removeClass=function(e,n){t(n).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let s=0;s<e;++s)n.push(t(s));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return s||(s="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*s()};const i=Promise.resolve();async function r(e,t,n){let s=0;const i=[],r=[];for(let o=0;o<e;o++){const e=(async()=>{for(;s<t.length;){const e=s++,i=t[e];r[e]=await n(i)}})();i.push(e)}try{await Promise.all(i)}catch(e){throw s=t.length,e}return r}function o(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return o()||a()}function u(){try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&!/nolocalhost=1/.test(window.location.href)}catch(e){return!1}}e.nextTick=function(e){i.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},e.throttle=function(e,t,n){let s;return function(){let i=this,r=arguments,o=function(){s=null,n||e.apply(i,r)},a=n&&!s;s||(s=setTimeout(o,t)),a&&e.apply(i,r)}},e.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},e.promiseMapAllSeries=function(e,t){return r(1,e,t)},e.promisePoolAsync=r,e.promiseTimeout=async function(e,t,n){let s,i;const r=new Promise(((t,r)=>{i=t,s=setTimeout((()=>{i=void 0,clearTimeout(s),r(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,r]).then((e=>(i&&(clearTimeout(s),i()),e)))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let s=0;s<t;++s)n[s]=255&e.charCodeAt(s);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let s=0;s<t;++s)n+=String.fromCharCode(e[s]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let s=255&e.charCodeAt(n);t+=37==s||s>127?"%"+s.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let s=0;s<e.length;++s){let i=e.charCodeAt(s);if(i<=127)n+=e.charAt(s);else if(i<=2047)n+=String.fromCharCode(192|i>>6,128|63&i);else{if(!t&&55296<=i&&i<=56319){let t=e.charCodeAt(++s);isNaN(t)||(i=65536+(i-55296<<10)+(t-56320))}n+=i<=65535?String.fromCharCode(224|i>>12,128|i>>6&63,128|63&i):String.fromCharCode(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=o,e.isIpcRenderer=a,e.isElectron=l,e.isLocalHost=u,e.isLocalHostDev=function(){return u()&&!l()},e.unique=function(e,t){let n=[],s={};return e.forEach((e=>{let i=t(e);s.hasOwnProperty(i)||(s[i]=null,n.push(e))})),n}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach((e=>e()))},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.codal.music.__stopSoundExpressions(),pxsim.AudioContextManager.stopAll()}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();console.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>console.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>console.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach((e=>e()))}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}poke(){this.lock=!0;let e=this.events;return this.events=[],U.promiseMapAllSeries(e,(e=>U.promiseMapAllSeries(this.handlers,(t=>this.runtime.runFiberAsync(t,...this.valueToArgs?this.valueToArgs(e):[e]))))).then((()=>this.events.length>0?this.poke():(this.lock=!1,this._addRemoveLog.forEach((e=>{e.log===LogType.BackAdd?this.addHandler(e.act):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act)})),this._addRemoveLog=[],Promise.resolve())))}get handlers(){return this._handlers}setHandler(e){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet}):this._handlers=[e]}addHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackAdd});else{-1==this._handlers.indexOf(e)&&this._handlers.push(e)}}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove});else{let t=this._handlers.indexOf(e);-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let s=0;for(;e.hasOwnProperty("arg"+s);)s++;const i=e;for(let e=s;e>0;e--)i["arg"+e]=i["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,(t=>_leave(t,e(t))))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,s){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=s}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let s=Date.now();return s-lastYield>=20&&(lastYield=s,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),5),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,s){let i={};__this.loopLock=i,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=s;const{msg:r,heap:o}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=o,pxsim.injectEnvironmentGlobals(r,o),Runtime.postMessage(r),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==i),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,s){if(setupResume(t,n),"<main>"===s.functionName||"main.ts"===s.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let s;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(s=pxsim.dumpHeap(e,dbgHeap,n.fields))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:s})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)console.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{console.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:s}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,s),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let s=1;for(;e.hasOwnProperty("arg"+s);)n["arg"+(s-1)]=e["arg"+s],s++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),oops("failed cast on "+e)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let s=i=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push((()=>s(i)));pxsim.runtime=__this;let r=Date.now();if(r-n>3&&(lastYield=r),U.assert(e.pc==t),i instanceof pxsim.FnWrapper){let t=i,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},s={};return __this.loopLock=s,removeFrame(e),__this.otherFrames.push(n),U.nextTick((()=>{U.assert(__this.loopLock===s),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()}))}return e.retval=i,loop(e)};return s}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs>>0}runFiberAsync(e,t,n,s){return new Promise(((i,r)=>U.nextTick((()=>{pxsim.runtime=this,this.setupTop(i),pxtcore.runAction(e,[t,n,s])}))))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function s(t,n,i=null){if(!(n instanceof pxsim.RefObject))return;const r=n;if(r.gcIsStatic())return;const o=e[r.id];if(o)return void(i&&o.pointers.push([i,t]));const a={obj:r,path:null,pointers:[[i,t]]};e[r.id]=a,r.scan(((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&s(t,n,a)}))}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))s(e.replace(/___\d+$/,""),this.globals[e]);const i=this.otherFrames.slice();this.currFrame&&i.indexOf(this.currFrame)<0&&i.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const i=n[t];i instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),s(e+"."+t,i))}if(n.caps)for(let t of n.caps)s(e+".cap",t)}}const r=Object.keys(e).map((t=>e[t]));r.sort(((e,t)=>t.obj.gcSize()-e.obj.gcSize()));const o=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,s]of e.pointers){if(null==n)return void(e.path=s);o(n);const i=n.path+"."+s;(!t||t.length>i.length)&&(t=i)}e.path=t};r.forEach(o);const a=[t];for(const e of r){const s=e.obj.gcSize(),i=e.obj.gcKey();n.hasOwnProperty(i)||a.push(n[i]={count:0,size:0,name:i});const r=n[i];r.size+=s,r.count++,t.size+=s,t.count++}a.sort(((e,t)=>e.size-t.size));let l="";const u=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=u(4*e.size)+u(e.count)+" "+e.name+"\n";const c=e=>u(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,h=r.slice(0,20).map(c).join("\n");let d="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,s=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);d=r.filter((n=>!e[n.obj.id]&&t[n.obj.id])).filter((e=>!s(e.obj))).map(c).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+h+"\n\nNew Objects:\n"+d}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static async postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;if(!t)return;const n=await t.screenshotAsync();Runtime.postMessage({type:"screenshot",data:n,delay:e&&e.delay})}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout((()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"})),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval((()=>this.postFrame()),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then((t=>{this.recordingLastImageData&&isImageDataEqual(this.recordingLastImageData,t)||(this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e}))}))}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map((e=>new PerfCounter(e))))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let s=t.lastFewPtr++;s>=t.lastFew.length&&(s=0,t.lastFewPtr=1),t.lastFew[s]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval((()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()}),20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),s=new TimeoutScheduled(-1,e,t,n);return s.id=setTimeout((()=>{const t=this.timeoutsScheduled.indexOf(s);t>=0&&this.timeoutsScheduled.splice(t,1),e()}),t),this.timeoutsScheduled.push(s),s.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach((e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))})),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach((e=>{this.schedule(e.fn,e.timeRemaining)})),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter((t=>{let n=e-t.timestampCall;return t.totalRuntime>n}))}registerUserInteraction(){this.lastInteractionTime=Date.now(),this.thumbnailRecordingIntervalRef||this.lastThumbnailTime&&this.lastInteractionTime-this.lastThumbnailTime<1e3||(this.thumbnailFrames=[],this.thumbnailRecordingIntervalRef=setInterval((async()=>{const e=await this.board.screenshotAsync();this.thumbnailFrames.length&&isImageDataEqual(e,this.thumbnailFrames[this.thumbnailFrames.length-1])||(this.thumbnailFrames.push(e),(Date.now()-this.lastInteractionTime>1e4||this.thumbnailFrames.length>30)&&(clearInterval(this.thumbnailRecordingIntervalRef),this.thumbnailRecordingIntervalRef=void 0,this.lastThumbnailTime=Date.now(),Runtime.postMessage({type:"thumbnail",frames:this.thumbnailFrames})))}),66))}}function setParentMuteState(e){Runtime.postMessage({type:"setmutebuttonstate",state:e})}pxsim.Runtime=Runtime,pxsim.setParentMuteState=setParentMuteState;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}function isImageDataEqual(e,t){if(e.data.byteLength!==t.data.byteLength)return!1;const n=e.data.byteLength;let s=0;for(s=0;s<n&&e.data[s]==t.data[s];++s);return s===n}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const s="pxtdriver";e.SimulatorDriver=class{constructor(n,s={}){this.container=n,this.options=s,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),s.parentOrigin&&this._allowedOrigins.push(s.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const i=null==s?void 0:s.messageSimulators;i&&Object.keys(i).map((e=>i[e])).forEach((e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)})),this._allowedOrigins=e.U.unique(this._allowedOrigins,(e=>e))}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter((e=>!!e.parent)),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:s,width:e})}stopRecording(){this.postMessage({type:"recorder",source:s,action:"stop"})}setFrameState(n){const s=n.nextElementSibling,i=s.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:s.style.display="",s.className="",i.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?s.style.display="none":(s.style.display="",s.className="videoplay xicon icon"),i.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),s.style.display="none",i.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach((e=>this.setFrameState(e))),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach((e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)})):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach((e=>e.parentElement.removeChild(e)))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const s=this.loanedIFrame();return s&&!t&&n.unshift(s),n}getSimUrl(){var e,t;const n=this.options.simUrl||(null===(e=window.pxtConfig)||void 0===e?void 0:e.simUrl)||(null===(t=pxt.webConfig)||void 0===t?void 0:t.simUrl)||`${location.origin}/sim/simulator.html`;try{return new URL(n)}catch(e){return new URL(n,location.origin)}}postMessage(t,n,s){var i;if(this.hwdbg)return void this.hwdbg.postMessage(t);const r=this.dependentEditors();let o=this.simFrames();s&&(o=o.filter((e=>e.id===s)));let a=!1;const l=t;if(n&&(null==l?void 0:l.broadcast)){const s=!!(null===(i=this._currentRuntime)||void 0===i?void 0:i.single),u=window.parent&&window.parent!==window.window?window.parent:window.opener;if(u&&n!==u&&u.postMessage(t,"*"),!this.options.nestedEditorSim&&!(null==l?void 0:l.toParentIFrameOnly))if(r)r.forEach((e=>{n!==e&&e.postMessage(t,window.location.origin)}));else if(!s){const n="messagepacket"===t.type&&t.channel,s=n&&this.options.messageSimulators&&this.options.messageSimulators[n];if(s){let t=o.find((e=>e.dataset.messagechannel===n));if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else{const i=(e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&s.localHostUrl||s.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||""));let r=this.createFrame(i);this.container.appendChild(r),t=r.firstElementChild,t.dataset.messagechannel=n,e.U.addClass(r,"simmsg"),e.U.addClass(r,"simmsg"+n),s.permanent&&(t.dataset.permanent="true"),this.startFrame(t),o=this.simFrames()}}else{a=!0;const e=o.filter((e=>!e.dataset.messagechannel));e.length<2?(this.container.appendChild(this.createFrame()),o=this.simFrames()):e[1].dataset.runid!=this.runId&&this.startFrame(e[1])}}}for(let e=0;e<o.length;++e){const s=o[e];if((!n||s.contentWindow!=n)&&(s.contentWindow&&(a?this.postDeferrableMessage(s,t):this.postMessageCore(s,t),"recorder"==t.type&&"start"==t.action)))break}}postDeferrableMessage(e,t){!e.dataset.loading?this.postMessageCore(e,t):(this.deferredMessages||(this.deferredMessages=[]),this.deferredMessages.push([e,t]))}postMessageCore(t,n){const s=e.U.isLocalHostDev()?"*":t.dataset.origin;t.contentWindow.postMessage(n,s)}setRunOptionQueryParams(e){var t,n;const s=new URL(e);if((null===(t=this._runOptions)||void 0===t?void 0:t.hideSimButtons)&&s.searchParams.set("hideSimButtons","1"),null===(n=this._runOptions)||void 0===n?void 0:n.queryParameters){const e=this._runOptions.queryParameters.split("&");for(const t of e){const[e,n]=t.split(/[:=]/);e&&n&&s.searchParams.set(e,n)}}return s.toString()}createFrame(n){var s;const i=document.createElement("div");i.className="simframe ui embed";const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay;microphone"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";let o=this.setRunOptionQueryParams(n||this.getSimUrl().toString());o+="#"+r.id,r.src=o,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(o).origin||"*",r.dataset.loading="true",(null===(s=this._runOptions)||void 0===s?void 0:s.autofocus)&&r.setAttribute("autofocus","true"),i.appendChild(r);const a=document.createElement("i");a.className="videoplay xicon icon",a.style.display="none",a.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),i.appendChild(a);const l=document.createElement("div");return l.className="ui active loader",a.style.display="none",i.appendChild(l),this._runOptions&&this.applyAspectRatioToFrame(r),i}preload(e,t){t&&(this._currentRuntime=void 0,this.container.textContent=""),this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.clearDebugger(),this.stopSound(),this.postMessage({type:"stop",source:s}),this.setState(n?t.Starting:t.Stopped),e&&this.unload()}suspend(){this.stopSound(),this.postMessage({type:"stop",source:s}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0,this.deferredMessages=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:s,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:s})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout((()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()}),5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach((t=>this.applyAspectRatioToFrame(t,e)))}applyAspectRatioToFrame(e,t){var n,s,i,r;let o=t;if(void 0===o){const t=parseFloat(e.dataset.aspectratio);isNaN(t)||(o=t)}if(void 0===o){const t=e.dataset.messagechannel;if(t){const e=null===(i=null===(s=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===s?void 0:s[t])||void 0===i?void 0:i.aspectRatio;e&&(o=e)}}void 0===o&&(o=(null===(r=this._runOptions)||void 0===r?void 0:r.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/o+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter((e=>!e.dataset.permanent)).forEach((e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())}))}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach((t=>{this.options.removeElement(t.parentElement,e)})),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach((e=>{this.options.unhideElement(e.parentElement)}))}setRunOptions(e={}){this._runOptions=e}run(e,t={}){this.setRunOptions(t),this.runId=this.nextId(),this._currentRuntime={type:"run",source:s,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies,activePlayer:t.activePlayer,theme:t.theme},this.stopSound(),this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.breakpointsSet=!1;let e=this.simFrames()[0];if(e)this.startFrame(e);else{let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){var t,n,s;if(!this._currentRuntime||!e.contentWindow)return!1;const i=JSON.parse(JSON.stringify(this._currentRuntime));i.frameCounter=++this.frameCounter;const r=(null===(t=this._runOptions)||void 0===t?void 0:t.mpRole)||(null===(s=null===(n=/[\&\?]mp=(server|client)/i.exec(window.location.href))||void 0===n?void 0:n[1])||void 0===s?void 0:s.toLowerCase());return i.options={theme:this.themes[this.nextFrameId++%this.themes.length],mpRole:r},i.id=`${i.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=i.id,e.id!==this.debuggingFrame&&(i.traceDisabled=!0,i.breakOnStart=!1),this.postMessageCore(e,i),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleDeferredMessages(e){var t,n,s;e.dataset.loading&&(delete e.dataset.loading,null===(n=null===(t=this.deferredMessages)||void 0===t?void 0:t.filter((t=>t[0]===e)))||void 0===n||n.forEach((t=>{const[n,s]=t;this.postMessageCore(e,s)})),this.deferredMessages=null===(s=this.deferredMessages)||void 0===s?void 0:s.filter((t=>t[0]!==e)))}handleMessage(e,n){var s,i,r;switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&((null===(s=this._runOptions)||void 0===s?void 0:s.autofocus)&&n.focus(),this.startFrame(n),this.options.revealElement&&this.options.revealElement(n),this.handleDeferredMessages(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,s=document.getElementById(n);if(s){const n=e;if(n.runtimeid==s.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running),this.handleDeferredMessages(s);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,s=document.getElementById(n);s&&(s.dataset.aspectratio=t.value+"",this.applyAspectRatioToFrame(s));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;case"setmutebuttonstate":null===(r=(i=this.options).onMuteButtonStateChange)||void 0===r||r.call(i,e.state);break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(e){let i;switch(e){case n.Resume:i="resume",this.setState(t.Running);break;case n.StepInto:i="stepinto",this.setState(t.Running);break;case n.StepOut:i="stepout",this.setState(t.Running);break;case n.StepOver:i="stepover",this.setState(t.Running);break;case n.Pause:i="pause";break;default:return void console.debug("unknown command")}this.postMessage({type:"debugger",subtype:i,source:s})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t},this.debuggingFrame).then((e=>e),(e=>{}))}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach((t=>{const{reject:n}=this.debuggerResolvers[t];n(e)})),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(e){if("trace"!==e.subtype&&console.log("DBG-MSG",e.subtype,e),e.seq){const{resolve:t}=this.debuggerResolvers[e.seq];t&&t(e)}switch(e.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(e);break;case"breakpoint":{const s=e;if(this.state==t.Running){if(s.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(s);let e=s.exceptionMessage+"\n";for(let t of s.stackframes){let n=t.funcInfo;e+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}s.exceptionMessage&&console.error(e)}else console.error("debugger: trying to pause from "+this.state);break}case"trace":{const n=e;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(n);break}default:const s=e.req_seq;if(s){const{resolve:t}=this.debuggerResolvers[s];t&&(delete this.debuggerResolvers[s],t(e))}}}postDebuggerMessageAsync(e,t={},n){return new Promise(((s,i)=>{const r=this.debuggerSeq++;this.debuggerResolvers[r.toString()]={resolve:s,reject:i},this.postDebuggerMessage(e,t,r,n)}))}postDebuggerMessage(e,t={},n,i){const r=JSON.parse(JSON.stringify(t));r.type="debugger",r.subtype=e,r.source=s,n&&(r.seq=n),this.postMessage(r,void 0,i)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,s,i=!1){let r=(s?"back":"fore")+":"+t+":"+n;return!this.queues[r]&&i&&(this.queues[r]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[r]}listen(e,t,n){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let s=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?s.addHandler(n):s.setHandler(n),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach((t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)}))}getQueues(e,t,n){let s=[this.start(0,0,n)];return 0==e&&0==t||(t&&s.push(this.start(0,t,n)),e&&s.push(this.start(e,0,n)),e&&t&&s.push(this.start(e,t,n))),s}queue(t,n,s=null){if(e.runtime.pausedOnBreakpoint)return;const i=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;i&&(t=this.notifyID);let r=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(r,(e=>e?e.push(s,i):Promise.resolve()))}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};let t;function n(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function s(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise(((e,n)=>{t.whenDone=e,this.enqueue(t)}))}},function(t){let n,s,i,r,o=0,a=!1;const l=[];let u,c=[];function h(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}(),n&&(u=n.createGain(),u.connect(n.destination),u.gain.setValueAtTime(1,0))),n}function d(){k(0),o=0,r&&r.pause()}function p(e,t){e.gain.value&&e.gain.setTargetAtTime(0,h().currentTime,.015),setTimeout((()=>{e.disconnect(),t&&t.disconnect()}),450)}t.isAudioElementActive=function(){return!!i},t.mute=function(e){a=e;const t=h();e?u.gain.setTargetAtTime(0,t.currentTime,.015):u.gain.setTargetAtTime(1,t.currentTime,.015),!e&&t&&"suspended"===t.state&&t.resume()},t.isMuted=function(){return a},t.stopAll=function(){d(),x();for(const e of c)e()},t.stop=function(){d(),function(){if(i){try{p(i,s)}catch(e){}i=void 0,s=void 0}}()},t.onStopAll=function(e){c.push(e)},t.frequency=function(){return o};const m=[null,"triangle","sawtooth","sine"];let f,g,b=[],v=[];function y(e,t){let n,s=m[e];if(s){let e=h().createOscillator();return e.type=s,e.frequency.value=t,e}if(4==e)n=function(){if(!g){const e=131072;g=h().createBuffer(1,e,h().sampleRate);const t=g.getChannelData(0);let n=251771520;for(let s=0;s<e;s+=4)n^=n<<13,n^=n>>17,n^=n<<5,32768&n?(t[s]=1,t[s+1]=1,t[s+2]=-1,t[s+3]=-1):(t[s]=0,t[s+1]=0,t[s+2]=0,t[s+3]=0)}return g}();else if(5==e)n=function(){if(!f){const e=1e5;f=h().createBuffer(1,e,h().sampleRate);const t=f.getChannelData(0);let n=251771520;for(let s=0;s<e;s++)n^=n<<13,n^=n>>17,n^=n<<5,t[s]=(1023&n)/512-1}return f}();else if(11<=e&&e<=15)n=function(e){if(!v[e]){const t=1024,n=h().createBuffer(1,t,h().sampleRate),s=n.getChannelData(0);for(let n=0;n<t;n++)s[n]=n<e/100*t?1:-1;v[e]=n}return v[e]}(10*(e-10));else{if(!(16<=e&&e<=18))return null;n=function(e){if(!b[e]){const t=1024,n=h().createBuffer(1,t,h().sampleRate),s=n.getChannelData(0),i=[770763591,3356908179],r=[15,31,63];for(let n=0;n<t;n+=4){let t,o=n/4;o&=r[e-4],t=0!=(i[o>>5]&1<<(31&o)),t?(s[n]=1,s[n+1]=1,s[n+2]=-1,s[n+3]=-1):(s[n]=0,s[n+1]=0,s[n+2]=0,s[n+3]=0)}b[e]=n}return b[e]}(e-16+4)}let i=h().createBufferSource();i.buffer=n,i.loop=!0;return 4==e||16<=e&&e<=18?i.playbackRate.value=t/(h().sampleRate/4):5!=e&&(i.playbackRate.value=t/(h().sampleRate/1024)),i}class w{disconnectNodes(){this.gain?p(this.gain,this.generator):this.generator&&(this.generator.stop(),this.generator.disconnect()),this.gain=null,this.generator=null}remove(){const e=l.indexOf(this);e>=0&&l.splice(e,1),this.disconnectNodes()}}let S=1;function x(){for(null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("muteallchannels"),S++;l.length;)l[0].remove()}function E(e,t){if(e<0)return;o=e;let n=h();if(n){t=Math.max(0,Math.min(1,t));try{s||(s=n.createOscillator(),i=n.createGain(),i.gain.value=0,s.type="triangle",s.connect(i),i.connect(u),s.start(0)),k(t)}catch(e){return s=void 0,void(i=void 0)}s.frequency.value=e,k(t)}}function k(e){(null==i?void 0:i.gain)&&i.gain.setTargetAtTime(e,n.currentTime,.015)}t.muteAllChannels=x,t.queuePlayInstructions=function(t,n){const s=S;e.U.delay(t).then((()=>s!=S?Promise.resolve():C(n.data)))},t.tone=E,t.setCurrentToneGain=k,t.playBufferAsync=function(e){return e?new Promise((t=>{function n(){t&&t(),t=void 0}const s="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let s=0;s<t;++s)n+=String.fromCharCode(e[s]);return n}(e.data));r=new Audio(s),a&&(r.volume=0),r.onended=()=>n(),r.onpause=()=>n(),r.onerror=()=>n(),r.play()})):Promise.resolve()};function C(n,s,i){return new Promise((async r=>{null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("playinstructions",n);let o=!1,a=h(),c=new w;l.length>20&&l[0].remove(),l.push(c),c.gain=a.createGain(),c.gain.gain.value=1,c.gain.connect(u);const d={},p={};let m=a.currentTime,f=m,g=0,b=0;const v=(e,t)=>e/1024/4*(t?.5:1),S=()=>{if(!o){o=!0,c.disconnectNodes();for(const e of Object.keys(d))d[e].stop(),d[e].disconnect(),p[e].disconnect();r()}};for(let e=0;e<n.length;e+=12){const t=n[e],s=I(n,e+2),i=I(n,e+4)/1e3,r=I(n,e+6),o=I(n,e+8),l=I(n,e+10);if(b+=i,0===t){f+=i;continue}const u=11<=t&&t<=15;d[t]||(d[t]=y(t,s),p[t]=a.createGain(),p[t].gain.value=0,p[t].connect(c.gain),d[t].connect(p[t]),d[t].start()),g&&t!==g&&p[g].gain.setTargetAtTime(0,f,.015);const h=d[t],m=p[t];if(h instanceof OscillatorNode)h.frequency.setValueAtTime(s,f),h.frequency.linearRampToValueAtTime(l,f+i);else{4==t||16<=t&&t<=18?h.playbackRate.linearRampToValueAtTime(l/(a.sampleRate/4),f+i):5!=t&&h.playbackRate.linearRampToValueAtTime(l/(a.sampleRate/1024),f+i)}m.gain.setValueAtTime(v(r,u),f),m.gain.linearRampToValueAtTime(v(o,u),f+i),g=t,f+=i}if(c.gain.gain.setTargetAtTime(0,f,.015),s||i){const e=()=>{const t=a.currentTime;if(t>m+b)return;if(s&&s())return void S();const{frequency:r,volume:o}=function(e,t){let n=0;for(let s=0;s<t.length;s+=12){const i=I(t,s+2),r=I(t,s+4),o=I(t,s+6),a=I(t,s+8),l=I(t,s+10);if(n+r<e){n+=r;continue}const u=(e-n)/r;return{frequency:i+(l-i)*u,volume:o+(a-o)*u}}return{frequency:-1,volume:-1}}(1e3*(t-m),n);i&&i(r,o/1024),requestAnimationFrame(e)};requestAnimationFrame(e)}await e.U.delay(1e3*b),S()}))}function I(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}t.playPCMBufferStreamAsync=function(e,t,n=.3,s){return new Promise((i=>{let r=[],o=h().currentTime,a=!1;const c=new w;c.gain=h().createGain(),c.gain.gain.value=0,c.gain.gain.setValueAtTime(n,h().currentTime),c.gain.connect(u),l.length>20&&l[0].remove(),l.push(c);const d=()=>!!(s&&s()||!c.gain)&&(i&&i(),i=void 0,c.remove(),!0);function p(){for(;!a&&r.length<3&&!d();){const t=e();if(!t||!t.length){a=!0;break}m(t)}a&&0===r.length&&(c.remove(),i&&i(),i=void 0)}function m(e){if(d())return;const n=h().createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const s=h().createBufferSource();r.push(s),s.connect(c.gain),s.buffer=n,s.addEventListener("ended",(()=>{r.shift().disconnect(),p()})),s.start(o),o+=n.duration}p()}))},t.playInstructionsAsync=C,t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,s=15&t[0],i=t[1]||0,r=(o=i,440*Math.pow(2,(o-69)/12));var o;const a=t[2]||0;8==n||9==n&&0==a?d():9==n&&(E(r,1),9==s&&setTimeout((()=>d()),500))}}(t=e.AudioContextManager||(e.AudioContextManager={})),e.isTouchEnabled=n,e.hasPointerEvents=s,e.pointerEvents=s()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function s(e,t){let n=e[0]-t[0],s=e[1]-t[1];return n*n+s*s}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,s]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==s.x&&0==s.y,"el1 and el2 x,y offsets not supported");let i=(t,n,s)=>e.svg.hydrate(t,{x:n,y:s}),r=(t,n,s)=>e.svg.hydrate(t,{width:`${n}px`,height:`${s}px`}),o=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,u=n.h*a;r(n.el,l,u);let c=1*s.w,h=1*s.h;r(s.el,c,h);let[d,p,m,f]=t.margin,g=t.middleMargin,b=Math.max(l,c),v=p+(b-l)/2,y=d;i(n.el,v,y);let w=p+(b-c)/2,S=y+u+g;i(s.el,w,S);let x=[y,y+u,S,S+h],E=p+b+f,k=d+u+g+h+m,C=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${E} ${k}`,class:"sim-bb"});((t,n,s)=>{n&&e.svg.hydrate(t,{width:n}),s&&e.svg.hydrate(t,{height:s})})(C,t.maxWidth,t.maxHeight),i(C,0,0);let I=e.svg.child(C,"g");return C.appendChild(n.el),C.appendChild(s.el),{under:I,over:e.svg.child(C,"g"),host:C,edges:x,scaleUnit:o,toHostCoord1:e=>{let[t,n]=e;return[t*a+v,n*a+y]},toHostCoord2:e=>{let[t,n]=e;return[1*t+w,1*n+S]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let s=n(t.imageUnitDist,t.targetUnitDist),i=s(t.width),r=s(t.height),o=e.svg.elt("image",{width:i,height:r});return o.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:o,w:i,h:r,x:0,y:0}},t.findDistSqrd=s,t.findClosestCoordIdx=function(e,t){return t.map((t=>s(e,t))).reduce(((e,t,n,s)=>t<s[e]?n:e),0)},t.mkTxt=function(t,n,s,i,r,o,a){let l=e.svg.elt("text");a=a||.3;const u=(o=o||-.33333)*s*r.length,c=a*s;return e.svg.hydrate(l,{style:`font-size:${s}px;`,transform:`translate(${t} ${n}) rotate(${i}) translate(${u} ${c})`}),e.U.addClass(l,"noselect"),l.textContent=r,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,s,[i,r,o]=e,[a,l,u]=[i/255,r/255,o/255],c=Math.min(a,l,u),h=Math.max(a,l,u),d=h-c,p=h+c;return s=p/2*100,0===d?n=t=0:(h===a?t=(l-u)/d%6*60:h===l?t=60*((u-a)/d+2):h===u&&(t=60*((a-l)/d+4)),n=s>50?d/(2-p)*100:d/p*100),[Math.floor(t),Math.floor(n),Math.floor(s)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function s(e,n,s){let i={class:e,d:n};s&&(i.title=s);let r=t.elt("path");return t.hydrate(r,i),r}function i(e,n=!1){let s=t.elt("linearGradient");t.hydrate(s,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(s,"stop",{offset:"0%"}),t.child(s,"stop",{offset:"100%"}),t.child(s,"stop",{offset:"100%"}),t.child(s,"stop",{offset:"100%"});return s}function r(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,s){e.setAttribute("transform",`translate(${t},${n}) rotate(${s+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let s in n)"title"==s?t.title(e,n[s]):e.setAttributeNS(null,s,n[s])},n.elt=function(e,n){let s=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(s,n),s},n.child=function(e,n,s){let i=t.elt(n,s);return e.appendChild(i),i},n.mkPath=s,n.path=function(e,t,n,i){let r=s(t,n,i);return e.appendChild(r),r},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach((e=>e.style.fill=t))},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let s=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(s=!0,!0)),!1))),t.addEventListener(e.pointerEvents.up,(e=>!s||(s=!1,n(e),e.preventDefault(),!1)),!1)},n.buttonEvents=function(t,n,s,i,r){let o=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(o=!0,s&&s(e),!0)),!1))),t.addEventListener(e.pointerEvents.move,(e=>!o||(n&&n(e),e.preventDefault(),!1)),!1),t.addEventListener(e.pointerEvents.up,(e=>{o=!1,i&&i(e)}),!1),t.addEventListener(e.pointerEvents.leave,(e=>{o=!1,i&&i(e)}),!1),t.addEventListener("keydown",(e=>{o=!1,r&&r(e)}))},n.mkLinearGradient=i,n.linearGradient=function(e,t,n=!1){let s=i(t,n);return e.appendChild(s),s},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let s=t.parentElement;s&&(s.removeChild(t),s.appendChild(t))},n.mkTitle=r,n.title=function(e,t){let n=r(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){!function(e){e.Metronome=class{constructor(){this.tickListeners=[],this.onTick=()=>{for(const e of this.tickListeners)e()}}initAsync(){return this.metronomeLoadPromise?this.metronomeLoadPromise:this.metronomeWorker?this.metronomeWorker:(this.metronomeLoadPromise=new Promise((e=>{this.metronomeWorker=new Worker("data:application/javascript,"+encodeURIComponent(t));const n=t=>{"ready"===t.data&&(e(this.metronomeWorker),this.metronomeWorker.removeEventListener("message",n),this.metronomeWorker.addEventListener("message",this.onTick))};this.metronomeWorker.addEventListener("message",n)})),this.metronomeLoadPromise)}stop(){this.postMessage({type:"stop"})}setInterval(e){this.currentInterval=e,this.postMessage({type:"set-interval",interval:e})}start(e){this.currentInterval=e,this.postMessage({type:"start",interval:e})}addTickListener(e){this.tickListeners.push(e)}removeTickListener(e){this.tickListeners=this.tickListeners.filter((t=>t!==e))}interval(){return this.currentInterval}dispose(){if(this.metronomeWorker)this.metronomeWorker.terminate(),this.metronomeWorker=void 0,this.metronomeLoadPromise=void 0,this.tickListeners=[],this.interval=void 0;else if(this.metronomeLoadPromise)return void this.metronomeLoadPromise.then((()=>this.dispose()))}postMessage(e){if(!this.metronomeWorker)throw new Error("initAsync not called on metronome");this.metronomeWorker.postMessage(e)}};const t='\n/**\n * Adpated from https://github.com/cwilso/metronome/\n */\n\nlet timerRef;\nlet interval;\n\naddEventListener("message", ev => {\n const message = ev.data;\n\n if (message.type === "start") {\n updateInterval(message.interval, true);\n }\n else if (message.type === "stop") {\n clearInterval(timerRef);\n timerRef = undefined;\n }\n else if (message.type === "set-interval") {\n updateInterval(message.interval, false);\n }\n})\n\npostMessage("ready");\n\nfunction updateInterval(interval, startIfStopped) {\n if (timerRef) {\n clearInterval(timerRef);\n startIfStopped = true;\n }\n interval = interval;\n\n if (startIfStopped) {\n timerRef = setInterval(() => postMessage("tick"), interval);\n }\n}\n'}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){e.chromaticInterval=[1,1.0417,1.125,1.2,1.25,1.3333,1.4063,1.5,1.6,1.6667,1.8,1.875],e.majorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[9],e.chromaticInterval[11]],e.minorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[3],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[8],e.chromaticInterval[10]],e.pentatonicScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[7],e.chromaticInterval[9]],e.majorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[4],e.chromaticInterval[7]],e.minorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[7]],e.diminishedInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[6],e.chromaticInterval[9]],e.wholeToneInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[6],e.chromaticInterval[8],e.chromaticInterval[10]]}(e.MusicalIntervals||(e.MusicalIntervals={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.chromatic={interval:e.MusicalIntervals.chromaticInterval,length:12},t.majorScale={interval:e.MusicalIntervals.majorScaleInterval,length:7},t.minorScale={interval:e.MusicalIntervals.minorScaleInterval,length:7},t.pentatonicScale={interval:e.MusicalIntervals.pentatonicScaleInterval,length:5},t.majorTriad={interval:e.MusicalIntervals.majorTriadInterval,length:3},t.minorTriad={interval:e.MusicalIntervals.minorTriadInterval,length:3},t.diminished={interval:e.MusicalIntervals.diminishedInterval,length:4},t.wholeTone={interval:e.MusicalIntervals.wholeToneInterval,length:6},t.calculateFrequencyFromProgression=function(e,t,n){let s=Math.floor(n/t.length),i=n%t.length;return e*Math.pow(2,s)*t.interval[i]}}(e.MusicalProgressions||(e.MusicalProgressions={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=[31,33,35,37,39,41,44,46,49,52,55,58,62,65,69,73,78,82,87,92,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,233,247,262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,4435,4699,4978,5274,5588,5920,6272,6645,7040,7459,7902];async function s(t,s,i,r,o=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderInstrument(s,n[t],i,o),r)}async function i(t,n,s=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderDrumInstrument(t,s),n)}function r(e,t,n){return 6e4/e/t*n}t.Sequencer=class{constructor(){this._currentTick=0,this._state="stop",this.listeners={},this.globalVolume=1024,this.trackVolumes=[],this.drumTrackVolumes=[],this.currentCancelToken={cancelled:!1},this.onTick=()=>{const e=this.currentCancelToken;for(let t=0;t<this.currentlyPlaying.tracks.length;t++){const n=this.currentlyPlaying.tracks[t];for(const o of n.notes)if(o.startTick===this._currentTick)for(const a of o.notes)n.drums?i(n.drums[a.note],(()=>e.cancelled),this.getDrumTrackVolume(t,a.note)):s(a.note,n.instrument,r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,o.endTick-o.startTick),(()=>e.cancelled),this.getMelodicTrackVolume(t));else if(o.startTick>this._currentTick)break}this.fireEvent("tick"),this._currentTick++,this._currentTick>=this.maxTick()&&("loop"===this._state?(this._currentTick=0,this.fireEvent("looped")):this.stop(!0))}}async initAsync(){this.metronome?await this.metronome.initAsync():(this.metronome=new t.Metronome,await this.metronome.initAsync(),this.metronome.addTickListener(this.onTick))}dispose(){this.metronome&&this.metronome.dispose(),this.stop(),this.currentlyPlaying=void 0,this.listeners={}}state(){return this._state}currentTick(){return this._currentTick}currentTime(){return r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.currentTick())}maxTick(){return this.currentlyPlaying?this.currentlyPlaying.measures*this.currentlyPlaying.beatsPerMeasure*this.currentlyPlaying.ticksPerBeat:0}duration(){return r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.maxTick())}start(e,t){this.startFrom(e,t,0)}startFrom(e,t,n){"stop"!==this._state&&this.stop(),void 0!==t&&(this.shouldLoop=t),this._currentTick=null!=n?n:0,this.currentlyPlaying=e,this.metronome.start(r(e.beatsPerMinute,e.ticksPerBeat,1)),this._state=this.shouldLoop?"loop":"play",this.fireStateChange()}stop(e=!1){"stop"!==this._state&&(this._state="stop",this.metronome.stop(),this.fireStateChange(),e||(this.currentCancelToken.cancelled=!0),this.currentCancelToken={cancelled:!1})}updateSong(e){this.currentlyPlaying=e,"stop"!==this._state&&this.metronome.setInterval(r(e.beatsPerMinute,e.ticksPerBeat,1))}setLooping(e){e&&"play"===this._state?(this._state="loop",this.fireStateChange()):e||"loop"!==this._state||(this._state="play",this.fireStateChange()),this.shouldLoop=e}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListener(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((e=>e!==t)))}setVolume(e){this.globalVolume=Math.min(Math.max(e,0),1024)}setTrackVolume(e,t){for(t=Math.min(Math.max(t,0),1024);this.trackVolumes.length<e;)this.trackVolumes.push(1024);this.trackVolumes[e]=t}setDrumTrackVolume(e,t,n){for(n=Math.min(Math.max(n,0),1024);this.drumTrackVolumes.length<e;)this.drumTrackVolumes.push([]);for(;this.drumTrackVolumes[e].length<t;)this.drumTrackVolumes[e].push(1024);this.drumTrackVolumes[e][t]=n}getMelodicTrackVolume(e){let t=1024;return e<this.trackVolumes.length&&(t=this.trackVolumes[e]),this.globalVolume*(t/1024)}getDrumTrackVolume(e,t){const n=this.getMelodicTrackVolume(e);let s=1024;return e<this.drumTrackVolumes.length&&t<this.drumTrackVolumes[e].length&&(s=this.drumTrackVolumes[e][t]),n*(s/1024)}fireStateChange(){this.fireEvent(this._state),this.fireEvent("state-change")}fireEvent(e){if(this.listeners[e])for(const t of this.listeners[e])t()}},t.playNoteAsync=s,t.playDrumAsync=i,t.tickToMs=r}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){function t(e,t,n,r){var o,a;let l=0;return(null===(o=e.pitchEnvelope)||void 0===o?void 0:o.amplitude)&&(l+=s(e.pitchEnvelope,r,n)),(null===(a=e.pitchLFO)||void 0===a?void 0:a.amplitude)&&(l+=i(e.pitchLFO,r)),Math.max(t+l,0)}function n(e,t,n,r){var o;let a=0;return e.ampEnvelope.amplitude&&(a+=s(e.ampEnvelope,n,t)),(null===(o=e.ampLFO)||void 0===o?void 0:o.amplitude)&&(a+=i(e.ampLFO,n)),Math.max(Math.min(a,e.ampEnvelope.amplitude),0)/1024*r|0}function s(e,t,n){const s=e.sustain/1024*e.amplitude;if(t>n){if(t-n>e.release)return 0;if(t<e.attack){const s=e.amplitude/e.attack*n;return s-s/e.release*(t-n)}if(t<e.attack+e.decay){const i=e.amplitude-(e.amplitude-s)/e.decay*(n-e.attack);return i-i/e.release*(t-n)}return s-s/e.release*(t-n)}return t<e.attack?e.amplitude/e.attack*t:t<e.attack+e.decay?e.amplitude-(e.amplitude-s)/e.decay*(t-e.attack):s}function i(e,t){return Math.cos(t/1e3*e.frequency*2*Math.PI)*e.amplitude}function r(e,t,n,s,i,r,a,l){return n>0&&(e[t]=r,e[t+1]=0,o(e,t+2,a),o(e,t+4,n),o(e,t+6,255*s>>6),o(e,t+8,255*i>>6),o(e,t+10,l),t+=12),e[t]=0,t}function o(e,t,n){const s=new Uint8Array(2);new Uint16Array(s.buffer)[0]=0|n,e[t]=s[0],e[t+1]=s[1]}function a(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:a(e,t+1),decay:a(e,t+3),sustain:a(e,t+5),release:a(e,t+7),amplitude:a(e,t+9)},pitchEnvelope:{attack:a(e,t+11),decay:a(e,t+13),sustain:a(e,t+15),release:a(e,t+17),amplitude:a(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:a(e,22)},pitchLFO:{frequency:e[t+24],amplitude:a(e,25)},octave:e[t+27]}}function u(e,t){return e[t+1]?function(e,t){const n={id:e[t],instrument:{ampEnvelope:{attack:0,decay:0,sustain:0,release:0,amplitude:0},waveform:0},notes:[],drums:[]},s=a(e,t+2);let i=t+4;for(;i<t+4+s;)n.drums.push(c(e,i)),i+=5+7*n.drums[n.drums.length-1].steps.length;const r=a(e,i);i+=2;for(;i<t+4+s+r;)n.notes.push(h(e,i,0,!0)),i+=5+n.notes[n.notes.length-1].notes.length;return[n,i]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},s=t+4+a(e,t+2),i=a(e,s);let r=s+2;for(;r<s+2+i;)n.notes.push(h(e,r,n.instrument.octave,!1)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t)}function c(e,t){const n={startFrequency:a(e,t+1),startVolume:a(e,t+3),steps:[]};for(let s=0;s<e[t];s++){const i=t+5+7*s;n.steps.push({waveform:e[i],frequency:a(e,i+1),volume:a(e,i+3),duration:a(e,i+5)})}return n}function h(e,t,n,s){const i={startTick:a(e,t),endTick:a(e,t+2),notes:[]};for(let r=0;r<e[t+4];r++)i.notes.push(d(e[t+5+r],n,s));return i}function d(e,t,n){const s=e>>6,i={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===s?i.enharmonicSpelling="flat":2===s&&(i.enharmonicSpelling="sharp"),i}e.renderInstrument=function(e,s,i,o){var a,l,u,c,h;const d=i+e.ampEnvelope.release,p=(null===(a=e.ampLFO)||void 0===a?void 0:a.amplitude)?Math.max(500/e.ampLFO.frequency,50):50,m=(null===(l=e.pitchLFO)||void 0===l?void 0:l.amplitude)?Math.max(500/e.pitchLFO.frequency,50):50;let f=[0],g=e.ampEnvelope.attack,b=(null===(u=e.pitchEnvelope)||void 0===u?void 0:u.amplitude)?e.pitchEnvelope.attack:d,v=(null===(c=e.pitchLFO)||void 0===c?void 0:c.amplitude)?m:d,y=(null===(h=e.ampLFO)||void 0===h?void 0:h.amplitude)?p:d,w=0;for(;w<d&&(g<=b&&g<=v&&g<=y?(w=g,f.push(g),g=w<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<i?e.ampEnvelope.attack+e.ampEnvelope.decay:w<i?i:d):b<=v&&b<=y&&b<d?(w=b,f.push(b),b=w<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<i?e.pitchEnvelope.attack+e.pitchEnvelope.decay:w<i?i:w<i+e.pitchEnvelope.release?Math.min(d,i+e.pitchEnvelope.release):d):v<=y&&v<d?(w=v,f.push(v),v+=m):y<d&&(w=y,f.push(y),y+=p),!(w>=d));){for(g<=w&&(g=w<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<i?e.ampEnvelope.attack+e.ampEnvelope.decay:w<i?i:d),b<=w&&(b=w<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<i?e.pitchEnvelope.attack+e.pitchEnvelope.decay:w<i?i:w<i+e.pitchEnvelope.release?Math.min(d,i+e.pitchEnvelope.release):d);y<=w;)y+=p;for(;v<=w;)v+=m}let S,x,E=0|n(e,i,0,o),k=0|t(e,s,i,0),C=0;const I=new Uint8Array(12*(f.length+1));for(let a=1;a<f.length;a++)f[a]-C<5||(S=0|n(e,i,f[a],o),x=0|t(e,s,i,f[a]),r(I,12*(a-1),f[a]-C|0,E,S,e.waveform,k,x),E=S,k=x),C=f[a];return r(I,12*f.length,10,E,0,e.waveform,k,k),I},e.renderDrumInstrument=function(e,t){let n=e.startVolume,s=e.startFrequency;const i=e=>e/1024*t;let o=new Uint8Array(12*(e.steps.length+1));for(let t=0;t<e.steps.length;t++)r(o,12*t,e.steps[t].duration,i(n),i(e.steps[t].volume),e.steps[t].waveform,s,e.steps[t].frequency),n=e.steps[t].volume,s=e.steps[t].frequency;return r(o,12*e.steps.length,10,i(n),0,e.steps[e.steps.length-1].waveform,s,s),o},e.decodeSong=function(e){const t={beatsPerMinute:a(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[s,i]=u(e,n);n=i,t.tracks.push(s)}return t}}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){e.EMOJI_SYNTHESIZER_SAMPLE_RATE=44100,e.EMOJI_SYNTHESIZER_TONE_WIDTH_F=1024,e.EMOJI_SYNTHESIZER_TONE_WIDTH=1024,e.EMOJI_SYNTHESIZER_BUFFER_SIZE=512,e.EMOJI_SYNTHESIZER_TONE_EFFECT_PARAMETERS=2,e.EMOJI_SYNTHESIZER_TONE_EFFECTS=3,e.EMOJI_SYNTHESIZER_STATUS_ACTIVE=1,e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY=2,e.EMOJI_SYNTHESIZER_STATUS_STOPPING=4;e.SoundEmojiSynthesizer=class{constructor(t,n=e.EMOJI_SYNTHESIZER_SAMPLE_RATE){this.samplesPerStep=[],this.status=0,this.effectPointer=0,this.position=0,this.bufferSize=e.EMOJI_SYNTHESIZER_BUFFER_SIZE,this.sampleRate=n,this.samplesToWrite=0,this.samplesWritten=0,this.sampleRange=1023,this.orMask=0,this.effectPointer=-1,this.volume=1}get effect(){return this.effectBuffer[this.effectPointer]}play(e){this.effectBuffer=e,this.effectPointer=-1,this.nextSoundEffect()}nextSoundEffect(){const t=null!=this.effect;if(this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING&&(this.effectPointer=null,this.effectBuffer=[]),this.effect?this.effectPointer++:this.effectPointer=0,this.effectPointer>=this.effectBuffer.length&&(this.effectPointer=0,this.effect.duration>=0))return this.effectPointer=-1,this.effectBuffer=[],this.samplesWritten=0,this.samplesToWrite=0,this.position=0,t;this.samplesToWrite=this.determineSampleCount(this.effect.duration),this.frequency=this.effect.frequency,this.volume=this.effect.volume,this.samplesWritten=0;for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.effect.effects[t].step=0,this.effect.effects[t].steps=Math.max(this.effect.effects[t].steps,1),this.samplesPerStep[t]=Math.floor(this.samplesToWrite/this.effect.effects[t].steps);return!1}pull(){let t,n,s=!1;for(;!s;){if(this.samplesWritten==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING){let t=this.nextSoundEffect();(0==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(s=!0,(t||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(this.status&=~e.EMOJI_SYNTHESIZER_STATUS_STOPPING))}for(!(this.samplesWritten<this.samplesToWrite)&&this.status&e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY||null!=t||(this.buffer=new Array(this.bufferSize),t=0,n=this.buffer.length);this.samplesWritten<this.samplesToWrite;){let s=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F*this.frequency/this.sampleRate,i=this.sampleRange*this.volume/1024,r=512-512*i,o=[];for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)o[t]=this.samplesPerStep[t]*this.effect.effects[t].step,this.effect.effects[t].step==this.effect.effects[t].steps-1&&(o[t]=this.samplesToWrite);let a=o[0];for(let t=1;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)a=Math.min(a,o[t]);for(;this.samplesWritten<a;){if(t==n)return this.buffer;let o=this.effect.tone.tonePrint(this.effect.tone.parameter,Math.max(this.position,0));for(this.buffer[t]=o*i+r,t++,this.samplesWritten++,this.position+=s;this.position>e.EMOJI_SYNTHESIZER_TONE_WIDTH_F;)this.position-=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F}for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.samplesWritten==o[t]&&this.effect.effects[t].step<this.effect.effects[t].steps&&(this.effect.effects[t].effect&&this.effect.effects[t].effect(this,this.effect.effects[t]),this.effect.effects[t].step++)}}if(null==t)this.buffer=[];else{const e=.5*this.sampleRange;for(;t<n;)this.buffer[t]=e,t++}return this.buffer}determineSampleCount(e){e<0&&(e=-e);const t=e/1e3;return Math.floor(this.sampleRate*t)}totalDuration(){let e=0;for(const t of this.effectBuffer)e+=t.duration;return e}}}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){const t=[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,11,11,12,13,13,14,15,16,16,17,18,19,20,21,22,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,40,41,42,43,45,46,47,49,50,51,53,54,56,57,58,60,61,63,64,66,68,69,71,72,74,76,77,79,81,82,84,86,87,89,91,93,95,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,141,143,145,147,149,152,154,156,158,161,163,165,167,170,172,175,177,179,182,184,187,189,191,194,196,199,201,204,206,209,211,214,216,219,222,224,227,229,232,235,237,240,243,245,248,251,253,256,259,262,264,267,270,273,275,278,281,284,287,289,292,295,298,301,304,307,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,424,427,430,433,436,439,442,445,448,452,455,458,461,464,467,470,473,477,480,483,486,489,492,495,498,502,505,508,511,514,517,520,524,527,530,533,536,539,542,545,549,552,555,558,561,564,567,570,574,577,580,583,586,589,592,595,598,602,605,608,611,614,617,620,623,626,629,632,635,638,641,644,647,650,653,656,659,662,665,668,671,674,677,680,683,686,689,692,695,698,701,704,707,710,713,715,718,721,724,727,730,733,735,738,741,744,747,749,752,755,758,760,763,766,769,771,774,777,779,782,785,787,790,793,795,798,800,803,806,808,811,813,816,818,821,823,826,828,831,833,835,838,840,843,845,847,850,852,855,857,859,861,864,866,868,870,873,875,877,879,881,884,886,888,890,892,894,896,898,900,902,904,906,908,910,912,914,916,918,920,922,924,926,927,929,931,933,935,936,938,940,941,943,945,946,948,950,951,953,954,956,958,959,961,962,964,965,966,968,969,971,972,973,975,976,977,979,980,981,982,984,985,986,987,988,989,990,992,993,994,995,996,997,998,999,1e3,1e3,1001,1002,1003,1004,1005,1006,1006,1007,1008,1009,1009,1010,1011,1011,1012,1013,1013,1014,1014,1015,1015,1016,1016,1017,1017,1018,1018,1019,1019,1019,1020,1020,1020,1021,1021,1021,1021,1022,1022,1022,1022,1022,1022,1022,1022,1022,1022,1023,1022];e.SineTone=function(e,n){let s=1024-(n|=0);return s<512&&(n=s),t[n]},e.SawtoothTone=function(e,t){return t},e.TriangleTone=function(e,t){return t<512?2*t:2*(1023-t)},e.NoiseTone=function(e,t){let n=e[0];return 0==n&&(n=7919),t*n&1023},e.SquareWaveTone=function(e,t){return t<512?1023:0}}(e.Synthesizer||(e.Synthesizer={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.noInterpolation=function(e,t){},t.linearInterpolation=function(e,t){let n=(t.parameter[0]-e.effect.frequency)/t.steps;e.frequency=e.effect.frequency+n*t.step},t.logarithmicInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.log10(Math.max(t.step,.1))*(t.parameter[0]-e.effect.frequency)/1.95},t.curveInterpolation=function(e,t){e.frequency=Math.sin(3.12159*t.step/180)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.slowVibratoInterpolation=function(e,t){e.frequency=Math.sin(t.step/10)*t.parameter[0]+e.effect.frequency},t.warbleInterpolation=function(e,t){e.frequency=Math.sin(t.step)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.vibratoInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(t.step)*t.parameter[0]},t.exponentialRisingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(.01745329*t.step)*t.parameter[0]},t.exponentialFallingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.cos(.01745329*t.step)*t.parameter[0]},t.appregrioAscending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.step)},t.appregrioDescending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.steps-n.step-1)},t.frequencyVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.frequency/=t.parameter[0]:e.frequency*=t.parameter[0])},t.volumeVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.volume/=t.parameter[0]:e.volume*=t.parameter[0])},t.adsrVolumeEffect=function(e,t){let n=.5*t.steps;if(t.step<=n){let s=(t.parameter[0]-e.effect.volume)/n;e.volume=e.effect.volume+t.step*s}else{let s=(t.parameter[1]-t.parameter[0])/n;e.volume=t.parameter[0]+(t.step-n)*s}},t.volumeRampEffect=function(e,t){let n=(t.parameter[0]-e.effect.volume)/t.steps;e.volume=e.effect.volume+t.step*n}}(e.SoundSynthesizerEffects||(e.SoundSynthesizerEffects={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){!function(t){let n,s,i;!function(e){e[e.Sine=0]="Sine",e[e.Sawtooth=1]="Sawtooth",e[e.Triangle=2]="Triangle",e[e.Square=3]="Square",e[e.Noise=4]="Noise"}(n=t.WaveShape||(t.WaveShape={})),function(e){e[e.None=0]="None",e[e.Linear=1]="Linear",e[e.Curve=2]="Curve",e[e.ExponentialRising=5]="ExponentialRising",e[e.ExponentialFalling=6]="ExponentialFalling",e[e.ArpeggioRisingMajor=8]="ArpeggioRisingMajor",e[e.ArpeggioRisingMinor=10]="ArpeggioRisingMinor",e[e.ArpeggioRisingDiminished=12]="ArpeggioRisingDiminished",e[e.ArpeggioRisingChromatic=14]="ArpeggioRisingChromatic",e[e.ArpeggioRisingWholeTone=16]="ArpeggioRisingWholeTone",e[e.ArpeggioFallingMajor=9]="ArpeggioFallingMajor",e[e.ArpeggioFallingMinor=11]="ArpeggioFallingMinor",e[e.ArpeggioFallingDiminished=13]="ArpeggioFallingDiminished",e[e.ArpeggioFallingChromatic=15]="ArpeggioFallingChromatic",e[e.ArpeggioFallingWholeTone=17]="ArpeggioFallingWholeTone",e[e.Logarithmic=18]="Logarithmic"}(s=t.InterpolationEffect||(t.InterpolationEffect={})),function(e){e[e.None=0]="None",e[e.Vibrato=1]="Vibrato",e[e.Tremolo=2]="Tremolo",e[e.Warble=3]="Warble"}(i=t.Effect||(t.Effect={}));class r{constructor(){this.src="000000000000000000000000000000000000000000000000000000000000000000000000"}get wave(){return this.getValue(0,1)}set wave(e){this.setValue(0,g(e,0,4),1)}get volume(){return this.getValue(1,4)}set volume(e){this.setValue(1,g(e,0,1023),4)}get frequency(){return this.getValue(5,4)}set frequency(e){this.setValue(5,e,4)}get duration(){return this.getValue(9,4)}set duration(e){this.setValue(9,e,4)}get shape(){return this.getValue(13,2)}set shape(e){this.setValue(13,e,2)}get endFrequency(){return this.getValue(18,4)}set endFrequency(e){this.setValue(18,e,4)}get endVolume(){return this.getValue(26,4)}set endVolume(e){this.setValue(26,g(e,0,1023),4)}get steps(){return this.getValue(30,4)}set steps(e){this.setValue(30,e,4)}get fx(){return this.getValue(34,2)}set fx(e){this.setValue(34,g(e,0,3),2)}get fxParam(){return this.getValue(36,4)}set fxParam(e){this.setValue(36,e,4)}get fxnSteps(){return this.getValue(40,4)}set fxnSteps(e){this.setValue(40,e,4)}get frequencyRandomness(){return this.getValue(44,4)}set frequencyRandomness(e){this.setValue(44,e,4)}get endFrequencyRandomness(){return this.getValue(48,4)}set endFrequencyRandomness(e){this.setValue(48,e,4)}get volumeRandomness(){return this.getValue(52,4)}set volumeRandomness(e){this.setValue(52,e,4)}get endVolumeRandomness(){return this.getValue(56,4)}set endVolumeRandomness(e){this.setValue(56,e,4)}get durationRandomness(){return this.getValue(60,4)}set durationRandomness(e){this.setValue(60,e,4)}get fxParamRandomness(){return this.getValue(64,4)}set fxParamRandomness(e){this.setValue(64,e,4)}get fxnStepsRandomness(){return this.getValue(68,4)}set fxnStepsRandomness(e){this.setValue(68,e,4)}copy(){const e=new r;return e.src=this.src.slice(0),e}setValue(e,t,n){t=g(0|t,0,Math.pow(10,n)-1),this.src=this.src.substr(0,e)+function(e,t){let n=e+"";for(;n.length<t;)n="0"+n;return n}(t,n)+this.src.substr(e+n)}getValue(e,t){return parseInt(this.src.substr(e,t))}}t.Sound=r;let o,a=!1,l={cancelled:!1};async function u(){if(o.length){a=!0;const e=o.shift();let t=l;try{e.onStarted(),await h(e.notes,(()=>t.cancelled)),t.cancelled?e.onCancelled():e.onFinished()}catch(t){e.onCancelled()}u()}else a=!1}function c(){o=[],l.cancelled=!0,l={cancelled:!1}}function h(n,s,i){const r=new t.SoundEmojiSynthesizer(0),o=function(e){const t=72,n=Math.floor((e.length+1)/(t+1)),s=n*(t+1)-1;if(e.length!=s)return[];const i=[];for(let s=0;s<n;++s){const n=s*t+s;if(n>0&&","!=e[n-1])return[];const r=f();if(!d(e.substr(n),r))return[];i.push(r)}return i}(n);r.play(o);let a=!1;return Promise.race([(l=r.totalDuration(),new Promise((e=>setTimeout(e,l)))).then((()=>{a=!0})),e.AudioContextManager.playPCMBufferStreamAsync((()=>{if(!r.effect)return;const e=r.pull();i&&i(r.frequency,r.volume);const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=(e[n]-512)/512;return t}),r.sampleRate,.03,(()=>a||s&&s()))]);var l}function d(e,n){let s=parseInt(e.substr(0,1)),i=parseInt(e.substr(1,4)),r=parseInt(e.substr(5,4)),o=parseInt(e.substr(9,4)),a=parseInt(e.substr(13,2)),l=parseInt(e.substr(18,4)),u=parseInt(e.substr(26,4)),c=parseInt(e.substr(30,4)),h=parseInt(e.substr(34,2)),d=parseInt(e.substr(36,4)),f=parseInt(e.substr(40,4));if(r=m(r,parseInt(e.substr(44,4))),l=m(l,parseInt(e.substr(48,4))),i=m(i,parseInt(e.substr(52,4))),u=m(u,parseInt(e.substr(56,4))),o=m(o,parseInt(e.substr(60,4))),d=m(d,parseInt(e.substr(64,4))),f=m(f,parseInt(e.substr(68,4))),-1==r||-1==l||-1==i||-1==u||-1==o||-1==d||-1==f)return!1;switch(s){case 0:n.tone.tonePrint=t.Synthesizer.SineTone;break;case 1:n.tone.tonePrint=t.Synthesizer.SawtoothTone;break;case 2:n.tone.tonePrint=t.Synthesizer.TriangleTone;break;case 3:n.tone.tonePrint=t.Synthesizer.SquareWaveTone;break;case 4:n.tone.tonePrint=t.Synthesizer.NoiseTone}switch(n.frequency=r,n.duration=o,n.effects[0].steps=c,a){case 0:n.effects[0].effect=t.SoundSynthesizerEffects.noInterpolation;break;case 1:n.effects[0].effect=t.SoundSynthesizerEffects.linearInterpolation,n.effects[0].parameter[0]=l;break;case 2:n.effects[0].effect=t.SoundSynthesizerEffects.curveInterpolation,n.effects[0].parameter[0]=l;break;case 5:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialRisingInterpolation,n.effects[0].parameter[0]=l;break;case 6:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialFallingInterpolation,n.effects[0].parameter[0]=l;break;case 8:case 10:case 12:case 14:case 16:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioAscending;break;case 9:case 11:case 13:case 15:case 17:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioDescending;break;case 18:n.effects[0].effect=t.SoundSynthesizerEffects.logarithmicInterpolation,n.effects[0].parameter[0]=l}switch(a){case 8:case 9:n.effects[0].parameter_p[0]=t.MusicalProgressions.majorScale;break;case 10:case 11:n.effects[0].parameter_p[0]=t.MusicalProgressions.minorScale;break;case 12:case 13:n.effects[0].parameter_p[0]=t.MusicalProgressions.diminished;break;case 14:case 15:n.effects[0].parameter_p[0]=t.MusicalProgressions.chromatic;break;case 16:case 17:n.effects[0].parameter_p[0]=t.MusicalProgressions.wholeTone}let g=p(0,i,1023)/1023,b=p(0,u,1023)/1023;n.volume=1*g,n.effects[1].effect=t.SoundSynthesizerEffects.volumeRampEffect,n.effects[1].steps=36,n.effects[1].parameter[0]=1*b;let v=Math.round(n.duration/1e4*f);switch(h){case 1:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.frequencyVibratoEffect,n.effects[2].parameter[0]=d;break;case 2:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.volumeVibratoEffect,n.effects[2].parameter[0]=d;break;case 3:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.warbleInterpolation,n.effects[2].parameter[0]=d}return!0}function p(e,t,n){return Math.min(n,Math.max(e,t))}function m(e,t){if(e<0||t<0)return-1;const n=(s=2*t+1,Math.floor(Math.random()*s)-t);var s;return Math.abs(e+n)}function f(){const e={frequency:0,volume:1,duration:0,tone:{tonePrint:void 0,parameter:[0]},effects:[]};for(let n=0;n<t.EMOJI_SYNTHESIZER_TONE_EFFECTS;n++)e.effects.push({effect:void 0,step:0,steps:0,parameter:[],parameter_p:[]});return e}function g(e,t,n){return Math.min(Math.max(e,t),n)}t.isSoundExpPlaying=function(){return a},t.__playSoundExpression=function(t,n){o||(o=[]);const s=e.getResume(),i=new Promise(((e,i)=>{o.push({notes:t,onStarted:()=>{n||s()},onFinished:e,onCancelled:e})}));a||u(),n&&i.then(s)},t.clearSoundQueue=c,t.playSoundExpressionAsync=h,t.__stopSoundExpressions=function(){c(),e.AudioContextManager.stopAll()},t.parseSoundExpression=d}(t.music||(t.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,s){this.parts=[],this.boardView=n,this.opts=s,s.boardDef.pinStyles||(s.boardDef.pinStyles={}),this.state=s.state;let i=s.partsList,r=0<i.length||s.forceBreadboardLayout;if(r){this.breadboard=new t.Breadboard({wireframe:s.wireframe});const n=s.boardDef.marginWhenBreadboarding||[0,0,40,0],o=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:s.maxWidth,maxHeight:s.maxHeight}),a=o.under,l=o.over;this.view=o.host;const u=o.edges;this.fromMBCoord=o.toHostCoord1,this.fromBBCoord=o.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,u,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const c=e.allocateDefinitions({boardDef:s.boardDef,partDefs:s.partDefs,fnArgs:s.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:i});c.partsAndWires.length||s.forceBreadboardLayout?(this.addAll(c),c.requiresBreadboard||s.forceBreadboardRender?c.hideBreadboard&&this.breadboard&&this.breadboard.hide():r=!1):r=!1}if(!r){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),s.maxWidth&&e.svg.hydrate(this.view,{width:s.maxWidth}),s.maxHeight&&e.svg.hydrate(this.view,{height:s.maxHeight})}this.state.updateSubscribers.push((()=>this.updateState()))}highlightBoardPin(e){this.boardView.highlightPin(e)}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach((t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"})),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(e){const t=this.view.classList.contains("sim")?this.view:this.view.querySelector(".sim"),n=t?t.cloneNode(!0):this.view.cloneNode(!0);n.setAttribute("width",n.viewBox.baseVal.width+""),n.setAttribute("height",n.viewBox.baseVal.height+"");const s=(new XMLSerializer).serializeToString(n),i="data:image/svg+xml,"+encodeURIComponent(s.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise(((t,n)=>{const s=document.createElement("img");s.onload=()=>{const n=document.createElement("canvas");n.width=s.width,n.height=s.height,e>0?(n.width=e,n.height=s.height*e/s.width|0):n.width<200?(n.width*=2,n.height*=2):n.width>480&&(n.width/=2,n.height/=2);const i=n.getContext("2d");i.drawImage(s,0,0,n.width,n.height),t(i.getImageData(0,0,n.width,n.height))},s.onerror=e=>{console.log(e),t(void 0)},s.src=i}))}updateState(){this.parts.forEach((e=>e.updateState()))}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(e){let t=this.boardView.getCoord(e);if(t)return this.fromMBCoord(t);console.error(`Unable to find coord for pin: ${e}`)}getLocCoord(e){let t;if("breadboard"===e.type){let n=e;t=this.getBBCoord(n)}else{let n=e.pin;t=this.getPinCoord(n)}return t||console.debug("Unknown location: "+name),t}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let s=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],i=this.state.builtinParts[e];s=t(),s.init(this.state.bus,i,this.view,n.params)}else{let e=n.visual;s=new t.GenericPart(e)}this.parts.push(s),this.partGroup.appendChild(s.element),s.overElement&&this.partOverGroup.appendChild(s.overElement),s.defs&&s.defs.forEach((e=>this.defs.appendChild(e))),this.style.textContent+=s.style||"";let i=n.startColumnIdx,r=n.startRowIdx,o={type:"breadboard",row:t.getRowName(r),col:t.getColumnName(i),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(o);s.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(s.element,l),e.U.addClass(s.element,"sim-cmp"),s.updateTheme(),s.updateState(),s}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach((t=>{const n=t.wires,s=n&&n.every((e=>this.wireFactory.checkWire(e.start,e.end)));s&&n.forEach((t=>e.wires.push(this.addWire(t))));let i=t.part;!i||n&&!s||e.parts.push(this.addPart(i))})),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,s="#DD4BA0",i=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:#1AA5D7;\n stroke:#1AA5D7\n }\n .sim-bb-red {\n fill:${s};\n stroke:${s};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:#1AA5D7;\n }\n .sim-bb-red.highlight {\n fill:${s};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const r=[4,4],o=t.BREADBOARD_MID_ROWS+r.length,a=25,l=[4,9,14,19],u=a+l.length,c=n*(t.BREADBOARD_MID_COLS+3),h=n*(o+4+5.5),d=2/3,p=h*d,m=.16666666666666669*h,f=(t.BREADBOARD_MID_COLS-1)*n,g=(c-f)/2,b=m+(p-(o-1)*n)/2,v=(u-1)*n,y=(c-v)/2,w=(m-15)/2,S=y,x=w+m+p,E=25.5,k=12,C=1.05,I=-90,R="abcdefghij".split("").reverse();function T(e){return`${e+1}`}function P(e){return R[e]}function _(t){let n=t.xOffset||0,s=t.yOffset||0,i=[],r=e.svg.elt("g"),o=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],u=(e,t)=>{let n,s=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),s+=1;return s},c=0,h=l(t.rowIdxsWithGap);for(let d=0;d<t.rowCount;d++){let p=0,m=l(t.colIdxsWithGap),f=s+d*t.pinDist+c*t.pinDist,g=d+a;for(let s=0;s<t.colCount;s++){let a=n+s*t.pinDist+p*t.pinDist,l=s+o;const c=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:f}:{x:a-.5*t.w,y:f-.5*t.h}),r.appendChild(t.el),t.el);let h=c(t.mkPin()),d=c(t.mkHoverPin()),b=t.getRowName(g),v=t.getColName(l),y=t.getGroupName?t.getGroupName(g,l):null,w={el:h,hoverEl:d,cx:a,cy:f,row:b,col:v,group:y};i.push(w),p+=u(m,l)}c+=u(h,g)}return{g:r,allPins:i}}function A(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function M(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function D(n,s,i,r,o,a,l){let u=t.mkTxt(n,s,i,r,o);e.U.addClass(u,"sim-bb-label"),l&&l.forEach((t=>e.U.addClass(u,t)));let c=t.mkTxt(n,s,1.3*i,r,o);return e.U.addClass(c,"sim-bb-label-hover"),l&&l.forEach((t=>e.U.addClass(c,t))),{el:u,hoverEl:c,txt:o,group:a}}t.getColumnName=T,t.getRowName=P,t.mkGrid=_;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let s=n[t];return s||null}getCoord(e){let{row:t,col:s,xOffset:i,yOffset:r}=e,o=this.getPin(t,s);if(!o)return null;let a=(i||0)*n,l=(r||0)*n;return[o.cx+a,o.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${c} ${h}`,class:"sim-bb",width:c+"px",height:h+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=i,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:c,height:h,rx:4.5,ry:4.5});let s="sim-bb-channel-grad",o=e.svg.elt("linearGradient");e.svg.hydrate(o,{id:s,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(o);e.svg.child(o,"stop",{offset:"0%",style:"stop-color: #AAA;"}),e.svg.child(o,"stop",{offset:"20%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"80%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"100%",style:"stop-color: #AAA;"});const u=(t,n,i)=>{let r=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${i||""}`,y:t-n/2,width:c,height:n});return r.setAttribute("fill",`url(#${s})`),r};u(m+p/2,15,"sim-bb-mid-channel"),u(m,.75,"sim-bb-sml-channel"),u(m+p,.75,"sim-bb-sml-channel");const d=(e,n)=>`${(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e)}${T(n)}`,f=e=>0===e?"-":"+",R=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${f(e)}${n}`};let B=_({xOffset:g,yOffset:b,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:A,mkHoverPin:M,getRowName:P,getColName:T,getGroupName:d,rowIdxsWithGap:r});B.g;this.allPins=this.allPins.concat(B.allPins);let F=_({xOffset:S,yOffset:x,rowCount:2,colCount:a,pinDist:n,mkPin:A,mkHoverPin:M,getRowName:f,getColName:T,getGroupName:R,colIdxsWithGap:l});F.g;this.allPins=this.allPins.concat(F.allPins);let O=_({xOffset:y,yOffset:w,rowCount:2,colCount:a,colStartIdx:a,pinDist:n,mkPin:A,mkHoverPin:M,getRowName:f,getColName:T,getGroupName:R,colIdxsWithGap:l.map((e=>e+a))});O.g;this.allPins=this.allPins.concat(O.allPins),this.allPins.forEach((t=>{let{el:n,row:s,col:i,hoverEl:r}=t,o=`(${s},${i})`;e.svg.hydrate(n,{title:o}),e.svg.hydrate(r,{title:o})})),this.allPins.forEach((e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e}));const L=(e,t,n,s,i,r)=>{let o=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=o;return D(a+n,l+s,10.5,-90,i,r)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=T(e),s=0,i=L(P(s),n,0,-15,n,d(s,e));this.allLabels.push(i);let r=t.BREADBOARD_MID_ROWS-1,o=L(P(r),n,0,15,n,d(r,e));this.allLabels.push(o)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=P(e),s=L(n,T(0),-15,0,n);this.allLabels.push(s);let i=L(n,T(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(i)}let U=[D(13.05,m+p+k,30,I,"-",R(0,0),["sim-bb-blue"]),D(12,m+p+m-k,E,I,"+",R(1,0),["sim-bb-red"]),D(c-k+C,m+p+k,30,I,"-",R(0,24),["sim-bb-blue"]),D(c-k,m+p+m-k,E,I,"+",R(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(U);let V=[D(13.05,12,30,I,"-",R(0,a),["sim-bb-blue"]),D(12,m-k,E,I,"+",R(1,a),["sim-bb-red"]),D(c-k+C,12,30,I,"-",R(0,49),["sim-bb-blue"]),D(c-k,m-k,E,I,"+",R(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(V);let q={};this.allLabels.forEach((e=>{let{el:t,txt:n}=e;(q[n]=q[n]||[]).push(e)}));this.allPins.forEach((e=>{let{row:t,col:n,group:s}=e,i=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),r=i[n]||(i[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=a?U.filter((t=>t.group==e.group)).forEach((e=>r.push(e))):V.filter((t=>t.group==e.group)).forEach((e=>r.push(e)))}else{q[t].forEach((e=>r.push(e))),q[n].forEach((e=>r.push(e)))}}));const N=v+22.5,W=(N-v)/2,$=(t,n,s,i)=>{let r=e.svg.elt("rect");return e.svg.hydrate(r,{class:`sim-bb-bar ${i}`,x:t,y:n-1.5,width:N,height:3}),{el:r,group:s}};let G=[$(S-W,x-9,R(0,49),"sim-bb-blue"),$(S-W,x+n+9,R(1,49),"sim-bb-red"),$(y-W,w-9,R(0,0),"sim-bb-blue"),$(y-W,w+n+9,R(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(G),this.allPowerBars.forEach((e=>this.bb.appendChild(e.el)));let H=this.allPins.map((e=>e.group)).filter(((e,t,n)=>n.indexOf(e)==t)),j=H.map((t=>e.svg.elt("g")));j.forEach((t=>e.U.addClass(t,"sim-bb-pin-group"))),j.forEach(((t,n)=>e.U.addClass(t,`group-${H[n]}`)));let z={};H.forEach(((e,t)=>z[e]=j[t]));let Y={};this.allPins.forEach(((e,t)=>{let n=e.group;(Y[n]||(Y[n]=[])).push(e)})),H.forEach((t=>{let n=Y[t],[s,i]=[n.map((e=>e.cx)),n.map((e=>e.cy))],r=e=>e.reduce(((e,t)=>e<t?e:t)),o=e=>e.reduce(((e,t)=>e>t?e:t)),[a,l,u,c]=[r(s),o(s),r(i),o(i)],h=e.svg.elt("rect"),d=Math.max(l-a,1e-4),p=Math.max(c-u,1e-4);e.svg.hydrate(h,{x:a,y:u,width:d,height:p}),e.U.addClass(h,"sim-bb-group-wire"),z[t].appendChild(h)})),this.allPins.forEach((e=>{let t=z[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}));let J=e.svg.elt("g");e.svg.hydrate(J,{class:"sim-bb-group-misc"}),j.push(J),this.allLabels.forEach((e=>{if(e.group){let t=z[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else J.appendChild(e.el),J.appendChild(e.hoverEl)})),j.forEach((e=>this.bb.appendChild(e)))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:c,h:h}}highlightLoc(t){let{row:n,col:s}=t,i=this.rowColToPin[n][s],{cx:r,cy:o}=i;this.rowColToLbls[n][s].forEach((t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")}))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,s=1.5*n,i=.66666*t.PIN_DIST,r=.66666*t.PIN_DIST+t.PIN_DIST/3;let o=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=o++;let l=a.visualDef,u=a.wireframe&&l.outlineImage?l.outlineImage:l.image,c=t.mkImageSVG({image:u,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),h=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=c.w,this.height=c.h;let d=c.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(d),this.background=d,e.svg.hydrate(d,{class:"sim-board"});const p=()=>{let t=e.svg.elt("circle"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},m=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("rect"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},g=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let b=l.pinBlocks.map(((n,s)=>{let i=h(n.x)+t.PIN_DIST/2,r=h(n.y)+t.PIN_DIST/2,o=n.labels.length,a=t.mkGrid({xOffset:i,yOffset:r,rowCount:1,colCount:o,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?p:f,mkHoverPin:l.useCrocClips?m:g,getRowName:()=>`${s+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a})),v=[];b.forEach(((e,t)=>e.allPins.forEach(((e,n)=>{this.allPins.push(e),v.push(l.pinBlocks[t])})))),this.allPins.forEach((t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})})),this.allPins.forEach((e=>{this.pinNmToPin[e.col]=e}));const y=(e,n,s,i,r)=>{let o,a;if("below"===r){a=e,o=n+12+.25*s*i.length}else{a=e,o=n-11-.32*s*i.length}return t.mkTxt(a,o,s,-90,i)};this.allLabels=this.allPins.map(((t,i)=>{let r=v[i];return((t,i,r,o)=>{let a=y(t,i,n,r,o);e.U.addClass(a,"sim-board-pin-lbl");let l=y(t,i,s,r,o);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:r}})(t.cx,t.cy,t.col,r.labelPosition||"above")})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)}))}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,s,i){let r=e.svg.elt("rect");return e.svg.hydrate(r,{x:t,y:n,width:s,height:i,class:"gray-cover"}),r}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),s=this.findPin(t);n&&s&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(s.el,"highlight"),e.U.addClass(s.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let s=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(s)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,s=.7;function i(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let r;function o(t,n,s,i){const r=e=>`${e[0]}, ${e[1]}`;let[o,a]=t,[l,u]=n,c=u-a,h=[o,a+c*s],d=[l,u-c*s],p=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(h)} ${r(d)} ${r(n)}`);return e.U.addClass(p,`wire-stroke-${i}`),p}function a(t,n,s){const i=e=>`${e[0]}, ${e[1]}`;let r=e.svg.mkPath("sim-bb-wire",`M${i(t)} L${i(n)}`);return e.U.addClass(r,`wire-stroke-${s}`),r}function l(s,i){const r=t.PIN_DIST/4;let o=e.svg.elt("circle"),a=s[0],l=s[1],u=n/2+r/2;return e.svg.hydrate(o,{cx:a,cy:l,r:u,class:"sim-bb-wire-end"}),e.U.addClass(o,`wire-fill-${i}`),o.style["stroke-width"]=`${r}px`,o}function u(n,s,i){let r=.24*t.PIN_DIST,o=10*r,a=2*r,l=6*r,u=r;const c=t.PIN_DIST/4;let[h,d]=n,p=s?-1:1,m=e.svg.elt("g"),f=e.svg.elt("rect"),g=o,b=a,v=h-b/2,y=d-g/2;e.svg.hydrate(f,{x:v,y:y,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${c}px`;let w=e.svg.elt("rect"),S=l,x=u,E=h-x/2,k=d+p*(g/2+S/2)-S/2;return e.svg.hydrate(w,{x:E,y:k,width:x,height:S,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",m.appendChild(w),m.appendChild(f),{el:m,x:v-c,y:Math.min(y,k),w:b+2*c,h:g+S}}function c(n,s,i){let r=.24*t.PIN_DIST;const o=4*r,a=10*r,l=3.5*r,u=3.5*r,c=t.PIN_DIST/4;let[h,d]=n,p=s?-1:1,m=e.svg.elt("g"),f=e.svg.elt("polygon"),g=a,b=o,v=h-b/2,y=d-g/2;const w=s?.15:.3,S=s?.7:1-.7,x=s?.3:.15;e.svg.hydrate(f,{points:((...e)=>e.map((e=>(e=>`${e[0]},${e[1]}`)(e))).join(" "))([v+b*w,y],[v+b*(1-w),y],[v+b,y+g*S],[v+b*(1-x),y+g],[v+b*x,y+g],[v,y+g*S])}),e.svg.hydrate(f,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${c}px`;let E=e.svg.elt("rect"),k=l,C=u,I=h-C/2,R=d+p*(g/2+k/2)-k/2;return e.svg.hydrate(E,{x:I,y:R,width:C,height:k,class:"sim-bb-wire-bare-end"}),m.appendChild(E),m.appendChild(f),{el:m,x:v-c,y:Math.min(y,R),w:b+2*c,h:g+k}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(r=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,s,i=!1){let r,o=e.svg.elt("g"),[a,l]=n,h=[a-15,l-50],d=[a+15,l+50];s=t.mapWireColor(s),r=i?c(h,!0,s):u(h,!0,s);let p=function(t,n,s){const i=e=>`${e[0]}, ${e[1]}`;let[r,o]=t,[a,l]=n,u=l-o,c=[r,o+.8*u],h=[a,l-.8*u],d=e.svg.mkPath("sim-bb-wire",`M${i(t)} C${i(c)} ${i(h)} ${i(n)}`);return d.style.stroke=s,{el:d,x:Math.min(r,a),y:Math.min(o,l),w:Math.abs(r-a),h:Math.abs(o-l)}}(h,d,s),m=u(d,!1,s);o.appendChild(p.el),o.appendChild(r.el),o.appendChild(m.el);let f=Math.min(r.x,m.x),g=Math.max(r.x+r.w,m.x+m.w),b=Math.min(r.y,m.y);return{el:o,x:f,y:b,w:g-f,h:Math.max(r.y+r.h,m.y+m.h)-b}};t.WireFactory=class{constructor(e,n,s,i,r,o){this.nextWireId=0,this.styleEl=i,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=s,this.getLocCoord=r,this.getPinStyle=o}indexOfMin(e){let t=0,n=e[0];for(let s=1;s<e.length;s++)e[s]<n&&(n=e[s],t=s);return t}closestEdgeIdx(e){let t=this.boardEdges.map((t=>Math.abs(e[1]-t)));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,r,u){let c=[],h=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const d=e=>{const n=t.PIN_DIST/2;let s,i=this.closestEdge(e);return s=i-e[1]<0?i-n:i+n,[e[0],s]};let p=this.nextWireId++,m=i(u),f=l(n,m),g=l(r,m),b=e.svg.child(h,"g",{class:"sim-bb-wire-ends-g"});b.appendChild(f),b.appendChild(g);let v=this.closestEdgeIdx(n),y=this.closestEdgeIdx(r);if(v==y){let e=a(n,r,m);h.appendChild(e),c.push(e)}else{let t,i,l=d(n),u=d(r),f=a(n,l,m),g=a(r,u,m);!(1!=v&&2!=v||1!=y&&2!=y)?(t=o(l,u,s,m),i=o(l,u,s,m)):(t=a(l,u,m),i=a(l,u,m)),e.U.addClass(i,"sim-bb-wire-hover"),h.appendChild(f),c.push(f),h.appendChild(g),c.push(g),this.underboard.appendChild(t),c.push(t),h.appendChild(i),c.push(i);let w=`sim-bb-wire-id-${p}`;const S=t=>e.U.addClass(t,w);S(b),S(i),this.styleEl.textContent+=`\n .${w}:hover ~ .${w}.sim-bb-wire-hover {\n visibility: visible;\n }`}let w=`\n .wire-stroke-${m} {\n stroke: ${t.mapWireColor(u)};\n }\n .wire-fill-${m} {\n fill: ${t.mapWireColor(u)};\n }\n `;return this.styleEl.textContent+=w,{endG:b,end1:f,end2:g,wires:c}}drawWireWithCrocs(n,r,u,h=!1){let d=[],p=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const m=e=>{const n=t.PIN_DIST/2;let s,i=this.closestEdge(e);return s=i-e[1]<0?i-n:i+n,[e[0],s]};let f=this.nextWireId++,g=i(u),b=l(n,g),v=r,[y,w]=r;r=[y,w+40],[y,w]=r;let S,x=[y,w+-17];S=h?function(n,s,i){let r=.24*t.PIN_DIST,o=4*r,a=1.2*r,l=10*r,u=r;const c=t.PIN_DIST/4;let[h,d]=n,p=s?-1:1,m=e.svg.elt("g"),f=e.svg.elt("rect"),g=o,b=a,v=h-b/2,y=d+10-g/2;e.svg.hydrate(f,{x:v,y:y,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${c}px`;let w=e.svg.elt("rect"),S=l,x=u,E=h-x/2,k=d+10+p*(g/2+S/2)-S/2;return e.svg.hydrate(w,{x:E,y:k,width:x,height:S,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",m.appendChild(w),m.appendChild(f),{el:m,x:v-c,y:Math.min(y,k),w:b+2*c,h:g+S}}(x,!0):c(x,!0);let E=S.el,k=e.svg.child(p,"g",{class:"sim-bb-wire-ends-g"});k.appendChild(b);let C=this.closestEdgeIdx(n),I=this.closestEdgeIdx(v);if(C==I){let e=a(n,r,g);p.appendChild(e),d.push(e)}else{let t,i,l=m(n),u=a(n,l,g);!(1!=C&&2!=C||1!=I&&2!=I)?(t=o(l,r,s,g),i=o(l,r,s,g)):(t=a(l,r,g),i=a(l,r,g)),e.U.addClass(i,"sim-bb-wire-hover"),p.appendChild(u),d.push(u),this.underboard.appendChild(t),d.push(t);let c=`sim-bb-wire-id-${f}`;const h=t=>e.U.addClass(t,c);h(k),h(i),this.styleEl.textContent+=`\n .${c}:hover ~ .${c}.sim-bb-wire-hover {\n visibility: visible;\n }`}k.appendChild(E);let R=`\n .wire-stroke-${g} {\n stroke: ${t.mapWireColor(u)};\n }\n .wire-fill-${g} {\n fill: ${t.mapWireColor(u)};\n }\n `;return this.styleEl.textContent+=R,{endG:k,end1:b,end2:E,wires:d}}checkWire(e,t){let n=this.getLocCoord(e),s=this.getLocCoord(t);return!!n&&!!s}addWire(e,t,n){let s=this.getLocCoord(e),i=this.getLocCoord(t);if(!s||!i)return void console.debug(`unable to allocate wire for ${e} or ${t}`);let r,o=this.getPinStyle(t);return r="dalboard"==t.type&&"croc"==o?this.drawWireWithCrocs(s,i,n):this.drawWire(s,i,n),r}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={}));