From 3f44ca5faad91c5e2402595c66f553e236f4a258 Mon Sep 17 00:00:00 2001 From: ssk Date: Thu, 1 Oct 2026 19:09:16 +0900 Subject: [PATCH 1/5] Preserve Gambatte LCD-off bootstrap state across rollback --- package-lock.json | 4 +- packages/romdev-core-gambatte/package.json | 2 +- packages/romdevtools/package.json | 2 +- .../romdevtools/scripts/multiplayer/README.md | 19 ++++- .../scripts/multiplayer/build-harness.mjs | 2 +- .../scripts/multiplayer/harness/index.html | 2 +- .../scripts/multiplayer/harness/worker.js | 28 ++++++- .../patches/gambatte-multiplayer-state.patch | 81 +++++++++++++++++-- .../test/fixtures/multiplayer/gb-fixture.mjs | 11 ++- .../romdevtools/test/multiplayer-core.test.js | 48 ++++++++++- 10 files changed, 177 insertions(+), 22 deletions(-) diff --git a/package-lock.json b/package-lock.json index da9d5736..7bcc77b6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3800,7 +3800,7 @@ } }, "packages/romdev-core-gambatte": { - "version": "0.13.0", + "version": "0.13.1", "license": "GPL-2.0-only", "engines": { "node": ">=24" @@ -4011,7 +4011,7 @@ "romdev-core-fake08": "0.1.1", "romdev-core-fceumm": "0.14.0", "romdev-core-flycast": "0.4.1", - "romdev-core-gambatte": "0.13.0", + "romdev-core-gambatte": "0.13.1", "romdev-core-gametank": "0.5.1", "romdev-core-geargrafx": "0.10.1", "romdev-core-gpgx": "0.15.1", diff --git a/packages/romdev-core-gambatte/package.json b/packages/romdev-core-gambatte/package.json index 094bcf45..f530e8df 100644 --- a/packages/romdev-core-gambatte/package.json +++ b/packages/romdev-core-gambatte/package.json @@ -1,6 +1,6 @@ { "name": "romdev-core-gambatte", - "version": "0.13.0", + "version": "0.13.1", "description": "gambatte libretro core (Game Boy / Game Boy Color) for romdev, bundled as WASM.", "type": "module", "main": "index.js", diff --git a/packages/romdevtools/package.json b/packages/romdevtools/package.json index a553fe35..53258cee 100644 --- a/packages/romdevtools/package.json +++ b/packages/romdevtools/package.json @@ -63,7 +63,7 @@ "romdev-core-fake08": "0.1.1", "romdev-core-fceumm": "0.14.0", "romdev-core-flycast": "0.4.1", - "romdev-core-gambatte": "0.13.0", + "romdev-core-gambatte": "0.13.1", "romdev-core-gametank": "0.5.1", "romdev-core-geargrafx": "0.10.1", "romdev-core-gpgx": "0.15.1", diff --git a/packages/romdevtools/scripts/multiplayer/README.md b/packages/romdevtools/scripts/multiplayer/README.md index ce4386bb..4d5d22be 100644 --- a/packages/romdevtools/scripts/multiplayer/README.md +++ b/packages/romdevtools/scripts/multiplayer/README.md @@ -42,7 +42,7 @@ from ROM identity and emulates its timers from CPU cycles. | Core | Schema | Snapshot additions and normalization | | --- | --- | --- | -| gambatte | `0x47420101` | Full CPU/mapper/RTC/HuC3/timer/serial/APU/PPU/WRAM/VRAM/OAM/HRAM/cart-RAM serializer; epoch and emulated clock; frontend frame/sample counters, turbo phase/config, both blipper buffers, phase, integrator and last sample. CC resampler and interframe blending are disabled in this mode. | +| gambatte | `0x47420102` | Full CPU/mapper/RTC/HuC3/timer/serial/APU/PPU/WRAM/VRAM/OAM/HRAM/cart-RAM serializer; epoch and emulated clock; frontend frame/sample counters, turbo phase/config, both blipper buffers, phase, integrator and last sample; native blit deadline and blank-LCD phase. CC resampler and interframe blending are disabled in this mode. | | fceumm | `0x4e450101` | Full CPU/mapper/PPU/APU/DMA/RAM/cart-RAM/controller serializer, Four Score enable flag and exact native device configuration, FIR interpolation index and full low/high quality wave histories. Existing DC filter accumulators remain included. Stereo widening is unsupported (digest refuses it). | Gambatte's `endx` was a cached next-tile boundary reconstructed on load from `xpos` @@ -51,6 +51,21 @@ PPU causal fields. The unused DMG-only `dmgPalette` payload previously contained uninitialized stack bytes; deterministic save writes explicit zeros when `isCgb()` is false. CGB palette data remains intact. No known byte is hidden from the digest. +The MP bootstrap can spend many native frames with the LCD off before world +initialization. Gambatte's ordinary loader recomputes the blit deadline and resets +the blank-LCD phase, changing the first restored native frame. Deterministic +schema `0x47420102` retains both in its 80-byte envelope (64-byte v1 envelopes +are rejected). Its loader also restores all captured sprite attributes/words, +including the dormant suffix that the ordinary loader leaves from a later frame, +and preserves the LCD-off initial current-sprite sentinel. A disabled mode-0 STAT +IRQ deadline is normalized only when the loader ignores it; active deadlines +remain part of the snapshot and digest. These changes are deterministic-only. + +The LCD-off regression restores four differently aged boot checkpoints after +LCD enable, visible sprite processing and active STAT timing. Each restore compares +40 subsequent native frames' CPU/RAM/pixels/audio/digest, including the transition +out of the wait. The browser harness performs the same checks. + Blipper serialization uses fixed-width little-endian integers and excludes its immutable coefficient table and pointers. Its signed residual phase can be negative after rounding to the next output sample; restore validates that range. @@ -109,7 +124,7 @@ ROMDEV_BUILD_CWD=packages/romdevtools build-image/build-wasm.sh build-fceumm.sh node --test packages/romdevtools/test/multiplayer-core.test.js packages/romdevtools/test/browser-surface-imports.test.js ``` -The thirteen core/compiler tests independently boot GB/GBC/NES across a wall-clock +The core/compiler tests independently boot GB/GBC/NES across a wall-clock second without sharing state. They compare 32 replay frames' RAM, CPU registers, pixels, audio and digest, check against Node SHA-256, require visible fixture pixels, and cover 1/2/3/4 pads, gapped slots, release and reload, plus all three NES filter qualities and invalid bootstrap rejection. The GBC fixture diff --git a/packages/romdevtools/scripts/multiplayer/build-harness.mjs b/packages/romdevtools/scripts/multiplayer/build-harness.mjs index 1cadf359..93ed31e9 100644 --- a/packages/romdevtools/scripts/multiplayer/build-harness.mjs +++ b/packages/romdevtools/scripts/multiplayer/build-harness.mjs @@ -13,7 +13,7 @@ const out=path.join(dist,'m1');mkdirSync(out,{recursive:true}); for(const name of ['index.html','main.js','worker.js'])cpSync(path.join(import.meta.dirname,'harness',name),path.join(out,name)); const hostDir=path.join(repo,'packages/romdev-core-host');mkdirSync(path.join(out,'host'),{recursive:true}); for(const name of (await import('node:fs')).readdirSync(hostDir).filter(n=>n.endsWith('.js')&&!n.endsWith('.test.js')))cpSync(path.join(hostDir,name),path.join(out,'host',name)); -const roms={nes:(await fourScoreRom()).outputs['pads.nes'],gb:gbFixture(false),gbc:gbFixture(true)}; +const roms={nes:(await fourScoreRom()).outputs['pads.nes'],gb:gbFixture(false),gbc:gbFixture(true),'gb-offlcd':gbFixture(false,false,true),'gbc-offlcd':gbFixture(true,false,true)}; const hash=bytes=>createHash('sha256').update(bytes).digest('hex'); const artifacts={};for(const [name,bytes]of Object.entries(roms)){writeFileSync(path.join(out,name+'.rom'),bytes);artifacts[name+'.rom']=hash(bytes);} for(const core of ['gambatte','fceumm'])for(const ext of ['js','wasm']){ diff --git a/packages/romdevtools/scripts/multiplayer/harness/index.html b/packages/romdevtools/scripts/multiplayer/harness/index.html index f93b7aac..c3d372d1 100644 --- a/packages/romdevtools/scripts/multiplayer/harness/index.html +++ b/packages/romdevtools/scripts/multiplayer/harness/index.html @@ -2,7 +2,7 @@ -

M1 core verification

Independent boot and rollback checks for GB, GBC and native NES Four Score.

Starting automatic checks…

+

M1 core verification

Independent boot, LCD-off bootstrap restoration, sprites, STAT timing and rollback checks for GB, GBC and native NES Four Score.

Starting automatic checks…

Player positions

After the checks, move each NES player's colored square. Hold a button for at least 50 ms. This is a core fixture, not the multiplayer game UI.


 

Test reports stay in this browser. No login or upload is needed: the fixtures contain no account or game data. License · Source

diff --git a/packages/romdevtools/scripts/multiplayer/harness/worker.js b/packages/romdevtools/scripts/multiplayer/harness/worker.js index d5a2d9bf..3e4750af 100644 --- a/packages/romdevtools/scripts/multiplayer/harness/worker.js +++ b/packages/romdevtools/scripts/multiplayer/harness/worker.js @@ -5,17 +5,38 @@ const hash=async bytes=>hex(new Uint8Array(await crypto.subtle.digest('SHA-256', const equal=(a,b)=>a.length===b.length&&a.every((v,i)=>v===b[i]); const check=(value,message)=>{if(!value)throw Error(message);}; let live=null; -async function make(platform,mask=15){ +async function make(platform,mask=15,fixture=platform){ const name=platform==='nes'?'fceumm':'gambatte'; const h=new LibretroHost(); await h.loadCore({factory:(await import('./'+name+'_libretro.js')).default,wasmBinary:new Uint8Array(await(await fetch('./'+name+'_libretro.wasm')).arrayBuffer()),io:false}); - await h.loadMedia({platform,bytes:new Uint8Array(await(await fetch('./'+platform+'.rom')).arrayBuffer()),deterministic:{rtcEpochSeconds:0},...(platform==='nes'?{controllerTopology:{kind:'nes',playerMask:mask}}:{})});return h; + await h.loadMedia({platform,bytes:new Uint8Array(await(await fetch('./'+fixture+'.rom')).arrayBuffer()),deterministic:{rtcEpochSeconds:0},...(platform==='nes'?{controllerTopology:{kind:'nes',playerMask:mask}}:{})});return h; } function trace(h,input){ h.setInput(input);h.state.audioRing.length=0;h.stepFrames(1); const audio=h.state.audioRing.flatMap(a=>Array.from(a)); return {state:hex(h.stateDigest().bytes),pixels:h.screenshotRgba().rgba.slice(),audio,regs:JSON.stringify(getCPUState(h,h.status.platform)),ram:h.readMemory('system_ram',0,h.status.platform==='nes'?2048:h.status.platform==='gbc'?32768:8192)}; } +async function verifyBootstrap(platform){ + const h=await make(platform,15,platform+'-offlcd'); + try{ + h.stepFrames(12);check(h.readMemory('system_ram',0x20,1)[0]===0x5a,'Bootstrap wait was not reached'); + for(const wait of [0,1,5,30]){ + h.stepFrames(wait);check(h.readMemory('system_ram',0x21,1)[0]===0,'World started before configuration'); + const snapshot=h.serializeState(); + const inputs=Array.from({length:40},(_,f)=>({ports:[{right:f%3===0,a:f%7<3}]})); + const run=()=>inputs.map((input,f)=>{if(f===8)h.writeMemory('system_ram',0x21,new Uint8Array([1]));return trace(h,input);}); + const expected=run();h.unserializeState(snapshot); + check(hex(h.stateDigest().bytes)===await hash(snapshot),'LCD-off bootstrap digest differs'); + const actual=run(); + for(let f=0;fsetTimeout(r,1100));const b=await make(platform); try{ @@ -34,7 +55,8 @@ async function verify(platform){ const pads=a.readMemory('system_ram',0x300,6),want=[mask&1?1:0,mask&2?2:0,...(mask>3?[mask&4?4:0,mask&8?8:0,8,4]:[255,255,255,255])];check(equal(pads,want),'Native pads / Four Score signature differs for mask '+mask); } if(platform==='gbc')check(a.readMemory('system_ram',0x400,1)[0]===0xa5&&a.readMemory('system_ram',0x10f0,1)[0]===0x5a&&a.readMemory('system_ram',0x20f0,1)[0]===0x99,'Banked header/context probe differs'); - return {platform,pass:true,schema:a.stateDigest().schema,snapshotBytes:snapshot.length,framesCompared:32,checks:['independent boot','digest SHA-256','restore','future digest/RAM/registers/pixels/audio',...(platform==='nes'?['1–4 native pads','gapped slots','Four Score signatures']:platform==='gbc'?['WRAM bank/context']:[])]}; + const bootstrap=platform==='nes'?[]:[await verifyBootstrap(platform)]; + return {platform,pass:true,schema:a.stateDigest().schema,snapshotBytes:snapshot.length,framesCompared:32,checks:[...bootstrap,'independent boot','digest SHA-256','restore','future digest/RAM/registers/pixels/audio',...(platform==='nes'?['1–4 native pads','gapped slots','Four Score signatures']:platform==='gbc'?['WRAM bank/context']:[])]}; }finally{a.dispose();b.dispose();} } onmessage=async({data})=>{ diff --git a/packages/romdevtools/scripts/patches/gambatte-multiplayer-state.patch b/packages/romdevtools/scripts/patches/gambatte-multiplayer-state.patch index 38a2bc09..c9b0e008 100644 --- a/packages/romdevtools/scripts/patches/gambatte-multiplayer-state.patch +++ b/packages/romdevtools/scripts/patches/gambatte-multiplayer-state.patch @@ -19,6 +19,24 @@ diff --git a/libgambatte/src/video/ppu.cpp b/libgambatte/src/video/ppu.cpp ss.ppu.reg0 = p_.reg0; ss.ppu.reg1 = p_.reg1; ss.ppu.tileword = p_.tileword; +@@ -1778,6 +1782,11 @@ + p_.lastM0Time = p_.now - ss.ppu.lastM0Time; + loadSpriteList(p_, ss); ++ // loadSpriteList restores only the visible sprite prefix. The remaining ++ // captured attributes/words must not inherit a later frame of this instance. ++ if (romdev_clock_enabled) { ++ for (unsigned i = 0; i < 10; ++i) { ++ p_.spriteList[i].attrib = ss.ppu.spAttribList[i]; ++ p_.spwordList[i] = ss.ppu.spByte1List[i] * 0x100 + ss.ppu.spByte0List[i]; ++ } ++ } ++ // With the LCD off, the dormant initial sprite sentinel may be 0xFF. ++ // loadSpriteList clamps it to zero even though no sprite fetch is running. ++ // Preserve the captured value; setLcdc starts M3Start before a later fetch. ++ if (romdev_clock_enabled && !lcdcEn(p_)) ++ p_.currentSprite = ss.ppu.currentSprite; + + if (m3loopState && videoCycles < 144 * 456L && p_.xpos < 168 diff --git a/libgambatte/src/initstate.cpp b/libgambatte/src/initstate.cpp --- a/libgambatte/src/initstate.cpp +++ b/libgambatte/src/initstate.cpp @@ -45,6 +63,19 @@ diff --git a/libgambatte/src/initstate.cpp b/libgambatte/src/initstate.cpp state.huc3.haltTime = state.huc3.baseTime; state.huc3.dataTime = 0; state.huc3.writingTime = 0; +diff --git a/libgambatte/src/video.cpp b/libgambatte/src/video.cpp +--- a/libgambatte/src/video.cpp ++++ b/libgambatte/src/video.cpp +@@ -88,6 +88,11 @@ + state.mem.hdmaTransfer = hdmaIsEnabled(); + state.ppu.nextM0Irq = eventTimes_(MODE0_IRQ) - ppu_.now(); ++ // A disabled event has no deadline. Subtracting stale PPU time makes this ++ // sentinel vary after restore (PPU::loadState catches up to CPU time). ++ // LCD::loadState ignores it with the LCD off or STAT mode-0 IRQ disabled; ++ // lcdcChange/statChange schedule a fresh deadline when enabled later. ++ if (romdev_clock_enabled && (!(ppu_.lcdc() & 0x80) || !(statReg_ & 0x08))) ++ state.ppu.nextM0Irq = 0; + state.ppu.pendingLcdstatIrq = eventTimes_(ONESHOT_LCDSTATIRQ) != disabled_time; diff --git a/libgambatte/src/mem/rtc.cpp b/libgambatte/src/mem/rtc.cpp --- a/libgambatte/src/mem/rtc.cpp +++ b/libgambatte/src/mem/rtc.cpp @@ -214,10 +245,11 @@ diff --git a/libgambatte/libretro/libretro.cpp b/libgambatte/libretro/libretro.c +extern "C" { +uint32_t romdev_clock_enabled = 0, romdev_clock_epoch = 0; +uint64_t romdev_clock_ticks = 0; ++uint32_t romdev_gb_blit_time=0, romdev_gb_blank_lcd=0, romdev_gb_restore_timing=0; +time_t romdev_time(void) { return romdev_clock_enabled ? (time_t)(romdev_clock_epoch + romdev_clock_ticks / 4194304) : time(NULL); } +} +static size_t mp_gb_size(void) { -+ return resampler_l && resampler_r ? 64 + gb.stateSize() + blipper_state_size(resampler_l) + blipper_state_size(resampler_r) : 0; ++ return resampler_l && resampler_r ? 80 + gb.stateSize() + blipper_state_size(resampler_l) + blipper_state_size(resampler_r) : 0; +} size_t retro_serialize_size(void) { @@ -232,11 +264,12 @@ diff --git a/libgambatte/libretro/libretro.cpp b/libgambatte/libretro/libretro.c + if (romdev_clock_enabled) { + unsigned char *p = (unsigned char *)data; + size_t core = gb.stateSize(), l = blipper_state_size(resampler_l), r = blipper_state_size(resampler_r); -+ memset(p,0,64);mp_w32(p,0x3142474d);mp_w32(p+4,core);mp_w32(p+8,romdev_clock_epoch);mp_w32(p+12,0x47420101); ++ memset(p,0,80);mp_w32(p,0x3142474d);mp_w32(p+4,core);mp_w32(p+8,romdev_clock_epoch);mp_w32(p+12,0x47420102); + mp_w64(p+16,romdev_clock_ticks);mp_w64(p+24,libretro_samples_count);mp_w64(p+32,libretro_frames_count); + mp_w32(p+40,turbo_a_counter);mp_w32(p+44,turbo_b_counter);mp_w32(p+48,turbo_period);mp_w32(p+52,turbo_pulse_width); -+ mp_w32(p+56,l);mp_w32(p+60,r);gb.saveState(p+64); -+ return blipper_state_write(resampler_l,p+64+core,l) && blipper_state_write(resampler_r,p+64+core+l,r); ++ mp_w32(p+56,l);mp_w32(p+60,r);gb.saveState(p+80); ++ mp_w32(p+64,romdev_gb_blit_time);mp_w32(p+68,romdev_gb_blank_lcd); ++ return blipper_state_write(resampler_l,p+80+core,l) && blipper_state_write(resampler_r,p+80+core+l,r); + } gb.saveState(data); return true; @@ -249,8 +282,11 @@ diff --git a/libgambatte/libretro/libretro.cpp b/libgambatte/libretro/libretro.c + if (romdev_clock_enabled) { + const unsigned char *p = (const unsigned char *)data; + size_t core = gb.stateSize(), l = blipper_state_size(resampler_l), r = blipper_state_size(resampler_r); -+ if (mp_r32(p)!=0x3142474d || mp_r32(p+4)!=core || mp_r32(p+8)!=romdev_clock_epoch || mp_r32(p+12)!=0x47420101 || mp_r32(p+56)!=l || mp_r32(p+60)!=r || mp_r32(p+48)!=turbo_period || mp_r32(p+52)!=turbo_pulse_width) return false; -+ if (!gb.loadState(p+64,core) || !blipper_state_read(resampler_l,p+64+core,l) || !blipper_state_read(resampler_r,p+64+core+l,r)) return false; ++ if (mp_r32(p)!=0x3142474d || mp_r32(p+4)!=core || mp_r32(p+8)!=romdev_clock_epoch || mp_r32(p+12)!=0x47420102 || mp_r32(p+56)!=l || mp_r32(p+60)!=r || mp_r32(p+48)!=turbo_period || mp_r32(p+52)!=turbo_pulse_width) return false; ++ if (mp_r32(p+68)>1) return false; ++ romdev_gb_blit_time=mp_r32(p+64);romdev_gb_blank_lcd=mp_r32(p+68);romdev_gb_restore_timing=1; ++ bool core_ok=gb.loadState(p+80,core);romdev_gb_restore_timing=0; ++ if (!core_ok || !blipper_state_read(resampler_l,p+80+core,l) || !blipper_state_read(resampler_r,p+80+core+l,r)) return false; + romdev_clock_ticks=mp_r64(p+16);libretro_samples_count=mp_r64(p+24);libretro_frames_count=mp_r64(p+32); + turbo_a_counter=mp_r32(p+40);turbo_b_counter=mp_r32(p+44);audio_out_buffer_pos=0; + return true; @@ -294,7 +330,7 @@ diff --git a/libgambatte/libretro/libretro.cpp b/libgambatte/libretro/libretro.c + return 1; +} +void romdev_deterministic_disable(void) { romdev_clock_enabled=0;invalidate_serialize_size(); } -+unsigned romdev_state_schema(void) { return 0x47420101; } ++unsigned romdev_state_schema(void) { return 0x47420102; } +unsigned romdev_state_digest(unsigned char *out, unsigned len) { + size_t size = retro_serialize_size(); + if (!out || !romdev_clock_enabled || len!=32 || !size || size>1048576 || use_cc_resampler || blend_frames) return 0; @@ -319,3 +355,34 @@ diff --git a/libgambatte/src/video.cpp b/libgambatte/src/video.cpp lycIrq_.saveState(state); +diff --git a/libgambatte/src/gambatte-memory.cpp b/libgambatte/src/gambatte-memory.cpp +--- a/libgambatte/src/gambatte-memory.cpp ++++ b/libgambatte/src/gambatte-memory.cpp +@@ -1,3 +1,8 @@ ++#include "romdev_multiplayer.h" ++extern "C" { ++extern uint32_t romdev_gb_blit_time, romdev_gb_blank_lcd, romdev_gb_restore_timing; ++} ++ + // + // Copyright (C) 2007 by sinamas + // +@@ -72,6 +77,10 @@ + state.mem.dmaDestination = dmaDestination_; + state.mem.oamDmaPos = oamDmaPos_; ++ if (romdev_clock_enabled) { ++ romdev_gb_blit_time = intreq_.eventTime(intevent_blit); ++ romdev_gb_blank_lcd = blanklcd_ ? 1 : 0; ++ } + #ifdef HAVE_NETWORK + state.mem.serialize_value = serialize_value_; +@@ -137,6 +146,10 @@ + ? lcd_.nextMode1IrqTime() + : state.cpu.cycleCounter); + blanklcd_ = false; ++ if (romdev_clock_enabled && romdev_gb_restore_timing) { ++ intreq_.setEventTime(romdev_gb_blit_time); ++ blanklcd_ = romdev_gb_blank_lcd != 0; ++ } + + if (!isCgb()) diff --git a/packages/romdevtools/test/fixtures/multiplayer/gb-fixture.mjs b/packages/romdevtools/test/fixtures/multiplayer/gb-fixture.mjs index cbc116c7..67dc2e74 100644 --- a/packages/romdevtools/test/fixtures/multiplayer/gb-fixture.mjs +++ b/packages/romdevtools/test/fixtures/multiplayer/gb-fixture.mjs @@ -1,6 +1,6 @@ // Small MBC3 timer ROM: native joypad, timer, serial, audio, WRAM bank probes. // No injected multiplayer ABI is required by this core-level fixture. -export function gbFixture(cgb = true, haltRtc = false) { +export function gbFixture(cgb = true, haltRtc = false, pauseBeforeLcd = false) { const rom = new Uint8Array(32768), labels = new Map(), fixups = []; let pc = 0x150; const emit = (...bytes) => { rom.set(bytes, pc); pc += bytes.length; }; @@ -29,7 +29,14 @@ export function gbFixture(cgb = true, haltRtc = false) { store(0xff4f,1);emit(0x21,0,0x98,0x01,0,4);label('attrs');emit(0xaf,0x22,0x0b,0x78,0xb1);jr(0x20,'attrs');store(0xff4f,0); store(0xff68,0x80);for(const byte of [0xff,0x7f,0,0,0x1f,0,0,0x7c])store(0xff69,byte); } - store(0xff47,0xe4);store(0xff40,0x91); + if(pauseBeforeLcd) { + store(0xc020,0x5a);store(0xff41,8); + label('paused');emit(0xfa,0x21,0xc0,0xb7);jr(0x28,'paused'); + // Different visible sprite attributes after release exercise restoration of + // dormant sprite-list entries after the core has visited a later frame. + for(let i=0;i<4;i++)for(const [j,v]of [16,16+i*24,0,3+i].entries())store(0xfe00+i*4+j,v); + } + store(0xff47,0xe4);store(0xff40,pauseBeforeLcd?0x93:0x91); label('frame');emit(0xf0,0x44,0xfe,144);jr(0x20,'frame'); store(0xff00,0x20);emit(0xf0,0,0xea,0x00,0xc0,0xe0,0x43); emit(0x21,1,0xc0,0x34); diff --git a/packages/romdevtools/test/multiplayer-core.test.js b/packages/romdevtools/test/multiplayer-core.test.js index f75dacf4..8f2522db 100644 --- a/packages/romdevtools/test/multiplayer-core.test.js +++ b/packages/romdevtools/test/multiplayer-core.test.js @@ -103,6 +103,29 @@ test('deterministic load leaves the CPU at reset before hidden warm-up',async t= } }); +for (const platform of ['gb', 'gbc']) test(`${platform}: LCD-off bootstrap restores before world initialization`, async t => { + const h = await host(platform, 15, true, undefined, gbFixture(platform === 'gbc', false, true)); + t.after(() => h.dispose()); + h.stepFrames(12); + assert.equal(h.readMemory('system_ram', 0x20, 1)[0], 0x5a); + for (const wait of [0, 1, 5, 30]) { + h.stepFrames(wait); + assert.equal(h.readMemory('system_ram', 0x21, 1)[0], 0); + const snapshot = h.serializeState(), before = digest(h); + const inputs = Array.from({length: 40}, (_, f) => ({ports: [{right: f % 3 === 0, a: f % 7 < 3}]})); + const run = () => inputs.map((input, f) => { + if (f === 8) h.writeMemory('system_ram', 0x21, new Uint8Array([1])); + return frame(h, input); + }); + const expected = run(); + h.unserializeState(snapshot); + assert.equal(digest(h), before, `LCD-off restore after ${wait} extra frames`); + assert.deepEqual(h.serializeState(), snapshot); + assert.deepEqual(run(), expected, 'LCD remains off, then native LCD/STAT IRQ/sprites resume'); + h.unserializeState(snapshot); + } +}); + // These parsers belong only to the pinned core's tests. Consumers use stateDigest(). function fields(snapshot,platform){ const out=new Map(),dv=new DataView(snapshot.buffer,snapshot.byteOffset,snapshot.byteLength); @@ -112,11 +135,32 @@ function fields(snapshot,platform){ while(pos{ + const h=await host(platform,15,true,undefined,gbFixture(platform==='gbc',false,true));t.after(()=>h.dispose()); + h.stepFrames(12);h.writeMemory('system_ram',0x21,new Uint8Array([1]));h.stepFrames(20); + const baseline=h.serializeState(),original=digest(h),map=fields(baseline,platform); + assert.equal(h.stateDigest().schema,0x47420102); + const active=baseline.slice(),irq=map.get('nm0irq');assert.ok(irq&&irq.size>0); + active[irq.pos+irq.size-1]^=2;h.unserializeState(active);assert.notEqual(digest(h),original,'active STAT mode-0 deadline'); + for(const at of [64,68]){ + h.unserializeState(baseline);const changed=baseline.slice();changed[at]^=1;h.unserializeState(changed); + assert.notEqual(digest(h),original,at===64?'native blit deadline':'blank-LCD phase'); + } + h.unserializeState(baseline); + for(const [at,value]of [[12,1],[68,2]]){ + const invalid=baseline.slice();invalid[at]=value;assert.throws(()=>h.unserializeState(invalid),/rejected/); + assert.equal(digest(h),original,'invalid envelope cannot mutate a live core'); + } + // Original v1 deterministic envelopes were shorter and carry another schema. + const old=new Uint8Array(baseline.length-16);old.set(baseline.subarray(0,64));old.set(baseline.subarray(80),64);old[12]=1; + assert.throws(()=>h.unserializeState(old),/size mismatch|rejected/);assert.equal(digest(h),original); +}); + for(const platform of ['gb','gbc','nes'])test(`${platform}: each causal state class participates in the digest`,async t=>{ const h=await host(platform);t.after(()=>h.dispose());h.setInput({ports:[{a:true}]});h.stepFrames(130); const baseline=h.serializeState(),original=digest(h),map=fields(baseline,platform); @@ -124,7 +168,7 @@ for(const platform of ['gb','gbc','nes'])test(`${platform}: each causal state cl for(const [tag,offset,bit]of probes){const f=map.get(tag);assert.ok(f&&offset