66 Commits
Author SHA1 Message Date
boubou666 02a590f184 Merge pull request #72 from TheBozos/release/v0.7.0
Release 0.7.0
2026-12-01 14:07:44 +01:00
Thomas MartinandClaude Opus 5.5 1234cf4f0f Release 0.7.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 14:04:45 +01:00
boubou666 8a9cf7781d Merge pull request #71 from TheBozos/dc/language
Game language: French, German, Italian from the disc's own translations
2026-12-01 14:02:54 +01:00
Thomas MartinandClaude Opus 5.5 767b3e9557 Options -> Language in the game
A Language entry in the game's own Options (between Travel and Quit
Game): English, Francais, Deutsch, Italiano, the one in use and the one
saved for the next start marked. Cross writes game.ini (as the launcher
does); the running game keeps its language until it starts again, since
part of its text is loaded once at boot. Without the game window
(headless) the page only says it needs it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 13:58:16 +01:00
Thomas MartinandClaude Opus 5.5 851b6244d7 Launcher: Game language beside Resolution, "Français" fixed
The row of its own pushed the Settings card past the window's bottom at
the default size; beside Resolution it costs no height. The label's
ç was written as two characters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 13:35:54 +01:00
Thomas MartinandClaude Opus 5.5 95903df0c9 Add a game language setting: French, German, Italian
The USA disc also carries the European release's translations of the
text (message files <name>_<n>.mes) and menus (commenu/a_fre, a_ger,
a_ita), and the program still picks them by LanguageCode (0x2A1E88,
1 on the USA disc). The port sets it before the first frame from
--language en|fr|de|it or <user folder>/game.ini, which the launcher's
Settings -> Game language and RecompLauncher's Language write.

Spanish is not offered: the USA disc lacks 42 of its 90 story text
files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 13:32:55 +01:00
Thomas MartinandClaude Opus 5.5 6481ee4cb4 Engine fetch: the unpacked release's files dated now
cmake/bozo_engine_fetch.cmake unpacked the pinned BozoEngine release with the
archive's own file dates, older than objects already built. After a pin bump
Ninja then kept port objects compiled against the previous release's headers
(found in Shinobido_WOTN_Recomp, 0.7.0 -> 0.7.3: shino_gs_state.cpp and
shino_render.cpp stayed on the old renderer.h, the picture lost its objects and
HUD while the game state was identical). Every unpacked file is now touched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 12:31:22 +01:00
boubou666 112cf4152f Merge pull request #70 from TheBozos/release/v0.6.1
Release 0.6.1
2026-12-01 01:32:23 +01:00
Thomas MartinandClaude Opus 5.5 98b2b54de7 Release 0.6.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:28:39 +01:00
boubou666 538902b3c0 Merge pull request #69 from TheBozos/dc/game-log
Write the game's log and crash reports
2026-12-01 01:28:22 +01:00
Thomas MartinandClaude Opus 5.5 07ac1d561f Write the game's log and crash reports
dc_main.cpp now calls bozo::app::startLogging() and installCrashHandler()
after setIdentity, as TMB's window does. Neither ran before, so
<user folder>/logs (DC Launcher's "Open game logs", RecompLauncher's Logs
in recompdata) and crashes/ stayed empty. Found by Amplitude's session.

Checked: a hidden, muted 300-frame run with its own PS2X_USER_DIR writes
logs/DC_Recomp.log (83 lines: the header and all 82 lines it printed), and
the pipe still gets all 82; the port's suites pass (139/139).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 01:25:30 +01:00
boubou666 e61fb960e3 Merge pull request #68 from TheBozos/release/v0.6.0
Release 0.6.0
2026-12-01 00:40:14 +01:00
Thomas MartinandClaude Opus 5.5 1f967b5c75 Release 0.6.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 00:37:08 +01:00
boubou666 357135cb0a Merge pull request #67 from TheBozos/dc/recomplauncher
Support RecompLauncher: ship recomplauncher.json
2026-12-01 00:33:56 +01:00
Thomas MartinandClaude Opus 5.5 c90df9d710 Support RecompLauncher: ship recomplauncher.json (#63)
recomplauncher.json at the repo's top, shipped at the release zip's top
(make_release, audited): the disc check (SCUS_971.11, SCUS-97111, Redump's
USA dump), prepare = the kit's Python running dc_build.py with
--progress-lines, start = game/dc.exe with PS2X_USER_DIR={data}, the
video.ini settings, the memory cards as saves.

dc_build: --progress-lines prints RecompLauncher's "progress <0-1> <text>"
lines (steps weighted as the launcher's), "progress 1 Already built" when
nothing ran; --disc defaults to the disc.iso an earlier build kept
(keeps_copy).

Checked end to end on the 0.5.2 zip with these files laid over it, run as
RecompLauncher runs them: first setup 394 s, setup again "Already built",
play 600 frames hidden with its data in recompdata, setup with the copy gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 00:28:42 +01:00
boubou666 13526ac41e Merge pull request #66 from TheBozos/dc/engine-release
Build on BozoEngine's releases instead of the submodule
2026-12-01 00:25:44 +01:00
Thomas MartinandClaude Opus 5.5 44e53f9833 Build on BozoEngine's releases instead of the submodule
cmake/bozo_engine.json pins BozoEngine 0.5.0 (the release of c27ce41, the
commit the submodule pinned) and the SHA-256 of its archive, hashed here.
cmake/bozo_engine_fetch.cmake (TMB_Recomp's, as in TMB_Recomp#121)
downloads it into BozoEngine/ once (TLS, hash checked), stamps
BozoEngine/.release, and refuses an unstamped BozoEngine/ (an old
submodule checkout). CMakeLists.txt, launcher/ and
tests/native_lifetime/ include it unless BOZO_ENGINE_DIR /
LAUNCHER_BOZO_DIR name another tree; the pin reconfigures the build.

dc_build fetches it in a git checkout; make_release puts the fetched tree
(with its stamp) in source\BozoEngine and records engine_version; scripts/
and CI fetch it; the pin test replaces the submodule test. The submodule,
.gitmodules and .git/modules/BozoEngine are gone; /BozoEngine/ is ignored.

Proved: a clean clone (no BozoEngine/) built with dc_build, and main's
submodule build, ran 3000 frames headless with the same pad script:
ref_compare identical on every field (ram, scratchpad, calls, draws,
sound, threads, eeCycle).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 00:08:56 +01:00
boubou666 914284e90e Merge pull request #62 from TheBozos/release/v0.5.2
Release 0.5.2
2026-11-30 16:57:38 +01:00
Thomas MartinandClaude Opus 5.5 ed49582da9 Release 0.5.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 16:54:36 +01:00
boubou666 57e0ed663f Merge pull request #61 from TheBozos/dc/update-times
Prepare after an unzipped update; add the missing update installer
2026-11-30 16:54:21 +01:00
Thomas MartinandClaude Opus 5.5 65d399ffa6 Prepare after an unzipped update; add the missing update installer
Issue #60: a release zip dates every file at its commit's UTC time, which an unzip reads as local time. West of
UTC, within hours of the commit, the source and the kit land in the future and ninja never settles ("manifest
'build.ninja' still dirty after 100 tries"). Fixed dates also let an update unzipped over a newer build keep its
changed files older than their objects, so they would not be compiled again.

dc_build.py now settles the times before building (release folders only): the kit comes back from the future
(CMake's own modules are build.ninja's inputs), and the source and the kit's FetchContent sources are compared with
build/source_times.json (size, time, SHA-1): changed or new files are dated now, unchanged ones get their time back.
Without the record over an earlier build everything is dated now, so the first Prepare after this rebuilds once.

The launcher's Update button runs source/tools/apply_update.py, which no release ever had. Ported from TMB_Recomp
with DC's names (DC_Recomp_Bozo/, DC Launcher.exe, .dc-old as the launcher's cleanup expects).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 16:32:19 +01:00
boubou666 96da183591 Merge pull request #59 from TheBozos/release/v0.5.1
Release 0.5.1
2026-11-30 09:28:02 +01:00
Thomas MartinandClaude Opus 5.5 fccc458694 Release 0.5.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 09:23:49 +01:00
boubou666 01433f480f Merge pull request #58 from TheBozos/dc/wide-culling
Widescreen: stop culling models outside the 4:3 frame
2026-11-30 09:18:55 +01:00
Thomas MartinandClaude Opus 5.5 e596e3e056 Widescreen: stop culling models outside the 4:3 frame
CFrameVu1::DrawVu1 skips a model whose projected bounding box lies wholly
more than 320 px from the screen centre, the 4:3 half width. In 16:9 the
frame reaches 426.67 px each side, so models in the extra strips vanished
until they crossed into the 4:3 area.

Its two loads of 320.0 (0x129ab4, 0x129ae4) become guarded native sites
returning the drawn frame's half width: 426.67 in widescreen, 320 in 4:3
(the same constant as before, so 4:3 is unchanged).

Checked headless from a Wise Owl Forest save state while turning the camera:
the old and new bounds give identical centres in all 39 frames, and the
differences lie only in the side strips, where plants and rocks now show.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 01:26:17 +01:00
boubou666 97b15a717e Merge pull request #57 from TheBozos/dc/release-utf8
Release tool: UTF-8 output
2026-11-28 20:07:32 +01:00
Thomas MartinandClaude Opus 5.5 8889dbb724 Release tool: UTF-8 output (the 0.5.0 notes carry an arrow)
The release workflow's changelog check printed the 0.5.0 section through the console's code page (cp1252 on the
Windows runner), which cannot encode the notes' arrow (Options -> Travel), and stopped before the build. The tool's
stdout and stderr are UTF-8 now; --check-changelog --version 0.5.0 prints the section and the release-tool tests
pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-28 19:57:11 +01:00
boubou666 135a95d76c Merge pull request #56 from TheBozos/release/v0.5.0
Release 0.5.0
2026-11-28 19:37:01 +01:00
Thomas MartinandClaude Opus 5.5 0fa612582e Release 0.5.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-28 19:33:11 +01:00
boubou666 97617b7afd Merge pull request #55 from TheBozos/dc/check-tools
Script checks: allies, the cleared save, the post-game; where and townevent
2026-11-28 19:24:14 +01:00
Thomas MartinandClaude Opus 5.5 daaf0642c1 Script checks: where shows the active character, monster HP and the post-game; townevent
where (and peek) now also report the game-cleared mark (GameClearFlag / the save's config), the Demon Shaft's
visit counter and, in a dungeon, the active character and each monster's HP: what the ally and post-game checks
read. townevent <n> runs a town or area map's own event through the game's RunEvent (0x1779F0).

Checked with them, headless, real input:
- Every ally switched in by the game's own quick change (Select, Right, Cross) and attacking (Cross): Toan,
  Osmond, Ungaga, Ruby, Goro and Xiao each took HP off floor monsters, kills included.
- The cleared save from the scripted playthrough: the title reads the cleared mark; after a Dark Heaven Castle
  visit, the town menu's Go to other area (World Map item) runs the game's own unlock (Demon Shaft visits 0 -> 1),
  and choosing the Demon Shaft on the map brings Toan to its entrance (map 60).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-28 19:18:21 +01:00
boubou666 8dfa1f69c6 Merge pull request #54 from TheBozos/dc/playthrough
The whole story by script: every boss beaten, the ending, the cleared save
2026-11-28 18:44:18 +01:00
Thomas MartinandClaude Opus 5.5 ce43fadc87 The whole story by script: every boss beaten, the ending, the cleared save
docs/playthrough.cheat plays Dark Cloud from an early Norune save to the ending, headless: each chapter's allies
join (party), each boss's fight starts from its own trigger where the dungeon has one (event 500; event 403 for
King's Curse, after the signet doors' flags), each boss is defeated through the game's own death path (kill), and
each defeat scene sets the story by itself (until): the chapter counter 100, flag 34, 300, 400, 500, flag 41, then
the ending, the credits and the game's own "save cleared data" (press). Run twice, each milestone within about 50
frames of the other run; the card's save file changes. Pendragon (Demon Shaft floor 100, post-game) falls the same
way: the counter reaches 700.

New script commands:
- kill: every live monster defeated by CMonstorUnit::CheckDmg's poison tick (countdown 1, strength past the HP):
  below 1 HP it is the game's death as from a blow, the kill counted and a boss's defeat scene run. (Writing 0 HP
  skips that death: the boss stays.) It waits for a dungeon's free play with a live monster.
- event <n> [reload]: a dungeon system event as the game's triggers start it; reload 1 (the default) resets the
  read buffers first, without which a boss's start ran out of its character buffer.
- party <n>, item <n> [count], press <buttons> <frames> (in turn), until intflag <n> <v> / until flag <n>.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-28 17:36:58 +01:00
boubou666 8dcf830c98 Merge pull request #53 from TheBozos/dc/widescreen
Widescreen with the HUD at the edges, and Travel: warps, georama, story chapters
2026-11-28 16:47:34 +01:00
Thomas MartinandClaude Opus 5.5 ba2f632589 Widescreen with the HUD at the edges, and Travel: warps, georama, story chapters
Widescreen (the Video tab, the in-game Graphics page, video.ini, PS2X_WIDESCREEN; hidden runs read only the
environment): the native frame is 853.33 GS pixels wide about the game's centre. The game's projection is
unchanged (Hor+); MGClipVertex is native and culls against the frame's width. The game's 2D stays centred; a
draw over the whole frame (fades, fills, frame copies) spans the wider one, a fill touching an edge reaches it
(the dungeon fade's tiles), and the field HUD's side pieces move to the edges (the town clock, the dungeon's
status, floor and gauge, the minimap as one piece). Frame copies take each side on its own, so the game's
half-size work copies round-trip.

Travel (Options -> Travel, F2 -> Travel, --cheat-script): warps to the 52 town and area maps and to any floor
of the seven dungeons through the game's own fades and loads (MapJump, the town exit, the interior loop's map
jump, the dungeon's exit task and floor build, the entrance menu's preset), next to the floor's monsters,
every georama part (the Atla tables through AtraPartsGet/AtraChipGet), the whole world map and a story chapter
select. A dungeon's story floors need its chapter's allies; ahead of the story the warp says so.

The in-game Graphics page also sets widescreen, anti-aliasing and texture smoothing. BozoEngine moves to
master c27ce41 (the widescreen setting and picture shape).

Checked headless: 139/139 suites; the 4:3 routes keep identical cards; tours of every town map and every
dungeon floor (208) in widescreen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-28 16:00:18 +01:00
boubou666 5c299d714f Merge pull request #52 from TheBozos/release/v0.4.0
Release 0.4.0
2026-11-24 14:24:09 +01:00
Thomas MartinandClaude Opus 5.5 a043405eab Release 0.4.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 14:21:10 +01:00
boubou666 37166934e9 Merge pull request #51 from TheBozos/dc/msaa-shadows
Shadows under anti-aliasing: the marks moved toward the camera
2026-11-24 11:23:15 +01:00
Thomas MartinandClaude Opus 5.5 fcfa1a580b Pin BozoEngine to master d04e9d8 (#135 merged)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 11:18:06 +01:00
Thomas MartinandClaude Opus 5.5 4d4e633ded Shadows under anti-aliasing: the marks moved toward the camera
With anti-aliasing the shadow work target's shared depth is resolved from one sample point off each
pixel's centre; on sloping ground that lies nearer than the mark's centre depth and every mark failed
the depth test, so the character shadows vanished (4x). Under anti-aliasing the marks now take
Material::depthOffset (slope 1, units 1); without it nothing changes.

BozoEngine: local branch dc/msaa-decal-offset (8ee365b), not pushed yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 10:51:44 +01:00
boubou666 b186560a21 Merge pull request #50 from TheBozos/dc/hidden-captures
BozoEngine master 36991be: hidden test runs, one fast forward
2026-11-24 10:51:04 +01:00
Thomas MartinandClaude Opus 5.5 15ef14bb8b Pin BozoEngine to master 36991be (save states written by older engines load)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 10:31:23 +01:00
Thomas MartinandClaude Opus 5.5 a51e17510a BozoEngine master e15775a: hidden test runs, one fast forward
- BozoEngine 6cf6faf -> e15775a (master, with the ps2f/VU0 smallest-normal fix #131).
- dc --hidden: the window is never shown and no sound device opens; --capture-frame reads the
  game's offscreen picture. --mute alone runs without a sound device.
- Fast forward is the engine's: its FastForward binding (` or the touchpad, Controls tab) at the
  Video tab's speed. DC no longer reads those keys, so the two never stack (3x x 3x before).
  "Fast-forward always on" stays, at the Video tab's speed; DC's own speed row and slider go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 01:14:35 +01:00
boubou666 25849df593 Merge pull request #49 from TheBozos/dc/readme-screenshots
README: refresh the screenshots from the current build
2026-11-23 15:09:20 +01:00
Thomas MartinandClaude Opus 5.5 67a4e61656 README: refresh the screenshots from the current build
Twelve captures from the current build (title, attract demo, Norune, Matataki,
town menu, load screen, cheats menu) replace the bring-up screenshots, as JPEG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 14:59:55 +01:00
boubou666 15aeeb7c37 Merge pull request #48 from TheBozos/dc/save-states
Save states: DC's section, command-line options and window slots
2026-11-18 22:16:41 +01:00
Thomas MartinandClaude Opus 5.5 83147e82a6 Pin BozoEngine to master 6cf6faf (save states merged via #104)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 22:13:01 +01:00
Thomas MartinandClaude Opus 5.5 dfc80d2af0 Save states: DC's section, command-line options and window slots
BozoEngine saves the runtime; DC's "dc" section (runtime/dc_state.cpp) adds
what that does not hold: the compiled sound modules' IOP host, the MDT copies
(the only model left once the game reuses a static piece's MDT memory) and
their bindings, pinned and patched pictures, GS place ownership, water
objects, frame identities, the haze seeds, the fishing strip and the native
Options pages. Images are written once in a table. On load the caches of the
old guest memory are dropped (decoded textures, render places, CLUT
overrides, shadow queues, the partial frame) and so are the cheats' mirrors
and queued edits. Unsaveable mid debug-font composition.

--save-state FILE --save-state-at N, --load-state FILE [--load-state-at N],
--dump-ram FILE; F5 / F7 / F6 slots and F2's Save states tab in the window.
Engine pinned to c853ec0 (BozoEngine #101) until the save-state commit is on
master.

Checked: headless Matataki (saved 6500) and dungeon (5000) states loaded in a
new process and mid-run give EE RAM identical to the uninterrupted runs;
windowed save + load gives identical captures at seven frames and identical
RAM. 135/135 suites, CI build 66/66, seven routes unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 20:42:32 +01:00
boubou666 a96c67d850 Merge pull request #47 from TheBozos/dc/water-after-menu
Town water: a place's rows follow every copy, not just the menu capture
2026-11-09 19:40:02 +01:00
Thomas MartinandClaude Opus 5.5 31b442693e Town water: a place's rows follow every copy, not just the menu capture
MGMoveFrameBuffImage (the menu's capture of both fields) marked its place 448
rows and nothing reset it; the town's water refracts that same place, which
its frame copies refill each frame at 224 rows. After the first menu, the
water sampled them at half height and showed the cliffs above it. The
stretch copy now marks its place 224 rows and the plain copy the source's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:37:08 +01:00
boubou666 b1541a5a67 Merge pull request #46 from TheBozos/dc/no-gs-library
sceGsSyncV and sceGsResetGraph answered by DC: no GS library call left
2026-11-09 17:52:42 +01:00
Thomas MartinandClaude Opus 5.5 66cd2b5f90 sceGsSyncV and sceGsResetGraph answered by DC: no GS library call left
sceGsSyncV keeps its meaning (the game waits for the next vblank and its
frame ends there): DC's override sets the same parity, then ends the frame
through the port, as DC's own frame boundary does. sceGsResetGraph only set
the field rate that is still used: DC's override sets it. The routes keep
their timeline (cheats-quit still quits at frame 9202, the attract demo is
frame-exact) and show no GS or DMA library call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:41:02 +01:00
boubou666 ea1ed845bb Merge pull request #45 from TheBozos/dc/native-draw-env
MGInit's draw environment native: no GS register images read
2026-11-09 17:27:39 +01:00
Thomas MartinandClaude Opus 5.5 a08c3283cd MGInit's draw environment native: no GS register images read
MGGetFBuffTex / MGGetFBuffBackTex hooks build the frame TEX0 words themselves
(640 wide, PSMCT32, FBP 0x46 / 0 by DBuffID: the values the record held),
and MGInit's loads of draw 0 TEST / ZBUF are native sites giving the same
values. MGInit's sceGsSetDefDBuff call is retired, so sceGsSetDefDrawEnv no
longer runs. GS library calls left: sceGsSyncV and sceGsResetGraph.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:17:01 +01:00
boubou666 3d3d37d935 Merge pull request #44 from TheBozos/dc/gs-dma-setup
Retire the remaining dead GS / DMA setup calls
2026-11-09 16:43:39 +01:00
Thomas MartinandClaude Opus 5.5 5b5c1f4256 Retire the remaining dead GS / DMA setup calls
A reader analysis of every live GS / DMA library call: the six sceDmaGetChan
lookups (same constants written in place), DevInit's DMA / GS resets, the
loading screen's sceGsSetDefDBuff, MGInit's two sceGsSetDefDispEnv halves
and the two live sceGsSyncPath calls have no live reader and are guarded
patches now. Kept: MGInit's sceGsSetDefDrawEnv halves (the native renderer
reads their FRAME / TEST / ZBUF images), sceGsResetGraph (field rate) and
sceGsSyncV (boot timeline). Span fixtures updated to the new expectations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:35:40 +01:00
boubou666 c844d22452 Merge pull request #43 from TheBozos/dc/libsdr-and-call-stats
libsdr's transport native; DC_CALL_STATS prints library calls by function
2026-11-09 16:06:49 +01:00
Thomas MartinandClaude Opus 5.5 473db2146d Pin BozoEngine to main 3bf62a6 (#79 merged; same tree as fba0920)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:01:26 +01:00
Thomas MartinandClaude Opus 5.5 1b1c3d8a9a libsdr's transport native; DC_CALL_STATS prints library calls by function
The engine's new FreeStats::libraryByName (BozoEngine #79, pinned at its
head fba0920) is printed with DC_CALL_STATS=1. It showed sceSifCallRpc still
called by libsdr's sceSdRemote (set_spu, CSound::SetReverb). sceSdRemoteInit,
sceSdTransToIOP and sceSdRemote's six library calls are guarded nops; the
native site is each delay slot, whose instruction the handler does first,
then the binding, RPC or transfer straight to the compiled module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:56:38 +01:00
boubou666 482abd9fc3 Merge pull request #42 from TheBozos/dc/native-cache-calls
Cache maintenance answered by DC: no EE kernel calls after boot
2026-11-09 15:26:52 +01:00
Thomas MartinandClaude Opus 5.5 35fcc4cdae Cache maintenance answered by DC: no EE kernel calls after boot
FlushCache, iFlushCache and iSyncDCache (the game's only live kernel calls:
MGEndFrame every frame, uploads, both vblank callbacks) are DC port
overrides returning 0; callers keep their calls and checkpoints, so EE time
is unchanged. The end-of-run report prints the host's kernel / library /
override call totals: kernel calls on a 9,000-frame route fall from 19,907
to 5 (boot). Documents the survey: the running game uses no threads,
semaphores or alarms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 14:43:40 +01:00
boubou666 ca778fe81e Merge pull request #41 from TheBozos/dc/native-sound-transport
Native sound transport: the game's sound calls reach the compiled driver without SIF
2026-11-09 14:31:33 +01:00
Thomas MartinandClaude Opus 5.5 b118d0a8ab CI build: link dc_sound.cpp wherever dc_port.cpp is
dc_port.cpp's native instructions now dispatch the sound sites; tests/native_lifetime (the CI build) lacked it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 14:29:14 +01:00
Thomas MartinandClaude Opus 5.5 320bc27f8d Native sound transport: the game's sound calls reach the compiled driver without SIF
ezMidiInit, ezMidi and ezTransToIOP stay the game's own code; their seven
library calls (sceSifInitRpc, sceSifBindRpc, two sceSifCallRpc, FlushCache,
sceSifSetDma, sceSifDmaStat) are guarded nops and native sites: the RPC goes
straight to the compiled sound module's handler, sample bytes straight into
its memory, with no SIF RPC, SIF DMA, DMA id or DMAC interrupt. Each site
charges its call's 8 EE cycles; the routines' spins stay, so the attract
demo stays frame-exact (replacing them whole drifted it).

Also drops an address from dc_pad.cpp's comment that the override scan
picked up as an (unregistered, harmless) override.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 14:15:09 +01:00
boubou666 f2ecd99cb3 Merge pull request #40 from TheBozos/dc/native-pad
Native controller: CGamePad reads the PC pad directly, libpad retired
2026-11-09 13:47:17 +01:00
Thomas MartinandClaude Opus 5.5 549c5753b7 Native controller: CGamePad reads the PC pad directly, libpad retired
read_pad (0x12A900) and Step (0x12B140) are native: each port's PAD_STATUS
comes from the engine's PadInput exactly as the original left it after its
libpad handshake (buttons as scePadRead's halfword arrived, sticks, ready
phase, DualShock 2 IDs, motor alignment), and Step's motor levels go to
player 1's rumble. Guarded patches retire CGamePad::Init's scePadInit and
scePadPortOpen calls; its sceGsSyncV waits stay (boot timeline).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:40:48 +01:00
96 changed files with 4216 additions and 243 deletions

No files matched your search

+2 -2
View File
@@ -7,8 +7,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: true
- name: The BozoEngine release cmake/bozo_engine.json pins (SHA-256 checked)
run: cmake -P cmake/bozo_engine_fetch.cmake
- name: Build the pinned native engine and synthetic fixtures
run: |
cmake -S tests/native_lifetime -B build/ci -G Ninja -DCMAKE_BUILD_TYPE=Release
+4 -2
View File
@@ -62,13 +62,15 @@ jobs:
fi
echo "WORK=$(cygpath -m "$RUNNER_TEMP")/dc" >> "$GITHUB_ENV"
- name: Check out the tag or the branch (and the BozoEngine submodule at its recorded commit)
- name: Check out the tag or the branch
uses: actions/checkout@v4
with:
ref: ${{ env.TAG != '' && format('refs/tags/{0}', env.TAG) || '' }}
submodules: true
persist-credentials: false
- name: The BozoEngine release cmake/bozo_engine.json pins (SHA-256 checked; the kit reads its library pins)
run: cmake -P cmake/bozo_engine_fetch.cmake
- name: Python
uses: actions/setup-python@v5
with:
+4
View File
@@ -17,6 +17,10 @@ SLUS_*
*.irx
*.IMG
# The BozoEngine release cmake/bozo_engine.json pins (cmake/bozo_engine_fetch.cmake)
/BozoEngine/
/.BozoEngine-unpack/
# Local build trees
build/
out/
-3
View File
@@ -1,3 +0,0 @@
[submodule "BozoEngine"]
path = BozoEngine
url = https://github.com/TheBozos/BozoEngine.git
Submodule BozoEngine deleted from 8a4ac058b9.
+76
View File
@@ -1,5 +1,81 @@
# Changelog
## [0.7.0] - 2026-12-01
### Added
- Game language: French, German and Italian ([#64](https://github.com/TheBozos/DC_Recomp/issues/64)). The USA disc also carries the European release's translations of the text and menus, and the game picks them by a language code it still has; the port sets it when the game starts, from the launcher's **Settings → Game language**, the game's **Options → Language** (applied at the next start), RecompLauncher's **Language** (all three write `game.ini` in the user folder) or `--language en|fr|de|it`. Spanish is not offered: the USA disc lacks about half of its story text.
### Fixed
- Building after an update that moves to a newer BozoEngine release compiles the port's files again: the engine's unpacked files took the archive's old dates, so the build could keep files compiled against the previous engine.
### Known limits
- Some European texts are longer than the boxes the USA layout gives them and run past their edge (the name entry's help).
- The Italian text names Circle for confirming in places (the name entry's help and its Yes/No); Cross confirms, as in the USA game.
## [0.6.1] - 2026-12-01
### Fixed
- The game now writes its log (`logs\` in its user folder: `%APPDATA%\DC_Recomp`, or RecompLauncher's `recompdata`), so the launcher's **Open game logs** and RecompLauncher's **Logs** show it, and a crash leaves a report in `crashes\`. Until now the game started neither, so both stayed empty.
## [0.6.0] - 2026-12-01
### Added
- RecompLauncher support: releases carry a `recomplauncher.json` ([#63](https://github.com/TheBozos/DC_Recomp/issues/63)). RecompLauncher checks the disc against the USA dump, prepares the game with the release's own build, starts it, shows the video settings (display mode, widescreen, frame rate, render scale, anti-aliasing, texture smoothing) on the game's page and backs up the memory cards. A game set up there keeps its saves, settings and logs in its `recompdata` folder.
- Preparing again without a disc image uses the one the earlier preparation kept in the game folder, so an update can be built after the original image was deleted.
### Changed
- BozoEngine comes from its releases instead of a git submodule: `cmake/bozo_engine.json` pins BozoEngine 0.5.0 (the same code as before, commit c27ce41) and the SHA-256 of its archive, which the build downloads once and checks. A release still carries the engine's source, so preparing the game stays offline.
## [0.5.2] - 2026-11-30
### Fixed
- Preparing a release unzipped over an earlier one no longer fails with "manifest 'build.ninja' still dirty after 100 tries" ([#60](https://github.com/TheBozos/DC_Recomp/issues/60)). The zip dates its files at the release's commit time, which an unzip west of UTC can place hours in the future; preparation now dates those files now. It also dates now every file that changed since the last preparation, so an update is always compiled in full even when its files are dated before the old build. The first preparation after this update builds everything again, once.
- The launcher's Update button installs the new release: the installer it runs (`tools/apply_update.py`) was missing from every release so far, so installs of 0.5.1 and earlier still need this one unzipped over them by hand.
## [0.5.1] - 2026-11-30
### Fixed
- Widescreen: models at the picture's sides (monsters, NPCs, plants, rocks, map pieces) no longer vanish outside the old 4:3 area. The game skipped any model lying wholly outside the 4:3 frame; that test now uses the frame actually drawn. 4:3 is unchanged.
## [0.5.0] - 2026-11-28
### Added
- Widescreen (Video tab, the in-game Graphics page, `widescreen = on` in `video.ini`): a 16:9 picture with more of the scene at the sides, nothing stretched; the HUD moves to the screen's edges (the town clock, the dungeon's status, floor and attack gauge, the minimap), menus and full-screen pictures stay centred, fades and backgrounds cover the whole width.
- The in-game Graphics page also sets widescreen, anti-aliasing and texture smoothing.
- Travel (Options → Travel, F2 → Travel): warp to any town or area, to any floor of any dungeon (boss floors included), next to the floor's monsters; every georama part, the whole world map, and a story chapter select. A story dungeon's floors ahead of its allies say which chapter to advance to first. See [the cheat reference](docs/CHEATS.md).
- `--cheat-script FILE`: travel, story and cheat commands by frame for scripted test runs, with dialogue read through (`talk 1`), the game's state logged (`where`: map, floor, chapter, party, the active character, the monsters' HP, the game-cleared mark) and a map's own events (`townevent`).
- The whole story by script: [docs/playthrough.cheat](docs/playthrough.cheat) beats every story boss (Dran, Master Utan, La Saia, King's Curse, Minotaur Joe, the Dark Genie) through the game's own fights and defeat scenes, plays the ending and the credits and saves the cleared game, headless. Script commands for it: `event`, `kill`, `party`, `item`, `press`, `until`.
### Changed
- BozoEngine moves to its current master (c27ce41): the widescreen setting and picture shape it needs, among other engine work.
### Known limits
- Gameplay testing covers, headless and by script: every town and area map, every dungeon floor (the Demon Shaft's 100 included), every story boss, the ending and the cleared save; every ally switched in and fighting with real input; the cleared save opening the Demon Shaft through the world map. A complete playthrough by hand, the allies' own join scenes and georama town building are unverified, as is full visual parity.
- A few areas warped to outside their story show an empty or dark view (s11, s12, s14, s38, s39, s96).
- Linux is not qualified.
## [0.4.0] - 2026-11-24
### Added
- Save states: F5 saves the game at any moment into one of ten slots, F7 loads it back (F6 / Shift+F6 pick the slot, F2 lists them); also `--save-state` / `--load-state` on the command line.
- Hidden test runs: `--hidden` runs the game silently without showing its window, and `--capture-frame` then reads the game's offscreen picture. `--mute` runs without a sound device.
### Fixed
- Character shadows no longer vanish with anti-aliasing on (Video tab).
- Town water no longer turns into a mirror of the cliffs after the menu has been opened.
### Changed
- The controller is read natively: the game's pad code takes the PC controller's state directly and sends rumble back to it, with no PS2 pad library in between.
- Sound commands, sound-hardware settings (volumes, reverb) and sample uploads go straight to the game's natively compiled sound drivers, with no PS2 SIF (EE-to-IOP) transfer layer in between.
- Fast forward is the engine's: hold **`** or a gamepad's touchpad (rebindable in the Controls tab) at the Video tab's speed, 2x to 10x or unlimited. The Cheats menu keeps **Fast-forward always on**, at that same speed; its own speed row is gone.
- BozoEngine moves to its current master (d04e9d8): anti-aliasing, texture smoothing, F12 screenshots, save-state pictures, rumble strength, pause in the background and the settings window from a gamepad.
- The game's PS2 cache-maintenance calls are answered natively instead of by the emulated console kernel: kernel calls during play drop to none after boot.
- Leftover PS2 graphics and DMA setup calls at boot, loading screens and mode changes are retired, the renderer no longer reads GS register images, and the vblank wait and video-mode setup are DC's own: the game calls no PS2 graphics library function.
### Known limits
- Gameplay testing covers the new-game opening, Norune, Divine Beast Cave, Matataki, Georama, saving and loading, and save states; a complete story playthrough and full visual parity are unverified.
- Linux and widescreen are not qualified.
## [0.3.0] - 2026-11-09
### Added
+52 -14
View File
@@ -9,7 +9,19 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)
option(DC_GUI_SUBSYSTEM "Build the Windows player without a console" OFF)
set(DC_GAME_DIR "${CMAKE_SOURCE_DIR}/game" CACHE PATH "User-owned extracted disc files")
set(BOZO_ENGINE_DIR "${CMAKE_SOURCE_DIR}/BozoEngine" CACHE PATH "Pinned native engine source")
# BozoEngine: the release cmake/bozo_engine.json pins, fetched into BozoEngine/ (cmake/bozo_engine_fetch.cmake), unless
# BOZO_ENGINE_DIR names another tree (development: a BozoEngine checkout).
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)")
set(dc_engine_given "")
if(BOZO_ENGINE_DIR)
file(REAL_PATH "${BOZO_ENGINE_DIR}" dc_engine_given)
endif()
file(REAL_PATH "${CMAKE_SOURCE_DIR}/BozoEngine" dc_engine_in_repo)
if(NOT BOZO_ENGINE_DIR OR dc_engine_given STREQUAL dc_engine_in_repo)
include("${CMAKE_SOURCE_DIR}/cmake/bozo_engine_fetch.cmake")
set(BOZO_ENGINE_DIR "${bozo_engine_tree}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/cmake/bozo_engine.json")
endif()
option(DC_WINDOW "Build the SDL3 native game window" ON)
option(DC_AUDIT_INDIRECT "Instrument generated register transfers for local audit traces" OFF)
set(BOZO_APP ${DC_WINDOW} CACHE BOOL "" FORCE)
@@ -40,7 +52,7 @@ add_custom_command(OUTPUT ${dc_externals} ${dc_overlay_externals}
COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/dc_bozo_externals.py ${dc_gen}/native_externals.txt ${dc_externals} ${dc_overlay_externals}
DEPENDS bozo-externals ${CMAKE_SOURCE_DIR}/tools/dc_bozo_externals.py ${CMAKE_SOURCE_DIR}/runtime/dc_native.cpp
${CMAKE_SOURCE_DIR}/runtime/dc_port.cpp ${CMAKE_SOURCE_DIR}/runtime/dc_cheats.cpp
${CMAKE_SOURCE_DIR}/runtime/dc_ingame_cheats.cpp ${DC_GAME_DIR}/SCUS_971.11)
${CMAKE_SOURCE_DIR}/runtime/dc_ingame_cheats.cpp ${CMAKE_SOURCE_DIR}/runtime/dc_warp.cpp ${CMAKE_SOURCE_DIR}/runtime/dc_pad.cpp ${CMAKE_SOURCE_DIR}/runtime/dc_sound.cpp ${DC_GAME_DIR}/SCUS_971.11)
set(dc_sources)
foreach(image dc title dun)
set(chunks 32)
@@ -92,10 +104,18 @@ endif()
target_compile_options(dc_game PRIVATE -O1 -w -ffp-contract=off)
add_library(dc_cheats STATIC runtime/dc_cheats.cpp)
target_link_libraries(dc_cheats PUBLIC bozo_host)
add_library(dc_warp STATIC runtime/dc_warp.cpp)
target_link_libraries(dc_warp PUBLIC dc_cheats dc_pad bozo_host)
add_library(dc_ingame_cheats STATIC runtime/dc_ingame_cheats.cpp)
target_link_libraries(dc_ingame_cheats PUBLIC dc_cheats bozo_host)
add_executable(dc-headless runtime/dc_main.cpp runtime/dc_port.cpp runtime/dc_native.cpp)
target_link_libraries(dc-headless PRIVATE dc_game bozo_host dc_cheats dc_ingame_cheats)
target_link_libraries(dc_ingame_cheats PUBLIC dc_cheats dc_warp dc_language bozo_host)
add_library(dc_pad STATIC runtime/dc_pad.cpp)
target_link_libraries(dc_pad PUBLIC bozo_host)
add_library(dc_language STATIC runtime/dc_language.cpp)
target_include_directories(dc_language PUBLIC ${CMAKE_SOURCE_DIR}/runtime)
add_library(dc_sound STATIC runtime/dc_sound.cpp)
target_link_libraries(dc_sound PUBLIC bozo_host)
add_executable(dc-headless runtime/dc_main.cpp runtime/dc_state.cpp runtime/dc_port.cpp runtime/dc_sound.cpp runtime/dc_native.cpp)
target_link_libraries(dc-headless PRIVATE dc_game bozo_host dc_cheats dc_ingame_cheats dc_warp dc_pad dc_language)
if(MINGW)
target_link_options(dc-headless PRIVATE -static)
endif()
@@ -129,8 +149,8 @@ target_include_directories(dc-headless PRIVATE ${dc_audio_gen})
add_dependencies(dc-headless dc_native_audio)
if(DC_WINDOW)
add_executable(dc runtime/dc_main.cpp runtime/dc_port.cpp runtime/dc_native.cpp runtime/dc_audio.cpp runtime/dc_cheats_ui.cpp $<TARGET_OBJECTS:dc_audio_code>)
target_link_libraries(dc PRIVATE dc_game bozo_host bozo_app dc_cheats dc_ingame_cheats)
add_executable(dc runtime/dc_main.cpp runtime/dc_state.cpp runtime/dc_port.cpp runtime/dc_sound.cpp runtime/dc_native.cpp runtime/dc_audio.cpp runtime/dc_cheats_ui.cpp $<TARGET_OBJECTS:dc_audio_code>)
target_link_libraries(dc PRIVATE dc_game bozo_host bozo_app dc_cheats dc_ingame_cheats dc_warp dc_pad dc_language)
if(WIN32)
enable_language(RC)
string(REPLACE "." "," DC_FILEVERSION "${PROJECT_VERSION}.0")
@@ -191,6 +211,24 @@ if(DC_ENGINE_TESTS)
target_link_options(dc-ingame-cheat-menu-tests PRIVATE -static)
endif()
add_test(NAME dc_native_ingame_cheats COMMAND dc-ingame-cheat-menu-tests)
add_executable(dc-pad-tests tests/dc_pad_tests.cpp)
target_link_libraries(dc-pad-tests PRIVATE dc_pad bozo_host)
if(MINGW)
target_link_options(dc-pad-tests PRIVATE -static)
endif()
add_test(NAME dc_native_pad COMMAND dc-pad-tests)
add_executable(dc-language-tests tests/dc_language_tests.cpp)
target_link_libraries(dc-language-tests PRIVATE dc_language)
if(MINGW)
target_link_options(dc-language-tests PRIVATE -static)
endif()
add_test(NAME dc_language COMMAND dc-language-tests)
add_executable(dc-sound-tests tests/dc_sound_tests.cpp)
target_link_libraries(dc-sound-tests PRIVATE dc_sound bozo_host)
if(MINGW)
target_link_options(dc-sound-tests PRIVATE -static)
endif()
add_test(NAME dc_native_sound_transport COMMAND dc-sound-tests)
add_executable(dc-cd-cancel-tests tests/dc_cd_cancel_tests.cpp)
target_link_libraries(dc-cd-cancel-tests PRIVATE dc_game bozo_host)
if(MINGW)
@@ -200,14 +238,14 @@ if(DC_ENGINE_TESTS)
set_tests_properties(dc_native_cd_cancel PROPERTIES TIMEOUT 15)
if(DC_WINDOW)
# Local diagnostic: the caller supplies a RAM capture; no assets are embedded.
add_executable(dc-sky-replay tools/dc_sky_replay.cpp runtime/dc_native.cpp runtime/dc_port.cpp)
add_executable(dc-sky-replay tools/dc_sky_replay.cpp runtime/dc_native.cpp runtime/dc_port.cpp runtime/dc_sound.cpp)
target_link_libraries(dc-sky-replay PRIVATE dc_game bozo_host bozo_app)
target_compile_definitions(dc-sky-replay PRIVATE DC_DEFAULT_TEXTURES="${dc_textures}")
if(MINGW)
target_link_options(dc-sky-replay PRIVATE -static)
endif()
endif()
add_executable(dc-native-tests tests/dc_native_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp)
add_executable(dc-native-tests tests/dc_native_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp runtime/dc_sound.cpp)
target_link_libraries(dc-native-tests PRIVATE bozo_host)
target_compile_definitions(dc-native-tests PRIVATE DC_DEFAULT_TEXTURES="")
if(MINGW)
@@ -241,14 +279,14 @@ if(DC_ENGINE_TESTS)
add_test(NAME dc_native_water_refraction_pixels COMMAND dc-water-refraction-tests --gpu)
set_tests_properties(dc_native_water_refraction_pixels PROPERTIES LABELS "gpu")
endif()
add_executable(dc-fishing-line-tests tests/dc_fishing_line_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp)
add_executable(dc-fishing-line-tests tests/dc_fishing_line_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp runtime/dc_sound.cpp)
target_link_libraries(dc-fishing-line-tests PRIVATE bozo_host)
target_compile_definitions(dc-fishing-line-tests PRIVATE DC_DEFAULT_TEXTURES="")
if(MINGW)
target_link_options(dc-fishing-line-tests PRIVATE -static)
endif()
add_test(NAME dc_native_fishing_line COMMAND dc-fishing-line-tests)
add_executable(dc-debug-font-tests tests/dc_debug_font_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp)
add_executable(dc-debug-font-tests tests/dc_debug_font_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp runtime/dc_sound.cpp)
target_link_libraries(dc-debug-font-tests PRIVATE bozo_host)
target_compile_definitions(dc-debug-font-tests PRIVATE DC_DEFAULT_TEXTURES="")
if(MINGW)
@@ -320,7 +358,7 @@ if(DC_ENGINE_TESTS)
COMMAND bozo-recomp ${dc_visibility_gen}/reference.elf ${dc_visibility_gen} --prefix dcvis
--symbol-prefix dcvis_ --files 1 --no-comments --externals ${dc_visibility_gen}/reference.externals
DEPENDS bozo-recomp tests/make_visibility_fixture.py ${DC_GAME_DIR}/SCUS_971.11)
add_executable(dc-visibility-tests tests/dc_visibility_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp
add_executable(dc-visibility-tests tests/dc_visibility_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp runtime/dc_sound.cpp
${dc_visibility_outputs})
target_link_libraries(dc-visibility-tests PRIVATE dc_game bozo_host)
target_include_directories(dc-visibility-tests PRIVATE runtime ${dc_visibility_gen})
@@ -377,7 +415,7 @@ if(DC_ENGINE_TESTS)
target_compile_definitions(dc-${kind}-wrapper-tests PRIVATE DC_DEFAULT_TEXTURES="")
endif()
if(kind STREQUAL "loading" OR kind STREQUAL "fishing" OR kind STREQUAL "debug_font")
target_sources(dc-${kind}-wrapper-tests PRIVATE runtime/dc_native.cpp runtime/dc_port.cpp)
target_sources(dc-${kind}-wrapper-tests PRIVATE runtime/dc_native.cpp runtime/dc_port.cpp runtime/dc_sound.cpp)
target_compile_definitions(dc-${kind}-wrapper-tests PRIVATE DC_DEFAULT_TEXTURES="")
endif()
target_link_libraries(dc-${kind}-wrapper-tests PRIVATE dc_game bozo_host)
@@ -453,7 +491,7 @@ if(DC_ENGINE_TESTS)
foreach(address 1dae2a0 1dc1510)
dc_overlay_packet_fixture(dun_${address} dun)
endforeach()
add_executable(dc-packet-audit-tests tests/dc_packet_audit_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp)
add_executable(dc-packet-audit-tests tests/dc_packet_audit_tests.cpp runtime/dc_native.cpp runtime/dc_port.cpp runtime/dc_sound.cpp)
target_link_libraries(dc-packet-audit-tests PRIVATE dc_game bozo_host)
target_compile_definitions(dc-packet-audit-tests PRIVATE DC_DEFAULT_TEXTURES="" DC_PACKET_AUDIT_GAME)
if(MINGW)
+1 -1
View File
@@ -24,7 +24,7 @@ SOFTWARE.
This licence covers DC_Recomp's own files. It does not cover:
- Git submodules, which have their own licences.
- BozoEngine/ (the recompiler and runtime, a separate MIT project, fetched from its releases): see BozoEngine/LICENSE.
- Anything from Dark Cloud, such as screenshots. No game data or code is in this repository;
players build the port from their own disc.
- Third-party components with their own licences.
+58 -27
View File
@@ -28,7 +28,7 @@ BozoEngine replaces the PS2Recomp fork completely; there is no emulation fallbac
## For players (Windows)
Download **`DC_Recomp-0.3.0-bozo.zip`** from [Releases](https://github.com/TheBozos/DC_Recomp/releases/latest),
Download **`DC_Recomp-0.7.0-bozo.zip`** from [Releases](https://github.com/TheBozos/DC_Recomp/releases/latest),
check its `.sha256`, and extract it to a writable folder such as `D:\Games\DC_Recomp_Bozo`.
Open **DC Launcher.exe**, select your own USA disc image (`.iso` or `.bin`/`.cue`), click **Prepare the game**,
then **Play**. Preparation runs locally with the bundled offline tools; no developer software is needed.
@@ -38,12 +38,18 @@ You need Windows 10 version 1903 or newer (or Windows 11), an AVX2/FMA CPU, Open
Only the unmodified `SCUS-97111` version 1.02 disc is supported; the executable and both overlays are verified.
The unsigned launcher may trigger Windows SmartScreen. Game files and generated game code are never distributed.
Use the launcher's **Settings** for display options, logs, maintenance and updates. **F2** opens the game's
Use the launcher's **Settings** for display options, the game's language, logs, maintenance and updates. **F2** opens the game's
settings. Saves, controls, video settings and cheats are stored in `%APPDATA%\DC_Recomp` and survive launcher
updates. Existing development saves are kept separately; copy only the desired card files into that directory.
The in-game pause menu includes **Graphics**, **Cheats** and **Quit Game**. Updates offer a rebuild when the source changes.
The in-game pause menu includes **Graphics** (widescreen, anti-aliasing and more), **Cheats**, **Travel** and **Quit Game**. Updates offer a rebuild when the source changes.
See [CHANGELOG.md](CHANGELOG.md) for release changes and the checked routes above for current coverage.
**RecompLauncher.** Releases carry a [`recomplauncher.json`](recomplauncher.json), so
[RecompLauncher](https://recomplauncher.com) can install DC_Recomp, check your disc, prepare the game with the
same build (its setup step), show the language and video settings on the game's page and back up the memory cards. A game
set up there keeps its saves, settings and logs in its own `recompdata` folder, not in `%APPDATA%\DC_Recomp`:
copy `mc0` across to bring saves from DC Launcher.
## Status
**Playable Windows port, under active gameplay testing.** Checked routes include Norune,
@@ -65,9 +71,12 @@ A complete story playthrough and full visual parity remain unverified.
| Controller-operated Graphics, Cheats and Quit Game inside Options; F2 settings remain available | ✅ |
| Georama and dungeon play on the current engine | ✅ |
| New-game opening on the current engine | 🔧 |
| Complete story, all companions, locations and effects | 🔧 |
| Scripted run of the whole story: every boss through the game's own fights and scenes, the ending, the cleared save ([docs/playthrough.cheat](docs/playthrough.cheat)) | ✅ |
| Complete story played by hand, all companions, locations and effects | 🔧 |
| Linux build | ⏳ |
| Widescreen | ⏳ |
| Widescreen, with the HUD at the screen's edges | ✅ |
| French, German and Italian text and menus, from the disc's own European translations | 🔧 |
| Travel: any town, area, dungeon floor and story chapter (cheats, scripted runs) | ✅ |
**Native port.** Models, textures, camera, lights and drawing routines feed native PC draws.
BozoEngine supplies the runtime, native SDK services, renderer and mixer.
@@ -102,25 +111,20 @@ and conditional dispatch audit; [docs/RECOMP_NOTES.md](docs/RECOMP_NOTES.md) rec
## Screenshots
Historical bring-up captures from before the native renderer and BozoEngine migration. They show the earlier
progress and are not evidence of the current build; current validation is in
[docs/NATIVE_RENDERING_FOLLOWUP.md](docs/NATIVE_RENDERING_FOLLOWUP.md).
Captured from the current build at 960x720.
| | | |
|---|---|---|
| ![The intro's castle](docs/screenshots/intro-castle.png) | ![The Dark Genie](docs/screenshots/genie.png) | ![The title menu](docs/screenshots/title-logo.png) |
| ![The desk narration](docs/screenshots/opening-desk.png) | ![In a dungeon](docs/screenshots/dungeon-scene.png) | ![Toan and the Fairy King](docs/screenshots/fairy-king.png) |
| ![Toan's house](docs/screenshots/toan-house.png) | ![The forest](docs/screenshots/forest-scene.png) | ![New game: the name entry](docs/screenshots/register-name.png) |
| ![The Dark Shrine](docs/screenshots/shrine-soldiers.png) | ![Colonel Flag](docs/screenshots/colonel-flag.png) | ![The urn](docs/screenshots/shrine-urn.png) |
| ![Opening dialogue](docs/screenshots/opening-dialogue.png) | ![The Dark Genie rises](docs/screenshots/genie-rises.png) | ![Norune at night](docs/screenshots/norune-night.png) |
| ![Toan at home](docs/screenshots/norune-house.png) | ![Norune's festival](docs/screenshots/norune-festival.png) | ![A cutscene dialogue](docs/screenshots/cutscene-balloon.png) |
| ![The title screen](docs/screenshots/title.jpg) | ![The attract demo: the castle](docs/screenshots/demo-castle.jpg) | ![The attract demo: Toan and the light](docs/screenshots/demo-light.jpg) |
| ![The attract demo: a serpent](docs/screenshots/demo-serpent.jpg) | ![The attract demo: the forest](docs/screenshots/demo-forest.jpg) | ![The attract demo: the crystals](docs/screenshots/demo-crystals.jpg) |
| ![Toan in Matataki](docs/screenshots/matataki.jpg) | ![Outside Norune](docs/screenshots/norune-outskirts.jpg) | ![Adventure Day 1, night](docs/screenshots/adventure-day.jpg) |
| ![The town menu](docs/screenshots/town-menu.jpg) | ![Loading a save](docs/screenshots/load-file.jpg) | ![The in-game cheats menu](docs/screenshots/cheats-menu.jpg) |
## Goal
A fully playable *Dark Cloud* as a native PC program, from the opening to the ending, drawing and playing
sound directly from the game's data. Accuracy and complete gameplay coverage come first; Linux,
widescreen and additional presentation options follow.
sound directly from the game's data. Accuracy and complete gameplay coverage come first; Linux and additional
presentation options follow.
## How it works
@@ -149,8 +153,13 @@ disc files (game/) ──► tools/dc_bozo_prepare.py ──► resident ELF + T
- The top-level build generates code and converts textures automatically, then links the windowed `dc` and
`dc-headless` runners. Game-derived output stays in the ignored build directory.
[BozoEngine](https://github.com/TheBozos/BozoEngine) is the sole engine submodule. Game-specific addresses, formats,
hook choices and module layouts stay in DC_Recomp; engine changes must be generic and reusable by other recompiles.
[BozoEngine](https://github.com/TheBozos/BozoEngine) is the sole engine. The build uses the BozoEngine release
`cmake/bozo_engine.json` pins (version and the SHA-256 of its archive): `cmake/bozo_engine_fetch.cmake` downloads it
into `BozoEngine/` once and checks the hash, and a release's `source\BozoEngine` carries it, so a player's build stays
offline. An engine bump changes that file to a newer release; engine work not released yet is built on a local
BozoEngine checkout with `-DBOZO_ENGINE_DIR=<it>` (or `tools/dc_build.py --engine <it>`, `BOZO_ENGINE_DIR=<it>` for
`scripts/`), never by pinning a commit. Game-specific addresses, formats, hook choices and module layouts stay in
DC_Recomp; engine changes must be generic and reusable by other recompiles.
## Requirements
@@ -180,8 +189,9 @@ With an extracted release, use `kit/python/python.exe -I -X utf8 source/tools/dc
### Developer build and regression suites
```bash
git clone --recurse-submodules https://github.com/TheBozos/DC_Recomp.git
git clone https://github.com/TheBozos/DC_Recomp.git
cd DC_Recomp
cmake -P cmake/bozo_engine_fetch.cmake # the pinned BozoEngine release into BozoEngine/ (configure does it too)
scripts/extract_iso.sh "/path/to/Dark Cloud (USA).iso"
scripts/bench_run.sh --alone 20 "native build" scripts/build_runtime.sh Release \
-DDC_ISO="D:/path/to/Dark Cloud (USA).iso"
@@ -211,10 +221,17 @@ pacman -S --needed mingw-w64-ucrt-x86_64-{gcc,cmake,ninja,pkgconf,ffmpeg,libarch
`--fullscreen` starts fullscreen; `--no-vsync` disables VSync for comparisons. The default is windowed
with VSync enabled. **F8** captures a frame when a capture directory is configured.
The game's **Options** entry page offers **Game Options** (the original settings), **Graphics**, **Cheats**, and
**Quit Game**. Up/Down selects rows, Cross confirms and Circle goes back. **Graphics** sets the display mode,
resolution, render scale and frame rate; **Apply and save** writes them to `video.ini` (shared with the launcher's
Settings and **F2 → Video**). Quit Game asks for confirmation,
**Save states:** **F5** saves the whole game at that moment into the selected slot, **F7** loads it back, **F6** /
**Shift+F6** choose the slot (0–9); **F2 → Save states** shows them. A state belongs to the build that made it: after
an update, use the game's own memory-card saves. `--save-state FILE --save-state-at FRAME` and
`--load-state FILE [--load-state-at FRAME]` do the same from the command line.
The game's **Options** entry page offers **Game Options** (the original settings), **Graphics**, **Cheats**,
**Travel**, **Language** and **Quit Game**. Up/Down selects rows, Cross confirms and Circle goes back. **Graphics** sets the display
mode, resolution, render scale, frame rate, widescreen, anti-aliasing and texture smoothing; **Apply and save** writes
them to `video.ini` (shared with the launcher's Settings and **F2 → Video**). **Widescreen** shows a 16:9 picture
with more of the scene at the sides; the HUD moves to the screen's edges while menus and full-screen pictures stay
centred. Quit Game asks for confirmation,
with Cancel selected initially. Save through the game's normal save menu before quitting to keep progress;
quitting does not autosave.
@@ -244,6 +261,17 @@ Those edits apply when Options closes or gameplay resumes, and become part of a
afterward. Toggle/multiplier settings are session-only: each launch starts with toggles off,
ABS at 1× and movement at 100%. See [the cheat reference](docs/CHEATS.md) for limits and validation.
**Travel** (**Options → Travel** or **F2 → Travel**) warps to any town or area, to any floor of any dungeon
(boss floors included) and next to the floor's monsters; it also unlocks every georama part, opens the whole world
map and advances the story to a chosen chapter. Each request waits until you walk freely, then goes through the
game's own fade and loading. Save before advancing the story: it is meant for testing.
**Language.** The USA disc also carries the European release's French, German and Italian text and menus, and its
program still picks them by a language code. The launcher's **Settings → Game language**, the game's own
**Options → Language** and RecompLauncher's **Language** write `language = en`, `fr`, `de` or `it` to `game.ini` in
the user folder; the game reads it when it starts, so a change made in the game applies at its next start. `--language fr` does the same for one run. Spanish is not offered: the USA disc lacks about half its story
text. Some European texts are longer than their English boxes (the name entry's help, for one) and run past them.
### Memory cards and data paths
The windowed runner uses BozoEngine's per-user memory-card directory. Existing `game/mc0` saves migrate
@@ -274,7 +302,10 @@ CI uses game-free engine fixtures and offline-tool checks; retail-route tests re
`--frames 0` runs until shutdown; `--frames N` bounds a run. `--wav <file>` records sound.
`--pad-script <file>` accepts entries such as `1200:START/6,1500:CROSS/6`; `--live-pad <file>` reloads
changed input text relative to the current frame. `--capture-dir` and repeatable `--capture-frame`
select native captures. `--profile-io` reports device-register accesses after a bounded run.
select native captures. `--hidden` never shows the window and plays no sound: captures then read the game's offscreen picture, so a
scripted run needs no visible window. `--mute` alone runs without a sound device. `--cheat-script <file>` drives
Travel, story and cheat commands by frame (`3400 dungeon 0 15`, `talk 1` to read through dialogue, `where` to log
the state; see [the cheat reference](docs/CHEATS.md)). `--profile-io` reports device-register accesses after a bounded run.
Normal play leaves expensive diagnostic recording disabled.
Recent results live in [NATIVE_RENDERING_FOLLOWUP.md](docs/NATIVE_RENDERING_FOLLOWUP.md).
@@ -292,7 +323,7 @@ licences and corresponding toolchain sources, and audits the archives for game d
```bash
python tools/make_build_kit.py --out D:/dc_kit/kit
scripts/bench_run.sh --alone 20 "release package" python tools/make_release.py \
--version 0.3.0 --kit D:/dc_kit/kit --out D:/dc_release --with-sources
--version 0.7.0 --kit D:/dc_kit/kit --out D:/dc_release --with-sources
```
Only committed source is exported. Follow [the release checklist](docs/RELEASE_CHECKLIST.md) before publishing;
@@ -326,7 +357,7 @@ scripts/bench_run.sh --alone 20 "runner build" scripts/build_runtime.sh
| Path | Contents |
|---|---|
| `BozoEngine/` | Sole engine submodule: native recompiler/runtime |
| `BozoEngine/` | The pinned BozoEngine release (`cmake/bozo_engine.json`, fetched, not in git): native recompiler/runtime |
| `runtime/` | DC render, audio, frame, menu and cheat adapters |
| `recomp/` | Function maps and guarded native adaptations |
| `scripts/` | Extraction, generation, builds, runs, tests and bench lock |
+1 -1
View File
@@ -1 +1 @@
0.3.0
0.7.0
+4
View File
@@ -0,0 +1,4 @@
{
"version": "0.5.0",
"sha256": "319cda4ce617638decdcb7d6eff482c94528fb66ab6e14e3e2c5b4e43e214d0f"
}
+58
View File
@@ -0,0 +1,58 @@
# The BozoEngine release cmake/bozo_engine.json pins, in BozoEngine/ beside cmake/: the release's archive
# (https://github.com/TheBozos/BozoEngine/releases), SHA-256 checked, unpacked, and its version and hash written to
# BozoEngine/.release; nothing is downloaded while those match the pin (a release's source\BozoEngine comes with it, so
# a player's build stays offline). Included by CMakeLists.txt, launcher/CMakeLists.txt and
# tests/native_lifetime/CMakeLists.txt when they are not given another tree, run by tools/dc_build.py in a git checkout
# and by tools/make_release.py, or on its own:
# cmake [-DBOZO_ENGINE_DOWNLOADS=<dir>] -P cmake/bozo_engine_fetch.cmake
# BOZO_ENGINE_DOWNLOADS is where the archive goes (default build/). The same scheme as TMB_Recomp's and
# SoulCaliburIII_Recomp's.
cmake_minimum_required(VERSION 3.20)
get_filename_component(bozo_engine_root "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
file(READ "${CMAKE_CURRENT_LIST_DIR}/bozo_engine.json" bozo_engine_pin)
string(JSON bozo_engine_version GET "${bozo_engine_pin}" version)
string(JSON bozo_engine_sha256 GET "${bozo_engine_pin}" sha256)
set(bozo_engine_tree "${bozo_engine_root}/BozoEngine")
set(bozo_engine_want "${bozo_engine_version} ${bozo_engine_sha256}")
set(bozo_engine_have "")
if(EXISTS "${bozo_engine_tree}/.release")
file(READ "${bozo_engine_tree}/.release" bozo_engine_have)
string(STRIP "${bozo_engine_have}" bozo_engine_have)
elseif(EXISTS "${bozo_engine_tree}")
file(GLOB bozo_engine_entries "${bozo_engine_tree}/*" "${bozo_engine_tree}/.*")
if(bozo_engine_entries)
message(FATAL_ERROR "BozoEngine: ${bozo_engine_tree} is not a pinned release (the old submodule's checkout?): "
"move it away (to build on it there: -DBOZO_ENGINE_DIR=<its new place>, or "
"tools/dc_build.py --engine <its new place>)")
endif()
endif()
if(NOT bozo_engine_have STREQUAL bozo_engine_want)
if(NOT BOZO_ENGINE_DOWNLOADS)
set(BOZO_ENGINE_DOWNLOADS "${bozo_engine_root}/build")
endif()
set(bozo_engine_name "BozoEngine-${bozo_engine_version}")
set(bozo_engine_archive "${BOZO_ENGINE_DOWNLOADS}/${bozo_engine_name}.tar.gz")
set(bozo_engine_url
"https://github.com/TheBozos/BozoEngine/releases/download/v${bozo_engine_version}/${bozo_engine_name}.tar.gz")
message(STATUS "BozoEngine ${bozo_engine_version}: ${bozo_engine_url}")
file(DOWNLOAD "${bozo_engine_url}" "${bozo_engine_archive}" EXPECTED_HASH SHA256=${bozo_engine_sha256}
TLS_VERIFY ON STATUS bozo_engine_status)
list(GET bozo_engine_status 0 bozo_engine_code)
if(bozo_engine_code)
list(GET bozo_engine_status 1 bozo_engine_error)
message(FATAL_ERROR "BozoEngine ${bozo_engine_version}: ${bozo_engine_error}")
endif()
set(bozo_engine_unpack "${bozo_engine_root}/.BozoEngine-unpack")
file(REMOVE_RECURSE "${bozo_engine_tree}" "${bozo_engine_unpack}")
file(ARCHIVE_EXTRACT INPUT "${bozo_engine_archive}" DESTINATION "${bozo_engine_unpack}")
# Its files dated now: unpacked with the archive's own dates (the release's, older than objects built since), a
# build made on the last release kept objects compiled against the old headers after a pin bump (Shinobido 0.7.0 ->
# 0.7.3: two files built on the old renderer.h, objects and the HUD missing from the picture).
file(GLOB_RECURSE bozo_engine_files LIST_DIRECTORIES false "${bozo_engine_unpack}/*")
file(TOUCH_NOCREATE ${bozo_engine_files})
file(WRITE "${bozo_engine_unpack}/${bozo_engine_name}/.release" "${bozo_engine_want}\n")
file(RENAME "${bozo_engine_unpack}/${bozo_engine_name}" "${bozo_engine_tree}")
file(REMOVE_RECURSE "${bozo_engine_unpack}")
endif()
+217 -1
View File
@@ -1,6 +1,6 @@
# BozoEngine migration
Implemented on 2026-11-06. The active build uses only the `BozoEngine` submodule. The previous dirty PS2Recomp checkout is retained locally as an ignored recovery directory; it is not a submodule, source input, include path or linked dependency. Local recovery patches and the previous runner are in `build/migration-baseline`.
Implemented on 2026-11-06. The active build uses only BozoEngine (a submodule then; since 2026-11-30 the release `cmake/bozo_engine.json` pins). The previous dirty PS2Recomp checkout is retained locally as an ignored recovery directory; it is not a submodule, source input, include path or linked dependency. Local recovery patches and the previous runner are in `build/migration-baseline`.
The graphics cleanup includes the DC adapters, regression fixtures, guarded offline adaptations and published
BozoEngine pin `4a8f70a` together. References to local/unpublished work in the milestone sections below describe
@@ -1837,3 +1837,219 @@ it draws from the simulation grid at `cloth + row*0x100 + column*0x10`. In the c
- With `DC_NATIVE_STATS=1` the Matataki, water and attract-demo routes build cloth 20, 12 and 64 times. All seven
routes end as before with identical cards and zero register/unknown accesses, VU0 calls, transfers and syncs; the
attract-demo route is frame-exact, and captures match within 3.5 mean levels outside the known fade frames.
## Native controller: libpad retired
The game reached its controllers only through `CGamePad` (the global at `0x1CBC540`): `Init` (`0x12A610`) called
`scePadInit` and opened ports 0 and 1 with `scePadPortOpen`; each frame `UpDate` ran `read_pad` (`0x12A900`) for both
ports, which walked libpad's handshake (`scePadGetState`, `scePadInfoMode`, `scePadSetMainMode`, `scePadInfoAct`,
`scePadSetActAlign`) before `pad_button_read` (`0x12A830`) called `scePadRead`; `Step` (`0x12B140`) sent the motor
levels with `scePadSetActDirect`. Nothing else in the game calls libpad.
`runtime/dc_pad.cpp` replaces `read_pad` and `Step`. The controller in each port is what it always is on the PC, a
DualShock 2 in analog mode: `read_pad` takes player 1's or 2's state from the engine's `PadInput` (the window's devices,
or a script in checks) at the frames ended, as the engine's `scePadRead` did, and writes the 19-word `PAD_STATUS`
exactly as the original left it after its handshake: the buttons byte-swapped as `scePadRead`'s halfword arrived (Cross
`0x40`, Up `0x1000`), the sticks in ly, lx, ry, rx order, phase 99, state 6 (stable), mode IDs 7 and the actuator
alignment (small motor byte 0, large byte 1). `Step` keeps the motor timers and the vibration switch (`+0x464`) and
hands port 0's levels to player 1's rumble. Guarded patches retire `Init`'s `scePadInit` (`nop`) and both
`scePadPortOpen` calls (`v0 = 1`); its `sceGsSyncV` waits stay, as they are part of the boot timeline.
The handshake took a few frames at boot during which the original reported nothing pressed; the native read reports the
controller from the first frame. No script or player presses anything that early.
- `dc-pad-tests`: every one of the 16 buttons lands where the original `pad_button_read` put `scePadRead`'s bytes; sticks,
handshake fields and alignment as the original left them; port 1 reads player 2; no input source reads as nothing
pressed with centred sticks; `Step`'s timers, expiry and vibration switch, and port 0's levels reaching player 1's
rumble. 127/127 suites.
- The game's only libpad call sites were `Init`'s three and those in `read_pad`, `pad_button_read` and `Step`; the
generated `Init` now calls only `sceGsSyncV` and `printf`, and the other three are no longer reachable.
- All seven routes (their input comes through the same `PadInput`, scripted) end as before with identical cards and zero
register/unknown accesses, VU0 calls, transfers and syncs; the cheats-quit route still ends through Quit Game; the
attract-demo route (live script) is frame-exact, and captures match within 3.4 mean levels outside the known fade
frame. A real controller's rumble is not covered by these runs.
## Native sound transport: SIF RPC and SIF DMA retired
The game reaches its sound driver (the IOP module the port compiles natively, `runtime/dc_audio.cpp`) through three
routines only. `ezMidiInit` (`0x147970`) bound the client at `0x1CECEC0` to RPC service `0x12346` with
`sceSifBindRpc`, retrying until the server existed. `ezMidi(command, argument)` (`0x147A00`, called from `CSound` and
`TransHdBd`) made one blocking `sceSifCallRpc`: with command bit `0x1000` clear the argument went into `sbuff`
(`0x1CECE80`) and those 16 bytes were sent, with it set the 64 bytes at the argument; with bit `0x8000` a 64-byte reply
landed in `sbuff`; it returned `sbuff`'s first word. `ezTransToIOP(destination, source, bytes)` (`0x147AE0`) copied
sample data into the module's memory with one `sceSifSetDma` and waited on `sceSifDmaStat`; the engine's
`sceSifSetDma` also raised a DMAC channel-5 interrupt for every transfer.
The three routines stay the game's own code; their seven library calls (`sceSifInitRpc`, `sceSifBindRpc`, the two
`sceSifCallRpc`, `FlushCache`, `sceSifSetDma`, `sceSifDmaStat`) are guarded patches to `nop`, and each is a native
site in `runtime/dc_sound.cpp`: the binding leaves the client header as the engine's did, the RPC goes straight to the
compiled module's handler (registered when the module called `sceSifRegisterRpc`) with the same request, the record's
bytes go straight into the module's memory (`sif.transfer`), the transfer reads as finished, and there is no cache to
flush. No SIF RPC, SIF DMA, DMA id or DMAC interrupt remains on the game's sound path. Each site charges the 8 EE cycles
the call's checkpoint did.
A first version replaced the three routines whole. It skipped `ezMidi`'s 2000-pass spin (64,000 EE cycles a command,
measured with a temporary probe: 64,008 per call with the call's 8) and `ezMidiInit`'s, and the attract demo drifted
(captures up to 7.75 mean levels apart, same scene a few frames off); running the original routines restored it
exactly. The spins are the game's own pacing, so they stay, with the checkpoints at which the original took its events.
- `dc-sound-tests`: each site's request against the original call's arguments (bind before and after the server exists,
16-byte, 64-byte and replying commands, an unbound client, the transfer record's bytes, no DMAC interrupt, the stat),
and the 8 cycles each site charges. 128/128 suites.
- All seven routes end as before with identical cards and zero register/unknown accesses, VU0 calls, transfers and
syncs; the attract-demo route is frame-exact again; captures match within 0.95 mean levels outside the known fade
frames.
- The attract demo recorded to WAV (5,000 frames) has the same peak in every ten-second block as the released 0.3.0
build's, which still used SIF, and RMS within a few percent; the recordings follow the host's audio clock, so their
samples do not line up one to one.
## Console OS services: what the running game uses
A survey of every EE kernel service's call sites (`tools/find_calls.py`, `recomp/dc_scus97111.toml`):
- **Threads, semaphores, alarms:** none in the running game. Its only `CreateThread` / `CreateSema` / `WaitSema` /
`SetAlarm` callers are the SDK startup's `InitThread` (which the engine answers by returning 1, creating nothing, so
its `topThread` never exists) and libcdvd / libsif internals (`sceCdInitEeCB`, `sceCdDelayThread`, `cmd_sem_init`,
`sceSifBindRpc`...), which are all engine-answered stubs, never run as game code. DC runs on its main thread alone.
- **Cache maintenance:** `FlushCache` (31 sites, every frame from `MGEndFrame`, and around texture, model and sound
uploads), `iFlushCache` and `iSyncDCache` (both vblank callbacks). The engine answered them with 0; the PC has no such
cache to keep coherent with a device. `runtime/dc_port.cpp` now answers the three itself (0, no kernel call); every
caller keeps its call and checkpoint, so EE time is unchanged. `SyncDCache` is called only from libpad code that no
longer runs.
- **Interrupts:** the vblank (INTC 2) handler that runs the game's vsync callbacks on the field clock stays: it is the
game's own timeline (the loading screens wait on a flag only that callback sets).
The end-of-run report now prints the host's call totals. On the Matataki route (9,000 frames) kernel calls fall from
19,907 to 5 (the entry point's two setup syscalls, `InitThread` and the like, at boot); all seven routes report the same 5.
All seven routes end as before with identical cards and zero register/unknown accesses, VU0 calls, transfers and syncs;
the attract-demo route is frame-exact; captures match within 0.95 mean levels outside the known fade frames. 128/128
suites.
## Library calls by function, and libsdr's transport
The host now counts its native library calls by function (BozoEngine `FreeStats::libraryByName`); with
`DC_CALL_STATS=1` DC prints them at the end of a run, most first. On the scripted routes (6,800 to 10,000 frames) they
are, by far, C library work that is native as it is: `__kernel_sinf` (260,000 to 675,000), `memcpy` (170,000 to
340,000), `rand` / `srand`, `memset`, `__kernel_cosf`, `__ieee754_rem_pio2f`, `strcmp`, `strcpy`, `strlen`, `sprintf`,
`printf`. The PS2 services are rare and event-driven: disc reads (`sceCdRead`, `sceCdSync`, `sceCdGetError`, about one
per file loaded), memory card (`sceMc*`, at saves and the load screen), the IOP heap (`sceSifInitIopHeap`,
`sceSifAllocIopHeap`, `sceSifFreeIopHeap`, at sound-bank loads), module loading at boot, GS setup at mode changes
(`sceGsSetDefDrawEnv`, `sceGsSetDefDispEnv`, `sceGsSetDefClear`, `sceGsSyncPath`, `sceDmaGetChan`) and `sceGsSyncV`
(the boot and loading timeline, kept).
They also showed `sceSifCallRpc` still made 51 to 88 times a route after the sound transport. A probe of its callers found
one: libsdr's `sceSdRemote`, the SDK's EE side of the IOP sound-hardware driver, compiled as game code, which
`set_spu` and `CSound::SetReverb` call for SPU volumes and reverb. Its `sceSdRemoteInit` and `sceSdTransToIOP` complete
it. They are compiled with work in their delay slots, so each call is a guarded `nop` and the native site is the delay
slot's instruction: the handler does that instruction first (`lui s1`, `daddu a2`, `sw zero,12(v0)`,
`daddu a0,s1`, `addiu t2,64`), then the call: binding, RPC to the module's handler, transfer into its memory, finished.
- `dc-sound-tests` also checks the six libsdr sites: each delay-slot instruction's effect before the call, the binding,
the RPC with its 64-byte reply size set first, the record cleared through `v0` before the transfer, and the stat.
- All seven routes end as before with identical cards and zero register/unknown accesses, VU0 calls, transfers and
syncs; the attract-demo route is frame-exact; captures match within 1.65 mean levels outside the known fade frame.
`sceSifCallRpc` no longer appears in any route's counts; the SIF calls left are boot and loading services
(`sceSifInitRpc`, `sceSifLoadModule`, `sceSifRebootIop`, `sceSifSyncIop`, the IOP heap).
- The attract demo recorded to WAV again has the released 0.3.0 build's peak in every ten-second block and RMS within
a few percent.
## GS and DMA setup
The library counts left a handful of GS / DMA setup calls, all at boot, loading screens or mode changes. A reader
analysis (every live reader of each call's output, after the patches already in place) found:
- `StoreImage` never runs (DC registers it to throw: a console screenshot needs a native owner), and the
`CTextureManager::EnterFixTexture(Z)` bodies never run (native hooks replace them), so their GS / DMA calls are
unreachable. No `sceDmaSend`, `sceDmaSync`, `sceGsSwapDBuff` or `sceGsSetHalfOffset` call is live anywhere.
- **Retired** (guarded patches): the six `sceDmaGetChan` lookups in `MGInit` and `init_all` (their handles are read only
by already-retired sends, syncs and channel bytes; the same constants, VIF1 `0x10009000`, GIF `0x1000A000`, fromSPR
`0x1000D000`, are written in place); `DevInit` (`sceDmaReset`, `sceDmaGetEnv` / `sceDmaPutEnv` on a stack copy,
`sceGsResetPath`: nothing reads them); the loading screen's `sceGsSetDefDBuff` (its records are read only by the
callback region already skipped); `MGInit`'s two `sceGsSetDefDispEnv` halves (read only by the retired swap); and the two
live `sceGsSyncPath` calls (main's loop exit on a mode change, DUN `MainDraw` before the mini-select capture; `v0`
unread).
- **Kept, and still a GS dependency:** `MGInit`'s two `sceGsSetDefDrawEnv` halves. The native renderer reads the GS
register images they write: draw 0 / draw 1 `FRAME` for the frame and back-buffer textures (`MGGetFBuff(Back)Tex`), and
draw 0 `TEST` / `ZBUF` for the Z mask and alpha test (`MGInit` copies them to the values `CFrameVu1::DrawVu1` hands the
native `SetGsReg3` hook). Retiring them means `MGInit` writing those words itself. Also kept: `sceGsResetGraph` (it sets
the kernel's field rate, NTSC or PAL, and the scratchpad word `DrawEnv` derives `ZBP` from) and `sceGsSyncV` (the boot and
loading timeline).
The span fixtures follow: `packet_handle` now expects the VIF1 handle without a lookup, and `loading_init` the same
ordered effects without `sceGsSetDefDBuff`'s event, record write or marker step.
- 128/128 suites; CI's own build (`tests/native_lifetime`) 59/59. All seven routes end as before with identical cards
and zero register/unknown accesses, VU0 calls, transfers and syncs; the attract-demo route is frame-exact; captures
match within 1.38 mean levels outside the known fade frames. The GS / DMA library calls left across the seven routes
are exactly the kept ones: `sceGsSyncV` 535, `sceGsSetDefDrawEnv` 14, `sceGsResetGraph` 7.
## MGInit's draw environment: no GS register images read
`MGInit`'s `sceGsSetDefDBuff` built a double-buffer record of GS register images (display, draw and clear environments)
at `0x1C752D0`. With its display halves and swap gone, its draw halves were the last GS register images DC read, at two
places:
- `MGGetFBuffTex` / `MGGetFBuffBackTex` built the frame's and the previous frame's `TEX0` from draw 0 / draw 1 `FRAME`
(picked by `DBuffID`, `gp-0x7440`); the native hooks took the frame bases from them. The two frames are fixed: 640
wide, PSMCT32, `FBP` `0x46` and 0 (the values the record held, read at run time). The hooks now build the same `TEX0`
words themselves (`0x228028000 | FBP << 5`); the game's texture calls compare these words, so only their identity
matters.
- `MGInit` loaded draw 0's `TEST` (`0x50000`: Z test on, GEQUAL) and `ZBUF` (`0x100008C`) into `mgTest` / `mgZbuf`,
which `CFrameVu1::DrawVu1` hands to `setGsReg3Hook` (it reads only the alpha-test fields and the Z mask). The two
loads are native sites giving those values; `MGInit`'s own alpha-test edit of `mgTest` runs as before.
`MGInit`'s `sceGsSetDefDBuff` call is retired, so no `sceGsSetDefDrawEnv` runs. `MGInit` still writes the record's
clear-colour bytes, which `MGBeginFrame` reads for the native screen clear. The GS library calls left are
`sceGsSyncV` (the boot and loading timeline) and `sceGsResetGraph` (it sets the kernel's field rate, NTSC or PAL).
- 128/128 suites; CI's build 59/59. All seven routes end as before with identical cards and zero register/unknown
accesses, VU0 calls, transfers and syncs; the attract-demo route is frame-exact; captures match within 2.35 mean levels
outside the known fade frames (Matataki 7400 has measured up to 3.8 between earlier builds). GS library calls left
across the routes: `sceGsSyncV` 535, `sceGsResetGraph` 7.
## The last two GS calls: sceGsSyncV and sceGsResetGraph
- `sceGsSyncV` (boot, loading screens, mode changes; 535 calls across the seven routes) is the game waiting for the
next vblank, and its frame ends there: the engine's stand-in was a `frameBoundary` library function returning the
parity of the frames ended by then, this one included. Removing the calls had shifted the boot and attract-demo
timeline (see "Startup GS calls"), so the wait stays and only its owner changes: DC's override (`runtime/dc_port.cpp`)
sets the same parity, then ends the frame through the port (`bozo::port::frameEnd`, as DC's own frame boundary does).
- `sceGsResetGraph` (MGInit) set the scratchpad words only the GS environment stand-ins read (none runs any more) and
the kernel's field rate. DC's override sets the field rate itself (NTSC 60000/1001, or PAL for video mode 3) and
nothing else.
With both, the game calls no GS library function.
- 128/128 suites; CI's build 59/59. All seven routes end as before with identical cards (the cheats-quit route quits at
frame 9,202 as before) and zero register/unknown accesses, VU0 calls, transfers and syncs; the attract-demo route is
frame-exact; captures match within 2.34 mean levels outside the known fade frames. No GS or DMA library call is left
on any route.
## Save states
BozoEngine saves the whole runtime at the dispatcher's safe point (EE RAM, dispatcher, kernel, every library, host;
`docs/save-states.md` in the engine). DC adds one section, `"dc"` (`runtime/dc_state.cpp`), for what those do not
hold. An audit of every piece of state the port keeps across frames sorted it into facts, caches, settings and
per-frame state:
- **Saved (facts the game told the port once):** DC's compiled sound modules' IOP host (`CompiledLibraries::serialize`:
IOP memory, tasks, RPC servers, mixer, libsd); the MDT copies (the game reuses a static model's MDT memory after
building it, so the copy is the only model left) with their texture bindings; the water objects of each visual;
pictures pinned to their records; what was sent to each GS place last; the records `MGMoveImage` patched and
their pictures; the frame identities last asked for; the haze's random sequences (one writes guest RAM); the
depth-of-field group; the fishing line's strip between two points; the native Options pages' state. Images are
written once in a table (many bindings share one): a Matataki state is 69 MB, 33.6 MB of it EE RAM.
- **Dropped on load (caches of the old guest memory):** decoded textures (except the patched records'), the render
places and their row counts (and the renderer's targets), CLUT overrides, shadow queues, the partial frame; the
cheats' mirrors of game values and their queued edits (nothing of the replaced run is applied to the loaded one).
- **Kept as the player's:** cheat toggles and rates.
- **Unsaveable, with the reason:** while the sound modules say so, and in the middle of a debug-font composition.
- **Not restored:** render-target pixels (on the GPU). A picture the game makes once, such as the menu's backdrop,
stays blank after a load until the game makes it again.
Checks (headless runs are deterministic):
- Matataki route, saved at 6,500: loaded in a new process, and loaded mid-run at 7,000, both give EE RAM byte-identical
to the run that never stopped, at 7,500. Dungeon route, saved at 5,000, loaded mid-run at 5,500: identical at 6,000.
- Windowed: a state saved by the window at 6,500 and loaded into it gives captures identical to the uninterrupted
run at 6,600, 7,000, 7,400, 7,700, 8,100, 8,500 and 8,900 (0.00 mean difference) and identical RAM at 9,000.
- A state made by the headless build loads into the window and plays, but follows the headless run's timeline (the
window runs on the PC clock), so compare windowed states with windowed runs.
+59 -7
View File
@@ -1,7 +1,7 @@
# Cheats and in-game options
Open the game's main menu, choose **Options**, then **Cheats**. The entry page also offers
**Game Options** (the original settings), **Graphics** and **Quit Game**. Circle goes back; Circle on the entry page
**Game Options** (the original settings), **Graphics**, **Travel** (below) and **Quit Game**. Circle goes back; Circle on the entry page
closes Options through the original fade/exit lifecycle. Quit Game defaults to Cancel and requires
an explicit confirmation. It uses normal application shutdown and does not autosave.
@@ -10,7 +10,9 @@ The same cheat controls remain available in **F2 → Cheats**. Both interfaces s
**Graphics** sets the window from the controller: **Display** (windowed, fullscreen or borderless),
**Resolution** (the window's or full-screen size; borderless uses the monitor's), **Render scale** (50% to 200% of
the window's resolution for the 3D) and **Frame rate** (60 fps, or the monitor's refresh with the frames between the
game's interpolated). Left/Right changes a row; **Apply and save** applies the choices at once and writes them to
game's interpolated), **Widescreen** (16:9: more of the scene at the sides, the HUD at the screen's edges, menus and
pictures centred), **Anti-aliasing** (off, 2x, 4x or 8x) and **Texture smoothing** (off, trilinear, 2x to 16x
anisotropic). Left/Right changes a row; **Apply and save** applies the choices at once and writes them to
`video.ini`, the same file as the launcher's Settings and **F2 → Video**. Nothing is stored in the game's save.
| Control | Effect and limits |
@@ -30,13 +32,13 @@ game's interpolated). Left/Right changes a row; **Apply and save** applies the c
| Reveal floor map | Marks every floor cell of the current dungeon floor explored, on arrival and when switched on; unopened chests, Atla and trap circles show too |
| Fish always bite | A fish near the bait never leaves it, and a hooked fish stays hooked until you reel in; fish kinds, sizes and points are unchanged |
| Spawn item / Spawn count / Give item | Gives up to 10 of a bag item, attachment or weapon through the game's own give-item routine, while there is room. Event, key and story items, default and story weapons are not offered |
| Fast-forward speed / always on | 150–400% (default 300%). Hold **`** (the key below Esc) or a gamepad's **touchpad** / **Share** button, or lock it on. Sound is muted while fast |
| Fast-forward always on | Runs the game at the **Video** tab's fast-forward speed (2×–10× or unlimited, 3× by default). To fast-forward only while a button is held, use the engine's **Fast forward** binding (**`** or a gamepad's **touchpad** by default, rebindable in the **Controls** tab), at the same speed; the two never stack. Sound is muted while fast |
| Damage multiplier | 1–16× damage you deal to monsters, capped at the monster's remaining HP; immunities stay |
| One-hit kills | Any hit that deals damage defeats the monster; immunities stay |
| No damage taken | Monster attacks never land: no damage, knock-down, status or theft. Poison already active, traps and thirst still apply |
| Key finder | The monster carrying the current floor's key blinks as a gold square on the dungeon map |
On the in-game list, Up/Down selects and scrolls through all 28 rows. Cross toggles on/off rows;
On the in-game list, Up/Down selects and scrolls through all 27 rows. Cross toggles on/off rows;
Left/Right sets them off/on. ATK, quantities and capacity use Left/Right ±1, L1/R1 ±10, L2/R2 ±100.
Gilda uses ±1/100/1000; movement uses ±5%. Select the active slot (1–3, left to right on the HUD)
before changing its quantity. Empty slots cannot create items. The row hint describes each control.
@@ -47,10 +49,59 @@ may allow a larger quantity afterward; close and reopen Options to refresh the d
Quantity requests retain the expected item ID, so changing the selected item before application
cannot silently edit a different item. Resizing never deletes or moves items.
Toggles start off, ABS and damage start at 1×, movement at 100% and fast-forward at 300% on each launch. These settings are not
Toggles start off, ABS and damage start at 1×, movement at 100% on each launch. These settings are not
stored in saves. Restored resources and one-time inventory edits **are** included if the game saves
afterward. Disabling a resource cheat restores normal depletion from its current value.
## Travel
**Options → Travel** in the game (or **F2 → Travel**) moves you anywhere and fast-forwards the story. Each request
waits until you walk freely in a town, an interior or a dungeon (not in a menu or a conversation), then goes
through the game's own fade and loading, so you arrive as the game would bring you there.
| Control | Effect and limits |
|---|---|
| Town or area / Warp to the town | Every town and area the disc has a map for (52), at its default entrance |
| Dungeon / Floor / Warp to the floor | Any floor of the seven dungeons (Demon Shaft included). The last floor is the boss's: its door and its fight are set up by the game as on a normal arrival. A warped-to floor counts as reached on the dungeon's entrance menu. A dungeon's story floors need the allies of its chapter (the Wise Owl Forest two, the Shipwreck three, ... the Gallery of Time six; Divine Beast Cave from floor 11 two; the Demon Shaft none): ahead of the story the warp says which chapter to advance to first |
| Next monster | In a dungeon: next to the next live monster of the floor, in turn |
| Unlock georama parts | Every building, villager and element of every town, as if every Atla had been opened (through the game's own Atla routines; elements already owned are not given twice). The dungeons' Atla are then empty. The Sun Sphere stays the Coliseum's |
| Open the world map | Every town and dungeon on the world map, and the World Map item |
| Story chapter / Advance the story | The story state a playthrough has when that chapter begins: the chapter counter, the allies and their weapons, the dungeons before it cleared, the places visited, the story flags the transition scenes set. It never moves the story back |
The story chapters are 1 Norune, 2 Matataki and Wise Owl Forest, 3 Queens and the Shipwreck, 4 Muska Lacka and
the Sun & Moon Temple, 5 Yellow Drops and the Moon Sea, 6 Dark Heaven Castle and the Gallery of Time, and 7 the
post-game (the game counts as cleared: the Demon Shaft opens). **Save first:** advancing the story is meant for
testing; key items handed out in the middle of a chapter and the georama house events of skipped chapters are not
all recreated, and an advanced save is not the same as a played one.
### Scripted runs
`--cheat-script FILE` drives the same requests by frame, for hidden test runs. Each line is
`<frame> <command> [arguments]` (`#` starts a comment); commands run in order, each once the game is idle:
| Command | Effect |
|---|---|
| `place <map>` | Warp to a town or area by map number (Norune 0, Matataki 1, Queens 2, Muska Lacka 3, Brownboo 14, Yellow Drops 23, Dark Heaven Castle 40, ...) |
| `dungeon <dungeon> <floor>` | Warp to a dungeon (0 Divine Beast Cave ... 6 Demon Shaft) and floor (1-based) |
| `monster`, `georama`, `world`, `chapter <1-7>` | As the Travel rows |
| `flag <n> <0/1>`, `intflag <n> <value>` | A story flag or counter, through the game's own setter |
| `cheat <name> <0/1>` | `health`, `durability`, `thirst`, `stamina`, `time`, `fast`, `fishing`, `map`, `onehit`, `nodamage`, `key` |
| `talk <0/1>` | Cross tapped every 16 frames while a conversation or an event waits, so a run reads through the story |
| `wait <frames>` | The next command that many frames later |
| `party <1-6>` | The allies up to that many, as their join scenes give them (the party size, each ally's weapon, its default weapon selected) |
| `item <n> [count]` | A story or bag item by the scripts' item number, through the game's own give-item routine |
| `event <n>` | In a dungeon: start that dungeon event as the game's triggers do (500: the boss's start in Divine Beast Cave, Wise Owl Forest and the Moon Sea; 403: King's Curse's) |
| `kill` | In a dungeon: defeat every live monster of the floor, bosses included, through the game's own poison tick (its countdown at 1, its strength past the HP): the death, the kill count and a boss's defeat scene follow as from a blow. Waits up to two minutes for free play with a live monster |
| `until intflag <n> <value>`, `until flag <n>` | Wait (up to 20 minutes) for the story to set that counter or flag |
| `press <buttons> <frames>` | Buttons held on top of the controller (`cross`, `circle`, `square`, `triangle`, `l1`, `r1`, `l2`, `r2`, `up`, `down`, `left`, `right`, `start`, `select`, joined with `+`) |
| `townevent <n>` | In a town or area's free walk: run that map's own event, as its triggers do (the game's `RunEvent`) |
| `where`, `peek` | The game's state in the log (`[dc:warp]`): mode, map, dungeon, floor, chapter, party, the game-cleared mark, the Demon Shaft's visits, deepest floors; in a dungeon also the active character and each monster's HP. `where` in turn, `peek` at once |
[`docs/playthrough.cheat`](playthrough.cheat) is a whole story in one script: from an early Norune save, each
chapter's allies join, each boss is fought (its trigger, then `kill`) and each defeat scene sets the story, from
Dran to the Dark Genie and the ending. Run it with `--hidden --cheat-script docs/playthrough.cheat` on a card whose
save is loaded by the `--pad-script` that reaches Norune's free walk (or start the script's frames later).
## Implementation and bounded validation
Only the game thread writes player state. The native UI publishes atomic settings and queues edits.
@@ -96,8 +147,9 @@ return-address checks and the identity-matched DUN module):
copy of the hook's context with a sentinel return. Names come from the resident system messages (`SystemMes`,
key = number + 100; a weapon's number from `ComItemInfo`, indexed id − 0x51). The allow-list excludes the 53
event-flagged bag items (every floor gate key among them), unused IDs, the Synthsphere and default/story weapons.
- **Fast-forward**: the frame pacer's cap is raised (the game's clock advances per frame); audio is not queued while
fast. `PS2X_FRAME_CAP=0` runs are left unlimited.
- **Fast-forward**: always on raises the frame pacer's cap to the Video tab's speed (the game's clock advances per
frame); while the engine's hold is active (`FramePacer::speedPercent`) the cap stays normal and the pacer applies
that speed itself, so they never stack. Audio is not queued while fast. `PS2X_FRAME_CAP=0` runs are left unlimited.
- **Damage dealt**: an instruction hook at 0x1DC3F4 (`subu v0,v0,s4` in `CMonstorUnit::CheckDmg`, a native site)
scales the final damage before the original subtraction. Every player attack reaches monster HP there.
- **Damage taken**: `CheckHitUser` (0x1B5920) answers "no hit" (-1) to DUN `BtCheckDamageProc` (return 0x1DBB0E0).
+13
View File
@@ -625,3 +625,16 @@ routes match the previous build (faces, HUD, menus, identical cards); the only d
timing and the random dungeon floor. A 42-minute human fullscreen run on this build averaged 60 FPS every
minute, its slowest two-second window 56.6 FPS, with up to 10.8 MiB hashed in a frame. The player revisited
the slow house in that run and reported no frame drop there.
## Town water mirrored the cliffs after the menu (November 9)
In a town canal the water near Toan showed the cliffs above it, like a mirror, while the far water looked normal. It
appeared only after the menu had been opened. The town copies its frame into the water's `work` place every frame
(`MGStretchMoveImage` / `MGMoveImage`), and `CWater` refracts that copy. Opening the menu runs
`MGMoveFrameBuffImage`, which captures both fields into the same place as a 448-row picture and marked the place
`g_targetRows = 448`. Nothing reset it, so every later 224-row frame copy was sampled at half its height: the water
read the upper part of the screen. A diagnostic run logged the copies (about 800 per session into `0x1A40`, two
captures at the menu) and the water's choice (refracted from that place every frame). The stretch copy now marks its
place 224 rows (the 640 x 224 picture it makes) and the plain copy the source's rows. The bug predates 0.3.0: its
screenshot without a menu opened shows the same water as the fixed build. 128/128 suites; all seven routes end as
before with identical cards, the attract demo frame-exact.
+81
View File
@@ -0,0 +1,81 @@
# Dark Cloud, the whole story by script (dc.exe --cheat-script, see docs/CHEATS.md "Scripted runs").
# Frame 3400 is when this run's --pad-script had reached Norune's free walk from an early save (any Norune save
# works: start the commands once the game is in Norune). Each command waits its turn and for an idle game.
# Checked headless (2026-11-28): every boss below beaten through the game's own death and defeat scenes, the
# ending, the credits and the cleared save, twice, each milestone within about 50 frames of the other run.
# One continuous run from an early Norune save to the ending: each boss's fight started by its own trigger, each
# boss defeated through the game's own death path (kill), each defeat scene left to set the story (until ...).
# Allies join as their scenes give them (party); the temple's signet doors as they set their flags (26, 27).
3400 talk 1
3400 cheat nodamage 1
3400 cheat health 1
3400 where
# 1. Divine Beast Cave: Dran
3400 party 2
3400 dungeon 0 15
3400 wait 300
3400 event 500
3400 kill
3400 until intflag 0 100
3400 wait 1800
3400 where
# 2. Wise Owl Forest: Master Utan
3400 party 3
3400 dungeon 1 17
3400 wait 300
3400 event 500
3400 kill
3400 until flag 34
3400 wait 1800
3400 where
# 3. The Shipwreck: La Saia (the floor's own scene in Area s34 first)
3400 party 4
3400 dungeon 2 18
3400 kill
3400 until intflag 0 300
3400 wait 1800
3400 where
# 4. The Sun & Moon Temple: King's Curse (both signet doors opened)
3400 party 5
3400 flag 26 1
3400 flag 27 1
3400 dungeon 3 18
3400 wait 300
3400 event 403
3400 kill
3400 until intflag 0 400
3400 wait 1800
3400 where
# 5. The Moon Sea: Minotaur Joe
3400 party 6
3400 dungeon 4 15
3400 wait 300
3400 event 500
3400 kill
3400 until intflag 0 500
3400 wait 1800
3400 where
# 6. The Gallery of Time: the Dark Genie, then the ending
3400 dungeon 5 25
3400 kill
3400 kill
3400 wait 600
3400 kill
3400 wait 600
3400 kill
3400 until flag 41
3400 where
# The ending and the credits, then the game's own "save cleared data?": Yes, the card, the save.
3400 wait 30000
3400 where
3400 press cross 4
3400 wait 240
3400 press cross 4
3400 wait 240
3400 press cross 4
3400 wait 240
3400 press cross 4
3400 wait 900
3400 where
3400 wait 3000
3400 where
Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 372 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 316 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 314 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 361 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 355 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

+14 -3
View File
@@ -25,10 +25,21 @@ endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# BozoEngine's tree (the submodule beside launcher/): its PNG writer only.
set(LAUNCHER_BOZO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../BozoEngine" CACHE PATH "BozoEngine's source tree")
# BozoEngine's tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/ beside launcher/): its PNG writer
# only.
set(LAUNCHER_BOZO_DIR "" CACHE PATH "BozoEngine's source tree (default: the pinned release, in BozoEngine/)")
set(launcher_engine_given "")
if(LAUNCHER_BOZO_DIR)
file(REAL_PATH "${LAUNCHER_BOZO_DIR}" launcher_engine_given)
endif()
file(REAL_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../BozoEngine" launcher_engine_in_repo)
if(NOT LAUNCHER_BOZO_DIR OR launcher_engine_given STREQUAL launcher_engine_in_repo)
include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/bozo_engine_fetch.cmake")
set(LAUNCHER_BOZO_DIR "${bozo_engine_tree}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/bozo_engine.json")
endif()
if(NOT EXISTS "${LAUNCHER_BOZO_DIR}/runtime/app/png.cpp")
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR} (git submodule update --init BozoEngine)")
message(FATAL_ERROR "No BozoEngine at ${LAUNCHER_BOZO_DIR}")
endif()
include(FetchContent)
+20
View File
@@ -126,6 +126,26 @@ bool VideoConfig::save(const std::string &file) const
return writeAtomically(file, text);
}
bool GameConfig::load(const std::string &file)
{
std::map<std::string, std::string> v;
if (!readIni(file, v, true))
return false;
const std::string l = v["language"];
if (l == "en" || l == "fr" || l == "de" || l == "it")
language = l;
return true;
}
bool GameConfig::save(const std::string &file) const
{
std::string text = "# Dark Cloud's own settings (the launcher and RecompLauncher write this file; the game reads it when it starts).\n"
"# language: en (English), fr (French), de (German) or it (Italian), from the disc's own text and menus.\n"
"\n[game]\n";
text += "language = " + language + "\n";
return writeAtomically(file, text);
}
std::vector<std::pair<int, int>> offeredResolutions(int monitorWidth, int monitorHeight)
{
static const std::pair<int, int> kCommon[] = {
+9
View File
@@ -36,6 +36,15 @@ struct VideoConfig
bool save(const std::string &file) const;
};
// The game's own settings (game.ini in the user folder, read by the game when it starts; RecompLauncher writes it too).
struct GameConfig
{
std::string language = "en"; // en, fr, de, it: the text and menus the game shows (runtime/dc_language.h)
bool load(const std::string &file);
bool save(const std::string &file) const;
};
// The sizes the game's Video tab offers on this monitor (ps2_video::resolutions): common 4:3 and 16:9 ones that fit,
// and the monitor's own.
std::vector<std::pair<int, int>> offeredResolutions(int monitorWidth, int monitorHeight);
+30 -2
View File
@@ -342,7 +342,7 @@ struct Paths
{
std::string release, source, kit, python, script, buildOut, buildLogs, game, gameExe, elf, iso;
std::string releaseIni, builtFrom; // the source's release stamp, and the one of the code the game was built from
std::string user, launcherIni, videoIni, logs, crashes;
std::string user, launcherIni, videoIni, gameIni, logs, crashes;
};
struct App
@@ -350,6 +350,8 @@ struct App
Paths p;
LauncherConfig cfg;
VideoConfig video;
GameConfig gameCfg;
bool gameCfgSaved = false;
Phase phase = Phase::Welcome;
Tab tab = Tab::Play;
std::string missingPart; // Incomplete: what is not there
@@ -440,12 +442,14 @@ struct App
const fs::path u = plat::path(p.user);
p.launcherIni = plat::str(u / L"launcher.ini");
p.videoIni = plat::str(u / L"video.ini");
p.gameIni = plat::str(u / L"game.ini");
p.logs = plat::str(u / L"logs");
p.crashes = plat::str(u / L"crashes");
cfg.load(p.launcherIni);
g_fr = (cfg.language.empty() ? plat::systemLanguage() : cfg.language) == "fr";
video.load(p.videoIni);
gameCfg.load(p.gameIni);
if (!exists(p.script))
missingPart = "source\\tools\\dc_build.py";
@@ -1301,6 +1305,8 @@ static void drawSettings(App &app, float inner)
}
}
gap(6);
const float settingsRowY = ImGui::GetCursorPosY();
ImGui::BeginGroup(); // Resolution, with Game language beside it
ui::text(L("Resolution", "Résolution"), 17, ui::color::inkFaint);
const auto sizes = offeredResolutions(win::monitorWidth(), win::monitorHeight());
auto label = [&](int w, int h)
@@ -1336,6 +1342,28 @@ static void drawSettings(App &app, float inner)
}
ImGui::PopFont();
}
ImGui::EndGroup();
// The game's language (game.ini): the disc's own English, French, German and Italian text and menus, level
// with Resolution (placed, not SameLine: a same-line label would take the combo's baseline offset).
const float belowResolution = ImGui::GetCursorPosY();
ImGui::SetCursorPos(ImVec2(ImGui::GetItemRectMax().x - ImGui::GetWindowPos().x + S(56), settingsRowY));
ImGui::BeginGroup();
ui::text(L("Game language", "Langue du jeu"), 17, ui::color::inkFaint);
static const char *gameLanguages[4][2] = {{"en", "English"}, {"fr", "Français"}, {"de", "Deutsch"}, {"it", "Italiano"}};
for (int i = 0; i < 4; ++i)
{
if (i)
ImGui::SameLine(0, S(8));
char langId[64];
std::snprintf(langId, sizeof(langId), "%s##game-%s", gameLanguages[i][1], gameLanguages[i][0]);
if (ui::pill(langId, app.gameCfg.language == gameLanguages[i][0], 18) && app.gameCfg.language != gameLanguages[i][0])
{
app.gameCfg.language = gameLanguages[i][0];
app.gameCfgSaved = app.gameCfg.save(app.p.gameIni);
}
}
ImGui::EndGroup();
ImGui::SetCursorPosY(std::max(belowResolution, ImGui::GetCursorPosY()));
if (changed)
{
VideoConfig out = v;
@@ -1347,7 +1375,7 @@ static void drawSettings(App &app, float inner)
out.save(app.p.videoIni);
app.video.exists = true;
}
if (v.exists)
if (v.exists || app.gameCfgSaved)
ui::text(L("Saved. The game uses it the next time it starts.", "Enregistré. Le jeu l'utilisera au prochain démarrage."), 16,
ui::color::good);
gap(12);
+58
View File
@@ -385,3 +385,61 @@
0x00223858 0x8f848bd4 0x24040000 # null packet argument; DrawNewFileTemplete__Fiii
# main's mode change: sceGsSyncPath always answers idle; v0 is reloaded right after.
0x00141334 0x0c044be6 0x00000000 # main: no sceGsSyncPath
# CGamePad::Init: the controller is native (runtime/dc_pad.cpp). No libpad initialisation; both ports open (v0 = 1).
# The sceGsSyncV waits around them stay: they are part of the boot timeline.
0x0012a648 0x0c047d4c 0x00000000 # CGamePad::Init: no scePadInit
0x0012a750 0x0c047de4 0x24020001 # CGamePad::Init: port 0 open, no scePadPortOpen
0x0012a7b8 0x0c047de4 0x24020001 # CGamePad::Init: port 1 open, no scePadPortOpen
# The sound transport is native (runtime/dc_sound.cpp): ezMidiInit's, ezMidi's and ezTransToIOP's library calls are
# native sites that reach the compiled sound module directly. Every delay slot is a nop; the sites set v0.
0x0014797c 0x0c045b12 0x00000000 # ezMidiInit: sceSifInitRpc
0x00147998 0x0c045cb6 0x00000000 # ezMidiInit: sceSifBindRpc
0x00147a70 0x0c045d2a 0x00000000 # ezMidi: sceSifCallRpc (64 bytes from the argument)
0x00147ab4 0x0c045d2a 0x00000000 # ezMidi: sceSifCallRpc (16 bytes from sbuff)
0x00147b10 0x0c045168 0x00000000 # ezTransToIOP: FlushCache
0x00147b24 0x0c0451b8 0x00000000 # ezTransToIOP: sceSifSetDma
0x00147b48 0x0c0451b0 0x00000000 # ezTransToIOP: sceSifDmaStat
# libsdr's transport is native too (runtime/dc_sound.cpp): each call is a nop and the native site is its delay slot,
# whose instruction the site does before the call.
0x00121260 0x0c045b12 0x00000000 # sceSdRemoteInit: sceSifInitRpc (site 0x121264)
0x00121274 0x0c045cb6 0x00000000 # sceSdRemoteInit: sceSifBindRpc (site 0x121278)
0x00121330 0x0c0451b8 0x00000000 # sceSdTransToIOP: sceSifSetDma (site 0x121334)
0x00121348 0x0c0451b0 0x00000000 # sceSdTransToIOP: sceSifDmaStat (site 0x12134c)
0x0012152c 0x0c045d2a 0x00000000 # sceSdRemote: sceSifCallRpc, 64-byte reply (site 0x121530)
0x00121560 0x0c045d2a 0x00000000 # sceSdRemote: sceSifCallRpc (site 0x121564)
# Remaining GS / DMA setup (docs/BOZO_MIGRATION.md, "GS and DMA setup"). sceDmaGetChan's handles are only read by
# already-retired sends, syncs and channel bytes: the same constants are written in place (VIF1, GIF, fromSPR).
0x0012c250 0x0c0430ea 0x3c021000 # MGInit: VIF1 handle without sceDmaGetChan (lui v0,0x1000)
0x0012c254 0x00000000 0x34429000 # ... ori v0,v0,0x9000
0x0012c260 0x0c0430ea 0x3c021000 # MGInit: GIF handle (lui v0,0x1000)
0x0012c264 0x00000000 0x3442a000 # ... ori v0,v0,0xa000
0x0012c270 0x0c0430ea 0x3c021000 # MGInit: fromSPR handle (lui v0,0x1000)
0x0012c274 0x00000000 0x3442d000 # ... ori v0,v0,0xd000
0x00140d44 0x0c0430ea 0x3c021000 # init_all: VIF1 handle (lui v0,0x1000)
0x00140d48 0x00000000 0x34429000 # ... ori v0,v0,0x9000
0x00140d54 0x0c0430ea 0x3c021000 # init_all: GIF handle (lui v0,0x1000)
0x00140d58 0x00000000 0x3442a000 # ... ori v0,v0,0xa000
0x00140d64 0x0c0430ea 0x3c021000 # init_all: fromSPR handle (lui v0,0x1000)
0x00140d68 0x00000000 0x3442d000 # ... ori v0,v0,0xd000
# DevInit only resets DMA (sceDmaReset, sceDmaGetEnv/PutEnv on a stack copy) and the GS path: nothing reads it.
0x00140d38 0x0c049ee8 0x00000000 # init_all: no DevInit
# The loading screen's double-buffer records are read only by the callback region already skipped (0x1546c4).
0x00154264 0x0c044b02 0x00000000 # init_now_loading: no sceGsSetDefDBuff
# MGInit's display halves are read only by the retired sceGsSwapDBuff. Its draw halves stay: the native frame
# textures and the Z / alpha state read their FRAME, ZBUF and TEST images.
0x00112c84 0x0c04490e 0x00000000 # sceGsSetDefDBuff: no sceGsSetDefDispEnv (half 0)
0x00112ca0 0x0c04490e 0x00000000 # sceGsSetDefDBuff: no sceGsSetDefDispEnv (half 1)
# main's loop exit on a mode change: sceGsSyncPath answers idle; v0 is not read.
0x00141bd4 0x0c044be6 0x00000000 # main: no sceGsSyncPath
# MGInit's double-buffer record (sceGsSetDefDBuff: display, draw and clear environments as GS register images) is no
# longer made. Its readers are native: the frame-texture getters build their TEX0 words themselves, and the two loads
# of draw 0's TEST and ZBUF are native sites (runtime/dc_port.cpp) giving the same values. MGInit writes the record's
# clear colour bytes itself, as before.
0x0012c33c 0x0c044b02 0x00000000 # MGInit: no sceGsSetDefDBuff
0x0012c510 0xdcc60000 0xdcc60000 # MGInit: native site, draw 0 TEST (guard)
0x0012c57c 0xdc840000 0xdc840000 # MGInit: native site, draw 0 ZBUF (guard)
# CFrameVu1::DrawVu1 skips a model whose projected bounding box lies wholly outside the frame: x within 320 of the
# centre (y within 112). Its two loads of 320.0 are native sites (runtime/dc_port.cpp) giving the frame's half width,
# so widescreen draws the models its wider sides show; 4:3 keeps 320.
0x00129ab4 0x3c0243a0 0x3c0243a0 # DrawVu1: native site, cull half width (guard)
0x00129ae4 0x3c0243a0 0x3c0243a0 # DrawVu1: native site, cull half width (guard)
+2
View File
@@ -85,3 +85,5 @@
0x01dc00bc 0x8f848bd4 0x24040000 # null packet argument; DrawtargetCursor__FPffff
0x01dc0104 0x8f848bd4 0x24040000 # null packet argument; DrawtargetCursor__FPffff
0x01dc174c 0x8f858bd4 0x24050000 # null packet argument; LoaderLoop__Fv
# MainDraw before the battle mini-select capture: sceGsSyncPath answers idle; v0 is reloaded right after.
0x01db0824 0x0c044be6 0x00000000 # no sceGsSyncPath
+142
View File
@@ -0,0 +1,142 @@
{
"$schema": "https://recomplauncher.com/schema/recomplauncher.json",
"format": 1,
"name": "Dark Cloud",
"repo": "TheBozos/DC_Recomp",
"inputs": [
{
"id": "game",
"label": "Your disc image of the USA release, serial SCUS-97111 (.iso, or .bin/.cue).",
"formats": [{ "type": "file" }],
"check": { "iso9660": "SCUS_971.11", "ids": ["SCUS-97111"] },
"dumps": [{ "name": "USA", "size": 1797980160, "crc32": "fe4adb70" }]
}
],
"prepare": {
"program": ["kit/python/python.exe"],
"args": ["-I", "-X", "utf8", "{install}/source/tools/dc_build.py", "--disc={input:game}",
"--out", "{install}/build", "--game", "{install}/game", "--progress-lines"],
"label": "Building the game from your disc",
"done": ["{install}/game/built_from.ini"],
"keeps_copy": true
},
"start": {
"program": ["game/dc.exe"],
"args": ["--elf", "{install}/game/SCUS_971.11", "--iso", "{install}/game/disc.iso"],
"env": { "PS2X_USER_DIR": "{data}" }
},
"folders": {
"game": [{ "path": "{install}/game" }],
"saves": [{ "path": "{data}/mc0" }],
"logs": [{ "path": "{data}/logs" }]
},
"saves": ["{data}/mc0", "{data}/mc1"],
"config": [
{ "format": "ini", "file": [{ "path": "{data}/video.ini" }] },
{ "id": "game", "format": "ini", "file": [{ "path": "{data}/game.ini" }] }
],
"settings": [
{
"id": "language", "label": "Language", "in": "game",
"help": "The game's text and menus: the disc's own English, or the European release's French, German or Italian, which the USA disc also carries.",
"choices": [
{ "label": "English", "set": { "game/language": "en" } },
{ "label": "Français", "set": { "game/language": "fr" } },
{ "label": "Deutsch", "set": { "game/language": "de" } },
{ "label": "Italiano", "set": { "game/language": "it" } }
],
"defaults": { "game/language": "en" }
},
{
"id": "mode", "label": "Display mode",
"choices": [
{ "label": "Windowed", "set": { "video/mode": "windowed" } },
{ "label": "Borderless", "set": { "video/mode": "borderless" } },
{ "label": "Full screen", "set": { "video/mode": "fullscreen" } }
],
"defaults": { "video/mode": "windowed" }
},
{
"id": "widescreen", "label": "Widescreen",
"help": "16:9 with more of the scene at the sides; menus and pictures stay centred.",
"choices": [
{ "label": "Off (4:3)", "set": { "video/widescreen": "off" } },
{ "label": "On (16:9)", "set": { "video/widescreen": "on" } }
],
"defaults": { "video/widescreen": "off" }
},
{
"id": "frame_rate", "label": "Frame rate",
"help": "Above 60, frames between the game's are drawn in between; the game itself still runs at its own speed.",
"choices": [
{ "label": "60 (the game's)", "set": { "video/frame_rate": "game" } },
{ "label": "Monitor's refresh", "set": { "video/frame_rate": "monitor" } },
{ "label": "120", "set": { "video/frame_rate": "120" } },
{ "label": "144", "set": { "video/frame_rate": "144" } },
{ "label": "240", "set": { "video/frame_rate": "240" } }
],
"defaults": { "video/frame_rate": "game" }
},
{
"id": "render_scale", "label": "Render scale",
"help": "The 3D drawn at this many times the window's size.",
"choices": [
{ "label": "1x", "set": { "video/render_scale": "1" } },
{ "label": "1.5x", "set": { "video/render_scale": "1.5" } },
{ "label": "2x", "set": { "video/render_scale": "2" } },
{ "label": "3x", "set": { "video/render_scale": "3" } },
{ "label": "4x", "set": { "video/render_scale": "4" } }
],
"defaults": { "video/render_scale": "1" }
},
{
"id": "anti_aliasing", "label": "Anti-aliasing",
"help": "Smooths the edges of the 3D (MSAA).",
"choices": [
{ "label": "Off", "set": { "video/anti_aliasing": "off" } },
{ "label": "2x", "set": { "video/anti_aliasing": "2x" } },
{ "label": "4x", "set": { "video/anti_aliasing": "4x" } },
{ "label": "8x", "set": { "video/anti_aliasing": "8x" } }
],
"defaults": { "video/anti_aliasing": "off" }
},
{
"id": "texture_smoothing", "label": "Texture smoothing",
"help": "Off samples textures as the PS2 does; the others stop distant textures shimmering.",
"choices": [
{ "label": "Off", "set": { "video/texture_smoothing": "off" } },
{ "label": "Trilinear", "set": { "video/texture_smoothing": "trilinear" } },
{ "label": "4x anisotropic", "set": { "video/texture_smoothing": "4x" } },
{ "label": "8x anisotropic", "set": { "video/texture_smoothing": "8x" } },
{ "label": "16x anisotropic", "set": { "video/texture_smoothing": "16x" } }
],
"defaults": { "video/texture_smoothing": "off" }
},
{
"id": "pause_in_background", "label": "Pause in the background", "advanced": true,
"help": "Holds the game while another window has the focus.",
"choices": [
{ "label": "Off", "set": { "video/pause_in_background": "off" } },
{ "label": "On", "set": { "video/pause_in_background": "on" } }
],
"defaults": { "video/pause_in_background": "off" }
},
{
"id": "fast_forward", "label": "Fast-forward speed", "advanced": true,
"help": "The game's speed while fast forward is held (` on the keyboard, or the touchpad).",
"choices": [
{ "label": "2x", "set": { "video/fast_forward": "2x" } },
{ "label": "3x", "set": { "video/fast_forward": "3x" } },
{ "label": "5x", "set": { "video/fast_forward": "5x" } },
{ "label": "10x", "set": { "video/fast_forward": "10x" } },
{ "label": "Unlimited", "set": { "video/fast_forward": "unlimited" } }
],
"defaults": { "video/fast_forward": "3x" }
}
],
"actions": [
{ "id": "logs", "label": "Logs", "help": "The game's logs, for a bug report.", "open": "logs" }
],
"looks": { "graphics": "opengl" },
"system": { "windows": { "version": "10", "graphics": { "opengl": "3.3" } } }
}
+8
View File
@@ -1,5 +1,6 @@
// Dark Cloud's sound-library selection. Engine services and translation are game independent.
#include "dc_audio_modules.h"
#include "bozo/state.h"
#include <algorithm>
#include <cctype>
#include <memory>
@@ -34,4 +35,11 @@ namespace dc
return sound->startImage(name + ";1");
};
}
// Save states: the compiled sound modules' IOP host, and why it cannot be saved right now (empty: it can).
void audioState(bozo::state::Archive &a)
{
if (sound)
sound->serialize(a);
}
std::string audioUnsaveable() { return sound ? sound->unsaveable() : std::string(); }
} // namespace dc
+13 -5
View File
@@ -23,8 +23,7 @@ namespace dc::cheats
{
std::array<std::atomic<bool>, 11> options{};
std::atomic<int> damageRate{1};
std::atomic<int> fastRate{300};
std::atomic<bool> fastHeld{false};
std::atomic<int> fastRate{300}; // the Video tab's fast-forward speed (0: as fast as the PC goes)
std::atomic<int> currentAttack{-1}, pendingAttack{-1};
std::atomic<int> absRate{1},moveRate{100},currentGilda{-1},pendingGilda{-1};
std::atomic<int> currentSize{-1},minimumSize{1},pendingSize{-1};
@@ -557,9 +556,8 @@ namespace dc::cheats
int absMultiplier(){return absRate.load(std::memory_order_relaxed);}
void setAbsMultiplier(int v){absRate.store(std::clamp(v,1,16),std::memory_order_relaxed);}
int fastForwardPercent(){return fastRate.load(std::memory_order_relaxed);}
void setFastForwardPercent(int v){fastRate.store(std::clamp(v,150,400),std::memory_order_relaxed);}
void setFastForwardHeld(bool held){fastHeld.store(held,std::memory_order_relaxed);}
int gameSpeedPercent(){return fastHeld.load(std::memory_order_relaxed) || enabled(Cheat::FastForwardLock) ? fastForwardPercent() : 100;}
void setFastForwardPercent(int v){fastRate.store(v,std::memory_order_relaxed);}
int gameSpeedPercent(){return enabled(Cheat::FastForwardLock) ? fastForwardPercent() : 100;}
int damageMultiplier(){return damageRate.load(std::memory_order_relaxed);}
void setDamageMultiplier(int v){damageRate.store(std::clamp(v,1,16),std::memory_order_relaxed);}
int movementPercent(){return moveRate.load(std::memory_order_relaxed);}
@@ -613,4 +611,14 @@ namespace dc::cheats
if(mapSymbols)registry.registerFunction(kMapSymbols,mapSymbolsHook);
priorInstruction=registry.instructionHandler();registry.nativeGraphics(instruction);
}
void stateLoaded()
{
currentAttack = pendingAttack = currentGilda = pendingGilda = currentSize = pendingSize = -1;
for (auto &item : currentItems) item = 0;
for (auto &item : pendingItems) item = 0;
pendingLevel = false;
pendingSpawn = 0;
haveHeldTime = false; // freeze time takes the loaded game's time again
observedGeneration = ~0u;
}
}
+7 -5
View File
@@ -11,12 +11,12 @@ namespace dc::cheats
enum class Cheat { InfiniteHealth, InfiniteWeaponDurability, InfiniteThirst, InfiniteStamina, FreezeTimeOfDay, FastForwardLock, FishingHelper, RevealFloorMap, OneHitKills, NoDamageTaken, KeyFinder };
bool enabled(Cheat cheat);
void setEnabled(Cheat cheat, bool on);
// Fast-forward: while held (the window's ` key or a gamepad's touchpad / Share button) or locked on, the frame
// cap is raised to this percentage of the normal rate and the sound is muted. Game logic runs per frame.
// Fast-forward always on: the frame cap is raised to the Video tab's fast-forward speed and the sound is muted.
// Holding fast forward is the engine's (its FastForward binding: ` or the touchpad by default); the two never
// stack. Game logic runs per frame.
int fastForwardPercent();
void setFastForwardPercent(int value); // 150..400
void setFastForwardHeld(bool held); // window input, sampled once a frame
int gameSpeedPercent(); // 100, or fastForwardPercent() while held or locked
void setFastForwardPercent(int value); // the Video tab's speed, copied each frame (0: as fast as the PC goes)
int gameSpeedPercent(); // 100, or fastForwardPercent() while locked on
int equippedWeaponAttack(); // game-thread snapshot; -1 when no weapon is equipped
void requestWeaponAttack(int value); // one edit, applied on the game thread
int absMultiplier();
@@ -49,4 +49,6 @@ namespace dc::cheats
void applyPlayerEdits(uint8_t *ram,const R5900Context *ctx);
void install(Runtime &runtime, bozo::port::Registry &registry);
void registerMenu();
// Save states: after a load, the mirrors of game values and the queued edits are dropped.
void stateLoaded();
}
+59 -4
View File
@@ -1,4 +1,5 @@
#include "dc_cheats.h"
#include "dc_warp.h"
#include "bozo/app/settings_tabs.h"
#include "imgui.h"
#include <algorithm>
@@ -77,11 +78,65 @@ namespace dc::cheats
}
else ImGui::TextDisabled("Item names appear once the game has loaded its messages.");
ImGui::Separator();
int fast = fastForwardPercent();
if (ImGui::SliderInt("Fast-forward speed", &fast, 150, 400, "%d%%")) setFastForwardPercent(fast / 50 * 50);
toggle("Fast-forward always on", Cheat::FastForwardLock, "Or hold ` (below Esc) or the gamepad's touchpad. Sound is muted.");
toggle("Fast-forward always on", Cheat::FastForwardLock,
"At the Video tab's fast-forward speed. Or hold the Fast forward binding (Controls tab: ` or the touchpad). Sound is muted.");
ImGui::Separator();
ImGui::TextWrapped("Cheats reset each launch: toggles off, ABS 1x, movement 100%, fast-forward 300%.");
ImGui::TextWrapped("Cheats reset each launch: toggles off, ABS 1x, movement 100%.");
});
// Travel and progress (dc_warp.h): carried out when the game is idle (a town's free walk, a dungeon's free
// play), through the game's own fades and loads.
bozo::app::ui::registerTab("Travel", [] {
ImGui::TextWrapped("Status: %s", dc::warp::status().c_str());
ImGui::TextDisabled("Each runs as soon as you are walking freely in a town or a dungeon (not in a menu, a talk or an interior).");
ImGui::Separator();
static int place = 0;
if (ImGui::BeginCombo("Town or area", dc::warp::place(place).name))
{
for (int i = 0; i < dc::warp::placeCount(); ++i)
if (ImGui::Selectable(dc::warp::place(i).name, i == place))
place = i;
ImGui::EndCombo();
}
if (ImGui::Button("Warp there"))
dc::warp::requestPlace(dc::warp::place(place).map);
ImGui::Separator();
static int dungeon = 0, floor = 1;
if (ImGui::BeginCombo("Dungeon", dc::warp::dungeon(dungeon).name))
{
for (int i = 0; i < dc::warp::dungeonCount(); ++i)
if (ImGui::Selectable(dc::warp::dungeon(i).name, i == dungeon))
dungeon = i;
ImGui::EndCombo();
}
ImGui::SliderInt("Floor", &floor, 1, dc::warp::dungeon(dungeon).floors);
floor = std::clamp(floor, 1, dc::warp::dungeon(dungeon).floors);
if (ImGui::Button("Warp to that floor"))
dc::warp::requestDungeon(dungeon, floor - 1);
ImGui::TextDisabled("The last floor is the boss's. A floor reached by warp counts as reached on the entrance menu.");
if (ImGui::Button("Teleport to the next monster"))
dc::warp::requestMonster();
ImGui::TextDisabled("In a dungeon: next to the next live monster of the floor, in turn.");
ImGui::Separator();
if (ImGui::Button("Unlock every georama part"))
dc::warp::requestGeorama();
ImGui::TextDisabled("Every town's buildings, villagers and elements, as if every Atla were opened. The dungeons' Atla are then empty.");
if (ImGui::Button("Open the whole world map"))
dc::warp::requestWorld();
ImGui::TextDisabled("Every town and dungeon on the world map, and the World Map item.");
ImGui::Separator();
static int chapter = 2;
if (ImGui::BeginCombo("Story chapter", dc::warp::chapterName(chapter)))
{
for (int i = 1; i <= dc::warp::chapterCount(); ++i)
if (ImGui::Selectable(dc::warp::chapterName(i), i == chapter))
chapter = i;
ImGui::EndCombo();
}
if (ImGui::Button("Advance the story to that chapter"))
dc::warp::requestChapter(chapter);
ImGui::TextWrapped("Sets the story state a playthrough has when that chapter starts (allies and their weapons, the "
"dungeons before it cleared, the places visited). It never moves the story back. Save first: "
"it is meant for testing, and skipped key items and house events are not all recreated.");
});
}
}
+145 -20
View File
@@ -2,16 +2,20 @@
// text buffers, menu-table extensions, save-format changes or console packets.
#include "dc_ingame_cheats.h"
#include "dc_cheats.h"
#include "dc_language.h"
#include "dc_warp.h"
#include "bozo/port.h"
#include "bozo/runtime.h"
#include "bozo/app/video_settings.h"
#include "bozo/render/renderer.h"
#include "bozo/state.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <iterator>
#include <memory>
#include <stdexcept>
@@ -26,7 +30,7 @@ constexpr uint32_t kPhase=0x1da8a50,kFade=0x1da8a54,kLoaded=0x1da8ac4,kPad=0x1cb
constexpr uint32_t kUp=0x1000,kDown=0x4000,kLeft=0x8000,kRight=0x2000,kCross=0x40,kCircle=0x20;
constexpr uint32_t kL1=4,kR1=8,kL2=1,kR2=2;
constexpr float identity[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};
enum class Page { Root, Game, Graphics, Cheats, Quit };
enum class Page { Root, Game, Graphics, Cheats, Quit, Travel, Language }; // new pages last: saved states keep their values
struct Menu {
bool active=false,queued=false;
Page page=Page::Root;
@@ -38,15 +42,22 @@ struct Menu {
bozo::app::video::Settings graphics;
const char *graphicsStatus="";
} menu;
constexpr int rootCount=4;
const char *const rootLabels[rootCount]={"Game Options","Graphics","Cheats","Quit Game"};
enum GraphicsRow { Display, Resolution, RenderScale, FrameRate, ApplyGraphics, GraphicsRowEnd };
constexpr int rootCount=6;
const char *const rootLabels[rootCount]={"Game Options","Graphics","Cheats","Travel","Language","Quit Game"};
const Page rootPages[rootCount]={Page::Game,Page::Graphics,Page::Cheats,Page::Travel,Page::Language,Page::Quit};
// Language: game.ini's choice (dc_language.h), read by the game when it starts; the page saves it for the next start
// (what the game has loaded stays in the language it started in). Not in save states: it is set again on opening.
std::filesystem::path languageFile; // set by the windowed build before the game thread starts; empty: unavailable
struct LanguagePage { int row=0; const language::Choice *running=nullptr,*saved=nullptr; const char *status=""; } languagePage;
const char *const languageLabels[]={"English","Francais","Deutsch","Italiano"}; // the menu font is ASCII
enum GraphicsRow { Display, Resolution, RenderScale, FrameRate, Widescreen, AntiAliasing, Smoothing, ApplyGraphics, GraphicsRowEnd };
constexpr int antiAliasings[]={0,2,4,8},smoothings[]={0,1,2,4,8,16};
constexpr float renderScales[]={0.5f,0.75f,1.f,1.5f,2.f};
RecompiledFunction originalInit=nullptr,originalExit=nullptr,originalKey=nullptr,originalDraw=nullptr;
RecompiledFunction originalHelp=nullptr,originalMessage=nullptr;
constexpr uint32_t kHelp=0x217A60,kMessage=0x153310;
// Rows 0..15 as before; then the level-up, map, fishing, spawner and fast-forward rows.
enum Row { LevelUp=16, RevealMap, FishBite, SpawnItem, SpawnCount, GiveItem, FastSpeed, FastLock, DamageRate, OneHit,
enum Row { LevelUp=16, RevealMap, FishBite, SpawnItem, SpawnCount, GiveItem, FastLock, DamageRate, OneHit,
NoDamage, KeyFinder, RowEnd };
constexpr int rowCount=RowEnd;
// The toggle rows and the cheat each switches.
@@ -130,7 +141,8 @@ namespace video=bozo::app::video;
bool sameGraphics(const video::Settings &a,const video::Settings &b)
{
return a.mode==b.mode && a.width==b.width && a.height==b.height && std::abs(a.renderScale-b.renderScale)<0.01f &&
a.frameRate==b.frameRate;
a.frameRate==b.frameRate && a.widescreen==b.widescreen && a.antiAliasing==b.antiAliasing &&
a.textureSmoothing==b.textureSmoothing;
}
int renderScaleIndex(float scale)
{
@@ -153,6 +165,9 @@ std::string graphicsValue(int row,const video::Settings &g,const video::Shared &
if(g.frameRate<0)std::snprintf(text,sizeof(text),"Monitor %d Hz",shared.monitorRefresh);
else std::snprintf(text,sizeof(text),"%d fps",g.frameRate);
}
if(row==Widescreen)return g.widescreen?"16:9":"Off";
if(row==AntiAliasing)return g.antiAliasing?std::to_string(g.antiAliasing)+"x":"Off";
if(row==Smoothing)return g.textureSmoothing==0?"Off":g.textureSmoothing==1?"Trilinear":std::to_string(g.textureSmoothing)+"x";
return text;
}
// Left/Right on a graphics row: the next choice that way.
@@ -171,6 +186,13 @@ void stepGraphics(int row,int way,const video::Shared &shared)
if(shared.applied.frameRate>0)rates.push_back(shared.applied.frameRate);
int at=0;for(int i=0;i<int(rates.size());++i)if(rates[i]==g.frameRate)at=i;
g.frameRate=rates[(at+int(rates.size())+way)%int(rates.size())];
}else if(row==Widescreen)g.widescreen=!g.widescreen;
else if(row==AntiAliasing){
int at=0;for(int i=0;i<int(std::size(antiAliasings));++i)if(antiAliasings[i]==g.antiAliasing)at=i;
g.antiAliasing=antiAliasings[std::clamp(at+way,0,int(std::size(antiAliasings))-1)];
}else if(row==Smoothing){
int at=0;for(int i=0;i<int(std::size(smoothings));++i)if(smoothings[i]==g.textureSmoothing)at=i;
g.textureSmoothing=smoothings[std::clamp(at+way,0,int(std::size(smoothings))-1)];
}
menu.graphicsStatus="";
}
@@ -181,9 +203,9 @@ void drawGraphics(std::vector<bozo::render::Vertex> &v,uint32_t white,uint32_t g
text(v,"Window settings are not",156,170,1.25f,white);text(v,"available in this run.",156,200,1.25f,white);
text(v,"O: Back",292,352,1,white);return;
}
const char *labels[]={"Display","Resolution","Render scale","Frame rate","Apply and save"};
const char *labels[]={"Display","Resolution","Render scale","Frame rate","Widescreen","Anti-aliasing","Texture smoothing","Apply and save"};
for(int i=0;i<GraphicsRowEnd;++i){
const float y=120.f+i*34+(i==ApplyGraphics?12:0);
const float y=112.f+i*26+(i==ApplyGraphics?8:0);
const bool locked=i==Resolution && menu.graphics.mode==video::WindowMode::Borderless;
const auto c=i==menu.graphicsRow?gold:locked?dim:white;
text(v,labels[i],140,y,1.25f,c);if(i==menu.graphicsRow)text(v,">",120,y,1.25f,c);
@@ -194,24 +216,89 @@ void drawGraphics(std::vector<bozo::render::Vertex> &v,uint32_t white,uint32_t g
}
const std::string now="Now: "+graphicsValue(Display,shared.applied,shared)+", "+graphicsValue(Resolution,shared.applied,shared)+
", "+graphicsValue(RenderScale,shared.applied,shared)+", "+graphicsValue(FrameRate,shared.applied,shared);
text(v,now,320-float(now.size())*3.6f,312,0.9f,dim);
text(v,now,320-float(now.size())*3.6f,330,0.9f,dim);
const char *help=menu.graphicsRow==Display?"L/R: Window, full screen or borderless":
menu.graphicsRow==Resolution?(menu.graphics.mode==video::WindowMode::Borderless?"Borderless uses the monitor size":"L/R: Window or full-screen size"):
menu.graphicsRow==RenderScale?"L/R: 3D resolution against the window":
menu.graphicsRow==FrameRate?"L/R: Monitor smooths between frames":"X: Apply now and keep for next launch";
menu.graphicsRow==FrameRate?"L/R: Monitor smooths between frames":
menu.graphicsRow==Widescreen?"L/R: 16:9, more at the sides, HUD at the edges":
menu.graphicsRow==AntiAliasing?"L/R: Smoother edges, 2x to 8x":
menu.graphicsRow==Smoothing?"L/R: Smoother textures at a distance":"X: Apply now and keep for next launch";
if(*menu.graphicsStatus)help=menu.graphicsStatus;
else if(!sameGraphics(menu.graphics,shared.applied) && menu.graphicsRow!=ApplyGraphics)help="Not applied yet: choose Apply and save";
text(v,help,320-float(std::strlen(help))*4,354,1,white);
}
// The Travel page (dc_warp.h): its choices live outside Menu, so a save state's menu record keeps its layout.
enum TravelRow { TownChoice, WarpTown, DungeonChoice, FloorChoice, WarpFloor, NextMonster, Georama, World, ChapterChoice, Advance, TravelRowEnd };
struct Travel { int row=0,place=0,dungeon=0,floor=1,chapter=2; const char *note=""; } travel;
void drawTravel(std::vector<bozo::render::Vertex> &v,uint32_t white,uint32_t gold,uint32_t dim)
{
const char *labels[]={"Town or area","Warp to the town","Dungeon","Floor","Warp to the floor","Next monster",
"Unlock georama parts","Open the world map","Story chapter","Advance the story"};
const int first=std::max(0,travel.row-5);
for(int i=first;i<std::min(first+6,int(TravelRowEnd));++i){
const float y=126.f+(i-first)*34;const auto c=i==travel.row?gold:white;
text(v,labels[i],128,y,1.25f,c);if(i==travel.row)text(v,">",108,y,1.25f,c);
std::string value;
if(i==TownChoice)value=dc::warp::place(travel.place).name;
if(i==DungeonChoice)value=dc::warp::dungeon(travel.dungeon).name;
if(i==FloorChoice)value=std::to_string(travel.floor)+"/"+std::to_string(dc::warp::dungeon(travel.dungeon).floors);
if(i==ChapterChoice)value=dc::warp::chapterShort(travel.chapter);
if(i==travel.row && !value.empty())value="< "+value+" >";
text(v,value,526-float(value.size())*10,y,1.25f,c);
}
char count[32];std::snprintf(count,sizeof(count),"%d/%d",travel.row+1,int(TravelRowEnd));text(v,count,470,88,1,dim);
const char *help=travel.row==TownChoice?"L/R: 1 L1/R1: 10":travel.row==DungeonChoice?"L/R: Choose a dungeon":
travel.row==FloorChoice?"L/R: 1 L1/R1: 10 The last is the boss":travel.row==ChapterChoice?"L/R: Choose Save first":
travel.row==NextMonster?"X: In a dungeon, next to a monster":travel.row==Georama?"X: Every town's parts":
travel.row==World?"X: Every place on the world map":travel.row==Advance?"X: Never moves the story back":"X: Go when play resumes";
if(*travel.note)help=travel.note;
text(v,help,112,354,1,white);
}
void travelKey(uint32_t pressed)
{
if(pressed&kUp)travel.row=(travel.row+TravelRowEnd-1)%TravelRowEnd;else if(pressed&kDown)travel.row=(travel.row+1)%TravelRowEnd;
if(pressed&(kUp|kDown))travel.note="";
int delta=0;if(pressed&kLeft)--delta;if(pressed&kRight)++delta;if(pressed&kL1)delta-=10;if(pressed&kR1)delta+=10;
const int places=dc::warp::placeCount(),dungeons=dc::warp::dungeonCount();
if(travel.row==TownChoice && delta)travel.place=((travel.place+delta)%places+places)%places;
if(travel.row==DungeonChoice && delta){travel.dungeon=((travel.dungeon+(delta>0?1:-1))%dungeons+dungeons)%dungeons;
travel.floor=std::min(travel.floor,dc::warp::dungeon(travel.dungeon).floors);}
if(travel.row==FloorChoice && delta)travel.floor=std::clamp(travel.floor+delta,1,dc::warp::dungeon(travel.dungeon).floors);
if(travel.row==ChapterChoice && delta)travel.chapter=std::clamp(travel.chapter+(delta>0?1:-1),1,dc::warp::chapterCount());
if(!(pressed&kCross))return;
const char *queued="Queued: close Options to go";
if(travel.row==WarpTown){dc::warp::requestPlace(dc::warp::place(travel.place).map);travel.note=queued;}
else if(travel.row==WarpFloor){dc::warp::requestDungeon(travel.dungeon,travel.floor-1);travel.note=queued;}
else if(travel.row==NextMonster){dc::warp::requestMonster();travel.note=queued;}
else if(travel.row==Georama){dc::warp::requestGeorama();travel.note="Queued: given when play resumes";}
else if(travel.row==World){dc::warp::requestWorld();travel.note="Queued: opened when play resumes";}
else if(travel.row==Advance){dc::warp::requestChapter(travel.chapter);travel.note="Queued: applied when play resumes";}
}
void drawLanguage(std::vector<bozo::render::Vertex> &v,uint32_t white,uint32_t gold,uint32_t dim)
{
const auto &list=language::choices();
for(int i=0;i<int(list.size());++i){
const float y=130.f+i*34;const auto c=i==languagePage.row?gold:white;
text(v,languageLabels[i],164,y,1.5f,c);if(i==languagePage.row)text(v,">",132,y,1.5f,c);
const char *note=&list[i]==languagePage.running?"in use":&list[i]==languagePage.saved?"next start":"";
text(v,note,526-float(std::strlen(note))*10,y+4,1.25f,dim);
}
text(v,"Text and menus change when the game",128,282,1,white);
text(v,"starts again. Spanish is incomplete on disc.",128,300,1,white);
const char *help=languageFile.empty()?"Needs the game window; O: Back":*languagePage.status?languagePage.status:"X: Choose for the next start O: Back";
text(v,help,112,354,1,white);
}
void drawPage(int alpha)
{
if(prepareScene)prepareScene();panel(alpha);
std::vector<bozo::render::Vertex> v;
const uint32_t white=colour(0x808080,alpha),gold=colour(0x207080,alpha),dim=colour(0x484848,alpha);
const auto heading=menu.page==Page::Root?"OPTIONS":menu.page==Page::Quit?"QUIT GAME?":menu.page==Page::Graphics?"GRAPHICS":"CHEATS";
const auto heading=menu.page==Page::Root?"OPTIONS":menu.page==Page::Quit?"QUIT GAME?":menu.page==Page::Graphics?"GRAPHICS":
menu.page==Page::Travel?"TRAVEL":menu.page==Page::Language?"LANGUAGE":"CHEATS";
text(v,heading,320-float(std::strlen(heading))*8,76,2,gold);
if(menu.page==Page::Root){
for(int i=0;i<rootCount;++i){const float y=136.f+i*44;const auto c=i==menu.root?gold:white;text(v,rootLabels[i],164,y,1.5f,c);if(i==menu.root)text(v,">",132,y,1.5f,c);}
for(int i=0;i<rootCount;++i){const float y=120.f+i*36;const auto c=i==menu.root?gold:white;text(v,rootLabels[i],164,y,1.5f,c);if(i==menu.root)text(v,">",132,y,1.5f,c);}
text(v,"D-pad: Select X: Open O: Back",120,352,1,white);
}else if(menu.page==Page::Quit){
text(v,"Close the game?",200,150,1.5f,white);
@@ -221,12 +308,16 @@ void drawPage(int alpha)
text(v,"X: Confirm O: Cancel",164,352,1,white);
}else if(menu.page==Page::Graphics){
drawGraphics(v,white,gold,dim);
}else if(menu.page==Page::Travel){
drawTravel(v,white,gold,dim);
}else if(menu.page==Page::Language){
drawLanguage(v,white,gold,dim);
}else{
const char *labels[]={"Infinite health","Weapon durability","Infinite thirst","Combo stamina",
"Equipped weapon ATK","Apply weapon ATK","Weapon ABS multiplier","Gilda","Apply Gilda",
"Active consumable slot","Consumable quantity","Apply quantity","Movement speed","Freeze time of day",
"Inventory size","Apply inventory size","Level up equipped weapon","Reveal floor map","Fish always bite",
"Spawn item","Spawn count","Give item","Fast-forward speed","Fast-forward always on","Damage multiplier",
"Spawn item","Spawn count","Give item","Fast-forward always on","Damage multiplier",
"One-hit kills","No damage taken","Key finder"};
const int first=std::max(0,menu.row-5);
for(int i=first;i<std::min(first+6,rowCount);++i){
@@ -243,7 +334,6 @@ void drawPage(int alpha)
if(i==14)value=inventorySize()<0?"---":std::to_string(menu.capacity);
if(i==SpawnItem)value=spawnItemCount()?spawnItem(menu.spawn).name:"---";
if(i==SpawnCount)value=std::to_string(menu.spawnCount);
if(i==FastSpeed)value=std::to_string(fastForwardPercent())+"%";
if(i==DamageRate)value=std::to_string(damageMultiplier())+"x";
text(v,value,526-float(value.size())*10,y,1.25f,c);
}
@@ -251,7 +341,7 @@ void drawPage(int alpha)
const char *help="L/R: 1 L1/R1: 10 L2/R2: 100 O: Back";
if(Cheat cheat;toggleRow(menu.row,cheat))
help=menu.row==RevealMap?"X: Toggle Whole floor shown on the map":menu.row==FishBite?"X: Toggle Fish bite and stay hooked":
menu.row==FastLock?"X: Toggle Sound is muted while fast":
menu.row==FastLock?"X: Toggle Video tab speed, sound muted":
menu.row==OneHit?"X: Toggle Any hit that deals damage kills":
menu.row==NoDamage?"X: Toggle Monster attacks never land":
menu.row==KeyFinder?"X: Toggle Key holder blinks gold on the map":"X: Toggle Left/Right: Set O: Back";
@@ -265,7 +355,6 @@ void drawPage(int alpha)
else if(menu.row==SpawnItem)help=spawnItemCount()?"L/R: 1 L1/R1: 10 Story items excluded":"Item names load with the game";
else if(menu.row==SpawnCount)help="L/R: 1 Each one takes a bag slot";
else if(menu.row==GiveItem)help="X: Give when play resumes O: Back";
else if(menu.row==FastSpeed)help="L/R: 50% Hold ` or the touchpad";
else if(menu.row==DamageRate)help="L/R: 1x Damage you deal to monsters";
if((menu.row==4 || menu.row==5 || menu.row==LevelUp) && equippedWeaponAttack()<0)help="No weapon equipped O: Back";
if((menu.row==10 || menu.row==11) && activeConsumable(menu.slot).id<0)help="Equip a consumable in this HUD slot first";
@@ -291,6 +380,14 @@ void init(uint8_t *r,R5900Context *c,Runtime *rt)
refreshPlayer(r,c);menu={};menu.active=true;menu.font=fontFromGame(r);if(!menu.font)menu.page=Page::Game;
originalInit(r,c,rt);
}
void openLanguage(const uint8_t *r)
{
languagePage={};languagePage.running=language::current(r);
languagePage.saved=languageFile.empty()?nullptr:language::find(language::readIni(languageFile));
if(!languagePage.saved)languagePage.saved=languagePage.running;
const auto &list=language::choices();
for(int i=0;i<int(list.size());++i)if(&list[i]==languagePage.saved)languagePage.row=i;
}
void exit(uint8_t *r,R5900Context *c,Runtime *rt){applyPlayerEdits(r,c);menu={};originalExit(r,c,rt);}
void key(uint8_t *r,R5900Context *c,Runtime *rt)
{
@@ -301,7 +398,7 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
return;
}
if(pressed&kCircle){
if(menu.page==Page::Cheats || menu.page==Page::Graphics || menu.page==Page::Quit){menu.page=Page::Root;menu.held=menu.ticks=0;done(c);}
if(menu.page==Page::Cheats || menu.page==Page::Graphics || menu.page==Page::Quit || menu.page==Page::Travel || menu.page==Page::Language){menu.page=Page::Root;menu.held=menu.ticks=0;done(c);}
else {
// The original Circle boundary starts this fade. Do not also run
// hidden Game Options navigation if Circle and a direction coincide.
@@ -311,8 +408,9 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
}
if(menu.page==Page::Root){
if(pressed&kUp)menu.root=(menu.root+rootCount-1)%rootCount;else if(pressed&kDown)menu.root=(menu.root+1)%rootCount;
if(pressed&kCross){menu.page=menu.root==0?Page::Game:menu.root==1?Page::Graphics:menu.root==2?Page::Cheats:Page::Quit;
menu.graphics=windowSettings().applied;menu.graphicsRow=0;menu.graphicsStatus="";menu.quitChoice=0;menu.held=menu.ticks=0;menu.attack=std::max(0,equippedWeaponAttack());menu.gold=std::max(0,gilda());menu.capacity=std::clamp(inventorySize(),1,100);menu.quantity=std::max(1,activeConsumable(menu.slot).quantity);menu.queued=false;}
if(pressed&kCross){menu.page=rootPages[menu.root];travel.note="";
menu.graphics=windowSettings().applied;menu.graphicsRow=0;menu.graphicsStatus="";menu.quitChoice=0;menu.held=menu.ticks=0;menu.attack=std::max(0,equippedWeaponAttack());menu.gold=std::max(0,gilda());menu.capacity=std::clamp(inventorySize(),1,100);menu.quantity=std::max(1,activeConsumable(menu.slot).quantity);menu.queued=false;
if(menu.page==Page::Language)openLanguage(r);}
}else if(menu.page==Page::Graphics){
const video::Shared shared=windowSettings();
if(shared.open){
@@ -326,6 +424,19 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
if(const auto post=videoPost.load(std::memory_order_acquire))post(next,true);menu.graphics=next;menu.graphicsStatus="Applied and saved";
}
}
}else if(menu.page==Page::Travel){
travelKey(pressed);
}else if(menu.page==Page::Language){
const int count=int(language::choices().size());
if(pressed&kUp)languagePage.row=(languagePage.row+count-1)%count;else if(pressed&kDown)languagePage.row=(languagePage.row+1)%count;
if(pressed&(kUp|kDown))languagePage.status="";
if((pressed&kCross) && !languageFile.empty()){
const language::Choice &choice=language::choices()[languagePage.row];
if(language::writeIni(languageFile,choice)){
languagePage.saved=&choice;
languagePage.status=&choice==languagePage.running?"Saved; already in use":"Saved; restart the game to apply";
}else languagePage.status="Could not save game.ini";
}
}else if(menu.page==Page::Quit){
if(pressed&(kUp|kDown|kLeft|kRight))menu.quitChoice^=1;
if(pressed&kCross){if(menu.quitChoice)quitRequested.store(true,std::memory_order_relaxed);else menu.page=Page::Root;}
@@ -355,7 +466,6 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
}
else if(menu.row==SpawnCount && delta)menu.spawnCount=std::clamp(menu.spawnCount+(delta>0?1:-1),1,10);
else if(menu.row==GiveItem && spawnItemCount() && (pressed&kCross)){requestSpawn(spawnItem(menu.spawn).id,menu.spawnCount);menu.queued=true;}
else if(menu.row==FastSpeed && delta)setFastForwardPercent(fastForwardPercent()+(delta>0?50:-50));
else if(menu.row==DamageRate && delta)setDamageMultiplier(damageMultiplier()+delta);
}
@@ -395,6 +505,21 @@ void installIngameMenu(Runtime &rt,bozo::port::Registry &registry,void (*prepare
registry.registerFunction(kInit,init);registry.registerFunction(kExit,exit);registry.registerFunction(kKey,key);registry.registerFunction(kDraw,draw);
}
bool takeIngameQuitRequest(){return quitRequested.exchange(false,std::memory_order_relaxed);}
// Save states: the native Options pages' state (a state may be saved with them open); the font is decoded again from the
// loaded game's atlas, and no quit request of the replaced run survives.
void menuState(bozo::state::Archive &a,const uint8_t *ram)
{
auto &g=menu.graphics;
bozo::state::fields(a,menu.active,menu.queued,menu.page,menu.root,menu.row,menu.attack,menu.quitChoice,menu.gold,menu.slot,
menu.quantity,menu.capacity,menu.spawn,menu.spawnCount,menu.held,menu.ticks,menu.graphicsRow,
g.width,g.height,g.mode,g.renderScale,g.gsScale,g.frameRate);
if(!a.loading())return;
menu.font=menu.active?fontFromGame(ram):nullptr;
menu.graphicsStatus="";
if(menu.active && menu.page==Page::Language)openLanguage(ram);
quitRequested.store(false,std::memory_order_relaxed);
}
void setLanguageFile(const std::filesystem::path &file){languageFile=file;}
void setGraphicsAccess(bozo::app::video::Shared (*shared)(),void (*post)(const bozo::app::video::Settings &,bool))
{videoPost.store(post,std::memory_order_release);videoShared.store(shared,std::memory_order_release);}
}
+7
View File
@@ -1,7 +1,9 @@
#pragma once
#include "bozo/app/video_settings.h"
#include <filesystem>
struct Runtime;
namespace bozo::port { class Registry; }
namespace bozo::state { class Archive; }
namespace dc::cheats {
// The original Options lifecycle stays in charge of loading, fading and
// returning to gameplay. Native pages share the existing cheat controls.
@@ -10,4 +12,9 @@ namespace dc::cheats {
// The windowed build, before the game thread starts: the window's settings for the Graphics page (without them,
// as headless, the page says they are unavailable).
void setGraphicsAccess(bozo::app::video::Shared (*shared)(), void (*post)(const bozo::app::video::Settings &, bool));
// The windowed build, before the game thread starts: game.ini, where the Language page saves the choice for the
// next start (without it, as headless, the page says it needs the game window).
void setLanguageFile(const std::filesystem::path &gameIni);
// Save states: the native Options pages' state; on load the font is decoded again from `ram`.
void menuState(bozo::state::Archive &, const uint8_t *ram);
}
+79
View File
@@ -0,0 +1,79 @@
#include "dc_language.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <fstream>
namespace dc::language
{
const std::vector<Choice> &choices()
{
static const std::vector<Choice> list = {
{"en", "English", 1}, {"fr", "Fran\xC3\xA7" "ais", 3}, {"de", "Deutsch", 4}, {"it", "Italiano", 5}};
return list;
}
const Choice *find(const std::string &key)
{
std::string k = key;
std::transform(k.begin(), k.end(), k.begin(), [](unsigned char c) { return char(std::tolower(c)); });
for (const Choice &c : choices())
if (k == c.key)
return &c;
return nullptr;
}
std::string readIni(const std::filesystem::path &file)
{
std::ifstream in(file);
std::string line, value;
auto trim = [](std::string s)
{
const size_t first = s.find_first_not_of(" \t\r");
return first == std::string::npos ? std::string() : s.substr(first, s.find_last_not_of(" \t\r") - first + 1);
};
while (std::getline(in, line))
{
line = trim(line.substr(0, line.find_first_of("#;")));
const size_t equal = line.find('=');
if (line.empty() || line.front() == '[' || equal == std::string::npos)
continue;
if (trim(line.substr(0, equal)) == "language")
value = trim(line.substr(equal + 1));
}
return value;
}
bool writeIni(const std::filesystem::path &file, const Choice &choice)
{
const std::filesystem::path tmp = file.string() + ".tmp";
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
out << "# Dark Cloud's own settings (the launcher and RecompLauncher write this file; the game reads it when it starts).\n"
"# language: en (English), fr (French), de (German) or it (Italian), from the disc's own text and menus.\n"
"\n[game]\nlanguage = "
<< choice.key << "\n";
if (!out)
return false;
}
std::error_code ec;
std::filesystem::rename(tmp, file, ec);
return !ec;
}
const Choice *current(const uint8_t *ram)
{
uint32_t code = 0;
std::memcpy(&code, ram + kLanguageCode, sizeof(code));
for (const Choice &c : choices())
if (c.code == code)
return &c;
return nullptr;
}
void apply(uint8_t *ram, const Choice &choice)
{
std::memcpy(ram + kLanguageCode, &choice.code, sizeof(choice.code));
}
} // namespace dc::language
+39
View File
@@ -0,0 +1,39 @@
#pragma once
// The game's language. The USA disc carries the European release's French, German and Italian text and menus next
// to the English ones (message files <name>_<n>.mes, menu folders commenu/a_<lang>), and its program still has the
// European language code: LanguageCode (0x2A1E88, 1 on the USA disc) picks the files when the game loads them. The
// port sets it at boot from --language or <user folder>/game.ini. Spanish (6) is not offered: the USA disc lacks 42
// of its 90 story text files.
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>
namespace dc::language
{
constexpr uint32_t kLanguageCode = 0x2A1E88;
struct Choice
{
const char *key; // in game.ini and --language
const char *name; // in its own language
uint32_t code; // LanguageCode
};
const std::vector<Choice> &choices(); // English (1), French (3), German (4), Italian (5)
// A choice by key ("en", "fr", "de", "it"; any case), or nullptr.
const Choice *find(const std::string &key);
// game.ini's "language" value: name = value lines, '#' and ';' start comments, [sections] are skipped; "" when the
// file or the key is missing.
std::string readIni(const std::filesystem::path &file);
// Writes game.ini with that language (as the launcher writes it); false when it cannot.
bool writeIni(const std::filesystem::path &file, const Choice &choice);
// The choice LanguageCode in guest memory holds, or nullptr (Spanish, or a code no choice has).
const Choice *current(const uint8_t *ram);
// The game's language for its next loads: LanguageCode in guest memory (before the first frame).
void apply(uint8_t *ram, const Choice &choice);
} // namespace dc::language
+123 -31
View File
@@ -6,6 +6,14 @@
#include "dc_functions.h"
#include "dc_cheats.h"
#include "dc_ingame_cheats.h"
#include "dc_language.h"
#include "dc_pad.h"
#include "dc_state.h"
#include "dc_warp.h"
#include <string>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include "dc_native_api.h"
#include "dun_functions.h"
#include "title_functions.h"
@@ -21,45 +29,28 @@
#include "bozo/app/app.h"
#include "bozo/app/audio_device.h"
#include "bozo/app/device_pad.h"
#include "bozo/app/video_settings.h"
#include "bozo/app/window.h"
#include <SDL3/SDL.h>
#endif
namespace dc
{
void installAudio(bozo::libs::Libraries &);
void install(Runtime &, bozo::port::Registry &);
} // namespace dc
#ifdef DC_WITH_WINDOW
namespace
{
// The fast-forward hold: the ` key (by position, below Esc), or a gamepad's touchpad / Share (MISC1) button. None
// of them is in the default PS2 bindings. SDL releases the keys when the window loses the keyboard.
bool fastForwardHeld()
{
bool held = false;
if (const bool *keys = SDL_GetKeyboardState(nullptr))
held = keys[SDL_SCANCODE_GRAVE];
int count = 0;
if (SDL_JoystickID *ids = SDL_GetGamepads(&count))
{
for (int i = 0; i < count && !held; ++i)
if (SDL_Gamepad *pad = SDL_GetGamepadFromID(ids[i]))
held = SDL_GetGamepadButton(pad, SDL_GAMEPAD_BUTTON_TOUCHPAD) ||
SDL_GetGamepadButton(pad, SDL_GAMEPAD_BUTTON_MISC1);
SDL_free(ids);
}
return held;
}
}
#endif
int main(int argc, char **argv)
{
bozo::host::FreeOptions options;
options.framePeriodCycles = 294912000 / 60;
bool window = false;
[[maybe_unused]] bool mute = false; // no sound device: --mute, and every --hidden run
std::string cheatScript; // --cheat-script FILE
#ifdef DC_WITH_WINDOW
window = true;
bozo::app::setIdentity({"Dark Cloud", "DC_Recomp", "dc-recomp", "SCUS_971.11"});
// What the game prints goes on to its console or pipe as before, and also into <user folder>/logs/<name>.log (the
// launcher's "Open game logs", RecompLauncher's Logs); a crash writes <user folder>/crashes/crash-<time>.txt.
bozo::app::startLogging();
bozo::app::installCrashHandler();
bozo::app::WindowOptions windowOptions;
windowOptions.title = "Dark Cloud - BozoEngine";
windowOptions.width = 960;
@@ -69,7 +60,7 @@ int main(int argc, char **argv)
options.iso = DC_DEFAULT_ISO;
options.frames = window ? 0 : 120;
options.printGameOutput = true;
std::string wav, livePad, assetDir;
std::string wav, livePad, assetDir, dumpRam, language; // language: --language, else game.ini's
for (int i = 1; i < argc; ++i)
{
const std::string a = argv[i];
@@ -91,15 +82,33 @@ int main(int argc, char **argv)
options.iso = argv[++i];
else if (a == "--wav" && i + 1 < argc)
wav = argv[++i];
else if (a == "--language" && i + 1 < argc) // en, fr, de, it (dc_language.h)
language = argv[++i];
else if (a == "--headless")
window = false;
else if (a == "--profile-io")
options.profileIo = true;
else if (a == "--dump-ram" && i + 1 < argc)
dumpRam = argv[++i];
else if (a == "--load-state" && i + 1 < argc)
options.loadState = argv[++i];
else if (a == "--load-state-at" && i + 1 < argc)
options.loadStateFrame = std::stoul(argv[++i]);
else if (a == "--save-state" && i + 1 < argc)
options.saveState = argv[++i];
else if (a == "--save-state-at" && i + 1 < argc)
options.saveStateFrame = std::stoul(argv[++i]);
#ifdef DC_WITH_WINDOW
else if (a == "--no-vsync")
windowOptions.vsync = false;
else if (a == "--fullscreen")
windowOptions.fullscreen = true;
else if (a == "--hidden") // never shown, and silent; captures read the game's offscreen picture
windowOptions.hidden = mute = true;
else if (a == "--cheat-script" && i + 1 < argc) // travel/progress commands by frame (dc_warp.cpp)
cheatScript = argv[++i];
else if (a == "--mute") // no sound device (a --wav recording still gets every sample)
mute = true;
else if (a == "--capture-dir" && i + 1 < argc)
windowOptions.captureDir = argv[++i];
else if (a == "--capture-frame" && i + 1 < argc)
@@ -110,7 +119,9 @@ int main(int argc, char **argv)
std::fprintf(stderr, "Usage: dc [--frames N] [--headless] [--elf FILE] [--iso FILE]\n"
" [--asset-dir DIR] [--card-dir DIR] [--pad-script FILE | --live-pad FILE] [--wav FILE]\n"
" [--out FILE] [--capture-dir DIR] [--capture-frame N] [--profile-io]\n"
" [--fullscreen] [--no-vsync]\n");
" [--fullscreen] [--hidden] [--mute] [--no-vsync] [--dump-ram FILE]\n"
" [--load-state FILE [--load-state-at FRAME]] [--save-state FILE --save-state-at FRAME]\n"
" [--cheat-script FILE] [--language en|fr|de|it]\n");
return a == "--help" ? 0 : 2;
}
}
@@ -121,6 +132,8 @@ int main(int argc, char **argv)
options.cardDir = bozo::app::userDirectory().string();
}
#endif
if (!cheatScript.empty() && !dc::warp::loadScript(cheatScript))
return 2;
if (assetDir.empty())
{
const auto besideElf = std::filesystem::absolute(options.elf).parent_path();
@@ -128,6 +141,7 @@ int main(int argc, char **argv)
}
dc::native::setAssetDirectory(assetDir);
options.realTime = window;
options.gameTag = "SCUS-97111"; // a save state loads only into Dark Cloud
bozo::host::FreeHost host(options);
bozo::ee::Dispatcher d(host);
dc::installAudio(host.libraries());
@@ -135,7 +149,12 @@ int main(int argc, char **argv)
bozo::port::Registry registry;
dc::install(d.runtime(), registry);
dc::cheats::install(d.runtime(), registry);
dc::warp::install(d.runtime(), registry);
dc::cheats::installIngameMenu(d.runtime(), registry, dc::native::finishSceneForMenu);
dc::pad::install(registry);
// Save states: DC's own part (the engine saves its runtime, libraries and host).
host.stateSections()->add({"dc", [&](bozo::state::Archive &a) { dc::state::serialize(a, d.runtime()); },
[] { return dc::state::unsaveable(); }});
std::string error;
if (!host.setUp(d, dc_external_table, dc_external_count, &registry, error))
{
@@ -152,6 +171,33 @@ int main(int argc, char **argv)
d.runtime().functions.addModule(0x1dabd00, 0x1f00000, d.runtime().memory.ram() + 0x1dabd00, std::move(id),
table, count, resume, resumes);
};
// The game's language (dc_language.h): --language, else <user folder>/game.ini (the launcher's and RecompLauncher's
// Game language), else English. The program is in memory now and has not run: its first file loads use it.
bool languageFromIni = false;
#ifdef DC_WITH_WINDOW
if (language.empty() && window && !bozo::app::userDirectory().empty())
{
language = dc::language::readIni(bozo::app::userDirectory() / "game.ini");
languageFromIni = !language.empty();
}
#endif
if (!language.empty())
{
const dc::language::Choice *choice = dc::language::find(language);
if (!choice && !languageFromIni)
{
std::fprintf(stderr, "--language %s: not one of en, fr, de, it\n", language.c_str());
return 2;
}
if (!choice)
std::fprintf(stderr, "[dc] game.ini: language '%s' is not one of en, fr, de, it; English\n", language.c_str());
else
{
dc::language::apply(d.runtime().memory.ram(), *choice);
if (choice->code != 1)
std::printf("[dc] language: %s (%s)\n", choice->name, choice->key);
}
}
module("title", title_function_table, title_function_count, title_resume_table, title_resume_count);
module("dun", dun_function_table, dun_function_count, dun_resume_table, dun_resume_count);
bozo::app::FramePacer pacer;
@@ -159,14 +205,34 @@ int main(int argc, char **argv)
const uint32_t normalCap = pacer.cap(); // 60, or PS2X_FRAME_CAP (0: unlimited, left alone)
host.onFrame = [&](uint64_t f, const R5900Context *ctx)
{
dc::warp::onFrame(f);
if (dc::cheats::takeIngameQuitRequest()) host.requestStop();
#ifdef DC_WITH_WINDOW
// Fast-forward always on runs at the Video tab's fast-forward speed (the one the engine's hold uses).
if (window && dc::cheats::enabled(dc::cheats::Cheat::FastForwardLock))
if (const auto shared = bozo::app::video::shared(); shared.open)
dc::cheats::setFastForwardPercent(shared.applied.fastForward);
// Widescreen (the Video tab, video.ini's widescreen, PS2X_WIDESCREEN): a 16:9 picture showing more at the sides,
// the HUD at the edges. A hidden run (a test) reads it from the environment alone, never the player's video.ini.
if (window)
dc::cheats::setFastForwardHeld(fastForwardHeld());
{
static const bool s_hiddenWide = [] { const char *e = std::getenv("PS2X_WIDESCREEN"); return e && (e[0] == '1' || e[0] == 'o'); }();
bool wide = s_hiddenWide;
if (!windowOptions.hidden)
if (const auto shared = bozo::app::video::shared(); shared.open)
wide = shared.applied.widescreen;
dc::native::setWidescreen(wide);
bozo::app::setPictureAspect(wide ? 16.0f / 9.0f : 0.0f);
}
#endif
// Fast-forward raises the cap: the game's logic and clock advance per frame, so it simply runs more of them.
// Fast-forward always on raises the cap: the game's logic and clock advance per frame, so it simply runs more
// of them. While the engine's fast forward is held (FramePacer::speedPercent), the pacer already runs the cap at
// that speed: the cap stays normal then, so the two never stack.
if (normalCap)
pacer.setCap(normalCap * static_cast<uint32_t>(dc::cheats::gameSpeedPercent()) / 100u);
{
const bool engineFast = bozo::app::FramePacer::speedPercent().load(std::memory_order_relaxed) != 100u;
pacer.setCap(engineFast ? normalCap : normalCap * static_cast<uint32_t>(dc::cheats::gameSpeedPercent()) / 100u);
}
pacer.frameEnd();
if (f % 60 == 0)
std::printf("[dc] frame=%llu pc=%x cycles=%llu\n", (unsigned long long)f, ctx->pc,
@@ -194,14 +260,15 @@ int main(int argc, char **argv)
#ifdef DC_WITH_WINDOW
// Muted while fast-forwarding: sound made faster than real time would overflow the device's queue and be
// dropped in bursts. A WAV recording keeps every sample.
if (window && dc::cheats::gameSpeedPercent() == 100)
if (window && !mute && dc::cheats::gameSpeedPercent() == 100 &&
bozo::app::FramePacer::speedPercent().load(std::memory_order_relaxed) == 100u)
audio.push(pcm, count);
#endif
};
auto run = [&]()
{
#ifdef DC_WITH_WINDOW
if (window)
if (window && !mute)
audio.open();
#endif
uint64_t frames = 0;
@@ -214,11 +281,29 @@ int main(int argc, char **argv)
std::fprintf(stderr, "[dc] native failure: %s\n", e.what());
return 1;
}
if (!dumpRam.empty())
if (FILE *f = std::fopen(dumpRam.c_str(), "wb"))
{
std::fwrite(d.runtime().memory.ram(), 1, 0x2000000u, f);
std::fclose(f);
}
std::printf("[dc] frames=%llu end=%s\n", (unsigned long long)frames, host.endReason().c_str());
const auto &stats = host.stats();
std::printf("[dc] compatibility: %llu register accesses, %llu unknown; %llu native VU0 calls\n",
(unsigned long long)stats.ioAccesses, (unsigned long long)stats.ioUnknown,
(unsigned long long)stats.vu0Calls);
std::printf("[dc] calls: %llu kernel, %llu library, %llu port overrides\n", (unsigned long long)stats.kernelCalls,
(unsigned long long)stats.libraryCalls, (unsigned long long)stats.overrideCalls);
// DC_CALL_STATS=1: the native library calls by function, most first.
if (std::getenv("DC_CALL_STATS"))
{
std::vector<std::pair<uint64_t, std::string>> byName;
for (const auto &[name, count] : stats.libraryByName)
byName.emplace_back(count, name);
std::sort(byName.rbegin(), byName.rend());
for (const auto &[count, name] : byName)
std::printf("[dc:lib] %10llu %s\n", (unsigned long long)count, name.c_str());
}
const auto &io = host.libraries().io;
for (const auto &[site, counts] : stats.ioSites)
std::printf("[dc:io] pc=%08x address=%08x reads=%llu writes=%llu %s\n", site.first, site.second,
@@ -239,11 +324,18 @@ int main(int argc, char **argv)
if (windowOptions.fullscreen)
bozo::app::video::edited().mode = bozo::app::video::WindowMode::Borderless;
windowOptions.videoSettings = true;
bozo::app::video::offerWidescreen(true); // the Video tab's Widescreen (see the frame hook)
dc::cheats::setGraphicsAccess(&bozo::app::video::shared, &bozo::app::video::post);
if (!bozo::app::userDirectory().empty()) // Options -> Language saves game.ini for the next start
dc::cheats::setLanguageFile(bozo::app::userDirectory() / "game.ini");
bozo::app::Game game;
game.run = run;
game.stop = [&] { host.requestStop(); };
game.framesEnded = [&] { return host.framesEnded(); };
// F5 saves the selected slot, F7 loads it, F6 / Shift+F6 pick the slot (0-9); also F2's Save states tab.
game.saveState = [&](int slot) { host.requestSave(bozo::app::stateSlotPath(slot)); };
game.loadState = [&](int slot) { host.requestLoad(bozo::app::stateSlotPath(slot)); };
host.onStateMessage = [](bool, const std::string &message) { bozo::app::notify(message); };
result = bozo::app::runWindow(windowOptions, game, &devices);
}
else
+514 -50
View File
@@ -21,6 +21,7 @@
#include "dc_native_api.h"
#include "dc_visibility.h"
#include "bozo/state.h"
#include "bozo/render/renderer.h"
#include "bozo/hash.h"
#include "bozo/libs/guest.h"
@@ -184,13 +185,89 @@ namespace dc::native
return value;
}
void wr64(uint8_t *rdram, uint32_t address, uint64_t value)
{
std::memcpy(rdram + (address & 0x1FFFFFFu), &value, sizeof(value));
}
// Widescreen (the engine's Settings::widescreen, posted each frame by dc_main): the frame is 16:9, 853.33 GS
// pixels wide (640 x 4/3) about the game's own centre (x 2048). The 3D shows more at the sides (Hor+: the game's
// projection is unchanged, its culling widened, see clipVertexHook); the game's 2D stays where it was, centred,
// except full-frame draws (clears, fills, fades, frame copies), which span the whole width, and the HUD's side
// pieces, which move out to the edges (hudShift). Latched once per frame, at its start (screen()).
std::atomic<bool> g_wideRequest{false};
bool g_wideFrame = false;
float frameW() { return g_wideFrame ? 640.0f * 4.0f / 3.0f : 640.0f; }
float frameLeft() { return 2048.0f - frameW() / 2.0f; }
// A span of the game's 640-wide frame (game x, 0..640) in GS x: the whole frame stays the whole, wider, frame.
bool wholeSpan(float x0, float x1) { return x0 <= 0.5f && x1 >= 639.5f; }
float spanLeft(float x0, float x1) { return g_wideFrame && wholeSpan(x0, x1) ? frameLeft() : 1728.0f + x0; }
float spanRight(float x0, float x1) { return g_wideFrame && wholeSpan(x0, x1) ? frameLeft() + frameW() : 1728.0f + x1; }
// An untextured fill's edges (game x): one on the frame's left or right edge reaches the wider frame's edge (the
// dungeon's fade is 64 x 32 tiles over the frame, letterbox bars and backgrounds touch the edges).
float fillLeft(float x0) { return g_wideFrame && x0 <= 0.5f ? frameLeft() : 1728.0f + x0; }
float fillRight(float x1) { return g_wideFrame && x1 >= 639.5f ? frameLeft() + frameW() : 1728.0f + x1; }
// A frame-sampling texture coordinate (0..1 over the frame) for GS x.
float frameU(float gsX) { return (gsX - frameLeft()) / frameW(); }
// A copy between the game's frame-sized pictures, x spans in game pixels: its GS x and its u (0..1 over the
// frame). Under widescreen each side is taken on its own: the whole 640 is the whole wider frame (a source over
// it samples all of it, a destination over it covers all of it); a part keeps its game pixels. So the game's
// half-size work copies of the frame (the whole frame into 0..320) hold the whole wider frame squeezed, and
// drawn back over the whole frame they spread it out again.
struct CopySpan
{
float x0, x1, u0, u1;
};
CopySpan copySpan(float dst0, float dst1, float src0, float src1)
{
const bool wideDst = g_wideFrame && wholeSpan(dst0, dst1), wideSrc = g_wideFrame && wholeSpan(src0, src1);
return {wideDst ? frameLeft() : 1728.0f + dst0, wideDst ? frameLeft() + frameW() : 1728.0f + dst1,
wideSrc ? 0.0f : frameU(1728.0f + src0), wideSrc ? 1.0f : frameU(1728.0f + src1)};
}
// The HUD under widescreen: while the game draws its field HUD (g_hudScope > 0, inside the HUD routines hooked
// in installWideHud), a piece in the left third of the game's frame moves to the left edge, one in its right
// third to the right edge; the middle stays. Menus, dialogue and pictures stay centred.
int g_hudScope = 0;
// The minimap moves as one piece (its large centred view stays centred): its first piece decides, and the
// monster symbols drawn on it after (DrawMapSymbol, the key finder's marker) take the same shift.
int g_mapScope = 0;
bool g_mapDecided = false;
float g_mapShift = 0.0f;
uint32_t g_2dCallerSeen = 0; // the 2D routine's caller (set by the 2D hooks)
float thirdShift(float gameLo, float gameHi)
{
const float half = (frameW() - 640.0f) / 2.0f, middle = (gameLo + gameHi) / 2.0f;
return middle < 640.0f / 3.0f ? -half : middle > 1280.0f / 3.0f ? half : 0.0f;
}
float hudShift(float gameLo, float gameHi)
{
if (!g_wideFrame)
return 0.0f;
const uint32_t caller = g_2dCallerSeen;
if (g_mapScope > 0)
{
if (!g_mapDecided)
g_mapShift = thirdShift(gameLo, gameHi), g_mapDecided = true;
return g_mapShift;
}
// DrawMapSymbol (0x1D7AA0..0x1D7C78) and the key finder's marker (drawn from a hook: its return is the
// cheats' sentinel, 0x80000) lie on the minimap.
if ((caller >= 0x001D7AA0u && caller < 0x001D7C78u) || caller == 0x00080000u)
return g_mapShift;
// DUN's MainDraw draws the weapon-ready plate itself (beside the attack gauge, bottom left).
if (g_hudScope > 0 || caller == 0x01DB019Cu)
return thirdShift(gameLo, gameHi);
return 0.0f;
}
bozo::render::Screen screen()
{
// DC's drawing environment: 640 x 224 fields, XYOFFSET (1728, 1936) (0x6C00, 0x7900 in 12.4).
// DC's drawing environment: 640 x 224 fields, XYOFFSET (1728, 1936) (0x6C00, 0x7900 in 12.4); widescreen
// widens it about the same centre.
bozo::render::Screen s;
s.originX = 1728.0f;
s.originX = frameLeft();
s.originY = 1936.0f;
s.width = 640.0f;
s.width = frameW();
s.height = 224.0f;
s.depthMax = 16777215.0f;
// The models' GIF tag writes ST, RGBAQ, XYZF2 (REGS 0x412) PACKED: the GS takes Z from bits 4..27 of the
@@ -198,6 +275,12 @@ namespace dc::native
s.gsZScale = 1.0f;
return s;
}
// A frame's start: widescreen is latched for the whole frame.
bozo::render::Screen beginScreen()
{
g_wideFrame = g_wideRequest.load(std::memory_order_relaxed);
return screen();
}
// DC's matrices as its VU0 code keeps them: four columns of four floats. mul(a, b) = a x b (MulMatrix).
struct Matrix
@@ -692,6 +775,7 @@ namespace dc::native
std::unordered_map<uint32_t, std::pair<uint64_t, std::shared_ptr<const bozo::render::Texture>>> g_decoded;
uint64_t g_textureVersion = 0;
bool g_dump2D = false; // the on-demand frame dump (drawStrip's [dc:dump])
uint32_t g_2dCaller = 0; // the game code that called the 2D routine being drawn (its return address)
// Live toggles (diagnosis): D:/DC_Recomp/build/toggles.txt, read every 60 frames, one word per line: noshadow
// (shadow passes not laid), nosprites3d (effect sprites not drawn), nofog, noguard, nodof (depth of field), nomade
// (sprites sampling a picture the game makes, frame copies), nomodels (DrawVu1 models), no2d (2D sprites), nocopies
@@ -1388,7 +1472,7 @@ namespace dc::native
const float x = (m[0] * v.x + m[4] * v.y + m[8] * v.z + m[12]) / w;
const float y = (m[1] * v.x + m[5] * v.y + m[9] * v.z + m[13]) / w;
const float z = (m[2] * v.x + m[6] * v.y + m[10] * v.z + m[14]) / w;
v.u = (x - 1728.0f + v.u) / material.frameWidth;
v.u = frameU(x + v.u); // v.u held the displacement in GS pixels
v.v = (y - 1936.0f + v.v) / material.frameHeight;
v.x = x; v.y = y; v.z = z; v.q = 1.0f;
valid &= std::isfinite(x) && std::isfinite(y) && std::isfinite(z) && std::isfinite(v.u) && std::isfinite(v.v);
@@ -2177,14 +2261,15 @@ namespace dc::native
std::vector<bozo::render::Vertex> vertices;
auto vertex = [&](float x, float y, float u, float v) {
bozo::render::Vertex out;
out.x = 1728.0f + x;
out.x = frameLeft() + x;
out.y = 1936.0f + y;
out.u = u;
out.v = v;
out.rgba = rgba;
return out;
};
const bozo::render::Vertex a = vertex(0, 0, 0, 0), b = vertex(640, 0, 1, 0), c = vertex(0, 224, 0, 1), d = vertex(640, 224, 1, 1);
const float w = frameW(); // the whole frame, widescreen or not
const bozo::render::Vertex a = vertex(0, 0, 0, 0), b = vertex(w, 0, 1, 0), c = vertex(0, 224, 0, 1), d = vertex(w, 224, 1, 1);
vertices.insert(vertices.end(), {a, b, c, b, d, c});
return vertices;
};
@@ -2207,6 +2292,12 @@ namespace dc::native
// texture shares its Z buffer): where a character stands in front of the ground, its depth hides the flattened
// shadow, the work texture stays unmarked and the character is not darkened.
mark.depthTest = true;
// With anti-aliasing the shared depth is resolved from one sample point off each pixel's centre: on sloping
// ground it can lie nearer than the mark's centre depth, and every mark failed (the shadows vanished). The
// marks are moved toward the camera by up to a pixel's depth slope then; without anti-aliasing they stay at
// the ground's own depth, as on the GS.
if (renderer.antiAliasing() >= 2)
mark.depthOffsetSlope = mark.depthOffsetUnits = 1.0f;
for (ShadowDraw &draw : draws)
{
for (bozo::render::Vertex &v : draw.vertices)
@@ -2280,9 +2371,11 @@ namespace dc::native
material.clampU = material.clampV = true;
static const float kIdentity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
std::vector<bozo::render::Vertex> strip, triangles;
// The strips cover the whole frame (u 0..1): widescreen stretches them over its width.
const float xScale = frameW() / 640.0f;
auto vertex = [&](float x, float y, int32_t z, float u, float v, uint32_t a) {
bozo::render::Vertex out;
out.x = 1728.0f + x;
out.x = frameLeft() + x * xScale;
out.y = 1936.0f + y;
out.z = static_cast<float>(static_cast<uint32_t>(z)) / zScale; // XYZ2's Z, unsigned
out.u = u;
@@ -2555,6 +2648,7 @@ namespace dc::native
if (!vertices.empty())
bozo::render::Renderer::instance().draw(material, kIdentity, vertices.data(), static_cast<uint32_t>(vertices.size()),
std::move(texture));
g_2dCallerSeen = 0; // a caller counts for its own draw only
}
// MGClearScreen (0x130000, a0..a3 the colour): a sprite over the 640 x 224 frame in that colour, ALPHA 0x2A (Cs:
@@ -2568,7 +2662,7 @@ namespace dc::native
material.depthTest = false;
material.depthWrite = true;
std::vector<bozo::render::Vertex> vertices;
quad(vertices, kOriginX, kOriginY, kOriginX + 640.0f, kOriginY + 224.0f, 0.0f,
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f, 0.0f,
flatColour(getRegU32(ctx, 4), getRegU32(ctx, 5), getRegU32(ctx, 6), getRegU32(ctx, 7)));
++g_stats.clears;
seq('C');
@@ -2586,14 +2680,76 @@ namespace dc::native
material.depthTest = false;
material.depthWrite = true;
std::vector<bozo::render::Vertex> vertices;
quad(vertices, kOriginX, kOriginY, kOriginX + 640.0f, kOriginY + 224.0f,
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f,
static_cast<float>(getRegU32(ctx, 4)), 0u);
drawScreen(material, vertices);
}
// The field HUD's routines (widescreen moves their side pieces to the edges, see hudShift): each runs inside a
// HUD scope. EdDrawClock (0x17DB60) is the towns' day clock, top right.
struct HudHook
{
uint32_t address;
RecompiledFunction original;
};
// topStatusInfo (0x1B04F0) is the dungeon's: health and weapon (top left), the item slots (middle), the floor
// and keys (top right), the attack gauge (bottom left); its numbers come from ValuePrint inside it.
// CDungeonMap::DrawMiniMap (0x1C3180) is the minimap, moved as one piece (g_mapScope).
HudHook g_hudHooks[] = {{0x0017DB60u, nullptr}, {0x001B04F0u, nullptr}, {0x001C3180u, nullptr}};
void hudHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
{
const uint32_t pc = ctx->pc;
for (const HudHook &hook : g_hudHooks)
if (hook.address == pc && hook.original)
{
int &scope = pc == 0x001C3180u ? g_mapScope : g_hudScope;
if (pc == 0x001C3180u)
g_mapDecided = false;
++scope;
hook.original(rdram, ctx, runtime);
--scope;
return;
}
}
// MGClipVertex (0x12EA40: a0 a point; MGClipBox and the models' culling call it): the point through the
// world-to-screen matrix (0x1C755F0), its clip flags: 0x20 nearer than the near plane (0x1C756E8), 0x10 past the
// far one (0x1C756F8), 8 / 4 above / below the frame (y within 112 of the centre 0x1C756D4), 2 / 1 left / right
// of it (x within 320 of the centre 0x1C756D0). Behind the camera (w <= 0) the tests reverse, as the game's do.
// Widescreen culls against the wider frame's half width instead, so what its sides show is drawn.
void clipVertexHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
ctx->pc = getRegU32(ctx, 31);
const Matrix m = load(rdram, 0x01C755F0u);
const uint32_t point = getRegU32(ctx, 4);
float in[4], out[4];
for (uint32_t k = 0; k < 4u; ++k)
in[k] = rdf(rdram, point + k * 4u);
for (int r = 0; r < 4; ++r)
out[r] = m.m[r] * in[0] + m.m[4 + r] * in[1] + m.m[8 + r] * in[2] + m.m[12 + r] * in[3];
float w = out[3];
if (w == 0.0f)
w = 1.0f;
const float x = out[0] * (1.0f / w) - rdf(rdram, 0x01C756D0u), y = out[1] * (1.0f / w) - rdf(rdram, 0x01C756D4u);
const float halfW = frameW() / 2.0f;
uint32_t flags = 0;
if (w < rdf(rdram, 0x01C756E8u))
flags = 0x20u;
if (rdf(rdram, 0x01C756F8u) < w)
flags |= 0x10u;
if (0.0f < w)
{
flags |= (y < -112.0f ? 8u : 0u) | (112.0f < y ? 4u : 0u) | (x < -halfW ? 2u : 0u) | (halfW < x ? 1u : 0u);
}
else
{
flags |= (-112.0f < y ? 8u : 0u) | (y < 112.0f ? 4u : 0u) | (-halfW < x ? 2u : 0u) | (x < halfW ? 1u : 0u);
}
setRegU64(ctx, 2, flags);
}
// MGFillBox (0x12FA70: a0 the rectangle, x, y, w, h in 1/16 pixels; a1..a4 the colour): an alpha-blended sprite
// (PRIM ABE with the game's ALPHA, (Cs - Cd) As + Cd), Z test ALWAYS, Z not written.
void fillBoxHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const uint32_t rect = getRegU32(ctx, 4);
const float x = static_cast<float>(static_cast<int32_t>(rd32(rdram, rect))) / 16.0f;
@@ -2606,7 +2762,12 @@ namespace dc::native
material.depthTest = false;
material.depthWrite = false;
std::vector<bozo::render::Vertex> vertices;
quad(vertices, kOriginX + x, kOriginY + y, kOriginX + x + w, kOriginY + y + h, 0.0f,
const float shift = hudShift(x, x + w); // widescreen: a fill on the frame's edges reaches the wider frame's
if (g_dump2D)
std::fprintf(stderr, "[dc:dump] caller %08x fill (%.1f %.1f %.1fx%.1f) colour %u %u %u %u\n", g_2dCaller, x, y, w, h,
getRegU32(ctx, 5) & 0xFFu, getRegU32(ctx, 6) & 0xFFu, getRegU32(ctx, 7) & 0xFFu, getRegU32(ctx, 8) & 0xFFu);
quad(vertices, shift != 0.0f ? 1728.0f + x + shift : fillLeft(x), kOriginY + y,
shift != 0.0f ? 1728.0f + x + w + shift : fillRight(x + w), kOriginY + y + h, 0.0f,
flatColour(getRegU32(ctx, 5), getRegU32(ctx, 6), getRegU32(ctx, 7), getRegU32(ctx, 8)));
drawScreen(material, vertices);
}
@@ -2680,10 +2841,33 @@ namespace dc::native
// A strip of four corners (v0 v1 v2, v1 v2 v3), textured with the record's texture when there is one.
// D:/DC_Recomp/build/dump2d.flag present (diagnosis, checked every 30 frames): the next frame's 2D draws logged one
// by one ([dc:dump]), then the flag removed.
void drawStrip(const uint8_t *rdram, uint32_t record, const Corner (&c)[4], bool flat = false)
void drawStrip(const uint8_t *rdram, uint32_t record, const Corner (&given)[4], bool flat = false)
{
if (g_toggles.no2D)
return;
// Widescreen: the strip placed in the wider frame. A strip over the whole 640-wide frame (a fade, a fill, a
// frame copy) spans the whole wide one: stretched here when flat, in the made-picture path below when it
// samples the frame; a picture of its own stays centred (pillarboxed). A HUD side piece moves out.
Corner c[4] = {given[0], given[1], given[2], given[3]};
const float gameLo = std::min({c[0].x, c[1].x, c[2].x, c[3].x}) - 1728.0f;
const float gameHi = std::max({c[0].x, c[1].x, c[2].x, c[3].x}) - 1728.0f;
const bool whole = g_wideFrame && wholeSpan(gameLo, gameHi);
auto stretch = [&]() {
for (Corner &k : c)
k.x = 2048.0f + (k.x - 2048.0f) * frameW() / 640.0f;
};
if (whole && (flat || record == 0u))
stretch();
else if (!whole)
{
const float shift = hudShift(gameLo, gameHi);
for (Corner &k : c)
{
k.x += shift;
if ((flat || record == 0u) && shift == 0.0f) // an untextured strip on an edge reaches the wider frame's
k.x = k.x <= 1728.5f ? fillLeft(k.x - 1728.0f) : k.x >= 2367.5f ? fillRight(k.x - 1728.0f) : k.x;
}
}
// DC_PROBE_COPIES=1 (diagnosis): the message windows' more-text triangle ("syst04"), each change of its
// corners, and its decoded texture once (build/syst04.pam).
static const bool s_probeTriangle = std::getenv("DC_PROBE_COPIES") != nullptr;
@@ -2709,8 +2893,8 @@ namespace dc::native
}
}
if (g_dump2D)
std::fprintf(stderr, "[dc:dump] sprite %08x \"%.32s\" tex0 %016llx pixels %08x (%.1f %.1f)-(%.1f %.1f) uv (%.0f %.0f)-(%.0f %.0f) rgba %08x alpha %llx flat %d\n",
record, record ? reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)) : "",
std::fprintf(stderr, "[dc:dump] caller %08x hud %d sprite %08x \"%.32s\" tex0 %016llx pixels %08x (%.1f %.1f)-(%.1f %.1f) uv (%.0f %.0f)-(%.0f %.0f) rgba %08x alpha %llx flat %d\n",
g_2dCaller, g_hudScope, record, record ? reinterpret_cast<const char *>(rdram + ((record + 8u) & 0x1FFFFFFu)) : "",
record ? static_cast<unsigned long long>(rd64(rdram, record + 0x28u)) : 0ull, record ? rd32(rdram, record + 0x38u) : 0u,
c[0].x, c[0].y, c[3].x, c[3].y, c[0].u, c[0].v, c[3].u, c[3].v, c[0].rgba, static_cast<unsigned long long>(g_alpha2D), flat ? 1 : 0);
bozo::render::Material made;
@@ -2752,12 +2936,17 @@ namespace dc::native
material.blend = bozo::render::blendOf(g_alpha2D);
material.depthTest = false;
material.depthWrite = false;
// Widescreen (as copySpan): drawn over the whole frame, it covers the whole wider frame; sampling the
// whole 640, it samples the whole wider frame; a part is the same game pixels.
const bool wholeSource = g_wideFrame && wholeSpan(std::min(c[0].u, c[3].u), std::max(c[0].u, c[3].u));
if (whole)
stretch();
std::vector<bozo::render::Vertex> vertices;
auto vertex = [&](const Corner &k) {
bozo::render::Vertex v;
v.x = k.x;
v.y = k.y;
v.u = k.u / 640.0f; // the target's pixels are the texture's texels
v.u = wholeSource ? k.u / 640.0f : frameU(1728.0f + k.u); // the target's pixels are the texture's texels
v.v = k.v / static_cast<float>(made.frameHeight);
v.rgba = k.rgba;
return v;
@@ -2864,6 +3053,7 @@ namespace dc::native
// set2DSprite (0x15BD00: a1 texture, a2 destination, a3 / t0 the source's corner, its size the destination's).
void sprite2DHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const uint32_t texture = getRegU32(ctx, 5);
if (texture == 0u)
@@ -2876,6 +3066,7 @@ namespace dc::native
// (0x15C630: t0..t3 the colour).
void sprite2DRectsHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
const uint32_t entry = ctx->pc;
ctx->pc = getRegU32(ctx, 31);
const uint32_t texture = getRegU32(ctx, 5);
@@ -2895,6 +3086,7 @@ namespace dc::native
// (top-left, top-right, bottom-left, bottom-right), the 9th argument the strip's order: 0 starts top-right).
void sprite2DCornersHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const uint32_t texture = getRegU32(ctx, 5);
if (texture == 0u)
@@ -2920,6 +3112,7 @@ namespace dc::native
// set2DSpriteC4 (0x15E120: a1 the rectangle, a2..a5 the corners' spRGBA): an untextured gradient strip.
void sprite2DC4Hook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const Rect d = rectAt(rdram, getRegU32(ctx, 5));
const float x0 = kOriginX + static_cast<float>(d.x), x1 = kOriginX + static_cast<float>(d.x + d.w);
@@ -2932,6 +3125,7 @@ namespace dc::native
// strip (PRIM 0x44).
void colSpriteHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const uint32_t rgba = (getRegU32(ctx, 8) & 0xFFu) | (getRegU32(ctx, 9) & 0xFFu) << 8 | (getRegU32(ctx, 10) & 0xFFu) << 16 |
(getRegU32(ctx, 11) & 0xFFu) << 24;
@@ -2949,6 +3143,7 @@ namespace dc::native
// colour): the corners turned about the pivot with the game's own formulas.
void sprite2DRotHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
const uint32_t entry = ctx->pc;
ctx->pc = getRegU32(ctx, 31);
const uint32_t texture = getRegU32(ctx, 5);
@@ -3010,6 +3205,7 @@ namespace dc::native
// (0x14C3C0: the same arguments; the sprite set2DSprite_Start opened a batch for, the message windows' glyphs).
void mySpriteHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const uint32_t texture = getRegU32(ctx, 5);
if (texture == 0u)
@@ -3045,6 +3241,7 @@ namespace dc::native
// + 0x28, the next entry at + 0x30. Sprites with mgAlpha's blend, Z test ALWAYS, no Z write.
void spriteTableHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const uint32_t table = getRegU32(ctx, 4);
const int32_t lists = static_cast<int32_t>(rd32(rdram, table + 4u));
@@ -3154,6 +3351,7 @@ namespace dc::native
// set3DColSprite (0x15D1B0: a1..a4 the points, t0..t3 their spRGBA): untextured, Gouraud.
void colSprite3DHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
Point3 p[4];
uint32_t rgba[4];
@@ -3170,6 +3368,7 @@ namespace dc::native
// 0x15DCA0: the sprite's corners with F, t1 the spRGBA).
void sprite3DHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
const uint32_t entry = ctx->pc;
ctx->pc = getRegU32(ctx, 31);
const uint32_t texture = getRegU32(ctx, 5);
@@ -3204,6 +3403,7 @@ namespace dc::native
// DrawLine (0x171210: a0 / a1 the ends, x, y in 1/16 pixels and Z; a2..a5 the colour): a line, drawn as a thin quad.
void drawLineHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const Point3 a = pointAt(rdram, getRegU32(ctx, 4), false), b = pointAt(rdram, getRegU32(ctx, 5), false);
const uint32_t rgba = (getRegU32(ctx, 6) & 0xFFu) | (getRegU32(ctx, 7) & 0xFFu) << 8 | (getRegU32(ctx, 8) & 0xFFu) << 16 |
@@ -3443,14 +3643,17 @@ namespace dc::native
if (sampleMade(static_cast<uint32_t>(srcTex0 & 0x3FFFu), made) && dstBase != g_frameBase && dstBase != g_backBase)
{
made.target = targetFor(dstBase);
// The place now holds a picture with the source's rows (MGMoveFrameBuffImage's 448 does not outlive it).
g_targetRows[made.target] = static_cast<float>(made.frameHeight);
made.blend = bozo::render::Material::Blend::Opaque;
made.depthTest = false;
made.depthWrite = false;
made.clampU = made.clampV = true;
std::vector<bozo::render::Vertex> vertices;
quad(vertices, kOriginX + static_cast<float>(dx), kOriginY + static_cast<float>(dy), kOriginX + static_cast<float>(dx + r.w),
kOriginY + static_cast<float>(dy + r.h), 0.0f, 0x80808080u, static_cast<float>(r.x) / 640.0f,
static_cast<float>(r.y) / made.frameHeight, static_cast<float>(r.x + r.w) / 640.0f,
const CopySpan span = copySpan(static_cast<float>(dx), static_cast<float>(dx + r.w), static_cast<float>(r.x),
static_cast<float>(r.x + r.w));
quad(vertices, span.x0, kOriginY + static_cast<float>(dy), span.x1, kOriginY + static_cast<float>(dy + r.h), 0.0f,
0x80808080u, span.u0, static_cast<float>(r.y) / made.frameHeight, span.u1,
static_cast<float>(r.y + r.h) / made.frameHeight);
drawScreen(made, vertices);
return;
@@ -3627,6 +3830,7 @@ namespace dc::native
}
void balloonHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
g_2dCaller = g_2dCallerSeen = getRegU32(ctx, 31); // the HUD probe and scope
ctx->pc = getRegU32(ctx, 31);
const uint32_t cls = getRegU32(ctx, 4);
const uint32_t balloonRecord = textureRecord(rdram, 0x00299A78u);
@@ -3645,7 +3849,7 @@ namespace dc::native
clear.depthWrite = true;
clear.target = balloon;
std::vector<bozo::render::Vertex> vertices;
quad(vertices, kOriginX, kOriginY, kOriginX + 640.0f, kOriginY + 224.0f, screen().depthMax, 0u);
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f, screen().depthMax, 0u);
drawScreen(clear, vertices);
// Opaque draws deliberately publish full coverage. Clear coverage
// separately so the sampled image stays transparent outside the
@@ -3865,21 +4069,27 @@ namespace dc::native
}
// MGGetFBuffTex / MGGetFBuffBackTex (0x12F130 / 0x12F1A0, a0 the sceGsTex0 they fill): where the game's frame
// and the frame before are, as the game itself works them out.
RecompiledFunction g_getFrameTex = nullptr, g_getBackTex = nullptr;
void getFrameTexHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
// and the frame before are. The originals read the FRAME images sceGsSetDefDBuff left in MGInit's record (no longer
// made); the two frames are fixed: 640 wide, PSMCT32, at FBP 0x46 and 0, the half DBuffID (gp-0x7440) names being
// drawn. Only their identity matters (the game's own texture calls compare these TEX0 words): the same words.
uint64_t frameTex0(uint32_t fbp) { return 0x228000000ull | (10ull << 14) | (static_cast<uint64_t>(fbp & 0x1FFu) << 5); }
constexpr uint32_t kFrameFbp[2] = {0x46u, 0x00u};
uint32_t dbuffId(const uint8_t *rdram, R5900Context *ctx) { return rd32(rdram, getRegU32(ctx, 28) - 0x7440u); }
void getFrameTexHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
const uint32_t out = getRegU32(ctx, 4);
g_getFrameTex(rdram, ctx, runtime);
g_frameBase = static_cast<uint32_t>(rd64(rdram, out) & 0x3FFFu);
const uint64_t tex0 = frameTex0(kFrameFbp[dbuffId(rdram, ctx) == 0u ? 0 : 1]);
wr64(rdram, getRegU32(ctx, 4), tex0);
g_frameBase = static_cast<uint32_t>(tex0 & 0x3FFFu);
g_backAsked = false;
ctx->pc = getRegU32(ctx, 31);
}
void getBackTexHook(uint8_t *rdram, R5900Context *ctx, Runtime *runtime)
void getBackTexHook(uint8_t *rdram, R5900Context *ctx, Runtime *)
{
const uint32_t out = getRegU32(ctx, 4);
g_getBackTex(rdram, ctx, runtime);
g_backBase = static_cast<uint32_t>(rd64(rdram, out) & 0x3FFFu);
const uint64_t tex0 = frameTex0(kFrameFbp[dbuffId(rdram, ctx) == 0u ? 1 : 0]);
wr64(rdram, getRegU32(ctx, 4), tex0);
g_backBase = static_cast<uint32_t>(tex0 & 0x3FFFu);
g_backAsked = true;
ctx->pc = getRegU32(ctx, 31);
}
// MGStretchMoveImage (0x12F430: a0 / a1 the source's TEX0 and rectangle, a2 / a3 the destination's; rectangles in
// 1/16 pixels): the game stretching its frame (or the frame before, or a work texture) into a work texture. Here
@@ -3901,16 +4111,20 @@ namespace dc::native
// The work picture at the PS2's size (the game's 640 x 224 frame copy): the title draws it back into the
// frame each frame before copying the frame into it again, a feedback loop whose blur is that of a 640 x
// 224 picture filtered each frame (at the window's resolution it blurred several times less).
bozo::render::Renderer::instance().setTargetSize(material.target, 640, 224);
bozo::render::Renderer::instance().setTargetSize(material.target, static_cast<uint32_t>(frameW() + 0.5f), 224);
// A 640 x 224 picture from now on: a place the menu's MGMoveFrameBuffImage filled with both fields (448 rows)
// and the town copies its frame into again each frame (the water's "work") is sampled as 224 rows again.
g_targetRows[material.target] = 224.0f;
material.blend = bozo::render::Material::Blend::Opaque;
material.depthTest = false;
material.depthWrite = false;
material.clampU = material.clampV = true;
std::vector<bozo::render::Vertex> vertices;
quad(vertices, kOriginX + static_cast<float>(to.x) / 16.0f, kOriginY + static_cast<float>(to.y) / 16.0f,
kOriginX + static_cast<float>(to.x + to.w) / 16.0f, kOriginY + static_cast<float>(to.y + to.h) / 16.0f, 0.0f, 0x80808080u,
static_cast<float>(from.x) / 16.0f / 640.0f, static_cast<float>(from.y) / 16.0f / 224.0f,
static_cast<float>(from.x + from.w) / 16.0f / 640.0f, static_cast<float>(from.y + from.h) / 16.0f / 224.0f);
const CopySpan span = copySpan(static_cast<float>(to.x) / 16.0f, static_cast<float>(to.x + to.w) / 16.0f,
static_cast<float>(from.x) / 16.0f, static_cast<float>(from.x + from.w) / 16.0f);
quad(vertices, span.x0, kOriginY + static_cast<float>(to.y) / 16.0f, span.x1, kOriginY + static_cast<float>(to.y + to.h) / 16.0f,
0.0f, 0x80808080u, span.u0, static_cast<float>(from.y) / 16.0f / 224.0f, span.u1,
static_cast<float>(from.y + from.h) / 16.0f / 224.0f);
drawScreen(material, vertices);
++g_stats.stretches;
seq('S');
@@ -3961,7 +4175,9 @@ namespace dc::native
const float wave = rdf(rdram, 0x01D18980u + static_cast<uint32_t>(std::clamp(index, 0, 31)) * 4u);
const int32_t offset = static_cast<int32_t>(amplitude * factor * wave * 16.0f);
const int32_t x0 = std::max(frame.x * 16 + offset, 0), x1 = std::min(offset + (frame.x + frame.w) * 16, 0x27F0);
quad(vertices, kOriginX, kOriginY + static_cast<float>(row), kOriginX + static_cast<float>(frame.w),
// Widescreen: the whole frame waves, its offsets in proportion (u 0..1 is the whole frame either way).
const float w = static_cast<float>(frame.w);
quad(vertices, spanLeft(0.0f, w), kOriginY + static_cast<float>(row), spanRight(0.0f, w),
kOriginY + static_cast<float>(row + 2), 0.0f, 0x80808080u, static_cast<float>(x0) / 16.0f / 640.0f,
static_cast<float>(frame.y + row) / copy.frameHeight, static_cast<float>(x1) / 16.0f / 640.0f,
static_cast<float>(frame.y + row + 2) / copy.frameHeight);
@@ -4116,7 +4332,7 @@ namespace dc::native
material.depthWrite = false;
material.clampU = material.clampV = true;
std::vector<bozo::render::Vertex> vertices;
quad(vertices, kOriginX, kOriginY, kOriginX + 640.0f, kOriginY + 224.0f, 0.0f, 0x80808080u);
quad(vertices, frameLeft(), kOriginY, frameLeft() + frameW(), kOriginY + 224.0f, 0.0f, 0x80808080u);
drawScreen(material, vertices);
}
@@ -4515,19 +4731,24 @@ namespace dc::native
// whether it connects to its predecessor. No packed graphics output is read.
// Like DrawLine, native segments are one-pixel-wide quads; console line
// rasterization and fishing gameplay still require visual qualification.
// FishLineDraw's strip between two of its points (namespace scope: a save state carries it, as a state can be saved
// between two points of the compiled loop).
struct FishStrip
{
Runtime *owner = nullptr;
uint32_t next = 0;
Point3 previous{};
};
thread_local FishStrip g_fishStrip;
// The debug font's compositions in progress (debugFontBoundary): a state is not saved in the middle of one.
thread_local bool g_debugFontBusy = false;
void fishLineVertex(uint8_t *ram, R5900Context *ctx, Runtime *runtime)
{
struct Strip
{
Runtime *owner = nullptr;
uint32_t next = 0;
Point3 previous{};
};
static thread_local Strip strip;
FishStrip &strip = g_fishStrip;
const uint32_t index = getRegU32(ctx, 19), decision = getRegU32(ctx, 5);
if (index >= 24u || (decision != 4u && decision != 12u))
throw std::runtime_error("native fishing line: invalid point boundary");
if (index == 0u) strip = {runtime, 0u, {}};
if (index == 0u) strip = FishStrip{runtime, 0u, {}};
if (strip.owner != runtime || strip.next != index)
throw std::runtime_error("native fishing line: nonsequential points");
bozo::libs::Guest guest(*runtime, ctx);
@@ -4569,6 +4790,12 @@ namespace dc::native
std::shared_ptr<bozo::render::Texture> image;
};
static thread_local std::unordered_map<Runtime *, std::unordered_map<uint32_t, Work>> pending;
struct Busy
{
std::unordered_map<Runtime *, std::unordered_map<uint32_t, Work>> &work;
Runtime *runtime;
~Busy() { g_debugFontBusy = !work[runtime].empty(); }
} busy{pending, runtime};
const uint32_t stack = getRegU32(ctx, 29);
bozo::libs::Guest guest(*runtime, ctx);
if (pc == 0x0013DFA8u)
@@ -4706,11 +4933,15 @@ namespace dc::native
registry.registerFunction(0x00130B30u, &endShadowHook);
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
renderer.setEnabled(true);
renderer.beginFrame(screen());
renderer.beginFrame(beginScreen());
renderer.setStreamDraws(false);
renderer.setPresentsAlone(true);
{
registry.registerFunction(0x00130000u, &clearScreenHook);
registry.registerFunction(0x0012EA40u, &clipVertexHook); // culls against the frame's width (widescreen)
for (HudHook &hook : g_hudHooks)
if ((hook.original = runtime.functions.generated(hook.address)))
registry.registerFunction(hook.address, &hudHook);
registry.registerFunction(0x0012FD30u, &clearZHook);
registry.registerFunction(0x0012FA70u, &fillBoxHook);
registry.registerFunction(0x0015BD00u, &sprite2DHook);
@@ -4746,11 +4977,8 @@ namespace dc::native
registry.registerFunction(0x00133A60u, &cleanupTextureListHook);
registry.registerFunction(0x00151AD0u, &balloonHook);
registry.registerFunction(0x00140660u, &moveImageTestHook);
if ((g_getFrameTex = runtime.functions.generated(0x0012F130u)) && (g_getBackTex = runtime.functions.generated(0x0012F1A0u)))
{
registry.registerFunction(0x0012F130u, &getFrameTexHook);
registry.registerFunction(0x0012F1A0u, &getBackTexHook);
}
registry.registerFunction(0x0012F130u, &getFrameTexHook);
registry.registerFunction(0x0012F1A0u, &getBackTexHook);
if ((std::getenv("DC_PROBE_SKY") || std::getenv("DC_SKY_TIME")) &&
(g_drawSky = runtime.functions.generated(0x00187F90u)))
registry.registerFunction(0x00187F90u, &skyProbeHook);
@@ -4926,7 +5154,7 @@ namespace dc::native
}
flushShadows();
renderer.endFrame();
renderer.beginFrame(screen());
renderer.beginFrame(beginScreen());
g_clutOverride.clear();
if (!g_publishingFromLoad)
g_lastMainPublish.store(nowMs(), std::memory_order_relaxed);
@@ -4976,6 +5204,23 @@ namespace dc::native
static uint32_t s_toggleCheck = 0;
if (++s_toggleCheck % 60u == 0u)
readToggles();
// DC_DUMP2D_AT=frame,frame,... (diagnosis, hidden runs): those published frames' 2D dumped as the flag file does.
static const std::vector<uint64_t> s_dumpAt = [] {
std::vector<uint64_t> at;
if (const char *e = std::getenv("DC_DUMP2D_AT"))
for (const char *p = e; *p;)
{
char *end = nullptr;
at.push_back(std::strtoull(p, &end, 10));
p = *end ? end + 1 : end;
}
return at;
}();
if (std::find(s_dumpAt.begin(), s_dumpAt.end(), g_publishedFrames) != s_dumpAt.end())
{
g_dump2D = true;
std::fprintf(stderr, "[dc:dump] frame start %llu\n", static_cast<unsigned long long>(g_publishedFrames));
}
static uint32_t s_dumpCheck = 0;
if (++s_dumpCheck % 30u == 0u)
if (FILE *flag = std::fopen("D:/DC_Recomp/build/dump2d.flag", "rb"))
@@ -5015,4 +5260,223 @@ namespace dc::native
static_cast<uint32_t>(tex0 >> 30) & 0xFu, static_cast<uint32_t>(tex0 >> 37) & 0x3FFFu, name);
}
}
// ---- Save states ----------------------------------------------------------------------------------------------
namespace
{
// A texture image (null: none), restored with a new version so the renderer sends it again.
void textureIo(bozo::state::Archive &a, std::shared_ptr<const bozo::render::Texture> &texture)
{
bool has = texture != nullptr;
uint32_t width = 0, height = 0;
std::vector<uint32_t> rgba;
uint64_t key = 0;
std::vector<std::pair<uint32_t, uint32_t>> pages;
std::vector<std::vector<uint32_t>> levels;
bool asset = false;
if (!a.loading() && texture)
{
width = texture->width, height = texture->height, rgba = texture->rgba, key = texture->key;
pages = texture->pages, levels = texture->levels, asset = texture->asset;
}
bozo::state::fields(a, has, width, height, rgba, key, pages, levels, asset);
if (!a.loading())
return;
if (!has)
{
texture = nullptr;
return;
}
auto made = std::make_shared<bozo::render::Texture>();
made->width = width, made->height = height, made->rgba = std::move(rgba), made->key = key;
made->pages = std::move(pages), made->levels = std::move(levels), made->asset = asset;
made->version = ++g_textureVersion;
texture = made;
}
// The images a state refers to, each written once (many bindings share one), and referred to by index (-1: none).
struct TextureTable
{
std::vector<std::shared_ptr<const bozo::render::Texture>> images;
std::unordered_map<const bozo::render::Texture *, int32_t> index;
int32_t add(const std::shared_ptr<const bozo::render::Texture> &image)
{
if (!image)
return -1;
const auto [at, added] = index.emplace(image.get(), static_cast<int32_t>(images.size()));
if (added)
images.push_back(image);
return at->second;
}
std::shared_ptr<const bozo::render::Texture> at(int32_t i) const
{
if (i < 0)
return nullptr;
if (static_cast<size_t>(i) >= images.size())
throw std::runtime_error("save state: a texture index past the table");
return images[static_cast<size_t>(i)];
}
};
template <class Key> std::vector<Key> sortedKeys(const auto &map)
{
std::vector<Key> keys;
for (const auto &entry : map)
keys.push_back(static_cast<Key>(entry.first));
std::sort(keys.begin(), keys.end());
return keys;
}
}
// What the native renderer and asset builders know that guest memory alone does not tell again, and, on load, the
// caches decoded from the old guest memory dropped (docs/BOZO_MIGRATION.md, "Save states").
void state(bozo::state::Archive &a, Runtime &runtime)
{
const uint8_t *rdram = runtime.memory.ram();
TextureTable table;
if (!a.loading())
{
std::lock_guard<std::mutex> lock(g_mdtMutex);
for (const uint32_t data : sortedKeys<uint32_t>(g_mdtCopies))
if (const auto &records = g_mdtCopies.at(data).records)
for (const TextureBinding &binding : *records)
if (resolveBinding(rdram, binding) == 0u)
table.add(binding.image);
for (const uint32_t record : sortedKeys<uint32_t>(g_pinned))
table.add(g_pinned.at(record).texture);
for (const uint32_t record : g_patchedRecords)
if (const auto found = g_decoded.find(record); found != g_decoded.end())
table.add(found->second.second);
}
{
uint64_t images = table.images.size();
bozo::state::fields(a, images);
if (a.loading())
table.images.resize(images);
for (auto &image : table.images)
textureIo(a, image);
}
// The MDT copies: the game reuses a static piece's MDT memory after building it, so its copy is the only model
// left. A binding's image is kept only where its record no longer resolves (otherwise it is decoded again).
{
std::lock_guard<std::mutex> lock(g_mdtMutex);
uint64_t count = g_mdtCopies.size();
bozo::state::fields(a, count);
std::vector<uint32_t> keys = a.loading() ? std::vector<uint32_t>(count) : sortedKeys<uint32_t>(g_mdtCopies);
if (a.loading())
g_mdtCopies.clear();
for (uint64_t i = 0; i < count; ++i)
{
uint32_t data = keys[i], mdt = 0;
bool hasCopy = false, hasRecords = false;
std::vector<uint8_t> bytes;
std::vector<TextureBinding> bindings;
if (!a.loading())
{
const MdtCopy &entry = g_mdtCopies.at(data);
mdt = entry.mdt;
hasCopy = entry.copy != nullptr;
if (hasCopy)
bytes = *entry.copy;
hasRecords = entry.records != nullptr;
if (hasRecords)
bindings = *entry.records;
}
bozo::state::fields(a, data, mdt, hasCopy, bytes, hasRecords);
uint64_t bindingCount = bindings.size();
bozo::state::fields(a, bindingCount);
if (a.loading())
bindings.resize(bindingCount);
for (TextureBinding &binding : bindings)
{
bozo::state::fields(a, binding.record, binding.resolvedRecord, binding.identity);
int32_t image = !a.loading() && resolveBinding(rdram, binding) == 0u ? table.add(binding.image) : -1;
bozo::state::fields(a, image);
if (a.loading())
binding.image = table.at(image);
}
if (a.loading())
{
MdtCopy &entry = g_mdtCopies[data];
entry.mdt = mdt;
entry.copy = hasCopy ? std::make_shared<const std::vector<uint8_t>>(std::move(bytes)) : nullptr;
entry.records = hasRecords ? std::make_shared<const std::vector<TextureBinding>>(std::move(bindings)) : nullptr;
}
}
}
{
uint64_t count = g_pinned.size();
bozo::state::fields(a, count);
std::vector<uint32_t> keys = a.loading() ? std::vector<uint32_t>(count) : sortedKeys<uint32_t>(g_pinned);
if (a.loading())
g_pinned.clear();
for (uint64_t i = 0; i < count; ++i)
{
uint32_t record = keys[i];
Pinned pinned = a.loading() ? Pinned{} : g_pinned.at(record);
int32_t image = a.loading() ? -1 : table.add(pinned.texture);
bozo::state::fields(a, record, pinned.pixels, pinned.tex0, image);
if (a.loading())
pinned.texture = table.at(image);
if (a.loading())
g_pinned[record] = std::move(pinned);
}
}
// What was sent to each GS place last, the records MGMoveImage patched and their decoded pictures.
bozo::state::fields(a, g_resident, g_waterOfVisual);
{
std::vector<uint32_t> patched(g_patchedRecords.begin(), g_patchedRecords.end());
std::sort(patched.begin(), patched.end());
bozo::state::fields(a, patched);
if (a.loading())
{
g_patchedRecords = std::unordered_set<uint32_t>(patched.begin(), patched.end());
g_decoded.clear();
}
for (uint32_t record : patched)
{
bool has = !a.loading() && g_decoded.count(record) != 0;
uint64_t hash = has ? g_decoded.at(record).first : 0u;
int32_t image = has ? table.add(g_decoded.at(record).second) : -1;
bozo::state::fields(a, has, hash, image);
if (a.loading() && has)
g_decoded[record] = {hash, table.at(image)};
}
}
// Facts and seeds: the frame identities the game asked for last, the haze's random sequences (the first writes
// guest RAM), the group the depth of field follows, the fishing strip between two points.
bozo::state::fields(a, g_frameBase, g_backBase, g_backAsked, g_hazeSeed, g_hazeRandom, g_group);
bozo::state::fields(a, g_fishStrip.next, g_fishStrip.previous.x, g_fishStrip.previous.y, g_fishStrip.previous.z,
g_fishStrip.previous.fog);
if (!a.loading())
return;
g_fishStrip.owner = &runtime;
// Caches of the old guest memory and of render targets whose pictures are on the GPU: dropped.
g_targetOfBase.clear();
for (float &rows : g_targetRows)
rows = 224.0f;
g_blendedLast.clear();
g_hazeLast.clear();
g_blendedExtent.clear();
bozo::render::Renderer &renderer = bozo::render::Renderer::instance();
for (uint8_t target = 1; target < 8; ++target)
{
renderer.setTargetSize(target, 0, 0);
renderer.setTargetSharesDepth(target, false);
}
g_clutOverride.clear();
g_shadowDraws.clear();
g_pendingShadows.clear();
renderer.beginFrame(beginScreen());
g_lastMainPublish.store(nowMs(), std::memory_order_relaxed);
}
void setWidescreen(bool on) { g_wideRequest.store(on, std::memory_order_relaxed); }
// CFrameVu1::DrawVu1's culling bound (runtime/dc_port.cpp): the drawn frame's half width, 320 or 426.67.
float modelCullHalfWidth() { return frameW() / 2.0f; }
std::string unsaveable()
{
if (g_debugFontBusy)
return "the debug font is drawing a picture";
return {};
}
}
+7 -1
View File
@@ -3,4 +3,10 @@
#include "bozo/runtime.h"
#include <bit>
#include <string>
namespace dc::native { void finishSceneForMenu(); void setAssetDirectory(const std::string &); }
namespace dc::native
{
void finishSceneForMenu();
void setAssetDirectory(const std::string &);
// Widescreen (16:9 Hor+, the HUD at the edges): taken at the next frame's start. Any thread.
void setWidescreen(bool on);
}
+76
View File
@@ -0,0 +1,76 @@
// Dark Cloud's controller, native. CGamePad (the global at 0x1CBC540) keeps one 19-word PAD_STATUS per port at +4 and
// +0x50: buttons, ly, lx, ry, rx, then the libpad handshake's phase, state, mode and mode IDs, and the vibration bytes
// at +0x28 (the levels Step sends) and +0x2E (the actuator alignment). The original read_pad (0x12A900) walked the
// libpad handshake (scePadGetState, scePadInfoMode, scePadSetMainMode, scePadInfoAct, scePadSetActAlign) before its
// pad_button_read called scePadRead; Step (0x12B140) sent the levels with scePadSetActDirect. Here the
// controller in each port is what it always is on the PC, a DualShock 2 in analog mode: its state comes from the
// engine's PadInput (the window's devices, or a script in checks) and its rumble goes back to it. CGamePad::Init's
// scePadInit and scePadPortOpen calls are retired by guarded patches (recomp/dc_native.patches).
#include "dc_pad.h"
#include "bozo/libs/libraries.h"
#include "bozo/port.h"
#include "bozo/runtime.h"
#include <cstring>
namespace dc::pad {
namespace {
constexpr uint32_t kReadPad=0x12a900,kStep=0x12b140;
// The handshake's end as the original leaves it: phase 99 (ready), state 6 (stable), mode IDs 7 (DualShock 2).
constexpr uint32_t kReady=99,kStable=6,kDualShock=7;
uint32_t rd32(const uint8_t *ram,uint32_t at){uint32_t v;std::memcpy(&v,ram+(at&0x1ffffffu),4);return v;}
void wr32(uint8_t *ram,uint32_t at,uint32_t v){std::memcpy(ram+(at&0x1ffffffu),&v,4);}
void wr8(uint8_t *ram,uint32_t at,uint8_t v){ram[at&0x1ffffffu]=v;}
void returnVoid(R5900Context *c){c->pc=c->r[31].uw[0];}
uint16_t g_extraButtons=0; // dc::pad::press (the cheat script's dialogue advance)
// read_pad(PAD_STATUS *status, int port, int slot): CGamePad::UpDate calls it for port 0 and port 1 (slot 0).
void readPad(uint8_t *ram,R5900Context *c,Runtime *rt)
{
const uint32_t status=c->r[4].uw[0];
const int port=static_cast<int>(c->r[5].uw[0]);
bozo::libs::PadInputState input;
if(rt->port && (port==0 || port==1)){
auto &libraries=rt->port->libraries();
if(libraries.pad.input)libraries.pad.input->read(libraries.framesEnded,port,input);
}
// scePadRead's halfword arrives byte-swapped in DC's word: Cross is 0x40, Up 0x1000.
const uint16_t buttons=static_cast<uint16_t>(((input.buttons<<8)|(input.buttons>>8))|(port==0?g_extraButtons:0u));
wr32(ram,status,buttons);
wr32(ram,status+4,input.ly);wr32(ram,status+8,input.lx);wr32(ram,status+12,input.ry);wr32(ram,status+16,input.rx);
wr32(ram,status+20,kReady);wr32(ram,status+24,kStable);wr32(ram,status+28,kDualShock);
wr32(ram,status+32,kDualShock);wr32(ram,status+36,kDualShock);
// The alignment the handshake set: byte 0 the small motor, byte 1 the large one, the rest none.
wr8(ram,status+0x2e,0);wr8(ram,status+0x2f,1);for(uint32_t i=2;i<6;++i)wr8(ram,status + 0x2e + i,0xff);
returnVoid(c);
}
// CGamePad::Step(): each port's two motor timers count down and a motor whose timer ran out stops (both stop while
// vibration is disabled at +0x464); port 0's levels then go to player 1's controller.
void step(uint8_t *ram,R5900Context *c,Runtime *rt)
{
const uint32_t pad=c->r[4].uw[0];
for(uint32_t port=0;port<2;++port){
const uint32_t base=pad+port*0x4c;
if(rd32(ram,pad+0x464)==0){wr8(ram,base+0x2c,0);wr8(ram,base+0x2d,0);}
for(uint32_t motor=0;motor<2;++motor){
const uint32_t timer=base+0x38+motor*4;
const int32_t left=static_cast<int32_t>(rd32(ram,timer));
if(left<1){wr32(ram,timer,0);wr8(ram,base+0x2c+motor,0);}else wr32(ram,timer,static_cast<uint32_t>(left-1));
}
}
if(rt->port){
auto &libraries=rt->port->libraries();
if(libraries.pad.input)libraries.pad.input->rumble(0,ram[(pad+0x2c)&0x1ffffffu]!=0,ram[(pad+0x2d)&0x1ffffffu]);
}
returnVoid(c);
}
}
void press(unsigned buttons){g_extraButtons=static_cast<uint16_t>(buttons);}
void install(bozo::port::Registry &registry)
{
registry.registerFunction(kReadPad,readPad);
registry.registerFunction(kStep,step);
}
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
struct Runtime;
namespace bozo::port { class Registry; }
namespace dc::pad {
// CGamePad's per-frame controller read and vibration, native: the PC's controller (the engine's PadInput) fills the
// game's PAD_STATUS directly, with no libpad port, mode handshake or pad DMA buffer in between.
void install(bozo::port::Registry &);
// Extra buttons for player 1 on top of the controller, until changed (DC's word: Cross 0x40); 0 none. Game thread.
void press(unsigned buttons);
}
+66
View File
@@ -3,6 +3,7 @@
#include "bozo/libs/guest.h"
#include "bozo/libs/libraries.h"
#include "bozo/port.h"
#include "dc_sound.h"
#include "dc_visibility.h"
#include <cstring>
namespace dc::native
@@ -11,11 +12,37 @@ namespace dc::native
void publish();
void fishLineVertex(uint8_t *, R5900Context *, Runtime *);
void debugFontBoundary(uint8_t *, R5900Context *, Runtime *, uint32_t);
float modelCullHalfWidth();
} // namespace dc::native
namespace dc
{
bool nativeInstruction(uint8_t *ram, R5900Context *ctx, Runtime *rt, uint32_t pc)
{
if (dc::sound::nativeSite(ram, ctx, rt, pc))
return true;
// MGInit's material defaults, once read from the draw record sceGsSetDefDBuff made (no longer made): draw 0's
// TEST (Z test on, GEQUAL; MGInit then sets the alpha test itself) and ZBUF (Z written). setGsReg3Hook reads only
// their alpha-test and Z-mask fields.
if (pc == 0x0012C510u) // ld a2,0(a2)
{
ctx->r[6].ud[0] = 0x50000u;
return true;
}
if (pc == 0x0012C57Cu) // ld a0,0(a0)
{
ctx->r[4].ud[0] = 0x100008Cu;
return true;
}
// CFrameVu1::DrawVu1's model culling, lui v0,0x43a0 (320.0, the frame's half width): the half width of the
// frame drawn, wider in widescreen, so models on its wider sides are not skipped.
if (pc == 0x00129AB4u || pc == 0x00129AE4u)
{
const float half = dc::native::modelCullHalfWidth();
uint32_t bits;
std::memcpy(&bits, &half, 4);
ctx->r[2].ud[0] = bits;
return true;
}
if (pc == 0x0013DFA8u || pc == 0x0013DFF0u || pc == 0x0013E314u || pc == 0x0013E420u)
{
dc::native::debugFontBoundary(ram, ctx, rt, pc);
@@ -47,9 +74,48 @@ namespace dc
bozo::port::frameEnd(rt, ctx);
ctx->pc = ctx->r[31].uw[0];
}
// FlushCache, iFlushCache and iSyncDCache: the game writes the PS2's data cache back before its transfers and in
// its vblank callbacks. The PC has no such cache to keep coherent with any device: nothing, 0, without a kernel
// call (each caller still makes its call, with its checkpoint).
void noCache(uint8_t *, R5900Context *ctx, Runtime *)
{
ctx->r[2].ud[0] = 0;
ctx->pc = ctx->r[31].uw[0];
}
// sceGsSyncV(mode): the game waits for the next vblank (boot, loading screens, mode changes), and its frame ends
// there. As the engine's frameBoundary stand-in did: the parity of the frames ended by then, this one included,
// then the frame boundary.
void syncV(uint8_t *, R5900Context *ctx, Runtime *rt)
{
const uint64_t parity = (rt->port->libraries().framesEnded + 1u) & 1u;
ctx->r[2].ud[0] = parity;
bozo::port::frameEnd(rt, ctx);
ctx->pc = ctx->r[31].uw[0];
}
// sceGsResetGraph(mode, interlace, video mode, field mode): mode 0 sets the display mode, whose only effect left is
// the field clock the game runs on (NTSC 59.94 Hz; PAL 50 Hz for video mode 3). No GS, no display registers; the
// parameter words the GS stand-ins read are no longer read by anything.
void resetGraph(uint8_t *, R5900Context *ctx, Runtime *rt)
{
if (static_cast<int16_t>(ctx->r[4].uw[0]) == 0)
{
auto &kernel = bozo::port::dispatcher(rt).kernel();
if ((ctx->r[6].uw[0] & 0xffu) == 3u)
kernel.fieldRate(50, 1);
else
kernel.fieldRate(60000, 1001);
}
ctx->r[2].ud[0] = 0;
ctx->pc = ctx->r[31].uw[0];
}
void install(Runtime &rt, bozo::port::Registry &r)
{
r.registerFunction(0x112f00, syncV); // sceGsSyncV
r.registerFunction(0x1122b0, resetGraph); // sceGsResetGraph
dc::native::install(rt, r);
r.registerFunction(0x1145a0, noCache); // FlushCache
r.registerFunction(0x1145d0, noCache); // iFlushCache
r.registerFunction(0x114c50, noCache); // iSyncDCache
r.registerFunction(0x12d070, frameEnd);
r.nativeGraphics(&nativeInstruction);
}
+94
View File
@@ -0,0 +1,94 @@
// Dark Cloud's sound transport, native. The game talks to its sound driver (the IOP module the port compiles natively,
// runtime/dc_audio.cpp) through three routines only, and they stay the game's own code:
// - ezMidiInit binds the client at 0x1CECEC0 to RPC service 0x12346 with sceSifInitRpc / sceSifBindRpc, spinning between
// attempts until the server exists;
// - ezMidi(command, argument) spins 2000 times, then makes one blocking sceSifCallRpc: with command bit 0x1000 clear the
// argument goes into sbuff (0x1CECE80) and those 16 bytes are sent, with it set the 64 bytes at the argument are;
// with bit 0x8000 a 64-byte reply lands in sbuff, whose first word it returns;
// - ezTransToIOP(destination, source, bytes) fills a transfer record, calls FlushCache, sends it with sceSifSetDma and
// waits on sceSifDmaStat.
// Their seven library calls are guarded patches to nop (recomp/dc_native.patches), and each is a native site here: the
// RPC goes straight to the compiled module's handler (registered when the module called sceSifRegisterRpc), the bytes
// straight into its memory, with no SIF RPC, SIF DMA, DMA id, DMAC interrupt or cache flush. Each site charges the 8 EE
// cycles the call's checkpoint did; the spins stay, so the game's timeline is the original's.
// libsdr (sceSdRemoteInit, sceSdTransToIOP, sceSdRemote, the SDK's EE side of the sound-hardware driver, called by
// set_spu and CSound::SetReverb) is compiled with work in its delay slots: there each jal is a nop and the native site
// is the delay slot's instruction, which the handler does first, so the order is the original's.
#include "dc_sound.h"
#include "bozo/libs/guest.h"
#include "bozo/libs/libraries.h"
#include "bozo/port.h"
#include "bozo/runtime.h"
#include <cstring>
namespace dc::sound {
namespace {
uint32_t reg(const R5900Context *c,int r){return c->r[r].uw[0];}
void wr32(uint8_t *ram,uint32_t at,uint32_t v){std::memcpy(ram+(at&0x1ffffffu),&v,4);}
void setV0(R5900Context *c,int32_t v){c->r[2].ud[0]=static_cast<uint64_t>(static_cast<int64_t>(v));}
// What the call's checkpoint charged (bozo::checkpoint's accounting; the next checkpoint takes any event due).
void chargeCall(R5900Context *c){c->cycles+=8;++c->checkpoints;}
// sceSifBindRpc(client, service, mode): the client header as the engine's binding leaves it; the server handle only
// once the module's server exists (the game's loop then stops retrying).
void bind(uint8_t *ram,R5900Context *c,bozo::libs::Libraries &l)
{
const uint32_t client=reg(c,4),service=reg(c,5);
wr32(ram,client+4,++l.sif.rpcId);wr32(ram,client+8,0xffffffffu);
if(l.sif.servers.count(service)){wr32(ram,client+0x24,service|0x80000000u);l.sif.bound[client]=service;}
}
// sceSifCallRpc(client, fno, mode, send, ssize, receive, rsize, end): the module's handler answers within the call.
void call(uint8_t *ram,R5900Context *c,Runtime *rt,bozo::libs::Libraries &l)
{
const uint32_t client=reg(c,4),command=reg(c,5);
wr32(ram,client+0x0c,reg(c,6));wr32(ram,client+0x10,command);
const auto bound=l.sif.bound.find(client);
if(bound==l.sif.bound.end())return;
if(const auto server=l.sif.servers.find(bound->second);server!=l.sif.servers.end()){
bozo::libs::Guest guest(*rt,c);
server->second(l,guest,bozo::libs::NativeRpcRequest{command,reg(c,7),reg(c,8),reg(c,9),reg(c,10)});
}
}
// sceSifSetDma(transfers, count): each 16-byte record (source, destination, bytes) into the module's memory.
void transfer(R5900Context *c,Runtime *rt,bozo::libs::Libraries &l)
{
if(!l.sif.transfer)return;
bozo::libs::Guest guest(*rt,c);
for(uint32_t i=0;i<reg(c,5) && i<32;++i){
const uint32_t t=reg(c,4)+16*i,source=guest.read32(t),destination=guest.read32(t+4),bytes=guest.read32(t+8);
if(bytes && bytes<=0x200000u)l.sif.transfer(destination,guest.in(source,bytes),bytes);
}
}
}
// libsdr: the delay slot's own instruction, then the call it followed.
bool libsdrSite(uint8_t *ram,R5900Context *c,Runtime *rt,uint32_t pc)
{
if(pc!=kSdInitRpcSite && pc!=kSdBindRpcSite && pc!=kSdSetDmaSite && pc!=kSdDmaStatSite && pc!=kSdCallRpcSite &&
pc!=kSdCallRpcSite2)return false;
chargeCall(c);
auto &l=rt->port->libraries();
auto set=[c](int r,uint64_t v){c->r[r].ud[0]=v;};
if(pc==kSdInitRpcSite){set(17,0x2a0000u);setV0(c,0);} // lui s1,0x2a; sceSifInitRpc
else if(pc==kSdBindRpcSite){set(6,0);bind(ram,c,l);setV0(c,0);} // daddu a2,zero,zero; sceSifBindRpc
else if(pc==kSdSetDmaSite){wr32(ram,reg(c,2)+12,0);transfer(c,rt,l);setV0(c,1);} // sw zero,12(v0); sceSifSetDma
else if(pc==kSdDmaStatSite){set(4,c->r[17].ud[0]);setV0(c,-1);} // daddu a0,s1,zero; sceSifDmaStat
else{if(pc==kSdCallRpcSite)set(10,64);call(ram,c,rt,l);setV0(c,0);} // addiu t2,zero,64 / nop; sceSifCallRpc
return true;
}
bool nativeSite(uint8_t *ram,R5900Context *c,Runtime *rt,uint32_t pc)
{
if(libsdrSite(ram,c,rt,pc))return true;
if(pc!=kInitRpcSite && pc!=kBindRpcSite && pc!=kCallRpcSite && pc!=kCallRpcSite2 && pc!=kFlushSite &&
pc!=kSetDmaSite && pc!=kDmaStatSite)return false;
chargeCall(c);
auto &l=rt->port->libraries();
if(pc==kInitRpcSite)setV0(c,0); // sceSifInitRpc: nothing to set up
else if(pc==kBindRpcSite){bind(ram,c,l);setV0(c,0);}
else if(pc==kCallRpcSite || pc==kCallRpcSite2){call(ram,c,rt,l);setV0(c,0);}
else if(pc==kSetDmaSite){transfer(c,rt,l);setV0(c,1);} // a transfer id: done at once
else if(pc==kDmaStatSite)setV0(c,-1); // finished
return true; // FlushCache: no cache to write back
}
}
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <cstdint>
struct R5900Context;
struct Runtime;
namespace dc::sound {
// The library calls of ezMidiInit, ezMidi and ezTransToIOP, patched to nop: sceSifInitRpc, sceSifBindRpc, the two
// sceSifCallRpc, FlushCache, sceSifSetDma and sceSifDmaStat.
constexpr uint32_t kInitRpcSite=0x14797c,kBindRpcSite=0x147998,kCallRpcSite=0x147a70,kCallRpcSite2=0x147ab4,
kFlushSite=0x147b10,kSetDmaSite=0x147b24,kDmaStatSite=0x147b48;
// libsdr's (sceSdRemoteInit, sceSdTransToIOP, sceSdRemote: set_spu and CSound::SetReverb) calls, at the delay slot
// that followed each, as its handler first does that instruction: sceSifInitRpc (lui s1), sceSifBindRpc
// (daddu a2), sceSifSetDma (sw zero,12(v0)), sceSifDmaStat (daddu a0,s1) and the two sceSifCallRpc (addiu t2,64; nop).
constexpr uint32_t kSdInitRpcSite=0x121264,kSdBindRpcSite=0x121278,kSdSetDmaSite=0x121334,kSdDmaStatSite=0x12134c,
kSdCallRpcSite=0x121530,kSdCallRpcSite2=0x121564;
// The game's sound commands and sample uploads reach DC's compiled sound module (its RPC server and memory) directly,
// with no SIF RPC, SIF DMA or DMA interrupt in between. True when `pc` is one of the sites (handled).
bool nativeSite(uint8_t *ram, R5900Context *ctx, Runtime *rt, uint32_t pc);
}
+36
View File
@@ -0,0 +1,36 @@
// Dark Cloud's save-state section (dc_state.h): the parts the engine's own sections do not hold.
#include "dc_state.h"
#include "dc_cheats.h"
#include "dc_ingame_cheats.h"
#include "bozo/runtime.h"
#include "bozo/state.h"
namespace dc
{
void audioState(bozo::state::Archive &);
std::string audioUnsaveable();
namespace native
{
void state(bozo::state::Archive &, Runtime &);
std::string unsaveable();
}
}
namespace dc::state
{
void serialize(bozo::state::Archive &a, Runtime &runtime)
{
dc::audioState(a); // the compiled sound modules' IOP host
dc::native::state(a, runtime); // the renderer's and asset builders' facts; caches dropped on load
dc::cheats::menuState(a, runtime.memory.ram());
if (a.loading())
dc::cheats::stateLoaded();
}
std::string unsaveable()
{
if (std::string why = dc::audioUnsaveable(); !why.empty())
return why;
return dc::native::unsaveable();
}
}
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <string>
struct Runtime;
namespace bozo::state { class Archive; }
namespace dc::state {
// DC's save-state section: what the port keeps across frames that guest memory and the engine's own sections do not
// hold (the compiled sound modules' IOP host, facts the game told the native renderer once), and, on load, the caches
// decoded from the old guest memory dropped.
void serialize(bozo::state::Archive &, Runtime &);
// Why a state cannot be saved right now (empty: it can).
std::string unsaveable();
}
+956
View File
@@ -0,0 +1,956 @@
// Travel and progress cheats (dc_warp.h). Everything the game thread does here goes through the game's own state
// and routines, at the point main() reads the pad (CGamePad::UpDate, 0x12AD70: after the frame's town or dungeon
// loop, before the next), and only while the game is idle:
// - a town's free walk: main mode 2 (EditLoop), its GameMode 1, no fade, no exit pending;
// - a dungeon's free play: main mode 3 (GameLoop), BtGameModeFlag 1, gameTask 0, no event, no fade, not the back
// floor, no forced floor.
// Map numbers: < 200 a town or area (gedit/e01.. map 0.., s01.. map 11..), 200 + d dungeon d. MapJump(map, -1)
// (0x141D30) names the next map; the town leaves through EdExitLoop (0x178110) after an EdFadeOut, the dungeon
// through its own exit task (gameTask 0xAF: a fade, then MapJump to its town and existFlag 2; the next map is then
// replaced by the warp's). A dungeon is entered at a floor through the entrance menu's own preset (InitDunEnterMenu,
// 0x226110, a2 >= 0: it picks that floor by itself); another floor of the same dungeon is built by the stairs' path
// (floor - 1 as the floor, system event 100 as the next event, gameTask 0x190). See build notes for the evidence.
#include "dc_warp.h"
#include "dc_cheats.h"
#include "dc_pad.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <initializer_list>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
namespace dc::warp
{
namespace
{
// ---- the game's state ----
constexpr uint32_t kSaveData = 0x01CD4140u; // CSaveData
constexpr uint32_t kDngStatusInSave = kSaveData + 0x540Cu; // CDngStatusData (also in town)
constexpr uint32_t kMainMode = 0x002A2534u; // main()'s mode: 2 town (EditLoop), 3 dungeon (GameLoop)
constexpr uint32_t kMapNo = 0x002A2518u, kNextMapNo = 0x002A1E90u;
constexpr uint32_t kTownGameMode = 0x002A1F50u; // EditLoop's GameMode: 1 free walk, 0xC in an interior
constexpr uint32_t kInnerGameMode = 0x002A2A84u; // EditInLoop's GameMode (interiors): 0 free walk, 1 talk, 4 event
constexpr uint32_t kEventResult = 0x01D3D618u; // EdEventInfo+0x448: an event's result, 8 a map jump
constexpr uint32_t kNowEditMap = 0x002A2810u; // the loaded town (0..5)
constexpr uint32_t kFadeInOut = 0x002A29F8u, kFadeEnd = 0x002A29FCu, kExitLoop = 0x002A287Cu;
constexpr uint32_t kUserStatus = 0x002A3468u; // DUN: CDngStatusData *
constexpr uint32_t kBtGameMode = 0x002A355Cu, kGameTask = 0x002A35ECu, kExistFlag = 0x002A35F0u;
constexpr uint32_t kBtEventMode = 0x002A3608u, kBtUra = 0x002A34B4u, kBtMapJumpFloor = 0x002A2BE4u;
constexpr uint32_t kBtActBusy = 0x01DC4490u, kLockOn = 0x002A3588u;
constexpr uint32_t kEventNext = 0x01D5676Cu, kEventReload = 0x01D56774u; // BtEventInfo +0x2C, +0x34
constexpr uint32_t kMonsterUnit = 0x002A34D0u; // CMonstorUnit * (16 slots)
constexpr uint32_t kPlayer = 0x01EA1D20u, kCamera = 0x01DC45E0u;
constexpr uint32_t kDunResident = 0x01DB7450u;
constexpr uint32_t kGameClear = 0x002A2510u;
constexpr uint32_t kEditPartsLive = 0x01D19BF0u; // CEditPartsInfo of the loaded town
constexpr uint32_t kAtlaRows = 0x0025DF30u; // AtraAppearData: 6 pointers to {id, floor, count} rows
constexpr uint32_t kEditPartsData = 0x002540D0u; // [6 towns][24 parts] x 0xBC
// ---- the game's routines ----
constexpr uint32_t kPadUpdate = 0x0012AD70u, kEnterMenu = 0x00226110u, kEnterMenuReturn = 0x01DB4CA0u;
constexpr uint32_t kMapJump = 0x00141D30u, kExitLoopFn = 0x00178110u, kFadeOut = 0x00189790u;
constexpr uint32_t kSetPosition = 0x00138FB0u, kSetFollow = 0x00124AE0u, kCameraStep = 0x001247D0u;
constexpr uint32_t kSetGameFlag = 0x00158280u, kSetIntFlag = 0x00158360u, kVisitMap = 0x00158800u;
constexpr uint32_t kQuestDungeon = 0x00158870u, kPartsGet = 0x00158660u, kChipGet = 0x00158760u;
constexpr uint32_t kPartsLoad = 0x0019A3F0u, kEdGetItem = 0x001730A0u, kEquipDefault = 0x0020BFB0u;
constexpr uint32_t kReturnSentinel = 0x00080000u; // not code: a routine's jr ra lands here
constexpr uint32_t kRunTownEvent = 0x001779F0u, kTownCamera = 0x002A28F0u; // RunEvent(n, NowCamera), outdoor maps
const Place kPlaces[] = {
{0, "Norune Village"}, {1, "Matataki Village"}, {2, "Queens"}, {3, "Muska Lacka"}, {4, "Sun Giant georama"},
{11, "Area s01"}, {13, "Area s03"}, {14, "Brownboo Village"}, {19, "Area s09"}, {21, "Area s11"}, {22, "Area s12"},
{23, "Yellow Drops"}, {24, "Area s14"}, {25, "Area s15"}, {26, "Area s16"}, {27, "Area s17"}, {33, "Area s23"},
{34, "Area s24"}, {35, "Area s25"}, {36, "Area s26"}, {37, "Area s27"}, {38, "Area s28"}, {39, "Area s29"},
{40, "Dark Heaven Castle"}, {41, "Area s31"}, {42, "Sun & Moon Temple approach"}, {43, "Area s33"},
{44, "Area s34"}, {45, "Area s35"}, {46, "Area s36"}, {47, "Area s37"}, {48, "Area s38"}, {49, "Area s39"},
{50, "Area s40"}, {51, "Area s41, the ending"}, {60, "Demon Shaft entrance"}, {61, "Area s51"}, {87, "Area s77"},
{88, "Area s78"}, {89, "Area s79"}, {96, "Area s86"}, {97, "Area s87"}, {98, "Area s88"}, {100, "Area s90"},
{101, "Area s91"}, {102, "Area s92"}, {103, "Area s93"}, {104, "Area s94"}, {105, "Area s95"}, {106, "Area s96"},
{107, "Area s97"}, {108, "Area s98"}, {109, "Area s99"}};
const Dungeon kDungeons[] = {{"Divine Beast Cave", 15}, {"Wise Owl Forest", 17}, {"Shipwreck", 18},
{"Sun & Moon Temple", 18}, {"Moon Sea", 15}, {"Gallery of Time", 25},
{"Demon Shaft", 100}};
const char *const kChapters[] = {"", "1: Norune (the start)", "2: Matataki, Wise Owl Forest", "3: Queens, Shipwreck",
"4: Muska Lacka, Sun & Moon Temple", "5: Yellow Drops, Moon Sea",
"6: Dark Heaven Castle, Gallery of Time", "7: After the Dark Genie (post-game)"};
// ---- requests ----
enum class Kind { Place, Dungeon, Monster, Georama, World, Chapter, Cheat, Flag, IntFlag, Where, Talk, Wait, Peek,
Event, Kill, Party, Item, Press, Until, TownEvent };
struct Command
{
Kind kind;
int a = 0, b = 0;
std::string text;
};
std::mutex g_mutex;
std::deque<Command> g_queue;
std::string g_status = "Ready";
std::atomic<bool> g_busy{false};
struct Scheduled
{
uint64_t frame;
Command command;
};
std::vector<Scheduled> g_script; // sorted by frame
size_t g_scriptNext = 0;
std::atomic<uint64_t> g_frame{0}; // the host's frame (onFrame), for the log
void say(const std::string &text)
{
std::fprintf(stderr, "[dc:warp] frame %llu: %s\n", static_cast<unsigned long long>(g_frame.load()), text.c_str());
std::lock_guard<std::mutex> lock(g_mutex);
g_status = text;
}
std::deque<Command> g_immediate; // where / cheat: carried out at once, ahead of a warp under way
void push(Command command)
{
std::lock_guard<std::mutex> lock(g_mutex);
if (command.kind == Kind::Peek || command.kind == Kind::Cheat || command.kind == Kind::Talk)
g_immediate.push_back(std::move(command));
else
{
g_queue.push_back(std::move(command));
g_busy = true;
}
}
// ---- guest access ----
template <typename T> T rd(const uint8_t *ram, uint32_t address)
{
T value;
std::memcpy(&value, ram + (address & 0x1FFFFFFu), sizeof(T));
return value;
}
template <typename T> void wr(uint8_t *ram, uint32_t address, T value)
{
std::memcpy(ram + (address & 0x1FFFFFFu), &value, sizeof(T));
}
// A compiled game routine on a copy of the hook's context: its frame below the current stack, its return to a
// sentinel; false when it did not come back there (never for the routines called here).
bool call(Runtime *rt, uint8_t *ram, const R5900Context *ctx, uint32_t address, std::initializer_list<uint32_t> ints,
std::initializer_list<float> floats = {}, int32_t *result = nullptr)
{
RecompiledFunction routine = rt->functions.generated(address);
if (!routine)
return false;
R5900Context c = *ctx;
int reg = 4;
for (const uint32_t a : ints)
c.r[reg++].ud[0] = uint64_t(int64_t(int32_t(a)));
int f = 12;
for (const float v : floats)
c.f[f++] = v;
c.r[31].ud[0] = kReturnSentinel;
c.leaving = false;
routine(ram, &c, rt);
if (c.pc != kReturnSentinel || c.leaving)
return false;
if (result)
*result = static_cast<int32_t>(c.r[2].uw[0]);
return true;
}
int mainMode(const uint8_t *ram) { return rd<int32_t>(ram, kMainMode); }
bool townIdle(const uint8_t *ram)
{
return mainMode(ram) == 2 && rd<int32_t>(ram, kTownGameMode) == 1 && rd<int32_t>(ram, kFadeInOut) == 0 &&
rd<int32_t>(ram, kExitLoop) == 0;
}
// An interior's free walk (EditLoop runs EditInLoop: its GameMode 0xC, the interior's own GameMode 0).
bool interiorIdle(const uint8_t *ram)
{
return mainMode(ram) == 2 && rd<int32_t>(ram, kTownGameMode) == 0xC && rd<int32_t>(ram, kInnerGameMode) == 0 &&
rd<int32_t>(ram, kFadeInOut) == 0;
}
uint32_t userStatus(const uint8_t *ram) { return rd<uint32_t>(ram, kUserStatus) & 0x1FFFFFFu; }
bool dungeonIdle(const uint8_t *ram, Runtime *rt)
{
const uint32_t s = userStatus(ram);
return mainMode(ram) == 3 && rt->functions.generated(kDunResident) && s != 0u && s < 0x2000000u &&
rd<int32_t>(ram, kBtGameMode) == 1 && rd<int32_t>(ram, kGameTask) == 0 && rd<int32_t>(ram, kBtEventMode) == 0 &&
rd<int32_t>(ram, kExistFlag) == 0 && rd<int32_t>(ram, kFadeInOut) == 0 && rd<int32_t>(ram, kBtUra) == 0 &&
rd<int32_t>(ram, kBtMapJumpFloor) == -1 && rd<int32_t>(ram, kBtActBusy) == 0;
}
int currentDungeon(const uint8_t *ram) { return rd<int8_t>(ram, userStatus(ram)); }
int currentFloor(const uint8_t *ram) { return rd<int8_t>(ram, userStatus(ram) + 2u); }
std::string where(const uint8_t *ram)
{
char line[256];
const int mode = mainMode(ram);
const int d = mode == 3 ? currentDungeon(ram) : -1, f = mode == 3 ? currentFloor(ram) : -1;
std::snprintf(line, sizeof line, "where: mode %d map %d next %d town-mode %d/%d dungeon %d floor %d chapter %d party %d",
mode, rd<int32_t>(ram, kMapNo), rd<int32_t>(ram, kNextMapNo), rd<int32_t>(ram, kTownGameMode),
rd<int32_t>(ram, kInnerGameMode), d, f,
rd<int32_t>(ram, kSaveData + 0x10668u), rd<int8_t>(ram, kDngStatusInSave + 5u));
std::string out = line;
if (mode == 3)
{
std::snprintf(line, sizeof line, " | bt-mode %d task 0x%x event %d exist %d fade %d ura %d jump-floor %d act %d active %d",
rd<int32_t>(ram, kBtGameMode), rd<int32_t>(ram, kGameTask), rd<int32_t>(ram, kBtEventMode),
rd<int32_t>(ram, kExistFlag), rd<int32_t>(ram, kFadeInOut), rd<int32_t>(ram, kBtUra),
rd<int32_t>(ram, kBtMapJumpFloor), rd<int32_t>(ram, kBtActBusy), rd<int8_t>(ram, userStatus(ram) + 4u));
out += line;
// The floor's monsters: slot:HP for each one present (-1 empty slots left out).
const uint32_t unit = rd<uint32_t>(ram, kMonsterUnit) & 0x1FFFFFFu;
out += " monsters";
for (uint32_t i = 0; unit && i < 16u; ++i)
if (rd<int32_t>(ram, unit + 0x1E3D0u + i * 400u) != -1)
out += " " + std::to_string(i) + ":" + std::to_string(rd<int32_t>(ram, unit + 0x1E3F4u + i * 400u));
}
out += " cleared " + std::to_string(rd<int32_t>(ram, kGameClear)) + "/" + std::to_string(rd<int32_t>(ram, kSaveData + 0x38u)) +
" demon-shaft-visits " + std::to_string(rd<int16_t>(ram, kSaveData + 0x12EE8u + 60u * 2u));
out += " deepest";
for (int i = 0; i < 7; ++i)
out += " " + std::to_string(rd<int8_t>(ram, kDngStatusInSave + 0x42BFu + static_cast<uint32_t>(i)));
return out;
}
// ---- the executor ----
bool g_active = false;
Command g_current;
int g_phase = 0;
uint32_t g_waited = 0;
int g_presetFloor = -1; // the entrance menu's preset for the warp under way
bool g_interiorExit = false; // EditInLoop's next call answers 99 (an interior left for the map named)
int g_nextMonster = 0;
// talk 1 (scripts): Cross tapped every 16 frames while a town talk or event (GameMode 2 / 0xE) or a dungeon
// event (gameTask 0x191) waits, so a scripted run reads through the story; never in free walk or a menu.
bool g_talk = false;
uint32_t g_talkClock = 0;
// press <buttons> <frames> (scripts): buttons held on top of the controller for that many frames.
uint32_t g_pressButtons = 0, g_pressFrames = 0;
bool talking(const uint8_t *ram)
{
const int mode = mainMode(ram);
if (mode == 2)
{
const int town = rd<int32_t>(ram, kTownGameMode), inner = rd<int32_t>(ram, kInnerGameMode);
return town == 2 || town == 0xE || (town == 0xC && (inner == 1 || inner == 4));
}
return mode == 3 && rd<int32_t>(ram, kGameTask) == 0x191 && rd<int32_t>(ram, kBtGameMode) == 1;
}
void finish(const std::string &text)
{
say(text);
g_active = false;
std::lock_guard<std::mutex> lock(g_mutex);
g_busy = !g_queue.empty();
}
// A warp's target, a town (map < 200) or a dungeon (200 + d, floor b).
bool targetIsDungeon() { return g_current.kind == Kind::Dungeon; }
int targetMap() { return targetIsDungeon() ? 200 + g_current.a : g_current.a; }
std::string targetName()
{
if (targetIsDungeon())
return std::string(kDungeons[g_current.a].name) + " floor " + std::to_string(g_current.b + 1);
for (const Place &p : kPlaces)
if (p.map == g_current.a)
return p.name;
return "map " + std::to_string(g_current.a);
}
// The allies a dungeon's story floors need: their scenes load each ally's weapon, and an ally not yet in the
// party has none (the game then stops on its own assertion, "commenu/weapon/"). Divine Beast Cave from floor
// 11 (Xiao), then one more ally a dungeon; the Demon Shaft none. (Checked: Wise Owl Forest floor 4 stops with
// Toan alone and plays with three; the Demon Shaft's 100 floors play with Toan alone.)
int partyNeeded(int dungeon, int floor)
{
if (dungeon == 0)
return floor >= 10 ? 2 : 1;
return dungeon == 6 ? 1 : dungeon + 1;
}
void stepWarp(uint8_t *ram, const R5900Context *ctx, Runtime *rt)
{
const bool dungeonTarget = targetIsDungeon();
if (dungeonTarget && g_phase == 0)
if (const int needed = partyNeeded(g_current.a, g_current.b); rd<int8_t>(ram, kDngStatusInSave + 5u) < needed)
return finish(std::string("Not yet: ") + targetName() + " needs " + std::to_string(needed) +
" party members. Advance the story to chapter " + std::to_string(needed) + " first");
switch (g_phase)
{
case 0: // wait for an idle game, then fade out (or ask the dungeon to)
if (townIdle(ram))
{
call(rt, ram, ctx, kFadeOut, {30u}, {0.0f, 0.0f, 0.0f});
g_phase = 1;
}
else if (interiorIdle(ram))
{
call(rt, ram, ctx, kFadeOut, {30u}, {0.0f, 0.0f, 0.0f});
g_phase = 30;
}
else if (g_waited > 1800u && mainMode(ram) == 2 &&
(rd<int32_t>(ram, kTownGameMode) == 0xE ||
(rd<int32_t>(ram, kTownGameMode) == 0xC && rd<int32_t>(ram, kInnerGameMode) == 4)))
{
// A town or interior event that has run for 30 s (a later chapter's scene, out of its story): left
// as its own script leaves, the next map named and the event's result "map jump".
g_presetFloor = dungeonTarget ? g_current.b : -1;
call(rt, ram, ctx, kMapJump, {static_cast<uint32_t>(targetMap()), 0xFFFFFFFFu});
wr<int32_t>(ram, kEventResult, 8);
say("Leaving a long event for " + targetName());
g_phase = 2;
}
else if (dungeonIdle(ram, rt))
{
if (dungeonTarget && currentDungeon(ram) == g_current.a)
{
call(rt, ram, ctx, kFadeOut, {30u}, {0.0f, 0.0f, 0.0f});
g_phase = 10;
}
else
{
wr<int32_t>(ram, kGameTask, 0xAF); // the dungeon's exit: a fade, then its town's MapJump
g_phase = 20;
}
}
break;
case 1: // town: faded out; name the next map and leave
if (rd<int32_t>(ram, kFadeEnd) == 1 || rd<int32_t>(ram, kFadeInOut) == 0)
{
g_presetFloor = dungeonTarget ? g_current.b : -1;
call(rt, ram, ctx, kMapJump, {static_cast<uint32_t>(targetMap()), 0xFFFFFFFFu});
call(rt, ram, ctx, kExitLoopFn, {});
g_phase = 2;
}
break;
case 30: // interior: faded out; the next map named, and EditInLoop's next call answers 99 (what it returns
// after a script's _MAP_JUMP): the town loop then exits to the map named (EditExit, as there)
if (rd<int32_t>(ram, kFadeEnd) == 1 || rd<int32_t>(ram, kFadeInOut) == 0)
{
g_presetFloor = dungeonTarget ? g_current.b : -1;
call(rt, ram, ctx, kMapJump, {static_cast<uint32_t>(targetMap()), 0xFFFFFFFFu});
g_interiorExit = true;
g_phase = 2;
}
break;
case 10: // dungeon, same dungeon: faded out; the stairs' path builds the floor
if (rd<int32_t>(ram, kFadeEnd) == 1 || rd<int32_t>(ram, kFadeInOut) == 0)
{
const uint32_t s = userStatus(ram);
wr<int8_t>(ram, s + 2u, static_cast<int8_t>(g_current.b - 1)); // event 100 builds floor + 1
wr<int32_t>(ram, kEventNext, 100);
wr<int32_t>(ram, kEventReload, 0);
wr<int32_t>(ram, kGameTask, 0x190);
g_phase = 2;
}
break;
case 20: // dungeon exit under way: replace its town by the target once it names it
if (rd<int32_t>(ram, kExistFlag) == 2)
{
if (!dungeonTarget)
{
wr<int32_t>(ram, kNextMapNo, targetMap());
g_phase = 2;
}
else
g_phase = 0; // to the town first, then into the target dungeon from there
}
break;
case 2: // arrival: the target loaded (its own arrival scene may play on; the next command waits for it)
if (dungeonTarget ? mainMode(ram) == 3 && rt->functions.generated(kDunResident) && userStatus(ram) != 0u &&
currentDungeon(ram) == g_current.a && currentFloor(ram) == g_current.b &&
rd<int32_t>(ram, kGameTask) != 0x190 && rd<int32_t>(ram, kBtGameMode) == 1
: mainMode(ram) == 2 && rd<int32_t>(ram, kMapNo) == g_current.a && rd<int32_t>(ram, kNextMapNo) < 0 &&
rd<int32_t>(ram, kFadeInOut) == 0)
finish("Arrived: " + targetName());
break;
}
}
// The next live monster of the floor (state 1, HP > 0), cycling; the player put 20 units from it, toward where
// the player stood, through CCharacter::SetPosition (its attached frames follow), the camera snapped there.
void teleportToMonster(uint8_t *ram, const R5900Context *ctx, Runtime *rt)
{
const uint32_t unit = rd<uint32_t>(ram, kMonsterUnit) & 0x1FFFFFFu;
if (!unit)
return finish("No monster unit");
for (int k = 0; k < 16; ++k)
{
const int i = (g_nextMonster + k) % 16;
const uint32_t rec = unit + 0x1E3D0u + static_cast<uint32_t>(i) * 400u;
if (rd<int32_t>(ram, rec) != 1 || rd<int32_t>(ram, rec + 0x24u) <= 0)
continue;
const uint32_t pos = unit + 0x1FCE0u + static_cast<uint32_t>(i) * 0x3510u;
const float mx = rd<float>(ram, pos), my = rd<float>(ram, pos + 4u), mz = rd<float>(ram, pos + 8u);
const float px = rd<float>(ram, kPlayer + 0x10u), pz = rd<float>(ram, kPlayer + 0x18u);
float dx = px - mx, dz = pz - mz;
const float length = std::sqrt(dx * dx + dz * dz);
if (length > 0.001f)
dx /= length, dz /= length;
else
dx = 0.0f, dz = 1.0f;
const float x = mx + dx * 20.0f, z = mz + dz * 20.0f;
wr<int32_t>(ram, kLockOn, 0);
call(rt, ram, ctx, kSetPosition, {kPlayer}, {x, my, z});
call(rt, ram, ctx, kSetFollow, {kCamera}, {x, my + 13.0f, z});
call(rt, ram, ctx, kCameraStep, {kCamera, 0xFFFFFFFFu});
g_nextMonster = i + 1;
char text[96];
std::snprintf(text, sizeof text, "Next to monster %d (HP %d) at %.0f %.0f %.0f", i, rd<int32_t>(ram, rec + 0x24u), mx, my, mz);
return finish(text);
}
finish("No live monster on this floor");
}
// Every georama part of every town, as the dungeons' Atla tables give them (AtraAppearData), through the
// game's AtraPartsGet / AtraChipGet; elements already owned (in the inventory or attached) are not given twice.
// The dungeons' Atla are then marked collected (a never-entered dungeon is marked entered, so none are placed).
// The Sun Sphere is not in the tables (the Coliseum gives it). The loaded town reloads its live copy.
void giveGeorama(uint8_t *ram, const R5900Context *ctx, Runtime *rt)
{
int parts = 0, chips = 0;
for (uint32_t t = 0; t < 6u; ++t)
{
const uint32_t rows = rd<uint32_t>(ram, kAtlaRows + t * 4u) & 0x1FFFFFFu;
if (!rows)
continue;
std::vector<int> wanted(60, 0);
for (uint32_t r = rows; rd<int32_t>(ram, r) != -1; r += 12u)
if (const int id = rd<int32_t>(ram, r); id >= 40 && id < 100)
wanted[static_cast<size_t>(id - 40)] += std::max(1, rd<int32_t>(ram, r + 8u));
auto owned = [&](int chip) {
int n = 0;
const uint32_t inventory = kSaveData + 0x4CCCu + t * 0x100u;
for (uint32_t k = 0; k < 128u; ++k)
n += rd<int16_t>(ram, inventory + k * 2u) == chip;
const uint32_t town = kSaveData + 0x67Cu + t * 3000u;
for (uint32_t k = 0; k < 24u; ++k)
for (uint32_t j = 0; j < 6u; ++j)
if (rd<int32_t>(ram, kEditPartsData + (t * 24u + k) * 0xBCu + (5u + 7u * j) * 4u) == chip &&
rd<int16_t>(ram, town + 0x68u + k * 0x18u + 10u + j * 2u) != 0)
++n;
return n;
};
for (uint32_t r = rows; rd<int32_t>(ram, r) != -1; r += 12u)
{
const int id = rd<int32_t>(ram, r), count = std::max(1, rd<int32_t>(ram, r + 8u));
for (int c = 0; c < count; ++c)
if (id < 40)
{
int32_t got = 0;
if (call(rt, ram, ctx, kPartsGet, {kSaveData, t, static_cast<uint32_t>(id)}, {}, &got) && got)
++parts;
}
else if (id < 100 && owned(id - 40) < wanted[static_cast<size_t>(id - 40)])
{
call(rt, ram, ctx, kChipGet, {kSaveData, t, static_cast<uint32_t>(id - 40)});
++chips;
}
}
// The dungeon side: nothing left to collect.
const uint32_t s = kDngStatusInSave;
if (rd<int8_t>(ram, s + 0x42BFu + t) == -1)
wr<int8_t>(ram, s + 0x42BFu + t, 0);
for (uint32_t f = 0; f < 40u; ++f)
for (uint32_t k = 0; k < 8u; ++k)
{
const uint32_t slot = s + 0x278u + t * 0x500u + f * 0x20u + k * 4u;
if (rd<int32_t>(ram, slot) != -1)
wr<int32_t>(ram, slot, -3);
}
for (uint32_t i = 0; i < 100u; ++i)
wr<int32_t>(ram, s + 0x2078u + t * 0x4B0u + i * 0xCu, -1);
}
if (mainMode(ram) == 2)
if (const int town = rd<int32_t>(ram, kNowEditMap); town >= 0 && town < 6)
call(rt, ram, ctx, kPartsLoad, {kEditPartsLive, static_cast<uint32_t>(town), kSaveData, 0u});
finish("Georama: " + std::to_string(parts) + " parts and " + std::to_string(chips) + " elements given");
}
// Every world-map point: the towns' and areas' visit counters, the dungeons' entry counters, the World Map item.
void openWorld(uint8_t *ram, const R5900Context *ctx, Runtime *rt)
{
for (const int map : {0, 1, 14, 2, 3, 42, 23, 4, 40, 60})
if (rd<int16_t>(ram, kSaveData + 0x12EE8u + static_cast<uint32_t>(map) * 2u) <= 0)
call(rt, ram, ctx, kVisitMap, {kSaveData, static_cast<uint32_t>(map), 1u});
for (uint32_t d = 0; d < 6u; ++d)
if (rd<int16_t>(ram, kSaveData + 0x12F88u + d * 2u) <= 0)
call(rt, ram, ctx, kQuestDungeon, {kSaveData, d, 1u});
if (rd<int8_t>(ram, kDngStatusInSave + 0x4320u) == 0)
call(rt, ram, ctx, kEdGetItem, {238u, 1u, 0xFFFFFFFFu});
finish("World map: every town and dungeon shown");
}
// The chapter select: the cumulative state of every chapter before the target, as the transition scripts
// write it (the chapter counter, game flags, party and ally weapons, the dungeons cleared, the places visited).
struct Chapter
{
int counter, party, allyItem;
int dungeonDone; // -1 none
std::vector<int> visits, flags;
};
const Chapter kChapterSteps[] = {
{0, 1, -1, -1, {}, {}}, // 1 (nothing)
{100, 2, 22, 0, {0}, {0, 1, 18, 24, 25, 32, 37, 40, 49, 50, 100, 101, 102, 103, 104, 105, 106}}, // 2
{100, 3, 34, 1, {1, 14, 2}, {2, 3, 4, 5, 8, 9, 10, 11, 15, 16, 17, 19, 20, 21, 23, 31, 34, 43, 48, 51, 58, 111}}, // 3
{300, 4, 47, 2, {3, 42}, {6, 12, 13, 14, 28, 42, 47, 57, 120, 121, 122, 123, 124}}, // 4
{400, 5, 59, 3, {23, 4}, {26, 27, 38, 44, 52, 53, 54, 55, 130, 131, 132, 133, 134}}, // 5
{500, 6, 71, 4, {40}, {22, 29, 30, 35, 36, 39, 45, 46, 56, 140}}, // 6
{600, 6, -1, 5, {60}, {41, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241}}, // 7
};
void applyChapter(uint8_t *ram, const R5900Context *ctx, Runtime *rt, int chapter)
{
if (chapter < 1 || chapter > 7)
return finish("No such chapter");
for (int c = 2; c <= chapter; ++c)
{
const Chapter &step = kChapterSteps[c - 1];
for (const int f : step.flags)
call(rt, ram, ctx, kSetGameFlag, {kSaveData, static_cast<uint32_t>(f), 1u});
if (rd<int8_t>(ram, kDngStatusInSave + 5u) < step.party)
{
wr<int8_t>(ram, kDngStatusInSave + 5u, static_cast<int8_t>(step.party));
if (step.allyItem >= 0)
{
call(rt, ram, ctx, kEdGetItem, {static_cast<uint32_t>(step.allyItem), 1u, 0xFFFFFFFFu});
call(rt, ram, ctx, kEquipDefault, {static_cast<uint32_t>(step.party - 1)});
}
}
if (step.dungeonDone >= 0)
{
const uint32_t deepest = kDngStatusInSave + 0x42BFu + static_cast<uint32_t>(step.dungeonDone);
wr<int8_t>(ram, deepest, static_cast<int8_t>(std::max<int>(rd<int8_t>(ram, deepest), kDungeons[step.dungeonDone].floors - 1)));
if (rd<int16_t>(ram, kSaveData + 0x12F88u + static_cast<uint32_t>(step.dungeonDone) * 2u) <= 0)
call(rt, ram, ctx, kQuestDungeon, {kSaveData, static_cast<uint32_t>(step.dungeonDone), 1u});
}
for (const int map : step.visits)
if (rd<int16_t>(ram, kSaveData + 0x12EE8u + static_cast<uint32_t>(map) * 2u) <= 0)
call(rt, ram, ctx, kVisitMap, {kSaveData, static_cast<uint32_t>(map), 1u});
if (c == 2 && rd<int8_t>(ram, kDngStatusInSave + 0x4320u) == 0)
call(rt, ram, ctx, kEdGetItem, {238u, 1u, 0xFFFFFFFFu}); // the World Map (Norune, after Dran)
if (c == 6)
call(rt, ram, ctx, kChipGet, {kSaveData, 4u, 15u}); // the Sun Sphere (the Coliseum's)
if (c == 7)
{
call(rt, ram, ctx, kSetIntFlag, {kSaveData, 10u, 3u});
wr<int32_t>(ram, kSaveData + 0x38u, 1); // the game-cleared mark (the Demon Shaft)
wr<int32_t>(ram, kGameClear, 1);
}
}
if (rd<int32_t>(ram, kSaveData + 0x10668u) < kChapterSteps[chapter - 1].counter)
call(rt, ram, ctx, kSetIntFlag, {kSaveData, 0u, static_cast<uint32_t>(kChapterSteps[chapter - 1].counter)});
finish(std::string("Story: chapter ") + kChapters[chapter]);
}
bool setCheat(const std::string &name, bool on)
{
using C = dc::cheats::Cheat;
static const std::pair<const char *, C> kNames[] = {
{"health", C::InfiniteHealth}, {"durability", C::InfiniteWeaponDurability}, {"thirst", C::InfiniteThirst},
{"stamina", C::InfiniteStamina}, {"time", C::FreezeTimeOfDay}, {"fast", C::FastForwardLock},
{"fishing", C::FishingHelper}, {"map", C::RevealFloorMap}, {"onehit", C::OneHitKills},
{"nodamage", C::NoDamageTaken}, {"key", C::KeyFinder}};
for (const auto &[n, c] : kNames)
if (name == n)
{
dc::cheats::setEnabled(c, on);
return true;
}
return false;
}
void stepExecutor(uint8_t *ram, const R5900Context *ctx, Runtime *rt)
{
for (;;)
{
Command now;
{
std::lock_guard<std::mutex> lock(g_mutex);
if (g_immediate.empty())
break;
now = g_immediate.front();
g_immediate.pop_front();
}
if (now.kind == Kind::Peek)
say(where(ram));
else if (now.kind == Kind::Talk)
say((g_talk = now.a != 0) ? "Dialogue advance on" : "Dialogue advance off");
else
say(setCheat(now.text, now.a != 0) ? "Cheat " + now.text + (now.a ? " on" : " off") : "Unknown cheat " + now.text);
}
if (!g_active)
{
std::lock_guard<std::mutex> lock(g_mutex);
if (g_queue.empty())
return;
g_current = g_queue.front();
g_queue.pop_front();
g_active = true;
g_phase = 0;
g_waited = 0;
}
if (g_current.kind == Kind::Until) // until intflag <i> <value> / until flag <n>: at most 20 minutes
{
++g_waited;
const bool flag = g_current.text == "flag";
const int32_t value = flag ? int32_t((rd<uint32_t>(ram, kSaveData + 0x10268u + uint32_t(g_current.a >> 5) * 4u) >> (g_current.a & 31)) & 1u)
: rd<int32_t>(ram, kSaveData + 0x10668u + static_cast<uint32_t>(g_current.a) * 4u);
const std::string name = (flag ? "Story flag " : "Story counter ") + std::to_string(g_current.a);
if (value >= g_current.b)
return finish(name + " reached " + std::to_string(value));
if (g_waited > 72000u)
return finish(name + " never reached " + std::to_string(g_current.b));
return;
}
if (g_current.kind == Kind::Press) // press <buttons> <frames>: in turn, then held by the pad hook
{
g_pressButtons = static_cast<uint32_t>(g_current.a);
g_pressFrames = static_cast<uint32_t>(std::max(0, g_current.b));
return finish("Pressing " + g_current.text + " for " + std::to_string(g_current.b) + " frames");
}
if (g_current.kind == Kind::Wait) // wait <frames>: the next command that much later
{
if (++g_waited >= static_cast<uint32_t>(std::max(0, g_current.a)))
finish("Waited " + std::to_string(g_current.a) + " frames");
return;
}
// Everything else waits for an idle town or dungeon (at most two minutes of frames).
if (++g_waited > 7200u)
return finish("Gave up at step " + std::to_string(g_phase) + ": the game never became idle (" + where(ram) + ")");
const bool idle = townIdle(ram) || interiorIdle(ram) || dungeonIdle(ram, rt);
switch (g_current.kind)
{
case Kind::Where:
return finish(where(ram));
case Kind::Place:
case Kind::Dungeon:
return stepWarp(ram, ctx, rt);
case Kind::Monster:
if (dungeonIdle(ram, rt))
teleportToMonster(ram, ctx, rt);
else if (mainMode(ram) != 3)
finish("Monster teleport: only in a dungeon");
return;
case Kind::Georama:
if (idle)
giveGeorama(ram, ctx, rt);
return;
case Kind::World:
if (idle)
openWorld(ram, ctx, rt);
return;
case Kind::Chapter:
if (idle)
applyChapter(ram, ctx, rt, g_current.a);
return;
case Kind::Event:
// event <n> (a dungeon's system event, as the stairs run event 100: the boss's start, 500, where the
// dungeon has one). Free play only.
if (dungeonIdle(ram, rt))
{
wr<int32_t>(ram, kEventNext, g_current.a);
wr<int32_t>(ram, kEventReload, g_current.b); // 1: the read buffers and monster views reset first
wr<int32_t>(ram, kGameTask, 0x190);
finish("Dungeon event " + std::to_string(g_current.a) + " started");
}
else if (mainMode(ram) != 3)
finish("Dungeon event: only in a dungeon");
return;
case Kind::Kill:
// kill: every live monster of the floor (bosses too) defeated by the game's own poison tick: its
// countdown (+0xC) at 1 and its strength (+0x20) past its HP (CMonstorUnit::CheckDmg takes 0.1 x the
// strength when the countdown runs out; below 1 HP it is the monster's death, as from a blow: the
// kill counted, the death and, for a boss, its defeat scene). Editing HP alone skips that death.
// It waits (at most two minutes) for a dungeon's free play with a live monster: a boss may first need
// its scene, or the story may pass through another map on the way.
if (mainMode(ram) == 3 && rt->functions.generated(kDunResident) && rd<int32_t>(ram, kGameTask) == 0 &&
[&] {
const uint32_t unit = rd<uint32_t>(ram, kMonsterUnit) & 0x1FFFFFFu;
for (uint32_t i = 0; unit && i < 16u; ++i)
if (rd<int32_t>(ram, unit + 0x1E3D0u + i * 400u) != -1 && rd<int32_t>(ram, unit + 0x1E3F4u + i * 400u) > 0)
return true;
return false;
}())
{
const uint32_t unit = rd<uint32_t>(ram, kMonsterUnit) & 0x1FFFFFFu;
int poisoned = 0;
for (uint32_t i = 0; unit && i < 16u; ++i)
{
const uint32_t rec = unit + 0x1E3D0u + i * 400u;
const int32_t hp = rd<int32_t>(ram, rec + 0x24u);
if (rd<int32_t>(ram, rec) != -1 && hp > 0)
{
wr<int32_t>(ram, rec + 0xCu, 1);
wr<int32_t>(ram, rec + 0x20u, std::min(hp, 10000000) * 10 + 100);
++poisoned;
}
}
finish("Defeating " + std::to_string(poisoned) + " monsters");
}
return;
case Kind::Party:
// party <n>: the allies up to n, as their join scenes give them (the party size, the ally's weapon
// through EdGetItem, its default weapon selected).
if (idle)
{
static const int kAllyItem[] = {0, 0, 22, 34, 47, 59, 71};
const int target = std::clamp(g_current.a, 1, 6);
for (int n = rd<int8_t>(ram, kDngStatusInSave + 5u) + 1; n <= target; ++n)
{
wr<int8_t>(ram, kDngStatusInSave + 5u, static_cast<int8_t>(n));
call(rt, ram, ctx, kEdGetItem, {static_cast<uint32_t>(kAllyItem[n]), 1u, 0xFFFFFFFFu});
call(rt, ram, ctx, kEquipDefault, {static_cast<uint32_t>(n - 1)});
}
finish("Party: " + std::to_string(rd<int8_t>(ram, kDngStatusInSave + 5u)));
}
return;
case Kind::TownEvent:
// townevent <n>: a town or area map's own event (its event.stb), as its triggers run it: RunEvent.
if (townIdle(ram))
{
call(rt, ram, ctx, kRunTownEvent, {static_cast<uint32_t>(g_current.a), rd<uint32_t>(ram, kTownCamera)});
finish("Town event " + std::to_string(g_current.a) + " started");
}
return;
case Kind::Item:
if (idle)
{
call(rt, ram, ctx, kEdGetItem, {static_cast<uint32_t>(g_current.a), static_cast<uint32_t>(std::max(1, g_current.b)), 0xFFFFFFFFu});
finish("Item " + std::to_string(g_current.a) + " x" + std::to_string(std::max(1, g_current.b)));
}
return;
case Kind::Until:
// until intflag <i> <value>: wait (up to the frames given, else 20 minutes) for a story counter
if (rd<int32_t>(ram, kSaveData + 0x10668u + static_cast<uint32_t>(g_current.a) * 4u) >= g_current.b)
return finish("Story counter " + std::to_string(g_current.a) + " reached " + std::to_string(g_current.b));
if (g_waited > 72000u)
return finish("Story counter " + std::to_string(g_current.a) + " never reached " + std::to_string(g_current.b));
return;
case Kind::Flag:
if (idle)
{
call(rt, ram, ctx, kSetGameFlag, {kSaveData, static_cast<uint32_t>(g_current.a), static_cast<uint32_t>(g_current.b)});
finish("Game flag " + std::to_string(g_current.a) + " = " + std::to_string(g_current.b));
}
return;
case Kind::IntFlag:
if (idle)
{
call(rt, ram, ctx, kSetIntFlag, {kSaveData, static_cast<uint32_t>(g_current.a), static_cast<uint32_t>(g_current.b)});
finish("Game int flag " + std::to_string(g_current.a) + " = " + std::to_string(g_current.b));
}
return;
default:
return;
}
}
RecompiledFunction g_padUpdate = nullptr, g_enterMenu = nullptr, g_interiorLoop = nullptr;
constexpr uint32_t kInteriorLoop = 0x0019C2B0u; // EditInLoop: 99 = leave for NextMapNo
void interiorLoopHook(uint8_t *ram, R5900Context *ctx, Runtime *rt)
{
if (g_interiorExit)
{
g_interiorExit = false;
ctx->r[2].ud[0] = 99u;
ctx->pc = ctx->r[31].uw[0];
return;
}
g_interiorLoop(ram, ctx, rt);
}
void padUpdateHook(uint8_t *ram, R5900Context *ctx, Runtime *rt)
{
stepExecutor(ram, ctx, rt);
const bool tap = g_talk && talking(ram) && (++g_talkClock % 16u) == 0u;
uint32_t held = tap ? 0x40u : 0u; // Cross, for this frame's read only
if (g_pressFrames)
--g_pressFrames, held |= g_pressButtons;
dc::pad::press(held);
g_padUpdate(ram, ctx, rt);
dc::pad::press(0u);
}
// The entrance menu, from the dungeon's arrival event: a warp's floor as its preset (it picks it by itself).
void enterMenuHook(uint8_t *ram, R5900Context *ctx, Runtime *rt)
{
if (g_presetFloor >= 0 && static_cast<uint32_t>(ctx->r[31].uw[0]) == kEnterMenuReturn)
{
ctx->r[6].ud[0] = static_cast<uint64_t>(g_presetFloor);
g_presetFloor = -1;
}
g_enterMenu(ram, ctx, rt);
}
bool parse(const std::string &line, Command &out)
{
std::istringstream in(line);
std::string word;
if (!(in >> word))
return false;
if (word == "place" && (in >> out.a))
return out.kind = Kind::Place, true;
if (word == "dungeon" && (in >> out.a >> out.b) && out.a >= 0 && out.a < 7)
return out.kind = Kind::Dungeon, out.b = std::clamp(out.b - 1, 0, kDungeons[out.a].floors - 1), true;
if (word == "monster")
return out.kind = Kind::Monster, true;
if (word == "georama")
return out.kind = Kind::Georama, true;
if (word == "world")
return out.kind = Kind::World, true;
if (word == "chapter" && (in >> out.a))
return out.kind = Kind::Chapter, true;
if (word == "flag" && (in >> out.a >> out.b))
return out.kind = Kind::Flag, true;
if (word == "intflag" && (in >> out.a >> out.b))
return out.kind = Kind::IntFlag, true;
if (word == "where")
return out.kind = Kind::Where, true;
if (word == "peek")
return out.kind = Kind::Peek, true;
if (word == "talk" && (in >> out.a))
return out.kind = Kind::Talk, true;
if (word == "wait" && (in >> out.a))
return out.kind = Kind::Wait, true;
if (word == "event" && (in >> out.a))
{
if (!(in >> out.b))
out.b = 1;
return out.kind = Kind::Event, true;
}
if (word == "kill")
return out.kind = Kind::Kill, true;
if (word == "townevent" && (in >> out.a))
return out.kind = Kind::TownEvent, true;
if (word == "party" && (in >> out.a))
return out.kind = Kind::Party, true;
if (word == "item" && (in >> out.a))
{
if (!(in >> out.b))
out.b = 1;
return out.kind = Kind::Item, true;
}
if (word == "until" && (in >> out.text))
{
if (out.text == "intflag" && (in >> out.a >> out.b))
return out.kind = Kind::Until, true;
if (out.text == "flag" && (in >> out.a))
return out.b = 1, out.kind = Kind::Until, true;
return false;
}
if (word == "press" && (in >> out.text >> out.b))
{
// Buttons by name, joined with '+': cross circle square triangle l1 r1 l2 r2 up down left right start
// select (DC's word: Cross 0x40, Circle 0x20, Square 0x80, Triangle 0x10, R1 8, L1 4, R2 2, L2 1, ...).
static const std::pair<const char *, int> kButtons[] = {
{"cross", 0x40}, {"circle", 0x20}, {"square", 0x80}, {"triangle", 0x10}, {"r1", 8}, {"l1", 4}, {"r2", 2},
{"l2", 1}, {"up", 0x1000}, {"down", 0x4000}, {"left", 0x8000}, {"right", 0x2000}, {"start", 0x800},
{"select", 0x100}};
out.a = 0;
std::stringstream names(out.text);
std::string name;
while (std::getline(names, name, '+'))
{
bool found = false;
for (const auto &[n, bits] : kButtons)
if (name == n)
out.a |= bits, found = true;
if (!found)
return false;
}
return out.kind = Kind::Press, true;
}
if (word == "cheat" && (in >> out.text >> out.a))
return out.kind = Kind::Cheat, true;
return false;
}
}
int placeCount() { return static_cast<int>(std::size(kPlaces)); }
Place place(int index) { return kPlaces[std::clamp(index, 0, placeCount() - 1)]; }
int dungeonCount() { return static_cast<int>(std::size(kDungeons)); }
Dungeon dungeon(int index) { return kDungeons[std::clamp(index, 0, dungeonCount() - 1)]; }
int chapterCount() { return 7; }
const char *chapterName(int chapter) { return kChapters[std::clamp(chapter, 1, 7)]; }
const char *chapterShort(int chapter)
{
static const char *const kShort[] = {"", "1 Norune", "2 Matataki", "3 Queens", "4 Muska Lacka", "5 Yellow Drops", "6 Dark Heaven", "7 Post-game"};
return kShort[std::clamp(chapter, 1, 7)];
}
void requestPlace(int map) { push({Kind::Place, map}); }
void requestDungeon(int d, int floor)
{
d = std::clamp(d, 0, dungeonCount() - 1);
push({Kind::Dungeon, d, std::clamp(floor, 0, kDungeons[d].floors - 1)});
}
void requestMonster() { push({Kind::Monster}); }
void requestGeorama() { push({Kind::Georama}); }
void requestWorld() { push({Kind::World}); }
void requestChapter(int chapter) { push({Kind::Chapter, chapter}); }
std::string status()
{
std::lock_guard<std::mutex> lock(g_mutex);
return g_status;
}
bool busy() { return g_busy.load(); }
// The file's lines: "<frame> <command> [args]", '#' starts a comment. Commands: place <map>, dungeon <d> <floor
// 1-based>, monster, georama, world, chapter <1..7>, flag <i> <0|1>, intflag <i> <value>, cheat <name> <0|1>
// (health durability thirst stamina time fast fishing map onehit nodamage key), where (the state, logged, in turn),
// peek (the same at once), talk <0|1>
// (Cross tapped through dialogue and events), wait <frames> (the next command that much later).
// Each is queued when the game reaches its frame and carried out when the game is idle, in order.
bool loadScript(const std::string &path)
{
std::ifstream in(path);
if (!in)
return false;
std::string line;
int number = 0;
while (std::getline(in, line))
{
++number;
if (const size_t hash = line.find('#'); hash != std::string::npos)
line.resize(hash);
std::istringstream words(line);
uint64_t frame = 0;
if (!(words >> frame))
continue;
std::string rest;
std::getline(words, rest);
Command command;
if (!parse(rest, command))
{
std::fprintf(stderr, "[dc:warp] %s:%d: not a command: %s\n", path.c_str(), number, rest.c_str());
return false;
}
g_script.push_back({frame, command});
}
std::stable_sort(g_script.begin(), g_script.end(), [](const Scheduled &a, const Scheduled &b) { return a.frame < b.frame; });
std::fprintf(stderr, "[dc:warp] %zu scripted commands from %s\n", g_script.size(), path.c_str());
return true;
}
void onFrame(uint64_t frame)
{
g_frame.store(frame);
while (g_scriptNext < g_script.size() && g_script[g_scriptNext].frame <= frame)
{
std::fprintf(stderr, "[dc:warp] frame %llu: queued\n", static_cast<unsigned long long>(frame));
push(g_script[g_scriptNext++].command);
}
}
void install(Runtime &runtime, bozo::port::Registry &registry)
{
if ((g_padUpdate = runtime.functions.generated(kPadUpdate)))
registry.registerFunction(kPadUpdate, &padUpdateHook);
if ((g_enterMenu = runtime.functions.generated(kEnterMenu)))
registry.registerFunction(kEnterMenu, &enterMenuHook);
if ((g_interiorLoop = runtime.functions.generated(kInteriorLoop)))
registry.registerFunction(kInteriorLoop, &interiorLoopHook);
}
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
// Travel and progress cheats: warps to any town, area or dungeon floor, a teleport to the floor's monsters, every
// georama part, every world-map place, and the story chapters. Requests come from any thread (the menus, the
// --cheat-script file); the game thread carries them out through the game's own routines once it is idle (a town's
// free walk, a dungeon's free play), one at a time.
#include "bozo/port.h"
#include "bozo/runtime.h"
#include <cstdint>
#include <string>
namespace dc::warp
{
// The places a warp reaches: the towns and areas the disc has a map for (gedit/eNN, sNN).
struct Place
{
int map;
const char *name;
};
int placeCount();
Place place(int index);
// The dungeons (map 200 + index) and their floor counts.
struct Dungeon
{
const char *name;
int floors;
};
int dungeonCount();
Dungeon dungeon(int index);
// The story chapters a chapter select reaches (1 the start of the game ... 7 after the Dark Genie).
int chapterCount();
const char *chapterName(int chapter);
const char *chapterShort(int chapter); // "3 Queens": for narrow menus
void requestPlace(int map); // a town or area by map number, its default entrance
void requestDungeon(int dungeon, int floor); // floor 0-based; arrives through the game's own floor build
void requestMonster(); // in a dungeon: next to the next live monster of the floor
void requestGeorama(); // every georama part of every town, as if every Atla were opened
void requestWorld(); // every town and dungeon shown on the world map, the World Map item
void requestChapter(int chapter); // the story state a playthrough has at that chapter's start
// What happened last ("Warped to ...", "Waiting for free walk", ...), for the menus.
std::string status();
bool busy();
// --cheat-script FILE: lines "<frame> <command> [args]" queued as the game reaches each frame (see dc_warp.cpp).
bool loadScript(const std::string &path);
void onFrame(uint64_t frame);
void install(Runtime &runtime, bozo::port::Registry &registry);
}
+2
View File
@@ -8,6 +8,8 @@
# Takes and releases are announced in the c2c f2f lane when the local hook build/announce.sh exists (not committed:
# it holds the room connection).
source "$(dirname "$0")/common.sh"
# The lock tool comes with the pinned BozoEngine release (fetched once into BozoEngine/).
[ -f "$ROOT/BozoEngine/tools/bench_lock.sh" ] || cmake -P "$ROOT/cmake/bozo_engine_fetch.cmake" >&2
source "$ROOT/BozoEngine/tools/bench_lock.sh"
[ -x "$ROOT/build/announce.sh" ] && export PS2X_BENCH_LOCK_ANNOUNCE="$ROOT/build/announce.sh"
+2
View File
@@ -7,6 +7,8 @@ source "$(dirname "$0")/common.sh"
# The lock tool is not written for common.sh's set -euo pipefail: its checks return false while it waits (two-slot
# version, main c3524b7), which ended this script silently before the command ran.
set +euo pipefail
# The lock tool comes with the pinned BozoEngine release (fetched once into BozoEngine/).
[ -f "$ROOT/BozoEngine/tools/bench_lock.sh" ] || cmake -P "$ROOT/cmake/bozo_engine_fetch.cmake" >&2
source "$ROOT/BozoEngine/tools/bench_lock.sh"
[ -x "$ROOT/build/announce.sh" ] && export PS2X_BENCH_LOCK_ANNOUNCE="$ROOT/build/announce.sh"
alone=""
+2 -1
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env bash
# Build BozoEngine's static recompiler and native-library binder.
source "$(dirname "$0")/common.sh"
cmake -S "$ROOT/BozoEngine" -B "$TOOLS_BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release -DBOZO_BUILD_TOOLS=OFF "$@"
fetch_engine
cmake -S "$ENGINE" -B "$TOOLS_BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release -DBOZO_BUILD_TOOLS=OFF "$@"
cmake --build "$TOOLS_BUILD" --target bozo-recomp bozo-externals -j "$JOBS"
+7
View File
@@ -19,6 +19,13 @@ if [ -z "${TMP:-}" ] || [ -z "${TEMP:-}" ]; then
export TMP="$ROOT/build/tmp" TEMP="$ROOT/build/tmp"
fi
# BozoEngine: BOZO_ENGINE_DIR (a checkout, for engine work not released yet), else the release cmake/bozo_engine.json
# pins, fetched into BozoEngine/ (nothing is downloaded while BozoEngine/.release matches the pin).
ENGINE="${BOZO_ENGINE_DIR:-$ROOT/BozoEngine}"
fetch_engine() {
[ -n "${BOZO_ENGINE_DIR:-}" ] || cmake -P "$ROOT/cmake/bozo_engine_fetch.cmake"
}
configure_game() {
cmake -S "$ROOT" -B "$GAME_BUILD" -G Ninja -DCMAKE_BUILD_TYPE="${BUILD_TYPE:-Release}" "$@"
}
+2 -1
View File
@@ -3,7 +3,8 @@ source "$(dirname "$0")/common.sh"
mkdir -p "$ROOT/build"
extra=()
[ ! -f "$GAME_BUILD/dc_gen/dc.elf" ] || extra+=("-DBOZO_TEST_ELF=$GAME_BUILD/dc_gen/dc.elf")
cmake -S "$ROOT/BozoEngine" -B "$TOOLS_BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release \
fetch_engine
cmake -S "$ENGINE" -B "$TOOLS_BUILD" -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DBUILD_TESTING=ON -DBOZO_BUILD_TOOLS=OFF "${extra[@]}" "$@"
cmake --build "$TOOLS_BUILD" -j "$JOBS"
ctest --test-dir "$TOOLS_BUILD" --output-on-failure
+5 -5
View File
@@ -192,10 +192,10 @@ int main()
// Fast-forward.
check(gameSpeedPercent()==100,"normal speed by default");
setFastForwardHeld(true);check(gameSpeedPercent()==300,"held: the fast-forward speed (300% by default)");
setFastForwardPercent(1000);check(gameSpeedPercent()==400,"fast-forward speed capped at 400%");
setFastForwardHeld(false);check(gameSpeedPercent()==100,"released: normal speed");
setEnabled(Cheat::FastForwardLock,true);check(gameSpeedPercent()==400,"locked on without holding");
setEnabled(Cheat::FastForwardLock,false);setFastForwardPercent(300);
setEnabled(Cheat::FastForwardLock,true);check(gameSpeedPercent()==300,"locked on: the Video tab's speed (300% by default)");
setFastForwardPercent(1000);check(gameSpeedPercent()==1000,"the Video tab's speed is taken as it is (up to 10x)");
setFastForwardPercent(0);check(gameSpeedPercent()==0,"unlimited: 0");
setEnabled(Cheat::FastForwardLock,false);check(gameSpeedPercent()==100,"off: normal speed");
setFastForwardPercent(300);
std::printf("Extra cheats: %d failures\n",failures);return failures?1:0;
}
+32 -1
View File
@@ -2,6 +2,9 @@
// player state. Real cheat resource hooks consume the queued weapon edit.
#include "../runtime/dc_ingame_cheats.h"
#include "../runtime/dc_cheats.h"
#include "../runtime/dc_warp.h"
#include "../runtime/dc_language.h"
#include <filesystem>
#include "bozo/port.h"
#include "bozo/runtime.h"
#include "bozo/render/renderer.h"
@@ -115,6 +118,15 @@ int main(){
tap(*rt,p,0x40);tap(*rt,p,0x4000);tap(*rt,p,0x40);
check(dc::cheats::takeIngameQuitRequest() && !dc::cheats::takeIngameQuitRequest(),"explicit Quit Game confirmation produces one shutdown request");
call(*rt,p,exitPc);
// Travel: the fourth entry; its warp row queues a request for the game thread (carried out once play is idle).
call(*rt,p,initPc);finishFade(*rt,p);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x40); // Root -> Travel
check(!dc::warp::busy(),"opening Travel queues nothing");
tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x40); // the next town, then Warp to the town
check(dc::warp::busy(),"Warp to the town queues the warp");
draw(*rt,p);const auto travelPage=bozo::render::Renderer::instance().published();
check(travelPage && travelPage->batches.size()>=2,"Travel page draws native text and board");
tap(*rt,p,0x20);check(read<int32_t>(r,phase)==0,"back from Travel returns to root without closing");
tap(*rt,p,0x20);finishFade(*rt,p);
// Graphics: without the window (headless) the page only explains; with it, Apply posts the edited settings once.
call(*rt,p,initPc);finishFade(*rt,p);tap(*rt,p,0x4000);tap(*rt,p,0x40); // Root -> Graphics
tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x40);
@@ -125,14 +137,33 @@ int main(){
tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x2000);
check(postCalls==0,"Graphics edits wait for Apply");
draw(*rt,p);const auto graphics=bozo::render::Renderer::instance().published();check(graphics && graphics->batches.size()>=2,"Graphics page draws native text and board");
// Widescreen on, anti-aliasing 2x, texture smoothing trilinear, then Apply.
tap(*rt,p,0x4000);tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x2000);
tap(*rt,p,0x4000);tap(*rt,p,0x40);
check(postCalls==1 && postedSave && posted.mode==video::WindowMode::Fullscreen && posted.width==1920 && posted.height==1080 &&
posted.renderScale==1.5f && posted.frameRate==-1,"Apply posts mode, size, render scale and frame rate once, saved");
check(posted.widescreen && posted.antiAliasing==2 && posted.textureSmoothing==1,
"Apply posts widescreen, anti-aliasing and texture smoothing");
tap(*rt,p,0x4000);tap(*rt,p,0x2000);tap(*rt,p,0x4000);tap(*rt,p,0x2000); // Display -> Borderless; its size row is locked
tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x40);
tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x40);
check(postCalls==2 && posted.mode==video::WindowMode::Borderless && posted.width==1280 && posted.height==960,
"Borderless keeps the window size it returns to");
const int exitsBefore=exitCalls;tap(*rt,p,0x20);tap(*rt,p,0x20);finishFade(*rt,p);check(exitCalls==exitsBefore+1,"Options still closes after Graphics");
// Language: the fifth entry. Without game.ini's place (headless) it only explains; with it, Cross saves the choice
// for the next start and leaves the running game's LanguageCode alone.
write<uint32_t>(r,dc::language::kLanguageCode,1);
call(*rt,p,initPc);finishFade(*rt,p);for(int i=0;i<4;++i)tap(*rt,p,0x4000);tap(*rt,p,0x40); // Root -> Language
tap(*rt,p,0x4000);tap(*rt,p,0x40);draw(*rt,p);const auto noFile=bozo::render::Renderer::instance().published();
check(noFile && noFile->batches.size()>=2,"Language without game.ini's place draws its notice");
const auto ini=std::filesystem::temp_directory_path()/"dc_menu_language_test.ini";std::filesystem::remove(ini);
dc::cheats::setLanguageFile(ini);tap(*rt,p,0x20);tap(*rt,p,0x40); // back to Root, Language again: opens on English
tap(*rt,p,0x4000);tap(*rt,p,0x40); // Francais
check(dc::language::readIni(ini)=="fr","Cross on Francais saves language = fr");
check(read<uint32_t>(r,dc::language::kLanguageCode)==1,"the running game keeps its language until it starts again");
tap(*rt,p,0x20);tap(*rt,p,0x40); // reopened: the cursor is on the saved choice
tap(*rt,p,0x4000);tap(*rt,p,0x40);check(dc::language::readIni(ini)=="de","the page opens on the saved choice (Down from Francais is Deutsch)");
draw(*rt,p);const auto langPage=bozo::render::Renderer::instance().published();check(langPage && langPage->batches.size()>=2,"Language page draws native text and board");
tap(*rt,p,0x20);tap(*rt,p,0x20);finishFade(*rt,p);std::filesystem::remove(ini);dc::cheats::setLanguageFile({});
std::memset(r+record+8,0,32);call(*rt,p,initPc);finishFade(*rt,p);const int fallback=drawCalls;draw(*rt,p);
check(drawCalls==fallback+1,"missing font falls back to original Options without trapping input");
for(int i=0;i<4;++i)dc::cheats::setEnabled(static_cast<dc::cheats::Cheat>(i),false);
+56
View File
@@ -0,0 +1,56 @@
// The game's language setting (dc_language.h): the choices, game.ini's reading and LanguageCode in guest memory.
#include "dc_language.h"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <vector>
namespace
{
int failures = 0;
void check(bool ok, const char *what)
{
if (!ok)
{
++failures;
std::printf("FAIL: %s\n", what);
}
}
std::string iniWith(const std::filesystem::path &file, const char *text)
{
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
return dc::language::readIni(file);
}
}
int main(int, char **argv)
{
using namespace dc::language;
check(choices().size() == 4, "four languages");
check(find("en") && find("en")->code == 1, "English is the USA disc's own code 1");
check(find("fr") && find("fr")->code == 3, "French 3");
check(find("DE") && find("DE")->code == 4, "German 4, any case");
check(find("it") && find("it")->code == 5, "Italian 5");
check(!find("es") && !find("") && !find("jp") && !find("english"), "Spanish and anything else refused");
const auto file = std::filesystem::path(argv[0]).parent_path() / "dc_language_test.ini";
check(iniWith(file, "# Dark Cloud\n[game]\nlanguage = fr\n") == "fr", "section and comment skipped");
check(iniWith(file, "[game]\r\n language=it ; Italiano\r\n") == "it", "CRLF, spaces and a trailing comment");
check(iniWith(file, "[game]\nlanguages = de\nlang = de\n") == "", "only the language key");
check(iniWith(file, "# language = de\n") == "", "a commented line");
std::filesystem::remove(file);
check(readIni(file) == "", "no file");
std::vector<uint8_t> ram(32u << 20, 0);
const uint32_t usa = 1;
std::memcpy(ram.data() + kLanguageCode, &usa, 4);
apply(ram.data(), *find("de"));
uint32_t code = 0;
std::memcpy(&code, ram.data() + kLanguageCode, 4);
check(code == 4, "LanguageCode written");
check(ram[kLanguageCode - 1] == 0 && ram[kLanguageCode + 4] == 0, "nothing around it");
std::printf("%s (%d failures)\n", failures ? "FAILED" : "dc_language: all checks passed", failures);
return failures ? 1 : 0;
}
+2 -1
View File
@@ -136,7 +136,8 @@ int main()
savedQwords += savings; word(expected.data(), counter, originalCounter - savings);
for (auto offset : {0x73f8u,0x73f4u}) word(expected.data(), gp - offset, 0x5a5a5a5a);
}
if (kind == 2) { check(channels == 1, "adapted channel lookup retained"); word(expected.data(), gp - 0x742c, oldHandle); }
// The VIF1 handle is written as the constant sceDmaGetChan returned, without the lookup.
if (kind == 2) { check(channels == 0, "adapted handle without a channel lookup"); word(expected.data(), gp - 0x742c, oldHandle); }
if (kind == 3) check(native.r[2].ud[0] == 0, "getter returns null with inaccessible GP");
check(std::memcmp(ram, expected.data(), stack - 0x1000) == 0 &&
std::memcmp(ram + stack, expected.data() + stack, expected.size() - stack) == 0,
+85
View File
@@ -0,0 +1,85 @@
// The native controller (runtime/dc_pad.cpp): read_pad fills CGamePad's PAD_STATUS as the original did from scePadRead
// once its handshake ended, and Step's motor levels reach the controller's rumble.
#include "../runtime/dc_pad.h"
#include "bozo/libs/libraries.h"
#include "bozo/port.h"
#include "bozo/runtime.h"
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
namespace {
int failures=0;
void check(bool ok,const char *what){if(!ok){++failures;std::printf("FAIL %s\n",what);}}
constexpr uint32_t pad=0x1cbc540,readPadPc=0x12a900,stepPc=0x12b140,ra=0x12ae00;
struct Controller : bozo::libs::PadInput {
bozo::libs::PadInputState state[2];
uint32_t lastFrame=0;int lastPlayer=-1,rumbles=0;bool small=false;uint8_t large=0;
void read(uint32_t frame,int player,bozo::libs::PadInputState &out) override{lastFrame=frame;lastPlayer=player;out=state[player&1];}
void rumble(int player,bool s,uint8_t l) override{++rumbles;lastPlayer=player;small=s;large=l;}
};
struct Host : bozo::port::Host {
bozo::libs::Libraries &libs;
explicit Host(bozo::libs::Libraries &l):libs(l){}
bozo::libs::Libraries &libraries() override{return libs;}
void frameEnd(Runtime *,R5900Context *) override{throw std::runtime_error("unexpected frame end");}
bool callLibrary(Runtime *,R5900Context *,uint32_t) override{return false;}
};
uint32_t rd32(const uint8_t *r,uint32_t at){uint32_t v;std::memcpy(&v,r+at,4);return v;}
void wr32(uint8_t *r,uint32_t at,uint32_t v){std::memcpy(r+at,&v,4);}
void call(bozo::port::Registry &p,Runtime &rt,uint32_t pc,uint32_t a0,uint32_t a1=0){
R5900Context c;c.pc=pc;c.r[4].uw[0]=a0;c.r[5].uw[0]=a1;c.r[6].uw[0]=0;c.r[31].uw[0]=ra;
p.find(pc)(rt.memory.ram(),&c,&rt);check(c.pc==ra,"the native routine returns to its caller");
}
// What the original pad_button_read made of scePadRead's bytes (the engine writes the buttons active low, low byte first).
uint32_t originalButtons(uint16_t pressed){
const uint16_t released=static_cast<uint16_t>(~pressed);const uint8_t d2=released&0xff,d3=released>>8;
return static_cast<uint32_t>(((d2<<8)|d3)^0xffff);
}
}
int main(){
auto rt=std::make_unique<Runtime>();bozo::libs::Libraries libs;Host host(libs);rt->port=&host;
Controller controller;libs.pad.input=&controller;libs.framesEnded=42;
bozo::port::Registry p;dc::pad::install(p);
check(p.find(readPadPc) && p.find(stepPc),"read_pad and Step are native");
auto *r=rt->memory.ram();
for(int bit=0;bit<16;++bit){
controller.state[0]={};controller.state[0].connected=true;controller.state[0].buttons=static_cast<uint16_t>(1u<<bit);
call(p,*rt,readPadPc,pad+4,0);
check(rd32(r,pad+4)==originalButtons(static_cast<uint16_t>(1u<<bit)),"each button lands where scePadRead put it");
}
controller.state[0]={};controller.state[0].buttons=bozo::libs::kPadCross|bozo::libs::kPadUp;
controller.state[0].rx=1;controller.state[0].ry=2;controller.state[0].lx=3;controller.state[0].ly=4;
call(p,*rt,readPadPc,pad+4,0);
check(rd32(r,pad+4)==0x1040u,"Cross and Up are DC's 0x40 and 0x1000");
check(rd32(r,pad+8)==4 && rd32(r,pad+12)==3 && rd32(r,pad+16)==2 && rd32(r,pad+20)==1,"sticks in ly, lx, ry, rx order");
check(rd32(r,pad+24)==99 && rd32(r,pad+28)==6 && rd32(r,pad+32)==7 && rd32(r,pad+36)==7 && rd32(r,pad+40)==7,
"the handshake reads as ended: ready, stable, DualShock 2");
check(r[pad+4+0x2e]==0 && r[pad+4+0x2f]==1 && r[pad+4+0x30]==0xff && r[pad+4+0x33]==0xff,"motor alignment as the handshake set it");
check(controller.lastFrame==42 && controller.lastPlayer==0,"port 0 reads player 1 at the frames ended");
controller.state[1]={};controller.state[1].buttons=bozo::libs::kPadStart;controller.state[1].lx=0x10;
call(p,*rt,readPadPc,pad+0x50,1);
check(controller.lastPlayer==1 && rd32(r,pad+0x50)==originalButtons(bozo::libs::kPadStart) && rd32(r,pad+0x58)==0x10,
"port 1 reads player 2 into its own status");
check(rd32(r,pad+4)==0x1040u,"port 1 leaves port 0's status alone");
libs.pad.input=nullptr;call(p,*rt,readPadPc,pad+4,0);
check(rd32(r,pad+4)==0 && rd32(r,pad+8)==0x80 && rd32(r,pad+20)==0x80,"no input source: nothing pressed, sticks centred");
libs.pad.input=&controller;
// Step: vibration enabled, port 0's small motor for two more frames, the large one's timer ran out.
wr32(r,pad+0x464,1);r[pad+0x2c]=1;r[pad+0x2d]=200;wr32(r,pad+0x38,2);wr32(r,pad+0x3c,0);
r[pad+0x4c+0x2c]=1;wr32(r,pad+0x4c+0x38,5);
controller.rumbles=0;call(p,*rt,stepPc,pad);
check(rd32(r,pad+0x38)==1 && r[pad+0x2c]==1 && rd32(r,pad+0x3c)==0 && r[pad+0x2d]==0,"motor timers count down and expire");
check(rd32(r,pad+0x4c+0x38)==4 && r[pad+0x4c+0x2c]==1,"port 1's timers count down too");
check(controller.rumbles==1 && controller.lastPlayer==0 && controller.small && controller.large==0,"port 0's levels reach player 1's rumble");
wr32(r,pad+0x464,0);r[pad+0x2d]=90;wr32(r,pad+0x3c,9);call(p,*rt,stepPc,pad);
check(r[pad+0x2c]==0 && r[pad+0x2d]==0 && !controller.small && controller.large==0,"vibration disabled stops both motors");
std::printf("Native pad: %d failures\n",failures);return failures?1:0;
}
+22 -1
View File
@@ -185,8 +185,29 @@ int main(int argc, char **argv)
REFERENCE[0].function(ram, &original, &rt);
check(original.pc == 0x123450 && !original.leaving, "reference returns normally");
check(packetCalls == (kind == 0 ? 4 : kind == 3 ? ((gate >> 1) || !(gate & 1) ? 0 : 1) : 1), "reference conditional packet count");
const auto expectedEvents = events;
auto expectedEvents = events;
std::vector<uint8_t> expected(ram, ram + base.size());
if (kind == 3)
{
// The loading screen's sceGsSetDefDBuff is retired (its records are read only by the callback
// region already skipped): no event, no write into the record, and the marker folds without it.
std::vector<Event> kept;
const auto read = [&](uint32_t at) { uint32_t v; std::memcpy(&v, initial.data() + at, 4); return v; };
uint32_t folded = read(marker);
for (const auto &event : expectedEvents)
{
if (event.pc == 0x112c08)
{
word(expected.data(), event.data[0], read(event.data[0]));
continue;
}
kept.push_back(event);
if (event.pc != 0x1110b0 && event.pc != 0x121830 && event.pc != 0x1218a8 && event.pc != 0x12c700)
folded = folded * 33 + event.pc;
}
word(expected.data(), marker, folded);
expectedEvents = kept;
}
std::memcpy(ram, initial.data(), initial.size());
// Poison both main objects, the loading object and all retired
// output. Main's packet handle is deliberately inaccessible.
+105
View File
@@ -0,0 +1,105 @@
// The native sound transport (runtime/dc_sound.cpp): the library calls of ezMidiInit, ezMidi and ezTransToIOP, patched
// to nop, reach the compiled sound module's RPC server and memory directly with the requests the original calls made,
// charging each call's 8 cycles.
#include "../runtime/dc_sound.h"
#include "bozo/libs/guest.h"
#include "bozo/libs/libraries.h"
#include "bozo/port.h"
#include "bozo/runtime.h"
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <vector>
namespace {
int failures=0;
void check(bool ok,const char *what){if(!ok){++failures;std::printf("FAIL %s\n",what);}}
constexpr uint32_t client=0x1cecec0,sbuff=0x1cece80,record=0x1cecef0;
struct Host : bozo::port::Host {
bozo::libs::Libraries &libs;
explicit Host(bozo::libs::Libraries &l):libs(l){}
bozo::libs::Libraries &libraries() override{return libs;}
void frameEnd(Runtime *,R5900Context *) override{throw std::runtime_error("unexpected frame end");}
bool callLibrary(Runtime *,R5900Context *,uint32_t) override{return false;}
};
uint32_t rd32(const uint8_t *r,uint32_t at){uint32_t v;std::memcpy(&v,r+at,4);return v;}
void wr32(uint8_t *r,uint32_t at,uint32_t v){std::memcpy(r+at,&v,4);}
// One site with argument registers a0..t3 (r4..r11); returns v0.
int32_t site(Runtime &rt,uint32_t pc,std::initializer_list<uint32_t> args,uint64_t *cycles=nullptr){
R5900Context c;int r=4;for(uint32_t a:args)c.r[r++].ud[0]=a;c.r[2].ud[0]=0x5555;
const uint64_t before=c.cycles;
check(dc::sound::nativeSite(rt.memory.ram(),&c,&rt,pc),"the site is native");
if(cycles)*cycles=c.cycles-before;
return static_cast<int32_t>(c.r[2].uw[0]);
}
}
int main(){
auto rt=std::make_unique<Runtime>();bozo::libs::Libraries libs;Host host(libs);rt->port=&host;
auto *r=rt->memory.ram();
check(!dc::sound::nativeSite(r,nullptr,rt.get(),0x147a74),"other instructions are not sound sites");
uint64_t cycles=0;
check(site(*rt,dc::sound::kInitRpcSite,{0},&cycles)==0 && cycles==8,"sceSifInitRpc: 0, the call's 8 cycles");
// Before the module's server exists: the client gets an id but no server, so ezMidiInit's loop retries.
const uint32_t ids=libs.sif.rpcId;
site(*rt,dc::sound::kBindRpcSite,{client,0x12346,0});
check(rd32(r,client+4)==ids+1 && rd32(r,client+8)==0xffffffffu && rd32(r,client+0x24)==0,"no server yet: not bound");
std::vector<bozo::libs::NativeRpcRequest> requests;std::vector<uint32_t> firstWords;
libs.sif.servers[0x12346]=[&](bozo::libs::Libraries &,bozo::libs::Guest &g,const bozo::libs::NativeRpcRequest &q){
requests.push_back(q);firstWords.push_back(g.read32(q.send));
if(q.receiveBytes){uint8_t reply[64]={};reply[0]=0x2a;g.write(q.receive,reply,64);}
};
site(*rt,dc::sound::kBindRpcSite,{client,0x12346,0});
check(rd32(r,client+4)==ids+2 && rd32(r,client+0x24)==(0x12346u|0x80000000u),"with the server, the client is bound");
// ezMidi's two calls: (client, fno, mode, send, ssize, receive, rsize, end).
wr32(r,sbuff,0x1234);
check(site(*rt,dc::sound::kCallRpcSite2,{client,5,0,sbuff,16,sbuff,0,0},&cycles)==0 && cycles==8,"sceSifCallRpc: 0, 8 cycles");
check(requests.size()==1 && requests[0].command==5 && requests[0].send==sbuff && requests[0].sendBytes==16 &&
requests[0].receive==sbuff && requests[0].receiveBytes==0 && firstWords[0]==0x1234,"a plain command reaches the server as sent");
check(rd32(r,client+0x0c)==0 && rd32(r,client+0x10)==5,"the client keeps the mode and the function");
site(*rt,dc::sound::kCallRpcSite2,{client,0x8007,0,sbuff,16,sbuff,64,0});
check(requests.size()==2 && requests[1].receiveBytes==64 && rd32(r,sbuff)==0x2a,"a 0x8000 command's reply lands in sbuff");
wr32(r,0x500000,0xcafe);
site(*rt,dc::sound::kCallRpcSite,{client,0x1003,0,0x500000,64,sbuff,0,0});
check(requests.size()==3 && requests[2].send==0x500000 && requests[2].sendBytes==64 && firstWords[2]==0xcafe,
"a 0x1000 command sends the 64 bytes at its argument");
site(*rt,dc::sound::kCallRpcSite,{0x1cec000,9,0,sbuff,16,sbuff,0,0});
check(requests.size()==3,"an unbound client reaches no server");
// ezTransToIOP: FlushCache, then sceSifSetDma(record, 1) and sceSifDmaStat(id).
check(site(*rt,dc::sound::kFlushSite,{0},&cycles)==0x5555 && cycles==8,"FlushCache: nothing, 8 cycles");
uint32_t gotDest=0,gotBytes=0;std::vector<uint8_t> got;
libs.sif.transfer=[&](uint32_t d,const uint8_t *b,uint32_t n){gotDest=d;gotBytes=n;got.assign(b,b+n);};
for(uint32_t i=0;i<32;++i)r[0x600000+i]=static_cast<uint8_t>(i*3);
wr32(r,record,0x600000);wr32(r,record+4,0x9000);wr32(r,record+8,32);wr32(r,record+12,0);
const int32_t id=site(*rt,dc::sound::kSetDmaSite,{record,1});
check(id>0 && gotDest==0x9000 && gotBytes==32 && got.size()==32 && got[5]==15,"the record's bytes reach the module's memory at once");
check(!(libs.io.stat & (1u<<5)),"no DMAC channel 5 interrupt is raised");
check(site(*rt,dc::sound::kDmaStatSite,{static_cast<uint32_t>(id)})==-1,"sceSifDmaStat: finished");
// libsdr: each site first does its delay slot's instruction.
R5900Context c;c.r[17].ud[0]=0x1234;
check(dc::sound::nativeSite(r,&c,rt.get(),dc::sound::kSdInitRpcSite) && c.r[17].ud[0]==0x2a0000u && c.r[2].ud[0]==0,
"sceSdRemoteInit: lui s1, then sceSifInitRpc");
const uint32_t sdClient=0x250aa0;libs.sif.servers[0x80000701u]=libs.sif.servers[0x12346];
c=R5900Context{};c.r[4].ud[0]=sdClient;c.r[5].ud[0]=0x80000701u;c.r[6].ud[0]=7;
check(dc::sound::nativeSite(r,&c,rt.get(),dc::sound::kSdBindRpcSite) && c.r[6].ud[0]==0 &&
rd32(r,sdClient+0x24)==(0x80000701u|0x80000000u),"sceSdRemoteInit: daddu a2, then the binding");
const size_t before=requests.size();
c=R5900Context{};c.r[4].ud[0]=sdClient;c.r[5].ud[0]=0x8000;c.r[7].ud[0]=0x500000;c.r[8].ud[0]=64;c.r[9].ud[0]=sbuff;c.r[10].ud[0]=3;
check(dc::sound::nativeSite(r,&c,rt.get(),dc::sound::kSdCallRpcSite) && c.r[10].ud[0]==64 && requests.size()==before+1 &&
requests.back().receiveBytes==64 && requests.back().sendBytes==64,"sceSdRemote: addiu t2,64 before the RPC reads it");
wr32(r,0x2a9f80,0x600000);wr32(r,0x2a9f84,0xa000);wr32(r,0x2a9f88,16);wr32(r,0x2a9f8c,0xdead);
c=R5900Context{};c.r[2].ud[0]=0x2a9f80;c.r[4].ud[0]=0x2a9f80;c.r[5].ud[0]=1;
check(dc::sound::nativeSite(r,&c,rt.get(),dc::sound::kSdSetDmaSite) && rd32(r,0x2a9f8c)==0 && gotDest==0xa000 && gotBytes==16 &&
c.r[2].ud[0]==1,"sceSdTransToIOP: the record's last word cleared through v0, then the transfer");
c=R5900Context{};c.r[17].ud[0]=1;c.r[4].ud[0]=99;
check(dc::sound::nativeSite(r,&c,rt.get(),dc::sound::kSdDmaStatSite) && c.r[4].ud[0]==1 && static_cast<int64_t>(c.r[2].ud[0])==-1,
"sceSdTransToIOP: daddu a0,s1, then finished");
std::printf("Native sound transport: %d failures\n",failures);return failures?1:0;
}
+2 -2
View File
@@ -92,8 +92,8 @@ selected = [line for line in patches.read_text().splitlines()
if line.split('#')[0].strip() and span_start <= int(line.split()[0], 16) < end]
expected = {'frame_close': 2, 'frame_draw': 0, 'frame_member': 0, 'mdt_draw': 2,
'message': 3, 'edit_state': 2, 'menu_state': 2, 'loading': 13, 'fire': 6, 'language': 2, 'fishing': 9,
'debug_font': 14, 'packet_init': 2, 'begin_frame': 5, 'resident_chain': 2, 'loading_init': 2,
'packet_reserve': 2, 'buffer_clear': 4, 'packet_handle': 1, 'packet_get': 1, 'frame_submit': 12}.get(kind, 4)
'debug_font': 14, 'packet_init': 2, 'begin_frame': 5, 'resident_chain': 2, 'loading_init': 3,
'packet_reserve': 2, 'buffer_clear': 4, 'packet_handle': 3, 'packet_get': 1, 'frame_submit': 12}.get(kind, 4)
handle_sites = {int(line.split()[0], 16) for line in selected
if int(line.split()[0], 16) != 0x12e280
and int(line.split()[1], 16) & 0xffe0ffff == 0x8f808bd4
+12 -5
View File
@@ -6,9 +6,16 @@ get_filename_component(DC_ROOT "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE)
set(BOZO_BUILD_TOOLS OFF CACHE BOOL "" FORCE)
set(BOZO_APP OFF CACHE BOOL "" FORCE)
include(CTest)
add_subdirectory("${DC_ROOT}/BozoEngine" engine)
# BozoEngine: the pinned release (cmake/bozo_engine.json, fetched into BozoEngine/), or BOZO_ENGINE_DIR (a checkout).
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the pinned release, in BozoEngine/)")
if(NOT BOZO_ENGINE_DIR)
include("${DC_ROOT}/cmake/bozo_engine_fetch.cmake")
set(BOZO_ENGINE_DIR "${bozo_engine_tree}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${DC_ROOT}/cmake/bozo_engine.json")
endif()
add_subdirectory("${BOZO_ENGINE_DIR}" engine)
if(BUILD_TESTING)
add_subdirectory("${DC_ROOT}/BozoEngine/tests" engine_tests)
add_subdirectory("${BOZO_ENGINE_DIR}/tests" engine_tests)
add_executable(dc-model-lifetime-tests "${DC_ROOT}/tests/dc_model_lifetime_tests.cpp" "${DC_ROOT}/runtime/dc_native.cpp")
target_link_libraries(dc-model-lifetime-tests PRIVATE bozo_host)
target_compile_definitions(dc-model-lifetime-tests PRIVATE DC_DEFAULT_TEXTURES="")
@@ -17,7 +24,7 @@ if(BUILD_TESTING)
endif()
add_test(NAME dc_native_model_lifetime COMMAND dc-model-lifetime-tests)
add_executable(dc-fishing-line-tests "${DC_ROOT}/tests/dc_fishing_line_tests.cpp"
"${DC_ROOT}/runtime/dc_native.cpp" "${DC_ROOT}/runtime/dc_port.cpp")
"${DC_ROOT}/runtime/dc_native.cpp" "${DC_ROOT}/runtime/dc_port.cpp" "${DC_ROOT}/runtime/dc_sound.cpp")
target_link_libraries(dc-fishing-line-tests PRIVATE bozo_host)
target_compile_definitions(dc-fishing-line-tests PRIVATE DC_DEFAULT_TEXTURES="")
if(MINGW)
@@ -25,7 +32,7 @@ if(BUILD_TESTING)
endif()
add_test(NAME dc_native_fishing_line COMMAND dc-fishing-line-tests)
add_executable(dc-debug-font-tests "${DC_ROOT}/tests/dc_debug_font_tests.cpp"
"${DC_ROOT}/runtime/dc_native.cpp" "${DC_ROOT}/runtime/dc_port.cpp")
"${DC_ROOT}/runtime/dc_native.cpp" "${DC_ROOT}/runtime/dc_port.cpp" "${DC_ROOT}/runtime/dc_sound.cpp")
target_link_libraries(dc-debug-font-tests PRIVATE bozo_host)
target_compile_definitions(dc-debug-font-tests PRIVATE DC_DEFAULT_TEXTURES="")
if(MINGW)
@@ -34,7 +41,7 @@ if(BUILD_TESTING)
add_test(NAME dc_native_debug_font COMMAND dc-debug-font-tests)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
add_executable(dc-packet-audit-tests "${DC_ROOT}/tests/dc_packet_audit_tests.cpp"
"${DC_ROOT}/runtime/dc_native.cpp" "${DC_ROOT}/runtime/dc_port.cpp")
"${DC_ROOT}/runtime/dc_native.cpp" "${DC_ROOT}/runtime/dc_port.cpp" "${DC_ROOT}/runtime/dc_sound.cpp")
target_link_libraries(dc-packet-audit-tests PRIVATE bozo_host)
target_compile_definitions(dc-packet-audit-tests PRIVATE DC_DEFAULT_TEXTURES="")
if(MINGW)
+289 -7
View File
@@ -1,5 +1,9 @@
"""Player-facing migration and timing regression checks; no game data required."""
import configparser
import contextlib
import hashlib
import json
import os
import re
import sys
import tempfile
import io
@@ -11,6 +15,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import apply_update
import make_release
import make_build_kit
import dc_build
@@ -18,7 +23,7 @@ from unittest.mock import patch
from types import SimpleNamespace
REQUIRED = (
'DC Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/TMB_Recomp/LICENSE',
'DC Launcher.exe', 'README.txt', 'CHANGELOG.md', 'recomplauncher.json', 'LICENSES/TMB_Recomp/LICENSE',
'LICENSES/BozoEngine/LICENSE', 'LICENSES/DC_Recomp/LICENSE', 'source/VERSION', 'source/release.ini', 'kit/kit_manifest.json',
'kit/python/python.exe', 'source/tools/dc_build.py', 'source/BozoEngine/CMakeLists.txt',
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp',
@@ -129,11 +134,115 @@ class ReleaseTests(unittest.TestCase):
self.assertTrue((root / 'tools/linked').exists())
def test_only_native_engine_is_a_submodule(self):
config = configparser.ConfigParser()
config.read(ROOT / '.gitmodules')
self.assertEqual(config.sections(), ['submodule "BozoEngine"'])
self.assertEqual(config[config.sections()[0]]['path'], 'BozoEngine')
@staticmethod
def release_source(folder, files):
"""A release's source folder: the files, dated as an unzip of the release zip dates them, and its listing."""
root = Path(folder) / 'source'
for name, data in files.items():
(root / name).parent.mkdir(parents=True, exist_ok=True)
(root / name).write_bytes(data)
(root / 'release_files.txt').write_text(''.join(n + '\n' for n in sorted(files)) + 'release_files.txt\n',
encoding='utf-8')
return root
@staticmethod
def date(root, ns):
for p in root.rglob('*'):
if p.is_file():
os.utime(p, ns=(ns, ns))
def settle(self, root, out, now, kit=None):
with patch.object(dc_build, 'ROOT', str(root)), contextlib.redirect_stdout(io.StringIO()):
dc_build.settle_source_times(str(out), kit, now_ns=now)
def test_source_dated_in_the_future_is_dated_now(self):
# Issue 60: the zip's commit time, read as local time west of UTC, is hours ahead; ninja then never settles.
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'CMakeLists.txt': b'project', 'runtime/a.cpp': b'a'})
kit = Path(folder) / 'kit'
(kit / 'deps/sdl3-src').mkdir(parents=True)
(kit / 'deps/sdl3-src/CMakeLists.txt').write_bytes(b'sdl')
module = kit / 'ucrt64/share/cmake/Modules/FindPython.cmake' # build.ninja's input too
module.parent.mkdir(parents=True)
module.write_bytes(b'module')
self.date(root, now + 3 * 3600 * 10**9)
self.date(kit, now + 3 * 3600 * 10**9)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, now, str(kit))
for p in (root / 'CMakeLists.txt', root / 'runtime/a.cpp', kit / 'deps/sdl3-src/CMakeLists.txt', module):
self.assertEqual(p.stat().st_mtime_ns, now)
record = json.loads((out / dc_build.SOURCE_TIMES).read_text(encoding='utf-8'))
self.assertIn('source/runtime/a.cpp', record)
self.assertIn('deps/sdl3-src/CMakeLists.txt', record)
def test_first_build_keeps_past_times(self):
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/a.cpp': b'a'})
self.date(root, now - 10**12)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, now)
self.assertEqual((root / 'runtime/a.cpp').stat().st_mtime_ns, now - 10**12)
def test_update_dates_changed_files_now_and_restores_unchanged_ones(self):
# An update unzipped over a game built after the update's commit: its files are older than the build's.
built, commit, now = 1_800_000_000 * 10**9, 1_799_990_000 * 10**9, 1_800_100_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/same.cpp': b'same', 'runtime/fixed.cpp': b'old'})
self.date(root, built - 10**12)
out = Path(folder) / 'build'
out.mkdir()
self.settle(root, out, built)
(root / 'runtime/fixed.cpp').write_bytes(b'new')
(root / 'runtime/added.cpp').write_bytes(b'added')
with open(root / 'release_files.txt', 'a', encoding='utf-8') as f:
f.write('runtime/added.cpp\n')
self.date(root, commit)
self.settle(root, out, now)
self.assertEqual((root / 'runtime/same.cpp').stat().st_mtime_ns, built - 10**12)
self.assertEqual((root / 'runtime/fixed.cpp').stat().st_mtime_ns, now)
self.assertEqual((root / 'runtime/added.cpp').stat().st_mtime_ns, now)
def test_update_without_a_record_over_a_build_rebuilds_everything(self):
# 0.5.1 and earlier wrote no record: an update over their build cannot tell what changed.
commit, now = 1_799_990_000 * 10**9, 1_800_100_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = self.release_source(folder, {'runtime/a.cpp': b'a'})
self.date(root, commit)
out = Path(folder) / 'build'
(out / 'build').mkdir(parents=True)
(out / 'build/build.ninja').write_bytes(b'')
self.settle(root, out, now)
self.assertEqual((root / 'runtime/a.cpp').stat().st_mtime_ns, now)
def test_checkout_is_left_alone(self):
now = 1_800_000_000 * 10**9
with tempfile.TemporaryDirectory() as folder:
root = Path(folder) / 'source'
root.mkdir()
(root / 'CMakeLists.txt').write_bytes(b'project')
os.utime(root / 'CMakeLists.txt', ns=(now + 10**12, now + 10**12))
self.settle(root, Path(folder), now)
self.assertEqual((root / 'CMakeLists.txt').stat().st_mtime_ns, now + 10**12)
self.assertFalse((Path(folder) / dc_build.SOURCE_TIMES).exists())
def test_engine_is_a_pinned_release(self):
# BozoEngine comes from its releases (cmake/bozo_engine.json, fetched by cmake/bozo_engine_fetch.cmake), no
# longer from a submodule.
self.assertFalse((ROOT / '.gitmodules').exists())
pin = json.loads((ROOT / 'cmake/bozo_engine.json').read_text(encoding='utf-8'))
self.assertRegex(pin['version'], r'^[0-9]+\.[0-9]+\.[0-9]+$')
self.assertRegex(pin['sha256'], r'^[0-9a-f]{64}$')
fetch = (ROOT / 'cmake/bozo_engine_fetch.cmake').read_text(encoding='utf-8')
self.assertIn('EXPECTED_HASH SHA256=${bozo_engine_sha256}', fetch)
self.assertIn('TLS_VERIFY ON', fetch)
self.assertIn('/BozoEngine/', (ROOT / '.gitignore').read_text(encoding='utf-8').splitlines())
for cmake in ('CMakeLists.txt', 'launcher/CMakeLists.txt', 'tests/native_lifetime/CMakeLists.txt'):
self.assertIn('bozo_engine_fetch.cmake', (ROOT / cmake).read_text(encoding='utf-8'), cmake)
def test_release_rejects_game_executables(self):
@@ -231,4 +340,177 @@ class CleanEnvironmentTests(unittest.TestCase):
self.assertNotIn('MSYSTEM',env)
self.assertNotIn('msys64',env['PATH'])
class ApplyUpdateTests(unittest.TestCase):
"""tools/apply_update.py, which the launcher's Update button runs from the installed source (launcher/src/main.cpp)."""
def release_zip(self, folder, version, extra=()):
path = Path(folder) / ('DC_Recomp-%s-bozo.zip' % version)
with zipfile.ZipFile(path, 'w') as archive:
archive.writestr('DC_Recomp_Bozo/DC Launcher.exe', b'launcher ' + version.encode())
archive.writestr('DC_Recomp_Bozo/source/release.ini', 'version = %s\ncommit = abc\n' % version)
archive.writestr('DC_Recomp_Bozo/source/runtime/a.cpp', b'new code')
for name, data in extra:
archive.writestr(name, data)
sha = Path(str(path) + '.sha256')
sha.write_text('%s *%s\n' % (hashlib.sha256(path.read_bytes()).hexdigest(), path.name), encoding='utf-8')
return path, sha
def apply(self, zip_path, sha, version, install):
out = io.StringIO()
with contextlib.redirect_stdout(out):
apply_update.main(['--zip', str(zip_path), '--sha256', str(sha), '--version', version, '--install', str(install)])
return out.getvalue().splitlines()
def test_the_launcher_runs_it_from_the_installed_source(self):
main_cpp = (ROOT / 'launcher/src/main.cpp').read_text(encoding='utf-8')
self.assertIn('L"tools" / L"apply_update.py"', main_cpp)
self.assertTrue((ROOT / 'tools/apply_update.py').is_file())
self.assertIn('"%s"' % apply_update.ASIDE, main_cpp)
self.assertEqual(apply_update.TOP, make_release.TOP + '/')
def test_update_installs_over_the_release_and_keeps_player_folders(self):
with tempfile.TemporaryDirectory() as folder:
install = Path(folder) / 'install'
for name, data in (('DC Launcher.exe', b'old'), ('source/runtime/a.cpp', b'old code'),
('build/dc_build_state.json', b'{}'), ('game/dc.exe', b'game')):
(install / name).parent.mkdir(parents=True, exist_ok=True)
(install / name).write_bytes(data)
(install / 'update').mkdir()
zip_path, sha = self.release_zip(install / 'update', '9.9.9')
lines = self.apply(zip_path, sha, '9.9.9', install)
self.assertEqual(lines[-1], 'done 9.9.9')
self.assertEqual((install / 'DC Launcher.exe').read_bytes(), b'launcher 9.9.9')
self.assertEqual((install / 'source/runtime/a.cpp').read_bytes(), b'new code')
self.assertEqual((install / 'game/dc.exe').read_bytes(), b'game')
self.assertEqual((install / 'build/dc_build_state.json').read_bytes(), b'{}')
self.assertFalse(zip_path.exists())
self.assertFalse((install / 'update/staging').exists())
def test_damaged_wrong_or_unsafe_zips_install_nothing(self):
with tempfile.TemporaryDirectory() as folder:
install = Path(folder) / 'install'
install.mkdir()
zip_path, sha = self.release_zip(folder, '9.9.9')
with self.assertRaisesRegex(apply_update.UpdateError, 'not \'9.9.8\''):
self.apply(zip_path, sha, '9.9.8', install)
sha.write_text('0' * 64 + '\n', encoding='utf-8')
with self.assertRaisesRegex(apply_update.UpdateError, 'damaged'):
self.apply(zip_path, sha, '9.9.9', install)
for bad in ('DC_Recomp_Bozo/game/dc.exe', 'DC_Recomp_Bozo/../escape.txt', 'Other/file.txt'):
with tempfile.TemporaryDirectory() as sub:
zip_path, sha = self.release_zip(sub, '9.9.9', [(bad, b'x')])
with self.assertRaises(apply_update.UpdateError):
self.apply(zip_path, sha, '9.9.9', install)
self.assertEqual(sorted(p.name for p in install.rglob('*') if p.is_file()), [])
class RecompLauncherTests(unittest.TestCase):
"""recomplauncher.json (RecompLauncher's manifest, recomplauncher.com/sdk) and what it runs."""
def manifest(self):
return json.loads((ROOT / 'recomplauncher.json').read_text(encoding='utf-8'))
def test_progress_lines_follow_the_steps(self):
self.assertEqual(dc_build.progress_line(('PROGRESS', 'verify', '1/8', 'Checking the disc')),
'progress 0.000 Checking the disc')
before = sum(dc_build.STEP_WEIGHTS[s] for s in dc_build.STEPS[:dc_build.STEPS.index('packs')])
half = (before + dc_build.STEP_WEIGHTS['packs'] / 2) / sum(dc_build.STEP_WEIGHTS.values())
self.assertEqual(dc_build.progress_line(('PERCENT', 'packs', 50)),
'progress %.3f Converting textures (50%%)' % half)
for other in (('SKIP', 'verify', '1/8'), ('DONE', 'stage', '8/8', 1.0), ('INFO', 'total', '1 s'),
('ERROR', 'compile', 'x')):
self.assertIsNone(dc_build.progress_line(other))
self.assertEqual(set(dc_build.STEP_WEIGHTS), set(dc_build.STEPS))
shares = []
for step in dc_build.STEPS:
for parts in (('PROGRESS', step, '', ''), ('PERCENT', step, 37), ('PERCENT', step, 100)):
shares.append(float(dc_build.progress_line(parts).split()[1]))
self.assertEqual(shares, sorted(shares))
self.assertTrue(0 <= shares[0] and shares[-1] < 1)
def test_a_missing_disc_says_why_and_an_earlier_build_keeps_one(self):
with tempfile.TemporaryDirectory() as folder:
def run(*extra):
return subprocess.run([sys.executable, '-I', '-X', 'utf8', str(ROOT / 'tools' / 'dc_build.py'),
'--out', str(Path(folder) / 'build'), '--game', str(Path(folder) / 'game')]
+ list(extra), capture_output=True, text=True, encoding='utf-8')
r = run('--progress-lines')
self.assertEqual(r.returncode, 1)
self.assertIn('ERROR verify no disc image given', r.stdout.strip().splitlines()[-1])
# No --disc: the disc image an earlier build kept in the game folder (keeps_copy). Here it is not a disc.
(Path(folder) / 'game').mkdir()
(Path(folder) / 'game' / 'disc.iso').write_bytes(b'\0' * 65536)
r = run('--check')
self.assertEqual(r.returncode, 1)
self.assertIn('ERROR verify disc.iso', r.stdout)
def test_manifest_runs_what_the_release_ships(self):
m = self.manifest()
self.assertEqual(m['format'], 1)
disc = m['inputs'][0]
self.assertEqual(disc['id'], 'game')
self.assertEqual(disc['check']['iso9660'], dc_build.ELF_NAME)
self.assertEqual(disc['check']['ids'], ['SCUS-97111'])
# Redump's Dark Cloud (USA), SCUS-97111 v1.02: its one dump, a DVD-5 (redump.org/disc/5435).
self.assertEqual(disc['dumps'], [{'name': 'USA', 'size': 1797980160, 'crc32': 'fe4adb70'}])
prepare, start = m['prepare'], m['start']
self.assertEqual(prepare['program'], ['kit/python/python.exe'])
self.assertIn('kit/python/python.exe', REQUIRED)
self.assertIn('{install}/source/tools/dc_build.py', prepare['args'])
self.assertIn('source/tools/dc_build.py', REQUIRED)
# The disc as one argument: RecompLauncher leaves it out when the player's copy is gone (keeps_copy).
self.assertTrue(prepare['keeps_copy'])
self.assertEqual([a for a in prepare['args'] if '{input:game}' in a], ['--disc={input:game}'])
help_text = subprocess.run([sys.executable, '-I', str(ROOT / 'tools' / 'dc_build.py'), '--help'],
capture_output=True, text=True, check=True).stdout
for flag in (a.split('=', 1)[0] for a in prepare['args'] if a.startswith('--')):
self.assertIn(flag, help_text)
self.assertIn('--progress-lines', prepare['args'])
self.assertEqual(prepare['done'], ['{install}/game/built_from.ini'])
self.assertEqual(start['program'], ['game/' + dc_build.GAME_EXE + '.exe'])
self.assertEqual(start['args'], ['--elf', '{install}/game/' + dc_build.ELF_NAME, '--iso', '{install}/game/disc.iso'])
# Everything the game writes (cards, settings, logs, save states) in RecompLauncher's {data}.
self.assertEqual(start['env'], {'PS2X_USER_DIR': '{data}'})
self.assertEqual(m['saves'], ['{data}/mc0', '{data}/mc1'])
def test_settings_are_keys_the_game_reads(self):
m = self.manifest()
self.assertEqual(m['config'], [{'format': 'ini', 'file': [{'path': '{data}/video.ini'}]},
{'id': 'game', 'format': 'ini', 'file': [{'path': '{data}/game.ini'}]}])
source = (ROOT / 'BozoEngine' / 'runtime' / 'app' / 'video_settings.cpp').read_text(encoding='utf-8')
written = set(re.findall(r'<< "([a-z_]+) = "', source))
self.assertIn('widescreen', written)
# game.ini (the game's language): the keys runtime/dc_language.cpp reads, the values it accepts.
language = (ROOT / 'runtime' / 'dc_language.cpp').read_text(encoding='utf-8')
self.assertIn('"language"', language)
accepted = set(re.findall(r'\{"([a-z]{2})", "', language))
self.assertEqual(accepted, {'en', 'fr', 'de', 'it'})
ids = [s['id'] for s in m['settings']]
self.assertEqual(len(ids), len(set(ids)))
for setting in m['settings']:
keys = set(setting['defaults'])
for choice in setting['choices']:
self.assertEqual(set(choice['set']), keys, setting['id'])
for key in keys:
section, name = key.split('/')
if setting.get('in') == 'game':
self.assertEqual(key, 'game/language')
self.assertTrue({c['set'][key] for c in setting['choices']} <= accepted)
continue
self.assertNotIn('in', setting)
self.assertEqual(section, 'video')
self.assertIn(name, written)
values = [c['set'][k] for c in setting['choices'] for k in keys]
self.assertEqual(len(values), len(set(values)), setting['id'])
self.assertIn(setting['defaults'], [c['set'] for c in setting['choices']], setting['id'])
def test_release_zip_carries_the_manifest_at_its_top(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'no_manifest.zip'
with zipfile.ZipFile(path, 'w') as archive:
for name in REQUIRED:
if name != 'recomplauncher.json':
archive.writestr('DC_Recomp_Bozo/' + name, b'fixture')
self.assertIn('DC_Recomp_Bozo/recomplauncher.json is missing', make_release.verify_zip(path))
if __name__ == '__main__': unittest.main()
+183
View File
@@ -0,0 +1,183 @@
#!/usr/bin/env python3
# Adapted from The Bozos TMB_Recomp (MIT); see launcher/LICENSE for original attribution.
"""apply_update: installs a downloaded release over this one, for the launcher's Update button.
python -I tools/apply_update.py --zip <DC_Recomp-x.y.z-bozo.zip> --sha256 <its .sha256 file> --version x.y.z
--install <the release folder> [--keep-zip]
Checks the zip's SHA-256 against the release's .sha256, checks every name in it (one top folder DC_Recomp_Bozo/, no
absolute or parent paths, nothing under build/, game/ or update/, the launcher and source/release.ini of the version
asked for), extracts it whole to <install>/update/staging, and only then moves its files over the release folder.
A file in use (the launcher that started this, the kit's Python running it) is renamed to <name>.dc-old first, as
Windows lets a running program's file be renamed but not replaced; those are listed in update/old_files.txt for the
launcher to delete at its next start. The player's own folders (build/, game/) and saves (%APPDATA%) are never
touched; dc_build removes the source files a release no longer has (source/release_files.txt). The files are written
now, so they are newer than the player's last build.
Prints one line per event for the launcher: "step <verify|extract|install|clean>", "progress <done> <total>" (bytes),
"done <version>", or "error <message>" (exit code 1).
"""
import argparse
import hashlib
import os
import shutil
import sys
import zipfile
TOP = 'DC_Recomp_Bozo/' # tools/make_release.py's TOP
LAUNCHER = 'DC Launcher.exe'
PROTECTED = ('build/', 'game/', 'update/') # the player's build and game, and this update's own folder
ASIDE = '.dc-old' # the launcher deletes only these (launcher/src/main.cpp, cleanUpdateLeftovers)
class UpdateError(Exception):
pass
def say(*parts):
print(*parts, flush=True)
def sha256_of(path):
h = hashlib.sha256()
total = os.path.getsize(path)
done = 0
with open(path, 'rb') as f:
for block in iter(lambda: f.read(1 << 20), b''):
h.update(block)
done += len(block)
if done % (16 << 20) < (1 << 20):
say('progress', done, total)
return h.hexdigest()
def expected_sha256(path):
with open(path, 'r', encoding='utf-8', errors='replace') as f:
token = f.read().split()
if not token or len(token[0]) != 64 or any(c not in '0123456789abcdefABCDEF' for c in token[0]):
raise UpdateError('the .sha256 file does not hold a SHA-256')
return token[0].lower()
def checked_names(zf, version):
"""The zip's file entries as (entry, path under the top folder), after checking every name."""
files = []
for info in zf.infolist():
name = info.filename
if not name.startswith(TOP) or '\\' in name or ':' in name or name.startswith('/'):
raise UpdateError('unexpected name in the zip: %r' % name)
rel = name[len(TOP):]
if any(part in ('..', '.') for part in rel.split('/')):
raise UpdateError('unexpected name in the zip: %r' % name)
if rel.startswith(PROTECTED) or rel.rstrip('/') in ('build', 'game', 'update'):
raise UpdateError('the zip holds %r, a folder of the player\'s own' % name)
if not name.endswith('/'):
files.append((info, rel))
rels = {rel for _info, rel in files}
if LAUNCHER not in rels or 'source/release.ini' not in rels:
raise UpdateError('this is not a DC_Recomp release (no launcher or source/release.ini)')
stamp = zf.read(TOP + 'source/release.ini').decode('utf-8', 'replace')
found = ''
for line in stamp.splitlines():
key, _, value = line.partition('=')
if key.strip() == 'version':
found = value.strip()
if found != version:
raise UpdateError('the zip is version %r, not %r' % (found, version))
return files
def remove_tree(path):
def onerror(func, p, _exc):
os.chmod(p, 0o666)
func(p)
if os.path.isdir(path):
shutil.rmtree(path, onerror=onerror)
def replace(src, dst, old_files):
"""Moves src over dst; a dst in use is renamed aside first (<dst>.dc-old, or .dc-old2... if that one is too)."""
os.makedirs(os.path.dirname(dst), exist_ok=True)
try:
os.replace(src, dst)
return
except PermissionError:
pass
for n in range(1, 100):
aside = dst + (ASIDE if n == 1 else '%s%d' % (ASIDE, n))
try:
if os.path.exists(aside):
os.remove(aside)
os.rename(dst, aside)
break
except OSError:
continue
else:
raise UpdateError('%s is in use and could not be set aside' % dst)
old_files.append(aside)
os.replace(src, dst)
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument('--zip', required=True)
ap.add_argument('--sha256', required=True)
ap.add_argument('--version', required=True)
ap.add_argument('--install', required=True)
ap.add_argument('--keep-zip', action='store_true')
args = ap.parse_args(argv)
install = os.path.abspath(args.install)
work = os.path.join(install, 'update')
staging = os.path.join(work, 'staging')
say('step verify')
want = expected_sha256(args.sha256)
got = sha256_of(args.zip)
if got != want:
raise UpdateError('the download is damaged (SHA-256 %s, expected %s): try again' % (got, want))
say('step extract')
remove_tree(staging)
with zipfile.ZipFile(args.zip) as zf:
files = checked_names(zf, args.version)
total = sum(info.file_size for info, _rel in files)
if shutil.disk_usage(install).free < total + (256 << 20):
raise UpdateError('not enough free space: %d MB needed' % ((total >> 20) + 256))
done = 0
for info, rel in files:
target = os.path.join(staging, *rel.split('/'))
os.makedirs(os.path.dirname(target), exist_ok=True)
with zf.open(info) as src, open(target, 'wb') as dst:
shutil.copyfileobj(src, dst, 1 << 20)
done += info.file_size
say('progress', done, total)
# Everything is extracted and checked: only moves on the same disk from here.
say('step install')
old_files = []
for n, (_info, rel) in enumerate(files):
replace(os.path.join(staging, *rel.split('/')), os.path.join(install, *rel.split('/')), old_files)
if n % 200 == 0:
say('progress', n, len(files))
say('progress', len(files), len(files))
if old_files:
with open(os.path.join(work, 'old_files.txt'), 'a', encoding='utf-8') as f:
f.write(''.join(path + '\n' for path in old_files))
say('step clean')
remove_tree(staging)
if not args.keep_zip:
for path in (args.zip, args.sha256):
try:
os.remove(path)
except OSError:
pass
say('done', args.version)
if __name__ == '__main__':
try:
main()
except (UpdateError, OSError, zipfile.BadZipFile) as e:
say('error', e)
sys.exit(1)
+4 -1
View File
@@ -5,7 +5,10 @@ if sys.argv[1]=='--overrides':
addresses=set()
for path in (root/'runtime').glob('dc_*.cpp'):
addresses.update(int(x,16) for x in re.findall(r'0x([0-9a-fA-F]+)',path.read_text()))
native_sites=(0x12C19C,0x15434C,0x12D268,0x1AB290,0x13DFA8,0x13DFF0,0x13E314,0x13E420,0x1DF2A0,0x1DC3F4) # guarded port boundaries
native_sites=(0x12C19C,0x15434C,0x12D268,0x1AB290,0x13DFA8,0x13DFF0,0x13E314,0x13E420,0x1DF2A0,0x1DC3F4,
0x14797C,0x147998,0x147A70,0x147AB4,0x147B10,0x147B24,0x147B48,
0x121264,0x121278,0x121334,0x12134C,0x121530,0x121564,
0x12C510,0x12C57C,0x129AB4,0x129AE4) # guarded port boundaries
out.write_text(''.join(f'override 0x{x:x}\n' for x in sorted(addresses) if 0x100000 <= x < 0x245300 and x not in native_sites)
+ ''.join(f'native 0x{x:x}\n' for x in native_sites))
sys.exit(0)
+141 -7
View File
@@ -11,7 +11,8 @@ No game data or generated game code is distributed. ISO and BIN/CUE use the engi
kit/python/python.exe -I -X utf8 source/tools/dc_build.py --disc IMAGE --out build --game game
The bundled kit builds offline without MSYS2, git or an installed Python. --check validates a disc
without building. PROGRESS/PERCENT/SKIP/DONE/ERROR/RESULT lines use the same launcher protocol as TMB.
without building. PROGRESS/PERCENT/SKIP/DONE/ERROR/RESULT lines use the same launcher protocol as TMB;
--progress-lines adds RecompLauncher's "progress <0 to 1> <text>" (recomplauncher.json at the repo's top).
"""
import argparse
import glob
@@ -42,7 +43,7 @@ def configure_gcc_paths(env, compiler_bin):
env['GCC_EXEC_PREFIX'] = gcc.replace('\\', '/') + '/'
libraries = versions + [os.path.join(prefix, 'x86_64-w64-mingw32', 'lib'), os.path.join(prefix, 'lib')]
env['LIBRARY_PATH'] = os.pathsep.join(p.replace('\\', '/') for p in libraries if os.path.isdir(p))
ENGINE = os.path.join(ROOT, 'BozoEngine') # --engine replaces it
ENGINE = os.path.join(ROOT, 'BozoEngine') # the release cmake/bozo_engine.json pins; --engine replaces it
ps2_disc = None # BozoEngine's tools/native_pack/ps2_disc.py, imported by load_engine()
ELF_NAME = 'SCUS_971.11'
@@ -65,19 +66,47 @@ class BuildError(Exception):
pass
# --progress-lines: RecompLauncher's setup step (recomplauncher.json's prepare) reads "progress <0 to 1> <text>" lines.
PROGRESS_LINES = False
# Each step's share of the bar: its usual seconds on a first build (launcher/src/build_model.cpp's kSteps).
STEP_WEIGHTS = {'verify': 1, 'extract': 2, 'configure': 60, 'tools': 7, 'recompile': 2, 'packs': 280, 'compile': 55,
'stage': 1}
def emit(*parts):
print(' '.join(str(p) for p in parts), flush=True)
if PROGRESS_LINES:
line = progress_line(parts)
if line:
print(line, flush=True)
def progress_line(parts):
"""RecompLauncher's line for a PROGRESS (a step starts) or PERCENT (it moves on) line, else None: the share of the
whole build done, and the step's title (recomplauncher.com/sdk, prepare)."""
if len(parts) < 3 or parts[0] not in ('PROGRESS', 'PERCENT') or parts[1] not in STEP_WEIGHTS:
return None
step = parts[1]
pct = int(parts[2]) if parts[0] == 'PERCENT' else 0
before = sum(STEP_WEIGHTS[s] for s in STEPS[:STEPS.index(step)])
done = (before + STEP_WEIGHTS[step] * min(max(pct, 0), 100) / 100) / sum(STEP_WEIGHTS.values())
return 'progress %.3f %s%s' % (min(done, 0.999), STEP_TITLES[step], ' (%d%%)' % pct if parts[0] == 'PERCENT' else '')
def load_engine(path=None):
"""BozoEngine's tree (--engine, else the submodule) and its disc reader."""
"""BozoEngine's tree (--engine, else the pinned release, fetched in a git checkout) and its disc reader."""
global ENGINE, ps2_disc
if path:
ENGINE = os.path.abspath(path)
tools = os.path.join(ENGINE, 'tools', 'native_pack')
fetch = os.path.join(ROOT, 'cmake', 'bozo_engine_fetch.cmake')
if not path and os.path.exists(os.path.join(ROOT, '.git')) and shutil.which('cmake'):
# A checkout follows cmake/bozo_engine.json (nothing is downloaded while BozoEngine/.release matches it). A
# release's source has its BozoEngine already (stamped), so a player's build never downloads it.
subprocess.run([shutil.which('cmake'), '-P', fetch], stdout=subprocess.DEVNULL, check=False)
if not os.path.isfile(os.path.join(tools, 'ps2_disc.py')):
raise SystemExit('ERROR verify BozoEngine is missing (%s): the release is incomplete, or in a git checkout run '
'"git submodule update --init BozoEngine"' % ENGINE)
'"cmake -P cmake/bozo_engine_fetch.cmake"' % ENGINE)
sys.path.insert(0, tools)
import ps2_disc as module # noqa: E402
ps2_disc = module
@@ -672,6 +701,7 @@ class Build:
redo_from = STEPS.index(self.args.redo) if self.args.redo else len(STEPS)
n = len(STEPS)
dirty = False
ran = False
total_start = time.time()
for i, step in enumerate(STEPS, 1):
self.step = step
@@ -684,7 +714,7 @@ class Build:
emit('INFO', 'stopped', 'after ' + step)
return 0
continue
dirty = True # every later step runs again (Ninja only redoes what changed)
dirty = ran = True # every later step runs again (Ninja only redoes what changed)
emit('PROGRESS', step, '%d/%d' % (i, n), STEP_TITLES[step])
t = time.time()
self.state[step] = {'done': False}
@@ -713,6 +743,8 @@ class Build:
launcher = os.path.join(self.game, 'Play Dark Cloud.cmd' if os.name == 'nt' else 'play_dc.sh')
emit('INFO', 'total', '%.1f s' % (time.time() - total_start))
emit('RESULT', self.game, launcher)
if PROGRESS_LINES:
print('progress 1 %s' % ('Ready to play' if ran else 'Already built'), flush=True)
return 0
@@ -775,12 +807,14 @@ def check_disc(path):
def main():
ap = argparse.ArgumentParser(description='Builds Dark Cloud (USA) as a native PC game from your own disc.')
ap.add_argument('--disc', required=True, help='the disc image (.iso, .bin, .cue) or an extracted disc folder')
ap.add_argument('--disc', help='the disc image (.iso, .bin, .cue) or an extracted disc folder (default: the '
'disc.iso an earlier build left in the game folder)')
ap.add_argument('--out', default='dc_build', help='the work folder; the game ends up in <out>/DC')
ap.add_argument('--game', help='the game folder to stage (default: <out>/DC)')
ap.add_argument('--check', action='store_true', help='only check the disc (no work folder): OK <message> or '
'ERROR verify <message>')
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the BozoEngine submodule)')
ap.add_argument('--engine', help='BozoEngine\'s source tree (default: the release cmake/bozo_engine.json pins, in '
'BozoEngine/)')
ap.add_argument('--kit', help='the build kit folder (default: <DC_Recomp>/kit or <its parent>/kit if present)')
ap.add_argument('--no-kit', action='store_true', help='do not use a build kit even if one is found')
ap.add_argument('--toolchain', help='compiler folder (with bin/g++, cmake, ninja), default: the kit, PATH, '
@@ -793,13 +827,28 @@ def main():
ap.add_argument('--jobs', type=int, default=os.cpu_count() or 4)
ap.add_argument('--redo', choices=STEPS, help='run this step and the ones after it again')
ap.add_argument('--stop-after', choices=STEPS, help='stop once this step is done')
ap.add_argument('--progress-lines', action='store_true', help='also print "progress <0 to 1> <text>" lines, for '
'RecompLauncher (recomplauncher.json)')
args = ap.parse_args()
global PROGRESS_LINES
PROGRESS_LINES = args.progress_lines
if not args.disc:
# Built before: the game folder keeps the disc image (a link to the player's, or a copy), so an update builds
# again without it (RecompLauncher's keeps_copy, after the player deleted their own).
kept = os.path.join(os.path.abspath(args.game) if args.game else os.path.join(os.path.abspath(args.out), 'DC'),
'disc.iso')
if not os.path.isfile(kept):
emit('ERROR', 'verify', 'no disc image given (--disc) and none kept from an earlier build: pick your Dark '
'Cloud disc image (USA, SCUS-97111)')
sys.exit(1)
args.disc = kept
load_engine(args.engine)
if args.check:
sys.exit(check_disc(args.disc))
os.makedirs(os.path.abspath(args.out), exist_ok=True)
if not os.environ.get(ALIAS_ENV):
remove_stale_sources()
settle_source_times(os.path.abspath(args.out), find_kit(args))
if needs_ascii_aliases(args):
sys.exit(run_through_aliases(args))
sys.exit(Build(args).main())
@@ -853,6 +902,91 @@ def remove_stale_sources():
emit('INFO', 'update', '%d files of an earlier release removed from %s' % (removed, ROOT))
SOURCE_TIMES = 'source_times.json'
def settle_source_times(out, kit, now_ns=None):
"""A release zip dates every file at its commit's time (tools/make_release.py), which an unzip takes as local
time. Two failures follow for ninja, which only compares times:
- dated in the future (unzipped west of UTC within hours of the commit): build.ninja, regenerated, stays older
than CMakeLists.txt forever ("manifest 'build.ninja' still dirty after 100 tries");
- dated before the player's last build (an update unzipped over a game built after the commit): a changed file
looks older than its object and is not compiled again.
So the release's source files (release_files.txt) and the kit's FetchContent sources (deps/) are re-dated here,
from <out>/source_times.json (each file's size, time and SHA-1 as the last run left them): a file whose content changed,
or new to this release, is dated now; one unchanged gets its time back; nothing stays in the future. Without that
record and with a build folder from before, every file is dated now: everything is built again, once. The rest of
the kit (the toolchain: CMake's own modules are build.ninja's inputs too, the compiler's headers every object's)
only comes back from the future. A git checkout (no release_files.txt) is left alone: git dates the files it
writes now."""
listing = os.path.join(ROOT, 'release_files.txt')
if not os.path.isfile(listing):
return
now = now_ns if now_ns is not None else time.time_ns()
future = 0
if kit and os.path.isdir(kit):
for dirpath, _dirs, names in os.walk(kit):
for n in names:
p = os.path.join(dirpath, n)
try:
if os.stat(p).st_mtime_ns > now:
os.utime(p, ns=(now, now))
future += 1
except OSError:
pass
files = []
with open(listing, encoding='utf-8') as f:
files += [('source/' + l.strip(), os.path.join(ROOT, *l.strip().split('/'))) for l in f if l.strip()]
deps = os.path.join(kit, 'deps') if kit else None
if deps and os.path.isdir(deps):
for dirpath, dirs, names in os.walk(deps):
dirs.sort()
for n in sorted(names):
p = os.path.join(dirpath, n)
files.append(('deps/' + os.path.relpath(p, deps).replace('\\', '/'), p))
record_path = os.path.join(out, SOURCE_TIMES)
try:
with open(record_path, encoding='utf-8') as f:
old = json.load(f)
if not isinstance(old, dict):
old = None
except (OSError, ValueError):
old = None
built_before = os.path.isfile(os.path.join(out, 'build', 'build.ninja'))
record, changed = {}, 0
for key, path in files:
try:
st = os.stat(path)
except OSError:
continue
mtime = st.st_mtime_ns
rec = old.get(key) if old else None
if rec and rec[0] == st.st_size and rec[1] == mtime:
digest, target = rec[2], mtime # untouched since the last build
else:
digest = sha1_file(path)
if rec and rec[2] == digest:
target = rec[1] # the same content: its time at the last build
elif rec or old is not None or built_before:
target = now # changed, new to this release, or unknown with a build from before
changed += 1
else:
target = mtime # a first build: nothing to be older than
if target > now:
target = now
future += 1
if target != mtime:
os.utime(path, ns=(target, target))
record[key] = [st.st_size, target, digest]
tmp = record_path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(record, f, separators=(',', ':'))
os.replace(tmp, record_path)
if changed or future:
emit('INFO', 'update', '%d source files dated now (%d changed or new, %d were dated in the future)'
% (changed + future, changed, future))
# ---- folders whose path is not ASCII (Windows) ----
#
# MSYS2's binutils open files in the ANSI code page: ld cannot open an object or library whose path, read from the
+3 -2
View File
@@ -2,8 +2,9 @@
# Adapted from The Bozos TMB_Recomp (MIT); see launcher/LICENSE for original attribution.
"""make_build_kit: assembles the build kit tools/dc_build.py uses on a PC with nothing installed (no MSYS2, git,
network or Python): a compiler, CMake and Ninja, a minimal static FFmpeg, the libraries' sources (SDL3, Dear ImGui)
and an embeddable Python. The game is built on BozoEngine, whose sources come with DC_Recomp's (the BozoEngine
submodule, in a release's source/BozoEngine): its recompiler is built on the player's PC with the rest. Run once on the
and an embeddable Python. The game is built on BozoEngine, whose sources come with DC_Recomp's (the release
cmake/bozo_engine.json pins, in BozoEngine/ and a release's source/BozoEngine): its recompiler is built on the player's
PC with the rest. Run once on the
developer's PC (MSYS2 UCRT64 installed, network for the downloads); the kit is build output, never committed.
python tools/make_build_kit.py --out D:/dc_kit/kit [--downloads D:/dc_kit/downloads] [--zip D:/dc_kit/kit.zip]
+37 -29
View File
@@ -9,9 +9,10 @@ redistributes.
python tools/make_release.py --out D:/dc_release --publish --dry-run (the version from the commit's tag)
What it does, from <commit> (default HEAD; only committed files count, the working tree is never read):
export git archive of the commit and of the BozoEngine submodule at the commit it records (without its
reference/ records, which the build never reads) -> source\\ (no .git, no build/, nothing generated);
source\\release.ini stamps the version and both commits. The tree is audited: no ELF, IRX, disc image,
export git archive of the commit -> source\\ (no .git, no build/, nothing generated), and the BozoEngine
release its cmake/bozo_engine.json pins -> source\\BozoEngine (cmake/bozo_engine_fetch.cmake: the
release's archive, SHA-256 checked); source\\release.ini stamps the version, the commit and the
engine's version. The tree is audited: no ELF, IRX, disc image,
pack, generated code or disc file name may be in it.
kit the build kit (--kit <dir>: an existing one, hard-linked into the release; else assembled by
tools/make_build_kit.py, which needs MSYS2 and the network): a BozoEngine kit (kit_version 2: SDL3 and
@@ -28,7 +29,8 @@ What it does, from <commit> (default HEAD; only committed files count, the worki
changelog CHANGELOG.md's section for the version (## [x.y.z], Keep a Changelog), from the commit: the release
refuses to be made without one (an empty one, or only "Unreleased", too) unless
--allow-missing-changelog (test builds). CHANGELOG.md is shipped at the zip's top (the launcher's
"What's new" reads it) and the section is the release notes' "What's new".
"What's new" reads it) and the section is the release notes' "What's new". recomplauncher.json (the
commit's) is shipped at the zip's top too, where RecompLauncher reads it.
zip DC_Recomp-<version>-bozo.zip (deflate, entries sorted, every timestamp the commit's), <zip>.sha256,
RELEASE_NOTES.md (the changelog section, the hashes, the source offer: the GitHub release's body). The
zip's names are audited again.
@@ -61,13 +63,13 @@ import zipfile
ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
REPO = 'TheBozos/DC_Recomp'
ENGINE_REPO = 'TheBozos/BozoEngine'
ENGINE_DIR = 'BozoEngine' # the submodule
# What BozoEngine's export leaves out (its reference records: hashes of recorded runs, never read by the build).
ENGINE_SKIP = ('reference',)
ENGINE_DIR = 'BozoEngine' # the release cmake/bozo_engine.json pins
NAME = 'DC_Recomp'
# Canonical player archive and installation folder, matching the TMB launcher workflow.
FLAVOR = 'bozo'
TOP = 'DC_Recomp_Bozo'
# RecompLauncher's manifest (recomplauncher.com/sdk): at the repo's top, shipped at the zip's top.
RECOMPLAUNCHER_JSON = 'recomplauncher.json'
VERSION_RE = re.compile(r'^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$')
MSYS2_SOURCES = 'https://repo.msys2.org/mingw/sources/'
# The launcher's font (launcher/CMakeLists.txt pins the same commit and hash).
@@ -377,7 +379,7 @@ class Release:
self.zip = os.path.join(self.out, self.name + '.zip')
self.sources_zip = os.path.join(self.out, self.name + '-sources.zip')
self.commit_date = int(git('show', '-s', '--format=%ct', self.commit))
self.engine_commit = None
self.engine_version = None
self.manifest = None
self.msys_sources = [] # (package base, version, licence, url, file, sha256)
@@ -398,21 +400,18 @@ class Release:
rmtree(self.stage)
os.makedirs(self.source)
extract_tar_stream([find_git(), 'archive', '--format=tar', self.commit], self.source, ROOT)
entry = git('ls-tree', self.commit, ENGINE_DIR).split()
if len(entry) < 3 or entry[0] != '160000':
raise ReleaseError('%s is not a submodule at %s' % (ENGINE_DIR, self.commit))
self.engine_commit = entry[2]
engine_repo = os.path.join(ROOT, ENGINE_DIR)
try:
git('cat-file', '-e', self.engine_commit + '^{commit}', cwd=engine_repo)
except ReleaseError:
raise ReleaseError('the submodule does not have %s: git submodule update --init %s'
% (self.engine_commit, ENGINE_DIR))
engine_dst = os.path.join(self.source, ENGINE_DIR)
os.makedirs(engine_dst, exist_ok=True)
extract_tar_stream([find_git(), 'archive', '--format=tar', self.engine_commit], engine_dst, engine_repo)
for skip in ENGINE_SKIP:
rmtree(os.path.join(engine_dst, skip))
# The BozoEngine release the commit's cmake/bozo_engine.json pins, fetched into source\BozoEngine with its
# .release stamp (the archive SHA-256 checked), so a player's build finds it and never downloads it.
with open(os.path.join(self.source, 'cmake', 'bozo_engine.json'), encoding='utf-8') as f:
self.engine_version = json.load(f)['version']
cmake = shutil.which('cmake')
if not cmake and os.path.isfile(os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')):
cmake = os.path.join(self.args.msys, 'ucrt64', 'bin', 'cmake.exe')
if not cmake:
raise ReleaseError('no cmake on PATH: it fetches the BozoEngine release (cmake/bozo_engine_fetch.cmake)')
os.makedirs(self.downloads, exist_ok=True)
run([cmake, '-DBOZO_ENGINE_DOWNLOADS=' + self.downloads, '-P',
os.path.join(self.source, 'cmake', 'bozo_engine_fetch.cmake')])
# The list of the source's files: dc_build removes the ones a newer release unzipped over this one no longer
# has (CMake globs runtime/*.cpp: a deleted file left behind would still be compiled).
files = sorted(os.path.relpath(os.path.join(d, n), self.source).replace('\\', '/')
@@ -421,14 +420,14 @@ class Release:
write_text(os.path.join(self.source, 'release_files.txt'), '\n'.join(sorted(set(files))) + '\n')
write_text(os.path.join(self.source, 'release.ini'),
'# The DC_Recomp release this folder is (tools/make_release.py writes this file).\n'
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_commit = %s\ndate = %s\n'
% (self.version, self.commit, self.engine_commit,
'version = %s\ncommit = %s\nengine = BozoEngine\nengine_version = %s\ndate = %s\n'
% (self.version, self.commit, self.engine_version,
time.strftime('%Y-%m-%d', time.gmtime(self.commit_date))))
problems = audit_tree(self.source, rel_prefix='source/')
if problems:
raise ReleaseError('the source export holds what looks like game data:\n ' + '\n '.join(problems[:20]))
n = sum(len(f) for _d, _s, f in os.walk(self.source))
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_commit[:12], n,
log(' source: %s + BozoEngine %s, %d files, %.1f MB, audited' % (self.commit[:12], self.engine_version, n,
dir_size(self.source) / 1e6))
# -- the kit
@@ -642,7 +641,7 @@ class Release:
'DC_Recomp (source\\, this release\'s code; MIT, LICENSES\\DC_Recomp)',
' https://github.com/%s/tree/%s' % (REPO, self.commit),
'BozoEngine, the recompiler and runtime the game is built on (source\\BozoEngine; MIT, LICENSES\\BozoEngine)',
' https://github.com/%s/tree/%s' % (ENGINE_REPO, self.engine_commit),
' https://github.com/%s/releases/tag/v%s' % (ENGINE_REPO, self.engine_version),
' The whole source is in source\\ already, the launcher\'s too (source\\launcher).',
'',
'The build kit (kit\\) redistributes these programs and libraries unmodified. Their corresponding source:',
@@ -778,6 +777,10 @@ class Release:
at = at + 1 if at >= 0 else len(text)
text = text[:at] + '## [%s] - test build\n\n%s\n\n' % (self.version, self.changelog_section) + text[at:]
write_text(os.path.join(self.stage, 'CHANGELOG.md'), text, crlf=True)
# RecompLauncher's manifest at the top, next to the launcher, where RecompLauncher reads it: the commit's.
manifest = git('show', '%s:%s' % (self.commit, RECOMPLAUNCHER_JSON), binary=True)
with open(os.path.join(self.stage, RECOMPLAUNCHER_JSON), 'wb') as f:
f.write(manifest)
# -- the changelog
@@ -842,7 +845,7 @@ class Release:
'Saves and settings stay in `%APPDATA%\\DC_Recomp`. The launcher offers future updates and rebuilds.',
'',
'## Build information', '',
'- Code: %s (`%s`), BozoEngine `%s`' % (REPO, self.commit, self.engine_commit),
'- Code: %s (`%s`), BozoEngine %s' % (REPO, self.commit, self.engine_version),
'- Build kit: GCC %s, CMake %s, Ninja %s (MSYS2 UCRT64), FFmpeg %s (LGPL, static), Python %s'
% (self.pkg_version('gcc'), self.pkg_version('cmake'), self.pkg_version('ninja'),
self.manifest['ffmpeg']['version'], self.manifest['python']['version']),
@@ -985,7 +988,7 @@ def verify_zip(path, top=TOP):
problems.append('%s: an ELF file' % n)
if len(head) >= 0x8006 and head[0x8001:0x8006] == b'CD001':
problems.append('%s: an ISO9660 volume' % n)
for need in ('DC Launcher.exe', 'README.txt', 'CHANGELOG.md', 'LICENSES/DC_Recomp/LICENSE',
for need in ('DC Launcher.exe', 'README.txt', 'CHANGELOG.md', RECOMPLAUNCHER_JSON, 'LICENSES/DC_Recomp/LICENSE',
'LICENSES/BozoEngine/LICENSE', 'LICENSES/TMB_Recomp/LICENSE', 'source/VERSION', 'source/release.ini', 'kit/kit_manifest.json',
'kit/python/python.exe', 'source/tools/dc_build.py', 'source/BozoEngine/CMakeLists.txt',
'kit/deps/sdl3-src/CMakeLists.txt', 'kit/deps/imgui-src/imgui.cpp'):
@@ -1149,6 +1152,11 @@ Version {version}
def main():
# The changelog and the notes are UTF-8 ("Options → Travel"): the console's code page (cp1252 on Windows) cannot
# print every character, so the tool's output is UTF-8 too.
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, 'reconfigure'):
stream.reconfigure(encoding='utf-8')
ap = argparse.ArgumentParser(description='Makes the DC_Recomp release zip (see the docstring).')
ap.add_argument('--version', help='MAJOR.MINOR.PATCH[-pre] (default: the commit\'s tag, v stripped)')
ap.add_argument('--commit', help='the commit to release (default HEAD); only committed files count')