diff --git a/Packages/App/Src/Audio.rux b/Packages/App/Src/Audio.rux index 2beff72..f2fbaab 100644 --- a/Packages/App/Src/Audio.rux +++ b/Packages/App/Src/Audio.rux @@ -4,14 +4,15 @@ /// `docs/dev/phases/phase-05-apu.md`「スコープの調整」によりフェーズ8へ持ち越されていた分)。 import Core::MutableSlice; -import Core::Slice; -import GbCore::{ Apu, ApuDrainSamples }; +import Core::{ Slice, #target }; +import GbCore::{ Apu, ApuDrainSamples, ApuSampleRate }; import Sdl3::{ SdlAudioS16Le, SdlAudioDeviceDefaultPlayback, SdlAudioSpec, SDL_GetCurrentAudioDriver, SDL_GetAudioDeviceFormat, SDL_OpenAudioDeviceStream, SDL_GetAudioStreamFormat, SDL_PutAudioStreamData, SDL_ResumeAudioStreamDevice, SDL_GetAudioStreamQueued, SDL_DestroyAudioStream, SDL_Delay, SDL_GetError, + SDL_SetHint, }; /// 診断ログ用の1行バッファ。実機でしか再現しない音声不具合を、現地で1回 @@ -50,12 +51,13 @@ func AudioLogSpec(prefix: Slice, spec: *SdlAudioSpec) { AudioLogLine(@buf); } -const SampleRate: int32 = 48000; +const SampleRate: int32 = ApuSampleRate; const Channels: int32 = 2; const BytesPerSample: int32 = 2; /// ペーシングの目標: キューに積まれたバイト数がこれを超える間は新フレームの /// 生成を待つ(=オーディオの消費速度で実行速度が決まる)。約4フレーム分。 const TargetQueuedBytes: int32 = (SampleRate / 60) * Channels * BytesPerSample * 4; +const LowQueuedBytes: int32 = (SampleRate / 60) * Channels * BytesPerSample * 2; /// 実行時ステータスをログに出す間隔(フレーム数、約1秒)。毎フレーム出すと /// 標準出力がスクロールして読めなくなるうえ処理も遅くなるため。 const StatsLogIntervalFrames: int32 = 60; @@ -65,6 +67,7 @@ pub struct Audio { pub frameCount: int32; pub everNonZeroSample: bool; pub putFailedLogged: bool; + pub skippedVideoFrames: int32; /// Ruxコンパイラのmacos-x86_64ターゲット向けコード生成バグの回避用ダミー /// フィールド。削除禁止。詳細は docs/dev/PLAN.md 1.2「Ruxコンパイラの /// 既知バグ」を参照。 @@ -76,6 +79,7 @@ pub func AudioInit() -> Audio { a.frameCount = 0; a.everNonZeroSample = false; a.putFailedLogged = false; + a.skippedVideoFrames = 0; a.reserved = 0; var driverBuf: PathBuf; @@ -97,7 +101,15 @@ pub func AudioInit() -> Audio { spec.channels = Channels; spec.freq = SampleRate; - a.stream = SDL_OpenAudioDeviceStream(SdlAudioDeviceDefaultPlayback, @spec, null, null); + // macOSの既定(1024サンプルフレーム、約23ms)だとキューが約2KBずつ段階的に + // 減り、ペーシング目標との差が画面提示の待ちで食い潰されて描画スキップが + // 起きる。512にするとM4実機でフレーム開始時のキュー最小値が約1KB増えた。 + // 他OSは未検証のため既定のまま。 + when #target.os == .macOS { + SDL_SetHint("SDL_AUDIO_DEVICE_SAMPLE_FRAMES\0".data, "512\0".data); + } + + a.stream =SDL_OpenAudioDeviceStream(SdlAudioDeviceDefaultPlayback, @spec, null, null); if a.stream == null { AudioLogError("audio: SDL_OpenAudioDeviceStream に失敗: "); return a; @@ -113,6 +125,17 @@ pub func AudioInit() -> Audio { if !SDL_ResumeAudioStreamDevice(a.stream) { AudioLogError("audio: SDL_ResumeAudioStreamDevice に失敗: "); } + + // 空のキューから始めると最初の数フレームで描画スキップが起きるため、 + // ペーシング目標まで無音を積んでおく。定常時のキュー量は変わらない。 + // 8192バイトの配列はTargetQueuedBytes(5872)を収める。 + var silence: int16[4096]; + var i: uint = 0; + while i < 4096 { + silence[i] = 0; + i += 1; + } + SDL_PutAudioStreamData(a.stream, @silence[0] as *opaque, TargetQueuedBytes); return a; } @@ -170,6 +193,8 @@ pub func AudioPushFrame(a: *var Audio, apu: *var Apu, volume: int32) { PathBufAppendInt(@statsBuf, volume); PathBufAppend(@statsBuf, " everNonZeroSample="); PathBufAppend(@statsBuf, a.everNonZeroSample ? "true" : "false"); + PathBufAppend(@statsBuf, " skippedVideoFrames="); + PathBufAppendInt(@statsBuf, a.skippedVideoFrames); AudioLogLine(@statsBuf); } } @@ -182,6 +207,11 @@ pub func AudioPace(a: *Audio) { } } +/// 音声キューが約2フレームを切ったら、次の画面描画を省いて補充を優先する。 +pub func AudioNeedsVideoSkip(a: *Audio) -> bool { + return a.stream != null && SDL_GetAudioStreamQueued(a.stream) < LowQueuedBytes; +} + pub func AudioDestroy(a: *var Audio) { if a.stream != null { SDL_DestroyAudioStream(a.stream); diff --git a/Packages/App/Src/Main.rux b/Packages/App/Src/Main.rux index dbc5f6c..f99885a 100644 --- a/Packages/App/Src/Main.rux +++ b/Packages/App/Src/Main.rux @@ -4,7 +4,7 @@ import Core::Slice; import GbCore::{ Cpu, Bus, GbMode, - CpuReset, BusInit, BusLoadRom, BusPowerOn, CpuStep, + CpuReset, BusInit, BusLoadRom, BusPowerOn, CpuRun, BusFlushApu, MbcSyncWallClock, }; import Sdl3::{ @@ -17,6 +17,10 @@ import Sdl3::{ const AppTitle: Slice = "RuxBoy\0"; const FrameTCycles: uint64 = 70224; const MaxArgs: uint = 32; +/// 音声開始前の空提示回数。Windows(D3D11)ではウィンドウ表示直後の4〜5回目の +/// 提示が合計約75msかかり、無音プリフィル(約66ms)を使い切って描画スキップが +/// 起きていた。 +const WarmUpPresents: int32 = 10; func Print(text: Slice) { PlatformWrite(1, text.data as *opaque, text.length as uint); @@ -124,6 +128,9 @@ func Main() -> int { return 1; } + // 提示の初回の待ちを音声の再生開始より前に済ませる(WarmUpPresents参照)。 + if !opts.headless { VideoWarmUp(@video, WarmUpPresents); } + var audio = AudioInit(); if !AudioIsValid(@audio) { PrintLine("オーディオデバイスのオープンに失敗しました。音声なしで続行します。"); @@ -139,10 +146,17 @@ func Main() -> int { const SaveIdleFrames: int32 = 60; var savePending = false; var saveIdleFrames: int32 = 0; + var skippedLastFrame = false; while running { if opts.headless && frameCount >= opts.frames { break; } + // 音声が不足した時だけ描画負荷を減らす。連続スキップは避ける。 + let skipRender = !opts.headless && frameCount > 0 && !skippedLastFrame && AudioNeedsVideoSkip(@audio); + bus.ppu.renderEnabled = !skipRender; + skippedLastFrame = skipRender; + if skipRender { audio.skippedVideoFrames += 1; } + var event: SdlEvent; while SDL_PollEvent(@event) { if event.kind == SdlEventQuit { @@ -168,16 +182,16 @@ func Main() -> int { // 1回のループが実ハードウェア半フレーム分しか進めず、映像更新も // オーディオ生成量も本来の半分になってしまう)。 let frameStart = bus.hwCycles; - while bus.hwCycles - frameStart < FrameTCycles { - CpuStep(@cpu, @bus); - } + cpu.haltBatchEndHwCycles = frameStart + FrameTCycles; + CpuRun(@cpu, @bus, frameStart + FrameTCycles); // MBC3のRTCは呼び出し間の経過秒しか進めない(`MbcSyncWallClock`参照)ため、 // 起動時の1回だけでは止まったままになる。毎フレーム供給し続ける。 MbcSyncWallClock(@bus.cart, WallClockNow() as uint64); - VideoPresent(@video, @bus.ppu.framebuffer[0]); + if !skipRender { VideoPresent(@video, @bus.ppu.framebuffer[0]); } + BusFlushApu(@bus); AudioPushFrame(@audio, @bus.apu, config.volume); if bus.cart.ramDirty { diff --git a/Packages/App/Src/StateFile.rux b/Packages/App/Src/StateFile.rux index 49062a3..0f1c796 100644 --- a/Packages/App/Src/StateFile.rux +++ b/Packages/App/Src/StateFile.rux @@ -28,7 +28,7 @@ func StatePath(romPath: Slice, buf: *var PathBuf) { PathBufAppend(buf, ".state"); } -pub func SaveStateToFile(cpu: *Cpu, bus: *Bus, romPath: Slice) -> bool { +pub func SaveStateToFile(cpu: *Cpu, bus: *var Bus, romPath: Slice) -> bool { let size = SaveStateExpectedSize(bus); let block = malloc(size) as *var uint8; if block == null { return false; } diff --git a/Packages/App/Src/Video.rux b/Packages/App/Src/Video.rux index 32c63da..67bb044 100644 --- a/Packages/App/Src/Video.rux +++ b/Packages/App/Src/Video.rux @@ -81,6 +81,18 @@ pub func VideoPresent(v: *Video, framebuffer: *uint32) { SDL_RenderPresent(v.renderer); } +/// 黒画面を`count`回提示する。音声の再生開始前に呼び、ウィンドウを初めて +/// 表示するときの提示の待ちを先に済ませる。 +pub func VideoWarmUp(v: *Video, count: int32) { + var i: int32 = 0; + while i < count { + SDL_SetRenderDrawColor(v.renderer, 0, 0, 0, 255); + SDL_RenderClear(v.renderer); + SDL_RenderPresent(v.renderer); + i += 1; + } +} + /// 現在の描画内容をBMPへ保存する(`--screenshot`用の検証手段)。`captureTexture` /// (ウィンドウの可視性に依存しないオフスクリーンターゲット)へ描き直してから読み戻す。 pub func VideoScreenshot(v: *Video, path: *char8) -> bool { diff --git a/Packages/Core/Src/Apu.rux b/Packages/Core/Src/Apu.rux index ac56934..d51f4f4 100644 --- a/Packages/Core/Src/Apu.rux +++ b/Packages/Core/Src/Apu.rux @@ -1,4 +1,4 @@ -/// APU: 4ch(矩形波x2/波形メモリ/ノイズ) + フレームシーケンサ + 48kHz ステレオサンプル +/// APU: 4ch(矩形波x2/波形メモリ/ノイズ) + フレームシーケンサ + 22.05kHz ステレオサンプル /// 生成。SDL3 に一切依存しない(core/app 分離、PLAN.md 1.1)。 /// 移植元: `~/dev/_Emu/BubiBoyLite/src/core/apu.odin`(T5-1〜T5-7、T20-2の /// 区間平均/ナイキストフォールバックを含む最終形をそのまま移植)。 @@ -41,8 +41,9 @@ pub const WaveRamEnd: uint16 = 0xFF3F; /// 512Hz = 4194304/8192 の分周に使うT-cycle周期。 pub const FrameSequencerPeriod: int32 = 8192; pub const ApuMaxVolume: int32 = 15; -/// 出力サンプルレート。 -pub const ApuSampleRate: int32 = 48000; +/// PCM出力のサンプルレート。APU内部の波形/フレームシーケンサは +/// 4,194,304HzのT-cycleで進め、音程やゲーム時間は変えない。 +pub const ApuSampleRate: int32 = 22050; /// リングバッファのステレオペア容量。あふれたら最古を破棄する。 pub const ApuRingCapacity: uint = 8192; @@ -90,8 +91,9 @@ pub struct WaveChannel { pub position: int32; /// NR32 bit6-5 を 0/1/2/3 にデコードした値(シフト量ではない)。 pub outputLevel: int32; + pub currentUnits: int32; // 現在のpositionとNR32から導出した出力 /// 区間平均(ボックスフィルタ)用アキュムレータ。単位は「量子化された生の - /// 単位」(-15..15相当)のまま、48kHzサンプル1個ごとに平均してリセットする。 + /// 単位」(-15..15相当)のまま、PCMサンプル1個ごとに平均してリセットする。 pub sampleArea: int32; pub sampleCycles: int32; } @@ -112,6 +114,7 @@ pub struct NoiseChannel { /// APU全体の状態。 pub struct Apu { pub poweredOn: bool; + pub anyChannelEnabled: bool; // チャンネル状態から導出する高速経路用キャッシュ /// 0-7、次にfire(未発火)のstep。 pub frameSequencerStep: int32; @@ -148,7 +151,7 @@ pub struct Apu { /// FF30-FF3F。電源off中も読み書き可。 pub waveRam: uint8[16]; - /// 48kHzダウンサンプリング用固定小数点カウンタ(CpuHz単位で蓄積)。 + /// PCMダウンサンプリング用固定小数点カウンタ(CpuHz単位で蓄積)。 pub sampleCounter: int32; /// リングバッファ(あふれたら最古を破棄)。ステレオはL/R別配列で持つ。 @@ -159,6 +162,27 @@ pub struct Apu { pub ringCount: uint; } +/// トリガー・DAC停止・長さ/スイープクロック後のチャンネル有効状態を同期する。 +pub func ApuRefreshActivity(apu: *var Apu) { + apu.anyChannelEnabled = apu.pulse1.enabled || apu.pulse2.enabled || + apu.wave.enabled || apu.noise.enabled; +} + +pub func ApuRefreshWaveUnit(apu: *var Apu) { + if apu.wave.outputLevel == 0 { + apu.wave.currentUnits = 0; + return; + } + let byteVal = apu.waveRam[(apu.wave.position / 2) as uint]; + var nibble: uint8 = 0; + if (apu.wave.position % 2) == 0 { nibble = byteVal >> 4; } + else { nibble = byteVal & 0x0F; } + var shifted = nibble as int32; + if apu.wave.outputLevel == 2 { shifted >>= 1; } + else if apu.wave.outputLevel == 3 { shifted >>= 2; } + apu.wave.currentUnits = 2 * shifted - 15; +} + func EnvelopeReset(env: *var Envelope) { env.initialVolume = 0; env.increase = false; @@ -199,6 +223,7 @@ func WaveChannelReset(ch: *var WaveChannel) { ch.timer = 0; ch.position = 0; ch.outputLevel = 0; + ch.currentUnits = 0; ch.sampleArea = 0; ch.sampleCycles = 0; } @@ -218,6 +243,7 @@ func NoiseChannelReset(ch: *var NoiseChannel) { /// `apu` を電源offの初期状態にする(レジスタ・chすべてゼロ、リングバッファ空)。 pub func ApuReset(apu: *var Apu) { apu.poweredOn = false; + apu.anyChannelEnabled = false; apu.frameSequencerStep = 0; apu.frameSequencerCycles = 0; @@ -263,6 +289,7 @@ pub func ApuReset(apu: *var Apu) { /// 位置づけ)。NR50/NR51 のみ Pan Docs の実測既定値を反映する。 pub func ApuPowerOn(apu: *var Apu) { apu.poweredOn = true; + apu.anyChannelEnabled = false; apu.nr50 = 0x77; apu.nr51 = 0xF3; apu.noise.lfsr = 0x7FFF; @@ -273,6 +300,7 @@ pub func ApuPowerOn(apu: *var Apu) { /// during power" / "11-regs after power" が検査)。 func ApuPowerOff(apu: *var Apu) { apu.poweredOn = false; + apu.anyChannelEnabled = false; apu.nr10 = 0; apu.nr11 = 0; @@ -562,6 +590,7 @@ func TriggerWave(apu: *var Apu) { apu.wave.timer = WavePeriod(apu.wave.frequency); apu.wave.position = 0; apu.wave.enabled = apu.wave.dacEnabled; + ApuRefreshWaveUnit(apu); } // --- ch4: ノイズ --- @@ -625,6 +654,7 @@ func ClockFrameSequencer(apu: *var Apu) { } apu.frameSequencerStep = (step + 1) & 0x07; + ApuRefreshActivity(apu); } /// DIV(0xFF04)書き込み時の副作用。内部16bitカウンタのbit12(DIVレジスタの @@ -662,9 +692,10 @@ func WaveCycleAverageUnits(apu: *Apu) -> int32 { } /// t_cycles ぶんAPUを進める。bus_tick から呼ばれる。wave/noiseチャンネルは -/// 1 T-cycle進めるたびにその瞬間の出力値をsampleArea/sampleCyclesへ蓄積し -/// (区間平均=ボックスフィルタ)、48kHzサンプル1個を出力する瞬間にarea/cycles +/// 1 T-cycleごとの出力値をsampleArea/sampleCyclesへ蓄積し +/// (区間平均=ボックスフィルタ)、PCMサンプル1個を出力する瞬間にarea/cycles /// の平均値を使う(点サンプリングによるエイリアシングノイズ対策)。 +/// 出力とタイマーが変わらない区間は同じ値をサイクル数ぶんまとめて加算する。 /// Pulseチャンネルは瞬時値のまま(区間平均を行わない)。 /// /// 落とし穴(性能): CPU全メモリアクセスごとに呼ばれる最も熱いパスであり、 @@ -676,6 +707,184 @@ func WaveCycleAverageUnits(apu: *Apu) -> int32 { /// (フェーズ1.5計測)から176%realtimeまで落ち込んだため、このループの本体に /// 手動でインライン化した(詳細はphase-05-apu.md)。 pub func ApuTick(apu: *var Apu, tCycles: int) { + // CPU側で保留した長い区間は次のイベントまで直接進める。周期の途中で + // 毎T-cycle波形/ノイズ/サンプル境界を検査する費用を払わない。 + // フレームシーケンサの境界だけは「クロック後にその1cycleの波形を + // 積分する」という既存の順序を維持するため、従来経路に渡す。 + if tCycles >= 32 { + var remaining = tCycles; + while remaining > 0 { + var span = remaining; + let sampleUntil = (4194304 - apu.sampleCounter + ApuSampleRate - 1) / ApuSampleRate; + if span > sampleUntil { span = sampleUntil; } + if apu.poweredOn { + let frameUntil = FrameSequencerPeriod - apu.frameSequencerCycles; + if span > frameUntil { span = frameUntil; } + if apu.pulse1.enabled && apu.pulse1.timer < span { span = apu.pulse1.timer; } + if apu.pulse2.enabled && apu.pulse2.timer < span { span = apu.pulse2.timer; } + if apu.wave.enabled && apu.wave.timer < span { span = apu.wave.timer; } + if apu.noise.enabled && apu.noise.timer < span { span = apu.noise.timer; } + if span < 1 { span = 1; } + if span == frameUntil { + if span == 1 { + ApuTick(apu, 1); + remaining -= 1; + continue; + } + span -= 1; + } + + apu.frameSequencerCycles += span; + if apu.pulse1.enabled { + apu.pulse1.timer -= span; + if apu.pulse1.timer <= 0 { + apu.pulse1.timer += PulsePeriod(apu.pulse1.frequency); + apu.pulse1.dutyStep = (apu.pulse1.dutyStep + 1) & 0x07; + } + } + if apu.pulse2.enabled { + apu.pulse2.timer -= span; + if apu.pulse2.timer <= 0 { + apu.pulse2.timer += PulsePeriod(apu.pulse2.frequency); + apu.pulse2.dutyStep = (apu.pulse2.dutyStep + 1) & 0x07; + } + } + var waveUnit: int32 = 0; + if apu.wave.enabled && apu.wave.dacEnabled && apu.wave.outputLevel != 0 { + waveUnit = apu.wave.currentUnits; + } + apu.wave.sampleArea += waveUnit * span; + apu.wave.sampleCycles += span; + if apu.wave.enabled { + apu.wave.timer -= span; + if apu.wave.timer <= 0 { + apu.wave.timer += WavePeriod(apu.wave.frequency); + apu.wave.position = (apu.wave.position + 1) & 0x1F; + ApuRefreshWaveUnit(apu); + } + } + var noiseUnit: int32 = 0; + if apu.noise.enabled && apu.noise.dacEnabled { + if (apu.noise.lfsr & 1) == 0 { noiseUnit = apu.noise.envelope.volume; } + else { noiseUnit = -apu.noise.envelope.volume; } + } + apu.noise.sampleArea += noiseUnit * span; + apu.noise.sampleCycles += span; + if apu.noise.enabled { + apu.noise.timer -= span; + if apu.noise.timer <= 0 { + apu.noise.timer += NoisePeriod(apu.nr43); + let feedback = (apu.noise.lfsr & 1) ^ ((apu.noise.lfsr >> 1) & 1); + apu.noise.lfsr = (apu.noise.lfsr >> 1) | (feedback << 14); + if (apu.nr43 & 0x08) != 0 { + apu.noise.lfsr = (apu.noise.lfsr & ~(0x0040 as uint16)) | (feedback << 6); + } + } + } + } + + apu.sampleCounter += span * ApuSampleRate; + if apu.sampleCounter >= 4194304 { + apu.sampleCounter -= 4194304; + var waveUnits: int32 = 0; + if apu.wave.sampleCycles > 0 { + if WaveAboveNyquist(apu.wave.frequency) { + waveUnits = WaveCycleAverageUnits(apu); + } else { + waveUnits = apu.wave.sampleArea / apu.wave.sampleCycles; + } + } + apu.wave.sampleArea = 0; + apu.wave.sampleCycles = 0; + var noiseUnits: int32 = 0; + if apu.noise.sampleCycles > 0 { + noiseUnits = apu.noise.sampleArea / apu.noise.sampleCycles; + } + apu.noise.sampleArea = 0; + apu.noise.sampleCycles = 0; + var left: int16 = 0; + var right: int16 = 0; + MixSample(apu, waveUnits, noiseUnits, @left, @right); + PushSample(apu, left, right); + } + remaining -= span; + } + return; + } + + // 全チャンネル停止中は音量・波形の再計算が不要。次のサンプルまたは + // フレームシーケンサ境界までなら、区間平均の分母だけ進める。 + if tCycles > 0 && tCycles <= 8 && apu.poweredOn && + !apu.anyChannelEnabled && + apu.sampleCounter + tCycles * ApuSampleRate < 4194304 && + apu.frameSequencerCycles + tCycles < FrameSequencerPeriod { + apu.frameSequencerCycles += tCycles; + apu.wave.sampleCycles += tCycles as int32; + apu.noise.sampleCycles += tCycles as int32; + apu.sampleCounter += tCycles * ApuSampleRate; + return; + } + + // CPUメモリアクセス由来の短い区間で、サンプル・フレームシーケンサ・ + // チャンネル周期のいずれの境界も越えない場合は同じ出力が続く。 + // 区間平均の和と各タイマーを一括更新し、1 T-cycleごとの反復を省く。 + if tCycles > 0 && tCycles <= 8 && + apu.poweredOn && + apu.sampleCounter + tCycles * ApuSampleRate < 4194304 && + apu.frameSequencerCycles + tCycles < FrameSequencerPeriod && + (!apu.pulse1.enabled || apu.pulse1.timer > tCycles) && + (!apu.pulse2.enabled || apu.pulse2.timer > tCycles) && + (!apu.wave.enabled || apu.wave.timer > tCycles) { + apu.frameSequencerCycles += tCycles; + if apu.pulse1.enabled { apu.pulse1.timer -= tCycles; } + if apu.pulse2.enabled { apu.pulse2.timer -= tCycles; } + + var waveUnit: int32 = 0; + if apu.wave.enabled && apu.wave.dacEnabled && apu.wave.outputLevel != 0 { + waveUnit = apu.wave.currentUnits; + } + apu.wave.sampleArea += waveUnit * (tCycles as int32); + apu.wave.sampleCycles += tCycles as int32; + if apu.wave.enabled { apu.wave.timer -= tCycles as int32; } + + var noiseUnit: int32 = 0; + if apu.noise.enabled && apu.noise.dacEnabled { + if (apu.noise.lfsr & 1) == 0 { + noiseUnit = apu.noise.envelope.volume; + } else { + noiseUnit = -apu.noise.envelope.volume; + } + } + var firstNoiseCycles = tCycles; + let noiseEdge = apu.noise.enabled && apu.noise.timer <= tCycles; + if noiseEdge { + firstNoiseCycles = apu.noise.timer; + if firstNoiseCycles < 1 { firstNoiseCycles = 1; } + } + apu.noise.sampleArea += noiseUnit * (firstNoiseCycles as int32); + apu.noise.sampleCycles += tCycles as int32; + if apu.noise.enabled { + apu.noise.timer -= tCycles as int32; + if noiseEdge { + apu.noise.timer += NoisePeriod(apu.nr43); + let feedback = (apu.noise.lfsr & 1) ^ ((apu.noise.lfsr >> 1) & 1); + apu.noise.lfsr = (apu.noise.lfsr >> 1) | (feedback << 14); + if (apu.nr43 & 0x08) != 0 { + apu.noise.lfsr = (apu.noise.lfsr & ~(0x0040 as uint16)) | (feedback << 6); + } + var nextUnit: int32 = 0; + if apu.noise.dacEnabled { + if (apu.noise.lfsr & 1) == 0 { nextUnit = apu.noise.envelope.volume; } + else { nextUnit = -apu.noise.envelope.volume; } + } + apu.noise.sampleArea += nextUnit * ((tCycles - firstNoiseCycles) as int32); + } + } + + apu.sampleCounter += tCycles * ApuSampleRate; + return; + } + var cycle: int = 0; while cycle < tCycles { if apu.poweredOn { @@ -705,23 +914,7 @@ pub func ApuTick(apu: *var Apu, tCycles: int) { // ch3(波形メモリ): 区間平均用アキュムレータへの蓄積 + 周期タイマー前進 var waveUnit: int32 = 0; if apu.wave.enabled && apu.wave.dacEnabled && apu.wave.outputLevel != 0 { - let byteVal = apu.waveRam[(apu.wave.position / 2) as uint]; - var nibble: uint8 = 0; - if (apu.wave.position % 2) == 0 { - nibble = byteVal >> 4; - } else { - nibble = byteVal & 0x0F; - } - let sample = nibble as int32; - var shifted: int32 = 0; - if apu.wave.outputLevel == 1 { - shifted = sample; // 100% - } else if apu.wave.outputLevel == 2 { - shifted = sample >> 1; // 50% - } else { - shifted = sample >> 2; // 25% - } - waveUnit = 2 * shifted - 15; + waveUnit = apu.wave.currentUnits; } apu.wave.sampleArea += waveUnit; apu.wave.sampleCycles += 1; @@ -730,6 +923,7 @@ pub func ApuTick(apu: *var Apu, tCycles: int) { if apu.wave.timer <= 0 { apu.wave.timer += WavePeriod(apu.wave.frequency); apu.wave.position = (apu.wave.position + 1) & 0x1F; + ApuRefreshWaveUnit(apu); } } @@ -865,11 +1059,12 @@ func MixSample(apu: *Apu, waveUnits: int32, noiseUnits: int32, left: *var int16, func PushSample(apu: *var Apu, left: int16, right: int16) { apu.ringLeft[apu.ringWrite] = left; apu.ringRight[apu.ringWrite] = right; - apu.ringWrite = (apu.ringWrite + 1) % ApuRingCapacity; + // 容量は2の冪。Releaseの剰余最適化に頼らずマスクで折り返す。 + apu.ringWrite = (apu.ringWrite + 1) & (ApuRingCapacity - 1); if apu.ringCount < ApuRingCapacity { apu.ringCount += 1; } else { - apu.ringRead = (apu.ringRead + 1) % ApuRingCapacity; // 満杯: 最古を破棄 + apu.ringRead = (apu.ringRead + 1) & (ApuRingCapacity - 1); // 満杯: 最古を破棄 } } @@ -886,7 +1081,7 @@ pub func ApuDrainSamples(apu: *var Apu, dst: MutableSlice) -> uint { while i < n { dst.data[i * 2] = apu.ringLeft[apu.ringRead]; dst.data[i * 2 + 1] = apu.ringRight[apu.ringRead]; - apu.ringRead = (apu.ringRead + 1) % ApuRingCapacity; + apu.ringRead = (apu.ringRead + 1) & (ApuRingCapacity - 1); i += 1; } apu.ringCount -= n; @@ -1038,6 +1233,7 @@ pub func ApuWriteRegister(apu: *var Apu, addr: uint16, value: uint8) { if addr >= WaveRamStart && addr <= WaveRamEnd { apu.waveRam[(addr - WaveRamStart) as uint] = value; // 電源off中も書き込み可 + ApuRefreshWaveUnit(apu); return; } @@ -1111,6 +1307,7 @@ pub func ApuWriteRegister(apu: *var Apu, addr: uint16, value: uint8) { } else if addr == Nr32Addr { apu.nr32 = value; apu.wave.outputLevel = ((value >> 5) & 0x03) as int32; + ApuRefreshWaveUnit(apu); } else if addr == Nr33Addr { apu.nr33 = value; apu.wave.frequency = (apu.wave.frequency & 0x700) | (value as int32); @@ -1150,4 +1347,5 @@ pub func ApuWriteRegister(apu: *var Apu, addr: uint16, value: uint8) { } else if addr == Nr51Addr { apu.nr51 = value; } + ApuRefreshActivity(apu); } diff --git a/Packages/Core/Src/Bus.rux b/Packages/Core/Src/Bus.rux index ffbab34..4280871 100644 --- a/Packages/Core/Src/Bus.rux +++ b/Packages/Core/Src/Bus.rux @@ -44,6 +44,11 @@ pub struct Bus { pub objPaletteRam: uint8[64]; pub bcps: uint8; pub ocps: uint8; + /// パレットRAMをARGBへ変換済みの32色(パレット×4+色番号)。描画のたびに + /// 変換しないよう、FF69/FF6B書き込み時に該当色だけ更新する。 + /// パレットRAMを直接書き換えた後はBusRefreshPaletteCacheを呼ぶ。 + pub bgPaletteArgb: uint32[32]; + pub objPaletteArgb: uint32[32]; // CGB HDMA/GDMA(FF51-FF55) pub hdmaSource: uint16; @@ -70,6 +75,14 @@ pub struct Bus { // APU pub apu: Apu; + /// CPU実行中にまだAPUへ渡していないハードウェアT-cycle。 + pub apuPendingCycles: int; + + // 遅延同期(BusSync参照)。Timer/PPU/DMAは`synced*`の時点まで進んでいる。 + // `hwCycles`が`syncAtHwCycles`に達するか、I/Oに触れるまで更新を遅らせる。 + pub syncedCycles: uint64; + pub syncedHwCycles: uint64; + pub syncAtHwCycles: uint64; // OAM DMA (FF46) pub dmaActive: bool; @@ -122,7 +135,11 @@ pub func BusInit(bus: *var Bus) { bus.joypSelectAction = false; bus.joypSelectDirection = false; bus.joypPressed = 0; + bus.ppu.renderEnabled = true; ApuReset(@bus.apu); + bus.apuPendingCycles = 0; + BusResetSync(bus); + BusRefreshPaletteCache(bus); var i: uint = 0; while i < IoSize { @@ -150,31 +167,156 @@ pub func BusPowerOn(bus: *var Bus) { ApuPowerOn(@bus.apu); } -/// t_cycles ぶん時間を進める。CPU の全メモリアクセスごとに呼ばれ、 -/// Timer/PPU/OAM DMA を駆動する唯一の場所。 +/// tCycles ぶん時間を進め、周辺機器も即座に同期する(GDMAやテスト用)。 pub func BusTick(bus: *var Bus, tCycles: int) { - let cyclesU = tCycles as uint64; - bus.cycles += cyclesU; - + bus.cycles += tCycles as uint64; // T6-6: ダブルスピード中、CPU/Timer/シリアルは2倍速、PPU/APUは等速で進む // (「CPUの1 M-cycleにつき、PPU/APUへは2 T-cycleだけ供給」する方式)。 // 逆にするとTimerの音程が半オクターブずれたりゲームが倍速になったりする // 落とし穴があるため、Timer/OAM DMAはCPU側のtCyclesのまま進める。 - var hwCycles = tCycles; if bus.doubleSpeed { - hwCycles = tCycles / 2; + bus.hwCycles += (tCycles / 2) as uint64; + } else { + bus.hwCycles += tCycles as uint64; } - bus.hwCycles += hwCycles as uint64; + BusFlushApu(bus); +} - TimerTick(bus, tCycles); - PpuTick(bus, hwCycles); - ApuTick(@bus.apu, hwCycles); +/// 保留中の時間をAPUへ反映する。音声レジスタ・保存状態・音声出力の前に呼ぶ。 +pub func BusFlushApu(bus: *var Bus) { + BusSync(bus); + if bus.apuPendingCycles > 0 { + ApuTick(@bus.apu, bus.apuPendingCycles); + bus.apuPendingCycles = 0; + } +} - var mCycles = tCycles / 4; - while mCycles > 0 { - DmaTickOneMcycle(bus); - mCycles -= 1; +/// CPU専用。時刻だけ進め、次のイベント時刻に達したときだけ周辺機器を同期する。 +/// 落とし穴(性能): Rux Release がインライン化しないため、CpuRead8/CpuWrite8と +/// CpuRunの命令フェッチはこの本体を手で展開している。変更するときは揃える。 +pub func BusCpuTick(bus: *var Bus, tCycles: int) { + bus.cycles += tCycles as uint64; + if bus.doubleSpeed { + bus.hwCycles += (tCycles / 2) as uint64; + } else { + bus.hwCycles += tCycles as uint64; } + if bus.hwCycles >= bus.syncAtHwCycles { BusSync(bus); } +} + +/// 遅延同期の基準を現在時刻に合わせ、次のアクセスで同期させる。 +/// cycles/hwCyclesを外から書き換えた後(BusInit・保存状態の復元)に呼ぶ。 +pub func BusResetSync(bus: *var Bus) { + bus.syncedCycles = bus.cycles; + bus.syncedHwCycles = bus.hwCycles; + bus.syncAtHwCycles = bus.hwCycles; +} + +/// Timer/PPU/OAM DMAを現在時刻まで進め、APUの保留時間を加算する。 +/// +/// 落とし穴(性能): 以前はCPUの4 T-cycleアクセスごとにTimer/PPU/DMAを呼んで +/// いたが、Rux Releaseは関数インライン化を行わないため、何も起きない区間でも +/// 呼び出し費用が積み重なっていた。いまはCPU側が時刻だけ進め、次の状態変化 +/// (PPUモード境界、TIMAオーバーフロー、DMA/TMAリロード中)の時刻 +/// `syncAtHwCycles`に達したときと、I/O領域に触れたときだけここを通す。 +/// 状態変化の起きるアクセスで同期するため、割り込みフラグの立つM-cycleは +/// 逐次更新と同じになる。 +pub func BusSync(bus: *var Bus) { + let cpuDelta = (bus.cycles - bus.syncedCycles) as int; + let hwDelta = (bus.hwCycles - bus.syncedHwCycles) as int; + // 先に基準を進める(DMA/HDMAの読み出しからI/O経由で再入しても二重に進めない)。 + bus.syncedCycles = bus.cycles; + bus.syncedHwCycles = bus.hwCycles; + if cpuDelta > 0 { + TimerTick(bus, cpuDelta); + PpuTick(bus, hwDelta); + bus.apuPendingCycles += hwDelta; + if bus.dmaActive || bus.dmaStartDelay > 0 { + var mCycles = cpuDelta / 4; + while mCycles > 0 { + DmaTickOneMcycle(bus); + mCycles -= 1; + } + } + if bus.apuPendingCycles >= 256 { + ApuTick(@bus.apu, bus.apuPendingCycles); + bus.apuPendingCycles = 0; + } + } + BusScheduleSync(bus); +} + +/// 次に同期が必要なハードウェア時刻を求める。 +func BusScheduleSync(bus: *var Bus) { + if bus.dmaActive || bus.dmaStartDelay > 0 || bus.timerReloadPending > 0 { + bus.syncAtHwCycles = bus.hwCycles; // 次のアクセスで同期 + return; + } + var untilHw: int = 65536; + if (bus.ppu.lcdc & LcdcBitLcdEnable) != 0 { + var nextEvent = CyclesPerLine; + if bus.ppu.mode == ModeOamScan { nextEvent = Mode2Dots; } + else if bus.ppu.mode == ModeDraw { nextEvent = Mode2Dots + Mode3Dots; } + untilHw = nextEvent - bus.ppu.dot; + } + if (bus.tac & 0x04) != 0 { + var period: uint16 = 256; + let speed = bus.tac & 0x03; + if speed == 0 { period = 1024; } + else if speed == 1 { period = 16; } + else if speed == 2 { period = 64; } + let untilEdge = (period - (bus.divCounter & (period - 1))) as int; + let untilOverflow = untilEdge + (255 - bus.tima as int) * (period as int); + // 倍速中はCPUの2 T-cycleがハードウェアの1 T-cycle。切り上げて、 + // オーバーフローを含むアクセスで同期する。 + var overflowHw = untilOverflow; + if bus.doubleSpeed { overflowHw = (untilOverflow + 1) / 2; } + if overflowHw < untilHw { untilHw = overflowHw; } + } + bus.syncAtHwCycles = bus.hwCycles + untilHw as uint64; +} + +/// HALT中、次のタイマーオーバーフロー/PPUイベントより手前をまとめて進める。 +/// 割り込みの発生するM-cycleは通常のCpuStepに渡す。DMA中も逐次更新する。 +/// maxCpuCyclesは現在のフレーム境界までのCPU T-cycle数。 +pub func BusHaltTick(bus: *var Bus, maxCpuCycles: int) -> int { + BusSync(bus); + if maxCpuCycles < 8 || bus.dmaActive || bus.dmaStartDelay > 0 || + (bus.io[0x0F] & bus.ie & 0x1F) != 0 || bus.timerReloadPending > 0 { + return 0; + } + + var mCycles = maxCpuCycles / 4; + if (bus.tac & 0x04) != 0 { + var period: uint16 = 256; + let speed = bus.tac & 0x03; + if speed == 0 { period = 1024; } + else if speed == 1 { period = 16; } + else if speed == 2 { period = 64; } + // TIMAの通常加算はまとめて計算できる。CPUを起こし得る + // オーバーフローの直前だけ通常のM-cycleへ戻す。 + let untilEdge = (period - (bus.divCounter & (period - 1))) as int; + let untilOverflow = untilEdge + (255 - bus.tima as int) * (period as int); + let beforeOverflow = (untilOverflow - 1) / 4; + if mCycles > beforeOverflow { mCycles = beforeOverflow; } + } + + if (bus.ppu.lcdc & LcdcBitLcdEnable) != 0 { + var nextEvent = CyclesPerLine; + if bus.ppu.mode == ModeOamScan { nextEvent = Mode2Dots; } + else if bus.ppu.mode == ModeDraw { nextEvent = Mode2Dots + Mode3Dots; } + let hwPerM = bus.doubleSpeed ? 2 : 4; + let beforeEvent = (nextEvent - bus.ppu.dot - 1) / hwPerM; + if mCycles > beforeEvent { mCycles = beforeEvent; } + } + if mCycles < 2 { return 0; } + + let cpuCycles = mCycles * 4; + let hwCycles = bus.doubleSpeed ? cpuCycles / 2 : cpuCycles; + bus.cycles += cpuCycles as uint64; + bus.hwCycles += hwCycles as uint64; + BusSync(bus); + return cpuCycles; } /// OAM DMA を1 M-cycleぶん進める。 @@ -192,7 +334,12 @@ func DmaTickOneMcycle(bus: *var Bus) { } if bus.dmaActive { - bus.oam[bus.dmaIndex as uint] = BusReadRaw(bus, bus.dmaSource + (bus.dmaIndex as uint16)); + let sourceAddr = bus.dmaSource + (bus.dmaIndex as uint16); + if (sourceAddr >= 0xFF10 && sourceAddr <= 0xFF26) || + (sourceAddr >= 0xFF30 && sourceAddr <= 0xFF3F) { + BusFlushApu(bus); + } + bus.oam[bus.dmaIndex as uint] = BusReadRaw(bus, sourceAddr); bus.dmaIndex += 1; if (bus.dmaIndex as uint) >= OamSize { bus.dmaActive = false; @@ -242,11 +389,11 @@ func TimerAdvanceReload(bus: *var Bus) { } } -/// DIV/TIMA を tCycles ぶん、1 T-cycleずつ進める(falling-edge検出の -/// 取りこぼしを防ぐため、まとめて計算せず逐次進める)。 +/// DIV/TIMA を tCycles ぶん進める。リロードがなく、TIMAがオーバーフロー +/// しない区間は立ち下がりの回数を算出して一括更新する。 /// -/// 落とし穴(性能): CPU全メモリアクセスごとに呼ばれる最も熱いパスであり、Rux -/// Releaseパイプラインは関数インライン化を行わない(external/Rux/Docs/ +/// 落とし穴(性能): 以前はCPU全メモリアクセスごとに呼ばれていた(いまはBusSync +/// 経由)。Rux Releaseパイプラインは関数インライン化を行わない(external/Rux/Docs/ /// Architecture.mdに列挙されたRelease最適化は定数畳み込み/コピー伝播/DCE/ /// CFG整理のみ)。TimerAdvanceReload/TimerSignal/TimerSelectedBit/ /// TimerIncrementTima を1 T-cycleごとに呼んでいた実装から、このループ本体へ @@ -254,6 +401,7 @@ func TimerAdvanceReload(bus: *var Bus) { /// selectedBit/enabled もループ外で1回だけ計算する)。Apu.rux の ApuTick と /// 同じ対策(phase-05-apu.md参照)。 func TimerTick(bus: *var Bus, tCycles: int) { + var remaining = tCycles; let tac = bus.tac; let enabled = (tac & 0x04) != 0; var selectedBit: uint = 7; @@ -263,6 +411,36 @@ func TimerTick(bus: *var Bus, tCycles: int) { else if speed == 2 { selectedBit = 5; } let mask: uint16 = (1 as uint16) << selectedBit; + // リロードも選択DIVビットの立ち下がりも起きない短い区間は、 + // TIMA/IFに変化がないためDIVをまとめて進める。 + if tCycles > 0 && bus.timerReloadPending <= 0 { + let period = mask << 1; + if !enabled || (((bus.divCounter & (period - 1)) as int) + tCycles < period as int) { + bus.divCounter += tCycles as uint16; + bus.timerReloadJustHappened = false; + return; + } + if tCycles > 8 { + let edges = (((bus.divCounter & (period - 1)) as int) + tCycles) / (period as int); + if (bus.tima as int) + edges <= 255 { + bus.divCounter += tCycles as uint16; + bus.tima += edges as uint8; + bus.timerReloadJustHappened = false; + return; + } + // オーバーフローを含む区間は、その立ち下がりの直前まで一括で進め、 + // 残り(遅延同期ではほぼ1アクセス分)だけを逐次処理する。 + let untilEdge = (period - (bus.divCounter & (period - 1))) as int; + let before = untilEdge + (255 - bus.tima as int) * (period as int) - 1; + if before > 0 { + bus.divCounter += before as uint16; + bus.tima = 0xFF; + bus.timerReloadJustHappened = false; + remaining -= before; + } + } + } + var divider = bus.divCounter; var reloadPending = bus.timerReloadPending; var tima = bus.tima; @@ -271,7 +449,7 @@ func TimerTick(bus: *var Bus, tCycles: int) { var reloadJustHappened = false; var cycle: int = 0; - while cycle < tCycles { + while cycle < remaining { // TimerAdvanceReload をインライン化 if reloadPending > 0 { if reloadPending == 1 { @@ -341,7 +519,7 @@ func WramLocate(bus: *Bus, addr: uint16, bank: *var uint8, offset: *var uint16) /// CPU からの読み出し。OAM DMA 中は OAM 領域(FE00-FE9F)読み出しが 0xFF に /// 化ける(DMA自身の内部読み出しはこの制限を受けない `BusReadRaw` を直接使う)。 -pub func BusRead(bus: *Bus, addr: uint16) -> uint8 { +pub func BusRead(bus: *var Bus, addr: uint16) -> uint8 { if bus.dmaActive && addr >= 0xFE00 && addr <= 0xFE9F { return 0xFF; } @@ -349,7 +527,7 @@ pub func BusRead(bus: *Bus, addr: uint16) -> uint8 { } /// OAM DMA によるバス競合を受けない生の読み出し。メモリマップ全域を解決する。 -pub func BusReadRaw(bus: *Bus, addr: uint16) -> uint8 { +pub func BusReadRaw(bus: *var Bus, addr: uint16) -> uint8 { if addr <= 0x7FFF { return MbcRead(@bus.cart, addr); } else if addr <= 0x9FFF { @@ -481,7 +659,8 @@ func JoypadReadP1(bus: *Bus) -> uint8 { } /// I/O レジスタ領域(FF00-FF7F)の読み出しをレジスタごとに振り分ける。 -func BusIoRead(bus: *Bus, addr: uint16) -> uint8 { +func BusIoRead(bus: *var Bus, addr: uint16) -> uint8 { + BusSync(bus); // DIV・LY・STATなどは遅延同期中に古いままなので先に追いつかせる if addr == 0xFF00 { return JoypadReadP1(bus); } else if addr == 0xFF04 { @@ -500,6 +679,7 @@ func BusIoRead(bus: *Bus, addr: uint16) -> uint8 { // FF46 (OAM DMA) は PPU レジスタではないため対象外 return PpuRead(bus, addr); } else if (addr >= 0xFF10 && addr <= 0xFF26) || (addr >= 0xFF30 && addr <= 0xFF3F) { + BusFlushApu(bus); return ApuReadRegister(@bus.apu, addr); } else if addr == 0xFF4D { // KEY1。CGB専用。bit7=現在の速度(読み専用)、bit0=切替準備(読み書き可)、 @@ -547,6 +727,28 @@ func BusIoRead(bus: *Bus, addr: uint16) -> uint8 { return 0xFF; } +/// パレットRAM 1色分(color = パレット×4+色番号)のARGBキャッシュを更新する。 +func BusRefreshPaletteColor(bus: *var Bus, obj: bool, color: uint) { + let index = color * 2; + if obj { + let raw = (bus.objPaletteRam[index] as uint16) | ((bus.objPaletteRam[index + 1] as uint16) << 8); + bus.objPaletteArgb[color] = Rgb555ToArgb(raw); + } else { + let raw = (bus.bgPaletteRam[index] as uint16) | ((bus.bgPaletteRam[index + 1] as uint16) << 8); + bus.bgPaletteArgb[color] = Rgb555ToArgb(raw); + } +} + +/// パレットRAM全体からARGBキャッシュを作り直す(初期化・保存状態の復元後)。 +pub func BusRefreshPaletteCache(bus: *var Bus) { + var color: uint = 0; + while color < 32 { + BusRefreshPaletteColor(bus, false, color); + BusRefreshPaletteColor(bus, true, color); + color += 1; + } +} + /// BCPS/OCPSのオートインクリメントを適用した新しいインデックスレジスタ値を返す。 /// bit7(オートインクリメント有効)が0なら何もしない。bit6は常に1で読める未使用bit /// として保持し、インデックス(bit5-0)だけ+1(64でラップ)する。 @@ -558,6 +760,7 @@ func PaletteIndexIncrement(indexReg: uint8) -> uint8 { /// DIV(FF04)書き込みの共通処理(DIVリセット)。CGBのSTOPによるダブルスピード /// 切替後のDIVリセットからも呼ばれる(Pan Docs "CGB Registers: KEY1")。 pub func TimerWriteDiv(bus: *var Bus) { + BusFlushApu(bus); let oldSignal = TimerSignal(bus.divCounter, bus.tac); ApuNotifyDivWrite(@bus.apu, bus.divCounter); // divCounterをリセットする前(旧値を見る)に呼ぶ bus.divCounter = 0; @@ -568,6 +771,7 @@ pub func TimerWriteDiv(bus: *var Bus) { /// I/O レジスタ領域(FF00-FF7F)の書き込みをレジスタごとに振り分ける。 func BusIoWrite(bus: *var Bus, addr: uint16, value: uint8) { + BusSync(bus); if addr == 0xFF00 { JoypadWriteP1(bus, value); } else if addr == 0xFF04 { @@ -602,6 +806,7 @@ func BusIoWrite(bus: *var Bus, addr: uint16, value: uint8) { } else if (addr >= 0xFF40 && addr <= 0xFF45) || (addr >= 0xFF47 && addr <= 0xFF4B) { PpuWrite(bus, addr, value); } else if (addr >= 0xFF10 && addr <= 0xFF26) || (addr >= 0xFF30 && addr <= 0xFF3F) { + BusFlushApu(bus); ApuWriteRegister(@bus.apu, addr, value); } else if addr == 0xFF4D { // bit0(切替準備)のみ書き込み可能。実際の速度反転はSTOP実行時(Cpu.rux)に行う。 @@ -643,6 +848,7 @@ func BusIoWrite(bus: *var Bus, addr: uint16, value: uint8) { } else if addr == 0xFF69 { if bus.mode == GbMode::Cgb { bus.bgPaletteRam[(bus.bcps & 0x3F) as uint] = value; + BusRefreshPaletteColor(bus, false, (bus.bcps & 0x3F) as uint / 2); bus.bcps = PaletteIndexIncrement(bus.bcps); // 落とし穴: 書き込み時のみオートインクリメント } } else if addr == 0xFF6A { @@ -652,6 +858,7 @@ func BusIoWrite(bus: *var Bus, addr: uint16, value: uint8) { } else if addr == 0xFF6B { if bus.mode == GbMode::Cgb { bus.objPaletteRam[(bus.ocps & 0x3F) as uint] = value; + BusRefreshPaletteColor(bus, true, (bus.ocps & 0x3F) as uint / 2); bus.ocps = PaletteIndexIncrement(bus.ocps); } } else if addr == 0xFF70 { @@ -662,6 +869,8 @@ func BusIoWrite(bus: *var Bus, addr: uint16, value: uint8) { } else { bus.io[(addr - 0xFF00) as uint] = value; } + // LCDC・TAC・TIMA・DMA開始などで次のイベント時刻が変わる。 + BusScheduleSync(bus); } // --- CGB HDMA / GDMA --- @@ -732,12 +941,53 @@ pub func HdmaOnHblank(bus: *var Bus) { /// CPU からの1バイト読み出し。4 T-cycle 消費してから読む。 pub func CpuRead8(cpu: *Cpu, bus: *var Bus, addr: uint16) -> uint8 { - BusTick(bus, 4); + // BusCpuTick(bus, 4) を展開(Rux Releaseはインライン化しない)。 + bus.cycles += 4; + if bus.doubleSpeed { bus.hwCycles += 2; } else { bus.hwCycles += 4; } + if bus.hwCycles >= bus.syncAtHwCycles { BusSync(bus); } + // 命令フェッチ・スタック・作業RAMはCPUアクセスの大半を占めるため、 + // BusRead→BusReadRaw→MbcRead/WramLocateの多段呼び出しを通さず直接読む。 + // OAM DMA中の読み出し制限はFE00-FE9Fだけなので、ここで扱う領域には影響しない。 + if addr < 0x4000 { + let p = bus.cart.romLow; + if p != null { return *(p + addr as uint); } + return MbcRead(@bus.cart, addr); + } + if addr < 0x8000 { + let p = bus.cart.romHigh; + if p != null { return *(p + (addr - 0x4000) as uint); } + return MbcRead(@bus.cart, addr); + } + if addr >= 0xC000 && addr < 0xE000 { + return bus.wram[CpuWramIndex(bus, addr)]; + } + if addr >= 0xFF80 && addr != 0xFFFF { + return bus.hram[(addr - 0xFF80) as uint]; + } return BusRead(bus, addr); } +/// C000-DFFFのCPUアドレスをwram配列の添字へ変換する(WramLocateのエコー無し版)。 +func CpuWramIndex(bus: *Bus, addr: uint16) -> uint { + if addr < 0xD000 { return (addr - 0xC000) as uint; } + var bank = (bus.wramBank & 0x07) as uint; + if bank == 0 { bank = 1; } + return bank * WramBankSize + (addr - 0xD000) as uint; +} + /// CPU からの1バイト書き込み。4 T-cycle 消費してから書く。 pub func CpuWrite8(cpu: *Cpu, bus: *var Bus, addr: uint16, value: uint8) { - BusTick(bus, 4); + // BusCpuTick(bus, 4) を展開(Rux Releaseはインライン化しない)。 + bus.cycles += 4; + if bus.doubleSpeed { bus.hwCycles += 2; } else { bus.hwCycles += 4; } + if bus.hwCycles >= bus.syncAtHwCycles { BusSync(bus); } + if addr >= 0xC000 && addr < 0xE000 { + bus.wram[CpuWramIndex(bus, addr)] = value; + return; + } + if addr >= 0xFF80 && addr != 0xFFFF { + bus.hram[(addr - 0xFF80) as uint] = value; + return; + } BusWrite(bus, addr, value); } diff --git a/Packages/Core/Src/Cpu.rux b/Packages/Core/Src/Cpu.rux index e26ff59..030145a 100644 --- a/Packages/Core/Src/Cpu.rux +++ b/Packages/Core/Src/Cpu.rux @@ -40,6 +40,8 @@ pub struct Cpu { pub illegalOpcodeHit: bool; pub debugBreakOnLdBb: bool; pub ldBbHit: bool; + /// HALT一括更新の上限。0なら従来の1 M-cycle更新を使う。 + pub haltBatchEndHwCycles: uint64; } // --- フラグ操作 --- @@ -98,6 +100,7 @@ pub func CpuReset(cpu: *var Cpu, mode: GbMode) { cpu.illegalOpcodeHit = false; cpu.debugBreakOnLdBb = false; cpu.ldBbHit = false; + cpu.haltBatchEndHwCycles = 0; } /// 未定義オペコードを検知したときの共通処理(停止扱いにする)。 @@ -125,27 +128,39 @@ func ReadImm16(cpu: *var Cpu, bus: *var Bus) -> uint16 { // --- r8 インデックス (0=B,1=C,2=D,3=E,4=H,5=L,6=(HL),7=A) --- /// r8 インデックスからレジスタ(または (HL))の値を読む。 +/// 比較回数を減らすため二分探索の形にしている(CpuExecute の落とし穴参照)。 func R8Get(cpu: *var Cpu, bus: *var Bus, idx: uint8) -> uint8 { - if idx == 0 { return cpu.bc.bytes.hi; } - else if idx == 1 { return cpu.bc.bytes.lo; } - else if idx == 2 { return cpu.de.bytes.hi; } - else if idx == 3 { return cpu.de.bytes.lo; } - else if idx == 4 { return cpu.hl.bytes.hi; } - else if idx == 5 { return cpu.hl.bytes.lo; } - else if idx == 6 { return CpuRead8(cpu, bus, cpu.hl.word); } - else { return cpu.af.bytes.hi; } + if idx < 4 { + if idx < 2 { + if idx == 0 { return cpu.bc.bytes.hi; } + return cpu.bc.bytes.lo; + } + if idx == 2 { return cpu.de.bytes.hi; } + return cpu.de.bytes.lo; + } + if idx < 6 { + if idx == 4 { return cpu.hl.bytes.hi; } + return cpu.hl.bytes.lo; + } + if idx == 7 { return cpu.af.bytes.hi; } + return CpuRead8(cpu, bus, cpu.hl.word); } /// r8 インデックスへレジスタ(または (HL))の値を書く。 func R8Set(cpu: *var Cpu, bus: *var Bus, idx: uint8, v: uint8) { - if idx == 0 { cpu.bc.bytes.hi = v; } - else if idx == 1 { cpu.bc.bytes.lo = v; } - else if idx == 2 { cpu.de.bytes.hi = v; } - else if idx == 3 { cpu.de.bytes.lo = v; } - else if idx == 4 { cpu.hl.bytes.hi = v; } - else if idx == 5 { cpu.hl.bytes.lo = v; } - else if idx == 6 { CpuWrite8(cpu, bus, cpu.hl.word, v); } - else { cpu.af.bytes.hi = v; } + if idx < 4 { + if idx < 2 { + if idx == 0 { cpu.bc.bytes.hi = v; } else { cpu.bc.bytes.lo = v; } + } else { + if idx == 2 { cpu.de.bytes.hi = v; } else { cpu.de.bytes.lo = v; } + } + } else if idx < 6 { + if idx == 4 { cpu.hl.bytes.hi = v; } else { cpu.hl.bytes.lo = v; } + } else if idx == 7 { + cpu.af.bytes.hi = v; + } else { + CpuWrite8(cpu, bus, cpu.hl.word, v); + } } // --- rp16 インデックス (0=BC,1=DE,2=HL,3=SP) --- @@ -188,10 +203,12 @@ func Rp2Set(cpu: *var Cpu, idx: uint8, v: uint16) { /// 条件コードインデックスを評価する。 func CcTest(cpu: *Cpu, idx: uint8) -> bool { - if idx == 0 { return !CpuFlagZ(cpu); } - else if idx == 1 { return CpuFlagZ(cpu); } - else if idx == 2 { return !CpuFlagC(cpu); } - else { return CpuFlagC(cpu); } + if idx < 2 { + let z = (cpu.af.bytes.lo & FlagZ) != 0; + return idx == 0 ? !z : z; + } + let c = (cpu.af.bytes.lo & FlagC) != 0; + return idx == 2 ? !c : c; } // --- スタック操作 --- @@ -334,8 +351,8 @@ func HandleInterrupts(cpu: *var Cpu, bus: *var Bus) -> bool { // 受理の最初の 2 M-cycle は内部サイクル。PC 上位バイトの PUSH が // IE を書き換え得るので、ベクタはその書き込み後の pending 状態から選ぶ。 - BusTick(bus, 4); - BusTick(bus, 4); + BusCpuTick(bus, 4); + BusCpuTick(bus, 4); cpu.ime = false; let pc = cpu.pc; @@ -363,7 +380,7 @@ func HandleInterrupts(cpu: *var Cpu, bus: *var Bus) -> bool { cpu.sp -= 1; CpuWrite8(cpu, bus, cpu.sp, pc as uint8); - BusTick(bus, 4); + BusCpuTick(bus, 4); cpu.pc = vector; return true; } @@ -376,7 +393,14 @@ pub func CpuStep(cpu: *var Cpu, bus: *var Bus) -> int { if InterruptPending(bus) != 0 { cpu.halted = false; } else { - BusTick(bus, 4); + if cpu.haltBatchEndHwCycles > bus.hwCycles { + let remainingHw = cpu.haltBatchEndHwCycles - bus.hwCycles; + let cpuFactor = bus.doubleSpeed ? 2u64 : 1u64; + if BusHaltTick(bus, (remainingHw * cpuFactor) as int) > 0 { + return (bus.cycles - start) as int; + } + } + BusCpuTick(bus, 4); return (bus.cycles - start) as int; } } @@ -412,16 +436,62 @@ pub func CpuStep(cpu: *var Cpu, bus: *var Bus) -> int { return (bus.cycles - start) as int; } +/// hwCyclesがendHwCyclesに達するまで命令を実行する(フレーム単位の実行用)。 +/// +/// 落とし穴(性能): Rux Releaseはインライン化しないため、命令ごとにCpuStep・ +/// HandleInterrupts・CpuRead8を呼ぶと呼び出し費用が命令の実処理に匹敵する。 +/// よくある状態(非HALT・EI遅延なし)では割り込み判定とROMからの命令フェッチを +/// ここで直接行い、それ以外はCpuStepに任せる。動作はCpuStepの繰り返しと同じ +/// (ただしテスト用のdebugBreakOnLdBbは見ない。使う場合はCpuStepで回す)。 +pub func CpuRun(cpu: *var Cpu, bus: *var Bus, endHwCycles: uint64) { + while bus.hwCycles < endHwCycles { + if cpu.halted || cpu.imeDelay > 0 || cpu.haltBug { + CpuStep(cpu, bus); + } else if cpu.ime && (bus.io[0x0F] & bus.ie & 0x1F) != 0 { + HandleInterrupts(cpu, bus); + } else { + let pc = cpu.pc; + var opcode: uint8 = 0; + if pc < 0x8000 { + // CpuRead8 のROM経路を展開 + bus.cycles += 4; + if bus.doubleSpeed { bus.hwCycles += 2; } else { bus.hwCycles += 4; } + if bus.hwCycles >= bus.syncAtHwCycles { BusSync(bus); } + var window = bus.cart.romHigh; + var offset = (pc as uint) - 0x4000; + if pc < 0x4000 { + window = bus.cart.romLow; + offset = pc as uint; + } + if window != null { + opcode = *(window + offset); + } else { + opcode = MbcRead(@bus.cart, pc); + } + } else { + opcode = CpuRead8(cpu, bus, pc); + } + cpu.pc = pc + 1; + CpuExecute(cpu, bus, opcode); + } + } +} + /// ALU演算グループ(op=0..7: ADD,ADC,SUB,SBC,AND,XOR,OR,CP)を1つ実行する。 func CpuAluOp(cpu: *var Cpu, op: uint8, v: uint8) { - if op == 0 { AluAdd(cpu, v, 0); } - else if op == 1 { AluAdd(cpu, v, CpuFlagC(cpu) ? 1u : 0u); } - else if op == 2 { AluSub(cpu, v, 0, true); } - else if op == 3 { AluSub(cpu, v, CpuFlagC(cpu) ? 1u : 0u, true); } - else if op == 4 { AluAnd(cpu, v); } - else if op == 5 { AluXor(cpu, v); } - else if op == 6 { AluOr(cpu, v); } - else { AluSub(cpu, v, 0, false); } // CP + if op < 4 { + if op < 2 { + if op == 0 { AluAdd(cpu, v, 0); } + else { AluAdd(cpu, v, CpuFlagC(cpu) ? 1u : 0u); } + } else { + if op == 2 { AluSub(cpu, v, 0, true); } + else { AluSub(cpu, v, CpuFlagC(cpu) ? 1u : 0u, true); } + } + } else if op < 6 { + if op == 4 { AluAnd(cpu, v); } else { AluXor(cpu, v); } + } else { + if op == 6 { AluOr(cpu, v); } else { AluSub(cpu, v, 0, false); } // CP + } } /// CBプレフィックスの回転/シフトグループ(op=0..7: RLC,RRC,RL,RR,SLA,SRA,SWAP,SRL)。 @@ -482,293 +552,307 @@ func CpuExecuteCb(cpu: *var Cpu, bus: *var Bus, opcode: uint8) { } /// 非CBプレフィックスの1命令を実行する(オペコードは呼び出し側で読み取り済み)。 +/// +/// 落とし穴(性能): Ruxには整数のmatchも関数ポインタも無く、Releaseは +/// ジャンプテーブルを作らない。以前は頻出順に並べた`opcode == 0xNN`の連鎖 +/// だったが、後方の命令は100回以上比較していた(プロファイルで全体の約3割)。 +/// SM83のオペコードは上位2bitで区画、下位3bit(列)で命令の種類、中位3bit +/// (行)でレジスタ/条件が決まるため、その順に二分して数回の比較で分岐する。 pub func CpuExecute(cpu: *var Cpu, bus: *var Bus, opcode: uint8) { - if opcode == 0x00 { - // NOP - } - // --- LD r,r'(実ゲームで最頻出の命令群のため先頭で判定する。落とし穴: - // 0x76=HALTはこの範囲に含まれるが、制御系ブロックで個別に扱うため - // ここでは除外する) --- - else if opcode != 0x76 && opcode >= 0x40 && opcode <= 0x7F { - let dst = (opcode >> 3) & 7; + // --- 0x40-0xBF: LD r,r' と ALU A,r(実ゲームで最頻出) --- + if opcode >= 0x40 && opcode < 0xC0 { let src = opcode & 7; - let v = R8Get(cpu, bus, src); - R8Set(cpu, bus, dst, v); - } - // --- ALU A,r(同じく高頻度) --- - else if opcode >= 0x80 && opcode <= 0xBF { - let op = (opcode >> 3) & 7; - let src = opcode & 7; - let v = R8Get(cpu, bus, src); - CpuAluOp(cpu, op, v); - } - // --- INC r / DEC r (8bit)(ループカウンタ等で高頻度のため先頭寄りへ) --- - else if opcode == 0x04 || opcode == 0x0C || opcode == 0x14 || opcode == 0x1C || - opcode == 0x24 || opcode == 0x2C || opcode == 0x34 || opcode == 0x3C { - let idx = (opcode >> 3) & 7; - let v = R8Get(cpu, bus, idx); - R8Set(cpu, bus, idx, AluInc8(cpu, v)); - } else if opcode == 0x05 || opcode == 0x0D || opcode == 0x15 || opcode == 0x1D || - opcode == 0x25 || opcode == 0x2D || opcode == 0x35 || opcode == 0x3D { - let idx = (opcode >> 3) & 7; - let v = R8Get(cpu, bus, idx); - R8Set(cpu, bus, idx, AluDec8(cpu, v)); - } - // --- JR(条件分岐、高頻度のため先頭寄りへ) --- - else if opcode == 0x20 || opcode == 0x30 || opcode == 0x28 || opcode == 0x38 { - let idx = (opcode >> 3) & 3; - let e8 = ReadImm8(cpu, bus); - if CcTest(cpu, idx) { - if (e8 & 0x80) != 0 { - let neg = (0x100 - (e8 as uint)) as uint16; - cpu.pc -= neg; + if opcode < 0x80 { + if opcode == 0x76 { + CpuHalt(cpu, bus); } else { - cpu.pc += e8 as uint16; + let v = R8Get(cpu, bus, src); + R8Set(cpu, bus, (opcode >> 3) & 7, v); } - BusTick(bus, 4); - } - } else if opcode == 0x18 { - let e8 = ReadImm8(cpu, bus); - if (e8 & 0x80) != 0 { - let neg = (0x100 - (e8 as uint)) as uint16; - cpu.pc -= neg; } else { - cpu.pc += e8 as uint16; + let v = R8Get(cpu, bus, src); + CpuAluOp(cpu, (opcode >> 3) & 7, v); } - BusTick(bus, 4); - } - // --- LD r,d8 --- - else if opcode == 0x06 || opcode == 0x0E || opcode == 0x16 || opcode == 0x1E || - opcode == 0x26 || opcode == 0x2E || opcode == 0x3E { - let dst = (opcode >> 3) & 7; - let v = ReadImm8(cpu, bus); - R8Set(cpu, bus, dst, v); - } else if opcode == 0x36 { - let v = ReadImm8(cpu, bus); - CpuWrite8(cpu, bus, cpu.hl.word, v); - } - // --- 16bit ロード --- - else if opcode == 0x01 || opcode == 0x11 || opcode == 0x21 || opcode == 0x31 { - let idx = (opcode >> 4) & 3; - RpSet(cpu, idx, ReadImm16(cpu, bus)); - } else if opcode == 0x02 { - CpuWrite8(cpu, bus, cpu.bc.word, cpu.af.bytes.hi); - } else if opcode == 0x12 { - CpuWrite8(cpu, bus, cpu.de.word, cpu.af.bytes.hi); - } else if opcode == 0x22 { - let hl = cpu.hl.word; - CpuWrite8(cpu, bus, hl, cpu.af.bytes.hi); - cpu.hl.word = hl + 1; - } else if opcode == 0x32 { - let hl = cpu.hl.word; - CpuWrite8(cpu, bus, hl, cpu.af.bytes.hi); - cpu.hl.word = hl - 1; - } else if opcode == 0x0A { - cpu.af.bytes.hi = CpuRead8(cpu, bus, cpu.bc.word); - } else if opcode == 0x1A { - cpu.af.bytes.hi = CpuRead8(cpu, bus, cpu.de.word); - } else if opcode == 0x2A { - let hl = cpu.hl.word; - cpu.af.bytes.hi = CpuRead8(cpu, bus, hl); - cpu.hl.word = hl + 1; - } else if opcode == 0x3A { - let hl = cpu.hl.word; - cpu.af.bytes.hi = CpuRead8(cpu, bus, hl); - cpu.hl.word = hl - 1; - } else if opcode == 0x08 { - let addr = ReadImm16(cpu, bus); - CpuWrite8(cpu, bus, addr, cpu.sp as uint8); - CpuWrite8(cpu, bus, addr + 1, (cpu.sp >> 8) as uint8); - } else if opcode == 0xF9 { - BusTick(bus, 4); // internal - cpu.sp = cpu.hl.word; - } - // --- 16bit INC/DEC (フラグ無影響、内部+4サイクル) --- - else if opcode == 0x03 || opcode == 0x13 || opcode == 0x23 || opcode == 0x33 { - let idx = (opcode >> 4) & 3; - RpSet(cpu, idx, RpGet(cpu, idx) + 1); - BusTick(bus, 4); - } else if opcode == 0x0B || opcode == 0x1B || opcode == 0x2B || opcode == 0x3B { - let idx = (opcode >> 4) & 3; - RpSet(cpu, idx, RpGet(cpu, idx) - 1); - BusTick(bus, 4); - } - // --- ADD HL,rr --- - else if opcode == 0x09 || opcode == 0x19 || opcode == 0x29 || opcode == 0x39 { - let idx = (opcode >> 4) & 3; - let hl = cpu.hl.word as uint; - let v = RpGet(cpu, idx) as uint; - let sum = hl + v; - let h = ((hl & 0xFFF) + (v & 0xFFF)) > 0xFFF; - CpuSetFlags(cpu, CpuFlagZ(cpu), false, h, sum > 0xFFFF); - cpu.hl.word = sum as uint16; - BusTick(bus, 4); - } - // --- ADD SP,e8 / LD HL,SP+e8 --- - else if opcode == 0xE8 { - let result = SpAddOffset(cpu, bus); - BusTick(bus, 4); - BusTick(bus, 4); - cpu.sp = result; - } else if opcode == 0xF8 { - let result = SpAddOffset(cpu, bus); - BusTick(bus, 4); - cpu.hl.word = result; - } - // --- PUSH/POP --- - else if opcode == 0xC1 || opcode == 0xD1 || opcode == 0xE1 || opcode == 0xF1 { - let idx = (opcode >> 4) & 3; - Rp2Set(cpu, idx, Pop16(cpu, bus)); - } else if opcode == 0xC5 || opcode == 0xD5 || opcode == 0xE5 || opcode == 0xF5 { - let idx = (opcode >> 4) & 3; - BusTick(bus, 4); // internal - Push16(cpu, bus, Rp2Get(cpu, idx)); + return; } - // --- RET / RETI --- - else if opcode == 0xC0 || opcode == 0xD0 || opcode == 0xC8 || opcode == 0xD8 { - let idx = (opcode >> 3) & 3; - BusTick(bus, 4); // 条件チェック用 - if CcTest(cpu, idx) { - cpu.pc = Pop16(cpu, bus); - BusTick(bus, 4); + + let col = opcode & 7; + let row = (opcode >> 3) & 7; + + // --- 0x00-0x3F --- + if opcode < 0x40 { + if col < 4 { + if col < 2 { + if col == 0 { + if row >= 4 { + // JR cc,e8 (0x20/0x28/0x30/0x38) + let e8 = ReadImm8(cpu, bus); + if CcTest(cpu, row & 3) { + CpuJumpRelative(cpu, e8); + BusCpuTick(bus, 4); + } + } else if row == 3 { + // JR e8 (0x18) + let e8 = ReadImm8(cpu, bus); + CpuJumpRelative(cpu, e8); + BusCpuTick(bus, 4); + } else if row == 1 { + // LD (a16),SP (0x08) + let addr = ReadImm16(cpu, bus); + CpuWrite8(cpu, bus, addr, cpu.sp as uint8); + CpuWrite8(cpu, bus, addr + 1, (cpu.sp >> 8) as uint8); + } else if row == 2 { + CpuStop(cpu, bus); // 0x10 + } + // row 0: NOP (0x00) + } else { + let idx = row >> 1; + if (row & 1) == 0 { + // LD rr,d16 (0x01/0x11/0x21/0x31) + RpSet(cpu, idx, ReadImm16(cpu, bus)); + } else { + // ADD HL,rr (0x09/0x19/0x29/0x39) + let hl = cpu.hl.word as uint; + let v = RpGet(cpu, idx) as uint; + let sum = hl + v; + let h = ((hl & 0xFFF) + (v & 0xFFF)) > 0xFFF; + CpuSetFlags(cpu, CpuFlagZ(cpu), false, h, sum > 0xFFFF); + cpu.hl.word = sum as uint16; + BusCpuTick(bus, 4); + } + } + } else { + if col == 2 { + // LD (rr),A / LD A,(rr) (0x02-0x3A) + if row < 4 { + let addr = row < 2 ? cpu.bc.word : cpu.de.word; + if (row & 1) == 0 { + CpuWrite8(cpu, bus, addr, cpu.af.bytes.hi); + } else { + cpu.af.bytes.hi = CpuRead8(cpu, bus, addr); + } + } else { + let hl = cpu.hl.word; + if (row & 1) == 0 { + CpuWrite8(cpu, bus, hl, cpu.af.bytes.hi); + } else { + cpu.af.bytes.hi = CpuRead8(cpu, bus, hl); + } + // row 4/5: HL+、row 6/7: HL- + if row < 6 { cpu.hl.word = hl + 1; } else { cpu.hl.word = hl - 1; } + } + } else { + // INC rr / DEC rr (フラグ無影響、内部+4サイクル) + let idx = row >> 1; + if (row & 1) == 0 { + RpSet(cpu, idx, RpGet(cpu, idx) + 1); + } else { + RpSet(cpu, idx, RpGet(cpu, idx) - 1); + } + BusCpuTick(bus, 4); + } + } + } else { + if col < 6 { + let v = R8Get(cpu, bus, row); + if col == 4 { + R8Set(cpu, bus, row, AluInc8(cpu, v)); // INC r + } else { + R8Set(cpu, bus, row, AluDec8(cpu, v)); // DEC r + } + } else if col == 6 { + // LD r,d8 (row 6 は LD (HL),d8) + let v = ReadImm8(cpu, bus); + R8Set(cpu, bus, row, v); + } else { + CpuExecuteAccFlags(cpu, row); + } } - } else if opcode == 0xC9 { - cpu.pc = Pop16(cpu, bus); - BusTick(bus, 4); - } else if opcode == 0xD9 { - cpu.pc = Pop16(cpu, bus); - BusTick(bus, 4); - cpu.ime = true; + return; } - // --- JP --- - else if opcode == 0xC2 || opcode == 0xD2 || opcode == 0xCA || opcode == 0xDA { - let idx = (opcode >> 3) & 3; - let addr = ReadImm16(cpu, bus); - if CcTest(cpu, idx) { - cpu.pc = addr; - BusTick(bus, 4); + + // --- 0xC0-0xFF --- + if col < 4 { + if col < 2 { + if col == 0 { + if row < 4 { + // RET cc + BusCpuTick(bus, 4); // 条件チェック用 + if CcTest(cpu, row) { + cpu.pc = Pop16(cpu, bus); + BusCpuTick(bus, 4); + } + } else if row == 4 { + // LDH (a8),A (0xE0) + let addr = 0xFF00u16 + ReadImm8(cpu, bus) as uint16; + CpuWrite8(cpu, bus, addr, cpu.af.bytes.hi); + } else if row == 6 { + // LDH A,(a8) (0xF0) + let addr = 0xFF00u16 + ReadImm8(cpu, bus) as uint16; + cpu.af.bytes.hi = CpuRead8(cpu, bus, addr); + } else if row == 5 { + // ADD SP,e8 (0xE8) + let result = SpAddOffset(cpu, bus); + BusCpuTick(bus, 4); + BusCpuTick(bus, 4); + cpu.sp = result; + } else { + // LD HL,SP+e8 (0xF8) + let result = SpAddOffset(cpu, bus); + BusCpuTick(bus, 4); + cpu.hl.word = result; + } + } else { + if (row & 1) == 0 { + Rp2Set(cpu, row >> 1, Pop16(cpu, bus)); // POP + } else if row == 1 { + cpu.pc = Pop16(cpu, bus); // RET + BusCpuTick(bus, 4); + } else if row == 3 { + cpu.pc = Pop16(cpu, bus); // RETI + BusCpuTick(bus, 4); + cpu.ime = true; + } else if row == 5 { + cpu.pc = cpu.hl.word; // JP HL + } else { + BusCpuTick(bus, 4); // LD SP,HL (internal) + cpu.sp = cpu.hl.word; + } + } + } else { + if col == 2 { + if row < 4 { + // JP cc,a16 + let addr = ReadImm16(cpu, bus); + if CcTest(cpu, row) { + cpu.pc = addr; + BusCpuTick(bus, 4); + } + } else if row == 4 { + CpuWrite8(cpu, bus, 0xFF00u16 + cpu.bc.bytes.lo as uint16, cpu.af.bytes.hi); // LD (C),A + } else if row == 6 { + cpu.af.bytes.hi = CpuRead8(cpu, bus, 0xFF00u16 + cpu.bc.bytes.lo as uint16); // LD A,(C) + } else if row == 5 { + let addr = ReadImm16(cpu, bus); // LD (a16),A + CpuWrite8(cpu, bus, addr, cpu.af.bytes.hi); + } else { + let addr = ReadImm16(cpu, bus); // LD A,(a16) + cpu.af.bytes.hi = CpuRead8(cpu, bus, addr); + } + } else { + if row == 0 { + // JP a16 (0xC3) + let addr = ReadImm16(cpu, bus); + cpu.pc = addr; + BusCpuTick(bus, 4); + } else if row == 1 { + // CB Prefix + let cbOpcode = CpuRead8(cpu, bus, cpu.pc); + cpu.pc += 1; + CpuExecuteCb(cpu, bus, cbOpcode); + } else if row == 6 { + cpu.ime = false; // DI + cpu.imeDelay = 0; + } else if row == 7 { + cpu.imeDelay = 1; // EI + } else { + CpuLogIllegal(cpu, opcode); // 0xD3/0xDB/0xE3/0xEB + } + } } - } else if opcode == 0xC3 { - let addr = ReadImm16(cpu, bus); - cpu.pc = addr; - BusTick(bus, 4); - } else if opcode == 0xE9 { - cpu.pc = cpu.hl.word; - } - // --- CALL --- - else if opcode == 0xC4 || opcode == 0xD4 || opcode == 0xCC || opcode == 0xDC { - let idx = (opcode >> 3) & 3; - let addr = ReadImm16(cpu, bus); - if CcTest(cpu, idx) { - BusTick(bus, 4); // internal + } else { + if col < 6 { + if col == 4 { + if row < 4 { + // CALL cc,a16 + let addr = ReadImm16(cpu, bus); + if CcTest(cpu, row) { + BusCpuTick(bus, 4); // internal + Push16(cpu, bus, cpu.pc); + cpu.pc = addr; + } + } else { + CpuLogIllegal(cpu, opcode); // 0xE4/0xEC/0xF4/0xFC + } + } else { + if (row & 1) == 0 { + BusCpuTick(bus, 4); // PUSH (internal) + Push16(cpu, bus, Rp2Get(cpu, row >> 1)); + } else if row == 1 { + // CALL a16 (0xCD) + let addr = ReadImm16(cpu, bus); + BusCpuTick(bus, 4); // internal + Push16(cpu, bus, cpu.pc); + cpu.pc = addr; + } else { + CpuLogIllegal(cpu, opcode); // 0xDD/0xED/0xFD + } + } + } else if col == 6 { + // ALU A,d8 + let v = ReadImm8(cpu, bus); + CpuAluOp(cpu, row, v); + } else { + // RST + BusCpuTick(bus, 4); // internal Push16(cpu, bus, cpu.pc); - cpu.pc = addr; + cpu.pc = (opcode & 0x38) as uint16; } - } else if opcode == 0xCD { - let addr = ReadImm16(cpu, bus); - BusTick(bus, 4); // internal - Push16(cpu, bus, cpu.pc); - cpu.pc = addr; } - // --- RST --- - else if opcode == 0xC7 || opcode == 0xCF || opcode == 0xD7 || opcode == 0xDF || - opcode == 0xE7 || opcode == 0xEF || opcode == 0xF7 || opcode == 0xFF { - let vector = (opcode & 0x38) as uint16; - BusTick(bus, 4); // internal - Push16(cpu, bus, cpu.pc); - cpu.pc = vector; +} + +/// JR の符号付き8bitオフセットをPCへ加える。 +func CpuJumpRelative(cpu: *var Cpu, e8: uint8) { + if (e8 & 0x80) != 0 { + let neg = (0x100 - (e8 as uint)) as uint16; + cpu.pc -= neg; + } else { + cpu.pc += e8 as uint16; } - // --- LDH / (C) / (a16) --- - else if opcode == 0xE0 { - let addr = 0xFF00u16 + ReadImm8(cpu, bus) as uint16; - CpuWrite8(cpu, bus, addr, cpu.af.bytes.hi); - } else if opcode == 0xF0 { - let addr = 0xFF00u16 + ReadImm8(cpu, bus) as uint16; - cpu.af.bytes.hi = CpuRead8(cpu, bus, addr); - } else if opcode == 0xE2 { - CpuWrite8(cpu, bus, 0xFF00u16 + cpu.bc.bytes.lo as uint16, cpu.af.bytes.hi); - } else if opcode == 0xF2 { - cpu.af.bytes.hi = CpuRead8(cpu, bus, 0xFF00u16 + cpu.bc.bytes.lo as uint16); - } else if opcode == 0xEA { - let addr = ReadImm16(cpu, bus); - CpuWrite8(cpu, bus, addr, cpu.af.bytes.hi); - } else if opcode == 0xFA { - let addr = ReadImm16(cpu, bus); - cpu.af.bytes.hi = CpuRead8(cpu, bus, addr); +} + +/// HALT (0x76)。 +func CpuHalt(cpu: *var Cpu, bus: *var Bus) { + if cpu.imeDelay > 0 { + cpu.ime = true; + cpu.imeDelay = 0; } - // --- CB Prefix --- - else if opcode == 0xCB { - let cbOpcode = CpuRead8(cpu, bus, cpu.pc); - cpu.pc += 1; - CpuExecuteCb(cpu, bus, cbOpcode); + if !cpu.ime && InterruptPending(bus) != 0 { + cpu.haltBug = true; + } else { + cpu.halted = true; } - // --- 制御系 --- - else if opcode == 0x76 { - // HALT - if cpu.imeDelay > 0 { - cpu.ime = true; - cpu.imeDelay = 0; - } - if !cpu.ime && InterruptPending(bus) != 0 { - cpu.haltBug = true; - } else { - cpu.halted = true; - } - } else if opcode == 0x10 { - // STOP: 2バイト命令(パディングバイトを読み飛ばす)。 - // T6-6: CGBモードでKEY1切替準備(speedSwitchPrepared)済みならここで速度を - // 反転する。DMGモード、またはCGBでも準備されていなければ何もしない。 - cpu.pc += 1; - if bus.mode == GbMode::Cgb && bus.speedSwitchPrepared { - bus.doubleSpeed = !bus.doubleSpeed; - bus.speedSwitchPrepared = false; - TimerWriteDiv(bus); // DIVリセット(実機の仕様、Pan Docs "CGB Registers: KEY1") - } - } else if opcode == 0xF3 { - cpu.ime = false; - cpu.imeDelay = 0; - } else if opcode == 0xFB { - cpu.imeDelay = 1; +} + +/// STOP (0x10): 2バイト命令(パディングバイトを読み飛ばす)。 +/// T6-6: CGBモードでKEY1切替準備(speedSwitchPrepared)済みならここで速度を +/// 反転する。DMGモード、またはCGBでも準備されていなければ何もしない。 +func CpuStop(cpu: *var Cpu, bus: *var Bus) { + cpu.pc += 1; + if bus.mode == GbMode::Cgb && bus.speedSwitchPrepared { + BusSync(bus); // 切替前の速度で保留時間を進める + bus.doubleSpeed = !bus.doubleSpeed; + bus.speedSwitchPrepared = false; + TimerWriteDiv(bus); // DIVリセット(実機の仕様、Pan Docs "CGB Registers: KEY1") + BusSync(bus); // 新しい速度で次のイベント時刻を求め直す } - // --- アキュムレータ回転 (非CB版は常に Z=0) --- - else if opcode == 0x07 { // RLCA - cpu.af.bytes.hi = CbRotateShift(cpu, 0, cpu.af.bytes.hi); - cpu.af.bytes.lo = cpu.af.bytes.lo & ~FlagZ; - } else if opcode == 0x0F { // RRCA - cpu.af.bytes.hi = CbRotateShift(cpu, 1, cpu.af.bytes.hi); - cpu.af.bytes.lo = cpu.af.bytes.lo & ~FlagZ; - } else if opcode == 0x17 { // RLA - cpu.af.bytes.hi = CbRotateShift(cpu, 2, cpu.af.bytes.hi); - cpu.af.bytes.lo = cpu.af.bytes.lo & ~FlagZ; - } else if opcode == 0x1F { // RRA - cpu.af.bytes.hi = CbRotateShift(cpu, 3, cpu.af.bytes.hi); +} + +/// 0x07-0x3F の列7: アキュムレータ回転(非CB版は常に Z=0)・DAA・CPL・SCF・CCF。 +func CpuExecuteAccFlags(cpu: *var Cpu, row: uint8) { + if row < 4 { + // RLCA/RRCA/RLA/RRA は CB の RLC/RRC/RL/RR と同じ演算 + cpu.af.bytes.hi = CbRotateShift(cpu, row, cpu.af.bytes.hi); cpu.af.bytes.lo = cpu.af.bytes.lo & ~FlagZ; - } - // --- DAA・フラグ操作系 --- - else if opcode == 0x27 { + } else if row == 4 { CpuDaa(cpu); - } else if opcode == 0x2F { // CPL + } else if row == 5 { // CPL cpu.af.bytes.hi = ~cpu.af.bytes.hi; cpu.af.bytes.lo = (cpu.af.bytes.lo & (FlagZ | FlagC)) | FlagN | FlagH; - } else if opcode == 0x37 { // SCF + } else if row == 6 { // SCF cpu.af.bytes.lo = (cpu.af.bytes.lo & FlagZ) | FlagC; - } else if opcode == 0x3F { // CCF + } else { // CCF let newC = CpuFlagC(cpu) ? 0u8 : FlagC; cpu.af.bytes.lo = (cpu.af.bytes.lo & FlagZ) | newC; } - // --- 未定義オペコード --- - else if opcode == 0xD3 || opcode == 0xDB || opcode == 0xDD || opcode == 0xE3 || - opcode == 0xE4 || opcode == 0xEB || opcode == 0xEC || opcode == 0xED || - opcode == 0xF4 || opcode == 0xFC || opcode == 0xFD { - CpuLogIllegal(cpu, opcode); - } - // --- ALU A,d8 --- - else if opcode == 0xC6 || opcode == 0xCE || opcode == 0xD6 || opcode == 0xDE || - opcode == 0xE6 || opcode == 0xEE || opcode == 0xF6 || opcode == 0xFE { - let op = (opcode >> 3) & 7; - let v = ReadImm8(cpu, bus); - CpuAluOp(cpu, op, v); - } else { - CpuLogIllegal(cpu, opcode); - } } diff --git a/Packages/Core/Src/Mbc.rux b/Packages/Core/Src/Mbc.rux index b92a5ff..8601f7a 100644 --- a/Packages/Core/Src/Mbc.rux +++ b/Packages/Core/Src/Mbc.rux @@ -30,6 +30,11 @@ pub struct Cartridge { /// 実書き込みでのみ立つ(バッテリーセーブの保存タイミング判定用)。 pub ramDirty: bool; pub mbc: Mbc; + /// 現在CPUから見える0000-3FFF/4000-7FFFのROM先頭。CPUの読み出しが + /// MbcReadを通らずに済むよう、バンク切替時にMbcUpdateRomWindowsで更新する。 + /// ROM長が足りない場合はnullで、MbcReadへ戻る。 + pub romLow: *uint8; + pub romHigh: *uint8; } /// MBC状態。フィールドは種別ごとに使い分ける(コメント参照)。 @@ -110,6 +115,7 @@ pub func CartridgeReset(cart: *var Cartridge) { cart.mbc.romBankLow8 = 1; cart.mbc.romBankHigh1 = 0; cart.mbc.ramBank = 0; + MbcUpdateRomWindows(cart); } /// ヘッダを解析し、MBC種別に応じた初期状態を作る。romの所有権は呼び出し側に @@ -128,15 +134,21 @@ pub func CartridgeInit(cart: *var Cartridge, rom: Slice) -> CartridgePars cart.rom = rom; cart.ramLength = info.ramSize; cart.mbc.kind = info.mbcKind; + MbcUpdateRomWindows(cart); return CartridgeParseError::None; } // --- 共通ヘルパー(バンク境界の正規化) --- +// romBanks はヘッダの0x0148(ROMサイズコード)から `2 << code` で求めるため +// 常に2の冪(RomSizeFromCode参照)。ROMの全バイトアクセス(オペコード +// フェッチ含む、CPU全命令で複数回発生する最も熱いパス)のたびに実行される +// ため、剰余演算をビットマスクに置き換える(HareGirl 17856de と同じ対策、 +// docs/PerformanceNotes.md 7章参照)。 func NormalizedRomBank(cart: *Cartridge, bank: uint) -> uint { if cart.info.romBanks == 0 { return 0; } - return bank % cart.info.romBanks; + return bank & (cart.info.romBanks - 1); } func ReadRomBank(cart: *Cartridge, bank: uint, offset: uint16) -> uint8 { @@ -150,10 +162,13 @@ func MbcRamBankCount(cart: *Cartridge) -> uint { return cart.ramLength / RamBankSize; } +// count(= ramLength/8KiB)はヘッダの0x0149(RAMサイズコード)から決まる値 +// {0,1,4,8,16}(RamSizeFromCode参照)で、0を除き常に2の冪。NormalizedRomBank +// と同じ理由でビットマスクに置き換える。 func NormalizedRamBank(cart: *Cartridge, bank: uint) -> uint { let count = MbcRamBankCount(cart); if count == 0 { return 0; } - return bank % count; + return bank & (count - 1); } func ReadRamBank(cart: *Cartridge, bank: uint, offset: uint16) -> uint8 { @@ -468,8 +483,44 @@ func Mbc5Write(cart: *var Cartridge, addr: uint16, value: uint8) { // --- ディスパッチ --- +/// ROMアドレス(0000-7FFF)を現在のバンクに従ってROM内の物理位置へ変換する。 +func MbcRomPhysical(cart: *Cartridge, addr: uint16) -> uint { + // 命令フェッチを含むROM読み出しの共通経路。MBC種別ごとのRead関数と + // ReadRomBankを重ねて呼ばず、現在のバンクから物理位置を直接求める。 + let kind = cart.mbc.kind; + var bank: uint = 0; + if addr <= 0x3FFF { + if kind == MbcKind::Mbc1 && cart.mbc.ramMode { + bank = (cart.mbc.bankHigh2 as uint) << 5; + } + } else if kind == MbcKind::RomOnly { + bank = 1; + } else if kind == MbcKind::Mbc1 { + bank = ((cart.mbc.bankHigh2 as uint) << 5) | (cart.mbc.romBankLow5 as uint); + if (bank & 0x1F) == 0 { bank = bank | 1; } + } else if kind == MbcKind::Mbc2 || kind == MbcKind::Mbc3 { + bank = cart.mbc.romBank as uint; + } else { + bank = ((cart.mbc.romBankHigh1 as uint) << 8) | (cart.mbc.romBankLow8 as uint); + } + var physical = addr as uint; + if addr >= 0x4000 || bank != 0 { + var normalizedBank: uint = 0; + if cart.info.romBanks > 0 { + normalizedBank = bank & (cart.info.romBanks - 1); + } + physical = normalizedBank * RomBankSize + ((addr as uint) & 0x3FFF); + } + return physical; +} + /// ROM(0000-7FFF)・外部RAM(A000-BFFF)への読み出しをMBC種別に応じてディスパッチする。 pub func MbcRead(cart: *Cartridge, addr: uint16) -> uint8 { + if addr <= 0x7FFF { + let physical = MbcRomPhysical(cart, addr); + if physical >= cart.rom.length { return 0xFF; } + return cart.rom.data[physical]; + } if cart.mbc.kind == MbcKind::RomOnly { return MbcNoneRead(cart, addr); } else if cart.mbc.kind == MbcKind::Mbc1 { return Mbc1Read(cart, addr); } else if cart.mbc.kind == MbcKind::Mbc2 { return Mbc2Read(cart, addr); } @@ -484,4 +535,18 @@ pub func MbcWrite(cart: *var Cartridge, addr: uint16, value: uint8) { else if cart.mbc.kind == MbcKind::Mbc3 { Mbc3Write(cart, addr, value); } else if cart.mbc.kind == MbcKind::Mbc5 { Mbc5Write(cart, addr, value); } // ROM only: バンク切替レジスタも外部RAMも無いので書き込みは無視 + if addr <= 0x7FFF { MbcUpdateRomWindows(cart); } +} + +/// romLow/romHighを現在のバンクレジスタから求め直す。保存状態の復元後にも呼ぶ。 +pub func MbcUpdateRomWindows(cart: *var Cartridge) { + cart.romLow = MbcRomWindow(cart, 0x0000); + cart.romHigh = MbcRomWindow(cart, 0x4000); +} + +/// MbcReadのROM経路と同じ計算で、addrを含む16KiB窓の先頭を返す。 +func MbcRomWindow(cart: *Cartridge, addr: uint16) -> *uint8 { + let physical = MbcRomPhysical(cart, addr); + if physical + RomBankSize > cart.rom.length { return null; } + return cart.rom.data + physical; } diff --git a/Packages/Core/Src/Ppu.rux b/Packages/Core/Src/Ppu.rux index 5d93851..1ef6feb 100644 --- a/Packages/Core/Src/Ppu.rux +++ b/Packages/Core/Src/Ppu.rux @@ -125,10 +125,11 @@ pub struct Ppu { pub dot: int; pub windowLine: int; pub statIrqLine: bool; + /// アプリが音声不足時に切り替える描画フラグ。PPUの時刻と割り込みは進める。 + pub renderEnabled: bool; pub framebuffer: uint32[23040]; // 160x144, ARGB, 行優先 pub bgColorIndex: uint8[160]; // 直近描画したラインのカラー番号(パレット適用前) - pub bgCgbPalette: uint8[160]; // CGB BG属性bit2-0(パレット番号)。DMGでは常に0 pub bgCgbPriority: bool[160]; // CGB BG属性bit7(BG-to-OBJ優先)。DMGでは常にfalse } @@ -155,6 +156,7 @@ pub func PpuPowerOn(ppu: *var Ppu) { ppu.mode = ModeOamScan; ppu.windowLine = 0; ppu.statIrqLine = false; + ppu.renderEnabled = true; PpuUpdateLycEqual(ppu); } @@ -394,23 +396,6 @@ func Rgb555ToArgb(raw: uint16) -> uint32 { return 0xFF000000 | (rr << 16) | (gg << 8) | bb; } -/// パレットRAM(BG/OBJいずれか)からpalette番号(0-7)・colorNumber(0-3)の色を -/// 引きARGBへ変換する。1色=2バイト、パレット1本=8バイト(4色×2バイト)。 -func CgbPaletteColor(bus: *Bus, useObjPalette: bool, palette: uint8, colorNumber: uint8) -> uint32 { - let index = ((palette & 0x07) as uint) * 8 + ((colorNumber & 0x03) as uint) * 2; - var low: uint8 = 0; - var high: uint8 = 0; - if useObjPalette { - low = bus.objPaletteRam[index]; - high = bus.objPaletteRam[index + 1]; - } else { - low = bus.bgPaletteRam[index]; - high = bus.bgPaletteRam[index + 1]; - } - let raw = (low as uint16) | ((high as uint16) << 8); - return Rgb555ToArgb(raw); -} - /// 1ライン分をframebufferに描く(BG→ウィンドウ→スプライトの順)。 /// LCDC bit0=0のときBG・ウィンドウとも白一色になる(DMGではbit0がBG&ウィンドウ /// 全体の有効/無効を兼ねる)。スプライトはbit0とは独立にbit1で制御される。 @@ -428,122 +413,318 @@ func PpuRenderScanline(bus: *var Bus) { var x: uint = 0; while x < 160 { bus.ppu.framebuffer[lineStart + x] = DmgShade0; - bus.ppu.bgColorIndex[x] = 0; - bus.ppu.bgCgbPalette[x] = 0; - bus.ppu.bgCgbPriority[x] = false; + if (bus.ppu.lcdc & LcdcBitObjEnable) != 0 { + bus.ppu.bgColorIndex[x] = 0; + bus.ppu.bgCgbPriority[x] = false; + } x += 1; } PpuRenderSprites(bus, lineStart); return; } - var bgMapBase: uint16 = 0x9800; - if (bus.ppu.lcdc & LcdcBitBgMap) != 0 { - bgMapBase = 0x9C00; + let winVisibleThisLine = (bus.ppu.lcdc & LcdcBitWinEnable) != 0 && ly >= (bus.ppu.wy as int) && + (bus.ppu.wx as int) - 7 < 160; + // 落とし穴(性能): 3つの経路を1関数に置くと一時変数のスタック領域が4KBを + // 超え、Rux Releaseの生成コードでは超えた分の読み書きが毎回3命令になる + // (アドレス計算が増える)。経路ごとに関数を分けてフレームを小さく保つ。 + // スプライトとの優先度判定用バッファ(bgColorIndex等)は、このラインに + // スプライトがあるときだけ書く(1ピクセルにつき2回の書き込みを省く)。 + let spriteBuffers = PpuLineHasSprites(bus); + if winVisibleThisLine { + PpuRenderLineWindow(bus, lineStart, spriteBuffers); + bus.ppu.windowLine += 1; + } else if bus.mode == GbMode::Cgb { + PpuRenderLineCgb(bus, lineStart, spriteBuffers); + } else { + PpuRenderLineDmg(bus, lineStart, spriteBuffers); } + if spriteBuffers { PpuRenderSprites(bus, lineStart); } +} - var winMapBase: uint16 = 0x9800; - if (bus.ppu.lcdc & LcdcBitWinMap) != 0 { - winMapBase = 0x9C00; +/// スプライトが有効で、現在のLYに掛かるOAMエントリが1つでもあればtrue。 +func PpuLineHasSprites(bus: *Bus) -> bool { + if (bus.ppu.lcdc & LcdcBitObjEnable) == 0 { return false; } + var height: int = 8; + if (bus.ppu.lcdc & LcdcBitObjSize) != 0 { height = 16; } + // OAMのYは+16されている: ly - (y - 16) が [0, height) なら掛かる + let lyPlus16 = (bus.ppu.ly as int) + 16; + var base: uint = 0; + while base < OamSize { + let d = lyPlus16 - (bus.oam[base] as int); + if d >= 0 && d < height { return true; } + base += 4; } + return false; +} - let winEnabled = (bus.ppu.lcdc & LcdcBitWinEnable) != 0; - let wxMinus7 = (bus.ppu.wx as int) - 7; - let winVisibleThisLine = winEnabled && ly >= (bus.ppu.wy as int) && wxMinus7 < 160; - - // 落とし穴(性能): TileMapPixelを毎ピクセル呼ぶと、同じタイル内の8ピクセル - // すべてでタイルマップ/属性/タイルデータのVRAM読み出しを重複して行う - // ことになる(Rux Releaseが関数インライン化を行わない問題も重なり特に高コスト。 - // Bus.rux の TimerTick と同じ対策方針)。タイル列(tileCol)とソース - // (BG/ウィンドウ)が変わったときだけタイルデータを取得し直す1ピクセル - // フェッチャー相当のキャッシュに書き換えた。結果はTileMapPixelを毎回 - // 呼んだ場合と同一(dmg-acid2/cgb-acid2でピクセル完全一致を確認)。 - var x: uint = 0; - var haveTile = false; - var curTileCol: int = -1; - var curMapBase: uint16 = 0; - var curIsWindow = false; - var lowByte: uint8 = 0; - var highByte: uint8 = 0; - var tileXFlip = false; - var tilePalette: uint8 = 0; - var tilePriority = false; - - while x < 160 { - let useWindow = winVisibleThisLine && (x as int) >= wxMinus7; - var sourceX: int; - var sourceY: int; - var mapBase: uint16; - if useWindow { - sourceX = (x as int) - wxMinus7; - sourceY = bus.ppu.windowLine; - mapBase = winMapBase; - } else { - sourceX = ((x as int) + (bus.ppu.scx as int)) & 0xFF; - sourceY = (ly + (bus.ppu.scy as int)) & 0xFF; - mapBase = bgMapBase; - } - +/// DMG・ウィンドウなしのラインのBGを描く。タイル行ごとに取得し、汎用の +/// ピクセルループで繰り返すウィンドウ/CGB分岐とタイル列判定を省く。 +func PpuRenderLineDmg(bus: *var Bus, lineStart: uint, spritesEnabled: bool) { + let ly = bus.ppu.ly as int; + let lcdc = bus.ppu.lcdc; + let scrollX = bus.ppu.scx as int; + let bgY = (ly + (bus.ppu.scy as int)) & 0xFF; + var bgMapBase: uint16 = 0x9800; + if (lcdc & LcdcBitBgMap) != 0 { bgMapBase = 0x9C00; } + let bgPalette = bus.ppu.bgp; + var shades: uint32[4]; + shades[0] = DmgShade(bgPalette & 0x03); + shades[1] = DmgShade((bgPalette >> 2) & 0x03); + shades[2] = DmgShade((bgPalette >> 4) & 0x03); + shades[3] = DmgShade((bgPalette >> 6) & 0x03); + let tileRowBase = ((bgY / 8) * 32) as uint16; + let rowInTile = bgY % 8; + var tileX: uint = 0; + while tileX < 160 { + let sourceX = ((tileX as int) + scrollX) & 0xFF; let tileCol = sourceX / 8; - - if !haveTile || tileCol != curTileCol || mapBase != curMapBase || useWindow != curIsWindow { - let tileRow = sourceY / 8; - let tileMapAddr = mapBase + ((tileRow * 32 + tileCol) as uint16); - let tileIndex = bus.vram[(tileMapAddr - 0x8000) as uint]; - - var attr: uint8 = 0; - if bus.mode == GbMode::Cgb { - attr = bus.vram[VramBankSize + (tileMapAddr - 0x8000) as uint]; + let tileMapAddr = bgMapBase + tileRowBase + (tileCol as uint16); + let tileIndex = bus.vram[(tileMapAddr - 0x8000) as uint]; + let tileAddr = BgTileDataAddr(lcdc, tileIndex, rowInTile); + let tileBase = (tileAddr - 0x8000) as uint; + let low = bus.vram[tileBase]; + let high = bus.vram[tileBase + 1]; + var count = 8 - (sourceX % 8); + if count > (160 - tileX) as int { count = (160 - tileX) as int; } + var pixel: int = 0; + var shift = 7 - (sourceX % 8); + while pixel < count { + let colorNumber = ((low >> (shift as uint)) & 0x01) | (((high >> (shift as uint)) & 0x01) << 1); + let dest = tileX + (pixel as uint); + if spritesEnabled { + bus.ppu.bgColorIndex[dest] = colorNumber; } + bus.ppu.framebuffer[lineStart + dest] = shades[colorNumber as uint]; + pixel += 1; + shift -= 1; + } + tileX += count as uint; + } +} - var rowInTile = sourceY % 8; - if (attr & CgbAttrYFlip) != 0 { - rowInTile = 7 - rowInTile; +/// CGB・ウィンドウなしのラインのBGを描く。タイル単位で属性・4色を取得し、 +/// パレットの参照は同じタイルの各ピクセルで繰り返さない。 +func PpuRenderLineCgb(bus: *var Bus, lineStart: uint, spritesEnabled: bool) { + let ly = bus.ppu.ly as int; + let lcdc = bus.ppu.lcdc; + let scrollX = bus.ppu.scx as int; + let bgY = (ly + (bus.ppu.scy as int)) & 0xFF; + var bgMapBase: uint16 = 0x9800; + if (lcdc & LcdcBitBgMap) != 0 { bgMapBase = 0x9C00; } + let tileRowBase = ((bgY / 8) * 32) as uint16; + let rowInTile = bgY % 8; + var tileX: uint = 0; + while tileX < 160 { + let sourceX = ((tileX as int) + scrollX) & 0xFF; + let tileCol = sourceX / 8; + let mapOffset = (bgMapBase + tileRowBase + (tileCol as uint16) - 0x8000) as uint; + let tileIndex = bus.vram[mapOffset]; + let attr = bus.vram[VramBankSize + mapOffset]; + var tileY = rowInTile; + if (attr & CgbAttrYFlip) != 0 { tileY = 7 - tileY; } + var tileBank: uint = 0; + if (attr & CgbAttrBank) != 0 { tileBank = 1; } + let tileAddr = BgTileDataAddr(lcdc, tileIndex, tileY); + let tileBase = tileBank * VramBankSize + (tileAddr - 0x8000) as uint; + let low = bus.vram[tileBase]; + let high = bus.vram[tileBase + 1]; + let tilePalette = attr & CgbAttrPaletteMask; + let tilePriority = (attr & CgbAttrBgPriority) != 0; + let colorBase = (tilePalette as uint) * 4; + var count = 8 - (sourceX % 8); + if count > (160 - tileX) as int { count = (160 - tileX) as int; } + let xFlip = (attr & CgbAttrXFlip) != 0; + if count == 8 { + // 落とし穴(性能): 8ピクセル揃ったタイル(大半)は定数シフトで展開する。 + // Rux Releaseは一時値をすべてメモリに置くため、ピクセルごとの + // カウンタ・シフト量更新・比較を省くだけでも大きく効く。 + let lo = low as uint; + let hi2 = (high as uint) << 1; + let fb = lineStart + tileX; + if xFlip { + let c0 = ((lo >> 0) & 1) | ((hi2 >> 0) & 2); + let c1 = ((lo >> 1) & 1) | ((hi2 >> 1) & 2); + let c2 = ((lo >> 2) & 1) | ((hi2 >> 2) & 2); + let c3 = ((lo >> 3) & 1) | ((hi2 >> 3) & 2); + let c4 = ((lo >> 4) & 1) | ((hi2 >> 4) & 2); + let c5 = ((lo >> 5) & 1) | ((hi2 >> 5) & 2); + let c6 = ((lo >> 6) & 1) | ((hi2 >> 6) & 2); + let c7 = ((lo >> 7) & 1) | ((hi2 >> 7) & 2); + bus.ppu.framebuffer[fb] = bus.bgPaletteArgb[colorBase + c0]; + bus.ppu.framebuffer[fb + 1] = bus.bgPaletteArgb[colorBase + c1]; + bus.ppu.framebuffer[fb + 2] = bus.bgPaletteArgb[colorBase + c2]; + bus.ppu.framebuffer[fb + 3] = bus.bgPaletteArgb[colorBase + c3]; + bus.ppu.framebuffer[fb + 4] = bus.bgPaletteArgb[colorBase + c4]; + bus.ppu.framebuffer[fb + 5] = bus.bgPaletteArgb[colorBase + c5]; + bus.ppu.framebuffer[fb + 6] = bus.bgPaletteArgb[colorBase + c6]; + bus.ppu.framebuffer[fb + 7] = bus.bgPaletteArgb[colorBase + c7]; + if spritesEnabled { + bus.ppu.bgColorIndex[tileX] = c0 as uint8; + bus.ppu.bgCgbPriority[tileX] = tilePriority; + bus.ppu.bgColorIndex[tileX + 1] = c1 as uint8; + bus.ppu.bgCgbPriority[tileX + 1] = tilePriority; + bus.ppu.bgColorIndex[tileX + 2] = c2 as uint8; + bus.ppu.bgCgbPriority[tileX + 2] = tilePriority; + bus.ppu.bgColorIndex[tileX + 3] = c3 as uint8; + bus.ppu.bgCgbPriority[tileX + 3] = tilePriority; + bus.ppu.bgColorIndex[tileX + 4] = c4 as uint8; + bus.ppu.bgCgbPriority[tileX + 4] = tilePriority; + bus.ppu.bgColorIndex[tileX + 5] = c5 as uint8; + bus.ppu.bgCgbPriority[tileX + 5] = tilePriority; + bus.ppu.bgColorIndex[tileX + 6] = c6 as uint8; + bus.ppu.bgCgbPriority[tileX + 6] = tilePriority; + bus.ppu.bgColorIndex[tileX + 7] = c7 as uint8; + bus.ppu.bgCgbPriority[tileX + 7] = tilePriority; + } + } else { + let c0 = ((lo >> 7) & 1) | ((hi2 >> 7) & 2); + let c1 = ((lo >> 6) & 1) | ((hi2 >> 6) & 2); + let c2 = ((lo >> 5) & 1) | ((hi2 >> 5) & 2); + let c3 = ((lo >> 4) & 1) | ((hi2 >> 4) & 2); + let c4 = ((lo >> 3) & 1) | ((hi2 >> 3) & 2); + let c5 = ((lo >> 2) & 1) | ((hi2 >> 2) & 2); + let c6 = ((lo >> 1) & 1) | ((hi2 >> 1) & 2); + let c7 = ((lo >> 0) & 1) | ((hi2 >> 0) & 2); + bus.ppu.framebuffer[fb] = bus.bgPaletteArgb[colorBase + c0]; + bus.ppu.framebuffer[fb + 1] = bus.bgPaletteArgb[colorBase + c1]; + bus.ppu.framebuffer[fb + 2] = bus.bgPaletteArgb[colorBase + c2]; + bus.ppu.framebuffer[fb + 3] = bus.bgPaletteArgb[colorBase + c3]; + bus.ppu.framebuffer[fb + 4] = bus.bgPaletteArgb[colorBase + c4]; + bus.ppu.framebuffer[fb + 5] = bus.bgPaletteArgb[colorBase + c5]; + bus.ppu.framebuffer[fb + 6] = bus.bgPaletteArgb[colorBase + c6]; + bus.ppu.framebuffer[fb + 7] = bus.bgPaletteArgb[colorBase + c7]; + if spritesEnabled { + bus.ppu.bgColorIndex[tileX] = c0 as uint8; + bus.ppu.bgCgbPriority[tileX] = tilePriority; + bus.ppu.bgColorIndex[tileX + 1] = c1 as uint8; + bus.ppu.bgCgbPriority[tileX + 1] = tilePriority; + bus.ppu.bgColorIndex[tileX + 2] = c2 as uint8; + bus.ppu.bgCgbPriority[tileX + 2] = tilePriority; + bus.ppu.bgColorIndex[tileX + 3] = c3 as uint8; + bus.ppu.bgCgbPriority[tileX + 3] = tilePriority; + bus.ppu.bgColorIndex[tileX + 4] = c4 as uint8; + bus.ppu.bgCgbPriority[tileX + 4] = tilePriority; + bus.ppu.bgColorIndex[tileX + 5] = c5 as uint8; + bus.ppu.bgCgbPriority[tileX + 5] = tilePriority; + bus.ppu.bgColorIndex[tileX + 6] = c6 as uint8; + bus.ppu.bgCgbPriority[tileX + 6] = tilePriority; + bus.ppu.bgColorIndex[tileX + 7] = c7 as uint8; + bus.ppu.bgCgbPriority[tileX + 7] = tilePriority; + } } - - var tileBank: uint = 0; - if (attr & CgbAttrBank) != 0 { - tileBank = 1; + tileX += 8; + continue; + } + var shift = 7 - (sourceX % 8); + var shiftStep = -1; + if xFlip { + shift = sourceX % 8; + shiftStep = 1; + } + var pixel: int = 0; + while pixel < count { + let colorNumber = ((low >> (shift as uint)) & 0x01) | (((high >> (shift as uint)) & 0x01) << 1); + let dest = tileX + (pixel as uint); + if spritesEnabled { + bus.ppu.bgColorIndex[dest] = colorNumber; + bus.ppu.bgCgbPriority[dest] = tilePriority; } - - let tileAddr = BgTileDataAddr(bus.ppu.lcdc, tileIndex, rowInTile); - let base = tileBank * VramBankSize + (tileAddr - 0x8000) as uint; - lowByte = bus.vram[base]; - highByte = bus.vram[base + 1]; - tileXFlip = (attr & CgbAttrXFlip) != 0; - tilePalette = attr & CgbAttrPaletteMask; - tilePriority = (attr & CgbAttrBgPriority) != 0; - - curTileCol = tileCol; - curMapBase = mapBase; - curIsWindow = useWindow; - haveTile = true; + // 色番号はほぼランダムなので分岐で選ぶと予測ミスが多い。表を引く。 + bus.ppu.framebuffer[lineStart + dest] = bus.bgPaletteArgb[colorBase + (colorNumber as uint)]; + pixel += 1; + shift += shiftStep; } + tileX += count as uint; + } +} - var colInTile = sourceX % 8; - if tileXFlip { - colInTile = 7 - colInTile; +/// ウィンドウが出るラインのBG/ウィンドウを描く(DMG/CGB共通)。BGからウィンドウ +/// への境界がタイル途中なら、そこで現在のタイルを切って次のソースへ移る。 +func PpuRenderLineWindow(bus: *var Bus, lineStart: uint, spritesEnabled: bool) { + let ly = bus.ppu.ly as int; + let lcdc = bus.ppu.lcdc; + let scrollX = bus.ppu.scx as int; + let bgY = (ly + (bus.ppu.scy as int)) & 0xFF; + var bgMapBase: uint16 = 0x9800; + if (lcdc & LcdcBitBgMap) != 0 { bgMapBase = 0x9C00; } + let bgPalette = bus.ppu.bgp; + let isCgb = bus.mode == GbMode::Cgb; + let wxMinus7 = (bus.ppu.wx as int) - 7; + let windowY = bus.ppu.windowLine; + var winMapBase: uint16 = 0x9800; + if (lcdc & LcdcBitWinMap) != 0 { winMapBase = 0x9C00; } + let dmg0 = DmgShade(bgPalette & 0x03); + let dmg1 = DmgShade((bgPalette >> 2) & 0x03); + let dmg2 = DmgShade((bgPalette >> 4) & 0x03); + let dmg3 = DmgShade((bgPalette >> 6) & 0x03); + var tileX: uint = 0; + while tileX < 160 { + let useWindow = (tileX as int) >= wxMinus7; + var sourceX: int = 0; + var sourceY = bgY; + var mapBase = bgMapBase; + if useWindow { + sourceX = (tileX as int) - wxMinus7; + sourceY = windowY; + mapBase = winMapBase; + } else { + sourceX = ((tileX as int) + scrollX) & 0xFF; } - let shift = (7 - colInTile) as uint; - let colorNumber = ((lowByte >> shift) & 0x01) | (((highByte >> shift) & 0x01) << 1); - - bus.ppu.bgColorIndex[x] = colorNumber; - bus.ppu.bgCgbPalette[x] = tilePalette; - bus.ppu.bgCgbPriority[x] = tilePriority; - if bus.mode == GbMode::Cgb { - bus.ppu.framebuffer[lineStart + x] = CgbPaletteColor(bus, false, tilePalette, colorNumber); + let tileCol = sourceX / 8; + let tileMapAddr = mapBase + (((sourceY / 8) * 32 + tileCol) as uint16); + let mapOffset = (tileMapAddr - 0x8000) as uint; + let tileIndex = bus.vram[mapOffset]; + var attr: uint8 = 0; + if isCgb { attr = bus.vram[VramBankSize + mapOffset]; } + var tileY = sourceY % 8; + if (attr & CgbAttrYFlip) != 0 { tileY = 7 - tileY; } + var tileBank: uint = 0; + if (attr & CgbAttrBank) != 0 { tileBank = 1; } + let tileAddr = BgTileDataAddr(lcdc, tileIndex, tileY); + let tileBase = tileBank * VramBankSize + (tileAddr - 0x8000) as uint; + let low = bus.vram[tileBase]; + let high = bus.vram[tileBase + 1]; + let tilePalette = attr & CgbAttrPaletteMask; + let tilePriority = (attr & CgbAttrBgPriority) != 0; + var colors: uint32[4]; + if isCgb { + let colorBase = (tilePalette as uint) * 4; + colors[0] = bus.bgPaletteArgb[colorBase]; + colors[1] = bus.bgPaletteArgb[colorBase + 1]; + colors[2] = bus.bgPaletteArgb[colorBase + 2]; + colors[3] = bus.bgPaletteArgb[colorBase + 3]; } else { - let shade = (bus.ppu.bgp >> (colorNumber * 2)) & 0x03; - bus.ppu.framebuffer[lineStart + x] = DmgShade(shade); + colors[0] = dmg0; + colors[1] = dmg1; + colors[2] = dmg2; + colors[3] = dmg3; } - x += 1; - } - - if winVisibleThisLine { - bus.ppu.windowLine += 1; + var count = 8 - (sourceX % 8); + if !useWindow && wxMinus7 > (tileX as int) && count > wxMinus7 - (tileX as int) { + count = wxMinus7 - (tileX as int); + } + if count > (160 - tileX) as int { count = (160 - tileX) as int; } + var shift = 7 - (sourceX % 8); + var shiftStep = -1; + if (attr & CgbAttrXFlip) != 0 { + shift = sourceX % 8; + shiftStep = 1; + } + var pixel: int = 0; + while pixel < count { + let colorNumber = ((low >> (shift as uint)) & 0x01) | (((high >> (shift as uint)) & 0x01) << 1); + let dest = tileX + (pixel as uint); + if spritesEnabled { + bus.ppu.bgColorIndex[dest] = colorNumber; + bus.ppu.bgCgbPriority[dest] = tilePriority; + } + bus.ppu.framebuffer[lineStart + dest] = colors[colorNumber as uint]; + pixel += 1; + shift += shiftStep; + } + tileX += count as uint; } - - PpuRenderSprites(bus, lineStart); } /// CGBのBG-to-OBJ優先度表(Pan Docs "BG-to-OBJ Priority in CGB Mode")。 @@ -698,7 +879,7 @@ func PpuRenderSprites(bus: *var Bus, lineStart: uint) { if draw { if bus.mode == GbMode::Cgb { let cgbPalette = attr & CgbAttrPaletteMask; - bus.ppu.framebuffer[lineStart + (x as uint)] = CgbPaletteColor(bus, true, cgbPalette, colorNumber); + bus.ppu.framebuffer[lineStart + (x as uint)] = bus.objPaletteArgb[(cgbPalette as uint) * 4 + (colorNumber as uint)]; } else { var palette = bus.ppu.obp0; if (attr & OamAttrPalette) != 0 { @@ -716,10 +897,11 @@ func PpuRenderSprites(bus: *var Bus, lineStart: uint) { } } -/// tCycles ぶん PPU の状態を進める。LY/モード遷移のエッジをまたぐ変化を -/// 見落とさないため1 T-cycleずつ進める。LCDC bit7=0の間は完全に停止する。 +/// tCycles ぶん PPU の状態を進める。LY/モード遷移のエッジは境界の dot で +/// 1つずつ処理し、境界の間はdotだけ一括で進める。LCDC bit7=0の間は完全に停止する。 /// -/// 落とし穴(性能): CPU全メモリアクセスごとに呼ばれる最も熱いパスの一つ。 +/// 落とし穴(性能): 以前はCPU全メモリアクセスごとに呼ばれていた(いまはBusSync +/// 経由で、境界をまたぐ区間はまとめて渡される)。 /// PpuUpdateStatIrq が見る statIrqLine は lycEqual(LY==LYC の一致、dot が /// ラインを跨いだときだけ再計算される)と mode(モード遷移時だけ変わる)にのみ /// 依存するため、そのどちらも変化しなかった T-cycle では呼んでも結果は @@ -731,6 +913,20 @@ pub func PpuTick(bus: *var Bus, tCycles: int) { return; } + // 通常の4 T-cycle更新ではモード境界をまたがない。現在のモードから + // 次の境界を求め、届かない場合はdotだけ進める。 + let endDot = bus.ppu.dot + tCycles; + var nextEvent = CyclesPerLine; + if bus.ppu.mode == ModeOamScan { + nextEvent = Mode2Dots; + } else if bus.ppu.mode == ModeDraw { + nextEvent = Mode2Dots + Mode3Dots; + } + if endDot < nextEvent { + bus.ppu.dot = endDot; + return; + } + // 最適化前(参考): dot/ly/mode を毎回 bus.ppu.* に直接読み書きしていた。 // Rux Release は mem2reg 相当の最適化(スタック/構造体メモリ上の変数を // レジスタへ昇格する処理)を行わないため、ループ内で同じフィールドへ @@ -795,6 +991,21 @@ pub func PpuTick(bus: *var Bus, tCycles: int) { var cycle: int = 0; while cycle < tCycles { + // 次のモード境界の1 dot手前までは状態が変わらないので一度に進める + // (遅延同期でまとめて渡される長い区間を1 dotずつ回さないため)。 + var segmentEnd = CyclesPerLine; + if mode == ModeOamScan { segmentEnd = Mode2Dots; } + else if mode == ModeDraw { segmentEnd = Mode2Dots + Mode3Dots; } + let skip = segmentEnd - 1 - dot; + if skip > 0 { + if tCycles - cycle <= skip { + dot += tCycles - cycle; + break; + } + dot += skip; + cycle += skip; + } + let prevMode = mode; var lineAdvanced = false; dot += 1; @@ -828,9 +1039,16 @@ pub func PpuTick(bus: *var Bus, tCycles: int) { bus.ppu.ly = ly; bus.ppu.mode = mode; bus.ppu.windowLine = windowLine; - PpuRenderScanline(bus); + if bus.ppu.renderEnabled { + PpuRenderScanline(bus); + } else if (bus.mode == GbMode::Cgb || (bus.ppu.lcdc & LcdcBitBgEnable) != 0) && + (bus.ppu.lcdc & LcdcBitWinEnable) != 0 && + (ly as int) >= (bus.ppu.wy as int) && (bus.ppu.wx as int) - 7 < 160 { + // 描画しなくてもウィンドウの内部行数は次の描画フレームへ引き継ぐ。 + bus.ppu.windowLine += 1; + } HdmaOnHblank(bus); // T6-7: HDMA(HBlank毎16バイト転送)のフック - windowLine = bus.ppu.windowLine; // PpuRenderScanlineが更新するため読み戻す + windowLine = bus.ppu.windowLine; // 描画時も省略時も更新されるため読み戻す } if lineAdvanced || prevMode != mode { diff --git a/Packages/Core/Src/SaveState.rux b/Packages/Core/Src/SaveState.rux index 6f6219d..cf78926 100644 --- a/Packages/Core/Src/SaveState.rux +++ b/Packages/Core/Src/SaveState.rux @@ -9,7 +9,7 @@ /// Mooneye判定用デバッグフラグ(cpu.debugBreakOnLdBb/ldBbHit)・APUのリングバッファ /// (apu.ringLeft/ringRight/ringRead/ringWrite/ringCount、単なる出力先バッファで /// ゲーム状態ではない)・PPUのスキャンライン描画スクラッチ(ppu.bgColorIndex/ -/// bgCgbPalette/bgCgbPriority、`PpuRenderScanline`内で書いてすぐ読むだけで1ライン +/// bgCgbPriority、`PpuRenderScanline`内で書いてすぐ読むだけで1ライン /// をまたいで生存しない)は保存しない。ジョイパッド(FF00)は選択ライン /// (joypSelectAction/joypSelectDirection)と押下状態(joypPressed)を専用フィールドとして /// 保存する(移植元`~/dev/_Emu/BubiBoyLite/src/core/savestate.odin`もJOYPAD_STATE_SIZE @@ -421,6 +421,8 @@ func ReadApuState(c: *var ReadCursor, apu: *var Apu) { GetBytes(c, @apu.waveRam[0], 16); apu.sampleCounter = GetI32(c); + ApuRefreshWaveUnit(apu); + ApuRefreshActivity(apu); apu.ringRead = 0; apu.ringWrite = 0; @@ -613,7 +615,8 @@ func ReadTimerState(c: *var ReadCursor, bus: *var Bus) { /// cpu/busの現在状態をdstへ書き込み、実際に書き込んだバイト数を返す。呼び出し側は /// 事前に`dst.length >= SaveStateExpectedSize(bus)`を保証すること /// (`SaveStateExpectedSize`ちょうどのバッファを渡すのが標準的な使い方)。 -pub func SaveStateWrite(cpu: *Cpu, bus: *Bus, dst: MutableSlice) -> uint { +pub func SaveStateWrite(cpu: *Cpu, bus: *var Bus, dst: MutableSlice) -> uint { + BusFlushApu(bus); let expected = SaveStateExpectedSize(bus); Assert(dst.length >= expected, "SaveStateWrite: dst is smaller than SaveStateExpectedSize"); @@ -671,6 +674,10 @@ pub func SaveStateRead(cpu: *var Cpu, bus: *var Bus, data: Slice) -> Save ReadCpuState(@c, cpu); ReadBusState(@c, bus); + bus.apuPendingCycles = 0; + BusResetSync(bus); + MbcUpdateRomWindows(@bus.cart); + BusRefreshPaletteCache(bus); return SaveStateError::None; } diff --git a/Packages/Sdl3/Src/Sdl3.rux b/Packages/Sdl3/Src/Sdl3.rux index 793fd91..a3d00d5 100644 --- a/Packages/Sdl3/Src/Sdl3.rux +++ b/Packages/Sdl3/Src/Sdl3.rux @@ -176,4 +176,6 @@ pub extern { func SDL_GetPerformanceCounter() -> uint64; func SDL_GetPerformanceFrequency() -> uint64; func SDL_Delay(ms: uint32); + // SDL_hints.h + func SDL_SetHint(name: *char8, value: *char8) -> bool8; } diff --git a/Tests/Packages/Core/Acid2/Src/Main.rux b/Tests/Packages/Core/Acid2/Src/Main.rux index 89b021b..52533ef 100644 --- a/Tests/Packages/Core/Acid2/Src/Main.rux +++ b/Tests/Packages/Core/Acid2/Src/Main.rux @@ -1,7 +1,7 @@ import Core::{ Slice, #target, #Error }; import GbCore::{ Cpu, Bus, GbMode, CyclesPerFrame, - CpuReset, BusInit, BusPowerOn, BusLoadRom, CpuStep + CpuReset, BusInit, BusPowerOn, BusLoadRom, CpuRun }; // dmg-acid2 のフレームバッファハッシュ判定(BubiBoy Lite tests/acid2_test.odin と同じ方式)。 @@ -143,9 +143,8 @@ func RunAcid2Test(romPath: Slice, label: Slice, expectedHash: uint CpuReset(@cpu, bus.mode); let targetCycles: uint64 = CyclesPerFrame * 100u64; - while bus.cycles < targetCycles { - CpuStep(@cpu, @bus); - } + // アプリと同じCpuRunで実行する(acid2は倍速を使わないのでhwCycles=cycles)。 + CpuRun(@cpu, @bus, targetCycles); var hash: uint64 = FnvOffsetBasis; var i: uint = 0; diff --git a/Tests/Packages/Core/Apu/Src/Main.rux b/Tests/Packages/Core/Apu/Src/Main.rux index 38caba2..a5ae897 100644 --- a/Tests/Packages/Core/Apu/Src/Main.rux +++ b/Tests/Packages/Core/Apu/Src/Main.rux @@ -63,7 +63,7 @@ func Main() -> int { if !bus.apu.noise.enabled { return 16; } // 10: 1フレーム(70224 T-cycle)ぶん進めた後のサンプル数が理論値どおり - // 803ペア(70224/4194304*48000 ≈ 803.6の整数部)になる。 + // 369ペア(70224/4194304*22050 ≈ 369.2の整数部)になる。 var bus2: Bus; BusInit(@bus2); BusPowerOn(@bus2); @@ -71,7 +71,7 @@ func Main() -> int { var sampleBuf: int16[2048]; let dst = MutableSlice { data: @sampleBuf[0], length: 2048 }; let drained = ApuDrainSamples(@bus2.apu, dst); - if drained != 1606 { return 17; } // 803ペア * 2 + if drained != 738 { return 17; } // 369ペア * 2 // 11: 上と同じ理論値を、CPUの実際の駆動パターン(BusTickを4 T-cycleずつ // 17556回)で確認する。sampleCounterの固定小数点蓄積が呼び出しの分割 @@ -87,7 +87,7 @@ func Main() -> int { var sampleBuf2: int16[2048]; let dst2 = MutableSlice { data: @sampleBuf2[0], length: 2048 }; let drained2 = ApuDrainSamples(@bus3.apu, dst2); - if drained2 != 1606 { return 18; } + if drained2 != 738 { return 18; } return 0; } diff --git a/Tests/Packages/Core/ApuBatch/Rux.toml b/Tests/Packages/Core/ApuBatch/Rux.toml new file mode 100644 index 0000000..00a8b17 --- /dev/null +++ b/Tests/Packages/Core/ApuBatch/Rux.toml @@ -0,0 +1,15 @@ +[Manifest] +Version = 1 + +[Package] +Name = "ApuBatchTest" +Version = "0.1.0" +Type = "Executable" +Description = "Compare batched and cycle-by-cycle APU output" + +[Dependencies] +Core = { Path = "../../../../external/Rux/Packages/Core" } +GbCore = { Path = "../../../../Packages/Core" } + +[Build] +Output = "../../../../Bin/Tests/Packages/Core" diff --git a/Tests/Packages/Core/ApuBatch/Src/Main.rux b/Tests/Packages/Core/ApuBatch/Src/Main.rux new file mode 100644 index 0000000..39ee7a8 --- /dev/null +++ b/Tests/Packages/Core/ApuBatch/Src/Main.rux @@ -0,0 +1,257 @@ +import Core::MutableSlice; +import GbCore::{ Apu, ApuReset, ApuPowerOn, ApuWriteRegister, ApuTick, ApuDrainSamples, + Bus, BusInit, BusPowerOn, BusTick, BusCpuTick, BusFlushApu, BusRead, BusWrite, + Cpu, CpuReset, CpuRead8, CpuWrite8, GbMode }; + +func ConfigureAllChannels(apu: *var Apu) { + ApuReset(apu); + ApuPowerOn(apu); + ApuWriteRegister(apu, 0xFF24, 0x77); + ApuWriteRegister(apu, 0xFF25, 0xFF); + ApuWriteRegister(apu, 0xFF11, 0x80); + ApuWriteRegister(apu, 0xFF12, 0xF0); + ApuWriteRegister(apu, 0xFF13, 0x20); + ApuWriteRegister(apu, 0xFF14, 0x86); + ApuWriteRegister(apu, 0xFF16, 0x40); + ApuWriteRegister(apu, 0xFF17, 0xA0); + ApuWriteRegister(apu, 0xFF18, 0x40); + ApuWriteRegister(apu, 0xFF19, 0x87); + ApuWriteRegister(apu, 0xFF1A, 0x80); + ApuWriteRegister(apu, 0xFF1C, 0x20); + var n: uint16 = 0; + while n < 16 { + ApuWriteRegister(apu, 0xFF30 + n, 0xA5); + n += 1; + } + ApuWriteRegister(apu, 0xFF1D, 0x40); + ApuWriteRegister(apu, 0xFF1E, 0x87); + ApuWriteRegister(apu, 0xFF21, 0xF0); + ApuWriteRegister(apu, 0xFF22, 0x35); + ApuWriteRegister(apu, 0xFF23, 0x80); +} + +func Main() -> int { + var fast: Apu; + var reference: Apu; + ConfigureAllChannels(@fast); + ConfigureAllChannels(@reference); + + // 36000 T-cycleを4ずつ(高速経路あり)と9ずつ(常に逐次経路)で進める。 + var step: int = 0; + while step < 9000 { + ApuTick(@fast, 4); + step += 1; + } + step = 0; + while step < 4000 { + ApuTick(@reference, 9); + step += 1; + } + + var fastPcm: int16[2048]; + var referencePcm: int16[2048]; + let fastCount = ApuDrainSamples(@fast, MutableSlice { data: @fastPcm[0], length: 2048 }); + let referenceCount = ApuDrainSamples(@reference, MutableSlice { data: @referencePcm[0], length: 2048 }); + if fastCount != referenceCount { return 1; } + var sample: uint = 0; + while sample < fastCount { + if fastPcm[sample] != referencePcm[sample] { return 2; } + sample += 1; + } + if fast.sampleCounter != reference.sampleCounter || + fast.frameSequencerStep != reference.frameSequencerStep || + fast.wave.sampleArea != reference.wave.sampleArea || + fast.noise.sampleArea != reference.noise.sampleArea || + fast.pulse1.timer != reference.pulse1.timer || + fast.pulse2.timer != reference.pulse2.timer || + fast.wave.timer != reference.wave.timer || + fast.noise.timer != reference.noise.timer { + return 3; + } + + // 無音高速経路を通ったサンプル区間の途中でch1を鳴らしても、 + // 区間平均の分母とPCM出力が逐次更新と一致することを確認する。 + ApuReset(@fast); + ApuReset(@reference); + ApuPowerOn(@fast); + ApuPowerOn(@reference); + step = 0; + while step < 250 { + ApuTick(@fast, 4); + step += 1; + } + step = 0; + while step < 111 { + ApuTick(@reference, 9); + step += 1; + } + ApuTick(@reference, 1); + if fast.anyChannelEnabled || reference.anyChannelEnabled { return 4; } + ApuWriteRegister(@fast, 0xFF11, 0x80); + ApuWriteRegister(@fast, 0xFF12, 0xF0); + ApuWriteRegister(@fast, 0xFF14, 0x80); + ApuWriteRegister(@reference, 0xFF11, 0x80); + ApuWriteRegister(@reference, 0xFF12, 0xF0); + ApuWriteRegister(@reference, 0xFF14, 0x80); + if !fast.anyChannelEnabled || !reference.anyChannelEnabled { return 5; } + step = 0; + while step < 9000 { + ApuTick(@fast, 4); + step += 1; + } + step = 0; + while step < 4000 { + ApuTick(@reference, 9); + step += 1; + } + let quietFastCount = ApuDrainSamples(@fast, MutableSlice { data: @fastPcm[0], length: 2048 }); + let quietRefCount = ApuDrainSamples(@reference, MutableSlice { data: @referencePcm[0], length: 2048 }); + if quietFastCount != quietRefCount { return 6; } + sample = 0; + while sample < quietFastCount { + if fastPcm[sample] != referencePcm[sample] { return 7; } + sample += 1; + } + + // 最短周期のノイズで4 T-cycle呼び出しがLFSR境界をまたぐ場合も、 + // 逐次更新と音声および内部状態が一致することを確認する。 + ConfigureAllChannels(@fast); + ConfigureAllChannels(@reference); + ApuWriteRegister(@fast, 0xFF22, 0x00); + ApuWriteRegister(@reference, 0xFF22, 0x00); + ApuWriteRegister(@fast, 0xFF23, 0x80); + ApuWriteRegister(@reference, 0xFF23, 0x80); + step = 0; + while step < 9000 { + ApuTick(@fast, 4); + step += 1; + } + step = 0; + while step < 4000 { + ApuTick(@reference, 9); + step += 1; + } + let noiseFastCount = ApuDrainSamples(@fast, MutableSlice { data: @fastPcm[0], length: 2048 }); + let noiseRefCount = ApuDrainSamples(@reference, MutableSlice { data: @referencePcm[0], length: 2048 }); + if noiseFastCount != noiseRefCount { return 8; } + sample = 0; + while sample < noiseFastCount { + if fastPcm[sample] != referencePcm[sample] { return 9; } + sample += 1; + } + if fast.noise.timer != reference.noise.timer || + fast.noise.lfsr != reference.noise.lfsr || + fast.noise.sampleArea != reference.noise.sampleArea { + return 10; + } + + // 最短周期の矩形波を含む区間も、波形位置とPCMが逐次更新に一致する。 + ConfigureAllChannels(@fast); + ConfigureAllChannels(@reference); + ApuWriteRegister(@fast, 0xFF13, 0xFF); + ApuWriteRegister(@fast, 0xFF14, 0x87); + ApuWriteRegister(@fast, 0xFF18, 0xFF); + ApuWriteRegister(@fast, 0xFF19, 0x87); + ApuWriteRegister(@reference, 0xFF13, 0xFF); + ApuWriteRegister(@reference, 0xFF14, 0x87); + ApuWriteRegister(@reference, 0xFF18, 0xFF); + ApuWriteRegister(@reference, 0xFF19, 0x87); + step = 0; + while step < 9000 { + ApuTick(@fast, 4); + step += 1; + } + step = 0; + while step < 4000 { + ApuTick(@reference, 9); + step += 1; + } + let pulseFastCount = ApuDrainSamples(@fast, MutableSlice { data: @fastPcm[0], length: 2048 }); + let pulseRefCount = ApuDrainSamples(@reference, MutableSlice { data: @referencePcm[0], length: 2048 }); + if pulseFastCount != pulseRefCount { return 11; } + sample = 0; + while sample < pulseFastCount { + if fastPcm[sample] != referencePcm[sample] { return 12; } + sample += 1; + } + if fast.pulse1.timer != reference.pulse1.timer || + fast.pulse2.timer != reference.pulse2.timer || + fast.pulse1.dutyStep != reference.pulse1.dutyStep || + fast.pulse2.dutyStep != reference.pulse2.dutyStep { + return 13; + } + + // CPU経路でAPU更新をまとめても、レジスタアクセス時の同期とPCMは + // 逐次BusTickと一致する。DMG/倍速CGBの両方を通す。 + var mode: int = 0; + while mode < 2 { + var bufferedBus: Bus; + var directBus: Bus; + var testCpu: Cpu; + BusInit(@bufferedBus); + BusInit(@directBus); + BusPowerOn(@bufferedBus); + BusPowerOn(@directBus); + ConfigureAllChannels(@bufferedBus.apu); + ConfigureAllChannels(@directBus.apu); + CpuReset(@testCpu, GbMode::Dmg); + if mode == 1 { + bufferedBus.doubleSpeed = true; + directBus.doubleSpeed = true; + } + step = 0; + while step < 10000 { + BusCpuTick(@bufferedBus, 4); + BusTick(@directBus, 4); + if step == 3000 { + CpuWrite8(@testCpu, @bufferedBus, 0xFF22, 0x00); + BusTick(@directBus, 4); + BusWrite(@directBus, 0xFF22, 0x00); + } + if step == 5000 { + BusWrite(@bufferedBus, 0xFF04, 0); + BusWrite(@directBus, 0xFF04, 0); + } + if step == 6000 { + let bufferedStatus = CpuRead8(@testCpu, @bufferedBus, 0xFF26); + BusTick(@directBus, 4); + if bufferedStatus != BusRead(@directBus, 0xFF26) { return 14; } + } + if step == 7000 { + if BusRead(@bufferedBus, 0xFF26) != BusRead(@directBus, 0xFF26) { return 18; } + } + if step == 8000 { + BusWrite(@bufferedBus, 0xFF46, 0xFF); + BusWrite(@directBus, 0xFF46, 0xFF); + } + step += 1; + } + BusFlushApu(@bufferedBus); + let bufferedCount = ApuDrainSamples(@bufferedBus.apu, + MutableSlice { data: @fastPcm[0], length: 2048 }); + let directCount = ApuDrainSamples(@directBus.apu, + MutableSlice { data: @referencePcm[0], length: 2048 }); + if bufferedCount != directCount { return 15; } + sample = 0; + while sample < bufferedCount { + if fastPcm[sample] != referencePcm[sample] { return 16; } + sample += 1; + } + if bufferedBus.apu.sampleCounter != directBus.apu.sampleCounter || + bufferedBus.apu.pulse1.timer != directBus.apu.pulse1.timer || + bufferedBus.apu.wave.timer != directBus.apu.wave.timer || + bufferedBus.apu.noise.timer != directBus.apu.noise.timer || + bufferedBus.apu.noise.lfsr != directBus.apu.noise.lfsr || + bufferedBus.apu.wave.sampleArea != directBus.apu.wave.sampleArea || + bufferedBus.apu.noise.sampleArea != directBus.apu.noise.sampleArea { + return 17; + } + var oamByte: uint = 0; + while oamByte < 160 { + if bufferedBus.oam[oamByte] != directBus.oam[oamByte] { return 19; } + oamByte += 1; + } + mode += 1; + } + return 0; +} diff --git a/Tests/Packages/Core/Blargg/Src/Main.rux b/Tests/Packages/Core/Blargg/Src/Main.rux index f783c84..710ee1f 100644 --- a/Tests/Packages/Core/Blargg/Src/Main.rux +++ b/Tests/Packages/Core/Blargg/Src/Main.rux @@ -1,7 +1,7 @@ import Core::{ Slice, #target, #Error }; import GbCore::{ Cpu, Bus, GbMode, - CpuReset, BusInit, BusPowerOn, BusLoadRom, CpuStep, + CpuReset, BusInit, BusPowerOn, BusLoadRom, CpuRun, SerialGetLog }; @@ -126,8 +126,9 @@ func RunBlarggRom(path: Slice, name: Slice, expectedPass: bool, ti var passed = false; var failed = false; + // アプリと同じCpuRunで1フレーム分ずつ進め、その都度シリアル出力を確認する。 while bus.cycles < timeout && !passed && !failed { - CpuStep(@cpu, @bus); + CpuRun(@cpu, @bus, bus.hwCycles + 70224u64); let log = SerialGetLog(@bus); if Contains(log, "Passed") { diff --git a/Tests/Packages/Core/Bus/Src/Main.rux b/Tests/Packages/Core/Bus/Src/Main.rux index b226a77..b2af3be 100644 --- a/Tests/Packages/Core/Bus/Src/Main.rux +++ b/Tests/Packages/Core/Bus/Src/Main.rux @@ -1,7 +1,8 @@ import Core::Slice; import GbCore::{ Bus, Cpu, - BusInit, BusLoadRom, BusRead, BusWrite, BusTick, + BusInit, BusLoadRom, BusRead, BusWrite, BusTick, BusPowerOn, + BusCpuTick, BusHaltTick, BusFlushApu, CpuRead8, CpuWrite8, SerialWrite, SerialGetLog }; @@ -203,5 +204,58 @@ func Main() -> int { BusWrite(@bus, 0xA000, 0x21); if BusRead(@bus, 0xA000) != 0x21 { return 48; } + // HALTの一括更新が、通常の4 T-cycle更新と同じタイマー/PPU/APU状態になる。 + var slow: Bus; + var speed: int = 0; + while speed < 2 { + BusInit(@bus); + BusInit(@slow); + BusPowerOn(@bus); + BusPowerOn(@slow); + bus.doubleSpeed = speed == 1; + slow.doubleSpeed = speed == 1; + bus.tac = 0x05; + slow.tac = 0x05; + bus.tima = 0xFA; + slow.tima = 0xFA; + bus.divCounter = 1; + slow.divCounter = 1; + let advanced = BusHaltTick(@bus, 600); + if advanced < 8 { return 49; } + var elapsed = 0; + while elapsed < advanced { + BusCpuTick(@slow, 4); + elapsed += 4; + } + BusFlushApu(@bus); + BusFlushApu(@slow); + if bus.cycles != slow.cycles || bus.hwCycles != slow.hwCycles || + bus.divCounter != slow.divCounter || bus.tima != slow.tima || + bus.ppu.dot != slow.ppu.dot || bus.ppu.mode != slow.ppu.mode || + bus.ppu.ly != slow.ppu.ly || bus.io[0x0F] != slow.io[0x0F] || + bus.apu.sampleCounter != slow.apu.sampleCounter || + bus.apu.ringCount != slow.apu.ringCount { return 50; } + speed += 1; + } + + // 画面を省いたラインも、ウィンドウの内部行数は描画時と同じだけ進む。 + BusInit(@bus); + BusInit(@slow); + BusPowerOn(@bus); + BusPowerOn(@slow); + bus.ppu.lcdc = bus.ppu.lcdc | 0x20; + slow.ppu.lcdc = slow.ppu.lcdc | 0x20; + bus.ppu.wx = 7; + slow.ppu.wx = 7; + slow.ppu.renderEnabled = false; + var ticks = 0; + while ticks < 63 { + BusCpuTick(@bus, 4); + BusCpuTick(@slow, 4); + ticks += 1; + } + if bus.ppu.windowLine != 1 || slow.ppu.windowLine != bus.ppu.windowLine || + bus.ppu.dot != slow.ppu.dot || bus.ppu.mode != slow.ppu.mode { return 51; } + return 0; } diff --git a/Tests/Packages/Core/PpuTiles/Rux.toml b/Tests/Packages/Core/PpuTiles/Rux.toml new file mode 100644 index 0000000..189ccd3 --- /dev/null +++ b/Tests/Packages/Core/PpuTiles/Rux.toml @@ -0,0 +1,15 @@ +[Manifest] +Version = 1 + +[Package] +Name = "PpuTilesTest" +Version = "0.1.0" +Type = "Executable" +Description = "Verify tile-at-a-time DMG scanline rendering" + +[Dependencies] +Core = { Path = "../../../../external/Rux/Packages/Core" } +GbCore = { Path = "../../../../Packages/Core" } + +[Build] +Output = "../../../../Bin/Tests/Packages/Core" diff --git a/Tests/Packages/Core/PpuTiles/Src/Main.rux b/Tests/Packages/Core/PpuTiles/Src/Main.rux new file mode 100644 index 0000000..5e3e736 --- /dev/null +++ b/Tests/Packages/Core/PpuTiles/Src/Main.rux @@ -0,0 +1,92 @@ +import GbCore::{Bus, BusInit, BusPowerOn, BusRefreshPaletteCache, PpuTick, GbMode, DmgShade0, DmgShade1, DmgShade2, DmgShade3}; + +func Main() -> int { + var bus: Bus; + BusInit(@bus); + BusPowerOn(@bus); + + // tile 0の各色は左から0,1,2,3,0,1,2,3。 + bus.vram[0] = 0x55; + bus.vram[1] = 0x33; + // tile 1は全ピクセルが色1。 + bus.vram[16] = 0xFF; + bus.vram[17] = 0; + bus.vram[0x1800] = 0; + bus.vram[0x1801] = 1; + bus.vram[0x181F] = 1; + bus.ppu.bgp = 0xE4; // 色番号を同じ番号のシェードへ写す + bus.ppu.lcdc = bus.ppu.lcdc | 0x02; // OBJ優先度用スクラッチも検査する + // スクラッチはスプライトの掛かるラインだけ書くので、LY=0に画面外(x=-8)の + // スプライトを1つ置く。 + bus.oam[0] = 16; + bus.oam[1] = 0; + + // 8ピクセル境界の途中から開始し、次のタイルへ進む。 + bus.ppu.scx = 5; + PpuTick(@bus, 252); + if bus.ppu.framebuffer[0] != DmgShade1 { return 1; } + if bus.ppu.framebuffer[1] != DmgShade2 { return 2; } + if bus.ppu.framebuffer[2] != DmgShade3 { return 3; } + if bus.ppu.framebuffer[3] != DmgShade1 { return 4; } + if bus.ppu.framebuffer[10] != DmgShade1 { return 5; } + if bus.ppu.bgColorIndex[0] != 1 || bus.ppu.bgColorIndex[2] != 3 { return 6; } + + // SCXの256ピクセル折り返しとタイルマップ先頭への復帰。 + BusInit(@bus); + BusPowerOn(@bus); + bus.vram[0] = 0x55; + bus.vram[1] = 0x33; + bus.vram[16] = 0xFF; + bus.vram[17] = 0; + bus.vram[0x1800] = 0; + bus.vram[0x181F] = 1; + bus.ppu.bgp = 0xE4; + bus.ppu.scx = 253; + bus.ppu.lcdc = bus.ppu.lcdc | 0x02; + PpuTick(@bus, 252); + if bus.ppu.framebuffer[0] != DmgShade1 { return 7; } + if bus.ppu.framebuffer[2] != DmgShade1 { return 8; } + if bus.ppu.framebuffer[3] != DmgShade0 { return 9; } + if bus.ppu.framebuffer[4] != DmgShade1 { return 10; } + + // CGB: VRAMバンク1、X/Y反転、パレット1、BG優先度を同時に確認。 + BusInit(@bus); + BusPowerOn(@bus); + bus.mode = GbMode::Cgb; + bus.ppu.lcdc = bus.ppu.lcdc | 0x02; + bus.oam[0] = 16; // LY=0に画面外のスプライト(スクラッチを書かせる) + bus.oam[1] = 0; + bus.vram[0x2000 + 14] = 0x01; // tile 0の最終行・右端だけcolor1 + bus.vram[0x1800] = 0; + bus.vram[0x2000 + 0x1800] = 0xE9; // priority,Y flip,X flip,bank1,palette1 + bus.bgPaletteRam[10] = 0x1F; // palette1/color1 = 赤 + bus.bgPaletteRam[11] = 0; + BusRefreshPaletteCache(@bus); // パレットRAMを直接書いたのでARGBキャッシュを作り直す + PpuTick(@bus, 252); + if bus.ppu.framebuffer[0] != 0xFFFF0000u32 { return 11; } + if bus.ppu.framebuffer[1] != 0xFF000000u32 { return 12; } + if bus.ppu.bgColorIndex[0] != 1 { return 13; } + if !bus.ppu.bgCgbPriority[0] { return 14; } + + // 画面x=3でBGからウィンドウへ切り替わる。タイル途中の境界を検査。 + BusInit(@bus); + BusPowerOn(@bus); + bus.ppu.lcdc = bus.ppu.lcdc | 0x62; // window有効、window map=9C00、OBJ有効 + bus.ppu.wx = 10; // 表示開始x=WX-7=3 + bus.ppu.wy = 0; + bus.ppu.bgp = 0xE4; + bus.vram[0] = 0x55; + bus.vram[1] = 0x33; + bus.vram[16] = 0xFF; + bus.vram[17] = 0; + bus.vram[0x1800] = 0; + bus.vram[0x1C00] = 1; + PpuTick(@bus, 252); + if bus.ppu.framebuffer[0] != DmgShade0 { return 15; } + if bus.ppu.framebuffer[1] != DmgShade1 { return 16; } + if bus.ppu.framebuffer[2] != DmgShade2 { return 17; } + if bus.ppu.framebuffer[3] != DmgShade1 { return 18; } + if bus.ppu.framebuffer[10] != DmgShade1 { return 19; } + if bus.ppu.windowLine != 1 { return 20; } + return 0; +} diff --git a/Tests/Packages/Core/SaveState/Src/Main.rux b/Tests/Packages/Core/SaveState/Src/Main.rux index 9189e2d..b45ffb1 100644 --- a/Tests/Packages/Core/SaveState/Src/Main.rux +++ b/Tests/Packages/Core/SaveState/Src/Main.rux @@ -137,7 +137,7 @@ func HashBytes(data: *uint8, len: uint) -> uint64 { // SaveStateWriteの出力バイト列そのものをハッシュ化して「その時点のcpu/busの // 保存対象状態」を1つの値に集約する。復元後に実行を再開して発散したかどうかは、 // 同じNサイクル実行後にもう一度この関数を呼んで比較すればよい。 -func SnapshotHash(cpu: *Cpu, bus: *Bus, scratch: MutableSlice) -> uint64 { +func SnapshotHash(cpu: *Cpu, bus: *var Bus, scratch: MutableSlice) -> uint64 { let n = SaveStateWrite(cpu, bus, scratch); return HashBytes(scratch.data, n); } diff --git a/docs/DevelopmentNotes.md b/docs/DevelopmentNotes.md index af25aa9..18b5ad4 100644 --- a/docs/DevelopmentNotes.md +++ b/docs/DevelopmentNotes.md @@ -140,9 +140,25 @@ RuxBoy 開発を通じて分かったことの棚卸し。`docs/BluePrint.md`( (関数サイズからの推測に過ぎず、実測では分岐位置の効果は+5.5%程度に 留まり、コスト自体は特定の1関数でなく呼び出し連鎖全体に広く薄く 分散していた)。詳細は `docs/PerformanceNotes.md` 参照。 -- **結論として、現時点ではこれ以上のソースコード側の性能対策は行わない - 方針とした**(根本原因は Rux コンパイラの未成熟さであり、コンパイラの - 改善を待つのが筋が良いと判断)。 +- **当時はこれ以上のソースコード側の性能対策を行わない方針とした** + (Rux コンパイラの未成熟さを主因と判断)。2026-09-25 に更新粒度を + 再検討し、PPU/APU/Timer のイベントが起きない短い区間を一括更新して + 改善した。この方針は取り下げた。実測は `docs/PerformanceNotes.md` 8章参照。 +- **2026-09-05 追記**: 同じ BubiBoy Lite 移植の姉妹プロジェクト + `~/dev/_Emu/haregirl`(Hare言語)が行った高速化(APUのdotループ閉じた式化、 + MBCバンク切替のビットマスク化、PPU関連)を1件ずつ RuxBoy と突き合わせ + 監査した。PPU側の対策(タイル単位VRAMキャッシュ・STAT境界判定)は + RuxBoy側で既に独立に先行実装済みだったため変更なし。MBCバンク切替の + 剰余演算(`bank % count`)は「除算命令そのものを除去するアルゴリズム + レベルの変更」でありコンパイラの巧拙に依存しないため、上の「これ以上 + 行わない」方針の例外として`bank & (count - 1)`へ書き換えた(ROM/RAMバンク数は + 仕様上常に2の冪)。APUのチャンネル周期タイマー閉じた式化(ch1/ch2)は + 実際に実装・全テストPASSまで確認したが、`CpuPerf`ベンチで + 221-227%→216-221%realtimeという退行を実測したため差し戻した + (RuxBoyは`BusTick`を4/8 T-cycle単位でしか呼ばずHareGirlのように + HALT待ちを一括バッチしないため、除算1回のコストが短いインライン + ループを数回展開するコストを上回った)。詳細・実測データ・対象外に + した理由の一覧は `docs/PerformanceNotes.md` 7章参照。 ## 4. エミュレーション精度の落とし穴集 diff --git a/docs/PerformanceNotes.md b/docs/PerformanceNotes.md index 133e491..6be2dc2 100644 --- a/docs/PerformanceNotes.md +++ b/docs/PerformanceNotes.md @@ -1,11 +1,10 @@ -# パフォーマンス調査メモ (2026-09-02〜03) +# パフォーマンス調査メモ (2026-09-02〜09-25) Instruments によるプロファイリングをきっかけに行った、CPU/PPU 周りの速度調査の -記録。**結論としては「Rux コンパイラの最適化パイプラインが未成熟であること」が -根本原因であり、コンパイラ側の改善を待つほうが筋が良いと判断し、これ以上の -ソースコード側の対策は現時点で行わない**(詳細は末尾「今後の方針」)。ただし -6章のレジスタペアunion化は、この方針の例外として言語制約内で実施した -軽微な対策。 +記録。2026-09-03 時点では Rux コンパイラの最適化不足を主因とみなし、ソース側の +対策を打ち切る方針だった。2026-09-25 に更新粒度そのものを再検討し、PPU・APU・ +タイマーのイベントが起きない短い区間を一括更新することで実測の改善を得た。 +従来の結論は当時の判断として残し、最新の結果を末尾の章に記録する。 ## 背景 @@ -303,3 +302,671 @@ Bus呼び出し連鎖(2章)ほど大きな効果ではないが、言語制約 実効性のある対策だったため採用した。**それ以外(ジャンプテーブル化、 関数インライン化)は依然としてコンパイラ側の制約であり、5章までの 「コンパイラの改善待ち」という基本方針は変わらない。** + +## 7. HareGirl(同一移植元の姉妹プロジェクト)の高速化との突き合わせ(2026-09-05) + +`~/dev/_Emu/haregirl`(同じ BubiBoy Lite を Hare 言語へ移植したプロジェクト)が +2026-09-04 に2件の `perf:` コミット(`17856de`・`c0c2452`)と1件の音声関連 +`fix:`(`5d4811b`、APUのdotループをO(1)の閉じた式へ書き換え)を行った。 +「HareGirl 側で採れた高速化を RuxBoy にも可能な限り取り込む」という依頼を +受け、該当コミットを1件ずつ RuxBoy の現状と突き合わせた監査の記録。 + +### 7.1 取り込んだもの + +**MBC バンク切替の剰余演算→ビットマスク化**(HareGirl `17856de` に相当、 +`Packages/Core/Src/Mbc.rux` の `NormalizedRomBank`/`NormalizedRamBank`)。 + +`romBanks`(ROMサイズコードから`2 << code`で算出、`RomSizeFromCode`参照)・ +RAMバンク数(`ramLength / 8192`、`RamSizeFromCode`が返しうる値は +{0,1,4,8,16}のみ)はいずれも仕様上常に2の冪であるにもかかわらず、 +`bank % count` という剰余演算で折り返していた。`ReadRomBank`はCPUの +オペコードフェッチを含むROM全バイトアクセスのたびに呼ばれる最も熱い +パスの一つのため、`bank & (count - 1)` へ置き換えた。 + +この最適化は「コンパイラが本来自動でやるべき最適化(mem2reg/インライン化) +の手動肩代わり」という1〜6章の対策群とは性質が異なり、**除算命令を +除去するアルゴリズムレベルの変更**であるため、6章末の「これ以上 +ソースコード側の対策は行わない」という方針の例外として妥当と判断し採用した +(HareGirl側もコンパイラ最適化の巧拙に関係なく効く変更として導入している)。 + +正確性の検証: `scripts/test.sh --release` 全PASS(既知の3件の +expected-failのみ、差分なし。mooneyeのmbc1/mbc5系ROMはいずれもバンク数が +2の冪のROMのため、`bank % n`と`bank & (n-1)`が同じ結果になり退行を +検出できない点に注意)。挙動が変わりうるのは「ヘッダの`romBanks`と実際の +ROM長が食い違い、かつ範囲外バンクを指定する」ケースだが、`CartridgeInit` +(`CartridgeParseHeader`)は`rom.length < romBytes`を`RomSmallerThanHeader` +エラーとして弾くため、`romBanks * RomBankSize <= rom.length`が常に成立し、 +`bank`を`[0, romBanks)`へ折り返す限りどちらの式でも範囲外アクセスにはならない +(`Tests/Packages/Core/Mbc`も`BusLoadRom`経由でこの検証を通るため、この +分岐は現状のコードパス上そもそも到達不能)。以上より計算結果の同値性は +コードの検査で確認済み。 + +性能の検証: `CpuPerf`ベンチ(NOP/JPループ、ROMバンク切替を経由しない)は +修正前後とも221-227%realtimeで測定誤差の範囲内(想定通り無風 — この +ベンチ自体がバンク切替を行わないため)。バンク切替を伴う実ゲーム +(MBC1/MBC5等)での定量的な改善幅は、それを継続的に測る専用ベンチマークが +現状無いため**未計測**(除算1回をビットAND1回に置き換える変更なので +悪化はしないと考えられるが、これは推測であり実測ではない)。 + +### 7.2 既に対策済みだったもの(HareGirlの後追いではなく独立に先行実装済み) + +- **PPU: BG/ウィンドウ描画のタイル単位VRAM読み出しキャッシュ** + (HareGirl `c0c2452`相当)。RuxBoy は `PpuRenderScanline` + (`Packages/Core/Src/Ppu.rux`)で2026-09-02〜03の調査時点(1章参照)から + 同じ設計(タイル列が変わったときだけVRAMを再フェッチ)を実装済み。 +- **PPU: STAT割り込み判定をモード/LY境界でのみ実行**(HareGirl `17856de`の + PPU部分に相当)。RuxBoy の `PpuTick` は境界(ライン送り・モード遷移)の + ときだけ `PpuUpdateStatIrq` を呼ぶ設計を1章の対策時点から実装済み。 + +### 7.3 対象外と判断したもの + +- **APU: チャンネル周期タイマーの閉じた式(O(1))化**(HareGirl `5d4811b`)。 + **実装して実測した上で、退行を確認して差し戻した。** 経緯: + + 1. まず ch1/ch2(矩形波)のみを対象に試作した。wave/noiseは1 T-cycle + ごとの出力値を区間平均(`sampleArea`)へ蓄積する必要があり + HareGirlには無い正確性リスクを抱えるため最初から対象外とし、 + ch1/ch2(瞬時値のみ、区間平均なし)に絞った。`timer`は常に + `[1, period]`に収まる不変条件(トリガー時・リロード時に成立)を + 利用し、`apu_periodic_wraps`(HareGirl)と同じ閉じた式(除算+剰余) + で経過ラップ数と最終timer値を一発で求める関数を実装。ただし + `PulseOutputUnits`は48kHzサンプル生成の瞬間にしか読まれないため、 + `BusTick`呼び出し(4/8 T-cycle)の途中でサンプル境界をまたぐ場合に + `dutyStep`が本来より早く進んだ状態を読んでしまわないよう、 + サンプル境界までの分だけ前進させてから`MixSample`を呼び、残りは + 次の境界まで`pulsePending`ローカル変数で持ち越す設計にした + (HareGirlが同コミットで「一括で進めると状態が凍結する」と書いている + 問題への対処と同じ理由)。 + 2. `scripts/test.sh --release` は全PASS(dmg_sound の "03-trigger"・ + "04-sweep"・"06-overflow on trigger"・"10-wave trigger while on" + などトリガー/タイミングに敏感なテストを含め、既存の3件の + expected-fail以外は差分なし)で、**正確性の面では問題が無かった**。 + 3. しかし `CpuPerf`ベンチ(`--release`、3回×2セット計測)は + **221-227%realtime(適用前) → 216-221%realtime(適用後)**と、 + むしろ2-5%ポイントの退行だった。原因は、`BusTick`が渡す tCycles が + 常に4または8(7.3節で確認済み)と小さく、除算を伴う閉じた式1回の + コストが「1 T-cycleごとの減算+比較+分岐を最大8回繰り返す」コストを + Release最適化なしのRux上では下回らなかったため、かつ関数呼び出し + (`ApuAdvancePulse`)自体のオーバーヘッドが元のインライン展開済み + コードより増えたためと考えられる(いずれも未検証の推測だが、 + 測定結果自体は再現性あり)。 + 4. `Packages/Core/Src/Apu.rux` の変更は `git checkout` で差し戻し、 + 元のT-cycleごとのインラインループへ戻した。 + + 結論: HareGirlでこの最適化が効いたのは、CPUのHALT/STOP待ちで + `apu_tick` に大きなT-cycle数を一括で渡す(バッチする)設計だから + であり、RuxBoyのように1命令(4/8 T-cycle)ごとにしか`BusTick`を + 呼ばない設計では、同じ変更が逆効果になることを実測で確認した。 + 将来 RuxBoy 側で HALT 中の T-cycle をまとめて進める設計に変更する + 場合は再検討の価値がある。 +- **APU: i16ミキサーのオーバーフロー修正**(HareGirl `1ec5d10`)。RuxBoy の + `MixSample`(`Packages/Core/Src/Apu.rux`)は元から `int64` で + `(mix * volBits * 32767) / 480` と最後に一度だけ除算する設計のため、 + HareGirlが踏んだ「`*128`の中間計算がi16レンジを超えてラップする」 + という不具合が構造的に発生しない。対応不要。 +- **APU: ノイズチャンネル周期のu16オーバーフロー**(HareGirl `5d4811b`が + ついでに直したガード)。RuxBoy はタイマーを`int32`で持つ設計 + (Apu.rux冒頭のコメント参照)のため、`u16`への丸め込みによる + ゼロ除算相当のバグはそもそも存在しない。対応不要。 +- **CPU: ブレークポイント検出用オペコードの二重フェッチ回避** + (HareGirl `17856de`)。RuxBoy の `App` 層にHareGirlの + `rom_runner_step`のようなブレークポイント検出機構自体が無い + (`grep -rn "breakpoint" Packages/App/Src/*.rux` 該当なし)ため対象外。 +- **APU: 電源投入時のNRx4トリガービット誤書き込み**(HareGirl `1a8847a`)。 + RuxBoy の `ApuPowerOn`(Apu.rux)はNRx4レジスタへの書き込みや + `TriggerPulse`等の呼び出しを行わず、`poweredOn`/`nr50`/`nr51`/ + `noise.lfsr`のみを直接セットする設計のため、この不具合はそもそも + 発生しない。対応不要。 +- **App層: ウィンドウ終了時の音声デバイスポーズ / 音量設定の反映漏れ / + フレームペーシング**(HareGirl `1a8847a`・`00362b8`・`17c5b90`)。 + いずれもApp/SDL層のバグ修正であり「コア(移植主対象)の軽量化」という + 今回の依頼の対象外と判断。RuxBoyのApp層は最初から音声駆動ペーシング + (バッファ残量に応じてスロットリング、5章のBubiBoy Lite比較参照)を + 採用しており、HareGirlが`17c5b90`で後追いした固定`delay`方式の問題は + そもそも発生しない設計。 + +## 8. イベント境界をまたがない区間の一括更新 (2026-09-25) + +gnuboy の C 実装は LCD の次のモード遷移や音声のサンプル生成まで時間を進める。 +これを参考に、RuxBoy の通常の `BusTick(4)` / 倍速時の `BusTick(2)` において +状態変化のない区間を T-cycle ごとに反復しない方針を試した。イベント境界を +またぐ呼び出しは既存の逐次処理を通すため、割り込み・描画・音声の順序は維持する。 + +- `PpuTick`: 現在の mode から次の境界(dot=80/252/456)を求め、今回の呼び出しが + そこへ届かなければ dot だけ更新して戻る。 +- `ApuTick`: 次の48kHzサンプル、フレームシーケンサ、各チャンネルの周期タイマー + のどれも越えない、最大8 T-cycleの区間を一括更新する。wave/noise の区間平均用 + `sampleArea` には不変の出力値×T-cycle数を足し、`sampleCycles`も同数進める。 +- `TimerTick`: リロード保留がなく、選択された DIV ビットの立ち下がりを + またがない最大8 T-cycleの区間は、DIVだけをまとめて進める。 + +Windows x86-64 の同一PC・Releaseビルドで計測した。`CpuPerf` は NOP/JP ループ +なので実ゲームの命令分布や音声出力を代表しない。短縮版(20M T-cycle)は +候補の採否を素早く決めるために一時的に使い、最終確認では元の200M T-cycleに +戻した。短縮版の変更は作業ツリーに残していない。 + +| 状態 | CpuPerf 200M T-cycle の realtime | dmg-acid2 300フレームのCPU時間中央値 | +|---|---:|---:| +| 変更前 | 59% | 10.06秒 (9.47, 10.06, 10.84) | +| PPU一括更新 | 70% | 9.03秒 (9.59, 8.86, 9.03) | +| PPU+APU一括更新 | 104% | 5.95秒 (5.92, 5.95, 6.02) | +| PPU+APU+Timer一括更新 | 102%, 103% (2回) | 5.52秒 (5.41, 5.58, 5.52) | + +実行コマンドは `CpuPerf` パッケージで `rux run --release`、実ROM側は +`RuxBoy.exe --headless --frames 300 Tests/roms/acid2/dmg-acid2.gb`。 +プロセスCPU時間は Windows の `TotalProcessorTime` を取得した。初回の壁時計は +起動等で大きくばらついたため、表にはCPU時間を用いた。dmg-acid2は公開テスト +ROMであり、音声を常時鳴らす商用ゲームの性能を保証する結果ではない。 +Timer追加後のCpuPerfは追加前の104%を上回らず、NOP/JPでの改善は確認 +できなかった。dmg-acid2では3回とも追加前よりCPU時間が短かった。 + +音声が有効な経路も確認するため、32KiBの一時的な検証ROMにNR11/NR12/NR13/ +NR14等への書き込みとNOP/JPループを置き、矩形波ch1を鳴らし続けた。 +PPU+Timerを同じ状態にしてAPU高速経路だけを無効化した場合の300フレームの +CPU時間は 9.03/9.03/8.95秒、新経路では 6.13/6.25/6.17秒だった。 +このROMは計測後に削除した。音色・命令分布とも実ゲームを代表しないが、 +APUチャンネル動作中にも高速経路が有効であることは確認できた。 + +採用前に DMA 停止中の呼び出し省略、PPU の境界計算を毎回行う方式、 +タイマー無効時だけの一括更新も試したが、CpuPerfで改善せず差し戻した。 +イベントが起きない場合の早期 return に絞った上記3件だけを採用した。 + +検証は `rux check`、`scripts/test.sh --release` 相当の全パッケージ実行で行った。 +Cpu/Bus/Joypad/CpuInstrs/Blargg/Apu/ApuBatch/DmgSound/Mbc/Mooneye/Cgb/Acid2/SaveStateが +すべて成功。Mooneyeの既知3件のEXPECTED FAIL以外に失敗はなく、 +dmg-acid2/cgb-acid2のフレームバッファハッシュも一致した。 +`ApuBatch` は全4チャンネルを有効にし、36000 T-cycleを4ずつ(高速経路あり)と +9ずつ(逐次経路)に分けて進め、PCMの全サンプル・各タイマー・区間平均の残量を +比較する。Debug/Releaseの両方で一致した。 + +この改善はコンパイラの関数インライン化不足とは独立に、イベントが起きない +T-cycleの処理そのものを減らす。従来の「コンパイラ改善待ちだけ」という方針は +取り下げる。ただし実ゲームに対する改善率はROMと音声・タイマーの使用状況で +変わるため、より代表的なワークロードでの計測は引き続き必要。 + +## 9. 現時点の残余コストの切り分け (2026-09-25) + +8章の改善後にも残るコストを調べるため、`CpuPerf` を一時的に20M T-cycleに +短縮し、`BusTick` 内の各サブシステム呼び出しを個別に外して3回ずつ計測した。 +いずれも計測専用の変更で、元に戻している。CPUはNOP/JPを繰り返し、DMGの +背景描画は動くが、スプライトと音声チャンネルは初期状態のままである。 + +| 条件 | 所要時間の中央値 | 基準との差 | +|---|---:|---:| +| 全サブシステム有効 | 約3.85秒 | — | +| PPU更新を省略 | 約2.36秒 | 約1.49秒 (39%) | +| APU更新を省略 | 約2.96秒 | 約0.89秒 (23%) | +| Timer更新を省略 | 約3.53秒 | 約0.33秒 (9%) | +| DMA更新を省略 | 約3.90秒 | 有意な改善なし | +| PPUの走査線描画だけ省略 | 約2.61秒 | 約1.24秒 (32%) | + +差は各処理の「呼び出しをなくした場合」の効果であり、関数単体の排他的な実行時間 +ではない。合計して全CPU使用率と解釈することもできない。特にAPUはチャンネルが +鳴っていない条件なので、音声を使うROMには割合をそのまま当てはめられない。 +一方、PPUでは描画だけでPPU全体の差分の大半を占めた。次の最適化対象は +`PpuRenderScanline` のBG/ウィンドウのピクセルループと判断した。 + +この調査中、モード境界のdot値をPPU状態にキャッシュする案も試したが、20M +T-cycleの中央値は約3.95秒と基準より遅く、採用しなかった。描画ループでは +DMG色変換の関数呼び出しを展開し、スクロール位置・パレット・モード等の +走査線中に変わらない値をローカルに保持した。20M T-cycleの中央値は約3.75秒 +(基準比約2.6%短縮)。200M T-cycleでは36.80秒、129% realtimeだった。 +同一条件の200M基準値は取り直していないため、この長時間計測値だけで改善率を +算出しない。dmg-acid2 300フレームのCPU時間は5.48/5.38/5.27秒で、 +8章の変更後に得た5.41/5.58/5.52秒と近い。短い合成ベンチでの改善を +実ゲームの確定的な改善率とは扱わない。 +Releaseの全テスト(Cpu/Bus/Joypad/CpuInstrs/Blargg/Apu/ApuBatch/DmgSound/Mbc/ +Mooneye/Cgb/Acid2/SaveState)は成功し、Mooneyeの既知3件以外に失敗はない。 + +## 10. タイル描画・無音APU・ROM読み出しの再設計 (2026-09-25) + +9章の切り分けで最大だった走査線描画を、BG/ウィンドウのソース切り替えを +含めてタイル単位のループに変更した。タイルマップ・属性・2bppの2バイトは +タイル境界でだけ読み、タイル内ではビット位置を1ずつ進める。ウィンドウが +タイルの途中から現れる場合はそこで処理を区切る。CGBパレットの32色は +走査線ごとに一度だけARGBへ変換する。スプライトが無効なラインでは +優先度判定用スクラッチを書かず、使われていなかった`bgCgbPalette`配列は +削除した。旧ピクセル単位の汎用ループは不要になったため削除した。 + +APUは全4チャンネルが停止中で、次のサンプル/フレームシーケンサ境界を +越えない呼び出しを別経路にした。波形値は常に0なので、区間平均の分母・ +フレーム時刻・サンプル時刻だけを進める。`anyChannelEnabled`はトリガー、 +DAC停止、長さ/スイープクロック、セーブステート復元の後に実チャンネルから +再構築する派生値で、ステート形式は変更しない。無音から発音へ切り替わる +サンプル区間のPCMも、1 T-cycle逐次処理と一致するテストを追加した。 + +ROM読み出しは、命令フェッチごとにMBC種別ディスパッチ→種別別Read→ +ReadRomBankと進んでいた経路を、`MbcRead`内のROM専用経路にまとめた。 +MBC1の下位バンク切り替え、MBC2/3/5の上位バンク選択、物理バンクの +マスクは従来と同じで、外部RAM/RTCの経路は変更していない。 +さらに`CpuRead8`からROM領域だけ直接`MbcRead`へ渡す案も試したが、 +NOP/JPでは約4%速くてもacid2のCPU時間には改善がなく、採用しなかった。 + +Windows x86-64 Release、同一PCの計測。`CpuPerf`の短縮版は候補比較に +のみ使用し、最終的には元の200M T-cycleへ戻した。 + +| 対象 | 比較条件 | 変更前 | 変更後 | +|---|---|---:|---:| +| CpuPerf | 200M T-cycle、NOP/JP | 36.80秒 (129% realtime) | 25.27–25.59秒 (186–188% realtime) | +| dmg-acid2 | headless、300フレーム、CPU時間中央値 | 5.38秒 | 4.27秒 | +| cgb-acid2 | 同上、CGBタイル経路を無効化した比較版 | 5.78秒 | 4.56秒 | + +CpuPerfの所要時間は約31%、dmg-acid2のCPU時間は約21%短くなった。 +cgb-acid2の比較版はこの章の作業途中の他の変更を含むため、表の差を +全変更の効果として解釈しない。いずれも短いテストROMであり、音声や +スプライトを多用する市販ゲームの性能は代表しない。発音中の合成ベンチは +測定のばらつきが大きく、無音APU経路の発音中への影響は定量化できなかった。 + +更新後の20M T-cycleで再び個別に処理を外すと、PPUで約27%、APUで約19%、 +Timerで約12%の差があった。CPU命令実行とメモリ読み出しを含む残りも大きい。 +60fpsを低いCPU使用率で実現したとはまだ言えず、実際に問題が出ているROMと +環境での計測、およびBusの更新頻度とCPU側の実行経路の見直しが必要。 +検証はReleaseの全パッケージ(Cpu/Bus/Joypad/CpuInstrs/Blargg/Apu/ApuBatch/ +DmgSound/Mbc/Mooneye/Cgb/PpuTiles/Acid2/SaveState)で成功。Mooneyeの既知3件 +以外に失敗はない。`PpuTiles`はスクロールのタイル途中開始・256ピクセル +折り返し・ウィンドウの途中切り替え・CGBのX/Y反転とVRAMバンク/パレット/ +優先度を検査する。DebugのPpuTiles/ApuBatchも通過した。 + +## 11. Dragon Quest III (CGB) の実測と切り分け (2026-09-26) + +ユーザー指定のROMを一時コピーしてRelease/Windows x86-64の`--headless`で +計測した。元のROMは読み取りだけに使用した。300フレームは約5.02秒、 +900フレームは約15.07秒のエミュレーション時間に相当する。測定した +プロセスCPU時間は、300フレームで約5.8~7.3秒、900フレームで約15.6~21.8秒 +と実行間の変動が大きい。単発値を最適化の効果として扱わず、変更前後を同じ +条件で交互に測る必要がある。いずれにしても、低CPU使用率で60fpsを達成する +目標には達していない。 + +300・900フレーム目にはCGBのダブルスピードに移行済みで、CPU命令ステップは +それぞれ約1.41万・1.45万回/フレームだった。両フレームともHALT中の +`CpuStep`は0回。HALT待ちのイベントジャンプはこのゲームの該当場面には +効かない。300フレーム目までは音声サンプルが無音で、約540フレーム目以降に +発音を確認した。 + +描画だけを外した比較では300フレームのCPU時間に有意な差がなく、 +`ApuTick`全体を外した比較は約0.55秒の差だった。したがって、この場面を +PPUの走査線描画だけで説明することはできない。DMA停止時の +`DmaTickOneMcycle`呼び出しを省く案、割り込み処理入口の条件を呼び出し側へ +移す案、WRAMアドレス変換を読み書き経路へ直接展開する案も、同条件3回ずつの +比較で改善を確認できず差し戻した。 +`VideoPresent`を外す比較も計測値が逆方向に動き、アプリ描画負荷の定量化には +使えなかった。Windows Performance RecorderのCPUサンプリングは、 +プロファイル開始時に権限エラー`0xc5585011`となり実施できなかった。 + +参考実装の[Peanut-GB](https://github.com/deltabeard/Peanut-GB)はDMG中心で、 +音声は標準設定で無効。CGBの実装は予備段階であり、このゲームの倍速・音声を +含む負荷との数値比較には使えない。 +[gregtour/gameboy](https://github.com/gregtour/gameboy)はC実装でCGB対応が +作業中。両者のメモリアクセス/命令実行の構造は設計の参考にするが、 +機能差と精度差を踏まえてRuxBoyの実ROMで計測する。 + +同じ条件で`Pocket Monsters - Aka (Japan) (Rev 1) (SGB Enhanced)`も測定した。 +300フレームのCPU時間は1.53~1.59秒、900フレームは6.47~6.53秒だった。 +このカートリッジのヘッダCGBフラグは`0x00`で、SGB拡張であってCGB倍速ではない。 +したがって、Dragon Quest IIIのCGBダブルスピード負荷とは別のワークロードであり、 +起動後15秒までの場面では実時間を大きく上回る。両ROMの差は、実行モードと +ゲーム側の命令量の差を含む。30秒以降の負荷については次章参照。 + +## 12. ポケモン赤の30秒以降の音切れ (2026-09-26) + +ユーザー報告を受け、同ROMを通常表示・WASAPI出力で3600フレーム(約60.3秒) +実行し、1秒ごとの音声キュー最小値とフレーム間隔を記録した。1800フレーム +以降の31区間中24区間で`SDL_GetAudioStreamQueued`の値が少なくとも1回0になった。 +発音中も毎フレーム約1606~1608個のint16サンプルが生成され、 +`SDL_PutAudioStreamData`は失敗していない。短時間のベンチでは見えなかった +再生待ちキューの枯渇が音切れと一致する。 + +アプリ層とコア層を分けるため、`SDL_GetPerformanceCounter`で60フレームごとの +時間を一時的に計測した。発音中の代表値はCPU/周辺機器更新が約820ms、 +画面提示などが約175ms、`AudioPushFrame`(リングバッファ取り出しとSDL投入) +が約1~2ms。`ApuTick`呼び出しを計測用に外した2100フレーム比較では +プロセスCPU時間が32.39秒から17.98秒へ下がった。ただし音声サンプル生成も +停止するため、差の全てをAPU関数単体の排他的時間とは解釈しない。 +少なくともアプリのSDL音声投入処理は主因ではない。 + +波形チャンネルのニブル・音量計算を、位置/波形RAM/NR32の変更時だけ更新する +派生キャッシュに変更した。`ApuBatch`、`DmgSound`、`SaveState`のReleaseテストは +成功し、2100フレームのCPU時間は同じPCで31.05秒だった。先の32.39秒とは +ヘッドレス計測時のペーシング/計測コードが一部異なるため、差を確定した +改善率とは扱わない。ただし再度の +3600フレーム通常表示では30秒以降の31区間中24区間でキュー0を記録し、 +音切れの解消には至っていない。 + +音声ストリームの周波数比を変える試行は、音程とゲーム時間の整合を崩すため +撤回した。完成版にその処理は含めない。命令内でAPU更新をまとめる案、 +ノイズ出力キャッシュなども実ROMのCPU時間が悪化したため採用しなかった。 + +短いAPU更新がノイズのLFSR更新境界をまたぐ場合も、高速経路で区間平均を +二分して計算するようにした。最短周期を含む逐次更新とのPCM/内部状態比較、 +`DmgSound`のReleaseテストが通った。2100フレームのCPU時間は同条件の +直前の31.05秒から29.62秒になった。再生速度は変更していない。 +通常表示の3600フレーム計測では、30秒以降のキュー0は31区間中12区間に +減ったが、なお音切れの可能性がある。音声を画面提示より先に投入する試行は +同じ条件で13区間となり、改善を確認できないため戻した。 +`AudioPushFrame`自体は約1~2ms/秒であり、アプリの音声投入処理より +APUを含むコア処理と画面提示の時間が問題。ただしAPU更新を外す比較は +音声生成も止めるため、APU単体の排他的CPU時間を示す値ではない。 + +## 13. Gambatte-libretroとの実行構造の比較 (2026-09-26) + +Gambatteの`CPU::process`はCPUのサイクルカウンタをローカルに保持し、 +`nextEventTime()`まで命令を連続実行する。通常のメモリ読み書きはページごとの +ポインタを通る高速経路を持つ。対してRuxBoyの`CpuRead8`/`CpuWrite8`は +毎回`BusTick(4)`を呼び、`BusTick`からTimer/PPU/APU/DMAへ進める。 +DMGでは1フレーム70224 T-cycleなので、4 T-cycle単位は約17556回/フレーム、 +約105万回/秒に相当する。CGB倍速時はPPU/APUへの供給量が半分になるだけで、 +CPU側の更新回数はさらに増える。これらは実際の関数呼び出し数を計測した値 +ではなく、現在の更新粒度から求めた目安。 + +RuxBoyのPPU/APU/Timerにはイベント境界をまたがない短い区間の高速経路を +追加済みだが、各メモリアクセスから複数の周辺機器へ到達する呼び出し構造は +残っている。Releaseコンパイラのインライン化不足はこの構造の費用を増やすが、 +構造自体もGambatteより細粒度である。音声出力SDL投入が約1~2ms/秒だった +実測とも整合する。Gambatteとの同一ROM・同一環境でのCPU時間比較はまだ +行っておらず、何倍遅いかは断定できない。 + +参考: [Gambatte CPU実行ループ](https://github.com/libretro/gambatte-libretro/blob/master/libgambatte/src/cpu.cpp)、 +[Gambatteメモリ高速経路](https://github.com/libretro/gambatte-libretro/blob/master/libgambatte/src/gambatte-memory.h)。 + +## 14. 周辺機器の間引き計測と不採用の構造変更 (2026-09-26) + +Gambatteのコードは移植せず、RuxBoyの更新粒度を変える試作を実ROMで評価した。 +ポケモン赤を一時コピーからRelease/Windows x86-64、`--headless --frames 2100`で +実行した。変更前のCPU時間は29.83秒。PPUのイベントに届かない区間を +`BusTick`へ展開した試作は30.55/30.36秒、CPU命令内でAPU更新を8 T-cycleまで +まとめる試作は31.08秒だった。DMG背景のパレット分岐を配列参照にする試作も +33.70秒で悪化した。矩形波の周期更新境界を高速経路へ含める試作は +30.17/30.09秒で改善を確認できなかった。いずれも製品コードから撤回した。 +最短周期の矩形波を逐次更新と比較するテストだけは残す。 + +`BusTick`の約997回に1回、Timer/PPU/APU/DMA呼び出し前後の高精度時計を +一時的に読んだ。3600フレームのうち1800フレーム以降だけを集計すると、 +31696サンプルの計測時間はTimer 27910、PPU 65944、APU 137356、DMA 18891 +カウンタtickだった。対象4処理の合計中ではAPU約55%、PPU約26%、 +Timer約11%、DMA約8%。CPU命令実行やメモリ読み書きはこの割合に含まない。 +計測コードの費用も各区間に入るため、排他的CPU時間の厳密値ではないが、 +APUが最も高価な周辺機器という判断は先のAPU停止比較とも整合する。 +同区間のチャンネル有効サンプル数は矩形波1/2とノイズが各31696、 +波形が31679で、ほぼ常時4チャンネル動作していた。 + +APU経路も一時的に数えた。1800~3600フレームでは高速経路29793578回、 +逐次経路1807571回。逐次経路のうちサンプル生成境界を含む呼び出しは +1446586回で、矩形波境界192545回、波形境界174792回(理由は重複可)。 +更新の約94%はイベントのない短い区間であり、周期境界だけを高速化しても +全体への効果は小さい。診断用カウンタは計測後に削除した。 + +したがって発音中のAPUを、レジスタ書き込み・フレームシーケンサ・各波形の +変化・サンプル生成というイベントの時刻でまとめて進める設計が次の主対象。 +各CPUメモリアクセスから単純に呼び出しを移すだけでは速くならなかった。 +音声のサンプルレートや再生速度は変更しない。 + +## 15. APUのイベント単位更新 (2026-09-26) + +14章の課題に対し、CPU経路で保留するAPU時間を8から256 T-cycleに広げ、 +`ApuTick`の長い更新では次のサンプル・矩形波/波形/ノイズ周期・フレーム +シーケンサ境界まで直接進める処理を追加した。波形とノイズの区間平均は、 +出力が不変の区間について出力単位×経過T-cycle数を加算する。境界のT-cycle +だけ従来と同じ順序で処理し、レジスタ読み書き・DIV書き込み・DMAのAPU +レジスタ読み取り・音声出力・保存状態の前には保留時間を反映する。 +音声サンプルレートやミキシング方式は変更していない。 +8192組の音声リングバッファは2の冪容量なので、読み書き位置の折り返しを +剰余から明示的なビットマスクへ変更した。この小変更の単独効果は未計測。 + +Windows x86-64 Release、同一PCで元実装と新実装を交互にビルドし、 +`--headless --frames 300`のプロセスCPU時間を計測した。公開テストROMの +dmg-acid2は元実装3.23/3.28秒、新実装2.70~2.83秒。合成ROMは4チャンネルを +起動してからNOP/JPを繰り返し、音声が非ゼロであることを確認した。 +元実装4.78/4.98秒、新実装3.36/3.30秒。合成ROMは実ゲームの命令分布や +レジスタ操作頻度を代表しないため、この割合を実ゲームの改善率とは見なさない。 + +`ApuBatch`はDMG/CGB倍速で、256 T-cycle単位の保留を使うCPU経路と逐次更新を +40,000 CPU T-cycle進め、生成PCM、タイマー、LFSR、区間平均残量を比較して一致。 +`DmgSound`、acid2の画面ハッシュも一致した。発音中の実ゲームでのCPU時間と +音切れの有無は未計測。 + +別途、頻出CPU命令のレジスタ読み書きヘルパー呼び出しを手動展開したが、 +dmg-acid2の交互比較では元実装3.23/3.28秒、新実装3.28/3.31秒で改善を +確認できなかった。レジスタ演算中心の合成ROMでも約1~2%の短縮にとどまり、 +製品コードへは採用しなかった。 + +## 16. CGB倍速ゲームのCPUアクセス経路 (2026-09-26) + +Dragon Quest IIIの起動後300/900フレームを、ユーザー指定ROMの一時コピーで +Windows x86-64 Release、headlessで計測した。CPUのROM読み出しは +`CpuRead8 → BusRead → BusReadRaw → MbcRead`だったので、ROMアドレスのみ +`CpuRead8 → MbcRead`へ短縮した。また通常の4 T-cycle更新でタイマーの +立ち下がりもリロードも起こらない場合、`BusCpuTick`でDIVを直接進めて +`TimerTick`の呼び出しを省いた。境界をまたぐ更新は従来経路を使う。 + +元版と変更版の実行ファイルを交互に走らせたプロセスCPU時間: + +| フレーム数 | 元版 | 変更版 | +|---|---:|---:| +| 300 | 6.64/6.83/6.70秒 | 6.19/6.19/6.06秒 | +| 900 | 17.28/17.23秒 | 16.05/15.94秒 | + +900フレーム時のBMPのSHA-256は元版と変更版で一致した。Releaseの全14テスト +パッケージも通過した(Mooneyeの既知の期待失敗3件は従来通り)。 +MBC5専用ROM分岐、CPU経路へのPPU短経路展開、WRAM/HRAMの直接アクセスは +追加効果が安定しないか悪化したため採用しなかった。 + +900フレームはゲーム内時間約15秒で、変更後もheadlessのCPU時間が約16秒。 +画面提示と音声出力を含む実プレイの余裕は確認できていない。今回の数値は +起動場面のもので、長時間の戦闘・街中などの負荷を代表しない。 + +## 17. PCM出力を22.05kHzへ変更 (2026-09-26) + +ユーザーの音質と速度の優先度に合わせ、APUのPCM生成レートを48kHzから +22.05kHzへ下げた。APUの波形タイマー、フレームシーケンサ、ゲーム時間は +4,194,304HzのハードウェアT-cycleのまま進む。SDLへ渡す入力レートは +APUの定数を参照し、デバイス側レートとの差はSDLのストリーム変換に任せる。 +実機のAPU出力はアナログで、48kHzという固定のPCMレートはない。 + +Dragon Quest III、Windows x86-64 Release、headless、900フレームを +48kHz版と22.05kHz版で交互に計測したプロセスCPU時間は、それぞれ +15.56/15.83秒、15.39/15.38秒だった。300フレームでは差がほぼなかった。 +速度への効果は小さく、GBC倍速処理の根本的な不足は残る。 +22.05kHz版で900フレーム後のBMPハッシュは48kHz版と一致し、 +音声ログでは入力22,050Hz、デバイス側44,100Hz、最終フレームの排出738個の +int16値(369ステレオペア)、非ゼロ音声を確認した。Apu/ApuBatch/DmgSound/ +SaveState/Acid2のReleaseテストは通過した。 +高域、とくに11.025kHzを超える成分では音質低下や折り返し雑音があり得る。 + +追加で、発音中のAPUイベント更新における周期関数呼び出しを減らす試作と、 +CPUの4 T-cycle更新を固定値で処理する試作を行った。前者の900フレーム +交互計測は元版15.33/15.44秒、試作15.67/15.38秒で改善が安定しなかった。 +後者は300フレームで差が小さく、900フレームでも改善を確認できず、 +どちらも取り消した。 + +## 18. Wizardry III の音切れ対策 (2026-09-26) + +ユーザー指定のWizardry III (GBC)を一時コピーで計測した。タイトル付近はCPUが +HALTしている時間が長く、従来の`CpuStep`はHALT中も4 CPU T-cycleごとに +Timer/PPU/APUの更新を呼んでいた。割り込みを起こし得るタイマーオーバー +フロー、PPUモード遷移、DMA、フレーム境界の手前まで、HALT中の時間を +`BusHaltTick`でまとめて進める。通常のTIMA加算はDIV位相から回数を計算し、 +オーバーフロー前の範囲に限って一括更新する。HALT以外の命令は従来の +`CpuStep`経路を使う。Rux Releaseのインライン化に依存しないよう、通常命令 +ループにHALT判定を追加せず、元からある`CpuStep`のHALT分岐に組み込んだ。 + +同じ一時セーブデータ、Windows x86-64 Release、headless、1800フレームで、 +旧版のCPU時間は約35.9秒、新版は27.6秒、壁時計は約31.0秒だった。 +1800フレーム後のBMPのSHA-256は旧版と新版で一致した。Dragon Quest IIIの +900フレームもBMPハッシュは一致したが、CPU時間は旧版15.56秒、新版 +15.97秒で、通常命令主体の場面では改善を確認できなかった。 + +実表示では音声ストリームの待機量が約2フレーム分を下回ると、次の画面の +スキャンライン描画とSDLへの画面提示を省く。PPUのモード、割り込み、 +ウィンドウ内部行数は進め、連続する画面の省略はしない。25秒間のWizardry III +表示実験で、旧版は約1320フレームに達し、発音後の待機量は約1.5KBだった。 +新版は約1440フレームに達し、発音後の待機量は約3~6KBを維持した。 +1020フレームまでに76回描画を省き、その後1440フレームまでは省略せず +再生した。音声の聴感は自動計測では検証できず、戦闘や長時間プレイの負荷も +未確認。 + +`Bus`テストで一括HALT更新と4 T-cycle更新をDMG/CGB倍速で比較し、 +タイマー、PPU、APUの主要状態の一致を確認した。画面を省いたラインの +ウィンドウ行数も比較した。Releaseの14テストパッケージは通過した。 +`CpuPerf`は長時間のベンチマークなので今回のテスト対象から除いた。 + +## 19. M4 Mac での Dragon Quest III の描画スキップ解消 (2026-10-05) + +結論: M4 ではエミュレーション本体は約6ms/フレームで処理能力は足りており、描画 +スキップの原因は音声キューの余裕不足だった。起動時の無音プリフィルと、macOS での +デバイスバッファ512サンプルフレーム指定で、60秒×3回の実表示でスキップ0になった。 + +### 計測 + +Release、ウィンドウ表示、操作なしで起動から60秒。フレームごとの時間を一時的な +計測コードで取った(計測コードは製品に含めない)。 + +| 項目 | 値 | +|---|---| +| エミュレーション本体 | 平均約6.0ms、最大7〜8ms | +| `VideoPresent` | 平均0.7〜11ms(時間帯で変動)、60フレーム中の最大は7〜13ms | +| ループ周期の最大 | ほぼ毎回32ms | +| フレーム開始時の音声キュー最小値 | 約3,840バイト(スキップ閾値2,936) | +| プロセスCPU時間 | 50秒中19.1秒 | + +CoreAudio は既定1024サンプルフレーム(約23ms)単位でストリームから引き取るため、 +キューは約2KBずつ段階的に減る。ペーシング目標5,872バイトから1回引き取られた +時点で閾値まで約900バイト(約10ms)しか残らず、画面提示の待ち(CPU処理ではなく +描画バッファ待ち)が重なると閾値を割る。修正前は起動直後に1〜2回、まれに途中でも +スキップした。 + +### 対策と結果 + +| 設定 | スキップ | フレーム開始時キュー最小値 | +|---|---:|---:| +| 修正前 | 2, 2(起動直後) | 3,828 | +| 無音プリフィルのみ | 0 | 3,828 | +| デバイス512のみ | 1(起動直後) | 4,852 | +| プリフィル+512 | 0, 0 | 4,852 | +| プリフィル+512、全10コアに `yes` で負荷 | 0 | 4,852 | + +各30〜45秒の計測。採用版の製品ビルドを60秒×3回実行し、アプリのログの +`skippedVideoFrames` は3回とも0、1秒目以降の `queuedBytes` 最小値は5,792〜6,044 +だった。デバイス512の指定は macOS 以外で未検証のため macOS に限定した。 + +| 不採用案 | 理由 | +|---|---| +| 音声投入を画面提示より前へ移す | 単独では改善が見えず(12章の Windows と同じ) | +| デバイス256 | 512と差がない | +| ペーシング目標を増やす | 遅延が増える。上記で足りた | + +10回の計測中2回、`VideoPresent` または本体が200〜350ms止まった(起動13〜17秒後)。 +OS側の停止とみられ、この長さはバッファでは吸収できない。この場合は従来どおり +描画スキップで追いつく。 + +### 最新 Rux (b682cc3a, 0.4.0) の試行 + +`d01b8c9` 以降704コミット。Release の最適化パスは定数畳み込み・コピー伝播・DCE・ +CFG整理のままで、インライン化は入っていない。配列・スライスの添字は全プロファイルで +境界検査されるようになった(生ポインタの添字は検査なし)。 + +| 項目 | 内容 | +|---|---| +| 必要なツール | Clang 23。mise の `github:llvm/llvm-project@llvmorg-23.1.2` を使用 | +| macOS での注意 | LLVM 同梱 libc++ を動的・静的にリンクしても、weak シンボルがシステムの libc++ と合体し `Manifest::Load` で double free する。`LDFLAGS="-nostdlib++ /lib/libc++.a /lib/libc++abi.a -Wl,-exported_symbol,_main"` で回避 | +| ソース移行 | `Slice` → `T[..]`、`MutableSlice` → `var T[..]`、`Slice{data:p,length:n}` → `p[..n]`。機械的置換で全パッケージが通った | +| 速度 | DQ3 headless 1800フレームの user 時間: 旧10.18/10.15秒、新9.83/9.82秒(約3.5%短縮) | +| 正確性 | 1800フレーム後の画面ハッシュ一致 | + +速度向上は小さく、ツールチェインと CI の更新を伴うため、今回は submodule を更新 +していない。 + +## 20. エミュレーション本体の高速化 (2026-10-05) + +結論: CPUアクセスごとに周辺機器を呼ぶ構造をやめ、次のイベント時刻まで同期を +遅らせる方式に変えた。命令ディスパッチの決定木化、ROM/WRAMの直接読み出し、描画の +分割・展開と合わせ、DQ3のコア処理は約2.6倍速(命令数は約1/3)になった。 + +### 計測方法 + +M4ではCPUの周波数とP/Eコアの割り当てが変わるため、`user`時間は同じバイナリでも +6〜8秒の幅で揺れた。`/usr/bin/time -l`の`instructions retired`(ほぼ決定的)を主指標、 +`cycles elapsed`を副指標にした。DQ3 headless 1800フレーム、各2回以上。プロファイルは +`sample`の結果を、x86-64向け`--emit asm`の関数順とAArch64バイナリの関数先頭 +(`mov x29, sp`)を突き合わせて関数名へ対応付けた(AArch64バイナリにシンボルが無いため)。 + +### 変更と効果 + +| 変更 | 命令数 (G) | サイクル (G) | +|---|---:|---:| +| 変更前 | 119.6 | 42.5 | +| 遅延同期(BusSync) | 90.4 | 32.6 | +| CpuExecuteを決定木化 | 66.4 | 25.6 | +| ROM窓・WRAM/HRAMの直接アクセス | 57.7 | 24.2 | +| CGBパレットのARGBキャッシュ | 54.9 | — | +| CpuRun(フレーム単位の実行ループ) | 52.1 | 19.8 | +| 走査線描画を3関数へ分割 | 49.3 | 19.5 | +| 色選択を表引きへ | 48.2 | 19.2 | +| 8ピクセル揃ったタイルを展開 | 45.6 | 18.1 | +| スプライトの無いラインでスクラッチ書き込みを省略 | 43.9 | 17.5〜18.1 | +| CpuRunからテスト用フラグ判定を除去 | 43.6 | — | + +「—」はP/Eコアの割り当てで値が大きく揺れた回。画面ハッシュは全段階で変更前と一致。 + +- **遅延同期**: CPUは`cycles`/`hwCycles`を進めて`syncAtHwCycles`と比べるだけにし、 + PPUモード境界・TIMAオーバーフロー・DMA中・TMAリロード中の時刻、またはI/O領域への + アクセス時に`BusSync`でTimer/PPU/DMAをまとめて進める。状態変化の起きるアクセスで + 同期するので、割り込みフラグが立つM-cycleは逐次更新と同じ。`PpuTick`は境界の間を + 一度に進め、`TimerTick`はオーバーフロー直前まで一括で進める。 +- **決定木**: オペコードを上位2bit(区画)・下位3bit(列)・中位3bit(行)で二分する。 + 以前の`opcode == 0xNN`連鎖は後方の命令で100回以上比較していた。 +- **ROM窓**: `Cartridge.romLow/romHigh`にバンクの先頭を持ち、バンク切替と保存状態の + 復元時に更新する。`CpuRead8`はROM・WRAM・HRAMを`BusRead`→`BusReadRaw`→`MbcRead`/ + `WramLocate`を通さずに読む。 +- **CpuRun**: 非HALT・EI遅延なしのときは割り込み判定とROMからの命令フェッチを + ループ内で行い、それ以外は`CpuStep`に任せる。アプリと、Blargg・acid2のテストが使う。 + +### Rux Release の生成コードについて分かったこと + +- 一時値と引数はすべてスタックに置かれ、引数はさらにローカルへコピーされる。 + `bus.cycles`のようなフィールドアクセス1回が約10命令になる。 +- フレームが4KBを超えると、超えた位置のバイト読み書きはアドレス計算で1回3命令に + なる。旧`PpuRenderScanline`は約7KBあった。 +- 構造体内の`union`フィールドは8バイト境界に置かれる(`Cpu.af`と`Cpu.bc`の間隔が8)。 + +関数呼び出しより式の数が支配的で、呼び出しを手で展開しても命令数は減らなかった。 + +| 不採用案 | 理由 | +|---|---| +| R8Get/R8Set・ALU・即値フェッチの呼び出しを全展開 | 命令数45.6G→45.7Gで効果なし、可読性が大きく下がる | +| レジスタをバイトポインタ+添字表で読み書き | 上記のunion配置に依存し、コンパイラ更新で壊れうる | +| `bus.cycles`を同期時だけ更新 | 見込み1〜2%に対し、テストと保存状態の意味が変わる | + +### ウィンドウ表示での確認 + +M4、DQ3、45秒。`instructions retired`は177.9G→65.1G、`cycles elapsed`は63.9G→ +37.6G。`user`時間は18.5秒→17.2秒とほとんど変わらなかった。負荷が下がるとmacOSが +低いクロックやEコアで動かすためで、M4のCPU時間・使用率は仕事量の指標にならない。 +`skippedVideoFrames`は0。 + +Windows/Linuxはクロスビルドの成功のみ確認した。x86-64での速度は未計測 +(このMacにRosetta 2とx86-64版SDL3が無い)。以前のWindows実機ではDQ3が +約19ms/フレームだったため、同じ比率で縮めば約7ms/フレームになる計算だが、 +x86-64の生成コードで同じ比率になるかは確かめていない。 + +## 21. Windows での Dragon Quest III の起動直後の描画スキップ (2026-10-05) + +結論: Windows(Ryzen 5 2600、GTX 1660、59Hz表示)でもエミュレーション本体は +2〜7ms/フレームで足りていた。`skippedVideoFrames`の1〜2は起動直後の1秒以内に +集中しており、D3D11 でウィンドウを表示した直後の4〜5回目の`SDL_RenderPresent` +が31ms+43msかかって無音プリフィル(約66ms)を使い切るのが原因だった。音声の +再生開始前に黒画面を10回提示して、この待ちを先に済ませるようにした。 + +| 条件 | 起動直後のスキップ | +|---|---| +| 修正前、direct3d11(既定) | 2, 1, 2 | +| 修正前、direct3d(D3D9) | 0 | +| 空提示10回、direct3d11 | 0 ×5回 | + +採用版で60秒×3回を実行し、3回とも`skippedVideoFrames=0`だった。定常時は +`SDL_RenderPresent`が12〜14ms待ち(表示のリフレッシュで律速)、`AudioPace`は +待っていない。 + +`--headless`(非表示ウィンドウ)では direct3d11/direct3d12/opengl の提示が約59Hzに +律速され、軽いROMでも1800フレームに約30.5秒かかる(direct3d では約5.8秒)。 +Windows で headless の実行時間をベンチマークに使うときは`SDL_RENDER_DRIVER=direct3d` +を付けるか、命令数など別の指標を使う。 diff --git a/scripts/build_macos.sh b/scripts/build_macos.sh index 94607b5..07319d0 100755 --- a/scripts/build_macos.sh +++ b/scripts/build_macos.sh @@ -24,7 +24,8 @@ case "${1:-}" in *) echo "usage: $0 [--debug|--release]" >&2; exit 2 ;; esac -if ! sdl_prefix=$(pkg-config --variable=prefix sdl3 2>/dev/null); then +if ! sdl_prefix=$(pkg-config --variable=prefix sdl3 2>/dev/null) && + ! sdl_prefix=$(brew --prefix sdl3 2>/dev/null); then echo "SDL3 が見つからない。'brew install sdl3' などで導入してください。" >&2 exit 1 fi diff --git a/scripts/test.sh b/scripts/test.sh index 6345477..7f33d20 100644 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -40,6 +40,10 @@ echo "=== Running ApuTest ===" (cd "$dir/Tests/Packages/Core/Apu" && "$rux" run ${1:+"$1"}) echo "ApuTest: OK" +echo "=== Running ApuBatchTest ===" +(cd "$dir/Tests/Packages/Core/ApuBatch" && "$rux" run ${1:+"$1"}) +echo "ApuBatchTest: OK" + echo "=== Running DmgSoundTest ===" (cd "$dir/Tests/Packages/Core/DmgSound" && "$rux" run ${1:+"$1"}) @@ -53,6 +57,10 @@ echo "=== Running CgbTest ===" (cd "$dir/Tests/Packages/Core/Cgb" && "$rux" run ${1:+"$1"}) echo "CgbTest: OK" +echo "=== Running PpuTilesTest ===" +(cd "$dir/Tests/Packages/Core/PpuTiles" && "$rux" run ${1:+"$1"}) +echo "PpuTilesTest: OK" + echo "=== Running Acid2Test ===" (cd "$dir/Tests/Packages/Core/Acid2" && "$rux" run ${1:+"$1"})