1
0
mirror of https://github.com/sehugg/8bitworkshop.git synced 2024-11-28 23:49:20 +00:00
8bitworkshop/lib/stellerator/stellerator-embedded.min.js
2021-09-15 14:41:25 -05:00

23 lines
145 KiB
JavaScript

!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).$6502=e()}(this,(function(){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */function t(t,e,s,i){var r,n=arguments.length,a=n<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,s,i);else for(var o=t.length-1;o>=0;o--)(r=t[o])&&(a=(n<3?r(a):n>3?r(e,s,a):r(e,s))||a);return n>3&&a&&Object.defineProperty(e,s,a),a}function e(t,e){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function s(t,e,s,i){return new(s||(s=Promise))((function(r,n){function a(t){try{h(i.next(t))}catch(t){n(t)}}function o(t){try{h(i.throw(t))}catch(t){n(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(a,o)}h((i=i.apply(t,e||[])).next())}))}function i(t,e){var s,i,r,n,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return n={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function o(n){return function(o){return function(n){if(s)throw new TypeError("Generator is already executing.");for(;a;)try{if(s=1,i&&(r=2&n[0]?i.return:n[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,n[1])).done)return r;switch(i=0,r&&(n=[2&n[0],r.value]),n[0]){case 0:case 1:r=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,i=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!(r=a.trys,(r=r.length>0&&r[r.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]<r[3])){a.label=n[1];break}if(6===n[0]&&a.label<r[1]){a.label=r[1],r=n;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(n);break}r[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a)}catch(t){n=[6,t],i=0}finally{s=r=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,o])}}}var r=function(){function t(t){if(this._maxConcurrency=t,this._queue=[],t<=0)throw new Error("semaphore must be initialized to a positive value");this._value=t}return t.prototype.acquire=function(){var t=this,e=this.isLocked(),s=new Promise((function(e){return t._queue.push(e)}));return e||this._dispatch(),s},t.prototype.runExclusive=function(t){return s(this,void 0,void 0,(function(){var e,s,r;return i(this,(function(i){switch(i.label){case 0:return[4,this.acquire()];case 1:e=i.sent(),s=e[0],r=e[1],i.label=2;case 2:return i.trys.push([2,,4,5]),[4,t(s)];case 3:return[2,i.sent()];case 4:return r(),[7];case 5:return[2]}}))}))},t.prototype.isLocked=function(){return this._value<=0},t.prototype.release=function(){if(this._maxConcurrency>1)throw new Error("this method is unavailabel on semaphores with concurrency > 1; use the scoped release returned by acquire instead");this._currentReleaser&&(this._currentReleaser(),this._currentReleaser=void 0)},t.prototype._dispatch=function(){var t=this,e=this._queue.shift();if(e){var s=!1;this._currentReleaser=function(){s||(s=!0,t._value++,t._dispatch())},e([this._value--,this._currentReleaser])}},t}(),n=function(){function t(){this._semaphore=new r(1)}return t.prototype.acquire=function(){return s(this,void 0,void 0,(function(){var t;return i(this,(function(e){switch(e.label){case 0:return[4,this._semaphore.acquire()];case 1:return t=e.sent(),[2,t[1]]}}))}))},t.prototype.runExclusive=function(t){return this._semaphore.runExclusive((function(){return t()}))},t.prototype.isLocked=function(){return this._semaphore.isLocked()},t.prototype.release=function(){this._semaphore.release()},t}();function a(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function o(t,e,s){return t(s={path:e,exports:{},require:function(t,e){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==e&&s.path)}},s.exports),s.exports}var h=o((function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var s=[];function i(t){return s[t]||(s[t]=function(t){for(var e="return function dispatcher"+t+"(payload) {\n",s=[],i=[],r=0;r<t;r++)s.push("cb"+r),i.push("ctx"+r),e+=" cb"+r+"(payload, ctx"+r+");\n";return e+="};",new(Function.bind.apply(Function,[void 0].concat(s.concat(i),[e])))}(t)),s[t]}s[0]=function(){return function(){}},s[1]=function(t,e){return void 0===e?t:function(s){t(s,e)}};var r=function(){function t(){this.hasHandlers=!1,this._handlers=[],this._contexts=[],this._createDispatcher()}return t.prototype.addHandler=function(t,e){return this.isHandlerAttached(t,e)||(this._handlers.push(t),this._contexts.push(e),this._createDispatcher(),this._updateHasHandlers()),this},t.prototype.removeHandler=function(t,e){var s=this._getHandlerIndex(t,e);return void 0!==s&&(this._handlers.splice(s,1),this._contexts.splice(s,1),this._createDispatcher(),this._updateHasHandlers()),this},t.prototype.isHandlerAttached=function(t,e){return void 0!==this._getHandlerIndex(t,e)},t.prototype._updateHasHandlers=function(){this.hasHandlers=!!this._handlers.length},t.prototype._getHandlerIndex=function(t,e){var s,i=this._handlers.length;for(s=0;s<i&&(this._handlers[s]!==t||this._contexts[s]!==e);s++);return s<i?s:void 0},t.prototype._createDispatcher=function(){this.dispatch=i(this._handlers.length).apply(this,this._handlers.concat(this._contexts))},t}();e.default=r}));a(h);var c=o((function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Event=h.default}));a(c);var _,l=c.Event;!function(t){let e;!function(t){t.stopped="stopped",t.running="running",t.paused="paused",t.error="error"}(e=t.State||(t.State={}))}(_||(_={}));var u=o((function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var s="resolve_transaction",i="reject_transaction",r="error",n=function(){function t(t,e){void 0===e&&(e=0),this._dispatch=t,this._rpcTimeout=e,this.error=new c.Event,this._rpcHandlers={},this._signalHandlers={},this._pendingTransactions={},this._nextTransactionId=0}return t.prototype.dispatch=function(e){var s=e;switch(s.type){case t.MessageType.signal:return this._handleSignal(s);case t.MessageType.rpc:return this._handeRpc(s);case t.MessageType.internal:return this._handleInternal(s);default:this._raiseError("invalid message type "+s.type)}},t.prototype.rpc=function(e,s,i){var r=this,n=this._nextTransactionId++;return this._dispatch({type:t.MessageType.rpc,transactionId:n,id:e,payload:s},i||void 0),new Promise((function(t,e){var s=r._pendingTransactions[n]={id:n,resolve:t,reject:e};r._rpcTimeout>0&&(r._pendingTransactions[n].timeoutHandle=setTimeout((function(){return r._transactionTimeout(s)}),r._rpcTimeout))}))},t.prototype.signal=function(e,s,i){return this._dispatch({type:t.MessageType.signal,id:e,payload:s},i||void 0),this},t.prototype.registerRpcHandler=function(t,e){if(this._rpcHandlers[t])throw new Error("rpc handler for "+t+" already registered");return this._rpcHandlers[t]=e,this},t.prototype.registerSignalHandler=function(t,e){return this._signalHandlers[t]||(this._signalHandlers[t]=[]),this._signalHandlers[t].push(e),this},t.prototype.deregisterRpcHandler=function(t,e){return this._rpcHandlers[t]&&delete this._rpcHandlers[t],this},t.prototype.deregisterSignalHandler=function(t,e){return this._signalHandlers[t]&&(this._signalHandlers[t]=this._signalHandlers[t].filter((function(t){return e!==t}))),this},t.prototype._raiseError=function(e){this.error.dispatch(new Error(e)),this._dispatch({type:t.MessageType.internal,id:r,payload:e})},t.prototype._handleSignal=function(t){if(!this._signalHandlers[t.id])return this._raiseError("invalid signal "+t.id);this._signalHandlers[t.id].forEach((function(e){return e(t.payload)}))},t.prototype._handeRpc=function(e){var r=this;if(!this._rpcHandlers[e.id])return this._raiseError("invalid rpc "+e.id);Promise.resolve(this._rpcHandlers[e.id](e.payload)).then((function(i){return r._dispatch({type:t.MessageType.internal,id:s,transactionId:e.transactionId,payload:i})}),(function(s){return r._dispatch({type:t.MessageType.internal,id:i,transactionId:e.transactionId,payload:s})}))},t.prototype._handleInternal=function(t){var e=void 0!==t.transactionId?this._pendingTransactions[t.transactionId]:void 0;switch(t.id){case s:if(!e||void 0===t.transactionId)return this._raiseError("no pending transaction with id "+t.transactionId);e.resolve(t.payload),this._clearTransaction(this._pendingTransactions[t.transactionId]);break;case i:if(!e||void 0===t.transactionId)return this._raiseError("no pending transaction with id "+t.transactionId);this._pendingTransactions[t.transactionId].reject(t.payload),this._clearTransaction(this._pendingTransactions[t.transactionId]);break;case r:this.error.dispatch(new Error("remote error: "+t.payload));break;default:this._raiseError("unhandled internal message "+t.id)}},t.prototype._transactionTimeout=function(t){t.reject("transaction timed out"),this._raiseError("transaction "+t.id+" timed out"),delete this._pendingTransactions[t.id]},t.prototype._clearTransaction=function(t){void 0!==t.timeoutHandle&&clearTimeout(t.timeoutHandle),delete this._pendingTransactions[t.id]},t}();!function(t){!function(t){t[t.signal=0]="signal",t[t.rpc=1]="rpc",t[t.internal=2]="internal"}(t.MessageType||(t.MessageType={}))}(n||(n={})),e.default=n}));a(u);var d=o((function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.RpcProvider=u.default}));a(d);var p=d.RpcProvider;class g{constructor(t,e,s,i,r){if(this._videoProxy=t,this._controlProxy=e,this._waveformChannels=s,this._pcmChannel=i,this._asyncIOProxy=r,this._config=null,2!==this._waveformChannels.length)throw new Error("invalid channel count "+this._waveformChannels.length)}setConfig(t){this._config=t}getConfig(){return this._config}getVideo(){return this._videoProxy}getJoystick(t){return this._controlProxy.getJoystick(t)}getControlPanel(){return this._controlProxy.getControlPanel()}getPaddle(t){return this._controlProxy.getPaddle(t)}getWaveformChannels(){return this._waveformChannels}getPCMChannel(){return this._pcmChannel}getVideoProxy(){return this._videoProxy}getAsyncIO(){return this._asyncIOProxy}}class f{constructor(t,e,s){this._value=t,this._releaseCB=e,this._disposeCB=s,this._isAvailable=!1,this._isDisposed=!1}adopt(t){this._value=t}get(){return this._value}release(){this._releaseCB(this)}dispose(){this._disposeCB(this)}}class m{constructor(t){this._factory=t,this.event={release:new l,dispose:new l},this._pool=[],this._poolSize=0}get(){let t;if(0===this._poolSize){const e=this._factory();t=new f(e,t=>this._releaseMember(t),t=>this._disposeMember(t))}else t=this._pool[--this._poolSize],t._isAvailable=!1;return t}_releaseMember(t){if(t._isAvailable)throw new Error("Trying to release an already released pool member");if(t._isDisposed)throw new Error("Trying to release an already disposed pool member");const e=this._poolSize++;this._pool[e]=t,t._isAvailable=!0,t._poolPosition=e,this.event.release.dispatch(t.get())}_disposeMember(t){if(t._isDisposed)throw new Error("Trying to dispose of an already disposed pool member");t._isAvailable&&(this._poolSize>1&&(this._pool[t._poolPosition]=this._pool[this._poolSize-1]),this._poolSize--),t._isDisposed=!0,this.event.dispose.dispatch(t.get())}}const y={emulationPause:"emulation/pause",emulationReset:"emulation/reset",emulationResume:"emulation/resume",emulationSetRateLimit:"emulation/setRateLimit",emulationStart:"emulation/start",emulationStop:"emulation/stop",emulationFetchLastError:"emulation/fetchLastError",getVideoParameters:"video/getParameters",getWaveformAudioParameters:t=>"audio/waveform/getParameters/"+t,getPCMAudioParameters:t=>"audio/pcm/getParameters/"+t,setup:"/setup"};Object.freeze(y);const b={emulationError:"emulation/error",emulationFrequencyUpdate:"emulation/frequencyUpdate",videoNewFrame:"video/newFrame",videoReturnSurface:"video/returnSurface",controlStateUpdate:"control/stateUpdate",waveformAudioVolumeChange:"audio/waveform/volumeChange",waveformAudioBufferChange:"audio/waveform/bufferChange",pcmAudioNewFrame:t=>"audio/pcm/newFrame/"+t,pcmAudioTogglePause:t=>"audio/pcm/togglePause/"+t,pcmAudioReturnFrame:t=>"audio/pcm/returnFrame/"+t,audioStop:"audio/stop",messageFromAsyncIO:"asyncIO/messageFrom",messageToAsyncIO:"asyncIO/messageTo"};Object.freeze(b);class v{constructor(t){this._rpc=t,this.newFrame=new l,this._framePool=new m(()=>null),this._frameMap=null,this._active=!1,this._width=0,this._height=0,this._framePool.event.release.addHandler(v._onDisposeFrame,this)}init(){this._rpc.registerSignalHandler(b.videoNewFrame,this._onNewFrame.bind(this))}start(){return s(this,void 0,void 0,(function*(){this._active&&this.stop();const t=yield this._rpc.rpc(y.getVideoParameters);this._active=!0,this._width=t.width,this._height=t.height,this._frameMap=new WeakMap}))}stop(){this._active=!1}getWidth(){return this._width}getHeight(){return this._height}static _onDisposeFrame(t,e){if(!e._active)return;if(!e._frameMap.has(t))return void console.warn("unknown imageData returned to proxy");const s=e._frameMap.get(t);e._frameMap.delete(t),e._rpc.signal(b.videoReturnSurface,{id:s,buffer:t.data.buffer},[t.data.buffer])}_onNewFrame(t){if(!this._active)return void console.warn("video proxy deactivated: ignoring frame");if(this._width!==t.width||this._height!==t.height)return void console.warn("surface dimensions do not match; ignoring frame");const e=this._framePool.get(),s=new ImageData(new Uint8ClampedArray(t.buffer),t.width,t.height);e.adopt(s),this._frameMap.set(s,t.id),this.newFrame.dispatch(e)}}class w{constructor(t=!1){this._state=t,this.stateChanged=new l,this.beforeRead=new l}read(){return this.beforeRead.dispatch(this),this._state}peek(){return this._state}toggle(t){this._state!==t&&(this._state=t,this.stateChanged.dispatch(t))}}class E{constructor(){this._left=new w,this._right=new w,this._up=new w,this._down=new w,this._fire=new w}getLeft(){return this._left}getRight(){return this._right}getUp(){return this._up}getDown(){return this._down}getFire(){return this._fire}}class x{constructor(){this._selectSwitch=new w,this._resetButton=new w,this._colorSwitch=new w,this._difficutlyP0=new w,this._difficutlyP1=new w}getSelectSwitch(){return this._selectSwitch}getResetButton(){return this._resetButton}getColorSwitch(){return this._colorSwitch}getDifficultySwitchP0(){return this._difficutlyP0}getDifficultySwitchP1(){return this._difficutlyP1}}class T{constructor(){this.valueChanged=new l,this._fireSwitch=new w,this._value=.5}setValue(t){this._value=t,this.valueChanged.dispatch(t)}getValue(){return this._value}getFire(){return this._fireSwitch}}class C{constructor(t){this._rpc=t,this._joysticks=new Array(2),this._paddles=new Array(4),this._controlPanel=new x;for(let t=0;t<2;t++)this._joysticks[t]=new E;for(let t=0;t<4;t++)this._paddles[t]=new T}sendUpdate(){this._rpc.signal(b.controlStateUpdate,{joystickState:this._joysticks.map(C._joystickState),paddleState:this._paddles.map(C._paddleState),controlPanelState:C._controlPanelState(this._controlPanel)})}getJoystick(t){if(t<0||t>1)throw new Error("invalid joystick index "+t);return this._joysticks[t]}getControlPanel(){return this._controlPanel}getPaddle(t){if(t<0||t>3)throw new Error("invalid paddle index "+t);return this._paddles[t]}static _joystickState(t){return{up:t.getUp().read(),down:t.getDown().read(),left:t.getLeft().read(),right:t.getRight().read(),fire:t.getFire().read()}}static _paddleState(t){return{value:t.getValue(),fire:t.getFire().read()}}static _controlPanelState(t){return{difficulty0:t.getDifficultySwitchP0().read(),difficulty1:t.getDifficultySwitchP1().read(),select:t.getSelectSwitch().read(),reset:t.getResetButton().read(),color:t.getColorSwitch().read()}}}var k;!function(t){t.State=class{constructor(){this.a=0,this.x=0,this.y=0,this.s=0,this.p=0,this.flags=0,this.irq=!1,this.nmi=!1}}}(k||(k={}));class A{constructor(){this.cycleType=0,this.address=0,this.value=0,this.pollInterrupts=!1,this.nextStep=null}read(t,e){return this.cycleType=0,this.address=e,this.nextStep=t,this}write(t,e,s){return this.cycleType=1,this.address=e,this.value=s,this.nextStep=t,this}poll(t){return this.pollInterrupts=t,this}}const S=Symbol("immutable properties");function R(t){const e=t[S];if(e)for(const s of e)Object.defineProperty(t,s,{writable:!1,configurable:!1})}function F(t,e){t[S]||Object.defineProperty(t,S,{value:[],writable:!1,enumerable:!1}),t[S].push(e)}class P{constructor(t){this.reset=()=>this._result.read(this._pre1Step,255),this._pre1Step=()=>this._result.read(this._pre2Step,255),this._pre2Step=()=>this._result.read(this._stack1Step,256),this._stack1Step=()=>this._result.read(this._stack2Step,511),this._stack2Step=()=>(this._state.s=253,this._result.read(this._stack3Step,510)),this._stack3Step=()=>this._result.read(this._readTargetLoStep,65532),this._readTargetLoStep=t=>(this._targetAddress=t,this._result.read(this._readTargetHiStep,65533)),this._readTargetHiStep=t=>(this._targetAddress|=t<<8,this._state.p=this._targetAddress,null),this._targetAddress=0,this._result=new A,this._state=t,R(this)}}t([F,e("design:type",Object)],P.prototype,"reset",void 0),t([F,e("design:type",Object)],P.prototype,"_pre1Step",void 0),t([F,e("design:type",Object)],P.prototype,"_pre2Step",void 0),t([F,e("design:type",Object)],P.prototype,"_stack1Step",void 0),t([F,e("design:type",Object)],P.prototype,"_stack2Step",void 0),t([F,e("design:type",Object)],P.prototype,"_stack3Step",void 0),t([F,e("design:type",Object)],P.prototype,"_readTargetLoStep",void 0),t([F,e("design:type",Object)],P.prototype,"_readTargetHiStep",void 0),t([F,e("design:type",Object)],P.prototype,"_result",void 0),t([F,e("design:type",k.State)],P.prototype,"_state",void 0);class B{constructor(t,e,s){this.reset=()=>this._result.read(this._dummyRead,this._state.p),this._dummyRead=()=>(this._isBrk&&(this._state.p=this._state.p+1&65535),this._result.write(this._pushPch,256+this._state.s,this._state.p>>>8)),this._pushPch=()=>(this._state.s=this._state.s-1&255,this._result.write(this._pushPcl,256+this._state.s,255&this._state.p).poll(!0)),this._pushPcl=()=>(this._state.s=this._state.s-1&255,this._vector=this._state.nmi?65530:this._defaultVector,this._result.write(this._pushFlags,256+this._state.s,this._isBrk?16|this._state.flags:-17&this._state.flags)),this._pushFlags=()=>(this._state.s=this._state.s-1&255,this._result.read(this._fetchPcl,this._vector)),this._fetchPcl=t=>(this._state.flags|=4,this._state.p=t,this._result.read(this._fetchPch,++this._vector)),this._fetchPch=t=>(this._state.p=this._state.p|t<<8,this._state.nmi=this._state.irq=!1,null),this._vector=0,this._result=new A,this._state=t,this._defaultVector=e,this._isBrk=s,R(this)}}t([F,e("design:type",Object)],B.prototype,"reset",void 0),t([F,e("design:type",Object)],B.prototype,"_dummyRead",void 0),t([F,e("design:type",Object)],B.prototype,"_pushPch",void 0),t([F,e("design:type",Object)],B.prototype,"_pushPcl",void 0),t([F,e("design:type",Object)],B.prototype,"_pushFlags",void 0),t([F,e("design:type",Object)],B.prototype,"_fetchPcl",void 0),t([F,e("design:type",Object)],B.prototype,"_fetchPch",void 0),t([F,e("design:type",Object)],B.prototype,"_result",void 0),t([F,e("design:type",k.State)],B.prototype,"_state",void 0),t([F,e("design:type",Number)],B.prototype,"_defaultVector",void 0),t([F,e("design:type",Boolean)],B.prototype,"_isBrk",void 0);class D{constructor(t,e,s=e){this.operation=t,this.addressingMode=e,this.effectiveAddressingMode=s}getSize(){switch(this.effectiveAddressingMode){case 1:case 2:case 6:case 9:case 8:case 11:case 5:return 2;case 3:case 7:case 10:case 4:return 3;default:return 1}}}!function(t){let e;!function(t){t[t.adc=0]="adc",t[t.and=1]="and",t[t.asl=2]="asl",t[t.bcc=3]="bcc",t[t.bcs=4]="bcs",t[t.beq=5]="beq",t[t.bit=6]="bit",t[t.bmi=7]="bmi",t[t.bne=8]="bne",t[t.bpl=9]="bpl",t[t.brk=10]="brk",t[t.bvc=11]="bvc",t[t.bvs=12]="bvs",t[t.clc=13]="clc",t[t.cld=14]="cld",t[t.cli=15]="cli",t[t.clv=16]="clv",t[t.cmp=17]="cmp",t[t.cpx=18]="cpx",t[t.cpy=19]="cpy",t[t.dec=20]="dec",t[t.dex=21]="dex",t[t.dey=22]="dey",t[t.eor=23]="eor",t[t.inc=24]="inc",t[t.inx=25]="inx",t[t.iny=26]="iny",t[t.jmp=27]="jmp",t[t.jsr=28]="jsr",t[t.lda=29]="lda",t[t.ldx=30]="ldx",t[t.ldy=31]="ldy",t[t.lsr=32]="lsr",t[t.nop=33]="nop",t[t.ora=34]="ora",t[t.pha=35]="pha",t[t.php=36]="php",t[t.pla=37]="pla",t[t.plp=38]="plp",t[t.rol=39]="rol",t[t.ror=40]="ror",t[t.rti=41]="rti",t[t.rts=42]="rts",t[t.sbc=43]="sbc",t[t.sec=44]="sec",t[t.sed=45]="sed",t[t.sei=46]="sei",t[t.sta=47]="sta",t[t.stx=48]="stx",t[t.sty=49]="sty",t[t.tax=50]="tax",t[t.tay=51]="tay",t[t.tsx=52]="tsx",t[t.txa=53]="txa",t[t.txs=54]="txs",t[t.tya=55]="tya",t[t.dop=56]="dop",t[t.top=57]="top",t[t.alr=58]="alr",t[t.axs=59]="axs",t[t.dcp=60]="dcp",t[t.lax=61]="lax",t[t.arr=62]="arr",t[t.slo=63]="slo",t[t.aax=64]="aax",t[t.lar=65]="lar",t[t.isc=66]="isc",t[t.aac=67]="aac",t[t.atx=68]="atx",t[t.rra=69]="rra",t[t.rla=70]="rla",t[t.invalid=71]="invalid"}(e=t.OperationMap||(t.OperationMap={})),t.opcodes=new Array(256)}(D||(D={})),function(t){let e;!function(e){for(let e=0;e<256;e++)t.opcodes[e]=new t(71,12);let s,i,r;for(let e=0;e<8;e++){switch(e){case 0:s=34;break;case 1:s=1;break;case 2:s=23;break;case 3:s=0;break;case 4:s=47;break;case 5:s=29;break;case 6:s=17;break;case 7:s=43}for(let n=0;n<8;n++){switch(n){case 0:i=8;break;case 1:i=2;break;case 2:i=1;break;case 3:i=3;break;case 4:i=11;break;case 5:i=6;break;case 6:i=10;break;case 7:i=7}47===s&&1===i&&(i=12),71!==s&&12!==i&&(r=e<<5|n<<2|1,t.opcodes[r]=new t(s,i))}}function n(e,s,i,r){if(71!==t.opcodes[e].operation)throw new Error("entry for opcode "+e+" already exists");t.opcodes[e]=new t(s,i,r)}n(6,2,2),n(10,2,0),n(14,2,3),n(22,2,6),n(30,2,7),n(38,39,2),n(42,39,0),n(46,39,3),n(54,39,6),n(62,39,7),n(70,32,2),n(74,32,0),n(78,32,3),n(86,32,6),n(94,32,7),n(102,40,2),n(106,40,0),n(110,40,3),n(118,40,6),n(126,40,7),n(134,48,2),n(142,48,3),n(150,48,9),n(162,30,1),n(166,30,2),n(174,30,3),n(182,30,9),n(190,30,10),n(198,20,2),n(206,20,3),n(214,20,6),n(222,20,7),n(230,24,2),n(238,24,3),n(246,24,6),n(254,24,7),n(36,6,2),n(44,6,3),n(76,27,3),n(108,27,4),n(132,49,2),n(140,49,3),n(148,49,6),n(160,31,1),n(164,31,2),n(172,31,3),n(180,31,6),n(188,31,7),n(192,19,1),n(196,19,2),n(204,19,3),n(224,18,1),n(228,18,2),n(236,18,3),n(16,9,5),n(48,7,5),n(80,11,5),n(112,12,5),n(144,3,5),n(176,4,5),n(208,8,5),n(240,5,5),n(0,10,0),n(32,28,0,3),n(64,41,0),n(96,42,0),n(8,36,0),n(40,38,0),n(72,35,0),n(104,37,0),n(136,22,0),n(168,51,0),n(200,26,0),n(232,25,0),n(24,13,0),n(56,44,0),n(88,15,0),n(120,46,0),n(152,55,0),n(184,16,0),n(216,14,0),n(248,45,0),n(138,53,0),n(154,54,0),n(170,50,0),n(186,52,0),n(202,21,0),n(234,33,0),n(26,33,0),n(58,33,0),n(90,33,0),n(122,33,0),n(218,33,0),n(250,33,0),n(4,56,2),n(20,56,6),n(52,56,6),n(68,56,2),n(84,56,6),n(100,56,2),n(116,56,6),n(128,56,1),n(130,56,1),n(137,56,1),n(194,56,1),n(212,56,6),n(226,56,1),n(244,56,6),n(12,57,3),n(28,57,7),n(60,57,7),n(92,57,7),n(124,57,7),n(220,57,7),n(252,57,7),n(235,43,1),n(75,58,1),n(203,59,1),n(199,60,2),n(215,60,6),n(207,60,3),n(223,60,7),n(219,60,10),n(195,60,8),n(211,60,11),n(167,61,2),n(183,61,9),n(175,61,3),n(191,61,10),n(163,61,8),n(179,61,11),n(107,62,1),n(7,63,2),n(23,63,6),n(15,63,3),n(31,63,7),n(27,63,10),n(3,63,8),n(19,63,11),n(135,64,2),n(151,64,9),n(131,64,8),n(143,64,3),n(187,65,10),n(231,66,2),n(247,66,6),n(239,66,3),n(255,66,7),n(251,66,10),n(227,66,8),n(243,66,11),n(11,67,1),n(43,67,1),n(171,68,1),n(103,69,2),n(119,69,6),n(111,69,3),n(127,69,7),n(123,69,10),n(99,69,8),n(115,69,11),n(39,70,2),n(55,70,6),n(47,70,3),n(63,70,7),n(59,70,10),n(35,70,8),n(51,70,11)}(e=t.__init||(t.__init={}))}(D||(D={}));class I{constructor(t,e=(()=>null)){this.reset=()=>this._result.read(this._fetchLo,this._state.p),this._fetchLo=t=>(this._operand=t,this._state.p=this._state.p+1&65535,this._result.read(this._fetchHi,this._state.p)),this._fetchHi=t=>(this._operand|=t<<8,this._state.p=this._state.p+1&65535,this._next(this._operand,this._state)),this._operand=0,this._result=new A,this._state=t,this._next=e,R(this)}}t([F,e("design:type",Object)],I.prototype,"reset",void 0),t([F,e("design:type",Object)],I.prototype,"_fetchLo",void 0),t([F,e("design:type",Object)],I.prototype,"_fetchHi",void 0),t([F,e("design:type",Object)],I.prototype,"_result",void 0),t([F,e("design:type",k.State)],I.prototype,"_state",void 0),t([F,e("design:type",Function)],I.prototype,"_next",void 0);class M{constructor(t,e,s=(()=>null),i=!1){this.reset=()=>this._result.read(this._fetchLo,this._state.p),this._fetchLo=t=>(this._operand=t,this._state.p=this._state.p+1&65535,this._result.read(this._fetchHi,this._state.p)),this._fetchHi=t=>{this._operand|=t<<8,this._state.p=this._state.p+1&65535;const e=this._indexExtractor(this._state);return this._carry=(255&this._operand)+e>255,this._operand=65280&this._operand|this._operand+e&255,this._carry||this._writeOp?this._result.read(this._dereferenceAndCarry,this._operand):this._next(this._operand,this._state)},this._dereferenceAndCarry=t=>(this._carry&&(this._operand=this._operand+256&65535),this._next(this._operand,this._state)),this._operand=0,this._carry=!1,this._result=new A,this._state=t,this._indexExtractor=e,this._next=s,this._writeOp=i,R(this)}static absoluteX(t,e,s){return new M(t,t=>t.x,e,s)}static absoluteY(t,e,s){return new M(t,t=>t.y,e,s)}}t([F,e("design:type",Object)],M.prototype,"reset",void 0),t([F,e("design:type",Object)],M.prototype,"_fetchLo",void 0),t([F,e("design:type",Object)],M.prototype,"_fetchHi",void 0),t([F,e("design:type",Object)],M.prototype,"_dereferenceAndCarry",void 0),t([F,e("design:type",Object)],M.prototype,"_result",void 0),t([F,e("design:type",k.State)],M.prototype,"_state",void 0),t([F,e("design:type",Function)],M.prototype,"_indexExtractor",void 0),t([F,e("design:type",Function)],M.prototype,"_next",void 0),t([F,e("design:type",Boolean)],M.prototype,"_writeOp",void 0),t([F,e("design:type",Function),e("design:paramtypes",[k.State,Function,Boolean]),e("design:returntype",M)],M,"absoluteX",null),t([F,e("design:type",Function),e("design:paramtypes",[k.State,Function,Boolean]),e("design:returntype",M)],M,"absoluteY",null);class O{constructor(t,e=(()=>null)){this.reset=t=>this._result.read(this._dereference,t),this._dereference=t=>this._next(t,this._state),this._result=new A,this._next=e,this._state=t,R(this)}}t([F,e("design:type",Object)],O.prototype,"reset",void 0),t([F,e("design:type",Object)],O.prototype,"_dereference",void 0),t([F,e("design:type",Object)],O.prototype,"_result",void 0),t([F,e("design:type",k.State)],O.prototype,"_state",void 0),t([F,e("design:type",Function)],O.prototype,"_next",void 0);class L{constructor(t,e=(()=>null)){this.reset=()=>this._result.read(this._fetchOperand,this._state.p),this._fetchOperand=t=>(this._operand=t,this._state.p=this._state.p+1&65535,this._next(this._operand,this._state)),this._operand=0,this._result=new A,this._state=t,this._next=e,R(this)}}t([F,e("design:type",Object)],L.prototype,"reset",void 0),t([F,e("design:type",Object)],L.prototype,"_fetchOperand",void 0),t([F,e("design:type",Object)],L.prototype,"_result",void 0),t([F,e("design:type",k.State)],L.prototype,"_state",void 0),t([F,e("design:type",Function)],L.prototype,"_next",void 0);class U{constructor(t,e=(()=>null)){this.reset=()=>this._result.read(this._fetchAddress,this._state.p),this._fetchAddress=t=>(this._address=t,this._state.p=this._state.p+1&65535,this._result.read(this._addIndex,this._address)),this._addIndex=t=>(this._address=this._address+this._state.x&255,this._result.read(this._fetchLo,this._address)),this._fetchLo=t=>(this._operand=t,this._address=this._address+1&255,this._result.read(this._fetchHi,this._address)),this._fetchHi=t=>(this._operand|=t<<8,this._next(this._operand,this._state)),this._operand=0,this._address=0,this._result=new A,this._state=t,this._next=e,R(this)}}t([F,e("design:type",Object)],U.prototype,"reset",void 0),t([F,e("design:type",Object)],U.prototype,"_fetchAddress",void 0),t([F,e("design:type",Object)],U.prototype,"_addIndex",void 0),t([F,e("design:type",Object)],U.prototype,"_fetchLo",void 0),t([F,e("design:type",Object)],U.prototype,"_fetchHi",void 0),t([F,e("design:type",Object)],U.prototype,"_result",void 0),t([F,e("design:type",k.State)],U.prototype,"_state",void 0),t([F,e("design:type",Function)],U.prototype,"_next",void 0);class j{constructor(t,e=(()=>null),s){this.reset=()=>this._result.read(this._fetchAddress,this._state.p),this._fetchAddress=t=>(this._address=t,this._state.p=this._state.p+1&65535,this._result.read(this._fetchLo,this._address)),this._fetchLo=t=>(this._operand=t,this._address=this._address+1&255,this._result.read(this._fetchHi,this._address)),this._fetchHi=t=>(this._operand|=t<<8,this._carry=(255&this._operand)+this._state.y>255,this._operand=65280&this._operand|this._operand+this._state.y&255,this._carry||this._writeOp?this._result.read(this._dereferenceAndCarry,this._operand):this._next(this._operand,this._state)),this._dereferenceAndCarry=t=>(this._carry&&(this._operand=this._operand+256&65535),this._next(this._operand,this._state)),this._operand=0,this._address=0,this._carry=!1,this._result=new A,this._state=t,this._next=e,this._writeOp=s,R(this)}}t([F,e("design:type",Object)],j.prototype,"reset",void 0),t([F,e("design:type",Object)],j.prototype,"_fetchAddress",void 0),t([F,e("design:type",Object)],j.prototype,"_fetchLo",void 0),t([F,e("design:type",Object)],j.prototype,"_fetchHi",void 0),t([F,e("design:type",Object)],j.prototype,"_dereferenceAndCarry",void 0),t([F,e("design:type",Object)],j.prototype,"_result",void 0),t([F,e("design:type",k.State)],j.prototype,"_state",void 0),t([F,e("design:type",Function)],j.prototype,"_next",void 0),t([F,e("design:type",Boolean)],j.prototype,"_writeOp",void 0);class H{constructor(t,e=(()=>null)){this.reset=()=>this._result.read(this._fetchAddress,this._state.p),this._fetchAddress=t=>(this._operand=t,this._state.p=this._state.p+1&65535,this._next(this._operand,this._state)),this._operand=0,this._result=new A,this._state=t,this._next=e,R(this)}}t([F,e("design:type",Object)],H.prototype,"reset",void 0),t([F,e("design:type",Object)],H.prototype,"_fetchAddress",void 0),t([F,e("design:type",Object)],H.prototype,"_result",void 0),t([F,e("design:type",k.State)],H.prototype,"_state",void 0),t([F,e("design:type",Function)],H.prototype,"_next",void 0);class z{constructor(t,e,s){this.reset=()=>this._result.read(this._fetchAddress,this._state.p),this._fetchAddress=t=>(this._operand=t,this._state.p=this._state.p+1&65535,this._result.read(this._addIndex,this._operand)),this._addIndex=t=>(this._operand=this._operand+this._indexExtractor(this._state)&255,this._next(this._operand,this._state)),this._operand=0,this._result=new A,this._state=t,this._indexExtractor=e,this._next=s,R(this)}static zeroPageX(t,e=(()=>null)){return new z(t,t=>t.x,e)}static zeroPageY(t,e=(()=>null)){return new z(t,t=>t.y,e)}}t([F,e("design:type",Object)],z.prototype,"reset",void 0),t([F,e("design:type",Object)],z.prototype,"_fetchAddress",void 0),t([F,e("design:type",Object)],z.prototype,"_addIndex",void 0),t([F,e("design:type",Object)],z.prototype,"_result",void 0),t([F,e("design:type",k.State)],z.prototype,"_state",void 0),t([F,e("design:type",Function)],z.prototype,"_next",void 0),t([F,e("design:type",Function)],z.prototype,"_indexExtractor",void 0);class X{constructor(t,e){this.reset=()=>this._result.read(this._fetchTarget,this._state.p).poll(!0),this._fetchTarget=t=>(this._operand=t,this._state.p=this._state.p+1&65535,this._predicate(this._state.flags)?this._result.read(this._firstDummyRead,this._state.p):null),this._firstDummyRead=t=>(this._target=this._state.p+(128&this._operand?this._operand-256:this._operand)&65535,(65280&this._target)==(65280&this._state.p)?(this._state.p=this._target,null):this._result.read(this._secondDummyRead,65280&this._state.p|255&this._target).poll(!0)),this._secondDummyRead=t=>(this._state.p=this._target,null),this._target=0,this._operand=0,this._result=new A,this._state=t,this._predicate=e,R(this)}}t([F,e("design:type",Object)],X.prototype,"reset",void 0),t([F,e("design:type",Object)],X.prototype,"_fetchTarget",void 0),t([F,e("design:type",Object)],X.prototype,"_firstDummyRead",void 0),t([F,e("design:type",Object)],X.prototype,"_secondDummyRead",void 0),t([F,e("design:type",Object)],X.prototype,"_result",void 0),t([F,e("design:type",k.State)],X.prototype,"_state",void 0),t([F,e("design:type",Function)],X.prototype,"_predicate",void 0);const V=(t,e)=>new X(t,e);class q{constructor(t){this.reset=()=>this._result.read(this._fetchPcl,this._state.p),this._fetchPcl=t=>(this._addressLo=t,this._state.p=this._state.p+1&65535,this._result.read(this._dummyStackRead,256+this._state.s)),this._dummyStackRead=()=>this._result.write(this._pushPch,256+this._state.s,this._state.p>>>8),this._pushPch=()=>(this._state.s=this._state.s-1&255,this._result.write(this._pushPcl,256+this._state.s,255&this._state.p)),this._pushPcl=()=>(this._state.s=this._state.s-1&255,this._result.read(this._fetchPch,this._state.p)),this._fetchPch=t=>(this._state.p=this._addressLo|t<<8,null),this._addressLo=0,this._result=new A,this._state=t,R(this)}}t([F,e("design:type",Object)],q.prototype,"_fetchPcl",void 0),t([F,e("design:type",Object)],q.prototype,"_dummyStackRead",void 0),t([F,e("design:type",Object)],q.prototype,"_pushPch",void 0),t([F,e("design:type",Object)],q.prototype,"_pushPcl",void 0),t([F,e("design:type",Object)],q.prototype,"_fetchPch",void 0),t([F,e("design:type",Object)],q.prototype,"_result",void 0),t([F,e("design:type",k.State)],q.prototype,"_state",void 0);class G{constructor(t,e){this.reset=t=>(this._address=t,this._result.read(this._read,t)),this._read=t=>(this._operand=t,this._result.write(this._dummyWrite,this._address,this._operand)),this._dummyWrite=t=>this._result.write(this._write,this._address,this._operation(this._operand,this._state)),this._write=()=>null,this._result=new A,this._state=t,this._operation=e,R(this)}}t([F,e("design:type",Object)],G.prototype,"reset",void 0),t([F,e("design:type",Object)],G.prototype,"_read",void 0),t([F,e("design:type",Object)],G.prototype,"_dummyWrite",void 0),t([F,e("design:type",Object)],G.prototype,"_write",void 0),t([F,e("design:type",Object)],G.prototype,"_result",void 0),t([F,e("design:type",k.State)],G.prototype,"_state",void 0),t([F,e("design:type",Function)],G.prototype,"_operation",void 0);const Q=(t,e)=>new G(t,e);class N{constructor(t){this.reset=()=>this._result.read(this._dummyOperandRead,this._state.p),this._dummyOperandRead=()=>this._result.read(this._dummyStackRead,256+this._state.s),this._dummyStackRead=()=>(this._state.s=this._state.s+1&255,this._result.read(this._popPcl,256+this._state.s)),this._popPcl=t=>(this._state.p=65280&this._state.p|t,this._state.s=this._state.s+1&255,this._result.read(this._popPch,256+this._state.s)),this._popPch=t=>(this._state.p=255&this._state.p|t<<8,this._result.read(this._incrementP,this._state.p)),this._incrementP=()=>(this._state.p=this._state.p+1&65535,null),this._result=new A,this._state=t,R(this)}}t([F,e("design:type",Object)],N.prototype,"reset",void 0),t([F,e("design:type",Object)],N.prototype,"_dummyOperandRead",void 0),t([F,e("design:type",Object)],N.prototype,"_dummyStackRead",void 0),t([F,e("design:type",Object)],N.prototype,"_popPcl",void 0),t([F,e("design:type",Object)],N.prototype,"_popPch",void 0),t([F,e("design:type",Object)],N.prototype,"_incrementP",void 0),t([F,e("design:type",Object)],N.prototype,"_result",void 0),t([F,e("design:type",k.State)],N.prototype,"_state",void 0);class W{constructor(t,e){this.reset=()=>this._result.read(this._executeOperation,this._state.p).poll(!0),this._executeOperation=()=>(this._operation(this._state),null),this._result=new A,this._state=t,this._operation=e,R(this)}}t([F,e("design:type",Object)],W.prototype,"reset",void 0),t([F,e("design:type",Object)],W.prototype,"_executeOperation",void 0),t([F,e("design:type",Object)],W.prototype,"_result",void 0),t([F,e("design:type",k.State)],W.prototype,"_state",void 0),t([F,e("design:type",Function)],W.prototype,"_operation",void 0);const Y=(t,e)=>new W(t,e);class ${constructor(t,e){this.reset=()=>this._result.read(this._dummyRead,this._state.p).poll(!0),this._dummyRead=()=>this._result.read(this._incrementS,256+this._state.s),this._incrementS=()=>(this._state.s=this._state.s+1&255,this._result.read(this._pull,256+this._state.s)),this._pull=t=>(this._operation(this._state,t),null),this._result=new A,this._state=t,this._operation=e,R(this)}}t([F,e("design:type",Object)],$.prototype,"reset",void 0),t([F,e("design:type",Object)],$.prototype,"_dummyRead",void 0),t([F,e("design:type",Object)],$.prototype,"_incrementS",void 0),t([F,e("design:type",Object)],$.prototype,"_pull",void 0),t([F,e("design:type",Object)],$.prototype,"_result",void 0),t([F,e("design:type",k.State)],$.prototype,"_state",void 0),t([F,e("design:type",Function)],$.prototype,"_operation",void 0);const K=(t,e)=>new $(t,e);class J{constructor(t,e){this.reset=()=>this._result.read(this._dummyRead,this._state.p),this._dummyRead=()=>this._result.write(this._push,256+this._state.s,this._operation(this._state)),this._push=()=>(this._state.s=this._state.s-1&255,null),this._result=new A,this._state=t,this._operation=e,R(this)}}t([F,e("design:type",Object)],J.prototype,"reset",void 0),t([F,e("design:type",Object)],J.prototype,"_dummyRead",void 0),t([F,e("design:type",Object)],J.prototype,"_push",void 0),t([F,e("design:type",Object)],J.prototype,"_result",void 0),t([F,e("design:type",k.State)],J.prototype,"_state",void 0),t([F,e("design:type",Function)],J.prototype,"_operation",void 0);const Z=(t,e)=>new J(t,e);class tt{constructor(t){this.reset=()=>this._result.read(this._dummyOperandRead,this._state.p),this._dummyOperandRead=()=>this._result.read(this._dummyStackRead,256+this._state.s),this._dummyStackRead=()=>(this._state.s=this._state.s+1&255,this._result.read(this._popP,256+this._state.s)),this._popP=t=>(this._state.flags=-17&(32|t),this._state.s=this._state.s+1&255,this._result.read(this._popPcl,256+this._state.s)),this._popPcl=t=>(this._state.p=65280&this._state.p|t,this._state.s=this._state.s+1&255,this._result.read(this._popPch,256+this._state.s)),this._popPch=t=>(this._state.p=255&this._state.p|t<<8,null),this._result=new A,this._state=t,R(this)}}t([F,e("design:type",Object)],tt.prototype,"reset",void 0),t([F,e("design:type",Object)],tt.prototype,"_dummyOperandRead",void 0),t([F,e("design:type",Object)],tt.prototype,"_dummyStackRead",void 0),t([F,e("design:type",Object)],tt.prototype,"_popP",void 0),t([F,e("design:type",Object)],tt.prototype,"_popPcl",void 0),t([F,e("design:type",Object)],tt.prototype,"_popPch",void 0),t([F,e("design:type",Object)],tt.prototype,"_result",void 0),t([F,e("design:type",k.State)],tt.prototype,"_state",void 0);class et{constructor(t,e){this.reset=t=>this._result.write(()=>null,t,this._operation(this._state)),this._result=new A,this._state=t,this._operation=e,R(this)}}t([F,e("design:type",Object)],et.prototype,"reset",void 0),t([F,e("design:type",Object)],et.prototype,"_result",void 0),t([F,e("design:type",k.State)],et.prototype,"_state",void 0),t([F,e("design:type",Function)],et.prototype,"_operation",void 0);const st=(t,e)=>new et(t,e);function it(t,e){e.flags=-131&e.flags|128&t|(t?0:2)}function rt(t,e,s){const i=s(t);return it(i,e),i}function nt(t,e){it(e(t),t)}function at(t,e,s){return it(s(t,e),e),null}function ot(t,e){if(8&e.flags){const s=(15&t)+(15&e.a)+(1&e.flags),i=(t>>>4)+(e.a>>>4)+(s>9?1:0);e.a=s%10|i%10<<4,e.flags=-132&e.flags|128&e.a|(e.a?0:2)|(i>9?1:0)}else{const s=e.a+t+(1&e.flags),i=255&s;e.flags=-196&e.flags|128&i|(i?0:2)|s>>>8|(~(t^e.a)&(i^t)&128)>>>1,e.a=i}return null}function ht(t){const e=t.a;t.a=t.a<<1&255,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|e>>>7}function ct(t,e){const s=t<<1&255;return e.flags=-132&e.flags|128&s|(s?0:2)|t>>>7,s}function _t(t,e){return e.flags=-195&e.flags|192&t|(t&e.a?0:2),null}function lt(t,e,s){const i=s(e)+(255&~t)+1;e.flags=-132&e.flags|128&i|(255&i?0:2)|i>>>8}function ut(t,e){if(8&e.flags){const s=(15&e.a)-(15&t)-(1&~e.flags),i=(e.a>>>4)-(t>>>4)-(s<0?1:0);e.a=(s<0?10+s:s)|(i<0?10+i:i)<<4,e.flags=-132&e.flags|128&e.a|(e.a?0:2)|(i<0?0:1)}else{t=255&~t;const s=e.a+t+(1&e.flags),i=255&s;e.flags=-196&e.flags|128&i|(i?0:2)|s>>>8|(~(t^e.a)&(i^t)&128)>>>1,e.a=i}return null}function dt(t){const e=t.a;t.a=t.a>>>1,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|1&e}function pt(t,e){const s=t>>>1;return e.flags=-132&e.flags|128&s|(s?0:2)|1&t,s}function gt(t){const e=t.a;t.a=t.a<<1&255|1&t.flags,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|e>>>7}function ft(t,e){const s=t<<1&255|1&e.flags;return e.flags=-132&e.flags|128&s|(s?0:2)|t>>>7,s}function mt(t){const e=t.a;t.a=t.a>>>1|(1&t.flags)<<7,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|1&e}function yt(t,e){const s=t>>>1|(1&e.flags)<<7;return e.flags=-132&e.flags|128&s|(s?0:2)|1&t,s}function bt(t,e){const s=e.a&t;return e.a=s>>>1,e.flags=-132&e.flags|128&e.a|(e.a?0:2)|1&s,null}function vt(t,e){const s=t+255&255,i=e.a+(255&~s)+1;return e.flags=-132&e.flags|128&i|(255&i?0:2)|i>>>8,s}function wt(t,e){const s=(e.a&e.x)+(255&~t)+1;return e.x=255&s,e.flags=-132&e.flags|128&e.x|(255&e.x?0:2)|s>>>8,null}function Et(t,e){const s=t>>>1|(1&e.flags)<<7;return e.flags=-2&e.flags|1&t,ot(s,e),s}function xt(t,e){const s=t<<1&255|1&e.flags;return e.flags=-2&e.flags|t>>>7,it(e.a&=s,e),s}function Tt(t,e){e.flags=-2&e.flags|t>>>7;const s=t<<1&255;return e.a=e.a|s,it(e.a,e),s}function Ct(t){const e=t.a&t.x;return it(e,t),e}function kt(t,e){const s=t+1&255;return ut(s,e),s}function At(t,e){return e.a&=t,it(e.a,e),e.flags=-2&e.flags|(128&e.a)>>>7,null}class St{constructor(t,e=(()=>null)){this.reset=()=>this._result.read(this._fetchAddressLo,this._state.p),this._fetchAddressLo=t=>(this._address=t,this._state.p=this._state.p+1&65535,this._result.read(this._fetchAddressHi,this._state.p)),this._fetchAddressHi=t=>(this._address|=t<<8,this._state.p=this._state.p+1&65535,this._result.read(this._fetchLo,this._address)),this._fetchLo=t=>(this._operand=t,255==(255&this._address)?this._address&=65280:this._address=this._address+1&65535,this._result.read(this._fetchHi,this._address)),this._fetchHi=t=>(this._operand|=t<<8,this._next(this._operand,this._state)),this._operand=0,this._address=0,this._result=new A,this._state=t,this._next=e,R(this)}}t([F,e("design:type",Object)],St.prototype,"reset",void 0),t([F,e("design:type",Object)],St.prototype,"_fetchAddressLo",void 0),t([F,e("design:type",Object)],St.prototype,"_fetchAddressHi",void 0),t([F,e("design:type",Object)],St.prototype,"_fetchLo",void 0),t([F,e("design:type",Object)],St.prototype,"_fetchHi",void 0),t([F,e("design:type",Object)],St.prototype,"_result",void 0),t([F,e("design:type",k.State)],St.prototype,"_state",void 0),t([F,e("design:type",Function)],St.prototype,"_next",void 0);class Rt{constructor(t){this._state=t}compile(t){const e=D.opcodes[t];switch(e.operation){case 0:return this._createAddressing(e.addressingMode,ot,{deref:!0});case 1:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.a=e.a&t),{deref:!0});case 2:return 0===e.addressingMode?Y(this._state,ht):this._createAddressing(e.addressingMode,Q(this._state,ct).reset,{writeOp:!0});case 6:return this._createAddressing(e.addressingMode,_t,{deref:!0});case 10:return s=this._state,new B(s,65534,!0);case 17:return this._createAddressing(e.addressingMode,(t,e)=>(lt(t,e,t=>t.a),null),{deref:!0});case 18:return this._createAddressing(e.addressingMode,(t,e)=>(lt(t,e,t=>t.x),null),{deref:!0});case 19:return this._createAddressing(e.addressingMode,(t,e)=>(lt(t,e,t=>t.y),null),{deref:!0});case 20:return this._createAddressing(e.addressingMode,Q(this._state,(t,e)=>rt(t,e,t=>t-1&255)).reset,{writeOp:!0});case 21:return Y(this._state,t=>nt(t,t=>t.x=t.x-1&255));case 22:return Y(this._state,t=>nt(t,t=>t.y=t.y-1&255));case 24:return this._createAddressing(e.addressingMode,Q(this._state,(t,e)=>rt(t,e,t=>t+1&255)).reset,{writeOp:!0});case 25:return Y(this._state,t=>nt(t,t=>t.x=t.x+1&255));case 26:return Y(this._state,t=>nt(t,t=>t.y=t.y+1&255));case 23:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.a=e.a^t),{deref:!0});case 27:return this._createAddressing(e.addressingMode,(t,e)=>(e.p=t,null));case 28:return(t=>new q(t))(this._state);case 29:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.a=t),{deref:!0});case 30:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.x=t),{deref:!0});case 31:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.y=t),{deref:!0});case 32:return 0===e.addressingMode?Y(this._state,dt):this._createAddressing(e.addressingMode,Q(this._state,pt).reset,{writeOp:!0});case 33:return Y(this._state,()=>{});case 34:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.a|=t),{deref:!0});case 35:return Z(this._state,t=>t.a);case 36:return Z(this._state,t=>16|t.flags);case 37:return K(this._state,(t,e)=>nt(t,t=>t.a=e));case 38:return K(this._state,(t,e)=>t.flags=-17&(32|e));case 39:return 0===e.addressingMode?Y(this._state,gt):this._createAddressing(e.addressingMode,Q(this._state,ft).reset,{writeOp:!0});case 40:return 0===e.addressingMode?Y(this._state,mt):this._createAddressing(e.addressingMode,Q(this._state,yt).reset,{writeOp:!0});case 41:return(t=>new tt(t))(this._state);case 42:return(t=>new N(t))(this._state);case 43:return this._createAddressing(e.addressingMode,ut,{deref:!0});case 48:return this._createAddressing(e.addressingMode,st(this._state,t=>t.x).reset,{writeOp:!0});case 49:return this._createAddressing(e.addressingMode,st(this._state,t=>t.y).reset,{writeOp:!0});case 50:return Y(this._state,t=>nt(t,t=>t.x=t.a));case 51:return Y(this._state,t=>nt(t,t=>t.y=t.a));case 52:return Y(this._state,t=>nt(t,t=>t.x=t.s));case 53:return Y(this._state,t=>nt(t,t=>t.a=t.x));case 54:return Y(this._state,t=>t.s=t.x);case 55:return Y(this._state,t=>nt(t,t=>t.a=t.y));case 3:return V(this._state,t=>0==(1&t));case 4:return V(this._state,t=>(1&t)>0);case 8:return V(this._state,t=>0==(2&t));case 5:return V(this._state,t=>(2&t)>0);case 9:return V(this._state,t=>0==(128&t));case 7:return V(this._state,t=>(128&t)>0);case 11:return V(this._state,t=>0==(64&t));case 12:return V(this._state,t=>(64&t)>0);case 44:return Y(this._state,t=>t.flags|=1);case 45:return Y(this._state,t=>t.flags|=8);case 46:return Y(this._state,t=>t.flags|=4);case 47:return this._createAddressing(e.addressingMode,st(this._state,t=>t.a).reset,{writeOp:!0});case 13:return Y(this._state,t=>t.flags&=-2);case 14:return Y(this._state,t=>t.flags&=-9);case 15:return Y(this._state,t=>t.flags&=-5);case 16:return Y(this._state,t=>t.flags&=-65);case 56:case 57:return this._createAddressing(e.addressingMode,()=>null,{deref:!0});case 67:return this._createAddressing(e.addressingMode,At);case 64:return this._createAddressing(e.addressingMode,st(this._state,Ct).reset,{writeOp:!0});case 58:return this._createAddressing(e.addressingMode,bt,{deref:!0});case 62:return this._createAddressing(e.addressingMode,(t,e)=>(function(t,e){e.a=(e.a&t)>>>1|(1&e.flags?128:0),e.flags=-196&e.flags|(64&e.a)>>>6|(e.a?0:2)|128&e.a|64&e.a^(32&e.a)<<1}(t,e),null),{deref:!0});case 59:return this._createAddressing(e.addressingMode,wt,{deref:!0});case 68:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.x=e.a=e.a&t),{deref:!0});case 60:return this._createAddressing(e.addressingMode,Q(this._state,vt).reset,{writeOp:!0});case 66:return this._createAddressing(e.addressingMode,Q(this._state,kt).reset,{writeOp:!0});case 61:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.a=e.x=t),{deref:!0});case 65:return this._createAddressing(e.addressingMode,(t,e)=>at(t,e,(t,e)=>e.s=e.x=e.a=e.s&t),{deref:!0});case 70:return this._createAddressing(e.addressingMode,Q(this._state,xt).reset,{writeOp:!0});case 69:return this._createAddressing(e.addressingMode,Q(this._state,Et).reset,{writeOp:!0});case 63:return this._createAddressing(e.addressingMode,Q(this._state,Tt).reset,{writeOp:!0});default:return null}var s}_createAddressing(t,e,{deref:s=!1,writeOp:i=!1}={}){switch(s&&1!==t&&(e=((t,e)=>new O(t,e))(this._state,e).reset),t){case 1:return((t,e)=>new L(t,e))(this._state,e);case 2:return((t,e)=>new H(t,e))(this._state,e);case 3:return((t,e)=>new I(t,e))(this._state,e);case 6:return((t,e)=>z.zeroPageX(t,e))(this._state,e);case 9:return((t,e)=>z.zeroPageY(t,e))(this._state,e);case 7:return((t,e,s)=>M.absoluteX(t,e,s))(this._state,e,i);case 10:return((t,e,s)=>M.absoluteY(t,e,s))(this._state,e,i);case 8:return((t,e)=>new U(t,e))(this._state,e);case 11:return((t,e,s)=>new j(t,e,s))(this._state,e,i);case 4:return((t,e)=>new St(t,e))(this._state,e);default:throw new Error("invalid addressing mode "+t)}}}class Ft{constructor(t,e){var s;this._bus=t,this._rng=e,this.executionState=0,this.state=new k.State,this._invalidInstructionCallback=null,this._interruptPending=!1,this._nmiPending=!1,this._halt=!1,this._pollInterruptsAfterLastInstruction=!1,this._lastInstructionPointer=0,this._operations=new Array(255),this._opBoot=(s=this.state,new P(s)),this._opIrq=(t=>new B(t,65534,!1))(this.state),this._opNmi=(t=>new B(t,65530,!1))(this.state);const i=new Rt(this.state);for(let t=0;t<256;t++)this._operations[t]=i.compile(t);this.reset()}reset(){return this.state.a=this._rng?this._rng.int(255):0,this.state.x=this._rng?this._rng.int(255):0,this.state.y=this._rng?this._rng.int(255):0,this.state.s=253,this.state.p=this._rng?this._rng.int(65535):0,this.state.flags=52|(this._rng?this._rng.int(255):0),this.state.irq=!1,this.state.nmi=!1,this.executionState=0,this._interruptPending=!1,this._nmiPending=!1,this._halt=!1,this._lastResult=this._opBoot.reset(void 0),this._lastInstructionPointer=0,this}setInterrupt(t){return this._interruptPending=t,this}isInterrupt(){return this._interruptPending}nmi(){return this._nmiPending=!0,this}halt(){return this._halt=!0,this}resume(){return this._halt=!1,this}isHalt(){return this._halt}setInvalidInstructionCallback(t){return this._invalidInstructionCallback=t,this}getInvalidInstructionCallback(){return this._invalidInstructionCallback}getLastInstructionPointer(){return this._lastInstructionPointer}cycle(){if(this._halt&&(!this._lastResult||0===this._lastResult.cycleType))return this;if(1===this.executionState)return this._fetch(),this;let t;switch(this._lastResult.cycleType){case 0:t=this._bus.read(this._lastResult.address);break;case 1:t=this._lastResult.value,this._bus.write(this._lastResult.address,t);break;default:throw new Error("invalid cycle type")}return this._lastResult.pollInterrupts&&(this._pollInterrupts(),this._lastResult.pollInterrupts=!1,this._pollInterruptsAfterLastInstruction=!1),this._lastResult=this._lastResult.nextStep(t),null===this._lastResult&&(this.executionState=1),this}_fetch(){let t;this._pollInterruptsAfterLastInstruction&&this._pollInterrupts(),this._lastInstructionPointer=this.state.p;const e=this._bus.read(this.state.p);this.state.nmi?(t=this._opNmi,this._pollInterruptsAfterLastInstruction=!1):this.state.irq?(t=this._opIrq,this._pollInterruptsAfterLastInstruction=!1):(t=this._operations[e],this.state.p=this.state.p+1&65535,this._pollInterruptsAfterLastInstruction=!0),t?(this.executionState=2,this._lastResult=t.reset(void 0)):this._invalidInstructionCallback&&this._invalidInstructionCallback(this)}_pollInterrupts(){if(this.state.irq=!1,this._nmiPending)return this.state.nmi=!0,void(this._nmiPending=!1);!this._interruptPending||this.state.nmi||4&this.state.flags||(this.state.irq=!0)}}function Pt(t,e){t.s=t.s+1&255,t.flags=-17&(32|e.read(256+t.s))}function Bt(t,e){t.flags=-131&t.flags|128&e|(e?0:2)}function Dt(t,e,s){if(8&t.flags){const e=(15&s)+(15&t.a)+(1&t.flags),i=(s>>>4)+(t.a>>>4)+(e>9?1:0);t.a=e%10|i%10<<4,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|(i>9?1:0)}else{const e=t.a+s+(1&t.flags),i=255&e;t.flags=-196&t.flags|128&i|(i?0:2)|e>>>8|(~(s^t.a)&(i^s)&128)>>>1,t.a=i}}function It(t,e,s){t.a&=s,Bt(t,t.a)}function Mt(t){const e=t.a;t.a=t.a<<1&255,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|e>>>7}function Ot(t,e,s){const i=e.read(s),r=i<<1&255;e.write(s,r),t.flags=-132&t.flags|128&r|(r?0:2)|i>>>7}function Lt(t,e,s){t.flags=-195&t.flags|192&s|(s&t.a?0:2)}function Ut(t,e){const s=t.p+1&65535;let i=65534;t.nmi&&(i=65530,t.nmi=!1),t.nmi=t.irq=!1,e.write(t.s+256,s>>>8&255),t.s=t.s+255&255,e.write(t.s+256,255&s),t.s=t.s+255&255,e.write(t.s+256,16|t.flags),t.s=t.s+255&255,t.flags|=4,t.p=e.readWord(i)}function jt(t){t.flags&=-2}function Ht(t){t.flags&=-9}function zt(t){t.flags&=-5}function Xt(t){t.flags&=-65}function Vt(t,e,s){const i=t.a+(255&~s)+1;t.flags=-132&t.flags|128&i|(255&i?0:2)|i>>>8}function qt(t,e,s){const i=t.x+(255&~s)+1;t.flags=-132&t.flags|128&i|(255&i?0:2)|i>>>8}function Gt(t,e,s){const i=t.y+(255&~s)+1;t.flags=-132&t.flags|128&i|(255&i?0:2)|i>>>8}function Qt(t,e,s){const i=e.read(s)+255&255;e.write(s,i),Bt(t,i)}function Nt(t){t.x=t.x+255&255,Bt(t,t.x)}function Wt(t,e,s){t.a=t.a^s,Bt(t,t.a)}function Yt(t){t.y=t.y+255&255,Bt(t,t.y)}function $t(t,e,s){const i=e.read(s)+1&255;e.write(s,i),Bt(t,i)}function Kt(t){t.x=t.x+1&255,Bt(t,t.x)}function Jt(t){t.y=t.y+1&255,Bt(t,t.y)}function Zt(t,e,s){t.p=s}function te(t,e,s){const i=t.p+1&65535,r=e.read(t.p);e.read(256+t.s),e.write(256+t.s,i>>>8),t.s=t.s+255&255,e.write(256+t.s,255&i),t.s=t.s+255&255,t.p=r|e.read(t.p+1&65535)<<8}function ee(t,e,s,i){t.a=1===i?s:e.read(s),Bt(t,t.a)}function se(t,e,s,i){t.x=1===i?s:e.read(s),Bt(t,t.x)}function ie(t,e,s,i){t.y=1===i?s:e.read(s),Bt(t,t.y)}function re(t){const e=t.a;t.a=t.a>>>1,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|1&e}function ne(t,e,s){const i=e.read(s),r=i>>>1;e.write(s,r),t.flags=-132&t.flags|128&r|(r?0:2)|1&i}function ae(){}function oe(t,e,s){t.a|=s,Bt(t,t.a)}function he(t,e){e.write(256+t.s,16|t.flags),t.s=t.s+255&255}function ce(t,e){Pt(t,e)}function _e(t,e){e.write(256+t.s,t.a),t.s=t.s+255&255}function le(t,e){t.s=t.s+1&255,t.a=e.read(256+t.s),Bt(t,t.a)}function ue(t){const e=t.a;t.a=t.a<<1&255|1&t.flags,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|e>>>7}function de(t,e,s){const i=e.read(s),r=i<<1&255|1&t.flags;e.write(s,r),t.flags=-132&t.flags|128&r|(r?0:2)|i>>>7}function pe(t){const e=t.a;t.a=t.a>>>1|(1&t.flags)<<7,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|1&e}function ge(t,e,s){const i=e.read(s),r=i>>>1|(1&t.flags)<<7;e.write(s,r),t.flags=-132&t.flags|128&r|(r?0:2)|1&i}function fe(t,e){let s;Pt(t,e),t.s=t.s+1&255,s=e.read(256+t.s),t.s=t.s+1&255,s|=e.read(256+t.s)<<8,t.p=s}function me(t,e){let s;e.read(256+t.s),t.s=t.s+1&255,s=e.read(256+t.s),t.s=t.s+1&255,s+=e.read(256+t.s)<<8,t.p=s+1&65535}function ye(t,e,s){if(8&t.flags){const e=(15&t.a)-(15&s)-(1&~t.flags),i=(t.a>>>4)-(s>>>4)-(e<0?1:0);t.a=(e<0?10+e:e)|(i<0?10+i:i)<<4,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|(i<0?0:1)}else{s=255&~s;const e=t.a+s+(1&t.flags),i=255&e;t.flags=-196&t.flags|128&i|(i?0:2)|e>>>8|(~(s^t.a)&(i^s)&128)>>>1,t.a=i}}function be(t){t.flags|=1}function ve(t){t.flags|=8}function we(t){t.flags|=4}function Ee(t,e,s){e.write(s,t.a)}function xe(t,e,s){e.write(s,t.x)}function Te(t,e,s){e.write(s,t.y)}function Ce(t){t.x=t.a,Bt(t,t.a)}function ke(t){t.y=t.a,Bt(t,t.a)}function Ae(t){t.x=t.s,Bt(t,t.x)}function Se(t){t.a=t.x,Bt(t,t.a)}function Re(t){t.s=t.x}function Fe(t){t.a=t.y,Bt(t,t.a)}function Pe(t,e,s){const i=t.a&s;t.a=i>>>1,t.flags=-132&t.flags|128&t.a|(t.a?0:2)|1&i}function Be(t,e,s){const i=(t.a&t.x)+(255&~s)+1;t.x=255&i,t.flags=-132&t.flags|128&t.x|(255&t.x?0:2)|i>>>8}function De(t,e,s){const i=e.read(s)+255&255;e.write(s,i);const r=t.a+(255&~i)+1;t.flags=-132&t.flags|128&r|(255&r?0:2)|r>>>8}function Ie(t,e,s){t.a=s,t.x=s,Bt(t,s)}function Me(t,e,s){t.a=(t.a&s)>>>1|(1&t.flags?128:0),t.flags=-196&t.flags|(64&t.a)>>>6|(t.a?0:2)|128&t.a|64&t.a^(32&t.a)<<1}function Oe(t,e,s){let i=e.read(s);t.flags=-2&t.flags|i>>>7,i=i<<1&255,e.write(s,i),t.a=t.a|i,Bt(t,t.a)}function Le(t,e,s){const i=t.x&t.a;e.write(s,i),Bt(t,i)}function Ue(t,e,s){t.s=t.a=t.x=t.s&s,Bt(t,t.a)}function je(t,e,s){const i=e.read(s)+1&255;e.write(s,i),ye(t,0,i)}function He(t,e,s){t.a&=s,Bt(t,t.a),t.flags=-2&t.flags|(128&t.a)>>>7}function ze(t,e,s){t.a&=s,t.x=t.a,Bt(t,t.a)}function Xe(t,e,s){const i=e.read(s),r=i>>>1|(1&t.flags)<<7;e.write(s,r),t.flags=-2&t.flags|1&i,Dt(t,0,r)}function Ve(t,e,s){const i=e.read(s),r=i<<1&255|1&t.flags;e.write(s,r),t.flags=-2&t.flags|i>>>7,It(t,0,r)}function qe(t,e){t.p=e.readWord(65532)}function Ge(t,e,s){const i=t.p;t.nmi&&(s=65530),t.nmi=t.irq=!1,e.write(t.s+256,i>>>8&255),t.s=t.s+255&255,e.write(t.s+256,255&i),t.s=t.s+255&255,e.write(t.s+256,-17&t.flags),t.s=t.s+255&255,t.flags|=4,t.p=e.readWord(s)}function Qe(t,e){Ge(t,e,65534)}function Ne(t,e){Ge(t,e,65530)}class We{constructor(t,e){this._bus=t,this._rng=e,this.executionState=0,this.state=new k.State,this._opCycles=0,this._instructionCallback=null,this._invalidInstructionCallback=null,this._interruptPending=!1,this._nmiPending=!1,this._interuptCheck=0,this._halted=!1,this._operand=0,this._lastInstructionPointer=0,this._currentAddressingMode=12,this._dereference=!1,this.reset()}setInterrupt(t){return this._interruptPending=t,this}isInterrupt(){return this._interruptPending}nmi(){return this._nmiPending=!0,this}halt(){return this._halted=!0,this}resume(){return this._halted=!1,this}isHalt(){return this._halted}setInvalidInstructionCallback(t){return this._invalidInstructionCallback=t,this}getInvalidInstructionCallback(){return this._invalidInstructionCallback}getLastInstructionPointer(){return this._lastInstructionPointer}reset(){return this.state.a=this._rng?this._rng.int(255):0,this.state.x=this._rng?this._rng.int(255):0,this.state.y=this._rng?this._rng.int(255):0,this.state.s=253,this.state.p=this._rng?this._rng.int(65535):0,this.state.flags=52|(this._rng?this._rng.int(255):0),this.state.irq=!1,this.state.nmi=!1,this.executionState=0,this._opCycles=7,this._interruptPending=!1,this._nmiPending=!1,this._instructionCallback=qe,this}cycle(){if(this._halted)return this;switch(this.executionState){case 0:case 2:0==--this._opCycles&&(this._dereference&&(this._operand=this._bus.read(this._operand)),1===this._interuptCheck&&this._checkForInterrupts(),this._instructionCallback(this.state,this._bus,this._operand,this._currentAddressingMode),this.executionState=1,0===this._interuptCheck&&this._checkForInterrupts());break;case 1:if(this.state.nmi)return this._instructionCallback=Ne,this._opCycles=6,this.state.nmi=this.state.irq=!1,this._interuptCheck=1,this.executionState=2,this;if(this.state.irq)return this._instructionCallback=Qe,this._opCycles=6,this.state.nmi=this.state.irq=!1,this._interuptCheck=1,this.executionState=2,this;this._fetch()}return this}_fetch(){const t=D.opcodes[this._bus.read(this.state.p)];let e,s,i=t.addressingMode,r=!1,n=!1;switch(this._lastInstructionPointer=this.state.p,this._currentAddressingMode=i,this._interuptCheck=0,t.operation){case 0:this._opCycles=0,this._instructionCallback=Dt,r=!0;break;case 1:this._opCycles=0,this._instructionCallback=It,r=!0;break;case 2:0===i?(this._opCycles=1,this._instructionCallback=Mt):(this._opCycles=3,this._instructionCallback=Ot,n=!0);break;case 3:1&this.state.flags?(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1):(this._instructionCallback=Zt,this._opCycles=0);break;case 4:1&this.state.flags?(this._instructionCallback=Zt,this._opCycles=0):(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1);break;case 5:2&this.state.flags?(this._instructionCallback=Zt,this._opCycles=0):(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1);break;case 6:this._opCycles=0,this._instructionCallback=Lt,r=!0;break;case 7:128&this.state.flags?(this._instructionCallback=Zt,this._opCycles=0):(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1);break;case 8:2&this.state.flags?(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1):(this._instructionCallback=Zt,this._opCycles=0);break;case 9:128&this.state.flags?(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1):(this._instructionCallback=Zt,this._opCycles=0);break;case 11:64&this.state.flags?(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1):(this._instructionCallback=Zt,this._opCycles=0);break;case 12:64&this.state.flags?(this._instructionCallback=Zt,this._opCycles=0):(i=0,this._instructionCallback=ae,this.state.p=this.state.p+1&65535,this._opCycles=1);break;case 10:this._opCycles=6,this._instructionCallback=Ut,this._interuptCheck=1;break;case 13:this._opCycles=1,this._instructionCallback=jt;break;case 14:this._opCycles=1,this._instructionCallback=Ht;break;case 15:this._opCycles=1,this._instructionCallback=zt,this._interuptCheck=1;break;case 16:this._opCycles=1,this._instructionCallback=Xt;break;case 17:this._opCycles=0,this._instructionCallback=Vt,r=!0;break;case 18:this._opCycles=0,this._instructionCallback=qt,r=!0;break;case 19:this._opCycles=0,this._instructionCallback=Gt,r=!0;break;case 20:this._opCycles=3,this._instructionCallback=Qt,n=!0;break;case 21:this._opCycles=1,this._instructionCallback=Nt;break;case 22:this._opCycles=1,this._instructionCallback=Yt;break;case 23:this._opCycles=0,this._instructionCallback=Wt,r=!0;break;case 24:this._opCycles=3,this._instructionCallback=$t,n=!0;break;case 25:this._opCycles=1,this._instructionCallback=Kt;break;case 26:this._opCycles=1,this._instructionCallback=Jt;break;case 27:this._opCycles=0,this._instructionCallback=Zt;break;case 28:this._opCycles=5,this._instructionCallback=te;break;case 29:this._opCycles=1===i?0:1,this._instructionCallback=ee;break;case 30:this._opCycles=1===i?0:1,this._instructionCallback=se;break;case 31:this._opCycles=1===i?0:1,this._instructionCallback=ie;break;case 32:0===i?(this._opCycles=1,this._instructionCallback=re):(this._opCycles=3,this._instructionCallback=ne,n=!0);break;case 33:this._opCycles=1,this._instructionCallback=ae;break;case 56:case 57:this._opCycles=0,r=!0,this._instructionCallback=ae;break;case 34:this._opCycles=0,this._instructionCallback=oe,r=!0;break;case 36:this._opCycles=2,this._instructionCallback=he;break;case 35:this._opCycles=2,this._instructionCallback=_e;break;case 37:this._opCycles=3,this._instructionCallback=le;break;case 38:this._opCycles=3,this._instructionCallback=ce,this._interuptCheck=1;break;case 39:0===i?(this._opCycles=1,this._instructionCallback=ue):(this._opCycles=3,this._instructionCallback=de,n=!0);break;case 40:0===i?(this._opCycles=1,this._instructionCallback=pe):(this._opCycles=3,this._instructionCallback=ge,n=!0);break;case 41:this._opCycles=5,this._instructionCallback=fe;break;case 42:this._opCycles=5,this._instructionCallback=me;break;case 43:this._opCycles=0,this._instructionCallback=ye,r=!0;break;case 44:this._opCycles=1,this._instructionCallback=be;break;case 45:this._opCycles=1,this._instructionCallback=ve;break;case 46:this._opCycles=1,this._instructionCallback=we,this._interuptCheck=1;break;case 47:this._opCycles=1,this._instructionCallback=Ee,n=!0;break;case 48:this._opCycles=1,this._instructionCallback=xe,n=!0;break;case 49:this._opCycles=1,this._instructionCallback=Te,n=!0;break;case 50:this._opCycles=1,this._instructionCallback=Ce;break;case 51:this._opCycles=1,this._instructionCallback=ke;break;case 52:this._opCycles=1,this._instructionCallback=Ae;break;case 53:this._opCycles=1,this._instructionCallback=Se;break;case 54:this._opCycles=1,this._instructionCallback=Re;break;case 55:this._opCycles=1,this._instructionCallback=Fe;break;case 62:this._opCycles=0,this._instructionCallback=Me;break;case 58:this._opCycles=0,this._instructionCallback=Pe;break;case 59:this._opCycles=0,this._instructionCallback=Be;break;case 60:this._opCycles=3,this._instructionCallback=De,n=!0;break;case 61:this._opCycles=0,this._instructionCallback=Ie,r=!0;break;case 63:this._opCycles=3,this._instructionCallback=Oe,n=!0,r=!1;break;case 64:this._opCycles=1,this._instructionCallback=Le;break;case 65:this._opCycles=0,this._instructionCallback=Ue,r=!0;break;case 66:this._opCycles=3,this._instructionCallback=je,n=!0;break;case 67:this._opCycles=0,this._instructionCallback=He;break;case 68:this._opCycles=0,this._instructionCallback=ze;break;case 69:this._opCycles=3,r=!1,n=!0,this._instructionCallback=Xe;break;case 70:this._opCycles=3,r=!1,n=!0,this._instructionCallback=Ve;break;default:return void(this._invalidInstructionCallback&&this._invalidInstructionCallback(this))}switch(this.state.p=this.state.p+1&65535,i){case 1:this._operand=this._bus.read(this.state.p),r=!1,this.state.p=this.state.p+1&65535,this._opCycles++;break;case 2:this._operand=this._bus.read(this.state.p),this.state.p=this.state.p+1&65535,this._opCycles++;break;case 3:this._operand=this._bus.readWord(this.state.p),this.state.p=this.state.p+2&65535,this._opCycles+=2;break;case 4:e=this._bus.readWord(this.state.p),this._operand=255==(255&e)?this._bus.read(e)+(this._bus.read(65280&e)<<8):this._bus.readWord(e),this.state.p=this.state.p+2&65535,this._opCycles+=4;break;case 5:e=this._bus.read(this.state.p),e=128&e?-(255&~(e-1)):e,this._operand=this.state.p+e+65537&65535,this.state.p=this.state.p+1&65535,this._opCycles+=(65280&this._operand)!=(65280&this.state.p)?3:2;break;case 6:s=this._bus.read(this.state.p),this._bus.read(s),this._operand=s+this.state.x&255,this.state.p=this.state.p+1&65535,this._opCycles+=2;break;case 7:e=this._bus.readWord(this.state.p),this._operand=e+this.state.x&65535,(65280&this._operand)!=(65280&e)&&this._bus.read(65280&e|255&this._operand),this._opCycles+=n||(65280&this._operand)!=(65280&e)?3:2,this.state.p=this.state.p+2&65535;break;case 9:s=this._bus.read(this.state.p),this._bus.read(s),this._operand=s+this.state.y&255,this.state.p=this.state.p+1&65535,this._opCycles+=2;break;case 10:e=this._bus.readWord(this.state.p),this._operand=e+this.state.y&65535,(65280&this._operand)!=(65280&e)&&this._bus.read(65280&e|255&this._operand),this._opCycles+=n||(65280&this._operand)!=(65280&e)?3:2,this.state.p=this.state.p+2&65535;break;case 8:s=this._bus.read(this.state.p),this._bus.read(s),e=s+this.state.x&255,this._operand=255===e?this._bus.read(255)+(this._bus.read(0)<<8):this._bus.readWord(e),this._opCycles+=4,this.state.p=this.state.p+1&65535;break;case 11:e=this._bus.read(this.state.p),e=255===e?this._bus.read(255)+(this._bus.read(0)<<8):this._bus.readWord(e),this._operand=e+this.state.y&65535,(65280&this._operand)!=(65280&e)&&this._bus.read(65280&e|255&this._operand),this._opCycles+=n||(65280&e)!=(65280&this._operand)?4:3,this.state.p=this.state.p+1&65535}this._dereference=r,r&&this._opCycles++,this.executionState=2}_checkForInterrupts(){this._nmiPending&&(this.state.irq=!1,this.state.nmi=!0,this._nmiPending=!1),!this._interruptPending||this.state.nmi||4&this.state.flags||(this.state.irq=!0)}}class Ye{constructor(t){this._type=t}create(t,e){switch(this._type){case Ye.Type.stateMachine:return new Ft(t,e);case Ye.Type.batchedAccess:return new We(t,e);default:throw new Error("invalid CPU type")}}}!function(t){let e;!function(t){t[t.stateMachine=0]="stateMachine",t[t.batchedAccess=1]="batchedAccess"}(e=t.Type||(t.Type={}))}(Ye||(Ye={}));var $e,Ke=Ye;!function(t){t.create=function(t={}){return Object.assign({tvMode:0,enableAudio:!0,randomSeed:-1,emulatePaddles:!0,frameStart:-1,pcmAudio:!1,cpuType:Ke.Type.stateMachine},t)},t.getClockHz=function(t){switch(t.tvMode){case 0:return 3584160;case 1:case 2:return 3556800}}}($e||($e={}));class Je{constructor(t,e){this._content=t,this._sampleRate=e}getLength(){return this._content.length}getContent(){return this._content}getSampleRate(){return this._sampleRate}replaceUnderlyingBuffer(t){this._content=t}}const Ze=new Uint8Array(256);function ts(t,e){const s=Ze[t.charCodeAt(e)];if(s>63)throw new Error('invalid base64 character "'+t[e]+'" at index '+e);return s}function es(t,e){return(ts(t,e)<<18)+(ts(t,e+1)<<12)+(ts(t,e+2)<<6)+ts(t,e+3)}function ss(t){if(t.length%4!=0)throw new Error("invalid base64 data --- char count mismatch");const e=t.length/4,s=3*e-function(t){let e=0,s=t.length-1;for(;s>=0&&"="===t[s--];)e++;return e}(t),i=new Uint8Array(s);let r=0;for(let n=0;n<e;n++){const e=es(t,4*n);for(let t=0;t<3&&r<s;t++)i[r++]=e>>>8*(2-t)&255}return i}!function(t){let e;for(e=0;e<256;e++)Ze[e]=255;for(e=0;e<64;e++)Ze["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;Ze["=".charCodeAt(0)]=0}();const is=ss("AQEPAQEBAQEBAQEBAwMDAQ=="),rs=new Int8Array([1]),ns=new Int8Array([1,1]),as=new Int8Array([16,15]),os=ss("AQICAQEBBAM="),hs=ss("AQIBAQICBQQCAQMBAQEBBA=="),cs=ss("AQQBAwIEAQIDAgEBAQEBAQIEAgEEAQECAgEDAgEDAQEBBAEBAQECAQECBgECAgECAQIBAQIBBgIBAgIBAQEBAgICAgcCAwICAQEBAwIBAQIBAQcBAQMBAQIDAwEBAQICAQECAgQDBQEDAQEFAgEBAQIBAgEDAQIFAQECAQEBBQEBAQEBAQEBBgEBAQIBAQEBBAIBAQMBAwYDAgMBAQIBAgQBAQEDAQEBAQMBAgEEAgIDBAEBBAECAQICAgEBBAMBBAQJBQQBBQMBAQMCAgIBBQECAQEBAgMBAgEBAwQCBQICAQIDAQEBAQECAQMDAwIBAgEBAQEBAwMBAgIDAQMBCA=="),_s=ss("BQYEBQoFAwcECgYDBgQJBg=="),ls=[rs,os,os,ss("AgMCAQQBBgoCBAIBAQQFCQMDBAEBAQgFBQUEAQEBCAQCCAMDAQEHBAIHBQEDAQcEAQQIAgEDBAcBAwcDAgEGBgICBAUDAgYGAQMDAgUDBwMEAwICAgUJAwEFAwECAgsFAQUDAQECDAUBAgUCAQEMBgECBQECAQoGAwICBAECBgo="),ns,ns,as,hs,cs,hs,as,rs,ns,ns,as,_s];class us{constructor(t){this._config=t}setConfig(t){this._config=t}getKey(t,e){return ls[t]===ns&&is[t]*(e+1)==1?0:t<<5|e}getBuffer(t){const e=t>>>5&15,s=31&t,i=ls[e];let r=0;for(let t=0;t<i.length;t++)r+=i[t];r=r*is[e]*(s+1);const n=new Float32Array(r),a=$e.getClockHz(this._config)/114;let o=0,h=0,c=0,_=!0;for(let t=0;t<r;t++)o++,o===is[e]*(s+1)&&(o=0,h++,h===i[c]&&(c++,h=0,i.length===c&&(c=0)),_=!(1&c)),n[t]=_?1:-1;return new Je(n,a)}}class ds{constructor(t,e){this._index=t,this._rpc=e,this.bufferChanged=new l,this.volumeChanged=new l,this.stop=new l,this._toneGenerator=new us,this._volume=0}init(){return this._rpc.registerSignalHandler(b.waveformAudioBufferChange,this._onBufferChangeSignal.bind(this)).registerSignalHandler(b.waveformAudioVolumeChange,this._onVolumeChangeSignal.bind(this)).registerSignalHandler(b.audioStop,this._onStopSignal.bind(this)),this}start(t){return s(this,void 0,void 0,(function*(){const e=yield this._rpc.rpc(y.getWaveformAudioParameters(this._index));this._toneGenerator.setConfig(t),this.setVolume(e.volume)}))}setVolume(t){return this._volume=t,this}getVolume(){return this._volume}getBuffer(t){return this._toneGenerator.getBuffer(t)}_onVolumeChangeSignal(t){t.index===this._index&&(this._volume=t.value,this.volumeChanged.dispatch(this._volume))}_onBufferChangeSignal(t){t.index===this._index&&this.bufferChanged.dispatch(t.key)}_onStopSignal(t){t===this._index&&this.stop.dispatch(void 0)}}class ps{constructor(t,e){this._index=t,this._rpc=e,this.newFrame=new l,this.togglePause=new l,this._sampleRate=0,this._frameSize=0,this._paused=!1,this._framePool=new m(()=>null),this._frameMap=new WeakMap,this._enabled=!1,this._signalReturnFrame="",this._framePool.event.release.addHandler(ps._onReleaseFragment,this),this._signalReturnFrame=b.pcmAudioReturnFrame(this._index)}init(){return this._rpc.registerSignalHandler(b.pcmAudioNewFrame(this._index),this._onNewFrame.bind(this)).registerSignalHandler(b.pcmAudioTogglePause(this._index),this._onTogglePause.bind(this)),this}start(){return s(this,void 0,void 0,(function*(){if(this._enabled)return;const t=yield this._rpc.rpc(y.getPCMAudioParameters(this._index));this._sampleRate=t.sampleRate,this._frameSize=t.frameSize,this._paused=t.paused,this._enabled=!0}))}stop(){this._enabled=!1}isPaused(){return this._paused}getSampleRate(){return this._sampleRate}getFrameSize(){return this._frameSize}static _onReleaseFragment(t,e){e._frameMap.has(t)&&e._rpc.signal(e._signalReturnFrame,{id:e._frameMap.get(t),buffer:t.buffer},[t.buffer])}_onNewFrame(t){if(!this._enabled)return;const e=this._framePool.get(),s=new Float32Array(t.buffer);e.adopt(s),this._frameMap.set(s,t.id),this.newFrame.dispatch(e)}_onTogglePause(t){t.paused!==this._paused&&(this._paused=t.paused,this.togglePause.dispatch(this._paused))}}class gs{constructor(t){this._rpc=t,this.message=new l}init(){this._rpc.registerSignalHandler(b.messageFromAsyncIO,t=>this.message.dispatch(t))}send(t){this._rpc.signal(b.messageToAsyncIO,Array.from(t))}}class fs{constructor(t){this._stellaWorkerUri=t,this.stateChanged=new l,this.frequencyUpdate=new l,this._rateLimitEnforced=!0,this._mutex=new n,this._worker=null,this._rpc=null,this._state=_.State.stopped,this._lastError=null,this._emulationContext=null,this._frequency=0,this._waveformChannels=new Array(2),this._pcmChannel=null,this._controlProxy=null,this._controlProxyUpdateHandle=null,this._proxyState=0,this._savedConfig=null}init(){return s(this,void 0,void 0,(function*(){this._worker=new Worker(this._stellaWorkerUri),this._rpc=new p((t,e)=>this._worker.postMessage(t,e)),this._pcmChannel=new ps(0,this._rpc).init();for(let t=0;t<2;t++)this._waveformChannels[t]=new ds(t,this._rpc).init();const t=new v(this._rpc),e=new C(this._rpc),s=new gs(this._rpc);s.init(),t.init(),this._emulationContext=new g(t,e,this._waveformChannels,this._pcmChannel,s),this._worker.onmessage=t=>this._rpc.dispatch(t.data),this._rpc.registerSignalHandler(b.emulationFrequencyUpdate,this._onFrequencyUpdate.bind(this)).registerSignalHandler(b.emulationError,this._onEmulationError.bind(this)),this._controlProxy=e}))}start(t,e,i){return s(this,void 0,void 0,(function*(){return yield this.stop(),this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){const s=yield this._rpc.rpc(y.emulationStart,{buffer:t,config:e,cartridgeType:i});return s===_.State.paused?(this._savedConfig=e,this._emulationContext.setConfig(e),yield this._startProxies(e)):this._savedConfig=null,this._applyState(s)})))}))}pause(){return this._mutex.runExclusive(()=>this._rpc.rpc(y.emulationPause).then(t=>(this._pauseProxies(),this._applyState(t))))}stop(){return this._mutex.runExclusive(()=>this._rpc.rpc(y.emulationStop).then(t=>(this._stopProxies(),this._applyState(t))))}reset(){return this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){const t=yield this._rpc.rpc(y.emulationReset);return this._state!==_.State.error||t!==_.State.running&&t!==_.State.paused||!this._savedConfig||(yield this._startProxies(this._savedConfig)),this._applyState(t)})))}resume(){return this._mutex.runExclusive(()=>this._rpc.rpc(y.emulationResume).then(t=>(this._resumeProxies(),this._applyState(t))))}setRateLimit(t){return this._rateLimitEnforced=t,this._rpc.rpc(y.emulationSetRateLimit,t)}getFrequency(){return this._frequency}getRateLimit(){return this._rateLimitEnforced}getState(){return this._state}getLastError(){return this._lastError}getEmulationContext(){switch(this._state){case _.State.running:case _.State.paused:return this._emulationContext;default:return null}}_fetchLastError(){return this._rpc.rpc(y.emulationFetchLastError).then(t=>t?new Error(t):null)}_applyState(t){return t===_.State.error?this._fetchLastError().then(e=>(this._state=t,this._lastError=e,this._stopProxies(),this.stateChanged.dispatch(t),t)):(this._state=t,this.stateChanged.dispatch(t),t)}_onFrequencyUpdate(t){this._frequency=t,this.frequencyUpdate.dispatch(this._frequency)}_onEmulationError(t){this._lastError=new Error(t||""),this._stopProxies(),this._state=_.State.error,this.stateChanged.dispatch(this._state)}_startProxies(t){return s(this,void 0,void 0,(function*(){yield this._emulationContext.getVideoProxy().start();for(let e=0;e<this._waveformChannels.length;e++)yield this._waveformChannels[e].start(t);yield this._pcmChannel.start(),this._startControlUpdates(),this._proxyState=1}))}_stopProxies(){0!==this._proxyState&&(this._emulationContext.getVideoProxy().stop(),this._pcmChannel.stop(),this._stopControlUpdates(),this._proxyState=0)}_pauseProxies(){1===this._proxyState&&(this._stopControlUpdates(),this._proxyState=2)}_resumeProxies(){2===this._proxyState&&(this._startControlUpdates(),this._proxyState=1)}_startControlUpdates(){null===this._controlProxyUpdateHandle&&(this._controlProxyUpdateHandle=setInterval(()=>this._controlProxy.sendUpdate(),25))}_stopControlUpdates(){null!==this._controlProxyUpdateHandle&&(clearInterval(this._controlProxyUpdateHandle),this._controlProxyUpdateHandle=null)}}class ms{constructor(){this._drivers=new Map,this._driversBound=!1}bind(t){return this._driversBound||(this._emulationService=t,this._shouldBindDrivers()&&this._bindDrivers(),this._emulationService.stateChanged.addHandler(ms._onEmuStateChange,this)),this}unbind(){return this._emulationService?(this._unbindDrivers(),this._emulationService.stateChanged.removeHandler(ms._onEmuStateChange,this),this._emulationService=null,this):this}addDriver(t,e){return this._drivers.set(t,new ms.DriverContext(t,e)),this._driversBound&&e(this._emulationService.getEmulationContext(),t),this}removeDriver(t){return this._drivers.get(t)?(t.unbind(),this._drivers.delete(t),this):this}static _onEmuStateChange(t,e){e._shouldBindDrivers(t)?e._bindDrivers():e._unbindDrivers()}_shouldBindDrivers(t=(this._emulationService?this._emulationService.getState():void 0)){return this._emulationService&&(t===_.State.running||t===_.State.paused)}_bindDrivers(){this._driversBound||(this._drivers.forEach(t=>t.binder(this._emulationService.getEmulationContext(),t.driver)),this._driversBound=!0)}_unbindDrivers(){this._driversBound&&(this._drivers.forEach(t=>t.driver.unbind()),this._driversBound=!1)}}function ys(t){return`precision ${t.highpInVsh?"highp":"mediump"} float;`}var bs,vs;function ws(t,e,s){const i=t.createShader(e);if(t.shaderSource(i,s),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error(`failed to compile shader:\n\n${t.getShaderInfoLog(i)}\n\n${s}`);return i}!function(t){t.DriverContext=class{constructor(t,e){this.driver=t,this.binder=e}}}(ms||(ms={})),function(t){let e;!function(t){t.source=t=>`\n ${function(t){return`precision ${t.highpInVsh?"highp":"mediump"} float;`}(t)}\n\n attribute vec2 a_VertexPosition;\n attribute vec2 a_TextureCoordinate;\n\n varying vec2 v_TextureCoordinate;\n\n void main() {\n v_TextureCoordinate = a_TextureCoordinate;\n gl_Position = vec4(a_VertexPosition, 0, 1);\n }\n `}(e=t.plain||(t.plain={}))}(bs||(bs={})),function(t){let e,s,i,r,n,a;!function(t){t.source=t=>`\n ${ys(t)}\n\n varying vec2 v_TextureCoordinate;\n\n uniform sampler2D u_Sampler0;\n\n void main() {\n gl_FragColor = vec4(texture2D(u_Sampler0, v_TextureCoordinate).rgb, 1.0);\n }\n `}(e=t.blit||(t.blit={})),function(t){t.source=t=>`\n ${ys(t)}\n\n varying vec2 v_TextureCoordinate;\n\n uniform sampler2D u_Sampler0;\n uniform float u_Gamma;\n\n void main() {\n vec4 texel = texture2D(u_Sampler0, v_TextureCoordinate);\n\n gl_FragColor = vec4(pow(texel.rgb, vec3(u_Gamma)), 1.);\n }\n `}(s=t.blitWithGamma||(t.blitWithGamma={})),function(t){t.source=t=>`\n ${ys(t)}\n\n varying vec2 v_TextureCoordinate;\n\n uniform float u_PhosphorLevel;\n uniform sampler2D u_Sampler_NewImage;\n uniform sampler2D u_Sampler_PreviousImage;\n\n float applyPhosphor(float new, float previous) {\n float decayed = previous * u_PhosphorLevel;\n decayed = step(0.5, (previous - decayed) * 255.0) * decayed;\n\n return max(new, decayed);\n }\n\n void main() {\n vec4 new = texture2D(u_Sampler_NewImage, v_TextureCoordinate);\n vec4 previous = texture2D(u_Sampler_PreviousImage, v_TextureCoordinate);\n\n gl_FragColor = vec4(\n applyPhosphor(new.r, previous.r),\n applyPhosphor(new.g, previous.g),\n applyPhosphor(new.b, previous.b),\n 1.0\n );\n }\n `}(i=t.phosphor||(t.phosphor={})),function(t){t.source=t=>`\n ${ys(t)}\n\n #define PI 3.14159265\n\n #define CHROMA_MOD_FREQ (PI / 3.0)\n\n #define SATURATION 1.0\n #define BRIGHTNESS 1.0\n\n uniform sampler2D u_Sampler0;\n uniform float u_Fringing;\n uniform float u_Artifacting;\n\n varying vec2 v_TextureCoordinate;\n\n const mat3 yiq_mat = mat3(\n 0.2989, 0.5870, 0.1140,\n 0.5959, -0.2744, -0.3216,\n 0.2115, -0.5229, 0.3114\n );\n\n vec3 rgb2yiq(vec3 col) {\n return col * yiq_mat;\n }\n\n ${t.floatTextures||t.halfFloatTextures?"":"\n vec4 pack(vec3 yiq) {\n yiq += 1.2;\n yiq /= 3.4;\n\n int y_byte = int(yiq.r * 1024.0);\n int i_byte = int(yiq.g * 1024.0);\n int q_byte = int(yiq.b * 1024.0);\n\n int y_high = (y_byte / 4) * 4;\n int i_high = (i_byte / 4) * 4;\n int q_high = (q_byte / 4) * 4;\n int alpha = (q_byte - q_high) * 16 + (i_byte - i_high) * 4 + (y_byte - y_high);\n\n return vec4(\n float(y_high / 4) / 255.0,\n float(i_high / 4) / 255.0,\n float(q_high / 4) / 255.0,\n float(alpha) / 255.0\n );\n }\n "}\n\n void main() {\n mat3 mix_mat = mat3(\n BRIGHTNESS, u_Fringing, u_Fringing,\n u_Artifacting, 2.0 * SATURATION, 0.0,\n u_Artifacting, 0.0, 2.0 * SATURATION\n );\n\n vec3 col = texture2D(u_Sampler0, v_TextureCoordinate).rgb;\n vec3 yiq = rgb2yiq(col);\n\n float mod_phase = v_TextureCoordinate.x * 960.0 * CHROMA_MOD_FREQ;\n\n float i_mod = cos(mod_phase);\n float q_mod = sin(mod_phase);\n\n yiq.yz *= vec2(i_mod, q_mod); // Modulate.\n yiq *= mix_mat; // Cross-talk.\n yiq.yz *= vec2(i_mod, q_mod); // Demodulate.\n\n gl_FragColor = ${t.floatTextures||t.halfFloatTextures?"vec4(yiq, 1.0)":"pack(yiq)"};\n }\n `}(r=t.ntscPass1||(t.ntscPass1={})),function(t){const e=[1202e-8,22146e-9,13155e-9,1202e-8,49979e-9,11394e-8,12215e-8,5612e-9,170516e-9,237199e-9,16964e-8,285688e-9,984574e-9,.002018683,.002002275,-909882e-9,-.007049081,-.01322286,-.012606931,.00246086,.035868225,.084016453,.1355635,.175261268,.190176552],s=[118847e-9,271306e-9,502642e-9,930833e-9,.001451013,.002064744,.002700432,.003241276,.003524948,-.003350284,-.002491729,-721149e-9,.002164659,.006313635,.011789103,.01854566,.026414396,.03510071,.044196567,.053207202,.061590275,.068803602,.074356193,.077856564,.079052396];function i(t,e){return t.floatTextures||t.halfFloatTextures?e+".rgb":`unpack(${e})`}t.source=t=>`\n ${ys(t)}\n\n uniform sampler2D u_Sampler0;\n varying vec2 v_TextureCoordinate;\n\n const mat3 yiq2rgb_mat = mat3(\n 1.0, 0.956, 0.6210,\n 1.0, -0.2720, -0.6474,\n 1.0, -1.1060, 1.7046\n );\n\n vec3 yiq2rgb(vec3 yiq) {\n return yiq * yiq2rgb_mat;\n }\n\n ${t.floatTextures||t.halfFloatTextures?"":"\n vec3 unpack(vec4 yiqPacked) {\n int y_high = int(yiqPacked.r * 1024.0);\n int i_high = int(yiqPacked.g * 1024.0);\n int q_high = int(yiqPacked.b * 1024.0);\n int alpha = int(yiqPacked.a * 256.0);\n\n int y_low = alpha - (alpha / 4) * 4;\n int i_low = alpha - y_low - (alpha / 16) * 16;\n int q_low = alpha - i_low - y_low;\n\n return vec3(\n float(y_high + y_low) / 1023.0,\n float(i_high + i_low) / 1023.0,\n float(q_high + q_low) / 1023.0\n ) * 3.4 - 1.2;\n }\n "}\n\n vec3 fetch_offset(int offset) {\n float x = v_TextureCoordinate.x + float(offset) / 960.0;\n\n return step(0.0, x) * step(-1.0, -x) *\n ${i(t,"texture2D(u_Sampler0, vec2(x, v_TextureCoordinate.y))")};\n }\n\n void main() {\n float one_x = 1.0 / 960.0;\n vec3 signal = vec3(0.0);\n\n ${new Array(24).fill(0).map((t,i)=>`\n signal +=\n (fetch_offset(${i-24}) + fetch_offset(${24-i})) *\n vec3(${e[i]}, ${s[i]}, ${s[i]});\n `).join("\n")}\n\n signal += ${i(t,"texture2D(u_Sampler0, v_TextureCoordinate)")} *\n vec3(${e[24]}, ${s[24]}, ${s[24]});\n\n vec3 rgb = yiq2rgb(signal);\n gl_FragColor = vec4(rgb, 1.0);\n }\n `}(n=t.ntscPass2||(t.ntscPass2={})),function(t){t.source=t=>`\n ${ys(t)}\n\n uniform sampler2D u_Sampler0;\n uniform float u_Level;\n uniform float u_Height;\n\n varying vec2 v_TextureCoordinate;\n\n void main() {\n vec3 texel = texture2D(u_Sampler0, v_TextureCoordinate).rgb;\n\n gl_FragColor = vec4(\n (step(1.0, mod(v_TextureCoordinate.y * u_Height, 2.0)) * (1.0 - u_Level) + u_Level) * texel, 1.0);\n }\n `}(a=t.scanlines||(t.scanlines={}))}(vs||(vs={}));class Es{constructor(t,e,s,i){this._gl=t,this._program=e,this._vsh=s,this._fsh=i,this._attributeLocations=new Map,this._uniformLocations=new Map}static compile(t,e,s,i={a_VertexPosition:0}){const r=ws(t,t.VERTEX_SHADER,e),n=ws(t,t.FRAGMENT_SHADER,s),a=t.createProgram();for(const e of Object.keys(i))t.bindAttribLocation(a,i[e],e);if(t.attachShader(a,r),t.attachShader(a,n),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS))throw new Error("failed to link program:\n\n"+t.getProgramInfoLog(a));return new Es(t,a,r,n)}delete(){const t=this._gl;t.deleteProgram(this._program),t.deleteShader(this._vsh),t.deleteShader(this._fsh)}use(){this._gl.useProgram(this._program)}getAttribLocation(t){if(!this._attributeLocations.has(t)){const e=this._gl.getAttribLocation(this._program,t);if(e<0)throw new Error("invalid attribute "+t);this._attributeLocations.set(t,e)}return this._attributeLocations.get(t)}getUniformLocation(t){if(!this._uniformLocations.has(t)){const e=this._gl.getUniformLocation(this._program,t);if(null===e)throw new Error("invalid uniform "+t);this._uniformLocations.set(t,e)}return this._uniformLocations.get(t)}bindVertexAttribArray(t,e,s,i,r,n,a){const o=this._gl;o.bindBuffer(o.ARRAY_BUFFER,e),o.vertexAttribPointer(this.getAttribLocation(t),s,i,r,n,a),o.enableVertexAttribArray(this.getAttribLocation(t))}uniform1i(t,e){this._gl.uniform1i(this.getUniformLocation(t),e)}uniform1f(t,e){this._gl.uniform1f(this.getUniformLocation(t),e)}}class xs{constructor(t,e){this._gl=t,this._capabilities=e,this._width=0,this._height=0,this._texture0=null,this._texture1=null,this._framebuffer=null,this._program=null,this._vertexCoordinateBuffer=null,this._textureCoordinateBuffer=null,this._initialized=!1}init(){if(this._initialized)return;const t=this._gl;this._framebuffer=t.createFramebuffer(),this._program=Es.compile(t,bs.plain.source(this._capabilities),vs.phosphor.source(this._capabilities)),this._program.use(),this._program.uniform1i("u_Sampler_NewImage",0),this._program.uniform1i("u_Sampler_PreviousImage",1),this._vertexCoordinateBuffer=t.createBuffer(),this._textureCoordinateBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._vertexCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,-1,1,1,-1,-1,-1]),t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this._textureCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,0,1,1,0,0,0]),t.STATIC_DRAW),this._initialized=!0}destroy(){if(!this._initialized)return;const t=this._gl;this._program.delete(),t.deleteFramebuffer(this._framebuffer),t.deleteBuffer(this._vertexCoordinateBuffer),t.deleteBuffer(this._textureCoordinateBuffer),this._texture0&&t.deleteTexture(this._texture0),this._texture1&&t.deleteTexture(this._texture1),this._initialized=!1}render(t){const e=this._gl;this._program.use(),this._program.bindVertexAttribArray("a_VertexPosition",this._vertexCoordinateBuffer,2,e.FLOAT,!1,0,0),this._program.bindVertexAttribArray("a_TextureCoordinate",this._textureCoordinateBuffer,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this._texture0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this._texture1,0),e.viewport(0,0,this._width,this._height),e.clearColor(0,0,0,1),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_STRIP,0,4);const s=this._texture1;this._texture1=this._texture0,this._texture0=s}getWidth(){return this._width}getHeight(){return this._height}getTexture(){return this._texture0}resize(t,e){if(!this._initialized)return;this._width=t,this._height=e;const s=this._gl;this._texture0&&s.deleteTexture(this._texture0),this._texture1&&s.deleteTexture(this._texture1),this._texture0=s.createTexture(),this._texture1=s.createTexture(),s.bindFramebuffer(s.FRAMEBUFFER,this._framebuffer),s.viewport(0,0,t,e),s.clearColor(0,0,0,1),s.activeTexture(s.TEXTURE0);for(const i of[this._texture0,this._texture1])s.bindTexture(s.TEXTURE_2D,i),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,t,e,0,s.RGBA,s.UNSIGNED_BYTE,null),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,i,0),s.clear(s.COLOR_BUFFER_BIT)}configure(t){this._initialized&&(this._program.use(),this._program.uniform1f("u_PhosphorLevel",t))}}class Ts{constructor(t,e){this._gl=t,this._capabilities=e,this._height=0,this._programPass1=null,this._programPass2=null,this._targetPass1=null,this._targetPass2=null,this._framebuffer=null,this._vertexCoordinateBuffer=null,this._textureCoordinateBuffer=null,this._initialized=!1}init(){if(this._initialized)return;const t=this._gl;t.getExtension("WEBGL_color_buffer_float"),t.getExtension("OES_texture_float"),this._programPass1=Es.compile(t,bs.plain.source(this._capabilities),vs.ntscPass1.source(this._capabilities)),this._programPass2=Es.compile(t,bs.plain.source(this._capabilities),vs.ntscPass2.source(this._capabilities)),this._programPass1.use(),this._programPass1.uniform1i("u_Sampler0",0),this._programPass2.use(),this._programPass2.uniform1i("u_Sampler0",0),this._framebuffer=t.createFramebuffer(),this._vertexCoordinateBuffer=t.createBuffer(),this._textureCoordinateBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._vertexCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,-1,1,1,-1,-1,-1]),t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this._textureCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,0,1,1,0,0,0]),t.STATIC_DRAW),this._initialized=!0}destroy(){if(!this._initialized)return;const t=this._gl;this._programPass1.delete(),this._programPass2.delete(),t.deleteFramebuffer(this._framebuffer),t.deleteTexture(this._targetPass1),t.deleteTexture(this._targetPass2),t.deleteBuffer(this._vertexCoordinateBuffer),t.deleteBuffer(this._textureCoordinateBuffer),this._initialized=!1}render(t){this._pass(t,this._targetPass1,this._programPass1,960),this._pass(this._targetPass1,this._targetPass2,this._programPass2,480)}getWidth(){return 480}getHeight(){return this._height}getTexture(){return this._targetPass2}resize(t,e){if(!this._initialized)return;if(160!==t)throw new Error("NTSC postprocessor supports only for width = 160");this._height=e;const s=this._gl;this._targetPass1&&s.deleteTexture(this._targetPass1),this._targetPass2&&s.deleteTexture(this._targetPass2),this._targetPass1=s.createTexture(),this._targetPass2=s.createTexture(),s.activeTexture(s.TEXTURE0);for(const t of[this._targetPass1,this._targetPass2])s.bindTexture(s.TEXTURE_2D,t),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,t===this._targetPass1?960:480,e,0,s.RGBA,t===this._targetPass1?this._textureType():s.UNSIGNED_BYTE,null),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR)}configure(t){this._initialized&&(this._programPass1.use(),"composite"===t?(this._programPass1.uniform1f("u_Artifacting",1),this._programPass1.uniform1f("u_Fringing",1)):(this._programPass1.uniform1f("u_Artifacting",0),this._programPass1.uniform1f("u_Fringing",0)))}_pass(t,e,s,i){const r=this._gl;s.use(),s.bindVertexAttribArray("a_VertexPosition",this._vertexCoordinateBuffer,2,r.FLOAT,!1,0,0),s.bindVertexAttribArray("a_TextureCoordinate",this._textureCoordinateBuffer,2,r.FLOAT,!1,0,0),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,t),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,this._framebuffer),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),r.viewport(0,0,i,this._height),r.clearColor(0,0,0,1),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_STRIP,0,4)}_textureType(){const t=this._gl;return this._capabilities.floatTextures?t.FLOAT:this._capabilities.halfFloatTextures?t.getExtension("OES_texture_half_float").HALF_FLOAT_OES:t.UNSIGNED_BYTE}}class Cs{constructor(t,e){this._gl=t,this._capabilities=e,this._width=0,this._height=0,this._texture=null,this._program=null,this._framebuffer=null,this._vertexCoordinateBuffer=null,this._textureCoordinateBuffer=null,this._initialized=!1}init(){if(this._initialized)return;const t=this._gl;this._framebuffer=t.createFramebuffer(),this._program=Es.compile(t,bs.plain.source(this._capabilities),vs.scanlines.source(this._capabilities)),this._program.use(),this._program.uniform1i("u_Sampler0",0),this._vertexCoordinateBuffer=t.createBuffer(),this._textureCoordinateBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._vertexCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,-1,1,1,-1,-1,-1]),t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this._textureCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,0,1,1,0,0,0]),t.STATIC_DRAW),this._initialized=!0}destroy(){if(!this._initialized)return;const t=this._gl;this._program.delete(),t.deleteFramebuffer(this._framebuffer),t.deleteBuffer(this._vertexCoordinateBuffer),t.deleteBuffer(this._textureCoordinateBuffer),this._texture&&t.deleteTexture(this._texture),this._initialized=!1}render(t){const e=this._gl;this._program.use(),this._program.bindVertexAttribArray("a_VertexPosition",this._vertexCoordinateBuffer,2,e.FLOAT,!1,0,0),this._program.bindVertexAttribArray("a_TextureCoordinate",this._textureCoordinateBuffer,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this._texture,0),e.viewport(0,0,this._width,2*this._height),e.clearColor(0,0,0,1),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_STRIP,0,4)}getWidth(){return this._width}getHeight(){return 2*this._height}getTexture(){return this._texture}resize(t,e){if(!this._initialized)return;this._width=t,this._height=e;const s=this._gl;this._texture&&s.deleteTexture(this._texture),this._texture=s.createTexture(),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,this._texture),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,t,2*e,0,s.RGBA,s.UNSIGNED_BYTE,null),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),this._program.use(),this._program.uniform1f("u_Height",2*this._height)}configure(t){this._initialized&&(this._program.use(),this._program.uniform1f("u_Level",1-t))}}class ks{constructor(t,e){this._gl=t,this._capabilities=e,this._width=0,this._height=0,this._widthFrom=0,this._heightFrom=0,this._widthTo=0,this._heightTo=0,this._texture=null,this._program=null,this._framebuffer=null,this._vertexCoordinateBuffer=null,this._textureCoordinateBuffer=null,this._initialized=!1}init(){if(this._initialized)return;const t=this._gl;this._framebuffer=t.createFramebuffer(),this._program=Es.compile(t,bs.plain.source(this._capabilities),vs.blit.source(this._capabilities)),this._program.use(),this._program.uniform1i("u_Sampler0",0),this._vertexCoordinateBuffer=t.createBuffer(),this._textureCoordinateBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._vertexCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,-1,1,1,-1,-1,-1]),t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this._textureCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,0,1,1,0,0,0]),t.STATIC_DRAW),this._initialized=!0}destroy(){if(!this._initialized)return;const t=this._gl;this._program.delete(),t.deleteFramebuffer(this._framebuffer),t.deleteBuffer(this._vertexCoordinateBuffer),t.deleteBuffer(this._textureCoordinateBuffer),this._texture&&t.deleteTexture(this._texture),this._initialized=!1}render(t){const e=this._gl;this._program.use(),this._program.bindVertexAttribArray("a_VertexPosition",this._vertexCoordinateBuffer,2,e.FLOAT,!1,0,0),this._program.bindVertexAttribArray("a_TextureCoordinate",this._textureCoordinateBuffer,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.bindFramebuffer(e.FRAMEBUFFER,this._framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this._texture,0),e.viewport(0,0,this._width,this._height),e.clearColor(0,0,0,1),e.clear(e.COLOR_BUFFER_BIT),e.drawArrays(e.TRIANGLE_STRIP,0,4)}getWidth(){return this._width}getHeight(){return this._height}getTexture(){return this._texture}resize(t,e){this._widthFrom=t,this._heightFrom=e,this._reconfigure()}configure(t,e){this._widthTo=t,this._heightTo=e,this._reconfigure()}_reconfigure(){if(this._widthFrom<=0||this._heightFrom<=0||this._widthTo<=0||this._heightTo<=0||!this._initialized)return;this._width=this._widthTo>this._widthFrom?Math.floor(this._widthTo/this._widthFrom)*this._widthFrom:this._widthFrom,this._height=this._heightTo>this._heightFrom?Math.floor(this._heightTo/this._heightFrom)*this._heightFrom:this._heightFrom;const t=this._gl;this._texture&&t.deleteTexture(this._texture),this._texture=t.createTexture(),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this._width,this._height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST)}}class As{constructor(t){this._capacity=t,this.evict=new l,this._size=0,this._index=0,this._buffer=new Array(this._capacity);for(let t=0;t<this._capacity;t++)this._buffer[t]=null}size(){return this._size}pop(){if(0===this._size)return;const t=this._buffer[this._index];return this._buffer[this._index]=null,this._index=(this._index+1)%this._capacity,this._size--,t}push(t){return this._size===this._capacity&&this.evict.dispatch(this.pop()),this._buffer[(this._index+this._size++)%this._capacity]=t,this}forEach(t){for(let e=0;e<this._size;e++)t(this._buffer[(this._index+e)%this._capacity]);return this}clear(){for(let t=0;t<this._capacity;t++)this._buffer[t]=null;return this._size=0,this._index=0,this}capacity(){return this._capacity}}function Ss(t,e){const s=t.createTexture(),i=t.createFramebuffer();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,64,64,0,t.RGBA,e,null),t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const r=t.checkFramebufferStatus(t.FRAMEBUFFER);return t.deleteFramebuffer(i),t.deleteTexture(s),r===t.FRAMEBUFFER_COMPLETE}function Rs(t){return t.getExtension("WEBGL_color_buffer_float"),!!t.getExtension("OES_texture_float")&&Ss(t,t.FLOAT)}function Fs(t){t.getExtension("EXT_color_buffer_half_float");const e=t.getExtension("OES_texture_half_float");return!!e&&Ss(t,e.HALF_FLOAT_OES)}function Ps(t,e,s){const i=t.getShaderPrecisionFormat(e,s);return!!i&&i.precision>0}class Bs{constructor(t,e={}){this._canvas=t,this._onContextLost=t=>{t.preventDefault(),this._gl=null,this._mainProgram=null,this._vertexCoordinateBuffer=null,this._textureCoordinateBuffer=null,this._sourceTexture=null,this._phosphorProcessor=null,this._ntscProcessor=null,this._integerScalingProcessor=null,this._scanlineProcessor=null,this._processors=[]},this._onContextRestored=()=>{this._getRenderingContext(),this.init()},this._config=null,this._gl=null,this._video=null,this._capabilities=null,this._mainProgram=null,this._vertexCoordinateBuffer=null,this._textureCoordinateBuffer=null,this._sourceTexture=null,this._anmiationFrameHandle=0,this._phosphorProcessor=null,this._ntscProcessor=null,this._scanlineProcessor=null,this._integerScalingProcessor=null,this._processors=[],this._pendingFrames=new As(3),this._consecutiveUnderflows=0,this._hasFrame=!1;this._config=Object.assign(Object.assign({},{gamma:1,scalingMode:"qis",phosphorLevel:.5,scanlineLevel:.2,tvEmulation:"composite"}),e),this._getRenderingContext(),this._canvas.addEventListener("webglcontextlost",this._onContextLost),this._canvas.addEventListener("webglcontextrestored",this._onContextRestored),this._pendingFrames.evict.addHandler(t=>t.release())}init(){return this._gl?(this._phosphorProcessor=new xs(this._gl,this._capabilities),this._ntscProcessor=new Ts(this._gl,this._capabilities),this._scanlineProcessor=new Cs(this._gl,this._capabilities),this._integerScalingProcessor=new ks(this._gl,this._capabilities),this._updateCanvasSize(),this._mainProgram=Es.compile(this._gl,bs.plain.source(this._capabilities),vs.blitWithGamma.source(this._capabilities)),this._mainProgram.use(),this._mainProgram.uniform1i("u_Sampler0",0),this._createVertexCoordinateBuffer(),this._createTextureCoordinateBuffer(),this._configureSourceTexture(),this._applyConfiguration(),this):this}close(){const t=this._gl;if(this._cancelDraw(),this.unbind(),t)return this._mainProgram.delete(),t.deleteBuffer(this._vertexCoordinateBuffer),t.deleteBuffer(this._textureCoordinateBuffer),t.deleteTexture(this._sourceTexture),this._ntscProcessor.destroy(),this._phosphorProcessor.destroy(),this._scanlineProcessor.destroy(),this._integerScalingProcessor.destroy(),this;this._canvas.removeEventListener("webglcontextlost",this._onContextLost),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestored),this._pendingFrames.forEach(t=>t.release())}resize(t,e){return this._updateCanvasSize(t,e),this._updateVertexBuffer(),this._video&&(this._configureProcessors(),this._scheduleDraw()),this._hasFrame&&this._draw(),this}getCanvas(){return this._canvas}bind(t){return this._video||(this._video=t,this._video.newFrame.addHandler(Bs._frameHandler,this),this._configureProcessors(),this._scheduleDraw()),this}unbind(){return this._video?(this._cancelDraw(),this._video.newFrame.removeHandler(Bs._frameHandler,this),this._video=null,this._pendingFrames.forEach(t=>t.release()),this._pendingFrames.clear(),this):this}getConfig(){return this._config}updateConfig(t){return this}static _frameHandler(t,e){e._pendingFrames.size()===e._pendingFrames.capacity()&&(e._pendingFrames.forEach(t=>t.release()),e._pendingFrames.clear()),e._pendingFrames.push(t),e._scheduleDraw()}_getRenderingContext(){const t={alpha:!1,depth:!1,antialias:!1};if(this._gl=this._canvas.getContext("webgl",t)||this._canvas.getContext("experimental-webgl",t),!this._gl)throw new Error("unable to acquire webgl context");this._capabilities=function(t=null){if(!t){const e=document.createElement("canvas");e.width=64,e.height=64,t=e.getContext("webgl")||e.getContext("experimental-webgl")}return t?{floatTextures:Rs(t),halfFloatTextures:Fs(t),highpInFsh:Ps(t,t.FRAGMENT_SHADER,t.HIGH_FLOAT),highpInVsh:Ps(t,t.VERTEX_SHADER,t.HIGH_FLOAT)}:null}(this._gl)}_scheduleDraw(){0===this._anmiationFrameHandle&&(this._anmiationFrameHandle=requestAnimationFrame(()=>this._onAnimationFrame()))}_cancelDraw(){0!==this._anmiationFrameHandle&&cancelAnimationFrame(this._anmiationFrameHandle),this._anmiationFrameHandle=0}_onAnimationFrame(){const t=this._gl;if(this._anmiationFrameHandle=0,0===this._pendingFrames.size())return void(this._consecutiveUnderflows++<=5&&this._scheduleDraw());this._consecutiveUnderflows=0,this._scheduleDraw();const e=this._pendingFrames.pop();t&&(t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._sourceTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e.get()),e.release(),this._hasFrame=!0,this._draw())}_draw(){if(!this._gl)return;const t=this._gl;let e=this._sourceTexture;for(const t of this._processors)t.render(e),e=t.getTexture();t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,"none"===this._config.scalingMode?t.NEAREST:t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,"none"===this._config.scalingMode?t.NEAREST:t.LINEAR),this._mainProgram.use(),this._mainProgram.bindVertexAttribArray("a_VertexPosition",this._vertexCoordinateBuffer,2,t.FLOAT,!1,0,0),this._mainProgram.bindVertexAttribArray("a_TextureCoordinate",this._textureCoordinateBuffer,2,t.FLOAT,!1,0,0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight),t.clearColor(0,0,0,1),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLE_STRIP,0,4)}_createVertexCoordinateBuffer(){if(!this._gl)return;const t=this._gl,e=t.drawingBufferWidth,s=t.drawingBufferHeight,i=e>0?2/e:1,r=s>0?2/s:1;let n,a,o,h;4/3*s<=e?(a=2,n=4/3*s*i,h=1,o=Math.floor(-4/3*s)/2*i):(a=e/(4/3)*r,n=2,h=Math.floor(e/(4/3))/2*r,o=-1);const c=[o+n,h,o,h,o+n,h-a,o,h-a];this._vertexCoordinateBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._vertexCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(c),t.STATIC_DRAW)}_updateVertexBuffer(){this._gl&&(this._gl.deleteBuffer(this._vertexCoordinateBuffer),this._createVertexCoordinateBuffer())}_createTextureCoordinateBuffer(){if(!this._gl)return;const t=this._gl;this._textureCoordinateBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._textureCoordinateBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array([1,1,0,1,1,0,0,0]),t.STATIC_DRAW)}_updateCanvasSize(t,e){void 0!==t&&void 0!==e||(t=this.getCanvas().clientWidth,e=this.getCanvas().clientHeight);const s=window.devicePixelRatio||1;this.getCanvas().width=t*s,this.getCanvas().height=e*s}_configureSourceTexture(){if(!this._gl)return;const t=this._gl;this._sourceTexture||(this._sourceTexture=t.createTexture()),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._sourceTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1)}_configureProcessors(){if(!this._video||!this._gl)return;switch(this._phosphorProcessor.configure(this._config.phosphorLevel),this._scanlineProcessor.configure(this._config.scanlineLevel),this._integerScalingProcessor.configure(this._gl.drawingBufferWidth,this._gl.drawingBufferHeight),this._config.tvEmulation){case"composite":this._ntscProcessor.configure("composite");break;case"svideo":this._ntscProcessor.configure("svideo")}let t=this._video.getWidth(),e=this._video.getHeight();for(const s of this._processors)s.resize(t,e),t=s.getWidth(),e=s.getHeight()}_applyConfiguration(){this._gl&&(this._mainProgram.use(),this._mainProgram.uniform1f("u_Gamma",this._config.gamma),this._processors=[],"none"!==this._config.tvEmulation&&(this._ntscProcessor.init(),this._processors.push(this._ntscProcessor)),this._config.phosphorLevel>0&&(this._phosphorProcessor.init(),this._processors.push(this._phosphorProcessor)),this._config.scanlineLevel>0&&(this._scanlineProcessor.init(),this._processors.push(this._scanlineProcessor)),"qis"===this._config.scalingMode&&(this._integerScalingProcessor.init(),this._processors.push(this._integerScalingProcessor)),this._configureProcessors())}}class Ds{constructor(t){this._cache=t,this._context=null,this._source=null,this._gain=null,this._audio=null,this._volume=0,this._masterVolume=1}init(t,e){this._context=t,this._gain=this._context.createGain(),this._gain.connect(e)}bind(t){this._audio||(this._audio=t,this._volume=this._audio.getVolume(),this._updateGain(),this._audio.volumeChanged.addHandler(Ds._onVolumeChanged,this),this._audio.bufferChanged.addHandler(Ds._onBufferChanged,this),this._audio.stop.addHandler(Ds._onStop,this))}unbind(){this._audio&&(this._audio.volumeChanged.removeHandler(Ds._onVolumeChanged,this),this._audio.bufferChanged.removeHandler(Ds._onBufferChanged,this),this._audio.stop.removeHandler(Ds._onStop,this),this._source&&(this._source.stop(),this._source=null),this._audio=null)}setMasterVolume(t){this._masterVolume=t,this._updateGain()}static _onVolumeChanged(t,e){e._volume=t,e._updateGain()}static _onBufferChanged(t,e){if(!e._cache.has(t)){const s=e._audio.getBuffer(t),i=e._context.createBuffer(1,s.getLength(),s.getSampleRate());i.getChannelData(0).set(s.getContent()),e._cache.set(t,i)}const s=e._cache.get(t),i=e._context.createBufferSource();e._source&&e._source.stop(),i.loop=!0,i.buffer=s,i.connect(e._gain),i.start(),e._source=i}static _onStop(t,e){e._source&&(e._source.stop(),e._source=null)}_updateGain(){this._gain.gain.value=this._volume*this._masterVolume}}class Is{constructor(){this._buffer=new Float32Array(2),this._fractionalIndex=0,this._needsData=!1,this._ratio=0,this.reset(1,1)}reset(t,e){this._ratio=t/e,this._needsData=!1,this._fractionalIndex=0;for(let t=0;t<2;t++)this._buffer[t]=0}get(){const t=(1-this._fractionalIndex)*this._buffer[0]+this._fractionalIndex*this._buffer[1];return this._fractionalIndex+=this._ratio,this._fractionalIndex>1&&(this._fractionalIndex-=1,this._needsData=!0),t}push(t){this._buffer[0]=this._buffer[1],this._buffer[1]=t,this._needsData=!1}needsData(){return this._needsData}}class Ms{constructor(t=1024){this._hostFragmentSize=t,this._outputSampleRate=0,this._bufferSize=0,this._volume=1,this._gain=null,this._processor=null,this._bufferUnderrun=!1,this._fragmentRing=null,this._fragmentSize=0,this._inputSampleRate=0,this._fragmentIndex=0,this._currentFragment=null,this._lastFragment=null,this._resampler=new Is}init(t,e){this._outputSampleRate=t.sampleRate,this._gain=t.createGain(),this._gain.gain.value=this._volume,this._gain.connect(e),this._processor=t.createScriptProcessor(this._hostFragmentSize,1,1),this._bufferSize=this._processor.bufferSize,this._processor.connect(this._gain),this._processor.onaudioprocess=t=>this._processAudio(t);t.createBuffer(1,1,t.sampleRate).getChannelData(0).set([0])}bind(t){this.unbind(),this._audio=t,this._fragmentSize=t.getFrameSize(),this._inputSampleRate=t.getSampleRate(),this._fragmentIndex=0,this._lastFragment=null,this._bufferUnderrun=!0,this._fragmentRing=new As(Math.ceil(4*this._bufferSize/this._outputSampleRate/this._fragmentSize*this._inputSampleRate)),this._fragmentRing.evict.addHandler(t=>t.release()),this._audio.newFrame.addHandler(Ms._onNewFragment,this),this._resampler.reset(this._inputSampleRate,this._outputSampleRate)}unbind(){this._audio&&(this._audio.newFrame.removeHandler(Ms._onNewFragment,this),this._lastFragment&&(this._lastFragment.release(),this._lastFragment=null),this._currentFragment&&(this._currentFragment.release(),this._currentFragment=null),this._fragmentRing&&(this._fragmentRing.forEach(t=>t.release()),this._fragmentRing.clear(),this._fragmentRing=null))}setMasterVolume(t){this._volume=t}static _onNewFragment(t,e){e._fragmentRing.push(t),e._currentFragment||(e._currentFragment=e._fragmentRing.pop(),e._fragmentIndex=0)}_processAudio(t){if(!this._audio)return;const e=t.outputBuffer.getChannelData(0);let s=0;const i=t=>{const i=this._lastFragment&&this._lastFragment.get();for(;s<t;)this._resampler.needsData()&&(this._resampler.push(this._audio&&this._audio.isPaused()||!i?0:i[this._fragmentIndex++]*this._volume),this._fragmentIndex>=this._fragmentSize&&(this._fragmentIndex=0)),e[s++]=this._resampler.get()};this._currentFragment&&this._bufferUnderrun&&(i(this._bufferSize>>>1),this._bufferUnderrun=!1);let r=this._currentFragment&&this._currentFragment.get();for(;s<this._bufferSize&&this._currentFragment;)this._resampler.needsData()&&(this._resampler.push(r[this._fragmentIndex++]*this._volume),this._fragmentIndex>=this._fragmentSize&&(this._fragmentIndex=0,this._lastFragment&&this._lastFragment.release(),this._lastFragment=this._currentFragment,this._currentFragment=this._fragmentRing.pop(),r=this._currentFragment&&this._currentFragment.get())),e[s++]=this._resampler.get();s<this._bufferSize&&(this._bufferUnderrun=!0),i(this._bufferSize)}}const Os="safari"in window,Ls=!!navigator.platform.match(/iPhone|iPad|iPod/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,Us=Ls||Os,js=["touchstart","click","keydown"],Hs=window.AudioContext||window.webkitAudioContext;function zs(t,e=500){return new Promise(s=>{t.then(()=>s()),setTimeout(s,e)})}class Xs{constructor(){if(this._interactionListener=()=>{const t=this.context;this.interactionRequired=!1,js.forEach(t=>document.removeEventListener(t,this._interactionListener)),this.mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){return yield zs(t.resume()),new Promise(e=>setTimeout(()=>s(this,void 0,void 0,(function*(){yield zs(t.suspend()),e()})),100))})))},this.mutex=new n,this.context=null,this.interactionRequired=!0,Hs){this.context=new Hs;try{this.context.destination.channelCount=1}catch(t){console.warn("audio driver: failed to set channel count")}js.forEach(t=>document.addEventListener(t,this._interactionListener))}}stopListening(){js.forEach(t=>document.removeEventListener(t,this._interactionListener))}}let Vs=Us?new Xs:null;class qs{constructor(t=0,e=0,s){this._touchListener=()=>{js.forEach(t=>document.removeEventListener(t,this._touchListener,!0)),this._context&&(this._context.resume(),setTimeout(()=>{this._mutex.runExclusive(()=>this._suspended?this._context.suspend():this._context.resume())},10))},this._context=null,this._merger=null,this._waveformChannels=null,this._pcmChannels=null,this._channels=null,this._cache=new Map,this._mutex=new n,this._suspended=!0,this._isBound=!1,this._waveformChannels=new Array(t),this._pcmChannels=new Array(e);for(let e=0;e<t;e++)this._waveformChannels[e]=new Ds(this._cache);for(let t=0;t<e;t++)this._pcmChannels[t]=new Ms(s);this._channels=[...this._waveformChannels,...this._pcmChannels]}init(){if(Vs){const t=Vs;Vs=new Xs,this._context=t.context,t.stopListening(),this._mutex=t.mutex,t.interactionRequired&&js.forEach(t=>document.addEventListener(t,this._touchListener,!0))}else{if(!Hs)throw new Error("web audio is not supported by runtime");this._context=new Hs;try{this._context.destination.channelCount=1}catch(t){console.warn("audio driver: failed to set channel count")}}this._merger=this._context.createChannelMerger(this._channels.length),this._merger.connect(this._context.destination),this._channels.forEach(t=>t.init(this._context,this._merger))}bind(t=[],e=[]){if(!this._isBound){if(t.length!==this._waveformChannels.length)throw new Error(`invalid number of waveform sources: expected ${this._waveformChannels.length}, got ${t.length}`);if(e.length!==this._pcmChannels.length)throw new Error(`invalid number of waveform sources: expected ${this._pcmChannels.length}, got ${e.length}`);this._waveformChannels.forEach((e,s)=>e.bind(t[s])),this._pcmChannels.forEach((t,s)=>t.bind(e[s])),this._isBound=!0,this.resume()}}unbind(){this._isBound&&(this._channels.forEach(t=>t.unbind()),this._isBound=!1,this.pause())}setMasterVolume(t,e){this._channels[t].setMasterVolume(e)}pause(){return this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){this._suspended||(this._suspended=!0,yield zs(this._context.suspend()))})))}resume(){return this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){this._suspended&&(this._suspended=!1,yield zs(this._context.resume()))})))}close(){this._mutex.runExclusive(()=>this._context.close())}}class Gs{constructor(t){this._fragmentSize=t,this._pcmAudio=!1,this._volume=1}init(){}bind(t,e){if(!this._channels){this._channels=[...e],this._driver&&this._pcmAudio===t||(this._driver&&this._driver.close(),this._driver=t?new qs(0,this._channels.length,this._fragmentSize):new qs(this._channels.length,0,this._fragmentSize),this._driver.init()),t?this._driver.bind([],this._channels):this._driver.bind(this._channels,[]);for(let t=0;t<this._channels.length;t++)this._driver.setMasterVolume(t,this._volume);this._pcmAudio=t}}unbind(){this._channels&&(this._driver.unbind(),this._channels=null)}setMasterVolume(t){if(this._volume=t,this._channels)for(let t=0;t<this._channels.length;t++)this._driver.setMasterVolume(t,this._volume)}getMasterVolume(){return this._volume}pause(){return s(this,void 0,void 0,(function*(){this._driver&&(yield this._driver.pause())}))}resume(){return s(this,void 0,void 0,(function*(){this._driver&&(yield this._driver.resume())}))}}function Qs(t){return{type:0,swtch:t}}function Ns(t){return{type:1,trigger:t}}class Ws{constructor(t,e=Ws.defaultMappings){this._target=t,this.toggleFullscreen=new l,this.hardReset=new l,this.togglePause=new l,this._keydownListener=null,this._keyupListener=null,this._joystick0=null,this._joystick1=null,this._controlPanel=null,this._dispatchTable={},this._compiledMappings=new Map,this._compileMappings(e)}bind(t,e,s){this._joystick0||(this._joystick0=t,this._joystick1=e,this._controlPanel=s,this._updateActionTable(),this._keydownListener=t=>{if(!this._compiledMappings.has(t.keyCode))return;const e=(t.shiftKey?4:0)|(t.ctrlKey?1:0)|(t.altKey?2:0);if(!this._compiledMappings.get(t.keyCode).has(e))return;const s=this._compiledMappings.get(t.keyCode).get(e);if(void 0!==s){t.preventDefault();const e=this._dispatchTable[s];switch(e.type){case 0:e.swtch.toggle(!0);break;case 1:e.trigger.dispatch(void 0)}}},this._keyupListener=t=>{if(this._compiledMappings.has(t.keyCode))for(const e of this._compiledMappings.get(t.keyCode).values()){t.preventDefault();const s=this._dispatchTable[e];switch(s.type){case 0:s.swtch.toggle(!1)}}},this._target.addEventListener("keydown",this._keydownListener),this._target.addEventListener("keyup",this._keyupListener))}unbind(){this._joystick0&&(this._target.removeEventListener("keydown",this._keydownListener),this._target.removeEventListener("keyup",this._keyupListener),this._joystick0=this._joystick1=this._controlPanel=null,this._keydownListener=this._keyupListener=null)}_updateActionTable(){this._dispatchTable[12]=Ns(this.toggleFullscreen),this._dispatchTable[13]=Ns(this.hardReset),this._dispatchTable[14]=Ns(this.togglePause),this._dispatchTable[0]=Qs(this._controlPanel.getSelectSwitch()),this._dispatchTable[1]=Qs(this._controlPanel.getResetButton()),this._dispatchTable[2]=Qs(this._joystick0.getLeft()),this._dispatchTable[3]=Qs(this._joystick0.getRight()),this._dispatchTable[4]=Qs(this._joystick0.getUp()),this._dispatchTable[5]=Qs(this._joystick0.getDown()),this._dispatchTable[10]=Qs(this._joystick0.getFire()),this._dispatchTable[6]=Qs(this._joystick1.getLeft()),this._dispatchTable[7]=Qs(this._joystick1.getRight()),this._dispatchTable[8]=Qs(this._joystick1.getUp()),this._dispatchTable[9]=Qs(this._joystick1.getDown()),this._dispatchTable[11]=Qs(this._joystick1.getFire())}_compileMappings(t){const e=(t,e,s)=>{if(0!=(-8&s))throw new Error("invalid modifier set "+s);this._compiledMappings.has(e)||this._compiledMappings.set(e,new Map),this._compiledMappings.get(e).set(s,t)};t.forEach(t=>{const s=t.action;(Array.isArray(t.spec)?t.spec:[t.spec]).forEach(t=>e(s,"object"==typeof t?t.keycode:t,"object"==typeof t?t.modifiers:0))})}}!function(t){t.defaultMappings=[{action:0,spec:{keycode:32,modifiers:4}},{action:1,spec:{keycode:13,modifiers:4}},{action:2,spec:[65,37]},{action:3,spec:[68,39]},{action:4,spec:[87,38]},{action:5,spec:[83,40]},{action:10,spec:[32,86]},{action:6,spec:74},{action:7,spec:76},{action:8,spec:73},{action:9,spec:75},{action:11,spec:66},{action:12,spec:13},{action:13,spec:{keycode:82,modifiers:4}},{action:14,spec:80}]}(Ws||(Ws={}));class Ys{constructor(t=500,e=200){this._maxTapLength=t,this._timeout=e,this.trigger=new l,this._dispatch=!1,this._touching=!1,this._lastTouchEligible=!1,this._lastTouchStart=0,this._lastTouchEnd=0}startTouch(){this._lastTouchStart=Date.now(),this._touching||(this._touching=!0,this._dispatch=this._lastTouchEligible&&this._lastTouchStart-this._lastTouchEnd<this._timeout)}endTouch(){this._lastTouchEnd=Date.now(),this._dispatch&&(this._dispatch=!1,this.trigger.dispatch(void 0)),this._touching&&(this._touching=!1,this._lastTouchEligible=this._lastTouchStart-this._lastTouchEnd<this._maxTapLength)}cancelTouch(){this.endTouch(),this._lastTouchEligible=!1}isDispatching(){return this._dispatch}}class $s{constructor(t,e=15,s=!1){this._canvas=t,this._joystickSensitivity=e,this._leftHanded=s,this._onTouchStart=t=>{for(let e=0;e<t.changedTouches.length;e++){const s=new Ks(t.changedTouches.item(e),this._canvas),i=s.touch.identifier;if((this._leftHanded?s.x>.5:s.x<=.5)?s.y<=.5?s.type="alt":s.type=this._isAlt?"pause":"fire":s.y<=.5?s.type=this._isAlt?"select":"joystick":s.type=this._isAlt?"reset":"joystick",!this._pendingTouches.has(i)&&!this._pendingTouches.has(s.type))switch(this._pendingTouches.set(i,s),this._pendingTouches.set(s.type,s),s.type){case"alt":this._isAlt=!0,this._fullscreenDoubleTapDetector.startTouch();break;case"fire":this._joystick.getFire().toggle(!0);break;case"pause":this.togglePause.dispatch(void 0),this._fullscreenDoubleTapDetector.cancelTouch();break;case"select":this._select.toggle(!0),this._fullscreenDoubleTapDetector.cancelTouch();break;case"reset":this._reset.toggle(!0),this._fullscreenDoubleTapDetector.cancelTouch();break;case"joystick":break;default:throw new Error("invalid touch type")}}t.preventDefault()},this._onTouchEnd=t=>{for(let e=0;e<t.changedTouches.length;e++){const s=this._pendingTouches.get(t.changedTouches.item(e).identifier);if(s){switch(s.type){case"alt":this._isAlt=!1,this._fullscreenDoubleTapDetector.endTouch();break;case"fire":this._joystick.getFire().toggle(!1);break;case"select":this._select.toggle(!1);break;case"reset":this._reset.toggle(!1);break;case"joystick":this._joystick.getDown().toggle(!1),this._joystick.getUp().toggle(!1),this._joystick.getLeft().toggle(!1),this._joystick.getRight().toggle(!1);break;case"pause":break;default:throw new Error("invalid touch type")}this._pendingTouches.delete(s.type),this._pendingTouches.delete(s.touch.identifier)}}t.preventDefault()},this._onTouchMove=t=>{for(let e=0;e<t.changedTouches.length;e++){const s=t.changedTouches.item(e),i=this._pendingTouches.get(s.identifier);if(!i)continue;if("joystick"!==i.type)continue;const r=s.clientX-i.x0,n=s.clientY-i.y0,a=Math.sqrt(r*r+n*n),o=Math.abs(n/a),h=Math.abs(r/a),c=a>this._joystickSensitivity;this._joystick.getLeft().toggle(c&&r<0&&h>.5),this._joystick.getRight().toggle(c&&r>0&&h>.5),this._joystick.getUp().toggle(c&&n<0&&o>.5),this._joystick.getDown().toggle(c&&n>0&&o>.5),a>3*this._joystickSensitivity&&(i.x0+=r/a*(a-3*this._joystickSensitivity),i.y0+=n/a*(a-3*this._joystickSensitivity))}t.preventDefault()},this.togglePause=new l,this._fullscreenDoubleTapDetector=new Ys,this._bound=!1,this._joystick=null,this._select=null,this._reset=null,this._isAlt=!1,this._pendingTouches=new Map,this.toggleFullscreen=this._fullscreenDoubleTapDetector.trigger}static isSupported(){return"ontouchstart"in window}bind(t,e){this._bound||(this._bound=!0,this._joystick=t,this._select=e.getSelectSwitch(),this._reset=e.getResetButton(),this._bindListeners())}unbind(){this._bound&&(this._unbindListeners(),this._bound=!1,this._joystick=this._reset=this._select=null)}_bindListeners(){this._canvas.addEventListener("touchstart",this._onTouchStart),this._canvas.addEventListener("touchend",this._onTouchEnd),this._canvas.addEventListener("touchmove",this._onTouchMove)}_unbindListeners(){this._canvas.removeEventListener("touchstart",this._onTouchStart),this._canvas.removeEventListener("touchend",this._onTouchEnd),this._canvas.removeEventListener("touchmove",this._onTouchMove)}}class Ks{constructor(t,e){this.touch=t,this.type="unknown";const s=e.getBoundingClientRect();this.x=(t.clientX-s.left)/s.width,this.y=(t.clientY-s.top)/s.height,this.x0=t.clientX,this.y0=t.clientY}}class Js{constructor(){this._x=-1,this._listener=this._onDocumentMouseMove.bind(this)}bind(t){this._paddle||(this._paddle=t,this._x=-1,document.addEventListener("mousemove",this._listener))}unbind(){this._paddle&&(document.removeEventListener("mousemove",this._listener),this._paddle=null)}_onDocumentMouseMove(t){if(this._x>=0){const e=t.screenX-this._x;let s=this._paddle.getValue();s+=-e/window.innerWidth/.9,s<0&&(s=0),s>1&&(s=1),this._paddle.setValue(s)}this._x=t.screenX}}class Zs{constructor(){this._state=!1,this._dirty=!1}toggle(t){t!==this._state&&(this._state=t,this._dirty=!0)}setState(t){this._state=t,this._dirty=!1}sync(t){this._dirty&&(t.toggle(this._state),this._dirty=!1)}}function ti(t,e){return{type:"button",index:t,target:e}}function ei(t,e,s){return{type:"axis",index:t,sign:e,target:s}}const si=[ti(12,"up"),ti(13,"down"),ti(14,"left"),ti(15,"right"),ti(8,"select"),ti(9,"start"),...[0,1,2,3,10,11].map(t=>ti(t,"fire")),...[4,5,6,7].map(t=>ti(t,"pause")),ei(0,"negative","left"),ei(0,"positive","right"),ei(1,"negative","up"),ei(1,"positive","down"),ei(2,"negative","left"),ei(2,"positive","right"),ei(3,"negative","up"),ei(3,"positive","down")];function ii(t){return"object"==typeof t?t.pressed:t>.5}class ri{constructor(){this._onGamepadConnect=()=>this.probeGamepads(),this._onGamepadDisconnect=()=>this.probeGamepads(),this.gamepadCountChanged=new l,this._shadows=null,this._mappings=new Map,this._mappingStates=new WeakMap,this._mappingTargets=new WeakMap,this._bound=!1,this._joysticks=[],this._auxSwitches={},this._gamepadCount=0,this._lastPoll=0,this.setMapping(si)}static probeGamepadCount(){let t=0;const e=navigator.getGamepads();for(let s=0;s<e.length;s++)e[s]&&t++;return t}init(){if(!navigator.getGamepads)throw new Error("gamepad API not available");this.probeGamepads(),window.addEventListener("gamepadconnected",this._onGamepadConnect),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnect)}deinit(){this.unbind(),window.removeEventListener("gamepadconnected",this._onGamepadConnect),window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnect)}bind(t=[],e={}){this._bound||(this._bound=!0,this._joysticks=t,this._auxSwitches=e,this._bound=!0,this._shadows=new WeakMap,this._controlledSwitches().forEach(t=>{const e=new Zs;this._shadows.set(t,e),e.setState(t.read()),t.beforeRead.addHandler(ri._onBeforeSwitchRead,this)}))}unbind(){this._bound&&(this._controlledSwitches().forEach(t=>t.beforeRead.removeHandler(ri._onBeforeSwitchRead,this)),this._shadows=null,this._auxSwitches={},this._joysticks=[],this._bound=!1)}getGamepadCount(){return this._gamepadCount}setMapping(t,e){void 0!==e&&this._mappings.set(e,t);const s=new Map,i=[];for(const e of t)i.indexOf(e.target)&&(i.push(e.target),s.set(e.target,!1));this._mappingStates.set(t,s),this._mappingTargets.set(t,i)}clearMapping(t){this._mappings.delete(t)}poll(){this._readGamepads()}static _onBeforeSwitchRead(t,e){e.poll()}probeGamepads(){const t=ri.probeGamepadCount();t!==this._gamepadCount&&(this._gamepadCount=t,this.gamepadCountChanged.dispatch(this._gamepadCount))}_getSwitchForTarget(t,e=null){if(this._auxSwitches[t])return this._auxSwitches[t];if(!e)return null;switch(t){case"up":return e.getUp();case"down":return e.getDown();case"left":return e.getLeft();case"right":return e.getRight();case"fire":return e.getFire();default:return null}}_controlledSwitches(){const t=[...Object.keys(this._auxSwitches).map(t=>this._auxSwitches[t])];for(const e of this._joysticks)t.push(e.getLeft(),e.getRight(),e.getUp(),e.getDown(),e.getFire());return t}_readGamepads(){const t=Date.now();if(0===this._gamepadCount||t-this._lastPoll<50)return;this._lastPoll=t;const e=navigator.getGamepads();let s=0;for(let t=0;t<e.length;t++){const i=e[t];if(!i)continue;const r=this._mappings.get(i.id)||si,n=this._mappingStates.get(r),a=this._mappingTargets.get(r);for(const t of a)n.set(t,!1);for(const t of r)switch(t.type){case"button":const e=i.buttons[t.index];void 0!==e&&ii(e)&&n.set(t.target,!0);break;case"axis":const s=i.axes[t.index];void 0!==s&&("positive"===t.sign?s>.5:s<-.5)&&n.set(t.target,!0)}for(const t of a){const e=this._getSwitchForTarget(t,this._joysticks[s]);if(!e)continue;const i=this._shadows.get(e);i.toggle(n.get(t)),i.sync(e)}s++}}}var ni=o((function(t){
/*!
* screenfull
* v5.0.2 - 2020-02-13
* (c) Sindre Sorhus; MIT License
*/
!function(){var e="undefined"!=typeof window&&void 0!==window.document?window.document:{},s=t.exports,i=function(){for(var t,s=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],i=0,r=s.length,n={};i<r;i++)if((t=s[i])&&t[1]in e){for(i=0;i<t.length;i++)n[s[0][i]]=t[i];return n}return!1}(),r={change:i.fullscreenchange,error:i.fullscreenerror},n={request:function(t){return new Promise(function(s,r){var n=function(){this.off("change",n),s()}.bind(this);this.on("change",n);var a=(t=t||e.documentElement)[i.requestFullscreen]();a instanceof Promise&&a.then(n).catch(r)}.bind(this))},exit:function(){return new Promise(function(t,s){if(this.isFullscreen){var r=function(){this.off("change",r),t()}.bind(this);this.on("change",r);var n=e[i.exitFullscreen]();n instanceof Promise&&n.then(r).catch(s)}else t()}.bind(this))},toggle:function(t){return this.isFullscreen?this.exit():this.request(t)},onchange:function(t){this.on("change",t)},onerror:function(t){this.on("error",t)},on:function(t,s){var i=r[t];i&&e.addEventListener(i,s,!1)},off:function(t,s){var i=r[t];i&&e.removeEventListener(i,s,!1)},raw:i};i?(Object.defineProperties(n,{isFullscreen:{get:function(){return Boolean(e[i.fullscreenElement])}},element:{enumerable:!0,get:function(){return e[i.fullscreenElement]}},isEnabled:{enumerable:!0,get:function(){return Boolean(e[i.fullscreenEnabled])}}}),s?t.exports=n:window.screenfull=n):s?t.exports={isEnabled:!1}:window.screenfull={isEnabled:!1}}()}));ni.isEnabled;const ai=Ls,oi=ni;class hi{constructor(t,e=1e5,s="stellerator-fullscreen"){this._videoDriver=t,this._zIndex=e,this._fullscreenClass=s,this._resizeListener=()=>{this._resizeHandle||(this._resizeHandle=setTimeout(()=>{this._resizeHandle=null,this._adjustSizeForFullscreen()},100))},this._resizeHandle=null,this._changeListener=this._onChange.bind(this),this._engaged=!1}engage(){this._engaged||(this._engaged=!0,ai||!oi?(this._adjustSizeForFullscreen(),window.addEventListener("resize",this._resizeListener),this._engaged=!0):(oi.on("change",this._changeListener),oi.request(this._videoDriver.getCanvas())))}disengage(){this._engaged&&(ai||!oi?(this._resetSize(),window.removeEventListener("resize",this._resizeListener),this._engaged=!1):oi.exit())}toggle(){this._engaged?this.disengage():this.engage()}isEngaged(){return this._engaged}_onChange(){oi&&(oi.isFullscreen?(window.addEventListener("resize",this._resizeListener),this._adjustSizeForFullscreen()):(this._resetSize(),window.removeEventListener("resize",this._resizeListener),oi.off("change",this._changeListener),this._engaged=!1))}_resetSize(){const t=this._videoDriver.getCanvas();this._resizeHandle&&(clearTimeout(this._resizeHandle),this._resizeHandle=null),t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",ai&&(t.style.position="",t.style.top="",t.style.left="",t.style.zIndex=""),document.body.classList.remove(this._fullscreenClass),setTimeout(()=>this._videoDriver.resize(),0)}_adjustSizeForFullscreen(){const t=this._videoDriver.getCanvas();this._videoDriver.resize(window.innerWidth,window.innerHeight),t.style.width=window.innerWidth+"px",t.style.height=window.innerHeight+"px",t.style.maxWidth=window.innerWidth+"px",t.style.maxHeight=window.innerHeight+"px",ai&&(t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.zIndex=""+this._zIndex),document.body.classList.add(this._fullscreenClass)}}var ci;!function(t){let e;!function(t){t.vanilla_2k="vanilla_2k",t.vanilla_4k="vanilla_4k",t.bankswitch_2k_cv="bankswitch_2k_cv",t.bankswitch_8k_F8="bankswitch_8k_F8",t.bankswitch_8k_E0="bankswitch_8k_E0",t.bankswitch_8k_3F="bankswitch_8k_3F",t.bankswitch_8k_FE="bankswitch_8k_FE",t.bankswitch_8k_UA="bankswitch_8k_UA",t.bankswitch_8k_DPC="bankswitch_8k_DPC",t.bankswitch_8k_econobanking="bankswitch_8k_econobanking",t.bankswitch_8k_pp="bankswitch_8k_pp",t.bankswitch_12k_FA="bankswitch_12k_FA",t.bankswitch_16k_F6="bankswitch_16k_F6",t.bankswitch_16k_E7="bankswitch_16k_E7",t.bankswitch_FA2="bankswitch_FA2",t.bankswitch_32k_F4="bankswitch_32k_F4",t.bankswitch_64k_F0="bankswitch_64k_F0",t.bankswitch_64k_EF="bankswitch_64k_EF",t.bankswitch_3E="bankswitch_3E",t.bankswitch_supercharger="bankswitch_supercharger",t.bankswitch_dpc_plus="bankswitch_dpc_plus",t.bankswitch_cdf="bankswitch_cdf",t.unknown="unknown"}(e=t.CartridgeType||(t.CartridgeType={})),t.getAllTypes=function(){return[e.vanilla_2k,e.vanilla_4k,e.bankswitch_2k_cv,e.bankswitch_8k_F8,e.bankswitch_8k_E0,e.bankswitch_8k_3F,e.bankswitch_8k_FE,e.bankswitch_8k_UA,e.bankswitch_8k_econobanking,e.bankswitch_8k_pp,e.bankswitch_12k_FA,e.bankswitch_8k_DPC,e.bankswitch_16k_F6,e.bankswitch_16k_E7,e.bankswitch_FA2,e.bankswitch_32k_F4,e.bankswitch_3E,e.bankswitch_64k_F0,e.bankswitch_64k_EF,e.bankswitch_supercharger,e.bankswitch_dpc_plus,e.bankswitch_cdf,e.unknown]},t.describeCartridgeType=function(t){switch(t){case e.vanilla_2k:return"plain 2k";case e.vanilla_4k:return"plain 4k";case e.bankswitch_2k_cv:return"2k CommaVideo scheme";case e.bankswitch_8k_F8:return"bankswitched 8k, F8 (Atari) scheme";case e.bankswitch_8k_E0:return"bankswitched 8k, E0 (Parker Bros.) scheme";case e.bankswitch_8k_3F:return"bankswitched 8k, 3F (Tigervision) scheme";case e.bankswitch_8k_FE:return"bankswitched 8k, FE (Activision) scheme";case e.bankswitch_8k_UA:return"bankswitched 8k, UA (Pleiades) scheme";case e.bankswitch_8k_pp:return"bankswitched 8k, Pink Panther scheme";case e.bankswitch_12k_FA:return"bankswitched 12k, FA (CBS) scheme";case e.bankswitch_8k_DPC:return"bankswitched 8k + DPC";case e.bankswitch_8k_econobanking:return"bankswitched 8k, econobanking scheme";case e.bankswitch_16k_F6:return"bankswitched 16k, F6 (Atari) scheme";case e.bankswitch_16k_E7:return"bankswitched 16k, E7 (M-Network) scheme";case e.bankswitch_FA2:return"bankswitched 28k/29k, FA2 (modified CBS) scheme";case e.bankswitch_32k_F4:return"bankswitched 32k, F4 (Atari) scheme";case e.bankswitch_3E:return"bankswitched 3E (Tigervision + RAM) scheme";case e.bankswitch_64k_F0:return"bankswitched 64k, F0 (Megaboy) scheme";case e.bankswitch_64k_EF:return"bankswitched 64k, EFSC (Homestar Runner) scheme";case e.bankswitch_supercharger:return"bankswitched supercharger";case e.bankswitch_dpc_plus:return"bankswitched DPC+";case e.bankswitch_cdf:return"bankswitched CDF";case e.unknown:return"unknown"}}}(ci||(ci={}));class _i{constructor(){this.stateChange=new l,this._state=!1,this._boundSwitch=null}bind(t){this.unbind(),this._boundSwitch=t,this._boundSwitch.toggle(this._state),this._boundSwitch.stateChanged.addHandler(_i._onBoundStateChange,this),this._setState(this._boundSwitch.read())}unbind(){this._boundSwitch&&(this._boundSwitch.stateChanged.removeHandler(_i._onBoundStateChange,this),this._boundSwitch=null)}toggle(t){return this._boundSwitch?this._boundSwitch.toggle(t):this._setState(t),this}read(){return this._state}static _onBoundStateChange(t,e){e._setState(t)}_setState(t){t!==this._state&&(this._state=t,this.stateChange.dispatch(this._state))}}class li{constructor(){this._reset=new _i,this._select=new _i,this._difficultyPlayer1=new _i,this._difficultyPlayer2=new _i,this._color=new _i,this._boundControlPanel=null}bind(t){this.unbind(),this._boundControlPanel=t,this._reset.bind(this._boundControlPanel.getResetButton()),this._select.bind(this._boundControlPanel.getSelectSwitch()),this._difficultyPlayer1.bind(this._boundControlPanel.getDifficultySwitchP0()),this._difficultyPlayer2.bind(this._boundControlPanel.getDifficultySwitchP1()),this._color.bind(this._boundControlPanel.getColorSwitch()),this._difficultyPlayer1.toggle(!0),this._difficultyPlayer2.toggle(!0)}unbind(){this._boundControlPanel&&(this._reset.unbind(),this._select.unbind(),this._difficultyPlayer1.unbind(),this._difficultyPlayer2.unbind(),this._color.unbind(),this._boundControlPanel=null)}reset(){return this._reset}select(){return this._select}difficultyPlayer1(){return this._difficultyPlayer1}difficultyPlayer2(){return this._difficultyPlayer2}color(){return this._color}}class ui{constructor(){this.message=new l,this._io=null}bind(t){this._io||(t&&t.message.addHandler(ui._onAsyncIOMessage,this),this._io=t)}unbind(){this._io&&(this._io.message.removeHandler(ui._onAsyncIOMessage,this),this._io=null)}send(t){this._io&&this._io.send(t)}static _onAsyncIOMessage(t,e){e.message.dispatch(t)}}class di{constructor(t=null,e,s={}){this._pauseHandler=()=>{switch(this._emulationService.getState()){case _.State.paused:this.resume();break;case _.State.running:this.pause()}},this._canvasElt=null,this._config=null,this._emulationService=null,this._serviceInitialized=null,this._videoDriver=null,this._fullscreenVideo=null,this._audioDriver=null,this._keyboardIO=null,this._asyncIO=null,this._touchIO=null,this._paddle=null,this._gamepad=null,this._controlPanel=new li,this._state=di.State.stopped,this._driverManager=new ms,this._mutex=new n,this._canvasElt=t,this._config=Object.assign({gamma:1,scalingMode:di.ScalingMode.qis,tvEmulation:di.TvEmulation.composite,phosphorLevel:.5,scanlineLevel:.2,audio:!0,volume:.5,enableKeyboard:!0,enableTouch:!0,touchLeftHanded:!1,touchJoystickSensitivity:15,keyboardTarget:document,fullscreenViaKeyboard:!0,paddleViaMouse:!0,pauseViaKeyboard:!0,pauseViaTouch:!0,fullscreenViaTouch:!0,enableGamepad:!0,resetViaKeyboard:!0},s),this._emulationService=new fs(e),this.frequencyUpdate=this._emulationService.frequencyUpdate;const i=new l;this._emulationService.stateChanged.addHandler(t=>i.dispatch(this._mapState(t))),this.stateChange=i,this._createDrivers(),this._driverManager.addDriver(this._controlPanel,t=>this._controlPanel.bind(t.getControlPanel())),this._driverManager.bind(this._emulationService),this._serviceInitialized=this._emulationService.init().then(void 0,t=>{throw console.log(t),t})}setGamma(t){return this._config.gamma=t,this._createVideoDriver(),this}getGamma(){return this._config.gamma}setScalingMode(t){return this._config.scalingMode=t,this._createVideoDriver(),this}getScalingMode(){return this._config.scalingMode}setTvEmulation(t){return this._config.tvEmulation=t,this._createVideoDriver(),this}getTvEmulation(){return this._config.tvEmulation}setPhosphorLevel(t){return this._config.phosphorLevel=t,this._createVideoDriver(),this}getPhosphorLevel(){return this._config.phosphorLevel}setScanlineLevel(t){return this._config.scanlineLevel=t,this._createVideoDriver(),this}getScanlineLevel(){return this._config.scanlineLevel}toggleFullscreen(t){return this._fullscreenVideo?(void 0===t?this._fullscreenVideo.toggle():t?this._fullscreenVideo.engage():this._fullscreenVideo.disengage(),this):this}isFullscreen(){return!!this._fullscreenVideo&&this._fullscreenVideo.isEngaged()}setVolume(t){return this._audioDriver&&this._audioDriver.setMasterVolume(Math.max(Math.min(t,1),0)),this}audioEnabled(){return!!this._audioDriver}getVolume(){return this._audioDriver?this._audioDriver.getMasterVolume():0}resize(){return this._videoDriver&&this._videoDriver.resize(),this}getState(){return this._state}getControlPanel(){return this._controlPanel}setCanvas(t){return this._canvasElt=t,this._createVideoDriver(),this._createTouchDriver(),this}releaseCanvas(){return this._removeVideoDriver(),this._removeTouchDriver(),this._canvasElt=null,this}start(t,e,i={}){return this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){"string"==typeof t&&(t=ss(t));const s=$e.create({tvMode:this._convertTvMode(e),pcmAudio:!0});return void 0!==i.randomSeed&&i.randomSeed>0&&(s.randomSeed=i.randomSeed),void 0!==i.emulatePaddles&&(s.emulatePaddles=i.emulatePaddles),void 0!==i.frameStart&&(s.frameStart=i.frameStart),s.cpuType=function(t=di.CpuAccuracy.cycle){switch(t){case di.CpuAccuracy.cycle:return Ke.Type.stateMachine;case di.CpuAccuracy.instruction:return Ke.Type.batchedAccess;default:throw new Error("invalid CPU Accuracy: "+t)}}(i.cpuAccuracy),yield this._serviceInitialized,this._state=this._mapState(yield this._emulationService.start(t,Object.assign(Object.assign({},s),{asyncIO:i.asyncIO}),i.cartridgeType))})))}run(t,e,i={}){return s(this,void 0,void 0,(function*(){if((yield this.start(t,e,i))===di.State.paused)return this.resume()}))}pause(){return s(this,void 0,void 0,(function*(){return yield this._serviceInitialized,this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){return this._state=this._mapState(yield this._emulationService.pause())})))}))}resume(){return s(this,void 0,void 0,(function*(){return yield this._serviceInitialized,this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){return this._state=this._mapState(yield this._emulationService.resume())})))}))}stop(){return s(this,void 0,void 0,(function*(){return yield this._serviceInitialized,this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){return this._state=this._mapState(yield this._emulationService.stop())})))}))}reset(){return s(this,void 0,void 0,(function*(){return yield this._serviceInitialized,this._mutex.runExclusive(()=>s(this,void 0,void 0,(function*(){return this._state=this._mapState(yield this._emulationService.reset())})))}))}lastError(){return this._emulationService.getLastError()}asyncIOSend(t){return this._asyncIO.send(t),this}_convertTvMode(t){switch(t){case di.TvMode.ntsc:return 0;case di.TvMode.pal:return 1;case di.TvMode.secam:return 2;default:throw new Error(`invalid TV mode '${t}'`)}}_createDrivers(){if(this._createVideoDriver(),this._config.audio)try{this._audioDriver=new Gs,this._audioDriver.init(),this._audioDriver.setMasterVolume(this._config.volume),this._driverManager.addDriver(this._audioDriver,t=>this._audioDriver.bind(!0,[t.getPCMChannel()])),this._emulationService.stateChanged.addHandler(t=>{switch(t){case _.State.running:this._audioDriver.resume();break;default:this._audioDriver.pause()}})}catch(t){console.error("failed to initialize audio: "+(t&&t.message))}this._createTouchDriver(),this._config.enableKeyboard&&(this._keyboardIO=new Ws(this._config.keyboardTarget),this._driverManager.addDriver(this._keyboardIO,t=>this._keyboardIO.bind(t.getJoystick(0),t.getJoystick(1),t.getControlPanel())),this._config.fullscreenViaKeyboard&&this._keyboardIO.toggleFullscreen.addHandler(()=>this._fullscreenVideo&&this._fullscreenVideo.toggle()),this._config.pauseViaKeyboard&&this._keyboardIO.togglePause.addHandler(this._pauseHandler)),this._config.resetViaKeyboard&&this._keyboardIO.hardReset.addHandler(()=>this.reset()),this._config.enableGamepad&&(this._gamepad=new ri,this._gamepad.init(),this._driverManager.addDriver(this._gamepad,t=>this._gamepad.bind([t.getJoystick(0),t.getJoystick(1)],{start:t.getControlPanel().getResetButton(),select:t.getControlPanel().getSelectSwitch()}))),this._config.paddleViaMouse&&(this._paddle=new Js,this._driverManager.addDriver(this._paddle,t=>this._paddle.bind(t.getPaddle(0)))),this._asyncIO=new ui,this.asyncIOMessage=this._asyncIO.message,this._driverManager.addDriver(this._asyncIO,(t,e)=>e.bind(t.getAsyncIO()))}_removeVideoDriver(){this._videoDriver&&(this._videoDriver.unbind(),this._driverManager.removeDriver(this._videoDriver),this._fullscreenVideo.disengage(),this._fullscreenVideo=null,this._videoDriver=null)}_createVideoDriver(){this._videoDriver&&this._removeVideoDriver(),this._canvasElt&&(this._videoDriver=new Bs(this._canvasElt,{gamma:this._config.gamma,scalingMode:this._config.scalingMode,tvEmulation:this._config.tvEmulation,phosphorLevel:this._config.phosphorLevel,scanlineLevel:this._config.scanlineLevel}).init(),this._driverManager.addDriver(this._videoDriver,t=>this._videoDriver.bind(t.getVideo())),this._fullscreenVideo=new hi(this._videoDriver))}_removeTouchDriver(){this._touchIO&&(this._touchIO.unbind(),this._driverManager.removeDriver(this._touchIO),this._touchIO=null)}_createTouchDriver(){this._touchIO&&this._removeTouchDriver(),this._config.enableTouch&&(this._touchIO=new $s(this._canvasElt,this._config.touchJoystickSensitivity,this._config.touchLeftHanded),this._driverManager.addDriver(this._touchIO,t=>this._touchIO.bind(t.getJoystick(0),t.getControlPanel())),this._config.pauseViaTouch&&this._touchIO.togglePause.addHandler(this._pauseHandler),this._config.fullscreenViaTouch&&this._touchIO.toggleFullscreen.addHandler(()=>this._fullscreenVideo&&this._fullscreenVideo.toggle()))}_mapState(t){switch(t){case _.State.stopped:return di.State.stopped;case _.State.running:return di.State.running;case _.State.paused:return di.State.paused;case _.State.error:return di.State.error;default:throw new Error("cannot happen")}}}return function(t){let e,s,i,r,n;!function(t){t.ntsc="ntsc",t.pal="pal",t.secam="secam"}(e=t.TvMode||(t.TvMode={})),function(t){t.composite="composite",t.svideo="svideo",t.none="none"}(s=t.TvEmulation||(t.TvEmulation={})),function(t){t.qis="qis",t.bilinear="bilinear",t.none="none"}(i=t.ScalingMode||(t.ScalingMode={})),t.CartridgeType=ci.CartridgeType,t.describeCartridgeType=ci.describeCartridgeType,t.allCartridgeTypes=ci.getAllTypes,function(t){t.running="running",t.paused="paused",t.stopped="stopped",t.error="error"}(r=t.State||(t.State={})),function(t){t.cycle="cycle",t.instruction="instruction"}(n=t.CpuAccuracy||(t.CpuAccuracy={}))}(di||(di={})),{Stellerator:di}}));
//# sourceMappingURL=stellerator-embedded.min.js.map