Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02a590f184 | ||
|
|
1234cf4f0f | ||
|
|
8a9cf7781d | ||
|
|
767b3e9557 | ||
|
|
851b6244d7 | ||
|
|
95903df0c9 | ||
|
|
6481ee4cb4 | ||
|
|
112cf4152f | ||
|
|
98b2b54de7 | ||
|
|
538902b3c0 | ||
|
|
07ac1d561f | ||
|
|
e61fb960e3 | ||
|
|
1f967b5c75 | ||
|
|
357135cb0a | ||
|
|
c90df9d710 | ||
|
|
13526ac41e | ||
|
|
44e53f9833 | ||
|
|
914284e90e | ||
|
|
ed49582da9 | ||
|
|
57e0ed663f | ||
|
|
65d399ffa6 | ||
|
|
96da183591 | ||
|
|
fccc458694 | ||
|
|
01433f480f | ||
|
|
e596e3e056 | ||
|
|
97b15a717e | ||
|
|
8889dbb724 | ||
|
|
135a95d76c | ||
|
|
0fa612582e | ||
|
|
97617b7afd | ||
|
|
daaf0642c1 | ||
|
|
8dfa1f69c6 | ||
|
|
ce43fadc87 | ||
|
|
8dcf830c98 | ||
|
|
ba2f632589 | ||
|
|
5c299d714f | ||
|
|
a043405eab | ||
|
|
37166934e9 | ||
|
|
fcfa1a580b | ||
|
|
4d4e633ded | ||
|
|
b186560a21 | ||
|
|
15ef14bb8b | ||
|
|
a51e17510a | ||
|
|
25849df593 | ||
|
|
67a4e61656 | ||
|
|
15aeeb7c37 | ||
|
|
83147e82a6 | ||
|
|
dfc80d2af0 | ||
|
|
a96c67d850 | ||
|
|
31b442693e | ||
|
|
b1541a5a67 | ||
|
|
66cd2b5f90 | ||
|
|
ea1ed845bb | ||
|
|
a08c3283cd | ||
|
|
3d3d37d935 | ||
|
|
5b5c1f4256 | ||
|
|
c844d22452 | ||
|
|
473db2146d | ||
|
|
1b1c3d8a9a | ||
|
|
482abd9fc3 | ||
|
|
35fcc4cdae | ||
|
|
ca778fe81e | ||
|
|
b118d0a8ab | ||
|
|
320bc27f8d | ||
|
|
f2ecd99cb3 | ||
|
|
549c5753b7 | ||
|
|
bdfcd6447b | ||
|
|
4ef5cf6f0a | ||
|
|
4a7f5ad4a6 | ||
|
|
e72dc61db6 | ||
|
|
7f1f6c802b | ||
|
|
a592d8e3ee | ||
|
|
42920f3a57 | ||
|
|
f9ec4ddce0 | ||
|
|
9710186230 | ||
|
|
4207130f78 | ||
|
|
b1025e01b3 | ||
|
|
a2ff5405c2 | ||
|
|
b9025d3717 | ||
|
|
f003c2c4ef | ||
|
|
8e469b6e98 | ||
|
|
7f34ba411e | ||
|
|
ad72ef2486 | ||
|
|
d43b9afeeb | ||
|
|
4367975295 | ||
|
|
7d374fc209 | ||
|
|
5aaf3050f9 | ||
|
|
72c93120b3 | ||
|
|
8132527b85 | ||
|
|
e103788620 | ||
|
|
5c5b1799f8 | ||
|
|
70e9be8e92 | ||
|
|
a8aa68dac3 | ||
|
|
6c0c9045a9 | ||
|
|
1e569a0c23 | ||
|
|
4759b4e787 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
[submodule "BozoEngine"]
|
||||
path = BozoEngine
|
||||
url = https://github.com/TheBozos/BozoEngine.git
|
||||
@@ -1,5 +1,111 @@
|
||||
# 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
|
||||
- Graphics page in the game's Options (controller): display mode, resolution, render scale and frame rate, applied at once and saved to `video.ini`.
|
||||
- Cheats: weapon level-up, reveal floor map, fish always bite, item spawner, fast-forward (hold ` or the touchpad, or lock it on), damage multiplier, one-hit kills, no damage taken and a key finder on the dungeon map.
|
||||
|
||||
### Changed
|
||||
- More of the game runs natively: the per-frame and loading-screen DMA transfers, the per-frame GS display swap and the startup GS sync-path calls are gone, and model, remake, shadow and cloth builds no longer reserve space for console packet data.
|
||||
- BozoEngine moves to its current main (8a4ac05), which adds the calls the Graphics page uses.
|
||||
|
||||
### Fixed
|
||||
- The game now reads `video.ini`: the launcher's display settings and the F2 Video tab apply (the game ignored them). `--fullscreen` still opens borderless over the monitor.
|
||||
|
||||
### Known limits
|
||||
- Gameplay testing covers Norune, Divine Beast Cave, Matataki, Georama, saving and loading; a complete story playthrough and full visual parity are unverified.
|
||||
- Linux and widescreen are not qualified.
|
||||
|
||||
## [0.2.0] - 2026-11-09
|
||||
|
||||
### Changed
|
||||
- BozoEngine moves to its current main (296ac6d), with the other ports' engine work since 0.1.0.
|
||||
|
||||
### Fixed
|
||||
- Frame-rate drops in heavy interiors (36-42 FPS in a house interior): a model's texture is checked once per draw instead of once per piece.
|
||||
- Loading screens no longer wait forever on the newer engine: the game's own vsync interrupt handler is kept.
|
||||
|
||||
### Known limits
|
||||
- Gameplay testing covers Norune, Divine Beast Cave, Matataki, Georama, saving and loading; a complete story playthrough and full visual parity are unverified.
|
||||
- Linux and widescreen are not qualified.
|
||||
|
||||
## [0.1.0] - 2026-11-08
|
||||
|
||||
### Added
|
||||
@@ -16,4 +122,5 @@
|
||||
- The release retains the gameplay-qualified engine revision. The newer-engine loading stall remains deferred.
|
||||
- Linux and widescreen are not qualified.
|
||||
|
||||
[0.2.0]: https://github.com/TheBozos/DC_Recomp/releases/tag/v0.2.0
|
||||
[0.1.0]: https://github.com/TheBozos/DC_Recomp/releases/tag/v0.1.0
|
||||
@@ -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")
|
||||
@@ -179,12 +199,36 @@ if(DC_ENGINE_TESTS)
|
||||
target_link_options(dc-cheat-tests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME dc_native_cheats COMMAND dc-cheat-tests)
|
||||
add_executable(dc-cheat-extra-tests tests/dc_cheat_extra_tests.cpp)
|
||||
target_link_libraries(dc-cheat-extra-tests PRIVATE dc_cheats bozo_host)
|
||||
if(MINGW)
|
||||
target_link_options(dc-cheat-extra-tests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME dc_native_cheat_extras COMMAND dc-cheat-extra-tests)
|
||||
add_executable(dc-ingame-cheat-menu-tests tests/dc_ingame_cheat_menu_tests.cpp)
|
||||
target_link_libraries(dc-ingame-cheat-menu-tests PRIVATE dc_ingame_cheats bozo_host)
|
||||
if(MINGW)
|
||||
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)
|
||||
@@ -194,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)
|
||||
@@ -235,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)
|
||||
@@ -314,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})
|
||||
@@ -371,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)
|
||||
@@ -447,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)
|
||||
|
||||
@@ -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.
|
||||
@@ -28,7 +28,7 @@ BozoEngine replaces the PS2Recomp fork completely; there is no emulation fallbac
|
||||
|
||||
## For players (Windows)
|
||||
|
||||
Download **`DC_Recomp-0.1.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 **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,
|
||||
@@ -62,11 +68,15 @@ A complete story playthrough and full visual parity remain unverified.
|
||||
| Travel to Matataki through “Go to Other Area” | ✅ |
|
||||
| Memory-card saving, loading and restart with saved progress | ✅ |
|
||||
| Native music and effects | ✅ |
|
||||
| Controller-operated Cheats and Quit Game inside Options; F2 settings remain available | ✅ |
|
||||
| New-game opening and Georama coverage on BozoEngine | 🔧 |
|
||||
| Complete story, all companions, locations and effects | 🔧 |
|
||||
| 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 | 🔧 |
|
||||
| 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.
|
||||
@@ -96,30 +106,25 @@ the full encounter still needs a player comparison. Matataki's reported sharp sk
|
||||
and confirmed in the player's comparison.
|
||||
|
||||
[docs/NATIVE_RENDERING_FOLLOWUP.md](docs/NATIVE_RENDERING_FOLLOWUP.md) records recent fixes, playtest
|
||||
coverage and the retained engine pin. [docs/BOZO_MIGRATION.md](docs/BOZO_MIGRATION.md) retains the migration
|
||||
coverage and the move to engine main (the loading-screen vsync callback). [docs/BOZO_MIGRATION.md](docs/BOZO_MIGRATION.md) retains the migration
|
||||
and conditional dispatch audit; [docs/RECOMP_NOTES.md](docs/RECOMP_NOTES.md) records earlier bring-up work.
|
||||
|
||||
## 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.
|
||||
|
||||
| | | |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|  |  |  |
|
||||
|
||||
## 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
|
||||
|
||||
@@ -148,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
|
||||
|
||||
@@ -179,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"
|
||||
@@ -210,8 +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), **Cheats**, and
|
||||
**Quit Game**. Up/Down selects rows, Cross confirms and Circle goes back. 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.
|
||||
|
||||
@@ -241,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
|
||||
@@ -271,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).
|
||||
@@ -289,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.1.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;
|
||||
@@ -323,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 |
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"version": "0.5.0",
|
||||
"sha256": "319cda4ce617638decdcb7d6eff482c94528fb66ab6e14e3e2c5b4e43e214d0f"
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -1140,7 +1140,7 @@ The allocation audit deliberately retains these different owners:
|
||||
| Shared primary arena and read/data subarenas | Real files, models, game objects and allocator cursor/bounds behavior |
|
||||
| Visibility descriptor/capacity/cursor | Native depth queries and per-frame reset of their logical request extent; its backing reserve is removed |
|
||||
| Visual MDT data address and size | `CreateVisual` `0x126770` passes the native builder's visual size to `CDataAlloc2::Alloc`, then advances game bookkeeping; the data address keys `g_mdtCopies` and visual fields |
|
||||
| Model/shadow/cloth allocation extents | The shared game allocation ABI still advances by these sizes. `modelAllocationQwords` and `clothCreateHook` retain legacy VIF-size formulas without serializing packets. Shrinking them requires migrating address identity, reuse/lifetime and live-animation/remake contracts together |
|
||||
| Model/shadow/cloth allocation extents | The shared game allocation ABI still advances by these sizes. Since the model-extent and cloth-extent migrations each build reserves one qword, keeping its own aligned address (see "Native model extent" and "Native cloth extent") |
|
||||
|
||||
The earlier snapshot/lifetime and original/native builder tests still pass. No generic allocator is replaced,
|
||||
and the model/cloth size ABI is not collapsed to zero or a shared dummy identity.
|
||||
@@ -1713,3 +1713,343 @@ methods and six changed-instruction guard rejections. **77/77 normal suites** an
|
||||
Runtime, production patches,
|
||||
the engine pin and saves are unchanged. Live DUN coverage remains **33/43** with
|
||||
497 unobserved sites globally; fixtures add no gameplay or visual qualification.
|
||||
|
||||
## Per-frame transfer retirement (2026-11-09)
|
||||
|
||||
`MGEndFrame`'s tail no longer waits, flushes or sends. The earlier frame-end pass kept one native SDK send per frame,
|
||||
an empty VIF1 transfer, to preserve its completion interrupt and callback. That completion has no consumer: the game's
|
||||
only `AddDmacHandler` call is in `sceSifInitCmd`, which BozoEngine answers natively, so no DMA-completion handler is
|
||||
ever installed. The `sceDmaSync` before it waits on the GIF channel (`gp-0x7434`, from `MGInit`), which never carries a
|
||||
transfer in this port. Three guarded patches retire `sceDmaSync` (`0x12d61c`), `FlushCache` (`0x12d678`) and
|
||||
`sceDmaSend` (`0x12d68c`); every delay slot was already a `nop`. The frame counter and its first-frame flag, the
|
||||
`sceDmaGetChan(1)` lookup stored at `gp-0x7438` and the double-buffer toggle stay.
|
||||
|
||||
- The `frame_submit` reference/adapted span now starts at `0x12d610`, covering the wait. 24 cases (counter overflow,
|
||||
buffer states, first frame): the published reference waits, flushes and sends once; the adapted tail makes no
|
||||
transfer, flush or wait and queues no completion. Frame counter, flag, channel handle and toggle match; all other
|
||||
guest RAM is unchanged.
|
||||
- **126/126** suites. The seven scripted routes end as before with identical cards and zero register/unknown accesses,
|
||||
VU0 calls or GIF submissions. VIF1 SDK submissions per route fall from 5,338–10,010 to **1,190** (1,571 on the
|
||||
Matataki route), and sync calls from 6,536–10,986 to 2,388–3,162. Captures match the previous build within 2 mean
|
||||
levels outside the two known fade frames.
|
||||
|
||||
Remaining transfer calls, about 1,190 per run, sit in the boot and loading paths: `main`'s four sends at mode changes
|
||||
(two upload VU1 microcode from `0x24f960`/`0x296680`, which nothing executes), `VSyncCallBack_Load`'s send and syncs,
|
||||
`EnterFixTexture`/`EnterFixTextureZ` and `StoreImage`.
|
||||
|
||||
### Boot and loading transfers (2026-11-09)
|
||||
|
||||
The rest follow the same reasoning:
|
||||
|
||||
- `VSyncCallBack_Load`, every vblank while loading: `sceDmaSync` of VIF1 (`0x154380`), `iFlushCache` (`0x15468c`),
|
||||
the empty VIF1 `sceDmaSend` (`0x1546a0`) and `sceDmaSync` of GIF (`0x15474c`) are retired. The `loading`
|
||||
reference/adapted span (96 cases) now requires the adapted callback to make no cache or transfer call and queue no
|
||||
completion, while its fade sprites match the reference's calls in order and all non-stack RAM matches.
|
||||
- `main`, at mode changes: four `FlushCache` / `sceDmaSend` / `sceGsSyncPath` triples (`0x141388`..`0x141638`) are
|
||||
retired, two of them the VU1 microcode uploads. `v0` is reloaded after each removed call.
|
||||
- `EnterFixTexture` / `EnterFixTextureZ` are replaced whole by native hooks, so their sends never run. `StoreImage` is
|
||||
reached only from `MGEndFrame`'s screenshot branch (`0x12d4e4`).
|
||||
|
||||
**126/126** suites. All seven routes now report **0 VIF0, 0 VIF1, 0 GIF submissions and 0 sync calls**, with the same
|
||||
ends, identical cards and zero register/unknown accesses and VU0 calls. A loading transition finishes slightly earlier
|
||||
(the Matataki route's frame 6,000 arrives where the previous build is still fading); later captures show the same views
|
||||
within about 3 mean levels.
|
||||
|
||||
### Per-frame display-buffer swap (2026-11-09)
|
||||
|
||||
`MGEndFrame` no longer calls `sceGsSetHalfOffset` (`0x12d5e8`), `FlushCache` (`0x12d5f4`) or `sceGsSwapDBuff`
|
||||
(`0x12d608`) every frame. `sceGsSetHalfOffset` only rewrites the draw record's XYOFFSET image, which the native
|
||||
renderer never reads; `sceGsSwapDBuff` writes nothing and only hands the records to `sceGsPutDispEnv` /
|
||||
`sceGsPutDrawEnv`, both no-ops in BozoEngine. The per-frame `sceDmaGetChan(1)` (`0x12d64c`) and its store
|
||||
(`0x12d654`) go too: `MGInit` already stored that VIF1 handle, and without the call the store would have written the
|
||||
frame counter left in `v0`. The buffer index toggle stays.
|
||||
|
||||
- The `frame_submit` span now starts at `0x12d5c0` (24 cases): the reference sets the half offset, swaps, waits,
|
||||
flushes twice, looks the channel up and sends; the adapted span does none of these, and all guest RAM matches, the
|
||||
channel handle included.
|
||||
- 126/126 suites; seven routes with the same ends, identical cards, and zero transfers or syncs. Matataki frames differ
|
||||
only by cloud drift after the earlier load (up to 3.8 mean levels).
|
||||
- A temporary per-name library-call count on the 9,000-frame Matataki route (not committed) shows
|
||||
`sceGsPutDispEnv` / `sceGsPutDrawEnv` going from 7,869 / 7,868 calls to none, and `sceDmaGetChan` from 7,874 to 6.
|
||||
The PS2 library calls left every frame are the controller (`scePad*`) and the sound driver's SIF commands. The
|
||||
GS-library calls left run at startup or mode changes: `sceGsSyncV` (86, in `CGamePad::Init`), `sceGsSyncPath` (9)
|
||||
and the `sceGsSetDef*` record setup.
|
||||
|
||||
### Startup GS calls: sceGsSyncPath retired, sceGsSyncV kept (2026-11-09)
|
||||
|
||||
`main`'s mode change no longer calls `sceGsSyncPath` (`0x141334`); it always answers "idle", and `v0` is reloaded
|
||||
right after. With it alone, the EE clock of the companion route (the title attract demo) matches the previous build at
|
||||
every logged frame and its captures are identical. 126/126 suites; all seven routes end as before with identical cards.
|
||||
|
||||
The 22 `sceGsSyncV` calls (`CGamePad::Init`, `main`, `SndBgmFadeOutStop`, `EditLoop`) are **kept**. BozoEngine's
|
||||
handler neither waits nor ends a frame, but these calls are still part of the boot timeline. Replacing them all with
|
||||
`v0 = 1` reached frame 0 about 36 fields later in EE time, and shifted the attract demo by one field from frame 120
|
||||
on. Restoring only `CGamePad::Init`'s waits put frame 0 back, but the attract demo still diverged: at frame 60 the
|
||||
previous build is inside `main`'s wait-for-odd-field loop (`0x141140`), which really does spin during boot until the
|
||||
loading screen's vsync callback ends a frame. Removing these calls would change behaviour for a few dozen free calls at
|
||||
startup, so they stay; the one-time `sceGsResetGraph` (field rate) and `sceGsSetDef*` record setup stay too.
|
||||
|
||||
## Model extents: who writes the VU data buffers (2026-11-09)
|
||||
|
||||
The model, remake and shadow builders still return the old VIF packet size (`modelAllocationQwords`), and the game
|
||||
reserves that much arena for a buffer nothing fills. Before replacing it with a native size, `DC_PROBE_EXTENTS=1`
|
||||
checks whether anything else uses those buffers. Each buffer is filled with a pattern when built (native builders write
|
||||
nothing there), and every 60 frames the buffers built in the last 600 frames are compared. A change is classified as
|
||||
**live** when the building visual still has its vtable, still points at this buffer and still has this size.
|
||||
|
||||
- The six gameplay routes (Matataki travel, Cheats + Quit, water, dungeon menu, save, reload) report 13–82 changed
|
||||
buffers each, and **none while their visual owned them**: every change is reuse after the scene or asset changed.
|
||||
- The attract-demo route reports 352 changed buffers, 8 classified live. Their new bytes are float vectors ending in
|
||||
1.0 and colour bytes: model data loaded at the demo's scene switches (frames 4,980, 6,120, 6,480, 7,020, 7,440),
|
||||
over buffers whose old visual records simply were not overwritten yet. No VIF command words appear.
|
||||
|
||||
No game code was found writing into a built VU data buffer that is still in use. `SetVuData`, the only original
|
||||
routine that wrote into one, is called only from the replaced `CreateVUdataFromMDT`. Cloth builds return a size before
|
||||
their buffer exists, so the probe does not cover cloth.
|
||||
|
||||
### Native model extent
|
||||
|
||||
Model, remake and shadow builds now reserve **one qword**; `modelAllocationQwords` and its VIF packet formula are
|
||||
gone. `CreateVisual` builds at the allocator's cursor, reserves the returned extent, adds it to the game's running
|
||||
total at `gp-0x7460` and calls `Align64`, so every build still gets its own 64-byte-aligned data address. That address
|
||||
keys the retained MDT copy, and double-buffered visuals keep their two distinct addresses at `+0x28`/`+0x2c`. Remakes
|
||||
reuse their buffer, and the raw `CVisualMDTVu1` draw's temporary allocation now takes one qword. Before, single builds
|
||||
reserved up to hundreds of kilobytes each (the probe saw 75,008- and 334,176-byte remake buffers).
|
||||
|
||||
- The builder fixture (1,064 cases) now requires the original to reserve its VIF size and the native build to reserve
|
||||
one qword, with its data address recorded and no console output written. 126/126 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 still frame-exact. Captures match within 3.6 mean levels outside the known fade
|
||||
frames. A scripted walk onto Divine Beast Cave B1 (map revealed through the Cheats page) renders the floor, Toan and
|
||||
HUD normally.
|
||||
|
||||
### Native cloth extent
|
||||
|
||||
Cloth `CreateVUData` (`0x13C5F0`) now also reserves **one qword**; `textureAllocationQwords` and its formula are gone.
|
||||
`CCloth::Initialize` stores the cursor as buffer 0 (`+0x24`), builds, records the size at `+0x1C`, reserves it with
|
||||
`Alloc`, takes buffer 1 with `Alloc64(size)` (`+0x28`) and builds again, so the two buffers keep distinct addresses.
|
||||
Its per-frame `DrawVu1` (`0x13C470`) is replaced by the native cloth draw, which never reads the size or either buffer:
|
||||
it draws from the simulation grid at `cloth + row*0x100 + column*0x10`. In the cloth code (`0x13B800`–`0x13E400`) only
|
||||
`Initialize` touches `+0x1C` (`0x13CC5C`–`0x13CC94`).
|
||||
|
||||
- The builder fixture's cloth case now requires the original to reserve its VIF size and the native build one qword.
|
||||
126/126 suites.
|
||||
- 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.
|
||||
@@ -1,12 +1,20 @@
|
||||
# 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) 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.
|
||||
|
||||
The same cheat controls remain available in **F2 → Cheats**. Both interfaces share session settings.
|
||||
|
||||
**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), **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 |
|
||||
|---|---|
|
||||
| Infinite health | Keeps all party HP full and cancels queued loss |
|
||||
@@ -20,8 +28,17 @@ The same cheat controls remain available in **F2 → Cheats**. Both interfaces s
|
||||
| Movement speed | 50–200% horizontal player displacement before collision; leaves gravity unchanged |
|
||||
| Freeze time of day | Holds one shared time input for outdoor sky and lighting; game/story timers and menu fades continue |
|
||||
| Inventory size | One edit, 1–100 slots; refuses shrinkage that would hide an occupied entry or exceed capacity with active quantities |
|
||||
| Level up equipped weapon | Fills the equipped weapon's ABS to the game's own threshold; choose **Level up** in the weapon menu as usual. Refused for default weapons, the Serpent Sword and level 99 |
|
||||
| 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 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 16 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.
|
||||
@@ -32,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 starts at 1× and movement starts at 100% 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.
|
||||
@@ -63,3 +129,35 @@ item requests; and observe the inputs reaching collision and both lighting rende
|
||||
transitions and the quit confirmation's default/cancel/one-shot behaviour. Native-window captures
|
||||
check layout and original settings access. Full retail combat and all movement/lighting situations
|
||||
remain part of manual gameplay testing.
|
||||
|
||||
### Level-up, map, fishing, spawner, fast-forward, combat and key finder
|
||||
|
||||
Hook points, all in the main program (the DUN overlay is reached through the main routines it calls, with
|
||||
return-address checks and the identity-matched DUN module):
|
||||
|
||||
- **Level-up**: a one-shot edit at the player's status tick. ABS (`WEAPON_HAVE+0x14`) is set to the compiled
|
||||
`GetWeaponMaxExp` (0x232080) result; the weapon menu's own flow then applies stat gains, attachment absorption,
|
||||
synthsphere counting, `level+1` and the ABS reset. A kill at full ABS never levels a weapon in the original either.
|
||||
- **Map**: `FlushCheckMask` (0x1C3C00, after the floor build clears it) and `checkMask` (0x1C39C0, walking updates)
|
||||
write the 20×20 explored grid (`CDungeonMap+0x8710`) and room flags for cells that have floor, on the two DUN map
|
||||
objects only (0x1DC4BE0, 0x1DD56F0); column 19, which no floor reaches, is left alone. The grid is not saved.
|
||||
- **Fishing**: `rand_check` (0x240050) gets probability 0 for the LeaveFood/LeaveHook rolls only, still drawing its
|
||||
`rand()`; `CFish::Step` (0x240480) holds a hooked fish's timer (state 8, `+0x58`) at 1. DC1 has no line break.
|
||||
- **Spawner**: the compiled `CheckItemGet` (0x1BDD40), `CheckWeaponRot` (0x1BDF90) and `GetItem` (0x1BE060) run on a
|
||||
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**: 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).
|
||||
- **Key finder**: after `CMonstorUnit::DrawMapSymbol` (0x1D7AA0, from DUN `MainDraw`), the live monster holding a
|
||||
gate key (`unit+i*400+0x1E470`; the floor's own key, `NowDngMap+0x464`, first) is located through its own virtual
|
||||
`GetPosition` and marked with the port's native `set2DSpriteC4` rectangle at the map's transform. No packet is built.
|
||||
|
||||
`dc_native_cheat_extras` checks each hook's decisions against recording stubs. A scripted dungeon run checked the
|
||||
page, map reveal, the key marker, level-up (Dagger ABS 27 → 32), spawning (two Fire), fast-forward (60 → 180 frames
|
||||
per second at 300%) and full HP with no damage taken. `DC_PROBE_CHEATS=1` logs applied level-ups and spawns.
|
||||
Fishing and the damage multiplier still need play-testing in a fishing spot and in combat.
|
||||
@@ -568,3 +568,73 @@ DC therefore retains its published, player-accepted 2278ba0 engine pin while
|
||||
the shared fixes land upstream. Its original cancellation regression is kept
|
||||
with that pin's contract. The newer engine upgrade remains deferred; merging
|
||||
the gameplay fixes and refreshed README does not enable the trial upgrade.
|
||||
|
||||
## Engine main and the loading-screen vsync callback (2026-11-08)
|
||||
|
||||
The frame-76 stall on engine main came from one changed binding. `init_now_loading` installs
|
||||
`VSyncCallBack_Load` through `MGInitVSyncCallBack`, and `wait_now_loading_vsync` then spins on
|
||||
`now_loading_vsync_end`, which only that vsync callback sets. `MGInit` registers `VSyncCallBack` with
|
||||
`sceGsSyncVCallback`. The previous pin had no native `sceGsSyncVCallback`, so the game's libgraph code ran:
|
||||
`AddIntcHandler(2, VSyncCallBack)` and `EnableIntc(2)`, fired by the kernel's field clock. Engine main
|
||||
answers `sceGsSyncVCallback` natively and queues the callback only in `Dispatcher::frameCompleted`, where a game
|
||||
frame ends (its `kernel.md` section 2). The loading wait ends no frame, so the callback never ran.
|
||||
|
||||
DC now registers its compiled `sceGsSyncVCallback` (`0x113DE8`) in the port registry, which takes precedence over
|
||||
the engine's native library at that external address. The callback is the vblank interrupt again, as on the
|
||||
previous pin. No engine change is involved. The CD-cancel regression asserts main's `sceCdBreak` contract: an
|
||||
active read ends at the current native time, and an idle drive's error is unchanged.
|
||||
|
||||
DC moves to BozoEngine main `296ac6d`. Qualification on this PC:
|
||||
|
||||
- **125/125** local suites including eight GPU checks, and the 14 release-tool tests.
|
||||
- Seven scripted routes on the new build and on a pin build carrying the same fix (`2278ba0`), each from identical
|
||||
copied cards: Matataki travel (9,000 frames), in-game Cheats ending in Quit Game, the outdoor water route, the
|
||||
companion menu, a main-menu route, a save route and a fresh-process reload. All end identically on both, with
|
||||
zero register/unknown accesses, native VU0 calls or GIF submissions. VIF1 operation counts differ by under 1%.
|
||||
- Captures match where the scene is the same, mostly under 1.5 mean levels. A separate save route on copied cards
|
||||
shows "Saving completed." on engine main; its written `darkcloud0` is byte-identical to the pin build's, and a
|
||||
fresh process lists and loads that save.
|
||||
- Two kinds of difference were examined, not dismissed. Some transitions finish a few frames later on engine
|
||||
main, so fade captures land at another point of the same fade. Windowed runs of the unchanged pin also move
|
||||
that fade from run to run. A dungeon floor entered by the save route starts Toan at another position on engine
|
||||
main, while two pin runs agree. `buildRandomMap` seeds each new floor from `rand()`, a sequence that other code
|
||||
also draws from and reseeds (`DrawFire`, villager placement). A different number of frames before the floor
|
||||
therefore gives another valid random floor. The seed itself was not dumped; the walk, menus and fades before
|
||||
the floor match.
|
||||
|
||||
Not covered by these routes: dungeon combat, the new-game opening, Georama and a human play session on the new
|
||||
engine. The released v0.1.0 keeps its `2278ba0` engine; this change applies to the next release.
|
||||
|
||||
## Texture change checks once per model draw (2026-11-08)
|
||||
|
||||
A human fullscreen run on engine main dropped to 36-42 FPS in a house interior after eleven minutes at 60.
|
||||
A four-second instruction-pointer sample of the running game put 265 of 455 game-thread samples in
|
||||
`contentHash`: the record-texture cache's change check, which hashes a record's texels and palette (whole
|
||||
pictures up to 256 KiB) on every lookup. The presentation thread was mostly waiting. This is the cost the
|
||||
"Dran's house frame rate" section reduced with XXH64, not an engine-main regression.
|
||||
|
||||
The model draw looked a record up once per primitive, and a model's primitives mostly share one picture. No game
|
||||
code runs between the primitives of one native draw, so their textures cannot change in between. `drawModel` now
|
||||
looks each record up once per draw and reuses the result for its other primitives. Lookups across draws still
|
||||
check every time: game code runs between them (character faces are rewritten between characters).
|
||||
|
||||
`DC_NATIVE_STATS=1` now also reports record-texture lookups and hashed bytes per frame, averaged over 300 frames.
|
||||
At the Matataki spot of the run's save: 480 lookups and 4.71 MiB hashed per frame before, 208 and 2.00 after; on
|
||||
the scripted Matataki route 1.84 MiB before, 1.01 after. The build passes 125/125 suites, and the seven scripted
|
||||
routes match the previous build (faces, HUD, menus, identical cards); the only differences are the known fade
|
||||
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.
|
||||
@@ -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
|
||||
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 168 KiB |
|
Before Width: | Height: | Size: 372 KiB |
|
Before Width: | Height: | Size: 242 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 109 KiB |
|
After Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 316 KiB |
|
Before Width: | Height: | Size: 314 KiB |
|
Before Width: | Height: | Size: 221 KiB |
|
Before Width: | Height: | Size: 153 KiB |
|
Before Width: | Height: | Size: 192 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 361 KiB |
|
Before Width: | Height: | Size: 339 KiB |
|
Before Width: | Height: | Size: 182 KiB |
|
Before Width: | Height: | Size: 214 KiB |
|
Before Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 189 KiB |
|
Before Width: | Height: | Size: 105 KiB |
|
Before Width: | Height: | Size: 355 KiB |
|
Before Width: | Height: | Size: 212 KiB |
|
Before Width: | Height: | Size: 296 KiB |
|
Before Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 123 KiB |
|
After Width: | Height: | Size: 107 KiB |
@@ -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)
|
||||
|
||||
@@ -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[] = {
|
||||
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
|
||||
@@ -16,6 +16,20 @@
|
||||
0x0012d574 0x0c0411a6 0x00000000 # retire console free-time percentage print
|
||||
# Native SDK submissions do not use the console channel's tag-transfer bit.
|
||||
# Remove those byte read/modify/write operations at their original callers.
|
||||
# main, at mode changes: four flush / sceDmaSend / sceGsSyncPath triples. Two upload VU1 microcode (0x296680,
|
||||
# 0x24f960) that nothing executes; the others send nothing a native consumer reads. v0 is reloaded after each.
|
||||
0x00141388 0x0c045168 0x00000000 # main: no FlushCache
|
||||
0x0014139c 0x0c0431be 0x00000000 # main: no sceDmaSend
|
||||
0x001413ac 0x0c044be6 0x00000000 # main: no sceGsSyncPath wait
|
||||
0x001413b8 0x0c045168 0x00000000 # main: no FlushCache
|
||||
0x001413cc 0x0c0431be 0x00000000 # main: no sceDmaSend
|
||||
0x001413dc 0x0c044be6 0x00000000 # main: no sceGsSyncPath wait
|
||||
0x001415e4 0x0c045168 0x00000000 # main: no FlushCache
|
||||
0x001415f8 0x0c0431be 0x00000000 # main: no VU1 microcode upload (0x296680)
|
||||
0x00141608 0x0c044be6 0x00000000 # main: no sceGsSyncPath wait
|
||||
0x00141614 0x0c045168 0x00000000 # main: no FlushCache
|
||||
0x00141628 0x0c0431be 0x00000000 # main: no VU1 microcode upload (0x24f960)
|
||||
0x00141638 0x0c044be6 0x00000000 # main: no sceGsSyncPath wait
|
||||
0x0014165c 0x90a40000 0x24040000 # main: channel byte read
|
||||
0x00141670 0xa0a20000 0x00000000 # main: channel byte store
|
||||
0x0012d43c 0x90a40000 0x24040000 # MGEndFrame: channel byte read
|
||||
@@ -56,9 +70,22 @@
|
||||
# Retain frame pacing, native visibility and the later native completion callback.
|
||||
0x0012d1dc 0x8f848bd4 0x0804b49a # continue directly at native visibility 0x12d268
|
||||
0x0012d1e0 0x70002e28 0x70002e28 # guard retained delay slot: a1 = 0 (caller-volatile)
|
||||
# The retained SDK send acknowledges completed native work; it reads no packet.
|
||||
0x0012d680 0x8f828bd4 0x00000000 # no packet-object lookup before completion
|
||||
0x0012d688 0x8c450004 0x24050000 # pass no packet/source pointer; retain channel/IRQ semantics
|
||||
# The per-frame transfer tail. The game installs no DMA-completion handler (its only AddDmacHandler is in
|
||||
# sceSifInitCmd, answered natively), so nothing consumes a VIF1 completion; the GIF channel it waits on
|
||||
# never carries a transfer. The frame counter, the channel lookup and the buffer toggle stay.
|
||||
# MGEndFrame's display-buffer swap. sceGsSetHalfOffset only rewrites the draw record's XYOFFSET image, which the
|
||||
# native renderer never reads; sceGsSwapDBuff only passes the records to sceGsPutDispEnv / sceGsPutDrawEnv, which
|
||||
# are no-ops natively. The buffer index toggle below stays.
|
||||
0x0012d5e8 0x0c044f92 0x00000000 # no sceGsSetHalfOffset
|
||||
0x0012d5f4 0x0c045168 0x00000000 # no FlushCache
|
||||
0x0012d608 0x0c044ba8 0x00000000 # no sceGsSwapDBuff
|
||||
0x0012d61c 0x0c043316 0x00000000 # no sceDmaSync of the (always idle) GIF channel
|
||||
0x0012d64c 0x0c0430ea 0x00000000 # no sceDmaGetChan(1): MGInit already stored the same VIF1 handle
|
||||
0x0012d654 0xaf828bc8 0x00000000 # ... so v0 (here the frame counter) is not stored over it
|
||||
0x0012d680 0x8f828bd4 0x00000000 # no packet-object lookup
|
||||
0x0012d688 0x8c450004 0x24050000 # no packet/source pointer
|
||||
0x0012d678 0x0c045168 0x00000000 # no FlushCache before a transfer
|
||||
0x0012d68c 0x0c0431be 0x00000000 # no sceDmaSend: nothing to transfer, nothing waiting on its completion
|
||||
# CVisualMDTVu1 raw draw: retain selected buffer metadata, temporary allocation
|
||||
# extent, all native draw arguments/results, and the post-draw buffer restore.
|
||||
# Its native draw reads MDT assets, so copying console VIF output is unused.
|
||||
@@ -80,6 +107,12 @@
|
||||
0x00154664 0x3c0201d0 0x080551a2 # skip packet End/Terminate to cache call 0x154688
|
||||
0x00154668 0x2444b370 0x00000000 # no unused packet pointer in delay slot
|
||||
0x0015469c 0x8c25b374 0x24050000 # completion has no packet source
|
||||
# Loading callback, every vblank while loading: the same transfer tail as MGEndFrame. No DMA-completion handler
|
||||
# exists and no transfer is ever outstanding, so nothing waits, flushes or sends.
|
||||
0x00154380 0x0c043316 0x00000000 # no sceDmaSync of VIF1
|
||||
0x0015468c 0x0c045174 0x00000000 # no iFlushCache before a transfer
|
||||
0x001546a0 0x0c0431be 0x00000000 # no sceDmaSend of VIF1
|
||||
0x0015474c 0x0c043316 0x00000000 # no sceDmaSync of GIF
|
||||
0x001546c4 0x8f828bc0 0x080551cb # skip half-offset/display/cache setup to buffer toggle 0x15472c
|
||||
0x001546c8 0x10400005 0x00000000 # discard obsolete environment-selection branch
|
||||
# TexAnime: native texture copies require no leading/trailing TEXFLUSH packets.
|
||||
@@ -350,3 +383,63 @@
|
||||
0x00223760 0x8f848bd4 0x24040000 # null packet argument; DrawNewFileTemplete__Fiii
|
||||
0x002237f0 0x8f848bd4 0x24040000 # null packet argument; DrawNewFileTemplete__Fiii
|
||||
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)
|
||||
@@ -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
|
||||
@@ -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" } } }
|
||||
}
|
||||
@@ -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
|
||||
@@ -7,15 +7,23 @@
|
||||
#include <atomic>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <iterator>
|
||||
#include <bit>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace dc::cheats
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::array<std::atomic<bool>, 5> options{};
|
||||
std::array<std::atomic<bool>, 11> options{};
|
||||
std::atomic<int> damageRate{1};
|
||||
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};
|
||||
@@ -27,6 +35,38 @@ namespace dc::cheats
|
||||
bozo::port::InstructionHandler priorInstruction=nullptr;
|
||||
RecompiledFunction moveCheck=nullptr,sky=nullptr,light=nullptr;
|
||||
constexpr uint32_t kMoveCheck=0x14A680u,kSky=0x187F90u,kLight=0x188D50u,kAbsGain=0x1DF2A0u;
|
||||
// Fishing (town only): every fish decision is rand_check(p) (0x240050, one rand() per call); a hooked fish
|
||||
// escapes only when its action timer (+0x58) runs out in state 8 (+0x50). DC1 has no line break.
|
||||
RecompiledFunction randCheck=nullptr,fishStep=nullptr;
|
||||
constexpr uint32_t kRandCheck=0x240050u,kFishStep=0x240480u;
|
||||
constexpr uint32_t kLeaveFood=0x2403FCu,kLeaveHook=0x24044Cu; // rand_check's return addresses in LeaveFood/LeaveHook
|
||||
// Dungeon floor maps: the two CDungeonMap objects of DUN's .bss (main floor, sub-map), each with a 20 x 20
|
||||
// explored grid (+0x8710, ints, index x + z * 20), 16 room-visited flags (+0x8) and the cell table (+0x9C50,
|
||||
// 16-byte records, part -1: no floor). FlushCheckMask clears them as a floor is built; checkMask marks them as
|
||||
// the player walks; only DrawMiniMap reads them (not saved).
|
||||
RecompiledFunction checkMask=nullptr,flushMask=nullptr;
|
||||
constexpr uint32_t kCheckMask=0x1C39C0u,kFlushMask=0x1C3C00u,kDunResident=0x1DB7450u;
|
||||
constexpr uint32_t kMapMain=0x01DC4BE0u,kMapSub=0x01DD56F0u;
|
||||
// Calling compiled game routines from a hook: GetWeaponMaxExp, CheckItemGet, CheckWeaponRot, GetItem.
|
||||
RecompiledFunction maxExp=nullptr,checkItemGet=nullptr,checkWeaponRot=nullptr,getItem=nullptr;
|
||||
constexpr uint32_t kMaxExp=0x232080u,kCheckItemGet=0x1BDD40u,kCheckWeaponRot=0x1BDF90u,kGetItem=0x1BE060u;
|
||||
constexpr uint32_t kReturnSentinel=0x00080000u; // not code: a routine's jr ra lands here
|
||||
std::atomic<bool> pendingLevel{false};
|
||||
std::atomic<uint32_t> pendingSpawn{0}; // id | count << 16
|
||||
std::mutex spawnMutex;
|
||||
std::vector<SpawnItem> spawnList;
|
||||
bool spawnListBuilt=false;
|
||||
// Combat: every player attack (melee, shots, magic, bombs, thrown items) reaches a monster's HP at one
|
||||
// instruction of CMonstorUnit::CheckDmg, 0x1DC3F4 subu v0,v0,s4 (v0 HP, s4 the final damage, s5 the unit).
|
||||
// The player is hit only where DUN's BtCheckDamageProc asks CheckHitUser (0x1B5920; returns to 0x1DBB0E0).
|
||||
constexpr uint32_t kMonsterHp=0x1DC3F4u,kCheckHitUser=0x1B5920u,kHitUserReturn=0x1DBB0E0u;
|
||||
RecompiledFunction checkHitUser=nullptr;
|
||||
// Key finder: SetKey gives a floor's key to one live monster (unit = gp-0x6320, 16 slots of 400 bytes: state
|
||||
// +0x1E3D0 (-1 none), HP +0x1E3F4, item +0x1E470 (s16, -1 none)). DUN MainDraw calls DrawMapSymbol (0x1D7AA0,
|
||||
// returning to 0x1DB0348) to put monster icons on the map; the marker is drawn after it.
|
||||
constexpr uint32_t kMapSymbols=0x1D7AA0u,kMapSymbolsReturn=0x1DB0348u,kColourRect=0x15E120u;
|
||||
RecompiledFunction mapSymbols=nullptr,colourRect=nullptr;
|
||||
uint32_t markerBlink=0;
|
||||
RecompiledFunction addLife = nullptr, setLife = nullptr, addDrink = nullptr, step = nullptr, wear = nullptr;
|
||||
constexpr uint32_t kAddLife = 0x001BE710u, kSetLife = 0x001BE900u, kAddDrink = 0x001BE510u,
|
||||
kStep = 0x001BEA50u, kWear = 0x001B5D90u;
|
||||
@@ -60,6 +100,9 @@ namespace dc::cheats
|
||||
return read<int16_t>(ram,record)>0 ? record : 0;
|
||||
}
|
||||
void weaponAttack(uint8_t *ram,uint32_t status);
|
||||
void levelUp(uint8_t *ram,uint32_t s,const R5900Context *ctx,Runtime *rt);
|
||||
void spawn(uint8_t *ram,uint32_t s,const R5900Context *ctx,Runtime *rt);
|
||||
void buildSpawnList(const uint8_t *ram);
|
||||
// GetItem and GetNowItemNum count active quantities as bag occupancy.
|
||||
// The backing array has 103 entries; ordinary capacity is at most 100.
|
||||
int occupied(const uint8_t *ram,uint32_t s,int excludedSlot=-1)
|
||||
@@ -94,7 +137,7 @@ namespace dc::cheats
|
||||
for(int i=0;i<3;++i){const auto a=item(ram,s,i);currentItems[i].store(
|
||||
a.id<0?0:uint64_t(a.id)|(uint64_t(a.quantity)<<16)|(uint64_t(a.maximum)<<32),std::memory_order_relaxed);}
|
||||
}
|
||||
void editPlayer(uint8_t *ram,uint32_t s)
|
||||
void editPlayer(uint8_t *ram,uint32_t s,const R5900Context *ctx=nullptr,Runtime *rt=nullptr)
|
||||
{
|
||||
const int size=pendingSize.exchange(-1,std::memory_order_relaxed);
|
||||
const int gold=pendingGilda.exchange(-1,std::memory_order_relaxed);
|
||||
@@ -104,15 +147,147 @@ namespace dc::cheats
|
||||
if(request && a.id==int(request&65535) && a.maximum>0)
|
||||
write<int16_t>(ram,s+0x4368+i*2,static_cast<int16_t>(std::clamp(int(request>>16),1,a.maximum)));}
|
||||
weaponAttack(ram,s);
|
||||
if(s){levelUp(ram,s,ctx,rt);spawn(ram,s,ctx,rt);buildSpawnList(ram);}
|
||||
publishPlayer(ram,s);
|
||||
}
|
||||
// Runs a compiled routine on a copy of the hook's context (its own frame below the current stack, its return to
|
||||
// a sentinel). -1 when it did not return there (a routine that blocks or switches threads is never called so).
|
||||
bool callGameDone(RecompiledFunction routine,uint8_t *ram,const R5900Context *ctx,Runtime *rt,
|
||||
std::initializer_list<uint32_t> args,int32_t *result=nullptr)
|
||||
{
|
||||
if(!routine || !ctx || !rt)return false;
|
||||
R5900Context call=*ctx;
|
||||
int reg=4;
|
||||
for(const uint32_t a:args)call.r[reg++].ud[0]=uint64_t(int64_t(int32_t(a)));
|
||||
call.r[31].ud[0]=kReturnSentinel;
|
||||
call.leaving=false;
|
||||
routine(ram,&call,rt);
|
||||
if(call.pc!=kReturnSentinel || call.leaving)return false;
|
||||
if(result)*result=getRegS32(&call,2);
|
||||
return true;
|
||||
}
|
||||
int32_t callGame(RecompiledFunction routine,uint8_t *ram,const R5900Context *ctx,Runtime *rt,
|
||||
std::initializer_list<uint32_t> args)
|
||||
{
|
||||
int32_t result=-1;
|
||||
return callGameDone(routine,ram,ctx,rt,args,&result)?result:-1;
|
||||
}
|
||||
// DC_PROBE_CHEATS=1: the one-shot edits that call game routines, as they are applied.
|
||||
bool probe(){static const bool on=std::getenv("DC_PROBE_CHEATS")!=nullptr;return on;}
|
||||
bool defaultWeapon(int id){return id==0x101 || id==0x12B || id==0x13A || id==0x14B || id==0x15B || id==0x16B;}
|
||||
void levelUp(uint8_t *ram,uint32_t s,const R5900Context *ctx,Runtime *rt)
|
||||
{
|
||||
if(!rt || !pendingLevel.exchange(false,std::memory_order_relaxed))return;
|
||||
const uint32_t w=equippedWeapon(ram,s);
|
||||
if(!w)return;
|
||||
const int id=read<int16_t>(ram,w),level=read<int16_t>(ram,w+2);
|
||||
// The game's own refusals: default weapons earn no ABS, the Serpent Sword waits for a story flag, 99 is
|
||||
// the last level.
|
||||
if(defaultWeapon(id) || id==0x10C || level>=99)return;
|
||||
const int32_t needed=callGame(maxExp,ram,ctx,rt,{w});
|
||||
const int before=read<int16_t>(ram,w+0x14);
|
||||
if(needed>0 && needed<=999 && before<needed)write<int16_t>(ram,w+0x14,int16_t(needed));
|
||||
if(probe())std::fprintf(stderr,"[dc:cheats] level-up: weapon 0x%x level %d ABS %d -> %d (needed %d)\n",id,level,before,
|
||||
read<int16_t>(ram,w+0x14),needed);
|
||||
}
|
||||
// The game's text: 16-bit codes (0xFD21.. 'A'.., 0xFD3B.. 'a'.., 0xFD6F.. '0'.., 0xFF02 space, 0xFF01 end).
|
||||
std::string gameText(const uint8_t *ram,int key)
|
||||
{
|
||||
const uint32_t buffer=read<uint32_t>(ram,0x2A2528u)&0x1FFFFFFu; // SystemMes, resident all session
|
||||
if(!buffer || buffer>0x1F00000u)return {};
|
||||
const int count=read<int16_t>(ram,buffer);
|
||||
if(count<=0 || count>4000)return {};
|
||||
for(int i=0;i<count;++i)
|
||||
{
|
||||
if(read<int16_t>(ram,buffer+4+4*uint32_t(i))!=key)continue;
|
||||
uint32_t at=buffer+2*uint32_t(count+read<int16_t>(ram,buffer+6+4*uint32_t(i))+1);
|
||||
std::string text;
|
||||
for(int n=0;n<40 && at<0x1FFFFFEu;++n,at+=2)
|
||||
{
|
||||
const uint16_t c=read<uint16_t>(ram,at);
|
||||
if(c==0xFF01)break;
|
||||
if(c>=0xFD21 && c<=0xFD3A)text+=char('A'+c-0xFD21);
|
||||
else if(c>=0xFD3B && c<=0xFD54)text+=char('a'+c-0xFD3B);
|
||||
else if(c>=0xFD6F && c<=0xFD78)text+=char('0'+c-0xFD6F);
|
||||
else if(c==0xFF02)text+=' ';
|
||||
else if(c==0xFD55)text+='\'';
|
||||
else if(c==0xFD5D)text+='-';
|
||||
else if(c==0xFD6D)text+='.';
|
||||
else if(c==0xFD5B)text+='&';
|
||||
else if(c==0xFD61)text+='(';
|
||||
else if(c==0xFD62)text+=')';
|
||||
else return {}; // an argument or a mark: not a plain item name
|
||||
}
|
||||
return text;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
// What the spawner offers: no event/key/story item (they satisfy doors and NPCs out of order), no default or
|
||||
// story weapon, no unused ID.
|
||||
bool spawnable(int id)
|
||||
{
|
||||
if(id>=0x84 && id<=0x100)
|
||||
return (id<=0x8D) || (id>=0x91 && id<=0x9B) || (id>=0x9F && id<=0xB7) || (id>=0xBA && id<=0xC1) ||
|
||||
id==0xC5 || id==0xC7 || (id>=0xF5 && id<=0xF7);
|
||||
if(id>=0x51 && id<=0x83)
|
||||
return (id<=0x55) || (id>=0x5B && id<=0x6B) || (id>=0x6F && id<=0x78);
|
||||
if(id>=0x102 && id<=0x177)
|
||||
{
|
||||
constexpr int excluded[]={0x10B,0x10C,0x115,0x116,0x117,0x118,0x129,0x12A,0x12B,0x13A,0x146,0x14A,0x14B,
|
||||
0x156,0x15A,0x15B,0x166,0x169,0x16A,0x16B};
|
||||
return std::find(std::begin(excluded),std::end(excluded),id)==std::end(excluded);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
void buildSpawnList(const uint8_t *ram)
|
||||
{
|
||||
if(spawnListBuilt)return;
|
||||
std::vector<SpawnItem> list;
|
||||
for(int id=0x51;id<=0x177;++id)
|
||||
{
|
||||
if(!spawnable(id))continue;
|
||||
// System message id + 100: a bag item's or an attachment's number is its id; a weapon's is ComItemInfo's
|
||||
// (8-byte entries indexed id - 0x51, the number at +6; 0 = unused).
|
||||
const int number=id<=0x100 ? id : read<int16_t>(ram,0x27DE50u+uint32_t(id-0x51)*8+6);
|
||||
if(number<=0)continue;
|
||||
const int key=number+100;
|
||||
const std::string name=gameText(ram,key);
|
||||
if(name.empty())continue;
|
||||
SpawnItem item;item.id=id;std::snprintf(item.name,sizeof(item.name),"%s",name.c_str());
|
||||
list.push_back(item);
|
||||
}
|
||||
if(list.empty())return; // the messages are not loaded yet
|
||||
std::lock_guard lock(spawnMutex);
|
||||
spawnList=std::move(list);spawnListBuilt=true;
|
||||
}
|
||||
void spawn(uint8_t *ram,uint32_t s,const R5900Context *ctx,Runtime *rt)
|
||||
{
|
||||
if(!rt)return;
|
||||
const uint32_t request=pendingSpawn.exchange(0,std::memory_order_relaxed);
|
||||
const int id=int(request&0xFFFF),count=std::clamp(int(request>>16),1,10);
|
||||
if(!request || !validStatus(s) || !spawnable(id))return;
|
||||
int given=0;
|
||||
for(int n=0;n<count;++n,++given)
|
||||
{
|
||||
if(id>=0x101)
|
||||
{
|
||||
// A weapon goes to its owner, who must have joined (+5: party size), with room left in slots 0..9.
|
||||
const int owner=read<int8_t>(ram,0x275A7Eu+uint32_t(id)*0x4C);
|
||||
if(owner<0 || owner>=read<int8_t>(ram,s+5) || callGame(checkWeaponRot,ram,ctx,rt,{s,uint32_t(id)})>=9)break;
|
||||
}
|
||||
else if(callGame(checkItemGet,ram,ctx,rt,{s,uint32_t(id)})!=0)break; // bag or attachments full
|
||||
// a2 = 1: a stat sphere (0x5B..0x5E) gives its +1 bonus, as when one is found.
|
||||
if(callGame(getItem,ram,ctx,rt,{s,uint32_t(id),1u})<0)break;
|
||||
}
|
||||
if(probe())std::fprintf(stderr,"[dc:cheats] spawn: item 0x%x, %d of %d given\n",id,given,count);
|
||||
}
|
||||
void moveHook(uint8_t *ram,R5900Context *ctx,Runtime *rt)
|
||||
{
|
||||
const uint32_t caller=getRegU32(ctx,31);
|
||||
const bool town=caller==0x16A9C0u;
|
||||
const bool dungeon=(caller==0x1DB39F4u || caller==0x1DB3EA0u || caller==0x1DB5C10u) && rt->functions.generated(0x1DB7450u);
|
||||
if(town || dungeon){
|
||||
editPlayer(ram,playerStatus(ram,ctx));
|
||||
editPlayer(ram,playerStatus(ram,ctx),ctx,rt);
|
||||
const int rate=movementPercent();
|
||||
const int64_t p=bozo::GuestMemory::flatOffset(getRegU32(ctx,5),12);
|
||||
if(rate!=100 && p>0 && p<=bozo::kFlatScratchpadOffset-12){
|
||||
@@ -134,6 +309,99 @@ namespace dc::cheats
|
||||
if(!haveHeldTime && std::isfinite(time) && time>=0 && time<=12){heldTime=time;haveHeldTime=true;}
|
||||
if(haveHeldTime)ctx->fu[12]=std::bit_cast<uint32_t>(heldTime);
|
||||
}
|
||||
void randCheckHook(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
{
|
||||
// A fish near the bait never decides to leave it: p = 0 for the two Leave rolls only. The call still draws
|
||||
// its rand(), so the shared sequence advances as it would; the Find/Eat/Bite odds (bait affinity) stay.
|
||||
const uint32_t from=getRegU32(c,31);
|
||||
if(enabled(Cheat::FishingHelper) && (from==kLeaveFood || from==kLeaveHook))c->fu[12]=0;
|
||||
randCheck(r,c,rt);
|
||||
}
|
||||
void fishStepHook(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
{
|
||||
// A hooked fish (state 8) stays hooked until the button is pressed: its timer never runs out.
|
||||
const int64_t fish=bozo::GuestMemory::flatOffset(getRegU32(c,4),0x60);
|
||||
if(enabled(Cheat::FishingHelper) && fish>=0 && fish<=bozo::kFlatScratchpadOffset-0x60 &&
|
||||
read<int32_t>(r,uint32_t(fish)+0x50)==8 && read<int32_t>(r,uint32_t(fish)+0x58)<1)
|
||||
write<int32_t>(r,uint32_t(fish)+0x58,1);
|
||||
fishStep(r,c,rt);
|
||||
}
|
||||
void revealFloor(uint8_t *r,uint32_t map)
|
||||
{
|
||||
if(map!=kMapMain && map!=kMapSub)return;
|
||||
// Every cell with floor, except column x = 19: SetUnderLoad fills it, but no floor reaches it.
|
||||
for(uint32_t i=0;i<400;++i)
|
||||
if(i%20!=19 && read<int32_t>(r,map+0x9C50+i*16)!=-1)write<int32_t>(r,map+0x8710+i*4,1);
|
||||
const int rooms=std::clamp(read<int32_t>(r,map+0xB650),0,16);
|
||||
for(int i=0;i<rooms;++i)
|
||||
if(read<int32_t>(r,map+0xB558+i*16)!=0)write<int32_t>(r,map+0x8+i*4,1);
|
||||
}
|
||||
void flushMaskHook(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
{
|
||||
// On arrival: after the floor build clears the grid (the three DUN floor-build call sites only).
|
||||
const uint32_t from=getRegU32(c,31),map=getRegU32(c,4);
|
||||
flushMask(r,c,rt);
|
||||
if(enabled(Cheat::RevealFloorMap) && !c->leaving && c->pc==from &&
|
||||
(from==0x1DB8A1Cu || from==0x1DB913Cu || from==0x1DB91FCu) && rt->functions.generated(kDunResident))
|
||||
revealFloor(r,map);
|
||||
}
|
||||
void checkMaskHook(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
{
|
||||
// Switched on mid-floor: at MoveChara's next walking update (it only ever adds explored cells).
|
||||
if(enabled(Cheat::RevealFloorMap) && getRegU32(c,31)==0x1DB159Cu && rt->functions.generated(kDunResident))
|
||||
revealFloor(r,getRegU32(c,4));
|
||||
checkMask(r,c,rt);
|
||||
}
|
||||
void checkHitUserHook(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
{
|
||||
// No damage taken: the hit test answers "no hit" (-1) to the player's hit routine, before its damage,
|
||||
// knock-down, status and theft effects.
|
||||
if(enabled(Cheat::NoDamageTaken) && getRegU32(c,31)==kHitUserReturn && rt->functions.generated(kDunResident))
|
||||
{setReturnS32(c,-1);c->pc=getRegU32(c,31);return;}
|
||||
checkHitUser(r,c,rt);
|
||||
}
|
||||
bool gateKey(int item){return item==0xC3 || item==0xC4 || item==0xC6 || (item>=0xC9 && item<=0xCE);}
|
||||
void mapSymbolsHook(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
{
|
||||
const uint32_t from=getRegU32(c,31);
|
||||
mapSymbols(r,c,rt);
|
||||
if(!enabled(Cheat::KeyFinder) || from!=kMapSymbolsReturn || c->pc!=from || !rt->functions.generated(kDunResident) ||
|
||||
!colourRect)return;
|
||||
const uint32_t gp=getRegU32(c,28),unit=read<uint32_t>(r,(gp-0x6320u)&0x1FFFFFFu)&0x1FFFFFFu;
|
||||
const uint32_t map=read<uint32_t>(r,(gp-0x6338u)&0x1FFFFFFu)&0x1FFFFFFu;
|
||||
if(!unit || unit>0x1F00000u)return;
|
||||
const int wanted=map && map<0x1F00000u ? read<int32_t>(r,map+0x464) : -1;
|
||||
int holder=-1;
|
||||
for(int i=0;i<16;++i){
|
||||
const uint32_t slot=unit+uint32_t(i)*400;
|
||||
const int item=read<int16_t>(r,slot+0x1E470);
|
||||
if(read<int32_t>(r,slot+0x1E3D0)==-1 || read<int32_t>(r,slot+0x1E3F4)<=0 || !gateKey(item))continue;
|
||||
if(holder<0 || item==wanted)holder=i; // dungeon 1 places three keys: the floor's own wins
|
||||
}
|
||||
if(holder<0)return;
|
||||
// Scratch guest memory below the stack, as the routine's own frame would use: position, rectangles.
|
||||
const uint32_t scratch=(getRegU32(c,29)-0x200u)&~15u;
|
||||
const uint32_t character=unit+uint32_t(holder)*0x3510+0x1FCD0u;
|
||||
// Its position through its own virtual GetPosition (vtable at +0xA0, slot +0xA0), as DrawMapSymbol asks.
|
||||
const uint32_t table=read<uint32_t>(r,(character+0xA0)&0x1FFFFFFu)&0x1FFFFFFu;
|
||||
const uint32_t getPosition=table?read<uint32_t>(r,(table+0xA0)&0x1FFFFFFu):0u;
|
||||
RecompiledFunction locate=rt->functions.override(getPosition);if(!locate)locate=rt->functions.generated(getPosition);
|
||||
if(!locate || !callGameDone(locate,r,c,rt,{character,scratch}))return;
|
||||
const float scale=read<float>(r,(gp-0x7F80u)&0x1FFFFFFu),x=read<float>(r,scratch),z=read<float>(r,scratch+8);
|
||||
if(!std::isfinite(x) || !std::isfinite(z) || !std::isfinite(scale))return;
|
||||
// A solid gold square, 10 x 10 around the holder's 8 x 8 icon position, blinking: drawn by the port's native
|
||||
// colour-rectangle routine (set2DSpriteC4), like the game's own map rectangles.
|
||||
const int32_t rect[4]={int32_t(scale*x)+384-1,int32_t(scale*z)+68-1,10,10};
|
||||
// spRGBA: the bytes R, G, B, A (255, 200, 32), alpha 0x80 = 1.0 then 0: blinking.
|
||||
const uint32_t gold=((++markerBlink/15)%2?0x80u:0x00u)<<24|0x0020C8FFu; // on and off: unlike the static exit tile
|
||||
std::memcpy(r+scratch+0x20,rect,16);
|
||||
for(uint32_t k=0;k<4;++k)write<uint32_t>(r,scratch+0x30+k*4,gold);
|
||||
R5900Context draw=*c;
|
||||
draw.r[4].ud[0]=0;draw.r[5].ud[0]=scratch+0x20;
|
||||
for(int k=0;k<4;++k)draw.r[6+k].ud[0]=scratch+0x30+uint32_t(k)*4;
|
||||
draw.r[31].ud[0]=kReturnSentinel;draw.pc=kColourRect;
|
||||
colourRect(r,&draw,rt);
|
||||
}
|
||||
void skyHook(uint8_t *r,R5900Context *c,Runtime *rt){timeInput(c);sky(r,c,rt);}
|
||||
void lightHook(uint8_t *r,R5900Context *c,Runtime *rt){timeInput(c);light(r,c,rt);}
|
||||
bool instruction(uint8_t *r,R5900Context *c,Runtime *rt,uint32_t pc)
|
||||
@@ -148,6 +416,18 @@ namespace dc::cheats
|
||||
c->r[7].ud[0]=uint64_t(std::min(int64_t(reward)*rate,int64_t(32767)));
|
||||
return false; // execute the original lh v1,0x14(s3)
|
||||
}
|
||||
if(pc==kMonsterHp){
|
||||
// Scales the final damage just before the original subtraction; immunities (0 damage) stay. Capped at
|
||||
// the HP left (or the original damage, if higher), so the damage number stays the game's own range.
|
||||
const int64_t damage=getRegS32(c,20),hp=getRegS32(c,2);
|
||||
if(damage>0){
|
||||
int64_t scaled=damage;
|
||||
if(enabled(Cheat::OneHitKills))scaled=std::max(damage,hp);
|
||||
else if(damageMultiplier()>1)scaled=std::min(damage*damageMultiplier(),std::max(damage,hp));
|
||||
c->r[20].ud[0]=uint64_t(scaled);
|
||||
}
|
||||
return false; // execute the original subu v0,v0,s4
|
||||
}
|
||||
return priorInstruction && priorInstruction(r,c,rt,pc);
|
||||
}
|
||||
void weaponAttack(uint8_t *ram,uint32_t status)
|
||||
@@ -236,7 +516,7 @@ namespace dc::cheats
|
||||
// The weapon menu ticks a preview copy of CUserStatus. Queue edits
|
||||
// until the real player is ticking again, rather than consuming
|
||||
// the request on a temporary preview/inventory allocation.
|
||||
if (!player || player==status) editPlayer(ram,player);
|
||||
if (!player || player==status) editPlayer(ram,player,ctx,runtime);
|
||||
else
|
||||
{
|
||||
const uint32_t weapon=equippedWeapon(ram,player);
|
||||
@@ -275,6 +555,11 @@ namespace dc::cheats
|
||||
void requestWeaponAttack(int value) { pendingAttack.store(std::clamp(value,0,999),std::memory_order_relaxed); }
|
||||
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(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);}
|
||||
void setMovementPercent(int v){moveRate.store(std::clamp(v,50,200),std::memory_order_relaxed);}
|
||||
int gilda(){return currentGilda.load(std::memory_order_relaxed);}
|
||||
@@ -290,7 +575,11 @@ namespace dc::cheats
|
||||
const auto a=activeConsumable(slot);if(a.id<0 || a.maximum<1)return;
|
||||
pendingItems[slot].store(uint64_t(a.id)|(uint64_t(std::clamp(quantity,1,a.maximum))<<16),std::memory_order_relaxed);
|
||||
}
|
||||
void refreshPlayer(const uint8_t *r,const R5900Context *c){publishPlayer(r,playerStatus(r,c));}
|
||||
void requestWeaponLevelUp(){pendingLevel.store(true,std::memory_order_relaxed);}
|
||||
int spawnItemCount(){std::lock_guard lock(spawnMutex);return int(spawnList.size());}
|
||||
SpawnItem spawnItem(int index){std::lock_guard lock(spawnMutex);return index>=0 && index<int(spawnList.size())?spawnList[size_t(index)]:SpawnItem{};}
|
||||
void requestSpawn(int id,int count){if(spawnable(id))pendingSpawn.store(uint32_t(id)|uint32_t(std::clamp(count,1,10))<<16,std::memory_order_relaxed);}
|
||||
void refreshPlayer(const uint8_t *r,const R5900Context *c){publishPlayer(r,playerStatus(r,c));buildSpawnList(r);}
|
||||
void applyPlayerEdits(uint8_t *r,const R5900Context *c){editPlayer(r,playerStatus(r,c));}
|
||||
void install(Runtime &runtime, bozo::port::Registry ®istry)
|
||||
{
|
||||
@@ -307,6 +596,29 @@ namespace dc::cheats
|
||||
if(moveCheck)registry.registerFunction(kMoveCheck,moveHook);
|
||||
if(sky)registry.registerFunction(kSky,skyHook);
|
||||
if(light)registry.registerFunction(kLight,lightHook);
|
||||
randCheck=runtime.functions.generated(kRandCheck);fishStep=runtime.functions.generated(kFishStep);
|
||||
if(randCheck)registry.registerFunction(kRandCheck,randCheckHook);
|
||||
if(fishStep)registry.registerFunction(kFishStep,fishStepHook);
|
||||
checkMask=runtime.functions.generated(kCheckMask);flushMask=runtime.functions.generated(kFlushMask);
|
||||
if(checkMask)registry.registerFunction(kCheckMask,checkMaskHook);
|
||||
if(flushMask)registry.registerFunction(kFlushMask,flushMaskHook);
|
||||
maxExp=runtime.functions.generated(kMaxExp);checkItemGet=runtime.functions.generated(kCheckItemGet);
|
||||
checkWeaponRot=runtime.functions.generated(kCheckWeaponRot);getItem=runtime.functions.generated(kGetItem);
|
||||
checkHitUser=runtime.functions.generated(kCheckHitUser);
|
||||
if(checkHitUser)registry.registerFunction(kCheckHitUser,checkHitUserHook);
|
||||
mapSymbols=registry.find(kMapSymbols);if(!mapSymbols)mapSymbols=runtime.functions.generated(kMapSymbols);
|
||||
colourRect=registry.find(kColourRect); // the port's native rectangle drawing (dc_native), installed first
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -8,13 +8,21 @@ namespace bozo::port { class Registry; }
|
||||
|
||||
namespace dc::cheats
|
||||
{
|
||||
enum class Cheat { InfiniteHealth, InfiniteWeaponDurability, InfiniteThirst, InfiniteStamina, FreezeTimeOfDay };
|
||||
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 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); // 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();
|
||||
void setAbsMultiplier(int value); // 1..16, positive combat rewards only
|
||||
int damageMultiplier();
|
||||
void setDamageMultiplier(int value); // 1..16, damage the party deals to monsters
|
||||
int movementPercent();
|
||||
void setMovementPercent(int value); // 50..200, horizontal movement before collision
|
||||
int gilda();
|
||||
@@ -25,10 +33,22 @@ namespace dc::cheats
|
||||
struct Consumable { int id=-1, quantity=0, maximum=0; };
|
||||
Consumable activeConsumable(int slot);
|
||||
void requestConsumableQuantity(int slot,int quantity);
|
||||
// Weapon level-up: fills the equipped weapon's ABS to the game's own threshold (GetWeaponMaxExp); the player then
|
||||
// levels it up in the weapon menu as usual. Refused for default weapons, the Serpent Sword and level 99.
|
||||
void requestWeaponLevelUp();
|
||||
// Item spawner: the bag items, attachments and weapons the game's GetItem may give without touching story
|
||||
// progress (event/key items, default and story weapons, unused IDs excluded), with their names read from the
|
||||
// game's resident system messages. Empty until the game has loaded them.
|
||||
struct SpawnItem { int id = 0; char name[32] = {}; };
|
||||
int spawnItemCount();
|
||||
SpawnItem spawnItem(int index);
|
||||
void requestSpawn(int id, int count); // count 1..10; stops at the first refusal (bag/attachment/weapon full)
|
||||
// Authoritative player state only. Called on the game thread at Options
|
||||
// entry/exit and gameplay updates, never against inventory preview copies.
|
||||
void refreshPlayer(const uint8_t *ram,const R5900Context *ctx);
|
||||
void applyPlayerEdits(uint8_t *ram,const R5900Context *ctx);
|
||||
void install(Runtime &runtime, bozo::port::Registry ®istry);
|
||||
void registerMenu();
|
||||
// Save states: after a load, the mirrors of game values and the queued edits are dropped.
|
||||
void stateLoaded();
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "dc_cheats.h"
|
||||
#include "dc_warp.h"
|
||||
#include "bozo/app/settings_tabs.h"
|
||||
#include "imgui.h"
|
||||
#include <algorithm>
|
||||
@@ -32,6 +33,10 @@ namespace dc::cheats
|
||||
ImGui::TextWrapped("Applies when gameplay resumes. The edited ATK is included when you save your game.");
|
||||
ImGui::Separator();
|
||||
int abs=absMultiplier();if(ImGui::SliderInt("Weapon ABS multiplier",&abs,1,16,"%dx"))setAbsMultiplier(abs);
|
||||
int damage=damageMultiplier();if(ImGui::SliderInt("Damage multiplier",&damage,1,16,"%dx"))setDamageMultiplier(damage);
|
||||
toggle("One-hit kills", Cheat::OneHitKills, "Any hit that deals damage defeats the monster; immunities still apply.");
|
||||
toggle("No damage taken", Cheat::NoDamageTaken, "Monster attacks never land: no damage, knock-down or theft.");
|
||||
toggle("Key finder", Cheat::KeyFinder, "The monster carrying the floor's key blinks gold on the map.");
|
||||
int speed=movementPercent();if(ImGui::SliderInt("Movement speed",&speed,50,200,"%d%%"))setMovementPercent(speed);
|
||||
toggle("Freeze time of day",Cheat::FreezeTimeOfDay,"Holds sky and lighting; game timers continue.");
|
||||
static int gold=1000;
|
||||
@@ -50,7 +55,88 @@ namespace dc::cheats
|
||||
ImGui::BeginDisabled(inventorySize()<0);if(ImGui::Button("Apply inventory size"))requestInventorySize(capacity);ImGui::EndDisabled();
|
||||
ImGui::TextWrapped("Inventory edits apply when gameplay resumes and are included in game saves. Existing items are never discarded by resizing.");
|
||||
ImGui::Separator();
|
||||
ImGui::BeginDisabled(current < 0);
|
||||
if (ImGui::Button("Level up equipped weapon")) requestWeaponLevelUp();
|
||||
ImGui::EndDisabled();
|
||||
ImGui::TextDisabled("Fills its ABS; choose Level up in the weapon menu. Not for default weapons.");
|
||||
toggle("Reveal floor map", Cheat::RevealFloorMap, "Shows the whole dungeon floor on the map, chests and Atla included.");
|
||||
toggle("Fish always bite", Cheat::FishingHelper, "Fish near the bait take it and stay hooked until you reel in.");
|
||||
static int spawn = 0, spawnCount = 1;
|
||||
const int items = spawnItemCount();
|
||||
if (items)
|
||||
{
|
||||
spawn = std::clamp(spawn, 0, items - 1);
|
||||
if (ImGui::BeginCombo("Spawn item", spawnItem(spawn).name))
|
||||
{
|
||||
for (int i = 0; i < items; ++i)
|
||||
if (ImGui::Selectable(spawnItem(i).name, i == spawn)) spawn = i;
|
||||
ImGui::EndCombo();
|
||||
}
|
||||
ImGui::SliderInt("Spawn count", &spawnCount, 1, 10);
|
||||
if (ImGui::Button("Give item")) requestSpawn(spawnItem(spawn).id, spawnCount);
|
||||
ImGui::TextDisabled("Given when gameplay resumes, while there is room. Story and key items are excluded.");
|
||||
}
|
||||
else ImGui::TextDisabled("Item names appear once the game has loaded its messages.");
|
||||
ImGui::Separator();
|
||||
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%.");
|
||||
});
|
||||
// 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.");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,21 @@
|
||||
// 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>
|
||||
#include <string>
|
||||
@@ -23,21 +30,55 @@ 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, 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;
|
||||
int root=0,row=0,attack=0,quitChoice=0,gold=0,slot=0,quantity=1,capacity=50;
|
||||
int root=0,row=0,attack=0,quitChoice=0,gold=0,slot=0,quantity=1,capacity=50,spawn=0,spawnCount=1;
|
||||
uint32_t held=0,ticks=0;
|
||||
std::shared_ptr<const bozo::render::Texture> font;
|
||||
// Graphics: the window's settings as edited on the page, posted to the window's thread by its Apply row.
|
||||
int graphicsRow=0;
|
||||
bozo::app::video::Settings graphics;
|
||||
const char *graphicsStatus="";
|
||||
} menu;
|
||||
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;
|
||||
constexpr int rowCount=16;
|
||||
// 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, FastLock, DamageRate, OneHit,
|
||||
NoDamage, KeyFinder, RowEnd };
|
||||
constexpr int rowCount=RowEnd;
|
||||
// The toggle rows and the cheat each switches.
|
||||
bool toggleRow(int row,Cheat &cheat)
|
||||
{
|
||||
if(row<4){cheat=static_cast<Cheat>(row);return true;}
|
||||
if(row==13){cheat=Cheat::FreezeTimeOfDay;return true;}
|
||||
if(row==RevealMap){cheat=Cheat::RevealFloorMap;return true;}
|
||||
if(row==FishBite){cheat=Cheat::FishingHelper;return true;}
|
||||
if(row==FastLock){cheat=Cheat::FastForwardLock;return true;}
|
||||
if(row==OneHit){cheat=Cheat::OneHitKills;return true;}
|
||||
if(row==NoDamage){cheat=Cheat::NoDamageTaken;return true;}
|
||||
if(row==KeyFinder){cheat=Cheat::KeyFinder;return true;}
|
||||
return false;
|
||||
}
|
||||
void (*prepareScene)()=nullptr;
|
||||
uint64_t fontVersion=0;
|
||||
std::atomic<bool> quitRequested{false};
|
||||
std::atomic<bozo::app::video::Shared (*)()> videoShared{nullptr};
|
||||
std::atomic<void (*)(const bozo::app::video::Settings &,bool)> videoPost{nullptr};
|
||||
bozo::app::video::Shared windowSettings(){const auto f=videoShared.load(std::memory_order_acquire);return f?f():bozo::app::video::Shared{};}
|
||||
template<class T> T read(const uint8_t *r,uint32_t at){T v;std::memcpy(&v,r+at,sizeof(v));return v;}
|
||||
template<class T> void write(uint8_t *r,uint32_t at,T v){std::memcpy(r+at,&v,sizeof(v));}
|
||||
void done(R5900Context *c){setReturnS32(c,0);c->pc=getRegU32(c,31);}
|
||||
@@ -96,16 +137,168 @@ void text(std::vector<bozo::render::Vertex> &v,std::string_view s,float x,float
|
||||
x+=8*scale;
|
||||
}
|
||||
}
|
||||
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.widescreen==b.widescreen && a.antiAliasing==b.antiAliasing &&
|
||||
a.textureSmoothing==b.textureSmoothing;
|
||||
}
|
||||
int renderScaleIndex(float scale)
|
||||
{
|
||||
int best=2;
|
||||
for(int i=0;i<int(std::size(renderScales));++i)if(std::abs(renderScales[i]-scale)<std::abs(renderScales[best]-scale))best=i;
|
||||
return best;
|
||||
}
|
||||
std::string graphicsValue(int row,const video::Settings &g,const video::Shared &shared)
|
||||
{
|
||||
char text[64]="";
|
||||
if(row==Display)return g.mode==video::WindowMode::Fullscreen?"Fullscreen":g.mode==video::WindowMode::Borderless?"Borderless":"Windowed";
|
||||
if(row==Resolution){
|
||||
if(g.mode==video::WindowMode::Borderless)std::snprintf(text,sizeof(text),"%dx%d monitor",shared.monitor.first,shared.monitor.second);
|
||||
else std::snprintf(text,sizeof(text),"%dx%d",g.width,g.height);
|
||||
}
|
||||
if(row==RenderScale)std::snprintf(text,sizeof(text),"%d%%",int(std::lround(g.renderScale*100)));
|
||||
if(row==FrameRate){
|
||||
// DC's font has no parentheses (they draw as braces).
|
||||
if(g.frameRate==0)return "60 fps";
|
||||
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.
|
||||
void stepGraphics(int row,int way,const video::Shared &shared)
|
||||
{
|
||||
auto &g=menu.graphics;
|
||||
if(row==Display)g.mode=static_cast<video::WindowMode>((int(g.mode)+3+way)%3);
|
||||
else if(row==Resolution && g.mode!=video::WindowMode::Borderless && !shared.resolutions.empty()){
|
||||
const auto &sizes=shared.resolutions;const int n=int(sizes.size());
|
||||
int at=-1;for(int i=0;i<n;++i)if(sizes[i]==std::pair{g.width,g.height})at=i;
|
||||
at=at<0?(way>0?0:n-1):std::clamp(at+way,0,n-1);
|
||||
g.width=sizes[at].first;g.height=sizes[at].second;
|
||||
}else if(row==RenderScale)g.renderScale=renderScales[std::clamp(renderScaleIndex(g.renderScale)+way,0,int(std::size(renderScales))-1)];
|
||||
else if(row==FrameRate){
|
||||
std::vector<int> rates={0,-1};
|
||||
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="";
|
||||
}
|
||||
void drawGraphics(std::vector<bozo::render::Vertex> &v,uint32_t white,uint32_t gold,uint32_t dim)
|
||||
{
|
||||
const video::Shared shared=windowSettings();
|
||||
if(!shared.open){
|
||||
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","Widescreen","Anti-aliasing","Texture smoothing","Apply and save"};
|
||||
for(int i=0;i<GraphicsRowEnd;++i){
|
||||
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);
|
||||
if(i==ApplyGraphics)continue;
|
||||
std::string value=graphicsValue(i,menu.graphics,shared);
|
||||
if(i==menu.graphicsRow && !locked)value="< "+value+" >";
|
||||
text(v,value,526-float(value.size())*10,y,1.25f,c);
|
||||
}
|
||||
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,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":
|
||||
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?":"CHEATS";
|
||||
text(v,heading,menu.page==Page::Root?264.f:menu.page==Page::Quit?240.f:272.f,76,2,gold);
|
||||
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){
|
||||
const char *labels[]={"Game Options","Cheats","Quit Game"};
|
||||
for(int i=0;i<3;++i){const float y=150.f+i*44;const auto c=i==menu.root?gold:white;text(v,labels[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);
|
||||
@@ -113,37 +306,57 @@ void drawPage(int alpha)
|
||||
const char *labels[]={"Cancel","Quit Game"};
|
||||
for(int i=0;i<2;++i){const float y=240.f+i*38;const auto c=i==menu.quitChoice?gold:white;text(v,labels[i],204,y,1.5f,c);if(i==menu.quitChoice)text(v,">",172,y,1.5f,c);}
|
||||
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"};
|
||||
"Inventory size","Apply inventory size","Level up equipped weapon","Reveal floor map","Fish always bite",
|
||||
"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){
|
||||
const float y=126.f+(i-first)*34;const auto c=i==menu.row?gold:white;
|
||||
text(v,labels[i],128,y,1.25f,c);if(i==menu.row)text(v,">",108,y,1.25f,c);
|
||||
std::string value;
|
||||
if(i<4)value=enabled(static_cast<Cheat>(i))?"ON":"OFF";
|
||||
if(Cheat cheat;toggleRow(i,cheat))value=enabled(cheat)?"ON":"OFF";
|
||||
if(i==4)value=equippedWeaponAttack()<0?"---":std::to_string(menu.attack);
|
||||
if(i==6)value=std::to_string(absMultiplier())+"x";
|
||||
if(i==7)value=gilda()<0?"---":std::to_string(menu.gold);
|
||||
if(i==9)value=std::to_string(menu.slot+1);
|
||||
if(i==10)value=activeConsumable(menu.slot).id<0?"---":std::to_string(menu.quantity);
|
||||
if(i==12)value=std::to_string(movementPercent())+"%";
|
||||
if(i==13)value=enabled(Cheat::FreezeTimeOfDay)?"ON":"OFF";
|
||||
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==DamageRate)value=std::to_string(damageMultiplier())+"x";
|
||||
text(v,value,526-float(value.size())*10,y,1.25f,c);
|
||||
}
|
||||
char count[32];std::snprintf(count,sizeof(count),"%d/%d",menu.row+1,rowCount);text(v,count,470,88,1,dim);
|
||||
const char *help="L/R: 1 L1/R1: 10 L2/R2: 100 O: Back";
|
||||
if(menu.row<4 || menu.row==13)help="X: Toggle Left/Right: Set 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 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";
|
||||
else if(menu.row==6)help="L/R: 1x Positive combat ABS O: Back";
|
||||
else if(menu.row==7)help="L/R: 1 L1/R1: 100 L2/R2: 1000";
|
||||
else if(menu.row==9)help="L/R: Choose one of the three HUD slots";
|
||||
else if(menu.row==12)help="L/R: 5% Collision stays enabled";
|
||||
else if(menu.row==14)help="1-100 slots; occupied items are protected";
|
||||
else if(menu.row==5 || menu.row==8 || menu.row==11 || menu.row==15)help="X: Apply when play resumes O: Back";
|
||||
if((menu.row==4 || menu.row==5) && equippedWeaponAttack()<0)help="No weapon equipped O: Back";
|
||||
else if(menu.row==LevelUp)help="X: Fill ABS; level up in the weapon menu";
|
||||
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==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";
|
||||
if(menu.queued)help="Edit queued; close Options to apply";
|
||||
text(v,help,112,354,1,white);
|
||||
@@ -167,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)
|
||||
{
|
||||
@@ -177,7 +398,7 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
return;
|
||||
}
|
||||
if(pressed&kCircle){
|
||||
if(menu.page==Page::Cheats || 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.
|
||||
@@ -186,8 +407,36 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
return;
|
||||
}
|
||||
if(menu.page==Page::Root){
|
||||
if(pressed&kUp)menu.root=(menu.root+2)%3;else if(pressed&kDown)menu.root=(menu.root+1)%3;
|
||||
if(pressed&kCross){menu.page=menu.root==0?Page::Game:menu.root==1?Page::Cheats:Page::Quit;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&kUp)menu.root=(menu.root+rootCount-1)%rootCount;else if(pressed&kDown)menu.root=(menu.root+1)%rootCount;
|
||||
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){
|
||||
if(pressed&kUp)menu.graphicsRow=(menu.graphicsRow+GraphicsRowEnd-1)%GraphicsRowEnd;
|
||||
else if(pressed&kDown)menu.graphicsRow=(menu.graphicsRow+1)%GraphicsRowEnd;
|
||||
if(menu.graphicsRow!=ApplyGraphics && (pressed&(kLeft|kRight)))stepGraphics(menu.graphicsRow,(pressed&kRight)?1:-1,shared);
|
||||
if(menu.graphicsRow==ApplyGraphics && (pressed&kCross)){
|
||||
// Borderless keeps the window size it returns to.
|
||||
video::Settings next=menu.graphics;
|
||||
if(next.mode==video::WindowMode::Borderless){next.width=shared.applied.width;next.height=shared.applied.height;}
|
||||
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;}
|
||||
@@ -196,8 +445,7 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
int delta=0;if(pressed&kLeft)--delta;if(pressed&kRight)++delta;
|
||||
if(pressed&kL1)delta-=10;if(pressed&kR1)delta+=10;if(pressed&kL2)delta-=100;if(pressed&kR2)delta+=100;
|
||||
if(delta)menu.queued=false;
|
||||
if(menu.row<4 || menu.row==13){
|
||||
const auto cheat=menu.row==13?Cheat::FreezeTimeOfDay:static_cast<Cheat>(menu.row);
|
||||
if(Cheat cheat;toggleRow(menu.row,cheat)){
|
||||
if(pressed&kCross)setEnabled(cheat,!enabled(cheat));else if(pressed&kLeft)setEnabled(cheat,false);else if(pressed&kRight)setEnabled(cheat,true);
|
||||
}else if(menu.row==4 && equippedWeaponAttack()>=0)menu.attack=std::clamp(menu.attack+delta,0,999);
|
||||
else if(menu.row==5 && equippedWeaponAttack()>=0 && (pressed&kCross)){requestWeaponAttack(menu.attack);menu.queued=true;}
|
||||
@@ -212,6 +460,13 @@ void key(uint8_t *r,R5900Context *c,Runtime *rt)
|
||||
else if(menu.row==12 && delta)setMovementPercent(movementPercent()+(delta>0?5:-5));
|
||||
else if(menu.row==14 && inventorySize()>=0)menu.capacity=std::clamp(menu.capacity+delta,std::min(100,minimumInventorySize()),100);
|
||||
else if(menu.row==15 && inventorySize()>=0 && (pressed&kCross)){requestInventorySize(menu.capacity);menu.queued=true;}
|
||||
else if(menu.row==LevelUp && equippedWeaponAttack()>=0 && (pressed&kCross)){requestWeaponLevelUp();menu.queued=true;}
|
||||
else if(menu.row==SpawnItem && delta && spawnItemCount()){
|
||||
const int n=spawnItemCount(),step=std::clamp(delta,-10,10);menu.spawn=((menu.spawn+step)%n+n)%n;
|
||||
}
|
||||
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==DamageRate && delta)setDamageMultiplier(damageMultiplier()+delta);
|
||||
|
||||
}
|
||||
done(c);
|
||||
@@ -250,4 +505,21 @@ void installIngameMenu(Runtime &rt,bozo::port::Registry ®istry,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);}
|
||||
}
|
||||
@@ -1,9 +1,20 @@
|
||||
#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.
|
||||
void installIngameMenu(Runtime &, bozo::port::Registry &, void (*prepareScene)() = nullptr);
|
||||
bool takeIngameQuitRequest(); // consumed at the application's frame boundary
|
||||
// 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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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,6 +29,7 @@
|
||||
#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"
|
||||
#endif
|
||||
namespace dc
|
||||
@@ -33,9 +42,15 @@ 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;
|
||||
@@ -45,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];
|
||||
@@ -67,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)
|
||||
@@ -86,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;
|
||||
}
|
||||
}
|
||||
@@ -97,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();
|
||||
@@ -104,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());
|
||||
@@ -111,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, ®istry, error))
|
||||
{
|
||||
@@ -128,13 +171,68 @@ 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;
|
||||
pacer.setPaced(window);
|
||||
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)
|
||||
{
|
||||
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 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)
|
||||
{
|
||||
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,
|
||||
@@ -160,14 +258,17 @@ int main(int argc, char **argv)
|
||||
if (recording.isOpen())
|
||||
recording.write(pcm, count);
|
||||
#ifdef DC_WITH_WINDOW
|
||||
if (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 && !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;
|
||||
@@ -180,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,
|
||||
@@ -199,10 +318,24 @@ int main(int argc, char **argv)
|
||||
if (window)
|
||||
{
|
||||
dc::cheats::registerMenu();
|
||||
// video.ini (the launcher's Settings, the F2 Video tab and the in-game Graphics page) over the defaults, and the
|
||||
// environment over the file; --fullscreen keeps its meaning, the monitor as it is.
|
||||
bozo::app::video::loadAtStartup(windowOptions.width, windowOptions.height);
|
||||
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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 ®istry)
|
||||
{
|
||||
registry.registerFunction(kReadPad,readPad);
|
||||
registry.registerFunction(kStep,step);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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 ®istry)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 ®istry);
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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=""
|
||||
|
||||
@@ -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"
|
||||
@@ -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}" "$@"
|
||||
}
|
||||
@@ -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
|
||||
@@ -47,7 +47,11 @@ int main(){
|
||||
auto &c=d.kernel().thread(1)->frames.front()->ctx;
|
||||
c.r[28].uw[0]=gp;c.r[31].uw[0]=done;
|
||||
try{d.run();}catch(const bozo::ee::EndRun &){}
|
||||
if(!host.returned || host.libs.cd.readEnd!=0 || host.libs.cd.error!=1 ||
|
||||
// Current engine main ends an active command at the current native
|
||||
// time and leaves an idle drive's error unchanged. Assert observable
|
||||
// completion, rather than the older implementation's zero sentinel.
|
||||
bozo::libs::Guest after(d.runtime(),&c);
|
||||
if(!host.returned || host.libs.now(after)<host.libs.cd.readEnd || host.libs.cd.error!=(busy?1:0) ||
|
||||
c.r[29].uw[0]!=stack || word(r,gp-0x72fc)!=0xffffffffu || word(r,gp-0x72f8)!=0)return 2;
|
||||
for(unsigned i=0;i<32;++i){
|
||||
if(word(r,queue+i*0x9c)!=0)return 3;
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// The level-up, map, fishing, spawner and fast-forward cheats. Each wrapped original is a recording stub, so the hooks'
|
||||
// own decisions are checked exactly: what they pass on, what they write, and what they refuse.
|
||||
#include "../runtime/dc_cheats.h"
|
||||
#include "bozo/port.h"
|
||||
#include "bozo/runtime.h"
|
||||
#include <bit>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
namespace {
|
||||
constexpr uint32_t user=0x400000,gp=0x300000,stack=0x700000,link=0x123450;
|
||||
constexpr uint32_t mapMain=0x01DC4BE0,mapSub=0x01DD56F0,fish=0x500000,messages=0x600000;
|
||||
int failures=0;
|
||||
void check(bool ok,const char *what){if(!ok){++failures;std::printf("FAIL %s\n",what);}}
|
||||
template<class T> T read(uint8_t *r,uint32_t p){T n;std::memcpy(&n,r+p,sizeof(n));return n;}
|
||||
template<class T> void write(uint8_t *r,uint32_t p,T n){std::memcpy(r+p,&n,sizeof(n));}
|
||||
void ret(R5900Context *c,int32_t v){c->r[2].ud[0]=uint64_t(int64_t(v));c->pc=c->r[31].uw[0];}
|
||||
|
||||
// The recording stubs.
|
||||
float seenProbability=-1;int stepCalls=0,maxExpCalls=0,itemChecks=0,weaponChecks=0,gives=0,checkResult=0,rotResult=0;
|
||||
std::vector<int> given;
|
||||
void randCheck(uint8_t *,R5900Context *c,Runtime *){seenProbability=std::bit_cast<float>(c->fu[12]);ret(c,0);}
|
||||
void fishStep(uint8_t *,R5900Context *c,Runtime *){++stepCalls;ret(c,0);}
|
||||
void checkMask(uint8_t *,R5900Context *c,Runtime *){ret(c,0);}
|
||||
void flushMask(uint8_t *r,R5900Context *c,Runtime *){
|
||||
const uint32_t m=c->r[4].uw[0];for(uint32_t i=0;i<400;++i)write<int32_t>(r,m+0x8710+i*4,0);ret(c,0);}
|
||||
void maxExp(uint8_t *,R5900Context *c,Runtime *){++maxExpCalls;ret(c,40);}
|
||||
void checkItemGet(uint8_t *,R5900Context *c,Runtime *){++itemChecks;ret(c,checkResult);}
|
||||
void checkWeaponRot(uint8_t *,R5900Context *c,Runtime *){++weaponChecks;ret(c,rotResult);}
|
||||
void getItem(uint8_t *,R5900Context *c,Runtime *){++gives;given.push_back(c->r[5].sw[0]);ret(c,0);}
|
||||
void plain(uint8_t *,R5900Context *c,Runtime *){ret(c,0);}
|
||||
int hitTests=0,symbolCalls=0,sprites=0;int32_t spriteRect[4]={};uint32_t spriteColour[4]={};
|
||||
void checkHitUser(uint8_t *,R5900Context *c,Runtime *){++hitTests;ret(c,3);}
|
||||
void mapSymbols(uint8_t *,R5900Context *c,Runtime *){++symbolCalls;ret(c,0);}
|
||||
void getPosition(uint8_t *r,R5900Context *c,Runtime *){ // (x, y, z) = (1000, 0, -200)
|
||||
const uint32_t out=c->r[5].uw[0];write<float>(r,out,1000);write<float>(r,out+4,0);write<float>(r,out+8,-200);ret(c,0);}
|
||||
void colourRect(uint8_t *r,R5900Context *c,Runtime *){
|
||||
++sprites;std::memcpy(spriteRect,r+c->r[5].uw[0],16);
|
||||
for(int i=0;i<4;++i)spriteColour[i]=read<uint32_t>(r,c->r[6+i].uw[0]);c->pc=c->r[31].uw[0];}
|
||||
|
||||
R5900Context at(uint32_t pc,uint32_t a0,uint32_t from=link)
|
||||
{R5900Context c;c.pc=pc;c.r[4].uw[0]=a0;c.r[28].uw[0]=gp;c.r[29].uw[0]=stack;c.r[31].uw[0]=from;return c;}
|
||||
void call(Runtime &rt,bozo::port::Registry ®,R5900Context &c)
|
||||
{const uint32_t back=c.r[31].uw[0];reg.find(c.pc)(rt.memory.ram(),&c,&rt);check(c.pc==back && !c.leaving,"hook returns to its caller");}
|
||||
|
||||
// The game's message table: n, then (key, offset) pairs, then the 16-bit text.
|
||||
void messageTable(uint8_t *r,const std::vector<std::pair<int,std::string>> &entries)
|
||||
{
|
||||
const int n=int(entries.size());write<int16_t>(r,messages,int16_t(n));
|
||||
int16_t offset=int16_t(n+1);std::vector<uint16_t> text; // text starts at u16 index 2n + 2 = n + (n + 1) + 1
|
||||
for(int i=0;i<n;++i){
|
||||
write<int16_t>(r,messages+4+4*i,int16_t(entries[size_t(i)].first));write<int16_t>(r,messages+6+4*i,offset);
|
||||
for(char ch:entries[size_t(i)].second)
|
||||
text.push_back(ch==' '?0xFF02:ch>='a'?uint16_t(0xFD3B+ch-'a'):ch>='A'?uint16_t(0xFD21+ch-'A'):uint16_t(0xFD6F+ch-'0'));
|
||||
text.push_back(0xFF01);offset=int16_t(n+1+int(text.size()));
|
||||
}
|
||||
for(size_t i=0;i<text.size();++i)write<uint16_t>(r,messages+2*uint32_t(2*n+2)+2*uint32_t(i),text[i]);
|
||||
write<uint32_t>(r,0x2A2528,messages);
|
||||
}
|
||||
}
|
||||
int main()
|
||||
{
|
||||
using namespace dc::cheats;
|
||||
// Sorted by address: the resource routines install() requires, then the wrapped originals.
|
||||
const BozoFunctionEntry table[]={
|
||||
{0x1B5920,checkHitUser},
|
||||
{0x1B5D90,plain},{0x1BDD40,checkItemGet},{0x1BDF90,checkWeaponRot},{0x1BE060,getItem},{0x1BE510,plain},
|
||||
{0x1BE710,plain},{0x1BE900,plain},{0x1BEA50,plain},{0x1C39C0,checkMask},{0x1C3C00,flushMask},{0x1D7AA0,mapSymbols},
|
||||
{0x200000,getPosition},{0x232080,maxExp},{0x240050,randCheck},{0x240480,fishStep}};
|
||||
const BozoFunctionEntry withDun[]={{0x1B5920,checkHitUser},
|
||||
{0x1B5D90,plain},{0x1BDD40,checkItemGet},{0x1BDF90,checkWeaponRot},{0x1BE060,getItem},{0x1BE510,plain},
|
||||
{0x1BE710,plain},{0x1BE900,plain},{0x1BEA50,plain},{0x1C39C0,checkMask},{0x1C3C00,flushMask},{0x1D7AA0,mapSymbols},
|
||||
{0x200000,getPosition},{0x232080,maxExp},{0x240050,randCheck},{0x240480,fishStep}};
|
||||
auto rt=std::make_unique<Runtime>();rt->functions.setGenerated(table,std::size(table));
|
||||
bozo::port::Registry reg;install(*rt,reg);auto *r=rt->memory.ram();
|
||||
|
||||
// Fishing: the Leave rolls only, and only when on.
|
||||
auto roll=[&](uint32_t from){auto c=at(0x240050,fish,from);c.fu[12]=std::bit_cast<uint32_t>(0.1f);call(*rt,reg,c);return seenProbability;};
|
||||
check(roll(0x2403FC)==0.1f && roll(0x24044C)==0.1f,"fishing off: the Leave rolls keep their odds");
|
||||
setEnabled(Cheat::FishingHelper,true);
|
||||
check(roll(0x2403FC)==0 && roll(0x24044C)==0,"fishing on: a fish near the bait never leaves it");
|
||||
check(roll(0x24022C)==0.1f && roll(0x2402F0)==0.1f && roll(0x2403B0)==0.1f,"fishing on: Find/Eat/Bite odds unchanged");
|
||||
write<int32_t>(r,fish+0x50,8);write<int32_t>(r,fish+0x58,0);
|
||||
{auto c=at(0x240480,fish);call(*rt,reg,c);}
|
||||
check(read<int32_t>(r,fish+0x58)==1 && read<int32_t>(r,fish+0x50)==8 && stepCalls==1,"a hooked fish keeps its timer; Step still runs");
|
||||
write<int32_t>(r,fish+0x50,7);write<int32_t>(r,fish+0x58,0);
|
||||
{auto c=at(0x240480,fish);call(*rt,reg,c);}
|
||||
check(read<int32_t>(r,fish+0x58)==0,"a nibbling fish's timer is not touched");
|
||||
setEnabled(Cheat::FishingHelper,false);
|
||||
write<int32_t>(r,fish+0x50,8);write<int32_t>(r,fish+0x58,0);
|
||||
{auto c=at(0x240480,fish);call(*rt,reg,c);}
|
||||
check(read<int32_t>(r,fish+0x58)==0,"fishing off: the hooked fish's timer runs out as before");
|
||||
|
||||
// Map: floor cells (part != -1) except column 19, two rooms.
|
||||
auto layout=[&](uint32_t m){
|
||||
for(uint32_t i=0;i<400;++i){write<int32_t>(r,m+0x9C50+i*16,(i%3==0 || i%20==19)?2:-1);write<int32_t>(r,m+0x8710+i*4,0);}
|
||||
for(uint32_t i=0;i<16;++i){write<int32_t>(r,m+8+i*4,0);write<int32_t>(r,m+0xB558+i*16,i<2?1:0);}
|
||||
write<int32_t>(r,m+0xB650,3);};
|
||||
auto revealed=[&](uint32_t m){
|
||||
for(uint32_t i=0;i<400;++i){const bool want=i%20!=19 && i%3==0;if((read<int32_t>(r,m+0x8710+i*4)==1)!=want)return false;}
|
||||
return read<int32_t>(r,m+8)==1 && read<int32_t>(r,m+12)==1 && read<int32_t>(r,m+16)==0;};
|
||||
layout(mapMain);setEnabled(Cheat::RevealFloorMap,true);
|
||||
{auto c=at(0x1C39C0,mapMain,0x1DB159C);call(*rt,reg,c);}
|
||||
check(read<int32_t>(r,mapMain+0x8710)==0,"no reveal while the DUN overlay is not resident");
|
||||
auto dun=std::make_unique<Runtime>();dun->functions.setGenerated(withDun,std::size(withDun));
|
||||
bozo::port::Registry dunReg;dunReg.registerFunction(0x15E120,colourRect);install(*dun,dunReg);auto *d=dun->memory.ram();
|
||||
// The DUN overlay resident: its module registered with identity bytes in place, as the game loads it.
|
||||
const std::vector<uint8_t> identity{0x44,0x55,0x4E,0x21};std::memcpy(d+0x1DABD00,identity.data(),identity.size());
|
||||
const BozoFunctionEntry dunModule[]={{0x1DB7450,plain}};
|
||||
dun->functions.addModule(0x1DABD00,0x1F00000,d+0x1DABD00,identity,dunModule,1,nullptr,0);
|
||||
std::swap(r,d);std::swap(rt,dun);
|
||||
layout(mapMain);{auto c=at(0x1C39C0,mapMain,0x1DB159C);call(*rt,dunReg,c);}
|
||||
check(revealed(mapMain),"walking update: every floor cell explored, column 19 and empty cells left alone");
|
||||
layout(mapMain);{auto c=at(0x1C39C0,mapMain,0x1DB1000);call(*rt,dunReg,c);}
|
||||
check(read<int32_t>(r,mapMain+0x8710)==0,"another caller of checkMask is not revealed");
|
||||
layout(mapSub);{auto c=at(0x1C3C00,mapSub,0x1DB913C);call(*rt,dunReg,c);}
|
||||
check(revealed(mapSub),"floor build: the sub-map is revealed after FlushCheckMask clears it");
|
||||
layout(0x500000);{auto c=at(0x1C39C0,0x500000,0x1DB159C);call(*rt,dunReg,c);}
|
||||
check(read<int32_t>(r,0x500000+0x8710)==0,"only the two real map objects are written");
|
||||
setEnabled(Cheat::RevealFloorMap,false);layout(mapMain);{auto c=at(0x1C3C00,mapMain,0x1DB8A1C);call(*rt,dunReg,c);}
|
||||
check(read<int32_t>(r,mapMain+0x8710)==0,"map off: the floor stays unexplored");
|
||||
|
||||
// The player (gp-0x6388) with character 0's equipped weapon in slot 0.
|
||||
std::memset(r+user,0,0x8C00);write<uint32_t>(r,gp-0x6388,user);write<int8_t>(r,user+5,2);
|
||||
const uint32_t weapon=user+0x450C;write<int16_t>(r,weapon,0x103);write<int16_t>(r,weapon+2,3);write<int16_t>(r,weapon+0x14,7);
|
||||
auto tick=[&]{auto c=at(0x1BEA50,user);call(*rt,dunReg,c);};
|
||||
requestWeaponLevelUp();tick();
|
||||
check(read<int16_t>(r,weapon+0x14)==40 && maxExpCalls==1,"level-up: ABS filled to the game's own threshold");
|
||||
write<int16_t>(r,weapon+0x14,7);tick();check(read<int16_t>(r,weapon+0x14)==7,"level-up request is used once");
|
||||
write<int16_t>(r,weapon,0x101);requestWeaponLevelUp();tick();check(read<int16_t>(r,weapon+0x14)==7,"default weapon refused");
|
||||
write<int16_t>(r,weapon,0x10C);requestWeaponLevelUp();tick();check(read<int16_t>(r,weapon+0x14)==7,"Serpent Sword refused");
|
||||
write<int16_t>(r,weapon,0x103);write<int16_t>(r,weapon+2,99);requestWeaponLevelUp();tick();
|
||||
check(read<int16_t>(r,weapon+0x14)==7,"level 99 refused");
|
||||
|
||||
// Spawner: names from the message table; bag items and attachments by id + 100, weapons through ComItemInfo
|
||||
// (indexed id - 0x51).
|
||||
write<int16_t>(r,0x27DE50+(0x103-0x51)*8+6,3);
|
||||
messageTable(r,{{0x91+100,"Bread"},{0xC3+100,"Drans Crest"},{0x5B+100,"Attack"},{3+100,"Baselard"}});
|
||||
tick();
|
||||
bool bread=false,crest=false,sphere=false,blade=false;
|
||||
for(int i=0;i<spawnItemCount();++i){const auto it=spawnItem(i);const std::string n=it.name;
|
||||
bread|=it.id==0x91 && n=="Bread";crest|=it.id==0xC3;sphere|=it.id==0x5B && n=="Attack";blade|=it.id==0x103 && n=="Baselard";}
|
||||
check(bread && sphere && blade && spawnItemCount()==3,"spawner lists named items with their game names");
|
||||
check(!crest,"spawner never offers a key or story item");
|
||||
requestSpawn(0x91,3);tick();check(gives==3 && given[0]==0x91 && itemChecks==3,"three units given through GetItem");
|
||||
checkResult=1;gives=0;requestSpawn(0x91,3);tick();check(gives==0,"a full bag refuses without entering the overflow path");
|
||||
checkResult=0;gives=0;requestSpawn(0xC3,1);tick();check(gives==0,"a key item request is ignored");
|
||||
write<int8_t>(r,0x275A7E + 0x103*0x4C,1);rotResult=3;gives=0;requestSpawn(0x103,1);tick();
|
||||
check(gives==1 && weaponChecks==1,"a weapon goes to its joined owner");
|
||||
write<int8_t>(r,0x275A7E + 0x103*0x4C,4);gives=0;requestSpawn(0x103,1);tick();check(gives==0,"a weapon for a character not yet joined is refused");
|
||||
write<int8_t>(r,0x275A7E + 0x103*0x4C,1);rotResult=9;gives=0;requestSpawn(0x103,1);tick();check(gives==0,"a full weapon list is refused");
|
||||
|
||||
// Damage dealt: the instruction before the game's own subtraction (v0 HP, s4 damage).
|
||||
auto hit=[&](int damage,int hp){R5900Context c;c.r[20].ud[0]=uint64_t(int64_t(damage));c.r[2].ud[0]=uint64_t(int64_t(hp));
|
||||
const bool handled=dunReg.instructionHandler()(r,&c,rt.get(),0x1DC3F4);check(!handled,"the original subtraction still runs");
|
||||
return int(c.r[20].sw[0]);};
|
||||
check(hit(30,100)==30,"damage unchanged at 1x");
|
||||
setDamageMultiplier(2);check(hit(30,100)==60,"2x doubles the damage");
|
||||
setDamageMultiplier(16);check(hit(30,100)==100,"scaled damage is capped at the HP left");
|
||||
check(hit(300,100)==300,"a hit already above the HP keeps its own damage");
|
||||
check(hit(0,100)==0,"an immune hit (0 damage) stays immune");
|
||||
setDamageMultiplier(1);setEnabled(Cheat::OneHitKills,true);check(hit(1,250)==250 && hit(0,250)==0,"one-hit kills, immunities kept");
|
||||
setEnabled(Cheat::OneHitKills,false);
|
||||
|
||||
// Damage taken: only BtCheckDamageProc's hit test, only in the dungeon.
|
||||
auto test=[&](uint32_t from){auto c=at(0x1B5920,0x480000,from);call(*rt,dunReg,c);return c.r[2].sw[0];};
|
||||
check(test(0x1DBB0E0)==3 && hitTests==1,"no-damage off: the hit test runs");
|
||||
setEnabled(Cheat::NoDamageTaken,true);
|
||||
check(test(0x1DBB0E0)==-1 && hitTests==1,"no-damage on: the player's hit test answers no hit");
|
||||
check(test(0x1DBC000)==3 && hitTests==2,"other hit tests are untouched");
|
||||
setEnabled(Cheat::NoDamageTaken,false);
|
||||
|
||||
// Key finder: unit at 0x800000 with slot 5 holding the floor's key (0xC9) and slot 2 another key (0xC4).
|
||||
const uint32_t unit=0x800000,floorMap=0x480000;
|
||||
std::memset(r+unit,0,0x80000);write<uint32_t>(r,gp-0x6320,unit);write<uint32_t>(r,gp-0x6338,floorMap);
|
||||
write<int32_t>(r,floorMap+0x464,0xC9);write<float>(r,gp-0x7F80,0.1f);
|
||||
for(uint32_t i=0;i<16;++i){write<int32_t>(r,unit+i*400+0x1E3D0,1);write<int32_t>(r,unit+i*400+0x1E3F4,10);write<int16_t>(r,unit+i*400+0x1E470,-1);}
|
||||
write<int16_t>(r,unit+5*400+0x1E470,0xC9);write<int16_t>(r,unit+2*400+0x1E470,0xC4);
|
||||
for(uint32_t i=0;i<16;++i){const uint32_t character=unit+i*0x3510+0x1FCD0;write<uint32_t>(r,character+0xA0,0x460000);}
|
||||
write<uint32_t>(r,0x460000+0xA0,0x200000); // the vtable's GetPosition
|
||||
auto symbols=[&]{auto c=at(0x1D7AA0,unit,0x1DB0348);call(*rt,dunReg,c);};
|
||||
symbols();check(sprites==0 && symbolCalls==1,"key finder off: only the game's icons");
|
||||
setEnabled(Cheat::KeyFinder,true);symbols();
|
||||
check(sprites==1 && spriteRect[0]==100+384-1 && spriteRect[1]==-20+68-1 && spriteRect[2]==10 && spriteRect[3]==10,
|
||||
"the marker sits on the holder at the game's map transform");
|
||||
check((spriteColour[0]&0xFFFFFF)==0x20C8FF && spriteColour[0]==spriteColour[3],"a gold square");
|
||||
write<int32_t>(r,unit+5*400+0x1E3F4,0);symbols();check(sprites==2,"the other key holder is marked once the floor's is gone");
|
||||
write<int32_t>(r,unit+2*400+0x1E3D0,-1);symbols();check(sprites==2,"no live holder: no marker");
|
||||
setEnabled(Cheat::KeyFinder,false);
|
||||
|
||||
// Fast-forward.
|
||||
check(gameSpeedPercent()==100,"normal speed by default");
|
||||
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;
|
||||
}
|
||||
@@ -51,7 +51,7 @@ namespace
|
||||
NativePort port{libs, this};
|
||||
Observer observer{libs};
|
||||
RecompiledFunction end = nullptr, terminate = nullptr, channel = nullptr;
|
||||
int packetCalls = 0, syncCalls = 0, flushCalls = 0, sendCalls = 0;
|
||||
int packetCalls = 0, syncCalls = 0, flushCalls = 0, sendCalls = 0, dmaSyncCalls = 0, gsCalls = 0, channelCalls = 0;
|
||||
uint32_t sentChannel = 0, sentSource = 0;
|
||||
Machine()
|
||||
{
|
||||
@@ -60,7 +60,7 @@ namespace
|
||||
end = rt.functions.generated(0x120de0); terminate = rt.functions.generated(0x120c28);
|
||||
channel = rt.functions.generated(0x10c3a8);
|
||||
if (!end || !terminate || !channel) throw std::runtime_error("missing original SDK helper");
|
||||
for (uint32_t pc : {0x120de0u,0x120c28u,0x112f98u,0x104698u,0x113f40u,0x10c3a8u,0x1145a0u,0x10c6f8u})
|
||||
for (uint32_t pc : {0x120de0u,0x120c28u,0x112f98u,0x104698u,0x113f40u,0x10c3a8u,0x1145a0u,0x10c6f8u,0x10cc58u,0x113e48u,0x112ea0u})
|
||||
rt.functions.setOverride(pc, sdk);
|
||||
libs.attach(dispatcher); rt.port = &port; dispatcher.kernel().setObserver(&observer);
|
||||
auto &old = libs.io.channels[1];
|
||||
@@ -82,7 +82,13 @@ namespace
|
||||
++m.syncCalls;
|
||||
m.libs.find("sceGsSyncPath")->handler(m.libs, guest);
|
||||
}
|
||||
else if (pc == 0x10c3a8) m.channel(ram, ctx, rt);
|
||||
else if (pc == 0x10c3a8) { ++m.channelCalls; m.channel(ram, ctx, rt); }
|
||||
else if (pc == 0x113e48 || pc == 0x112ea0) ++m.gsCalls; // sceGsSetHalfOffset / sceGsSwapDBuff
|
||||
else if (pc == 0x10cc58)
|
||||
{
|
||||
++m.dmaSyncCalls;
|
||||
m.libs.find("sceDmaSync")->handler(m.libs, guest);
|
||||
}
|
||||
else if (pc == 0x1145a0) { ++m.flushCalls; guest.ret(0); } // coherent native RAM, no cache device
|
||||
else if (pc == 0x10c6f8)
|
||||
{
|
||||
@@ -140,39 +146,41 @@ int main()
|
||||
}
|
||||
std::printf("DC frame close: %d reference/adapted cases, %d failures\n", cases, failures);
|
||||
#else
|
||||
// The per-frame transfer tail: the published reference waits on the GIF channel, flushes and sends an empty VIF1
|
||||
// transfer; the adapted tail does none of it. The game installs no DMA-completion handler, so no completion is
|
||||
// owed. Frame counter, its first-frame flag, channel lookup and buffer toggle must match.
|
||||
for (uint32_t count : {0u,1u,0x7fffffffu,0xffffffffu})
|
||||
for (uint32_t frame : {0u,1u,0xffffffffu})
|
||||
for (bool masked : {false,true})
|
||||
for (bool first : {false,true})
|
||||
{
|
||||
++cases; Machine reference, native;
|
||||
reference.setup(0, false, count, frame, false); native.setup(0, false, count, frame, true);
|
||||
for (Machine *m : {&reference, &native})
|
||||
{
|
||||
m->dispatcher.kernel().addHandler(true, 1, 0x123400, -1, 0, 0, 0);
|
||||
m->dispatcher.kernel().causeEnable(true, 1, !masked);
|
||||
auto *r = m->dispatcher.runtime().memory.ram();
|
||||
r[gp - 0x73a8] = first ? 0 : 1;
|
||||
word(r, gp - 0x7434, 0x1000a000); // the GIF and VIF1 channel handles MGInit stored
|
||||
word(r, gp - 0x7438, 0x10009000);
|
||||
}
|
||||
reference.run(DC_FRAME_REFERENCE[0].function);
|
||||
auto *ram = native.dispatcher.runtime().memory.ram();
|
||||
const auto *ref = reference.dispatcher.runtime().memory.ram();
|
||||
std::vector<uint8_t> expected(ram, ram + bozo::kFlatScratchpadOffset);
|
||||
for (uint32_t address : {gp - 0x73ac, gp - 0x7438, gp - 0x7440}) word(expected.data(), address, word(ref, address));
|
||||
expected[gp - 0x73a8] = ref[gp - 0x73a8];
|
||||
native.run(DC_FRAME_NATIVE[0].function);
|
||||
check(reference.flushCalls == 1 && native.flushCalls == 1 && reference.sendCalls == 1 && native.sendCalls == 1,
|
||||
"native completion and surrounding retained SDK call occur exactly once");
|
||||
check(reference.sentChannel == 0x10009000 && native.sentChannel == reference.sentChannel &&
|
||||
reference.sentSource == output && native.sentSource == 0, "same native channel completion no longer needs a packet source");
|
||||
check(native.libs.io.nativeSubmissions[1] == 1 && reference.libs.io.nativeSubmissions[1] == 1 &&
|
||||
native.libs.io.nativeCompleted[1] && reference.libs.io.nativeCompleted[1], "native completion state matches published reference");
|
||||
check(reference.dispatcher.kernel().handlerQueued() == !masked && native.dispatcher.kernel().handlerQueued() == !masked,
|
||||
"completion callback delivery respects its original mask");
|
||||
if (masked)
|
||||
{
|
||||
reference.dispatcher.kernel().causeEnable(true, 1, true); native.dispatcher.kernel().causeEnable(true, 1, true);
|
||||
check(reference.dispatcher.kernel().handlerQueued() && native.dispatcher.kernel().handlerQueued(),
|
||||
"masked completion survives until callback enable");
|
||||
}
|
||||
check(reference.gsCalls == 2 && reference.dmaSyncCalls == 1 && reference.flushCalls == 2 &&
|
||||
reference.channelCalls == 1 && reference.sendCalls == 1,
|
||||
"published reference sets the half offset, swaps, waits, flushes twice, looks the channel up and sends");
|
||||
check(word(ref, gp - 0x7438) == 0x10009000, "the reference's lookup returns the handle MGInit stored");
|
||||
check(native.gsCalls == 0 && native.channelCalls == 0 && native.dmaSyncCalls == 0 && native.flushCalls == 0 && native.sendCalls == 0 &&
|
||||
native.libs.io.nativeSubmissions[1] == 0 && native.libs.io.nativeSynchronizations == 0,
|
||||
"adapted tail makes no transfer, flush or wait");
|
||||
check(reference.sentChannel == 0x10009000 && reference.sentSource == output,
|
||||
"the reference sent the old packet on the VIF1 channel");
|
||||
check(!native.dispatcher.kernel().handlerQueued(), "no completion callback is queued");
|
||||
check(std::memcmp(ram, expected.data(), expected.size()) == 0,
|
||||
"frame counter, channel handle and buffer toggle match; ALL other guest RAM stays unchanged");
|
||||
"frame counter, its flag, channel handle and buffer toggle match; ALL other guest RAM stays unchanged");
|
||||
reference.checkRetiredBank(); native.checkRetiredBank();
|
||||
}
|
||||
std::printf("DC frame submit: %d reference/adapted cases, %d failures\n", cases, failures);
|
||||
|
||||
@@ -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"
|
||||
@@ -9,7 +12,15 @@
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
|
||||
namespace video=bozo::app::video;
|
||||
namespace {
|
||||
int postCalls=0;video::Settings posted;bool postedSave=false;
|
||||
video::Shared fakeWindow(){
|
||||
video::Shared s;s.open=true;s.applied.width=1280;s.applied.height=960;s.applied.mode=video::WindowMode::Windowed;
|
||||
s.applied.renderScale=1.f;s.applied.frameRate=0;s.resolutions={{1280,960},{1920,1080}};s.monitor={2560,1440};s.monitorRefresh=144;
|
||||
return s;
|
||||
}
|
||||
void fakePost(const video::Settings &settings,bool save){++postCalls;posted=settings;postedSave=save;}
|
||||
constexpr uint32_t initPc=0x21e4d0,exitPc=0x21e780,keyPc=0x21e9b0,drawPc=0x21f2b0;
|
||||
constexpr uint32_t phase=0x1da8a50,fade=0x1da8a54,loaded=0x1da8ac4,pad=0x1cbc540;
|
||||
constexpr uint32_t user=0x400000,gp=0x300000,weapon=user+0x450c,record=0x1c76968,pixels=0x500000;
|
||||
@@ -67,7 +78,7 @@ int main(){
|
||||
check(initCalls==1 && read<int32_t>(r,phase)==0,"original loading and opening fade complete");
|
||||
check(drawCalls==0 && sceneCalls>0,"native page owns drawing after flushing scene work");
|
||||
const auto frame=bozo::render::Renderer::instance().published();check(frame && frame->batches.size()>=2,"root page submits board and owned font geometry");
|
||||
tap(*rt,p,0x4000);tap(*rt,p,0x40); // Root -> Cheats
|
||||
tap(*rt,p,0x4000);tap(*rt,p,0x4000);tap(*rt,p,0x40); // Root -> Graphics -> Cheats
|
||||
for(int i=0;i<4;++i){tap(*rt,p,0x40);check(dc::cheats::enabled(static_cast<dc::cheats::Cheat>(i)),"each cheat is controllable through the in-game page");if(i<3)tap(*rt,p,0x4000);}
|
||||
tap(*rt,p,0x4000); // ATK row
|
||||
tap(*rt,p,0x2000);tap(*rt,p,8);tap(*rt,p,2);tap(*rt,p,0x8000); // 30+1+10+100-1 = 140
|
||||
@@ -92,7 +103,7 @@ int main(){
|
||||
tap(*rt,p,0x4000);tap(*rt,p,2);tap(*rt,p,0x4000);tap(*rt,p,0x40);step(*rt,p);
|
||||
check(read<int8_t>(r,user+0x4360)==100,"inventory size is controller accessible and capped at 100");
|
||||
draw(*rt,p);const auto scrolled=bozo::render::Renderer::instance().published();check(scrolled && scrolled->batches.size()>=2,"last scroll page draws native text and board");
|
||||
tap(*rt,p,0x20);tap(*rt,p,0x1000);tap(*rt,p,0x40); // back -> Game Options
|
||||
tap(*rt,p,0x20);tap(*rt,p,0x1000);tap(*rt,p,0x1000);tap(*rt,p,0x40); // back -> Game Options
|
||||
const int beforeDraw=drawCalls;draw(*rt,p);check(drawCalls==beforeDraw+1,"original Game Options drawing remains available");
|
||||
tap(*rt,p,0x2000);check(read<int32_t>(r,0x1da8a64)==1,"Game Options input reaches its original handler");
|
||||
tap(*rt,p,0x20);check(read<int32_t>(r,phase)==0,"back from Game Options returns to root without closing");
|
||||
@@ -107,6 +118,52 @@ 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);
|
||||
draw(*rt,p);const auto unavailable=bozo::render::Renderer::instance().published();
|
||||
check(postCalls==0 && unavailable && unavailable->batches.size()>=2,"Graphics without a window draws its notice and posts nothing");
|
||||
tap(*rt,p,0x20);check(read<int32_t>(r,phase)==0,"back from Graphics returns to root without closing");
|
||||
dc::cheats::setGraphicsAccess(fakeWindow,fakePost);tap(*rt,p,0x40); // Root (still on Graphics) -> Graphics
|
||||
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,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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -200,23 +200,22 @@ int main()
|
||||
check(ref->packetCalls == (submitted ? 4 : 0) && native->packetCalls == 0,
|
||||
"only reference resets/ends/terminates, including End's now-visible nested terminate");
|
||||
check(ref->consoleCalls == (p.ended ? 0 : 3) && native->consoleCalls == 0, "adapted callback skips console half-offset/cache/swap setup");
|
||||
// The published reference still waits, flushes and sends; the adapted callback makes no transfer (the
|
||||
// game installs no DMA-completion handler). Its fade sprites must be the same calls, in order.
|
||||
auto sprites = [](const std::vector<Event> &all) {
|
||||
std::vector<Event> only;
|
||||
for (const auto &e : all) if (e.pc == 0x15c310) only.push_back(e);
|
||||
return only;
|
||||
};
|
||||
const int expectedSyncs = p.ended ? 0 : p.countdown == 0 ? 2 : 1;
|
||||
check(ref->events == native->events && ref->syncCalls == expectedSyncs && ref->syncCalls == native->syncCalls,
|
||||
"fade/sprite inputs, completion/cache/sync arguments and ordering match");
|
||||
check(ref->sendCalls == submitted && native->sendCalls == submitted &&
|
||||
(!submitted || (ref->sentChannel == native->sentChannel && ref->sentSource == output && native->sentSource == 0)),
|
||||
"same native completion count/channel without a packet source");
|
||||
check(ref->libs.io.nativeSubmissions[1] == submitted && native->libs.io.nativeSubmissions[1] == submitted &&
|
||||
ref->libs.io.nativeCompleted[1] == submitted && native->libs.io.nativeCompleted[1] == submitted,
|
||||
"native completion ownership matches");
|
||||
const bool queued = submitted && !masked;
|
||||
check(ref->dispatcher.kernel().handlerQueued() == queued && native->dispatcher.kernel().handlerQueued() == queued,
|
||||
"completion IRQ respects callback mask");
|
||||
if (submitted && masked)
|
||||
{
|
||||
ref->dispatcher.kernel().causeEnable(true, 1, true); native->dispatcher.kernel().causeEnable(true, 1, true);
|
||||
check(ref->dispatcher.kernel().handlerQueued() && native->dispatcher.kernel().handlerQueued(), "masked completion survives until enabled");
|
||||
}
|
||||
check(sprites(ref->events) == sprites(native->events), "fade/sprite inputs and ordering match");
|
||||
check(ref->syncCalls == expectedSyncs && native->syncCalls == 0, "only the reference waits on a channel");
|
||||
check(ref->sendCalls == submitted && (!submitted || ref->sentSource == output) && native->sendCalls == 0,
|
||||
"only the reference sends");
|
||||
check(native->events.size() == sprites(native->events).size(), "adapted callback makes no cache or transfer call");
|
||||
check(ref->libs.io.nativeSubmissions[1] == submitted && native->libs.io.nativeSubmissions[1] == 0,
|
||||
"no native submission from the adapted callback");
|
||||
check(!native->dispatcher.kernel().handlerQueued(), "no completion callback queued");
|
||||
check(adapted.fcr31 == original.fcr31, "fade float status matches published reference");
|
||||
check(std::memcmp(ram, expectedRam.data(), stack - 0x1000) == 0 &&
|
||||
std::memcmp(ram + stack, expectedRam.data() + stack, expectedRam.size() - stack) == 0,
|
||||
|
||||
@@ -64,14 +64,18 @@ namespace
|
||||
std::memset(ram + output, 0xa5, 0x20000);
|
||||
auto native = context(); native.pc = pc;
|
||||
registry.find(pc)(ram, &native, &rt);
|
||||
check(native.r[2].uw[0] == expectedSize, "native allocation extent matches original compiled builder");
|
||||
check(word(ram, visual + 0x1c) == expectedVisualSize, "visual size bookkeeping matches original");
|
||||
// The native extent is one qword: CreateVisual reserves it at the data address and aligns to 64 bytes, so each
|
||||
// build keeps a distinct address. The original's VIF packet size is no longer reserved.
|
||||
check(expectedSize > 1u && expectedVisualSize == expectedSize, "the original reserves its VIF packet size");
|
||||
check(native.r[2].uw[0] == 1u, "native allocation extent is one qword");
|
||||
check(word(ram, visual + 0x1c) == 1u && word(ram, visual + 0x18) == output,
|
||||
"visual records its data address and the native extent");
|
||||
check(native.pc == 0x123450 && native.r[29].uw[0] == 0x700000, "native builder preserves return and stack");
|
||||
check(std::all_of(ram + output, ram + output + 0x20000, [](uint8_t v) { return v == 0xa5; }),
|
||||
"native builder never serializes the console output");
|
||||
native = context(0x12000000); native.pc = pc;
|
||||
registry.find(pc)(ram, &native, &rt);
|
||||
check(native.r[2].uw[0] == expectedSize, "obsolete output address is never dereferenced");
|
||||
check(native.r[2].uw[0] == 1u, "obsolete output address is never dereferenced");
|
||||
}
|
||||
}
|
||||
int main()
|
||||
@@ -115,7 +119,8 @@ int main()
|
||||
auto native = context(0x12000000); native.pc = 0x13c5f0;
|
||||
registry.find(0x13c5f0)(ram, &native, rt.get());
|
||||
++cases;
|
||||
check(native.r[2].uw[0] == original.r[2].uw[0], "cloth allocation extent matches original compiled builder");
|
||||
check(original.r[2].uw[0] > 1u && native.r[2].uw[0] == 1u,
|
||||
"the original reserves its VIF size; native cloth reserves one qword");
|
||||
check(std::memcmp(ram, beforeCloth.data(), beforeCloth.size()) == 0, "cloth builder leaves all guest RAM unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -18,7 +18,7 @@ base, end, helpers = {
|
||||
'water': (0x160f20, 0x1610fc, [0x161100, 0x1281b0, 0x1607e0]),
|
||||
'effect': (0x163480, 0x1638ec, [0x1312d0, 0x12e990, 0x1110b0, 0x12e740, 0x15d4b0]),
|
||||
'frame_close': (0x12d1dc, 0x12d268, [0x120de0, 0x120c28, 0x112f98, 0x104698, 0x113f40]),
|
||||
'frame_submit': (0x12d63c, 0x12d6a8, [0x10c3a8, 0x1145a0, 0x10c6f8]),
|
||||
'frame_submit': (0x12d5c0, 0x12d6a8, [0x113e48, 0x112ea0, 0x10cc58, 0x10c3a8, 0x1145a0, 0x10c6f8]),
|
||||
'frame_draw': (0x12ed80, 0x12edec, [0x120c28, 0x120f78]),
|
||||
'frame_member': (0x12a110, 0x12a18c, [0x120c28, 0x120f78]),
|
||||
'mdt_draw': (0x1360e0, 0x136200, [0x127900, 0x1033b0, 0x135000]),
|
||||
@@ -91,9 +91,9 @@ target.with_suffix('.native.externals').write_text(target.with_suffix('.external
|
||||
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': 9, '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}.get(kind, 4)
|
||||
'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': 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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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) # 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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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')
|
||||
|
||||