├── .nvmrc
├── .gitignore
├── runtime
├── constants.js
├── icons
│ ├── play.svg
│ ├── pause.svg
│ ├── exitfullscreen.svg
│ ├── fullscreen.svg
│ ├── open.svg
│ ├── close.svg
│ ├── reset.svg
│ ├── tape_play.svg
│ └── tape_pause.svg
├── render.js
├── audio.js
├── worker.js
├── keyboard.js
├── snapshot.js
├── ui.js
├── tape.js
└── jsspeccy.js
├── static
├── favicon.ico
├── roms
│ ├── 48.rom
│ ├── 128-0.rom
│ ├── 128-1.rom
│ ├── trdos.rom
│ └── pentagon-0.rom
├── tapeloaders
│ ├── tape_48.szx
│ ├── tape_128.szx
│ ├── tape_128_usr0.szx
│ ├── tape_pentagon.szx
│ └── tape_pentagon_usr0.szx
└── index.html
├── tsconfig.json
├── asconfig.json
├── webpack.config.js
├── generator
├── opcodes_ed.txt
├── opcodes_dd.txt
├── opcodes_base.txt
├── opcodes_cb.txt
├── opcodes_ddcb.txt
└── gencore.js
├── CHANGELOG.md
├── package.json
├── README.md
├── test
└── test.js
├── tech_notes.md
└── COPYING
/.nvmrc:
--------------------------------------------------------------------------------
1 | 16
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | /dist
3 |
--------------------------------------------------------------------------------
/runtime/constants.js:
--------------------------------------------------------------------------------
1 | export const FRAME_BUFFER_SIZE = 0x6600;
2 |
--------------------------------------------------------------------------------
/static/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/favicon.ico
--------------------------------------------------------------------------------
/static/roms/48.rom:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/roms/48.rom
--------------------------------------------------------------------------------
/static/roms/128-0.rom:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/roms/128-0.rom
--------------------------------------------------------------------------------
/static/roms/128-1.rom:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/roms/128-1.rom
--------------------------------------------------------------------------------
/static/roms/trdos.rom:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/roms/trdos.rom
--------------------------------------------------------------------------------
/static/roms/pentagon-0.rom:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/roms/pentagon-0.rom
--------------------------------------------------------------------------------
/static/tapeloaders/tape_48.szx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/tapeloaders/tape_48.szx
--------------------------------------------------------------------------------
/static/tapeloaders/tape_128.szx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/tapeloaders/tape_128.szx
--------------------------------------------------------------------------------
/static/tapeloaders/tape_128_usr0.szx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/tapeloaders/tape_128_usr0.szx
--------------------------------------------------------------------------------
/static/tapeloaders/tape_pentagon.szx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/tapeloaders/tape_pentagon.szx
--------------------------------------------------------------------------------
/static/tapeloaders/tape_pentagon_usr0.szx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gasman/jsspeccy3/HEAD/static/tapeloaders/tape_pentagon_usr0.szx
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "assemblyscript/std/assembly.json",
3 | "include": [
4 | "./build/core.ts"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/runtime/icons/play.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/runtime/icons/pause.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/runtime/icons/exitfullscreen.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/runtime/icons/fullscreen.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/runtime/icons/open.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/runtime/icons/close.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/runtime/icons/reset.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/asconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "targets": {
3 | "debug": {
4 | "binaryFile": "dist/jsspeccy/jsspeccy-core.wasm",
5 | "textFile": "build/core.wat",
6 | "sourceMap": true,
7 | "debug": true
8 | },
9 | "release": {
10 | "binaryFile": "dist/jsspeccy/jsspeccy-core.wasm",
11 | "textFile": "build/core.wat",
12 | "sourceMap": true,
13 | "optimizeLevel": 3,
14 | "shrinkLevel": 0,
15 | "converge": false,
16 | "noAssert": false
17 | }
18 | },
19 | "options": {
20 | "memoryBase": 589824
21 | }
22 | }
--------------------------------------------------------------------------------
/static/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | JSSpeccy v3
5 |
6 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | export default [
2 | {
3 | output: {
4 | filename: 'jsspeccy/jsspeccy.js',
5 | },
6 | name: 'jsspeccy',
7 | entry: './runtime/jsspeccy.js',
8 | mode: 'production',
9 | module: {
10 | rules: [
11 | {
12 | test: /\.svg$/,
13 | loader: 'svg-inline-loader',
14 | }
15 | ],
16 | }
17 | },
18 | {
19 | output: {
20 | filename: 'jsspeccy/jsspeccy-worker.js',
21 | },
22 | name: 'worker',
23 | entry: './runtime/worker.js',
24 | mode: 'production',
25 | },
26 | ];
27 |
--------------------------------------------------------------------------------
/runtime/icons/tape_play.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/runtime/icons/tape_pause.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/generator/opcodes_ed.txt:
--------------------------------------------------------------------------------
1 | 40 IN B,(C)
2 | 41 OUT (C),B
3 | 42 SBC HL,BC
4 | 43 LD (nn),BC
5 | 44 NEG
6 | 45 RETN
7 | 46 IM 0
8 | 47 LD I,A
9 | 48 IN C,(C)
10 | 49 OUT (C),C
11 | 4a ADC HL,BC
12 | 4b LD BC,(nn)
13 | 4c NEG
14 | 4d RETN
15 | 4e IM 0
16 | 4f LD R,A
17 |
18 | 50 IN D,(C)
19 | 51 OUT (C),D
20 | 52 SBC HL,DE
21 | 53 LD (nn),DE
22 | 54 NEG
23 | 55 RETN
24 | 56 IM 1
25 | 57 LD A,I
26 | 58 IN E,(C)
27 | 59 OUT (C),E
28 | 5a ADC HL,DE
29 | 5b LD DE,(nn)
30 | 5c NEG
31 | 5d RETN
32 | 5e IM 2
33 | 5f LD A,R
34 |
35 | 60 IN H,(C)
36 | 61 OUT (C),H
37 | 62 SBC HL,HL
38 | 63 LD (nn),HL
39 | 64 NEG
40 | 65 RETN
41 | 66 IM 0
42 | 67 RRD
43 | 68 IN L,(C)
44 | 69 OUT (C),L
45 | 6a ADC HL,HL
46 | 6b LD HL,(nn)
47 | 6c NEG
48 | 6d RETN
49 | 6e IM 0
50 | 6f RLD
51 |
52 | 70 IN F,(C)
53 | 71 OUT (C),0
54 | 72 SBC HL,SP
55 | 73 LD (nn),SP
56 | 74 NEG
57 | 75 RETN
58 | 76 IM 1
59 | 78 IN A,(C)
60 | 79 OUT (C),A
61 | 7a ADC HL,SP
62 | 7b LD SP,(nn)
63 | 7c NEG
64 | 7d RETN
65 | 7e IM 2
66 |
67 | a0 LDI
68 | a1 CPI
69 | a2 INI
70 | a3 OUTI
71 | a8 LDD
72 | a9 CPD
73 | aa IND
74 | ab OUTD
75 | b0 LDIR
76 | b1 CPIR
77 | b2 INIR
78 | b3 OTIR
79 | b8 LDDR
80 | b9 CPDR
81 | ba INDR
82 | bb OTDR
83 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | 3.2 (2024-11-23)
2 | ----------------
3 |
4 | * Add mappings from keyboard symbol keys to equivalent Spectrum keypresses (Andrew Forrest)
5 | * Add support for the Recreated ZX Spectrum's "game mode" (Andrew Forrest)
6 | * Add `keyboardEnabled` configuration option
7 | * Add `uiEnabled` configuration option
8 | * Add `loadSnapshotFromStruct` API endpoint
9 | * Add `onReady` API endpoint
10 | * Enable 'instant tape loading' option in sandbox mode
11 | * Make keyboard event listeners play better with other interactive elements on the page
12 |
13 |
14 | 3.1 (2021-08-26)
15 | ----------------
16 |
17 | * Real-time tape loading, including turbo loaders (except for direct recording, CSW and generalized data TZX blocks)
18 | * Emulate floating bus behaviour
19 | * Fix typo in docs (`openURL` -> `openUrl`)
20 |
21 |
22 | 3.0.1 (2021-08-16)
23 | ------------------
24 |
25 | * Fix relative jump instructions to not treat +0x7f as -0x81 (which broke the Protracker 3 player)
26 |
27 |
28 | 3.0 (2021-08-14)
29 | ----------------
30 |
31 | Initial release of JSSpeccy 3.
32 |
33 | * Web Worker and WebAssembly emulation core
34 | * 48K, 128K, Pentagon emulaton
35 | * Accurate multicolour
36 | * AY and beeper audio
37 | * TAP, TZX, Z80, SNA, SZX, ZIP loading
38 | * Fullscreen mode
39 | * Browsing games from Internet Archive
40 |
--------------------------------------------------------------------------------
/generator/opcodes_dd.txt:
--------------------------------------------------------------------------------
1 | 09 ADD IX,BC
2 | 19 ADD IX,DE
3 | 21 LD IX,nn
4 | 22 LD (nn),IX
5 | 23 INC IX
6 | 24 INC IXH
7 | 25 DEC IXH
8 | 26 LD IXH,n
9 | 29 ADD IX,IX
10 | 2a LD IX,(nn)
11 | 2b DEC IX
12 | 2c INC IXL
13 | 2d DEC IXL
14 | 2e LD IXL,n
15 | 34 INC (IX+n)
16 | 35 DEC (IX+n)
17 | 36 LD (IX+n),n
18 | 39 ADD IX,SP
19 | 44 LD B,IXH
20 | 45 LD B,IXL
21 | 46 LD B,(IX+n)
22 | 4c LD C,IXH
23 | 4d LD C,IXL
24 | 4e LD C,(IX+n)
25 | 54 LD D,IXH
26 | 55 LD D,IXL
27 | 56 LD D,(IX+n)
28 | 5c LD E,IXH
29 | 5d LD E,IXL
30 | 5e LD E,(IX+n)
31 | 60 LD IXH,B
32 | 61 LD IXH,C
33 | 62 LD IXH,D
34 | 63 LD IXH,E
35 | 64 LD IXH,IXH
36 | 65 LD IXH,IXL
37 | 66 LD H,(IX+n)
38 | 67 LD IXH,A
39 | 68 LD IXL,B
40 | 69 LD IXL,C
41 | 6a LD IXL,D
42 | 6b LD IXL,E
43 | 6c LD IXL,IXH
44 | 6d LD IXL,IXL
45 | 6e LD L,(IX+n)
46 | 6f LD IXL,A
47 | 70 LD (IX+n),B
48 | 71 LD (IX+n),C
49 | 72 LD (IX+n),D
50 | 73 LD (IX+n),E
51 | 74 LD (IX+n),H
52 | 75 LD (IX+n),L
53 | 77 LD (IX+n),A
54 | 7c LD A,IXH
55 | 7d LD A,IXL
56 | 7e LD A,(IX+n)
57 | 84 ADD A,IXH
58 | 85 ADD A,IXL
59 | 86 ADD A,(IX+n)
60 | 8c ADC A,IXH
61 | 8d ADC A,IXL
62 | 8e ADC A,(IX+n)
63 | 94 SUB IXH
64 | 95 SUB IXL
65 | 96 SUB (IX+n)
66 | 9c SBC A,IXH
67 | 9d SBC A,IXL
68 | 9e SBC A,(IX+n)
69 | a4 AND IXH
70 | a5 AND IXL
71 | a6 AND (IX+n)
72 | ac XOR IXH
73 | ad XOR IXL
74 | ae XOR (IX+n)
75 | b4 OR IXH
76 | b5 OR IXL
77 | b6 OR (IX+n)
78 | bc CP IXH
79 | bd CP IXL
80 | be CP (IX+n)
81 | cb prefix ddcb
82 | e1 POP IX
83 | e3 EX (SP),IX
84 | e5 PUSH IX
85 | e9 JP (IX)
86 | f9 LD SP,IX
87 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jsspeccy",
3 | "version": "3.2.0",
4 | "description": "a ZX Spectrum emulator in the browser",
5 | "main": "jsspeccy.js",
6 | "type": "module",
7 | "scripts": {
8 | "test": "npm run build && node --experimental-wasm-modules test/test.js test/tests.in test/tests.expected",
9 | "build:core": "node generator/gencore.js generator/core.ts.in build/core.ts",
10 | "build:wasm:debug": "asc build/core.ts --target debug",
11 | "build:wasm:release": "asc build/core.ts --target release",
12 | "build:js": "mkdir -p dist/jsspeccy && webpack",
13 | "build:static": "mkdir -p dist/jsspeccy && cp static/index.html dist/ && cp static/favicon.ico dist/ && cp README.md dist/ && cp COPYING dist/ && cp CHANGELOG.md dist/ && cp -r static/roms dist/jsspeccy && cp -r static/tapeloaders dist/jsspeccy",
14 | "build": "npm run build:core && npm run build:wasm:debug && npm run build:js && npm run build:static",
15 | "build:release": "npm run build:core && npm run build:wasm:release && npm run build:js && npm run build:static",
16 | "watch": "npm-watch"
17 | },
18 | "watch": {
19 | "build:core": {
20 | "patterns": [
21 | "generator/*.js",
22 | "generator/*.ts.in"
23 | ],
24 | "extensions": [
25 | "js",
26 | "in"
27 | ]
28 | },
29 | "build:wasm:debug": {
30 | "patterns": [
31 | "build/core.ts"
32 | ],
33 | "extensions": "ts"
34 | },
35 | "build:js": {
36 | "patterns": [
37 | "runtime/*.js",
38 | "runtime/icons/*.svg",
39 | "build/*.js"
40 | ],
41 | "extensions": ["js", "svg"]
42 | },
43 | "build:static": {
44 | "patterns": [
45 | "static/*.html",
46 | "static/*.rom"
47 | ],
48 | "extensions": [
49 | "html",
50 | "rom"
51 | ]
52 | }
53 | },
54 | "author": "Matt Westcott",
55 | "license": "ISC",
56 | "devDependencies": {
57 | "assemblyscript": "^0.19.6",
58 | "npm-watch": "^0.10.0",
59 | "svg-inline-loader": "^0.8.2",
60 | "webpack": "^5.44.0",
61 | "webpack-cli": "^4.7.2"
62 | },
63 | "dependencies": {
64 | "file-dialog": "^0.0.8",
65 | "jszip": "^3.7.1",
66 | "pako": "^2.0.4"
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/generator/opcodes_base.txt:
--------------------------------------------------------------------------------
1 | 00 NOP
2 | 01 LD BC,nn
3 | 02 LD (BC),A
4 | 03 INC BC
5 | 04 INC B
6 | 05 DEC B
7 | 06 LD B,n
8 | 07 RLCA
9 | 08 EX AF,AF'
10 | 09 ADD HL,BC
11 | 0a LD A,(BC)
12 | 0b DEC BC
13 | 0c INC C
14 | 0d DEC C
15 | 0e LD C,n
16 | 0f RRCA
17 |
18 | 10 DJNZ n
19 | 11 LD DE,nn
20 | 12 LD (DE),A
21 | 13 INC DE
22 | 14 INC D
23 | 15 DEC D
24 | 16 LD D,n
25 | 17 RLA
26 | 18 JR n
27 | 19 ADD HL,DE
28 | 1a LD A,(DE)
29 | 1b DEC DE
30 | 1c INC E
31 | 1d DEC E
32 | 1e LD E,n
33 | 1f RRA
34 |
35 | 20 JR NZ,n
36 | 21 LD HL,nn
37 | 22 LD (nn),HL
38 | 23 INC HL
39 | 24 INC H
40 | 25 DEC H
41 | 26 LD H,n
42 | 27 DAA
43 | 28 JR Z,n
44 | 29 ADD HL,HL
45 | 2a LD HL,(nn)
46 | 2b DEC HL
47 | 2c INC L
48 | 2d DEC L
49 | 2e LD L,n
50 | 2f CPL
51 |
52 | 30 JR NC,n
53 | 31 LD SP,nn
54 | 32 LD (nn),A
55 | 33 INC SP
56 | 34 INC (HL)
57 | 35 DEC (HL)
58 | 36 LD (HL),n
59 | 37 SCF
60 | 38 JR C,n
61 | 39 ADD HL,SP
62 | 3a LD A,(nn)
63 | 3b DEC SP
64 | 3c INC A
65 | 3d DEC A
66 | 3e LD A,n
67 | 3f CCF
68 |
69 | 40 LD B,B
70 | 41 LD B,C
71 | 42 LD B,D
72 | 43 LD B,E
73 | 44 LD B,H
74 | 45 LD B,L
75 | 46 LD B,(HL)
76 | 47 LD B,A
77 | 48 LD C,B
78 | 49 LD C,C
79 | 4a LD C,D
80 | 4b LD C,E
81 | 4c LD C,H
82 | 4d LD C,L
83 | 4e LD C,(HL)
84 | 4f LD C,A
85 |
86 | 50 LD D,B
87 | 51 LD D,C
88 | 52 LD D,D
89 | 53 LD D,E
90 | 54 LD D,H
91 | 55 LD D,L
92 | 56 LD D,(HL)
93 | 57 LD D,A
94 | 58 LD E,B
95 | 59 LD E,C
96 | 5a LD E,D
97 | 5b LD E,E
98 | 5c LD E,H
99 | 5d LD E,L
100 | 5e LD E,(HL)
101 | 5f LD E,A
102 |
103 | 60 LD H,B
104 | 61 LD H,C
105 | 62 LD H,D
106 | 63 LD H,E
107 | 64 LD H,H
108 | 65 LD H,L
109 | 66 LD H,(HL)
110 | 67 LD H,A
111 | 68 LD L,B
112 | 69 LD L,C
113 | 6a LD L,D
114 | 6b LD L,E
115 | 6c LD L,H
116 | 6d LD L,L
117 | 6e LD L,(HL)
118 | 6f LD L,A
119 |
120 | 70 LD (HL),B
121 | 71 LD (HL),C
122 | 72 LD (HL),D
123 | 73 LD (HL),E
124 | 74 LD (HL),H
125 | 75 LD (HL),L
126 | 76 HALT
127 | 77 LD (HL),A
128 | 78 LD A,B
129 | 79 LD A,C
130 | 7a LD A,D
131 | 7b LD A,E
132 | 7c LD A,H
133 | 7d LD A,L
134 | 7e LD A,(HL)
135 | 7f LD A,A
136 |
137 | 80 ADD A,B
138 | 81 ADD A,C
139 | 82 ADD A,D
140 | 83 ADD A,E
141 | 84 ADD A,H
142 | 85 ADD A,L
143 | 86 ADD A,(HL)
144 | 87 ADD A,A
145 | 88 ADC A,B
146 | 89 ADC A,C
147 | 8a ADC A,D
148 | 8b ADC A,E
149 | 8c ADC A,H
150 | 8d ADC A,L
151 | 8e ADC A,(HL)
152 | 8f ADC A,A
153 |
154 | 90 SUB B
155 | 91 SUB C
156 | 92 SUB D
157 | 93 SUB E
158 | 94 SUB H
159 | 95 SUB L
160 | 96 SUB (HL)
161 | 97 SUB A
162 | 98 SBC A,B
163 | 99 SBC A,C
164 | 9a SBC A,D
165 | 9b SBC A,E
166 | 9c SBC A,H
167 | 9d SBC A,L
168 | 9e SBC A,(HL)
169 | 9f SBC A,A
170 |
171 | a0 AND B
172 | a1 AND C
173 | a2 AND D
174 | a3 AND E
175 | a4 AND H
176 | a5 AND L
177 | a6 AND (HL)
178 | a7 AND A
179 | a8 XOR B
180 | a9 XOR C
181 | aa XOR D
182 | ab XOR E
183 | ac XOR H
184 | ad XOR L
185 | ae XOR (HL)
186 | af XOR A
187 |
188 | b0 OR B
189 | b1 OR C
190 | b2 OR D
191 | b3 OR E
192 | b4 OR H
193 | b5 OR L
194 | b6 OR (HL)
195 | b7 OR A
196 | b8 CP B
197 | b9 CP C
198 | ba CP D
199 | bb CP E
200 | bc CP H
201 | bd CP L
202 | be CP (HL)
203 | bf CP A
204 |
205 | c0 RET NZ
206 | c1 POP BC
207 | c2 JP NZ,nn
208 | c3 JP nn
209 | c4 CALL NZ,nn
210 | c5 PUSH BC
211 | c6 ADD A,n
212 | c7 RST 0x00
213 | c8 RET Z
214 | c9 RET
215 | ca JP Z,nn
216 | cb prefix cb
217 | cc CALL Z,nn
218 | cd CALL nn
219 | ce ADC A,n
220 | cf RST 0x08
221 |
222 | d0 RET NC
223 | d1 POP DE
224 | d2 JP NC,nn
225 | d3 OUT (n),A
226 | d4 CALL NC,nn
227 | d5 PUSH DE
228 | d6 SUB n
229 | d7 RST 0x10
230 | d8 RET C
231 | d9 EXX
232 | da JP C,nn
233 | db IN A,(n)
234 | dc CALL C,nn
235 | dd prefix dd
236 | de SBC A,n
237 | df RST 0x18
238 |
239 | e0 RET PO
240 | e1 POP HL
241 | e2 JP PO,nn
242 | e3 EX (SP),HL
243 | e4 CALL PO,nn
244 | e5 PUSH HL
245 | e6 AND n
246 | e7 RST 0x20
247 | e8 RET PE
248 | e9 JP (HL)
249 | ea JP PE,nn
250 | eb EX DE,HL
251 | ec CALL PE,nn
252 | ed prefix ed
253 | ee XOR n
254 | ef RST 0x28
255 |
256 | f0 RET P
257 | f1 POP AF
258 | f2 JP P,nn
259 | f3 DI
260 | f4 CALL P,nn
261 | f5 PUSH AF
262 | f6 OR n
263 | f7 RST 0x30
264 | f8 RET M
265 | f9 LD SP,HL
266 | fa JP M,nn
267 | fb EI
268 | fc CALL M,nn
269 | fd prefix fd
270 | fe CP n
271 | ff RST 0x38
272 |
--------------------------------------------------------------------------------
/generator/opcodes_cb.txt:
--------------------------------------------------------------------------------
1 | 00 RLC B
2 | 01 RLC C
3 | 02 RLC D
4 | 03 RLC E
5 | 04 RLC H
6 | 05 RLC L
7 | 06 RLC (HL)
8 | 07 RLC A
9 | 08 RRC B
10 | 09 RRC C
11 | 0a RRC D
12 | 0b RRC E
13 | 0c RRC H
14 | 0d RRC L
15 | 0e RRC (HL)
16 | 0f RRC A
17 |
18 | 10 RL B
19 | 11 RL C
20 | 12 RL D
21 | 13 RL E
22 | 14 RL H
23 | 15 RL L
24 | 16 RL (HL)
25 | 17 RL A
26 | 18 RR B
27 | 19 RR C
28 | 1a RR D
29 | 1b RR E
30 | 1c RR H
31 | 1d RR L
32 | 1e RR (HL)
33 | 1f RR A
34 |
35 | 20 SLA B
36 | 21 SLA C
37 | 22 SLA D
38 | 23 SLA E
39 | 24 SLA H
40 | 25 SLA L
41 | 26 SLA (HL)
42 | 27 SLA A
43 | 28 SRA B
44 | 29 SRA C
45 | 2a SRA D
46 | 2b SRA E
47 | 2c SRA H
48 | 2d SRA L
49 | 2e SRA (HL)
50 | 2f SRA A
51 |
52 | 30 SLL B
53 | 31 SLL C
54 | 32 SLL D
55 | 33 SLL E
56 | 34 SLL H
57 | 35 SLL L
58 | 36 SLL (HL)
59 | 37 SLL A
60 | 38 SRL B
61 | 39 SRL C
62 | 3a SRL D
63 | 3b SRL E
64 | 3c SRL H
65 | 3d SRL L
66 | 3e SRL (HL)
67 | 3f SRL A
68 |
69 | 40 BIT 0,B
70 | 41 BIT 0,C
71 | 42 BIT 0,D
72 | 43 BIT 0,E
73 | 44 BIT 0,H
74 | 45 BIT 0,L
75 | 46 BIT 0,(HL)
76 | 47 BIT 0,A
77 | 48 BIT 1,B
78 | 49 BIT 1,C
79 | 4a BIT 1,D
80 | 4b BIT 1,E
81 | 4c BIT 1,H
82 | 4d BIT 1,L
83 | 4e BIT 1,(HL)
84 | 4f BIT 1,A
85 |
86 | 50 BIT 2,B
87 | 51 BIT 2,C
88 | 52 BIT 2,D
89 | 53 BIT 2,E
90 | 54 BIT 2,H
91 | 55 BIT 2,L
92 | 56 BIT 2,(HL)
93 | 57 BIT 2,A
94 | 58 BIT 3,B
95 | 59 BIT 3,C
96 | 5a BIT 3,D
97 | 5b BIT 3,E
98 | 5c BIT 3,H
99 | 5d BIT 3,L
100 | 5e BIT 3,(HL)
101 | 5f BIT 3,A
102 |
103 | 60 BIT 4,B
104 | 61 BIT 4,C
105 | 62 BIT 4,D
106 | 63 BIT 4,E
107 | 64 BIT 4,H
108 | 65 BIT 4,L
109 | 66 BIT 4,(HL)
110 | 67 BIT 4,A
111 | 68 BIT 5,B
112 | 69 BIT 5,C
113 | 6a BIT 5,D
114 | 6b BIT 5,E
115 | 6c BIT 5,H
116 | 6d BIT 5,L
117 | 6e BIT 5,(HL)
118 | 6f BIT 5,A
119 |
120 | 70 BIT 6,B
121 | 71 BIT 6,C
122 | 72 BIT 6,D
123 | 73 BIT 6,E
124 | 74 BIT 6,H
125 | 75 BIT 6,L
126 | 76 BIT 6,(HL)
127 | 77 BIT 6,A
128 | 78 BIT 7,B
129 | 79 BIT 7,C
130 | 7a BIT 7,D
131 | 7b BIT 7,E
132 | 7c BIT 7,H
133 | 7d BIT 7,L
134 | 7e BIT 7,(HL)
135 | 7f BIT 7,A
136 |
137 | 80 RES 0,B
138 | 81 RES 0,C
139 | 82 RES 0,D
140 | 83 RES 0,E
141 | 84 RES 0,H
142 | 85 RES 0,L
143 | 86 RES 0,(HL)
144 | 87 RES 0,A
145 | 88 RES 1,B
146 | 89 RES 1,C
147 | 8a RES 1,D
148 | 8b RES 1,E
149 | 8c RES 1,H
150 | 8d RES 1,L
151 | 8e RES 1,(HL)
152 | 8f RES 1,A
153 |
154 | 90 RES 2,B
155 | 91 RES 2,C
156 | 92 RES 2,D
157 | 93 RES 2,E
158 | 94 RES 2,H
159 | 95 RES 2,L
160 | 96 RES 2,(HL)
161 | 97 RES 2,A
162 | 98 RES 3,B
163 | 99 RES 3,C
164 | 9a RES 3,D
165 | 9b RES 3,E
166 | 9c RES 3,H
167 | 9d RES 3,L
168 | 9e RES 3,(HL)
169 | 9f RES 3,A
170 |
171 | a0 RES 4,B
172 | a1 RES 4,C
173 | a2 RES 4,D
174 | a3 RES 4,E
175 | a4 RES 4,H
176 | a5 RES 4,L
177 | a6 RES 4,(HL)
178 | a7 RES 4,A
179 | a8 RES 5,B
180 | a9 RES 5,C
181 | aa RES 5,D
182 | ab RES 5,E
183 | ac RES 5,H
184 | ad RES 5,L
185 | ae RES 5,(HL)
186 | af RES 5,A
187 |
188 | b0 RES 6,B
189 | b1 RES 6,C
190 | b2 RES 6,D
191 | b3 RES 6,E
192 | b4 RES 6,H
193 | b5 RES 6,L
194 | b6 RES 6,(HL)
195 | b7 RES 6,A
196 | b8 RES 7,B
197 | b9 RES 7,C
198 | ba RES 7,D
199 | bb RES 7,E
200 | bc RES 7,H
201 | bd RES 7,L
202 | be RES 7,(HL)
203 | bf RES 7,A
204 |
205 | c0 SET 0,B
206 | c1 SET 0,C
207 | c2 SET 0,D
208 | c3 SET 0,E
209 | c4 SET 0,H
210 | c5 SET 0,L
211 | c6 SET 0,(HL)
212 | c7 SET 0,A
213 | c8 SET 1,B
214 | c9 SET 1,C
215 | ca SET 1,D
216 | cb SET 1,E
217 | cc SET 1,H
218 | cd SET 1,L
219 | ce SET 1,(HL)
220 | cf SET 1,A
221 |
222 | d0 SET 2,B
223 | d1 SET 2,C
224 | d2 SET 2,D
225 | d3 SET 2,E
226 | d4 SET 2,H
227 | d5 SET 2,L
228 | d6 SET 2,(HL)
229 | d7 SET 2,A
230 | d8 SET 3,B
231 | d9 SET 3,C
232 | da SET 3,D
233 | db SET 3,E
234 | dc SET 3,H
235 | dd SET 3,L
236 | de SET 3,(HL)
237 | df SET 3,A
238 |
239 | e0 SET 4,B
240 | e1 SET 4,C
241 | e2 SET 4,D
242 | e3 SET 4,E
243 | e4 SET 4,H
244 | e5 SET 4,L
245 | e6 SET 4,(HL)
246 | e7 SET 4,A
247 | e8 SET 5,B
248 | e9 SET 5,C
249 | ea SET 5,D
250 | eb SET 5,E
251 | ec SET 5,H
252 | ed SET 5,L
253 | ee SET 5,(HL)
254 | ef SET 5,A
255 |
256 | f0 SET 6,B
257 | f1 SET 6,C
258 | f2 SET 6,D
259 | f3 SET 6,E
260 | f4 SET 6,H
261 | f5 SET 6,L
262 | f6 SET 6,(HL)
263 | f7 SET 6,A
264 | f8 SET 7,B
265 | f9 SET 7,C
266 | fa SET 7,D
267 | fb SET 7,E
268 | fc SET 7,H
269 | fd SET 7,L
270 | fe SET 7,(HL)
271 | ff SET 7,A
--------------------------------------------------------------------------------
/generator/opcodes_ddcb.txt:
--------------------------------------------------------------------------------
1 | 00 RLC (IX+n>B)
2 | 01 RLC (IX+n>C)
3 | 02 RLC (IX+n>D)
4 | 03 RLC (IX+n>E)
5 | 04 RLC (IX+n>H)
6 | 05 RLC (IX+n>L)
7 | 06 RLC (IX+n)
8 | 07 RLC (IX+n>A)
9 | 08 RRC (IX+n>B)
10 | 09 RRC (IX+n>C)
11 | 0a RRC (IX+n>D)
12 | 0b RRC (IX+n>E)
13 | 0c RRC (IX+n>H)
14 | 0d RRC (IX+n>L)
15 | 0e RRC (IX+n)
16 | 0f RRC (IX+n>A)
17 |
18 | 10 RL (IX+n>B)
19 | 11 RL (IX+n>C)
20 | 12 RL (IX+n>D)
21 | 13 RL (IX+n>E)
22 | 14 RL (IX+n>H)
23 | 15 RL (IX+n>L)
24 | 16 RL (IX+n)
25 | 17 RL (IX+n>A)
26 | 18 RR (IX+n>B)
27 | 19 RR (IX+n>C)
28 | 1a RR (IX+n>D)
29 | 1b RR (IX+n>E)
30 | 1c RR (IX+n>H)
31 | 1d RR (IX+n>L)
32 | 1e RR (IX+n)
33 | 1f RR (IX+n>A)
34 |
35 | 20 SLA (IX+n>B)
36 | 21 SLA (IX+n>C)
37 | 22 SLA (IX+n>D)
38 | 23 SLA (IX+n>E)
39 | 24 SLA (IX+n>H)
40 | 25 SLA (IX+n>L)
41 | 26 SLA (IX+n)
42 | 27 SLA (IX+n>A)
43 | 28 SRA (IX+n>B)
44 | 29 SRA (IX+n>C)
45 | 2a SRA (IX+n>D)
46 | 2b SRA (IX+n>E)
47 | 2c SRA (IX+n>H)
48 | 2d SRA (IX+n>L)
49 | 2e SRA (IX+n)
50 | 2f SRA (IX+n>A)
51 |
52 | 30 SLL (IX+n>B)
53 | 31 SLL (IX+n>C)
54 | 32 SLL (IX+n>D)
55 | 33 SLL (IX+n>E)
56 | 34 SLL (IX+n>H)
57 | 35 SLL (IX+n>L)
58 | 36 SLL (IX+n)
59 | 37 SLL (IX+n>A)
60 | 38 SRL (IX+n>B)
61 | 39 SRL (IX+n>C)
62 | 3a SRL (IX+n>D)
63 | 3b SRL (IX+n>E)
64 | 3c SRL (IX+n>H)
65 | 3d SRL (IX+n>L)
66 | 3e SRL (IX+n)
67 | 3f SRL (IX+n>A)
68 |
69 | 40 BIT 0,(IX+n)
70 | 41 BIT 0,(IX+n)
71 | 42 BIT 0,(IX+n)
72 | 43 BIT 0,(IX+n)
73 | 44 BIT 0,(IX+n)
74 | 45 BIT 0,(IX+n)
75 | 46 BIT 0,(IX+n)
76 | 47 BIT 0,(IX+n)
77 | 48 BIT 1,(IX+n)
78 | 49 BIT 1,(IX+n)
79 | 4a BIT 1,(IX+n)
80 | 4b BIT 1,(IX+n)
81 | 4c BIT 1,(IX+n)
82 | 4d BIT 1,(IX+n)
83 | 4e BIT 1,(IX+n)
84 | 4f BIT 1,(IX+n)
85 |
86 | 50 BIT 2,(IX+n)
87 | 51 BIT 2,(IX+n)
88 | 52 BIT 2,(IX+n)
89 | 53 BIT 2,(IX+n)
90 | 54 BIT 2,(IX+n)
91 | 55 BIT 2,(IX+n)
92 | 56 BIT 2,(IX+n)
93 | 57 BIT 2,(IX+n)
94 | 58 BIT 3,(IX+n)
95 | 59 BIT 3,(IX+n)
96 | 5a BIT 3,(IX+n)
97 | 5b BIT 3,(IX+n)
98 | 5c BIT 3,(IX+n)
99 | 5d BIT 3,(IX+n)
100 | 5e BIT 3,(IX+n)
101 | 5f BIT 3,(IX+n)
102 |
103 | 60 BIT 4,(IX+n)
104 | 61 BIT 4,(IX+n)
105 | 62 BIT 4,(IX+n)
106 | 63 BIT 4,(IX+n)
107 | 64 BIT 4,(IX+n)
108 | 65 BIT 4,(IX+n)
109 | 66 BIT 4,(IX+n)
110 | 67 BIT 4,(IX+n)
111 | 68 BIT 5,(IX+n)
112 | 69 BIT 5,(IX+n)
113 | 6a BIT 5,(IX+n)
114 | 6b BIT 5,(IX+n)
115 | 6c BIT 5,(IX+n)
116 | 6d BIT 5,(IX+n)
117 | 6e BIT 5,(IX+n)
118 | 6f BIT 5,(IX+n)
119 |
120 | 70 BIT 6,(IX+n)
121 | 71 BIT 6,(IX+n)
122 | 72 BIT 6,(IX+n)
123 | 73 BIT 6,(IX+n)
124 | 74 BIT 6,(IX+n)
125 | 75 BIT 6,(IX+n)
126 | 76 BIT 6,(IX+n)
127 | 77 BIT 6,(IX+n)
128 | 78 BIT 7,(IX+n)
129 | 79 BIT 7,(IX+n)
130 | 7a BIT 7,(IX+n)
131 | 7b BIT 7,(IX+n)
132 | 7c BIT 7,(IX+n)
133 | 7d BIT 7,(IX+n)
134 | 7e BIT 7,(IX+n)
135 | 7f BIT 7,(IX+n)
136 |
137 | 80 RES 0,(IX+n>B)
138 | 81 RES 0,(IX+n>C)
139 | 82 RES 0,(IX+n>D)
140 | 83 RES 0,(IX+n>E)
141 | 84 RES 0,(IX+n>H)
142 | 85 RES 0,(IX+n>L)
143 | 86 RES 0,(IX+n)
144 | 87 RES 0,(IX+n>A)
145 | 88 RES 1,(IX+n>B)
146 | 89 RES 1,(IX+n>C)
147 | 8a RES 1,(IX+n>D)
148 | 8b RES 1,(IX+n>E)
149 | 8c RES 1,(IX+n>H)
150 | 8d RES 1,(IX+n>L)
151 | 8e RES 1,(IX+n)
152 | 8f RES 1,(IX+n>A)
153 |
154 | 90 RES 2,(IX+n>B)
155 | 91 RES 2,(IX+n>C)
156 | 92 RES 2,(IX+n>D)
157 | 93 RES 2,(IX+n>E)
158 | 94 RES 2,(IX+n>H)
159 | 95 RES 2,(IX+n>L)
160 | 96 RES 2,(IX+n)
161 | 97 RES 2,(IX+n>A)
162 | 98 RES 3,(IX+n>B)
163 | 99 RES 3,(IX+n>C)
164 | 9a RES 3,(IX+n>D)
165 | 9b RES 3,(IX+n>E)
166 | 9c RES 3,(IX+n>H)
167 | 9d RES 3,(IX+n>L)
168 | 9e RES 3,(IX+n)
169 | 9f RES 3,(IX+n>A)
170 |
171 | a0 RES 4,(IX+n>B)
172 | a1 RES 4,(IX+n>C)
173 | a2 RES 4,(IX+n>D)
174 | a3 RES 4,(IX+n>E)
175 | a4 RES 4,(IX+n>H)
176 | a5 RES 4,(IX+n>L)
177 | a6 RES 4,(IX+n)
178 | a7 RES 4,(IX+n>A)
179 | a8 RES 5,(IX+n>B)
180 | a9 RES 5,(IX+n>C)
181 | aa RES 5,(IX+n>D)
182 | ab RES 5,(IX+n>E)
183 | ac RES 5,(IX+n>H)
184 | ad RES 5,(IX+n>L)
185 | ae RES 5,(IX+n)
186 | af RES 5,(IX+n>A)
187 |
188 | b0 RES 6,(IX+n>B)
189 | b1 RES 6,(IX+n>C)
190 | b2 RES 6,(IX+n>D)
191 | b3 RES 6,(IX+n>E)
192 | b4 RES 6,(IX+n>H)
193 | b5 RES 6,(IX+n>L)
194 | b6 RES 6,(IX+n)
195 | b7 RES 6,(IX+n>A)
196 | b8 RES 7,(IX+n>B)
197 | b9 RES 7,(IX+n>C)
198 | ba RES 7,(IX+n>D)
199 | bb RES 7,(IX+n>E)
200 | bc RES 7,(IX+n>H)
201 | bd RES 7,(IX+n>L)
202 | be RES 7,(IX+n)
203 | bf RES 7,(IX+n>A)
204 |
205 | c0 SET 0,(IX+n>B)
206 | c1 SET 0,(IX+n>C)
207 | c2 SET 0,(IX+n>D)
208 | c3 SET 0,(IX+n>E)
209 | c4 SET 0,(IX+n>H)
210 | c5 SET 0,(IX+n>L)
211 | c6 SET 0,(IX+n)
212 | c7 SET 0,(IX+n>A)
213 | c8 SET 1,(IX+n>B)
214 | c9 SET 1,(IX+n>C)
215 | ca SET 1,(IX+n>D)
216 | cb SET 1,(IX+n>E)
217 | cc SET 1,(IX+n>H)
218 | cd SET 1,(IX+n>L)
219 | ce SET 1,(IX+n)
220 | cf SET 1,(IX+n>A)
221 |
222 | d0 SET 2,(IX+n>B)
223 | d1 SET 2,(IX+n>C)
224 | d2 SET 2,(IX+n>D)
225 | d3 SET 2,(IX+n>E)
226 | d4 SET 2,(IX+n>H)
227 | d5 SET 2,(IX+n>L)
228 | d6 SET 2,(IX+n)
229 | d7 SET 2,(IX+n>A)
230 | d8 SET 3,(IX+n>B)
231 | d9 SET 3,(IX+n>C)
232 | da SET 3,(IX+n>D)
233 | db SET 3,(IX+n>E)
234 | dc SET 3,(IX+n>H)
235 | dd SET 3,(IX+n>L)
236 | de SET 3,(IX+n)
237 | df SET 3,(IX+n>A)
238 |
239 | e0 SET 4,(IX+n>B)
240 | e1 SET 4,(IX+n>C)
241 | e2 SET 4,(IX+n>D)
242 | e3 SET 4,(IX+n>E)
243 | e4 SET 4,(IX+n>H)
244 | e5 SET 4,(IX+n>L)
245 | e6 SET 4,(IX+n)
246 | e7 SET 4,(IX+n>A)
247 | e8 SET 5,(IX+n>B)
248 | e9 SET 5,(IX+n>C)
249 | ea SET 5,(IX+n>D)
250 | eb SET 5,(IX+n>E)
251 | ec SET 5,(IX+n>H)
252 | ed SET 5,(IX+n>L)
253 | ee SET 5,(IX+n)
254 | ef SET 5,(IX+n>A)
255 |
256 | f0 SET 6,(IX+n>B)
257 | f1 SET 6,(IX+n>C)
258 | f2 SET 6,(IX+n>D)
259 | f3 SET 6,(IX+n>E)
260 | f4 SET 6,(IX+n>H)
261 | f5 SET 6,(IX+n>L)
262 | f6 SET 6,(IX+n)
263 | f7 SET 6,(IX+n>A)
264 | f8 SET 7,(IX+n>B)
265 | f9 SET 7,(IX+n>C)
266 | fa SET 7,(IX+n>D)
267 | fb SET 7,(IX+n>E)
268 | fc SET 7,(IX+n>H)
269 | fd SET 7,(IX+n>L)
270 | fe SET 7,(IX+n)
271 | ff SET 7,(IX+n>A)
272 |
--------------------------------------------------------------------------------
/runtime/render.js:
--------------------------------------------------------------------------------
1 | import { FRAME_BUFFER_SIZE } from './constants.js';
2 |
3 |
4 | export class CanvasRenderer {
5 | constructor(canvas) {
6 | this.canvas = canvas;
7 | this.ctx = this.canvas.getContext('2d');
8 | this.imageData = this.ctx.getImageData(0, 0, 320, 240);
9 | this.pixels = new Uint32Array(this.imageData.data.buffer);
10 | this.flashPhase = 0;
11 |
12 | this.palette = new Uint32Array([
13 | /* RGBA dark */
14 | 0x000000ff,
15 | 0x2030c0ff,
16 | 0xc04010ff,
17 | 0xc040c0ff,
18 | 0x40b010ff,
19 | 0x50c0b0ff,
20 | 0xe0c010ff,
21 | 0xc0c0c0ff,
22 | /* RGBA bright */
23 | 0x000000ff,
24 | 0x3040ffff,
25 | 0xff4030ff,
26 | 0xff70f0ff,
27 | 0x50e010ff,
28 | 0x50e0ffff,
29 | 0xffe850ff,
30 | 0xffffffff
31 | ]);
32 |
33 | const testUint8 = new Uint8Array(new Uint16Array([0x8000]).buffer);
34 | const isLittleEndian = (testUint8[0] === 0);
35 | if (isLittleEndian) {
36 | /* need to reverse the byte ordering of palette */
37 | for (let i = 0; i < 16; i++) {
38 | const color = this.palette[i];
39 | this.palette[i] = (
40 | (color << 24) & 0xff000000)
41 | | ((color << 8) & 0xff0000)
42 | | ((color >>> 8) & 0xff00)
43 | | ((color >>> 24) & 0xff
44 | );
45 | }
46 | }
47 | }
48 |
49 | showFrame(frameBuffer) {
50 | const frameBytes = new Uint8Array(frameBuffer);
51 | let pixelPtr = 0;
52 | let bufferPtr = 0;
53 | /* top border */
54 | for (let y = 0; y < 24; y++) {
55 | for (let x = 0; x < 160; x++) {
56 | let border = this.palette[frameBytes[bufferPtr++]]
57 | this.pixels[pixelPtr++] = border;
58 | this.pixels[pixelPtr++] = border;
59 | }
60 | }
61 |
62 | for (let y = 0; y < 192; y++) {
63 | /* left border */
64 | for (let x = 0; x < 16; x++) {
65 | let border = this.palette[frameBytes[bufferPtr++]]
66 | this.pixels[pixelPtr++] = border;
67 | this.pixels[pixelPtr++] = border;
68 | }
69 | /* main screen */
70 | for (let x = 0; x < 32; x++) {
71 | let bitmap = frameBytes[bufferPtr++];
72 | const attr = frameBytes[bufferPtr++];
73 | let ink, paper;
74 | if ((attr & 0x80) && (this.flashPhase & 0x10)) {
75 | // reverse ink and paper
76 | paper = this.palette[((attr & 0x40) >> 3) | (attr & 0x07)];
77 | ink = this.palette[(attr & 0x78) >> 3];
78 | } else {
79 | ink = this.palette[((attr & 0x40) >> 3) | (attr & 0x07)];
80 | paper = this.palette[(attr & 0x78) >> 3];
81 | }
82 | for (let i = 0; i < 8; i++) {
83 | this.pixels[pixelPtr++] = (bitmap & 0x80) ? ink : paper;
84 | bitmap <<= 1;
85 | }
86 | }
87 | /* right border */
88 | for (let x = 0; x < 16; x++) {
89 | let border = this.palette[frameBytes[bufferPtr++]]
90 | this.pixels[pixelPtr++] = border;
91 | this.pixels[pixelPtr++] = border;
92 | }
93 | }
94 | /* bottom border */
95 | for (let y = 0; y < 24; y++) {
96 | for (let x = 0; x < 160; x++) {
97 | let border = this.palette[frameBytes[bufferPtr++]]
98 | this.pixels[pixelPtr++] = border;
99 | this.pixels[pixelPtr++] = border;
100 | }
101 | }
102 | this.ctx.putImageData(this.imageData, 0, 0);
103 | this.flashPhase = (this.flashPhase + 1) & 0x1f;
104 | }
105 | }
106 |
107 |
108 | export class DisplayHandler {
109 | /*
110 | Handles triple-buffering so that at any given time we can have:
111 | - one buffer being drawn to the screen by the renderer
112 | - one buffer just finished being built by the worker process and waiting to be shown
113 | on the next animation frame
114 | - one buffer buffer being built by the worker process
115 | */
116 | constructor(canvas) {
117 | this.renderer = new CanvasRenderer(canvas);
118 |
119 | this.frameBuffers = [
120 | new ArrayBuffer(FRAME_BUFFER_SIZE),
121 | new ArrayBuffer(FRAME_BUFFER_SIZE),
122 | new ArrayBuffer(FRAME_BUFFER_SIZE),
123 | ];
124 | this.bufferBeingShown = null;
125 | this.bufferAwaitingShow = null;
126 | this.lockedBuffer = null;
127 | }
128 |
129 | frameCompleted(newFrameBuffer) {
130 | this.frameBuffers[this.lockedBuffer] = newFrameBuffer;
131 | this.bufferAwaitingShow = this.lockedBuffer;
132 | this.lockedBuffer = null;
133 | }
134 |
135 | getNextFrameBufferIndex() {
136 | for (let i = 0; i < 3; i++) {
137 | if (i !== this.bufferBeingShown && i !== this.bufferAwaitingShow) {
138 | return i;
139 | }
140 | }
141 | }
142 | getNextFrameBuffer() {
143 | this.lockedBuffer = this.getNextFrameBufferIndex();
144 | return this.frameBuffers[this.lockedBuffer];
145 | }
146 |
147 | readyToShow() {
148 | return this.bufferAwaitingShow !== null;
149 | }
150 | show() {
151 | this.bufferBeingShown = this.bufferAwaitingShow;
152 | this.bufferAwaitingShow = null;
153 | this.renderer.showFrame(this.frameBuffers[this.bufferBeingShown]);
154 | this.bufferBeingShown = null;
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/runtime/audio.js:
--------------------------------------------------------------------------------
1 | const ENABLE_OSCILLOSCOPE = false;
2 | const BUFFER_SIZE = 0x10000;
3 |
4 | export class AudioHandler {
5 | constructor() {
6 | this.isActive = false;
7 |
8 | if (ENABLE_OSCILLOSCOPE) {
9 | this.canvas = document.createElement('canvas');
10 | document.body.appendChild(this.canvas);
11 | this.canvasCtx = this.canvas.getContext('2d');
12 | }
13 | }
14 | start() {
15 | const AudioContext = window.AudioContext || window.webkitAudioContext;
16 | this.audioContext = new AudioContext({latencyHint: 'interactive'});
17 | this.samplesPerFrame = this.audioContext.sampleRate / 50;
18 |
19 | this.frameBuffers = [
20 | new ArrayBuffer(this.samplesPerFrame * 4),
21 | new ArrayBuffer(this.samplesPerFrame * 4)
22 | ];
23 |
24 | this.leftBuffer = new Float32Array(BUFFER_SIZE);
25 | this.rightBuffer = new Float32Array(BUFFER_SIZE);
26 | this.readPtr = 0;
27 | this.writePtr = 0;
28 |
29 | this.scriptNode = this.audioContext.createScriptProcessor(0, 0, 2);
30 | this.scriptNode.onaudioprocess = (audioProcessingEvent) => {
31 | const outputBuffer = audioProcessingEvent.outputBuffer;
32 | const leftData = outputBuffer.getChannelData(0);
33 | const rightData = outputBuffer.getChannelData(1);
34 |
35 | let availableDataLength = this.writePtr - this.readPtr;
36 | if (availableDataLength < 0) availableDataLength += BUFFER_SIZE;
37 |
38 | if (availableDataLength >= leftData.length) {
39 | // enough data is available to fill the buffer
40 | if (this.readPtr + leftData.length <= BUFFER_SIZE) {
41 | // can copy all in one go
42 | leftData.set(this.leftBuffer.slice(this.readPtr, this.readPtr + leftData.length));
43 | rightData.set(this.rightBuffer.slice(this.readPtr, this.readPtr + rightData.length));
44 | this.readPtr = (this.readPtr + leftData.length) % BUFFER_SIZE;
45 | } else {
46 | // straddles the end of our circular buffer - need to copy in two steps
47 | const firstChunkLength = BUFFER_SIZE - this.readPtr;
48 | const secondChunkLength = leftData.length - firstChunkLength;
49 |
50 | leftData.set(this.leftBuffer.slice(this.readPtr, this.readPtr + firstChunkLength));
51 | rightData.set(this.rightBuffer.slice(this.readPtr, this.readPtr + firstChunkLength));
52 | leftData.set(this.leftBuffer.slice(0, secondChunkLength), firstChunkLength);
53 | rightData.set(this.rightBuffer.slice(0, secondChunkLength), firstChunkLength);
54 |
55 | this.readPtr = secondChunkLength;
56 | }
57 | if (ENABLE_OSCILLOSCOPE) {
58 | this.drawOscilloscope(leftData, rightData);
59 | }
60 | }
61 | }
62 | this.scriptNode.connect(this.audioContext.destination);
63 |
64 | this.isActive = true;
65 |
66 | if (ENABLE_OSCILLOSCOPE) {
67 | this.canvas.width = this.samplesPerFrame;
68 | this.canvas.height = 64;
69 | }
70 | }
71 |
72 | stop() {
73 | this.scriptNode.disconnect(this.audioContext.destination);
74 | this.audioContext.close();
75 | }
76 |
77 | frameCompleted(audioBufferLeft, audioBufferRight) {
78 | this.frameBuffers[0] = audioBufferLeft;
79 | this.frameBuffers[1] = audioBufferRight;
80 |
81 | if (!this.isActive) return;
82 |
83 | const dataLength = audioBufferLeft.byteLength / 4;
84 | if (this.writePtr + dataLength <= BUFFER_SIZE) {
85 | /* can copy all in one go */
86 | const leftData = new Float32Array(audioBufferLeft);
87 | const rightData = new Float32Array(audioBufferRight);
88 | this.leftBuffer.set(leftData, this.writePtr);
89 | this.rightBuffer.set(rightData, this.writePtr);
90 | this.writePtr = (this.writePtr + dataLength) % BUFFER_SIZE;
91 | } else {
92 | /* straddles the end of our circular buffer - need to copy in two steps */
93 | const firstChunkLength = BUFFER_SIZE - this.writePtr;
94 | const secondChunkLength = dataLength - firstChunkLength;
95 | const leftData1 = new Float32Array(audioBufferLeft, 0, firstChunkLength);
96 | const rightData1 = new Float32Array(audioBufferRight, 0, firstChunkLength);
97 | this.leftBuffer.set(leftData1, this.writePtr);
98 | this.rightBuffer.set(rightData1, this.writePtr);
99 | const leftData2 = new Float32Array(audioBufferLeft, firstChunkLength * 4, secondChunkLength);
100 | const rightData2 = new Float32Array(audioBufferRight, firstChunkLength * 4, secondChunkLength);
101 | this.leftBuffer.set(leftData2, 0);
102 | this.rightBuffer.set(rightData2, 0);
103 | this.writePtr = secondChunkLength;
104 | }
105 | }
106 |
107 | drawOscilloscope(leftBuffer, rightBuffer) {
108 | this.canvasCtx.fillStyle = '#000';
109 | this.canvasCtx.strokeStyle = '#0f0';
110 | this.canvasCtx.fillRect(0, 0, this.samplesPerFrame, 64);
111 |
112 | const leftData = new Float32Array(leftBuffer);
113 | this.canvasCtx.beginPath();
114 | this.canvasCtx.moveTo(0, 16);
115 | for (let i = 0; i < this.samplesPerFrame; i++) {
116 | this.canvasCtx.lineTo(i, 16 - leftData[i] * 16);
117 | }
118 | this.canvasCtx.stroke();
119 |
120 | const rightData = new Float32Array(rightBuffer);
121 | this.canvasCtx.beginPath();
122 | this.canvasCtx.moveTo(0, 48);
123 | for (let i = 0; i < this.samplesPerFrame; i++) {
124 | this.canvasCtx.lineTo(i, 48 - rightData[i] * 16);
125 | }
126 | this.canvasCtx.stroke();
127 |
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # JSSpeccy 3
2 |
3 | A ZX Spectrum emulator for the browser
4 |
5 | ## Features
6 |
7 | * Emulates the Spectrum 48K, Spectrum 128K and Pentagon machines
8 | * Handles all Z80 instructions, documented and undocumented
9 | * Cycle-accurate emulation of scanline / multicolour effects
10 | * AY and beeper audio
11 | * Loads SZX, Z80 and SNA snapshots
12 | * Loads TZX and TAP tape images (via traps only)
13 | * Loads any of the above files from inside a ZIP file
14 | * 100% / 200% / 300% and fullscreen display modes
15 |
16 | ## Implementation notes
17 |
18 | JSSpeccy 3 is a complete rewrite of JSSpeccy to make full use of the web technologies and APIs available as of 2021 for high-performance web apps. The emulation runs in a Web Worker, freeing up the UI thread to handle screen and audio updates, with the emulator core (consisting of the Z80 processor emulation and any auxiliary processes that are likely to interrupt its execution multiple times per frame, such as constructing the video output, reading the keyboard and generating audio) running in WebAssembly, compiled from AssemblyScript (with a custom preprocessor).
19 |
20 | ## Contributions
21 |
22 | These days, releasing open source code tends to come with an unspoken social contract, so I'd like to set some expectations...
23 |
24 | This is a personal project, created for my own enjoyment, and my act of publishing the code does not come with any commitment to provide technical support or assistance. I'm always happy to hear of other people getting similar enjoyment from hacking on the code, and pull requests are welcome, but I can't promise to review them or shepherd them into an "official" release on any sort of timescale. Managing external contributions is often the point at which a "fun" project stops being fun. If there's a feature you need in the project - feel free to fork.
25 |
26 | ## Embedding
27 |
28 | JSSpeccy 3 is designed with embedding in mind. To include it in your own site, download [a release archive](https://github.com/gasman/jsspeccy3/releases) and copy the contents of the `jsspeccy` folder somewhere web-accessible. Be sure to keep the .js and .wasm files and the subdirectories in the same place relative to jsspeccy.js.
29 |
30 | In the `` of your HTML page, include the tag
31 |
32 | ```html
33 |
34 | ```
35 |
36 | replacing `/path/to/jsspeccy.js` with (yes!) the path to jsspeccy.js. At the point in the page where you want the emulator to show, place the code:
37 |
38 | ```html
39 |
40 |
41 | ```
42 |
43 | If you're suitably confident with JavaScript, you can put the call to `JSSpeccy` anywhere else that runs on page load, or in response to any user action.
44 |
45 | You can also pass configuration options as a second argument to `JSSpeccy`:
46 |
47 | ```html
48 |
49 | ```
50 |
51 | The available configuration options are:
52 |
53 | * `autoStart`: if true, the emulator will start immediately with no need to press the play button. Bear in mind that browser policies usually don't allow enabling audio without a user interaction, so if you enable this option (and don't put the `JSSpeccy` call behind an onclick event or similar), expect things to be silent.
54 | * `autoLoadTapes`: if true, any tape files opened (either manually or through the openUrl option) will be loaded automatically without the user having to enter LOAD "" or select the Tape Loader menu option.
55 | * `tapeAutoLoadMode`: specifies the mode that the machine should be set to before auto-loading tape files. When set to 'default' (the default), this is equivalent to selecting the Tape Loader menu option on machines that support it; when set to 'usr0', this is equivalent to entering 'usr0' in 128 BASIC then LOAD "" from the resulting 48K BASIC prompt (which leaves 128K memory paging available without the extra housekeeping of the 128K ROM - this mode is commonly used for launching demos).
56 | * `machine`: specifies the machine to emulate. Can be `48` (for a 48K Spectrum), `128` (for a 128K Spectrum), or `5` (for a Pentagon 128).
57 | * `openUrl`: specifies a URL, or an array of URLs, to a file (or files) to load on startup, in any supported snapshot, tape or archive format. Standard browser security restrictions apply for loading remote files: if the URL being loaded is not on the same domain as the calling page, it must serve [CORS HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) to be loadable.
58 | * `zoom`: specifies the size of the emulator window; 1 for 100% size (one Spectrum pixel per screen pixel), 2 for 200% size and so on.
59 | * `sandbox`: if true, all UI options for opening a new file are disabled - useful if you're showcasing a specific bit of Spectrum software on your page.
60 | * `tapeTrapsEnabled`: if true (the default), the emulator will recognise when the tape loading routine in the ROM is called, and load tape files instantly instead.
61 | * `keyboardEnabled`: True by default; if false, the emulator will not respond to keypresses.
62 | * `uiEnabled`: True by default; if false, the menu bar and toolbar will not be shown.
63 | * `keyboardMap`: if this is set to the value `"recreated"`, the emulator will accept keypresses in the encoded format emitted by the [Recreated ZX Spectrum](https://recreatedzxspectrum.com/) keyboard in "game mode". If it is unset or set to any other value, the emulator will accept keypresses as normal.
64 |
65 | For additional JavaScript hackery, the return value of the JSSpeccy function call is an object exposing a number of functions for controlling the running emulator:
66 |
67 | ```html
68 |
72 | ```
73 |
74 | * `emu.setZoom(zoomLevel)` - set the zoom level of the emulator
75 | * `emu.enterFullscreen()` - activate full-screen mode
76 | * `emu.exitFullscreen()` - exit full-screen mode
77 | * `emu.toggleFullscreen()` - enter or exit full-screen mode
78 | * `emu.setMachine(machine)` - set the emulated machine type
79 | * `emu.openFileDialog()` - open the file chooser dialog
80 | * `emu.openUrl(url)` - open the file at the given URL
81 | * `emu.loadSnapshotFromStruct(snapshot)` - load a snapshot from the given data structure; the data format is currently undocumented but runtime/snapshot.js should give you a decent idea of it...
82 | * `emu.onReady(callback)` - call the given callback once the emulator is fully initialised
83 | * `emu.exit()` - immediately stop the emulator and remove it from the document
84 |
85 |
86 | ## Licence
87 |
88 | JSSpeccy 3 is licensed under the GPL version 3 - see COPYING.
89 |
--------------------------------------------------------------------------------
/test/test.js:
--------------------------------------------------------------------------------
1 | import { argv, exit } from 'process';
2 | import * as fs from 'fs';
3 | import * as readline from 'readline';
4 |
5 | import * as core from '../dist/jsspeccy-core.wasm';
6 |
7 | if (argv.length != 4) {
8 | console.log("Usage: node test.js path/to/tests.in path/to/tests.expected");
9 | exit(1);
10 | }
11 |
12 | const EVENT_TYPE_IDS = {
13 | 1: 'MR', 2: 'MW', 3: 'MC', 4: 'PR', 5: 'PW', 6: 'PC', 0xffff: 'END'
14 | }
15 |
16 | const inputFilename = argv[2];
17 | const resultsFilename = argv[3];
18 |
19 | const registers = new Uint16Array(core.memory.buffer, core.REGISTERS, 12);
20 | const logEvents = new Uint16Array(core.memory.buffer, core.LOG_ENTRIES, 2048);
21 | core.setMachineType(1212);
22 |
23 |
24 | const inFile = fs.createReadStream(inputFilename);
25 | const reader = readline.createInterface({input: inFile, crlfDelay: Infinity});
26 | const getLine = (function () {
27 | const getLineGen = (async function* () {
28 | for await (const line of reader) {
29 | yield line;
30 | }
31 | })();
32 | return async () => ((await getLineGen.next()).value);
33 | })();
34 |
35 | const resultsFile = fs.createReadStream(resultsFilename);
36 | const resultsReader = readline.createInterface({input: resultsFile, crlfDelay: Infinity});
37 | const getResultLine = (function () {
38 | const getLineGen = (async function* () {
39 | for await (const line of resultsReader) {
40 | yield line;
41 | }
42 | })();
43 | return async () => ((await getLineGen.next()).value);
44 | })();
45 |
46 | function assertEqual(actual, expected, testName, reg) {
47 | if (actual != expected) {
48 | console.log(testName, reg, '- expected', expected.toString(16), 'but got', actual.toString(16));
49 | }
50 | }
51 |
52 | while (true) {
53 | const line = await getLine();
54 | if (line === undefined) break;
55 | if (!line) continue;
56 |
57 | core.reset();
58 |
59 | const testName = line;
60 | const mainRegistersLine = await getLine();
61 | const [af, bc, de, hl, af_, bc_, de_, hl_, ix, iy, sp, pc] = mainRegistersLine.split(/\s+/).map(x => parseInt(x, 16));
62 | const auxRegistersLine = await getLine();
63 | const auxRegistersStrings = auxRegistersLine.split(/\s+/)
64 | // tstates is in decimal, just to keep us on our toes
65 | const tstates = parseInt(auxRegistersStrings.pop(), 10);
66 | const [i, r, iff1, iff2, im, halted] = auxRegistersLine.split(/\s+/).map(x => parseInt(x, 16));
67 | while (true) {
68 | const memState = await getLine();
69 | if (memState == '-1') break;
70 | let [addr, ...vals] = memState.split(/\s+/).map(x => parseInt(x, 16));
71 | for (const val of vals) {
72 | if (val == -1) break;
73 | core.poke(addr++, val);
74 | }
75 | }
76 | registers[0] = af;
77 | registers[1] = bc;
78 | registers[2] = de;
79 | registers[3] = hl;
80 | registers[4] = af_;
81 | registers[5] = bc_;
82 | registers[6] = de_;
83 | registers[7] = hl_;
84 | registers[8] = ix;
85 | registers[9] = iy;
86 | registers[10] = sp;
87 | registers[11] = (i << 8) | r;
88 | core.setPC(pc);
89 | core.setIFF1(iff1);
90 | core.setIFF2(iff2);
91 | core.setIM(im);
92 | core.setHalted(halted);
93 |
94 | core.startLog();
95 | const status = core.runUntil(tstates);
96 | core.stopLog();
97 |
98 | let resultLine;
99 | while (true) {
100 | resultLine = await getResultLine();
101 | if (resultLine === undefined) {
102 | console.log("unexpected EOF in results file!");
103 | break;
104 | } else if (resultLine) {
105 | break;
106 | }
107 | }
108 | if (resultLine != testName) {
109 | console.log(
110 | "Test name in results file does not match: expected", testName, "but got", resultLine
111 | );
112 | }
113 |
114 | resultLine = await getResultLine();
115 | let checkingEvents = true;
116 | let logPtr = 0;
117 | while (resultLine.startsWith(' ')) {
118 | if (checkingEvents) {
119 | const [expectedEventTime, expectedEventType, expectedEventAddr, expectedEventVal] = resultLine.trim().split(/\s+/);
120 | const actualEventTime = logEvents[logPtr++];
121 | const actualEventType = EVENT_TYPE_IDS[logEvents[logPtr++]];
122 | const actualEventAddr = logEvents[logPtr++];
123 | const actualEventVal = logEvents[logPtr++];
124 | if (
125 | (parseInt(expectedEventTime) != actualEventTime)
126 | || (expectedEventType != actualEventType)
127 | || (parseInt(expectedEventAddr, 16) != actualEventAddr)
128 | || (parseInt(expectedEventVal || '0', 16) != actualEventVal)
129 | ) {
130 | const actualResult = '' + actualEventTime + ' ' + actualEventType + ' ' + actualEventAddr.toString(16) + ' ' + actualEventVal.toString(16);
131 | console.log("Event mismatch on test", testName, "- expected", resultLine, "but got", actualResult);
132 | checkingEvents = false;
133 | }
134 | }
135 |
136 | resultLine = await getResultLine();
137 | }
138 | if (checkingEvents && logEvents[logPtr] != 0xffff) {
139 | console.log("Extra event on test", testName);
140 | }
141 |
142 | const mainRegistersOutLine = resultLine;
143 | const [newaf, newbc, newde, newhl, newaf_, newbc_, newde_, newhl_, newix, newiy, newsp, newpc] = mainRegistersOutLine.split(/\s+/).map(x => parseInt(x, 16));
144 | const auxRegistersOutLine = await getResultLine()
145 | const auxRegistersOutStrings = auxRegistersOutLine.split(/\s+/);
146 | const newtstates = parseInt(auxRegistersOutStrings.pop(), 10);
147 | const [newi, newr, newiff1, newiff2, newim, newhalted] = auxRegistersOutStrings.map(x => parseInt(x, 16));
148 |
149 | if (status) {
150 | console.log(testName, 'failed with status', status.toString(16));
151 |
152 | while (await getResultLine()) {
153 | // discard memory lines
154 | }
155 | } else {
156 | while (resultLine = await getResultLine()) {
157 | // check memory span
158 | let [addr, ...vals] = resultLine.split(/\s+/).map(x => parseInt(x, 16));
159 | for (const val of vals) {
160 | if (val == -1) break;
161 | const actual = core.peek(addr)
162 | if (actual != val) {
163 | console.log(testName, 'mem', addr.toString(16), '- expected', val.toString(16), 'but got', actual.toString(16));
164 | }
165 | addr++;
166 | }
167 | };
168 |
169 | assertEqual(registers[0], newaf, testName, 'AF');
170 | assertEqual(registers[1], newbc, testName, 'BC');
171 | assertEqual(registers[2], newde, testName, 'DE');
172 | assertEqual(registers[3], newhl, testName, 'HL');
173 | assertEqual(registers[4], newaf_, testName, 'AF_');
174 | assertEqual(registers[5], newbc_, testName, 'BC_');
175 | assertEqual(registers[6], newde_, testName, 'DE_');
176 | assertEqual(registers[7], newhl_, testName, 'HL_');
177 | assertEqual(registers[8], newix, testName, 'IX');
178 | assertEqual(registers[9], newiy, testName, 'IY');
179 | assertEqual(registers[10], newsp, testName, 'SP');
180 | assertEqual(registers[11], (newi << 8) | newr, testName, 'IR');
181 | assertEqual(core.getPC(), newpc, testName, 'PC');
182 | assertEqual(core.getIFF1(), newiff1, testName, 'IFF1');
183 | assertEqual(core.getIFF2(), newiff2, testName, 'IFF2');
184 | assertEqual(core.getIM(), newim, testName, 'IM');
185 | assertEqual(core.getHalted(), newhalted, testName, 'halted');
186 | assertEqual(core.getTStates(), newtstates, testName, 'tstates');
187 | }
188 | }
189 |
190 | inFile.close();
191 | resultsFile.close();
--------------------------------------------------------------------------------
/tech_notes.md:
--------------------------------------------------------------------------------
1 | JSSpeccy 3 Tech Notes
2 | =====================
3 |
4 | Architecture
5 | ------------
6 |
7 | The browser UI thread (starting point in runtime/jsspeccy.js) is kept as lightweight as possible, only performing tasks that are directly related to communication with the "outside world": rendering the screen data to a canvas, handling keyboard events, outputting audio and managing UI actions such as loading files.
8 |
9 | All the actual emulation happens inside a Web Worker (runtime/worker.js), with all communcation between the UI thread and the worker happening through `postMessage`. The most important messages are `runFrame` (sent from the UI thread to the worker, to tell it to run one frame of emulation and fill the passed video and audio buffers with the resulting output) and `frameCompleted` (sent from the worker to the UI thread when execution of the frame is complete, passing the filled video and audio buffers back).
10 |
11 | Within the Web Worker, all of the performance-critical work is handled by a WebAssembly module (jsspeccy-core.wasm). The main entry point into this is the `runFrame` function, which runs the Z80 and all related 'continuous' processes (memory reads / writes, responding to port reads / writes, building the screen and generating audio) for one video frame. `runFrame` returns a status of 1 to indicate that the frame has completed execution (and thus the video / audio buffers are ready to send back to the UI thread), with other status values serving as 'exceptions', indicating that execution was interrupted and needs action from the calling code before it can be continued (by calling `resumeFrame`). At the time of writing, the only kind of exception implemented is a tape loading trap.
12 |
13 | All state required for the WebAssembly core module to run - including memory contents (ROM and RAM), registers, audio / video buffers and lookup tables - is contained within the module's own memory map, and statically allocated at compile time.
14 |
15 | On the real machine, generating video and audio output happens in parallel with the Z80's execution - an emulator implementing this naïvely would have to break out of the Z80 loop every few cycles to perform these tasks. In fact, these processes can be deferred for as long as we like, as long as we catch up on them before any state changes occur that would affect the output. With this in mind, the JSSpeccy core implements two functions `updateFramebuffer` and `updateAudioBuffer` which perform all pending video / audio generation as far as the current Z80 cycle. These are called immediately before any state change (which means, for audio, a write to any AY register or the beeper port; and for video, a write to video memory, change of border colour or a write to the memory paging port).
16 |
17 |
18 | Building the core
19 | -----------------
20 |
21 | To build jsspeccy-core.wasm, we run the script generator/gencore.js, which runs a preprocessing pass over the input file generator/core.ts.in, to generate the [AssemblyScript](https://www.assemblyscript.org/) source file build/core.ts. This is then passed to the AssemblyScript compiler to produce the final dist/jsspeccy-core.wasm module.
22 |
23 | The preprocessor step serves two purposes: firstly, it allows us to programmatically build the large repetitive `switch` statements that form the Z80 core. Secondly, it allows us to use conventional array syntax to access our statically-defined arrays. Currently, AssemblyScript does not appear to have any native support for static arrays - any use of array syntax causes it to immediately pull in a `malloc` implementation and a higher-level array construct with bounds checking, all of which is unwanted overhead for our purposes. The gencore.js processor rewrites array syntax into direct memory access [`load` / `store` instructions](https://www.assemblyscript.org/stdlib/builtins.html#memory).
24 |
25 | All statically-defined arrays are allocated at the start of the module's memory map, from address 0 onward. Currently a 512Kb block is allocated for these - if you need more, increase `memoryBase` in asconfig.json.
26 |
27 | The gencore.js preprocessor recognises the following directives:
28 |
29 | * `#alloc` - allocates an array of the given size and type. For example, if `#alloc frameBuffer[0x6600]: u8` is the first line of the file, then 0x6600 bytes from address 0 will be allocated to an array named `frameBuffer`. This will then rewrite subsequent lines as follows:
30 | * An assignment such as `frameBuffer = [0x00, 0x01, 0x02];` will be rewritten as a sequence of `store(0, 0x00);`, `store(1, 0x01);` lines
31 | * An assignment such as `frameBuffer[ptr] = 0x00;` will be rewritten as `store(0 + ptr, 0x00);`
32 | * A lookup such as `val = frameBuffer[ptr];` will be rewritten as `val = load(0 + ptr);`
33 | * `(&frameBuffer)` will be replaced with the array's base address, e.g. `const FRAME_BUFFER = (&frameBuffer);` becomes `const FRAME_BUFFER = 0;`
34 | * Keep in mind that these are simple regexp replacements, not a full parser - it's likely to fail on statements that are split over multiple lines, or have nested brackets. If you don't like this, feel free to submit a better implementation of static arrays to the AssemblyScript project :-)
35 | * `#const` - defines an identifier to be replaced by the given expression. For example, given a directive `#const FLAG_C 0x01`, a subsequent line `result &= FLAG_C;` will be rewritten to `result &= 0x01;`. `const FLAG_C = 0x01;` would achieve the same thing, but will also define a symbol in the resulting module, which we probably don't want.
36 | * `#regpair` - allocates two bytes to store a Z80 register pair. This is always little-endian, as per the WebAssembly spec. For example, if the next memory address to be allocated is 0x1000, then `#regpair BC B C` will define identifiers `BC`, `B` and `C` such that:
37 | * `val = BC;` is rewritten to `val = load(0x1000);`
38 | * `BC = 0x1234;` is rewritten to `store(0x1000, 0x1234);`
39 | * `val = B;` is rewritten to `val = load(0x1001);`
40 | * `B = result;` is rewritten to `store(0x1001, result);`
41 | * `val = C;` is rewritten to `val = load(0x1000);`
42 | * `C = result;` is rewritten to `store(0x1000, result);`
43 | * `#optable` - generates the sequence of `case` statements that decode an opcode byte. The subroutine bodies for each class of instruction are defined in generator/instructions.js, and these are pattern-matched to the actual instruction lists in generator/opcodes_*.txt.
44 |
45 |
46 | Frame buffer format
47 | -------------------
48 |
49 | The frame buffer data structure (as written by the WebAssembly core and passed to the UI thread in the `frameCompleted` message) is essentially a log of all border, screen and attribute bytes in the order that they would be read to build the video output. This is based on a 320x240 output image consisting of 24 lines of upper border, 192 lines of main screen (each consisting of 32px left border, 256px main screen, and 32px right border), and 24 lines of lower border. This results in a 0x6600 byte buffer, breaking down as follows:
50 |
51 | * 0x0000..0x009f: line 0 of the upper border. 160 bytes, each one being a border colour (0..7) and contributing two pixels to the final image. (This corresponds to the maximum resolution at which border colour changes happen on the Pentagon; these take effect on every cycle, and one cycle equals two pixels.)
52 | * 0x00a0..0x013f: line 1 of the upper border
53 | * ...
54 | * 0x0e60..0x0eff: line 23 of the upper border
55 | * 0x0f00..0x0f0f: left border of main screen line 0. 16 bytes, each contributing two pixels of border as before
56 | * 0x0f10..0x0f4f: main screen line 0. 32*2 bytes, consisting of the pixel byte and attribute byte for each of the 32 character cells
57 | * 0x0f50..0x0f5f: right border of main screen line 0. 16 bytes, each contributing two pixels of border as before
58 | * 0x0f60..0x0f6f: left border of main screen line 1
59 | * 0x0f70..0x0faf: main screen line 1. (Again, since the data here is in the order that the video output would be generated, this is the data pulled from address 0x4100 onward, not 0x4020.)
60 | * 0x0fb0..0x0fbf: right border of main screen line 2
61 | * ...
62 | * 0x56a0..0x56af: left border of main screen line 191
63 | * 0x56b0..0x56ef: main screen line 191
64 | * 0x56f0..0x56ff: right border of main screen line 191
65 | * 0x5700..0x579f: line 0 of the lower border. 160 bytes, as per upper border
66 | * 0x57a0..0x583f: line 1 of the lower border
67 | * ...
68 | * 0x6560..0x65ff: line 23 of the lower border
69 |
--------------------------------------------------------------------------------
/runtime/worker.js:
--------------------------------------------------------------------------------
1 | import { FRAME_BUFFER_SIZE } from './constants.js';
2 | import { TAPFile, TZXFile } from './tape.js';
3 |
4 | let core = null;
5 | let memory = null;
6 | let memoryData = null;
7 | let workerFrameData = null;
8 | let registerPairs = null;
9 | let tapePulses = null;
10 |
11 | let stopped = false;
12 | let tape = null;
13 | let tapeIsPlaying = false;
14 |
15 | const loadCore = (baseUrl) => {
16 | WebAssembly.instantiateStreaming(
17 | fetch(new URL('jsspeccy-core.wasm', baseUrl), {})
18 | ).then(results => {
19 | core = results.instance.exports;
20 | memory = core.memory;
21 | memoryData = new Uint8Array(memory.buffer);
22 | workerFrameData = memoryData.subarray(core.FRAME_BUFFER, FRAME_BUFFER_SIZE);
23 | registerPairs = new Uint16Array(core.memory.buffer, core.REGISTERS, 12);
24 | tapePulses = new Uint16Array(core.memory.buffer, core.TAPE_PULSES, core.TAPE_PULSES_LENGTH);
25 |
26 | postMessage({
27 | 'message': 'ready',
28 | });
29 | });
30 | }
31 |
32 | const loadMemoryPage = (page, data) => {
33 | memoryData.set(data, core.MACHINE_MEMORY + page * 0x4000);
34 | };
35 |
36 | const loadSnapshot = (snapshot) => {
37 | core.setMachineType(snapshot.model);
38 | for (let page in snapshot.memoryPages) {
39 | loadMemoryPage(page, snapshot.memoryPages[page]);
40 | }
41 | ['AF', 'BC', 'DE', 'HL', 'AF_', 'BC_', 'DE_', 'HL_', 'IX', 'IY', 'SP', 'IR'].forEach(
42 | (r, i) => {
43 | registerPairs[i] = snapshot.registers[r];
44 | }
45 | )
46 | core.setPC(snapshot.registers.PC);
47 | core.setIFF1(snapshot.registers.iff1);
48 | core.setIFF2(snapshot.registers.iff2);
49 | core.setIM(snapshot.registers.im);
50 | core.setHalted(!!snapshot.halted);
51 |
52 | core.writePort(0x00fe, snapshot.ulaState.borderColour);
53 | if (snapshot.model != 48) {
54 | core.writePort(0x7ffd, snapshot.ulaState.pagingFlags);
55 | }
56 |
57 | core.setTStates(snapshot.tstates);
58 | };
59 |
60 | const trapTapeLoad = () => {
61 | if (!tape) return;
62 | const block = tape.getNextLoadableBlock();
63 | if (!block) return;
64 |
65 | /* get expected block type and load vs verify flag from AF' */
66 | const af_ = registerPairs[4];
67 | const expectedBlockType = af_ >> 8;
68 | const shouldLoad = af_ & 0x0001; // LOAD rather than VERIFY
69 | let addr = registerPairs[8]; /* IX */
70 | const requestedLength = registerPairs[2]; /* DE */
71 | const actualBlockType = block[0];
72 |
73 | let success = true;
74 | if (expectedBlockType != actualBlockType) {
75 | success = false;
76 | } else {
77 | if (shouldLoad) {
78 | let offset = 1;
79 | let loadedBytes = 0;
80 | let checksum = actualBlockType;
81 | while (loadedBytes < requestedLength) {
82 | if (offset >= block.length) {
83 | /* have run out of bytes to load */
84 | success = false;
85 | break;
86 | }
87 | const byte = block[offset++];
88 | loadedBytes++;
89 | core.poke(addr, byte);
90 | addr = (addr + 1) & 0xffff;
91 | checksum ^= byte;
92 | }
93 |
94 | // if loading is going right, we should still have a checksum byte left to read
95 | success &= (offset < block.length);
96 | if (success) {
97 | const expectedChecksum = block[offset];
98 | success = (checksum === expectedChecksum);
99 | }
100 | } else {
101 | // VERIFY. TODO: actually verify.
102 | success = true;
103 | }
104 | }
105 |
106 | if (success) {
107 | /* set carry to indicate success */
108 | registerPairs[0] |= 0x0001;
109 | } else {
110 | /* reset carry to indicate failure */
111 | registerPairs[0] &= 0xfffe;
112 | }
113 | core.setPC(0x05e2); /* address at which to exit the tape trap */
114 | }
115 |
116 | onmessage = (e) => {
117 | switch (e.data.message) {
118 | case 'loadCore':
119 | loadCore(e.data.baseUrl);
120 | break;
121 | case 'runFrame':
122 | if (stopped) return;
123 | const frameBuffer = e.data.frameBuffer;
124 | const frameData = new Uint8Array(frameBuffer);
125 |
126 | let audioBufferLeft = null;
127 | let audioBufferRight = null;
128 | let audioLength = 0;
129 | if ('audioBufferLeft' in e.data) {
130 | audioBufferLeft = e.data.audioBufferLeft;
131 | audioBufferRight = e.data.audioBufferRight;
132 | audioLength = audioBufferLeft.byteLength / 4;
133 | core.setAudioSamplesPerFrame(audioLength);
134 | } else {
135 | core.setAudioSamplesPerFrame(0);
136 | }
137 |
138 | if (tape && tapeIsPlaying) {
139 | const tapePulseBufferTstateCount = core.getTapePulseBufferTstateCount();
140 | const tapePulseWriteIndex = core.getTapePulseWriteIndex();
141 | const [newTapePulseWriteIndex, tstatesGenerated, tapeFinished] = tape.pulseGenerator.emitPulses(
142 | tapePulses, tapePulseWriteIndex, 80000 - tapePulseBufferTstateCount
143 | );
144 | core.setTapePulseBufferState(newTapePulseWriteIndex, tapePulseBufferTstateCount + tstatesGenerated);
145 | if (tapeFinished) {
146 | tapeIsPlaying = false;
147 | postMessage({
148 | message: 'stoppedTape',
149 | });
150 | }
151 | }
152 |
153 | let status = core.runFrame();
154 | while (status) {
155 | switch (status) {
156 | case 1:
157 | stopped = true;
158 | throw("Unrecognised opcode!");
159 | case 2:
160 | trapTapeLoad();
161 | break;
162 | default:
163 | stopped = true;
164 | throw("runFrame returned unexpected result: " + status);
165 | }
166 |
167 | status = core.resumeFrame();
168 | }
169 |
170 | frameData.set(workerFrameData);
171 | if (audioLength) {
172 | const leftSource = new Float32Array(core.memory.buffer, core.AUDIO_BUFFER_LEFT, audioLength);
173 | const rightSource = new Float32Array(core.memory.buffer, core.AUDIO_BUFFER_RIGHT, audioLength);
174 | const leftData = new Float32Array(audioBufferLeft);
175 | const rightData = new Float32Array(audioBufferRight);
176 | leftData.set(leftSource);
177 | rightData.set(rightSource);
178 | postMessage({
179 | message: 'frameCompleted',
180 | frameBuffer,
181 | audioBufferLeft,
182 | audioBufferRight,
183 | }, [frameBuffer, audioBufferLeft, audioBufferRight]);
184 | } else {
185 | postMessage({
186 | message: 'frameCompleted',
187 | frameBuffer,
188 | }, [frameBuffer]);
189 | }
190 |
191 | break;
192 | case 'keyDown':
193 | core.keyDown(e.data.row, e.data.mask);
194 | break;
195 | case 'keyUp':
196 | core.keyUp(e.data.row, e.data.mask);
197 | break;
198 | case 'setMachineType':
199 | core.setMachineType(e.data.type);
200 | break;
201 | case 'reset':
202 | core.reset();
203 | break;
204 | case 'loadMemory':
205 | loadMemoryPage(e.data.page, e.data.data);
206 | break;
207 | case 'loadSnapshot':
208 | loadSnapshot(e.data.snapshot);
209 | postMessage({
210 | message: 'fileOpened',
211 | id: e.data.id,
212 | mediaType: 'snapshot',
213 | });
214 | break;
215 | case 'openTAPFile':
216 | tape = new TAPFile(e.data.data);
217 | tapeIsPlaying = false;
218 | postMessage({
219 | message: 'fileOpened',
220 | id: e.data.id,
221 | mediaType: 'tape',
222 | });
223 | break;
224 | case 'openTZXFile':
225 | tape = new TZXFile(e.data.data);
226 | tapeIsPlaying = false;
227 | postMessage({
228 | message: 'fileOpened',
229 | id: e.data.id,
230 | mediaType: 'tape',
231 | });
232 | break;
233 |
234 | case 'playTape':
235 | if (tape && !tapeIsPlaying) {
236 | tapeIsPlaying = true;
237 | postMessage({
238 | message: 'playingTape',
239 | });
240 | }
241 | break;
242 | case 'stopTape':
243 | if (tape && tapeIsPlaying) {
244 | tapeIsPlaying = false;
245 | postMessage({
246 | message: 'stoppedTape',
247 | });
248 | }
249 | break;
250 | case 'setTapeTraps':
251 | core.setTapeTraps(e.data.value);
252 | break;
253 | default:
254 | console.log('message received by worker:', e.data);
255 | }
256 | };
257 |
--------------------------------------------------------------------------------
/runtime/keyboard.js:
--------------------------------------------------------------------------------
1 | // Mapping from Spectrum key identifiers to keyboard matrix info
2 | const SPECCY = {
3 | ONE: {row: 3, mask: 0x01},
4 | TWO: {row: 3, mask: 0x02},
5 | THREE: {row: 3, mask: 0x04},
6 | FOUR: {row: 3, mask: 0x08},
7 | FIVE: {row: 3, mask: 0x10},
8 | SIX: {row: 4, mask: 0x10},
9 | SEVEN: {row: 4, mask: 0x08},
10 | EIGHT: {row: 4, mask: 0x04},
11 | NINE: {row: 4, mask: 0x02},
12 | ZERO: {row: 4, mask: 0x01},
13 |
14 | Q: {row: 2, mask: 0x01},
15 | W: {row: 2, mask: 0x02},
16 | E: {row: 2, mask: 0x04},
17 | R: {row: 2, mask: 0x08},
18 | T: {row: 2, mask: 0x10},
19 | Y: {row: 5, mask: 0x10},
20 | U: {row: 5, mask: 0x08},
21 | I: {row: 5, mask: 0x04},
22 | O: {row: 5, mask: 0x02},
23 | P: {row: 5, mask: 0x01},
24 |
25 | A: {row: 1, mask: 0x01},
26 | S: {row: 1, mask: 0x02},
27 | D: {row: 1, mask: 0x04},
28 | F: {row: 1, mask: 0x08},
29 | G: {row: 1, mask: 0x10},
30 | H: {row: 6, mask: 0x10},
31 | J: {row: 6, mask: 0x08},
32 | K: {row: 6, mask: 0x04},
33 | L: {row: 6, mask: 0x02},
34 | ENTER: {row: 6, mask: 0x01},
35 |
36 | CAPS_SHIFT: {row: 0, mask: 0x01, isCaps: true},
37 | Z: {row: 0, mask: 0x02},
38 | X: {row: 0, mask: 0x04},
39 | C: {row: 0, mask: 0x08},
40 | V: {row: 0, mask: 0x10},
41 | B: {row: 7, mask: 0x10},
42 | N: {row: 7, mask: 0x08},
43 | M: {row: 7, mask: 0x04},
44 | SYMBOL_SHIFT: {row: 7, mask: 0x02, isSymbol: true},
45 | BREAK_SPACE: {row: 7, mask: 0x01},
46 | };
47 |
48 | function sym(speccyKey) {
49 | // patch key definition to indicate that symbol shift should be activated
50 | return {...speccyKey, sym: true}
51 | }
52 |
53 | function caps(speccyKey) {
54 | // patch key definition to indicate that caps shift should be activated
55 | return {...speccyKey, caps: true}
56 | }
57 |
58 | // Mapping from JS key codes to Spectrum key definitions
59 | const KEY_CODES = {
60 | 49: SPECCY.ONE,
61 | 50: SPECCY.TWO,
62 | 51: SPECCY.THREE,
63 | 52: SPECCY.FOUR,
64 | 53: SPECCY.FIVE,
65 | 54: SPECCY.SIX,
66 | 55: SPECCY.SEVEN,
67 | 56: SPECCY.EIGHT,
68 | 57: SPECCY.NINE,
69 | 48: SPECCY.ZERO,
70 |
71 | 81: SPECCY.Q,
72 | 87: SPECCY.W,
73 | 69: SPECCY.E,
74 | 82: SPECCY.R,
75 | 84: SPECCY.T,
76 | 89: SPECCY.Y,
77 | 85: SPECCY.U,
78 | 73: SPECCY.I,
79 | 79: SPECCY.O,
80 | 80: SPECCY.P,
81 |
82 | 65: SPECCY.A,
83 | 83: SPECCY.S,
84 | 68: SPECCY.D,
85 | 70: SPECCY.F,
86 | 71: SPECCY.G,
87 | 72: SPECCY.H,
88 | 74: SPECCY.J,
89 | 75: SPECCY.K,
90 | 76: SPECCY.L,
91 | 13: SPECCY.ENTER,
92 |
93 | 16: SPECCY.CAPS_SHIFT, /* caps */
94 | 192: SPECCY.CAPS_SHIFT, /* backtick as caps - because firefox screws up a load of key codes when pressing shift */
95 | 90: SPECCY.Z,
96 | 88: SPECCY.X,
97 | 67: SPECCY.C,
98 | 86: SPECCY.V,
99 | 66: SPECCY.B,
100 | 78: SPECCY.N,
101 | 77: SPECCY.M,
102 | 17: SPECCY.SYMBOL_SHIFT, /* sym - gah, firefox screws up ctrl+key too */
103 | 32: SPECCY.BREAK_SPACE, /* space */
104 |
105 | /* shifted combinations */
106 | 8: caps(SPECCY.ZERO), /* backspace */
107 | 37: caps(SPECCY.FIVE), /* left arrow */
108 | 38: caps(SPECCY.SEVEN), /* up arrow */
109 | 39: caps(SPECCY.EIGHT), /* right arrow */
110 | 40: caps(SPECCY.SIX), /* down arrow */
111 |
112 | /* symbol keys */
113 | '-': sym(SPECCY.J),
114 | '_': sym(SPECCY.ZERO),
115 | '=': sym(SPECCY.L),
116 | '+': sym(SPECCY.K),
117 | ';': sym(SPECCY.O),
118 | ':': sym(SPECCY.Z),
119 | '\'': sym(SPECCY.SEVEN),
120 | '"': sym(SPECCY.P),
121 | ',': sym(SPECCY.N),
122 | '<': sym(SPECCY.R),
123 | '.': sym(SPECCY.M),
124 | '>': sym(SPECCY.T),
125 | '/': sym(SPECCY.V),
126 | '?': sym(SPECCY.C),
127 | '*': sym(SPECCY.B),
128 | '@': sym(SPECCY.TWO),
129 | '#': sym(SPECCY.THREE),
130 | };
131 | KEY_CODES[String.fromCharCode(0x2264)] = sym(SPECCY.Q); // LESS_THAN_EQUAL symbol (≤)
132 | KEY_CODES[String.fromCharCode(0x2265)] = sym(SPECCY.E); // GREATER_THAN_EQUAL symbol (≥)
133 | KEY_CODES[String.fromCharCode(0x2260)] = sym(SPECCY.W); // NOT_EQUAL symbol (≠)
134 |
135 |
136 | export class BaseKeyboardHandler {
137 | constructor(worker, rootElement) {
138 | this.worker = worker;
139 | this.rootElement = rootElement; // where we attach keyboard event listeners
140 | this.eventsAreBound = false;
141 |
142 | this.keypressHandler = (evt) => {
143 | if (!evt.metaKey) evt.preventDefault();
144 | };
145 | }
146 |
147 | start() {
148 | this.rootElement.addEventListener('keydown', this.keydownHandler);
149 | this.rootElement.addEventListener('keyup', this.keyupHandler);
150 | this.rootElement.addEventListener('keypress', this.keypressHandler);
151 | this.eventsAreBound = true;
152 | }
153 |
154 | stop() {
155 | this.rootElement.removeEventListener('keydown', this.keydownHandler);
156 | this.rootElement.removeEventListener('keyup', this.keyupHandler);
157 | this.rootElement.removeEventListener('keypress', this.keypressHandler);
158 | this.eventsAreBound = false;
159 | }
160 |
161 | setRootElement(newRootElement) {
162 | if (this.eventsAreBound) {
163 | this.stop();
164 | this.rootElement = newRootElement;
165 | this.start();
166 | } else {
167 | this.rootElement = newRootElement;
168 | }
169 | }
170 | }
171 |
172 | export class StandardKeyboardHandler extends BaseKeyboardHandler {
173 | constructor(worker, rootElement) {
174 | super(worker, rootElement);
175 |
176 | // if true, the real symbol shift key is being held (as opposed to being active through a
177 | // virtual key combination)
178 | this.symbolIsShifted = false;
179 |
180 | // if true, the real caps shift key is being held (as opposed to being active through a
181 | // virtual key combination)
182 | this.capsIsShifted = false;
183 |
184 | // When a keypress is recognised by its character rather than its numeric key code, store
185 | // the resolved key info struct here, indexed by key code. If the state of shift keys
186 | // changes while that key is held down, we will see subsequent keydown events with a
187 | // different character but the same key code. For example, if the user holds the semicolon
188 | // key and then presses shift, we will see a keydown event with {keyCode: 186, key: ';'},
189 | // and then another keydown event with {keyCode: 186, key=':'}. In this case, we would need
190 | // to simulate a keyup event for the semicolon before registering the colon as a new
191 | // keypress. This table allows us to recognise when changes like this happen.
192 | this.seenKeyCodes = {};
193 |
194 | this.keydownHandler = (evt) => {
195 | let keyInfo = KEY_CODES[evt.keyCode];
196 | if (keyInfo) {
197 | this.keyDown(keyInfo);
198 | } else {
199 | keyInfo = KEY_CODES[evt.key];
200 | if (keyInfo) {
201 | const lastKeyInfo = this.seenKeyCodes[evt.keyCode];
202 | if (lastKeyInfo && lastKeyInfo !== keyInfo) {
203 | this.keyUp(lastKeyInfo);
204 | }
205 | this.seenKeyCodes[evt.keyCode] = keyInfo;
206 | this.keyDown(keyInfo);
207 | }
208 | }
209 | if (!evt.metaKey) evt.preventDefault();
210 | };
211 |
212 | this.keyupHandler = (evt) => {
213 | const keyInfo = KEY_CODES[evt.keyCode];
214 | if (keyInfo) {
215 | this.keyUp(keyInfo);
216 | } else {
217 | const lastKeyInfo = this.seenKeyCodes[evt.keyCode];
218 | if (lastKeyInfo) {
219 | this.seenKeyCodes[evt.keyCode] = null;
220 | this.keyUp(lastKeyInfo);
221 | }
222 | }
223 | if (!evt.metaKey) evt.preventDefault();
224 | };
225 | }
226 |
227 | sendKeyMessage(speccyKey, downNotUp) {
228 | this.worker.postMessage({
229 | message: downNotUp ? 'keyDown' : 'keyUp', row: speccyKey.row, mask: speccyKey.mask,
230 | });
231 | }
232 |
233 | keyDown(speccyKey) {
234 | this.sendKeyMessage(speccyKey, true);
235 | if ('caps' in speccyKey || 'sym' in speccyKey) {
236 | this.sendKeyMessage(SPECCY.CAPS_SHIFT, 'caps' in speccyKey);
237 | this.sendKeyMessage(SPECCY.SYMBOL_SHIFT, 'sym' in speccyKey);
238 | } else if (speccyKey.isCaps) {
239 | this.capsIsShifted = true;
240 | } else if (speccyKey.isSymbol) {
241 | this.symbolIsShifted = true;
242 | }
243 | }
244 |
245 | keyUp(speccyKey) {
246 | this.sendKeyMessage(speccyKey, false);
247 | if ('caps' in speccyKey || 'sym' in speccyKey) {
248 | this.sendKeyMessage(SPECCY.CAPS_SHIFT, this.capsIsShifted);
249 | this.sendKeyMessage(SPECCY.SYMBOL_SHIFT, this.symbolIsShifted);
250 | } else if (speccyKey.isCaps) {
251 | this.capsIsShifted = false;
252 | } else if (speccyKey.isSymbol) {
253 | this.symbolIsShifted = false;
254 | }
255 | }
256 | }
257 |
258 | const RECREATED_SPECTRUM_GAME_LAYER = {
259 | "ab": SPECCY.ONE,
260 | "cd": SPECCY.TWO,
261 | "ef": SPECCY.THREE,
262 | "gh": SPECCY.FOUR,
263 | "ij": SPECCY.FIVE,
264 | "kl": SPECCY.SIX,
265 | "mn": SPECCY.SEVEN,
266 | "op": SPECCY.EIGHT,
267 | "qr": SPECCY.NINE,
268 | "st": SPECCY.ZERO,
269 |
270 | "uv": SPECCY.Q,
271 | "wx": SPECCY.W,
272 | "yz": SPECCY.E,
273 | "AB": SPECCY.R,
274 | "CD": SPECCY.T,
275 | "EF": SPECCY.Y,
276 | "GH": SPECCY.U,
277 | "IJ": SPECCY.I,
278 | "KL": SPECCY.O,
279 | "MN": SPECCY.P,
280 |
281 | "OP": SPECCY.A,
282 | "QR": SPECCY.S,
283 | "ST": SPECCY.D,
284 | "UV": SPECCY.F,
285 | "WX": SPECCY.G,
286 | "YZ": SPECCY.H,
287 | "01": SPECCY.J,
288 | "23": SPECCY.K,
289 | "45": SPECCY.L,
290 | "67": SPECCY.ENTER,
291 |
292 | "89": SPECCY.CAPS_SHIFT,
293 | "<>": SPECCY.Z,
294 | "-=": SPECCY.X,
295 | "[]": SPECCY.C,
296 | ";:": SPECCY.V,
297 | ",.": SPECCY.B,
298 | "/?": SPECCY.N,
299 | "{}": SPECCY.M,
300 | "!$": SPECCY.SYMBOL_SHIFT,
301 | "%^": SPECCY.BREAK_SPACE,
302 | };
303 | let recreatedUpDown = {};
304 |
305 | for (const [pair, key] of Object.entries(RECREATED_SPECTRUM_GAME_LAYER)) {
306 | recreatedUpDown[pair.charAt(0)] = { ...key, message: "keyDown" };
307 | recreatedUpDown[pair.charAt(1)] = { ...key, message: "keyUp" };
308 | }
309 |
310 | export class RecreatedZXSpectrumHandler extends BaseKeyboardHandler {
311 | constructor(worker, rootElement) {
312 | super(worker, rootElement);
313 |
314 | this.keydownHandler = (evt) => {
315 | const specialCode = recreatedUpDown[evt.key];
316 | if (specialCode) {
317 | this.worker.postMessage({
318 | message: specialCode.message, row: specialCode.row, mask: specialCode.mask,
319 | });
320 | }
321 | if (!evt.metaKey) evt.preventDefault();
322 | };
323 |
324 | this.keyupHandler = (evt) => {
325 | if (!evt.metaKey) evt.preventDefault();
326 | };
327 | }
328 | }
329 |
--------------------------------------------------------------------------------
/runtime/snapshot.js:
--------------------------------------------------------------------------------
1 | import pako from 'pako';
2 |
3 | function extractMemoryBlock(data, fileOffset, isCompressed, unpackedLength) {
4 | if (!isCompressed) {
5 | /* uncompressed; extract a byte array directly from data */
6 | return new Uint8Array(data, fileOffset, unpackedLength);
7 | } else {
8 | /* compressed */
9 | const fileBytes = new Uint8Array(data, fileOffset);
10 | const memoryBytes = new Uint8Array(unpackedLength);
11 | let filePtr = 0;
12 | let memoryPtr = 0;
13 | while (memoryPtr < unpackedLength) {
14 | /* check for coded ED ED nn bb sequence */
15 | if (
16 | unpackedLength - memoryPtr >= 2 && /* at least two bytes left to unpack */
17 | fileBytes[filePtr] == 0xed &&
18 | fileBytes[filePtr + 1] == 0xed
19 | ) {
20 | /* coded sequence */
21 | const count = fileBytes[filePtr + 2];
22 | const value = fileBytes[filePtr + 3];
23 | for (let i = 0; i < count; i++) {
24 | memoryBytes[memoryPtr++] = value;
25 | }
26 | filePtr += 4;
27 | } else {
28 | /* plain byte */
29 | memoryBytes[memoryPtr++] = fileBytes[filePtr++];
30 | }
31 | }
32 | return memoryBytes;
33 | }
34 | }
35 |
36 | export function parseZ80File(data) {
37 | const file = new DataView(data);
38 |
39 | const iReg = file.getUint8(10);
40 | const byte12 = file.getUint8(12);
41 | const rReg = (file.getUint8(11) & 0x7f) | ((byte12 & 0x01) << 7);
42 | const byte29 = file.getUint8(29);
43 |
44 | const snapshot = {
45 | registers: {
46 | 'AF': file.getUint16(0, false), /* NB Big-endian */
47 | 'BC': file.getUint16(2, true),
48 | 'HL': file.getUint16(4, true),
49 | 'PC': file.getUint16(6, true),
50 | 'SP': file.getUint16(8, true),
51 | 'IR': (iReg << 8) | rReg,
52 | 'DE': file.getUint16(13, true),
53 | 'BC_': file.getUint16(15, true),
54 | 'DE_': file.getUint16(17, true),
55 | 'HL_': file.getUint16(19, true),
56 | 'AF_': file.getUint16(21, false), /* Big-endian */
57 | 'IY': file.getUint16(23, true),
58 | 'IX': file.getUint16(25, true),
59 | 'iff1': !!file.getUint8(27),
60 | 'iff2': !!file.getUint8(28),
61 | 'im': byte29 & 0x03
62 | },
63 | ulaState: {
64 | borderColour: (byte12 & 0x0e) >> 1
65 | },
66 | memoryPages: {},
67 | };
68 |
69 | if (snapshot.registers.PC !== 0) {
70 | /* a non-zero value for PC at offset 6 indicates a version 1 file */
71 | snapshot.model = 48;
72 | const memory = extractMemoryBlock(data, 30, byte12 & 0x20, 0xc000);
73 |
74 | /* construct byte arrays of length 0x4000 at the appropriate offsets into the data stream */
75 | snapshot.memoryPages[5] = new Uint8Array(memory.buffer, 0, 0x4000);
76 | snapshot.memoryPages[2] = new Uint8Array(memory.buffer, 0x4000, 0x4000);
77 | snapshot.memoryPages[0] = new Uint8Array(memory.buffer, 0x8000, 0x4000);
78 |
79 | snapshot.tstates = 0;
80 | } else {
81 | /* version 2-3 snapshot */
82 | const additionalHeaderLength = file.getUint16(30, true);
83 | const isVersion2 = (additionalHeaderLength == 23);
84 | snapshot.registers.PC = file.getUint16(32, true);
85 | const machineId = file.getUint8(34);
86 | const is48K = (isVersion2 ? machineId < 3 : machineId < 4);
87 | snapshot.model = (is48K ? 48 : 128);
88 | if (!is48K) {
89 | snapshot.ulaState.pagingFlags = file.getUint8(35);
90 | }
91 | const tstateChunkSize = (is48K ? 69888 : 70908) / 4;
92 | snapshot.tstates = (
93 | (((file.getUint8(57) + 1) % 4) + 1) * tstateChunkSize
94 | - (file.getUint16(55, true) + 1)
95 | );
96 | if (snapshot.tstates >= tstateChunkSize * 4) snapshot.tstates = 0;
97 |
98 | let offset = 32 + additionalHeaderLength;
99 |
100 | /* translation table from the IDs Z80 assigns to pages, to the page numbers they
101 | actually get loaded into */
102 | let pageIdToNumber;
103 | if (is48K) {
104 | pageIdToNumber = {
105 | 4: 2,
106 | 5: 0,
107 | 8: 5
108 | };
109 | } else {
110 | pageIdToNumber = {
111 | 3: 0,
112 | 4: 1,
113 | 5: 2,
114 | 6: 3,
115 | 7: 4,
116 | 8: 5,
117 | 9: 6,
118 | 10: 7
119 | };
120 | }
121 | while (offset < data.byteLength) {
122 | let compressedLength = file.getUint16(offset, true);
123 | let isCompressed = true;
124 | if (compressedLength == 0xffff) {
125 | compressedLength = 0x4000;
126 | isCompressed = false;
127 | }
128 | const pageId = file.getUint8(offset + 2);
129 | if (pageId in pageIdToNumber) {
130 | const pageNumber = pageIdToNumber[pageId];
131 | const pageData = extractMemoryBlock(data, offset + 3, isCompressed, 0x4000);
132 | snapshot.memoryPages[pageNumber] = pageData;
133 | }
134 | offset += compressedLength + 3;
135 | }
136 | }
137 |
138 | return snapshot;
139 | }
140 |
141 |
142 | export function parseSNAFile(data) {
143 | let mode128 = false;
144 | let snapshot = null;
145 | const len = data.byteLength;
146 | let sna;
147 |
148 | switch (len) {
149 | case 131103:
150 | case 147487:
151 | mode128 = true;
152 | case 49179:
153 | sna = new DataView(data, 0, mode128 ? 49182 : len);
154 | snapshot = {
155 | model: (mode128 ? 128 : 48),
156 | registers: {},
157 | ulaState: {},
158 | /* construct byte arrays of length 0x4000 at the appropriate offsets into the data stream */
159 | memoryPages: {
160 | 5: new Uint8Array(data, 0x0000 + 27, 0x4000),
161 | 2: new Uint8Array(data, 0x4000 + 27, 0x4000)
162 | },
163 | tstates: 0,
164 | };
165 |
166 | if (mode128) {
167 | const page = (sna.getUint8(49181) & 7);
168 | snapshot.memoryPages[page] = new Uint8Array(data, 0x8000 + 27, 0x4000);
169 |
170 | for (let i = 0, ptr = 49183; i < 8; i++) {
171 | if (typeof snapshot.memoryPages[i] === 'undefined') {
172 | snapshot.memoryPages[i] = new Uint8Array(data, ptr, 0x4000);
173 | ptr += 0x4000;
174 | }
175 | }
176 | }
177 | else
178 | snapshot.memoryPages[0] = new Uint8Array(data, 0x8000 + 27, 0x4000);
179 |
180 | snapshot.registers['IR'] = (sna.getUint8(0) << 8) | sna.getUint8(20);
181 | snapshot.registers['HL_'] = sna.getUint16(1, true);
182 | snapshot.registers['DE_'] = sna.getUint16(3, true);
183 | snapshot.registers['BC_'] = sna.getUint16(5, true);
184 | snapshot.registers['AF_'] = sna.getUint16(7, true);
185 | snapshot.registers['HL'] = sna.getUint16(9, true);
186 | snapshot.registers['DE'] = sna.getUint16(11, true);
187 | snapshot.registers['BC'] = sna.getUint16(13, true);
188 | snapshot.registers['IY'] = sna.getUint16(15, true);
189 | snapshot.registers['IX'] = sna.getUint16(17, true);
190 | snapshot.registers['iff1'] = snapshot.registers['iff2'] = (sna.getUint8(19) & 0x04) >> 2;
191 | snapshot.registers['AF'] = sna.getUint16(21, true);
192 |
193 | if (mode128) {
194 | snapshot.registers['SP'] = sna.getUint16(23, true);
195 | snapshot.registers['PC'] = sna.getUint16(49179, true);
196 | snapshot.ulaState.pagingFlags = sna.getUint8(49181);
197 | }
198 | else {
199 | /* peek memory at SP to get proper value of PC */
200 | let sp = sna.getUint16(23, true);
201 | const l = sna.getUint8(sp - 16384 + 27);
202 | sp = (sp + 1) & 0xffff;
203 | const h = sna.getUint8(sp - 16384 + 27);
204 | sp = (sp + 1) & 0xffff;
205 | snapshot.registers['PC'] = (h << 8) | l;
206 | snapshot.registers['SP'] = sp;
207 | }
208 |
209 | snapshot.registers['im'] = sna.getUint8(25);
210 | snapshot.ulaState.borderColour = sna.getUint8(26);
211 | break;
212 |
213 | default:
214 | throw "Cannot handle SNA snapshots of length " + len;
215 | }
216 |
217 | return snapshot;
218 | }
219 |
220 |
221 | function getSZXIDString(file, offset) {
222 | const dword = file.getUint32(offset, true);
223 | return (
224 | String.fromCharCode(dword & 0xff)
225 | + String.fromCharCode((dword & 0xff00) >> 8)
226 | + String.fromCharCode((dword & 0xff0000) >> 16)
227 | + String.fromCharCode(dword >> 24)
228 | )
229 | }
230 |
231 | export function parseSZXFile(data) {
232 | const file = new DataView(data);
233 | const fileLen = data.byteLength;
234 | const snapshot = {
235 | memoryPages: {},
236 | };
237 |
238 | if (getSZXIDString(file, 0) != 'ZXST') {
239 | throw "Not a valid SZX file";
240 | }
241 |
242 | const machineId = file.getUint8(6);
243 | switch (machineId) {
244 | case 1:
245 | snapshot.model = 48;
246 | break;
247 | case 2:
248 | case 3:
249 | snapshot.model = 128;
250 | break;
251 | case 7:
252 | snapshot.model = 5;
253 | break;
254 | default:
255 | throw "Unsupported machine type: " + machineId;
256 | }
257 |
258 | let offset = 8;
259 | while (offset < fileLen) {
260 | const blockId = getSZXIDString(file, offset);
261 | const blockLen = file.getUint32(offset + 4, true);
262 | offset += 8;
263 |
264 | switch (blockId) {
265 | case 'Z80R':
266 | snapshot.registers = {
267 | 'AF': file.getUint16(offset + 0, true),
268 | 'BC': file.getUint16(offset + 2, true),
269 | 'DE': file.getUint16(offset + 4, true),
270 | 'HL': file.getUint16(offset + 6, true),
271 | 'AF_': file.getUint16(offset + 8, true),
272 | 'BC_': file.getUint16(offset + 10, true),
273 | 'DE_': file.getUint16(offset + 12, true),
274 | 'HL_': file.getUint16(offset + 14, true),
275 | 'IX': file.getUint16(offset + 16, true),
276 | 'IY': file.getUint16(offset + 18, true),
277 | 'SP': file.getUint16(offset + 20, true),
278 | 'PC': file.getUint16(offset + 22, true),
279 | 'IR': file.getUint16(offset + 24, false),
280 | 'iff1': !!file.getUint8(offset + 26),
281 | 'iff2': !!file.getUint8(offset + 27),
282 | 'im': file.getUint8(offset + 28),
283 | };
284 | snapshot.tstates = file.getUint32(offset + 29, true);
285 | snapshot.halted = !!(file.getUint8(offset + 37) & 0x02);
286 | // currently ignored:
287 | // chHoldIntReqCycles, eilast, memptr
288 |
289 | break;
290 | case 'SPCR':
291 | snapshot.ulaState = {
292 | borderColour: file.getUint8(offset + 0),
293 | pagingFlags: file.getUint8(offset + 1),
294 | };
295 | // currently ignored:
296 | // ch1ffd, chEff7, chFe
297 | break;
298 | case 'RAMP':
299 | const isCompressed = file.getUint16(offset + 0, true) & 0x0001;
300 | const pageNumber = file.getUint8(offset + 2);
301 | if (isCompressed) {
302 | const compressedLength = blockLen - 3;
303 | const compressed = new Uint8Array(data, offset + 3, compressedLength);
304 | const pageData = pako.inflate(compressed);
305 | snapshot.memoryPages[pageNumber] = pageData;
306 | } else {
307 | const pageData = new Uint8Array(data, offset + 3, 0x4000);
308 | snapshot.memoryPages[pageNumber] = pageData;
309 | }
310 | break;
311 | // default:
312 | // console.log('skipping block', blockId);
313 | }
314 |
315 | offset += blockLen;
316 | }
317 |
318 | return snapshot;
319 |
320 |
321 | }
322 |
--------------------------------------------------------------------------------
/generator/gencore.js:
--------------------------------------------------------------------------------
1 | import { argv, exit } from 'process';
2 | import * as fs from 'fs';
3 | import * as readline from 'readline';
4 |
5 | import instructionTable from './instructions.js';
6 |
7 | if (argv.length != 4) {
8 | console.log("Usage: node gencore.js path/to/input.ts.in path/to/output.ts");
9 | exit(1);
10 | }
11 | const inputFilename = argv[2];
12 | const outputFilename = argv[3];
13 |
14 | const loadOpcodeTable = (filename, table, altTable) => {
15 | for (let line of fs.readFileSync(filename).toString().split("\n")) {
16 | let match = line.match(/^(\w+)\s+(.*)$/);
17 | if (match) {
18 | const code = parseInt(match[1], 16);
19 | const instruction = match[2];
20 | table[code] = instruction;
21 | if (altTable) {
22 | const altInstruction = (
23 | instruction.replaceAll(/\bIX\b/g, 'IY')
24 | .replaceAll(/\bIXH\b/g, 'IYH')
25 | .replaceAll(/\bIXL\b/g, 'IYL')
26 | .replaceAll(/prefix ddcb/g, 'prefix fdcb')
27 | );
28 | altTable[code] = altInstruction;
29 | }
30 | }
31 | }
32 | }
33 |
34 | const baseOpcodes = {};
35 | loadOpcodeTable('generator/opcodes_base.txt', baseOpcodes);
36 | const cbOpcodes = {};
37 | loadOpcodeTable('generator/opcodes_cb.txt', cbOpcodes);
38 | const ddOpcodes = {};
39 | const fdOpcodes = {};
40 | loadOpcodeTable('generator/opcodes_dd.txt', ddOpcodes, fdOpcodes);
41 | const ddcbOpcodes = {};
42 | const fdcbOpcodes = {};
43 | loadOpcodeTable('generator/opcodes_ddcb.txt', ddcbOpcodes, fdcbOpcodes);
44 | const edOpcodes = {};
45 | loadOpcodeTable('generator/opcodes_ed.txt', edOpcodes);
46 |
47 | class Variable {
48 | getter() {
49 | throw "getter not implemented";
50 | }
51 | setter(expr) {
52 | throw "setter not implemented";
53 | }
54 | arrayGetter(index) {
55 | throw "arrayGetter not implemented";
56 | }
57 | arraySetter(index, expr) {
58 | throw "arraySetter not implemented";
59 | }
60 | }
61 |
62 | class Constant extends Variable {
63 | constructor(expr) {
64 | super();
65 | this.expr = expr;
66 | }
67 | getter() {
68 | return parseExpression(this.expr);
69 | }
70 | }
71 |
72 | class PointerVariable extends Variable {
73 | constructor(address, type) {
74 | super();
75 | this.address = address;
76 | this.type = type;
77 | }
78 | getter() {
79 | return `load<${this.type}>(${this.address})`;
80 | }
81 | setter(expr) {
82 | return `store<${this.type}>(${this.address}, (${parseExpression(expr)}));`;
83 | }
84 | }
85 |
86 | class ArrayVariable extends Variable {
87 | constructor(address, type) {
88 | super();
89 | this.address = address;
90 | this.type = type;
91 | this.typeSize = TYPE_SIZES[type];
92 | }
93 | arrayGetter(index) {
94 | if (this.typeSize == 1) {
95 | return `load<${this.type}>(${this.address} + (${parseExpression(index)}))`;
96 | } else {
97 | return `load<${this.type}>(${this.address} + ${this.typeSize} * (${parseExpression(index)}))`;
98 | }
99 | }
100 | arraySetter(index, expr) {
101 | if (this.typeSize == 1) {
102 | return `store<${this.type}>(${this.address} + (${parseExpression(index)}), (${parseExpression(expr)}));`;
103 | } else {
104 | return `store<${this.type}>(${this.address} + ${this.typeSize} * (${parseExpression(index)}), (${parseExpression(expr)}));`;
105 | }
106 | }
107 | setter(expr) {
108 | let match = expr.match(/^\s*\[([^\]]*)\]\s*$/);
109 | if (!match) {
110 | throw "bad array assignment: " + expr;
111 | }
112 | let result = '';
113 | match[1].split(/\s*\,\s*/).forEach((element, i) => {
114 | result += `store<${this.type}>(${this.address + i * this.typeSize}, ${parseExpression(element)});\n`
115 | });
116 | return result;
117 | }
118 | }
119 |
120 | /* Memory allocations */
121 | const TYPE_SIZES = {
122 | 'bool': 1,
123 | 'u8': 1,
124 | 'u16': 2,
125 | 'u32': 4,
126 | 'f32': 4,
127 | }
128 | let mem = 0;
129 | const vars = {};
130 |
131 | const allocateArray = (varName, type, count) => {
132 | const len = TYPE_SIZES[type] * count;
133 | vars[varName] = new ArrayVariable(mem, type);
134 | mem += len;
135 | }
136 | const allocateRegisterPair = (pair, hi, lo) => {
137 | vars[pair] = new PointerVariable(mem, 'u16');
138 | if (lo) vars[lo] = new PointerVariable(mem, 'u8');
139 | if (hi) vars[hi] = new PointerVariable(mem + 1, 'u8');
140 | mem += 2;
141 | }
142 | const defineConstant = (varName, val) => {
143 | vars[varName] = new Constant(val);
144 | }
145 |
146 | const parseExpression = (expr) => {
147 | /* array accesses: foo[x] */
148 | expr = expr.replaceAll(
149 | /(\w+)\s*\[([^\]]+)\]/g,
150 | (str, varName, index) => {
151 | if (varName in vars) {
152 | return vars[varName].arrayGetter(index);
153 | } else {
154 | return str;
155 | }
156 | }
157 | );
158 |
159 | /* address getting: (&foo) - note that parentheses are required */
160 | expr = expr.replaceAll(
161 | /\(\&(\w+)\)/g,
162 | (str, varName) => varName in vars ? vars[varName].address : varName
163 | );
164 |
165 | /* plain variable accesses: foo */
166 | expr = expr.replaceAll(
167 | /\w+/g,
168 | varName => varName in vars ? vars[varName].getter() : varName
169 | );
170 | return expr;
171 | }
172 |
173 | const generateOpcode = (code, instruction, outFile) => {
174 | let exactMatchFunc = null;
175 | let fuzzyMatchFunc = null;
176 | let fuzzyMatchArgs = null;
177 |
178 | /* check every instruction in the table for a match */
179 | for (let [candidate, func] of Object.entries(instructionTable)) {
180 | if (candidate == instruction) {
181 | exactMatchFunc = func;
182 | break;
183 | } else {
184 | /*
185 | look for a fuzzy match - e.g. ADD A,r for ADD A,B.
186 | Split candidate and target instruction into tokens by word break;
187 | a fuzzy match succeeds if both are the same length, and each token either:
188 | - matches exactly, or
189 | - is a placeholder that's valid for the target instruction
190 | ('r' is valid for any of ABCDEHL; 'rr' is valid for BC, DE, HL, SP),
191 | in which case the token in the target is stored to be passed as a parameter.
192 | */
193 | const instructionTokens = instruction.split(/[\s,]/);
194 | const candidateTokens = candidate.split(/[\s,]/);
195 | let fuzzyMatchOk = true;
196 | let args = [];
197 | if (instructionTokens.length != candidateTokens.length) {
198 | fuzzyMatchOk = false;
199 | } else {
200 | for (let i = 0; i < instructionTokens.length; i++) {
201 | const instructionToken = instructionTokens[i];
202 | const candidateToken = candidateTokens[i];
203 | if (candidateToken == 'r' && instructionToken.match(/^([ABCDEHL]|I[XY][HL])$/)) {
204 | args.push(instructionToken);
205 | } else if (candidateToken == 'rr' && instructionToken.match(/^(AF|BC|DE|HL|IX|IY|SP)$/)) {
206 | args.push(instructionToken);
207 | } else if (candidateToken == 'c' && instructionToken.match(/^(C|NC|Z|NZ|PO|PE|P|M)$/)) {
208 | args.push(instructionToken);
209 | } else if (candidateToken == 'v' && instructionToken.match(/^([ABCDEHL]|I[XY][HL]|\(HL\)|\(I[XY]\+n\)|\(I[XY]\+n\>[ABCDEHL]\)|n)$/)) {
210 | args.push(instructionToken);
211 | } else if (candidateToken == 'k' && instructionToken.match(/^[0123456789abcdefx]+$/)) {
212 | args.push(parseInt(instructionToken));
213 | } else if (candidateToken != instructionToken) {
214 | fuzzyMatchOk = false;
215 | break;
216 | }
217 | }
218 | }
219 | if (fuzzyMatchOk) {
220 | fuzzyMatchFunc = func;
221 | fuzzyMatchArgs = args;
222 | }
223 | }
224 | }
225 | let impl;
226 | if (exactMatchFunc) {
227 | impl = exactMatchFunc();
228 | } else if (fuzzyMatchFunc) {
229 | impl = fuzzyMatchFunc(...fuzzyMatchArgs);
230 | } else {
231 | throw("Unmatched instruction: " + instruction);
232 | }
233 |
234 | outFile.write(`
235 | case 0x${code.toString(16)}: /* ${instruction} */
236 | `)
237 | for (const implLine of impl.split(/\n/)) {
238 | processLine(implLine);
239 | }
240 | outFile.write(`
241 | break;
242 | `)
243 | }
244 |
245 | const generateOpcodeTable = (prefix, outFile) => {
246 | if (prefix == 'base') {
247 | for (let i = 0; i < 0x100; i++) {
248 | generateOpcode(i, baseOpcodes[i], outFile);
249 | }
250 | } else if (prefix == 'cb') {
251 | for (let i = 0; i < 0x100; i++) {
252 | generateOpcode(i, cbOpcodes[i], outFile);
253 | }
254 | } else if (prefix == 'dd') {
255 | for (let i = 0; i < 0x100; i++) {
256 | if (i in ddOpcodes) {
257 | generateOpcode(i, ddOpcodes[i], outFile);
258 | } else {
259 | generateOpcode(i, baseOpcodes[i], outFile);
260 | }
261 | }
262 | } else if (prefix == 'ddcb') {
263 | for (let i = 0; i < 0x100; i++) {
264 | generateOpcode(i, ddcbOpcodes[i], outFile);
265 | }
266 | } else if (prefix == 'ed') {
267 | for (let i = 0; i < 0x100; i++) {
268 | if (i in edOpcodes) {
269 | generateOpcode(i, edOpcodes[i], outFile);
270 | } else {
271 | generateOpcode(i, 'NOP', outFile);
272 | }
273 | }
274 | } else if (prefix == 'fd') {
275 | for (let i = 0; i < 0x100; i++) {
276 | if (i in fdOpcodes) {
277 | generateOpcode(i, fdOpcodes[i], outFile);
278 | } else {
279 | generateOpcode(i, baseOpcodes[i], outFile);
280 | }
281 | }
282 | } else if (prefix == 'fdcb') {
283 | for (let i = 0; i < 0x100; i++) {
284 | generateOpcode(i, fdcbOpcodes[i], outFile);
285 | }
286 | } else {
287 | throw("unknown opcode table prefix: " + prefix);
288 | }
289 | }
290 |
291 | const inFile = fs.createReadStream(inputFilename);
292 | const outFile = fs.createWriteStream(outputFilename);
293 |
294 | const processLine = (line) => {
295 | if (line.startsWith('#')) {
296 | let match;
297 | match = line.match(/^#alloc\s+(\w+)\s*\[\s*(\w+)\s*\]\s*:\s*(\w+)\s*$/);
298 | if (match) {
299 | const varName = match[1];
300 | const len = parseInt(match[2]);
301 | const type = match[3];
302 | allocateArray(varName, type, len);
303 | return;
304 | }
305 | match = line.match(/^#const\s+(\w+)\s+(.+)$/);
306 | if (match) {
307 | const varName = match[1];
308 | const expr = match[2];
309 | defineConstant(varName, expr);
310 | return;
311 | }
312 | match = line.match(/^#regpair\s+(\w+)\s+(\w+)\s+(\w+)\s*$/);
313 | if (match) {
314 | const pair = match[1];
315 | const hi = match[2];
316 | const lo = match[3];
317 | allocateRegisterPair(pair, hi, lo);
318 | return;
319 | }
320 | match = line.match(/^#regpair\s+(\w+)\s*$/);
321 | if (match) {
322 | const pair = match[1];
323 | allocateRegisterPair(pair);
324 | return;
325 | }
326 | throw "Unrecognised directive: " + line;
327 | } else {
328 | let match;
329 |
330 | /* opcode table */
331 | match = line.match(/^\s*#optable\s+(\w+)$/);
332 | if (match) {
333 | let prefix = match[1];
334 | generateOpcodeTable(prefix, outFile);
335 | return;
336 | }
337 |
338 | /* opcode case */
339 | match = line.match(/^\s*#op\s+(\w+)\s+(.*)$/);
340 | if (match) {
341 | let code = parseInt(match[1], 16);
342 | let instruction = match[2].trim();
343 |
344 | generateOpcode(code, instruction, outFile);
345 | return;
346 | }
347 |
348 | /* array assignment */
349 | match = line.match(/^\s*(\w+)\s*\[([^\]]+)\]\s*(\|\=|\=)\s*(.*);/);
350 | if (match && match[1] in vars) {
351 | let variable = vars[match[1]];
352 | let index = match[2];
353 | let operator = match[3];
354 | let expr = match[4];
355 | if (operator == '=') {
356 | outFile.write(variable.arraySetter(index, expr) + "\n");
357 | } else if (operator == '|=') {
358 | outFile.write(
359 | variable.arraySetter(
360 | index,
361 | `${variable.arrayGetter(index)} | (${expr})`
362 | ) + "\n"
363 | );
364 | } else {
365 | throw "unknown operator " + operator
366 | }
367 | return;
368 | }
369 |
370 | /* var assignment */
371 | match = line.match(/^\s*(\w+)\s*=\s*(.*);/);
372 | if (match && match[1] in vars) {
373 | let variable = vars[match[1]];
374 | let expr = parseExpression(match[2]);
375 | outFile.write(variable.setter(expr) + "\n");
376 | return;
377 | }
378 |
379 | outFile.write(parseExpression(line) + "\n");
380 | }
381 | }
382 |
383 | const reader = readline.createInterface({input: inFile, crlfDelay: Infinity});
384 | for await (let line of reader) {
385 | processLine(line);
386 | }
387 | inFile.close();
388 | outFile.close();
389 |
390 | /* check that allocated memory fits within the memoryBase set in asconfig.json */
391 | const asconfig = JSON.parse(fs.readFileSync('asconfig.json', {encoding: 'utf-8'}));
392 | console.log('memory allocated:', mem);
393 | console.log('memory available:', asconfig.options.memoryBase);
394 | if (mem > asconfig.options.memoryBase) {
395 | console.log("ERROR: not enough memory allocated in asconfig.json");
396 | exit(1);
397 | }
398 |
--------------------------------------------------------------------------------
/runtime/ui.js:
--------------------------------------------------------------------------------
1 | import EventEmitter from 'events';
2 |
3 | import playIcon from './icons/play.svg';
4 | import closeIcon from './icons/close.svg';
5 |
6 |
7 | export class MenuBar {
8 | constructor(container) {
9 | this.elem = document.createElement('div');
10 | this.elem.style.display = 'flow-root';
11 | this.elem.style.backgroundColor = '#eee';
12 | this.elem.style.fontFamily = 'Arial, Helvetica, sans-serif';
13 | this.elem.style.top = '0';
14 | this.elem.style.width = '100%';
15 | container.appendChild(this.elem);
16 | this.currentMouseenterEvent = null;
17 | this.currentMouseoutEvent = null;
18 | }
19 |
20 | addMenu(title) {
21 | return new Menu(this.elem, title);
22 | }
23 |
24 | enterFullscreen() {
25 | this.elem.style.position = 'absolute';
26 | }
27 | exitFullscreen() {
28 | this.elem.style.position = 'static';
29 | }
30 | show() {
31 | this.elem.style.visibility = 'visible';
32 | }
33 | hide() {
34 | this.elem.style.visibility = 'hidden';
35 | }
36 | onmouseenter(e) {
37 | if (this.currentMouseenterEvent) {
38 | this.elem.removeEventListener('mouseenter', this.currentMouseenterEvent);
39 | }
40 | if (e) {
41 | this.elem.addEventListener('mouseenter', e);
42 | }
43 | this.currentMouseenterEvent = e;
44 | }
45 | onmouseout(e) {
46 | if (this.currentMouseoutEvent) {
47 | this.elem.removeEventListener('mouseleave', this.currentMouseoutEvent);
48 | }
49 | if (e) {
50 | this.elem.addEventListener('mouseleave', e);
51 | }
52 | this.currentMouseoutEvent = e;
53 | }
54 | }
55 |
56 | export class Menu {
57 | constructor(container, title) {
58 | const elem = document.createElement('div');
59 | elem.style.float = 'left';
60 | elem.style.position = 'relative';
61 | container.appendChild(elem);
62 |
63 | const button = document.createElement('button');
64 | button.style.margin = '2px';
65 | button.innerText = title;
66 | elem.appendChild(button);
67 |
68 | this.list = document.createElement('ul');
69 | this.list.style.position = 'absolute';
70 | this.list.style.width = '150px';
71 | this.list.style.backgroundColor = '#eee';
72 | this.list.style.listStyleType = 'none';
73 | this.list.style.margin = '0';
74 | this.list.style.padding = '0';
75 | this.list.style.border = '1px solid #888';
76 | this.list.style.display = 'none';
77 | elem.appendChild(this.list);
78 |
79 | button.addEventListener('click', () => {
80 | if (this.isOpen()) {
81 | this.close();
82 | } else {
83 | this.open();
84 | }
85 | })
86 | document.addEventListener('click', (e) => {
87 | if (e.target != button && this.isOpen()) this.close();
88 | })
89 | }
90 |
91 | isOpen() {
92 | return this.list.style.display == 'block';
93 | }
94 |
95 | open() {
96 | this.list.style.display = 'block';
97 | }
98 |
99 | close() {
100 | this.list.style.display = 'none';
101 | }
102 |
103 | addItem(title, onClick) {
104 | const li = document.createElement('li');
105 | this.list.appendChild(li);
106 | const button = document.createElement('button');
107 | button.innerText = title;
108 | button.style.width = '100%';
109 | button.style.textAlign = 'left';
110 | button.style.borderWidth = '0';
111 | button.style.paddingTop = '4px';
112 | button.style.paddingBottom = '4px';
113 |
114 | // eww.
115 | button.addEventListener('mouseenter', () => {
116 | button.style.backgroundColor = '#ddd';
117 | });
118 | button.addEventListener('mouseout', () => {
119 | button.style.backgroundColor = 'inherit';
120 | });
121 | if (onClick) {
122 | button.addEventListener('click', onClick);
123 | }
124 | li.appendChild(button);
125 | return {
126 | setBullet: () => {
127 | button.innerText = String.fromCharCode(0x2022) + ' ' + title;
128 | },
129 | unsetBullet: () => {
130 | button.innerText = title;
131 | },
132 | setCheckbox: () => {
133 | button.innerText = String.fromCharCode(0x2713) + ' ' + title;
134 | },
135 | unsetCheckbox: () => {
136 | button.innerText = title;
137 | },
138 | }
139 | }
140 | }
141 |
142 | export class Toolbar {
143 | constructor(container) {
144 | this.elem = document.createElement('div');
145 | this.elem.style.backgroundColor = '#ccc';
146 | this.elem.style.bottom = '0';
147 | this.elem.style.width = '100%';
148 | container.appendChild(this.elem);
149 | this.currentMouseenterEvent = null;
150 | this.currentMouseoutEvent = null;
151 | }
152 | addButton(icon, opts, onClick) {
153 | opts = opts || {};
154 | const button = new ToolbarButton(icon, opts, onClick);
155 | if (opts.align == 'right') button.elem.style.float = 'right';
156 | this.elem.appendChild(button.elem);
157 | return button;
158 | }
159 | enterFullscreen() {
160 | this.elem.style.position = 'absolute';
161 | }
162 | exitFullscreen() {
163 | this.elem.style.position = 'static';
164 | }
165 | show() {
166 | this.elem.style.visibility = 'visible';
167 | }
168 | hide() {
169 | this.elem.style.visibility = 'hidden';
170 | }
171 | onmouseenter(e) {
172 | if (this.currentMouseenterEvent) {
173 | this.elem.removeEventListener('mouseenter', this.currentMouseenterEvent);
174 | }
175 | if (e) {
176 | this.elem.addEventListener('mouseenter', e);
177 | }
178 | this.currentMouseenterEvent = e;
179 | }
180 | onmouseout(e) {
181 | if (this.currentMouseoutEvent) {
182 | this.elem.removeEventListener('mouseleave', this.currentMouseoutEvent);
183 | }
184 | if (e) {
185 | this.elem.addEventListener('mouseleave', e);
186 | }
187 | this.currentMouseoutEvent = e;
188 | }
189 | }
190 |
191 | class ToolbarButton {
192 | constructor(icon, opts, onClick) {
193 | this.elem = document.createElement('button');
194 | this.elem.style.margin = '2px';
195 | this.setIcon(icon);
196 | if (opts.label) this.setLabel(opts.label);
197 | this.elem.addEventListener('click', onClick);
198 | }
199 | setIcon(icon) {
200 | this.elem.innerHTML = icon;
201 | this.elem.firstChild.style.height = '20px';
202 | this.elem.firstChild.style.verticalAlign = 'middle';
203 | }
204 | setLabel(label) {
205 | this.elem.title = label;
206 | }
207 | disable() {
208 | this.elem.disabled = true;
209 | this.elem.firstChild.style.opacity = '0.5';
210 | }
211 | enable() {
212 | this.elem.disabled = false;
213 | this.elem.firstChild.style.opacity = '1';
214 | }
215 | }
216 |
217 |
218 | export class UIController extends EventEmitter {
219 | constructor(container, emulator, opts) {
220 | super();
221 | this.canvas = emulator.canvas;
222 | this.uiEnabled = ('uiEnabled' in opts) ? opts.uiEnabled : true;
223 |
224 | /* build UI elements */
225 | if (this.uiEnabled) {
226 | this.dialog = document.createElement('div');
227 | this.dialog.style.display = 'none';
228 | container.appendChild(this.dialog);
229 | const dialogCloseButton = document.createElement('button');
230 | dialogCloseButton.innerHTML = closeIcon;
231 | dialogCloseButton.style.float = 'right';
232 | dialogCloseButton.style.border = 'none';
233 | dialogCloseButton.firstChild.style.height = '20px';
234 | dialogCloseButton.firstChild.style.verticalAlign = 'middle';
235 | this.dialog.appendChild(dialogCloseButton);
236 | dialogCloseButton.addEventListener('click', () => {
237 | this.hideDialog();
238 | })
239 | this.dialogBody = document.createElement('div');
240 | this.dialogBody.style.clear = 'both';
241 | this.dialog.appendChild(this.dialogBody);
242 | }
243 |
244 | this.appContainer = document.createElement('div');
245 | container.appendChild(this.appContainer);
246 | this.appContainer.style.position = 'relative';
247 | this.appContainer.style.outline = 'none';
248 |
249 | if (this.uiEnabled) {
250 | this.menuBar = new MenuBar(this.appContainer);
251 | }
252 | this.appContainer.appendChild(this.canvas);
253 | this.canvas.style.objectFit = 'contain';
254 | this.canvas.style.display = 'block';
255 |
256 | if (this.uiEnabled) {
257 | this.toolbar = new Toolbar(this.appContainer);
258 | }
259 |
260 | this.startButton = document.createElement('button');
261 | this.startButton.innerHTML = playIcon;
262 | this.appContainer.appendChild(this.startButton);
263 | this.startButton.style.position = 'absolute';
264 | this.startButton.style.top = '50%';
265 | this.startButton.style.left = '50%';
266 | this.startButton.style.width = '96px';
267 | this.startButton.style.height = '64px';
268 | this.startButton.style.marginLeft = '-48px';
269 | this.startButton.style.marginTop = '-32px';
270 | this.startButton.style.backgroundColor = 'rgba(160, 160, 160, 0.7)';
271 | this.startButton.style.border = 'none';
272 | this.startButton.style.borderRadius = '4px';
273 | this.startButton.firstChild.style.height = '56px';
274 | this.startButton.firstChild.style.verticalAlign = 'middle';
275 | this.startButton.addEventListener('mouseenter', () => {
276 | this.startButton.style.backgroundColor = 'rgba(128, 128, 128, 0.7)';
277 | });
278 | this.startButton.addEventListener('mouseleave', () => {
279 | this.startButton.style.backgroundColor = 'rgba(160, 160, 160, 0.7)';
280 | });
281 | this.startButton.addEventListener('click', (e) => {
282 | emulator.start();
283 | });
284 | emulator.on('start', () => {
285 | this.startButton.style.display = 'none';
286 | });
287 | emulator.on('pause', () => {
288 | this.startButton.style.display = 'block';
289 | });
290 |
291 | /* variables for tracking zoom / fullscreen state */
292 | this.zoom = null;
293 | this.isFullscreen = false;
294 | this.uiIsHidden = false;
295 | this.allowUIHiding = true;
296 | this.hideUITimeout = null;
297 | this.ignoreNextMouseMove = false;
298 |
299 | /* state changes when entering / exiting fullscreen */
300 | const fullscreenMouseMove = () => {
301 | if (this.ignoreNextMouseMove) {
302 | this.ignoreNextMouseMove = false;
303 | return;
304 | }
305 | this.showUI();
306 | if (this.hideUITimeout) clearTimeout(this.hideUITimeout);
307 | this.hideUITimeout = setTimeout(() => {this.hideUI();}, 3000);
308 | }
309 | this.appContainer.addEventListener('fullscreenchange', () => {
310 | if (document.fullscreenElement) {
311 | this.isFullscreen = true;
312 | this.canvas.style.width = '100%';
313 | this.canvas.style.height = '100%';
314 |
315 | if (this.uiEnabled) {
316 | document.addEventListener('mousemove', fullscreenMouseMove);
317 | /* a bogus mousemove event is emitted on entering fullscreen, so ignore it */
318 | this.ignoreNextMouseMove = true;
319 |
320 | this.menuBar.enterFullscreen();
321 | this.menuBar.onmouseenter(() => {this.allowUIHiding = false;});
322 | this.menuBar.onmouseout(() => {this.allowUIHiding = true;});
323 |
324 | this.toolbar.enterFullscreen();
325 | this.toolbar.onmouseenter(() => {this.allowUIHiding = false;});
326 | this.toolbar.onmouseout(() => {this.allowUIHiding = true;});
327 |
328 | this.hideUI();
329 | }
330 | this.emit('setZoom', 'fullscreen');
331 | emulator.focus();
332 | } else {
333 | this.isFullscreen = false;
334 | if (this.uiEnabled) {
335 | if (this.hideUITimeout) clearTimeout(this.hideUITimeout);
336 | this.showUI();
337 |
338 | this.menuBar.exitFullscreen();
339 | this.menuBar.onmouseenter(null);
340 | this.menuBar.onmouseout(null);
341 |
342 | this.toolbar.exitFullscreen();
343 | this.toolbar.onmouseenter(null);
344 | this.toolbar.onmouseout(null);
345 |
346 | document.removeEventListener('mousemove', fullscreenMouseMove);
347 | }
348 | this.setZoom(this.zoom);
349 | }
350 | })
351 |
352 | this.setZoom(opts.zoom || 1);
353 |
354 | if (!opts.sandbox) {
355 | /* drag-and-drop for loading files */
356 | this.appContainer.addEventListener('drop', (ev) => {
357 | ev.preventDefault();
358 | let loadList = Promise.resolve();
359 | if (ev.dataTransfer.items) {
360 | // Use DataTransferItemList interface to access the file(s)
361 | for (const item of ev.dataTransfer.items) {
362 | // If dropped items aren't files, reject them
363 | if (item.kind === 'file') {
364 | const file = item.getAsFile();
365 | loadList = loadList.then(() => {
366 | emulator.openFile(file);
367 | });
368 | }
369 | }
370 | } else {
371 | // Use DataTransfer interface to access the file(s)
372 | for (const file of ev.dataTransfer.files) {
373 | loadList = loadList.then(() => {
374 | emulator.openFile(file);
375 | });
376 | }
377 | }
378 | loadList.then(() => {
379 | if (emulator.isInitiallyPaused) emulator.start();
380 | })
381 | });
382 | this.appContainer.addEventListener('dragover', (ev) => {
383 | ev.preventDefault();
384 | });
385 | }
386 | }
387 |
388 | setZoom(factor) {
389 | this.zoom = factor;
390 | if (this.isFullscreen) {
391 | document.exitFullscreen();
392 | return; // setZoom will be retriggered once fullscreen has exited
393 | }
394 | const displayWidth = 320 * this.zoom;
395 | const displayHeight = 240 * this.zoom;
396 | this.canvas.style.width = '' + displayWidth + 'px';
397 | this.canvas.style.height = '' + displayHeight + 'px';
398 | this.appContainer.style.width = '' + displayWidth + 'px';
399 | this.emit('setZoom', factor);
400 | }
401 |
402 | enterFullscreen() {
403 | this.appContainer.requestFullscreen();
404 | }
405 | exitFullscreen() {
406 | if (this.isFullscreen) {
407 | document.exitFullscreen();
408 | }
409 | }
410 | toggleFullscreen() {
411 | if (this.isFullscreen) {
412 | this.exitFullscreen();
413 | } else {
414 | this.enterFullscreen();
415 | }
416 | }
417 |
418 | hideUI() {
419 | if (this.uiEnabled && this.allowUIHiding && !this.uiIsHidden) {
420 | this.uiIsHidden = true;
421 | this.appContainer.style.cursor = 'none';
422 | this.menuBar.hide();
423 | this.toolbar.hide();
424 | }
425 | }
426 | showUI() {
427 | if (this.uiEnabled && this.uiIsHidden) {
428 | this.uiIsHidden = false;
429 | this.appContainer.style.cursor = 'default';
430 | this.menuBar.show();
431 | this.toolbar.show();
432 | }
433 | }
434 | showDialog() {
435 | this.dialog.style.display = 'block';
436 | this.dialog.style.position = 'absolute';
437 | this.dialog.style.backgroundColor = '#eee';
438 | this.dialog.style.zIndex = '100';
439 | this.dialog.style.width = '75%';
440 | this.dialog.style.height = '80%';
441 | this.dialog.style.left = '12%';
442 | this.dialog.style.top = '10%';
443 | this.dialog.style.overflow = 'scroll'; // TODO: less hacky scrolling that doesn't hide the close button
444 | this.dialogBody.style.paddingLeft = '8px';
445 | this.dialogBody.style.paddingRight = '8px';
446 | this.dialogBody.style.paddingBottom = '8px';
447 |
448 | return this.dialogBody;
449 | }
450 | hideDialog() {
451 | this.dialog.style.display = 'none';
452 | this.dialogBody.innerHTML = '';
453 | }
454 | unload() {
455 | if (this.uiEnabled) {
456 | this.dialog.remove();
457 | }
458 | this.appContainer.remove();
459 | }
460 | }
461 |
--------------------------------------------------------------------------------
/runtime/tape.js:
--------------------------------------------------------------------------------
1 | class ToneSegment {
2 | constructor(pulseLength, pulseCount) {
3 | this.pulseLength = pulseLength;
4 | this.pulseCount = pulseCount;
5 | this.pulsesGenerated = 0;
6 | }
7 | isFinished() {
8 | return this.pulsesGenerated == this.pulseCount;
9 | }
10 | getNextPulseLength() {
11 | this.pulsesGenerated++;
12 | return this.pulseLength;
13 | }
14 | }
15 |
16 | class PulseSequenceSegment {
17 | constructor(pulses) {
18 | this.pulses = pulses;
19 | this.index = 0;
20 | }
21 | isFinished() {
22 | return this.index == this.pulses.length;
23 | }
24 | getNextPulseLength() {
25 | return this.pulses[this.index++];
26 | }
27 | }
28 |
29 | class DataSegment {
30 | constructor(data, zeroPulseLength, onePulseLength, lastByteBits) {
31 | this.data = data;
32 | this.zeroPulseLength = zeroPulseLength;
33 | this.onePulseLength = onePulseLength;
34 | this.bitCount = (this.data.length - 1) * 8 + lastByteBits;
35 | this.pulsesOutput = 0;
36 | this.lastPulseLength = null;
37 | }
38 | isFinished() {
39 | return this.pulsesOutput == this.bitCount * 2;
40 | }
41 | getNextPulseLength() {
42 | if (this.pulsesOutput & 0x01) {
43 | this.pulsesOutput++;
44 | return this.lastPulseLength;
45 | } else {
46 | const bitIndex = this.pulsesOutput >> 1;
47 | const byteIndex = bitIndex >> 3;
48 | const bitMask = 1 << (7 - (bitIndex & 0x07));
49 | this.lastPulseLength = (this.data[byteIndex] & bitMask) ? this.onePulseLength : this.zeroPulseLength;
50 | this.pulsesOutput++;
51 | return this.lastPulseLength;
52 | }
53 | }
54 | }
55 |
56 | class PauseSegment {
57 | constructor(duration) {
58 | this.duration = duration;
59 | this.emitted = false;
60 | }
61 | isFinished() {
62 | return this.emitted;
63 | }
64 | getNextPulseLength() {
65 | // TODO: take level back down to 0 after 1ms if it's currently high
66 | this.emitted = true;
67 | return this.duration * 3500;
68 | }
69 | }
70 |
71 | class PulseGenerator {
72 | constructor(getSegments) {
73 | this.segments = [];
74 | this.getSegments = getSegments;
75 | this.level = 0x0000;
76 | this.tapeIsFinished = false; // if true, don't call getSegments again
77 | this.pendingCycles = 0;
78 | }
79 | addSegment(segment) {
80 | this.segments.push(segment);
81 | }
82 | emitPulses(buffer, startIndex, cycleCount) {
83 | let cyclesEmitted = 0;
84 | let index = startIndex;
85 | let isFinished = false;
86 | while (cyclesEmitted < cycleCount) {
87 | if (this.pendingCycles > 0) {
88 | if (this.pendingCycles >= 0x8000) {
89 | // emit a pulse of length 0x7fff
90 | buffer[index++] = this.level | 0x7fff;
91 | cyclesEmitted += 0x7fff;
92 | this.pendingCycles -= 0x7fff;
93 | } else {
94 | // emit a the remainder of this pulse in full
95 | buffer[index++] = this.level | this.pendingCycles;
96 | cyclesEmitted += this.pendingCycles;
97 | this.pendingCycles = 0;
98 | }
99 | } else if (this.segments.length === 0) {
100 | if (this.tapeIsFinished) {
101 | // mark end of tape
102 | isFinished = true;
103 | break;
104 | } else {
105 | // get more segments
106 | this.tapeIsFinished = !this.getSegments(this);
107 | }
108 | } else if (this.segments[0].isFinished()) {
109 | // discard finished segment
110 | this.segments.shift();
111 | } else {
112 | // new pulse
113 | this.pendingCycles = this.segments[0].getNextPulseLength();
114 | this.level ^= 0x8000;
115 | }
116 | }
117 | return [index, cyclesEmitted, isFinished];
118 | }
119 | }
120 |
121 | export class TAPFile {
122 | constructor(data) {
123 | let i = 0;
124 | this.blocks = [];
125 | var tap = new DataView(data);
126 |
127 | while ((i+1) < data.byteLength) {
128 | const blockLength = tap.getUint16(i, true);
129 | i += 2;
130 | this.blocks.push(new Uint8Array(data, i, blockLength));
131 | i += blockLength;
132 | }
133 |
134 | this.nextBlockIndex = 0;
135 |
136 | this.pulseGenerator = new PulseGenerator((generator) => {
137 | if (this.blocks.length === 0) return false;
138 | const block = this.blocks[this.nextBlockIndex];
139 | this.nextBlockIndex = (this.nextBlockIndex + 1) % this.blocks.length;
140 |
141 | if (block[0] & 0x80) {
142 | // add short leader tone for data block
143 | generator.addSegment(new ToneSegment(2168, 3223));
144 | } else {
145 | // add long leader tone for header block
146 | generator.addSegment(new ToneSegment(2168, 8063));
147 | }
148 | generator.addSegment(new PulseSequenceSegment([667, 735]));
149 | generator.addSegment(new DataSegment(block, 855, 1710, 8));
150 | generator.addSegment(new PauseSegment(1000));
151 |
152 | // return false if tape has ended
153 | return this.nextBlockIndex != 0;
154 | });
155 | }
156 |
157 | getNextLoadableBlock() {
158 | if (this.blocks.length === 0) return null;
159 | const block = this.blocks[this.nextBlockIndex];
160 | this.nextBlockIndex = (this.nextBlockIndex + 1) % this.blocks.length;
161 | return block;
162 | }
163 |
164 | static isValid(data) {
165 | /* test whether the given ArrayBuffer is a valid TAP file, i.e. EOF is consistent with the
166 | block lengths we read from the file */
167 | let pos = 0;
168 | const tap = new DataView(data);
169 |
170 | while (pos < data.byteLength) {
171 | if (pos + 1 >= data.byteLength) return false; /* EOF in the middle of a length word */
172 | const blockLength = tap.getUint16(pos, true);
173 | pos += blockLength + 2;
174 | }
175 |
176 | return (pos == data.byteLength); /* file is a valid TAP if pos is exactly at EOF and no further */
177 | }
178 | };
179 |
180 |
181 | export class TZXFile {
182 | static isValid(data) {
183 | const tzx = new DataView(data);
184 |
185 | const signature = "ZXTape!\x1A";
186 | for (let i = 0; i < signature.length; i++) {
187 | if (signature.charCodeAt(i) != tzx.getUint8(i)) {
188 | return false;
189 | }
190 | }
191 | return true;
192 | }
193 |
194 | constructor(data) {
195 | this.blocks = [];
196 | const tzx = new DataView(data);
197 |
198 | let offset = 0x0a;
199 |
200 | while (offset < data.byteLength) {
201 | const blockType = tzx.getUint8(offset);
202 | offset++;
203 | switch (blockType) {
204 | case 0x10:
205 | (() => {
206 | const pause = tzx.getUint16(offset, true);
207 | offset += 2;
208 | const dataLength = tzx.getUint16(offset, true);
209 | offset += 2;
210 | const blockData = new Uint8Array(data, offset, dataLength);
211 | this.blocks.push({
212 | 'type': 'StandardSpeedData',
213 | 'pause': pause,
214 | 'data': blockData,
215 | 'generatePulses': (generator) => {
216 | if (blockData[0] & 0x80) {
217 | // add short leader tone for data block
218 | generator.addSegment(new ToneSegment(2168, 3223));
219 | } else {
220 | // add long leader tone for header block
221 | generator.addSegment(new ToneSegment(2168, 8063));
222 | }
223 | generator.addSegment(new PulseSequenceSegment([667, 735]));
224 | generator.addSegment(new DataSegment(blockData, 855, 1710, 8));
225 | if (pause) generator.addSegment(new PauseSegment(pause));
226 | }
227 | });
228 | offset += dataLength;
229 | })();
230 | break;
231 | case 0x11:
232 | (() => {
233 | const pilotPulseLength = tzx.getUint16(offset, true); offset += 2;
234 | const syncPulse1Length = tzx.getUint16(offset, true); offset += 2;
235 | const syncPulse2Length = tzx.getUint16(offset, true); offset += 2;
236 | const zeroBitLength = tzx.getUint16(offset, true); offset += 2;
237 | const oneBitLength = tzx.getUint16(offset, true); offset += 2;
238 | const pilotPulseCount = tzx.getUint16(offset, true); offset += 2;
239 | const lastByteMask = tzx.getUint8(offset); offset += 1;
240 | const pause = tzx.getUint16(offset, true); offset += 2;
241 | const dataLength = tzx.getUint16(offset, true) | (tzx.getUint8(offset+2) << 16); offset += 3;
242 | const blockData = new Uint8Array(data, offset, dataLength);
243 | this.blocks.push({
244 | 'type': 'TurboSpeedData',
245 | 'pilotPulseLength': pilotPulseLength,
246 | 'syncPulse1Length': syncPulse1Length,
247 | 'syncPulse2Length': syncPulse2Length,
248 | 'zeroBitLength': zeroBitLength,
249 | 'oneBitLength': oneBitLength,
250 | 'pilotPulseCount': pilotPulseCount,
251 | 'lastByteMask': lastByteMask,
252 | 'pause': pause,
253 | 'data': blockData,
254 | 'generatePulses': (generator) => {
255 | generator.addSegment(new ToneSegment(pilotPulseLength, pilotPulseCount));
256 | generator.addSegment(new PulseSequenceSegment([syncPulse1Length, syncPulse2Length]));
257 | generator.addSegment(new DataSegment(blockData, zeroBitLength, oneBitLength, lastByteMask));
258 | if (pause) generator.addSegment(new PauseSegment(pause));
259 | }
260 | });
261 | offset += dataLength;
262 | })();
263 | break;
264 | case 0x12:
265 | (() => {
266 | const pulseLength = tzx.getUint16(offset, true); offset += 2;
267 | const pulseCount = tzx.getUint16(offset, true); offset += 2;
268 | this.blocks.push({
269 | 'type': 'PureTone',
270 | 'pulseLength': pulseLength,
271 | 'pulseCount': pulseCount,
272 | 'generatePulses': (generator) => {
273 | generator.addSegment(new ToneSegment(pulseLength, pulseCount));
274 | }
275 | });
276 | })();
277 | break;
278 | case 0x13:
279 | (() => {
280 | const pulseCount = tzx.getUint8(offset); offset += 1;
281 | const pulseLengths = [];
282 | for (let i = 0; i < pulseCount; i++) {
283 | pulseLengths[i] = tzx.getUint16(offset + i*2, true);
284 | }
285 | this.blocks.push({
286 | 'type': 'PulseSequence',
287 | 'pulseLengths': pulseLengths,
288 | 'generatePulses': (generator) => {
289 | generator.addSegment(new PulseSequenceSegment(pulseLengths));
290 | }
291 | });
292 | offset += (pulseCount * 2);
293 | })();
294 | break;
295 | case 0x14:
296 | (() => {
297 | const zeroBitLength = tzx.getUint16(offset, true); offset += 2;
298 | const oneBitLength = tzx.getUint16(offset, true); offset += 2;
299 | const lastByteMask = tzx.getUint8(offset); offset += 1;
300 | const pause = tzx.getUint16(offset, true); offset += 2;
301 | const dataLength = tzx.getUint16(offset, true) | (tzx.getUint8(offset+2) << 16); offset += 3;
302 | const blockData = new Uint8Array(data, offset, dataLength);
303 | this.blocks.push({
304 | 'type': 'PureData',
305 | 'zeroBitLength': zeroBitLength,
306 | 'oneBitLength': oneBitLength,
307 | 'lastByteMask': lastByteMask,
308 | 'pause': pause,
309 | 'data': blockData,
310 | 'generatePulses': (generator) => {
311 | generator.addSegment(new DataSegment(blockData, zeroBitLength, oneBitLength, lastByteMask));
312 | if (pause) generator.addSegment(new PauseSegment(pause));
313 | }
314 | });
315 | offset += dataLength;
316 | })();
317 | break;
318 | case 0x15:
319 | (() => {
320 | const tstatesPerSample = tzx.getUint16(offset, true); offset += 2;
321 | const pause = tzx.getUint16(offset, true); offset += 2;
322 | const lastByteMask = tzx.getUint8(offset); offset += 1;
323 | const dataLength = tzx.getUint16(offset, true) | (tzx.getUint8(offset+2) << 16); offset += 3;
324 | this.blocks.push({
325 | 'type': 'DirectRecording',
326 | 'tstatesPerSample': tstatesPerSample,
327 | 'lastByteMask': lastByteMask,
328 | 'pause': pause,
329 | 'data': new Uint8Array(data, offset, dataLength)
330 | });
331 | offset += dataLength;
332 | })();
333 | break;
334 | case 0x20:
335 | (() => {
336 | // TODO: handle pause length of 0 (= stop tape)
337 | const pause = tzx.getUint16(offset, true); offset += 2;
338 | this.blocks.push({
339 | 'type': 'Pause',
340 | 'pause': pause,
341 | 'generatePulses': (generator) => {
342 | generator.addSegment(new PauseSegment(pause));
343 | }
344 | });
345 | })();
346 | break;
347 | case 0x21:
348 | (() => {
349 | const nameLength = tzx.getUint8(offset); offset += 1;
350 | const nameBytes = new Uint8Array(data, offset, nameLength);
351 | offset += nameLength;
352 | const name = String.fromCharCode.apply(null, nameBytes);
353 | this.blocks.push({
354 | 'type': 'GroupStart',
355 | 'name': name
356 | });
357 | })();
358 | break;
359 | case 0x22:
360 | (() => {
361 | this.blocks.push({
362 | 'type': 'GroupEnd'
363 | });
364 | })();
365 | break;
366 | case 0x23:
367 | (() => {
368 | const jumpOffset = tzx.getUint16(offset, true); offset += 2;
369 | this.blocks.push({
370 | 'type': 'JumpToBlock',
371 | 'offset': jumpOffset
372 | });
373 | })();
374 | break;
375 | case 0x24:
376 | (() => {
377 | const repeatCount = tzx.getUint16(offset, true); offset += 2;
378 | this.blocks.push({
379 | 'type': 'LoopStart',
380 | 'repeatCount': repeatCount
381 | });
382 | })();
383 | break;
384 | case 0x25:
385 | (() => {
386 | this.blocks.push({
387 | 'type': 'LoopEnd'
388 | });
389 | })();
390 | break;
391 | case 0x26:
392 | (() => {
393 | const callCount = tzx.getUint16(offset, true); offset += 2;
394 | const offsets = [];
395 | for (let i = 0; i < callCount; i++) {
396 | offsets[i] = tzx.getUint16(offset + i*2, true);
397 | }
398 | this.blocks.push({
399 | 'type': 'CallSequence',
400 | 'offsets': offsets
401 | });
402 | offset += (callCount * 2);
403 | })();
404 | break;
405 | case 0x27:
406 | (() => {
407 | this.blocks.push({
408 | 'type': 'ReturnFromSequence'
409 | });
410 | })();
411 | break;
412 | case 0x28:
413 | (() => {
414 | const blockLength = tzx.getUint16(offset, true); offset += 2;
415 | /* This is a silly block. Don't bother parsing it further. */
416 | this.blocks.push({
417 | 'type': 'Select',
418 | 'data': new Uint8Array(data, offset, blockLength)
419 | });
420 | offset += blockLength;
421 | })();
422 | break;
423 | case 0x30:
424 | (() => {
425 | const textLength = tzx.getUint8(offset); offset += 1;
426 | const textBytes = new Uint8Array(data, offset, textLength);
427 | offset += textLength;
428 | const text = String.fromCharCode.apply(null, textBytes);
429 | this.blocks.push({
430 | 'type': 'TextDescription',
431 | 'text': text
432 | });
433 | })();
434 | break;
435 | case 0x31:
436 | (() => {
437 | const displayTime = tzx.getUint8(offset); offset += 1;
438 | const textLength = tzx.getUint8(offset); offset += 1;
439 | const textBytes = new Uint8Array(data, offset, textLength);
440 | offset += textLength;
441 | const text = String.fromCharCode.apply(null, textBytes);
442 | this.blocks.push({
443 | 'type': 'MessageBlock',
444 | 'displayTime': displayTime,
445 | 'text': text
446 | });
447 | })();
448 | break;
449 | case 0x32:
450 | (() => {
451 | const blockLength = tzx.getUint16(offset, true); offset += 2;
452 | this.blocks.push({
453 | 'type': 'ArchiveInfo',
454 | 'data': new Uint8Array(data, offset, blockLength)
455 | });
456 | offset += blockLength;
457 | })();
458 | break;
459 | case 0x33:
460 | (() => {
461 | const blockLength = tzx.getUint8(offset) * 3; offset += 1;
462 | this.blocks.push({
463 | 'type': 'HardwareType',
464 | 'data': new Uint8Array(data, offset, blockLength)
465 | });
466 | offset += blockLength;
467 | })();
468 | break;
469 | case 0x35:
470 | (() => {
471 | const identifierBytes = new Uint8Array(data, offset, 10);
472 | offset += 10;
473 | const identifier = String.fromCharCode.apply(null, identifierBytes);
474 | const dataLength = tzx.getUint32(offset, true);
475 | this.blocks.push({
476 | 'type': 'CustomInfo',
477 | 'identifier': identifier,
478 | 'data': new Uint8Array(data, offset, dataLength)
479 | });
480 | offset += dataLength;
481 | })();
482 | break;
483 | case 0x5A:
484 | (() => {
485 | offset += 9;
486 | this.blocks.push({
487 | 'type': 'Glue'
488 | });
489 | })();
490 | break;
491 | default:
492 | (() => {
493 | /* follow extension rule: next 4 bytes = length of block */
494 | const blockLength = tzx.getUint32(offset, true);
495 | offset += 4;
496 | this.blocks.push({
497 | 'type': 'unknown',
498 | 'data': new Uint8Array(data, offset, blockLength)
499 | });
500 | offset += blockLength;
501 | })();
502 | }
503 | }
504 |
505 | this.nextBlockIndex = 0;
506 | this.loopToBlockIndex;
507 | this.repeatCount;
508 | this.callStack = [];
509 |
510 | this.pulseGenerator = new PulseGenerator((generator) => {
511 | const block = this.getNextMeaningfulBlock(false);
512 | if (!block) return false;
513 | block.generatePulses(generator);
514 | return true;
515 | });
516 | }
517 |
518 | getNextMeaningfulBlock(wrapAtEnd) {
519 | let startedAtZero = (this.nextBlockIndex === 0);
520 | while (true) {
521 | if (this.nextBlockIndex >= this.blocks.length) {
522 | if (startedAtZero || !wrapAtEnd) return null; /* have looped around; quit now */
523 | this.nextBlockIndex = 0;
524 | startedAtZero = true;
525 | }
526 | var block = this.blocks[this.nextBlockIndex];
527 | switch (block.type) {
528 | case 'StandardSpeedData':
529 | case 'TurboSpeedData':
530 | case 'PureTone':
531 | case 'PulseSequence':
532 | case 'PureData':
533 | case 'DirectRecording':
534 | case 'Pause':
535 | /* found a meaningful block */
536 | this.nextBlockIndex++;
537 | return block;
538 | case 'JumpToBlock':
539 | this.nextBlockIndex += block.offset;
540 | break;
541 | case 'LoopStart':
542 | this.loopToBlockIndex = this.nextBlockIndex + 1;
543 | this.repeatCount = block.repeatCount;
544 | this.nextBlockIndex++;
545 | break;
546 | case 'LoopEnd':
547 | this.repeatCount--;
548 | if (this.repeatCount > 0) {
549 | this.nextBlockIndex = this.loopToBlockIndex;
550 | } else {
551 | this.nextBlockIndex++;
552 | }
553 | break;
554 | case 'CallSequence':
555 | /* push the future destinations (where to go on reaching a ReturnFromSequence block)
556 | onto the call stack in reverse order, starting with the block immediately
557 | after the CallSequence (which we go to when leaving the sequence) */
558 | this.callStack.unshift(this.nextBlockIndex+1);
559 | for (var i = block.offsets.length - 1; i >= 0; i--) {
560 | this.callStack.unshift(this.nextBlockIndex + block.offsets[i]);
561 | }
562 | /* now visit the first destination on the list */
563 | this.nextBlockIndex = this.callStack.shift();
564 | break;
565 | case 'ReturnFromSequence':
566 | this.nextBlockIndex = this.callStack.shift();
567 | break;
568 | default:
569 | /* not one of the types we care about; skip past it */
570 | this.nextBlockIndex++;
571 | }
572 | }
573 | }
574 |
575 | getNextLoadableBlock() {
576 | while (true) {
577 | var block = this.getNextMeaningfulBlock(true);
578 | if (!block) return null;
579 | if (block.type == 'StandardSpeedData' || block.type == 'TurboSpeedData') {
580 | return block.data;
581 | }
582 | /* FIXME: avoid infinite loop if the TZX file consists only of meaningful but non-loadable blocks */
583 | }
584 | }
585 | };
586 |
--------------------------------------------------------------------------------
/runtime/jsspeccy.js:
--------------------------------------------------------------------------------
1 | import EventEmitter from 'events';
2 | import fileDialog from 'file-dialog';
3 | import JSZip from 'jszip';
4 |
5 | import { DisplayHandler } from './render.js';
6 | import { UIController } from './ui.js';
7 | import { parseSNAFile, parseZ80File, parseSZXFile } from './snapshot.js';
8 | import { TAPFile, TZXFile } from './tape.js';
9 | import { StandardKeyboardHandler, RecreatedZXSpectrumHandler } from './keyboard.js';
10 | import { AudioHandler } from './audio.js';
11 |
12 | import openIcon from './icons/open.svg';
13 | import resetIcon from './icons/reset.svg';
14 | import playIcon from './icons/play.svg';
15 | import pauseIcon from './icons/pause.svg';
16 | import fullscreenIcon from './icons/fullscreen.svg';
17 | import exitFullscreenIcon from './icons/exitfullscreen.svg';
18 | import tapePlayIcon from './icons/tape_play.svg';
19 | import tapePauseIcon from './icons/tape_pause.svg';
20 |
21 | const scriptUrl = document.currentScript.src;
22 |
23 | class Emulator extends EventEmitter {
24 | constructor(canvas, opts) {
25 | super();
26 | this.canvas = canvas;
27 | this.worker = new Worker(new URL('jsspeccy-worker.js', scriptUrl));
28 | this.keyboardEnabled = ('keyboardEnabled' in opts) ? opts.keyboardEnabled : true;
29 | if (this.keyboardEnabled) {
30 | this.keyboardHandler = (opts.keyboardMap == 'recreated')
31 | ? new RecreatedZXSpectrumHandler(this.worker, opts.keyboardEventRoot || document)
32 | : new StandardKeyboardHandler(this.worker, opts.keyboardEventRoot || document);
33 | }
34 | this.displayHandler = new DisplayHandler(this.canvas);
35 | this.audioHandler = new AudioHandler();
36 | this.isRunning = false;
37 | this.isReady = false;
38 | this.isInitiallyPaused = (!opts.autoStart);
39 | this.autoLoadTapes = opts.autoLoadTapes || false;
40 | this.tapeAutoLoadMode = opts.tapeAutoLoadMode || 'default'; // or usr0
41 | this.tapeIsPlaying = false;
42 | this.tapeTrapsEnabled = ('tapeTrapsEnabled' in opts) ? opts.tapeTrapsEnabled : true;
43 |
44 | this.msPerFrame = 20;
45 |
46 | this.isExecutingFrame = false;
47 | this.nextFrameTime = null;
48 | this.machineType = null;
49 |
50 | this.nextFileOpenID = 0;
51 | this.fileOpenPromiseResolutions = {};
52 |
53 | this.onReadyHandlers = [];
54 |
55 | this.worker.onmessage = (e) => {
56 | switch(e.data.message) {
57 | case 'ready':
58 | this.loadRoms().then(() => {
59 | this.setMachine(opts.machine || 128);
60 | this.setTapeTraps(this.tapeTrapsEnabled);
61 | if (opts.openUrl) {
62 | this.openUrlList(opts.openUrl).catch(err => {
63 | alert(err);
64 | }).then(() => {
65 | if (opts.autoStart) this.start();
66 | });
67 | } else if (opts.autoStart) {
68 | this.start();
69 | }
70 |
71 | this.isReady = true;
72 | for (let i=0; i < this.onReadyHandlers.length; i++) {
73 | this.onReadyHandlers[i]();
74 | }
75 | });
76 | break;
77 | case 'frameCompleted':
78 | // benchmarkRunCount++;
79 | if ('audioBufferLeft' in e.data) {
80 | this.audioHandler.frameCompleted(e.data.audioBufferLeft, e.data.audioBufferRight);
81 | }
82 |
83 | this.displayHandler.frameCompleted(e.data.frameBuffer);
84 | if (this.isRunning) {
85 | const time = performance.now();
86 | if (time > this.nextFrameTime) {
87 | /* running at full blast - start next frame but adjust time base
88 | to give it the full time allocation */
89 | this.runFrame();
90 | this.nextFrameTime = time + this.msPerFrame;
91 | } else {
92 | this.isExecutingFrame = false;
93 | }
94 | } else {
95 | this.isExecutingFrame = false;
96 | }
97 | break;
98 | case 'fileOpened':
99 | if (e.data.mediaType == 'tape' && this.autoLoadTapes) {
100 | const TAPE_LOADERS_BY_MACHINE = {
101 | '48': {'default': 'tapeloaders/tape_48.szx', 'usr0': 'tapeloaders/tape_48.szx'},
102 | '128': {'default': 'tapeloaders/tape_128.szx', 'usr0': 'tapeloaders/tape_128_usr0.szx'},
103 | '5': {'default': 'tapeloaders/tape_pentagon.szx', 'usr0': 'tapeloaders/tape_pentagon_usr0.szx'},
104 | };
105 | this.openUrl(new URL(TAPE_LOADERS_BY_MACHINE[this.machineType][this.tapeAutoLoadMode], scriptUrl));
106 | if (!this.tapeTrapsEnabled) {
107 | this.playTape();
108 | }
109 | }
110 | this.fileOpenPromiseResolutions[e.data.id]({
111 | mediaType: e.data.mediaType,
112 | });
113 | if (e.data.mediaType == 'tape') {
114 | this.emit('openedTapeFile');
115 | }
116 | break;
117 | case 'playingTape':
118 | this.tapeIsPlaying = true;
119 | this.emit('playingTape');
120 | break;
121 | case 'stoppedTape':
122 | this.tapeIsPlaying = false;
123 | this.emit('stoppedTape');
124 | break;
125 | default:
126 | console.log('message received by host:', e.data);
127 | }
128 | }
129 | this.worker.postMessage({
130 | message: 'loadCore',
131 | baseUrl: scriptUrl,
132 | })
133 | }
134 |
135 | start() {
136 | if (!this.isRunning) {
137 | this.isRunning = true;
138 | this.isInitiallyPaused = false;
139 | this.nextFrameTime = performance.now();
140 | if (this.keyboardEnabled) {
141 | this.keyboardHandler.start();
142 | }
143 | this.audioHandler.start();
144 | this.focus();
145 | this.emit('start');
146 | window.requestAnimationFrame((t) => {
147 | this.runAnimationFrame(t);
148 | });
149 | }
150 | }
151 |
152 | focus() {
153 | if (this.keyboardEnabled && this.keyboardHandler.rootElement.focus) {
154 | this.keyboardHandler.rootElement.focus();
155 | }
156 | }
157 |
158 | setKeyboardEventRoot(newRootElement) {
159 | if (this.keyboardEnabled) {
160 | this.keyboardHandler.setRootElement(newRootElement);
161 | }
162 | }
163 |
164 | pause() {
165 | if (this.isRunning) {
166 | this.isRunning = false;
167 | if (this.keyboardEnabled) {
168 | this.keyboardHandler.stop();
169 | }
170 | this.audioHandler.stop();
171 | this.emit('pause');
172 | }
173 | }
174 |
175 | async loadRom(url, page) {
176 | const response = await fetch(new URL(url, scriptUrl));
177 | const data = new Uint8Array(await response.arrayBuffer());
178 | this.worker.postMessage({
179 | message: 'loadMemory',
180 | data,
181 | page: page,
182 | });
183 | }
184 |
185 | async loadRoms() {
186 | await this.loadRom('roms/128-0.rom', 8);
187 | await this.loadRom('roms/128-1.rom', 9);
188 | await this.loadRom('roms/48.rom', 10);
189 | await this.loadRom('roms/pentagon-0.rom', 12);
190 | await this.loadRom('roms/trdos.rom', 13);
191 | }
192 |
193 |
194 | runFrame() {
195 | this.isExecutingFrame = true;
196 | const frameBuffer = this.displayHandler.getNextFrameBuffer();
197 |
198 | if (this.audioHandler.isActive) {
199 | const [audioBufferLeft, audioBufferRight] = this.audioHandler.frameBuffers;
200 |
201 | this.worker.postMessage({
202 | message: 'runFrame',
203 | frameBuffer,
204 | audioBufferLeft,
205 | audioBufferRight,
206 | }, [frameBuffer, audioBufferLeft, audioBufferRight]);
207 | } else {
208 | this.worker.postMessage({
209 | message: 'runFrame',
210 | frameBuffer,
211 | }, [frameBuffer]);
212 | }
213 | }
214 |
215 | runAnimationFrame(time) {
216 | if (this.displayHandler.readyToShow()) {
217 | this.displayHandler.show();
218 | // benchmarkRenderCount++;
219 | }
220 | if (this.isRunning) {
221 | if (time > this.nextFrameTime && !this.isExecutingFrame) {
222 | this.runFrame();
223 | this.nextFrameTime += this.msPerFrame;
224 | }
225 | window.requestAnimationFrame((t) => {
226 | this.runAnimationFrame(t);
227 | });
228 | }
229 | };
230 |
231 | setMachine(type) {
232 | if (type != 128 && type != 5) type = 48;
233 | this.worker.postMessage({
234 | message: 'setMachineType',
235 | type,
236 | });
237 | this.machineType = type;
238 | this.emit('setMachine', type);
239 | }
240 |
241 | reset() {
242 | this.worker.postMessage({message: 'reset'});
243 | }
244 |
245 | loadSnapshot(snapshot) {
246 | const fileID = this.nextFileOpenID++;
247 | this.worker.postMessage({
248 | message: 'loadSnapshot',
249 | id: fileID,
250 | snapshot,
251 | })
252 | this.emit('setMachine', snapshot.model);
253 | return new Promise((resolve, reject) => {
254 | this.fileOpenPromiseResolutions[fileID] = resolve;
255 | });
256 | }
257 |
258 | openTAPFile(data) {
259 | const fileID = this.nextFileOpenID++;
260 | this.worker.postMessage({
261 | message: 'openTAPFile',
262 | id: fileID,
263 | data,
264 | })
265 | return new Promise((resolve, reject) => {
266 | this.fileOpenPromiseResolutions[fileID] = resolve;
267 | });
268 | }
269 |
270 | openTZXFile(data) {
271 | const fileID = this.nextFileOpenID++;
272 | this.worker.postMessage({
273 | message: 'openTZXFile',
274 | id: fileID,
275 | data,
276 | })
277 | return new Promise((resolve, reject) => {
278 | this.fileOpenPromiseResolutions[fileID] = resolve;
279 | });
280 | }
281 |
282 | getFileOpener(filename) {
283 | const cleanName = filename.toLowerCase();
284 | if (cleanName.endsWith('.z80')) {
285 | return arrayBuffer => {
286 | const z80file = parseZ80File(arrayBuffer);
287 | return this.loadSnapshot(z80file);
288 | };
289 | } else if (cleanName.endsWith('.szx')) {
290 | return arrayBuffer => {
291 | const szxfile = parseSZXFile(arrayBuffer);
292 | return this.loadSnapshot(szxfile);
293 | };
294 | } else if (cleanName.endsWith('.sna')) {
295 | return arrayBuffer => {
296 | const snafile = parseSNAFile(arrayBuffer);
297 | return this.loadSnapshot(snafile);
298 | };
299 | } else if (cleanName.endsWith('.tap')) {
300 | return arrayBuffer => {
301 | if (!TAPFile.isValid(arrayBuffer)) {
302 | alert('Invalid TAP file');
303 | } else {
304 | return this.openTAPFile(arrayBuffer);
305 | }
306 | };
307 | } else if (cleanName.endsWith('.tzx')) {
308 | return arrayBuffer => {
309 | if (!TZXFile.isValid(arrayBuffer)) {
310 | alert('Invalid TZX file');
311 | } else {
312 | return this.openTZXFile(arrayBuffer);
313 | }
314 | };
315 | } else if (cleanName.endsWith('.zip')) {
316 | return async arrayBuffer => {
317 | const zip = await JSZip.loadAsync(arrayBuffer);
318 | const openers = [];
319 | zip.forEach((path, file) => {
320 | if (path.startsWith('__MACOSX/')) return;
321 | const opener = this.getFileOpener(path);
322 | if (opener) {
323 | const boundOpener = async () => {
324 | const buf = await file.async('arraybuffer');
325 | return opener(buf);
326 | };
327 | openers.push(boundOpener);
328 | }
329 | });
330 | if (openers.length == 1) {
331 | return openers[0]();
332 | } else if (openers.length == 0) {
333 | throw 'No loadable files found inside ZIP file: ' + filename;
334 | } else {
335 | // TODO: prompt to choose a file
336 | throw 'Multiple loadable files found inside ZIP file: ' + filename;
337 | }
338 | }
339 | }
340 | }
341 |
342 | async openFile(file) {
343 | const opener = this.getFileOpener(file.name);
344 | if (opener) {
345 | const buf = await file.arrayBuffer();
346 | return opener(buf).catch(err => {alert(err);});
347 | } else {
348 | throw 'Unrecognised file type: ' + file.name;
349 | }
350 | }
351 |
352 | async openUrl(url) {
353 | const opener = this.getFileOpener(url.toString());
354 | if (opener) {
355 | const response = await fetch(url);
356 | const buf = await response.arrayBuffer();
357 | return opener(buf);
358 | } else {
359 | throw 'Unrecognised file type: ' + url.split('/').pop();
360 | }
361 | }
362 | async openUrlList(urls) {
363 | if (typeof(urls) === 'string') {
364 | return await this.openUrl(urls);
365 | } else {
366 | for (const url of urls) {
367 | await this.openUrl(url);
368 | }
369 | }
370 | }
371 |
372 | setAutoLoadTapes(val) {
373 | this.autoLoadTapes = val;
374 | this.emit('setAutoLoadTapes', val);
375 | }
376 | setTapeTraps(val) {
377 | this.tapeTrapsEnabled = val;
378 | this.worker.postMessage({
379 | message: 'setTapeTraps',
380 | value: val,
381 | })
382 | this.emit('setTapeTraps', val);
383 | }
384 |
385 | playTape() {
386 | this.worker.postMessage({
387 | message: 'playTape',
388 | });
389 | }
390 | stopTape() {
391 | this.worker.postMessage({
392 | message: 'stopTape',
393 | });
394 | }
395 |
396 | exit() {
397 | this.pause();
398 | this.worker.terminate();
399 | }
400 | }
401 |
402 | window.JSSpeccy = (container, opts) => {
403 | // let benchmarkRunCount = 0;
404 | // let benchmarkRenderCount = 0;
405 | opts = opts || {};
406 |
407 | const canvas = document.createElement('canvas');
408 | canvas.width = 320;
409 | canvas.height = 240;
410 |
411 | const keyboardEnabled = ('keyboardEnabled' in opts) ? opts.keyboardEnabled : true;
412 | const uiEnabled = ('uiEnabled' in opts) ? opts.uiEnabled : true;
413 |
414 | const emu = new Emulator(canvas, {
415 | machine: opts.machine || 128,
416 | autoStart: opts.autoStart || false,
417 | autoLoadTapes: opts.autoLoadTapes || false,
418 | tapeAutoLoadMode: opts.tapeAutoLoadMode || 'default',
419 | openUrl: opts.openUrl,
420 | tapeTrapsEnabled: ('tapeTrapsEnabled' in opts) ? opts.tapeTrapsEnabled : true,
421 | keyboardEnabled: keyboardEnabled,
422 | keyboardMap: opts.keyboardMap || 'standard',
423 | });
424 | const ui = new UIController(container, emu, {
425 | zoom: opts.zoom || 1,
426 | sandbox: opts.sandbox,
427 | uiEnabled: uiEnabled,
428 | });
429 |
430 | if (keyboardEnabled) {
431 | if (ui.appContainer.tabIndex == -1) {
432 | ui.appContainer.tabIndex = 0; // allow receiving focus for keyboard events
433 | }
434 | emu.setKeyboardEventRoot(ui.appContainer);
435 | }
436 |
437 | if (uiEnabled) {
438 | const fileMenu = ui.menuBar.addMenu('File');
439 | if (!opts.sandbox) {
440 | fileMenu.addItem('Open...', () => {
441 | openFileDialog();
442 | });
443 | fileMenu.addItem('Find games...', () => {
444 | openGameBrowser();
445 | });
446 | const autoLoadTapesMenuItem = fileMenu.addItem('Auto-load tapes', () => {
447 | emu.setAutoLoadTapes(!emu.autoLoadTapes);
448 | emu.focus();
449 | });
450 | const updateAutoLoadTapesCheckbox = () => {
451 | if (emu.autoLoadTapes) {
452 | autoLoadTapesMenuItem.setCheckbox();
453 | } else {
454 | autoLoadTapesMenuItem.unsetCheckbox();
455 | }
456 | }
457 | emu.on('setAutoLoadTapes', updateAutoLoadTapesCheckbox);
458 | updateAutoLoadTapesCheckbox();
459 | }
460 |
461 | const tapeTrapsMenuItem = fileMenu.addItem('Instant tape loading', () => {
462 | emu.setTapeTraps(!emu.tapeTrapsEnabled);
463 | emu.focus();
464 | });
465 |
466 | const updateTapeTrapsCheckbox = () => {
467 | if (emu.tapeTrapsEnabled) {
468 | tapeTrapsMenuItem.setCheckbox();
469 | } else {
470 | tapeTrapsMenuItem.unsetCheckbox();
471 | }
472 | }
473 | emu.on('setTapeTraps', updateTapeTrapsCheckbox);
474 | updateTapeTrapsCheckbox();
475 |
476 | const machineMenu = ui.menuBar.addMenu('Machine');
477 | const machine48Item = machineMenu.addItem('Spectrum 48K', () => {
478 | emu.setMachine(48);
479 | emu.focus();
480 | });
481 | const machine128Item = machineMenu.addItem('Spectrum 128K', () => {
482 | emu.setMachine(128);
483 | emu.focus();
484 | });
485 | const machinePentagonItem = machineMenu.addItem('Pentagon 128', () => {
486 | emu.setMachine(5);
487 | emu.focus();
488 | });
489 | const displayMenu = ui.menuBar.addMenu('Display');
490 |
491 | const zoomItemsBySize = {
492 | 1: displayMenu.addItem('100%', () => {ui.setZoom(1); emu.focus();}),
493 | 2: displayMenu.addItem('200%', () => {ui.setZoom(2); emu.focus();}),
494 | 3: displayMenu.addItem('300%', () => {ui.setZoom(3); emu.focus();}),
495 | }
496 | const fullscreenItem = displayMenu.addItem('Fullscreen', () => {
497 | ui.enterFullscreen();
498 | })
499 | const setZoomCheckbox = (factor) => {
500 | if (factor == 'fullscreen') {
501 | fullscreenItem.setBullet();
502 | for (let i in zoomItemsBySize) {
503 | zoomItemsBySize[i].unsetBullet();
504 | }
505 | } else {
506 | fullscreenItem.unsetBullet();
507 | for (let i in zoomItemsBySize) {
508 | if (parseInt(i) == factor) {
509 | zoomItemsBySize[i].setBullet();
510 | } else {
511 | zoomItemsBySize[i].unsetBullet();
512 | }
513 | }
514 | }
515 | }
516 |
517 | ui.on('setZoom', setZoomCheckbox);
518 | setZoomCheckbox(ui.zoom);
519 |
520 | emu.on('setMachine', (type) => {
521 | if (type == 48) {
522 | machine48Item.setBullet();
523 | machine128Item.unsetBullet();
524 | machinePentagonItem.unsetBullet();
525 | } else if (type == 128) {
526 | machine48Item.unsetBullet();
527 | machine128Item.setBullet();
528 | machinePentagonItem.unsetBullet();
529 | } else { // pentagon
530 | machine48Item.unsetBullet();
531 | machine128Item.unsetBullet();
532 | machinePentagonItem.setBullet();
533 | }
534 | });
535 |
536 | if (!opts.sandbox) {
537 | ui.toolbar.addButton(openIcon, {label: 'Open file'}, () => {
538 | openFileDialog();
539 | });
540 | }
541 | ui.toolbar.addButton(resetIcon, {label: 'Reset'}, () => {
542 | emu.reset();
543 | });
544 | const pauseButton = ui.toolbar.addButton(playIcon, {label: 'Unpause'}, () => {
545 | if (emu.isRunning) {
546 | emu.pause();
547 | } else {
548 | emu.start();
549 | }
550 | });
551 | emu.on('pause', () => {
552 | pauseButton.setIcon(playIcon);
553 | pauseButton.setLabel('Unpause');
554 | });
555 | emu.on('start', () => {
556 | pauseButton.setIcon(pauseIcon);
557 | pauseButton.setLabel('Pause');
558 | });
559 | const tapeButton = ui.toolbar.addButton(tapePlayIcon, {label: 'Start tape'}, () => {
560 | if (emu.tapeIsPlaying) {
561 | emu.stopTape();
562 | } else {
563 | emu.playTape();
564 | }
565 | });
566 | tapeButton.disable();
567 | emu.on('openedTapeFile', () => {
568 | tapeButton.enable();
569 | });
570 | emu.on('playingTape', () => {
571 | tapeButton.setIcon(tapePauseIcon);
572 | tapeButton.setLabel('Stop tape');
573 | });
574 | emu.on('stoppedTape', () => {
575 | tapeButton.setIcon(tapePlayIcon);
576 | tapeButton.setLabel('Start tape');
577 | });
578 |
579 | const fullscreenButton = ui.toolbar.addButton(
580 | fullscreenIcon,
581 | {label: 'Enter full screen mode', align: 'right'},
582 | () => {
583 | ui.toggleFullscreen();
584 | }
585 | )
586 |
587 | ui.on('setZoom', (factor) => {
588 | if (factor == 'fullscreen') {
589 | fullscreenButton.setIcon(exitFullscreenIcon);
590 | fullscreenButton.setLabel('Exit full screen mode');
591 | } else {
592 | fullscreenButton.setIcon(fullscreenIcon);
593 | fullscreenButton.setLabel('Enter full screen mode');
594 | }
595 | });
596 | }
597 |
598 | const openFileDialog = () => {
599 | fileDialog().then(files => {
600 | const file = files[0];
601 | emu.openFile(file).then(() => {
602 | if (emu.isInitiallyPaused) emu.start();
603 | emu.focus();
604 | }).catch((err) => {alert(err);});
605 | });
606 | }
607 |
608 | const openGameBrowser = () => {
609 | emu.pause();
610 | const body = ui.showDialog();
611 | body.innerHTML = `
612 | Find games
613 |
617 |
618 |
619 | `;
620 | const input = body.querySelector('input');
621 | const searchButton = body.querySelector('button');
622 | const searchForm = body.querySelector('form');
623 | const resultsContainer = body.querySelector('.results');
624 |
625 | searchForm.addEventListener('submit', (e) => {
626 | e.preventDefault();
627 | searchButton.innerText = 'Searching...';
628 | const searchTerm = input.value.replace(/[^\w\s\-\']/, '');
629 |
630 | const encodeParam = (key, val) => {
631 | return encodeURIComponent(key) + '=' + encodeURIComponent(val);
632 | }
633 |
634 | const searchUrl = (
635 | 'https://archive.org/advancedsearch.php?'
636 | + encodeParam('q', 'collection:softwarelibrary_zx_spectrum title:"' + searchTerm + '"')
637 | + '&' + encodeParam('fl[]', 'creator')
638 | + '&' + encodeParam('fl[]', 'identifier')
639 | + '&' + encodeParam('fl[]', 'title')
640 | + '&' + encodeParam('rows', '50')
641 | + '&' + encodeParam('page', '1')
642 | + '&' + encodeParam('output', 'json')
643 | )
644 | fetch(searchUrl).then(response => {
645 | searchButton.innerText = 'Search';
646 | return response.json();
647 | }).then(data => {
648 | resultsContainer.innerHTML = '- powered by Internet Archive
';
649 | const ul = resultsContainer.querySelector('ul');
650 | const results = data.response.docs;
651 | results.forEach(result => {
652 | const li = document.createElement('li');
653 | ul.appendChild(li);
654 | const resultLink = document.createElement('a');
655 | resultLink.href = '#';
656 | resultLink.innerText = result.title;
657 | const creator = document.createTextNode(' - ' + result.creator)
658 | li.appendChild(resultLink);
659 | li.appendChild(creator);
660 | resultLink.addEventListener('click', (e) => {
661 | e.preventDefault();
662 | fetch(
663 | 'https://archive.org/metadata/' + result.identifier
664 | ).then(response => response.json()).then(data => {
665 | let chosenFilename = null;
666 | data.files.forEach(file => {
667 | const ext = file.name.split('.').pop().toLowerCase();
668 | if (ext == 'z80' || ext == 'sna' || ext == 'tap' || ext == 'tzx' || ext == 'szx') {
669 | chosenFilename = file.name;
670 | }
671 | });
672 | if (!chosenFilename) {
673 | alert('No loadable file found');
674 | } else {
675 | const finalUrl = 'https://cors.archive.org/cors/' + result.identifier + '/' + chosenFilename;
676 | emu.openUrl(finalUrl).catch((err) => {
677 | alert(err);
678 | }).then(() => {
679 | ui.hideDialog();
680 | emu.focus();
681 | emu.start();
682 | });
683 | }
684 | })
685 | })
686 | })
687 | })
688 | })
689 | input.focus();
690 | }
691 |
692 | const exit = () => {
693 | emu.exit();
694 | ui.unload();
695 | }
696 |
697 | /*
698 | const benchmarkElement = document.getElementById('benchmark');
699 | setInterval(() => {
700 | benchmarkElement.innerText = (
701 | "Running at " + benchmarkRunCount + "fps, rendering at "
702 | + benchmarkRenderCount + "fps"
703 | );
704 | benchmarkRunCount = 0;
705 | benchmarkRenderCount = 0;
706 | }, 1000)
707 | */
708 |
709 | return {
710 | setZoom: (zoom) => {ui.setZoom(zoom);},
711 | toggleFullscreen: () => {ui.toggleFullscreen();},
712 | enterFullscreen: () => {ui.enterFullscreen();},
713 | exitFullscreen: () => {ui.exitFullscreen();},
714 | setMachine: (model) => {emu.setMachine(model);},
715 | openFileDialog: () => {openFileDialog();},
716 | openUrl: (url) => {
717 | emu.openUrl(url).catch((err) => {alert(err);});
718 | },
719 | loadSnapshotFromStruct: (snapshot) => {
720 | emu.loadSnapshot(snapshot);
721 | },
722 | onReady: (callback) => {
723 | if (emu.isReady) {
724 | callback();
725 | } else {
726 | emu.onReadyHandlers.push(callback);
727 | }
728 | },
729 | exit: () => {exit();},
730 | };
731 | };
732 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------