mirror of
https://github.com/bryanthaboi/gen1recomp.git
synced 2026-08-12 16:31:05 +02:00
Compare commits
27 Commits
v0.1.6
...
pokecenter-fix
| Author | SHA1 | Date | |
|---|---|---|---|
| aad86fb351 | |||
| 2c9970a643 | |||
| 352a9a0eb8 | |||
| 5533785364 | |||
| 11f4f5570e | |||
| 6239387643 | |||
| 4a50cb0728 | |||
| 78aa1f3c0a | |||
| 5128b840b1 | |||
| da14b7ee3f | |||
| 2dbe21babf | |||
| 7a85862602 | |||
| 09b12a7cf0 | |||
| e2f2b432ff | |||
| 8c274d969e | |||
| 4c7633b56e | |||
| 943ae23e73 | |||
| 839cf19088 | |||
| 5019ba2caf | |||
| 0b267fc536 | |||
| 290bde1c39 | |||
| 7e92e54669 | |||
| b89b895962 | |||
| 4311955c43 | |||
| 747d9acad1 | |||
| 5041125751 | |||
| 15029d811f |
@@ -1,7 +1,7 @@
|
||||
name: Release
|
||||
|
||||
# Builds the macOS and Windows desktop apps on the self-hosted Mac runner
|
||||
# and publishes them as a GitHub Release.
|
||||
# Builds the macOS, Windows, and Linux desktop apps plus an Android APK
|
||||
# on the self-hosted Mac runner, and publishes them as a GitHub Release.
|
||||
#
|
||||
# Versioning:
|
||||
# - First ever release is 0.1.0.
|
||||
@@ -152,14 +152,20 @@ jobs:
|
||||
echo "Identities available to codesign:"
|
||||
security find-identity -v -p codesigning "$KEYCHAIN_PATH"
|
||||
|
||||
- name: Build macOS + Windows
|
||||
- name: Build macOS + Windows + Linux
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Sign in-build (identity auto-detected from the temp keychain);
|
||||
# notarize separately below so it uses secret credentials, not a
|
||||
# login-keychain profile.
|
||||
# login-keychain profile. "all" also builds the Linux AppImage,
|
||||
# which needs no signing/notarization.
|
||||
scripts/build.sh all --version "${{ steps.ver.outputs.version }}" --no-notarize
|
||||
|
||||
- name: Build Android
|
||||
run: |
|
||||
set -euo pipefail
|
||||
scripts/build_android.sh --version "${{ steps.ver.outputs.version }}"
|
||||
|
||||
- name: Notarize & staple macOS app
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -171,8 +177,8 @@ jobs:
|
||||
set -a; . "$ci_dir/notary.env"; set +a
|
||||
echo "::add-mask::$APPLE_APP_PASSWORD"
|
||||
|
||||
app=".bazinga/work/PokemonRed.app"
|
||||
zip="dist/mac/PokemonRed-macos.zip"
|
||||
app=".bazinga/work/gen1recomp.app"
|
||||
zip="dist/mac/gen1recomp-macos.zip"
|
||||
[ -d "$app" ] || { echo "::error::signed app not found at $app"; exit 1; }
|
||||
if [ -z "${APPLE_ID:-}" ] || [ -z "${APPLE_APP_PASSWORD:-}" ] || [ -z "${APPLE_TEAM_ID:-}" ]; then
|
||||
echo "::error::notary.env is missing APPLE_ID / APPLE_APP_PASSWORD / APPLE_TEAM_ID."
|
||||
@@ -202,8 +208,12 @@ jobs:
|
||||
outdir="dist/release"
|
||||
rm -rf "$outdir"
|
||||
mkdir -p "$outdir"
|
||||
cp "dist/mac/PokemonRed-macos.zip" "$outdir/PokemonRed-${v}-macos.zip"
|
||||
cp "dist/win/PokemonRed-win64.zip" "$outdir/PokemonRed-${v}-windows.zip"
|
||||
cp "dist/mac/gen1recomp-macos.zip" "$outdir/gen1recomp-${v}-macos.zip"
|
||||
cp "dist/win/gen1recomp-win64.zip" "$outdir/gen1recomp-${v}-windows.zip"
|
||||
cp "dist/linux/gen1recomp-linux.zip" "$outdir/gen1recomp-${v}-linux.zip"
|
||||
apk="$(find dist/android/debug -name '*.apk' | head -1)"
|
||||
[ -n "$apk" ] || { echo "::error::no Android APK found under dist/android/debug"; exit 1; }
|
||||
cp "$apk" "$outdir/gen1recomp-${v}-android.apk"
|
||||
ls -lh "$outdir"
|
||||
|
||||
- name: Publish GitHub Release
|
||||
@@ -253,8 +263,10 @@ jobs:
|
||||
--target "$GITHUB_SHA" \
|
||||
--title "$v" \
|
||||
--notes "$notes" \
|
||||
"dist/release/PokemonRed-${v}-macos.zip" \
|
||||
"dist/release/PokemonRed-${v}-windows.zip"
|
||||
"dist/release/gen1recomp-${v}-macos.zip" \
|
||||
"dist/release/gen1recomp-${v}-windows.zip" \
|
||||
"dist/release/gen1recomp-${v}-linux.zip" \
|
||||
"dist/release/gen1recomp-${v}-android.apk"
|
||||
|
||||
echo "Published release $tag"
|
||||
|
||||
|
||||
@@ -45,6 +45,29 @@ then `love .` for later launches. Windows PowerShell scripts, the optional
|
||||
developer data build, test suites, and cache management are covered in
|
||||
[Developer Setup](https://github.com/bryanthaboi/pokemon-gen1-recomp-project/wiki/Guide-Developer-Setup).
|
||||
|
||||
## Portable Mode
|
||||
|
||||
By default the game keeps your save, options, and the private ROM-derived
|
||||
data cache in your OS's normal per-user app data folder. To keep everything
|
||||
next to the game instead (handy for a USB stick or portable drive you carry
|
||||
between computers), drop an empty file named `portable.txt` next to the app
|
||||
(next to `PokemonRed.app`/`.exe`, or next to `main.lua`/`conf.lua` when
|
||||
running from source), then launch the game. Portable mode is desktop-only
|
||||
(Windows, Linux, macOS); it has no effect on Android or iOS, where the app
|
||||
runs from a read-only package.
|
||||
|
||||
With `portable.txt` present:
|
||||
|
||||
- `save.lua`, `save.lua.bak`, and `options.lua` are read from and written to
|
||||
that same folder instead of the OS save directory.
|
||||
- A ROM import writes the generated `data/generated` and `assets/generated`
|
||||
cache straight into that folder too (nothing is left in the OS save
|
||||
directory), so a later launch reuses it without asking for the ROM again
|
||||
even on a different computer, as long as the same folder comes along.
|
||||
- Deleting `portable.txt` switches back to the normal OS save directory; nothing
|
||||
already written to either location is touched automatically, so copy files
|
||||
over yourself if you want to carry existing progress across the switch.
|
||||
|
||||
## Modding
|
||||
|
||||
The game ships a native mod platform: content registries, events and hooks,
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 370 KiB |
@@ -1,13 +1,16 @@
|
||||
function love.conf(t)
|
||||
local editor = os.getenv("POKEPORT_EDITOR") == "1"
|
||||
local developer = os.getenv("POKEPORT_DEV") == "1"
|
||||
if arg then
|
||||
for _, a in ipairs(arg) do
|
||||
if a == "--editor" then editor = true end
|
||||
if a == "--developer" then developer = true end
|
||||
end
|
||||
end
|
||||
-- main.lua runs in the same Lua state right after conf.lua; stash the
|
||||
-- decision in a global so it doesn't need to reparse `arg`.
|
||||
_G.POKEPORT_EDITOR_MODE = editor
|
||||
_G.POKEPORT_DEV_MODE = developer
|
||||
|
||||
if editor then
|
||||
t.identity = os.getenv("POKEPORT_IDENTITY") or "pokemon-love2d-editor"
|
||||
@@ -20,9 +23,13 @@ function love.conf(t)
|
||||
-- back to the plain title if the source is not mounted yet
|
||||
local ok, Version = pcall(require, "src.core.Version")
|
||||
t.window.title = ok and Version.title()
|
||||
or "Pokemon Red (Gen 1 Recompilation Project)"
|
||||
t.window.width = 160 * 4
|
||||
t.window.height = 144 * 4
|
||||
or "gen1recomp"
|
||||
-- Open at the launcher's design size (the split-screen ROM selector is
|
||||
-- laid out for 1024x768). The window is resizable and the 160x144 game
|
||||
-- canvas letterboxes into whatever size it ends up, so this only sets the
|
||||
-- starting size, not the game's resolution.
|
||||
t.window.width = 1024
|
||||
t.window.height = 768
|
||||
end
|
||||
t.version = "11.5"
|
||||
t.window.vsync = 1
|
||||
@@ -34,14 +41,29 @@ function love.conf(t)
|
||||
local osName = love._os
|
||||
local mobile = osName == "Android" or osName == "iOS"
|
||||
if mobile then
|
||||
-- On Android/iOS, width/height aspect picks portrait vs landscape
|
||||
-- (fullscreen alone is not enough). Use a tall portrait size; the
|
||||
-- OS then resizes to the real display. highdpi is required for
|
||||
-- Retina iOS (Android always behaves as highdpi).
|
||||
-- resizable is what unlocks orientation. SDL's Android backend, given no
|
||||
-- SDL_HINT_ORIENTATIONS (LÖVE sets none), calls setRequestedOrientation
|
||||
-- at window creation -- FULL_SENSOR when the window is resizable (rotates
|
||||
-- freely to portrait or landscape), otherwise locked to the window's w/h
|
||||
-- aspect. So a non-resizable tall window forced portrait; resizable lets
|
||||
-- the game follow the device. The renderer letterboxes the 160x144
|
||||
-- viewport into whatever size results, and touch input is gesture-based,
|
||||
-- so both orientations just work. iOS follows the Info.plist orientations
|
||||
-- (see mobile/ios/overlays/love-ios.plist, now portrait + landscape).
|
||||
t.window.resizable = true
|
||||
-- Starting size is a tall portrait hint; the OS resizes to the real
|
||||
-- display and rotations resize again. highdpi is required for Retina iOS
|
||||
-- (Android always behaves as highdpi).
|
||||
t.window.width = 1080
|
||||
t.window.height = 1920
|
||||
t.window.fullscreen = true
|
||||
t.window.highdpi = true
|
||||
-- Android only (irrelevant on iOS): puts the save directory under the
|
||||
-- app's external-files folder, which is readable/writable via USB or a
|
||||
-- file manager with no runtime permission, so RomImporter can ask the
|
||||
-- player to copy their ROM there instead of needing a native file
|
||||
-- picker (LOVE 11.5 on Android has none -- see src/import/RomImporter.lua).
|
||||
t.externalstorage = osName == "Android"
|
||||
else
|
||||
t.window.resizable = true
|
||||
end
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Celadon Chief House (scripts/CeladonChiefHouse.asm). The CHIEF is a
|
||||
-- talk-only NPC in the original ROM, and ChiefData (data/trainers/
|
||||
-- parties.asm) is an empty, unreferenced trainer entry. After the HALL
|
||||
-- OF FAME (EVENT_BEAT_CHAMPION_RIVAL) the CHIEF puts up a fight, using a
|
||||
-- reconstructed party for the otherwise-unused OPP_CHIEF class.
|
||||
|
||||
return {
|
||||
talk = {
|
||||
TEXT_CELADONCHIEFHOUSE_CHIEF = {
|
||||
{ "face_player" }, -- 1
|
||||
{ "check_flag", "EVENT_BEAT_CHAMPION_RIVAL" }, -- 2
|
||||
{ "jump_if_false", 12 }, -- 3
|
||||
{ "check_flag", "EVENT_BEAT_CELADON_CHIEF" }, -- 4
|
||||
{ "jump_if_true", 12 }, -- 5
|
||||
{ "show_text", "So you've come to\nshut down my\noperation?\f"
|
||||
.. "TEAM ROCKET's\nCHIEF won't go\ndown so easy!" }, -- 6
|
||||
{ "start_battle", "trainer", "OPP_CHIEF", 1 }, -- 7
|
||||
{ "jump_if_false", "end" }, -- 8
|
||||
{ "set_flag", "EVENT_BEAT_CELADON_CHIEF" }, -- 9
|
||||
{ "show_text", "Gah! Even the\nCHIEF is no match\nfor you!\f"
|
||||
.. "TEAM ROCKET is\nfinished for\ngood!" }, -- 10
|
||||
{ "jump", "end" }, -- 11
|
||||
{ "show_text", "_CeladonChiefHouseChiefText" }, -- 12
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -5,10 +5,11 @@
|
||||
-- The escort choreography (SUPER_NERD1 walking the player to the
|
||||
-- museum, YOUNGSTER walking the player to the gym) is scripted NPC
|
||||
-- movement + a wPewterCityCurScript state machine that steers the
|
||||
-- player off-map; that part is already covered on this map by
|
||||
-- story5.lua's onStep gate (walks the player back a step at the
|
||||
-- east exit before EVENT_BEAT_BROCK). Here we only port the real
|
||||
-- YES/NO-branched flavor text these NPCs speak when talked to.
|
||||
-- player off-map; the YOUNGSTER's escort to the gym is handled on this
|
||||
-- map by story5.lua's onStep gate at the east exit (before
|
||||
-- EVENT_BEAT_BROCK), while the SUPER_NERD1 museum escort is not ported.
|
||||
-- Here we only port the real YES/NO-branched flavor text these NPCs
|
||||
-- speak when talked to.
|
||||
|
||||
local M = {}
|
||||
|
||||
|
||||
+20
-17
@@ -19,32 +19,35 @@ local function starterBall(askText, species, choseFlag, ownBall,
|
||||
rivalBallX, rivalBall)
|
||||
return {
|
||||
{ "check_flag", "EVENT_GOT_STARTER" }, -- 1
|
||||
{ "jump_if_true", 19 }, -- 2
|
||||
{ "jump_if_true", 20 }, -- 2
|
||||
-- no picking until Oak has walked you in (OaksLabScript gating)
|
||||
{ "check_flag", "EVENT_FOLLOWED_OAK_INTO_LAB" }, -- 3
|
||||
{ "jump_if_false", 19 }, -- 4
|
||||
{ "ask", askText }, -- 5
|
||||
{ "jump_if_false", 20 }, -- 6
|
||||
{ "give_pokemon", species, 5 }, -- 7
|
||||
{ "set_flag", "EVENT_GOT_STARTER" }, -- 8
|
||||
{ "set_flag", choseFlag }, -- 9
|
||||
{ "jump_if_false", 20 }, -- 4
|
||||
-- the Pokédex "new species" entry shows before the ask (predef
|
||||
-- StarterDex ahead of OaksLabYouWant...Text)
|
||||
{ "push_screen", "DexEntryMenu", species }, -- 5
|
||||
{ "ask", askText }, -- 6
|
||||
{ "jump_if_false", 21 }, -- 7
|
||||
{ "give_pokemon", species, 5 }, -- 8
|
||||
{ "set_flag", "EVENT_GOT_STARTER" }, -- 9
|
||||
{ "set_flag", choseFlag }, -- 10
|
||||
-- POKé BALLs are not handed out here in the original -- Oak gives
|
||||
-- them later, at OaksLabOak1Text's .give_poke_balls beat once the
|
||||
-- player has beaten the Route 22 rival (see TEXT_OAKSLAB_OAK1 below)
|
||||
{ "show_text", "_OaksLabReceivedMonText", { RAM = species } }, -- 10
|
||||
{ "hide_object", "OAKS_LAB", ownBall }, -- 11
|
||||
{ "show_text", "_OaksLabReceivedMonText", { RAM = species } }, -- 11
|
||||
{ "hide_object", "OAKS_LAB", ownBall }, -- 12
|
||||
-- the rival walks to the countering ball (around the furniture)
|
||||
{ "move_npc_to", 1, rivalBallX, 4 }, -- 12
|
||||
{ "face_object", 1, "up" }, -- 13
|
||||
{ "show_text", "_OaksLabRivalIllTakeThisOneText" }, -- 14
|
||||
{ "hide_object", "OAKS_LAB", rivalBall }, -- 15
|
||||
{ "move_npc_to", 1, rivalBallX, 4 }, -- 13
|
||||
{ "face_object", 1, "up" }, -- 14
|
||||
{ "show_text", "_OaksLabRivalIllTakeThisOneText" }, -- 15
|
||||
{ "hide_object", "OAKS_LAB", rivalBall }, -- 16
|
||||
{ "show_text", "_OaksLabRivalReceivedMonText",
|
||||
{ RAM = rivalBall == "OAKSLAB_CHARMANDER_POKE_BALL" and "CHARMANDER"
|
||||
or rivalBall == "OAKSLAB_SQUIRTLE_POKE_BALL" and "SQUIRTLE"
|
||||
or "BULBASAUR" } }, -- 16
|
||||
{ "jump", 20 }, -- 17
|
||||
{ "jump", 20 }, -- 18 (spacer)
|
||||
{ "show_text", "_OaksLabThoseArePokeBallsText" }, -- 19
|
||||
or "BULBASAUR" } }, -- 17
|
||||
{ "jump", 21 }, -- 18
|
||||
{ "jump", 21 }, -- 19 (spacer)
|
||||
{ "show_text", "_OaksLabThoseArePokeBallsText" }, -- 20
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -10,15 +10,39 @@
|
||||
-- The girl, fisher and the four signs resolve automatically through the
|
||||
-- extracted text pointers (no script needed).
|
||||
|
||||
-- Once the HALL OF FAME has been reached (EVENT_BEAT_CHAMPION_RIVAL, set
|
||||
-- alongside Commands.record_hall_of_fame) Oak offers the ProfOakData
|
||||
-- battle (data/trainers/parties.asm) -- three teams picked by the
|
||||
-- player's starter, mirroring the rival's type-advantage lineup, that go
|
||||
-- unused in the original ROM.
|
||||
return {
|
||||
talk = {
|
||||
TEXT_PALLETTOWN_OAK = {
|
||||
{ "face_player" }, -- 1
|
||||
{ "check_flag", "EVENT_GOT_STARTER" }, -- 2
|
||||
{ "jump_if_true", 6 }, -- 3
|
||||
{ "show_text", "_PalletTownOakHeyWaitDontGoOutText" },-- 4
|
||||
{ "jump", 7 }, -- 5
|
||||
{ "show_text", "_PalletTownOakItsUnsafeText" }, -- 6
|
||||
{ "face_player" }, -- 1
|
||||
{ "check_flag", "EVENT_BEAT_CHAMPION_RIVAL" }, -- 2
|
||||
{ "jump_if_false", 20 }, -- 3
|
||||
{ "check_flag", "EVENT_BEAT_PROF_OAK" }, -- 4
|
||||
{ "jump_if_true", 20 }, -- 5
|
||||
{ "show_text", "OAK: So you want\nto test your\nskills on me?\f"
|
||||
.. "Very well! Let\nme show you what\na real trainer\ncan do!" }, -- 6
|
||||
{ "check_flag", "EVENT_CHOSE_BULBASAUR" }, -- 7
|
||||
{ "jump_if_false", 11 }, -- 8
|
||||
{ "start_battle", "trainer", "OPP_PROF_OAK", 3 }, -- 9 CHARIZARD
|
||||
{ "jump", 16 }, -- 10
|
||||
{ "check_flag", "EVENT_CHOSE_SQUIRTLE" }, -- 11
|
||||
{ "jump_if_false", 15 }, -- 12
|
||||
{ "start_battle", "trainer", "OPP_PROF_OAK", 2 }, -- 13 VENUSAUR
|
||||
{ "jump", 16 }, -- 14
|
||||
{ "start_battle", "trainer", "OPP_PROF_OAK", 1 }, -- 15 BLASTOISE
|
||||
{ "jump_if_false", "end" }, -- 16
|
||||
{ "set_flag", "EVENT_BEAT_PROF_OAK" }, -- 17
|
||||
{ "show_text", "OAK: Impressive!\nYou truly are a\nPOKéMON MASTER!" }, -- 18
|
||||
{ "jump", "end" }, -- 19
|
||||
{ "check_flag", "EVENT_GOT_STARTER" }, -- 20
|
||||
{ "jump_if_true", 24 }, -- 21
|
||||
{ "show_text", "_PalletTownOakHeyWaitDontGoOutText" }, -- 22
|
||||
{ "jump", "end" }, -- 23
|
||||
{ "show_text", "_PalletTownOakItsUnsafeText" }, -- 24
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
+174
-26
@@ -133,22 +133,70 @@ M.BLUES_HOUSE = {
|
||||
|
||||
M.BILLS_HOUSE = {
|
||||
talk = {
|
||||
TEXT_BILLSHOUSE_BILL_POKEMON = {
|
||||
{ "check_flag", "EVENT_GOT_SS_TICKET" }, -- 1
|
||||
{ "jump_if_true", 13 }, -- 2
|
||||
{ "show_text", "_BillsHouseBillImNotAPokemonText" }, -- 3
|
||||
{ "show_text", "_BillsHouseBillNoYouGottaHelpText" }, -- 4
|
||||
-- the cell-separator PC throws its switch
|
||||
-- (bills_house_pc.asm BillsHouseInitiatedText: SFX_SWITCH)
|
||||
{ "play_sound", "Switch" }, -- 5
|
||||
{ "show_text", "_BillsHouseBillThankYouText" }, -- 6
|
||||
-- BillsHouseBillPokemonText: "I'm not a POKéMON!", a YES/NO choice
|
||||
-- (NO only adds "No, you gotta help!" before rejoining the YES
|
||||
-- path), then the "get in the TELEPORTER" line and the monster
|
||||
-- walking into the cell-separator machine
|
||||
-- (BillsHousePokemonWalkToMachineScript: up 3, or around the player
|
||||
-- when they stand in the way facing down), where it is hidden and
|
||||
-- EVENT_BILL_SAID_USE_CELL_SEPARATOR arms the PC at (1,4) -- see
|
||||
-- OverworldState.billsHousePC for the separator itself.
|
||||
TEXT_BILLSHOUSE_BILL_POKEMON = function(game, ow, npc, done)
|
||||
local TextBox = require("src.render.TextBox")
|
||||
local t = game.data.text
|
||||
local function toMachine()
|
||||
game.stack:push(TextBox.new(game,
|
||||
t._BillsHouseBillUseSeparationSystemText
|
||||
or "When I'm in the\nTELEPORTER, run\nthe Cell\nSeparation System!", function()
|
||||
local function entered()
|
||||
local Commands = require("src.script.Commands")
|
||||
Commands.hide_object({ game = game, save = game.save,
|
||||
overworld = ow },
|
||||
"BILLS_HOUSE", "BILLSHOUSE_BILL_POKEMON")
|
||||
game.save.flags.EVENT_BILL_SAID_USE_CELL_SEPARATOR = true
|
||||
done()
|
||||
end
|
||||
if ow.player.facing == "down" then
|
||||
-- the player is standing on his straight path: walk around
|
||||
-- (.PokemonWalkAroundPlayerMovement)
|
||||
ow:scriptMove(npc, "right", 1, function()
|
||||
ow:scriptMove(npc, "up", 2, function()
|
||||
ow:scriptMove(npc, "left", 1, function()
|
||||
ow:scriptMove(npc, "up", 1, entered)
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
else
|
||||
ow:scriptMove(npc, "up", 3, entered)
|
||||
end
|
||||
end))
|
||||
end
|
||||
game.stack:push(TextBox.new(game,
|
||||
t._BillsHouseBillImNotAPokemonText or "Hey! I'm not a\nPOKéMON!",
|
||||
nil, { choice = function(yes)
|
||||
if yes then
|
||||
toMachine()
|
||||
else
|
||||
game.stack:push(TextBox.new(game,
|
||||
t._BillsHouseBillNoYouGottaHelpText
|
||||
or "No! You gotta\nhelp me!", toMachine))
|
||||
end
|
||||
end }))
|
||||
end,
|
||||
|
||||
-- BillsHouseBillSSTicketText (human Bill after the separation)
|
||||
TEXT_BILLSHOUSE_BILL_SS_TICKET = {
|
||||
{ "face_player" }, -- 1
|
||||
{ "check_flag", "EVENT_GOT_SS_TICKET" }, -- 2
|
||||
{ "jump_if_true", 12 }, -- 3
|
||||
{ "show_text", "_BillsHouseBillThankYouText" }, -- 4
|
||||
-- pokered gives first (GiveItem fills wStringBuffer), then prints
|
||||
-- the received text that reads it (scripts/BillsHouse.asm; the
|
||||
-- item id is S_S_TICKET in generated items.lua -- keyItem, so the
|
||||
-- sound_get_key_item jingle plays like BillsHouse.asm:196)
|
||||
{ "give_item", "S_S_TICKET", 1, false }, -- 7
|
||||
{ "show_text", "_SSTicketReceivedText" }, -- 8
|
||||
{ "set_flag", "EVENT_GOT_SS_TICKET" }, -- 9
|
||||
{ "give_item", "S_S_TICKET", 1, false }, -- 5
|
||||
{ "show_text", "_SSTicketReceivedText" }, -- 6
|
||||
{ "set_flag", "EVENT_GOT_SS_TICKET" }, -- 7
|
||||
-- The two Cerulean guards are a SWAP PAIR, not scenery
|
||||
-- (BillsHouse.asm:174-178): handing over the ticket shows GUARD1 at
|
||||
-- (28,12) and hides GUARD2 at (27,12). This matters far more than it
|
||||
@@ -156,16 +204,36 @@ M.BILLS_HOUSE = {
|
||||
-- house's south door at (27,11), and that house is one of the two
|
||||
-- ways through the fence that splits Cerulean in half (the badge
|
||||
-- house is the other). Leaving GUARD2 up forever severs the city --
|
||||
-- the gym/mart half can never reach the Route 5 exit -- which is
|
||||
-- exactly what stranded the bot after it beat Misty.
|
||||
-- the gym/mart half can never reach the Route 5 exit.
|
||||
-- Same swap fires after the TM28 Rocket (CeruleanCity_2.asm
|
||||
-- CeruleanHideRocket), so either route opens the path.
|
||||
{ "show_object", "CERULEAN_CITY", "CERULEANCITY_GUARD1" }, -- 10
|
||||
{ "hide_object", "CERULEAN_CITY", "CERULEANCITY_GUARD2" }, -- 11
|
||||
{ "jump", 14 }, -- 12
|
||||
{ "show_text", "_BillsHouseBillCheckOutMyRarePokemonText" }, -- 13
|
||||
{ "show_object", "CERULEAN_CITY", "CERULEANCITY_GUARD1" }, -- 8
|
||||
{ "hide_object", "CERULEAN_CITY", "CERULEANCITY_GUARD2" }, -- 9
|
||||
{ "show_text", "_BillsHouseBillWhyDontYouGoInsteadOfMeText" }, -- 10
|
||||
{ "jump", 13 }, -- 11
|
||||
{ "show_text", "_BillsHouseBillWhyDontYouGoInsteadOfMeText" }, -- 12
|
||||
},
|
||||
|
||||
TEXT_BILLSHOUSE_BILL_CHECK_OUT_MY_RARE_POKEMON = {
|
||||
{ "face_player" }, -- 1
|
||||
{ "show_text", "_BillsHouseBillCheckOutMyRarePokemonText" }, -- 2
|
||||
},
|
||||
},
|
||||
-- repair saves that already got the ticket under the old collapsed
|
||||
-- script (the monster never hidden, human Bill never shown)
|
||||
onEnter = function(game, ow)
|
||||
if game.save.flags.EVENT_GOT_SS_TICKET
|
||||
and not game.save.flags.EVENT_USED_CELL_SEPARATOR_ON_BILL then
|
||||
local Commands = require("src.script.Commands")
|
||||
local ctx = { game = game, save = game.save, overworld = ow }
|
||||
Commands.hide_object(ctx, "BILLS_HOUSE", "BILLSHOUSE_BILL_POKEMON")
|
||||
Commands.show_object(ctx, "BILLS_HOUSE", "BILLSHOUSE_BILL1")
|
||||
game.save.flags.EVENT_BILL_SAID_USE_CELL_SEPARATOR = true
|
||||
game.save.flags.EVENT_USED_CELL_SEPARATOR_ON_BILL = true
|
||||
game.save.flags.EVENT_MET_BILL = true
|
||||
game.save.flags.EVENT_MET_BILL_2 = true
|
||||
end
|
||||
end,
|
||||
}
|
||||
|
||||
-- -------------------------------------------------------------------
|
||||
@@ -186,17 +254,48 @@ M.VERMILION_CITY = {
|
||||
game.save.trashPuzzle = puz
|
||||
puz.first = love.math.random(0, 7) * 2
|
||||
end,
|
||||
-- VermilionCityDefaultScript's per-frame SSAnneTicketCheckCoords check:
|
||||
-- the unguarded cell (18,30) just west of the sailor leads straight
|
||||
-- onto the dock warp, so stepping onto it heading for the dock gets
|
||||
-- ticket-checked (and turned back once the ship has sailed) without
|
||||
-- the player ever pressing A. The sailor himself never disappears.
|
||||
onStep = function(game, ow, x, y)
|
||||
if x ~= 18 or y ~= 30 then return false end
|
||||
if ow.player.facing ~= "down" then return false end
|
||||
local f = game.save.flags
|
||||
local t = game.data.text
|
||||
local TextBox = require("src.render.TextBox")
|
||||
if f.EVENT_SS_ANNE_LEFT then
|
||||
game.stack:push(TextBox.new(game,
|
||||
t._VermilionCitySailor1ShipSetSailText or "The ship set sail.",
|
||||
function() ow:scriptMove(ow.player, "up", 1) end))
|
||||
return true
|
||||
end
|
||||
if (game.save.inventory.S_S_TICKET or 0) > 0 then return false end
|
||||
game.stack:push(TextBox.new(game,
|
||||
(t._VermilionCitySailor1WelcomeToSSAnneText or "Welcome to S.S.\nANNE!")
|
||||
.. "\f"
|
||||
.. (t._VermilionCitySailor1YouNeedATicketText
|
||||
or "You need a ticket\nto get aboard."),
|
||||
function() ow:scriptMove(ow.player, "up", 1) end))
|
||||
return true
|
||||
end,
|
||||
talk = {
|
||||
-- the sailor guarding the dock gangway
|
||||
-- the sailor guarding the dock gangway (VermilionCitySailor1Text):
|
||||
-- flashing the ticket just lets you through -- he never hides, and
|
||||
-- once the ship has sailed he only reports it gone
|
||||
TEXT_VERMILIONCITY_SAILOR1 = {
|
||||
{ "face_player" }, -- 1
|
||||
{ "show_text", "_VermilionCitySailor1WelcomeToSSAnneText" }, -- 2
|
||||
{ "check_item", "S_S_TICKET" }, -- 3
|
||||
{ "jump_if_false", 8 }, -- 4
|
||||
{ "show_text", "_VermilionCitySailor1FlashedTicketText" }, -- 5
|
||||
{ "hide_object", "VERMILION_CITY", "VERMILIONCITY_SAILOR1" }, -- 6
|
||||
{ "jump", 9 }, -- 7
|
||||
{ "show_text", "_VermilionCitySailor1YouNeedATicketText" }, -- 8
|
||||
{ "check_flag", "EVENT_SS_ANNE_LEFT" }, -- 2
|
||||
{ "jump_if_true", 11 }, -- 3
|
||||
{ "show_text", "_VermilionCitySailor1WelcomeToSSAnneText" }, -- 4
|
||||
{ "check_item", "S_S_TICKET" }, -- 5
|
||||
{ "jump_if_false", 9 }, -- 6
|
||||
{ "show_text", "_VermilionCitySailor1FlashedTicketText" }, -- 7
|
||||
{ "jump", 12 }, -- 8
|
||||
{ "show_text", "_VermilionCitySailor1YouNeedATicketText" }, -- 9
|
||||
{ "jump", 12 }, -- 10
|
||||
{ "show_text", "_VermilionCitySailor1ShipSetSailText" }, -- 11
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -613,6 +712,29 @@ M.HALL_OF_FAME = {
|
||||
local toggles = game.save.objectToggles and game.save.objectToggles.HALL_OF_FAME
|
||||
if toggles then toggles.HALLOFFAME_OAK = nil end
|
||||
|
||||
-- Make the Hall of Fame recording machine interactable. The console
|
||||
-- juts from the north wall as the two solid cells (4,1) and (5,1); a
|
||||
-- sign on each lets the player face the machine (from below, or from
|
||||
-- either side) and press A to run the TEXT_HALLOFFAME_PC talk script.
|
||||
-- maps.lua is generated from the ROM and gitignored, so the sign is
|
||||
-- injected here (a tracked script) rather than baked into map data.
|
||||
local def = ow.map.def
|
||||
def.signs = def.signs or {}
|
||||
local present = false
|
||||
for _, s in ipairs(def.signs) do
|
||||
if s.text == "TEXT_HALLOFFAME_PC" then present = true break end
|
||||
end
|
||||
if not present then
|
||||
table.insert(def.signs, { text = "TEXT_HALLOFFAME_PC", x = 4, y = 1 })
|
||||
table.insert(def.signs, { text = "TEXT_HALLOFFAME_PC", x = 5, y = 1 })
|
||||
end
|
||||
-- the live Map instance built its signAt lookup from def.signs before
|
||||
-- this hook ran, so rebuild it (idempotent) to pick up the injection
|
||||
ow.map.signAt = {}
|
||||
for _, s in ipairs(def.signs) do
|
||||
ow.map.signAt[s.y * ow.map.widthCells + s.x] = s
|
||||
end
|
||||
|
||||
if not game.save.pendingHallOfFame then return end
|
||||
game.save.pendingHallOfFame = false
|
||||
ow:queueScript({
|
||||
@@ -626,6 +748,17 @@ M.HALL_OF_FAME = {
|
||||
{ "record_hall_of_fame" }, -- predef HallOfFamePC: induction + credits
|
||||
})
|
||||
end,
|
||||
talk = {
|
||||
-- The recording machine doubles as a "warp home" PC: a YES/NO prompt
|
||||
-- that teleports back to the new-game bedroom spawn (special_warps.asm
|
||||
-- NewGameWarp: REDS_HOUSE_2F, 3, 6, facing down). Fabricated
|
||||
-- convenience -- there is no such prompt in the original ROM.
|
||||
TEXT_HALLOFFAME_PC = {
|
||||
{ "ask", "Return to\nPALLET TOWN?" }, -- 1 YES/NO -> lastCheck
|
||||
{ "jump_if_false", "end" }, -- 2 NO: back away
|
||||
{ "warp", "REDS_HOUSE_2F", 3, 6, "down" }, -- 3 YES: home to your room
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
-- -------------------------------------------------------------------
|
||||
@@ -665,6 +798,21 @@ M.POKEMON_TOWER_2F = {
|
||||
{ "show_text", "_PokemonTower2FRivalHowsYourDexText" }, -- 10
|
||||
},
|
||||
},
|
||||
-- PokemonTower2FDefaultScript: walking past the rival's tile forces
|
||||
-- the encounter (ArePlayerCoordsInArray on (15,5)/(14,6)) -- he never
|
||||
-- waits to be talked to
|
||||
onStep = function(game, ow, x, y)
|
||||
if game.save.flags.EVENT_BEAT_POKEMON_TOWER_RIVAL then return false end
|
||||
if not ((x == 15 and y == 5) or (x == 14 and y == 6)) then return false end
|
||||
if ow.runner:isRunning() then return false end
|
||||
local rival = ow:npcByIndex(1)
|
||||
if not rival then return false end
|
||||
ow.player.facing = (x == 15) and "left" or "up"
|
||||
require("src.core.Music").play(game.data, "Music_MeetRival")
|
||||
ow.runner:run(M.POKEMON_TOWER_2F.talk.TEXT_POKEMONTOWER2F_RIVAL,
|
||||
{ npc = rival })
|
||||
return true
|
||||
end,
|
||||
}
|
||||
|
||||
-- -------------------------------------------------------------------
|
||||
|
||||
+13
-5
@@ -308,8 +308,12 @@ local function saffronGate(guardText, triggers, horizontal)
|
||||
end
|
||||
if takeGuardDrink(game) then
|
||||
game.stack:push(TextBox.new(game,
|
||||
(t._SaffronGateGuardYouCanGoOnThroughText or
|
||||
"Thanks! You can\ngo on through!"), done))
|
||||
t._SaffronGateGuardImParchedText or "Whoa, boy!\nI'm parched!",
|
||||
function()
|
||||
game.stack:push(TextBox.new(game,
|
||||
(t._SaffronGateGuardYouCanGoOnThroughText or
|
||||
"You can go on\nthrough!"), done))
|
||||
end))
|
||||
return
|
||||
end
|
||||
game.stack:push(TextBox.new(game,
|
||||
@@ -344,8 +348,12 @@ local function saffronGate(guardText, triggers, horizontal)
|
||||
-- for the POKE_FLUTE at all.
|
||||
if takeGuardDrink(game) then
|
||||
game.stack:push(TextBox.new(game,
|
||||
(t._SaffronGateGuardYouCanGoOnThroughText or
|
||||
"Thanks! You can\ngo on through!")))
|
||||
t._SaffronGateGuardImParchedText or "Whoa, boy!\nI'm parched!",
|
||||
function()
|
||||
game.stack:push(TextBox.new(game,
|
||||
(t._SaffronGateGuardYouCanGoOnThroughText or
|
||||
"You can go on\nthrough!")))
|
||||
end))
|
||||
return true
|
||||
end
|
||||
local back
|
||||
@@ -355,7 +363,7 @@ local function saffronGate(guardText, triggers, horizontal)
|
||||
back = ow.player.facing == "up" and "down" or "up"
|
||||
end
|
||||
game.stack:push(TextBox.new(game,
|
||||
t._SaffronGateGuardImParchedText or "I'm parched...\nNo entry until\nI get a drink!",
|
||||
t._SaffronGateGuardGeeImThirstyText or "Gee, I'm thirsty\nthough!\nThe road's closed.",
|
||||
function()
|
||||
ow:scriptMove(ow.player, back, 1)
|
||||
end))
|
||||
|
||||
+93
-10
@@ -317,6 +317,33 @@ M.GAME_CORNER = {
|
||||
done()
|
||||
end))
|
||||
end,
|
||||
-- the grunt guarding the poster (GameCornerRocketText /
|
||||
-- GameCornerRocketBattleScript / GameCornerRocketExitScript): after
|
||||
-- losing he warns the BOSS and leaves the floor for good, freeing
|
||||
-- the tile in front of the hideout switch
|
||||
TEXT_GAMECORNER_ROCKET = function(game, ow, npc, done)
|
||||
if ow:trainerDefeated(npc) then
|
||||
done()
|
||||
return
|
||||
end
|
||||
ow:engageTrainer(npc, function()
|
||||
if not ow:trainerDefeated(npc) then
|
||||
done()
|
||||
return
|
||||
end
|
||||
local TextBox = require("src.render.TextBox")
|
||||
game.stack:push(TextBox.new(game,
|
||||
game.data.text._GameCornerRocketAfterBattleText
|
||||
or "Our hideout might\nbe discovered! I\nbetter tell BOSS!",
|
||||
function()
|
||||
local Commands = require("src.script.Commands")
|
||||
Commands.hide_object({ game = game, save = game.save,
|
||||
overworld = ow },
|
||||
"GAME_CORNER", "GAMECORNER_ROCKET")
|
||||
done()
|
||||
end))
|
||||
end)
|
||||
end,
|
||||
TEXT_GAMECORNER_CLERK1 = function(game, ow, npc, done)
|
||||
local TextBox = require("src.render.TextBox")
|
||||
local ChoiceBox = require("src.ui.ChoiceBox")
|
||||
@@ -363,24 +390,42 @@ M.GAME_CORNER = {
|
||||
},
|
||||
}
|
||||
|
||||
-- Red-version prize lists (data/events/prizes.asm, prize_mon_levels.asm)
|
||||
local PRIZES = {
|
||||
-- Game Corner prize lists (data/events/prizes.asm, prize_mon_levels.asm).
|
||||
-- The six mon prizes differ between Red and Blue; the three TM prizes are
|
||||
-- identical, so they are shared and appended to each version's mon list.
|
||||
local PRIZE_TMS = {
|
||||
{ kind = "item", item = "TM_DRAGON_RAGE", cost = 3300 },
|
||||
{ kind = "item", item = "TM_HYPER_BEAM", cost = 5500 },
|
||||
{ kind = "item", item = "TM_SUBSTITUTE", cost = 7700 },
|
||||
}
|
||||
local RED_PRIZES = {
|
||||
{ kind = "mon", species = "ABRA", level = 9, cost = 180 },
|
||||
{ kind = "mon", species = "CLEFAIRY", level = 8, cost = 500 },
|
||||
{ kind = "mon", species = "NIDORINA", level = 17, cost = 1200 },
|
||||
{ kind = "mon", species = "DRATINI", level = 18, cost = 2800 },
|
||||
{ kind = "mon", species = "SCYTHER", level = 25, cost = 5500 },
|
||||
{ kind = "mon", species = "PORYGON", level = 26, cost = 9999 },
|
||||
{ kind = "item", item = "TM_DRAGON_RAGE", cost = 3300 },
|
||||
{ kind = "item", item = "TM_HYPER_BEAM", cost = 5500 },
|
||||
{ kind = "item", item = "TM_SUBSTITUTE", cost = 7700 },
|
||||
PRIZE_TMS[1], PRIZE_TMS[2], PRIZE_TMS[3],
|
||||
}
|
||||
local BLUE_PRIZES = {
|
||||
{ kind = "mon", species = "ABRA", level = 6, cost = 120 },
|
||||
{ kind = "mon", species = "CLEFAIRY", level = 12, cost = 750 },
|
||||
{ kind = "mon", species = "NIDORINO", level = 17, cost = 1200 },
|
||||
{ kind = "mon", species = "PINSIR", level = 20, cost = 2500 },
|
||||
{ kind = "mon", species = "DRATINI", level = 24, cost = 4600 },
|
||||
{ kind = "mon", species = "PORYGON", level = 18, cost = 6500 },
|
||||
PRIZE_TMS[1], PRIZE_TMS[2], PRIZE_TMS[3],
|
||||
}
|
||||
|
||||
local function activePrizes()
|
||||
return require("src.core.GameVersion").isBlue() and BLUE_PRIZES or RED_PRIZES
|
||||
end
|
||||
|
||||
local function prizeCounter(game, ow, npc, done)
|
||||
local ListMenu = require("src.ui.ListMenu")
|
||||
local Commands = require("src.script.Commands")
|
||||
local items = {}
|
||||
for _, p in ipairs(PRIZES) do
|
||||
for _, p in ipairs(activePrizes()) do
|
||||
local label
|
||||
if p.kind == "mon" then
|
||||
label = ("%s L%d"):format(game.data.pokemon[p.species].name, p.level)
|
||||
@@ -425,18 +470,56 @@ M.GAME_CORNER_PRIZE_ROOM = {
|
||||
-- and the player steps off the dock, the ship sets sail.
|
||||
-- -------------------------------------------------------------------
|
||||
|
||||
-- the ship's hull/deck blocks (block cols 5-8, rows 1-2) and the water
|
||||
-- that replaces them once she sails (the surrounding blocks of each row)
|
||||
local DOCK_SHIP_BLOCKS = {
|
||||
{ bx = 5, by = 1, water = 1 }, { bx = 6, by = 1, water = 1 },
|
||||
{ bx = 7, by = 1, water = 1 }, { bx = 8, by = 1, water = 1 },
|
||||
{ bx = 5, by = 2, water = 13 }, { bx = 6, by = 2, water = 13 },
|
||||
{ bx = 7, by = 2, water = 13 }, { bx = 8, by = 2, water = 13 },
|
||||
}
|
||||
|
||||
M.VERMILION_DOCK = {
|
||||
onEnter = function(game, ow)
|
||||
if game.save.flags.EVENT_SS_ANNE_LEFT then
|
||||
local f = game.save.flags
|
||||
if f.EVENT_SS_ANNE_LEFT then
|
||||
-- the ship is long gone: erase her right away, and anyone who
|
||||
-- still lands here is sent back out past the guard
|
||||
for _, b in ipairs(DOCK_SHIP_BLOCKS) do
|
||||
ow.map:setBlock(b.bx, b.by, b.water)
|
||||
end
|
||||
ow.map.renderer:rebuild()
|
||||
local TextBox = require("src.render.TextBox")
|
||||
game.stack:push(TextBox.new(game,
|
||||
game.data.text._VermilionCitySailor1ShipSetSailText
|
||||
or "The ship set sail.", function()
|
||||
ow:startWarpTo("VERMILION_CITY", 19, 30, "up")
|
||||
ow:startWarpTo("VERMILION_CITY", 18, 29, "up")
|
||||
end))
|
||||
elseif game.save.flags.EVENT_GOT_HM01 then
|
||||
game.save.flags.EVENT_SS_ANNE_LEFT = true
|
||||
elseif f.EVENT_GOT_HM01 and ow.player.cellY == 2 then
|
||||
-- VermilionDockSSAnneLeavesScript: only stepping OFF the ship
|
||||
-- triggers the departure (wDestinationWarpID == 1 in pokered) --
|
||||
-- the horn blows, smoke puffs drift off the funnel, the ship is
|
||||
-- erased to open water, and the player is walked off the dock
|
||||
-- into the city past the guard (VermilionCity's
|
||||
-- SCRIPT_VERMILIONCITY_PLAYER_EXIT_SHIP walk)
|
||||
f.EVENT_SS_ANNE_LEFT = true
|
||||
require("src.core.Music").stop()
|
||||
require("src.core.Sound").play(game.data, "SS_Anne_Horn")
|
||||
local function puff(n, cx)
|
||||
if n <= 0 then return end
|
||||
ow:startDustAnim(cx, 1, function() puff(n - 1, cx + 2) end)
|
||||
end
|
||||
puff(3, 15)
|
||||
local rows = {}
|
||||
rows[#rows + 1] = { "wait", 100 }
|
||||
for _, b in ipairs(DOCK_SHIP_BLOCKS) do
|
||||
rows[#rows + 1] = { "replace_block", b.bx, b.by, b.water }
|
||||
end
|
||||
rows[#rows + 1] = { "wait", 30 }
|
||||
rows[#rows + 1] = { "move_player", "up", 2 }
|
||||
rows[#rows + 1] = { "warp", "VERMILION_CITY", 18, 31, "up" }
|
||||
rows[#rows + 1] = { "move_player", "up", 2 }
|
||||
ow:queueScript(rows)
|
||||
end
|
||||
end,
|
||||
}
|
||||
|
||||
@@ -457,6 +457,25 @@ M.ROUTE_24 = {
|
||||
battleOrDone()
|
||||
end,
|
||||
},
|
||||
-- Route24DefaultScript forces TEXT_ROUTE24_COOLTRAINER_M1 whenever the
|
||||
-- player stands on (10,15) in front of the recruiter while
|
||||
-- EVENT_GOT_NUGGET is unset (dbmapcoord 10,15), independent of facing
|
||||
-- or input -- he has no trainer header, so sight never engages him.
|
||||
onStep = function(game, ow, x, y)
|
||||
if game.save.flags.EVENT_GOT_NUGGET then return false end
|
||||
if not (x == 10 and y == 15) then return false end
|
||||
if ow.runner:isRunning() or ow.engaging then return false end
|
||||
local recruiter
|
||||
for _, npc in ipairs(ow.npcs) do
|
||||
if npc.def and npc.def.name == "ROUTE24_COOLTRAINER_M1" then
|
||||
recruiter = npc
|
||||
break
|
||||
end
|
||||
end
|
||||
if not recruiter then return false end
|
||||
ow:showMapText("TEXT_ROUTE24_COOLTRAINER_M1", recruiter)
|
||||
return true
|
||||
end,
|
||||
}
|
||||
|
||||
-- -------------------------------------------------------------------
|
||||
@@ -723,4 +742,6 @@ M.LANCES_ROOM = {
|
||||
end,
|
||||
}
|
||||
|
||||
M.CELADON_CHIEF_HOUSE = require("data.scripts.celadon_chief_house")
|
||||
|
||||
return M
|
||||
|
||||
+35
-5
@@ -259,21 +259,39 @@ M.CINNABAR_ISLAND = {
|
||||
end,
|
||||
}
|
||||
|
||||
-- Pewter's youngster stops you leaving east before Brock is beaten
|
||||
-- (scripts/PewterCity.asm PewterCityCheckPlayerLeavingEastScript; the
|
||||
-- original escorts you to the gym, we walk you back a step)
|
||||
-- Pewter's youngster stops you leaving east before Brock is beaten and
|
||||
-- escorts you to the gym (scripts/PewterCity.asm
|
||||
-- PewterCityCheckPlayerLeavingEastScript /
|
||||
-- PewterCityYoungsterShowsPlayerGymScript, engine/events/pewter_guys.asm
|
||||
-- PewterGymGuyCoords): the "follow me" lines, then the player is walked
|
||||
-- west along the road to the front of the PEWTER_GYM door at (16,17).
|
||||
M.PEWTER_CITY = {
|
||||
onStep = function(game, ow, x, y)
|
||||
if game.save.flags.EVENT_BEAT_BROCK then return false end
|
||||
if ow.runner:isRunning() or #ow.scriptMoves > 0 then return false end
|
||||
if not inCoords({ { 35, 17 }, { 36, 17 }, { 37, 18 }, { 37, 19 } }, x, y) then
|
||||
return false
|
||||
end
|
||||
local t = text(game)
|
||||
-- walk up onto the road row (y=17), west to one tile east of the gym
|
||||
-- door, then drop below the door and turn to face it
|
||||
local steps = {}
|
||||
for _ = 1, y - 17 do steps[#steps + 1] = "up" end
|
||||
for _ = 1, x - 17 do steps[#steps + 1] = "left" end
|
||||
steps[#steps + 1] = "down"
|
||||
steps[#steps + 1] = "left"
|
||||
local function walk(i)
|
||||
if not steps[i] then
|
||||
ow.player.facing = "up"
|
||||
return
|
||||
end
|
||||
ow:scriptMove(ow.player, steps[i], 1, function() walk(i + 1) end)
|
||||
end
|
||||
push(game, t._PewterCityYoungsterYoureATrainerFollowMeText
|
||||
or "Hey! You're a\ntrainer, right?", function()
|
||||
push(game, t._PewterCityYoungsterGoTakeOnBrockText
|
||||
or "Go take on BROCK\nat the GYM first!", function()
|
||||
ow:scriptMove(ow.player, "left", 1)
|
||||
walk(1)
|
||||
end)
|
||||
end)
|
||||
return true
|
||||
@@ -453,10 +471,22 @@ local function bikeGateGuard(coords, stopText, explainText)
|
||||
return function(game, ow, x, y)
|
||||
if game.save.inventory.BICYCLE then return false end
|
||||
if not inCoords(coords, x, y) then return false end
|
||||
-- walk the player up to the tile beside the counter, no further:
|
||||
-- (matchedY - closestY) tiles, 0 when already next to it
|
||||
-- (Route16Gate1FDefaultScript's wCoordIndex-1). Forcing a fixed one
|
||||
-- tile up from the counter-adjacent row shoved the player onto the
|
||||
-- impassable desk and boxed them in.
|
||||
local closestY = coords[1][2]
|
||||
for _, c in ipairs(coords) do
|
||||
if c[2] < closestY then closestY = c[2] end
|
||||
end
|
||||
local dist = y - closestY
|
||||
local t = text(game)
|
||||
push(game, t[stopText] or "Hey! Wait up!", function()
|
||||
push(game, t[explainText] or "You need a\nBICYCLE for\nCYCLING ROAD!", function()
|
||||
ow:scriptMove(ow.player, "up", 1)
|
||||
if dist > 0 then
|
||||
ow:scriptMove(ow.player, "up", dist)
|
||||
end
|
||||
end)
|
||||
end)
|
||||
return true
|
||||
|
||||
@@ -6,4 +6,37 @@ work for true parity. Faithfully-ported behavior is documented in
|
||||
docs/behavior-porting-notes.md; deliberate additions beyond the original
|
||||
are in docs/new-features.md.
|
||||
|
||||
None currently.
|
||||
## Reimplemented unused Prof. Oak and Rocket Chief battles
|
||||
|
||||
The original ROM defines trainer data for `PROF_OAK` and `CHIEF`
|
||||
(`data/trainers/parties.asm`) but never attaches either to an NPC, so
|
||||
both battles are unreachable in the real game. This project makes them
|
||||
fightable after the Hall of Fame:
|
||||
|
||||
- Prof. Oak battles you in Pallet Town once `EVENT_BEAT_CHAMPION_RIVAL`
|
||||
is set, using `ProfOakData`'s three starter-matched teams (the team is
|
||||
picked by the type that counters your starter, mirroring the rival).
|
||||
- The Celadon Game Corner Chief battles you in his house post-game.
|
||||
`ChiefData` is empty in the ROM, so `OPP_CHIEF` is given a
|
||||
reconstructed party.
|
||||
|
||||
This is an intentional divergence: neither battle can be triggered in the
|
||||
original game.
|
||||
|
||||
## Reimplemented unused Silph Co. card-key doors
|
||||
|
||||
`engine/events/card_key.asm` and the unused `CardKeyTable1/2/3` coordinate
|
||||
lists (`data/events/card_key_coords.asm`) describe locked doors for Silph
|
||||
Co. floors 2F-11F, but no retail `.blk` map layout ever places the closed
|
||||
door block at those coordinates, so the card key check is dead code in
|
||||
the original game. This project stamps the closed door block (`$54`/`$5f`
|
||||
on floors 2F-10F, `$20` on 11F) over each of the 20 door coordinates on
|
||||
map load, and swaps it for the open block once that door's
|
||||
`EVENT_SILPH_CO_n_UNLOCKED_DOORn` flag is set (using the key from a Team
|
||||
Rocket grunt, as in the original's unused design).
|
||||
|
||||
This is an intentional divergence: the doors are not visible or
|
||||
functional in the original game. The door layout lives in
|
||||
`tools/rom_manifest.json` (`field.cardKeyDoors.closedDoors`), hand-ported
|
||||
since no retail ROM data encodes it; `src/import/RomExtractor.lua` copies
|
||||
it straight through on ROM import.
|
||||
|
||||
@@ -17,3 +17,33 @@ Regenerate the reference straight into a wiki checkout:
|
||||
```sh
|
||||
luajit tools/gen_registry_docs.lua ../pokemon-gen1-recomp-project.wiki
|
||||
```
|
||||
|
||||
## Developer console
|
||||
|
||||
Boot with developer mode on to unlock the in-game console and hot-reload
|
||||
hotkeys. Either set `POKEPORT_DEV=1` in the environment or pass
|
||||
`--developer` on the command line:
|
||||
|
||||
```sh
|
||||
love . --developer
|
||||
```
|
||||
|
||||
While developer mode is active:
|
||||
|
||||
- `` ` `` (backtick) opens the console overlay — a Lua REPL with `game`,
|
||||
`data` and `mods` in scope. Press `` ` `` again to close it.
|
||||
- `F5` hot-reloads mods and asset caches without restarting.
|
||||
|
||||
The console understands these verbs (anything else is evaluated as Lua):
|
||||
|
||||
- `warp MAP [x y]` — teleport to a map (default cell 5,5).
|
||||
- `give ID [n|level]` — add an item (count) or a Pokémon (level).
|
||||
- `flag NAME [on|off]` — read or set an event flag.
|
||||
- `party` — dump the current party.
|
||||
- `mods` — list loaded mods and their state.
|
||||
- `reload` — hot-reload mods (same as `F5`).
|
||||
- `trace PAT | trace off` — trace events/hooks matching a glob pattern.
|
||||
- `help` — list the verbs.
|
||||
|
||||
Developer mode also arms the mod loader's dev tripwire, which flags mods
|
||||
that reach outside their permission set.
|
||||
|
||||
+29
-12
@@ -42,8 +42,10 @@ Game Boy equivalent:
|
||||
rows above the player recede and rows below come toward the viewer. Only
|
||||
things that actually *stand* on the ground draw as upright billboards,
|
||||
unscaled and pixel-identical to flat mode: the player, NPCs, item balls,
|
||||
and the screen-anchored FX attached to them (heal machine glow, emote
|
||||
bubbles, the fishing rod, the FLY bird). An earlier revision tried
|
||||
and the standing FX attached to them (emote bubbles, the fishing rod,
|
||||
the FLY bird). The Poké Center heal-machine overlay stays on the ground
|
||||
plane with the machine tiles (it is OAM glued to a BG graphic, not a
|
||||
standing sprite). An earlier revision tried
|
||||
billboarding buildings/trees/signs too (cutting them out of the ground
|
||||
per hand-curated per-tileset tables); that chased an endless tail of
|
||||
special cases, dense tree canopy, fences fused into grass, building
|
||||
@@ -68,19 +70,31 @@ Game Boy equivalent:
|
||||
|
||||
## Colors mode
|
||||
|
||||
The `2` key (and the Options menu COLORS row) cycles the global shade-remap
|
||||
display mode through **GBC → OG → OG INV → GBC INV → CLASSIC → GBC**:
|
||||
The `2` key (and the Options menu COLORS row) cycles the display mode
|
||||
through **OG RED → SGB → RED++ → OG → OG INV → SGB INV → CLASSIC → OG RED**.
|
||||
The first three are the real colorizations; the rest are DMG-shade novelties:
|
||||
|
||||
- **GBC** (default): current SGB / GBC zone palettes.
|
||||
- **OG RED**: the Game Boy Color boot-ROM look for Pokemon Red -- one global
|
||||
red BG palette + one green OBJ palette, every map, no per-map variation
|
||||
(Pokemon Red has no CGB code, so on a GBC the boot ROM colors it globally).
|
||||
The player/NPCs stay green over the red terrain via the OBP bake +
|
||||
post-zone redraw (`PaletteFX.GBC_BG` / `GBC_OBJ`).
|
||||
- **SGB** (default): the per-map Super Game Boy region palettes
|
||||
(`data/sgb/sgb_palettes.asm`). Sprites tint with the region palette, as on
|
||||
real SGB. (This is the mode formerly mislabeled "GBC".)
|
||||
- **RED++**: pokered-gbc SuperPalettes -- real per-tile GBC coloring plus
|
||||
per-species mon colors (`data/palettes_gbc.lua`).
|
||||
- **OG**: force the four DMG grays (colorization off).
|
||||
- **OG INV**: inverted DMG grays.
|
||||
- **GBC INV**: each SGB zone palette with shade order reversed.
|
||||
- **SGB INV**: each SGB zone palette with shade order reversed.
|
||||
- **CLASSIC**: original Game Boy pea-soup greens
|
||||
(`#9BBC0F` / `#8BAC0F` / `#306230` / `#0F380F`).
|
||||
|
||||
The transform is applied centrally in `PaletteFX.sendColors`, so it covers
|
||||
overworld, menus, battles, and tilt upright billboards. Persisted as
|
||||
`save.options.colors`.
|
||||
The shade-remap transform is applied centrally in `PaletteFX.sendColors`, so
|
||||
it covers overworld, menus, battles, and tilt upright billboards. OG RED's
|
||||
global BG palette is supplied by `OverworldState:overworldBgColors` (per-map
|
||||
override in the overworld pass). Persisted as `save.options.colors`; the
|
||||
`gbc` / `gbc_inv` save ids are kept for back-compat under the new labels.
|
||||
|
||||
## GBC FX
|
||||
|
||||
@@ -132,7 +146,10 @@ migrated once into `options.lua` on load.
|
||||
- Music / SFX volume
|
||||
- Music Filter
|
||||
- OG GLITCHES on / off (Gen 1 quirks vs. modern-clean battle rules)
|
||||
- COLORS (GBC / RED++ / OG / OG INV / GBC INV / CLASSIC), also hotkey `2`
|
||||
(RED++ uses pokered-gbc SuperPalettes + per-species mon colors)
|
||||
- COLORS (OG RED / SGB / RED++ / OG / OG INV / SGB INV / CLASSIC), also
|
||||
hotkey `2` (OG RED = GBC boot-ROM look; RED++ uses pokered-gbc
|
||||
SuperPalettes + per-species mon colors)
|
||||
- TILT (OFF / 15 / 35 / 50), also hotkey `3` while free-roaming
|
||||
- GBC FX (OFF / 1 / 2 / 3 / 4), also hotkey `5`
|
||||
- GBC FX (OFF / 1 / 2 / 3 / 4), also hotkey `5`
|
||||
- MAX FPS (30 / 40 / 50 / 60 / 75 / 90 / 100 / 120 / 144 / 160, default 60),
|
||||
a hard render frame-rate cap (`save.options.fpsCap`).
|
||||
@@ -26,7 +26,19 @@ local function scriptedIterations()
|
||||
return math.max(1, math.floor(require("src.core.GameSpeed").clamp(speedOverride)))
|
||||
end
|
||||
|
||||
local function bootGame()
|
||||
local function bootGame(version)
|
||||
-- The launcher hands us the chosen game (Red / Blue); scripted and headless
|
||||
-- runs fall back to POKEPORT_VERSION, then Red. Set the active version and
|
||||
-- overlay its extracted cache BEFORE anything requires generated data, so
|
||||
-- data/generated + assets/generated resolve to that version's files.
|
||||
local GameVersion = require("src.core.GameVersion")
|
||||
GameVersion.set(version or os.getenv("POKEPORT_VERSION") or "red")
|
||||
require("src.import.CacheFs").mountVersion(GameVersion.get())
|
||||
if love.window and love.window.setTitle then
|
||||
local Version = require("src.core.Version")
|
||||
love.window.setTitle(Version.title(
|
||||
GameVersion.info().displayName .. " (Gen 1 Recompilation Project)"))
|
||||
end
|
||||
Game = require("src.core.Game")
|
||||
Game:load()
|
||||
if os.getenv("POKEPORT_AUTOPILOT") then
|
||||
@@ -48,6 +60,8 @@ function love.load(args)
|
||||
for i, a in ipairs(args or {}) do
|
||||
if a == "--editor" then
|
||||
editorMode = true
|
||||
elseif a == "--developer" then
|
||||
_G.POKEPORT_DEV_MODE = true
|
||||
elseif a == "--save" and args[i + 1] and args[i + 1] ~= "" then
|
||||
savePath = args[i + 1]
|
||||
elseif a == "--speed" and tonumber(args[i + 1]) then
|
||||
@@ -66,20 +80,46 @@ function love.load(args)
|
||||
end
|
||||
|
||||
local RomImporter = require("src.import.RomImporter")
|
||||
if os.getenv("POKEPORT_FORCE_IMPORT") == "1" or not RomImporter.isReady() then
|
||||
Importer = RomImporter.new(function()
|
||||
if os.getenv("POKEPORT_IMPORT_ONLY") == "1" then
|
||||
love.event.quit()
|
||||
return
|
||||
end
|
||||
Importer = nil
|
||||
bootGame()
|
||||
end)
|
||||
local importPath = os.getenv("POKEPORT_IMPORT_ROM")
|
||||
if importPath then Importer:startPath(importPath) end
|
||||
local forceImport = os.getenv("POKEPORT_FORCE_IMPORT") == "1"
|
||||
local importPath = os.getenv("POKEPORT_IMPORT_ROM")
|
||||
-- Scripted / headless runs pick their game from POKEPORT_VERSION (default
|
||||
-- Red); the launcher's per-column choice does not apply to them.
|
||||
local scriptedVersion = os.getenv("POKEPORT_VERSION") or "red"
|
||||
local ready = RomImporter.isReady(scriptedVersion)
|
||||
-- Scripted / headless runs have to reach the game with no human pressing
|
||||
-- Play: an autopilot, a frame driver, an import-only build step, or an
|
||||
-- explicit ROM path all bypass the interactive launcher and keep today's
|
||||
-- import-then-boot (or boot-straight-in) behavior.
|
||||
local scripted = os.getenv("POKEPORT_AUTOPILOT") or os.getenv("POKEPORT_DRIVER")
|
||||
or os.getenv("POKEPORT_IMPORT_ONLY") == "1" or importPath ~= nil
|
||||
|
||||
if scripted then
|
||||
if forceImport or not ready then
|
||||
-- The importer detects the dropped/loaded ROM's version by SHA-1 and
|
||||
-- passes it to onComplete; boot that version.
|
||||
Importer = RomImporter.new(function(version)
|
||||
if os.getenv("POKEPORT_IMPORT_ONLY") == "1" then
|
||||
love.event.quit()
|
||||
return
|
||||
end
|
||||
Importer = nil
|
||||
bootGame(version or scriptedVersion)
|
||||
end)
|
||||
if importPath then Importer:startPath(importPath) end
|
||||
return
|
||||
end
|
||||
bootGame(scriptedVersion)
|
||||
return
|
||||
end
|
||||
bootGame()
|
||||
|
||||
-- Interactive: the launcher always runs. Red and Blue are each live: a
|
||||
-- column shows Play when that game's ROM is already imported, or Choose ROM
|
||||
-- / drag-drop when it is not (Yellow is still a placeholder). Any dropped
|
||||
-- .gb is routed to Red or Blue by its SHA-1; pressing Play boots that game.
|
||||
Importer = RomImporter.new(function(version)
|
||||
Importer = nil
|
||||
bootGame(version)
|
||||
end, { launcher = true, forceImport = forceImport })
|
||||
end
|
||||
|
||||
function love.update(dt)
|
||||
@@ -171,6 +211,31 @@ function love.gamepadaxis(joystick, axis, value)
|
||||
Game:gamepadaxis(joystick, axis, value)
|
||||
end
|
||||
|
||||
function love.joystickremoved(joystick)
|
||||
if editorMode then return end
|
||||
if Importer then return end
|
||||
Game:joystickremoved(joystick)
|
||||
end
|
||||
|
||||
-- f is true on focus gained, false on focus lost (e.g. alt-tab). A held
|
||||
-- direction's key-up can be delivered to the OS instead of the game while
|
||||
-- unfocused, so reset input on either transition rather than trust it.
|
||||
function love.focus(f)
|
||||
if editorMode then return end
|
||||
if Importer then
|
||||
if Importer.focus then Importer:focus(f) end
|
||||
return
|
||||
end
|
||||
Game:focus(f)
|
||||
end
|
||||
|
||||
-- v is true when the window becomes visible again, false on minimize.
|
||||
function love.visible(v)
|
||||
if editorMode then return end
|
||||
if Importer then return end
|
||||
Game:visible(v)
|
||||
end
|
||||
|
||||
function love.touchpressed(id, x, y, dx, dy, pressure)
|
||||
if editorMode then return end
|
||||
if Importer then return Importer:mousepressed(x, y, 1) end
|
||||
@@ -234,3 +299,78 @@ function love.filedropped(file)
|
||||
end
|
||||
if Importer then Importer:filedropped(file) end
|
||||
end
|
||||
|
||||
local function pacingEnabled()
|
||||
if os.getenv("POKEPORT_AUTOPILOT") then return false end
|
||||
if os.getenv("POKEPORT_DRIVER") then return false end
|
||||
if os.getenv("POKEPORT_IMPORT_ONLY") == "1" then return false end
|
||||
return true
|
||||
end
|
||||
|
||||
function love.run()
|
||||
if love.load then love.load(love.arg.parseGameArguments(arg), arg) end
|
||||
|
||||
-- don't let love.load's cost land in the first frame's dt
|
||||
if love.timer then love.timer.step() end
|
||||
|
||||
local FrameCap = require("src.core.FrameCap")
|
||||
local paced = pacingEnabled()
|
||||
-- The deadline the next present() should not beat. Carried forward one
|
||||
-- budget per frame so pacing stays even instead of drifting with the
|
||||
-- per-frame sleep-granularity jitter.
|
||||
local nextFrame = love.timer and love.timer.getTime() or 0
|
||||
local dt = 0
|
||||
|
||||
return function()
|
||||
-- process events
|
||||
if love.event then
|
||||
love.event.pump()
|
||||
for name, a, b, c, d, e, f in love.event.poll() do
|
||||
if name == "quit" then
|
||||
if not love.quit or not love.quit() then
|
||||
return a or 0
|
||||
end
|
||||
end
|
||||
love.handlers[name](a, b, c, d, e, f)
|
||||
end
|
||||
end
|
||||
|
||||
-- update dt
|
||||
if love.timer then dt = love.timer.step() end
|
||||
|
||||
-- call update and draw
|
||||
if love.update then love.update(dt) end
|
||||
|
||||
if love.graphics and love.graphics.isActive() then
|
||||
love.graphics.origin()
|
||||
love.graphics.clear(love.graphics.getBackgroundColor())
|
||||
if love.draw then love.draw() end
|
||||
love.graphics.present()
|
||||
end
|
||||
|
||||
if love.timer then
|
||||
if paced then
|
||||
-- Sleep out the remainder of the frame budget, measured from the
|
||||
-- carried deadline, in small chunks so the OS timer stays
|
||||
-- responsive. vsync is untouched: when it already paces slower
|
||||
-- than the cap the remainder is <= 0 and this rounds to a no-op.
|
||||
local budget = 1 / FrameCap.current
|
||||
nextFrame = nextFrame + budget
|
||||
local now = love.timer.getTime()
|
||||
-- A stall (alt-tab, a GC pause, a blocked import) can leave the
|
||||
-- deadline more than a full budget in the past; re-anchor to now so
|
||||
-- we pace the next frame rather than burst uncapped to catch up.
|
||||
if now - nextFrame > budget then
|
||||
nextFrame = now
|
||||
end
|
||||
while true do
|
||||
local remaining = nextFrame - love.timer.getTime()
|
||||
if remaining <= 0 then break end
|
||||
love.timer.sleep(remaining < 0.001 and remaining or 0.001)
|
||||
end
|
||||
else
|
||||
love.timer.sleep(0.001)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+15
-19
@@ -27,17 +27,17 @@ refresh is safe, just rebuild.
|
||||
## Build
|
||||
|
||||
```bash
|
||||
# Debug APK (default Android debug keystore)
|
||||
# Build the APK
|
||||
scripts/build_android.sh
|
||||
|
||||
# Release APK (signing is manual, see below)
|
||||
scripts/build_android.sh --release
|
||||
# Build the APK, setting app.version_name/app.version_code to match a release
|
||||
scripts/build_android.sh --version 0.2.5
|
||||
|
||||
# Zip game.love + branding only (no Android SDK required)
|
||||
scripts/build_android.sh --package-only
|
||||
```
|
||||
|
||||
Or via `scripts/build.sh android`.
|
||||
Or via `scripts/build.sh android [--version X.Y.Z]`.
|
||||
|
||||
The embedded `game.love` deliberately excludes `data/generated/`,
|
||||
`assets/generated/`, and any ROM. It contains the first-boot Lua importer and
|
||||
@@ -59,12 +59,10 @@ Set `ANDROID_SDK_ROOT` (or `ANDROID_HOME`), or let the script write
|
||||
`local.properties` when it finds `~/Library/Android/sdk`.
|
||||
|
||||
Gradle flavor used: **`embedNoRecord`** (game fused into the APK, no microphone).
|
||||
Build task: `assembleEmbedNoRecordDebug`.
|
||||
|
||||
- Debug task: `assembleEmbedNoRecordDebug`
|
||||
- Release task: `assembleEmbedNoRecordRelease`
|
||||
|
||||
APKs land under `app/build/outputs/apk/embedNoRecord/{debug,release}/`.
|
||||
`scripts/build_android.sh` also copies the built APK(s) to `dist/android/{debug,release}/`.
|
||||
The APK lands under `app/build/outputs/apk/embedNoRecord/debug/`.
|
||||
`scripts/build_android.sh` also copies it to `dist/android/debug/`.
|
||||
|
||||
### Payload path
|
||||
|
||||
@@ -79,17 +77,15 @@ scripts, tests, and mobile build sources are excluded.
|
||||
| `app.application_id` | `com.theboisclub.pokemonred` |
|
||||
| `app.name` | Pokemon Red |
|
||||
| `app.orientation` | `portrait` |
|
||||
| `app.version_name` / `app.version_code` | set from `--version X.Y.Z` (code = major*10000 + minor*100 + patch); left as-is if `--version` is omitted |
|
||||
| Permissions | INTERNET / RECORD_AUDIO / WRITE_EXTERNAL_STORAGE stripped; VIBRATE + BLUETOOTH kept |
|
||||
|
||||
## Releases
|
||||
|
||||
`.github/workflows/release.yml` builds the APK with `--version` set to the
|
||||
release version and publishes it alongside the macOS/Windows/Linux builds as
|
||||
`PokemonRed-<version>-android.apk`.
|
||||
|
||||
## Signing
|
||||
|
||||
- **Debug**: default Android debug keystore (no setup).
|
||||
- **Release**: out-of-band. Create a keystore yourself and wire it into
|
||||
`app/build.gradle`, **do not commit keystores or passwords**.
|
||||
|
||||
Example (placeholder only):
|
||||
|
||||
```bash
|
||||
keytool -genkey -v -keystore /path/to/pokemonred-release.jks \
|
||||
-alias pokemonred -keyalg RSA -keysize 2048 -validity 10000
|
||||
```
|
||||
Signed with the default Android keystore (no setup required).
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
#app.name=LÖVE for Android
|
||||
|
||||
app.application_id=com.theboisclub.pokemonred
|
||||
app.orientation=portrait
|
||||
# fullUser: allow every orientation the player's device permits (portrait and
|
||||
# landscape), honouring their auto-rotate lock. Was "portrait" (locked).
|
||||
app.orientation=fullUser
|
||||
app.version_code=32
|
||||
app.version_name=11.5a
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
*.[oa]
|
||||
# Prebuilt vendored static libs Android.mk links against directly (not
|
||||
# built by the Gradle/NDK build itself) -- must stay tracked or a fresh
|
||||
# checkout fails ndk-build with "LOCAL_SRC_FILES points to a missing file".
|
||||
!android/*/libluajit.a
|
||||
*.so
|
||||
*.obj
|
||||
*.lib
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -36,6 +36,7 @@ demos
|
||||
*~
|
||||
Makefile*
|
||||
config*
|
||||
!src/common/config.h
|
||||
libtool
|
||||
/platform/unix/ar-lib
|
||||
/platform/unix/compile
|
||||
|
||||
@@ -183,6 +183,18 @@ void vibrate(double seconds)
|
||||
env->DeleteLocalRef(activity);
|
||||
}
|
||||
|
||||
bool showFilePicker()
|
||||
{
|
||||
JNIEnv *env = (JNIEnv*) SDL_AndroidGetJNIEnv();
|
||||
jclass activity = env->FindClass("org/love2d/android/GameActivity");
|
||||
|
||||
jmethodID method = env->GetStaticMethodID(activity, "showRomFilePicker", "()Z");
|
||||
jboolean result = env->CallStaticBooleanMethod(activity, method);
|
||||
|
||||
env->DeleteLocalRef(activity);
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* Helper functions for the filesystem module
|
||||
*/
|
||||
|
||||
@@ -59,6 +59,14 @@ bool openURL(const std::string &url);
|
||||
|
||||
void vibrate(double seconds);
|
||||
|
||||
/**
|
||||
* Shows the system's "pick a document" UI (Storage Access Framework).
|
||||
* Returns true if the picker was launched; the picked file (if any) is
|
||||
* copied asynchronously by GameActivity.onActivityResult into the app's
|
||||
* external save directory, not returned here -- see src/import/RomImporter.lua.
|
||||
**/
|
||||
bool showFilePicker();
|
||||
|
||||
/*
|
||||
* Helper functions for the filesystem module
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Copyright (c) 2006-2023 LOVE Development Team
|
||||
*
|
||||
* This software is provided 'as-is', without any express or implied
|
||||
* warranty. In no event will the authors be held liable for any damages
|
||||
* arising from the use of this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software for any purpose,
|
||||
* including commercial applications, and to alter it and redistribute it
|
||||
* freely, subject to the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be misrepresented; you must not
|
||||
* claim that you wrote the original software. If you use this software
|
||||
* in a product, an acknowledgment in the product documentation would be
|
||||
* appreciated but is not required.
|
||||
* 2. Altered source versions must be plainly marked as such, and must not be
|
||||
* misrepresented as being the original software.
|
||||
* 3. This notice may not be removed or altered from any source distribution.
|
||||
**/
|
||||
|
||||
#ifndef LOVE_CONFIG_H
|
||||
#define LOVE_CONFIG_H
|
||||
|
||||
// Platform stuff.
|
||||
#if defined(WIN32) || defined(_WIN32)
|
||||
# define LOVE_WINDOWS 1
|
||||
// If _USING_V110_SDK71_ is defined it means we are using the xp toolset.
|
||||
# if defined(_MSC_VER) && (_MSC_VER >= 1700) && !_USING_V110_SDK71_
|
||||
# include <winapifamily.h>
|
||||
# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
|
||||
# define LOVE_WINDOWS_UWP 1
|
||||
# define LOVE_NO_MODPLUG 1
|
||||
# define LOVE_NOMPG123 1
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
#if defined(linux) || defined(__linux) || defined(__linux__)
|
||||
# define LOVE_LINUX 1
|
||||
#endif
|
||||
#if defined(__ANDROID__)
|
||||
# define LOVE_ANDROID 1
|
||||
#endif
|
||||
#if defined(__APPLE__)
|
||||
# include <TargetConditionals.h>
|
||||
# if TARGET_OS_IPHONE
|
||||
# define LOVE_IOS 1
|
||||
# elif TARGET_OS_MAC
|
||||
# define LOVE_MACOSX 1
|
||||
# endif
|
||||
#endif
|
||||
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
|
||||
// I know it's not linux, but it seems most "linux-only" code is bsd-compatible
|
||||
# define LOVE_LINUX 1
|
||||
#endif
|
||||
|
||||
// Endianness.
|
||||
#if defined(__ppc__) || defined(__ppc) || defined(__powerpc__) || defined(__powerpc)
|
||||
# define LOVE_BIG_ENDIAN 1
|
||||
#else
|
||||
# define LOVE_LITTLE_ENDIAN 1
|
||||
#endif
|
||||
|
||||
// SSE instructions.
|
||||
#if defined(__SSE__)
|
||||
# define LOVE_SIMD_SSE
|
||||
#elif defined(_MSC_VER)
|
||||
# if defined(_M_AMD64) || defined(_M_X64)
|
||||
# define LOVE_SIMD_SSE
|
||||
# elif _M_IX86_FP
|
||||
# define LOVE_SIMD_SSE
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// NEON instructions.
|
||||
#if defined(__ARM_NEON)
|
||||
# define LOVE_SIMD_NEON
|
||||
#endif
|
||||
|
||||
// Warnings.
|
||||
#ifndef _CRT_SECURE_NO_WARNINGS
|
||||
# define _CRT_SECURE_NO_WARNINGS
|
||||
#endif
|
||||
|
||||
// Preferably, and ironically, this macro should go unused.
|
||||
#ifndef LOVE_UNUSED
|
||||
# define LOVE_UNUSED(x) (void)sizeof(x)
|
||||
#endif
|
||||
|
||||
|
||||
// Warn on unused return values
|
||||
#ifdef __GNUC__
|
||||
# define LOVE_WARN_UNUSED __attribute__((warn_unused_result))
|
||||
#elif _MSC_VER
|
||||
# define LOVE_WARN_UNUSED _Check_return_
|
||||
#else
|
||||
# define LOVE_WARN_UNUSED
|
||||
#endif
|
||||
|
||||
#ifndef LOVE_BUILD
|
||||
# define LOVE_BUILD
|
||||
# define LOVE_BUILD_STANDALONE
|
||||
# define LOVE_BUILD_EXE
|
||||
//# define LOVE_BUILD_DLL
|
||||
#endif
|
||||
|
||||
// DLL-stuff.
|
||||
#if defined(_MSC_VER) || defined(__MINGW32__)
|
||||
# define LOVE_EXPORT __declspec(dllexport)
|
||||
#elif defined(__GNUC__) || defined(__clang__)
|
||||
# define LOVE_EXPORT __attribute__((visibility("default")))
|
||||
#else
|
||||
# define LOVE_EXPORT
|
||||
#endif
|
||||
|
||||
#if defined(LOVE_WINDOWS)
|
||||
#ifndef LOVE_WINDOWS_UWP
|
||||
# define LOVE_LEGENDARY_CONSOLE_IO_HACK
|
||||
#endif // LOVE_WINDOWS_UWP
|
||||
#ifndef __MINGW32__
|
||||
# define NOMINMAX
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(LOVE_MACOSX) || defined(LOVE_IOS)
|
||||
# define LOVE_LEGENDARY_APP_ARGV_HACK
|
||||
#endif
|
||||
|
||||
#if defined(LOVE_ANDROID) || defined(LOVE_IOS)
|
||||
# define LOVE_LEGENDARY_ACCELEROMETER_AS_JOYSTICK_HACK
|
||||
#endif
|
||||
|
||||
// Autotools config.h
|
||||
#ifdef HAVE_CONFIG_H
|
||||
# include <../config.h>
|
||||
# undef VERSION
|
||||
# ifdef WORDS_BIGENDIAN
|
||||
# undef LOVE_LITTLE_ENDIAN
|
||||
# define LOVE_BIG_ENDIAN 1
|
||||
# else
|
||||
# undef LOVE_BIG_ENDIAN
|
||||
# define LOVE_LITTLE_ENDIAN 1
|
||||
# endif
|
||||
#else
|
||||
# define LOVE_ENABLE_LOVE
|
||||
# define LOVE_ENABLE_AUDIO
|
||||
# define LOVE_ENABLE_DATA
|
||||
# define LOVE_ENABLE_EVENT
|
||||
# define LOVE_ENABLE_FILESYSTEM
|
||||
# define LOVE_ENABLE_FONT
|
||||
# define LOVE_ENABLE_GRAPHICS
|
||||
# define LOVE_ENABLE_IMAGE
|
||||
# define LOVE_ENABLE_JOYSTICK
|
||||
# define LOVE_ENABLE_KEYBOARD
|
||||
# define LOVE_ENABLE_MATH
|
||||
# define LOVE_ENABLE_MOUSE
|
||||
# define LOVE_ENABLE_PHYSICS
|
||||
# define LOVE_ENABLE_SOUND
|
||||
# define LOVE_ENABLE_SYSTEM
|
||||
# define LOVE_ENABLE_THREAD
|
||||
# define LOVE_ENABLE_TIMER
|
||||
# define LOVE_ENABLE_TOUCH
|
||||
# define LOVE_ENABLE_VIDEO
|
||||
# define LOVE_ENABLE_WINDOW
|
||||
|
||||
# define LOVE_ENABLE_ENET
|
||||
# define LOVE_ENABLE_LUASOCKET
|
||||
# define LOVE_ENABLE_LUA53
|
||||
#endif
|
||||
|
||||
// Check we have a sane configuration
|
||||
#if !defined(LOVE_WINDOWS) && !defined(LOVE_LINUX) && !defined(LOVE_IOS) && !defined(LOVE_MACOSX) && !defined(LOVE_ANDROID)
|
||||
# error Could not detect target platform
|
||||
#endif
|
||||
#if !defined(LOVE_LITTLE_ENDIAN) && !defined(LOVE_BIG_ENDIAN)
|
||||
# error Could not detect endianness
|
||||
#endif
|
||||
|
||||
#endif // LOVE_CONFIG_H
|
||||
@@ -186,6 +186,18 @@ bool Filesystem::setIdentity(const char *ident, bool appendToPath)
|
||||
|
||||
save_path_full = storage_path + std::string("/save/") + save_identity;
|
||||
|
||||
// love::android::mkdir is a single mkdir(), not mkdir -p: on a genuinely
|
||||
// first-ever launch (nothing has touched this app's external-files dir
|
||||
// before) save_directory doesn't exist yet either, so creating
|
||||
// save_path_full in one step fails with ENOENT and PHYSFS_mount below
|
||||
// silently never mounts anything for the rest of this process -- not
|
||||
// just the save dir, but everything routed through it (save.lua/
|
||||
// options.lua, the ROM-derived asset cache, RomImporter's Android
|
||||
// folder scan). Ensure each level exists in order instead.
|
||||
if (!love::android::directoryExists(save_directory.c_str()) &&
|
||||
!love::android::mkdir(save_directory.c_str()))
|
||||
SDL_Log("Error: Could not create save directory %s!", save_directory.c_str());
|
||||
|
||||
if (!love::android::directoryExists(save_path_full.c_str()) &&
|
||||
!love::android::mkdir(save_path_full.c_str()))
|
||||
SDL_Log("Error: Could not create save directory %s!", save_path_full.c_str());
|
||||
@@ -338,6 +350,26 @@ bool Filesystem::setupWriteDirectory()
|
||||
std::string temp_writedir = getDriveRoot(save_path_full);
|
||||
std::string temp_createdir = skipDriveRoot(save_path_full);
|
||||
|
||||
#ifdef LOVE_ANDROID
|
||||
// getUserDirectory() falls back to $HOME/getpwuid() (physfs_platform_posix.c),
|
||||
// which is meaningless on Android and unrelated to save_path_full (an
|
||||
// SDL_AndroidGet*StoragePath() subdirectory -- see setIdentity above), so
|
||||
// the generic check below never matches and falls through to setting the
|
||||
// write dir to the drive root ("/"), which no Android app can write to.
|
||||
// Anchor to the real Android storage root instead.
|
||||
std::string androidStorageRoot = isAndroidSaveExternal()
|
||||
? SDL_AndroidGetExternalStoragePath() : SDL_AndroidGetInternalStoragePath();
|
||||
if (save_path_full.find(androidStorageRoot) == 0)
|
||||
{
|
||||
temp_writedir = androidStorageRoot;
|
||||
temp_createdir = save_path_full.substr(androidStorageRoot.length());
|
||||
|
||||
size_t startpos = temp_createdir.find_first_not_of('/');
|
||||
if (startpos != std::string::npos)
|
||||
temp_createdir = temp_createdir.substr(startpos);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
// On some sandboxed platforms, physfs will break when its write directory
|
||||
// is the root of the drive and it tries to create a folder (even if the
|
||||
// folder's path is in a writable location.) If the user's home folder is
|
||||
|
||||
@@ -180,6 +180,15 @@ void System::vibrate(double seconds) const
|
||||
#endif
|
||||
}
|
||||
|
||||
bool System::pickFile() const
|
||||
{
|
||||
#ifdef LOVE_ANDROID
|
||||
return love::android::showFilePicker();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool System::hasBackgroundMusic() const
|
||||
{
|
||||
#if defined(LOVE_ANDROID)
|
||||
|
||||
@@ -106,6 +106,15 @@ public:
|
||||
*/
|
||||
virtual void vibrate(double seconds) const;
|
||||
|
||||
/**
|
||||
* Shows the platform's native "pick a file" UI, if one is available.
|
||||
* Android only for now; the result (if any) is not returned here -- see
|
||||
* love::android::showFilePicker and src/import/RomImporter.lua.
|
||||
*
|
||||
* @return Whether the picker was shown.
|
||||
**/
|
||||
virtual bool pickFile() const;
|
||||
|
||||
/**
|
||||
* Gets if the user is playing music on background.
|
||||
* Throws an exception on unsupported platforms.
|
||||
|
||||
@@ -95,6 +95,12 @@ int w_vibrate(lua_State *L)
|
||||
return 0;
|
||||
}
|
||||
|
||||
int w_pickFile(lua_State *L)
|
||||
{
|
||||
luax_pushboolean(L, instance()->pickFile());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int w_hasBackgroundMusic(lua_State *L)
|
||||
{
|
||||
lua_pushboolean(L, instance()->hasBackgroundMusic());
|
||||
@@ -110,6 +116,7 @@ static const luaL_Reg functions[] =
|
||||
{ "getPowerInfo", w_getPowerInfo },
|
||||
{ "openURL", w_openURL },
|
||||
{ "vibrate", w_vibrate },
|
||||
{ "pickFile", w_pickFile },
|
||||
{ "hasBackgroundMusic", w_hasBackgroundMusic },
|
||||
{ 0, 0 }
|
||||
};
|
||||
|
||||
@@ -61,6 +61,13 @@ public class GameActivity extends SDLActivity {
|
||||
protected final int[] recordAudioRequestDummy = new int[1];
|
||||
public static final int EXTERNAL_STORAGE_REQUEST_CODE = 2;
|
||||
public static final int RECORD_AUDIO_REQUEST_CODE = 3;
|
||||
public static final int ROM_PICKER_REQUEST_CODE = 4;
|
||||
// Mirrors conf.lua's t.identity ("pokemon-love2d"): where the picked ROM
|
||||
// is dropped so RomImporter's existing folder scan finds it -- see
|
||||
// src/import/RomImporter.lua and Filesystem::setIdentity (sets Android's
|
||||
// save directory to getExternalFilesDir()/save/<identity>).
|
||||
private static final String ROM_SAVE_IDENTITY = "pokemon-love2d";
|
||||
private static final String PICKED_ROM_FILENAME = "picked_rom.gb";
|
||||
private static boolean immersiveActive = false;
|
||||
private static boolean needToCopyGameInArchive = false;
|
||||
private boolean storagePermissionUnnecessary = false;
|
||||
@@ -332,6 +339,64 @@ public class GameActivity extends SDLActivity {
|
||||
return openURL(url) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the system document picker (Storage Access Framework) so the
|
||||
* player can pick their ROM from anywhere (Downloads, Drive, etc.)
|
||||
* without needing to know where the app's external files folder is.
|
||||
* Requires API 19+ (ACTION_OPEN_DOCUMENT); the picked file (if any)
|
||||
* arrives later in onActivityResult, not synchronously here.
|
||||
*/
|
||||
@Keep
|
||||
public static boolean showRomFilePicker() {
|
||||
if (android.os.Build.VERSION.SDK_INT < 19) return false;
|
||||
GameActivity self = (GameActivity) mSingleton;
|
||||
if (self == null) return false;
|
||||
|
||||
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType("*/*");
|
||||
try {
|
||||
self.startActivityForResult(intent, ROM_PICKER_REQUEST_CODE);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
Log.d("GameActivity", "could not open ROM file picker: " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (requestCode != ROM_PICKER_REQUEST_CODE) return;
|
||||
if (resultCode != RESULT_OK || data == null || data.getData() == null) {
|
||||
Log.d("GameActivity", "ROM picker returned no file (cancelled?)");
|
||||
return;
|
||||
}
|
||||
|
||||
Uri uri = data.getData();
|
||||
File destDir = new File(new File(getExternalFilesDir(null), "save"), ROM_SAVE_IDENTITY);
|
||||
if (!destDir.exists() && !destDir.mkdirs()) {
|
||||
Log.d("GameActivity", "could not create " + destDir);
|
||||
return;
|
||||
}
|
||||
File destFile = new File(destDir, PICKED_ROM_FILENAME);
|
||||
|
||||
InputStream source;
|
||||
try {
|
||||
source = getContentResolver().openInputStream(uri);
|
||||
} catch (FileNotFoundException e) {
|
||||
Log.d("GameActivity", "could not open picked ROM: " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
if (source == null) {
|
||||
Log.d("GameActivity", "ContentResolver returned no stream for picked ROM");
|
||||
return;
|
||||
}
|
||||
if (!copyAssetFile(source, destFile.getPath())) {
|
||||
Log.d("GameActivity", "could not copy picked ROM to " + destFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a given file from the assets folder to the destination.
|
||||
*
|
||||
|
||||
@@ -62,10 +62,15 @@
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UTExportedTypeDeclarations</key>
|
||||
<array>
|
||||
|
||||
+101
-19
@@ -1,17 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Packages the LÖVE2D Pokémon Red port into distributable macOS and
|
||||
# Windows builds. Runs entirely on macOS (no cross-compiling needed,
|
||||
# the Windows build reuses LÖVE's prebuilt win64 binaries).
|
||||
# Packages the LÖVE2D Pokémon Red port into distributable macOS, Windows,
|
||||
# and Linux builds. Runs entirely on macOS (no cross-compiling needed,
|
||||
# the Windows and Linux builds reuse LÖVE's prebuilt win64 / AppImage
|
||||
# binaries, fusing our game.love onto them the same way love.exe does).
|
||||
#
|
||||
# Usage: scripts/build.sh [mac|win|android|ios|all] [--version X.Y.Z] [--identity "Developer ID Application: ..."]
|
||||
# Usage: scripts/build.sh [mac|win|linux|android|ios|all] [--version X.Y.Z] [--identity "Developer ID Application: ..."]
|
||||
# [--notary-profile NAME] [--no-notarize]
|
||||
# [--release] # android/ios: release config instead of debug
|
||||
# [--release] # ios only: release config instead of debug
|
||||
#
|
||||
# Output: dist/mac/PokemonRed-macos.zip
|
||||
# dist/win/PokemonRed-win64.zip
|
||||
# dist/android/{debug,release}/*.apk (full gradle output stays under
|
||||
# Output: dist/mac/gen1recomp-macos.zip
|
||||
# dist/win/gen1recomp-win64.zip
|
||||
# dist/linux/gen1recomp-linux.zip (fused x86_64 AppImage)
|
||||
# dist/android/debug/*.apk (full gradle output stays under
|
||||
# mobile/android/app/build/outputs/apk/embedNoRecord/)
|
||||
# dist/ios/<Config>-<sdk>/PokemonRed.app (full xcodebuild output stays
|
||||
# dist/ios/<Config>-<sdk>/gen1recomp.app (full xcodebuild output stays
|
||||
# under mobile/ios/build/Build/Products/)
|
||||
|
||||
set -euo pipefail
|
||||
@@ -23,15 +25,15 @@ WORK="$HERE/work"
|
||||
DIST="$ROOT/dist"
|
||||
ENTITLEMENTS="$ROOT/scripts/macos-entitlements.plist"
|
||||
|
||||
APP_NAME="PokemonRed"
|
||||
APP_NAME="gen1recomp"
|
||||
BUNDLE_ID="com.theboisclub.pokemonred"
|
||||
LOVE_VERSION="11.5"
|
||||
VERSION="$(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || echo dev)"
|
||||
VERSION_EXPLICIT=false
|
||||
IDENTITY=""
|
||||
TARGET="all"
|
||||
NOTARY_PROFILE="notary-profile"
|
||||
NOTARIZE=true
|
||||
ANDROID_RELEASE=false
|
||||
IOS_RELEASE=false
|
||||
|
||||
say() { printf '\033[1;32m==>\033[0m %s\n' "$*"; }
|
||||
@@ -40,25 +42,25 @@ fail() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
mac|win|android|ios|all) TARGET="$1" ;;
|
||||
--version) VERSION="$2"; shift ;;
|
||||
mac|win|linux|android|ios|all) TARGET="$1" ;;
|
||||
--version) VERSION="$2"; VERSION_EXPLICIT=true; shift ;;
|
||||
--identity) IDENTITY="$2"; shift ;;
|
||||
--notary-profile) NOTARY_PROFILE="$2"; shift ;;
|
||||
--no-notarize) NOTARIZE=false ;;
|
||||
--release) ANDROID_RELEASE=true; IOS_RELEASE=true ;;
|
||||
--release) IOS_RELEASE=true ;;
|
||||
*) fail "unknown argument: $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
mkdir -p "$CACHE" "$WORK" "$DIST/mac" "$DIST/win"
|
||||
mkdir -p "$CACHE" "$WORK" "$DIST/mac" "$DIST/win" "$DIST/linux"
|
||||
|
||||
# --------------------------------------------------------------- game.love
|
||||
say "packing game.love"
|
||||
LOVE_FILE="$WORK/game.love"
|
||||
rm -f "$LOVE_FILE"
|
||||
(cd "$ROOT" && zip -q -9 -r "$LOVE_FILE" \
|
||||
main.lua conf.lua src data assets tools/rom_manifest.json \
|
||||
main.lua conf.lua src data assets tools/rom_manifest.json tools/rom_manifest_blue.json \
|
||||
-x '*.DS_Store' 'data/generated/*' 'assets/generated/*')
|
||||
if unzip -Z1 "$LOVE_FILE" \
|
||||
| grep -Eq '^(data|assets)/generated/[^/]+|^(data|assets)/generated/.+/'; then
|
||||
@@ -139,11 +141,20 @@ build_win() {
|
||||
say "building Windows (win64) app"
|
||||
local zip_name="love-$LOVE_VERSION-win64.zip"
|
||||
local love_zip="$CACHE/$zip_name"
|
||||
# A cache hit only checks existence, not validity -- a prior run truncated
|
||||
# by a network drop mid-download (curl still leaves the partial file if
|
||||
# the exit code slips through) would otherwise be reused forever.
|
||||
if [ -f "$love_zip" ] && ! unzip -tqq "$love_zip" >/dev/null 2>&1; then
|
||||
warn "cached $zip_name is not a valid zip, removing and re-downloading"
|
||||
rm -f "$love_zip"
|
||||
fi
|
||||
if [ ! -f "$love_zip" ]; then
|
||||
say "downloading LÖVE $LOVE_VERSION win64 binaries"
|
||||
curl -fL --progress-bar \
|
||||
"https://github.com/love2d/love/releases/download/$LOVE_VERSION/$zip_name" \
|
||||
-o "$love_zip" || fail "download failed, check LOVE_VERSION or your network"
|
||||
unzip -tqq "$love_zip" >/dev/null 2>&1 \
|
||||
|| fail "downloaded $zip_name is not a valid zip (truncated download?)"
|
||||
fi
|
||||
|
||||
local extract_dir="$WORK/love-win64"
|
||||
@@ -167,12 +178,82 @@ build_win() {
|
||||
say "Windows build: $zip_out"
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------- Linux
|
||||
build_linux() {
|
||||
say "building Linux (x86_64 AppImage) app"
|
||||
local appimage_name="love-$LOVE_VERSION-x86_64.AppImage"
|
||||
local love_appimage="$CACHE/$appimage_name"
|
||||
# Same cache-validity gap as the win64 zip above: an AppImage is just an
|
||||
# ELF, so check the magic bytes before trusting a cached copy is complete.
|
||||
if [ -f "$love_appimage" ] && [ "$(head -c 4 "$love_appimage" | od -An -tx1 | tr -d ' \n')" != "7f454c46" ]; then
|
||||
warn "cached $appimage_name is not a valid ELF binary, removing and re-downloading"
|
||||
rm -f "$love_appimage"
|
||||
fi
|
||||
if [ ! -f "$love_appimage" ]; then
|
||||
say "downloading LÖVE $LOVE_VERSION Linux AppImage"
|
||||
curl -fL --progress-bar \
|
||||
"https://github.com/love2d/love/releases/download/$LOVE_VERSION/$appimage_name" \
|
||||
-o "$love_appimage" || fail "download failed, check LOVE_VERSION or your network"
|
||||
[ "$(head -c 4 "$love_appimage" | od -An -tx1 | tr -d ' \n')" = "7f454c46" ] \
|
||||
|| fail "downloaded $appimage_name is not a valid ELF binary (truncated download?)"
|
||||
fi
|
||||
chmod +x "$love_appimage"
|
||||
|
||||
# The Windows-style `cat love.exe game.love` fusion does NOT work here:
|
||||
# an AppImage is a small runtime ELF with a squashfs appended, and at
|
||||
# launch the runtime mounts the squashfs and executes bin/love from
|
||||
# *inside* it -- bytes appended to the outer file are never read, so
|
||||
# users would just get vanilla LÖVE's no-game screen. Instead, unpack
|
||||
# the squashfs, drop game.love in, point AppRun's FUSE_PATH hook at it
|
||||
# (the hook ships commented-out in LÖVE's official AppImage), and glue
|
||||
# runtime + repacked squashfs back together.
|
||||
command -v unsquashfs >/dev/null && command -v mksquashfs >/dev/null \
|
||||
|| fail "squashfs tools not found; install with: brew install squashfs"
|
||||
|
||||
# The squashfs starts right where the ELF ends:
|
||||
# e_shoff + e_shnum * e_shentsize (all little-endian in the ELF64 header).
|
||||
local e_shoff e_shentsize e_shnum sfs_offset
|
||||
e_shoff=$(od -An -j40 -N8 -tu8 "$love_appimage" | tr -d ' ')
|
||||
e_shentsize=$(od -An -j58 -N2 -tu2 "$love_appimage" | tr -d ' ')
|
||||
e_shnum=$(od -An -j60 -N2 -tu2 "$love_appimage" | tr -d ' ')
|
||||
sfs_offset=$((e_shoff + e_shentsize * e_shnum))
|
||||
[ "$(dd if="$love_appimage" bs=1 skip="$sfs_offset" count=4 2>/dev/null)" = "hsqs" ] \
|
||||
|| fail "no squashfs superblock at computed offset $sfs_offset (unexpected AppImage layout)"
|
||||
|
||||
local appdir="$WORK/linux-appdir"
|
||||
rm -rf "$appdir"
|
||||
unsquashfs -q -no-xattrs -o "$sfs_offset" -d "$appdir" "$love_appimage" >/dev/null
|
||||
|
||||
cp "$LOVE_FILE" "$appdir/game.love"
|
||||
sed -i '' 's|^#FUSE_PATH="$APPDIR/my_game.love"$|FUSE_PATH="$APPDIR/game.love"|' "$appdir/AppRun"
|
||||
grep -q '^FUSE_PATH="\$APPDIR/game.love"$' "$appdir/AppRun" \
|
||||
|| fail "failed to enable FUSE_PATH in AppRun (upstream AppRun changed?)"
|
||||
|
||||
# Match the upstream image's compression (gzip, 128K blocks) so the
|
||||
# bundled runtime can read it.
|
||||
local sfs_out="$WORK/game.squashfs"
|
||||
rm -f "$sfs_out"
|
||||
mksquashfs "$appdir" "$sfs_out" \
|
||||
-comp gzip -b 131072 -noappend -all-root -no-xattrs -quiet >/dev/null
|
||||
|
||||
local out_bin="$WORK/$APP_NAME-x86_64.AppImage"
|
||||
rm -f "$out_bin"
|
||||
head -c "$sfs_offset" "$love_appimage" > "$out_bin"
|
||||
cat "$sfs_out" >> "$out_bin"
|
||||
chmod +x "$out_bin"
|
||||
|
||||
local zip_out="$DIST/linux/$APP_NAME-linux.zip"
|
||||
rm -f "$zip_out"
|
||||
(cd "$WORK" && zip -q -9 -j "$zip_out" "$(basename "$out_bin")")
|
||||
say "Linux build: $zip_out"
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------- Android
|
||||
build_android() {
|
||||
say "building Android (delegating to scripts/build_android.sh)"
|
||||
local args=()
|
||||
if [ "$ANDROID_RELEASE" = true ]; then
|
||||
args+=(--release)
|
||||
if [ "$VERSION_EXPLICIT" = true ]; then
|
||||
args+=(--version "$VERSION")
|
||||
fi
|
||||
"$ROOT/scripts/build_android.sh" ${args[@]+"${args[@]}"}
|
||||
}
|
||||
@@ -190,9 +271,10 @@ build_ios() {
|
||||
case "$TARGET" in
|
||||
mac) build_mac ;;
|
||||
win) build_win ;;
|
||||
linux) build_linux ;;
|
||||
android) build_android ;;
|
||||
ios) build_ios ;;
|
||||
all) build_mac; build_win ;;
|
||||
all) build_mac; build_win; build_linux ;;
|
||||
esac
|
||||
|
||||
case "$TARGET" in
|
||||
|
||||
+31
-33
@@ -1,11 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Packages the LÖVE2D Pokémon Red port into an Android APK via love-android 11.5a.
|
||||
#
|
||||
# Usage: scripts/build_android.sh [--release] [--package-only]
|
||||
# Usage: scripts/build_android.sh [--version X.Y.Z] [--package-only]
|
||||
#
|
||||
# (default) assembleEmbedNoRecordDebug (debug keystore)
|
||||
# --release assembleEmbedNoRecordRelease (requires out-of-band signing)
|
||||
# --package-only zip game.love + apply branding; skip gradle
|
||||
# --version X.Y.Z set app.version_name / app.version_code (else left as-is)
|
||||
# --package-only zip game.love + apply branding; skip gradle
|
||||
#
|
||||
# Prerequisites:
|
||||
# - mobile/android vendored love-android tree at tag 11.5a (in-repo; see mobile/ANDROID.md)
|
||||
@@ -13,9 +12,8 @@
|
||||
# - JDK 17
|
||||
#
|
||||
# Output (after gradle):
|
||||
# dist/android/{debug,release}/*.apk (convenience copy)
|
||||
# dist/android/debug/*.apk (convenience copy)
|
||||
# mobile/android/app/build/outputs/apk/embedNoRecord/debug/*.apk
|
||||
# mobile/android/app/build/outputs/apk/embedNoRecord/release/*.apk
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
@@ -24,12 +22,12 @@ ANDROID_DIR="$ROOT/mobile/android"
|
||||
EMBED_ASSETS="$ANDROID_DIR/app/src/embed/assets"
|
||||
LOVE_FILE="$EMBED_ASSETS/game.love"
|
||||
DIST="$ROOT/dist/android"
|
||||
APP_NAME="Pokemon Red"
|
||||
APP_NAME="gen1recomp"
|
||||
APPLICATION_ID="com.theboisclub.pokemonred"
|
||||
LOVE_ANDROID_VERSION="11.5a"
|
||||
NDK_VERSION="25.2.9519653"
|
||||
|
||||
RELEASE=false
|
||||
VERSION=""
|
||||
PACKAGE_ONLY=false
|
||||
|
||||
say() { printf '\033[1;32m==>\033[0m %s\n' "$*"; }
|
||||
@@ -38,17 +36,29 @@ fail() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--release) RELEASE=true ;;
|
||||
--version) VERSION="$2"; shift ;;
|
||||
--package-only) PACKAGE_ONLY=true ;;
|
||||
-h|--help)
|
||||
sed -n '2,20p' "$0"
|
||||
exit 0
|
||||
;;
|
||||
*) fail "unknown argument: $1 (try --release or --package-only)" ;;
|
||||
*) fail "unknown argument: $1 (try --version X.Y.Z or --package-only)" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
VERSION_CODE=""
|
||||
if [ -n "$VERSION" ]; then
|
||||
if ! printf '%s' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then
|
||||
fail "invalid --version '$VERSION' (expected X.Y.Z)"
|
||||
fi
|
||||
major="${VERSION%%.*}"
|
||||
rest="${VERSION#*.}"
|
||||
minor="${rest%%.*}"
|
||||
patch="${rest##*.}"
|
||||
VERSION_CODE=$((major * 10000 + minor * 100 + patch))
|
||||
fi
|
||||
|
||||
# --------------------------------------------------------------- preconditions
|
||||
if [ ! -f "$ANDROID_DIR/settings.gradle" ] || [ ! -f "$ANDROID_DIR/gradlew" ]; then
|
||||
fail "love-android not found at mobile/android/.
|
||||
@@ -74,10 +84,10 @@ apply_android_branding() {
|
||||
|
||||
say "applying Android branding (gradle.properties + permission trim)"
|
||||
|
||||
python3 - "$props" "$APPLICATION_ID" "$APP_NAME" <<'PY'
|
||||
python3 - "$props" "$APPLICATION_ID" "$APP_NAME" "$VERSION" "$VERSION_CODE" <<'PY'
|
||||
import pathlib, re, sys
|
||||
path = pathlib.Path(sys.argv[1])
|
||||
app_id, name = sys.argv[2], sys.argv[3]
|
||||
app_id, name, version, version_code = sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]
|
||||
text = path.read_text()
|
||||
|
||||
def set_prop(text, key, value):
|
||||
@@ -91,7 +101,10 @@ def set_prop(text, key, value):
|
||||
text = re.sub(r"(?m)^app\.name_byte_array=.*\n?", "", text)
|
||||
text = set_prop(text, "app.name", name)
|
||||
text = set_prop(text, "app.application_id", app_id)
|
||||
text = set_prop(text, "app.orientation", "portrait")
|
||||
text = set_prop(text, "app.orientation", "fullUser")
|
||||
if version:
|
||||
text = set_prop(text, "app.version_name", version)
|
||||
text = set_prop(text, "app.version_code", version_code)
|
||||
path.write_text(text)
|
||||
PY
|
||||
|
||||
@@ -124,7 +137,7 @@ pack_game_love() {
|
||||
mkdir -p "$EMBED_ASSETS"
|
||||
rm -f "$LOVE_FILE"
|
||||
(cd "$ROOT" && zip -q -9 -r "$LOVE_FILE" \
|
||||
main.lua conf.lua src data assets tools/rom_manifest.json \
|
||||
main.lua conf.lua src data assets tools/rom_manifest.json tools/rom_manifest_blue.json \
|
||||
-x '*.DS_Store' -x '*/.git/*' -x '*/.DS_Store' \
|
||||
-x 'data/generated/*' -x 'assets/generated/*')
|
||||
if unzip -Z1 "$LOVE_FILE" \
|
||||
@@ -178,16 +191,8 @@ require_android_sdk() {
|
||||
|
||||
# --------------------------------------------------------------- gradle
|
||||
run_gradle() {
|
||||
local task
|
||||
if $RELEASE; then
|
||||
task="assembleEmbedNoRecordRelease"
|
||||
say "building release APK ($task)"
|
||||
warn "release signing is out-of-band, see mobile/ANDROID.md (Signing)."
|
||||
warn "without a signingConfig, assembleRelease may produce an unsigned APK or fail."
|
||||
else
|
||||
task="assembleEmbedNoRecordDebug"
|
||||
say "building debug APK ($task), uses the default Android debug keystore"
|
||||
fi
|
||||
local task="assembleEmbedNoRecordDebug"
|
||||
say "building APK ($task)"
|
||||
|
||||
if ! (
|
||||
cd "$ANDROID_DIR"
|
||||
@@ -199,19 +204,12 @@ run_gradle() {
|
||||
You can still iterate on the .love payload with: scripts/build_android.sh --package-only"
|
||||
fi
|
||||
|
||||
local out_dir
|
||||
if $RELEASE; then
|
||||
out_dir="$ANDROID_DIR/app/build/outputs/apk/embedNoRecord/release"
|
||||
else
|
||||
out_dir="$ANDROID_DIR/app/build/outputs/apk/embedNoRecord/debug"
|
||||
fi
|
||||
local out_dir="$ANDROID_DIR/app/build/outputs/apk/embedNoRecord/debug"
|
||||
if [ -d "$out_dir" ]; then
|
||||
say "APK output:"
|
||||
find "$out_dir" -name '*.apk' -exec ls -lh {} \;
|
||||
|
||||
local flavor="debug"
|
||||
$RELEASE && flavor="release"
|
||||
local dist_dir="$DIST/$flavor"
|
||||
local dist_dir="$DIST/debug"
|
||||
rm -rf "$dist_dir"
|
||||
mkdir -p "$dist_dir"
|
||||
find "$out_dir" -name '*.apk' -exec cp {} "$dist_dir/" \;
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
# - mobile/ios/love-src/ (see --fetch / mobile/ios/README.md)
|
||||
# - prebuilt iOS libraries under love-src/platform/xcode/ios/libraries/
|
||||
#
|
||||
# Output: dist/ios/<Config>-<sdk>/PokemonRed.app (convenience copy)
|
||||
# mobile/ios/build/Build/Products/<Config>-<sdk>/PokemonRed.app
|
||||
# Output: dist/ios/<Config>-<sdk>/gen1recomp.app (convenience copy)
|
||||
# mobile/ios/build/Build/Products/<Config>-<sdk>/gen1recomp.app
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
@@ -33,8 +33,8 @@ RESOURCES_DIR="$XCODE_DIR/ios/resources"
|
||||
LOVE_FILE="$RESOURCES_DIR/game.love"
|
||||
LIBS_DIR="$XCODE_DIR/ios/libraries"
|
||||
|
||||
APP_NAME="PokemonRed"
|
||||
DISPLAY_NAME="Pokemon Red"
|
||||
APP_NAME="gen1recomp"
|
||||
DISPLAY_NAME="gen1recomp"
|
||||
BUNDLE_ID="com.theboisclub.pokemonred"
|
||||
LOVE_VERSION="$(tr -d '[:space:]' < "$IOS_DIR/LOVE_VERSION" 2>/dev/null || echo 11.5)"
|
||||
IOS_SOURCE_ZIP="love-${LOVE_VERSION}-ios-source.zip"
|
||||
@@ -155,7 +155,7 @@ require_ios_libraries
|
||||
apply_ios_branding() {
|
||||
[ -f "$OVERLAY_PLIST" ] || fail "missing overlay plist: $OVERLAY_PLIST"
|
||||
local dest="$XCODE_DIR/ios/love-ios.plist"
|
||||
say "applying iOS branding (portrait-only Info.plist, display name)"
|
||||
say "applying iOS branding (portrait + landscape Info.plist, display name)"
|
||||
cp "$OVERLAY_PLIST" "$dest"
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ pack_game_love() {
|
||||
rm -f "$LOVE_FILE"
|
||||
# Same payload as scripts/build.sh / build_android.sh: game sources only.
|
||||
(cd "$ROOT" && zip -q -9 -r "$LOVE_FILE" \
|
||||
main.lua conf.lua src data assets tools/rom_manifest.json \
|
||||
main.lua conf.lua src data assets tools/rom_manifest.json tools/rom_manifest_blue.json \
|
||||
-x '*.DS_Store' -x '*/.git/*' -x '*/.DS_Store' \
|
||||
-x 'data/generated/*' -x 'assets/generated/*')
|
||||
if unzip -Z1 "$LOVE_FILE" \
|
||||
|
||||
@@ -144,6 +144,25 @@ function AnimPlayer.new(data)
|
||||
}, AnimPlayer)
|
||||
end
|
||||
|
||||
-- Release the tilesheet images and quads this player built. They live in
|
||||
-- per-instance caches (a fresh AnimPlayer is made per battle), so unlike a
|
||||
-- shared module cache they are dead the moment the battle ends -- freeing
|
||||
-- them here instead of waiting on a GC finalizer keeps grinding battles
|
||||
-- from piling orphaned VRAM up faster than the (Lua-heap-triggered) GC
|
||||
-- reclaims it.
|
||||
function AnimPlayer:release()
|
||||
for _, img in pairs(self.images) do
|
||||
if img and img.release then pcall(img.release, img) end
|
||||
end
|
||||
self.images = {}
|
||||
for _, byTile in pairs(self.quads) do
|
||||
for _, q in pairs(byTile) do
|
||||
if q and q.release then pcall(q.release, q) end
|
||||
end
|
||||
end
|
||||
self.quads = {}
|
||||
end
|
||||
|
||||
function AnimPlayer:warnOnce(key, fmt, ...)
|
||||
if not self.warned[key] then
|
||||
self.warned[key] = true
|
||||
|
||||
+103
-12
@@ -635,7 +635,6 @@ function BattleState:startMessage(item)
|
||||
self.total = self.total + #codes
|
||||
end
|
||||
self.charIndex = 0
|
||||
self.holdTimer = nil
|
||||
end
|
||||
|
||||
function BattleState:updateQueue()
|
||||
@@ -786,9 +785,8 @@ function BattleState:updateQueue()
|
||||
if self.charIndex < self.total then
|
||||
self.charIndex = math.min(self.total, self.charIndex + 2)
|
||||
else
|
||||
self.holdTimer = (self.holdTimer or 40) - 1
|
||||
local input = self.game.input
|
||||
if self.holdTimer <= 0 or input:wasPressed("a") or input:wasPressed("b") then
|
||||
if input:wasPressed("a") or input:wasPressed("b") then
|
||||
self.current = nil
|
||||
end
|
||||
end
|
||||
@@ -936,6 +934,20 @@ end
|
||||
-- (end_of_battle.asm clears wLowHealthAlarm when a battle ends)
|
||||
function BattleState:exit()
|
||||
require("src.core.Sound").stopLoop("Low_Health_Alarm")
|
||||
-- Free this battle's own GPU objects now rather than waiting on a GC
|
||||
-- finalizer: the two full-screen wavy-effect canvases (colorMode) and
|
||||
-- the AnimPlayer's per-instance tilesheet images/quads. The shared
|
||||
-- module caches (imageCache/imagePadBottom, keyed by path+palette) are
|
||||
-- reused by the next battle, so they are deliberately left alone -- only
|
||||
-- the per-instance objects, which are dead once this battle is popped,
|
||||
-- are released here.
|
||||
local function rel(o) if o and o.release then pcall(o.release, o) end end
|
||||
rel(self.bgCanvas); self.bgCanvas = nil
|
||||
rel(self.waveCanvas); self.waveCanvas = nil
|
||||
self.colorFxReady = nil
|
||||
if self.animPlayer and self.animPlayer.release then
|
||||
self.animPlayer:release()
|
||||
end
|
||||
end
|
||||
|
||||
-- An action the battler is locked into (bypasses the menu), or nil.
|
||||
@@ -968,6 +980,25 @@ function BattleState:playerHasPP()
|
||||
return false
|
||||
end
|
||||
|
||||
function BattleState:swapMoves(i, j)
|
||||
if i == j then return end
|
||||
local moves = self.player.curMoves
|
||||
local a, b = moves[i], moves[j]
|
||||
if not (a and b) then return end
|
||||
moves[i], moves[j] = b, a
|
||||
local stored = self.player.mon and self.player.mon.moves
|
||||
if stored and stored ~= moves and stored[i] and stored[j] then
|
||||
stored[i], stored[j] = stored[j], stored[i]
|
||||
end
|
||||
local disabled = self.player.disabledSlot
|
||||
if disabled == i then
|
||||
self.player.disabledSlot = j
|
||||
elseif disabled == j then
|
||||
self.player.disabledSlot = i
|
||||
end
|
||||
require("src.core.Sound").play(self.data, "Swap")
|
||||
end
|
||||
|
||||
function BattleState:update(dt)
|
||||
self.frame = self.frame + 1
|
||||
self:updateFx()
|
||||
@@ -1081,6 +1112,7 @@ function BattleState:update(dt)
|
||||
end
|
||||
self.phase = "moveSelect"
|
||||
self.moveIndex = math.min(self.moveIndex, #self.player.curMoves)
|
||||
self.moveSwapIndex = nil
|
||||
elseif choice == "run" then
|
||||
self:tryRun()
|
||||
elseif choice == "item" then
|
||||
@@ -1098,9 +1130,22 @@ function BattleState:update(dt)
|
||||
self.moveIndex = self.moveIndex > 1 and self.moveIndex - 1 or #moves
|
||||
elseif input:wasPressed("down") then
|
||||
self.moveIndex = self.moveIndex < #moves and self.moveIndex + 1 or 1
|
||||
elseif input:wasPressed("select") then
|
||||
if self.moveSwapIndex then
|
||||
self:swapMoves(self.moveSwapIndex, self.moveIndex)
|
||||
self.moveSwapIndex = nil
|
||||
else
|
||||
self.moveSwapIndex = self.moveIndex
|
||||
end
|
||||
elseif input:wasPressed("b") then
|
||||
self.moveSwapIndex = nil
|
||||
self.phase = "menu"
|
||||
elseif input:wasPressed("a") then
|
||||
if self.moveSwapIndex then
|
||||
self:swapMoves(self.moveSwapIndex, self.moveIndex)
|
||||
self.moveSwapIndex = nil
|
||||
return
|
||||
end
|
||||
local mv = moves[self.moveIndex]
|
||||
if self.player.disabledSlot == self.moveIndex then
|
||||
self:say("The move is\ndisabled!")
|
||||
@@ -1501,10 +1546,16 @@ function BattleState:endOfTurn()
|
||||
-- that sets the flag also zeroes the counter, so a stale value is
|
||||
-- unobservable (a switch or cure downgrades Toxic to plain poison).
|
||||
self.sideToxic = self.sideToxic or {}
|
||||
for _, pair in ipairs({ { self.player, self.enemy, "player" },
|
||||
{ self.enemy, self.player, "enemy" } }) do
|
||||
local b, opp, side = pair[1], pair[2], pair[3]
|
||||
if b.mon.hp > 0 then
|
||||
-- a battler whose opponent was already knocked out by a move this turn
|
||||
-- skips its own residual (HandlePoisonBurnLeechSeed is bypassed when the
|
||||
-- move faints the target); snapshot before residual so one side's
|
||||
-- residual faint can't suppress the other's
|
||||
local playerAlive = self.player.mon.hp > 0
|
||||
local enemyAlive = self.enemy.mon.hp > 0
|
||||
for _, pair in ipairs({ { self.player, self.enemy, "player", enemyAlive },
|
||||
{ self.enemy, self.player, "enemy", playerAlive } }) do
|
||||
local b, opp, side, oppAlive = pair[1], pair[2], pair[3], pair[4]
|
||||
if b.mon.hp > 0 and oppAlive then
|
||||
local msgs = Status.residual(b, opp, self)
|
||||
for _, m in ipairs(msgs) do self:sayNext(prefixEnemy(m, b)) end
|
||||
if #msgs > 0 then self:drainNext() end -- poison/burn/seed HP moved
|
||||
@@ -2265,6 +2316,7 @@ function BattleState:performMove(user, target, moveInst, isCalled)
|
||||
-- falling back to the id tables (Fly AND Dig go semi-invulnerable:
|
||||
-- ChargeEffect sets INVULNERABLE for both)
|
||||
if record and record.charge and not releasing then
|
||||
self:cancelMoveAnim()
|
||||
user.charging = moveInst
|
||||
user.chargeReady = true
|
||||
local invulnerable = move.semiInvulnerable
|
||||
@@ -2274,6 +2326,15 @@ function BattleState:performMove(user, target, moveInst, isCalled)
|
||||
if invulnerable then
|
||||
user.invulnerable = true
|
||||
end
|
||||
local chargeAnim = record.charge.anim
|
||||
if move.id == "DIG" then
|
||||
chargeAnim = "SLIDE_DOWN_ANIM"
|
||||
elseif record.charge.enemyAnim and not user.isPlayer then
|
||||
chargeAnim = record.charge.enemyAnim
|
||||
end
|
||||
if chargeAnim then
|
||||
self:animNext(chargeAnim, user.isPlayer)
|
||||
end
|
||||
local chargeText = move.chargeText or CHARGE_TEXT[move.id]
|
||||
or "%s\nis charging up!"
|
||||
self:sayNext(chargeText:format(displayName(user)))
|
||||
@@ -2401,6 +2462,9 @@ end
|
||||
function BattleState:onFaint(battler)
|
||||
if battler.faintQueued then return end
|
||||
battler.faintQueued = true
|
||||
if battler.isPlayer and self.participants then
|
||||
self.participants[battler.mon] = nil
|
||||
end
|
||||
Runtime.emit("battle.fainted", { battle = self, battler = battler })
|
||||
-- the faint slide + cry ride the queue (after the move animation and
|
||||
-- the HP-bar drain, pokered's order); the slide finishes before the
|
||||
@@ -2437,9 +2501,9 @@ function BattleState:enemyMonFainted()
|
||||
-- exp is split among the mons that fought this enemy
|
||||
-- (engine/battle/experience.asm); traded mons earn x1.5; each
|
||||
-- participant gets the full stat exp
|
||||
-- the divisor counts EVERY participant, fainted ones included
|
||||
-- (DivideExpDataByNumMonsGainingExp keeps their flag bits); only the
|
||||
-- living ones are actually paid
|
||||
-- a mon that fainted mid-fight has had its gain-exp flag cleared
|
||||
-- (RemoveFaintedPlayerMon), so it drops out of the divisor and only
|
||||
-- the surviving participants are counted and paid
|
||||
local participants, alive = 0, {}
|
||||
for _, mon in ipairs(self.game.save.party) do
|
||||
if self.participants and self.participants[mon] then
|
||||
@@ -2749,6 +2813,7 @@ function BattleState:safariAction(choice)
|
||||
local playerName = self.game.save.player.name
|
||||
|
||||
if choice == "run" then
|
||||
require("src.core.Sound").play(self.data, "Run")
|
||||
self:say("Got away safely!")
|
||||
self.result = "run"
|
||||
self.afterQueue = "finish"
|
||||
@@ -2830,6 +2895,12 @@ function BattleState:safariEnemyTurn()
|
||||
end
|
||||
if fled then
|
||||
self:sayNext(("Wild %s\nran!"):format(self.enemy.name))
|
||||
self:actNext(function()
|
||||
require("src.core.Sound").play(self.data, "Run")
|
||||
startPicKind(self:picFxFor(self.enemy), "slideOff")
|
||||
end)
|
||||
self.nextInsert = (self.nextInsert or 0) + 1
|
||||
table.insert(self.queue, self.nextInsert, { wait = 24 })
|
||||
self.result = "run"
|
||||
self.afterQueue = "finish"
|
||||
end
|
||||
@@ -3494,12 +3565,28 @@ function BattleState:sgbBattlePals()
|
||||
if placeholder or not b then return pals.MEWMON or pals.GREENBAR end
|
||||
return PaletteFX.monPal(self.data, b.mon.species) or pals.MEWMON
|
||||
end
|
||||
return {
|
||||
local out = {
|
||||
[0] = bar(self.player),
|
||||
[1] = bar(self.enemy),
|
||||
[2] = mon(self.player, self.showPlayerBack or self.safari or self.demo),
|
||||
[3] = mon(self.enemy, self.showEnemyTrainer),
|
||||
}
|
||||
-- OG RED: the Game Boy Color drew the whole battle from one BG palette --
|
||||
-- white paper, black ink -- so every zone shares the same background and
|
||||
-- outline; only the two mid shades differ per element (green HP bar, red
|
||||
-- mon pic). The bar/base zones otherwise carry the SGB off-white
|
||||
-- (255,239,255) as color 0 while the mon zones (monPal -> GBC_BG) carry a
|
||||
-- true white, which is what drew a white box around each pic on the pink
|
||||
-- field. Snap every zone's color 0/3 to the global GBC white/black; the
|
||||
-- mid shades (and the green bar the user prefers) stay untouched.
|
||||
if PaletteFX.mode == "ogred" then
|
||||
local white, black = PaletteFX.GBC_BG[1], PaletteFX.GBC_BG[4]
|
||||
for i = 0, 3 do
|
||||
local c = out[i]
|
||||
out[i] = { white, c[2], c[3], black }
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the SGB palette covering a screen pixel (BlkPacket_Battle regions)
|
||||
@@ -3826,7 +3913,11 @@ function BattleState:drawTextArea()
|
||||
for i, mv in ipairs(self.player.curMoves) do
|
||||
Font.draw(self.data.moves[mv.id].name, 48, 96 + i * 8)
|
||||
end
|
||||
Font.drawCode(0xED, 40, 96 + self.moveIndex * 8)
|
||||
Font.drawCode((self.moveSwapIndex == self.moveIndex) and 0xEC or 0xED,
|
||||
40, 96 + self.moveIndex * 8)
|
||||
if self.moveSwapIndex and self.moveSwapIndex ~= self.moveIndex then
|
||||
Font.drawCode(0xEC, 40, 96 + self.moveSwapIndex * 8)
|
||||
end
|
||||
local sel = self.player.curMoves[self.moveIndex]
|
||||
if sel then
|
||||
if self.player.disabledSlot == self.moveIndex then
|
||||
|
||||
@@ -516,8 +516,8 @@ MoveEffects.full = {
|
||||
|
||||
-- charge moves: first turn just charges; Fly AND Dig go
|
||||
-- semi-invulnerable (ChargeEffect sets INVULNERABLE for both)
|
||||
CHARGE_EFFECT = { charge = {} },
|
||||
FLY_EFFECT = { charge = { invulnerable = true } },
|
||||
CHARGE_EFFECT = { charge = { anim = "XSTATITEM_ANIM", enemyAnim = "XSTATITEM_DUPLICATE_ANIM" } },
|
||||
FLY_EFFECT = { charge = { invulnerable = true, anim = "TELEPORT" } },
|
||||
|
||||
TRAPPING_EFFECT = {
|
||||
-- TrappingEffect runs BEFORE the hit test and clears the target's
|
||||
|
||||
+316
-801
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,760 @@
|
||||
-- Pure Game Boy audio synthesis (the DMG/GBC channel-program interpreter and
|
||||
-- PCM renderer), factored out of ChipAudio so it can run on EITHER the main
|
||||
-- thread (SFX/cries, and the synchronous music fallback) or the ChipAudio
|
||||
-- worker thread (src/core/chip_worker.lua), which is where map/battle music is
|
||||
-- synthesized so a song change never stutters the render thread.
|
||||
--
|
||||
-- Deliberately depends ONLY on `bit`, love.sound and love.filesystem: no
|
||||
-- love.audio (Sources are a playback concern the caller owns) and no
|
||||
-- src.render.Assets (hot-reload registration stays in ChipAudio). Both of
|
||||
-- those are unavailable or main-thread-only inside a love.thread worker, so
|
||||
-- keeping them out is what lets the same synth code run in the worker.
|
||||
|
||||
local bit = require("bit")
|
||||
|
||||
local ChipSynth = {}
|
||||
|
||||
local SAMPLE_RATE = 22050
|
||||
local TICKS_PER_SECOND = 15360
|
||||
local FRAME_TICKS = 256
|
||||
local GB_CLOCK = 4194304
|
||||
|
||||
-- one 4096-sample stereo SoundData is the unit both the worker hands off and
|
||||
-- the synchronous fallback queues; the source keeps MUSIC_BUFFER_COUNT of them
|
||||
-- (~6s) for stall tolerance (window resize, a long GC pause)
|
||||
local MUSIC_BUFFER_SAMPLES = 4096
|
||||
local MUSIC_BUFFER_COUNT = 32
|
||||
|
||||
ChipSynth.SAMPLE_RATE = SAMPLE_RATE
|
||||
ChipSynth.MUSIC_BUFFER_SAMPLES = MUSIC_BUFFER_SAMPLES
|
||||
ChipSynth.MUSIC_BUFFER_COUNT = MUSIC_BUFFER_COUNT
|
||||
|
||||
local PITCHES = {
|
||||
0xF82C, 0xF89D, 0xF907, 0xF96B, 0xF9CA, 0xFA23,
|
||||
0xFA77, 0xFAC7, 0xFB12, 0xFB58, 0xFB9B, 0xFBDA,
|
||||
}
|
||||
local DUTY = { [0] = 0.125, [1] = 0.25, [2] = 0.5, [3] = 0.75 }
|
||||
local WAVE_LEVEL = { [0] = 0, [1] = 1, [2] = 0.5, [3] = 0.25 }
|
||||
local NOISE_DIVISORS = {
|
||||
[0] = 8, [1] = 16, [2] = 32, [3] = 48,
|
||||
[4] = 64, [5] = 80, [6] = 96, [7] = 112,
|
||||
}
|
||||
|
||||
local function snapTicks(ticks)
|
||||
return math.floor((ticks * 735 + 256) / 512)
|
||||
end
|
||||
|
||||
local cachedProgramFile
|
||||
local cachedBanks
|
||||
|
||||
local function loadBanks(data)
|
||||
local audio = data.audio
|
||||
if cachedProgramFile == audio.programFile and cachedBanks then
|
||||
return cachedBanks
|
||||
end
|
||||
local raw, readError = love.filesystem.read(audio.programFile)
|
||||
if not raw then error("could not read sound programs: " .. tostring(readError)) end
|
||||
local banks = {}
|
||||
for index, bank in ipairs(audio.bankOrder) do
|
||||
local first = (index - 1) * 0x4000 + 1
|
||||
banks[bank] = raw:sub(first, first + 0x3FFF)
|
||||
end
|
||||
cachedProgramFile, cachedBanks = audio.programFile, banks
|
||||
return banks
|
||||
end
|
||||
|
||||
-- drop the single-slot bank cache; the worker keeps its own copy of this
|
||||
-- module's state, so ChipAudio.invalidate must reach it via a worker message
|
||||
function ChipSynth.invalidateBanks()
|
||||
cachedProgramFile, cachedBanks = nil, nil
|
||||
end
|
||||
|
||||
-- A def-local program (ChipAsm output) is mounted as pseudo-bank 0 next to
|
||||
-- the ROM banks, so the 0x4000-window byte reader and every call/loop
|
||||
-- target work unchanged. The ROM's own cached bank table is never touched
|
||||
-- because bank 0 differs per def, and a blob that carries its own waves and
|
||||
-- drums renders even where programs.bin is unreadable.
|
||||
local function engineBanks(data, chip)
|
||||
if not chip then return loadBanks(data) end
|
||||
local banks = {}
|
||||
local ok, romBanks = pcall(loadBanks, data)
|
||||
if ok then
|
||||
for bank, bytes in pairs(romBanks) do banks[bank] = bytes end
|
||||
end
|
||||
banks[0] = chip.blob
|
||||
return banks
|
||||
end
|
||||
|
||||
local function romByte(banks, bank, address)
|
||||
local bytes = assert(banks[bank], "uncached audio bank " .. tostring(bank))
|
||||
local value = bytes:byte(address - 0x4000 + 1)
|
||||
if not value then
|
||||
error(("audio read outside bank %02X:%04X"):format(bank, address))
|
||||
end
|
||||
return value
|
||||
end
|
||||
|
||||
local function romWord(banks, bank, address)
|
||||
return romByte(banks, bank, address)
|
||||
+ romByte(banks, bank, address + 1) * 0x100
|
||||
end
|
||||
|
||||
local function headerChannels(banks, header)
|
||||
local channels = {}
|
||||
local address = header.address
|
||||
local first = romByte(banks, header.bank, address)
|
||||
local count = bit.rshift(bit.band(first, 0xF0), 6) + 1
|
||||
for _ = 1, count do
|
||||
local descriptor = romByte(banks, header.bank, address)
|
||||
channels[#channels + 1] = {
|
||||
number = bit.band(descriptor, 0x0F) + 1,
|
||||
address = romWord(banks, header.bank, address + 1),
|
||||
}
|
||||
address = address + 3
|
||||
end
|
||||
return channels
|
||||
end
|
||||
|
||||
local function fadeValue(nibble)
|
||||
if bit.band(nibble, 8) ~= 0 then return -bit.band(nibble, 7) end
|
||||
return nibble
|
||||
end
|
||||
|
||||
local Channel = {}
|
||||
Channel.__index = Channel
|
||||
|
||||
function Channel.new(engine, spec, options)
|
||||
options = options or {}
|
||||
local hardware = (spec.number - 1) % 4 + 1
|
||||
local isSfxChannel = spec.number > 4
|
||||
return setmetatable({
|
||||
engine = engine,
|
||||
bank = options.bank,
|
||||
address = spec.address,
|
||||
number = spec.number,
|
||||
hardware = hardware,
|
||||
wave = hardware == 3,
|
||||
noise = hardware == 4,
|
||||
sfx = isSfxChannel,
|
||||
executeMusic = not isSfxChannel,
|
||||
allowLoops = options.allowLoops ~= false,
|
||||
frequencyOffset = options.frequencyOffset or 0,
|
||||
frameTicks = options.frameTicks or FRAME_TICKS,
|
||||
speed = 12,
|
||||
volume = 12,
|
||||
fade = 0,
|
||||
duty = 0.5,
|
||||
octave = 4,
|
||||
waveInstrument = 0,
|
||||
waveLevel = 1,
|
||||
perfectPitch = false,
|
||||
vibrato = nil,
|
||||
pendingSlide = nil,
|
||||
sweep = nil,
|
||||
callStack = {},
|
||||
loopCounts = {},
|
||||
event = nil,
|
||||
ended = false,
|
||||
phase = 0,
|
||||
noiseLfsr = 0x7FFF,
|
||||
noiseClock = 0,
|
||||
timeTicks = 0,
|
||||
}, Channel)
|
||||
end
|
||||
|
||||
function Channel:byte()
|
||||
local value = romByte(self.engine.banks, self.bank, self.address)
|
||||
self.address = self.address + 1
|
||||
return value
|
||||
end
|
||||
|
||||
function Channel:word()
|
||||
local value = romWord(self.engine.banks, self.bank, self.address)
|
||||
self.address = self.address + 2
|
||||
return value
|
||||
end
|
||||
|
||||
function Channel:frequency(note, octave)
|
||||
local signed = PITCHES[note + 1] - 0x10000
|
||||
local register = bit.band(
|
||||
bit.arshift(signed, math.max(0, (octave or self.octave) - 1)), 0x7FF)
|
||||
if self.perfectPitch then register = bit.band(register + 1, 0x7FF) end
|
||||
return bit.band(register + self.frequencyOffset, 0x7FF)
|
||||
end
|
||||
|
||||
function Channel:durationTicks(length)
|
||||
local tempo = self.sfx and self.frameTicks or self.engine.tempo
|
||||
local speed = self.sfx and (self.executeMusic and self.speed or 1)
|
||||
or self.speed
|
||||
return length * speed * tempo
|
||||
end
|
||||
|
||||
function Channel:timedEvent(event, ticks)
|
||||
local first = snapTicks(self.timeTicks)
|
||||
self.timeTicks = self.timeTicks + ticks
|
||||
event.duration = ticks / TICKS_PER_SECOND
|
||||
event.samples = snapTicks(self.timeTicks) - first
|
||||
event.sample = 0
|
||||
event.elapsed = 0
|
||||
return event
|
||||
end
|
||||
|
||||
function Channel:pan()
|
||||
local mask = bit.lshift(1, self.hardware - 1)
|
||||
return bit.band(bit.rshift(self.engine.pan, 4), mask) ~= 0,
|
||||
bit.band(self.engine.pan, mask) ~= 0
|
||||
end
|
||||
|
||||
function Channel:tone(ticks, register, volume, fade)
|
||||
if register >= 0x800 then
|
||||
return self:timedEvent({ silence = true }, ticks)
|
||||
end
|
||||
local duration = ticks / TICKS_PER_SECOND
|
||||
local panLeft, panRight = self:pan()
|
||||
local slide
|
||||
if self.pendingSlide then
|
||||
slide = {
|
||||
target = self.pendingSlide.target,
|
||||
frames = math.max(1, duration * 60 - self.pendingSlide.length),
|
||||
}
|
||||
self.pendingSlide = nil
|
||||
end
|
||||
return self:timedEvent({
|
||||
register = register,
|
||||
volume = volume == nil and self.volume or volume,
|
||||
fade = fade == nil and self.fade or fade,
|
||||
duty = self.duty,
|
||||
wave = self.wave,
|
||||
waveInstrument = self.waveInstrument,
|
||||
waveLevel = self.waveLevel,
|
||||
vibrato = slide and nil or self.vibrato,
|
||||
slide = slide,
|
||||
sweep = self.sfx and self.hardware == 1 and self.sweep or nil,
|
||||
panLeft = panLeft,
|
||||
panRight = panRight,
|
||||
}, ticks)
|
||||
end
|
||||
|
||||
function Channel:noiseEvent(ticks, volume, fade, parameter)
|
||||
local panLeft, panRight = self:pan()
|
||||
return self:timedEvent({
|
||||
noise = true,
|
||||
volume = volume or self.volume,
|
||||
fade = fade or 0,
|
||||
noiseParameter = parameter,
|
||||
panLeft = panLeft, panRight = panRight,
|
||||
}, ticks)
|
||||
end
|
||||
|
||||
function Channel:drumEvent(ticks, instrument)
|
||||
local panLeft, panRight = self:pan()
|
||||
return self:timedEvent({
|
||||
noise = true,
|
||||
drum = self.engine:noiseInstrument(instrument),
|
||||
panLeft = panLeft,
|
||||
panRight = panRight,
|
||||
}, ticks)
|
||||
end
|
||||
|
||||
function Channel:silenceEvent(ticks)
|
||||
return self:timedEvent({ silence = true }, ticks)
|
||||
end
|
||||
|
||||
function Channel:nextEvent()
|
||||
if self.ended then return nil end
|
||||
for _ = 1, 100000 do
|
||||
local commandAddress = self.address
|
||||
local command = self:byte()
|
||||
|
||||
if (self.executeMusic or not self.sfx) and command < 0xC0 then
|
||||
local note = bit.rshift(command, 4)
|
||||
local length = bit.band(command, 0x0F) + 1
|
||||
if self.noise then
|
||||
local instrument = note
|
||||
if command >= 0xB0 then instrument = self:byte() end
|
||||
return self:drumEvent(self:durationTicks(length), instrument)
|
||||
end
|
||||
return self:tone(self:durationTicks(length), self:frequency(note))
|
||||
elseif command >= 0xC0 and command < 0xD0 then
|
||||
local length = bit.band(command, 0x0F) + 1
|
||||
return self:silenceEvent(self:durationTicks(length))
|
||||
elseif command >= 0xD0 and command < 0xE0 then
|
||||
self.speed = bit.band(command, 0x0F)
|
||||
if not self.noise then
|
||||
local packed = self:byte()
|
||||
if self.wave then
|
||||
self.waveLevel = WAVE_LEVEL[bit.band(bit.rshift(packed, 4), 3)]
|
||||
self.waveInstrument = bit.band(packed, 0x0F)
|
||||
else
|
||||
self.volume = bit.rshift(packed, 4)
|
||||
self.fade = fadeValue(bit.band(packed, 0x0F))
|
||||
end
|
||||
end
|
||||
elseif command >= 0xE0 and command <= 0xE7 then
|
||||
self.octave = 8 - bit.band(command, 7)
|
||||
elseif command == 0xE8 then
|
||||
self.perfectPitch = not self.perfectPitch
|
||||
elseif command == 0xE9 then
|
||||
-- Unused command.
|
||||
elseif command == 0xEA then
|
||||
local delay, packed = self:byte(), self:byte()
|
||||
local depth = bit.rshift(packed, 4)
|
||||
if depth == 0 then
|
||||
self.vibrato = nil
|
||||
else
|
||||
self.vibrato = {
|
||||
delay = delay,
|
||||
above = bit.rshift(depth, 1) + bit.band(depth, 1),
|
||||
below = bit.rshift(depth, 1),
|
||||
rate = bit.band(packed, 0x0F),
|
||||
}
|
||||
end
|
||||
elseif command == 0xEB then
|
||||
local length, packed = self:byte(), self:byte()
|
||||
local octave = 8 - bit.rshift(packed, 4)
|
||||
self.pendingSlide = {
|
||||
length = length,
|
||||
target = self:frequency(bit.band(packed, 0x0F), octave),
|
||||
}
|
||||
elseif command == 0xEC then
|
||||
self.duty = DUTY[bit.band(self:byte(), 3)] or 0.5
|
||||
elseif command == 0xED then
|
||||
self.engine.tempo = self:byte() * 0x100 + self:byte()
|
||||
elseif command == 0xEE then
|
||||
self.engine.pan = self:byte()
|
||||
elseif command == 0xEF or command == 0xF0 then
|
||||
self:byte()
|
||||
elseif command == 0xF8 then
|
||||
self.executeMusic = not self.executeMusic
|
||||
elseif command == 0xFC then
|
||||
local packed = self:byte()
|
||||
self.duty = {
|
||||
DUTY[bit.band(bit.rshift(packed, 6), 3)],
|
||||
DUTY[bit.band(bit.rshift(packed, 4), 3)],
|
||||
DUTY[bit.band(bit.rshift(packed, 2), 3)],
|
||||
DUTY[bit.band(packed, 3)],
|
||||
}
|
||||
elseif command == 0xFD then
|
||||
self.callStack[#self.callStack + 1] = self.address + 2
|
||||
self.address = self:word()
|
||||
elseif command == 0xFE then
|
||||
local count, target = self:byte(), self:word()
|
||||
if count == 0 then
|
||||
if self.allowLoops then
|
||||
self.address = target
|
||||
else
|
||||
self.ended = true
|
||||
return nil
|
||||
end
|
||||
else
|
||||
local remaining = self.loopCounts[commandAddress]
|
||||
if remaining == nil then remaining = count end
|
||||
remaining = remaining - 1
|
||||
if remaining > 0 then
|
||||
self.loopCounts[commandAddress] = remaining
|
||||
self.address = target
|
||||
else
|
||||
self.loopCounts[commandAddress] = nil
|
||||
end
|
||||
end
|
||||
elseif command == 0xFF then
|
||||
local returnAddress = table.remove(self.callStack)
|
||||
if returnAddress then
|
||||
self.address = returnAddress
|
||||
else
|
||||
self.ended = true
|
||||
return nil
|
||||
end
|
||||
elseif self.sfx and command >= 0x20 and command < 0x30 then
|
||||
local length = bit.band(command, 0x0F) + 1
|
||||
local packed = self:byte()
|
||||
local volume = bit.rshift(packed, 4)
|
||||
local fade = fadeValue(bit.band(packed, 0x0F))
|
||||
if self.noise then
|
||||
local parameter = self:byte()
|
||||
return self:noiseEvent(
|
||||
self:durationTicks(length), volume, fade, parameter)
|
||||
end
|
||||
local register = bit.band(self:word() + self.frequencyOffset, 0x7FF)
|
||||
return self:tone(self:durationTicks(length), register, volume, fade)
|
||||
elseif command == 0x10 then
|
||||
local packed = self:byte()
|
||||
self.sweep = {
|
||||
pace = bit.band(bit.rshift(packed, 4), 7),
|
||||
subtract = bit.band(packed, 8) ~= 0,
|
||||
shift = bit.band(packed, 7),
|
||||
}
|
||||
else
|
||||
self.ended = true
|
||||
return nil
|
||||
end
|
||||
end
|
||||
self.ended = true
|
||||
return nil
|
||||
end
|
||||
|
||||
local function envelopeVolume(volume, fade, elapsed)
|
||||
if fade == 0 then return volume end
|
||||
local steps = math.floor(elapsed / (math.abs(fade) / 64))
|
||||
if fade > 0 then return math.max(0, volume - steps) end
|
||||
return math.min(15, volume + steps)
|
||||
end
|
||||
|
||||
function Channel:resetNoise()
|
||||
self.noiseLfsr = 0x7FFF
|
||||
self.noiseClock = 0
|
||||
end
|
||||
|
||||
function Channel:clockNoise(width7)
|
||||
local feedback = bit.bxor(
|
||||
bit.band(self.noiseLfsr, 1),
|
||||
bit.band(bit.rshift(self.noiseLfsr, 1), 1))
|
||||
self.noiseLfsr = bit.bor(
|
||||
bit.rshift(self.noiseLfsr, 1),
|
||||
bit.lshift(feedback, 14))
|
||||
if width7 then
|
||||
self.noiseLfsr = bit.bor(
|
||||
bit.band(self.noiseLfsr, bit.bnot(0x40)),
|
||||
bit.lshift(feedback, 6))
|
||||
end
|
||||
end
|
||||
|
||||
function Channel:sampleNoise(parameter)
|
||||
parameter = parameter or 0
|
||||
local divisor = NOISE_DIVISORS[bit.band(parameter, 7)]
|
||||
local shift = bit.rshift(parameter, 4)
|
||||
local output = bit.band(self.noiseLfsr, 1) == 0 and 1 or -1
|
||||
if shift >= 14 then return output end
|
||||
local cycles = GB_CLOCK / divisor / (2 ^ shift) / SAMPLE_RATE
|
||||
local width7 = bit.band(parameter, 8) ~= 0
|
||||
local remaining = cycles
|
||||
local area = 0
|
||||
|
||||
while remaining > 0 do
|
||||
local untilClock = 1 - self.noiseClock
|
||||
local span = math.min(remaining, untilClock)
|
||||
output = bit.band(self.noiseLfsr, 1) == 0 and 1 or -1
|
||||
area = area + output * span
|
||||
self.noiseClock = self.noiseClock + span
|
||||
remaining = remaining - span
|
||||
if self.noiseClock >= 1 - 1e-12 then
|
||||
self.noiseClock = 0
|
||||
self:clockNoise(width7)
|
||||
end
|
||||
end
|
||||
|
||||
return area / cycles
|
||||
end
|
||||
|
||||
local function sweepCalculation(register, sweep)
|
||||
local delta = math.floor(register / (2 ^ sweep.shift))
|
||||
if sweep.subtract then return register - delta end
|
||||
return register + delta
|
||||
end
|
||||
|
||||
local function sweptRegister(register, sweep, elapsed)
|
||||
if not sweep or sweep.shift == 0 then return register end
|
||||
local nextRegister = sweepCalculation(register, sweep)
|
||||
if nextRegister > 0x7FF or nextRegister < 0 then return nil end
|
||||
if sweep.pace == 0 then return register end
|
||||
|
||||
local iterations = math.floor(elapsed * 128 / sweep.pace)
|
||||
for _ = 1, iterations do
|
||||
register = nextRegister
|
||||
nextRegister = sweepCalculation(register, sweep)
|
||||
if nextRegister > 0x7FF or nextRegister < 0 then return nil end
|
||||
end
|
||||
return register
|
||||
end
|
||||
|
||||
function Channel:sampleDrum(event, sampleIndex)
|
||||
local index = event.drumSegmentIndex or 1
|
||||
local segment = event.drum[index]
|
||||
while segment and sampleIndex >= segment.endSample do
|
||||
index = index + 1
|
||||
segment = event.drum[index]
|
||||
end
|
||||
if not segment or sampleIndex < segment.startSample then return 0 end
|
||||
if event.drumSegmentIndex ~= index then
|
||||
event.drumSegmentIndex = index
|
||||
self:resetNoise()
|
||||
end
|
||||
local elapsed = (sampleIndex - segment.startSample) / SAMPLE_RATE
|
||||
local volume = envelopeVolume(segment.volume, segment.fade, elapsed)
|
||||
return self:sampleNoise(segment.parameter) * volume / 15 * 0.35
|
||||
end
|
||||
|
||||
function Channel:sample()
|
||||
while not self.ended
|
||||
and (not self.event or self.event.sample >= self.event.samples) do
|
||||
self.event = self:nextEvent()
|
||||
self.phase = 0
|
||||
self:resetNoise()
|
||||
end
|
||||
local event = self.event
|
||||
if not event then return 0 end
|
||||
local sampleIndex = event.sample
|
||||
event.elapsed = sampleIndex / SAMPLE_RATE
|
||||
event.sample = sampleIndex + 1
|
||||
if event.silence then return 0 end
|
||||
|
||||
if event.drum then return self:sampleDrum(event, sampleIndex) end
|
||||
local volume = envelopeVolume(
|
||||
event.volume or 0, event.fade or 0, event.elapsed)
|
||||
if event.noise then
|
||||
return self:sampleNoise(event.noiseParameter) * volume / 15 * 0.35
|
||||
end
|
||||
|
||||
local register = event.register
|
||||
local frame = math.floor(event.elapsed * 60)
|
||||
if event.sweep then
|
||||
register = sweptRegister(register, event.sweep, event.elapsed)
|
||||
if not register then return 0 end
|
||||
elseif event.slide then
|
||||
local amount = math.min(1, frame / event.slide.frames)
|
||||
register = register + (event.slide.target - register) * amount
|
||||
elseif event.vibrato and frame >= event.vibrato.delay then
|
||||
local vibrato = event.vibrato
|
||||
local toggles = math.floor(
|
||||
(frame - vibrato.delay + 1) / (vibrato.rate + 1))
|
||||
if toggles > 0 then
|
||||
local low = bit.band(register, 0xFF)
|
||||
local high = bit.band(register, 0x700)
|
||||
if bit.band(toggles, 1) ~= 0 then
|
||||
register = high + math.min(0xFF, low + vibrato.above)
|
||||
else
|
||||
register = high + math.max(0, low - vibrato.below)
|
||||
end
|
||||
end
|
||||
end
|
||||
local frequency = 131072 / (2048 - math.min(register, 2047))
|
||||
if event.wave then frequency = frequency * 0.5 end
|
||||
local phase = self.phase
|
||||
self.phase = (phase + frequency / SAMPLE_RATE) % 1
|
||||
if event.wave then
|
||||
local wave = self.engine.waves[
|
||||
math.min(event.waveInstrument + 1, #self.engine.waves)]
|
||||
-- a def-local program may omit its wave table entirely
|
||||
if not wave then return 0 end
|
||||
local index = math.min(32, math.floor(phase * 32) + 1)
|
||||
return wave[index] * event.waveLevel * 0.55
|
||||
end
|
||||
local duty = event.duty
|
||||
if type(duty) == "table" then
|
||||
duty = duty[frame % 4 + 1]
|
||||
end
|
||||
return (phase < duty and 1 or -1) * volume / 15 * 0.5
|
||||
end
|
||||
|
||||
local Engine = {}
|
||||
Engine.__index = Engine
|
||||
|
||||
function Engine:noiseInstrument(number)
|
||||
-- a def-local drum wins over the ROM engine's table for that id
|
||||
local custom = self.customDrums and self.customDrums[number]
|
||||
if custom then return custom end
|
||||
local cached = self.noiseInstruments[number]
|
||||
if cached then return cached end
|
||||
|
||||
local header = self.noiseHeaders[tostring(number)]
|
||||
local segments = {}
|
||||
if header then
|
||||
local spec = headerChannels(self.banks, header)[1]
|
||||
local address = spec and spec.address
|
||||
local ticks = 0
|
||||
for _ = 1, 64 do
|
||||
local command = romByte(self.banks, header.bank, address)
|
||||
address = address + 1
|
||||
if command == 0xFF then break end
|
||||
if command < 0x20 or command >= 0x30 then
|
||||
error(("unsupported drum command %02X at %02X:%04X")
|
||||
:format(command, header.bank, address - 1))
|
||||
end
|
||||
local packed = romByte(self.banks, header.bank, address)
|
||||
local parameter = romByte(self.banks, header.bank, address + 1)
|
||||
address = address + 2
|
||||
local duration = (bit.band(command, 0x0F) + 1) * FRAME_TICKS
|
||||
segments[#segments + 1] = {
|
||||
startSample = snapTicks(ticks),
|
||||
endSample = snapTicks(ticks + duration),
|
||||
volume = bit.rshift(packed, 4),
|
||||
fade = fadeValue(bit.band(packed, 0x0F)),
|
||||
parameter = parameter,
|
||||
}
|
||||
ticks = ticks + duration
|
||||
end
|
||||
end
|
||||
|
||||
self.noiseInstruments[number] = segments
|
||||
return segments
|
||||
end
|
||||
|
||||
local function readWaves(banks, audio, engineNumber)
|
||||
local spec = audio.waveBanks[tostring(engineNumber)]
|
||||
local waves = {}
|
||||
for wave = 0, 4 do
|
||||
local values = {}
|
||||
for byteIndex = 0, 15 do
|
||||
local packed = romByte(
|
||||
banks, spec.bank, spec.address + wave * 16 + byteIndex)
|
||||
values[#values + 1] = (bit.rshift(packed, 4) - 7.5) / 7.5
|
||||
values[#values + 1] = (bit.band(packed, 0x0F) - 7.5) / 7.5
|
||||
end
|
||||
waves[#waves + 1] = values
|
||||
end
|
||||
local values = {}
|
||||
for byteIndex = 0, 15 do
|
||||
local packed = romByte(
|
||||
banks, spec.bank, spec.address + 5 * 16 + byteIndex)
|
||||
values[#values + 1] = (bit.rshift(packed, 4) - 7.5) / 7.5
|
||||
values[#values + 1] = (bit.band(packed, 0x0F) - 7.5) / 7.5
|
||||
end
|
||||
for _ = 1, 4 do waves[#waves + 1] = values end
|
||||
return waves
|
||||
end
|
||||
|
||||
-- def-local waves are authored either as raw 0-15 nibbles (the ROM's own
|
||||
-- units) or as the -1..1 samples readWaves produces; the synth wants the
|
||||
-- latter
|
||||
local function normalizeWaves(source)
|
||||
local waves = {}
|
||||
for index, values in ipairs(source) do
|
||||
local nibbles = false
|
||||
for _, value in ipairs(values) do
|
||||
if value > 1 or value < -1 then nibbles = true break end
|
||||
end
|
||||
local wave = {}
|
||||
for position, value in ipairs(values) do
|
||||
wave[position] = nibbles and (value - 7.5) / 7.5 or value
|
||||
end
|
||||
waves[index] = wave
|
||||
end
|
||||
return waves
|
||||
end
|
||||
|
||||
function Engine.new(data, header, options)
|
||||
options = options or {}
|
||||
local audio = data.audio or {}
|
||||
-- shape dispatch: a def-local chip program supplies its own channels and
|
||||
-- may supply its own waves/drums, falling back to a ROM engine's tables
|
||||
local chip = header.chip
|
||||
local banks = engineBanks(data, chip)
|
||||
local engineNumber = chip and (chip.engine or 1) or header.engine
|
||||
local waves
|
||||
if chip and chip.waves then
|
||||
waves = normalizeWaves(chip.waves)
|
||||
elseif chip then
|
||||
local ok, romWaves = pcall(readWaves, banks, audio, engineNumber)
|
||||
waves = ok and romWaves or {}
|
||||
else
|
||||
waves = readWaves(banks, audio, engineNumber)
|
||||
end
|
||||
local engine = setmetatable({
|
||||
banks = banks,
|
||||
tempo = 0x100,
|
||||
pan = 0xFF,
|
||||
waves = waves,
|
||||
noiseHeaders = audio.noiseHeaders
|
||||
and audio.noiseHeaders[tostring(engineNumber)] or {},
|
||||
customDrums = chip and chip.drums or nil,
|
||||
noiseInstruments = {},
|
||||
channels = {},
|
||||
}, Engine)
|
||||
for _, spec in ipairs(chip and chip.channels
|
||||
or headerChannels(banks, header)) do
|
||||
local frameTicks = options.frameTicks
|
||||
local hardware = (spec.number - 1) % 4 + 1
|
||||
if hardware == 4 then
|
||||
frameTicks = FRAME_TICKS
|
||||
elseif options.cryLength then
|
||||
frameTicks = 0x80 + options.cryLength
|
||||
end
|
||||
engine.channels[#engine.channels + 1] = Channel.new(engine, spec, {
|
||||
bank = chip and 0 or header.bank,
|
||||
sfx = options.sfx,
|
||||
allowLoops = options.allowLoops,
|
||||
frequencyOffset = options.frequencyOffset,
|
||||
frameTicks = frameTicks,
|
||||
})
|
||||
end
|
||||
return engine
|
||||
end
|
||||
|
||||
function Engine:finished()
|
||||
for _, channel in ipairs(self.channels) do
|
||||
if not channel.ended or channel.event then return false end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function Engine:sample()
|
||||
local value = 0
|
||||
for _, channel in ipairs(self.channels) do value = value + channel:sample() end
|
||||
return math.max(-1, math.min(1, value * 0.5))
|
||||
end
|
||||
|
||||
function Engine:sampleStereo()
|
||||
local left, right = 0, 0
|
||||
for _, channel in ipairs(self.channels) do
|
||||
local value = channel:sample()
|
||||
local event = channel.event
|
||||
if not event or event.panLeft ~= false then left = left + value end
|
||||
if not event or event.panRight ~= false then right = right + value end
|
||||
end
|
||||
return math.max(-1, math.min(1, left * 0.5)),
|
||||
math.max(-1, math.min(1, right * 0.5))
|
||||
end
|
||||
|
||||
function Engine:sampleChannel(number)
|
||||
local selected = 0
|
||||
for _, channel in ipairs(self.channels) do
|
||||
local value = channel:sample()
|
||||
if channel.number == number then selected = value end
|
||||
end
|
||||
return math.max(-1, math.min(1, selected * 0.5))
|
||||
end
|
||||
|
||||
-- render `samples` frames into a fresh SoundData (mono or stereo). love.sound
|
||||
-- is available on worker threads, so this is the hand-off unit the worker
|
||||
-- produces and the main thread queues.
|
||||
local function soundData(engine, samples, channels)
|
||||
local result = love.sound.newSoundData(samples, SAMPLE_RATE, 16, channels)
|
||||
for index = 0, samples - 1 do
|
||||
if channels == 2 then
|
||||
local left, right = engine:sampleStereo()
|
||||
result:setSample(index, 1, left)
|
||||
result:setSample(index, 2, right)
|
||||
else
|
||||
result:setSample(index, engine:sample())
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
-- Render a one-shot effect (SFX/cry) to a mono SoundData, or nil when it is
|
||||
-- too short to be audible. The caller wraps it in a static love.audio.Source
|
||||
-- (a playback concern, hence not done here).
|
||||
local function renderEffectData(data, header, options)
|
||||
if not header then return nil end
|
||||
options = options or {}
|
||||
options.sfx = true
|
||||
options.allowLoops = false
|
||||
local engine = Engine.new(data, header, options)
|
||||
local maximum = SAMPLE_RATE * 5
|
||||
local values = {}
|
||||
local count = 0
|
||||
while count < maximum and not engine:finished() do
|
||||
count = count + 1
|
||||
values[count] = engine:sample()
|
||||
end
|
||||
if count < math.floor(SAMPLE_RATE / 100) then return nil end
|
||||
local result = love.sound.newSoundData(count, SAMPLE_RATE, 16, 1)
|
||||
for index = 1, count do result:setSample(index - 1, values[index]) end
|
||||
return result
|
||||
end
|
||||
|
||||
ChipSynth.newEngine = Engine.new
|
||||
ChipSynth.soundData = soundData
|
||||
ChipSynth.renderEffectData = renderEffectData
|
||||
|
||||
return ChipSynth
|
||||
@@ -0,0 +1,72 @@
|
||||
-- Render frame-rate cap. With a driver control panel forcing
|
||||
-- vsync off, the 160x144 game is trivially cheap and love.run will present
|
||||
-- thousands of frames a second; over hours that cooks the graphics driver
|
||||
-- until a restart, and it wastes power whenever the window is left open in
|
||||
-- the background. A hard cap bounds the present rate. Render-only: game
|
||||
-- logic is fixed-step off dt (src/core/FixedStep.lua), so pacing present()
|
||||
-- changes nothing about timing, audio, or determinism.
|
||||
--
|
||||
-- Persisted as save.options.fpsCap; applied from OptionsMenu and on boot
|
||||
-- via Game:applyOptions. main.lua's love.run reads FrameCap.current each
|
||||
-- frame for its sleep budget. The module never touches love.timer itself,
|
||||
-- so it stays safe under the headless test stub.
|
||||
|
||||
local FrameCap = {}
|
||||
|
||||
-- Selectable steps: the normal framerate stops between the floor and the
|
||||
-- ceiling. STEPS[1] == MIN and STEPS[#STEPS] == MAX, so the nearest-step
|
||||
-- snap in normalize doubles as the clamp. Cycling past the last wraps.
|
||||
FrameCap.STEPS = { 30, 40, 50, 60, 75, 90, 100, 120, 144, 160 }
|
||||
FrameCap.MIN = 30
|
||||
FrameCap.MAX = 160
|
||||
FrameCap.DEFAULT = 60
|
||||
|
||||
-- The live cap the run loop paces to. Defaults so the launcher and the
|
||||
-- save editor are paced before any save applies its stored option.
|
||||
FrameCap.current = FrameCap.DEFAULT
|
||||
|
||||
-- Nearest valid step for an arbitrary value (a hand-edited options.lua or
|
||||
-- an old save with no fpsCap key), so a bad number degrades to something
|
||||
-- sane; nil / non-numbers fall back to the default. A value below MIN or
|
||||
-- above MAX snaps to that end, since MIN/MAX are the first/last steps.
|
||||
function FrameCap.normalize(value)
|
||||
value = tonumber(value)
|
||||
if not value then return FrameCap.DEFAULT end
|
||||
local best, bestDiff = FrameCap.DEFAULT, math.huge
|
||||
for _, step in ipairs(FrameCap.STEPS) do
|
||||
local diff = math.abs(step - value)
|
||||
if diff < bestDiff then best, bestDiff = step, diff end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- plain numeric text for the options row (e.g. "60")
|
||||
function FrameCap.label(value)
|
||||
return tostring(FrameCap.normalize(value))
|
||||
end
|
||||
|
||||
-- cycle to the next/previous step, wrapping (the options row idiom)
|
||||
function FrameCap.cycle(value, dir)
|
||||
local steps = FrameCap.STEPS
|
||||
local snapped = FrameCap.normalize(value)
|
||||
local cur = 1
|
||||
for i, step in ipairs(steps) do
|
||||
if step == snapped then cur = i break end
|
||||
end
|
||||
local nextIdx = (cur - 1 + (dir or 1)) % #steps + 1
|
||||
return steps[nextIdx]
|
||||
end
|
||||
|
||||
-- Store the chosen cap as the live value the run loop paces to. Never
|
||||
-- touches love.timer, so it is safe headless -- the loop just reads the
|
||||
-- number back. Returns the normalized value it stored.
|
||||
function FrameCap.apply(value)
|
||||
FrameCap.current = FrameCap.normalize(value)
|
||||
return FrameCap.current
|
||||
end
|
||||
|
||||
function FrameCap.applyOptions(opts)
|
||||
FrameCap.apply(opts and opts.fpsCap)
|
||||
end
|
||||
|
||||
return FrameCap
|
||||
+56
-6
@@ -17,7 +17,7 @@ local Game = {}
|
||||
|
||||
-- dev-mode gate for the F5/backtick hotkeys; false keeps every src/dev
|
||||
-- module unloaded, so a player boot never touches a byte of dev code
|
||||
local devMode = os.getenv("POKEPORT_DEV") == "1"
|
||||
local devMode = os.getenv("POKEPORT_DEV") == "1" or _G.POKEPORT_DEV_MODE == true
|
||||
|
||||
-- the boot screen ids (field.boot.screens); a plain function so the
|
||||
-- headless harness can borrow makeTitleState onto a stub game
|
||||
@@ -99,7 +99,12 @@ end
|
||||
-- total conversion overrides. Threaded into SaveData so persistence stays
|
||||
-- free of a Data dependency.
|
||||
function Game:bootConfig()
|
||||
return self.data and self.data.field and self.data.field.boot
|
||||
local boot = self.data and self.data.field and self.data.field.boot
|
||||
-- stamp the running game version onto the boot config so a New Game records
|
||||
-- it (SaveData.newGame reads boot.version); this is what routes a Blue
|
||||
-- playthrough to save_blue.lua and Blue's version-gated content
|
||||
if boot then boot.version = require("src.core.GameVersion").get() end
|
||||
return boot
|
||||
end
|
||||
|
||||
-- the title screen with its NEW GAME / CONTINUE wiring; used at boot
|
||||
@@ -194,6 +199,13 @@ function Game:update(dt)
|
||||
-- frame dt (not the fixed logic step) for a smooth ~0.25s glide.
|
||||
require("src.render.Tilt").update(dt)
|
||||
pcall(function() require("src.core.DiscordPresence").update(dt) end)
|
||||
-- Steady-state memory backstop: advance the incremental collector one
|
||||
-- small step every rendered frame. The heavy GPU objects are now freed
|
||||
-- explicitly (map eviction, battle exit, canvas/renderer swaps), so this
|
||||
-- only has to keep ordinary Lua-heap garbage (per-frame tables/closures)
|
||||
-- from drifting upward over a long session, and to spread collection out
|
||||
-- so the default lazy schedule never batches it into a visible pause.
|
||||
if collectgarbage then collectgarbage("step", 1) end
|
||||
end
|
||||
|
||||
-- render.zones' identity default: unhooked, the zone list reaches the blit
|
||||
@@ -283,10 +295,22 @@ function Game:keypressed(key)
|
||||
self:zoomStep(1)
|
||||
return
|
||||
elseif key == "2" then
|
||||
-- cycle COLORS (GBC / OG / OG INV / GBC INV / CLASSIC); always on
|
||||
local PaletteFX = require("src.render.PaletteFX")
|
||||
self.save.options.colors = PaletteFX.cycleMode()
|
||||
self:writeOptions()
|
||||
-- cycle COLORS (GBC / OG / OG INV / GBC INV / CLASSIC); the pack change
|
||||
-- forces Game.overworld:reloadMap, which rebuilds the live NPC array, so
|
||||
-- hold it while a warp/transition or an on-screen scripted cutscene is
|
||||
-- driving the overworld rather than tear the escort's NPCs out mid-move
|
||||
local ow = self.overworld
|
||||
local top = self.stack:top()
|
||||
local busy = ow and (ow.transitioning
|
||||
or (top == ow and (
|
||||
(ow.runner and ow.runner.isRunning and ow.runner:isRunning())
|
||||
or (ow.scriptMoves and #ow.scriptMoves > 0)
|
||||
or ow.engaging or ow.emote)))
|
||||
if not busy then
|
||||
local PaletteFX = require("src.render.PaletteFX")
|
||||
self.save.options.colors = PaletteFX.cycleMode()
|
||||
self:writeOptions()
|
||||
end
|
||||
return
|
||||
elseif key == "3" then
|
||||
-- cycle TILT OFF → 15 → 35 → 50 → OFF (mnemonic: 3D), free-roam only
|
||||
@@ -337,6 +361,28 @@ function Game:gamepadaxis(joystick, axis, value)
|
||||
Input:gamepadaxis(joystick, axis, value)
|
||||
end
|
||||
|
||||
-- Window focus/visibility flips: a release due while unfocused/hidden can
|
||||
-- be swallowed by the OS. Reset on both edges -- gaining focus with a
|
||||
-- physically held key won't re-fire keypressed, so trusting leftover
|
||||
-- state is worse than asking the player to re-press.
|
||||
function Game:focus(f)
|
||||
Input:reset()
|
||||
TouchInput:reset()
|
||||
end
|
||||
|
||||
function Game:visible(v)
|
||||
Input:reset()
|
||||
TouchInput:reset()
|
||||
end
|
||||
|
||||
-- A disconnected/dropped controller can't send the button-up for whatever
|
||||
-- it was holding, so drop all input state rather than try to guess which
|
||||
-- flags it owned.
|
||||
function Game:joystickremoved(joystick)
|
||||
Input:reset()
|
||||
TouchInput:reset()
|
||||
end
|
||||
|
||||
function Game:touchpressed(id, x, y)
|
||||
TouchInput:touchpressed(id, x, y)
|
||||
end
|
||||
@@ -399,6 +445,10 @@ function Game:applyOptions(opts)
|
||||
require("src.render.Tilt").applyOptions(opts)
|
||||
require("src.render.GBCFX").applyOptions(opts)
|
||||
require("src.core.VideoMode").applyOptions(opts)
|
||||
-- normalizes a nil/garbage cap to the 60 default, so old saves with no
|
||||
-- fpsCap key pace at the standard rate (issue #88)
|
||||
require("src.core.FrameCap").applyOptions(opts)
|
||||
Input:applyBindings(opts.bindings)
|
||||
end
|
||||
|
||||
function Game:restoreSave(loaded, recovered)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
-- Which Gen-1 game this process is running: Red (the historical default) or
|
||||
-- Blue. One source of truth for everything that differs by version -- the
|
||||
-- accepted ROM hash, the import manifest, where the extracted cache lives,
|
||||
-- and the save-file suffix -- so the importer, cache mount, SaveData, title
|
||||
-- screen and palette all agree.
|
||||
--
|
||||
-- Red keeps every un-suffixed path it always used (save.lua, the root cache),
|
||||
-- so existing installs are untouched; Blue is namespaced under blue/ and
|
||||
-- _blue so both can be imported and played side by side.
|
||||
--
|
||||
-- Zero requires, so it loads during love.conf and under plain Lua for tools
|
||||
-- and tests. The active version is a process-global set once at boot from
|
||||
-- the launcher's column choice (main.lua); it defaults to Red.
|
||||
|
||||
local GameVersion = {}
|
||||
|
||||
GameVersion.VERSIONS = {
|
||||
red = {
|
||||
id = "red",
|
||||
label = "Red",
|
||||
displayName = "Pokemon Red",
|
||||
sha1 = "ea9bcae617fdf159b045185467ae58b2e4a48b9a",
|
||||
manifest = "tools/rom_manifest.json",
|
||||
cachePrefix = "", -- Red owns the cache root (backwards compatible)
|
||||
saveSuffix = "", -- save.lua / save.lua.bak / save.lua.tmp
|
||||
},
|
||||
blue = {
|
||||
id = "blue",
|
||||
label = "Blue",
|
||||
displayName = "Pokemon Blue",
|
||||
sha1 = "d7037c83e1ae5b39bde3c30787637ba1d4c48ce2",
|
||||
manifest = "tools/rom_manifest_blue.json",
|
||||
cachePrefix = "blue/", -- blue/data/generated, blue/assets/generated
|
||||
saveSuffix = "_blue", -- save_blue.lua / .bak / .tmp
|
||||
},
|
||||
}
|
||||
|
||||
-- Launcher column order (Yellow is still a placeholder, handled by the UI).
|
||||
GameVersion.ORDER = { "red", "blue" }
|
||||
|
||||
GameVersion.current = "red"
|
||||
|
||||
function GameVersion.set(id)
|
||||
GameVersion.current = GameVersion.VERSIONS[id] and id or "red"
|
||||
return GameVersion.current
|
||||
end
|
||||
|
||||
function GameVersion.get()
|
||||
return GameVersion.current
|
||||
end
|
||||
|
||||
function GameVersion.isBlue()
|
||||
return GameVersion.current == "blue"
|
||||
end
|
||||
|
||||
-- Metadata for a version id, defaulting to the active one.
|
||||
function GameVersion.info(id)
|
||||
return GameVersion.VERSIONS[id or GameVersion.current]
|
||||
end
|
||||
|
||||
function GameVersion.saveSuffix(id)
|
||||
return GameVersion.info(id).saveSuffix
|
||||
end
|
||||
|
||||
function GameVersion.cachePrefix(id)
|
||||
return GameVersion.info(id).cachePrefix
|
||||
end
|
||||
|
||||
-- The version a ROM belongs to, by its SHA-1, or nil for an unknown ROM.
|
||||
function GameVersion.forSha1(sha1)
|
||||
for id, info in pairs(GameVersion.VERSIONS) do
|
||||
if info.sha1 == sha1 then return id end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return GameVersion
|
||||
+102
-16
@@ -3,7 +3,7 @@
|
||||
|
||||
local Input = {}
|
||||
|
||||
local BINDINGS = {
|
||||
local DEFAULT_BINDINGS = {
|
||||
up = "up", w = "up",
|
||||
down = "down", s = "down",
|
||||
left = "left", a = "left",
|
||||
@@ -18,8 +18,11 @@ local BINDINGS = {
|
||||
-- Escape = start for desktop friendliness.
|
||||
|
||||
-- LÖVE's standard gamepad mapping (SDL game controller DB), consistent
|
||||
-- across Xbox/PlayStation/generic controllers on desktop and mobile.
|
||||
local GAMEPAD_BINDINGS = {
|
||||
-- across Xbox/PlayStation/generic controllers on desktop and mobile. Some
|
||||
-- third-party pads report their own SDL mapping for a given physical
|
||||
-- button (e.g. Select/Back/View on off-brand XInput pads), which is what
|
||||
-- src/ui/BindingsMenu.lua's rebinding is for -- see applyBindings below.
|
||||
local DEFAULT_GAMEPAD_BINDINGS = {
|
||||
dpup = "up", dpdown = "down", dpleft = "left", dpright = "right",
|
||||
a = "a", b = "b",
|
||||
start = "start", back = "select",
|
||||
@@ -32,48 +35,131 @@ local STICK_ON = 0.5
|
||||
local STICK_OFF = 0.3
|
||||
|
||||
function Input:init()
|
||||
self:applyBindings(nil)
|
||||
self:reset()
|
||||
end
|
||||
|
||||
-- Layers a player's rebind choices (save.options.bindings, written by
|
||||
-- src/ui/BindingsMenu.lua) on top of the defaults above. A rebind adds an
|
||||
-- extra way to trigger that action instead of replacing the default key,
|
||||
-- so e.g. Z/Enter/Space all still press A even after binding a 4th key to
|
||||
-- it. Call whenever options load or change (see Game:applyOptions and
|
||||
-- BindingsMenu:storeBinding) -- without this the menu records a choice
|
||||
-- that never actually reaches gameplay.
|
||||
function Input:applyBindings(overlay)
|
||||
local keys, pads = {}, {}
|
||||
for key, action in pairs(DEFAULT_BINDINGS) do keys[key] = action end
|
||||
for button, action in pairs(DEFAULT_GAMEPAD_BINDINGS) do pads[button] = action end
|
||||
for actionId, binding in pairs(overlay or {}) do
|
||||
if type(binding) == "table" then
|
||||
if binding.key then keys[binding.key] = actionId end
|
||||
if binding.pad then pads[binding.pad] = actionId end
|
||||
elseif type(binding) == "string" then
|
||||
keys[binding] = actionId
|
||||
end
|
||||
end
|
||||
self.keyBindings = keys
|
||||
self.padBindings = pads
|
||||
end
|
||||
|
||||
-- Purely event-driven state (press sets true, release sets false) has no
|
||||
-- fallback if a release event never arrives -- focus loss, a minimized
|
||||
-- window, or a disconnected gamepad can all swallow the key-up/button-up
|
||||
-- that would have cleared a held direction. Called from Game on those
|
||||
-- transitions so a stuck flag can't outlive them.
|
||||
function Input:reset()
|
||||
self.state = {}
|
||||
self.pressQueue = {}
|
||||
self.pressed = {}
|
||||
self.sources = {}
|
||||
self.stickAxis = { x = 0, y = 0 }
|
||||
self.stickDir = nil
|
||||
end
|
||||
|
||||
function Input:keypressed(key)
|
||||
local btn = BINDINGS[key]
|
||||
if btn then
|
||||
-- Multiple physical sources (W + Up, d-pad + stick, etc.) can claim the
|
||||
-- same GB button. Track them individually so releasing one doesn't clear
|
||||
-- a hold another source still owns, and so a press+release that both land
|
||||
-- before the next FixedStep can't be revived when step() drains the queue.
|
||||
local function press(self, btn, source)
|
||||
local sources = self.sources[btn]
|
||||
if not sources then
|
||||
sources = {}
|
||||
self.sources[btn] = sources
|
||||
end
|
||||
if not sources[source] then
|
||||
sources[source] = true
|
||||
table.insert(self.pressQueue, btn)
|
||||
end
|
||||
self.state[btn] = true
|
||||
end
|
||||
|
||||
function Input:keyreleased(key)
|
||||
local btn = BINDINGS[key]
|
||||
if btn then
|
||||
local function release(self, btn, source)
|
||||
local sources = self.sources[btn]
|
||||
if sources then
|
||||
sources[source] = nil
|
||||
if next(sources) == nil then
|
||||
-- Leave an empty table (not nil) so step() can tell a real
|
||||
-- source was released before the queue drained, versus a
|
||||
-- synthetic pressQueue inject that never had sources at all.
|
||||
self.state[btn] = false
|
||||
end
|
||||
else
|
||||
self.state[btn] = false
|
||||
end
|
||||
end
|
||||
|
||||
function Input:keypressed(key)
|
||||
local btn = self.keyBindings[key]
|
||||
if btn then
|
||||
press(self, btn, "key:" .. key)
|
||||
end
|
||||
end
|
||||
|
||||
function Input:keyreleased(key)
|
||||
local btn = self.keyBindings[key]
|
||||
if btn then
|
||||
release(self, btn, "key:" .. key)
|
||||
end
|
||||
end
|
||||
|
||||
-- Called once per fixed step: promote queued presses to this step's edges.
|
||||
-- Hold state is owned by live sources (updated in press/release), not
|
||||
-- re-asserted here -- otherwise a same-frame press→release leaves the
|
||||
-- button stuck on after the queue drains.
|
||||
-- Synthetic injects (tests/drivers writing pressQueue directly, with no
|
||||
-- source entry) still set state so scripted holds keep working.
|
||||
function Input:step()
|
||||
self.pressed = {}
|
||||
for _, btn in ipairs(self.pressQueue) do
|
||||
self.pressed[btn] = true
|
||||
self.state[btn] = true
|
||||
local sources = self.sources[btn]
|
||||
if sources == nil then
|
||||
-- synthetic pressQueue inject (tests/drivers): no live source map
|
||||
self.state[btn] = true
|
||||
elseif next(sources) ~= nil then
|
||||
self.state[btn] = true
|
||||
end
|
||||
-- sources == {}: real press fully released before this step — keep up
|
||||
end
|
||||
for btn, sources in pairs(self.sources) do
|
||||
if next(sources) == nil then
|
||||
self.sources[btn] = nil
|
||||
end
|
||||
end
|
||||
self.pressQueue = {}
|
||||
end
|
||||
|
||||
function Input:gamepadpressed(joystick, button)
|
||||
local btn = GAMEPAD_BINDINGS[button]
|
||||
local btn = self.padBindings[button]
|
||||
if btn then
|
||||
table.insert(self.pressQueue, btn)
|
||||
press(self, btn, "pad:" .. button)
|
||||
end
|
||||
end
|
||||
|
||||
function Input:gamepadreleased(joystick, button)
|
||||
local btn = GAMEPAD_BINDINGS[button]
|
||||
local btn = self.padBindings[button]
|
||||
if btn then
|
||||
self.state[btn] = false
|
||||
release(self, btn, "pad:" .. button)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -103,10 +189,10 @@ function Input:gamepadaxis(joystick, axis, value)
|
||||
|
||||
if newDir ~= self.stickDir then
|
||||
if self.stickDir then
|
||||
self.state[self.stickDir] = false
|
||||
release(self, self.stickDir, "stick")
|
||||
end
|
||||
if newDir then
|
||||
table.insert(self.pressQueue, newDir)
|
||||
press(self, newDir, "stick")
|
||||
end
|
||||
self.stickDir = newDir
|
||||
end
|
||||
|
||||
+15
-1
@@ -114,6 +114,7 @@ local SPECIAL = {
|
||||
oakRoute = "Music_Routes2",
|
||||
bike = "Music_BikeRiding",
|
||||
surf = "Music_Surfing",
|
||||
evolution = "Music_SafariZone",
|
||||
}
|
||||
|
||||
-- the label a scene role resolves to; call sites keep their own presence
|
||||
@@ -253,6 +254,7 @@ function Music.stop()
|
||||
require("src.core.ChipAudio").stopMusic()
|
||||
state.current, state.source, state.loopSource, state.fade = nil, nil, nil, nil
|
||||
state.chip = false
|
||||
state.pendingRestore = nil
|
||||
if previous and Runtime.wants("music.stopped") then
|
||||
Runtime.emit("music.stopped", { song = previous })
|
||||
end
|
||||
@@ -346,14 +348,24 @@ end
|
||||
function Music.playOnce(data, song)
|
||||
if not songDef(data, song) then return false end
|
||||
Music.play(data, song, false, { reason = "once" })
|
||||
-- play() can no-op (hook silence, failed def); only arm restore when
|
||||
-- the jingle actually became current
|
||||
if state.current ~= song then return false end
|
||||
state.pendingRestore = true
|
||||
return true
|
||||
end
|
||||
|
||||
local function chipAwaitingFirstBuffer()
|
||||
return state.chip
|
||||
and require("src.core.ChipAudio").awaitingFirstBuffer()
|
||||
end
|
||||
|
||||
-- is a playOnce jingle still sounding? (AnimateHealingMachine's
|
||||
-- .waitLoop2 holds the healing machine until MUSIC_PKMN_HEALED ends)
|
||||
function Music.oneShotPlaying()
|
||||
if not state.pendingRestore then return false end
|
||||
-- threaded chip songs start silent for ~1 frame; that gap is not "over"
|
||||
if chipAwaitingFirstBuffer() then return true end
|
||||
local src = state.source
|
||||
if not src then return false end
|
||||
local ok, playing = pcall(src.isPlaying, src)
|
||||
@@ -440,8 +452,10 @@ function Music.update(data)
|
||||
state.source = loopSrc
|
||||
pcall(loopSrc.play, loopSrc)
|
||||
end
|
||||
-- do not treat "threaded source still waiting on its first buffer" as
|
||||
-- ended, or playOnce jingles get restored over before they can sound
|
||||
if state.pendingRestore and sourceStopped(state.source)
|
||||
and not state.loopSource then
|
||||
and not state.loopSource and not chipAwaitingFirstBuffer() then
|
||||
Music.restoreMap(data)
|
||||
end
|
||||
end
|
||||
|
||||
+176
-11
@@ -18,14 +18,157 @@ local Semver = require("src.mods.Semver")
|
||||
local Boxes = require("src.pokemon.Boxes")
|
||||
local Bag = require("src.inventory.Bag")
|
||||
|
||||
local GameVersion = require("src.core.GameVersion")
|
||||
|
||||
local SaveData = {}
|
||||
|
||||
local FILENAME = "save.lua"
|
||||
-- Progress files carry the game-version suffix so Red and Blue saves coexist:
|
||||
-- Red keeps save.lua / .bak / .tmp exactly as before; Blue is save_blue.lua
|
||||
-- (+ .bak/.tmp). options.lua is deliberately shared across versions (it holds
|
||||
-- global preferences and the mod enable-state, not per-playthrough data).
|
||||
local OPTIONS_FILENAME = "options.lua"
|
||||
-- one rolling backup plus the staged-write witness; load promotes either
|
||||
-- when the main file is missing or fails to parse
|
||||
local BACKUP_FILENAME = FILENAME .. ".bak"
|
||||
local TMP_FILENAME = FILENAME .. ".tmp"
|
||||
|
||||
-- Main / backup / staged-witness names for a version (defaults to the active
|
||||
-- one). The backup is a rolling copy and .tmp is the staged-write witness;
|
||||
-- load promotes either when the main file is missing or fails to parse.
|
||||
local function saveNames(version)
|
||||
local main = "save" .. GameVersion.saveSuffix(version) .. ".lua"
|
||||
return main, main .. ".bak", main .. ".tmp"
|
||||
end
|
||||
|
||||
-- The main save filename for a version -- used by the title screen's
|
||||
-- CONTINUE gate so it looks for the right game's save.
|
||||
function SaveData.saveFilename(version)
|
||||
local main = saveNames(version)
|
||||
return main
|
||||
end
|
||||
|
||||
-- ------- portable mode
|
||||
-- LÖVE's save directory is always the OS per-user path derived from the
|
||||
-- identity (conf.lua), so it can't be relocated at runtime. Portable mode
|
||||
-- instead drops a plain-Lua io.* filesystem next to the game whenever a
|
||||
-- `portable.txt` marker sits beside the executable/source, letting a USB
|
||||
-- copy carry its own save.lua/options.lua (and, through options.lua, the
|
||||
-- mod enable-state) rather than leaving them on the host machine.
|
||||
local PORTABLE_MARKER = "portable.txt"
|
||||
local SEP = package.config:sub(1, 1)
|
||||
|
||||
local portableChecked = false
|
||||
local portableBase = false -- resolved base dir when active, else false
|
||||
local portableFsCache = nil
|
||||
|
||||
local function pathExists(path)
|
||||
local f = io.open(path, "rb")
|
||||
if not f then return false end
|
||||
f:close()
|
||||
return true
|
||||
end
|
||||
|
||||
-- an io.* filesystem exposing the love.filesystem subset the save/options
|
||||
-- round-trip needs (getInfo/read/write/remove), rooted at `dir`
|
||||
local function makePortableFs(dir)
|
||||
local function full(name) return dir .. SEP .. name end
|
||||
return {
|
||||
getInfo = function(name)
|
||||
if not pathExists(full(name)) then return nil end
|
||||
return { type = "file" }
|
||||
end,
|
||||
read = function(name)
|
||||
local f = io.open(full(name), "rb")
|
||||
if not f then return nil, "no file: " .. name end
|
||||
local data = f:read("*a")
|
||||
f:close()
|
||||
return data
|
||||
end,
|
||||
write = function(name, data)
|
||||
local f, err = io.open(full(name), "wb")
|
||||
if not f then return false, err end
|
||||
f:write(data)
|
||||
f:close()
|
||||
return true
|
||||
end,
|
||||
remove = function(name)
|
||||
os.remove(full(name))
|
||||
return true
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local function detectPortable()
|
||||
if portableChecked then return portableBase end
|
||||
portableChecked = true
|
||||
portableBase = false
|
||||
if not (love and love.filesystem) then return false end
|
||||
-- Desktop only: portable mode carries the save (and, since issue #74, the
|
||||
-- ROM cache) in the game folder next to the executable/source. On
|
||||
-- Android/iOS the source is a read-only package with no such folder, so
|
||||
-- portable mode never applies there.
|
||||
if love.system and love.system.getOS then
|
||||
local osName = love.system.getOS()
|
||||
if osName ~= "Windows" and osName ~= "Linux" and osName ~= "OS X" then
|
||||
return false
|
||||
end
|
||||
end
|
||||
local src = love.filesystem.getSource and love.filesystem.getSource()
|
||||
local sbd = love.filesystem.getSourceBaseDirectory
|
||||
and love.filesystem.getSourceBaseDirectory()
|
||||
-- A packaged macOS build nests the game inside gen1recomp.app/Contents/
|
||||
-- Resources, so getSource()/getSourceBaseDirectory() point INSIDE the
|
||||
-- bundle -- not where the player drops portable.txt (next to the .app).
|
||||
-- Recover the folder containing the .app so a packaged app finds its
|
||||
-- marker. On Windows/Linux the executable is not a bundle, so this is nil
|
||||
-- and the plain source-base directory (next to the .exe/AppImage) is used.
|
||||
local function appContainer(path)
|
||||
local appPath = path and path:match("^(.*%.app)/Contents/")
|
||||
return appPath and appPath:match("^(.*)/[^/]+$") or nil
|
||||
end
|
||||
-- Order: the .app's containing folder (packaged macOS), then the
|
||||
-- source-base directory (next to a packaged .exe/AppImage), then the
|
||||
-- source itself (a `love <gamedir>` run drops portable.txt in the game
|
||||
-- folder). First one holding the marker wins. Built by appending so a
|
||||
-- nil (e.g. no .app in the path) never truncates the ipairs scan.
|
||||
local candidates = {}
|
||||
local appDir = appContainer(src) or appContainer(sbd)
|
||||
if appDir then candidates[#candidates + 1] = appDir end
|
||||
if sbd then candidates[#candidates + 1] = sbd end
|
||||
if src then candidates[#candidates + 1] = src end
|
||||
for _, base in ipairs(candidates) do
|
||||
if base ~= "" and pathExists(base .. SEP .. PORTABLE_MARKER) then
|
||||
portableBase = base
|
||||
break
|
||||
end
|
||||
end
|
||||
return portableBase
|
||||
end
|
||||
|
||||
function SaveData.isPortable()
|
||||
return detectPortable() ~= false
|
||||
end
|
||||
|
||||
-- the raw portable-folder path (for callers building their own nested
|
||||
-- paths, e.g. the ROM-derived asset cache), or nil when portable mode
|
||||
-- is off
|
||||
function SaveData.portableBaseDir()
|
||||
return detectPortable() or nil
|
||||
end
|
||||
|
||||
-- the io.* filesystem for the active portable folder, or nil when off
|
||||
function SaveData.portableFs()
|
||||
local base = detectPortable()
|
||||
if not base then return nil end
|
||||
if not portableFsCache then portableFsCache = makePortableFs(base) end
|
||||
return portableFsCache
|
||||
end
|
||||
|
||||
-- Resolve the filesystem a persistent read/write should land on: an
|
||||
-- explicitly injected non-love fs (headless tests, the mod loader's stub)
|
||||
-- always wins; otherwise portable mode reroutes off the OS save directory.
|
||||
local function persistFs(fs)
|
||||
if fs and love and love.filesystem and fs ~= love.filesystem then
|
||||
return fs
|
||||
end
|
||||
return SaveData.portableFs() or fs or (love and love.filesystem)
|
||||
end
|
||||
|
||||
-- Port + original Options menu defaults. Missing keys on load are filled
|
||||
-- from this table so old options.lua files stay compatible.
|
||||
@@ -49,6 +192,8 @@ function SaveData.defaultOptions()
|
||||
gbcfx = 0,
|
||||
-- windowed | borderless (desktop fullscreen); ignored on mobile
|
||||
videoMode = "windowed",
|
||||
-- hard render frame-rate cap; render-only pacing (issue #88, FrameCap.lua)
|
||||
fpsCap = 60,
|
||||
-- Native mod enablement is an installation option, not save-slot data.
|
||||
-- Missing entries mean enabled so newly installed mods work by default.
|
||||
mods = {},
|
||||
@@ -94,7 +239,7 @@ end
|
||||
-- love.filesystem, so the mod loader's injected filesystem can carry the
|
||||
-- options round-trip headless (no love global).
|
||||
function SaveData.saveOptions(opts, fs)
|
||||
fs = fs or love.filesystem
|
||||
fs = persistFs(fs)
|
||||
opts = SaveData.mergeOptions(opts)
|
||||
-- modOptions is per-mod nested state: fold the on-disk sub-tree
|
||||
-- underneath (newest value winning per key) so one caller's partial
|
||||
@@ -123,7 +268,7 @@ function SaveData.saveOptions(opts, fs)
|
||||
end
|
||||
|
||||
function SaveData.loadOptions(fs)
|
||||
fs = fs or love.filesystem
|
||||
fs = persistFs(fs)
|
||||
local data, err = readTable(fs, OPTIONS_FILENAME)
|
||||
if not data then
|
||||
if fs.getInfo(OPTIONS_FILENAME) then
|
||||
@@ -311,7 +456,7 @@ end)
|
||||
-- afterwards either way
|
||||
SaveData.addCoreMigration(1, function(save)
|
||||
if type(save.options) == "table"
|
||||
and not love.filesystem.getInfo(OPTIONS_FILENAME) then
|
||||
and not persistFs(nil).getInfo(OPTIONS_FILENAME) then
|
||||
SaveData.saveOptions(save.options)
|
||||
end
|
||||
end)
|
||||
@@ -322,6 +467,17 @@ SaveData.addCoreMigration(1, function(save)
|
||||
Boxes.ensure(save)
|
||||
end)
|
||||
|
||||
-- game version (Red vs Blue) prep: saves written before Blue support
|
||||
-- existed carry no `version` tag, and Red is the only game that ever
|
||||
-- shipped, so default every untagged save to Red. from=2 so it catches
|
||||
-- every pre-bump save (format 1 and 2) and is skipped once re-stamped to
|
||||
-- the current format.
|
||||
SaveData.addCoreMigration(2, function(save)
|
||||
if not save.version then
|
||||
save.version = "red"
|
||||
end
|
||||
end)
|
||||
|
||||
-- ------- write
|
||||
|
||||
-- Game progress only; options are written separately via saveOptions.
|
||||
@@ -331,6 +487,9 @@ end)
|
||||
-- itself rolls the last good save into .bak and stages the new bytes as
|
||||
-- a .tmp witness before the swap, so a crash mid-write is recoverable.
|
||||
function SaveData.save(data, mods)
|
||||
-- write to the file matching this save's own version, not just the active
|
||||
-- one, so a Blue playthrough always lands in save_blue.lua
|
||||
local FILENAME, BACKUP_FILENAME, TMP_FILENAME = saveNames(data.version)
|
||||
if data.options then
|
||||
SaveData.saveOptions(data.options)
|
||||
end
|
||||
@@ -342,7 +501,7 @@ function SaveData.save(data, mods)
|
||||
if k ~= "options" then gameOnly[k] = v end
|
||||
end
|
||||
local encoded = SaveSerializer.encode(gameOnly)
|
||||
local fs = love.filesystem
|
||||
local fs = persistFs(nil)
|
||||
if fs.getInfo(FILENAME) then
|
||||
local prev = fs.read(FILENAME)
|
||||
if prev then fs.write(BACKUP_FILENAME, prev) end
|
||||
@@ -370,8 +529,11 @@ end
|
||||
-- returns the parsed save plus "tmp"/"bak" when the main file was gone
|
||||
-- or corrupt and a staged/backup copy was promoted; Game surfaces the
|
||||
-- recovery on the load report
|
||||
function SaveData.load()
|
||||
local fs = love.filesystem
|
||||
function SaveData.load(version)
|
||||
-- version defaults to the active game (set at boot from the launcher);
|
||||
-- an explicit version lets callers/tests load a specific game's save.
|
||||
local FILENAME, BACKUP_FILENAME, TMP_FILENAME = saveNames(version)
|
||||
local fs = persistFs(nil)
|
||||
local data, err = readTable(fs, FILENAME)
|
||||
local recovered
|
||||
if not data then
|
||||
@@ -658,6 +820,9 @@ function SaveData.newGame(boot)
|
||||
local heal = SaveData.defaultHeal(boot)
|
||||
local save = {
|
||||
meta = { format = Version.saveFormat, mods = {} },
|
||||
-- which game this playthrough is (Red vs Blue). Only Red ships today;
|
||||
-- boot carries the choice once Blue support lands.
|
||||
version = boot.version or "red",
|
||||
player = {
|
||||
map = map,
|
||||
x = x,
|
||||
|
||||
@@ -75,6 +75,21 @@ function TouchInput:init()
|
||||
self.selectFired = false -- one SELECT per two-finger gesture cluster
|
||||
end
|
||||
|
||||
-- LÖVE has no touchcancelled event, so a touch interrupted by the OS (app
|
||||
-- backgrounded mid-touch, a system gesture stealing the finger) never fires
|
||||
-- touchreleased and would otherwise strand its direction held forever.
|
||||
-- Called from Game alongside Input:reset() on focus/visibility loss.
|
||||
function TouchInput:reset()
|
||||
for _, touch in pairs(self.touches) do
|
||||
releaseDir(self, touch)
|
||||
end
|
||||
self.touches = {}
|
||||
self.pendingA = nil
|
||||
self.armed = {}
|
||||
self.autoRelease = {}
|
||||
self.selectFired = false
|
||||
end
|
||||
|
||||
local function pulse(self, key)
|
||||
Input:keypressed(key)
|
||||
self.armed[#self.armed + 1] = key
|
||||
|
||||
@@ -7,13 +7,13 @@ local Version = {
|
||||
engine = "1.0.0", -- game/engine release (semver triple)
|
||||
modApi = 2, -- mod API major (manifest `api`)
|
||||
linkProtocol = 2, -- link handshake wire version (Handshake.PROTOCOL)
|
||||
saveFormat = 2, -- save.meta.format
|
||||
saveFormat = 3, -- save.meta.format
|
||||
cache = "rom-cache-v5", -- ROM import cache generation (RomImporter marker)
|
||||
}
|
||||
|
||||
-- "Pokemon Red (Gen 1 Recompilation Project) v1.0.0"
|
||||
-- "gen1recomp v1.0.0"
|
||||
function Version.title(base)
|
||||
return (base or "Pokemon Red (Gen 1 Recompilation Project)")
|
||||
return (base or "gen1recomp")
|
||||
.. " v" .. Version.engine
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
-- ChipAudio synthesis worker (love.thread). Runs the Game Boy audio synth
|
||||
-- (src/core/ChipSynth.lua) off the main thread so a map/battle song change
|
||||
-- never stutters the render thread: filling the ~6s playback queue from
|
||||
-- scratch is ~200ms of Lua synthesis, and this is where it now happens.
|
||||
--
|
||||
-- Protocol -- main thread pushes command tables onto the "chipaudio_cmd"
|
||||
-- channel and drains produced buffers off "chipaudio_out":
|
||||
-- cmd = "play" { gen, header, allowLoops, audio } start a song
|
||||
-- cmd = "stop" halt production
|
||||
-- cmd = "invalidate" drop the bank cache
|
||||
-- cmd = "quit" end the thread
|
||||
-- out buffers are tagged with the play's `gen` so the main thread can
|
||||
-- discard anything left over from a superseded song:
|
||||
-- { gen, sd = SoundData } one rendered buffer
|
||||
-- { gen, done = true } the song ended (non-looping jingle finished)
|
||||
-- { gen, error = msg } build/synth failed; main logs and gives up
|
||||
|
||||
require("love.thread")
|
||||
require("love.timer")
|
||||
require("love.sound")
|
||||
require("love.filesystem")
|
||||
|
||||
-- Load the synth explicitly via love.filesystem (a fresh thread Lua state does
|
||||
-- not necessarily carry the package searcher that resolves "src.core..."):
|
||||
local ChipSynth = assert(love.filesystem.load("src/core/ChipSynth.lua"))()
|
||||
|
||||
local cmdCh = love.thread.getChannel("chipaudio_cmd")
|
||||
local outCh = love.thread.getChannel("chipaudio_out")
|
||||
|
||||
local BUF = ChipSynth.MUSIC_BUFFER_SAMPLES
|
||||
-- how many finished buffers may sit in the hand-off channel before the worker
|
||||
-- pauses. The deep (~6s) playback depth lives in the main-thread Source; this
|
||||
-- only bounds the worker's look-ahead (and its memory) between drains.
|
||||
local LOOKAHEAD = 8
|
||||
|
||||
local gen = nil -- active song generation, or nil when stopped
|
||||
local engine = nil -- the ChipSynth engine producing the current song
|
||||
local finished = false -- the current song ran out (non-looping)
|
||||
local data = nil -- { audio = <slim audio tables> } for ROM bank/wave reads
|
||||
|
||||
local function handle(cmd)
|
||||
if cmd.cmd == "play" then
|
||||
gen = cmd.gen
|
||||
finished = false
|
||||
engine = nil
|
||||
outCh:clear() -- drop any buffers left from the previous song
|
||||
data = { audio = cmd.audio }
|
||||
local ok, eng = pcall(ChipSynth.newEngine, data, cmd.header,
|
||||
{ allowLoops = cmd.allowLoops })
|
||||
if ok then
|
||||
engine = eng
|
||||
else
|
||||
outCh:push({ gen = gen, error = tostring(eng) })
|
||||
finished = true
|
||||
end
|
||||
elseif cmd.cmd == "stop" then
|
||||
gen = nil
|
||||
engine = nil
|
||||
finished = false
|
||||
outCh:clear()
|
||||
elseif cmd.cmd == "invalidate" then
|
||||
ChipSynth.invalidateBanks()
|
||||
elseif cmd.cmd == "quit" then
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
while true do
|
||||
-- drain every pending command first, so a stop/new-play is seen promptly
|
||||
local quit = false
|
||||
local cmd = cmdCh:pop()
|
||||
while cmd do
|
||||
if handle(cmd) then quit = true end
|
||||
cmd = cmdCh:pop()
|
||||
end
|
||||
if quit then break end
|
||||
|
||||
if engine and not finished and gen and outCh:getCount() < LOOKAHEAD then
|
||||
local activeGen = gen
|
||||
local ok, sd = pcall(ChipSynth.soundData, engine, BUF, 2)
|
||||
if not ok then
|
||||
outCh:push({ gen = activeGen, error = tostring(sd) })
|
||||
finished = true
|
||||
else
|
||||
outCh:push({ gen = activeGen, sd = sd })
|
||||
if engine:finished() then
|
||||
outCh:push({ gen = activeGen, done = true })
|
||||
finished = true
|
||||
end
|
||||
end
|
||||
else
|
||||
-- nothing to do (idle, or the look-ahead is full): yield the core
|
||||
love.timer.sleep(0.001)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,283 @@
|
||||
-- Routes ROM-derived cache I/O (data/generated, assets/generated and the
|
||||
-- rom-cache.complete marker) to the right place.
|
||||
--
|
||||
-- Normally the cache lives in LÖVE's per-user OS save directory and is
|
||||
-- written through love.filesystem. In portable mode it lives in the game
|
||||
-- folder next to the executable instead (the folder holding portable.txt --
|
||||
-- see SaveData), so nothing is left on the host machine. That folder is
|
||||
-- written with raw io.* (love.filesystem can only write to the save dir) and
|
||||
-- read back through love.filesystem, require and love.graphics.newImage --
|
||||
-- which works because the folder is on the physfs read path:
|
||||
--
|
||||
-- * Source runs (`love <gamedir>`, what the Play-* launchers use): the
|
||||
-- folder IS the physfs source, so it is already readable.
|
||||
-- * Fused builds (the packaged .app/.exe): the folder sits next to the
|
||||
-- executable and is NOT normally readable, so CacheFs mounts it onto the
|
||||
-- read path via PhysFS. love.filesystem.mount refuses external folders,
|
||||
-- but the underlying PHYSFS_mount (exported from love's framework) allows
|
||||
-- them; we call it through LuaJIT's FFI.
|
||||
--
|
||||
-- Directories in the portable folder are created with a plain mkdir syscall
|
||||
-- via FFI rather than os.execute, so importing never flashes a console window
|
||||
-- on Windows (issue #74 -- the old per-file `os.execute("mkdir")` froze the
|
||||
-- app behind a storm of one-frame cmd.exe windows).
|
||||
--
|
||||
-- Portable mode is desktop-only (Windows/Linux/macOS); on Android/iOS the
|
||||
-- source is a read-only package with no game folder to write into, so
|
||||
-- SaveData.isPortable() is false there and this module falls back to the
|
||||
-- ordinary love.filesystem/save-directory behaviour.
|
||||
|
||||
local CacheFs = {}
|
||||
|
||||
local SEP = package.config:sub(1, 1)
|
||||
|
||||
-- Cache-relative paths are prefixed with this before every read/write, so a
|
||||
-- Blue import lands in blue/ (see src.core.GameVersion) while a Red import
|
||||
-- keeps the historical root. The launcher sets it per import / per readiness
|
||||
-- check; it stays "" for Red. Runtime *reads* (require / newImage) do NOT go
|
||||
-- through here -- CacheFs.mountVersion overlays the active version's subtree
|
||||
-- onto the un-prefixed paths instead.
|
||||
CacheFs.prefix = ""
|
||||
|
||||
local function withPrefix(rel)
|
||||
local p = CacheFs.prefix
|
||||
if p == nil or p == "" then return rel end
|
||||
return p .. rel
|
||||
end
|
||||
|
||||
-- lazily-resolved windowless mkdir: function(absolutePath) or false when
|
||||
-- FFI is unavailable (the cache then stays on the save directory)
|
||||
local mkdirFn = nil
|
||||
|
||||
local function resolveMkdir()
|
||||
if mkdirFn ~= nil then return mkdirFn end
|
||||
mkdirFn = false
|
||||
local ok, ffi = pcall(require, "ffi")
|
||||
if not ok then return mkdirFn end
|
||||
if ffi.os == "Windows" then
|
||||
-- kernel32 is reliably resolvable through ffi.C on Windows (the engine
|
||||
-- already binds it in DiscordPresence); CreateDirectoryA returns
|
||||
-- nonzero on success and 0 when the directory already exists -- both
|
||||
-- fine, the result is ignored.
|
||||
pcall(ffi.cdef,
|
||||
"int CreateDirectoryA(const char *lpPathName, void *lpSecurityAttributes);")
|
||||
local resolved = pcall(function() return ffi.C.CreateDirectoryA end)
|
||||
if resolved then
|
||||
mkdirFn = function(path) pcall(ffi.C.CreateDirectoryA, path, nil) end
|
||||
end
|
||||
else
|
||||
pcall(ffi.cdef, "int mkdir(const char *pathname, unsigned int mode);")
|
||||
local resolved = pcall(function() return ffi.C.mkdir end)
|
||||
if resolved then
|
||||
mkdirFn = function(path) pcall(ffi.C.mkdir, path, 493) end -- 0755
|
||||
end
|
||||
end
|
||||
return mkdirFn
|
||||
end
|
||||
|
||||
-- Mount an external directory onto the physfs read path (appended, so the
|
||||
-- game's own source always wins a name clash). Returns true on success.
|
||||
--
|
||||
-- PHYSFS_mount is exported by love's own binary. How ffi finds it differs
|
||||
-- per platform: on macOS/Linux the symbol is in the default namespace, so
|
||||
-- ffi.C resolves it; on Windows it lives in love.dll, which ffi.C does NOT
|
||||
-- search, so love.dll is loaded explicitly with ffi.load("love"). Try the
|
||||
-- default first, then love.
|
||||
local physfsMountFn = nil
|
||||
local function resolveMount()
|
||||
if physfsMountFn ~= nil then return physfsMountFn end
|
||||
physfsMountFn = false
|
||||
local ok, ffi = pcall(require, "ffi")
|
||||
if not ok then return physfsMountFn end
|
||||
pcall(ffi.cdef,
|
||||
"int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath);")
|
||||
local libs = {
|
||||
function() return ffi.C end,
|
||||
function() return ffi.load("love") end,
|
||||
}
|
||||
for _, getlib in ipairs(libs) do
|
||||
local okl, lib = pcall(getlib)
|
||||
if okl and lib then
|
||||
local oks, fn = pcall(function() return lib.PHYSFS_mount end)
|
||||
if oks and fn then
|
||||
physfsMountFn = function(d, append)
|
||||
if append == nil then append = true end
|
||||
local okr, ret = pcall(fn, d, "", append and 1 or 0)
|
||||
return okr and ret ~= 0
|
||||
end
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
return physfsMountFn
|
||||
end
|
||||
|
||||
-- append (default true): the game's own source wins a name clash, matching
|
||||
-- how the portable cache root has always been mounted. Pass false to
|
||||
-- prepend, so the mounted tree wins -- used to overlay the active version's
|
||||
-- cache on top of the root (Red) copy and the source.
|
||||
local function mountReadable(dir, append)
|
||||
local fn = resolveMount()
|
||||
if not fn then return false end
|
||||
return fn(dir, append)
|
||||
end
|
||||
|
||||
-- The portable game folder when the cache should live there, else nil.
|
||||
-- Resolved (and, for a fused build, mounted) once and cached. Requires a
|
||||
-- desktop portable install (SaveData) and a working windowless mkdir.
|
||||
local portableRoot = nil
|
||||
local portableResolved = false
|
||||
local function resolvePortableRoot()
|
||||
if portableResolved then return portableRoot end
|
||||
portableResolved = true
|
||||
portableRoot = nil
|
||||
if not resolveMkdir() then return nil end
|
||||
local base = require("src.core.SaveData").portableBaseDir()
|
||||
if not base then return nil end
|
||||
if love.filesystem.getSource and base == love.filesystem.getSource() then
|
||||
-- source run: the folder is already the physfs source
|
||||
portableRoot = base
|
||||
elseif mountReadable(base) then
|
||||
-- fused build: base is next to the executable; mount it so io.* writes
|
||||
-- there are visible to love.filesystem/require/newImage
|
||||
portableRoot = base
|
||||
end
|
||||
return portableRoot
|
||||
end
|
||||
|
||||
function CacheFs.root()
|
||||
return resolvePortableRoot()
|
||||
end
|
||||
|
||||
local function realPath(root, rel)
|
||||
return root .. SEP .. rel:gsub("/", SEP)
|
||||
end
|
||||
|
||||
-- create every parent directory of `rel` under `root` (best effort; an
|
||||
-- already-existing directory is fine, a genuine failure surfaces when the
|
||||
-- subsequent io.open write fails)
|
||||
local function ensureParents(root, rel)
|
||||
local mkdir = resolveMkdir()
|
||||
if not mkdir then return end
|
||||
local parts = {}
|
||||
for part in rel:gmatch("[^/]+") do parts[#parts + 1] = part end
|
||||
local cur = root
|
||||
for i = 1, #parts - 1 do
|
||||
cur = cur .. SEP .. parts[i]
|
||||
mkdir(cur)
|
||||
end
|
||||
end
|
||||
|
||||
-- write cache-relative `rel` (forward-slash path) with the given bytes;
|
||||
-- returns ok, err like love.filesystem.write
|
||||
function CacheFs.write(rel, data)
|
||||
rel = withPrefix(rel)
|
||||
local root = CacheFs.root()
|
||||
if root then
|
||||
ensureParents(root, rel)
|
||||
local f, err = io.open(realPath(root, rel), "wb")
|
||||
if not f then return false, err end
|
||||
f:write(data)
|
||||
f:close()
|
||||
return true
|
||||
end
|
||||
local parent = rel:match("^(.*)/[^/]+$")
|
||||
if parent and not love.filesystem.createDirectory(parent) then
|
||||
local info = love.filesystem.getInfo(parent)
|
||||
local reason = info and ("a " .. info.type .. " already exists there")
|
||||
or "unknown reason"
|
||||
return false, "could not create " .. parent .. ": " .. reason
|
||||
end
|
||||
return love.filesystem.write(rel, data)
|
||||
end
|
||||
|
||||
-- read cache-relative `rel`; returns the bytes or nil
|
||||
function CacheFs.read(rel)
|
||||
rel = withPrefix(rel)
|
||||
local root = CacheFs.root()
|
||||
if root then
|
||||
local f = io.open(realPath(root, rel), "rb")
|
||||
if not f then return nil end
|
||||
local data = f:read("*a")
|
||||
f:close()
|
||||
return data
|
||||
end
|
||||
return love.filesystem.read(rel)
|
||||
end
|
||||
|
||||
-- does cache-relative `rel` exist as a file?
|
||||
function CacheFs.exists(rel)
|
||||
rel = withPrefix(rel)
|
||||
local root = CacheFs.root()
|
||||
if root then
|
||||
local f = io.open(realPath(root, rel), "rb")
|
||||
if not f then return false end
|
||||
f:close()
|
||||
return true
|
||||
end
|
||||
return love.filesystem.getInfo(rel, "file") ~= nil
|
||||
end
|
||||
|
||||
-- remove a single cache-relative file
|
||||
function CacheFs.remove(rel)
|
||||
rel = withPrefix(rel)
|
||||
local root = CacheFs.root()
|
||||
if root then
|
||||
os.remove(realPath(root, rel))
|
||||
return
|
||||
end
|
||||
love.filesystem.remove(rel)
|
||||
end
|
||||
|
||||
-- Remove the game-folder copy of a cache subtree before a fresh import, so a
|
||||
-- cache-format bump does not leave orphaned files behind. No-op when the
|
||||
-- portable cache is inactive (the save-directory copy is cleared by
|
||||
-- RomImporter's own removeTree). The tree is enumerated through
|
||||
-- love.filesystem (the game folder is mounted) and the real files deleted
|
||||
-- with os.remove; empty directories are harmless and left in place.
|
||||
function CacheFs.removeTree(rel)
|
||||
rel = withPrefix(rel)
|
||||
local root = CacheFs.root()
|
||||
if not root then return end
|
||||
local function walk(r)
|
||||
local info = love.filesystem.getInfo(r)
|
||||
if not info then return end
|
||||
if info.type == "directory" then
|
||||
for _, child in ipairs(love.filesystem.getDirectoryItems(r)) do
|
||||
walk(r .. "/" .. child)
|
||||
end
|
||||
else
|
||||
os.remove(realPath(root, r))
|
||||
end
|
||||
end
|
||||
walk(rel)
|
||||
end
|
||||
|
||||
-- Overlay the active version's extracted cache onto the un-prefixed read
|
||||
-- paths, so require("data.generated.*") and love.graphics.newImage(
|
||||
-- "assets/generated/*") resolve to that version's files. Red lives at the
|
||||
-- cache root and needs nothing; Blue lives under blue/ and is *prepended* so
|
||||
-- it wins over any Red copy at the root and over the game source. Called
|
||||
-- once at boot, before Game:load (main.lua). Returns true when nothing was
|
||||
-- needed or the mount succeeded.
|
||||
function CacheFs.mountVersion(version)
|
||||
local prefix = require("src.core.GameVersion").cachePrefix(version)
|
||||
if prefix == "" then return true end -- Red: already at the root
|
||||
local sub = prefix:gsub("/+$", "") -- "blue/" -> "blue"
|
||||
-- The cache root is the portable game folder when active, else LÖVE's OS
|
||||
-- save directory (where love.filesystem wrote blue/...).
|
||||
local base = CacheFs.root()
|
||||
if not base and love.filesystem.getSaveDirectory then
|
||||
base = love.filesystem.getSaveDirectory()
|
||||
end
|
||||
if not base then return false end
|
||||
if mountReadable(base .. SEP .. sub, false) then return true end
|
||||
-- Fallback when FFI/PHYSFS_mount is unavailable: LÖVE can mount a folder
|
||||
-- that lives in the save directory by name (prepended: appendToPath=false).
|
||||
if love.filesystem.mount then
|
||||
return love.filesystem.mount(sub, "", false)
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
return CacheFs
|
||||
@@ -126,14 +126,14 @@ function ImageWriter.columnsToRows(raw, tilesWide, tilesHigh, bytesPerTile)
|
||||
end
|
||||
|
||||
function ImageWriter.save(image, path)
|
||||
local parent = path:match("^(.*)/[^/]+$")
|
||||
if parent then
|
||||
local ok, err = love.filesystem.createDirectory(parent)
|
||||
if not ok then error("could not create " .. parent .. ": " .. tostring(err)) end
|
||||
end
|
||||
local ok, fileData = pcall(image.encode, image, "png")
|
||||
if not ok then error("could not encode " .. path .. ": " .. tostring(fileData)) end
|
||||
local written, writeError = love.filesystem.write(path, fileData)
|
||||
-- CacheFs routes this to the OS save directory (normal builds) or straight
|
||||
-- into the game folder (portable installs), creating parent directories as
|
||||
-- needed. io.* needs the bytes as a string; love.filesystem would also
|
||||
-- take the FileData, but getString() keeps one code path.
|
||||
local CacheFs = require("src.import.CacheFs")
|
||||
local written, writeError = CacheFs.write(path, fileData:getString())
|
||||
if not written then
|
||||
error("could not write " .. path .. ": " .. tostring(writeError))
|
||||
end
|
||||
|
||||
@@ -87,12 +87,11 @@ function LuaWriter.encode(value)
|
||||
end
|
||||
|
||||
function LuaWriter.write(path, value)
|
||||
local parent = path:match("^(.*)/[^/]+$")
|
||||
if parent then
|
||||
local ok, err = love.filesystem.createDirectory(parent)
|
||||
if not ok then error("could not create " .. parent .. ": " .. tostring(err)) end
|
||||
end
|
||||
local ok, err = love.filesystem.write(path, LuaWriter.encode(value))
|
||||
-- CacheFs routes this to the OS save directory (normal builds) or straight
|
||||
-- into the game folder (portable installs); it also creates the parent
|
||||
-- directories. See src/import/CacheFs.lua.
|
||||
local CacheFs = require("src.import.CacheFs")
|
||||
local ok, err = CacheFs.write(path, LuaWriter.encode(value))
|
||||
if not ok then error("could not write " .. path .. ": " .. tostring(err)) end
|
||||
end
|
||||
|
||||
|
||||
@@ -1253,14 +1253,24 @@ function RomExtractor:extractTrainers()
|
||||
"battle/trainers/" .. picture.imageBase .. ".png")
|
||||
written[picture.imageBase] = true
|
||||
end
|
||||
local parties = self:trainerParties(
|
||||
pointers.bank, partyStarts[index], partyEnds[index])
|
||||
-- ChiefData is empty in the ROM (the Celadon Chief battle is unused/
|
||||
-- cut content); tools/rom_manifest.json carries a hand-authored party
|
||||
-- for the trainers this project reimplements, since no ROM data exists
|
||||
-- to extract for them.
|
||||
if #parties == 0 then
|
||||
local override = self.manifest.trainerPartyOverrides
|
||||
and self.manifest.trainerPartyOverrides[trainerId]
|
||||
if override then parties = { copy(override) } end
|
||||
end
|
||||
out[trainerId] = {
|
||||
id = trainerId, index = index, name = decodedNames[index],
|
||||
source = "ROM:TrainerDataPointers",
|
||||
pic = picture and picture.path or nil,
|
||||
baseMoney = math.floor(Rom.bcd(rawMoney) / 100),
|
||||
aiMods = aiMods[index],
|
||||
parties = self:trainerParties(
|
||||
pointers.bank, partyStarts[index], partyEnds[index]),
|
||||
parties = parties,
|
||||
}
|
||||
self:tick("Trainers", index, #order)
|
||||
end
|
||||
@@ -1426,7 +1436,7 @@ end
|
||||
|
||||
function RomExtractor:extractField()
|
||||
self:beginStage("Interface artwork")
|
||||
local done, total = 0, 48
|
||||
local done, total = 0, 49
|
||||
local function tick()
|
||||
done = done + 1
|
||||
self:tick("Interface artwork", math.min(done, total), total)
|
||||
@@ -1576,6 +1586,34 @@ function RomExtractor:extractField()
|
||||
"fx/" .. spec[4], { transparent = true })
|
||||
tick()
|
||||
end
|
||||
|
||||
-- The cuttable tree's own sprite: InitCutAnimOAM (engine/overworld/cut.asm)
|
||||
-- copies Overworld_GFX tiles $2d-$2e (top half) and $3d-$3e (bottom half)
|
||||
-- into the OAM tiles the Cut animation slides apart, so this comes out of
|
||||
-- the OVERWORLD tileset's own graphics blob rather than a named symbol.
|
||||
do
|
||||
local overworldIndex
|
||||
for i, name in ipairs(self.manifest.constants.tilesetOrder) do
|
||||
if name == "OVERWORLD" then overworldIndex = i break end
|
||||
end
|
||||
assert(overworldIndex, "OVERWORLD tileset not found in tilesetOrder")
|
||||
local tilesetHeaders = self:symbol("Tilesets")
|
||||
local rowAddress = tilesetHeaders.address + (overworldIndex - 1) * 12
|
||||
local gfxBank = self.rom:byte(tilesetHeaders.bank, rowAddress)
|
||||
local gfxPointer = self.rom:word(tilesetHeaders.bank, rowAddress + 3)
|
||||
local cutTree = ImageWriter.blank(16, 16, 1, 1, 1, 0)
|
||||
for _, spec in ipairs({
|
||||
{ 0x2d, 0, 0 }, { 0x2e, 8, 0 }, { 0x3d, 0, 8 }, { 0x3e, 8, 8 },
|
||||
}) do
|
||||
local tileIndex, dx, dy = spec[1], spec[2], spec[3]
|
||||
local tile = ImageWriter.decode2bpp(
|
||||
self.rom:bytes(gfxBank, gfxPointer + tileIndex * 16, 16),
|
||||
8, 8, true)
|
||||
ImageWriter.blit(cutTree, tile, dx, dy)
|
||||
end
|
||||
self:save(cutTree, "fx/cut_tree.png"); tick()
|
||||
end
|
||||
|
||||
self:raw2bpp("BattleTransitionTile", 8, 8,
|
||||
"fx/battle_transition.png"); tick()
|
||||
self:raw2bpp("PokedexTileGraphics", 24, 48,
|
||||
@@ -1631,10 +1669,11 @@ function RomExtractor:extractAudio()
|
||||
chunks[index] = self.rom.data:sub(first, first + 0x3FFF)
|
||||
self:tick("Sound programs", index, #bankOrder + 2)
|
||||
end
|
||||
local ok, writeError = love.filesystem.createDirectory(
|
||||
"assets/generated/audio")
|
||||
if ok == false then error("could not create audio cache: " .. tostring(writeError)) end
|
||||
ok, writeError = love.filesystem.write(
|
||||
-- CacheFs (not love.filesystem directly) so a portable install lands this
|
||||
-- in the game folder with the rest of the cache; it creates the parent
|
||||
-- directory too.
|
||||
local CacheFs = require("src.import.CacheFs")
|
||||
local ok, writeError = CacheFs.write(
|
||||
"assets/generated/audio/programs.bin", table.concat(chunks))
|
||||
if not ok then error("could not write audio programs: " .. tostring(writeError)) end
|
||||
|
||||
|
||||
+845
-162
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,10 @@ local function isBadge(id)
|
||||
return id:find("BADGE", 1, true) ~= nil
|
||||
end
|
||||
|
||||
-- exported so item lists that share save.inventory (e.g. the PC deposit
|
||||
-- menu) can exclude badges the same way the bag does
|
||||
Bag.isBadge = isBadge
|
||||
|
||||
function Bag.slots(save)
|
||||
local n = 0
|
||||
for id in pairs(save.inventory) do
|
||||
|
||||
+3
-1
@@ -129,7 +129,9 @@ end
|
||||
-- tripwire on for tests that cannot set the environment.
|
||||
function Loader.new(opts)
|
||||
local dev = opts and opts.dev
|
||||
if dev == nil then dev = os.getenv("POKEPORT_DEV") == "1" end
|
||||
if dev == nil then
|
||||
dev = os.getenv("POKEPORT_DEV") == "1" or _G.POKEPORT_DEV_MODE == true
|
||||
end
|
||||
local self = setmetatable({
|
||||
mods = {}, loaded = {}, errors = {}, initialized = false,
|
||||
events = Events.new(), hooks = Hooks.new(), content = {}, assets = {},
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
-- "trade" | "manual" | <mod>, item = id?, ... }), wrapped by the
|
||||
-- evolution.check hook so a mod can cancel or force any evolution.
|
||||
|
||||
local Music = require("src.core.Music")
|
||||
local Runtime = require("src.mods.Runtime")
|
||||
local Screens = require("src.ui.Screens")
|
||||
local Stats = require("src.pokemon.Stats")
|
||||
@@ -112,11 +113,15 @@ function Evolution.evolve(game, mon, newSpecies, onDone, via)
|
||||
Screens.push(game, "EvolutionState", mon, newSpecies, onDone)
|
||||
return
|
||||
end
|
||||
Music.play(game.data, Music.special(game.data, "evolution"))
|
||||
local oldName = mon.nickname or game.data.pokemon[mon.species].name
|
||||
Evolution.apply(game, mon, newSpecies, via)
|
||||
local msg = ("What?\n%s is\nevolving!\fCongratulations!\nYour %s\nevolved into\n%s!")
|
||||
:format(oldName, oldName, game.data.pokemon[newSpecies].name)
|
||||
game.stack:push(TextBox.new(game, msg, onDone))
|
||||
game.stack:push(TextBox.new(game, msg, function()
|
||||
Music.restoreMap(game.data)
|
||||
if onDone then onDone() end
|
||||
end))
|
||||
end
|
||||
|
||||
-- Entry point for mods whose methods fire outside the vanilla moments
|
||||
|
||||
@@ -9,12 +9,18 @@ local Pokemon = {}
|
||||
-- keeping the most recent four (engine/pokemon/learn_move.asm behavior).
|
||||
function Pokemon.movesAtLevel(speciesDef, level)
|
||||
local moves = {}
|
||||
local function add(id)
|
||||
for _, existing in ipairs(moves) do
|
||||
if existing == id then return end
|
||||
end
|
||||
table.insert(moves, id)
|
||||
end
|
||||
for _, m in ipairs(speciesDef.level1Moves) do
|
||||
table.insert(moves, m)
|
||||
add(m)
|
||||
end
|
||||
for _, entry in ipairs(speciesDef.learnset) do
|
||||
if entry.level <= level then
|
||||
table.insert(moves, entry.move)
|
||||
add(entry.move)
|
||||
end
|
||||
end
|
||||
while #moves > 4 do
|
||||
|
||||
+140
-5
@@ -10,16 +10,23 @@
|
||||
-- RED++ swaps the named-palette pack for pokered-gbc SuperPalettes
|
||||
-- (data/palettes_gbc.lua), including per-species mon colors.
|
||||
|
||||
local GameVersion = require("src.core.GameVersion")
|
||||
|
||||
local PaletteFX = {}
|
||||
|
||||
local shader -- false = unavailable (headless / no shader support)
|
||||
local gbcPack -- false = missing; nil = not loaded yet
|
||||
|
||||
-- Cycle order matches OptionsMenu / hotkey 2
|
||||
PaletteFX.MODES = { "gbc", "redpp", "og", "og_inv", "gbc_inv", "classic" }
|
||||
-- Cycle order matches OptionsMenu / hotkey 2. The three real colorizations
|
||||
-- come first (OG RED = GBC hardware, SGB = per-map Super Game Boy, RED++ =
|
||||
-- pokered-gbc per-tile), then the DMG-shade novelty modes.
|
||||
PaletteFX.MODES = { "ogred", "gbc", "redpp", "og", "og_inv", "gbc_inv", "classic" }
|
||||
-- `gbc`/`gbc_inv` keep their save-value ids for back-compat; their LABELS are
|
||||
-- "SGB"/"SGB INV" because that is what the mode actually is (the old "GBC"
|
||||
-- label was a misnomer -- it never was the real Game Boy Color palette).
|
||||
PaletteFX.MODE_LABELS = {
|
||||
gbc = "GBC", redpp = "RED++", og = "OG", og_inv = "OG INV",
|
||||
gbc_inv = "GBC INV", classic = "CLASSIC",
|
||||
ogred = "OG RED", gbc = "SGB", redpp = "RED++", og = "OG",
|
||||
og_inv = "OG INV", gbc_inv = "SGB INV", classic = "CLASSIC",
|
||||
}
|
||||
PaletteFX.mode = "gbc"
|
||||
|
||||
@@ -28,6 +35,40 @@ PaletteFX.CLASSIC = {
|
||||
{ 155, 188, 15 }, { 139, 172, 15 }, { 48, 98, 48 }, { 15, 56, 15 },
|
||||
}
|
||||
|
||||
-- OG RED: the Game Boy Color boot-ROM auto-palette for Pokemon Red. Pokemon
|
||||
-- Red ships no CGB code (pokered's wOnCGB is hardwired 0), so on a Game Boy
|
||||
-- Color the boot ROM colorizes it with ONE global palette pair -- a red
|
||||
-- background and green objects -- applied to the whole game with no per-map
|
||||
-- variation (that variety was the Super Game Boy's doing, i.e. SGB mode).
|
||||
-- Lightest shade first, matching the SGB palette tables. Values verified
|
||||
-- against hardware captures of Pallet Town and Oak's Lab.
|
||||
PaletteFX.GBC_BG = {
|
||||
{ 255, 255, 255 }, { 255, 132, 132 }, { 148, 58, 58 }, { 0, 0, 0 },
|
||||
}
|
||||
PaletteFX.GBC_OBJ = {
|
||||
{ 255, 255, 255 }, { 123, 255, 49 }, { 0, 132, 0 }, { 0, 0, 0 },
|
||||
}
|
||||
|
||||
-- OG BLUE: Pokemon Blue's Game Boy Color boot-ROM auto-palette. Same
|
||||
-- one-global-pair scheme as OG RED (Blue also ships no CGB code), but the
|
||||
-- boot ROM colorizes the background blue instead of red -- so "OG RED" for a
|
||||
-- Blue playthrough is white -> light blue -> dark blue -> black, mirroring
|
||||
-- GBC_BG channel-for-channel so the blue reads at the same brightness. The
|
||||
-- OBJ (sprite) palette stays the same green, matching how Red and Blue share
|
||||
-- the green-character look on a Game Boy Color.
|
||||
PaletteFX.GBC_BG_BLUE = {
|
||||
{ 255, 255, 255 }, { 132, 132, 255 }, { 58, 58, 148 }, { 0, 0, 0 },
|
||||
}
|
||||
|
||||
-- The active game's OG boot-ROM background palette: blue for a Blue
|
||||
-- playthrough, red otherwise. White (index 1) and black (index 4) are
|
||||
-- identical across versions, so callers that only touch the endpoints
|
||||
-- (e.g. BattleState's zone white/black snap) need no version branch.
|
||||
function PaletteFX.ogBg()
|
||||
if GameVersion.isBlue() then return PaletteFX.GBC_BG_BLUE end
|
||||
return PaletteFX.GBC_BG
|
||||
end
|
||||
|
||||
local INV_MAP = { [0] = 3, [1] = 2, [2] = 1, [3] = 0 }
|
||||
|
||||
function PaletteFX.shader()
|
||||
@@ -141,6 +182,56 @@ function PaletteFX.usesGbcPack(mode)
|
||||
return mode == "redpp"
|
||||
end
|
||||
|
||||
-- Whether the active mode bakes a per-OBJ palette onto overworld sprites
|
||||
-- (the OBP bake + post-zone redraw path). ONLY OG RED does: it wears the
|
||||
-- GBC boot-ROM green object palette (PaletteFX.GBC_OBJ) so the player and
|
||||
-- NPCs stay green over the red background, exactly like Pokemon Red on a
|
||||
-- Game Boy Color. SGB mode deliberately does NOT: an SGB OBJ carries no
|
||||
-- palette of its own, so the characters tint with the whole-map region
|
||||
-- palette along with the terrain (the Super Game Boy never colored Pokemon
|
||||
-- Red's sprites separately -- baking a per-sprite palette there was the
|
||||
-- "reds coloring on the player/NPCs" bug). RED++ colors sprites through
|
||||
-- the usesGbcPack() path in SpriteRenderer instead.
|
||||
function PaletteFX.usesSpriteObp(mode)
|
||||
return (mode or PaletteFX.mode) == "ogred"
|
||||
end
|
||||
|
||||
-- ------- post-zone sprite redraw (GBC mode)
|
||||
--
|
||||
-- In GBC mode the world canvas still runs through the per-map zone
|
||||
-- shade-remap shader, which would corrupt an OBP-baked sprite's true-color
|
||||
-- pixels. So SpriteRenderer draws the baked sprite into the canvas (its
|
||||
-- pixels come out zone-tinted there) AND records the draw here;
|
||||
-- Renderer:endFrame replays the list on top of the finished zone pass,
|
||||
-- scaled into screen space -- the GBC's OBJ-over-BG compositing, one draw
|
||||
-- late. Entries carrying `colors` are re-colorized draws (the tall-grass
|
||||
-- feet overdraw, which must keep hiding sprite feet) issued through the
|
||||
-- color-0-keyed shade-remap shader. World pass only; cleared per frame.
|
||||
local spriteRedraws = {}
|
||||
|
||||
function PaletteFX.clearSpriteRedraws()
|
||||
for i = #spriteRedraws, 1, -1 do spriteRedraws[i] = nil end
|
||||
end
|
||||
|
||||
function PaletteFX.markSpriteRedraw(image, quad, x, y, sx, colors, keyed)
|
||||
if currentPass ~= "world" then return end
|
||||
spriteRedraws[#spriteRedraws + 1] =
|
||||
{ image = image, quad = quad, x = x, y = y, sx = sx or 1,
|
||||
colors = colors, keyed = keyed }
|
||||
end
|
||||
|
||||
-- whether a draw issued right now would land in the redraw list -- the
|
||||
-- OBP bake is only correct when the replay can restore it after the zone
|
||||
-- pass (tilt's upright pass colorizes per-billboard instead, so sprites
|
||||
-- there keep the raw sheet)
|
||||
function PaletteFX.spriteRedrawPassActive()
|
||||
return currentPass == "world"
|
||||
end
|
||||
|
||||
function PaletteFX.spriteRedraws()
|
||||
return spriteRedraws
|
||||
end
|
||||
|
||||
-- Active named-palette table for COLORS: RED++ uses data/palettes_gbc.lua,
|
||||
-- everything else uses the ROM-imported data.palettes.
|
||||
function PaletteFX.pack(data)
|
||||
@@ -153,7 +244,13 @@ end
|
||||
|
||||
-- named palette from the active pack (nil on stale builds / missing name).
|
||||
-- RED++ falls back to the ROM pack for names the gbc table omits (rare).
|
||||
-- OG RED short-circuits EVERY name to the one global GBC boot-ROM BG palette
|
||||
-- (the hardware had a single BGP for the whole game), so terrain zones,
|
||||
-- battle HP bars / text, and menu boxes all come out red -- everything a
|
||||
-- background tile drew. Objects do not come through here (they bake
|
||||
-- GBC_OBJ green), so this stays a BG-only hook.
|
||||
function PaletteFX.pal(data, name)
|
||||
if PaletteFX.mode == "ogred" then return PaletteFX.ogBg() end
|
||||
local p = PaletteFX.pack(data)
|
||||
local c = p and p.palettes[name]
|
||||
if c then return c end
|
||||
@@ -169,6 +266,11 @@ end
|
||||
-- Transformed mon's pic is tinted gray, not the copied species' own
|
||||
-- SGB color). RED++ uses per-species pals from mon_palettes.asm.
|
||||
function PaletteFX.monPal(data, species, transformed)
|
||||
-- OG RED: a battle mon pic is a BG tile on the Game Boy Color (drawn into
|
||||
-- the tilemap, colored by BGP), so it wears the global red BG palette, not
|
||||
-- a per-species one -- matching the hardware capture where both mons are
|
||||
-- red/pink on the white field.
|
||||
if PaletteFX.mode == "ogred" then return PaletteFX.ogBg() end
|
||||
local p = PaletteFX.pack(data)
|
||||
if not p then return nil end
|
||||
if transformed then
|
||||
@@ -223,6 +325,29 @@ local TILE_GROUP_EXCEPTIONS = {
|
||||
CELADON_MART_1F = { tiles = { [0x07] = true, [0x08] = true,
|
||||
[0x17] = true, [0x18] = true }, group = 4 },
|
||||
}
|
||||
|
||||
-- keyed by tileset id (applies on every map that uses it), consulted after
|
||||
-- the per-map table above
|
||||
local TILESET_GROUP_EXCEPTIONS = {
|
||||
-- tile $22 (the hollow-square grave marker) -> GRAY: the extracted pack
|
||||
-- files it under the bright blue family, which makes a purely
|
||||
-- decorative floor marker read as an interactive pad
|
||||
CEMETERY = { tiles = { [0x22] = true }, group = 0 },
|
||||
}
|
||||
|
||||
-- pokered-gbc's lobby.bst repoints the Celadon roof table's flat top
|
||||
-- (block 29, cells 5/6/9/10) at a duplicate tile ($5a, BROWN) so the
|
||||
-- tabletop and the checkerboard floor -- both raw tile $37 -- can take
|
||||
-- different palettes; the vanilla-derived blockset shares the one tile
|
||||
-- id, so the RED++ atlas path re-creates the duplicate: the alias slot
|
||||
-- is baked as a copy of `tile` in `group`'s colors, and the listed
|
||||
-- 0-based block cells draw the alias instead of the shared tile.
|
||||
PaletteFX.TILE_ALIASES = {
|
||||
CELADON_MART_ROOF = {
|
||||
{ block = 29, cells = { [5] = true, [6] = true, [9] = true, [10] = true },
|
||||
tile = 0x37, alias = 0x5a, group = 5 },
|
||||
},
|
||||
}
|
||||
local ROOF_GROUP = 6
|
||||
local ROUTE_6_SAFFRON = { mapId = "ROUTE_6", useMapId = "SAFFRON_CITY", cellYBelow = 2 }
|
||||
|
||||
@@ -244,6 +369,8 @@ function PaletteFX.worldGroupAt(tileset, mapId, tileId)
|
||||
if not groups then return nil end
|
||||
local exc = TILE_GROUP_EXCEPTIONS[mapId]
|
||||
if exc and exc.tiles[tileId] then return exc.group end
|
||||
exc = TILESET_GROUP_EXCEPTIONS[tileset]
|
||||
if exc and exc.tiles[tileId] then return exc.group end
|
||||
return groups[tileId] or 7 -- TEXT: tile ids past the tileset's 96 (menus)
|
||||
end
|
||||
|
||||
@@ -293,6 +420,10 @@ function PaletteFX.spriteObp(spriteDef, seed)
|
||||
local src = spriteDef and spriteDef.source
|
||||
if not (w and src) then return nil end
|
||||
local idx = tonumber(src:match("%[(%d+)%]"))
|
||||
-- RedBikeSprite loads outside SpriteSheetPointerTable
|
||||
-- (LoadBikePlayerSpriteGraphics), so its source carries no bracketed
|
||||
-- index; it wears the player's own palette, same as SPRITE_RED
|
||||
if not idx and src:find("RedBikeSprite", 1, true) then idx = 0 end
|
||||
local group = idx and w.spriteAssignment[idx]
|
||||
if group == nil then return nil end
|
||||
if group == "random" then
|
||||
@@ -381,7 +512,11 @@ function PaletteFX.applyOptions(opts)
|
||||
end
|
||||
|
||||
function PaletteFX.modeLabel(mode)
|
||||
return PaletteFX.MODE_LABELS[mode or PaletteFX.mode] or "GBC"
|
||||
mode = mode or PaletteFX.mode
|
||||
-- The GBC boot-ROM mode wears the running game's name: it is red for Red and
|
||||
-- blue for Blue (see ogBg), so a Blue playthrough shows "OG BLUE".
|
||||
if mode == "ogred" and GameVersion.isBlue() then return "OG BLUE" end
|
||||
return PaletteFX.MODE_LABELS[mode] or "GBC"
|
||||
end
|
||||
|
||||
-- When a state exposes no SGB zones but COLORS needs a forced palette
|
||||
|
||||
+38
-1
@@ -62,8 +62,10 @@ end
|
||||
function Renderer:beginFrame(transparent)
|
||||
self.worldActive = false
|
||||
self.uprightActive = false
|
||||
-- last frame's trueColor rects go before anything draws this one
|
||||
-- last frame's trueColor rects and sprite redraws go before anything
|
||||
-- draws this one
|
||||
PaletteFX.clearTrueColor()
|
||||
PaletteFX.clearSpriteRedraws()
|
||||
PaletteFX.setPass("ui")
|
||||
love.graphics.setCanvas(self.canvas)
|
||||
if transparent then
|
||||
@@ -77,6 +79,10 @@ function Renderer:beginWorldPass()
|
||||
local vw, vh = self:worldViewSize()
|
||||
if not self.worldCanvas or self.worldCanvas:getWidth() ~= vw
|
||||
or self.worldCanvas:getHeight() ~= vh then
|
||||
-- free the old canvas before replacing it: a zoom/tilt tween changes
|
||||
-- the view size every frame, so without this the superseded canvases
|
||||
-- pile up in VRAM until a GC finalizer happens to run
|
||||
if self.worldCanvas and self.worldCanvas.release then self.worldCanvas:release() end
|
||||
self.worldCanvas = love.graphics.newCanvas(vw, vh)
|
||||
self.worldCanvas:setFilter("nearest", "nearest")
|
||||
end
|
||||
@@ -105,6 +111,7 @@ function Renderer:beginUprightPass()
|
||||
local cw, ch = vw + 2 * M, vh + 2 * M
|
||||
if not self.uprightCanvas or self.uprightCanvas:getWidth() ~= cw
|
||||
or self.uprightCanvas:getHeight() ~= ch then
|
||||
if self.uprightCanvas and self.uprightCanvas.release then self.uprightCanvas:release() end
|
||||
self.uprightCanvas = love.graphics.newCanvas(cw, ch)
|
||||
self.uprightCanvas:setFilter("nearest", "nearest")
|
||||
end
|
||||
@@ -198,6 +205,7 @@ function Renderer:drawTiltedWorld(zoneList, s, wox, woy, target)
|
||||
-- 2x for extra crispness.
|
||||
if not self.tiltCanvas or self.tiltCanvas:getWidth() ~= wvw
|
||||
or self.tiltCanvas:getHeight() ~= wvh then
|
||||
if self.tiltCanvas and self.tiltCanvas.release then self.tiltCanvas:release() end
|
||||
self.tiltCanvas = love.graphics.newCanvas(wvw, wvh)
|
||||
self.tiltCanvas:setFilter("linear", "linear")
|
||||
end
|
||||
@@ -363,6 +371,35 @@ function Renderer:endFrame(zones, worldZones)
|
||||
else
|
||||
blit(self.worldCanvas, s, zones, S, wox, woy, 0, 0, ww, wh)
|
||||
end
|
||||
-- OBP-baked overworld sprites replay on top of the zone pass (GBC
|
||||
-- mode per-object coloring; see PaletteFX.markSpriteRedraw). Grass
|
||||
-- feet-overdraw entries carry `colors` and re-colorize through the
|
||||
-- color-0-keyed shade-remap shader so they keep hiding sprite feet.
|
||||
local redraws = PaletteFX.spriteRedraws()
|
||||
if redraws[1] then
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
love.graphics.setScissor(0, 0, ww, wh)
|
||||
local activeShader = nil
|
||||
for _, r in ipairs(redraws) do
|
||||
local wanted = r.colors
|
||||
and (r.keyed and PaletteFX.keyedShader() or PaletteFX.shader())
|
||||
or nil
|
||||
if wanted ~= activeShader then
|
||||
activeShader = wanted
|
||||
love.graphics.setShader(wanted)
|
||||
end
|
||||
if wanted then PaletteFX.sendColors(wanted, r.colors) end
|
||||
if r.quad then
|
||||
love.graphics.draw(r.image, r.quad, wox + r.x * s, woy + r.y * s,
|
||||
0, s * r.sx, s)
|
||||
else
|
||||
love.graphics.draw(r.image, wox + r.x * s, woy + r.y * s,
|
||||
0, s * r.sx, s)
|
||||
end
|
||||
end
|
||||
if activeShader then love.graphics.setShader() end
|
||||
love.graphics.setScissor()
|
||||
end
|
||||
end
|
||||
-- Composite the tilt upright pass over the ground (projected or, in the
|
||||
-- rare no-shader fallback, flat). It already carries its billboards'
|
||||
|
||||
@@ -85,10 +85,21 @@ end
|
||||
|
||||
-- facing: down/up/left/right; walkPhase: 0 stand, 1 walk; flip: alternate
|
||||
-- steps mirror the walk frame for up/down (GB uses OAM flip for this).
|
||||
local function blitFrame(image, quad, x, y, flip, redraw)
|
||||
if flip then
|
||||
love.graphics.draw(image, quad, x + 16, y, 0, -1, 1)
|
||||
if redraw then PaletteFX.markSpriteRedraw(image, quad, x + 16, y, -1) end
|
||||
else
|
||||
love.graphics.draw(image, quad, x, y)
|
||||
if redraw then PaletteFX.markSpriteRedraw(image, quad, x, y, 1) end
|
||||
end
|
||||
end
|
||||
|
||||
function SpriteRenderer:draw(px, py, camX, camY, facing, walkPhase, stepFlip)
|
||||
local x = math.floor(px - camX)
|
||||
local y = math.floor(py - camY) - 4
|
||||
local image = self.image
|
||||
local redraw = false
|
||||
-- full-color art claims its 16x16 cell out of the shade-remap pass
|
||||
if self.def.trueColor then
|
||||
PaletteFX.markTrueColor(x, y, 16, 16)
|
||||
@@ -102,12 +113,19 @@ function SpriteRenderer:draw(px, py, camX, camY, facing, walkPhase, stepFlip)
|
||||
if colors then
|
||||
image = getObpImage(self.def.image, colors, group)
|
||||
end
|
||||
elseif PaletteFX.usesSpriteObp() and PaletteFX.spriteRedrawPassActive() then
|
||||
-- OG RED (GBC boot-ROM look): every OBJ wears the one global green
|
||||
-- object palette. The red BG zone shader still runs over the world
|
||||
-- canvas, so the baked sprite is queued for a post-zone redraw
|
||||
-- (PaletteFX.markSpriteRedraw) that restores its green pixels on top.
|
||||
image = getObpImage(self.def.image, PaletteFX.GBC_OBJ, "gbcobj")
|
||||
redraw = true
|
||||
end
|
||||
-- single-frame sprites (item balls, fossils...) have one fixed pose;
|
||||
-- still 3-frame sprites turn to face (the nurse at her machine,
|
||||
-- facePlayer on STAY NPCs) but never show walk frames
|
||||
if self.def.frames <= 1 then
|
||||
love.graphics.draw(image, self.frames[0], x, y)
|
||||
blitFrame(image, self.frames[0], x, y, false, redraw)
|
||||
return
|
||||
end
|
||||
local frame = (self.def.walker and walkPhase == 1)
|
||||
@@ -119,11 +137,7 @@ function SpriteRenderer:draw(px, py, camX, camY, facing, walkPhase, stepFlip)
|
||||
flip = true
|
||||
end
|
||||
local quad = self.frames[frame] or self.frames[0]
|
||||
if flip then
|
||||
love.graphics.draw(image, quad, x + 16, y, 0, -1, 1)
|
||||
else
|
||||
love.graphics.draw(image, quad, x, y)
|
||||
end
|
||||
blitFrame(image, quad, x, y, flip, redraw)
|
||||
end
|
||||
|
||||
return SpriteRenderer
|
||||
|
||||
+211
-81
@@ -90,8 +90,8 @@ function TileRenderer.setSpinning(active)
|
||||
end
|
||||
|
||||
-- true while the spinner arrow tiles should show the 'blur' graphic; false
|
||||
-- means draw nothing extra (the static mapBatch/ringBatch tile shows
|
||||
-- through, matching the asm's restore-to-original behavior). The 8-tick
|
||||
-- means draw nothing extra (the static window tile shows through,
|
||||
-- matching the asm's restore-to-original behavior). The 8-tick
|
||||
-- half-period approximates one GB movement step (2px/frame); this is a
|
||||
-- deliberate approximation of wSimulatedJoypadStatesIndex bit-0 parity, not
|
||||
-- a cycle-accurate replication -- the port's tweened scriptMove has no
|
||||
@@ -347,9 +347,10 @@ local function getGbcAtlas(imagePath, tilesetId, mapId, perRow, data)
|
||||
if groupColors then
|
||||
local src = Assets.imageData(imagePath)
|
||||
local iw, ih = src:getDimensions()
|
||||
local total = (iw / 8) * (ih / 8)
|
||||
local out = love.image.newImageData(iw, ih)
|
||||
local tileColors = {}
|
||||
for t = 0, (iw / 8) * (ih / 8) - 1 do
|
||||
for t = 0, total - 1 do
|
||||
local colors = tileColors[t]
|
||||
if colors == nil then
|
||||
local group = PaletteFX.worldGroupAt(tilesetId, mapId, t)
|
||||
@@ -366,6 +367,25 @@ local function getGbcAtlas(imagePath, tilesetId, mapId, perRow, data)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- duplicate-tile aliases: bake a copy of a shared tile graphic into
|
||||
-- a spare slot under a different palette group, so block cells that
|
||||
-- draw the alias can color apart from cells sharing the raw tile
|
||||
for _, al in ipairs(PaletteFX.TILE_ALIASES and PaletteFX.TILE_ALIASES[mapId] or {}) do
|
||||
if al.alias < total then
|
||||
local colors = groupColors[al.group + 1]
|
||||
local sxo = (al.tile % perRow) * 8
|
||||
local syo = math.floor(al.tile / perRow) * 8
|
||||
local dxo = (al.alias % perRow) * 8
|
||||
local dyo = math.floor(al.alias / perRow) * 8
|
||||
for py = 0, 7 do
|
||||
for px = 0, 7 do
|
||||
local r, g, b, a = src:getPixel(sxo + px, syo + py)
|
||||
r, g, b, a = recolorSample(r, g, b, a, colors)
|
||||
out:setPixel(dxo + px, dyo + py, r, g, b, a)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
img = love.graphics.newImage(out)
|
||||
end
|
||||
end
|
||||
@@ -406,22 +426,24 @@ function TileRenderer.new(map, data)
|
||||
end
|
||||
|
||||
local def = map.def
|
||||
local wB, hB = def.width, def.height
|
||||
-- two batches: the border-block ring around the map, and the map body.
|
||||
-- Connected-map strips draw body-only on top of this map's ring.
|
||||
local total = (wB + 2 * BORDER_BLOCKS) * (hB + 2 * BORDER_BLOCKS) * 16
|
||||
self.ringBatch = love.graphics.newSpriteBatch(self.image, total, "static")
|
||||
self.mapBatch = love.graphics.newSpriteBatch(self.image, wB * hB * 16, "static")
|
||||
-- animated tiles overdraw the static batches each frame. Entry order
|
||||
-- decides which one claims a tile listed twice, so the vanilla defaults
|
||||
-- keep the old water-then-flower-then-spinner precedence.
|
||||
-- The map body measured in 8px tiles (each block is 4x4 tiles). The tile
|
||||
-- layer is drawn windowed to the camera (see :ensureWindow) instead of
|
||||
-- baked into a whole-map SpriteBatch, so a map becoming visible -- a warp,
|
||||
-- a connection seam -- costs nothing to "build": there is no per-map batch
|
||||
-- construction that scales with map size, which is what stuttered.
|
||||
self.bodyTilesW = def.width * 4
|
||||
self.bodyTilesH = def.height * 4
|
||||
-- Animated tiles overdraw the static window each frame. Only the per-entry
|
||||
-- render spec (textures/sequence/gate) is kept here; the animated cells are
|
||||
-- gathered per camera window in :ensureWindow, so nothing here scales with
|
||||
-- map size either. Entry order decides which entry claims a tile listed
|
||||
-- twice (the vanilla water-then-flower-then-spinner precedence).
|
||||
local anims, claimedBy = {}, {}
|
||||
local declared = map.tileset.animatedTiles
|
||||
or TileRenderer.defaultAnimatedTiles(map.tileset)
|
||||
for _, spec in ipairs(declared) do
|
||||
local anim = buildAnim(spec, map.tileset.image, perRow, self.quads, gbcCtx)
|
||||
if anim then
|
||||
anim.cells = {}
|
||||
anims[#anims + 1] = anim
|
||||
for _, tile in ipairs(anim.tiles) do
|
||||
if claimedBy[tile] == nil then claimedBy[tile] = anim end
|
||||
@@ -429,53 +451,20 @@ function TileRenderer.new(map, data)
|
||||
end
|
||||
end
|
||||
|
||||
for by = -BORDER_BLOCKS, hB + BORDER_BLOCKS - 1 do
|
||||
for bx = -BORDER_BLOCKS, wB + BORDER_BLOCKS - 1 do
|
||||
local inside = bx >= 0 and by >= 0 and bx < wB and by < hB
|
||||
local batch = inside and self.mapBatch or self.ringBatch
|
||||
local block = map.tileset.blocks[map:blockAt(bx, by) + 1]
|
||||
for ty = 0, 3 do
|
||||
for tx = 0, 3 do
|
||||
local tile = block[ty * 4 + tx + 1]
|
||||
local quad = self.quads[tile]
|
||||
if quad then
|
||||
batch:add(quad, bx * 32 + tx * 8, by * 32 + ty * 8)
|
||||
end
|
||||
local anim = claimedBy[tile]
|
||||
if anim then
|
||||
local cells = anim.cells
|
||||
cells[#cells + 1] = { bx * 32 + tx * 8, by * 32 + ty * 8, inside, tile }
|
||||
end
|
||||
end
|
||||
end
|
||||
-- duplicate-tile alias remap (RED++ atlas only): [blockId][0-based cell]
|
||||
-- -> alias tile id (see PaletteFX.TILE_ALIASES / getGbcAtlas's bake)
|
||||
local aliasMap
|
||||
if gbcCtx then
|
||||
for _, al in ipairs(PaletteFX.TILE_ALIASES and PaletteFX.TILE_ALIASES[map.id] or {}) do
|
||||
aliasMap = aliasMap or {}
|
||||
local cells = aliasMap[al.block] or {}
|
||||
for ci in pairs(al.cells) do cells[ci] = al.alias end
|
||||
aliasMap[al.block] = cells
|
||||
end
|
||||
end
|
||||
|
||||
-- animated overdraw batches: the full set (ring + body) for the
|
||||
-- current map, and a body-only set for connected-map drawing --
|
||||
-- a neighbor's water ring must never overdraw this map's tiles.
|
||||
-- `quadFor`, when given, looks up a per-entry quad (used by toggle
|
||||
-- entries, whose texture is a full tileset-atlas clone rather than a
|
||||
-- single-tile image like the hshift/frames variants).
|
||||
local function animBatches(entries, image, quadFor)
|
||||
if #entries == 0 then return nil, nil end
|
||||
local all = love.graphics.newSpriteBatch(image, #entries, "static")
|
||||
local body
|
||||
for _, c in ipairs(entries) do
|
||||
if quadFor then all:add(quadFor(c[4]), c[1], c[2]) else all:add(c[1], c[2]) end
|
||||
if c[3] then
|
||||
body = body or love.graphics.newSpriteBatch(image, #entries, "static")
|
||||
if quadFor then body:add(quadFor(c[4]), c[1], c[2]) else body:add(c[1], c[2]) end
|
||||
end
|
||||
end
|
||||
return all, body
|
||||
end
|
||||
for _, anim in ipairs(anims) do
|
||||
anim.batch, anim.bodyBatch =
|
||||
animBatches(anim.cells, anim.textures[1], anim.quadFor)
|
||||
anim.cells = nil
|
||||
end
|
||||
self.aliasMap = aliasMap
|
||||
self.anims = anims
|
||||
self.claimedBy = claimedBy
|
||||
|
||||
-- a repeating 32x32 image of the border block, tiled behind
|
||||
-- everything the 3-block ring doesn't cover (the survey zoom sees
|
||||
@@ -510,8 +499,16 @@ function TileRenderer:drawBorderFill(camX, camY, vw, vh)
|
||||
if not self.borderFill then return end
|
||||
if self.trueColor then PaletteFX.markTrueColor(0, 0, vw, vh) end
|
||||
local x, y = math.floor(camX), math.floor(camY)
|
||||
local quad = love.graphics.newQuad(x, y, vw, vh, 32, 32)
|
||||
love.graphics.draw(self.borderFill, quad, 0, 0)
|
||||
-- one reused Quad per renderer, mutated in place: this runs every
|
||||
-- overworld frame, so allocating a fresh Quad here churned the GC
|
||||
local q = self.borderQuad
|
||||
if q then
|
||||
q:setViewport(x, y, vw, vh, 32, 32)
|
||||
else
|
||||
q = love.graphics.newQuad(x, y, vw, vh, 32, 32)
|
||||
self.borderQuad = q
|
||||
end
|
||||
love.graphics.draw(self.borderFill, q, 0, 0)
|
||||
end
|
||||
|
||||
-- GB OBJ-to-BG priority: sprites show through BG color 0 and hide under
|
||||
@@ -556,19 +553,114 @@ function TileRenderer:drawCellBottom(cx, cy, camX, camY)
|
||||
if shader then love.graphics.setShader() end
|
||||
end
|
||||
|
||||
-- animated overdraw at the current step; bodyOnly skips the ring
|
||||
-- positions (connected maps draw body-only)
|
||||
function TileRenderer:drawAnimated(camX, camY, bodyOnly)
|
||||
-- queue the same bottom tile row for the post-zone sprite-redraw pass
|
||||
-- (GBC mode: OBP-baked sprites replay after the zone shader, so the
|
||||
-- grass patch that hides their feet must replay over them, colorized
|
||||
-- with the map's palette and color-0 keyed)
|
||||
function TileRenderer:markCellBottomRedraw(cx, cy, camX, camY, colors)
|
||||
local ty = cy * 2 + 1
|
||||
for i = 0, 1 do
|
||||
local tx = cx * 2 + i
|
||||
local quad = self.quads[self.map:tileAt(tx, ty)]
|
||||
if quad then
|
||||
PaletteFX.markSpriteRedraw(self.image, quad, tx * 8 - math.floor(camX),
|
||||
ty * 8 - math.floor(camY), 1, colors, true)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Window cover for the static tile layer. Refill the reusable window batch
|
||||
-- (and the per-entry animated batches) only when the camera has scrolled past
|
||||
-- what they already cover; a small margin keeps small scrolls free. Cost
|
||||
-- scales with the view, never the map -- crossing a seam or warping in builds
|
||||
-- nothing. The beyond-body area (what the old 3-block ring drew) is painted
|
||||
-- by :drawBorderFill, whose world-aligned border-block tiling is identical
|
||||
-- there, so only body tiles are gathered here.
|
||||
local WINDOW_MARGIN = 8 -- tiles of slack kept around the view between refills
|
||||
|
||||
function TileRenderer:ensureWindow(camX, camY, vw, vh)
|
||||
local W, H = self.bodyTilesW, self.bodyTilesH
|
||||
vw = vw or W * 8 -- a nil view (headless draw) means the whole body
|
||||
vh = vh or H * 8
|
||||
-- visible body-tile range (8px tiles), clamped to the map body
|
||||
local tx0 = math.min(W, math.max(0, math.floor(camX / 8)))
|
||||
local ty0 = math.min(H, math.max(0, math.floor(camY / 8)))
|
||||
local tx1 = math.max(0, math.min(W, math.floor((camX + vw) / 8) + 1))
|
||||
local ty1 = math.max(0, math.min(H, math.floor((camY + vh) / 8) + 1))
|
||||
local win = self.win
|
||||
if win and tx0 >= win.tx0 and ty0 >= win.ty0
|
||||
and tx1 <= win.tx1 and ty1 <= win.ty1 then
|
||||
return -- still inside the last fill
|
||||
end
|
||||
-- refill with margin so the next few scrolled pixels stay covered
|
||||
tx0 = math.max(0, tx0 - WINDOW_MARGIN)
|
||||
ty0 = math.max(0, ty0 - WINDOW_MARGIN)
|
||||
tx1 = math.min(W, tx1 + WINDOW_MARGIN)
|
||||
ty1 = math.min(H, ty1 + WINDOW_MARGIN)
|
||||
if not self.winBatch then
|
||||
self.winBatch = love.graphics.newSpriteBatch(self.image, 1024, "dynamic")
|
||||
end
|
||||
self.winBatch:clear()
|
||||
local anims = self.anims
|
||||
for _, anim in ipairs(anims) do
|
||||
if not anim.batch then
|
||||
anim.batch = love.graphics.newSpriteBatch(anim.textures[1], 256, "dynamic")
|
||||
end
|
||||
anim.batch:clear()
|
||||
end
|
||||
local map, quads = self.map, self.quads
|
||||
local claimedBy, aliasMap = self.claimedBy, self.aliasMap
|
||||
for ty = ty0, ty1 - 1 do
|
||||
local by = math.floor(ty / 4)
|
||||
local ty4 = ty % 4
|
||||
for tx = tx0, tx1 - 1 do
|
||||
local blockId = map:blockAt(math.floor(tx / 4), by)
|
||||
local block = map.tileset.blocks[blockId + 1]
|
||||
if block then
|
||||
local ci = ty4 * 4 + (tx % 4)
|
||||
local tile = block[ci + 1]
|
||||
local remap = aliasMap and aliasMap[blockId]
|
||||
if remap and remap[ci] then tile = remap[ci] end
|
||||
local wx, wy = tx * 8, ty * 8
|
||||
local quad = quads[tile]
|
||||
if quad then self.winBatch:add(quad, wx, wy) end
|
||||
local anim = claimedBy[tile]
|
||||
if anim then
|
||||
if anim.quadFor then
|
||||
anim.batch:add(anim.quadFor(tile), wx, wy)
|
||||
else
|
||||
anim.batch:add(wx, wy)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
self.win = { tx0 = tx0, ty0 = ty0, tx1 = tx1, ty1 = ty1 }
|
||||
end
|
||||
|
||||
-- draw the static tile window, then its animated overdraw, at the camera offset
|
||||
function TileRenderer:drawWindow(camX, camY, vw, vh)
|
||||
self:ensureWindow(camX, camY, vw, vh)
|
||||
if self.winBatch then
|
||||
love.graphics.draw(self.winBatch, -math.floor(camX), -math.floor(camY))
|
||||
end
|
||||
self:drawAnimated(camX, camY)
|
||||
end
|
||||
|
||||
-- animated overdraw at the current step, over the static window batch. The
|
||||
-- cells were gathered for the current camera window by :ensureWindow, so this
|
||||
-- only ever touches on-screen animated tiles.
|
||||
function TileRenderer:drawAnimated(camX, camY)
|
||||
local anims = self.anims
|
||||
if not anims then return end
|
||||
local x, y = -math.floor(camX), -math.floor(camY)
|
||||
for _, anim in ipairs(anims) do
|
||||
local batch = bodyOnly and anim.bodyBatch or anim.batch
|
||||
local batch = anim.batch
|
||||
if batch then
|
||||
if anim.gate then
|
||||
-- a gated entry has only the two frames the asm has (patch /
|
||||
-- restore-to-static); when the gate is shut draw nothing so the
|
||||
-- already-static mapBatch/ringBatch tile shows through unchanged
|
||||
-- already-static window tile shows through unchanged
|
||||
if gateOpen(anim.gate) then love.graphics.draw(batch, x, y) end
|
||||
else
|
||||
local step = math.floor(animFrame / anim.period) % #anim.sequence + 1
|
||||
@@ -589,30 +681,68 @@ function TileRenderer:markTrueColor(camX, camY, blocks)
|
||||
(def.height + 2 * blocks) * 32)
|
||||
end
|
||||
|
||||
function TileRenderer:draw(camX, camY)
|
||||
function TileRenderer:draw(camX, camY, vw, vh)
|
||||
if self.trueColor then self:markTrueColor(camX, camY, BORDER_BLOCKS) end
|
||||
love.graphics.draw(self.ringBatch, -math.floor(camX), -math.floor(camY))
|
||||
love.graphics.draw(self.mapBatch, -math.floor(camX), -math.floor(camY))
|
||||
self:drawAnimated(camX, camY)
|
||||
self:drawWindow(camX, camY, vw, vh)
|
||||
end
|
||||
|
||||
-- body only, for connected-map strips
|
||||
function TileRenderer:drawMapOnly(camX, camY)
|
||||
-- body only, for connected-map strips. Identical to :draw now that the
|
||||
-- border ring is served by :drawBorderFill for the current map too -- the
|
||||
-- only remaining difference is the trueColor mark extent.
|
||||
function TileRenderer:drawMapOnly(camX, camY, vw, vh)
|
||||
if self.trueColor then self:markTrueColor(camX, camY, 0) end
|
||||
love.graphics.draw(self.mapBatch, -math.floor(camX), -math.floor(camY))
|
||||
self:drawAnimated(camX, camY, true)
|
||||
self:drawWindow(camX, camY, vw, vh)
|
||||
end
|
||||
|
||||
-- rebuild after a block change (Cut trees)
|
||||
local function safeRelease(o)
|
||||
if o and o.release then pcall(o.release, o) end
|
||||
end
|
||||
|
||||
-- Release only the GPU objects this instance built and uniquely owns: the
|
||||
-- two SpriteBatches, the border-fill image and its quad, the per-tile
|
||||
-- quads, and the animated-overdraw batches. Deliberately leaves the
|
||||
-- tileset atlas (self.image, shared through Assets/imageCache) and the
|
||||
-- animation textures (shared module caches) alone -- other maps still use
|
||||
-- them. Used by :rebuild before it swaps in fresh batches, and by
|
||||
-- :release on eviction.
|
||||
function TileRenderer:releaseBatches()
|
||||
safeRelease(self.winBatch); self.winBatch = nil
|
||||
safeRelease(self.borderFill); self.borderFill = nil
|
||||
safeRelease(self.borderQuad); self.borderQuad = nil
|
||||
self.win = nil
|
||||
if self.quads then
|
||||
for _, q in pairs(self.quads) do safeRelease(q) end
|
||||
self.quads = nil
|
||||
end
|
||||
if self.anims then
|
||||
for _, a in ipairs(self.anims) do
|
||||
safeRelease(a.batch); a.batch = nil
|
||||
-- a.textures are shared, module-cached: never released here
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Full teardown for eviction (MapLoader.evict): the owned batches, plus
|
||||
-- the RED++ per-map recolored atlas, which -- unlike the plain tileset
|
||||
-- atlas -- is unique to this map (gbcAtlasCache is keyed by map id).
|
||||
function TileRenderer:release()
|
||||
self:releaseBatches()
|
||||
if self.gbcAtlas and self.image then
|
||||
local key = self.map.tileset.image .. "#gbc:" .. self.map.id
|
||||
if gbcAtlasCache[key] == self.image then gbcAtlasCache[key] = nil end
|
||||
safeRelease(self.image)
|
||||
self.image = nil
|
||||
self.gbcAtlas = nil
|
||||
end
|
||||
self.anims = nil
|
||||
end
|
||||
|
||||
-- rebuild after a block change (Cut trees, card-key doors). The tile layer
|
||||
-- is read live from the map on every window fill, so a block swap only needs
|
||||
-- the cached window dropped -- the next draw re-reads the changed blocks. No
|
||||
-- SpriteBatch is reconstructed; that is the whole point of the windowed draw.
|
||||
function TileRenderer:rebuild()
|
||||
local fresh = TileRenderer.new(self.map, self.data)
|
||||
self.image = fresh.image
|
||||
self.gbcAtlas = fresh.gbcAtlas
|
||||
self.quads = fresh.quads
|
||||
self.ringBatch = fresh.ringBatch
|
||||
self.mapBatch = fresh.mapBatch
|
||||
self.anims = fresh.anims
|
||||
self.borderFill = fresh.borderFill
|
||||
self.win = nil
|
||||
end
|
||||
|
||||
-- drop every atlas and every derived animation texture so the next
|
||||
|
||||
+22
-5
@@ -5,6 +5,7 @@
|
||||
-- Conditionals: check_flag stores its result in ctx.lastCheck;
|
||||
-- jump_if_true/jump_if_false jump to an absolute row index.
|
||||
|
||||
local Collision = require("src.world.Collision")
|
||||
local Flags = require("src.script.Flags")
|
||||
local Logger = require("src.core.Logger")
|
||||
local Screens = require("src.ui.Screens")
|
||||
@@ -269,7 +270,10 @@ end
|
||||
local DIRS4 = { { 0, -1, "up" }, { 0, 1, "down" },
|
||||
{ -1, 0, "left" }, { 1, 0, "right" } }
|
||||
|
||||
local function bfsPath(map, sx, sy, tx, ty)
|
||||
-- entities/mover let the walk route around other entities' cells (the
|
||||
-- player especially), so a scripted NPC never clips through them; the
|
||||
-- target cell is exempt so an NPC can still walk up onto its goal
|
||||
local function bfsPath(map, sx, sy, tx, ty, entities, mover)
|
||||
local key = function(x, y) return y * 1000 + x end
|
||||
local prev = { [key(sx, sy)] = false }
|
||||
local queue = { { sx, sy } }
|
||||
@@ -289,8 +293,11 @@ local function bfsPath(map, sx, sy, tx, ty)
|
||||
for _, d in ipairs(DIRS4) do
|
||||
local nx, ny = cx + d[1], cy + d[2]
|
||||
local nk = key(nx, ny)
|
||||
local isTarget = nx == tx and ny == ty
|
||||
if prev[nk] == nil and map:inBounds(nx, ny)
|
||||
and (map:isWalkableCell(nx, ny) or (nx == tx and ny == ty)) then
|
||||
and (map:isWalkableCell(nx, ny) or isTarget)
|
||||
and (isTarget or not entities
|
||||
or not Collision.occupied(entities, nx, ny, mover)) then
|
||||
prev[nk] = { cx, cy, d[3] }
|
||||
table.insert(queue, { nx, ny })
|
||||
end
|
||||
@@ -303,7 +310,7 @@ function Commands.move_npc_to(ctx, objIndex, tx, ty)
|
||||
local ow = ctx.overworld
|
||||
local npc = ow:npcByIndex(objIndex)
|
||||
if not npc then return end
|
||||
local path = bfsPath(ow.map, npc.cellX, npc.cellY, tx, ty)
|
||||
local path = bfsPath(ow.map, npc.cellX, npc.cellY, tx, ty, ow.entities, npc)
|
||||
if not path then
|
||||
Logger.warn("move_npc_to: no path to (%d,%d)", tx, ty)
|
||||
return
|
||||
@@ -390,6 +397,7 @@ local function toggleObject(ctx, mapId, objName, visible)
|
||||
-- positions mid-cutscene)
|
||||
local ow = ctx.overworld
|
||||
if not ow or ow.map.id ~= mapId then return end
|
||||
ow.npcPool = ow.npcPool or {}
|
||||
if visible then
|
||||
for _, n in ipairs(ow.npcs) do
|
||||
if n.def.name == objName then return end
|
||||
@@ -400,12 +408,16 @@ local function toggleObject(ctx, mapId, objName, visible)
|
||||
local npc = NPC.new(ctx.game.data, mapId, obj)
|
||||
table.insert(ow.npcs, npc)
|
||||
table.insert(ow.entities, npc)
|
||||
ow.npcPool[npc.id] = npc
|
||||
return
|
||||
end
|
||||
end
|
||||
else
|
||||
for i = #ow.npcs, 1, -1 do
|
||||
if ow.npcs[i].def.name == objName then table.remove(ow.npcs, i) end
|
||||
if ow.npcs[i].def.name == objName then
|
||||
ow.npcPool[ow.npcs[i].id] = nil
|
||||
table.remove(ow.npcs, i)
|
||||
end
|
||||
end
|
||||
for i = #ow.entities, 1, -1 do
|
||||
local e = ow.entities[i]
|
||||
@@ -823,7 +835,12 @@ end
|
||||
-- registry and block until the screen pops itself
|
||||
function Commands.push_screen(ctx, screenId, args)
|
||||
local screens = ctx.game.data.screens
|
||||
if not (screens and screens[screenId]) then
|
||||
local known = screens and screens[screenId] ~= nil
|
||||
if not known then
|
||||
-- builtin engine screens (src/ui/<id>.lua) resolve through Screens too
|
||||
known = pcall(Screens.get, ctx.game, screenId)
|
||||
end
|
||||
if not known then
|
||||
error(("push_screen: unknown screen '%s'"):format(tostring(screenId)), 0)
|
||||
end
|
||||
local runner = ctx.runner
|
||||
|
||||
+43
-28
@@ -296,37 +296,52 @@ local function useOn(game, battle, id, target, list, moveIndex)
|
||||
showMessages(game, payload) -- failed
|
||||
end
|
||||
|
||||
local function pickTargetAndUse(game, battle, id, list)
|
||||
-- pick a target from the party
|
||||
-- the ETHERs and PP UP open the move menu after picking a mon
|
||||
-- (ItemUsePPRestore / ItemUsePPUp); the ELIXERs hit every move
|
||||
local wantsMove = id == "ETHER" or id == "MAX_ETHER" or id == "PP_UP"
|
||||
require("src.ui.Screens").push(game, "PartyMenu", {
|
||||
pickOnly = true,
|
||||
onSwitch = function(mon)
|
||||
if not wantsMove then
|
||||
useOn(game, battle, id, mon, list)
|
||||
return
|
||||
end
|
||||
local rows = {}
|
||||
for mi, mv in ipairs(mon.moves) do
|
||||
local mdef = game.data.moves[mv.id]
|
||||
table.insert(rows, {
|
||||
value = mi,
|
||||
label = mdef and mdef.name or mv.id,
|
||||
right = ("%d"):format(mv.pp),
|
||||
})
|
||||
end
|
||||
game.stack:push(ListMenu.new(game, "Which move?", rows, {
|
||||
onChoose = function(row, l)
|
||||
l:close()
|
||||
useOn(game, battle, id, mon, list, row.value)
|
||||
end,
|
||||
}))
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
local function useItem(game, battle, id, list)
|
||||
local def = game.data.items[id]
|
||||
if ItemEffects.needsTarget(id, def) and not ItemEffects.isBall(id) then
|
||||
-- pick a target from the party
|
||||
-- the ETHERs and PP UP open the move menu after picking a mon
|
||||
-- (ItemUsePPRestore / ItemUsePPUp); the ELIXERs hit every move
|
||||
local wantsMove = id == "ETHER" or id == "MAX_ETHER" or id == "PP_UP"
|
||||
require("src.ui.Screens").push(game, "PartyMenu", {
|
||||
pickOnly = true,
|
||||
onSwitch = function(mon)
|
||||
if not wantsMove then
|
||||
useOn(game, battle, id, mon, list)
|
||||
return
|
||||
end
|
||||
local rows = {}
|
||||
for mi, mv in ipairs(mon.moves) do
|
||||
local mdef = game.data.moves[mv.id]
|
||||
table.insert(rows, {
|
||||
value = mi,
|
||||
label = mdef and mdef.name or mv.id,
|
||||
right = ("%d"):format(mv.pp),
|
||||
})
|
||||
end
|
||||
game.stack:push(ListMenu.new(game, "Which move?", rows, {
|
||||
onChoose = function(row, l)
|
||||
l:close()
|
||||
useOn(game, battle, id, mon, list, row.value)
|
||||
end,
|
||||
}))
|
||||
end,
|
||||
})
|
||||
-- TMs/HMs boot up and announce their move before the target picker
|
||||
-- (ItemUseTMHM: BootedUpTMText / BootedUpHMText + TeachMachineMoveText)
|
||||
if def and def.machine then
|
||||
local moveDef = game.data.moves[def.machine.move]
|
||||
local moveName = moveDef and moveDef.name or def.machine.move
|
||||
local booted = def.machine.kind == "HM"
|
||||
and "Booted up an HM!" or "Booted up a TM!"
|
||||
showMessages(game, { booted, ("It contained\n%s!"):format(moveName) },
|
||||
function() pickTargetAndUse(game, battle, id, list) end)
|
||||
return
|
||||
end
|
||||
pickTargetAndUse(game, battle, id, list)
|
||||
else
|
||||
useOn(game, battle, id, nil, list)
|
||||
end
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
-- Rebinding over the logical Game Boy buttons (gap C2's file-12 half,
|
||||
-- 12-ui-extensibility 4.4): one row per button, A arms a "PRESS A BUTTON"
|
||||
-- capture and the captured key or pad button lands in
|
||||
-- save.options.bindings -- the overlay src/core/Bindings.lua
|
||||
-- (04-mod-api-core) reads back over Input's fixed map.
|
||||
-- save.options.bindings, which Input:applyBindings layers over its fixed
|
||||
-- default map (see src/core/Input.lua and Game:applyOptions).
|
||||
|
||||
local Font = require("src.render.Font")
|
||||
local ListMenu = require("src.ui.ListMenu")
|
||||
local Input = require("src.core.Input")
|
||||
|
||||
local BindingsMenu = setmetatable({}, { __index = ListMenu })
|
||||
BindingsMenu.__index = BindingsMenu
|
||||
@@ -78,6 +79,7 @@ function BindingsMenu:storeBinding(slot, value)
|
||||
b[slot] = value
|
||||
opts.bindings[item.button.id] = b
|
||||
item.right = boundKey(opts.bindings, item.button):upper()
|
||||
Input:applyBindings(opts.bindings)
|
||||
if game.writeOptions then game:writeOptions() end
|
||||
end
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
-- has no cancel; the flash always completes).
|
||||
|
||||
local Font = require("src.render.Font")
|
||||
local Music = require("src.core.Music")
|
||||
|
||||
local EvolutionState = {}
|
||||
EvolutionState.__index = EvolutionState
|
||||
@@ -39,6 +40,7 @@ function EvolutionState.new(game, mon, newSpecies, onDone)
|
||||
self.newSprite = frontSprite(game, newSpecies)
|
||||
self.t = 0
|
||||
self.done = false
|
||||
Music.play(game.data, Music.special(game.data, "evolution"))
|
||||
return self
|
||||
end
|
||||
|
||||
@@ -57,6 +59,7 @@ function EvolutionState:update(dt)
|
||||
("Congratulations!\nYour %s\nevolved into\n%s!")
|
||||
:format(self.oldName, newName),
|
||||
function()
|
||||
Music.restoreMap(game.data)
|
||||
game.stack:pop() -- the evolution screen itself
|
||||
if self.onDone then self.onDone() end
|
||||
end))
|
||||
|
||||
+56
-6
@@ -16,6 +16,11 @@ local OakSpeech = {}
|
||||
OakSpeech.__index = OakSpeech
|
||||
OakSpeech.isOpaque = true
|
||||
|
||||
-- FadeInIntroPic runs a 6-step palette fade; MovePicLeft wipes the mon
|
||||
-- sprite in from the right. Both play out before the beat's text prints.
|
||||
local FADE_FRAMES = 24
|
||||
local WIPE_FRAMES = 32
|
||||
|
||||
-- naming presets are boot config (field.boot.namePresets), which a total
|
||||
-- conversion replaces; the Red/Blue lists remain the fallback
|
||||
local function namePresets(game, who, fallback)
|
||||
@@ -93,16 +98,23 @@ function OakSpeech:say(key, next)
|
||||
end
|
||||
|
||||
local STEPS = {
|
||||
-- 1. Oak's welcome
|
||||
-- 1. Oak's welcome (Oak's pic fades in first, FadeInIntroPic)
|
||||
function(self)
|
||||
self.pic = self.oakPic
|
||||
self:say("_OakSpeechText1", function() self:advance() end)
|
||||
self:revealPic("fade", function()
|
||||
self:say("_OakSpeechText1", function() self:advance() end)
|
||||
end)
|
||||
end,
|
||||
-- 2. NIDORINO show-off, with its cry
|
||||
-- 2. NIDORINO show-off: the front sprite is mirrored horizontally
|
||||
-- (LoadFlippedFrontSpriteByMonIndex) and wipes in from the right
|
||||
-- (MovePicLeft), then its cry sounds and the text prints
|
||||
function(self)
|
||||
self.pic = self.demoPic
|
||||
Sound.playCry(self.game.data, self.demoSpecies)
|
||||
self:say("_OakSpeechText2A", function() self:advance() end)
|
||||
self.picFlip = true
|
||||
self:revealPic("wipe", function()
|
||||
Sound.playCry(self.game.data, self.demoSpecies)
|
||||
self:say("_OakSpeechText2A", function() self:advance() end)
|
||||
end)
|
||||
end,
|
||||
-- 3. the rest of the world-of-POKéMON spiel
|
||||
function(self)
|
||||
@@ -175,8 +187,21 @@ function OakSpeech:lastPageLines(key)
|
||||
return ok and lines or nil
|
||||
end
|
||||
|
||||
-- Reveal the current pic over `dur` frames, then run `next`. Ticked from
|
||||
-- update() while OakSpeech is the top state (before the beat's text box is
|
||||
-- pushed), so the fade/wipe plays out ahead of the text like the ROM.
|
||||
function OakSpeech:revealPic(kind, next)
|
||||
self.picReveal = {
|
||||
kind = kind,
|
||||
t = 0,
|
||||
dur = kind == "fade" and FADE_FRAMES or WIPE_FRAMES,
|
||||
next = next,
|
||||
}
|
||||
end
|
||||
|
||||
function OakSpeech:advance()
|
||||
self.step = self.step + 1
|
||||
self.picFlip = false
|
||||
local fn = STEPS[self.step]
|
||||
if fn then
|
||||
fn(self)
|
||||
@@ -205,6 +230,15 @@ end
|
||||
-- ClearScreenArea / wUpdateSpritesEnabled; ld c, 50)
|
||||
-- frames 79-102 GBFadeOutToWhite (3 palettes x 8 frames)
|
||||
function OakSpeech:update(dt)
|
||||
local r = self.picReveal
|
||||
if r then
|
||||
r.t = r.t + 1
|
||||
if r.t >= r.dur then
|
||||
self.picReveal = nil
|
||||
if r.next then r.next() end
|
||||
end
|
||||
return
|
||||
end
|
||||
if not self.shrink then return end
|
||||
local s = self.shrink
|
||||
s.frame = s.frame + 1
|
||||
@@ -238,7 +272,23 @@ function OakSpeech:draw()
|
||||
local w, h = self.pic:getDimensions()
|
||||
local x = 48 + math.floor((8 - w / 8) / 2) * 8
|
||||
local y = 32 + (7 - h / 8) * 8
|
||||
love.graphics.draw(self.pic, x, y)
|
||||
local reveal = self.picReveal
|
||||
local off = 0
|
||||
if reveal and reveal.kind == "fade" then
|
||||
-- FadeInIntroPic: ramp the pic's alpha up over the fade window
|
||||
love.graphics.setColor(1, 1, 1, math.min(1, reveal.t / reveal.dur))
|
||||
elseif reveal and reveal.kind == "wipe" then
|
||||
-- MovePicLeft: the pic slides in from the right edge to its spot
|
||||
off = math.floor((160 - x) * (1 - math.min(1, reveal.t / reveal.dur)))
|
||||
end
|
||||
if self.picFlip then
|
||||
-- LoadFlippedFrontSpriteByMonIndex mirrors the front sprite
|
||||
-- horizontally (wSpriteFlipped): draw with a negative x scale
|
||||
love.graphics.draw(self.pic, x + off + w, y, 0, -1, 1)
|
||||
else
|
||||
love.graphics.draw(self.pic, x + off, y)
|
||||
end
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
end
|
||||
if self.walkVisible and self.walkSheet then
|
||||
-- ResetPlayerSpriteData: Y screen pos $3c, X screen pos $40
|
||||
|
||||
@@ -13,6 +13,7 @@ local Tilt = require("src.render.Tilt")
|
||||
local GBCFX = require("src.render.GBCFX")
|
||||
local GameSpeed = require("src.core.GameSpeed")
|
||||
local VideoMode = require("src.core.VideoMode")
|
||||
local FrameCap = require("src.core.FrameCap")
|
||||
local Logger = require("src.core.Logger")
|
||||
local Runtime = require("src.mods.Runtime")
|
||||
local OptionRows = require("src.ui.OptionRows")
|
||||
@@ -202,6 +203,19 @@ local function buildRows(game)
|
||||
VideoMode.apply(o.videoMode)
|
||||
return true
|
||||
end },
|
||||
-- hard render cap (issue #88): bounds the present rate so a
|
||||
-- driver-forced vsync-off run cannot spin at thousands of FPS. Logic
|
||||
-- is fixed-step off dt, so this touches presentation only.
|
||||
{ id = "fpsCap", label = "MAX FPS",
|
||||
value = function(g)
|
||||
return FrameCap.label(g.save.options.fpsCap)
|
||||
end,
|
||||
step = function(g, dir)
|
||||
local o = g.save.options
|
||||
o.fpsCap = FrameCap.cycle(o.fpsCap, dir)
|
||||
FrameCap.apply(o.fpsCap)
|
||||
return true
|
||||
end },
|
||||
-- fast-forward the logic clock only; music and sfx keep their tempo
|
||||
-- (src/core/GameSpeed.lua), so this is safe to leave on
|
||||
{ id = "speed", label = "GAME SPEED",
|
||||
|
||||
+7
-1
@@ -99,7 +99,13 @@ end
|
||||
local function deposit(game)
|
||||
local pc = game.save.pcItems
|
||||
local inv = game.save.inventory
|
||||
game.stack:push(ListMenu.new(game, "DEPOSIT ITEM", buildItems(game, inv), {
|
||||
local Bag = require("src.inventory.Bag")
|
||||
-- badges live in save.inventory alongside items but are not depositable
|
||||
local depositable = {}
|
||||
for id, count in pairs(inv) do
|
||||
if not Bag.isBadge(id) then depositable[id] = count end
|
||||
end
|
||||
game.stack:push(ListMenu.new(game, "DEPOSIT ITEM", buildItems(game, depositable), {
|
||||
onChoose = function(item, list)
|
||||
askQuantity(game, list, inv[item.value] or 1, item.value, function(qty)
|
||||
if pcFull(game, pc, item.value) then
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
-- item list runs through the ui.start_menu.items hook before the menu
|
||||
-- opens, so mods insert or remove rows without patching this file.
|
||||
|
||||
local Font = require("src.render.Font")
|
||||
local Logger = require("src.core.Logger")
|
||||
local Menu = require("src.ui.Menu")
|
||||
local Runtime = require("src.mods.Runtime")
|
||||
@@ -126,6 +127,24 @@ function StartMenu.new(game)
|
||||
baseUpdate(self, dt)
|
||||
game.save.startMenuIndex = self.index
|
||||
end
|
||||
|
||||
-- inside the Safari Zone the start menu also shows remaining steps and
|
||||
-- SAFARI BALLs (PrintSafariZoneSteps): a 9x5 border at the top-left with
|
||||
-- "steps/500" and "BALL xx"
|
||||
if game.save.safari then
|
||||
local baseDraw = menu.draw
|
||||
menu.draw = function(self)
|
||||
baseDraw(self)
|
||||
local safari = game.save.safari
|
||||
Font.drawBox(0, 0, 9, 5)
|
||||
love.graphics.setColor(0, 0, 0, 1)
|
||||
Font.draw(("%3d"):format(math.floor(safari.steps or 0)), 8, 8)
|
||||
Font.draw("/500", 32, 8)
|
||||
Font.draw("BALL", 8, 24)
|
||||
Font.draw(("%2d"):format(math.floor(safari.balls or 0)), 48, 24)
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
end
|
||||
end
|
||||
return menu
|
||||
end
|
||||
|
||||
|
||||
+32
-9
@@ -5,6 +5,7 @@
|
||||
|
||||
local Font = require("src.render.Font")
|
||||
local Music = require("src.core.Music")
|
||||
local GameVersion = require("src.core.GameVersion")
|
||||
|
||||
local TitleState = {}
|
||||
TitleState.__index = TitleState
|
||||
@@ -30,6 +31,13 @@ local CYCLE_SPECIES = {
|
||||
"PIKACHU", "CLEFAIRY", "RHYDON", "ABRA", "GASTLY", "DITTO",
|
||||
"PIDGEOTTO", "ONIX", "PONYTA", "MAGIKARP",
|
||||
}
|
||||
-- Blue's TitleMons (data/pokemon/title_mons.asm, _BLUE branch): STARTER2 is
|
||||
-- Squirtle, STARTER1 Charmander, STARTER3 Bulbasaur.
|
||||
local BLUE_CYCLE_SPECIES = {
|
||||
"SQUIRTLE", "CHARMANDER", "BULBASAUR", "MANKEY", "HITMONLEE",
|
||||
"VULPIX", "CHANSEY", "AERODACTYL", "JOLTEON", "SNORLAX",
|
||||
"GLOOM", "POLIWAG", "DODUO", "PORYGON", "GENGAR", "RAICHU",
|
||||
}
|
||||
local CYCLE_FRAMES = 240 -- the original waits ~4s between picks
|
||||
|
||||
local function tryImage(path)
|
||||
@@ -61,9 +69,13 @@ function TitleState.new(game, opts)
|
||||
self.version = tryImage(imagePath(title.versionRibbon or title.version)
|
||||
or "assets/generated/title/red_version.png")
|
||||
self.player = tryImage("assets/generated/title/player.png")
|
||||
self.blue = GameVersion.isBlue()
|
||||
-- Blue cycles its own title mons and prints its ribbon contiguously; a
|
||||
-- field.title.cycleSpecies override (mods / total conversions) still wins.
|
||||
local defaultCycle = self.blue and BLUE_CYCLE_SPECIES or CYCLE_SPECIES
|
||||
self.cycleSpecies = (type(title.cycleSpecies) == "table"
|
||||
and #title.cycleSpecies > 0)
|
||||
and title.cycleSpecies or CYCLE_SPECIES
|
||||
and title.cycleSpecies or defaultCycle
|
||||
self.sprites = {} -- species -> image or false (load failed)
|
||||
self.cycleIndex = 1
|
||||
self.timer = 0
|
||||
@@ -92,8 +104,10 @@ end
|
||||
|
||||
local function hasSave()
|
||||
local ok, info = pcall(function()
|
||||
-- the active game's save file (save.lua for Red, save_blue.lua for Blue)
|
||||
local name = require("src.core.SaveData").saveFilename(GameVersion.get())
|
||||
return love.filesystem and love.filesystem.getInfo
|
||||
and love.filesystem.getInfo("save.lua") or nil
|
||||
and love.filesystem.getInfo(name) or nil
|
||||
end)
|
||||
return ok and info ~= nil
|
||||
end
|
||||
@@ -211,17 +225,26 @@ function TitleState:draw()
|
||||
love.graphics.draw(self.logo, 16, 8)
|
||||
else
|
||||
love.graphics.setColor(0, 0, 0, 1)
|
||||
Font.draw("POKéMON RED", (160 - 11 * 8) / 2, 24)
|
||||
Font.draw(self.blue and "POKéMON BLUE" or "POKéMON RED",
|
||||
(160 - 12 * 8) / 2, 24)
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
end
|
||||
if self.version then
|
||||
-- the strip holds Red+Green+Version glyphs; the tilemap prints
|
||||
-- tiles $60,$61 ("Red"), a space, then $65-$69 ("Version")
|
||||
local iw, ih = self.version:getDimensions()
|
||||
love.graphics.draw(self.version,
|
||||
love.graphics.newQuad(0, 0, 16, 8, iw, ih), 56, 64)
|
||||
love.graphics.draw(self.version,
|
||||
love.graphics.newQuad(40, 0, 40, 8, iw, ih), 80, 64)
|
||||
if self.blue then
|
||||
-- Blue prints its ribbon contiguously ("Blue Version", hlcoord 7,8).
|
||||
-- The extracted strip packs those eight glyph tiles into image tiles
|
||||
-- 0..7 (tiles 8..9 are blank), so draw that 64px run at px (56, 64).
|
||||
love.graphics.draw(self.version,
|
||||
love.graphics.newQuad(0, 0, 64, 8, iw, ih), 56, 64)
|
||||
else
|
||||
-- Red's strip holds Red+Green+Version glyphs; the tilemap prints
|
||||
-- tiles $60,$61 ("Red"), a space, then $65-$69 ("Version").
|
||||
love.graphics.draw(self.version,
|
||||
love.graphics.newQuad(0, 0, 16, 8, iw, ih), 56, 64)
|
||||
love.graphics.draw(self.version,
|
||||
love.graphics.newQuad(40, 0, 40, 8, iw, ih), 80, 64)
|
||||
end
|
||||
end
|
||||
local sprite = self:currentSprite()
|
||||
if sprite then
|
||||
|
||||
@@ -24,6 +24,15 @@ local NO_SHORE_TILESETS = { SHIP_PORT = true }
|
||||
-- what counts as "outside" for the wLastMap memory (CheckIfInOutsideMap)
|
||||
local OUTSIDE_TILESETS = { "OVERWORLD", "PLATEAU" }
|
||||
|
||||
-- warp pads and fall-through holes (data/tilesets/warp_pad_hole_tile_ids
|
||||
-- .asm WarpPadAndHoleData); a tileset record carrying warpPadTiles
|
||||
-- ({ [tileId] = "pad"|"hole" }) wins over these vanilla rows
|
||||
local WARP_PAD_TILES = {
|
||||
FACILITY = { [0x20] = "pad", [0x11] = "hole" },
|
||||
CAVERN = { [0x22] = "hole" },
|
||||
INTERIOR = { [0x55] = "pad" },
|
||||
}
|
||||
|
||||
local function hashSet(list, into)
|
||||
for _, t in ipairs(list) do into[t] = true end
|
||||
return into
|
||||
@@ -199,6 +208,14 @@ function Map:isWarpTileCell(cx, cy)
|
||||
return self.doorTiles[t] or self.warpTiles[t] or false
|
||||
end
|
||||
|
||||
-- "pad"/"hole" when the cell's collision tile is a teleporter warp pad or
|
||||
-- a fall-through hole (IsPlayerStandingOnWarpPadOrHole), nil otherwise
|
||||
function Map:warpPadOrHoleAt(cx, cy)
|
||||
local table_ = self.tileset.warpPadTiles or WARP_PAD_TILES[self.def.tileset]
|
||||
if not table_ then return nil end
|
||||
return table_[self:cellTile(cx, cy)]
|
||||
end
|
||||
|
||||
-- counter tiles allow talking to NPCs across them (mart clerks, nurses)
|
||||
function Map:isCounterCell(cx, cy)
|
||||
local t = self:cellTile(cx, cy)
|
||||
|
||||
+72
-5
@@ -2,6 +2,13 @@
|
||||
-- data, cached by map id. The cache is keyed so a mod that patches one
|
||||
-- map record after boot (or the dev-mode hot reload) can drop just that
|
||||
-- entry instead of every map's SpriteBatches.
|
||||
--
|
||||
-- The resident set is trimmed LRU (trim) so exploring a large world never
|
||||
-- holds every visited map's GPU objects at once. Maps are built on demand
|
||||
-- and cheaply: a map's tile layer draws windowed to the camera (see
|
||||
-- TileRenderer), so there is no per-map batch to construct up front and thus
|
||||
-- nothing to stream -- OverworldState:rebuildNeighbors just loads each
|
||||
-- neighbor directly.
|
||||
|
||||
local Assets = require("src.render.Assets")
|
||||
local Map = require("src.world.Map")
|
||||
@@ -10,9 +17,20 @@ local TileRenderer = require("src.render.TileRenderer")
|
||||
local MapLoader = {}
|
||||
|
||||
local cache = {}
|
||||
-- mapId -> monotonic access stamp, for LRU eviction
|
||||
local lru = {}
|
||||
local accessSeq = 0
|
||||
-- max map renderers kept resident. Comfortably above the largest
|
||||
-- current+neighbor set (~15 in dense overworld), so protected maps are
|
||||
-- never the ones evicted; this only caps the lingering trail behind you.
|
||||
local RESIDENT_CAP = 32
|
||||
|
||||
function MapLoader.load(data, mapId)
|
||||
if cache[mapId] then return cache[mapId] end
|
||||
local function touch(mapId)
|
||||
accessSeq = accessSeq + 1
|
||||
lru[mapId] = accessSeq
|
||||
end
|
||||
|
||||
local function build(data, mapId)
|
||||
local def = data.maps[mapId]
|
||||
assert(def, "unknown map: " .. tostring(mapId) ..
|
||||
" (not in the maps registry)")
|
||||
@@ -25,26 +43,75 @@ function MapLoader.load(data, mapId)
|
||||
local map = Map.new(def, tilesetDef)
|
||||
map.renderer = TileRenderer.new(map, data)
|
||||
cache[mapId] = map
|
||||
touch(mapId)
|
||||
return map
|
||||
end
|
||||
|
||||
function MapLoader.load(data, mapId)
|
||||
local m = cache[mapId]
|
||||
if m then touch(mapId); return m end
|
||||
return build(data, mapId)
|
||||
end
|
||||
|
||||
-- the live instance for a map id, or nil when it has not been loaded;
|
||||
-- callers that must not build a map (invalidation, tests) use this
|
||||
function MapLoader.cached(mapId)
|
||||
return cache[mapId]
|
||||
local m = cache[mapId]
|
||||
if m then touch(mapId) end
|
||||
return m
|
||||
end
|
||||
|
||||
-- evict one resident map, releasing its renderer's GPU objects. Callers
|
||||
-- must ensure the map is not the current map and not drawn as a connected
|
||||
-- strip (nothing live may hold its renderer) -- MapLoader.trim guarantees
|
||||
-- this via its `protected` set.
|
||||
function MapLoader.evict(mapId)
|
||||
local m = cache[mapId]
|
||||
if not m then return false end
|
||||
cache[mapId] = nil
|
||||
lru[mapId] = nil
|
||||
local r = m.renderer
|
||||
if r and r.release then pcall(r.release, r) end
|
||||
return true
|
||||
end
|
||||
|
||||
-- keep the resident renderer set bounded. `protected` (mapId -> true) is
|
||||
-- never evicted (the current map and everything drawn as a connected
|
||||
-- strip); the rest is trimmed least-recently-used down to RESIDENT_CAP.
|
||||
function MapLoader.trim(protected)
|
||||
local n = 0
|
||||
for _ in pairs(cache) do n = n + 1 end
|
||||
if n <= RESIDENT_CAP then return end
|
||||
local ids = {}
|
||||
for id in pairs(cache) do
|
||||
if not (protected and protected[id]) then ids[#ids + 1] = id end
|
||||
end
|
||||
table.sort(ids, function(a, b) return (lru[a] or 0) < (lru[b] or 0) end)
|
||||
local over = n - RESIDENT_CAP
|
||||
for _, id in ipairs(ids) do
|
||||
if over <= 0 then break end
|
||||
MapLoader.evict(id)
|
||||
over = over - 1
|
||||
end
|
||||
end
|
||||
|
||||
-- drop one map so the next load re-reads its record and rebuilds its
|
||||
-- renderer. Callers holding the old instance keep it -- OverworldState
|
||||
-- re-points self.map itself (WorldAPI:invalidateMap).
|
||||
-- renderer. Deliberately does NOT release the old renderer: callers
|
||||
-- holding the old instance keep drawing it until they re-point themselves
|
||||
-- (OverworldState re-points self.map / self.neighbors via setMap /
|
||||
-- rebuildNeighbors), so releasing here would free a batch still in use.
|
||||
-- The orphaned instance is reclaimed by GC; MapLoader.evict is the path
|
||||
-- that releases eagerly, and it only runs on maps nothing live holds.
|
||||
function MapLoader.invalidate(mapId)
|
||||
local had = cache[mapId] ~= nil
|
||||
cache[mapId] = nil
|
||||
lru[mapId] = nil
|
||||
return had
|
||||
end
|
||||
|
||||
function MapLoader.invalidateAll()
|
||||
cache = {}
|
||||
lru = {}
|
||||
end
|
||||
|
||||
-- kept as the pre-v2 name
|
||||
|
||||
@@ -40,6 +40,10 @@ local HEAL_BALL_XY = {
|
||||
{ 40, 37 }, { 48, 37, true },
|
||||
}
|
||||
|
||||
-- the healing machine's flash beat (FlashSprite8Times: rOBP1 ^= $28)
|
||||
-- swaps the two middle shades of the monitor/ball art in place
|
||||
local HEAL_FLASH_MAP = { [0] = 0, [1] = 2, [2] = 1, [3] = 3 }
|
||||
|
||||
-- object_event spawn filter (toggleable_objects, items taken, beaten
|
||||
-- static encounters), shared by the current map's real NPCs and the
|
||||
-- visual-only ghosts on connected neighbor maps
|
||||
@@ -91,11 +95,25 @@ local NEIGHBOR_HOPS = 2
|
||||
-- (32 px), the same alignment the connection macro encodes
|
||||
-- (macros/scripts/maps.asm: _x = offset * -2 walk cells for
|
||||
-- north/south, _y = offset * -2 for west/east).
|
||||
function OverworldState.computeNeighbors(maps, rootId, hops)
|
||||
-- reachW/reachH (optional, world pixels): with a full zoom-out the view
|
||||
-- shows far more world than the fixed hop count covers, so any map whose
|
||||
-- body could overlap the current map's rect inflated by the view
|
||||
-- half-extents joins the set (and keeps the walk going) regardless of how
|
||||
-- many connections away it sits -- otherwise far map bodies pop between
|
||||
-- real tiles and the border filler when a crossing re-roots the BFS.
|
||||
function OverworldState.computeNeighbors(maps, rootId, hops, reachW, reachH)
|
||||
local out = {}
|
||||
local rootDef = maps[rootId]
|
||||
local placed = { [rootId] = true }
|
||||
local queue = { { def = maps[rootId], ox = 0, oy = 0, hops = 0 } }
|
||||
local queue = { { def = rootDef, ox = 0, oy = 0, hops = 0 } }
|
||||
local qi = 1
|
||||
local function inReach(def, ox, oy)
|
||||
if not (reachW and reachH and rootDef) then return false end
|
||||
return ox + def.width * 32 > -reachW
|
||||
and ox < rootDef.width * 32 + reachW
|
||||
and oy + def.height * 32 > -reachH
|
||||
and oy < rootDef.height * 32 + reachH
|
||||
end
|
||||
while queue[qi] do
|
||||
local cur = queue[qi]
|
||||
qi = qi + 1
|
||||
@@ -114,11 +132,13 @@ function OverworldState.computeNeighbors(maps, rootId, hops)
|
||||
ox, oy = cur.def.width * 32, conn.offset * 32
|
||||
end
|
||||
ox, oy = cur.ox + ox, cur.oy + oy
|
||||
table.insert(out, { id = conn.map, ox = ox, oy = oy })
|
||||
if cur.hops + 1 < hops then
|
||||
table.insert(queue,
|
||||
{ def = destDef, ox = ox, oy = oy,
|
||||
hops = cur.hops + 1 })
|
||||
if cur.hops + 1 <= hops or inReach(destDef, ox, oy) then
|
||||
table.insert(out, { id = conn.map, ox = ox, oy = oy })
|
||||
if cur.hops + 1 < hops or inReach(destDef, ox, oy) then
|
||||
table.insert(queue,
|
||||
{ def = destDef, ox = ox, oy = oy,
|
||||
hops = cur.hops + 1 })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -200,6 +220,24 @@ function OverworldState:setMap(mapId, x, y, facing, opts)
|
||||
self.map.renderer:rebuild()
|
||||
self.cutBlocks[mapId] = nil
|
||||
end
|
||||
-- Silph Co card key doors: the .blk layouts ship with the doorways
|
||||
-- open; each floor's map script stamps the closed door block on load
|
||||
-- until its unlock event is set (scripts/SilphCo2F.asm
|
||||
-- SilphCo2FGateCallbackScript et al., closed blocks $54/$5f/$20)
|
||||
local closedDoors = FieldDefaults.fieldValue(Game.data, "cardKeyDoors",
|
||||
"closedDoors")
|
||||
local floorDoors = closedDoors and closedDoors[mapId]
|
||||
if floorDoors then
|
||||
local stamped = false
|
||||
for _, door in ipairs(floorDoors) do
|
||||
local want = Game.save.flags[door.event] and door.open or door.block
|
||||
if self.map:blockAt(door.bx, door.by) ~= want then
|
||||
self.map:setBlock(door.bx, door.by, want)
|
||||
stamped = true
|
||||
end
|
||||
end
|
||||
if stamped then self.map.renderer:rebuild() end
|
||||
end
|
||||
-- forced dismount only where riding is disallowed (IsBikeRidingAllowed,
|
||||
-- home/overworld.asm: bike_riding_tilesets.asm tilesets plus the
|
||||
-- ROUTE_23/INDIGO_PLATEAU map exceptions)
|
||||
@@ -278,6 +316,13 @@ function OverworldState:setMap(mapId, x, y, facing, opts)
|
||||
self.player.surfing)
|
||||
end
|
||||
|
||||
-- forced bike/surf tiles fire the moment the player is placed on the
|
||||
-- map, like EnterMap's unconditional CheckForceBikeOrSurf farcall
|
||||
-- (home/overworld.asm) -- a warp can land directly on one (the Route
|
||||
-- 16/18 gate exits), and the scripted door-mat walkout that follows
|
||||
-- suppresses onStepComplete, so waiting for a plain step never mounts
|
||||
self:checkForcedMovement()
|
||||
|
||||
-- snap the camera immediately: the overworld doesn't update while a
|
||||
-- Transition is on top, so a stale camera would show the new map at
|
||||
-- the old scroll position for the whole fade-in
|
||||
@@ -299,17 +344,45 @@ function OverworldState:setMap(mapId, x, y, facing, opts)
|
||||
hooks.onEnter(Game, self)
|
||||
end
|
||||
|
||||
-- neighbor maps drawn at the composed connection offsets, two hops
|
||||
-- out (the GB only ever streamed a 32px strip of the single
|
||||
-- directly connected map -- home/overworld.asm .loadNewMap)
|
||||
self:rebuildNeighbors()
|
||||
Logger.info("map: %s at (%d,%d)", mapId, x, y)
|
||||
-- Route22Gate_Script rewrites wLastMap from the player's Y on entry
|
||||
-- too (not only on step), so a save/load mid-gate keeps exits correct
|
||||
self:syncLastMapRewrite()
|
||||
end
|
||||
|
||||
-- Neighbor maps drawn at the composed connection offsets: at least the
|
||||
-- configured hop count out (the GB only ever streamed a 32px strip of
|
||||
-- the single directly connected map -- home/overworld.asm .loadNewMap),
|
||||
-- widened to everything the current view size can show so a full
|
||||
-- zoom-out never runs past the rendered set. Re-run whenever the view
|
||||
-- grows (zoom/resize), not only on setMap.
|
||||
--
|
||||
-- Neighbors are built eagerly here. A TileRenderer is now a light object --
|
||||
-- the tile layer draws windowed to the camera, so nothing per-map is
|
||||
-- constructed up front (see TileRenderer) -- so there is no build cost to
|
||||
-- amortize and no prefetch race to lose at a seam. That is what the old
|
||||
-- one-per-frame streaming queue existed to hide, and it is gone.
|
||||
function OverworldState:rebuildNeighbors()
|
||||
local mapId = self.map.id
|
||||
self.neighbors = {}
|
||||
local hops = FieldDefaults.world(Game.data, "neighborHops") or NEIGHBOR_HOPS
|
||||
for _, n in ipairs(OverworldState.computeNeighbors(Game.data.maps,
|
||||
mapId, hops)) do
|
||||
table.insert(self.neighbors,
|
||||
{ map = MapLoader.load(Game.data, n.id),
|
||||
ox = n.ox, oy = n.oy })
|
||||
local vw, vh = Game.renderer:worldViewSize()
|
||||
self.neighborViewW, self.neighborViewH = vw, vh
|
||||
-- resident set the eviction pass must never touch: the current map plus
|
||||
-- every drawn neighbor
|
||||
local keep = { [mapId] = true }
|
||||
for _, n in ipairs(OverworldState.computeNeighbors(Game.data.maps, mapId,
|
||||
hops,
|
||||
math.floor(vw / 2) + 64,
|
||||
math.floor(vh / 2) + 64)) do
|
||||
keep[n.id] = true
|
||||
local m = MapLoader.load(Game.data, n.id)
|
||||
table.insert(self.neighbors, { map = m, ox = n.ox, oy = n.oy })
|
||||
end
|
||||
-- bound resident memory: drop maps behind us that are neither current nor
|
||||
-- a drawn neighbor, releasing their window batch / border image / atlas
|
||||
MapLoader.trim(keep)
|
||||
|
||||
-- visual-only NPCs on connected maps (survey zoom): same spawn filter
|
||||
-- as a real map entry, but they never join self.entities -- no sight
|
||||
@@ -328,10 +401,6 @@ function OverworldState:setMap(mapId, x, y, facing, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
Logger.info("map: %s at (%d,%d)", mapId, x, y)
|
||||
-- Route22Gate_Script rewrites wLastMap from the player's Y on entry
|
||||
-- too (not only on step), so a save/load mid-gate keeps exits correct
|
||||
self:syncLastMapRewrite()
|
||||
end
|
||||
|
||||
-- SGB overworld palette (engine/gfx/palettes.asm SetPal_Overworld):
|
||||
@@ -377,7 +446,9 @@ function OverworldState:paletteNameFor(map)
|
||||
return Runtime.call("map.palette", samePalette, name, map)
|
||||
end
|
||||
|
||||
-- UI-pass palette (text boxes and menus tint with the current map)
|
||||
-- UI-pass palette (text boxes and menus tint with the current map). OG RED
|
||||
-- resolves every name to the one global red BG palette inside PaletteFX.pal,
|
||||
-- so this needs no mode-specific branch.
|
||||
function OverworldState:sgbPalettes()
|
||||
local PaletteFX = require("src.render.PaletteFX")
|
||||
return PaletteFX.wholeNamed(Game.data, self:paletteNameFor(self.map))
|
||||
@@ -607,6 +678,14 @@ function OverworldState:update(dt)
|
||||
-- keep the player sprite in sync with the bike state (the drawer
|
||||
-- picks the red_bike sheet while riding)
|
||||
self.player.onBike = Game.save.onBike
|
||||
-- the rendered neighbor set depends on the view size; zooming out (or
|
||||
-- resizing) past what setMap computed re-runs the walk in place
|
||||
if self.map and (self.neighborViewW or 0) > 0 then
|
||||
local vw, vh = Game.renderer:worldViewSize()
|
||||
if vw ~= self.neighborViewW or vh ~= self.neighborViewH then
|
||||
self:rebuildNeighbors()
|
||||
end
|
||||
end
|
||||
if self.dustAnim then
|
||||
local da = self.dustAnim
|
||||
da.frames = da.frames - 1
|
||||
@@ -615,6 +694,14 @@ function OverworldState:update(dt)
|
||||
if da.onDone then da.onDone() end
|
||||
end
|
||||
end
|
||||
if self.cutAnim then
|
||||
local ca = self.cutAnim
|
||||
ca.frames = ca.frames - 1
|
||||
if ca.frames <= 0 then
|
||||
self.cutAnim = nil
|
||||
if ca.onDone then ca.onDone() end
|
||||
end
|
||||
end
|
||||
if self.healAnim then
|
||||
local ha = self.healAnim
|
||||
local Music = require("src.core.Music")
|
||||
@@ -704,6 +791,14 @@ function OverworldState:update(dt)
|
||||
end
|
||||
|
||||
local stepped = self.player:update()
|
||||
-- the warp-arrival cell goes stale the instant the player's real cell
|
||||
-- leaves it, scripted walk-outs included -- pokered re-checks warps
|
||||
-- after simulated steps too (CheckWarpsNoCollision), so a forced
|
||||
-- door-mat exit must not leave the door permanently inert
|
||||
local entry = self.warpEntryCell
|
||||
if entry and (self.player.cellX ~= entry.x or self.player.cellY ~= entry.y) then
|
||||
self.warpEntryCell = nil
|
||||
end
|
||||
if stepped and not scripted then
|
||||
self:onStepComplete()
|
||||
end
|
||||
@@ -1272,6 +1367,14 @@ function OverworldState:tryHiddenObject(fx, fy)
|
||||
end
|
||||
end
|
||||
|
||||
-- Bill's cell-separator PC (data/events/hidden_events.asm: hidden_event
|
||||
-- 1,4 BillsHousePC SPRITE_FACING_UP)
|
||||
if self.map.id == "BILLS_HOUSE" and fx == 1 and fy == 4
|
||||
and self.player.facing == "up" then
|
||||
self:billsHousePC()
|
||||
return true
|
||||
end
|
||||
|
||||
local extras = field.hiddenExtras
|
||||
if not extras then return false end
|
||||
local facing = self.player.facing
|
||||
@@ -1354,7 +1457,18 @@ function OverworldState:tryCardKeyDoor(fx, fy)
|
||||
return true
|
||||
end
|
||||
require("src.core.Sound").play(Game.data, "Go_Inside")
|
||||
self:replaceBlock(math.floor(fx / 2), math.floor(fy / 2), openBlock)
|
||||
local bx, by = math.floor(fx / 2), math.floor(fy / 2)
|
||||
self:replaceBlock(bx, by, openBlock)
|
||||
-- opened doors stay open across reloads (the per-door unlock events
|
||||
-- the floors' gate callbacks check, EVENT_SILPH_CO_n_UNLOCKED_DOOR*)
|
||||
local closedDoors = FieldDefaults.fieldValue(Game.data, "cardKeyDoors",
|
||||
"closedDoors")
|
||||
for _, door in ipairs(closedDoors and closedDoors[self.map.id] or {}) do
|
||||
if door.bx == bx and door.by == by then
|
||||
Game.save.flags[door.event] = true
|
||||
break
|
||||
end
|
||||
end
|
||||
Game.stack:push(TextBox.new(Game,
|
||||
(t._CardKeySuccessText1 or "Bingo!")
|
||||
.. (t._CardKeySuccessText2 or "\nThe CARD KEY\nopened the door!")))
|
||||
@@ -1456,6 +1570,71 @@ function OverworldState:trashCanSwitch(canIndex)
|
||||
end
|
||||
end
|
||||
|
||||
-- Bill's House PC (engine/events/hidden_events/bills_house_pc.asm
|
||||
-- BillsHousePC): once Bill-the-Pokémon has climbed into the machine
|
||||
-- (EVENT_BILL_SAID_USE_CELL_SEPARATOR), running the PC plays the cell
|
||||
-- separator's SFX sequence, sets EVENT_USED_CELL_SEPARATOR_ON_BILL and
|
||||
-- Bill steps back out of the machine human again
|
||||
-- (BillsHouseBillExitsMachineScript / CleanupScript set EVENT_MET_BILL).
|
||||
function OverworldState:billsHousePC()
|
||||
local t = Game.data.text
|
||||
local flags = Game.save.flags
|
||||
if not (flags.EVENT_BILL_SAID_USE_CELL_SEPARATOR
|
||||
and not flags.EVENT_USED_CELL_SEPARATOR_ON_BILL) then
|
||||
Game.stack:push(TextBox.new(Game, t._BillsHouseMonitorText
|
||||
or "TELEPORTER is\ndisplayed on the\nPC monitor."))
|
||||
return
|
||||
end
|
||||
require("src.core.Music").stop()
|
||||
Game.stack:push(TextBox.new(Game, t._BillsHouseInitiatedText
|
||||
or "{PLAYER} initiated\nTELEPORTER's Cell\nSeparator!", function()
|
||||
flags.EVENT_USED_CELL_SEPARATOR_ON_BILL = true
|
||||
require("src.core.Sound").play(Game.data, "Switch")
|
||||
self:queueScript({
|
||||
{ "wait", 32 },
|
||||
{ "play_sound", "Tink" },
|
||||
{ "wait", 80 },
|
||||
{ "play_sound", "Shrink" },
|
||||
{ "wait", 48 },
|
||||
{ "play_sound", "Tink" },
|
||||
{ "wait", 32 },
|
||||
{ "play_sound", "Get_Item1" },
|
||||
{ "wait", 30 },
|
||||
}, { onDone = function() self:billsHouseBillExits() end })
|
||||
end))
|
||||
end
|
||||
|
||||
-- BillsHouseBillExitsMachineScript: human Bill appears inside the machine
|
||||
-- at (1,2) and walks out to his spot at (4,4); the map music resumes and
|
||||
-- EVENT_MET_BILL / EVENT_MET_BILL_2 arm the SS-Ticket dialogue.
|
||||
function OverworldState:billsHouseBillExits()
|
||||
local Commands = require("src.script.Commands")
|
||||
local ctx = { game = Game, save = Game.save, overworld = self }
|
||||
Commands.show_object(ctx, "BILLS_HOUSE", "BILLSHOUSE_BILL1")
|
||||
local function done()
|
||||
Game.save.flags.EVENT_MET_BILL = true
|
||||
Game.save.flags.EVENT_MET_BILL_2 = true
|
||||
require("src.core.Music").playMap(Game.data, self.map.id,
|
||||
Game.save.onBike, self.player.surfing)
|
||||
end
|
||||
local bill
|
||||
for _, n in ipairs(self.npcs) do
|
||||
if n.def and n.def.name == "BILLSHOUSE_BILL1" then bill = n break end
|
||||
end
|
||||
if not (bill and self.map.id == "BILLS_HOUSE") then
|
||||
done()
|
||||
return
|
||||
end
|
||||
bill.cellX, bill.cellY = 1, 2
|
||||
bill.px, bill.py = 16, 32
|
||||
bill.facing = "down"
|
||||
self:scriptMove(bill, "down", 1, function()
|
||||
self:scriptMove(bill, "right", 3, function()
|
||||
self:scriptMove(bill, "down", 1, done)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
-- Any hidden item still unfound NEAR the player? (the ITEMFINDER,
|
||||
-- engine/items/itemfinder.asm HiddenItemNear: coord > clamp0(player-5)
|
||||
-- and coord <= player+4 (Y) / player+5 (X) -- the clamp excludes
|
||||
@@ -1543,8 +1722,10 @@ function OverworldState:tryCut(fx, fy)
|
||||
-- chain-cut "ornamental bushes" around Saffron and Celadon.
|
||||
local ts = self.map.def.tileset
|
||||
local tile = self.map:cellTile(fx, fy)
|
||||
local isGrass = (ts == "OVERWORLD" and tile == 0x52)
|
||||
if not ((ts == "OVERWORLD" and tile == 0x3d)
|
||||
or (ts == "GYM" and tile == 0x50)) then
|
||||
or (ts == "GYM" and tile == 0x50)
|
||||
or isGrass) then
|
||||
return false
|
||||
end
|
||||
local bx, by = math.floor(fx / 2), math.floor(fy / 2)
|
||||
@@ -1553,7 +1734,7 @@ function OverworldState:tryCut(fx, fy)
|
||||
for _, sw in ipairs(Game.data.field.cutTreeSwaps) do
|
||||
if sw.before == block then swap = sw break end
|
||||
end
|
||||
if not swap or self.map:isWalkableCell(fx, fy) then return false end
|
||||
if not swap or (not isGrass and self.map:isWalkableCell(fx, fy)) then return false end
|
||||
local mon = self:partyKnows("CUT")
|
||||
if not mon then return false end
|
||||
-- gen 1 confirms nothing (engine/overworld/cut.asm UsedCut): the
|
||||
@@ -1568,13 +1749,37 @@ function OverworldState:tryCut(fx, fy)
|
||||
{ bx = bx, by = by, block = block })
|
||||
self.map:setBlock(bx, by, swap.after)
|
||||
self.map.renderer:rebuild()
|
||||
self:startDustAnim(fx, fy, function()
|
||||
local finish = function()
|
||||
require("src.core.Sound").play(Game.data, "Cut")
|
||||
end)
|
||||
end
|
||||
if isGrass then
|
||||
-- AnimCut .grass: tall grass gets the leaf-swirl / dust puff, not
|
||||
-- the tree-split slide
|
||||
self:startDustAnim(fx, fy, finish)
|
||||
elseif ts == "OVERWORLD" then
|
||||
-- the tree splits in half and slides apart (AnimCut .cutTreeLoop);
|
||||
-- the GYM plant keeps the shared dust/leaf puff
|
||||
self:startCutTreeAnim(fx, fy, finish)
|
||||
else
|
||||
self:startDustAnim(fx, fy, finish)
|
||||
end
|
||||
end))
|
||||
return true
|
||||
end
|
||||
|
||||
-- The cut-tree split (engine/overworld/cut.asm InitCutAnimOAM +
|
||||
-- engine/overworld/cut2.asm AnimCut): the tree sprite's top half slides
|
||||
-- +1px and its bottom half -1px per frame for 8 frames, flickering,
|
||||
-- before the swapped block shows through. Falls back to the dust puff
|
||||
-- when the extracted tree sprite is unavailable.
|
||||
function OverworldState:startCutTreeAnim(cx, cy, onDone)
|
||||
local fxDef = Game.data.field.overworldFx
|
||||
if not (fxDef and fxDef.cutTree) then
|
||||
return self:startDustAnim(cx, cy, onDone)
|
||||
end
|
||||
self.cutAnim = { x = cx, y = cy, frames = 8, total = 8, onDone = onDone }
|
||||
end
|
||||
|
||||
-- Party-menu SURF entry (start_sub_menus.asm .surf): badge-check SOULBADGE,
|
||||
-- farcall IsSurfingAllowed, then UseItem(SURFBOARD) -> ItemUseSurfboard
|
||||
-- (item_effects.asm), which either tries to dismount (already surfing) or
|
||||
@@ -1637,8 +1842,10 @@ function OverworldState:useCutFieldMove()
|
||||
-- "nothing to cut" in vanilla
|
||||
local ts = self.map.def.tileset
|
||||
local tile = self.map:cellTile(fx, fy)
|
||||
local isGrass = (ts == "OVERWORLD" and tile == 0x52)
|
||||
if not ((ts == "OVERWORLD" and tile == 0x3d)
|
||||
or (ts == "GYM" and tile == 0x50)) then
|
||||
or (ts == "GYM" and tile == 0x50)
|
||||
or isGrass) then
|
||||
return "nothing"
|
||||
end
|
||||
local bx, by = math.floor(fx / 2), math.floor(fy / 2)
|
||||
@@ -1647,7 +1854,7 @@ function OverworldState:useCutFieldMove()
|
||||
for _, sw in ipairs(Game.data.field.cutTreeSwaps) do
|
||||
if sw.before == block then swap = sw break end
|
||||
end
|
||||
if not swap or self.map:isWalkableCell(fx, fy) then return "nothing" end
|
||||
if not swap or (not isGrass and self.map:isWalkableCell(fx, fy)) then return "nothing" end
|
||||
return "ok"
|
||||
end
|
||||
|
||||
@@ -1819,9 +2026,11 @@ function OverworldState:openPC(onDone)
|
||||
end
|
||||
table.insert(items, { label = "LOG OFF", onSelect = logOff })
|
||||
-- pokered sets BIT_NO_MENU_BUTTON_SOUND for the whole PC session
|
||||
-- (engine/overworld/pokecenter_pc.asm / player_pc.asm)
|
||||
-- (engine/overworld/pokecenter_pc.asm / player_pc.asm); DisplayPCMainMenu
|
||||
-- calls TextBoxBorder with c=14 (interior width, +2 for the border), so
|
||||
-- tw here (total width) is 16
|
||||
Game.stack:push(Menu.new(Game, items,
|
||||
{ tx = 0, ty = 0, tw = 14, th = #items * 2 + 2, onCancel = logOff,
|
||||
{ tx = 0, ty = 0, tw = 16, th = #items * 2 + 2, onCancel = logOff,
|
||||
noSound = true }))
|
||||
end
|
||||
|
||||
@@ -2805,6 +3014,25 @@ function OverworldState:takeWarp(warpDef)
|
||||
-- facing carries across the warp (leaving a gate sideways keeps you
|
||||
-- walking sideways; house exit mats are stepped onto facing down)
|
||||
local facing = self.player.facing
|
||||
-- warp pads and fall-through holes are not doors (WarpFound2
|
||||
-- .indoorMaps: IsPlayerStandingOnWarpPadOrHole routes them through
|
||||
-- LeaveMapAnim/EnterMapAnim instead of the door SFX)
|
||||
local pad = self.map.warpPadOrHoleAt
|
||||
and self.map:warpPadOrHoleAt(self.player.cellX, self.player.cellY)
|
||||
if pad == "pad" then
|
||||
-- teleporter: spin out with the exit SFX, spin back in on arrival
|
||||
-- (player_animations.asm _LeaveMapAnim / EnterMapAnim)
|
||||
require("src.core.Sound").play(Game.data, "Teleport_Exit1")
|
||||
self.player.spinning = true
|
||||
self.player.spinTimer = 0
|
||||
self.arriveWarp = "teleport"
|
||||
self:startWarpTo(destMap, x, y, facing)
|
||||
return
|
||||
elseif pad == "hole" then
|
||||
-- falling through a hole: no door SFX, no walk-out step
|
||||
self:startWarpTo(destMap, x, y, facing)
|
||||
return
|
||||
end
|
||||
self.doorWarp = true -- door SFX + outdoor walk-out step
|
||||
self:startWarpTo(destMap, x, y, facing)
|
||||
end
|
||||
@@ -2874,14 +3102,26 @@ function OverworldState:startWarpTo(mapId, x, y, facing, onDone, opts)
|
||||
require("src.core.Sound").play(Game.data, "Teleport_Enter1")
|
||||
-- ENTER_2 caps the spin-down a moment later
|
||||
self.delaySfx = { frames = 40, key = "Teleport_Enter2" }
|
||||
-- the sprite spins down into place (EnterMapAnim
|
||||
-- PlayerSpinWhileMovingDown), not just the SFX
|
||||
self.player.spinning = true
|
||||
self.player.spinTimer = 0
|
||||
self.player.spinFrames = 48
|
||||
self.player.spinTotal = 48
|
||||
self.player.spinDrop = true
|
||||
end
|
||||
if doorWarp then
|
||||
local outdoor = Map.isOutdoor(self.map.def)
|
||||
require("src.core.Sound").play(Game.data,
|
||||
outdoor and "Go_Outside" or "Go_Inside")
|
||||
-- stepping out of an outdoor door mat (the original's walk-out)
|
||||
-- stepping out of an outdoor door/cave entrance (the original's
|
||||
-- walk-out). Auto-walk leaves the mat, so the arrival disable
|
||||
-- (warpEntryCell / justWarped) is unnecessary -- and would let you
|
||||
-- stand on the door without re-entering if you hold back into it.
|
||||
if outdoor and self.player.facing == "down"
|
||||
and self.map:isWarpTileCell(self.player.cellX, self.player.cellY) then
|
||||
self.warpEntryCell = nil
|
||||
self.justWarped = false
|
||||
self:scriptMove(self.player, "down", 1)
|
||||
end
|
||||
end
|
||||
@@ -3120,9 +3360,9 @@ function OverworldState:drawWorld()
|
||||
-- reorder (no draws), so they run once for both paths.
|
||||
local tilt = Tilt.active()
|
||||
self.map.renderer:drawBorderFill(cam.x, bgY, vw, vh)
|
||||
self.map.renderer:draw(cam.x, bgY)
|
||||
self.map.renderer:draw(cam.x, bgY, vw, vh)
|
||||
for _, nb in ipairs(self.neighbors) do
|
||||
nb.map.renderer:drawMapOnly(cam.x - nb.ox, bgY - nb.oy)
|
||||
nb.map.renderer:drawMapOnly(cam.x - nb.ox, bgY - nb.oy, vw, vh)
|
||||
end
|
||||
-- per-billboard SGB palette source; only needed (and only paid for) when
|
||||
-- tilting. nil headless / on stale palettes -> billboards go uncolorized.
|
||||
@@ -3146,7 +3386,7 @@ function OverworldState:drawWorld()
|
||||
-- at (64,64); anchoring those coords to where the player stood keeps
|
||||
-- the overlay on the machine at any zoom.
|
||||
local function fxHeal()
|
||||
if not (self.healAnim and self.healAnim.visible) then return end
|
||||
if not self.healAnim then return end
|
||||
local ha = self.healAnim
|
||||
local fxDef = Game.data.field.overworldFx
|
||||
if self.healMachineImg == nil and fxDef and fxDef.healMachine then
|
||||
@@ -3162,8 +3402,24 @@ function OverworldState:drawWorld()
|
||||
love.graphics.newQuad(0, 8, 8, 8, w, h), -- ball ($7d)
|
||||
}
|
||||
end
|
||||
local ox = ha.px - 64 - cam.x
|
||||
local oy = ha.py - 64 - cam.y
|
||||
-- the jingle flash recolors the machine sprites in place
|
||||
-- (FlashSprite8Times XORs rOBP1; the sprites never disappear):
|
||||
-- ha.visible == false is the flashed half of each beat, drawn with
|
||||
-- the light/dark shades swapped instead of skipped
|
||||
local shader
|
||||
if not ha.visible then
|
||||
shader = PaletteFX.shader()
|
||||
if shader then
|
||||
PaletteFX.sendColors(shader,
|
||||
PaletteFX.permute(PaletteFX.GRAYS, HEAL_FLASH_MAP))
|
||||
love.graphics.setShader(shader)
|
||||
end
|
||||
end
|
||||
-- TileRenderer windows with -floor(cam), so the overlay must use the
|
||||
-- same snap or a fractional camera (odd fill/tilt view sizes) parks
|
||||
-- the balls a pixel off the machine tiles
|
||||
local ox = ha.px - 64 - math.floor(cam.x)
|
||||
local oy = ha.py - 64 - math.floor(cam.y)
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
love.graphics.draw(img, self.healMachineQuads[1], ox + 44, oy + 20)
|
||||
for i = 1, math.min(ha.lit, #HEAL_BALL_XY) do
|
||||
@@ -3176,6 +3432,7 @@ function OverworldState:drawWorld()
|
||||
ox + b[1], oy + b[2])
|
||||
end
|
||||
end
|
||||
if shader then love.graphics.setShader() end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -3206,6 +3463,37 @@ function OverworldState:drawWorld()
|
||||
end
|
||||
end
|
||||
|
||||
-- the cut tree splitting apart (AnimCut): top half slides right,
|
||||
-- bottom half slides left, 1px per frame, flickering as they go
|
||||
local function fxCutTree()
|
||||
if not self.cutAnim then return end
|
||||
local fxDef = Game.data.field.overworldFx
|
||||
local tree = fxDef and fxDef.cutTree
|
||||
if not tree then return end
|
||||
if self.cutTreeImg == nil then
|
||||
local ok, img = pcall(love.graphics.newImage, tree.path)
|
||||
self.cutTreeImg = ok and img or false
|
||||
end
|
||||
local img = self.cutTreeImg
|
||||
if not img then return end
|
||||
if not self.cutTreeQuads then
|
||||
local w, h = img:getWidth(), img:getHeight()
|
||||
self.cutTreeQuads = {
|
||||
love.graphics.newQuad(0, 0, 16, 8, w, h), -- top half
|
||||
love.graphics.newQuad(0, 8, 16, 8, w, h), -- bottom half
|
||||
}
|
||||
end
|
||||
local ca = self.cutAnim
|
||||
local off = (ca.total or 8) - ca.frames
|
||||
local dx = ca.x * 16 - cam.x
|
||||
local dy = ca.y * 16 - cam.y
|
||||
local flicker = ca.frames % 2 == 0
|
||||
love.graphics.setColor(1, 1, 1, flicker and 1 or 0.55)
|
||||
love.graphics.draw(img, self.cutTreeQuads[1], dx + off, dy)
|
||||
love.graphics.draw(img, self.cutTreeQuads[2], dx - off, dy + 8)
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
end
|
||||
|
||||
-- the "!" bubble above a trainer who spotted the player
|
||||
local function fxEmote()
|
||||
if not (self.emote and self.emote.npc) then return end
|
||||
@@ -3221,11 +3509,21 @@ function OverworldState:drawWorld()
|
||||
end)
|
||||
-- EXCLAMATION_BUBBLE is index 0 -> first crop; the emote command
|
||||
-- picks question/happy crops instead
|
||||
local rect = bubble.bubbles and bubble.bubbles[self.emote.bubble or 1]
|
||||
local bi = self.emote.bubble or 1
|
||||
local rect = bubble.bubbles and bubble.bubbles[bi]
|
||||
if ok and img and rect then
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
love.graphics.draw(img, love.graphics.newQuad(rect.x, rect.y,
|
||||
rect.w, rect.h, img:getDimensions()), ex, ey)
|
||||
-- one Quad per bubble crop, cached: this draws every frame the "!"
|
||||
-- (or the emote-command crops) is up, so a fresh Quad here churned
|
||||
-- the GC. The bubble set is small and fixed, so the cache is bounded.
|
||||
self.emoteQuads = self.emoteQuads or {}
|
||||
local q = self.emoteQuads[bi]
|
||||
if not q then
|
||||
q = love.graphics.newQuad(rect.x, rect.y, rect.w, rect.h,
|
||||
img:getDimensions())
|
||||
self.emoteQuads[bi] = q
|
||||
end
|
||||
love.graphics.draw(img, q, ex, ey)
|
||||
drawn = true
|
||||
end
|
||||
end
|
||||
@@ -3297,6 +3595,11 @@ function OverworldState:drawWorld()
|
||||
|
||||
if not tilt then
|
||||
-- === FLAT PATH: everything into the one world canvas, as before =====
|
||||
-- OBP-baked sprites replay after the zone pass in GBC mode, so their
|
||||
-- grass feet-overdraw must replay over them too, colorized with the
|
||||
-- current map's palette (see PaletteFX.markSpriteRedraw)
|
||||
local grassColors = PaletteFX.usesSpriteObp()
|
||||
and PaletteFX.pal(Game.data, self:paletteNameFor(self.map)) or nil
|
||||
for _, g in ipairs(self.ghosts) do
|
||||
g.npc:draw(cam.x - g.ox, cam.y - g.oy)
|
||||
end
|
||||
@@ -3308,14 +3611,23 @@ function OverworldState:drawWorld()
|
||||
love.graphics.setColor(1, 1, 1, 1)
|
||||
if self.map:isGrassCell(e.cellX, e.cellY) then
|
||||
self.map.renderer:drawCellBottom(e.cellX, e.cellY, cam.x, bgY)
|
||||
if grassColors then
|
||||
self.map.renderer:markCellBottomRedraw(e.cellX, e.cellY,
|
||||
cam.x, bgY, grassColors)
|
||||
end
|
||||
end
|
||||
if e.targetX and self.map:isGrassCell(e.targetX, e.targetY) then
|
||||
self.map.renderer:drawCellBottom(e.targetX, e.targetY, cam.x, bgY)
|
||||
if grassColors then
|
||||
self.map.renderer:markCellBottomRedraw(e.targetX, e.targetY,
|
||||
cam.x, bgY, grassColors)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
fxHeal()
|
||||
fxDust()
|
||||
fxCutTree()
|
||||
fxEmote()
|
||||
fxDark()
|
||||
fxBird()
|
||||
@@ -3323,12 +3635,15 @@ function OverworldState:drawWorld()
|
||||
else
|
||||
-- === TILT PATH: ground-hugging FX stay on the projected ground, all
|
||||
-- standing things billboard upright over it in a separate pass. ======
|
||||
-- Dust is ground-hugging smoke -> ground canvas (puts it
|
||||
-- with the flat layer, so it projects with the ground). Flat mode
|
||||
-- draws it last, over the sprites, in the same canvas; here the two
|
||||
-- Dust / cut / the Poké Center heal overlay hug the BG (the heal
|
||||
-- machine is a tileset graphic; its OAM balls must ride that plane or
|
||||
-- they float off the machine once the ground foreshortens). Flat mode
|
||||
-- draws them last, over the sprites, in the same canvas; here the two
|
||||
-- layers are separate and composited ground-under-upright, so drawing
|
||||
-- it now into the still-active ground canvas is order-equivalent.
|
||||
-- them now into the still-active ground canvas is order-equivalent.
|
||||
fxHeal()
|
||||
fxDust()
|
||||
fxCutTree()
|
||||
|
||||
Game.renderer:beginUprightPass()
|
||||
|
||||
@@ -3382,18 +3697,11 @@ function OverworldState:drawWorld()
|
||||
end
|
||||
end
|
||||
|
||||
-- Screen-anchored world FX : each billboards at the
|
||||
-- ground foot of the character it belongs to, so it stands upright and
|
||||
-- scales with that character's depth.
|
||||
-- heal machine -> the healed player's foot (the machine stands on
|
||||
-- the ground in front of where the player was)
|
||||
-- Standing world FX: each billboards at the ground foot of the
|
||||
-- character it belongs to, so it stays upright over the tilted ground.
|
||||
-- emote bubble -> the spotting NPC's foot (rides above its head)
|
||||
-- fly bird, rod -> the player's foot
|
||||
if self.healAnim and self.healAnim.visible then
|
||||
local fx = self.healAnim.px - cam.x + 8
|
||||
local fy = self.healAnim.py - cam.y + 16
|
||||
self:billboard(fx, fy, vw, vh, zoneColorsAt(zones, fx, fy), false, fxHeal)
|
||||
end
|
||||
-- (heal machine is ground-hugging -- drawn above with dust/cut)
|
||||
if self.emote and self.emote.npc then
|
||||
local fx = self.emote.npc.px - cam.x + 8
|
||||
local fy = self.emote.npc.py - cam.y + 16
|
||||
|
||||
+29
-6
@@ -84,9 +84,21 @@ function Player:update()
|
||||
if self.turnTimer > 0 then
|
||||
self.turnTimer = self.turnTimer - 1
|
||||
end
|
||||
if self.spinFrames then
|
||||
self.spinFrames = self.spinFrames - 1
|
||||
if self.spinFrames <= 0 then
|
||||
self.spinFrames = nil
|
||||
self.spinDrop = nil
|
||||
self.spinning = false
|
||||
end
|
||||
end
|
||||
if not self.moving then return false end
|
||||
local stepLen = self.stepFramesCur or self.stepFrames or STEP_FRAMES
|
||||
self.progress = self.progress + 1
|
||||
-- the walk-cycle clock ticks once per real frame while moving, so the
|
||||
-- leg cadence stays constant when the bike halves stepFramesCur (only
|
||||
-- translation speed doubles, like UpdatePlayerSprite's frame counters)
|
||||
self.animClock = (self.animClock or 0) + 1
|
||||
local d = Collision.DELTA[self.facing]
|
||||
local px = math.floor(self.progress * 16 / stepLen)
|
||||
self.px = self.cellX * 16 + d[1] * px
|
||||
@@ -108,8 +120,8 @@ end
|
||||
|
||||
function Player:walkPhase()
|
||||
if not self.moving then return 0 end
|
||||
-- walk frame during the middle of the step
|
||||
local p = self.progress % 16
|
||||
-- walk frame during the middle of each 16-frame animation cycle
|
||||
local p = (self.animClock or self.progress) % 16
|
||||
return (p >= 4 and p < 12) and 1 or 0
|
||||
end
|
||||
|
||||
@@ -139,15 +151,26 @@ function Player:draw(camX, camY)
|
||||
py = py + (self.bobTimer < 16 and 0 or 1)
|
||||
end
|
||||
local facing = self.facing
|
||||
local phase = self:walkPhase()
|
||||
-- alternate walk cycles mirror the up/down frame; derived from the
|
||||
-- fixed-rate animation clock so the bike's shorter steps don't double
|
||||
-- the leg cadence
|
||||
local flip = math.floor((self.animClock or 0) / 16) % 2 == 1
|
||||
if self.spinning then
|
||||
-- spinner tiles whirl the sprite (PlayerSpinningFacingOrder)
|
||||
-- spinner tiles whirl the sprite on its standing pose, one facing
|
||||
-- per frame (LoadSpinnerArrowTiles runs every OverworldLoop frame)
|
||||
self.spinTimer = (self.spinTimer or 0) + 1
|
||||
facing = SPIN_ORDER[math.floor(self.spinTimer / 4) % 4 + 1]
|
||||
facing = SPIN_ORDER[self.spinTimer % 4 + 1]
|
||||
phase, flip = 0, false
|
||||
-- teleport arrivals spin the sprite down into place
|
||||
-- (EnterMapAnim PlayerSpinWhileMovingDown)
|
||||
if self.spinFrames and self.spinDrop then
|
||||
py = py - math.floor(self.spinFrames * 24 / (self.spinTotal or 64))
|
||||
end
|
||||
end
|
||||
local sprite = (self.surfing and self.surfSprite)
|
||||
or (self.onBike and self.bikeSprite) or self.sprite
|
||||
sprite:draw(self.px, py, camX, camY, facing,
|
||||
self:walkPhase(), self.stepFlip)
|
||||
sprite:draw(self.px, py, camX, camY, facing, phase, flip)
|
||||
end
|
||||
|
||||
return Player
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
-- Driver: the Hall of Fame recording-machine "PC". Teleports into the
|
||||
-- HALL_OF_FAME room, faces the console jutting from the north wall, and
|
||||
-- exercises the injected TEXT_HALLOFFAME_PC sign both ways: NO leaves the
|
||||
-- player in the room, YES warps home to the new-game bedroom spawn
|
||||
-- (REDS_HOUSE_2F, 3, 6). Screenshots the prompt and the arrival.
|
||||
|
||||
return function(game)
|
||||
local U = dofile("tests/drivers/util.lua")
|
||||
local DIR = os.getenv("SHOT_DIR") or "/tmp/shots"
|
||||
local TextBox = require("src.render.TextBox")
|
||||
local ChoiceBox = require("src.ui.ChoiceBox")
|
||||
|
||||
local pass = true
|
||||
local function check(cond, msg)
|
||||
if cond then U.log("PASS: " .. msg) else pass = false; U.log("FAIL: " .. msg) end
|
||||
end
|
||||
local function topIs(mt) return getmetatable(game.stack:top()) == mt end
|
||||
|
||||
-- press A to advance the ask text until the YES/NO box is on top
|
||||
local function openChoice()
|
||||
for _ = 1, 120 do
|
||||
if topIs(ChoiceBox) then return true end
|
||||
if topIs(TextBox) then U.tap(game, "a") end
|
||||
U.wait(3)
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- stand at (4,2) facing up: the console solid cell (4,1) is dead ahead
|
||||
U.teleport(game, "HALL_OF_FAME", 4, 2, "up")
|
||||
local ow = game.overworld
|
||||
local fx, fy = ow.player:facingCell()
|
||||
U.log(("at (%d,%d) facing %s -> facing cell (%d,%d)"):format(
|
||||
ow.player.cellX, ow.player.cellY, ow.player.facing, fx, fy))
|
||||
check(ow.map:signAtCell(fx, fy) ~= nil, "a sign sits on the console tile")
|
||||
|
||||
-- ---- NO: prompt appears, player stays in the Hall of Fame ----
|
||||
U.tap(game, "a") -- interact -> ask
|
||||
U.wait(4)
|
||||
check(openChoice(), "NO run: YES/NO prompt opened")
|
||||
U.shot(game, DIR .. "/hof_pc_1_prompt.png")
|
||||
U.tap(game, "down") -- cursor YES -> NO
|
||||
U.wait(2)
|
||||
U.tap(game, "a") -- confirm NO
|
||||
U.wait(20)
|
||||
check(ow.map.id == "HALL_OF_FAME", "NO keeps the player in HALL_OF_FAME")
|
||||
|
||||
-- ---- YES: warp back to the bedroom spawn ----
|
||||
U.teleport(game, "HALL_OF_FAME", 4, 2, "up")
|
||||
ow = game.overworld
|
||||
U.tap(game, "a")
|
||||
U.wait(4)
|
||||
check(openChoice(), "YES run: YES/NO prompt opened")
|
||||
U.tap(game, "a") -- YES (default cursor)
|
||||
local warped = false
|
||||
for _ = 1, 300 do
|
||||
if ow.map.id == "REDS_HOUSE_2F" and not ow.transitioning then warped = true; break end
|
||||
U.wait(2)
|
||||
end
|
||||
U.log(("after YES: map=%s pos=(%d,%d) facing=%s"):format(
|
||||
ow.map.id, ow.player.cellX, ow.player.cellY, ow.player.facing))
|
||||
U.wait(10)
|
||||
U.shot(game, DIR .. "/hof_pc_2_home.png")
|
||||
check(warped, "YES warps to REDS_HOUSE_2F")
|
||||
check(ow.player.cellX == 3 and ow.player.cellY == 6,
|
||||
"landed on the bedroom spawn (3,6)")
|
||||
|
||||
U.log(pass and "RESULT: ALL PASS" or "RESULT: SEE FAILURES ABOVE")
|
||||
end
|
||||
@@ -0,0 +1,48 @@
|
||||
-- Visual test: SQUIRTLE (player) vs BULBASAUR (enemy) in OG RED, to match
|
||||
-- the Game Boy Color hardware capture. Run with a display:
|
||||
--
|
||||
-- SHOT_DIR=/tmp/ogred POKEPORT_IDENTITY=pokeport-ogred-shot \
|
||||
-- POKEPORT_DRIVER=tests/drivers/ogred_battle_test.lua love .
|
||||
--
|
||||
-- Captures ogred_0{1..5}_*.png into SHOT_DIR. OG RED is a global palette:
|
||||
-- red BG (terrain, mon pics, HUD, text) + green OBJ (overworld characters,
|
||||
-- battle effects). Battle mon pics are BG tiles, so they come out red/pink
|
||||
-- on the near-white field -- see PaletteFX.GBC_BG / monPal.
|
||||
return function(game)
|
||||
local U = dofile("tests/drivers/util.lua")
|
||||
local DIR = os.getenv("SHOT_DIR") or "."
|
||||
local PaletteFX = require("src.render.PaletteFX")
|
||||
|
||||
-- Set the SAVED option, not just the live mode: Game:applyOptions re-reads
|
||||
-- save.options.colors, so a bare setMode would get reverted to the default.
|
||||
game.save.options = game.save.options or {}
|
||||
game.save.options.colors = "ogred"
|
||||
PaletteFX.setMode("ogred")
|
||||
|
||||
local Pokemon = require("src.pokemon.Pokemon")
|
||||
game.save.party = { Pokemon.new(game.data, "SQUIRTLE", 5) }
|
||||
|
||||
U.teleport(game, "ROUTE_1", 5, 5, "down")
|
||||
local ow = game.overworld
|
||||
|
||||
local BattleState = require("src.battle.BattleState")
|
||||
local battle = BattleState.newWild(game, "BULBASAUR", 5)
|
||||
battle.onFinish = function() end
|
||||
ow:pushBattle(battle)
|
||||
|
||||
U.wait(220)
|
||||
U.shot(game, DIR .. "/ogred_01_intro.png")
|
||||
|
||||
for _ = 1, 24 do U.tap(game, "a"); U.wait(6) end
|
||||
U.shot(game, DIR .. "/ogred_02_menu.png")
|
||||
|
||||
U.tap(game, "a"); U.wait(12) -- FIGHT -> move list
|
||||
U.shot(game, DIR .. "/ogred_03_moves.png")
|
||||
|
||||
U.tap(game, "down"); U.wait(6) -- TACKLE -> TAIL WHIP
|
||||
U.tap(game, "a"); U.wait(30)
|
||||
U.shot(game, DIR .. "/ogred_04_tailwhip.png")
|
||||
U.wait(40)
|
||||
U.shot(game, DIR .. "/ogred_05_after.png")
|
||||
U.wait(4)
|
||||
end
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Same-frame press→release and multi-source hold regressions for Input.lua.
|
||||
-- Self-contained: `luajit tests/input_hold_test.lua`; also dofile'd by
|
||||
-- tests/run_tests.lua.
|
||||
package.path = "./?.lua;./?/init.lua;" .. package.path
|
||||
if not _G.love then _G.love = require("tests.love_stub") end
|
||||
|
||||
local S = require("tests.harness").suite("input hold")
|
||||
local check = S.check
|
||||
local Input = require("src.core.Input")
|
||||
|
||||
Input:init()
|
||||
|
||||
-- Quick tap before the next FixedStep must edge-fire without leaving isDown.
|
||||
Input:keypressed("up")
|
||||
Input:keyreleased("up")
|
||||
Input:step()
|
||||
check(Input:wasPressed("up"), "same-frame tap still edges wasPressed")
|
||||
check(not Input:isDown("up"), "same-frame tap does not stick isDown")
|
||||
|
||||
Input:reset()
|
||||
Input:keypressed("up")
|
||||
Input:step()
|
||||
check(Input:wasPressed("up"), "held press edges wasPressed")
|
||||
check(Input:isDown("up"), "held press keeps isDown across step")
|
||||
Input:step()
|
||||
check(not Input:wasPressed("up"), "hold does not re-edge next step")
|
||||
check(Input:isDown("up"), "hold stays down next step")
|
||||
Input:keyreleased("up")
|
||||
check(not Input:isDown("up"), "release clears isDown")
|
||||
|
||||
-- W and Up both map to up; releasing one must not drop the other.
|
||||
Input:reset()
|
||||
Input:keypressed("w")
|
||||
Input:keypressed("up")
|
||||
Input:step()
|
||||
Input:keyreleased("w")
|
||||
check(Input:isDown("up"), "second source keeps up held after first release")
|
||||
Input:keyreleased("up")
|
||||
check(not Input:isDown("up"), "last source release clears up")
|
||||
|
||||
-- Stick flick on→off before step must not stick.
|
||||
Input:reset()
|
||||
Input:gamepadaxis(nil, "leftx", -0.9)
|
||||
Input:gamepadaxis(nil, "leftx", 0)
|
||||
Input:step()
|
||||
check(Input:wasPressed("left"), "stick flick edges wasPressed")
|
||||
check(not Input:isDown("left"), "stick flick does not stick isDown")
|
||||
|
||||
-- Drivers that only inject pressQueue still get a one-step hold.
|
||||
Input:reset()
|
||||
table.insert(Input.pressQueue, "down")
|
||||
Input:step()
|
||||
check(Input:wasPressed("down"), "synthetic pressQueue edges wasPressed")
|
||||
check(Input:isDown("down"), "synthetic pressQueue sets isDown")
|
||||
|
||||
S.finish()
|
||||
@@ -40,6 +40,8 @@ stub.graphics = {
|
||||
newSpriteBatch = function(image, size)
|
||||
local batch = { image = image, sprites = {} }
|
||||
function batch:add(quad, x, y) table.insert(self.sprites, { quad, x, y }) end
|
||||
function batch:clear() self.sprites = {} end
|
||||
function batch:setTexture(tex) self.texture = tex end
|
||||
return batch
|
||||
end,
|
||||
draw = noop, rectangle = noop, setColor = noop, clear = noop,
|
||||
|
||||
@@ -344,6 +344,24 @@ check(lastSource().queueable and lastSource().playing,
|
||||
"a chip song still plays after a file song")
|
||||
check(not body.playing, "the outgoing file song was stopped")
|
||||
|
||||
-- playOnce must survive the threaded "empty QueueableSource" window:
|
||||
-- Source:isPlaying is false until the first worker buffer lands, and that
|
||||
-- gap must not look like the jingle already ended (Poké Center heal).
|
||||
data = reset(fixtureData())
|
||||
Music.playMap(data, "PALLET_TOWN", false, false)
|
||||
check(Music.playOnce(data, "Music_Chip"), "playOnce starts a chip jingle")
|
||||
local jingle = lastSource()
|
||||
local clearAwait = ChipAudio._simulateAwaitingFirstBufferForTest()
|
||||
check(clearAwait ~= nil, "test can force the awaiting-first-buffer window")
|
||||
check(Music.oneShotPlaying(),
|
||||
"oneShotPlaying stays true while the first buffer is still in flight")
|
||||
Music.update(data)
|
||||
check(jingle == lastSource() and jingle.queueable,
|
||||
"pendingRestore does not swap the map theme over a pending chip jingle")
|
||||
check(ChipAudio.awaitingFirstBuffer(),
|
||||
"awaitingFirstBuffer reports the forced window")
|
||||
clearAwait()
|
||||
|
||||
-- sfx shape dispatch
|
||||
check(Sound.play(data, "Beep") == nil, "Sound.play returns nothing")
|
||||
check(lastSource().file == "assets/beep.wav", "a bare string sfx is a static source")
|
||||
|
||||
@@ -113,6 +113,7 @@ love.graphics = {
|
||||
newSpriteBatch = function(image, size)
|
||||
local batch = { image = image, sprites = {} }
|
||||
function batch:add(quad, x, y) table.insert(self.sprites, { quad, x, y }) end
|
||||
function batch:clear() self.sprites = {} end
|
||||
function batch:setTexture(tex) self.texture = tex end
|
||||
return batch
|
||||
end,
|
||||
@@ -287,6 +288,8 @@ local renderer = TileRenderer.new(map)
|
||||
check(#renderer.anims == 1, "a declared animatedTiles entry builds one anim")
|
||||
check(renderer.anims[1].period == 12, "the declared period is honored")
|
||||
check(#renderer.anims[1].textures == 3, "the declared frame images load")
|
||||
-- the camera-window fill gathers the on-screen animated cells into anims[].batch
|
||||
renderer:draw(0, 0)
|
||||
check(renderer.anims[1].batch ~= nil, "the animated tile collected cells")
|
||||
|
||||
-- the vanilla water cycle, driven through the same data path: eight
|
||||
@@ -307,6 +310,8 @@ local sea = TileRenderer.new({
|
||||
check(#sea.anims == 1, "an OVERWORLD tileset animates its water with no record edit")
|
||||
check(#sea.anims[1].textures == 8, "the water entry builds 8 shifted variants")
|
||||
|
||||
-- fill the camera window so the water cells are gathered into the batch
|
||||
sea:draw(0, 0)
|
||||
local seen = {}
|
||||
for step = 1, 8 do
|
||||
sea:drawAnimated(0, 0)
|
||||
|
||||
@@ -196,6 +196,7 @@ do
|
||||
check(#loaded.meta.mods == 0, "old vanilla save records an empty mod set")
|
||||
check(loaded.boxes and loaded.boxes[1][1].species == "PIDGEY", "box list folded into boxes[1]")
|
||||
check(loaded.box == nil, "legacy box key gone")
|
||||
check(loaded.version == "red", "untagged save defaults to the Red version")
|
||||
local opts = SaveSerializer.decode(files["options.lua"])
|
||||
check(opts and opts.musicVol == 2, "embedded options split into options.lua")
|
||||
|
||||
@@ -203,7 +204,16 @@ do
|
||||
local current = { meta = { format = Version.saveFormat, mods = {} },
|
||||
player = { map = "PALLET_TOWN", x = 1, y = 1 } }
|
||||
SaveData.runMigrations(current)
|
||||
check(current.player.id == nil, "format-2 save skips the id backfill")
|
||||
check(current.player.id == nil, "current-format save skips the id backfill")
|
||||
|
||||
-- a format-2 save (Blue support not yet shipped) gains the Red tag;
|
||||
-- a save that already names a version keeps it
|
||||
local untagged = { meta = { format = 2, mods = {} }, player = {} }
|
||||
SaveData.runMigrations(untagged)
|
||||
check(untagged.version == "red", "pre-version save defaults to Red")
|
||||
local tagged = { meta = { format = 2, mods = {} }, version = "blue", player = {} }
|
||||
SaveData.runMigrations(tagged)
|
||||
check(tagged.version == "blue", "an existing version tag is left untouched")
|
||||
|
||||
love.filesystem = realFS
|
||||
end
|
||||
|
||||
+41
-3
@@ -22,6 +22,7 @@ local StateStack = require("src.core.StateStack")
|
||||
local ManagerState = require("src.mods.ManagerState")
|
||||
local ModUI = require("src.ui.ModUI")
|
||||
local Theme = require("src.ui.Theme")
|
||||
local FrameCap = require("src.core.FrameCap")
|
||||
|
||||
local savedEvents, savedHooks, savedErrors =
|
||||
Runtime.events, Runtime.hooks, Runtime.errors
|
||||
@@ -205,7 +206,7 @@ end
|
||||
local om = OptionsMenu.new(optGame())
|
||||
local WANT_IDS = { "textSpeed", "animations", "battleStyle", "ruleset",
|
||||
"musicVol", "sfxVol", "musicFilter", "colors", "tilt",
|
||||
"gbcfx", "videoMode", "speed", "mods", "controls" }
|
||||
"gbcfx", "videoMode", "fpsCap", "speed", "mods", "controls" }
|
||||
check(#om.rows == #WANT_IDS, "vanilla options row count (plus MODS/CONTROLS)")
|
||||
for i, id in ipairs(WANT_IDS) do
|
||||
check(om.rows[i].id == id, "options row order: " .. id)
|
||||
@@ -235,10 +236,47 @@ check(om.game.save.options.musicVol == 6, "music volume steps down")
|
||||
for _ = 1, 10 do om.rows[5].step(om.game, -1) end
|
||||
check(om.game.save.options.musicVol == 0, "music volume clamps at 0")
|
||||
|
||||
-- the MAX FPS row cycles the render-cap steps and shows the value plain
|
||||
om.game.save.options.fpsCap = nil
|
||||
check(om.rows[12].value(om.game) == "60",
|
||||
"MAX FPS row defaults to 60 with no saved cap")
|
||||
om.rows[12].step(om.game, 1)
|
||||
check(om.game.save.options.fpsCap == 75, "MAX FPS steps up from 60 to 75")
|
||||
check(om.rows[12].value(om.game) == "75", "the MAX FPS row renders the cap")
|
||||
om.game.save.options.fpsCap = 160
|
||||
om.rows[12].step(om.game, 1)
|
||||
check(om.game.save.options.fpsCap == 30, "MAX FPS wraps past the ceiling to 30")
|
||||
om.rows[12].step(om.game, -1)
|
||||
check(om.game.save.options.fpsCap == 160, "MAX FPS wraps back down to the ceiling")
|
||||
|
||||
-- ------- FrameCap normalize / cycle (issue #88)
|
||||
check(FrameCap.normalize(nil) == 60, "FrameCap defaults nil to 60")
|
||||
check(FrameCap.normalize("junk") == 60, "FrameCap defaults garbage to 60")
|
||||
check(FrameCap.normalize(60) == 60, "FrameCap keeps an exact step")
|
||||
check(FrameCap.normalize(58) == 60, "FrameCap snaps 58 to the nearest step 60")
|
||||
check(FrameCap.normalize(72) == 75, "FrameCap snaps 72 to the nearest step 75")
|
||||
check(FrameCap.normalize(0) == 30, "FrameCap clamps below the floor to 30")
|
||||
check(FrameCap.normalize(9999) == 160, "FrameCap clamps above the ceiling to 160")
|
||||
check(FrameCap.normalize(30) == 30 and FrameCap.normalize(160) == 160,
|
||||
"FrameCap keeps the exact floor and ceiling")
|
||||
check(FrameCap.label(nil) == "60" and FrameCap.label(144) == "144",
|
||||
"FrameCap.label renders the normalized cap as plain text")
|
||||
check(FrameCap.cycle(60, 1) == 75, "FrameCap cycles 60 up to 75")
|
||||
check(FrameCap.cycle(60, -1) == 50, "FrameCap cycles 60 down to 50")
|
||||
check(FrameCap.cycle(160, 1) == 30, "FrameCap cycle wraps the ceiling to the floor")
|
||||
check(FrameCap.cycle(30, -1) == 160, "FrameCap cycle wraps the floor to the ceiling")
|
||||
check(FrameCap.cycle(nil, 1) == 75,
|
||||
"FrameCap cycle normalizes a nil cap (60) before stepping")
|
||||
-- apply drives the live value the run loop paces to; never touches love.timer
|
||||
FrameCap.apply(144)
|
||||
check(FrameCap.current == 144, "FrameCap.apply stores the live cap")
|
||||
FrameCap.applyOptions({})
|
||||
check(FrameCap.current == 60, "FrameCap.applyOptions defaults a missing key to 60")
|
||||
|
||||
-- the MODS row is the manager's discoverable home
|
||||
local mgGame = optGame()
|
||||
om = OptionsMenu.new(mgGame)
|
||||
om.rows[13].activate(mgGame)
|
||||
om.rows[14].activate(mgGame)
|
||||
check(getmetatable(mgGame.stack:top()) == ManagerState,
|
||||
"the MODS row opens the manager")
|
||||
check(mgGame.stack:top().screenId == "ManagerState",
|
||||
@@ -248,7 +286,7 @@ check(mgGame.stack:top().screenId == "ManagerState",
|
||||
local BindingsMenu = require("src.ui.BindingsMenu")
|
||||
local cbGame = optGame()
|
||||
om = OptionsMenu.new(cbGame)
|
||||
om.rows[14].activate(cbGame)
|
||||
om.rows[15].activate(cbGame)
|
||||
local bm = cbGame.stack:top()
|
||||
check(getmetatable(bm) == BindingsMenu,
|
||||
"the CONTROLS row opens the rebind list")
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
-- Parity: losing the Oak's Lab starter rival must not black out.
|
||||
-- pret HandlePlayerBlackOut special-cases OPP_RIVAL1 on OAKS_LAB:
|
||||
-- Rival1WinText only, no PlayerBlackedOutText, no warp / half-money.
|
||||
-- OaksLabRivalEndBattleScript then HealParty and continues either way.
|
||||
-- Self-contained; run via `luajit tests/parity_oaks_lab_rival_loss.lua`.
|
||||
package.path = "./?.lua;./?/init.lua;" .. package.path
|
||||
if not _G.love then _G.love = require("tests.love_stub") end
|
||||
local BattleState = require("src.battle.BattleState")
|
||||
local S = require("tests.harness").suite("parity oaks lab rival loss")
|
||||
local check, eq = S.check, S.eq
|
||||
|
||||
local function saidBlackout(b)
|
||||
for _, m in ipairs(b.said) do
|
||||
if tostring(m):find("blacked") then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function saidRivalTaunt(b)
|
||||
for _, m in ipairs(b.said) do
|
||||
if tostring(m):find("great or what") then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function rivalBattle(mapId)
|
||||
return {
|
||||
kind = "trainer",
|
||||
oppClass = "OPP_RIVAL1",
|
||||
result = nil,
|
||||
afterQueue = nil,
|
||||
said = {},
|
||||
data = {
|
||||
text = { _Rival1WinText = "{RIVAL}: Yeah! Am\nI great or what?" },
|
||||
},
|
||||
game = {
|
||||
save = {
|
||||
party = { { species = "SQUIRTLE", hp = 0, stats = { hp = 20 } } },
|
||||
player = { name = "RED", rival = "BLUE", map = mapId },
|
||||
},
|
||||
overworld = { map = { id = mapId } },
|
||||
},
|
||||
sayNext = function(self, m) self.said[#self.said + 1] = m end,
|
||||
say = function(self, m) self.said[#self.said + 1] = m end,
|
||||
}
|
||||
end
|
||||
|
||||
do
|
||||
local b = rivalBattle("OAKS_LAB")
|
||||
BattleState.playerMonFainted(b)
|
||||
eq(b.result, "lose", "lab rival wipe is still a loss")
|
||||
check(saidRivalTaunt(b), "lab rival wipe shows Rival1WinText")
|
||||
check(not saidBlackout(b), "lab rival wipe does not say blacked out")
|
||||
check(BattleState.isOaksLabStarterRival(b), "oaks-lab starter-rival detector")
|
||||
end
|
||||
|
||||
do
|
||||
local b = rivalBattle("ROUTE_22")
|
||||
BattleState.playerMonFainted(b)
|
||||
eq(b.result, "lose", "route-22 rival wipe is a loss")
|
||||
check(saidRivalTaunt(b), "route-22 rival still shows Rival1WinText")
|
||||
check(saidBlackout(b), "route-22 rival still blacks out")
|
||||
check(not BattleState.isOaksLabStarterRival(b),
|
||||
"route-22 is not the oaks-lab special case")
|
||||
end
|
||||
|
||||
S.finish()
|
||||
@@ -1,190 +0,0 @@
|
||||
-- Parity test, Viridian City's two old men + the Pokédex object swap.
|
||||
--
|
||||
-- pokered has TWO old men on this map (data/maps/objects/ViridianCity.asm):
|
||||
--
|
||||
-- object_event 18, 9, SPRITE_GAMBLER_ASLEEP, STAY, NONE, ..._OLD_MAN_SLEEPY
|
||||
-- object_event 17, 5, SPRITE_GAMBLER, WALK, LEFT_RIGHT, ..._OLD_MAN
|
||||
--
|
||||
-- The sleeper only ever grumbles "private property" and shoves you back
|
||||
-- down; he never wakes, moves or hides. The coffee ask and the catch
|
||||
-- tutorial belong to the walking man, who starts OFF
|
||||
-- (data/maps/toggleable_objects.asm) and is swapped in for the sleeper
|
||||
-- when Oak hands over the Pokédex (scripts/OaksLab.asm:602-606). The
|
||||
-- north corridor is gated on EVENT_GOT_POKEDEX at exactly (19,9)
|
||||
-- (ViridianCityCheckGotPokedexScript), not on either man's visibility.
|
||||
--
|
||||
-- All three of those were wrong at once: the port merged both men into
|
||||
-- the sleeper, never ran the swap (so the walking man stayed hidden for
|
||||
-- the entire game), and gated the corridor on the sleeper being hidden --
|
||||
-- which made talking to him and answering "yes, I'm in a hurry" the only
|
||||
-- way out of Viridian. Self-contained; run via `luajit tests/parity_viridian.lua`.
|
||||
package.path = "./?.lua;./?/init.lua;" .. package.path
|
||||
if not _G.love then _G.love = require("tests.love_stub") end
|
||||
local Data = require("src.core.Data")
|
||||
if not (Data.maps and Data.maps.VIRIDIAN_CITY) then Data:load() end
|
||||
-- The gate builds a real TextBox, which wants a loaded Font atlas we have
|
||||
-- no graphics device for. The hook requires it lazily, so a stub in
|
||||
-- package.loaded is enough to exercise the branch headlessly -- we only
|
||||
-- care that the step was blocked and that a box was pushed, not what it
|
||||
-- rendered (parity_flavor already covers the text labels themselves).
|
||||
package.loaded["src.render.TextBox"] = {
|
||||
new = function(_, text, onDone) return { text = text, onDone = onDone } end,
|
||||
}
|
||||
local init = require("data.scripts.init")
|
||||
local S = require("tests.harness").suite("parity viridian")
|
||||
local check = S.check
|
||||
|
||||
local function rowsOf(script)
|
||||
return type(script) == "table" and script or nil
|
||||
end
|
||||
|
||||
-- find the first row whose command is `cmd`; returns index, row
|
||||
local function findRow(rows, cmd, arg2)
|
||||
for i, row in ipairs(rows or {}) do
|
||||
if row[1] == cmd and (arg2 == nil or row[2] == arg2) then return i, row end
|
||||
end
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- (1) the sleeper is text-and-shove only
|
||||
-- ---------------------------------------------------------------------
|
||||
|
||||
local sleepy = rowsOf(init.talkScript("VIRIDIAN_CITY", "TEXT_VIRIDIANCITY_OLD_MAN_SLEEPY"))
|
||||
check(sleepy ~= nil, "sleeper resolves to a row-list script")
|
||||
if sleepy then
|
||||
check(findRow(sleepy, "show_text", "_ViridianCityOldManSleepyPrivatePropertyText") ~= nil,
|
||||
"sleeper shows the private-property text")
|
||||
check(findRow(sleepy, "move_player") ~= nil, "sleeper shoves the player back")
|
||||
-- the bugs: his script must NOT own the other man's dialogue, and must
|
||||
-- never hide himself (pokered's HideObject fires from Oak's lab instead)
|
||||
check(findRow(sleepy, "ask") == nil, "sleeper does not ask about coffee")
|
||||
check(findRow(sleepy, "old_man_demo") == nil, "sleeper does not run the catch demo")
|
||||
check(findRow(sleepy, "hide_object") == nil, "sleeper never hides himself")
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- (2) the walking old man owns the coffee ask + the real catch tutorial
|
||||
-- ---------------------------------------------------------------------
|
||||
|
||||
local oldMan = rowsOf(init.talkScript("VIRIDIAN_CITY", "TEXT_VIRIDIANCITY_OLD_MAN"))
|
||||
-- a Lua function handler here would mean data/scripts/flavor/viridian_city.lua
|
||||
-- (which loads AFTER story.lua) had silently won the talk-table merge back
|
||||
check(oldMan ~= nil, "walking old man resolves to a row-list script, not a handler")
|
||||
if oldMan then
|
||||
local askAt = findRow(oldMan, "ask", "_ViridianCityOldManHadMyCoffeeNowText")
|
||||
check(askAt ~= nil, "walking old man asks the coffee question")
|
||||
check(findRow(oldMan, "old_man_demo") ~= nil, "walking old man runs the catch demo")
|
||||
-- polarity: the question is "Are you in a hurry?", so YES is the refusal
|
||||
-- (ViridianCityOldManText: `and a / jr z, .refused` -- wCurrentMenuItem 0
|
||||
-- is YES). jump_if_true must therefore land on the "Time is money" line.
|
||||
local jAt, jRow = findRow(oldMan, "jump_if_true")
|
||||
check(jAt ~= nil and askAt ~= nil and jAt > askAt, "the yes/no branch follows the ask")
|
||||
if jRow then
|
||||
local target = oldMan[jRow[2]]
|
||||
check(target ~= nil and target[1] == "show_text"
|
||||
and target[2] == "_ViridianCityOldManTimeIsMoneyText",
|
||||
"YES (in a hurry) brushes you off rather than starting the demo")
|
||||
end
|
||||
-- pokered prints this AFTER the demo battle (EndCatchTrainingScript)
|
||||
local demoAt = findRow(oldMan, "old_man_demo")
|
||||
local weakenAt = findRow(oldMan, "show_text", "_ViridianCityOldManYouNeedToWeakenTheTargetText")
|
||||
check(demoAt and weakenAt and weakenAt > demoAt,
|
||||
"the weaken-the-target line comes after the demo, not before it")
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- (3) the Pokédex performs the swap (OaksLab.asm:602-606)
|
||||
-- ---------------------------------------------------------------------
|
||||
|
||||
local oak1 = rowsOf(init.talkScript("OAKS_LAB", "TEXT_OAKSLAB_OAK1"))
|
||||
check(oak1 ~= nil, "Oak's main script resolves")
|
||||
if oak1 then
|
||||
local dexAt = findRow(oak1, "set_flag", "EVENT_GOT_POKEDEX")
|
||||
check(dexAt ~= nil, "Oak sets EVENT_GOT_POKEDEX")
|
||||
local hideAt = findRow(oak1, "hide_object", "VIRIDIAN_CITY")
|
||||
local showAt = findRow(oak1, "show_object", "VIRIDIAN_CITY")
|
||||
check(hideAt ~= nil, "the Pokédex hides the Viridian sleeper")
|
||||
check(showAt ~= nil, "the Pokédex shows the walking Viridian old man")
|
||||
if hideAt then
|
||||
check(oak1[hideAt][3] == "VIRIDIANCITY_OLD_MAN_SLEEPY", "hides the right object")
|
||||
end
|
||||
if showAt then
|
||||
check(oak1[showAt][3] == "VIRIDIANCITY_OLD_MAN", "shows the right object")
|
||||
end
|
||||
check(dexAt and hideAt and showAt and hideAt > dexAt and showAt > dexAt,
|
||||
"the swap runs on the branch that grants the Pokédex")
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- (4) every jump target in the touched scripts is in range
|
||||
--
|
||||
-- Inserting the two swap rows renumbered Oak's whole 30-row jump table.
|
||||
-- An off-by-one there is invisible until a branch silently runs the wrong
|
||||
-- line, so check every target lands on a real row (or the end sentinel,
|
||||
-- #rows + 1) across both files.
|
||||
-- ---------------------------------------------------------------------
|
||||
|
||||
local JUMPS = { jump = true, jump_if_true = true, jump_if_false = true }
|
||||
local checkedJumps = 0
|
||||
for _, modname in ipairs({ "data.scripts.oaks_lab", "data.scripts.story" }) do
|
||||
local mod = require(modname)
|
||||
-- oaks_lab returns one map's table; story returns { [mapId] = table }
|
||||
local maps = mod.talk and { [modname] = mod } or mod
|
||||
for mapId, m in pairs(maps) do
|
||||
if type(m) == "table" and m.talk then
|
||||
for const, script in pairs(m.talk) do
|
||||
local rows = rowsOf(script)
|
||||
if rows then
|
||||
for i, row in ipairs(rows) do
|
||||
if type(row) == "table" and JUMPS[row[1]] then
|
||||
local t = row[2]
|
||||
checkedJumps = checkedJumps + 1
|
||||
check(type(t) == "number" and t >= 1 and t <= #rows + 1,
|
||||
("%s/%s row %d: %s -> %s in range"):format(
|
||||
mapId, const, i, tostring(row[1]), tostring(t)))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
check(checkedJumps > 0, "found jump rows to range-check (got " .. checkedJumps .. ")")
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- (5) the corridor gate keys off EVENT_GOT_POKEDEX at (19,9)
|
||||
-- ---------------------------------------------------------------------
|
||||
|
||||
local onStep = init.get("VIRIDIAN_CITY").onStep
|
||||
check(type(onStep) == "function", "VIRIDIAN_CITY has an onStep hook")
|
||||
|
||||
local function step(flags, x, y)
|
||||
local pushed = 0
|
||||
local game = {
|
||||
save = { flags = flags, inventory = {}, objectToggles = {} },
|
||||
data = Data,
|
||||
stack = { push = function() pushed = pushed + 1 end },
|
||||
}
|
||||
local ow = { player = {}, scriptMove = function() end }
|
||||
local ok, blocked = pcall(onStep, game, ow, x, y)
|
||||
return ok, blocked, pushed
|
||||
end
|
||||
|
||||
if type(onStep) == "function" then
|
||||
local ok, blocked, pushed = step({}, 19, 9)
|
||||
check(ok, "onStep runs at the gate cell")
|
||||
check(ok and blocked == true, "(19,9) is blocked without the Pokédex")
|
||||
check(ok and pushed == 1, "being blocked shows a text box")
|
||||
|
||||
local ok2, blocked2 = step({ EVENT_GOT_POKEDEX = true }, 19, 9)
|
||||
check(ok2 and blocked2 ~= true, "(19,9) is walkable once you have the Pokédex")
|
||||
|
||||
-- the old port blocked the whole 3-wide corridor (x 17-19, y<=8); pokered
|
||||
-- blocks one cell, and the sleeper/girl bodies do the rest
|
||||
local ok3, blocked3 = step({}, 19, 8)
|
||||
check(ok3 and blocked3 ~= true, "(19,8) north of the gate is not itself gated")
|
||||
local ok4, blocked4 = step({}, 17, 8)
|
||||
check(ok4 and blocked4 ~= true, "(17,8) is not gated (only (19,9) triggers)")
|
||||
end
|
||||
|
||||
S.finish()
|
||||
+75
-10
@@ -931,6 +931,61 @@ do
|
||||
Game.save.inventory.EXP_ALL = nil
|
||||
end
|
||||
|
||||
-- these build throwaway battles/mons, which normally roll DVs off the
|
||||
-- ambient love.math.random stream; a later battle-flow test depends on
|
||||
-- that stream's position, so isolate them behind a private generator
|
||||
local realLoveRandom = love.math.random
|
||||
local isoN = 0
|
||||
love.math.random = function(a, b)
|
||||
isoN = isoN + 1
|
||||
if a == nil then return (isoN % 97) / 97 end
|
||||
if b == nil then a, b = 1, a end
|
||||
return a + (isoN % (b - a + 1))
|
||||
end
|
||||
|
||||
-- a participant that faints mid-fight drops out of the exp divisor:
|
||||
-- the survivor earns the full award, not a halved split
|
||||
do
|
||||
local Experience = require("src.battle.Experience")
|
||||
local mon1 = Pokemon.new(Data, "BULBASAUR", 30)
|
||||
local mon2 = Pokemon.new(Data, "PIDGEY", 30)
|
||||
Game.save.party = { mon1, mon2 }
|
||||
local fb = BattleState.newWild(Game, "RATTATA", 10)
|
||||
fb.participants = { [mon1] = true, [mon2] = true }
|
||||
mon2.hp = 0
|
||||
fb:onFaint({ mon = mon2, isPlayer = true, name = "PIDGEY" })
|
||||
check(fb.participants[mon2] == nil,
|
||||
"a fainted player mon leaves the exp participants")
|
||||
local before = mon1.exp
|
||||
fb:enemyMonFainted()
|
||||
eq(mon1.exp - before,
|
||||
Experience.gainFor(Data.pokemon.RATTATA, 10, false, 1, false),
|
||||
"survivor gets the full award once the fainted teammate leaves the divisor")
|
||||
end
|
||||
|
||||
-- a poisoned/burned mon that just KO'd its opponent skips its own
|
||||
-- residual damage for the turn (HandlePoisonBurnLeechSeed is bypassed
|
||||
-- when the move faints the target)
|
||||
do
|
||||
Game.save.party = { Pokemon.new(Data, "BULBASAUR", 20) }
|
||||
local kb = BattleState.newWild(Game, "RATTATA", 5)
|
||||
kb.player.mon.status = "PSN"
|
||||
kb.enemy.mon.hp = 0 -- the opponent was already knocked out this turn
|
||||
local hpBefore = kb.player.mon.hp
|
||||
kb:endOfTurn()
|
||||
eq(kb.player.mon.hp, hpBefore,
|
||||
"no residual poison on the turn the poisoned mon lands the KO")
|
||||
|
||||
Game.save.party = { Pokemon.new(Data, "BULBASAUR", 20) }
|
||||
local lb = BattleState.newWild(Game, "RATTATA", 5)
|
||||
lb.player.mon.status = "PSN"
|
||||
local live = lb.player.mon.hp
|
||||
lb:endOfTurn()
|
||||
check(lb.player.mon.hp < live, "poison still ticks while the opponent lives")
|
||||
end
|
||||
|
||||
love.math.random = realLoveRandom
|
||||
|
||||
Game.save.party = savedParty
|
||||
end
|
||||
|
||||
@@ -2036,6 +2091,7 @@ do
|
||||
local GBCFX = require("src.render.GBCFX")
|
||||
local GameSpeed = require("src.core.GameSpeed")
|
||||
local VideoMode = require("src.core.VideoMode")
|
||||
local FrameCap = require("src.core.FrameCap")
|
||||
local SD = require("src.core.SaveData")
|
||||
-- Isolate from earlier save/options writes in this suite
|
||||
SD.saveOptions(SD.defaultOptions())
|
||||
@@ -2076,10 +2132,7 @@ do
|
||||
press("down")
|
||||
eq(om.index, 8, "cursor reaches COLORS")
|
||||
press("a")
|
||||
eq(og.save.options.colors, "og", "A cycles COLORS to OG")
|
||||
eq(PaletteFX.mode, "og", "PaletteFX mode tracks COLORS option")
|
||||
for _ = 1, 4 do press("a") end
|
||||
eq(og.save.options.colors, "gbc", "COLORS wraps back to GBC")
|
||||
press("down")
|
||||
eq(om.index, 9, "cursor reaches TILT")
|
||||
press("a")
|
||||
@@ -2103,7 +2156,16 @@ do
|
||||
eq(og.save.options.videoMode, "windowed",
|
||||
"VIDEO MODE wraps back to WINDOWED")
|
||||
press("down")
|
||||
eq(om.index, 12, "cursor reaches GAME SPEED")
|
||||
eq(om.index, 12, "cursor reaches MAX FPS")
|
||||
press("a")
|
||||
eq(og.save.options.fpsCap, 75, "A cycles MAX FPS up from 60 to 75")
|
||||
eq(FrameCap.current, 75, "the live render cap tracks the MAX FPS option")
|
||||
-- Driven by the step list rather than a literal press count, like GAME
|
||||
-- SPEED below: a full loop of #STEPS presses returns to the 60 default.
|
||||
for _ = 1, #FrameCap.STEPS - 1 do press("a") end
|
||||
eq(og.save.options.fpsCap, 60, "MAX FPS wraps back to 60")
|
||||
press("down")
|
||||
eq(om.index, 13, "cursor reaches GAME SPEED")
|
||||
press("a")
|
||||
eq(og.save.options.speed, 2, "A cycles GAME SPEED to 2X")
|
||||
-- Driven by the level list rather than a literal press count: adding a
|
||||
@@ -2112,19 +2174,19 @@ do
|
||||
for _ = 1, #GameSpeed.LEVELS - 1 do press("a") end
|
||||
eq(og.save.options.speed, 1, "GAME SPEED wraps back to NORMAL")
|
||||
press("down")
|
||||
eq(om.index, 13, "cursor reaches MODS")
|
||||
eq(om.index, 14, "cursor reaches MODS")
|
||||
press("down")
|
||||
eq(om.index, 14, "cursor reaches CONTROLS")
|
||||
eq(om.index, 15, "cursor reaches CONTROLS")
|
||||
press("down")
|
||||
eq(om.index, 15, "CANCEL stays the fixed final row")
|
||||
eq(om.scroll, 10, "CANCEL keeps the last option boxes on screen")
|
||||
eq(om.index, 16, "CANCEL stays the fixed final row")
|
||||
eq(om.scroll, 11, "CANCEL keeps the last option boxes on screen")
|
||||
om:draw() -- smoke: scrolled layout draws under the headless stub
|
||||
press("a")
|
||||
check(popped, "A on CANCEL closes the options menu")
|
||||
local om2 = OptionsMenu.new(og)
|
||||
OInput.pressed = { up = true }; om2:update(1 / 60); OInput.pressed = {}
|
||||
eq(om2.index, 15, "up from the top wraps to CANCEL")
|
||||
eq(om2.scroll, 10, "wrapping to CANCEL scrolls to the tail")
|
||||
eq(om2.index, 16, "up from the top wraps to CANCEL")
|
||||
eq(om2.scroll, 11, "wrapping to CANCEL scrolls to the tail")
|
||||
-- headless-safe: no love.audio, setters only update internal state
|
||||
require("src.core.Music").applyOptions(og.save.options)
|
||||
require("src.core.Sound").applyOptions(og.save.options)
|
||||
@@ -2526,6 +2588,9 @@ do
|
||||
check(status == 0 or status == true, "save_editor_mod_tests suite")
|
||||
end
|
||||
|
||||
-- ---------------------------------------------- input hold regressions
|
||||
runSuites({ "tests/input_hold_test.lua" })
|
||||
|
||||
-- ---------------------------------------------- parity workstream tests
|
||||
-- Each tests/parity_*.lua is a self-contained file (own bootstrap + check,
|
||||
-- error()s if any assertion fails). Globbed, so dropping a new parity
|
||||
|
||||
+54
-2
@@ -116,7 +116,8 @@ def parse_hidden_events(pokered):
|
||||
Itemfinder detects), HiddenCoins (Game Corner floor coins) and
|
||||
StartSlotMachine (slot machine seats; arg SLOTS_* marks broken ones).
|
||||
Also collects the engine text hooks that the port implements natively:
|
||||
OpenPokemonCenterPC, PrintBenchGuyText, GymStatues and the Vermilion
|
||||
OpenPokemonCenterPC / OpenRedsPC (the player's storage PC in the
|
||||
bedroom), PrintBenchGuyText, GymStatues and the Vermilion
|
||||
Gym GymTrashScript cans (arg = [wGymTrashCanIndex]). For those the
|
||||
fourth macro argument is the facing direction required to trigger the
|
||||
event, except GymTrashScript where it is the can index.
|
||||
@@ -153,7 +154,7 @@ def parse_hidden_events(pokered):
|
||||
elif arg == "SLOTS_SOMEONESKEYS":
|
||||
state = "keys"
|
||||
slots.setdefault(current, []).append({"x": x, "y": y, "state": state})
|
||||
elif func == "OpenPokemonCenterPC":
|
||||
elif func == "OpenPokemonCenterPC" or func == "OpenRedsPC":
|
||||
extras["pcTiles"].setdefault(current, []).append(
|
||||
{"x": x, "y": y, "facing": DIRS.get(arg, arg)})
|
||||
elif func == "PrintBenchGuyText":
|
||||
@@ -303,12 +304,63 @@ def parse_card_key_doors(pokered):
|
||||
util.die(f"card_key.asm: {needle!r} not found (door tiles/blocks changed?)")
|
||||
if n_doors != 22 or len(maps) != 10:
|
||||
util.die(f"card key doors: expected 22 doors / 10 maps, got {n_doors}/{len(maps)}")
|
||||
# closedDoors is hand-ported, not extracted: no retail .blk layout places
|
||||
# a closed-door block at any of the coordinates above (the feature is
|
||||
# unused/cut in the original game), so there is no ROM or disassembly
|
||||
# source to derive this from. It restores that cut content by stamping
|
||||
# facility.bst blocks 0x54/0x5f (2F-10F) or interior.bst block 0x20
|
||||
# (11F) over each door on map load, opened by that door's
|
||||
# EVENT_SILPH_CO_n_UNLOCKED_DOORn flag. Kept in sync by hand with
|
||||
# tools/rom_manifest.json's field.cardKeyDoors.closedDoors.
|
||||
closed_doors = {
|
||||
"SILPH_CO_2F": [
|
||||
{"block": 0x54, "bx": 2, "by": 2, "event": "EVENT_SILPH_CO_2_UNLOCKED_DOOR1", "open": 0x0e},
|
||||
{"block": 0x54, "bx": 2, "by": 5, "event": "EVENT_SILPH_CO_2_UNLOCKED_DOOR2", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_3F": [
|
||||
{"block": 0x5f, "bx": 4, "by": 4, "event": "EVENT_SILPH_CO_3_UNLOCKED_DOOR1", "open": 0x0e},
|
||||
{"block": 0x5f, "bx": 8, "by": 4, "event": "EVENT_SILPH_CO_3_UNLOCKED_DOOR2", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_4F": [
|
||||
{"block": 0x54, "bx": 2, "by": 6, "event": "EVENT_SILPH_CO_4_UNLOCKED_DOOR1", "open": 0x0e},
|
||||
{"block": 0x54, "bx": 6, "by": 4, "event": "EVENT_SILPH_CO_4_UNLOCKED_DOOR2", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_5F": [
|
||||
{"block": 0x5f, "bx": 3, "by": 2, "event": "EVENT_SILPH_CO_5_UNLOCKED_DOOR1", "open": 0x0e},
|
||||
{"block": 0x5f, "bx": 3, "by": 6, "event": "EVENT_SILPH_CO_5_UNLOCKED_DOOR2", "open": 0x0e},
|
||||
{"block": 0x5f, "bx": 7, "by": 5, "event": "EVENT_SILPH_CO_5_UNLOCKED_DOOR3", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_6F": [
|
||||
{"block": 0x5f, "bx": 2, "by": 6, "event": "EVENT_SILPH_CO_6_UNLOCKED_DOOR", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_7F": [
|
||||
{"block": 0x54, "bx": 5, "by": 3, "event": "EVENT_SILPH_CO_7_UNLOCKED_DOOR1", "open": 0x0e},
|
||||
{"block": 0x54, "bx": 10, "by": 2, "event": "EVENT_SILPH_CO_7_UNLOCKED_DOOR2", "open": 0x0e},
|
||||
{"block": 0x54, "bx": 10, "by": 6, "event": "EVENT_SILPH_CO_7_UNLOCKED_DOOR3", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_8F": [
|
||||
{"block": 0x5f, "bx": 3, "by": 4, "event": "EVENT_SILPH_CO_8_UNLOCKED_DOOR", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_9F": [
|
||||
{"block": 0x5f, "bx": 1, "by": 4, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR1", "open": 0x0e},
|
||||
{"block": 0x54, "bx": 9, "by": 2, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR2", "open": 0x0e},
|
||||
{"block": 0x54, "bx": 9, "by": 5, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR3", "open": 0x0e},
|
||||
{"block": 0x5f, "bx": 5, "by": 6, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR4", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_10F": [
|
||||
{"block": 0x54, "bx": 5, "by": 4, "event": "EVENT_SILPH_CO_10_UNLOCKED_DOOR", "open": 0x0e},
|
||||
],
|
||||
"SILPH_CO_11F": [
|
||||
{"block": 0x20, "bx": 3, "by": 6, "event": "EVENT_SILPH_CO_11_UNLOCKED_DOOR", "open": 0x03},
|
||||
],
|
||||
}
|
||||
return {
|
||||
"maps": maps, # maps where the engine checks for doors
|
||||
"doors": doors, # tile coords; block coord = floor(coord/2)
|
||||
"doorTiles": [0x18, 0x24], # locked-door tile ids (FACILITY tileset)
|
||||
"openBlock": 0x0e, # block written over the door's block
|
||||
"silphCo11F": {"doorTile": 0x5e, "openBlock": 0x03},
|
||||
"closedDoors": closed_doors,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -642,6 +642,22 @@ def extract_overworld_fx(pokered, assets_dir):
|
||||
"path": f"assets/generated/fx/{base}.png",
|
||||
"width": size[0], "height": size[1], "source": rel,
|
||||
}
|
||||
|
||||
# The cuttable tree's own OAM sprite: InitCutAnimOAM copies
|
||||
# Overworld_GFX tiles $2d-$2e (top half) and $3d-$3e (bottom half)
|
||||
# into the sprite tiles the Cut animation slides apart, so the crop
|
||||
# comes straight out of the overworld tileset sheet (16 tiles/row:
|
||||
# $2d sits at column 13, row 2).
|
||||
tree_src = Image.open(os.path.join(pokered, "gfx/tilesets/overworld.png"))
|
||||
tree = _convert_image(tree_src.crop((104, 16, 120, 32)),
|
||||
transparent_color0=True)
|
||||
_save_png(tree, os.path.join(assets_dir, "fx", "cut_tree.png"))
|
||||
out["cutTree"] = {
|
||||
"path": "assets/generated/fx/cut_tree.png",
|
||||
"width": 16, "height": 16,
|
||||
"source": "gfx/tilesets/overworld.png tiles $2d-$2e/$3d-$3e "
|
||||
"(engine/overworld/cut.asm InitCutAnimOAM)",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Derive the Pokemon Blue import manifest from the shipped Red manifest.
|
||||
|
||||
Red and Blue are assembled from one pokered source tree; the two ROMs are
|
||||
byte-identical except for a small set of version-gated regions (wild
|
||||
encounters, SGB/GBC palettes, the title ribbon, credits text, preset names).
|
||||
Everything the manifest carries is either identical between the versions or
|
||||
derivable, so rather than re-parsing pokered from scratch -- which would drag
|
||||
in unrelated drift between the checked-out source and the *shipped* Red
|
||||
manifest -- we take the shipped Red manifest verbatim and override only the
|
||||
fields that genuinely differ for Blue:
|
||||
|
||||
* romSha1 -- Blue's ROM hash.
|
||||
* symbols -- the 23 map-header symbols in bank $1D that shift by one
|
||||
byte in Blue (everything else, audio included, is at the
|
||||
same address). Re-sourced from pokeblue.sym.
|
||||
* field.presetNames -- player/rival name presets swap (Blue's player is
|
||||
BLUE/GARY/JOHN, rival RED/ASH/JACK).
|
||||
* field.credits -- the "BLUE VERSION STAFF" title line (and any staff
|
||||
reordering) parsed with _BLUE defined.
|
||||
|
||||
Every other field -- maps, trainers, text, audio addresses, trainer party
|
||||
overrides, tilesets, etc. -- is inherited unchanged, so Blue behaves exactly
|
||||
like Red wherever the two games are identical. The version-specific *content*
|
||||
that is not in the manifest (wild Pokemon, palette colours, the ribbon
|
||||
graphic, credits strings) is decoded from the Blue ROM at import time, which
|
||||
works because the symbol addresses above now point at Blue's data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from extract import field, util # noqa: E402
|
||||
from rom_data import CANONICAL_BLUE_SHA1, SymbolTable # noqa: E402
|
||||
|
||||
DEV = "/Users/bryanbassett/Documents/development"
|
||||
DEFAULT_RED = os.path.join(os.path.dirname(__file__), "rom_manifest.json")
|
||||
DEFAULT_OUT = os.path.join(os.path.dirname(__file__), "rom_manifest_blue.json")
|
||||
DEFAULT_POKERED = os.path.join(DEV, "pokered")
|
||||
DEFAULT_SYMBOLS = os.path.join(DEV, "decprep/pokered-symbols/pokeblue.sym")
|
||||
|
||||
|
||||
def derive(red, pokered, symbols_path):
|
||||
"""Return the Blue manifest derived from the Red manifest dict."""
|
||||
blue = copy.deepcopy(red)
|
||||
blue["romSha1"] = CANONICAL_BLUE_SHA1
|
||||
|
||||
# Re-source every symbol the manifest already references from Blue's .sym.
|
||||
# The name set is identical between versions; only 23 bank-$1D map headers
|
||||
# actually move, but resolving the whole set keeps this robust to future
|
||||
# shifts and fails loudly if pokeblue.sym is ever missing a name.
|
||||
blue_symbols = SymbolTable(symbols_path)
|
||||
resolved, missing = {}, []
|
||||
for name in red["symbols"]:
|
||||
symbol = blue_symbols.by_name.get(name)
|
||||
if symbol is None:
|
||||
missing.append(name)
|
||||
continue
|
||||
resolved[name] = [symbol.bank, symbol.address]
|
||||
if missing:
|
||||
raise SystemExit(
|
||||
"pokeblue.sym is missing symbols the manifest needs: "
|
||||
+ ", ".join(sorted(missing)[:10])
|
||||
+ (" ..." if len(missing) > 10 else ""))
|
||||
blue["symbols"] = resolved
|
||||
|
||||
# Version-gated field bits. Calling the parsers directly (rather than
|
||||
# through field_metadata) sidesteps field_metadata's Red-only sanity
|
||||
# checks, which is exactly what we want for a Blue build.
|
||||
saved = util.ASM_DEFINES
|
||||
util.ASM_DEFINES = {"_BLUE"}
|
||||
try:
|
||||
blue["field"]["presetNames"] = field.parse_preset_names(pokered)
|
||||
blue["field"]["credits"] = field.parse_credits(pokered)
|
||||
finally:
|
||||
util.ASM_DEFINES = saved
|
||||
|
||||
# Sanity: Blue's presets must be the swapped set, and the credits banner
|
||||
# must say BLUE. A silent Red-through here would be a hard-to-spot bug.
|
||||
presets = blue["field"]["presetNames"]
|
||||
if "BLUE" not in presets["player"] or "RED" not in presets["rival"]:
|
||||
raise SystemExit("Blue preset-name parse did not swap player/rival")
|
||||
banner = blue["field"]["credits"]["screens"][0]["lines"][1]["text"]
|
||||
if banner != "BLUE VERSION STAFF":
|
||||
raise SystemExit(f"Blue credits banner is {banner!r}, expected BLUE")
|
||||
|
||||
return blue
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--red", default=DEFAULT_RED,
|
||||
help="shipped Red manifest to derive from")
|
||||
parser.add_argument("--pokered", default=DEFAULT_POKERED,
|
||||
help="pokered source checkout (for _BLUE field bits)")
|
||||
parser.add_argument("--symbols", default=DEFAULT_SYMBOLS,
|
||||
help="pokeblue.sym symbol file")
|
||||
parser.add_argument("--out", default=DEFAULT_OUT)
|
||||
args = parser.parse_args()
|
||||
|
||||
pokered = os.path.abspath(args.pokered)
|
||||
if not os.path.isfile(os.path.join(pokered, "main.asm")):
|
||||
raise SystemExit(f"{pokered} is not a pokered checkout")
|
||||
with open(args.red, encoding="utf-8") as f:
|
||||
red = json.load(f)
|
||||
|
||||
blue = derive(red, pokered, os.path.abspath(args.symbols))
|
||||
with open(args.out, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(blue, f, ensure_ascii=False, indent=2, sort_keys=True)
|
||||
f.write("\n")
|
||||
print(f"wrote {args.out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -9,6 +9,7 @@ from dataclasses import dataclass
|
||||
|
||||
|
||||
CANONICAL_RED_SHA1 = "ea9bcae617fdf159b045185467ae58b2e4a48b9a"
|
||||
CANONICAL_BLUE_SHA1 = "d7037c83e1ae5b39bde3c30787637ba1d4c48ce2"
|
||||
ROM_BANK_SIZE = 0x4000
|
||||
|
||||
|
||||
|
||||
@@ -4253,6 +4253,48 @@
|
||||
]
|
||||
},
|
||||
"cardKeyDoors": {
|
||||
"closedDoors": {
|
||||
"SILPH_CO_2F": [
|
||||
{ "block": 84, "bx": 2, "by": 2, "event": "EVENT_SILPH_CO_2_UNLOCKED_DOOR1", "open": 14 },
|
||||
{ "block": 84, "bx": 2, "by": 5, "event": "EVENT_SILPH_CO_2_UNLOCKED_DOOR2", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_3F": [
|
||||
{ "block": 95, "bx": 4, "by": 4, "event": "EVENT_SILPH_CO_3_UNLOCKED_DOOR1", "open": 14 },
|
||||
{ "block": 95, "bx": 8, "by": 4, "event": "EVENT_SILPH_CO_3_UNLOCKED_DOOR2", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_4F": [
|
||||
{ "block": 84, "bx": 2, "by": 6, "event": "EVENT_SILPH_CO_4_UNLOCKED_DOOR1", "open": 14 },
|
||||
{ "block": 84, "bx": 6, "by": 4, "event": "EVENT_SILPH_CO_4_UNLOCKED_DOOR2", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_5F": [
|
||||
{ "block": 95, "bx": 3, "by": 2, "event": "EVENT_SILPH_CO_5_UNLOCKED_DOOR1", "open": 14 },
|
||||
{ "block": 95, "bx": 3, "by": 6, "event": "EVENT_SILPH_CO_5_UNLOCKED_DOOR2", "open": 14 },
|
||||
{ "block": 95, "bx": 7, "by": 5, "event": "EVENT_SILPH_CO_5_UNLOCKED_DOOR3", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_6F": [
|
||||
{ "block": 95, "bx": 2, "by": 6, "event": "EVENT_SILPH_CO_6_UNLOCKED_DOOR", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_7F": [
|
||||
{ "block": 84, "bx": 5, "by": 3, "event": "EVENT_SILPH_CO_7_UNLOCKED_DOOR1", "open": 14 },
|
||||
{ "block": 84, "bx": 10, "by": 2, "event": "EVENT_SILPH_CO_7_UNLOCKED_DOOR2", "open": 14 },
|
||||
{ "block": 84, "bx": 10, "by": 6, "event": "EVENT_SILPH_CO_7_UNLOCKED_DOOR3", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_8F": [
|
||||
{ "block": 95, "bx": 3, "by": 4, "event": "EVENT_SILPH_CO_8_UNLOCKED_DOOR", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_9F": [
|
||||
{ "block": 95, "bx": 1, "by": 4, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR1", "open": 14 },
|
||||
{ "block": 84, "bx": 9, "by": 2, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR2", "open": 14 },
|
||||
{ "block": 84, "bx": 9, "by": 5, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR3", "open": 14 },
|
||||
{ "block": 95, "bx": 5, "by": 6, "event": "EVENT_SILPH_CO_9_UNLOCKED_DOOR4", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_10F": [
|
||||
{ "block": 84, "bx": 5, "by": 4, "event": "EVENT_SILPH_CO_10_UNLOCKED_DOOR", "open": 14 }
|
||||
],
|
||||
"SILPH_CO_11F": [
|
||||
{ "block": 32, "bx": 3, "by": 6, "event": "EVENT_SILPH_CO_11_UNLOCKED_DOOR", "open": 3 }
|
||||
]
|
||||
},
|
||||
"doorTiles": [
|
||||
24,
|
||||
36
|
||||
@@ -5656,6 +5698,13 @@
|
||||
"y": 3
|
||||
}
|
||||
],
|
||||
"REDS_HOUSE_2F": [
|
||||
{
|
||||
"facing": "up",
|
||||
"x": 0,
|
||||
"y": 1
|
||||
}
|
||||
],
|
||||
"ROCK_TUNNEL_POKECENTER": [
|
||||
{
|
||||
"facing": "up",
|
||||
@@ -6373,6 +6422,11 @@
|
||||
"path": "assets/generated/fx/battle_transition.png",
|
||||
"width": 8
|
||||
},
|
||||
"cutTree": {
|
||||
"height": 16,
|
||||
"path": "assets/generated/fx/cut_tree.png",
|
||||
"width": 16
|
||||
},
|
||||
"fishingRod": {
|
||||
"height": 24,
|
||||
"path": "assets/generated/fx/fishing_rod.png",
|
||||
@@ -44689,6 +44743,15 @@
|
||||
"TRI_ATTACK",
|
||||
"SUBSTITUTE"
|
||||
],
|
||||
"trainerPartyOverrides": {
|
||||
"OPP_CHIEF": [
|
||||
{ "level": 41, "species": "MACHOKE" },
|
||||
{ "level": 41, "species": "GOLBAT" },
|
||||
{ "level": 43, "species": "MAROWAK" },
|
||||
{ "level": 43, "species": "WEEZING" },
|
||||
{ "level": 46, "species": "PERSIAN" }
|
||||
]
|
||||
},
|
||||
"trainerPics": [
|
||||
{
|
||||
"imageBase": "youngster",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user