mirror of
https://github.com/sehugg/8bitworkshop.git
synced 2024-11-29 14:51:17 +00:00
1 line
618 KiB
Plaintext
1 line
618 KiB
Plaintext
{"version":3,"file":"stellerator-embedded.min.js","sources":["../../node_modules/tslib/tslib.es6.js","../../node_modules/async-mutex/es6/Semaphore.js","../../node_modules/async-mutex/es6/Mutex.js","../../node_modules/microevent.ts/lib/Event.js","../../node_modules/microevent.ts/lib/index.js","../../src/web/stella/service/EmulationServiceInterface.ts","../../node_modules/worker-rpc/lib/RpcProvider.js","../../node_modules/worker-rpc/lib/index.js","../../src/web/stella/service/worker/EmulationContext.ts","../../src/tools/pool/PoolMember.ts","../../src/tools/pool/Pool.ts","../../src/web/stella/service/worker/messages.ts","../../src/web/stella/service/worker/VideoProxy.ts","../../src/machine/io/Switch.ts","../../src/machine/io/DigitalJoystick.ts","../../src/machine/stella/ControlPanel.ts","../../src/machine/io/Paddle.ts","../../src/web/stella/service/worker/ControlProxy.ts","../../src/machine/cpu/CpuInterface.ts","../../src/machine/cpu/statemachine/ResultImpl.ts","../../src/tools/decorators.ts","../../src/machine/cpu/statemachine/vector/boot.ts","../../src/machine/cpu/statemachine/vector/interrupt.ts","../../src/machine/cpu/Instruction.ts","../../src/machine/cpu/statemachine/addressing/absolute.ts","../../src/machine/cpu/statemachine/addressing/absoluteIndexed.ts","../../src/machine/cpu/statemachine/addressing/dereference.ts","../../src/machine/cpu/statemachine/addressing/immediate.ts","../../src/machine/cpu/statemachine/addressing/indexedIndirectX.ts","../../src/machine/cpu/statemachine/addressing/indirectIndexedY.ts","../../src/machine/cpu/statemachine/addressing/zeroPage.ts","../../src/machine/cpu/statemachine/addressing/zeroPageIndexed.ts","../../src/machine/cpu/statemachine/instruction/branch.ts","../../src/machine/cpu/statemachine/instruction/jsr.ts","../../src/machine/cpu/statemachine/instruction/readModifyWrite.ts","../../src/machine/cpu/statemachine/instruction/rts.ts","../../src/machine/cpu/statemachine/instruction/nullaryOneCycle.ts","../../src/machine/cpu/statemachine/instruction/pull.ts","../../src/machine/cpu/statemachine/instruction/push.ts","../../src/machine/cpu/statemachine/instruction/rti.ts","../../src/machine/cpu/statemachine/instruction/write.ts","../../src/machine/cpu/statemachine/ops.ts","../../src/machine/cpu/statemachine/addressing/indirect.ts","../../src/machine/cpu/statemachine/Compiler.ts","../../src/machine/cpu/StateMachineCpu.ts","../../src/machine/cpu/ops.ts","../../src/machine/cpu/BatchedAccessCpu.ts","../../src/machine/cpu/Factory.ts","../../src/machine/stella/Config.ts","../../src/tools/AudioOutputBuffer.ts","../../src/tools/base64.ts","../../src/machine/stella/tia/ToneGenerator.ts","../../src/web/stella/service/worker/WaveformAudioProxy.ts","../../src/web/stella/service/worker/PCMAudioProxy.ts","../../src/web/stella/service/worker/AsyncIOProxy.ts","../../src/web/stella/service/worker/EmulationService.ts","../../src/web/stella/service/DriverManager.ts","../../src/web/driver/video/shader.ts","../../src/web/driver/video/Program.ts","../../src/web/driver/video/PhosphorProcessor.ts","../../src/web/driver/video/NtscProcessor.ts","../../src/web/driver/video/ScanlineProcessor.ts","../../src/web/driver/video/IntegerScalingProcessor.ts","../../src/tools/RingBuffer.ts","../../src/web/driver/video/Capabilities.ts","../../src/web/driver/Video.ts","../../src/web/driver/audio/WaveformChannel.ts","../../src/web/driver/audio/LinearResampler.ts","../../src/web/driver/audio/PCMChannel.ts","../../src/tools/browser.ts","../../src/web/driver/WebAudio.ts","../../src/web/stella/driver/WebAudio.ts","../../src/web/stella/driver/KeyboardIO.ts","../../src/web/stella/driver/touch/DoubleTapDetector.ts","../../src/web/stella/driver/TouchIO.ts","../../src/web/driver/MouseAsPaddle.ts","../../src/web/driver/gamepad/ShadowSwitch.ts","../../src/web/driver/gamepad/Mapping.ts","../../src/web/driver/gamepad/defaultMapping.ts","../../src/web/driver/Gamepad.ts","../../node_modules/screenfull/dist/screenfull.js","../../src/web/driver/FullscreenVideo.ts","../../src/machine/stella/cartridge/CartridgeInfo.ts","../../src/web/embedded/stellerator/SwitchProxy.ts","../../src/web/embedded/stellerator/ControlPanelProxy.ts","../../src/web/driver/AsyncIO.ts","../../src/web/embedded/stellerator/Stellerator.ts","../../src/web/embedded/stellerator/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","import { __awaiter, __generator } from \"tslib\";\nvar Semaphore = /** @class */ (function () {\n function Semaphore(_maxConcurrency) {\n this._maxConcurrency = _maxConcurrency;\n this._queue = [];\n if (_maxConcurrency <= 0) {\n throw new Error('semaphore must be initialized to a positive value');\n }\n this._value = _maxConcurrency;\n }\n Semaphore.prototype.acquire = function () {\n var _this = this;\n var locked = this.isLocked();\n var ticket = new Promise(function (r) { return _this._queue.push(r); });\n if (!locked)\n this._dispatch();\n return ticket;\n };\n Semaphore.prototype.runExclusive = function (callback) {\n return __awaiter(this, void 0, void 0, function () {\n var _a, value, release;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, this.acquire()];\n case 1:\n _a = _b.sent(), value = _a[0], release = _a[1];\n _b.label = 2;\n case 2:\n _b.trys.push([2, , 4, 5]);\n return [4 /*yield*/, callback(value)];\n case 3: return [2 /*return*/, _b.sent()];\n case 4:\n release();\n return [7 /*endfinally*/];\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n Semaphore.prototype.isLocked = function () {\n return this._value <= 0;\n };\n Semaphore.prototype.release = function () {\n if (this._maxConcurrency > 1) {\n throw new Error('this method is unavailabel on semaphores with concurrency > 1; use the scoped release returned by acquire instead');\n }\n if (this._currentReleaser) {\n this._currentReleaser();\n this._currentReleaser = undefined;\n }\n };\n Semaphore.prototype._dispatch = function () {\n var _this = this;\n var nextConsumer = this._queue.shift();\n if (!nextConsumer)\n return;\n var released = false;\n this._currentReleaser = function () {\n if (released)\n return;\n released = true;\n _this._value++;\n _this._dispatch();\n };\n nextConsumer([this._value--, this._currentReleaser]);\n };\n return Semaphore;\n}());\nexport default Semaphore;\n","import { __awaiter, __generator } from \"tslib\";\nimport Semaphore from './Semaphore';\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._semaphore = new Semaphore(1);\n }\n Mutex.prototype.acquire = function () {\n return __awaiter(this, void 0, void 0, function () {\n var _a, releaser;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, this._semaphore.acquire()];\n case 1:\n _a = _b.sent(), releaser = _a[1];\n return [2 /*return*/, releaser];\n }\n });\n });\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this._semaphore.runExclusive(function () { return callback(); });\n };\n Mutex.prototype.isLocked = function () {\n return this._semaphore.isLocked();\n };\n Mutex.prototype.release = function () {\n this._semaphore.release();\n };\n return Mutex;\n}());\nexport default Mutex;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar factories = [];\nfactories[0] = function () {\n return function dispatcher0() { };\n};\nfactories[1] = function (callback, context) {\n if (typeof (context) === 'undefined')\n return callback;\n return function dispatcher1(payload) {\n callback(payload, context);\n };\n};\nfunction getFactory(handlerCount) {\n if (!factories[handlerCount])\n factories[handlerCount] = compileFactory(handlerCount);\n return factories[handlerCount];\n}\nfunction compileFactory(handlerCount) {\n var src = 'return function dispatcher' + handlerCount + '(payload) {\\n';\n var argsHandlers = [], argsContexts = [];\n for (var i = 0; i < handlerCount; i++) {\n argsHandlers.push('cb' + i);\n argsContexts.push('ctx' + i);\n src += ' cb' + i + '(payload, ctx' + i + ');\\n';\n }\n src += '};';\n return new (Function.bind.apply(Function, [void 0].concat(argsHandlers.concat(argsContexts), [src])))();\n}\nvar Event = /** @class */ (function () {\n function Event() {\n this.hasHandlers = false;\n this._handlers = [];\n this._contexts = [];\n this._createDispatcher();\n }\n Event.prototype.addHandler = function (handler, context) {\n if (!this.isHandlerAttached(handler, context)) {\n this._handlers.push(handler);\n this._contexts.push(context);\n this._createDispatcher();\n this._updateHasHandlers();\n }\n return this;\n };\n Event.prototype.removeHandler = function (handler, context) {\n var idx = this._getHandlerIndex(handler, context);\n if (typeof (idx) !== 'undefined') {\n this._handlers.splice(idx, 1);\n this._contexts.splice(idx, 1);\n this._createDispatcher();\n this._updateHasHandlers();\n }\n return this;\n };\n Event.prototype.isHandlerAttached = function (handler, context) {\n return typeof (this._getHandlerIndex(handler, context)) !== 'undefined';\n };\n Event.prototype._updateHasHandlers = function () {\n this.hasHandlers = !!this._handlers.length;\n };\n Event.prototype._getHandlerIndex = function (handler, context) {\n var handlerCount = this._handlers.length;\n var idx;\n for (idx = 0; idx < handlerCount; idx++) {\n if (this._handlers[idx] === handler && this._contexts[idx] === context)\n break;\n }\n return idx < handlerCount ? idx : undefined;\n };\n Event.prototype._createDispatcher = function () {\n this.dispatch = getFactory(this._handlers.length).apply(this, this._handlers.concat(this._contexts));\n };\n return Event;\n}());\nexports.default = Event;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Event_1 = require(\"./Event\");\nexports.Event = Event_1.default;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { EventInterface } from 'microevent.ts';\n\nimport StellaConfig from '../../../machine/stella/Config';\nimport CartridgeInfo from '../../../machine/stella/cartridge/CartridgeInfo';\nimport EmulationContextInterface from './EmulationContextInterface';\n\ninterface EmulationServiceInterface {\n init(): Promise<void>;\n\n start(\n buffer: { [i: number]: number; length: number },\n config: EmulationServiceInterface.Config,\n cartridgeType?: CartridgeInfo.CartridgeType\n ): Promise<EmulationServiceInterface.State>;\n\n stop(): Promise<EmulationServiceInterface.State>;\n\n pause(): Promise<EmulationServiceInterface.State>;\n\n resume(): Promise<EmulationServiceInterface.State>;\n\n reset(): Promise<EmulationServiceInterface.State>;\n\n setRateLimit(enforce: boolean): Promise<void>;\n\n getRateLimit(): boolean;\n\n getState(): EmulationServiceInterface.State;\n\n getLastError(): Error;\n\n getEmulationContext(): EmulationContextInterface;\n\n getFrequency(): number;\n\n stateChanged: EventInterface<EmulationServiceInterface.State>;\n\n frequencyUpdate: EventInterface<number>;\n}\n\nnamespace EmulationServiceInterface {\n export enum State {\n stopped = 'stopped',\n running = 'running',\n paused = 'paused',\n error = 'error'\n }\n\n export interface Config extends StellaConfig {\n asyncIO?: boolean;\n }\n}\n\nexport { EmulationServiceInterface as default };\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar microevent_ts_1 = require(\"microevent.ts\");\nvar MSG_RESOLVE_TRANSACTION = \"resolve_transaction\", MSG_REJECT_TRANSACTION = \"reject_transaction\", MSG_ERROR = \"error\";\nvar RpcProvider = /** @class */ (function () {\n function RpcProvider(_dispatch, _rpcTimeout) {\n if (_rpcTimeout === void 0) { _rpcTimeout = 0; }\n this._dispatch = _dispatch;\n this._rpcTimeout = _rpcTimeout;\n this.error = new microevent_ts_1.Event();\n this._rpcHandlers = {};\n this._signalHandlers = {};\n this._pendingTransactions = {};\n this._nextTransactionId = 0;\n }\n RpcProvider.prototype.dispatch = function (payload) {\n var message = payload;\n switch (message.type) {\n case RpcProvider.MessageType.signal:\n return this._handleSignal(message);\n case RpcProvider.MessageType.rpc:\n return this._handeRpc(message);\n case RpcProvider.MessageType.internal:\n return this._handleInternal(message);\n default:\n this._raiseError(\"invalid message type \" + message.type);\n }\n };\n RpcProvider.prototype.rpc = function (id, payload, transfer) {\n var _this = this;\n var transactionId = this._nextTransactionId++;\n this._dispatch({\n type: RpcProvider.MessageType.rpc,\n transactionId: transactionId,\n id: id,\n payload: payload\n }, transfer ? transfer : undefined);\n return new Promise(function (resolve, reject) {\n var transaction = _this._pendingTransactions[transactionId] = {\n id: transactionId,\n resolve: resolve,\n reject: reject\n };\n if (_this._rpcTimeout > 0) {\n _this._pendingTransactions[transactionId].timeoutHandle =\n setTimeout(function () { return _this._transactionTimeout(transaction); }, _this._rpcTimeout);\n }\n });\n };\n ;\n RpcProvider.prototype.signal = function (id, payload, transfer) {\n this._dispatch({\n type: RpcProvider.MessageType.signal,\n id: id,\n payload: payload,\n }, transfer ? transfer : undefined);\n return this;\n };\n RpcProvider.prototype.registerRpcHandler = function (id, handler) {\n if (this._rpcHandlers[id]) {\n throw new Error(\"rpc handler for \" + id + \" already registered\");\n }\n this._rpcHandlers[id] = handler;\n return this;\n };\n ;\n RpcProvider.prototype.registerSignalHandler = function (id, handler) {\n if (!this._signalHandlers[id]) {\n this._signalHandlers[id] = [];\n }\n this._signalHandlers[id].push(handler);\n return this;\n };\n RpcProvider.prototype.deregisterRpcHandler = function (id, handler) {\n if (this._rpcHandlers[id]) {\n delete this._rpcHandlers[id];\n }\n return this;\n };\n ;\n RpcProvider.prototype.deregisterSignalHandler = function (id, handler) {\n if (this._signalHandlers[id]) {\n this._signalHandlers[id] = this._signalHandlers[id].filter(function (h) { return handler !== h; });\n }\n return this;\n };\n RpcProvider.prototype._raiseError = function (error) {\n this.error.dispatch(new Error(error));\n this._dispatch({\n type: RpcProvider.MessageType.internal,\n id: MSG_ERROR,\n payload: error\n });\n };\n RpcProvider.prototype._handleSignal = function (message) {\n if (!this._signalHandlers[message.id]) {\n return this._raiseError(\"invalid signal \" + message.id);\n }\n this._signalHandlers[message.id].forEach(function (handler) { return handler(message.payload); });\n };\n RpcProvider.prototype._handeRpc = function (message) {\n var _this = this;\n if (!this._rpcHandlers[message.id]) {\n return this._raiseError(\"invalid rpc \" + message.id);\n }\n Promise.resolve(this._rpcHandlers[message.id](message.payload))\n .then(function (result) { return _this._dispatch({\n type: RpcProvider.MessageType.internal,\n id: MSG_RESOLVE_TRANSACTION,\n transactionId: message.transactionId,\n payload: result\n }); }, function (reason) { return _this._dispatch({\n type: RpcProvider.MessageType.internal,\n id: MSG_REJECT_TRANSACTION,\n transactionId: message.transactionId,\n payload: reason\n }); });\n };\n RpcProvider.prototype._handleInternal = function (message) {\n var transaction = typeof (message.transactionId) !== 'undefined' ? this._pendingTransactions[message.transactionId] : undefined;\n switch (message.id) {\n case MSG_RESOLVE_TRANSACTION:\n if (!transaction || typeof (message.transactionId) === 'undefined') {\n return this._raiseError(\"no pending transaction with id \" + message.transactionId);\n }\n transaction.resolve(message.payload);\n this._clearTransaction(this._pendingTransactions[message.transactionId]);\n break;\n case MSG_REJECT_TRANSACTION:\n if (!transaction || typeof (message.transactionId) === 'undefined') {\n return this._raiseError(\"no pending transaction with id \" + message.transactionId);\n }\n this._pendingTransactions[message.transactionId].reject(message.payload);\n this._clearTransaction(this._pendingTransactions[message.transactionId]);\n break;\n case MSG_ERROR:\n this.error.dispatch(new Error(\"remote error: \" + message.payload));\n break;\n default:\n this._raiseError(\"unhandled internal message \" + message.id);\n break;\n }\n };\n RpcProvider.prototype._transactionTimeout = function (transaction) {\n transaction.reject('transaction timed out');\n this._raiseError(\"transaction \" + transaction.id + \" timed out\");\n delete this._pendingTransactions[transaction.id];\n return;\n };\n RpcProvider.prototype._clearTransaction = function (transaction) {\n if (typeof (transaction.timeoutHandle) !== 'undefined') {\n clearTimeout(transaction.timeoutHandle);\n }\n delete this._pendingTransactions[transaction.id];\n };\n return RpcProvider;\n}());\n(function (RpcProvider) {\n var MessageType;\n (function (MessageType) {\n MessageType[MessageType[\"signal\"] = 0] = \"signal\";\n MessageType[MessageType[\"rpc\"] = 1] = \"rpc\";\n MessageType[MessageType[\"internal\"] = 2] = \"internal\";\n })(MessageType = RpcProvider.MessageType || (RpcProvider.MessageType = {}));\n ;\n})(RpcProvider || (RpcProvider = {}));\nexports.default = RpcProvider;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RpcProvider_1 = require(\"./RpcProvider\");\nexports.RpcProvider = RpcProvider_1.default;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport VideoEndpointInterface from '../../../driver/VideoEndpointInterface';\nimport JoystickInterface from '../../../../machine/io/DigitalJoystickInterface';\nimport ControlPanelInterface from '../../../../machine/stella/ControlPanelInterface';\nimport PaddleInterface from '../../../../machine/io/PaddleInterface';\nimport WaveformAudioOutputInterface from '../../../../machine/io/WaveformAudioOutputInterface';\nimport PCMAudioEndpointInterface from '../../../driver/PCMAudioEndpointInterface';\nimport Config from '../../../../machine/stella/Config';\n\nimport EmulationContextInterface from '../EmulationContextInterface';\nimport VideoProxy from './VideoProxy';\nimport ControlProxy from './ControlProxy';\nimport WaveformAudioProxy from './WaveformAudioProxy';\nimport PCMAudioProxy from './PCMAudioProxy';\nimport AsyncIOProxy from './AsyncIOProxy';\n\nclass EmulationContext implements EmulationContextInterface {\n constructor(\n private _videoProxy: VideoProxy,\n private _controlProxy: ControlProxy,\n private _waveformChannels: Array<WaveformAudioProxy>,\n private _pcmChannel: PCMAudioProxy,\n private _asyncIOProxy: AsyncIOProxy\n ) {\n if (this._waveformChannels.length !== 2) {\n throw new Error(`invalid channel count ${this._waveformChannels.length}`);\n }\n }\n\n setConfig(config: Config): void {\n this._config = config;\n }\n\n getConfig(): Config {\n return this._config;\n }\n\n getVideo(): VideoEndpointInterface {\n return this._videoProxy;\n }\n\n getJoystick(i: number): JoystickInterface {\n return this._controlProxy.getJoystick(i);\n }\n\n getControlPanel(): ControlPanelInterface {\n return this._controlProxy.getControlPanel();\n }\n\n getPaddle(i: number): PaddleInterface {\n return this._controlProxy.getPaddle(i);\n }\n\n getWaveformChannels(): Array<WaveformAudioOutputInterface> {\n return this._waveformChannels;\n }\n\n getPCMChannel(): PCMAudioEndpointInterface {\n return this._pcmChannel;\n }\n\n getVideoProxy(): VideoProxy {\n return this._videoProxy;\n }\n\n getAsyncIO(): AsyncIOProxy {\n return this._asyncIOProxy;\n }\n\n private _config: Config = null;\n}\n\nexport { EmulationContext as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport PoolMemberInterface from './PoolMemberInterface';\n\nclass PoolMember<T> implements PoolMemberInterface<T> {\n constructor(\n private _value: T,\n private _releaseCB: (victim: PoolMember<T>) => void,\n private _disposeCB: (victim: PoolMember<T>) => void\n ) {}\n\n adopt(target: T): void {\n this._value = target;\n }\n\n get(): T {\n return this._value;\n }\n\n release(): void {\n this._releaseCB(this);\n }\n\n dispose(): void {\n this._disposeCB(this);\n }\n\n public _isAvailable = false;\n public _isDisposed = false;\n public _poolPosition: number;\n}\n\nexport { PoolMember as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport PoolMember from './PoolMember';\nimport PoolInterface from './PoolInterface';\n\nclass Pool<T> implements PoolInterface<T> {\n constructor(private _factory: Pool.FactoryInterface<T>) {}\n\n get(): PoolMember<T> {\n let member: PoolMember<T>;\n\n if (this._poolSize === 0) {\n const newItem = this._factory();\n\n member = new PoolMember<T>(\n newItem,\n (victim: PoolMember<T>) => this._releaseMember(victim),\n (victim: PoolMember<T>) => this._disposeMember(victim)\n );\n } else {\n member = this._pool[--this._poolSize];\n member._isAvailable = false;\n }\n\n return member;\n }\n\n private _releaseMember(victim: PoolMember<T>) {\n if (victim._isAvailable) {\n throw new Error('Trying to release an already released pool member');\n }\n\n if (victim._isDisposed) {\n throw new Error('Trying to release an already disposed pool member');\n }\n\n const position = this._poolSize++;\n\n this._pool[position] = victim;\n\n victim._isAvailable = true;\n victim._poolPosition = position;\n\n this.event.release.dispatch(victim.get());\n }\n\n private _disposeMember(victim: PoolMember<T>) {\n if (victim._isDisposed) {\n throw new Error('Trying to dispose of an already disposed pool member');\n }\n\n if (victim._isAvailable) {\n if (this._poolSize > 1) {\n this._pool[victim._poolPosition] = this._pool[this._poolSize - 1];\n }\n\n this._poolSize--;\n }\n\n victim._isDisposed = true;\n\n this.event.dispose.dispatch(victim.get());\n }\n\n event = {\n release: new Event<T>(),\n dispose: new Event<T>(),\n };\n\n private _pool: Array<PoolMember<T>> = [];\n\n private _poolSize = 0;\n}\n\nnamespace Pool {\n export interface FactoryInterface<T> {\n (): T;\n }\n}\n\nexport { Pool as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport EventServiceInterface from '../EmulationServiceInterface';\nimport CartridgeInfo from '../../../../machine/stella/cartridge/CartridgeInfo';\n\nexport const RPC_TYPE = {\n emulationPause: 'emulation/pause',\n emulationReset: 'emulation/reset',\n emulationResume: 'emulation/resume',\n emulationSetRateLimit: 'emulation/setRateLimit',\n emulationStart: 'emulation/start',\n emulationStop: 'emulation/stop',\n emulationFetchLastError: 'emulation/fetchLastError',\n getVideoParameters: 'video/getParameters',\n getWaveformAudioParameters: (index: number) => `audio/waveform/getParameters/${index}`,\n getPCMAudioParameters: (index: number) => `audio/pcm/getParameters/${index}`,\n setup: '/setup'\n};\nObject.freeze(RPC_TYPE);\n\nexport const SIGNAL_TYPE = {\n emulationError: 'emulation/error',\n emulationFrequencyUpdate: 'emulation/frequencyUpdate',\n videoNewFrame: 'video/newFrame',\n videoReturnSurface: 'video/returnSurface',\n controlStateUpdate: 'control/stateUpdate',\n waveformAudioVolumeChange: 'audio/waveform/volumeChange',\n waveformAudioBufferChange: 'audio/waveform/bufferChange',\n pcmAudioNewFrame: (index: number) => `audio/pcm/newFrame/${index}`,\n pcmAudioTogglePause: (index: number) => `audio/pcm/togglePause/${index}`,\n pcmAudioReturnFrame: (index: number) => `audio/pcm/returnFrame/${index}`,\n audioStop: 'audio/stop',\n messageFromAsyncIO: 'asyncIO/messageFrom',\n messageToAsyncIO: 'asyncIO/messageTo'\n};\nObject.freeze(SIGNAL_TYPE);\n\nexport interface SetupMessage {}\n\nexport interface EmulationStartMessage {\n buffer: { [i: number]: number; length: number };\n config: EventServiceInterface.Config;\n cartridgeType?: CartridgeInfo.CartridgeType;\n}\n\nexport interface VideoParametersResponse {\n width: number;\n height: number;\n}\n\nexport interface WaveformAudioParametersResponse {\n volume: number;\n}\n\nexport interface VideoNewFrameMessage {\n id: number;\n width: number;\n height: number;\n buffer: ArrayBuffer;\n}\n\nexport interface VideoReturnSurfaceMessage {\n id: number;\n buffer: ArrayBuffer;\n}\n\nexport interface WaveformAudioVolumeChangeMessage {\n index: number;\n value: number;\n}\n\nexport interface WaveformAudioBufferChangeMessage {\n index: number;\n key: number;\n}\n\nexport interface PCMAudioParametersResponse {\n sampleRate: number;\n frameSize: number;\n paused: boolean;\n}\n\nexport interface PCMAudioNewFrameMessage {\n buffer: ArrayBuffer;\n id: number;\n}\n\nexport interface PCMAudioTogglePauseMessage {\n paused: boolean;\n}\n\nexport interface PCMAudioReturnFrameMessage {\n id: number;\n buffer: ArrayBuffer;\n}\n\nexport type MessageFromAsyncIOMessage = ArrayLike<number>;\n\nexport type MessageToAsyncIOMessage = Array<number>;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport VideoEndpointInterface from '../../../driver/VideoEndpointInterface';\nimport { RpcProviderInterface } from 'worker-rpc';\nimport PoolMemberInterface from '../../../../tools/pool/PoolMemberInterface';\nimport Pool from '../../../../tools/pool/Pool';\n\nimport {\n SIGNAL_TYPE,\n RPC_TYPE,\n VideoNewFrameMessage,\n VideoReturnSurfaceMessage,\n VideoParametersResponse\n} from './messages';\n\nclass VideoProxy implements VideoEndpointInterface {\n constructor(private _rpc: RpcProviderInterface) {\n this._framePool.event.release.addHandler(VideoProxy._onDisposeFrame, this);\n }\n\n init(): void {\n this._rpc.registerSignalHandler(SIGNAL_TYPE.videoNewFrame, this._onNewFrame.bind(this));\n }\n\n async start(): Promise<void> {\n if (this._active) {\n this.stop();\n }\n\n const videoParameters = await this._rpc.rpc<void, VideoParametersResponse>(RPC_TYPE.getVideoParameters);\n\n this._active = true;\n this._width = videoParameters.width;\n this._height = videoParameters.height;\n this._frameMap = new WeakMap<ImageData, number>();\n }\n\n stop(): void {\n this._active = false;\n }\n\n getWidth(): number {\n return this._width;\n }\n\n getHeight(): number {\n return this._height;\n }\n\n private static _onDisposeFrame(imageData: ImageData, self: VideoProxy): void {\n if (!self._active) return;\n\n if (!self._frameMap.has(imageData)) {\n console.warn('unknown imageData returned to proxy');\n return;\n }\n\n const id = self._frameMap.get(imageData);\n self._frameMap.delete(imageData);\n\n self._rpc.signal<VideoReturnSurfaceMessage>(\n SIGNAL_TYPE.videoReturnSurface,\n {\n id,\n buffer: imageData.data.buffer\n },\n [imageData.data.buffer]\n );\n }\n\n private _onNewFrame(message: VideoNewFrameMessage): void {\n if (!this._active) {\n console.warn('video proxy deactivated: ignoring frame');\n return;\n }\n\n if (this._width !== message.width || this._height !== message.height) {\n console.warn(`surface dimensions do not match; ignoring frame`);\n return;\n }\n\n const frame = this._framePool.get();\n const imageData = new ImageData(new Uint8ClampedArray(message.buffer), message.width, message.height);\n\n frame.adopt(imageData);\n this._frameMap.set(imageData, message.id);\n\n this.newFrame.dispatch(frame);\n }\n\n newFrame = new Event<PoolMemberInterface<ImageData>>();\n\n private _framePool = new Pool<ImageData>(() => null);\n private _frameMap: WeakMap<ImageData, number> = null;\n\n private _active = false;\n private _width = 0;\n private _height = 0;\n}\n\nexport { VideoProxy as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport SwitchInterface from './SwitchInterface';\n\nexport default class Switch implements SwitchInterface {\n constructor(private _state: boolean = false) {}\n\n read(): boolean {\n this.beforeRead.dispatch(this);\n return this._state;\n }\n\n peek(): boolean {\n return this._state;\n }\n\n toggle(state: boolean): void {\n if (this._state === state) {\n return;\n }\n\n this._state = state;\n this.stateChanged.dispatch(state);\n }\n\n stateChanged = new Event<boolean>();\n beforeRead = new Event<this>();\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport DigitalJoystickInterface from './DigitalJoystickInterface';\nimport Switch from './Switch';\nimport SwitchInterface from './SwitchInterface';\n\nexport default class DigitalJoystick implements DigitalJoystickInterface {\n getLeft(): SwitchInterface {\n return this._left;\n }\n\n getRight(): SwitchInterface {\n return this._right;\n }\n\n getUp(): SwitchInterface {\n return this._up;\n }\n\n getDown(): SwitchInterface {\n return this._down;\n }\n\n getFire(): SwitchInterface {\n return this._fire;\n }\n\n private _left = new Switch();\n private _right = new Switch();\n private _up = new Switch();\n private _down = new Switch();\n\n private _fire = new Switch();\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Switch from '../io/Switch';\nimport SwitchInterface from '../io/SwitchInterface';\nimport ControlPanelInterface from './ControlPanelInterface';\n\nclass ControlPanel implements ControlPanelInterface {\n getSelectSwitch(): SwitchInterface {\n return this._selectSwitch;\n }\n\n getResetButton(): SwitchInterface {\n return this._resetButton;\n }\n\n getColorSwitch(): SwitchInterface {\n return this._colorSwitch;\n }\n\n getDifficultySwitchP0(): SwitchInterface {\n return this._difficutlyP0;\n }\n\n getDifficultySwitchP1(): SwitchInterface {\n return this._difficutlyP1;\n }\n\n private _selectSwitch = new Switch();\n private _resetButton = new Switch();\n private _colorSwitch = new Switch();\n private _difficutlyP0 = new Switch();\n private _difficutlyP1 = new Switch();\n}\n\nexport { ControlPanel as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport Switch from './Switch';\nimport PaddleInterface from './PaddleInterface';\n\nexport default class Paddle implements PaddleInterface {\n setValue(value: number): void {\n this._value = value;\n this.valueChanged.dispatch(value);\n }\n\n getValue(): number {\n return this._value;\n }\n\n getFire(): Switch {\n return this._fireSwitch;\n }\n\n valueChanged = new Event<number>();\n\n protected _fireSwitch = new Switch();\n protected _value = 0.5;\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Joystick from '../../../../machine/io/DigitalJoystick';\nimport ControlPanel from '../../../../machine/stella/ControlPanel';\nimport Paddle from '../../../../machine/io/Paddle';\nimport ControlState from './ControlState';\nimport { RpcProviderInterface } from 'worker-rpc';\n\nimport { SIGNAL_TYPE } from './messages';\n\nclass ControlProxy {\n constructor(private _rpc: RpcProviderInterface) {\n for (let i = 0; i < 2; i++) {\n this._joysticks[i] = new Joystick();\n }\n\n for (let i = 0; i < 4; i++) {\n this._paddles[i] = new Paddle();\n }\n }\n\n sendUpdate(): void {\n this._rpc.signal<ControlState>(SIGNAL_TYPE.controlStateUpdate, {\n joystickState: this._joysticks.map(ControlProxy._joystickState),\n paddleState: this._paddles.map(ControlProxy._paddleState),\n controlPanelState: ControlProxy._controlPanelState(this._controlPanel)\n });\n }\n\n getJoystick(i: number): Joystick {\n if (i < 0 || i > 1) {\n throw new Error(`invalid joystick index ${i}`);\n }\n\n return this._joysticks[i];\n }\n\n getControlPanel(): ControlPanel {\n return this._controlPanel;\n }\n\n getPaddle(i: number): Paddle {\n if (i < 0 || i > 3) {\n throw new Error(`invalid paddle index ${i}`);\n }\n\n return this._paddles[i];\n }\n\n private static _joystickState(joystick: Joystick): ControlState.JoystickState {\n return {\n up: joystick.getUp().read(),\n down: joystick.getDown().read(),\n left: joystick.getLeft().read(),\n right: joystick.getRight().read(),\n fire: joystick.getFire().read()\n };\n }\n\n private static _paddleState(paddle: Paddle): ControlState.PaddleState {\n return {\n value: paddle.getValue(),\n fire: paddle.getFire().read()\n };\n }\n\n private static _controlPanelState(controlPanel: ControlPanel): ControlState.ControlPanelState {\n return {\n difficulty0: controlPanel.getDifficultySwitchP0().read(),\n difficulty1: controlPanel.getDifficultySwitchP1().read(),\n select: controlPanel.getSelectSwitch().read(),\n reset: controlPanel.getResetButton().read(),\n color: controlPanel.getColorSwitch().read()\n };\n }\n\n private _joysticks = new Array<Joystick>(2);\n private _paddles = new Array<Paddle>(4);\n private _controlPanel = new ControlPanel();\n}\n\nexport { ControlProxy as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\ninterface CpuInterface {\n setInterrupt(irq: boolean): CpuInterface;\n\n isInterrupt(): boolean;\n\n nmi(): CpuInterface;\n\n halt(): CpuInterface;\n\n resume(): CpuInterface;\n\n isHalt(): boolean;\n\n setInvalidInstructionCallback(callback: CpuInterface.InvalidInstructionCallbackInterface): CpuInterface;\n\n getInvalidInstructionCallback(): CpuInterface.InvalidInstructionCallbackInterface;\n\n getLastInstructionPointer(): number;\n\n reset(): CpuInterface;\n\n cycle(): CpuInterface;\n\n executionState: CpuInterface.ExecutionState;\n state: CpuInterface.State;\n}\n\nnamespace CpuInterface {\n export const enum ExecutionState {\n boot,\n fetch,\n execute\n }\n\n export class State {\n a: number = 0;\n x: number = 0;\n y: number = 0;\n s: number = 0;\n p: number = 0;\n flags: number = 0;\n\n irq = false;\n nmi = false;\n }\n\n export const enum Flags {\n c = 0x01, // carry\n z = 0x02, // zero\n i = 0x04, // interrupt\n d = 0x08, // decimal mode\n b = 0x10, // break\n e = 0x20, // reserved\n v = 0x40, // overflow\n n = 0x80 // sign\n }\n\n export interface InvalidInstructionCallbackInterface {\n (cpu?: CpuInterface): void;\n }\n}\n\nexport { CpuInterface as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from './StateMachineInterface';\n\nclass ResultImpl implements StateMachineInterface.Result {\n constructor() {}\n\n read(nextStep: StateMachineInterface.Step, address: number): this {\n this.cycleType = StateMachineInterface.CycleType.read;\n this.address = address;\n this.nextStep = nextStep;\n\n return this;\n }\n\n write(nextStep: StateMachineInterface.Step, address: number, value: number): this {\n this.cycleType = StateMachineInterface.CycleType.write;\n this.address = address;\n this.value = value;\n this.nextStep = nextStep;\n\n return this;\n }\n\n poll(poll: boolean): this {\n this.pollInterrupts = poll;\n\n return this;\n }\n\n cycleType = StateMachineInterface.CycleType.read;\n address = 0;\n value = 0;\n pollInterrupts = false;\n nextStep: StateMachineInterface.Step = null;\n}\n\nexport default ResultImpl;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst immutables = Symbol('immutable properties');\n\nexport function freezeImmutables(target: any): void {\n const immutableProperties = target[immutables];\n if (!immutableProperties) {\n return;\n }\n\n for (const prop of immutableProperties) {\n Object.defineProperty(target, prop, { writable: false, configurable: false });\n }\n}\n\nexport function Immutable(target: any, prop: string): void {\n if (!target[immutables]) {\n Object.defineProperty(target, immutables, { value: [], writable: false, enumerable: false });\n }\n\n target[immutables].push(prop);\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass Boot implements StateMachineInterface {\n constructor(state: CpuInterface.State) {\n this._state = state;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._pre1Step, 0xff);\n\n @Immutable private _pre1Step = (): StateMachineInterface.Result => this._result.read(this._pre2Step, 0x0ff);\n\n @Immutable private _pre2Step = (): StateMachineInterface.Result => this._result.read(this._stack1Step, 0x0100);\n\n @Immutable private _stack1Step = (): StateMachineInterface.Result => this._result.read(this._stack2Step, 0x01ff);\n\n @Immutable\n private _stack2Step = (): StateMachineInterface.Result => {\n this._state.s = 0xfd;\n return this._result.read(this._stack3Step, 0x01fe);\n };\n\n @Immutable\n private _stack3Step = (): StateMachineInterface.Result => this._result.read(this._readTargetLoStep, 0xfffc);\n\n @Immutable\n private _readTargetLoStep = (operand: number): StateMachineInterface.Result => {\n this._targetAddress = operand;\n return this._result.read(this._readTargetHiStep, 0xfffd);\n };\n\n @Immutable\n private _readTargetHiStep = (operand: number): null => {\n this._targetAddress |= operand << 8;\n this._state.p = this._targetAddress;\n\n return null;\n };\n\n private _targetAddress = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n}\n\nexport const boot = (state: CpuInterface.State) => new Boot(state);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass Interrupt implements StateMachineInterface {\n constructor(state: CpuInterface.State, defaultVector: number, isBrk: boolean) {\n this._state = state;\n this._defaultVector = defaultVector;\n this._isBrk = isBrk;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._dummyRead, this._state.p);\n\n @Immutable\n private _dummyRead = (): StateMachineInterface.Result => {\n if (this._isBrk) {\n this._state.p = (this._state.p + 1) & 0xffff;\n }\n\n return this._result.write(this._pushPch, 0x0100 + this._state.s, this._state.p >>> 8);\n };\n\n @Immutable\n private _pushPch = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s - 1) & 0xff;\n\n return this._result.write(this._pushPcl, 0x0100 + this._state.s, this._state.p & 0xff).poll(true);\n };\n\n @Immutable\n private _pushPcl = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s - 1) & 0xff;\n this._vector = this._state.nmi ? 0xfffa : this._defaultVector;\n\n return this._result.write(\n this._pushFlags,\n 0x0100 + this._state.s,\n this._isBrk ? this._state.flags | CpuInterface.Flags.b : this._state.flags & ~CpuInterface.Flags.b\n );\n };\n\n @Immutable\n private _pushFlags = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s - 1) & 0xff;\n\n return this._result.read(this._fetchPcl, this._vector);\n };\n\n @Immutable\n private _fetchPcl = (value: number): StateMachineInterface.Result => {\n this._state.flags |= CpuInterface.Flags.i;\n this._state.p = value;\n\n return this._result.read(this._fetchPch, ++this._vector);\n };\n\n @Immutable\n private _fetchPch = (value: number): null => {\n this._state.p = this._state.p | (value << 8);\n this._state.nmi = this._state.irq = false;\n\n return null;\n };\n\n private _vector = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _defaultVector: number;\n @Immutable private readonly _isBrk: boolean;\n}\n\nexport const brk = (state: CpuInterface.State) => new Interrupt(state, 0xfffe, true);\nexport const irq = (state: CpuInterface.State) => new Interrupt(state, 0xfffe, false);\nexport const nmi = (state: CpuInterface.State) => new Interrupt(state, 0xfffa, false);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nclass Instruction {\n constructor(\n public readonly operation: Instruction.Operation,\n public readonly addressingMode: Instruction.AddressingMode,\n public readonly effectiveAddressingMode = addressingMode\n ) {}\n\n getSize(): number {\n switch (this.effectiveAddressingMode) {\n case Instruction.AddressingMode.immediate:\n case Instruction.AddressingMode.zeroPage:\n case Instruction.AddressingMode.zeroPageX:\n case Instruction.AddressingMode.zeroPageY:\n case Instruction.AddressingMode.indexedIndirectX:\n case Instruction.AddressingMode.indirectIndexedY:\n case Instruction.AddressingMode.relative:\n return 2;\n\n case Instruction.AddressingMode.absolute:\n case Instruction.AddressingMode.absoluteX:\n case Instruction.AddressingMode.absoluteY:\n case Instruction.AddressingMode.indirect:\n return 3;\n\n default:\n return 1;\n }\n }\n}\n\nnamespace Instruction {\n export const enum Operation {\n adc,\n and,\n asl,\n bcc,\n bcs,\n beq,\n bit,\n bmi,\n bne,\n bpl,\n brk,\n bvc,\n bvs,\n clc,\n cld,\n cli,\n clv,\n cmp,\n cpx,\n cpy,\n dec,\n dex,\n dey,\n eor,\n inc,\n inx,\n iny,\n jmp,\n jsr,\n lda,\n ldx,\n ldy,\n lsr,\n nop,\n ora,\n pha,\n php,\n pla,\n plp,\n rol,\n ror,\n rti,\n rts,\n sbc,\n sec,\n sed,\n sei,\n sta,\n stx,\n sty,\n tax,\n tay,\n tsx,\n txa,\n txs,\n tya,\n // undocumented operations\n dop,\n top,\n alr,\n axs,\n dcp,\n lax,\n arr,\n slo,\n aax,\n lar,\n isc,\n aac,\n atx,\n rra,\n rla,\n invalid\n }\n\n export enum OperationMap {\n adc,\n and,\n asl,\n bcc,\n bcs,\n beq,\n bit,\n bmi,\n bne,\n bpl,\n brk,\n bvc,\n bvs,\n clc,\n cld,\n cli,\n clv,\n cmp,\n cpx,\n cpy,\n dec,\n dex,\n dey,\n eor,\n inc,\n inx,\n iny,\n jmp,\n jsr,\n lda,\n ldx,\n ldy,\n lsr,\n nop,\n ora,\n pha,\n php,\n pla,\n plp,\n rol,\n ror,\n rti,\n rts,\n sbc,\n sec,\n sed,\n sei,\n sta,\n stx,\n sty,\n tax,\n tay,\n tsx,\n txa,\n txs,\n tya,\n // undocumented operations\n dop,\n top,\n alr,\n axs,\n dcp,\n lax,\n arr,\n slo,\n aax,\n lar,\n isc,\n aac,\n atx,\n rra,\n rla,\n invalid\n }\n\n export const enum AddressingMode {\n implied,\n immediate,\n zeroPage,\n absolute,\n indirect,\n relative,\n zeroPageX,\n absoluteX,\n indexedIndirectX,\n zeroPageY,\n absoluteY,\n indirectIndexedY,\n invalid\n }\n\n export const opcodes = new Array<Instruction>(256);\n}\n\nexport { Instruction as default };\n\n// Opcodes init\n\nnamespace Instruction {\n export namespace __init {\n for (let i = 0; i < 256; i++) {\n opcodes[i] = new Instruction(Operation.invalid, AddressingMode.invalid);\n }\n\n let operation: Operation, addressingMode: AddressingMode, opcode: number;\n\n for (let i = 0; i < 8; i++) {\n switch (i) {\n case 0:\n operation = Operation.ora;\n break;\n case 1:\n operation = Operation.and;\n break;\n case 2:\n operation = Operation.eor;\n break;\n case 3:\n operation = Operation.adc;\n break;\n case 4:\n operation = Operation.sta;\n break;\n case 5:\n operation = Operation.lda;\n break;\n case 6:\n operation = Operation.cmp;\n break;\n case 7:\n operation = Operation.sbc;\n break;\n }\n for (let j = 0; j < 8; j++) {\n switch (j) {\n case 0:\n addressingMode = AddressingMode.indexedIndirectX;\n break;\n case 1:\n addressingMode = AddressingMode.zeroPage;\n break;\n case 2:\n addressingMode = AddressingMode.immediate;\n break;\n case 3:\n addressingMode = AddressingMode.absolute;\n break;\n case 4:\n addressingMode = AddressingMode.indirectIndexedY;\n break;\n case 5:\n addressingMode = AddressingMode.zeroPageX;\n break;\n case 6:\n addressingMode = AddressingMode.absoluteY;\n break;\n case 7:\n addressingMode = AddressingMode.absoluteX;\n break;\n }\n\n if (operation === Operation.sta && addressingMode === AddressingMode.immediate) {\n addressingMode = AddressingMode.invalid;\n }\n\n if (operation !== Operation.invalid && addressingMode !== AddressingMode.invalid) {\n opcode = (i << 5) | (j << 2) | 1;\n opcodes[opcode] = new Instruction(operation, addressingMode);\n }\n }\n }\n\n function set(\n _opcode: number,\n _operation: Operation,\n _addressingMode: AddressingMode,\n _effectiveAdressingMode?: AddressingMode\n ): void {\n if (opcodes[_opcode].operation !== Operation.invalid) {\n throw new Error('entry for opcode ' + _opcode + ' already exists');\n }\n\n opcodes[_opcode] = new Instruction(_operation, _addressingMode, _effectiveAdressingMode);\n }\n\n set(0x06, Operation.asl, AddressingMode.zeroPage);\n set(0x0a, Operation.asl, AddressingMode.implied);\n set(0x0e, Operation.asl, AddressingMode.absolute);\n set(0x16, Operation.asl, AddressingMode.zeroPageX);\n set(0x1e, Operation.asl, AddressingMode.absoluteX);\n\n set(0x26, Operation.rol, AddressingMode.zeroPage);\n set(0x2a, Operation.rol, AddressingMode.implied);\n set(0x2e, Operation.rol, AddressingMode.absolute);\n set(0x36, Operation.rol, AddressingMode.zeroPageX);\n set(0x3e, Operation.rol, AddressingMode.absoluteX);\n\n set(0x46, Operation.lsr, AddressingMode.zeroPage);\n set(0x4a, Operation.lsr, AddressingMode.implied);\n set(0x4e, Operation.lsr, AddressingMode.absolute);\n set(0x56, Operation.lsr, AddressingMode.zeroPageX);\n set(0x5e, Operation.lsr, AddressingMode.absoluteX);\n\n set(0x66, Operation.ror, AddressingMode.zeroPage);\n set(0x6a, Operation.ror, AddressingMode.implied);\n set(0x6e, Operation.ror, AddressingMode.absolute);\n set(0x76, Operation.ror, AddressingMode.zeroPageX);\n set(0x7e, Operation.ror, AddressingMode.absoluteX);\n\n set(0x86, Operation.stx, AddressingMode.zeroPage);\n set(0x8e, Operation.stx, AddressingMode.absolute);\n set(0x96, Operation.stx, AddressingMode.zeroPageY);\n\n set(0xa2, Operation.ldx, AddressingMode.immediate);\n set(0xa6, Operation.ldx, AddressingMode.zeroPage);\n set(0xae, Operation.ldx, AddressingMode.absolute);\n set(0xb6, Operation.ldx, AddressingMode.zeroPageY);\n set(0xbe, Operation.ldx, AddressingMode.absoluteY);\n\n set(0xc6, Operation.dec, AddressingMode.zeroPage);\n set(0xce, Operation.dec, AddressingMode.absolute);\n set(0xd6, Operation.dec, AddressingMode.zeroPageX);\n set(0xde, Operation.dec, AddressingMode.absoluteX);\n\n set(0xe6, Operation.inc, AddressingMode.zeroPage);\n set(0xee, Operation.inc, AddressingMode.absolute);\n set(0xf6, Operation.inc, AddressingMode.zeroPageX);\n set(0xfe, Operation.inc, AddressingMode.absoluteX);\n\n set(0x24, Operation.bit, AddressingMode.zeroPage);\n set(0x2c, Operation.bit, AddressingMode.absolute);\n\n set(0x4c, Operation.jmp, AddressingMode.absolute);\n set(0x6c, Operation.jmp, AddressingMode.indirect);\n\n set(0x84, Operation.sty, AddressingMode.zeroPage);\n set(0x8c, Operation.sty, AddressingMode.absolute);\n set(0x94, Operation.sty, AddressingMode.zeroPageX);\n\n set(0xa0, Operation.ldy, AddressingMode.immediate);\n set(0xa4, Operation.ldy, AddressingMode.zeroPage);\n set(0xac, Operation.ldy, AddressingMode.absolute);\n set(0xb4, Operation.ldy, AddressingMode.zeroPageX);\n set(0xbc, Operation.ldy, AddressingMode.absoluteX);\n\n set(0xc0, Operation.cpy, AddressingMode.immediate);\n set(0xc4, Operation.cpy, AddressingMode.zeroPage);\n set(0xcc, Operation.cpy, AddressingMode.absolute);\n\n set(0xe0, Operation.cpx, AddressingMode.immediate);\n set(0xe4, Operation.cpx, AddressingMode.zeroPage);\n set(0xec, Operation.cpx, AddressingMode.absolute);\n\n set(0x10, Operation.bpl, AddressingMode.relative);\n set(0x30, Operation.bmi, AddressingMode.relative);\n set(0x50, Operation.bvc, AddressingMode.relative);\n set(0x70, Operation.bvs, AddressingMode.relative);\n set(0x90, Operation.bcc, AddressingMode.relative);\n set(0xb0, Operation.bcs, AddressingMode.relative);\n set(0xd0, Operation.bne, AddressingMode.relative);\n set(0xf0, Operation.beq, AddressingMode.relative);\n\n set(0x00, Operation.brk, AddressingMode.implied);\n set(0x20, Operation.jsr, AddressingMode.implied, AddressingMode.absolute);\n set(0x40, Operation.rti, AddressingMode.implied);\n set(0x60, Operation.rts, AddressingMode.implied);\n set(0x08, Operation.php, AddressingMode.implied);\n set(0x28, Operation.plp, AddressingMode.implied);\n set(0x48, Operation.pha, AddressingMode.implied);\n set(0x68, Operation.pla, AddressingMode.implied);\n set(0x88, Operation.dey, AddressingMode.implied);\n set(0xa8, Operation.tay, AddressingMode.implied);\n set(0xc8, Operation.iny, AddressingMode.implied);\n set(0xe8, Operation.inx, AddressingMode.implied);\n set(0x18, Operation.clc, AddressingMode.implied);\n set(0x38, Operation.sec, AddressingMode.implied);\n set(0x58, Operation.cli, AddressingMode.implied);\n set(0x78, Operation.sei, AddressingMode.implied);\n set(0x98, Operation.tya, AddressingMode.implied);\n set(0xb8, Operation.clv, AddressingMode.implied);\n set(0xd8, Operation.cld, AddressingMode.implied);\n set(0xf8, Operation.sed, AddressingMode.implied);\n set(0x8a, Operation.txa, AddressingMode.implied);\n set(0x9a, Operation.txs, AddressingMode.implied);\n set(0xaa, Operation.tax, AddressingMode.implied);\n set(0xba, Operation.tsx, AddressingMode.implied);\n set(0xca, Operation.dex, AddressingMode.implied);\n set(0xea, Operation.nop, AddressingMode.implied);\n\n // instructions for undocumented opcodes\n set(0x1a, Operation.nop, AddressingMode.implied);\n set(0x3a, Operation.nop, AddressingMode.implied);\n set(0x5a, Operation.nop, AddressingMode.implied);\n set(0x7a, Operation.nop, AddressingMode.implied);\n set(0xda, Operation.nop, AddressingMode.implied);\n set(0xfa, Operation.nop, AddressingMode.implied);\n\n set(0x04, Operation.dop, AddressingMode.zeroPage);\n set(0x14, Operation.dop, AddressingMode.zeroPageX);\n set(0x34, Operation.dop, AddressingMode.zeroPageX);\n set(0x44, Operation.dop, AddressingMode.zeroPage);\n set(0x54, Operation.dop, AddressingMode.zeroPageX);\n set(0x64, Operation.dop, AddressingMode.zeroPage);\n set(0x74, Operation.dop, AddressingMode.zeroPageX);\n set(0x80, Operation.dop, AddressingMode.immediate);\n set(0x82, Operation.dop, AddressingMode.immediate);\n set(0x89, Operation.dop, AddressingMode.immediate);\n set(0xc2, Operation.dop, AddressingMode.immediate);\n set(0xd4, Operation.dop, AddressingMode.zeroPageX);\n set(0xe2, Operation.dop, AddressingMode.immediate);\n set(0xf4, Operation.dop, AddressingMode.zeroPageX);\n\n set(0x0c, Operation.top, AddressingMode.absolute);\n set(0x1c, Operation.top, AddressingMode.absoluteX);\n set(0x3c, Operation.top, AddressingMode.absoluteX);\n set(0x5c, Operation.top, AddressingMode.absoluteX);\n set(0x7c, Operation.top, AddressingMode.absoluteX);\n set(0xdc, Operation.top, AddressingMode.absoluteX);\n set(0xfc, Operation.top, AddressingMode.absoluteX);\n\n set(0xeb, Operation.sbc, AddressingMode.immediate);\n\n set(0x4b, Operation.alr, AddressingMode.immediate);\n\n set(0xcb, Operation.axs, AddressingMode.immediate);\n\n set(0xc7, Operation.dcp, AddressingMode.zeroPage);\n set(0xd7, Operation.dcp, AddressingMode.zeroPageX);\n set(0xcf, Operation.dcp, AddressingMode.absolute);\n set(0xdf, Operation.dcp, AddressingMode.absoluteX);\n set(0xdb, Operation.dcp, AddressingMode.absoluteY);\n set(0xc3, Operation.dcp, AddressingMode.indexedIndirectX);\n set(0xd3, Operation.dcp, AddressingMode.indirectIndexedY);\n\n set(0xa7, Operation.lax, AddressingMode.zeroPage);\n set(0xb7, Operation.lax, AddressingMode.zeroPageY);\n set(0xaf, Operation.lax, AddressingMode.absolute);\n set(0xbf, Operation.lax, AddressingMode.absoluteY);\n set(0xa3, Operation.lax, AddressingMode.indexedIndirectX);\n set(0xb3, Operation.lax, AddressingMode.indirectIndexedY);\n\n set(0x6b, Operation.arr, AddressingMode.immediate);\n\n set(0x07, Operation.slo, AddressingMode.zeroPage);\n set(0x17, Operation.slo, AddressingMode.zeroPageX);\n set(0x0f, Operation.slo, AddressingMode.absolute);\n set(0x1f, Operation.slo, AddressingMode.absoluteX);\n set(0x1b, Operation.slo, AddressingMode.absoluteY);\n set(0x03, Operation.slo, AddressingMode.indexedIndirectX);\n set(0x13, Operation.slo, AddressingMode.indirectIndexedY);\n\n set(0x87, Operation.aax, AddressingMode.zeroPage);\n set(0x97, Operation.aax, AddressingMode.zeroPageY);\n set(0x83, Operation.aax, AddressingMode.indexedIndirectX);\n set(0x8f, Operation.aax, AddressingMode.absolute);\n\n set(0xbb, Operation.lar, AddressingMode.absoluteY);\n\n set(0xe7, Operation.isc, AddressingMode.zeroPage);\n set(0xf7, Operation.isc, AddressingMode.zeroPageX);\n set(0xef, Operation.isc, AddressingMode.absolute);\n set(0xff, Operation.isc, AddressingMode.absoluteX);\n set(0xfb, Operation.isc, AddressingMode.absoluteY);\n set(0xe3, Operation.isc, AddressingMode.indexedIndirectX);\n set(0xf3, Operation.isc, AddressingMode.indirectIndexedY);\n\n set(0x0b, Operation.aac, AddressingMode.immediate);\n set(0x2b, Operation.aac, AddressingMode.immediate);\n\n set(0xab, Operation.atx, AddressingMode.immediate);\n\n set(0x67, Operation.rra, AddressingMode.zeroPage);\n set(0x77, Operation.rra, AddressingMode.zeroPageX);\n set(0x6f, Operation.rra, AddressingMode.absolute);\n set(0x7f, Operation.rra, AddressingMode.absoluteX);\n set(0x7b, Operation.rra, AddressingMode.absoluteY);\n set(0x63, Operation.rra, AddressingMode.indexedIndirectX);\n set(0x73, Operation.rra, AddressingMode.indirectIndexedY);\n\n set(0x27, Operation.rla, AddressingMode.zeroPage);\n set(0x37, Operation.rla, AddressingMode.zeroPageX);\n set(0x2f, Operation.rla, AddressingMode.absolute);\n set(0x3f, Operation.rla, AddressingMode.absoluteX);\n set(0x3b, Operation.rla, AddressingMode.absoluteY);\n set(0x23, Operation.rla, AddressingMode.indexedIndirectX);\n set(0x33, Operation.rla, AddressingMode.indirectIndexedY);\n }\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport StateMachineInterface from '../StateMachineInterface';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass Absolute implements StateMachineInterface {\n constructor(state: CpuInterface.State, next: NextStep = () => null) {\n this._state = state;\n this._next = next;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchLo, this._state.p);\n\n @Immutable\n private _fetchLo = (value: number): StateMachineInterface.Result => {\n this._operand = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._fetchHi, this._state.p);\n };\n\n @Immutable\n private _fetchHi = (value: number): StateMachineInterface.Result | null => {\n this._operand |= value << 8;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n}\n\nexport const absolute = (state: CpuInterface.State, next: NextStep) => new Absolute(state, next);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport StateMachineInterface from '../StateMachineInterface';\n\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass AbsoluteIndexed implements StateMachineInterface {\n private constructor(\n state: CpuInterface.State,\n indexExtractor: AbsoluteIndexed.IndexExtractor,\n next: NextStep = () => null,\n writeOp = false\n ) {\n this._state = state;\n this._indexExtractor = indexExtractor;\n this._next = next;\n this._writeOp = writeOp;\n\n freezeImmutables(this);\n }\n\n @Immutable\n static absoluteX(state: CpuInterface.State, next: NextStep, writeOp: boolean): AbsoluteIndexed {\n return new AbsoluteIndexed(state, s => s.x, next, writeOp);\n }\n\n @Immutable\n static absoluteY(state: CpuInterface.State, next: NextStep, writeOp: boolean): AbsoluteIndexed {\n return new AbsoluteIndexed(state, s => s.y, next, writeOp);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchLo, this._state.p);\n\n @Immutable\n private _fetchLo = (value: number): StateMachineInterface.Result => {\n this._operand = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._fetchHi, this._state.p);\n };\n\n @Immutable\n private _fetchHi = (value: number): StateMachineInterface.Result | null => {\n this._operand |= value << 8;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n const index = this._indexExtractor(this._state);\n this._carry = (this._operand & 0xff) + index > 0xff;\n this._operand = (this._operand & 0xff00) | ((this._operand + index) & 0xff);\n\n return this._carry || this._writeOp\n ? this._result.read(this._dereferenceAndCarry, this._operand)\n : this._next(this._operand, this._state);\n };\n\n @Immutable\n private _dereferenceAndCarry = (value: number): StateMachineInterface.Result | null => {\n if (this._carry) {\n this._operand = (this._operand + 0x0100) & 0xffff;\n }\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n private _carry = false;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _indexExtractor: AbsoluteIndexed.IndexExtractor;\n @Immutable private readonly _next: NextStep;\n @Immutable private readonly _writeOp: boolean;\n}\n\nnamespace AbsoluteIndexed {\n export interface IndexExtractor {\n (s: CpuInterface.State): number;\n }\n}\n\nexport const absoluteX = (state: CpuInterface.State, next: NextStep, writeOp: boolean) =>\n AbsoluteIndexed.absoluteX(state, next, writeOp);\n\nexport const absoluteY = (state: CpuInterface.State, next: NextStep, writeOp: boolean) =>\n AbsoluteIndexed.absoluteY(state, next, writeOp);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\nimport CpuInterface from '../../CpuInterface';\n\nclass Dereference implements StateMachineInterface<number> {\n constructor(state: CpuInterface.State, next: NextStep = () => null) {\n this._next = next;\n this._state = state;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (operand: number): StateMachineInterface.Result => this._result.read(this._dereference, operand);\n\n @Immutable\n private _dereference = (value: number): StateMachineInterface.Result | null => this._next(value, this._state);\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n}\n\nexport const dereference = (state: CpuInterface.State, next: NextStep) => new Dereference(state, next);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport StateMachineInterface from '../StateMachineInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass Immediate implements StateMachineInterface {\n constructor(state: CpuInterface.State, next: NextStep = () => null) {\n this._state = state;\n this._next = next;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchOperand, this._state.p);\n\n @Immutable\n private _fetchOperand = (value: number): StateMachineInterface.Result | null => {\n this._operand = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n}\n\nexport const immediate = (state: CpuInterface.State, next: NextStep) => new Immediate(state, next);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport StateMachineInterface from '../StateMachineInterface';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass IndexedIndirectX implements StateMachineInterface {\n constructor(state: CpuInterface.State, next: NextStep = () => null) {\n this._state = state;\n this._next = next;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchAddress, this._state.p);\n\n @Immutable\n private _fetchAddress = (value: number): StateMachineInterface.Result => {\n this._address = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._addIndex, this._address);\n };\n\n @Immutable\n private _addIndex = (value: number): StateMachineInterface.Result => {\n this._address = (this._address + this._state.x) & 0xff;\n\n return this._result.read(this._fetchLo, this._address);\n };\n\n @Immutable\n private _fetchLo = (value: number): StateMachineInterface.Result => {\n this._operand = value;\n this._address = (this._address + 1) & 0xff;\n\n return this._result.read(this._fetchHi, this._address);\n };\n\n @Immutable\n private _fetchHi = (value: number): StateMachineInterface.Result | null => {\n this._operand |= value << 8;\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n private _address = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n}\n\nexport const indexedIndirectX = (state: CpuInterface.State, next: NextStep) => new IndexedIndirectX(state, next);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport StateMachineInterface from '../StateMachineInterface';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass IndexedIndirectY implements StateMachineInterface {\n constructor(state: CpuInterface.State, next: NextStep = () => null, writeOp: boolean) {\n this._state = state;\n this._next = next;\n this._writeOp = writeOp;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchAddress, this._state.p);\n\n @Immutable\n private _fetchAddress = (value: number): StateMachineInterface.Result => {\n this._address = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._fetchLo, this._address);\n };\n\n @Immutable\n private _fetchLo = (value: number): StateMachineInterface.Result => {\n this._operand = value;\n this._address = (this._address + 1) & 0xff;\n\n return this._result.read(this._fetchHi, this._address);\n };\n\n @Immutable\n private _fetchHi = (value: number): StateMachineInterface.Result | null => {\n this._operand |= value << 8;\n\n this._carry = (this._operand & 0xff) + this._state.y > 0xff;\n this._operand = (this._operand & 0xff00) | ((this._operand + this._state.y) & 0xff);\n\n return this._carry || this._writeOp\n ? this._result.read(this._dereferenceAndCarry, this._operand)\n : this._next(this._operand, this._state);\n };\n\n @Immutable\n private _dereferenceAndCarry = (value: number): StateMachineInterface.Result | null => {\n if (this._carry) {\n this._operand = (this._operand + 0x0100) & 0xffff;\n }\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n private _address = 0;\n private _carry = false;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n @Immutable private readonly _writeOp: boolean;\n}\n\nexport const indirectIndexedY = (state: CpuInterface.State, next: NextStep, writeOp: boolean) =>\n new IndexedIndirectY(state, next, writeOp);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport StateMachineInterface from '../StateMachineInterface';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass ZeroPage implements StateMachineInterface {\n constructor(state: CpuInterface.State, next: NextStep = () => null) {\n this._state = state;\n this._next = next;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchAddress, this._state.p);\n\n @Immutable\n private _fetchAddress = (value: number): StateMachineInterface.Result | null => {\n this._operand = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n}\n\nexport const zeroPage = (state: CpuInterface.State, next: NextStep) => new ZeroPage(state, next);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport StateMachineInterface from '../StateMachineInterface';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass ZeroPageIndexed implements StateMachineInterface {\n private constructor(state: CpuInterface.State, indexExtractor: ZeroPageIndexed.IndexExtractor, next: NextStep) {\n this._state = state;\n this._indexExtractor = indexExtractor;\n this._next = next;\n\n freezeImmutables(this);\n }\n\n static zeroPageX(state: CpuInterface.State, next: NextStep = () => null): ZeroPageIndexed {\n return new ZeroPageIndexed(state, s => s.x, next);\n }\n\n static zeroPageY(state: CpuInterface.State, next: NextStep = () => null): ZeroPageIndexed {\n return new ZeroPageIndexed(state, s => s.y, next);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchAddress, this._state.p);\n\n @Immutable\n private _fetchAddress = (value: number): StateMachineInterface.Result => {\n this._operand = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._addIndex, this._operand);\n };\n\n @Immutable\n private _addIndex = (value: number): StateMachineInterface.Result | null => {\n this._operand = (this._operand + this._indexExtractor(this._state)) & 0xff;\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n @Immutable private readonly _indexExtractor: ZeroPageIndexed.IndexExtractor;\n}\n\nnamespace ZeroPageIndexed {\n export interface IndexExtractor {\n (s: CpuInterface.State): number;\n }\n}\n\nexport const zeroPageX = (state: CpuInterface.State, next: NextStep) => ZeroPageIndexed.zeroPageX(state, next);\n\nexport const zeroPageY = (state: CpuInterface.State, next: NextStep) => ZeroPageIndexed.zeroPageY(state, next);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass Branch implements StateMachineInterface {\n constructor(state: CpuInterface.State, predicate: Branch.Predicate) {\n this._state = state;\n this._predicate = predicate;\n\n freezeImmutables(this);\n }\n\n @Immutable\n reset = (): StateMachineInterface.Result => this._result.read(this._fetchTarget, this._state.p).poll(true);\n\n @Immutable\n private _fetchTarget = (value: number): StateMachineInterface.Result | null => {\n this._operand = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._predicate(this._state.flags) ? this._result.read(this._firstDummyRead, this._state.p) : null;\n };\n\n @Immutable\n private _firstDummyRead = (value: number): StateMachineInterface.Result | null => {\n this._target = (this._state.p + (this._operand & 0x80 ? this._operand - 256 : this._operand)) & 0xffff;\n\n if ((this._target & 0xff00) === (this._state.p & 0xff00)) {\n this._state.p = this._target;\n return null;\n }\n\n return this._result.read(this._secondDummyRead, (this._state.p & 0xff00) | (this._target & 0x00ff)).poll(true);\n };\n\n @Immutable\n private _secondDummyRead = (value: number): null => {\n this._state.p = this._target;\n return null;\n };\n\n private _target = 0;\n private _operand = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _predicate: Branch.Predicate;\n}\n\nnamespace Branch {\n export interface Predicate {\n (flags: number): boolean;\n }\n}\n\nexport const branch = (state: CpuInterface.State, predicate: Branch.Predicate) => new Branch(state, predicate);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass Jsr implements StateMachineInterface {\n constructor(state: CpuInterface.State) {\n this._state = state;\n\n freezeImmutables(this);\n }\n\n reset = (): StateMachineInterface.Result => this._result.read(this._fetchPcl, this._state.p);\n\n @Immutable\n private _fetchPcl = (value: number): StateMachineInterface.Result => {\n this._addressLo = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._dummyStackRead, 0x0100 + this._state.s);\n };\n\n @Immutable\n private _dummyStackRead = (): StateMachineInterface.Result =>\n this._result.write(this._pushPch, 0x0100 + this._state.s, this._state.p >>> 8);\n\n @Immutable\n private _pushPch = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s - 1) & 0xff;\n\n return this._result.write(this._pushPcl, 0x0100 + this._state.s, this._state.p & 0xff);\n };\n\n @Immutable\n private _pushPcl = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s - 1) & 0xff;\n\n return this._result.read(this._fetchPch, this._state.p);\n };\n\n @Immutable\n private _fetchPch = (value: number): null => {\n this._state.p = this._addressLo | (value << 8);\n\n return null;\n };\n\n private _addressLo = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n}\n\nexport const jsr = (state: CpuInterface.State) => new Jsr(state);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass ReadModifyWrite implements StateMachineInterface<number> {\n constructor(state: CpuInterface.State, operation: ReadModifyWrite.Operation) {\n this._state = state;\n this._operation = operation;\n\n freezeImmutables(this);\n }\n\n @Immutable\n reset = (address: number): StateMachineInterface.Result => {\n this._address = address;\n\n return this._result.read(this._read, address);\n };\n\n @Immutable\n private _read = (value: number): StateMachineInterface.Result => {\n this._operand = value;\n\n return this._result.write(this._dummyWrite, this._address, this._operand);\n };\n\n @Immutable\n private _dummyWrite = (value: number): StateMachineInterface.Result =>\n this._result.write(this._write, this._address, this._operation(this._operand, this._state));\n\n @Immutable private _write = (): null => null;\n\n private _address: number;\n private _operand: number;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _operation: ReadModifyWrite.Operation;\n}\n\nnamespace ReadModifyWrite {\n export interface Operation {\n (o: number, s: CpuInterface.State): number;\n }\n}\n\nexport const readModifyWrite = (state: CpuInterface.State, operation: ReadModifyWrite.Operation) =>\n new ReadModifyWrite(state, operation);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass Rts implements StateMachineInterface {\n constructor(state: CpuInterface.State) {\n this._state = state;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._dummyOperandRead, this._state.p);\n\n @Immutable\n private _dummyOperandRead = (): StateMachineInterface.Result =>\n this._result.read(this._dummyStackRead, 0x0100 + this._state.s);\n\n @Immutable\n private _dummyStackRead = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s + 1) & 0xff;\n\n return this._result.read(this._popPcl, 0x0100 + this._state.s);\n };\n\n @Immutable\n private _popPcl = (value: number): StateMachineInterface.Result => {\n this._state.p = (this._state.p & 0xff00) | value;\n this._state.s = (this._state.s + 1) & 0xff;\n\n return this._result.read(this._popPch, 0x0100 + this._state.s);\n };\n\n @Immutable\n private _popPch = (value: number): StateMachineInterface.Result => {\n this._state.p = (this._state.p & 0xff) | (value << 8);\n\n return this._result.read(this._incrementP, this._state.p);\n };\n\n @Immutable\n private _incrementP = (): null => {\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return null;\n };\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n}\n\nexport const rts = (state: CpuInterface.State) => new Rts(state);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass NullaryOneCycle implements StateMachineInterface<number> {\n constructor(state: CpuInterface.State, operation: UnaryOneCycle.Operation) {\n this._state = state;\n this._operation = operation;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = () => this._result.read(this._executeOperation, this._state.p).poll(true);\n\n @Immutable\n private _executeOperation = (): null => {\n this._operation(this._state);\n\n return null;\n };\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _operation: UnaryOneCycle.Operation;\n}\n\nnamespace UnaryOneCycle {\n export interface Operation {\n (s: CpuInterface.State): void;\n }\n}\n\nexport const nullaryOneCycle = (state: CpuInterface.State, operation: UnaryOneCycle.Operation) =>\n new NullaryOneCycle(state, operation);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport StateMachineInterface from '../StateMachineInterface';\nimport ResultImpl from '../ResultImpl';\nimport CpuInterface from '../../CpuInterface';\n\nclass Pull implements StateMachineInterface {\n constructor(state: CpuInterface.State, operation: Pull.Operation) {\n this._state = state;\n this._operation = operation;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._dummyRead, this._state.p).poll(true);\n\n @Immutable\n private _dummyRead = (): StateMachineInterface.Result =>\n this._result.read(this._incrementS, 0x0100 + this._state.s);\n\n @Immutable\n private _incrementS = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s + 1) & 0xff;\n\n return this._result.read(this._pull, 0x0100 + this._state.s);\n };\n\n @Immutable private _pull = (value: number): null => (this._operation(this._state, value), null);\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _operation: Pull.Operation;\n}\n\nnamespace Pull {\n export interface Operation {\n (state: CpuInterface.State, ooperand: number): void;\n }\n}\n\nexport const pull = (state: CpuInterface.State, operation: Pull.Operation) => new Pull(state, operation);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport CpuInterface from '../../CpuInterface';\nimport StateMachineInterface from '../StateMachineInterface';\nimport ResultImpl from '../ResultImpl';\n\nclass Push implements StateMachineInterface {\n constructor(state: CpuInterface.State, operation: Push.Operation) {\n this._state = state;\n this._operation = operation;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._dummyRead, this._state.p);\n\n @Immutable\n private _dummyRead = (): StateMachineInterface.Result =>\n this._result.write(this._push, 0x0100 + this._state.s, this._operation(this._state));\n\n @Immutable\n private _push = (): null => {\n this._state.s = (this._state.s - 1) & 0xff;\n\n return null;\n };\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _operation: Push.Operation;\n}\n\nnamespace Push {\n export interface Operation {\n (s: CpuInterface.State): number;\n }\n}\n\nexport const push = (state: CpuInterface.State, operation: Push.Operation) => new Push(state, operation);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass Rti implements StateMachineInterface {\n constructor(state: CpuInterface.State) {\n this._state = state;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._dummyOperandRead, this._state.p);\n\n @Immutable\n private _dummyOperandRead = (): StateMachineInterface.Result =>\n this._result.read(this._dummyStackRead, 0x0100 + this._state.s);\n\n @Immutable\n private _dummyStackRead = (): StateMachineInterface.Result => {\n this._state.s = (this._state.s + 1) & 0xff;\n\n return this._result.read(this._popP, 0x0100 + this._state.s);\n };\n\n @Immutable\n private _popP = (value: number): StateMachineInterface.Result => {\n this._state.flags = (value | CpuInterface.Flags.e) & ~CpuInterface.Flags.b;\n this._state.s = (this._state.s + 1) & 0xff;\n\n return this._result.read(this._popPcl, 0x0100 + this._state.s);\n };\n\n @Immutable\n private _popPcl = (value: number): StateMachineInterface.Result => {\n this._state.p = (this._state.p & 0xff00) | value;\n this._state.s = (this._state.s + 1) & 0xff;\n\n return this._result.read(this._popPch, 0x0100 + this._state.s);\n };\n\n @Immutable\n private _popPch = (value: number): null => {\n this._state.p = (this._state.p & 0xff) | (value << 8);\n\n return null;\n };\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n}\n\nexport const rti = (state: CpuInterface.State) => new Rti(state);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport StateMachineInterface from '../StateMachineInterface';\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\n\nclass Write implements StateMachineInterface<number> {\n constructor(state: CpuInterface.State, operation: Write.Operation) {\n this._state = state;\n this._operation = operation;\n\n freezeImmutables(this);\n }\n\n @Immutable\n reset = (operand: number): StateMachineInterface.Result =>\n this._result.write(() => null, operand, this._operation(this._state));\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _operation: Write.Operation;\n}\n\nnamespace Write {\n export interface Operation {\n (s: CpuInterface.State): number;\n }\n}\n\nexport const write = (state: CpuInterface.State, operation: Write.Operation) => new Write(state, operation);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../CpuInterface';\n\nfunction setFlagsNZ(operand: number, state: CpuInterface.State): void {\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z)) |\n (operand & 0x80) |\n (operand ? 0 : CpuInterface.Flags.z);\n}\n\nexport function genRmw(operand: number, state: CpuInterface.State, operation: (x: number) => number): number {\n const result = operation(operand);\n setFlagsNZ(result, state);\n\n return result;\n}\n\nexport function genNullary(state: CpuInterface.State, operation: (state: CpuInterface.State) => number): void {\n setFlagsNZ(operation(state), state);\n}\n\nexport function genUnary(\n operand: number,\n state: CpuInterface.State,\n operation: (operand: number, state: CpuInterface.State) => number\n): null {\n setFlagsNZ(operation(operand, state), state);\n\n return null;\n}\n\nexport function adc(operand: number, state: CpuInterface.State): null {\n if (state.flags & CpuInterface.Flags.d) {\n const d0 = (operand & 0x0f) + (state.a & 0x0f) + (state.flags & CpuInterface.Flags.c),\n d1 = (operand >>> 4) + (state.a >>> 4) + (d0 > 9 ? 1 : 0);\n\n state.a = d0 % 10 | (d1 % 10 << 4);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) | // negative\n (state.a ? 0 : CpuInterface.Flags.z) | // zero\n (d1 > 9 ? CpuInterface.Flags.c : 0); // carry\n } else {\n const sum = state.a + operand + (state.flags & CpuInterface.Flags.c),\n result = sum & 0xff;\n\n state.flags =\n (state.flags &\n ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c | CpuInterface.Flags.v)) |\n (result & 0x80) | // negative\n (result ? 0 : CpuInterface.Flags.z) | // zero\n (sum >>> 8) | // carry\n ((~(operand ^ state.a) & (result ^ operand) & 0x80) >>> 1); // overflow\n\n state.a = result;\n }\n\n return null;\n}\n\nexport function aslImmediate(state: CpuInterface.State): void {\n const old = state.a;\n state.a = (state.a << 1) & 0xff;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old >>> 7);\n}\n\nexport function aslRmw(operand: number, state: CpuInterface.State): number {\n const result = (operand << 1) & 0xff;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (result & 0x80) |\n (result ? 0 : CpuInterface.Flags.z) |\n (operand >>> 7);\n\n return result;\n}\n\nexport function bit(operand: number, state: CpuInterface.State): null {\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.v | CpuInterface.Flags.z)) |\n (operand & (CpuInterface.Flags.n | CpuInterface.Flags.v)) |\n (operand & state.a ? 0 : CpuInterface.Flags.z);\n\n return null;\n}\n\nexport function cmp(\n operand: number,\n state: CpuInterface.State,\n getRegister: (state: CpuInterface.State) => number\n): void {\n const diff = getRegister(state) + (~operand & 0xff) + 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (diff & 0x80) |\n (diff & 0xff ? 0 : CpuInterface.Flags.z) |\n (diff >>> 8);\n}\n\nexport function sbc(operand: number, state: CpuInterface.State): null {\n if (state.flags & CpuInterface.Flags.d) {\n const d0 = (state.a & 0x0f) - (operand & 0x0f) - (~state.flags & CpuInterface.Flags.c),\n d1 = (state.a >>> 4) - (operand >>> 4) - (d0 < 0 ? 1 : 0);\n\n state.a = (d0 < 0 ? 10 + d0 : d0) | ((d1 < 0 ? 10 + d1 : d1) << 4);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) | // negative\n (state.a ? 0 : CpuInterface.Flags.z) | // zero\n (d1 < 0 ? 0 : CpuInterface.Flags.c); // carry / borrow\n } else {\n operand = ~operand & 0xff;\n\n const sum = state.a + operand + (state.flags & CpuInterface.Flags.c),\n result = sum & 0xff;\n\n state.flags =\n (state.flags &\n ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c | CpuInterface.Flags.v)) |\n (result & 0x80) | // negative\n (result ? 0 : CpuInterface.Flags.z) | // zero\n (sum >>> 8) | // carry / borrow\n ((~(operand ^ state.a) & (result ^ operand) & 0x80) >>> 1); // overflow\n\n state.a = result;\n }\n\n return null;\n}\n\nexport function lsrImmediate(state: CpuInterface.State): void {\n const old = state.a;\n state.a = state.a >>> 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old & CpuInterface.Flags.c);\n}\n\nexport function lsrRmw(operand: number, state: CpuInterface.State): number {\n const result = operand >>> 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (result & 0x80) |\n (result ? 0 : CpuInterface.Flags.z) |\n (operand & CpuInterface.Flags.c);\n\n return result;\n}\n\nexport function rolImmediate(state: CpuInterface.State): void {\n const old = state.a;\n state.a = ((state.a << 1) & 0xff) | (state.flags & CpuInterface.Flags.c);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old >>> 7);\n}\n\nexport function rolRmw(operand: number, state: CpuInterface.State): number {\n const result = ((operand << 1) & 0xff) | (state.flags & CpuInterface.Flags.c);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (result & 0x80) |\n (result ? 0 : CpuInterface.Flags.z) |\n (operand >>> 7);\n\n return result;\n}\n\nexport function rorImmediate(state: CpuInterface.State): void {\n const old = state.a;\n state.a = (state.a >>> 1) | ((state.flags & CpuInterface.Flags.c) << 7);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old & CpuInterface.Flags.c);\n}\n\nexport function rorRmw(operand: number, state: CpuInterface.State): number {\n const result = (operand >>> 1) | ((state.flags & CpuInterface.Flags.c) << 7);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (result & 0x80) |\n (result ? 0 : CpuInterface.Flags.z) |\n (operand & CpuInterface.Flags.c);\n\n return result;\n}\n\n// Undocumented opcodes\n\nexport function arr(operand: number, state: CpuInterface.State): void {\n state.a = ((state.a & operand) >>> 1) | (state.flags & CpuInterface.Flags.c ? 0x80 : 0);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.c | CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.v)) |\n ((state.a & 0x40) >>> 6) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (state.a & 0x80) |\n ((state.a & 0x40) ^ ((state.a & 0x20) << 1));\n}\n\nexport function alr(operand: number, state: CpuInterface.State): null {\n const i = state.a & operand;\n state.a = i >>> 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (i & CpuInterface.Flags.c);\n\n return null;\n}\n\nexport function dcp(operand: number, state: CpuInterface.State): number {\n const result = (operand + 0xff) & 0xff;\n const diff = state.a + (~result & 0xff) + 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (diff & 0x80) |\n (diff & 0xff ? 0 : CpuInterface.Flags.z) |\n (diff >>> 8);\n\n return result;\n}\n\nexport function axs(operand: number, state: CpuInterface.State): null {\n const value = (state.a & state.x) + (~operand & 0xff) + 1;\n\n state.x = value & 0xff;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.x & 0x80) |\n (state.x & 0xff ? 0 : CpuInterface.Flags.z) |\n (value >>> 8);\n\n return null;\n}\n\nexport function rra(operand: number, state: CpuInterface.State): number {\n const result = (operand >>> 1) | ((state.flags & CpuInterface.Flags.c) << 7);\n\n state.flags = (state.flags & ~CpuInterface.Flags.c) | (operand & CpuInterface.Flags.c);\n\n adc(result, state);\n\n return result;\n}\n\nexport function rla(operand: number, state: CpuInterface.State): number {\n const result = ((operand << 1) & 0xff) | (state.flags & CpuInterface.Flags.c);\n\n state.flags = (state.flags & ~CpuInterface.Flags.c) | (operand >>> 7);\n\n setFlagsNZ((state.a &= result), state);\n\n return result;\n}\n\nexport function slo(operand: number, state: CpuInterface.State): number {\n state.flags = (state.flags & ~CpuInterface.Flags.c) | (operand >>> 7);\n const result = (operand << 1) & 0xff;\n\n state.a = state.a | result;\n setFlagsNZ(state.a, state);\n\n return result;\n}\n\nexport function aax(state: CpuInterface.State): number {\n const result = state.a & state.x;\n setFlagsNZ(result, state);\n\n return result;\n}\n\nexport function isc(operand: number, state: CpuInterface.State): number {\n const result = (operand + 1) & 0xff;\n\n sbc(result, state);\n\n return result;\n}\n\nexport function aac(operand: number, state: CpuInterface.State): null {\n state.a &= operand;\n setFlagsNZ(state.a, state);\n state.flags = (state.flags & ~CpuInterface.Flags.c) | ((state.a & 0x80) >>> 7);\n\n return null;\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../../CpuInterface';\nimport ResultImpl from '../ResultImpl';\nimport StateMachineInterface from '../StateMachineInterface';\nimport { freezeImmutables, Immutable } from '../../../../tools/decorators';\nimport NextStep from './NextStep';\n\nclass Indirect implements StateMachineInterface {\n constructor(state: CpuInterface.State, next: NextStep = () => null) {\n this._state = state;\n this._next = next;\n\n freezeImmutables(this);\n }\n\n @Immutable reset = (): StateMachineInterface.Result => this._result.read(this._fetchAddressLo, this._state.p);\n\n @Immutable\n private _fetchAddressLo = (value: number): StateMachineInterface.Result => {\n this._address = value;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._fetchAddressHi, this._state.p);\n };\n\n @Immutable\n private _fetchAddressHi = (value: number): StateMachineInterface.Result => {\n this._address |= value << 8;\n this._state.p = (this._state.p + 1) & 0xffff;\n\n return this._result.read(this._fetchLo, this._address);\n };\n\n @Immutable\n private _fetchLo = (value: number): StateMachineInterface.Result => {\n this._operand = value;\n\n if ((this._address & 0xff) === 0xff) {\n this._address &= 0xff00;\n } else {\n this._address = (this._address + 1) & 0xffff;\n }\n\n return this._result.read(this._fetchHi, this._address);\n };\n\n @Immutable\n private _fetchHi = (value: number): StateMachineInterface.Result | null => {\n this._operand |= value << 8;\n\n return this._next(this._operand, this._state);\n };\n\n private _operand = 0;\n private _address = 0;\n\n @Immutable private readonly _result = new ResultImpl();\n\n @Immutable private readonly _state: CpuInterface.State;\n @Immutable private readonly _next: NextStep;\n}\n\nexport const indirect = (state: CpuInterface.State, next: NextStep) => new Indirect(state, next);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from '../CpuInterface';\nimport StateMachineInterface from './StateMachineInterface';\nimport Instruction from '../Instruction';\nimport {\n immediate,\n dereference,\n zeroPage,\n absolute,\n zeroPageX,\n zeroPageY,\n absoluteX,\n absoluteY,\n indexedIndirectX,\n indirectIndexedY\n} from './addressing';\nimport { nullaryOneCycle, readModifyWrite, jsr, push, pull, rti, rts, write, branch } from './instruction';\nimport * as ops from './ops';\nimport { indirect } from './addressing/indirect';\nimport NextStep from './addressing/NextStep';\nimport { brk } from './vector';\n\nclass Compiler {\n constructor(private readonly _state: CpuInterface.State) {}\n\n compile(op: number): StateMachineInterface | null {\n const instruction = Instruction.opcodes[op];\n\n switch (instruction.operation) {\n case Instruction.Operation.adc:\n return this._createAddressing(instruction.addressingMode, ops.adc, {\n deref: true\n });\n\n case Instruction.Operation.and:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.a = state.a & operand)),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.asl:\n return instruction.addressingMode === Instruction.AddressingMode.implied\n ? nullaryOneCycle(this._state, ops.aslImmediate)\n : this._createAddressing(\n instruction.addressingMode,\n readModifyWrite(this._state, ops.aslRmw).reset,\n { writeOp: true }\n );\n\n case Instruction.Operation.bit:\n return this._createAddressing(instruction.addressingMode, ops.bit, {\n deref: true\n });\n\n case Instruction.Operation.brk:\n return brk(this._state);\n\n case Instruction.Operation.cmp:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => (ops.cmp(o, s, state => state.a), null),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.cpx:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => (ops.cmp(o, s, state => state.x), null),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.cpy:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => (ops.cmp(o, s, state => state.y), null),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.dec:\n return this._createAddressing(\n instruction.addressingMode,\n readModifyWrite(this._state, (s, o) => ops.genRmw(s, o, x => (x - 1) & 0xff)).reset,\n {\n writeOp: true\n }\n );\n\n case Instruction.Operation.dex:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.x = (state.x - 1) & 0xff)));\n\n case Instruction.Operation.dey:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.y = (state.y - 1) & 0xff)));\n\n case Instruction.Operation.inc:\n return this._createAddressing(\n instruction.addressingMode,\n readModifyWrite(this._state, (s, o) => ops.genRmw(s, o, x => (x + 1) & 0xff)).reset,\n {\n writeOp: true\n }\n );\n\n case Instruction.Operation.inx:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.x = (state.x + 1) & 0xff)));\n\n case Instruction.Operation.iny:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.y = (state.y + 1) & 0xff)));\n\n case Instruction.Operation.eor:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.a = state.a ^ operand)),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.jmp:\n return this._createAddressing(instruction.addressingMode, (o, s) => ((s.p = o), null));\n\n case Instruction.Operation.jsr:\n return jsr(this._state);\n\n case Instruction.Operation.lda:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.a = operand)),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.ldx:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.x = operand)),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.ldy:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.y = operand)),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.lsr:\n return instruction.addressingMode === Instruction.AddressingMode.implied\n ? nullaryOneCycle(this._state, ops.lsrImmediate)\n : this._createAddressing(\n instruction.addressingMode,\n readModifyWrite(this._state, ops.lsrRmw).reset,\n { writeOp: true }\n );\n\n case Instruction.Operation.nop:\n return nullaryOneCycle(this._state, () => undefined);\n\n case Instruction.Operation.ora:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.a |= operand)),\n { deref: true }\n );\n\n case Instruction.Operation.pha:\n return push(this._state, s => s.a);\n\n case Instruction.Operation.php:\n return push(this._state, s => s.flags | CpuInterface.Flags.b);\n\n case Instruction.Operation.pla:\n return pull(this._state, (s, o) => ops.genNullary(s, state => (state.a = o)));\n\n case Instruction.Operation.plp:\n return pull(this._state, (s, o) => (s.flags = (o | CpuInterface.Flags.e) & ~CpuInterface.Flags.b));\n\n case Instruction.Operation.rol:\n return instruction.addressingMode === Instruction.AddressingMode.implied\n ? nullaryOneCycle(this._state, ops.rolImmediate)\n : this._createAddressing(\n instruction.addressingMode,\n readModifyWrite(this._state, ops.rolRmw).reset,\n { writeOp: true }\n );\n\n case Instruction.Operation.ror:\n return instruction.addressingMode === Instruction.AddressingMode.implied\n ? nullaryOneCycle(this._state, ops.rorImmediate)\n : this._createAddressing(\n instruction.addressingMode,\n readModifyWrite(this._state, ops.rorRmw).reset,\n { writeOp: true }\n );\n\n case Instruction.Operation.rti:\n return rti(this._state);\n\n case Instruction.Operation.rts:\n return rts(this._state);\n\n case Instruction.Operation.sbc:\n return this._createAddressing(instruction.addressingMode, ops.sbc, {\n deref: true\n });\n\n case Instruction.Operation.stx:\n return this._createAddressing(instruction.addressingMode, write(this._state, s => s.x).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.sty:\n return this._createAddressing(instruction.addressingMode, write(this._state, s => s.y).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.tax:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.x = state.a)));\n\n case Instruction.Operation.tay:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.y = state.a)));\n\n case Instruction.Operation.tsx:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.x = state.s)));\n\n case Instruction.Operation.txa:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.a = state.x)));\n\n case Instruction.Operation.txs:\n return nullaryOneCycle(this._state, s => (s.s = s.x));\n\n case Instruction.Operation.tya:\n return nullaryOneCycle(this._state, s => ops.genNullary(s, state => (state.a = state.y)));\n\n // Bramches\n\n case Instruction.Operation.bcc:\n return branch(this._state, flags => (flags & CpuInterface.Flags.c) === 0);\n\n case Instruction.Operation.bcs:\n return branch(this._state, flags => (flags & CpuInterface.Flags.c) > 0);\n\n case Instruction.Operation.bne:\n return branch(this._state, flags => (flags & CpuInterface.Flags.z) === 0);\n\n case Instruction.Operation.beq:\n return branch(this._state, flags => (flags & CpuInterface.Flags.z) > 0);\n\n case Instruction.Operation.bpl:\n return branch(this._state, flags => (flags & CpuInterface.Flags.n) === 0);\n\n case Instruction.Operation.bmi:\n return branch(this._state, flags => (flags & CpuInterface.Flags.n) > 0);\n\n case Instruction.Operation.bvc:\n return branch(this._state, flags => (flags & CpuInterface.Flags.v) === 0);\n\n case Instruction.Operation.bvs:\n return branch(this._state, flags => (flags & CpuInterface.Flags.v) > 0);\n\n // Flags\n\n case Instruction.Operation.sec:\n return nullaryOneCycle(this._state, s => (s.flags |= CpuInterface.Flags.c));\n\n case Instruction.Operation.sed:\n return nullaryOneCycle(this._state, s => (s.flags |= CpuInterface.Flags.d));\n\n case Instruction.Operation.sei:\n return nullaryOneCycle(this._state, s => (s.flags |= CpuInterface.Flags.i));\n\n case Instruction.Operation.sta:\n return this._createAddressing(instruction.addressingMode, write(this._state, s => s.a).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.clc:\n return nullaryOneCycle(this._state, s => (s.flags &= ~CpuInterface.Flags.c));\n\n case Instruction.Operation.cld:\n return nullaryOneCycle(this._state, s => (s.flags &= ~CpuInterface.Flags.d));\n\n case Instruction.Operation.cli:\n return nullaryOneCycle(this._state, s => (s.flags &= ~CpuInterface.Flags.i));\n\n case Instruction.Operation.clv:\n return nullaryOneCycle(this._state, s => (s.flags &= ~CpuInterface.Flags.v));\n\n // Undocumented opcodes\n\n case Instruction.Operation.dop:\n case Instruction.Operation.top:\n return this._createAddressing(instruction.addressingMode, () => null, { deref: true });\n\n case Instruction.Operation.aac:\n return this._createAddressing(instruction.addressingMode, ops.aac);\n\n case Instruction.Operation.aax:\n return this._createAddressing(instruction.addressingMode, write(this._state, ops.aax).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.alr:\n return this._createAddressing(instruction.addressingMode, ops.alr, {\n deref: true\n });\n\n case Instruction.Operation.arr:\n return this._createAddressing(instruction.addressingMode, (o, s) => (ops.arr(o, s), null), {\n deref: true\n });\n\n case Instruction.Operation.axs:\n return this._createAddressing(instruction.addressingMode, ops.axs, {\n deref: true\n });\n\n case Instruction.Operation.atx:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.x = state.a = state.a & operand)),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.dcp:\n return this._createAddressing(instruction.addressingMode, readModifyWrite(this._state, ops.dcp).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.isc:\n return this._createAddressing(instruction.addressingMode, readModifyWrite(this._state, ops.isc).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.lax:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.a = state.x = operand)),\n {\n deref: true\n }\n );\n\n case Instruction.Operation.lar:\n return this._createAddressing(\n instruction.addressingMode,\n (o, s) => ops.genUnary(o, s, (operand, state) => (state.s = state.x = state.a = state.s & operand)),\n { deref: true }\n );\n\n case Instruction.Operation.rla:\n return this._createAddressing(instruction.addressingMode, readModifyWrite(this._state, ops.rla).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.rra:\n return this._createAddressing(instruction.addressingMode, readModifyWrite(this._state, ops.rra).reset, {\n writeOp: true\n });\n\n case Instruction.Operation.slo:\n return this._createAddressing(instruction.addressingMode, readModifyWrite(this._state, ops.slo).reset, {\n writeOp: true\n });\n\n default:\n return null;\n }\n }\n\n private _createAddressing(\n addressingMode: Instruction.AddressingMode,\n next: NextStep,\n { deref = false, writeOp = false } = {}\n ): StateMachineInterface {\n if (deref && addressingMode !== Instruction.AddressingMode.immediate) {\n next = dereference(this._state, next).reset;\n }\n\n switch (addressingMode) {\n case Instruction.AddressingMode.immediate:\n return immediate(this._state, next);\n\n case Instruction.AddressingMode.zeroPage:\n return zeroPage(this._state, next);\n\n case Instruction.AddressingMode.absolute:\n return absolute(this._state, next);\n\n case Instruction.AddressingMode.zeroPageX:\n return zeroPageX(this._state, next);\n\n case Instruction.AddressingMode.zeroPageY:\n return zeroPageY(this._state, next);\n\n case Instruction.AddressingMode.absoluteX:\n return absoluteX(this._state, next, writeOp);\n\n case Instruction.AddressingMode.absoluteY:\n return absoluteY(this._state, next, writeOp);\n\n case Instruction.AddressingMode.indexedIndirectX:\n return indexedIndirectX(this._state, next);\n\n case Instruction.AddressingMode.indirectIndexedY:\n return indirectIndexedY(this._state, next, writeOp);\n\n case Instruction.AddressingMode.indirect:\n return indirect(this._state, next);\n\n default:\n throw new Error(`invalid addressing mode ${addressingMode}`);\n }\n }\n}\n\nexport default Compiler;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from './CpuInterface';\nimport StateMachineInterface from './statemachine/StateMachineInterface';\nimport BusInterface from '../bus/BusInterface';\nimport RngInterface from '../../tools/rng/GeneratorInterface';\nimport { boot, irq, nmi } from './statemachine/vector';\nimport Compiler from './statemachine/Compiler';\n\nclass StateMachineCpu implements CpuInterface {\n constructor(private _bus: BusInterface, private _rng?: RngInterface) {\n this._opBoot = boot(this.state);\n this._opIrq = irq(this.state);\n this._opNmi = nmi(this.state);\n\n const compiler = new Compiler(this.state);\n for (let op = 0; op < 256; op++) {\n this._operations[op] = compiler.compile(op);\n }\n\n this.reset();\n }\n\n reset(): this {\n this.state.a = this._rng ? this._rng.int(0xff) : 0;\n this.state.x = this._rng ? this._rng.int(0xff) : 0;\n this.state.y = this._rng ? this._rng.int(0xff) : 0;\n this.state.s = 0xfd;\n this.state.p = this._rng ? this._rng.int(0xffff) : 0;\n this.state.flags =\n (this._rng ? this._rng.int(0xff) : 0) | CpuInterface.Flags.i | CpuInterface.Flags.e | CpuInterface.Flags.b;\n this.state.irq = false;\n this.state.nmi = false;\n\n this.executionState = CpuInterface.ExecutionState.boot;\n this._interruptPending = false;\n this._nmiPending = false;\n this._halt = false;\n this._lastResult = this._opBoot.reset(undefined);\n this._lastInstructionPointer = 0;\n\n return this;\n }\n\n setInterrupt(i: boolean): this {\n this._interruptPending = i;\n\n return this;\n }\n\n isInterrupt(): boolean {\n return this._interruptPending;\n }\n\n nmi(): this {\n this._nmiPending = true;\n\n return this;\n }\n\n halt(): this {\n this._halt = true;\n\n return this;\n }\n\n resume(): this {\n this._halt = false;\n\n return this;\n }\n\n isHalt(): boolean {\n return this._halt;\n }\n\n setInvalidInstructionCallback(callback: CpuInterface.InvalidInstructionCallbackInterface): this {\n this._invalidInstructionCallback = callback;\n\n return this;\n }\n\n getInvalidInstructionCallback(): CpuInterface.InvalidInstructionCallbackInterface {\n return this._invalidInstructionCallback;\n }\n\n getLastInstructionPointer(): number {\n return this._lastInstructionPointer;\n }\n\n cycle(): this {\n if (this._halt && (!this._lastResult || this._lastResult.cycleType === StateMachineInterface.CycleType.read)) {\n return this;\n }\n\n if (this.executionState === CpuInterface.ExecutionState.fetch) {\n this._fetch();\n return this;\n }\n\n let value: number;\n\n switch (this._lastResult.cycleType) {\n case StateMachineInterface.CycleType.read:\n value = this._bus.read(this._lastResult.address);\n break;\n\n case StateMachineInterface.CycleType.write:\n value = this._lastResult.value;\n this._bus.write(this._lastResult.address, value);\n break;\n\n default:\n throw new Error('invalid cycle type');\n }\n\n if (this._lastResult.pollInterrupts) {\n this._pollInterrupts();\n\n this._lastResult.pollInterrupts = false;\n this._pollInterruptsAfterLastInstruction = false;\n }\n\n this._lastResult = this._lastResult.nextStep(value);\n if (this._lastResult === null) {\n this.executionState = CpuInterface.ExecutionState.fetch;\n }\n\n return this;\n }\n\n private _fetch(): void {\n if (this._pollInterruptsAfterLastInstruction) {\n this._pollInterrupts();\n }\n\n this._lastInstructionPointer = this.state.p;\n\n let operation: StateMachineInterface;\n const opcode = this._bus.read(this.state.p);\n\n if (this.state.nmi) {\n operation = this._opNmi;\n this._pollInterruptsAfterLastInstruction = false;\n } else if (this.state.irq) {\n operation = this._opIrq;\n this._pollInterruptsAfterLastInstruction = false;\n } else {\n operation = this._operations[opcode];\n this.state.p = (this.state.p + 1) & 0xffff;\n this._pollInterruptsAfterLastInstruction = true;\n }\n\n if (!operation) {\n if (this._invalidInstructionCallback) {\n this._invalidInstructionCallback(this);\n }\n\n return;\n }\n\n this.executionState = CpuInterface.ExecutionState.execute;\n\n this._lastResult = operation.reset(undefined);\n }\n\n private _pollInterrupts(): void {\n this.state.irq = false;\n\n if (this._nmiPending) {\n this.state.nmi = true;\n this._nmiPending = false;\n\n return;\n }\n\n if (this._interruptPending && !this.state.nmi && !(this.state.flags & CpuInterface.Flags.i)) {\n this.state.irq = true;\n }\n }\n\n executionState = CpuInterface.ExecutionState.boot;\n state = new CpuInterface.State();\n\n private _invalidInstructionCallback: CpuInterface.InvalidInstructionCallbackInterface = null;\n\n private _lastResult: StateMachineInterface.Result;\n private _interruptPending = false;\n private _nmiPending = false;\n private _halt = false;\n private _pollInterruptsAfterLastInstruction = false;\n\n private _lastInstructionPointer = 0;\n\n private _opBoot: StateMachineInterface;\n private _opNmi: StateMachineInterface;\n private _opIrq: StateMachineInterface;\n private _operations = new Array<StateMachineInterface>(255);\n}\n\nexport default StateMachineCpu;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuInterface from './CpuInterface';\nimport BusInterface from '../bus/BusInterface';\nimport Instruction from './Instruction';\n\nfunction restoreFlagsFromStack(state: CpuInterface.State, bus: BusInterface): void {\n state.s = (state.s + 0x01) & 0xff;\n state.flags = (bus.read(0x0100 + state.s) | CpuInterface.Flags.e) & ~CpuInterface.Flags.b;\n}\n\nfunction setFlagsNZ(state: CpuInterface.State, operand: number): void {\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z)) |\n (operand & 0x80) |\n (operand ? 0 : CpuInterface.Flags.z);\n}\n\nexport function opAdc(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n if (state.flags & CpuInterface.Flags.d) {\n const d0 = (operand & 0x0f) + (state.a & 0x0f) + (state.flags & CpuInterface.Flags.c),\n d1 = (operand >>> 4) + (state.a >>> 4) + (d0 > 9 ? 1 : 0);\n\n state.a = d0 % 10 | (d1 % 10 << 4);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) | // negative\n (state.a ? 0 : CpuInterface.Flags.z) | // zero\n (d1 > 9 ? CpuInterface.Flags.c : 0); // carry\n } else {\n const sum = state.a + operand + (state.flags & CpuInterface.Flags.c),\n result = sum & 0xff;\n\n state.flags =\n (state.flags &\n ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c | CpuInterface.Flags.v)) |\n (result & 0x80) | // negative\n (result ? 0 : CpuInterface.Flags.z) | // zero\n (sum >>> 8) | // carry\n ((~(operand ^ state.a) & (result ^ operand) & 0x80) >>> 1); // overflow\n\n state.a = result;\n }\n}\n\nexport function opAnd(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.a &= operand;\n setFlagsNZ(state, state.a);\n}\n\nexport function opAslAcc(state: CpuInterface.State): void {\n const old = state.a;\n state.a = (state.a << 1) & 0xff;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old >>> 7);\n}\n\nexport function opAslMem(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const old = bus.read(operand),\n value = (old << 1) & 0xff;\n bus.write(operand, value);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (value & 0x80) |\n (value ? 0 : CpuInterface.Flags.z) |\n (old >>> 7);\n}\n\nexport function opBit(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.v | CpuInterface.Flags.z)) |\n (operand & (CpuInterface.Flags.n | CpuInterface.Flags.v)) |\n (operand & state.a ? 0 : CpuInterface.Flags.z);\n}\n\nexport function opBrk(state: CpuInterface.State, bus: BusInterface): void {\n const nextOpAddr = (state.p + 1) & 0xffff;\n let vector = 0xfffe;\n\n if (state.nmi) {\n vector = 0xfffa;\n state.nmi = false;\n }\n\n state.nmi = state.irq = false;\n\n bus.write(state.s + 0x0100, (nextOpAddr >>> 8) & 0xff);\n state.s = (state.s + 0xff) & 0xff;\n bus.write(state.s + 0x0100, nextOpAddr & 0xff);\n state.s = (state.s + 0xff) & 0xff;\n\n bus.write(state.s + 0x0100, state.flags | CpuInterface.Flags.b);\n state.s = (state.s + 0xff) & 0xff;\n\n state.flags |= CpuInterface.Flags.i;\n\n state.p = bus.readWord(vector);\n}\n\nexport function opClc(state: CpuInterface.State): void {\n state.flags &= ~CpuInterface.Flags.c;\n}\n\nexport function opCld(state: CpuInterface.State): void {\n state.flags &= ~CpuInterface.Flags.d;\n}\n\nexport function opCli(state: CpuInterface.State): void {\n state.flags &= ~CpuInterface.Flags.i;\n}\n\nexport function opClv(state: CpuInterface.State): void {\n state.flags &= ~CpuInterface.Flags.v;\n}\n\nexport function opCmp(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const diff = state.a + (~operand & 0xff) + 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (diff & 0x80) |\n (diff & 0xff ? 0 : CpuInterface.Flags.z) |\n (diff >>> 8);\n}\n\nexport function opCpx(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const diff = state.x + (~operand & 0xff) + 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (diff & 0x80) |\n (diff & 0xff ? 0 : CpuInterface.Flags.z) |\n (diff >>> 8);\n}\n\nexport function opCpy(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const diff = state.y + (~operand & 0xff) + 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (diff & 0x80) |\n (diff & 0xff ? 0 : CpuInterface.Flags.z) |\n (diff >>> 8);\n}\n\nexport function opDec(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const value = (bus.read(operand) + 0xff) & 0xff;\n bus.write(operand, value);\n setFlagsNZ(state, value);\n}\n\nexport function opDex(state: CpuInterface.State): void {\n state.x = (state.x + 0xff) & 0xff;\n setFlagsNZ(state, state.x);\n}\n\nexport function opEor(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.a = state.a ^ operand;\n setFlagsNZ(state, state.a);\n}\n\nexport function opDey(state: CpuInterface.State): void {\n state.y = (state.y + 0xff) & 0xff;\n setFlagsNZ(state, state.y);\n}\n\nexport function opInc(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const value = (bus.read(operand) + 1) & 0xff;\n bus.write(operand, value);\n setFlagsNZ(state, value);\n}\n\nexport function opInx(state: CpuInterface.State): void {\n state.x = (state.x + 0x01) & 0xff;\n setFlagsNZ(state, state.x);\n}\n\nexport function opIny(state: CpuInterface.State): void {\n state.y = (state.y + 0x01) & 0xff;\n setFlagsNZ(state, state.y);\n}\n\nexport function opJmp(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.p = operand;\n}\n\nexport function opJsr(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const returnPtr = (state.p + 1) & 0xffff,\n addrLo = bus.read(state.p);\n\n bus.read(0x0100 + state.s);\n bus.write(0x0100 + state.s, returnPtr >>> 8);\n state.s = (state.s + 0xff) & 0xff;\n bus.write(0x0100 + state.s, returnPtr & 0xff);\n state.s = (state.s + 0xff) & 0xff;\n\n state.p = addrLo | (bus.read((state.p + 1) & 0xffff) << 8);\n}\n\nexport function opLda(\n state: CpuInterface.State,\n bus: BusInterface,\n operand: number,\n addressingMode: Instruction.AddressingMode\n): void {\n state.a = addressingMode === Instruction.AddressingMode.immediate ? operand : bus.read(operand);\n setFlagsNZ(state, state.a);\n}\n\nexport function opLdx(\n state: CpuInterface.State,\n bus: BusInterface,\n operand: number,\n addressingMode: Instruction.AddressingMode\n): void {\n state.x = addressingMode === Instruction.AddressingMode.immediate ? operand : bus.read(operand);\n setFlagsNZ(state, state.x);\n}\n\nexport function opLdy(\n state: CpuInterface.State,\n bus: BusInterface,\n operand: number,\n addressingMode: Instruction.AddressingMode\n): void {\n state.y = addressingMode === Instruction.AddressingMode.immediate ? operand : bus.read(operand);\n setFlagsNZ(state, state.y);\n}\n\nexport function opLsrAcc(state: CpuInterface.State): void {\n const old = state.a;\n state.a = state.a >>> 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old & CpuInterface.Flags.c);\n}\n\nexport function opLsrMem(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const old = bus.read(operand),\n value = old >>> 1;\n bus.write(operand, value);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (value & 0x80) |\n (value ? 0 : CpuInterface.Flags.z) |\n (old & CpuInterface.Flags.c);\n}\n\nexport function opNop(): void {}\n\nexport function opOra(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.a |= operand;\n setFlagsNZ(state, state.a);\n}\n\nexport function opPhp(state: CpuInterface.State, bus: BusInterface): void {\n bus.write(0x0100 + state.s, state.flags | CpuInterface.Flags.b);\n state.s = (state.s + 0xff) & 0xff;\n}\n\nexport function opPlp(state: CpuInterface.State, bus: BusInterface): void {\n restoreFlagsFromStack(state, bus);\n}\n\nexport function opPha(state: CpuInterface.State, bus: BusInterface): void {\n bus.write(0x0100 + state.s, state.a);\n state.s = (state.s + 0xff) & 0xff;\n}\n\nexport function opPla(state: CpuInterface.State, bus: BusInterface): void {\n state.s = (state.s + 0x01) & 0xff;\n state.a = bus.read(0x0100 + state.s);\n setFlagsNZ(state, state.a);\n}\n\nexport function opRolAcc(state: CpuInterface.State): void {\n const old = state.a;\n state.a = ((state.a << 1) & 0xff) | (state.flags & CpuInterface.Flags.c);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old >>> 7);\n}\n\nexport function opRolMem(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const old = bus.read(operand),\n value = ((old << 1) & 0xff) | (state.flags & CpuInterface.Flags.c);\n bus.write(operand, value);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (value & 0x80) |\n (value ? 0 : CpuInterface.Flags.z) |\n (old >>> 7);\n}\n\nexport function opRorAcc(state: CpuInterface.State): void {\n const old = state.a;\n state.a = (state.a >>> 1) | ((state.flags & CpuInterface.Flags.c) << 7);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (old & CpuInterface.Flags.c);\n}\n\nexport function opRorMem(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const old = bus.read(operand),\n value = (old >>> 1) | ((state.flags & CpuInterface.Flags.c) << 7);\n bus.write(operand, value);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (value & 0x80) |\n (value ? 0 : CpuInterface.Flags.z) |\n (old & CpuInterface.Flags.c);\n}\n\nexport function opRti(state: CpuInterface.State, bus: BusInterface): void {\n let returnPtr: number;\n\n restoreFlagsFromStack(state, bus);\n\n state.s = (state.s + 1) & 0xff;\n returnPtr = bus.read(0x0100 + state.s);\n state.s = (state.s + 1) & 0xff;\n returnPtr |= bus.read(0x0100 + state.s) << 8;\n\n state.p = returnPtr;\n}\n\nexport function opRts(state: CpuInterface.State, bus: BusInterface): void {\n let returnPtr: number;\n\n bus.read(0x0100 + state.s);\n state.s = (state.s + 1) & 0xff;\n returnPtr = bus.read(0x0100 + state.s);\n state.s = (state.s + 1) & 0xff;\n returnPtr += bus.read(0x0100 + state.s) << 8;\n\n state.p = (returnPtr + 1) & 0xffff;\n}\n\nexport function opSbc(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n if (state.flags & CpuInterface.Flags.d) {\n const d0 = (state.a & 0x0f) - (operand & 0x0f) - (~state.flags & CpuInterface.Flags.c),\n d1 = (state.a >>> 4) - (operand >>> 4) - (d0 < 0 ? 1 : 0);\n\n state.a = (d0 < 0 ? 10 + d0 : d0) | ((d1 < 0 ? 10 + d1 : d1) << 4);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) | // negative\n (state.a ? 0 : CpuInterface.Flags.z) | // zero\n (d1 < 0 ? 0 : CpuInterface.Flags.c); // carry / borrow\n } else {\n operand = ~operand & 0xff;\n\n const sum = state.a + operand + (state.flags & CpuInterface.Flags.c),\n result = sum & 0xff;\n\n state.flags =\n (state.flags &\n ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c | CpuInterface.Flags.v)) |\n (result & 0x80) | // negative\n (result ? 0 : CpuInterface.Flags.z) | // zero\n (sum >>> 8) | // carry / borrow\n ((~(operand ^ state.a) & (result ^ operand) & 0x80) >>> 1); // overflow\n\n state.a = result;\n }\n}\n\nexport function opSec(state: CpuInterface.State): void {\n state.flags |= CpuInterface.Flags.c;\n}\n\nexport function opSed(state: CpuInterface.State): void {\n state.flags |= CpuInterface.Flags.d;\n}\n\nexport function opSei(state: CpuInterface.State): void {\n state.flags |= CpuInterface.Flags.i;\n}\n\nexport function opSta(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n bus.write(operand, state.a);\n}\n\nexport function opStx(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n bus.write(operand, state.x);\n}\n\nexport function opSty(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n bus.write(operand, state.y);\n}\n\nexport function opTax(state: CpuInterface.State): void {\n state.x = state.a;\n setFlagsNZ(state, state.a);\n}\n\nexport function opTay(state: CpuInterface.State): void {\n state.y = state.a;\n setFlagsNZ(state, state.a);\n}\n\nexport function opTsx(state: CpuInterface.State): void {\n state.x = state.s;\n setFlagsNZ(state, state.x);\n}\n\nexport function opTxa(state: CpuInterface.State): void {\n state.a = state.x;\n setFlagsNZ(state, state.a);\n}\n\nexport function opTxs(state: CpuInterface.State): void {\n state.s = state.x;\n}\n\nexport function opTya(state: CpuInterface.State): void {\n state.a = state.y;\n setFlagsNZ(state, state.a);\n}\n\nexport function opAlr(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const i = state.a & operand;\n state.a = i >>> 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.a & 0x80) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (i & CpuInterface.Flags.c);\n}\n\nexport function opAxs(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const value = (state.a & state.x) + (~operand & 0xff) + 1;\n\n state.x = value & 0xff;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (state.x & 0x80) |\n (state.x & 0xff ? 0 : CpuInterface.Flags.z) |\n (value >>> 8);\n}\n\nexport function opDcp(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const value = (bus.read(operand) + 0xff) & 0xff;\n bus.write(operand, value);\n\n const diff = state.a + (~value & 0xff) + 1;\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.c)) |\n (diff & 0x80) |\n (diff & 0xff ? 0 : CpuInterface.Flags.z) |\n (diff >>> 8);\n}\n\nexport function opLax(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.a = operand;\n state.x = operand;\n setFlagsNZ(state, operand);\n}\n\nexport function opArr(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.a = ((state.a & operand) >>> 1) | (state.flags & CpuInterface.Flags.c ? 0x80 : 0);\n\n state.flags =\n (state.flags & ~(CpuInterface.Flags.c | CpuInterface.Flags.n | CpuInterface.Flags.z | CpuInterface.Flags.v)) |\n ((state.a & 0x40) >>> 6) |\n (state.a ? 0 : CpuInterface.Flags.z) |\n (state.a & 0x80) |\n ((state.a & 0x40) ^ ((state.a & 0x20) << 1));\n}\n\nexport function opSlo(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n let value = bus.read(operand);\n state.flags = (state.flags & ~CpuInterface.Flags.c) | (value >>> 7);\n value = (value << 1) & 0xff;\n\n bus.write(operand, value);\n\n state.a = state.a | value;\n setFlagsNZ(state, state.a);\n}\n\nexport function opAax(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const value = state.x & state.a;\n bus.write(operand, value);\n setFlagsNZ(state, value);\n}\n\nexport function opLar(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.s = state.a = state.x = state.s & operand;\n setFlagsNZ(state, state.a);\n}\n\nexport function opIsc(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const value = (bus.read(operand) + 1) & 0xff;\n bus.write(operand, value);\n\n opSbc(state, bus, value);\n}\n\nexport function opAac(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.a &= operand;\n setFlagsNZ(state, state.a);\n state.flags = (state.flags & ~CpuInterface.Flags.c) | ((state.a & 0x80) >>> 7);\n}\n\nexport function opAtx(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n state.a &= operand;\n state.x = state.a;\n setFlagsNZ(state, state.a);\n}\n\nexport function opRra(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const old = bus.read(operand),\n value = (old >>> 1) | ((state.flags & CpuInterface.Flags.c) << 7);\n bus.write(operand, value);\n\n state.flags = (state.flags & ~CpuInterface.Flags.c) | (old & CpuInterface.Flags.c);\n\n opAdc(state, bus, value);\n}\n\nexport function opRla(state: CpuInterface.State, bus: BusInterface, operand: number): void {\n const old = bus.read(operand),\n value = ((old << 1) & 0xff) | (state.flags & CpuInterface.Flags.c);\n bus.write(operand, value);\n\n state.flags = (state.flags & ~CpuInterface.Flags.c) | (old >>> 7);\n\n opAnd(state, bus, value);\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Instruction from './Instruction';\nimport BusInterface from '../bus/BusInterface';\nimport CpuInterface from './CpuInterface';\nimport * as ops from './ops';\n\nimport RngInterface from '../../tools/rng/GeneratorInterface';\n\nconst enum InterruptCheck {\n endOfInstruction,\n beforeOp\n}\nexport function opBoot(state: CpuInterface.State, bus: BusInterface): void {\n state.p = bus.readWord(0xfffc);\n}\n\nfunction dispatchInterrupt(state: CpuInterface.State, bus: BusInterface, vector: number): void {\n const nextOpAddr = state.p;\n\n if (state.nmi) {\n vector = 0xfffa;\n }\n\n state.nmi = state.irq = false;\n\n bus.write(state.s + 0x0100, (nextOpAddr >>> 8) & 0xff);\n state.s = (state.s + 0xff) & 0xff;\n bus.write(state.s + 0x0100, nextOpAddr & 0xff);\n state.s = (state.s + 0xff) & 0xff;\n\n bus.write(state.s + 0x0100, state.flags & ~CpuInterface.Flags.b);\n state.s = (state.s + 0xff) & 0xff;\n\n state.flags |= CpuInterface.Flags.i;\n\n state.p = bus.readWord(vector);\n}\n\nexport function opIrq(state: CpuInterface.State, bus: BusInterface) {\n dispatchInterrupt(state, bus, 0xfffe);\n}\n\nexport function opNmi(state: CpuInterface.State, bus: BusInterface) {\n dispatchInterrupt(state, bus, 0xfffa);\n}\n\nclass BatchedAccessCpu {\n constructor(private _bus: BusInterface, private _rng?: RngInterface) {\n this.reset();\n }\n\n setInterrupt(irq: boolean): BatchedAccessCpu {\n this._interruptPending = irq;\n return this;\n }\n\n isInterrupt(): boolean {\n return this._interruptPending;\n }\n\n nmi(): BatchedAccessCpu {\n this._nmiPending = true;\n return this;\n }\n\n halt(): BatchedAccessCpu {\n this._halted = true;\n return this;\n }\n\n resume(): BatchedAccessCpu {\n this._halted = false;\n return this;\n }\n\n isHalt(): boolean {\n return this._halted;\n }\n\n setInvalidInstructionCallback(callback: CpuInterface.InvalidInstructionCallbackInterface): BatchedAccessCpu {\n this._invalidInstructionCallback = callback;\n return this;\n }\n\n getInvalidInstructionCallback(): CpuInterface.InvalidInstructionCallbackInterface {\n return this._invalidInstructionCallback;\n }\n\n getLastInstructionPointer(): number {\n return this._lastInstructionPointer;\n }\n\n reset(): BatchedAccessCpu {\n this.state.a = this._rng ? this._rng.int(0xff) : 0;\n this.state.x = this._rng ? this._rng.int(0xff) : 0;\n this.state.y = this._rng ? this._rng.int(0xff) : 0;\n this.state.s = 0xfd;\n this.state.p = this._rng ? this._rng.int(0xffff) : 0;\n this.state.flags =\n (this._rng ? this._rng.int(0xff) : 0) | CpuInterface.Flags.i | CpuInterface.Flags.e | CpuInterface.Flags.b;\n this.state.irq = false;\n this.state.nmi = false;\n\n this.executionState = CpuInterface.ExecutionState.boot;\n this._opCycles = 7;\n this._interruptPending = false;\n this._nmiPending = false;\n\n this._instructionCallback = opBoot;\n\n return this;\n }\n\n cycle(): BatchedAccessCpu {\n if (this._halted) {\n return this;\n }\n\n switch (this.executionState) {\n case CpuInterface.ExecutionState.boot:\n case CpuInterface.ExecutionState.execute:\n if (--this._opCycles === 0) {\n if (this._dereference) {\n this._operand = this._bus.read(this._operand);\n }\n\n if (this._interuptCheck === InterruptCheck.beforeOp) {\n this._checkForInterrupts();\n }\n\n this._instructionCallback(this.state, this._bus, this._operand, this._currentAddressingMode);\n this.executionState = CpuInterface.ExecutionState.fetch;\n\n if (this._interuptCheck === InterruptCheck.endOfInstruction) {\n this._checkForInterrupts();\n }\n }\n\n break;\n\n case CpuInterface.ExecutionState.fetch:\n if (this.state.nmi) {\n this._instructionCallback = opNmi;\n this._opCycles = 6;\n this.state.nmi = this.state.irq = false;\n this._interuptCheck = InterruptCheck.beforeOp;\n this.executionState = CpuInterface.ExecutionState.execute;\n\n return this;\n }\n\n if (this.state.irq) {\n this._instructionCallback = opIrq;\n this._opCycles = 6;\n this.state.nmi = this.state.irq = false;\n this._interuptCheck = InterruptCheck.beforeOp;\n this.executionState = CpuInterface.ExecutionState.execute;\n\n return this;\n }\n\n this._fetch();\n break;\n }\n\n return this;\n }\n\n private _fetch() {\n const instruction = Instruction.opcodes[this._bus.read(this.state.p)];\n\n let addressingMode = instruction.addressingMode,\n dereference = false,\n slowIndexedAccess = false;\n\n this._lastInstructionPointer = this.state.p;\n this._currentAddressingMode = addressingMode;\n this._interuptCheck = InterruptCheck.endOfInstruction;\n\n switch (instruction.operation) {\n case Instruction.Operation.adc:\n this._opCycles = 0;\n this._instructionCallback = ops.opAdc;\n dereference = true;\n break;\n\n case Instruction.Operation.and:\n this._opCycles = 0;\n this._instructionCallback = ops.opAnd;\n dereference = true;\n break;\n\n case Instruction.Operation.asl:\n if (addressingMode === Instruction.AddressingMode.implied) {\n this._opCycles = 1;\n this._instructionCallback = ops.opAslAcc;\n } else {\n this._opCycles = 3;\n this._instructionCallback = ops.opAslMem;\n slowIndexedAccess = true;\n }\n break;\n\n case Instruction.Operation.bcc:\n if (this.state.flags & CpuInterface.Flags.c) {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n } else {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n }\n break;\n\n case Instruction.Operation.bcs:\n if (this.state.flags & CpuInterface.Flags.c) {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n } else {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n }\n break;\n\n case Instruction.Operation.beq:\n if (this.state.flags & CpuInterface.Flags.z) {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n } else {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n }\n break;\n\n case Instruction.Operation.bit:\n this._opCycles = 0;\n this._instructionCallback = ops.opBit;\n dereference = true;\n break;\n\n case Instruction.Operation.bmi:\n if (this.state.flags & CpuInterface.Flags.n) {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n } else {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n }\n break;\n\n case Instruction.Operation.bne:\n if (this.state.flags & CpuInterface.Flags.z) {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n } else {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n }\n break;\n\n case Instruction.Operation.bpl:\n if (this.state.flags & CpuInterface.Flags.n) {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n } else {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n }\n break;\n\n case Instruction.Operation.bvc:\n if (this.state.flags & CpuInterface.Flags.v) {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n } else {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n }\n break;\n\n case Instruction.Operation.bvs:\n if (this.state.flags & CpuInterface.Flags.v) {\n this._instructionCallback = ops.opJmp;\n this._opCycles = 0;\n } else {\n addressingMode = Instruction.AddressingMode.implied;\n this._instructionCallback = ops.opNop;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles = 1;\n }\n break;\n\n case Instruction.Operation.brk:\n this._opCycles = 6;\n this._instructionCallback = ops.opBrk;\n this._interuptCheck = InterruptCheck.beforeOp;\n break;\n\n case Instruction.Operation.clc:\n this._opCycles = 1;\n this._instructionCallback = ops.opClc;\n break;\n\n case Instruction.Operation.cld:\n this._opCycles = 1;\n this._instructionCallback = ops.opCld;\n break;\n\n case Instruction.Operation.cli:\n this._opCycles = 1;\n this._instructionCallback = ops.opCli;\n this._interuptCheck = InterruptCheck.beforeOp;\n break;\n\n case Instruction.Operation.clv:\n this._opCycles = 1;\n this._instructionCallback = ops.opClv;\n break;\n\n case Instruction.Operation.cmp:\n this._opCycles = 0;\n this._instructionCallback = ops.opCmp;\n dereference = true;\n break;\n\n case Instruction.Operation.cpx:\n this._opCycles = 0;\n this._instructionCallback = ops.opCpx;\n dereference = true;\n break;\n\n case Instruction.Operation.cpy:\n this._opCycles = 0;\n this._instructionCallback = ops.opCpy;\n dereference = true;\n break;\n\n case Instruction.Operation.dec:\n this._opCycles = 3;\n this._instructionCallback = ops.opDec;\n slowIndexedAccess = true;\n break;\n\n case Instruction.Operation.dex:\n this._opCycles = 1;\n this._instructionCallback = ops.opDex;\n break;\n\n case Instruction.Operation.dey:\n this._opCycles = 1;\n this._instructionCallback = ops.opDey;\n break;\n\n case Instruction.Operation.eor:\n this._opCycles = 0;\n this._instructionCallback = ops.opEor;\n dereference = true;\n break;\n\n case Instruction.Operation.inc:\n this._opCycles = 3;\n this._instructionCallback = ops.opInc;\n slowIndexedAccess = true;\n break;\n\n case Instruction.Operation.inx:\n this._opCycles = 1;\n this._instructionCallback = ops.opInx;\n break;\n\n case Instruction.Operation.iny:\n this._opCycles = 1;\n this._instructionCallback = ops.opIny;\n break;\n\n case Instruction.Operation.jmp:\n this._opCycles = 0;\n this._instructionCallback = ops.opJmp;\n break;\n\n case Instruction.Operation.jsr:\n this._opCycles = 5;\n this._instructionCallback = ops.opJsr;\n break;\n\n case Instruction.Operation.lda:\n this._opCycles = addressingMode === Instruction.AddressingMode.immediate ? 0 : 1;\n this._instructionCallback = ops.opLda;\n break;\n\n case Instruction.Operation.ldx:\n this._opCycles = addressingMode === Instruction.AddressingMode.immediate ? 0 : 1;\n this._instructionCallback = ops.opLdx;\n break;\n\n case Instruction.Operation.ldy:\n this._opCycles = addressingMode === Instruction.AddressingMode.immediate ? 0 : 1;\n this._instructionCallback = ops.opLdy;\n break;\n\n case Instruction.Operation.lsr:\n if (addressingMode === Instruction.AddressingMode.implied) {\n this._opCycles = 1;\n this._instructionCallback = ops.opLsrAcc;\n } else {\n this._opCycles = 3;\n this._instructionCallback = ops.opLsrMem;\n slowIndexedAccess = true;\n }\n break;\n\n case Instruction.Operation.nop:\n this._opCycles = 1;\n\n this._instructionCallback = ops.opNop;\n break;\n\n case Instruction.Operation.dop:\n case Instruction.Operation.top:\n this._opCycles = 0;\n dereference = true;\n\n this._instructionCallback = ops.opNop;\n break;\n\n case Instruction.Operation.ora:\n this._opCycles = 0;\n this._instructionCallback = ops.opOra;\n dereference = true;\n break;\n\n case Instruction.Operation.php:\n this._opCycles = 2;\n this._instructionCallback = ops.opPhp;\n break;\n\n case Instruction.Operation.pha:\n this._opCycles = 2;\n this._instructionCallback = ops.opPha;\n break;\n\n case Instruction.Operation.pla:\n this._opCycles = 3;\n this._instructionCallback = ops.opPla;\n break;\n\n case Instruction.Operation.plp:\n this._opCycles = 3;\n this._instructionCallback = ops.opPlp;\n this._interuptCheck = InterruptCheck.beforeOp;\n break;\n\n case Instruction.Operation.rol:\n if (addressingMode === Instruction.AddressingMode.implied) {\n this._opCycles = 1;\n this._instructionCallback = ops.opRolAcc;\n } else {\n this._opCycles = 3;\n this._instructionCallback = ops.opRolMem;\n slowIndexedAccess = true;\n }\n break;\n\n case Instruction.Operation.ror:\n if (addressingMode === Instruction.AddressingMode.implied) {\n this._opCycles = 1;\n this._instructionCallback = ops.opRorAcc;\n } else {\n this._opCycles = 3;\n this._instructionCallback = ops.opRorMem;\n slowIndexedAccess = true;\n }\n break;\n\n case Instruction.Operation.rti:\n this._opCycles = 5;\n this._instructionCallback = ops.opRti;\n break;\n\n case Instruction.Operation.rts:\n this._opCycles = 5;\n this._instructionCallback = ops.opRts;\n break;\n\n case Instruction.Operation.sbc:\n this._opCycles = 0;\n this._instructionCallback = ops.opSbc;\n dereference = true;\n break;\n\n case Instruction.Operation.sec:\n this._opCycles = 1;\n this._instructionCallback = ops.opSec;\n break;\n\n case Instruction.Operation.sed:\n this._opCycles = 1;\n this._instructionCallback = ops.opSed;\n break;\n\n case Instruction.Operation.sei:\n this._opCycles = 1;\n this._instructionCallback = ops.opSei;\n this._interuptCheck = InterruptCheck.beforeOp;\n break;\n\n case Instruction.Operation.sta:\n this._opCycles = 1;\n this._instructionCallback = ops.opSta;\n slowIndexedAccess = true;\n break;\n\n case Instruction.Operation.stx:\n this._opCycles = 1;\n this._instructionCallback = ops.opStx;\n slowIndexedAccess = true;\n break;\n\n case Instruction.Operation.sty:\n this._opCycles = 1;\n this._instructionCallback = ops.opSty;\n slowIndexedAccess = true;\n break;\n\n case Instruction.Operation.tax:\n this._opCycles = 1;\n this._instructionCallback = ops.opTax;\n break;\n\n case Instruction.Operation.tay:\n this._opCycles = 1;\n this._instructionCallback = ops.opTay;\n break;\n\n case Instruction.Operation.tsx:\n this._opCycles = 1;\n this._instructionCallback = ops.opTsx;\n break;\n\n case Instruction.Operation.txa:\n this._opCycles = 1;\n this._instructionCallback = ops.opTxa;\n break;\n\n case Instruction.Operation.txs:\n this._opCycles = 1;\n this._instructionCallback = ops.opTxs;\n break;\n\n case Instruction.Operation.tya:\n this._opCycles = 1;\n this._instructionCallback = ops.opTya;\n break;\n\n case Instruction.Operation.arr:\n this._opCycles = 0;\n this._instructionCallback = ops.opArr;\n break;\n\n case Instruction.Operation.alr:\n this._opCycles = 0;\n this._instructionCallback = ops.opAlr;\n break;\n\n case Instruction.Operation.axs:\n this._opCycles = 0;\n this._instructionCallback = ops.opAxs;\n break;\n\n case Instruction.Operation.dcp:\n this._opCycles = 3;\n this._instructionCallback = ops.opDcp;\n slowIndexedAccess = true;\n break;\n\n case Instruction.Operation.lax:\n this._opCycles = 0;\n this._instructionCallback = ops.opLax;\n dereference = true;\n break;\n\n case Instruction.Operation.slo:\n this._opCycles = 3;\n this._instructionCallback = ops.opSlo;\n slowIndexedAccess = true;\n dereference = false;\n break;\n\n case Instruction.Operation.aax:\n this._opCycles = 1;\n this._instructionCallback = ops.opAax;\n break;\n\n case Instruction.Operation.lar:\n this._opCycles = 0;\n this._instructionCallback = ops.opLar;\n dereference = true;\n break;\n\n case Instruction.Operation.isc:\n this._opCycles = 3;\n this._instructionCallback = ops.opIsc;\n slowIndexedAccess = true;\n break;\n\n case Instruction.Operation.aac:\n this._opCycles = 0;\n this._instructionCallback = ops.opAac;\n break;\n\n case Instruction.Operation.atx:\n this._opCycles = 0;\n this._instructionCallback = ops.opAtx;\n break;\n\n case Instruction.Operation.rra:\n this._opCycles = 3;\n dereference = false;\n slowIndexedAccess = true;\n this._instructionCallback = ops.opRra;\n break;\n\n case Instruction.Operation.rla:\n this._opCycles = 3;\n dereference = false;\n slowIndexedAccess = true;\n this._instructionCallback = ops.opRla;\n break;\n\n default:\n if (this._invalidInstructionCallback) {\n this._invalidInstructionCallback(this);\n }\n return;\n }\n\n this.state.p = (this.state.p + 1) & 0xffff;\n\n let value: number, base: number;\n\n switch (addressingMode) {\n case Instruction.AddressingMode.immediate:\n this._operand = this._bus.read(this.state.p);\n dereference = false;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles++;\n break;\n\n case Instruction.AddressingMode.zeroPage:\n this._operand = this._bus.read(this.state.p);\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles++;\n break;\n\n case Instruction.AddressingMode.absolute:\n this._operand = this._bus.readWord(this.state.p);\n this.state.p = (this.state.p + 2) & 0xffff;\n this._opCycles += 2;\n break;\n\n case Instruction.AddressingMode.indirect:\n value = this._bus.readWord(this.state.p);\n if ((value & 0xff) === 0xff) {\n this._operand = this._bus.read(value) + (this._bus.read(value & 0xff00) << 8);\n } else {\n this._operand = this._bus.readWord(value);\n }\n this.state.p = (this.state.p + 2) & 0xffff;\n this._opCycles += 4;\n break;\n\n case Instruction.AddressingMode.relative:\n value = this._bus.read(this.state.p);\n value = value & 0x80 ? -(~(value - 1) & 0xff) : value;\n this._operand = (this.state.p + value + 0x10001) & 0xffff;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles += (this._operand & 0xff00) !== (this.state.p & 0xff00) ? 3 : 2;\n break;\n\n case Instruction.AddressingMode.zeroPageX:\n base = this._bus.read(this.state.p);\n this._bus.read(base);\n\n this._operand = (base + this.state.x) & 0xff;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles += 2;\n break;\n\n case Instruction.AddressingMode.absoluteX:\n value = this._bus.readWord(this.state.p);\n this._operand = (value + this.state.x) & 0xffff;\n\n if ((this._operand & 0xff00) !== (value & 0xff00)) {\n this._bus.read((value & 0xff00) | (this._operand & 0xff));\n }\n\n this._opCycles += slowIndexedAccess || (this._operand & 0xff00) !== (value & 0xff00) ? 3 : 2;\n this.state.p = (this.state.p + 2) & 0xffff;\n break;\n\n case Instruction.AddressingMode.zeroPageY:\n base = this._bus.read(this.state.p);\n this._bus.read(base);\n\n this._operand = (base + this.state.y) & 0xff;\n this.state.p = (this.state.p + 1) & 0xffff;\n this._opCycles += 2;\n break;\n\n case Instruction.AddressingMode.absoluteY:\n value = this._bus.readWord(this.state.p);\n this._operand = (value + this.state.y) & 0xffff;\n\n if ((this._operand & 0xff00) !== (value & 0xff00)) {\n this._bus.read((value & 0xff00) | (this._operand & 0xff));\n }\n\n this._opCycles += slowIndexedAccess || (this._operand & 0xff00) !== (value & 0xff00) ? 3 : 2;\n this.state.p = (this.state.p + 2) & 0xffff;\n break;\n\n case Instruction.AddressingMode.indexedIndirectX:\n base = this._bus.read(this.state.p);\n this._bus.read(base);\n\n value = (base + this.state.x) & 0xff;\n\n if (value === 0xff) {\n this._operand = this._bus.read(0xff) + (this._bus.read(0x00) << 8);\n } else {\n this._operand = this._bus.readWord(value);\n }\n\n this._opCycles += 4;\n this.state.p = (this.state.p + 1) & 0xffff;\n break;\n\n case Instruction.AddressingMode.indirectIndexedY:\n value = this._bus.read(this.state.p);\n\n if (value === 0xff) {\n value = this._bus.read(0xff) + (this._bus.read(0x00) << 8);\n } else {\n value = this._bus.readWord(value);\n }\n\n this._operand = (value + this.state.y) & 0xffff;\n\n if ((this._operand & 0xff00) !== (value & 0xff00)) {\n this._bus.read((value & 0xff00) | (this._operand & 0xff));\n }\n\n this._opCycles += slowIndexedAccess || (value & 0xff00) !== (this._operand & 0xff00) ? 4 : 3;\n this.state.p = (this.state.p + 1) & 0xffff;\n break;\n }\n\n this._dereference = dereference;\n if (dereference) {\n this._opCycles++;\n }\n\n this.executionState = CpuInterface.ExecutionState.execute;\n }\n\n private _checkForInterrupts(): void {\n if (this._nmiPending) {\n this.state.irq = false;\n this.state.nmi = true;\n this._nmiPending = false;\n }\n\n if (this._interruptPending && !this.state.nmi && !(this.state.flags & CpuInterface.Flags.i)) {\n this.state.irq = true;\n }\n }\n\n executionState: CpuInterface.ExecutionState = CpuInterface.ExecutionState.boot;\n state: CpuInterface.State = new CpuInterface.State();\n\n private _opCycles: number = 0;\n private _instructionCallback: InstructionCallbackInterface = null;\n private _invalidInstructionCallback: CpuInterface.InvalidInstructionCallbackInterface = null;\n\n private _interruptPending: boolean = false;\n private _nmiPending: boolean = false;\n private _interuptCheck = InterruptCheck.endOfInstruction;\n\n private _halted: boolean = false;\n\n private _operand: number = 0;\n private _lastInstructionPointer: number = 0;\n private _currentAddressingMode: Instruction.AddressingMode = Instruction.AddressingMode.invalid;\n\n private _dereference = false;\n}\n\ninterface InstructionCallbackInterface {\n (\n state?: CpuInterface.State,\n bus?: BusInterface,\n operand?: number,\n addressingMode?: Instruction.AddressingMode\n ): void;\n}\n\nexport { BatchedAccessCpu as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport RngInterface from '../../tools/rng/GeneratorInterface';\nimport BusInterface from '../bus/BusInterface';\nimport CpuInterface from './CpuInterface';\nimport StateMachineCpu from './StateMachineCpu';\nimport BatchedAccessCpu from './BatchedAccessCpu';\n\nclass Factory {\n constructor(private _type: Factory.Type) {}\n\n create(bus: BusInterface, rng?: RngInterface): CpuInterface {\n switch (this._type) {\n case Factory.Type.stateMachine:\n return new StateMachineCpu(bus, rng);\n\n case Factory.Type.batchedAccess:\n return new BatchedAccessCpu(bus, rng);\n\n default:\n throw new Error('invalid CPU type');\n }\n }\n}\n\nnamespace Factory {\n export enum Type {\n stateMachine,\n batchedAccess\n }\n}\n\nexport default Factory;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport CpuFactory from '../cpu/Factory';\n\ninterface Config {\n tvMode: Config.TvMode;\n enableAudio: boolean;\n randomSeed: number;\n emulatePaddles: boolean;\n frameStart: number;\n pcmAudio: boolean;\n cpuType: CpuFactory.Type;\n}\n\nnamespace Config {\n export const enum TvMode {\n ntsc,\n pal,\n secam\n }\n\n export function create(config: Partial<Config> = {}): Config {\n return {\n tvMode: TvMode.ntsc,\n enableAudio: true,\n randomSeed: -1,\n emulatePaddles: true,\n frameStart: -1,\n pcmAudio: false,\n cpuType: CpuFactory.Type.stateMachine,\n\n ...config\n };\n }\n\n export function getClockHz(config: Config): number {\n switch (config.tvMode) {\n case Config.TvMode.ntsc:\n return 262 * 228 * 60;\n\n case Config.TvMode.pal:\n case Config.TvMode.secam:\n return 312 * 228 * 50;\n }\n }\n}\n\nexport { Config as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nclass AudioOutputBuffer {\n constructor(private _content: Float32Array, private _sampleRate: number) {}\n\n getLength(): number {\n return this._content.length;\n }\n\n getContent(): Float32Array {\n return this._content;\n }\n\n getSampleRate(): number {\n return this._sampleRate;\n }\n\n replaceUnderlyingBuffer(buffer: Float32Array): void {\n this._content = buffer;\n }\n}\n\nexport { AudioOutputBuffer as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst encodingsString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n encodings = new Uint8Array(256);\n\nexport namespace __init {\n let i: number;\n\n for (i = 0; i < 256; i++) {\n encodings[i] = 255;\n }\n for (i = 0; i < 64; i++) {\n encodings[encodingsString.charCodeAt(i)] = i;\n }\n\n encodings['='.charCodeAt(0)] = 0;\n}\n\nfunction decodeChar(data: string, idx: number): number {\n const value = encodings[data.charCodeAt(idx)];\n\n if (value > 63) {\n throw new Error('invalid base64 character \"' + data[idx] + '\" at index ' + idx);\n }\n\n return value;\n}\n\nfunction decodeNibble(data: string, idx: number): number {\n return (\n (decodeChar(data, idx) << 18) +\n (decodeChar(data, idx + 1) << 12) +\n (decodeChar(data, idx + 2) << 6) +\n decodeChar(data, idx + 3)\n );\n}\n\nfunction getPadding(data: string): number {\n let padding = 0,\n idx = data.length - 1;\n\n while (idx >= 0 && data[idx--] === '=') {\n padding++;\n }\n\n return padding;\n}\n\nexport function decode(data: string): Uint8Array {\n if (data.length % 4 !== 0) {\n throw new Error('invalid base64 data --- char count mismatch');\n }\n\n const nibbles = data.length / 4,\n decodedSize = nibbles * 3 - getPadding(data),\n decoded = new Uint8Array(decodedSize);\n\n let idx = 0;\n\n for (let i = 0; i < nibbles; i++) {\n const nibble = decodeNibble(data, i * 4);\n\n for (let j = 0; j < 3 && idx < decodedSize; j++) {\n decoded[idx++] = (nibble >>> (8 * (2 - j))) & 0xff;\n }\n }\n\n return decoded;\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/*\n * The tone generator has been heavily influenced by the code found at\n * http://www.biglist.com/lists/stella/archives/200311/msg00156.html with following licence:\n *\n * sound.c\n * version 0.2\n *\n * Copyright (c) 2003 Adam Wozniak (adam@wozniakconsulting.com)\n * All Rights Reserved\n *\n * Permission granted to freely copy and use for any purpose, provided\n * this copyright header remains intact.\n */\nimport Config from '../Config';\nimport AudioOutputBuffer from '../../../tools/AudioOutputBuffer';\nimport { decode as decodeBase64 } from '../../../tools/base64';\n\nconst FREQUENCY_DIVISIORS = decodeBase64('AQEPAQEBAQEBAQEBAwMDAQ==');\n\n// all ones\nconst POLY0 = new Int8Array([1]);\n\n// 50% duty cycle\nconst POLY1 = new Int8Array([1, 1]);\n\n// 16/31 duty cycle\nconst POLY2 = new Int8Array([16, 15]);\n\n// 4 bit LFSR\nconst POLY4 = decodeBase64('AQICAQEBBAM=');\n\n// 5 bit LFSR\nconst POLY5 = decodeBase64('AQIBAQICBQQCAQMBAQEBBA==');\n\n// 9 bit LFSR\nconst POLY9 = decodeBase64(\n 'AQQBAwIEAQIDAgEBAQEBAQIEAgEEAQECAgEDAgEDAQEBBAEBAQECAQECBgECAgECAQIBAQIBBg' +\n 'IBAgIBAQEBAgICAgcCAwICAQEBAwIBAQIBAQcBAQMBAQIDAwEBAQICAQECAgQDBQEDAQEFAgEB' +\n 'AQIBAgEDAQIFAQECAQEBBQEBAQEBAQEBBgEBAQIBAQEBBAIBAQMBAwYDAgMBAQIBAgQBAQEDAQ' +\n 'EBAQMBAgEEAgIDBAEBBAECAQICAgEBBAMBBAQJBQQBBQMBAQMCAgIBBQECAQEBAgMBAgEBAwQC' +\n 'BQICAQIDAQEBAQECAQMDAwIBAgEBAQEBAwMBAgIDAQMBCA=='\n);\n\n// used by mode 15\nconst POLY68 = decodeBase64('BQYEBQoFAwcECgYDBgQJBg==');\n\n// used by mode 3\nconst POLY465 = decodeBase64(\n 'AgMCAQQBBgoCBAIBAQQFCQMDBAEBAQgFBQUEAQEBCAQCCAMDAQEHBAIHBQEDAQcEAQQIAgEDBA' +\n 'cBAwcDAgEGBgICBAUDAgYGAQMDAgUDBwMEAwICAgUJAwEFAwECAgsFAQUDAQECDAUBAgUCAQEM' +\n 'BgECBQECAQoGAwICBAECBgo='\n);\n\nconst POLYS = [\n POLY0,\n POLY4,\n POLY4,\n POLY465,\n POLY1,\n POLY1,\n POLY2,\n POLY5,\n POLY9,\n POLY5,\n POLY2,\n POLY0,\n POLY1,\n POLY1,\n POLY2,\n POLY68\n];\n\nclass ToneGenerator {\n constructor(private _config?: Config) {}\n\n setConfig(config: Config) {\n this._config = config;\n }\n\n getKey(tone: number, frequency: number): number {\n // Hack: this is at the boundary of hearing anyway and causes nasty artifacts during\n // resampling, so we kill it right away.\n if (POLYS[tone] === POLY1 && FREQUENCY_DIVISIORS[tone] * (frequency + 1) === 1) {\n return 0;\n }\n\n return (tone << 5) | frequency;\n }\n\n getBuffer(key: number): AudioOutputBuffer {\n const tone = (key >>> 5) & 0x0f,\n frequency = key & 0x1f;\n\n const poly = POLYS[tone];\n\n let length = 0;\n for (let i = 0; i < poly.length; i++) {\n length += poly[i];\n }\n\n length = length * FREQUENCY_DIVISIORS[tone] * (frequency + 1);\n\n const content = new Float32Array(length);\n\n const sampleRate = Config.getClockHz(this._config) / 114;\n\n let f = 0;\n let count = 0;\n let offset = 0;\n let state = true;\n\n for (let i = 0; i < length; i++) {\n f++;\n\n if (f === FREQUENCY_DIVISIORS[tone] * (frequency + 1)) {\n f = 0;\n count++;\n\n if (count === poly[offset]) {\n offset++;\n count = 0;\n\n if (poly.length === offset) {\n offset = 0;\n }\n }\n\n state = !(offset & 0x01);\n }\n\n content[i] = state ? 1 : -1;\n }\n\n return new AudioOutputBuffer(content, sampleRate);\n }\n}\n\nexport { ToneGenerator as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport { RpcProviderInterface } from 'worker-rpc';\nimport WaveformAudioOutputInterface from '../../../../machine/io/WaveformAudioOutputInterface';\nimport ToneGenerator from '../../../../machine/stella/tia/ToneGenerator';\nimport StellaConfig from '../../../../machine/stella/Config';\nimport AudioOutputBuffer from '../../../../tools/AudioOutputBuffer';\n\nimport {\n SIGNAL_TYPE,\n RPC_TYPE,\n WaveformAudioBufferChangeMessage,\n WaveformAudioVolumeChangeMessage,\n WaveformAudioParametersResponse\n} from './messages';\n\nclass WaveformAudioProxy implements WaveformAudioOutputInterface {\n constructor(private _index: number, private _rpc: RpcProviderInterface) {}\n\n init(): this {\n this._rpc\n .registerSignalHandler(SIGNAL_TYPE.waveformAudioBufferChange, this._onBufferChangeSignal.bind(this))\n .registerSignalHandler(SIGNAL_TYPE.waveformAudioVolumeChange, this._onVolumeChangeSignal.bind(this))\n .registerSignalHandler(SIGNAL_TYPE.audioStop, this._onStopSignal.bind(this));\n\n return this;\n }\n\n async start(config: StellaConfig): Promise<void> {\n const parameters = await this._rpc.rpc<void, WaveformAudioParametersResponse>(\n RPC_TYPE.getWaveformAudioParameters(this._index)\n );\n\n this._toneGenerator.setConfig(config);\n this.setVolume(parameters.volume);\n }\n\n setVolume(value: number): this {\n this._volume = value;\n\n return this;\n }\n\n getVolume(): number {\n return this._volume;\n }\n\n getBuffer(key: number): AudioOutputBuffer {\n return this._toneGenerator.getBuffer(key);\n }\n\n private _onVolumeChangeSignal(message: WaveformAudioVolumeChangeMessage): void {\n if (message.index === this._index) {\n this._volume = message.value;\n this.volumeChanged.dispatch(this._volume);\n }\n }\n\n private _onBufferChangeSignal(message: WaveformAudioBufferChangeMessage): void {\n if (message.index === this._index) {\n this.bufferChanged.dispatch(message.key);\n }\n }\n\n private _onStopSignal(index: number): void {\n if (index === this._index) {\n this.stop.dispatch(undefined);\n }\n }\n\n bufferChanged = new Event<number>();\n volumeChanged = new Event<number>();\n stop = new Event<void>();\n\n private _toneGenerator = new ToneGenerator();\n private _volume = 0;\n}\n\nexport { WaveformAudioProxy as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { RpcProviderInterface } from 'worker-rpc';\nimport { Event } from 'microevent.ts';\n\nimport Pool from '../../../../tools/pool/Pool';\nimport PoolMemberInterface from '../../../../tools/pool/PoolMemberInterface';\nimport PCMAudioEndpointInterface from '../../../driver/PCMAudioEndpointInterface';\nimport {\n SIGNAL_TYPE,\n RPC_TYPE,\n PCMAudioReturnFrameMessage,\n PCMAudioNewFrameMessage,\n PCMAudioTogglePauseMessage,\n PCMAudioParametersResponse\n} from './messages';\n\nclass PCMAudioProxy implements PCMAudioEndpointInterface {\n constructor(private _index: number, private _rpc: RpcProviderInterface) {\n this._framePool.event.release.addHandler(PCMAudioProxy._onReleaseFragment, this);\n\n this._signalReturnFrame = SIGNAL_TYPE.pcmAudioReturnFrame(this._index);\n }\n\n init(): this {\n this._rpc\n .registerSignalHandler(SIGNAL_TYPE.pcmAudioNewFrame(this._index), this._onNewFrame.bind(this))\n .registerSignalHandler(SIGNAL_TYPE.pcmAudioTogglePause(this._index), this._onTogglePause.bind(this));\n\n return this;\n }\n\n async start(): Promise<void> {\n if (this._enabled) {\n return;\n }\n\n const params = await this._rpc.rpc<void, PCMAudioParametersResponse>(\n RPC_TYPE.getPCMAudioParameters(this._index)\n );\n\n this._sampleRate = params.sampleRate;\n this._frameSize = params.frameSize;\n this._paused = params.paused;\n\n this._enabled = true;\n }\n\n stop(): void {\n this._enabled = false;\n }\n\n isPaused(): boolean {\n return this._paused;\n }\n\n getSampleRate(): number {\n return this._sampleRate;\n }\n\n getFrameSize(): number {\n return this._frameSize;\n }\n\n private static _onReleaseFragment(frame: Float32Array, self: PCMAudioProxy): void {\n if (!self._frameMap.has(frame)) {\n return;\n }\n\n self._rpc.signal<PCMAudioReturnFrameMessage>(\n self._signalReturnFrame,\n {\n id: self._frameMap.get(frame),\n buffer: frame.buffer\n },\n [frame.buffer]\n );\n }\n\n private _onNewFrame(msg: PCMAudioNewFrameMessage): void {\n if (!this._enabled) {\n return;\n }\n\n const frame = this._framePool.get(),\n data = new Float32Array(msg.buffer);\n\n frame.adopt(data);\n this._frameMap.set(data, msg.id);\n\n this.newFrame.dispatch(frame);\n }\n\n private _onTogglePause(msg: PCMAudioTogglePauseMessage): void {\n if (msg.paused === this._paused) {\n return;\n }\n\n this._paused = msg.paused;\n this.togglePause.dispatch(this._paused);\n }\n\n newFrame = new Event<PoolMemberInterface<Float32Array>>();\n\n togglePause = new Event<boolean>();\n\n private _sampleRate = 0;\n private _frameSize = 0;\n private _paused = false;\n\n private _framePool = new Pool<Float32Array>(() => null);\n private _frameMap = new WeakMap<Float32Array, number>();\n\n private _enabled = false;\n\n private _signalReturnFrame = '';\n}\n\nexport { PCMAudioProxy as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport AsyncIOInterface from '../../../../machine/io/AsyncIOInterface';\nimport { RpcProviderInterface } from 'worker-rpc';\nimport { SIGNAL_TYPE, MessageToAsyncIOMessage } from './messages';\nimport { Event } from 'microevent.ts';\n\nclass AsyncIOProxy implements AsyncIOInterface {\n constructor(private _rpc: RpcProviderInterface) {}\n\n init(): void {\n this._rpc.registerSignalHandler<Array<number>>(SIGNAL_TYPE.messageFromAsyncIO, data =>\n this.message.dispatch(data)\n );\n }\n\n send(message: ArrayLike<number>): void {\n this._rpc.signal<MessageToAsyncIOMessage>(SIGNAL_TYPE.messageToAsyncIO, Array.from(message));\n }\n\n message = new Event<Array<number>>();\n}\n\nexport default AsyncIOProxy;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\nimport { RpcProvider } from 'worker-rpc';\n\nimport EmulationServiceInterface from '../EmulationServiceInterface';\nimport EmulationContext from './EmulationContext';\nimport EmulationContextInterface from '../EmulationContextInterface';\nimport VideoProxy from './VideoProxy';\nimport ControlProxy from './ControlProxy';\nimport WaveformAudioProxy from './WaveformAudioProxy';\nimport PCMAudioProxy from './PCMAudioProxy';\n\nimport CartridgeInfo from '../../../../machine/stella/cartridge/CartridgeInfo';\n\nimport { Mutex } from 'async-mutex';\n\nimport { RPC_TYPE, SIGNAL_TYPE, EmulationStartMessage } from './messages';\nimport AsyncIOProxy from './AsyncIOProxy';\n\nconst CONTROL_PROXY_UPDATE_INTERVAL = 25;\n\nconst enum ProxyState {\n stopped,\n running,\n paused\n}\n\nclass EmulationService implements EmulationServiceInterface {\n constructor(private _stellaWorkerUri: string) {}\n\n async init(): Promise<void> {\n this._worker = new Worker(this._stellaWorkerUri);\n this._rpc = new RpcProvider((message, transfer?) => this._worker.postMessage(message, transfer));\n\n this._pcmChannel = new PCMAudioProxy(0, this._rpc).init();\n\n for (let i = 0; i < 2; i++) {\n this._waveformChannels[i] = new WaveformAudioProxy(i, this._rpc).init();\n }\n\n const videoProxy = new VideoProxy(this._rpc),\n controlProxy = new ControlProxy(this._rpc),\n asyncIOProxy = new AsyncIOProxy(this._rpc);\n\n asyncIOProxy.init();\n videoProxy.init();\n\n this._emulationContext = new EmulationContext(\n videoProxy,\n controlProxy,\n this._waveformChannels,\n this._pcmChannel,\n asyncIOProxy\n );\n\n this._worker.onmessage = messageEvent => this._rpc.dispatch(messageEvent.data);\n\n this._rpc\n .registerSignalHandler<number>(SIGNAL_TYPE.emulationFrequencyUpdate, this._onFrequencyUpdate.bind(this))\n .registerSignalHandler<string>(SIGNAL_TYPE.emulationError, this._onEmulationError.bind(this));\n\n this._controlProxy = controlProxy;\n }\n\n async start(\n buffer: { [i: number]: number; length: number },\n config: EmulationServiceInterface.Config,\n cartridgeType?: CartridgeInfo.CartridgeType\n ): Promise<EmulationServiceInterface.State> {\n await this.stop();\n\n return this._mutex.runExclusive(async () => {\n const state = await this._rpc.rpc<EmulationStartMessage, EmulationServiceInterface.State>(\n RPC_TYPE.emulationStart,\n {\n buffer,\n config,\n cartridgeType\n }\n );\n\n if (state === EmulationServiceInterface.State.paused) {\n this._savedConfig = config;\n this._emulationContext.setConfig(config);\n\n await this._startProxies(config);\n } else {\n this._savedConfig = null;\n }\n\n return this._applyState(state);\n });\n }\n\n pause(): Promise<EmulationServiceInterface.State> {\n return this._mutex.runExclusive(() =>\n this._rpc.rpc<void, EmulationServiceInterface.State>(RPC_TYPE.emulationPause).then(state => {\n this._pauseProxies();\n return this._applyState(state);\n })\n );\n }\n\n stop(): Promise<EmulationServiceInterface.State> {\n return this._mutex.runExclusive(() =>\n this._rpc.rpc<void, EmulationServiceInterface.State>(RPC_TYPE.emulationStop).then(state => {\n this._stopProxies();\n return this._applyState(state);\n })\n );\n }\n\n reset(): Promise<EmulationServiceInterface.State> {\n return this._mutex.runExclusive(async () => {\n const state = await this._rpc.rpc<void, EmulationServiceInterface.State>(RPC_TYPE.emulationReset);\n\n // Try to restart the proxies if the reset recovered from an an error\n if (\n this._state === EmulationServiceInterface.State.error &&\n (state === EmulationServiceInterface.State.running ||\n state === EmulationServiceInterface.State.paused) &&\n this._savedConfig\n ) {\n await this._startProxies(this._savedConfig);\n }\n\n return this._applyState(state);\n });\n }\n\n resume(): Promise<EmulationServiceInterface.State> {\n return this._mutex.runExclusive(() =>\n this._rpc.rpc<void, EmulationServiceInterface.State>(RPC_TYPE.emulationResume).then(state => {\n this._resumeProxies();\n return this._applyState(state);\n })\n );\n }\n\n setRateLimit(enforce: boolean): Promise<void> {\n this._rateLimitEnforced = enforce;\n\n return this._rpc.rpc<boolean, void>(RPC_TYPE.emulationSetRateLimit, enforce);\n }\n\n getFrequency(): number {\n return this._frequency;\n }\n\n getRateLimit(): boolean {\n return this._rateLimitEnforced;\n }\n\n getState(): EmulationServiceInterface.State {\n return this._state;\n }\n\n getLastError(): Error {\n return this._lastError;\n }\n\n getEmulationContext(): EmulationContextInterface {\n switch (this._state) {\n case EmulationServiceInterface.State.running:\n case EmulationServiceInterface.State.paused:\n return this._emulationContext;\n\n default:\n return null;\n }\n }\n\n private _fetchLastError(): Promise<Error> {\n return this._rpc\n .rpc<void, string>(RPC_TYPE.emulationFetchLastError)\n .then(message => (message ? new Error(message) : null));\n }\n\n private _applyState(\n state: EmulationServiceInterface.State\n ): Promise<EmulationServiceInterface.State> | EmulationServiceInterface.State {\n if (state === EmulationServiceInterface.State.error) {\n return this._fetchLastError().then(error => {\n this._state = state;\n this._lastError = error;\n\n this._stopProxies();\n\n this.stateChanged.dispatch(state);\n\n return state;\n });\n } else {\n this._state = state;\n this.stateChanged.dispatch(state);\n\n return state;\n }\n }\n\n private _onFrequencyUpdate(message: number): void {\n this._frequency = message;\n this.frequencyUpdate.dispatch(this._frequency);\n }\n\n private _onEmulationError(message: string): void {\n this._lastError = new Error(message || '');\n\n this._stopProxies();\n this._state = EmulationServiceInterface.State.error;\n this.stateChanged.dispatch(this._state);\n }\n\n private async _startProxies(config: EmulationServiceInterface.Config): Promise<void> {\n await this._emulationContext.getVideoProxy().start();\n\n for (let i = 0; i < this._waveformChannels.length; i++) {\n await this._waveformChannels[i].start(config);\n }\n await this._pcmChannel.start();\n\n this._startControlUpdates();\n\n this._proxyState = ProxyState.running;\n }\n\n private _stopProxies(): void {\n if (this._proxyState === ProxyState.stopped) {\n return;\n }\n\n this._emulationContext.getVideoProxy().stop();\n this._pcmChannel.stop();\n this._stopControlUpdates();\n\n this._proxyState = ProxyState.stopped;\n }\n\n private _pauseProxies(): void {\n if (this._proxyState !== ProxyState.running) {\n return;\n }\n\n this._stopControlUpdates();\n\n this._proxyState = ProxyState.paused;\n }\n\n private _resumeProxies(): void {\n if (this._proxyState !== ProxyState.paused) {\n return;\n }\n\n this._startControlUpdates();\n\n this._proxyState = ProxyState.running;\n }\n\n private _startControlUpdates(): void {\n if (this._controlProxyUpdateHandle === null) {\n this._controlProxyUpdateHandle = setInterval(\n () => this._controlProxy.sendUpdate(),\n CONTROL_PROXY_UPDATE_INTERVAL\n );\n }\n }\n\n private _stopControlUpdates(): void {\n if (this._controlProxyUpdateHandle !== null) {\n clearInterval(this._controlProxyUpdateHandle);\n this._controlProxyUpdateHandle = null;\n }\n }\n\n stateChanged = new Event<EmulationServiceInterface.State>();\n frequencyUpdate = new Event<number>();\n\n private _rateLimitEnforced = true;\n\n private _mutex = new Mutex();\n private _worker: Worker = null;\n private _rpc: RpcProvider = null;\n\n private _state = EmulationServiceInterface.State.stopped;\n private _lastError: Error = null;\n\n private _emulationContext: EmulationContext = null;\n private _frequency = 0;\n\n private _waveformChannels = new Array<WaveformAudioProxy>(2);\n private _pcmChannel: PCMAudioProxy = null;\n\n private _controlProxy: ControlProxy = null;\n private _controlProxyUpdateHandle: any = null;\n private _proxyState = ProxyState.stopped;\n\n private _savedConfig: EmulationServiceInterface.Config = null;\n}\n\nexport { EmulationService as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport EmulationServiceInterface from './EmulationServiceInterface';\nimport EmulationContextInterface from './EmulationContextInterface';\n\nclass DriverManager {\n bind(emulationService: EmulationServiceInterface): this {\n if (this._driversBound) {\n return this;\n }\n\n this._emulationService = emulationService;\n\n if (this._shouldBindDrivers()) {\n this._bindDrivers();\n }\n\n this._emulationService.stateChanged.addHandler(DriverManager._onEmuStateChange, this);\n\n return this;\n }\n\n unbind(): this {\n if (!this._emulationService) {\n return this;\n }\n\n this._unbindDrivers();\n\n this._emulationService.stateChanged.removeHandler(DriverManager._onEmuStateChange, this);\n\n this._emulationService = null;\n\n return this;\n }\n\n addDriver(driver: DriverManager.Driver, binder: DriverManager.Binder): this {\n this._drivers.set(driver, new DriverManager.DriverContext(driver, binder));\n\n if (this._driversBound) {\n binder(this._emulationService.getEmulationContext(), driver);\n }\n\n return this;\n }\n\n removeDriver(driver: DriverManager.Driver): this {\n if (!this._drivers.get(driver)) {\n return this;\n }\n\n driver.unbind();\n\n this._drivers.delete(driver);\n\n return this;\n }\n\n private static _onEmuStateChange(newState: EmulationServiceInterface.State, self: DriverManager): void {\n if (self._shouldBindDrivers(newState)) {\n self._bindDrivers();\n } else {\n self._unbindDrivers();\n }\n }\n\n private _shouldBindDrivers(\n state = this._emulationService ? this._emulationService.getState() : undefined\n ): boolean {\n return (\n this._emulationService &&\n (state === EmulationServiceInterface.State.running || state === EmulationServiceInterface.State.paused)\n );\n }\n\n private _bindDrivers(): void {\n if (this._driversBound) {\n return;\n }\n\n this._drivers.forEach(driverContext =>\n driverContext.binder(this._emulationService.getEmulationContext(), driverContext.driver)\n );\n\n this._driversBound = true;\n }\n\n private _unbindDrivers(): void {\n if (!this._driversBound) {\n return;\n }\n\n this._drivers.forEach(driverContext => driverContext.driver.unbind());\n\n this._driversBound = false;\n }\n\n private _emulationService: EmulationServiceInterface;\n private _drivers = new Map<DriverManager.Driver, DriverManager.DriverContext>();\n private _driversBound = false;\n}\n\nnamespace DriverManager {\n export interface Driver {\n unbind(): void;\n }\n\n export interface Binder {\n (context: EmulationContextInterface, driver: Driver): void;\n }\n\n export class DriverContext {\n constructor(public driver: Driver, public binder: Binder) {}\n }\n}\n\nexport { DriverManager as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Capabilities } from './Capabilities';\n\nfunction precisionFsh(capabilities: Capabilities): string {\n return `precision ${capabilities.highpInVsh ? 'highp' : 'mediump'} float;`;\n}\n\nfunction precisionVsh(capabilities: Capabilities): string {\n return `precision ${capabilities.highpInVsh ? 'highp' : 'mediump'} float;`;\n}\n\nexport namespace vsh {\n export namespace plain {\n export const source = (capabilities: Capabilities) => `\n ${precisionVsh(capabilities)}\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 `;\n\n export const enum attribute {\n vertexPosition = 'a_VertexPosition',\n textureCoordinate = 'a_TextureCoordinate'\n }\n }\n}\n\nexport namespace fsh {\n export namespace blit {\n export const source = (capabilities: Capabilities) => `\n ${precisionFsh(capabilities)}\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 `;\n\n export const enum uniform {\n textureUnit = 'u_Sampler0'\n }\n }\n\n export namespace blitWithGamma {\n export const source = (capabilities: Capabilities) => `\n ${precisionFsh(capabilities)}\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 `;\n\n export const enum uniform {\n textureUnit = 'u_Sampler0',\n gamma = 'u_Gamma'\n }\n }\n\n export namespace phosphor {\n export const source = (capabilities: Capabilities) => `\n ${precisionFsh(capabilities)}\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 `;\n\n export const enum uniform {\n level = 'u_PhosphorLevel',\n textureUnitNew = 'u_Sampler_NewImage',\n textureUnitPrevious = 'u_Sampler_PreviousImage'\n }\n }\n\n export namespace ntscPass1 {\n export const source = (capabilities: Capabilities) => `\n ${precisionFsh(capabilities)}\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 ${\n capabilities.floatTextures || capabilities.halfFloatTextures\n ? ''\n : `\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\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 = ${\n capabilities.floatTextures || capabilities.halfFloatTextures ? 'vec4(yiq, 1.0)' : 'pack(yiq)'\n };\n }\n `;\n\n export const enum uniform {\n textureUnit = 'u_Sampler0',\n artifacting = 'u_Artifacting',\n fringing = 'u_Fringing'\n }\n }\n\n export namespace ntscPass2 {\n const lumaFilter = [\n 0.00001202,\n 0.000022146,\n 0.000013155,\n 0.00001202,\n 0.000049979,\n 0.00011394,\n 0.00012215,\n 0.000005612,\n 0.000170516,\n 0.000237199,\n 0.00016964,\n 0.000285688,\n 0.000984574,\n 0.002018683,\n 0.002002275,\n -0.000909882,\n -0.007049081,\n -0.01322286,\n -0.012606931,\n 0.00246086,\n 0.035868225,\n 0.084016453,\n 0.1355635,\n 0.175261268,\n 0.190176552\n ];\n\n const chromaFilter = [\n 0.000118847,\n 0.000271306,\n 0.000502642,\n 0.000930833,\n 0.001451013,\n 0.002064744,\n 0.002700432,\n 0.003241276,\n 0.003524948,\n -0.003350284,\n -0.002491729,\n -0.000721149,\n 0.002164659,\n 0.006313635,\n 0.011789103,\n 0.01854566,\n 0.026414396,\n 0.03510071,\n 0.044196567,\n 0.053207202,\n 0.061590275,\n 0.068803602,\n 0.074356193,\n 0.077856564,\n 0.079052396\n ];\n\n function maybeUnpack(capabilities: Capabilities, expr: string): string {\n return capabilities.floatTextures || capabilities.halfFloatTextures ? `${expr}.rgb` : `unpack(${expr})`;\n }\n\n export const source = (capabilities: Capabilities) => `\n ${precisionFsh(capabilities)}\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 ${\n capabilities.floatTextures || capabilities.halfFloatTextures\n ? ''\n : `\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\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 ${maybeUnpack(capabilities, '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)\n .fill(0)\n .map(\n (_, i) => `\n signal +=\n (fetch_offset(${i - 24}) + fetch_offset(${24 - i})) *\n vec3(${lumaFilter[i]}, ${chromaFilter[i]}, ${chromaFilter[i]});\n `\n )\n .join('\\n')}\n\n signal += ${maybeUnpack(capabilities, 'texture2D(u_Sampler0, v_TextureCoordinate)')} *\n vec3(${lumaFilter[24]}, ${chromaFilter[24]}, ${chromaFilter[24]});\n\n vec3 rgb = yiq2rgb(signal);\n gl_FragColor = vec4(rgb, 1.0);\n }\n `;\n\n export const enum uniform {\n textureUnit = 'u_Sampler0'\n }\n }\n\n export namespace scanlines {\n export const source = (capabilities: Capabilities) => `\n ${precisionFsh(capabilities)}\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 `;\n\n export const enum uniform {\n textureUnit = 'u_Sampler0',\n level = 'u_Level',\n height = 'u_Height'\n }\n }\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nfunction compileShader(gl: WebGLRenderingContext, type: GLenum, source: string): WebGLShader {\n const shader = gl.createShader(type);\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n throw new Error(`failed to compile shader:\\n\\n${gl.getShaderInfoLog(shader)}\\n\\n${source}`);\n }\n\n return shader;\n}\n\nclass Program {\n private constructor(\n private _gl: WebGLRenderingContext,\n private _program: WebGLProgram,\n private _vsh: WebGLShader,\n private _fsh: WebGLShader\n ) {}\n\n static compile(\n gl: WebGLRenderingContext,\n vshSource: string,\n fshSource: string,\n layout: Record<string, number> = { a_VertexPosition: 0 }\n ): Program {\n const vsh = compileShader(gl, gl.VERTEX_SHADER, vshSource);\n const fsh = compileShader(gl, gl.FRAGMENT_SHADER, fshSource);\n const program = gl.createProgram();\n\n for (const attrib of Object.keys(layout)) {\n gl.bindAttribLocation(program, layout[attrib], attrib);\n }\n\n gl.attachShader(program, vsh);\n gl.attachShader(program, fsh);\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n throw new Error(`failed to link program:\\n\\n${gl.getProgramInfoLog(program)}`);\n }\n\n return new Program(gl, program, vsh, fsh);\n }\n\n delete(): void {\n const gl = this._gl;\n\n gl.deleteProgram(this._program);\n gl.deleteShader(this._vsh);\n gl.deleteShader(this._fsh);\n }\n\n use(): void {\n this._gl.useProgram(this._program);\n }\n\n getAttribLocation(name: string): number {\n if (!this._attributeLocations.has(name)) {\n const location = this._gl.getAttribLocation(this._program, name);\n\n if (location < 0) {\n throw new Error(`invalid attribute ${name}`);\n }\n\n this._attributeLocations.set(name, location);\n }\n\n return this._attributeLocations.get(name);\n }\n\n getUniformLocation(name: string): WebGLUniformLocation {\n if (!this._uniformLocations.has(name)) {\n const location = this._gl.getUniformLocation(this._program, name);\n\n if (location === null) {\n throw new Error(`invalid uniform ${name}`);\n }\n\n this._uniformLocations.set(name, location);\n }\n\n return this._uniformLocations.get(name);\n }\n\n bindVertexAttribArray(\n attribute: string,\n buffer: WebGLBuffer,\n size: number,\n type: number,\n normalized: boolean,\n stride: number,\n offset: number\n ): void {\n const gl = this._gl;\n\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.vertexAttribPointer(this.getAttribLocation(attribute), size, type, normalized, stride, offset);\n gl.enableVertexAttribArray(this.getAttribLocation(attribute));\n }\n\n uniform1i(uniform: string, value: number) {\n this._gl.uniform1i(this.getUniformLocation(uniform), value);\n }\n\n uniform1f(uniform: string, value: number) {\n this._gl.uniform1f(this.getUniformLocation(uniform), value);\n }\n\n private _attributeLocations = new Map<string, number>();\n private _uniformLocations = new Map<string, WebGLUniformLocation>();\n}\n\nexport default Program;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Processor from './Processor';\nimport Program from './Program';\nimport { vsh, fsh } from './shader';\nimport { Capabilities } from './Capabilities';\n\nclass PhosphorProcessor implements Processor {\n constructor(private _gl: WebGLRenderingContext, private _capabilities: Capabilities) {}\n\n init(): void {\n if (this._initialized) return;\n\n const gl = this._gl;\n\n this._framebuffer = gl.createFramebuffer();\n this._program = Program.compile(\n gl,\n vsh.plain.source(this._capabilities),\n fsh.phosphor.source(this._capabilities)\n );\n\n this._program.use();\n this._program.uniform1i(fsh.phosphor.uniform.textureUnitNew, 0);\n this._program.uniform1i(fsh.phosphor.uniform.textureUnitPrevious, 1);\n\n this._vertexCoordinateBuffer = gl.createBuffer();\n this._textureCoordinateBuffer = gl.createBuffer();\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._textureCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW);\n\n this._initialized = true;\n }\n\n destroy(): void {\n if (!this._initialized) return;\n\n const gl = this._gl;\n\n this._program.delete();\n gl.deleteFramebuffer(this._framebuffer);\n gl.deleteBuffer(this._vertexCoordinateBuffer);\n gl.deleteBuffer(this._textureCoordinateBuffer);\n\n if (this._texture0) gl.deleteTexture(this._texture0);\n if (this._texture1) gl.deleteTexture(this._texture1);\n\n this._initialized = false;\n }\n\n render(texture: WebGLTexture): void {\n const gl = this._gl;\n\n this._program.use();\n\n this._program.bindVertexAttribArray(\n vsh.plain.attribute.vertexPosition,\n this._vertexCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n this._program.bindVertexAttribArray(\n vsh.plain.attribute.textureCoordinate,\n this._textureCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, this._texture0);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._texture1, 0);\n\n gl.viewport(0, 0, this._width, this._height);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n\n const t = this._texture1;\n this._texture1 = this._texture0;\n this._texture0 = t;\n }\n\n getWidth(): number {\n return this._width;\n }\n\n getHeight(): number {\n return this._height;\n }\n\n getTexture(): WebGLTexture {\n return this._texture0;\n }\n\n resize(width: number, height: number): void {\n if (!this._initialized) return;\n\n this._width = width;\n this._height = height;\n\n const gl = this._gl;\n\n if (this._texture0) gl.deleteTexture(this._texture0);\n if (this._texture1) gl.deleteTexture(this._texture1);\n\n this._texture0 = gl.createTexture();\n this._texture1 = gl.createTexture();\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer);\n gl.viewport(0, 0, width, height);\n gl.clearColor(0, 0, 0, 1);\n gl.activeTexture(gl.TEXTURE0);\n\n for (const texture of [this._texture0, this._texture1]) {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n }\n }\n\n configure(level: number) {\n if (!this._initialized) return;\n\n this._program.use();\n this._program.uniform1f(fsh.phosphor.uniform.level, level);\n }\n\n private _width = 0;\n private _height = 0;\n\n private _texture0: WebGLTexture = null;\n private _texture1: WebGLTexture = null;\n private _framebuffer: WebGLFramebuffer = null;\n private _program: Program = null;\n private _vertexCoordinateBuffer: WebGLBuffer = null;\n private _textureCoordinateBuffer: WebGLBuffer = null;\n\n private _initialized = false;\n}\n\nexport default PhosphorProcessor;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Processor from './Processor';\nimport Program from './Program';\nimport { vsh, fsh } from './shader';\nimport { Capabilities } from './Capabilities';\n\nclass NtscProcessor implements Processor {\n constructor(private _gl: WebGLRenderingContext, private _capabilities: Capabilities) {}\n\n init(): void {\n if (this._initialized) return;\n\n const gl = this._gl;\n\n gl.getExtension('WEBGL_color_buffer_float');\n gl.getExtension('OES_texture_float');\n\n this._programPass1 = Program.compile(\n gl,\n vsh.plain.source(this._capabilities),\n fsh.ntscPass1.source(this._capabilities)\n );\n this._programPass2 = Program.compile(\n gl,\n vsh.plain.source(this._capabilities),\n fsh.ntscPass2.source(this._capabilities)\n );\n\n this._programPass1.use();\n this._programPass1.uniform1i(fsh.ntscPass1.uniform.textureUnit, 0);\n\n this._programPass2.use();\n this._programPass2.uniform1i(fsh.ntscPass2.uniform.textureUnit, 0);\n\n this._framebuffer = gl.createFramebuffer();\n\n this._vertexCoordinateBuffer = gl.createBuffer();\n this._textureCoordinateBuffer = gl.createBuffer();\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._textureCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW);\n\n this._initialized = true;\n }\n\n destroy(): void {\n if (!this._initialized) return;\n\n const gl = this._gl;\n\n this._programPass1.delete();\n this._programPass2.delete();\n\n gl.deleteFramebuffer(this._framebuffer);\n\n gl.deleteTexture(this._targetPass1);\n gl.deleteTexture(this._targetPass2);\n\n gl.deleteBuffer(this._vertexCoordinateBuffer);\n gl.deleteBuffer(this._textureCoordinateBuffer);\n\n this._initialized = false;\n }\n\n render(texture: WebGLTexture): void {\n this._pass(texture, this._targetPass1, this._programPass1, 960);\n this._pass(this._targetPass1, this._targetPass2, this._programPass2, 480);\n }\n\n getWidth(): number {\n return 480;\n }\n\n getHeight(): number {\n return this._height;\n }\n\n getTexture(): WebGLTexture {\n return this._targetPass2;\n }\n\n resize(width: number, height: number): void {\n if (!this._initialized) return;\n\n if (width !== 160) {\n throw new Error('NTSC postprocessor supports only for width = 160');\n }\n\n this._height = height;\n\n const gl = this._gl;\n\n if (this._targetPass1) gl.deleteTexture(this._targetPass1);\n if (this._targetPass2) gl.deleteTexture(this._targetPass2);\n\n this._targetPass1 = gl.createTexture();\n this._targetPass2 = gl.createTexture();\n\n gl.activeTexture(gl.TEXTURE0);\n\n for (const texture of [this._targetPass1, this._targetPass2]) {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n texture === this._targetPass1 ? 960 : 480,\n height,\n 0,\n gl.RGBA,\n texture === this._targetPass1 ? this._textureType() : gl.UNSIGNED_BYTE,\n null\n );\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n }\n }\n\n configure(mode: NtscProcessor.mode) {\n if (!this._initialized) return;\n\n this._programPass1.use();\n\n if (mode === NtscProcessor.mode.composite) {\n this._programPass1.uniform1f(fsh.ntscPass1.uniform.artifacting, 1);\n this._programPass1.uniform1f(fsh.ntscPass1.uniform.fringing, 1);\n } else {\n this._programPass1.uniform1f(fsh.ntscPass1.uniform.artifacting, 0);\n this._programPass1.uniform1f(fsh.ntscPass1.uniform.fringing, 0);\n }\n }\n\n private _pass(textureIn: WebGLTexture, textureOut: WebGLTexture, program: Program, width: number): void {\n const gl = this._gl;\n\n program.use();\n\n program.bindVertexAttribArray(\n vsh.plain.attribute.vertexPosition,\n this._vertexCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n program.bindVertexAttribArray(\n vsh.plain.attribute.textureCoordinate,\n this._textureCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, textureIn);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureOut, 0);\n\n gl.viewport(0, 0, width, this._height);\n\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n }\n\n private _textureType(): number {\n const gl = this._gl;\n\n if (this._capabilities.floatTextures) {\n return gl.FLOAT;\n }\n\n if (this._capabilities.halfFloatTextures) {\n return gl.getExtension('OES_texture_half_float').HALF_FLOAT_OES;\n }\n\n return gl.UNSIGNED_BYTE;\n }\n\n private _height = 0;\n\n private _programPass1: Program = null;\n private _programPass2: Program = null;\n private _targetPass1: WebGLTexture = null;\n private _targetPass2: WebGLTexture = null;\n private _framebuffer: WebGLFramebuffer = null;\n private _vertexCoordinateBuffer: WebGLBuffer = null;\n private _textureCoordinateBuffer: WebGLBuffer = null;\n\n private _initialized = false;\n}\n\nnamespace NtscProcessor {\n export const enum mode {\n composite = 'composite',\n svideo = 'svideo'\n }\n}\n\nexport default NtscProcessor;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Processor from './Processor';\nimport Program from './Program';\nimport { fsh, vsh } from './shader';\nimport { Capabilities } from './Capabilities';\n\nclass ScanlineProcessor implements Processor {\n constructor(private _gl: WebGLRenderingContext, private _capabilities: Capabilities) {}\n\n init(): void {\n if (this._initialized) return;\n\n const gl = this._gl;\n\n this._framebuffer = gl.createFramebuffer();\n this._program = Program.compile(\n gl,\n vsh.plain.source(this._capabilities),\n fsh.scanlines.source(this._capabilities)\n );\n\n this._program.use();\n this._program.uniform1i(fsh.scanlines.uniform.textureUnit, 0);\n\n this._vertexCoordinateBuffer = gl.createBuffer();\n this._textureCoordinateBuffer = gl.createBuffer();\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._textureCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW);\n\n this._initialized = true;\n }\n\n destroy(): void {\n if (!this._initialized) return;\n\n const gl = this._gl;\n\n this._program.delete();\n gl.deleteFramebuffer(this._framebuffer);\n gl.deleteBuffer(this._vertexCoordinateBuffer);\n gl.deleteBuffer(this._textureCoordinateBuffer);\n\n if (this._texture) gl.deleteTexture(this._texture);\n\n this._initialized = false;\n }\n\n render(texture: WebGLTexture): void {\n const gl = this._gl;\n\n this._program.use();\n\n this._program.bindVertexAttribArray(\n vsh.plain.attribute.vertexPosition,\n this._vertexCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n this._program.bindVertexAttribArray(\n vsh.plain.attribute.textureCoordinate,\n this._textureCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._texture, 0);\n\n gl.viewport(0, 0, this._width, 2 * this._height);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n }\n\n getWidth(): number {\n return this._width;\n }\n\n getHeight(): number {\n return 2 * this._height;\n }\n\n getTexture(): WebGLTexture {\n return this._texture;\n }\n\n resize(width: number, height: number): void {\n if (!this._initialized) return;\n\n this._width = width;\n this._height = height;\n\n const gl = this._gl;\n\n if (this._texture) gl.deleteTexture(this._texture);\n this._texture = gl.createTexture();\n\n gl.activeTexture(gl.TEXTURE0);\n\n gl.bindTexture(gl.TEXTURE_2D, this._texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, 2 * height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n this._program.use();\n this._program.uniform1f(fsh.scanlines.uniform.height, 2 * this._height);\n }\n\n configure(level: number): void {\n if (!this._initialized) return;\n\n this._program.use();\n this._program.uniform1f(fsh.scanlines.uniform.level, 1 - level);\n }\n\n private _width = 0;\n private _height = 0;\n\n private _texture: WebGLTexture = null;\n private _program: Program = null;\n private _framebuffer: WebGLFramebuffer = null;\n private _vertexCoordinateBuffer: WebGLBuffer = null;\n private _textureCoordinateBuffer: WebGLBuffer = null;\n\n private _initialized = false;\n}\n\nexport default ScanlineProcessor;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Processor from './Processor';\nimport Program from './Program';\nimport { fsh, vsh } from './shader';\nimport { Capabilities } from './Capabilities';\n\nclass IntegerScalingProcessor implements Processor {\n constructor(private _gl: WebGLRenderingContext, private _capabilities: Capabilities) {}\n\n init(): void {\n if (this._initialized) return;\n\n const gl = this._gl;\n\n this._framebuffer = gl.createFramebuffer();\n this._program = Program.compile(gl, vsh.plain.source(this._capabilities), fsh.blit.source(this._capabilities));\n\n this._program.use();\n this._program.uniform1i(fsh.blit.uniform.textureUnit, 0);\n\n this._vertexCoordinateBuffer = gl.createBuffer();\n this._textureCoordinateBuffer = gl.createBuffer();\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this._textureCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW);\n\n this._initialized = true;\n }\n\n destroy(): void {\n if (!this._initialized) return;\n\n const gl = this._gl;\n\n this._program.delete();\n gl.deleteFramebuffer(this._framebuffer);\n gl.deleteBuffer(this._vertexCoordinateBuffer);\n gl.deleteBuffer(this._textureCoordinateBuffer);\n\n if (this._texture) gl.deleteTexture(this._texture);\n\n this._initialized = false;\n }\n\n render(texture: WebGLTexture): void {\n const gl = this._gl;\n\n this._program.use();\n\n this._program.bindVertexAttribArray(\n vsh.plain.attribute.vertexPosition,\n this._vertexCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n this._program.bindVertexAttribArray(\n vsh.plain.attribute.textureCoordinate,\n this._textureCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._texture, 0);\n\n gl.viewport(0, 0, this._width, this._height);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n }\n\n getWidth(): number {\n return this._width;\n }\n\n getHeight(): number {\n return this._height;\n }\n\n getTexture(): WebGLTexture {\n return this._texture;\n }\n\n resize(width: number, height: number): void {\n this._widthFrom = width;\n this._heightFrom = height;\n\n this._reconfigure();\n }\n\n configure(widthTo: number, heightTo: number): void {\n this._widthTo = widthTo;\n this._heightTo = heightTo;\n\n this._reconfigure();\n }\n\n private _reconfigure(): void {\n if (\n this._widthFrom <= 0 ||\n this._heightFrom <= 0 ||\n this._widthTo <= 0 ||\n this._heightTo <= 0 ||\n !this._initialized\n )\n return;\n\n this._width =\n this._widthTo > this._widthFrom\n ? Math.floor(this._widthTo / this._widthFrom) * this._widthFrom\n : this._widthFrom;\n this._height =\n this._heightTo > this._heightFrom\n ? Math.floor(this._heightTo / this._heightFrom) * this._heightFrom\n : this._heightFrom;\n\n const gl = this._gl;\n\n if (this._texture) gl.deleteTexture(this._texture);\n this._texture = gl.createTexture();\n\n gl.activeTexture(gl.TEXTURE0);\n\n gl.bindTexture(gl.TEXTURE_2D, this._texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this._width, this._height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n }\n\n private _width = 0;\n private _height = 0;\n\n private _widthFrom = 0;\n private _heightFrom = 0;\n private _widthTo = 0;\n private _heightTo = 0;\n\n private _texture: WebGLTexture = null;\n private _program: Program = null;\n private _framebuffer: WebGLFramebuffer = null;\n private _vertexCoordinateBuffer: WebGLBuffer = null;\n private _textureCoordinateBuffer: WebGLBuffer = null;\n\n private _initialized = false;\n}\n\nexport default IntegerScalingProcessor;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nclass RingBuffer<T> {\n constructor(private _capacity: number) {\n this._buffer = new Array<T>(this._capacity);\n\n for (let i = 0; i < this._capacity; i++) {\n this._buffer[i] = null;\n }\n }\n\n size(): number {\n return this._size;\n }\n\n pop(): T {\n if (this._size === 0) {\n return undefined;\n }\n\n const item = this._buffer[this._index];\n this._buffer[this._index] = null;\n\n this._index = (this._index + 1) % this._capacity;\n this._size--;\n\n return item;\n }\n\n push(item: T): this {\n if (this._size === this._capacity) {\n this.evict.dispatch(this.pop());\n }\n\n this._buffer[(this._index + this._size++) % this._capacity] = item;\n\n return this;\n }\n\n forEach(fn: (item: T) => void): this {\n for (let i = 0; i < this._size; i++) {\n fn(this._buffer[(this._index + i) % this._capacity]);\n }\n\n return this;\n }\n\n clear(): this {\n for (let i = 0; i < this._capacity; i++) {\n this._buffer[i] = null;\n }\n\n this._size = 0;\n this._index = 0;\n\n return this;\n }\n\n capacity(): number {\n return this._capacity;\n }\n\n evict = new Event<T>();\n\n private _size = 0;\n private _index = 0;\n private _buffer: Array<T>;\n}\n\nexport { RingBuffer as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport interface Capabilities {\n floatTextures: boolean;\n halfFloatTextures: boolean;\n highpInVsh: boolean;\n highpInFsh: boolean;\n}\n\nfunction framebufferSupportTextureType(gl: WebGLRenderingContext, type: number): boolean {\n const texture = gl.createTexture();\n const framebuffer = gl.createFramebuffer();\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 64, 64, 0, gl.RGBA, type, null);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n const fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER);\n\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(texture);\n\n return fbStatus === gl.FRAMEBUFFER_COMPLETE;\n}\n\nfunction detectFloatTextureSupport(gl: WebGLRenderingContext): boolean {\n gl.getExtension('WEBGL_color_buffer_float');\n if (!gl.getExtension('OES_texture_float')) return false;\n\n return framebufferSupportTextureType(gl, gl.FLOAT);\n}\n\nfunction detectHalfFloatTextureSupport(gl: WebGLRenderingContext): boolean {\n gl.getExtension('EXT_color_buffer_half_float');\n\n const extHalfFLoat = gl.getExtension('OES_texture_half_float');\n if (!extHalfFLoat) {\n return false;\n }\n\n return framebufferSupportTextureType(gl, extHalfFLoat.HALF_FLOAT_OES);\n}\n\nfunction shaderSupportsPrecision(gl: WebGLRenderingContext, shaderType: number, precisionType: number): boolean {\n const format = gl.getShaderPrecisionFormat(shaderType, precisionType);\n\n return !!format && format.precision > 0;\n}\n\nexport function detect(): Capabilities | null;\nexport function detect(gl: WebGLRenderingContext): Capabilities;\nexport function detect(gl: WebGLRenderingContext = null) {\n if (!gl) {\n const canvas = document.createElement('canvas');\n canvas.width = 64;\n canvas.height = 64;\n\n gl = canvas.getContext('webgl') || (canvas.getContext('experimental-webgl') as any);\n }\n\n if (!gl) return null;\n\n return {\n floatTextures: detectFloatTextureSupport(gl),\n halfFloatTextures: detectHalfFloatTextureSupport(gl),\n highpInFsh: shaderSupportsPrecision(gl, gl.FRAGMENT_SHADER, gl.HIGH_FLOAT),\n highpInVsh: shaderSupportsPrecision(gl, gl.VERTEX_SHADER, gl.HIGH_FLOAT)\n };\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport VideoEndpointInterface from './VideoEndpointInterface';\nimport { fsh, vsh } from './video/shader';\nimport Program from './video/Program';\nimport PoolMemberInterface from '../../tools/pool/PoolMemberInterface';\nimport PhosphorProcessor from './video/PhosphorProcessor';\nimport NtscProcessor from './video/NtscProcessor';\nimport ScanlineProcessor from './video/ScanlineProcessor';\nimport IntegerScalingProcessor from './video/IntegerScalingProcessor';\nimport RingBuffer from '../../tools/RingBuffer';\nimport Processor from './video/Processor';\nimport { Capabilities, detect } from './video/Capabilities';\n\nconst MAX_CONSECUTIVE_UNDERFLOWS = 5;\n\nclass Video {\n constructor(private _canvas: HTMLCanvasElement, config: Partial<Video.Config> = {}) {\n const defaultConfig: Video.Config = {\n gamma: 1,\n scalingMode: Video.ScalingMode.qis,\n phosphorLevel: 0.5,\n scanlineLevel: 0.2,\n tvEmulation: Video.TvEmulation.composite\n };\n\n this._config = {\n ...defaultConfig,\n ...config\n };\n\n this._getRenderingContext();\n\n this._canvas.addEventListener('webglcontextlost', this._onContextLost);\n this._canvas.addEventListener('webglcontextrestored', this._onContextRestored);\n\n this._pendingFrames.evict.addHandler(frame => frame.release());\n }\n\n init(): this {\n if (!this._gl) return this;\n\n this._phosphorProcessor = new PhosphorProcessor(this._gl, this._capabilities);\n this._ntscProcessor = new NtscProcessor(this._gl, this._capabilities);\n this._scanlineProcessor = new ScanlineProcessor(this._gl, this._capabilities);\n this._integerScalingProcessor = new IntegerScalingProcessor(this._gl, this._capabilities);\n\n this._updateCanvasSize();\n\n this._mainProgram = Program.compile(\n this._gl,\n vsh.plain.source(this._capabilities),\n fsh.blitWithGamma.source(this._capabilities)\n );\n\n this._mainProgram.use();\n this._mainProgram.uniform1i(fsh.blitWithGamma.uniform.textureUnit, 0);\n\n this._createVertexCoordinateBuffer();\n this._createTextureCoordinateBuffer();\n this._configureSourceTexture();\n\n this._applyConfiguration();\n\n return this;\n }\n\n close(): this {\n const gl = this._gl;\n\n this._cancelDraw();\n this.unbind();\n\n if (gl) {\n this._mainProgram.delete();\n gl.deleteBuffer(this._vertexCoordinateBuffer);\n gl.deleteBuffer(this._textureCoordinateBuffer);\n gl.deleteTexture(this._sourceTexture);\n\n this._ntscProcessor.destroy();\n this._phosphorProcessor.destroy();\n this._scanlineProcessor.destroy();\n this._integerScalingProcessor.destroy();\n\n return this;\n }\n\n this._canvas.removeEventListener('webglcontextlost', this._onContextLost);\n this._canvas.removeEventListener('webglcontextrestored', this._onContextRestored);\n\n this._pendingFrames.forEach(f => f.release());\n }\n\n resize(width?: number, height?: number): this {\n this._updateCanvasSize(width, height);\n this._updateVertexBuffer();\n\n if (this._video) {\n this._configureProcessors();\n this._scheduleDraw();\n }\n\n if (this._hasFrame) this._draw();\n\n return this;\n }\n\n getCanvas(): HTMLCanvasElement {\n return this._canvas;\n }\n\n bind(video: VideoEndpointInterface): this {\n if (this._video) {\n return this;\n }\n\n this._video = video;\n this._video.newFrame.addHandler(Video._frameHandler, this);\n\n this._configureProcessors();\n\n this._scheduleDraw();\n\n return this;\n }\n\n unbind(): this {\n if (!this._video) {\n return this;\n }\n\n this._cancelDraw();\n this._video.newFrame.removeHandler(Video._frameHandler, this);\n this._video = null;\n\n this._pendingFrames.forEach(f => f.release());\n this._pendingFrames.clear();\n\n return this;\n }\n\n getConfig(): Video.Config {\n return this._config;\n }\n\n updateConfig(config: Partial<Video.Config>): this {\n return this;\n }\n\n private static _frameHandler(imageDataPoolMember: PoolMemberInterface<ImageData>, self: Video): void {\n if (self._pendingFrames.size() === self._pendingFrames.capacity()) {\n self._pendingFrames.forEach(f => f.release());\n self._pendingFrames.clear();\n }\n\n self._pendingFrames.push(imageDataPoolMember);\n\n self._scheduleDraw();\n }\n\n private _getRenderingContext(): void {\n const contextOptions: WebGLContextAttributes = {\n alpha: false,\n depth: false,\n antialias: false\n };\n\n this._gl =\n this._canvas.getContext('webgl', contextOptions) ||\n (this._canvas.getContext('experimental-webgl', contextOptions) as any);\n\n if (!this._gl) {\n throw new Error('unable to acquire webgl context');\n }\n\n this._capabilities = detect(this._gl);\n }\n\n private _scheduleDraw(): void {\n if (this._anmiationFrameHandle !== 0) {\n return;\n }\n\n this._anmiationFrameHandle = requestAnimationFrame(() => this._onAnimationFrame());\n }\n\n private _cancelDraw(): void {\n if (this._anmiationFrameHandle !== 0) {\n cancelAnimationFrame(this._anmiationFrameHandle);\n }\n\n this._anmiationFrameHandle = 0;\n }\n\n private _onAnimationFrame(): void {\n const gl = this._gl;\n this._anmiationFrameHandle = 0;\n\n if (this._pendingFrames.size() === 0) {\n if (this._consecutiveUnderflows++ <= MAX_CONSECUTIVE_UNDERFLOWS) {\n this._scheduleDraw();\n }\n\n return;\n }\n\n this._consecutiveUnderflows = 0;\n this._scheduleDraw();\n\n const frame = this._pendingFrames.pop();\n\n if (!gl) return;\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, this._sourceTexture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, frame.get());\n\n frame.release();\n\n this._hasFrame = true;\n\n this._draw();\n }\n\n private _draw(): void {\n if (!this._gl) return;\n\n const gl = this._gl;\n\n let texture = this._sourceTexture;\n\n for (const processor of this._processors) {\n processor.render(texture);\n texture = processor.getTexture();\n }\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n gl.texParameteri(\n gl.TEXTURE_2D,\n gl.TEXTURE_MIN_FILTER,\n this._config.scalingMode === Video.ScalingMode.none ? gl.NEAREST : gl.LINEAR\n );\n gl.texParameteri(\n gl.TEXTURE_2D,\n gl.TEXTURE_MAG_FILTER,\n this._config.scalingMode === Video.ScalingMode.none ? gl.NEAREST : gl.LINEAR\n );\n\n this._mainProgram.use();\n this._mainProgram.bindVertexAttribArray(\n vsh.plain.attribute.vertexPosition,\n this._vertexCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n this._mainProgram.bindVertexAttribArray(\n vsh.plain.attribute.textureCoordinate,\n this._textureCoordinateBuffer,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n }\n\n private _createVertexCoordinateBuffer(): void {\n if (!this._gl) return;\n\n const gl = this._gl,\n targetWidth = gl.drawingBufferWidth,\n targetHeight = gl.drawingBufferHeight,\n scaleX = targetWidth > 0 ? 2 / targetWidth : 1,\n scaleY = targetHeight > 0 ? 2 / targetHeight : 1;\n\n let width: number, height: number, west: number, north: number;\n\n if ((4 / 3) * targetHeight <= targetWidth) {\n height = 2;\n width = (4 / 3) * targetHeight * scaleX;\n north = 1;\n west = (Math.floor((-4 / 3) * targetHeight) / 2) * scaleX;\n } else {\n height = (targetWidth / (4 / 3)) * scaleY;\n width = 2;\n north = (Math.floor(targetWidth / (4 / 3)) / 2) * scaleY;\n west = -1;\n }\n\n const vertexData = [west + width, north, west, north, west + width, north - height, west, north - height];\n\n this._vertexCoordinateBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexData), gl.STATIC_DRAW);\n }\n\n private _updateVertexBuffer(): void {\n if (!this._gl) return;\n\n this._gl.deleteBuffer(this._vertexCoordinateBuffer);\n this._createVertexCoordinateBuffer();\n }\n\n private _createTextureCoordinateBuffer(): void {\n if (!this._gl) return;\n\n const gl = this._gl;\n const textureCoordinateData = [1, 1, 0, 1, 1, 0, 0, 0];\n\n this._textureCoordinateBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, this._textureCoordinateBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinateData), gl.STATIC_DRAW);\n }\n\n private _updateCanvasSize(width?: number, height?: number): void {\n if (typeof width === 'undefined' || typeof height === 'undefined') {\n width = this.getCanvas().clientWidth;\n height = this.getCanvas().clientHeight;\n }\n\n const pixelRatio = window.devicePixelRatio || 1;\n\n this.getCanvas().width = width * pixelRatio;\n this.getCanvas().height = height * pixelRatio;\n }\n\n private _configureSourceTexture(): void {\n if (!this._gl) return;\n\n const gl = this._gl;\n\n if (!this._sourceTexture) {\n this._sourceTexture = gl.createTexture();\n }\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, this._sourceTexture);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);\n }\n\n private _configureProcessors() {\n if (!this._video || !this._gl) return;\n\n this._phosphorProcessor.configure(this._config.phosphorLevel);\n this._scanlineProcessor.configure(this._config.scanlineLevel);\n this._integerScalingProcessor.configure(this._gl.drawingBufferWidth, this._gl.drawingBufferHeight);\n\n switch (this._config.tvEmulation) {\n case Video.TvEmulation.composite:\n this._ntscProcessor.configure(NtscProcessor.mode.composite);\n break;\n\n case Video.TvEmulation.svideo:\n this._ntscProcessor.configure(NtscProcessor.mode.svideo);\n break;\n }\n\n let width = this._video.getWidth();\n let height = this._video.getHeight();\n\n for (const processor of this._processors) {\n processor.resize(width, height);\n\n width = processor.getWidth();\n height = processor.getHeight();\n }\n }\n\n private _applyConfiguration(): void {\n if (!this._gl) return;\n\n this._mainProgram.use();\n this._mainProgram.uniform1f(fsh.blitWithGamma.uniform.gamma, this._config.gamma);\n\n this._processors = [];\n\n if (this._config.tvEmulation !== Video.TvEmulation.none) {\n this._ntscProcessor.init();\n this._processors.push(this._ntscProcessor);\n }\n\n if (this._config.phosphorLevel > 0) {\n this._phosphorProcessor.init();\n this._processors.push(this._phosphorProcessor);\n }\n\n if (this._config.scanlineLevel > 0) {\n this._scanlineProcessor.init();\n this._processors.push(this._scanlineProcessor);\n }\n\n if (this._config.scalingMode === Video.ScalingMode.qis) {\n this._integerScalingProcessor.init();\n this._processors.push(this._integerScalingProcessor);\n }\n\n this._configureProcessors();\n }\n\n private _onContextLost = (e: Event): void => {\n e.preventDefault();\n\n this._gl = null;\n this._mainProgram = null;\n this._vertexCoordinateBuffer = null;\n this._textureCoordinateBuffer = null;\n this._sourceTexture = null;\n this._phosphorProcessor = null;\n this._ntscProcessor = null;\n this._integerScalingProcessor = null;\n this._scanlineProcessor = null;\n\n this._processors = [];\n };\n\n private _onContextRestored = (): void => {\n this._getRenderingContext();\n this.init();\n };\n\n private _config: Video.Config = null;\n private _gl: WebGLRenderingContext = null;\n private _video: VideoEndpointInterface = null;\n private _capabilities: Capabilities = null;\n\n private _mainProgram: Program = null;\n private _vertexCoordinateBuffer: WebGLBuffer = null;\n private _textureCoordinateBuffer: WebGLBuffer = null;\n private _sourceTexture: WebGLTexture = null;\n\n private _anmiationFrameHandle = 0;\n\n private _phosphorProcessor: PhosphorProcessor = null;\n private _ntscProcessor: NtscProcessor = null;\n private _scanlineProcessor: ScanlineProcessor = null;\n private _integerScalingProcessor: IntegerScalingProcessor = null;\n private _processors: Array<Processor> = [];\n\n private _pendingFrames = new RingBuffer<PoolMemberInterface<ImageData>>(3);\n private _consecutiveUnderflows = 0;\n private _hasFrame = false;\n}\n\nnamespace Video {\n export const enum ScalingMode {\n qis = 'qis',\n bilinear = 'bilinear',\n none = 'none'\n }\n\n export const enum TvEmulation {\n composite = 'composite',\n svideo = 'svideo',\n none = 'none'\n }\n\n export interface Config {\n gamma: number;\n scalingMode: ScalingMode;\n phosphorLevel: number;\n scanlineLevel: number;\n tvEmulation: TvEmulation;\n }\n}\n\nexport default Video;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport ChannelInterface from './ChannelInterface';\nimport WaveformAudioOutputInterface from '../../../machine/io/WaveformAudioOutputInterface';\n\nclass WaveformChannel implements ChannelInterface {\n constructor(private _cache: Map<number, AudioBuffer>) {}\n\n init(context: AudioContext, target: AudioNode): void {\n this._context = context;\n\n this._gain = this._context.createGain();\n this._gain.connect(target);\n }\n\n bind(target: WaveformAudioOutputInterface): void {\n if (this._audio) {\n return;\n }\n\n this._audio = target;\n this._volume = this._audio.getVolume();\n this._updateGain();\n\n this._audio.volumeChanged.addHandler(WaveformChannel._onVolumeChanged, this);\n this._audio.bufferChanged.addHandler(WaveformChannel._onBufferChanged, this);\n this._audio.stop.addHandler(WaveformChannel._onStop, this);\n }\n\n unbind(): void {\n if (!this._audio) {\n return;\n }\n\n this._audio.volumeChanged.removeHandler(WaveformChannel._onVolumeChanged, this);\n this._audio.bufferChanged.removeHandler(WaveformChannel._onBufferChanged, this);\n this._audio.stop.removeHandler(WaveformChannel._onStop, this);\n\n if (this._source) {\n this._source.stop();\n this._source = null;\n }\n\n this._audio = null;\n }\n\n setMasterVolume(volume: number): void {\n this._masterVolume = volume;\n this._updateGain();\n }\n\n private static _onVolumeChanged(volume: number, self: WaveformChannel): void {\n self._volume = volume;\n self._updateGain();\n }\n\n private static _onBufferChanged(key: number, self: WaveformChannel): void {\n if (!self._cache.has(key)) {\n const sampleBuffer = self._audio.getBuffer(key),\n audioBuffer = self._context.createBuffer(1, sampleBuffer.getLength(), sampleBuffer.getSampleRate());\n\n audioBuffer.getChannelData(0).set(sampleBuffer.getContent());\n self._cache.set(key, audioBuffer);\n }\n\n const buffer = self._cache.get(key),\n source = self._context.createBufferSource();\n\n if (self._source) {\n self._source.stop();\n }\n\n source.loop = true;\n source.buffer = buffer;\n source.connect(self._gain);\n source.start();\n\n self._source = source;\n }\n\n private static _onStop(payload: void, self: WaveformChannel): void {\n if (self._source) {\n self._source.stop();\n self._source = null;\n }\n }\n\n private _updateGain(): void {\n this._gain.gain.value = this._volume * this._masterVolume;\n }\n\n private _context: AudioContext = null;\n private _source: AudioBufferSourceNode = null;\n private _gain: GainNode = null;\n private _audio: WaveformAudioOutputInterface = null;\n\n private _volume = 0;\n private _masterVolume = 1;\n}\n\nexport { WaveformChannel as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport ResamplerInterface from './ResamplerInterface';\n\nclass LinearReasmpler implements ResamplerInterface {\n constructor() {\n this.reset(1, 1);\n }\n\n reset(sourceRate: number, targetRate: number) {\n this._ratio = sourceRate / targetRate;\n this._needsData = false;\n this._fractionalIndex = 0;\n\n for (let i = 0; i < 2; i++) {\n this._buffer[i] = 0;\n }\n }\n\n get(): number {\n const x = (1 - this._fractionalIndex) * this._buffer[0] + this._fractionalIndex * this._buffer[1];\n\n this._fractionalIndex += this._ratio;\n if (this._fractionalIndex > 1) {\n this._fractionalIndex -= 1;\n this._needsData = true;\n }\n\n return x;\n }\n\n push(sample: number): void {\n this._buffer[0] = this._buffer[1];\n this._buffer[1] = sample;\n\n this._needsData = false;\n }\n\n needsData(): boolean {\n return this._needsData;\n }\n\n private _buffer = new Float32Array(2);\n private _fractionalIndex = 0;\n private _needsData = false;\n\n private _ratio = 0;\n}\n\nexport { LinearReasmpler as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport ChannelInterface from './ChannelInterface';\nimport PCMAudioEndpointInterface from '../PCMAudioEndpointInterface';\nimport PoolMemberInterface from '../../../tools/pool/PoolMemberInterface';\nimport RingBuffer from '../../../tools/RingBuffer';\nimport ResamplerInterface from './ResamplerInterface';\nimport LinearReasmpler from './LinearResampler';\n\nclass PCMChannel implements ChannelInterface {\n constructor(private _hostFragmentSize = 1024) {}\n\n init(context: AudioContext, target: AudioNode) {\n this._outputSampleRate = context.sampleRate;\n\n this._gain = context.createGain();\n this._gain.gain.value = this._volume;\n this._gain.connect(target);\n\n this._processor = context.createScriptProcessor(this._hostFragmentSize, 1, 1);\n this._bufferSize = this._processor.bufferSize;\n\n this._processor.connect(this._gain);\n this._processor.onaudioprocess = e => this._processAudio(e);\n\n const buffer = context.createBuffer(1, 1, context.sampleRate);\n buffer.getChannelData(0).set([0]);\n }\n\n bind(audio: PCMAudioEndpointInterface): void {\n this.unbind();\n\n this._audio = audio;\n this._fragmentSize = audio.getFrameSize();\n this._inputSampleRate = audio.getSampleRate();\n this._fragmentIndex = 0;\n this._lastFragment = null;\n this._bufferUnderrun = true;\n this._fragmentRing = new RingBuffer<PoolMemberInterface<Float32Array>>(\n Math.ceil(((4 * this._bufferSize) / this._outputSampleRate / this._fragmentSize) * this._inputSampleRate)\n );\n this._fragmentRing.evict.addHandler(b => b.release());\n\n this._audio.newFrame.addHandler(PCMChannel._onNewFragment, this);\n\n this._resampler.reset(this._inputSampleRate, this._outputSampleRate);\n }\n\n unbind() {\n if (!this._audio) {\n return;\n }\n\n this._audio.newFrame.removeHandler(PCMChannel._onNewFragment, this);\n\n if (this._lastFragment) {\n this._lastFragment.release();\n this._lastFragment = null;\n }\n\n if (this._currentFragment) {\n this._currentFragment.release();\n this._currentFragment = null;\n }\n\n if (this._fragmentRing) {\n this._fragmentRing.forEach(b => b.release());\n this._fragmentRing.clear();\n this._fragmentRing = null;\n }\n }\n\n setMasterVolume(volume: number): void {\n this._volume = volume;\n }\n\n private static _onNewFragment(fragment: PoolMemberInterface<Float32Array>, self: PCMChannel): void {\n self._fragmentRing.push(fragment);\n\n if (!self._currentFragment) {\n self._currentFragment = self._fragmentRing.pop();\n self._fragmentIndex = 0;\n }\n }\n\n private _processAudio(e: AudioProcessingEvent): void {\n if (!this._audio) {\n return;\n }\n\n const outputBuffer = e.outputBuffer.getChannelData(0);\n let bufferIndex = 0;\n\n const fillBuffer = (until: number) => {\n const previousFragmentBuffer = this._lastFragment && this._lastFragment.get();\n\n while (bufferIndex < until) {\n if (this._resampler.needsData()) {\n this._resampler.push(\n (this._audio && this._audio.isPaused()) || !previousFragmentBuffer\n ? 0\n : previousFragmentBuffer[this._fragmentIndex++] * this._volume\n );\n\n if (this._fragmentIndex >= this._fragmentSize) {\n this._fragmentIndex = 0;\n }\n }\n\n outputBuffer[bufferIndex++] = this._resampler.get();\n }\n };\n\n // Give the emulation half a fragment of head start when recovering from an underrun\n if (this._currentFragment && this._bufferUnderrun) {\n fillBuffer(this._bufferSize >>> 1);\n this._bufferUnderrun = false;\n }\n\n let fragmentBuffer = this._currentFragment && this._currentFragment.get();\n\n while (bufferIndex < this._bufferSize && this._currentFragment) {\n if (this._resampler.needsData()) {\n this._resampler.push(fragmentBuffer[this._fragmentIndex++] * this._volume);\n\n if (this._fragmentIndex >= this._fragmentSize) {\n this._fragmentIndex = 0;\n\n if (this._lastFragment) {\n this._lastFragment.release();\n }\n\n this._lastFragment = this._currentFragment;\n this._currentFragment = this._fragmentRing.pop();\n\n fragmentBuffer = this._currentFragment && this._currentFragment.get();\n }\n }\n\n outputBuffer[bufferIndex++] = this._resampler.get();\n }\n\n if (bufferIndex < this._bufferSize) {\n this._bufferUnderrun = true;\n }\n\n fillBuffer(this._bufferSize);\n }\n\n private _outputSampleRate = 0;\n private _bufferSize = 0;\n private _volume = 1;\n\n private _gain: GainNode = null;\n private _processor: ScriptProcessorNode = null;\n private _bufferUnderrun = false;\n\n private _fragmentRing: RingBuffer<PoolMemberInterface<Float32Array>> = null;\n\n private _fragmentSize = 0;\n private _inputSampleRate = 0;\n private _fragmentIndex = 0;\n private _currentFragment: PoolMemberInterface<Float32Array> = null;\n private _lastFragment: PoolMemberInterface<Float32Array> = null;\n\n private _audio: PCMAudioEndpointInterface;\n\n private _resampler: ResamplerInterface = new LinearReasmpler();\n}\n\nexport { PCMChannel as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport const isSafari = 'safari' in window;\nexport const isIOS =\n !!navigator.platform.match(/iPhone|iPad|iPod/) ||\n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Mutex } from 'async-mutex';\n\nimport ChannelInterface from './audio/ChannelInterface';\nimport WaveformChannel from './audio/WaveformChannel';\nimport PCMChannel from './audio/PCMChannel';\n\nimport WaveformAudioOutputInterface from '../../machine/io/WaveformAudioOutputInterface';\nimport PCMAudioEndpointInterface from './PCMAudioEndpointInterface';\nimport { isIOS, isSafari } from '../../tools/browser';\n\nconst audioNeedsInteraction = isIOS || isSafari;\nconst INTERACTION_EVENTS = ['touchstart', 'click', 'keydown'];\n\ntype AudioContextType = typeof AudioContext;\n\ndeclare namespace window {\n const webkitAudioContext: AudioContextType;\n // tslint:disable-next-line:variable-name\n const AudioContext: AudioContextType;\n}\n\nconst audioContextCtor = window.AudioContext || window.webkitAudioContext;\n\nfunction waitMax<T>(waitFor: Promise<T>, timeout: number = 500): Promise<void> {\n return new Promise(r => {\n waitFor.then(() => r());\n setTimeout(r, timeout);\n });\n}\n\nclass PreallocatedContext {\n constructor() {\n if (!audioContextCtor) {\n return;\n }\n\n this.context = new audioContextCtor();\n\n try {\n this.context.destination.channelCount = 1;\n } catch (e) {\n console.warn('audio driver: failed to set channel count');\n }\n\n INTERACTION_EVENTS.forEach(event => document.addEventListener(event, this._interactionListener));\n }\n\n stopListening(): void {\n INTERACTION_EVENTS.forEach(event => document.removeEventListener(event, this._interactionListener));\n }\n\n private _interactionListener = () => {\n const context = this.context;\n\n this.interactionRequired = false;\n INTERACTION_EVENTS.forEach(event => document.removeEventListener(event, this._interactionListener));\n\n this.mutex.runExclusive(async () => {\n await waitMax(context.resume());\n\n return new Promise(r =>\n setTimeout(async () => {\n await waitMax(context.suspend());\n r();\n }, 100)\n );\n });\n };\n\n public readonly mutex = new Mutex();\n public readonly context: AudioContext = null;\n public interactionRequired = true;\n}\n\nlet preallocatedContext = audioNeedsInteraction ? new PreallocatedContext() : null;\n\nclass WebAudioDriver {\n constructor(waveformChannels = 0, pcmChannels = 0, fragmentSize?: number) {\n this._waveformChannels = new Array<WaveformChannel>(waveformChannels);\n this._pcmChannels = new Array<PCMChannel>(pcmChannels);\n\n for (let i = 0; i < waveformChannels; i++) {\n this._waveformChannels[i] = new WaveformChannel(this._cache);\n }\n\n for (let i = 0; i < pcmChannels; i++) {\n this._pcmChannels[i] = new PCMChannel(fragmentSize);\n }\n\n this._channels = [...this._waveformChannels, ...this._pcmChannels];\n }\n\n init(): void {\n if (preallocatedContext) {\n const p = preallocatedContext;\n preallocatedContext = new PreallocatedContext();\n\n this._context = p.context;\n p.stopListening();\n\n this._mutex = p.mutex;\n\n if (p.interactionRequired) {\n INTERACTION_EVENTS.forEach(event => document.addEventListener(event, this._touchListener, true));\n }\n } else {\n if (!audioContextCtor) {\n throw new Error(`web audio is not supported by runtime`);\n }\n\n this._context = new audioContextCtor();\n\n try {\n this._context.destination.channelCount = 1;\n } catch (e) {\n console.warn('audio driver: failed to set channel count');\n }\n }\n\n this._merger = this._context.createChannelMerger(this._channels.length);\n this._merger.connect(this._context.destination);\n\n this._channels.forEach(channel => channel.init(this._context, this._merger));\n }\n\n bind(\n waveformSources: Array<WaveformAudioOutputInterface> = [],\n pcmSources: Array<PCMAudioEndpointInterface> = []\n ): void {\n if (this._isBound) {\n return;\n }\n\n if (waveformSources.length !== this._waveformChannels.length) {\n throw new Error(\n `invalid number of waveform sources: expected ${this._waveformChannels.length}, got ${waveformSources.length}`\n );\n }\n\n if (pcmSources.length !== this._pcmChannels.length) {\n throw new Error(\n `invalid number of waveform sources: expected ${this._pcmChannels.length}, got ${pcmSources.length}`\n );\n }\n\n this._waveformChannels.forEach((channel, i) => channel.bind(waveformSources[i]));\n this._pcmChannels.forEach((channel, i) => channel.bind(pcmSources[i]));\n\n this._isBound = true;\n\n this.resume();\n }\n\n unbind(): void {\n if (!this._isBound) {\n return;\n }\n\n this._channels.forEach(channel => channel.unbind());\n\n this._isBound = false;\n\n this.pause();\n }\n\n setMasterVolume(channel: number, volume: number): void {\n this._channels[channel].setMasterVolume(volume);\n }\n\n pause(): Promise<void> {\n return this._mutex.runExclusive(async () => {\n if (this._suspended) {\n return;\n }\n\n this._suspended = true;\n\n await waitMax(this._context.suspend());\n });\n }\n\n resume(): Promise<void> {\n return this._mutex.runExclusive(async () => {\n if (!this._suspended) {\n return;\n }\n\n this._suspended = false;\n\n await waitMax(this._context.resume());\n });\n }\n\n close(): void {\n this._mutex.runExclusive(() => this._context.close());\n }\n\n private _touchListener = () => {\n INTERACTION_EVENTS.forEach(event => document.removeEventListener(event, this._touchListener, true));\n\n if (!this._context) {\n return;\n }\n\n this._context.resume();\n\n setTimeout(() => {\n this._mutex.runExclusive(() => (this._suspended ? this._context.suspend() : this._context.resume()));\n }, 10);\n };\n\n private _context: AudioContext = null;\n private _merger: ChannelMergerNode = null;\n private _waveformChannels: Array<WaveformChannel> = null;\n private _pcmChannels: Array<PCMChannel> = null;\n private _channels: Array<ChannelInterface> = null;\n private _cache = new Map<number, AudioBuffer>();\n private _mutex = new Mutex();\n\n private _suspended = true;\n\n private _isBound = false;\n}\n\nexport { WebAudioDriver as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport VanillaDriver from '../../driver/WebAudio';\nimport WaveformAudioOutputInterface from '../../../machine/io/WaveformAudioOutputInterface';\nimport PCMAudioEndpointInterface from '../../driver/PCMAudioEndpointInterface';\n\nclass WebAudioDriver {\n constructor(private _fragmentSize?: number) {}\n\n init(): void {}\n\n bind(pcmAudio: boolean, channels: WebAudioDriver.Channels): void {\n if (this._channels) {\n return;\n }\n this._channels = [...channels] as any;\n\n if (!this._driver || this._pcmAudio !== pcmAudio) {\n if (this._driver) {\n this._driver.close();\n }\n\n this._driver = pcmAudio\n ? new VanillaDriver(0, this._channels.length, this._fragmentSize)\n : new VanillaDriver(this._channels.length, 0, this._fragmentSize);\n this._driver.init();\n }\n\n if (pcmAudio) {\n this._driver.bind([], this._channels as Array<PCMAudioEndpointInterface>);\n } else {\n this._driver.bind(this._channels as Array<WaveformAudioOutputInterface>, []);\n }\n\n for (let i = 0; i < this._channels.length; i++) {\n this._driver.setMasterVolume(i, this._volume);\n }\n\n this._pcmAudio = pcmAudio;\n }\n\n unbind(): void {\n if (!this._channels) {\n return;\n }\n\n this._driver.unbind();\n\n this._channels = null;\n }\n\n setMasterVolume(volume: number): void {\n this._volume = volume;\n\n if (this._channels) {\n for (let i = 0; i < this._channels.length; i++) {\n this._driver.setMasterVolume(i, this._volume);\n }\n }\n }\n\n getMasterVolume(): number {\n return this._volume;\n }\n\n async pause(): Promise<void> {\n if (this._driver) {\n await this._driver.pause();\n }\n }\n\n async resume(): Promise<void> {\n if (this._driver) {\n await this._driver.resume();\n }\n }\n\n private _driver: VanillaDriver;\n private _pcmAudio = false;\n private _volume = 1;\n private _channels: WebAudioDriver.Channels;\n}\n\nnamespace WebAudioDriver {\n export type Channels = Array<WaveformAudioOutputInterface> | Array<PCMAudioEndpointInterface>;\n}\n\nexport { WebAudioDriver as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport SwitchInterface from '../../../machine/io/SwitchInterface';\nimport JoystickInterface from '../../../machine/io/DigitalJoystickInterface';\nimport ControlPanelInterface from '../../../machine/stella/ControlPanelInterface';\n\nconst enum DispatchType {\n swtch,\n triggerDown\n}\n\ninterface SwitchDispatch {\n type: DispatchType.swtch;\n swtch: SwitchInterface;\n}\n\ninterface TriggerDispatch {\n type: DispatchType.triggerDown;\n trigger: Event<void>;\n}\n\ntype Dispatch = SwitchDispatch | TriggerDispatch;\n\nfunction mkSwitch(swtch: SwitchInterface): SwitchDispatch {\n return {\n type: DispatchType.swtch,\n swtch\n };\n}\n\nfunction mkTrigger(event: Event<void>): TriggerDispatch {\n return {\n type: DispatchType.triggerDown,\n trigger: event\n };\n}\n\nclass KeyboardIO {\n constructor(\n private _target: HTMLElement | HTMLDocument,\n // tslint:disable-next-line\n mappings: Array<KeyboardIO.Mapping> = KeyboardIO.defaultMappings\n ) {\n this._compileMappings(mappings);\n }\n\n bind(joystick0: JoystickInterface, joystick1: JoystickInterface, controlPanel: ControlPanelInterface): void {\n if (this._joystick0) {\n return;\n }\n\n this._joystick0 = joystick0;\n this._joystick1 = joystick1;\n this._controlPanel = controlPanel;\n\n this._updateActionTable();\n\n this._keydownListener = e => {\n if (!this._compiledMappings.has(e.keyCode)) {\n return;\n }\n\n const modifiers =\n (e.shiftKey ? KeyboardIO.Modifier.shift : 0) |\n (e.ctrlKey ? KeyboardIO.Modifier.ctrl : 0) |\n (e.altKey ? KeyboardIO.Modifier.alt : 0);\n\n if (!this._compiledMappings.get(e.keyCode).has(modifiers)) {\n return;\n }\n\n const action = this._compiledMappings.get(e.keyCode).get(modifiers);\n\n if (typeof action !== 'undefined') {\n e.preventDefault();\n\n const dispatch = this._dispatchTable[action];\n switch (dispatch.type) {\n case DispatchType.swtch:\n dispatch.swtch.toggle(true);\n break;\n\n case DispatchType.triggerDown:\n dispatch.trigger.dispatch(undefined);\n break;\n\n default:\n }\n }\n };\n\n this._keyupListener = e => {\n if (!this._compiledMappings.has(e.keyCode)) {\n return;\n }\n\n for (const action of this._compiledMappings.get(e.keyCode).values()) {\n e.preventDefault();\n\n const dispatch = this._dispatchTable[action];\n\n switch (dispatch.type) {\n case DispatchType.swtch:\n dispatch.swtch.toggle(false);\n break;\n\n default:\n }\n }\n };\n\n this._target.addEventListener('keydown', this._keydownListener);\n this._target.addEventListener('keyup', this._keyupListener);\n }\n\n unbind(): void {\n if (!this._joystick0) {\n return;\n }\n\n this._target.removeEventListener('keydown', this._keydownListener);\n this._target.removeEventListener('keyup', this._keyupListener);\n\n this._joystick0 = this._joystick1 = this._controlPanel = null;\n this._keydownListener = this._keyupListener = null;\n }\n\n private _updateActionTable(): void {\n this._dispatchTable[KeyboardIO.Action.fullscreen] = mkTrigger(this.toggleFullscreen);\n this._dispatchTable[KeyboardIO.Action.hardReset] = mkTrigger(this.hardReset);\n this._dispatchTable[KeyboardIO.Action.togglePause] = mkTrigger(this.togglePause);\n this._dispatchTable[KeyboardIO.Action.select] = mkSwitch(this._controlPanel.getSelectSwitch());\n this._dispatchTable[KeyboardIO.Action.reset] = mkSwitch(this._controlPanel.getResetButton());\n this._dispatchTable[KeyboardIO.Action.left0] = mkSwitch(this._joystick0.getLeft());\n this._dispatchTable[KeyboardIO.Action.right0] = mkSwitch(this._joystick0.getRight());\n this._dispatchTable[KeyboardIO.Action.up0] = mkSwitch(this._joystick0.getUp());\n this._dispatchTable[KeyboardIO.Action.down0] = mkSwitch(this._joystick0.getDown());\n this._dispatchTable[KeyboardIO.Action.fire0] = mkSwitch(this._joystick0.getFire());\n this._dispatchTable[KeyboardIO.Action.left1] = mkSwitch(this._joystick1.getLeft());\n this._dispatchTable[KeyboardIO.Action.right1] = mkSwitch(this._joystick1.getRight());\n this._dispatchTable[KeyboardIO.Action.up1] = mkSwitch(this._joystick1.getUp());\n this._dispatchTable[KeyboardIO.Action.down1] = mkSwitch(this._joystick1.getDown());\n this._dispatchTable[KeyboardIO.Action.fire1] = mkSwitch(this._joystick1.getFire());\n }\n\n private _compileMappings(mappings: Array<KeyboardIO.Mapping>): void {\n const compileMapping = (action: KeyboardIO.Action, keycode: number, modifiers: number) => {\n if ((modifiers & ~(KeyboardIO.Modifier.shift | KeyboardIO.Modifier.ctrl | KeyboardIO.Modifier.alt)) !== 0) {\n throw new Error(`invalid modifier set ${modifiers}`);\n }\n\n if (!this._compiledMappings.has(keycode)) {\n this._compiledMappings.set(keycode, new Map<number, KeyboardIO.Action>());\n }\n\n this._compiledMappings.get(keycode).set(modifiers, action);\n };\n\n mappings.forEach(mapping => {\n const action = mapping.action,\n specs = Array.isArray(mapping.spec) ? mapping.spec : [mapping.spec];\n\n specs.forEach(spec =>\n compileMapping(\n action,\n typeof spec === 'object' ? spec.keycode : spec,\n typeof spec === 'object' ? spec.modifiers : 0\n )\n );\n });\n }\n\n toggleFullscreen = new Event<void>();\n hardReset = new Event<void>();\n togglePause = new Event<void>();\n\n private _keydownListener: (e: KeyboardEvent) => void = null;\n private _keyupListener: (e: KeyboardEvent) => void = null;\n\n private _joystick0: JoystickInterface = null;\n private _joystick1: JoystickInterface = null;\n private _controlPanel: ControlPanelInterface = null;\n\n private _dispatchTable: { [action: number]: Dispatch } = {};\n private _compiledMappings = new Map<number, Map<number, KeyboardIO.Action>>();\n}\n\nnamespace KeyboardIO {\n export const enum Action {\n select,\n reset,\n left0,\n right0,\n up0,\n down0,\n left1,\n right1,\n up1,\n down1,\n fire0,\n fire1,\n\n fullscreen,\n hardReset,\n togglePause\n }\n\n export const enum Modifier {\n ctrl = 1,\n alt = 2,\n shift = 4\n }\n\n export interface ComplexKeySpec {\n keycode: number;\n modifiers: number;\n }\n\n export type keySpec = number | ComplexKeySpec;\n\n export interface Mapping {\n action: Action;\n spec: keySpec | Array<keySpec>;\n }\n\n export const defaultMappings: Array<Mapping> = [\n {\n action: Action.select,\n spec: {\n keycode: 32, // space\n modifiers: Modifier.shift\n }\n },\n {\n action: Action.reset,\n spec: {\n keycode: 13, // enter\n modifiers: Modifier.shift\n }\n },\n {\n action: Action.left0,\n spec: [\n 65, // w\n 37 // left\n ]\n },\n {\n action: Action.right0,\n spec: [\n 68, // d\n 39 // right\n ]\n },\n {\n action: Action.up0,\n spec: [\n 87, // w\n 38 // up\n ]\n },\n {\n action: Action.down0,\n spec: [\n 83, // s\n 40 // down\n ]\n },\n {\n action: Action.fire0,\n spec: [\n 32, // space\n 86 // v\n ]\n },\n {\n action: Action.left1,\n spec: 74 // j\n },\n {\n action: Action.right1,\n spec: 76 // l\n },\n {\n action: Action.up1,\n spec: 73 // i\n },\n {\n action: Action.down1,\n spec: 75 // k\n },\n {\n action: Action.fire1,\n spec: 66 // b\n },\n {\n action: Action.fullscreen,\n spec: 13 // enter\n },\n {\n action: Action.hardReset,\n spec: {\n keycode: 82, // r\n modifiers: Modifier.shift\n }\n },\n {\n action: Action.togglePause,\n spec: 80 // p\n }\n ];\n}\n\nexport { KeyboardIO as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nclass DoubleTapDetector {\n constructor(private _maxTapLength = 500, private _timeout = 200) {}\n\n startTouch(): void {\n this._lastTouchStart = Date.now();\n\n if (this._touching) {\n return;\n }\n\n this._touching = true;\n\n this._dispatch = this._lastTouchEligible && this._lastTouchStart - this._lastTouchEnd < this._timeout;\n }\n\n endTouch(): void {\n this._lastTouchEnd = Date.now();\n\n // We need to dispatch on touchend in order to enable the fullscreen API in chrome. wtf.\n if (this._dispatch) {\n this._dispatch = false;\n this.trigger.dispatch(undefined);\n }\n\n if (!this._touching) {\n return;\n }\n\n this._touching = false;\n\n this._lastTouchEligible = this._lastTouchStart - this._lastTouchEnd < this._maxTapLength;\n }\n\n cancelTouch(): void {\n this.endTouch();\n this._lastTouchEligible = false;\n }\n\n isDispatching(): boolean {\n return this._dispatch;\n }\n\n trigger = new Event<void>();\n\n private _dispatch = false;\n private _touching = false;\n private _lastTouchEligible = false;\n private _lastTouchStart = 0;\n private _lastTouchEnd = 0;\n}\n\nexport default DoubleTapDetector;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport DoubleTapDetector from './touch/DoubleTapDetector';\nimport DigitalJoystickInterface from '../../../machine/io/DigitalJoystickInterface';\nimport SwitchInterface from '../../../machine/io/SwitchInterface';\nimport ControlPanelInterface from '../../../machine/stella/ControlPanelInterface';\n\nconst enum TouchType {\n alt = 'alt',\n fire = 'fire',\n joystick = 'joystick',\n select = 'select',\n reset = 'reset',\n pause = 'pause',\n unknown = 'unknown'\n}\n\nclass TouchIO {\n constructor(private _canvas: HTMLCanvasElement, private _joystickSensitivity = 15, private _leftHanded = false) {\n this.toggleFullscreen = this._fullscreenDoubleTapDetector.trigger;\n }\n\n static isSupported(): boolean {\n return 'ontouchstart' in window;\n }\n\n bind(joystick: DigitalJoystickInterface, controlPanel: ControlPanelInterface): void {\n if (this._bound) {\n return;\n }\n\n this._bound = true;\n\n this._joystick = joystick;\n this._select = controlPanel.getSelectSwitch();\n this._reset = controlPanel.getResetButton();\n\n this._bindListeners();\n }\n\n unbind(): void {\n if (!this._bound) {\n return;\n }\n\n this._unbindListeners();\n\n (this._bound = false), (this._joystick = this._reset = this._select = null);\n }\n\n private _bindListeners(): void {\n this._canvas.addEventListener('touchstart', this._onTouchStart);\n this._canvas.addEventListener('touchend', this._onTouchEnd);\n this._canvas.addEventListener('touchmove', this._onTouchMove);\n }\n\n private _unbindListeners(): void {\n this._canvas.removeEventListener('touchstart', this._onTouchStart);\n this._canvas.removeEventListener('touchend', this._onTouchEnd);\n this._canvas.removeEventListener('touchmove', this._onTouchMove);\n }\n\n private _onTouchStart = (e: TouchEvent): void => {\n for (let i = 0; i < e.changedTouches.length; i++) {\n const normalizedTouch = new NormalizedTouch(e.changedTouches.item(i), this._canvas),\n id = normalizedTouch.touch.identifier;\n\n if (this._leftHanded ? normalizedTouch.x > 0.5 : normalizedTouch.x <= 0.5) {\n if (normalizedTouch.y <= 0.5) {\n // NW\n normalizedTouch.type = TouchType.alt;\n } else {\n // SW\n normalizedTouch.type = this._isAlt ? TouchType.pause : TouchType.fire;\n }\n } else {\n if (normalizedTouch.y <= 0.5) {\n // NE\n normalizedTouch.type = this._isAlt ? TouchType.select : TouchType.joystick;\n } else {\n // SE\n normalizedTouch.type = this._isAlt ? TouchType.reset : TouchType.joystick;\n }\n }\n\n if (this._pendingTouches.has(id) || this._pendingTouches.has(normalizedTouch.type)) {\n continue;\n }\n\n this._pendingTouches.set(id, normalizedTouch);\n this._pendingTouches.set(normalizedTouch.type, normalizedTouch);\n\n switch (normalizedTouch.type) {\n case TouchType.alt:\n this._isAlt = true;\n this._fullscreenDoubleTapDetector.startTouch();\n break;\n\n case TouchType.fire:\n this._joystick.getFire().toggle(true);\n break;\n\n case TouchType.pause:\n this.togglePause.dispatch(undefined);\n this._fullscreenDoubleTapDetector.cancelTouch();\n break;\n\n case TouchType.select:\n this._select.toggle(true);\n this._fullscreenDoubleTapDetector.cancelTouch();\n break;\n\n case TouchType.reset:\n this._reset.toggle(true);\n this._fullscreenDoubleTapDetector.cancelTouch();\n break;\n\n case TouchType.joystick:\n break;\n\n default:\n throw new Error('invalid touch type');\n }\n }\n\n e.preventDefault();\n };\n\n private _onTouchEnd = (e: TouchEvent): void => {\n for (let i = 0; i < e.changedTouches.length; i++) {\n const normalizedTouch = this._pendingTouches.get(e.changedTouches.item(i).identifier);\n\n if (!normalizedTouch) {\n continue;\n }\n\n switch (normalizedTouch.type) {\n case TouchType.alt:\n this._isAlt = false;\n this._fullscreenDoubleTapDetector.endTouch();\n break;\n\n case TouchType.fire:\n this._joystick.getFire().toggle(false);\n break;\n\n case TouchType.select:\n this._select.toggle(false);\n break;\n\n case TouchType.reset:\n this._reset.toggle(false);\n break;\n\n case TouchType.joystick:\n this._joystick.getDown().toggle(false);\n this._joystick.getUp().toggle(false);\n this._joystick.getLeft().toggle(false);\n this._joystick.getRight().toggle(false);\n break;\n\n case TouchType.pause:\n break;\n\n default:\n throw new Error('invalid touch type');\n }\n\n this._pendingTouches.delete(normalizedTouch.type);\n this._pendingTouches.delete(normalizedTouch.touch.identifier);\n }\n\n e.preventDefault();\n };\n\n private _onTouchMove = (e: TouchEvent): void => {\n for (let i = 0; i < e.changedTouches.length; i++) {\n const touch = e.changedTouches.item(i),\n normalizedTouch = this._pendingTouches.get(touch.identifier);\n\n if (!normalizedTouch) {\n continue;\n }\n\n if (normalizedTouch.type !== TouchType.joystick) {\n continue;\n }\n\n const deltaX = touch.clientX - normalizedTouch.x0,\n deltaY = touch.clientY - normalizedTouch.y0,\n abs = Math.sqrt(deltaX * deltaX + deltaY * deltaY),\n sin = Math.abs(deltaY / abs),\n cos = Math.abs(deltaX / abs),\n trigger = abs > this._joystickSensitivity;\n\n this._joystick.getLeft().toggle(trigger && deltaX < 0 && cos > 0.5);\n this._joystick.getRight().toggle(trigger && deltaX > 0 && cos > 0.5);\n this._joystick.getUp().toggle(trigger && deltaY < 0 && sin > 0.5);\n this._joystick.getDown().toggle(trigger && deltaY > 0 && sin > 0.5);\n\n if (abs > 3 * this._joystickSensitivity) {\n normalizedTouch.x0 += (deltaX / abs) * (abs - 3 * this._joystickSensitivity);\n normalizedTouch.y0 += (deltaY / abs) * (abs - 3 * this._joystickSensitivity);\n }\n }\n\n e.preventDefault();\n };\n\n toggleFullscreen: Event<void>;\n togglePause = new Event<void>();\n\n private _fullscreenDoubleTapDetector = new DoubleTapDetector();\n\n private _bound = false;\n\n private _joystick: DigitalJoystickInterface = null;\n private _select: SwitchInterface = null;\n private _reset: SwitchInterface = null;\n\n private _isAlt = false;\n\n private _pendingTouches = new Map<number | TouchType, NormalizedTouch>();\n}\n\nclass NormalizedTouch {\n constructor(public touch: Touch, canvas: HTMLCanvasElement) {\n const boundingRect = canvas.getBoundingClientRect();\n\n this.x = (touch.clientX - boundingRect.left) / boundingRect.width;\n this.y = (touch.clientY - boundingRect.top) / boundingRect.height;\n\n this.x0 = touch.clientX;\n this.y0 = touch.clientY;\n }\n\n x0: number;\n y0: number;\n\n x: number;\n y: number;\n type = TouchType.unknown;\n}\n\nexport default TouchIO;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport PaddleInterface from '../../machine/io/PaddleInterface';\n\nexport default class MouseAsPaddleDriver {\n bind(paddle: PaddleInterface): void {\n if (this._paddle) {\n return;\n }\n\n this._paddle = paddle;\n this._x = -1;\n\n document.addEventListener('mousemove', this._listener);\n }\n\n unbind(): void {\n if (!this._paddle) {\n return;\n }\n\n document.removeEventListener('mousemove', this._listener);\n this._paddle = null;\n }\n\n private _onDocumentMouseMove(e: MouseEvent) {\n if (this._x >= 0) {\n const dx = e.screenX - this._x;\n let value = this._paddle.getValue();\n\n value += -dx / window.innerWidth / 0.9;\n if (value < 0) {\n value = 0;\n }\n if (value > 1) {\n value = 1;\n }\n\n this._paddle.setValue(value);\n }\n\n this._x = e.screenX;\n }\n\n private _paddle: PaddleInterface;\n private _x = -1;\n private _listener: (e: MouseEvent) => void = this._onDocumentMouseMove.bind(this);\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport SwitchInterface from '../../../machine/io/SwitchInterface';\n\nclass ShadowSwitch {\n toggle(state: boolean): void {\n if (state === this._state) {\n return;\n }\n\n this._state = state;\n this._dirty = true;\n }\n\n setState(state: boolean): void {\n this._state = state;\n this._dirty = false;\n }\n\n sync(swtch: SwitchInterface): void {\n if (this._dirty) {\n swtch.toggle(this._state);\n this._dirty = false;\n }\n }\n\n private _state = false;\n private _dirty = false;\n}\n\nexport default ShadowSwitch;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport const enum Target {\n left = 'left',\n right = 'right',\n up = 'up',\n down = 'down',\n fire = 'fire',\n start = 'start',\n select = 'select',\n pause = 'pause'\n}\n\nexport const enum MappingType {\n button = 'button',\n axis = 'axis'\n}\n\nexport const enum Sign {\n positive = 'positive',\n negative = 'negative'\n}\n\nexport interface ButtonMapping {\n type: MappingType.button;\n\n index: number;\n target: Target;\n}\n\nexport interface AxisMapping {\n type: MappingType.axis;\n\n index: number;\n sign: Sign;\n target: Target;\n}\n\nexport type Mapping = ButtonMapping | AxisMapping;\n\nexport function button(index: number, target: Target): ButtonMapping {\n return {\n type: MappingType.button,\n index,\n target\n };\n}\n\nexport function axis(index: number, sign: Sign, target: Target): AxisMapping {\n return {\n type: MappingType.axis,\n index,\n sign,\n target\n };\n}\n\nexport default Mapping;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Mapping, button, Target, axis, Sign } from './Mapping';\n\nexport const defaultMapping: Array<Mapping> = [\n button(12, Target.up),\n button(13, Target.down),\n button(14, Target.left),\n button(15, Target.right),\n\n button(8, Target.select),\n button(9, Target.start),\n\n ...[0, 1, 2, 3, 10, 11].map(i => button(i, Target.fire)),\n ...[4, 5, 6, 7].map(i => button(i, Target.pause)),\n\n axis(0, Sign.negative, Target.left),\n axis(0, Sign.positive, Target.right),\n axis(1, Sign.negative, Target.up),\n axis(1, Sign.positive, Target.down),\n\n axis(2, Sign.negative, Target.left),\n axis(2, Sign.positive, Target.right),\n axis(3, Sign.negative, Target.up),\n axis(3, Sign.positive, Target.down)\n];\n\nexport default defaultMapping;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport ShadowSwitch from './gamepad/ShadowSwitch';\nimport DigitalJoystickInterface from '../../machine/io/DigitalJoystickInterface';\nimport SwitchInterface from '../../machine/io/SwitchInterface';\nimport { Target, Mapping, MappingType, Sign } from './gamepad/Mapping';\nimport { defaultMapping } from './gamepad/defaultMapping';\n\nconst MIN_POLL_INTERVAL = 50;\n\nexport const joystickTargets: Array<Target> = [\n Target.left,\n Target.right,\n Target.up,\n Target.down,\n Target.fire,\n Target.start,\n Target.select,\n Target.pause\n];\n\nexport type AuxTarget = Target.start | Target.select | Target.pause;\nexport const auxTargets: Array<Target> = [Target.start, Target.select, Target.pause];\n\nfunction readButton(button: GamepadButton | number): boolean {\n return typeof button === 'object' ? button.pressed : button > 0.5;\n}\n\nexport default class GamepadDriver {\n constructor() {\n this.setMapping(defaultMapping);\n }\n\n static probeGamepadCount(): number {\n let cnt = 0;\n\n const gamepads = navigator.getGamepads();\n\n for (let i = 0; i < gamepads.length; i++) {\n if (gamepads[i]) {\n cnt++;\n }\n }\n\n return cnt;\n }\n\n init(): void {\n if (!navigator.getGamepads) {\n throw new Error(`gamepad API not available`);\n }\n\n this.probeGamepads();\n window.addEventListener('gamepadconnected', this._onGamepadConnect);\n window.addEventListener('gamepaddisconnected', this._onGamepadDisconnect);\n }\n\n deinit(): void {\n this.unbind();\n\n window.removeEventListener('gamepadconnected', this._onGamepadConnect);\n window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnect);\n }\n\n bind(\n joysticks: Array<DigitalJoystickInterface> = [],\n auxSwitches: Partial<Record<AuxTarget, SwitchInterface>> = {}\n ): void {\n if (this._bound) {\n return;\n }\n this._bound = true;\n\n this._joysticks = joysticks;\n this._auxSwitches = auxSwitches;\n this._bound = true;\n\n this._shadows = new WeakMap();\n\n this._controlledSwitches().forEach(swtch => {\n const shadow = new ShadowSwitch();\n\n this._shadows.set(swtch, shadow);\n shadow.setState(swtch.read());\n\n swtch.beforeRead.addHandler(GamepadDriver._onBeforeSwitchRead, this);\n });\n }\n\n unbind(): void {\n if (!this._bound) {\n return;\n }\n\n this._controlledSwitches().forEach(swtch =>\n swtch.beforeRead.removeHandler(GamepadDriver._onBeforeSwitchRead, this)\n );\n\n this._shadows = null;\n this._auxSwitches = {};\n this._joysticks = [];\n\n this._bound = false;\n }\n\n getGamepadCount(): number {\n return this._gamepadCount;\n }\n\n setMapping(mapping: Array<Mapping>, id?: string) {\n if (typeof id !== 'undefined') {\n this._mappings.set(id, mapping);\n }\n\n const states = new Map<Target, boolean>();\n const targets: Array<Target> = [];\n\n for (const m of mapping) {\n if (targets.indexOf(m.target)) {\n targets.push(m.target);\n states.set(m.target, false);\n }\n }\n\n this._mappingStates.set(mapping, states);\n this._mappingTargets.set(mapping, targets);\n }\n\n clearMapping(id: string) {\n this._mappings.delete(id);\n }\n\n poll() {\n this._readGamepads();\n }\n\n private static _onBeforeSwitchRead(swtch: SwitchInterface, self: GamepadDriver) {\n self.poll();\n }\n\n private probeGamepads(): void {\n const cnt = GamepadDriver.probeGamepadCount();\n\n if (cnt !== this._gamepadCount) {\n this._gamepadCount = cnt;\n this.gamepadCountChanged.dispatch(this._gamepadCount);\n }\n }\n\n private _getSwitchForTarget(target: Target, joystick: DigitalJoystickInterface = null): SwitchInterface | null {\n if (this._auxSwitches[target as AuxTarget]) {\n return this._auxSwitches[target as AuxTarget];\n }\n\n if (!joystick) {\n return null;\n }\n\n switch (target) {\n case Target.up:\n return joystick.getUp();\n\n case Target.down:\n return joystick.getDown();\n\n case Target.left:\n return joystick.getLeft();\n\n case Target.right:\n return joystick.getRight();\n\n case Target.fire:\n return joystick.getFire();\n\n default:\n return null;\n }\n }\n\n private _controlledSwitches(): Array<SwitchInterface> {\n const switches: Array<SwitchInterface> = [\n ...Object.keys(this._auxSwitches).map(target => this._auxSwitches[target as AuxTarget])\n ];\n\n for (const joystick of this._joysticks) {\n switches.push(\n joystick.getLeft(),\n joystick.getRight(),\n joystick.getUp(),\n joystick.getDown(),\n joystick.getFire()\n );\n }\n\n return switches;\n }\n\n private _readGamepads() {\n const now = Date.now();\n\n if (this._gamepadCount === 0 || now - this._lastPoll < MIN_POLL_INTERVAL) {\n return;\n }\n\n this._lastPoll = now;\n\n const gamepads = navigator.getGamepads();\n\n let joystickIndex = 0;\n\n for (let i = 0; i < gamepads.length; i++) {\n const gamepad = gamepads[i];\n\n if (!gamepad) {\n continue;\n }\n\n const mapping = this._mappings.get(gamepad.id) || defaultMapping;\n\n const states = this._mappingStates.get(mapping);\n const targets = this._mappingTargets.get(mapping);\n\n for (const target of targets) {\n states.set(target, false);\n }\n\n for (const mappingEntry of mapping) {\n switch (mappingEntry.type) {\n case MappingType.button:\n const button = gamepad.buttons[mappingEntry.index];\n\n if (typeof button !== 'undefined' && readButton(button)) {\n states.set(mappingEntry.target, true);\n }\n\n break;\n\n case MappingType.axis:\n const axis = gamepad.axes[mappingEntry.index];\n\n if (\n typeof axis !== 'undefined' &&\n (mappingEntry.sign === Sign.positive ? axis > 0.5 : axis < -0.5)\n ) {\n states.set(mappingEntry.target, true);\n }\n\n break;\n }\n }\n\n for (const target of targets) {\n const swtch = this._getSwitchForTarget(target, this._joysticks[joystickIndex]);\n if (!swtch) {\n continue;\n }\n\n const shadow = this._shadows.get(swtch);\n\n shadow.toggle(states.get(target));\n\n shadow.sync(swtch);\n }\n\n joystickIndex++;\n }\n }\n\n private _onGamepadConnect = () => this.probeGamepads();\n\n private _onGamepadDisconnect = () => this.probeGamepads();\n\n gamepadCountChanged = new Event<number>();\n\n private _shadows: WeakMap<SwitchInterface, ShadowSwitch> = null;\n private _mappings = new Map<string, Array<Mapping>>();\n private _mappingStates = new WeakMap<Array<Mapping>, Map<Target, boolean>>();\n private _mappingTargets = new WeakMap<Array<Mapping>, Array<Target>>();\n\n private _bound = false;\n private _joysticks: Array<DigitalJoystickInterface> = [];\n private _auxSwitches: Partial<Record<AuxTarget, SwitchInterface>> = {};\n\n private _gamepadCount = 0;\n private _lastPoll = 0;\n}\n","/*!\n* screenfull\n* v5.0.2 - 2020-02-13\n* (c) Sindre Sorhus; MIT License\n*/\n(function () {\n\t'use strict';\n\n\tvar document = typeof window !== 'undefined' && typeof window.document !== 'undefined' ? window.document : {};\n\tvar isCommonjs = typeof module !== 'undefined' && module.exports;\n\n\tvar fn = (function () {\n\t\tvar val;\n\n\t\tvar fnMap = [\n\t\t\t[\n\t\t\t\t'requestFullscreen',\n\t\t\t\t'exitFullscreen',\n\t\t\t\t'fullscreenElement',\n\t\t\t\t'fullscreenEnabled',\n\t\t\t\t'fullscreenchange',\n\t\t\t\t'fullscreenerror'\n\t\t\t],\n\t\t\t// New WebKit\n\t\t\t[\n\t\t\t\t'webkitRequestFullscreen',\n\t\t\t\t'webkitExitFullscreen',\n\t\t\t\t'webkitFullscreenElement',\n\t\t\t\t'webkitFullscreenEnabled',\n\t\t\t\t'webkitfullscreenchange',\n\t\t\t\t'webkitfullscreenerror'\n\n\t\t\t],\n\t\t\t// Old WebKit\n\t\t\t[\n\t\t\t\t'webkitRequestFullScreen',\n\t\t\t\t'webkitCancelFullScreen',\n\t\t\t\t'webkitCurrentFullScreenElement',\n\t\t\t\t'webkitCancelFullScreen',\n\t\t\t\t'webkitfullscreenchange',\n\t\t\t\t'webkitfullscreenerror'\n\n\t\t\t],\n\t\t\t[\n\t\t\t\t'mozRequestFullScreen',\n\t\t\t\t'mozCancelFullScreen',\n\t\t\t\t'mozFullScreenElement',\n\t\t\t\t'mozFullScreenEnabled',\n\t\t\t\t'mozfullscreenchange',\n\t\t\t\t'mozfullscreenerror'\n\t\t\t],\n\t\t\t[\n\t\t\t\t'msRequestFullscreen',\n\t\t\t\t'msExitFullscreen',\n\t\t\t\t'msFullscreenElement',\n\t\t\t\t'msFullscreenEnabled',\n\t\t\t\t'MSFullscreenChange',\n\t\t\t\t'MSFullscreenError'\n\t\t\t]\n\t\t];\n\n\t\tvar i = 0;\n\t\tvar l = fnMap.length;\n\t\tvar ret = {};\n\n\t\tfor (; i < l; i++) {\n\t\t\tval = fnMap[i];\n\t\t\tif (val && val[1] in document) {\n\t\t\t\tfor (i = 0; i < val.length; i++) {\n\t\t\t\t\tret[fnMap[0][i]] = val[i];\n\t\t\t\t}\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t})();\n\n\tvar eventNameMap = {\n\t\tchange: fn.fullscreenchange,\n\t\terror: fn.fullscreenerror\n\t};\n\n\tvar screenfull = {\n\t\trequest: function (element) {\n\t\t\treturn new Promise(function (resolve, reject) {\n\t\t\t\tvar onFullScreenEntered = function () {\n\t\t\t\t\tthis.off('change', onFullScreenEntered);\n\t\t\t\t\tresolve();\n\t\t\t\t}.bind(this);\n\n\t\t\t\tthis.on('change', onFullScreenEntered);\n\n\t\t\t\telement = element || document.documentElement;\n\n\t\t\t\tvar returnPromise = element[fn.requestFullscreen]();\n\n\t\t\t\tif (returnPromise instanceof Promise) {\n\t\t\t\t\treturnPromise.then(onFullScreenEntered).catch(reject);\n\t\t\t\t}\n\t\t\t}.bind(this));\n\t\t},\n\t\texit: function () {\n\t\t\treturn new Promise(function (resolve, reject) {\n\t\t\t\tif (!this.isFullscreen) {\n\t\t\t\t\tresolve();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tvar onFullScreenExit = function () {\n\t\t\t\t\tthis.off('change', onFullScreenExit);\n\t\t\t\t\tresolve();\n\t\t\t\t}.bind(this);\n\n\t\t\t\tthis.on('change', onFullScreenExit);\n\n\t\t\t\tvar returnPromise = document[fn.exitFullscreen]();\n\n\t\t\t\tif (returnPromise instanceof Promise) {\n\t\t\t\t\treturnPromise.then(onFullScreenExit).catch(reject);\n\t\t\t\t}\n\t\t\t}.bind(this));\n\t\t},\n\t\ttoggle: function (element) {\n\t\t\treturn this.isFullscreen ? this.exit() : this.request(element);\n\t\t},\n\t\tonchange: function (callback) {\n\t\t\tthis.on('change', callback);\n\t\t},\n\t\tonerror: function (callback) {\n\t\t\tthis.on('error', callback);\n\t\t},\n\t\ton: function (event, callback) {\n\t\t\tvar eventName = eventNameMap[event];\n\t\t\tif (eventName) {\n\t\t\t\tdocument.addEventListener(eventName, callback, false);\n\t\t\t}\n\t\t},\n\t\toff: function (event, callback) {\n\t\t\tvar eventName = eventNameMap[event];\n\t\t\tif (eventName) {\n\t\t\t\tdocument.removeEventListener(eventName, callback, false);\n\t\t\t}\n\t\t},\n\t\traw: fn\n\t};\n\n\tif (!fn) {\n\t\tif (isCommonjs) {\n\t\t\tmodule.exports = {isEnabled: false};\n\t\t} else {\n\t\t\twindow.screenfull = {isEnabled: false};\n\t\t}\n\n\t\treturn;\n\t}\n\n\tObject.defineProperties(screenfull, {\n\t\tisFullscreen: {\n\t\t\tget: function () {\n\t\t\t\treturn Boolean(document[fn.fullscreenElement]);\n\t\t\t}\n\t\t},\n\t\telement: {\n\t\t\tenumerable: true,\n\t\t\tget: function () {\n\t\t\t\treturn document[fn.fullscreenElement];\n\t\t\t}\n\t\t},\n\t\tisEnabled: {\n\t\t\tenumerable: true,\n\t\t\tget: function () {\n\t\t\t\t// Coerce to boolean in case of old WebKit\n\t\t\t\treturn Boolean(document[fn.fullscreenEnabled]);\n\t\t\t}\n\t\t}\n\t});\n\n\tif (isCommonjs) {\n\t\tmodule.exports = screenfull;\n\t} else {\n\t\twindow.screenfull = screenfull;\n\t}\n})();\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport _screenfull, { Screenfull } from 'screenfull';\n\nimport VideoDriver from './Video';\nimport { isIOS } from '../../tools/browser';\n\nconst noFullscrenApi = isIOS;\nconst screenfull = _screenfull as Screenfull;\n\nexport default class FullscreenVideoDriver {\n constructor(\n private _videoDriver: VideoDriver,\n private _zIndex = 100000,\n private _fullscreenClass = 'stellerator-fullscreen'\n ) {}\n\n engage(): void {\n if (this._engaged) {\n return;\n }\n\n this._engaged = true;\n\n if (noFullscrenApi || !screenfull) {\n this._adjustSizeForFullscreen();\n window.addEventListener('resize', this._resizeListener);\n this._engaged = true;\n } else {\n screenfull.on('change', this._changeListener);\n screenfull.request(this._videoDriver.getCanvas());\n }\n }\n\n disengage(): void {\n if (!this._engaged) {\n return;\n }\n\n if (noFullscrenApi || !screenfull) {\n this._resetSize();\n window.removeEventListener('resize', this._resizeListener);\n this._engaged = false;\n } else {\n screenfull.exit();\n }\n }\n\n toggle(): void {\n if (this._engaged) {\n this.disengage();\n } else {\n this.engage();\n }\n }\n\n isEngaged(): boolean {\n return this._engaged;\n }\n\n private _onChange(): void {\n if (!screenfull) {\n return;\n }\n\n if (screenfull.isFullscreen) {\n window.addEventListener('resize', this._resizeListener);\n this._adjustSizeForFullscreen();\n } else {\n this._resetSize();\n window.removeEventListener('resize', this._resizeListener);\n screenfull.off('change', this._changeListener);\n\n this._engaged = false;\n }\n }\n\n private _resetSize() {\n const element = this._videoDriver.getCanvas();\n\n if (this._resizeHandle) {\n clearTimeout(this._resizeHandle);\n this._resizeHandle = null;\n }\n\n element.style.width = '';\n element.style.height = '';\n element.style.maxWidth = '';\n element.style.maxHeight = '';\n\n if (noFullscrenApi) {\n element.style.position = '';\n element.style.top = '';\n element.style.left = '';\n element.style.zIndex = '';\n }\n\n document.body.classList.remove(this._fullscreenClass);\n\n setTimeout(() => this._videoDriver.resize(), 0);\n }\n\n private _adjustSizeForFullscreen() {\n const element = this._videoDriver.getCanvas();\n\n this._videoDriver.resize(window.innerWidth, window.innerHeight);\n element.style.width = window.innerWidth + 'px';\n element.style.height = window.innerHeight + 'px';\n element.style.maxWidth = window.innerWidth + 'px';\n element.style.maxHeight = window.innerHeight + 'px';\n\n if (noFullscrenApi) {\n element.style.position = 'fixed';\n element.style.top = '0';\n element.style.left = '0';\n element.style.zIndex = '' + this._zIndex;\n }\n\n document.body.classList.add(this._fullscreenClass);\n }\n\n private _resizeListener = () => {\n if (this._resizeHandle) {\n return;\n }\n\n this._resizeHandle = setTimeout(() => {\n this._resizeHandle = null;\n this._adjustSizeForFullscreen();\n }, 100);\n };\n\n private _resizeHandle: any = null;\n\n private _changeListener: () => void = this._onChange.bind(this);\n\n private _engaged = false;\n}\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nnamespace CartridgeInfo {\n export enum CartridgeType {\n vanilla_2k = 'vanilla_2k',\n vanilla_4k = 'vanilla_4k',\n\n bankswitch_2k_cv = 'bankswitch_2k_cv',\n\n bankswitch_8k_F8 = 'bankswitch_8k_F8',\n bankswitch_8k_E0 = 'bankswitch_8k_E0',\n bankswitch_8k_3F = 'bankswitch_8k_3F',\n bankswitch_8k_FE = 'bankswitch_8k_FE',\n bankswitch_8k_UA = 'bankswitch_8k_UA',\n bankswitch_8k_DPC = 'bankswitch_8k_DPC',\n bankswitch_8k_econobanking = 'bankswitch_8k_econobanking',\n bankswitch_8k_pp = 'bankswitch_8k_pp',\n\n bankswitch_12k_FA = 'bankswitch_12k_FA',\n\n bankswitch_16k_F6 = 'bankswitch_16k_F6',\n bankswitch_16k_E7 = 'bankswitch_16k_E7',\n\n bankswitch_FA2 = 'bankswitch_FA2',\n\n bankswitch_32k_F4 = 'bankswitch_32k_F4',\n\n bankswitch_64k_F0 = 'bankswitch_64k_F0',\n bankswitch_64k_EF = 'bankswitch_64k_EF',\n\n bankswitch_3E = 'bankswitch_3E',\n bankswitch_supercharger = 'bankswitch_supercharger',\n bankswitch_dpc_plus = 'bankswitch_dpc_plus',\n bankswitch_cdf = 'bankswitch_cdf',\n\n unknown = 'unknown'\n }\n\n export function getAllTypes(): Array<CartridgeType> {\n return [\n CartridgeType.vanilla_2k,\n CartridgeType.vanilla_4k,\n CartridgeType.bankswitch_2k_cv,\n CartridgeType.bankswitch_8k_F8,\n CartridgeType.bankswitch_8k_E0,\n CartridgeType.bankswitch_8k_3F,\n CartridgeType.bankswitch_8k_FE,\n CartridgeType.bankswitch_8k_UA,\n CartridgeType.bankswitch_8k_econobanking,\n CartridgeType.bankswitch_8k_pp,\n CartridgeType.bankswitch_12k_FA,\n CartridgeType.bankswitch_8k_DPC,\n CartridgeType.bankswitch_16k_F6,\n CartridgeType.bankswitch_16k_E7,\n CartridgeType.bankswitch_FA2,\n CartridgeType.bankswitch_32k_F4,\n CartridgeType.bankswitch_3E,\n CartridgeType.bankswitch_64k_F0,\n CartridgeType.bankswitch_64k_EF,\n CartridgeType.bankswitch_supercharger,\n CartridgeType.bankswitch_dpc_plus,\n CartridgeType.bankswitch_cdf,\n CartridgeType.unknown\n ];\n }\n\n export function describeCartridgeType(cartridgeType: CartridgeType): string {\n switch (cartridgeType) {\n case CartridgeType.vanilla_2k:\n return 'plain 2k';\n\n case CartridgeType.vanilla_4k:\n return 'plain 4k';\n\n case CartridgeType.bankswitch_2k_cv:\n return '2k CommaVideo scheme';\n\n case CartridgeType.bankswitch_8k_F8:\n return 'bankswitched 8k, F8 (Atari) scheme';\n\n case CartridgeType.bankswitch_8k_E0:\n return 'bankswitched 8k, E0 (Parker Bros.) scheme';\n\n case CartridgeType.bankswitch_8k_3F:\n return 'bankswitched 8k, 3F (Tigervision) scheme';\n\n case CartridgeType.bankswitch_8k_FE:\n return 'bankswitched 8k, FE (Activision) scheme';\n\n case CartridgeType.bankswitch_8k_UA:\n return 'bankswitched 8k, UA (Pleiades) scheme';\n\n case CartridgeType.bankswitch_8k_pp:\n return 'bankswitched 8k, Pink Panther scheme';\n\n case CartridgeType.bankswitch_12k_FA:\n return 'bankswitched 12k, FA (CBS) scheme';\n\n case CartridgeType.bankswitch_8k_DPC:\n return 'bankswitched 8k + DPC';\n\n case CartridgeType.bankswitch_8k_econobanking:\n return 'bankswitched 8k, econobanking scheme';\n\n case CartridgeType.bankswitch_16k_F6:\n return 'bankswitched 16k, F6 (Atari) scheme';\n\n case CartridgeType.bankswitch_16k_E7:\n return 'bankswitched 16k, E7 (M-Network) scheme';\n\n case CartridgeType.bankswitch_FA2:\n return 'bankswitched 28k/29k, FA2 (modified CBS) scheme';\n\n case CartridgeType.bankswitch_32k_F4:\n return 'bankswitched 32k, F4 (Atari) scheme';\n\n case CartridgeType.bankswitch_3E:\n return 'bankswitched 3E (Tigervision + RAM) scheme';\n\n case CartridgeType.bankswitch_64k_F0:\n return 'bankswitched 64k, F0 (Megaboy) scheme';\n\n case CartridgeType.bankswitch_64k_EF:\n return 'bankswitched 64k, EFSC (Homestar Runner) scheme';\n\n case CartridgeType.bankswitch_supercharger:\n return 'bankswitched supercharger';\n\n case CartridgeType.bankswitch_dpc_plus:\n return 'bankswitched DPC+';\n\n case CartridgeType.bankswitch_cdf:\n return 'bankswitched CDF';\n\n case CartridgeType.unknown:\n return 'unknown';\n }\n }\n}\n\nexport { CartridgeInfo as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\n\nimport Switch from './Switch';\nimport SwitchIO from '../../../machine/io/SwitchInterface';\n\nclass SwitchProxy implements Switch {\n bind(swtch: SwitchIO): void {\n this.unbind();\n\n this._boundSwitch = swtch;\n this._boundSwitch.toggle(this._state);\n\n this._boundSwitch.stateChanged.addHandler(SwitchProxy._onBoundStateChange, this);\n this._setState(this._boundSwitch.read());\n }\n\n unbind(): void {\n if (!this._boundSwitch) {\n return;\n }\n\n this._boundSwitch.stateChanged.removeHandler(SwitchProxy._onBoundStateChange, this);\n this._boundSwitch = null;\n }\n\n toggle(state: boolean): this {\n if (this._boundSwitch) {\n this._boundSwitch.toggle(state);\n } else {\n this._setState(state);\n }\n\n return this;\n }\n\n read(): boolean {\n return this._state;\n }\n\n private static _onBoundStateChange(newState: boolean, self: SwitchProxy) {\n self._setState(newState);\n }\n\n private _setState(newState: boolean) {\n if (newState !== this._state) {\n this._state = newState;\n this.stateChange.dispatch(this._state);\n }\n }\n\n stateChange = new Event<boolean>();\n\n private _state = false;\n private _boundSwitch: SwitchIO = null;\n}\n\nexport { SwitchProxy as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Switch from './Switch';\nimport SwitchProxy from './SwitchProxy';\nimport ControlPanel from './ControlPanel';\nimport StellaControlPanel from '../../../machine/stella/ControlPanelInterface';\n\nclass ControlPanelProxy implements ControlPanel {\n bind(controlPanel: StellaControlPanel): void {\n this.unbind();\n\n this._boundControlPanel = controlPanel;\n\n this._reset.bind(this._boundControlPanel.getResetButton());\n this._select.bind(this._boundControlPanel.getSelectSwitch());\n this._difficultyPlayer1.bind(this._boundControlPanel.getDifficultySwitchP0());\n this._difficultyPlayer2.bind(this._boundControlPanel.getDifficultySwitchP1());\n this._color.bind(this._boundControlPanel.getColorSwitch());\n\n this._difficultyPlayer1.toggle(true);\n this._difficultyPlayer2.toggle(true);\n }\n\n unbind(): void {\n if (!this._boundControlPanel) {\n return;\n }\n\n this._reset.unbind();\n this._select.unbind();\n this._difficultyPlayer1.unbind();\n this._difficultyPlayer2.unbind();\n this._color.unbind();\n\n this._boundControlPanel = null;\n }\n\n reset(): Switch {\n return this._reset;\n }\n\n select(): Switch {\n return this._select;\n }\n\n difficultyPlayer1(): Switch {\n return this._difficultyPlayer1;\n }\n\n difficultyPlayer2(): Switch {\n return this._difficultyPlayer2;\n }\n\n color(): Switch {\n return this._color;\n }\n\n private _reset = new SwitchProxy();\n private _select = new SwitchProxy();\n private _difficultyPlayer1 = new SwitchProxy();\n private _difficultyPlayer2 = new SwitchProxy();\n private _color = new SwitchProxy();\n\n private _boundControlPanel: StellaControlPanel = null;\n}\n\nexport { ControlPanelProxy as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Event } from 'microevent.ts';\nimport AsyncIOInterface from '../../machine/io/AsyncIOInterface';\n\nclass AsyncIO {\n bind(io: AsyncIOInterface | null): void {\n if (this._io) {\n return;\n }\n\n if (io) {\n io.message.addHandler(AsyncIO._onAsyncIOMessage, this);\n }\n\n this._io = io;\n }\n\n unbind(): void {\n if (!this._io) {\n return;\n }\n\n this._io.message.removeHandler(AsyncIO._onAsyncIOMessage, this);\n\n this._io = null;\n }\n\n send(message: ArrayLike<number>): void {\n if (this._io) {\n this._io.send(message);\n }\n }\n\n private static _onAsyncIOMessage(message: ArrayLike<number>, self: AsyncIO): void {\n self.message.dispatch(message);\n }\n\n message = new Event<ArrayLike<number>>();\n\n private _io: AsyncIOInterface = null;\n}\n\nexport default AsyncIO;\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Mutex } from 'async-mutex';\nimport { EventInterface as Event, Event as EventImplementation } from 'microevent.ts';\n\nimport EmulationServiceInterface from '../../stella/service/EmulationServiceInterface';\nimport EmulationService from '../../stella/service/worker/EmulationService';\nimport DriverManager from '../../stella/service/DriverManager';\n\nimport VideoDriver from '../../driver/Video';\n\nimport AudioDriver from '../../stella/driver/WebAudio';\nimport KeyboardIO from '../../stella/driver/KeyboardIO';\nimport TouchIO from '../../stella/driver/TouchIO';\nimport Paddle from '../../driver/MouseAsPaddle';\nimport Gamepad from '../../driver/Gamepad';\nimport FullscreenDriver from '../../driver/FullscreenVideo';\n\nimport CartridgeInfo from '../../../machine/stella/cartridge/CartridgeInfo';\nimport StellaConfig from '../../../machine/stella/Config';\n\nimport { decode as decodeBase64 } from '../../../tools/base64';\n\nimport ControlPanel from './ControlPanel';\nimport ControlPanelProxy from './ControlPanelProxy';\nimport { Target } from '../../driver/gamepad/Mapping';\nimport CpuFactory from '../../../machine/cpu/Factory';\nimport AsyncIO from '../../driver/AsyncIO';\n\nfunction cpuType(config = Stellerator.CpuAccuracy.cycle): CpuFactory.Type {\n switch (config) {\n case Stellerator.CpuAccuracy.cycle:\n return CpuFactory.Type.stateMachine;\n\n case Stellerator.CpuAccuracy.instruction:\n return CpuFactory.Type.batchedAccess;\n\n default:\n throw new Error(`invalid CPU Accuracy: ${config}`);\n }\n}\n\n/**\n * The stellerator class and namespace. In a typical application, a single instance is\n * created and bound to a canvas element. This instance can than be used to run many\n * different ROMs during its lifetime.\n *\n * Notes on reading this documentation:\n * * All code examples are ES6\n * * The actual emulation runs on a web worker, and all methods that control emulation\n * are asynchronous and return [ES6 Promises](http://exploringjs.com/es6/ch_promises.html)\n * * Check out the [microevent.ts](https://github.com/DirtyHairy/microevent) documentation\n * for the event API\n *\n * Basic example:\n * ```typescript\n * const stellerator = new Stellerator(\n * document.getElementById('stellerator-canvas'),\n * 'js/stellerator_worker.js'\n * );\n *\n * stellerator.run(rom, Stellerator.TvMode.ntsc);\n * ```\n */\nexport class Stellerator {\n /**\n * Creates an instance of Stellerator.\n * @param canvasElt The canvas element that is used to display the TIA image.\n * The `height` and `width` attributes of the canvas will be automatically\n * maintained by Stellerator, so there is not requirement to set those to\n * specific values.\n *\n * @param workerUrl The URL from which the web worker will be loaded.\n * In order to avoid cross domain issues, the worker should be hosted on the same\n * domain as the stellerator build, and this parameter should read e.g.\n * `js/stellerator_worker.js`\n *\n * @param config Optional configuration to\n * customize emulator behavior. See [[Config]] for a full explanation of the values\n * and their default.\n */\n constructor(\n canvasElt: HTMLCanvasElement | null = null,\n workerUrl: string,\n config: Partial<Stellerator.Config> = {}\n ) {\n this._canvasElt = canvasElt;\n\n this._config = {\n gamma: 1,\n scalingMode: Stellerator.ScalingMode.qis,\n tvEmulation: Stellerator.TvEmulation.composite,\n phosphorLevel: 0.5,\n scanlineLevel: 0.2,\n audio: true,\n volume: 0.5,\n enableKeyboard: true,\n enableTouch: true,\n touchLeftHanded: false,\n touchJoystickSensitivity: 15,\n keyboardTarget: document,\n fullscreenViaKeyboard: true,\n paddleViaMouse: true,\n pauseViaKeyboard: true,\n pauseViaTouch: true,\n fullscreenViaTouch: true,\n enableGamepad: true,\n resetViaKeyboard: true,\n\n ...config,\n };\n\n this._emulationService = new EmulationService(workerUrl);\n\n this.frequencyUpdate = this._emulationService.frequencyUpdate;\n\n const stateChange = new EventImplementation<Stellerator.State>();\n this._emulationService.stateChanged.addHandler((newState) => stateChange.dispatch(this._mapState(newState)));\n this.stateChange = stateChange;\n\n this._createDrivers();\n\n this._driverManager.addDriver(this._controlPanel, (context) =>\n this._controlPanel.bind(context.getControlPanel())\n );\n this._driverManager.bind(this._emulationService);\n\n this._serviceInitialized = this._emulationService.init().then(undefined, (e) => {\n console.log(e);\n throw e;\n });\n }\n\n /**\n * Set the gamma correction factor. Will take effect **only** if WebGL is available.\n *\n * @param gamma\n */\n setGamma(gamma: number): this {\n this._config.gamma = gamma;\n this._createVideoDriver();\n\n return this;\n }\n\n /**\n * Query the current gamme correction factor.\n *\n * @returns {number}\n */\n getGamma(): number {\n return this._config.gamma;\n }\n\n /**\n * Configures the scaling mode.\n *\n * @param scalingMode\n */\n setScalingMode(scalingMode: Stellerator.ScalingMode): this {\n this._config.scalingMode = scalingMode;\n this._createVideoDriver();\n\n return this;\n }\n\n /**\n * Query the current scaling mode.\n */\n getScalingMode(): Stellerator.ScalingMode {\n return this._config.scalingMode;\n }\n\n /**\n * Configures the TV emulation mode.\n *\n * @param tvEmulation\n */\n setTvEmulation(tvEmulation: Stellerator.TvEmulation): this {\n this._config.tvEmulation = tvEmulation;\n this._createVideoDriver();\n\n return this;\n }\n\n /**\n * Query the current TV emulation mode.\n */\n getTvEmulation(): Stellerator.TvEmulation {\n return this._config.tvEmulation;\n }\n\n /**\n * Configure the phosphore level.\n *\n * @param phosphorLevel\n */\n setPhosphorLevel(phosphorLevel: number): this {\n this._config.phosphorLevel = phosphorLevel;\n this._createVideoDriver();\n\n return this;\n }\n\n /**\n * Query the current phosphor level\n */\n getPhosphorLevel(): number {\n return this._config.phosphorLevel;\n }\n\n /**\n * Configure the scanline level.\n *\n * @param scanlineLevel\n */\n setScanlineLevel(scanlineLevel: number): this {\n this._config.scanlineLevel = scanlineLevel;\n this._createVideoDriver();\n\n return this;\n }\n\n /**\n * Query the current scanline level.\n */\n getScanlineLevel(): number {\n return this._config.scanlineLevel;\n }\n\n /**\n * Enable / disable fullscreen mode.\n *\n * @param fullscreen\n * @returns {this}\n */\n toggleFullscreen(fullscreen?: boolean): this {\n if (!this._fullscreenVideo) {\n return this;\n }\n\n if (typeof fullscreen === 'undefined') {\n this._fullscreenVideo.toggle();\n } else {\n fullscreen ? this._fullscreenVideo.engage() : this._fullscreenVideo.disengage();\n }\n\n return this;\n }\n\n /**\n * Query if emulator is running fullscreen.\n *\n * @returns {boolean}\n */\n isFullscreen(): boolean {\n return this._fullscreenVideo ? this._fullscreenVideo.isEngaged() : false;\n }\n\n /**\n * Change the master volume.\n *\n * @param volume Will be clipped to the range 0 .. 1\n * @returns {this}\n */\n setVolume(volume: number): this {\n if (this._audioDriver) {\n this._audioDriver.setMasterVolume(Math.max(Math.min(volume, 1), 0));\n }\n\n return this;\n }\n\n /**\n * Query whether audio has been enabled on this instance.\n *\n * @returns {boolean}\n */\n audioEnabled(): boolean {\n return !!this._audioDriver;\n }\n\n /**\n * Query the master volume.\n *\n * @returns {number}\n */\n getVolume(): number {\n return this._audioDriver ? this._audioDriver.getMasterVolume() : 0;\n }\n\n /**\n * Notify the video driver of a change of the visible dimensions (client size) of\n * the canvas element. This will cause the driver to adjust the resolution to match.\n */\n resize(): this {\n if (this._videoDriver) {\n this._videoDriver.resize();\n }\n\n return this;\n }\n\n /**\n * Query the current state of the emulation.\n *\n * @returns {Stellerator.State}\n */\n getState(): Stellerator.State {\n return this._state;\n }\n\n /**\n * Get the console control panel. This allows you to monitor and control\n * the console switches (select, reset, difficulty P1 / P2, color / BW).\n */\n getControlPanel(): ControlPanel {\n return this._controlPanel;\n }\n\n setCanvas(canvas: HTMLCanvasElement): this {\n this._canvasElt = canvas;\n\n this._createVideoDriver();\n this._createTouchDriver();\n\n return this;\n }\n\n releaseCanvas(): this {\n this._removeVideoDriver();\n this._removeTouchDriver();\n\n this._canvasElt = null;\n\n return this;\n }\n\n /**\n * Start emulation of a cartridge image. This method is **async** and returns\n * a promise for the resulting emulation state.\n *\n * **IMPORTANT:** The emulator will start up in [[State.paused]] mode. Use the `run` method\n * below in order to start and run the emulation immediatelly.\n *\n * @param cartridge The cartridge image. Can be either\n * an array / typed array of byte values or a base64 encoded string.\n *\n * @param tvMode The TV mode (NTSC / PAL / SECAM)\n *\n * @param config Optional configuration\n * values to customize emulation behavior. See [[CartridgeConfig]] for a full list of supported\n * settings and their defaults.\n *\n * @returns {Promise<Stellerator.State>}\n */\n start(\n cartridge: ArrayLike<number> | string,\n tvMode: Stellerator.TvMode,\n config: Partial<Stellerator.CartridgeConfig> = {}\n ): Promise<Stellerator.State> {\n return this._mutex.runExclusive(async () => {\n if (typeof cartridge === 'string') {\n cartridge = decodeBase64(cartridge);\n }\n\n const stellaConfig = StellaConfig.create({\n tvMode: this._convertTvMode(tvMode),\n pcmAudio: true,\n });\n\n if (typeof config.randomSeed !== 'undefined' && config.randomSeed > 0) {\n stellaConfig.randomSeed = config.randomSeed;\n }\n\n if (typeof config.emulatePaddles !== 'undefined') {\n stellaConfig.emulatePaddles = config.emulatePaddles;\n }\n\n if (typeof config.frameStart !== 'undefined') {\n stellaConfig.frameStart = config.frameStart;\n }\n\n stellaConfig.cpuType = cpuType(config.cpuAccuracy);\n\n await this._serviceInitialized;\n\n return (this._state = this._mapState(\n await this._emulationService.start(\n cartridge,\n { ...stellaConfig, asyncIO: config.asyncIO },\n config.cartridgeType\n )\n ));\n });\n }\n\n /**\n * Like [[start]], but run the emulator immediatelly instead of starting\n * in paused mode.\n *\n * Just like its counterpart, this method is **async** and returns a promise\n * for the resulting emualtion state.\n *\n * @param cartridge The cartridge image. Can be either\n * an array / typed array of byte values or a base64 encoded string.\n *\n * @param tvMode The TV mode (NTSC / PAL / SECAM)\n *\n * @param config Optional configuration\n * values to customize emulation behavior. See [[CartridgeConfig]] for a full list of supported\n * settings and their defaults.\n *\n * @returns {Promise<Stellerator.State>}\n */\n async run(\n cartridge: ArrayLike<number> | string,\n tvMode: Stellerator.TvMode,\n config: Partial<Stellerator.CartridgeConfig> = {}\n ): Promise<Stellerator.State> {\n if ((await this.start(cartridge, tvMode, config)) === Stellerator.State.paused) {\n return this.resume();\n }\n }\n\n /**\n * Pause a running emulation session. This method is **async** and returns a\n * promise for the resulting emulation state.\n *\n * @returns {Promise<Stellerator.State>}\n */\n async pause(): Promise<Stellerator.State> {\n await this._serviceInitialized;\n\n return this._mutex.runExclusive(\n async () => (this._state = this._mapState(await this._emulationService.pause()))\n );\n }\n\n /**\n * Resume a paused emulation session. This method is **async** and returns a\n * promise for the resulting emulation state.\n *\n * @returns {Promise<Stellerator.State>}\n */\n async resume(): Promise<Stellerator.State> {\n await this._serviceInitialized;\n\n return this._mutex.runExclusive(\n async () => (this._state = this._mapState(await this._emulationService.resume()))\n );\n }\n\n /**\n * Stop a running or paused emulation session. This method is **async** and returns a\n * promise for the resulting emulation state.\n *\n * @returns {Promise<Stellerator.State>}\n */\n async stop(): Promise<Stellerator.State> {\n await this._serviceInitialized;\n\n return this._mutex.runExclusive(\n async () => (this._state = this._mapState(await this._emulationService.stop()))\n );\n }\n\n /**\n * Reset a running emulation session. This method is **async** and returns a\n * promise for the resulting emulation state.\n *\n * @returns {Promise<Stellerator.State>}\n */\n async reset(): Promise<Stellerator.State> {\n await this._serviceInitialized;\n\n return this._mutex.runExclusive(\n async () => (this._state = this._mapState(await this._emulationService.reset()))\n );\n }\n\n /**\n * Retrieve the last emulation error.\n *\n * **IMPORTANT:** Don't use this to check whether an error occurred; use [[getState]]\n * and check for [[State.error]] instead.\n *\n * @returns {Error}\n */\n lastError(): Error {\n return this._emulationService.getLastError();\n }\n\n asyncIOSend(message: ArrayLike<number>): this {\n this._asyncIO.send(message);\n\n return this;\n }\n\n private _convertTvMode(tvMode: Stellerator.TvMode): StellaConfig.TvMode {\n switch (tvMode) {\n case Stellerator.TvMode.ntsc:\n return StellaConfig.TvMode.ntsc;\n\n case Stellerator.TvMode.pal:\n return StellaConfig.TvMode.pal;\n\n case Stellerator.TvMode.secam:\n return StellaConfig.TvMode.secam;\n\n default:\n throw new Error(`invalid TV mode '${tvMode}'`);\n }\n }\n\n private _createDrivers(): void {\n this._createVideoDriver();\n\n if (this._config.audio) {\n try {\n this._audioDriver = new AudioDriver();\n this._audioDriver.init();\n this._audioDriver.setMasterVolume(this._config.volume);\n\n this._driverManager.addDriver(this._audioDriver, (context) =>\n this._audioDriver.bind(true, [context.getPCMChannel()])\n );\n\n this._emulationService.stateChanged.addHandler((newState) => {\n switch (newState) {\n case EmulationServiceInterface.State.running:\n this._audioDriver.resume();\n break;\n\n default:\n this._audioDriver.pause();\n break;\n }\n });\n } catch (e) {\n console.error(`failed to initialize audio: ${e && e.message}`);\n }\n }\n\n this._createTouchDriver();\n\n if (this._config.enableKeyboard) {\n this._keyboardIO = new KeyboardIO(this._config.keyboardTarget);\n\n this._driverManager.addDriver(this._keyboardIO, (context) =>\n this._keyboardIO.bind(context.getJoystick(0), context.getJoystick(1), context.getControlPanel())\n );\n\n if (this._config.fullscreenViaKeyboard) {\n this._keyboardIO.toggleFullscreen.addHandler(\n () => this._fullscreenVideo && this._fullscreenVideo.toggle()\n );\n }\n\n if (this._config.pauseViaKeyboard) {\n this._keyboardIO.togglePause.addHandler(this._pauseHandler);\n }\n }\n\n if (this._config.resetViaKeyboard) {\n this._keyboardIO.hardReset.addHandler(() => this.reset());\n }\n\n if (this._config.enableGamepad) {\n this._gamepad = new Gamepad();\n this._gamepad.init();\n\n this._driverManager.addDriver(this._gamepad, (context) =>\n this._gamepad.bind([context.getJoystick(0), context.getJoystick(1)], {\n [Target.start]: context.getControlPanel().getResetButton(),\n [Target.select]: context.getControlPanel().getSelectSwitch(),\n })\n );\n }\n\n if (this._config.paddleViaMouse) {\n this._paddle = new Paddle();\n\n this._driverManager.addDriver(this._paddle, (context) => this._paddle.bind(context.getPaddle(0)));\n }\n\n this._asyncIO = new AsyncIO();\n this.asyncIOMessage = this._asyncIO.message;\n this._driverManager.addDriver(this._asyncIO, (context, driver: AsyncIO) => driver.bind(context.getAsyncIO()));\n }\n\n private _removeVideoDriver(): void {\n if (!this._videoDriver) {\n return;\n }\n\n this._videoDriver.unbind();\n\n this._driverManager.removeDriver(this._videoDriver);\n\n this._fullscreenVideo.disengage();\n\n this._fullscreenVideo = null;\n this._videoDriver = null;\n }\n\n private _createVideoDriver(): void {\n if (this._videoDriver) {\n this._removeVideoDriver();\n }\n\n if (!this._canvasElt) {\n return;\n }\n\n // FIXME: configuration\n this._videoDriver = new VideoDriver(this._canvasElt, {\n gamma: this._config.gamma,\n scalingMode: this._config.scalingMode as any,\n tvEmulation: this._config.tvEmulation as any,\n phosphorLevel: this._config.phosphorLevel,\n scanlineLevel: this._config.scanlineLevel,\n }).init();\n\n this._driverManager.addDriver(this._videoDriver, (context) => this._videoDriver.bind(context.getVideo()));\n\n this._fullscreenVideo = new FullscreenDriver(this._videoDriver);\n }\n\n private _removeTouchDriver() {\n if (!this._touchIO) {\n return;\n }\n\n this._touchIO.unbind();\n\n this._driverManager.removeDriver(this._touchIO);\n\n this._touchIO = null;\n }\n\n private _createTouchDriver() {\n if (this._touchIO) {\n this._removeTouchDriver();\n }\n if (this._config.enableTouch) {\n this._touchIO = new TouchIO(\n this._canvasElt,\n this._config.touchJoystickSensitivity,\n this._config.touchLeftHanded\n );\n\n this._driverManager.addDriver(this._touchIO, (context) =>\n this._touchIO.bind(context.getJoystick(0), context.getControlPanel())\n );\n\n if (this._config.pauseViaTouch) {\n this._touchIO.togglePause.addHandler(this._pauseHandler);\n }\n\n if (this._config.fullscreenViaTouch) {\n this._touchIO.toggleFullscreen.addHandler(\n () => this._fullscreenVideo && this._fullscreenVideo.toggle()\n );\n }\n }\n }\n\n private _mapState(state: EmulationServiceInterface.State): Stellerator.State {\n switch (state) {\n case EmulationServiceInterface.State.stopped:\n return Stellerator.State.stopped;\n\n case EmulationServiceInterface.State.running:\n return Stellerator.State.running;\n\n case EmulationServiceInterface.State.paused:\n return Stellerator.State.paused;\n\n case EmulationServiceInterface.State.error:\n return Stellerator.State.error;\n\n default:\n throw new Error('cannot happen');\n }\n }\n\n private _pauseHandler: () => void = () => {\n switch (this._emulationService.getState()) {\n case EmulationServiceInterface.State.paused:\n this.resume();\n break;\n\n case EmulationServiceInterface.State.running:\n this.pause();\n break;\n }\n };\n\n /**\n * Subscribe to this event to receive periodic updates on the frequency of the\n * emulated system. The unit is Hz. Check out the\n * [microevent.ts](https://github.com/DirtyHairy/microevent)\n * documentation on the event API.\n *\n * Example (using JQuery to display emulation speed):\n * ```typescript\n * stellerator.frequencyUpdate.addHandler(\n * frequency => $('emulation-speed').text(`System speed: ${(frequency / 1e6).toFixed(2)} MHz`)\n * );\n * ```\n */\n frequencyUpdate: Event<number>;\n\n /**\n * Subscribe to this event to receive messages that are sent from the ROM running\n * inside the emulator via the data tap.\n *\n * @type {Event<ArrayLike<number>>}\n * @memberof Stellerator\n */\n asyncIOMessage: Event<ArrayLike<number>>;\n\n /**\n * This event is dispatched whenever emulation state changes. Check out the\n * [microevent.ts](https://github.com/DirtyHairy/microevent)\n * documentation on the event API.\n *\n * Example (using JQuery to display an error message):\n * ```typescript\n * stellerator.stateChange.addHandler(\n * state => {\n * if (state === Stellerator.State.error) {\n * $('error-message').text(stellerator.lastError().message);\n * }\n * }\n * );\n * ```\n */\n stateChange: Event<Stellerator.State>;\n\n private _canvasElt: HTMLCanvasElement = null;\n private _config: Stellerator.Config = null;\n private _emulationService: EmulationServiceInterface = null;\n private _serviceInitialized: Promise<void> = null;\n\n private _videoDriver: VideoDriver = null;\n private _fullscreenVideo: FullscreenDriver = null;\n private _audioDriver: AudioDriver = null;\n private _keyboardIO: KeyboardIO = null;\n private _asyncIO: AsyncIO = null;\n private _touchIO: TouchIO = null;\n private _paddle: Paddle = null;\n private _gamepad: Gamepad = null;\n\n private _controlPanel = new ControlPanelProxy();\n\n private _state = Stellerator.State.stopped;\n\n private _driverManager = new DriverManager();\n\n private _mutex = new Mutex();\n}\n\nexport namespace Stellerator {\n /**\n * General emulator configuration. The configuration is set on construction of the\n * stellerator instance. Each setting is strictly optional and has a default\n * value.\n */\n export interface Config {\n /**\n * Gamma correction. Will take effect **only** if WebGL is available.\n *\n * Default: true\n */\n gamma: number;\n\n /**\n * Scaling mode.\n *\n * Default: qis (quasi-integer scaling)\n */\n scalingMode: ScalingMode;\n\n /**\n * TV emulation\n *\n * Default: composite\n */\n tvEmulation: TvEmulation;\n\n /**\n * Phosphor level. Valid values are between 0 and 1.\n * A value of 0 disables phosphor emulation.\n *\n * Default: 0.5\n */\n phosphorLevel: number;\n\n /**\n * Scanlone leve. Valid values are between 0 an 1. A value of 0 disables scanlines.\n *\n * Default: 0.2\n */\n scanlineLevel: number;\n\n /**\n * Enable audio.\n *\n * Default: true\n */\n audio: boolean;\n\n /**\n * Master volume.\n *\n * Default: 0.5\n */\n volume: number;\n\n /**\n * Enable keyboard for joysticks and reset / resume.\n *\n * Default: true\n *\n */\n enableKeyboard: boolean;\n\n /**\n * Enable touch controls for left joystick and reset / resume.\n *\n * Default: true\n */\n enableTouch: boolean;\n\n /**\n * Mirror touch controls for left handed users.\n *\n * Default: false\n */\n touchLeftHanded: boolean;\n\n /**\n * Touch control joystick emulation sensitivity (in pixels).\n *\n * Default: 15\n */\n touchJoystickSensitivity: number;\n\n /**\n * Specify an HTML element on which the driver listens for keyboard\n * events.\n *\n * Default: document\n */\n keyboardTarget: HTMLElement | HTMLDocument;\n\n /**\n * Toggle fullscreen with \"enter\". Applicable **only** if `enableKeyboard`\n * is set.\n *\n * Default: true\n */\n fullscreenViaKeyboard: boolean;\n\n /**\n * Toggle pause with \"p\". Applicable **only** if `enableKeyboard` is set.\n *\n * Default: true\n */\n pauseViaKeyboard: boolean;\n\n /**\n * Reset emulation with \"shift-r\".\n *\n * Default: true\n */\n resetViaKeyboard: boolean;\n\n /**\n * Toggle pause via touch controls. Applicable **only** if `enableTouch` is set.\n *\n * Default: true\n */\n pauseViaTouch: boolean;\n\n /**\n * Toggle fullscreen via touch controls. Applicable **only** if `enableTouch` is set.\n */\n fullscreenViaTouch: boolean;\n\n /**\n * Emulate the first paddlewith the horizontal movement of the mouse.\n *\n * Default: true\n *\n */\n paddleViaMouse: boolean;\n\n /**\n * Enable gamepad support.\n *\n * Default: true\n */\n enableGamepad: boolean;\n }\n\n /**\n * TV mode constants\n */\n export enum TvMode {\n /**\n * NTSC\n */\n ntsc = 'ntsc',\n /**\n * PAL\n */\n pal = 'pal',\n /**\n * SECAM\n */\n secam = 'secam',\n }\n\n /**\n * TV emulation modes. Enabling TV emulation may cause visual artifacts on some\n * (ancient) GPUs\n */\n export enum TvEmulation {\n /**\n * Composite\n */\n composite = VideoDriver.TvEmulation.composite,\n /**\n * S-Video\n */\n svideo = VideoDriver.TvEmulation.svideo,\n /**\n * No TV emulation\n */\n none = VideoDriver.TvEmulation.none,\n }\n\n /**\n * Scaling algorithm\n */\n export enum ScalingMode {\n /**\n * Quasi-integer scaling. This is slightly more expensive than bilinear scaling\n * but gives a nice, sharp image while avoiding Moirée patterns.\n */\n qis = VideoDriver.ScalingMode.qis,\n /**\n * Plain bilinear scaling. Blurry and fast, avoids Moirée patterns.\n */\n bilinear = VideoDriver.ScalingMode.bilinear,\n /**\n * Nearest neighbour interpolation\n */\n none = VideoDriver.ScalingMode.none,\n }\n\n /**\n * Optional configuration for a specific cartridge. This configuration is passed to\n * the emulator together with a cartridge image for emulation. Each setting\n * is strictly optional and has a default value.\n */\n export interface CartridgeConfig {\n /**\n * Specify the cartridge type. The default is autodetection which should\n * work fine in almost all cases.\n *\n * Default: undefined [autodetect]\n */\n cartridgeType: CartridgeInfo.CartridgeType;\n\n /**\n * Random number generator seed. This is used to initialize the initial\n * hardware state. The default is automatic, which uses a random seed.\n *\n * Default: undefined [automatic]\n */\n randomSeed: number;\n\n /**\n * Emulate paddles.\n *\n * Default: true\n */\n emulatePaddles: boolean;\n\n /**\n * The first visible scanline of the frame. The default is autodetection, which\n * should work fine for most cases.\n *\n * Default: undefined [autodetect]\n */\n frameStart: number;\n\n /**\n * The accuracy of the CPU core (see below).\n *\n * Default: cycle (high precision)\n */\n cpuAccuracy: CpuAccuracy;\n\n /**\n * Enable the data tap.\n *\n * Default: false\n */\n asyncIO: boolean;\n }\n\n /**\n * The CartridgeType enum. Reexported from the `CartridgeInfo` module. Please check the\n * [source](https://github.com/6502ts/6502.ts/blob/master/src/machine/stella/cartridge/CartridgeInfo.ts)\n * for the various possible values if you really need this setting.\n *\n * Example:\n * ```typescript\n * stellerator.run(cartridgeImage, Stellerator.TvMode.ntsc, {\n * cartridgeType: Stellerator.CartridgeType.bankswitch_DPC\n * });\n * ```\n */\n export const CartridgeType = CartridgeInfo.CartridgeType;\n\n /**\n * This function takes a cartridge type and returns a human readable\n * description suitable for building an UI. Reexported from the `CartridgeInfo` module.\n *\n * Example:\n * ```typescript\n * const description = Stellerator.describeCartridgeType(\n * Stellerator.CartridgeType.bankswitch_DPC\n * );\n * ```\n */\n export const describeCartridgeType: (cartridgeType: CartridgeInfo.CartridgeType) => string =\n CartridgeInfo.describeCartridgeType;\n\n /**\n * This function returns an array of all possible cartridge types suitable for building an UI.\n * Reexported from the `CartridgeInfo` module.\n */\n export const allCartridgeTypes: () => Array<CartridgeInfo.CartridgeType> = CartridgeInfo.getAllTypes;\n\n /**\n * The different possible states of the emulation.\n */\n export enum State {\n running = 'running',\n /**\n * Emulation has been paused and can be stopped or continued.\n */\n paused = 'paused',\n /**\n * Emulation has been stopped regularily.\n */\n stopped = 'stopped',\n /**\n * Emulation has been stopped by an error.\n */\n error = 'error',\n }\n\n /**\n * The different possible CPU emulation modes.\n */\n export enum CpuAccuracy {\n /**\n * True cycle-exact CPU emulation. High accuracy.\n */\n cycle = 'cycle',\n /**\n * Less accurate memory access patters. Slightly less accurate, but faster\n */\n instruction = 'instruction',\n }\n}\n\nexport { Stellerator as default };\n","/*\n * This file is part of 6502.ts, an emulator for 6502 based systems built\n * in Typescript\n *\n * Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport Stellerator from './Stellerator';\n\nexport default {\n Stellerator\n};\n"],"names":["__decorate","decorators","target","key","desc","d","c","arguments","length","r","Object","getOwnPropertyDescriptor","Reflect","decorate","i","defineProperty","__metadata","metadataKey","metadataValue","metadata","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","__generator","body","f","y","t","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","this","n","v","op","TypeError","call","pop","push","Semaphore","_maxConcurrency","_queue","Error","_value","prototype","acquire","_this","locked","isLocked","ticket","_dispatch","runExclusive","callback","_a","release","_b","_currentReleaser","undefined","nextConsumer","shift","released","Mutex","_semaphore","exports","factories","getFactory","handlerCount","src","argsHandlers","argsContexts","Function","bind","concat","compileFactory","context","payload","Event","hasHandlers","_handlers","_contexts","_createDispatcher","addHandler","handler","isHandlerAttached","_updateHasHandlers","removeHandler","idx","_getHandlerIndex","splice","dispatch","Event_1","default","EmulationServiceInterface","State","MSG_RESOLVE_TRANSACTION","MSG_REJECT_TRANSACTION","MSG_ERROR","RpcProvider","_rpcTimeout","error","microevent_ts_1","_rpcHandlers","_signalHandlers","_pendingTransactions","_nextTransactionId","message","type","MessageType","signal","_handleSignal","rpc","_handeRpc","internal","_handleInternal","_raiseError","id","transfer","transactionId","transaction","timeoutHandle","setTimeout","_transactionTimeout","registerRpcHandler","registerSignalHandler","deregisterRpcHandler","deregisterSignalHandler","filter","h","forEach","reason","_clearTransaction","clearTimeout","RpcProvider_1","EmulationContext","[object Object]","_videoProxy","_controlProxy","_waveformChannels","_pcmChannel","_asyncIOProxy","config","_config","getJoystick","getControlPanel","getPaddle","PoolMember","_releaseCB","_disposeCB","Pool","_factory","dispose","member","_poolSize","newItem","victim","_releaseMember","_disposeMember","_pool","_isAvailable","_isDisposed","position","_poolPosition","event","get","RPC_TYPE","emulationPause","emulationReset","emulationResume","emulationSetRateLimit","emulationStart","emulationStop","emulationFetchLastError","getVideoParameters","getWaveformAudioParameters","index","getPCMAudioParameters","setup","freeze","SIGNAL_TYPE","emulationError","emulationFrequencyUpdate","videoNewFrame","videoReturnSurface","controlStateUpdate","waveformAudioVolumeChange","waveformAudioBufferChange","pcmAudioNewFrame","pcmAudioTogglePause","pcmAudioReturnFrame","audioStop","messageFromAsyncIO","messageToAsyncIO","VideoProxy","_rpc","_framePool","_onDisposeFrame","_onNewFrame","_active","stop","videoParameters","_width","width","_height","height","_frameMap","WeakMap","imageData","self","has","console","warn","delete","buffer","data","frame","ImageData","Uint8ClampedArray","adopt","set","newFrame","Switch","_state","beforeRead","state","stateChanged","DigitalJoystick","_left","_right","_up","_down","_fire","ControlPanel","_selectSwitch","_resetButton","_colorSwitch","_difficutlyP0","_difficutlyP1","Paddle","valueChanged","_fireSwitch","ControlProxy","Array","_joysticks","Joystick","_paddles","joystickState","map","_joystickState","paddleState","_paddleState","controlPanelState","_controlPanelState","_controlPanel","joystick","up","getUp","read","down","getDown","left","getLeft","right","getRight","fire","getFire","paddle","getValue","controlPanel","difficulty0","getDifficultySwitchP0","difficulty1","getDifficultySwitchP1","select","getSelectSwitch","reset","getResetButton","color","getColorSwitch","CpuInterface","ResultImpl","nextStep","address","cycleType","poll","pollInterrupts","immutables","freezeImmutables","immutableProperties","prop","writable","configurable","Immutable","enumerable","Boot","_result","_pre1Step","_pre2Step","_stack1Step","_stack2Step","s","_stack3Step","_readTargetLoStep","operand","_targetAddress","_readTargetHiStep","p","Interrupt","defaultVector","isBrk","_dummyRead","_isBrk","write","_pushPch","_pushPcl","_vector","nmi","_defaultVector","_pushFlags","flags","_fetchPcl","_fetchPch","irq","Instruction","operation","addressingMode","effectiveAddressingMode","OperationMap","__init","opcodes","opcode","j","_opcode","_operation","_addressingMode","_effectiveAdressingMode","Absolute","_fetchLo","_operand","_fetchHi","_next","AbsoluteIndexed","indexExtractor","writeOp","_indexExtractor","_carry","_writeOp","_dereferenceAndCarry","x","Dereference","_dereference","Immediate","_fetchOperand","IndexedIndirectX","_fetchAddress","_address","_addIndex","IndexedIndirectY","ZeroPage","ZeroPageIndexed","Branch","predicate","_fetchTarget","_predicate","_firstDummyRead","_target","_secondDummyRead","branch","Jsr","_addressLo","_dummyStackRead","ReadModifyWrite","_read","_dummyWrite","_write","readModifyWrite","Rts","_dummyOperandRead","_popPcl","_popPch","_incrementP","NullaryOneCycle","_executeOperation","nullaryOneCycle","Pull","_incrementS","_pull","pull","Push","_push","Rti","_popP","Write","setFlagsNZ","genRmw","genNullary","genUnary","adc","d0","a","d1","sum","aslImmediate","old","aslRmw","bit","cmp","getRegister","diff","sbc","lsrImmediate","lsrRmw","rolImmediate","rolRmw","rorImmediate","rorRmw","alr","dcp","axs","rra","rla","slo","aax","isc","aac","Indirect","_fetchAddressLo","_fetchAddressHi","Compiler","instruction","_createAddressing","ops.adc","deref","o","ops.genUnary","ops.aslImmediate","ops.aslRmw","ops.bit","ops.cmp","ops.genRmw","ops.genNullary","jsr","ops.lsrImmediate","ops.lsrRmw","ops.rolImmediate","ops.rolRmw","ops.rorImmediate","ops.rorRmw","rti","rts","ops.sbc","ops.aac","ops.aax","ops.alr","ops.arr","ops.axs","ops.dcp","ops.isc","ops.rla","ops.rra","ops.slo","dereference","immediate","zeroPage","absolute","zeroPageX","zeroPageY","absoluteX","absoluteY","indexedIndirectX","indirectIndexedY","indirect","StateMachineCpu","_bus","_rng","_opBoot","_opIrq","_opNmi","compiler","_operations","compile","int","executionState","_interruptPending","_nmiPending","_halt","_lastResult","_lastInstructionPointer","_invalidInstructionCallback","_fetch","_pollInterrupts","_pollInterruptsAfterLastInstruction","restoreFlagsFromStack","bus","opAdc","opAnd","opAslAcc","opAslMem","opBit","opBrk","nextOpAddr","vector","readWord","opClc","opCld","opCli","opClv","opCmp","opCpx","opCpy","opDec","opDex","opEor","opDey","opInc","opInx","opIny","opJmp","opJsr","returnPtr","addrLo","opLda","opLdx","opLdy","opLsrAcc","opLsrMem","opNop","opOra","opPhp","opPlp","opPha","opPla","opRolAcc","opRolMem","opRorAcc","opRorMem","opRti","opRts","opSbc","opSec","opSed","opSei","opSta","opStx","opSty","opTax","opTay","opTsx","opTxa","opTxs","opTya","opAlr","opAxs","opDcp","opLax","opArr","opSlo","opAax","opLar","opIsc","opAac","opAtx","opRra","opRla","opBoot","dispatchInterrupt","opIrq","opNmi","BatchedAccessCpu","_halted","_opCycles","_instructionCallback","_interuptCheck","_checkForInterrupts","_currentAddressingMode","base","slowIndexedAccess","ops.opAdc","ops.opAnd","ops.opAslAcc","ops.opAslMem","ops.opNop","ops.opJmp","ops.opBit","ops.opBrk","ops.opClc","ops.opCld","ops.opCli","ops.opClv","ops.opCmp","ops.opCpx","ops.opCpy","ops.opDec","ops.opDex","ops.opDey","ops.opEor","ops.opInc","ops.opInx","ops.opIny","ops.opJsr","ops.opLda","ops.opLdx","ops.opLdy","ops.opLsrAcc","ops.opLsrMem","ops.opOra","ops.opPhp","ops.opPha","ops.opPla","ops.opPlp","ops.opRolAcc","ops.opRolMem","ops.opRorAcc","ops.opRorMem","ops.opRti","ops.opRts","ops.opSbc","ops.opSec","ops.opSed","ops.opSei","ops.opSta","ops.opStx","ops.opSty","ops.opTax","ops.opTay","ops.opTsx","ops.opTxa","ops.opTxs","ops.opTya","ops.opArr","ops.opAlr","ops.opAxs","ops.opDcp","ops.opLax","ops.opSlo","ops.opAax","ops.opLar","ops.opIsc","ops.opAac","ops.opAtx","ops.opRra","ops.opRla","Factory","_type","rng","Type","stateMachine","batchedAccess","Config","tvMode","enableAudio","randomSeed","emulatePaddles","frameStart","pcmAudio","cpuType","CpuFactory","AudioOutputBuffer","_content","_sampleRate","encodings","Uint8Array","decodeChar","charCodeAt","decodeNibble","decode","nibbles","decodedSize","padding","getPadding","decoded","nibble","FREQUENCY_DIVISIORS","decodeBase64","POLY0","Int8Array","POLY1","POLY2","POLY4","POLY5","POLY9","POLY68","POLYS","ToneGenerator","tone","frequency","poly","content","Float32Array","sampleRate","getClockHz","count","offset","WaveformAudioProxy","_index","_onBufferChangeSignal","_onVolumeChangeSignal","_onStopSignal","parameters","_toneGenerator","setConfig","setVolume","volume","_volume","getBuffer","volumeChanged","bufferChanged","PCMAudioProxy","_onReleaseFragment","_signalReturnFrame","_onTogglePause","_enabled","params","_frameSize","frameSize","_paused","paused","msg","togglePause","AsyncIOProxy","from","EmulationService","_stellaWorkerUri","stopped","_worker","Worker","postMessage","init","videoProxy","controlProxy","asyncIOProxy","_emulationContext","onmessage","messageEvent","_onFrequencyUpdate","_onEmulationError","cartridgeType","_mutex","_savedConfig","_startProxies","_applyState","_pauseProxies","_stopProxies","running","_resumeProxies","enforce","_rateLimitEnforced","_frequency","_lastError","_fetchLastError","frequencyUpdate","getVideoProxy","start","_startControlUpdates","_proxyState","_stopControlUpdates","_controlProxyUpdateHandle","setInterval","sendUpdate","clearInterval","DriverManager","Map","emulationService","_driversBound","_emulationService","_shouldBindDrivers","_bindDrivers","_onEmuStateChange","_unbindDrivers","driver","binder","_drivers","DriverContext","getEmulationContext","unbind","newState","getState","driverContext","precisionFsh","capabilities","highpInVsh","vsh","fsh","compileShader","gl","source","shader","createShader","shaderSource","getShaderParameter","COMPILE_STATUS","getShaderInfoLog","plain","precisionVsh","blit","blitWithGamma","phosphor","ntscPass1","ntscPass2","scanlines","floatTextures","halfFloatTextures","lumaFilter","chromaFilter","maybeUnpack","expr","fill","join","Program","_gl","_program","_vsh","_fsh","vshSource","fshSource","layout","a_VertexPosition","VERTEX_SHADER","FRAGMENT_SHADER","program","createProgram","attrib","keys","bindAttribLocation","attachShader","linkProgram","getProgramParameter","LINK_STATUS","getProgramInfoLog","deleteProgram","deleteShader","useProgram","name","_attributeLocations","location","getAttribLocation","_uniformLocations","getUniformLocation","attribute","size","normalized","stride","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","enableVertexAttribArray","uniform","uniform1i","uniform1f","PhosphorProcessor","_capabilities","_initialized","_framebuffer","createFramebuffer","use","_vertexCoordinateBuffer","createBuffer","_textureCoordinateBuffer","bufferData","STATIC_DRAW","deleteFramebuffer","deleteBuffer","_texture0","deleteTexture","_texture1","texture","bindVertexAttribArray","FLOAT","activeTexture","TEXTURE0","bindTexture","TEXTURE_2D","texParameteri","TEXTURE_MIN_FILTER","NEAREST","TEXTURE_MAG_FILTER","TEXTURE1","bindFramebuffer","FRAMEBUFFER","framebufferTexture2D","COLOR_ATTACHMENT0","viewport","clearColor","clear","COLOR_BUFFER_BIT","drawArrays","TRIANGLE_STRIP","createTexture","texImage2D","RGBA","UNSIGNED_BYTE","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","level","NtscProcessor","getExtension","_programPass1","_programPass2","_targetPass1","_targetPass2","_pass","_textureType","LINEAR","mode","textureIn","textureOut","HALF_FLOAT_OES","ScanlineProcessor","_texture","IntegerScalingProcessor","_widthFrom","_heightFrom","_reconfigure","widthTo","heightTo","_widthTo","_heightTo","Math","floor","RingBuffer","_capacity","_buffer","_size","item","evict","fn","framebufferSupportTextureType","framebuffer","fbStatus","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","detectFloatTextureSupport","detectHalfFloatTextureSupport","extHalfFLoat","shaderSupportsPrecision","shaderType","precisionType","format","getShaderPrecisionFormat","precision","Video","_canvas","preventDefault","_mainProgram","_sourceTexture","_phosphorProcessor","_ntscProcessor","_integerScalingProcessor","_scanlineProcessor","_processors","_getRenderingContext","gamma","scalingMode","phosphorLevel","scanlineLevel","tvEmulation","addEventListener","_onContextLost","_onContextRestored","_pendingFrames","_updateCanvasSize","_createVertexCoordinateBuffer","_createTextureCoordinateBuffer","_configureSourceTexture","_applyConfiguration","_cancelDraw","destroy","removeEventListener","_updateVertexBuffer","_video","_configureProcessors","_scheduleDraw","_hasFrame","_draw","video","_frameHandler","imageDataPoolMember","capacity","contextOptions","alpha","depth","antialias","getContext","canvas","document","createElement","highpInFsh","HIGH_FLOAT","detect","_anmiationFrameHandle","requestAnimationFrame","_onAnimationFrame","cancelAnimationFrame","_consecutiveUnderflows","processor","render","getTexture","drawingBufferWidth","drawingBufferHeight","targetWidth","targetHeight","scaleX","scaleY","west","north","vertexData","getCanvas","clientWidth","clientHeight","pixelRatio","window","devicePixelRatio","pixelStorei","UNPACK_FLIP_Y_WEBGL","configure","getWidth","getHeight","resize","WaveformChannel","_cache","_context","_gain","createGain","connect","_audio","getVolume","_updateGain","_onVolumeChanged","_onBufferChanged","_onStop","_source","_masterVolume","sampleBuffer","audioBuffer","getLength","getSampleRate","getChannelData","getContent","createBufferSource","loop","gain","LinearReasmpler","sourceRate","targetRate","_ratio","_needsData","_fractionalIndex","sample","PCMChannel","_hostFragmentSize","_outputSampleRate","_processor","createScriptProcessor","_bufferSize","bufferSize","onaudioprocess","_processAudio","audio","_fragmentSize","getFrameSize","_inputSampleRate","_fragmentIndex","_lastFragment","_bufferUnderrun","_fragmentRing","ceil","b","_onNewFragment","_resampler","_currentFragment","fragment","outputBuffer","bufferIndex","fillBuffer","until","previousFragmentBuffer","needsData","isPaused","fragmentBuffer","isSafari","isIOS","navigator","platform","match","maxTouchPoints","audioNeedsInteraction","INTERACTION_EVENTS","audioContextCtor","AudioContext","webkitAudioContext","waitMax","waitFor","timeout","PreallocatedContext","interactionRequired","_interactionListener","mutex","resume","suspend","destination","channelCount","preallocatedContext","WebAudioDriver","waveformChannels","pcmChannels","fragmentSize","_touchListener","_suspended","_pcmChannels","_channels","stopListening","_merger","createChannelMerger","channel","waveformSources","pcmSources","_isBound","pause","setMasterVolume","close","channels","_driver","_pcmAudio","VanillaDriver","mkSwitch","swtch","mkTrigger","trigger","KeyboardIO","mappings","defaultMappings","_compileMappings","joystick0","joystick1","_joystick0","_joystick1","_updateActionTable","_keydownListener","_compiledMappings","keyCode","modifiers","shiftKey","ctrlKey","altKey","action","_dispatchTable","toggle","_keyupListener","values","toggleFullscreen","hardReset","compileMapping","keycode","mapping","isArray","spec","DoubleTapDetector","_maxTapLength","_timeout","_lastTouchStart","Date","now","_touching","_lastTouchEligible","_lastTouchEnd","endTouch","TouchIO","_joystickSensitivity","_leftHanded","changedTouches","normalizedTouch","NormalizedTouch","touch","identifier","_isAlt","_pendingTouches","_fullscreenDoubleTapDetector","startTouch","_joystick","cancelTouch","_select","_reset","deltaX","clientX","x0","deltaY","clientY","y0","abs","sqrt","sin","cos","_bound","_bindListeners","_unbindListeners","_onTouchStart","_onTouchEnd","_onTouchMove","boundingRect","getBoundingClientRect","top","MouseAsPaddleDriver","_onDocumentMouseMove","_paddle","_x","_listener","dx","screenX","innerWidth","setValue","ShadowSwitch","_dirty","button","axis","sign","defaultMapping","readButton","pressed","GamepadDriver","probeGamepads","setMapping","cnt","gamepads","getGamepads","_onGamepadConnect","_onGamepadDisconnect","joysticks","auxSwitches","_auxSwitches","_shadows","_controlledSwitches","shadow","setState","_onBeforeSwitchRead","_gamepadCount","_mappings","states","targets","m","indexOf","_mappingStates","_mappingTargets","_readGamepads","probeGamepadCount","gamepadCountChanged","switches","_lastPoll","joystickIndex","gamepad","mappingEntry","buttons","axes","_getSwitchForTarget","sync","isCommonjs","module","val","fnMap","l","ret","eventNameMap","change","fullscreenchange","fullscreenerror","screenfull","request","element","onFullScreenEntered","off","on","returnPromise","documentElement","requestFullscreen","catch","exit","isFullscreen","onFullScreenExit","exitFullscreen","onchange","onerror","eventName","raw","defineProperties","Boolean","fullscreenElement","isEnabled","fullscreenEnabled","noFullscrenApi","_screenfull","FullscreenVideoDriver","_videoDriver","_zIndex","_fullscreenClass","_resizeHandle","_adjustSizeForFullscreen","_onChange","_engaged","_resizeListener","_changeListener","_resetSize","disengage","engage","style","maxWidth","maxHeight","zIndex","classList","remove","innerHeight","add","CartridgeInfo","CartridgeType","vanilla_2k","vanilla_4k","bankswitch_2k_cv","bankswitch_8k_F8","bankswitch_8k_E0","bankswitch_8k_3F","bankswitch_8k_FE","bankswitch_8k_UA","bankswitch_8k_econobanking","bankswitch_8k_pp","bankswitch_12k_FA","bankswitch_8k_DPC","bankswitch_16k_F6","bankswitch_16k_E7","bankswitch_FA2","bankswitch_32k_F4","bankswitch_3E","bankswitch_64k_F0","bankswitch_64k_EF","bankswitch_supercharger","bankswitch_dpc_plus","bankswitch_cdf","unknown","SwitchProxy","_boundSwitch","_onBoundStateChange","_setState","stateChange","ControlPanelProxy","_boundControlPanel","_difficultyPlayer1","_difficultyPlayer2","_color","AsyncIO","io","_io","_onAsyncIOMessage","send","Stellerator","canvasElt","workerUrl","_canvasElt","ScalingMode","qis","TvEmulation","composite","enableKeyboard","enableTouch","touchLeftHanded","touchJoystickSensitivity","keyboardTarget","fullscreenViaKeyboard","paddleViaMouse","pauseViaKeyboard","pauseViaTouch","fullscreenViaTouch","enableGamepad","resetViaKeyboard","EventImplementation","_mapState","_createDrivers","_driverManager","addDriver","_serviceInitialized","log","_createVideoDriver","fullscreen","_fullscreenVideo","isEngaged","_audioDriver","max","min","getMasterVolume","_createTouchDriver","_removeVideoDriver","_removeTouchDriver","cartridge","stellaConfig","StellaConfig","create","_convertTvMode","CpuAccuracy","cycle","cpuAccuracy","asyncIO","getLastError","_asyncIO","TvMode","ntsc","pal","secam","AudioDriver","getPCMChannel","_keyboardIO","_pauseHandler","_gamepad","Gamepad","asyncIOMessage","getAsyncIO","removeDriver","VideoDriver","getVideo","FullscreenDriver","_touchIO","describeCartridgeType","getAllTypes"],"mappings":";;;;;;;;;;;;;;oFAoDO,SAASA,EAAWC,EAAYC,EAAQC,EAAKC,GAChD,IAA2HC,EAAvHC,EAAIC,UAAUC,OAAQC,EAAIH,EAAI,EAAIJ,EAAkB,OAATE,EAAgBA,EAAOM,OAAOC,yBAAyBT,EAAQC,GAAOC,EACrH,GAAuB,iBAAZQ,SAAoD,mBAArBA,QAAQC,SAAyBJ,EAAIG,QAAQC,SAASZ,EAAYC,EAAQC,EAAKC,QACpH,IAAK,IAAIU,EAAIb,EAAWO,OAAS,EAAGM,GAAK,EAAGA,KAAST,EAAIJ,EAAWa,MAAIL,GAAKH,EAAI,EAAID,EAAEI,GAAKH,EAAI,EAAID,EAAEH,EAAQC,EAAKM,GAAKJ,EAAEH,EAAQC,KAASM,GAChJ,OAAOH,EAAI,GAAKG,GAAKC,OAAOK,eAAeb,EAAQC,EAAKM,GAAIA,EAOzD,SAASO,EAAWC,EAAaC,GACpC,GAAuB,iBAAZN,SAAoD,mBAArBA,QAAQO,SAAyB,OAAOP,QAAQO,SAASF,EAAaC,GAG7G,SAASE,EAAUC,EAASC,EAAYC,EAAGC,GAE9C,OAAO,IAAKD,IAAMA,EAAIE,WAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,IAAW,MAAOG,GAAKL,EAAOK,IACpF,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,IAAW,MAAOG,GAAKL,EAAOK,IACvF,SAASF,EAAKI,GAJlB,IAAeL,EAIaK,EAAOC,KAAOT,EAAQQ,EAAOL,QAJ1CA,EAIyDK,EAAOL,MAJh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