zx81

Emulateur Sinclair ZX81 dans le navigateur : Z80, ROM Sinclair, tout en JavaScript
git clone https://git.schurger.org/zx81.git
Log | Files | Refs | README

commit 8707c70cf2151610ff5b2da1516c1fd7543cd256
Author: Jean Schurger <jean@schurger.org>
Date:   Wed,  4 Nov 2026 12:38:02 -0500

Émulateur ZX81 dans le navigateur : Z80, ULA simplifiée, clavier, .P, démo

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QyJB9yqUAYm3wRQi4uytj9

Diffstat:
A.gitignore | 3+++
AMakefile | 35+++++++++++++++++++++++++++++++++++
AREADME.md | 36++++++++++++++++++++++++++++++++++++
Adeploy/zx81.schurger.org | 42++++++++++++++++++++++++++++++++++++++++++
Aprograms/demo.bas | 39+++++++++++++++++++++++++++++++++++++++
Atest/boot.mjs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Atest/browser.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/bas2p.py | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/app.js | 322+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/index.html | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/programs/demo.bas | 39+++++++++++++++++++++++++++++++++++++++
Aweb/programs/demo.p | 0
Aweb/style.css | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/z80.js | 3402+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/zx81.js | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/zx81.rom | 0
16 files changed, 4694 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +.DS_Store diff --git a/Makefile b/Makefile @@ -0,0 +1,35 @@ +# zx81-web : émulateur ZX81 dans le navigateur, servi sur https://zx81.schurger.org +HOST = apostrophe +WWW = /var/www/zx81.schurger.org +VHOST = zx81.schurger.org + +.PHONY: all demo test serve deploy install-vhost + +all: demo + +# BASIC → .P (la source est aussi publiée à côté du .P) +demo: web/programs/demo.p + +web/programs/demo.p: programs/demo.bas tools/bas2p.py + python3 tools/bas2p.py $< $@ + cp programs/demo.bas web/programs/demo.bas + +# Démarrage de la ROM, PRINT 2+2, puis chargement et exécution de la démo (sans navigateur) +test: demo + node test/boot.mjs + node test/boot.mjs web/programs/demo.p 8 + +# Essai local : http://localhost:8081/ +serve: + python3 -m http.server 8081 -d web + +# Publication : fichiers statiques copiés sur apostrophe +deploy: demo test + ssh $(HOST) 'sudo install -d -o jeansch -g jeansch $(WWW)' + rsync -rc --delete --exclude '.*' web/ $(HOST):$(WWW)/ + @echo "https://$(VHOST)/" + +# Vhost nginx (une fois) : 8443 derrière sslh, certificat joker, comme les autres sites d'apostrophe +install-vhost: + scp deploy/$(VHOST) $(HOST):/tmp/$(VHOST) + ssh $(HOST) 'sudo install -m 644 /tmp/$(VHOST) /etc/nginx/sites-available/$(VHOST) && sudo ln -sf /etc/nginx/sites-available/$(VHOST) /etc/nginx/sites-enabled/$(VHOST) && sudo nginx -t && sudo systemctl reload nginx && rm /tmp/$(VHOST)' diff --git a/README.md b/README.md @@ -0,0 +1,36 @@ +# zx81-web — un ZX81 dans le navigateur + +Émulateur de Sinclair ZX81 écrit en JavaScript (modules ES, sans dépendance ni étape de +construction), publié sur https://zx81.schurger.org. + +- `web/` : la page (`index.html`, `style.css`, `app.js`), la machine (`zx81.js`), le cœur Z80 + (`z80.js`, Z80.js de Molly Howell, MIT, légèrement adapté — voir l'en-tête du fichier), la ROM + d'origine (`zx81.rom`, édition 3, CRC32 4b1dd6eb) et les programmes (`programs/`). +- `tools/bas2p.py` : convertit un listage BASIC ZX81 en fichier `.P` chargeable (tokenisation, + nombres flottants ZX81, variables système, fichier d'écran étendu, démarrage automatique). +- `programs/demo.bas` : la démo (attraper les étoiles, touches 5 et 8). +- `test/boot.mjs` : test sans navigateur (démarrage de la ROM, frappe de `PRINT 2+2`, chargement + et exécution d'un `.P`). +- `deploy/` : vhost nginx d'apostrophe. + +## Fonctionnement + +Le Z80 exécute la ROM telle quelle. La ULA est reproduite par son mécanisme : quand le CPU lit +un opcode à une adresse écho (A15 = 1) dont le bit 6 est à 0, le caractère est affiché et le CPU +exécute un NOP ; le `HALT` de fin de ligne déclenche l'interruption qui enchaîne la ligne +suivante ; en mode SLOW le NMI est cadencé toutes les 207 T (une ligne vidéo). La trame est +présentée à la fin du VSYNC (sortie sur un port après un `IN` du port 0xFE). Pas de +rendu pixel-exact des programmes « haute résolution » : c'est une émulation au caractère. + +`LOAD` et `SAVE` sont interceptés dans la ROM (0x0347 et 0x02FC, retour par 0x0207, comme z81) : +`LOAD ""` prend le `.P` déposé dans `machine.tape`, `SAVE` remet l'image mémoire 0x4009→E_LINE. + +## Commandes + + make test # démarrage + démo sans navigateur + make serve # http://localhost:8081/ + make deploy # rsync vers apostrophe:/var/www/zx81.schurger.org + make install-vhost # une fois : vhost nginx + +La ROM ZX81 appartient à Amstrad (ex-Sinclair Research), qui autorise sa distribution avec les +émulateurs. diff --git a/deploy/zx81.schurger.org b/deploy/zx81.schurger.org @@ -0,0 +1,42 @@ +# https://zx81.schurger.org : émulateur ZX81 dans le navigateur (fichiers statiques, +# dépôt ~/src/perso/zx81 de hotrats, publié par « make deploy »). +# TLS on 8443 behind sslh, like the other vhosts; wildcard certificate. +server { + server_name zx81.schurger.org; + listen 8443 ssl; + http2 on; + ssl_certificate /etc/letsencrypt/live/schurger.org/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/schurger.org/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; + + root /var/www/zx81.schurger.org; + index index.html; + + types { + text/html html; + text/css css; + text/javascript js mjs; + application/octet-stream rom p; + text/plain bas; + image/svg+xml svg; + } + + gzip on; + gzip_types text/css text/javascript text/plain application/octet-stream; + + location ~* \.(rom|p|bas)$ { + add_header Cache-Control "no-cache"; + } + + location / { + try_files $uri $uri/ =404; + } +} + +server { + listen 80; + listen [::]:80; + server_name zx81.schurger.org; + return 301 https://$host$request_uri; +} diff --git a/programs/demo.bas b/programs/demo.bas @@ -0,0 +1,39 @@ +# Démo interactive : attraper les étoiles avec les touches 5 et 8. +1 REM ZX81.SCHURGER.ORG +5 RAND +10 LET S=0 +20 LET R=0 +30 LET P=14 +40 CLS +50 PRINT AT 0,0;"~ ATTRAPE L ETOILE ~ 5=< 8=>" +60 PRINT AT 1,0;"SCORE 0 RATEES 0" +70 PRINT AT 21,P;"~ ~" +100 LET X=INT (RND*32) +110 FOR Y=3 TO 20 +120 PRINT AT Y,X;"*";AT Y-1,X;" " +130 LET K=CODE INKEY$ +140 IF K=33 AND P>0 THEN GOSUB 300 +150 IF K=36 AND P<29 THEN GOSUB 400 +160 NEXT Y +170 PRINT AT 20,X;" " +180 IF X>=P AND X<=P+2 THEN GOTO 250 +190 LET R=R+1 +200 PRINT AT 1,0;"SCORE ";S;" RATEES ";R +210 IF R=5 THEN GOTO 500 +220 GOTO 100 +250 LET S=S+1 +260 PRINT AT 1,0;"SCORE ";S;" RATEES ";R +270 GOTO 100 +300 PRINT AT 21,P+2;" " +310 LET P=P-1 +320 PRINT AT 21,P;"~ ~" +330 RETURN +400 PRINT AT 21,P;" " +410 LET P=P+1 +420 PRINT AT 21,P;"~ ~" +430 RETURN +500 PRINT AT 10,6;"~ PARTIE TERMINEE ~" +510 PRINT AT 12,6;"SCORE FINAL: ";S +520 PRINT AT 14,4;"UNE TOUCHE POUR REJOUER" +530 IF INKEY$="" THEN GOTO 530 +540 GOTO 10 diff --git a/test/boot.mjs b/test/boot.mjs @@ -0,0 +1,49 @@ +// Test sans navigateur : démarre la ROM, vérifie le curseur K, charge le .P passé en +// argument (ou aucun) et affiche l'écran en texte. +// node test/boot.mjs [fichier.p] [secondes émulées] +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, join } from 'node:path'; +import { ZX81, FRAME_T } from '../web/zx81.js'; + +const here = dirname(fileURLToPath(import.meta.url)); +const rom = new Uint8Array(readFileSync(join(here, '..', 'web', 'zx81.rom'))); +const m = new ZX81(rom); + +const runFrames = (n) => { for (let i = 0; i < n; i++) m.run(FRAME_T); }; +// Appuie sur une touche pendant quelques trames puis la relâche. +const press = (...names) => { + for (const k of names) m.keyDown(k); + runFrames(4); + for (const k of names) m.keyUp(k); + runFrames(4); +}; + +runFrames(130); +const boot = m.screenText(); +const kCursor = boot.split('\n')[23].startsWith('k'); +console.log(`Démarrage : ${m.frames} trames, curseur K ${kCursor ? 'présent' : 'ABSENT'}`); +if (!kCursor) { console.log(boot); process.exit(1); } + +const file = process.argv[2]; +if (file) { + m.tape = new Uint8Array(readFileSync(file)); + let loaded = false; + m.onLoad = () => { loaded = true; }; + press('J'); // LOAD + press('SHIFT', 'P'); press('SHIFT', 'P'); // "" + press('NEWLINE'); + runFrames(40); + console.log(`LOAD intercepté : ${loaded ? 'oui' : 'NON'}`); + if (!loaded) { console.error(m.screenText()); process.exitCode = 1; } + const secs = Number(process.argv[3] ?? 3); + runFrames(Math.round(secs * 50)); +} else { + // Tape PRINT 2+2 puis NEWLINE + press('P'); press('2'); press('SHIFT', 'K'); press('2'); press('NEWLINE'); + runFrames(80); +} +console.log('+' + '-'.repeat(32) + '+'); +for (const l of m.screenText().split('\n')) console.log('|' + l + '|'); +console.log('+' + '-'.repeat(32) + '+'); +console.log(`${m.frames} trames, ${(m.tstates / 3250000).toFixed(2)} s émulées`); diff --git a/test/browser.mjs b/test/browser.mjs @@ -0,0 +1,55 @@ +// Essai dans un vrai Chromium headless (protocole DevTools, sans dépendance) : +// ouvre l'URL, attend `secondes`, affiche la ligne de statut et les erreurs console, +// puis enregistre une capture d'écran. +// node test/browser.mjs [url] [secondes] [capture.png] [js à évaluer après l'attente] +import { spawn } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; + +const url = process.argv[2] ?? 'http://localhost:8081/'; +const secs = Number(process.argv[3] ?? 8); +const shot = process.argv[4] ?? '/tmp/zx81.png'; +const extra = process.argv[5]; +const port = 9333; + +const chrome = spawn(process.env.CHROME ?? 'chromium', [ + '--headless=new', '--no-sandbox', '--disable-gpu', '--hide-scrollbars', + `--remote-debugging-port=${port}`, '--window-size=1000,1500', 'about:blank', +], { stdio: 'ignore' }); + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let target; +for (let i = 0; i < 50 && !target; i++) { + await sleep(200); + try { + const r = await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: 'PUT' }); + target = await r.json(); + } catch { /* pas encore prêt */ } +} +if (!target) { chrome.kill(); throw new Error('Chromium ne répond pas'); } + +const ws = new WebSocket(target.webSocketDebuggerUrl); +await new Promise((r) => ws.addEventListener('open', r)); +let id = 0; +const pending = new Map(); +const logs = []; +ws.addEventListener('message', (ev) => { + const m = JSON.parse(ev.data); + if (m.id && pending.has(m.id)) { pending.get(m.id)(m.result ?? m.error); pending.delete(m.id); } + else if (m.method === 'Runtime.consoleAPICalled') logs.push(`[${m.params.type}] ${m.params.args.map((a) => a.value ?? a.description).join(' ')}`); + else if (m.method === 'Runtime.exceptionThrown') logs.push(`[exception] ${m.params.exceptionDetails.exception?.description ?? m.params.exceptionDetails.text}`); +}); +const send = (method, params = {}) => new Promise((r) => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params })); }); +const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value; + +await send('Runtime.enable'); +await send('Page.enable'); +await send('Page.navigate', { url }); +await sleep(secs * 1000); +console.log('Statut :', await evaluate("document.getElementById('status')?.textContent")); +if (extra) console.log('Évaluation :', JSON.stringify(await evaluate(extra))); +for (const l of logs) console.log(l); +const png = (await send('Page.captureScreenshot', { format: 'png' })).data; +writeFileSync(shot, Buffer.from(png, 'base64')); +console.log('Capture :', shot); +ws.close(); +chrome.kill(); diff --git a/tools/bas2p.py b/tools/bas2p.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""bas2p : convertit un listage BASIC ZX81 (texte) en fichier .P (image mémoire chargeable). + +Usage : bas2p.py source.bas sortie.p [--no-autorun] + +Syntaxe du source : une instruction par ligne, « NUMERO instruction ». Les mots-clés +s'écrivent en clair (PRINT AT, INKEY$, GOTO, <=, **…) et sont tokenisés ; les espaces +hors chaînes sont ignorés. Dans une chaîne, « ~ » inverse la vidéo jusqu'au prochain +« ~ », et « \\xNN » insère le code ZX81 NN (par ex. \\x08 pour un pavé graphique). +Par défaut, le programme démarre tout seul au chargement (NXTLIN pointe la première +ligne) ; --no-autorun laisse l'utilisateur taper RUN. +""" +import struct +import sys + +# Jeu de caractères ZX81 (codes 0x00-0x3F). Les codes 1-10 sont des pavés graphiques. +CHARS = ' ' + '\0' * 10 + '"£$:?()><=+-*/;,.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +ASCII_TO_CODE = {c: i for i, c in enumerate(CHARS) if c != '\0'} + +# Tokens 0xC0-0xFF, dans l'ordre de la ROM. +TOKENS = ['""', 'AT', 'TAB', '?', 'CODE', 'VAL', 'LEN', 'SIN', 'COS', 'TAN', 'ASN', 'ACS', + 'ATN', 'LN', 'EXP', 'INT', 'SQR', 'SGN', 'ABS', 'PEEK', 'USR', 'STR$', 'CHR$', + 'NOT', '**', 'OR', 'AND', '<=', '>=', '<>', 'THEN', 'TO', 'STEP', 'LPRINT', + 'LLIST', 'STOP', 'SLOW', 'FAST', 'NEW', 'SCROLL', 'CONT', 'DIM', 'REM', 'FOR', + 'GOTO', 'GOSUB', 'INPUT', 'LOAD', 'LIST', 'LET', 'PAUSE', 'NEXT', 'POKE', 'PRINT', + 'PLOT', 'RUN', 'SAVE', 'RAND', 'IF', 'CLS', 'UNPLOT', 'CLEAR', 'RETURN', 'COPY'] +TOKEN_CODE = {t: 0xC0 + i for i, t in enumerate(TOKENS) if t not in ('?', '""')} +TOKEN_CODE['INKEY$'] = 0x41 +TOKEN_CODE['PI'] = 0x42 +TOKEN_CODE['RND'] = 0x40 +# Essayer les plus longs d'abord (GOSUB avant GOTO, <= avant <, ** avant *…) +KEYWORDS = sorted(TOKEN_CODE, key=len, reverse=True) +# Mots-clés alphabétiques : ne pas les reconnaître à l'intérieur d'un nom de variable. +WORDY = {k for k in KEYWORDS if k[0].isalpha()} + +NEWLINE = 0x76 +NUMBER = 0x7E +ORG = 0x407D # début du programme (après les variables système) +DFILE_LEN = 1 + 24 * 33 # fichier d'écran étendu : 0x76 puis 24 × (32 caractères + 0x76) + + +def zx_float(x): + """Flottant ZX81 sur 5 octets : exposant+128, mantisse 32 bits (bit 31 = signe).""" + if x == 0: + return bytes(5) + sign = x < 0 + x = abs(x) + e = 0 + while x >= 1.0: + x /= 2 + e += 1 + while x < 0.5: + x *= 2 + e -= 1 + m = round(x * (1 << 32)) + if m >= (1 << 32): + m >>= 1 + e += 1 + if not -128 <= e < 128: + raise ValueError('nombre hors limites') + m &= 0x7FFFFFFF + if sign: + m |= 0x80000000 + return bytes([e + 128]) + struct.pack('>I', m) + + +def encode_string(s): + out = bytearray() + inverse = 0 + i = 0 + while i < len(s): + c = s[i] + if c == '~': + inverse ^= 0x80 + elif c == '\\' and s[i + 1:i + 2] == 'x': + out.append(int(s[i + 2:i + 4], 16) | inverse) + i += 3 + else: + c = c.upper() + if c not in ASCII_TO_CODE: + raise ValueError(f'caractère hors ZX81 : {c!r}') + out.append(ASCII_TO_CODE[c] | inverse) + i += 1 + return bytes(out) + + +def tokenize(stmt): + out = bytearray() + i = 0 + n = len(stmt) + prev_ident = False # le caractère précédent appartient à un identificateur + while i < n: + c = stmt[i] + if c == ' ': + i += 1 + prev_ident = False + continue + if c == '"': + j = stmt.index('"', i + 1) + out.append(ASCII_TO_CODE['"']) + out += encode_string(stmt[i + 1:j]) + out.append(ASCII_TO_CODE['"']) + i = j + 1 + prev_ident = False + continue + if out and out[-1] == TOKEN_CODE['REM'] and len(out) == 1: + # Tout ce qui suit REM est du texte brut. + out += encode_string(stmt[i:].strip()) + break + matched = None + up = stmt[i:].upper() + for k in KEYWORDS: + if up.startswith(k) and not (k in WORDY and prev_ident): + matched = k + break + if matched: + out.append(TOKEN_CODE[matched]) + i += len(matched) + prev_ident = False + continue + if c.isdigit() or (c == '.' and stmt[i + 1:i + 2].isdigit()): + if prev_ident: + out.append(ASCII_TO_CODE[c]) + i += 1 + continue + j = i + while j < n and (stmt[j].isdigit() or stmt[j] == '.'): + j += 1 + lit = stmt[i:j] + out += bytes(ASCII_TO_CODE[ch] for ch in lit) + out.append(NUMBER) + out += zx_float(float(lit)) + i = j + prev_ident = False + continue + cu = c.upper() + if cu not in ASCII_TO_CODE: + raise ValueError(f'caractère inconnu : {c!r} dans {stmt!r}') + out.append(ASCII_TO_CODE[cu]) + prev_ident = cu.isalnum() or cu == '$' + i += 1 + return bytes(out) + + +def build(lines, autorun=True): + prog = bytearray() + for num, stmt in lines: + body = tokenize(stmt) + bytes([NEWLINE]) + prog += struct.pack('>H', num) + struct.pack('<H', len(body)) + body + d_file = ORG + len(prog) + vars_ = d_file + DFILE_LEN + e_line = vars_ + 1 + sysvars = bytearray(0x407D - 0x4009) + + def w8(addr, v): sysvars[addr - 0x4009] = v + + def w16(addr, v): struct.pack_into('<H', sysvars, addr - 0x4009, v) + + w8(0x4009, 0) # VERSN + w16(0x400A, lines[0][0]) # E_PPC + w16(0x400C, d_file) # D_FILE + w16(0x400E, d_file + 1) # DF_CC + w16(0x4010, vars_) # VARS + w16(0x4012, 0) # DEST + w16(0x4014, e_line) # E_LINE + w16(0x4016, e_line + 4) # CH_ADD + w16(0x4018, 0) # X_PTR + w16(0x401A, e_line + 5) # STKBOT + w16(0x401C, e_line + 5) # STKEND + w8(0x401E, 0) # BERG + w16(0x401F, 0x405D) # MEM + w8(0x4022, 2) # DF_SZ + w16(0x4023, lines[0][0]) # S_TOP + w16(0x4025, 0xFFFF) # LAST_K + w8(0x4027, 0xFF) # DEBOUNCE + w8(0x4028, 55) # MARGIN (50 Hz) + w16(0x4029, ORG if autorun else d_file) # NXTLIN + w16(0x402B, 0) # OLDPPC + w8(0x402D, 0) # FLAGX + w16(0x402E, 0) # STRLEN + w16(0x4030, 0x0C8D) # T_ADDR + w16(0x4032, 0) # SEED + w16(0x4034, 0xFFFF) # FRAMES + w16(0x4036, 0) # COORDS + w8(0x4038, 0xBC) # PR_CC + w16(0x4039, 0x1821) # S_POSN + w8(0x403B, 0x40) # CDFLAG : mode SLOW + sysvars[0x403C - 0x4009:0x403C - 0x4009 + 33] = bytes(32) + bytes([NEWLINE]) # PRBUFF + dfile = bytes([NEWLINE]) + (bytes(32) + bytes([NEWLINE])) * 24 + return bytes(sysvars) + bytes(prog) + dfile + bytes([0x80]) + + +def parse(text): + lines = [] + for raw in text.splitlines(): + s = raw.strip() + if not s or s.startswith('#'): + continue + num, _, stmt = s.partition(' ') + lines.append((int(num), stmt.strip())) + if lines != sorted(lines, key=lambda x: x[0]): + raise ValueError('numéros de ligne non croissants') + return lines + + +def main(): + args = [a for a in sys.argv[1:] if not a.startswith('--')] + if len(args) != 2: + print(__doc__) + sys.exit(2) + autorun = '--no-autorun' not in sys.argv + lines = parse(open(args[0], encoding='utf-8').read()) + data = build(lines, autorun) + open(args[1], 'wb').write(data) + print(f'{args[1]} : {len(lines)} lignes, {len(data)} octets, programme {len(data) - (0x407D - 0x4009) - DFILE_LEN - 1} octets') + + +if __name__ == '__main__': + main() diff --git a/web/app.js b/web/app.js @@ -0,0 +1,322 @@ +// Interface de l'émulateur : boucle temps réel, écran, claviers (physique et à l'écran), +// chargement/sauvegarde de .P, saisie automatique de LOAD "". +import { ZX81, FRAME_T, CPU_HZ, KEYS, COLS, ROWS } from './zx81.js'; + +const $ = (id) => document.getElementById(id); +const canvas = $('screen'); +const ctx = canvas.getContext('2d', { alpha: false }); +const img = ctx.createImageData(COLS * 8, ROWS * 8); +const status = $('status'); + +const PAPER = [0xe4, 0xe4, 0xe0], INK = [0x10, 0x10, 0x10]; +const CURSORS = [0xb0, 0xb1, 0xab, 0xa8]; // K, L, F, G inversés + +let machine = null; +let dirty = false, lastFrameAt = 0, noSignal = false; +let paused = false, speed = 1; +let lastTick = 0, fpsFrames = 0, fpsAt = 0, fps = 0; + +// ---------------------------------------------------------------- écran + +function draw() { + const px = machine.pixels, d = img.data; + for (let i = 0, o = 0; i < px.length; i++, o += 4) { + const c = px[i] ? INK : PAPER; + d[o] = c[0]; d[o + 1] = c[1]; d[o + 2] = c[2]; d[o + 3] = 255; + } + ctx.putImageData(img, 0, 0); + noSignal = false; +} + +// Mode FAST (ou machine plantée) : pas de signal vidéo, le téléviseur montre de la neige. +function drawNoSignal() { + const d = img.data; + for (let o = 0; o < d.length; o += 4) { + const v = 150 + ((Math.random() * 70) | 0); + d[o] = d[o + 1] = d[o + 2] = v; d[o + 3] = 255; + } + ctx.putImageData(img, 0, 0); + noSignal = true; +} + +// ---------------------------------------------------------------- saisie automatique + +// File d'attente de touches « tapées » par la page (LOAD "" après un reset…). +// Chaque entrée : { keys: [...], frames } ou { wait: () => bool, timeout }. +const typist = { + queue: [], current: null, left: 0, gap: 0, acc: 0, + clear() { if (this.current?.keys) this.current.keys.forEach((k) => machine.keyUp(k)); this.queue = []; this.current = null; this.gap = 0; }, + type(seqs) { for (const keys of seqs) this.queue.push({ keys, frames: 3 }); }, + wait(fn, timeoutFrames = 1000) { this.queue.push({ wait: fn, timeout: timeoutFrames }); }, + tick(tstates) { + this.acc += tstates; + while (this.acc >= FRAME_T) { this.acc -= FRAME_T; this.step(); } + }, + step() { + const c = this.current; + if (c) { + if (c.wait) { + if (c.wait() || --c.timeout <= 0) { this.current = null; this.gap = 2; } + return; + } + if (--c.left <= 0) { c.keys.forEach((k) => machine.keyUp(k)); this.current = null; this.gap = 3; } + return; + } + if (this.gap > 0) { this.gap--; return; } + if (!this.queue.length) return; + const n = this.queue.shift(); + this.current = n; + if (n.keys) { n.keys.forEach((k) => machine.keyDown(k)); n.left = n.frames; } + }, +}; + +const cursorShown = () => CURSORS.some((c) => machine.screen.includes(c)); + +// Réinitialise la machine et fait charger `bytes` par la ROM (LOAD ""). +function loadProgram(bytes, label) { + typist.clear(); + machine.reset(); + machine.tape = bytes; + typist.wait(cursorShown, 600); + typist.type([['J'], ['SHIFT', 'P'], ['SHIFT', 'P'], ['NEWLINE']]); + setStatus(`Démarrage puis LOAD "" de ${label} (${bytes.length} octets)…`); +} + +// ---------------------------------------------------------------- boucle + +function loop(now) { + if (!paused) { + const dt = Math.min(now - (lastTick || now), 100); + const t = Math.round(dt * (CPU_HZ / 1000) * speed); + if (t > 0) { machine.run(t); typist.tick(t); } + } + lastTick = now; + if (dirty) { draw(); dirty = false; } + else if (!paused && now - lastFrameAt > 300 && (!noSignal || Math.random() < 0.3)) drawNoSignal(); + if (now - fpsAt > 1000) { + fps = fpsFrames; fpsFrames = 0; fpsAt = now; + updateStatus(); + } + requestAnimationFrame(loop); +} + +let statusMsg = ''; +function setStatus(m) { statusMsg = m; updateStatus(); } +function updateStatus() { + if (!machine) return; + const cd = machine.ram[0x403b - 0x4000]; + const mode = (cd & 0x40) ? 'SLOW' : 'FAST'; + const base = paused ? 'En pause' : `${mode} · ${fps} trames/s · ${(CPU_HZ * speed / 1e6).toFixed(2)} MHz`; + status.textContent = statusMsg ? `${base} — ${statusMsg}` : base; +} + +// ---------------------------------------------------------------- clavier physique + +// Symboles obtenus avec SHIFT sur le ZX81 (table K-SHIFTED de la ROM). +const SYMBOLS = { + '"': ['SHIFT', 'P'], '£': ['SHIFT', 'SPACE'], '$': ['SHIFT', 'U'], ':': ['SHIFT', 'Z'], '?': ['SHIFT', 'C'], + '(': ['SHIFT', 'I'], ')': ['SHIFT', 'O'], '>': ['SHIFT', 'M'], '<': ['SHIFT', 'N'], '=': ['SHIFT', 'L'], + '+': ['SHIFT', 'K'], '-': ['SHIFT', 'J'], '*': ['SHIFT', 'B'], '/': ['SHIFT', 'V'], ';': ['SHIFT', 'X'], + ',': ['SHIFT', '.'], '.': ['.'], +}; +const SPECIAL = { + Enter: ['NEWLINE'], NumpadEnter: ['NEWLINE'], Backspace: ['SHIFT', '0'], Delete: ['SHIFT', '0'], + ArrowLeft: ['SHIFT', '5'], ArrowDown: ['SHIFT', '6'], ArrowUp: ['SHIFT', '7'], ArrowRight: ['SHIFT', '8'], + Escape: ['SHIFT', 'SPACE'], Space: ['SPACE'], ShiftLeft: ['SHIFT'], ShiftRight: ['SHIFT'], Tab: ['SHIFT', 'NEWLINE'], +}; + +function mapKey(e) { + if (SPECIAL[e.code]) return SPECIAL[e.code]; + const k = e.key; + if (k.length === 1) { + if (/[a-z]/i.test(k)) return [k.toUpperCase()]; + if (/[0-9]/.test(k)) return [k]; + if (SYMBOLS[k]) return SYMBOLS[k]; + } + let m; + if ((m = /^Key([A-Z])$/.exec(e.code))) return [m[1]]; + if ((m = /^(?:Digit|Numpad)([0-9])$/.exec(e.code))) return [m[1]]; + return null; +} + +const held = new Map(); // e.code → touches ZX81 enfoncées + +function applyHeld() { + machine.releaseAll(); + for (const keys of held.values()) keys.forEach((k) => machine.keyDown(k)); + for (const k of stickyKeys) machine.keyDown(k); + refreshKeyboardHighlight(); +} + +window.addEventListener('keydown', (e) => { + if (!machine || e.ctrlKey || e.metaKey || e.altKey) return; + if (['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'].includes(e.target.tagName) && e.code !== 'Escape') return; + const keys = mapKey(e); + if (!keys) return; + e.preventDefault(); + if (e.repeat) return; + held.set(e.code, keys); + applyHeld(); +}); +window.addEventListener('keyup', (e) => { + if (!machine) return; + if (held.delete(e.code)) applyHeld(); +}); +window.addEventListener('blur', () => { held.clear(); if (machine) applyHeld(); }); + +// ---------------------------------------------------------------- clavier à l'écran + +// Ordre des touches dans les tables de la ROM (K-UNSHIFTED à 0x007E). +const TABLE_ORDER = ['Z', 'X', 'C', 'V', 'A', 'S', 'D', 'F', 'G', 'Q', 'W', 'E', 'R', 'T', '1', '2', '3', '4', '5', + '0', '9', '8', '7', '6', 'P', 'O', 'I', 'U', 'Y', 'NEWLINE', 'L', 'K', 'J', 'H', 'SPACE', '.', 'M', 'N', 'B']; +const LAYOUT = [ + ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], + ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'], + ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'NEWLINE'], + ['SHIFT', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '.', 'SPACE'], +]; +const CHARSET = ' \0\0\0\0\0\0\0\0\0\0"£$:?()><=+-*/;,.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; +const CONTROL = { 0x70: '↑', 0x71: '↓', 0x72: '←', 0x73: '→', 0x74: 'GRAPHICS', 0x75: 'EDIT', 0x76: 'NEWLINE', 0x77: 'RUBOUT', 0x78: '', 0x79: 'FUNCTION' }; + +// Décode la table des mots-clés de la ROM (0x0111, dernier caractère de chaque mot inversé). +function decodeTokens(rom) { + const tokens = []; let cur = ''; + for (let a = 0x0112; tokens.length < 64; a++) { + const b = rom[a]; + cur += CHARSET[b & 0x3f] ?? '?'; + if (b & 0x80) { tokens.push(cur); cur = ''; } + } + return tokens; // tokens[i] = texte du code 0xC0 + i +} + +function codeText(code, tokens) { + if (code >= 0xc0) return tokens[code - 0xc0]; + if (code === 0x40) return 'RND'; + if (code === 0x41) return 'INKEY$'; + if (code === 0x42) return 'PI'; + if (code >= 0x70 && code <= 0x79) return CONTROL[code]; + if (code < 0x40) return CHARSET[code] === '\0' ? '▞' : CHARSET[code]; + return ''; +} + +const stickyKeys = new Set(); // SHIFT « collant » du clavier à l'écran +const keyEls = new Map(); + +function buildKeyboard(rom) { + const tokens = decodeTokens(rom); + const kb = $('keyboard'); + for (const row of LAYOUT) { + for (const name of row) { + const el = document.createElement('div'); + el.className = 'key'; + el.dataset.key = name; + let kw = '', sh = '', fn = '', main = name, small = false; + const idx = TABLE_ORDER.indexOf(name); + if (idx >= 0) { + const unsh = rom[0x007e + idx]; + if (unsh >= 0x26 && unsh <= 0x3f) kw = tokens[unsh + 0xc0 - 0xc0]; // mot-clé = lettre + 0xC0 + sh = codeText(rom[0x00a5 + idx], tokens); + fn = codeText(rom[0x00cc + idx], tokens); + if (name === 'NEWLINE' || name === 'SPACE') { main = name === 'SPACE' ? 'SPACE' : 'NEW LINE'; small = true; } + } else { main = 'SHIFT'; small = true; } + el.innerHTML = `<div class="top"><span class="kw">${kw}</span><span class="sh">${sh}</span></div>` + + `<div class="main${small ? ' small' : ''}">${main}</div><div class="fn">${fn}</div>`; + el.title = name === 'SHIFT' ? 'SHIFT (reste enfoncé jusqu’à la touche suivante)' : [kw && `K : ${kw}`, sh && `SHIFT : ${sh}`, fn && `FUNCTION : ${fn}`].filter(Boolean).join(' · '); + kb.appendChild(el); + keyEls.set(name, el); + + const press = (ev) => { + ev.preventDefault(); + if (ev.button !== undefined && ev.button !== 0) return; + canvas.focus({ preventScroll: true }); + if (name === 'SHIFT') { + if (stickyKeys.has('SHIFT')) stickyKeys.delete('SHIFT'); else stickyKeys.add('SHIFT'); + applyHeld(); + return; + } + el.setPointerCapture?.(ev.pointerId); + held.set('ui:' + name, stickyKeys.has('SHIFT') ? ['SHIFT', name] : [name]); + applyHeld(); + }; + const release = () => { + if (!held.has('ui:' + name)) return; + held.delete('ui:' + name); + stickyKeys.delete('SHIFT'); + applyHeld(); + }; + el.addEventListener('pointerdown', press); + el.addEventListener('pointerup', release); + el.addEventListener('pointercancel', release); + el.addEventListener('lostpointercapture', release); + el.addEventListener('contextmenu', (ev) => ev.preventDefault()); + } + } +} + +function refreshKeyboardHighlight() { + const down = new Set(); + for (const keys of held.values()) keys.forEach((k) => down.add(k)); + for (const [name, el] of keyEls) { + el.classList.toggle('down', down.has(name)); + el.classList.toggle('sticky', name === 'SHIFT' && stickyKeys.has('SHIFT')); + } +} + +// ---------------------------------------------------------------- boutons + +function download(bytes, name) { + const a = document.createElement('a'); + a.href = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' })); + a.download = name; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); +} + +async function fetchBytes(url) { + const r = await fetch(url, { cache: 'no-cache' }); + if (!r.ok) throw new Error(`${url} : HTTP ${r.status}`); + return new Uint8Array(await r.arrayBuffer()); +} + +$('btn-demo').addEventListener('click', async () => loadProgram(await fetchBytes('programs/demo.p'), 'demo.p')); +$('btn-load').addEventListener('click', () => $('file').click()); +$('file').addEventListener('change', async (e) => { + const f = e.target.files[0]; + if (!f) return; + loadProgram(new Uint8Array(await f.arrayBuffer()), f.name); + e.target.value = ''; +}); +$('btn-save').addEventListener('click', () => { + if (!cursorShown()) { setStatus('SAVE : il faut d’abord revenir au curseur (BREAK = Échap)'); return; } + typist.clear(); + typist.type([['S'], ['SHIFT', 'P'], ['Z'], ['X'], ['8'], ['1'], ['SHIFT', 'P'], ['NEWLINE']]); // SAVE "ZX81" +}); +$('btn-reset').addEventListener('click', () => { typist.clear(); machine.reset(); setStatus('Réinitialisé'); }); +$('speed').addEventListener('change', (e) => { speed = Number(e.target.value); updateStatus(); }); +$('btn-pause').addEventListener('click', (e) => { + paused = !paused; + e.target.textContent = paused ? 'Reprendre' : 'Pause'; + e.target.classList.toggle('on', paused); + updateStatus(); +}); +canvas.tabIndex = 0; + +// ---------------------------------------------------------------- démarrage + +(async () => { + try { + const rom = await fetchBytes('zx81.rom'); + machine = new ZX81(rom); + window.zx81 = machine; // pour les essais et la console + machine.onFrame = () => { dirty = true; lastFrameAt = performance.now(); fpsFrames++; }; + machine.onSave = (bytes) => { download(bytes, 'zx81.p'); setStatus(`SAVE : ${bytes.length} octets téléchargés (zx81.p)`); }; + machine.onLoad = () => setStatus('Programme chargé'); + buildKeyboard(rom); + setStatus(''); + requestAnimationFrame(loop); + try { loadProgram(await fetchBytes('programs/demo.p'), 'demo.p'); } + catch (err) { setStatus(`Démo indisponible : ${err.message}`); } + } catch (err) { + status.textContent = `Impossible de démarrer : ${err.message}`; + } +})(); diff --git a/web/index.html b/web/index.html @@ -0,0 +1,93 @@ +<!doctype html> +<html lang="fr"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<title>ZX81 dans le navigateur</title> +<meta name="description" content="Émulateur de Sinclair ZX81 (Z80, ROM 8 Ko, 16 Ko de RAM) qui tourne dans le navigateur, avec clavier à l'écran et chargement de fichiers .P."> +<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' fill='%23111'/%3E%3Crect x='2' y='3' width='12' height='9' fill='%23ddd'/%3E%3Crect x='3' y='9' width='2' height='2' fill='%23111'/%3E%3C/svg%3E"> +<link rel="stylesheet" href="style.css"> +</head> +<body> +<header> + <h1><span class="logo">ZX<span>81</span></span> dans le navigateur</h1> + <p class="sub">Z80 à 3,25 MHz, ROM d'origine (édition 3), 16 Ko de RAM, affichage SLOW/FAST, clavier à 40 touches. + Le programme de démonstration se charge tout seul : attrapez les étoiles avec <kbd>5</kbd> et <kbd>8</kbd>.</p> +</header> + +<main> + <section class="tv" aria-label="Écran du ZX81"> + <div class="bezel"> + <canvas id="screen" width="256" height="192"></canvas> + </div> + <div class="status" id="status" aria-live="polite">Chargement de la ROM…</div> + </section> + + <section class="toolbar"> + <button id="btn-demo" title="Réinitialise la machine et charge la démo (LOAD &quot;&quot;)">Démo</button> + <button id="btn-load" title="Réinitialise et charge un fichier .P de votre ordinateur">Charger un .P…</button> + <input type="file" id="file" accept=".p,.P,.81,application/octet-stream" hidden> + <button id="btn-save" title="Tape SAVE pour télécharger le programme en mémoire (fichier .P)">Sauver (.P)</button> + <button id="btn-reset" title="Mise sous tension : RAM effacée, retour au curseur K">Réinitialiser</button> + <label class="speed">Vitesse + <select id="speed"> + <option value="1" selected>1× (3,25 MHz)</option> + <option value="2">2×</option> + <option value="4">4×</option> + <option value="10">10×</option> + </select> + </label> + <button id="btn-pause" title="Suspendre / reprendre l'émulation">Pause</button> + </section> + + <section class="keyboard" id="keyboard" aria-label="Clavier du ZX81"></section> + + <section class="help"> + <h2>Comment ça marche</h2> + <div class="cols"> + <div> + <h3>Le clavier du ZX81</h3> + <p>Le ZX81 saisit les mots-clés en une touche. Au début d'une ligne, le curseur <b class="inv">K</b> est en mode + <i>Keyword</i> : la touche <kbd>P</kbd> écrit <code>PRINT</code>, <kbd>J</kbd> écrit <code>LOAD</code>, + <kbd>R</kbd> écrit <code>RUN</code>… (mot blanc au-dessus de chaque touche). Le curseur passe ensuite en + <b class="inv">L</b> (lettres). Les symboles rouges s'obtiennent avec <kbd>SHIFT</kbd> ; + <kbd>SHIFT</kbd>+<kbd>NEWLINE</kbd> donne le curseur <b class="inv">F</b> (fonctions, mots rouges sous les touches) et + <kbd>SHIFT</kbd>+<kbd>9</kbd> le curseur <b class="inv">G</b> (graphismes).</p> + <p>Essayez : <kbd>P</kbd> <kbd>2</kbd> <kbd>SHIFT</kbd>+<kbd>K</kbd> <kbd>2</kbd> <kbd>NEWLINE</kbd> + affiche <code>4</code> ; après la démo, <kbd>SHIFT</kbd>+<kbd>SPACE</kbd> (BREAK) puis <kbd>K</kbd> <kbd>NEWLINE</kbd> liste le programme.</p> + </div> + <div> + <h3>Votre clavier</h3> + <table> + <tr><td>Lettres, chiffres, <kbd>.</kbd>, <kbd>Espace</kbd>, <kbd>Maj</kbd></td><td>touches équivalentes</td></tr> + <tr><td><kbd>Entrée</kbd></td><td>NEWLINE</td></tr> + <tr><td><kbd>Retour arrière</kbd></td><td>RUBOUT (SHIFT+0)</td></tr> + <tr><td><kbd>←</kbd> <kbd>↓</kbd> <kbd>↑</kbd> <kbd>→</kbd></td><td>curseur (SHIFT+5…8)</td></tr> + <tr><td><kbd>Échap</kbd></td><td>BREAK (SHIFT+SPACE)</td></tr> + <tr><td><kbd>"</kbd> <kbd>=</kbd> <kbd>+</kbd> <kbd>-</kbd> <kbd>*</kbd> <kbd>/</kbd> <kbd>&lt;</kbd> <kbd>&gt;</kbd> <kbd>(</kbd> <kbd>)</kbd> <kbd>$</kbd> <kbd>:</kbd> <kbd>;</kbd> <kbd>,</kbd> <kbd>?</kbd></td><td>le symbole, SHIFT compris</td></tr> + </table> + <p>Le clavier à l'écran fonctionne à la souris et au doigt ; <kbd>SHIFT</kbd> y reste enfoncé jusqu'à la touche suivante.</p> + </div> + <div> + <h3>Sous le capot</h3> + <p>Tout tourne en JavaScript dans la page : le cœur Z80 (<a href="https://github.com/DrGoldfire/Z80.js">Z80.js</a>, MIT) + exécute la ROM d'origine ; la ULA est reproduite par son mécanisme réel — le fichier d'écran est « exécuté » par le + processeur à l'adresse écho, les caractères deviennent des NOP et le <code>HALT</code> de fin de ligne déclenche + l'interruption de ligne suivante ; le NMI cadence les bordures en mode SLOW. En mode FAST, l'écran s'éteint comme sur + un vrai téléviseur. <code>LOAD</code> et <code>SAVE</code> sont interceptés dans la ROM pour lire et écrire des + fichiers .P (format des émulateurs). Le démarrage prend ~2 s, comme sur la machine : la ROM remplit le fichier + d'écran du 16 Ko octet par octet.</p> + <p>Démo : <a href="programs/demo.bas">source BASIC</a> → <a href="programs/demo.p">demo.p</a> (outil <code>bas2p.py</code>). + Code source : <a href="https://git.schurger.org/zx81.git/">git.schurger.org/zx81</a>.</p> + </div> + </div> + </section> +</main> + +<footer> + <p>ROM ZX81 © 1981 Sinclair Research, aujourd'hui Amstrad/Sky, qui en autorise la distribution avec les émulateurs. Page de Jean Schurger, 2026.</p> +</footer> + +<script type="module" src="app.js"></script> +</body> +</html> diff --git a/web/programs/demo.bas b/web/programs/demo.bas @@ -0,0 +1,39 @@ +# Démo interactive : attraper les étoiles avec les touches 5 et 8. +1 REM ZX81.SCHURGER.ORG +5 RAND +10 LET S=0 +20 LET R=0 +30 LET P=14 +40 CLS +50 PRINT AT 0,0;"~ ATTRAPE L ETOILE ~ 5=< 8=>" +60 PRINT AT 1,0;"SCORE 0 RATEES 0" +70 PRINT AT 21,P;"~ ~" +100 LET X=INT (RND*32) +110 FOR Y=3 TO 20 +120 PRINT AT Y,X;"*";AT Y-1,X;" " +130 LET K=CODE INKEY$ +140 IF K=33 AND P>0 THEN GOSUB 300 +150 IF K=36 AND P<29 THEN GOSUB 400 +160 NEXT Y +170 PRINT AT 20,X;" " +180 IF X>=P AND X<=P+2 THEN GOTO 250 +190 LET R=R+1 +200 PRINT AT 1,0;"SCORE ";S;" RATEES ";R +210 IF R=5 THEN GOTO 500 +220 GOTO 100 +250 LET S=S+1 +260 PRINT AT 1,0;"SCORE ";S;" RATEES ";R +270 GOTO 100 +300 PRINT AT 21,P+2;" " +310 LET P=P-1 +320 PRINT AT 21,P;"~ ~" +330 RETURN +400 PRINT AT 21,P;" " +410 LET P=P+1 +420 PRINT AT 21,P;"~ ~" +430 RETURN +500 PRINT AT 10,6;"~ PARTIE TERMINEE ~" +510 PRINT AT 12,6;"SCORE FINAL: ";S +520 PRINT AT 14,4;"UNE TOUCHE POUR REJOUER" +530 IF INKEY$="" THEN GOTO 530 +540 GOTO 10 diff --git a/web/programs/demo.p b/web/programs/demo.p Binary files differ. diff --git a/web/style.css b/web/style.css @@ -0,0 +1,127 @@ +:root { + --bg: #15161a; + --fg: #e8e6e0; + --muted: #a7a49c; + --accent: #d9312f; + --key: #262830; + --key-edge: #0c0d10; + --key-fg: #f2f0ea; + --paper: #e4e4e0; + --ink: #101010; + color-scheme: dark; +} +* { box-sizing: border-box; } +html, body { margin: 0; padding: 0; } +body { + background: var(--bg); + color: var(--fg); + font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + padding: 0 16px 40px; +} +a { color: #8fb8ff; } +header { max-width: 900px; margin: 24px auto 12px; } +h1 { font-size: 1.6rem; font-weight: 600; margin: 0 0 6px; letter-spacing: .01em; } +.logo { font-weight: 800; color: #fff; } +.logo span { color: var(--accent); } +.sub { color: var(--muted); margin: 0; } +main { max-width: 900px; margin: 0 auto; } +kbd { + font: 0.85em ui-monospace, SFMono-Regular, Menlo, monospace; + background: #2b2d35; border: 1px solid #3c3f49; border-bottom-width: 2px; + border-radius: 4px; padding: 0 5px; color: #fff; white-space: nowrap; +} +code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: #fff; } +.inv { background: #fff; color: #000; padding: 0 3px; font-family: ui-monospace, monospace; font-style: normal; } + +/* Téléviseur */ +.tv { margin: 0 auto; max-width: 840px; } +.bezel { + background: #050505; + border-radius: 14px; + padding: 4%; + box-shadow: 0 10px 40px rgba(0,0,0,.6), inset 0 0 0 2px #222; +} +#screen { + display: block; + width: 100%; + aspect-ratio: 4 / 3; + background: var(--paper); + image-rendering: pixelated; + image-rendering: crisp-edges; + border-radius: 4px; + outline: none; +} +.status { + text-align: center; color: var(--muted); font-size: .85rem; margin: 8px 0 0; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; min-height: 1.4em; +} + +/* Barre d'outils */ +.toolbar { + display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; align-items: center; + margin: 14px auto 18px; max-width: 840px; +} +.toolbar button, .toolbar select { + background: #2b2d35; color: #fff; border: 1px solid #40434e; border-radius: 6px; + padding: 7px 14px; font: inherit; font-size: .95rem; cursor: pointer; +} +.toolbar button:hover { background: #363946; } +.toolbar button:active, .toolbar button.on { background: var(--accent); border-color: var(--accent); } +.toolbar .speed { color: var(--muted); font-size: .9rem; display: inline-flex; gap: 6px; align-items: center; } + +/* Clavier ZX81 */ +.keyboard { + background: #0e0f12; + border-radius: 12px; + padding: 12px 10px 14px; + margin: 0 auto; + max-width: 840px; + display: grid; + grid-template-columns: repeat(10, 1fr); + gap: 6px 5px; + user-select: none; + -webkit-user-select: none; + touch-action: manipulation; +} +.key { + position: relative; + aspect-ratio: 1 / 1.15; + background: var(--key); + border: 1px solid var(--key-edge); + border-bottom-width: 3px; + border-radius: 6px; + color: var(--key-fg); + display: grid; + grid-template-rows: 1fr auto 1fr; + padding: 3px 4px 2px; + cursor: pointer; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + transition: background .05s; +} +.key.down { background: #4a4d5a; border-bottom-width: 1px; transform: translateY(2px); } +.key.sticky { background: var(--accent); } +.key .kw { font-size: clamp(7px, 1.15vw, 10px); color: #fff; letter-spacing: -.02em; line-height: 1; white-space: nowrap; overflow: hidden; } +.key .sh { font-size: clamp(7px, 1.15vw, 10px); color: #ff6b66; line-height: 1; text-align: right; white-space: nowrap; } +.key .top { display: flex; justify-content: space-between; align-items: start; gap: 2px; } +.key .main { font-size: clamp(14px, 2.6vw, 24px); font-weight: 700; text-align: center; line-height: 1; } +.key .main.small { font-size: clamp(8px, 1.4vw, 12px); font-weight: 600; } +.key .fn { font-size: clamp(7px, 1.15vw, 10px); color: #ff6b66; text-align: center; align-self: end; line-height: 1; white-space: nowrap; overflow: hidden; } +.key .g { display: inline-block; width: .9em; height: .9em; vertical-align: -0.1em; background: + conic-gradient(from 0deg at 50% 50%, #fff 0 25%, #000 0 50%, #fff 0 75%, #000 0); } +.key .g[data-g="1"] { background: linear-gradient(to bottom, transparent 50%, #fff 50%) , linear-gradient(to right, #fff 50%, transparent 50%); background-size: 50% 50%; } + +/* Aide */ +.help { max-width: 900px; margin: 28px auto 0; color: #d4d2cc; } +.help h2 { font-size: 1.15rem; margin: 0 0 8px; } +.help h3 { font-size: 1rem; margin: 0 0 6px; color: #fff; } +.help .cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 20px; } +.help p { margin: 0 0 10px; font-size: .95rem; } +.help table { border-collapse: collapse; font-size: .9rem; margin-bottom: 10px; } +.help td { padding: 3px 10px 3px 0; vertical-align: top; border-bottom: 1px solid #2a2c33; } +footer { max-width: 900px; margin: 30px auto 0; color: var(--muted); font-size: .8rem; } + +@media (max-width: 480px) { + .key .kw, .key .fn { display: none; } + .key { aspect-ratio: 1 / 1.2; grid-template-rows: auto 1fr; } + .toolbar button, .toolbar select { padding: 6px 10px; font-size: .85rem; } +} diff --git a/web/z80.js b/web/z80.js @@ -0,0 +1,3402 @@ +// Z80.js de Molly Howell (MIT, https://github.com/DrGoldfire/Z80.js), adapté pour zx81-web : +// - l'opcode est lu par core.fetch_opcode(pc) (et non mem_read), pour que la ULA du ZX81 +// puisse intercepter les fetchs dans la zone « écho » (A15 = 1) ; +// - quelques accesseurs ajoutés (get_i, get_pc, set_pc, get_iff1, is_halted) ; +// - export en module ES. +/////////////////////////////////////////////////////////////////////////////// +/// @file Z80.js +/// +/// @brief Emulator for the Zilog Z80 microprocessor +/// +/// @author Molly Howell +/// +/// @remarks +/// This module is a simple, straightforward instruction interpreter. +/// There is no fancy dynamic recompilation or cycle-accurate emulation. +/// The author believes that this should be sufficient for any emulator that +/// would be feasible to write in JavaScript anyway. +/// The code and the comments in this file assume that the reader is familiar +/// with the Z80 architecture. If you're not, here are some references I use: +/// http://clrhome.org/table/ - Z80 instruction set tables +/// http://www.zilog.com/docs/z80/um0080.pdf - The official manual +/// http://www.myquest.nl/z80undocumented/z80-documented-v0.91.pdf +/// - The Undocumented Z80, Documented +/// +/// @copyright (c) Molly Howell +/// This code is released under the MIT license, +/// a copy of which is available in the associated README.md file, +/// or at http://opensource.org/licenses/MIT +/////////////////////////////////////////////////////////////////////////////// + +"use strict"; + +/////////////////////////////////////////////////////////////////////////////// +/// We'll begin with the object constructor and the public API functions. +/////////////////////////////////////////////////////////////////////////////// +function Z80(coreParameter) +{ + // Obviously we'll be needing the core object's functions again. + let core = coreParameter; + + // The argument to this constructor should be an object containing 4 functions: + // mem_read(address) should return the byte at the given memory address, + // mem_write(address, value) should write the given value to the given memory address, + // io_read(port) should read a return a byte read from the given I/O port, + // io_write(port, value) should write the given byte to the given I/O port. + // If any of those functions is missing, this module cannot run. + if (!core || (typeof core.mem_read !== "function") || (typeof core.mem_write !== "function") || + (typeof core.io_read !== "function") || (typeof core.io_write !== "function")) + throw("Z80: Core object is missing required functions."); + + if (typeof window !== "undefined" && this === window) + throw("Z80: This function is a constructor; call it using operator new."); + + // All right, let's initialize the registers. + // First, the standard 8080 registers. + let a = 0x00; + let b = 0x00; + let c = 0x00; + let d = 0x00; + let e = 0x00; + let h = 0x00; + let l = 0x00; + // Now the special Z80 copies of the 8080 registers + // (the ones used for the SWAP instruction and such). + let a_prime = 0x00; + let b_prime = 0x00; + let c_prime = 0x00; + let d_prime = 0x00; + let e_prime = 0x00; + let h_prime = 0x00; + let l_prime = 0x00; + // And now the Z80 index registers. + let ix = 0x0000; + let iy = 0x0000; + // Then the "utility" registers: the interrupt vector, + // the memory refresh, the stack pointer, and the program counter. + let i = 0x00; + let r = 0x00; + let sp = 0xdff0; + let pc = 0x0000; + // We don't keep an F register for the flags, + // because most of the time we're only accessing a single flag, + // so we optimize for that case and use utility functions + // for the rarer occasions when we need to access the whole register. + let flags = {S:0, Z:0, Y:0, H:0, X:0, P:0, N:0, C:0}; + let flags_prime = {S:0, Z:0, Y:0, H:0, X:0, P:0, N:0, C:0}; + // And finally we have the interrupt mode and flip-flop registers. + let imode = 0; + let iff1 = 0; + let iff2 = 0; + + // These are all specific to this implementation, not Z80 features. + // Keep track of whether we've had a HALT instruction called. + let halted = false; + // EI and DI wait one instruction before they take effect; + // these flags tell us when we're in that wait state. + let do_delayed_di = false; + let do_delayed_ei = false; + // This tracks the number of cycles spent in a single instruction run, + // including processing any prefixes and handling interrupts. + let cycle_counter = 0; + + function getState() { + return { + b: b, + a: a, + c: c, + d: d, + e: e, + h: h, + l: l, + a_prime: a_prime, + b_prime: b_prime, + c_prime: c_prime, + d_prime: d_prime, + e_prime: e_prime, + h_prime: h_prime, + l_prime: l_prime, + ix : ix, + iy : iy, + i : i, + r : r, + sp : sp, + pc : pc, + flags: { + S: flags.S, + Z: flags.Z, + Y: flags.Y, + H: flags.H, + X: flags.X, + P: flags.P, + N: flags.N, + C: flags.C + }, + flags_prime: { + S: flags_prime.S, + Z: flags_prime.Z, + Y: flags_prime.Y, + H: flags_prime.H, + X: flags_prime.X, + P: flags_prime.P, + N: flags_prime.N, + C: flags_prime.C + }, + imode : imode, + iff1 : iff1, + iff2 : iff2, + halted : halted, + do_delayed_di : do_delayed_di, + do_delayed_ei : do_delayed_ei, + cycle_counter : cycle_counter + }; + } + + function setState(state) { + b = state.b; + a = state.a; + c = state.c; + d = state.d; + e = state.e; + h = state.h; + l = state.l; + a_prime = state.a_prime; + b_prime = state.b_prime; + c_prime = state.c_prime; + d_prime = state.d_prime; + e_prime = state.e_prime; + h_prime = state.h_prime; + l_prime = state.l_prime; + ix = state.ix; + iy = state.iy; + i = state.i; + r = state.r; + sp = state.sp; + pc = state.pc; + flags.S = state.flags.S; + flags.Z = state.flags.Z; + flags.Y = state.flags.Y; + flags.H = state.flags.H; + flags.X = state.flags.X; + flags.P = state.flags.P; + flags.N = state.flags.N; + flags.C = state.flags.C; + flags_prime.S = state.flags_prime.S; + flags_prime.Z = state.flags_prime.Z; + flags_prime.Y = state.flags_prime.Y; + flags_prime.H = state.flags_prime.H; + flags_prime.X = state.flags_prime.X; + flags_prime.P = state.flags_prime.P; + flags_prime.N = state.flags_prime.N; + flags_prime.C = state.flags_prime.C; + imode = state.imode; + iff1 = state.iff1; + iff2 = state.iff2; + halted = state.halted; + do_delayed_di = state.do_delayed_di; + do_delayed_ei = state.do_delayed_ei; + cycle_counter = state.cycle_counter; + } + +/////////////////////////////////////////////////////////////////////////////// +/// @public reset +/// +/// @brief Re-initialize the processor as if a reset or power on had occured +/////////////////////////////////////////////////////////////////////////////// +let reset = function() +{ + // These registers are the ones that have predictable states + // immediately following a power-on or a reset. + // The others are left alone, because their states are unpredictable. + sp = 0xdff0; + pc = 0x0000; + a = 0x00; + r = 0x00; + set_flags_register(0); + // Start up with interrupts disabled. + imode = 0; + iff1 = 0; + iff2 = 0; + // Don't start halted or in a delayed DI or EI. + halted = false; + do_delayed_di = false; + do_delayed_ei = false; + // Obviously we've not used any cycles yet. + cycle_counter = 0; +}; + +/////////////////////////////////////////////////////////////////////////////// +/// @public run_instruction +/// +/// @brief Runs a single instruction +/// +/// @return The number of T cycles the instruction took to run, +/// plus any time that went into handling interrupts that fired +/// while this instruction was executing +/////////////////////////////////////////////////////////////////////////////// +let run_instruction = function() +{ + if (!halted) + { + // If the previous instruction was a DI or an EI, + // we'll need to disable or enable interrupts + // after whatever instruction we're about to run is finished. + var doing_delayed_di = false, doing_delayed_ei = false; + if (do_delayed_di) + { + do_delayed_di = false; + doing_delayed_di = true; + } + else if (do_delayed_ei) + { + do_delayed_ei = false; + doing_delayed_ei = true; + } + + // R is incremented at the start of every instruction cycle, + // before the instruction actually runs. + // The high bit of R is not affected by this increment, + // it can only be changed using the LD R, A instruction. + r = (r & 0x80) | (((r & 0x7f) + 1) & 0x7f); + + // Read the byte at the PC and run the instruction it encodes. + var opcode = core.fetch_opcode(pc); + decode_instruction(opcode); + pc = (pc + 1) & 0xffff; + + // Actually do the delayed interrupt disable/enable if we have one. + if (doing_delayed_di) + { + iff1 = 0; + iff2 = 0; + } + else if (doing_delayed_ei) + { + iff1 = 1; + iff2 = 1; + } + + // And finally clear out the cycle counter for the next instruction + // before returning it to the emulator core. + var retval = cycle_counter; + cycle_counter = 0; + return retval; + } + else + { + // While we're halted, claim that we spent a cycle doing nothing, + // so that the rest of the emulator can still proceed. + return 1; + } +}; + +/////////////////////////////////////////////////////////////////////////////// +/// @public interrupt +/// +/// @brief Simulates pulsing the processor's INT (or NMI) pin +/// +/// @param non_maskable - true if this is a non-maskable interrupt +/// @param data - the value to be placed on the data bus, if needed +/////////////////////////////////////////////////////////////////////////////// +let interrupt = function(non_maskable, data) +{ + if (non_maskable) + { + // The high bit of R is not affected by this increment, + // it can only be changed using the LD R, A instruction. + r = (r & 0x80) | (((r & 0x7f) + 1) & 0x7f); + // Non-maskable interrupts are always handled the same way; + // clear IFF1 and then do a CALL 0x0066. + // Also, all interrupts reset the HALT state. + halted = false; + iff2 = iff1; + iff1 = 0; + push_word(pc); + pc = 0x66; + cycle_counter += 11; + } + else if (iff1) + { + // The high bit of R is not affected by this increment, + // it can only be changed using the LD R, A instruction. + r = (r & 0x80) | (((r & 0x7f) + 1) & 0x7f); + + halted = false; + iff1 = 0; + iff2 = 0; + + if (imode === 0) + { + // In the 8080-compatible interrupt mode, + // decode the content of the data bus as an instruction and run it. + // it's probably a RST instruction, which pushes (PC+1) onto the stack + // so we should decrement PC before we decode the instruction + pc = (pc - 1) & 0xffff; + decode_instruction(data); + pc = (pc + 1) & 0xffff; // increment PC upon return + cycle_counter += 2; + } + else if (imode === 1) + { + // Mode 1 is always just RST 0x38. + push_word(pc); + pc = 0x38; + cycle_counter += 13; + } + else if (imode === 2) + { + // Mode 2 uses the value on the data bus as in index + // into the vector table pointer to by the I register. + push_word(pc); + // The Z80 manual says that this address must be 2-byte aligned, + // but it doesn't appear that this is actually the case on the hardware, + // so we don't attempt to enforce that here. + var vector_address = ((i << 8) | data); + pc = core.mem_read(vector_address) | + (core.mem_read((vector_address + 1) & 0xffff) << 8); + + cycle_counter += 19; + } + } +}; + +/////////////////////////////////////////////////////////////////////////////// +/// The public API functions end here. +/// +/// What begins here are just general utility functions, used variously. +/////////////////////////////////////////////////////////////////////////////// +let decode_instruction = function(opcode) +{ + // The register-to-register loads and ALU instructions + // are all so uniform that we can decode them directly + // instead of going into the instruction array for them. + // This function gets the operand for all of these instructions. + var get_operand = function(opcode) + { + return ((opcode & 0x07) === 0) ? b : + ((opcode & 0x07) === 1) ? c : + ((opcode & 0x07) === 2) ? d : + ((opcode & 0x07) === 3) ? e : + ((opcode & 0x07) === 4) ? h : + ((opcode & 0x07) === 5) ? l : + ((opcode & 0x07) === 6) ? core.mem_read(l | (h << 8)) : a; + }; + + // Handle HALT right up front, because it fouls up our LD decoding + // by falling where LD (HL), (HL) ought to be. + if (opcode === 0x76) + { + halted = true; + } + else if ((opcode >= 0x40) && (opcode < 0x80)) + { + // This entire range is all 8-bit register loads. + // Get the operand and assign it to the correct destination. + var operand = get_operand(opcode); + + if (((opcode & 0x38) >>> 3) === 0) + b = operand; + else if (((opcode & 0x38) >>> 3) === 1) + c = operand; + else if (((opcode & 0x38) >>> 3) === 2) + d = operand; + else if (((opcode & 0x38) >>> 3) === 3) + e = operand; + else if (((opcode & 0x38) >>> 3) === 4) + h = operand; + else if (((opcode & 0x38) >>> 3) === 5) + l = operand; + else if (((opcode & 0x38) >>> 3) === 6) + core.mem_write(l | (h << 8), operand); + else if (((opcode & 0x38) >>> 3) === 7) + a = operand; + } + else if ((opcode >= 0x80) && (opcode < 0xc0)) + { + // These are the 8-bit register ALU instructions. + // We'll get the operand and then use this "jump table" + // to call the correct utility function for the instruction. + var operand = get_operand(opcode), + op_array = [do_add, do_adc, do_sub, do_sbc, + do_and, do_xor, do_or, do_cp]; + + op_array[(opcode & 0x38) >>> 3]( operand); + } + else + { + // This is one of the less formulaic instructions; + // we'll get the specific function for it from our array. + var func = instructions[opcode]; + func(); + } + + // Update the cycle counter with however many cycles + // the base instruction took. + // If this was a prefixed instruction, then + // the prefix handler has added its extra cycles already. + cycle_counter += cycle_counts[opcode]; +}; + +let get_signed_offset_byte = function(value) +{ + // This function requires some explanation. + // We just use JavaScript Number variables for our registers, + // not like a typed array or anything. + // That means that, when we have a byte value that's supposed + // to represent a signed offset, the value we actually see + // isn't signed at all, it's just a small integer. + // So, this function converts that byte into something JavaScript + // will recognize as signed, so we can easily do arithmetic with it. + // First, we clamp the value to a single byte, just in case. + value &= 0xff; + // We don't have to do anything if the value is positive. + if (value & 0x80) + { + // But if the value is negative, we need to manually un-two's-compliment it. + // I'm going to assume you can figure out what I meant by that, + // because I don't know how else to explain it. + // We could also just do value |= 0xffffff00, but I prefer + // not caring how many bits are in the integer representation + // of a JavaScript number in the currently running browser. + value = -((0xff & ~value) + 1); + } + return value; +}; + +let get_flags_register = function() +{ + // We need the whole F register for some reason. + // probably a PUSH AF instruction, + // so make the F register out of our separate flags. + return (flags.S << 7) | + (flags.Z << 6) | + (flags.Y << 5) | + (flags.H << 4) | + (flags.X << 3) | + (flags.P << 2) | + (flags.N << 1) | + (flags.C); +}; + +let get_flags_prime = function() +{ + // This is the same as the above for the F' register. + return (flags_prime.S << 7) | + (flags_prime.Z << 6) | + (flags_prime.Y << 5) | + (flags_prime.H << 4) | + (flags_prime.X << 3) | + (flags_prime.P << 2) | + (flags_prime.N << 1) | + (flags_prime.C); +}; + +let set_flags_register = function(operand) +{ + // We need to set the F register, probably for a POP AF, + // so break out the given value into our separate flags. + flags.S = (operand & 0x80) >>> 7; + flags.Z = (operand & 0x40) >>> 6; + flags.Y = (operand & 0x20) >>> 5; + flags.H = (operand & 0x10) >>> 4; + flags.X = (operand & 0x08) >>> 3; + flags.P = (operand & 0x04) >>> 2; + flags.N = (operand & 0x02) >>> 1; + flags.C = (operand & 0x01); +}; + +let set_flags_prime = function(operand) +{ + // Again, this is the same as the above for F'. + flags_prime.S = (operand & 0x80) >>> 7; + flags_prime.Z = (operand & 0x40) >>> 6; + flags_prime.Y = (operand & 0x20) >>> 5; + flags_prime.H = (operand & 0x10) >>> 4; + flags_prime.X = (operand & 0x08) >>> 3; + flags_prime.P = (operand & 0x04) >>> 2; + flags_prime.N = (operand & 0x02) >>> 1; + flags_prime.C = (operand & 0x01); +}; + +let update_xy_flags = function(result) +{ + // Most of the time, the undocumented flags + // (sometimes called X and Y, or 3 and 5), + // take their values from the corresponding bits + // of the result of the instruction, + // or from some other related value. + // This is a utility function to set those flags based on those bits. + flags.Y = (result & 0x20) >>> 5; + flags.X = (result & 0x08) >>> 3; +}; + +let get_parity = function(value) +{ + // We could try to actually calculate the parity every time, + // but why calculate what you can pre-calculate? + var parity_bits = [ + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 + ]; + return parity_bits[value]; +}; + +let push_word = function(operand) +{ + // Pretty obvious what this function does; given a 16-bit value, + // decrement the stack pointer, write the high byte to the new + // stack pointer location, then repeat for the low byte. + sp = (sp - 1) & 0xffff; + core.mem_write(sp, (operand & 0xff00) >>> 8); + sp = (sp - 1) & 0xffff; + core.mem_write(sp, operand & 0x00ff); +}; + +let pop_word = function() +{ + // Again, not complicated; read a byte off the top of the stack, + // increment the stack pointer, rinse and repeat. + var retval = core.mem_read(sp) & 0xff; + sp = (sp + 1) & 0xffff; + retval |= core.mem_read(sp) << 8; + sp = (sp + 1) & 0xffff; + return retval; +}; + +/////////////////////////////////////////////////////////////////////////////// +/// Now, the way most instructions work in this emulator is that they set up +/// their operands according to their addressing mode, and then they call a +/// utility function that handles all variations of that instruction. +/// Those utility functions begin here. +/////////////////////////////////////////////////////////////////////////////// +let do_conditional_absolute_jump = function(condition) +{ + // This function implements the JP [condition],nn instructions. + if (condition) + { + // We're taking this jump, so write the new PC, + // and then decrement the thing we just wrote, + // because the instruction decoder increments the PC + // unconditionally at the end of every instruction + // and we need to counteract that so we end up at the jump target. + pc = core.mem_read((pc + 1) & 0xffff) | + (core.mem_read((pc + 2) & 0xffff) << 8); + pc = (pc - 1) & 0xffff; + } + else + { + // We're not taking this jump, just move the PC past the operand. + pc = (pc + 2) & 0xffff; + } +}; + +let do_conditional_relative_jump = function(condition) +{ + // This function implements the JR [condition],n instructions. + if (condition) + { + // We need a few more cycles to actually take the jump. + cycle_counter += 5; + // Calculate the offset specified by our operand. + var offset = get_signed_offset_byte(core.mem_read((pc + 1) & 0xffff)); + // Add the offset to the PC, also skipping past this instruction. + pc = (pc + offset + 1) & 0xffff; + } + else + { + // No jump happening, just skip the operand. + pc = (pc + 1) & 0xffff; + } +}; + +let do_conditional_call = function(condition) +{ + // This function is the CALL [condition],nn instructions. + // If you've seen the previous functions, you know this drill. + if (condition) + { + cycle_counter += 7; + push_word((pc + 3) & 0xffff); + pc = core.mem_read((pc + 1) & 0xffff) | + (core.mem_read((pc + 2) & 0xffff) << 8); + pc = (pc - 1) & 0xffff; + } + else + { + pc = (pc + 2) & 0xffff; + } +}; + +let do_conditional_return = function(condition) +{ + if (condition) + { + cycle_counter += 6; + pc = (pop_word() - 1) & 0xffff; + } +}; + +let do_reset = function(address) +{ + // The RST [address] instructions go through here. + push_word((pc + 1) & 0xffff); + pc = (address - 1) & 0xffff; +}; + +let do_add = function(operand) +{ + // This is the ADD A, [operand] instructions. + // We'll do the literal addition, which includes any overflow, + // so that we can more easily figure out whether we had + // an overflow or a carry and set the flags accordingly. + var result = a + operand; + + // The great majority of the work for the arithmetic instructions + // turns out to be setting the flags rather than the actual operation. + flags.S = (result & 0x80) ? 1 : 0; + flags.Z = !(result & 0xff) ? 1 : 0; + flags.H = (((operand & 0x0f) + (a & 0x0f)) & 0x10) ? 1 : 0; + // An overflow has happened if the sign bits of the accumulator and the operand + // don't match the sign bit of the result value. + flags.P = ((a & 0x80) === (operand & 0x80)) && ((a & 0x80) !== (result & 0x80)) ? 1 : 0; + flags.N = 0; + flags.C = (result & 0x100) ? 1 : 0; + + a = result & 0xff; + update_xy_flags(a); +}; + +let do_adc = function(operand) +{ + var result = a + operand + flags.C; + + flags.S = (result & 0x80) ? 1 : 0; + flags.Z = !(result & 0xff) ? 1 : 0; + flags.H = (((operand & 0x0f) + (a & 0x0f) + flags.C) & 0x10) ? 1 : 0; + flags.P = ((a & 0x80) === (operand & 0x80)) && ((a & 0x80) !== (result & 0x80)) ? 1 : 0; + flags.N = 0; + flags.C = (result & 0x100) ? 1 : 0; + + a = result & 0xff; + update_xy_flags(a); +}; + +let do_sub = function(operand) +{ + var result = a - operand; + + flags.S = (result & 0x80) ? 1 : 0; + flags.Z = !(result & 0xff) ? 1 : 0; + flags.H = (((a & 0x0f) - (operand & 0x0f)) & 0x10) ? 1 : 0; + flags.P = ((a & 0x80) !== (operand & 0x80)) && ((a & 0x80) !== (result & 0x80)) ? 1 : 0; + flags.N = 1; + flags.C = (result & 0x100) ? 1 : 0; + + a = result & 0xff; + update_xy_flags(a); +}; + +let do_sbc = function(operand) +{ + var result = a - operand - flags.C; + + flags.S = (result & 0x80) ? 1 : 0; + flags.Z = !(result & 0xff) ? 1 : 0; + flags.H = (((a & 0x0f) - (operand & 0x0f) - flags.C) & 0x10) ? 1 : 0; + flags.P = ((a & 0x80) !== (operand & 0x80)) && ((a & 0x80) !== (result & 0x80)) ? 1 : 0; + flags.N = 1; + flags.C = (result & 0x100) ? 1 : 0; + + a = result & 0xff; + update_xy_flags(a); +}; + +let do_cp = function(operand) +{ + // A compare instruction is just a subtraction that doesn't save the value, + // so we implement it as... a subtraction that doesn't save the value. + var temp = a; + do_sub(operand); + a = temp; + // Since this instruction has no "result" value, the undocumented flags + // are set based on the operand instead. + update_xy_flags(operand); +}; + +let do_and = function(operand) +{ + // The logic instructions are all pretty straightforward. + a &= operand & 0xff; + flags.S = (a & 0x80) ? 1 : 0; + flags.Z = !a ? 1 : 0; + flags.H = 1; + flags.P = get_parity(a); + flags.N = 0; + flags.C = 0; + update_xy_flags(a); +}; + +let do_or = function(operand) +{ + a = (operand | a) & 0xff; + flags.S = (a & 0x80) ? 1 : 0; + flags.Z = !a ? 1 : 0; + flags.H = 0; + flags.P = get_parity(a); + flags.N = 0; + flags.C = 0; + update_xy_flags(a); +}; + +let do_xor = function(operand) +{ + a = (operand ^ a) & 0xff; + flags.S = (a & 0x80) ? 1 : 0; + flags.Z = !a ? 1 : 0; + flags.H = 0; + flags.P = get_parity(a); + flags.N = 0; + flags.C = 0; + update_xy_flags(a); +}; + +let do_inc = function(operand) +{ + var result = operand + 1; + + flags.S = (result & 0x80) ? 1 : 0; + flags.Z = !(result & 0xff) ? 1 : 0; + flags.H = ((operand & 0x0f) === 0x0f) ? 1 : 0; + // It's a good deal easier to detect overflow for an increment/decrement. + flags.P = (operand === 0x7f) ? 1 : 0; + flags.N = 0; + + result &= 0xff; + update_xy_flags(result); + + return result; +}; + +let do_dec = function(operand) +{ + var result = operand - 1; + + flags.S = (result & 0x80) ? 1 : 0; + flags.Z = !(result & 0xff) ? 1 : 0; + flags.H = ((operand & 0x0f) === 0x00) ? 1 : 0; + flags.P = (operand === 0x80) ? 1 : 0; + flags.N = 1; + + result &= 0xff; + update_xy_flags(result); + + return result; +}; + +let do_hl_add = function(operand) +{ + // The HL arithmetic instructions are the same as the A ones, + // just with twice as many bits happening. + var hl = l | (h << 8), result = hl + operand; + + flags.N = 0; + flags.C = (result & 0x10000) ? 1 : 0; + flags.H = (((hl & 0x0fff) + (operand & 0x0fff)) & 0x1000) ? 1 : 0; + + l = result & 0xff; + h = (result & 0xff00) >>> 8; + + update_xy_flags(h); +}; + +let do_hl_adc = function(operand) +{ + operand += flags.C; + var hl = l | (h << 8), result = hl + operand; + + flags.S = (result & 0x8000) ? 1 : 0; + flags.Z = !(result & 0xffff) ? 1 : 0; + flags.H = (((hl & 0x0fff) + (operand & 0x0fff)) & 0x1000) ? 1 : 0; + flags.P = ((hl & 0x8000) === (operand & 0x8000)) && ((result & 0x8000) !== (hl & 0x8000)) ? 1 : 0; + flags.N = 0; + flags.C = (result & 0x10000) ? 1 : 0; + + l = result & 0xff; + h = (result >>> 8) & 0xff; + + update_xy_flags(h); +}; + +let do_hl_sbc = function(operand) +{ + operand += flags.C; + var hl = l | (h << 8), result = hl - operand; + + flags.S = (result & 0x8000) ? 1 : 0; + flags.Z = !(result & 0xffff) ? 1 : 0; + flags.H = (((hl & 0x0fff) - (operand & 0x0fff)) & 0x1000) ? 1 : 0; + flags.P = ((hl & 0x8000) !== (operand & 0x8000)) && ((result & 0x8000) !== (hl & 0x8000)) ? 1 : 0; + flags.N = 1; + flags.C = (result & 0x10000) ? 1 : 0; + + l = result & 0xff; + h = (result >>> 8) & 0xff; + + update_xy_flags(h); +}; + +let do_in = function(port) +{ + var result = core.io_read(port); + + flags.S = (result & 0x80) ? 1 : 0; + flags.Z = result ? 0 : 1; + flags.H = 0; + flags.P = get_parity(result) ? 1 : 0; + flags.N = 0; + update_xy_flags(result); + + return result; +}; + +let do_neg = function() +{ + // This instruction is defined to not alter the register if it === 0x80. + if (a !== 0x80) + { + // This is a signed operation, so convert A to a signed value. + a = get_signed_offset_byte(a); + + a = (-a) & 0xff; + } + + flags.S = (a & 0x80) ? 1 : 0; + flags.Z = !a ? 1 : 0; + flags.H = (((-a) & 0x0f) > 0) ? 1 : 0; + flags.P = (a === 0x80) ? 1 : 0; + flags.N = 1; + flags.C = a ? 1 : 0; + update_xy_flags(a); +}; + +let do_ldi = function() +{ + // Copy the value that we're supposed to copy. + var read_value = core.mem_read(l | (h << 8)); + core.mem_write(e | (d << 8), read_value); + + // Increment DE and HL, and decrement BC. + var result = (e | (d << 8)) + 1; + e = result & 0xff; + d = (result & 0xff00) >>> 8; + result = (l | (h << 8)) + 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + result = (c | (b << 8)) - 1; + c = result & 0xff; + b = (result & 0xff00) >>> 8; + + flags.H = 0; + flags.P = (c || b) ? 1 : 0; + flags.N = 0; + flags.Y = ((a + read_value) & 0x02) >>> 1; + flags.X = ((a + read_value) & 0x08) >>> 3; +}; + +let do_cpi = function() +{ + var temp_carry = flags.C; + var read_value = core.mem_read(l | (h << 8)) + do_cp(read_value); + flags.C = temp_carry; + flags.Y = ((a - read_value - flags.H) & 0x02) >>> 1; + flags.X = ((a - read_value - flags.H) & 0x08) >>> 3; + + var result = (l | (h << 8)) + 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + result = (c | (b << 8)) - 1; + c = result & 0xff; + b = (result & 0xff00) >>> 8; + + flags.P = result ? 1 : 0; +}; + +let do_ini = function() +{ + b = do_dec(b); + + core.mem_write(l | (h << 8), core.io_read((b << 8) | c)); + + var result = (l | (h << 8)) + 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + + flags.N = 1; +}; + +let do_outi = function() +{ + core.io_write((b << 8) | c, core.mem_read(l | (h << 8))); + + var result = (l | (h << 8)) + 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + + b = do_dec(b); + flags.N = 1; +}; + +let do_ldd = function() +{ + flags.N = 0; + flags.H = 0; + + var read_value = core.mem_read(l | (h << 8)); + core.mem_write(e | (d << 8), read_value); + + var result = (e | (d << 8)) - 1; + e = result & 0xff; + d = (result & 0xff00) >>> 8; + result = (l | (h << 8)) - 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + result = (c | (b << 8)) - 1; + c = result & 0xff; + b = (result & 0xff00) >>> 8; + + flags.P = (c || b) ? 1 : 0; + flags.Y = ((a + read_value) & 0x02) >>> 1; + flags.X = ((a + read_value) & 0x08) >>> 3; +}; + +let do_cpd = function() +{ + var temp_carry = flags.C + var read_value = core.mem_read(l | (h << 8)) + do_cp(read_value); + flags.C = temp_carry; + flags.Y = ((a - read_value - flags.H) & 0x02) >>> 1; + flags.X = ((a - read_value - flags.H) & 0x08) >>> 3; + + var result = (l | (h << 8)) - 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + result = (c | (b << 8)) - 1; + c = result & 0xff; + b = (result & 0xff00) >>> 8; + + flags.P = result ? 1 : 0; +}; + +let do_ind = function() +{ + b = do_dec(b); + + core.mem_write(l | (h << 8), core.io_read((b << 8) | c)); + + var result = (l | (h << 8)) - 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + + flags.N = 1; +}; + +let do_outd = function() +{ + core.io_write((b << 8) | c, core.mem_read(l | (h << 8))); + + var result = (l | (h << 8)) - 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; + + b = do_dec(b); + flags.N = 1; +}; + +let do_rlc = function(operand) +{ + flags.N = 0; + flags.H = 0; + + flags.C = (operand & 0x80) >>> 7; + operand = ((operand << 1) | flags.C) & 0xff; + + flags.Z = !operand ? 1 : 0; + flags.P = get_parity(operand); + flags.S = (operand & 0x80) ? 1 : 0; + update_xy_flags(operand); + + return operand; +}; + +let do_rrc = function(operand) +{ + flags.N = 0; + flags.H = 0; + + flags.C = operand & 1; + operand = ((operand >>> 1) & 0x7f) | (flags.C << 7); + + flags.Z = !(operand & 0xff) ? 1 : 0; + flags.P = get_parity(operand); + flags.S = (operand & 0x80) ? 1 : 0; + update_xy_flags(operand); + + return operand & 0xff; +}; + +let do_rl = function(operand) +{ + flags.N = 0; + flags.H = 0; + + var temp = flags.C; + flags.C = (operand & 0x80) >>> 7; + operand = ((operand << 1) | temp) & 0xff; + + flags.Z = !operand ? 1 : 0; + flags.P = get_parity(operand); + flags.S = (operand & 0x80) ? 1 : 0; + update_xy_flags(operand); + + return operand; +}; + +let do_rr = function(operand) +{ + flags.N = 0; + flags.H = 0; + + var temp = flags.C; + flags.C = operand & 1; + operand = ((operand >>> 1) & 0x7f) | (temp << 7); + + flags.Z = !operand ? 1 : 0; + flags.P = get_parity(operand); + flags.S = (operand & 0x80) ? 1 : 0; + update_xy_flags(operand); + + return operand; +}; + +let do_sla = function(operand) +{ + flags.N = 0; + flags.H = 0; + + flags.C = (operand & 0x80) >>> 7; + operand = (operand << 1) & 0xff; + + flags.Z = !operand ? 1 : 0; + flags.P = get_parity(operand); + flags.S = (operand & 0x80) ? 1 : 0; + update_xy_flags(operand); + + return operand; +}; + +let do_sra = function(operand) +{ + flags.N = 0; + flags.H = 0; + + flags.C = operand & 1; + operand = ((operand >>> 1) & 0x7f) | (operand & 0x80); + + flags.Z = !operand ? 1 : 0; + flags.P = get_parity(operand); + flags.S = (operand & 0x80) ? 1 : 0; + update_xy_flags(operand); + + return operand; +}; + +let do_sll = function(operand) +{ + flags.N = 0; + flags.H = 0; + + flags.C = (operand & 0x80) >>> 7; + operand = ((operand << 1) & 0xff) | 1; + + flags.Z = !operand ? 1 : 0; + flags.P = get_parity(operand); + flags.S = (operand & 0x80) ? 1 : 0; + update_xy_flags(operand); + + return operand; +}; + +let do_srl = function(operand) +{ + flags.N = 0; + flags.H = 0; + + flags.C = operand & 1; + operand = (operand >>> 1) & 0x7f; + + flags.Z = !operand ? 1 : 0; + flags.P = get_parity(operand); + flags.S = 0; + update_xy_flags(operand); + + return operand; +}; + +let do_ix_add = function(operand) +{ + flags.N = 0; + + var result = ix + operand; + + flags.C = (result & 0x10000) ? 1 : 0; + flags.H = (((ix & 0xfff) + (operand & 0xfff)) & 0x1000) ? 1 : 0; + update_xy_flags((result & 0xff00) >>> 8); + + ix = result; +}; + + +/////////////////////////////////////////////////////////////////////////////// +/// This table contains the implementations for the instructions that weren't +/// implemented directly in the decoder function (everything but the 8-bit +/// register loads and the accumulator ALU instructions, in other words). +/// Similar tables for the ED and DD/FD prefixes follow this one. +/////////////////////////////////////////////////////////////////////////////// +let instructions = []; + +// 0x00 : NOP +instructions[0x00] = function() { }; +// 0x01 : LD BC, nn +instructions[0x01] = function() +{ + pc = (pc + 1) & 0xffff; + c = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + b = core.mem_read(pc); +}; +// 0x02 : LD (BC), A +instructions[0x02] = function() +{ + core.mem_write(c | (b << 8), a); +}; +// 0x03 : INC BC +instructions[0x03] = function() +{ + var result = (c | (b << 8)); + result += 1; + c = result & 0xff; + b = (result & 0xff00) >>> 8; +}; +// 0x04 : INC B +instructions[0x04] = function() +{ + b = do_inc(b); +}; +// 0x05 : DEC B +instructions[0x05] = function() +{ + b = do_dec(b); +}; +// 0x06 : LD B, n +instructions[0x06] = function() +{ + pc = (pc + 1) & 0xffff; + b = core.mem_read(pc); +}; +// 0x07 : RLCA +instructions[0x07] = function() +{ + // This instruction is implemented as a special case of the + // more general Z80-specific RLC instruction. + // Specifially, RLCA is a version of RLC A that affects fewer flags. + // The same applies to RRCA, RLA, and RRA. + var temp_s = flags.S, temp_z = flags.Z, temp_p = flags.P; + a = do_rlc(a); + flags.S = temp_s; + flags.Z = temp_z; + flags.P = temp_p; +}; +// 0x08 : EX AF, AF' +instructions[0x08] = function() +{ + var temp = a; + a = a_prime; + a_prime = temp; + + temp = get_flags_register(); + set_flags_register(get_flags_prime()); + set_flags_prime(temp); +}; +// 0x09 : ADD HL, BC +instructions[0x09] = function() +{ + do_hl_add(c | (b << 8)); +}; +// 0x0a : LD A, (BC) +instructions[0x0a] = function() +{ + a = core.mem_read(c | (b << 8)); +}; +// 0x0b : DEC BC +instructions[0x0b] = function() +{ + var result = (c | (b << 8)); + result -= 1; + c = result & 0xff; + b = (result & 0xff00) >>> 8; +}; +// 0x0c : INC C +instructions[0x0c] = function() +{ + c = do_inc(c); +}; +// 0x0d : DEC C +instructions[0x0d] = function() +{ + c = do_dec(c); +}; +// 0x0e : LD C, n +instructions[0x0e] = function() +{ + pc = (pc + 1) & 0xffff; + c = core.mem_read(pc); +}; +// 0x0f : RRCA +instructions[0x0f] = function() +{ + var temp_s = flags.S, temp_z = flags.Z, temp_p = flags.P; + a = do_rrc(a); + flags.S = temp_s; + flags.Z = temp_z; + flags.P = temp_p; +}; +// 0x10 : DJNZ nn +instructions[0x10] = function() +{ + b = (b - 1) & 0xff; + do_conditional_relative_jump(b !== 0); +}; +// 0x11 : LD DE, nn +instructions[0x11] = function() +{ + pc = (pc + 1) & 0xffff; + e = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + d = core.mem_read(pc); +}; +// 0x12 : LD (DE), A +instructions[0x12] = function() +{ + core.mem_write(e | (d << 8), a); +}; +// 0x13 : INC DE +instructions[0x13] = function() +{ + var result = (e | (d << 8)); + result += 1; + e = result & 0xff; + d = (result & 0xff00) >>> 8; +}; +// 0x14 : INC D +instructions[0x14] = function() +{ + d = do_inc(d); +}; +// 0x15 : DEC D +instructions[0x15] = function() +{ + d = do_dec(d); +}; +// 0x16 : LD D, n +instructions[0x16] = function() +{ + pc = (pc + 1) & 0xffff; + d = core.mem_read(pc); +}; +// 0x17 : RLA +instructions[0x17] = function() +{ + var temp_s = flags.S, temp_z = flags.Z, temp_p = flags.P; + a = do_rl(a); + flags.S = temp_s; + flags.Z = temp_z; + flags.P = temp_p; +}; +// 0x18 : JR n +instructions[0x18] = function() +{ + var offset = get_signed_offset_byte(core.mem_read((pc + 1) & 0xffff)); + pc = (pc + offset + 1) & 0xffff; +}; +// 0x19 : ADD HL, DE +instructions[0x19] = function() +{ + do_hl_add(e | (d << 8)); +}; +// 0x1a : LD A, (DE) +instructions[0x1a] = function() +{ + a = core.mem_read(e | (d << 8)); +}; +// 0x1b : DEC DE +instructions[0x1b] = function() +{ + var result = (e | (d << 8)); + result -= 1; + e = result & 0xff; + d = (result & 0xff00) >>> 8; +}; +// 0x1c : INC E +instructions[0x1c] = function() +{ + e = do_inc(e); +}; +// 0x1d : DEC E +instructions[0x1d] = function() +{ + e = do_dec(e); +}; +// 0x1e : LD E, n +instructions[0x1e] = function() +{ + pc = (pc + 1) & 0xffff; + e = core.mem_read(pc); +}; +// 0x1f : RRA +instructions[0x1f] = function() +{ + var temp_s = flags.S, temp_z = flags.Z, temp_p = flags.P; + a = do_rr(a); + flags.S = temp_s; + flags.Z = temp_z; + flags.P = temp_p; +}; +// 0x20 : JR NZ, n +instructions[0x20] = function() +{ + do_conditional_relative_jump(!flags.Z); +}; +// 0x21 : LD HL, nn +instructions[0x21] = function() +{ + pc = (pc + 1) & 0xffff; + l = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + h = core.mem_read(pc); +}; +// 0x22 : LD (nn), HL +instructions[0x22] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + core.mem_write(address, l); + core.mem_write((address + 1) & 0xffff, h); +}; +// 0x23 : INC HL +instructions[0x23] = function() +{ + var result = (l | (h << 8)); + result += 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; +}; +// 0x24 : INC H +instructions[0x24] = function() +{ + h = do_inc(h); +}; +// 0x25 : DEC H +instructions[0x25] = function() +{ + h = do_dec(h); +}; +// 0x26 : LD H, n +instructions[0x26] = function() +{ + pc = (pc + 1) & 0xffff; + h = core.mem_read(pc); +}; +// 0x27 : DAA +instructions[0x27] = function() +{ + var temp = a; + if (!flags.N) + { + if (flags.H || ((a & 0x0f) > 9)) + temp += 0x06; + if (flags.C || (a > 0x99)) + temp += 0x60; + } + else + { + if (flags.H || ((a & 0x0f) > 9)) + temp -= 0x06; + if (flags.C || (a > 0x99)) + temp -= 0x60; + } + + flags.S = (temp & 0x80) ? 1 : 0; + flags.Z = !(temp & 0xff) ? 1 : 0; + flags.H = ((a & 0x10) ^ (temp & 0x10)) ? 1 : 0; + flags.P = get_parity(temp & 0xff); + // DAA never clears the carry flag if it was already set, + // but it is able to set the carry flag if it was clear. + // Don't ask me, I don't know. + // Note also that we check for a BCD carry, instead of the usual. + flags.C = (flags.C || (a > 0x99)) ? 1 : 0; + + a = temp & 0xff; + + update_xy_flags(a); +}; +// 0x28 : JR Z, n +instructions[0x28] = function() +{ + do_conditional_relative_jump(!!flags.Z); +}; +// 0x29 : ADD HL, HL +instructions[0x29] = function() +{ + do_hl_add(l | (h << 8)); +}; +// 0x2a : LD HL, (nn) +instructions[0x2a] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + l = core.mem_read(address); + h = core.mem_read((address + 1) & 0xffff); +}; +// 0x2b : DEC HL +instructions[0x2b] = function() +{ + var result = (l | (h << 8)); + result -= 1; + l = result & 0xff; + h = (result & 0xff00) >>> 8; +}; +// 0x2c : INC L +instructions[0x2c] = function() +{ + l = do_inc(l); +}; +// 0x2d : DEC L +instructions[0x2d] = function() +{ + l = do_dec(l); +}; +// 0x2e : LD L, n +instructions[0x2e] = function() +{ + pc = (pc + 1) & 0xffff; + l = core.mem_read(pc); +}; +// 0x2f : CPL +instructions[0x2f] = function() +{ + a = (~a) & 0xff; + flags.N = 1; + flags.H = 1; + update_xy_flags(a); +}; +// 0x30 : JR NC, n +instructions[0x30] = function() +{ + do_conditional_relative_jump(!flags.C); +}; +// 0x31 : LD SP, nn +instructions[0x31] = function() +{ + sp = core.mem_read((pc + 1) & 0xffff) | + (core.mem_read((pc + 2) & 0xffff) << 8); + pc = (pc + 2) & 0xffff; +}; +// 0x32 : LD (nn), A +instructions[0x32] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + core.mem_write(address, a); +}; +// 0x33 : INC SP +instructions[0x33] = function() +{ + sp = (sp + 1) & 0xffff; +}; +// 0x34 : INC (HL) +instructions[0x34] = function() +{ + var address = l | (h << 8); + core.mem_write(address, do_inc(core.mem_read(address))); +}; +// 0x35 : DEC (HL) +instructions[0x35] = function() +{ + var address = l | (h << 8); + core.mem_write(address, do_dec(core.mem_read(address))); +}; +// 0x36 : LD (HL), n +instructions[0x36] = function() +{ + pc = (pc + 1) & 0xffff; + core.mem_write(l | (h << 8), core.mem_read(pc)); +}; +// 0x37 : SCF +instructions[0x37] = function() +{ + flags.N = 0; + flags.H = 0; + flags.C = 1; + update_xy_flags(a); +}; +// 0x38 : JR C, n +instructions[0x38] = function() +{ + do_conditional_relative_jump(!!flags.C); +}; +// 0x39 : ADD HL, SP +instructions[0x39] = function() +{ + do_hl_add(sp); +}; +// 0x3a : LD A, (nn) +instructions[0x3a] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + a = core.mem_read(address); +}; +// 0x3b : DEC SP +instructions[0x3b] = function() +{ + sp = (sp - 1) & 0xffff; +}; +// 0x3c : INC A +instructions[0x3c] = function() +{ + a = do_inc(a); +}; +// 0x3d : DEC A +instructions[0x3d] = function() +{ + a = do_dec(a); +}; +// 0x3e : LD A, n +instructions[0x3e] = function() +{ + a = core.mem_read((pc + 1) & 0xffff); + pc = (pc + 1) & 0xffff; +}; +// 0x3f : CCF +instructions[0x3f] = function() +{ + flags.N = 0; + flags.H = flags.C; + flags.C = flags.C ? 0 : 1; + update_xy_flags(a); +}; +// 0xc0 : RET NZ +instructions[0xc0] = function() +{ + do_conditional_return(!flags.Z); +}; +// 0xc1 : POP BC +instructions[0xc1] = function() +{ + var result = pop_word(); + c = result & 0xff; + b = (result & 0xff00) >>> 8; +}; +// 0xc2 : JP NZ, nn +instructions[0xc2] = function() +{ + do_conditional_absolute_jump(!flags.Z); +}; +// 0xc3 : JP nn +instructions[0xc3] = function() +{ + pc = core.mem_read((pc + 1) & 0xffff) | + (core.mem_read((pc + 2) & 0xffff) << 8); + pc = (pc - 1) & 0xffff; +}; +// 0xc4 : CALL NZ, nn +instructions[0xc4] = function() +{ + do_conditional_call(!flags.Z); +}; +// 0xc5 : PUSH BC +instructions[0xc5] = function() +{ + push_word(c | (b << 8)); +}; +// 0xc6 : ADD A, n +instructions[0xc6] = function() +{ + pc = (pc + 1) & 0xffff; + do_add(core.mem_read(pc)); +}; +// 0xc7 : RST 00h +instructions[0xc7] = function() +{ + do_reset(0x00); +}; +// 0xc8 : RET Z +instructions[0xc8] = function() +{ + do_conditional_return(!!flags.Z); +}; +// 0xc9 : RET +instructions[0xc9] = function() +{ + pc = (pop_word() - 1) & 0xffff; +}; +// 0xca : JP Z, nn +instructions[0xca] = function() +{ + do_conditional_absolute_jump(!!flags.Z); +}; +// 0xcb : CB Prefix +instructions[0xcb] = function() +{ + // R is incremented at the start of the second instruction cycle, + // before the instruction actually runs. + // The high bit of R is not affected by this increment, + // it can only be changed using the LD R, A instruction. + r = (r & 0x80) | (((r & 0x7f) + 1) & 0x7f); + + // We don't have a table for this prefix, + // the instructions are all so uniform that we can directly decode them. + pc = (pc + 1) & 0xffff; + var opcode = core.mem_read(pc), + bit_number = (opcode & 0x38) >>> 3, + reg_code = opcode & 0x07; + + if (opcode < 0x40) + { + // Shift/rotate instructions + var op_array = [do_rlc, do_rrc, do_rl, do_rr, + do_sla, do_sra, do_sll, do_srl]; + + if (reg_code === 0) + b = op_array[bit_number]( b); + else if (reg_code === 1) + c = op_array[bit_number]( c); + else if (reg_code === 2) + d = op_array[bit_number]( d); + else if (reg_code === 3) + e = op_array[bit_number]( e); + else if (reg_code === 4) + h = op_array[bit_number]( h); + else if (reg_code === 5) + l = op_array[bit_number]( l); + else if (reg_code === 6) + core.mem_write(l | (h << 8), + op_array[bit_number]( core.mem_read(l | (h << 8)))); + else if (reg_code === 7) + a = op_array[bit_number]( a); + } + else if (opcode < 0x80) + { + // BIT instructions + if (reg_code === 0) + flags.Z = !(b & (1 << bit_number)) ? 1 : 0; + else if (reg_code === 1) + flags.Z = !(c & (1 << bit_number)) ? 1 : 0; + else if (reg_code === 2) + flags.Z = !(d & (1 << bit_number)) ? 1 : 0; + else if (reg_code === 3) + flags.Z = !(e & (1 << bit_number)) ? 1 : 0; + else if (reg_code === 4) + flags.Z = !(h & (1 << bit_number)) ? 1 : 0; + else if (reg_code === 5) + flags.Z = !(l & (1 << bit_number)) ? 1 : 0; + else if (reg_code === 6) + flags.Z = !((core.mem_read(l | (h << 8))) & (1 << bit_number)) ? 1 : 0; + else if (reg_code === 7) + flags.Z = !(a & (1 << bit_number)) ? 1 : 0; + + flags.N = 0; + flags.H = 1; + flags.P = flags.Z; + flags.S = ((bit_number === 7) && !flags.Z) ? 1 : 0; + // For the BIT n, (HL) instruction, the X and Y flags are obtained + // from what is apparently an internal temporary register used for + // some of the 16-bit arithmetic instructions. + // I haven't implemented that register here, + // so for now we'll set X and Y the same way for every BIT opcode, + // which means that they will usually be wrong for BIT n, (HL). + flags.Y = ((bit_number === 5) && !flags.Z) ? 1 : 0; + flags.X = ((bit_number === 3) && !flags.Z) ? 1 : 0; + } + else if (opcode < 0xc0) + { + // RES instructions + if (reg_code === 0) + b &= (0xff & ~(1 << bit_number)); + else if (reg_code === 1) + c &= (0xff & ~(1 << bit_number)); + else if (reg_code === 2) + d &= (0xff & ~(1 << bit_number)); + else if (reg_code === 3) + e &= (0xff & ~(1 << bit_number)); + else if (reg_code === 4) + h &= (0xff & ~(1 << bit_number)); + else if (reg_code === 5) + l &= (0xff & ~(1 << bit_number)); + else if (reg_code === 6) + core.mem_write(l | (h << 8), + core.mem_read(l | (h << 8)) & ~(1 << bit_number)); + else if (reg_code === 7) + a &= (0xff & ~(1 << bit_number)); + } + else + { + // SET instructions + if (reg_code === 0) + b |= (1 << bit_number); + else if (reg_code === 1) + c |= (1 << bit_number); + else if (reg_code === 2) + d |= (1 << bit_number); + else if (reg_code === 3) + e |= (1 << bit_number); + else if (reg_code === 4) + h |= (1 << bit_number); + else if (reg_code === 5) + l |= (1 << bit_number); + else if (reg_code === 6) + core.mem_write(l | (h << 8), + core.mem_read(l | (h << 8)) | (1 << bit_number)); + else if (reg_code === 7) + a |= (1 << bit_number); + } + + cycle_counter += cycle_counts_cb[opcode]; +}; +// 0xcc : CALL Z, nn +instructions[0xcc] = function() +{ + do_conditional_call(!!flags.Z); +}; +// 0xcd : CALL nn +instructions[0xcd] = function() +{ + push_word((pc + 3) & 0xffff); + pc = core.mem_read((pc + 1) & 0xffff) | + (core.mem_read((pc + 2) & 0xffff) << 8); + pc = (pc - 1) & 0xffff; +}; +// 0xce : ADC A, n +instructions[0xce] = function() +{ + pc = (pc + 1) & 0xffff; + do_adc(core.mem_read(pc)); +}; +// 0xcf : RST 08h +instructions[0xcf] = function() +{ + do_reset(0x08); +}; +// 0xd0 : RET NC +instructions[0xd0] = function() +{ + do_conditional_return(!flags.C); +}; +// 0xd1 : POP DE +instructions[0xd1] = function() +{ + var result = pop_word(); + e = result & 0xff; + d = (result & 0xff00) >>> 8; +}; +// 0xd2 : JP NC, nn +instructions[0xd2] = function() +{ + do_conditional_absolute_jump(!flags.C); +}; +// 0xd3 : OUT (n), A +instructions[0xd3] = function() +{ + pc = (pc + 1) & 0xffff; + core.io_write((a << 8) | core.mem_read(pc), a); +}; +// 0xd4 : CALL NC, nn +instructions[0xd4] = function() +{ + do_conditional_call(!flags.C); +}; +// 0xd5 : PUSH DE +instructions[0xd5] = function() +{ + push_word(e | (d << 8)); +}; +// 0xd6 : SUB n +instructions[0xd6] = function() +{ + pc = (pc + 1) & 0xffff; + do_sub(core.mem_read(pc)); +}; +// 0xd7 : RST 10h +instructions[0xd7] = function() +{ + do_reset(0x10); +}; +// 0xd8 : RET C +instructions[0xd8] = function() +{ + do_conditional_return(!!flags.C); +}; +// 0xd9 : EXX +instructions[0xd9] = function() +{ + var temp = b; + b = b_prime; + b_prime = temp; + temp = c; + c = c_prime; + c_prime = temp; + temp = d; + d = d_prime; + d_prime = temp; + temp = e; + e = e_prime; + e_prime = temp; + temp = h; + h = h_prime; + h_prime = temp; + temp = l; + l = l_prime; + l_prime = temp; +}; +// 0xda : JP C, nn +instructions[0xda] = function() +{ + do_conditional_absolute_jump(!!flags.C); +}; +// 0xdb : IN A, (n) +instructions[0xdb] = function() +{ + pc = (pc + 1) & 0xffff; + a = core.io_read((a << 8) | core.mem_read(pc)); +}; +// 0xdc : CALL C, nn +instructions[0xdc] = function() +{ + do_conditional_call(!!flags.C); +}; +// 0xdd : DD Prefix (IX instructions) +instructions[0xdd] = function() +{ + // R is incremented at the start of the second instruction cycle, + // before the instruction actually runs. + // The high bit of R is not affected by this increment, + // it can only be changed using the LD R, A instruction. + r = (r & 0x80) | (((r & 0x7f) + 1) & 0x7f); + + pc = (pc + 1) & 0xffff; + var opcode = core.mem_read(pc), + func = dd_instructions[opcode]; + + if (func) + { + //func = func.bind(this); + func(); + cycle_counter += cycle_counts_dd[opcode]; + } + else + { + // Apparently if a DD opcode doesn't exist, + // it gets treated as an unprefixed opcode. + // What we'll do to handle that is just back up the + // program counter, so that this byte gets decoded + // as a normal instruction. + pc = (pc - 1) & 0xffff; + // And we'll add in the cycle count for a NOP. + cycle_counter += cycle_counts[0]; + } +}; +// 0xde : SBC n +instructions[0xde] = function() +{ + pc = (pc + 1) & 0xffff; + do_sbc(core.mem_read(pc)); +}; +// 0xdf : RST 18h +instructions[0xdf] = function() +{ + do_reset(0x18); +}; +// 0xe0 : RET PO +instructions[0xe0] = function() +{ + do_conditional_return(!flags.P); +}; +// 0xe1 : POP HL +instructions[0xe1] = function() +{ + var result = pop_word(); + l = result & 0xff; + h = (result & 0xff00) >>> 8; +}; +// 0xe2 : JP PO, (nn) +instructions[0xe2] = function() +{ + do_conditional_absolute_jump(!flags.P); +}; +// 0xe3 : EX (SP), HL +instructions[0xe3] = function() +{ + var temp = core.mem_read(sp); + core.mem_write(sp, l); + l = temp; + temp = core.mem_read((sp + 1) & 0xffff); + core.mem_write((sp + 1) & 0xffff, h); + h = temp; +}; +// 0xe4 : CALL PO, nn +instructions[0xe4] = function() +{ + do_conditional_call(!flags.P); +}; +// 0xe5 : PUSH HL +instructions[0xe5] = function() +{ + push_word(l | (h << 8)); +}; +// 0xe6 : AND n +instructions[0xe6] = function() +{ + pc = (pc + 1) & 0xffff; + do_and(core.mem_read(pc)); +}; +// 0xe7 : RST 20h +instructions[0xe7] = function() +{ + do_reset(0x20); +}; +// 0xe8 : RET PE +instructions[0xe8] = function() +{ + do_conditional_return(!!flags.P); +}; +// 0xe9 : JP (HL) +instructions[0xe9] = function() +{ + pc = l | (h << 8); + pc = (pc - 1) & 0xffff; +}; +// 0xea : JP PE, nn +instructions[0xea] = function() +{ + do_conditional_absolute_jump(!!flags.P); +}; +// 0xeb : EX DE, HL +instructions[0xeb] = function() +{ + var temp = d; + d = h; + h = temp; + temp = e; + e = l; + l = temp; +}; +// 0xec : CALL PE, nn +instructions[0xec] = function() +{ + do_conditional_call(!!flags.P); +}; +// 0xed : ED Prefix +instructions[0xed] = function() +{ + // R is incremented at the start of the second instruction cycle, + // before the instruction actually runs. + // The high bit of R is not affected by this increment, + // it can only be changed using the LD R, A instruction. + r = (r & 0x80) | (((r & 0x7f) + 1) & 0x7f); + + pc = (pc + 1) & 0xffff; + var opcode = core.mem_read(pc), + func = ed_instructions[opcode]; + + if (func) + { + //func = func.bind(this); + func(); + cycle_counter += cycle_counts_ed[opcode]; + } + else + { + // If the opcode didn't exist, the whole thing is a two-byte NOP. + cycle_counter += cycle_counts[0]; + } +}; +// 0xee : XOR n +instructions[0xee] = function() +{ + pc = (pc + 1) & 0xffff; + do_xor(core.mem_read(pc)); +}; +// 0xef : RST 28h +instructions[0xef] = function() +{ + do_reset(0x28); +}; +// 0xf0 : RET P +instructions[0xf0] = function() +{ + do_conditional_return(!flags.S); +}; +// 0xf1 : POP AF +instructions[0xf1] = function() +{ + var result = pop_word(); + set_flags_register(result & 0xff); + a = (result & 0xff00) >>> 8; +}; +// 0xf2 : JP P, nn +instructions[0xf2] = function() +{ + do_conditional_absolute_jump(!flags.S); +}; +// 0xf3 : DI +instructions[0xf3] = function() +{ + // DI doesn't actually take effect until after the next instruction. + do_delayed_di = true; +}; +// 0xf4 : CALL P, nn +instructions[0xf4] = function() +{ + do_conditional_call(!flags.S); +}; +// 0xf5 : PUSH AF +instructions[0xf5] = function() +{ + push_word(get_flags_register() | (a << 8)); +}; +// 0xf6 : OR n +instructions[0xf6] = function() +{ + pc = (pc + 1) & 0xffff; + do_or(core.mem_read(pc)); +}; +// 0xf7 : RST 30h +instructions[0xf7] = function() +{ + do_reset(0x30); +}; +// 0xf8 : RET M +instructions[0xf8] = function() +{ + do_conditional_return(!!flags.S); +}; +// 0xf9 : LD SP, HL +instructions[0xf9] = function() +{ + sp = l | (h << 8); +}; +// 0xfa : JP M, nn +instructions[0xfa] = function() +{ + do_conditional_absolute_jump(!!flags.S); +}; +// 0xfb : EI +instructions[0xfb] = function() +{ + // EI doesn't actually take effect until after the next instruction. + do_delayed_ei = true; +}; +// 0xfc : CALL M, nn +instructions[0xfc] = function() +{ + do_conditional_call(!!flags.S); +}; +// 0xfd : FD Prefix (IY instructions) +instructions[0xfd] = function() +{ + // R is incremented at the start of the second instruction cycle, + // before the instruction actually runs. + // The high bit of R is not affected by this increment, + // it can only be changed using the LD R, A instruction. + r = (r & 0x80) | (((r & 0x7f) + 1) & 0x7f); + + pc = (pc + 1) & 0xffff; + var opcode = core.mem_read(pc), + func = dd_instructions[opcode]; + + if (func) + { + // Rather than copy and paste all the IX instructions into IY instructions, + // what we'll do is sneakily copy IY into IX, run the IX instruction, + // and then copy the result into IY and restore the old IX. + var temp = ix; + ix = iy; + //func = func.bind(this); + func(); + iy = ix; + ix = temp; + + cycle_counter += cycle_counts_dd[opcode]; + } + else + { + // Apparently if an FD opcode doesn't exist, + // it gets treated as an unprefixed opcode. + // What we'll do to handle that is just back up the + // program counter, so that this byte gets decoded + // as a normal instruction. + pc = (pc - 1) & 0xffff; + // And we'll add in the cycle count for a NOP. + cycle_counter += cycle_counts[0]; + } +}; +// 0xfe : CP n +instructions[0xfe] = function() +{ + pc = (pc + 1) & 0xffff; + do_cp(core.mem_read(pc)); +}; +// 0xff : RST 38h +instructions[0xff] = function() +{ + do_reset(0x38); +}; + + +/////////////////////////////////////////////////////////////////////////////// +/// This table of ED opcodes is pretty sparse; +/// there are not very many valid ED-prefixed opcodes in the Z80, +/// and many of the ones that are valid are not documented. +/////////////////////////////////////////////////////////////////////////////// +let ed_instructions = []; +// 0x40 : IN B, (C) +ed_instructions[0x40] = function() +{ + b = do_in((b << 8) | c); +}; +// 0x41 : OUT (C), B +ed_instructions[0x41] = function() +{ + core.io_write((b << 8) | c, b); +}; +// 0x42 : SBC HL, BC +ed_instructions[0x42] = function() +{ + do_hl_sbc(c | (b << 8)); +}; +// 0x43 : LD (nn), BC +ed_instructions[0x43] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + core.mem_write(address, c); + core.mem_write((address + 1) & 0xffff, b); +}; +// 0x44 : NEG +ed_instructions[0x44] = function() +{ + do_neg(); +}; +// 0x45 : RETN +ed_instructions[0x45] = function() +{ + pc = (pop_word() - 1) & 0xffff; + iff1 = iff2; +}; +// 0x46 : IM 0 +ed_instructions[0x46] = function() +{ + imode = 0; +}; +// 0x47 : LD I, A +ed_instructions[0x47] = function() +{ + i = a +}; +// 0x48 : IN C, (C) +ed_instructions[0x48] = function() +{ + c = do_in((b << 8) | c); +}; +// 0x49 : OUT (C), C +ed_instructions[0x49] = function() +{ + core.io_write((b << 8) | c, c); +}; +// 0x4a : ADC HL, BC +ed_instructions[0x4a] = function() +{ + do_hl_adc(c | (b << 8)); +}; +// 0x4b : LD BC, (nn) +ed_instructions[0x4b] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + c = core.mem_read(address); + b = core.mem_read((address + 1) & 0xffff); +}; +// 0x4c : NEG (Undocumented) +ed_instructions[0x4c] = function() +{ + do_neg(); +}; +// 0x4d : RETI +ed_instructions[0x4d] = function() +{ + pc = (pop_word() - 1) & 0xffff; +}; +// 0x4e : IM 0 (Undocumented) +ed_instructions[0x4e] = function() +{ + imode = 0; +}; +// 0x4f : LD R, A +ed_instructions[0x4f] = function() +{ + r = a; +}; +// 0x50 : IN D, (C) +ed_instructions[0x50] = function() +{ + d = do_in((b << 8) | c); +}; +// 0x51 : OUT (C), D +ed_instructions[0x51] = function() +{ + core.io_write((b << 8) | c, d); +}; +// 0x52 : SBC HL, DE +ed_instructions[0x52] = function() +{ + do_hl_sbc(e | (d << 8)); +}; +// 0x53 : LD (nn), DE +ed_instructions[0x53] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + core.mem_write(address, e); + core.mem_write((address + 1) & 0xffff, d); +}; +// 0x54 : NEG (Undocumented) +ed_instructions[0x54] = function() +{ + do_neg(); +}; +// 0x55 : RETN +ed_instructions[0x55] = function() +{ + pc = (pop_word() - 1) & 0xffff; + iff1 = iff2; +}; +// 0x56 : IM 1 +ed_instructions[0x56] = function() +{ + imode = 1; +}; +// 0x57 : LD A, I +ed_instructions[0x57] = function() +{ + a = i; + flags.S = a & 0x80 ? 1 : 0; + flags.Z = a ? 0 : 1; + flags.H = 0; + flags.P = iff2; + flags.N = 0; + update_xy_flags(a); +}; +// 0x58 : IN E, (C) +ed_instructions[0x58] = function() +{ + e = do_in((b << 8) | c); +}; +// 0x59 : OUT (C), E +ed_instructions[0x59] = function() +{ + core.io_write((b << 8) | c, e); +}; +// 0x5a : ADC HL, DE +ed_instructions[0x5a] = function() +{ + do_hl_adc(e | (d << 8)); +}; +// 0x5b : LD DE, (nn) +ed_instructions[0x5b] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + e = core.mem_read(address); + d = core.mem_read((address + 1) & 0xffff); +}; +// 0x5c : NEG (Undocumented) +ed_instructions[0x5c] = function() +{ + do_neg(); +}; +// 0x5d : RETN +ed_instructions[0x5d] = function() +{ + pc = (pop_word() - 1) & 0xffff; + iff1 = iff2; +}; +// 0x5e : IM 2 +ed_instructions[0x5e] = function() +{ + imode = 2; +}; +// 0x5f : LD A, R +ed_instructions[0x5f] = function() +{ + a = r; + flags.S = a & 0x80 ? 1 : 0; + flags.Z = a ? 0 : 1; + flags.H = 0; + flags.P = iff2; + flags.N = 0; + update_xy_flags(a); +}; +// 0x60 : IN H, (C) +ed_instructions[0x60] = function() +{ + h = do_in((b << 8) | c); +}; +// 0x61 : OUT (C), H +ed_instructions[0x61] = function() +{ + core.io_write((b << 8) | c, h); +}; +// 0x62 : SBC HL, HL +ed_instructions[0x62] = function() +{ + do_hl_sbc(l | (h << 8)); +}; +// 0x63 : LD (nn), HL (Undocumented) +ed_instructions[0x63] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + core.mem_write(address, l); + core.mem_write((address + 1) & 0xffff, h); +}; +// 0x64 : NEG (Undocumented) +ed_instructions[0x64] = function() +{ + do_neg(); +}; +// 0x65 : RETN +ed_instructions[0x65] = function() +{ + pc = (pop_word() - 1) & 0xffff; + iff1 = iff2; +}; +// 0x66 : IM 0 +ed_instructions[0x66] = function() +{ + imode = 0; +}; +// 0x67 : RRD +ed_instructions[0x67] = function() +{ + var hl_value = core.mem_read(l | (h << 8)); + var temp1 = hl_value & 0x0f, temp2 = a & 0x0f; + hl_value = ((hl_value & 0xf0) >>> 4) | (temp2 << 4); + a = (a & 0xf0) | temp1; + core.mem_write(l | (h << 8), hl_value); + + flags.S = (a & 0x80) ? 1 : 0; + flags.Z = a ? 0 : 1; + flags.H = 0; + flags.P = get_parity(a) ? 1 : 0; + flags.N = 0; + update_xy_flags(a); +}; +// 0x68 : IN L, (C) +ed_instructions[0x68] = function() +{ + l = do_in((b << 8) | c); +}; +// 0x69 : OUT (C), L +ed_instructions[0x69] = function() +{ + core.io_write((b << 8) | c, l); +}; +// 0x6a : ADC HL, HL +ed_instructions[0x6a] = function() +{ + do_hl_adc(l | (h << 8)); +}; +// 0x6b : LD HL, (nn) (Undocumented) +ed_instructions[0x6b] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + l = core.mem_read(address); + h = core.mem_read((address + 1) & 0xffff); +}; +// 0x6c : NEG (Undocumented) +ed_instructions[0x6c] = function() +{ + do_neg(); +}; +// 0x6d : RETN +ed_instructions[0x6d] = function() +{ + pc = (pop_word() - 1) & 0xffff; + iff1 = iff2; +}; +// 0x6e : IM 0 (Undocumented) +ed_instructions[0x6e] = function() +{ + imode = 0; +}; +// 0x6f : RLD +ed_instructions[0x6f] = function() +{ + var hl_value = core.mem_read(l | (h << 8)); + var temp1 = hl_value & 0xf0, temp2 = a & 0x0f; + hl_value = ((hl_value & 0x0f) << 4) | temp2; + a = (a & 0xf0) | (temp1 >>> 4); + core.mem_write(l | (h << 8), hl_value); + + flags.S = (a & 0x80) ? 1 : 0; + flags.Z = a ? 0 : 1; + flags.H = 0; + flags.P = get_parity(a) ? 1 : 0; + flags.N = 0; + update_xy_flags(a); +}; +// 0x70 : IN (C) (Undocumented) +ed_instructions[0x70] = function() +{ + do_in((b << 8) | c); +}; +// 0x71 : OUT (C), 0 (Undocumented) +ed_instructions[0x71] = function() +{ + core.io_write((b << 8) | c, 0); +}; +// 0x72 : SBC HL, SP +ed_instructions[0x72] = function() +{ + do_hl_sbc(sp); +}; +// 0x73 : LD (nn), SP +ed_instructions[0x73] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + core.mem_write(address, sp & 0xff); + core.mem_write((address + 1) & 0xffff, (sp >>> 8) & 0xff); +}; +// 0x74 : NEG (Undocumented) +ed_instructions[0x74] = function() +{ + do_neg(); +}; +// 0x75 : RETN +ed_instructions[0x75] = function() +{ + pc = (pop_word() - 1) & 0xffff; + iff1 = iff2; +}; +// 0x76 : IM 1 +ed_instructions[0x76] = function() +{ + imode = 1; +}; +// 0x78 : IN A, (C) +ed_instructions[0x78] = function() +{ + a = do_in((b << 8) | c); +}; +// 0x79 : OUT (C), A +ed_instructions[0x79] = function() +{ + core.io_write((b << 8) | c, a); +}; +// 0x7a : ADC HL, SP +ed_instructions[0x7a] = function() +{ + do_hl_adc(sp); +}; +// 0x7b : LD SP, (nn) +ed_instructions[0x7b] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= core.mem_read(pc) << 8; + + sp = core.mem_read(address); + sp |= core.mem_read((address + 1) & 0xffff) << 8; +}; +// 0x7c : NEG (Undocumented) +ed_instructions[0x7c] = function() +{ + do_neg(); +}; +// 0x7d : RETN +ed_instructions[0x7d] = function() +{ + pc = (pop_word() - 1) & 0xffff; + iff1 = iff2; +}; +// 0x7e : IM 2 +ed_instructions[0x7e] = function() +{ + imode = 2; +}; +// 0xa0 : LDI +ed_instructions[0xa0] = function() +{ + do_ldi(); +}; +// 0xa1 : CPI +ed_instructions[0xa1] = function() +{ + do_cpi(); +}; +// 0xa2 : INI +ed_instructions[0xa2] = function() +{ + do_ini(); +}; +// 0xa3 : OUTI +ed_instructions[0xa3] = function() +{ + do_outi(); +}; +// 0xa8 : LDD +ed_instructions[0xa8] = function() +{ + do_ldd(); +}; +// 0xa9 : CPD +ed_instructions[0xa9] = function() +{ + do_cpd(); +}; +// 0xaa : IND +ed_instructions[0xaa] = function() +{ + do_ind(); +}; +// 0xab : OUTD +ed_instructions[0xab] = function() +{ + do_outd(); +}; +// 0xb0 : LDIR +ed_instructions[0xb0] = function() +{ + do_ldi(); + if (b || c) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; +// 0xb1 : CPIR +ed_instructions[0xb1] = function() +{ + do_cpi(); + if (!flags.Z && (b || c)) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; +// 0xb2 : INIR +ed_instructions[0xb2] = function() +{ + do_ini(); + if (b) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; +// 0xb3 : OTIR +ed_instructions[0xb3] = function() +{ + do_outi(); + if (b) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; +// 0xb8 : LDDR +ed_instructions[0xb8] = function() +{ + do_ldd(); + if (b || c) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; +// 0xb9 : CPDR +ed_instructions[0xb9] = function() +{ + do_cpd(); + if (!flags.Z && (b || c)) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; +// 0xba : INDR +ed_instructions[0xba] = function() +{ + do_ind(); + if (b) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; +// 0xbb : OTDR +ed_instructions[0xbb] = function() +{ + do_outd(); + if (b) + { + cycle_counter += 5; + pc = (pc - 2) & 0xffff; + } +}; + + +/////////////////////////////////////////////////////////////////////////////// +/// Like ED, this table is quite sparse, +/// and many of the opcodes here are also undocumented. +/// The undocumented instructions here are those that deal with only one byte +/// of the two-byte IX register; the bytes are designed IXH and IXL here. +/////////////////////////////////////////////////////////////////////////////// +let dd_instructions = []; +// 0x09 : ADD IX, BC +dd_instructions[0x09] = function() +{ + do_ix_add(c | (b << 8)); +}; +// 0x19 : ADD IX, DE +dd_instructions[0x19] = function() +{ + do_ix_add(e | (d << 8)); +}; +// 0x21 : LD IX, nn +dd_instructions[0x21] = function() +{ + pc = (pc + 1) & 0xffff; + ix = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + ix |= (core.mem_read(pc) << 8); +}; +// 0x22 : LD (nn), IX +dd_instructions[0x22] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= (core.mem_read(pc) << 8); + + core.mem_write(address, ix & 0xff); + core.mem_write((address + 1) & 0xffff, (ix >>> 8) & 0xff); +}; +// 0x23 : INC IX +dd_instructions[0x23] = function() +{ + ix = (ix + 1) & 0xffff; +}; +// 0x24 : INC IXH (Undocumented) +dd_instructions[0x24] = function() +{ + ix = (do_inc(ix >>> 8) << 8) | (ix & 0xff); +}; +// 0x25 : DEC IXH (Undocumented) +dd_instructions[0x25] = function() +{ + ix = (do_dec(ix >>> 8) << 8) | (ix & 0xff); +}; +// 0x26 : LD IXH, n (Undocumented) +dd_instructions[0x26] = function() +{ + pc = (pc + 1) & 0xffff; + ix = (core.mem_read(pc) << 8) | (ix & 0xff); +}; +// 0x29 : ADD IX, IX +dd_instructions[0x29] = function() +{ + do_ix_add(ix); +}; +// 0x2a : LD IX, (nn) +dd_instructions[0x2a] = function() +{ + pc = (pc + 1) & 0xffff; + var address = core.mem_read(pc); + pc = (pc + 1) & 0xffff; + address |= (core.mem_read(pc) << 8); + + ix = core.mem_read(address); + ix |= (core.mem_read((address + 1) & 0xffff) << 8); +}; +// 0x2b : DEC IX +dd_instructions[0x2b] = function() +{ + ix = (ix - 1) & 0xffff; +}; +// 0x2c : INC IXL (Undocumented) +dd_instructions[0x2c] = function() +{ + ix = do_inc(ix & 0xff) | (ix & 0xff00); +}; +// 0x2d : DEC IXL (Undocumented) +dd_instructions[0x2d] = function() +{ + ix = do_dec(ix & 0xff) | (ix & 0xff00); +}; +// 0x2e : LD IXL, n (Undocumented) +dd_instructions[0x2e] = function() +{ + pc = (pc + 1) & 0xffff; + ix = (core.mem_read(pc) & 0xff) | (ix & 0xff00); +}; +// 0x34 : INC (IX+n) +dd_instructions[0x34] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)), + value = core.mem_read((offset + ix) & 0xffff); + core.mem_write((offset + ix) & 0xffff, do_inc(value)); +}; +// 0x35 : DEC (IX+n) +dd_instructions[0x35] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)), + value = core.mem_read((offset + ix) & 0xffff); + core.mem_write((offset + ix) & 0xffff, do_dec(value)); +}; +// 0x36 : LD (IX+n), n +dd_instructions[0x36] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + pc = (pc + 1) & 0xffff; + core.mem_write((ix + offset) & 0xffff, core.mem_read(pc)); +}; +// 0x39 : ADD IX, SP +dd_instructions[0x39] = function() +{ + do_ix_add(sp); +}; +// 0x44 : LD B, IXH (Undocumented) +dd_instructions[0x44] = function() +{ + b = (ix >>> 8) & 0xff; +}; +// 0x45 : LD B, IXL (Undocumented) +dd_instructions[0x45] = function() +{ + b = ix & 0xff; +}; +// 0x46 : LD B, (IX+n) +dd_instructions[0x46] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + b = core.mem_read((ix + offset) & 0xffff); +}; +// 0x4c : LD C, IXH (Undocumented) +dd_instructions[0x4c] = function() +{ + c = (ix >>> 8) & 0xff; +}; +// 0x4d : LD C, IXL (Undocumented) +dd_instructions[0x4d] = function() +{ + c = ix & 0xff; +}; +// 0x4e : LD C, (IX+n) +dd_instructions[0x4e] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + c = core.mem_read((ix + offset) & 0xffff); +}; +// 0x54 : LD D, IXH (Undocumented) +dd_instructions[0x54] = function() +{ + d = (ix >>> 8) & 0xff; +}; +// 0x55 : LD D, IXL (Undocumented) +dd_instructions[0x55] = function() +{ + d = ix & 0xff; +}; +// 0x56 : LD D, (IX+n) +dd_instructions[0x56] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + d = core.mem_read((ix + offset) & 0xffff); +}; +// 0x5c : LD E, IXH (Undocumented) +dd_instructions[0x5c] = function() +{ + e = (ix >>> 8) & 0xff; +}; +// 0x5d : LD E, IXL (Undocumented) +dd_instructions[0x5d] = function() +{ + e = ix & 0xff; +}; +// 0x5e : LD E, (IX+n) +dd_instructions[0x5e] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + e = core.mem_read((ix + offset) & 0xffff); +}; +// 0x60 : LD IXH, B (Undocumented) +dd_instructions[0x60] = function() +{ + ix = (ix & 0xff) | (b << 8); +}; +// 0x61 : LD IXH, C (Undocumented) +dd_instructions[0x61] = function() +{ + ix = (ix & 0xff) | (c << 8); +}; +// 0x62 : LD IXH, D (Undocumented) +dd_instructions[0x62] = function() +{ + ix = (ix & 0xff) | (d << 8); +}; +// 0x63 : LD IXH, E (Undocumented) +dd_instructions[0x63] = function() +{ + ix = (ix & 0xff) | (e << 8); +}; +// 0x64 : LD IXH, IXH (Undocumented) +dd_instructions[0x64] = function() +{ + // No-op. +}; +// 0x65 : LD IXH, IXL (Undocumented) +dd_instructions[0x65] = function() +{ + ix = (ix & 0xff) | ((ix & 0xff) << 8); +}; +// 0x66 : LD H, (IX+n) +dd_instructions[0x66] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + h = core.mem_read((ix + offset) & 0xffff); +}; +// 0x67 : LD IXH, A (Undocumented) +dd_instructions[0x67] = function() +{ + ix = (ix & 0xff) | (a << 8); +}; +// 0x68 : LD IXL, B (Undocumented) +dd_instructions[0x68] = function() +{ + ix = (ix & 0xff00) | b; +}; +// 0x69 : LD IXL, C (Undocumented) +dd_instructions[0x69] = function() +{ + ix = (ix & 0xff00) | c; +}; +// 0x6a : LD IXL, D (Undocumented) +dd_instructions[0x6a] = function() +{ + ix = (ix & 0xff00) | d; +}; +// 0x6b : LD IXL, E (Undocumented) +dd_instructions[0x6b] = function() +{ + ix = (ix & 0xff00) | e; +}; +// 0x6c : LD IXL, IXH (Undocumented) +dd_instructions[0x6c] = function() +{ + ix = (ix & 0xff00) | (ix >>> 8); +}; +// 0x6d : LD IXL, IXL (Undocumented) +dd_instructions[0x6d] = function() +{ + // No-op. +}; +// 0x6e : LD L, (IX+n) +dd_instructions[0x6e] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + l = core.mem_read((ix + offset) & 0xffff); +}; +// 0x6f : LD IXL, A (Undocumented) +dd_instructions[0x6f] = function() +{ + ix = (ix & 0xff00) | a; +}; +// 0x70 : LD (IX+n), B +dd_instructions[0x70] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + core.mem_write((ix + offset) & 0xffff, b); +}; +// 0x71 : LD (IX+n), C +dd_instructions[0x71] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + core.mem_write((ix + offset) & 0xffff, c); +}; +// 0x72 : LD (IX+n), D +dd_instructions[0x72] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + core.mem_write((ix + offset) & 0xffff, d); +}; +// 0x73 : LD (IX+n), E +dd_instructions[0x73] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + core.mem_write((ix + offset) & 0xffff, e); +}; +// 0x74 : LD (IX+n), H +dd_instructions[0x74] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + core.mem_write((ix + offset) & 0xffff, h); +}; +// 0x75 : LD (IX+n), L +dd_instructions[0x75] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + core.mem_write((ix + offset) & 0xffff, l); +}; +// 0x77 : LD (IX+n), A +dd_instructions[0x77] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + core.mem_write((ix + offset) & 0xffff, a); +}; +// 0x7c : LD A, IXH (Undocumented) +dd_instructions[0x7c] = function() +{ + a = (ix >>> 8) & 0xff; +}; +// 0x7d : LD A, IXL (Undocumented) +dd_instructions[0x7d] = function() +{ + a = ix & 0xff; +}; +// 0x7e : LD A, (IX+n) +dd_instructions[0x7e] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + a = core.mem_read((ix + offset) & 0xffff); +}; +// 0x84 : ADD A, IXH (Undocumented) +dd_instructions[0x84] = function() +{ + do_add((ix >>> 8) & 0xff); +}; +// 0x85 : ADD A, IXL (Undocumented) +dd_instructions[0x85] = function() +{ + do_add(ix & 0xff); +}; +// 0x86 : ADD A, (IX+n) +dd_instructions[0x86] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_add(core.mem_read((ix + offset) & 0xffff)); +}; +// 0x8c : ADC A, IXH (Undocumented) +dd_instructions[0x8c] = function() +{ + do_adc((ix >>> 8) & 0xff); +}; +// 0x8d : ADC A, IXL (Undocumented) +dd_instructions[0x8d] = function() +{ + do_adc(ix & 0xff); +}; +// 0x8e : ADC A, (IX+n) +dd_instructions[0x8e] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_adc(core.mem_read((ix + offset) & 0xffff)); +}; +// 0x94 : SUB IXH (Undocumented) +dd_instructions[0x94] = function() +{ + do_sub((ix >>> 8) & 0xff); +}; +// 0x95 : SUB IXL (Undocumented) +dd_instructions[0x95] = function() +{ + do_sub(ix & 0xff); +}; +// 0x96 : SUB A, (IX+n) +dd_instructions[0x96] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_sub(core.mem_read((ix + offset) & 0xffff)); +}; +// 0x9c : SBC IXH (Undocumented) +dd_instructions[0x9c] = function() +{ + do_sbc((ix >>> 8) & 0xff); +}; +// 0x9d : SBC IXL (Undocumented) +dd_instructions[0x9d] = function() +{ + do_sbc(ix & 0xff); +}; +// 0x9e : SBC A, (IX+n) +dd_instructions[0x9e] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_sbc(core.mem_read((ix + offset) & 0xffff)); +}; +// 0xa4 : AND IXH (Undocumented) +dd_instructions[0xa4] = function() +{ + do_and((ix >>> 8) & 0xff); +}; +// 0xa5 : AND IXL (Undocumented) +dd_instructions[0xa5] = function() +{ + do_and(ix & 0xff); +}; +// 0xa6 : AND A, (IX+n) +dd_instructions[0xa6] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_and(core.mem_read((ix + offset) & 0xffff)); +}; +// 0xac : XOR IXH (Undocumented) +dd_instructions[0xac] = function() +{ + do_xor((ix >>> 8) & 0xff); +}; +// 0xad : XOR IXL (Undocumented) +dd_instructions[0xad] = function() +{ + do_xor(ix & 0xff); +}; +// 0xae : XOR A, (IX+n) +dd_instructions[0xae] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_xor(core.mem_read((ix + offset) & 0xffff)); +}; +// 0xb4 : OR IXH (Undocumented) +dd_instructions[0xb4] = function() +{ + do_or((ix >>> 8) & 0xff); +}; +// 0xb5 : OR IXL (Undocumented) +dd_instructions[0xb5] = function() +{ + do_or(ix & 0xff); +}; +// 0xb6 : OR A, (IX+n) +dd_instructions[0xb6] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_or(core.mem_read((ix + offset) & 0xffff)); +}; +// 0xbc : CP IXH (Undocumented) +dd_instructions[0xbc] = function() +{ + do_cp((ix >>> 8) & 0xff); +}; +// 0xbd : CP IXL (Undocumented) +dd_instructions[0xbd] = function() +{ + do_cp(ix & 0xff); +}; +// 0xbe : CP A, (IX+n) +dd_instructions[0xbe] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + do_cp(core.mem_read((ix + offset) & 0xffff)); +}; +// 0xcb : CB Prefix (IX bit instructions) +dd_instructions[0xcb] = function() +{ + pc = (pc + 1) & 0xffff; + var offset = get_signed_offset_byte(core.mem_read(pc)); + pc = (pc + 1) & 0xffff; + var opcode = core.mem_read(pc), value; + + // As with the "normal" CB prefix, we implement the DDCB prefix + // by decoding the opcode directly, rather than using a table. + if (opcode < 0x40) + { + // Shift and rotate instructions. + var ddcb_functions = [do_rlc, do_rrc, do_rl, do_rr, + do_sla, do_sra, do_sll, do_srl]; + + // Most of the opcodes in this range are not valid, + // so we map this opcode onto one of the ones that is. + var func = ddcb_functions[(opcode & 0x38) >>> 3], + value = func( core.mem_read((ix + offset) & 0xffff)); + + core.mem_write((ix + offset) & 0xffff, value); + } + else + { + var bit_number = (opcode & 0x38) >>> 3; + + if (opcode < 0x80) + { + // BIT + flags.N = 0; + flags.H = 1; + flags.Z = !(core.mem_read((ix + offset) & 0xffff) & (1 << bit_number)) ? 1 : 0; + flags.P = flags.Z; + flags.S = ((bit_number === 7) && !flags.Z) ? 1 : 0; + } + else if (opcode < 0xc0) + { + // RES + value = core.mem_read((ix + offset) & 0xffff) & ~(1 << bit_number) & 0xff; + core.mem_write((ix + offset) & 0xffff, value); + } + else + { + // SET + value = core.mem_read((ix + offset) & 0xffff) | (1 << bit_number); + core.mem_write((ix + offset) & 0xffff, value); + } + } + + // This implements the undocumented shift, RES, and SET opcodes, + // which write their result to memory and also to an 8080 register. + if (value !== undefined) + { + if ((opcode & 0x07) === 0) + b = value; + else if ((opcode & 0x07) === 1) + c = value; + else if ((opcode & 0x07) === 2) + d = value; + else if ((opcode & 0x07) === 3) + e = value; + else if ((opcode & 0x07) === 4) + h = value; + else if ((opcode & 0x07) === 5) + l = value; + // 6 is the documented opcode, which doesn't set a register. + else if ((opcode & 0x07) === 7) + a = value; + } + + cycle_counter += cycle_counts_cb[opcode] + 8; +}; +// 0xe1 : POP IX +dd_instructions[0xe1] = function() +{ + ix = pop_word(); +}; +// 0xe3 : EX (SP), IX +dd_instructions[0xe3] = function() +{ + var temp = ix; + ix = core.mem_read(sp); + ix |= core.mem_read((sp + 1) & 0xffff) << 8; + core.mem_write(sp, temp & 0xff); + core.mem_write((sp + 1) & 0xffff, (temp >>> 8) & 0xff); +}; +// 0xe5 : PUSH IX +dd_instructions[0xe5] = function() +{ + push_word(ix); +}; +// 0xe9 : JP (IX) +dd_instructions[0xe9] = function() +{ + pc = (ix - 1) & 0xffff; +}; +// 0xf9 : LD SP, IX +dd_instructions[0xf9] = function() +{ + sp = ix; +}; + + +/////////////////////////////////////////////////////////////////////////////// +/// These tables contain the number of T cycles used for each instruction. +/// In a few special cases, such as conditional control flow instructions, +/// additional cycles might be added to these values. +/// The total number of cycles is the return value of run_instruction(). +/////////////////////////////////////////////////////////////////////////////// +let cycle_counts = [ + 4, 10, 7, 6, 4, 4, 7, 4, 4, 11, 7, 6, 4, 4, 7, 4, + 8, 10, 7, 6, 4, 4, 7, 4, 12, 11, 7, 6, 4, 4, 7, 4, + 7, 10, 16, 6, 4, 4, 7, 4, 7, 11, 16, 6, 4, 4, 7, 4, + 7, 10, 13, 6, 11, 11, 10, 4, 7, 11, 13, 6, 4, 4, 7, 4, + 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, + 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, + 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, + 7, 7, 7, 7, 7, 7, 4, 7, 4, 4, 4, 4, 4, 4, 7, 4, + 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, + 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, + 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, + 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, + 5, 10, 10, 10, 10, 11, 7, 11, 5, 10, 10, 0, 10, 17, 7, 11, + 5, 10, 10, 11, 10, 11, 7, 11, 5, 4, 10, 11, 10, 0, 7, 11, + 5, 10, 10, 19, 10, 11, 7, 11, 5, 4, 10, 4, 10, 0, 7, 11, + 5, 10, 10, 4, 10, 11, 7, 11, 5, 6, 10, 4, 10, 0, 7, 11 +]; + +let cycle_counts_ed = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 12, 12, 15, 20, 8, 14, 8, 9, 12, 12, 15, 20, 8, 14, 8, 9, + 12, 12, 15, 20, 8, 14, 8, 9, 12, 12, 15, 20, 8, 14, 8, 9, + 12, 12, 15, 20, 8, 14, 8, 18, 12, 12, 15, 20, 8, 14, 8, 18, + 12, 12, 15, 20, 8, 14, 8, 0, 12, 12, 15, 20, 8, 14, 8, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 0, 0, 0, 0, + 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +]; + +let cycle_counts_cb = [ + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, + 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, + 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, + 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8, + 8, 8, 8, 8, 8, 8, 15, 8, 8, 8, 8, 8, 8, 8, 15, 8 +]; + +let cycle_counts_dd = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, + 0, 14, 20, 10, 8, 8, 11, 0, 0, 15, 20, 10, 8, 8, 11, 0, + 0, 0, 0, 0, 23, 23, 19, 0, 0, 15, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 8, 19, 0, 0, 0, 0, 0, 8, 8, 19, 0, + 0, 0, 0, 0, 8, 8, 19, 0, 0, 0, 0, 0, 8, 8, 19, 0, + 8, 8, 8, 8, 8, 8, 19, 8, 8, 8, 8, 8, 8, 8, 19, 8, + 19, 19, 19, 19, 19, 19, 0, 19, 0, 0, 0, 0, 8, 8, 19, 0, + 0, 0, 0, 0, 8, 8, 19, 0, 0, 0, 0, 0, 8, 8, 19, 0, + 0, 0, 0, 0, 8, 8, 19, 0, 0, 0, 0, 0, 8, 8, 19, 0, + 0, 0, 0, 0, 8, 8, 19, 0, 0, 0, 0, 0, 8, 8, 19, 0, + 0, 0, 0, 0, 8, 8, 19, 0, 0, 0, 0, 0, 8, 8, 19, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 14, 0, 23, 0, 15, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0 +]; + + // There's tons of stuff in this object, + // but only these three functions are the public API. + return { + getState, + setState, + reset, + run_instruction, + interrupt, + // Ajouts pour l'émulateur ZX81 : registre I (jeu de caractères), + // PC et IFF1 lisibles/modifiables sans passer par getState(). + get_i() { return i; }, + get_pc() { return pc; }, + set_pc(v) { pc = v & 0xffff; }, + get_iff1() { return iff1; }, + is_halted() { return halted; } + }; +} + +export { Z80 }; diff --git a/web/zx81.js b/web/zx81.js @@ -0,0 +1,233 @@ +// Machine ZX81 : Z80 à 3,25 MHz, ROM 8 Ko, 16 Ko de RAM, clavier matriciel et +// une émulation simplifiée de la ULA pour l'affichage. +// +// Principe de l'affichage (fidèle au mécanisme réel, simplifié dans le détail) : +// la ROM fait « exécuter » le fichier d'écran (D_FILE) par le Z80 à l'adresse +// écho (A15 = 1). Quand le Z80 lit un opcode dans cette zone et que le bit 6 de +// l'octet est à 0, la ULA affiche le caractère et fait exécuter un NOP au CPU ; +// le 0x76 (HALT) qui termine chaque ligne, lui, s'exécute pour de vrai et +// l'interruption qui suit enchaîne la ligne suivante. Chaque ligne de texte est +// parcourue 8 fois (une par ligne de pixels, compteur LNCTR de la ULA). +// Ici, on dessine le glyphe complet dès qu'on voit le caractère, on compte les +// HALT pour avancer de ligne, et on présente l'image à la fin du VSYNC. + +import { Z80 } from './z80.js'; + +export const CPU_HZ = 3250000; +export const FRAME_T = 65000; // T-states par trame (50 Hz) +const LINE_T = 207; // T-states par ligne (période du NMI) + +export const COLS = 32, ROWS = 24; + +// Ordre des touches dans les tables clavier de la ROM (K-UNSHIFTED à 0x007E…). +// Chaque touche : [rangée du port (bit d'adresse à 0), bit de donnée]. +export const KEYS = { + SHIFT: [0, 0], Z: [0, 1], X: [0, 2], C: [0, 3], V: [0, 4], + A: [1, 0], S: [1, 1], D: [1, 2], F: [1, 3], G: [1, 4], + Q: [2, 0], W: [2, 1], E: [2, 2], R: [2, 3], T: [2, 4], + '1': [3, 0], '2': [3, 1], '3': [3, 2], '4': [3, 3], '5': [3, 4], + '0': [4, 0], '9': [4, 1], '8': [4, 2], '7': [4, 3], '6': [4, 4], + P: [5, 0], O: [5, 1], I: [5, 2], U: [5, 3], Y: [5, 4], + NEWLINE: [6, 0], L: [6, 1], K: [6, 2], J: [6, 3], H: [6, 4], + SPACE: [7, 0], '.': [7, 1], M: [7, 2], N: [7, 3], B: [7, 4], +}; + +// Adresses de la ROM utilisées pour les interceptions. +const ROM_LOAD = 0x0347; // boucle de lecture d'octets de LOAD +const ROM_SAVE = 0x02FC; // boucle d'écriture de SAVE +const ROM_SLOW_FAST = 0x0207; // retour après LOAD/SAVE (comme z81) + +export class ZX81 { + constructor(rom) { + if (!(rom instanceof Uint8Array) || rom.length !== 8192) throw new Error('ROM ZX81 : 8192 octets attendus'); + this.rom = rom; + this.ram = new Uint8Array(0x4000); + this.keys = new Uint8Array(8).fill(0x1f); // bits actifs à 0 + // Image : 32×24 cellules, chaque cellule = code affiché (0..0x3f | 0x80 inverse), 0xff = vide + this.screen = new Uint8Array(COLS * ROWS); + this.work = new Uint8Array(COLS * ROWS); + this.pixels = new Uint8Array(COLS * 8 * ROWS * 8); // 1 = pixel noir, image présentée + this.frames = 0; // trames présentées depuis le reset + this.onFrame = null; // rappel à chaque trame présentée + this.tape = null; // Uint8Array d'un fichier .P à charger au prochain LOAD + this.onSave = null; // rappel (Uint8Array) quand le programme fait SAVE + this.onLoad = null; // rappel quand un .P a été chargé + this.cpu = new Z80({ + mem_read: (a) => this.read(a), + mem_write: (a, v) => this.write(a, v), + io_read: (p) => this.ioRead(p), + io_write: (p, v) => this.ioWrite(p, v), + fetch_opcode: (a) => this.fetch(a), + }); + this.reset(); + } + + reset() { + this.ram.fill(0); + this.cpu.reset(); + this.nmiOn = false; + this.vsync = false; + this.nmiT = 0; + this.row = 0; this.col = 0; this.hline = 0; + this.pendingInt = false; + this.work.fill(0xff); + this.screen.fill(0xff); + this.pixels.fill(0); + this.frames = 0; + this.tstates = 0; + } + + read(addr) { + const a = addr & 0x7fff; + return a < 0x4000 ? this.rom[a & 0x1fff] : this.ram[a - 0x4000]; + } + + write(addr, v) { + const a = addr & 0x7fff; + if (a >= 0x4000) this.ram[a - 0x4000] = v; + } + + fetch(addr) { + if (addr & 0x8000) { + const b = this.read(addr); + if ((b & 0x40) === 0) { + // Caractère affiché par la ULA ; le CPU voit un NOP. + if (this.row < ROWS && this.col < COLS) this.work[this.row * COLS + this.col] = b; + this.col++; + return 0x00; + } + if (b === 0x76) { + // Fin de ligne : on simule l'interruption que le compteur de + // rafraîchissement (R) produirait pendant le HALT. + this.col = 0; + this.hline++; + this.row = this.hline >> 3; + this.pendingInt = true; + return 0x00; + } + return b; + } + if (addr === ROM_LOAD && this.tape) { + this.loadP(this.tape); + this.tape = null; + this.cpu.set_pc(ROM_SLOW_FAST); + if (this.onLoad) this.onLoad(); + return this.read(ROM_SLOW_FAST); + } + if (addr === ROM_SAVE && this.onSave) { + this.onSave(this.dumpP()); + this.cpu.set_pc(ROM_SLOW_FAST); + return this.read(ROM_SLOW_FAST); + } + return this.read(addr); + } + + ioRead(port) { + if ((port & 1) === 0) { + // Port 0xFE : clavier ; lance aussi le VSYNC si le générateur de NMI est coupé. + if (!this.nmiOn) this.vsync = true; + let v = 0x1f; + const hi = port >> 8; + for (let r = 0; r < 8; r++) if (((hi >> r) & 1) === 0) v &= this.keys[r]; + // bit 5 : inutilisé (1) ; bit 6 : 1 = machine 50 Hz ; bit 7 : entrée magnétophone (0) + return v | 0x60; + } + return 0xff; + } + + ioWrite(port, _v) { + if (this.vsync) { + this.vsync = false; + this.endFrame(); + } + if ((port & 0xff) === 0xfd) { this.nmiOn = false; } + else if ((port & 0xff) === 0xfe) { this.nmiOn = true; this.nmiT = 0; } + } + + endFrame() { + // Fin du VSYNC : l'image accumulée depuis le dernier VSYNC devient la trame courante. + this.screen.set(this.work); + this.work.fill(0xff); + this.row = 0; this.col = 0; this.hline = 0; + this.frames++; + this.render(); + if (this.onFrame) this.onFrame(this); + } + + // Convertit la trame (codes) en pixels avec le jeu de caractères pointé par I. + render() { + const base = this.cpu.get_i() << 8; + const px = this.pixels, scr = this.screen; + const W = COLS * 8; + for (let r = 0; r < ROWS; r++) { + for (let c = 0; c < COLS; c++) { + const code = scr[r * COLS + c]; + const inv = code !== 0xff && (code & 0x80) ? 0xff : 0; + const g = code === 0xff ? -1 : base + ((code & 0x3f) << 3); + for (let y = 0; y < 8; y++) { + const bits = g < 0 ? 0 : this.read(g + y) ^ inv; + let o = (r * 8 + y) * W + c * 8; + for (let x = 7; x >= 0; x--) px[o++] = (bits >> x) & 1; + } + } + } + } + + // Exécute au moins `t` T-states. + run(t) { + const cpu = this.cpu; + let done = 0; + while (done < t) { + const n = cpu.run_instruction(); + done += n; + if (this.pendingInt) { + this.pendingInt = false; + cpu.interrupt(false, 0xff); + } + if (this.nmiOn) { + this.nmiT += n; + if (this.nmiT >= LINE_T) { + this.nmiT -= LINE_T; + cpu.interrupt(true, 0); + } + } + } + this.tstates += done; + return done; + } + + keyDown(name) { const k = KEYS[name]; if (k) this.keys[k[0]] &= ~(1 << k[1]); } + keyUp(name) { const k = KEYS[name]; if (k) this.keys[k[0]] |= (1 << k[1]); } + releaseAll() { this.keys.fill(0x1f); } + + // Charge un fichier .P (image mémoire à partir de 0x4009, variables système comprises). + loadP(bytes) { + const max = 0x8000 - 0x4009; + const n = Math.min(bytes.length, max); + this.ram.set(bytes.subarray(0, n), 0x4009 - 0x4000); + } + + // Image .P du programme en mémoire : de 0x4009 à E_LINE (exclu), comme SAVE. + dumpP() { + const eline = this.ram[0x4014 - 0x4000] | (this.ram[0x4015 - 0x4000] << 8); + return this.ram.slice(0x4009 - 0x4000, Math.max(0x4009, Math.min(eline, 0x8000)) - 0x4000); + } + + // Texte de l'écran (pour les tests) : codes convertis en ASCII approximatif. + screenText() { + const lines = []; + for (let r = 0; r < ROWS; r++) { + let s = ''; + for (let c = 0; c < COLS; c++) s += charToAscii(this.screen[r * COLS + c]); + lines.push(s); + } + return lines.join('\n'); + } +} + +const ASCII = ' ##########"£$:?()><=+-*/;,.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; +export function charToAscii(code) { + if (code === 0xff) return ' '; + const ch = ASCII[code & 0x3f] ?? '?'; + return (code & 0x80) ? ch.toLowerCase() : ch; +} diff --git a/web/zx81.rom b/web/zx81.rom Binary files differ.