commit db23855630bd6a0ed892cb478e74994d88a5c5d7 Author: syskiller Date: Tue Nov 10 21:17:44 2026 +0900 다마고치 연구소 한국어판 소스 공개 diff --git a/.github/workflows/paramix-studio.yml b/.github/workflows/paramix-studio.yml new file mode 100644 index 0000000..21241da --- /dev/null +++ b/.github/workflows/paramix-studio.yml @@ -0,0 +1,119 @@ +# Builds Paramix Studio on GitHub. +# +# The repository holds the project unpacked (build.js in the root). For older +# setups a single .zip of the project in the root works too: it is unpacked +# first. +# +# Result: +# 1. A GitHub release "vX.Y.Z" (from the file VERSION) with +# ParamixStudio-vX.Y.Z.html to download. Building the same version again +# replaces the file in that release. Releases do not count against the +# Actions storage. +# Any other branch (for example "dev") makes a pre-release +# "vX.Y.Z-" with ParamixStudio-vX.Y.Z-.html instead, so +# the normal release stays untouched. +# 2. Optional, main branch only: the page on GitHub Pages. Enable it once +# under Settings > Pages > Source: "GitHub Actions". Without that the step +# is skipped and the release is made anyway. +# +# No ROMs are needed and none are uploaded. +name: Paramix Studio + +on: + push: + workflow_dispatch: + +permissions: + contents: write + pages: write + id-token: write + +concurrency: + group: paramix-studio + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Get the source + uses: actions/checkout@v4 + + - name: Find the project + run: | + set -e + if [ -f build.js ]; then + echo "PROJECT=." >> "$GITHUB_ENV" + else + echo "PROJECT=project" >> "$GITHUB_ENV" + ZIP=$(ls -1 *.zip 2>/dev/null | head -n1 || true) + if [ -z "$ZIP" ]; then echo "Neither build.js nor a .zip in the root."; exit 1; fi + echo "Unpacking $ZIP" + mkdir -p project + unzip -o -q "$ZIP" -d project + if [ ! -f project/build.js ]; then + DIR=$(find project -maxdepth 3 -name build.js -printf '%h\n' | head -n1) + if [ -z "$DIR" ]; then echo "build.js not found in the zip"; exit 1; fi + cp -a "$DIR"/. project/ + fi + fi + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Self test (no ROM needed) + working-directory: ${{ env.PROJECT }} + run: node test/unit_test.js + + - name: Build + working-directory: ${{ env.PROJECT }} + run: node build.js + + - name: Read the version + id: ver + run: echo "version=$(tr -d '[:space:]' < "$PROJECT/VERSION")" >> "$GITHUB_OUTPUT" + + - name: Create or update the release + env: + GH_TOKEN: ${{ github.token }} + run: | + set -e + TAG="v${{ steps.ver.outputs.version }}" + PRE="" + BRANCH="${{ github.ref_name }}" + if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ]; then + TAG="$TAG-$(echo "$BRANCH" | tr -c 'A-Za-z0-9.\n' '-')" + PRE="--prerelease" + fi + cp "$PROJECT/dist/ParamixStudio.html" "ParamixStudio-$TAG.html" + if gh release view "$TAG" >/dev/null 2>&1; then + echo "Release $TAG exists, replacing the file." + gh release upload "$TAG" "ParamixStudio-$TAG.html" --clobber + else + gh release create "$TAG" "ParamixStudio-$TAG.html" $PRE \ + --target "${{ github.sha }}" \ + --title "Paramix Studio $TAG" \ + --notes "Download and open in Chrome or Edge. Runs locally, your ROM is never uploaded. Changes: see CHANGELOG.md." + fi + + - name: Prepare the page for GitHub Pages + if: github.ref_name == 'main' || github.ref_name == 'master' + uses: actions/upload-pages-artifact@v3 + with: + path: ${{ env.PROJECT }}/dist + retention-days: 1 + + pages: + needs: build + if: github.ref_name == 'main' || github.ref_name == 'master' + runs-on: ubuntu-latest + continue-on-error: true + environment: + name: github-pages + url: ${{ steps.deploy.outputs.page_url }} + steps: + - name: Publish on GitHub Pages + id: deploy + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..614823a --- /dev/null +++ b/.gitignore @@ -0,0 +1,68 @@ +# Your own files never go into the repository: dumps, firmware, WADs, download content. +# Only the binaries built from the sources here are allowed. +*.bin +*.BIN +!emu/emu.bin +!emu/stub_tpl.bin +!doom/doom_app.bin +!doom/doom_xip.bin +!doom/doomf_app.bin +!doom/doomf_xip.bin +!feld/feld.bin +!feld/feldc.bin +!feld/feld-ko.bin +!feld/feldc-ko.bin +!feld/stub_feld_tpl.bin +!flash/flashapp.bin +!six/six.bin +!t7/t7.bin +!t7/t7x.bin +!t18/t18.bin +!t18/t18x.bin +!v1/v1.bin +!v3/v3.bin +!gb/gb.bin +!gb/gbc.bin +!wolf/wolf.bin +!wolf/wolfsod.bin +!sms/sms.bin +!pm/pm.bin +!ab/ab.bin +*.wad +*.WAD +*.jpg +*.JPG +*.wasm +!doom/mcuwad.wasm +# build output +dist/ +*.o +*.elf +*.map +feld/src/feld/menu_host +feld/src/feld/preview-ko +feld/src/feld/qa/ +doom/src/pdoom/dev/obj/ +# tools +node_modules/ +__pycache__/ +*.sqlite3* +server/generated/ +.DS_Store +Thumbs.db + +wolf/src/host/wolfhost +wolf/src/dev/obj/ +*.sms +*.SMS +*.gg +*.ppm +*.min +*.MIN +*.eep +*.hex +*.HEX +*.pgm +# test screenshots show game pictures: never in the repository +*.png +*.ppm diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fcbd4f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,636 @@ +# Changelog + +Versions are listed newest first. + +## 1.7.4 (2026-11-08) + +Fixes: +- TamaEmu, T7Emu, T18Emu, V1Emu, V3Emu and Pokémon mini: the sound no longer cuts off when one note follows another directly. +- TamaEmu: saves that ran for a long time (for example P's and 4U) are now accepted instead of "firmware too big". They are packed when needed. +- TamaEmu: the Tamagotchi iD (also Lovely Melody) no longer starts in debug mode. In the menu it is called "ID". +- T7Emu: after a pause the Tama starts right away, only the clock and the date are set (no more "Catching up"). +- T18Emu: faster, above all with many figures on the screen (for example twins). Walks (for example to the park) are shown step by step instead of standing still and jumping to the end. +- T18Emu: after leaving the settings the whole picture is shown at once, no longer split. +- T18Emu: a call lights the screen again when it went dark through "Screen off after". +- T18Emu: a key on the dark screen during a call no longer shows a stray patch where the name is first. +- More fields: Land, Water and Sky food now gives food symbols, so the Tama becomes the young stage of its field (Tropical/Glacier, and Sky on Jade Forest). + +## 1.7.3 (2026-11-07) + +New: +- Pokémon mini and Arduboy: your own games in the Paramix menu (also from .zip), with sound and saves. Play time earns Tamapoints. +- DOOM without the Paradise: several episodes or the whole WAD in one entry, Ultimate DOOM with episode 4, DOOM II, and extra WADs like Sigil and Sigil II. The entries share their pictures and sounds and need less room. +- V1Emu: own menu icons for Genjintchi, Morino and Umino. +- TamaEmu: option "Pack the firmware" (saves room, some places can run slower). +- Each emulator: "Remember where you left off" can be switched off. +- Without the Paradise: "Set the clock at the start" can be switched off. +- Start page with an overview of what Paramix can do. + +Fixes: +- TamaEmu: slow in some places, and very slow after transferring items or download content. +- Own Tama pictures: playdates failed at about 90 %, and the small Tama could show a red tint. +- T7Emu: with the screen off no care mistakes were counted. +- When the screen turns on, it shows a recent picture instead of an old one. +- V1Emu: the clock of the Umino ran too slow. +- 6 fields: the egg hunt in Land, Water and Sky gave the food of another field. +- A and C on the home screen could open the flash app instead of the program. +- Without the Paradise: the free space is shown correctly and used better, and the autostart works again after a reset. +- A Glacier or Tropical could be recognized as Land. +- Connecting: clearer message when the adapter sends no data (with a hint for Prolific adapters). + +## 1.7.2 (2026-11-01) + +- Start device without the Paradise: almost the whole 16 MB for programs, DOOM is a menu program like the others, any program can start first, the clock is set in the menu. +- All 6 fields: the lab games follow the field the Tama starts with. Land, Water and Sky get Matching Meals, Catching Poop and Cleaning Dust, Forest gets the Jade Forest games. +- 6 fields (Tropical, Glacier): the DNA, residents and field times belong to each field on its own, with its own symbol. Existing saves are taken over. +- Way back: holding C while the device starts opens the flash app, so the device can always be written again. +- Game Boy Color: colour games (.gbc) in the Game Boy tab, also large ones like Pokémon Gold. +- Menu: play time in DOOM, Wolfenstein, Game Boy and Master System earns Tamapoints (checkbox in the Menu tab). +- TamaEmu: download content can also be added as .zip. +- V1Emu: Umino, Genjintchi and Tamaotchi show which menu icon is chosen. Umino, Genjintchi, Tamaotchi, Morino and Yasashii do not have their own menu icons yet (they show those of the P1). +- Colour Tamas in the menu take 1 to 1.8 MB less room. +- Studio: the help explains the start device, the 6 fields and the way back. +- T18Emu: after a key with the screen dark the picture comes back faster and no key press is lost. +- Fix: T18Emu: animations in busy scenes (such as the blinking pumpkin at Halloween) are shown properly. +- Fix: T18Emu, TamaEmu and V1Emu: the clock stays on time after a long time in standby. +- Fix: T18Emu: the game's save could be damaged when the screen went dark (for example a letter of the name changed). +- Fix: T18Emu: a tone no longer keeps sounding while the settings are open. +- Fix: T18Emu: full care also heals toothache. Before, a Tama with toothache could no longer be healed, fed or played with; full care now repairs it. +- Fix: TamaEmu: installing a VDP on the P's no longer hangs. +- Fix: TamaEmu, V1Emu, V3Emu, T7Emu: a short wheel press with the screen dark only turns it on. +- Fix: start device: leftover copies of the flash app are removed (up to 700 KB more room). +- Fix: menu TAMA and Studio: changing the Tama also finds a Tama from Breed. When the Tama cannot be changed, this is shown instead of "changed". +- Fix: the room overview follows added Tama-Go figures. +- Fix: character sheet: the small figure is no longer blown up. +- Fix: connecting works more reliably with some USB adapters (PL2303). + +## 1.7.1 (2026-10-27) + +- Start device: a colour Tama in the menu (iD L, P's) takes up to 450 KB less room. +- Game Boy: games with empty banks at the end take less room (Pokémon Red and Blue: 256 KB less). +- Fix: TamaEmu: visits between two iD L or two P's failed when connecting. + +## 1.7.0 (2026-10-27) + +- Studio: write protection. A write that is cut off (battery, reset, PC off) can be finished, the device starts in the flash screen. +- Studio: a save goes to the right program on import, also a save of the T18Emu app; saves move along when a program gets another place. +- Studio: more room in a start device, the programs are arranged so that they fit. +- Tab Menu: choose how to get back from the emulators, Game Boy and Master System. +- All emulators: settings for dimming, screen off and language on the device, sound in four steps, the screen comes on when the Tama calls, much less power with the screen dark. +- All emulators: on empty batteries everything is saved and the emulator switches off with the battery picture. +- TamaEmu and T18Emu: faster, T18Emu with smoother pictures. +- T7Emu: fast taps no longer pile up, the clock keeps better time. +- Fix: T7Emu: the Tama could be gone after a battery change. +- Fix: TamaEmu (iD L): the date is taken from the Paradise too. +- Fix: importing a T7Emu save could say that T7Emu is missing. + +## 1.6.13 (2026-10-25) + +- T7Emu: much less power with the screen off. +- T7Emu: runs the game code translated (JIT), much less CPU load also with the screen on. +- T7Emu: the game clock no longer skips seconds. +- T7Emu: sound volume in steps (Off, Quiet, Medium, Loud). +- T7Emu: cleaner tones (no clicks between notes, even note timing). +- T7Emu: a short wheel press right after the screen was dark no longer closes the program. + +## 1.6.12 (2026-10-24) + +- Game Gear: your own Game Gear games in the Paramix menu. +- Game Boy and Master System: holding the wheel saves the game, the next start continues there. +- Game Boy and Master System: restart the game in the settings. +- Game Boy: two Paradise plugged together work like a link cable, e.g. to trade Pokémon. +- Spear of Destiny from your own game files, next to Wolfenstein 3D. +- Warning when a program on the device is outdated. +- Save export and import also for T18Emu, Game Boy, Master System and Wolfenstein 3D (.sav of Game Boy and Master System as in other emulators). +- Fix: T7Emu date after a battery change. + +## 1.6.11 (2026-10-24) + +- Master System: your own Master System games in the Paramix menu, with sound. +- Game Boy and Master System with their own part in "Your new ROM". +- Better use of free room in a start device. +- Fix: removing the main program in a start device damaged Tama Meets. A damaged Tama Meets is now shown. +- Fix: Tama Meets as main program reported too little room. +- Fix: V3Emu clock was sometimes not set. + +## 1.6.10 (2026-10-24) + +- Wolfenstein 3D: shareware or full version from your own game files, in the Paramix menu. Save and continue. + +## 1.6.9 (2026-10-24) + +- Game Boy: black and white Game Boy games in the Paramix menu, with sound. +- Simulated visit: one Paradise is enough for a playdate. +- V3Emu: the Tamagotchi Connection V3. +- Visits and battles between two Paradise for the emulators. +- T18Emu: grow up on the device, items, Tamapoints, mixing-meets.com. +- Care and points on the device for all emulators. +- Battery: longer runtime with the screen off, battery level shown. + +## 1.6.8 (2026-10-19) + +- Start device: the Paradise as a device for programs only. After its own setup the PARAMIX menu comes up with the emulators and DOOM, a SETTINGS entry (sound, display time) and DOWNLOAD (starts the flash program for the PC). All game pictures go, about 5 MB more room; colour Tamas (TamaEmu) and a TG18 (T18Emu) run as further programs there. +- V1Emu (new): the first Tamagotchis (P1, P2, Angel, Morino, Umino, Yasashii, Genjintchi, Tamaotchi) and Digimon V1/V2, from your own ROMs, about 88 KB each. Clock from the Paradise for P1, P2, Angel, Morino and Digimon; turning the wheel shakes the toy; Digimon and Yasashii turned the right way; own icons for Angel and Digimon. Digimon: its icons, its beeps (one-shot buzzer) and its keys (key interrupt) now work. +- Emulator tab: one button for all emulators, every program with its row (▾: clock, start when switched on, figures, download slots), a star for the main program, DOOM in the list, each program once, a program that no longer fits is refused when chosen. +- TamaEmu and T18Emu settings in the Studio and on the device (wheel short): volume, brightness 5 to 100 %, screen off after. +- Light: all emulators now dim the backlight itself, not the colours. T7Emu and V1Emu: "Light" 5 to 100 % and "Dim to" 1 to 50 %. +- Battery change: every emulator saves its run state by itself (screen dark, or every 30 minutes); a session is used once. +- The Paradise no longer lives the time spent in a program at once when you come back (hunger, care misses): its "lived up to" date moves on by that time. +- Save tab: Programs (back up and restore the save of every program) and Paradise (with the editor and, with several saves, the slot to export or write). +- Names tab: rename fields, Tamas and items. Figure drawer: move the eyes and the mouth, per pose. Card tab: TamaSma cards too. Glacier and Tropical with six fields: all six names. +- T18Emu: much faster (translator, idle detection, cached flash), melodies on the real clock, camera and diary on all nine firmwares, the clock after the game's own setup, the save data of the firmware by the 4 KB sector (a 7th block was lost before: the diary hung). Starts again after a test build put start code into the flash window. +- TamaEmu: the 4U and 4U+ need one press per step (NFC chip answered), the iD L clock no longer runs fast with the screen off, only finished pictures, the clock after the game's own setup. +- Settings of the start device and the clock from the Paradise also when started from the menu. +- T18Emu is no longer marked as a test version. +- Fields tab: "Game menu Fields: all fields from level 4": the game's own field menu offers all six fields and the Tama stays (adults only get the three fields of their set). +- Menu: new entry TAMA ("Change Tama" in the Menu tab) sets level, character and care (fed, happy, healthy); the same in the Studio's save editor. +- Menu: after a field change inside the game the menu says "The Tama moved to ... in the game" and asks whether to delete or keep the older save of that field. "Switch was interrupted" only comes after a real power loss. +- Menu: one tick "Several saves (with field choice)". SAVES lists SAVE 1 to 3 (up to 6) with field and Tama, an empty slot starts a new game on a chosen field. A ROM with the old menu per field is converted when written, the stored saves stay. +- A ROM with T18Emu and the menu no longer loses the T18 firmware when it is saved again in the Studio. +- TamaEmu: switch "4U: emulate the NFC chip" (4U and 4U+ only, on by default). +- Menu entries are named after the firmware: TAMA-GO, FRIENDS, ID L, 4U+, PS, PLUS COLOR, TAMA MEETS. iD L versions are named after their version (ID L, ID L JP, ID L 15TH, ID L SPACY). +- Studio: a start device ROM is recognised when loaded (DOOM and emulators); the same firmware chosen again is not added twice. +- Start device: the 1 MB behind the Paradise's save is free for programs, except with T18Emu. +- Menu tab: "All 6 fields" can be unticked again on a ROM with six fields. +- Menu: saving SETTINGS, items or Tamapoints no longer gives error 41 (the menu's flash buffers are word aligned). +- Writing with "Keep saves": the same firmware chosen again no longer counts as a new one (the save stays, no question); a colour Tama keeps its save when an item goes into a store that already has items; a T7Emu or V1Emu that moves between main program and menu takes its save along. +- The menu takes up to 12 further programs and pages through them. +- V1Emu settings (wheel short): colour, grid, shadow, icons, sound, light, dim, screen off, clock, language. V1Emu can be the main program, also in a normal ROM (A and C, start when switched on). +- DOOM in the program list with × and ↺. DOOM as the main program of a normal ROM can start when switched on and stays in the Paradise after leaving. +- Normal ROM: choosing a colour Tama or TG18 makes it the main program; a Tama-Go or Friends that was main goes to the menu. +- All emulators: no white flash when the screen wakes; the display gets 120 ms first, then the light (switch WAKE_QUICK for the old way). +- TamaEmu and T18Emu: the settings menu looks like the one of T7Emu and V1Emu. +- All sprites: the field pictures added from Land, Water or Sky show after saving and loading again (pale, locked). +- T18Emu: a visit (CONNECTION, TAMAGOTCHI) without a partner waits and goes back after a few seconds instead of hanging. +- V1Emu Digimon: the picture is no longer shifted by 3 pixels (own LCD mapping). + +## 1.6.7 (2026-10-16) + +- More emulators (started from the menu): they never started on the device and went back to the Paradise. The cached flash window shows only 1 MB, the further programs lie higher up. The launcher now copies them from the uncached flash (stub_feld_tpl.bin rebuilt). +- Writing with "Keep saves": Tropical and Glacier (and Land, Water, Sky) are the same firmware, only the active field differs. A device on Glacier with a ROM made from Tropical no longer refuses; the device keeps its save and its field, a note says so. + +## 1.6.6 (2026-10-16) + +- T7Emu: new light settings. "Dim after" (10 s to 10 min or never), "Dim to" (1 % to 50 %, only when dimming) and "Screen off after" (never or a time, always longer than the dim time). Dimmed means darker colours (the backlight PWM had no effect on the device). +- T7Emu: when the pet calls, the screen comes on (or bright again), as after a key. +- T7Emu: the Tamagotchi Friends gets its own icons around the screen. +- T7Emu, T18Emu, TamaEmu: the wheel within the first 3 seconds after a resumed start now asks first ("Reset?", A yes, B no). A press meant for the menu no longer throws the game away. +- TamaEmu: the Tama's own save is also written while the screen stays on: after 20 seconds without a key, at the latest 10 minutes after the first change. Before, with "always on", it could wait until leaving, and a power loss lost it. +- TamaEmu: saves of the Android emulator with download content (more than 80 blocks of 64 KB, P's) did not fit and could not be used. The sparsest blocks now go into spare pages behind the firmware, as the device does with blocks it writes; exporting gives the same .sav back. +- TamaEmu: download content (.jpg) for the P's, 4U+ and 4U as well, not only the iD L (stores and routing from tamaemu's dlc tool). +- TamaEmu: the reset question follows the language of the Studio. +- T18Emu (experimental) a lot faster: the most read firmware blocks lie in a part of the Paradise flash that is read through the cache; blocks that are empty in the firmware are answered at once; a bigger buffer for translated code; the idle check runs from the fast memory. The screen only shows finished pictures. The last written part of the firmware's own save is written back after 3 seconds (before only when leaving). +- T18Emu: the speed display and the code screens of the test builds are gone. + +## 1.6.5 (2026-10-15) + +- T18Emu: 1.6.4 hung on the device at the black start screen. At the start every firmware block is now checked: only where the cached flash window shows the same as the flash itself is it read through the cache, otherwise uncached as before. +- T18Emu: the speed display (wheel short) shows a second line "C" with the number of firmware blocks read through the cache. + +## 1.6.4 (2026-10-15) + +- T18Emu faster: the firmware's flash (pictures, code) is now read through the cached flash window instead of the uncached one (about 1.5 us per access on the device; in the simulation the start alone made about 300,000 such accesses per second). Blocks the firmware writes to are still read uncached. Switch T18_FLASH_UNCACHED for the old way. +- T18Emu: the picture goes to the screen at the moment the firmware has finished it. Before it was read later, while the next one was being drawn: built up from the top, black behind texts. Switch T18_PRESENT_LATE for the old way. + +## 1.6.3 (2026-10-15) + +- T18Emu: the next red screen E1 (UNALIGNED). The translator's helper for memory accesses read its two data words after the call with one double load (LDRD); they are only halfword aligned, and the Paradise's processor faults there (the PC emulator did not). Now read as halfwords. +- Device simulation: ALIGNCHK=1 reports every LDRD/STRD/LDM/STM/PUSH/POP with an address that is not a multiple of 4. + +## 1.6.2 (2026-10-15) + +- T18Emu: cause of the red screen E1 found. On the device a halfword write into the PRAM fills the other half of its word with the halfword written just before (somewhere else). The translator patches single halfwords, so the first translated block got a broken instruction. The translated code is now written as whole words (read, change one half, write the word). Build switch T18_PRAM_HALF for the old way. +- Device simulation (t18/test/devt18.py): PRAMQUIRK=1 behaves like that PRAM; with it the old build stops exactly like on the device, the new one runs. IRQ=1 takes the SysTick as a real exception. + +## 1.6.1 (2026-10-15) + +- Saves of the further emulators: in the Save tab a choice "T7Emu" (main emulator or one of the further ones) appears; backing up and taking over a save.bin works for each. "Back up save" on the device also fetches the save of every further T7Emu of the loaded ROM. +- "Keep saves" with a save.bin taken over for a further emulator: its new pet stays, its settings come from the device. + +## 1.6.0 (2026-10-15) + +- More emulators in one ROM: in the Emulator tab "Add another emulator" takes one more Tama-Go or Friends ROM (up to 6). Each runs its own T7Emu with its own save and is started from the menu (A and C), under "PROGRAMS". The menu must be on (field switch or items). +- The menu (settings block version 5) lists the programs; the launcher has a second entry for that. "Keep saves" keeps the save of each further emulator while its ROM stays the same. +- The flash bar counts the further emulators. + +## 1.5.6 (2026-10-15) + +- Writing to the device with "Keep saves" after T18Emu: the old firmware blocks of T18Emu are no longer kept as if they were a save of the Paradise. They are freed (the new ROM's content goes there), and the Studio no longer reads about 1 MB from the device before writing. +- Writing: if the device does not answer right before writing, the Studio asks again (with a ping in between) instead of stopping at once; if it still does not answer, a clear message says that nothing was written. +- Web Serial: a buffer overrun, framing or parity error no longer ends the reading for good; the Studio takes a new reader. + +## 1.5.5 (2026-10-15) + +- T18Emu: the red screen E1 shows 16 values in two columns (fault frame, stack, fault status, start stage, translator). +- T18Emu: self test at the start: code written into the PRAM where code already ran must run as written, otherwise red screen E6. +- T18Emu: holding B while T18Emu starts runs the firmware without the translator (slower, for tests). + +## 1.5.4 (2026-10-15) + +- T18Emu: red screen E1 at the start on the device. The translated code is now written into the PRAM by a small routine running from the SRAM (the way TamaEmu does it on the device) instead of from the flash window. +- T18Emu: the red screen E1 shows more: PC, LR, fault status, fault address, how far the start got and the firmware's PC. + +## 1.5.3 (2026-10-15) + +- T7Emu runs the Tamagotchi Friends too (test): choose its ROM (768 KB) in the Emulator tab instead of the Tama-Go ROM. Same settings, saves and clock as with the Tama-Go. There are no figures for it. +- T7Emu core: the Friends ROM has 16 KB more in front and its bank 0 sits differently; its frame tick comes from another interrupt. Both are recognised from the ROM, the Tama-Go runs as before. + +## 1.5.2 (2026-10-15) + +- T7Emu: the full figure dumps (4 MB, with the extra games) can be added. The Studio keeps one copy of the 1 MB figure (the dump holds it four times), so it takes about 700 KB. In the menu it shows as "... Full". +- The hint on the number of figures is gone. +- New "Help" button at the top: steps, buttons on the Paradise, clock, saves. Opens and closes on a click. +- The repository allows t7/t7.bin, t18/t18.bin and t18/t18x.bin (.gitignore). + +## 1.5.1 (2026-10-15) + +- T18Emu runs on the device. 1.5.0 hung with a black screen: the RAM at 0x20000000, where it kept its data and the translated code, has only 4 KB on the Paradise. Now the hot code and the translated code are in the PRAM, the rest of the code runs from the flash, the data is in a part of the SRAM the firmware does not use. +- T18Emu: a red screen with a code instead of hanging when something goes wrong; the wheel goes back to the Paradise. +- T18Emu: the firmware is placed from the top of the flash down, so the field switch of the menu now fits next to it (Land, Sky, Water). +- All emulators: new switch "Take the clock from the Paradise at the start" (tab Emulator, on by default). At every start the emulator sets its clock to the Paradise's time, nothing is caught up. +- Writing to the device with "Keep saves": if the device has an emulator whose save cannot be kept (another emulator, or a newly chosen firmware), the Studio says so before writing, so it can be backed up first. +- README: how the emulators behave when leaving and coming back, the clock, the shortcuts. + +## 1.5.0 (2026-10-15) + +- New emulator T18Emu (test version) for the Tamagotchi Meets and On: choose the TG18 firmware (8 MB) in the Emulator tab. The Studio places its used blocks into free blocks of the Paradise flash and keeps spares for the firmware's own save data. +- On the device: hold A and C on the home screen to start, hold the wheel to go back (saves). A short press on the wheel shows the speed. The firmware runs through a translator from ARM to Cortex-M3 code; loops that only wait are skipped. The pet screen may still run a little slower than on the toy. +- "Keep saves" keeps the T18Emu save as long as the firmware is the same. +- The menu on A and C shows T18EMU. + +## 1.4.2 (2026-10-15) + +- T7Emu: on a new install the screen starts pixel exact and without the pixel look. +- Studio: the Emulator and Save tabs now name both emulators (TamaEmu for colour tamas, T7Emu for the Tama-Go) and both save formats. + +## 1.4.1 (2026-10-15) + +- T7Emu: the first time setting got stuck. The game only takes the time once the hour was changed, so at midnight it started over and the egg did not hatch. T7Emu now fills in the time: the one written along by the Studio when writing to the device, or after a restart the game time from before. Birthday and name follow as on the toy. +- T7Emu: the clock no longer corrects the time while the game asks for it. +- T7Emu settings: light and dark grey, grid, pixel view, icons in steps, clock (Auto or game), language. New "Screen": Large fills the width (the pixels are 2 or 3 dots wide), Pixel exact keeps every pixel the same size (smaller). +- The menu on A and C shows T7EMU instead of PROGRAM. + +## 1.4.0 (2026-10-14) + +- New emulator T7Emu: choose the ROM of the Tama-Go (640 KB) in the Emulator tab, like a firmware. Figure ROMs can be added (up to 16) and removed again. +- On the device: hold A and C on the home screen to start, hold the wheel to go back (saves). A short press on the wheel opens the settings: figure, background colour, Tama colour, pixel mode, icons, sound and light. They are kept on the device. +- The clock of the Tama-Go follows the Paradise clock. After a pause the missed hours pass (up to 30). +- Tab "Save": the T7Emu save as a .bin file (the same as the save.bin of the T7Emu app), out of the ROM and back in. "Back up save" on a device with T7Emu also downloads it. +- "Keep saves" keeps the Tama-Go save as long as the Tama-Go ROM stays the same. + +## 1.3.4 (2026-10-14) + +- Fix: 1.3.3 did not load any ROM because of a broken text. Every script is now checked when building. + +## 1.3.3 (2026-10-14) + +- TamaEmu: Connect on the iD L (Plus Color) hung. Code that keeps overwriting itself made the emulator throw away its translated code thousands of times per second. Such parts now run without translation; after the waiting time FAILED appears and the iD L goes back as usual. +- Emulator tab: the hint says how to restart TamaEmu if it hangs. + +## 1.3.2 (2026-10-14) + +- TamaEmu: firmware of the P's, 4U+ and 4U is recognised. Their firmware is bigger than the room so far; it now goes into a larger area of the ROM. With such a firmware the field switch of the menu has no room (items in the menu still work). +- TamaEmu: the 4U+ and 4U run with their own clock (30 MHz). They need more computing power than the iD L, so games run slower on the Paradise. + +## 1.3.1 (2026-10-14) + +- Tab "Save": own buttons to import a save. A TamaEmu .sav goes into the ROM, a Paradise .tamasave onto the connected device. +- Switching the language now updates every text, also in the tabs. +- Some error messages now have a German text. + +## 1.3.0 (2026-10-14) + +- Save games: back up the Paradise save from the device as a .tamasave for the TamaParadise app, with the device's clock, and the TamaEmu save as a .sav for the TamaEmu app. A .tamasave goes back onto the device; a save of another edition is refused. New tab "Save" for the same from a loaded ROM. +- TamaEmu: a .sav from the TamaEmu app can be chosen like a firmware, so the game carries on on the Paradise. +- Device: the edition is now read from the device's flash. Before, every device counted as Land, so "Keep saves" refused other editions. +- Flash app: reads and sets the Paradise's clock. + +## 1.2.12 (2026-10-14) + +- Menu: the saved fields share one room instead of a fixed slot each. With all 6 fields on Tropical or Glacier a slot was only 72 KB, so a much played save stopped the switch with error code 11. Now one field can use up to about 430 KB there (the room the other fields do not need). Saves of older versions are still read; they move to the new form at the next switch. +- Menu on Tropical and Glacier: since 1.2.2 the menu wrote the device ID to the wrong page (0xD49000, inside the save area) and left the real ID page alone. Fixed: the ID page is set again on every switch. +- Menu program rebuilt. + +## 1.2.11 (2026-10-14) + +- Menu: field saves get all the free room. Without emulator or DOOM each field slot is now up to about 1.7 MB instead of 352 KB. A large save (much played, many items) no longer stops the field switch with error code 11. Saved fields on the device are moved to the new slots when writing with "Keep saves". +- Menu: error codes 10 and 11 now say "SAVE TOO BIG" on the device. The active field stays as it is. +- Menu program rebuilt. + +## 1.2.10 (2026-10-14) + +- Start page: describes everything the Studio does (TamaEmu, DOOM, more fields, menu, device, characters) instead of only the character sheets. + +## 1.2.9 (2026-10-14) + +- TamaEmu: if the screen of the Tamagotchi is dark right after resuming (its own screen saver ran out while the clock caught up, often after the autostart), the emulator presses C once to wake it. Only in the first seconds after the start and only while the screen is dark. +- Emulator program v0.9.5. + +## 1.2.8 (2026-10-14) + +- TamaEmu autostart: going back with a long press now keeps the Paradise, also after its screen went dark (deep sleep). The emulator comes back with A and C, the reset button, or after the battery was out. Holding B while the Paradise starts skips the emulator. +- Emulator program v0.9.4 (tells the stub that you went back on purpose). + +## 1.2.7 (2026-10-14) + +- TamaEmu: new switch "Start when switched on". After power-on the Paradise goes straight into the emulator. Holding the wheel goes back to the Paradise as before and it stays there until the next power-on (A and C start the emulator again). Holding B while switching on skips the emulator once. +- Stub: the original home screen handlers now sit at a fixed place in both stub variants. Menus of older versions are still recognised. + +## 1.2.6 (2026-10-14) + +- TamaEmu: updating keeps the save. A ROM that already has the emulator gets the new emulator program when it is saved, without choosing the firmware again. Written with "Keep saves", the Tamagotchi's save, its items and the saved session stay on the device. +- Keep saves: the spare pages of TamaEmu (item stores, since 1.2.3) are kept too. Before they were overwritten even with "Keep saves". + +## 1.2.5 (2026-10-14) + +- Six fields: the planet now follows the field. On Land, Water and Sky the planet view and the travel scenes show the Land, Water and Sky planet instead of the Tropical or Glacier one, like on the original devices. New switch "Planet to match the field" (on by default). Jade Forest: the Sky planet on Sky. +- Helper page version 5 (planet tables per field). ROMs with more fields from 1.2.0 to 1.2.4 are updated when saved: Jade Forest on its own, Tropical/Glacier with your Land, Water or Sky ROM chosen. +- TamaEmu: the clock no longer runs slow. The emulator dropped part of each millisecond while the Tamagotchi runs on its slow clock (about 2.3 percent, up to half an hour a day). It also follows the seconds counter of the Paradise now, so time lost in busy scenes (shopping, saving) is added back. +- Emulator program v0.9.3. + +## 1.2.4 (2026-10-14) + +- Six fields: the special character of each field. On Land, Water and Sky the firmware now picks Chodracotchi, Mermarintchi and Yayacorntchi instead of the Tropical, Glacier and Forest special characters (Manapatchi, Hobohorntchi, Tatsutchi). Jade Forest: Yayacorntchi on Sky. +- Helper page version 4 (the site list also holds plain values). ROMs with more fields from 1.2.0 to 1.2.3 are updated when saved: Jade Forest on its own, Tropical/Glacier with your Land, Water or Sky ROM chosen. + +## 1.2.3 (2026-10-14) + +- TamaEmu: fixed the crash when buying in the Tamadepa (for example the mop under daily items on the iD L). The iD L writes its item stores into 64 KB flash sectors; the emulator only kept writes to the small parameter sectors, so the purchase was lost and the game hung waiting for the flash. Now 64 KB sectors are erased and written like on the real chip. Blocks that are empty in the firmware get spare pages behind the packed firmware. The in-game reset of the iD L works again too (it hung on "WAIT!" before). +- TamaEmu: a long press after such a hang no longer saves the hung session (no save if the core stopped or guest writes were lost). +- TamaEmu: new way out of a bad session: release A and C after starting and press the wheel within the first 3 seconds. The saved session is dropped, the next start begins fresh from the Tamagotchi's own save. No reflashing needed. +- Emulator program v0.9.2, settings block version 3 (end of the spare area). Saved sessions of older versions are not resumed (the Tamagotchi's own save stays). + +## 1.2.2 (2026-10-14) + +- Six fields: rain on Land, Water and Sky. The rain pictures lie in the unused flash area from 0xF00000 (the cells the clear pictures do not share); the Studio points them there again after every save. +- Six fields: the scene animations now follow Jade Forest's tables, which have the same layout as Tropical's (the columns of 1.2.1 were partly wrong), and the wagon scene of the planet view shows Land, Water and Sky too. +- Jade Forest: new switch "Sky as 4th field". Jade Forest already carries everything of Sky, no second ROM is needed. Sky uses the Water slot with the set byte; the menu lists Land, Water, Forest, Sky. +- Helper page version 3 (one code for both firmwares, all addresses and tables filled in by the Studio). ROMs of 1.2.0 and 1.2.1 are updated when saved with a Land, Water or Sky ROM chosen. +- Menu settings block: field table for the set byte (Jade Forest: Sky; Tropical/Glacier: Land, Water, Sky). The menu no longer packs the area from 0xF00000 into the field saves. +- Device: "Keep saves" does not keep the area from 0xF00000 of the device when the new ROM has the extra fields (it holds pictures there). + +## 1.2.1 (2026-10-14) + +- Six fields: on Land, Water and Sky the travel backgrounds, the field eggs and the scene animations (birthday and others) now show the Land, Water and Sky pictures too. Eleven more places of the firmware jump into the helper page; the Land scripts are copied with the scripts and sprites they use (most sprites are already in Tropical/Glacier and are shared). +- Six fields of 1.2.0 are updated automatically when the ROM is saved again. +- DOOM: the wheel button is now followed every millisecond. Quick taps on the wheel (looking for secret doors) no longer add up to a long press that ended the game. The long press (2 s) counts from the last press. + +## 1.2.0 (2026-10-14) + +- Menu tab: new switch "All 6 fields" for Tropical and Glacier. Adds Land, Water and Sky to Tropical, Glacier and Forest. The field pictures come from your own Land, Water or Sky ROM (any of the three). +- How it works: the Tropical/Glacier firmware has three field slots and already carries the characters of all six fields. The Studio copies the field pictures of Land, Water and Sky into the archive (128 colours per picture, tiles shared between the times of day) and patches four places of the firmware: a set byte in the save (offset 0xF04) switches the three slots to Land, Water, Sky for the backgrounds and for child, teen and adult characters. Helper code at flash 0x10F000, source in `six/src`. +- To make room the Tropical, Glacier and Forest field pictures are stored with 128 colours (no visible difference). +- On Land, Water and Sky rain shows the clear picture (no room for the rain pictures). Some scenes still show the pictures of the matching Tropical, Glacier or Forest slot (fixed in 1.2.1). +- Menu on the device: six fields in a compact list; saves of the fields in two regions (behind the menu and behind the character data). Settings block version 4. +- Not possible together with DOOM or the emulator (Tropical, Glacier and Jade Forest have no room for them anyway). + +## 1.1.0 (2026-10-13) + +- Characters tab: new field filter. Shows only the characters of one field (Land, Water, Sky, Forest, Tropical, Glacier), with their names from the ROM. +- "Field as ZIP": all sheets of one field in one ZIP: 22 characters (child, 4 teens, 17 adults), the 7 field map pictures (plus 7 overlays on Tropical/Glacier), the 6 close-up backgrounds, a contents list and field.json. +- "Load field from ZIP": puts a field ZIP (from the same or another ROM) into the selected field, character by character in the same order. Characters whose eye images do not fit stay original as a whole. +- Character tiles show the character's name. +- A character sheet is now applied completely or not at all (no half replaced characters). + +## 1.0.5 (2026-10-13) + +- Fixed missing item pictures in ROMs with DOOM: the Studio searched the whole ROM for the image table and found a similar looking table inside the DOOM program first. It now searches only the asset archive. This was the cause of the codes P6 and P7 on the device. + +## 1.0.4 (2026-10-13) + +- Catalog of the menu: the Studio now stores the flash address, length, sum and first word of every item picture. The menu reads the picture straight from there and no longer looks it up in the ROM's image table (the device returned wrong values there, code P6). +- Menu: three ways to read a picture (32-bit reads, byte reads, the cached XIP window); the first one whose sum matches is used. If none matches, "RD" shows the sums of all three and the first word read and expected. + +## 1.0.3 (2026-10-13) + +- Menu on the device: item pictures are copied to RAM with aligned 32-bit reads (the way the flash app reads dumps) and checked against a sum stored by the Studio before they are drawn. Damaged data can no longer hang the menu; a mismatch shows "RD" with both sums. +- Picture decoder: every loop is bounded by the entry size. + +## 1.0.2 (2026-10-13) + +- English page: error messages of the emulator, DOOM and menu parts are now English too (they were German). The German page translates them. +- Card tab: "No." instead of "Nr." on the English page. Saved file names use "_fields" instead of "_felder". +- Menu: a ROM with a menu from an older Studio version gets the current menu when it is saved or written (the overview shows "gets updated"). Before, such a ROM was kept unchanged, so item pictures (new in 0.9.6) were missing on the device. +- Menu on the device: if an item picture cannot be drawn, a short code (NO PICS, P1 to P4) appears in the picture box. + +## 1.0.1 (2026-10-13) + +- Disclaimer on the page, in the Device panel and in the README: use at your own risk, no warranty, no liability for damage to devices or data. +- Trademark notice on the page and in the README. + +## 1.0.0 (2026-10-13) + +- Device tab: read the ROM over a UART dongle (Web Serial, Chrome or Edge) and write a ROM to the device. The flash app is loaded from the download screen, so no P-COM is needed. The source of the flash app is in flash/src. +- Device tab, "only write changes": the tool compares CRCs per 64 KB and 4 KB and writes only the sectors that differ. +- Device tab, "keep saves": save data, field slots, TamaEmu state and guest save, and the DOOM save are taken over from the device. +- TamaEmu: all download content stores of the 8 MB firmware are supported: meals, snacks, clothing, accessories, items, daily items, wallpapers, games and destinations. +- TamaEmu: several .jpg files can be added at once, and each slot can be removed. The store layout follows tools/dlc.c from tamaemu. +- Release: English code comments, English README, LICENSE (GPL-3.0), NOTICE with third party credits and this CHANGELOG. Every shipped binary rebuilds byte-identical from the sources. + +## 0.9.6 + +- New overview at the top, "Your new ROM": shows what the saved ROM will contain (new, kept, removed) and how full the flash is. +- Emulator tab warns that a chosen firmware replaces DOOM. The overview then shows "DOOM will be removed". +- DOOM program v0.4.0: key layout can be set in the DOOM tab (fire, forward, back, use, hold key, double tap run). A ROM with DOOM already built in can be changed without the WAD. +- DOOM program v0.4.0: fixed "back" sometimes firing for one tick before the 120 ms delay had passed. +- Field switch shows three fields for every ROM (Land, Water, Sky; Land, Water, Forest on Jade Forest; Tropical, Glacier, Forest). +- Item picker shows the item picture next to the amount. + +## 0.9.5 + +- New Menu tab. The on-device menu is called PARAMIX and opens with A+C on the home screen. Texts are in English. +- FIELD: switch field, as in 0.9.4. Works for Land/Water/Sky and for Tropical/Glacier. +- ITEMS: show the bag, add items from a catalogue (food, snacks, toys, goods), set amounts, save. +- POINTS: set Tamapoints digit by digit. +- Jade Forest gets ITEMS and POINTS only. + +## 0.9.4 + +- New Fields tab with "Field switch". The A+C menu lists Land, Water and Sky. Switching packs the save of the old field into its own slot and brings back the save of the new field. +- A field that never ran starts like a new device. Switching back restores the old state. +- Works together with TamaEmu or DOOM. With DOOM each field has room for about 36 KB of packed save. If it does not fit, error code 11 is shown and nothing changes. +- Dumps that already contain stored fields keep them when saved. + +## 0.9.3 + +- New DOOM tab. Choose your own DOOM.WAD (Ultimate DOOM or Shareware, episode 1), the Studio builds DOOM into the ROM. The WAD stays on your computer and no game graphics ship with the Studio. +- The WAD converter runs in the browser (WebAssembly). +- DOOM program v0.3.1: title screen, status bar and menu labels are built from your own WAD. No third party graphics remain in the program. +- DOOM program v0.3.0: black start screen with a loading bar on first start, no test screens. C held plus wheel press switches sound: all on, music off, all off. +- DOOM program v0.2.5: music, a one voice player that plays the main theme of the first level. Music volume 0 in the menu turns it off. +- DOOM program v0.2.4: sound effects on the buzzer. Wheel turns the other way. C held plus wheel changes weapon. C alone goes back. +- DOOM program v0.2.3: game starts and runs. Fixed a crash on unaligned memory access when a level loads. +- DOOM program v0.2.0 to v0.2.2: fixed a black screen and a crash caused by RAM at 0x20000000 being only 4 KB. Frame and palette now work. +- DOOM program v0.1.x: first bring-up on the device (128x128 picture, wheel and button control). Fixed several start hangs. Based on nRF52840 Doom by next-hack (GPL). +- Studio and test builds share the same build path, so the ROM is the same in the browser and on the command line. + +## 0.9.2 + +- Fewer short hangs when keys are pressed quickly. +- Saving happens when the screen goes dark, not while playing. + +## 0.9.1 + +- Fewer hangs on fast key presses in menus and games. +- The TamaEmu save is written when the guest screen goes dark, invisibly. + +## 0.9.0 + +- First finished TamaEmu build without any test numbers on screen. +- Start screen is black instead of blue. +- The wheel short press no longer shows a speed readout. +- Behavior otherwise as in 0.8.22. + +## 0.8.22 + +- The guest save is written to flash in small pieces instead of all at once. This shortens the hangs that made sound stretch. + +## 0.8.21 + +- Test build: shows where the program spends its time in a game. + +## 0.8.20 + +- Test build: shows how much time emulation and screen output take. + +## 0.8.19 + +- Cleaner screen: no leftovers of old figures, no stripes. +- A second short wheel press removes the number lines again. +- Backlight stays off on a black picture and comes back on a key press. + +## 0.8.18 + +- Backlight handling fixed: it turns off when the guest picture is black. +- Test build with faster screen output ("LCDschnell"). + +## 0.8.17 + +- Faster screen output. +- Backlight really turns off when the guest picture is black. +- Frequently read game data is kept in fast memory. + +## 0.8.16 + +- Translated code is back in fast memory and has more room. +- Backlight turns off when the guest picture goes black. +- Short wheel press shows two lines of speed numbers. + +## 0.8.15 + +- Guest ROM is read through the fast flash cache. +- The translator clears its code more cheaply. New sound output. +- Short wheel press shows a speed number line. + +## 0.8.14 + +- Translated code now lives in working memory. Nothing writes into program memory any more. + +## 0.8.13 + +- Memory probe test build and a normal build. + +## 0.8.12 + +- The translator no longer writes its code byte by byte into program RAM. Added a write self test. +- A long wheel press returns to the Paradise even on an error screen. + +## 0.8.11 + +- Further hardening of the jump guard. Same behavior as 0.8.10. + +## 0.8.10 + +- Further hardening of the jump guard. Same behavior as 0.8.9. + +## 0.8.9 + +- Further hardening of the jump guard. Same behavior as 0.8.8. + +## 0.8.8 + +- A guard checks every jump into translated code and reports when one returns wrongly. + +## 0.8.7 + +- Program code is write protected. A write into it shows an error screen with the place that wrote. +- Test build without the translator. + +## 0.8.6 + +- Self test at start checks whether the device runs freshly written code correctly. If it fails, TamaEmu runs without the translator (slower). +- Test build that never uses the translator. + +## 0.8.5 + +- TamaEmu no longer reads the guest ROM through the flash cache. + +## 0.8.4 + +- At start the emulator code in memory is checked and repaired. + +## 0.8.3 + +- Start hang report shows more lines (read test, error picture). + +## 0.8.2 + +- Start screen shows numbers so that a hang on the real device can be located. + +## 0.8.1 + +- Start on the real device reworked. + +## 0.8.0 + +- TamaEmu runs much faster, with its own JIT. + +## 0.7.0 + +- TamaEmu is faster and plays sound. +- Fixed game 3 (camera) hanging. +- Keys in the menu react at once and beep. +- A saved state from 0.6 is discarded. + +## 0.6.0 + +- New Emulator tab. Choose your own colour Tamagotchi firmware (4 MB or 8 MB) and TamaEmu is built into the ROM. +- Start with A+C held for about two seconds on the home screen. Hold the wheel for two seconds to save and return to the Paradise. The next start continues where you left off. +- With an 8 MB firmware a download game (.jpg) can be put into one of two game slots. +- The guest display switches off after about 36 seconds without a key and wakes on a key press. +- TamaEmu core is derived from tamaemu by maragotchi (GPL-3.0). + +## 0.5.0 + +- Baby, child and teen stay original (figure, eyes, cell). Only adults are replaced. +- A replaced adult keeps the eyes of the card figure. The cell has no eyes for that stage. +- The first adult is preselected as target. + +## 0.4.1 + +- No brand names in the Studio. The tab is called "Card", figures are "No. 0" to "No. 16". +- ROMs are the same as in 0.4.0. + +## 0.4.0 + +- The cell stays original with all eye expressions. The baby stays the original Tama and card figures start at the child stage. +- The switch "Make figure blink" is off by default. It is the old way from 0.3.0. + +## 0.3.0 + +- Card figures get their own eye layer, so they blink and the cell shows eyes. +- Drag the eye frame by clicking the eye. +- The selected figure is shown large with a pink frame around the eye. + +## 0.2.0 + +- First Studio release. Open a Paradise 16 MB flash dump, pick a figure, download its sheet, edit it and upload it again. +- Download all sheets as a ZIP, or upload a ZIP or many PNG files at once. +- Insert figures from a figure card image, including the egg. +- Number test ROM: each figure shows its number. +- Land, Water, Sky, Jade Forest, Tropical and Glacier are recognised. Archive checksums are recalculated and every changed graphic is read back before saving. + +## 0.1.0 + +- Command line tool paramix.py builds ROMs from recipe files with figures from a figure card image. +- Three sample recipes: one evolution line, all figures of a card, and a number test. diff --git a/Dockerfile.builder b/Dockerfile.builder new file mode 100644 index 0000000..bc83190 --- /dev/null +++ b/Dockerfile.builder @@ -0,0 +1,3 @@ +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends clang lld llvm gcc python3 python3-pil ca-certificates && rm -rf /var/lib/apt/lists/* +WORKDIR /src diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..818433e --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..e8dd1d0 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,167 @@ +# Notice: authors and licenses + +## ITOSM Korean edition (2026-11-10) + +Modified from mameise/Paramix-Studio commit +`675b904ab1c8a9086b977a82cbc47cd0c319187f` (version 1.7.4). +Changes: Korean web translations, optional Korean A+C menu, Korean font rendering, +menu language detection, compact layouts, and self-hosted Docker packaging. +The original English device-menu binaries are retained. Korean device-menu builds +have PC-only synthetic checks; no physical-device validation has been performed. +The Korean UI uses English for emulator settings that only support English/German. +Galmuri9 by quiple is used under SIL OFL 1.1; its source and license are in +`third-party/`. Generated font data is marked as a subset. +The modified program remains GPL-3.0-or-later. See README.ko.md for build steps. + +Paramix Studio by mameise is licensed under the GNU General Public License, +version 3 or (at your option) any later version. The full text is in +[LICENSE](LICENSE). + +Parts of this repository are based on the work of other people. Their +copyright and licenses stay in force; the files keep their original notices. + +## TamaEmu (`emu/`) + +- **tamaemu** by maragotchi, https://github.com/maragotchi/tamaemu, + GNU GPL version 3 (copy in `emu/LICENSE` and `emu/src/core/LICENSE-tamaemu`). + The emulator core in `emu/src/core` is derived from tamaemu. The layout of + the download content stores and the routing of download records + (`src/emu.js`, `emu/src/tools/dlc.py`) follow tamaemu `tools/dlc.c`. +- Changes for this project: a slim core for the Paradise without an operating + system, the JIT translator from S1C33 to Thumb-2 (`tc_jit.c`), the Paradise + host (`emu/src/emu`), the launcher stub and the ROM packing. Same license. +- The S1C33 instruction decoding follows the SLEIGH definition by GMMan, + https://github.com/GMMan/s1c33_sleigh. + +## T7Emu (`t7/`) + +- The 6502 core in `t7/src/core` is a C port of the JavaScript emulator + **tamago** by asterick, https://github.com/asterick/tamago, which its + package declares under the BSD license. The port comes from the T7Emu app by + mameise. The note in the source files stays. +- Changes for this project: a fast run loop (`t7_run.inc`), a build without C + library, the Paradise host (`t7/src/app`) with screen, settings menu, clock + and save. The 20x20 icons were drawn by mameise for the T7Emu ESP32 version. +- No ROM of the Tama-Go or of a figure is in this repository. + +## T18Emu (`t18/`) + +- The ARM7TDMI core and the TG18 SoC model in `t18/src/core` come from the + T18Emu app by mameise. +- Changes for this project: a slim core for the Paradise, idle round skipping, + the translator from ARM and Thumb to Thumb-2 (`t18jit.c`, `t2enc.h`) and the + Paradise host (`t18/src/app`). It uses the Paradise hardware layer of TamaEmu + (`emu/src/emu`). Same license as the rest of this repository. +- No firmware of the Meets or On is in this repository. + +## DOOM (`doom/`) + +- **DOOM** source code by id Software, released under the GNU GPL. +- **PrBoom** (based on BOOM, LxDoom and LSDLDoom), Copyright (C) 1999 id + Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman; + (C) 1999-2000 Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze; + (C) 2005, 2006 Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko. +- **GBADoom** by doomhack, https://github.com/doomhack/GBADoom, with additions + by Kippykip. +- **nRF52840 Doom** by Nicola Wrachien (next-hack), + https://github.com/next-hack/nRF52840Doom. + + These are licensed under the GNU GPL version 2 or (at your option) any later + version (copy of version 2 in `doom/LICENSE-GPL-2.0`). The Paradise port in + `doom/src/pdoom/dev` is by mameise under the same terms. +- **MCUDoomWadUtil** by Nicola Wrachien, based on GbaWadUtil by doomhack, + GNU GPL version 2. It is used as a separate program: compiled to WebAssembly + (`doom/mcuwad.wasm`, source in `doom/src/wasm`, command line version in + `doom/src/umwandler`) and only fed with the WAD file chosen by the user. +- **printf** by Marco Paland (PALANDesign Hannover), MIT License, notice in + `doom/src/pdoom/plat/printf.c`. + +No WAD file and no DOOM game graphics are part of this repository. The user +brings their own WAD; the Studio converts it in the browser. + +## V1Emu (`v1/`) + +- **TamaLIB** by Jean-Christophe Rona, https://github.com/jcrona/tamalib, + GNU GPL version 2 or (at your option) any later version (copy in + `v1/src/core/LICENSE_tamalib`). The core in `v1/src/core` is TamaLIB with + changes for the Paradise (decode table, saving the CPU state, the Digimon's + LCD, keys, buzzer and contact P20). +- The Paradise program (`v1/src/app`) and the icons are by mameise. +- No ROM of a Tamagotchi or Digimon is in this repository. + +## V3Emu (`v3/`) + +- **BrickEmuPy** by azya52, https://github.com/azya52/BrickEmuPy, released + under **CC0 1.0 Universal** (public domain dedication: the author gave up all + copyright, the work may be copied, changed and used for any purpose without + asking and without credit). Credit is given here anyway. + From it come: the Sunplus SPLB32 core (`cores/SPLB32.py`, the 256 + instructions translated to C by `v3/gen/py2c.py`, the rest by hand), the + HT24LC08 EEPROM (`peripherals/HT24LC08.py`), the infrared byte link + (`peripherals/CON_V3_IR.py`) and the positions of the 32 x 30 dots and the + ten icon segments of the Connection V3 face (`assets/Tamagotchi_v3.svg`, + only the positions, in `v3/src/core/v3lcd.inc`). +- The C port, the timer and halt speedups, the Paradise program + (`v3/src/app`) and the icons are by mameise; with the rest of this + repository under the GNU GPL version 3. +- No ROM of the Connection V3 is in this repository. + +## GBEmu (`gb/`) + +- **Peanut-GB** by Mahyar Koshkouei, https://github.com/deltabeard/Peanut-GB, + **MIT License** (the notice is at the top of `gb/src/core/peanut_gb.h`). + Parts of it come from SameBoy by Lior Halphon (MIT), marked in the file. + Changed for the Paradise: the ROM is read straight from the flash window + (marked "Paramix"). +- The Paradise program (`gb/src/app`) is by mameise; with the rest of this + repository under the GNU GPL version 3. +- No Game Boy game is in this repository. + +## ArduboyEmu (`ab/`) + +Own code (mameise), no code of other emulators. The CPU was checked against simavr (GPL) on the PC only; simavr is +not part of Paramix Studio. Arduboy is a trademark of Arduboy Inc. + +## PokeMiniEmu (`pm/`) + +- **PokeMini** by JustBurn (Team Pokeme), libretro version https://github.com/libretro/PokeMini (commit 132111b), + **GNU GPL version 3 or later** (copy in `pm/src/core/LICENSE_pokemini`). The core in `pm/src/core` (CPU, PRC, + LCD, timers, IRQ, I/O with the EEPROM, sound) comes from it, with the **FreeBIOS** (Team Pokeme, in `freebios.c`). + Changed for the Paradise: `pm_glue.c` instead of PokeMini.c (no files, no colour PRC, the cartridge read from the + flash window), the LCD read by the program for the shown frames (`PM_FASTLCD`), small stubs (`pm/src/stub`). +- The Paradise program (`pm/src/app`) is by mameise; with the rest of this repository under the GNU GPL version 3. +- No Pokemon mini game and no Nintendo BIOS are in this repository. + +## Wolfenstein 3D (`wolf/`) + +- **Wolf4SDL** by Moritz "Ripper" Kroll and others, maintained by KS-Presto, + https://github.com/KS-Presto/Wolf4SDL (commit dc8b250), based on the + Wolfenstein 3D source code by **id Software** (1992). Wolf4SDL offers the + original source license (`wolf/src/w4/license-id.txt`) or the **GNU GPL + version 2 or later** (`wolf/src/w4/license-gpl.txt`); used here under the GPL. + John Carmack confirmed the GPL relicensing of the Wolfenstein 3D source. + The OPL emulators of Wolf4SDL (MAME license) are not used. +- Taken: the game parts (`wolf/src/w4`, changes marked `PARAMIX`). New for the + Paradise (`wolf/src/pmx`, `wolf/src/dev`, `src/wolf.js`) by mameise; with the + rest of this repository under the GNU GPL version 3. +- No game data of Wolfenstein 3D (maps, graphics, sounds) is in this repository. + +## Formats and protocols + +- File formats of the Paradise flash (archive, sprites, scenes): + https://github.com/GMMan/tama-para-research by GMMan. +- The rest (settings block, ID pages, field slots, app loading and the PAU1 + flash protocol in `flash/`) was worked out for this project. + +## Trademarks + +Tamagotchi is a trademark of BANDAI. DOOM is a trademark of id Software. All +trademarks belong to their respective owners and are only named to describe +what this project works with. This project is not affiliated with, endorsed or +sponsored by them. It contains no firmware, +ROM, WAD or game graphics of theirs; you need your own devices and files. + +- **TamaLIB** by Jean-Christophe Rona, https://github.com/jcrona/tamalib, + GNU GPL version 2 or later (copy in `v1/src/core/LICENSE_tamalib`). V1Emu + (`v1/src/core`) is TamaLIB with small changes for the Paradise (decode table, + state as bytes, names of the hardware functions). diff --git a/README.ko.md b/README.ko.md new file mode 100644 index 0000000..a29d580 --- /dev/null +++ b/README.ko.md @@ -0,0 +1,61 @@ +# Paramix Studio ITOSM 한국어판 + +원작 mameise / Paramix Studio 1.7.4를 기반으로 한 수정판입니다. +웹 번역 705개, 모듈 오류 번역, 선택형 한국어 A+C 본체 메뉴를 추가했습니다. +원본: https://github.com/mameise/Paramix-Studio + +## 범위와 검증 한계 + +- 웹에서 한국어·영어·독일어를 선택할 수 있습니다. 처음에는 한국어입니다. +- 본체 메뉴 탭에서 한국어 A+C 메뉴를 선택합니다. 원본 영문 메뉴도 포함되어 있습니다. +- A+C 메뉴는 한글 문구와 그림 중심 화면을 사용합니다. ROM의 한국어 이름 표와 완성형 한글 2350자 입력을 지원합니다. 이름 변경 시 본편의 한국어 이름과 유효한 현재 개체 이름 캐시의 확인값도 갱신합니다. +- 기기 기록·실기 육성·실기 저장 복원은 수행하지 않았습니다. 본체 메뉴는 실기 미검증 시험판입니다. +- 파일 열기·편집은 브라우저에서 처리합니다. 본체 전체 ROM 추출 시 미확보 기종만 서버 비공개 백업 후 PC 다운로드합니다. 기종당 1개이며 관리자 승인 전까지 공개되지 않습니다. +- 복원은 공개된 백업의 SHA-256·기종을 확인한 뒤 기존 UART 기록기로 파일 그대로 기록합니다. 실제 기기 시험은 미수행입니다. +- `server/app.py`는 별도 `/data` 볼륨의 기종별 백업과 관리자 설정을 관리합니다. 비밀번호는 scrypt로 저장하고 세션은 HttpOnly·Secure 쿠키를 사용합니다. 펌웨어와 관리자 설정은 소스 배포에 포함하지 않습니다. +- 회원가입은 선택 사항입니다. 회원별 160MiB/10개 개인 보관함은 `server/members.py`와 `/data/members.sqlite3`에 저장하며, 로그인 상태의 본체 ROM 추출 시 개인 백업도 수행합니다. 개인 업로드는 공개용 기종 수집과 분리됩니다. +- 회원은 업로드·다운로드·이름 변경·삭제·편집기 열기·개인 덤프 복원·비밀번호 변경·복구 코드 재설정·탈퇴를 사용할 수 있습니다. 동일 파일은 중복 보관하지 않고, 용량이 차도 기존 파일을 자동 삭제하지 않습니다. +- 관리자는 가입 허용, 회원 보관함 전체 저장 한도(기본 5GiB), 회원별 파일 수, 계정 정지를 관리합니다. 개인 파일을 공개로 전환하는 기능은 제공하지 않습니다. +- 회원 세션은 재시작 후에도 유지되며, 로그아웃·비밀번호 변경·복구·계정 정지 시 해당 세션을 무효화합니다. 관리자 계정도 개인 보관함을 이용할 수 있으나 회원 로그인만으로 관리자 권한을 얻지는 않습니다. +- 여섯 지역 확장은 회원 서비스입니다. 비회원 화면은 음영 처리되며, 통합 조립 코드는 `/api/member/six.js`에서 로그인 확인 후 제공합니다. 저장 시에도 로그인 상태를 다시 확인합니다. 기존 제이드 포레스트 네 지역 확장과 기본 편집은 비회원에게 유지합니다. +- 여섯 지역 통합에는 트로피컬/글레이셔 원본과 랜드/워터/스카이 중 하나의 원본이 필요합니다. 이 두 원본은 현재 확보하지 못했으므로 실제 여섯 지역 결과 ROM 및 실기 동작은 검증하지 못했습니다. 해당 기능은 공개된 upstream 알고리즘을 사용합니다. +- GPL 원본/수정 소스는 계속 공개합니다. 회원 제한은 이 웹 서비스의 기능 접근 제한이며 공개 소스를 별도로 빌드하는 것까지 차단하는 방식은 아닙니다. + +## 빌드 + +Node.js로 `node scripts/localize-web.cjs`와 `node scripts/build-menu-ko.cjs`를 실행합니다. +`Dockerfile.builder`로 빌드 이미지를 만들고, 소스를 `/src`로 연결한 컨테이너에서 +`sh feld/src/feld/build-ko.sh`를 실행합니다. 생성된 `feld-ko.bin`, `feldc-ko.bin`을 +`feld/`로 복사한 뒤 `node build.js`를 실행하면 `dist/index.html`이 생성됩니다. +컴파일 도구: Debian bookworm의 clang/LLVM 14, LTO, -Oz. +일반 한국어 메뉴는 32 KB 이하여야 하며 빌드가 이를 검사합니다. + +## 테스트 + +웹 화면의 실행·언어 전환·번역 누락·본체 메뉴 선택/인식 검사는 +`npm --prefix test install` 후 `node test/ko-web-test.cjs`로 실행합니다. +이 검사는 jsdom 기반이며 실제 브라우저의 화면 배치나 USB 연결 검사를 대신하지 않습니다. + +`feld/src/feld/preview-ko.c`는 자체 생성 데이터로 화면을 확인하는 PC 전용 도구입니다. +상용 ROM을 포함하지 않습니다. 같은 디렉터리에서 다음과 같이 실행합니다. + +``` +mkdir -p qa +gcc -w -fsanitize=address,undefined -g preview-ko.c -o preview-ko +./preview-ko qa +``` + +## 저작권 + +원본 및 수정 프로그램: GPL-3.0-or-later. LICENSE와 NOTICE.md를 함께 제공합니다. +한글 비트맵은 quiple의 Galmuri9에서 필요한 글자를 추출했습니다. +글꼴 원본과 라이선스는 `third-party/Galmuri9.bdf`, `third-party/Galmuri-OFL.txt`에 있습니다. +이 프로젝트는 BANDAI 또는 각 게임 제작사의 공식 제품이 아닙니다. + +## 2026-11-10 기능 갱신 + +- 서버 우선 기기 백업과 쿠키로 보호한 임시 다운로드 및 재시도를 지원합니다. 관리자 설정으로 PC 직접 저장을 선택할 수 있습니다. +- 에뮬레이터와 추가 게임은 관리자 설정에서 기본 OFF입니다. +- 육성 편집은 성장 단계와 종류 및 레벨과 배부름과 행복 및 건강 회복을 지원합니다. 나이와 수치의 지속 고정은 미구현입니다. +- 테스트는 보유한 제이드 포레스트 ROM과 PC 화면 및 모의 기기에서 수행했습니다. 다른 기종의 결과 ROM과 실제 본체 작동은 별도 검증이 필요합니다. +- 홈페이지에 전체 소스 압축파일을 배포하지 않습니다. 공개 저장소: https://gitea.itosm.co.kr/syskiller/tamagotchi-paradise-ko diff --git a/README.md b/README.md new file mode 100644 index 0000000..c7590a6 --- /dev/null +++ b/README.md @@ -0,0 +1,751 @@ +# Paramix Studio + +A tool for the Tamagotchi Paradise that runs in your browser. Open a dump of the +device (the 16 MB flash image), change it, save a new ROM and write it back to +the device over a UART dongle. + +- **TamaEmu:** build an emulator for colour Tamagotchis into the ROM (Plus Color, + iD L, P's, 4U+, 4U). You bring your own firmware (4 MB or 8 MB). Download + content (food, clothes, games ...) can be added for the 8 MB firmware. + Optionally starts when the Paradise is switched on. +- **T7Emu:** the Tama-Go with its figures (also the full figure dumps) and the + Tamagotchi Friends, from your own ROMs. +- **T18Emu:** the Tamagotchi Meets / On (TG18 firmware). + Grow up on the device, items and Tamapoints from MyMeets files, visits and + marriages over mixing-meets.com through the UART dongle. +- **V1Emu (test):** the first Tamagotchis (P1 Japanese and English, P2, Angel ...) and the Digital + Monster V1, V2 and V3, from your own ROMs; small enough for many of them on one ROM. +- **V3Emu (test):** the Tamagotchi Connection V3, from your own ROM. +- **Visits between two Paradise:** plug two Paradise together at the top: + T18Emu, T7Emu (Tama-Go), TamaEmu (P's, iD L) and V1Emu (Digimon battles) + talk to each other as two toys would. +- **More emulators:** up to twelve more programs next to the main one, started + from the on-device menu. +- **Start device:** turn the Paradise into a device for programs only: after + the setup (language, clock) a menu with your emulators and DOOM comes up, + with its own settings (sound, display time) and a DOWNLOAD entry for the + PC. All pictures of the game go, which gives about 5 MB more room. +- **DOOM:** build DOOM into the ROM from your own DOOM.WAD. +- **More fields:** Land, Water and Sky on Tropical and Glacier, Sky on Jade + Forest, with pictures, special characters and the matching planet. +- **Menu:** an on-device menu with several saves (each on a field of your + choice), items in the bag, Tamapoints and changes to the Tama (level, care, + character). +- **Save editor:** change level, character and care of a Paradise save + (a .tamasave or the save inside the loaded ROM). +- **Characters:** export every character as an image sheet, edit it in any paint + program, upload it again. Digimon from DIM cards too. +- **Names:** rename fields, Tamas and items; move the eyes and the mouth of a + character; take characters from TamaSma cards. +- **Device:** read the ROM from the device and write a new one, only the parts + that changed, keeping the saves on the device. +- **Save games:** back up the Paradise and the TamaEmu save on their own and + restore them, for example to play on in the TamaParadise or TamaEmu app. + +Everything runs locally in one HTML file. Your ROM, firmware and WAD never leave +your computer. The Studio contains no ROM, no firmware, no WAD and no game +graphics; you need your own. + +## Disclaimer + +Use this tool at your own risk. Changing a ROM and writing it to a device can +make the device unusable or erase its saves, and something can always go wrong +(a loose cable, an empty battery, a bug). Read a backup of your device first and +only use the tool if you know what you are doing. + +This software is provided "as is", without warranty of any kind. The authors +are not liable for any damage to devices, data or anything else that results +from using it (see sections 15 and 16 of the [LICENSE](LICENSE)). + +## Trademarks + +Tamagotchi is a trademark of BANDAI. DOOM is a trademark of id Software. All +trademarks and product names belong to their respective owners. They are only +named to describe what this tool works with. This is not an official product +and is not affiliated with, endorsed or sponsored by any of these companies. +The repository contains no firmware, ROM, WAD or game graphics of theirs; use +your own devices and your own files. + +## Use + +1. Download `ParamixStudio-vX.Y.Z.html` from the + [Releases](../../releases) and open it in Chrome or Edge (or open the GitHub + Pages site of this repository). +2. Open a ROM. Recognised editions: Land, Water, Sky, Jade Forest, Tropical, + Glacier. No dump yet? Read one with the Device button (see below). +3. Make your changes in the tabs. "Your new ROM" at the top shows what the new + ROM will contain and how full the flash is. +4. "Save new ROM" downloads the new ROM, or write it straight to the device. + +### Characters +Click a character, download its sheet, edit it (keep the size), upload it. +Extras: all sheets as ZIP, upload many sheets at once, take characters from the +image of a character card, number test ROM (each character shows its number). + +Rules the tool keeps on its own: eye images keep their byte size, new colours +use palette slots 8 to 15 (outline slot 1, slots 2 to 7 are recoloured by the +game), archive checksums are recalculated and every changed image is read back +before saving. + +### Fields +Every edition carries complete character sets for several field types: Land, +Water and Sky ROMs have all three, Jade Forest also has Sky, Tropical and +Glacier carry all six. Each field has the same structure: 1 child, 4 teens, +17 adults. In the Characters tab, "Field" shows only one field's characters. +"Field as ZIP" exports everything of that field (characters, field map, +close-up backgrounds) for editing; upload the edited sheets as usual. +"Load field from ZIP" puts a field from the same or another ROM into the +selected field. Eye images must not get bigger than the original ones, so +characters whose eyes do not fit stay original. + +### TamaEmu +Tab "Emulator": choose the firmware of a colour Tamagotchi (4 MB or 8 MB image). +Known: Plus Color, iD (also Lovely Melody), iD L, P's, 4U+ and 4U. The 4U and 4U+ firmware keeps asking +its NFC chip, which the Paradise does not have; TamaEmu answers in its place, +so the menus react to a single press ("4U: emulate the NFC chip", on by +default). The P's and 4U firmware is bigger and +uses the room the menu needs for the field switch, so the two do not go together. +It is packed into the ROM on save. On the device: hold A and C on the home +screen to start, hold the wheel to go back (the state is saved and continues +next time). To start over from the Tamagotchi's own save instead, release A +and C and press the wheel within the first 3 seconds: the saved session is +dropped and you are back on the Paradise; the next start begins fresh. + +Battery change (1.6.8): the emulators no longer need the wheel to keep the game. Every emulator writes +its run state by itself when the screen goes dark (10 minutes after the last time at the earliest) and +otherwise every 30 minutes after 10 s without a key (V1Emu: every 15 minutes). A session is used once: +after it has been resumed it is dropped, so an old one never wins over newer play. Switches SESS_ONCE +and SESS_AUTO in the build scripts (SESS_T1/SESS_T2 for shorter test times). + +TamaEmu and T18Emu settings (1.6.8): volume (normal, quiet, loud, off), brightness (5, 10, 20 .. 90, 100 %), +screen off after (as the toy, 10 s to 10 min; the first key only wakes). In the Studio under ▾ in the +program's row (flags bits 16-22 and 24-27, switch HW_OPTS), and on the device with a short press on the wheel +(A next line, B change, C close; switch OPT_MENU). A change on the device is kept in the save area +(TamaEmu: its last sector, T18Emu: behind the session) and applies until the Studio's setting changes. + +Card tab (1.6.8): besides character cards (4 MB) also TamaSma cards (1 or 2 MB): their characters are drawn +from body and face layers (accessories that live in the toy are left out) and go into a figure like card characters. + +Names (1.6.8, tab Names): fields, Tamas and items get new names (capitals, digits, space and . & ' ! ? /). +They go into every text table with Latin letters (EN, FR, DE, PT, ES, IT; third file of the asset +archive), laid out anew, and into the menu's field names. With six fields switched on (Tropical, Glacier) +the names of Land, Water and Sky can be changed too. + +Eyes and mouth (1.6.8, figure drawer): "Move the eyes" and "Move the mouth" shift a character's eye or mouth layer in all its composite entries +on the field (small figure half as far). The game copies these entries when a Tama hatches or grows, +so a Tama that is already there keeps its old eyes until then. The preview steps through every pose of the big +and the small figure; "This pose only" moves eyes or mouth of the pose shown alone (for own figures). A layer of the data pack (table 15) is a mask +word, one word per set bit (x, y, sub-image, ..., type) and the picture last; x and y are the picture's centre. + +Six fields: the field pictures taken from the Land, Water or Sky ROM show under All Sprites once the new ROM +is loaded, but they cannot be changed (they share their data and are made again when the fields are updated). + +Start when switched on (tick under ▾ in the main program's row, tab Emulator): after power-on the +Paradise starts the emulator right away. Holding the wheel goes back to the +Paradise, which stays there, also when its screen goes dark. A and C, the +reset button or a battery change bring the emulator back. Hold B while the +Paradise starts to skip the emulator once. + +Two colour Tamas in one ROM (1.6.9, start device, e.g. iD L as the main program and P's in the menu): each +starts its own firmware (switch `APP_SELF`). The iD L clock no longer runs fast while its screen is off and only +finished pictures go to the panel (1.6.8). When the colour Tama wakes its display without its own light (the P's +does it every 20 minutes for about 9 s, all night) the Paradise's light stays off: it follows the toy's own +backlight, a key or a tone (1.6.9, switch `BL_GUEST_PWM`). + +Updating the emulator: open your ROM with the emulator in a newer Studio and +save it (do not choose the firmware again). Only the emulator program is +replaced. Written with "Keep saves", the Tamagotchi keeps its save and the +saved session. Choosing the firmware again starts the emulator fresh. + +The guest may write anywhere in its flash (item stores, shop purchases, its +own reset). Written parts of blocks that are empty in the firmware go into +spare pages behind the packed firmware (up to 0xD40000). + +With the 8 MB firmware the tab lists the download content stores (meals, +snacks, clothing, accessories, items, daily items, wallpapers, games, +destinations). Add `.jpg` download files (several at once), remove entries per +slot. + +### T7Emu +Tab "Emulator": choose the ROM of the Tama-Go (640 KB) instead of a firmware. +The ROM of the Tamagotchi Friends (768 KB) works the same way (test version, +no figures). +Figure ROMs (the ones that start with AA 55) can be added with "Add figure", +also the full figure dumps (4 MB, with the extra games), and removed with the cross next to their name. Everything is packed +into the ROM on save; you bring your own ROMs. + +On the device: hold A and C on the home screen to start, hold the wheel to go +back (the state is saved). A short press on the wheel opens the settings: A +goes to the next line, B changes it, C goes back or closes. Figure, background +colour, Tama colour, light and dark grey, screen (Large fills the width, Pixel +exact keeps every pixel the same size), pixel look, grid, pixel view, icons, +sound (off, quiet, medium, loud), light (5 to 100 %), dim after, dim to (1 to 50 %), screen off after, clock and language. The settings stay on the device. When the +game asks for the time, T7Emu fills it in (the Paradise's time, or the local +time written along by the Studio, or after a restart the game time from before); +birthday and name follow. The game clock follows the Paradise clock (see "How +the emulators behave"). If T7Emu hangs: start with A and C, release them and +press the wheel within the first 3 seconds. + +Since 1.6.13 T7Emu translates the game code while it runs (much less work for the chip) and saves power with the +screen off: it runs slower and sleeps between the seconds; a call still rings and lights the screen. The game clock +no longer skips seconds. + +Updating: open the ROM in a newer Studio and save it. Written with "Keep +saves", the Tama-Go keeps its save as long as its ROM is the same. + +Gotchi Points (1.6.9, under ▾ in the Tama-Go's row): 0 to 999999, written into its saved EEPROM like an +imported save (the Tama stays, the running state starts anew). + +PC passwords (1.6.9): Door and PC of the Tama-Go work. The game's nibble helper at $3080 was missing, so +the login password was always 000000000000 and no logout password was taken (switch `T7_PW_FIX`). + +Battery, keys and tone (1.6.9): the game's wait for the next frame is added up at once and its STOP +(the Tama-Go stops its CPU until a timer or a key) halts the emulated CPU too, as in TamaGo for the Pebble; +about 80 % of the emulated time no longer needs the Paradise's CPU (switches `T7_IDLE`, `T7_STOP`). For 1 s +after a key there is no STOP (`T7_STOP_KEYACT`). Every press is counted every millisecond (after 30 ms +released, against bouncing contacts) and goes to the game for at least 120 ms, then 100 ms released +(`T7_KEYQ`): quick presses are kept in order instead of lost. Tones are queued and played on the real clock, +80 ms late, so melodies keep every note (`T7_TONE_Q`). The main loop sleeps whenever it is less than one 2 ms +step behind (`T7_WFI_FIX`, 1.6.9; before it spun through every other millisecond). Details in `t7/README.md`. + +### More emulators (1.6.0) +"Choose firmware or ROM" (tab Emulator) takes the main emulator first; every further file goes to the +list of further programs (Tama-Go, Friends, V1Emu ROMs, up to twelve). Each entry has a × to take it +out again. The filled star marks the main program (DOOM when it is in the ROM; in a start device the emulators +then all go to the menu; DOOM has its own × and ↺ in the list), a click on an empty star makes another one the main +program. In a normal ROM a colour Tama or TG18 always becomes the main program. Each program goes in once. + +Editions whose firmware reaches past 0x0A0000 (Jade Forest wave 2 up to 0x0A1683, Tropical and Glacier up to +0x0B5E00; 1.6.9, GitHub issue) have no room for a main program there. The Studio then puts every program into +the menu: in a normal ROM Tama-Go, Friends, V1Emu and V3Emu (A and C, with field switch or items switched on), +colour Tamas and TG18 only in a start device. 0x0A0000.. of the firmware stays untouched. DOOM as +the main program of a normal ROM can start when switched on (▾ in its row). +▾ opens a program's row: its settings (clock per program, NFC for a 4U, start when switched on +for the main one) and its figures or download slots. The overview "Your new ROM" shows all emulators in one +entry, the main one in bold. Every program has its extras in its own row, wherever it sits (1.6.8): figures for every Tama-Go, +download content with ⓘ for the slots for every 8 MB colour Tama (iD L, P's, 4U+, 4U). The room on the ROM decides +what fits. Each program keeps its own save: T7Emu 24 KB, TamaEmu its run state (320 KB) and spare pages, +T18Emu its save area, V1Emu 4 KB session plus 4 KB settings. With "Keep saves" a colour Tama keeps its save +when only download content was added; the first item in a still empty store needs a new block and starts the +save anew (the Studio says so). In a start device (see below) also colour +Tama firmware (TamaEmu) and one TG18 firmware (T18Emu). In the menu each +program is named after its firmware (TAMA-GO, FRIENDS, ID L, 4U+, PS, +PLUS COLOR, TAMA MEETS). Each one gets its own copy of T7Emu, its +own save and its own ROM, placed from the top of the emulator area (0xD40000) +down: program 64 KB, save 24 KB, then the ROM. They are started from the menu +(A and C, then "PROGRAMS"), so the field switch or the items must be switched +on in the Menu tab. In the Save tab a +choice "T7Emu" picks which one a save.bin is backed up from or taken over into. "Keep saves" keeps +the save of each one as long as its ROM is the same; a T7Emu or V1Emu that changes its place (main program and +menu) takes its save along. The Save tab has two parts: "Programs" lists every program (main and menu) to back up or restore its +save (T7Emu, TamaEmu, V1Emu), "Paradise" holds the Paradise save and its editor. + +### V1Emu (1.6.8, test version) +The first Tamagotchis and the Digital Monster: ROMs of 12 KB or 16 KB (Epson E0C6S46 and E0C6S48, as +TamaLIB and MAME read them). Known by name: Tamagotchi P1 and P2, Angel, Morino, Umino, Yasashii, +Genjintchi, Tamaotchi, Digimon V1, V2 and V3; other ROMs of the same kind run as well. Each one takes about +88 KB (program, session, settings, ROM), so many fit next to the other programs; the menu takes up to +12 further programs. Choose the ROM with "Choose firmware or ROM", it goes to the menu. + +On the device: A, B and C as on the toy. Wheel short: settings (colour, grid, shadow of the unlit dots, +icons on or off, brightness of the unlit icons, sound, light (5 to 100 %), dim after, dim to (1 to 50 %), +screen off after, clock, language, +A next line, B change, C close). Digimon V1/V2 and Yasashii have their LCD the other way round; V1Emu turns them (flags bit 5). Turning the wheel shakes the toy (Angel's shake sensor). Wheel long: save and back. The toy is +paused while you are away. The eight LCD icons are our own pictograms. The Digimon has its own icon +segments, takes its keys by interrupt and beeps with the one-shot buzzer; V1Emu does all three (1.6.8). + +V1Emu can be the main program too (star in the list): A and C on the home screen, start when switched on (▾). +Shake (the Angel's sensor): turn the wheel. Icons: the Angel and the Digimon have their own sets, the others the P1/P2 set for now. + +The Digimon's LCD is mounted the other way round: V1Emu turns it (and its icons). The Digimon V3 (1.6.9) is +handled like V1 and V2: turned LCD, the Digimon icons, its clock at 0x1A (checked on the host: set and running as +the V1), battles over the contacts (`V1_LINK`; its send and receive routines are the same as in the V1, at 0x0B06 +and 0x0B5B). + +Clock (1.6.8): for Tamagotchi P1, P2, Angel, Morino and the Digimon V1/V2/V3 V1Emu takes the Paradise's time at every start +(tick "Take the clock from the Paradise" under ▾ in the program's row, and "Clock: Auto" on the device). +On a fresh start it first sets the toy's clock with the toy's own keys (B, B, A, C), so the Angel comes down +on its own. For the other ROMs set the clock in the game as on the toy. +After the start the toy's clock is checked against the Paradise's time and set again when it is off (1.6.9, +switch `V1_CLK_CHECK`; a resumed P2 kept its old time). Register B of the toy is kept with the running state +(1.6.9, `V1_REGB`; it was 0 after a resume). + +Since 1.7.0 V1Emu behaves like the other emulators: sound in four steps (off, normal, loud, quiet) played in real +time (`V1_VOL`, `V1_TONE_Q`), the screen comes on when the toy calls (`V1_CALL_WAKE`), deep sleep with the screen dark +(`V1_PW`, as V3Emu: internal 12 MHz clock, the toy's time is run in one go after each RTC second), the battery +display smoothed and the empty battery handled as described under Battery. + +### V3Emu (1.6.9, test version) +The Tamagotchi Connection V3: ROM of 512 KB (Sunplus SPLB32, a 6502, as BrickEmuPy reads it). Choose it like a +V1Emu ROM ("Choose firmware or ROM"); the Studio treats it as a V1Emu (same settings block and save layout) and puts +V3Emu in instead of V1Emu. Main program: ROM at 0x940000. In the menu: about 584 KB (ROM, 64 KB aligned, then +program, session 4 KB, settings 4 KB). + +On the device: A, B and C as on the toy (left, middle, right). The screen shows the ten menu icons above and +below, lit as the toy lights them, and the 32 x 30 dots three times enlarged (setting "Icons" off: no icons, the +dots four times enlarged). The icon pictures are mameise's V3 icons (`v3/gen/icons.py` makes `icons_v3.h` from the PNGs). Wheel short: settings (battery, colour, grid in percent, +pixel view in percent (the unlit dots), icons on/off, icons inactive in percent (how strongly the icons that are off show), +sound, light, dim after, dim to, screen off after, clock Auto/Game (when the Studio knows the toy's clock), language; +A next line, B change, C close; switch `V3_SETX` for the percent settings and the clock line). Wheel long: save and back. The toy's own save (its EEPROM, 1 KB) is +kept in the settings sector and written 3 s after the game changed it; the running state on leaving, when the +screen goes off and every 15 minutes. If the game has saved since the last running state, it starts from its own +save, like the toy after a battery change. + +The core (v3/src/core) is ported from BrickEmuPy: the instructions are generated from its Python (v3/gen/py2c.py), +the rest follows it line by line, checked to the bit against it on the host. The timers only get the time when +something can happen, and while the toy has stopped its CPU the steps up to its next timer event are skipped at once. +Clock (switch `V3_CLOCK`): with "Take the clock from the Paradise" (on by default) V3Emu writes the Paradise's time +and date into the toy at every start: seconds 0x81/0x82, minutes 0x83/0x84, hour 0x85 (1..12) and 0x86 (PM), day 0x13D (ones) +and 0x13E (tens), month 0x13F. Only when the toy's clock runs, so set it once in the game; then it is checked and written again if +it is off. + +Connection (switch `V3_LINK`): two Paradise plugged together at the top, V3Emu on both, then the connection in the +game as with two real V3. The core turns the toy's infrared pulses into bytes and back (as BrickEmuPy's CON_V3_IR, +which links two emulators over a serial line); the bytes go as 'V' frames over the UART on the contacts (plink.h). + +V3Emu can start when the Paradise is switched on (main program, ▾ "Start when switched on"), like the others. + +### T18Emu +Tab "Emulator": choose the firmware of the Tamagotchi Meets or On (TG18, 8 MB) +instead of a colour Tama firmware. The Studio puts its used 64 KB blocks into +free blocks of the Paradise flash, from the top down (from 0xF00000, then from +0xD40000 downwards; empty blocks are left out), plus up to 10 spare blocks for +the save data the firmware writes later. T18Emu fills them by the 4 KB sector +(1.6.8): start, photo and diary need 30 sectors in 7 blocks, 6 spare blocks hold 96. A game that has grown up +needs more (a baby to child step was measured with 99), so in a start device the Studio adds spares up to 15 where +there is room (1.6.9, also to an installed T18Emu, behind its spares: the save stays), and a full pool takes over +sectors the firmware has erased (switch `T18_POOL_RECLAIM`). The bottom (from 0x830000) stays free, so the +field switch of the menu fits next to it on Land, Sky and Water. The program +has two parts: one is loaded into the PRAM, the other runs from the flash +(0x0F0000). + +On the device: hold A and C on the home screen to start, hold the wheel to go +back (the state is saved). The firmware keeps its own save in its flash as on the toy; the +first start sets that area up and takes a while. If T18Emu hangs: start with A +and C, release them, press the wheel within the first 3 seconds and confirm with A; the +firmware then starts over from its own save ("CONTINUE"). Busy scenes (a call) can still run a little slower than on the toy; melodies keep +their tempo anyway (played on the real clock, about 0.3 s late). The camera +(Item Box, Special) and the diary work on all nine known firmwares. + +Grow up (on the device, wheel short, line "Grow up"): as in the Android T18Emu, the Tama becomes an adult in +about a minute and a half (its age is put just before each step, the game clock runs fast only for that one game +minute, the step and its animation run in real time, care stays full, the screen stays on, the firmware does the rest). A Tama of the +first generation can be chosen (ten adults, the Sanrio firmware has Flowertchi); a child of a married pair grows +up like its parents. Pictures for the choice: the Studio has none; under ▾ in the T18Emu row "Choose pictures" +takes your own PNG files named after the character (Mametchi.png, Kuchipatchi.png ...) or its number (16.png), +or the folder erwachsen of the Android T18Emu with its erwachsen.json. They are scaled to 64x64 and stored at +0x0E4000 (main program only). + +Items (under ▾ in the T18Emu row): MyMeets files (tg18_gh..., _oy..., _as..., _ac..., _bg... .txt, also in a .zip) +go into the game's save, with a picture, the number of pieces (1 to 3) and a room. Tamapoints can be set. The game +must have run once (read the ROM from the device). The running state of the emulator starts anew, the Tama stays. A name in +Japanese letters shows as its number (Nr. 3006). T18Emu in the menu of a start device keeps its place when the ROM is +saved again. +With "Keep saves" ticked, writing items or Tamapoints to the device asks first: T18Emu's save is replaced by the +one in the ROM. + +The date (1.6.9, switch `T18_DAY_FIX`): the game counts the days itself and a new start (CONTINUE) loaded the day of +leaving; the days since are added once after the start. Started from the menu, a sleeping game is woken once +with a short C (`T18_WAKE_START`). + +Screen (1.6.9): the picture goes out whole once the game has finished drawing it, only the rows that changed +(1.6.6 to 1.6.8). The check value per row is now FNV-1a (`T18_SUM_FNV`): the old one gave the same value for +many different rows and left parts of the picture old (AM/PM on the clock, frames). One row per picture always +goes out (`T18_ROW_RR`), the first picture after the start is complete (`T18_PRES_FIRST`), and switching the +screen on no longer stops the game for 145 ms while the panel wakes (`T18_WAKE_ASYNC`). + +MixingMeets (1.6.9, under ▾ in the T18Emu row): visits and marriages over mixing-meets.com through the UART +dongle on the Paradise's contacts. Drag the "Paramix bridge" bookmark to the bookmarks bar once; disconnect +the Studio from the dongle ("Release UART" or close it); on the Tama CONNECTION, APP, VISIT; on +mixing-meets.com open Connect or Return, click the bookmark, then Select Tamagotchi and choose the dongle. +Click the bookmark again after every page change. The page's Bluetooth goes over the dongle to T18Emu, which +hands it to the firmware's Bluetooth module like the Android T18Emu (switch `T18_LINK`). + +### Visits between two Paradise (1.6.9) +Plug two Paradise together at the top (the connector crosses TX and RX), start the same program on both and +connect as with two toys. The programs talk over the contacts (UART1, 460800 baud), the Studio does not take +part (under ▾ it only says how). + +| Program | On both devices | +| --- | --- | +| T18Emu | CONNECTION, TAMAGOTCHI: playdate, gift, marriage (switch `T18_LINK`) | +| T7Emu (Tama-Go) | connection, TAMA-GO, VISIT or GAME; B on the visiting one (`T7_LINK`) | +| TamaEmu (P's, iD L) | P's: あそぶ, あそびにいく on one, ともだちをよぶ on the other; iD L: connection, iDL, PLAY (or SWAP ITEM) on both, B on one (`TC_IRLINK`, `LK_SYNC` since 1.7.1: the two emulators keep in step while they exchange) | +| V1Emu (Digimon) | choose and start the battle (`V1_LINK`, not yet checked with a real battle) | +| V3Emu | the connection in the game on both (`V3_LINK`, not yet checked on two devices) | + +Checked on the PC with two cores in lockstep; on the device see the test notes. + +### Game Boy (1.6.9) +Tab "Game Boy": choose Game Boy games (.gb, the black and white Game Boy; since 1.7.2 also Game Boy Color games, .gbc, run by GBCEmu `gb/gbc.bin`). They go +into the Paramix menu (switch the menu on in the tab "Menu"). The screen is shrunk from 160 x 144 to 128 x 115, nothing +is cut off. The keys are set in the tab for all games (default: A left, C right, B = B, wheel press = A, wheel up and +down, A+C Start). On the device: A+B+C together opens the settings (with Select and sound), holding the wheel for 2 s +saves and goes back. Battery saves of the games are kept. Sound: the Paradise's buzzer plays one tone at a time (the +melody or the effect). Since 1.6.12: holding the wheel keeps the whole game, the next start continues exactly there; +"Restart game" in the settings; two Paradise plugged together at the top work like a link cable (e.g. trading +Pokémon). Since 1.7.1 equal banks at the end of a game are stored once (Pokémon Red and Blue: 256 KB less, `GB_TRIM`). +Program and details: `gb/`. + +### Wolfenstein 3D (1.6.10) +Tab "Wolf3D": choose all files of your own Wolfenstein 3D together, the shareware (.WL1, episode 1) or the full +version (.WL6, six episodes), version 1.4. The Studio builds one data pack from them in the browser (nothing is sent +anywhere) and the game goes into the Paramix menu (switch the menu on in the tab "Menu"). Screen: the view 128 x 96, +below a status bar with face, health, ammo, keys, weapon, floor, lives and score. Sound: the game's PC speaker sounds +on the buzzer (no music). Keys as DOOM on the Paradise, set in the tab: A fire, B forward, C back, wheel turns (degrees +per step to choose), wheel press doors and switches, hold C + wheel weapon, B twice quickly run. Fixed: A+C menu, +holding the wheel for 2 s saves the game and goes back to the Paradise; "Continue" goes on at the next start. +Since 1.6.12 also Spear of Destiny (.SOD, 21 floors), as a second entry next to Wolfenstein 3D. +Game from Wolf4SDL (GPL), program and details: `wolf/`. + +### Master System (1.6.11) +Tab "Master System": choose your own Sega Master System games (.sms). They go into the +Paramix menu (switch the menu on in the tab "Menu"). The screen is shrunk from 256 x 192 to 128 x 96, nothing is cut +off. The keys are set in the tab for all games (default: A left, C right, B button 1, wheel press button 2, wheel up +and down, A+C Pause). On the device: A+B+C together opens the settings (with Pause and sound), holding the wheel for +2 s saves and goes back. Battery saves of the games are kept. Sound: the buzzer plays the loudest tone channel. +Since 1.6.12 also Game Gear games (.gg, 160 x 144 shrunk to 128 x 115, START on A+C), the whole game kept when +holding the wheel, and "Restart game" in the settings. Own emulator (Z80, video chip, Sega mapper), program and +details: `sms/`. + +### Pokemon mini (1.7.3) +Tab "Pokemon mini": choose your own Pokemon mini games (.min, also inside .zip files). They go into the Paramix menu +(switch the menu on in the tab "Menu"). The screen grows from 96 x 64 to 128 x 85 (3 dots to 4, mixed), with the grey +shades the games make by switching dots every frame. The keys are set in the tab for all games (default: A left, C +right, B = B, wheel press = A, wheel up and down, A+C = C, A+B shake). On the device: A+B+C together opens the +settings (with Power and sound), holding the wheel for 2 s saves the whole game and goes back. The games' EEPROM saves +are kept, export and import as .eep in the tab "Save". Without an own BIOS the free BIOS of PokeMini runs; an own BIOS +(4 KB, chosen in the tab) goes into the ROM next to the games. The Pokemon mini clock keeps running while the game +waits. Core: PokeMini (GPL), program and details: `pm/`. + +### Arduboy (1.7.3) +Tab "Arduboy": choose your own Arduboy games (.hex, also inside .zip files). They go into the Paramix menu (switch the +menu on in the tab "Menu"). The screen shows the Arduboy's 128 x 64 at 1:1, 3:2 or 2:1 height (setting on the device), +greys made by switching pictures come out grey. The keys are set in the tab for all games (default: A left, C right, +B = B, wheel press = A, wheel up and down). On the device: A+B+C together opens the settings (with picture size and +sound), holding the wheel for 2 s saves the whole game and goes back. The games' EEPROM saves are kept, export and +import as .eep in the tab "Save". Games that need a lot of computing run slower than on the Arduboy. Own emulator +(ATmega32U4, display, timers), program and details: `ab/`. + +### Simulated visit for the Paradise itself (1.6.9) +Under "Device" the Studio can play a second Paradise over the dongle, so one device is enough for a playdate. +The Paradise runs its normal game (no flash app). "Connect" above is not needed for it. + +1. Choose the edition the visitor comes from (Land, Water, Sky, Jade Forest, Tropics, Glacier), "Start", pick the dongle. +2. On the Paradise: planet menu, CONNECTION, PLAYDATE, then B. + +The visitor is a copy of your own Tama (its picture comes from your device, the Studio has no game data); only +the edition and its IDs are its own, so every edition is a friend of its own. At the young stage the Paradise +notes the edition of each partner (seen in its save after a visit from Water and one from Sky); the secret +characters want two other colours there. Whether the secret character then comes is to be checked on the device. +Protocol: GMMan's tama-para-research (TCP over UART, 460800 baud), code in `src/visit.js`. The Studio +answers as the device that was asked (the Paradise presses B), never breeds (it answers BREED 0). +Checked on the PC with the emulated Land against the Studio in the browser (Sky, Water, Jade Forest). + +### Battery (1.6.9) +Battery saving (1.6.9, switch `CLK_ECO`, `emu/src/emu/eco.h`): with the screen off T7Emu, V1Emu and V3Emu lower the +chip's clock (AHB prescaler `SYS_AHBCP` 0x45000010, Sonix TRM: SYSCLK / 2^n for core, memory and peripherals) step by +step from 96 MHz down to 12 MHz while the emulation keeps up (busy share from the DWT cycle counter every 500 ms: +below 35 % one step down, above 80 % one step up). If it falls 25 ms behind: full speed at once, then one step less +deep for 5 minutes. A key, the screen, a tone or link traffic (30 s) bring full speed. SysTick is set for 1 ms at +each step, a playing tone keeps its pitch. Measured in the Unicorn simulation with the screen off: V1Emu (P2) at 12 MHz, V3Emu and T7Emu at 48 MHz, +T18Emu (Meets in standby) mostly at 12 MHz. TamaEmu has it too (no simulation for it); on the device the busy share +decides how far each one goes down. ECO_LAG per program (T7Emu 400, TamaEmu 50, T18Emu 120, V1/V3 25 ms). +Tick check (1.6.9, switch `ECO_RTC`): T7Emu, V1Emu and V3Emu compare the millisecond tick with the Paradise's seconds +counter every 4 whole seconds; a clock step that counted fewer than 3800 ms is not used again until the next start, +T7Emu adds the missing time (its emulation catches up). The counts go into T7Emu's session sector at 0xFF0 +(clock steps found wrong | corrections << 8, ms added), so a dump shows them. + +Care and points on the device (wheel short, in the settings): T18Emu has "Tamapoints" (A next digit, B the +digit + 1, C OK, the wheel goes back without change) and "Full care" (hunger and mood full, not sick, no call), on +all nine known firmwares. T7Emu (Tama-Go and Friends) has "Gotchi Points" (up to 999999) and "Full care" (hunger +and happy 5 hearts). TamaEmu has "Gotchi Points" (up to 99999) and "Full care" with Plus Color, iD L (v050 to v055), +P's, 4U and 4U+ (hunger full and the happy bar as far as the game allows it: iD L friend level and +Plus Color HAPPY! by the medals, P's ring by the medals, 4U love ring by the stage). V3Emu has "Gotchi Points" (4 digits) +and "Full care" (hunger and happy 4 hearts). V1Emu has "Full care" for all twelve known ROMs (P1 also English, P2, Angel, Genjintch, +Morino, Tamaotch, Umino, Yasashii, Digimon V1 to V3; Digimon: hunger and strength). Other ROMs show no such lines. + +The settings of T7Emu, V1Emu, TamaEmu and T18Emu (wheel short) show the battery, e.g. "2.84V 80%", and the +home screen of a start device shows it bottom right. It is measured as the Paradise firmware does it: SAR ADC at +0x4003A000, channel 4 (P0.6), volts = sample x 3.3 / 1024; below 2.2 V the Paradise switches off (0 %), 3.0 V and +more count as full. Shared code `emu/src/emu/batt.h`, switch `BAT_SHOW`. "?" means no reading came. + +Empty batteries (1.7.0, switches `BAT_GUARD`, `BAT_PIC`): every emulator reads the battery every 20 s; twice in a row +below 2.21 V it saves everything, shows the Paradise's own "battery empty" picture for about 3 s and switches off, as +the Paradise does at 2.2 V. New batteries: it continues where it was. The Studio puts the picture (sprite 53 of Land, +Water and Sky, 54 of Jade Forest, 56 of Tropical and Glacier) into the last sector of the write protection block +(0xFFF000, "BAT1", 16 colours, run lengths). + +### How the emulators behave (TamaEmu, T7Emu, T18Emu) + +Starting and leaving: + +| What | TamaEmu | T7Emu | T18Emu | +| --- | --- | --- | --- | +| Start | A and C on the home screen | same | same | +| Wheel long (about 1.5 s) | save the state, back to the Paradise | same | same | +| Other way back (1.7.0) | tab "Menu", "Back from programs": wheel and A, wheel and C, or the wheel 5 s, for all emulators, Game Boy and Master System | same | same | +| Wheel short | nothing | settings menu | nothing | +| Wheel in the first 3 s after a resumed start | asks first (A yes, B no); yes drops the saved state, back to the Paradise; next start fresh from the Tama's own save | same | same | +| Autostart on, hold B while the Paradise starts | the Paradise starts instead of the emulator | same | same | +| Hold C while the device starts (1.7.2) | the flash app opens (way back when a program or a save leaves the screen black; C alone, A and C is the program key since 1.7.3) | same | same | +| Reset button, battery change | with autostart: the emulator starts again | same | same | + +Leaving with the wheel saves the whole state (CPU, memory, screen). The next +start continues exactly there. The Tama's own save (the one the toy keeps in +its flash or EEPROM) is written by the game itself as on the toy and stays even +when the state is dropped. + +The clock: by default ("Take the clock from the Paradise at the start", under ▾ in each +program's row of the tab "Emulator", set per program) every start sets the emulator's clock to the Paradise's time. The +time in between is not played through by the emulator: the Tama sees the clock +jump, as when the toy's clock is set. If the Paradise's time cannot be read +(for example right after its own first setup) the old way is used. Without +the tick: TamaEmu moves its clock on by the time the Paradise counted while +away, T7Emu lets the missed hours pass (up to 30, the pet ages), T18Emu moves +its clock on like TamaEmu. While running, all three keep their clock on the +Paradise's seconds counter, also when the emulation falls behind. + +The Paradise while a program runs (1.6.8, switch `PARA_BACK`): the Paradise does not run, but its +seconds counter does, and back home its firmware would live the whole gap at once (hunger, care +misses). So every program (and the menu) notes the Paradise's time when it starts (clock mailbox +"PCLK" at 0x20000FC0, kept over the restart) and, when it goes back, moves the "lived up to" date of the +Paradise's settings block (both copies, new CRC) on by the time spent outside, never past now. +The Paradise's clock itself stays right. Shared code: `emu/src/emu/paraback.h`. + +Brightness and dimming (1.6.8, switch `BL_PWM`): the light itself, not darker colours. Traced in the +Paradise emulator: the Paradise's own brightness setting (settings byte 8, bits 0..2) changes nothing but +the duty of timer 2 (MR1 = 85, 70 or 55 % of the period 0x17700; MR1 = period at the start). Left at that, +the counter never restarts at MR3 (match control 0 after the setup), so MR1 changes nothing; the emulators +keep MR3 reset on for a dimmed light (`hw_bl_set` in `emu/src/emu/hw.c`, switch `BL_MR3RST`), a 750 Hz PWM. +TamaEmu and T18Emu "Brightness" 5 to 100 %; T7Emu and V1Emu "Light" 5 to 100 % and "Dim to" 1 to 50 % +after the dim time (never brighter than the light). + +Battery: the emulators sleep (WFI) whenever they have caught up with real +time; waiting loops of the guest firmware are skipped, the screen only gets +the rows that changed, and the light goes off when the guest switches it off. +A running pet screen keeps the CPU busy, as on the toy. + +### DOOM +Tab "DOOM": choose your own `DOOM.WAD` (Ultimate DOOM or the shareware +`DOOM1.WAD`) and an episode. The WAD is converted in the browser. Keys can be +changed, also for a ROM that already has DOOM. Start with A and C like the +emulator. In a normal ROM only one of the emulator and DOOM fits; in a start +device both go together (the emulator becomes a further program of the menu). + +### Start device (1.6.8) +Tab "Menu": "Start device for programs only". Of the Paradise only its setup +stays (continue or new, clock, after "new" also language, birthday and planet +name). Then the PARAMIX menu comes up instead of the home screen: wheel +selects, B starts. Leaving a program brings the menu back. All pictures of the +game are replaced by tiny empty ones, which frees about 5 MB for programs. The +menu only comes once the Paradise has a save, so a fresh device runs its setup +to the end first. + +- SETTINGS in the menu: sound of the Paradise (off, low, medium, loud; its own + settings screen is gone) and the time after which the display goes dark + when no key is pressed (30 s to 5 min, or never). B changes, C saves. +- DOWNLOAD in the menu: starts the Studio's flash app, the Studio then connects + without the Paradise's download screen (which a start device no longer has). +- The Studio opens a start device again: the programs show in the Emulator tab + as further programs. Choosing the same firmware again does not add it twice. +- The room behind the Paradise's save (from 0xF00000) is used for programs as + long as there is no T18Emu (which needs it). +- A colour Tama in the menu (1.7.1, `GUEST_SPARSE`): almost empty firmware blocks that the game hardly reads + are kept as 8 KB parts, iD L about 250 KB and P's up to 450 KB less room. +- A colour Tama in the menu (1.7.3, `GUEST_LZ`): the cold firmware blocks (not hot, not read in the device + simulation, no download item store) are packed in 1 KB LZ4 parts behind the other blocks. The program (settings + version 5, `lz_off`) unpacks a part when the guest reads it into one of two 1 KB buffers at 0x20000400. iD L about + 1 MB less, P's 1.65 MB, 4U+ 1.45 MB, Plus Color 1.75 MB; in the simulation the same pictures and load as before. +- A save that ran for a long time (1.7.4, `BIG_LZ`): when its blocks do not fit unpacked (a P's or 4U with + 92 written blocks), the cold blocks are packed anyway, also without "Pack the firmware". +- Without the Paradise (1.7.2, `CLEAN_ROM`): second switch under "Start device". No Paradise code is left: + the load table at 0 starts the menu directly (not encrypted), the menu sets up the hardware itself, has its own + clock (SETTINGS, CLOCK; first start asks for it; sector "PMXK" at 0x0C0000) and passes the time to the programs. + Programs go from 0x010000 to 0xFF0000, the device's ID page stays (edition). Leaving a program goes through a small + restart routine at 0x110568 back to the menu. The empty battery shows a short text. A clean ROM opened in the + Studio shows only the program tabs and DOOM. +- DOOM without the Paradise (1.7.2, `DOOM_FREE`): DOOM is a program of the menu like the others, placed anywhere, + any program can be the main one. A second DOOM build (`doomf_app.bin`, `doomf_xip.bin`, built with + `XCF=-DDOOM_FREE`) reads the places of its WAD, level data, save and program part from its settings block (PDMC); + the program part runs at XIP 0x100A0000 with the window following it (so from 0x0A0000 up), the packed flash + pointers reach two 4 MB windows set from the WAD place. The start device with the Paradise keeps the DOOM build + with fixed places. +- Main program with DOOM (1.6.9): DOOM stays at its place, but the star in the + Emulator tab can make any program of the menu the main one. It is shown first + and, with "Start when switched on" under ▾, starts instead of the menu after a + battery change or a reset while it ran (hold B: the menu). Switch `FELD_AUTO` + in the menu program, settings version 9. + +### Menu (saves, fields, items, Tamapoints, Tama) +Tab "Menu": tick "Several saves (with field choice)", "Items and Tamapoints" +and/or "Change Tama". On the device, hold A and C on the home screen: wheel +selects, B confirms, C goes back. + +"Back from programs" (1.7.0): how to get back from the emulators, Game Boy and Master System to the Paradise or the +menu: hold the wheel (as before), hold wheel and A, hold wheel and C, or hold the wheel 5 s. The Studio writes the +choice into every program (the last word of its vector table, 0x13C, "EX" and the mode; `emu/src/emu/exitkey.h`). +The menu itself, while the screen is dark, sleeps deeply until a key or the wheel (1.7.0, `FELD_PW`). + +- Several saves: the menu keeps several saves and switches between them; a new + save starts on a field of your choice. + +- Field switch: every edition has three fields (Land/Water/Sky, Jade Forest: + Land/Water/Forest, Tropical and Glacier: Tropical/Glacier/Forest). Switching + packs the save of the current field and brings back the save of the chosen + one. A field that never ran starts like a new device. All fields share the + room for the saves, so one big save can use what the others do not need. +- All 6 fields (Tropical and Glacier): tick "All 6 fields" and choose your + own Land, Water or Sky ROM. The menu then offers Tropical, Glacier, Forest, + Land, Water and Sky. The pictures of Land, Water and Sky are taken from that + ROM; characters of all six fields are already in Tropical/Glacier. Without + the tick you keep the three own fields and still have several saves; on a + ROM that already has them, untick it to take the extra fields out again + (the device must be on one of the own fields). +- Game menu Fields: all fields from level 4 in the game's own field menu. +- Sky as 4th field (Jade Forest): tick "Sky as 4th field". Jade Forest + already has everything of Sky, no second ROM is needed. +- Planet to match the field: on by default. Land, Water and Sky then show + their own planet like the original devices. Untick it to keep the planet of + the edition. Changing it on Tropical/Glacier needs the Land, Water or Sky ROM. +- Neither works together with DOOM or the emulator (these editions have no + room for them). +- Items: put items into the bag and set their amount, with picture. The list + and the pictures come from your own ROM. Amount 0 ("REMOVE") takes an item out + again; items the game holds with amount 0 (eaten up) are not shown (switch `BAG_DEL`). +- Tamapoints: set digit by digit. +- Change Tama: level, care (fed, happy, healthy) and the character. +- TamaEmu or DOOM, when built in, is the last entry of the same menu. + +### Device (read and write over UART) +Needs a USB UART dongle with 3.3 V (CH340 or similar) and Chrome or Edge on a +computer (Web Serial). + +Wiring to the three contacts of the Paradise: left = RX of the dongle, +middle = GND, right = TX of the dongle. 3.3 V, not 5 V. + +1. On the Paradise open the download screen: Planet, A, Connect, Download, + Download. + On a start device choose DOWNLOAD in the menu instead. +2. Click "Device", then "Connect" and pick the port. The Studio loads its own + flash app into the device's RAM (nothing is written for this; switching the + device off and on returns to normal). +3. "Read ROM" reads all 16 MB (about 6 minutes), downloads the file as a backup + and opens it in the Studio. +4. "Write new ROM to the device" writes the ROM you put together. + - "Only write changes": the device's flash is compared first (CRC per 64 KB, + then per 4 KB) and only differing sectors are written. A typical change + takes about a minute instead of 40. + - "Keep saves": the game progress stays as it is on the device: the save area + of the Paradise, stored fields of the menu, the TamaEmu state and its guest + save, the DOOM save. The rest of the new ROM is written. To change the + edition (for example Glacier onto a Land), untick it. + Keep the device switched on while writing. Every sector is checked after it + is written and the whole flash is checked at the end. If something goes + wrong, leave the device on and write again. +5. "Back up save" reads only the game progress: the Paradise save as a + .tamasave for the TamaParadise app (with the device's clock), and if the + device runs TamaEmu also the colour Tama's save as a .sav for the TamaEmu + app. "Save to device" writes a .tamasave back. It must be from the same + edition; a save of another edition is refused. Only pages that differ are + written and the clock is set from the save. + +### Save games (tab "Save") +From the loaded ROM: the Paradise save as a .tamasave (without the clock, set +it in the app if needed), the TamaEmu save as a .sav and the T7Emu save as a .bin +(the save.bin of the T7Emu app). Import: a .sav or a T7Emu .bin goes into the +ROM (then save the ROM or write it to the device), a .tamasave goes straight to +a connected device. +Since 1.6.12 every program in the list has export and import: T18Emu the firmware with its save (.bin, as a +firmware for T18Emu), Game Boy and Master System the cartridge RAM (.sav, as other emulators use it; a kept game +state is dropped), Wolfenstein 3D and Spear of Destiny their saved game (.bin). An imported save wins over "Keep saves". +T7Emu saves written up to 1.6.8 may lie 2 bytes off in the flash (the page buffer was not word aligned, the flash DMA +takes words); the export finds them too and gives the right save.bin, and T7Emu from 1.6.9 reads them itself +(switch `T7_EE_SHIFT`). + +How to import a save (1.7.0): +1. Read the ROM from the device ("Device", read), or open the dump you read last. +2. Tab "Save": "Import" and choose the file. It goes to the program it belongs to (a T7Emu .bin to T7Emu, a TamaEmu + .sav to the TamaEmu with that firmware, a T18Emu .bin, .sav or .zip of the T18Emu app to T18Emu), whatever the list + shows. An emulator added in this session counts too. +3. Write to the device with "Keep saves" on. Only the imported save is replaced; the Paradise's own save and the saves + of all other programs stay as they are on the device. +Without "Keep saves" every save comes from the file, the Paradise's too: from a fresh read that is the same, from an +older file everything goes back to that file. When a program is added or removed in the same write, other programs +may get a new place. T7Emu, V1Emu, TamaEmu and T18Emu take their save along then (TamaEmu and T18Emu: the Studio +reads the sectors of their flash that changed on the device and puts them into the new place; the pet continues +from its own save, as after a battery change). If the device does not hold the loaded ROM, the Studio asks before +writing. Exporting all saves first is still a good idea. + +Slot (1.6.8): with the menu's "Several saves" (or the field switch) the menu keeps further saves in +slots. "Slot" picks which one: export takes it out of the ROM (unpacked), write to device puts the +.tamasave into that slot on the device (packed like the menu does it, header page last). With the +field switch a save only goes into the slot of its own field. The device must have the same menu +as the loaded ROM. + +Change save: open a .tamasave, or take the save inside the loaded ROM. Level, +character (names from your ROM) and care (fed, happy, healthy) can be changed. +A .tamasave is saved as a new file; the ROM's own save is changed in the ROM +(then save the ROM, or write it without "Keep saves"). "Close" puts it away. + +## Build + +``` +node build.js # creates dist/ParamixStudio.html +node test/unit_test.js # checks the core without a ROM +``` + +The other tests in `test/` need your own dumps and are run by hand (see the +first lines of each file). `test/flash_bridge_test.js` and +`test/ui_device_test.js` run the flasher against an emulated Paradise. + +GitHub Actions builds the HTML on every push and attaches it to a release named +after `VERSION` (see `.github/workflows/paramix-studio.yml`). Optional: Settings, +Pages, Source "GitHub Actions" publishes the page as a website as well. + +## Repository layout + +| Folder | What | +| --- | --- | +| `src/` | the Studio (HTML, JavaScript) | +| `emu/` | TamaEmu, the emulator program for the Paradise, with source in `emu/src` | +| `t7/` | T7Emu, the Tama-Go and Tamagotchi Friends emulator program for the Paradise, with source in `t7/src` | +| `t18/` | T18Emu, the Meets/On emulator program for the Paradise, with source in `t18/src` | +| `doom/` | DOOM for the Paradise and the WAD converter (WebAssembly), with source in `doom/src` | +| `feld/` | the on-device menu (field switch, items, Tamapoints), with source in `feld/src` | +| `gb/` | GBEmu, the Game Boy emulator program for the Paradise (core Peanut-GB), with source in `gb/src` | +| `sms/` | SMSEmu, the Master System emulator program for the Paradise, with source in `sms/src` | +| `six/` | helper code for six fields on Tropical/Glacier, with source in `six/src` | +| `flash/` | the flash app loaded for reading and writing over UART, with source in `flash/src` | +| `test/` | tests (`visit_test.js`: the simulated visit with a test key) | + +Every shipped binary (`emu/emu.bin`, `t7/t7.bin`, `t18/t18.bin`, `emu/stub_tpl.bin`, `doom/*.bin`, +`doom/mcuwad.wasm`, `gb/gb.bin`, `sms/sms.bin`, `v1/v1.bin`, `v3/v3.bin`, `wolf/wolf.bin`, `wolf/wolfsod.bin`, `feld/*.bin`, `six/six.bin`, `flash/flashapp.bin`) is built from the source +next to it; the build commands are in the README of each folder. + +## Credits and license + +Paramix Studio is free software under the GNU General Public License version 3 +or later, see [LICENSE](LICENSE). It builds on the work of others, see +[NOTICE.md](NOTICE.md) for the full list: + +- **TamaEmu** is based on [tamaemu](https://github.com/maragotchi/tamaemu) by + maragotchi (GPL-3.0). The JIT and the Paradise port were written for this + project; the emulator core and the download content layout come from tamaemu. +- **V1Emu** is based on [TamaLIB](https://github.com/jcrona/tamalib) by + Jean-Christophe Rona (GPL-2.0-or-later). +- **V3Emu** is based on [BrickEmuPy](https://github.com/azya52/BrickEmuPy) by + azya52, released under CC0 1.0 (public domain dedication: free to use, change + and pass on, no conditions): the SPLB32 core, the HT24LC08 EEPROM, the + infrared byte link and the dot and icon layout of the Connection V3 face. + See NOTICE.md. +- **DOOM** is based on nRF52840 Doom by next-hack, GBADoom by doomhack, PrBoom + and the DOOM source by id Software (GPL-2.0-or-later). The WAD converter is + MCUDoomWadUtil by Nicola Wrachien (GPL-2.0). +- **PokeMiniEmu** is based on [PokeMini](https://github.com/libretro/PokeMini) by + JustBurn (GPL-3.0-or-later), with its FreeBIOS. +- File format research: [tama-para-research](https://github.com/GMMan/tama-para-research) + and the S1C33 SLEIGH definition by GMMan. + +Made by mameise. +! Supported by AI ! diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..1839685 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +1.7.4 diff --git a/ab/README.md b/ab/README.md new file mode 100644 index 0000000..1caedb1 --- /dev/null +++ b/ab/README.md @@ -0,0 +1,52 @@ +# ArduboyEmu + +The Arduboy on the Tamagotchi Paradise, as a further program of the Paramix menu. +No game here: bring your own games (.hex). + +- `src/core/avr.c`: own emulation of the ATmega32U4 (16 MHz AVR) and of what the Arduboy uses of it: + - CPU: every instruction of the AVRe+ core with its cycles. The program is decoded once into one word per + instruction (handler and operands). The flags are kept apart and only put together when SREG is read. + Straight code runs without the event check; jumps check it. + - Timers 0, 1, 3 and 4: brought up to date when read or written and at their next event (all modes the + Arduino and Arduboy libraries use). Each timer's next event is kept until a write, a flag or an interrupt + changes it (AB_EVC), so a fast sound interrupt costs little. + - SPI to the SSD1306 display (commands, both addressing modes, inverting, contrast, start line, flipping), the + display's reset pin, the state the boot loader leaves it in. + - Buttons on the pins (kept current in the data space, so reading them is a plain load), EEPROM (1 KB), ADC (random values for seeds), PLL, watchdog (reset), sleep. + - Busy waiting (AB_SPIN): a loop that only asks the clock (millis(), micros()) and changes nothing is skipped up to + the next event. + - Sound: the tone of the speaker pins, from the timer that drives them or from the pin changes (AB_SND2: the pitch + from the times of the changes, both pins at once count once), and the PWM samples of OC4A (ATMlib music) from + their rising edges. The program leaves out changes below 3 % so the buzzer is not started anew every 20 ms. +- `src/core/jit.inc` (AB_JIT, on the Paradise): the fast core. The program is translated block by block into Thumb-2 + code in the SRAM (a 56 KB cache, emptied when full). AVR registers stay in the data space, the flags in ARM + registers; a flag is only worked out when something later reads it (H only inside a block). Blocks jump straight + to each other while cycles are left (AB_CHAIN), else through a small dispatcher. Rare instructions (I/O, SREG, + sleep, the signed multiplications) run in C (`jit_op`) with the flags handed over. The display byte (OUT SPDR) has its + own short helper; reading SPSR and the button pins, and SBIC/SBIS on them, are translated inline. On the PC the interpreter of + avr.c runs (it is the reference). +- `src/app/main.c`: the Paradise program (PRAM). Settings block "ABXP" at 0x140: game, length, save, flags (bit 0 + English, bit 1 wheel the other way round), name, keys (12 bytes: Arduboy buttons for the Paradise inputs 0 A, 1 B, + 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B; bits 1 up, 2 down, 4 left, 8 right, 16 A, 32 B). + The game lies at the start of its own 64 KB block (the cached window), the save behind it at +0x8000 (4 KB settings, + 4 KB EEPROM, 8 KB state). +- Screen: 128 x 64 at 1:1, 3:2 or 2:1 height (setting PICTURE, default 1:1 = SMALL, switch AB_SIZE0). Pictures that games switch for greys come out grey. +- Fixed keys: A+B+C settings (colour, picture, sound, light, dim, screen off, restart game, language); wheel held 2 s + = save and back to the Paradise. +- Save: the EEPROM goes to the flash 3 s after the game wrote it (1 s without a key), when the screen goes off and on + leaving. On leaving the whole state too (`emu/src/emu/pstate.h`), read once at the next start. +- The core is built with GCC (arm-none-eabi-gcc): each handler gets its own dispatch. + +Build: `sh src/app/build.sh` gives `ab.bin`. +Tests: +- `test/hostab.c` (gcc on the PC): runs a game, pictures as PGM (KEYS, SHOTS, OUT, PCS for a pc histogram). +- `test/fuzz.c`, `test/lock.c`: the CPU against simavr (libsimavr-dev), see the files. +- `test/jitfuzz/`: random programs run by the interpreter on the PC and by the fast core in Unicorn, compared + (`run.sh seed`). +- `python3 test/mkimg.py ab.bin game.hex img.bin` then `python3 test/devab.py src/app/ab.elf img.bin ` (Unicorn, + KEYS="t:mask,...", SHOTS="t,...", OUT=dir); `test/prof.py` instructions per function, `test/profl.py` per line. + +Author: mameise + +No session (1.7.3 test7, switch SESS_FLAG): flags bit 12 set by the Studio ("Remember where you left off" off): leaving writes +no state, a start drops an old one; only the game's own save (cartridge RAM or EEPROM) is kept. diff --git a/ab/ab.bin b/ab/ab.bin new file mode 100644 index 0000000..8c2207d Binary files /dev/null and b/ab/ab.bin differ diff --git a/ab/src/app/build.sh b/ab/src/app/build.sh new file mode 100644 index 0000000..42926a1 --- /dev/null +++ b/ab/src/app/build.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Build ArduboyEmu for the Paradise (clang/lld, Cortex-M3). Output: ../../ab.bin +set -e +cd "$(dirname "$0")" +E=../../../emu/src/emu +C=../core +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -Wno-unused-variable -Wno-parentheses -Wno-dangling-else -Wno-unknown-attributes -fno-builtin-memset -ffunction-sections -DAVR_FAST= -DPERFORMANCE -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DBL_SLEEP -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DTONE_SAFE -DGPLAY -DSESS_FLAG $XCF" +O="" +for f in main.c $C/avr.c $E/hw.c $E/flash.c $E/libc.c; do + n=$(basename $f .c); OPT=-Os + case $n in avr) OPT=-O2;; esac + if [ $n = avr ] && [ -z "$CLANG_CORE" ]; then + # the core with GCC: each handler gets its own dispatch (clang shares one indirect jump for all) + arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -ffunction-sections -fno-tree-loop-distribute-patterns -Wall -Wno-unused-function -Wno-unused-variable -Wno-misleading-indentation -DAVR_FAST= $XCF -O2 -c $f -o $n.o + else clang $CF $OPT -c $f -o $n.o; fi + O="$O $n.o"; done +ld.lld -T link.ld --gc-sections --no-rosegment $O -o ab.elf +llvm-objcopy -O binary -j .text -j .data -j .init ab.elf ab.bin +cp ab.bin ../../ab.bin; rm -f *.o ab.bin; [ -n "$KEEPELF" ] || rm -f ab.elf; ls -l ../../ab.bin diff --git a/ab/src/app/font.h b/ab/src/app/font.h new file mode 100644 index 0000000..b01afaa --- /dev/null +++ b/ab/src/app/font.h @@ -0,0 +1,99 @@ +/* generated by gen/font.py: custom 5x7 font */ +static const unsigned char g_font[96][7]={ + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x04,0x04,0x04,0x04,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x19,0x19,0x02,0x04,0x08,0x13,0x13}, + {0x0c,0x12,0x14,0x08,0x15,0x12,0x0d}, + {0x04,0x04,0x08,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x08,0x08,0x04,0x02}, + {0x08,0x04,0x02,0x02,0x02,0x04,0x08}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x04,0x04,0x1f,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x0c,0x04,0x08}, + {0x00,0x00,0x00,0x1f,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x0c,0x0c}, + {0x01,0x01,0x02,0x04,0x08,0x10,0x10}, + {0x0e,0x11,0x13,0x15,0x19,0x11,0x0e}, + {0x04,0x0c,0x04,0x04,0x04,0x04,0x0e}, + {0x0e,0x11,0x01,0x02,0x04,0x08,0x1f}, + {0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e}, + {0x02,0x06,0x0a,0x12,0x1f,0x02,0x02}, + {0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e}, + {0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e}, + {0x1f,0x01,0x02,0x04,0x08,0x08,0x08}, + {0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e}, + {0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e}, + {0x00,0x04,0x04,0x00,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x10,0x08,0x04,0x02}, + {0x00,0x00,0x1f,0x00,0x1f,0x00,0x00}, + {0x08,0x04,0x02,0x01,0x02,0x04,0x08}, + {0x0e,0x11,0x01,0x02,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x0e,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e}, + {0x0e,0x11,0x10,0x10,0x10,0x11,0x0e}, + {0x1e,0x11,0x11,0x11,0x11,0x11,0x1e}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x10,0x17,0x11,0x11,0x0f}, + {0x11,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x0e,0x04,0x04,0x04,0x04,0x04,0x0e}, + {0x07,0x02,0x02,0x02,0x02,0x12,0x0c}, + {0x11,0x12,0x14,0x18,0x14,0x12,0x11}, + {0x10,0x10,0x10,0x10,0x10,0x10,0x1f}, + {0x11,0x1b,0x15,0x15,0x11,0x11,0x11}, + {0x11,0x19,0x15,0x13,0x11,0x11,0x11}, + {0x0e,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x1e,0x11,0x11,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x11,0x11,0x15,0x12,0x0d}, + {0x1e,0x11,0x11,0x1e,0x14,0x12,0x11}, + {0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e}, + {0x1f,0x04,0x04,0x04,0x04,0x04,0x04}, + {0x11,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x11,0x11,0x11,0x11,0x0a,0x04}, + {0x11,0x11,0x11,0x15,0x15,0x15,0x0a}, + {0x11,0x11,0x0a,0x04,0x0a,0x11,0x11}, + {0x11,0x11,0x0a,0x04,0x04,0x04,0x04}, + {0x1f,0x01,0x02,0x04,0x08,0x10,0x1f}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x11,0x0a,0x04,0x0a,0x11}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x11,0x0e,0x11,0x1f,0x11,0x11,0x11}, + {0x11,0x0e,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x00,0x11,0x11,0x11,0x11,0x0e}, +}; diff --git a/ab/src/app/link.ld b/ab/src/app/link.ld new file mode 100644 index 0000000..106ae96 --- /dev/null +++ b/ab/src/app/link.ld @@ -0,0 +1,23 @@ +ENTRY(Reset_Handler) +MEMORY { + PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000 + SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000 +} +SECTIONS { + .text : { + KEEP(*(.vectors)) + KEEP(*(.pmxcfg)) + *(.text*) + *(.rodata*) + . = ALIGN(4); + __pdata_start = .; + } > PRAM + .bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM + /* mutable data in SRAM (initial values in PRAM, copied at startup), as in TamaEmu */ + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + .init : { . = ALIGN(4); KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); __prog_end = .; } > PRAM + ASSERT(__prog_end <= 0x10000, "program too big for PRAM") + ASSERT(__bss_end <= 0x1801F000, "RAM full") + /DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/ab/src/app/main.c b/ab/src/app/main.c new file mode 100644 index 0000000..c0af877 --- /dev/null +++ b/ab/src/app/main.c @@ -0,0 +1,470 @@ +/* ArduboyEmu: the Arduboy on the Tamagotchi Paradise, a further program of the Paramix menu. Bring your own games + * (.hex). Core: own ATmega32U4 emulation (../core/avr.c). + * Screen: the Arduboy's 128 x 64 at 1:1, 3:2 or 2:1 height (setting PICTURE); greys that games make by switching two + * pictures come out as grey. Keys: set in the Studio (tab Arduboy). A+B+C together: settings; wheel held 2 s: save and + * back to the Paradise. Sound: the speaker's tone on the Paradise's buzzer. Save: the EEPROM (1 KB) goes to the flash a + * few seconds after the game wrote it, and on leaving; on leaving the whole state too, the next start continues there. + * Author: mameise */ +#include "../../../emu/src/emu/hw.h" +#include "../../../emu/src/emu/exitkey.h" +#include "../../../emu/src/emu/flash.h" +#define PARA_ATTR +#include "../../../emu/src/emu/paraclock.h" +#ifdef PARA_BACK +#include "../../../emu/src/emu/paraback.h" +#ifdef GPLAY +#define GP_POINTS +#include "../../../emu/src/emu/gplay.h" +#endif +#endif +#include "../core/avr.h" +#include "font.h" + +/* ---- settings block at 0x140, filled in by the Studio ---- + * keys[i]: Arduboy buttons (bit 0 UP, 1 DOWN, 2 LEFT, 3 RIGHT, 4 A, 5 B) for the Paradise input i: 0 A, 1 B, 2 C, + * 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. flags: bit 0 English, bit 1 wheel the other way round. + * save_off: 4 KB settings of the device, 4 KB EEPROM (1 KB used), then the state (up to 8 KB). */ +#define NIN 9 +typedef struct { u32 magic, version, rom_off, rom_len, save_off, flags; char name[16]; u8 keys[12]; } AbCfg; +#define AB_MAGIC 0x50584241u /* "ABXP" */ +__attribute__((section(".pmxcfg"), used)) +volatile const AbCfg g_cfg = { AB_MAGIC, 1, 0, 0, 0, 0, {0}, { AB_LEFT, AB_B, AB_RIGHT, AB_A, AB_UP, AB_DOWN, 0, 0, 0 } }; +#define SETTINGS (g_cfg.save_off) +#define EEP_AT (g_cfg.save_off + 0x1000u) +#define STATE_AT (g_cfg.save_off + 0x2000u) +#define STATE_MAX 0x2000u +#define XIP_BASE_REG REG(0x4002F004u) +#define XIP_CTRL_REG REG(0x4002F000u) +#define ROMWIN ((const u16 *)0x10000000u) + +/* ---- time: SysTick 1 ms; the wheel's encoder is read here too ---- */ +static volatile u32 g_ms; +static volatile s32 g_enc_acc; static u32 g_enc_last; +static const signed char QD[16] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 }; +#define GPIO2 0x4001A000u +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +#define CORE_HZ 96000000u +__attribute__((used)) void systick_c(void) +{ + g_ms++; + u32 n = REG(GPIO2) & 3u; + if (n != g_enc_last) { g_enc_acc += QD[(g_enc_last << 2) | n]; g_enc_last = n; } +} +__attribute__((naked)) void SysTick_Handler(void) { __asm__ volatile("b systick_c\n"); } +void abort(void) { for (;;) hw_wdt_feed(); } + +/* ---- settings on the device ---- */ +typedef struct { u8 magic[4]; u8 pal, dim, lang, dimto, off, r0, size, mute; } AbSet; /* mute: 0 = sound on */ +#ifndef AB_SIZE0 +#define AB_SIZE0 0 /* 1.7.3 test10: picture size SMALL by default (1:1, not stretched); 1 = MEDIUM as before */ +#endif +static AbSet g_set = { {'A','B','S','1'}, 0, 7, 0, 6, 3, 0x80, AB_SIZE0, 0 }; +/* background, dot: white, amber, cyan (as the OLED), paper (black on white) */ +static const u16 PAL[4][2] = { { 0x0000u, 0xFFFFu }, { 0x0000u, 0xFDA0u }, { 0x0000u, 0x5FFFu }, { 0xEF5Du, 0x10A2u } }; +static const char *const PAL_NM[2][4] = { { "WEISS", "GELB", "BLAU", "PAPIER" }, { "WHITE", "AMBER", "CYAN", "PAPER" } }; +static const char *const SIZE_NM[2][3] = { { "KLEIN", "MITTEL", "GROSS" }, { "SMALL", "MEDIUM", "LARGE" } }; +#define T_N 7 +static const u32 T_MS[T_N] = { 10000u, 20000u, 30000u, 60000u, 120000u, 300000u, 600000u }; +static const char *const T_NM[2][T_N + 1] = { { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NIE" }, { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NEVER" } }; +#define LV_N 11 +#define DIM2_N 10 +static const u8 LV_PCT[LV_N] = { 100u, 5u, 10u, 20u, 30u, 40u, 50u, 60u, 70u, 80u, 90u }; +static const u8 DIM2_PCT[DIM2_N] = { 1u, 2u, 3u, 5u, 10u, 15u, 20u, 30u, 40u, 50u }; +static int en(void) { return g_set.lang ? g_set.lang == 2u : (int)(g_cfg.flags & 1u); } +static u16 BG, INK, OFF; +static u16 g_lut[3]; /* dot off, grey, on (with the game's contrast) */ +static u32 g_contrast = 0x100u; +static int g_dimmed, g_redraw; +static u16 mix(u16 a, u16 b, int p, int q) /* a + (b - a) * p / q */ +{ + int r = (a >> 11) + (((b >> 11) - (a >> 11)) * p) / q, g = ((a >> 5) & 63) + ((((b >> 5) & 63) - ((a >> 5) & 63)) * p) / q; + int bl = (a & 31) + (((b & 31) - (a & 31)) * p) / q; + return (u16)((r << 11) | (g << 5) | bl); +} +static void lut(void) +{ + const u16 *p = PAL[g_set.pal & 3u]; + u32 c = 128u + (A_LCD.contrast >> 1); /* the game's contrast: 128..255 of the full dot */ + g_lut[0] = p[0]; g_lut[2] = mix(p[0], p[1], (int)c, 255); g_lut[1] = mix(p[0], p[1], (int)c, 510); + g_contrast = A_LCD.contrast; +} +static void colours(void) +{ + const u16 *p = PAL[g_set.pal & 3u]; + BG = p[0]; INK = p[1]; OFF = mix(p[0], p[1], 1, 2); + lut(); +#ifdef BL_PWM + { u32 l = LV_PCT[(g_set.r0 & 15u) % LV_N], d = DIM2_PCT[g_set.dimto % DIM2_N]; + hw_bl_set(g_dimmed ? (d < l ? d : l) : l); } +#endif + g_redraw = 1; +} +/* sector buffer (4 KB) and state buffer: the end of the fast core's cache (ab_scratch empties it), so the cache is + * bigger; only used between runs */ +static void set_load(void) +{ + const volatile u8 *p = XIP_PTR(SETTINGS); AbSet t; u8 *d = (u8 *)&t; + for (u32 i = 0; i < sizeof t; i++) d[i] = p[i]; + if (t.magic[0] == 'A' && t.magic[1] == 'B' && t.magic[2] == 'S' && t.magic[3] == '1' && t.pal < 4u && t.dim <= T_N && t.off <= T_N && t.lang < 3u && t.size < 3u) g_set = t; + colours(); +} +static void set_store(void) +{ + u8 *sec = ab_scratch(); + for (u32 i = 0; i < 0x1000u; i++) sec[i] = 0xFF; + const u8 *s = (const u8 *)&g_set; for (u32 i = 0; i < sizeof g_set; i++) sec[i] = s[i]; + flash_update4k(SETTINGS, sec); +} + +/* ---- EEPROM (the games' saves, 1 KB) ---- */ +static u32 g_tone_now; +static void tone(u32 hz) +{ +#ifndef AB_TONE_ALL + /* as GB_TONE_RESTART: every new pitch starts the buzzer anew (a new pitch in the running timer stayed silent on the + * device); changes below about 3 % (measuring) are left out, so it does not start anew every 20 ms */ + if (hz && g_tone_now) { u32 d = hz > g_tone_now ? hz - g_tone_now : g_tone_now - hz; if (d * 32u < g_tone_now) return; } +#endif + if (hz != g_tone_now) { if (hz && g_tone_now) hw_tone(0); g_tone_now = hz; hw_tone(hz); } +} +static void eep_load(void) { const volatile u8 *p = XIP_PTR(EEP_AT); for (u32 i = 0; i < AVR_EEP; i++) A_EEP[i] = p[i]; } +static void eep_store(void) +{ + u8 *sec = ab_scratch(); + for (u32 i = 0; i < 0x1000u; i++) sec[i] = i < AVR_EEP ? A_EEP[i] : 0xFFu; + tone(0); flash_update4k(EEP_AT, sec); + A_EEP_DIRTY = 0; +} + +/* ---- screen ---- */ +static u8 g_snap[2][1024] __attribute__((aligned(4))); /* the last two full pictures */ +static u32 g_si, g_nsnap, g_nsnap_shown; +void ab_frame(void) +{ + u32 *d = (u32 *)g_snap[g_si ^= 1u]; const u32 *s = (const u32 *)A_GD; + for (int i = 0; i < 256; i++) d[i] = s[i]; + g_nsnap++; +} +static u8 g_src[64][128] __attribute__((aligned(4))); /* the Arduboy's rows as shown: 0 off, 1 grey, 2 on */ +static u16 g_row[128] __attribute__((aligned(4))); +static int g_dirty_lo = 64, g_dirty_hi = -1; /* changed source rows */ +static int oh(void) { return g_set.size == 0 ? 64 : g_set.size == 1 ? 96 : 128; } +static void src_dirty_all(void) { for (int y = 0; y < 64; y++) for (int x = 0; x < 128; x++) g_src[y][x] = 0xFF; } +/* one row of the Arduboy's picture: 0, 1 (grey) or 2 per dot */ +static void src_row(int y, const u8 *a, const u8 *b, u8 *o) +{ + if (!A_LCD.on) { for (int x = 0; x < 128; x++) o[x] = 0; return; } + if (A_LCD.allon) { for (int x = 0; x < 128; x++) o[x] = 2; return; } + int ry = (A_LCD.flip_y ? y : 63 - y) + A_LCD.start; ry &= 63; + const u8 *pa = a + (ry >> 3) * 128, *pb = b + (ry >> 3) * 128; u32 sh = (u32)ry & 7u, inv = A_LCD.invert ? 1u : 0u; + if (A_LCD.flip_x) for (int x = 0; x < 128; x++) o[x] = (u8)((((pa[x] >> sh) & 1u) ^ inv) + (((pb[x] >> sh) & 1u) ^ inv)); + else for (int x = 0; x < 128; x++) o[x] = (u8)((((pa[127 - x] >> sh) & 1u) ^ inv) + (((pb[127 - x] >> sh) & 1u) ^ inv)); +} +static void frame_build(void) +{ + const u8 *a, *b; + if (g_nsnap != g_nsnap_shown && g_nsnap >= 2u) { a = g_snap[g_si]; b = g_snap[g_si ^ 1u]; g_nsnap_shown = g_nsnap; } + else { a = A_GD; b = A_GD; } + if (A_LCD.contrast != g_contrast) { lut(); g_redraw = 1; } + static u8 t[128] __attribute__((aligned(4))); + for (int y = 0; y < 64; y++) { + src_row(y, a, b, t); + u32 *f = (u32 *)g_src[y], d = 0; const u32 *w = (const u32 *)t; + for (int x = 0; x < 32; x++) { d |= f[x] ^ w[x]; f[x] = w[x]; } + if (d) { if (y < g_dirty_lo) g_dirty_lo = y; if (y > g_dirty_hi) g_dirty_hi = y; } + } +} +/* output row r of the shown height h from the source rows */ +static void out_px(int r, int h) +{ + if (h == 64) { const u8 *f = g_src[r]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; return; } + if (h == 128) { const u8 *f = g_src[r >> 1]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; return; } + int k = r / 3, m = r % 3; const u8 *p = g_src[2 * k], *q = g_src[2 * k + 1]; /* 2 rows to 3: a, (a + b) / 2, b */ + if (m == 0) for (int x = 0; x < 128; x++) g_row[x] = g_lut[p[x]]; + else if (m == 2) for (int x = 0; x < 128; x++) g_row[x] = g_lut[q[x]]; + else for (int x = 0; x < 128; x++) g_row[x] = g_lut[(p[x] + q[x] + 1u) >> 1]; +} +static void push(int all) +{ + int h = oh(), oy = (128 - h) / 2; + if (g_redraw) { g_redraw = 0; all = 1; } + if (all && oy) { /* the bars */ + for (int x = 0; x < 128; x++) g_row[x] = BG; + hw_px_begin(0, 0, 128, (u32)oy); for (int y = 0; y < oy; y++) hw_px_row(g_row, 128); hw_px_end(); + hw_px_begin(0, (u32)(oy + h), 128, 128); for (int y = oy + h; y < 128; y++) hw_px_row(g_row, 128); hw_px_end(); + } + int lo = all ? 0 : g_dirty_lo, hi = all ? 63 : g_dirty_hi; + g_dirty_lo = 64; g_dirty_hi = -1; + if (lo > hi) return; + int r0 = h == 64 ? lo : h == 128 ? 2 * lo : (lo >> 1) * 3, r1 = h == 64 ? hi : h == 128 ? 2 * hi + 1 : (hi >> 1) * 3 + 2; + hw_px_begin(0, (u32)(oy + r0), 128, (u32)(oy + r1 + 1)); + for (int r = r0; r <= r1; r++) { out_px(r, h); hw_px_row(g_row, 128); } + hw_px_end(); +} + +/* ---- the settings menu (A+B+C): A next line, B change, C close ---- */ +static int g_menu, g_msel, g_mtop; +static void text(int x, int y, const char *s, u16 col, u16 *row, int ry) +{ + for (; *s; s++, x += 6) { + int c = (unsigned char)*s; if (c >= 97 && c <= 122) c -= 32; c = (c < 32 || c > 127) ? 0 : c - 32; + if (ry < y || ry >= y + 7) continue; + u8 bits = g_font[c][ry - y]; + for (int k = 0; k < 5; k++) if ((bits & (0x10 >> k)) && x + k >= 0 && x + k < 128) row[x + k] = col; + } +} +enum { M_PAL, M_SIZE, M_SND, M_LIGHT, M_DIM, M_DIMTO, M_OFF, M_RESET, M_LANG, M_N }; +static int g_items[M_N], g_nitems; +static void menu_items(void) +{ + g_nitems = 0; + for (int k = 0; k < M_N; k++) { if (k == M_DIMTO && g_set.dim >= T_N) continue; g_items[g_nitems++] = k; } + if (g_msel >= g_nitems) g_msel = g_nitems - 1; +} +static void pct(char *o, int v) { int n = 0; if (v >= 100) o[n++] = '1'; if (v >= 10) o[n++] = (char)('0' + (v / 10) % 10); o[n++] = (char)('0' + v % 10); o[n++] = '%'; o[n] = 0; } +static int g_reset_ask; +static void menu_line(int it, const char **a, char *b) +{ + int e = en(); const char *v = 0; b[0] = 0; + switch (it) { + case M_PAL: *a = e ? "COLOUR" : "FARBE"; v = PAL_NM[e][g_set.pal & 3u]; break; + case M_SIZE: *a = e ? "PICTURE" : "BILD"; v = SIZE_NM[e][g_set.size % 3u]; break; + case M_SND: *a = e ? "SOUND" : "TON"; v = g_set.mute ? (e ? "OFF" : "AUS") : (e ? "ON" : "AN"); break; + case M_LIGHT: *a = e ? "LIGHT" : "LICHT"; pct(b, LV_PCT[(g_set.r0 & 15u) % LV_N]); break; + case M_DIM: *a = e ? "DIM AFTER" : "DIMMEN NACH"; v = T_NM[e][g_set.dim <= T_N ? g_set.dim : T_N]; break; + case M_DIMTO: *a = e ? "DIM TO" : "DIMMEN AUF"; pct(b, DIM2_PCT[g_set.dimto % DIM2_N]); break; + case M_OFF: *a = e ? "SCREEN OFF" : "BILD AUS NACH"; v = T_NM[e][g_set.off <= T_N ? g_set.off : T_N]; break; + case M_RESET: *a = e ? "RESTART GAME" : "SPIEL NEU"; v = g_reset_ask ? (e ? "SURE? B" : "SICHER? B") : ""; break; + default: *a = e ? "LANGUAGE" : "SPRACHE"; v = e ? "ENGLISH" : "DEUTSCH"; break; + } + if (v) { int n = 0; while (v[n] && n < 11) { b[n] = v[n]; n++; } b[n] = 0; } +} +#define ROWS 9 +static void menu_draw(void) +{ + if (g_msel < g_mtop) g_mtop = g_msel; + if (g_msel >= g_mtop + ROWS) g_mtop = g_msel - ROWS + 1; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + for (int x = 0; x < 128; x++) g_row[x] = BG; + text(4, 3, en() ? "SETTINGS" : "EINSTELLUNGEN", INK, g_row, y); + if (y == 12) for (int x = 0; x < 128; x++) g_row[x] = OFF; + for (int k = 0; k < ROWS && g_mtop + k < g_nitems; k++) { + int i = g_mtop + k, ly = 16 + k * 11; const char *a; char b[12]; menu_line(g_items[i], &a, b); + if (i == g_msel && y >= ly - 2 && y < ly + 9) for (int x = 0; x < 128; x++) g_row[x] = INK; + u16 c = i == g_msel ? BG : INK; + text(4, ly, a, c, g_row, y); int w = 0; while (b[w]) w++; text(124 - w * 6, ly, b, c, g_row, y); + } + text(4, 118, en() ? "A NEXT B SET C OK" : "A ZEILE B SETZEN C OK", OFF, g_row, y); + hw_px_row(g_row, 128); + } + hw_px_end(); +} +static int g_set_dirty; +static void ab_fresh(void); +static void menu_close(void) +{ + g_menu = 0; g_reset_ask = 0; if (g_set_dirty) { set_store(); g_set_dirty = 0; } + src_dirty_all(); frame_build(); push(1); +} +static void menu_key(u32 k) +{ + if (k & BTN_A) { g_msel = (g_msel + 1) % g_nitems; g_reset_ask = 0; } + if (k & BTN_B) { + switch (g_items[g_msel]) { + case M_PAL: g_set.pal = (u8)((g_set.pal + 1u) & 3u); break; + case M_SIZE: g_set.size = (u8)((g_set.size + 1u) % 3u); break; + case M_SND: g_set.mute ^= 1u; break; + case M_LIGHT: g_set.r0 = (u8)(0x80u | (((g_set.r0 & 15u) + 1u) % LV_N)); break; + case M_DIM: g_set.dim = (u8)((g_set.dim + 1u) % (T_N + 1u)); if (g_set.dim < T_N && g_set.off < T_N && g_set.off <= g_set.dim) g_set.off = (u8)(g_set.dim + 1u); break; + case M_DIMTO: g_set.dimto = (u8)((g_set.dimto + 1u) % DIM2_N); break; + case M_OFF: do g_set.off = (u8)((g_set.off + 1u) % (T_N + 1u)); while (g_set.off < T_N && g_set.dim < T_N && g_set.off <= g_set.dim); break; + case M_RESET: if (g_reset_ask) { g_reset_ask = 0; ab_fresh(); menu_close(); return; } g_reset_ask = 1; break; + default: g_set.lang = (u8)(en() ? 1u : 2u); break; + } + if (g_items[g_msel] != M_RESET) g_set_dirty = 1; + colours(); menu_items(); + } + if (k & BTN_C) { menu_close(); return; } + menu_draw(); +} +static void message(const char *a, const char *b) +{ + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { for (int x = 0; x < 128; x++) g_row[x] = BG; text(4, 50, a, INK, g_row, y); text(4, 62, b, INK, g_row, y); hw_px_row(g_row, 128); } + hw_px_end(); +} + +/* ---- keys: the Paradise inputs to the Arduboy's buttons (map from the Studio) ---- */ +static u32 g_wheel_until[2]; /* wheel up / down held until (ms) */ +static u32 ab_keys(u32 b, u32 now) +{ + u32 in = 0; + int ac = (b & (BTN_A | BTN_C)) == (BTN_A | BTN_C), bc = (b & (BTN_B | BTN_C)) == (BTN_B | BTN_C), ab = (b & (BTN_A | BTN_B)) == (BTN_A | BTN_B); + u32 used = 0; /* a pair held: its two keys count as the pair only (if the pair has a meaning) */ + if (ac && g_cfg.keys[6]) { in |= 1u << 6; used |= BTN_A | BTN_C; } + if (bc && g_cfg.keys[7]) { in |= 1u << 7; used |= BTN_B | BTN_C; } + if (ab && g_cfg.keys[8]) { in |= 1u << 8; used |= BTN_A | BTN_B; } + u32 r = b & ~used; + if (r & BTN_A) in |= 1u; if (r & BTN_B) in |= 2u; if (r & BTN_C) in |= 4u; if (b & BTN_WHEEL) in |= 8u; + if ((s32)(g_wheel_until[0] - now) > 0) in |= 16u; + if ((s32)(g_wheel_until[1] - now) > 0) in |= 32u; + u32 k = 0; + for (int i = 0; i < NIN; i++) if (in & (1u << i)) k |= g_cfg.keys[i]; + return k; +} + +/* ---- the game ---- */ +static void ab_fresh(void) { A_KEYS = 0; ab_reset(); } + +/* ---- the whole state on leaving (wheel held), read once at the next start ---- */ +#include "../../../emu/src/emu/pstate.h" +#ifdef SESS_FLAG +#define NOSESS ((g_cfg.flags & 0x1000u) != 0u) /* 1.7.3 test7: the Studio's "remember on leaving" off: only the game's own save */ +#else +#define NOSESS 0 +#endif +#define STATE_N 0x1400u +static int g_running; +static u32 st_tag(void) { return 0x41420001u ^ (u32)STATE_N ^ g_cfg.rom_len ^ (u32)&A_D ^ (u32)ab_run; } +static void state_store(void) +{ + if (!g_running) return; + u8 *sec = ab_scratch(), *st = sec + 0x1000u; + for (u32 i = 0; i < STATE_N; i++) st[i] = 0; + if (!ab_state_save(st, STATE_N)) return; + StPart pt[1] = { { st, STATE_N } }; + st_store(STATE_AT, STATE_MAX, st_tag(), pt, 1, sec); +} +static int state_load(void) +{ + if (NOSESS) { st_drop(STATE_AT); return 0; } + u8 *st = ab_scratch() + 0x1000u; + StPart pt[1] = { { st, STATE_N } }; + int ok = st_load(STATE_AT, STATE_MAX, st_tag(), pt, 1) && ab_state_load(st, STATE_N); + st_drop(STATE_AT); + return ok; +} + +/* ---- leaving ---- */ +static void leave(void) +{ + tone(0); hw_tone(0); + if (g_set_dirty) set_store(); + REG(0x20000FF8u) = 0; + REG(0x20000FFCu) = 0x4C584D50u; /* "PMXL": back on purpose, the autostart stays off */ + if (g_running && !NOSESS) { message(en() ? "SAVING" : "SPEICHERN", ""); state_store(); } + if (A_EEP_DIRTY) eep_store(); +#ifdef PARA_BACK +#ifdef GPLAY + para_points((uint8_t *)ab_scratch()); /* play time to Tamapoints */ +#endif + para_back_fix(ab_scratch()); +#endif + hw_bl_pwm_off(); + for (u32 t = 0; hw_buttons() && t < 20000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); + XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u; + hw_back_to_paradise(); +} + +__attribute__((used)) volatile u32 g_abst[4]; /* ms run, pictures pushed, ms dropped, last slice in ms (for the tests) */ +extern u32 __bss_start, __bss_end; +void Reset_Handler(void) +{ + __asm__ volatile("cpsid i"); + u32 cnt = REG(0x45000304u), para = para_clock(cnt, 0, 0x1F000u, 0, 0); + if (!para) para = para_mailbox(cnt); +#ifdef PARA_BACK + para_leave_mark(cnt, para); +#endif + __asm__ volatile("" ::: "memory"); + for (u32 *p = &__bss_start; p < &__bss_end; p++) *p = 0; + { extern u32 __data_start, __data_end, __data_load; + const u32 *src = &__data_load; for (u32 *p = &__data_start; p < &__data_end; p++) *p = *src++; } + (void)para; + hw_init(); + hw_tone(0); + XIP_BASE_REG = 0x60000000u | g_cfg.rom_off; /* the game in the cached window from 0x10000000 */ + XIP_CTRL_REG = 3u; + REG(GPIO2 + 0x04) &= ~3u; g_enc_last = REG(GPIO2) & 3u; + set_load(); + ab_load(ROMWIN, (g_cfg.rom_len + 1u) / 2u); + eep_load(); + ab_reset(); + state_load(); + A_EEP_DIRTY = 0; + g_running = 1; + src_dirty_all(); + frame_build(); push(1); + SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; SYST_CSR = 7; + __asm__ volatile("cpsie i"); + + u32 last_in = g_ms, wheel_ms = 0, eep_ms = 0, done_ms = g_ms, last_push = g_ms, mk0 = 0, tone_ms = g_ms, tone_cyc = A_CYC; + int bl = 1, lock = 1, menu_lock = 0; + for (;;) { + hw_wdt_feed(); + u32 now = g_ms; + u32 b = hw_buttons(); + if (lock) { if (b) b = 0; else lock = 0; } + /* wheel steps: one step = 4 phases; each step holds up or down for 150 ms */ + { s32 a = g_enc_acc; + if (a >= 4 || a <= -4) { + __asm__ volatile("cpsid i"); g_enc_acc -= a >= 4 ? 4 : -4; __asm__ volatile("cpsie i"); + int up = (a > 0) ^ ((g_cfg.flags & 2u) != 0); + u32 *u = &g_wheel_until[up ? 0 : 1]; *u = ((s32)(*u - now) > 0 ? *u : now) + 150u; + last_in = now; + if (g_menu) { g_msel = up ? (g_msel + g_nitems - 1) % g_nitems : (g_msel + 1) % g_nitems; menu_draw(); } + } } + if (b) { + last_in = now; + if (!bl || g_dimmed) { /* the key only wakes */ + bl = 1; hw_backlight(1); if (g_dimmed) { g_dimmed = 0; colours(); } + if (g_menu) menu_draw(); else push(1); + while (hw_buttons()) hw_wdt_feed(); + done_ms = g_ms; + continue; + } + } + /* wheel held 2 s: save and back */ + if (b & BTN_WHEEL) { if (!wheel_ms) wheel_ms = now ? now : 1; else if (EXIT_NOW(now - wheel_ms, 2000u)) leave(); } else wheel_ms = 0; + /* A+B+C: settings */ + if ((b & (BTN_A | BTN_B | BTN_C)) == (BTN_A | BTN_B | BTN_C) && !g_menu && !menu_lock) { + tone(0); A_KEYS = 0; g_menu = 1; menu_lock = 1; g_msel = 0; g_mtop = 0; menu_items(); menu_draw(); mk0 = BTN_A | BTN_B | BTN_C; + } + if (!(b & (BTN_A | BTN_B | BTN_C))) menu_lock = 0; + if (g_menu) { + u32 k = b & (BTN_A | BTN_B | BTN_C), nk = k & ~mk0; mk0 = k; if (nk) menu_key(nk); + done_ms = g_ms; + __asm__ volatile("wfi"); + continue; + } + if (!bl) { tone(0); done_ms = g_ms; __asm__ volatile("wfi"); continue; } /* screen off: the game waits (battery) */ + A_KEYS = ab_keys(b, now); + /* the Arduboy runs 16000 cycles per millisecond */ + if ((s32)(now - done_ms) > 0) { + if ((s32)(now - done_ms) > 50) { g_abst[2] += now - done_ms - 50u; done_ms = now - 50u; } /* too far behind: drop the time */ + u32 t0 = g_ms; + ab_run(16000u); + done_ms++; g_abst[0]++; g_abst[3] = g_ms - t0; + if (now - tone_ms >= 20u) { + u32 hz = ab_tone(A_CYC - tone_cyc); tone_ms = now; tone_cyc = A_CYC; + tone(!g_set.mute && hz >= 40u && hz <= 12000u ? hz : 0u); + } + if (now - last_push >= 33u) { last_push = now; frame_build(); push(0); g_abst[1]++; } + } + if (A_EEP_DIRTY && !eep_ms) eep_ms = now ? now : 1; + if (eep_ms && now - eep_ms > 3000u && now - last_in > 1000u) { eep_ms = 0; eep_store(); } + if (bl && !g_dimmed && g_set.dim < T_N && now - last_in > T_MS[g_set.dim]) { g_dimmed = 1; colours(); push(1); } + if (bl && g_set.off < T_N && now - last_in > T_MS[g_set.off]) { bl = 0; tone(0); hw_backlight(0); if (A_EEP_DIRTY) { eep_ms = 0; eep_store(); } } + if ((s32)(g_ms - done_ms) <= 0) __asm__ volatile("wfi"); + } +} + +__attribute__((naked)) static void Default_Handler(void) { __asm__ volatile("1: b 1b\n"); } +__attribute__((naked)) static void Irq_Off(void) { __asm__ volatile("cpsid i\n bx lr\n"); } +__attribute__((section(".vectors"), used)) +const void *const g_vectors[16 + 64] = { (void *)0x18020000u, (void *)Reset_Handler, + [2 ... 10] = (void *)Default_Handler, [11] = (void *)Irq_Off, [12 ... 13] = (void *)Default_Handler, [14] = (void *)Irq_Off, + [15] = (void *)SysTick_Handler, [16 ... 79] = (void *)Irq_Off }; diff --git a/ab/src/core/avr.c b/ab/src/core/avr.c new file mode 100644 index 0000000..e1c0798 --- /dev/null +++ b/ab/src/core/avr.c @@ -0,0 +1,926 @@ +/* ArduboyEmu: ATmega32U4 core and the Arduboy's hardware (see avr.h). Author: mameise. License: GPL-3.0-or-later. */ +#include "avr.h" +#include + +#ifndef AVR_FAST +#define AVR_FAST __attribute__((optimize("O2"))) +#endif + +AbMem g_mem __attribute__((aligned(8))); +u8 A_EEP[AVR_EEP] __attribute__((aligned(4))); +u8 A_GD[1024] __attribute__((aligned(4))); +#if !AB_JIT +u32 A_OP[AVR_FLASH_WORDS + 4]; /* behind the end: O_BAD, which wraps the pc */ +#endif +const u16 *A_FLASH; +static u32 g_words; +u32 A_CYC, A_KEYS, A_FRAMES; +int A_EEP_DIRTY; +AvrLcd A_LCD; +#ifdef AB_COUNT +u32 A_INS, A_OPC[96], A_PCH[16384]; +#endif + +/* ------------------------------------------------------------------ decoding + * One u32 per program word: the handler (low 16 bits: its index, or on the Paradise its address in PRAM) and the + * operands in the high 16 bits (f = o >> 16): + * two registers: d | r << 5 (CPSE: | skip of a two-word instruction << 10); register and byte: d | K << 8; + * jumps and branches: the target word; SBRC/SBRS/BLD/BST: d | skip2 << 5 | bit mask << 8; + * SBI/CBI/SBIC/SBIS: bit mask | (I/O address - 0x20) << 8 | skip2 << 13; LDS/STS: d, the address in the next slot. */ +enum { + O_NOP, O_MOVW, O_MULS, O_MULSU, O_FMUL, O_FMULS, O_FMULSU, O_CPC, O_SBC, O_ADD, O_CPSE, O_CP, O_SUB, O_ADC, O_AND, + O_EOR, O_OR, O_MOV, O_CPI, O_SBCI, O_SUBI, O_ORI, O_ANDI, O_LDDY, O_LDDZ, O_STDY, O_STDZ, O_LDS, O_LDZP, O_LDMZ, + O_LPMZ, O_LPMZP, O_LDYP, O_LDMY, O_LDX, O_LDXP, O_LDMX, O_POP, O_STS, O_STZP, O_STMZ, O_STYP, O_STMY, O_STX, O_STXP, + O_STMX, O_PUSH, O_COM, O_NEG, O_SWAP, O_INC, O_ASR, O_LSR, O_ROR, O_DEC, O_BSET, O_BCLR, O_RET, O_RETI, O_SLEEP, + O_WDR, O_LPM0, O_IJMP, O_ICALL, O_JMP, O_CALL, O_ADIW, O_SBIW, O_CBI, O_SBIC, O_SBI, O_SBIS, O_MUL, O_IN, O_OUT, + O_RJMP, O_RCALL, O_LDI, O_BLD, O_BST, O_SBRC, O_SBRS, O_INSREG, O_OUTSREG, + O_BREQ, O_BRNE, O_BRCS, O_BRCC, O_BRMI, O_BRPL, O_BRVS, O_BRVC, O_BRLT, O_BRGE, O_BRHS, O_BRHC, O_BRTS, O_BRTC, + O_BRIE, O_BRID, O_BAD, O_N +}; +static int two_words(u32 w) { return (w & 0xFE0Fu) == 0x9000u || (w & 0xFE0Fu) == 0x9200u || (w & 0xFE0Cu) == 0x940Cu; } +#define F(op, f) ((u32)(op) | ((u32)(f) << 16)) +static u32 decode(u32 pc) +{ + u32 w = A_FLASH[pc], w2 = pc + 1 < AVR_FLASH_WORDS ? A_FLASH[pc + 1] : 0, sk2 = pc + 1 < AVR_FLASH_WORDS && two_words(w2); + u32 d5 = (w >> 4) & 31u, r5 = (w & 15u) | ((w >> 5) & 16u), d4 = 16u + ((w >> 4) & 15u), K8 = ((w >> 4) & 0xF0u) | (w & 15u); +#define DR(op, d, r) F(op, (d) | (r) << 5) +#define DK(op, d, k) F(op, (d) | (k) << 8) + switch (w >> 12) { + case 0x0: + if (w == 0) return O_NOP; + switch ((w >> 10) & 3u) { + case 0: + if ((w & 0xFF00u) == 0x0100u) return DR(O_MOVW, ((w >> 4) & 15u) * 2u, (w & 15u) * 2u); + if ((w & 0xFF00u) == 0x0200u) return DR(O_MULS, d4, 16u + (w & 15u)); + if ((w & 0xFF00u) == 0x0300u) { + u32 d = 16u + ((w >> 4) & 7u), r = 16u + (w & 7u); + switch (w & 0x88u) { case 0x00: return DR(O_MULSU, d, r); case 0x08: return DR(O_FMUL, d, r); case 0x80: return DR(O_FMULS, d, r); default: return DR(O_FMULSU, d, r); } + } + return O_BAD; + case 1: return DR(O_CPC, d5, r5); + case 2: return DR(O_SBC, d5, r5); + default: return DR(O_ADD, d5, r5); + } + case 0x1: + switch ((w >> 10) & 3u) { case 0: return DR(O_CPSE, d5, r5) | sk2 << 26; case 1: return DR(O_CP, d5, r5); case 2: return DR(O_SUB, d5, r5); default: return DR(O_ADC, d5, r5); } + case 0x2: + switch ((w >> 10) & 3u) { case 0: return DR(O_AND, d5, r5); case 1: return DR(O_EOR, d5, r5); case 2: return DR(O_OR, d5, r5); default: return DR(O_MOV, d5, r5); } + case 0x3: return DK(O_CPI, d4, K8); + case 0x4: return DK(O_SBCI, d4, K8); + case 0x5: return DK(O_SUBI, d4, K8); + case 0x6: return DK(O_ORI, d4, K8); + case 0x7: return DK(O_ANDI, d4, K8); + case 0x8: case 0xA: { + u32 q = (w & 7u) | ((w >> 7) & 0x18u) | ((w >> 8) & 0x20u), st = (w >> 9) & 1u, y = (w >> 3) & 1u; + return DK(st ? (y ? O_STDY : O_STDZ) : (y ? O_LDDY : O_LDDZ), d5, q); + } + case 0x9: + switch ((w >> 9) & 7u) { + case 0: /* 1001 000d */ + switch (w & 15u) { + case 0: return F(O_LDS, d5); + case 1: return F(O_LDZP, d5); case 2: return F(O_LDMZ, d5); + case 4: case 6: return F(O_LPMZ, d5); case 5: case 7: return F(O_LPMZP, d5); + case 9: return F(O_LDYP, d5); case 10: return F(O_LDMY, d5); + case 12: return F(O_LDX, d5); case 13: return F(O_LDXP, d5); case 14: return F(O_LDMX, d5); + case 15: return F(O_POP, d5); + default: return O_BAD; + } + case 1: + switch (w & 15u) { + case 0: return F(O_STS, d5); + case 1: return F(O_STZP, d5); case 2: return F(O_STMZ, d5); + case 9: return F(O_STYP, d5); case 10: return F(O_STMY, d5); + case 12: return F(O_STX, d5); case 13: return F(O_STXP, d5); case 14: return F(O_STMX, d5); + case 15: return F(O_PUSH, d5); + default: return O_BAD; + } + case 2: /* 1001 010x */ + switch (w & 15u) { + case 0: return F(O_COM, d5); case 1: return F(O_NEG, d5); case 2: return F(O_SWAP, d5); + case 3: return F(O_INC, d5); case 5: return F(O_ASR, d5); case 6: return F(O_LSR, d5); + case 7: return F(O_ROR, d5); case 10: return F(O_DEC, d5); + case 12: case 13: case 14: case 15: { + u32 k = ((((w >> 4) & 31u) << 1 | (w & 1u)) << 16 | w2) & 0x3FFFu; + return F((w & 2u) ? O_CALL : O_JMP, k); + } + case 8: + if ((w & 0xFF0Fu) == 0x9408u) return F((w & 0x80u) ? O_BCLR : O_BSET, 1u << ((w >> 4) & 7u)); + switch (w) { + case 0x9508: return O_RET; case 0x9518: return O_RETI; case 0x9588: return O_SLEEP; case 0x9598: return O_NOP; + case 0x95A8: return O_WDR; case 0x95C8: case 0x95D8: return O_LPM0; case 0x95E8: case 0x95F8: return O_NOP; + } + return O_BAD; + case 9: + if (w == 0x9409u || w == 0x9419u) return O_IJMP; + if (w == 0x9509u || w == 0x9519u) return O_ICALL; + return O_BAD; + default: return O_BAD; + } + case 3: + return DK((w & 0x0100u) ? O_SBIW : O_ADIW, 24u + ((w >> 3) & 6u), ((w >> 2) & 0x30u) | (w & 15u)); + case 4: case 5: { + u32 a = (w >> 3) & 31u, m = 1u << (w & 7u), set = (w >> 9) & 1u, sk = (w >> 8) & 1u; + return F(set ? (sk ? O_SBIS : O_SBI) : (sk ? O_SBIC : O_CBI), m | a << 8 | sk2 << 13); + } + default: return DR(O_MUL, d5, r5); + } + case 0xB: { + u32 a = 0x20u + ((w & 15u) | ((w >> 5) & 0x30u)); + if (a == 0x5Fu) return F((w & 0x0800u) ? O_OUTSREG : O_INSREG, d5); + return DK((w & 0x0800u) ? O_OUT : O_IN, d5, a); + } + case 0xC: { s32 k = (s32)(w << 20) >> 20; return F(O_RJMP, (pc + 1 + (u32)k) & 0x3FFFu); } + case 0xD: { s32 k = (s32)(w << 20) >> 20; return F(O_RCALL, (pc + 1 + (u32)k) & 0x3FFFu); } + case 0xE: return DK(O_LDI, d4, K8); + default: { + if ((w & 0x0800u) == 0) { /* BRBS / BRBC: one handler per flag and sense */ + s32 k = (s32)(w << 22) >> 25; u32 t = (pc + 1 + (u32)k) & 0x3FFFu, b = w & 7u, clr = (w >> 10) & 1u; + static const u8 BR[8] = { O_BRCS, O_BREQ, O_BRMI, O_BRVS, O_BRLT, O_BRHS, O_BRTS, O_BRIE }; + return F(BR[b] + clr, t); + } + u32 m = 1u << (w & 7u); + switch ((w >> 9) & 3u) { + case 0: return DK(O_BLD, d5, m); + case 1: return DK(O_BST, d5, m); + case 2: return DK(O_SBRC, d5 | sk2 << 5, m); + default: return DK(O_SBRS, d5 | sk2 << 5, m); + } + } + } +} + +/* ------------------------------------------------------------------ I/O registers (data addresses) */ +#define PINB 0x23 +#define DDRB 0x24 +#define PORTB 0x25 +#define PINC 0x26 +#define DDRC 0x27 +#define PORTC 0x28 +#define PIND 0x29 +#define DDRD 0x2A +#define PORTD 0x2B +#define PINE 0x2C +#define DDRE 0x2D +#define PORTE 0x2E +#define PINF 0x2F +#define DDRF 0x30 +#define PORTF 0x31 +#define TIFR0 0x35 +#define TIFR1 0x36 +#define TIFR3 0x38 +#define TIFR4 0x39 +#define EECR 0x3F +#define EEDR 0x40 +#define EEARL 0x41 +#define EEARH 0x42 +#define TCCR0A 0x44 +#define TCCR0B 0x45 +#define TCNT0 0x46 +#define OCR0A 0x47 +#define OCR0B 0x48 +#define PLLCSR 0x49 +#define SPCR 0x4C +#define SPSR 0x4D +#define SPDR 0x4E +#define SMCR 0x53 +#define MCUSR 0x54 +#define SPL 0x5D +#define SPH 0x5E +#define SREG 0x5F +#define WDTCSR 0x60 +#define TIMSK0 0x6E +#define TIMSK1 0x6F +#define TIMSK3 0x71 +#define TIMSK4 0x72 +#define ADCL 0x78 +#define ADCH 0x79 +#define ADCSRA 0x7A +#define TCCR1A 0x80 +#define TCCR3A 0x90 +#define TCNT4 0xBE +#define TC4H 0xBF +#define TCCR4A 0xC0 +#define TCCR4B 0xC1 +#define TCCR4C 0xC2 +#define TCCR4D 0xC3 +#define OCR4A 0xCF +#define OCR4B 0xD0 +#define OCR4C 0xD1 +#define OCR4D 0xD2 +#define PLLFRQ 0x52 +#define I_FLAG 0x80u + +/* ------------------------------------------------------------------ timers + * The counter is a position ph in one period P (up: P = top + 1, count = ph; both ways: P = 2 top, count goes up then + * down). Kept at cycle `base`; brought up to date (flags set) when read or changed and at each event. */ +typedef struct { + u32 base, ph, P, top, sh, mul, dual, tov_ok, temp, ocr[4]; + u8 tifr, timsk, t16; +} Tm; +static Tm g_t[4]; /* timer 0, 1, 3, 4 */ +/* AB_EVC: each timer's next event (cycle) is kept until something changes it (I/O write, flag change, interrupt); + * only a timer whose event came is brought up to date (at the latest every 4M cycles) */ +#ifndef AB_EVC +#define AB_EVC 1 +#endif +static u32 g_tat[4], g_tv; /* g_tv bit i: g_tat[i] holds */ +static const u8 T_TIFR[4] = { TIFR0, TIFR1, TIFR3, TIFR4 }, T_TIMSK[4] = { TIMSK0, TIMSK1, TIMSK3, TIMSK4 }; +/* flag bits of the compare channels and overflow */ +static const u8 T_FB[4][4] = { { 2, 4, 0, 0 }, { 2, 4, 8, 0 }, { 2, 4, 8, 0 }, { 0x40, 0x20, 0x80, 0 } }; +static const u8 T_TOV[4] = { 1, 1, 1, 4 }; +#define STOP 255u +static u32 tm_count(const Tm *t) { return t->dual && t->ph > t->top ? t->P - t->ph : t->ph; } +static u32 tm_dist(const Tm *t, u32 e) { return (e + t->P - t->ph - 1u) % t->P + 1u; } /* ticks until position e */ +static void tm_flags(Tm *t, u32 n, u8 *fl) +{ + if (!n) return; + u32 f = 0; + for (int c = 0; c < 3; c++) { + u32 v = t->ocr[c], b = T_FB[t - g_t][c]; + if (!b || v > t->top) continue; + if (tm_dist(t, v) <= n) f |= b; + else if (t->dual && v && v < t->top && tm_dist(t, t->P - v) <= n) f |= b; + } + if (t->tov_ok && tm_dist(t, 0) <= n) f |= T_TOV[t - g_t]; + *fl |= (u8)f; +} +static void tm_sync(int i) +{ + Tm *t = &g_t[i]; + if (t->sh == STOP) { t->base = A_CYC; return; } + u32 el = A_CYC - t->base, n = (el * t->mul) >> t->sh; + if (!n) return; + t->base += t->mul == 1u ? n << t->sh : ((n << t->sh) + t->mul - 1u) / t->mul; + { u8 *fl = &A_D[T_TIFR[i]]; u32 o = *fl; tm_flags(t, n, fl); if (*fl != o) g_tv &= ~(1u << i); } + t->ph = (t->ph + n % t->P) % t->P; +} +/* cycles until the next flag that would start an interrupt (0xFFFFFFFF: none) */ +static u32 tm_next(int i) +{ + Tm *t = &g_t[i]; + u32 m = A_D[T_TIMSK[i]] & ~A_D[T_TIFR[i]]; + if (t->sh == STOP || !m) return 0xFFFFFFFFu; + u32 best = 0xFFFFFFFFu; + for (int c = 0; c < 3; c++) { + u32 v = t->ocr[c], b = T_FB[i][c]; + if (!(m & b) || v > t->top) continue; + u32 dd = tm_dist(t, v); if (dd < best) best = dd; + if (t->dual && v && v < t->top) { dd = tm_dist(t, t->P - v); if (dd < best) best = dd; } + } + if ((m & T_TOV[i]) && t->tov_ok) { u32 dd = tm_dist(t, 0); if (dd < best) best = dd; } + if (best == 0xFFFFFFFFu) return best; + /* cycles: the tick `best` comes at base + best * 2^sh / mul */ + u32 at = t->base + (t->mul == 1u ? best << t->sh : ((best << t->sh) + t->mul - 1u) / t->mul); + u32 d = at - A_CYC; + return (s32)d < 0 ? 0u : d; /* already due (the clock moved on since the last sync) */ +} +static const u8 PS0[8] = { STOP, 0, 3, 6, 8, 10, STOP, STOP }; +static void tm_cfg(int i) +{ + Tm *t = &g_t[i]; u32 cnt = tm_count(t), wgm, top = 0xFF, dual = 0, tov = 1; + t->mul = 1; + if (i == 0) { + wgm = (A_D[TCCR0A] & 3u) | ((A_D[TCCR0B] >> 1) & 4u); t->sh = PS0[A_D[TCCR0B] & 7u]; + switch (wgm) { case 1: dual = 1; break; case 2: top = t->ocr[0]; tov = top == 0xFF; break; case 5: dual = 1; top = t->ocr[0]; break; case 7: top = t->ocr[0]; break; } + } else if (i < 3) { + u32 a = i == 1 ? TCCR1A : TCCR3A; + wgm = (A_D[a] & 3u) | ((A_D[a + 1] >> 1) & 12u); t->sh = PS0[A_D[a + 1] & 7u]; + static const u16 TOPS[16] = { 0xFFFF, 0xFF, 0x1FF, 0x3FF, 0, 0xFF, 0x1FF, 0x3FF, 1, 0, 1, 0, 1, 0xFFFF, 1, 0 }; + top = TOPS[wgm]; if (!top) top = t->ocr[0]; else if (top == 1) top = t->ocr[3]; /* 0: OCRnA, 1: ICRn */ + dual = (wgm >= 1 && wgm <= 3) || (wgm >= 8 && wgm <= 11); + tov = wgm == 0 || (wgm >= 5 && wgm <= 7) || wgm >= 14 || dual || top == 0xFFFF; + } else { + u32 cs = A_D[TCCR4B] & 15u; t->sh = cs ? cs - 1u : STOP; + u32 tm = (A_D[PLLFRQ] >> 4) & 3u; static const u8 MUL[4] = { 1, 6, 4, 3 }; /* PLL 96 MHz /1, /1.5, /2 */ + if (tm && (A_D[PLLCSR] & 2u)) { t->mul = MUL[tm]; if (tm == 2) t->mul = 4; } + top = t->ocr[3] ? t->ocr[3] : 0x3FF; dual = (A_D[TCCR4D] & 3u) == 1u; + } + if (top == 0) top = 1; + t->top = top; t->dual = dual; t->tov_ok = tov; t->P = dual ? 2u * top : top + 1u; + t->ph = cnt % t->P; +} + +/* ------------------------------------------------------------------ display (SSD1306) */ +static u32 g_col, g_page, g_c0 = 0, g_c1 = 127, g_p0 = 0, g_p1 = 7, g_amode = 2, g_cmd_n, g_cmd[8]; +static u32 lcd_args(u32 c) +{ + switch (c) { + case 0x81: case 0x20: case 0xA8: case 0xD3: case 0xD5: case 0xD9: case 0xDA: case 0xDB: case 0x8D: return 1; + case 0x21: case 0x22: case 0xA3: return 2; + case 0x26: case 0x27: return 6; + case 0x29: case 0x2A: return 5; + default: return 0; + } +} +#ifdef AB_TRACE +#include +#endif +/* boot: as the Arduboy's boot loader leaves the display (on, rows across); rst: the display's own reset (pin PD7) */ +static void lcd_reset(int boot) +{ + A_LCD.on = (u8)boot; A_LCD.invert = 0; A_LCD.contrast = boot ? 0xCF : 0x7F; A_LCD.flip_x = (u8)boot; A_LCD.flip_y = (u8)boot; A_LCD.allon = 0; A_LCD.start = 0; + g_col = g_page = 0; g_c0 = 0; g_c1 = 127; g_p0 = 0; g_p1 = 7; g_amode = boot ? 0 : 2; g_cmd_n = 0; +} +static void lcd_cmd(u32 c) +{ +#ifdef AB_TRACE + printf("cmd %02x\n", c); +#endif + if (g_cmd_n) { + g_cmd[g_cmd_n++] = c; + if (g_cmd_n <= lcd_args(g_cmd[0])) return; + switch (g_cmd[0]) { + case 0x81: A_LCD.contrast = (u8)g_cmd[1]; break; + case 0x20: g_amode = g_cmd[1] & 3u; break; + case 0x21: g_c0 = g_cmd[1] & 127u; g_c1 = g_cmd[2] & 127u; g_col = g_c0; break; + case 0x22: g_p0 = g_cmd[1] & 7u; g_p1 = g_cmd[2] & 7u; g_page = g_p0; break; + } + g_cmd_n = 0; return; + } + if (lcd_args(c)) { g_cmd[0] = c; g_cmd_n = 1; return; } + if (c <= 0x0F) { g_col = (g_col & 0xF0u) | c; return; } + if (c <= 0x1F) { g_col = (g_col & 0x0Fu) | ((c & 7u) << 4); return; } + if (c >= 0x40 && c <= 0x7F) { A_LCD.start = (u8)(c & 63u); return; } + if (c >= 0xB0 && c <= 0xB7) { g_page = c & 7u; return; } + switch (c) { + case 0xAE: A_LCD.on = 0; break; case 0xAF: A_LCD.on = 1; break; + case 0xA6: A_LCD.invert = 0; break; case 0xA7: A_LCD.invert = 1; break; + case 0xA4: A_LCD.allon = 0; break; case 0xA5: A_LCD.allon = 1; break; + case 0xA0: A_LCD.flip_x = 0; break; case 0xA1: A_LCD.flip_x = 1; break; + case 0xC0: A_LCD.flip_y = 0; break; case 0xC8: A_LCD.flip_y = 1; break; + } +} +/* the program may want each full picture (greys made by switching pictures) */ +__attribute__((weak)) void ab_frame(void) {} +static inline __attribute__((always_inline)) void lcd_data(u32 v) +{ +#ifdef AB_TRACE + { static u32 n, nz; n++; if (v) nz++; if ((n & 0xFFF) == 0) printf("data %u nonzero %u cyc %u\n", n, nz, A_CYC); } +#endif + u32 col = g_col; + A_GD[(g_page & 7u) * 128u + (col & 127u)] = (u8)v; + if (__builtin_expect(g_amode == 0 && col < g_c1, 1)) { g_col = col + 1u; return; } + if (g_amode == 2) { g_col = (col + 1u) & 127u; return; } + if (g_amode == 0) { + if (g_col >= g_c1) { g_col = g_c0; if (g_page >= g_p1) { g_page = g_p0; A_FRAMES++; ab_frame(); } else g_page++; } + else g_col++; + } else { + if (g_page >= g_p1) { g_page = g_p0; if (g_col >= g_c1) { g_col = g_c0; A_FRAMES++; ab_frame(); } else g_col++; } + else g_page++; + } +} + +/* ------------------------------------------------------------------ the rest of the hardware */ +/* AB_SND2: the pitch from the times of the pin changes (not their number in the window), a change of both speaker pins + * at once counts once, and sound made by PWM samples on OC4A (ATMlib) from the rising edges of the samples */ +#ifndef AB_SND2 +#define AB_SND2 1 +#endif +static u32 g_tt0, g_tt1, g_pe, g_pt0, g_pt1, g_pl, g_pd; +static u32 g_lfsr = 0xACE1u, g_tog, g_wdt_at, g_sleep, g_spm, g_pc, g_rst; +/* AB_SPIN: busy waiting (a loop that only asks the clock, as millis() and micros() do, and changes nothing) is skipped + * up to the next event. Anchor: "in rd, SREG" (the start of millis() and micros()). An iteration from the anchor back to + * it, at the same stack depth, that wrote nothing but its own stack (and the call into the anchor's function: 32 + * bytes above it) and no I/O, changes nothing but the time. */ +#ifndef AB_SPIN +#define AB_SPIN 1 +#endif +#if AB_JIT +#define g_dirty (g_mem.jit[9]) /* J_DIRTY of jit.inc */ +static u32 g_anc_pc = 0xFFFFFFFFu, g_anc_sp, g_tread; +#else +static u32 g_anc_pc = 0xFFFFFFFFu, g_anc_sp, g_dirty = 1, g_tread; +#endif +static u32 rnd(void) { g_lfsr ^= g_lfsr << 13; g_lfsr ^= g_lfsr >> 17; g_lfsr ^= g_lfsr << 5; return g_lfsr; } +#define WDT_ON (A_D[WDTCSR] & 0x48u) +static void wdt_restart(void) +{ + u32 p = (A_D[WDTCSR] & 7u) | ((A_D[WDTCSR] >> 2) & 8u); if (p > 9u) p = 9u; + g_wdt_at = A_CYC + (16000u * 16u << p); /* 16 ms << WDP */ +} +static int tm_of(u32 a, u32 *reg) +{ + if (a >= TCCR0A && a <= OCR0B) { *reg = a; return 0; } + if (a >= 0x80 && a <= 0x8D) { *reg = a; return 1; } + if (a >= 0x90 && a <= 0x9D) { *reg = a; return 2; } + if (a == TCNT4 || a == TC4H || (a >= TCCR4A && a <= 0xC4) || (a >= OCR4A && a <= OCR4D)) { *reg = a; return 3; } + return -1; +} +static u32 pins(u32 port, u32 ext) +{ + u32 ddr = A_D[port - 1]; + return (A_D[port] & ddr) | (ext & ~ddr); +} +static u8 io_rd(u32 a) +{ + u32 r; +#ifdef AB_IOSTAT + { extern u32 A_IOR[256]; A_IOR[a & 255u]++; } +#endif + switch (a) { + case PINB: case PINC: case PIND: case PINE: case PINF: return A_D[a]; /* pins_upd */ + case PLLCSR: return (u8)((A_D[PLLCSR] & ~1u) | ((A_D[PLLCSR] >> 1) & 1u)); + case SPSR: return A_D[SPSR]; + case SPDR: A_D[SPSR] &= 0x3Fu; return 0; + case ADCL: return A_D[ADCL]; + case EECR: return A_D[EECR] & ~2u; + } + int i = tm_of(a, &r); + if (i >= 0) { + tm_sync(i); Tm *t = &g_t[i]; + if (i == 0) { if (a == TCNT0) { g_tread = 1; return (u8)tm_count(t); } return A_D[a]; } + if (i < 3) { + u32 o = a - (i == 1 ? 0x80u : 0x90u); + if (o == 4) { u32 c = tm_count(t); t->temp = c >> 8; g_tread = 1; return (u8)c; } + if (o == 5) return (u8)t->temp; + if (o == 6) { t->temp = t->ocr[3] >> 8; return (u8)t->ocr[3]; } + if (o == 7) return (u8)t->temp; + if (o >= 8 && o <= 13) { u32 v = t->ocr[(o - 8) >> 1]; return (u8)(o & 1u ? v >> 8 : v); } + return A_D[a]; + } + if (a == TCNT4) { u32 c = tm_count(t); A_D[TC4H] = (u8)(c >> 8); g_tread = 1; return (u8)c; } + if (a >= OCR4A && a <= OCR4D) { static const u8 SL[4] = { 0, 1, 3, 2 }; u32 x = t->ocr[SL[a - OCR4A]]; A_D[TC4H] = (u8)(x >> 8); return (u8)x; } + return A_D[a]; + } + return A_D[a]; +} +/* returns 1 when an interrupt may now be due (the run loop looks again) */ +#ifdef AB_IOSTAT +u32 A_IOW[256], A_IOR[256]; +#endif +/* the pins as the program reads them, kept in the data space (the fast core reads them there) */ +static void pins_upd(void) +{ + u32 m = 0xFFu; if (A_KEYS & AB_UP) m &= ~0x80u; if (A_KEYS & AB_RIGHT) m &= ~0x40u; if (A_KEYS & AB_LEFT) m &= ~0x20u; if (A_KEYS & AB_DOWN) m &= ~0x10u; + A_D[PINB] = (u8)pins(PORTB, (A_KEYS & AB_B) ? 0xEFu : 0xFFu); A_D[PINC] = (u8)pins(PORTC, 0xFFu); + A_D[PIND] = (u8)pins(PORTD, 0xFFu); A_D[PINE] = (u8)pins(PORTE, (A_KEYS & AB_A) ? 0xBFu : 0xFFu); A_D[PINF] = (u8)pins(PORTF, m); +} +static int io_wr0(u32 a, u32 v); +static int io_wr(u32 a, u32 v) +{ + int r = io_wr0(a, v); + if (a >= PINB && a <= PORTF) pins_upd(); + else if (!(a >= SPCR && a <= SPDR) && !(a >= SPL && a <= SREG)) g_tv = 0; + return r; +} +static int io_wr0(u32 a, u32 v) +{ + u32 r, old; +#ifdef AB_IOSTAT + A_IOW[a & 255u]++; +#endif + if (a != SPL && a != SPH && a != SREG) g_dirty = 1; + switch (a) { + case PINB: case PINC: case PIND: case PINE: case PINF: a += 2; v = A_D[a] ^ v; /* fall through: toggle */ + case PORTB: case PORTD: case PORTE: case PORTF: case PORTC: + old = A_D[a]; A_D[a] = (u8)v; + if (a == PORTD && (old & ~v & A_D[DDRD] & 0x80u)) lcd_reset(0); /* display reset pin low */ + if (a == PORTC) { u32 x = (old ^ v) & A_D[DDRC] & 0xC0u; +#if AB_SND2 + if (x) { if (!g_tog) g_tt0 = A_CYC; g_tog++; g_tt1 = A_CYC; } +#else + g_tog += (x >> 7) + ((x >> 6) & 1u); +#endif + } + return 0; + case TIFR0: case TIFR1: case TIFR3: case TIFR4: + { int i = a == TIFR0 ? 0 : a == TIFR1 ? 1 : a == TIFR3 ? 2 : 3; tm_sync(i); A_D[a] &= (u8)~v; return 1; } + case TIMSK0: case TIMSK1: case TIMSK3: case TIMSK4: + { int i = a == TIMSK0 ? 0 : a == TIMSK1 ? 1 : a == TIMSK3 ? 2 : 3; tm_sync(i); A_D[a] = (u8)v; return 1; } + case SREG: old = A_D[SREG]; A_D[SREG] = (u8)v; return (v & ~old & I_FLAG) != 0; + case SPDR: + A_D[SPDR] = (u8)v; + if (A_D[SPCR] & 0x40u) { + if (A_D[PORTD] & 0x10u) lcd_data(v); else lcd_cmd(v); /* the display is always selected (CS not used) */ + A_D[SPSR] |= 0x80u; + return (A_D[SPCR] & 0x80u) != 0; + } + return 0; + case SPSR: A_D[SPSR] = (u8)((A_D[SPSR] & 0xFEu) | (v & 1u)); return 0; + case EECR: + A_D[EECR] = (u8)(v & 0x3Fu); + if (v & 1u) A_D[EEDR] = A_EEP[(A_D[EEARL] | A_D[EEARH] << 8) & (AVR_EEP - 1u)]; + if ((v & 2u) && (v & 4u || g_spm)) { + u32 ad = (A_D[EEARL] | A_D[EEARH] << 8) & (AVR_EEP - 1u), md = (v >> 4) & 3u, nv = md == 0 ? A_D[EEDR] : md == 1 ? 0xFFu : (A_EEP[ad] & A_D[EEDR]); + if (A_EEP[ad] != nv) { A_EEP[ad] = (u8)nv; A_EEP_DIRTY = 1; } + A_D[EECR] &= ~6u; + } + g_spm = (v & 4u) != 0; + return (v & 8u) != 0; + case ADCSRA: + A_D[ADCSRA] = (u8)(v & ~0x10u) | (A_D[ADCSRA] & 0x10u & ~v); + if (v & 0x40u) { u32 x = rnd() & 0x3FFu; A_D[ADCL] = (u8)x; A_D[ADCH] = (u8)(x >> 8); A_D[ADCSRA] = (u8)((A_D[ADCSRA] & ~0x40u) | 0x10u); return (v & 8u) != 0; } + return 0; + case WDTCSR: + A_D[WDTCSR] = (u8)((v & 0x7Fu) | (A_D[WDTCSR] & 0x80u & ~v)); + if (WDT_ON) wdt_restart(); + return 1; + case SMCR: A_D[SMCR] = (u8)v; return 0; + case MCUSR: A_D[MCUSR] = (u8)(A_D[MCUSR] & v); return 0; + case PLLCSR: A_D[PLLCSR] = (u8)(v & 0xFEu); tm_sync(3); tm_cfg(3); return 0; + case PLLFRQ: A_D[PLLFRQ] = (u8)v; tm_sync(3); tm_cfg(3); return 0; + } + int i = tm_of(a, &r); + if (i >= 0) { + tm_sync(i); Tm *t = &g_t[i]; + if (i == 0) { + if (a == TCNT0) { t->ph = v % t->P; return 1; } + A_D[a] = (u8)v; + if (a == OCR0A) t->ocr[0] = v; else if (a == OCR0B) t->ocr[1] = v; + tm_cfg(0); return 1; + } + if (i < 3) { + u32 o = a - (i == 1 ? 0x80u : 0x90u); + if (o == 5 || o == 7 || o == 9 || o == 11 || o == 13) { t->temp = v; return 0; } + u32 w = (t->temp << 8) | v; + if (o == 4) { t->ph = w % t->P; return 1; } + if (o == 6) t->ocr[3] = w; else if (o >= 8) t->ocr[(o - 8) >> 1] = w; else A_D[a] = (u8)v; + tm_cfg(i); return 1; + } + u32 w = ((A_D[TC4H] & 3u) << 8) | v; + if (a == TC4H) { A_D[TC4H] = (u8)(v & 3u); return 0; } + if (a == TCNT4) { t->ph = w % t->P; return 1; } + if (a == OCR4A) { + t->ocr[0] = w; +#if AB_SND2 + if (w > g_pl + 8u) { if (g_pd != 1u) { if (!g_pe) g_pt0 = A_CYC; g_pe++; g_pt1 = A_CYC; } g_pd = 1; } + else if (w + 8u < g_pl) g_pd = 2; + g_pl = w; +#endif + } else if (a == OCR4B) t->ocr[1] = w; + else if (a == OCR4C) t->ocr[3] = w; else if (a == OCR4D) t->ocr[2] = w; /* D has the third flag, C is the top */ + else A_D[a] = (u8)v; + tm_cfg(3); return 1; + } + A_D[a] = (u8)v; + return 0; +} +/* the interrupt to run now (vector number), 0: none */ +static u32 irq_now(void) +{ + u32 f; + if ((A_D[WDTCSR] & 0xC0u) == 0xC0u) return 12; + if ((f = A_D[TIFR1] & A_D[TIMSK1] & 0x2Fu)) return f & 0x20u ? 16 : f & 2u ? 17 : f & 4u ? 18 : f & 8u ? 19 : 20; + if ((f = A_D[TIFR0] & A_D[TIMSK0] & 7u)) return f & 2u ? 21 : f & 4u ? 22 : 23; + if ((A_D[SPSR] & 0x80u) && (A_D[SPCR] & 0x80u)) return 24; + if ((A_D[ADCSRA] & 0x18u) == 0x18u) return 29; + if (A_D[EECR] & 8u) return 30; + if ((f = A_D[TIFR3] & A_D[TIMSK3] & 0x2Fu)) return f & 0x20u ? 31 : f & 2u ? 32 : f & 4u ? 33 : f & 8u ? 34 : 35; + if ((f = A_D[TIFR4] & A_D[TIMSK4] & 0xE4u)) return f & 0x40u ? 38 : f & 0x20u ? 39 : f & 0x80u ? 40 : 41; + return 0; +} +#ifdef AB_IOSTAT +u32 A_IRQ[64]; +#endif +static void irq_ack(u32 v) +{ +#ifdef AB_IOSTAT + A_IRQ[v & 63u]++; +#endif + g_tv &= v >= 38 ? ~8u : v >= 31 ? ~4u : v >= 21 ? ~1u : v >= 16 ? ~2u : ~0u; + switch (v) { + case 12: A_D[WDTCSR] &= ~0x80u; break; + case 16: A_D[TIFR1] &= ~0x20u; break; case 17: A_D[TIFR1] &= ~2u; break; case 18: A_D[TIFR1] &= ~4u; break; case 19: A_D[TIFR1] &= ~8u; break; case 20: A_D[TIFR1] &= ~1u; break; + case 21: A_D[TIFR0] &= ~2u; break; case 22: A_D[TIFR0] &= ~4u; break; case 23: A_D[TIFR0] &= ~1u; break; + case 24: A_D[SPSR] &= ~0x80u; break; case 29: A_D[ADCSRA] &= ~0x10u; break; + case 31: A_D[TIFR3] &= ~0x20u; break; case 32: A_D[TIFR3] &= ~2u; break; case 33: A_D[TIFR3] &= ~4u; break; case 34: A_D[TIFR3] &= ~8u; break; case 35: A_D[TIFR3] &= ~1u; break; + case 38: A_D[TIFR4] &= ~0x40u; break; case 39: A_D[TIFR4] &= ~0x20u; break; case 40: A_D[TIFR4] &= ~0x80u; break; case 41: A_D[TIFR4] &= ~4u; break; + } +} +static void ev_sync(void) +{ +#if AB_EVC + for (int i = 0; i < 4; i++) if (!(g_tv & (1u << i)) || (s32)(A_CYC - g_tat[i]) >= 0) { tm_sync(i); g_tv &= ~(1u << i); } +#else + for (int i = 0; i < 4; i++) tm_sync(i); +#endif + if (WDT_ON && (s32)(A_CYC - g_wdt_at) >= 0) { + if (A_D[WDTCSR] & 0x40u) { A_D[WDTCSR] |= 0x80u; wdt_restart(); } + else { ab_reset(); A_D[MCUSR] |= 8u; } + } +} +static u32 ev_next(void) +{ + u32 b = 0xFFFFFFFFu; +#if AB_EVC + for (int i = 0; i < 4; i++) { + if (!(g_tv & (1u << i))) { u32 n = tm_next(i); g_tat[i] = A_CYC + (n < 0x400000u ? n : 0x400000u); g_tv |= 1u << i; } + u32 n = g_tat[i] - A_CYC; if ((s32)n < 0) n = 0; if (n < b) b = n; + } +#else + for (int i = 0; i < 4; i++) { u32 n = tm_next(i); if (n < b) b = n; } +#endif + if (WDT_ON) { u32 n = g_wdt_at - A_CYC; if ((s32)n < 0) n = 0; if (n < b) b = n; } + return b; +} + +/* ------------------------------------------------------------------ program */ +#if !AB_JIT +static void *const *g_T; /* the handlers (filled in by the first ab_run(0)) */ +#if defined(__arm__) && !defined(AB_INDEX) +#define AB_ADDR 1 /* the handler's address in the op (PRAM is below 64 KB) */ +#else +#define AB_ADDR 0 +#endif +static u32 op_of(u32 o) { u32 i = o & 0xFFFFu; return AB_ADDR ? (o & 0xFFFF0000u) | ((u32)(uintptr_t)g_T[i] & 0xFFFFu) : o; } +void ab_load(const u16 *flash, u32 words) +{ + if (!g_T) ab_run(0); + A_FLASH = flash; g_words = words; + for (u32 pc = 0; pc < AVR_FLASH_WORDS; pc++) A_OP[pc] = op_of(pc < words ? decode(pc) : O_BAD); + for (u32 pc = 0; pc + 1 < words; pc++) { /* LDS, STS: the address in the next slot */ + u32 w = flash[pc]; + if ((w & 0xFE0Fu) == 0x9000u || (w & 0xFE0Fu) == 0x9200u) A_OP[pc + 1] = op_of(F(O_BAD, flash[pc + 1])); + } + for (u32 pc = AVR_FLASH_WORDS; pc < AVR_FLASH_WORDS + 4; pc++) A_OP[pc] = op_of(O_BAD); +} +#endif +void ab_reset(void) +{ + for (u32 i = 0; i < AVR_DATA; i++) A_D[i] = 0; + A_D[SPL] = (u8)(AVR_DATA - 1u); A_D[SPH] = (u8)((AVR_DATA - 1u) >> 8); + A_D[PLLFRQ] = 0x04; A_D[0x61] = 0; A_D[MCUSR] = 1; + for (int i = 0; i < 4; i++) { Tm *t = &g_t[i]; for (u32 k = 0; k < sizeof *t; k++) ((u8 *)t)[k] = 0; t->base = A_CYC; } + g_t[3].ocr[3] = 0xFF; + for (int i = 0; i < 4; i++) tm_cfg(i); + lcd_reset(1); + g_sleep = 0; g_spm = 0; g_pc = 0; g_rst = 1; g_dirty = 1; g_anc_pc = 0xFFFFFFFFu; g_tv = 0; pins_upd(); +} + +#if !AB_JIT +/* ------------------------------------------------------------------ the CPU + * Flags are kept apart and put together only when SREG is read: fc = C (0/1), fz = 0 exactly when Z, fn bit 7 = N, + * fv bit 7 = V, fh bit 4 = H, S = N ^ V; sr keeps I and T. left: cycles until the next event (lim). */ +#define T_F 64u +#define R(i) D[i] +#define RW(i) (D[i] | (u32)D[(i) + 1] << 8) +#define SP_GET() (D[SPL] | (u32)D[SPH] << 8) +#define SP_SET(v) do { u32 _v = (v); D[SPL] = (u8)_v; D[SPH] = (u8)(_v >> 8); } while (0) +#define PUSHB(v) do { u32 _s = SP_GET(); D[_s < 0x1000u ? _s : 0xFFFu] = (u8)(v); if (_s > g_anc_sp + 32u) g_dirty = 1; SP_SET(_s - 1u); } while (0) +#define POPB() ({ u32 _s = SP_GET() + 1u; SP_SET(_s); D[_s < 0x1000u ? _s : 0xFFFu]; }) +#define PUSHPC(p) do { PUSHB(p); PUSHB((p) >> 8); } while (0) +#define POPPC() ({ u32 _h = POPB(); u32 _l = POPB(); ((_h << 8) | _l) & 0x3FFFu; }) + +AVR_FAST void ab_run(u32 cycles) +{ + static void *const T[O_N] = { + &&nop, &&movw, &&muls, &&mulsu, &&fmul, &&fmuls, &&fmulsu, &&cpc, &&sbc, &&add, &&cpse, &&cp, &&sub, &&adc, &&and_, + &&eor, &&or_, &&mov, &&cpi, &&sbci, &&subi, &&ori, &&andi, &&lddy, &&lddz, &&stdy, &&stdz, &&lds, &&ldzp, &&ldmz, + &&lpmz, &&lpmzp, &&ldyp, &&ldmy, &&ldx, &&ldxp, &&ldmx, &&pop, &&sts, &&stzp, &&stmz, &&styp, &&stmy, &&stx, &&stxp, + &&stmx, &&push, &&com, &&neg, &&swap, &&inc, &&asr, &&lsr, &&ror, &&dec, &&bset, &&bclr, &&ret, &&reti, &&sleep, + &&wdr, &&lpm0, &&ijmp, &&icall, &&jmp, &&call, &&adiw, &&sbiw, &&cbi, &&sbic, &&sbi, &&sbis, &&mul, &&in, &&out, + &&rjmp, &&rcall, &&ldi, &&bld, &&bst, &&sbrc, &&sbrs, &&insreg, &&outsreg, + &&breq, &&brne, &&brcs, &&brcc, &&brmi, &&brpl, &&brvs, &&brvc, &&brlt, &&brge, &&brhs, &&brhc, &&brts, &&brtc, + &&brie, &&brid, &&bad }; + if (!cycles) { g_T = T; return; } + u8 *D = A_D; __asm__("" : "+r"(D)); /* one base register for the data space */ + u32 end = A_CYC + cycles, pc = g_pc, lim, sr, fc, fz, fn, fv, fh, o, d, a, b, v, res; + s32 left; + const u32 *ip; + pins_upd(); /* the buttons */ + for (;;) { + g_rst = 0; ev_sync(); if (g_rst) pc = 0; + if ((D[SREG] & I_FLAG) && (v = irq_now())) { + irq_ack(v); + if (g_sleep) { g_sleep = 0; A_CYC += 4; } + PUSHPC(pc); D[SREG] &= ~I_FLAG; pc = v * 2u; A_CYC += 5; + } + if ((s32)(A_CYC - end) >= 0) break; + lim = ev_next(); lim = lim < end - A_CYC ? A_CYC + lim : end; + if (g_sleep) { A_CYC = lim; continue; } + left = (s32)(lim - A_CYC); + v = D[SREG]; sr = v & 0xC0u; fc = v & 1u; fz = (v & 2u) ? 0u : 1u; fn = (v & 4u) << 5; fv = (v & 8u) << 4; fh = (v & 32u) >> 1; + ip = A_OP + pc; +#define SRG() ((sr & 0xC0u) | fc | (fz ? 0u : 2u) | ((fn >> 5) & 4u) | ((fv >> 4) & 8u) | (((fn ^ fv) >> 3) & 16u) | ((fh << 1) & 32u)) +#define SRSET(x) do { u32 _x = (x); sr = _x & 0xC0u; fc = _x & 1u; fz = (_x & 2u) ? 0u : 1u; fn = (_x & 4u) << 5; fv = (_x & 8u) << 4; fh = (_x & 32u) >> 1; } while (0) +#define CYC() (lim - (u32)left) +#define SAVE() do { A_CYC = CYC(); } while (0) +#define BREAK_AFTER() do { lim -= (u32)left; left = 0; } while (0) /* leave after this instruction */ +#define ONE_MORE(n) do { lim = lim - (u32)left + (n) + 1u; left = (s32)(n) + 1; } while (0) +#if AB_ADDR +#define GO() goto *(void *)(uintptr_t)(o & 0xFFFFu) +#else +#define GO() goto *T[o & 255u] +#endif +#ifdef AB_COUNT +#define CNT A_INS++; A_OPC[(AB_ADDR ? 0 : o & 255u)]++; A_PCH[PCNOW & 0x3FFFu]++; +#else +#define CNT +#endif +#define NEXT(n) do { CNT left -= (s32)(n); if (left <= 0) goto leave; o = *ip; GO(); } while (0) +/* straight on: the event check waits for the next jump (a block of straight code is short) */ +#ifdef AB_SINGLE +#define STEP(n) do { ip++; NEXT(n); } while (0) /* tests: one instruction per ab_run(1) */ +#else +#define STEP(n) do { CNT left -= (s32)(n); o = *++ip; GO(); } while (0) +#endif +#define D5 ((o >> 16) & 31u) +#define R5 ((o >> 21) & 31u) +#define KH (o >> 24) +#define T14 (o >> 16) +#define RD_DATA(ad, dst) do { u32 _a = (ad); if (_a >= 0x100u) dst = D[_a < 0x1000u ? _a : 0xFFFu]; /* as the fast core: beyond the 4 KB on its last byte */ else if (_a < 0x20u) dst = D[_a]; else if (_a == SREG) dst = SRG(); else { SAVE(); dst = io_rd(_a); } } while (0) +#define WR_DATA(ad, val) do { u32 _a = (ad); if (_a >= 0x100u) { D[_a < 0x1000u ? _a : 0xFFFu] = (u8)(val); if (_a < SP_GET() || _a > g_anc_sp + 32u) g_dirty = 1; } \ + else if (_a < 0x20u) D[_a] = (u8)(val); else if (_a == SREG) { u32 _v = (val); if ((_v & ~sr & I_FLAG) && irq_now()) ONE_MORE(2u); SRSET(_v); } \ + else { SAVE(); if (io_wr(_a, (val))) BREAK_AFTER(); } } while (0) +#define JUMP(t) (ip = A_OP + (t)) +#define PCNOW ((u32)(ip - A_OP)) + o = *ip; GO(); + nop: STEP(1); + movw: d = D5; a = R5; D[d] = D[a]; D[d + 1] = D[a + 1]; STEP(1); + muls: res = (u32)((s32)(int8_t)R(D5) * (s32)(int8_t)R(R5)) & 0xFFFFu; goto mulf; + mulsu: res = (u32)((s32)(int8_t)R(D5) * (s32)R(R5)) & 0xFFFFu; goto mulf; + mul: res = (u32)R(D5) * R(R5); + mulf: D[0] = (u8)res; D[1] = (u8)(res >> 8); fc = res >> 15; fz = res; STEP(2); + fmul: res = (u32)R(D5) * R(R5); goto fmulf; + fmuls: res = (u32)((s32)(int8_t)R(D5) * (s32)(int8_t)R(R5)) & 0xFFFFu; goto fmulf; + fmulsu: res = (u32)((s32)(int8_t)R(D5) * (s32)R(R5)) & 0xFFFFu; + fmulf: fc = res >> 15; res = (res << 1) & 0xFFFFu; fz = res; D[0] = (u8)res; D[1] = (u8)(res >> 8); STEP(2); +#define ADDF(a_, b_, r_) do { fc = (r_) >> 8; fz = (r_) & 0xFFu; fn = (r_); fv = ((a_) ^ (r_)) & ((b_) ^ (r_)); fh = (a_) ^ (b_) ^ (r_); } while (0) +#define SUBF(a_, b_, r_) do { fc = ((r_) >> 8) & 1u; fz = (r_) & 0xFFu; fn = (r_); fv = ((a_) ^ (b_)) & ((a_) ^ (r_)); fh = (a_) ^ (b_) ^ (r_); } while (0) +#define SBCF(a_, b_, r_) do { fc = ((r_) >> 8) & 1u; fz |= (r_) & 0xFFu; fn = (r_); fv = ((a_) ^ (b_)) & ((a_) ^ (r_)); fh = (a_) ^ (b_) ^ (r_); } while (0) + add: d = D5; a = R(d); b = R(R5); res = a + b; D[d] = (u8)res; ADDF(a, b, res); STEP(1); + adc: d = D5; a = R(d); b = R(R5); res = a + b + fc; D[d] = (u8)res; ADDF(a, b, res); STEP(1); + sub: d = D5; a = R(d); b = R(R5); res = a - b; D[d] = (u8)res; SUBF(a, b, res); STEP(1); + sbc: d = D5; a = R(d); b = R(R5); res = a - b - fc; D[d] = (u8)res; SBCF(a, b, res); STEP(1); + cp: a = R(D5); b = R(R5); res = a - b; SUBF(a, b, res); STEP(1); + cpc: a = R(D5); b = R(R5); res = a - b - fc; SBCF(a, b, res); STEP(1); + cpi: a = R(D5); b = KH; res = a - b; SUBF(a, b, res); STEP(1); + subi: d = D5; a = R(d); b = KH; res = a - b; D[d] = (u8)res; SUBF(a, b, res); STEP(1); + sbci: d = D5; a = R(d); b = KH; res = a - b - fc; D[d] = (u8)res; SBCF(a, b, res); STEP(1); + cpse: if (R(D5) == R(R5)) { a = (o >> 26) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1); + and_: d = D5; res = R(d) & R(R5); goto logic; + eor: d = D5; res = R(d) ^ R(R5); goto logic; + or_: d = D5; res = R(d) | R(R5); goto logic; + andi: d = D5; res = R(d) & KH; goto logic; + ori: d = D5; res = R(d) | KH; + logic: D[d] = (u8)res; fz = res; fn = res; fv = 0; STEP(1); + mov: D[D5] = D[R5]; STEP(1); + ldi: D[D5] = (u8)KH; STEP(1); + lddy: a = RW(28) + KH; goto ldd; + lddz: a = RW(30) + KH; + ldd: RD_DATA(a & 0xFFFFu, v); D[D5] = (u8)v; STEP(2); + stdy: a = RW(28) + KH; goto std_; + stdz: a = RW(30) + KH; + std_: v = D[D5]; WR_DATA(a & 0xFFFFu, v); STEP(2); + lds: a = ip[1] >> 16; RD_DATA(a, v); D[D5] = (u8)v; ip += 2; NEXT(2); + sts: a = ip[1] >> 16; v = D[D5]; WR_DATA(a, v); ip += 2; NEXT(2); +#define PTR_LD(rp, pre, post) do { a = RW(rp); if (pre) a = (a - 1u) & 0xFFFFu; RD_DATA(a, v); if (post) a = (a + 1u) & 0xFFFFu; if ((pre) || (post)) { D[rp] = (u8)a; D[rp + 1] = (u8)(a >> 8); } D[D5] = (u8)v; } while (0) +#define PTR_ST(rp, pre, post) do { a = RW(rp); if (pre) a = (a - 1u) & 0xFFFFu; v = D[D5]; WR_DATA(a, v); if (post) a = (a + 1u) & 0xFFFFu; if ((pre) || (post)) { D[rp] = (u8)a; D[rp + 1] = (u8)(a >> 8); } } while (0) + ldzp: PTR_LD(30, 0, 1); STEP(2); + ldmz: PTR_LD(30, 1, 0); STEP(2); + ldyp: PTR_LD(28, 0, 1); STEP(2); + ldmy: PTR_LD(28, 1, 0); STEP(2); + ldx: PTR_LD(26, 0, 0); STEP(2); + ldxp: PTR_LD(26, 0, 1); STEP(2); + ldmx: PTR_LD(26, 1, 0); STEP(2); + stzp: PTR_ST(30, 0, 1); STEP(2); + stmz: PTR_ST(30, 1, 0); STEP(2); + styp: PTR_ST(28, 0, 1); STEP(2); + stmy: PTR_ST(28, 1, 0); STEP(2); + stx: PTR_ST(26, 0, 0); STEP(2); + stxp: PTR_ST(26, 0, 1); STEP(2); + stmx: PTR_ST(26, 1, 0); STEP(2); + lpmz: a = RW(30); D[D5] = (u8)(A_FLASH[(a >> 1) & 0x3FFFu] >> ((a & 1u) * 8u)); STEP(3); + lpmzp: a = RW(30); D[D5] = (u8)(A_FLASH[(a >> 1) & 0x3FFFu] >> ((a & 1u) * 8u)); a = (a + 1u) & 0xFFFFu; D[30] = (u8)a; D[31] = (u8)(a >> 8); STEP(3); + lpm0: a = RW(30); D[0] = (u8)(A_FLASH[(a >> 1) & 0x3FFFu] >> ((a & 1u) * 8u)); STEP(3); + push: PUSHB(D[D5]); STEP(2); + pop: D[D5] = (u8)POPB(); STEP(2); + com: d = D5; res = ~R(d) & 0xFFu; D[d] = (u8)res; fc = 1; fv = 0; fn = fz = res; STEP(1); + neg: d = D5; a = R(d); res = 0u - a; D[d] = (u8)res; SUBF(0u, a, res); STEP(1); + swap: d = D5; a = R(d); D[d] = (u8)((a >> 4) | (a << 4)); STEP(1); + inc: d = D5; a = R(d); res = (a + 1u) & 0xFFu; D[d] = (u8)res; fv = res & ~a; fn = fz = res; STEP(1); + dec: d = D5; a = R(d); res = (a - 1u) & 0xFFu; D[d] = (u8)res; fv = a & ~res; fn = fz = res; STEP(1); + asr: d = D5; a = R(d); res = (a >> 1) | (a & 0x80u); goto shf; + lsr: d = D5; a = R(d); res = a >> 1; goto shf; + ror: d = D5; a = R(d); res = (a >> 1) | (fc << 7); + shf: D[d] = (u8)res; fc = a & 1u; fn = fz = res; fv = res ^ (fc << 7); STEP(1); + bset: v = SRG(); a = (o >> 16) & 255u; if ((a & ~v & I_FLAG) && irq_now()) ONE_MORE(1u); SRSET(v | a); STEP(1); + bclr: v = SRG(); SRSET(v & ~(o >> 16)); STEP(1); + bst: sr = (sr & ~T_F) | ((D[D5] & KH) ? T_F : 0u); STEP(1); + bld: d = D5; if (sr & T_F) D[d] |= (u8)KH; else D[d] &= (u8)~KH; STEP(1); + ret: JUMP(POPPC()); NEXT(4); + reti: JUMP(POPPC()); sr |= I_FLAG; if (irq_now()) ONE_MORE(4u); NEXT(4); + sleep: ip++; if (D[SMCR] & 1u) { g_sleep = 1; BREAK_AFTER(); } NEXT(1); + wdr: if (WDT_ON) { SAVE(); wdt_restart(); } STEP(1); + ijmp: JUMP(RW(30) & 0x3FFFu); NEXT(2); + icall: a = PCNOW + 1u; PUSHPC(a); JUMP(RW(30) & 0x3FFFu); NEXT(3); + jmp: JUMP(T14); NEXT(3); + call: a = PCNOW + 2u; PUSHPC(a); JUMP(T14); NEXT(4); + rjmp: JUMP(T14); NEXT(2); + rcall: a = PCNOW + 1u; PUSHPC(a); JUMP(T14); NEXT(3); + adiw: d = D5; a = RW(d); res = (a + KH) & 0xFFFFu; D[d] = (u8)res; D[d + 1] = (u8)(res >> 8); + fz = res; fn = res >> 8; fc = ((a & ~res) >> 15) & 1u; fv = (res & ~a) >> 8; STEP(2); + sbiw: d = D5; a = RW(d); res = (a - KH) & 0xFFFFu; D[d] = (u8)res; D[d + 1] = (u8)(res >> 8); + fz = res; fn = res >> 8; fc = ((res & ~a) >> 15) & 1u; fv = (a & ~res) >> 8; STEP(2); +#define IOA (((o >> 24) & 31u) + 0x20u) +#define IOM ((o >> 16) & 255u) +#define IS_PIN(a_) ((a_) >= PINB && (a_) <= PORTF && ((a_) - PINB) % 3u == 0u) +#define IS_FLAG(a_) ((a_) >= TIFR0 && (a_) <= TIFR4) + cbi: a = IOA; SAVE(); + if (!IS_PIN(a) && !IS_FLAG(a)) { v = io_rd(a) & ~IOM; if (io_wr(a, v)) BREAK_AFTER(); } + STEP(2); + sbi: a = IOA; SAVE(); + v = (IS_PIN(a) || IS_FLAG(a)) ? IOM : io_rd(a) | IOM; + if (io_wr(a, v)) BREAK_AFTER(); + STEP(2); + sbic: a = IOA; SAVE(); v = io_rd(a); if (!(v & IOM)) { a = (o >> 29) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1); + sbis: a = IOA; SAVE(); v = io_rd(a); if (v & IOM) { a = (o >> 29) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1); + sbrc: if (!(D[D5] & KH)) { a = (o >> 21) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1); + sbrs: if (D[D5] & KH) { a = (o >> 21) & 1u; ip += 2u + a; NEXT(2u + a); } STEP(1); + in: SAVE(); D[D5] = io_rd(KH); STEP(1); + out: SAVE(); if (io_wr(KH, D[D5])) BREAK_AFTER(); STEP(1); + outsreg: v = D[D5]; if ((v & ~sr & I_FLAG) && irq_now()) ONE_MORE(1u); SRSET(v); STEP(1); + insreg: D[D5] = (u8)SRG(); + if (AB_SPIN) { /* busy waiting: see g_anc_pc */ + u32 sp = SP_GET(), pcn = PCNOW; + if (pcn == g_anc_pc && sp == g_anc_sp) { + if (!g_dirty) { + u32 cyc = CYC(), to = lim; if (g_tread && to - cyc > 512u) to = cyc + 512u; + if ((s32)(to - cyc) > 1) left = (s32)(lim - to) + 1; /* after this instruction the time is `to` */ + } + g_dirty = 0; g_tread = 0; + } else if (g_dirty) { g_anc_pc = pcn; g_anc_sp = sp; g_dirty = 0; g_tread = 0; } + } + STEP(1); + breq: if (!fz) { JUMP(T14); NEXT(2); } STEP(1); + brne: if (fz) { JUMP(T14); NEXT(2); } STEP(1); + brcs: if (fc) { JUMP(T14); NEXT(2); } STEP(1); + brcc: if (!fc) { JUMP(T14); NEXT(2); } STEP(1); + brmi: if (fn & 0x80u) { JUMP(T14); NEXT(2); } STEP(1); + brpl: if (!(fn & 0x80u)) { JUMP(T14); NEXT(2); } STEP(1); + brvs: if (fv & 0x80u) { JUMP(T14); NEXT(2); } STEP(1); + brvc: if (!(fv & 0x80u)) { JUMP(T14); NEXT(2); } STEP(1); + brlt: if ((fn ^ fv) & 0x80u) { JUMP(T14); NEXT(2); } STEP(1); + brge: if (!((fn ^ fv) & 0x80u)) { JUMP(T14); NEXT(2); } STEP(1); + brhs: if (fh & 0x10u) { JUMP(T14); NEXT(2); } STEP(1); + brhc: if (!(fh & 0x10u)) { JUMP(T14); NEXT(2); } STEP(1); + brts: if (sr & T_F) { JUMP(T14); NEXT(2); } STEP(1); + brtc: if (!(sr & T_F)) { JUMP(T14); NEXT(2); } STEP(1); + brie: if (sr & I_FLAG) { JUMP(T14); NEXT(2); } STEP(1); + brid: if (!(sr & I_FLAG)) { JUMP(T14); NEXT(2); } STEP(1); + bad: JUMP((PCNOW + 1u) & 0x3FFFu); NEXT(1); + leave: + A_CYC = CYC(); D[SREG] = (u8)SRG(); pc = PCNOW; + } + g_pc = pc; +} +#undef SAVE + +#endif +/* ------------------------------------------------------------------ sound */ +u32 ab_tone(u32 cycles) +{ + u32 t = g_tog; g_tog = 0; + /* timer 3 toggling OC3A (PC6) in CTC mode */ + if ((A_D[TCCR3A] & 0xC0u) == 0x40u && (A_D[DDRC] & 0x40u) && g_t[2].sh != STOP) + return (16000000u / (2u << g_t[2].sh)) / (g_t[2].top + 1u); + /* timer 4 toggling OC4A (PC7) */ + if ((A_D[TCCR4A] & 0xC2u) == 0x40u && (A_D[DDRC] & 0x80u) && g_t[3].sh != STOP) /* not PWM4A: there 01 is PWM on both pins */ + return (16000000u / (2u << g_t[3].sh)) * g_t[3].mul / (g_t[3].top + 1u); +#if AB_SND2 + u32 e = g_pe; g_pe = 0; + if (t >= 3u && g_tt1 != g_tt0) return (t - 1u) * 8000000u / (g_tt1 - g_tt0); /* two changes per period */ + if (e >= 2u && e < 250u && g_pt1 != g_pt0 && (A_D[TCCR4A] & 0xC2u) > 0x02u) return (e - 1u) * 16000000u / (g_pt1 - g_pt0); + return 0; +#else + if (t < 4u || !cycles) return 0; + cycles /= 1000u; if (!cycles) return 0; + return t * 8000u / cycles; +#endif +} + +/* ------------------------------------------------------------------ state */ +#define ST_ID 0x31534241u /* "ABS1" */ +u32 ab_state_save(u8 *buf, u32 size) +{ + struct { void *p; u32 n; } P[] = { { A_D, AVR_DATA }, { A_GD, 1024 }, { &A_LCD, sizeof A_LCD }, { g_t, sizeof g_t }, + { &g_pc, 4 }, { &A_CYC, 4 }, { &g_col, 4 }, { &g_page, 4 }, { &g_c0, 4 }, { &g_c1, 4 }, { &g_p0, 4 }, { &g_p1, 4 }, + { &g_amode, 4 }, { &g_cmd_n, 4 }, { g_cmd, sizeof g_cmd }, { &g_lfsr, 4 }, { &g_wdt_at, 4 }, { &g_sleep, 4 } }; + u32 n = 4; if (size < 4) return 0; + buf[0] = 'A'; buf[1] = 'B'; buf[2] = 'S'; buf[3] = '1'; + for (u32 i = 0; i < sizeof P / sizeof P[0]; i++) { if (n + P[i].n > size) return 0; for (u32 k = 0; k < P[i].n; k++) buf[n + k] = ((u8 *)P[i].p)[k]; n += P[i].n; } + return n; +} +int ab_state_load(const u8 *buf, u32 size) +{ + struct { void *p; u32 n; } P[] = { { A_D, AVR_DATA }, { A_GD, 1024 }, { &A_LCD, sizeof A_LCD }, { g_t, sizeof g_t }, + { &g_pc, 4 }, { &A_CYC, 4 }, { &g_col, 4 }, { &g_page, 4 }, { &g_c0, 4 }, { &g_c1, 4 }, { &g_p0, 4 }, { &g_p1, 4 }, + { &g_amode, 4 }, { &g_cmd_n, 4 }, { g_cmd, sizeof g_cmd }, { &g_lfsr, 4 }, { &g_wdt_at, 4 }, { &g_sleep, 4 } }; + u32 n = 4, tot = 4; + for (u32 i = 0; i < sizeof P / sizeof P[0]; i++) tot += P[i].n; + if (size < tot || buf[0] != 'A' || buf[1] != 'B' || buf[2] != 'S' || buf[3] != '1') return 0; + for (u32 i = 0; i < sizeof P / sizeof P[0]; i++) { for (u32 k = 0; k < P[i].n; k++) ((u8 *)P[i].p)[k] = buf[n + k]; n += P[i].n; } + g_tv = 0; pins_upd(); + return 1; +} +#if !AB_JIT +u8 *ab_scratch(void) { static u8 b[AB_SCRATCH] __attribute__((aligned(4))); return b; } +#endif +u32 ab_pc(void) { return g_pc; } +void ab_set_pc(u32 p) { g_pc = p; } +void ab_wake(void) { g_sleep = 0; } +u32 ab_tm(int i, int c) { return c < 4 ? g_t[i].ocr[c] : c == 4 ? g_t[i].top : g_t[i].sh; } +#if AB_JIT +#include "jit.inc" +#endif diff --git a/ab/src/core/avr.h b/ab/src/core/avr.h new file mode 100644 index 0000000..e3588f1 --- /dev/null +++ b/ab/src/core/avr.h @@ -0,0 +1,57 @@ +/* ArduboyEmu: the ATmega32U4 of the Arduboy (16 MHz AVR) with what the Arduboy uses of it: timers 0, 1, 3, 4, SPI to + * the SSD1306 display, the buttons, EEPROM, ADC (random seeds), the PLL and an idle USB, the speaker pins. + * Own code, no other emulator in it. Author: mameise. License: GPL-3.0-or-later (as Paramix Studio). */ +#ifndef AVR_H +#define AVR_H +#include +typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef int32_t s32; + +#define AVR_FLASH_WORDS 16384u +#define AVR_DATA 0xB00u /* 32 registers, 64 + 160 I/O, 2.5 KB SRAM */ +#define AVR_EEP 1024u + +/* buttons (pressed = 1) */ +#define AB_UP 1u +#define AB_DOWN 2u +#define AB_LEFT 4u +#define AB_RIGHT 8u +#define AB_A 16u +#define AB_B 32u + +#if (defined(__arm__) && !defined(AB_NOJIT)) || defined(AB_JIT_HOST) +#define AB_JIT 1 /* the fast core (jit.inc) */ +#else +#define AB_JIT 0 +#endif +/* the data space (4 KB: addresses are masked), the fast core's context just before it */ +typedef struct { u32 jit[64]; u8 d[0x1000]; } AbMem; +extern AbMem g_mem; +#define A_D (g_mem.d) +extern u8 A_EEP[AVR_EEP]; +extern u8 A_GD[1024]; /* the display's memory: 8 pages of 128 columns */ +#if !AB_JIT +extern u32 A_OP[AVR_FLASH_WORDS + 4]; /* the program, decoded */ +#endif +extern const u16 *A_FLASH; /* the program as it is (words, little endian) */ +extern u32 A_CYC; /* cycles run (wraps) */ +extern int A_EEP_DIRTY; /* the game wrote the EEPROM */ +extern u32 A_KEYS; /* buttons held */ +extern u32 A_FRAMES; /* display frames sent (1024 data bytes) */ +/* display state the program needs to draw */ +typedef struct { u8 on, invert, contrast, flip_x, flip_y, allon, start; } AvrLcd; +extern AvrLcd A_LCD; + +void ab_frame(void); /* called after each full picture (weak, the program may give its own) */ +void ab_load(const u16 *flash, u32 words); /* decode the program (words beyond: 0xFFFF) */ +void ab_reset(void); +void ab_run(u32 cycles); /* run about this many cycles */ +/* the speaker: tone in Hz (0 silent), from the timers driving the pins or the pin changes counted since the last call + * over `cycles` */ +u32 ab_tone(u32 cycles); +/* state save / load (registers, data, timers, display): bytes used, 0 when it did not fit */ +u32 ab_state_save(u8 *buf, u32 size); +/* 9 KB of scratch memory for the program between runs (with the fast core: the end of its cache, emptied) */ +#define AB_SCRATCH 0x2400u +u8 *ab_scratch(void); +int ab_state_load(const u8 *buf, u32 size); +#endif diff --git a/ab/src/core/jit.inc b/ab/src/core/jit.inc new file mode 100644 index 0000000..c7b7dfe --- /dev/null +++ b/ab/src/core/jit.inc @@ -0,0 +1,763 @@ +/* ArduboyEmu AB_JIT: the AVR program translated block by block into Thumb-2 for the Paradise's Cortex-M3 (code in + * the SRAM: a cache, emptied when full). Included at the end of avr.c (uses its I/O, timers and interrupts). + * + * Registers of the translated code: r4 = the data space D (the context lies just before it), r5 = cycles left until + * the next event, r6 = fz (0 exactly when Z), r7 = fc (C, 0/1), r8 = fn (bit 7 N), r9 = fv (bit 7 V), r10 = fh + * (bit 4 H), r11 = I and T (bits 7, 6). r0..r3, r12, lr are free. A block ends at a jump, a branch, a skip, a call, + * a return or after JB_MAX instructions; it subtracts its cycles and goes to the dispatcher with the next pc in r0. + * The dispatcher leaves for C when no cycles are left. Flags are worked out only where something later reads them + * (in the block, or at its end: C, Z, N, V; H only for an instruction that reads it in the same block). + * Rare instructions (I/O, SREG, sleep ...) run in C (jit_op) with the flags handed over in the context. + * Author: mameise. License: GPL-3.0-or-later. */ + +#ifndef T_F +#define T_F 64u +#endif +/* ---- the context before D: g_mem.jit[i] lies at D - 4 * (64 - i) ---- */ +enum { J_XLATE = 1, J_OP, J_LD, J_ST, J_MAP, J_CODE1, J_FLASH, J_PC, J_DIRTY, J_IN, J_OUT, J_BIT, J_SPDR, + J_LEFT = 56, J_FZ, J_FC, J_FN, J_FV, J_FH, J_SR, J_SPARE }; +#define JOFF(i) (4u * (64u - (i))) /* offset below D */ +#define JC (g_mem.jit) + +#ifndef JIT_CACHE +#define JIT_CACHE 0x11C00u /* bytes of translated code (71 KB; its last 9 KB are also ab_scratch) */ +#endif +#define JB_MAX 40u +static u16 g_map[AVR_FLASH_WORDS]; /* pc -> code (in halfwords from g_code, 0: not translated) */ +static u16 g_code[JIT_CACHE / 2] __attribute__((aligned(4))); +static u16 *g_ep, *g_cend; /* emit pointer, end of the cache */ +static u32 g_stub_enter, g_stub_disp, g_stub_exit; /* halfword offsets in g_code */ +static u32 g_hold, g_flushes; +#define PEND_N 512u +static u16 g_pend_at[PEND_N], g_pend_pc[PEND_N]; static u32 g_npend, g_blk_pc, g_blk_at; /* AB_CHAIN */ + +/* ---------------- Thumb-2 encoder ---------------- */ +static void H1(u32 x) { if (g_ep < g_cend) *g_ep = (u16)x; g_ep++; } +static void H2(u32 a, u32 b) { H1(a); H1(b); } +#define LDRB_I 0xF890u +#define STRB_I 0xF880u +#define LDRH_I 0xF8B0u +#define STRH_I 0xF8A0u +#define LDR_I 0xF8D0u +#define STR_I 0xF8C0u +static void mem_i(u32 op, u32 rt, u32 rn, u32 imm) +{ + if (rt < 8u && rn < 8u) { /* the 16-bit forms (half the code) */ + if ((op == LDRB_I || op == STRB_I) && imm < 32u) { H1((op == LDRB_I ? 0x7800u : 0x7000u) | (imm << 6) | (rn << 3) | rt); return; } + if ((op == LDRH_I || op == STRH_I) && imm < 64u && !(imm & 1u)) { H1((op == LDRH_I ? 0x8800u : 0x8000u) | ((imm >> 1) << 6) | (rn << 3) | rt); return; } + } + H2(op | rn, (rt << 12) | (imm & 0xFFFu)); +} +static void ldr_ctx(u32 rt, u32 i) { H2(0xF850u | 4u, (rt << 12) | 0xC00u | JOFF(i)); } /* ldr rt, [r4, #-off] */ +static void str_ctx(u32 rt, u32 i) { H2(0xF840u | 4u, (rt << 12) | 0xC00u | JOFF(i)); } +#define LDRB_R 0xF810u +#define STRB_R 0xF800u +#define LDRH_R 0xF830u +static void mem_r(u32 op, u32 rt, u32 rn, u32 rm, u32 sh) { H2(op | rn, (rt << 12) | (sh << 4) | rm); } +static void dp_r_w(u32 op, u32 s, u32 rd, u32 rn, u32 rm, u32 ty, u32 sh); +#define DP_AND 0xEA00u +#define DP_BIC 0xEA20u +#define DP_ORR 0xEA40u +#define DP_EOR 0xEA80u +#define DP_ADD 0xEB00u +#define DP_ADC 0xEB40u +#define DP_SUB 0xEBA0u +#define SH_LSL 0u +#define SH_LSR 1u +#define SH_ASR 2u +static void dp_r(u32 op, u32 s, u32 rd, u32 rn, u32 rm, u32 ty, u32 sh) +{ + /* 16-bit forms where the flags they set do not matter (no flag test follows them) */ + if (!s && !sh && rd < 8u && rn < 8u && rm < 8u) { + if (op == DP_ADD) { H1(0x1800u | (rm << 6) | (rn << 3) | rd); return; } + if (op == DP_SUB) { H1(0x1A00u | (rm << 6) | (rn << 3) | rd); return; } + if (rd == rn && (op == DP_AND || op == DP_EOR || op == DP_ORR || op == DP_BIC)) { H1(0x4000u | ((op == DP_AND ? 0u : op == DP_EOR ? 1u : op == DP_ORR ? 12u : 14u) << 6) | (rm << 3) | rd); return; } + } + dp_r_w(op, s, rd, rn, rm, ty, sh); +} +static void dp_r_w(u32 op, u32 s, u32 rd, u32 rn, u32 rm, u32 ty, u32 sh) { H2(op | (s << 4) | rn, ((sh >> 2) << 12) | (rd << 8) | ((sh & 3u) << 6) | (ty << 4) | rm); } +static void mov_r(u32 rd, u32 rm) { H1(0x4600u | ((rd & 8u) << 4) | (rm << 3) | (rd & 7u)); } +static void movs_sh(u32 rd, u32 rm, u32 ty, u32 sh) { dp_r(DP_ORR, 1, rd, 15, rm, ty, sh); } +static void mov_sh(u32 rd, u32 rm, u32 ty, u32 sh) { dp_r(DP_ORR, 0, rd, 15, rm, ty, sh); } +#define DI_AND 0xF000u +#define DI_ORR 0xF040u +#define DI_EOR 0xF080u +#define DI_ADD 0xF100u +#define DI_SUB 0xF1A0u +static void dp_i(u32 op, u32 s, u32 rd, u32 rn, u32 imm8) { H2(op | (s << 4) | rn, (rd << 8) | (imm8 & 255u)); } +static void tst_i(u32 rn, u32 imm8) { dp_i(DI_AND, 1, 15, rn, imm8); } +static void cmp_i(u32 rn, u32 imm8) { dp_i(DI_SUB, 1, 15, rn, imm8); } +static void movw(u32 rd, u32 v) { if (rd < 8u && v < 256u) { H1(0x2000u | (rd << 8) | v); return; } H2(0xF240u | (((v >> 11) & 1u) << 10) | ((v >> 12) & 15u), (((v >> 8) & 7u) << 12) | (rd << 8) | (v & 255u)); } +static void movt(u32 rd, u32 v) { H2(0xF2C0u | (((v >> 11) & 1u) << 10) | ((v >> 12) & 15u), (((v >> 8) & 7u) << 12) | (rd << 8) | (v & 255u)); } +static void ubfx(u32 rd, u32 rn, u32 lsb, u32 w) { H2(0xF3C0u | rn, ((lsb >> 2) << 12) | (rd << 8) | ((lsb & 3u) << 6) | (w - 1u)); } +/* usat rd, #12, rn: addresses beyond the 4 KB land on its last byte (not on the registers) */ +static void sat12(u32 rd, u32 rn) { H2(0xF380u | rn, (rd << 8) | 12u); } +static void uxtb(u32 rd, u32 rm) { if (rd < 8u && rm < 8u) { H1(0xB2C0u | (rm << 3) | rd); return; } H2(0xFA5Fu, 0xF080u | (rd << 8) | rm); } +static void sxtb(u32 rd, u32 rm) { H2(0xFA4Fu, 0xF080u | (rd << 8) | rm); } +static void mul(u32 rd, u32 rn, u32 rm) { H2(0xFB00u | rn, 0xF000u | (rd << 8) | rm); } +static void subw(u32 rd, u32 rn, u32 imm) { H2(0xF2A0u | rn | (((imm >> 11) & 1u) << 10), (((imm >> 8) & 7u) << 12) | (rd << 8) | (imm & 255u)); } +static void addw(u32 rd, u32 rn, u32 imm) { H2(0xF200u | rn | (((imm >> 11) & 1u) << 10), (((imm >> 8) & 7u) << 12) | (rd << 8) | (imm & 255u)); } +static void subs5(u32 n) { while (n > 255u) { H1(0x3D00u | 255u); n -= 255u; } if (n) H1(0x3D00u | n); } /* subs r5, #n */ +static void blx(u32 rm) { H1(0x4780u | (rm << 3)); } +static void bx(u32 rm) { H1(0x4700u | (rm << 3)); } +/* branches: to a halfword index in g_code */ +static void bcc_w(u32 cc, u32 to) /* b.w, +-1 MB */ +{ + s32 off = (s32)(to - (u32)(g_ep - g_code) - 2u) * 2; + u32 s = (off >> 20) & 1u, j2 = (off >> 19) & 1u, j1 = (off >> 18) & 1u; + H2(0xF000u | (s << 10) | (cc << 6) | ((off >> 12) & 0x3Fu), 0x8000u | (j1 << 13) | (j2 << 11) | ((off >> 1) & 0x7FFu)); +} +static void b_w(u32 to) +{ + s32 off = (s32)(to - (u32)(g_ep - g_code) - 2u) * 2; + u32 s = (off >> 24) & 1u, i1 = (off >> 23) & 1u, i2 = (off >> 22) & 1u, j1 = (~(i1 ^ s)) & 1u, j2 = (~(i2 ^ s)) & 1u; + H2(0xF000u | (s << 10) | ((off >> 12) & 0x3FFu), 0x9000u | (j1 << 13) | (j2 << 11) | ((off >> 1) & 0x7FFu)); +} +#define CC_EQ 0u +#define CC_NE 1u +#define CC_CS 2u +#define CC_CC 3u +#define CC_LE 13u +/* a forward conditional branch (16 bit) filled in later */ +static u16 *bcc_fwd(u32 cc) { u16 *p = g_ep; H1(0xD000u | (cc << 8)); return p; } +static void fix_fwd(u16 *p) { if (p >= g_cend) return; s32 off = (s32)((g_ep - p) - 2); *p |= (u16)(off & 255); } +static u16 *b_fwd(void) { u16 *p = g_ep; H1(0xE000u); return p; } +static void fix_b(u16 *p) { if (p >= g_cend) return; s32 off = (s32)((g_ep - p) - 2); *p |= (u16)(off & 0x7FFu); } +#define R_D 4u +#define R_LEFT 5u +#define R_FZ 6u +#define R_FC 7u +#define R_FN 8u +#define R_FV 9u +#define R_FH 10u +#define R_SR 11u + +/* ---------------- the stubs at the start of the cache ---------------- */ +static void stubs(void) +{ + g_ep = g_code + 2; /* offset 0 means "not translated" */ + /* enter: push {r3-r11, lr}; r4 = D; load r5..r11; r0 = pc */ + g_stub_enter = (u32)(g_ep - g_code); + H2(0xE92Du, 0x4FF8u); + movw(R_D, (u32)(uintptr_t)A_D & 0xFFFFu); movt(R_D, (u32)(uintptr_t)A_D >> 16); + subw(12, R_D, JOFF(J_LEFT)); H2(0xE890u | 12u, 0x0FE0u); /* ldm r12, {r5-r11} */ + ldr_ctx(0, J_PC); + /* dispatch: r0 = pc */ + g_stub_disp = (u32)(g_ep - g_code); + H1(0x2D00u); /* cmp r5, #0 */ + u16 *pe = bcc_fwd(CC_LE); + ldr_ctx(1, J_MAP); mem_r(LDRH_R, 2, 1, 0, 1); /* ldrh r2, [r1, r0, lsl #1] */ + H1(0x2A00u); u16 *px = bcc_fwd(CC_EQ); /* cmp r2, #0; beq translate */ + ldr_ctx(1, J_CODE1); dp_r(DP_ADD, 0, 1, 1, 2, SH_LSL, 1); bx(1); + fix_fwd(px); + ldr_ctx(12, J_XLATE); blx(12); /* r0 = pc again */ + b_w(g_stub_disp); + fix_fwd(pe); + /* exit: pc in r0 */ + g_stub_exit = (u32)(g_ep - g_code); + str_ctx(0, J_PC); + subw(12, R_D, JOFF(J_LEFT)); H2(0xE880u | 12u, 0x0FE0u); /* stm r12, {r5-r11} */ + H2(0xE8BDu, 0x8FF8u); /* pop {r3-r11, pc} */ +} +static void jit_flush(void) +{ + for (u32 i = 0; i < AVR_FLASH_WORDS; i++) g_map[i] = 0; + g_cend = g_code + JIT_CACHE / 2; + g_npend = 0; g_blk_pc = 0xFFFFFFFFu; + stubs(); + g_flushes++; +} + +/* ---------------- what each instruction reads and sets of the flags ---------------- */ +#define FC 1u +#define FZ 2u +#define FN 4u +#define FV 8u +#define FH 16u +#define FALL 31u +enum { K_HELP, K_ADD, K_ADC, K_SUB, K_SBC, K_CP, K_CPC, K_AND, K_OR, K_EOR, K_MOV, K_MOVW, K_LDI, K_SUBI, K_SBCI, K_CPI, + K_ANDI, K_ORI, K_COM, K_NEG, K_SWAP, K_INC, K_DEC, K_ASR, K_LSR, K_ROR, K_ADIW, K_SBIW, K_MUL, K_LDS, K_STS, K_LDD, + K_STD, K_LD, K_ST, K_LPM, K_PUSH, K_POP, K_BST, K_BLD, K_INSP, K_OUTSP, K_NOP, K_IN, K_OUT, K_BITIO, K_CLI, + /* block ends */ + K_RJMP, K_JMP, K_RCALL, K_CALL, K_RET, K_IJMP, K_ICALL, K_BR, K_SBRC, K_SBRS, K_CPSE, K_SKIPIO, K_RETI, K_END }; +typedef struct { u16 pc, w, w2, len; u8 k, a, b, c, use, def, live, cyc; } JIns; + +static u32 two_w(u32 w) { return (w & 0xFE0Fu) == 0x9000u || (w & 0xFE0Fu) == 0x9200u || (w & 0xFE0Cu) == 0x940Cu; } +/* classify; a, b, c operands (see each kind) */ +static void jdec(u32 pc, JIns *x) +{ + u32 w = A_FLASH[pc], w2 = pc + 1 < AVR_FLASH_WORDS ? A_FLASH[pc + 1] : 0; + u32 d5 = (w >> 4) & 31u, r5 = (w & 15u) | ((w >> 5) & 16u), d4 = 16u + ((w >> 4) & 15u), K8 = ((w >> 4) & 0xF0u) | (w & 15u); + x->pc = (u16)pc; x->w = (u16)w; x->w2 = (u16)w2; x->len = two_w(w) ? 2 : 1; x->k = K_HELP; x->a = x->b = x->c = 0; + x->use = FALL; x->def = FALL; x->cyc = 1; +#define S(k_, a_, b_, u_, d_, cy_) do { x->k = (k_); x->a = (u8)(a_); x->b = (u8)(b_); x->use = (u_); x->def = (d_); x->cyc = (cy_); } while (0) + switch (w >> 12) { + case 0x0: + if (w == 0) { S(K_NOP, 0, 0, 0, 0, 1); return; } + switch ((w >> 10) & 3u) { + case 0: + if ((w & 0xFF00u) == 0x0100u) { S(K_MOVW, ((w >> 4) & 15u) * 2u, (w & 15u) * 2u, 0, 0, 1); return; } + return; /* MULS, MULSU, FMUL...: in C */ + case 1: S(K_CPC, d5, r5, FC | FZ, FALL, 1); return; + case 2: S(K_SBC, d5, r5, FC | FZ, FALL, 1); return; + default: S(K_ADD, d5, r5, 0, FALL, 1); return; + } + case 0x1: + switch ((w >> 10) & 3u) { + case 0: S(K_CPSE, d5, r5, 0, 0, 1); return; + case 1: S(K_CP, d5, r5, 0, FALL, 1); return; + case 2: S(K_SUB, d5, r5, 0, FALL, 1); return; + default: S(K_ADC, d5, r5, FC, FALL, 1); return; + } + case 0x2: + switch ((w >> 10) & 3u) { + case 0: S(K_AND, d5, r5, 0, FZ | FN | FV, 1); return; + case 1: S(K_EOR, d5, r5, 0, FZ | FN | FV, 1); return; + case 2: S(K_OR, d5, r5, 0, FZ | FN | FV, 1); return; + default: S(K_MOV, d5, r5, 0, 0, 1); return; + } + case 0x3: S(K_CPI, d4, K8, 0, FALL, 1); return; + case 0x4: S(K_SBCI, d4, K8, FC | FZ, FALL, 1); return; + case 0x5: S(K_SUBI, d4, K8, 0, FALL, 1); return; + case 0x6: S(K_ORI, d4, K8, 0, FZ | FN | FV, 1); return; + case 0x7: S(K_ANDI, d4, K8, 0, FZ | FN | FV, 1); return; + case 0x8: case 0xA: { + u32 q = (w & 7u) | ((w >> 7) & 0x18u) | ((w >> 8) & 0x20u), st = (w >> 9) & 1u, y = (w >> 3) & 1u; + S(st ? K_STD : K_LDD, d5, q, st ? FC | FZ | FN | FV : 0, 0, 2); x->c = (u8)(y ? 28 : 30); /* a store may leave for C */ + return; + } + case 0x9: + switch ((w >> 9) & 7u) { + case 0: case 1: { + u32 st = (w >> 9) & 1u, m = w & 15u; + if (m == 0) { if (!st && w2 >= 0x100u) S(K_LDS, d5, 0, 0, 0, 2); else if (st && w2 >= 0x100u) S(K_STS, d5, 0, 0, 0, 2); else if (w2 < 0x20u) S(st ? K_STS : K_LDS, d5, 0, 0, 0, 2); return; } + if (!st && (m == 4 || m == 5 || m == 6 || m == 7)) { S(K_LPM, d5, (m & 1u), 0, 0, 3); return; } + if (m == 15) { S(st ? K_PUSH : K_POP, d5, 0, 0, 0, 2); return; } + /* LD / ST: c = pointer register, b: 0 plain, 1 post increment, 2 pre decrement */ + { u32 p = 0, mode = 0; + switch (m) { case 1: p = 30; mode = 1; break; case 2: p = 30; mode = 2; break; case 9: p = 28; mode = 1; break; case 10: p = 28; mode = 2; break; + case 12: p = 26; break; case 13: p = 26; mode = 1; break; case 14: p = 26; mode = 2; break; default: return; } + S(st ? K_ST : K_LD, d5, mode, st ? FC | FZ | FN | FV : 0, 0, 2); x->c = (u8)p; return; } + } + case 2: + switch (w & 15u) { + case 0: S(K_COM, d5, 0, 0, FC | FZ | FN | FV, 1); return; + case 1: S(K_NEG, d5, 0, 0, FALL, 1); return; + case 2: S(K_SWAP, d5, 0, 0, 0, 1); return; + case 3: S(K_INC, d5, 0, 0, FZ | FN | FV, 1); return; + case 5: S(K_ASR, d5, 0, 0, FC | FZ | FN | FV, 1); return; + case 6: S(K_LSR, d5, 0, 0, FC | FZ | FN | FV, 1); return; + case 7: S(K_ROR, d5, 0, FC, FC | FZ | FN | FV, 1); return; + case 10: S(K_DEC, d5, 0, 0, FZ | FN | FV, 1); return; + case 12: case 13: case 14: case 15: { + u32 k = ((((w >> 4) & 31u) << 1 | (w & 1u)) << 16 | w2) & 0x3FFFu; + x->k = (w & 2u) ? K_CALL : K_JMP; x->use = 0; x->def = 0; x->cyc = (w & 2u) ? 4 : 3; x->c = 0; x->w2 = (u16)k; return; + } + case 8: + if (w == 0x9508u) { x->k = K_RET; x->use = 0; x->def = 0; x->cyc = 4; return; } + if (w == 0x9518u) { x->k = K_RETI; x->use = 0; x->def = 0; x->cyc = 4; return; } + if (w == 0x95C8u || w == 0x95D8u) { S(K_LPM, 0, 0, 0, 0, 3); return; } /* LPM r0, Z */ + if (w == 0x94F8u) { S(K_CLI, 0, 0, 0, 0, 1); return; } + if ((w & 0xFF0Fu) == 0x9408u && !(w & 0x80u) && ((w >> 4) & 7u) < 6u) return; /* SEC ... : in C */ + return; + case 9: + if (w == 0x9409u || w == 0x9419u) { x->k = K_IJMP; x->use = 0; x->def = 0; x->cyc = 2; return; } + if (w == 0x9509u || w == 0x9519u) { x->k = K_ICALL; x->use = 0; x->def = 0; x->cyc = 3; return; } + return; + default: return; + } + case 3: S((w & 0x0100u) ? K_SBIW : K_ADIW, 24u + ((w >> 3) & 6u), ((w >> 2) & 0x30u) | (w & 15u), 0, FC | FZ | FN | FV, 2); return; + case 4: case 5: + if (w & 0x0100u) { x->k = K_SKIPIO; x->cyc = 1; x->use = 0; x->def = 0; } /* SBIC, SBIS: in C, then a skip */ + else { x->k = K_BITIO; x->cyc = 2; x->use = 0; x->def = 0; } /* SBI, CBI */ + return; + default: S(K_MUL, d5, r5, 0, FC | FZ, 2); return; + } + case 0xB: { + u32 a = 0x20u + ((w & 15u) | ((w >> 5) & 0x30u)); + if (a == SPL || a == SPH) { S((w & 0x0800u) ? K_OUTSP : K_INSP, d5, a, 0, 0, 1); return; } + if (a != SREG) { S((w & 0x0800u) ? K_OUT : K_IN, d5, a, 0, 0, 1); return; } /* I/O without the flags */ + return; /* SREG: in C */ + } + case 0xC: { s32 k = (s32)(w << 20) >> 20; x->k = K_RJMP; x->use = 0; x->def = 0; x->cyc = 2; x->w2 = (u16)((pc + 1 + (u32)k) & 0x3FFFu); return; } + case 0xD: { s32 k = (s32)(w << 20) >> 20; x->k = K_RCALL; x->use = 0; x->def = 0; x->cyc = 3; x->w2 = (u16)((pc + 1 + (u32)k) & 0x3FFFu); return; } + case 0xE: S(K_LDI, d4, K8, 0, 0, 1); return; + default: + if ((w & 0x0800u) == 0) { /* BRBS / BRBC: a = flag bit, b = 1 when "clear" */ + s32 k = (s32)(w << 22) >> 25; u32 b = w & 7u; + static const u8 U[8] = { FC, FZ, FN, FV, FN | FV, FH, 0, 0 }; + x->k = K_BR; x->a = (u8)b; x->b = (u8)((w >> 10) & 1u); x->use = U[b]; x->def = 0; x->cyc = 1; x->w2 = (u16)((pc + 1 + (u32)k) & 0x3FFFu); + return; + } + { u32 m = 1u << (w & 7u); + switch ((w >> 9) & 3u) { + case 0: S(K_BLD, d5, m, 0, 0, 1); return; + case 1: S(K_BST, d5, m, 0, 0, 1); return; + case 2: S(K_SBRC, d5, m, 0, 0, 1); return; + default: S(K_SBRS, d5, m, 0, 0, 1); return; + } + } + } +#undef S +} +static int ends_block(u32 k) { return k >= K_RJMP; } + +/* ---------------- C helpers called from translated code ---------------- */ +#define CTX_SR() ((JC[J_SR] & 0xC0u) | (JC[J_FC] & 1u) | (JC[J_FZ] ? 0u : 2u) | ((JC[J_FN] >> 5) & 4u) | ((JC[J_FV] >> 4) & 8u) | (((JC[J_FN] ^ JC[J_FV]) >> 3) & 16u) | ((JC[J_FH] << 1) & 32u)) +static void ctx_srset(u32 x) { JC[J_SR] = x & 0xC0u; JC[J_FC] = x & 1u; JC[J_FZ] = (x & 2u) ? 0u : 1u; JC[J_FN] = (x & 4u) << 5; JC[J_FV] = (x & 8u) << 4; JC[J_FH] = (x & 32u) >> 1; } +static u32 g_jlim; /* the event cycle of this run (A_CYC = g_jlim - left) */ +#define JCYC() (g_jlim - JC[J_LEFT]) +/* SREG written (I may come on): returns 1 when an interrupt is due now (leave for C, one instruction first) */ +static u32 sr_write(u32 v) +{ + u32 on = v & ~JC[J_SR] & I_FLAG; ctx_srset(v); + if (on && irq_now()) { g_hold = 1; return 1; } + return 0; +} +static u32 j_rd(u32 a) +{ + if (a >= 0x100u) return a < AVR_DATA ? A_D[a] : 0u; + if (a < 0x20u) return A_D[a]; + if (a == SREG) return CTX_SR(); + A_CYC = JCYC(); return io_rd(a); +} +static u32 j_wr(u32 a, u32 v) +{ + if (a >= 0x100u) { if (a < AVR_DATA) A_D[a] = (u8)v; JC[J_DIRTY] = 1; return 0; } + if (a < 0x20u) { A_D[a] = (u8)v; return 0; } + if (a == SREG) return sr_write(v); + A_CYC = JCYC(); return io_wr(a, v) ? 1u : 0u; +} +/* loads and stores of the pointer instructions that hit I/O (the fast path is in the code) */ +__attribute__((used)) static u32 jit_ld(u32 a) { return j_rd(a & 0xFFFFu); } +__attribute__((used)) static u32 jit_st(u32 a, u32 v) { return j_wr(a & 0xFFFFu, v & 255u); } +/* I/O without the flags (left is in the context for the time) */ +__attribute__((used)) static u32 jit_in(u32 a) { A_CYC = JCYC(); return io_rd(a); } +__attribute__((used)) static u32 jit_out(u32 a, u32 v) { A_CYC = JCYC(); return io_wr(a, v) ? 1u : 0u; } +/* the display's byte (the most frequent I/O by far): as io_wr(SPDR) */ +__attribute__((used)) static u32 jit_spdr(u32 v) +{ + JC[J_DIRTY] = 1; A_D[SPDR] = (u8)v; + if (!(A_D[SPCR] & 0x40u)) return 0; + if (A_D[PORTD] & 0x10u) lcd_data(v); else lcd_cmd(v); + A_D[SPSR] |= 0x80u; + return (A_D[SPCR] & 0x80u) != 0; +} +/* SBI, CBI, SBIC, SBIS (the word): bit 0 leave for C, bit 1 skip */ +__attribute__((used)) static u32 jit_bit(u32 w) +{ + u32 a = 0x20u + ((w >> 3) & 31u), m = 1u << (w & 7u), pin = a >= PINB && a <= PORTF && (a - PINB) % 3u == 0u, fl = a >= TIFR0 && a <= TIFR4; + A_CYC = JCYC(); + switch ((w >> 8) & 3u) { + case 0: return (!pin && !fl && io_wr(a, io_rd(a) & ~m)) ? 1u : 0u; + case 2: return io_wr(a, (pin || fl) ? m : io_rd(a) | m) ? 1u : 0u; + case 1: return (io_rd(a) & m) ? 0u : 2u; + default: return (io_rd(a) & m) ? 2u : 0u; + } +} +/* one rare instruction at pc, flags in the context. Returns bit 0: leave for C after it, bit 1: the condition (skip) */ +__attribute__((used)) static u32 jit_op(u32 pc) +{ + u32 w = A_FLASH[pc], w2 = A_FLASH[(pc + 1) & 0x3FFFu], r = 0; + u32 d5 = (w >> 4) & 31u, r5 = (w & 15u) | ((w >> 5) & 16u); + switch (w >> 12) { + case 0x0: { /* MULS, MULSU, FMUL, FMULS, FMULSU */ + u32 d = 16u + ((w >> 4) & 15u), rr = 16u + (w & 15u), res, f = 0; + if ((w & 0xFF00u) == 0x0200u) res = (u32)((s32)(int8_t)A_D[d] * (s32)(int8_t)A_D[rr]); + else { + d = 16u + ((w >> 4) & 7u); rr = 16u + (w & 7u); + switch (w & 0x88u) { + case 0x00: res = (u32)((s32)(int8_t)A_D[d] * (s32)A_D[rr]); break; + case 0x08: res = (u32)A_D[d] * A_D[rr]; f = 1; break; + case 0x80: res = (u32)((s32)(int8_t)A_D[d] * (s32)(int8_t)A_D[rr]); f = 1; break; + default: res = (u32)((s32)(int8_t)A_D[d] * (s32)A_D[rr]); f = 1; break; + } + } + res &= 0xFFFFu; JC[J_FC] = res >> 15; if (f) res = (res << 1) & 0xFFFFu; + JC[J_FZ] = res; A_D[0] = (u8)res; A_D[1] = (u8)(res >> 8); + return 0; + } + case 0x9: + if ((w & 0xFE0Fu) == 0x9000u) { A_D[d5] = (u8)j_rd(w2); return 0; } + if ((w & 0xFE0Fu) == 0x9200u) return j_wr(w2, A_D[d5]); + if ((w & 0xFF0Fu) == 0x9408u) { /* BSET / BCLR */ + u32 m = 1u << ((w >> 4) & 7u), v = CTX_SR(); + return sr_write((w & 0x80u) ? v & ~m : v | m); + } + if (w == 0x9588u) { if (A_D[SMCR] & 1u) { g_sleep = 1; return 1; } return 0; } + if (w == 0x95A8u) { if (WDT_ON) { A_CYC = JCYC(); wdt_restart(); } return 0; } + if ((w & 0xFC00u) == 0x9800u) { /* CBI, SBI, SBIC, SBIS */ + u32 a = 0x20u + ((w >> 3) & 31u), m = 1u << (w & 7u), pin = a >= PINB && a <= PORTF && (a - PINB) % 3u == 0u, fl = a >= TIFR0 && a <= TIFR4; + A_CYC = JCYC(); + switch ((w >> 8) & 3u) { + case 0: if (!pin && !fl) r = io_wr(a, io_rd(a) & ~m) ? 1u : 0u; return r; + case 2: r = io_wr(a, (pin || fl) ? m : io_rd(a) | m) ? 1u : 0u; return r; + case 1: return (io_rd(a) & m) ? 0u : 2u; + default: return (io_rd(a) & m) ? 2u : 0u; + } + } + if ((w & 0xFC00u) == 0x9400u && (w & 15u) == 1u) { /* NEG (rarely needs all flags) */ + u32 a = A_D[d5], res = (0u - a); A_D[d5] = (u8)res; + JC[J_FC] = (res >> 8) & 1u; JC[J_FZ] = res & 255u; JC[J_FN] = res; JC[J_FV] = a & res; JC[J_FH] = a ^ res; return 0; + } + return 0; + case 0xB: { + u32 a = 0x20u + ((w & 15u) | ((w >> 5) & 0x30u)); + if (w & 0x0800u) { + u32 v = A_D[d5]; + if (a == SREG) return sr_write(v); + A_CYC = JCYC(); return io_wr(a, v) ? 1u : 0u; + } + if (a == SREG) { /* IN rd, SREG: also the anchor of the busy waiting (see avr.c) */ + A_D[d5] = (u8)CTX_SR(); + if (AB_SPIN) { + u32 sp = A_D[SPL] | (u32)A_D[SPH] << 8; + if (pc == g_anc_pc && sp == g_anc_sp) { + if (!JC[J_DIRTY]) { + u32 cyc = JCYC(), to = g_jlim; if (g_tread && to - cyc > 512u) to = cyc + 512u; + if ((s32)(to - cyc) > 1) JC[J_LEFT] = g_jlim - to; + } + JC[J_DIRTY] = 0; g_tread = 0; + } else if (JC[J_DIRTY]) { g_anc_pc = pc; g_anc_sp = sp; JC[J_DIRTY] = 0; g_tread = 0; } + } + return 0; + } + A_CYC = JCYC(); A_D[d5] = io_rd(a); return 0; + } + case 0xF: + if ((w & 0xFE08u) == 0xFA00u) { JC[J_SR] = (JC[J_SR] & ~T_F) | ((A_D[d5] & (1u << (w & 7u))) ? T_F : 0u); return 0; } + return 0; + } + (void)r5; + return 0; +} + +/* ---------------- the translator ---------------- */ +static JIns g_jb[JB_MAX + 1]; +/* emit: load AVR register d into host register rt */ +static void ldr_avr(u32 rt, u32 d) { mem_i(LDRB_I, rt, R_D, d); } +static void str_avr(u32 rt, u32 d) { mem_i(STRB_I, rt, R_D, d); } +static u32 g_acc; /* cycles of the block not yet taken from r5 */ +static void flush_cyc(void) { subs5(g_acc); g_acc = 0; } +/* call a C helper with the flags handed over (r0 = arg) */ +static void sync_out(void) { subw(12, R_D, JOFF(J_LEFT)); H2(0xE880u | 12u, 0x0FE0u); } +static void sync_in(void) { subw(12, R_D, JOFF(J_LEFT)); H2(0xE890u | 12u, 0x0FE0u); } +static void call_ctx(u32 h) { ldr_ctx(12, h); blx(12); } +/* leave the block towards pc: straight to its code when it is there and cycles are left (AB_CHAIN), else through + * the dispatcher. A jump to a block not yet there is noted and set straight when that block is made. */ +#define CC_GT 12u +static void exit_to(u32 pc, u32 cyc) +{ + if (cyc) subs5(cyc); else H1(0x2D00u); /* the flags for the test */ + u32 at = pc == g_blk_pc ? g_blk_at : g_map[pc]; + if (at) { bcc_w(CC_GT, at); movw(0, pc); b_w(g_stub_disp); return; } + if (g_npend < PEND_N) { g_pend_at[g_npend] = (u16)(g_ep - g_code); g_pend_pc[g_npend++] = (u16)pc; } + movw(0, pc); b_w(g_stub_disp); H2(0xF3AFu, 0x8000u); /* nop.w: room for the patch */ +} +static void chain_fix(u32 pc, u32 at) +{ + u16 *keep = g_ep; + for (u32 i = 0; i < g_npend; ) { + if (g_pend_pc[i] != pc) { i++; continue; } + g_ep = g_code + g_pend_at[i]; bcc_w(CC_GT, at); movw(0, pc); b_w(g_stub_disp); + g_pend_at[i] = g_pend_at[g_npend - 1]; g_pend_pc[i] = g_pend_pc[--g_npend]; + } + g_ep = keep; +} +static void exit_c(u32 pc) { movw(0, pc); b_w(g_stub_exit); } +/* flags from a result in r2 (operands in r0, r1), only those wanted */ +static void fl_add(u32 want, int sticky) +{ + if (want & FC) ubfx(R_FC, 2, 8, 1); + if (want & FZ) { if (sticky) { uxtb(3, 2); dp_r(DP_ORR, 0, R_FZ, R_FZ, 3, 0, 0); } else uxtb(R_FZ, 2); } + if (want & FN) mov_r(R_FN, 2); + if (want & FH) { dp_r(DP_EOR, 0, R_FH, 0, 1, 0, 0); dp_r(DP_EOR, 0, R_FH, R_FH, 2, 0, 0); } +} +static void fl_v_add(void) { dp_r(DP_EOR, 0, 3, 0, 2, 0, 0); dp_r(DP_EOR, 0, 12, 1, 2, 0, 0); dp_r(DP_AND, 0, R_FV, 3, 12, 0, 0); } +static void fl_v_sub(void) { dp_r(DP_EOR, 0, 3, 0, 1, 0, 0); dp_r(DP_EOR, 0, 12, 0, 2, 0, 0); dp_r(DP_AND, 0, R_FV, 3, 12, 0, 0); } +/* address of a data access in r0 (16 bit): r2 = the byte (load), or store r2; slow path for 0x20..0xFF */ +static void data_ld(void) +{ + subw(1, 0, 0x20); cmp_i(1, 0xE0); u16 *slow = bcc_fwd(CC_CC); + sat12(1, 0); mem_r(LDRB_R, 2, R_D, 1, 0); u16 *done = b_fwd(); + fix_fwd(slow); + H1(0x9000u | (0u << 8) | 0); /* str r0, [sp] (keep the address) */ + sync_out(); call_ctx(J_LD); mov_r(2, 0); sync_in(); H1(0x9800u); /* ldr r0, [sp] */ + fix_b(done); +} +/* store r2 at the address in r0; status in r0 bit 0 (only on the slow path; fast path r0 = address >= 0x20) */ +static u16 *data_st(void) +{ + subw(1, 0, 0x20); cmp_i(1, 0xE0); u16 *slow = bcc_fwd(CC_CC); + sat12(1, 0); mem_r(STRB_R, 2, R_D, 1, 0); + /* dirty when below the stack pointer (data, not stack) */ + mem_i(LDRH_I, 3, R_D, SPL); dp_r(DP_SUB, 1, 15, 0, 3, 0, 0); u16 *nd = bcc_fwd(CC_CS); str_ctx(R_D, J_DIRTY); fix_fwd(nd); + u16 *done = b_fwd(); + fix_fwd(slow); + H1(0x9000u); sync_out(); mov_r(1, 2); call_ctx(J_ST); sync_in(); + tst_i(0, 1); u16 *brk = bcc_fwd(CC_NE); H1(0x9800u); + fix_b(done); + return brk; /* the caller lets it leave for C (after the instruction) */ +} +/* pointer register p (26, 28, 30) into r0, with pre decrement / post increment written back after */ +static void ptr_get(u32 p, u32 mode) { mem_i(LDRH_I, 0, R_D, p); if (mode == 2) { subw(0, 0, 1); H2(0xFA1Fu, 0xF080u | (0u << 8) | 0u); mem_i(STRH_I, 0, R_D, p); } } +static void ptr_post(u32 p, u32 mode) { if (mode == 1) { mem_i(LDRH_I, 3, R_D, p); addw(3, 3, 1); mem_i(STRH_I, 3, R_D, p); } } +/* push the return address (2 bytes) */ +static void push_pc(u32 ret) +{ + mem_i(LDRH_I, 0, R_D, SPL); movw(2, ret); + sat12(1, 0); mem_r(STRB_R, 2, R_D, 1, 0); + subw(1, 0, 1); sat12(1, 1); mov_sh(2, 2, SH_LSR, 8); mem_r(STRB_R, 2, R_D, 1, 0); + subw(0, 0, 2); mem_i(STRH_I, 0, R_D, SPL); +} +/* pop a return address into r0 */ +static void pop_pc(void) +{ + mem_i(LDRH_I, 0, R_D, SPL); + addw(1, 0, 1); sat12(1, 1); mem_r(LDRB_R, 2, R_D, 1, 0); + addw(1, 0, 2); sat12(1, 1); mem_r(LDRB_R, 3, R_D, 1, 0); + addw(0, 0, 2); mem_i(STRH_I, 0, R_D, SPL); + dp_r(DP_ORR, 0, 0, 3, 2, SH_LSL, 8); ubfx(0, 0, 0, 14); +} +/* one block from pc; returns the code's halfword offset (0: no room) */ +static u32 xlate(u32 pc) +{ + u32 n = 0; + while (n < JB_MAX) { + JIns *x = &g_jb[n]; jdec(pc, x); n++; + if (ends_block(x->k)) break; + pc = (pc + x->len) & 0x3FFFu; + if (pc == 0) break; + } + /* which flags are read later: at the end C, Z, N, V (H only inside a block) */ + u32 live = FC | FZ | FN | FV; + for (u32 i = n; i-- > 0; ) { g_jb[i].live = (u8)live; live = (live & ~g_jb[i].def) | g_jb[i].use; } + u16 *start = g_ep; g_acc = 0; g_blk_pc = g_jb[0].pc; g_blk_at = (u32)(start - g_code); + for (u32 i = 0; i < n; i++) { + JIns *x = &g_jb[i]; u32 want = x->def & x->live, next = (x->pc + x->len) & 0x3FFFu; + g_acc += x->cyc; + switch (x->k) { + case K_NOP: break; + case K_LDI: movw(0, x->b); str_avr(0, x->a); break; + case K_MOV: ldr_avr(0, x->b); str_avr(0, x->a); break; + case K_MOVW: mem_i(LDRH_I, 0, R_D, x->b); mem_i(STRH_I, 0, R_D, x->a); break; + case K_ADD: case K_ADC: + ldr_avr(0, x->a); ldr_avr(1, x->b); dp_r(DP_ADD, 0, 2, 0, 1, 0, 0); + if (x->k == K_ADC) dp_r(DP_ADD, 0, 2, 2, R_FC, 0, 0); + str_avr(2, x->a); if (want & FV) fl_v_add(); fl_add(want, 0); break; + case K_SUB: case K_SBC: case K_CP: case K_CPC: case K_SUBI: case K_SBCI: case K_CPI: { + int imm = x->k == K_SUBI || x->k == K_SBCI || x->k == K_CPI, carry = x->k == K_SBC || x->k == K_CPC || x->k == K_SBCI; + int store = x->k == K_SUB || x->k == K_SBC || x->k == K_SUBI || x->k == K_SBCI; + ldr_avr(0, x->a); if (imm) movw(1, x->b); else ldr_avr(1, x->b); + dp_r(DP_SUB, 0, 2, 0, 1, 0, 0); if (carry) dp_r(DP_SUB, 0, 2, 2, R_FC, 0, 0); + if (store) str_avr(2, x->a); + if (want & FV) fl_v_sub(); fl_add(want, carry); break; + } + case K_AND: case K_OR: case K_EOR: case K_ANDI: case K_ORI: + ldr_avr(0, x->a); + if (x->k == K_ANDI || x->k == K_ORI) dp_i(x->k == K_ANDI ? DI_AND : DI_ORR, 0, 2, 0, x->b); + else { ldr_avr(1, x->b); dp_r(x->k == K_AND ? DP_AND : x->k == K_OR ? DP_ORR : DP_EOR, 0, 2, 0, 1, 0, 0); } + str_avr(2, x->a); + if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2); if (want & FV) movw(R_FV, 0); break; + case K_COM: + ldr_avr(0, x->a); dp_i(DI_EOR, 0, 2, 0, 0xFF); str_avr(2, x->a); + if (want & FC) movw(R_FC, 1); if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2); if (want & FV) movw(R_FV, 0); break; + case K_NEG: + ldr_avr(1, x->a); movw(0, 0); dp_r(DP_SUB, 0, 2, 0, 1, 0, 0); str_avr(2, x->a); + if (want & FV) fl_v_sub(); fl_add(want, 0); break; + case K_SWAP: + ldr_avr(0, x->a); mov_sh(1, 0, SH_LSR, 4); dp_r(DP_ORR, 0, 2, 1, 0, SH_LSL, 4); str_avr(2, x->a); break; + case K_INC: case K_DEC: + ldr_avr(0, x->a); if (x->k == K_INC) addw(2, 0, 1); else subw(2, 0, 1); uxtb(2, 2); str_avr(2, x->a); + if (want & FV) { if (x->k == K_INC) dp_r(DP_BIC, 0, R_FV, 2, 0, 0, 0); else dp_r(DP_BIC, 0, R_FV, 0, 2, 0, 0); } + if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2); break; + case K_ASR: case K_LSR: case K_ROR: + ldr_avr(0, x->a); + if (x->k == K_LSR) mov_sh(2, 0, SH_LSR, 1); + else if (x->k == K_ASR) { dp_i(DI_AND, 0, 2, 0, 0x80); dp_r(DP_ORR, 0, 2, 2, 0, SH_LSR, 1); } + else { mov_sh(2, 0, SH_LSR, 1); dp_r(DP_ORR, 0, 2, 2, R_FC, SH_LSL, 7); } + str_avr(2, x->a); + dp_i(DI_AND, 0, R_FC, 0, 1); /* C always (ROR reads it next) */ + if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_r(R_FN, 2); + if (want & FV) dp_r(DP_EOR, 0, R_FV, 2, R_FC, SH_LSL, 7); + break; + case K_ADIW: case K_SBIW: + mem_i(LDRH_I, 0, R_D, x->a); + if (x->k == K_ADIW) addw(2, 0, x->b); else subw(2, 0, x->b); + H2(0xFA1Fu, 0xF080u | (2u << 8) | 2u); /* uxth r2, r2 */ + mem_i(STRH_I, 2, R_D, x->a); + if (want & FZ) mov_r(R_FZ, 2); if (want & FN) mov_sh(R_FN, 2, SH_LSR, 8); + if (want & FC) { if (x->k == K_ADIW) dp_r(DP_BIC, 0, 3, 0, 2, 0, 0); else dp_r(DP_BIC, 0, 3, 2, 0, 0, 0); ubfx(R_FC, 3, 15, 1); } + if (want & FV) { if (x->k == K_ADIW) dp_r(DP_BIC, 0, 3, 2, 0, 0, 0); else dp_r(DP_BIC, 0, 3, 0, 2, 0, 0); mov_sh(R_FV, 3, SH_LSR, 8); } + break; + case K_MUL: + ldr_avr(0, x->a); ldr_avr(1, x->b); mul(2, 0, 1); mem_i(STRH_I, 2, R_D, 0); + if (want & FC) ubfx(R_FC, 2, 15, 1); if (want & FZ) mov_r(R_FZ, 2); break; + case K_LDS: case K_STS: + if (x->w2 >= 0x100u || x->w2 < 0x20u) { + u32 ad = x->w2 & 0xFFFu; + if (x->k == K_LDS) { mem_i(LDRB_I, 0, R_D, ad); str_avr(0, x->a); } + else { ldr_avr(0, x->a); mem_i(STRB_I, 0, R_D, ad); if (x->w2 >= 0x100u) str_ctx(R_D, J_DIRTY); } + break; + } + goto help; + case K_LDD: case K_STD: + flush_cyc(); + mem_i(LDRH_I, 0, R_D, x->c); if (x->b) addw(0, 0, x->b); + if (x->k == K_LDD) { data_ld(); str_avr(2, x->a); } + else { ldr_avr(2, x->a); u16 *brk = data_st(); u16 *ok = b_fwd(); fix_fwd(brk); exit_c(next); fix_b(ok); } + break; + case K_LD: case K_ST: + flush_cyc(); + ptr_get(x->c, x->b); + if (x->k == K_LD) { data_ld(); str_avr(2, x->a); ptr_post(x->c, x->b); } + else { ldr_avr(2, x->a); u16 *brk = data_st(); ptr_post(x->c, x->b); u16 *ok = b_fwd(); fix_fwd(brk); ptr_post(x->c, x->b); exit_c(next); fix_b(ok); } + break; + case K_LPM: + mem_i(LDRH_I, 0, R_D, 30); ubfx(1, 0, 0, 15); ldr_ctx(3, J_FLASH); mem_r(LDRB_R, 2, 3, 1, 0); + str_avr(2, x->a); + if (x->b) { addw(0, 0, 1); mem_i(STRH_I, 0, R_D, 30); } + break; + case K_PUSH: + mem_i(LDRH_I, 0, R_D, SPL); sat12(1, 0); ldr_avr(2, x->a); mem_r(STRB_R, 2, R_D, 1, 0); + subw(0, 0, 1); mem_i(STRH_I, 0, R_D, SPL); break; + case K_POP: + mem_i(LDRH_I, 0, R_D, SPL); addw(0, 0, 1); mem_i(STRH_I, 0, R_D, SPL); sat12(1, 0); mem_r(LDRB_R, 2, R_D, 1, 0); str_avr(2, x->a); break; + case K_INSP: mem_i(LDRB_I, 0, R_D, x->b); str_avr(0, x->a); break; + case K_IN: + if (x->b == SPSR || (x->b >= PINB && x->b <= PINF && (x->b - PINB) % 3u == 0u)) { mem_i(LDRB_I, 0, R_D, x->b); str_avr(0, x->a); break; } /* kept current in D */ + flush_cyc(); str_ctx(R_LEFT, J_LEFT); movw(0, x->b); call_ctx(J_IN); str_avr(0, x->a); break; + case K_OUT: + if (x->b == SPDR) { ldr_avr(0, x->a); call_ctx(J_SPDR); tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); flush_cyc(); exit_c(next); fix_fwd(ok); } break; } + flush_cyc(); str_ctx(R_LEFT, J_LEFT); movw(0, x->b); ldr_avr(1, x->a); call_ctx(J_OUT); + tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); exit_c(next); fix_fwd(ok); } break; + case K_BITIO: flush_cyc(); str_ctx(R_LEFT, J_LEFT); movw(0, x->w); call_ctx(J_BIT); + tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); exit_c(next); fix_fwd(ok); } break; + case K_CLI: dp_i(DI_AND, 0, R_SR, R_SR, 0x7F); break; + case K_OUTSP: ldr_avr(0, x->a); mem_i(STRB_I, 0, R_D, x->b); break; + case K_BST: + ldr_avr(0, x->a); tst_i(0, x->b); dp_i(DI_AND, 0, R_SR, R_SR, 0xBF); + { u16 *z = bcc_fwd(CC_EQ); dp_i(DI_ORR, 0, R_SR, R_SR, 0x40); fix_fwd(z); } + break; + case K_BLD: + ldr_avr(0, x->a); dp_i(DI_AND, 0, 0, 0, (~x->b) & 0xFFu); tst_i(R_SR, 0x40); + { u16 *z = bcc_fwd(CC_EQ); dp_i(DI_ORR, 0, 0, 0, x->b); fix_fwd(z); } + str_avr(0, x->a); break; + /* ---- block ends ---- */ + case K_RJMP: case K_JMP: exit_to(x->w2, g_acc); g_acc = 0; break; + case K_RCALL: case K_CALL: push_pc(next); exit_to(x->w2, g_acc); g_acc = 0; break; + case K_RET: pop_pc(); subs5(g_acc); g_acc = 0; b_w(g_stub_disp); break; + case K_RETI: pop_pc(); subs5(g_acc); g_acc = 0; dp_i(DI_ORR, 0, R_SR, R_SR, 0x80); str_ctx(R_D, J_SPARE); b_w(g_stub_exit); break; /* C: one instruction, then the interrupts */ + case K_IJMP: case K_ICALL: + if (x->k == K_ICALL) push_pc(next); + mem_i(LDRH_I, 0, R_D, 30); ubfx(0, 0, 0, 14); subs5(g_acc); g_acc = 0; b_w(g_stub_disp); break; + case K_BR: { + u32 c = g_acc - x->cyc; /* not taken: 1 cycle, taken: 2 */ + u16 *tk; + switch (x->a) { + case 0: H1(0x2F00u); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; /* C: cmp r7, #0 */ + case 1: H1(0x2E00u); tk = bcc_fwd(x->b ? CC_NE : CC_EQ); break; /* Z: cmp r6, #0 */ + case 2: tst_i(R_FN, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; + case 3: tst_i(R_FV, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; + case 4: dp_r(DP_EOR, 0, 0, R_FN, R_FV, 0, 0); tst_i(0, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; + case 5: tst_i(R_FH, 0x10); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; + case 6: tst_i(R_SR, 0x40); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; + default: tst_i(R_SR, 0x80); tk = bcc_fwd(x->b ? CC_EQ : CC_NE); break; + } + exit_to(next, c + 1); + fix_fwd(tk); exit_to(x->w2, c + 2); g_acc = 0; break; + } + case K_SBRC: case K_SBRS: case K_CPSE: { + u32 c = g_acc - x->cyc, l2 = two_w(A_FLASH[next]) ? 2u : 1u; + u16 *sk; + if (x->k == K_CPSE) { ldr_avr(0, x->a); ldr_avr(1, x->b); dp_r(DP_SUB, 1, 15, 0, 1, 0, 0); sk = bcc_fwd(CC_EQ); } + else { ldr_avr(0, x->a); tst_i(0, x->b); sk = bcc_fwd(x->k == K_SBRC ? CC_EQ : CC_NE); } + exit_to(next, c + 1); + fix_fwd(sk); exit_to((next + l2) & 0x3FFFu, c + 1 + l2); g_acc = 0; break; + } + case K_SKIPIO: { + u32 c = g_acc - x->cyc, l2 = two_w(A_FLASH[next]) ? 2u : 1u; + subs5(c); g_acc = 0; + u32 ia = 0x20u + ((x->w >> 3) & 31u), sk_set = (x->w & 0x0200u) != 0; /* SBIS: skip when set */ + u16 *sk; + if (ia == SPSR || (ia >= PINB && ia <= PINF && (ia - PINB) % 3u == 0u)) { + mem_i(LDRB_I, 0, R_D, ia); tst_i(0, 1u << (x->w & 7u)); sk = bcc_fwd(sk_set ? CC_NE : CC_EQ); + } else { str_ctx(R_LEFT, J_LEFT); movw(0, x->w); call_ctx(J_BIT); tst_i(0, 2); sk = bcc_fwd(CC_NE); } + exit_to(next, 1); + fix_fwd(sk); exit_to((next + l2) & 0x3FFFu, 1 + l2); break; + } + default: + help: + flush_cyc(); + sync_out(); movw(0, x->pc); call_ctx(J_OP); sync_in(); + tst_i(0, 1); { u16 *ok = bcc_fwd(CC_EQ); exit_c(next); fix_fwd(ok); } + break; + } + if (g_ep >= g_cend - 64) return 0; + } + if (!ends_block(g_jb[n - 1].k)) { u32 nx = (g_jb[n - 1].pc + g_jb[n - 1].len) & 0x3FFFu; exit_to(nx, g_acc); g_acc = 0; } + if (g_ep >= g_cend - 8) return 0; + return (u32)(start - g_code); +} +/* called by the dispatcher: translate the block at pc (empty the cache when full), returns pc */ +__attribute__((used)) static u32 jit_xlate(u32 pc) +{ + pc &= 0x3FFFu; + u32 at = xlate(pc); + if (!at) { jit_flush(); at = xlate(pc); } + g_map[pc] = (u16)at; g_blk_pc = 0xFFFFFFFFu; + chain_fix(pc, at); +#ifdef __arm__ + __asm__ volatile("dsb\n isb" ::: "memory"); +#endif + return pc; +} + +static void jit_init(void) +{ + JC[J_XLATE] = (u32)(uintptr_t)jit_xlate; JC[J_OP] = (u32)(uintptr_t)jit_op; JC[J_LD] = (u32)(uintptr_t)jit_ld; JC[J_ST] = (u32)(uintptr_t)jit_st; + JC[J_IN] = (u32)(uintptr_t)jit_in; JC[J_OUT] = (u32)(uintptr_t)jit_out; JC[J_BIT] = (u32)(uintptr_t)jit_bit; JC[J_SPDR] = (u32)(uintptr_t)jit_spdr; + JC[J_MAP] = (u32)(uintptr_t)g_map; JC[J_CODE1] = (u32)(uintptr_t)g_code | 1u; JC[J_FLASH] = (u32)(uintptr_t)A_FLASH; + jit_flush(); +} +u8 *ab_scratch(void) { jit_flush(); return (u8 *)g_code + JIT_CACHE - AB_SCRATCH; } +void ab_load(const u16 *flash, u32 words) +{ + A_FLASH = flash; g_words = words; + jit_init(); +} + +#ifdef AB_JIT_HOST +u16 *jit_code(u32 *n) { *n = (u32)(g_ep - g_code); return g_code; } +u32 jit_x(u32 pc) { return jit_xlate(pc); } +u32 jit_at(u32 pc) { return g_map[pc]; } +#endif +AVR_FAST void ab_run(u32 cycles) +{ + u32 end = A_CYC + cycles, pc = g_pc, lim, v; + pins_upd(); /* the buttons */ +#ifdef AB_JIT_HOST + void (*enter)(void) = 0; (void)enter; return; +#else + void (*enter)(void) = (void (*)(void))((uintptr_t)(g_code + g_stub_enter) | 1u); +#endif + for (;;) { + g_rst = 0; ev_sync(); if (g_rst) pc = 0; + if (g_hold) g_hold = 0; /* after SEI, RETI: one more instruction first */ + else if ((A_D[SREG] & I_FLAG) && (v = irq_now())) { + irq_ack(v); + if (g_sleep) { g_sleep = 0; A_CYC += 4; } + { u32 s = A_D[SPL] | (u32)A_D[SPH] << 8; + A_D[s & 0xFFFu] = (u8)pc; s--; A_D[s & 0xFFFu] = (u8)(pc >> 8); s--; A_D[SPL] = (u8)s; A_D[SPH] = (u8)(s >> 8); } + A_D[SREG] &= ~I_FLAG; pc = v * 2u; A_CYC += 5; + } + if ((s32)(A_CYC - end) >= 0) break; + lim = ev_next(); lim = lim < end - A_CYC ? A_CYC + lim : end; + if (g_sleep) { A_CYC = lim; continue; } + g_jlim = lim; JC[J_LEFT] = lim - A_CYC; JC[J_PC] = pc; ctx_srset(A_D[SREG]); + enter(); + A_CYC = g_jlim - JC[J_LEFT]; A_D[SREG] = (u8)CTX_SR(); pc = JC[J_PC] & 0x3FFFu; + if (JC[J_SPARE]) { JC[J_SPARE] = 0; g_hold = 1; } + } + g_pc = pc; +} diff --git a/ab/test/devab.py b/ab/test/devab.py new file mode 100644 index 0000000..f743850 --- /dev/null +++ b/ab/test/devab.py @@ -0,0 +1,181 @@ +# ArduboyEmu (ab.bin) in Unicorn, as devt7.py: hardware calls caught, the screen into a picture. +# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms). +# python3 devv3.py [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir] +import sys, struct, subprocess, os +from unicorn import * +from unicorn.arm_const import * +elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3]) +RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each) +out = os.environ.get('OUT', '.') +syms = {} +for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 3: syms[p[2]] = int(p[0], 16) +fl = bytearray(open(img, 'rb').read()) +u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS) +u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4) +APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere) +u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000])) +u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000) +u.mem_map(0x10000000, 0x100000) +u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl)) +u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here) +u.mem_write(0x4000B014, struct.pack('= t: m = v + return m +def ret(uc, v=None): + if v is not None: uc.reg_write(UC_ARM_REG_R0, v) + uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1) +def h_begin(uc, *a): + x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3)) + rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc) +def h_row(uc, *a): + p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n)) + for v in d: + if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v + rect['x'] += 1 + if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1 + ret(uc) +def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc) +def h_btn(uc, *a): ret(uc, keys()) +def h_prog(uc, *a): + ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = bytes(uc.mem_read(src, 0x1000)); a = ad & 0xFFFFFF + uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc) +def h_erase(uc, *a): + a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF + uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc) +def h_back(uc, *a): state['back'] = 1; uc.emu_stop() +def h_nop(uc, *a): ret(uc) +H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn, + 'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop, + 'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop} +for n, f in H.items(): + a = syms[n] & ~1 + u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a) +import builtins +if hasattr(builtins, '__gbprof'): u.hook_add(UC_HOOK_BLOCK, builtins.__gbprof[0]) +if os.environ.get('CACHESIM'): # test38: the I-cache of the flash window (16 KB, 32-byte lines, WAYS ways, LRU): misses per frame + _ways = int(os.environ.get('WAYS', '4')); _sets = 16384 // 32 // _ways + _cs = [[] for _ in range(_sets)]; state['miss'] = 0; state['acc'] = 0 + def _cr(uc, acc, a, sz, v, ud): + state['acc'] += 1 + ln = (a - 0x10000000) >> 5; s = _cs[ln % _sets] + if ln in s: s.remove(ln); s.append(ln); return + state['miss'] += 1; s.append(ln) + if len(s) > _ways: s.pop(0) + u.hook_add(UC_HOOK_MEM_READ, _cr, begin=0x10000000, end=0x100FFFFF) +def bad(uc, access, addr, size, value, ud): + print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False +u.hook_add(UC_HOOK_MEM_UNMAPPED, bad) +# 1.6.9 test22 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms +state['sh'] = 0; state['shms'] = [0, 0, 0, 0] +def _ahb(uc, acc, a, sz, v, ud): + state['sh'] = v & 7 + if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms']) +u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013) +if os.environ.get('MEMW'): + _mw = int(os.environ['MEMW'], 16) + u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F) +def shot(name): + from PIL import Image + im = Image.new('RGB', (128, 128)) + for y in range(128): + for x in range(128): + v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3)) + im.save(os.path.join(out, name)) +if os.environ.get('PMB'): # test: the Paradise's time in the mailbox (seconds since 1970, local) + _t = int(os.environ['PMB']); _c = int(os.environ.get('RTC0', '5000')) + u.mem_write(0x20000FC0, struct.pack(' 1: LK['tx'].append(v & 0xFF) # the first is the baud divisor + u.hook_add(UC_HOOK_MEM_WRITE, _uw, begin=0x4000B000, end=0x4000B000) + LK['w'] = os.fdopen(os.open(os.environ['LINKW'], os.O_RDWR), 'wb', buffering=0); LK['r'] = os.fdopen(os.open(os.environ['LINKR'], os.O_RDWR), 'rb', buffering=0) # (O_RDWR: no wait for the other end) +def link_ms(): + d = bytes(LK['tx']); LK['tx'] = bytearray() + LK['w'].write(struct.pack('> state['sh'])); state['shms'][min(state['sh'], 3)] += 1 + except UcError as ex: + print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break + pc = u.reg_read(UC_ARM_REG_PC) + state['ms'] += 1 + if 'w' in LK: link_ms() + v = struct.unpack('= w[0]: + d = 1 if w[1] > 0 else -1; state_enc['ph'] = (state_enc['ph'] + d) % 4; w[0] += 0.004 if (state_enc['ph'] % 4) else 0.02 + if state_enc['ph'] == 0: w[1] -= d + u.mem_write(0x4001A000, struct.pack('= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1 + if 'miss' in state and state['ms'] % 1000 == 0: + _f = struct.unpack(' +#include +#include +#include +#include +#include "../src/core/avr.h" +extern u32 ab_pc(void); +static u16 fl[AVR_FLASH_WORDS]; +static unsigned rr(void) { return (unsigned)rand(); } +static u16 gen(void) +{ + unsigned d = rr() & 31, r = rr() & 31, K = rr() & 255, d4 = rr() & 15, b = rr() & 7; + switch (rr() % 40) { + case 0: return 0x0C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADD */ + case 1: return 0x1C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADC */ + case 2: return 0x1800 | (r & 16) << 5 | d << 4 | (r & 15); /* SUB */ + case 3: return 0x0800 | (r & 16) << 5 | d << 4 | (r & 15); /* SBC */ + case 4: return 0x2000 | (r & 16) << 5 | d << 4 | (r & 15); /* AND */ + case 5: return 0x2800 | (r & 16) << 5 | d << 4 | (r & 15); /* OR */ + case 6: return 0x2400 | (r & 16) << 5 | d << 4 | (r & 15); /* EOR */ + case 7: return 0x1400 | (r & 16) << 5 | d << 4 | (r & 15); /* CP */ + case 8: return 0x0400 | (r & 16) << 5 | d << 4 | (r & 15); /* CPC */ + case 9: return 0x2C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MOV */ + case 10: return 0x5000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SUBI */ + case 11: return 0x4000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SBCI */ + case 12: return 0x7000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ANDI */ + case 13: return 0x6000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ORI */ + case 14: return 0x3000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* CPI */ + case 15: return 0x9400 | d << 4 | 0; /* COM */ + case 16: return 0x9400 | d << 4 | 1; /* NEG */ + case 17: return 0x9400 | d << 4 | 2; /* SWAP */ + case 18: return 0x9400 | d << 4 | 3; /* INC */ + case 19: return 0x9400 | d << 4 | 5; /* ASR */ + case 20: return 0x9400 | d << 4 | 6; /* LSR */ + case 21: return 0x9400 | d << 4 | 7; /* ROR */ + case 22: return 0x9400 | d << 4 | 10; /* DEC */ + case 23: return 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MUL */ + case 24: return 0x0200 | d4 << 4 | (rr() & 15); /* MULS */ + case 25: return 0x0300 | (rr() & 0x88) | (rr() & 0x77); /* MULSU FMUL* */ + case 26: return 0x9600 | (rr() & 0xFF); /* ADIW */ + case 27: return 0x9700 | (rr() & 0xFF); /* SBIW */ + case 28: return 0x0100 | (rr() & 0xFF); /* MOVW */ + case 29: return 0xFA00 | d << 4 | b; /* BST */ + case 30: return 0xF800 | d << 4 | b; /* BLD */ + case 31: { static const int B[4] = { 0, 1, 5, 6 }; return 0x9408 | B[rr() & 3] << 4 | ((rr() & 1) << 7); } /* BSET/BCLR of C Z H T */ + case 32: return 0xE000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* LDI */ + case 34: case 35: return 0xF000 | (rr() & 0x400) | (1 << 3) | (rr() & 7); /* BRBS/BRBC .+1 */ + case 36: return 0xFC00 | (rr() & 0x200) | d << 4 | b; /* SBRC/SBRS */ + case 37: return 0x1000 | (r & 16) << 5 | d << 4 | (r & 15); /* CPSE */ + + default: return 0x0000; + } +} +int main(int argc, char **argv) +{ + int seeds = argc > 1 ? atoi(argv[1]) : 200, fails = 0; + for (int sd = 1; sd <= seeds; sd++) { + srand(sd); + int n = 200; + for (int i = 0; i < n; i++) { fl[i] = gen(); if (fl[i] == 0x9478 || fl[i] == 0x94F8) fl[i] = 0; { unsigned o = fl[i] & 0xfc0f; if ((o == 0x940c || o == 0x940d || o == 0x940e || o == 0x940f || o == 0x9000 || o == 0x9200) && (fl[i] & 0xFE0F) != 0x9000) fl[i] = 0; } if ((fl[i] & 0xFE0F) == 0x9000 && i + 1 < n) { fl[++i] = 0x0100 + (rr() & 0x7FF); } } + fl[n] = 0xCFFF; /* rjmp . */ + avr_t *a = avr_make_mcu_by_name("atmega32u4"); avr_init(a); + avr_loadcode(a, (uint8_t *)fl, (n + 1) * 2, 0); + ab_load(fl, n + 1); ab_reset(); + unsigned sreg0 = rr() & 0x6F; sreg0 |= (((sreg0 >> 2) ^ (sreg0 >> 3)) & 1) << 4; + for (int i = 0; i < 32; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; } + a->data[R_SREG] = sreg0; for (int i = 0; i < 8; i++) a->sreg[i] = (sreg0 >> i) & 1; A_D[0x5F] = sreg0; + for (int i = 0x100; i < 0xB00; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; } + a->pc = 0; + for (int st = 0; st < n; st++) { + u16 w = fl[a->pc / 2]; + if (a->pc / 2 >= n) break; + avr_run(a); + ab_run(1); + if (getenv("TR") && sd == atoi(getenv("TR"))) { unsigned s2 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s2 |= 1 << i; printf(" st %d op %04x sreg sim %02x ours %02x pc %x/%x cyc %llu/%u\n", st, w, s2, A_D[0x5F], a->pc/2, ab_pc(), (unsigned long long)a->cycle, A_CYC); } + unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i; + int bad = s1 != A_D[0x5F] || a->pc / 2 != ab_pc(); for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) bad = 1; + if (bad) { + printf("seed %d step %d at %x op %04x: sreg sim %02x ours %02x pc sim %x ours %x\n", sd, st, (unsigned)0, w, s1, A_D[0x5F], a->pc/2, ab_pc()); + for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) printf(" r%d sim %02x ours %02x\n", i, a->data[i], A_D[i]); + fails++; break; + } + } + avr_terminate(a); + if (fails > 10) break; + } + printf("fails %d\n", fails); + return 0; +} diff --git a/ab/test/hostab.c b/ab/test/hostab.c new file mode 100644 index 0000000..af49c63 --- /dev/null +++ b/ab/test/hostab.c @@ -0,0 +1,63 @@ +/* PC test of the ArduboyEmu core: hostab game.hex seconds [KEYS="t:mask,..."] [SHOTS="t,..."] [OUT=dir] + * Writes the display as PGM pictures (128 x 64) at the shot times, prints frames, sound and timing. */ +#include "../src/core/avr.h" +#include +#include +#include +#include +static u16 g_fl[AVR_FLASH_WORDS]; +extern u32 ab_pc(void); +static u32 g_hist[AVR_FLASH_WORDS]; +static int hexval(const char *s, int n) { int v = 0; for (int i = 0; i < n; i++) { int c = s[i]; v = v * 16 + (c <= '9' ? c - '0' : (c | 32) - 'a' + 10); } return v; } +static u32 load_hex(const char *fn) +{ + FILE *f = fopen(fn, "r"); if (!f) { perror(fn); exit(1); } + u8 *b = (u8 *)g_fl; memset(b, 0xFF, sizeof g_fl); + char l[600]; u32 hi = 0, top = 0; + while (fgets(l, sizeof l, f)) { + if (l[0] != ':') continue; + int n = hexval(l + 1, 2), ad = hexval(l + 3, 4), ty = hexval(l + 7, 2); + if (ty == 0) for (int i = 0; i < n; i++) { u32 a = hi + ad + i; if (a < sizeof g_fl) { b[a] = (u8)hexval(l + 9 + 2 * i, 2); if (a + 1 > top) top = a + 1; } } + else if (ty == 2) hi = hexval(l + 9, 4) << 4; + else if (ty == 4) hi = hexval(l + 9, 4) << 16; + } + fclose(f); + return (top + 1) / 2; +} +static void shot(const char *out, int k) +{ + char fn[512]; snprintf(fn, sizeof fn, "%s/shot%02d.pgm", out, k); + FILE *f = fopen(fn, "wb"); fprintf(f, "P5 128 64 255\n"); + for (int y = 0; y < 64; y++) for (int x = 0; x < 128; x++) { + int on = (A_GD[(y >> 3) * 128 + x] >> (y & 7)) & 1; + if (A_LCD.invert) on ^= 1; + if (!A_LCD.on) on = 0; + fputc(on ? 255 : 0, f); + } + fclose(f); +} +int main(int argc, char **argv) +{ + u32 words = load_hex(argv[1]); double secs = atof(argv[2]); + const char *ks = getenv("KEYS"), *ss = getenv("SHOTS"), *out = getenv("OUT"); if (!out) out = "."; + double kt[64]; u32 km[64]; int nk = 0; double st[64]; int ns = 0; + if (ks) { const char *p = ks; while (*p && nk < 64) { kt[nk] = atof(p); const char *c = strchr(p, ':'); km[nk++] = (u32)atoi(c + 1); p = strchr(c, ','); if (!p) break; p++; } } + if (ss) { const char *p = ss; while (*p && ns < 64) { st[ns++] = atof(p); p = strchr(p, ','); if (!p) break; p++; } } + ab_load(g_fl, words); ab_reset(); + for (u32 i = 0; i < AVR_EEP; i++) A_EEP[i] = 0xFF; + clock_t c0 = clock(); int si = 0; u32 tones = 0, lastf = 0; + u32 ms_n = (u32)(secs * 1000); + for (u32 ms = 0; ms < ms_n; ms++) { + double t = ms / 1000.0; A_KEYS = 0; for (int i = 0; i < nk; i++) if (t >= kt[i]) A_KEYS = km[i]; + if (getenv("CALLER")) { u32 c = strtoul(getenv("CALLER"), 0, 16); for (u32 e = A_CYC + 16000; (s32)(A_CYC - e) < 0; ) { if (ab_pc() == c) { u32 sp = A_D[0x5D] | A_D[0x5E] << 8; g_hist[((A_D[sp + 1] << 8) | A_D[sp + 2]) & 0x3FFF]++; } ab_run(1); } } else + if (getenv("PCS")) for (int q = 0; q < 16; q++) { ab_run(1000); g_hist[ab_pc() & 0x3FFF]++; } else ab_run(16000); + if (ms % 50 == 49) { u32 hz = ab_tone(800000); if (hz) tones++; } + while (si < ns && t >= st[si]) shot(out, si++); + if (ms % 1000 == 999) { printf("t=%u s frames %u (+%u)\n", (ms + 1) / 1000, A_FRAMES, A_FRAMES - lastf); lastf = A_FRAMES; } + } + while (si < ns) shot(out, si++); + if (getenv("PCS") || getenv("CALLER")) { for (int k = 0; k < 8; k++) { u32 b = 0, bi = 0; for (u32 i = 0; i < AVR_FLASH_WORDS; i++) if (g_hist[i] > b) { b = g_hist[i]; bi = i; } printf("pc %04x (byte %05x) %u\n", bi, bi * 2, b); g_hist[bi] = 0; } } + double el = (double)(clock() - c0) / CLOCKS_PER_SEC; + printf("frames %u, tone windows %u, host %.2f s for %.1f s\n", A_FRAMES, tones, el, secs); + return 0; +} diff --git a/ab/test/jitfuzz/bis.sh b/ab/test/jitfuzz/bis.sh new file mode 100644 index 0000000..7ab201f --- /dev/null +++ b/ab/test/jitfuzz/bis.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# smallest prefix of seed $1 that differs +lo=0; hi=200 +while [ $((hi-lo)) -gt 1 ]; do m=$(((lo+hi)/2)); if ./run.sh $1 $m | grep -q ok; then lo=$m; else hi=$m; fi; done +echo "seed $1 first diff at body $hi" +python3 -c " +import sys; sys.path.insert(0,'/tmp/jf'); import gen +p=gen.gen($1,$hi); n=len(gen.gen($1,0))-3 +for k,x in enumerate(p[n:n+$hi]): print(k, '%04x'%x) +" | tail -4 diff --git a/ab/test/jitfuzz/cmp.py b/ab/test/jitfuzz/cmp.py new file mode 100644 index 0000000..2f1111c --- /dev/null +++ b/ab/test/jitfuzz/cmp.py @@ -0,0 +1,9 @@ +import sys +for d in sys.argv[1:]: + r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split() + out=[] + for k,(a,b) in enumerate(zip(r,j)): + base = 0 if k==0 else 0x100 + for i in range(0,len(a),2): + if a[i:i+2]!=b[i:i+2]: out.append('%x:%s/%s'%(base+i//2, a[i:i+2], b[i:i+2])) + print(d, ' '.join(out[:8])) diff --git a/ab/test/jitfuzz/gen.py b/ab/test/jitfuzz/gen.py new file mode 100644 index 0000000..38f9502 --- /dev/null +++ b/ab/test/jitfuzz/gen.py @@ -0,0 +1,83 @@ +import random, sys, struct +def gen(seed, lim=10**9): + R = random.Random(seed); w = [] + # init registers r0..r31 via r16 + for r in list(range(0, 16)) + list(range(17, 32)): + v = R.randrange(256); w.append(0xE000 | (v & 0xF0) << 4 | (0 << 4) | (v & 15)) # ldi r16, v + w.append(0x2C00 | (r & 16) << 5 | (r & 15) << 4 | 0 | (16 & 16) << 5 | (16 & 15)) # mov r, r16 (placeholder fixed below) + # fix movs: mov rd, r16: 0010 11rd dddd rrrr with r=16 -> r bit4 at bit9 + out = [] + for i in range(0, len(w), 2): + out.append(w[i]); r = (list(range(0, 16)) + list(range(17, 32)))[i // 2] + out.append(0x2C00 | 0x200 | ((r & 16) << 4) | ((r & 15) << 4) | 0) + v = R.randrange(256); out.append(0xE000 | (v & 0xF0) << 4 | (v & 15)) + # SREG: random consistent (S = N^V), no I + s = R.randrange(128) & 0x6F; s |= (((s >> 2) ^ (s >> 3)) & 1) << 4 + out.append(0xE010 | (s & 0xF0) << 4 | (s & 15)) # ldi r17, s + out.append(0xBF1F) # out SREG, r17 + out.append(0xE0A0); out.append(0xE0B1) # X = 0x100 + out.append(0xE0C8); out.append(0xE0D1) # Y = 0x108 + out.append(0xE0E0 | 0); out.append(0xE0F1) # Z = 0x100 (r30=0? ldi r30,0) + body = [] + n = 120 + i = 0 + depth = 0 + while i < n: + d = R.randrange(32); r = R.randrange(32); K = R.randrange(256); d4 = R.randrange(16); b = R.randrange(8) + c = R.randrange(46) + def dr(op): return op | (r & 16) << 5 | d << 4 | (r & 15) + if c < 10: x = dr([0x0C00,0x1C00,0x1800,0x0800,0x2000,0x2800,0x2400,0x1400,0x0400,0x2C00][c]) + elif c < 15: x = [0x5000,0x4000,0x7000,0x6000,0x3000][c-10] | (K & 0xF0) << 4 | d4 << 4 | (K & 15) + elif c < 23: x = 0x9400 | d << 4 | [0,1,2,3,5,6,7,10][c-15] + elif c == 23: x = 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15) + elif c == 24: x = 0x0200 | d4 << 4 | R.randrange(16) + elif c == 25: x = 0x0300 | R.randrange(256) & 0xFF + elif c == 26: x = 0x9600 | R.randrange(256) & 0x3F | 0x00 # adiw r24 + elif c == 27: x = 0x9700 | R.randrange(256) & 0x3F + elif c == 28: x = 0x0100 | R.randrange(256) + elif c == 29: x = 0xFA00 | d << 4 | b + elif c == 30: x = 0xF800 | d << 4 | b + elif c == 31: x = 0x9408 | [0,1,5,6][R.randrange(4)] << 4 | R.randrange(2) << 7 + elif c in (32, 33): x = 0xF000 | R.randrange(2) << 10 | 1 << 3 | R.choice([0,1,2,3,4,6,7]) # branch .+1 (not on H) + elif c == 34: x = 0xFC00 | R.randrange(2) << 9 | d << 4 | b + elif c == 35: x = 0x1000 | (r & 16) << 5 | d << 4 | (r & 15) + elif c == 36: # ld/st through X, Y, Z (pointers kept in 0x100..0x13F) + if d >= 26: d = 16 + x = [0x900C,0x900D,0x9009,0x9001,0x920C,0x920D,0x9209,0x9201,0x8000,0x8200][R.randrange(10)] | d << 4 + elif c == 37: # ldd/std Y+q + if d >= 26: d = 17 + q = R.randrange(8); x = (0x8008 | (R.randrange(2) << 9) | d << 4 | q) + elif c == 38: + if not depth: continue + if d >= 26: d = 18 + x = 0x900F | d << 4; depth -= 1 # pop + elif c == 39: x = 0x920F | d << 4; depth += 1 # push + elif c == 40: x = 0x95C8 # lpm + elif c == 41: x = 0x9004 | d << 4 # lpm rd, Z + elif c == 42: # reset pointers into range + body += [0xE0A0 | R.randrange(16), 0xE0B1, 0xE0C0 | R.randrange(8), 0xE0D1, 0xE0E0 | R.randrange(16), 0xE0F1]; i += 6; continue + elif c == 43: x = 0x0000 # (in rd, SREG: H differs on purpose) + elif c == 44: x = 0x9000 | (d % 26) << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # lds + else: x = 0x9200 | d << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # sts + # keep the pointers sane: never write r26..r31 with ALU ops + if c < 36 and c not in (28,) and ((x >> 4) & 31) >= 26 and c not in (32, 33, 34, 35, 29, 31): x = 0 + if c == 28 and ((x >> 4) & 15) * 2 >= 26: x = 0 + if c in (26, 27): x = x & ~0x30 # adiw/sbiw r24 only + body.append(x); i += 1 + # avoid skips landing in the middle of a 2-word instruction: put a nop after each 2-word one + fixed = [] + for k, x in enumerate(body): + fixed.append(x) + if (x & 0xFE0F) in (0x9000, 0x9200) and k + 1 < len(body): pass + prog = out + fixed[:lim] + [0x0000, 0x0000, 0xCFFF] + return prog +def to_hex(prog, fn): + b = b''.join(struct.pack('> 8) + (a & 255) + sum(c) + f.write(':%02X%04X00%s%02X\n' % (len(c), a, c.hex().upper(), (-s) & 255)) + f.write(':00000001FF\n') + open(fn + '.bin', 'wb').write(b) +if __name__ == '__main__': + to_hex(gen(int(sys.argv[1]), int(sys.argv[3]) if len(sys.argv) > 3 else 10**9), sys.argv[2]) diff --git a/ab/test/jitfuzz/ref.c b/ab/test/jitfuzz/ref.c new file mode 100644 index 0000000..4707352 --- /dev/null +++ b/ab/test/jitfuzz/ref.c @@ -0,0 +1,13 @@ +#include "../../src/core/avr.h" +#include +#include +#include +static u16 fl[AVR_FLASH_WORDS]; +int main(int argc, char **argv) +{ + FILE *f = fopen(argv[1], "rb"); memset(fl, 0xFF, sizeof fl); size_t n = fread(fl, 1, sizeof fl, f); fclose(f); + ab_load(fl, (n + 1) / 2); ab_reset(); + for (int ms = 0; ms < 30; ms++) ab_run(16000); + for (int i = 0; i < 96; i++) printf("%02x", A_D[i]); printf("\n"); + for (int i = 0x100; i < 0x140; i++) printf("%02x", A_D[i]); printf("\n"); +} diff --git a/ab/test/jitfuzz/run.sh b/ab/test/jitfuzz/run.sh new file mode 100644 index 0000000..9344550 --- /dev/null +++ b/ab/test/jitfuzz/run.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# setup: cp * /tmp/jf; cd /tmp/jf; gcc -O1 -o ref ref.c /ab/src/core/avr.c; cp /ab/ab.bin /ab/src/app/ab.elf /tmp/jf (KEEPELF=1 build) +# run.sh seed: compare host interpreter and the device JIT (Unicorn) +s=$1; d=/tmp/jf/w$s${2:+_$2}; mkdir -p $d; cd /tmp/jf +python3 gen.py $s $d/p.hex $2 +./ref $d/p.hex.bin > $d/ref.txt +cd /home/claude/studio/ab/test +python3 mkimg.py /tmp/jf/ab.bin $d/p.hex $d/img.bin +OUT=$d DUMP="g_mem+256:96,g_mem+512:64" python3 devab.py /tmp/jf/ab.elf $d/img.bin 40 2>&1 | grep DUMP | awk '{print $3}' > $d/jit.txt +if python3 /tmp/jf/same.py $d; then echo "seed $s ok"; rm -rf $d; else echo "seed $s DIFF"; fi diff --git a/ab/test/jitfuzz/same.py b/ab/test/jitfuzz/same.py new file mode 100644 index 0000000..8f4b4e8 --- /dev/null +++ b/ab/test/jitfuzz/same.py @@ -0,0 +1,5 @@ +import sys +d=sys.argv[1]; r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split() +if len(r)!=2 or len(j)!=2: sys.exit(1) +a=bytearray.fromhex(r[0]); b=bytearray.fromhex(j[0]); a[0x5f]&=0xDF; b[0x5f]&=0xDF +sys.exit(0 if a==b and r[1]==j[1] else 1) diff --git a/ab/test/lock.c b/ab/test/lock.c new file mode 100644 index 0000000..2c24ed2 --- /dev/null +++ b/ab/test/lock.c @@ -0,0 +1,52 @@ +/* lockstep against simavr on a game: gcc -O1 -DAB_SINGLE -o lock lock.c ../src/core/avr.c -lsimavr -lelf && ./lock game.hex steps + * (interrupts and I/O reads differ between the two: the simulator is followed there) */ +/* lockstep: game hex in our core and simavr, instruction by instruction */ +#include +#include +#include +#include +#include +#include +#include "../src/core/avr.h" +extern u32 ab_pc(void); extern void ab_set_pc(u32); extern void ab_wake(void); +static u16 fl[AVR_FLASH_WORDS]; +int main(int argc, char **argv) +{ + uint32_t sz, base; uint8_t *code = read_ihex_file(argv[1], &sz, &base); + long steps = atol(argv[2]); + memset(fl, 0xFF, sizeof fl); memcpy(fl, code, sz); + avr_t *a = avr_make_mcu_by_name("atmega32u4"); a->frequency = 16000000; avr_init(a); + avr_loadcode(a, code, sz, base); + ab_load(fl, (sz + 1) / 2); ab_reset(); + long syncs = 0, irqs = 0; unsigned lastpc = 0; + static char hist[64][160]; int hn = 0; + for (long st = 0; st < steps; st++) { + unsigned pc0 = a->pc / 2; + u16 w = fl[pc0]; + unsigned spa = a->data[0x5D] | a->data[0x5E] << 8, spb = A_D[0x5D] | A_D[0x5E] << 8, ourpc = ab_pc(); + avr_run(a); + ab_run(1); + snprintf(hist[hn++ & 63], 160, "st %ld pc %04x/%04x op %04x sp %04x/%04x r24 %02x/%02x -> %04x/%04x sreg %02x", st, pc0, ourpc, w, spa, spb, a->data[24], A_D[24], a->pc/2, ab_pc(), A_D[0x5F]); + unsigned p1 = a->pc / 2, p2 = ab_pc(); + int isld = (w & 0xF800) == 0xB000 || (w & 0xFE0F) == 0x9000 || (w & 0xFC00) == 0x9000 || (w & 0xD200) == 0x8000; + if (p1 != p2) { + int skio = (w & 0xFD00) == 0x9900; if (p1 < 0x56 || p2 < 0x56 || skio || p1 == pc0 || p2 == pc0) { /* one took an interrupt: follow the simulator */ + for (int i = 0; i < 32; i++) A_D[i] = a->data[i]; + for (int i = 0x100; i < 0xB00; i++) A_D[i] = a->data[i]; + A_D[0x5D] = a->data[0x5D]; A_D[0x5E] = a->data[0x5E]; + { unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i; A_D[0x5F] = s1; } + ab_wake(); ab_set_pc(p1); A_CYC = (u32)a->cycle; irqs++; continue; + } + for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); + printf("step %ld: pc sim %04x ours %04x (from %04x op %04x) cyc sim %llu ours %u\n", st, p1, p2, pc0, w, (unsigned long long)a->cycle, A_CYC); break; } + for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) { + if (isld) { A_D[i] = a->data[i]; syncs++; } + else { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("step %ld pc %04x op %04x: r%d sim %02x ours %02x\n", st, pc0, w, i, a->data[i], A_D[i]); st = steps; break; } + } + if (0 && a->cycle != A_CYC) { printf("cycles step %ld pc %04x op %04x sim %llu ours %u\n", st, pc0, w, (unsigned long long)a->cycle, A_CYC); break; } + if (0) { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("SP differs at step %ld\n", st); break; } + lastpc = pc0; + } + printf("irqs %ld syncs %ld cyc sim %llu ours %u\n", irqs, syncs, (unsigned long long)a->cycle, A_CYC); + return 0; +} diff --git a/ab/test/mkimg.py b/ab/test/mkimg.py new file mode 100644 index 0000000..6a92b42 --- /dev/null +++ b/ab/test/mkimg.py @@ -0,0 +1,25 @@ +# test image: ab.bin at 0xA0000 with its settings block, the game at 0x200000, the saves at 0x300000 (16 KB) +# python3 mkimg.py ab.bin game.hex out.bin [flags] +import sys, struct +app, hexf, out = sys.argv[1], sys.argv[2], sys.argv[3] +def hex2bin(fn): + b = bytearray(b'\xff' * 0x8000); top = 0; hi = 0 + for l in open(fn): + l = l.strip() + if not l.startswith(':'): continue + n, ad, ty = int(l[1:3], 16), int(l[3:7], 16), int(l[7:9], 16) + if ty == 0: + for i in range(n): + a = hi + ad + i + if a < len(b): b[a] = int(l[9 + 2 * i:11 + 2 * i], 16); top = max(top, a + 1) + elif ty == 2: hi = int(l[9:13], 16) << 4 + elif ty == 4: hi = int(l[9:13], 16) << 16 + return bytes(b[:top + (top & 1)]) +fl = bytearray(b'\xff' * 0x400000) +a = open(app, 'rb').read(); r = hex2bin(hexf) +fl[0xA0000:0xA0000 + len(a)] = a; fl[0x200000:0x200000 + len(r)] = r +flags = int(sys.argv[4]) if len(sys.argv) > 4 else 0 +c = 0xA0000 + 0x140 +struct.pack_into('<6I16s', fl, c, 0x50584241, 1, 0x200000, len(r), 0x300000, flags, b'ARDUBOY') +struct.pack_into('<12B', fl, c + 40, 4, 32, 8, 16, 1, 2, 0, 0, 0, 0, 0, 0) +open(out, 'wb').write(fl) diff --git a/ab/test/prof.py b/ab/test/prof.py new file mode 100644 index 0000000..92a2f19 --- /dev/null +++ b/ab/test/prof.py @@ -0,0 +1,19 @@ +# count instructions per function (PROF=1 in devgb): exec devgb with a block hook +import os, sys, subprocess, bisect, collections +elf = sys.argv[1] +fs = [] +for l in subprocess.run(['llvm-nm', '-S', '--size-sort', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 4 and p[2] in 'tT': fs.append((int(p[0], 16) & ~1, int(p[1], 16), p[3])) +fs.sort(); starts = [f[0] for f in fs] +cnt = collections.Counter() +def blk(uc, addr, size, ud): + i = bisect.bisect_right(starts, addr) - 1 + if i >= 0 and addr < fs[i][0] + fs[i][1]: cnt[fs[i][2]] += size // 2 + else: cnt['?'] += size // 2 +import builtins +builtins.__gbprof = (blk, cnt) + +exec(open(os.path.join(os.path.dirname(__file__), 'devab.py')).read()) +tot = sum(cnt.values()) +for n, c in cnt.most_common(25): print('%6.2f%% %s' % (100 * c / tot, n)) diff --git a/ab/test/profj.py b/ab/test/profj.py new file mode 100644 index 0000000..faa7fba --- /dev/null +++ b/ab/test/profj.py @@ -0,0 +1,15 @@ +# where the time goes in the translated code: dispatcher stub vs blocks (python3 profj.py elf img ms) +import os, sys, subprocess, collections, builtins +elf = sys.argv[1] +syms0 = {} +for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 3: syms0[p[2]] = int(p[0], 16) +cb = syms0['g_code']; cnt = collections.Counter(); tot = [0] +def blk(uc, addr, size, ud): + n = size // 2; tot[0] += n + if cb <= addr < cb + 0x10000: cnt['stub' if addr - cb < 0x50 else 'block'] += n + else: cnt['C'] += n +builtins.__gbprof = (blk, cnt) +exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read()) +for k, v in cnt.most_common(): print('%6.2f%% %s' % (100 * v / tot[0], k)) diff --git a/ab/test/profl.py b/ab/test/profl.py new file mode 100644 index 0000000..9536a98 --- /dev/null +++ b/ab/test/profl.py @@ -0,0 +1,23 @@ +# instructions per source line (needs an ELF with -g): python3 profl.py elf img ms +import os, sys, subprocess, collections +elf = sys.argv[1] +cnt = collections.Counter() +def blk(uc, addr, size, ud): cnt[addr] += size // 2 +import builtins +builtins.__gbprof = (blk, cnt) +exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read()) +# expand blocks to instruction addresses roughly: attribute the block to its first address +addrs = sorted(cnt) +out = subprocess.run(['llvm-addr2line', '-e', elf, '-f'] + [hex(a) for a in addrs], capture_output=True, text=True).stdout.splitlines() +# llvm-addr2line with -i prints inline chains; take the first file:line per address +res = collections.Counter(); i = 0; k = 0 +lines = out +mp = {} +cur = 0 +j = 0 +for a in addrs: + fn = lines[j]; loc = lines[j + 1]; j += 2 + while j < len(lines) and not lines[j].startswith('0x') and j + 1 < len(lines) and ':' in lines[j + 1] and not lines[j].startswith('/') and lines[j] != '??' and False: j += 2 + res[(fn, loc.split('/')[-1])] += cnt[a] +tot = sum(res.values()) +for (fn, loc), c in res.most_common(40): print('%6.2f%% %s %s' % (100 * c / tot, fn, loc)) diff --git a/about.html b/about.html new file mode 100644 index 0000000..1a53b47 --- /dev/null +++ b/about.html @@ -0,0 +1,9 @@ +다마고치 펌웨어 편집·한국어 메뉴 · 다마고치 연구소 +

ITOSM · TAMAGOTCHI PARADISE

다마고치 연구소

다마고치 파라다이스 펌웨어 편집과 한국어 A+C 메뉴, 원본 백업·복원을 한곳에서.

한국어 편집 도구 열기 +

내 다마고치를 한국어 도구로 편집하세요

Paramix Studio를 바탕으로 만든 공개 웹 도구입니다. 내 본체에서 추출한 ROM으로 캐릭터·아이템·지역 구성과 추가 프로그램을 편집하고 A+C로 여는 본체 메뉴를 한국어로 바꿀 수 있습니다.

한국어판 ROM에 들어 있는 다마고치 이름과 아이템 이름을 사용합니다. 이름을 한글로 수정하면 본편의 한국어 이름 표와 A+C 메뉴에 반영합니다. 본체가 지원하는 완성형 한글 2350자를 입력할 수 있습니다.

+

한국어 편집

캐릭터·아이템·지역을 편집하고 새 ROM 파일을 저장합니다. PC에서 선택한 파일의 편집은 브라우저 안에서 처리합니다.

기종별 자동 백업

ROM을 본체에서 추출하면 서버에 없는 기종만 먼저 비공개 백업한 뒤 PC에 저장합니다. 기종당 1개만 보관하고 관리자가 선택한 파일만 공개합니다.

백업 그대로 복원

공개된 백업의 기종과 파일 상태를 확인하고 본체에 기록합니다. 복원하면 저장 데이터도 해당 백업 당시로 돌아갑니다.

+

회원 전용 · 여섯 지역 캐릭터 통합

트로피컬 또는 글레이셔 원본을 바탕으로 랜드·워터·스카이·포레스트·트로피컬·글레이셔를 한 기기에 구성할 수 있습니다. 지역 그림을 가져올 랜드·워터·스카이 중 하나의 원본도 필요합니다. ROM 파일은 이용자가 준비합니다. 제이드 포레스트 원본만으로는 여섯 지역 통합이 되지 않습니다.

로그인한 뒤 상단의 기기 메뉴에서 본체를 연결하세요. 같은 메뉴의 여섯 지역 확장에서 ROM 읽기와 백업을 마친 뒤 설정할 수 있습니다. 여섯 지역 확장은 회원 전용입니다. 기본 편집과 기존 제이드 포레스트 네 지역 확장은 비회원도 이용할 수 있습니다.

로그인하고 이용하기

회원 전용 덤프 보관함

회원가입은 선택 사항입니다. 비회원도 편집과 ROM 추출을 이용할 수 있습니다. 기종별 복원은 로그인 후 이용할 수 있습니다. 회원에게는 16 MiB 덤프를 최대 10개까지 보관할 수 있도록 총 160 MiB의 개인 공간을 제공합니다.

로그인 후 ROM을 추출하면 내 보관함에도 자동 저장합니다. PC 파일 업로드, 다운로드, 이름 변경, 삭제, 편집기에서 열기와 개인 백업 복원을 지원합니다. 같은 파일은 중복 저장하지 않습니다. 가득 차도 기존 파일을 자동 삭제하지 않습니다. 개인 보관함 파일은 공개 목록에 올라가지 않습니다.

회원가입·내 보관함 열기

시작하는 방법

  1. PC의 Chrome 또는 Edge에서 편집 도구를 엽니다.
  2. 본체를 연결해 ROM을 추출하거나 보관한 ROM 파일을 엽니다.
  3. 필요한 기능을 선택한 뒤 새 ROM을 저장합니다.
  4. 본체에 기록하기 전에 현재 ROM과 저장 데이터를 보관합니다.

랜드·워터·스카이·제이드 포레스트·트로피컬·글레이셔를 분류합니다. 다른 다마고치 제품군이나 알 수 없는 기종은 자동 보관 대상이 아닙니다.

자세한 사용 안내 →

+

백업 파일은 어떻게 보관하나요?

본체에서 읽은 16 MB 전체 ROM에는 저장 데이터가 포함됩니다. ROM 추출 버튼을 누르면 미확보 기종에 한해 서버 저장이 먼저 진행됩니다. 공개용 기종 수집은 기본 비공개입니다. 이미 보유한 기종은 다시 수집하지 않습니다. 로그인한 회원의 개인 보관함 저장은 이와 별도로 진행됩니다. 관리자 승인 후 공개되는 파일은 방문자가 다운로드할 수 있습니다.

일반 파일 열기·편집이나 세이브만 따로 추출하는 작업은 이 자동 수집에 포함되지 않습니다. 서버 오류가 발생하면 화면에 알리고 PC 다운로드를 계속 제공합니다.

+

다마고치 연구소를 알려 주세요

한국어 편집 도구와 회원별 개인 보관함을 다마고치 사용자에게 소개해 주세요. 아래 버튼으로 주소나 소개글을 복사할 수 있습니다.

원본 백업 참여를 기다립니다

여섯 지역 통합 확인에 필요한 파일은 트로피컬 또는 글레이셔 원본 1개와 랜드·워터·스카이 중 원본 1개입니다. 해당 기기의 수정 전 원본을 보유하고 있다면 홈페이지의 기기 → ROM 추출·백업 후 다운로드를 이용해 참여할 수 있습니다.

미확보 기종만 서버에 비공개 보관합니다. 전체 ROM에는 저장 데이터도 포함되므로 참여 전에 안내를 확인하세요. 개인 보관함에 따로 올린 파일은 이 참여로 취급하거나 공개하지 않습니다.

편집 도구에서 ROM 추출하기
+ + diff --git a/account.html b/account.html new file mode 100644 index 0000000..197358b --- /dev/null +++ b/account.html @@ -0,0 +1,11 @@ +회원가입·내 덤프 보관함 · 다마고치 연구소
+

MY TAMAGOTCHI · BACKUPS

내 덤프 보관함

회원마다 총 160 MiB의 공간에 파라다이스 덤프를 최대 10개까지 보관할 수 있습니다.

가입하지 않아도 기존 편집·추출 기능을 이용할 수 있습니다. 개인 보관함 파일은 다른 회원이나 공개 복원 목록에 노출되지 않습니다.

+ +

로그인

관리자도 기존 관리자 계정으로 개인 보관함을 이용할 수 있습니다.

+

회원가입

영문과 숫자 또는 밑줄로 4~24자를 입력하세요. 대소문자는 구분하지 않습니다.

+
비밀번호를 잊으셨나요?
+
개인 보관함은 회원 본인만 접근합니다. 본체 ROM 추출 시 진행되는 기존 기종별 수집은 별도로 유지됩니다. 미확보 기종만 관리자 승인 전까지 비공개 보관합니다.
+ + diff --git a/account.js b/account.js new file mode 100644 index 0000000..f83d72a --- /dev/null +++ b/account.js @@ -0,0 +1,79 @@ +'use strict'; +const $=id=>document.getElementById(id); +let working=false, current=null; +function message(text){$('message').textContent=text;} +async function api(path,body,binary=false){ + let response; + try { response=await fetch('/api/member/'+path,{cache:'no-store',signal:AbortSignal.timeout(90000),...(body===undefined?{}:{method:'POST',headers:{'Content-Type':binary?'application/octet-stream':'application/json'},body:binary?body:JSON.stringify(body)})}); } + catch(e){throw Error(e.name==='TimeoutError'?'서버 응답 시간이 초과됐습니다. 잠시 후 다시 시도하세요.':'서버에 연결하지 못했습니다. 인터넷 연결을 확인한 뒤 다시 시도하세요.');} + let result; + try { result=await response.json(); } catch(e){throw Error('서버 응답을 처리하지 못했습니다. 잠시 후 다시 시도하세요.');} + if(response.status===401){$('vault').hidden=true;$('authPanels').hidden=false;} + if(!response.ok){const error=Error(response.status>=500?'서버 오류가 발생했습니다. 잠시 후 다시 시도하세요.':result.error||'요청에 실패했습니다.');error.status=response.status;throw error;}return result; +} +async function action(fn,onError=e=>message(e.message)){if(working)return;working=true;document.querySelectorAll('button').forEach(b=>b.disabled=true);try{await fn();}catch(e){onError(e);}finally{working=false;document.querySelectorAll('button').forEach(b=>b.disabled=false);}} +function save(data,name,type='text/plain;charset=utf-8'){ + const url=URL.createObjectURL(new Blob([data],{type})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),30000); +} +function recovery(result){if(result.recoveryCode){$('recoveryCode').textContent=result.recoveryCode;$('recoveryPanel').hidden=false;}} +async function refresh(){ + const result=await api('me');current=result; + document.querySelectorAll('[data-member-restore]').forEach(el=>{el.hidden=!result.authenticated;}); + document.querySelectorAll('[data-member-admin]').forEach(el=>{el.hidden=!(result.authenticated && result.isAdmin);}); + $('vault').hidden=!result.authenticated;$('authPanels').hidden=!!result.authenticated;if(!result.authenticated){$('files').replaceChildren();return;} + $('welcome').textContent=result.username+' 님의 보관함';$('usage').textContent=result.count+' / '+result.maxFiles+'개 · '+(result.usedBytes/1048576)+' / '+(result.quotaBytes/1048576)+' MiB 사용';$('capacity').max=result.maxFiles;$('capacity').value=result.count; + $('memberPassword').hidden=$('deleteAccount').hidden=result.isAdmin; + $('files').replaceChildren(); + if(!result.items.length){$('files').textContent='저장한 덤프가 없습니다. ROM을 추출하거나 PC 파일을 추가하세요.';return;} + for(const item of result.items){ + const row=document.createElement('div');row.className='record'; + const label=document.createElement('label');label.textContent='백업 이름';const input=document.createElement('input');input.value=item.label;input.maxLength=100;label.appendChild(input); + const info=document.createElement('p');info.className='hint';info.textContent=item.name+' · '+new Date(item.createdAt).toLocaleString('ko-KR')+' · 16MiB\nSHA-256: '+item.sha256; + const rename=document.createElement('button');rename.textContent='이름 저장';rename.onclick=()=>action(async()=>{await api('file',{id:item.id,label:input.value});await refresh();message('이름을 저장했습니다.');}); + const download=document.createElement('button');download.textContent='다운로드';download.onclick=()=>action(async()=>{ + const r=await fetch(item.fileUrl,{cache:'no-store'});if(!r.ok)throw Error('로그인 상태와 파일을 확인하세요.');const bytes=await r.arrayBuffer(); + const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),v=>v.toString(16).padStart(2,'0')).join('');if(bytes.byteLength!==item.size||hash!==item.sha256)throw Error('파일 검증에 실패했습니다.'); + save(bytes,item.label.replace(/[<>:"/\\|?*\x00-\x1f]/g,'_')+'.bin','application/octet-stream');message('파일 검증 후 다운로드했습니다.'); + }); + const edit=document.createElement('a');edit.className='button';edit.textContent='편집 도구에서 열기';edit.href='/?backup='+item.id; + const restore=document.createElement('a');restore.className='button';restore.textContent='본체 복원';restore.href='restore.html?backup='+item.id; + const remove=document.createElement('button');remove.className='danger';remove.textContent='삭제';remove.onclick=()=>action(async()=>{if(!confirm('이 백업을 개인 보관함에서 삭제할까요?'))return;await api('file',{id:item.id,action:'delete'});await refresh();message('파일을 삭제했습니다.');}); + row.append(label,info,rename,download,edit);if(item.edition)row.appendChild(restore);row.appendChild(remove);$('files').appendChild(row); + } +} +function form(id,fn){$(id).onsubmit=e=>{e.preventDefault();action(fn);};} +function loginFeedback(text,fields=[]){ + const box=$('loginError');box.textContent=text;box.hidden=!text; + for(const id of ['loginName','loginPassword'])$(id).setAttribute('aria-invalid',String(fields.includes(id))); + if(text){box.focus();box.scrollIntoView?.({block:'nearest'});} +} +$('loginForm').onsubmit=e=>{ + e.preventDefault();if(working)return; + loginFeedback('');message(''); + const username=$('loginName').value.trim(),password=$('loginPassword').value; + if(!username){loginFeedback('아이디를 입력하세요.',['loginName']);$('loginName').focus();return;} + if(!password){loginFeedback('비밀번호를 입력하세요.',['loginPassword']);$('loginPassword').focus();return;} + const button=$('loginSubmit');button.textContent='로그인 중…';$('loginForm').setAttribute('aria-busy','true'); + action(async()=>{ + await api('login',{username,password});await refresh(); + if(!current?.authenticated)throw Error('로그인 상태를 유지하지 못했습니다. 브라우저의 쿠키 허용 설정을 확인하세요.'); + $('loginForm').reset();message('로그인했습니다.'); + },error=>{ + loginFeedback('로그인 실패: '+(error.status===401?'아이디 또는 비밀번호가 올바르지 않거나 사용할 수 없는 계정입니다. 입력 내용을 확인하세요.':error.message),error.status===401?['loginName','loginPassword']:[]); + }).finally(()=>{button.textContent='로그인';$('loginForm').setAttribute('aria-busy','false');}); +}; +form('registerForm',async()=>{if($('registerPassword').value!==$('registerRepeat').value)throw Error('비밀번호가 서로 다릅니다.');const r=await api('register',{username:$('registerName').value,password:$('registerPassword').value});$('registerForm').reset();recovery(r);await refresh();message('가입했습니다. 아래 복구 코드를 별도로 보관하세요.');}); +form('recoverForm',async()=>{const r=await api('recover',{username:$('recoverName').value,recoveryCode:$('recoverCode').value,newPassword:$('recoverPassword').value});$('recoverForm').reset();recovery(r);await refresh();message('계정을 복구했습니다. 새 복구 코드를 보관하세요. 기존 코드는 만료됐습니다.');}); +form('passwordForm',async()=>{if($('newPassword').value!==$('newRepeat').value)throw Error('새 비밀번호가 서로 다릅니다.');await api('password',{currentPassword:$('currentPassword').value,newPassword:$('newPassword').value});$('passwordForm').reset();await refresh();message('새 비밀번호로 다시 로그인하세요.');}); +form('deleteForm',async()=>{if(!confirm('계정과 개인 보관함의 모든 덤프를 삭제합니다. 탈퇴할까요?'))return;await api('delete-account',{currentPassword:$('deletePassword').value});$('deleteForm').reset();$('recoveryCode').textContent='';$('recoveryPanel').hidden=true;await refresh();message('계정과 개인 파일을 삭제했습니다.');}); +$('logout').onclick=()=>action(async()=>{await api('logout',{});$('recoveryCode').textContent='';$('recoveryPanel').hidden=true;await refresh();message('로그아웃했습니다.');}); +$('uploadButton').onclick=()=>action(async()=>{ + const file=$('upload').files[0];if(!file)throw Error('덤프 파일을 선택하세요.');if(file.size!==16777216)throw Error('16MiB 덤프 파일만 보관할 수 있습니다.');message('개인 보관함에 저장하고 있습니다…'); + const bytes=await file.arrayBuffer(), hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),v=>v.toString(16).padStart(2,'0')).join(''); + const result=await api('files',bytes,true);if(result.sha256!==hash)throw Error('파일 확인값이 일치하지 않습니다.'); + if(result.status==='stored')await api('file',{id:result.id,label:file.name.replace(/\.bin$/i,'').slice(0,100)||'내 덤프'}); + $('upload').value='';await refresh();message(result.status==='duplicate'?'이미 보관한 동일 파일입니다. 중복 용량은 사용하지 않습니다.':'개인 보관함에 저장했습니다.'); +}); +$('saveRecovery').onclick=()=>save('아이디: '+current.username+'\n복구 코드: '+$('recoveryCode').textContent+'\nhttps://tama.itosm.co.kr/account.html\n','다마고치-계정복구코드.txt'); +$('dismissRecovery').onclick=()=>{$('recoveryCode').textContent='';$('recoveryPanel').hidden=true;}; +refresh().catch(e=>message(e.message)); diff --git a/admin.html b/admin.html new file mode 100644 index 0000000..4ff9d90 --- /dev/null +++ b/admin.html @@ -0,0 +1,24 @@ +관리자 · 다마고치 연구소 +

ITOSM · ADMIN

백업과 홈페이지 관리

+

관리자 로그인

+ +
백업 파일은 공개 웹 폴더와 소스 코드에서 분리해 보관합니다. 최초 제이드 포레스트 원본은 삭제할 수 없습니다.
diff --git a/admin.js b/admin.js new file mode 100644 index 0000000..a8ed46e --- /dev/null +++ b/admin.js @@ -0,0 +1,76 @@ +'use strict'; +const $ = id => document.getElementById(id); +const names = {1:'랜드',2:'워터',3:'스카이',4:'제이드 포레스트',5:'트로피컬',6:'글레이셔'}; +let working = false; +function message(text) { $('message').textContent = text; } +function loggedIn(value) { $('dashboard').hidden = !value; $('loginPanel').hidden = value; } +async function api(path, body) { + const r = await fetch('/api/' + path, {cache:'no-store', ...(body !== undefined ? {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)} : {})}); + const result = await r.json(); + if (r.status === 401) loggedIn(false); + if (!r.ok) throw new Error(result.error || '요청 실패'); + return result; +} +async function action(fn) { + if (working) return; + working = true; + document.querySelectorAll('button').forEach(b => b.disabled = true); + try { await fn(); } catch(e) { message(e.message); } + finally { working = false; document.querySelectorAll('button').forEach(b => b.disabled = false); } +} +async function refresh() { + const result = await api('admin/state'); + loggedIn(true); + $('account').textContent = result.username + ' 님'; + $('siteTitle').value = result.settings.title; + $('description').value = result.settings.description; + $('autoBackup').checked = result.settings.autoBackup; + $('maxStorageMB').value = result.settings.maxStorageMB; + $('backupMode').value=result.settings.backupMode||'server'; + $('deviceStorageMB').value=result.settings.deviceStorageMB||512; + $('deviceRetentionHours').value=result.settings.deviceRetentionHours||24; + document.querySelectorAll('[data-feature-setting]').forEach(el=>el.checked=result.settings.features?.[el.dataset.featureSetting]===true); + $('usage').textContent = '현재 사용: ' + result.usedMB + ' MB / ' + result.settings.maxStorageMB + ' MB'; + $('coverage').textContent = Object.entries(names).map(([id,name]) => name + ': ' + (result.items.some(x => x.edition === +id) ? '확보' : '미확보')).join(' · '); + $('records').replaceChildren(); + for (const item of result.items) { + const section = document.createElement('div'); section.className = 'record'; + const title = document.createElement('h3'); title.textContent = item.name + (item.protected ? ' · 최초 원본 보호' : ' · 원본 여부 미확인'); + const info = document.createElement('p'); info.className = 'hint'; info.textContent = '보관: ' + new Date(item.createdAt).toLocaleString('ko-KR') + '\n크기: 16 MB\nSHA-256: ' + item.sha256; + const label = document.createElement('label'); label.textContent = '복원 목록 표시 이름'; + const input = document.createElement('input'); input.value = item.label; input.maxLength = 100; label.appendChild(input); + const publicLabel = document.createElement('label'); publicLabel.className = 'check'; + const check = document.createElement('input'); check.type='checkbox'; check.checked=item.published; publicLabel.append(check, document.createTextNode('복원 목록에 공개하고 다운로드 허용')); + const save = document.createElement('button'); save.textContent='이 파일 설정 저장'; save.onclick=()=>action(async()=>{ + if (check.checked && !item.published && !confirm('이 파일과 포함된 저장 데이터를 방문자가 다운로드할 수 있게 공개할까요?')) return; + await api('admin/record',{sha256:item.sha256,label:input.value,published:check.checked}); await refresh(); message('파일 설정을 저장했습니다.'); + }); + const download=document.createElement('a'); download.className='button'; download.textContent='관리자 다운로드'; download.href='/api/admin/file/'+item.sha256; + section.append(title,info,label,publicLabel,save,download); + if (!item.protected) { const remove=document.createElement('button'); remove.className='danger'; remove.textContent='비공개 백업 삭제'; remove.onclick=()=>action(async()=>{ + if (!confirm('이 서버 백업을 삭제할까요? 해당 기종은 다음 추출 때 다시 확보합니다.')) return; + await api('admin/record',{sha256:item.sha256,action:'delete'}); await refresh(); message('백업을 삭제했습니다.'); + }); section.appendChild(remove); } + $('records').appendChild(section); + } + await refreshMembers(); +} +async function refreshMembers(){ + const data=await api('admin/members'); + $('signupEnabled').checked=!!data.settings.enabled;$('memberTotalMB').value=data.settings.total_mb; + $('memberUsage').textContent=data.items.length+'명 · 총 '+(data.items.reduce((sum,x)=>sum+x.usedBytes,0)/1048576)+' MiB 사용';$('memberList').replaceChildren(); + for(const member of data.items){ + const row=document.createElement('div');row.className='record';const title=document.createElement('h3');title.textContent=member.username; + const info=document.createElement('p');info.textContent=member.count+'개 · '+(member.usedBytes/1048576)+' MiB 사용'; + const label=document.createElement('label');label.textContent='최대 보관 개수';const slots=document.createElement('input');slots.type='number';slots.min=1;slots.max=100;slots.value=member.slots;label.appendChild(slots); + const state=document.createElement('label');state.className='check';const disabled=document.createElement('input');disabled.type='checkbox';disabled.checked=!!member.disabled;state.append(disabled,document.createTextNode('계정 이용 정지 (파일은 보존)')); + const save=document.createElement('button');save.textContent='회원 설정 저장';save.onclick=()=>action(async()=>{await api('admin/members',{id:member.id,slots:Number(slots.value),disabled:disabled.checked});await refreshMembers();message('회원 설정을 저장했습니다.');}); + row.append(title,info,label,state,save);$('memberList').appendChild(row); + } +} +$('memberSettingsForm').onsubmit=e=>{e.preventDefault();action(async()=>{await api('admin/members',{action:'settings',enabled:$('signupEnabled').checked,totalMB:Number($('memberTotalMB').value)});await refreshMembers();message('회원 보관함 설정을 저장했습니다.');});}; +$('loginForm').onsubmit=e=>{e.preventDefault();action(async()=>{await api('login',{username:$('username').value,password:$('password').value});$('password').value='';await refresh();message('로그인했습니다.');});}; +$('logout').onclick=()=>action(async()=>{await api('admin/logout',{});loggedIn(false);message('로그아웃했습니다.');}); +$('settingsForm').onsubmit=e=>{e.preventDefault();action(async()=>{await api('admin/settings',{title:$('siteTitle').value,description:$('description').value,autoBackup:$('autoBackup').checked,maxStorageMB:Number($('maxStorageMB').value),backupMode:$('backupMode').value,deviceStorageMB:Number($('deviceStorageMB').value),deviceRetentionHours:Number($('deviceRetentionHours').value),features:Object.fromEntries([...document.querySelectorAll('[data-feature-setting]')].map(el=>[el.dataset.featureSetting,el.checked]))});await refresh();message('홈페이지와 백업 설정을 저장했습니다.');});}; +$('passwordForm').onsubmit=e=>{e.preventDefault();action(async()=>{if($('newPassword').value!==$('repeatPassword').value)throw new Error('새 비밀번호가 서로 다릅니다.');await api('admin/password',{currentPassword:$('currentPassword').value,newPassword:$('newPassword').value});$('passwordForm').reset();loggedIn(false);message('변경한 비밀번호로 다시 로그인하세요.');});}; +refresh().catch(()=>loggedIn(false)); diff --git a/build.js b/build.js new file mode 100644 index 0000000..1ec5591 --- /dev/null +++ b/build.js @@ -0,0 +1,140 @@ +// Builds a single HTML file: dist/ParamixStudio.html (runs offline). +// Usage: node build.js +const fs = require('fs'); +const v = fs.readFileSync(__dirname + '/VERSION', 'utf8').trim(); +let html = fs.readFileSync(__dirname + '/src/index.html', 'utf8'); +const core = fs.readFileSync(__dirname + '/src/core.js', 'utf8') + '\n' + fs.readFileSync(__dirname + '/src/menu-font-ko.js', 'utf8'); +const app = fs.readFileSync(__dirname + '/src/app.js', 'utf8'); +// Emulator: embed the prebuilt program and stub template as Base64 (if present) +let emu = fs.readFileSync(__dirname + '/src/emu.js', 'utf8'); +const eb = __dirname + '/emu/emu.bin', es = __dirname + '/emu/stub_tpl.bin'; +if (!fs.existsSync(eb) || !fs.existsSync(es)) throw new Error('emu/emu.bin oder emu/stub_tpl.bin fehlt'); +{ + emu = emu.replace('__EMU_APP_B64__', fs.readFileSync(eb).toString('base64')).replace('__EMU_STUB_B64__', fs.readFileSync(es).toString('base64')); +} +// T7Emu: V7 program (source in t7/src). No ROM, no figures. +{ + const t7 = __dirname + '/t7/t7.bin'; + if (!fs.existsSync(t7)) throw new Error('t7/t7.bin fehlt'); + emu = emu.replace('__T7_APP_B64__', fs.readFileSync(t7).toString('base64')); + const t7x = __dirname + '/t7/t7x.bin'; // 1.6.12 test2: second part (JIT) + if (fs.existsSync(t7x)) emu = emu.replace('__T7X_APP_B64__', fs.readFileSync(t7x).toString('base64')); + // V1Emu: E0C6S46/48 program (source in v1/src, core TamaLIB). No ROM. + const v1 = __dirname + '/v1/v1.bin'; + if (!fs.existsSync(v1)) throw new Error('v1/v1.bin fehlt'); + emu = emu.replace('__V1_APP_B64__', fs.readFileSync(v1).toString('base64')); + // V3Emu (1.6.9): Connection V3 program (source in v3/src, core from BrickEmuPy). No ROM. + const v3 = __dirname + '/v3/v3.bin'; + if (!fs.existsSync(v3)) throw new Error('v3/v3.bin fehlt'); + emu = emu.replace('__V3_APP_B64__', fs.readFileSync(v3).toString('base64')); + // GBEmu (1.6.9 test36): Game Boy program (source in gb/src, core Peanut-GB). No ROM. + const gbb = __dirname + '/gb/gb.bin'; + if (!fs.existsSync(gbb)) throw new Error('gb/gb.bin fehlt'); + emu = emu.replace('__GB_APP_B64__', fs.readFileSync(gbb).toString('base64')); + // GBCEmu (1.7.2): Game Boy Color program (gb/src, build_gbc.sh, core Peanut-GB cgb branch). No ROM. + const gbcb = __dirname + '/gb/gbc.bin'; + if (!fs.existsSync(gbcb)) throw new Error('gb/gbc.bin fehlt'); + emu = emu.replace('__GBC_APP_B64__', fs.readFileSync(gbcb).toString('base64')); + // PokeMiniEmu (1.7.3): Pokemon mini program (source in pm/src). No game, no BIOS. + const abb = __dirname + '/ab/ab.bin'; + if (!fs.existsSync(abb)) throw new Error('ab/ab.bin fehlt'); + emu = emu.replace('__AB_APP_B64__', fs.readFileSync(abb).toString('base64')); + const pmb = __dirname + '/pm/pm.bin'; + if (!fs.existsSync(pmb)) throw new Error('pm/pm.bin fehlt'); + emu = emu.replace('__PM_APP_B64__', fs.readFileSync(pmb).toString('base64')); + // SMSEmu (1.6.10 test2): Master System program (source in sms/src). No ROM. + const smb = __dirname + '/sms/sms.bin'; + if (!fs.existsSync(smb)) throw new Error('sms/sms.bin fehlt'); + emu = emu.replace('__SMS_APP_B64__', fs.readFileSync(smb).toString('base64')); + // Wolf3D (1.6.10 test1): program (source in wolf/src, Wolf4SDL by id Software and others, GPL). No game data. + const wb = __dirname + '/wolf/wolf.bin'; + if (!fs.existsSync(wb)) throw new Error('wolf/wolf.bin fehlt'); + emu = emu.replace('__WOLF_APP_B64__', fs.readFileSync(wb).toString('base64')); + // Spear of Destiny (1.6.11 test2): the same program built for SOD. No game data. + const wsb = __dirname + '/wolf/wolfsod.bin'; + if (!fs.existsSync(wsb)) throw new Error('wolf/wolfsod.bin fehlt'); + emu = emu.replace('__WOLFSOD_APP_B64__', fs.readFileSync(wsb).toString('base64')); + // T18Emu: TG18 program (source in t18/src). No firmware. + const t18 = __dirname + '/t18/t18.bin'; + if (!fs.existsSync(t18)) throw new Error('t18/t18.bin fehlt'); + const t18x = __dirname + '/t18/t18x.bin'; + if (!fs.existsSync(t18x)) throw new Error('t18/t18x.bin fehlt'); + emu = emu.replace('__T18_APP_B64__', fs.readFileSync(t18).toString('base64')).replace('__T18_XIP_B64__', fs.readFileSync(t18x).toString('base64')); +} +// DOOM: program (two parts) and WAD converter (WebAssembly) as Base64 (if present). No WAD, no graphics. +let doom = fs.readFileSync(__dirname + '/src/doom.js', 'utf8'); +{ + const d = (f) => fs.readFileSync(__dirname + '/doom/' + f).toString('base64'); + for (const f of ['doom_app.bin', 'doom_xip.bin', 'mcuwad.wasm']) if (!fs.existsSync(__dirname + '/doom/' + f)) throw new Error('doom/' + f + ' fehlt'); + doom = doom.replace('__DOOM_APP_B64__', d('doom_app.bin')).replace('__DOOM_XIP_B64__', d('doom_xip.bin')).replace('__DOOM_WASM_B64__', d('mcuwad.wasm')); + if (fs.existsSync(__dirname + '/doom/doomf_app.bin')) doom = doom.replace('__DOOMF_APP_B64__', d('doomf_app.bin')).replace('__DOOMF_XIP_B64__', d('doomf_xip.bin')); // 1.7.2 DOOM_FREE +} +// Field switch: program and stub template +let feld = fs.readFileSync(__dirname + '/src/feld.js', 'utf8'); +{ + const d = (f) => fs.readFileSync(__dirname + '/feld/' + f).toString('base64'); + for (const f of ['feld.bin', 'stub_feld_tpl.bin']) if (!fs.existsSync(__dirname + '/feld/' + f)) throw new Error('feld/' + f + ' fehlt'); + feld = feld.replace('__FELD_B64__', d('feld.bin')).replace('__FELD_STUB_B64__', d('stub_feld_tpl.bin')); + // The Korean menu is optional; retain the upstream English binaries unchanged. + const ko = fs.readFileSync(__dirname + '/feld/feld-ko.bin'); + const koc = fs.readFileSync(__dirname + '/feld/feldc-ko.bin'); + if (ko.length > 0x8000 || koc.length > 0xE000) throw new Error('Korean menu exceeds upstream allocation'); + feld = feld.replace('__FELD_KO_B64__', ko.toString('base64')).replace('__FELDC_KO_B64__', koc.toString('base64')); + if (fs.existsSync(__dirname + '/feld/feldc.bin')) feld = feld.replace('__FELDC_B64__', d('feldc.bin')); // 1.7.2 CLEAN_ROM: menu for ROMs without the Paradise +} +// Six fields: helper page (source in six/src) +let six = fs.readFileSync(__dirname + '/src/six.js', 'utf8').replace(/\r\n/g, '\n'); +{ + const f = __dirname + '/six/six.bin'; + if (!fs.existsSync(f)) throw new Error('six/six.bin fehlt'); + six = six.replace('__SIX_B64__', fs.readFileSync(f).toString('base64')); +} +if (six.includes(' core).replace('__EMU__', () => emu).replace('__DOOM__', () => doom).replace('__FELD__', () => feld).replace('__SIX__', () => six).replace('__FLASH__', () => flash).replace('__SAVES__', () => saves).replace('__VISIT__', () => visit).replace('__WOLF__', () => wolf).replace('__APP__', () => app).split('__VERSION__').join('v' + v); +fs.mkdirSync(__dirname + '/dist', { recursive: true }); +fs.mkdirSync(__dirname + '/server/generated', {recursive:true}); +fs.writeFileSync(__dirname + '/server/generated/six.js', memberSix); +const archive = fs.readFileSync(__dirname + '/src/archive-client.js', 'utf8'); +const restore = fs.readFileSync(__dirname + '/src/restore.js', 'utf8'); +for (const [name, code] of [['archive-client', archive], ['restore', restore]]) new (require('vm').Script)(code, {filename: name}); +html = html.replace('__ARCHIVE__', () => archive); +fs.writeFileSync(__dirname + '/dist/ParamixStudio.html', html); +fs.writeFileSync(__dirname + '/dist/index.html', html); +const recoveryHtml = fs.readFileSync(__dirname + '/src/restore.html', 'utf8').replace('__FLASH__', () => flash).replace('__ARCHIVE__', () => archive).replace('__RESTORE__', () => restore); +fs.writeFileSync(__dirname + '/dist/restore.html', recoveryHtml); +console.log('dist/ParamixStudio.html', html.length, 'Byte, Version', v); diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..631a32b --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,54 @@ +services: + web: + image: nginx:stable-alpine + container_name: tamagotchi-studio + restart: unless-stopped + ports: + - "127.0.0.1:18130:80" + volumes: + - /home/syskiller/docker/tamagotchi/site:/usr/share/nginx/html:ro + - /home/syskiller/docker/tamagotchi/nginx-static.conf:/etc/nginx/conf.d/default.conf:ro + read_only: true + tmpfs: + - /var/cache/nginx + - /var/run + healthcheck: + test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1/health.txt || exit 1"] + interval: 30s + timeout: 5s + retries: 3 + logging: + driver: json-file + options: + max-size: "5m" + max-file: "3" + backup: + image: python:3.13-alpine + container_name: tamagotchi-backup + restart: unless-stopped + stop_grace_period: 10s + user: "1000:1000" + working_dir: /app + command: ["python", "-B", "app.py"] + environment: + PUBLIC_ORIGIN: https://tama.itosm.co.kr + volumes: + - /home/syskiller/docker/tamagotchi/source/server:/app:ro + - /home/syskiller/docker/tamagotchi/backups:/data + read_only: true + tmpfs: + - /tmp + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + mem_limit: 256m + pids_limit: 64 + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=3)"] + interval: 30s + timeout: 5s + retries: 3 + logging: + driver: json-file + options: + max-size: "5m" + max-file: "3" diff --git a/doom/LICENSE-GPL-2.0 b/doom/LICENSE-GPL-2.0 new file mode 100644 index 0000000..52723c3 --- /dev/null +++ b/doom/LICENSE-GPL-2.0 @@ -0,0 +1,339 @@ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/doom/README.md b/doom/README.md new file mode 100644 index 0000000..72b049d --- /dev/null +++ b/doom/README.md @@ -0,0 +1,55 @@ +# DOOM for the Tamagotchi Paradise + +Only the program and the converter are here. No WAD and no game graphics. +Everyone brings their own WAD (Ultimate DOOM `DOOM.WAD` or shareware +`DOOM1.WAD`); the Studio reads it in the browser only. + +- `doom_app.bin`, `doom_xip.bin`: DOOM for the Paradise (PRAM part and flash + part). Source in `src/pdoom`, GPL-2.0-or-later. Based on nRF52840 Doom by + next-hack, GBADoom by doomhack, PrBoom and the DOOM source by id Software. +- `mcuwad.wasm`: the WAD converter MCUDoomWadUtil by Nicola Wrachien (GPL-2.0), + compiled to WebAssembly. Source in `src/wasm` (with a small C library + `libc.c`); `src/umwandler` is the same converter as a command line program. +- The extra pictures of the GBA version (status bar 240x32, narrow digits, menu + texts) are built from the user's WAD by `src/doom.js` (and + `src/pdoom/tools/gbaextras.py`). + +## Keys + +The key layout is stored in the settings block PDMC of the program (version 2, +build switch `-DKEYMAP`): fire, forward, back, use (key or wheel press), hold key +for weapon change (hold + wheel) and sound (hold + wheel press), run with a +double tap on forward, wheel direction. The Studio sets it when building DOOM in +and can change it in a ROM that already has DOOM, without the WAD. +The wheel button is sampled every millisecond by the timer (from v0.4.1), so quick +taps between two frames are not lost and do not add up to the long press (2 s, back +to the Paradise). `src/pdoom/test/tasten_test.c` checks the key logic on a PC +(`cc -w tasten_test.c && ./a.out`). + +## Build + +``` +cd src/pdoom && sh dev/build_dev.sh # arm-none-eabi-gcc 13, newlib-nano +# -> dev/pram.bin (= doom_app.bin) and dev/xip.bin (= doom_xip.bin) +XCF=-DDOOM_FREE sh dev/build_dev.sh # 1.7.2: doomf_app.bin, doomf_xip.bin (places from the settings block) + +cd src/wasm +for f in libc wadfile wadprocessor conv; do + clang --target=wasm32 -O2 -nostdlib -ffreestanding -Iinc -DKEEP_DP -DKEEP_MUS -c $f.c -o $f.o +done +wasm-ld --no-entry --export-dynamic -o mcuwad.wasm libc.o wadfile.o wadprocessor.o conv.o --export=__heap_base +``` + +The results are byte-identical to the files shipped here. + +License: GNU GPL version 2 or later for DOOM (`LICENSE-GPL-2.0`), GNU GPL +version 2 for MCUDoomWadUtil. + +Leaving DOOM (1.6.8, switch `-DPMXL_BACK` in `dev/build_dev.sh`) writes "PMXL" to the mailbox word 0x20000FFC like the +emulators, so the autostart of the stub keeps the Paradise after DOOM was left on purpose. + +1.7.3 test12: `-DDOOM_EXITKEY`: the way back chosen in the Studio (word at 0x13C, as `emu/src/emu/exitkey.h`; wheel and +A/C held 1 s, the hold key + a short wheel press is the sound, toggled when the wheel comes up). `-DPDM_ONE_EPI`: a WAD +with only E2 or E3 is "registered" (it was "indetermined" and the title screen called a missing entry); with one +episode a new game goes straight to the skill (`pdm_one_epi`). Without the Paradise the Studio puts several episodes +into the menu, each its own DOOM (WAD and level data inside 8 MB, so E2 and E3 fit). diff --git a/doom/doom_app.bin b/doom/doom_app.bin new file mode 100644 index 0000000..4ef4198 Binary files /dev/null and b/doom/doom_app.bin differ diff --git a/doom/doom_xip.bin b/doom/doom_xip.bin new file mode 100644 index 0000000..ec58510 Binary files /dev/null and b/doom/doom_xip.bin differ diff --git a/doom/doomf_app.bin b/doom/doomf_app.bin new file mode 100644 index 0000000..cd7b5a6 Binary files /dev/null and b/doom/doomf_app.bin differ diff --git a/doom/doomf_xip.bin b/doom/doomf_xip.bin new file mode 100644 index 0000000..590a9b9 Binary files /dev/null and b/doom/doomf_xip.bin differ diff --git a/doom/mcuwad.wasm b/doom/mcuwad.wasm new file mode 100644 index 0000000..491c46c Binary files /dev/null and b/doom/mcuwad.wasm differ diff --git a/doom/src/pdoom/Doom/include/am_map.h b/doom/src/pdoom/Doom/include/am_map.h new file mode 100644 index 0000000..c38864f --- /dev/null +++ b/doom/src/pdoom/Doom/include/am_map.h @@ -0,0 +1,90 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * AutoMap module. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __AMMAP_H__ +#define __AMMAP_H__ + +#include "d_event.h" + +#define MAPBITS 12 +#define FRACTOMAPBITS (FRACBITS-MAPBITS) + +// Used by ST StatusBar stuff. +#define AM_MSGHEADER (('a'<<24)+('m'<<16)) +#define AM_MSGENTERED (AM_MSGHEADER | ('e'<<8)) +#define AM_MSGEXITED (AM_MSGHEADER | ('x'<<8)) + +// scale on entry +#define INITSCALEMTOF (.2*FRACUNIT) + +// Called by main loop. +boolean AM_Responder(event_t *ev); + +// Called by main loop. +void AM_Ticker(void); + +// Called by main loop, +// called instead of view drawer if automap active. +void AM_Drawer(void); + +// Called to force the automap to quit +// if the level is completed while it is up. +void AM_Stop(void); + +// killough 2/22/98: for saving automap information in savegame: + +extern void AM_Start(void); + +//jff 4/16/98 make externally available + +extern void AM_clearMarks(void); + +typedef struct +{ + fixed_t x, y; +} mpoint_t; + +// end changes -- killough 2/22/98 + +#endif diff --git a/doom/src/pdoom/Doom/include/config.h b/doom/src/pdoom/Doom/include/config.h new file mode 100644 index 0000000..9c9c4b0 --- /dev/null +++ b/doom/src/pdoom/Doom/include/config.h @@ -0,0 +1,185 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +#ifdef _MSC_VER + #define __WINS__ +#endif + +/* Uncomment this to exhaustively run memory checks while the game is running + (this is EXTREMELY slow). */ +/* #undef CHECKHEAP */ + +/* Define for support for MBF helper dogs */ +//#define DOGS 1 +/* Define to be the path where Doom WADs are stored */ +#define DOOMWADDIR "/usr/local/share/games/doom" + +/* Define to 1 if you have the header file. */ +//#define HAVE_ASM_BYTEORDER_H 1 +/* Define to 1 if you have the declaration of `sys_siglist', and to 0 if you + don't. */ +//#define HAVE_DECL_SYS_SIGLIST 1 +/* Define to 1 if you have the `getopt' function. */ +//#define HAVE_GETOPT 1 +/* Define to 1 if you have the `inet_aton' function. */ +//#define HAVE_INET_ATON 1 +/* Define to 1 if you have the `inet_ntop' function. */ +//#define HAVE_INET_NTOP 1 +/* Define to 1 if you have the `inet_pton' function. */ +//#define HAVE_INET_PTON 1 +/* Define to 1 if you have the header file. */ +//#define HAVE_INTTYPES_H 1 +/* Define if you have struct sockaddr_in6 */ +//#define HAVE_IPv6 1 +/* Define to 1 if you have the `m' library (-lm). */ +//#define HAVE_LIBM 1 +/* Define to 1 if you have the `png' library (-lpng). */ +//#define HAVE_LIBPNG 1 +/* Define to 1 if you have the `SDL_mixer' library (-lSDL_mixer). */ +/* #undef HAVE_LIBSDL_MIXER */ + +/* Define if you have the SDL net library -lSDL_net */ +/* #undef HAVE_LIBSDL_NET */ + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `mmap' function. */ +//#define HAVE_MMAP 1 +/* Define to 1 if you have the header file. */ +//#define HAVE_SCHED_H 1 +/* Define to 1 if you have the `sched_setaffinity' function. */ +//#define HAVE_SCHED_SETAFFINITY 1 +/* Define to 1 if you have the `SDL_JoystickGetAxis' function. */ +//#define HAVE_SDL_JOYSTICKGETAXIS 1 +/* Define to 1 if you have the `snprintf' function. */ +//#define HAVE_SNPRINTF 1 +/* Define to 1 if you have the header file. */ +//#define HAVE_STDINT_H 1 +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +//#define HAVE_STRINGS_H 1 +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have that is POSIX.1 compatible. */ +#define HAVE_SYS_WAIT_H 1 + +/* Define to 1 if you have the header file. */ +//#define HAVE_UNISTD_H 1 +/* Define to 1 if you have the `usleep' function. */ +//#define HAVE_USLEEP 1 +/* Define to 1 if you have the `vsnprintf' function. */ +//#define HAVE_VSNPRINTF 1 +/* Uncomment this to cause heap dumps to be generated. Only useful if + INSTRUMENTED is also defined. */ +/* #undef HEAPDUMP */ + +/* Define for high resolution support */ +//#define HIGHRES 1 +/* Define on targets supporting 386 assembly */ +//#define I386_ASM 1 +/* Define this to see real-time memory allocation statistics, and enable extra + debugging features */ +/* #undef INSTRUMENTED */ + +/* If your platform has a fast version of max, define MAX to it */ +/* #undef MAX */ + +/* If your platform has a fast version of min, define MIN to it */ +/* #undef MIN */ + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "prboom" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "prboom 2.5.0" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "prboom" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "2.5.0" + +/* Set to the attribute to apply to struct definitions to make them packed */ + +#ifndef __WINS__ +#define PACKEDATTR __attribute__((packed)) +#else + #define PACKEDATTR +#endif +/* Define to enable internal range checking */ + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Defining this causes time stamps to be created each time a lump is locked, + and lumps locked for long periods of time are reported */ +/* #undef TIMEDIAG */ + +/* Define if you want to use gluImageScale */ +//#define USE_GLU_IMAGESCALE 1 +/* Define if you want to use gluBuild2DMipmaps */ +//#define USE_GLU_MIPMAP 1 +/* Define if you want to use the SDL net lib */ +/* #undef USE_SDL_NET */ + +/* Version number of package */ +#define VERSION "2.5.0" + +/* Define if using the dmalloc debugging malloc package */ +/* #undef WITH_DMALLOC */ + +/* Define to 1 if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ +/* #undef WORDS_BIGENDIAN */ + +/* Define this to perform id checks on zone blocks, to detect corrupted and + illegally freed blocks */ + +#ifdef DEBUG +#define ZONEIDCHECK 1 +#endif + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `int' if doesn't define. */ +/* #undef gid_t */ + +/* Define to `__inline__' or `__inline' if that's what the C compiler + calls it, or to nothing if 'inline' is not supported under any name. */ +//#ifndef __cplusplus +#ifdef __WINS__ + #define inline __inline +#else +#define inline __inline__ +#endif + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ + +#ifdef __WINS__ + #define strncasecmp _strnicmp + #define strcasecmp _stricmp +#endif + +/* Define to strcasecmp, if we have it */ +#define stricmp strcasecmp + +/* Define to strncasecmp, if we have it */ +#define strnicmp strncasecmp + +/* Define to `int' if doesn't define. */ +/* #undef uid_t */ diff --git a/doom/src/pdoom/Doom/include/d_englsh.h b/doom/src/pdoom/Doom/include/d_englsh.h new file mode 100644 index 0000000..ac3dd7e --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_englsh.h @@ -0,0 +1,701 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Printed strings for translation. + * English language support (default). + * See dstrings.h for suggestions about foreign language BEX support + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_ENGLSH__ +#define __D_ENGLSH__ + +/* d_main.c */ +#define D_DEVSTR "Development mode ON.\n" +#define D_CDROM "CD-ROM Version: default.cfg from c:\\doomdata\n" + +/* m_menu.c */ +#define PRESSKEY "press a key." +#define PRESSYN "FIRE to confirm." +#define QUITMSG "are you sure you want to\nquit this great game?" +#define LOADNET "you can't do load while in a net game!\n\n"PRESSKEY +#define QLOADNET "you can't quickload during a netgame!\n\n"PRESSKEY +#define QSAVESPOT "you haven't picked a quicksave slot yet!\n\n"PRESSKEY +#define SAVEDEAD "you can't save if\nyou aren't playing!\n\n"PRESSKEY +#define QSPROMPT "quicksave over your game named\n\n'%s'?\n\n"PRESSYN +#define QLPROMPT "do you want to quickload the game named\n\n'%s'?\n\n"PRESSYN + +#define NEWGAME \ + "you can't start a new game\n"\ + "while in a network game.\n\n"PRESSKEY + +#define NIGHTMARE \ + "are you sure?\n this skill level\n"\ + "isn't even\n remotely fair.\n\n"PRESSYN + +#define SWSTRING \ + "this is the\nshareware version\n"\ + "of doom.\n You need to order\n"\ + "the entire trilogy.\n\n"PRESSKEY + +#define MSGOFF "Messages OFF" +#define MSGON "Messages ON" + +#define RUNOFF "Take your time." +#define RUNON "In a hurry, marine?" + +#define NETEND "you can't end a netgame!\n\n"PRESSKEY +#define ENDGAME "are you sure you want to\nend the game?\n\n"PRESSYN +#define RESTARTLEVEL "restart the level?\n\n"PRESSYN + +#define DOSY "(press y to quit)" + +#define DETAILHI "High detail" +#define DETAILLO "Low detail" +#define GAMMALVL0 "Gamma correction OFF" +//Unused ~Kippykip +//#define GAMMALVL1 "Gamma correction level 1" +//#define GAMMALVL2 "Gamma correction level 2" +//#define GAMMALVL3 "Gamma correction level 3" +//#define GAMMALVL4 "Gamma correction level 4" +#define GAMMALVL4 "Gamma correction ON" +#define EMPTYSTRING "empty slot" + +/* p_inter.c */ +#define GOTARMOR "Picked up the armor." +#define GOTMEGA "Picked up the MegaArmor!" +#define GOTHTHBONUS "Picked up a health bonus." +#define GOTARMBONUS "Picked up an armor bonus." +#define GOTSTIM "Picked up a stimpack." +#define GOTMEDIKIT "Picked up a medikit." +//#define GOTMEDINEED "Picked up a medikit that you REALLY need!" - String is too long for GBA res +#define GOTMEDINEED "Picked up a medikit." +#define GOTSUPER "Supercharge!" + +#define GOTBLUECARD "Picked up a blue keycard." +#define GOTYELWCARD "Picked up a yellow keycard." +#define GOTREDCARD "Picked up a red keycard." +#define GOTBLUESKUL "Picked up a blue skull key." +#define GOTYELWSKUL "Picked up a yellow skull key." +#define GOTREDSKULL "Picked up a red skull key." + +#define GOTINVUL "Invulnerability!" +#define GOTBERSERK "Berserk!" +#define GOTINVIS "Partial Invisibility" +#define GOTSUIT "Radiation Shielding Suit" +#define GOTMAP "Computer Area Map" +#define GOTVISOR "Light Amplification Visor" +#define GOTMSPHERE "MegaSphere!" + +#define GOTCLIP "Picked up a clip." +#define GOTCLIPBOX "Picked up a box of bullets." +#define GOTROCKET "Picked up a rocket." +#define GOTROCKBOX "Picked up a box of rockets." +#define GOTCELL "Picked up an energy cell." +#define GOTCELLBOX "Picked up an energy cell pack." +#define GOTSHELLS "Picked up 4 shotgun shells." +#define GOTSHELLBOX "Picked up a box of shotgun shells." +#define GOTBACKPACK "Picked up a backpack full of ammo!" + +#define GOTBFG9000 "You got the BFG9000! Oh, yes." +#define GOTCHAINGUN "You got the chaingun!" +#define GOTCHAINSAW "A chainsaw! Find some meat!" +#define GOTLAUNCHER "You got the rocket launcher!" +#define GOTPLASMA "You got the plasma gun!" +#define GOTSHOTGUN "You got the shotgun!" +#define GOTSHOTGUN2 "You got the super shotgun!" + +/* p_doors.c */ +#define PD_BLUEO "You need a blue key to activate this object" +#define PD_REDO "You need a red key to activate this object" +#define PD_YELLOWO "You need a yellow key to activate this object" +#define PD_BLUEK "You need a blue key to open this door" +#define PD_REDK "You need a red key to open this door" +#define PD_YELLOWK "You need a yellow key to open this door" +/* jff 02/05/98 Create messages specific to card and skull keys */ +#define PD_BLUEC "You need a blue card to open this door" +#define PD_REDC "You need a red card to open this door" +#define PD_YELLOWC "You need a yellow card to open this door" +#define PD_BLUES "You need a blue skull to open this door" +#define PD_REDS "You need a red skull to open this door" +#define PD_YELLOWS "You need a yellow skull to open this door" +#define PD_ANY "Any key will open this door" +#define PD_ALL3 "You need all three keys to open this door" +#define PD_ALL6 "You need all six keys to open this door" + +/* g_game.c */ +#define GGSAVED "game saved." + +/* hu_stuff.c */ +#define HUSTR_MSGU "[Message unsent]" + +#define HUSTR_E1M1 "E1M1: Hangar" +#define HUSTR_E1M2 "E1M2: Nuclear Plant" +#define HUSTR_E1M3 "E1M3: Toxin Refinery" +#define HUSTR_E1M4 "E1M4: Command Control" +#define HUSTR_E1M5 "E1M5: Phobos Lab" +#define HUSTR_E1M6 "E1M6: Central Processing" +#define HUSTR_E1M7 "E1M7: Computer Station" +#define HUSTR_E1M8 "E1M8: Phobos Anomaly" +#define HUSTR_E1M9 "E1M9: Military Base" + +#define HUSTR_E2M1 "E2M1: Deimos Anomaly" +#define HUSTR_E2M2 "E2M2: Containment Area" +#define HUSTR_E2M3 "E2M3: Refinery" +#define HUSTR_E2M4 "E2M4: Deimos Lab" +#define HUSTR_E2M5 "E2M5: Command Center" +#define HUSTR_E2M6 "E2M6: Halls of the Damned" +#define HUSTR_E2M7 "E2M7: Spawning Vats" +#define HUSTR_E2M8 "E2M8: Tower of Babel" +#define HUSTR_E2M9 "E2M9: Fortress of Mystery" + +#define HUSTR_E3M1 "E3M1: Hell Keep" +#define HUSTR_E3M2 "E3M2: Slough of Despair" +#define HUSTR_E3M3 "E3M3: Pandemonium" +#define HUSTR_E3M4 "E3M4: House of Pain" +#define HUSTR_E3M5 "E3M5: Unholy Cathedral" +#define HUSTR_E3M6 "E3M6: Mt. Erebus" +#define HUSTR_E3M7 "E3M7: Limbo" +#define HUSTR_E3M8 "E3M8: Dis" +#define HUSTR_E3M9 "E3M9: Warrens" + +#define HUSTR_E4M1 "E4M1: Hell Beneath" +#define HUSTR_E4M2 "E4M2: Perfect Hatred" +#define HUSTR_E4M3 "E4M3: Sever The Wicked" +#define HUSTR_E4M4 "E4M4: Unruly Evil" +#define HUSTR_E4M5 "E4M5: They Will Repent" +#define HUSTR_E4M6 "E4M6: Against Thee Wickedly" +#define HUSTR_E4M7 "E4M7: And Hell Followed" +#define HUSTR_E4M8 "E4M8: Unto The Cruel" +#define HUSTR_E4M9 "E4M9: Fear" + +#define HUSTR_1 "level 1: entryway" +#define HUSTR_2 "level 2: underhalls" +#define HUSTR_3 "level 3: the gantlet" +#define HUSTR_4 "level 4: the focus" +#define HUSTR_5 "level 5: the waste tunnels" +#define HUSTR_6 "level 6: the crusher" +#define HUSTR_7 "level 7: dead simple" +#define HUSTR_8 "level 8: tricks and traps" +#define HUSTR_9 "level 9: the pit" +#define HUSTR_10 "level 10: refueling base" +#define HUSTR_11 "level 11: 'o' of destruction!" + +#define HUSTR_12 "level 12: the factory" +#define HUSTR_13 "level 13: downtown" +#define HUSTR_14 "level 14: the inmost dens" +#define HUSTR_15 "level 15: industrial zone" +#define HUSTR_16 "level 16: suburbs" +#define HUSTR_17 "level 17: tenements" +#define HUSTR_18 "level 18: the courtyard" +#define HUSTR_19 "level 19: the citadel" +#define HUSTR_20 "level 20: gotcha!" + +#define HUSTR_21 "level 21: nirvana" +#define HUSTR_22 "level 22: the catacombs" +#define HUSTR_23 "level 23: barrels o' fun" +#define HUSTR_24 "level 24: the chasm" +#define HUSTR_25 "level 25: bloodfalls" +#define HUSTR_26 "level 26: the abandoned mines" +#define HUSTR_27 "level 27: monster condo" +#define HUSTR_28 "level 28: the spirit world" +#define HUSTR_29 "level 29: the living end" +#define HUSTR_30 "level 30: icon of sin" + +#define HUSTR_31 "level 31: wolfenstein" +#define HUSTR_32 "level 32: grosse" + +#define PHUSTR_1 "level 1: congo" +#define PHUSTR_2 "level 2: well of souls" +#define PHUSTR_3 "level 3: aztec" +#define PHUSTR_4 "level 4: caged" +#define PHUSTR_5 "level 5: ghost town" +#define PHUSTR_6 "level 6: baron's lair" +#define PHUSTR_7 "level 7: caughtyard" +#define PHUSTR_8 "level 8: realm" +#define PHUSTR_9 "level 9: abattoire" +#define PHUSTR_10 "level 10: onslaught" +#define PHUSTR_11 "level 11: hunted" + +#define PHUSTR_12 "level 12: speed" +#define PHUSTR_13 "level 13: the crypt" +#define PHUSTR_14 "level 14: genesis" +#define PHUSTR_15 "level 15: the twilight" +#define PHUSTR_16 "level 16: the omen" +#define PHUSTR_17 "level 17: compound" +#define PHUSTR_18 "level 18: neurosphere" +#define PHUSTR_19 "level 19: nme" +#define PHUSTR_20 "level 20: the death domain" + +#define PHUSTR_21 "level 21: slayer" +#define PHUSTR_22 "level 22: impossible mission" +#define PHUSTR_23 "level 23: tombstone" +#define PHUSTR_24 "level 24: the final frontier" +#define PHUSTR_25 "level 25: the temple of darkness" +#define PHUSTR_26 "level 26: bunker" +#define PHUSTR_27 "level 27: anti-christ" +#define PHUSTR_28 "level 28: the sewers" +#define PHUSTR_29 "level 29: odyssey of noises" +#define PHUSTR_30 "level 30: the gateway of hell" + +#define PHUSTR_31 "level 31: cyberden" +#define PHUSTR_32 "level 32: go 2 it" + +#define THUSTR_1 "level 1: system control" +#define THUSTR_2 "level 2: human bbq" +#define THUSTR_3 "level 3: power control" +#define THUSTR_4 "level 4: wormhole" +#define THUSTR_5 "level 5: hanger" +#define THUSTR_6 "level 6: open season" +#define THUSTR_7 "level 7: prison" +#define THUSTR_8 "level 8: metal" +#define THUSTR_9 "level 9: stronghold" +#define THUSTR_10 "level 10: redemption" +#define THUSTR_11 "level 11: storage facility" + +#define THUSTR_12 "level 12: crater" +#define THUSTR_13 "level 13: nukage processing" +#define THUSTR_14 "level 14: steel works" +#define THUSTR_15 "level 15: dead zone" +#define THUSTR_16 "level 16: deepest reaches" +#define THUSTR_17 "level 17: processing area" +#define THUSTR_18 "level 18: mill" +#define THUSTR_19 "level 19: shipping/respawning" +#define THUSTR_20 "level 20: central processing" + +#define THUSTR_21 "level 21: administration center" +#define THUSTR_22 "level 22: habitat" +#define THUSTR_23 "level 23: lunar mining project" +#define THUSTR_24 "level 24: quarry" +#define THUSTR_25 "level 25: baron's den" +#define THUSTR_26 "level 26: ballistyx" +#define THUSTR_27 "level 27: mount pain" +#define THUSTR_28 "level 28: heck" +#define THUSTR_29 "level 29: river styx" +#define THUSTR_30 "level 30: last call" + +#define THUSTR_31 "level 31: pharaoh" +#define THUSTR_32 "level 32: caribbean" + +#define HUSTR_CHATMACRO1 "I'm ready to kick butt!" +#define HUSTR_CHATMACRO2 "I'm OK." +#define HUSTR_CHATMACRO3 "I'm not looking too good!" +#define HUSTR_CHATMACRO4 "Help!" +#define HUSTR_CHATMACRO5 "You suck!" +#define HUSTR_CHATMACRO6 "Next time, scumbag..." +#define HUSTR_CHATMACRO7 "Come here!" +#define HUSTR_CHATMACRO8 "I'll take care of it." +#define HUSTR_CHATMACRO9 "Yes" +#define HUSTR_CHATMACRO0 "No" + +#define HUSTR_TALKTOSELF1 "You mumble to yourself" +#define HUSTR_TALKTOSELF2 "Who's there?" +#define HUSTR_TALKTOSELF3 "You scare yourself" +#define HUSTR_TALKTOSELF4 "You start to rave" +#define HUSTR_TALKTOSELF5 "You've lost it..." + +#define HUSTR_MESSAGESENT "[Message Sent]" + +/* The following should NOT be changed unless it seems + * just AWFULLY necessary */ + +#define HUSTR_PLRGREEN "Player 1: " +#define HUSTR_PLRINDIGO "Player 2: " +#define HUSTR_PLRBROWN "Player 3: " +#define HUSTR_PLRRED "Player 4: " + +#define HUSTR_KEYGREEN 'g' +#define HUSTR_KEYINDIGO 'i' +#define HUSTR_KEYBROWN 'b' +#define HUSTR_KEYRED 'r' + +/* am_map.c */ + +#define AMSTR_FOLLOWON "Follow Mode ON" +#define AMSTR_FOLLOWOFF "Follow Mode OFF" + +#define AMSTR_GRIDON "Grid ON" +#define AMSTR_GRIDOFF "Grid OFF" + +#define AMSTR_MARKEDSPOT "Marked Spot" +#define AMSTR_MARKSCLEARED "All Marks Cleared" + +#define AMSTR_ROTATEON "Rotate Mode ON" +#define AMSTR_ROTATEOFF "Rotate Mode OFF" + +#define AMSTR_OVERLAYON "Overlay Mode ON" +#define AMSTR_OVERLAYOFF "Overlay Mode OFF" + +/* st_stuff.c */ + +#define STSTR_MUS "Music Change" +#define STSTR_NOMUS "IMPOSSIBLE SELECTION" +#define STSTR_DQDON "Degreelessness Mode On" +#define STSTR_DQDOFF "Degreelessness Mode Off" + +#define STSTR_KFAADDED "Very Happy Ammo Added" +#define STSTR_FAADDED "Ammo (no keys) Added" + +#define STSTR_NCON "No Clipping Mode ON" +#define STSTR_NCOFF "No Clipping Mode OFF" + +#define STSTR_BEHOLD "inVuln, Str, Inviso, Rad, Allmap, or Lite-amp" +#define STSTR_BEHOLDX "Power-up Toggled" + +#define STSTR_CHOPPERS "... doesn't suck - GM" +#define STSTR_CLEV "Changing Level..." + +#define STSTR_COMPON "Compatibility Mode On" /* phares */ +#define STSTR_COMPOFF "Compatibility Mode Off" /* phares */ + +#define STSTR_ROCKETON "Enemy Rockets On" +#define STSTR_ROCKETOFF "Enemy Rockets Off" + +#define STSTR_FPSON "FPS Counter On" +#define STSTR_FPSOFF "FPS Counter Off" + +/* f_finale.c */ + +#define E1TEXT \ + "Once you beat the big badasses\n"\ + "and clean out the moon base\n"\ + "you're supposed to win?\n"\ + "Where's your ticket home?\n"\ + "What the hell is this? It's not\n"\ + "supposed to end this way!\n"\ + "\n" \ + "It stinks like rotten meat, but\n"\ + "looks like the lost Deimos base.\n"\ + "You're stuck on The Shores of\n"\ + "Hell.\n"\ + "The only way out is through." + +#define E2TEXT \ + "You've done it! The hideous\n"\ + "cyber-demon that ruled the\n"\ + "lost Deimos moon base has been\n"\ + "slain and you are triumphant!\n"\ + "But...where are you?\n"\ + "You clamber to the edge of the\n"\ + "moon and see the awful truth.\n" \ + "\n"\ + "Deimos floats above Hell itself!\n"\ + "You've never heard of anyone\n"\ + "escaping from Hell, but you'll\n"\ + "make the bastards sorry they\n"\ + "ever heard of you!" + +#define E3TEXT \ + "The loathsome spiderdemon that\n"\ + "masterminded the invasion of the\n"\ + "moon bases and caused so much\n"\ + "death has had its ass kicked.\n"\ + "\n"\ + "A hidden doorway opens.\n"\ + "You've proven too tough for\n"\ + "Hell to contain, and now Hell at\n"\ + "last plays fair -- you emerge\n"\ + "from the door to see the green\n"\ + "fields of Earth! Home at last.\n" + +#define E4TEXT \ + "the spider mastermind must have\n"\ + "sent forth its legions of\n"\ + "hellspawn before your final\n"\ + "confrontation with that\n"\ + "terrible beast from hell.\n"\ + "but you stepped forward and\n"\ + "brought eternal damnation\n"\ + "and suffering upon the horde as\n"\ + "a true hero would in the face\n"\ + "of evil.\n"\ + "besides, someone is gonna pay for\n"\ + "what happened to daisy.\n"\ + "next stop, hell on earth!" + +/* after level 6, put this: */ + +#define C1TEXT \ + "YOU HAVE ENTERED DEEPLY INTO\n"\ + "THE INFESTED STARPORT. SOMETHING\n"\ + "IS WRONG. THE MONSTERS HAVE\n"\ + "BROUGHT THEIR OWN REALITY WITH\n"\ + "THEM, AND THE STARPORT'S TECH\n" \ + "IS BEING SUBVERTED BY THEM.\n" \ + "AHEAD, YOU SEE AN OUTPOST OF\n"\ + "HELL, A FORTIFIED ZONE. IF YOU\n"\ + "CAN GET PAST YOU CAN PENETRATE\n"\ + "INTO THE HAUNTED HEART OF THE\n"\ + "STARBASE AND FIND THE SWITCH\n"\ + "WHICH HOLDS EARTH'S POPULATION\n"\ + "HOSTAGE." + +/* After level 11, put this: */ + +#define C2TEXT \ + "YOU HAVE WON! YOUR VICTORY HAS\n"\ + "ENABLED HUMANKIND TO EVACUATE\n"\ + "EARTH AND ESCAPE THE NIGHTMARE.\n"\ + "NOW YOU ARE THE ONLY HUMAN LEFT.\n"\ + "CANNIBALS, ALIENS AND EVIL\n"\ + "SPIRITS ARE YOUR NEIGHBORS.\n"\ + "BUT THEN, EARTH CONTROL BEAMS\n"\ + "DOWN A MESSAGE: SENSORS HAVE\n"\ + "LOCATED THE SOURCE OF THE ALIEN\n"\ + "INVASION. THE ALIEN BASE IS IN\n"\ + "THE HEART OF YOUR OWN HOME CITY.\n"\ + "SLOWLY AND PAINFULLY YOU GET UP\n"\ + "AND RETURN TO THE FRAY." + +/* After level 20, put this: */ + +#define C3TEXT \ + "YOU ARE AT THE CORRUPT HEART OF\n"\ + "THE CITY, SURROUNDED BY THE\n"\ + "CORPSES OF YOUR ENEMIES. YOU\n"\ + "SEE NO WAY TO DESTROY THE\n"\ + "CREATURES' ENTRYWAY ON THIS SIDE,\n"\ + "SO YOU CLENCH YOUR TEETH AND\n"\ + "PLUNGE THROUGH IT.\n"\ + "\n"\ + "THERE MUST BE A WAY TO CLOSE\n"\ + "IT ON THE OTHER SIDE. WHAT DO\n"\ + "YOU CARE IF YOU'VE GOT TO GO\n"\ + "THROUGH HELL TO GET TO IT?"\ + + +/* After level 29, put this: */ + +#define C4TEXT \ + "THE HORRENDOUS VISAGE OF THE\n"\ + "BIGGEST DEMON YOU'VE EVER SEEN\n"\ + "CRUMBLES BEFORE YOU, AFTER YOU\n"\ + "PUMP ROCKETS INTO HIS EXPOSED\n"\ + "BRAIN. THE MONSTERS THRASHING\n"\ + "LIMBS DEVASTATING UNTOLD MILES\n"\ + "OF HELL'S SURFACE.\n"\ + "YOU'VE DONE IT. THE INVASION IS\n"\ + "OVER. HELL IS A WRECK.\n"\ + "YOU BEGIN THE LONG TREK BACK\n"\ + "HOME. REBUILDING EARTH WILL\n"\ + "BE A LOT LESS FUN THAN\n"\ + "RUINING IT WAS." + +/* Before level 31, put this: */ + +#define C5TEXT \ + "CONGRATULATIONS, YOU'VE FOUND\n"\ + "THE SECRET LEVEL! LOOKS LIKE\n"\ + "IT'S BEEN BUILT BY HUMANS,\n"\ + "RATHER THAN DEMONS. YOU WONDER\n"\ + "WHO THE INMATES OF THIS CORNER\n"\ + "OF HELL WILL BE." + +/* Before level 32, put this: */ + +#define C6TEXT \ + "CONGRATULATIONS, YOU'VE FOUND\n"\ + "THE SUPER SECRET LEVEL!\n"\ + "YOU'D BETTER BLAZE THROUGH\n"\ + "THIS ONE!" + +/*** Plutonia ***/ +/* after map 06 */ + +#define P1TEXT \ + "You gloat over the steaming carcass of the\n"\ + "Guardian. With its death, you've wrested\n"\ + "the Accelerator from the stinking claws\n"\ + "of Hell. You relax and glance around the\n"\ + "room. Damn! There was supposed to be at\n"\ + "least one working prototype, but you can't\n"\ + "see it. The demons must have taken it.\n"\ + "\n"\ + "You must find the prototype, or all your\n"\ + "struggles will have been wasted. Keep\n"\ + "moving, keep fighting, keep killing.\n"\ + "Oh yes, keep living, too." + +/* after map 11 */ + +#define P2TEXT \ + "Even the deadly Arch-Vile labyrinth could\n"\ + "not stop you, and you've gotten to the\n"\ + "prototype Accelerator which is soon\n"\ + "efficiently and permanently deactivated.\n"\ + "\n"\ + "You're good at that kind of thing." + +/* after map 20 */ + +#define P3TEXT \ + "You've bashed and battered your way into\n"\ + "the heart of the devil-hive. Time for a\n"\ + "Search-and-Destroy mission, aimed at the\n"\ + "Gatekeeper, whose foul offspring is\n"\ + "cascading to Earth. Yeah, he's bad. But\n"\ + "you know who's worse!\n"\ + "\n"\ + "Grinning evilly, you check your gear, and\n"\ + "get ready to give the bastard a little Hell\n"\ + "of your own making!" + +/* after map 30 */ + +#define P4TEXT \ + "The Gatekeeper's evil face is splattered\n"\ + "all over the place. As its tattered corpse\n"\ + "collapses, an inverted Gate forms and\n"\ + "sucks down the shards of the last\n"\ + "prototype Accelerator, not to mention the\n"\ + "few remaining demons. You're done. Hell\n"\ + "has gone back to pounding bad dead folks \n"\ + "instead of good live ones. Remember to\n"\ + "tell your grandkids to put a rocket\n"\ + "launcher in your coffin. If you go to Hell\n"\ + "when you die, you'll need it for some\n"\ + "final cleaning-up ..." + +/* before map 31 */ + +#define P5TEXT \ + "You've found the second-hardest level we\n"\ + "got. Hope you have a saved game a level or\n"\ + "two previous. If not, be prepared to die\n"\ + "aplenty. For master marines only." + +/* before map 32 */ + +#define P6TEXT \ + "Betcha wondered just what WAS the hardest\n"\ + "level we had ready for ya? Now you know.\n"\ + "No one gets out alive." + +/*** TNT: Evilution ***/ + +#define T1TEXT \ + "You've fought your way out of the infested\n"\ + "experimental labs. It seems that UAC has\n"\ + "once again gulped it down. With their\n"\ + "high turnover, it must be hard for poor\n"\ + "old UAC to buy corporate health insurance\n"\ + "nowadays..\n"\ + "\n"\ + "Ahead lies the military complex, now\n"\ + "swarming with diseased horrors hot to get\n"\ + "their teeth into you. With luck, the\n"\ + "complex still has some warlike ordnance\n"\ + "laying around." + +#define T2TEXT \ + "You hear the grinding of heavy machinery\n"\ + "ahead. You sure hope they're not stamping\n"\ + "out new hellspawn, but you're ready to\n"\ + "ream out a whole herd if you have to.\n"\ + "They might be planning a blood feast, but\n"\ + "you feel about as mean as two thousand\n"\ + "maniacs packed into one mad killer.\n"\ + "\n"\ + "You don't plan to go down easy." + +#define T3TEXT \ + "The vista opening ahead looks real damn\n"\ + "familiar. Smells familiar, too -- like\n"\ + "fried excrement. You didn't like this\n"\ + "place before, and you sure as hell ain't\n"\ + "planning to like it now. The more you\n"\ + "brood on it, the madder you get.\n"\ + "Hefting your gun, an evil grin trickles\n"\ + "onto your face. Time to take some names." + +#define T4TEXT \ + "Suddenly, all is silent, from one horizon\n"\ + "to the other. The agonizing echo of Hell\n"\ + "fades away, the nightmare sky turns to\n"\ + "blue, the heaps of monster corpses start \n"\ + "to evaporate along with the evil stench \n"\ + "that filled the air. Jeeze, maybe you've\n"\ + "done it. Have you really won?\n"\ + "\n"\ + "Something rumbles in the distance.\n"\ + "A blue light begins to glow inside the\n"\ + "ruined skull of the demon-spitter." + +#define T5TEXT \ + "What now? Looks totally different. Kind\n"\ + "of like King Tut's condo. Well,\n"\ + "whatever's here can't be any worse\n"\ + "than usual. Can it? Or maybe it's best\n"\ + "to let sleeping gods lie.." + +#define T6TEXT \ + "Time for a vacation. You've burst the\n"\ + "bowels of hell and by golly you're ready\n"\ + "for a break. You mutter to yourself,\n"\ + "Maybe someone else can kick Hell's ass\n"\ + "next time around. Ahead lies a quiet town,\n"\ + "with peaceful flowing water, quaint\n"\ + "buildings, and presumably no Hellspawn.\n"\ + "\n"\ + "As you step off the transport, you hear\n"\ + "the stomp of a cyberdemon's iron shoe." + +/* + * Character cast strings F_FINALE.C + */ +#define CC_ZOMBIE "ZOMBIEMAN" +#define CC_SHOTGUN "SHOTGUN GUY" +#define CC_HEAVY "HEAVY WEAPON DUDE" +#define CC_IMP "IMP" +#define CC_DEMON "DEMON" +#define CC_LOST "LOST SOUL" +#define CC_CACO "CACODEMON" +#define CC_HELL "HELL KNIGHT" +#define CC_BARON "BARON OF HELL" +#define CC_ARACH "ARACHNOTRON" +#define CC_PAIN "PAIN ELEMENTAL" +#define CC_REVEN "REVENANT" +#define CC_MANCU "MANCUBUS" +#define CC_ARCH "ARCH-VILE" +#define CC_SPIDER "THE SPIDER MASTERMIND" +#define CC_CYBER "THE CYBERDEMON" +#define CC_HERO "OUR HERO" + +#endif diff --git a/doom/src/pdoom/Doom/include/d_event.h b/doom/src/pdoom/Doom/include/d_event.h new file mode 100644 index 0000000..6ffd80a --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_event.h @@ -0,0 +1,120 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Event information structures. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_EVENT__ +#define __D_EVENT__ + +#include "doomtype.h" + +// +// Event handling. +// + +// Input event types. +typedef enum +{ + ev_keydown, ev_keyup, ev_mouse, ev_joystick +} evtype_t; + +// Event structure. +typedef struct +{ + evtype_t type; + int data1; // keys / mouse/joystick buttons + int data2; // mouse/joystick x move + int data3; // mouse/joystick y move +} event_t; + +typedef enum +{ + ga_nothing, + ga_loadlevel, + ga_newgame, + ga_loadgame, + ga_savegame, + ga_playdemo, + ga_completed, + ga_victory, + ga_worlddone, +} gameaction_t; + +// +// Button/action code definitions. +// +typedef enum +{ + // Press "Fire". + BT_ATTACK = 1, + + // Use button, to open doors, activate switches. + BT_USE = 2, + + // Flag: game events, not really buttons. + BT_SPECIAL = 128, + BT_SPECIALMASK = 3, + + // Flag, weapon change pending. + // If true, the next 4 bits hold weapon num. + BT_CHANGE = 4, + + // The 4bit weapon mask and shift, convenience. +//BT_WEAPONMASK = (8+16+32), + BT_WEAPONMASK = (8 + 16 + 32 + 64), // extended to pick up SSG // phares + BT_WEAPONSHIFT = 3, + + // Special events + BTS_LOADGAME = 0, // Loads a game + // Pause the game. + BTS_PAUSE = 1, + // Save the game at each console. + BTS_SAVEGAME = 2, + BTS_RESTARTLEVEL = 3, // Restarts the current level + + // Savegame slot numbers occupy the second byte of buttons. + BTS_SAVEMASK = (4 + 8 + 16), + BTS_SAVESHIFT = 2, + +} buttoncode_t; + +#endif diff --git a/doom/src/pdoom/Doom/include/d_items.h b/doom/src/pdoom/Doom/include/d_items.h new file mode 100644 index 0000000..4110614 --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_items.h @@ -0,0 +1,68 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Items: key cards, artifacts, weapon, ammunition. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_ITEMS__ +#define __D_ITEMS__ + +#include "doomdef.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +/* Weapon info: sprite frames, ammunition use. */ +typedef struct +{ + ammotype_t ammo; + int upstate; + int downstate; + int readystate; + int atkstate; + int flashstate; + +} weaponinfo_t; + +extern const weaponinfo_t weaponinfo[NUMWEAPONS]; + +#endif diff --git a/doom/src/pdoom/Doom/include/d_main.h b/doom/src/pdoom/Doom/include/d_main.h new file mode 100644 index 0000000..7ecfe17 --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_main.h @@ -0,0 +1,77 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Main startup and splash screenstuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_MAIN__ +#define __D_MAIN__ + +#include "d_event.h" +#include "w_wad.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +//jff end of external declaration of command line playmode + +extern const boolean nosfxparm; +extern const boolean nomusicparm; + +extern const boolean nodrawers; +// Called by IO functions when input is detected. +void D_PostEvent(event_t *ev); + +// Demo stuff +void D_AdvanceDemo(void); +void D_DoAdvanceDemo(void); + +// +// BASE LEVEL +// + +void D_PageTicker(void); +void D_StartTitle(void); +void D_DoomMain(void); +void D_AddFile(); + +#endif diff --git a/doom/src/pdoom/Doom/include/d_net.h b/doom/src/pdoom/Doom/include/d_net.h new file mode 100644 index 0000000..783df0d --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_net.h @@ -0,0 +1,62 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Networking stuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_NET__ +#define __D_NET__ + +#include "d_player.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +void D_BuildNewTiccmds(void); + +//? how many ticks to run? +void TryRunTics(void); + +// CPhipps - move to header file +void D_InitNetGame(void); // This does the setup + +#endif diff --git a/doom/src/pdoom/Doom/include/d_player.h b/doom/src/pdoom/Doom/include/d_player.h new file mode 100644 index 0000000..554d4c0 --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_player.h @@ -0,0 +1,243 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Player state structure. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_PLAYER__ +#define __D_PLAYER__ + +// The player data structure depends on a number +// of other structs: items (internal inventory), +// animation states (closely tied to the sprites +// used to represent them, unfortunately). + +#include "d_items.h" + +#include "p_pspr.h" + +// In addition, the player is just a special +// case of the generic moving object/actor. +#include "p_mobj.h" + +// Finally, for odd reasons, the player input +// is buffered within the player data struct, +// as commands per game tick. +#include "d_ticcmd.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +// +// Player states. +// +typedef enum +{ + // Playing or camping. + PST_LIVE, + // Dead on the ground, view follows killer. + PST_DEAD, + // Ready to restart/respawn??? + PST_REBORN + +} playerstate_t; + +// +// Player internal flags, for cheats and debug. +// +typedef enum +{ + // No clipping, walk through barriers. + CF_NOCLIP = 1, + // No damage, no health loss. + CF_GODMODE = 2, + // Not really a cheat, just a debug aid. + CF_NOMOMENTUM = 4, + + //You played goldeneye right? + CF_ENEMY_ROCKETS = 8 + +} cheat_t; + +// +// Extended player object info: player_t +// +typedef struct player_s +{ + mobj_t *mo; + playerstate_t playerstate; + ticcmd_t cmd; + + // Determine POV, + // including viewpoint bobbing during movement. + // Focal origin above r.z + fixed_t viewz; + // Base height above floor for viewz. + fixed_t viewheight; + // Bob/squat speed. + fixed_t deltaviewheight; + // bounded/scaled total momentum. + fixed_t bob; + + /* killough 10/98: used for realistic bobbing (i.e. not simply overall speed) + * mo->momx and mo->momy represent true momenta experienced by player. + * This only represents the thrust that the player applies himself. + * This avoids anomolies with such things as Boom ice and conveyors. + */ + fixed_t momx, momy; // killough 10/98 + + // This is only used between levels, + // mo->health is used during levels. + short health; + short armorpoints; + // Armor type is 0-2. + short armortype; + + // Power ups. invinc and invis are tic counters. + short powers[NUMPOWERS]; + boolean cards[NUMCARDS]; + boolean backpack; + + // Frags, kills of other players. + short frags[MAXPLAYERS]; + short readyweapon; + + // Is wp_nochange if not changing. + short pendingweapon; + + short weaponowned[NUMWEAPONS]; + short ammo[NUMAMMO]; + short maxammo[NUMAMMO]; + + // True if button down last tic. + char attackdown; + char usedown; + + // Bit flags, for cheats and debug. + // See cheat_t, above. + int cheats; + + // Refired shots are less accurate. + char refire; + + // For intermission stats. + short killcount; + short itemcount; + short secretcount; + + // Hint messages. // CPhipps - const + const char *message; + + // For screen flashing (red or bright). + short damagecount; + short bonuscount; + + // Who did damage (NULL for floors/ceilings). + mobj_t *attacker; + + // So gun flashes light up areas. + short extralight; + + // Current PLAYPAL, ??? + // can be set to REDCOLORMAP for pain, etc. + short fixedcolormap; + + // Player skin colorshift, + // 0-3 for which color to draw player. + char colormap; + + // Overlay view sprites (gun, etc). + pspdef_t psprites[NUMPSPRITES]; + + // True if secret level has been done. + boolean didsecret; + +} player_t; + +// +// INTERMISSION +// Structure passed e.g. to WI_Start(wb) +// +typedef struct +{ + boolean in; // whether the player is in game + + // Player stats, kills, collected items etc. + short skills; + short sitems; + short ssecret; + int stime; + short frags[4]; + int score; // current score on entry, modified on return + +} wbplayerstruct_t; + +typedef struct +{ + uint8_t epsd; // episode # (0-2) + + // if true, splash the secret level + boolean didsecret; + + // previous and next levels, origin 0 + char last; + char next; + + short maxkills; + short maxitems; + short maxsecret; + short maxfrags; + + // the par time + int partime; + + // index of this player in game + short pnum; + + wbplayerstruct_t plyr[MAXPLAYERS]; + + // CPhipps - total game time for completed levels so far + int totaltimes; + +} wbstartstruct_t; + +#endif diff --git a/doom/src/pdoom/Doom/include/d_think.h b/doom/src/pdoom/Doom/include/d_think.h new file mode 100644 index 0000000..2ff7571 --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_think.h @@ -0,0 +1,103 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * MapObj data. Map Objects or mobjs are actors, entities, + * thinker, take-your-pick... anything that moves, acts, or + * suffers state changes of more or less violent nature. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_THINK__ +#define __D_THINK__ + +#ifdef __GNUG__ +#pragma interface +#endif +#include "doomdef.h" +/* + * Experimental stuff. + * To compile this as "ANSI C with classes" + * we will need to handle the various + * action functions cleanly. + */ +// killough 11/98: convert back to C instead of C++ +typedef void (*actionf_t)(); +//typedef void (*actionf_v)(); +//typedef void (*actionf_p1)( void* ); +//typedef void (*actionf_p2)( void*, void* ); + +/* Note: In d_deh.c you will find references to these + * wherever code pointers and function handlers exist + */ +/* + typedef union + { + actionf_p1 acp1; + actionf_v acv; + actionf_p2 acp2; + + } actionf_t; + */ + +/* Historically, "think_t" is yet another + * function pointer to a routine to handle + * an actor. + */ +typedef actionf_t think_t; + +/* Doubly linked list of actors. */ +typedef struct thinker_s +{ + //struct thinker_s* prev; + unsigned short prev_sptr; + //struct thinker_s* next; + unsigned short next_sptr; + think_t function; + +} thinker_t; +static inline thinker_t* getThinkerPrev(thinker_t *pthinker) +{ + return (thinker_t*) getLongPtr(pthinker->prev_sptr); +} +static inline thinker_t* getThinkerNext(thinker_t *pthinker) +{ + return (thinker_t*) getLongPtr(pthinker->next_sptr); +} +#endif diff --git a/doom/src/pdoom/Doom/include/d_ticcmd.h b/doom/src/pdoom/Doom/include/d_ticcmd.h new file mode 100644 index 0000000..46c1c5f --- /dev/null +++ b/doom/src/pdoom/Doom/include/d_ticcmd.h @@ -0,0 +1,70 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * System specific interface stuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_TICCMD__ +#define __D_TICCMD__ + +#include "doomtype.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +/* The data sampled per tick (single player) + * and transmitted to other peers (multiplayer). + * Mainly movements/button commands per game tick, + * plus a checksum for internal state consistency. + * CPhipps - explicitely signed the elements, since they have to be signed to work right + */ +typedef struct +{ + signed char forwardmove; /* *2048 for move */ + signed char sidemove; /* *2048 for move */ + signed short angleturn; /* <<16 for angle delta */ + short consistancy; /* checks for net game */ + byte chatchar; + byte buttons; +} ticcmd_t; + +#endif diff --git a/doom/src/pdoom/Doom/include/doom_iwad.h b/doom/src/pdoom/Doom/include/doom_iwad.h new file mode 100644 index 0000000..1381ff2 --- /dev/null +++ b/doom/src/pdoom/Doom/include/doom_iwad.h @@ -0,0 +1,7 @@ +#ifndef DOOM_IWAD_H +#define DOOM_IWAD_H + +extern const unsigned char *doom_iwad; +extern const unsigned int *p_doom_iwad_len; + +#endif // DOOM_IWAD_H diff --git a/doom/src/pdoom/Doom/include/doomdata.h b/doom/src/pdoom/Doom/include/doomdata.h new file mode 100644 index 0000000..c7961cb --- /dev/null +++ b/doom/src/pdoom/Doom/include/doomdata.h @@ -0,0 +1,227 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * all external data is defined here + * most of the data is loaded into different structures at run time + * some internal structures shared by many modules are here + * + *-----------------------------------------------------------------------------*/ + +#ifndef __DOOMDATA__ +#define __DOOMDATA__ + +// The most basic types we use, portability. +#include "config.h" +#include "doomtype.h" + +// +// Map level types. +// The following data structures define the persistent format +// used in the lumps of the WAD files. +// + +// Lump order in a map WAD: each map needs a couple of lumps +// to provide a complete scene geometry description. +enum +{ + ML_LABEL, // A separator, name, ExMx or MAPxx + ML_THINGS, // Monsters, items.. + ML_LINEDEFS, // LineDefs, from editing + ML_SIDEDEFS, // SideDefs, from editing + ML_VERTEXES, // Vertices, edited and BSP splits generated + ML_SEGS, // LineSegs, from LineDefs split by BSP + ML_SSECTORS, // SubSectors, list of LineSegs + ML_NODES, // BSP nodes + ML_SECTORS, // Sectors, from editing + ML_REJECT, // LUT, sector-sector visibility + ML_BLOCKMAP // LUT, motion clipping, walls/grid element +}; + +#ifdef _MSC_VER // proff: This is the same as __attribute__ ((packed)) in GNUC +#pragma pack(push) +#pragma pack(1) +#endif //_MSC_VER + +// A single Vertex. +typedef struct +{ + short x, y; +} PACKEDATTR mapvertex_t; + +// A SideDef, defining the visual appearance of a wall, +// by setting textures and offsets. +typedef struct +{ + short textureoffset; + short rowoffset; + short toptexture; + short bottomtexture; + short midtexture; + short sector; // Front sector, towards viewer. +} PACKEDATTR mapsidedef_t; + +// A LineDef, as used for editing, and as input to the BSP builder. + +typedef struct +{ + unsigned short v1; + unsigned short v2; + unsigned short flags; + short special; + short tag; + // proff 07/23/2006 - support more than 32768 sidedefs + // use the unsigned value and special case the -1 + // sidenum[1] will be -1 (NO_INDEX) if one sided + unsigned short sidenum[2]; +} PACKEDATTR maplinedef_t; + +#define NO_INDEX ((unsigned short)-1) + +// +// LineDef attributes. +// + +// Solid, is an obstacle. +#define ML_BLOCKING 1 + +// Blocks monsters only. +#define ML_BLOCKMONSTERS 2 + +// Backside will not be drawn if not two sided. +#define ML_TWOSIDED 4 + +// If a texture is pegged, the texture will have +// the end exposed to air held constant at the +// top or bottom of the texture (stairs or pulled +// down things) and will move with a height change +// of one of the neighbor sectors. +// Unpegged textures always have the first row of +// the texture at the top pixel of the line for both +// top and bottom textures (use next to windows). + +// upper texture unpegged +#define ML_DONTPEGTOP 8 + +// lower texture unpegged +#define ML_DONTPEGBOTTOM 16 + +// In AutoMap: don't map as two sided: IT'S A SECRET! +#define ML_SECRET 32 + +// Sound rendering: don't let sound cross two of these. +#define ML_SOUNDBLOCK 64 + +// Don't draw on the automap at all. +#define ML_DONTDRAW 128 + +// Set if already seen, thus drawn in automap. +#define ML_MAPPED 256 + +//jff 3/21/98 Set if line absorbs use by player +//allow multiple push/switch triggers to be used on one push +#define ML_PASSUSE 512 + +// Sector definition, from editing. +typedef struct +{ + short floorheight; + short ceilingheight; + char floorpic[8]; + char ceilingpic[8]; + short lightlevel; + short special; + short tag; +} PACKEDATTR mapsector_t; + +// SubSector, as generated by BSP. +typedef struct +{ + unsigned short numsegs; + unsigned short firstseg; // Index of first one; segs are stored sequentially. +} PACKEDATTR mapsubsector_t; + +// LineSeg, generated by splitting LineDefs +// using partition lines selected by BSP builder. +typedef struct +{ + unsigned short v1; + unsigned short v2; + short angle; + unsigned short linedef; + short side; + short offset; +} PACKEDATTR mapseg_t; + +// BSP node structure. + +// Indicate a leaf. +#define NF_SUBSECTOR 0x8000 + +// Thing definition, position, orientation and type, +// plus skill/visibility flags and attributes. +typedef struct +{ + short x; + short y; + short angle; + short type; + short options; +} PACKEDATTR mapthing_t; + +#ifdef _MSC_VER +#pragma pack(pop) +#endif //_MSC_VER + +//This is used at runtime so not packed. +//compiler uses byte access on packed structs. + +typedef struct +{ + short x; // Partition line from (x,y) to x+dx,y+dy) + short y; + short dx; + short dy; + // Bounding box for each child, clip against view frustum. + short bbox[2][4]; + // If NF_SUBSECTOR its a subsector, else it's a node of another subtree. + unsigned short children[2]; +} mapnode_t; + +#endif // __DOOMDATA__ diff --git a/doom/src/pdoom/Doom/include/doomdef.h b/doom/src/pdoom/Doom/include/doomdef.h new file mode 100644 index 0000000..478d61e --- /dev/null +++ b/doom/src/pdoom/Doom/include/doomdef.h @@ -0,0 +1,317 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Internally used data structures for virtually everything, + * key definitions, lots of other stuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __DOOMDEF__ +#define __DOOMDEF__ +#include "main.h" +/* use config.h if autoconf made one -- josh */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#define demo_compatibility 1 +// killough 4/25/98: Make gcc extensions mean nothing on other compilers +#ifndef __GNUC__ +#define __attribute__(x) +#endif + +// +#define YCOORD_DATATYPE signed short +// This must come first, since it redefines malloc(), free(), etc. -- killough: +#include "z_zone.h" + +#include +#include +#include +#include +#include +#include "printf.h" +// this should go here, not in makefile/configure.ac -- josh +#ifndef O_BINARY +#define O_BINARY 0 +#endif + +#include "m_swap.h" +#include "version.h" +#include "main.h" +#include "i_memory.h" +// +// +typedef unsigned angle_t; +// Game mode handling - identify IWAD version +// to handle IWAD dependend animations etc. +typedef enum +{ + shareware, // DOOM 1 shareware, E1, M9 + registered, // DOOM 1 registered, E3, M27 + commercial, // DOOM 2 retail, E1 M34 (DOOM 2 german edition not handled) + retail, // DOOM 1 retail, E4, M36 + indetermined // Well, no IWAD found. +} GameMode_t; + +// Mission packs - might be useful for TC stuff? +typedef enum +{ + doom, // DOOM 1 + doom2, // DOOM 2 + pack_tnt, // TNT mission pack + pack_plut, // Plutonia pack + none +} GameMission_t; + +// Identify language to use, software localization. +typedef enum +{ + english, french, german, unknown +} Language_t; + +// +// For resize of screen, at start of game. +// + +#define BASE_WIDTH 320 +#define BASE_HEIGHT 200 + +// It is educational but futile to change this +// scaling e.g. to 2. Drawing of status bar, +// menues etc. is tied to the scale implied +// by the graphics. + +#define INV_ASPECT_RATIO 0.625 /* 0.75, ideally */ + +// killough 2/8/98: MAX versions for maximum screen sizes +// allows us to avoid the overhead of dynamic allocation +// when multiple screen sizes are supported + +// proff 08/17/98: Changed for high-res + +#ifndef PDOOM_W +#define PDOOM_W 128 +#define PDOOM_H 128 +#endif +#define SCREENWIDTH_PHYSICAL PDOOM_W +#define MAX_SCREENHEIGHT PDOOM_H + +// SCREENWIDTH and SCREENHEIGHT define the visible size +#define HIGHRES +#ifdef HIGHRES +#define MAX_SCREENWIDTH (SCREENWIDTH_PHYSICAL) +#else +#define MAX_SCREENWIDTH (SCREENWIDTH_PHYSICAL/2) +#endif +#define SCREENWIDTH MAX_SCREENWIDTH + +#define SCREENHEIGHT MAX_SCREENHEIGHT +#define SCREENPITCH SCREENWIDTH //In pixels. +// SCREENPITCH is the size of one line in the buffer and +// can be bigger than the SCREENWIDTH depending on the size +// of one pixel (8, 16 or 32 bit) and the padding at the +// end of the line caused by hardware considerations + +// The maximum number of players, multiplayer/networking. +#define MAXPLAYERS 1 + +// phares 5/14/98: +// DOOM Editor Numbers (aka doomednum in mobj_t) + +#define DEN_PLAYER5 4001 +#define DEN_PLAYER6 4002 +#define DEN_PLAYER7 4003 +#define DEN_PLAYER8 4004 + +// State updates, number of tics / second. +#define TICRATE 35 + +// The current state of the game: whether we are playing, gazing +// at the intermission screen, the game final animation, or a demo. + +typedef enum +{ + GS_LEVEL, GS_INTERMISSION, GS_FINALE, GS_DEMOSCREEN +} gamestate_t; + +// +// Difficulty/skill settings/filters. +// +// These are Thing flags + +// Skill flags. +#define MTF_EASY 1 +#define MTF_NORMAL 2 +#define MTF_HARD 4 +// Deaf monsters/do not react to sound. +#define MTF_AMBUSH 8 + +/* killough 11/98 */ +#define MTF_NOTSINGLE 16 +#define MTF_NOTDM 32 +#define MTF_NOTCOOP 64 +#define MTF_FRIEND 128 +#define MTF_RESERVED 256 + +typedef enum +{ + sk_none = -1, //jff 3/24/98 create unpicked skill setting + sk_baby = 0, + sk_easy, + sk_medium, + sk_hard, + sk_nightmare +} skill_t; + +// +// Key cards. +// + +typedef enum +{ + it_bluecard, + it_yellowcard, + it_redcard, + it_blueskull, + it_yellowskull, + it_redskull, + NUMCARDS +} card_t; + +// The defined weapons, including a marker +// indicating user has not changed weapon. +typedef enum +{ + wp_fist, + wp_pistol, + wp_shotgun, + wp_chaingun, + wp_missile, + wp_plasma, + wp_bfg, + wp_chainsaw, + wp_supershotgun, + + NUMWEAPONS, + wp_nochange // No pending weapon change. +} weapontype_t; + +// Ammunition types defined. +typedef enum +{ + am_clip, // Pistol / chaingun ammo. + am_shell, // Shotgun / double barreled shotgun. + am_cell, // Plasma rifle, BFG. + am_misl, // Missile launcher. + NUMAMMO, + am_noammo // Unlimited for chainsaw / fist. +} ammotype_t; + +// Power up artifacts. +typedef enum +{ + pw_invulnerability, + pw_strength, + pw_invisibility, + pw_ironfeet, + pw_allmap, + pw_infrared, + NUMPOWERS +} powertype_t; + +// Power up durations (how many seconds till expiration). +typedef enum +{ + INVULNTICS = (30 * TICRATE), + INVISTICS = (60 * TICRATE), + INFRATICS = (120 * TICRATE), + IRONTICS = (60 * TICRATE) +} powerduration_t; +#include "keyboard.h" +// +#define KEYD_ALT 1 +#define KEYD_FIRE 2 +#define KEYD_USE 3 +#define KEYD_CHGW 4 +#define KEYD_CHGWDOWN 5 +#define KEYD_UP 6 +#define KEYD_DOWN 7 +#define KEYD_LEFT 8 +#define KEYD_RIGHT 9 +#define KEYD_SL 10 +#define KEYD_SR 11 +#define KEYD_MENU 12 +// +#define KEYD_MAP1 13 +#define KEYD_SPEED 14 + +// + +// phares 4/19/98: +// Defines Setup Screen groups that config variables appear in. +// Used when resetting the defaults for every item in a Setup group. + +typedef enum +{ + ss_none, + ss_keys, + ss_weap, + ss_stat, + ss_auto, + ss_enem, + ss_mess, + ss_chat, + ss_gen, /* killough 10/98 */ + ss_comp, /* killough 10/98 */ + ss_max +} ss_types; + +typedef YCOORD_DATATYPE ycoord_t; // +// phares 3/20/98: +// +// Player friction is variable, based on controlling +// linedefs. More friction can create mud, sludge, +// magnetized floors, etc. Less friction can create ice. + +#define MORE_FRICTION_MOMENTUM 15000 // mud factor based on momentum +#define ORIG_FRICTION 0xE800 // original value +#define ORIG_FRICTION_FACTOR 2048 // original value + +#endif // __DOOMDEF__ diff --git a/doom/src/pdoom/Doom/include/doomstat.h b/doom/src/pdoom/Doom/include/doomstat.h new file mode 100644 index 0000000..f009db9 --- /dev/null +++ b/doom/src/pdoom/Doom/include/doomstat.h @@ -0,0 +1,90 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * All the global variables that store the internal state. + * Theoretically speaking, the internal state of the engine + * should be found by looking at the variables collected + * here, and every relevant module will have to include + * this header file. + * In practice, things are a bit messy. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __D_STATE__ +#define __D_STATE__ + +// We need the playr data structure as well. + +#include "d_player.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +// ------------------------------------------- +// Selected skill type, map etc. +// + +// Defaults for menu, methinks. +extern const skill_t startskill; +extern const int startepisode; +extern const int startmap; + +// ------------------------- +// Status flags for refresh. +// + +enum automapmode_e +{ + am_active = 1, // currently shown + am_overlay = 2, // covers the screen, i.e. not overlay mode + am_rotate = 4, // rotates to the player facing direction + am_follow = 8, // keep the player centred + am_grid = 16, // show grid +}; +extern enum automapmode_e automapmode; // Mode that the automap is in + +//----------------------------------------- +// Internal parameters, used for engine. +// + +//----------------------------------------------------------------------------- + +#endif diff --git a/doom/src/pdoom/Doom/include/doomtype.h b/doom/src/pdoom/Doom/include/doomtype.h new file mode 100644 index 0000000..b23be14 --- /dev/null +++ b/doom/src/pdoom/Doom/include/doomtype.h @@ -0,0 +1,123 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Simple basic typedefs, isolated here to make it easier + * separating modules. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __DOOMTYPE__ +#define __DOOMTYPE__ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include +#ifndef __BYTEBOOL__ +#define __BYTEBOOL__ +/* Fixed to use builtin bool type with C++. */ +#if 0 + #ifdef __cplusplus + typedef bool boolean; + #else + typedef enum {false, true} boolean; + #endif +#else +// next-hack +//typedef enum {false, true} boolean_t; +typedef unsigned char boolean; +#endif +typedef unsigned char byte; +#endif +// 2021-02-13 next-hack. Each pointer is 4 bytes long, and we use a lot of them. +// But since we will have less than 256kB of RAM, and since pointers to struct, int +// other zmalloc'ed things are 4-bytes aligned, we can just use one unsigned short +// In this way, we save 2 bytes per each pointer. + +//e6y +#ifndef MAX +#define MAX(a,b) ((a)>(b)?(a):(b)) +#endif +#ifndef MIN +#define MIN(a,b) ((a)<(b)?(a):(b)) +#endif + +/* cph - Wrapper for the long long type, as Win32 used a different name. + * Except I don't know what to test as it's compiler specific + * Proff - I fixed it */ + +#ifdef __WINS__ + #define int_64_t __int64 + #define uint_64_t unsigned __int64 +#else +#define int_64_t long long +#define uint_64_t unsigned long long +#endif + +//typedef _int64 int_64_t; +//typedef unsigned _int64 uint_64_t; +// define compiled-specific long-long contstant notation here +#define LONGLONG(num) (uint_64_t)num +#undef PATH_MAX +#define PATH_MAX 1024 + +#ifdef __GNUC__ +#define CONSTFUNC +#define PUREFUNC +#define NORETURN __attribute__ ((noreturn)) +#else +#define CONSTFUNC +#define PUREFUNC +#define NORETURN +#endif + +/* CPhipps - use limits.h instead of depreciated values.h */ +#include + +/* cph - from v_video.h, needed by gl_struct.h */ +enum patch_translation_e +{ + VPT_NONE = 0, // Normal + VPT_FLIP = 1, // Flip image horizontally + VPT_TRANS = 2, // Translate image via a translation table + VPT_STRETCH = 4, // Stretch to compensate for high-res +}; + +#endif diff --git a/doom/src/pdoom/Doom/include/dstrings.h b/doom/src/pdoom/Doom/include/dstrings.h new file mode 100644 index 0000000..fee07ee --- /dev/null +++ b/doom/src/pdoom/Doom/include/dstrings.h @@ -0,0 +1,87 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * DOOM strings, by language. + * Note: In BOOM, some new strings have been defined that are + * not found in the French version. A better approach is + * to create a BEX text-replacement file for other + * languages since any language can be supported that way + * without recompiling the program. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __DSTRINGS__ +#define __DSTRINGS__ + +/* All important printed strings. + * Language selection (message strings). + * Use -DFRENCH etc. + */ + +#ifdef FRENCH +#include "d_french.h" +#else +#include "d_englsh.h" +#endif + +/* Note this is not externally modifiable through DEH/BEX + * Misc. other strings. + * #define SAVEGAMENAME "boomsav" * killough 3/22/98 * + * Ty 05/04/98 - replaced with a modifiable string, see d_deh.c + */ + +/* + * File locations, + * relative to current position. + * Path names are OS-sensitive. + */ +#define DEVMAPS "devmaps" +#define DEVDATA "devdata" + + +/* Not done in french? + * QuitDOOM messages * + * killough 1/18/98: + * replace hardcoded limit with extern var (silly hack, I know) + */ + +#include + +#endif diff --git a/doom/src/pdoom/Doom/include/f_finale.h b/doom/src/pdoom/Doom/include/f_finale.h new file mode 100644 index 0000000..a36b9a2 --- /dev/null +++ b/doom/src/pdoom/Doom/include/f_finale.h @@ -0,0 +1,66 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Related to f_finale.c, which is called at the end of a level + * + *-----------------------------------------------------------------------------*/ + +#ifndef __F_FINALE__ +#define __F_FINALE__ + +#include "doomtype.h" +#include "d_event.h" + +/* + * FINALE + */ + +/* Called by main loop. */ +boolean F_Responder(event_t *ev); + +/* Called by main loop. */ +void F_Ticker(void); + +/* Called by main loop. */ +void F_Drawer(void); + +void F_StartFinale(void); + +#endif diff --git a/doom/src/pdoom/Doom/include/f_wipe.h b/doom/src/pdoom/Doom/include/f_wipe.h new file mode 100644 index 0000000..eafa114 --- /dev/null +++ b/doom/src/pdoom/Doom/include/f_wipe.h @@ -0,0 +1,56 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Mission start screen wipe/melt, special effects. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __F_WIPE_H__ +#define __F_WIPE_H__ +#include +/* + * SCREEN WIPE PACKAGE + */ +void wipe_initMelt(short *y_lookup); +int wipe_ScreenWipe(int ticks, short *y_lookup); +int wipe_StartScreen(void); +int wipe_EndScreen(void); + +#endif diff --git a/doom/src/pdoom/Doom/include/g_game.h b/doom/src/pdoom/Doom/include/g_game.h new file mode 100644 index 0000000..b24213b --- /dev/null +++ b/doom/src/pdoom/Doom/include/g_game.h @@ -0,0 +1,156 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: Main game control interface. + *-----------------------------------------------------------------------------*/ + +#ifndef __G_GAME__ +#define __G_GAME__ + +#include "doomdef.h" +#include "d_event.h" +#include "d_ticcmd.h" + +// +// GAME +// + +// killough 5/2/98: number of bytes reserved for saving options +#define GAME_OPTION_SIZE 64 + +boolean G_Responder(event_t *ev); +boolean G_CheckDemoStatus(void); +void G_InitNew(skill_t skill, int episode, int map); +void G_DeferedInitNew(skill_t skill, int episode, int map); +void G_DeferedPlayDemo(const char *demo); // CPhipps - const +void G_LoadGame(int slot, boolean is_command); // killough 5/15/98 +void G_ForcedLoadGame(void); // killough 5/15/98: forced loadgames +void G_DoLoadGame(void); +void G_SaveGame(int slot, const char *description); // Called by M_Responder. +void G_ExitLevel(void); +void G_SecretExitLevel(void); +void G_WorldDone(void); +void G_EndGame(void); /* cph - make m_menu.c call a G_* function for this */ +void G_Ticker(void); +void G_ReloadDefaults(void); // killough 3/1/98: loads game defaults +void G_DoNewGame(void); +void G_DoReborn(int playernum); +void G_DoPlayDemo(void); +void G_DoCompleted(void); +void G_ReadDemoTiccmd(ticcmd_t *cmd); +void G_DoWorldDone(void); +void G_Compatibility(void); +const byte* G_ReadOptions(const byte *demo_p); /* killough 3/1/98 - cph: const byte* */ +void G_PlayerReborn(int player); +void G_RestartLevel(void); // CPhipps - menu involked level restart +void G_DoVictory(void); +void G_BuildTiccmd(ticcmd_t *cmd); // CPhipps - move decl to header +void G_MakeSpecialEvent(buttoncode_t bc, ...); /* cph - new event stuff */ + +void G_UpdateSaveGameStrings(); + +void G_LoadSettings(); +void G_SaveSettings(); + +// killough 5/2/98: moved from m_misc.c: + +extern const int key_right; +extern const int key_left; +extern const int key_up; +extern const int key_down; +extern const int key_menu_right; // phares 3/7/98 +extern const int key_menu_left; // | +extern const int key_menu_up; // V +extern const int key_menu_down; +extern const int key_menu_escape; // | +extern const int key_menu_enter; // phares 3/7/98 +extern const int key_strafeleft; +extern const int key_straferight; +extern const int key_fire; +extern const int key_use; +extern const int key_strafe; +extern const int key_speed; +extern const int key_escape; // phares +extern const int key_savegame; // | +extern const int key_loadgame; // V +extern const int key_reverse; +extern const int key_zoomin; +extern const int key_zoomout; +extern const int key_chat; +extern const int key_backspace; +extern const int key_enter; +extern const int key_help; +extern const int key_soundvolume; +extern const int key_hud; +extern const int key_quicksave; +extern const int key_endgame; +extern const int key_messages; +extern const int key_quickload; +extern const int key_quit; +extern const int key_gamma; +extern const int key_spy; +extern const int key_pause; +extern const int key_setup; +extern const int key_forward; +extern const int key_leftturn; +extern const int key_rightturn; +extern const int key_backward; +extern const int key_map_right; +extern const int key_map_left; +extern const int key_map_up; +extern const int key_map_down; +extern const int key_map_zoomin; +extern const int key_map_zoomout; +extern const int key_map; +extern const int key_map_gobig; +extern const int key_map_follow; +extern const int key_map_mark; // ^ +extern const int key_map_clear; // | +extern const int key_map_grid; // phares + +// killough 5/2/98: moved from d_deh.c: +// Par times (new item with BOOM) - from g_game.c +extern const int pars[4][10]; // hardcoded array size +extern const int cpars[32]; // hardcoded array size +// CPhipps - Make savedesciption visible in wider scope +#define SAVEDESCLEN 8 + +#define NUMKEYS 16 + +#endif diff --git a/doom/src/pdoom/Doom/include/global_data.h b/doom/src/pdoom/Doom/include/global_data.h new file mode 100644 index 0000000..2d4581a --- /dev/null +++ b/doom/src/pdoom/Doom/include/global_data.h @@ -0,0 +1,1640 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * global data collected by doomhack. + * Modified by next-hack, still a lot of optimization is required. + */ +#ifndef GLOBAL_DATA_H +#define GLOBAL_DATA_H + +#include "doomstat.h" +#include "doomdef.h" +#include "m_fixed.h" +#include "am_map.h" +#include "g_game.h" +#include "hu_lib.h" +#include "hu_stuff.h" +#include "r_defs.h" +#include "i_sound.h" +#include "m_menu.h" +#include "p_spec.h" +#include "p_enemy.h" +#include "p_map.h" +#include "p_maputl.h" + +#include "p_mobj.h" +#include "p_tick.h" + +#include "r_draw.h" +#include "r_main.h" +#include "r_plane.h" +#include "r_things.h" + +#include "s_sound.h" + +#include "st_lib.h" +#include "st_stuff.h" + +#include "v_video.h" + +#include "w_wad.h" + +#include "wi_stuff.h" +#include + +extern short draw_starty, draw_stopy; +extern const patch_t *hu_font[]; +extern intercept_t intercepts[MAXINTERCEPTS]; +extern boolean interceptIsALine[MAXINTERCEPTS]; +extern intercept_t *intercept_p; +// 2021/04/01 next-hack: still a lot to optimize here. +typedef struct globals_t +{ +#ifndef GLOBAL_DEFS_H +#define GLOBAL_DEFS_H + uint32_t *lumpSizes; // pointer to lump sizes + +//****************************************************************************** +//am_map.c +//****************************************************************************** + byte automapmode; // Mode that the automap is in + +// constant to 0... +// location of window on screen +// int f_x; = 0 +// int f_y; = 0 + +// size of window on screen +// int f_w; = SCREENWIDTH_PHYSICAL +// int f_h; = SCREENHEIGHT-ST_SCALED_HEIGHT + + mpoint_t m_paninc; // how far the window pans each tic (map coords) + + fixed_t m_x, m_y; // LL x,y window location on the map (map coords) + fixed_t m_x2, m_y2; // UR x,y window location on the map (map coords) + +// +// width/height of window on map (map coords) +// + fixed_t m_w; + fixed_t m_h; + +// based on level size + fixed_t min_x; + fixed_t min_y; + fixed_t max_x; + fixed_t max_y; + +//fixed_t max_w; // max_x-min_x, +//fixed_t max_h; // max_y-min_y + + fixed_t min_scale_mtof; // used to tell when to stop zooming out + fixed_t max_scale_mtof; // used to tell when to stop zooming in + +// old location used by the Follower routine + mpoint_t f_oldloc; + +// used by MTOF to scale from map-to-frame-buffer coords + fixed_t scale_mtof; +// used by FTOM to scale from frame-buffer-to-map coords (=1/scale_mtof) + fixed_t scale_ftom; + +//int lastlevel, lastepisode; + uint8_t lastlevel, lastepisode; + + boolean stopped; + + fixed_t mtof_zoommul; // how far the window zooms each tic (map coords) + fixed_t ftom_zoommul; // how far the window zooms each tic (fb coords) + +//****************************************************************************** +//d_client.c +//****************************************************************************** + + ticcmd_t netcmd; + int maketic; + int lastmadetic; + +//****************************************************************************** +//d_main.c +//****************************************************************************** + + short pagetic; + short pagelump; // CPhipps - const + + unsigned int fps_timebefore; + unsigned int fps_frames; + unsigned short fps_framerate; + +// wipegamestate can be set to -1 to force a wipe on the next draw + signed char wipegamestate; + signed char oldgamestate; + + byte demosequence; // killough 5/2/98: made static + + boolean singletics; // debug flag to cancel adaptiveness + boolean advancedemo; + + byte gamma; + + boolean fps_show; + +//****************************************************************************** +//doomstat.c +//****************************************************************************** + +// Game Mode - identify IWAD as shareware, retail etc. + byte gamemode; + byte gamemission; + +//****************************************************************************** +//f_finale.c +//****************************************************************************** + + int castnum; + int casttics; + const state_t *caststate; + int castframes; + int castonmelee; + + const char *finaletext; // cph - + const char *finaleflat; // made static const + short finalecount; // made static + +// Stage of animation: +// 0 = text, 1 = art screen, 2 = character cast + byte finalestage; // cph - + + byte midstage; // whether we're in "mid-stage" + byte laststage; + + boolean castattacking; + boolean castdeath; + +//****************************************************************************** +//f_wipe.c +//****************************************************************************** + + int wipe_tick; + +//****************************************************************************** +//g_game.c +//****************************************************************************** + + const byte *demobuffer; /* cph - only used for playback */ + int demolength; // check for overrun (missing DEMOMARKER) + + const byte *demo_p; + + wbstartstruct_t wminfo; // parms for world map / intermission + + player_t player; + + int starttime; // for comparative timing purposes + int totalleveltimes; // CPhipps - total time for all completed levels + int longtics; + int gametic; + int basetic; /* killough 9/29/98: for demo sync */ + short totalkills, totallive, totalitems, totalsecret; // for intermission + short totalstatic; + + byte gameaction; + byte gamestate; + byte gameskill; + + uint8_t gameepisode; + uint8_t gamemap; + + uint8_t demover; + +// CPhipps - made lots of key/button state vars static + boolean gamekeydown[NUMKEYS]; + byte turnheld; // for accelerative turning + +// Game events info + byte special_event; // Event triggered by local player, to send + + byte prevgamestate; + + byte d_skill; + uint8_t d_episode; + uint8_t d_map; + + byte savegameslot; // Slot to load if gameaction == ga_loadgame + + boolean secretexit; + + boolean respawnmonsters; + boolean paused; +// CPhipps - moved *_loadgame vars here + boolean command_loadgame; + + boolean usergame; // ok to save / end game + boolean timingdemo; // if true, exit with report on completion + boolean playeringame; + boolean demoplayback; + boolean singledemo; // quit after playing a demo from cmdline + boolean haswolflevels; // jff 4/18/98 wolf levels present + +//****************************************************************************** +//hu_stuff.c +//****************************************************************************** + +// widgets + hu_textline_t w_title; + hu_stext_t w_message; + uint8_t message_counter; + + boolean message_on; + boolean message_dontfuckwithme; + boolean headsupactive; + +//****************************************************************************** +//i_audio.c +//****************************************************************************** + + boolean sound_inited; + + uint8_t music_looping; + uint8_t music_volume; + uint8_t music_init; + +//int lasttimereply; + unsigned int basetime; + +//****************************************************************************** +//i_video.c +//****************************************************************************** + + unsigned short *current_palette; +//const unsigned char* palette_lump; + uint8_t newpal; + +//****************************************************************************** +//m_cheat.c +//****************************************************************************** + + unsigned int cheat_buffer; + +//****************************************************************************** +//m_menu.c +//****************************************************************************** + +// +// defaulted values +// + boolean showMessages; // Show messages has default, 0 = off, 1 = on + + boolean alwaysRun; + + boolean messageToPrint; // 1 = message to be printed + + uint8_t messageLastMenuActive; + + uint8_t saveSlot; // which slot to save in +// old save description before edit + + uint8_t epi; + + uint8_t itemOn; // menu item skull is on (for Big Font menus) + uint8_t skullAnimCounter; // skull animation counter + uint8_t whichSkull; // which skull to draw (he blinks) + + boolean menuactive; // The menus are up + boolean messageNeedsInput; // timed message = no input from user + +//****************************************************************************** +//m_random.c +//****************************************************************************** + + uint8_t rndindex; + uint8_t prndindex; + +//****************************************************************************** +//p_ceiling.c +//****************************************************************************** + +// the list of ceilings moving currently, including crushers + ceilinglist_t *activeceilings; + +//****************************************************************************** +//p_enemy.c +//****************************************************************************** + + mobj_t *current_actor; + + fixed_t dropoff_deltax, dropoff_deltay, floorz; + +//int current_allaround; + + mobj_t *corpsehit; + fixed_t viletryx; + fixed_t viletryy; + +// killough 2/7/98: Remove limit on icon landings: + mobj_t **braintargets; + short numbraintargets_alloc; + short numbraintargets; + + brain_t brain; // killough 3/26/98: global state of boss brain + +//****************************************************************************** +//p_map.c +//****************************************************************************** + + /* killough 8/2/98: for more intelligent autoaiming */ + uint_64_t aim_flags_mask; + + mobj_t *tmthing; + fixed_t tmx; + fixed_t tmy; + + int pe_x; // Pain Elemental position for Lost Soul checks // phares + int pe_y; // Pain Elemental position for Lost Soul checks // phares + int ls_x; // Lost Soul position for Lost Soul checks // phares + int ls_y; // Lost Soul position for Lost Soul checks // phares + +// The tm* items are used to hold information globally, usually for +// line or object intersection checking + + fixed_t tmbbox[4]; // bounding box for line intersection checks + fixed_t tmfloorz; // floor you'd hit if free to fall + fixed_t tmceilingz; // ceiling of sector you're in + fixed_t tmdropoffz; // dropoff on other side of line you're crossing + +// keep track of the line that lowers the ceiling, +// so missiles don't explode against sky hack walls + + const line_t *ceilingline; + const line_t *blockline; /* killough 8/11/98: blocking linedef */ + const line_t *floorline; /* killough 8/1/98: Highest touched floor */ + int tmunstuck; /* killough 8/1/98: whether to allow unsticking */ + +// keep track of special lines as they are hit, +// but don't process them until the move is proven valid + +// 1/11/98 killough: removed limit on special lines crossed + const line_t *spechit[4]; // new code -- killough + +// Temporary holder for thing_sectorlist threads + msecnode_t *sector_list; // phares 3/16/98 + + /* killough 8/2/98: make variables static */ + fixed_t bestslidefrac; + const line_t *bestslideline; + mobj_t *slidemo; + fixed_t tmxmove; + fixed_t tmymove; + + mobj_t *linetarget; // who got hit (or NULL) + mobj_t *shootthing; + +// Height if not aiming up or down + fixed_t shootz; + + int la_damage; + fixed_t attackrange; + + fixed_t aimslope; + +// slopes to top and bottom of target +// killough 4/20/98: make static instead of using ones in p_sight.c + + fixed_t topslope; + fixed_t bottomslope; + + mobj_t *bombsource, *bombspot; + int bombdamage; + + mobj_t *usething; + + short numspechit; + +// If "floatok" true, move would be ok +// if within "tmfloorz - tmceilingz". + boolean floatok; + + /* killough 11/98: if "felldown" true, object was pushed down ledge */ + boolean felldown; + + boolean crushchange, nofit; + + boolean telefrag; /* killough 8/9/98: whether to telefrag at exit */ + +//****************************************************************************** +//p_maputl.c +//****************************************************************************** + + fixed_t opentop; + fixed_t openbottom; + fixed_t openrange; + fixed_t lowfloor; + +// moved front and back outside P-LineOpening and changed // phares 3/7/98 +// them to these so we can pick up the new friction value +// in PIT_CheckLine() + sector_t *openfrontsector; // made global // phares + sector_t *openbacksector; // made global + + divline_t trace; + +//****************************************************************************** +//p_mobj.c +//****************************************************************************** + +//****************************************************************************** +//p_plats.c +//****************************************************************************** + +//****************************************************************************** +//p_pspr.c +//****************************************************************************** + + fixed_t bulletslope; + +//****************************************************************************** +//p_setup.c +//****************************************************************************** + +// +// MAP related Lookup tables. +// Store VERTEXES, LINEDEFS, SIDEDEFS, etc. +// + const vertex_t *vertexes; + const seg_t *segs; + sector_t *sectors; + subsector_t *subsectors; + + short numvertexes; + + short numsegs; + + short numsectors; + + short numsubsectors; + + short numsides; + short numlines; + + const line_t *lines; + linedata_t *linedata; + + side_t *sides; + byte *textureoffsets; // 2021-02-13 next-hack: added this to avoid storing the whole side structure to ram. +// 2021-08-07 next-hack: to support full DOOM we need uint16_t and not only bytes. We still have ram + uint16_t *linesChangeableTextureIndex; // 2021-03-13: forgot that switches have changeable textures... + uint16_t *switch_texture_top; + uint16_t *switch_texture_mid; + uint16_t *switch_texture_bot; + +// BLOCKMAP +// Created from axis aligned bounding box +// of the map, a rectangular array of +// blocks of size ... +// Used to speed up collision detection +// by spatial subdivision in 2D. +// +// Blockmap size. + + short bmapwidth, bmapheight; // size in mapblocks + +// killough 3/1/98: remove blockmap limit internally: + const short *blockmap; // was short -- killough + +// offsets in blockmap are from here + const short *blockmaplump; // was short -- killough + + fixed_t bmaporgx, bmaporgy; // origin of block map + +//mobj_t **blocklinks; // for thing chains + unsigned short *blocklinks_sptrs; +// +// REJECT +// For fast sight rejection. +// Speeds up enemy AI by skipping detailed +// LineOf Sight calculation. +// Without the special effect, this could +// be used as a PVS lookup as well. +// + +//int rejectlump;// cph - store reject lump num if cached + const byte *rejectmatrix; // cph - const* + +// Maintain single and multi player starting spots. + mapthing_t playerstarts[MAXPLAYERS]; + +//****************************************************************************** +//p_sight.c +//****************************************************************************** + +//****************************************************************************** +//p_spec.c +//****************************************************************************** + + anim_t *lastanim; + anim_t anims[MAXANIMS]; + + pusher_t *tmpusher; // pusher structure for blockmap searches + +//****************************************************************************** +//p_switch.c +//****************************************************************************** + button_t buttonlist[MAXBUTTONS]; + + short numswitches; // killough + +//****************************************************************************** +//p_tick.c +//****************************************************************************** + + int leveltime; // tics in game play for par + +// killough 8/29/98: we maintain several separate threads, each containing +// a special class of thinkers, to allow more efficient searches. + thinker_t thinkerclasscap[th_all + 1]; + +//****************************************************************************** +//r_bsp.c +//****************************************************************************** + +//****************************************************************************** +//r_data.c +//****************************************************************************** + char tex_lookup_last_name[8]; // added full string + + short firstflat, lastflat, numflats; + short firstspritelump, lastspritelump, numspritelumps; + short numtextures; + +//Store last lookup and return that if they match. + short tex_lookup_last_num; + boolean tex_lookup_valid; + +//****************************************************************************** +//p_user.c +//****************************************************************************** + + boolean onground; // whether player is on ground or in air + +//****************************************************************************** +//r_draw.c +//****************************************************************************** + + uint8_t fuzzpos; + +//****************************************************************************** +//r_draw.c +//****************************************************************************** +// next-hack: all validcounts can be unsigned short + unsigned short validcount; // increment every time a check is made + + player_t *viewplayer; + +// killough 3/20/98, 4/4/98: end dynamic colormaps + +//****************************************************************************** +//r_patch.c +//****************************************************************************** + +//****************************************************************************** +//r_plane.c +//****************************************************************************** + + visplane_t *visplanes[MAXVISPLANES]; // killough + visplane_t *freetail; // killough + visplane_t **freehead; // killough + +// Clip values are the solid pixel bounding the range. +// floorclip starts out SCREENHEIGHT +// ceilingclip starts out -1 + +// killough 2/8/98: make variables static + +//****************************************************************************** +//r_segs.c +//****************************************************************************** + +// +// regular wall +// + drawseg_t drawsegs[MAXDRAWSEGS]; // about 4.6k + short *lastopening; + +//****************************************************************************** +//r_sky.c +//****************************************************************************** + +// +// sky mapping +// + short skyflatnum; + short skytexture; + +//****************************************************************************** +//r_things.c +//****************************************************************************** + +// variables used to look up and range check thing_t sprites patches + +//spritedef_t *sprites; +//int numsprites; + +// why do we need this one? +//spriteframe_t sprtemp[MAX_SPRITE_FRAMES]; + short maxframe; // nh + vissprite_t vissprites[MAXVISSPRITES]; // size: 40 * MAXVISSPRITES +//vissprite_t* vissprite_ptrs[MAXVISSPRITES*2]; // killough + uint8_t vissprite_indexes[MAXVISSPRITES * 2]; // 2021-02-13 next-hack bytes are smaller... + +//****************************************************************************** +//st_stuff.c +//****************************************************************************** + +// main player in game + player_t *plyr; + + +// health widget + st_percent_t st_health; + +// ready-weapon widget + st_number_t w_ready; + + +// weapon ownership widgets + st_multicon_t w_arms[6]; + +// face status widget + st_multicon_t w_faces; + +// keycard widgets + st_multicon_t w_keyboxes[3]; + +// ammo widgets + st_number_t w_ammo[4]; + +// max ammo widgets + st_number_t w_maxammo[4]; + +// armor widget + st_percent_t st_armor; + +// used to use appopriately pained face + short st_oldhealth; + +// used for evil grin + boolean oldweaponsowned[NUMWEAPONS]; + + // count until face changes + short st_facecount; + +// current face index, used by w_faces + short st_faceindex; + +// holds key-type for each key box on bar + short keyboxes[3]; + +// a random number per tick + uint8_t st_randomnumber; + + uint8_t st_palette; + + uint8_t st_needrefresh; + +//****************************************************************************** +//v_video.c +//****************************************************************************** + +// Each screen is [SCREENWIDTH*SCREENHEIGHT]; // 2021-02-13 next-hack: actually no, we use a quarter of the buffer, to save ram + + screeninfo_t screens[NUM_SCREENS]; + +//****************************************************************************** +//wi_stuff.c +//****************************************************************************** + + // specifies current state + stateenum_t state; + +// contains information passed into intermission + wbstartstruct_t *wbs; + + wbplayerstruct_t *plrs; // wbs->plyr[] + + int cnt_time; + int cnt_total_time; + int cnt_par; + int cnt_pause; + +// 0-9 graphic + const patch_t *num[10]; + + short cnt_kills; + short cnt_items; + short cnt_secret; + +// used for general timing + uint8_t cnt; + +// used for timing of background animation + uint8_t bcnt; +// + uint8_t sp_state; +// wbs->pnum + uint8_t me; + +//****************************************************************************** +//w_wad.c +//****************************************************************************** + + short numlumps; // killough + + boolean snl_pointeron; +// used to accelerate or skip a stage + boolean acceleratestage; // killough 3/28/98: made global +// whether left-side main status bar is active + boolean st_statusbaron; + +//****************************************************************************** +//s_sound.c +//****************************************************************************** + +// the set of channels available + channel_t *channels; + +// These are not used, but should be (menu). +// Maximum volume of a sound effect. +// Internal default is max out of 0-15. + unsigned char snd_SfxVolume; // int + +// Maximum volume of music. Useless so far. + unsigned char snd_MusicVolume; // int + +// music currently being played + unsigned char mus_playing; + +//jff 3/17/98 to keep track of last IDMUS specified music num + signed char idmusnum; // v0.2.5: char is unsigned on ARM, -1 became 255 + +// whether songs are mus_paused + boolean mus_paused; + +//****************************************************************************** +#endif // GLOBAL_DEFS_H + +} globals_t; + +#if 0 +typedef struct globals_t +{ +#ifndef GLOBAL_DEFS_H +#define GLOBAL_DEFS_H + +//****************************************************************************** +//am_map.c +//****************************************************************************** + +enum automapmode_e automapmode; // Mode that the automap is in + +// location of window on screen +int f_x; +int f_y; + +// size of window on screen +int f_w; +int f_h; + +mpoint_t m_paninc; // how far the window pans each tic (map coords) + +fixed_t m_x, m_y; // LL x,y window location on the map (map coords) +fixed_t m_x2, m_y2; // UR x,y window location on the map (map coords) + +// +// width/height of window on map (map coords) +// +fixed_t m_w; +fixed_t m_h; + +// based on level size +fixed_t min_x; +fixed_t min_y; +fixed_t max_x; +fixed_t max_y; + +fixed_t max_w; // max_x-min_x, +fixed_t max_h; // max_y-min_y + +fixed_t min_scale_mtof; // used to tell when to stop zooming out +fixed_t max_scale_mtof; // used to tell when to stop zooming in + +// old location used by the Follower routine +mpoint_t f_oldloc; + +// used by MTOF to scale from map-to-frame-buffer coords +fixed_t scale_mtof; +// used by FTOM to scale from frame-buffer-to-map coords (=1/scale_mtof) +fixed_t scale_ftom; + +int lastlevel, lastepisode; + +boolean stopped; + +fixed_t mtof_zoommul; // how far the window zooms each tic (map coords) +fixed_t ftom_zoommul; // how far the window zooms each tic (fb coords) + +//****************************************************************************** +//d_client.c +//****************************************************************************** + +ticcmd_t netcmd; +int maketic; +int lastmadetic; + +//****************************************************************************** +//d_main.c +//****************************************************************************** + +// wipegamestate can be set to -1 to force a wipe on the next draw +gamestate_t wipegamestate; +gamestate_t oldgamestate; + +int demosequence; // killough 5/2/98: made static +int pagetic; +int pagelump; // CPhipps - const + +boolean singletics; // debug flag to cancel adaptiveness +boolean advancedemo; + +unsigned int gamma; + +//fps counter stuff + +unsigned int fps_timebefore; +unsigned int fps_frames; +unsigned int fps_framerate; +boolean fps_show; + +//****************************************************************************** +//doomstat.c +//****************************************************************************** + +// Game Mode - identify IWAD as shareware, retail etc. +GameMode_t gamemode; +GameMission_t gamemission; + + +//****************************************************************************** +//f_finale.c +//****************************************************************************** + + +// Stage of animation: +// 0 = text, 1 = art screen, 2 = character cast +int finalestage; // cph - +int finalecount; // made static +const char* finaletext; // cph - +const char* finaleflat; // made static const + +int castnum; +int casttics; +const state_t* caststate; +int castframes; +int castonmelee; + + +int midstage; // whether we're in "mid-stage" +int laststage; + +boolean castattacking; +boolean castdeath; + +//****************************************************************************** +//f_wipe.c +//****************************************************************************** + +int wipe_tick; + +//****************************************************************************** +//g_game.c +//****************************************************************************** + +const byte *demobuffer; /* cph - only used for playback */ +int demolength; // check for overrun (missing DEMOMARKER) + +const byte *demo_p; + +gameaction_t gameaction; +gamestate_t gamestate; +skill_t gameskill; + +int gameepisode; +int gamemap; + +player_t player; + +int starttime; // for comparative timing purposes + +int gametic; +int basetic; /* killough 9/29/98: for demo sync */ +int totalkills, totallive, totalitems, totalsecret; // for intermission +int demover; +wbstartstruct_t wminfo; // parms for world map / intermission +int totalleveltimes; // CPhipps - total time for all completed levels +int longtics; + + +// CPhipps - made lots of key/button state vars static +boolean gamekeydown[NUMKEYS]; +int turnheld; // for accelerative turning + +// Game events info +buttoncode_t special_event; // Event triggered by local player, to send + +gamestate_t prevgamestate; + +skill_t d_skill; +int d_episode; +int d_map; + +byte savegameslot; // Slot to load if gameaction == ga_loadgame + + +boolean secretexit; + +boolean respawnmonsters; +boolean paused; +// CPhipps - moved *_loadgame vars here +boolean command_loadgame; + +boolean usergame; // ok to save / end game +boolean timingdemo; // if true, exit with report on completion +boolean playeringame; +boolean demoplayback; +boolean singledemo; // quit after playing a demo from cmdline +boolean haswolflevels;// jff 4/18/98 wolf levels present + + +//****************************************************************************** +//hu_stuff.c +//****************************************************************************** + +// font sets +const patch_t* hu_font[HU_FONTSIZE]; + +// widgets +hu_textline_t w_title; +hu_stext_t w_message; +int message_counter; + +boolean message_on; +boolean message_dontfuckwithme; +boolean headsupactive; + +//****************************************************************************** +//i_audio.c +//****************************************************************************** + +boolean sound_inited; + +unsigned int music_looping; +unsigned int music_volume; +unsigned int music_init; + +//int lasttimereply; +unsigned int basetime; + + + +//****************************************************************************** +//i_video.c +//****************************************************************************** + +const unsigned char* current_palette; +const unsigned char* palette_lump; +int newpal; + +//****************************************************************************** +//m_cheat.c +//****************************************************************************** + +unsigned int cheat_buffer; + +//****************************************************************************** +//m_menu.c +//****************************************************************************** + +// +// defaulted values +// +boolean showMessages; // Show messages has default, 0 = off, 1 = on + +boolean alwaysRun; + +boolean messageToPrint; // 1 = message to be printed + +// CPhipps - static const +const char* messageString; // ...and here is the message string! + +int messageLastMenuActive; + +int saveSlot; // which slot to save in +// old save description before edit + +const menu_t* currentMenu; // current menudef + +int epi; + +short itemOn; // menu item skull is on (for Big Font menus) +short skullAnimCounter; // skull animation counter +short whichSkull; // which skull to draw (he blinks) + +boolean menuactive; // The menus are up +boolean messageNeedsInput; // timed message = no input from user + +char savegamestrings[8][8]; + + +//****************************************************************************** +//m_random.c +//****************************************************************************** + +int rndindex; +int prndindex; + + +//****************************************************************************** +//p_ceiling.c +//****************************************************************************** + +// the list of ceilings moving currently, including crushers +ceilinglist_t *activeceilings; + +//****************************************************************************** +//p_enemy.c +//****************************************************************************** + +mobj_t *current_actor; + +fixed_t dropoff_deltax, dropoff_deltay, floorz; + +int current_allaround; + +mobj_t* corpsehit; +fixed_t viletryx; +fixed_t viletryy; + +// killough 2/7/98: Remove limit on icon landings: +mobj_t **braintargets; +int numbraintargets_alloc; +int numbraintargets; + +brain_t brain; // killough 3/26/98: global state of boss brain + +//****************************************************************************** +//p_map.c +//****************************************************************************** + +/* killough 8/2/98: for more intelligent autoaiming */ +uint_64_t aim_flags_mask; + +mobj_t *tmthing; +fixed_t tmx; +fixed_t tmy; + +int pe_x; // Pain Elemental position for Lost Soul checks // phares +int pe_y; // Pain Elemental position for Lost Soul checks // phares +int ls_x; // Lost Soul position for Lost Soul checks // phares +int ls_y; // Lost Soul position for Lost Soul checks // phares + +// The tm* items are used to hold information globally, usually for +// line or object intersection checking + +fixed_t tmbbox[4]; // bounding box for line intersection checks +fixed_t tmfloorz; // floor you'd hit if free to fall +fixed_t tmceilingz; // ceiling of sector you're in +fixed_t tmdropoffz; // dropoff on other side of line you're crossing + +// keep track of the line that lowers the ceiling, +// so missiles don't explode against sky hack walls + +const line_t *ceilingline; +const line_t *blockline; /* killough 8/11/98: blocking linedef */ +const line_t *floorline; /* killough 8/1/98: Highest touched floor */ +int tmunstuck; /* killough 8/1/98: whether to allow unsticking */ + +// keep track of special lines as they are hit, +// but don't process them until the move is proven valid + +// 1/11/98 killough: removed limit on special lines crossed +const line_t *spechit[4]; // new code -- killough + +int numspechit; + +// Temporary holder for thing_sectorlist threads +msecnode_t* sector_list; // phares 3/16/98 + +/* killough 8/2/98: make variables static */ +fixed_t bestslidefrac; +const line_t* bestslideline; +mobj_t* slidemo; +fixed_t tmxmove; +fixed_t tmymove; + +mobj_t* linetarget; // who got hit (or NULL) +mobj_t* shootthing; + +// Height if not aiming up or down +fixed_t shootz; + +int la_damage; +fixed_t attackrange; + +fixed_t aimslope; + +// slopes to top and bottom of target +// killough 4/20/98: make static instead of using ones in p_sight.c + +fixed_t topslope; +fixed_t bottomslope; + +mobj_t *bombsource, *bombspot; +int bombdamage; + +mobj_t* usething; + +// If "floatok" true, move would be ok +// if within "tmfloorz - tmceilingz". +boolean floatok; + +/* killough 11/98: if "felldown" true, object was pushed down ledge */ +boolean felldown; + +boolean crushchange, nofit; + +boolean telefrag; /* killough 8/9/98: whether to telefrag at exit */ + + + +//****************************************************************************** +//p_maputl.c +//****************************************************************************** + +fixed_t opentop; +fixed_t openbottom; +fixed_t openrange; +fixed_t lowfloor; + +// moved front and back outside P-LineOpening and changed // phares 3/7/98 +// them to these so we can pick up the new friction value +// in PIT_CheckLine() +sector_t *openfrontsector; // made global // phares +sector_t *openbacksector; // made global + +divline_t trace; + + +// 1/11/98 killough: Intercept limit removed +intercept_t intercepts[MAXINTERCEPTS]; +intercept_t* intercept_p; + +//****************************************************************************** +//p_mobj.c +//****************************************************************************** + +//****************************************************************************** +//p_plats.c +//****************************************************************************** + +platlist_t *activeplats; // killough 2/14/98: made global again + + +//****************************************************************************** +//p_pspr.c +//****************************************************************************** + +fixed_t bulletslope; + +//****************************************************************************** +//p_setup.c +//****************************************************************************** + + +// +// MAP related Lookup tables. +// Store VERTEXES, LINEDEFS, SIDEDEFS, etc. +// + +int numvertexes; +const vertex_t *vertexes; + +int numsegs; +const seg_t *segs; + +int numsectors; +sector_t *sectors; + + +int numsubsectors; +subsector_t *subsectors; + + + +int numlines; +const line_t *lines; +linedata_t* linedata; + + +int numsides; +side_t *sides; + +// BLOCKMAP +// Created from axis aligned bounding box +// of the map, a rectangular array of +// blocks of size ... +// Used to speed up collision detection +// by spatial subdivision in 2D. +// +// Blockmap size. + +int bmapwidth, bmapheight; // size in mapblocks + +// killough 3/1/98: remove blockmap limit internally: +const short *blockmap; // was short -- killough + +// offsets in blockmap are from here +const short *blockmaplump; // was short -- killough + +fixed_t bmaporgx, bmaporgy; // origin of block map + +mobj_t **blocklinks; // for thing chains + +// +// REJECT +// For fast sight rejection. +// Speeds up enemy AI by skipping detailed +// LineOf Sight calculation. +// Without the special effect, this could +// be used as a PVS lookup as well. +// + +int rejectlump;// cph - store reject lump num if cached +const byte *rejectmatrix; // cph - const* + +// Maintain single and multi player starting spots. +mapthing_t playerstarts[MAXPLAYERS]; + + +//****************************************************************************** +//p_sight.c +//****************************************************************************** + +los_t los; // cph - made static + +//****************************************************************************** +//p_spec.c +//****************************************************************************** + +anim_t* lastanim; +anim_t anims[MAXANIMS]; + +pusher_t* tmpusher; // pusher structure for blockmap searches + + +//****************************************************************************** +//p_switch.c +//****************************************************************************** + +short switchlist[MAXSWITCHES * 2]; +int numswitches; // killough + +button_t buttonlist[MAXBUTTONS]; + + +//****************************************************************************** +//p_tick.c +//****************************************************************************** + +int leveltime; // tics in game play for par + +// killough 8/29/98: we maintain several separate threads, each containing +// a special class of thinkers, to allow more efficient searches. +thinker_t thinkerclasscap[th_all+1]; + +//****************************************************************************** +//p_user.c +//****************************************************************************** + +boolean onground; // whether player is on ground or in air + + +//****************************************************************************** +//r_bsp.c +//****************************************************************************** + + +//****************************************************************************** +//r_data.c +//****************************************************************************** + +int firstflat, lastflat, numflats; +int firstspritelump, lastspritelump, numspritelumps; +int numtextures; + +//Store last lookup and return that if they match. +const char* tex_lookup_last_name; +int tex_lookup_last_num; + + +//****************************************************************************** +//r_draw.c +//****************************************************************************** + + +int fuzzpos; + +//****************************************************************************** +//r_draw.c +//****************************************************************************** + +unsigned short validcount; // increment every time a check is made + + + +player_t *viewplayer; + +// killough 3/20/98, 4/4/98: end dynamic colormaps + + + +//****************************************************************************** +//r_patch.c +//****************************************************************************** + + +//****************************************************************************** +//r_plane.c +//****************************************************************************** + +visplane_t *visplanes[MAXVISPLANES]; // killough +visplane_t *freetail; // killough +visplane_t **freehead; // killough + + + +// Clip values are the solid pixel bounding the range. +// floorclip starts out SCREENHEIGHT +// ceilingclip starts out -1 + + +// killough 2/8/98: make variables static + + + +//****************************************************************************** +//r_segs.c +//****************************************************************************** + +// +// regular wall +// +drawseg_t drawsegs[MAXDRAWSEGS]; + +short openings[MAXOPENINGS]; +short* lastopening; + + + +//****************************************************************************** +//r_sky.c +//****************************************************************************** + +// +// sky mapping +// +int skyflatnum; +int skytexture; + + +//****************************************************************************** +//r_things.c +//****************************************************************************** + +// variables used to look up and range check thing_t sprites patches + +spritedef_t *sprites; +int numsprites; + + +spriteframe_t sprtemp[MAX_SPRITE_FRAMES]; +int maxframe; + +vissprite_t vissprites[MAXVISSPRITES]; +vissprite_t* vissprite_ptrs[MAXVISSPRITES*2]; // killough + + + +//****************************************************************************** +//s_sound.c +//****************************************************************************** + +// the set of channels available +channel_t *channels; + +// These are not used, but should be (menu). +// Maximum volume of a sound effect. +// Internal default is max out of 0-15. +int snd_SfxVolume; + +// Maximum volume of music. Useless so far. +int snd_MusicVolume; + +// music currently being played +int mus_playing; + +//jff 3/17/98 to keep track of last IDMUS specified music num +int idmusnum; + +// whether songs are mus_paused +boolean mus_paused; + +//****************************************************************************** +//st_stuff.c +//****************************************************************************** + +// main player in game +player_t *plyr; + + +unsigned int st_needrefresh; + +// 0-9, tall numbers +const patch_t* tallnum[10]; + +// 0-9, short, yellow (,different!) numbers +const patch_t* shortnum[10]; + +// tall % sign +const patch_t* tallpercent; + +const patch_t* keys[NUMCARDS]; + +// face status patches +const patch_t* faces[ST_NUMFACES]; + +//e6y: status bar background +const patch_t* stbarbg; +unsigned int stbar_len; + + +// weapon ownership patches +const patch_t* arms[6][2]; + +// ready-weapon widget +st_number_t w_ready; + +// health widget +st_percent_t st_health; + +// weapon ownership widgets +st_multicon_t w_arms[6]; + +// face status widget +st_multicon_t w_faces; + +// keycard widgets +st_multicon_t w_keyboxes[3]; + +// ammo widgets +st_number_t w_ammo[4]; + +// max ammo widgets +st_number_t w_maxammo[4]; + +// armor widget +st_percent_t st_armor; + +// used to use appopriately pained face +int st_oldhealth; + +// used for evil grin +boolean oldweaponsowned[NUMWEAPONS]; + + // count until face changes +int st_facecount; + +// current face index, used by w_faces +int st_faceindex; + +// holds key-type for each key box on bar +int keyboxes[3]; + +// a random number per tick +int st_randomnumber; + +int st_palette; + +// whether left-side main status bar is active +boolean st_statusbaron; + +//****************************************************************************** +//v_video.c +//****************************************************************************** + +// Each screen is [SCREENWIDTH*SCREENHEIGHT]; +screeninfo_t screens[NUM_SCREENS]; + +//****************************************************************************** +//w_wad.c +//****************************************************************************** + +int numlumps; // killough + +//****************************************************************************** +//wi_stuff.c +//****************************************************************************** + +// used to accelerate or skip a stage +int acceleratestage; // killough 3/28/98: made global + +// wbs->pnum +int me; + + // specifies current state +stateenum_t state; + +// contains information passed into intermission +wbstartstruct_t* wbs; + +wbplayerstruct_t* plrs; // wbs->plyr[] + +// used for general timing +int cnt; + +// used for timing of background animation +int bcnt; + +int cnt_time; +int cnt_total_time; +int cnt_par; +int cnt_pause; + +// 0-9 graphic +const patch_t* num[10]; + +int sp_state; + +int cnt_kills; +int cnt_items; +int cnt_secret; + +boolean snl_pointeron; + + +//****************************************************************************** +#endif // GLOBAL_DEFS_H + +} globals_t; + +#endif +void InitGlobals(); + +extern globals_t *_g; + +#endif // GLOBAL_DATA_H diff --git a/doom/src/pdoom/Doom/include/hu_lib.h b/doom/src/pdoom/Doom/include/hu_lib.h new file mode 100644 index 0000000..2b13e12 --- /dev/null +++ b/doom/src/pdoom/Doom/include/hu_lib.h @@ -0,0 +1,181 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: none + * + *-----------------------------------------------------------------------------*/ + +#ifndef __HULIB__ +#define __HULIB__ + +// We are referring to patches. +#include "r_defs.h" +#include "v_video.h" //jff 2/16/52 include color range defs + +/* background and foreground screen numbers + * different from other modules. */ +#define HU_BG 0 +#define HU_FG 0 + +/* font stuff + * #define HU_CHARERASE KEYD_BACKSPACE / not used / phares + */ + +#define HU_MAXLINES 1 +#define HU_MAXLINELENGTH 31 +#define HU_REFRESHSPACING 8 /*jff 2/26/98 space lines in text refresh widget*/ +/*jff 2/26/98 maximum number of messages allowed in refresh list */ +#define HU_MAXMESSAGES 1 + +/* + * Typedefs of widgets + */ + +/* Text Line widget + * (parent of Scrolling Text and Input Text widgets) */ +typedef struct +{ + // left-justified position of scrolling text window + short x; + short y; + + const patch_t **f; // font + short sc; // start character + //const char *cr; //jff 2/16/52 output color range + // Proff - Made this an int again. Needed for OpenGL + + // killough 1/23/98: Support multiple lines: +#define MAXLINES 1 + + short linelen; + char l[HU_MAXLINELENGTH * MAXLINES + 1]; // line of text + short len; // current line length + + // whether this line needs to be udpated + short needsupdate; + +} hu_textline_t; + +// Scrolling Text window widget +// (child of Text Line widget) +typedef struct +{ + hu_textline_t l[HU_MAXLINES]; // text lines to draw + short h; // height in lines + short cl; // current line number + + // pointer to boolean stating whether to update window + boolean *on; + boolean laston; // last value of *->on. + +} hu_stext_t; + +//jff 2/26/98 new widget to display last hud_msg_lines of messages +// Message refresh window widget +typedef struct +{ + hu_textline_t l[HU_MAXMESSAGES]; // text lines to draw + short nl; // height in lines + short nr; // total height in rows + short cl; // current line number + + short x, y, w, h; // window position and size + const patch_t *bg; // patches for background + + // pointer to boolean stating whether to update window + boolean *on; + boolean laston; // last value of *->on. + +} hu_mtext_t; + +// Input Text Line widget +// (child of Text Line widget) +typedef struct +{ + hu_textline_t l; // text line to input on + + // left margin past which I am not to delete characters + short lm; + + // pointer to boolean stating whether to update window + boolean *on; + boolean laston; // last value of *->on; + +} hu_itext_t; + +// +// Widget creation, access, and update routines +// + +// +// textline code +// + +// clear a line of text +void HUlib_clearTextLine(hu_textline_t *t); + +void HUlib_initTextLine(hu_textline_t *t, short x, short y, const patch_t *f, short sc); + +// returns success +boolean HUlib_addCharToTextLine(hu_textline_t *t, char ch); + +// draws tline +void HUlib_drawTextLine(hu_textline_t *l, boolean drawcursor); + +// erases text line +void HUlib_eraseTextLine(hu_textline_t *l); + +// +// Scrolling Text window widget routines +// + +// initialize an stext widget +void HUlib_initSText(hu_stext_t *s, short x, short y, short h, const patch_t *font, short startchar, //jff 2/16/98 add color range parameter +boolean *on); + +// add a text message to an stext widget +void HUlib_addMessageToSText(hu_stext_t *s, const char *prefix, const char *msg); + +// draws stext +void HUlib_drawSText(hu_stext_t *s); + +// erases all stext lines +void HUlib_eraseSText(hu_stext_t *s); + +#endif diff --git a/doom/src/pdoom/Doom/include/hu_stuff.h b/doom/src/pdoom/Doom/include/hu_stuff.h new file mode 100644 index 0000000..e0a196e --- /dev/null +++ b/doom/src/pdoom/Doom/include/hu_stuff.h @@ -0,0 +1,87 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: Head up display + * + *-----------------------------------------------------------------------------*/ + +#ifndef __HU_STUFF_H__ +#define __HU_STUFF_H__ + +#include "d_event.h" + +/* + * Globally visible constants. + */ +#define HU_FONTSTART '!' /* the first font characters */ +#define HU_FONTEND '_' /*jff 2/16/98 '_' the last font characters */ + +/* Calculate # of glyphs in font. */ +#define HU_FONTSIZE (HU_FONTEND - HU_FONTSTART + 1) + +#define HU_BROADCAST 5 + +/*#define HU_MSGREFRESH KEYD_ENTER phares */ +#define HU_MSGX 0 +#define HU_MSGY 0 +#define HU_MSGWIDTH 64 /* in characters */ +#define HU_MSGHEIGHT 1 /* in lines */ + +#define HU_MSGTIMEOUT (4*TICRATE) + +/* + * Heads up text + */ +void HU_Init(void); +void HU_Start(void); + +boolean HU_Responder(event_t *ev); + +void HU_Ticker(void); +void HU_Drawer(void); +void HU_Erase(void); +void HU_MoveHud(void); // jff 3/9/98 avoid glitch in HUD display + +/* killough 5/2/98: moved from m_misc.c: */ + +/* jff 2/26/98 hud message list color and background enable */ +extern const int hud_msg_lines; /* number of message lines in window up to 16 */ +/* jff 2/23/98 hud is currently displayed */ + +#endif diff --git a/doom/src/pdoom/Doom/include/i_main.h b/doom/src/pdoom/Doom/include/i_main.h new file mode 100644 index 0000000..0607ed1 --- /dev/null +++ b/doom/src/pdoom/Doom/include/i_main.h @@ -0,0 +1,52 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * General system functions. Signal related stuff, exit function + * prototypes, and programmable Doom clock. + * + *----------------------------------------------------------------------------- + */ + +#ifndef __I_MAIN__ +#define __I_MAIN__ + +void I_Init(void); + +#endif diff --git a/doom/src/pdoom/Doom/include/i_memory.h b/doom/src/pdoom/Doom/include/i_memory.h new file mode 100644 index 0000000..dda4229 --- /dev/null +++ b/doom/src/pdoom/Doom/include/i_memory.h @@ -0,0 +1,179 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * next-hack: packed (24) and 16 bit pointers utility functions and other stuff + */ + +#ifndef DOOM_INCLUDE_I_MEMORY_H_ +#define DOOM_INCLUDE_I_MEMORY_H_ +#include + +#ifdef PARADISE_DEV +/* Paradise: SRAM 0x18000000, flash uncached from 0x60000000 (WAD and region), program window 0x10000000 */ +#define RAM_PTR_BASE 0x18000000UL +#define EXT_FLASH_BASE 0x60000000 +#define FLASH_PTR_BASE 0x10000000 +#define PACKED_MEMORY_ADDRESS0 RAM_PTR_BASE +#ifdef DOOM_FREE +#include "pdmcfg.h" +#define PACKED_MEMORY_ADDRESS1 g_pk_hi +#define PACKED_MEMORY_ADDRESS2 g_pk_lo +#define PACKED_MEMORY_ADDRESS2_C 0x60800000 +#define PD_WAD_OFF (g_dcfg.wad_off - 4u) +#define PD_REGION_OFF (g_dcfg.region_off) +#define PD_REGION_LEN (g_dcfg.region_len) +#define PD_SAVE_ADDR (0x60000000u + g_dcfg.save_off) /* settings, then the save */ +#else +#define PD_SAVE_ADDR 0x6010E000u +#define PACKED_MEMORY_ADDRESS1 0x60C00000 +#define PACKED_MEMORY_ADDRESS2 0x60800000 +#define PACKED_MEMORY_ADDRESS2_C PACKED_MEMORY_ADDRESS2 +#endif +#define PACKED_MEMORY_ADDRESS3 FLASH_PTR_BASE +#ifndef PD_WAD_OFF +#define PD_WAD_OFF 0x830000 +#define PD_REGION_OFF 0xCA0000 +#define PD_REGION_LEN 0xA8000 +#endif +#define WAD_ADDRESS (EXT_FLASH_BASE + PD_WAD_OFF + 4) +#define FLASH_ADDRESS (EXT_FLASH_BASE + PD_REGION_OFF) +#define FLASH_CACHE_REGION_SIZE (PD_REGION_LEN) +#else +#define RAM_PTR_BASE 0x20000000UL +#define EXT_FLASH_BASE 0x12000000 +#define FLASH_PTR_BASE 0 +#define PACKED_MEMORY_ADDRESS0 RAM_PTR_BASE +#define PACKED_MEMORY_ADDRESS1 RAM_PTR_BASE +#define PACKED_MEMORY_ADDRESS2 EXT_FLASH_BASE +#define PACKED_MEMORY_ADDRESS3 FLASH_PTR_BASE +// +#define WAD_ADDRESS (EXT_FLASH_BASE + 4) +#define FLASH_CODE_KB 268 +#define FLASH_ADDRESS (0x00000000 + FLASH_CODE_KB * 1024) +#define FLASH_CACHE_REGION_SIZE ((1024 - FLASH_CODE_KB) * 1024) +#endif +#define isRamPtr(p) ((((uint32_t)(p)) >> 24) == (RAM_PTR_BASE >> 24)) +#define FLASH_IMMUTABLE_REGION_ADDRESS FLASH_ADDRESS +#define FLASH_IMMUTABLE_REGION 0 +#define FLASH_LEVEL_REGION 1 +#define FLASH_BLOCK_SIZE 4096 +// +#define DEBUG_GETSHORTPTR 0 +// +#ifdef PARADISE +#ifdef PARADISE_DEV +/* The WAD (before the region) counts as "external": the core then copies columns into RAM buffers */ +#ifdef DOOM_FREE +#define isOnExternalFlash(a) (((uint32_t)(a) - (0x60000000u + g_dcfg.wad_off - 4u)) < g_dcfg.wad_len + 4u) +#else +#define isOnExternalFlash(a) (((uint32_t)(a) - 0x60000000u) < (uint32_t) PD_REGION_OFF) +#endif +#else +#define isOnExternalFlash(a) (0) /* Paradise test run: everything directly readable */ +#endif +#else +#define isOnExternalFlash(a) (((uint32_t) a & EXT_FLASH_BASE) == EXT_FLASH_BASE) +#endif + +typedef struct +{ + uint8_t addrBytes[3]; +} __attribute((packed)) packedAddress_t; + +static inline void* getLongPtr(unsigned short shortPointer) +{ // Special case: short pointer being all 0 => NULL + if (!shortPointer) + return 0; + return (void*) (((unsigned int) shortPointer << 2) | RAM_PTR_BASE); +} +static inline unsigned short getShortPtr(void *longPtr) +{ + + return ((unsigned int) longPtr) >> 2; +} + +static inline packedAddress_t getPackedAddress(void *addr) +{ + packedAddress_t ret; + unsigned int intaddr = (uint32_t) addr; + uint8_t highaddr = intaddr >> 24; + uint8_t highAddrBits = 0; + ret.addrBytes[0] = intaddr; + ret.addrBytes[1] = intaddr >> 8; +#ifdef PARADISE_DEV + if (highaddr == 0x60) + { + highAddrBits = intaddr >= PACKED_MEMORY_ADDRESS1 ? 0x40 : 0x80; + ret.addrBytes[2] = ((intaddr >> 16) & 0x3F) | highAddrBits; + return ret; + } +#endif + switch (highaddr) + { + case (PACKED_MEMORY_ADDRESS0 >> 24) & 0xFF: + highAddrBits = 0x0; + break; + /*case (PACKED_MEMORY_ADDRESS1 >> 24) & 0xFF: + highAddrBits = 0x40; + break;*/ + case (PACKED_MEMORY_ADDRESS2_C >> 24) & 0xFF: + highAddrBits = 0x80; + break; + case (PACKED_MEMORY_ADDRESS3 >> 24) & 0xFF: + highAddrBits = 0xC0; + break; + } + ret.addrBytes[2] = ((intaddr >> 16) & 0x3F) | highAddrBits; + return ret; +} + +static inline void* unpackAddress(packedAddress_t a) // passed by copy, because it is shorted than a pointer! +{ + const uint32_t addresses[] = + { PACKED_MEMORY_ADDRESS0, PACKED_MEMORY_ADDRESS1, PACKED_MEMORY_ADDRESS2, PACKED_MEMORY_ADDRESS3 }; + + if (!a.addrBytes[2] && !a.addrBytes[1] && !a.addrBytes[0]) + { + return NULL; + } + return (void*) (addresses[a.addrBytes[2] >> 6] | (a.addrBytes[0]) | (a.addrBytes[1] << 8) | ((a.addrBytes[2] & 0x3F) << 16)); +} + +#endif /* DOOM_INCLUDE_I_MEMORY_H_ */ diff --git a/doom/src/pdoom/Doom/include/i_network.h b/doom/src/pdoom/Doom/include/i_network.h new file mode 100644 index 0000000..00e5890 --- /dev/null +++ b/doom/src/pdoom/Doom/include/i_network.h @@ -0,0 +1,68 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Low level network interface. + *-----------------------------------------------------------------------------*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define UDP_CHANNEL struct sockaddr + +#ifndef IPPORT_RESERVED +#define IPPORT_RESERVED 1024 +#endif + +void I_InitNetwork(void); +size_t I_GetPacket(packet_header_t *buffer, size_t buflen); +void I_SendPacket(packet_header_t *packet, size_t len); +void I_WaitForPacket(int ms); + +#ifdef AF_INET +void I_SendPacketTo(packet_header_t* packet, size_t len, UDP_CHANNEL *to); +void I_SetupSocket(int sock, int port, int family); +void I_PrintAddress(FILE* fp, UDP_CHANNEL *addr); + +extern UDP_CHANNEL sentfrom; +extern int v4socket, v6socket; +#endif + +extern size_t sentbytes, recvdbytes; diff --git a/doom/src/pdoom/Doom/include/i_sound.h b/doom/src/pdoom/Doom/include/i_sound.h new file mode 100644 index 0000000..9b51b48 --- /dev/null +++ b/doom/src/pdoom/Doom/include/i_sound.h @@ -0,0 +1,99 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * System interface, sound. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __I_SOUND__ +#define __I_SOUND__ + +#include "sounds.h" +#include "doomtype.h" + +// Init at program start... +void I_InitSound(void); + +// ... shut down and relase at program termination. +void I_ShutdownSound(void); + +// +// SFX I/O +// + +// Starts a sound in a particular sound channel. +int I_StartSound(int id, int channel, int vol, int sep); + +// +// MUSIC I/O +// +void I_InitMusic(void); + +// Volume. +void I_SetMusicVolume(int volume); + +// PAUSE game handling. +void I_PauseSong(int handle); +void I_ResumeSong(int handle); + +// Called by anything that wishes to start music. +// plays a song, and when the song is done, +// starts playing it again in an endless loop. +// Horrible thing to do, considering. +void I_PlaySong(int handle, int looping); + +// Stops a song over 3 seconds. +void I_StopSong(int handle); + +// CPhipps - put these in config file +extern const int snd_samplerate; + +typedef struct +{ + const char *data; + const char *enddata; + int vol; + +} channel_info_t; + +#define MUSIC_BUFFER_SAMPLES 2048 +#define MAX_CHANNELS 8 + +#endif diff --git a/doom/src/pdoom/Doom/include/i_spi_support.h b/doom/src/pdoom/Doom/include/i_spi_support.h new file mode 100644 index 0000000..5366233 --- /dev/null +++ b/doom/src/pdoom/Doom/include/i_spi_support.h @@ -0,0 +1,87 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * next-hack: Some wrapper functions, to use SPI routines. + * Memory mapped code has been removed. + */ +#ifndef I_SPI_SUPPORT_H_ +#define I_SPI_SUPPORT_H_ +#include +#include "string.h" +// +extern uint8_t *currentSpiAddress; +#ifdef PARADISE_DEV +/* Paradise: flash is only fast to read word by word (uncached byte read ~1.3 us), so read aligned words */ +void plat_fcopy(void *dst, const void *src, unsigned int n); +#define FLASH_MEMCPY(d, s, n) plat_fcopy((d), (s), (n)) +#else +#define FLASH_MEMCPY(d, s, n) memcpy((d), (s), (n)) +#endif +static inline uint8_t spiFlashGetByte() +{ + return *currentSpiAddress++; +} +static inline short spiFlashGetShort() +{ + uint16_t s = *currentSpiAddress++; + s |= (*currentSpiAddress++ << 8); + return (short) s; + /* + short s = *((short*) currentSpiAddress); + currentSpiAddress+=2; + return s;*/ +} +static inline uint8_t spiFlashGetByteFromAddress(const void *addr) +{ + currentSpiAddress = (void*) addr; + return spiFlashGetByte(); +} +static inline void* spiFlashGetData(void *dest, unsigned int length) +{ + uint32_t *b = (void*) currentSpiAddress; + FLASH_MEMCPY(dest, b, length); + currentSpiAddress += length; + return dest; +} +static inline uint32_t spiFlashSetAddress(uint32_t address) +{ + currentSpiAddress = (uint8_t*) address; +} +#endif /* SOURCE_I_SPI_SUPPORT_H_ */ diff --git a/doom/src/pdoom/Doom/include/i_system.h b/doom/src/pdoom/Doom/include/i_system.h new file mode 100644 index 0000000..a036618 --- /dev/null +++ b/doom/src/pdoom/Doom/include/i_system.h @@ -0,0 +1,63 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * System specific interface stuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __I_SYSTEM__ +#define __I_SYSTEM__ + +#ifdef __GNUG__ +#pragma interface +#endif + +#include "printf.h" +boolean I_StartDisplay(void); +void I_EndDisplay(void); +unsigned int I_GetTime(void); /* killough */ +unsigned int I_GetTimeMicrosecs(); + +/* cphipps - I_GetVersionString + * Returns a version string in the given buffer + */ +const char* I_GetVersionString(char *buf, size_t sz); + +#endif diff --git a/doom/src/pdoom/Doom/include/i_video.h b/doom/src/pdoom/Doom/include/i_video.h new file mode 100644 index 0000000..41557e9 --- /dev/null +++ b/doom/src/pdoom/Doom/include/i_video.h @@ -0,0 +1,85 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * System specific interface stuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __I_VIDEO__ +#define __I_VIDEO__ + +#include "doomtype.h" +#include "v_video.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +void I_PreInitGraphics(void); /* CPhipps - do stuff immediately on start */ +void I_SetRes(void); /* set resolution */ +void I_InitGraphics(void); +void I_UpdateVideoMode(void); +void I_ShutdownGraphics(void); + +/* Takes full 8 bit values. */ +void I_SetPalette(int pal); /* CPhipps - pass down palette number */ +boolean I_StartDisplay(void); +void I_FinishUpdateBlock(void); +/* I_StartTic + * Called by D_DoomLoop, + * called before processing each tic in a frame. + * Quick syncronous operations are performed here. + * Can call D_PostEvent. + */ +void I_StartTic(void); +key_t keysDown(); +/* I_StartFrame + * Called by D_DoomLoop, + * called before processing any tics in a frame + * (just after displaying a frame). + * Time consuming syncronous operations + * are performed here (joystick reading). + * Can call D_PostEvent. + */ +void handleDisplayBacklightToggle(); + +void I_StartFrame(void); +extern uint8_t displayBuffer[96 * SCREENWIDTH_PHYSICAL]; +#endif diff --git a/doom/src/pdoom/Doom/include/info.h b/doom/src/pdoom/Doom/include/info.h new file mode 100644 index 0000000..107e936 --- /dev/null +++ b/doom/src/pdoom/Doom/include/info.h @@ -0,0 +1,1508 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Thing frame/state LUT, + * generated by multigen utilitiy. + * This one is the original DOOM version, preserved. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __INFO__ +#define __INFO__ + +/* Needed for action function pointer handling. */ +#include "d_think.h" + +/******************************************************************** + * Sprite name enumeration - must match info.c * + ********************************************************************/ +typedef enum +{ + SPR_TROO, + SPR_SHTG, + SPR_PUNG, + SPR_PISG, + SPR_PISF, + SPR_SHTF, + SPR_SHT2, + SPR_CHGG, + SPR_CHGF, + SPR_MISG, + SPR_MISF, + SPR_SAWG, + SPR_PLSG, + SPR_PLSF, + SPR_BFGG, + SPR_BFGF, + SPR_BLUD, + SPR_PUFF, + SPR_BAL1, + SPR_BAL2, + SPR_PLSS, + SPR_PLSE, + SPR_MISL, + SPR_BFS1, + SPR_BFE1, + SPR_BFE2, + SPR_TFOG, + SPR_IFOG, + SPR_PLAY, + SPR_POSS, + SPR_SPOS, + SPR_VILE, + SPR_FIRE, + SPR_FATB, + SPR_FBXP, + SPR_SKEL, + SPR_MANF, + SPR_FATT, + SPR_CPOS, + SPR_SARG, + SPR_HEAD, + SPR_BAL7, + SPR_BOSS, + SPR_BOS2, + SPR_SKUL, + SPR_SPID, + SPR_BSPI, + SPR_APLS, + SPR_APBX, + SPR_CYBR, + SPR_PAIN, + SPR_SSWV, + SPR_KEEN, + SPR_BBRN, + SPR_BOSF, + SPR_ARM1, + SPR_ARM2, + SPR_BAR1, + SPR_BEXP, + SPR_FCAN, + SPR_BON1, + SPR_BON2, + SPR_BKEY, + SPR_RKEY, + SPR_YKEY, + SPR_BSKU, + SPR_RSKU, + SPR_YSKU, + SPR_STIM, + SPR_MEDI, + SPR_SOUL, + SPR_PINV, + SPR_PSTR, + SPR_PINS, + SPR_MEGA, + SPR_SUIT, + SPR_PMAP, + SPR_PVIS, + SPR_CLIP, + SPR_AMMO, + SPR_ROCK, + SPR_BROK, + SPR_CELL, + SPR_CELP, + SPR_SHEL, + SPR_SBOX, + SPR_BPAK, + SPR_BFUG, + SPR_MGUN, + SPR_CSAW, + SPR_LAUN, + SPR_PLAS, + SPR_SHOT, + SPR_SGN2, + SPR_COLU, + SPR_SMT2, + SPR_GOR1, + SPR_POL2, + SPR_POL5, + SPR_POL4, + SPR_POL3, + SPR_POL1, + SPR_POL6, + SPR_GOR2, + SPR_GOR3, + SPR_GOR4, + SPR_GOR5, + SPR_SMIT, + SPR_COL1, + SPR_COL2, + SPR_COL3, + SPR_COL4, + SPR_CAND, + SPR_CBRA, + SPR_COL6, + SPR_TRE1, + SPR_TRE2, + SPR_ELEC, + SPR_CEYE, + SPR_FSKU, + SPR_COL5, + SPR_TBLU, + SPR_TGRN, + SPR_TRED, + SPR_SMBT, + SPR_SMGT, + SPR_SMRT, + SPR_HDB1, + SPR_HDB2, + SPR_HDB3, + SPR_HDB4, + SPR_HDB5, + SPR_HDB6, + SPR_POB1, + SPR_POB2, + SPR_BRS1, + SPR_TLMP, + SPR_TLP2, + SPR_TNT1, /* add invisible sprite phares 3/8/98 */ + +#ifdef DOGS + SPR_DOGS, /* killough 7/19/98: Marine's best friend :) */ +#endif + + NUMSPRITES /* counter of how many there are */ + +} spritenum_t; + +/******************************************************************** + * States (frames) enumeration -- must match info.c * + ********************************************************************/ + +typedef enum +{ + S_NULL, + S_LIGHTDONE, + S_PUNCH, + S_PUNCHDOWN, + S_PUNCHUP, + S_PUNCH1, + S_PUNCH2, + S_PUNCH3, + S_PUNCH4, + S_PUNCH5, + S_PISTOL, + S_PISTOLDOWN, + S_PISTOLUP, + S_PISTOL1, + S_PISTOL2, + S_PISTOL3, + S_PISTOL4, + S_PISTOLFLASH, + S_SGUN, + S_SGUNDOWN, + S_SGUNUP, + S_SGUN1, + S_SGUN2, + S_SGUN3, + S_SGUN4, + S_SGUN5, + S_SGUN6, + S_SGUN7, + S_SGUN8, + S_SGUN9, + S_SGUNFLASH1, + S_SGUNFLASH2, + S_DSGUN, + S_DSGUNDOWN, + S_DSGUNUP, + S_DSGUN1, + S_DSGUN2, + S_DSGUN3, + S_DSGUN4, + S_DSGUN5, + S_DSGUN6, + S_DSGUN7, + S_DSGUN8, + S_DSGUN9, + S_DSGUN10, + S_DSNR1, + S_DSNR2, + S_DSGUNFLASH1, + S_DSGUNFLASH2, + S_CHAIN, + S_CHAINDOWN, + S_CHAINUP, + S_CHAIN1, + S_CHAIN2, + S_CHAIN3, + S_CHAINFLASH1, + S_CHAINFLASH2, + S_MISSILE, + S_MISSILEDOWN, + S_MISSILEUP, + S_MISSILE1, + S_MISSILE2, + S_MISSILE3, + S_MISSILEFLASH1, + S_MISSILEFLASH2, + S_MISSILEFLASH3, + S_MISSILEFLASH4, + S_SAW, + S_SAWB, + S_SAWDOWN, + S_SAWUP, + S_SAW1, + S_SAW2, + S_SAW3, + S_PLASMA, + S_PLASMADOWN, + S_PLASMAUP, + S_PLASMA1, + S_PLASMA2, + S_PLASMAFLASH1, + S_PLASMAFLASH2, + S_BFG, + S_BFGDOWN, + S_BFGUP, + S_BFG1, + S_BFG2, + S_BFG3, + S_BFG4, + S_BFGFLASH1, + S_BFGFLASH2, + S_BLOOD1, + S_BLOOD2, + S_BLOOD3, + S_PUFF1, + S_PUFF2, + S_PUFF3, + S_PUFF4, + S_TBALL1, + S_TBALL2, + S_TBALLX1, + S_TBALLX2, + S_TBALLX3, + S_RBALL1, + S_RBALL2, + S_RBALLX1, + S_RBALLX2, + S_RBALLX3, + S_PLASBALL, + S_PLASBALL2, + S_PLASEXP, + S_PLASEXP2, + S_PLASEXP3, + S_PLASEXP4, + S_PLASEXP5, + S_ROCKET, + S_BFGSHOT, + S_BFGSHOT2, + S_BFGLAND, + S_BFGLAND2, + S_BFGLAND3, + S_BFGLAND4, + S_BFGLAND5, + S_BFGLAND6, + S_BFGEXP, + S_BFGEXP2, + S_BFGEXP3, + S_BFGEXP4, + S_EXPLODE1, + S_EXPLODE2, + S_EXPLODE3, + S_TFOG, + S_TFOG01, + S_TFOG02, + S_TFOG2, + S_TFOG3, + S_TFOG4, + S_TFOG5, + S_TFOG6, + S_TFOG7, + S_TFOG8, + S_TFOG9, + S_TFOG10, + S_IFOG, + S_IFOG01, + S_IFOG02, + S_IFOG2, + S_IFOG3, + S_IFOG4, + S_IFOG5, + S_PLAY, + S_PLAY_RUN1, + S_PLAY_RUN2, + S_PLAY_RUN3, + S_PLAY_RUN4, + S_PLAY_ATK1, + S_PLAY_ATK2, + S_PLAY_PAIN, + S_PLAY_PAIN2, + S_PLAY_DIE1, + S_PLAY_DIE2, + S_PLAY_DIE3, + S_PLAY_DIE4, + S_PLAY_DIE5, + S_PLAY_DIE6, + S_PLAY_DIE7, + S_PLAY_XDIE1, + S_PLAY_XDIE2, + S_PLAY_XDIE3, + S_PLAY_XDIE4, + S_PLAY_XDIE5, + S_PLAY_XDIE6, + S_PLAY_XDIE7, + S_PLAY_XDIE8, + S_PLAY_XDIE9, + S_POSS_STND, + S_POSS_STND2, + S_POSS_RUN1, + S_POSS_RUN2, + S_POSS_RUN3, + S_POSS_RUN4, + S_POSS_RUN5, + S_POSS_RUN6, + S_POSS_RUN7, + S_POSS_RUN8, + S_POSS_ATK1, + S_POSS_ATK2, + S_POSS_ATK3, + S_POSS_PAIN, + S_POSS_PAIN2, + S_POSS_DIE1, + S_POSS_DIE2, + S_POSS_DIE3, + S_POSS_DIE4, + S_POSS_DIE5, + S_POSS_XDIE1, + S_POSS_XDIE2, + S_POSS_XDIE3, + S_POSS_XDIE4, + S_POSS_XDIE5, + S_POSS_XDIE6, + S_POSS_XDIE7, + S_POSS_XDIE8, + S_POSS_XDIE9, + S_POSS_RAISE1, + S_POSS_RAISE2, + S_POSS_RAISE3, + S_POSS_RAISE4, + S_SPOS_STND, + S_SPOS_STND2, + S_SPOS_RUN1, + S_SPOS_RUN2, + S_SPOS_RUN3, + S_SPOS_RUN4, + S_SPOS_RUN5, + S_SPOS_RUN6, + S_SPOS_RUN7, + S_SPOS_RUN8, + S_SPOS_ATK1, + S_SPOS_ATK2, + S_SPOS_ATK3, + S_SPOS_PAIN, + S_SPOS_PAIN2, + S_SPOS_DIE1, + S_SPOS_DIE2, + S_SPOS_DIE3, + S_SPOS_DIE4, + S_SPOS_DIE5, + S_SPOS_XDIE1, + S_SPOS_XDIE2, + S_SPOS_XDIE3, + S_SPOS_XDIE4, + S_SPOS_XDIE5, + S_SPOS_XDIE6, + S_SPOS_XDIE7, + S_SPOS_XDIE8, + S_SPOS_XDIE9, + S_SPOS_RAISE1, + S_SPOS_RAISE2, + S_SPOS_RAISE3, + S_SPOS_RAISE4, + S_SPOS_RAISE5, + S_VILE_STND, + S_VILE_STND2, + S_VILE_RUN1, + S_VILE_RUN2, + S_VILE_RUN3, + S_VILE_RUN4, + S_VILE_RUN5, + S_VILE_RUN6, + S_VILE_RUN7, + S_VILE_RUN8, + S_VILE_RUN9, + S_VILE_RUN10, + S_VILE_RUN11, + S_VILE_RUN12, + S_VILE_ATK1, + S_VILE_ATK2, + S_VILE_ATK3, + S_VILE_ATK4, + S_VILE_ATK5, + S_VILE_ATK6, + S_VILE_ATK7, + S_VILE_ATK8, + S_VILE_ATK9, + S_VILE_ATK10, + S_VILE_ATK11, + S_VILE_HEAL1, + S_VILE_HEAL2, + S_VILE_HEAL3, + S_VILE_PAIN, + S_VILE_PAIN2, + S_VILE_DIE1, + S_VILE_DIE2, + S_VILE_DIE3, + S_VILE_DIE4, + S_VILE_DIE5, + S_VILE_DIE6, + S_VILE_DIE7, + S_VILE_DIE8, + S_VILE_DIE9, + S_VILE_DIE10, + S_FIRE1, + S_FIRE2, + S_FIRE3, + S_FIRE4, + S_FIRE5, + S_FIRE6, + S_FIRE7, + S_FIRE8, + S_FIRE9, + S_FIRE10, + S_FIRE11, + S_FIRE12, + S_FIRE13, + S_FIRE14, + S_FIRE15, + S_FIRE16, + S_FIRE17, + S_FIRE18, + S_FIRE19, + S_FIRE20, + S_FIRE21, + S_FIRE22, + S_FIRE23, + S_FIRE24, + S_FIRE25, + S_FIRE26, + S_FIRE27, + S_FIRE28, + S_FIRE29, + S_FIRE30, + S_SMOKE1, + S_SMOKE2, + S_SMOKE3, + S_SMOKE4, + S_SMOKE5, + S_TRACER, + S_TRACER2, + S_TRACEEXP1, + S_TRACEEXP2, + S_TRACEEXP3, + S_SKEL_STND, + S_SKEL_STND2, + S_SKEL_RUN1, + S_SKEL_RUN2, + S_SKEL_RUN3, + S_SKEL_RUN4, + S_SKEL_RUN5, + S_SKEL_RUN6, + S_SKEL_RUN7, + S_SKEL_RUN8, + S_SKEL_RUN9, + S_SKEL_RUN10, + S_SKEL_RUN11, + S_SKEL_RUN12, + S_SKEL_FIST1, + S_SKEL_FIST2, + S_SKEL_FIST3, + S_SKEL_FIST4, + S_SKEL_MISS1, + S_SKEL_MISS2, + S_SKEL_MISS3, + S_SKEL_MISS4, + S_SKEL_PAIN, + S_SKEL_PAIN2, + S_SKEL_DIE1, + S_SKEL_DIE2, + S_SKEL_DIE3, + S_SKEL_DIE4, + S_SKEL_DIE5, + S_SKEL_DIE6, + S_SKEL_RAISE1, + S_SKEL_RAISE2, + S_SKEL_RAISE3, + S_SKEL_RAISE4, + S_SKEL_RAISE5, + S_SKEL_RAISE6, + S_FATSHOT1, + S_FATSHOT2, + S_FATSHOTX1, + S_FATSHOTX2, + S_FATSHOTX3, + S_FATT_STND, + S_FATT_STND2, + S_FATT_RUN1, + S_FATT_RUN2, + S_FATT_RUN3, + S_FATT_RUN4, + S_FATT_RUN5, + S_FATT_RUN6, + S_FATT_RUN7, + S_FATT_RUN8, + S_FATT_RUN9, + S_FATT_RUN10, + S_FATT_RUN11, + S_FATT_RUN12, + S_FATT_ATK1, + S_FATT_ATK2, + S_FATT_ATK3, + S_FATT_ATK4, + S_FATT_ATK5, + S_FATT_ATK6, + S_FATT_ATK7, + S_FATT_ATK8, + S_FATT_ATK9, + S_FATT_ATK10, + S_FATT_PAIN, + S_FATT_PAIN2, + S_FATT_DIE1, + S_FATT_DIE2, + S_FATT_DIE3, + S_FATT_DIE4, + S_FATT_DIE5, + S_FATT_DIE6, + S_FATT_DIE7, + S_FATT_DIE8, + S_FATT_DIE9, + S_FATT_DIE10, + S_FATT_RAISE1, + S_FATT_RAISE2, + S_FATT_RAISE3, + S_FATT_RAISE4, + S_FATT_RAISE5, + S_FATT_RAISE6, + S_FATT_RAISE7, + S_FATT_RAISE8, + S_CPOS_STND, + S_CPOS_STND2, + S_CPOS_RUN1, + S_CPOS_RUN2, + S_CPOS_RUN3, + S_CPOS_RUN4, + S_CPOS_RUN5, + S_CPOS_RUN6, + S_CPOS_RUN7, + S_CPOS_RUN8, + S_CPOS_ATK1, + S_CPOS_ATK2, + S_CPOS_ATK3, + S_CPOS_ATK4, + S_CPOS_PAIN, + S_CPOS_PAIN2, + S_CPOS_DIE1, + S_CPOS_DIE2, + S_CPOS_DIE3, + S_CPOS_DIE4, + S_CPOS_DIE5, + S_CPOS_DIE6, + S_CPOS_DIE7, + S_CPOS_XDIE1, + S_CPOS_XDIE2, + S_CPOS_XDIE3, + S_CPOS_XDIE4, + S_CPOS_XDIE5, + S_CPOS_XDIE6, + S_CPOS_RAISE1, + S_CPOS_RAISE2, + S_CPOS_RAISE3, + S_CPOS_RAISE4, + S_CPOS_RAISE5, + S_CPOS_RAISE6, + S_CPOS_RAISE7, + S_TROO_STND, + S_TROO_STND2, + S_TROO_RUN1, + S_TROO_RUN2, + S_TROO_RUN3, + S_TROO_RUN4, + S_TROO_RUN5, + S_TROO_RUN6, + S_TROO_RUN7, + S_TROO_RUN8, + S_TROO_ATK1, + S_TROO_ATK2, + S_TROO_ATK3, + S_TROO_PAIN, + S_TROO_PAIN2, + S_TROO_DIE1, + S_TROO_DIE2, + S_TROO_DIE3, + S_TROO_DIE4, + S_TROO_DIE5, + S_TROO_XDIE1, + S_TROO_XDIE2, + S_TROO_XDIE3, + S_TROO_XDIE4, + S_TROO_XDIE5, + S_TROO_XDIE6, + S_TROO_XDIE7, + S_TROO_XDIE8, + S_TROO_RAISE1, + S_TROO_RAISE2, + S_TROO_RAISE3, + S_TROO_RAISE4, + S_TROO_RAISE5, + S_SARG_STND, + S_SARG_STND2, + S_SARG_RUN1, + S_SARG_RUN2, + S_SARG_RUN3, + S_SARG_RUN4, + S_SARG_RUN5, + S_SARG_RUN6, + S_SARG_RUN7, + S_SARG_RUN8, + S_SARG_ATK1, + S_SARG_ATK2, + S_SARG_ATK3, + S_SARG_PAIN, + S_SARG_PAIN2, + S_SARG_DIE1, + S_SARG_DIE2, + S_SARG_DIE3, + S_SARG_DIE4, + S_SARG_DIE5, + S_SARG_DIE6, + S_SARG_RAISE1, + S_SARG_RAISE2, + S_SARG_RAISE3, + S_SARG_RAISE4, + S_SARG_RAISE5, + S_SARG_RAISE6, + S_HEAD_STND, + S_HEAD_RUN1, + S_HEAD_ATK1, + S_HEAD_ATK2, + S_HEAD_ATK3, + S_HEAD_PAIN, + S_HEAD_PAIN2, + S_HEAD_PAIN3, + S_HEAD_DIE1, + S_HEAD_DIE2, + S_HEAD_DIE3, + S_HEAD_DIE4, + S_HEAD_DIE5, + S_HEAD_DIE6, + S_HEAD_RAISE1, + S_HEAD_RAISE2, + S_HEAD_RAISE3, + S_HEAD_RAISE4, + S_HEAD_RAISE5, + S_HEAD_RAISE6, + S_BRBALL1, + S_BRBALL2, + S_BRBALLX1, + S_BRBALLX2, + S_BRBALLX3, + S_BOSS_STND, + S_BOSS_STND2, + S_BOSS_RUN1, + S_BOSS_RUN2, + S_BOSS_RUN3, + S_BOSS_RUN4, + S_BOSS_RUN5, + S_BOSS_RUN6, + S_BOSS_RUN7, + S_BOSS_RUN8, + S_BOSS_ATK1, + S_BOSS_ATK2, + S_BOSS_ATK3, + S_BOSS_PAIN, + S_BOSS_PAIN2, + S_BOSS_DIE1, + S_BOSS_DIE2, + S_BOSS_DIE3, + S_BOSS_DIE4, + S_BOSS_DIE5, + S_BOSS_DIE6, + S_BOSS_DIE7, + S_BOSS_RAISE1, + S_BOSS_RAISE2, + S_BOSS_RAISE3, + S_BOSS_RAISE4, + S_BOSS_RAISE5, + S_BOSS_RAISE6, + S_BOSS_RAISE7, + S_BOS2_STND, + S_BOS2_STND2, + S_BOS2_RUN1, + S_BOS2_RUN2, + S_BOS2_RUN3, + S_BOS2_RUN4, + S_BOS2_RUN5, + S_BOS2_RUN6, + S_BOS2_RUN7, + S_BOS2_RUN8, + S_BOS2_ATK1, + S_BOS2_ATK2, + S_BOS2_ATK3, + S_BOS2_PAIN, + S_BOS2_PAIN2, + S_BOS2_DIE1, + S_BOS2_DIE2, + S_BOS2_DIE3, + S_BOS2_DIE4, + S_BOS2_DIE5, + S_BOS2_DIE6, + S_BOS2_DIE7, + S_BOS2_RAISE1, + S_BOS2_RAISE2, + S_BOS2_RAISE3, + S_BOS2_RAISE4, + S_BOS2_RAISE5, + S_BOS2_RAISE6, + S_BOS2_RAISE7, + S_SKULL_STND, + S_SKULL_STND2, + S_SKULL_RUN1, + S_SKULL_RUN2, + S_SKULL_ATK1, + S_SKULL_ATK2, + S_SKULL_ATK3, + S_SKULL_ATK4, + S_SKULL_PAIN, + S_SKULL_PAIN2, + S_SKULL_DIE1, + S_SKULL_DIE2, + S_SKULL_DIE3, + S_SKULL_DIE4, + S_SKULL_DIE5, + S_SKULL_DIE6, + S_SPID_STND, + S_SPID_STND2, + S_SPID_RUN1, + S_SPID_RUN2, + S_SPID_RUN3, + S_SPID_RUN4, + S_SPID_RUN5, + S_SPID_RUN6, + S_SPID_RUN7, + S_SPID_RUN8, + S_SPID_RUN9, + S_SPID_RUN10, + S_SPID_RUN11, + S_SPID_RUN12, + S_SPID_ATK1, + S_SPID_ATK2, + S_SPID_ATK3, + S_SPID_ATK4, + S_SPID_PAIN, + S_SPID_PAIN2, + S_SPID_DIE1, + S_SPID_DIE2, + S_SPID_DIE3, + S_SPID_DIE4, + S_SPID_DIE5, + S_SPID_DIE6, + S_SPID_DIE7, + S_SPID_DIE8, + S_SPID_DIE9, + S_SPID_DIE10, + S_SPID_DIE11, + S_BSPI_STND, + S_BSPI_STND2, + S_BSPI_SIGHT, + S_BSPI_RUN1, + S_BSPI_RUN2, + S_BSPI_RUN3, + S_BSPI_RUN4, + S_BSPI_RUN5, + S_BSPI_RUN6, + S_BSPI_RUN7, + S_BSPI_RUN8, + S_BSPI_RUN9, + S_BSPI_RUN10, + S_BSPI_RUN11, + S_BSPI_RUN12, + S_BSPI_ATK1, + S_BSPI_ATK2, + S_BSPI_ATK3, + S_BSPI_ATK4, + S_BSPI_PAIN, + S_BSPI_PAIN2, + S_BSPI_DIE1, + S_BSPI_DIE2, + S_BSPI_DIE3, + S_BSPI_DIE4, + S_BSPI_DIE5, + S_BSPI_DIE6, + S_BSPI_DIE7, + S_BSPI_RAISE1, + S_BSPI_RAISE2, + S_BSPI_RAISE3, + S_BSPI_RAISE4, + S_BSPI_RAISE5, + S_BSPI_RAISE6, + S_BSPI_RAISE7, + S_ARACH_PLAZ, + S_ARACH_PLAZ2, + S_ARACH_PLEX, + S_ARACH_PLEX2, + S_ARACH_PLEX3, + S_ARACH_PLEX4, + S_ARACH_PLEX5, + S_CYBER_STND, + S_CYBER_STND2, + S_CYBER_RUN1, + S_CYBER_RUN2, + S_CYBER_RUN3, + S_CYBER_RUN4, + S_CYBER_RUN5, + S_CYBER_RUN6, + S_CYBER_RUN7, + S_CYBER_RUN8, + S_CYBER_ATK1, + S_CYBER_ATK2, + S_CYBER_ATK3, + S_CYBER_ATK4, + S_CYBER_ATK5, + S_CYBER_ATK6, + S_CYBER_PAIN, + S_CYBER_DIE1, + S_CYBER_DIE2, + S_CYBER_DIE3, + S_CYBER_DIE4, + S_CYBER_DIE5, + S_CYBER_DIE6, + S_CYBER_DIE7, + S_CYBER_DIE8, + S_CYBER_DIE9, + S_CYBER_DIE10, + S_PAIN_STND, + S_PAIN_RUN1, + S_PAIN_RUN2, + S_PAIN_RUN3, + S_PAIN_RUN4, + S_PAIN_RUN5, + S_PAIN_RUN6, + S_PAIN_ATK1, + S_PAIN_ATK2, + S_PAIN_ATK3, + S_PAIN_ATK4, + S_PAIN_PAIN, + S_PAIN_PAIN2, + S_PAIN_DIE1, + S_PAIN_DIE2, + S_PAIN_DIE3, + S_PAIN_DIE4, + S_PAIN_DIE5, + S_PAIN_DIE6, + S_PAIN_RAISE1, + S_PAIN_RAISE2, + S_PAIN_RAISE3, + S_PAIN_RAISE4, + S_PAIN_RAISE5, + S_PAIN_RAISE6, + S_SSWV_STND, + S_SSWV_STND2, + S_SSWV_RUN1, + S_SSWV_RUN2, + S_SSWV_RUN3, + S_SSWV_RUN4, + S_SSWV_RUN5, + S_SSWV_RUN6, + S_SSWV_RUN7, + S_SSWV_RUN8, + S_SSWV_ATK1, + S_SSWV_ATK2, + S_SSWV_ATK3, + S_SSWV_ATK4, + S_SSWV_ATK5, + S_SSWV_ATK6, + S_SSWV_PAIN, + S_SSWV_PAIN2, + S_SSWV_DIE1, + S_SSWV_DIE2, + S_SSWV_DIE3, + S_SSWV_DIE4, + S_SSWV_DIE5, + S_SSWV_XDIE1, + S_SSWV_XDIE2, + S_SSWV_XDIE3, + S_SSWV_XDIE4, + S_SSWV_XDIE5, + S_SSWV_XDIE6, + S_SSWV_XDIE7, + S_SSWV_XDIE8, + S_SSWV_XDIE9, + S_SSWV_RAISE1, + S_SSWV_RAISE2, + S_SSWV_RAISE3, + S_SSWV_RAISE4, + S_SSWV_RAISE5, + S_KEENSTND, + S_COMMKEEN, + S_COMMKEEN2, + S_COMMKEEN3, + S_COMMKEEN4, + S_COMMKEEN5, + S_COMMKEEN6, + S_COMMKEEN7, + S_COMMKEEN8, + S_COMMKEEN9, + S_COMMKEEN10, + S_COMMKEEN11, + S_COMMKEEN12, + S_KEENPAIN, + S_KEENPAIN2, + S_BRAIN, + S_BRAIN_PAIN, + S_BRAIN_DIE1, + S_BRAIN_DIE2, + S_BRAIN_DIE3, + S_BRAIN_DIE4, + S_BRAINEYE, + S_BRAINEYESEE, + S_BRAINEYE1, + S_SPAWN1, + S_SPAWN2, + S_SPAWN3, + S_SPAWN4, + S_SPAWNFIRE1, + S_SPAWNFIRE2, + S_SPAWNFIRE3, + S_SPAWNFIRE4, + S_SPAWNFIRE5, + S_SPAWNFIRE6, + S_SPAWNFIRE7, + S_SPAWNFIRE8, + S_BRAINEXPLODE1, + S_BRAINEXPLODE2, + S_BRAINEXPLODE3, + S_ARM1, + S_ARM1A, + S_ARM2, + S_ARM2A, + S_BAR1, + S_BAR2, + S_BEXP, + S_BEXP2, + S_BEXP3, + S_BEXP4, + S_BEXP5, + S_BBAR1, + S_BBAR2, + S_BBAR3, + S_BON1, + S_BON1A, + S_BON1B, + S_BON1C, + S_BON1D, + S_BON1E, + S_BON2, + S_BON2A, + S_BON2B, + S_BON2C, + S_BON2D, + S_BON2E, + S_BKEY, + S_BKEY2, + S_RKEY, + S_RKEY2, + S_YKEY, + S_YKEY2, + S_BSKULL, + S_BSKULL2, + S_RSKULL, + S_RSKULL2, + S_YSKULL, + S_YSKULL2, + S_STIM, + S_MEDI, + S_SOUL, + S_SOUL2, + S_SOUL3, + S_SOUL4, + S_SOUL5, + S_SOUL6, + S_PINV, + S_PINV2, + S_PINV3, + S_PINV4, + S_PSTR, + S_PINS, + S_PINS2, + S_PINS3, + S_PINS4, + S_MEGA, + S_MEGA2, + S_MEGA3, + S_MEGA4, + S_SUIT, + S_PMAP, + S_PMAP2, + S_PMAP3, + S_PMAP4, + S_PMAP5, + S_PMAP6, + S_PVIS, + S_PVIS2, + S_CLIP, + S_AMMO, + S_ROCK, + S_BROK, + S_CELL, + S_CELP, + S_SHEL, + S_SBOX, + S_BPAK, + S_BFUG, + S_MGUN, + S_CSAW, + S_LAUN, + S_PLAS, + S_SHOT, + S_SHOT2, + S_COLU, + S_STALAG, + S_BLOODYTWITCH, + S_BLOODYTWITCH2, + S_BLOODYTWITCH3, + S_BLOODYTWITCH4, + S_DEADTORSO, + S_DEADBOTTOM, + S_HEADSONSTICK, + S_GIBS, + S_HEADONASTICK, + S_HEADCANDLES, + S_HEADCANDLES2, + S_DEADSTICK, + S_LIVESTICK, + S_LIVESTICK2, + S_MEAT2, + S_MEAT3, + S_MEAT4, + S_MEAT5, + S_STALAGTITE, + S_TALLGRNCOL, + S_SHRTGRNCOL, + S_TALLREDCOL, + S_SHRTREDCOL, + S_CANDLESTIK, + S_CANDELABRA, + S_SKULLCOL, + S_TORCHTREE, + S_BIGTREE, + S_TECHPILLAR, + S_EVILEYE, + S_EVILEYE2, + S_EVILEYE3, + S_EVILEYE4, + S_FLOATSKULL, + S_FLOATSKULL2, + S_FLOATSKULL3, + S_HEARTCOL, + S_HEARTCOL2, + S_BLUETORCH, + S_BLUETORCH2, + S_BLUETORCH3, + S_BLUETORCH4, + S_GREENTORCH, + S_GREENTORCH2, + S_GREENTORCH3, + S_GREENTORCH4, + S_REDTORCH, + S_REDTORCH2, + S_REDTORCH3, + S_REDTORCH4, + S_BTORCHSHRT, + S_BTORCHSHRT2, + S_BTORCHSHRT3, + S_BTORCHSHRT4, + S_GTORCHSHRT, + S_GTORCHSHRT2, + S_GTORCHSHRT3, + S_GTORCHSHRT4, + S_RTORCHSHRT, + S_RTORCHSHRT2, + S_RTORCHSHRT3, + S_RTORCHSHRT4, + S_HANGNOGUTS, + S_HANGBNOBRAIN, + S_HANGTLOOKDN, + S_HANGTSKULL, + S_HANGTLOOKUP, + S_HANGTNOBRAIN, + S_COLONGIBS, + S_SMALLPOOL, + S_BRAINSTEM, + S_TECHLAMP, + S_TECHLAMP2, + S_TECHLAMP3, + S_TECHLAMP4, + S_TECH2LAMP, + S_TECH2LAMP2, + S_TECH2LAMP3, + S_TECH2LAMP4, + S_TNT1, /* add state for invisible sprite phares 3/8/98 */ + + S_GRENADE, /* killough 8/9/98: grenade launcher */ + S_DETONATE, /* killough 8/9/98: detonation of objects */ + S_DETONATE2, + S_DETONATE3, + + // always count dog states, even if dogs are disabled + S_DOGS_STND, /* killough 7/19/98: Marine's best friend :) */ + S_DOGS_STND2, + S_DOGS_RUN1, + S_DOGS_RUN2, + S_DOGS_RUN3, + S_DOGS_RUN4, + S_DOGS_RUN5, + S_DOGS_RUN6, + S_DOGS_RUN7, + S_DOGS_RUN8, + S_DOGS_ATK1, + S_DOGS_ATK2, + S_DOGS_ATK3, + S_DOGS_PAIN, + S_DOGS_PAIN2, + S_DOGS_DIE1, + S_DOGS_DIE2, + S_DOGS_DIE3, + S_DOGS_DIE4, + S_DOGS_DIE5, + S_DOGS_DIE6, + S_DOGS_RAISE1, + S_DOGS_RAISE2, + S_DOGS_RAISE3, + S_DOGS_RAISE4, + S_DOGS_RAISE5, + S_DOGS_RAISE6, + + // add dummy beta bfg / lost soul frames for dehacked compatibility + // fixes bug #1576151 (part 2) + S_OLDBFG1, // killough 7/11/98: the old BFG's 43 firing frames + S_OLDBFG42 = S_OLDBFG1 + 41, + S_OLDBFG43, + + S_PLS1BALL, // killough 7/19/98: first plasma fireball in the beta + S_PLS1BALL2, + S_PLS1EXP, + S_PLS1EXP2, + S_PLS1EXP3, + S_PLS1EXP4, + S_PLS1EXP5, + + S_PLS2BALL, // killough 7/19/98: second plasma fireball in the beta + S_PLS2BALL2, + S_PLS2BALLX1, + S_PLS2BALLX2, + S_PLS2BALLX3, + S_BON3, // killough 7/11/98: evil sceptre in beta version + S_BON4, // killough 7/11/98: unholy bible in beta version + + // killough 10/98: beta lost souls were different from their modern cousins + S_BSKUL_STND, + S_BSKUL_RUN1, + S_BSKUL_RUN2, + S_BSKUL_RUN3, + S_BSKUL_RUN4, + S_BSKUL_ATK1, + S_BSKUL_ATK2, + S_BSKUL_ATK3, + S_BSKUL_PAIN1, + S_BSKUL_PAIN2, + S_BSKUL_PAIN3, + S_BSKUL_DIE1, + S_BSKUL_DIE2, + S_BSKUL_DIE3, + S_BSKUL_DIE4, + S_BSKUL_DIE5, + S_BSKUL_DIE6, + S_BSKUL_DIE7, + S_BSKUL_DIE8, + + S_MUSHROOM, /* killough 10/98: mushroom explosion effect */ + + NUMSTATES /* Counter of how many there are */ + +} statenum_t; + +/******************************************************************** + * Definition of the state (frames) structure * + ********************************************************************/ + +typedef struct +{ + short sprite; /* sprite number to show */ + short frame; /* which frame/subframe of the sprite is shown */ + short tics; /* number of gametics this frame should last */ + actionf_t action; /* code pointer to function for action if any */ + short nextstate; /* linked list pointer to next state or zero */ + short misc1, misc2; /* apparently never used in DOOM */ +} __attribute__ ((packed)) state_t; + +/* these are in info.c */ +extern const state_t states[NUMSTATES]; +extern const char *const sprnames[]; /* 1/17/98 killough - CPhipps - const */ + +/******************************************************************** + * Thing enumeration -- must match info.c * + ******************************************************************** + * Note that many of these are generically named for the ornamentals + */ + +typedef enum +{ + MT_PLAYER, + MT_POSSESSED, + MT_SHOTGUY, + MT_VILE, + MT_FIRE, + MT_UNDEAD, + MT_TRACER, + MT_SMOKE, + MT_FATSO, + MT_FATSHOT, + MT_CHAINGUY, + MT_TROOP, + MT_SERGEANT, + MT_SHADOWS, + MT_HEAD, + MT_BRUISER, + MT_BRUISERSHOT, + MT_KNIGHT, + MT_SKULL, + MT_SPIDER, + MT_BABY, + MT_CYBORG, + MT_PAIN, + MT_WOLFSS, + MT_KEEN, + MT_BOSSBRAIN, + MT_BOSSSPIT, + MT_BOSSTARGET, + MT_SPAWNSHOT, + MT_SPAWNFIRE, + MT_BARREL, + MT_TROOPSHOT, + MT_HEADSHOT, + MT_ROCKET, + MT_PLASMA, + MT_BFG, + MT_ARACHPLAZ, + MT_PUFF, + MT_BLOOD, + MT_TFOG, + MT_IFOG, + MT_TELEPORTMAN, + MT_EXTRABFG, + MT_MISC0, + MT_MISC1, + MT_MISC2, + MT_MISC3, + MT_MISC4, + MT_MISC5, + MT_MISC6, + MT_MISC7, + MT_MISC8, + MT_MISC9, + MT_MISC10, + MT_MISC11, + MT_MISC12, + MT_INV, + MT_MISC13, + MT_INS, + MT_MISC14, + MT_MISC15, + MT_MISC16, + MT_MEGA, + MT_CLIP, + MT_MISC17, + MT_MISC18, + MT_MISC19, + MT_MISC20, + MT_MISC21, + MT_MISC22, + MT_MISC23, + MT_MISC24, + MT_MISC25, + MT_CHAINGUN, + MT_MISC26, + MT_MISC27, + MT_MISC28, + MT_SHOTGUN, + MT_SUPERSHOTGUN, + MT_MISC29, + MT_MISC30, + MT_MISC31, + MT_MISC32, + MT_MISC33, + MT_MISC34, + MT_MISC35, + MT_MISC36, + MT_MISC37, + MT_MISC38, + MT_MISC39, + MT_MISC40, + MT_MISC41, + MT_MISC42, + MT_MISC43, + MT_MISC44, + MT_MISC45, + MT_MISC46, + MT_MISC47, + MT_MISC48, + MT_MISC49, + MT_MISC50, + MT_MISC51, + MT_MISC52, + MT_MISC53, + MT_MISC54, + MT_MISC55, + MT_MISC56, + MT_MISC57, + MT_MISC58, + MT_MISC59, + MT_MISC60, + MT_MISC61, + MT_MISC62, + MT_MISC63, + MT_MISC64, + MT_MISC65, + MT_MISC66, + MT_MISC67, + MT_MISC68, + MT_MISC69, + MT_MISC70, + MT_MISC71, + MT_MISC72, + MT_MISC73, + MT_MISC74, + MT_MISC75, + MT_MISC76, + MT_MISC77, + MT_MISC78, + MT_MISC79, + MT_MISC80, + MT_MISC81, + MT_MISC82, + MT_MISC83, + MT_MISC84, + MT_MISC85, + MT_MISC86, + MT_PUSH, /* controls push source - phares */ + MT_PULL, /* controls pull source - phares 3/20/98 */ + + /* proff 11/22/98: Andy Baker's stealth monsters (next 12) + * cph - moved below the MBF stuff, no need to displace them */ + MT_STEALTHBABY, + MT_STEALTHVILE, + MT_STEALTHBRUISER, + MT_STEALTHHEAD, + MT_STEALTHCHAINGUY, + MT_STEALTHSERGEANT, + MT_STEALTHKNIGHT, + MT_STEALTHIMP, + MT_STEALTHFATSO, + MT_STEALTHUNDEAD, + MT_STEALTHSHOTGUY, + MT_STEALTHZOMBIE, + + NUMMOBJTYPES // Counter of how many there are +} mobjtype_t; + +/******************************************************************** + * Definition of the Thing structure + ********************************************************************/ +/* Note that these are only indices to the state, sound, etc. arrays + * and not actual pointers. Most can be set to zero if the action or + * sound doesn't apply (like lamps generally don't attack or whistle). + */ + +typedef struct +{ + short doomednum; + /* Thing number used in id's editor, and now + probably by every other editor too */ + short spawnstate; + /* The state (frame) index when this Thing is + first created */ + short spawnhealth; /* The initial hit points for this Thing */ + short seestate; /* The state when it sees you or wakes up */ + short seesound; /* The sound it makes when waking */ + short reactiontime; /* How many tics it waits after it wakes up + before it will start to attack, in normal + skills (halved for nightmare) */ + short attacksound; /* The sound it makes when it attacks */ + short painstate; /* The state to indicate pain */ + short painchance; /* A number that is checked against a random + number 0-255 to see if the Thing is supposed + to go to its painstate or not. Note this + has absolutely nothing to do with the chance + it will get hurt, just the chance of it + reacting visibly. */ + short painsound; /* The sound it emits when it feels pain */ + short meleestate; /* Melee==close attack */ + short missilestate; /* What states to use when it's in the air, if + in fact it is ever used as a missile */ + short deathstate; /* What state begins the death sequence */ + short xdeathstate; /* What state begins the horrible death sequence + like when a rocket takes out a trooper */ + short deathsound; /* The death sound. See also A_Scream() in + p_enemy.c for some tweaking that goes on + for certain monsters */ + int speed; /* How fast it moves. Too fast and it can miss + collision logic. */ + int radius; /* An often incorrect radius */ + int height; /* An often incorrect height, used only to see + if a monster can enter a sector */ + int mass; /* How much an impact will move it. Cacodemons + seem to retreat when shot because they have + very little mass and are moved by impact */ + short damage; /* If this is a missile, how much does it hurt? */ + short activesound; /* What sound it makes wandering around, once + in a while. Chance is 3/256 it will. */ + unsigned int flags; /* Bit masks for lots of things. See p_mobj.h */ + short raisestate; /* The first state for an Archvile or respawn + resurrection. Zero means it won't come + back to life. */ +} mobjinfo_t; + +/* See p_mobj_h for addition more technical info */ +extern const mobjinfo_t mobjinfo[NUMMOBJTYPES]; + +#endif diff --git a/doom/src/pdoom/Doom/include/lprintf.h b/doom/src/pdoom/Doom/include/lprintf.h new file mode 100644 index 0000000..55aede4 --- /dev/null +++ b/doom/src/pdoom/Doom/include/lprintf.h @@ -0,0 +1,98 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Declarations etc. for logical console output + * + *-----------------------------------------------------------------------------*/ + +#ifndef __LPRINTF__ +#define __LPRINTF__ +#include "printf.h" +#include +typedef enum /* Logical output levels */ +{ + LO_INFO = 1, /* One of these is used in each physical output */ + LO_CONFIRM = 2, /* call. Which are output, or echoed to console */ + LO_WARN = 4, /* if output redirected is determined by the */ + LO_ERROR = 8, /* global masks: cons_output_mask,cons_error_mask. */ + LO_FATAL = 16, LO_DEBUG = 32, LO_ALWAYS = 64, +} OutputLevels; + +//extern int lprintf(OutputLevels pri, const char *fmt, ...); +#ifdef PARADISE_DEV +void plat_plog(int n); +#define PLOG(n) plat_plog(n) +#else +#define PLOG(n) +#endif +#ifdef PARADISE_DEV +void plat_mark(int line, const char *file); +#define lprintf(pri, fmt, ...) plat_mark(__LINE__, __FILE__) +#else +#define lprintf(pri, fmt, ...) printf(fmt, ## __VA_ARGS__) +#endif +#define MIN_DEMO_GAMETIC_TO_PRINT 0 +/* 1.7.2 DOOM_FREE: P_Random looked for a backslash in the file name on every call (about 15 KB backwards through the + * program part, for a debug print that is off): left out */ +#ifdef DOOM_FREE +#define PRND_SCAN 0 +#else +#define PRND_SCAN 1 +#endif + +#define DEBUG_DEMO 0 +#if DEBUG_DEMO +#define demodbgprintf printf +#else +#define demodbgprintf(...) +#endif + +/* killough 3/20/98: add const + * killough 4/25/98: add gcc attributes + * cphipps 01/11- moved from i_system.h */ +//void I_Error (const char *error, ...); +#ifdef PARADISE_DEV +void plat_error(int line, const char *file); +#define I_Error(...) plat_error(__LINE__, __FILE__) +#else +#define I_Error printf +#endif + +#endif diff --git a/doom/src/pdoom/Doom/include/m_bbox.h b/doom/src/pdoom/Doom/include/m_bbox.h new file mode 100644 index 0000000..151cd2e --- /dev/null +++ b/doom/src/pdoom/Doom/include/m_bbox.h @@ -0,0 +1,64 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Simple bounding box datatype and functions. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __M_BBOX__ +#define __M_BBOX__ + +#include +#include "m_fixed.h" + +/* Bounding box coordinate storage. */ +enum +{ + BOXTOP, BOXBOTTOM, BOXLEFT, BOXRIGHT +}; +/* bbox coordinates */ + +/* Bounding box functions. */ + +void M_ClearBox(fixed_t *box); + +void M_AddToBox(fixed_t *box, fixed_t x, fixed_t y); + +#endif diff --git a/doom/src/pdoom/Doom/include/m_cheat.h b/doom/src/pdoom/Doom/include/m_cheat.h new file mode 100644 index 0000000..1bfea68 --- /dev/null +++ b/doom/src/pdoom/Doom/include/m_cheat.h @@ -0,0 +1,8 @@ +#ifndef M_CHEAT_H +#define M_CHEAT_H + +#include "d_event.h" + +boolean C_Responder(event_t *ev); + +#endif // M_CHEAT_H diff --git a/doom/src/pdoom/Doom/include/m_fixed.h b/doom/src/pdoom/Doom/include/m_fixed.h new file mode 100644 index 0000000..b263ad1 --- /dev/null +++ b/doom/src/pdoom/Doom/include/m_fixed.h @@ -0,0 +1,167 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Fixed point arithemtics, implementation. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __M_FIXED__ +#define __M_FIXED__ + +#include "config.h" +#include "doomtype.h" +#include + +// to count divisions per frame +extern int divisions; +/* + * Fixed point, 32bit as 16.16. + */ + +#define FRACBITS 16 +#define FRACUNIT (1<> (8 * sizeof _t - 1); + return (_t ^ _s) - _s;*/ +} + +/* + * Fixed Point Multiplication + */ + +/* CPhipps - made __inline__ to inline, as specified in the gcc docs + * Also made const */ + +fixed_t CONSTFUNC FixedMul(fixed_t a, fixed_t b); + +/* + * Fixed Point Division + */ + +/* CPhipps - made __inline__ to inline, as specified in the gcc docs + * Also made const */ + +inline static fixed_t CONSTFUNC FixedDiv(fixed_t a, fixed_t b) +{ + + divisions++; + return ((unsigned)D_abs(a)>>14) >= (unsigned)D_abs(b) ? ((a^b)>>31) ^ INT_MAX : (fixed_t)(((int_64_t) a << FRACBITS) / b); + // this is much faster as we have a FPU.. + // float r = ((float) a) / b; +// return (fixed_t) 65536 * r; +} + +/* CPhipps - + * FixedMod - returns a % b, guaranteeing 0<=a 0 ? INT_MAX : -INT_MAX; + return (fixed_t) (0x100000000LL / v); +#else + float r; + r = 65536.0 / v; + result = (fixed_t) (r * 65536); + return result; +#endif +} +//Count leading zeros. 16bit. +inline static CONSTFUNC unsigned int clz16(unsigned int x) +{ + return __builtin_clz(x); +} + +//Approx fixed point divide of a/b using reciprocal. -> a * (1/b). +inline static CONSTFUNC fixed_t FixedApproxDiv(fixed_t a, fixed_t b) +{ + divisions++; + +#ifdef PARADISE + if (!b) return 0; + return (fixed_t) (((int_64_t) a << FRACBITS) / b); +#else + float r = ((float) a) / b; + return (fixed_t) 65536 * r; +#endif +// return FixedMul(a, FixedReciprocal(b)); +} + +#endif diff --git a/doom/src/pdoom/Doom/include/m_menu.h b/doom/src/pdoom/Doom/include/m_menu.h new file mode 100644 index 0000000..459fcb6 --- /dev/null +++ b/doom/src/pdoom/Doom/include/m_menu.h @@ -0,0 +1,162 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Menu widget stuff, episode selection and such. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __M_MENU__ +#define __M_MENU__ + +#include "d_event.h" + +// +// MENUS +// +// Called by main loop, +// saves config file and calls I_Quit when user exits. +// Even when the menu is not displayed, +// this can resize the view and change game parameters. +// Does all the real work of the menu interaction. + +boolean M_Responder(event_t *ev); + +// Called by main loop, +// only used for menu (skull cursor) animation. + +void M_Ticker(void); + +// Called by main loop, +// draws the menus directly into the screen buffer. + +void M_Drawer(void); + +// Called by D_DoomMain, +// loads the config file. + +void M_Init(void); + +// Called by intro code to force menu up upon a keypress, +// does nothing if menu is already up. + +void M_StartControlPanel(void); + +void M_ResetMenu(void); // killough 11/98: reset main menu ordering + +void M_DrawCredits(void); // killough 11/98 + +void M_ChangeGamma(int choice); // Adafruit Clue onboard button gamma adjust + +/**************************** + * + * The following #defines are for the m_flags field of each item on every + * Setup Screen. They can be OR'ed together where appropriate + */ + +#define S_HILITE 0x1 // Cursor is sitting on this item +#define S_SELECT 0x2 // We're changing this item +#define S_TITLE 0x4 // Title item +#define S_YESNO 0x8 // Yes or No item +#define S_CRITEM 0x10 // Message color +#define S_COLOR 0x20 // Automap color +#define S_CHAT 0x40 // Chat String +#define S_RESET 0x80 // Reset to Defaults Button +#define S_PREV 0x100 // Previous menu exists +#define S_NEXT 0x200 // Next menu exists +#define S_KEY 0x400 // Key Binding +#define S_WEAP 0x800 // Weapon # +#define S_NUM 0x1000 // Numerical item +#define S_SKIP 0x2000 // Cursor can't land here +#define S_KEEP 0x4000 // Don't swap key out +#define S_END 0x8000 // Last item in list (dummy) +#define S_LEVWARN 0x10000// killough 8/30/98: Always warn about pending change +#define S_PRGWARN 0x20000// killough 10/98: Warn about change until next run +#define S_BADVAL 0x40000// killough 10/98: Warn about bad value +#define S_FILE 0x80000// killough 10/98: Filenames +#define S_LEFTJUST 0x100000 // killough 10/98: items which are left-justified +#define S_CREDIT 0x200000 // killough 10/98: credit +#define S_BADVID 0x400000 // killough 12/98: video mode change error +#define S_CHOICE 0x800000 // this item has several values + +/* S_SHOWDESC = the set of items whose description should be displayed + * S_SHOWSET = the set of items whose setting should be displayed + * S_STRING = the set of items whose settings are strings -- killough 10/98: + * S_HASDEFPTR = the set of items whose var field points to default array + */ + +#define S_SHOWDESC (S_TITLE|S_YESNO|S_CRITEM|S_COLOR|S_CHAT|S_RESET|S_PREV|S_NEXT|S_KEY|S_WEAP|S_NUM|S_FILE|S_CREDIT|S_CHOICE) + +#define S_SHOWSET (S_YESNO|S_CRITEM|S_COLOR|S_CHAT|S_KEY|S_WEAP|S_NUM|S_FILE|S_CHOICE) + +#define S_STRING (S_CHAT|S_FILE) + +#define S_HASDEFPTR (S_STRING|S_YESNO|S_NUM|S_WEAP|S_COLOR|S_CRITEM|S_CHOICE) + +#define SAVESTRINGSIZE 8 + +// +// MENU TYPEDEFS +// + +typedef struct +{ + short status; // 0 = no cursor here, 1 = ok, 2 = arrows ok + char name[10]; + + // choice = menu item #. + // if status = 2, + // choice=0:leftarrow,1:rightarrow + void (*routine)(int choice); +} menuitem_t; + +typedef struct menu_s +{ + short numitems; // # of menu items + const menuitem_t *menuitems; // menu items + void (*routine)(); // draw routine + short x; + short y; // x,y of menu + const struct menu_s *prevMenu; // previous menu + short previtemOn; +} menu_t; + +extern char savegamestrings[8][8]; + +#endif diff --git a/doom/src/pdoom/Doom/include/m_misc.h b/doom/src/pdoom/Doom/include/m_misc.h new file mode 100644 index 0000000..6c0a87e --- /dev/null +++ b/doom/src/pdoom/Doom/include/m_misc.h @@ -0,0 +1,51 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * External non-system-specific stuff, like storing config settings, + * simple file handling, and saving screnshots. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __M_MISC__ +#define __M_MISC__ + +#include "doomtype.h" + +#endif diff --git a/doom/src/pdoom/Doom/include/m_random.h b/doom/src/pdoom/Doom/include/m_random.h new file mode 100644 index 0000000..d587bf6 --- /dev/null +++ b/doom/src/pdoom/Doom/include/m_random.h @@ -0,0 +1,62 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Functions to return random numbers. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __M_RANDOM__ +#define __M_RANDOM__ + +#include "doomtype.h" + +#include "doomtype.h" + +// Returns a number from 0 to 255, +// from a lookup table. +int M_Random(void); + +// As M_Random, but used only by the play simulation. +int P_Random(const char *, int, const char *); + +// Fix randoms for demos. +void M_ClearRandom(void); + +#endif diff --git a/doom/src/pdoom/Doom/include/m_swap.h b/doom/src/pdoom/Doom/include/m_swap.h new file mode 100644 index 0000000..cba7b61 --- /dev/null +++ b/doom/src/pdoom/Doom/include/m_swap.h @@ -0,0 +1,110 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Endianess handling, swapping 16bit and 32bit. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __M_SWAP__ +#define __M_SWAP__ + +#ifdef __GNUG__ +#pragma interface +#endif + +/* CPhipps - now the endianness handling, converting input or output to/from + * the machine's endianness to that wanted for this type of I/O + * + * To find our own endianness, use config.h + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +/* Endianess handling. */ + +/* cph - First the macros to do the actual byte swapping */ + +/* leban + * rather than continue the confusing tradition of redefining the + * stardard macro, we now present the doom_ntoh and doom_hton macros.... + * might as well use the xdoom macros. + */ + +#ifndef doom_swap_l +#define doom_swap_l(x) \ + ((long int)((((unsigned long int)(x) & 0x000000ffU) << 24) | \ + (((unsigned long int)(x) & 0x0000ff00U) << 8) | \ + (((unsigned long int)(x) & 0x00ff0000U) >> 8) | \ + (((unsigned long int)(x) & 0xff000000U) >> 24))) +#endif + +#ifndef doom_swap_s +#define doom_swap_s(x) \ + ((short int)((((unsigned short int)(x) & 0x00ff) << 8) | \ + (((unsigned short int)(x) & 0xff00) >> 8))) +#endif + +/* Macros are named doom_XtoYT, where + * X is thing to convert from, Y is thing to convert to, chosen from + * n for network, h for host (i.e our machine's), w for WAD (Doom data files) + * and T is the type, l or s for long or short + * + * CPhipps - all WADs and network packets will be little endian for now + * Use separate macros so network could be converted to big-endian later. + */ + +#define doom_wtohl(x) (long int)(x) +#define doom_htowl(x) (long int)(x) +#define doom_wtohs(x) (short int)(x) +#define doom_htows(x) (short int)(x) + +#define doom_ntohl(x) (long int)(x) +#define doom_htonl(x) (long int)(x) +#define doom_ntohs(x) (short int)(x) +#define doom_htons(x) (short int)(x) + +/* CPhipps - Boom's old LONG and SHORT endianness macros are for WAD stuff */ + +#define LONG(x) doom_wtohl(x) +#define SHORT(x) doom_htows(x) + +#endif diff --git a/doom/src/pdoom/Doom/include/p_enemy.h b/doom/src/pdoom/Doom/include/p_enemy.h new file mode 100644 index 0000000..dbcc236 --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_enemy.h @@ -0,0 +1,129 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Enemy thinking, AI. + * Action Pointer Functions + * that are associated with states/frames. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_ENEMY__ +#define __P_ENEMY__ + +#include "p_mobj.h" + +void P_NoiseAlert(mobj_t *target, mobj_t *emmiter); +void P_SpawnBrainTargets(void); /* killough 3/26/98: spawn icon landings */ + +typedef struct brain_t +{ /* killough 3/26/98: global state of boss brain */ + int easy, targeton; +} brain_t; + +// ******************************************************************** +// Function addresses or Code Pointers +// ******************************************************************** +// These function addresses are the Code Pointers that have been +// modified for years by Dehacked enthusiasts. The new BEX format +// allows more extensive changes (see d_deh.c) + +// Doesn't work with g++, needs actionf_p1 +void A_Explode(); +void A_Pain(); +void A_PlayerScream(); +void A_Fall(); +void A_XScream(); +void A_Look(); +void A_Chase(); +void A_FaceTarget(); +void A_PosAttack(); +void A_Scream(); +void A_SPosAttack(); +void A_VileChase(); +void A_VileStart(); +void A_VileTarget(); +void A_VileAttack(); +void A_StartFire(); +void A_Fire(); +void A_FireCrackle(); +void A_Tracer(); +void A_SkelWhoosh(); +void A_SkelFist(); +void A_SkelMissile(); +void A_FatRaise(); +void A_FatAttack1(); +void A_FatAttack2(); +void A_FatAttack3(); +void A_BossDeath(); +void A_CPosAttack(); +void A_CPosRefire(); +void A_TroopAttack(); +void A_SargAttack(); +void A_HeadAttack(); +void A_BruisAttack(); +void A_SkullAttack(); +void A_Metal(); +void A_SpidRefire(); +void A_BabyMetal(); +void A_BspiAttack(); +void A_Hoof(); +void A_CyberAttack(); +void A_PainAttack(); +void A_PainDie(); +void A_KeenDie(); +void A_BrainPain(); +void A_BrainScream(); +void A_BrainDie(); +void A_BrainAwake(); +void A_BrainSpit(); +void A_SpawnSound(); +void A_SpawnFly(); +void A_BrainExplode(); +void A_Die(); +void A_Detonate(); /* killough 8/9/98: detonate a bomb or other device */ +void A_Mushroom(); /* killough 10/98: mushroom effect */ +void A_Spawn(); // killough 11/98 +void A_Turn(); // killough 11/98 +void A_Face(); // killough 11/98 +void A_Scratch(); // killough 11/98 +void A_PlaySound(); // killough 11/98 +void A_RandomJump(); // killough 11/98 + +#endif // __P_ENEMY__ diff --git a/doom/src/pdoom/Doom/include/p_inter.h b/doom/src/pdoom/Doom/include/p_inter.h new file mode 100644 index 0000000..7afc65d --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_inter.h @@ -0,0 +1,85 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Thing events, and dehacked specified numbers controlling them. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_INTER__ +#define __P_INTER__ + +#include "d_player.h" +#include "p_mobj.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +/* Ty 03/09/98 Moved to an int in p_inter.c for deh and externalization */ +#define MAXHEALTH maxhealth + +/* follow a player exlusively for 3 seconds */ +#define BASETHRESHOLD (100) + +boolean P_GivePower(player_t*, int); +void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher); +void P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, int damage); + +/* killough 5/2/98: moved from d_deh.c, g_game.c, m_misc.c, others: */ + +extern const int god_health; /* Ty 03/09/98 - deh support, see also p_inter.c */ +extern const int idfa_armor; +extern const int idfa_armor_class; +extern const int idkfa_armor; +extern const int idkfa_armor_class; /* Ty - end */ +/* Ty 03/13/98 - externalized initial settings for respawned player */ +extern const int initial_health; +extern const int initial_bullets; +extern const int maxhealth; +extern const int max_armor; +extern const int green_armor_class; +extern const int blue_armor_class; +extern const int max_soul; +extern const int soul_health; +extern const int mega_health; +extern const int bfgcells; +extern const int maxammo[], clipammo[]; + +#endif diff --git a/doom/src/pdoom/Doom/include/p_map.h b/doom/src/pdoom/Doom/include/p_map.h new file mode 100644 index 0000000..be7b76c --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_map.h @@ -0,0 +1,86 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Map functions + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_MAP__ +#define __P_MAP__ + +#include "r_defs.h" +#include "d_player.h" + +#define USERANGE (64*FRACUNIT) +#define MELEERANGE (64*FRACUNIT) +#define MISSILERANGE (32*64*FRACUNIT) +#define LOOKRANGE (768*FRACUNIT) // was 768 in GBA + +// MAXRADIUS is for precalculated sector block boxes the spider demon +// is larger, but we do not have any moving sectors nearby +#define MAXRADIUS (32*FRACUNIT) + +// killough 3/15/98: add fourth argument to P_TryMove +boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean dropoff); + +// killough 8/9/98: extra argument for telefragging +boolean P_TeleportMove(mobj_t *thing, fixed_t x, fixed_t y, boolean boss); +void P_SlideMove(mobj_t *mo); +boolean P_CheckSight(mobj_t *t1, mobj_t *t2); +void P_UseLines(player_t *player); + +// killough 8/2/98: add 'mask' argument to prevent friends autoaiming at others +fixed_t P_AimLineAttack(mobj_t *t1, angle_t angle, fixed_t distance, uint_64_t mask); + +void P_LineAttack(mobj_t *t1, angle_t angle, fixed_t distance, fixed_t slope, int damage); +void P_RadiusAttack(mobj_t *spot, mobj_t *source, int damage); +boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y); + +//jff 3/19/98 P_CheckSector(): new routine to replace P_ChangeSector() +boolean P_CheckSector(sector_t *sector, boolean crunch); +void P_DelSeclist(msecnode_t*); // phares 3/16/98 +void P_CreateSecNodeList(mobj_t*, fixed_t, fixed_t); // phares 3/14/98 +boolean Check_Sides(mobj_t*, int, int); // phares + +/* cphipps 2004/08/30 */ +void P_MapStart(void); +void P_MapEnd(void); + +#endif // __P_MAP__ diff --git a/doom/src/pdoom/Doom/include/p_maputl.h b/doom/src/pdoom/Doom/include/p_maputl.h new file mode 100644 index 0000000..de721ae --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_maputl.h @@ -0,0 +1,106 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Map utility functions + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_MAPUTL__ +#define __P_MAPUTL__ + +#include "r_defs.h" + +/* mapblocks are used to check movement against lines and things */ +#define MAPBLOCKUNITS 128 +#define MAPBLOCKSIZE (MAPBLOCKUNITS*FRACUNIT) +#define MAPBLOCKSHIFT (FRACBITS+7) +#define MAPBMASK (MAPBLOCKSIZE-1) +#define MAPBTOFRAC (MAPBLOCKSHIFT-FRACBITS) + +#define PT_ADDLINES 1 +#define PT_ADDTHINGS 2 +#define PT_EARLYOUT 4 + +#define MAXINTERCEPTS 64 + +typedef struct +{ + fixed_t x; + fixed_t y; + fixed_t dx; + fixed_t dy; +} divline_t; + +typedef struct +{ + fixed_t frac; /* along trace line */ + //boolean isaline; + union + { + mobj_t *thing; + const line_t *line; + } d; +} intercept_t; + +typedef struct +{ + fixed_t sightzstart, t2x, t2y; // eye z of looker + divline_t strace; // from t1 to t2 + fixed_t topslope, bottomslope; // slopes to top and bottom of target + fixed_t bbox[4]; + fixed_t maxz, minz; // cph - z optimisations for 2sided lines +} los_t; + +typedef boolean (*traverser_t)(intercept_t *in); + +fixed_t CONSTFUNC P_AproxDistance(fixed_t dx, fixed_t dy); +int P_PointOnLineSide(fixed_t x, fixed_t y, const line_t *line); +int P_BoxOnLineSide(const fixed_t *tmbox, const line_t *ld); +/* cph - old compatibility version below */ +fixed_t P_InterceptVector2(const divline_t *v2, const divline_t *v1); + +void P_LineOpening(const line_t *linedef); +void P_UnsetThingPosition(mobj_t *thing); +void P_SetThingPosition(mobj_t *thing); +boolean P_BlockLinesIterator(int x, int y, boolean func(const line_t*)); +boolean P_BlockThingsIterator(int x, int y, boolean func(mobj_t*)); +boolean P_PathTraverse(fixed_t x1, fixed_t y1, fixed_t x2, fixed_t y2, int flags, boolean trav(intercept_t*)); + +#endif /* __P_MAPUTL__ */ diff --git a/doom/src/pdoom/Doom/include/p_mobj.h b/doom/src/pdoom/Doom/include/p_mobj.h new file mode 100644 index 0000000..71d5fa6 --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_mobj.h @@ -0,0 +1,507 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Map Objects, MObj, definition and handling. + * + * next-hack: optimzed a lot this, bringing the structure size from 140 b + * down to 92 bytes. Added also static_mobj_t, which uses only 44 bytes. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_MOBJ__ +#define __P_MOBJ__ +// Basics. +#include "tables.h" +#include "m_fixed.h" + +// We need the thinker_t stuff. +#include "d_think.h" + +// We need the WAD data structure for Map things, +// from the THINGS lump. +#include "doomdata.h" + +// States are tied to finite states are +// tied to animation frames. +// Needs precompiled tables/data structures. +#include "info.h" + +// +// NOTES: mobj_t +// +// mobj_ts are used to tell the refresh where to draw an image, +// tell the world simulation when objects are contacted, +// and tell the sound driver how to position a sound. +// +// The refresh uses the next and prev links to follow +// lists of things in sectors as they are being drawn. +// The sprite, frame, and angle elements determine which patch_t +// is used to draw the sprite if it is visible. +// The sprite and frame values are allmost allways set +// from state_t structures. +// The statescr.exe utility generates the states.h and states.c +// files that contain the sprite/frame numbers from the +// statescr.txt source file. +// The xyz origin point represents a point at the bottom middle +// of the sprite (between the feet of a biped). +// This is the default origin position for patch_ts grabbed +// with lumpy.exe. +// A walking creature will have its z equal to the floor +// it is standing on. +// +// The sound code uses the x,y, and subsector fields +// to do stereo positioning of any sound effited by the mobj_t. +// +// The play simulation uses the blocklinks, x,y,z, radius, height +// to determine when mobj_ts are touching each other, +// touching lines in the map, or hit by trace lines (gunshots, +// lines of sight, etc). +// The mobj_t->flags element has various bit flags +// used by the simulation. +// +// Every mobj_t is linked into a single sector +// based on its origin coordinates. +// The subsector_t is found with R_PointInSubsector(x,y), +// and the sector_t can be found with subsector->sector. +// The sector links are only used by the rendering code, +// the play simulation does not care about them at all. +// +// Any mobj_t that needs to be acted upon by something else +// in the play world (block movement, be shot, etc) will also +// need to be linked into the blockmap. +// If the thing has the MF_NOBLOCK flag set, it will not use +// the block links. It can still interact with other things, +// but only as the instigator (missiles will run into other +// things, but nothing can run into a missile). +// Each block in the grid is 128*128 units, and knows about +// every line_t that it contains a piece of, and every +// interactable mobj_t that has its origin contained. +// +// A valid mobj_t is a mobj_t that has the proper subsector_t +// filled in for its xy coordinates and is linked into the +// sector from which the subsector was made, or has the +// MF_NOSECTOR flag set (the subsector_t needs to be valid +// even if MF_NOSECTOR is set), and is linked into a blockmap +// block or has the MF_NOBLOCKMAP flag set. +// Links should only be modified by the P_[Un]SetThingPosition() +// functions. +// Do not change the MF_NO? flags while a thing is valid. +// +// Any questions? +// + +// +// Misc. mobj flags +// + +// Call P_SpecialThing when touched. +#define MF_SPECIAL (unsigned int)(0x0000000000000001) +// Blocks. +#define MF_SOLID (unsigned int)(0x0000000000000002) +// Can be hit. +#define MF_SHOOTABLE (unsigned int)(0x0000000000000004) +// Don't use the sector links (invisible but touchable). +#define MF_NOSECTOR (unsigned int)(0x0000000000000008) +// Don't use the blocklinks (inert but displayable) +#define MF_NOBLOCKMAP (unsigned int)(0x0000000000000010) + +// Not to be activated by sound, deaf monster. +#define MF_AMBUSH (unsigned int)(0x0000000000000020) +// Will try to attack right back. +#define MF_JUSTHIT (unsigned int)(0x0000000000000040) +// Will take at least one step before attacking. +#define MF_JUSTATTACKED (unsigned int)(0x0000000000000080) +// On level spawning (initial position), +// hang from ceiling instead of stand on floor. +#define MF_SPAWNCEILING (unsigned int)(0x0000000000000100) +// Don't apply gravity (every tic), +// that is, object will float, keeping current height +// or changing it actively. +#define MF_NOGRAVITY (unsigned int)(0x0000000000000200) + +// Movement flags. +// This allows jumps from high places. +#define MF_DROPOFF (unsigned int)(0x0000000000000400) +// For players, will pick up items. +#define MF_PICKUP (unsigned int)(0x0000000000000800) +// Player cheat. ??? +#define MF_NOCLIP (unsigned int)(0x0000000000001000) +// Player: keep info about sliding along walls. +#define MF_SLIDE (unsigned int)(0x0000000000002000) +// Allow moves to any height, no gravity. +// For active floaters, e.g. cacodemons, pain elementals. +#define MF_FLOAT (unsigned int)(0x0000000000004000) +// Don't cross lines +// ??? or look at heights on teleport. +#define MF_TELEPORT (unsigned int)(0x0000000000008000) +// Don't hit same species, explode on block. +// Player missiles as well as fireballs of various kinds. +#define MF_MISSILE (unsigned int)(0x0000000000010000) +// Dropped by a demon, not level spawned. +// E.g. ammo clips dropped by dying former humans. +#define MF_DROPPED (unsigned int)(0x0000000000020000) +// Use fuzzy draw (shadow demons or spectres), +// temporary player invisibility powerup. +#define MF_SHADOW (unsigned int)(0x0000000000040000) +// Flag: don't bleed when shot (use puff), +// barrels and shootable furniture shall not bleed. +#define MF_NOBLOOD (unsigned int)(0x0000000000080000) +// Don't stop moving halfway off a step, +// that is, have dead bodies slide down all the way. +#define MF_CORPSE (unsigned int)(0x0000000000100000) +// Floating to a height for a move, ??? +// don't auto float to target's height. +#define MF_INFLOAT (unsigned int)(0x0000000000200000) + +// On kill, count this enemy object +// towards intermission kill total. +// Happy gathering. +#define MF_COUNTKILL (unsigned int)(0x0000000000400000) + +// On picking up, count this item object +// towards intermission item total. +#define MF_COUNTITEM (unsigned int)(0x0000000000800000) + +// Special handling: skull in flight. +// Neither a cacodemon nor a missile. +#define MF_SKULLFLY (unsigned int)(0x0000000001000000) + +// Don't spawn this object +// in death match mode (e.g. key cards). +#define MF_NOTDMATCH (unsigned int)(0x0000000002000000) + +// Player sprites in multiplayer modes are modified +// using an internal color lookup table for re-indexing. +// If 0x4 0x8 or 0xc, +// use a translation table for player colormaps +#define MF_TRANSLATION (unsigned int)(0x000000000c000000) +#define MF_TRANSLATION1 (unsigned int)(0x0000000004000000) +#define MF_TRANSLATION2 (unsigned int)(0x0000000008000000) +// Hmm ???. +#define MF_TRANSSHIFT 26 + +//#define MF_UNUSED2 (unsigned int)(0x0000000010000000) +#define MF_DECORATION (unsigned int)(0x0000000010000000) // next-hack. + +#define MF_STATIC (MF_DECORATION | MF_SPECIAL) // next-hack. Objects with this flags go in the static mobj zone, and occupy less RAM + +#define MF_UNUSED3 (unsigned int)(0x0000000020000000) + +// Translucent sprite? // phares +#define MF_TRANSLUCENT (unsigned int)(0x0000000040000000) + +#define MF_FRIEND (unsigned int)(0x0000000080000000) + +// killough 9/15/98: Same, but internal flags, not intended for .deh +// (some degree of opaqueness is good, to avoid compatibility woes) + +enum +{ + MIF_FALLING = 1 // Object is falling +}; + +// Map Object definition. +// +// +// killough 2/20/98: +// +// WARNING: Special steps must be taken in p_saveg.c if C pointers are added to +// this mobj_s struct, or else savegames will crash when loaded. See p_saveg.c. +// Do not add "struct mobj_s *fooptr" without adding code to p_saveg.c to +// convert the pointers to ordinals and back for savegames. This was the whole +// reason behind monsters going to sleep when loading savegames (the "target" +// pointer was simply nullified after loading, to prevent Doom from crashing), +// and the whole reason behind loadgames crashing on savegames of AV attacks. +// + +// killough 9/8/98: changed some fields to shorts, +// for better memory usage (if only for cache). +/* cph 2006/08/28 - move Prev[XYZ] fields to the end of the struct. Add any + * other new fields to the end, and make sure you don't break savegames! */ + +// 18/06/2021 next-hack. New Simplicity Studio 5.2 comes with a newer GNU +// toolchain version and it complains that member thinker might be unaligned as +// mobj_t and static_mobj_t are packed. +// We could pass simply the mobj address, and cast it to thinker_t*, but it is +// better to use unpacked structures at this point. Noticeably, there should +// not be any change in size because we carefully we reordered members to prevent +// paddings but to be sure we don't accidentally mess, we declare our expected +// size here, and an array that has null size if the size is correct, otherwise +// it will have a negative size, generating an error. +// +#define MOBJ_SIZE 92 +#define STATIC_MOBJ_SIZE 44 +// +typedef struct mobj_s +{ + // WARNING: the order of these variables is important! It must be kept the same as static_mobj + // List: thinker links. + thinker_t thinker; + // killough 11/98: the lowest floor over all contacted Sectors. + unsigned int flags; // must be 32bit at least + // Interaction info, by BLOCKMAP. + // Links in blocks (if needed). + unsigned short bnext_sptr; + unsigned short bprev_sptr; + // sector linked list. Note: short pointers. + unsigned short snext_sptr; + unsigned short sprev_sptr; + // a linked list of sectors where this object appears + // For movement checking. + short tics:14; // state tic counter + unsigned short lastlook:2; + uint8_t type; // less than 255 mobjtypes. + uint8_t sprite; // used to find patch_t and flip value + // + uint16_t frame; // might be ORed with FF_FULLBRIGHT (0x8000) but we do not need an int + unsigned short state_idx :11; // there are less than 2048 states + //short movedir; // 0-8 + + // + unsigned short subsector_sptr; + unsigned short touching_sectorlist_sptr; + // + // Info for drawing: position. + fixed_t x; + fixed_t y; + fixed_t z; + // + // The closest interval over all contacted Sectors. + fixed_t ceilingz; + fixed_t floorz; + fixed_t dropoffz; + + // + uint8_t height_s; // we could reduce this too + uint8_t radiusb; // now it is a byte... + + int16_t health; // max is 4000 but we need a negative value + + // AFTER THIS LINE, THE SUBSEQUENT PARAMETERS ARE MISSING IN THE STATIC MOBJ TYPE + //More drawing info: to determine current sprite. + angle_t angle; // orientation + // + + // Momentums, used to update position. + fixed_t momx; + fixed_t momy; + fixed_t momz; + // Additional info record for player avatars only. + // Only valid if type == MT_PLAYER + unsigned short player_sptr; + // new field: last known enemy -- killough 2/15/98 + //struct mobj_s* lastenemy; + unsigned short lastenemy_sptr; + // + // Thing being chased/attacked (or NULL), + // also the originator for missiles. + //struct mobj_s* target; + unsigned short target_sptr; + // Thing being chased/attacked for tracers. + //struct mobj_s* tracer; + unsigned short tracer_sptr; + // + // + // const state_t* state; + // + // Movement direction, movement generation (zig-zagging). + int movecount :12; // when 0, select a new dir + int strafecount :12; // killough 9/8/98: monster strafing + int movedir :5; // 0-8 + + // Reaction time: if non 0, don't attack yet. + // Used by player to freeze a bit after teleporting. + // short reactiontime; + uint8_t reactiontime; + // + // If >0, the current target will be chased no + // matter what (even if shot by another object) + uint8_t threshold; // could be uint8_t + // + // killough 9/9/98: How long a monster pursues a target. + uint8_t pursuecount; + uint8_t dummy; + +} mobj_t; +// +typedef struct static_mobj_s +{ + // WARNING: the order of these variables is important! It must be kept the same as static_mobj + // List: thinker links. + thinker_t thinker; + // The closest interval over all contacted Sectors. + // killough 11/98: the lowest floor over all contacted Sectors. + unsigned int flags; // must be 32bit at least + // Interaction info, by BLOCKMAP. + // Links in blocks (if needed). + unsigned short bnext_sptr; + unsigned short bprev_sptr; + // sector linked list. Note: short pointers. + unsigned short snext_sptr; + unsigned short sprev_sptr; + // a linked list of sectors where this object appears + // For movement checking. + short tics:14; // state tic counter + unsigned short lastlook:2; + uint8_t type; // less than 255 mobjtypes. + // Actually we do not really need a sprite, it is used very seldom + uint8_t sprite; // used to find patch_t and flip value + // + uint16_t frame; // might be ORed with FF_FULLBRIGHT (0x8000) but we do not need an int + unsigned short state_idx :11; // there are less than 2048 states + //short movedir; // 0-8 + + // + unsigned short subsector_sptr; + unsigned short touching_sectorlist_sptr; + // + // Info for drawing: position. + fixed_t x; + fixed_t y; + fixed_t z; +} static_mobj_t; + +static inline fixed_t getMobjHeight(mobj_t *pmobj) +{ + if (!(pmobj->flags & MF_STATIC)) + return pmobj->height_s << FRACBITS; + else + return mobjinfo[pmobj->type].height; +} +static inline fixed_t getMobjRadius(mobj_t *pmobj) +{ + if (!(pmobj->flags & MF_STATIC)) + return pmobj->radiusb << FRACBITS; + else + return mobjinfo[pmobj->type].radius; + +} +static inline const mobjinfo_t* getMobjInfo(mobj_t *pmobj) +{ + return &mobjinfo[pmobj->type]; +} +static inline mobj_t* getLastEnemy(mobj_t *pmobj) +{ + return (mobj_t*) getLongPtr(pmobj->lastenemy_sptr); +} +static inline mobj_t* getTracer(mobj_t *pmobj) +{ + return (mobj_t*) getLongPtr(pmobj->tracer_sptr); +} +static inline mobj_t* getTarget(mobj_t *pmobj) +{ + return (mobj_t*) getLongPtr(pmobj->target_sptr); +} +static inline mobj_t* getSNext(mobj_t *pmobj) +{ + return (mobj_t*) getLongPtr(pmobj->snext_sptr); +} +static inline mobj_t* getSPrev(mobj_t *pmobj) +{ + return (mobj_t*) getLongPtr(pmobj->sprev_sptr); +} +static inline mobj_t* getBNext(mobj_t *pmobj) +{ + return (mobj_t*) getLongPtr(pmobj->bnext_sptr); +} +static inline mobj_t* getBPrev(mobj_t *pmobj) +{ + return (mobj_t*) getLongPtr(pmobj->bprev_sptr); +} + +static inline struct player_s* getMobjPlayer(mobj_t *pmobj) +{ + return (struct player_s*) getLongPtr(pmobj->player_sptr); +} +static inline const state_t* getMobjState(mobj_t *pmobj) +{ + unsigned short index = pmobj->state_idx; + if (index >= NUMSTATES || index == S_NULL) // TODO: is really needed this one? + return NULL; + return &states[index]; +} +// External declarations (fomerly in p_local.h) -- killough 5/2/98 + +#define VIEWHEIGHT (41*FRACUNIT) + +#define GRAVITY FRACUNIT +#define MAXMOVE (30*FRACUNIT) + +#define ONFLOORZ INT_MIN +#define ONCEILINGZ INT_MAX + +// Time interval for item respawning. +#define ITEMQUESIZE 32 + +#define FLOATSPEED (FRACUNIT*4) +#define STOPSPEED (FRACUNIT/16) + +// killough 11/98: +// For torque simulation: + +#define OVERDRIVE 6 +#define MAXGEAR (OVERDRIVE+16) + +// killough 11/98: +// Whether an object is "sentient" or not. Used for environmental influences. +#define sentient(mobj) ((mobj)->health > 0 && (mobj)->info->seestate) + +void P_RespawnSpecials(void); +mobj_t* P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type); +static_mobj_t* P_SpawnStaticMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type); // 2021-03-13 next-hack +void P_RemoveMobj(mobj_t *th); +void P_RemoveStaticMobj(static_mobj_t *mobj); // 2021-03-13 next-hack + +boolean P_SetMobjState(mobj_t *mobj, statenum_t state); + +void P_MobjThinker(mobj_t *mobj); +void P_MobjBrainlessThinker(mobj_t *mobj); + +void P_SpawnPuff(fixed_t x, fixed_t y, fixed_t z); +void P_SpawnBlood(fixed_t x, fixed_t y, fixed_t z, int damage); +mobj_t* P_SpawnMissile(mobj_t *source, mobj_t *dest, mobjtype_t type); +void P_SpawnPlayerMissile(mobj_t *source, mobjtype_t type); +boolean P_IsDoomnumAllowed(int doomnum); +void P_SpawnMapThing(const mapthing_t *mthing); +void P_SpawnPlayer(int n, const mapthing_t *mthing); +void P_CheckMissileSpawn(mobj_t*); // killough 8/2/98 +void P_ExplodeMissile(mobj_t*); // killough +#endif + diff --git a/doom/src/pdoom/Doom/include/p_pspr.h b/doom/src/pdoom/Doom/include/p_pspr.h new file mode 100644 index 0000000..a1c8d48 --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_pspr.h @@ -0,0 +1,132 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Sprite animation. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_PSPR__ +#define __P_PSPR__ + +/* Basic data types. + * Needs fixed point, and BAM angles. */ + +#include "m_fixed.h" + +#include "tables.h" + +/* Needs to include the precompiled sprite animation tables. + * + * Header generated by multigen utility. + * This includes all the data for thing animation, + * i.e. the Thing Atrributes table and the Frame Sequence table. + */ + +#include "info.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +/* + * Frame flags: + * handles maximum brightness (torches, muzzle flare, light sources) + */ + +#define FF_FULLBRIGHT 0x8000 /* flag in thing->frame */ +#define FF_FRAMEMASK 0x7fff + +/* + * Overlay psprites are scaled shapes + * drawn directly on the view screen, + * coordinates are given for a 320*200 view screen. + */ + +typedef enum +{ + ps_weapon, ps_flash, NUMPSPRITES +} psprnum_t; + +typedef struct +{ + const state_t *state; /* a NULL state means not active */ + int tics; + fixed_t sx; + fixed_t sy; +} pspdef_t; + +extern const int weapon_preferences[NUMWEAPONS + 1]; /* killough 5/2/98 */ +int P_WeaponPreferred(int w1, int w2); + +struct player_s; +int P_SwitchWeapon(struct player_s *player); +boolean P_CheckAmmo(struct player_s *player); +void P_SetupPsprites(struct player_s *curplayer); +void P_MovePsprites(struct player_s *curplayer); +void P_DropWeapon(struct player_s *player); + +int P_WeaponCycleUp(struct player_s *player); +int P_WeaponCycleDown(struct player_s *player); + +void A_Light0(); +void A_WeaponReady(); +void A_Lower(); +void A_Raise(); +void A_Punch(); +void A_ReFire(); +void A_FirePistol(); +void A_Light1(); +void A_FireShotgun(); +void A_Light2(); +void A_FireShotgun2(); +void A_CheckReload(); +void A_OpenShotgun2(); +void A_LoadShotgun2(); +void A_CloseShotgun2(); +void A_FireCGun(); +void A_GunFlash(); +void A_FireMissile(); +void A_Saw(); +void A_FirePlasma(); +void A_BFGsound(); +void A_FireBFG(); +void A_BFGSpray(); + +#endif diff --git a/doom/src/pdoom/Doom/include/p_setup.h b/doom/src/pdoom/Doom/include/p_setup.h new file mode 100644 index 0000000..0145a6c --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_setup.h @@ -0,0 +1,57 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Setup a game, startup stuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_SETUP__ +#define __P_SETUP__ + +#include "p_mobj.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +void P_SetupLevel(int episode, int map, int playermask, skill_t skill); +void P_Init(void); /* Called by startup code. */ + +#endif diff --git a/doom/src/pdoom/Doom/include/p_spec.h b/doom/src/pdoom/Doom/include/p_spec.h new file mode 100644 index 0000000..b5e4461 --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_spec.h @@ -0,0 +1,992 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: definitions, declarations and prototypes for specials + * + *-----------------------------------------------------------------------------*/ +// TODO: A lot to optimize here. +#ifndef __P_SPEC__ +#define __P_SPEC__ + +#include "r_defs.h" +#include "d_player.h" + +// Define values for map objects +#define MO_TELEPORTMAN 14 + +// p_floor + +#define ELEVATORSPEED (FRACUNIT*4) +#define FLOORSPEED FRACUNIT + +// p_ceilng + +#define CEILSPEED FRACUNIT +#define CEILWAIT 150 + +// p_doors + +#define VDOORSPEED (FRACUNIT*2) +#define VDOORWAIT 150 + +// p_plats + +#define PLATWAIT 3 +#define PLATSPEED FRACUNIT + +// p_switch + +// 4 players, 4 buttons each at once, max. +// killough 2/14/98: redefine in terms of MAXPLAYERS +#define MAXBUTTONS (MAXPLAYERS*4) +#define MAXSWITCHES 50 + +// 1 second, in ticks. +#define BUTTONTIME TICRATE + +// p_lights + +#define GLOWSPEED 8 +#define STROBEBRIGHT 5 +#define FASTDARK 15 +#define SLOWDARK 35 + +//jff 3/14/98 add bits and shifts for generalized sector types + +#define DAMAGE_MASK 0x60 +#define DAMAGE_SHIFT 5 +#define SECRET_MASK 0x80 +#define SECRET_SHIFT 7 +#define FRICTION_MASK 0x100 +#define FRICTION_SHIFT 8 +#define PUSH_MASK 0x200 +#define PUSH_SHIFT 9 + +//jff 02/04/98 Define masks, shifts, for fields in +// generalized linedef types + +#define GenEnd 0x8000 +#define GenFloorBase 0x6000 +#define GenCeilingBase 0x4000 +#define GenDoorBase 0x3c00 +#define GenLockedBase 0x3800 +#define GenLiftBase 0x3400 +#define GenStairsBase 0x3000 +#define GenCrusherBase 0x2F80 + +#define TriggerType 0x0007 +#define TriggerTypeShift 0 + +// define masks and shifts for the floor type fields + +#define FloorCrush 0x1000 +#define FloorChange 0x0c00 +#define FloorTarget 0x0380 +#define FloorDirection 0x0040 +#define FloorModel 0x0020 +#define FloorSpeed 0x0018 + +#define FloorCrushShift 12 +#define FloorChangeShift 10 +#define FloorTargetShift 7 +#define FloorDirectionShift 6 +#define FloorModelShift 5 +#define FloorSpeedShift 3 + +// define masks and shifts for the ceiling type fields + +#define CeilingCrush 0x1000 +#define CeilingChange 0x0c00 +#define CeilingTarget 0x0380 +#define CeilingDirection 0x0040 +#define CeilingModel 0x0020 +#define CeilingSpeed 0x0018 + +#define CeilingCrushShift 12 +#define CeilingChangeShift 10 +#define CeilingTargetShift 7 +#define CeilingDirectionShift 6 +#define CeilingModelShift 5 +#define CeilingSpeedShift 3 + +// define masks and shifts for the lift type fields + +#define LiftTarget 0x0300 +#define LiftDelay 0x00c0 +#define LiftMonster 0x0020 +#define LiftSpeed 0x0018 + +#define LiftTargetShift 8 +#define LiftDelayShift 6 +#define LiftMonsterShift 5 +#define LiftSpeedShift 3 + +// define masks and shifts for the stairs type fields + +#define StairIgnore 0x0200 +#define StairDirection 0x0100 +#define StairStep 0x00c0 +#define StairMonster 0x0020 +#define StairSpeed 0x0018 + +#define StairIgnoreShift 9 +#define StairDirectionShift 8 +#define StairStepShift 6 +#define StairMonsterShift 5 +#define StairSpeedShift 3 + +// define masks and shifts for the crusher type fields + +#define CrusherSilent 0x0040 +#define CrusherMonster 0x0020 +#define CrusherSpeed 0x0018 + +#define CrusherSilentShift 6 +#define CrusherMonsterShift 5 +#define CrusherSpeedShift 3 + +// define masks and shifts for the door type fields + +#define DoorDelay 0x0300 +#define DoorMonster 0x0080 +#define DoorKind 0x0060 +#define DoorSpeed 0x0018 + +#define DoorDelayShift 8 +#define DoorMonsterShift 7 +#define DoorKindShift 5 +#define DoorSpeedShift 3 + +// define masks and shifts for the locked door type fields + +#define LockedNKeys 0x0200 +#define LockedKey 0x01c0 +#define LockedKind 0x0020 +#define LockedSpeed 0x0018 + +#define LockedNKeysShift 9 +#define LockedKeyShift 6 +#define LockedKindShift 5 +#define LockedSpeedShift 3 + +// define names for the TriggerType field of the general linedefs + +typedef enum +{ + WalkOnce, + WalkMany, + SwitchOnce, + SwitchMany, + GunOnce, + GunMany, + PushOnce, + PushMany, +} triggertype_e; + +// define names for the Speed field of the general linedefs + +typedef enum +{ + SpeedSlow, SpeedNormal, SpeedFast, SpeedTurbo, +} motionspeed_e; + +// define names for the Target field of the general floor + +typedef enum +{ + FtoHnF, FtoLnF, FtoNnF, FtoLnC, FtoC, FbyST, Fby24, Fby32, +} floortarget_e; + +// define names for the Changer Type field of the general floor + +typedef enum +{ + FNoChg, FChgZero, FChgTxt, FChgTyp, +} floorchange_e; + +// define names for the Change Model field of the general floor + +typedef enum +{ + FTriggerModel, FNumericModel, +} floormodel_t; + +// define names for the Target field of the general ceiling + +typedef enum +{ + CtoHnC, CtoLnC, CtoNnC, CtoHnF, CtoF, CbyST, Cby24, Cby32, +} ceilingtarget_e; + +// define names for the Changer Type field of the general ceiling + +typedef enum +{ + CNoChg, CChgZero, CChgTxt, CChgTyp, +} ceilingchange_e; + +// define names for the Change Model field of the general ceiling + +typedef enum +{ + CTriggerModel, CNumericModel, +} ceilingmodel_t; + +// define names for the Target field of the general lift + +typedef enum +{ + F2LnF, F2NnF, F2LnC, LnF2HnF, +} lifttarget_e; + +// define names for the door Kind field of the general ceiling + +typedef enum +{ + OdCDoor, ODoor, CdODoor, CDoor, +} doorkind_e; + +// define names for the locked door Kind field of the general ceiling + +typedef enum +{ + AnyKey, RCard, BCard, YCard, RSkull, BSkull, YSkull, AllKeys, +} keykind_e; + +////////////////////////////////////////////////////////////////// +// +// enums for classes of linedef triggers +// +////////////////////////////////////////////////////////////////// + +//jff 2/23/98 identify the special classes that can share sectors + +typedef enum +{ + floor_special, ceiling_special, lighting_special, +} special_e; + +//jff 3/15/98 pure texture/type change for better generalized support +typedef enum +{ + trigChangeOnly, numChangeOnly, +} change_e; + +// p_plats + +typedef enum +{ + up, down, waiting, in_stasis +} plat_e; + +typedef enum +{ + perpetualRaise, + downWaitUpStay, + raiseAndChange, + raiseToNearestAndChange, + blazeDWUS, + genLift, //jff added to support generalized Plat types + genPerpetual, + toggleUpDn, //jff 3/14/98 added to support instant toggle type + +} plattype_e; + +// p_doors + +typedef enum +{ + normal, + close30ThenOpen, + dclose, + dopen, + raiseIn5Mins, + blazeRaise, + blazeOpen, + blazeClose, + + //jff 02/05/98 add generalize door types + genRaise, + genBlazeRaise, + genOpen, + genBlazeOpen, + genClose, + genBlazeClose, + genCdO, + genBlazeCdO, +} vldoor_e; + +// p_ceilng + +typedef enum +{ + lowerToFloor, + raiseToHighest, + lowerToLowest, + lowerToMaxFloor, + lowerAndCrush, + crushAndRaise, + fastCrushAndRaise, + silentCrushAndRaise, + + //jff 02/04/98 add types for generalized ceiling mover + genCeiling, + genCeilingChg, + genCeilingChg0, + genCeilingChgT, + + //jff 02/05/98 add types for generalized ceiling mover + genCrusher, + genSilentCrusher, + +} ceiling_e; + +// p_floor + +typedef enum +{ + // lower floor to highest surrounding floor + lowerFloor, + + // lower floor to lowest surrounding floor + lowerFloorToLowest, + + // lower floor to highest surrounding floor VERY FAST + turboLower, + + // raise floor to lowest surrounding CEILING + raiseFloor, + + // raise floor to next highest surrounding floor + raiseFloorToNearest, + + //jff 02/03/98 lower floor to next lowest neighbor + lowerFloorToNearest, + + //jff 02/03/98 lower floor 24 absolute + lowerFloor24, + + //jff 02/03/98 lower floor 32 absolute + lowerFloor32Turbo, + + // raise floor to shortest height texture around it + raiseToTexture, + + // lower floor to lowest surrounding floor + // and change floorpic + lowerAndChange, + + raiseFloor24, + + //jff 02/03/98 raise floor 32 absolute + raiseFloor32Turbo, + + raiseFloor24AndChange, + raiseFloorCrush, + + // raise to next highest floor, turbo-speed + raiseFloorTurbo, + donutRaise, + raiseFloor512, + + //jff 02/04/98 add types for generalized floor mover + genFloor, + genFloorChg, + genFloorChg0, + genFloorChgT, + + //new types for stair builders + buildStair, + genBuildStair, +} floor_e; + +typedef enum +{ + build8, // slowly build by 8 + turbo16 // quickly build by 16 + +} stair_e; + +typedef enum +{ + elevateUp, elevateDown, elevateCurrent, +} elevator_e; + +////////////////////////////////////////////////////////////////// +// +// general enums +// +////////////////////////////////////////////////////////////////// + +// texture type enum +typedef enum +{ + top, middle, bottom + +} bwhere_e; + +// crush check returns +typedef enum +{ + ok, crushed, pastdest +} result_e; + +////////////////////////////////////////////////////////////////// +// +// linedef and sector special data types +// +////////////////////////////////////////////////////////////////// + +// p_switch + +// switch animation structure type + +#if defined(__MWERKS__) +#pragma options align=packed +#endif + +typedef struct +{ + char name1[9]; + char name2[9]; + short episode; +} PACKEDATTR switchlist_t; //jff 3/23/98 pack to read from memory + +#if defined(__MWERKS__) +#pragma options align=reset +#endif + +typedef struct +{ + const line_t *line; + int btimer; + degenmobj_t *soundorg; + short btexture; + byte where; +} button_t; + +// p_lights + +typedef struct +{ + thinker_t thinker; + sector_t *sector; + short count; + byte maxlight; + byte minlight; + +} fireflicker_t; + +typedef struct +{ + thinker_t thinker; + sector_t *sector; + short count; + byte maxlight; + byte minlight; + short maxtime; + short mintime; + +} lightflash_t; + +typedef struct +{ + thinker_t thinker; + sector_t *sector; + short count; + byte minlight; + byte maxlight; + short darktime; + short brighttime; + +} strobe_t; + +typedef struct +{ + thinker_t thinker; + sector_t *sector; + byte minlight; + byte maxlight; + short direction; +} glow_t; + +// p_plats +typedef struct +{ + thinker_t thinker; + sector_t *sector; + fixed_t speed; + fixed_t low; + fixed_t high; + short wait; + short count; + uint8_t status; + uint8_t oldstatus; + boolean crush; + short tag; + byte type; + struct platlist *list; // killough +} plat_t; + +// New limit-free plat structure -- killough + +typedef struct platlist +{ + plat_t *plat; + struct platlist *next, **prev; +} platlist_t; + +// p_ceilng +#if 1 +typedef struct +{ + thinker_t thinker; + vldoor_e type; + sector_t *sector; + fixed_t topheight; + fixed_t speed; + + // 1 = up, 0 = waiting at top, -1 = down + int direction; + + // tics to wait at the top + int topwait; + // (keep in case a door going down is reset) + // when it reaches 0, start going down + int topcountdown; + + //jff 1/31/98 keep track of line door is triggered by + const line_t *line; + + /* killough 10/98: sector tag for gradual lighting effects */ + int lighttag; +} vldoor_t; +#else + +typedef struct +{ + thinker_t thinker; + sector_t* sector; + fixed_t topheight; + fixed_t speed; + + //jff 1/31/98 keep track of line door is triggered by + const line_t *line; + + // tics to wait at the top + short topwait; + // (keep in case a door going down is reset) + // when it reaches 0, start going down + short topcountdown; + + + /* killough 10/98: sector tag for gradual lighting effects */ + short lighttag; + // 1 = up, 0 = waiting at top, -1 = down + char direction; + byte type; + +} vldoor_t; +#endif +// p_doors + +typedef struct +{ + thinker_t thinker; + ceiling_e type; + sector_t *sector; + fixed_t bottomheight; + fixed_t topheight; + fixed_t speed; + fixed_t oldspeed; + struct ceilinglist *list; // jff 2/22/98 copied from killough's plats + + //jff 02/04/98 add these to support ceiling changers + short newspecial; // was int! + short oldspecial; //jff 3/14/98 add to fix bug in change transfers + short texture; + // ID + short tag; + + // 1 = up, 0 = waiting, -1 = down + signed char direction; + signed char olddirection; + boolean crush; +} ceiling_t; + +typedef struct ceilinglist +{ + ceiling_t *ceiling; + struct ceilinglist *next, **prev; +} ceilinglist_t; + +// p_floor + +typedef struct +{ + thinker_t thinker; + fixed_t floordestheight; + fixed_t speed; +// sector_t* sector; + unsigned short sector_sptr; + short newspecial; + short oldspecial; //jff 3/14/98 add to fix bug in change transfers + short texture; + int8_t direction; + int8_t type; + boolean crush; +} floormove_t; +static inline sector_t* getFloorMoveSector(floormove_t *p_fm) +{ + return (sector_t*) getLongPtr(p_fm->sector_sptr); +} + +typedef struct +{ + thinker_t thinker; + sector_t *sector; + fixed_t floordestheight; + fixed_t ceilingdestheight; + fixed_t speed; + signed char direction; + byte type; +} elevator_t; + +// p_spec + +// killough 3/7/98: Add generalized scroll effects + +typedef struct +{ + thinker_t thinker; // Thinker structure for scrolling + int affectee; // Number of affected sidedef, sector, tag, or whatever +} scroll_t; + +// phares 3/12/98: added new model of friction for ice/sludge effects + +typedef struct +{ + //thinker_t thinker; // Thinker structure for friction + int friction; // friction value (E800 = normal) + //int movefactor; // inertia factor when adding to momentum + int affectee; // Number of affected sector +} friction_t; + +// phares 3/20/98: added new model of Pushers for push/pull effects +enum +{ + p_push, p_pull, p_wind, p_current, +}; +typedef struct +{ + thinker_t thinker; // Thinker structure for Pusher + mobj_t *source; // Point source if point pusher + short x_mag; // X Strength + short y_mag; // Y Strength + short magnitude; // Vector strength for point pusher + short radius; // Effective radius for point pusher + short x; // X of point source if point pusher + short y; // Y of point source if point pusher + short affectee; // Number of affected sector + byte type; +} pusher_t; + +// +// Animating textures and planes +// There is another anim_t used in wi_stuff, unrelated. +// +typedef struct +{ + int picnum :12; + int basepic :10; + int numpics :10; + short speed :15; + short istexture :1; +} __attribute__ ((packed)) anim_t; + +// +// source animation definition +// +// + +typedef struct +{ + signed char istexture; //jff 3/23/98 make char for comparison // cph - make signed + char endname[9]; // if false, it is a flat + char startname[9]; + short speed; +} PACKEDATTR animdef_t; //jff 3/23/98 pack to read from memory + +#define MAXANIMS 32 + +//////////////////////////////////////////////////////////////// +// +// Linedef and sector special utility function prototypes +// +//////////////////////////////////////////////////////////////// + +int twoSided(int sector, int line); + +side_t* getSide(int currentSector, int line, int side); + +fixed_t P_FindLowestFloorSurrounding(sector_t *sec); + +fixed_t P_FindHighestFloorSurrounding(sector_t *sec); + +fixed_t P_FindNextHighestFloor(sector_t *sec, int currentheight); + +fixed_t P_FindNextLowestFloor(sector_t *sec, int currentheight); + +fixed_t P_FindLowestCeilingSurrounding(sector_t *sec); // jff 2/04/98 + +fixed_t P_FindHighestCeilingSurrounding(sector_t *sec); // jff 2/04/98 + +fixed_t P_FindNextLowestCeiling(sector_t *sec, int currentheight); // jff 2/04/98 + +fixed_t P_FindNextHighestCeiling(sector_t *sec, int currentheight); // jff 2/04/98 + +fixed_t P_FindShortestTextureAround(int secnum); // jff 2/04/98 + +fixed_t P_FindShortestUpperAround(int secnum); // jff 2/04/98 + +sector_t* P_FindModelFloorSector(fixed_t floordestheight, int secnum); //jff 02/04/98 + +sector_t* P_FindModelCeilingSector(fixed_t ceildestheight, int secnum); //jff 02/04/98 + +int P_FindSectorFromLineTag(const line_t *line, int start); // killough 4/17/98 + +int P_FindLineFromLineTag(const line_t *line, int start); // killough 4/17/98 + +int P_FindMinSurroundingLight(sector_t *sector, int max); + +sector_t* getNextSector(const line_t *line, sector_t *sec); + +int P_CheckTag(const line_t *line); // jff 2/27/98 + +boolean P_CanUnlockGenDoor(const line_t *line, player_t *player); + +boolean P_SectorActive(special_e t, const sector_t *s); + +boolean P_IsSecret(const sector_t *sec); + +boolean P_WasSecret(const sector_t *sec); + +void P_ChangeSwitchTexture(const line_t *line, int useAgain); + +//////////////////////////////////////////////////////////////// +// +// Linedef and sector special action function prototypes +// +//////////////////////////////////////////////////////////////// + +// p_lights + +void T_LightFlash(lightflash_t *flash); + +void T_StrobeFlash(strobe_t *flash); + +// jff 8/8/98 add missing thinker for flicker +void T_FireFlicker(fireflicker_t *flick); + +void T_Glow(glow_t *g); + +// p_plats + +void T_PlatRaise(plat_t *plat); + +// p_doors + +void T_VerticalDoor(vldoor_t *door); + +// p_ceilng + +void T_MoveCeiling(ceiling_t *ceiling); + +// p_floor + +result_e T_MovePlane(sector_t *sector, fixed_t speed, fixed_t dest, boolean crush, int floorOrCeiling, int direction); + +void T_MoveFloor(floormove_t *floor); + +void T_MoveElevator(elevator_t *elevator); + +// p_spec + +void T_Scroll(scroll_t*); // killough 3/7/98: scroll effect thinker + +//////////////////////////////////////////////////////////////// +// +// Linedef and sector special handler prototypes +// +//////////////////////////////////////////////////////////////// + +// p_telept + +int EV_Teleport(const line_t *line, int side, mobj_t *thing); + +// killough 2/14/98: Add silent teleporter +int EV_SilentTeleport(const line_t *line, int side, mobj_t *thing); + +// killough 1/31/98: Add silent line teleporter +int EV_SilentLineTeleport(const line_t *line, int side, mobj_t *thing, boolean reverse); + +// p_floor + +int +EV_DoElevator(const line_t *line, elevator_e type); + +int EV_BuildStairs(const line_t *line, stair_e type); + +int EV_DoFloor(const line_t *line, floor_e floortype); + +// p_ceilng + +int EV_DoCeiling(const line_t *line, ceiling_e type); + +int EV_CeilingCrushStop(const line_t *line); + +// p_doors + +int EV_VerticalDoor(const line_t *line, mobj_t *thing); + +int EV_DoDoor(const line_t *line, vldoor_e type); + +int EV_DoLockedDoor(const line_t *line, vldoor_e type, mobj_t *thing); + +// p_lights + +int EV_StartLightStrobing(const line_t *line); + +int EV_TurnTagLightsOff(const line_t *line); + +int EV_LightTurnOn(const line_t *line, int bright); + +int EV_LightTurnOnPartway(const line_t *line, fixed_t level); // killough 10/10/98 + +// p_floor + +int EV_DoChange(const line_t *line, change_e changetype); + +int EV_DoDonut(const line_t *line); + +// p_plats + +int EV_DoPlat(const line_t *line, plattype_e type, int amount); + +int EV_StopPlat(const line_t *line); + +// p_genlin + +int EV_DoGenFloor(const line_t *line); + +int EV_DoGenCeiling(const line_t *line); + +int EV_DoGenLift(const line_t *line); + +int EV_DoGenStairs(const line_t *line); + +int EV_DoGenCrusher(const line_t *line); + +int EV_DoGenDoor(const line_t *line); + +int EV_DoGenLockedDoor(const line_t *line); + +//////////////////////////////////////////////////////////////// +// +// Linedef and sector special thinker spawning +// +//////////////////////////////////////////////////////////////// + +// at game start +void P_InitPicAnims(void); + +void P_InitSwitchList(void); + +// at map load +void P_SpawnSpecials(void); + +// every tic +void P_UpdateSpecials(void); + +// when needed +boolean P_UseSpecialLine(mobj_t *thing, const line_t *line, int side); + +void P_ShootSpecialLine(mobj_t *thing, const line_t *line); + +void P_CrossSpecialLine(const line_t *line, int side, mobj_t *thing); + +void P_PlayerInSpecialSector(player_t *player); + +// p_lights + +void P_SpawnFireFlicker(sector_t *sector); + +void P_SpawnLightFlash(sector_t *sector); + +void P_SpawnStrobeFlash(sector_t *sector, int fastOrSlow, int inSync); + +void P_SpawnGlowingLight(sector_t *sector); + +// p_plats + +void P_AddActivePlat(plat_t *plat); + +void P_RemoveActivePlat(plat_t *plat); + +void P_RemoveAllActivePlats(void); // killough + +void P_ActivateInStasis(int tag); + +// p_doors + +void P_SpawnDoorCloseIn30(sector_t *sec); + +void P_SpawnDoorRaiseIn5Mins(sector_t *sec, int secnum); + +// p_ceilng + +void P_RemoveActiveCeiling(ceiling_t *ceiling); //jff 2/22/98 + +void P_RemoveAllActiveCeilings(void); //jff 2/22/98 + +void P_AddActiveCeiling(ceiling_t *c); + +int P_ActivateInStasisCeiling(const line_t *line); + +#endif diff --git a/doom/src/pdoom/Doom/include/p_tick.h b/doom/src/pdoom/Doom/include/p_tick.h new file mode 100644 index 0000000..348cc21 --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_tick.h @@ -0,0 +1,84 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Core thinker processing prototypes. + *-----------------------------------------------------------------------------*/ + +#ifndef __P_TICK__ +#define __P_TICK__ + +#include "d_think.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +/* Called by C_Ticker, can call G_PlayerExited. + * Carries out all thinking of monsters and players. */ + +void P_Ticker(void); + +void P_InitThinkers(void); +void P_AddThinker(thinker_t *thinker); +void P_RemoveThinker(thinker_t *thinker); +void P_RemoveStaticThinker(thinker_t *thinker); +void P_RemoveThinkerDelayed(thinker_t *thinker); // killough 4/25/98 +void P_RemoveStaticThinkerDelayed(thinker_t *thinker); // 2021-03-13 next-hack +void P_UpdateThinker(thinker_t *thinker); // killough 8/29/98 + +void P_RunThinkers(void); + +void P_SetTarget(mobj_t **mo, mobj_t *target); // killough 11/98 + +/* killough 8/29/98: threads of thinkers, for more efficient searches + * cph 2002/01/13: for consistency with the main thinker list, keep objects + * pending deletion on a class list too + */ +typedef enum +{ + th_all = 0, /* For P_NextThinker, indicates "any class" */ +} th_class; + +#define thinkercap _g->thinkerclasscap[th_all] + +/* cph 2002/01/13 - iterator for thinker lists */ +thinker_t* P_NextThinker(thinker_t*); + +#endif diff --git a/doom/src/pdoom/Doom/include/p_user.h b/doom/src/pdoom/Doom/include/p_user.h new file mode 100644 index 0000000..cdab447 --- /dev/null +++ b/doom/src/pdoom/Doom/include/p_user.h @@ -0,0 +1,56 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Player related stuff. + * Bobbing POV/weapon, movement. + * Pending weapon. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __P_USER__ +#define __P_USER__ + +#include "d_player.h" + +void P_PlayerThink(player_t *player); +void P_CalcHeight(player_t *player); +void P_Thrust(player_t *player, angle_t angle, fixed_t move); + +#endif /* __P_USER__ */ diff --git a/doom/src/pdoom/Doom/include/protocol.h b/doom/src/pdoom/Doom/include/protocol.h new file mode 100644 index 0000000..464c659 --- /dev/null +++ b/doom/src/pdoom/Doom/include/protocol.h @@ -0,0 +1,116 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Doom Network protocol packet definitions. + *-----------------------------------------------------------------------------*/ + +#include "doomtype.h" +#include "d_ticcmd.h" +#include "m_swap.h" + +enum packet_type_e +{ + PKT_INIT, // initial packet to server + PKT_SETUP, // game information packet + PKT_GO, // game has started + PKT_TICC, // tics from client + PKT_TICS, // tics from server + PKT_RETRANS, // Request for retransmission + PKT_EXTRA, // Extra info packet + PKT_QUIT, // Player quit game + PKT_DOWN, // Server downed + PKT_WAD, // Wad file request + PKT_BACKOFF, // Request for client back-off +}; + +typedef struct +{ + byte checksum; // Simple checksum of the entire packet + byte type; /* Type of packet */ + byte reserved[2]; /* Was random in prboom <=2.2.4, now 0 */ + unsigned tic; // Timestamp +}PACKEDATTR packet_header_t; + +static inline void packet_set(packet_header_t *p, enum packet_type_e t, unsigned long tic) +{ + p->tic = doom_htonl(tic); + p->type = t; + p->reserved[0] = 0; + p->reserved[1] = 0; +} + +#ifndef GAME_OPTIONS_SIZE +// From g_game.h +#define GAME_OPTIONS_SIZE 64 +#endif + +struct setup_packet_s +{ + byte players, yourplayer, skill, episode, level, deathmatch, complevel, + ticdup, extratic; + byte game_options[GAME_OPTIONS_SIZE]; + byte numwads; + byte wadnames[1]; // Actually longer +}; + +/* cph - convert network byte stream to usable ticcmd_t and visa-versa + * - the functions are functionally identical apart from parameters + * - the void* param can be unaligned. By using void* as the parameter + * it means gcc won't assume alignment so won't make false assumptions + * when optimising. So I'm told. + */ +inline static void RawToTic(ticcmd_t *dst, const void *src) +{ + memcpy(dst, src, sizeof *dst); + dst->angleturn = doom_ntohs(dst->angleturn); + dst->consistancy = doom_ntohs(dst->consistancy); +} + +inline static void TicToRaw(void *dst, const ticcmd_t *src) +{ + /* We have to make a copy of the source struct, then do byte swaps, + * and fnially copy to the destination (can't do the swaps in the + * destination, because it might not be aligned). + */ + ticcmd_t tmp = *src; + tmp.angleturn = doom_ntohs(tmp.angleturn); + tmp.consistancy = doom_ntohs(tmp.consistancy); + memcpy(dst, &tmp, sizeof tmp); +} diff --git a/doom/src/pdoom/Doom/include/r_data.h b/doom/src/pdoom/Doom/include/r_data.h new file mode 100644 index 0000000..950a5c2 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_data.h @@ -0,0 +1,104 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Refresh module, data I/O, caching, retrieval of graphics + * by name. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_DATA__ +#define __R_DATA__ + +#include "r_defs.h" +#include "r_state.h" +#include "r_patch.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +// A single patch from a texture definition, basically +// a rectangular area within the texture rectangle. +typedef struct +{ + short originx, originy; // Block origin, which has already accounted + const patch_t *patch; // for the internal origin of the patch. +} texpatch_t; + +// +// Texture definition. +// A DOOM wall texture is a list of patches +// which are to be combined in a predefined order. +// +typedef struct +{ + // 2021/03/06: next-hack removed name, useless + //const char* name; // Keep name for switch changing, etc. + //int next, index; // killough 1/31/98: used in hashing algorithm + // CPhipps - moved arrays with per-texture entries to elements here + unsigned short widthmask; + // CPhipps - end of additions + short width, height; + + unsigned char overlapped; + unsigned char patchcount; // All the patches[patchcount] are drawn + texpatch_t patches[1]; // back-to-front into the cached texture. +} texture_t; + +// I/O, setting up the stuff. +void R_InitData(void); + +// Retrieval. +// Floor/ceiling opaque texture tiles, +// lookup by name. For animation? +int R_FlatNumForName(const char *name); // killough -- const added + +// R_*TextureNumForName returns the texture number for the texture name, or NO_TEXTURE if +// there is no texture (i.e. "-") specified. +/* cph 2006/07/23 - defined value for no-texture marker (texture "-" in the WAD file) */ +#define NO_TEXTURE 0 +int R_CheckTextureNumForName(const char *name); + +const texture_t* R_GetTexture(int texture, boolean cacheToFlash, uint32_t *spaceRequired); +int R_LoadTextureByName(const char *tex_name, boolean cacheToFlash); +uint32_t getTextureStructSize(int texture_num); +void R_FillTextureHeightData(); + +#endif diff --git a/doom/src/pdoom/Doom/include/r_defs.h b/doom/src/pdoom/Doom/include/r_defs.h new file mode 100644 index 0000000..056b623 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_defs.h @@ -0,0 +1,635 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Refresh/rendering module, shared data struct definitions. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_DEFS__ +#define __R_DEFS__ + +// Screenwidth. +#include "doomdef.h" + +// Some more or less basic data types +// we depend on. +#include "m_fixed.h" + +// We rely on the thinker data struct +// to handle sound origins in sectors. +#include "d_think.h" + +// SECTORS do store MObjs anyway. +#include "p_mobj.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +// Silhouette, needed for clipping Segs (mainly) +// and sprites representing things. +#define SIL_NONE 0 +#define SIL_BOTTOM 1 +#define SIL_TOP 2 +#define SIL_BOTH 3 + +#define MAXDRAWSEGS 192 // same as doomhack GBA port + +#define MAXOPENINGS (SCREENWIDTH * 16) // same as doomhack GBA port + +#define MAXVISSPRITES 128 + +// +// INTERNAL MAP TYPES +// used by play and refresh +// + +// +// Your plain vanilla vertex. +// Note: transformed values not buffered locally, +// like some DOOM-alikes ("wt", "WebView") do. +// +typedef struct +{ + fixed_t x, y; +} vertex_t; + +// Each sector has a degenmobj_t in its center for sound origin purposes. +typedef struct +{ + fixed_t x; + fixed_t y; +} degenmobj_t; + +// +// The SECTORS record, at runtime. +// Stores things/mobjs. +// +#if 0 +typedef struct +{ + fixed_t floorheight; + fixed_t ceilingheight; + degenmobj_t soundorg; // origin for any sounds played by the sector + int validcount : 24; // if == validcount, already checked + int lightlevel:8; + + int linecount : 11; // 11 bit + int floorpic : 11; // 11 bit + int ceilingpic : 10; // 10 bit + + // thinker_t for reversable actions + //void *floordata; // jff 2/22/98 make thinkers on + unsigned short floordata_sptr; + //void *ceilingdata; // floors, ceilings, lighting, + unsigned short ceilingdata_sptr; + // list of mobjs that are at least partially in the sector + // thinglist is a subset of touching_thinglist +// mobj_t *thinglist; // list of mobjs in sector + //struct msecnode_s *touching_thinglist; // phares 3/14/98 + unsigned short touching_thinglist_sptr; + unsigned short thinglist_sptr; + // mobj_t *soundtarget; // thing that made a sound (or null) + unsigned short soundtarget_sptr; + //unsigned short thinglist_sptr; + // +// 2021-02-13 next-hack save some bytes... + short special; + short oldspecial; //jff 2/16/98 remembers if sector WAS secret (automap) + short tag; + //const struct line_s **lines; + packedAddress_t lines_ppptr; // packed pointer to packed address + + // short lightlevel; + // short soundtraversed; // 0 = untraversed, 1,2 = sndlines-1 + uint8_t soundtraversed; // 0 = untraversed, 1,2 = sndlines-1 + + +} sector_t; +#else +typedef struct +{ + fixed_t floorheight; + fixed_t ceilingheight; + degenmobj_t soundorg; // origin for any sounds played by the sector + int validcount :24; // if == validcount, already checked + int soundtraversed :8; // 0 = untraversed, 1,2 = sndlines-1 + + int linecount :12; // 11 bit + int floorpic :10; // 11 bit + int ceilingpic :10; // 10 bit + + // thinker_t for reversable actions + //void *floordata; // jff 2/22/98 make thinkers on + unsigned short floordata_sptr; + //void *ceilingdata; // floors, ceilings, lighting, + unsigned short ceilingdata_sptr; + // list of mobjs that are at least partially in the sector + // thinglist is a subset of touching_thinglist +// mobj_t *thinglist; // list of mobjs in sector + //struct msecnode_s *touching_thinglist; // phares 3/14/98 + unsigned short touching_thinglist_sptr; + unsigned short thinglist_sptr; + // mobj_t *soundtarget; // thing that made a sound (or null) + unsigned short soundtarget_sptr; + //unsigned short thinglist_sptr; + // +// 2021-02-13 next-hack save some bytes... + short special; + short oldspecial; //jff 2/16/98 remembers if sector WAS secret (automap) + short tag; + //const struct line_s **lines; + packedAddress_t lines_ppptr; // packed pointer to packed address + uint8_t lightlevel; + + // short lightlevel; + // short soundtraversed; // 0 = untraversed, 1,2 = sndlines-1 + +} sector_t; +#endif +static inline mobj_t* getSectorThingList(sector_t *psec) +{ + return (mobj_t*) getLongPtr(psec->thinglist_sptr); +} +static inline void* getSectorCeilingData(sector_t *psec) +{ + return (void*) getLongPtr(psec->ceilingdata_sptr); +} +static inline void* getSectorFloorData(sector_t *psec) +{ + return (void*) getLongPtr(psec->floordata_sptr); +} +//static inline packedAddress_t * getSectorLines(sector_t *psec) {return (packedAddress_t*) unpackAddress(psec->lines_ppptr);} +//static inline const struct line_s* getSectorLineByIndex(sector_t *psec, int i) {return (const struct line_s*) unpackAddress(getSectorLines(psec)[i]);} +static inline const struct line_s** getSectorLines(sector_t *psec) +{ + return (const struct line_s**) unpackAddress(psec->lines_ppptr); +} +static inline const struct line_s* getSectorLineByIndex(sector_t *psec, int i) +{ + return getSectorLines(psec)[i]; +} + +// +// The SideDef. +// + +typedef struct +{ +// 2021-02-13 next-hack: changed to reflect map side def, so we do not have to copy a lot of bytes in RAM + short textureoffset; + short rowoffset; + short toptexture; + short bottomtexture; + short midtexture; + short sector_num; // Front sector, towards viewer. + // sector_t* sector; // Sector the SideDef is facing. + // short textureoffset; // add this to the calculated texture column + // short rowoffset; // add this to the calculated texture top + // short toptexture; // Texture indices. We do not maintain names here. + // short bottomtexture; + // short midtexture; +} PACKEDATTR side_t; + +// +// Move clipping aid for LineDefs. +// +typedef enum +{ + ST_HORIZONTAL, ST_VERTICAL, ST_POSITIVE, ST_NEGATIVE +} slopetype_t; + +typedef enum +{ // cph: +/* // not used + RF_TOP_TILE = 1, // Upper texture needs tiling + // not used + RF_MID_TILE = 2, // Mid texture needs tiling + // Not used + RF_BOT_TILE = 4, // Lower texture needs tiling + RF_IGNORE = 8, // Renderer can skip this line + RF_CLOSED =16, // Line blocks view + RF_MAPPED =32 // Seen so show on automap.*/ +// 2020-03-14 next-hack changed value to fit 3 bits + RF_IGNORE = 1, // Renderer can skip this line + RF_CLOSED = 2, // Line blocks view + RF_MAPPED = 4 // Seen so show on automap.*/ + +} r_flags; + +//Runtime mutable data for lines. +#define VALIDCOUNT_MASK 0xFFff +#if !USE_SEPARATE_R_VALIDCOUNT +#define r_validcount validcount +#endif +typedef struct linedata_s +{ +// unsigned short validcount; // if == validcount, already checked +// unsigned short r_validcount; // cph: if == gametic, r_flags already done + uint32_t validcount :16; // if == validcount, already checked +#if USE_SEPARATE_R_VALIDCOUNT + uint32_t r_validcount :16; // cph: if == gametic, r_flags already done +#endif + uint32_t special :12; + uint32_t r_flags :3; +} PACKEDATTR linedata_t; + +typedef struct line_s +{ + vertex_t v1; + vertex_t v2; // Vertices, from v1 to v2. + unsigned int lineno; //line number. + + fixed_t dx, dy; // Precalculated v2 - v1 for side checking. + + unsigned short sidenum[2]; // Visual appearance: SideDefs. + fixed_t bbox[4]; //Line bounding box. + + unsigned short flags; // Animation related. + short const_special; + short tag; + short slopetype; // To aid move clipping. + +} line_t; + +//#define LN_FRONTSECTOR(l) (_g->sides[(l)->sidenum[0]].sector) +#define LN_FRONTSECTOR(l) (&_g->sectors[_g->sides[(l)->sidenum[0]].sector_num]) //nh: replaced to sector num (saves ram) +#define LN_BACKSECTOR(l) ((l)->sidenum[1] != NO_INDEX ? &_g->sectors[_g->sides[(l)->sidenum[1]].sector_num] : NULL) + +#define LN_SPECIAL(l) (_g->linedata[(l)->lineno].special) + +// phares 3/14/98 +// +// Sector list node showing all sectors an object appears in. +// +// There are two threads that flow through these nodes. The first thread +// starts at touching_thinglist in a sector_t and flows through the m_snext +// links to find all mobjs that are entirely or partially in the sector. +// The second thread starts at touching_sectorlist in an mobj_t and flows +// through the m_tnext links to find all sectors a thing touches. This is +// useful when applying friction or push effects to sectors. These effects +// can be done as thinkers that act upon all objects touching their sectors. +// As an mobj moves through the world, these nodes are created and +// destroyed, with the links changed appropriately. +// +// For the links, NULL means top or end of list. + +typedef struct msecnode_s +{ +// sector_t *m_sector; // a sector containing this object + unsigned short m_sector_sptr; +// struct mobj_s *m_thing; // this object + unsigned short m_thing_sptr; + //struct msecnode_s *m_tprev; // prev msecnode_t for this thing + unsigned short m_tprev_sptr; +// struct msecnode_s *m_tnext; // next msecnode_t for this thing + unsigned short m_tnext_sptr; +// struct msecnode_s *m_sprev; // prev msecnode_t for this sector + unsigned short m_sprev_sptr; +// struct msecnode_s *m_snext; // next msecnode_t for this sector + unsigned short m_snext_sptr; +// boolean visited; // killough 4/4/98, 4/7/98: used in search algorithms + +} __attribute__ ((aligned (4))) msecnode_t; +static inline sector_t* getMsecnodeSector(const msecnode_t *p_msn) +{ + return (sector_t*) getLongPtr(p_msn->m_sector_sptr); +} +static inline struct mobj_s* getMsecnodeThing(msecnode_t *p_msn) +{ + return (struct mobj_s*) getLongPtr(p_msn->m_thing_sptr); +} +static inline msecnode_t* getMsecnodeTPrev(msecnode_t *p_msn) +{ + return (msecnode_t*) getLongPtr(p_msn->m_tprev_sptr); +} +static inline msecnode_t* getMsecnodeTNext(const msecnode_t *p_msn) +{ + return (msecnode_t*) getLongPtr(p_msn->m_tnext_sptr); +} +static inline msecnode_t* getMsecnodeSPrev(msecnode_t *p_msn) +{ + return (msecnode_t*) getLongPtr(p_msn->m_sprev_sptr); +} +static inline msecnode_t* getMsecnodeSNext(msecnode_t *p_msn) +{ + return (msecnode_t*) getLongPtr(p_msn->m_snext_sptr); +} +// +static inline msecnode_t* getSectorTouchingThingList(sector_t *psec) +{ + return (msecnode_t*) getLongPtr(psec->touching_thinglist_sptr); +} + +// +// The LineSeg. +// + +/* + typedef struct + { + vertex_t *v1, *v2; + fixed_t offset; + angle_t angle; + side_t* sidedef; + const line_t* linedef; + + // Sector references. + // Could be retrieved from linedef, too + // (but that would be slower -- killough) + // backsector is NULL for one sided lines + + sector_t *frontsector, *backsector; + } seg_t; + */ + +// +// The LineSeg. +// +typedef struct +{ + vertex_t v1; + vertex_t v2; // Vertices, from v1 to v2. + + fixed_t offset; + angle_t angle; + + unsigned short sidenum; + unsigned short linenum; + + unsigned short frontsectornum; + unsigned short backsectornum; +} seg_t; + +#define SG_FRONTSECTOR(s) ((s)->frontsectornum != NO_INDEX ? &_g->sectors[(s)->frontsectornum] : NULL) +#define SG_BACKSECTOR(s) ((s)->backsectornum != NO_INDEX ? &_g->sectors[(s)->backsectornum] : NULL) + +// +// A SubSector. +// References a Sector. +// Basically, this is a list of LineSegs, +// indicating the visible walls that define +// (all or some) sides of a convex BSP leaf. +// + +typedef struct subsector_s +{ + sector_t *sector; + unsigned short numlines, firstline; +} subsector_t; + +static inline subsector_t* getSubSectorPtr(unsigned short shortPointer) +{ + return (subsector_t*) getLongPtr(shortPointer); +} +static inline subsector_t* getMobjSubsector(mobj_t *pmobj) +{ + return getSubSectorPtr(pmobj->subsector_sptr); +} +static inline subsector_t* setMobjSubesctor(mobj_t *pmobj, subsector_t *ss) +{ + pmobj->subsector_sptr = getShortPtr(ss); + return ss; +} + +// +// OTHER TYPES +// + +// This could be wider for >8 bit display. +// Indeed, true color support is posibble +// precalculating 24bpp lightmap/colormap LUT. +// from darkening PLAYPAL to all black. +// Could use even more than 32 levels. + +typedef byte lighttable_t; + +// +// Masked 2s linedefs +// + +typedef struct drawseg_s +{ + const seg_t *curline; + fixed_t scale1, scale2, scalestep; + fixed_t bsilheight; // do not clip sprites above this + fixed_t tsilheight; // do not clip sprites below this +// short *sprtopclip, *sprbottomclip; + short *maskedtexturecol; // dropoff overflow. NOTE: can't use short ptr, as it does not point to 4-byte aligned memory. + unsigned short sprtopclip_ssptr, sprbottomclip_ssptr; // short pointer to short + // Pointers to lists for sprite clipping, + // all three adjusted so [x1] is first value. + #if SCREENWIDTH > 255 + uint16_t x1, x2; + #else + uint8_t x1, x2; // the screen is 240 pix wide... + #endif + uint8_t silhouette; // 0=none, 1=bottom, 2=top, 3=both +} drawseg_t; + +// Patches. +// A patch holds one or more columns. +// Patches are used for sprites and all masked pictures, +// and we compose textures from the TEXTURE1/2 lists +// of patches. +typedef struct +{ + short width; // bounding box size + short height; + short leftoffset; // pixels to the left of origin + short topoffset; // pixels below the origin + int columnofs[8]; // only [width] used + // the [0] is &columnofs[width] +} patch_t; + +typedef struct +{ + short width; // bounding box size + short height; + short leftoffset; // pixels to the left of origin + short topoffset; // pixels below the origin +} patchsizeoffsets_t; // like patch, but only size and offset + +// posts are runs of non masked source pixels +typedef struct +{ + byte topdelta; // -1 is the last post in a column + byte length; // length data bytes follows +} post_t; + +// column_t is a list of 0 or more post_t, (byte)-1 terminated +typedef post_t column_t; + +// +// A vissprite_t is a thing that will be drawn during a refresh. +// i.e. a sprite object that is partly visible. +// + +typedef struct vissprite_s +{ + fixed_t gx, gy; // for line side calculation + fixed_t gz, gzt; // global bottom / top for silhouette clipping + fixed_t startfrac; // horizontal position of x1. We could reduce this... + fixed_t scale; + fixed_t xiscale; // negative if flipped + fixed_t texturemid; // we could reduce this if we need some bits... +// 2021/03/27 next-hack: removed iscale and calculated when necessary. Saved some bytes... +// fixed_t iscale; + // for color translation and shadow draw, maxbright frames as well +// const lighttable_t *colormap; + //const patch_t *patch; + uint32_t lumpNum; + // + uint8_t colormap_idx; + uint8_t mobjflags; + #if SCREENWIDTH > 255 + uint16_t x1, x2; + #else + uint8_t x1, x2; +#endif +} vissprite_t; + +// +// Sprites are patches with a special naming convention +// so they can be recognized by R_InitSprites. +// The base name is NNNNFx or NNNNFxFx, with +// x indicating the rotation, x = 0, 1-7. +// The sprite and frame specified by a thing_t +// is range checked at run time. +// A sprite is a patch_t that is assumed to represent +// a three dimensional object and may have multiple +// rotations pre drawn. +// Horizontal flipping is used to save space, +// thus NNNNF2F5 defines a mirrored patch. +// Some sprites will only have one picture used +// for all views: NNNNF0 +// + +typedef struct +{ + // Lump to use for view angles 0-7. + short lump[8]; + // Flip bit (1 = flip) to use for view angles 0-7. + //byte flip[8]; + byte flipmask; + + // If false use 0 for any position. + // Note: as eight entries are available, + // we might as well insert the same name eight times. + boolean rotate; + +} spriteframe_t; + +#define SPR_FLIPPED(s, r) (s->flipmask & (1 << r)) + +// +// A sprite definition: +// a number of animation frames. +// + +typedef struct +{ + short numframes; +#ifndef USE_SPRITEFRAME_SPTR + spriteframe_t *spriteframes; +#else + unsigned short spriteframes_sptr; +#endif +} spritedef_t __attribute__ ((aligned (4))); +static inline spriteframe_t* getSpriteFrames(const spritedef_t *p_sd) +{ +#ifndef USE_SPRITEFRAME_SPTR + return p_sd->spriteframes; +#else + return (spriteframe_t *) getLongPtr(p_sd->spriteframes_sptr); +#endif +} +// +// Now what is a visplane, anyway? +// +// Go to http://classicgaming.com/doom/editing/ to find out -- killough +// + +typedef struct visplane +{ +#if 1 + struct visplane *next; // Next visplane in hash chain -- killough + fixed_t height; + short picnum; + short minx, maxx; + byte modified; + byte lightlevel; + byte top[SCREENWIDTH]; + byte pad2; + byte pad3; + byte bottom[SCREENWIDTH]; + byte pad4; +#else + struct visplane *next; // Next visplane in hash chain -- killough + short picnum, lightlevel; + short minx, maxx; + fixed_t height; + unsigned int modified; + + //byte pad1; + // Here lies the rub for all + // dynamic resize/change of resolution. + byte top[SCREENWIDTH]; + byte pad2; + byte pad3; + // See above. + byte bottom[SCREENWIDTH]; + byte pad4; +#endif +} visplane_t; +static inline sector_t* getSectorPtr(unsigned short shortPointer) +{ + return (sector_t*) getLongPtr(shortPointer); +} +static inline msecnode_t* getTouchingSectorList(mobj_t *pmobj) +{ + return (msecnode_t*) getLongPtr(pmobj->touching_sectorlist_sptr); +} +static inline mobj_t* getSectorSoundTarget(sector_t *ps) +{ + return (mobj_t*) getLongPtr(ps->soundtarget_sptr); +} +//inline mobj_t * getSectorThingList(sector_t * ps) {return (mobj_t*) getLongPtr(ps->thinglist_sptr);} +#endif diff --git a/doom/src/pdoom/Doom/include/r_draw.h b/doom/src/pdoom/Doom/include/r_draw.h new file mode 100644 index 0000000..5e78b7b --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_draw.h @@ -0,0 +1,96 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * System specific interface stuff. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_DRAW__ +#define __R_DRAW__ + +#include "r_defs.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +// Packaged into a struct - POPE +typedef struct +{ + int x; + int yl; + int yh; + fixed_t iscale; + fixed_t texturemid; + + const byte *source; // first pixel in a column + + const lighttable_t *colormap; + const byte *translation; + +} draw_column_vars_t; + +void R_SetDefaultDrawColumnVars(draw_column_vars_t *dcvars); + +typedef struct +{ + unsigned int position; + unsigned int step; + const byte *source; // start of a 64*64 tile image + const lighttable_t *colormap; +} draw_span_vars_t; + +typedef struct +{ + uint8_t *byte_topleft; +} draw_vars_t; + +extern draw_vars_t drawvars; + +typedef void (*R_DrawColumn_f)(const draw_column_vars_t *dcvars); + +// Draw with color translation tables, +// for player sprite rendering, +// Green/Red/Blue/Indigo shirts. +void R_DrawTranslatedColumn(const draw_column_vars_t *dcvars); + +void R_InitBuffer(); + +#endif diff --git a/doom/src/pdoom/Doom/include/r_main.h b/doom/src/pdoom/Doom/include/r_main.h new file mode 100644 index 0000000..4aa3223 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_main.h @@ -0,0 +1,110 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Renderer main interface. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_MAIN__ +#define __R_MAIN__ + +#include "d_player.h" +#include "r_data.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +// +// Lighting LUT. +// Used for z-depth cuing per column/row, +// and other lighting effects (sector ambient, flash). +// + +extern const int viewheight; + +extern const int centery; + +extern const fixed_t projection; +extern const fixed_t iprojection; + +//Global vars. + +extern short numnodes; +extern const mapnode_t *nodes; + +extern fixed_t viewx, viewy, viewz; + +extern angle_t viewangle; + +//extern short *floorclip, *ceilingclip; + +extern const lighttable_t *fullcolormap; +//extern const lighttable_t *colormaps; +extern const lighttable_t *fixedcolormap; + +extern byte extralight; // bumped light from gun blasts + +extern const texture_t **textures; // proff - 04/05/2000 removed static for OpenGL +extern fixed_t *textureheight; //needed for texture pegging (and TFE fix - killough) + +extern short *flattranslation; // for global animation +extern short *texturetranslation; + +extern fixed_t basexscale, baseyscale; + +extern fixed_t viewcos, viewsin; + +// +// Utility functions. +// + +angle_t R_PointToAngle2(fixed_t x1, fixed_t y1, fixed_t x2, fixed_t y2); +subsector_t* R_PointInSubsector(fixed_t x, fixed_t y); + +// +// REFRESH - the actual rendering functions. +// + +void R_RenderPlayerView(player_t *player); // Called by G_Drawer. +void R_Init(void); // Called by startup code. +void R_SetupFrame(player_t *player); + +#endif diff --git a/doom/src/pdoom/Doom/include/r_patch.h b/doom/src/pdoom/Doom/include/r_patch.h new file mode 100644 index 0000000..7e9cdfb --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_patch.h @@ -0,0 +1,51 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + *-----------------------------------------------------------------------------*/ + +#ifndef R_PATCH_H +#define R_PATCH_H + +// Size query funcs +int R_NumPatchWidth(int lump); +int R_NumPatchHeight(int lump); +//#define R_NamePatchWidth(name) R_NumPatchWidth(W_GetNumForName(name)) +//#define R_NamePatchHeight(name) R_NumPatchHeight(W_GetNumForName(name)) + +#endif diff --git a/doom/src/pdoom/Doom/include/r_plane.h b/doom/src/pdoom/Doom/include/r_plane.h new file mode 100644 index 0000000..71091b8 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_plane.h @@ -0,0 +1,65 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Refresh, visplane stuff (floor, ceilings). + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_PLANE__ +#define __R_PLANE__ + +#include "r_data.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +void R_InitPlanes(void); +void R_ResetPlanes(); + +#define MAXVISPLANES 32 /* must be a power of 2 */ + +// killough -- hash function for visplanes +// Empirically verified to be fairly uniform: + +#define visplane_hash(picnum,lightlevel,height) \ + ((unsigned)((picnum)*3+(lightlevel)+(height)*7) & (MAXVISPLANES-1)) + +#endif diff --git a/doom/src/pdoom/Doom/include/r_segs.h b/doom/src/pdoom/Doom/include/r_segs.h new file mode 100644 index 0000000..37d34f7 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_segs.h @@ -0,0 +1,52 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Refresh module, drawing LineSegs from BSP. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_SEGS__ +#define __R_SEGS__ + +#ifdef __GNUG__ +#pragma interface +#endif + +#endif diff --git a/doom/src/pdoom/Doom/include/r_sky.h b/doom/src/pdoom/Doom/include/r_sky.h new file mode 100644 index 0000000..748daa9 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_sky.h @@ -0,0 +1,60 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Sky rendering. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_SKY__ +#define __R_SKY__ + +#include "m_fixed.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +/* SKY, store the number for name. */ +#define SKYFLATNAME "F_SKY1" + +/* The sky map is 256*128*4 maps. */ +#define ANGLETOSKYSHIFT 22 + +#endif diff --git a/doom/src/pdoom/Doom/include/r_state.h b/doom/src/pdoom/Doom/include/r_state.h new file mode 100644 index 0000000..09aa2c2 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_state.h @@ -0,0 +1,56 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Refresh/render internal state variables (global). + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_STATE__ +#define __R_STATE__ + +// Need data structure definitions. +#include "d_player.h" +#include "r_data.h" + +#ifdef __GNUG__ +#pragma interface +#endif + +#endif diff --git a/doom/src/pdoom/Doom/include/r_things.h b/doom/src/pdoom/Doom/include/r_things.h new file mode 100644 index 0000000..363ac58 --- /dev/null +++ b/doom/src/pdoom/Doom/include/r_things.h @@ -0,0 +1,64 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Rendering of moving objects, sprites. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __R_THINGS__ +#define __R_THINGS__ + +#ifdef __GNUG__ +#pragma interface +#endif + +#include "r_draw.h" + +/* Constant arrays used for psprite clipping and initializing clipping. */ + +void R_InitSprites(const char *const*namelist); + +#define MAX_SPRITE_FRAMES 29 /* Macroized -- killough 1/25/98 */ + +#define MINZ (FRACUNIT*4) +#define MAXZ (FRACUNIT*1280) + + +#endif diff --git a/doom/src/pdoom/Doom/include/s_sound.h b/doom/src/pdoom/Doom/include/s_sound.h new file mode 100644 index 0000000..934ebfe --- /dev/null +++ b/doom/src/pdoom/Doom/include/s_sound.h @@ -0,0 +1,116 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * The not so system specific sound interface. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __S_SOUND__ +#define __S_SOUND__ + +#ifdef __GNUG__ +#pragma interface +#endif + +#include "p_mobj.h" +#include "r_defs.h" +#include "sounds.h" + +// +// Initializes sound stuff, including volume +// Sets channels, SFX and music volume, +// allocates channel buffer, sets S_sfx lookup. +// +void S_Init(int sfxVolume, int musicVolume); + +// Kills all sounds +void S_Stop(void); + +// +// Per level startup code. +// Kills playing sounds at start of level, +// determines music if any, changes music. +// +void S_Start(void); + +// +// Start sound for thing at +// using from sounds.h +// +void S_StartSound(mobj_t *origin, int sfx_id); + +void S_StartSound2(degenmobj_t *origin, int sfx_id); + +// killough 4/25/98: mask used to indicate sound origin is player item pickup +#define PICKUP_SOUND (0x8000) + +// Stop sound for thing at +void S_StopSound(void *origin); + +// Start music using from sounds.h +void S_StartMusic(int music_id); + +// Start music using from sounds.h, and set whether looping +void S_ChangeMusic(int music_id, int looping); + +// Stops the music fer sure. +void S_StopMusic(void); + +// Stop and resume music, during game PAUSE. +void S_PauseSound(void); +void S_ResumeSound(void); + +// +// Updates music & sounds +// +void S_UpdateSounds(void *listener); +void S_SetMusicVolume(int volume); +void S_SetSfxVolume(int volume); + +typedef struct +{ + const sfxinfo_t *sfxinfo; // sound information (if null, channel avail.) + int tickend; + void *origin; // origin of sound + short handle; // handle of the sound being played + short is_pickup; // killough 4/25/98: whether sound is a player's weapon +} channel_t; + +#endif diff --git a/doom/src/pdoom/Doom/include/sounds.h b/doom/src/pdoom/Doom/include/sounds.h new file mode 100644 index 0000000..6291558 --- /dev/null +++ b/doom/src/pdoom/Doom/include/sounds.h @@ -0,0 +1,280 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Created by the sound utility written by Dave Taylor. + * Kept as a sample, DOOM2 sounds. Frozen. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __SOUNDS__ +#define __SOUNDS__ + +// +// SoundFX struct. +// + +struct sfxinfo_struct; + +typedef struct sfxinfo_struct sfxinfo_t; + +struct sfxinfo_struct +{ + + // up to 6-character name + const char *name; // CPhipps - const + + int singularity; + + // Sfx priority + int priority; + + // referenced sound if a link + const sfxinfo_t *link; + + // volume if a link + int volume; + + //Length of clip + int ticks; +}; + +// +// MusicInfo struct. +// + +// the complete set of sound effects +extern const sfxinfo_t S_sfx[]; + +// +// Identifiers for all music in game. +// + +typedef enum +{ + mus_None, + mus_e1m1, + mus_e1m2, + mus_e1m3, + mus_e1m4, + mus_e1m5, + mus_e1m6, + mus_e1m7, + mus_e1m8, + mus_e1m9, + mus_e2m1, + mus_e2m2, + mus_e2m3, + mus_e2m4, + mus_e2m5, + mus_e2m6, + mus_e2m7, + mus_e2m8, + mus_e2m9, + mus_e3m1, + mus_e3m2, + mus_e3m3, + mus_e3m4, + mus_e3m5, + mus_e3m6, + mus_e3m7, + mus_e3m8, + mus_e3m9, + mus_inter, + mus_intro, + mus_bunny, + mus_victor, + mus_introa, + mus_runnin, + mus_stalks, + mus_countd, + mus_betwee, + mus_doom, + mus_the_da, + mus_shawn, + mus_ddtblu, + mus_in_cit, + mus_dead, + mus_stlks2, + mus_theda2, + mus_doom2, + mus_ddtbl2, + mus_runni2, + mus_dead2, + mus_stlks3, + mus_romero, + mus_shawn2, + mus_messag, + mus_count2, + mus_ddtbl3, + mus_ampie, + mus_theda3, + mus_adrian, + mus_messg2, + mus_romer2, + mus_tense, + mus_shawn3, + mus_openin, + mus_evil, + mus_ultima, + mus_read_m, + mus_dm2ttl, + mus_dm2int, + NUMMUSIC +} musicenum_t; + +// +// Identifiers for all sfx in game. +// + +typedef enum +{ + sfx_None, + sfx_pistol, + sfx_shotgn, + sfx_sgcock, + sfx_dshtgn, + sfx_dbopn, + sfx_dbcls, + sfx_dbload, + sfx_plasma, + sfx_bfg, + sfx_sawup, + sfx_sawidl, + sfx_sawful, + sfx_sawhit, + sfx_rlaunc, + sfx_rxplod, + sfx_firsht, + sfx_firxpl, + sfx_pstart, + sfx_pstop, + sfx_doropn, + sfx_dorcls, + sfx_stnmov, + sfx_swtchn, + sfx_swtchx, + sfx_plpain, + sfx_dmpain, + sfx_popain, + sfx_vipain, + sfx_mnpain, + sfx_pepain, + sfx_slop, + sfx_itemup, + sfx_wpnup, + sfx_oof, + sfx_telept, + sfx_posit1, + sfx_posit2, + sfx_posit3, + sfx_bgsit1, + sfx_bgsit2, + sfx_sgtsit, + sfx_cacsit, + sfx_brssit, + sfx_cybsit, + sfx_spisit, + sfx_bspsit, + sfx_kntsit, + sfx_vilsit, + sfx_mansit, + sfx_pesit, + sfx_sklatk, + sfx_sgtatk, + sfx_skepch, + sfx_vilatk, + sfx_claw, + sfx_skeswg, + sfx_pldeth, + sfx_pdiehi, + sfx_podth1, + sfx_podth2, + sfx_podth3, + sfx_bgdth1, + sfx_bgdth2, + sfx_sgtdth, + sfx_cacdth, + sfx_skldth, + sfx_brsdth, + sfx_cybdth, + sfx_spidth, + sfx_bspdth, + sfx_vildth, + sfx_kntdth, + sfx_pedth, + sfx_skedth, + sfx_posact, + sfx_bgact, + sfx_dmact, + sfx_bspact, + sfx_bspwlk, + sfx_vilact, + sfx_noway, + sfx_barexp, + sfx_punch, + sfx_hoof, + sfx_metal, + sfx_chgun, + sfx_tink, + sfx_bdopn, + sfx_bdcls, + sfx_itmbk, + sfx_flame, + sfx_flamst, + sfx_getpow, + sfx_bospit, + sfx_boscub, + sfx_bossit, + sfx_bospn, + sfx_bosdth, + sfx_manatk, + sfx_mandth, + sfx_sssit, + sfx_ssdth, + sfx_keenpn, + sfx_keendt, + sfx_skeact, + sfx_skesit, + sfx_skeatk, + sfx_radio, + NUMSFX +} sfxenum_t; + +#endif diff --git a/doom/src/pdoom/Doom/include/st_gfx.h b/doom/src/pdoom/Doom/include/st_gfx.h new file mode 100644 index 0000000..3bff329 --- /dev/null +++ b/doom/src/pdoom/Doom/include/st_gfx.h @@ -0,0 +1,7 @@ +#ifndef ST_GFX_H +#define ST_GFX_H + +extern const unsigned char gfx_stbar[]; +extern const unsigned int gfx_stbar_len; + +#endif // ST_GFX_H diff --git a/doom/src/pdoom/Doom/include/st_lib.h b/doom/src/pdoom/Doom/include/st_lib.h new file mode 100644 index 0000000..04696c7 --- /dev/null +++ b/doom/src/pdoom/Doom/include/st_lib.h @@ -0,0 +1,177 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * The status bar widget definitions and prototypes + * + *-----------------------------------------------------------------------------*/ + +#ifndef __STLIB__ +#define __STLIB__ + +// We are referring to patches. +#include "r_defs.h" +#include "v_video.h" // color ranges + +// +// Background and foreground screen numbers +// +#define ST_BG 1 +#define ST_FG 0 + +// +// Typedefs of widgets +// + +// Number widget + +typedef struct +{ + // upper right-hand corner + // of the number (right-justified) + int x; + int y; + + // max # of digits in number + int width; + + // last number value + int oldnum; + + // pointer to current value + short *num; + + // pointer to boolean stating + // whether to update number + boolean *on; + + // list of patches for 0-9 + const patch_t **p; + +} st_number_t; + +// Percent widget ("child" of number widget, +// or, more precisely, contains a number widget.) +typedef struct +{ + // number information + st_number_t n; + + // percent sign graphic + const patch_t *p; +} st_percent_t; + +// Multiple Icon widget +typedef struct +{ + // center-justified location of icons + short x; + short y; + + // last icon number + short oldinum; + + // pointer to current icon + short *inum; + + // pointer to boolean stating + // whether to update icon + boolean *on; + + // list of icons + const patch_t **p; + +} st_multicon_t; + +// Binary Icon widget + +typedef struct +{ + // center-justified location of icon + int x; + int y; + + // last icon value + boolean oldval; + + // pointer to current icon status + boolean *val; + + // pointer to boolean + // stating whether to update icon + boolean *on; + + const patch_t *p; // icon + int data; // user data +} st_binicon_t; + +// +// Widget creation, access, and update routines +// + +// Initializes widget library. +// More precisely, initialize STMINUS, +// everything else is done somewhere else. +// +void STlib_init(void); + +// Number widget routines +void STlib_initNum(st_number_t *n, int x, int y, const patch_t **pl, short *num, boolean *on, int width); + +void STlib_updateNum(st_number_t *n, int cm, boolean refresh); + +// Percent widget routines +void STlib_initPercent(st_percent_t *p, int x, int y, const patch_t **pl, short *num, boolean *on, const patch_t *percent); + +void STlib_updatePercent(st_percent_t *per, int cm, int refresh); + +// Multiple Icon widget routines +void STlib_initMultIcon(st_multicon_t *mi, int x, int y, const patch_t **il, short *inum, boolean *on); + +void STlib_updateMultIcon(st_multicon_t *mi, boolean refresh); + +// Binary Icon widget routines + +void STlib_initBinIcon(st_binicon_t *b, int x, int y, const patch_t *i, boolean *val, boolean *on); + +void STlib_updateBinIcon(st_binicon_t *bi, boolean refresh); + +void ST_refreshBackground(void); + +#endif diff --git a/doom/src/pdoom/Doom/include/st_stuff.h b/doom/src/pdoom/Doom/include/st_stuff.h new file mode 100644 index 0000000..86144a3 --- /dev/null +++ b/doom/src/pdoom/Doom/include/st_stuff.h @@ -0,0 +1,380 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Status bar code. + * Does the face/direction indicator animatin. + * Does palette indicators as well (red pain/berserk, bright pickup) + * + * next-hack: + * pointers to patches now stored in immutable flash region, saving a few + * hundred bytes of RAM. + * modified so that instead of re-rendering, if no + * changes are required, and the status bar is already rendered in + * the previous frame buffer (but not on the current one), then the + * previous frame is copied to the current frame buffer. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __STSTUFF_H__ +#define __STSTUFF_H__ + +#include "doomtype.h" +#include "d_event.h" + +// Size of statusbar. +// Now sensitive for scaling. + +// proff 08/18/98: Changed for high-res +#define ST_HEIGHT 32 +#define ST_WIDTH 320 +#define ST_Y (SCREENHEIGHT - ST_HEIGHT) +#if PDOOM_W == 240 +#define ST_SCALED_HEIGHT ST_HEIGHT +#else +#define ST_SCALED_HEIGHT 17 /* Paradise: status bar 240x32 scaled down to 128x17 */ +#define ST_SMALL 1 +#endif +#define ST_SCALED_WIDTH SCREENWIDTH +#define ST_SCALED_Y (SCREENHEIGHT - ST_SCALED_HEIGHT) +// nh: reduction constant from GBA port to ours +#define ST_C 160/160 +// +// STATUS BAR DATA +// + +// Palette indices. +// For damage/bonus red-/gold-shifts +#define STARTREDPALS 1 +#define STARTBONUSPALS 9 +#define NUMREDPALS 8 +#define NUMBONUSPALS 4 +// Radiation suit, green shift. +#define RADIATIONPAL 13 + +// Location of status bar +#define ST_X 0 +#define ST_X2 104 + +// proff 08/18/98: Changed for high-res +#define ST_FX (ST_X+143 * ST_C) +#define ST_FY (ST_Y+1) + +// Should be set to patch width +// for tall numbers later on +#define ST_TALLNUMWIDTH (tallnum[0]->width) + +// Number of status faces. +#define ST_NUMPAINFACES 5 +#define ST_NUMSTRAIGHTFACES 3 +#define ST_NUMTURNFACES 2 +#define ST_NUMSPECIALFACES 3 + +#define ST_FACESTRIDE \ + (ST_NUMSTRAIGHTFACES+ST_NUMTURNFACES+ST_NUMSPECIALFACES) + +#define ST_NUMEXTRAFACES 2 + +#define ST_NUMFACES \ + (ST_FACESTRIDE*ST_NUMPAINFACES+ST_NUMEXTRAFACES) + +#define ST_TURNOFFSET (ST_NUMSTRAIGHTFACES) +#define ST_OUCHOFFSET (ST_TURNOFFSET + ST_NUMTURNFACES) +#define ST_EVILGRINOFFSET (ST_OUCHOFFSET + 1) +#define ST_RAMPAGEOFFSET (ST_EVILGRINOFFSET + 1) +#define ST_GODFACE (ST_NUMPAINFACES*ST_FACESTRIDE) +#define ST_DEADFACE (ST_GODFACE+1) + +// proff 08/18/98: Changed for high-res +#define ST_FACESX (ST_X+104 * ST_C) +#define ST_FACESY (ST_Y) + +#define ST_EVILGRINCOUNT (2*TICRATE) +//Fix Status bar face timing ~Kippykip +//#define ST_STRAIGHTFACECOUNT (TICRATE*2) +#define ST_STRAIGHTFACECOUNT (18) +#define ST_TURNCOUNT (1*TICRATE) +#define ST_OUCHCOUNT (1*TICRATE) +#define ST_RAMPAGEDELAY (2*TICRATE) + +#define ST_MUCHPAIN 20 + +// Location and size of statistics, +// justified according to widget type. +// Problem is, within which space? STbar? Screen? +// Note: this could be read in by a lump. +// Problem is, is the stuff rendered +// into a buffer, +// or into the frame buffer? +// I dunno, why don't you go and find out!!! killough +#if 1 +// AMMO number pos. +#define ST_AMMOWIDTH 3 +// proff 08/18/98: Changed for high-res +#define ST_AMMOX (ST_X+32 * ST_C) +#define ST_AMMOY (ST_Y+6) +//#define ST_AMMOX 44 +//#define ST_AMMOY 171 + +// HEALTH number pos. +#define ST_HEALTHWIDTH 2 +// proff 08/18/98: Changed for high-res +#define ST_HEALTHX (ST_X+66 * ST_C) +#define ST_HEALTHY (ST_Y+6) + +// Weapon pos. +// proff 08/18/98: Changed for high-res +#define ST_ARMSX (ST_X+82 * ST_C) +#define ST_ARMSY (ST_Y+4) +#define ST_ARMSBGX (ST_X+104 * ST_C) +#define ST_ARMSBGY (ST_Y) + +#define ST_ARMSXSPACE 8 +#define ST_ARMSYSPACE 10 + +// Frags pos. +// proff 08/18/98: Changed for high-res +#define ST_FRAGSX (ST_X+138 * ST_C) +#define ST_FRAGSY (ST_Y+3) +//#define ST_FRAGSX 138 +//#define ST_FRAGSY 171 +#define ST_FRAGSWIDTH 2 + +// ARMOR number pos. +#define ST_ARMORWIDTH 3 +// proff 08/18/98: Changed for high-res +#define ST_ARMORX (ST_X+166 * ST_C) +#define ST_ARMORY (ST_Y+6) + +// Key icon positions. +#define ST_KEY0WIDTH 8 +#define ST_KEY0HEIGHT 5 +// proff 08/18/98: Changed for high-res +#define ST_KEY0X (ST_X+178 * ST_C) +#define ST_KEY0Y (ST_Y+3) + +#define ST_KEY1WIDTH ST_KEY0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_KEY1X (ST_X+178 * ST_C) +#define ST_KEY1Y (ST_Y+13) + +#define ST_KEY2WIDTH ST_KEY0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_KEY2X (ST_X+178 * ST_C) +#define ST_KEY2Y (ST_Y+23) + +// Ammunition counter. +#define ST_AMMO0WIDTH 3 +#define ST_AMMO0HEIGHT 6 +// proff 08/18/98: Changed for high-res +#define ST_AMMO0X (ST_X+220 * ST_C) +#define ST_AMMO0Y (ST_Y+5) + +#define ST_AMMO1WIDTH ST_AMMO0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_AMMO1X (ST_X+220 * ST_C) +#define ST_AMMO1Y (ST_Y+11) + +#define ST_AMMO2WIDTH ST_AMMO0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_AMMO2X (ST_X+220 * ST_C) +#define ST_AMMO2Y (ST_Y+23) + +#define ST_AMMO3WIDTH ST_AMMO0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_AMMO3X (ST_X+220 * ST_C) +#define ST_AMMO3Y (ST_Y+17) + +// Indicate maximum ammunition. +// Only needed because backpack exists. +#define ST_MAXAMMO0WIDTH 3 +#define ST_MAXAMMO0HEIGHT 5 +// proff 08/18/98: Changed for high-res +#define ST_MAXAMMO0X (ST_X+238 * ST_C) +#define ST_MAXAMMO0Y (ST_Y+5) + +#define ST_MAXAMMO1WIDTH ST_MAXAMMO0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_MAXAMMO1X (ST_X+238 * ST_C) +#define ST_MAXAMMO1Y (ST_Y+11) + +#define ST_MAXAMMO2WIDTH ST_MAXAMMO0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_MAXAMMO2X (ST_X+238 * ST_C) +#define ST_MAXAMMO2Y (ST_Y+23) + +#define ST_MAXAMMO3WIDTH ST_MAXAMMO0WIDTH +// proff 08/18/98: Changed for high-res +#define ST_MAXAMMO3X (ST_X+238 * ST_C) +#define ST_MAXAMMO3Y (ST_Y+17) + +#else +#define ST_YC 1 +// AMMO number pos. +#define ST_AMMOWIDTH 3 +#define ST_AMMOX 44 +#define ST_AMMOY 171 * ST_YC + +// HEALTH number pos. +#define ST_HEALTHWIDTH 3 +#define ST_HEALTHX 90 +#define ST_HEALTHY 171 * ST_YC + +// Weapon pos. +#define ST_ARMSX 111 +#define ST_ARMSY 172 * ST_YC +#define ST_ARMSBGX 104 +#define ST_ARMSBGY 168 * ST_YC +#define ST_ARMSXSPACE 12 +#define ST_ARMSYSPACE 10 + +// Frags pos. +#define ST_FRAGSX 138 +#define ST_FRAGSY 171 * ST_YC +#define ST_FRAGSWIDTH 2 + +// ARMOR number pos. +#define ST_ARMORWIDTH 3 +#define ST_ARMORX 221 +#define ST_ARMORY 171 * ST_YC + +// Key icon positions. +#define ST_KEY0WIDTH 8 +#define ST_KEY0HEIGHT 5 +#define ST_KEY0X 239 +#define ST_KEY0Y 171 * ST_YC +#define ST_KEY1WIDTH ST_KEY0WIDTH +#define ST_KEY1X 239 +#define ST_KEY1Y 181 * ST_YC +#define ST_KEY2WIDTH ST_KEY0WIDTH +#define ST_KEY2X 239 +#define ST_KEY2Y 191 * ST_YC + +// Ammunition counter. +#define ST_AMMO0WIDTH 3 +#define ST_AMMO0HEIGHT 6 +#define ST_AMMO0X 288 +#define ST_AMMO0Y 173 * ST_YC +#define ST_AMMO1WIDTH ST_AMMO0WIDTH +#define ST_AMMO1X 288 +#define ST_AMMO1Y 179 * ST_YC +#define ST_AMMO2WIDTH ST_AMMO0WIDTH +#define ST_AMMO2X 288 +#define ST_AMMO2Y 191 * ST_YC +#define ST_AMMO3WIDTH ST_AMMO0WIDTH +#define ST_AMMO3X 288 +#define ST_AMMO3Y 185 * ST_YC + +// Indicate maximum ammunition. +// Only needed because backpack exists. +#define ST_MAXAMMO0WIDTH 3 +#define ST_MAXAMMO0HEIGHT 5 +#define ST_MAXAMMO0X 314 +#define ST_MAXAMMO0Y 173 * ST_YC +#define ST_MAXAMMO1WIDTH ST_MAXAMMO0WIDTH +#define ST_MAXAMMO1X 314 +#define ST_MAXAMMO1Y 179 * ST_YC +#define ST_MAXAMMO2WIDTH ST_MAXAMMO0WIDTH +#define ST_MAXAMMO2X 314 +#define ST_MAXAMMO2Y 191 * ST_YC +#define ST_MAXAMMO3WIDTH ST_MAXAMMO0WIDTH +#define ST_MAXAMMO3X 314 +#define ST_MAXAMMO3Y 185 * ST_YC + +// pistol +#define ST_WEAPON0X 110 +#define ST_WEAPON0Y 172 * ST_YC + +// shotgun +#define ST_WEAPON1X 122 +#define ST_WEAPON1Y 172 * ST_YC + +// chain gun +#define ST_WEAPON2X 134 +#define ST_WEAPON2Y 172 * ST_YC + +// missile launcher +#define ST_WEAPON3X 110 +#define ST_WEAPON3Y 181 * ST_YC + +// plasma gun +#define ST_WEAPON4X 122 +#define ST_WEAPON4Y 181 * ST_YC + + // bfg +#define ST_WEAPON5X 134 +#define ST_WEAPON5Y 181 * ST_YC + +// WPNS title +#define ST_WPNSX 109 +#define ST_WPNSY 191 * ST_YC + + // DETH title +#define ST_DETHX 109 +#define ST_DETHY 191 * ST_YC +#endif + +// +// STATUS BAR +// + +// Called by main loop. +boolean ST_Responder(const event_t *ev); + +// Called by main loop. +void ST_Ticker(void); + +// Called by main loop. +void ST_Drawer(boolean st_statusbaron, boolean refresh); + +// Called when the console player is spawned on each level. +void ST_Start(void); + +// Called by startup code. +void ST_Init(void); + +// States for status bar code. +typedef enum +{ + AutomapState, FirstPersonState +} st_stateenum_t; + +// killough 5/2/98: moved from m_misc.c: + +#endif diff --git a/doom/src/pdoom/Doom/include/tables.h b/doom/src/pdoom/Doom/include/tables.h new file mode 100644 index 0000000..7fa90ce --- /dev/null +++ b/doom/src/pdoom/Doom/include/tables.h @@ -0,0 +1,137 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Lookup tables. + * Do not try to look them up :-). + * In the order of appearance: + * + * int finetangent[4096] - Tangens LUT. + * Should work with BAM fairly well (12 of 16bit, + * effectively, by shifting). + * + * int finesine[10240] - Sine lookup. + * Guess what, serves as cosine, too. + * Remarkable thing is, how to use BAMs with this? + * + * int tantoangle[2049] - ArcTan LUT, + * maps tan(angle) to angle fast. Gotta search. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __TABLES__ +#define __TABLES__ + +#include "m_fixed.h" +#include "doomdef.h" +// +// Lighting constants. + +#define LIGHTLEVELS 16 +#define LIGHTSEGSHIFT 4 +#define MAXLIGHTSCALE 48 +#define LIGHTSCALESHIFT 12 +#define MAXLIGHTZ 128 +#define LIGHTZSHIFT 20 + +// Number of diminishing brightness levels. +// There a 0-31, i.e. 32 LUT in the COLORMAP lump. + +#define NUMCOLORMAPS 32 +// +#define TABULATED_VALUES 1 // use resolution-dependent tabulated values for some arrays. +#define FINEANGLES 8192 +#define FINEMASK (FINEANGLES-1) + +// 0x100000000 to 0x2000 +#define ANGLETOFINESHIFT 19 + +// Binary Angle Measument, BAM. +#define ANG45 0x20000000 +#define ANG90 0x40000000 +#define ANG180 0x80000000 +#define ANG270 0xc0000000 +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#define SLOPERANGE 2048 +#define SLOPEBITS 11 +#define DBITS (FRACBITS-SLOPEBITS) + +typedef unsigned angle_t; + +// Load trig tables if needed +void R_LoadTrigTables(void); + +// Effective size is 10240. +extern const fixed_t finesine[10240]; + +// Re-use data, is just PI/2 phase shift. +extern const fixed_t *const finecosine; + +// Effective size is 4096. +extern const fixed_t finetangent[4096]; + +// Effective size is 2049; +// The +1 size is to handle the case when x==y without additional checking. + +extern const angle_t tantoangle[2049]; + +#if TABULATED_VALUES +extern const short viewangletox[4096]; +extern const angle_t xtoviewangle[SCREENWIDTH + 1]; +extern const fixed_t yslope[SCREENHEIGHT]; +extern const fixed_t distscale[SCREENWIDTH]; +extern const uint8_t scalelight[LIGHTLEVELS][MAXLIGHTSCALE]; +extern const uint8_t zlight[LIGHTLEVELS][MAXLIGHTZ]; +#else +extern int viewangletox[4096]; +extern angle_t xtoviewangle[SCREENWIDTH + 1]; +extern fixed_t yslope[SCREENHEIGHT]; +extern fixed_t distscale[SCREENWIDTH]; +#endif + +extern const short screenheightarray[SCREENWIDTH_PHYSICAL]; + +extern const short negonearray[SCREENWIDTH_PHYSICAL]; + +extern const unsigned char translationtables[1023]; + +#endif diff --git a/doom/src/pdoom/Doom/include/v_video.h b/doom/src/pdoom/Doom/include/v_video.h new file mode 100644 index 0000000..901ad63 --- /dev/null +++ b/doom/src/pdoom/Doom/include/v_video.h @@ -0,0 +1,147 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Gamma correction LUT. + * Color range translation support + * Functions to draw patches (by post) directly to screen. + * Functions to blit a block to the screen. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __V_VIDEO__ +#define __V_VIDEO__ + +#include "doomtype.h" +#include "doomdef.h" +// Needed because we are refering to patches. +#include "r_data.h" +#include "r_patch.h" + +#define MAX_PATCH_COLOFFS 128 +#define MAX_COLUMN_DATA 256 +// +// VIDEO +// +#define MAX_GAMMA 4 +#define CENTERY (SCREENHEIGHT/2) +extern int v_pitch; +#define ScreenYToOffset(x) (v_pitch * (x)) + +// symbolic indices into color translation table pointer array +typedef enum +{ + CR_BRICK, //0 + CR_TAN, //1 + CR_GRAY, //2 + CR_GREEN, //3 + CR_BROWN, //4 + CR_GOLD, //5 + CR_RED, //6 + CR_BLUE, //7 + CR_ORANGE, //8 + CR_YELLOW, //9 + CR_BLUE2, //10 // proff + CR_LIMIT //11 //jff 2/27/98 added for range check +} crange_idx_e; +//jff 1/16/98 end palette color range additions + +#define CR_DEFAULT CR_RED /* default value for out of range colors */ + +typedef struct +{ + uint8_t *data; // pointer to the screen content +// short width; // the width of the surface +// short height; // the height of the surface, used when mallocing +} screeninfo_t; + +#define NUM_SCREENS 1 + +// V_FillRect +void V_FillRect(int x, int y, int width, int height, byte colour); + +// CPhipps - patch drawing +// Consolidated into the 3 really useful functions: + +// V_DrawNumPatch - Draws the patch from lump num +void V_DrawNumPatch(int x, int y, int scrn, int lump, int cm, enum patch_translation_e flags); + +void V_DrawPatch(int x, int y, int scrn, const patch_t *patch); + +void V_DrawPatchXScale(int x, int y, const patch_t *patch); +void V_DrawPatchNoScale(int x, int y, const patch_t *patch); + +// V_DrawNamePatch - Draws the patch from lump "name" +#define V_DrawNamePatch(x,y,s,n,t,f) V_DrawNumPatch(x,y,s,W_GetNumForName(n),t,f) + +/* cph - + * Functions to return width & height of a patch. + * Doesn't really belong here, but is often used in conjunction with + * this code. + */ +#define V_NamePatchWidth(name) R_NumPatchWidth(W_GetNumForName(name)) +#define V_NamePatchHeight(name) R_NumPatchHeight(W_GetNumForName(name)) + +/* cphipps 10/99: function to tile a flat over the screen */ +void V_DrawBackground(const char *flatname); + +// CPhipps - function to set the palette to palette number pal. +void V_SetPalette(int pal); + +// Kippykip - Multiple colour corrected palettes +void V_SetPalLump(int pal); + +// CPhipps - function to plot a pixel + +typedef struct +{ + int x, y; +} fpoint_t; + +typedef struct +{ + fpoint_t a, b; +} fline_t; + +// V_DrawLine +void V_DrawLine(fline_t *fl, int color); +// +extern const byte gammatable[5][256]; + +#endif diff --git a/doom/src/pdoom/Doom/include/version.h b/doom/src/pdoom/Doom/include/version.h new file mode 100644 index 0000000..79f9cb3 --- /dev/null +++ b/doom/src/pdoom/Doom/include/version.h @@ -0,0 +1,50 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Doom version indicators. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __DOOMVERSION__ +#define __DOOMVERSION__ + +extern const char version_date[]; + +#endif diff --git a/doom/src/pdoom/Doom/include/w_wad.h b/doom/src/pdoom/Doom/include/w_wad.h new file mode 100644 index 0000000..a6de7c5 --- /dev/null +++ b/doom/src/pdoom/Doom/include/w_wad.h @@ -0,0 +1,167 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * WAD I/O functions. + * next-hack: important data internal flash caching functions. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __W_WAD__ +#define __W_WAD__ + +#include "doomtype.h" +#include +#include "st_stuff.h" +#include "r_defs.h" +#include "i_memory.h" +// +// TYPES +// + +typedef struct +{ + char identification[4]; // Should be "IWAD" or "PWAD". + int numlumps; + int infotableofs; +} wadinfo_t; + +typedef struct +{ + int filepos; + int size; + char name[8]; +} filelump_t; + +// killough 4/17/98: if W_CheckNumForName() called with only +// one argument, pass ns_global as the default namespace +typedef struct +{ + uint32_t dataLength; + union + { + struct + { + uint32_t map :16; + uint32_t episode :16; + }; + uint32_t mapEpisode; + }; + void **lumpAddressTable; + uint32_t numvertex; + vertex_t *vertexes; + uint32_t numsegs; + seg_t *segs; + int numnodes; + mapnode_t *nodes; + int numlines; + line_t *lines; + int numsides; + short *blockmaplump; + side_t *sides; + byte *rejectmatrix; + uint32_t data[0]; // textures, flats, +} wad_level_flash_data_t; +typedef struct +{ + uint32_t wadCRC; + uint32_t wadSize; + uint32_t immutableDataCRC; + uint32_t immutableDataLength; // including this structure + wadinfo_t wadHeader; + uint32_t numsprites; + spritedef_t *sprites; + uint8_t *palette_lump; + lighttable_t *colormaps; + uint32_t *soundLumps; + uint32_t numtextures; + fixed_t *textureheight; + short *switchlist; + patchsizeoffsets_t *patchLumpSizeOffsets; + // 0-9, tall numbers + const patch_t *tallnum[10]; + // 0-9, short, yellow (,different!) numbers + const patch_t *shortnum[10]; + // tall % sign + const patch_t *tallpercent; + const patch_t *keys[NUMCARDS]; + // face status patches + const patch_t *faces[ST_NUMFACES]; // >160 bytes wasted... + // weapon ownership patches + const patch_t *arms[6][2]; + wad_level_flash_data_t *levelData; + // after this, immutable data: + // playpal, and some TBD + uint32_t data[0]; +} wad_immutable_flash_data_t; +extern wad_immutable_flash_data_t *p_wad_immutable_flash_data; +extern wad_level_flash_data_t *p_wad_level_flash_data; +void W_Init(void); // CPhipps - uses the above array + +int PUREFUNC W_CheckNumForName(const char *name); // killough 4/17/98 +int PUREFUNC W_GetNumForName(const char *name); +const char* PUREFUNC W_GetNameForNum(int lump); + +int PUREFUNC W_LumpLength(int lump); + +// CPhipps - modified for 'new' lump locking +const void* /*PUREFUNC*/W_CacheLumpNum(int lump); + +// CPhipps - convenience macros +#define W_CacheLumpName(name) W_CacheLumpNum(W_GetNumForName(name)) +/*static inline void *W_CacheLumpName(char * name) + { + printf("Caching name %s\r\n", name); + return W_CacheLumpNum(W_GetNumForName(name)); + }*/ +void ExtractFileBase(const char*, char*); // killough +// next-hack additions +void initLumpPtrTable(void); +void* writeLumpToFlashRegion(int lumpnum, uint8_t flashRegion, boolean updateSize); +void* writeBufferToFlashRegion(void *buffer, int size, uint8_t flashRegion, boolean updateSize); +int getUserFlashRegionRemainingSpace(); +void getFileLumpByNum(int n, filelump_t *fl); +void initImmutableFlashRegion(); +void* getAddressOrCacheLumpNum(int lump, boolean storeInFlash, uint8_t flashRegion); +void** storeLumpArrayToFlash(boolean levelChanged); +void* storeFlashImmutableValues(); +void* storeLevelValues(boolean levelChanged); +wad_level_flash_data_t* initLevelFlashRegion(); +extern void **lumpPtrArray; +#endif diff --git a/doom/src/pdoom/Doom/include/wi_stuff.h b/doom/src/pdoom/Doom/include/wi_stuff.h new file mode 100644 index 0000000..1aa1d34 --- /dev/null +++ b/doom/src/pdoom/Doom/include/wi_stuff.h @@ -0,0 +1,76 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Intermission screens. + * + *-----------------------------------------------------------------------------*/ + +#ifndef __WI_STUFF__ +#define __WI_STUFF__ + +//#include "v_video.h" + +#include "doomdef.h" + +// States for the intermission + +typedef enum +{ + NoState = -1, StatCount, ShowNextLoc + +} stateenum_t; + +// called by the initialization +void WI_Init(void); + +// Called by main loop, animate the intermission. +void WI_Ticker(void); + +// Called by main loop, +// draws the intermission directly into the screen buffer. +void WI_Drawer(void); + +// Setup for an intermission screen. +void WI_Start(wbstartstruct_t *wbstartstruct); + +// Release intermission screen memory +void WI_End(void); + +#endif diff --git a/doom/src/pdoom/Doom/include/z_bmalloc.h b/doom/src/pdoom/Doom/include/z_bmalloc.h new file mode 100644 index 0000000..bf68d87 --- /dev/null +++ b/doom/src/pdoom/Doom/include/z_bmalloc.h @@ -0,0 +1,67 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Block memory allocator + * This is designed to be a fast allocator for small, regularly used block sizes + *-----------------------------------------------------------------------------*/ + +struct block_memory_alloc_s +{ + void *firstpool; +// size_t size; +// size_t perpool; +// int tag; + unsigned short size; + unsigned short perpool :11; + unsigned short tag :5; +// const char *desc; +}; + +#define DECLARE_BLOCK_MEMORY_ALLOC_ZONE(name) extern struct block_memory_alloc_s name +#define IMPLEMENT_BLOCK_MEMORY_ALLOC_ZONE(name, size, tag, num, desc) \ +struct block_memory_alloc_s name = { NULL, size, num, tag} +#define NULL_BLOCK_MEMORY_ALLOC_ZONE(name) name.firstpool = NULL + +DECLARE_BLOCK_MEMORY_ALLOC_ZONE(mobjzone); +DECLARE_BLOCK_MEMORY_ALLOC_ZONE(static_mobjzone); + +void* Z_BMalloc(struct block_memory_alloc_s *pzone); + +boolean Z_BFree(struct block_memory_alloc_s *pzone, void *p); diff --git a/doom/src/pdoom/Doom/include/z_zone.h b/doom/src/pdoom/Doom/include/z_zone.h new file mode 100644 index 0000000..03c99bf --- /dev/null +++ b/doom/src/pdoom/Doom/include/z_zone.h @@ -0,0 +1,125 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Zone Memory Allocation, perhaps NeXT ObjectiveC inspired. + * Remark: this was the only stuff that, according + * to John Carmack, might have been useful for + * Quake. + * + * Rewritten by Lee Killough, though, since it was not efficient enough. + * + * Restored back to its original form by Nicola Wrachien and optimized, + * as it was not memory efficient enough (see zone.c). + * + *---------------------------------------------------------------------*/ + +#ifndef __Z_ZONE__ +#define __Z_ZONE__ + +#ifndef __GNUC__ +#define __attribute__(x) +#endif + +// Include system definitions so that prototypes become +// active before macro replacements below are in effect. + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include +#include +#include +//#include +#define STRINGIFY(x) #x +#define TOSTRING(x) STRINGIFY(x) + +// ZONE MEMORY +// PU - purge tags. + +enum +{ + PU_FREE, PU_STATIC, /*PU_SOUND, PU_MUSIC,*/PU_LEVEL, PU_LEVSPEC, /*PU_CACHE,*/ + /* Must always be last -- killough */PU_MAX +}; + +#define PU_PURGELEVEL PU_MAX /* First purgable tag's level */ + +#define DA(x,y) +#define DAC(x,y) + +void* (Z_Malloc2)(int size, int tag, void **ptr, const char *sz DA(const char *, int)); +void (Z_Free)(void *ptr DA(const char *, int)); +void (Z_FreeTags)(int lowtag, int hightag DA(const char *, int)); +void (Z_ChangeTag)(void *ptr, int tag DA(const char *, int)); +void (Z_Init)(void); +void Z_Close(void); +void* (Z_Calloc)(size_t n, size_t n2, int tag, void **user DA(const char *, int)); +void* (Z_Realloc)(void *p, size_t n, int tag, void **user DA(const char *, int)); +char* (Z_Strdup)(const char *s, int tag, void **user DA(const char *, int)); +void (Z_CheckHeap)(DAC(const char *,int)); // killough 3/22/98: add file/line info +void Z_DumpHistory(char*); + +#define Z_Malloc(n, tag, u) Z_Malloc2(n, tag, u, TOSTRING(n) ) +/* cphipps 2001/11/18 - + * If we're using memory mapped file access to WADs, we won't need to maintain + * our own heap. So we *could* let "normal" malloc users use the libc malloc + * directly, for efficiency. Except we do need a wrapper to handle out of memory + * errors... damn, ok, we'll leave it for now. + */ +#ifndef HAVE_LIBDMALLOC +// Remove all definitions before including system definitions +// +#undef malloc +#undef free +#undef realloc +#undef calloc +#undef strdup + +#define malloc(n) Z_Malloc(n,PU_STATIC,0) +#define free(p) Z_Free(p) +#define realloc(p,n) Z_Realloc(p,n,PU_STATIC,0) +#define calloc(n1,n2) Z_Calloc(n1,n2,PU_STATIC,0) +#define strdup(s) Z_Strdup(s,PU_STATIC,0) + +#endif + +void Z_ZoneHistory(char*); + +#endif diff --git a/doom/src/pdoom/Doom/source/am_map.c b/doom/src/pdoom/Doom/source/am_map.c new file mode 100644 index 0000000..f8ca64a --- /dev/null +++ b/doom/src/pdoom/Doom/source/am_map.c @@ -0,0 +1,1087 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * the automap code + * + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "doomstat.h" +#include "st_stuff.h" +#include "r_main.h" +#include "p_setup.h" +#include "p_maputl.h" +#include "w_wad.h" +#include "v_video.h" +#include "p_spec.h" +#include "am_map.h" +#include "dstrings.h" +#include "lprintf.h" // jff 08/03/98 - declaration of lprintf +#include "g_game.h" + +#include "global_data.h" +// location of window on screen +static const int f_x = 0; +static const int f_y = 0; + +// size of window on screen +static const int f_w = SCREENWIDTH_PHYSICAL; +static const int f_h = SCREENHEIGHT - ST_SCALED_HEIGHT; + +static const int mapcolor_back = 247; // map background +static const int mapcolor_grid = 104; // grid lines color +static const int mapcolor_wall = 23; // normal 1s wall color +static const int mapcolor_fchg = 55; // line at floor height change color +static const int mapcolor_cchg = 215; // line at ceiling height change color +static const int mapcolor_clsd = 208; // line at sector with floor=ceiling color +static const int mapcolor_rdor = 175; // red door color (diff from keys to allow option) +static const int mapcolor_bdor = 204; // blue door color (of enabling one but not other ) +static const int mapcolor_ydor = 231; // yellow door color +static const int mapcolor_tele = 119; // teleporter line color +static const int mapcolor_secr = 252; // secret sector boundary color +static const int mapcolor_exit = 0; // jff 4/23/98 add exit line color +static const int mapcolor_unsn = 104; // computer map unseen line color +static const int mapcolor_flat = 88; // line with no floor/ceiling changes +static const int mapcolor_sngl = 208; // single player arrow color +static const int map_secret_after = 0; + +#define USEMAP 1 + +// jff 3/9/98 add option to not show secret sectors until entered +// jff 4/3/98 add symbols for "no-color" for disable and "black color" for black +#define NC 0 +#define BC 247 + +// drawing stuff +#define FB 0 + +// how much the automap moves window per tic in frame-buffer coordinates +// moves 140 pixels in 1 second +#define F_PANINC 4 +// how much zoom-in per tic +// goes to 2x in 1 second +#define M_ZOOMIN ((int)(1.02 * FRACUNIT)) +// how much zoom-out per tic +// pulls out to 0.5x in 1 second +#define M_ZOOMOUT ((int)(FRACUNIT / 1.02)) + +#define PLAYERRADIUS (16 * (1 << MAPBITS)) // e6y + +// translates between frame-buffer and map distances +#define FTOM(x) FixedMul(((x) << 16), _g->scale_ftom) +#define MTOF(x) (FixedMul((x), _g->scale_mtof) >> 16) +// translates between frame-buffer and map coordinates +#define CXMTOF(x) (f_x + MTOF((x)-_g->m_x)) +#define CYMTOF(y) (f_y + (f_h - MTOF((y)-_g->m_y))) + +typedef struct +{ + mpoint_t a, b; +} mline_t; + +// +// The vector graphics for the automap. +// A line drawing of the player pointing right, +// starting from the middle. +// +#define R ((8 * PLAYERRADIUS) / 7) +static const mline_t player_arrow[] = +{ + { + {-R + R / 8, 0}, {R, 0} + }, // ----- + { + {R, 0}, {R - R / 2, R / 4} + }, // -----> + { + {R, 0}, {R - R / 2, -R / 4} + }, + { + {-R + R / 8, 0}, + {-R - R / 8, R / 4} + }, // >----> + { + {-R + R / 8, 0}, + {-R - R / 8, -R / 4} + }, + { + {-R + 3 * R / 8, 0}, + {-R + R / 8, R / 4} + }, // >>---> + { + {-R + 3 * R / 8, 0}, + {-R + R / 8, -R / 4} + } +}; +#undef R +#define NUMPLYRLINES (sizeof(player_arrow) / sizeof(mline_t)) + +// +// AM_activateNewScale() +// +// Changes the map scale after zooming or translating +// +// Passed nothing, returns nothing +// +static void AM_activateNewScale(void) +{ + _g->m_x += _g->m_w / 2; + _g->m_y += _g->m_h / 2; + _g->m_w = FTOM(f_w); + _g->m_h = FTOM(f_h); + _g->m_x -= _g->m_w / 2; + _g->m_y -= _g->m_h / 2; + _g->m_x2 = _g->m_x + _g->m_w; + _g->m_y2 = _g->m_y + _g->m_h; +} + +// +// AM_findMinMaxBoundaries() +// +// Determines bounding box of all vertices, +// sets global variables controlling zoom range. +// +// Passed nothing, returns nothing +// +static void AM_findMinMaxBoundaries(void) +{ + int i; + fixed_t a; + fixed_t b; + + _g->min_x = _g->min_y = INT_MAX; + _g->max_x = _g->max_y = -INT_MAX; + + for (i = 0; i < _g->numvertexes; i++) + { + if (_g->vertexes[i].x < _g->min_x) + _g->min_x = _g->vertexes[i].x; + else if (_g->vertexes[i].x > _g->max_x) + _g->max_x = _g->vertexes[i].x; + + if (_g->vertexes[i].y < _g->min_y) + _g->min_y = _g->vertexes[i].y; + else if (_g->vertexes[i].y > _g->max_y) + _g->max_y = _g->vertexes[i].y; + } + + // _g->max_w = (_g->max_x >>= FRACTOMAPBITS) - (_g->min_x >>= FRACTOMAPBITS);//e6y + // _g->max_h = (_g->max_y >>= FRACTOMAPBITS) - (_g->min_y >>= FRACTOMAPBITS);//e6y + + fixed_t max_w = (_g->max_x >>= FRACTOMAPBITS) - (_g->min_x >>= FRACTOMAPBITS); // e6y + fixed_t max_h = (_g->max_y >>= FRACTOMAPBITS) - (_g->min_y >>= FRACTOMAPBITS); // e6y + + // a = FixedDiv(_g->f_w<max_w); + // b = FixedDiv(_g->f_h<max_h); + + a = FixedDiv(f_w << FRACBITS, max_w); + b = FixedDiv(f_h << FRACBITS, max_h); + + _g->min_scale_mtof = a < b ? a : b; + _g->max_scale_mtof = FixedDiv(f_h << FRACBITS, 2 * PLAYERRADIUS); +} + +// +// AM_changeWindowLoc() +// +// Moves the map window by the global variables m_paninc.x, m_paninc.y +// +// Passed nothing, returns nothing +// +static void AM_changeWindowLoc(void) +{ + if (_g->m_paninc.x || _g->m_paninc.y) + { + _g->automapmode &= ~am_follow; + _g->f_oldloc.x = INT_MAX; + } + + _g->m_x += _g->m_paninc.x; + _g->m_y += _g->m_paninc.y; + + if (_g->m_x + _g->m_w / 2 > _g->max_x) + _g->m_x = _g->max_x - _g->m_w / 2; + else if (_g->m_x + _g->m_w / 2 < _g->min_x) + _g->m_x = _g->min_x - _g->m_w / 2; + + if (_g->m_y + _g->m_h / 2 > _g->max_y) + _g->m_y = _g->max_y - _g->m_h / 2; + else if (_g->m_y + _g->m_h / 2 < _g->min_y) + _g->m_y = _g->min_y - _g->m_h / 2; + + _g->m_x2 = _g->m_x + _g->m_w; + _g->m_y2 = _g->m_y + _g->m_h; +} + +// +// AM_initVariables() +// +// Initialize the variables for the automap +// +// Affects the automap global variables +// Status bar is notified that the automap has been entered +// Passed nothing, returns nothing +// +static void AM_initVariables(void) +{ + static const event_t st_notify = {ev_keyup, AM_MSGENTERED, 0, 0}; + + _g->automapmode |= am_active; + + _g->f_oldloc.x = INT_MAX; + + _g->m_paninc.x = _g->m_paninc.y = 0; + + _g->m_w = FTOM(f_w); + _g->m_h = FTOM(f_h); + + _g->m_x = (_g->player.mo->x >> FRACTOMAPBITS) - _g->m_w / 2; // e6y + _g->m_y = (_g->player.mo->y >> FRACTOMAPBITS) - _g->m_h / 2; // e6y + AM_changeWindowLoc(); + + // inform the status bar of the change + ST_Responder(&st_notify); +} + +// +// AM_LevelInit() +// +// Initialize the automap at the start of a new level +// should be called at the start of every level +// +// Passed nothing, returns nothing +// Affects automap's global variables +// +// CPhipps - get status bar height from status bar code +static void AM_LevelInit(void) +{ + // _g->f_x = _g->f_y = 0; + // _g->f_w = SCREENWIDTH_PHYSICAL; // killough 2/7/98: get rid of finit_ vars + // _g->f_h = SCREENHEIGHT-ST_SCALED_HEIGHT;// to allow runtime setting of width/height + printf("AM_LevelInit()\r\n"); + AM_findMinMaxBoundaries(); + _g->scale_mtof = FixedDiv(_g->min_scale_mtof, (int)(0.7 * FRACUNIT)); + if (_g->scale_mtof > _g->max_scale_mtof) + _g->scale_mtof = _g->min_scale_mtof; + _g->scale_ftom = FixedDiv(FRACUNIT, _g->scale_mtof); +} + +// +// AM_Stop() +// +// Cease automap operations, unload patches, notify status bar +// +// Passed nothing, returns nothing +// +void AM_Stop(void) +{ + static const event_t st_notify = {0, ev_keyup, AM_MSGEXITED, 0}; + printf("AM_Stop()\r\n"); + _g->automapmode = 0; + ST_Responder(&st_notify); + _g->stopped = true; +} + +// +// AM_Start() +// +// Start up automap operations, +// if a new level, or game start, (re)initialize level variables +// init map variables +// load mark patches +// +// Passed nothing, returns nothing +// +void AM_Start(void) +{ + if (!_g->stopped) + AM_Stop(); + printf("AM_Start()\r\n"); + _g->stopped = false; + if (_g->lastlevel != _g->gamemap || _g->lastepisode != _g->gameepisode) + { + AM_LevelInit(); + _g->lastlevel = _g->gamemap; + _g->lastepisode = _g->gameepisode; + } + printf("AM_initVariables()\r\n"); + AM_initVariables(); + printf("AM_initVariablesafter()\r\n"); +} + +// +// AM_minOutWindowScale() +// +// Set the window scale to the maximum size +// +// Passed nothing, returns nothing +// +static void AM_minOutWindowScale(void) +{ + _g->scale_mtof = _g->min_scale_mtof; + _g->scale_ftom = FixedDiv(FRACUNIT, _g->scale_mtof); + AM_activateNewScale(); +} + +// +// AM_maxOutWindowScale(void) +// +// Set the window scale to the minimum size +// +// Passed nothing, returns nothing +// +static void AM_maxOutWindowScale(void) +{ + _g->scale_mtof = _g->max_scale_mtof; + _g->scale_ftom = FixedDiv(FRACUNIT, _g->scale_mtof); + AM_activateNewScale(); +} + +// +// AM_Responder() +// +// Handle events (user inputs) in automap mode +// +// Passed an input event, returns true if its handled +// +boolean AM_Responder(event_t * ev) +{ + int rc; + int ch; // phares + + rc = false; + + if (!(_g->automapmode & am_active)) + { + if (ev->type == ev_keydown && ev->data1 == key_map) // phares + { + AM_Start(); + rc = true; + } + } + else if (ev->type == ev_keydown) + { + rc = true; + ch = ev->data1; // phares + + if (ch == key_map_right) + if (!(_g->automapmode & am_follow)) + _g->m_paninc.x = FTOM(F_PANINC); + else + rc = false; + else if (ch == key_map_left) + if (!(_g->automapmode & am_follow)) + _g->m_paninc.x = -FTOM(F_PANINC); + else + rc = false; + else if (ch == key_map_up) + if (!(_g->automapmode & am_follow)) + _g->m_paninc.y = FTOM(F_PANINC); + else + rc = false; + else if (ch == key_map_down) + if (!(_g->automapmode & am_follow)) + _g->m_paninc.y = -FTOM(F_PANINC); + else + rc = false; + else if (ch == key_map) + { + if (_g->automapmode & am_overlay) + AM_Stop(); + else + _g->automapmode |= (am_overlay | am_rotate | am_follow); + } + else if (ch == key_map_follow && _g->gamekeydown[key_use]) + { + _g->automapmode ^= am_follow; // CPhipps - put all automap mode stuff into one enum + _g->f_oldloc.x = INT_MAX; + // Ty 03/27/98 - externalized + _g->player.message = (_g->automapmode & am_follow) ? AMSTR_FOLLOWON : AMSTR_FOLLOWOFF; + } // | + else if (ch == key_map_zoomout) + { + _g->mtof_zoommul = M_ZOOMOUT; + _g->ftom_zoommul = M_ZOOMIN; + } + else if (ch == key_map_zoomin) + { + _g->mtof_zoommul = M_ZOOMIN; + _g->ftom_zoommul = M_ZOOMOUT; + } + else // phares + { + rc = false; + } + } + else if (ev->type == ev_keyup) + { + rc = false; + ch = ev->data1; + if (ch == key_map_right) + { + if (!(_g->automapmode & am_follow)) + _g->m_paninc.x = 0; + } + else if (ch == key_map_left) + { + if (!(_g->automapmode & am_follow)) + _g->m_paninc.x = 0; + } + else if (ch == key_map_up) + { + if (!(_g->automapmode & am_follow)) + _g->m_paninc.y = 0; + } + else if (ch == key_map_down) + { + if (!(_g->automapmode & am_follow)) + _g->m_paninc.y = 0; + } + else if ((ch == key_map_zoomout) || (ch == key_map_zoomin)) + { + _g->mtof_zoommul = FRACUNIT; + _g->ftom_zoommul = FRACUNIT; + } + } + return rc; +} + +// +// AM_rotate() +// +// Rotation in 2D. +// Used to rotate player arrow line character. +// +// Passed the coordinates of a point, and an angle +// Returns the coordinates rotated by the angle +// +// CPhipps - made static & enhanced for automap rotation + +static void AM_rotate(fixed_t * x, fixed_t * y, angle_t a, fixed_t xorig, fixed_t yorig) +{ + fixed_t tmpx; + + // e6y + xorig >>= FRACTOMAPBITS; + yorig >>= FRACTOMAPBITS; + + tmpx = FixedMul(*x - xorig, finecosine[a >> ANGLETOFINESHIFT]) - FixedMul(*y - yorig, finesine[a >> ANGLETOFINESHIFT]); + + *y = yorig + FixedMul(*x - xorig, finesine[a >> ANGLETOFINESHIFT]) + FixedMul(*y - yorig, finecosine[a >> ANGLETOFINESHIFT]); + + *x = tmpx + xorig; +} + +// +// AM_changeWindowScale() +// +// Automap zooming +// +// Passed nothing, returns nothing +// +static void AM_changeWindowScale(void) +{ + // Change the scaling multipliers + _g->scale_mtof = FixedMul(_g->scale_mtof, _g->mtof_zoommul); + _g->scale_ftom = FixedDiv(FRACUNIT, _g->scale_mtof); + + if (_g->scale_mtof < _g->min_scale_mtof) + AM_minOutWindowScale(); + else if (_g->scale_mtof > _g->max_scale_mtof) + AM_maxOutWindowScale(); + else + AM_activateNewScale(); +} + +// +// AM_doFollowPlayer() +// +// Turn on follow mode - the map scrolls opposite to player motion +// +// Passed nothing, returns nothing +// +static void AM_doFollowPlayer(void) +{ + if (_g->f_oldloc.x != _g->player.mo->x || _g->f_oldloc.y != _g->player.mo->y) + { + _g->m_x = FTOM(MTOF(_g->player.mo->x >> FRACTOMAPBITS)) - _g->m_w / 2; // e6y + _g->m_y = FTOM(MTOF(_g->player.mo->y >> FRACTOMAPBITS)) - _g->m_h / 2; // e6y + _g->m_x2 = _g->m_x + _g->m_w; + _g->m_y2 = _g->m_y + _g->m_h; + _g->f_oldloc.x = _g->player.mo->x; + _g->f_oldloc.y = _g->player.mo->y; + } +} + +// +// AM_Ticker() +// +// Updates on gametic - enter follow mode, zoom, or change map location +// +// Passed nothing, returns nothing +// +void AM_Ticker(void) +{ +#if USEMAP + if (!(_g->automapmode & am_active)) + return; + + if (_g->automapmode & am_follow) + AM_doFollowPlayer(); + + // Change the zoom if necessary + if (_g->ftom_zoommul != FRACUNIT) + AM_changeWindowScale(); + + // Change x,y location + if (_g->m_paninc.x || _g->m_paninc.y) + AM_changeWindowLoc(); +#endif +} + +// +// AM_clipMline() +// +// Automap clipping of lines. +// +// Based on Cohen-Sutherland clipping algorithm but with a slightly +// faster reject and precalculated slopes. If the speed is needed, +// use a hash algorithm to handle the common cases. +// +// Passed the line's coordinates on map and in the frame buffer performs +// clipping on them in the lines frame coordinates. +// Returns true if any part of line was not clipped +// +static boolean AM_clipMline(mline_t * ml, fline_t * fl) +{ + enum + { + LEFT = 1, + RIGHT = 2, + BOTTOM = 4, + TOP = 8 + }; + + register int outcode1 = 0; + register int outcode2 = 0; + register int outside; + + fpoint_t tmp; + int dx; + int dy; + +#define DOOUTCODE(oc, mx, my) \ + (oc) = 0; \ + if ((my) < 0) \ + (oc) |= TOP; \ + else if ((my) >= f_h) \ + (oc) |= BOTTOM; \ + if ((mx) < 0) \ + (oc) |= LEFT; \ + else if ((mx) >= f_w) \ + (oc) |= RIGHT; + + // do trivial rejects and outcodes + if (ml->a.y > _g->m_y2) + outcode1 = TOP; + else if (ml->a.y < _g->m_y) + outcode1 = BOTTOM; + + if (ml->b.y > _g->m_y2) + outcode2 = TOP; + else if (ml->b.y < _g->m_y) + outcode2 = BOTTOM; + + if (outcode1 & outcode2) + return false; // trivially outside + + if (ml->a.x < _g->m_x) + outcode1 |= LEFT; + else if (ml->a.x > _g->m_x2) + outcode1 |= RIGHT; + + if (ml->b.x < _g->m_x) + outcode2 |= LEFT; + else if (ml->b.x > _g->m_x2) + outcode2 |= RIGHT; + + if (outcode1 & outcode2) + return false; // trivially outside + + // transform to frame-buffer coordinates. + fl->a.x = CXMTOF(ml->a.x); + fl->a.y = CYMTOF(ml->a.y); + fl->b.x = CXMTOF(ml->b.x); + fl->b.y = CYMTOF(ml->b.y); + + DOOUTCODE(outcode1, fl->a.x, fl->a.y) + DOOUTCODE(outcode2, fl->b.x, fl->b.y) + + if (outcode1 & outcode2) + return false; + + while (outcode1 | outcode2) + { + // may be partially inside box + // find an outside point + if (outcode1) + outside = outcode1; + else + outside = outcode2; + + // clip to each side + if (outside & TOP) + { + dy = fl->a.y - fl->b.y; + dx = fl->b.x - fl->a.x; + tmp.x = fl->a.x + (dx * (fl->a.y)) / dy; + tmp.y = 0; + } + else if (outside & BOTTOM) + { + dy = fl->a.y - fl->b.y; + dx = fl->b.x - fl->a.x; + tmp.x = fl->a.x + (dx * (fl->a.y - f_h)) / dy; + tmp.y = f_h - 1; + } + else if (outside & RIGHT) + { + dy = fl->b.y - fl->a.y; + dx = fl->b.x - fl->a.x; + tmp.y = fl->a.y + (dy * (f_w - 1 - fl->a.x)) / dx; + tmp.x = f_w - 1; + } + else if (outside & LEFT) + { + dy = fl->b.y - fl->a.y; + dx = fl->b.x - fl->a.x; + tmp.y = fl->a.y + (dy * (-fl->a.x)) / dx; + tmp.x = 0; + } + + if (outside == outcode1) + { + fl->a = tmp; + DOOUTCODE(outcode1, fl->a.x, fl->a.y) + } + else + { + fl->b = tmp; + DOOUTCODE(outcode2, fl->b.x, fl->b.y) + } + + if (outcode1 & outcode2) + return false; // trivially outside + } + + return true; +} +#undef DOOUTCODE + +// +// AM_drawMline() +// +// Clip lines, draw visible parts of lines. +// +// Passed the map coordinates of the line, and the color to draw it +// Color -1 is special and prevents drawing. Color 247 is special and +// is translated to black, allowing Color 0 to represent feature disable +// in the defaults file. +// Returns nothing. +// +static void AM_drawMline(mline_t * ml, int color) +{ + fline_t fl; + + if (color == -1) // jff 4/3/98 allow not drawing any sort of line + return; // by setting its color to -1 + if (color == 247) // jff 4/3/98 if color is 247 (xparent), use black + color = 0; + + if (AM_clipMline(ml, &fl)) + V_DrawLine(&fl, color); // draws it on frame buffer using fb coords +} + +// +// AM_drawGrid() +// +// Draws blockmap aligned grid lines. +// +// Passed the color to draw the grid lines +// Returns nothing +// +static void AM_drawGrid(int color) +{ + fixed_t x, y; + fixed_t start, end; + mline_t ml; + + // Figure out start of vertical gridlines + start = _g->m_x; + if ((start - _g->bmaporgx) % (MAPBLOCKUNITS << MAPBITS)) // e6y + start += (MAPBLOCKUNITS << MAPBITS) // e6y + - ((start - _g->bmaporgx) % (MAPBLOCKUNITS << MAPBITS)); // e6y + end = _g->m_x + _g->m_w; + + // draw vertical gridlines + ml.a.y = _g->m_y; + ml.b.y = _g->m_y + _g->m_h; + for (x = start; x < end; x += (MAPBLOCKUNITS << MAPBITS)) // e6y + { + ml.a.x = x; + ml.b.x = x; + AM_drawMline(&ml, color); + } + + // Figure out start of horizontal gridlines + start = _g->m_y; + if ((start - _g->bmaporgy) % (MAPBLOCKUNITS << MAPBITS)) // e6y + start += (MAPBLOCKUNITS << MAPBITS) // e6y + - ((start - _g->bmaporgy) % (MAPBLOCKUNITS << MAPBITS)); // e6y + end = _g->m_y + _g->m_h; + + // draw horizontal gridlines + ml.a.x = _g->m_x; + ml.b.x = _g->m_x + _g->m_w; + for (y = start; y < end; y += (MAPBLOCKUNITS << MAPBITS)) // e6y + { + ml.a.y = y; + ml.b.y = y; + AM_drawMline(&ml, color); + } +} + +// +// AM_DoorColor() +// +// Returns the 'color' or key needed for a door linedef type +// +// Passed the type of linedef, returns: +// -1 if not a keyed door +// 0 if a red key required +// 1 if a blue key required +// 2 if a yellow key required +// 3 if a multiple keys required +// +// jff 4/3/98 add routine to get color of generalized keyed door +// +static int AM_DoorColor(int type) +{ + if (GenLockedBase <= type && type < GenDoorBase) + { + type -= GenLockedBase; + type = (type & LockedKey) >> LockedKeyShift; + if (!type || type == 7) + return 3; // any or all keys + else + return (type - 1) % 3; + } + switch (type) + // closed keyed door + { + case 26: + case 32: + case 99: + case 133: + /*bluekey*/ + return 1; + case 27: + case 34: + case 136: + case 137: + /*yellowkey*/ + return 2; + case 28: + case 33: + case 134: + case 135: + /*redkey*/ + return 0; + default: + return -1; // not a keyed door + } +} + +// +// Determines visible lines, draws them. +// This is LineDef based, not LineSeg based. +// +// jff 1/5/98 many changes in this routine +// backward compatibility not needed, so just changes, no ifs +// addition of clauses for: +// doors opening, keyed door id, secret sectors, +// teleports, exit lines, key things +// ability to suppress any of added features or lines with no height changes +// +// support for gamma correction in automap abandoned +// +// jff 4/3/98 changed mapcolor_xxxx=0 as control to disable feature +// jff 4/3/98 changed mapcolor_xxxx=-1 to disable drawing line completely +// +static void AM_drawWalls(void) +{ + int i; + mline_t l; + + // draw the unclipped visible portions of all lines + for (i = 0; i < _g->numlines; i++) + { + l.a.x = _g->lines[i].v1.x >> FRACTOMAPBITS; // e6y + l.a.y = _g->lines[i].v1.y >> FRACTOMAPBITS; // e6y + l.b.x = _g->lines[i].v2.x >> FRACTOMAPBITS; // e6y + l.b.y = _g->lines[i].v2.y >> FRACTOMAPBITS; // e6y + + const sector_t * backsector = LN_BACKSECTOR(&_g->lines[i]); + const sector_t * frontsector = LN_FRONTSECTOR(&_g->lines[i]); + + const unsigned int line_special = LN_SPECIAL(&_g->lines[i]); + + if (_g->automapmode & am_rotate) + { + AM_rotate(&l.a.x, &l.a.y, ANG90 - _g->player.mo->angle, _g->player.mo->x, _g->player.mo->y); + AM_rotate(&l.b.x, &l.b.y, ANG90 - _g->player.mo->angle, _g->player.mo->x, _g->player.mo->y); + } + + // if line has been seen or IDDT has been used + if (_g->linedata[i].r_flags & RF_MAPPED) // 2020-03-14 next-hack was ML_MAPPED, changed to RF_MAPPED + { + if (_g->lines[i].flags & ML_DONTDRAW) + continue; + { + /* cph - show keyed doors and lines */ + int amd; + if ((mapcolor_bdor || mapcolor_ydor || mapcolor_rdor) && !(_g->lines[i].flags & ML_SECRET) && /* non-secret */ + (amd = AM_DoorColor(line_special)) != -1) + { + { + switch (amd) + /* closed keyed door */ + { + case 1: + /*bluekey*/ + AM_drawMline(&l, mapcolor_bdor ? mapcolor_bdor : mapcolor_cchg); + continue; + case 2: + /*yellowkey*/ + AM_drawMline(&l, mapcolor_ydor ? mapcolor_ydor : mapcolor_cchg); + continue; + case 0: + /*redkey*/ + AM_drawMline(&l, mapcolor_rdor ? mapcolor_rdor : mapcolor_cchg); + continue; + case 3: + /*any or all*/ + AM_drawMline(&l, mapcolor_clsd ? mapcolor_clsd : mapcolor_cchg); + continue; + } + } + } + } + if /* jff 4/23/98 add exit lines to automap */ + (mapcolor_exit && + (line_special == 11 || line_special == 52 || line_special == 197 || line_special == 51 || line_special == 124 || line_special == 198)) + { + AM_drawMline(&l, mapcolor_exit); /* exit line */ + continue; + } + + if (!backsector) + { + // jff 1/10/98 add new color for 1S secret sector boundary + if (mapcolor_secr && // jff 4/3/98 0 is disable + ((map_secret_after && P_WasSecret(frontsector) && !P_IsSecret(frontsector)) || (!map_secret_after && P_WasSecret(frontsector)))) + AM_drawMline(&l, mapcolor_secr); // line bounding secret sector + else + // jff 2/16/98 fixed bug + AM_drawMline(&l, mapcolor_wall); // special was cleared + } + else /* now for 2S lines */ + { + // jff 1/10/98 add color change for all teleporter types + if (mapcolor_tele && !(_g->lines[i].flags & ML_SECRET) && + (line_special == 39 || line_special == 97 || line_special == 125 || line_special == 126)) + { // teleporters + AM_drawMline(&l, mapcolor_tele); + } + else if (_g->lines[i].flags & ML_SECRET) // secret door + { + AM_drawMline(&l, mapcolor_wall); // wall color + } + else if (mapcolor_clsd && !(_g->lines[i].flags & ML_SECRET) && // non-secret closed door + ((backsector->floorheight == backsector->ceilingheight) || (frontsector->floorheight == frontsector->ceilingheight))) + { + AM_drawMline(&l, mapcolor_clsd); // non-secret closed door + } // jff 1/6/98 show secret sector 2S lines + else if (mapcolor_secr && // jff 2/16/98 fixed bug + ( // special was cleared after getting it + (map_secret_after && + ((P_WasSecret(frontsector) && !P_IsSecret(frontsector)) || + (P_WasSecret(backsector) && !P_IsSecret(backsector)))) || // jff 3/9/98 add logic to not show secret til after entered + ( // if map_secret_after is true + !map_secret_after && (P_WasSecret(frontsector) || P_WasSecret(backsector))))) + { + AM_drawMline(&l, mapcolor_secr); // line bounding secret sector + } // jff 1/6/98 end secret sector line change + else if (backsector->floorheight != frontsector->floorheight) + { + AM_drawMline(&l, mapcolor_fchg); // floor level change + } + else if (backsector->ceilingheight != frontsector->ceilingheight) + { + AM_drawMline(&l, mapcolor_cchg); // ceiling level change + } + } + } // now draw the lines only visible because the player has computermap + else if (_g->player.powers[pw_allmap]) // computermap visible lines + { + if (!(_g->lines[i].flags & ML_DONTDRAW)) // invisible flag lines do not show + { + if (mapcolor_flat || !backsector || backsector->floorheight != frontsector->floorheight || + backsector->ceilingheight != frontsector->ceilingheight) + AM_drawMline(&l, mapcolor_unsn); + } + } + } +} + +// +// AM_drawLineCharacter() +// +// Draws a vector graphic according to numerous parameters +// +// Passed the structure defining the vector graphic shape, the number +// of vectors in it, the scale to draw it at, the angle to draw it at, +// the color to draw it with, and the map coordinates to draw it at. +// Returns nothing +// +static void AM_drawLineCharacter(const mline_t * lineguy, int lineguylines, fixed_t scale, angle_t angle, int color, fixed_t x, fixed_t y) +{ + int i; + mline_t l; + + if (_g->automapmode & am_rotate) + angle -= _g->player.mo->angle - ANG90; // cph + + for (i = 0; i < lineguylines; i++) + { + l.a.x = lineguy[i].a.x; + l.a.y = lineguy[i].a.y; + + if (scale) + { + l.a.x = FixedMul(scale, l.a.x); + l.a.y = FixedMul(scale, l.a.y); + } + + if (angle) + AM_rotate(&l.a.x, &l.a.y, angle, 0, 0); + + l.a.x += x; + l.a.y += y; + + l.b.x = lineguy[i].b.x; + l.b.y = lineguy[i].b.y; + + if (scale) + { + l.b.x = FixedMul(scale, l.b.x); + l.b.y = FixedMul(scale, l.b.y); + } + + if (angle) + AM_rotate(&l.b.x, &l.b.y, angle, 0, 0); + + l.b.x += x; + l.b.y += y; + + AM_drawMline(&l, color); + } +} + +// +// AM_drawPlayers() +// +// Draws the player arrow in single player, +// +// Passed nothing, returns nothing +// +static void AM_drawPlayers(void) +{ + + AM_drawLineCharacter(player_arrow, NUMPLYRLINES, 0, _g->player.mo->angle, mapcolor_sngl, // jff color + _g->player.mo->x >> FRACTOMAPBITS, // e6y + _g->player.mo->y >> FRACTOMAPBITS); // e6y +} + +// +// AM_Drawer() +// +// Draws the entire automap +// +// Passed nothing, returns nothing +// +void AM_Drawer(void) +{ +#if USEMAP + // CPhipps - all automap modes put into one enum + if (!(_g->automapmode & am_active)) + return; + + if (!(_g->automapmode & am_overlay)) // cph - If not overlay mode, clear background for the automap + { + + V_FillRect(f_x, f_y, f_w, f_h, (byte)mapcolor_back); // jff 1/5/98 background default color + } + if (_g->automapmode & am_grid) + { + + AM_drawGrid(mapcolor_grid); // jff 1/7/98 grid default color + } + + AM_drawWalls(); + + AM_drawPlayers(); + +#endif +} \ No newline at end of file diff --git a/doom/src/pdoom/Doom/source/d_client.c b/doom/src/pdoom/Doom/source/d_client.c new file mode 100644 index 0000000..67d493d --- /dev/null +++ b/doom/src/pdoom/Doom/source/d_client.c @@ -0,0 +1,168 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * next-hack: On this port no multplayer is supported. + * Here we use the display-buffer (15kB) as stack, so we + * do not need to worry for stack overflows at least when dealing + * with Doom game-logic handling. + * + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_SYS_WAIT_H +#include +#endif + +#include "doomtype.h" +#include "doomstat.h" +#include "d_net.h" +#include "z_zone.h" + +#include "d_main.h" +#include "g_game.h" +#include "m_menu.h" + +#include "protocol.h" +#include "i_network.h" +#include "i_system.h" +#include "i_main.h" +#include "i_video.h" +#include "lprintf.h" + +#include "global_data.h" +#include "graphics.h" +void D_InitNetGame(void) +{ + _g->playeringame = true; +} + +void D_BuildNewTiccmds(void) +{ + int newtics = I_GetTime() - _g->lastmadetic; + _g->lastmadetic += newtics; + + while (newtics--) + { + I_StartTic(); + if (_g->maketic - _g->gametic > 3) + break; + + G_BuildTiccmd(&_g->netcmd); + _g->maketic++; + } +} + +void TryRunTics2(void) +{ + int runtics; + int entertime = I_GetTime(); + + // Wait for tics to run + static int plog_tr; int plog_b = 0; + if (plog_tr < 3) PLOG(0x300 + plog_tr * 0x10); + while (1) + { + D_BuildNewTiccmds(); + if (plog_tr < 3 && !plog_b) { PLOG(0x301 + plog_tr * 0x10); plog_b = 1; } + + runtics = (_g->maketic) - _g->gametic; + if (runtics <= 0) + { + if (I_GetTime() - entertime > 10) + { + M_Ticker(); + if (plog_tr < 3) { PLOG(0x30F + plog_tr * 0x10); plog_tr++; } + return; + } + } + else + break; + } + + while (runtics-- > 0) + { + + if (_g->advancedemo) + D_DoAdvanceDemo(); + if (plog_tr < 3) PLOG(0x302 + plog_tr * 0x10); + M_Ticker(); + if (plog_tr < 3) PLOG(0x303 + plog_tr * 0x10); + G_Ticker(); + if (plog_tr < 3) PLOG(0x304 + plog_tr * 0x10); + + _g->gametic++; + } + if (plog_tr < 3) plog_tr++; +} +void TryRunTics(void) +{ +#ifdef NO_STACK_SWITCH + /* v0.1.9: game loop on the normal stack in SRAM instead of in the framebuffer (RAM20) */ + TryRunTics2(); + return; +#endif + // "displayData.displayFrameBuffer[displayData.workingBuffer]" is a very large buffer, which will be modified + // by the game rendering AFTER the game logic has been called, and for sure is not the one used by the DMA. + // Why not using it as stack ? + // Note, why "-SCREEN_WIDTH * ST_HEIGHT - 4"? Because in this way, when the status bar does not need an update (i.e. no change in ammo, health, etc.) + // we can avoid redrawing it, saving a lot of time. + __asm volatile + ( + "STR SP, [%[newStack]], #-4\n\t" + "MOV SP, %[newStack]\n\t" + : : [newStack] "r" ((uint8_t*) displayData.displayFrameBuffer[displayData.workingBuffer] + sizeof(displayData.displayFrameBuffer[0]) - SCREENWIDTH * ST_HEIGHT - 4) + ); + // actually run doom game + TryRunTics2(); + // restore stack + __asm volatile + ( + "LDR SP, [%[newStack]]\n\t" + : : [newStack] "r" ((uint8_t*) displayData.displayFrameBuffer[displayData.workingBuffer] + sizeof(displayData.displayFrameBuffer[0]) - SCREENWIDTH * ST_HEIGHT - 4) + ); + +} diff --git a/doom/src/pdoom/Doom/source/d_items.c b/doom/src/pdoom/Doom/source/d_items.c new file mode 100644 index 0000000..c2671bd --- /dev/null +++ b/doom/src/pdoom/Doom/source/d_items.c @@ -0,0 +1,81 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Something to do with weapon sprite frames. Don't ask me. + * + *----------------------------------------------------------------------------- + */ + +// We are referring to sprite numbers. +#include "doomtype.h" +#include "info.h" + +#include "d_items.h" + +// +// PSPRITE ACTIONS for waepons. +// This struct controls the weapon animations. +// +// Each entry is: +// ammo/amunition type +// upstate +// downstate +// readystate +// atkstate, i.e. attack/fire/hit frame +// flashstate, muzzle flash +// +const weaponinfo_t weaponinfo[NUMWEAPONS] = { + {// fist + am_noammo, S_PUNCHUP, S_PUNCHDOWN, S_PUNCH, S_PUNCH1, S_NULL + }, + {// pistol + am_clip, S_PISTOLUP, S_PISTOLDOWN, S_PISTOL, S_PISTOL1, S_PISTOLFLASH + }, + {// shotgun + am_shell, S_SGUNUP, S_SGUNDOWN, S_SGUN, S_SGUN1, S_SGUNFLASH1 + }, + {// chaingun + am_clip, S_CHAINUP, S_CHAINDOWN, S_CHAIN, S_CHAIN1, S_CHAINFLASH1 + }, + {// missile launcher + am_misl, S_MISSILEUP, S_MISSILEDOWN, S_MISSILE, S_MISSILE1, S_MISSILEFLASH1 + }, + {// plasma rifle + am_cell, S_PLASMAUP, S_PLASMADOWN, S_PLASMA, S_PLASMA1, S_PLASMAFLASH1 + }, + {// bfg 9000 + am_cell, S_BFGUP, S_BFGDOWN, S_BFG, S_BFG1, S_BFGFLASH1 + }, + {// chainsaw + am_noammo, S_SAWUP, S_SAWDOWN, S_SAW, S_SAW1, S_NULL + }, + {// super shotgun + am_shell, S_DSGUNUP, S_DSGUNDOWN, S_DSGUN, S_DSGUN1, S_DSGUNFLASH1 + }, +}; \ No newline at end of file diff --git a/doom/src/pdoom/Doom/source/d_main.c b/doom/src/pdoom/Doom/source/d_main.c new file mode 100644 index 0000000..3ca6fac --- /dev/null +++ b/doom/src/pdoom/Doom/source/d_main.c @@ -0,0 +1,981 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * DOOM main program (D_DoomMain) and game loop (D_DoomLoop), + * plus functions to determine game mode (shareware, registered), + * parse command line parameters, configure game parameters (turbo), + * and call the startup functions. + * next-hack: modified setup order to support flash caching. + * also removed if-less handling of input events. + * + *----------------------------------------------------------------------------- + */ + + +#include "doomdef.h" +#include "doomtype.h" +#include "doomstat.h" +#include "d_net.h" +#include "dstrings.h" +#include "sounds.h" +#include "z_zone.h" +#include "w_wad.h" +#include "s_sound.h" +#include "v_video.h" +#include "f_finale.h" +#include "f_wipe.h" +#include "m_misc.h" +#include "m_menu.h" +#include "i_main.h" +#include "i_system.h" +#include "i_sound.h" +#include "i_video.h" +#include "g_game.h" +#include "hu_stuff.h" +#include "wi_stuff.h" +#include "st_stuff.h" +#include "am_map.h" +#include "p_setup.h" +#include "r_draw.h" +#include "r_main.h" +#include "d_main.h" +#include "lprintf.h" // jff 08/03/98 - declaration of lprintf +#include "am_map.h" +#include "m_cheat.h" + +#include "doom_iwad.h" +#include "global_data.h" +#include "i_spi_support.h" +#include "pwm_audio.h" +#include "graphics.h" +#include "main.h" +#include "delay.h" +static int g_plog_loops; + +void GetFirstMap(int *ep, int *map); // Ty 08/29/98 - add "-warp x" functionality +static void D_PageDrawer(void); +static void D_UpdateFPS(void); + +// CPhipps - removed wadfiles[] stuff + +//jff 1/22/98 parms for disabling music and sound +const boolean nosfxparm = false; +#if defined(PARADISE_DEV) && defined(MUS_PLAY) +const boolean nomusicparm = false; /* v0.2.5: music on the buzzer */ +#else +const boolean nomusicparm = true; +#endif + +const skill_t startskill = sk_medium; +const int startepisode = 1; +const int startmap = 1; + +const boolean nodrawers = false; + +static const char *timedemo = NULL; //"demo1"; + +/* + * D_PostEvent - Event handling + * + * Called by I/O functions when an event is received. + * Try event handlers for each code area in turn. + * cph - in the true spirit of the Boom source, let the + * short ciruit operator madness begin! + * + * next-hack: nah, the original code was very unreadable, and threw + * a warning too, as the result of the statement was not read. Better to + * get closer to 2021 standards. + * + */ + +void D_PostEvent(event_t *ev) +{ + /* cph - suppress all input events at game start + * FIXME: This is a lousy kludge */ + if (_g->gametic < 3) + return; + // next-hack: I understand you love short-circuits, but the original code + // was too much over the line. + if (!M_Responder(ev)) + { + if (!(_g->gamestate == GS_LEVEL && (C_Responder(ev) || HU_Responder(ev) || ST_Responder(ev) || AM_Responder(ev)))) + { + G_Responder(ev); + } + } +} + +// +// D_Wipe +// +// CPhipps - moved the screen wipe code from D_Display to here +// The screens to wipe between are already stored, this just does the timing +// and screen updating +static void D_Wipe(void) +{ + short tmp_y_lookup[SCREENWIDTH]; // on the stack. We have plenty. + boolean done = false; + int wipestart = I_GetTime() - 1; + wipe_initMelt(tmp_y_lookup); + displayData.workingBuffer = 1 - displayData.workingBuffer; + do + { + int nowtime, tics; + do + { + nowtime = I_GetTime(); + tics = nowtime - wipestart; + } while (!tics); + + wipestart = nowtime; + done = wipe_ScreenWipe(tics, tmp_y_lookup); +// 2021-08-08 next-hack: Due to memory constraint we cannot draw the menu over. Never mind. +// M_Drawer(); // menu is drawn even on top of wipes + I_FinishUpdateBlock(); // page flip or blit buffer + // 2021-08-08 next-hack: during wipes we use the two buffers, one contains the new scene, the other contains + // the old one. As a result we cannot use double buffering, and we need to wait for DMA to finish update + while (displayData.dmaBusy) + { + } + // I_FinishUpdateBlock will swap buffers, but we don't want it. + displayData.workingBuffer = 1 - displayData.workingBuffer; + } while (!done); +} + +// +// D_Display +// draw current display, possibly wiping it from the previous +// + +static void D_Display(void) +{ + + boolean wipe; + boolean viewactive = false; + + if (nodrawers) // for comparative timing / profiling + return; + + if (!I_StartDisplay()) + return; + + // save the current screen if about to wipe + if (g_plog_loops < 4) PLOG(0x200); +#ifdef SINGLE_FB + wipe = 0; /* one framebuffer: no wipe */ +#else + if ((wipe = (_g->gamestate != _g->wipegamestate))) + wipe_StartScreen(); +#endif + if (g_plog_loops < 4) PLOG(0x201); + + _g->screens[0].data = displayData.displayFrameBuffer[displayData.workingBuffer]; + drawvars.byte_topleft = _g->screens[0].data; + draw_stopy = SCREENHEIGHT - ST_SCALED_HEIGHT - 1; + draw_starty = 0; + if (_g->gamestate != GS_LEVEL) + { // Not a level + + if (_g->oldgamestate == GS_LEVEL) + { + V_SetPalette(0); // cph - use default (basic) palette + } + + switch (_g->gamestate) + { + case GS_INTERMISSION: + WI_Drawer(); + break; + case GS_FINALE: + F_Drawer(); + break; + case GS_DEMOSCREEN: + if (g_plog_loops < 4) PLOG(0x202); D_PageDrawer(); if (g_plog_loops < 4) PLOG(0x203); + break; + default: + break; + } + } + else if (_g->gametic != _g->basetic) + { // In a level + HU_Erase(); + + // Work out if the player view is visible, and if there is a border + // TODO: BUG if viewactive is false, then automap will lock the system. + // It seems to me that R_RenderBSPNode is required before. + viewactive = (!(_g->automapmode & am_active) || (_g->automapmode & am_overlay)); + // Now do the drawing + if (viewactive) + R_RenderPlayerView(&_g->player); + if ((_g->automapmode & am_active)) + AM_Drawer(); + + HU_Drawer(); + draw_stopy = SCREENHEIGHT - 1; + ST_Drawer(true, false); // status bar on, do not force refresh + + } + + _g->oldgamestate = _g->wipegamestate = _g->gamestate; + + // draw pause pic + if (_g->paused) + { + // Simplified the "logic" here and no need for x-coord caching - POPE + V_DrawNamePatch((320 - V_NamePatchWidth("M_PAUSE"))/2, 4, 0, "M_PAUSE", CR_DEFAULT, VPT_STRETCH); + } + + // menus go directly to the screen + if (g_plog_loops < 4) PLOG(0x204); + M_Drawer(); // menu is drawn even on top of everything + if (g_plog_loops < 4) PLOG(0x205); + + D_BuildNewTiccmds(); + + // normal update + if (!wipe) + { + I_FinishUpdateBlock(); // page flip or blit buffer + } + else + { + // wipe update + wipe_EndScreen(); + { if (g_plog_loops < 4) PLOG(0x206); D_Wipe(); if (g_plog_loops < 4) PLOG(0x207); } + } + // + //I_EndDisplay(); // removed +} + +// +// D_DoomLoop() +// +// Not a globally visible function, +// just included for source reference, +// called by D_DoomMain, never exits. +// Manages timing and IO, +// calls all ?_Responder, ?_Ticker, and ?_Drawer, +// calls I_GetTime, I_StartFrame, and I_StartTic +// +int divisions; +extern int lumpByNameRequest; +static void D_DoomLoop(void) +{ + int oldMaxDivisions = 0; + int oldLumpByNameRequests = 0; +#if DEBUG_SETUP + // this to launch directly a new game without having to press keys... + // useful if you are in a hurry and want to test if new code is faster or slower. + bool startedGame = false; +#endif + // set default behavior of ammo widget. + _g->fps_show = SHOW_FPS; + // + restoreWirelessAudio(); + // + PLOG(6); + for (;;) + { + if (g_plog_loops < 4) PLOG(0x10 + g_plog_loops * 0x10); + if (!nosfxparm) + updateSound(); + // frame syncronous IO operations + divisions = 0; + lumpByNameRequest = 0; + + // process one or more tics + if (_g->singletics) // this is normally not executed + { + I_StartTic(); + G_BuildTiccmd(&_g->netcmd); + + if (_g->advancedemo) + D_DoAdvanceDemo(); + + M_Ticker(); + + G_Ticker(); + + _g->gametic++; + _g->maketic++; + } + else + { + TryRunTics(); // will run at least one tic + } + if (g_plog_loops < 4) PLOG(0x11 + g_plog_loops * 0x10); + // killough 3/16/98: change consoleplayer to displayplayer + if (_g->player.mo) // cph 2002/08/10 + S_UpdateSounds(_g->player.mo); // move positional sounds + // Update display, next frame, with current state. + D_Display(); + if (g_plog_loops < 4) { PLOG(0x12 + g_plog_loops * 0x10); g_plog_loops++; } + #if !MINEWDONGLE + handleDisplayBacklightToggle(); + #endif + #if 0 + if (oldMaxDivisions < divisions) + { + oldMaxDivisions = divisions; + printf("Max div/frame %d\r\n", oldMaxDivisions); + + } + if (oldLumpByNameRequests < lumpByNameRequest) + { + oldLumpByNameRequests = lumpByNameRequest; + printf("Max lumpByNameRequest per frame increased to %d\r\n", lumpByNameRequest); + + } + #endif + if (_g->fps_show) + { + D_UpdateFPS(); + } +#ifdef PD_AUTOSTART + { static int pd_started; if (!pd_started) { pd_started = 1; G_DeferedInitNew(2, 1, PD_AUTOSTART); } } +#endif +#if DEBUG_SETUP +#if AUTOSTART_GAME + if (!startedGame) + { + startedGame = true; + G_DeferedInitNew(2, 1, START_MAP); + } +#endif +#endif + } +} + +static void D_UpdateFPS() +{ + _g->fps_frames++; + + unsigned int timenow = I_GetTimeMicrosecs(); // this is running at 10MHz. + unsigned int elapsed = timenow - _g->fps_timebefore; + + if (elapsed >= 1000000UL) + { + _g->fps_framerate = (int) (_g->fps_frames * 10000000 / ((float) elapsed)); + _g->fps_frames = 0; + _g->fps_timebefore = timenow; + } +} + +// +// DEMO LOOP +// + +// +// D_PageTicker +// Handles timing for warped projection +// +void D_PageTicker(void) +{ + if (--_g->pagetic < 0) + D_AdvanceDemo(); +} + +// +// D_PageDrawer +// +static void D_PageDrawer(void) +{ + // proff/nicolas 09/14/98 -- now stretchs bitmaps to fullscreen! + // CPhipps - updated for new patch drawing + // proff - added M_DrawCredits + if (_g->pagelump) + { + + V_DrawNumPatch(0, 0, 0, _g->pagelump, CR_DEFAULT, VPT_STRETCH); + } + +} + +// +// D_AdvanceDemo +// Called after each demo or intro demosequence finishes +// +void D_AdvanceDemo(void) +{ + _g->advancedemo = true; +} + +/* killough 11/98: functions to perform demo sequences + * cphipps 10/99: constness fixes + */ + +static void D_SetPageName(const char *name) +{ + _g->pagelump = W_GetNumForName(name); +} + +static void D_DrawTitle1(const char *name) +{ + S_StartMusic(mus_intro); + _g->pagetic = (TICRATE * 30); + D_SetPageName(name); +} + +static void D_DrawTitle2(const char *name) +{ + S_StartMusic(mus_dm2ttl); + D_SetPageName(name); +} + +/* killough 11/98: tabulate demo sequences + */ + +static struct +{ + void (*func)(const char*); + const char *name; +} + +const demostates[][4] = +{ +#if 1 + { + { D_DrawTitle1, "TITLEPIC" }, + { D_DrawTitle1, "TITLEPIC" }, + { D_DrawTitle2, "TITLEPIC" }, + { D_DrawTitle1, "TITLEPIC" }, + }, + +#else + { + { G_DeferedPlayDemo, "demo3" }, + { G_DeferedPlayDemo, "demo3" }, + { G_DeferedPlayDemo, "demo3" }, + { G_DeferedPlayDemo, "demo3" }, + }, +#if 0 + { + { D_SetPageName, "TITLEPIC" }, + { D_SetPageName, "TITLEPIC" }, + { D_SetPageName, "TITLEPIC" }, + { D_SetPageName, "TITLEPIC" }, + }, + + { + { G_DeferedPlayDemo, "demo2" }, + { G_DeferedPlayDemo, "demo2" }, + { G_DeferedPlayDemo, "demo2" }, + { G_DeferedPlayDemo, "demo2" }, + }, + + { + { D_SetPageName, "TITLEPIC" }, + { D_SetPageName, "TITLEPIC" }, + { D_SetPageName, "TITLEPIC" }, + { D_SetPageName, "TITLEPIC" }, + }, + + { + { G_DeferedPlayDemo, "demo3" }, + { G_DeferedPlayDemo, "demo3" }, + { G_DeferedPlayDemo, "demo3" }, + { G_DeferedPlayDemo, "demo3" }, + }, + #endif +#endif + { + { NULL, NULL }, + { NULL, NULL }, + { NULL, NULL }, + { NULL, NULL }, + } +}; + +/* + * This cycles through the demo sequences. + * killough 11/98: made table-driven + */ + +void D_DoAdvanceDemo(void) +{ + _g->player.playerstate = PST_LIVE; /* not reborn */ + _g->advancedemo = _g->usergame = _g->paused = false; + _g->gameaction = ga_nothing; + + _g->pagetic = TICRATE * 11; /* killough 11/98: default behavior */ + _g->gamestate = GS_DEMOSCREEN; + + /* Paradise: no demos on the title screen (the WAD may not contain all maps) */ + do + { + if (!demostates[++_g->demosequence][_g->gamemode].func) + _g->demosequence = 0; + } while (demostates[_g->demosequence][_g->gamemode].func == G_DeferedPlayDemo); + + demostates[_g->demosequence][_g->gamemode].func(demostates[_g->demosequence][_g->gamemode].name); +} + +// +// D_StartTitle +// +void D_StartTitle(void) +{ + printf("Start Title\r\n"); + _g->gameaction = ga_nothing; + _g->demosequence = -1; + D_AdvanceDemo(); + printf("After AdvanceDemo()\r\n"); +} + +// +// D_AddFile +// +// Rewritten by Lee Killough +// +// Ty 08/29/98 - add source parm to indicate where this came from +// CPhipps - static, const char* parameter +// - source is an enum +// - modified to allocate & use new wadfiles array +void D_AddFile() +{ + +} + +// +// CheckIWAD +// +// Verify a file is indeed tagged as an IWAD +// Scan its lumps for levelnames and return gamemode as indicated +// Detect missing wolf levels in DOOM II +// +// The filename to check is passed in iwadname, the gamemode detected is +// returned in gmode, hassec returns the presence of secret levels +// +// jff 4/19/98 Add routine to test IWAD for validity and determine +// the gamemode from it. Also note if DOOM II, whether secret levels exist +// CPhipps - const char* for iwadname, made static + +#ifdef PDM_ONE_EPI +int pdm_one_epi; /* the only episode of the WAD (1..3), 0: several */ +#endif +static void CheckIWAD2(const unsigned char *iwad_data, const unsigned int iwad_len, GameMode_t *gmode, boolean *hassec) +{ + spiFlashSetAddress((uint32_t) iwad_data); + wadinfo_t header_v; + spiFlashGetData(&header_v, sizeof(header_v)); + const wadinfo_t *header = &header_v; //(const wadinfo_t*)iwad_data; + + int ud = 0, rg = 0, sw = 0, cm = 0, sc = 0, e2 = 0, e3 = 0; +#ifdef PDM_E4 + int credit = 0, help2 = 0; /* Paramix 1.7.3 test14: Ultimate DOOM has CREDIT but no HELP2 */ +#endif + + if (!strncmp(header->identification, "IWAD", 4)) + { + size_t length = header->numlumps; + printf("Found %d lumps\r\n", length); + filelump_t *fileinfo = Z_Malloc(length * sizeof(*fileinfo), PU_STATIC, NULL); + spiFlashSetAddress((uint32_t) &iwad_data[header->infotableofs]); + spiFlashGetData(fileinfo, length * sizeof(*fileinfo)); + while (length--) + { +#ifdef PDM_E4 + if (!strncmp(fileinfo[length].name, "CREDIT", 8)) credit = 1; + if (!strncmp(fileinfo[length].name, "HELP2", 8)) help2 = 1; +#endif + if (fileinfo[length].name[0] == 'E' && fileinfo[length].name[2] == 'M' && fileinfo[length].name[4] == 0) + { + if (fileinfo[length].name[1] == '4') + ++ud; + else if (fileinfo[length].name[1] == '3') + { ++rg; ++e3; } + else if (fileinfo[length].name[1] == '2') + { ++rg; ++e2; } + else if (fileinfo[length].name[1] == '1') + ++sw; + } + else if (fileinfo[length].name[0] == 'M' && fileinfo[length].name[1] == 'A' && fileinfo[length].name[2] == 'P' && fileinfo[length].name[5] == 0) + { + ++cm; + if (fileinfo[length].name[3] == '3') + { + if (fileinfo[length].name[4] == '1' || fileinfo[length].name[4] == '2') + ++sc; + } + } + //Final Doom IWAD check hacks ~Kippykip + //TNT - MURAL1 + else if (fileinfo[length].name[0] == 'M' && fileinfo[length].name[1] == 'U' && fileinfo[length].name[2] == 'R' && fileinfo[length].name[3] == 'A' && fileinfo[length].name[4] == 'L' && fileinfo[length].name[5] == '1' && fileinfo[length].name[6] == 0) + { + cm = 32; + sc = 2; + *gmode = commercial; + _g->gamemission = pack_tnt; + _g->gamemode = commercial; + Z_Free(fileinfo); + return; + } + //Plutonia - WFALL1 + else if (fileinfo[length].name[0] == 'W' && fileinfo[length].name[1] == 'F' && fileinfo[length].name[2] == 'A' && fileinfo[length].name[3] == 'L' && fileinfo[length].name[4] == 'L' && fileinfo[length].name[5] == '1' && fileinfo[length].name[6] == 0) + { + cm = 32; + sc = 2; + *gmode = commercial; + _g->gamemission = pack_plut; + _g->gamemode = commercial; + Z_Free(fileinfo); + return; + } + } + Z_Free(fileinfo); + + } + else + { + I_Error("CheckIWAD: IWAD tag not present"); + } + // Determine game mode from levels present + // Must be a full set for whichever mode is present + // Lack of wolf-3d levels also detected here + + *gmode = indetermined; + *hassec = false; + if (cm >= 30) + { + *gmode = commercial; + *hassec = sc >= 2; + } + else if (ud >= 9) + *gmode = retail; + else if (rg >= 18) + *gmode = registered; + else if (sw >= 9) + *gmode = shareware; +#ifdef PDM_ONE_EPI + /* Paramix 1.7.3 test12: the Studio builds one episode per DOOM. E2 or E3 alone was "indetermined" (the title + * screen then called a missing entry and crashed); it is registered now, and the new game skips the episode + * menu (pdm_one_epi). */ + else if (rg >= 9) + *gmode = registered; +#ifdef PDM_LUMPTXT + else if (cm > 0) + *gmode = commercial; /* 1.7.3 test17: a DOOM II map pack alone (one-humanity: MAP01 only) */ +#endif +#ifdef PDM_E4 + /* 1.7.3 test14: E4 (Ultimate DOOM) too. One episode from Ultimate DOOM is retail: its pages are CREDIT, not HELP2 + * (the title loop and the end of E1 would ask for HELP2). */ + pdm_one_epi = (sw > 0) + (e2 > 0) + (e3 > 0) + (ud > 0) == 1 ? (sw ? 1 : e2 ? 2 : e3 ? 3 : 4) : 0; + if ((*gmode == shareware || *gmode == registered) && credit && !help2) + *gmode = retail; +#else + pdm_one_epi = (sw > 0) + (e2 > 0) + (e3 > 0) == 1 ? (sw ? 1 : e2 ? 2 : 3) : 0; +#endif +#endif + +} + +// +// IdentifyVersion +// +// Set the location of the defaults file and the savegame root +// Locate and validate an IWAD file +// Determine gamemode from the IWAD +// +// supports IWADs with custom names. Also allows the -iwad parameter to +// specify which iwad is being searched for if several exist in one dir. +// The -iwad parm may specify: +// +// 1) a specific pathname, which must exist (.wad optional) +// 2) or a directory, which must contain a standard IWAD, +// 3) or a filename, which must be found in one of the standard places: +// a) current dir, +// b) exe dir +// c) $DOOMWADDIR +// d) or $HOME +// +// jff 4/19/98 rewritten to use a more advanced search algorithm + +static void IdentifyVersion() +{ + if (doom_iwad && (p_doom_iwad_len > 0)) + { + uint32_t doom_iwad_len; + spiFlashSetAddress((uint32_t) p_doom_iwad_len); + spiFlashGetData(&doom_iwad_len, sizeof(doom_iwad_len)); + CheckIWAD2(doom_iwad, doom_iwad_len, &_g->gamemode, &_g->haswolflevels); + + /* jff 8/23/98 set gamemission global appropriately in all cases + * cphipps 12/1999 - no version output here, leave that to the caller + */ + switch (_g->gamemode) + { + case retail: + case registered: + case shareware: + _g->gamemission = doom; + break; + case commercial: + _g->gamemission = doom2; + break; + + default: + _g->gamemission = none; + break; + } + + if (_g->gamemode == indetermined) + { + //jff 9/3/98 use logical output routine + lprintf(LO_WARN, "Unknown Game Version, may not work\n"); + } + + D_AddFile(); + } +} + +// +// D_DoomMainSetup +// +// CPhipps - the old contents of D_DoomMain, but moved out of the main +// line of execution so its stack space can be freed + +static void D_DoomMainSetup(void) +{ + IdentifyVersion(); + + // jff 1/24/98 end of set to both working and command line value + + { + // CPhipps - localise title variable + // print title for every printed line + // cph - code cleaned and made smaller + const char *doomverstr; + + switch (_g->gamemode) + { + case retail: + doomverstr = "The Ultimate DOOM"; + break; + case shareware: + doomverstr = "DOOM Shareware"; + break; + case registered: + doomverstr = "DOOM Registered"; + break; + case commercial: // Ty 08/27/98 - fixed gamemode vs gamemission + switch (_g->gamemission) + { + case pack_plut: + doomverstr = "DOOM 2: Plutonia Experiment"; + break; + case pack_tnt: + doomverstr = "DOOM 2: TNT - Evilution"; + break; + default: + doomverstr = "DOOM 2: Hell on Earth"; + break; + } + break; + default: + doomverstr = "Public DOOM"; + break; + } + + /* cphipps - the main display. This shows the build date, copyright, and game type */ + + lprintf(LO_ALWAYS, "\r\nPrBoom (built %s)", version_date); + lprintf(LO_ALWAYS, "\r\nPlaying: %s", doomverstr); + lprintf(LO_ALWAYS, "\r\nPrBoom is released under the"); + lprintf(LO_ALWAYS, "\r\nGNU GPL v2.0."); + + lprintf(LO_ALWAYS, "\r\nYou are welcome to"); + lprintf(LO_ALWAYS, "\r\nredistribute it under"); + lprintf(LO_ALWAYS, "\r\ncertain conditions."); + + lprintf(LO_ALWAYS, "\r\nIt comes with ABSOLUTELY\r\nNO WARRANTY.\r\nSee the file COPYING for\r\ndetails."); + + lprintf(LO_ALWAYS, "\r\nPhew. Thats the nasty legal\r\nstuff out of the way.\r\nLet's play Doom!\n"); + + } + + // init subsystems + + G_ReloadDefaults(); // killough 3/4/98: set defaults just loaded. + // jff 3/24/98 this sets startskill if it was -1 + // CPhipps - move up netgame init + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "D_InitNetGame.\r\n"); + D_InitNetGame(); + + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "W_Init: Init WADfiles.\r\n"); + W_Init(); // CPhipps - handling of wadfiles init changed + + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "R_Init: DOOM refresh daemon.\r\n"); + R_Init(); // here initImmutableFlashRegion() called too + + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "M_Init: Init misc info.\r\n"); + M_Init(); + + // 2021/05/19 next-hack: added WiInit to use lump nums instead of names + lprintf(LO_INFO, "Wi_Init: Init misc info.\r\n"); + WI_Init(); + + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "P_Init: Init Playloop state.\r\n"); + P_Init(); + + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "I_Init: Set up machine state.\r\n"); + I_Init(); + + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "S_Init: Setting up sound.\r\n"); + S_Init(_g->snd_SfxVolume /* *8 */, _g->snd_MusicVolume /* *8*/); + + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "HU_Init: Setting up HUD.\r\n"); + HU_Init(); + //jff 9/3/98 use logical output routine + lprintf(LO_INFO, "ST_Init: Init status bar.\r\n"); + ST_Init(); + lprintf(LO_INFO, "G_LoadSettings: Loading settings.\r\n"); + G_LoadSettings(); + PLOG(1); + _g->idmusnum = -1; //jff 3/17/98 insure idmus number is blank + + _g->fps_show = false; + + if (timedemo) + { + _g->singletics = true; + _g->timingdemo = true; // show stats after quit + G_DeferedPlayDemo(timedemo); + _g->singledemo = true; // quit after one demo + } + else + { + D_StartTitle(); // start up intro loop + } + PLOG(2); + // finally fill the patch lump width array + patchsizeoffsets_t *patchSizeOffsets = Z_Malloc( sizeof(patchsizeoffsets_t) * _g->numlumps, PU_STATIC, NULL); + for (int i = 0; i < _g->numlumps; i++) + { + const patch_t *patch = W_CacheLumpNum(i); + spiFlashSetAddress((uint32_t) patch); + spiFlashGetData(&patchSizeOffsets[i], sizeof (patchsizeoffsets_t)); + } + PLOG(3); + p_wad_immutable_flash_data->patchLumpSizeOffsets = writeBufferToFlashRegion(patchSizeOffsets, sizeof(patchsizeoffsets_t) * _g->numlumps, FLASH_IMMUTABLE_REGION, true); + Z_Free(patchSizeOffsets); + // + // + PLOG(4); + p_wad_immutable_flash_data = storeFlashImmutableValues(); + PLOG(5); +} + +// +// D_DoomMain +// + +void D_DoomMain(void) +{ + D_DoomMainSetup(); // CPhipps - setup out of main execution stack + // + delay(100); // still have not figured why after WAD upload this has to be added: probably due to nvm programming. + // + D_DoomLoop(); // never returns +} + +// +// GetFirstMap +// +// Ty 08/29/98 - determine first available map from the loaded wads and run it +// + +void GetFirstMap(int *ep, int *map) +{ + int i, j; // used to generate map name + boolean done = false; // Ty 09/13/98 - to exit inner loops + char test[6]; // MAPxx or ExMx plus terminator for testing + char name[6]; // MAPxx or ExMx plus terminator for display + boolean newlevel = false; // Ty 10/04/98 - to test for new level + int ix; // index for lookup + + strcpy(name, ""); // initialize + if (*map == 0) // unknown so go search for first changed one + { + *ep = 1; + *map = 1; // default E1M1 or MAP01 + if (_g->gamemode == commercial) + { + for (i = 1; !done && i < 33; i++) // Ty 09/13/98 - add use of !done + { + sprintf(test, "MAP%02d", i); + ix = W_CheckNumForName(test); + if (ix != -1) // Ty 10/04/98 avoid -1 subscript + { + if (!*name) // found one, not pwad. First default. + strcpy(name, test); + } + } + } + else // one of the others + { + strcpy(name, "E1M1"); // Ty 10/04/98 - default for display + for (i = 1; !done && i < 5; i++) // Ty 09/13/98 - add use of !done + { + for (j = 1; !done && j < 10; j++) // Ty 09/13/98 - add use of !done + { + sprintf(test, "E%dM%d", i, j); + ix = W_CheckNumForName(test); + if (ix != -1) // Ty 10/04/98 avoid -1 subscript + { + + if (!*name) // found one, not pwad. First default. + strcpy(name, test); + } + } + } + } + //jff 9/3/98 use logical output routine + lprintf(LO_CONFIRM, "Auto-warping to first %slevel: %s\n", + newlevel ? "new " : "", name); // Ty 10/04/98 - new level test + } +} diff --git a/doom/src/pdoom/Doom/source/doom_iwad.c b/doom/src/pdoom/Doom/source/doom_iwad.c new file mode 100644 index 0000000..d898481 --- /dev/null +++ b/doom/src/pdoom/Doom/source/doom_iwad.c @@ -0,0 +1,54 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * wad pointers. + * + */ +#pragma GCC optimize ("-O0") +#include "w_wad.h" +#include "doom_iwad.h" +#ifdef DOOM_FREE +const unsigned char *doom_iwad; /* set at start from the settings block */ +const unsigned int *p_doom_iwad_len; +#else +const unsigned char *doom_iwad = (const unsigned char*) WAD_ADDRESS; +const unsigned int *p_doom_iwad_len = (const unsigned int*) (WAD_ADDRESS - 4); +#endif + diff --git a/doom/src/pdoom/Doom/source/f_finale.c b/doom/src/pdoom/Doom/source/f_finale.c new file mode 100644 index 0000000..d63c492 --- /dev/null +++ b/doom/src/pdoom/Doom/source/f_finale.c @@ -0,0 +1,687 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Game completion, final screen animation. + * + *----------------------------------------------------------------------------- + */ + +#include "doomstat.h" +#include "d_event.h" +#include "v_video.h" +#include "w_wad.h" +#include "s_sound.h" +#include "sounds.h" +#include "f_finale.h" // CPhipps - hmm... +#include "dstrings.h" + +#include "global_data.h" + +// defines for the end mission display text // phares + +#define TEXTSPEED 3 // original value // phares +#define TEXTWAIT 250 // original value // phares +#define NEWTEXTSPEED 0.01f // new value // phares +#define NEWTEXTWAIT 1000 // new value // phares + +// CPhipps - removed the old finale screen text message strings; +// they were commented out for ages already +// Ty 03/22/98 - ... the new s_WHATEVER extern variables are used +// in the code below instead. + +void F_StartCast(void); +void F_CastTicker(void); +boolean F_CastResponder(event_t *ev); +void F_CastDrawer(void); + +void WI_checkForAccelerate(void); // killough 3/28/98: used to + +// +// F_StartFinale +// +void F_StartFinale(void) +{ + _g->gameaction = ga_nothing; + _g->gamestate = GS_FINALE; + _g->automapmode &= ~am_active; + + // killough 3/28/98: clear accelerative text flags + _g->acceleratestage = _g->midstage = 0; + + // Okay - IWAD dependend stuff. + // This has been changed severly, and + // some stuff might have changed in the process. + switch (_g->gamemode) + { + // DOOM 1 - E1, E3 or E4, but each nine missions + case shareware: + case registered: + case retail: + { + S_ChangeMusic(mus_victor, true); + + switch (_g->gameepisode) + { + case 1: + _g->finaleflat = "FLOOR4_8"; + _g->finaletext = E1TEXT; + break; + case 2: + _g->finaleflat = "SFLR6_1"; + _g->finaletext = E2TEXT; + break; + case 3: + _g->finaleflat = "MFLR8_4"; + _g->finaletext = E3TEXT; + break; + case 4: + _g->finaleflat = "MFLR8_3"; + _g->finaletext = E4TEXT; +#ifdef PDM_LUMPTXT + /* 1.7.3 test17: the text of an episode in the place of E4 (Sigil), written by the Studio with a 0 */ + { int l = W_CheckNumForName("PDMTXT4"); if (l >= 0) _g->finaletext = (const char*) W_CacheLumpNum(l); } +#endif + break; + default: + // Ouch. + break; + } + break; + } + + // DOOM II and missions packs with E1, M34 + case commercial: + { + S_ChangeMusic(mus_read_m, true); + + // Ty 08/27/98 - added the gamemission logic + switch (_g->gamemap) + { + case 6: + _g->finaleflat = "SLIME16"; + _g->finaletext = + (_g->gamemission == pack_tnt) ? T1TEXT : + (_g->gamemission == pack_plut) ? P1TEXT : C1TEXT; + break; + case 11: + _g->finaleflat = "RROCK14"; + _g->finaletext = + (_g->gamemission == pack_tnt) ? T2TEXT : + (_g->gamemission == pack_plut) ? P2TEXT : C2TEXT; + break; + case 20: + _g->finaleflat = "RROCK07"; + _g->finaletext = + (_g->gamemission == pack_tnt) ? T3TEXT : + (_g->gamemission == pack_plut) ? P3TEXT : C3TEXT; + break; + case 30: + _g->finaleflat = "RROCK17"; + _g->finaletext = + (_g->gamemission == pack_tnt) ? T4TEXT : + (_g->gamemission == pack_plut) ? P4TEXT : C4TEXT; + break; + case 15: + _g->finaleflat = "RROCK13"; + _g->finaletext = + (_g->gamemission == pack_tnt) ? T5TEXT : + (_g->gamemission == pack_plut) ? P5TEXT : C5TEXT; + break; + case 31: + _g->finaleflat = "RROCK19"; + _g->finaletext = + (_g->gamemission == pack_tnt) ? T6TEXT : + (_g->gamemission == pack_plut) ? P6TEXT : C6TEXT; + break; + default: + // Ouch. + break; + } + break; + // Ty 08/27/98 - end gamemission logic + } + + // Indeterminate. + default: // Ty 03/30/98 - not externalized + S_ChangeMusic(mus_read_m, true); + _g->finaleflat = "F_SKY1"; // Not used anywhere else. + _g->finaletext = C1TEXT; // FIXME - other text, music? + break; + } + + _g->finalestage = 0; + _g->finalecount = 0; +} + +boolean F_Responder(event_t *event) +{ + if (_g->finalestage == 2) + return F_CastResponder(event); + + return false; +} + +// Get_TextSpeed() returns the value of the text display speed // phares +// Rewritten to allow user-directed acceleration -- killough 3/28/98 + +static float Get_TextSpeed(void) +{ + return _g->midstage ? NEWTEXTSPEED : + ((_g->midstage = _g->acceleratestage)) ? _g->acceleratestage = 0, NEWTEXTSPEED : TEXTSPEED; +} + +// +// F_Ticker +// +// killough 3/28/98: almost totally rewritten, to use +// player-directed acceleration instead of constant delays. +// Now the player can accelerate the text display by using +// the fire/use keys while it is being printed. The delay +// automatically responds to the user, and gives enough +// time to read. +// +// killough 5/10/98: add back v1.9 demo compatibility +// + +void F_Ticker(void) +{ + + WI_checkForAccelerate(); // killough 3/28/98: check for acceleration + + // advance animation + _g->finalecount++; + + if (_g->finalestage == 2) + F_CastTicker(); + + if (!_g->finalestage) + { + float speed = Get_TextSpeed(); + /* killough 2/28/98: changed to allow acceleration */ + if (_g->finalecount > strlen(_g->finaletext) * speed + ( + _g->midstage ? NEWTEXTWAIT : TEXTWAIT) || (_g->midstage && _g->acceleratestage)) + { + if (_g->gamemode != commercial) // Doom 1 / Ultimate Doom episode end + { // with enough time, it's automatic + _g->finalecount = 0; + _g->finalestage = 1; + _g->wipegamestate = -1; // force a wipe + if (_g->gameepisode == 3) + S_StartMusic(mus_bunny); + } + else // you must press a button to continue in Doom 2 + if (_g->midstage) + { + if (_g->gamemap == 30) + F_StartCast(); // cast of Doom 2 characters + else + _g->gameaction = ga_worlddone; // next level, e.g. MAP07 + } + } + } +} + +// +// F_TextWrite +// +// This program displays the background and text at end-mission // phares +// text time. It draws both repeatedly so that other displays, // | +// like the main menu, can be drawn over it dynamically and // V +// erased dynamically. The TEXTSPEED constant is changed into +// the Get_TextSpeed function so that the speed of writing the // ^ +// text can be increased, and there's still time to read what's // | +// written. // phares +// CPhipps - reformatted + +#include "hu_stuff.h" + +static void F_TextWrite(void) +{ + V_DrawBackground(_g->finaleflat); + { // draw some of the text onto the screen + int cx = 10; + int cy = 10; + const char *ch = _g->finaletext; // CPhipps - const + int count = (int) ((float) (_g->finalecount - 10) / Get_TextSpeed()); // phares + int w; + + if (count < 0) + count = 0; + + for (; count; count--) + { + int c = *ch++; + + if (!c) + break; + if (c == '\n') + { + cx = 10; + cy += 11; + continue; + } + + c = toupper(c) - HU_FONTSTART; + if (c < 0 || c > HU_FONTSIZE) + { + cx += 4; + continue; + } + + w = hu_font[c]->width; + // CPhipps - patch drawing updated + V_DrawPatchNoScale(cx, cy, hu_font[c]); + cx += w; + } + } +} + +// +// Final DOOM 2 animation +// Casting by id Software. +// in order of appearance +// +typedef struct +{ + const char *name; // CPhipps - const** + mobjtype_t type; +} castinfo_t; + +#define MAX_CASTORDER 18 /* Ty - hard coded for now */ +static const castinfo_t castorder[] = +{ // CPhipps - static const, initialised here + { CC_ZOMBIE, MT_POSSESSED }, + { CC_SHOTGUN, MT_SHOTGUY }, + { CC_HEAVY, MT_CHAINGUY }, + { CC_IMP, MT_TROOP }, + { CC_DEMON, MT_SERGEANT }, + { CC_LOST, MT_SKULL }, + { CC_CACO, MT_HEAD }, + { CC_HELL, MT_KNIGHT }, + { CC_BARON, MT_BRUISER }, + { CC_ARACH, MT_BABY }, + { CC_PAIN, MT_PAIN }, + { CC_REVEN, MT_UNDEAD }, + { CC_MANCU, MT_FATSO }, + { CC_ARCH, MT_VILE }, + { CC_SPIDER, MT_SPIDER }, + { CC_CYBER, MT_CYBORG }, + { CC_HERO, MT_PLAYER }, + { NULL, 0 } +}; + +// +// F_StartCast +// + +void F_StartCast(void) +{ + _g->wipegamestate = -1; // force a screen wipe + _g->castnum = 0; + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].seestate]; + _g->casttics = _g->caststate->tics; + _g->castdeath = false; + _g->finalestage = 2; + _g->castframes = 0; + _g->castonmelee = 0; + _g->castattacking = false; + S_ChangeMusic(mus_evil, true); +} + +// +// F_CastTicker +// +void F_CastTicker(void) +{ + int st; + int sfx; + + if (--_g->casttics > 0) + return; // not time to change state yet + + if (_g->caststate->tics == -1 || _g->caststate->nextstate == S_NULL) + { + // switch from deathstate to next monster + _g->castnum++; + _g->castdeath = false; + if (castorder[_g->castnum].name == NULL) + _g->castnum = 0; + if (mobjinfo[castorder[_g->castnum].type].seesound) + S_StartSound(NULL, mobjinfo[castorder[_g->castnum].type].seesound); + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].seestate]; + _g->castframes = 0; + } + else + { + // just advance to next state in animation + if (_g->caststate == &states[S_PLAY_ATK1]) + goto stopattack; + // Oh, gross hack! + st = _g->caststate->nextstate; + _g->caststate = &states[st]; + _g->castframes++; + + // sound hacks.... + switch (st) + { + case S_PLAY_ATK1: + sfx = sfx_dshtgn; + break; + case S_POSS_ATK2: + sfx = sfx_pistol; + break; + case S_SPOS_ATK2: + sfx = sfx_shotgn; + break; + case S_VILE_ATK2: + sfx = sfx_vilatk; + break; + case S_SKEL_FIST2: + sfx = sfx_skeswg; + break; + case S_SKEL_FIST4: + sfx = sfx_skepch; + break; + case S_SKEL_MISS2: + sfx = sfx_skeatk; + break; + case S_FATT_ATK8: + case S_FATT_ATK5: + case S_FATT_ATK2: + sfx = sfx_firsht; + break; + case S_CPOS_ATK2: + case S_CPOS_ATK3: + case S_CPOS_ATK4: + sfx = sfx_shotgn; + break; + case S_TROO_ATK3: + sfx = sfx_claw; + break; + case S_SARG_ATK2: + sfx = sfx_sgtatk; + break; + case S_BOSS_ATK2: + case S_BOS2_ATK2: + case S_HEAD_ATK2: + sfx = sfx_firsht; + break; + case S_SKULL_ATK2: + sfx = sfx_sklatk; + break; + case S_SPID_ATK2: + case S_SPID_ATK3: + sfx = sfx_shotgn; + break; + case S_BSPI_ATK2: + sfx = sfx_plasma; + break; + case S_CYBER_ATK2: + case S_CYBER_ATK4: + case S_CYBER_ATK6: + sfx = sfx_rlaunc; + break; + case S_PAIN_ATK3: + sfx = sfx_sklatk; + break; + default: + sfx = 0; + break; + } + + if (sfx) + S_StartSound(NULL, sfx); + } + + if (_g->castframes == 12) + { + // go into attack frame + _g->castattacking = true; + if (_g->castonmelee) + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].meleestate]; + else + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].missilestate]; + _g->castonmelee ^= 1; + if (_g->caststate == &states[S_NULL]) + { + if (_g->castonmelee) + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].meleestate]; + else + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].missilestate]; + } + } + + if (_g->castattacking) + { + if (_g->castframes == 24 || _g->caststate == &states[mobjinfo[castorder[_g->castnum].type].seestate]) + { + stopattack: _g->castattacking = false; + _g->castframes = 0; + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].seestate]; + } + } + + _g->casttics = _g->caststate->tics; + if (_g->casttics == -1) + _g->casttics = 15; +} + +// +// F_CastResponder +// + +boolean F_CastResponder(event_t *ev) +{ + if (ev->type != ev_keydown) + return false; + + if (_g->castdeath) + return true; // already in dying frames + + // go into death frame + _g->castdeath = true; + _g->caststate = &states[mobjinfo[castorder[_g->castnum].type].deathstate]; + _g->casttics = _g->caststate->tics; + _g->castframes = 0; + _g->castattacking = false; + if (mobjinfo[castorder[_g->castnum].type].deathsound) + S_StartSound(NULL, mobjinfo[castorder[_g->castnum].type].deathsound); + + return true; +} + +static void F_CastPrint(const char *text) // CPhipps - static, const char* +{ + const char *ch; // CPhipps - const + int c; + int cx; + int w; + int width; + + // find width + ch = text; + width = 0; + + while (ch) + { + c = *ch++; + if (!c) + break; + c = toupper(c) - HU_FONTSTART; + if (c < 0 || c > HU_FONTSIZE) + { + width += 4; + continue; + } + + w = hu_font[c]->width; + width += w; + } + + // draw it + cx = SCREENWIDTH / 2 - width / 2; + ch = text; + while (ch) + { + c = *ch++; + if (!c) + break; + c = toupper(c) - HU_FONTSTART; + if (c < 0 || c > HU_FONTSIZE) + { + cx += 4; + continue; + } + + w = hu_font[c]->width; + // CPhipps - patch drawing updated + V_DrawPatchNoScale(cx, 144, hu_font[c]); + cx += w; + } +} + +// +// F_CastDrawer +// + +void F_CastDrawer(void) +{ + spritedef_t *sprdef; + spriteframe_t *sprframe; + int lump; + boolean flip; + + // erase the entire screen to a background + // CPhipps - patch drawing updated + V_DrawNamePatch(0, 0, 0, "BOSSBACK", CR_DEFAULT, VPT_STRETCH); // Ty 03/30/98 bg texture extern + + F_CastPrint((castorder[_g->castnum].name)); + + // draw the current frame in the middle of the screen + sprdef = &p_wad_immutable_flash_data->sprites[_g->caststate->sprite]; + sprframe = &(getSpriteFrames(sprdef)[_g->caststate->frame & FF_FRAMEMASK]); + lump = sprframe->lump[0]; + + flip = (boolean) SPR_FLIPPED(sprframe, 0); + + // CPhipps - patch drawing updated + V_DrawNumPatch(160, 170, 0, lump + _g->firstspritelump, CR_DEFAULT, VPT_STRETCH | ( + flip ? VPT_FLIP : 0)); +} + +// +// F_BunnyScroll +// +static const char pfub2[] = +{ "PFUB2" }; +static const char pfub1[] = +{ "PFUB1" }; + +static void F_BunnyScroll(void) +{ + char name[10]; + int stage; + + { + int scrolled = 320 - (_g->finalecount - 230) / 2; + if (scrolled <= 0) + { + V_DrawNamePatch(0, 0, 0, pfub2, CR_DEFAULT, VPT_STRETCH); + } + else if (scrolled >= 320) + { + V_DrawNamePatch(0, 0, 0, pfub1, CR_DEFAULT, VPT_STRETCH); + } + else + { + V_DrawNamePatch(320 - scrolled, 0, 0, pfub1, CR_DEFAULT, VPT_STRETCH); + V_DrawNamePatch(-scrolled, 0, 0, pfub2, CR_DEFAULT, VPT_STRETCH); + } + } + + if (_g->finalecount < 1130) + return; + if (_g->finalecount < 1180) + { + // CPhipps - patch drawing updated + V_DrawNamePatch((320 - 13 * 8) / 2, (200 - 8 * 8) / 2, 0, "END0", CR_DEFAULT, VPT_STRETCH); + _g->laststage = 0; + return; + } + + stage = (_g->finalecount - 1180) / 5; + if (stage > 6) + stage = 6; + if (stage > _g->laststage) + { + S_StartSound(NULL, sfx_pistol); + _g->laststage = stage; + } + + sprintf(name, "END%i", stage); + // CPhipps - patch drawing updated + V_DrawNamePatch((320 - 13 * 8) / 2, (200 - 8 * 8) / 2, 0, name, CR_DEFAULT, VPT_STRETCH); +} + +// +// F_Drawer +// +void F_Drawer(void) +{ + if (_g->finalestage == 2) + { + F_CastDrawer(); + return; + } + + if (!_g->finalestage) + F_TextWrite(); + else + { + switch (_g->gameepisode) + { + // CPhipps - patch drawing updated + case 1: + if (_g->gamemode == retail) + V_DrawNamePatch(0, 0, 0, "CREDIT", CR_DEFAULT, VPT_STRETCH); + else + V_DrawNamePatch(0, 0, 0, "HELP2", CR_DEFAULT, VPT_STRETCH); + break; + case 2: + V_DrawNamePatch(0, 0, 0, "VICTORY2", CR_DEFAULT, VPT_STRETCH); + break; + case 3: + F_BunnyScroll(); + break; + case 4: + V_DrawNamePatch(0, 0, 0, "ENDPIC", CR_DEFAULT, VPT_STRETCH); + break; + } + } +} diff --git a/doom/src/pdoom/Doom/source/f_wipe.c b/doom/src/pdoom/Doom/source/f_wipe.c new file mode 100644 index 0000000..8f431a2 --- /dev/null +++ b/doom/src/pdoom/Doom/source/f_wipe.c @@ -0,0 +1,159 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Mission begin melt/wipe screen special effect. + * next-hack: the GBA doom port removed the screen melt effect, so the + * wipe has been reduced now to a stub function. + * I will probably remove all the functions and variables too sooner or later. + * + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "doomdef.h" +#include "f_wipe.h" +#include "global_data.h" +#include "graphics.h" +#include "i_video.h" +#include "m_random.h" +#include "v_video.h" +#include "z_zone.h" +// +// SCREEN WIPE PACKAGE +// + +int wipe_StartScreen(void) +{ + _g->wipe_tick = 0; + return 0; +} + +int wipe_EndScreen(void) +{ + _g->wipe_tick = 0; + return 0; +} + + +// oh man, why aren't you commenting anything ? +// 2021-08-08 next-hack: commented and modified to use the dual buffer. +static int wipe_doMelt(int ticks, short *y_lookup) +{ + boolean done = true; + int i; + while (ticks--) + { + for (i = 0; i < (SCREENWIDTH); i++) + { + if (y_lookup[i] < 0) + { + y_lookup[i]++; + done = false; + continue; + } + // scroll down columns, which are still visible + if (y_lookup[i] < SCREENHEIGHT) + { + byte *s, *d; + int j, k, dy; + + /* cph 2001/07/29 - + * The original melt rate was 8 pixels/sec, i.e. 25 frames to melt + * the whole screen, so make the melt rate depend on SCREENHEIGHT + * so it takes no longer in high res + */ + dy = (y_lookup[i] < 16) ? y_lookup[i] + 1 : SCREENHEIGHT / 25; + // At most dy shall be so that the column is shifted by SCREENHEIGHT (i.e. just + // invisible) + if (y_lookup[i] + dy >= SCREENHEIGHT) + dy = SCREENHEIGHT - y_lookup[i]; + s = &displayData.displayFrameBuffer[displayData.workingBuffer][i] + + ((SCREENHEIGHT - dy - 1) * SCREENPITCH); + d = &displayData.displayFrameBuffer[displayData.workingBuffer][i] + + ((SCREENHEIGHT - 1) * SCREENPITCH); + // scroll down the column. Of course we need to copy from the bottom... up to + // SCREENHEIGHT - yLookup - dy + for (j = SCREENHEIGHT - y_lookup[i] - dy; j; j--) + { + *d = *s; + d += -SCREENPITCH; + s += -SCREENPITCH; + } + // copy new screen. We need to copy only between y_lookup and + dy y_lookup + s = &displayData.displayFrameBuffer[1 - displayData.workingBuffer][i] + y_lookup[i] * SCREENPITCH; + d = &displayData.displayFrameBuffer[displayData.workingBuffer][i] + y_lookup[i] * SCREENPITCH; + for (j = 0 ; j < dy; j++) + { + *d = *s; + d += SCREENPITCH; + s += SCREENPITCH; + } + y_lookup[i] += dy; + done = false; + } + } + } + return done; +} + +void wipe_initMelt(short *y_lookup) +{ + // setup initial column positions (y<0 => not ready to scroll yet) + y_lookup[0] = -(M_Random() % 16); + for (int i = 1; i < SCREENWIDTH; i++) + { + int r = (M_Random() % 3) - 1; + y_lookup[i] = y_lookup[i - 1] + r; + if (y_lookup[i] > 0) + y_lookup[i] = 0; + else if (y_lookup[i] == -16) + y_lookup[i] = -15; + } +} + + +int wipe_ScreenWipe(int ticks, short *y_lookup) +{ + // do a piece of wipe-in + return wipe_doMelt(ticks, y_lookup); +} \ No newline at end of file diff --git a/doom/src/pdoom/Doom/source/g_game.c b/doom/src/pdoom/Doom/source/g_game.c new file mode 100644 index 0000000..1ee1218 --- /dev/null +++ b/doom/src/pdoom/Doom/source/g_game.c @@ -0,0 +1,1515 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: none + * The original Doom description was none, basically because this file + * has everything. This ties up the game logic, linking the menu and + * input code to the underlying game by creating & respawning players, + * building game tics, calling the underlying thing logic. + * next-hack: added support for reading from external spi. + * modified save/load game functions, to use the displaybuffer + * as temporary buffer :) NOTE: display buffer is used also as + * stack in almost all the function calls here, but it is huge (56k) + * and it is used starting from its last element. + * + *----------------------------------------------------------------------------- + */ + +#include +#include +#include + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "doomstat.h" +#include "d_net.h" +#include "f_finale.h" +#include "m_misc.h" +#include "m_menu.h" +#include "m_random.h" +#include "p_setup.h" +#include "p_tick.h" +#include "p_map.h" +#include "d_main.h" +#include "wi_stuff.h" +#include "hu_stuff.h" +#include "st_stuff.h" +#include "am_map.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_draw.h" +#include "p_map.h" +#include "s_sound.h" +#include "dstrings.h" +#include "sounds.h" +#include "r_data.h" +#include "r_sky.h" +#include "p_inter.h" +#include "g_game.h" +#include "lprintf.h" +#include "i_main.h" +#include "i_system.h" +#include "i_video.h" +#include "global_data.h" +#include "z_bmalloc.h" + +#include "i_spi_support.h" +#include "main.h" +#include "graphics.h" +// +#include "qspi.h" +#include "i_memory.h" + +DECLARE_BLOCK_MEMORY_ALLOC_ZONE(secnodezone); +// +// controls (have defaults) +// + +const int key_right = KEYD_RIGHT; +const int key_left = KEYD_LEFT; +const int key_up = KEYD_UP; +const int key_down = KEYD_DOWN; +const int key_menu_right = KEYD_RIGHT; // phares 3/7/98 +const int key_menu_left = KEYD_LEFT; // | +const int key_menu_up = KEYD_UP; // V +const int key_menu_down = KEYD_DOWN; +const int key_menu_escape = KEYD_MENU; // | +const int key_menu_enter = KEYD_FIRE; // phares 3/7/98 +const int key_strafeleft = KEYD_SL; +const int key_straferight = KEYD_SR; +//Match Doom II GBA retail controls ~ Kippykip +const int key_fire = KEYD_FIRE; +const int key_use = KEYD_USE; +const int key_weapon_down = KEYD_CHGWDOWN; +const int key_weapon_up = KEYD_CHGW; +const int key_speed = KEYD_SPEED; +const int key_escape = KEYD_MENU; // phares 4/13/98 +const int key_enter = KEYD_FIRE; +const int key_map_right = KEYD_RIGHT; +const int key_map_left = KEYD_LEFT; +const int key_map_up = KEYD_UP; +const int key_map_down = KEYD_DOWN; +const int key_map = KEYD_MAP1; +const int key_map_follow = KEYD_USE; +const int key_map_zoomin = KEYD_SL; +const int key_map_zoomout = KEYD_SR; + +#ifdef PARADISE_DEV +#define SAVEGAME_ADDRESS (PD_SAVE_ADDR + 0x1000u) +#define SETTINGS_ADDRESS (PD_SAVE_ADDR) +#else +#define SAVEGAME_ADDRESS ((qspiFlashGetSize() - 4096) | EXT_FLASH_BASE) +#define SETTINGS_ADDRESS ((qspiFlashGetSize() - 2 * 4096) | EXT_FLASH_BASE) +#endif + +// phares + +#define MAXPLMOVE (forwardmove[1]) +#define TURBOTHRESHOLD 0x32 +#define SLOWTURNTICS 6 +#define QUICKREVERSE (short)32768 // 180 degree reverse // phares + +static const fixed_t forwardmove[2] = +{ 0x19, 0x32 }; +static const fixed_t sidemove[2] = +{ 0x18, 0x28 }; +static const fixed_t angleturn[3] = +{ 640, 1280, 320 }; // + slow turn + +static void G_DoSaveGame(boolean menu); +static const byte* G_ReadDemoHeader(const byte *demo_p, size_t size, boolean failonerror); + +typedef struct doom_save_data_t +{ + int save_present; + skill_t gameskill; + int gameepisode; + int gamemap; + int totalleveltimes; + int alwaysRun; + int gamma; + + int weaponowned[NUMWEAPONS]; + int ammo[NUMAMMO]; + int maxammo[NUMAMMO]; +} doom_save_data_t; + +typedef struct doom_save_settings_t +{ + unsigned int cookie; + unsigned int alwaysRun; + unsigned int gamma; + unsigned int showMessages; + unsigned int musicVolume; + unsigned int soundVolume; + +} doom_save_settings_t; + +const unsigned int settings_cookie = 0xbaddead1; + +// +// G_BuildTiccmd +// Builds a ticcmd from all of the available inputs +// or reads it from the demo buffer. +// If recording a demo, write it out +// +static inline signed char fudgef(signed char b) +{ + static int c; + if (!b || _g->longtics) + return b; + if (++c & 0x1f) + return b; + b |= 1; + if (b > 2) + b -= 2; + return b; +} + +static inline signed short fudgea(signed short b) +{ + if (!b || !_g->longtics) + return b; + b |= 1; + if (b > 2) + b -= 2; + return b; +} + +void G_BuildTiccmd(ticcmd_t *cmd) +{ + int speed; + int tspeed; + int forward; + int side; + int newweapon; // phares + /* cphipps - remove needless I_BaseTiccmd call, just set the ticcmd to zero */ + memset(cmd, 0, sizeof *cmd); + + //Use button negates the always run setting. + speed = (_g->gamekeydown[key_use] ^ _g->alwaysRun); + + forward = side = 0; + + // use two stage accelerative turning + // on the keyboard and joystick + if (_g->gamekeydown[key_right] || _g->gamekeydown[key_left]) + { + _g->turnheld++; + // next-hack: prevent overflow if one keeps the button pressed for long + // this allows using a byte. + if (_g->turnheld > SLOWTURNTICS) + { + _g->turnheld = SLOWTURNTICS; + } + } + else + _g->turnheld = 0; + + if (_g->turnheld < SLOWTURNTICS) + tspeed = 2; // slow turn + else + tspeed = speed; + + // let movement keys cancel each other out + + if (_g->gamekeydown[key_right]) + cmd->angleturn -= angleturn[tspeed]; + if (_g->gamekeydown[key_left]) + cmd->angleturn += angleturn[tspeed]; + + if (_g->gamekeydown[key_up]) + forward += forwardmove[speed]; + if (_g->gamekeydown[key_down]) + forward -= forwardmove[speed]; + + if (_g->gamekeydown[key_straferight]) + side += sidemove[speed]; + + if (_g->gamekeydown[key_strafeleft]) + side -= sidemove[speed]; + + if (_g->gamekeydown[key_fire]) + cmd->buttons |= BT_ATTACK; + + if (_g->gamekeydown[key_use]) + { + cmd->buttons |= BT_USE; + } + + // Toggle between the top 2 favorite weapons. // phares + // If not currently aiming one of these, switch to // phares + // the favorite. Only switch if you possess the weapon. // phares + + // killough 3/22/98: + // + // Perform automatic weapons switch here rather than in p_pspr.c, + // except in demo_compatibility mode. + // + // killough 3/26/98, 4/2/98: fix autoswitch when no weapons are left + + if (_g->gamekeydown[key_weapon_up]) + { + newweapon = P_WeaponCycleUp(&_g->player); + //side -= sidemove[speed]; //Hack cancel strafe. + } + else if (_g->gamekeydown[key_weapon_down]) + { + newweapon = P_WeaponCycleDown(&_g->player); + //side += sidemove[speed]; //Hack cancel strafe. + } + else if (!demo_compatibility && (_g->player.attackdown && !P_CheckAmmo(&_g->player))) + newweapon = P_SwitchWeapon(&_g->player); // phares + else + { // phares 02/26/98: Added gamemode checks + newweapon = wp_nochange; + + // killough 3/22/98: For network and demo consistency with the + // new weapons preferences, we must do the weapons switches here + // instead of in p_user.c. But for old demos we must do it in + // p_user.c according to the old rules. Therefore demo_compatibility + // determines where the weapons switch is made. + + // killough 2/8/98: + // Allow user to switch to fist even if they have chainsaw. + // Switch to fist or chainsaw based on preferences. + // Switch to shotgun or SSG based on preferences. + + { + const player_t *player = &_g->player; + + // only select chainsaw from '1' if it's owned, it's + // not already in use, and the player prefers it or + // the fist is already in use, or the player does not + // have the berserker strength. + + if (newweapon == wp_fist && player->weaponowned[wp_chainsaw] && player->readyweapon != wp_chainsaw && (player->readyweapon == wp_fist || !player->powers[pw_strength] || P_WeaponPreferred(wp_chainsaw, wp_fist))) + newweapon = wp_chainsaw; + + // Select SSG from '3' only if it's owned and the player + // does not have a shotgun, or if the shotgun is already + // in use, or if the SSG is not already in use and the + // player prefers it. + + if (newweapon == wp_shotgun && _g->gamemode == commercial && player->weaponowned[wp_supershotgun] && (!player->weaponowned[wp_shotgun] || player->readyweapon == wp_shotgun || (player->readyweapon != wp_supershotgun && P_WeaponPreferred(wp_supershotgun, wp_shotgun)))) + newweapon = wp_supershotgun; + } + // killough 2/8/98, 3/22/98 -- end of weapon selection changes + } + + if (newweapon != wp_nochange) + { + cmd->buttons |= BT_CHANGE; + cmd->buttons |= newweapon << BT_WEAPONSHIFT; + } + + if (forward > MAXPLMOVE) + forward = MAXPLMOVE; + else if (forward < -MAXPLMOVE) + forward = -MAXPLMOVE; + if (side > MAXPLMOVE) + side = MAXPLMOVE; + else if (side < -MAXPLMOVE) + side = -MAXPLMOVE; + + cmd->forwardmove += fudgef((signed char) forward); + cmd->sidemove += side; + cmd->angleturn = fudgea(cmd->angleturn); + + // CPhipps - special events (game new/load/save/pause) + if (_g->special_event & BT_SPECIAL) + { + cmd->buttons = _g->special_event; + _g->special_event = 0; + } +} + +// +// G_RestartLevel +// + +void G_RestartLevel(void) +{ + _g->special_event = BT_SPECIAL | (BTS_RESTARTLEVEL & BT_SPECIALMASK); +} + +// +// G_DoLoadLevel +// + +static void G_DoLoadLevel(void) +{ + + /* cph 2006/07/31 - took out unused levelstarttic variable */ + + if (_g->wipegamestate == GS_LEVEL) + _g->wipegamestate = -1; // force a wipe + + _g->gamestate = GS_LEVEL; + + if (_g->playeringame && _g->player.playerstate == PST_DEAD) + _g->player.playerstate = PST_REBORN; + + memset(_g->player.frags, 0, sizeof(_g->player.frags)); + + // initialize the msecnode_t freelist. phares 3/25/98 + // any nodes in the freelist are gone by now, cleared + // by Z_FreeTags() when the previous level ended or player + // died. + + NULL_BLOCK_MEMORY_ALLOC_ZONE(secnodezone); + NULL_BLOCK_MEMORY_ALLOC_ZONE(mobjzone); + NULL_BLOCK_MEMORY_ALLOC_ZONE(static_mobjzone); + + P_SetupLevel(_g->gameepisode, _g->gamemap, 0, _g->gameskill); + + _g->gameaction = ga_nothing; + + // clear cmd building stuff + memset(_g->gamekeydown, 0, sizeof(_g->gamekeydown)); + + _g->special_event = 0; + _g->paused = false; + + // killough 5/13/98: in case netdemo has consoleplayer other than green + ST_Start(); + HU_Start(); +} + +// +// G_Responder +// Get info needed to make ticcmd_ts for the players. +// + +boolean G_Responder(event_t *ev) +{ + // any other key pops up menu if in demos + // + // killough 8/2/98: enable automap in -timedemo demos + // + // killough 9/29/98: make any key pop up menu regardless of + // which kind of demo, and allow other events during playback + + if (_g->gameaction == ga_nothing && (_g->demoplayback || _g->gamestate == GS_DEMOSCREEN)) + { + + // killough 10/98: + // Don't pop up menu, if paused in middle + // of demo playback, or if automap active. + // Don't suck up keys, which may be cheats + + return _g->gamestate == GS_DEMOSCREEN && !(_g->paused & 2) && !(_g->automapmode & am_active) && ((ev->type == ev_keydown) || (ev->type == ev_mouse && ev->data1) || (ev->type == ev_joystick && ev->data1)) ? M_StartControlPanel(), true : false; + } + + if (_g->gamestate == GS_FINALE && F_Responder(ev)) + return true; // finale ate the event + + switch (ev->type) + { + case ev_keydown: + + if (ev->data1 < NUMKEYS) + _g->gamekeydown[ev->data1] = true; + return true; // eat key down events + + case ev_keyup: + if (ev->data1 < NUMKEYS) + _g->gamekeydown[ev->data1] = false; + return false; // always let key up events filter down + + default: + break; + } + return false; +} + +// +// G_Ticker +// Make ticcmd_ts for the players. +// + +void G_Ticker(void) +{ + P_MapStart(); + if (_g->playeringame && _g->player.playerstate == PST_REBORN) + G_DoReborn(0); + + P_MapEnd(); + // do things to change the game state + while (_g->gameaction != ga_nothing) + { + switch (_g->gameaction) + { + case ga_loadlevel: + _g->player.playerstate = PST_REBORN; + G_DoLoadLevel(); + break; + case ga_newgame: + G_DoNewGame(); + break; + case ga_loadgame: + G_DoLoadGame(); + break; + case ga_savegame: + G_DoSaveGame(false); + break; + case ga_playdemo: + G_DoPlayDemo(); + break; + case ga_completed: + G_DoCompleted(); + break; + case ga_victory: + F_StartFinale(); + break; + case ga_worlddone: + G_DoWorldDone(); + break; + case ga_nothing: + break; + } + } + if ((_g->paused & 2) || (!_g->demoplayback && _g->menuactive)) + _g->basetic++; // For revenant tracers and RNG -- we must maintain sync + else + { + if (_g->playeringame) + { + ticcmd_t *cmd = &_g->player.cmd; + + memcpy(cmd, &_g->netcmd, sizeof *cmd); + + if (_g->demoplayback) + G_ReadDemoTiccmd(cmd); + } + + if (_g->playeringame) + { + if (_g->player.cmd.buttons & BT_SPECIAL) + { + switch (_g->player.cmd.buttons & BT_SPECIALMASK) + { + case BTS_PAUSE: + _g->paused ^= 1; + if (_g->paused) + S_PauseSound(); + else + S_ResumeSound(); + break; + + case BTS_SAVEGAME: + _g->savegameslot = (_g->player.cmd.buttons & BTS_SAVEMASK) >> BTS_SAVESHIFT; + _g->gameaction = ga_savegame; + break; + + // CPhipps - remote loadgame request + case BTS_LOADGAME: + _g->savegameslot = (_g->player.cmd.buttons & BTS_SAVEMASK) >> BTS_SAVESHIFT; + _g->gameaction = ga_loadgame; + _g->command_loadgame = false; + break; + + // CPhipps - Restart the level + case BTS_RESTARTLEVEL: + if (_g->demoplayback) + break; // CPhipps - Ignore in demos or old games + _g->gameaction = ga_loadlevel; + break; + } + _g->player.cmd.buttons = 0; + } + } + } + + // cph - if the gamestate changed, we may need to clean up the old gamestate + if (_g->gamestate != _g->prevgamestate) + { + if (_g->prevgamestate == GS_INTERMISSION) + { + WI_End(); + } + _g->prevgamestate = _g->gamestate; + } + + // e6y + // do nothing if a pause has been pressed during playback + // pausing during intermission can cause desynchs without that + if ((_g->paused & 2) && _g->gamestate != GS_LEVEL) + return; + + // do main actions + switch (_g->gamestate) + { + case GS_LEVEL: + P_Ticker(); + ST_Ticker(); + AM_Ticker(); + HU_Ticker(); + break; + + case GS_INTERMISSION: + WI_Ticker(); + break; + + case GS_FINALE: + F_Ticker(); + break; + + case GS_DEMOSCREEN: + D_PageTicker(); + break; + } +} + +// +// PLAYER STRUCTURE FUNCTIONS +// also see P_SpawnPlayer in P_Things +// + +// +// G_PlayerFinishLevel +// Can when a player completes a level. +// + +static void G_PlayerFinishLevel(int player) +{ + player_t *p = &_g->player; + memset(p->powers, 0, sizeof p->powers); + memset(p->cards, 0, sizeof p->cards); + p->mo = NULL; // cph - this is allocated PU_LEVEL so it's gone + p->extralight = 0; // cancel gun flashes + p->fixedcolormap = 0; // cancel ir gogles + p->damagecount = 0; // no palette changes + p->bonuscount = 0; +} + +// +// G_PlayerReborn +// Called after a player dies +// almost everything is cleared and initialized +// + +void G_PlayerReborn(int player) +{ + player_t *p; + int i; + int frags[MAXPLAYERS]; + int killcount; + int itemcount; + int secretcount; + + memcpy(frags, _g->player.frags, sizeof frags); + killcount = _g->player.killcount; + itemcount = _g->player.itemcount; + secretcount = _g->player.secretcount; + + p = &_g->player; + + // killough 3/10/98,3/21/98: preserve cheats across idclev + { + int cheats = p->cheats; + memset(p, 0, sizeof(*p)); + p->cheats = cheats; + } + + memcpy(_g->player.frags, frags, sizeof(_g->player.frags)); + _g->player.killcount = killcount; + _g->player.itemcount = itemcount; + _g->player.secretcount = secretcount; + + p->usedown = p->attackdown = true; // don't do anything immediately + p->playerstate = PST_LIVE; + p->health = initial_health; // Ty 03/12/98 - use dehacked values + p->readyweapon = p->pendingweapon = wp_pistol; + p->weaponowned[wp_fist] = true; + p->weaponowned[wp_pistol] = true; + p->ammo[am_clip] = initial_bullets; // Ty 03/12/98 - use dehacked values + + for (i = 0; i < NUMAMMO; i++) + p->maxammo[i] = maxammo[i]; +} + +// +// G_DoReborn +// + +void G_DoReborn(int playernum) +{ + _g->gameaction = ga_loadlevel; // reload the level from scratch +} + +// DOOM Par Times +const int pars[4][10] = +{ + { 0 }, + { 0, 30, 75, 120, 90, 165, 180, 180, 30, 165 }, + { 0, 90, 90, 90, 120, 90, 360, 240, 30, 170 }, + { 0, 90, 45, 90, 150, 90, 90, 165, 30, 135 } +}; + +// DOOM II Par Times +const int cpars[32] = +{ + 30, 90, 120, 120, 90, 150, 120, 120, 270, 90, // 1-10 + 210, 150, 150, 150, 210, 150, 420, 150, 210, 150, // 11-20 + 240, 150, 180, 150, 150, 300, 330, 420, 300, 180, // 21-30 + 120, 30 // 31-32 +}; + +void G_ExitLevel(void) +{ + // 2021/05/19: next hack workaround for repeating sound before going to the intermission screen + S_Stop(); + _g->secretexit = false; + _g->gameaction = ga_completed; +} + +// Here's for the german edition. +// IF NO WOLF3D LEVELS, NO SECRET EXIT! + +void G_SecretExitLevel(void) +{ + // 2021/05/19: next hack workaround for repeating sound before going to the intermission screen + S_Stop(); + if (_g->gamemode != commercial || _g->haswolflevels) + _g->secretexit = true; + else + _g->secretexit = false; + _g->gameaction = ga_completed; +} + +// +// G_DoCompleted +// + +void G_DoCompleted(void) +{ + _g->gameaction = ga_nothing; + + if (_g->playeringame) + G_PlayerFinishLevel(0); // take away cards and stuff + + if (_g->automapmode & am_active) + AM_Stop(); + + if (_g->gamemode != commercial) // kilough 2/7/98 + switch (_g->gamemap) + { + // cph - Remove ExM8 special case, so it gets summary screen displayed + case 9: + _g->player.didsecret = true; + break; + } + + _g->wminfo.didsecret = _g->player.didsecret; + _g->wminfo.epsd = _g->gameepisode - 1; + _g->wminfo.last = _g->gamemap - 1; + + // wminfo.next is 0 biased, unlike gamemap + if (_g->gamemode == commercial) + { + if (_g->secretexit) + switch (_g->gamemap) + { + case 15: + _g->wminfo.next = 30; + break; + case 31: + _g->wminfo.next = 31; + break; + } + else + switch (_g->gamemap) + { + case 31: + case 32: + _g->wminfo.next = 15; + break; + default: + _g->wminfo.next = _g->gamemap; + } + } + else + { + if (_g->secretexit) + _g->wminfo.next = 8; // go to secret level + else if (_g->gamemap == 9) + { + // returning from secret level + switch (_g->gameepisode) + { + case 1: + _g->wminfo.next = 3; + break; + case 2: + _g->wminfo.next = 5; + break; + case 3: + _g->wminfo.next = 6; + break; + case 4: + _g->wminfo.next = 2; +#ifdef PDM_LUMPTXT + /* 1.7.3 test17: an episode in the place of E4 (Sigil) goes back to its own map (lump PDMNXT4: "7") */ + { int l = W_CheckNumForName("PDMNXT4"); if (l >= 0) { const char *t = (const char*) W_CacheLumpNum(l); if (t[0] >= '1' && t[0] <= '8') _g->wminfo.next = t[0] - '1'; } } +#endif + break; + } + } + else + _g->wminfo.next = _g->gamemap; // go to next level + } + + _g->wminfo.maxkills = _g->totalkills; + _g->wminfo.maxitems = _g->totalitems; + _g->wminfo.maxsecret = _g->totalsecret; + _g->wminfo.maxfrags = 0; + + if (_g->gamemode == commercial) + _g->wminfo.partime = TICRATE * cpars[_g->gamemap - 1]; + else +#ifdef PDM_E4 + _g->wminfo.partime = _g->gameepisode < 4 ? TICRATE * pars[_g->gameepisode][_g->gamemap] : 0; /* 1.7.3 test14: E4 has no par times (read past the table) */ +#else + _g->wminfo.partime = TICRATE * pars[_g->gameepisode][_g->gamemap]; +#endif + + _g->wminfo.pnum = 0; + + _g->wminfo.plyr[0].in = _g->playeringame; + _g->wminfo.plyr[0].skills = _g->player.killcount; + _g->wminfo.plyr[0].sitems = _g->player.itemcount; + _g->wminfo.plyr[0].ssecret = _g->player.secretcount; + _g->wminfo.plyr[0].stime = _g->leveltime; + memcpy(_g->wminfo.plyr[0].frags, _g->player.frags, sizeof(_g->wminfo.plyr[0].frags)); + + /* cph - modified so that only whole seconds are added to the totalleveltimes + * value; so our total is compatible with the "naive" total of just adding + * the times in seconds shown for each level. Also means our total time + * will agree with Compet-n. + */ + _g->wminfo.totaltimes = (_g->totalleveltimes += (_g->leveltime - _g->leveltime % 35)); + + _g->gamestate = GS_INTERMISSION; + _g->automapmode &= ~am_active; + + // lmpwatch.pl engine-side demo testing support + // print "FINISHED: " when the player exits the current map + if (nodrawers && (_g->demoplayback || _g->timingdemo)) + { + if (_g->gamemode == commercial) + lprintf(LO_INFO, "FINISHED: MAP%02d\n", _g->gamemap); + else + lprintf(LO_INFO, "FINISHED: E%dM%d\n", _g->gameepisode, _g->gamemap); + } + + WI_Start(&_g->wminfo); +} + +// +// G_WorldDone +// + +void G_WorldDone(void) +{ + _g->gameaction = ga_worlddone; + + if (_g->secretexit) + _g->player.didsecret = true; + + if (_g->gamemode == commercial) + { + switch (_g->gamemap) + { + case 15: + case 31: + if (!_g->secretexit) + { + break; + } + else + { + F_StartFinale(); + } + break; + case 6: + case 11: + case 20: + case 30: + F_StartFinale(); + break; + } + } + else if (_g->gamemap == 8) + _g->gameaction = ga_victory; // cph - after ExM8 summary screen, show victory stuff +} + +void G_DoWorldDone(void) +{ + _g->idmusnum = -1; //jff 3/17/98 allow new level's music to be loaded +#ifdef PDM_LUMPTXT + /* 1.7.3 test17: a map pack with only a few maps (one-humanity: MAP01) ends after its last map: back to the title + * instead of looking for a map that is not there */ + { + char nm[9]; int m = _g->wminfo.next + 1; + if (_g->gamemode == commercial) { nm[0] = 'M'; nm[1] = 'A'; nm[2] = 'P'; nm[3] = (char) ('0' + m / 10); nm[4] = (char) ('0' + m % 10); nm[5] = 0; } + else { nm[0] = 'E'; nm[1] = (char) ('0' + _g->gameepisode); nm[2] = 'M'; nm[3] = (char) ('0' + m); nm[4] = 0; } + if (W_CheckNumForName(nm) < 0) { D_StartTitle(); return; } + } +#endif + _g->gamestate = GS_LEVEL; + _g->gamemap = _g->wminfo.next + 1; + G_DoLoadLevel(); + _g->gameaction = ga_nothing; +} + +// killough 2/28/98: A ridiculously large number +// of players, the most you'll ever need in a demo +// or savegame. This is used to prevent problems, in +// case more players in a game are supported later. + +#define MIN_MAXPLAYERS 4 + +// +// killough 5/15/98: add forced loadgames, which allow user to override checks +// + +void G_ForcedLoadGame(void) +{ + // CPhipps - net loadgames are always forced, so we only reach here + // in single player + _g->gameaction = ga_loadgame; +} +// +// 2021/05/02 next-hack: cheap itoa. +// +int str2num(const char *str) +{ + int num = 0; + int d; + while ((d = *str)) + { + d -= '0'; + if (d < 0 || d > 9) + return 0; + num = 10 * num + d; + str++; + } + return num; +} + +// +// Update the strings displayed in the load-save menu. +// +void G_UpdateSaveGameStrings() +{ + unsigned int savebuffersize = sizeof(doom_save_data_t) * 8; + + // 2021/05/09 next-hack: display buffer is used here also as a stack + // but it is huge (15kB) and, as stack, its last elements are used first. + // Therefore we can "safely" use it as a temporary work buffer. + // Yes, this is a bad hack, but it works :) + byte *loadbuffer = (byte*) displayData.displayFrameBuffer[displayData.workingBuffer]; + + spiFlashSetAddress(SAVEGAME_ADDRESS); + spiFlashGetData(loadbuffer, savebuffersize); + // + doom_save_data_t *saveslots = (doom_save_data_t*) loadbuffer; + + for (int i = 0; i < 8; i++) + { + if (saveslots[i].save_present != 1) + { + strcpy(savegamestrings[i], "EMPTY"); + } + else + { + if (_g->gamemode == commercial) + { + snprintf(savegamestrings[i], sizeof(savegamestrings[i]), "MAP %d", saveslots[i].gamemap); + } + else + { + strcpy(savegamestrings[i], "ExMy"); + + savegamestrings[i][1] = '0' + saveslots[i].gameepisode; + savegamestrings[i][3] = '0' + saveslots[i].gamemap; + } + } + } +} + +// killough 3/16/98: add slot info +// killough 5/15/98: add command-line +void G_LoadGame(int slot, boolean command) +{ + _g->savegameslot = slot; + _g->demoplayback = false; + + G_DoLoadGame(); +} + +// CPhipps - size of version header +#define VERSIONSIZE 16 + +void G_DoLoadGame() +{ + unsigned int savebuffersize = sizeof(doom_save_data_t) * 8; + + // 2021/05/09 next-hack: display buffer is used here also as a stack + // but it is huge (15kB) and, as stack, its last elements are used first. + // Therefore we can "safely" use it as a temporary work buffer. + // Yes, this is a bad hack, but it works :) + byte *loadbuffer = (byte*) displayData.displayFrameBuffer[displayData.workingBuffer]; + // load buffer + spiFlashSetAddress(SAVEGAME_ADDRESS); + spiFlashGetData(loadbuffer, savebuffersize); + + doom_save_data_t *saveslots = (doom_save_data_t*) loadbuffer; + + doom_save_data_t *savedata = &saveslots[_g->savegameslot]; + + if (savedata->save_present != 1) + return; + + _g->gameskill = savedata->gameskill; + _g->gameepisode = savedata->gameepisode; + _g->gamemap = savedata->gamemap; + _g->alwaysRun = savedata->alwaysRun; + _g->gamma = savedata->gamma; + V_SetPalLump(_g->gamma); + printf("InitNew()\r\n"); + G_InitNew(_g->gameskill, _g->gameepisode, _g->gamemap); + + _g->totalleveltimes = savedata->totalleveltimes; + for (int i = 0; i < NUMWEAPONS; i++) + { + _g->player.weaponowned[i] = savedata->weaponowned[i]; + } + for (int i = 0; i < NUMAMMO; i++) + { + _g->player.ammo[i] = savedata->ammo[i]; + _g->player.maxammo[i] = savedata->maxammo[i]; + } + //If stored maxammo is more than no backpack ammo, player had a backpack. + if (_g->player.maxammo[am_clip] > maxammo[am_clip]) + _g->player.backpack = true; +# +} + +// +// G_SaveGame +// Called by the menu task. +// Description is a 24 byte text string +// + +void G_SaveGame(int slot, const char *description) +{ + _g->savegameslot = slot; + G_DoSaveGame(true); +} +void writeToExternalFlash(uint32_t address, void *buffer, int size) +{ + // note: when we are executing this, we are sure that all pending read operations for QSPI have ended. + qspiFlashErasePage4k(address & (qspiFlashGetSize() - 1)); + // + qspiFlashProgram(address & (qspiFlashGetSize() - 1), buffer, size); + // put again in dual mode +} +static void G_DoSaveGame(boolean menu) +{ + unsigned int savebuffersize = sizeof(doom_save_data_t) * 8; + + // 2021/05/09 next-hack: display buffer is used here also as a stack + // but it is huge (15kB) and, as stack, its last elements are used first. + // Therefore we can "safely" use it as a temporary work buffer. + // Yes, this is a bad hack, but it works :) + byte *savebuffer = (byte*) displayData.displayFrameBuffer[displayData.workingBuffer]; + // read old data + spiFlashSetAddress(SAVEGAME_ADDRESS); + spiFlashGetData(savebuffer, savebuffersize); + // + doom_save_data_t *saveslots = (doom_save_data_t*) savebuffer; + doom_save_data_t *savedata = &saveslots[_g->savegameslot]; + // update + savedata->save_present = 1; + savedata->gameskill = _g->gameskill; + savedata->gameepisode = _g->gameepisode; + savedata->gamemap = _g->gamemap; + savedata->totalleveltimes = _g->totalleveltimes; + savedata->alwaysRun = _g->alwaysRun; + savedata->gamma = _g->gamma; + // + for (int i = 0; i < NUMWEAPONS; i++) + { + savedata->weaponowned[i] = _g->player.weaponowned[i]; + } + for (int i = 0; i < NUMAMMO; i++) + { + savedata->ammo[i] = _g->player.ammo[i]; + savedata->maxammo[i] = _g->player.maxammo[i]; + } + // + writeToExternalFlash(SAVEGAME_ADDRESS, savebuffer, savebuffersize); + +// Z_Free(savebuffer); + + _g->player.message = GGSAVED; + + G_UpdateSaveGameStrings(); +} + +void G_SaveSettings() +{ + doom_save_settings_t settings; + + settings.cookie = settings_cookie; + + settings.gamma = _g->gamma; + settings.alwaysRun = _g->alwaysRun; + + settings.showMessages = _g->showMessages; + + settings.musicVolume = _g->snd_MusicVolume; + settings.soundVolume = _g->snd_SfxVolume; + + writeToExternalFlash(SETTINGS_ADDRESS, &settings, sizeof(settings)); +} + +void G_LoadSettings() +{ + doom_save_settings_t *settings = (doom_save_settings_t*) displayData.displayFrameBuffer[displayData.workingBuffer]; + memset(settings, 0, sizeof(*settings)); + // + spiFlashSetAddress(SETTINGS_ADDRESS); + spiFlashGetData(settings, sizeof(*settings)); + // + if (settings->cookie == settings_cookie) + { + _g->gamma = (settings->gamma >= MAX_GAMMA) ? MAX_GAMMA : settings->gamma; + _g->alwaysRun = (settings->alwaysRun > 0) ? 1 : 0; + + _g->showMessages = (settings->showMessages > 0) ? 1 : 0; + + _g->snd_SfxVolume = (settings->soundVolume > 15) ? 15 : settings->soundVolume; + _g->snd_MusicVolume = (settings->musicVolume > 15) ? 15 : settings->musicVolume; + + V_SetPalLump(_g->gamma); + V_SetPalette(0); + + S_SetSfxVolume(_g->snd_SfxVolume); + S_SetMusicVolume(_g->snd_MusicVolume); + } +} + +void G_DeferedInitNew(skill_t skill, int episode, int map) +{ + _g->d_skill = skill; + _g->d_episode = episode; + _g->d_map = map; + _g->gameaction = ga_newgame; +} + +// killough 3/1/98: function to reload all the default parameter +// settings before a new game begins + +void G_ReloadDefaults(void) +{ + // killough 3/1/98: Initialize options based on config file + // (allows functions above to load different values for demos + // and savegames without messing up defaults). + + _g->demoplayback = false; + _g->singledemo = false; // killough 9/29/98: don't stop after 1 demo +} + +void G_DoNewGame(void) +{ + G_ReloadDefaults(); // killough 3/1/98 + // here we can choose the map for testing + _g->d_map = START_MAP; + G_InitNew(_g->d_skill, _g->d_episode, _g->d_map); + _g->gameaction = ga_nothing; + + //jff 4/26/98 wake up the status bar in case were coming out of a DM demo + ST_Start(); +} + +// +// G_InitNew +// Can be called by the startup code or the menu task, +// consoleplayer, displayplayer, playeringame[] should be set. +// + +void G_InitNew(skill_t skill, int episode, int map) +{ + if (_g->paused) + { + _g->paused = false; + S_ResumeSound(); + } + + if (skill > sk_nightmare) + skill = sk_nightmare; + + if (episode < 1) + episode = 1; + + if (_g->gamemode == retail) + { + if (episode > 4) + episode = 4; + } + else if (_g->gamemode == shareware) + { + if (episode > 1) + episode = 1; // only start episode 1 on shareware + } + else if (episode > 3) + episode = 3; + + if (map < 1) + map = 1; + if (map > 9 && _g->gamemode != commercial) + map = 9; + + M_ClearRandom(); + + _g->respawnmonsters = skill == sk_nightmare; + + _g->player.playerstate = PST_REBORN; + + _g->usergame = true; // will be set false if a demo + _g->paused = false; + _g->automapmode &= ~am_active; + _g->gameepisode = episode; + _g->gamemap = map; + _g->gameskill = skill; + + _g->totalleveltimes = 0; // cph + printf("\r\n\r\nDo load Level\r\n\r\n"); + G_DoLoadLevel(); +} + +// +// DEMO RECORDING +// + +#define DEMOMARKER 0x80 + +void G_ReadDemoTiccmd(ticcmd_t *cmd) +{ + unsigned char at; // e6y: tasdoom stuff + + if (spiFlashGetByteFromAddress(_g->demo_p) == DEMOMARKER) + G_CheckDemoStatus(); // end of demo data stream + else if (_g->demoplayback && _g->demo_p + (_g->longtics ? 5 : 4) > _g->demobuffer + _g->demolength) + { + lprintf(LO_WARN, "G_ReadDemoTiccmd: missing DEMOMARKER\n"); + G_CheckDemoStatus(); + } + else + { + cmd->forwardmove = ((signed char) spiFlashGetByteFromAddress(_g->demo_p++)); + cmd->sidemove = ((signed char) spiFlashGetByteFromAddress(_g->demo_p++)); + if (!_g->longtics) + { + cmd->angleturn = ((unsigned char) (at = spiFlashGetByteFromAddress(_g->demo_p++))) << 8; + } + else + { + unsigned int lowbyte = (unsigned char) spiFlashGetByteFromAddress(_g->demo_p++); + cmd->angleturn = (((signed int) (spiFlashGetByteFromAddress(_g->demo_p++))) << 8) + lowbyte; + } + cmd->buttons = (unsigned char) spiFlashGetByteFromAddress(_g->demo_p++); + demodbgprintf("MR: %02X GT: %d. fm %x, sm %x, at %x, bt %x, X: %x, Y: %x, Mx: %x, My: %x, angle: %x\r\n",_g->prndindex, _g->gametic, cmd->forwardmove, cmd->sidemove, cmd->angleturn, cmd->buttons, _g->player.mo->x, _g->player.mo->y, _g->player.mo->momx, _g->player.mo->momy, _g->player.mo->angle); + } +} + +/* Same, but read instead of write + * cph - const byte*'s + */ + +const byte* G_ReadOptions(const byte *demo_p) +{ + const byte *target = demo_p + GAME_OPTION_SIZE; + + return target; +} + +// +// G_PlayDemo +// + +static const char *defdemoname; + +void G_DeferedPlayDemo(const char *name) +{ + defdemoname = name; + _g->gameaction = ga_playdemo; +} + +static int demolumpnum = -1; + +//e6y: Check for overrun +static boolean CheckForOverrun(const byte *start_p, const byte *current_p, size_t maxsize, size_t size, boolean failonerror) +{ + size_t pos = current_p - start_p; + if (pos + size > maxsize) + { + if (failonerror) + I_Error("G_ReadDemoHeader: wrong demo header\n"); + else + return true; + } + return false; +} + +static const byte* G_ReadDemoHeader(const byte *demo_p, size_t size, boolean failonerror) +{ + skill_t skill; + int episode, map; + + // e6y + // The local variable should be used instead of demobuffer, + // because demobuffer can be uninitialized + const byte *header_p = demo_p; + + _g->basetic = _g->gametic; // killough 9/29/98 + + // killough 2/22/98, 2/28/98: autodetect old demos and act accordingly. + // Old demos turn on demo_compatibility => compatibility; new demos load + // compatibility flag, and other flags as well, as a part of the demo. + + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, 1, failonerror)) + return NULL; + + _g->demover = spiFlashGetByteFromAddress(demo_p++); + _g->longtics = 0; + + // e6y + // Handling of unrecognized demo formats + // Versions up to 1.2 use a 7-byte header - first byte is a skill level. + // Versions after 1.2 use a 13-byte header - first byte is a demoversion. + // BOOM's demoversion starts from 200 + if (!((_g->demover >= 0 && _g->demover <= 4) || (_g->demover >= 104 && _g->demover <= 111) || (_g->demover >= 200 && _g->demover <= 214))) + { + I_Error("G_ReadDemoHeader: Unknown demo format %d.", _g->demover); + } + + if (_g->demover < 200) // Autodetect old demos + { + if (_g->demover >= 111) + _g->longtics = 1; + + // killough 3/2/98: force these variables to be 0 in demo_compatibility + + // killough 3/6/98: rearrange to fix savegame bugs (moved fastparm, + // respawnparm, nomonsters flags to G_LoadOptions()/G_SaveOptions()) + + if ((skill = _g->demover) >= 100) // For demos from versions >= 1.4 + { + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, 8, failonerror)) + return NULL; + + skill = spiFlashGetByteFromAddress(demo_p++); + episode = spiFlashGetByteFromAddress(demo_p++); + map = spiFlashGetByteFromAddress(demo_p++); + demo_p++; + demo_p++; + demo_p++; + demo_p++; + demo_p++; + } + else + { + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, 2, failonerror)) + return NULL; + + episode = spiFlashGetByteFromAddress(demo_p++); + map = spiFlashGetByteFromAddress(demo_p++); + } + + } + else // new versions of demos + { + demo_p += 6; // skip signature; + switch (_g->demover) + { + case 200: /* BOOM */ + case 201: + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, 1, failonerror)) + { + return NULL; + } + break; + case 202: + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, 1, failonerror)) + { + return NULL; + } + break; + case 203: + /* LxDoom or MBF - determine from signature + * cph - load compatibility level */ + switch (*(header_p + 2)) + { + case 'B': /* LxDoom */ + /* cph - DEMOSYNC - LxDoom demos recorded in compatibility modes support dropped */ + break; + case 'M': + demo_p++; + break; + } + break; + case 210: + demo_p++; + break; + case 211: + demo_p++; + break; + case 212: + demo_p++; + break; + case 213: + demo_p++; + break; + case 214: + _g->longtics = 1; + demo_p++; + break; + } + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, 5, failonerror)) + return NULL; + + skill = spiFlashGetByteFromAddress(demo_p++); + episode = spiFlashGetByteFromAddress(demo_p++); + map = spiFlashGetByteFromAddress(demo_p++); + demo_p++; + demo_p++; + + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, GAME_OPTION_SIZE, failonerror)) + return NULL; + + demo_p = G_ReadOptions(demo_p); // killough 3/1/98: Read game options + + if (_g->demover == 200) // killough 6/3/98: partially fix v2.00 demos + demo_p += 256 - GAME_OPTION_SIZE; + } + + //e6y: check for overrun + if (CheckForOverrun(header_p, demo_p, size, MAXPLAYERS, failonerror)) + { + return NULL; + } + _g->playeringame = spiFlashGetByteFromAddress(demo_p++); + demo_p += MIN_MAXPLAYERS - MAXPLAYERS; + if (_g->gameaction != ga_loadgame) + { /* killough 12/98: support -loadgame */ + + G_InitNew(skill, episode, map); + } + _g->player.cheats = 0; + return demo_p; +} + +void G_DoPlayDemo(void) +{ + + char basename[9]; + + ExtractFileBase(defdemoname, basename); // killough + basename[8] = 0; + + /* cph - store lump number for unlocking later */ + demolumpnum = W_GetNumForName(basename); + _g->demobuffer = W_CacheLumpNum(demolumpnum); + _g->demolength = W_LumpLength(demolumpnum); + + _g->demo_p = G_ReadDemoHeader(_g->demobuffer, _g->demolength, true); + + _g->gameaction = ga_nothing; + _g->usergame = false; + + _g->demoplayback = true; + + _g->starttime = I_GetTime(); +} + +/* G_CheckDemoStatus + * + * Called after a death or level completion to allow demos to be cleaned up + * Returns true if a new demo loop action will take place + */ +boolean G_CheckDemoStatus(void) +{ + if (_g->timingdemo) + { + int endtime = I_GetTime(); + // killough -- added fps information and made it work for longer demos: + unsigned realtics = endtime - _g->starttime; + unsigned int fps = (unsigned) _g->gametic * 100 * TICRATE / realtics; + printf("Timed %u gametics in %u realtics = %u.%02u frames per second", (unsigned) _g->gametic, realtics, fps / 100, fps % 100); + } + + if (_g->demoplayback) + { +// if (_g->singledemo) + // exit(0); // killough + + if (demolumpnum != -1) + { + demolumpnum = -1; + } + G_ReloadDefaults(); // killough 3/1/98 + D_AdvanceDemo(); + return true; + } + return false; +} + diff --git a/doom/src/pdoom/Doom/source/global_data.c b/doom/src/pdoom/Doom/source/global_data.c new file mode 100644 index 0000000..dd2a8b9 --- /dev/null +++ b/doom/src/pdoom/Doom/source/global_data.c @@ -0,0 +1,122 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * next-hack: originally doomhack, in his GBA port, put (almost) all the global + * variables in a global structure, which was by the way Z_malloc'ed. + * Here the structure is not z_malloc'ed but it is static. + * + *----------------------------------------------------------------------------- + */ +#include +#include "global_data.h" + +globals_t global; +globals_t *_g; + +void InitGlobals() +{ + _g = &global; + memset(_g, 0, sizeof(globals_t)); + + //****************************************************************************** + //am_map.c + //****************************************************************************** + + _g->scale_mtof = (fixed_t) INITSCALEMTOF; + _g->stopped = true; + + _g->lastlevel = -1; + _g->lastepisode = -1; + + _g->mtof_zoommul = FRACUNIT; // how far the window zooms each tic (map coords) + _g->ftom_zoommul = FRACUNIT; // how far the window zooms each tic (fb coords) + + //****************************************************************************** + //d_main.c + //****************************************************************************** + + _g->wipegamestate = GS_DEMOSCREEN; + _g->oldgamestate = -1; + + //****************************************************************************** + //doomstat.c + //****************************************************************************** + + // Game Mode - identify IWAD as shareware, retail etc. + _g->gamemode = indetermined; + _g->gamemission = doom; + + //****************************************************************************** + //m_menu.c + //****************************************************************************** + + _g->showMessages = 1; // Show messages has default, 0 = off, 1 = on + + //****************************************************************************** + //p_setup.c + //****************************************************************************** + +// _g->rejectlump = -1;// cph - store reject lump num if cached + + //****************************************************************************** + //r_main.c + //****************************************************************************** + + _g->validcount = 1; // increment every time a check is made + + _g->freehead = &_g->freetail; // killough + + //****************************************************************************** + //s_sounds.c + //****************************************************************************** + + _g->snd_SfxVolume = 15; + + // Maximum volume of music. Useless so far. + _g->snd_MusicVolume = 15; + + //****************************************************************************** + //st_stuff.c + //****************************************************************************** + + _g->st_oldhealth = -1; + // + _g->tex_lookup_valid = false; +} diff --git a/doom/src/pdoom/Doom/source/hu_lib.c b/doom/src/pdoom/Doom/source/hu_lib.c new file mode 100644 index 0000000..25c5181 --- /dev/null +++ b/doom/src/pdoom/Doom/source/hu_lib.c @@ -0,0 +1,312 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: heads-up text and input code + * + *----------------------------------------------------------------------------- + */ + +#include "doomdef.h" +#include "doomstat.h" +#include "v_video.h" +#include "m_swap.h" +#include "hu_lib.h" +#include "hu_stuff.h" +#include "r_main.h" +#include "r_draw.h" + +#include "global_data.h" + +//////////////////////////////////////////////////////// +// +// Basic text line widget +// +//////////////////////////////////////////////////////// + +// +// HUlib_clearTextLine() +// +// Blank the internal text line in a hu_textline_t widget +// +// Passed a hu_textline_t, returns nothing +// +void HUlib_clearTextLine(hu_textline_t *t) +{ + t->linelen = // killough 1/23 98: support multiple lines + t->len = 0; + t->l[0] = 0; + t->needsupdate = true; +} + +// +// HUlib_initTextLine() +// +// Initialize a hu_textline_t widget. Set the position, font, start char +// of the font, and color range to be used. +// +// Passed a hu_textline_t, and the values used to initialize +// Returns nothing +// +void HUlib_initTextLine(hu_textline_t *t, short x, short y, const patch_t *f, short sc) +//jff 2/16/98 add color range parameter +{ + t->x = x; + t->y = y; + t->f = (const patch_t**) f; + t->sc = sc; + HUlib_clearTextLine(t); +} + +// +// HUlib_addCharToTextLine() +// +// Adds a character at the end of the text line in a hu_textline_t widget +// +// Passed the hu_textline_t and the char to add +// Returns false if already at length limit, true if the character added +// +boolean HUlib_addCharToTextLine(hu_textline_t *t, char ch) +{ + // killough 1/23/98 -- support multiple lines + if (t->linelen == HU_MAXLINELENGTH) + return false; + else + { + t->linelen++; + if (ch == '\n') + t->linelen = 0; + + t->l[t->len++] = ch; + t->l[t->len] = 0; + t->needsupdate = 4; + return true; + } + +} + +// +// HUlib_drawTextLine() +// +// Draws a hu_textline_t widget +// +// Passed the hu_textline_t and flag whether to draw a cursor +// Returns nothing +// +void HUlib_drawTextLine(hu_textline_t *l, boolean drawcursor) +{ + + int i; + int w; + int x; + unsigned char c; + int y = l->y; // killough 1/18/98 -- support multiple lines + + // draw the new stuff + x = l->x; + for (i = 0; i < l->len; i++) + { + c = toupper(l->l[i]); //jff insure were not getting a cheap toupper conv. + + if (c == '\n') // killough 1/18/98 -- support multiple lines + x = 0, y += 8; + else if (c == '\t') // killough 1/23/98 -- support tab stops + x = x - x % 80 + 80; + else if (c != ' ' && c >= l->sc && c <= '_') + { + w = l->f[c - l->sc]->width; + if (x + w > SCREENWIDTH_PHYSICAL) + break; + // killough 1/18/98 -- support multiple lines: + // CPhipps - patch drawing updated + V_DrawPatchNoScale(x, y, l->f[c - l->sc]); + x += w; + } + else + { + x += 4; + if (x >= SCREENWIDTH_PHYSICAL) + break; + } + } + + // draw the cursor if requested + if (drawcursor && x + l->f['_' - l->sc]->width <= BASE_WIDTH) + { + // killough 1/18/98 -- support multiple lines + // CPhipps - patch drawing updated + V_DrawPatch(x, y, HU_FG, l->f['_' - l->sc]); + } +} + +// +// HUlib_eraseTextLine() +// +// Erases a hu_textline_t widget when screen border is behind text +// Sorta called by HU_Erase and just better darn get things straight +// +// Passed the hu_textline_t +// Returns nothing +// +void HUlib_eraseTextLine(hu_textline_t *l) +{ + if (l->needsupdate) + l->needsupdate--; +} + +//////////////////////////////////////////////////////// +// +// Player message widget (up to 4 lines of text) +// +//////////////////////////////////////////////////////// + +// +// HUlib_initSText() +// +// Initialize a hu_stext_t widget. Set the position, number of lines, font, +// start char of the font, and color range to be used, and whether enabled. +// +// Passed a hu_stext_t, and the values used to initialize +// Returns nothing +// +void HUlib_initSText(hu_stext_t *s, short x, short y, short h, const patch_t *font, short startchar, boolean *on) +{ + + int i; + + s->h = h; + s->on = on; + s->laston = true; + s->cl = 0; + for (i = 0; i < h; i++) + HUlib_initTextLine(&s->l[i], x, y - i * (font[0].height + 1), font, startchar); +} + +// +// HUlib_addLineToSText() +// +// Adds a blank line to a hu_stext_t widget +// +// Passed a hu_stext_t +// Returns nothing +// +static void HUlib_addLineToSText(hu_stext_t *s) +{ + + int i; + + // add a clear line + if (++s->cl == s->h) + s->cl = 0; + HUlib_clearTextLine(&s->l[s->cl]); + + // everything needs updating + for (i = 0; i < s->h; i++) + s->l[i].needsupdate = 4; + +} + +// +// HUlib_addMessageToSText() +// +// Adds a message line with prefix to a hu_stext_t widget +// +// Passed a hu_stext_t, the prefix string, and a message string +// Returns nothing +// +void HUlib_addMessageToSText(hu_stext_t *s, const char *prefix, const char *msg) +{ + HUlib_addLineToSText(s); + if (prefix) + while (*prefix) + HUlib_addCharToTextLine(&s->l[s->cl], *(prefix++)); + + while (*msg) + HUlib_addCharToTextLine(&s->l[s->cl], *(msg++)); +} + +// +// HUlib_drawSText() +// +// Displays a hu_stext_t widget +// +// Passed a hu_stext_t +// Returns nothing +// +void HUlib_drawSText(hu_stext_t *s) +{ + int i, idx; + hu_textline_t *l; + + if (!*s->on) + return; // if not on, don't draw + + // draw everything + for (i = 0; i < s->h; i++) + { + idx = s->cl - i; + if (idx < 0) + idx += s->h; // handle queue of lines + + l = &s->l[idx]; + + // need a decision made here on whether to skip the draw + HUlib_drawTextLine(l, false); // no cursor, please + } +} + +// +// HUlib_eraseSText() +// +// Erases a hu_stext_t widget, when the screen is not fullsize +// +// Passed a hu_stext_t +// Returns nothing +// +void HUlib_eraseSText(hu_stext_t *s) +{ + int i; + + for (i = 0; i < s->h; i++) + { + if (s->laston && !*s->on) + s->l[i].needsupdate = 4; + HUlib_eraseTextLine(&s->l[i]); + } + s->laston = *s->on; +} diff --git a/doom/src/pdoom/Doom/source/hu_stuff.c b/doom/src/pdoom/Doom/source/hu_stuff.c new file mode 100644 index 0000000..5e9291f --- /dev/null +++ b/doom/src/pdoom/Doom/source/hu_stuff.c @@ -0,0 +1,535 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: Heads-up displays + * + *----------------------------------------------------------------------------- + */ + +// killough 5/3/98: remove unnecessary headers +#include "doomstat.h" +#include "hu_stuff.h" +#include "hu_lib.h" +#include "st_stuff.h" /* jff 2/16/98 need loc of status bar */ +#include "w_wad.h" +#include "s_sound.h" +#include "dstrings.h" +#include "sounds.h" +#include "g_game.h" +#include "r_main.h" + +#include "global_data.h" + +// global heads up display controls + +// +// Locally used constants, shortcuts. +// +// Ty 03/28/98 - +// These four shortcuts modifed to reflect char ** of mapnamesx[] +#define HU_TITLE (mapnames[(_g->gameepisode-1)*9+_g->gamemap-1]) +#define HU_TITLE2 (mapnames2[_g->gamemap-1]) +#define HU_TITLEP (mapnamesp[_g->gamemap-1]) +#define HU_TITLET (mapnamest[_g->gamemap-1]) +#define HU_TITLEHEIGHT 1 +#define HU_TITLEX 0 +//jff 2/16/98 change 167 to ST_Y-1 +// CPhipps - changed to ST_TY +// proff - changed to 200-ST_HEIGHT for stretching +#define HU_TITLEY ((SCREENHEIGHT-ST_SCALED_HEIGHT) - 1 - hu_font[0]->height) + +//jff 2/16/98 add coord text widget coordinates +// proff - changed to SCREENWIDTH to 320 for stretching +#define HU_COORDX (320 - 13*hu_font['A'-HU_FONTSTART].width) +//jff 3/3/98 split coord widget into three lines in upper right of screen +#define HU_COORDX_Y (1 + 0*hu_font['A'-HU_FONTSTART].height) +#define HU_COORDY_Y (2 + 1*hu_font['A'-HU_FONTSTART].height) +#define HU_COORDZ_Y (3 + 2*hu_font['A'-HU_FONTSTART].height) + +//jff 2/16/98 add ammo, health, armor widgets, 2/22/98 less gap +#define HU_GAPY 8 +#define HU_HUDHEIGHT (6*HU_GAPY) +#define HU_HUDX 2 +#define HU_HUDY (200-HU_HUDHEIGHT-1) +#define HU_MONSECX (HU_HUDX) +#define HU_MONSECY (HU_HUDY+0*HU_GAPY) +#define HU_KEYSX (HU_HUDX) +//jff 3/7/98 add offset for graphic key widget +#define HU_KEYSGX (HU_HUDX+4*hu_font['A'-HU_FONTSTART].width) +#define HU_KEYSY (HU_HUDY+1*HU_GAPY) +#define HU_WEAPX (HU_HUDX) +#define HU_WEAPY (HU_HUDY+2*HU_GAPY) +#define HU_AMMOX (HU_HUDX) +#define HU_AMMOY (HU_HUDY+3*HU_GAPY) +#define HU_HEALTHX (HU_HUDX) +#define HU_HEALTHY (HU_HUDY+4*HU_GAPY) +#define HU_ARMORX (HU_HUDX) +#define HU_ARMORY (HU_HUDY+5*HU_GAPY) + +//jff 3/4/98 distributed HUD positions +#define HU_HUDX_LL 2 +#define HU_HUDY_LL (200-2*HU_GAPY-1) +// proff/nicolas 09/20/98: Changed for high-res +//#define HU_HUDX_LR (320-120) +#define HU_HUDY_LR (200-2*HU_GAPY-1) +// proff/nicolas 09/20/98: Changed for high-res +#define HU_HUDX_UR (320-96) +#define HU_HUDY_UR 2 +#define HU_MONSECX_D (HU_HUDX_LL) +#define HU_MONSECY_D (HU_HUDY_LL+0*HU_GAPY) +#define HU_KEYSX_D (HU_HUDX_LL) +#define HU_KEYSGX_D (HU_HUDX_LL+4*hu_font['A'-HU_FONTSTART].width) +#define HU_KEYSY_D (HU_HUDY_LL+1*HU_GAPY) +//#define HU_WEAPX_D (HU_HUDX_LR) +#define HU_WEAPY_D (HU_HUDY_LR+0*HU_GAPY) +//#define HU_AMMOX_D (HU_HUDX_LR) +#define HU_AMMOY_D (HU_HUDY_LR+1*HU_GAPY) +#define HU_HEALTHX_D (HU_HUDX_UR) +#define HU_HEALTHY_D (HU_HUDY_UR+0*HU_GAPY) +#define HU_ARMORX_D (HU_HUDX_UR) +#define HU_ARMORY_D (HU_HUDY_UR+1*HU_GAPY) + +//#define HU_INPUTTOGGLE 't' // not used // phares +#define HU_INPUTX HU_MSGX +#define HU_INPUTY (HU_MSGY + HU_MSGHEIGHT*(hu_font[0].height) +1) +#define HU_INPUTWIDTH 64 +#define HU_INPUTHEIGHT 1 + +#define key_alt KEYD_RALT +#define key_shift KEYD_RSHIFT + +//jff 2/16/98 hud supported automap colors added +const int hudcolor_titl = 5; // color range of automap level title +//jff 2/16/98 hud text colors, controls added +const int hudcolor_mesg = 6; // color range of scrolling messages + +//jff 2/26/98 hud text colors, controls added + +const int hud_msg_lines = 1; // number of message lines in window + +// font sets +const patch_t *hu_font[HU_FONTSIZE]; + +// +// Builtin map names. +// The actual names can be found in DStrings.h. +// +// Ty 03/27/98 - externalized map name arrays - now in d_deh.c +// and converted to arrays of pointers to char * +// See modified HUTITLEx macros +// DOOM shareware/registered/retail (Ultimate) names. +// CPhipps - const**const +const char *const mapnames[] = +{ + HUSTR_E1M1, + HUSTR_E1M2, + HUSTR_E1M3, + HUSTR_E1M4, + HUSTR_E1M5, + HUSTR_E1M6, + HUSTR_E1M7, + HUSTR_E1M8, + HUSTR_E1M9, + + HUSTR_E2M1, + HUSTR_E2M2, + HUSTR_E2M3, + HUSTR_E2M4, + HUSTR_E2M5, + HUSTR_E2M6, + HUSTR_E2M7, + HUSTR_E2M8, + HUSTR_E2M9, + + HUSTR_E3M1, + HUSTR_E3M2, + HUSTR_E3M3, + HUSTR_E3M4, + HUSTR_E3M5, + HUSTR_E3M6, + HUSTR_E3M7, + HUSTR_E3M8, + HUSTR_E3M9, + + HUSTR_E4M1, + HUSTR_E4M2, + HUSTR_E4M3, + HUSTR_E4M4, + HUSTR_E4M5, + HUSTR_E4M6, + HUSTR_E4M7, + HUSTR_E4M8, + HUSTR_E4M9, +}; + +// CPhipps - const**const +const char *const mapnames2[] = // DOOM 2 map names. +{ + HUSTR_1, + HUSTR_2, + HUSTR_3, + HUSTR_4, + HUSTR_5, + HUSTR_6, + HUSTR_7, + HUSTR_8, + HUSTR_9, + HUSTR_10, + HUSTR_11, + + HUSTR_12, + HUSTR_13, + HUSTR_14, + HUSTR_15, + HUSTR_16, + HUSTR_17, + HUSTR_18, + HUSTR_19, + HUSTR_20, + + HUSTR_21, + HUSTR_22, + HUSTR_23, + HUSTR_24, + HUSTR_25, + HUSTR_26, + HUSTR_27, + HUSTR_28, + HUSTR_29, + HUSTR_30, + HUSTR_31, + HUSTR_32, +}; + +//CPhipps - const**const +const char *const mapnamesp[] = // Plutonia WAD map names. +{ + PHUSTR_1, + PHUSTR_2, + PHUSTR_3, + PHUSTR_4, + PHUSTR_5, + PHUSTR_6, + PHUSTR_7, + PHUSTR_8, + PHUSTR_9, + PHUSTR_10, + PHUSTR_11, + + PHUSTR_12, + PHUSTR_13, + PHUSTR_14, + PHUSTR_15, + PHUSTR_16, + PHUSTR_17, + PHUSTR_18, + PHUSTR_19, + PHUSTR_20, + + PHUSTR_21, + PHUSTR_22, + PHUSTR_23, + PHUSTR_24, + PHUSTR_25, + PHUSTR_26, + PHUSTR_27, + PHUSTR_28, + PHUSTR_29, + PHUSTR_30, + PHUSTR_31, + PHUSTR_32, +}; + +// CPhipps - const**const +const char *const mapnamest[] = // TNT WAD map names. +{ + THUSTR_1, + THUSTR_2, + THUSTR_3, + THUSTR_4, + THUSTR_5, + THUSTR_6, + THUSTR_7, + THUSTR_8, + THUSTR_9, + THUSTR_10, + THUSTR_11, + + THUSTR_12, + THUSTR_13, + THUSTR_14, + THUSTR_15, + THUSTR_16, + THUSTR_17, + THUSTR_18, + THUSTR_19, + THUSTR_20, + + THUSTR_21, + THUSTR_22, + THUSTR_23, + THUSTR_24, + THUSTR_25, + THUSTR_26, + THUSTR_27, + THUSTR_28, + THUSTR_29, + THUSTR_30, + THUSTR_31, + THUSTR_32, +}; + +// +// HU_Init() +// +// Initialize the heads-up display, text that overwrites the primary display +// +// Passed nothing, returns nothing +// +void HU_Init(void) +{ + int i; + int j; + char buffer[9]; + + // load the heads-up font + j = HU_FONTSTART; + for (i = 0; i < HU_FONTSIZE; i++) + { + sprintf(buffer, "STCFN%.3d", j++); + hu_font[i] = (const patch_t*) writeLumpToFlashRegion(W_GetNumForName(buffer), FLASH_IMMUTABLE_REGION, true); // W_CacheLumpName(buffer); + } +} + +// +// HU_Stop() +// +// Make the heads-up displays inactive +// +// Passed nothing, returns nothing +// +static void HU_Stop(void) +{ + _g->headsupactive = false; +} + +// +// HU_Start(void) +// +// Create and initialize the heads-up widgets, software machines to +// maintain, update, and display information over the primary display +// +// This routine must be called after any change to the heads up configuration +// in order for the changes to take effect in the actual displays +// +// Passed nothing, returns nothing +// +void HU_Start(void) +{ + const char *s; /* cph - const */ + + if (_g->headsupactive) // stop before starting + HU_Stop(); + + _g->message_on = false; + _g->message_dontfuckwithme = false; + + // create the message widget + // messages to player in upper-left of screen + + HUlib_initSText(&_g->w_message, + HU_MSGX, + HU_MSGY, + HU_MSGHEIGHT, (const patch_t*) hu_font, // nh FIXME possible bug + HU_FONTSTART, &_g->message_on); + + //jff 2/16/98 added some HUD widgets + // create the map title widget - map title display in lower left of automap + HUlib_initTextLine(&_g->w_title, + HU_TITLEX, + HU_TITLEY, (const patch_t*) hu_font, // nh FIXME possible bug + HU_FONTSTART); + + // initialize the automap's level title widget + if (_g->gamestate == GS_LEVEL) /* cph - stop SEGV here when not in level */ + switch (_g->gamemode) + { + case shareware: + case registered: + case retail: + s = HU_TITLE; +#ifdef PDM_LUMPTXT + /* 1.7.3 test17: names of an episode in the place of E4 (Sigil): lump PDMHU4, one line per map */ + if (_g->gameepisode == 4) + { + static char t[40]; int l = W_CheckNumForName("PDMHU4"); + if (l >= 0) + { + const char *p = (const char*) W_CacheLumpNum(l), *e = p + W_LumpLength(l); + for (int k = 1; k < _g->gamemap && p < e; p++) if (*p == '\n') k++; + int n = 0; while (p < e && *p != '\n' && *p && n < 39) t[n++] = *p++; + t[n] = 0; if (n) s = t; + } + } +#endif + break; + + case commercial: + default: // Ty 08/27/98 - modified to check mission for TNT/Plutonia + s = (_g->gamemission == pack_tnt) ? HU_TITLET : + (_g->gamemission == pack_plut) ? HU_TITLEP : HU_TITLE2; + break; + } + else + s = ""; + while (*s) + HUlib_addCharToTextLine(&_g->w_title, *(s++)); + + // now allow the heads-up display to run + _g->headsupactive = true; + + HU_MoveHud(); +} + +// +// HU_MoveHud() +// +// Move the HUD display from distributed to compact mode or vice-versa +// +// Passed nothing, returns nothing +// +//jff 3/9/98 create this externally callable to avoid glitch +// when menu scatter's HUD due to delay in change of position +// +void HU_MoveHud(void) +{ + +} + +// +// HU_Drawer() +// +// Draw all the pieces of the heads-up display +// +// Passed nothing, returns nothing +// +void HU_Drawer(void) +{ + // draw the automap widgets if automap is displayed + if (_g->automapmode & am_active) + { + // map title + HUlib_drawTextLine(&_g->w_title, false); + } + + //jff 3/4/98 display last to give priority + HU_Erase(); // jff 4/24/98 Erase current lines before drawing current + // needed when screen not fullsize + + HUlib_drawSText(&_g->w_message); +} + +// +// HU_Erase() +// +// Erase hud display lines that can be trashed by small screen display +// +// Passed nothing, returns nothing +// +void HU_Erase(void) +{ + // erase the message display or the message review display + HUlib_eraseSText(&_g->w_message); + + // erase the automap title + HUlib_eraseTextLine(&_g->w_title); +} + +// +// HU_Ticker() +// +// Update the hud displays once per frame +// +// Passed nothing, returns nothing +// + +void HU_Ticker(void) +{ + player_t *plr = &_g->player; // killough 3/7/98 + + // tick down message counter if message is up + if (_g->message_counter && !--_g->message_counter) + { + _g->message_on = false; + } + + // if messages on, or "Messages Off" is being displayed + // this allows the notification of turning messages off to be seen + if (_g->showMessages || _g->message_dontfuckwithme) + { + // display message if necessary + if (plr->message) + { + //post the message to the message widget + HUlib_addMessageToSText(&_g->w_message, 0, plr->message); + + // clear the message to avoid posting multiple times + plr->message = 0; + // note a message is displayed + _g->message_on = true; + // start the message persistence counter + _g->message_counter = HU_MSGTIMEOUT; + + // clear the flag that "Messages Off" is being posted + _g->message_dontfuckwithme = 0; + } + } +} + +// +// HU_Responder() +// +// Responds to input events that affect the heads up displays +// +// Passed the event to respond to, returns true if the event was handled +// +boolean HU_Responder(event_t *ev) +{ + return false; +} diff --git a/doom/src/pdoom/Doom/source/i_audio.c b/doom/src/pdoom/Doom/source/i_audio.c new file mode 100644 index 0000000..bd5c791 --- /dev/null +++ b/doom/src/pdoom/Doom/source/i_audio.c @@ -0,0 +1,163 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * System interface for sound. + * next-hack: added support for pwm sound. Removed music. + * + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#ifdef HAVE_UNISTD_H +#include +#endif + +#include "z_zone.h" + +#include "m_swap.h" +#include "i_sound.h" +#include "m_misc.h" +#include "w_wad.h" +#include "lprintf.h" +#include "s_sound.h" + +#include "doomdef.h" +#include "doomstat.h" +#include "doomtype.h" + +#include "d_main.h" + +#include "m_fixed.h" + +#include "global_data.h" +#include "pwm_audio.h" + +// +// Starting a sound means adding it +// to the current list of active sounds +// in the internal channels. +// As the SFX info struct contains +// e.g. a pointer to the raw data, +// it is ignored. +// As our sound handling does not handle +// priority, it is ignored. +// Pitching (that is, increased speed of playback) +// is set, but currently not used by mixing. +// +int I_StartSound(int id, int channel, int vol, int sep) +{ + + if ((channel < 0) || (channel >= MAX_CHANNELS)) + return -1; + // 2021/05/15 next-hack + // + soundChannels[channel].lastAudioBufferIdx = 0xFFFF; + soundChannels[channel].offset = 0; + soundChannels[channel].sfxIdx = id; + soundChannels[channel].volume = vol; +#ifdef PARADISE_DEV + { extern void plat_sound(int id); if (vol > 0) plat_sound(id); } /* v0.2.6: effects volume 0 in the menu = silent */ +#endif + return channel; +} + +void I_ShutdownSound(void) +{ + if (_g->sound_inited) + { + lprintf(LO_INFO, "I_ShutdownSound: "); + lprintf(LO_INFO, "\n"); + _g->sound_inited = false; + } +} + +//static SDL_AudioSpec audio; + +void I_InitSound(void) +{ + + if (!nomusicparm) + I_InitMusic(); + + // Finished initialization. + lprintf(LO_INFO, "I_InitSound: sound ready"); +} + +void I_InitMusic(void) +{ +} + +void I_PlaySong(int handle, int looping) +{ + if (handle == mus_None) + return; +#if defined(PARADISE_DEV) && defined(MUS_PLAY) + { extern void plat_music_play(int h, int l); plat_music_play(handle, looping); } +#endif + +} + +#if defined(PARADISE_DEV) && defined(MUS_PLAY) +extern void plat_music_pause(int p); extern void plat_music_stop(void); extern void plat_music_volume(int v); +void I_PauseSong(int handle) { plat_music_pause(1); } +void I_ResumeSong(int handle) { plat_music_pause(0); } +void I_StopSong(int handle) { plat_music_stop(); } +void I_SetMusicVolume(int volume) { plat_music_volume(volume); } +#else +void I_PauseSong(int handle) +{ +} + +void I_ResumeSong(int handle) +{ +} + +void I_StopSong(int handle) +{ +} + +void I_SetMusicVolume(int volume) +{ +} +#endif diff --git a/doom/src/pdoom/Doom/source/i_main.c b/doom/src/pdoom/Doom/source/i_main.c new file mode 100644 index 0000000..74b4377 --- /dev/null +++ b/doom/src/pdoom/Doom/source/i_main.c @@ -0,0 +1,106 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Startup and quit functions. Handles signals, inits the + * memory management, then calls D_DoomMain. Also contains + * I_Init which does other system-related startup stuff. + * + * next-hack: put sound init and time functions + * + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#ifdef HAVE_UNISTD_H +#include +#endif + +#include "doomdef.h" +#include "d_main.h" +#include "m_fixed.h" +#include "i_system.h" +#include "i_video.h" +#include "z_zone.h" +#include "lprintf.h" +#include "m_random.h" +#include "doomstat.h" +#include "g_game.h" +#include "m_misc.h" +#include "i_sound.h" +#include "i_main.h" +#include "lprintf.h" +#include "global_data.h" + +#include +#include +#include "nrf.h" +unsigned int plat_micros(void); +unsigned int I_GetTimeMicrosecs() +{ + return plat_micros(); +} + +unsigned int I_GetTime(void) +{ + uint32_t time = I_GetTimeMicrosecs(); + if (!_g->basetime) + { + _g->basetime = time; + return 0; + } + uint32_t diff = time - _g->basetime; + #define SPEED10X 0 + #if SPEED10X + #warning speed10x + diff = diff / (100000 / TICRATE); + + #else + diff = diff / (1000000 / TICRATE); + #endif + return diff; +} + +void I_Init(void) +{ + if (!(nomusicparm && nosfxparm)) + I_InitSound(); +} diff --git a/doom/src/pdoom/Doom/source/i_spi_support.c b/doom/src/pdoom/Doom/source/i_spi_support.c new file mode 100644 index 0000000..fbefe34 --- /dev/null +++ b/doom/src/pdoom/Doom/source/i_spi_support.c @@ -0,0 +1,61 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * next-hack: Some wrapper functions, to use SPI routines. + * Memory mapped code has been removed. + */ +#include +#include "i_spi_support.h" +#include "printf.h" +uint8_t *currentSpiAddress; +#if NO_INLINE_SPI +uint32_t spiFlashSetAddress(uint32_t address) +{ + currentSpiAddress = (uint8_t*) address; +// printf("SA 0x%08x 0x%02x\r\n", address, *currentSpiAddress); +} +void* spiFlashGetData(void *dest, unsigned int length) +{ + memcpy(dest, currentSpiAddress, length); + currentSpiAddress += length; +// printf("GD: %08x, %d: %08x\r\n", currentSpiAddress, length, *((uint32_t*) dest)); + return dest; +} +#endif diff --git a/doom/src/pdoom/Doom/source/i_video.c b/doom/src/pdoom/Doom/source/i_video.c new file mode 100644 index 0000000..f601db3 --- /dev/null +++ b/doom/src/pdoom/Doom/source/i_video.c @@ -0,0 +1,297 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * DOOM graphics stuff. + * next-hack: and also key handling, don't ask me why they were put in + * i_video.c. Key handling and graphics I/O modified according HW... + * + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "main.h" +#include + +#ifdef HAVE_UNISTD_H +#include +#endif + +#include +#include "main.h" + +#include "doomstat.h" +#include "doomdef.h" +#include "doomtype.h" +#include "v_video.h" +#include "r_draw.h" +#include "d_main.h" +#include "d_event.h" +#include "i_video.h" +#include "i_sound.h" +#include "m_menu.h" +#include "z_zone.h" +#include "s_sound.h" +#include "sounds.h" +#include "w_wad.h" +#include "st_stuff.h" +#include "lprintf.h" +#include "doomdef.h" + +#include "global_data.h" +#include "display.h" +#include "graphics.h" +#include "keyboard.h" + +#define NO_PALETTE_CHANGE 255 + +uint16_t palette[256]; +bool toggleBacklight = false; + +key_t keysDown() +{ + key_t buttons = 0; + getKeys(&buttons); + return buttons; +} +// +// I_StartTic +// +void I_StartTic(void) +{ + static uint16_t oldGameKeyState = 0; + // get which keys are currently pressed + key_t hwKeyState = keysDown(); + // translate between the hardware key state and the game key state + uint16_t gameKeyState = 0; + + if (hwKeyState & KEY_ALT) + { + if (hwKeyState & KEY_RIGHT) + gameKeyState |= 1 << KEYD_SR; + if (hwKeyState & KEY_LEFT) + gameKeyState |= 1 << KEYD_SL; + if (hwKeyState & KEY_USE) +#if KEYBOARD == I2C_GAMEPAD + // USE negates always run setting, so with a dedicated MENU key the USE button + // can be freed from the ALT combo allowing it to be dual-purpose USE and SPEED button + gameKeyState |= 1 << KEYD_USE; +#else + gameKeyState |= 1 << KEYD_MENU; +#endif + if (hwKeyState & KEY_CHGW) + gameKeyState |= 1 << KEYD_CHGWDOWN; +#if OLD_KEYMAP // it was not wise setting ALT with fire to trigger automap... + if (hwKeyState & KEY_FIRE) + gameKeyState |= 1 << KEYD_MAP1; +#else + if (hwKeyState & KEY_FIRE) + gameKeyState |= 1 << KEYD_FIRE; +#endif + if (! (hwKeyState & (KEY_RIGHT | KEY_LEFT | KEY_USE | KEY_CHGW | KEY_FIRE))) + gameKeyState |= 1 << KEYD_ALT; + } + else + { + if (hwKeyState & KEY_RIGHT) + gameKeyState |= 1 << KEYD_RIGHT; + if (hwKeyState & KEY_LEFT) + gameKeyState |= 1 << KEYD_LEFT; + if (hwKeyState & KEY_FIRE) + gameKeyState |= 1 << KEYD_FIRE; +#if KEYBOARD == I2C_GAMEPAD + // remap USE+CHGW from MAP1 in other keymaps to CHGWDOWN + if ((hwKeyState & (KEY_USE | KEY_CHGW)) == (KEY_USE | KEY_CHGW)) + gameKeyState |= 1 << KEYD_CHGWDOWN; + else + { +#endif + if (hwKeyState & KEY_USE) + gameKeyState |= 1 << KEYD_USE; + if (hwKeyState & KEY_CHGW) + gameKeyState |= 1 << KEYD_CHGW; +#if KEYBOARD == I2C_GAMEPAD + } +#endif + } + + if (hwKeyState & KEY_UP) + gameKeyState |= 1 << KEYD_UP; + if (hwKeyState & KEY_DOWN) + gameKeyState |= 1 << KEYD_DOWN; +#if KEYBOARD == I2C_GAMEPAD + // Gamepad has 10 total buttons, with extra byte for key data can have MAP1 and MENU as dedicated buttons + if (hwKeyState & KEY_MAP) + gameKeyState |= 1 << KEYD_MAP1; + if (hwKeyState & KEY_MENU) + gameKeyState |= 1 << KEYD_MENU; +#endif +#if !OLD_KEYMAP && KEYBOARD != I2C_GAMEPAD + // automap is now enabled when use and change weapon are pressed at the same time (or chgwdown for i2c gamepad) + if ((hwKeyState & (KEY_USE | KEY_CHGW)) == (KEY_USE | KEY_CHGW)) + gameKeyState |= 1 << KEYD_MAP1; +#endif + // Get which keys have changed since last time + uint16_t keys_changed = oldGameKeyState ^ gameKeyState; + + event_t ev; + ev.type = ev_keydown; + for (int i = 0; i < NUMKEYS; i++) + { + if ((1 & (keys_changed >> i)) && (1 & (gameKeyState >> i))) + { + ev.data1 = i; + D_PostEvent(&ev); + } + } + ev.type = ev_keyup; + for (int i = 0; i < NUMKEYS; i++) + { + if ((1 & (keys_changed >> i)) && !(1 & (gameKeyState >> i))) + { + ev.data1 = i; + D_PostEvent(&ev); + } + } + oldGameKeyState = gameKeyState; + +#if 0 + // handle onboard clue buttons for gamma adjust and toggling backlight + static bool aBtnWasDown = false; + static bool bBtnWasDown = false; + bool aDown = !(GPIO_PORT(PORT_NUM_BTN_A)->IN & (1 << PIN_NUM_BTN_A)); + bool bDown = !(GPIO_PORT(PORT_NUM_BTN_B)->IN & (1 << PIN_NUM_BTN_B)); + + if (aDown && bDown && (!aBtnWasDown || !bBtnWasDown)) + toggleBacklight = true; + else if (aDown && !aBtnWasDown) + M_ChangeGamma(0); + else if (bDown && !bBtnWasDown) + M_ChangeGamma(1); + + aBtnWasDown = aDown; + bBtnWasDown = bDown; +#endif +} + +boolean I_StartDisplay(void) +{ + _g->screens[0].data = displayData.displayFrameBuffer[displayData.workingBuffer]; + // Same with base row offset. + drawvars.byte_topleft = _g->screens[0].data; + return true; +} + +///////////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////// +// Palette stuff. +// + +static void I_UploadNewPalette(int pal) +{ +#ifdef PARADISE_DEV + static int lastpal = -1, lastgamma = -1; + if (pal == lastpal && _g->gamma == lastgamma && _g->current_palette == palette) + return; + lastpal = pal; lastgamma = _g->gamma; +#endif + _g->current_palette = palette; + // + if (_g->gamma) + { + + for (int i = 0; i < 256; i++) + { + uint16_t r = gammatable[_g->gamma][p_wad_immutable_flash_data->palette_lump[pal * 256 * 3 + 3 * i]] >> 3; + uint16_t g = gammatable[_g->gamma][p_wad_immutable_flash_data->palette_lump[pal * 256 * 3 + 3 * i + 1]] >> 2; + uint16_t b = gammatable[_g->gamma][p_wad_immutable_flash_data->palette_lump[pal * 256 * 3 + 3 * i + 2]] >> 3; + uint16_t rgb = (r << (6 + 5)) | (g << 5) | (b << (0)); + rgb = (rgb >> 8) | (rgb << 8); + _g->current_palette[i] = rgb; + } + } + else + { // save some cycles for those playing with 0 gamma. + for (int i = 0; i < 256; i++) + { + uint16_t r = p_wad_immutable_flash_data->palette_lump[pal * 256 * 3 + 3 * i] >> 3; + uint16_t g = p_wad_immutable_flash_data->palette_lump[pal * 256 * 3 + 3 * i + 1] >> 2; + uint16_t b = p_wad_immutable_flash_data->palette_lump[pal * 256 * 3 + 3 * i + 2] >> 3; + uint16_t rgb = (r << (6 + 5)) | (g << 5) | (b << (0)); + rgb = (rgb >> 8) | (rgb << 8); + _g->current_palette[i] = rgb; + } + } + displayData.pPalette = _g->current_palette; +} + +////////////////////////////////////////////////////////////////////////////// +// Graphics API +// + +void I_FinishUpdateBlock(void) +{ + I_UploadNewPalette(_g->newpal); + + startDisplayRefresh(displayData.workingBuffer); + displayData.workingBuffer = 1 - displayData.workingBuffer; +} + +// +// I_SetPalette +// +void I_SetPalette(int pal) +{ + _g->newpal = pal; +} + +void handleDisplayBacklightToggle() { + static bool backlightOn = true; + + if (toggleBacklight) + { + toggleBacklight = false; + backlightOn = !backlightOn; + SetBacklight(backlightOn); + } +} \ No newline at end of file diff --git a/doom/src/pdoom/Doom/source/info.c b/doom/src/pdoom/Doom/source/info.c new file mode 100644 index 0000000..fdf9a54 --- /dev/null +++ b/doom/src/pdoom/Doom/source/info.c @@ -0,0 +1,4835 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Thing frame/state LUT, + * generated by multigen utilitiy. + * This one is the original DOOM version, preserved. + * BOOM changes include commenting and addition of predefined lumps + * for providing things that aren't in the IWAD without sending a + * separate must-use wad file around with the EXE. + * + * next-hack: added MF_DECORATION flag, to identify those objects + * that are static (like MF_SPECIAL), and do not require full mobj_t structure. + * This saves 96 bytes/mobj with respect to GBA port. + *----------------------------------------------------------------------------- + */ + +#include "doomdef.h" +#include "sounds.h" +#include "m_fixed.h" +#include "p_mobj.h" +#include "p_enemy.h" +#include "p_pspr.h" +#include "w_wad.h" + +#ifdef __GNUG__ +#pragma implementation "info.h" +#endif +#include "info.h" + +// ******************************************************************** +// Sprite names +// ******************************************************************** +// This is the list of sprite 4-character prefixes. They are searched +// through, with a NULL entry terminating the list. In DOOM originally +// this NULL entry was missing, and coincidentally the next thing in +// memory was the dummy state_t[] entry that started with zero bytes. +// killough 1/17/98: add an explicit NULL entry. +// NUMSPRITES is an enum from info.h where all these are listed +// as SPR_xxxx + +const char *const sprnames[NUMSPRITES + 1] = +{ "TROO", "SHTG", "PUNG", "PISG", "PISF", "SHTF", "SHT2", "CHGG", "CHGF", "MISG", "MISF", "SAWG", "PLSG", "PLSF", "BFGG", "BFGF", "BLUD", "PUFF", "BAL1", "BAL2", "PLSS", "PLSE", "MISL", "BFS1", "BFE1", "BFE2", "TFOG", "IFOG", "PLAY", "POSS", "SPOS", "VILE", "FIRE", "FATB", "FBXP", "SKEL", "MANF", "FATT", "CPOS", "SARG", "HEAD", "BAL7", "BOSS", "BOS2", "SKUL", "SPID", "BSPI", "APLS", "APBX", "CYBR", "PAIN", "SSWV", "KEEN", "BBRN", "BOSF", "ARM1", "ARM2", "BAR1", "BEXP", "FCAN", "BON1", "BON2", "BKEY", "RKEY", "YKEY", "BSKU", "RSKU", "YSKU", "STIM", "MEDI", "SOUL", "PINV", "PSTR", "PINS", "MEGA", "SUIT", "PMAP", "PVIS", "CLIP", "AMMO", "ROCK", "BROK", "CELL", "CELP", "SHEL", "SBOX", "BPAK", "BFUG", "MGUN", "CSAW", "LAUN", "PLAS", "SHOT", "SGN2", "COLU", "SMT2", "GOR1", "POL2", "POL5", "POL4", "POL3", "POL1", "POL6", "GOR2", "GOR3", "GOR4", "GOR5", "SMIT", "COL1", "COL2", "COL3", "COL4", "CAND", "CBRA", "COL6", "TRE1", "TRE2", "ELEC", "CEYE", "FSKU", "COL5", "TBLU", "TGRN", "TRED", "SMBT", "SMGT", "SMRT", "HDB1", "HDB2", "HDB3", "HDB4", "HDB5", "HDB6", "POB1", "POB2", "BRS1", "TLMP", "TLP2", "TNT1", // invisible sprite phares 3/9/98 +NULL }; + +// ******************************************************************** +// State or "frame" information +// ******************************************************************** +// Each of the states, otherwise known as "frames", is outlined +// here. The data in each element of the array is the way it is +// initialized, with sprite names identified by their enumerator +// value such as SPR_SHTG. These correlate to the above sprite +// array so don't change them around unless you understand what +// you're doing. +// +// The commented name beginning with S_ at the end of each line +// is there to help figure out where the next-frame pointer is +// pointing. These are also additionally identified in info.h +// as enumerated values. From a change-and-recompile point of +// view this is fairly workable, but it adds a lot to the effort +// when trying to change things externally. See also the d_deh.c +// parts where frame rewiring is done for more details and the +// extended way a BEX file can handle this. +const state_t states[NUMSTATES] = +{ + { SPR_TROO, 0, -1, NULL, S_NULL, 0, 0 }, // S_NULL + { SPR_SHTG, 4, 0, A_Light0, S_NULL, 0, 0 }, // S_LIGHTDONE + { SPR_PUNG, 0, 1, A_WeaponReady, S_PUNCH, 0, 0 }, // S_PUNCH + { SPR_PUNG, 0, 1, A_Lower, S_PUNCHDOWN, 0, 0 }, // S_PUNCHDOWN + { SPR_PUNG, 0, 1, A_Raise, S_PUNCHUP, 0, 0 }, // S_PUNCHUP + { SPR_PUNG, 1, 4, NULL, S_PUNCH2, 0, 0 }, // S_PUNCH1 + { SPR_PUNG, 2, 4, A_Punch, S_PUNCH3, 0, 0 }, // S_PUNCH2 + { SPR_PUNG, 3, 5, NULL, S_PUNCH4, 0, 0 }, // S_PUNCH3 + { SPR_PUNG, 2, 4, NULL, S_PUNCH5, 0, 0 }, // S_PUNCH4 + { SPR_PUNG, 1, 5, A_ReFire, S_PUNCH, 0, 0 }, // S_PUNCH5 + { SPR_PISG, 0, 1, A_WeaponReady, S_PISTOL, 0, 0 }, // S_PISTOL + { SPR_PISG, 0, 1, A_Lower, S_PISTOLDOWN, 0, 0 }, // S_PISTOLDOWN + { SPR_PISG, 0, 1, A_Raise, S_PISTOLUP, 0, 0 }, // S_PISTOLUP + { SPR_PISG, 0, 4, NULL, S_PISTOL2, 0, 0 }, // S_PISTOL1 + { SPR_PISG, 1, 6, A_FirePistol, S_PISTOL3, 0, 0 }, // S_PISTOL2 + { SPR_PISG, 2, 4, NULL, S_PISTOL4, 0, 0 }, // S_PISTOL3 + { SPR_PISG, 1, 5, A_ReFire, S_PISTOL, 0, 0 }, // S_PISTOL4 + { SPR_PISF, 32768, 7, A_Light1, S_LIGHTDONE, 0, 0 }, // S_PISTOLFLASH + { SPR_SHTG, 0, 1, A_WeaponReady, S_SGUN, 0, 0 }, // S_SGUN + { SPR_SHTG, 0, 1, A_Lower, S_SGUNDOWN, 0, 0 }, // S_SGUNDOWN + { SPR_SHTG, 0, 1, A_Raise, S_SGUNUP, 0, 0 }, // S_SGUNUP + { SPR_SHTG, 0, 3, NULL, S_SGUN2, 0, 0 }, // S_SGUN1 + { SPR_SHTG, 0, 7, A_FireShotgun, S_SGUN3, 0, 0 }, // S_SGUN2 + { SPR_SHTG, 1, 5, NULL, S_SGUN4, 0, 0 }, // S_SGUN3 + { SPR_SHTG, 2, 5, NULL, S_SGUN5, 0, 0 }, // S_SGUN4 + { SPR_SHTG, 3, 4, NULL, S_SGUN6, 0, 0 }, // S_SGUN5 + { SPR_SHTG, 2, 5, NULL, S_SGUN7, 0, 0 }, // S_SGUN6 + { SPR_SHTG, 1, 5, NULL, S_SGUN8, 0, 0 }, // S_SGUN7 + { SPR_SHTG, 0, 3, NULL, S_SGUN9, 0, 0 }, // S_SGUN8 + { SPR_SHTG, 0, 7, A_ReFire, S_SGUN, 0, 0 }, // S_SGUN9 + { SPR_SHTF, 32768, 4, A_Light1, S_SGUNFLASH2, 0, 0 }, // S_SGUNFLASH1 + { SPR_SHTF, 32769, 3, A_Light2, S_LIGHTDONE, 0, 0 }, // S_SGUNFLASH2 + { SPR_SHT2, 0, 1, A_WeaponReady, S_DSGUN, 0, 0 }, // S_DSGUN + { SPR_SHT2, 0, 1, A_Lower, S_DSGUNDOWN, 0, 0 }, // S_DSGUNDOWN + { SPR_SHT2, 0, 1, A_Raise, S_DSGUNUP, 0, 0 }, // S_DSGUNUP + { SPR_SHT2, 0, 3, NULL, S_DSGUN2, 0, 0 }, // S_DSGUN1 + { SPR_SHT2, 0, 7, A_FireShotgun2, S_DSGUN3, 0, 0 }, // S_DSGUN2 + { SPR_SHT2, 1, 7, NULL, S_DSGUN4, 0, 0 }, // S_DSGUN3 + { SPR_SHT2, 2, 7, A_CheckReload, S_DSGUN5, 0, 0 }, // S_DSGUN4 + { SPR_SHT2, 3, 7, A_OpenShotgun2, S_DSGUN6, 0, 0 }, // S_DSGUN5 + { SPR_SHT2, 4, 7, NULL, S_DSGUN7, 0, 0 }, // S_DSGUN6 + { SPR_SHT2, 5, 7, A_LoadShotgun2, S_DSGUN8, 0, 0 }, // S_DSGUN7 + { SPR_SHT2, 6, 6, NULL, S_DSGUN9, 0, 0 }, // S_DSGUN8 + { SPR_SHT2, 7, 6, A_CloseShotgun2, S_DSGUN10, 0, 0 }, // S_DSGUN9 + { SPR_SHT2, 0, 5, A_ReFire, S_DSGUN, 0, 0 }, // S_DSGUN10 + { SPR_SHT2, 1, 7, NULL, S_DSNR2, 0, 0 }, // S_DSNR1 + { SPR_SHT2, 0, 3, NULL, S_DSGUNDOWN, 0, 0 }, // S_DSNR2 + { SPR_SHT2, 32776, 5, A_Light1, S_DSGUNFLASH2, 0, 0 }, // S_DSGUNFLASH1 + { SPR_SHT2, 32777, 4, A_Light2, S_LIGHTDONE, 0, 0 }, // S_DSGUNFLASH2 + { SPR_CHGG, 0, 1, A_WeaponReady, S_CHAIN, 0, 0 }, // S_CHAIN + { SPR_CHGG, 0, 1, A_Lower, S_CHAINDOWN, 0, 0 }, // S_CHAINDOWN + { SPR_CHGG, 0, 1, A_Raise, S_CHAINUP, 0, 0 }, // S_CHAINUP + { SPR_CHGG, 0, 4, A_FireCGun, S_CHAIN2, 0, 0 }, // S_CHAIN1 + { SPR_CHGG, 1, 4, A_FireCGun, S_CHAIN3, 0, 0 }, // S_CHAIN2 + { SPR_CHGG, 1, 0, A_ReFire, S_CHAIN, 0, 0 }, // S_CHAIN3 + { SPR_CHGF, 32768, 5, A_Light1, S_LIGHTDONE, 0, 0 }, // S_CHAINFLASH1 + { SPR_CHGF, 32769, 5, A_Light2, S_LIGHTDONE, 0, 0 }, // S_CHAINFLASH2 + { SPR_MISG, 0, 1, A_WeaponReady, S_MISSILE, 0, 0 }, // S_MISSILE + { SPR_MISG, 0, 1, A_Lower, S_MISSILEDOWN, 0, 0 }, // S_MISSILEDOWN + { SPR_MISG, 0, 1, A_Raise, S_MISSILEUP, 0, 0 }, // S_MISSILEUP + { SPR_MISG, 1, 8, A_GunFlash, S_MISSILE2, 0, 0 }, // S_MISSILE1 + { SPR_MISG, 1, 12, A_FireMissile, S_MISSILE3, 0, 0 }, // S_MISSILE2 + { SPR_MISG, 1, 0, A_ReFire, S_MISSILE, 0, 0 }, // S_MISSILE3 + { SPR_MISF, 32768, 3, A_Light1, S_MISSILEFLASH2, 0, 0 }, // S_MISSILEFLASH1 + { SPR_MISF, 32769, 4, NULL, S_MISSILEFLASH3, 0, 0 }, // S_MISSILEFLASH2 + { SPR_MISF, 32770, 4, A_Light2, S_MISSILEFLASH4, 0, 0 }, // S_MISSILEFLASH3 + { SPR_MISF, 32771, 4, A_Light2, S_LIGHTDONE, 0, 0 }, // S_MISSILEFLASH4 + { SPR_SAWG, 2, 4, A_WeaponReady, S_SAWB, 0, 0 }, // S_SAW + { SPR_SAWG, 3, 4, A_WeaponReady, S_SAW, 0, 0 }, // S_SAWB + { SPR_SAWG, 2, 1, A_Lower, S_SAWDOWN, 0, 0 }, // S_SAWDOWN + { SPR_SAWG, 2, 1, A_Raise, S_SAWUP, 0, 0 }, // S_SAWUP + { SPR_SAWG, 0, 4, A_Saw, S_SAW2, 0, 0 }, // S_SAW1 + { SPR_SAWG, 1, 4, A_Saw, S_SAW3, 0, 0 }, // S_SAW2 + { SPR_SAWG, 1, 0, A_ReFire, S_SAW, 0, 0 }, // S_SAW3 + { SPR_PLSG, 0, 1, A_WeaponReady, S_PLASMA, 0, 0 }, // S_PLASMA + { SPR_PLSG, 0, 1, A_Lower, S_PLASMADOWN, 0, 0 }, // S_PLASMADOWN + { SPR_PLSG, 0, 1, A_Raise, S_PLASMAUP, 0, 0 }, // S_PLASMAUP + { SPR_PLSG, 0, 3, A_FirePlasma, S_PLASMA2, 0, 0 }, // S_PLASMA1 + { SPR_PLSG, 1, 20, A_ReFire, S_PLASMA, 0, 0 }, // S_PLASMA2 + { SPR_PLSF, 32768, 4, A_Light1, S_LIGHTDONE, 0, 0 }, // S_PLASMAFLASH1 + { SPR_PLSF, 32769, 4, A_Light1, S_LIGHTDONE, 0, 0 }, // S_PLASMAFLASH2 + { SPR_BFGG, 0, 1, A_WeaponReady, S_BFG, 0, 0 }, // S_BFG + { SPR_BFGG, 0, 1, A_Lower, S_BFGDOWN, 0, 0 }, // S_BFGDOWN + { SPR_BFGG, 0, 1, A_Raise, S_BFGUP, 0, 0 }, // S_BFGUP + { SPR_BFGG, 0, 20, A_BFGsound, S_BFG2, 0, 0 }, // S_BFG1 + { SPR_BFGG, 1, 10, A_GunFlash, S_BFG3, 0, 0 }, // S_BFG2 + { SPR_BFGG, 1, 10, A_FireBFG, S_BFG4, 0, 0 }, // S_BFG3 + { SPR_BFGG, 1, 20, A_ReFire, S_BFG, 0, 0 }, // S_BFG4 + { SPR_BFGF, 32768, 11, A_Light1, S_BFGFLASH2, 0, 0 }, // S_BFGFLASH1 + { SPR_BFGF, 32769, 6, A_Light2, S_LIGHTDONE, 0, 0 }, // S_BFGFLASH2 + { SPR_BLUD, 2, 8, NULL, S_BLOOD2, 0, 0 }, // S_BLOOD1 + { SPR_BLUD, 1, 8, NULL, S_BLOOD3, 0, 0 }, // S_BLOOD2 + { SPR_BLUD, 0, 8, NULL, S_NULL, 0, 0 }, // S_BLOOD3 + { SPR_PUFF, 32768, 4, NULL, S_PUFF2, 0, 0 }, // S_PUFF1 + { SPR_PUFF, 1, 4, NULL, S_PUFF3, 0, 0 }, // S_PUFF2 + { SPR_PUFF, 2, 4, NULL, S_PUFF4, 0, 0 }, // S_PUFF3 + { SPR_PUFF, 3, 4, NULL, S_NULL, 0, 0 }, // S_PUFF4 + { SPR_BAL1, 32768, 4, NULL, S_TBALL2, 0, 0 }, // S_TBALL1 + { SPR_BAL1, 32769, 4, NULL, S_TBALL1, 0, 0 }, // S_TBALL2 + { SPR_BAL1, 32770, 6, NULL, S_TBALLX2, 0, 0 }, // S_TBALLX1 + { SPR_BAL1, 32771, 6, NULL, S_TBALLX3, 0, 0 }, // S_TBALLX2 + { SPR_BAL1, 32772, 6, NULL, S_NULL, 0, 0 }, // S_TBALLX3 + { SPR_BAL2, 32768, 4, NULL, S_RBALL2, 0, 0 }, // S_RBALL1 + { SPR_BAL2, 32769, 4, NULL, S_RBALL1, 0, 0 }, // S_RBALL2 + { SPR_BAL2, 32770, 6, NULL, S_RBALLX2, 0, 0 }, // S_RBALLX1 + { SPR_BAL2, 32771, 6, NULL, S_RBALLX3, 0, 0 }, // S_RBALLX2 + { SPR_BAL2, 32772, 6, NULL, S_NULL, 0, 0 }, // S_RBALLX3 + { SPR_PLSS, 32768, 6, NULL, S_PLASBALL2, 0, 0 }, // S_PLASBALL + { SPR_PLSS, 32769, 6, NULL, S_PLASBALL, 0, 0 }, // S_PLASBALL2 + { SPR_PLSE, 32768, 4, NULL, S_PLASEXP2, 0, 0 }, // S_PLASEXP + { SPR_PLSE, 32769, 4, NULL, S_PLASEXP3, 0, 0 }, // S_PLASEXP2 + { SPR_PLSE, 32770, 4, NULL, S_PLASEXP4, 0, 0 }, // S_PLASEXP3 + { SPR_PLSE, 32771, 4, NULL, S_PLASEXP5, 0, 0 }, // S_PLASEXP4 + { SPR_PLSE, 32772, 4, NULL, S_NULL, 0, 0 }, // S_PLASEXP5 + { SPR_MISL, 32768, 1, NULL, S_ROCKET, 0, 0 }, // S_ROCKET + { SPR_BFS1, 32768, 4, NULL, S_BFGSHOT2, 0, 0 }, // S_BFGSHOT + { SPR_BFS1, 32769, 4, NULL, S_BFGSHOT, 0, 0 }, // S_BFGSHOT2 + { SPR_BFE1, 32768, 8, NULL, S_BFGLAND2, 0, 0 }, // S_BFGLAND + { SPR_BFE1, 32769, 8, NULL, S_BFGLAND3, 0, 0 }, // S_BFGLAND2 + { SPR_BFE1, 32770, 8, A_BFGSpray, S_BFGLAND4, 0, 0 }, // S_BFGLAND3 + { SPR_BFE1, 32771, 8, NULL, S_BFGLAND5, 0, 0 }, // S_BFGLAND4 + { SPR_BFE1, 32772, 8, NULL, S_BFGLAND6, 0, 0 }, // S_BFGLAND5 + { SPR_BFE1, 32773, 8, NULL, S_NULL, 0, 0 }, // S_BFGLAND6 + { SPR_BFE2, 32768, 8, NULL, S_BFGEXP2, 0, 0 }, // S_BFGEXP + { SPR_BFE2, 32769, 8, NULL, S_BFGEXP3, 0, 0 }, // S_BFGEXP2 + { SPR_BFE2, 32770, 8, NULL, S_BFGEXP4, 0, 0 }, // S_BFGEXP3 + { SPR_BFE2, 32771, 8, NULL, S_NULL, 0, 0 }, // S_BFGEXP4 + { SPR_MISL, 32769, 8, A_Explode, S_EXPLODE2, 0, 0 }, // S_EXPLODE1 + { SPR_MISL, 32770, 6, NULL, S_EXPLODE3, 0, 0 }, // S_EXPLODE2 + { SPR_MISL, 32771, 4, NULL, S_NULL, 0, 0 }, // S_EXPLODE3 + { SPR_TFOG, 32768, 6, NULL, S_TFOG01, 0, 0 }, // S_TFOG + { SPR_TFOG, 32769, 6, NULL, S_TFOG02, 0, 0 }, // S_TFOG01 + { SPR_TFOG, 32768, 6, NULL, S_TFOG2, 0, 0 }, // S_TFOG02 + { SPR_TFOG, 32769, 6, NULL, S_TFOG3, 0, 0 }, // S_TFOG2 + { SPR_TFOG, 32770, 6, NULL, S_TFOG4, 0, 0 }, // S_TFOG3 + { SPR_TFOG, 32771, 6, NULL, S_TFOG5, 0, 0 }, // S_TFOG4 + { SPR_TFOG, 32772, 6, NULL, S_TFOG6, 0, 0 }, // S_TFOG5 + { SPR_TFOG, 32773, 6, NULL, S_TFOG7, 0, 0 }, // S_TFOG6 + { SPR_TFOG, 32774, 6, NULL, S_TFOG8, 0, 0 }, // S_TFOG7 + { SPR_TFOG, 32775, 6, NULL, S_TFOG9, 0, 0 }, // S_TFOG8 + { SPR_TFOG, 32776, 6, NULL, S_TFOG10, 0, 0 }, // S_TFOG9 + { SPR_TFOG, 32777, 6, NULL, S_NULL, 0, 0 }, // S_TFOG10 + { SPR_IFOG, 32768, 6, NULL, S_IFOG01, 0, 0 }, // S_IFOG + { SPR_IFOG, 32769, 6, NULL, S_IFOG02, 0, 0 }, // S_IFOG01 + { SPR_IFOG, 32768, 6, NULL, S_IFOG2, 0, 0 }, // S_IFOG02 + { SPR_IFOG, 32769, 6, NULL, S_IFOG3, 0, 0 }, // S_IFOG2 + { SPR_IFOG, 32770, 6, NULL, S_IFOG4, 0, 0 }, // S_IFOG3 + { SPR_IFOG, 32771, 6, NULL, S_IFOG5, 0, 0 }, // S_IFOG4 + { SPR_IFOG, 32772, 6, NULL, S_NULL, 0, 0 }, // S_IFOG5 + { SPR_PLAY, 0, -1, NULL, S_NULL, 0, 0 }, // S_PLAY + { SPR_PLAY, 0, 4, NULL, S_PLAY_RUN2, 0, 0 }, // S_PLAY_RUN1 + { SPR_PLAY, 1, 4, NULL, S_PLAY_RUN3, 0, 0 }, // S_PLAY_RUN2 + { SPR_PLAY, 2, 4, NULL, S_PLAY_RUN4, 0, 0 }, // S_PLAY_RUN3 + { SPR_PLAY, 3, 4, NULL, S_PLAY_RUN1, 0, 0 }, // S_PLAY_RUN4 + { SPR_PLAY, 4, 12, NULL, S_PLAY, 0, 0 }, // S_PLAY_ATK1 + { SPR_PLAY, 32773, 6, NULL, S_PLAY_ATK1, 0, 0 }, // S_PLAY_ATK2 + { SPR_PLAY, 6, 4, NULL, S_PLAY_PAIN2, 0, 0 }, // S_PLAY_PAIN + { SPR_PLAY, 6, 4, A_Pain, S_PLAY, 0, 0 }, // S_PLAY_PAIN2 + { SPR_PLAY, 7, 10, NULL, S_PLAY_DIE2, 0, 0 }, // S_PLAY_DIE1 + { SPR_PLAY, 8, 10, A_PlayerScream, S_PLAY_DIE3, 0, 0 }, // S_PLAY_DIE2 + { SPR_PLAY, 9, 10, A_Fall, S_PLAY_DIE4, 0, 0 }, // S_PLAY_DIE3 + { SPR_PLAY, 10, 10, NULL, S_PLAY_DIE5, 0, 0 }, // S_PLAY_DIE4 + { SPR_PLAY, 11, 10, NULL, S_PLAY_DIE6, 0, 0 }, // S_PLAY_DIE5 + { SPR_PLAY, 12, 10, NULL, S_PLAY_DIE7, 0, 0 }, // S_PLAY_DIE6 + { SPR_PLAY, 13, -1, NULL, S_NULL, 0, 0 }, // S_PLAY_DIE7 + { SPR_PLAY, 14, 5, NULL, S_PLAY_XDIE2, 0, 0 }, // S_PLAY_XDIE1 + { SPR_PLAY, 15, 5, A_XScream, S_PLAY_XDIE3, 0, 0 }, // S_PLAY_XDIE2 + { SPR_PLAY, 16, 5, A_Fall, S_PLAY_XDIE4, 0, 0 }, // S_PLAY_XDIE3 + { SPR_PLAY, 17, 5, NULL, S_PLAY_XDIE5, 0, 0 }, // S_PLAY_XDIE4 + { SPR_PLAY, 18, 5, NULL, S_PLAY_XDIE6, 0, 0 }, // S_PLAY_XDIE5 + { SPR_PLAY, 19, 5, NULL, S_PLAY_XDIE7, 0, 0 }, // S_PLAY_XDIE6 + { SPR_PLAY, 20, 5, NULL, S_PLAY_XDIE8, 0, 0 }, // S_PLAY_XDIE7 + { SPR_PLAY, 21, 5, NULL, S_PLAY_XDIE9, 0, 0 }, // S_PLAY_XDIE8 + { SPR_PLAY, 22, -1, NULL, S_NULL, 0, 0 }, // S_PLAY_XDIE9 + { SPR_POSS, 0, 10, A_Look, S_POSS_STND2, 0, 0 }, // S_POSS_STND + { SPR_POSS, 1, 10, A_Look, S_POSS_STND, 0, 0 }, // S_POSS_STND2 + { SPR_POSS, 0, 4, A_Chase, S_POSS_RUN2, 0, 0 }, // S_POSS_RUN1 + { SPR_POSS, 0, 4, A_Chase, S_POSS_RUN3, 0, 0 }, // S_POSS_RUN2 + { SPR_POSS, 1, 4, A_Chase, S_POSS_RUN4, 0, 0 }, // S_POSS_RUN3 + { SPR_POSS, 1, 4, A_Chase, S_POSS_RUN5, 0, 0 }, // S_POSS_RUN4 + { SPR_POSS, 2, 4, A_Chase, S_POSS_RUN6, 0, 0 }, // S_POSS_RUN5 + { SPR_POSS, 2, 4, A_Chase, S_POSS_RUN7, 0, 0 }, // S_POSS_RUN6 + { SPR_POSS, 3, 4, A_Chase, S_POSS_RUN8, 0, 0 }, // S_POSS_RUN7 + { SPR_POSS, 3, 4, A_Chase, S_POSS_RUN1, 0, 0 }, // S_POSS_RUN8 + { SPR_POSS, 4, 10, A_FaceTarget, S_POSS_ATK2, 0, 0 }, // S_POSS_ATK1 + { SPR_POSS, 5, 8, A_PosAttack, S_POSS_ATK3, 0, 0 }, // S_POSS_ATK2 + { SPR_POSS, 4, 8, NULL, S_POSS_RUN1, 0, 0 }, // S_POSS_ATK3 + { SPR_POSS, 6, 3, NULL, S_POSS_PAIN2, 0, 0 }, // S_POSS_PAIN + { SPR_POSS, 6, 3, A_Pain, S_POSS_RUN1, 0, 0 }, // S_POSS_PAIN2 + { SPR_POSS, 7, 5, NULL, S_POSS_DIE2, 0, 0 }, // S_POSS_DIE1 + { SPR_POSS, 8, 5, A_Scream, S_POSS_DIE3, 0, 0 }, // S_POSS_DIE2 + { SPR_POSS, 9, 5, A_Fall, S_POSS_DIE4, 0, 0 }, // S_POSS_DIE3 + { SPR_POSS, 10, 5, NULL, S_POSS_DIE5, 0, 0 }, // S_POSS_DIE4 + { SPR_POSS, 11, -1, NULL, S_NULL, 0, 0 }, // S_POSS_DIE5 + { SPR_POSS, 12, 5, NULL, S_POSS_XDIE2, 0, 0 }, // S_POSS_XDIE1 + { SPR_POSS, 13, 5, A_XScream, S_POSS_XDIE3, 0, 0 }, // S_POSS_XDIE2 + { SPR_POSS, 14, 5, A_Fall, S_POSS_XDIE4, 0, 0 }, // S_POSS_XDIE3 + { SPR_POSS, 15, 5, NULL, S_POSS_XDIE5, 0, 0 }, // S_POSS_XDIE4 + { SPR_POSS, 16, 5, NULL, S_POSS_XDIE6, 0, 0 }, // S_POSS_XDIE5 + { SPR_POSS, 17, 5, NULL, S_POSS_XDIE7, 0, 0 }, // S_POSS_XDIE6 + { SPR_POSS, 18, 5, NULL, S_POSS_XDIE8, 0, 0 }, // S_POSS_XDIE7 + { SPR_POSS, 19, 5, NULL, S_POSS_XDIE9, 0, 0 }, // S_POSS_XDIE8 + { SPR_POSS, 20, -1, NULL, S_NULL, 0, 0 }, // S_POSS_XDIE9 + { SPR_POSS, 10, 5, NULL, S_POSS_RAISE2, 0, 0 }, // S_POSS_RAISE1 + { SPR_POSS, 9, 5, NULL, S_POSS_RAISE3, 0, 0 }, // S_POSS_RAISE2 + { SPR_POSS, 8, 5, NULL, S_POSS_RAISE4, 0, 0 }, // S_POSS_RAISE3 + { SPR_POSS, 7, 5, NULL, S_POSS_RUN1, 0, 0 }, // S_POSS_RAISE4 + { SPR_SPOS, 0, 10, A_Look, S_SPOS_STND2, 0, 0 }, // S_SPOS_STND + { SPR_SPOS, 1, 10, A_Look, S_SPOS_STND, 0, 0 }, // S_SPOS_STND2 + { SPR_SPOS, 0, 3, A_Chase, S_SPOS_RUN2, 0, 0 }, // S_SPOS_RUN1 + { SPR_SPOS, 0, 3, A_Chase, S_SPOS_RUN3, 0, 0 }, // S_SPOS_RUN2 + { SPR_SPOS, 1, 3, A_Chase, S_SPOS_RUN4, 0, 0 }, // S_SPOS_RUN3 + { SPR_SPOS, 1, 3, A_Chase, S_SPOS_RUN5, 0, 0 }, // S_SPOS_RUN4 + { SPR_SPOS, 2, 3, A_Chase, S_SPOS_RUN6, 0, 0 }, // S_SPOS_RUN5 + { SPR_SPOS, 2, 3, A_Chase, S_SPOS_RUN7, 0, 0 }, // S_SPOS_RUN6 + { SPR_SPOS, 3, 3, A_Chase, S_SPOS_RUN8, 0, 0 }, // S_SPOS_RUN7 + { SPR_SPOS, 3, 3, A_Chase, S_SPOS_RUN1, 0, 0 }, // S_SPOS_RUN8 + { SPR_SPOS, 4, 10, A_FaceTarget, S_SPOS_ATK2, 0, 0 }, // S_SPOS_ATK1 + { SPR_SPOS, 32773, 10, A_SPosAttack, S_SPOS_ATK3, 0, 0 }, // S_SPOS_ATK2 + { SPR_SPOS, 4, 10, NULL, S_SPOS_RUN1, 0, 0 }, // S_SPOS_ATK3 + { SPR_SPOS, 6, 3, NULL, S_SPOS_PAIN2, 0, 0 }, // S_SPOS_PAIN + { SPR_SPOS, 6, 3, A_Pain, S_SPOS_RUN1, 0, 0 }, // S_SPOS_PAIN2 + { SPR_SPOS, 7, 5, NULL, S_SPOS_DIE2, 0, 0 }, // S_SPOS_DIE1 + { SPR_SPOS, 8, 5, A_Scream, S_SPOS_DIE3, 0, 0 }, // S_SPOS_DIE2 + { SPR_SPOS, 9, 5, A_Fall, S_SPOS_DIE4, 0, 0 }, // S_SPOS_DIE3 + { SPR_SPOS, 10, 5, NULL, S_SPOS_DIE5, 0, 0 }, // S_SPOS_DIE4 + { SPR_SPOS, 11, -1, NULL, S_NULL, 0, 0 }, // S_SPOS_DIE5 + { SPR_SPOS, 12, 5, NULL, S_SPOS_XDIE2, 0, 0 }, // S_SPOS_XDIE1 + { SPR_SPOS, 13, 5, A_XScream, S_SPOS_XDIE3, 0, 0 }, // S_SPOS_XDIE2 + { SPR_SPOS, 14, 5, A_Fall, S_SPOS_XDIE4, 0, 0 }, // S_SPOS_XDIE3 + { SPR_SPOS, 15, 5, NULL, S_SPOS_XDIE5, 0, 0 }, // S_SPOS_XDIE4 + { SPR_SPOS, 16, 5, NULL, S_SPOS_XDIE6, 0, 0 }, // S_SPOS_XDIE5 + { SPR_SPOS, 17, 5, NULL, S_SPOS_XDIE7, 0, 0 }, // S_SPOS_XDIE6 + { SPR_SPOS, 18, 5, NULL, S_SPOS_XDIE8, 0, 0 }, // S_SPOS_XDIE7 + { SPR_SPOS, 19, 5, NULL, S_SPOS_XDIE9, 0, 0 }, // S_SPOS_XDIE8 + { SPR_SPOS, 20, -1, NULL, S_NULL, 0, 0 }, // S_SPOS_XDIE9 + { SPR_SPOS, 11, 5, NULL, S_SPOS_RAISE2, 0, 0 }, // S_SPOS_RAISE1 + { SPR_SPOS, 10, 5, NULL, S_SPOS_RAISE3, 0, 0 }, // S_SPOS_RAISE2 + { SPR_SPOS, 9, 5, NULL, S_SPOS_RAISE4, 0, 0 }, // S_SPOS_RAISE3 + { SPR_SPOS, 8, 5, NULL, S_SPOS_RAISE5, 0, 0 }, // S_SPOS_RAISE4 + { SPR_SPOS, 7, 5, NULL, S_SPOS_RUN1, 0, 0 }, // S_SPOS_RAISE5 + { SPR_VILE, 0, 10, A_Look, S_VILE_STND2, 0, 0 }, // S_VILE_STND + { SPR_VILE, 1, 10, A_Look, S_VILE_STND, 0, 0 }, // S_VILE_STND2 + { SPR_VILE, 0, 2, A_VileChase, S_VILE_RUN2, 0, 0 }, // S_VILE_RUN1 + { SPR_VILE, 0, 2, A_VileChase, S_VILE_RUN3, 0, 0 }, // S_VILE_RUN2 + { SPR_VILE, 1, 2, A_VileChase, S_VILE_RUN4, 0, 0 }, // S_VILE_RUN3 + { SPR_VILE, 1, 2, A_VileChase, S_VILE_RUN5, 0, 0 }, // S_VILE_RUN4 + { SPR_VILE, 2, 2, A_VileChase, S_VILE_RUN6, 0, 0 }, // S_VILE_RUN5 + { SPR_VILE, 2, 2, A_VileChase, S_VILE_RUN7, 0, 0 }, // S_VILE_RUN6 + { SPR_VILE, 3, 2, A_VileChase, S_VILE_RUN8, 0, 0 }, // S_VILE_RUN7 + { SPR_VILE, 3, 2, A_VileChase, S_VILE_RUN9, 0, 0 }, // S_VILE_RUN8 + { SPR_VILE, 4, 2, A_VileChase, S_VILE_RUN10, 0, 0 }, // S_VILE_RUN9 + { SPR_VILE, 4, 2, A_VileChase, S_VILE_RUN11, 0, 0 }, // S_VILE_RUN10 + { SPR_VILE, 5, 2, A_VileChase, S_VILE_RUN12, 0, 0 }, // S_VILE_RUN11 + { SPR_VILE, 5, 2, A_VileChase, S_VILE_RUN1, 0, 0 }, // S_VILE_RUN12 + { SPR_VILE, 32774, 0, A_VileStart, S_VILE_ATK2, 0, 0 }, // S_VILE_ATK1 + { SPR_VILE, 32774, 10, A_FaceTarget, S_VILE_ATK3, 0, 0 }, // S_VILE_ATK2 + { SPR_VILE, 32775, 8, A_VileTarget, S_VILE_ATK4, 0, 0 }, // S_VILE_ATK3 + { SPR_VILE, 32776, 8, A_FaceTarget, S_VILE_ATK5, 0, 0 }, // S_VILE_ATK4 + { SPR_VILE, 32777, 8, A_FaceTarget, S_VILE_ATK6, 0, 0 }, // S_VILE_ATK5 + { SPR_VILE, 32778, 8, A_FaceTarget, S_VILE_ATK7, 0, 0 }, // S_VILE_ATK6 + { SPR_VILE, 32779, 8, A_FaceTarget, S_VILE_ATK8, 0, 0 }, // S_VILE_ATK7 + { SPR_VILE, 32780, 8, A_FaceTarget, S_VILE_ATK9, 0, 0 }, // S_VILE_ATK8 + { SPR_VILE, 32781, 8, A_FaceTarget, S_VILE_ATK10, 0, 0 }, // S_VILE_ATK9 + { SPR_VILE, 32782, 8, A_VileAttack, S_VILE_ATK11, 0, 0 }, // S_VILE_ATK10 + { SPR_VILE, 32783, 20, NULL, S_VILE_RUN1, 0, 0 }, // S_VILE_ATK11 + { SPR_VILE, 32794, 10, NULL, S_VILE_HEAL2, 0, 0 }, // S_VILE_HEAL1 + { SPR_VILE, 32795, 10, NULL, S_VILE_HEAL3, 0, 0 }, // S_VILE_HEAL2 + { SPR_VILE, 32796, 10, NULL, S_VILE_RUN1, 0, 0 }, // S_VILE_HEAL3 + { SPR_VILE, 16, 5, NULL, S_VILE_PAIN2, 0, 0 }, // S_VILE_PAIN + { SPR_VILE, 16, 5, A_Pain, S_VILE_RUN1, 0, 0 }, // S_VILE_PAIN2 + { SPR_VILE, 16, 7, NULL, S_VILE_DIE2, 0, 0 }, // S_VILE_DIE1 + { SPR_VILE, 17, 7, A_Scream, S_VILE_DIE3, 0, 0 }, // S_VILE_DIE2 + { SPR_VILE, 18, 7, A_Fall, S_VILE_DIE4, 0, 0 }, // S_VILE_DIE3 + { SPR_VILE, 19, 7, NULL, S_VILE_DIE5, 0, 0 }, // S_VILE_DIE4 + { SPR_VILE, 20, 7, NULL, S_VILE_DIE6, 0, 0 }, // S_VILE_DIE5 + { SPR_VILE, 21, 7, NULL, S_VILE_DIE7, 0, 0 }, // S_VILE_DIE6 + { SPR_VILE, 22, 7, NULL, S_VILE_DIE8, 0, 0 }, // S_VILE_DIE7 + { SPR_VILE, 23, 5, NULL, S_VILE_DIE9, 0, 0 }, // S_VILE_DIE8 + { SPR_VILE, 24, 5, NULL, S_VILE_DIE10, 0, 0 }, // S_VILE_DIE9 + { SPR_VILE, 25, -1, NULL, S_NULL, 0, 0 }, // S_VILE_DIE10 + { SPR_FIRE, 32768, 2, A_StartFire, S_FIRE2, 0, 0 }, // S_FIRE1 + { SPR_FIRE, 32769, 2, A_Fire, S_FIRE3, 0, 0 }, // S_FIRE2 + { SPR_FIRE, 32768, 2, A_Fire, S_FIRE4, 0, 0 }, // S_FIRE3 + { SPR_FIRE, 32769, 2, A_Fire, S_FIRE5, 0, 0 }, // S_FIRE4 + { SPR_FIRE, 32770, 2, A_FireCrackle, S_FIRE6, 0, 0 }, // S_FIRE5 + { SPR_FIRE, 32769, 2, A_Fire, S_FIRE7, 0, 0 }, // S_FIRE6 + { SPR_FIRE, 32770, 2, A_Fire, S_FIRE8, 0, 0 }, // S_FIRE7 + { SPR_FIRE, 32769, 2, A_Fire, S_FIRE9, 0, 0 }, // S_FIRE8 + { SPR_FIRE, 32770, 2, A_Fire, S_FIRE10, 0, 0 }, // S_FIRE9 + { SPR_FIRE, 32771, 2, A_Fire, S_FIRE11, 0, 0 }, // S_FIRE10 + { SPR_FIRE, 32770, 2, A_Fire, S_FIRE12, 0, 0 }, // S_FIRE11 + { SPR_FIRE, 32771, 2, A_Fire, S_FIRE13, 0, 0 }, // S_FIRE12 + { SPR_FIRE, 32770, 2, A_Fire, S_FIRE14, 0, 0 }, // S_FIRE13 + { SPR_FIRE, 32771, 2, A_Fire, S_FIRE15, 0, 0 }, // S_FIRE14 + { SPR_FIRE, 32772, 2, A_Fire, S_FIRE16, 0, 0 }, // S_FIRE15 + { SPR_FIRE, 32771, 2, A_Fire, S_FIRE17, 0, 0 }, // S_FIRE16 + { SPR_FIRE, 32772, 2, A_Fire, S_FIRE18, 0, 0 }, // S_FIRE17 + { SPR_FIRE, 32771, 2, A_Fire, S_FIRE19, 0, 0 }, // S_FIRE18 + { SPR_FIRE, 32772, 2, A_FireCrackle, S_FIRE20, 0, 0 }, // S_FIRE19 + { SPR_FIRE, 32773, 2, A_Fire, S_FIRE21, 0, 0 }, // S_FIRE20 + { SPR_FIRE, 32772, 2, A_Fire, S_FIRE22, 0, 0 }, // S_FIRE21 + { SPR_FIRE, 32773, 2, A_Fire, S_FIRE23, 0, 0 }, // S_FIRE22 + { SPR_FIRE, 32772, 2, A_Fire, S_FIRE24, 0, 0 }, // S_FIRE23 + { SPR_FIRE, 32773, 2, A_Fire, S_FIRE25, 0, 0 }, // S_FIRE24 + { SPR_FIRE, 32774, 2, A_Fire, S_FIRE26, 0, 0 }, // S_FIRE25 + { SPR_FIRE, 32775, 2, A_Fire, S_FIRE27, 0, 0 }, // S_FIRE26 + { SPR_FIRE, 32774, 2, A_Fire, S_FIRE28, 0, 0 }, // S_FIRE27 + { SPR_FIRE, 32775, 2, A_Fire, S_FIRE29, 0, 0 }, // S_FIRE28 + { SPR_FIRE, 32774, 2, A_Fire, S_FIRE30, 0, 0 }, // S_FIRE29 + { SPR_FIRE, 32775, 2, A_Fire, S_NULL, 0, 0 }, // S_FIRE30 + { SPR_PUFF, 1, 4, NULL, S_SMOKE2, 0, 0 }, // S_SMOKE1 + { SPR_PUFF, 2, 4, NULL, S_SMOKE3, 0, 0 }, // S_SMOKE2 + { SPR_PUFF, 1, 4, NULL, S_SMOKE4, 0, 0 }, // S_SMOKE3 + { SPR_PUFF, 2, 4, NULL, S_SMOKE5, 0, 0 }, // S_SMOKE4 + { SPR_PUFF, 3, 4, NULL, S_NULL, 0, 0 }, // S_SMOKE5 + { SPR_FATB, 32768, 2, A_Tracer, S_TRACER2, 0, 0 }, // S_TRACER + { SPR_FATB, 32769, 2, A_Tracer, S_TRACER, 0, 0 }, // S_TRACER2 + { SPR_FBXP, 32768, 8, NULL, S_TRACEEXP2, 0, 0 }, // S_TRACEEXP1 + { SPR_FBXP, 32769, 6, NULL, S_TRACEEXP3, 0, 0 }, // S_TRACEEXP2 + { SPR_FBXP, 32770, 4, NULL, S_NULL, 0, 0 }, // S_TRACEEXP3 + { SPR_SKEL, 0, 10, A_Look, S_SKEL_STND2, 0, 0 }, // S_SKEL_STND + { SPR_SKEL, 1, 10, A_Look, S_SKEL_STND, 0, 0 }, // S_SKEL_STND2 + { SPR_SKEL, 0, 2, A_Chase, S_SKEL_RUN2, 0, 0 }, // S_SKEL_RUN1 + { SPR_SKEL, 0, 2, A_Chase, S_SKEL_RUN3, 0, 0 }, // S_SKEL_RUN2 + { SPR_SKEL, 1, 2, A_Chase, S_SKEL_RUN4, 0, 0 }, // S_SKEL_RUN3 + { SPR_SKEL, 1, 2, A_Chase, S_SKEL_RUN5, 0, 0 }, // S_SKEL_RUN4 + { SPR_SKEL, 2, 2, A_Chase, S_SKEL_RUN6, 0, 0 }, // S_SKEL_RUN5 + { SPR_SKEL, 2, 2, A_Chase, S_SKEL_RUN7, 0, 0 }, // S_SKEL_RUN6 + { SPR_SKEL, 3, 2, A_Chase, S_SKEL_RUN8, 0, 0 }, // S_SKEL_RUN7 + { SPR_SKEL, 3, 2, A_Chase, S_SKEL_RUN9, 0, 0 }, // S_SKEL_RUN8 + { SPR_SKEL, 4, 2, A_Chase, S_SKEL_RUN10, 0, 0 }, // S_SKEL_RUN9 + { SPR_SKEL, 4, 2, A_Chase, S_SKEL_RUN11, 0, 0 }, // S_SKEL_RUN10 + { SPR_SKEL, 5, 2, A_Chase, S_SKEL_RUN12, 0, 0 }, // S_SKEL_RUN11 + { SPR_SKEL, 5, 2, A_Chase, S_SKEL_RUN1, 0, 0 }, // S_SKEL_RUN12 + { SPR_SKEL, 6, 0, A_FaceTarget, S_SKEL_FIST2, 0, 0 }, // S_SKEL_FIST1 + { SPR_SKEL, 6, 6, A_SkelWhoosh, S_SKEL_FIST3, 0, 0 }, // S_SKEL_FIST2 + { SPR_SKEL, 7, 6, A_FaceTarget, S_SKEL_FIST4, 0, 0 }, // S_SKEL_FIST3 + { SPR_SKEL, 8, 6, A_SkelFist, S_SKEL_RUN1, 0, 0 }, // S_SKEL_FIST4 + { SPR_SKEL, 32777, 0, A_FaceTarget, S_SKEL_MISS2, 0, 0 }, // S_SKEL_MISS1 + { SPR_SKEL, 32777, 10, A_FaceTarget, S_SKEL_MISS3, 0, 0 }, // S_SKEL_MISS2 + { SPR_SKEL, 10, 10, A_SkelMissile, S_SKEL_MISS4, 0, 0 }, // S_SKEL_MISS3 + { SPR_SKEL, 10, 10, A_FaceTarget, S_SKEL_RUN1, 0, 0 }, // S_SKEL_MISS4 + { SPR_SKEL, 11, 5, NULL, S_SKEL_PAIN2, 0, 0 }, // S_SKEL_PAIN + { SPR_SKEL, 11, 5, A_Pain, S_SKEL_RUN1, 0, 0 }, // S_SKEL_PAIN2 + { SPR_SKEL, 11, 7, NULL, S_SKEL_DIE2, 0, 0 }, // S_SKEL_DIE1 + { SPR_SKEL, 12, 7, NULL, S_SKEL_DIE3, 0, 0 }, // S_SKEL_DIE2 + { SPR_SKEL, 13, 7, A_Scream, S_SKEL_DIE4, 0, 0 }, // S_SKEL_DIE3 + { SPR_SKEL, 14, 7, A_Fall, S_SKEL_DIE5, 0, 0 }, // S_SKEL_DIE4 + { SPR_SKEL, 15, 7, NULL, S_SKEL_DIE6, 0, 0 }, // S_SKEL_DIE5 + { SPR_SKEL, 16, -1, NULL, S_NULL, 0, 0 }, // S_SKEL_DIE6 + { SPR_SKEL, 16, 5, NULL, S_SKEL_RAISE2, 0, 0 }, // S_SKEL_RAISE1 + { SPR_SKEL, 15, 5, NULL, S_SKEL_RAISE3, 0, 0 }, // S_SKEL_RAISE2 + { SPR_SKEL, 14, 5, NULL, S_SKEL_RAISE4, 0, 0 }, // S_SKEL_RAISE3 + { SPR_SKEL, 13, 5, NULL, S_SKEL_RAISE5, 0, 0 }, // S_SKEL_RAISE4 + { SPR_SKEL, 12, 5, NULL, S_SKEL_RAISE6, 0, 0 }, // S_SKEL_RAISE5 + { SPR_SKEL, 11, 5, NULL, S_SKEL_RUN1, 0, 0 }, // S_SKEL_RAISE6 + { SPR_MANF, 32768, 4, NULL, S_FATSHOT2, 0, 0 }, // S_FATSHOT1 + { SPR_MANF, 32769, 4, NULL, S_FATSHOT1, 0, 0 }, // S_FATSHOT2 + { SPR_MISL, 32769, 8, NULL, S_FATSHOTX2, 0, 0 }, // S_FATSHOTX1 + { SPR_MISL, 32770, 6, NULL, S_FATSHOTX3, 0, 0 }, // S_FATSHOTX2 + { SPR_MISL, 32771, 4, NULL, S_NULL, 0, 0 }, // S_FATSHOTX3 + { SPR_FATT, 0, 15, A_Look, S_FATT_STND2, 0, 0 }, // S_FATT_STND + { SPR_FATT, 1, 15, A_Look, S_FATT_STND, 0, 0 }, // S_FATT_STND2 + { SPR_FATT, 0, 4, A_Chase, S_FATT_RUN2, 0, 0 }, // S_FATT_RUN1 + { SPR_FATT, 0, 4, A_Chase, S_FATT_RUN3, 0, 0 }, // S_FATT_RUN2 + { SPR_FATT, 1, 4, A_Chase, S_FATT_RUN4, 0, 0 }, // S_FATT_RUN3 + { SPR_FATT, 1, 4, A_Chase, S_FATT_RUN5, 0, 0 }, // S_FATT_RUN4 + { SPR_FATT, 2, 4, A_Chase, S_FATT_RUN6, 0, 0 }, // S_FATT_RUN5 + { SPR_FATT, 2, 4, A_Chase, S_FATT_RUN7, 0, 0 }, // S_FATT_RUN6 + { SPR_FATT, 3, 4, A_Chase, S_FATT_RUN8, 0, 0 }, // S_FATT_RUN7 + { SPR_FATT, 3, 4, A_Chase, S_FATT_RUN9, 0, 0 }, // S_FATT_RUN8 + { SPR_FATT, 4, 4, A_Chase, S_FATT_RUN10, 0, 0 }, // S_FATT_RUN9 + { SPR_FATT, 4, 4, A_Chase, S_FATT_RUN11, 0, 0 }, // S_FATT_RUN10 + { SPR_FATT, 5, 4, A_Chase, S_FATT_RUN12, 0, 0 }, // S_FATT_RUN11 + { SPR_FATT, 5, 4, A_Chase, S_FATT_RUN1, 0, 0 }, // S_FATT_RUN12 + { SPR_FATT, 6, 20, A_FatRaise, S_FATT_ATK2, 0, 0 }, // S_FATT_ATK1 + { SPR_FATT, 32775, 10, A_FatAttack1, S_FATT_ATK3, 0, 0 }, // S_FATT_ATK2 + { SPR_FATT, 8, 5, A_FaceTarget, S_FATT_ATK4, 0, 0 }, // S_FATT_ATK3 + { SPR_FATT, 6, 5, A_FaceTarget, S_FATT_ATK5, 0, 0 }, // S_FATT_ATK4 + { SPR_FATT, 32775, 10, A_FatAttack2, S_FATT_ATK6, 0, 0 }, // S_FATT_ATK5 + { SPR_FATT, 8, 5, A_FaceTarget, S_FATT_ATK7, 0, 0 }, // S_FATT_ATK6 + { SPR_FATT, 6, 5, A_FaceTarget, S_FATT_ATK8, 0, 0 }, // S_FATT_ATK7 + { SPR_FATT, 32775, 10, A_FatAttack3, S_FATT_ATK9, 0, 0 }, // S_FATT_ATK8 + { SPR_FATT, 8, 5, A_FaceTarget, S_FATT_ATK10, 0, 0 }, // S_FATT_ATK9 + { SPR_FATT, 6, 5, A_FaceTarget, S_FATT_RUN1, 0, 0 }, // S_FATT_ATK10 + { SPR_FATT, 9, 3, NULL, S_FATT_PAIN2, 0, 0 }, // S_FATT_PAIN + { SPR_FATT, 9, 3, A_Pain, S_FATT_RUN1, 0, 0 }, // S_FATT_PAIN2 + { SPR_FATT, 10, 6, NULL, S_FATT_DIE2, 0, 0 }, // S_FATT_DIE1 + { SPR_FATT, 11, 6, A_Scream, S_FATT_DIE3, 0, 0 }, // S_FATT_DIE2 + { SPR_FATT, 12, 6, A_Fall, S_FATT_DIE4, 0, 0 }, // S_FATT_DIE3 + { SPR_FATT, 13, 6, NULL, S_FATT_DIE5, 0, 0 }, // S_FATT_DIE4 + { SPR_FATT, 14, 6, NULL, S_FATT_DIE6, 0, 0 }, // S_FATT_DIE5 + { SPR_FATT, 15, 6, NULL, S_FATT_DIE7, 0, 0 }, // S_FATT_DIE6 + { SPR_FATT, 16, 6, NULL, S_FATT_DIE8, 0, 0 }, // S_FATT_DIE7 + { SPR_FATT, 17, 6, NULL, S_FATT_DIE9, 0, 0 }, // S_FATT_DIE8 + { SPR_FATT, 18, 6, NULL, S_FATT_DIE10, 0, 0 }, // S_FATT_DIE9 + { SPR_FATT, 19, -1, A_BossDeath, S_NULL, 0, 0 }, // S_FATT_DIE10 + { SPR_FATT, 17, 5, NULL, S_FATT_RAISE2, 0, 0 }, // S_FATT_RAISE1 + { SPR_FATT, 16, 5, NULL, S_FATT_RAISE3, 0, 0 }, // S_FATT_RAISE2 + { SPR_FATT, 15, 5, NULL, S_FATT_RAISE4, 0, 0 }, // S_FATT_RAISE3 + { SPR_FATT, 14, 5, NULL, S_FATT_RAISE5, 0, 0 }, // S_FATT_RAISE4 + { SPR_FATT, 13, 5, NULL, S_FATT_RAISE6, 0, 0 }, // S_FATT_RAISE5 + { SPR_FATT, 12, 5, NULL, S_FATT_RAISE7, 0, 0 }, // S_FATT_RAISE6 + { SPR_FATT, 11, 5, NULL, S_FATT_RAISE8, 0, 0 }, // S_FATT_RAISE7 + { SPR_FATT, 10, 5, NULL, S_FATT_RUN1, 0, 0 }, // S_FATT_RAISE8 + { SPR_CPOS, 0, 10, A_Look, S_CPOS_STND2, 0, 0 }, // S_CPOS_STND + { SPR_CPOS, 1, 10, A_Look, S_CPOS_STND, 0, 0 }, // S_CPOS_STND2 + { SPR_CPOS, 0, 3, A_Chase, S_CPOS_RUN2, 0, 0 }, // S_CPOS_RUN1 + { SPR_CPOS, 0, 3, A_Chase, S_CPOS_RUN3, 0, 0 }, // S_CPOS_RUN2 + { SPR_CPOS, 1, 3, A_Chase, S_CPOS_RUN4, 0, 0 }, // S_CPOS_RUN3 + { SPR_CPOS, 1, 3, A_Chase, S_CPOS_RUN5, 0, 0 }, // S_CPOS_RUN4 + { SPR_CPOS, 2, 3, A_Chase, S_CPOS_RUN6, 0, 0 }, // S_CPOS_RUN5 + { SPR_CPOS, 2, 3, A_Chase, S_CPOS_RUN7, 0, 0 }, // S_CPOS_RUN6 + { SPR_CPOS, 3, 3, A_Chase, S_CPOS_RUN8, 0, 0 }, // S_CPOS_RUN7 + { SPR_CPOS, 3, 3, A_Chase, S_CPOS_RUN1, 0, 0 }, // S_CPOS_RUN8 + { SPR_CPOS, 4, 10, A_FaceTarget, S_CPOS_ATK2, 0, 0 }, // S_CPOS_ATK1 + { SPR_CPOS, 32773, 4, A_CPosAttack, S_CPOS_ATK3, 0, 0 }, // S_CPOS_ATK2 + { SPR_CPOS, 32772, 4, A_CPosAttack, S_CPOS_ATK4, 0, 0 }, // S_CPOS_ATK3 + { SPR_CPOS, 5, 1, A_CPosRefire, S_CPOS_ATK2, 0, 0 }, // S_CPOS_ATK4 + { SPR_CPOS, 6, 3, NULL, S_CPOS_PAIN2, 0, 0 }, // S_CPOS_PAIN + { SPR_CPOS, 6, 3, A_Pain, S_CPOS_RUN1, 0, 0 }, // S_CPOS_PAIN2 + { SPR_CPOS, 7, 5, NULL, S_CPOS_DIE2, 0, 0 }, // S_CPOS_DIE1 + { SPR_CPOS, 8, 5, A_Scream, S_CPOS_DIE3, 0, 0 }, // S_CPOS_DIE2 + { SPR_CPOS, 9, 5, A_Fall, S_CPOS_DIE4, 0, 0 }, // S_CPOS_DIE3 + { SPR_CPOS, 10, 5, NULL, S_CPOS_DIE5, 0, 0 }, // S_CPOS_DIE4 + { SPR_CPOS, 11, 5, NULL, S_CPOS_DIE6, 0, 0 }, // S_CPOS_DIE5 + { SPR_CPOS, 12, 5, NULL, S_CPOS_DIE7, 0, 0 }, // S_CPOS_DIE6 + { SPR_CPOS, 13, -1, NULL, S_NULL, 0, 0 }, // S_CPOS_DIE7 + { SPR_CPOS, 14, 5, NULL, S_CPOS_XDIE2, 0, 0 }, // S_CPOS_XDIE1 + { SPR_CPOS, 15, 5, A_XScream, S_CPOS_XDIE3, 0, 0 }, // S_CPOS_XDIE2 + { SPR_CPOS, 16, 5, A_Fall, S_CPOS_XDIE4, 0, 0 }, // S_CPOS_XDIE3 + { SPR_CPOS, 17, 5, NULL, S_CPOS_XDIE5, 0, 0 }, // S_CPOS_XDIE4 + { SPR_CPOS, 18, 5, NULL, S_CPOS_XDIE6, 0, 0 }, // S_CPOS_XDIE5 + { SPR_CPOS, 19, -1, NULL, S_NULL, 0, 0 }, // S_CPOS_XDIE6 + { SPR_CPOS, 13, 5, NULL, S_CPOS_RAISE2, 0, 0 }, // S_CPOS_RAISE1 + { SPR_CPOS, 12, 5, NULL, S_CPOS_RAISE3, 0, 0 }, // S_CPOS_RAISE2 + { SPR_CPOS, 11, 5, NULL, S_CPOS_RAISE4, 0, 0 }, // S_CPOS_RAISE3 + { SPR_CPOS, 10, 5, NULL, S_CPOS_RAISE5, 0, 0 }, // S_CPOS_RAISE4 + { SPR_CPOS, 9, 5, NULL, S_CPOS_RAISE6, 0, 0 }, // S_CPOS_RAISE5 + { SPR_CPOS, 8, 5, NULL, S_CPOS_RAISE7, 0, 0 }, // S_CPOS_RAISE6 + { SPR_CPOS, 7, 5, NULL, S_CPOS_RUN1, 0, 0 }, // S_CPOS_RAISE7 + { SPR_TROO, 0, 10, A_Look, S_TROO_STND2, 0, 0 }, // S_TROO_STND + { SPR_TROO, 1, 10, A_Look, S_TROO_STND, 0, 0 }, // S_TROO_STND2 + { SPR_TROO, 0, 3, A_Chase, S_TROO_RUN2, 0, 0 }, // S_TROO_RUN1 + { SPR_TROO, 0, 3, A_Chase, S_TROO_RUN3, 0, 0 }, // S_TROO_RUN2 + { SPR_TROO, 1, 3, A_Chase, S_TROO_RUN4, 0, 0 }, // S_TROO_RUN3 + { SPR_TROO, 1, 3, A_Chase, S_TROO_RUN5, 0, 0 }, // S_TROO_RUN4 + { SPR_TROO, 2, 3, A_Chase, S_TROO_RUN6, 0, 0 }, // S_TROO_RUN5 + { SPR_TROO, 2, 3, A_Chase, S_TROO_RUN7, 0, 0 }, // S_TROO_RUN6 + { SPR_TROO, 3, 3, A_Chase, S_TROO_RUN8, 0, 0 }, // S_TROO_RUN7 + { SPR_TROO, 3, 3, A_Chase, S_TROO_RUN1, 0, 0 }, // S_TROO_RUN8 + { SPR_TROO, 4, 8, A_FaceTarget, S_TROO_ATK2, 0, 0 }, // S_TROO_ATK1 + { SPR_TROO, 5, 8, A_FaceTarget, S_TROO_ATK3, 0, 0 }, // S_TROO_ATK2 + { SPR_TROO, 6, 6, A_TroopAttack, S_TROO_RUN1, 0, 0 }, // S_TROO_ATK3 + { SPR_TROO, 7, 2, NULL, S_TROO_PAIN2, 0, 0 }, // S_TROO_PAIN + { SPR_TROO, 7, 2, A_Pain, S_TROO_RUN1, 0, 0 }, // S_TROO_PAIN2 + { SPR_TROO, 8, 8, NULL, S_TROO_DIE2, 0, 0 }, // S_TROO_DIE1 + { SPR_TROO, 9, 8, A_Scream, S_TROO_DIE3, 0, 0 }, // S_TROO_DIE2 + { SPR_TROO, 10, 6, NULL, S_TROO_DIE4, 0, 0 }, // S_TROO_DIE3 + { SPR_TROO, 11, 6, A_Fall, S_TROO_DIE5, 0, 0 }, // S_TROO_DIE4 + { SPR_TROO, 12, -1, NULL, S_NULL, 0, 0 }, // S_TROO_DIE5 + { SPR_TROO, 13, 5, NULL, S_TROO_XDIE2, 0, 0 }, // S_TROO_XDIE1 + { SPR_TROO, 14, 5, A_XScream, S_TROO_XDIE3, 0, 0 }, // S_TROO_XDIE2 + { SPR_TROO, 15, 5, NULL, S_TROO_XDIE4, 0, 0 }, // S_TROO_XDIE3 + { SPR_TROO, 16, 5, A_Fall, S_TROO_XDIE5, 0, 0 }, // S_TROO_XDIE4 + { SPR_TROO, 17, 5, NULL, S_TROO_XDIE6, 0, 0 }, // S_TROO_XDIE5 + { SPR_TROO, 18, 5, NULL, S_TROO_XDIE7, 0, 0 }, // S_TROO_XDIE6 + { SPR_TROO, 19, 5, NULL, S_TROO_XDIE8, 0, 0 }, // S_TROO_XDIE7 + { SPR_TROO, 20, -1, NULL, S_NULL, 0, 0 }, // S_TROO_XDIE8 + { SPR_TROO, 12, 8, NULL, S_TROO_RAISE2, 0, 0 }, // S_TROO_RAISE1 + { SPR_TROO, 11, 8, NULL, S_TROO_RAISE3, 0, 0 }, // S_TROO_RAISE2 + { SPR_TROO, 10, 6, NULL, S_TROO_RAISE4, 0, 0 }, // S_TROO_RAISE3 + { SPR_TROO, 9, 6, NULL, S_TROO_RAISE5, 0, 0 }, // S_TROO_RAISE4 + { SPR_TROO, 8, 6, NULL, S_TROO_RUN1, 0, 0 }, // S_TROO_RAISE5 + { SPR_SARG, 0, 10, A_Look, S_SARG_STND2, 0, 0 }, // S_SARG_STND + { SPR_SARG, 1, 10, A_Look, S_SARG_STND, 0, 0 }, // S_SARG_STND2 + { SPR_SARG, 0, 2, A_Chase, S_SARG_RUN2, 0, 0 }, // S_SARG_RUN1 + { SPR_SARG, 0, 2, A_Chase, S_SARG_RUN3, 0, 0 }, // S_SARG_RUN2 + { SPR_SARG, 1, 2, A_Chase, S_SARG_RUN4, 0, 0 }, // S_SARG_RUN3 + { SPR_SARG, 1, 2, A_Chase, S_SARG_RUN5, 0, 0 }, // S_SARG_RUN4 + { SPR_SARG, 2, 2, A_Chase, S_SARG_RUN6, 0, 0 }, // S_SARG_RUN5 + { SPR_SARG, 2, 2, A_Chase, S_SARG_RUN7, 0, 0 }, // S_SARG_RUN6 + { SPR_SARG, 3, 2, A_Chase, S_SARG_RUN8, 0, 0 }, // S_SARG_RUN7 + { SPR_SARG, 3, 2, A_Chase, S_SARG_RUN1, 0, 0 }, // S_SARG_RUN8 + { SPR_SARG, 4, 8, A_FaceTarget, S_SARG_ATK2, 0, 0 }, // S_SARG_ATK1 + { SPR_SARG, 5, 8, A_FaceTarget, S_SARG_ATK3, 0, 0 }, // S_SARG_ATK2 + { SPR_SARG, 6, 8, A_SargAttack, S_SARG_RUN1, 0, 0 }, // S_SARG_ATK3 + { SPR_SARG, 7, 2, NULL, S_SARG_PAIN2, 0, 0 }, // S_SARG_PAIN + { SPR_SARG, 7, 2, A_Pain, S_SARG_RUN1, 0, 0 }, // S_SARG_PAIN2 + { SPR_SARG, 8, 8, NULL, S_SARG_DIE2, 0, 0 }, // S_SARG_DIE1 + { SPR_SARG, 9, 8, A_Scream, S_SARG_DIE3, 0, 0 }, // S_SARG_DIE2 + { SPR_SARG, 10, 4, NULL, S_SARG_DIE4, 0, 0 }, // S_SARG_DIE3 + { SPR_SARG, 11, 4, A_Fall, S_SARG_DIE5, 0, 0 }, // S_SARG_DIE4 + { SPR_SARG, 12, 4, NULL, S_SARG_DIE6, 0, 0 }, // S_SARG_DIE5 + { SPR_SARG, 13, -1, NULL, S_NULL, 0, 0 }, // S_SARG_DIE6 + { SPR_SARG, 13, 5, NULL, S_SARG_RAISE2, 0, 0 }, // S_SARG_RAISE1 + { SPR_SARG, 12, 5, NULL, S_SARG_RAISE3, 0, 0 }, // S_SARG_RAISE2 + { SPR_SARG, 11, 5, NULL, S_SARG_RAISE4, 0, 0 }, // S_SARG_RAISE3 + { SPR_SARG, 10, 5, NULL, S_SARG_RAISE5, 0, 0 }, // S_SARG_RAISE4 + { SPR_SARG, 9, 5, NULL, S_SARG_RAISE6, 0, 0 }, // S_SARG_RAISE5 + { SPR_SARG, 8, 5, NULL, S_SARG_RUN1, 0, 0 }, // S_SARG_RAISE6 + { SPR_HEAD, 0, 10, A_Look, S_HEAD_STND, 0, 0 }, // S_HEAD_STND + { SPR_HEAD, 0, 3, A_Chase, S_HEAD_RUN1, 0, 0 }, // S_HEAD_RUN1 + { SPR_HEAD, 1, 5, A_FaceTarget, S_HEAD_ATK2, 0, 0 }, // S_HEAD_ATK1 + { SPR_HEAD, 2, 5, A_FaceTarget, S_HEAD_ATK3, 0, 0 }, // S_HEAD_ATK2 + { SPR_HEAD, 32771, 5, A_HeadAttack, S_HEAD_RUN1, 0, 0 }, // S_HEAD_ATK3 + { SPR_HEAD, 4, 3, NULL, S_HEAD_PAIN2, 0, 0 }, // S_HEAD_PAIN + { SPR_HEAD, 4, 3, A_Pain, S_HEAD_PAIN3, 0, 0 }, // S_HEAD_PAIN2 + { SPR_HEAD, 5, 6, NULL, S_HEAD_RUN1, 0, 0 }, // S_HEAD_PAIN3 + { SPR_HEAD, 6, 8, NULL, S_HEAD_DIE2, 0, 0 }, // S_HEAD_DIE1 + { SPR_HEAD, 7, 8, A_Scream, S_HEAD_DIE3, 0, 0 }, // S_HEAD_DIE2 + { SPR_HEAD, 8, 8, NULL, S_HEAD_DIE4, 0, 0 }, // S_HEAD_DIE3 + { SPR_HEAD, 9, 8, NULL, S_HEAD_DIE5, 0, 0 }, // S_HEAD_DIE4 + { SPR_HEAD, 10, 8, A_Fall, S_HEAD_DIE6, 0, 0 }, // S_HEAD_DIE5 + { SPR_HEAD, 11, -1, NULL, S_NULL, 0, 0 }, // S_HEAD_DIE6 + { SPR_HEAD, 11, 8, NULL, S_HEAD_RAISE2, 0, 0 }, // S_HEAD_RAISE1 + { SPR_HEAD, 10, 8, NULL, S_HEAD_RAISE3, 0, 0 }, // S_HEAD_RAISE2 + { SPR_HEAD, 9, 8, NULL, S_HEAD_RAISE4, 0, 0 }, // S_HEAD_RAISE3 + { SPR_HEAD, 8, 8, NULL, S_HEAD_RAISE5, 0, 0 }, // S_HEAD_RAISE4 + { SPR_HEAD, 7, 8, NULL, S_HEAD_RAISE6, 0, 0 }, // S_HEAD_RAISE5 + { SPR_HEAD, 6, 8, NULL, S_HEAD_RUN1, 0, 0 }, // S_HEAD_RAISE6 + { SPR_BAL7, 32768, 4, NULL, S_BRBALL2, 0, 0 }, // S_BRBALL1 + { SPR_BAL7, 32769, 4, NULL, S_BRBALL1, 0, 0 }, // S_BRBALL2 + { SPR_BAL7, 32770, 6, NULL, S_BRBALLX2, 0, 0 }, // S_BRBALLX1 + { SPR_BAL7, 32771, 6, NULL, S_BRBALLX3, 0, 0 }, // S_BRBALLX2 + { SPR_BAL7, 32772, 6, NULL, S_NULL, 0, 0 }, // S_BRBALLX3 + { SPR_BOSS, 0, 10, A_Look, S_BOSS_STND2, 0, 0 }, // S_BOSS_STND + { SPR_BOSS, 1, 10, A_Look, S_BOSS_STND, 0, 0 }, // S_BOSS_STND2 + { SPR_BOSS, 0, 3, A_Chase, S_BOSS_RUN2, 0, 0 }, // S_BOSS_RUN1 + { SPR_BOSS, 0, 3, A_Chase, S_BOSS_RUN3, 0, 0 }, // S_BOSS_RUN2 + { SPR_BOSS, 1, 3, A_Chase, S_BOSS_RUN4, 0, 0 }, // S_BOSS_RUN3 + { SPR_BOSS, 1, 3, A_Chase, S_BOSS_RUN5, 0, 0 }, // S_BOSS_RUN4 + { SPR_BOSS, 2, 3, A_Chase, S_BOSS_RUN6, 0, 0 }, // S_BOSS_RUN5 + { SPR_BOSS, 2, 3, A_Chase, S_BOSS_RUN7, 0, 0 }, // S_BOSS_RUN6 + { SPR_BOSS, 3, 3, A_Chase, S_BOSS_RUN8, 0, 0 }, // S_BOSS_RUN7 + { SPR_BOSS, 3, 3, A_Chase, S_BOSS_RUN1, 0, 0 }, // S_BOSS_RUN8 + { SPR_BOSS, 4, 8, A_FaceTarget, S_BOSS_ATK2, 0, 0 }, // S_BOSS_ATK1 + { SPR_BOSS, 5, 8, A_FaceTarget, S_BOSS_ATK3, 0, 0 }, // S_BOSS_ATK2 + { SPR_BOSS, 6, 8, A_BruisAttack, S_BOSS_RUN1, 0, 0 }, // S_BOSS_ATK3 + { SPR_BOSS, 7, 2, NULL, S_BOSS_PAIN2, 0, 0 }, // S_BOSS_PAIN + { SPR_BOSS, 7, 2, A_Pain, S_BOSS_RUN1, 0, 0 }, // S_BOSS_PAIN2 + { SPR_BOSS, 8, 8, NULL, S_BOSS_DIE2, 0, 0 }, // S_BOSS_DIE1 + { SPR_BOSS, 9, 8, A_Scream, S_BOSS_DIE3, 0, 0 }, // S_BOSS_DIE2 + { SPR_BOSS, 10, 8, NULL, S_BOSS_DIE4, 0, 0 }, // S_BOSS_DIE3 + { SPR_BOSS, 11, 8, A_Fall, S_BOSS_DIE5, 0, 0 }, // S_BOSS_DIE4 + { SPR_BOSS, 12, 8, NULL, S_BOSS_DIE6, 0, 0 }, // S_BOSS_DIE5 + { SPR_BOSS, 13, 8, NULL, S_BOSS_DIE7, 0, 0 }, // S_BOSS_DIE6 + { SPR_BOSS, 14, -1, A_BossDeath, S_NULL, 0, 0 }, // S_BOSS_DIE7 + { SPR_BOSS, 14, 8, NULL, S_BOSS_RAISE2, 0, 0 }, // S_BOSS_RAISE1 + { SPR_BOSS, 13, 8, NULL, S_BOSS_RAISE3, 0, 0 }, // S_BOSS_RAISE2 + { SPR_BOSS, 12, 8, NULL, S_BOSS_RAISE4, 0, 0 }, // S_BOSS_RAISE3 + { SPR_BOSS, 11, 8, NULL, S_BOSS_RAISE5, 0, 0 }, // S_BOSS_RAISE4 + { SPR_BOSS, 10, 8, NULL, S_BOSS_RAISE6, 0, 0 }, // S_BOSS_RAISE5 + { SPR_BOSS, 9, 8, NULL, S_BOSS_RAISE7, 0, 0 }, // S_BOSS_RAISE6 + { SPR_BOSS, 8, 8, NULL, S_BOSS_RUN1, 0, 0 }, // S_BOSS_RAISE7 + { SPR_BOS2, 0, 10, A_Look, S_BOS2_STND2, 0, 0 }, // S_BOS2_STND + { SPR_BOS2, 1, 10, A_Look, S_BOS2_STND, 0, 0 }, // S_BOS2_STND2 + { SPR_BOS2, 0, 3, A_Chase, S_BOS2_RUN2, 0, 0 }, // S_BOS2_RUN1 + { SPR_BOS2, 0, 3, A_Chase, S_BOS2_RUN3, 0, 0 }, // S_BOS2_RUN2 + { SPR_BOS2, 1, 3, A_Chase, S_BOS2_RUN4, 0, 0 }, // S_BOS2_RUN3 + { SPR_BOS2, 1, 3, A_Chase, S_BOS2_RUN5, 0, 0 }, // S_BOS2_RUN4 + { SPR_BOS2, 2, 3, A_Chase, S_BOS2_RUN6, 0, 0 }, // S_BOS2_RUN5 + { SPR_BOS2, 2, 3, A_Chase, S_BOS2_RUN7, 0, 0 }, // S_BOS2_RUN6 + { SPR_BOS2, 3, 3, A_Chase, S_BOS2_RUN8, 0, 0 }, // S_BOS2_RUN7 + { SPR_BOS2, 3, 3, A_Chase, S_BOS2_RUN1, 0, 0 }, // S_BOS2_RUN8 + { SPR_BOS2, 4, 8, A_FaceTarget, S_BOS2_ATK2, 0, 0 }, // S_BOS2_ATK1 + { SPR_BOS2, 5, 8, A_FaceTarget, S_BOS2_ATK3, 0, 0 }, // S_BOS2_ATK2 + { SPR_BOS2, 6, 8, A_BruisAttack, S_BOS2_RUN1, 0, 0 }, // S_BOS2_ATK3 + { SPR_BOS2, 7, 2, NULL, S_BOS2_PAIN2, 0, 0 }, // S_BOS2_PAIN + { SPR_BOS2, 7, 2, A_Pain, S_BOS2_RUN1, 0, 0 }, // S_BOS2_PAIN2 + { SPR_BOS2, 8, 8, NULL, S_BOS2_DIE2, 0, 0 }, // S_BOS2_DIE1 + { SPR_BOS2, 9, 8, A_Scream, S_BOS2_DIE3, 0, 0 }, // S_BOS2_DIE2 + { SPR_BOS2, 10, 8, NULL, S_BOS2_DIE4, 0, 0 }, // S_BOS2_DIE3 + { SPR_BOS2, 11, 8, A_Fall, S_BOS2_DIE5, 0, 0 }, // S_BOS2_DIE4 + { SPR_BOS2, 12, 8, NULL, S_BOS2_DIE6, 0, 0 }, // S_BOS2_DIE5 + { SPR_BOS2, 13, 8, NULL, S_BOS2_DIE7, 0, 0 }, // S_BOS2_DIE6 + { SPR_BOS2, 14, -1, NULL, S_NULL, 0, 0 }, // S_BOS2_DIE7 + { SPR_BOS2, 14, 8, NULL, S_BOS2_RAISE2, 0, 0 }, // S_BOS2_RAISE1 + { SPR_BOS2, 13, 8, NULL, S_BOS2_RAISE3, 0, 0 }, // S_BOS2_RAISE2 + { SPR_BOS2, 12, 8, NULL, S_BOS2_RAISE4, 0, 0 }, // S_BOS2_RAISE3 + { SPR_BOS2, 11, 8, NULL, S_BOS2_RAISE5, 0, 0 }, // S_BOS2_RAISE4 + { SPR_BOS2, 10, 8, NULL, S_BOS2_RAISE6, 0, 0 }, // S_BOS2_RAISE5 + { SPR_BOS2, 9, 8, NULL, S_BOS2_RAISE7, 0, 0 }, // S_BOS2_RAISE6 + { SPR_BOS2, 8, 8, NULL, S_BOS2_RUN1, 0, 0 }, // S_BOS2_RAISE7 + { SPR_SKUL, 32768, 10, A_Look, S_SKULL_STND2, 0, 0 }, // S_SKULL_STND + { SPR_SKUL, 32769, 10, A_Look, S_SKULL_STND, 0, 0 }, // S_SKULL_STND2 + { SPR_SKUL, 32768, 6, A_Chase, S_SKULL_RUN2, 0, 0 }, // S_SKULL_RUN1 + { SPR_SKUL, 32769, 6, A_Chase, S_SKULL_RUN1, 0, 0 }, // S_SKULL_RUN2 + { SPR_SKUL, 32770, 10, A_FaceTarget, S_SKULL_ATK2, 0, 0 }, // S_SKULL_ATK1 + { SPR_SKUL, 32771, 4, A_SkullAttack, S_SKULL_ATK3, 0, 0 }, // S_SKULL_ATK2 + { SPR_SKUL, 32770, 4, NULL, S_SKULL_ATK4, 0, 0 }, // S_SKULL_ATK3 + { SPR_SKUL, 32771, 4, NULL, S_SKULL_ATK3, 0, 0 }, // S_SKULL_ATK4 + { SPR_SKUL, 32772, 3, NULL, S_SKULL_PAIN2, 0, 0 }, // S_SKULL_PAIN + { SPR_SKUL, 32772, 3, A_Pain, S_SKULL_RUN1, 0, 0 }, // S_SKULL_PAIN2 + { SPR_SKUL, 32773, 6, NULL, S_SKULL_DIE2, 0, 0 }, // S_SKULL_DIE1 + { SPR_SKUL, 32774, 6, A_Scream, S_SKULL_DIE3, 0, 0 }, // S_SKULL_DIE2 + { SPR_SKUL, 32775, 6, NULL, S_SKULL_DIE4, 0, 0 }, // S_SKULL_DIE3 + { SPR_SKUL, 32776, 6, A_Fall, S_SKULL_DIE5, 0, 0 }, // S_SKULL_DIE4 + { SPR_SKUL, 9, 6, NULL, S_SKULL_DIE6, 0, 0 }, // S_SKULL_DIE5 + { SPR_SKUL, 10, 6, NULL, S_NULL, 0, 0 }, // S_SKULL_DIE6 + { SPR_SPID, 0, 10, A_Look, S_SPID_STND2, 0, 0 }, // S_SPID_STND + { SPR_SPID, 1, 10, A_Look, S_SPID_STND, 0, 0 }, // S_SPID_STND2 + { SPR_SPID, 0, 3, A_Metal, S_SPID_RUN2, 0, 0 }, // S_SPID_RUN1 + { SPR_SPID, 0, 3, A_Chase, S_SPID_RUN3, 0, 0 }, // S_SPID_RUN2 + { SPR_SPID, 1, 3, A_Chase, S_SPID_RUN4, 0, 0 }, // S_SPID_RUN3 + { SPR_SPID, 1, 3, A_Chase, S_SPID_RUN5, 0, 0 }, // S_SPID_RUN4 + { SPR_SPID, 2, 3, A_Metal, S_SPID_RUN6, 0, 0 }, // S_SPID_RUN5 + { SPR_SPID, 2, 3, A_Chase, S_SPID_RUN7, 0, 0 }, // S_SPID_RUN6 + { SPR_SPID, 3, 3, A_Chase, S_SPID_RUN8, 0, 0 }, // S_SPID_RUN7 + { SPR_SPID, 3, 3, A_Chase, S_SPID_RUN9, 0, 0 }, // S_SPID_RUN8 + { SPR_SPID, 4, 3, A_Metal, S_SPID_RUN10, 0, 0 }, // S_SPID_RUN9 + { SPR_SPID, 4, 3, A_Chase, S_SPID_RUN11, 0, 0 }, // S_SPID_RUN10 + { SPR_SPID, 5, 3, A_Chase, S_SPID_RUN12, 0, 0 }, // S_SPID_RUN11 + { SPR_SPID, 5, 3, A_Chase, S_SPID_RUN1, 0, 0 }, // S_SPID_RUN12 + { SPR_SPID, 32768, 20, A_FaceTarget, S_SPID_ATK2, 0, 0 }, // S_SPID_ATK1 + { SPR_SPID, 32774, 4, A_SPosAttack, S_SPID_ATK3, 0, 0 }, // S_SPID_ATK2 + { SPR_SPID, 32775, 4, A_SPosAttack, S_SPID_ATK4, 0, 0 }, // S_SPID_ATK3 + { SPR_SPID, 32775, 1, A_SpidRefire, S_SPID_ATK2, 0, 0 }, // S_SPID_ATK4 + { SPR_SPID, 8, 3, NULL, S_SPID_PAIN2, 0, 0 }, // S_SPID_PAIN + { SPR_SPID, 8, 3, A_Pain, S_SPID_RUN1, 0, 0 }, // S_SPID_PAIN2 + { SPR_SPID, 9, 20, A_Scream, S_SPID_DIE2, 0, 0 }, // S_SPID_DIE1 + { SPR_SPID, 10, 10, A_Fall, S_SPID_DIE3, 0, 0 }, // S_SPID_DIE2 + { SPR_SPID, 11, 10, NULL, S_SPID_DIE4, 0, 0 }, // S_SPID_DIE3 + { SPR_SPID, 12, 10, NULL, S_SPID_DIE5, 0, 0 }, // S_SPID_DIE4 + { SPR_SPID, 13, 10, NULL, S_SPID_DIE6, 0, 0 }, // S_SPID_DIE5 + { SPR_SPID, 14, 10, NULL, S_SPID_DIE7, 0, 0 }, // S_SPID_DIE6 + { SPR_SPID, 15, 10, NULL, S_SPID_DIE8, 0, 0 }, // S_SPID_DIE7 + { SPR_SPID, 16, 10, NULL, S_SPID_DIE9, 0, 0 }, // S_SPID_DIE8 + { SPR_SPID, 17, 10, NULL, S_SPID_DIE10, 0, 0 }, // S_SPID_DIE9 + { SPR_SPID, 18, 30, NULL, S_SPID_DIE11, 0, 0 }, // S_SPID_DIE10 + { SPR_SPID, 18, -1, A_BossDeath, S_NULL, 0, 0 }, // S_SPID_DIE11 + { SPR_BSPI, 0, 10, A_Look, S_BSPI_STND2, 0, 0 }, // S_BSPI_STND + { SPR_BSPI, 1, 10, A_Look, S_BSPI_STND, 0, 0 }, // S_BSPI_STND2 + { SPR_BSPI, 0, 20, NULL, S_BSPI_RUN1, 0, 0 }, // S_BSPI_SIGHT + { SPR_BSPI, 0, 3, A_BabyMetal, S_BSPI_RUN2, 0, 0 }, // S_BSPI_RUN1 + { SPR_BSPI, 0, 3, A_Chase, S_BSPI_RUN3, 0, 0 }, // S_BSPI_RUN2 + { SPR_BSPI, 1, 3, A_Chase, S_BSPI_RUN4, 0, 0 }, // S_BSPI_RUN3 + { SPR_BSPI, 1, 3, A_Chase, S_BSPI_RUN5, 0, 0 }, // S_BSPI_RUN4 + { SPR_BSPI, 2, 3, A_Chase, S_BSPI_RUN6, 0, 0 }, // S_BSPI_RUN5 + { SPR_BSPI, 2, 3, A_Chase, S_BSPI_RUN7, 0, 0 }, // S_BSPI_RUN6 + { SPR_BSPI, 3, 3, A_BabyMetal, S_BSPI_RUN8, 0, 0 }, // S_BSPI_RUN7 + { SPR_BSPI, 3, 3, A_Chase, S_BSPI_RUN9, 0, 0 }, // S_BSPI_RUN8 + { SPR_BSPI, 4, 3, A_Chase, S_BSPI_RUN10, 0, 0 }, // S_BSPI_RUN9 + { SPR_BSPI, 4, 3, A_Chase, S_BSPI_RUN11, 0, 0 }, // S_BSPI_RUN10 + { SPR_BSPI, 5, 3, A_Chase, S_BSPI_RUN12, 0, 0 }, // S_BSPI_RUN11 + { SPR_BSPI, 5, 3, A_Chase, S_BSPI_RUN1, 0, 0 }, // S_BSPI_RUN12 + { SPR_BSPI, 32768, 20, A_FaceTarget, S_BSPI_ATK2, 0, 0 }, // S_BSPI_ATK1 + { SPR_BSPI, 32774, 4, A_BspiAttack, S_BSPI_ATK3, 0, 0 }, // S_BSPI_ATK2 + { SPR_BSPI, 32775, 4, NULL, S_BSPI_ATK4, 0, 0 }, // S_BSPI_ATK3 + { SPR_BSPI, 32775, 1, A_SpidRefire, S_BSPI_ATK2, 0, 0 }, // S_BSPI_ATK4 + { SPR_BSPI, 8, 3, NULL, S_BSPI_PAIN2, 0, 0 }, // S_BSPI_PAIN + { SPR_BSPI, 8, 3, A_Pain, S_BSPI_RUN1, 0, 0 }, // S_BSPI_PAIN2 + { SPR_BSPI, 9, 20, A_Scream, S_BSPI_DIE2, 0, 0 }, // S_BSPI_DIE1 + { SPR_BSPI, 10, 7, A_Fall, S_BSPI_DIE3, 0, 0 }, // S_BSPI_DIE2 + { SPR_BSPI, 11, 7, NULL, S_BSPI_DIE4, 0, 0 }, // S_BSPI_DIE3 + { SPR_BSPI, 12, 7, NULL, S_BSPI_DIE5, 0, 0 }, // S_BSPI_DIE4 + { SPR_BSPI, 13, 7, NULL, S_BSPI_DIE6, 0, 0 }, // S_BSPI_DIE5 + { SPR_BSPI, 14, 7, NULL, S_BSPI_DIE7, 0, 0 }, // S_BSPI_DIE6 + { SPR_BSPI, 15, -1, A_BossDeath, S_NULL, 0, 0 }, // S_BSPI_DIE7 + { SPR_BSPI, 15, 5, NULL, S_BSPI_RAISE2, 0, 0 }, // S_BSPI_RAISE1 + { SPR_BSPI, 14, 5, NULL, S_BSPI_RAISE3, 0, 0 }, // S_BSPI_RAISE2 + { SPR_BSPI, 13, 5, NULL, S_BSPI_RAISE4, 0, 0 }, // S_BSPI_RAISE3 + { SPR_BSPI, 12, 5, NULL, S_BSPI_RAISE5, 0, 0 }, // S_BSPI_RAISE4 + { SPR_BSPI, 11, 5, NULL, S_BSPI_RAISE6, 0, 0 }, // S_BSPI_RAISE5 + { SPR_BSPI, 10, 5, NULL, S_BSPI_RAISE7, 0, 0 }, // S_BSPI_RAISE6 + { SPR_BSPI, 9, 5, NULL, S_BSPI_RUN1, 0, 0 }, // S_BSPI_RAISE7 + { SPR_APLS, 32768, 5, NULL, S_ARACH_PLAZ2, 0, 0 }, // S_ARACH_PLAZ + { SPR_APLS, 32769, 5, NULL, S_ARACH_PLAZ, 0, 0 }, // S_ARACH_PLAZ2 + { SPR_APBX, 32768, 5, NULL, S_ARACH_PLEX2, 0, 0 }, // S_ARACH_PLEX + { SPR_APBX, 32769, 5, NULL, S_ARACH_PLEX3, 0, 0 }, // S_ARACH_PLEX2 + { SPR_APBX, 32770, 5, NULL, S_ARACH_PLEX4, 0, 0 }, // S_ARACH_PLEX3 + { SPR_APBX, 32771, 5, NULL, S_ARACH_PLEX5, 0, 0 }, // S_ARACH_PLEX4 + { SPR_APBX, 32772, 5, NULL, S_NULL, 0, 0 }, // S_ARACH_PLEX5 + { SPR_CYBR, 0, 10, A_Look, S_CYBER_STND2, 0, 0 }, // S_CYBER_STND + { SPR_CYBR, 1, 10, A_Look, S_CYBER_STND, 0, 0 }, // S_CYBER_STND2 + { SPR_CYBR, 0, 3, A_Hoof, S_CYBER_RUN2, 0, 0 }, // S_CYBER_RUN1 + { SPR_CYBR, 0, 3, A_Chase, S_CYBER_RUN3, 0, 0 }, // S_CYBER_RUN2 + { SPR_CYBR, 1, 3, A_Chase, S_CYBER_RUN4, 0, 0 }, // S_CYBER_RUN3 + { SPR_CYBR, 1, 3, A_Chase, S_CYBER_RUN5, 0, 0 }, // S_CYBER_RUN4 + { SPR_CYBR, 2, 3, A_Chase, S_CYBER_RUN6, 0, 0 }, // S_CYBER_RUN5 + { SPR_CYBR, 2, 3, A_Chase, S_CYBER_RUN7, 0, 0 }, // S_CYBER_RUN6 + { SPR_CYBR, 3, 3, A_Metal, S_CYBER_RUN8, 0, 0 }, // S_CYBER_RUN7 + { SPR_CYBR, 3, 3, A_Chase, S_CYBER_RUN1, 0, 0 }, // S_CYBER_RUN8 + { SPR_CYBR, 4, 6, A_FaceTarget, S_CYBER_ATK2, 0, 0 }, // S_CYBER_ATK1 + { SPR_CYBR, 5, 12, A_CyberAttack, S_CYBER_ATK3, 0, 0 }, // S_CYBER_ATK2 + { SPR_CYBR, 4, 12, A_FaceTarget, S_CYBER_ATK4, 0, 0 }, // S_CYBER_ATK3 + { SPR_CYBR, 5, 12, A_CyberAttack, S_CYBER_ATK5, 0, 0 }, // S_CYBER_ATK4 + { SPR_CYBR, 4, 12, A_FaceTarget, S_CYBER_ATK6, 0, 0 }, // S_CYBER_ATK5 + { SPR_CYBR, 5, 12, A_CyberAttack, S_CYBER_RUN1, 0, 0 }, // S_CYBER_ATK6 + { SPR_CYBR, 6, 10, A_Pain, S_CYBER_RUN1, 0, 0 }, // S_CYBER_PAIN + { SPR_CYBR, 7, 10, NULL, S_CYBER_DIE2, 0, 0 }, // S_CYBER_DIE1 + { SPR_CYBR, 8, 10, A_Scream, S_CYBER_DIE3, 0, 0 }, // S_CYBER_DIE2 + { SPR_CYBR, 9, 10, NULL, S_CYBER_DIE4, 0, 0 }, // S_CYBER_DIE3 + { SPR_CYBR, 10, 10, NULL, S_CYBER_DIE5, 0, 0 }, // S_CYBER_DIE4 + { SPR_CYBR, 11, 10, NULL, S_CYBER_DIE6, 0, 0 }, // S_CYBER_DIE5 + { SPR_CYBR, 12, 10, A_Fall, S_CYBER_DIE7, 0, 0 }, // S_CYBER_DIE6 + { SPR_CYBR, 13, 10, NULL, S_CYBER_DIE8, 0, 0 }, // S_CYBER_DIE7 + { SPR_CYBR, 14, 10, NULL, S_CYBER_DIE9, 0, 0 }, // S_CYBER_DIE8 + { SPR_CYBR, 15, 30, NULL, S_CYBER_DIE10, 0, 0 }, // S_CYBER_DIE9 + { SPR_CYBR, 15, -1, A_BossDeath, S_NULL, 0, 0 }, // S_CYBER_DIE10 + { SPR_PAIN, 0, 10, A_Look, S_PAIN_STND, 0, 0 }, // S_PAIN_STND + { SPR_PAIN, 0, 3, A_Chase, S_PAIN_RUN2, 0, 0 }, // S_PAIN_RUN1 + { SPR_PAIN, 0, 3, A_Chase, S_PAIN_RUN3, 0, 0 }, // S_PAIN_RUN2 + { SPR_PAIN, 1, 3, A_Chase, S_PAIN_RUN4, 0, 0 }, // S_PAIN_RUN3 + { SPR_PAIN, 1, 3, A_Chase, S_PAIN_RUN5, 0, 0 }, // S_PAIN_RUN4 + { SPR_PAIN, 2, 3, A_Chase, S_PAIN_RUN6, 0, 0 }, // S_PAIN_RUN5 + { SPR_PAIN, 2, 3, A_Chase, S_PAIN_RUN1, 0, 0 }, // S_PAIN_RUN6 + { SPR_PAIN, 3, 5, A_FaceTarget, S_PAIN_ATK2, 0, 0 }, // S_PAIN_ATK1 + { SPR_PAIN, 4, 5, A_FaceTarget, S_PAIN_ATK3, 0, 0 }, // S_PAIN_ATK2 + { SPR_PAIN, 32773, 5, A_FaceTarget, S_PAIN_ATK4, 0, 0 }, // S_PAIN_ATK3 + { SPR_PAIN, 32773, 0, A_PainAttack, S_PAIN_RUN1, 0, 0 }, // S_PAIN_ATK4 + { SPR_PAIN, 6, 6, NULL, S_PAIN_PAIN2, 0, 0 }, // S_PAIN_PAIN + { SPR_PAIN, 6, 6, A_Pain, S_PAIN_RUN1, 0, 0 }, // S_PAIN_PAIN2 + { SPR_PAIN, 32775, 8, NULL, S_PAIN_DIE2, 0, 0 }, // S_PAIN_DIE1 + { SPR_PAIN, 32776, 8, A_Scream, S_PAIN_DIE3, 0, 0 }, // S_PAIN_DIE2 + { SPR_PAIN, 32777, 8, NULL, S_PAIN_DIE4, 0, 0 }, // S_PAIN_DIE3 + { SPR_PAIN, 32778, 8, NULL, S_PAIN_DIE5, 0, 0 }, // S_PAIN_DIE4 + { SPR_PAIN, 32779, 8, A_PainDie, S_PAIN_DIE6, 0, 0 }, // S_PAIN_DIE5 + { SPR_PAIN, 32780, 8, NULL, S_NULL, 0, 0 }, // S_PAIN_DIE6 + { SPR_PAIN, 12, 8, NULL, S_PAIN_RAISE2, 0, 0 }, // S_PAIN_RAISE1 + { SPR_PAIN, 11, 8, NULL, S_PAIN_RAISE3, 0, 0 }, // S_PAIN_RAISE2 + { SPR_PAIN, 10, 8, NULL, S_PAIN_RAISE4, 0, 0 }, // S_PAIN_RAISE3 + { SPR_PAIN, 9, 8, NULL, S_PAIN_RAISE5, 0, 0 }, // S_PAIN_RAISE4 + { SPR_PAIN, 8, 8, NULL, S_PAIN_RAISE6, 0, 0 }, // S_PAIN_RAISE5 + { SPR_PAIN, 7, 8, NULL, S_PAIN_RUN1, 0, 0 }, // S_PAIN_RAISE6 + { SPR_SSWV, 0, 10, A_Look, S_SSWV_STND2, 0, 0 }, // S_SSWV_STND + { SPR_SSWV, 1, 10, A_Look, S_SSWV_STND, 0, 0 }, // S_SSWV_STND2 + { SPR_SSWV, 0, 3, A_Chase, S_SSWV_RUN2, 0, 0 }, // S_SSWV_RUN1 + { SPR_SSWV, 0, 3, A_Chase, S_SSWV_RUN3, 0, 0 }, // S_SSWV_RUN2 + { SPR_SSWV, 1, 3, A_Chase, S_SSWV_RUN4, 0, 0 }, // S_SSWV_RUN3 + { SPR_SSWV, 1, 3, A_Chase, S_SSWV_RUN5, 0, 0 }, // S_SSWV_RUN4 + { SPR_SSWV, 2, 3, A_Chase, S_SSWV_RUN6, 0, 0 }, // S_SSWV_RUN5 + { SPR_SSWV, 2, 3, A_Chase, S_SSWV_RUN7, 0, 0 }, // S_SSWV_RUN6 + { SPR_SSWV, 3, 3, A_Chase, S_SSWV_RUN8, 0, 0 }, // S_SSWV_RUN7 + { SPR_SSWV, 3, 3, A_Chase, S_SSWV_RUN1, 0, 0 }, // S_SSWV_RUN8 + { SPR_SSWV, 4, 10, A_FaceTarget, S_SSWV_ATK2, 0, 0 }, // S_SSWV_ATK1 + { SPR_SSWV, 5, 10, A_FaceTarget, S_SSWV_ATK3, 0, 0 }, // S_SSWV_ATK2 + { SPR_SSWV, 32774, 4, A_CPosAttack, S_SSWV_ATK4, 0, 0 }, // S_SSWV_ATK3 + { SPR_SSWV, 5, 6, A_FaceTarget, S_SSWV_ATK5, 0, 0 }, // S_SSWV_ATK4 + { SPR_SSWV, 32774, 4, A_CPosAttack, S_SSWV_ATK6, 0, 0 }, // S_SSWV_ATK5 + { SPR_SSWV, 5, 1, A_CPosRefire, S_SSWV_ATK2, 0, 0 }, // S_SSWV_ATK6 + { SPR_SSWV, 7, 3, NULL, S_SSWV_PAIN2, 0, 0 }, // S_SSWV_PAIN + { SPR_SSWV, 7, 3, A_Pain, S_SSWV_RUN1, 0, 0 }, // S_SSWV_PAIN2 + { SPR_SSWV, 8, 5, NULL, S_SSWV_DIE2, 0, 0 }, // S_SSWV_DIE1 + { SPR_SSWV, 9, 5, A_Scream, S_SSWV_DIE3, 0, 0 }, // S_SSWV_DIE2 + { SPR_SSWV, 10, 5, A_Fall, S_SSWV_DIE4, 0, 0 }, // S_SSWV_DIE3 + { SPR_SSWV, 11, 5, NULL, S_SSWV_DIE5, 0, 0 }, // S_SSWV_DIE4 + { SPR_SSWV, 12, -1, NULL, S_NULL, 0, 0 }, // S_SSWV_DIE5 + { SPR_SSWV, 13, 5, NULL, S_SSWV_XDIE2, 0, 0 }, // S_SSWV_XDIE1 + { SPR_SSWV, 14, 5, A_XScream, S_SSWV_XDIE3, 0, 0 }, // S_SSWV_XDIE2 + { SPR_SSWV, 15, 5, A_Fall, S_SSWV_XDIE4, 0, 0 }, // S_SSWV_XDIE3 + { SPR_SSWV, 16, 5, NULL, S_SSWV_XDIE5, 0, 0 }, // S_SSWV_XDIE4 + { SPR_SSWV, 17, 5, NULL, S_SSWV_XDIE6, 0, 0 }, // S_SSWV_XDIE5 + { SPR_SSWV, 18, 5, NULL, S_SSWV_XDIE7, 0, 0 }, // S_SSWV_XDIE6 + { SPR_SSWV, 19, 5, NULL, S_SSWV_XDIE8, 0, 0 }, // S_SSWV_XDIE7 + { SPR_SSWV, 20, 5, NULL, S_SSWV_XDIE9, 0, 0 }, // S_SSWV_XDIE8 + { SPR_SSWV, 21, -1, NULL, S_NULL, 0, 0 }, // S_SSWV_XDIE9 + { SPR_SSWV, 12, 5, NULL, S_SSWV_RAISE2, 0, 0 }, // S_SSWV_RAISE1 + { SPR_SSWV, 11, 5, NULL, S_SSWV_RAISE3, 0, 0 }, // S_SSWV_RAISE2 + { SPR_SSWV, 10, 5, NULL, S_SSWV_RAISE4, 0, 0 }, // S_SSWV_RAISE3 + { SPR_SSWV, 9, 5, NULL, S_SSWV_RAISE5, 0, 0 }, // S_SSWV_RAISE4 + { SPR_SSWV, 8, 5, NULL, S_SSWV_RUN1, 0, 0 }, // S_SSWV_RAISE5 + { SPR_KEEN, 0, -1, NULL, S_KEENSTND, 0, 0 }, // S_KEENSTND + { SPR_KEEN, 0, 6, NULL, S_COMMKEEN2, 0, 0 }, // S_COMMKEEN + { SPR_KEEN, 1, 6, NULL, S_COMMKEEN3, 0, 0 }, // S_COMMKEEN2 + { SPR_KEEN, 2, 6, A_Scream, S_COMMKEEN4, 0, 0 }, // S_COMMKEEN3 + { SPR_KEEN, 3, 6, NULL, S_COMMKEEN5, 0, 0 }, // S_COMMKEEN4 + { SPR_KEEN, 4, 6, NULL, S_COMMKEEN6, 0, 0 }, // S_COMMKEEN5 + { SPR_KEEN, 5, 6, NULL, S_COMMKEEN7, 0, 0 }, // S_COMMKEEN6 + { SPR_KEEN, 6, 6, NULL, S_COMMKEEN8, 0, 0 }, // S_COMMKEEN7 + { SPR_KEEN, 7, 6, NULL, S_COMMKEEN9, 0, 0 }, // S_COMMKEEN8 + { SPR_KEEN, 8, 6, NULL, S_COMMKEEN10, 0, 0 }, // S_COMMKEEN9 + { SPR_KEEN, 9, 6, NULL, S_COMMKEEN11, 0, 0 }, // S_COMMKEEN10 + { SPR_KEEN, 10, 6, A_KeenDie, S_COMMKEEN12, 0, 0 }, // S_COMMKEEN11 + { SPR_KEEN, 11, -1, NULL, S_NULL, 0, 0 }, // S_COMMKEEN12 + { SPR_KEEN, 12, 4, NULL, S_KEENPAIN2, 0, 0 }, // S_KEENPAIN + { SPR_KEEN, 12, 8, A_Pain, S_KEENSTND, 0, 0 }, // S_KEENPAIN2 + { SPR_BBRN, 0, -1, NULL, S_NULL, 0, 0 }, // S_BRAIN + { SPR_BBRN, 1, 36, A_BrainPain, S_BRAIN, 0, 0 }, // S_BRAIN_PAIN + { SPR_BBRN, 0, 100, A_BrainScream, S_BRAIN_DIE2, 0, 0 }, // S_BRAIN_DIE1 + { SPR_BBRN, 0, 10, NULL, S_BRAIN_DIE3, 0, 0 }, // S_BRAIN_DIE2 + { SPR_BBRN, 0, 10, NULL, S_BRAIN_DIE4, 0, 0 }, // S_BRAIN_DIE3 + { SPR_BBRN, 0, -1, A_BrainDie, S_NULL, 0, 0 }, // S_BRAIN_DIE4 + { SPR_SSWV, 0, 10, A_Look, S_BRAINEYE, 0, 0 }, // S_BRAINEYE + { SPR_SSWV, 0, 181, A_BrainAwake, S_BRAINEYE1, 0, 0 }, // S_BRAINEYESEE + { SPR_SSWV, 0, 150, A_BrainSpit, S_BRAINEYE1, 0, 0 }, // S_BRAINEYE1 + { SPR_BOSF, 32768, 3, A_SpawnSound, S_SPAWN2, 0, 0 }, // S_SPAWN1 + { SPR_BOSF, 32769, 3, A_SpawnFly, S_SPAWN3, 0, 0 }, // S_SPAWN2 + { SPR_BOSF, 32770, 3, A_SpawnFly, S_SPAWN4, 0, 0 }, // S_SPAWN3 + { SPR_BOSF, 32771, 3, A_SpawnFly, S_SPAWN1, 0, 0 }, // S_SPAWN4 + { SPR_FIRE, 32768, 4, A_Fire, S_SPAWNFIRE2, 0, 0 }, // S_SPAWNFIRE1 + { SPR_FIRE, 32769, 4, A_Fire, S_SPAWNFIRE3, 0, 0 }, // S_SPAWNFIRE2 + { SPR_FIRE, 32770, 4, A_Fire, S_SPAWNFIRE4, 0, 0 }, // S_SPAWNFIRE3 + { SPR_FIRE, 32771, 4, A_Fire, S_SPAWNFIRE5, 0, 0 }, // S_SPAWNFIRE4 + { SPR_FIRE, 32772, 4, A_Fire, S_SPAWNFIRE6, 0, 0 }, // S_SPAWNFIRE5 + { SPR_FIRE, 32773, 4, A_Fire, S_SPAWNFIRE7, 0, 0 }, // S_SPAWNFIRE6 + { SPR_FIRE, 32774, 4, A_Fire, S_SPAWNFIRE8, 0, 0 }, // S_SPAWNFIRE7 + { SPR_FIRE, 32775, 4, A_Fire, S_NULL, 0, 0 }, // S_SPAWNFIRE8 + { SPR_MISL, 32769, 10, NULL, S_BRAINEXPLODE2, 0, 0 }, // S_BRAINEXPLODE1 + { SPR_MISL, 32770, 10, NULL, S_BRAINEXPLODE3, 0, 0 }, // S_BRAINEXPLODE2 + { SPR_MISL, 32771, 10, A_BrainExplode, S_NULL, 0, 0 }, // S_BRAINEXPLODE3 + { SPR_ARM1, 0, 6, NULL, S_ARM1A, 0, 0 }, // S_ARM1 + { SPR_ARM1, 32769, 7, NULL, S_ARM1, 0, 0 }, // S_ARM1A + { SPR_ARM2, 0, 6, NULL, S_ARM2A, 0, 0 }, // S_ARM2 + { SPR_ARM2, 32769, 6, NULL, S_ARM2, 0, 0 }, // S_ARM2A + { SPR_BAR1, 0, 6, NULL, S_BAR2, 0, 0 }, // S_BAR1 + { SPR_BAR1, 1, 6, NULL, S_BAR1, 0, 0 }, // S_BAR2 + { SPR_BEXP, 32768, 5, NULL, S_BEXP2, 0, 0 }, // S_BEXP + { SPR_BEXP, 32769, 5, A_Scream, S_BEXP3, 0, 0 }, // S_BEXP2 + { SPR_BEXP, 32770, 5, NULL, S_BEXP4, 0, 0 }, // S_BEXP3 + { SPR_BEXP, 32771, 10, A_Explode, S_BEXP5, 0, 0 }, // S_BEXP4 + { SPR_BEXP, 32772, 10, NULL, S_NULL, 0, 0 }, // S_BEXP5 + { SPR_FCAN, 32768, 4, NULL, S_BBAR2, 0, 0 }, // S_BBAR1 + { SPR_FCAN, 32769, 4, NULL, S_BBAR3, 0, 0 }, // S_BBAR2 + { SPR_FCAN, 32770, 4, NULL, S_BBAR1, 0, 0 }, // S_BBAR3 + { SPR_BON1, 0, 6, NULL, S_BON1A, 0, 0 }, // S_BON1 + { SPR_BON1, 1, 6, NULL, S_BON1B, 0, 0 }, // S_BON1A + { SPR_BON1, 2, 6, NULL, S_BON1C, 0, 0 }, // S_BON1B + { SPR_BON1, 3, 6, NULL, S_BON1D, 0, 0 }, // S_BON1C + { SPR_BON1, 2, 6, NULL, S_BON1E, 0, 0 }, // S_BON1D + { SPR_BON1, 1, 6, NULL, S_BON1, 0, 0 }, // S_BON1E + { SPR_BON2, 0, 6, NULL, S_BON2A, 0, 0 }, // S_BON2 + { SPR_BON2, 1, 6, NULL, S_BON2B, 0, 0 }, // S_BON2A + { SPR_BON2, 2, 6, NULL, S_BON2C, 0, 0 }, // S_BON2B + { SPR_BON2, 3, 6, NULL, S_BON2D, 0, 0 }, // S_BON2C + { SPR_BON2, 2, 6, NULL, S_BON2E, 0, 0 }, // S_BON2D + { SPR_BON2, 1, 6, NULL, S_BON2, 0, 0 }, // S_BON2E + { SPR_BKEY, 0, 10, NULL, S_BKEY2, 0, 0 }, // S_BKEY + { SPR_BKEY, 32769, 10, NULL, S_BKEY, 0, 0 }, // S_BKEY2 + { SPR_RKEY, 0, 10, NULL, S_RKEY2, 0, 0 }, // S_RKEY + { SPR_RKEY, 32769, 10, NULL, S_RKEY, 0, 0 }, // S_RKEY2 + { SPR_YKEY, 0, 10, NULL, S_YKEY2, 0, 0 }, // S_YKEY + { SPR_YKEY, 32769, 10, NULL, S_YKEY, 0, 0 }, // S_YKEY2 + { SPR_BSKU, 0, 10, NULL, S_BSKULL2, 0, 0 }, // S_BSKULL + { SPR_BSKU, 32769, 10, NULL, S_BSKULL, 0, 0 }, // S_BSKULL2 + { SPR_RSKU, 0, 10, NULL, S_RSKULL2, 0, 0 }, // S_RSKULL + { SPR_RSKU, 32769, 10, NULL, S_RSKULL, 0, 0 }, // S_RSKULL2 + { SPR_YSKU, 0, 10, NULL, S_YSKULL2, 0, 0 }, // S_YSKULL + { SPR_YSKU, 32769, 10, NULL, S_YSKULL, 0, 0 }, // S_YSKULL2 + { SPR_STIM, 0, -1, NULL, S_NULL, 0, 0 }, // S_STIM + { SPR_MEDI, 0, -1, NULL, S_NULL, 0, 0 }, // S_MEDI + { SPR_SOUL, 32768, 6, NULL, S_SOUL2, 0, 0 }, // S_SOUL + { SPR_SOUL, 32769, 6, NULL, S_SOUL3, 0, 0 }, // S_SOUL2 + { SPR_SOUL, 32770, 6, NULL, S_SOUL4, 0, 0 }, // S_SOUL3 + { SPR_SOUL, 32771, 6, NULL, S_SOUL5, 0, 0 }, // S_SOUL4 + { SPR_SOUL, 32770, 6, NULL, S_SOUL6, 0, 0 }, // S_SOUL5 + { SPR_SOUL, 32769, 6, NULL, S_SOUL, 0, 0 }, // S_SOUL6 + { SPR_PINV, 32768, 6, NULL, S_PINV2, 0, 0 }, // S_PINV + { SPR_PINV, 32769, 6, NULL, S_PINV3, 0, 0 }, // S_PINV2 + { SPR_PINV, 32770, 6, NULL, S_PINV4, 0, 0 }, // S_PINV3 + { SPR_PINV, 32771, 6, NULL, S_PINV, 0, 0 }, // S_PINV4 + { SPR_PSTR, 32768, -1, NULL, S_NULL, 0, 0 }, // S_PSTR + { SPR_PINS, 32768, 6, NULL, S_PINS2, 0, 0 }, // S_PINS + { SPR_PINS, 32769, 6, NULL, S_PINS3, 0, 0 }, // S_PINS2 + { SPR_PINS, 32770, 6, NULL, S_PINS4, 0, 0 }, // S_PINS3 + { SPR_PINS, 32771, 6, NULL, S_PINS, 0, 0 }, // S_PINS4 + { SPR_MEGA, 32768, 6, NULL, S_MEGA2, 0, 0 }, // S_MEGA + { SPR_MEGA, 32769, 6, NULL, S_MEGA3, 0, 0 }, // S_MEGA2 + { SPR_MEGA, 32770, 6, NULL, S_MEGA4, 0, 0 }, // S_MEGA3 + { SPR_MEGA, 32771, 6, NULL, S_MEGA, 0, 0 }, // S_MEGA4 + { SPR_SUIT, 32768, -1, NULL, S_NULL, 0, 0 }, // S_SUIT + { SPR_PMAP, 32768, 6, NULL, S_PMAP2, 0, 0 }, // S_PMAP + { SPR_PMAP, 32769, 6, NULL, S_PMAP3, 0, 0 }, // S_PMAP2 + { SPR_PMAP, 32770, 6, NULL, S_PMAP4, 0, 0 }, // S_PMAP3 + { SPR_PMAP, 32771, 6, NULL, S_PMAP5, 0, 0 }, // S_PMAP4 + { SPR_PMAP, 32770, 6, NULL, S_PMAP6, 0, 0 }, // S_PMAP5 + { SPR_PMAP, 32769, 6, NULL, S_PMAP, 0, 0 }, // S_PMAP6 + { SPR_PVIS, 32768, 6, NULL, S_PVIS2, 0, 0 }, // S_PVIS + { SPR_PVIS, 1, 6, NULL, S_PVIS, 0, 0 }, // S_PVIS2 + { SPR_CLIP, 0, -1, NULL, S_NULL, 0, 0 }, // S_CLIP + { SPR_AMMO, 0, -1, NULL, S_NULL, 0, 0 }, // S_AMMO + { SPR_ROCK, 0, -1, NULL, S_NULL, 0, 0 }, // S_ROCK + { SPR_BROK, 0, -1, NULL, S_NULL, 0, 0 }, // S_BROK + { SPR_CELL, 0, -1, NULL, S_NULL, 0, 0 }, // S_CELL + { SPR_CELP, 0, -1, NULL, S_NULL, 0, 0 }, // S_CELP + { SPR_SHEL, 0, -1, NULL, S_NULL, 0, 0 }, // S_SHEL + { SPR_SBOX, 0, -1, NULL, S_NULL, 0, 0 }, // S_SBOX + { SPR_BPAK, 0, -1, NULL, S_NULL, 0, 0 }, // S_BPAK + { SPR_BFUG, 0, -1, NULL, S_NULL, 0, 0 }, // S_BFUG + { SPR_MGUN, 0, -1, NULL, S_NULL, 0, 0 }, // S_MGUN + { SPR_CSAW, 0, -1, NULL, S_NULL, 0, 0 }, // S_CSAW + { SPR_LAUN, 0, -1, NULL, S_NULL, 0, 0 }, // S_LAUN + { SPR_PLAS, 0, -1, NULL, S_NULL, 0, 0 }, // S_PLAS + { SPR_SHOT, 0, -1, NULL, S_NULL, 0, 0 }, // S_SHOT + { SPR_SGN2, 0, -1, NULL, S_NULL, 0, 0 }, // S_SHOT2 + { SPR_COLU, 32768, -1, NULL, S_NULL, 0, 0 }, // S_COLU + { SPR_SMT2, 0, -1, NULL, S_NULL, 0, 0 }, // S_STALAG + { SPR_GOR1, 0, 10, NULL, S_BLOODYTWITCH2, 0, 0 }, // S_BLOODYTWITCH + { SPR_GOR1, 1, 15, NULL, S_BLOODYTWITCH3, 0, 0 }, // S_BLOODYTWITCH2 + { SPR_GOR1, 2, 8, NULL, S_BLOODYTWITCH4, 0, 0 }, // S_BLOODYTWITCH3 + { SPR_GOR1, 1, 6, NULL, S_BLOODYTWITCH, 0, 0 }, // S_BLOODYTWITCH4 + { SPR_PLAY, 13, -1, NULL, S_NULL, 0, 0 }, // S_DEADTORSO + { SPR_PLAY, 18, -1, NULL, S_NULL, 0, 0 }, // S_DEADBOTTOM + { SPR_POL2, 0, -1, NULL, S_NULL, 0, 0 }, // S_HEADSONSTICK + { SPR_POL5, 0, -1, NULL, S_NULL, 0, 0 }, // S_GIBS + { SPR_POL4, 0, -1, NULL, S_NULL, 0, 0 }, // S_HEADONASTICK + { SPR_POL3, 32768, 6, NULL, S_HEADCANDLES2, 0, 0 }, // S_HEADCANDLES + { SPR_POL3, 32769, 6, NULL, S_HEADCANDLES, 0, 0 }, // S_HEADCANDLES2 + { SPR_POL1, 0, -1, NULL, S_NULL, 0, 0 }, // S_DEADSTICK + { SPR_POL6, 0, 6, NULL, S_LIVESTICK2, 0, 0 }, // S_LIVESTICK + { SPR_POL6, 1, 8, NULL, S_LIVESTICK, 0, 0 }, // S_LIVESTICK2 + { SPR_GOR2, 0, -1, NULL, S_NULL, 0, 0 }, // S_MEAT2 + { SPR_GOR3, 0, -1, NULL, S_NULL, 0, 0 }, // S_MEAT3 + { SPR_GOR4, 0, -1, NULL, S_NULL, 0, 0 }, // S_MEAT4 + { SPR_GOR5, 0, -1, NULL, S_NULL, 0, 0 }, // S_MEAT5 + { SPR_SMIT, 0, -1, NULL, S_NULL, 0, 0 }, // S_STALAGTITE + { SPR_COL1, 0, -1, NULL, S_NULL, 0, 0 }, // S_TALLGRNCOL + { SPR_COL2, 0, -1, NULL, S_NULL, 0, 0 }, // S_SHRTGRNCOL + { SPR_COL3, 0, -1, NULL, S_NULL, 0, 0 }, // S_TALLREDCOL + { SPR_COL4, 0, -1, NULL, S_NULL, 0, 0 }, // S_SHRTREDCOL + { SPR_CAND, 32768, -1, NULL, S_NULL, 0, 0 }, // S_CANDLESTIK + { SPR_CBRA, 32768, -1, NULL, S_NULL, 0, 0 }, // S_CANDELABRA + { SPR_COL6, 0, -1, NULL, S_NULL, 0, 0 }, // S_SKULLCOL + { SPR_TRE1, 0, -1, NULL, S_NULL, 0, 0 }, // S_TORCHTREE + { SPR_TRE2, 0, -1, NULL, S_NULL, 0, 0 }, // S_BIGTREE + { SPR_ELEC, 0, -1, NULL, S_NULL, 0, 0 }, // S_TECHPILLAR + { SPR_CEYE, 32768, 6, NULL, S_EVILEYE2, 0, 0 }, // S_EVILEYE + { SPR_CEYE, 32769, 6, NULL, S_EVILEYE3, 0, 0 }, // S_EVILEYE2 + { SPR_CEYE, 32770, 6, NULL, S_EVILEYE4, 0, 0 }, // S_EVILEYE3 + { SPR_CEYE, 32769, 6, NULL, S_EVILEYE, 0, 0 }, // S_EVILEYE4 + { SPR_FSKU, 32768, 6, NULL, S_FLOATSKULL2, 0, 0 }, // S_FLOATSKULL + { SPR_FSKU, 32769, 6, NULL, S_FLOATSKULL3, 0, 0 }, // S_FLOATSKULL2 + { SPR_FSKU, 32770, 6, NULL, S_FLOATSKULL, 0, 0 }, // S_FLOATSKULL3 + { SPR_COL5, 0, 14, NULL, S_HEARTCOL2, 0, 0 }, // S_HEARTCOL + { SPR_COL5, 1, 14, NULL, S_HEARTCOL, 0, 0 }, // S_HEARTCOL2 + { SPR_TBLU, 32768, 4, NULL, S_BLUETORCH2, 0, 0 }, // S_BLUETORCH + { SPR_TBLU, 32769, 4, NULL, S_BLUETORCH3, 0, 0 }, // S_BLUETORCH2 + { SPR_TBLU, 32770, 4, NULL, S_BLUETORCH4, 0, 0 }, // S_BLUETORCH3 + { SPR_TBLU, 32771, 4, NULL, S_BLUETORCH, 0, 0 }, // S_BLUETORCH4 + { SPR_TGRN, 32768, 4, NULL, S_GREENTORCH2, 0, 0 }, // S_GREENTORCH + { SPR_TGRN, 32769, 4, NULL, S_GREENTORCH3, 0, 0 }, // S_GREENTORCH2 + { SPR_TGRN, 32770, 4, NULL, S_GREENTORCH4, 0, 0 }, // S_GREENTORCH3 + { SPR_TGRN, 32771, 4, NULL, S_GREENTORCH, 0, 0 }, // S_GREENTORCH4 + { SPR_TRED, 32768, 4, NULL, S_REDTORCH2, 0, 0 }, // S_REDTORCH + { SPR_TRED, 32769, 4, NULL, S_REDTORCH3, 0, 0 }, // S_REDTORCH2 + { SPR_TRED, 32770, 4, NULL, S_REDTORCH4, 0, 0 }, // S_REDTORCH3 + { SPR_TRED, 32771, 4, NULL, S_REDTORCH, 0, 0 }, // S_REDTORCH4 + { SPR_SMBT, 32768, 4, NULL, S_BTORCHSHRT2, 0, 0 }, // S_BTORCHSHRT + { SPR_SMBT, 32769, 4, NULL, S_BTORCHSHRT3, 0, 0 }, // S_BTORCHSHRT2 + { SPR_SMBT, 32770, 4, NULL, S_BTORCHSHRT4, 0, 0 }, // S_BTORCHSHRT3 + { SPR_SMBT, 32771, 4, NULL, S_BTORCHSHRT, 0, 0 }, // S_BTORCHSHRT4 + { SPR_SMGT, 32768, 4, NULL, S_GTORCHSHRT2, 0, 0 }, // S_GTORCHSHRT + { SPR_SMGT, 32769, 4, NULL, S_GTORCHSHRT3, 0, 0 }, // S_GTORCHSHRT2 + { SPR_SMGT, 32770, 4, NULL, S_GTORCHSHRT4, 0, 0 }, // S_GTORCHSHRT3 + { SPR_SMGT, 32771, 4, NULL, S_GTORCHSHRT, 0, 0 }, // S_GTORCHSHRT4 + { SPR_SMRT, 32768, 4, NULL, S_RTORCHSHRT2, 0, 0 }, // S_RTORCHSHRT + { SPR_SMRT, 32769, 4, NULL, S_RTORCHSHRT3, 0, 0 }, // S_RTORCHSHRT2 + { SPR_SMRT, 32770, 4, NULL, S_RTORCHSHRT4, 0, 0 }, // S_RTORCHSHRT3 + { SPR_SMRT, 32771, 4, NULL, S_RTORCHSHRT, 0, 0 }, // S_RTORCHSHRT4 + { SPR_HDB1, 0, -1, NULL, S_NULL, 0, 0 }, // S_HANGNOGUTS + { SPR_HDB2, 0, -1, NULL, S_NULL, 0, 0 }, // S_HANGBNOBRAIN + { SPR_HDB3, 0, -1, NULL, S_NULL, 0, 0 }, // S_HANGTLOOKDN + { SPR_HDB4, 0, -1, NULL, S_NULL, 0, 0 }, // S_HANGTSKULL + { SPR_HDB5, 0, -1, NULL, S_NULL, 0, 0 }, // S_HANGTLOOKUP + { SPR_HDB6, 0, -1, NULL, S_NULL, 0, 0 }, // S_HANGTNOBRAIN + { SPR_POB1, 0, -1, NULL, S_NULL, 0, 0 }, // S_COLONGIBS + { SPR_POB2, 0, -1, NULL, S_NULL, 0, 0 }, // S_SMALLPOOL + { SPR_BRS1, 0, -1, NULL, S_NULL, 0, 0 }, // S_BRAINSTEM + { SPR_TLMP, 32768, 4, NULL, S_TECHLAMP2, 0, 0 }, // S_TECHLAMP + { SPR_TLMP, 32769, 4, NULL, S_TECHLAMP3, 0, 0 }, // S_TECHLAMP2 + { SPR_TLMP, 32770, 4, NULL, S_TECHLAMP4, 0, 0 }, // S_TECHLAMP3 + { SPR_TLMP, 32771, 4, NULL, S_TECHLAMP, 0, 0 }, // S_TECHLAMP4 + { SPR_TLP2, 32768, 4, NULL, S_TECH2LAMP2, 0, 0 }, // S_TECH2LAMP + { SPR_TLP2, 32769, 4, NULL, S_TECH2LAMP3, 0, 0 }, // S_TECH2LAMP2 + { SPR_TLP2, 32770, 4, NULL, S_TECH2LAMP4, 0, 0 }, // S_TECH2LAMP3 + { SPR_TLP2, 32771, 4, NULL, S_TECH2LAMP, 0, 0 }, // S_TECH2LAMP4 + { SPR_TNT1, 0, -1, NULL, S_TNT1, 0, 0 }, // S_TNT1 // phares 3/8/98 + + // killough 8/9/98: grenade + { SPR_MISL, 32768, 1000, A_Die, S_GRENADE }, // S_GRENADE + + // killough 8/10/98: variable damage explosion + { SPR_MISL, 32769, 4, A_Scream, S_DETONATE2 }, // S_DETONATE + { SPR_MISL, 32770, 6, A_Detonate, S_DETONATE3 }, // S_DETONATE2 + { SPR_MISL, 32771, 10, NULL, S_NULL }, // S_DETONATE3 + + // if dogs are disabled, dummy states are required for dehacked compatibility + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_STND + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_STND2 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN1 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN2 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN3 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN4 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN5 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN6 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN7 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RUN8 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_ATK1 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_ATK2 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_ATK3 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_PAIN + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_PAIN2 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_DIE1 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_DIE2 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_DIE3 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_DIE4 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_DIE5 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_DIE6 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RAISE1 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RAISE2 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RAISE3 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RAISE4 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RAISE5 + { 0, 0, -1, NULL, S_NULL }, // S_DOGS_RAISE6 + + // add dummy beta bfg / lost soul frames for dehacked compatibility + // fixes bug #1576151 (part 2) + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG1 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG2 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG3 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG4 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG5 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG6 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG7 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG8 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG9 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG10 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG11 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG12 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG13 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG14 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG15 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG16 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG17 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG18 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG19 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG20 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG21 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG22 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG23 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG24 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG25 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG26 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG27 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG28 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG29 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG30 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG31 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG32 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG33 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG34 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG35 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG36 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG37 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG38 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG39 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG40 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG41 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG42 + { 0, 0, -1, NULL, S_NULL }, // S_OLDBFG43 + + { 0, 0, -1, NULL, S_NULL }, // S_PLS1BALL + { 0, 0, -1, NULL, S_NULL }, // S_PLS1BALL2 + { 0, 0, -1, NULL, S_NULL }, // S_PLS1EXP + { 0, 0, -1, NULL, S_NULL }, // S_PLS1EXP2 + { 0, 0, -1, NULL, S_NULL }, // S_PLS1EXP3 + { 0, 0, -1, NULL, S_NULL }, // S_PLS1EXP4 + { 0, 0, -1, NULL, S_NULL }, // S_PLS1EXP5 + + { 0, 0, -1, NULL, S_NULL }, // S_PLS2BALL + { 0, 0, -1, NULL, S_NULL }, // S_PLS2BALL2 + { 0, 0, -1, NULL, S_NULL }, // S_PLS2BALLX1 + { 0, 0, -1, NULL, S_NULL }, // S_PLS2BALLX2 + { 0, 0, -1, NULL, S_NULL }, // S_PLS2BALLX3 + + { 0, 0, -1, NULL, S_NULL }, // S_BON3 + { 0, 0, -1, NULL, S_NULL }, // S_BON4 + + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_STND + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_RUN1 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_RUN2 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_RUN3 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_RUN4 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_ATK1 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_ATK2 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_ATK3 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_PAIN1 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_PAIN2 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_PAIN3 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE1 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE2 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE3 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE4 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE5 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE6 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE7 + { 0, 0, -1, NULL, S_NULL }, // S_BSKUL_DIE8 + + // killough 10/98: mushroom effect + { SPR_MISL, 32769, 8, A_Mushroom, S_EXPLODE2 }, // S_MUSHROOM +}; + +// ******************************************************************** +// Object "Thing" definitions +// ******************************************************************** +// Now we get to the actual objects and their characteristics. If +// you've seen Dehacked, much of this is where the Bits are set, +// commented below as "flags", as well as where you wire in which +// frames are the beginning frames for near and far attack, death, +// and such. Sounds are hooked in here too, as well as how much +// mass, speed and so forth a Thing has. Everything you ever wanted +// to know... +// +// Like all this other stuff, the MT_* entries are enumerated in info.h +// +// Note that these are all just indices of the elements involved, and +// not real pointers to them. For example, the player's death sequence +// is S_PLAY_DIE1, which just evaluates to the index in the states[] +// array above, which actually knows what happens then and what the +// sprite looks like, if it makes noise or not, etc. +// +// Additional comments about each of the entries are located in info.h +// next to the mobjinfo_t structure definition. +// +// This goes on for the next 3000+ lines... + +const mobjinfo_t mobjinfo[NUMMOBJTYPES] = +{ +{ // MT_PLAYER +-1, // doomednum +S_PLAY, // spawnstate +100, // spawnhealth +S_PLAY_RUN1, // seestate +sfx_None, // seesound +0, // reactiontime +sfx_None, // attacksound +S_PLAY_PAIN, // painstate +255, // painchance +sfx_plpain, // painsound +S_NULL, // meleestate +S_PLAY_ATK1, // missilestate +S_PLAY_DIE1, // deathstate +S_PLAY_XDIE1, // xdeathstate +sfx_pldeth, // deathsound +0, // speed +16 * FRACUNIT, // radius +56 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SHOOTABLE | MF_DROPOFF | MF_PICKUP | MF_NOTDMATCH, // flags +S_NULL // raisestate +}, + +{ // MT_POSSESSED +3004, // doomednum +S_POSS_STND, // spawnstate +20, // spawnhealth +S_POSS_RUN1, // seestate +sfx_posit1, // seesound +8, // reactiontime +sfx_pistol, // attacksound +S_POSS_PAIN, // painstate +200, // painchance +sfx_popain, // painsound +0, // meleestate +S_POSS_ATK1, // missilestate +S_POSS_DIE1, // deathstate +S_POSS_XDIE1, // xdeathstate +sfx_podth1, // deathsound +8, // speed +20 * FRACUNIT, // radius +56 * FRACUNIT, // height +100, // mass +0, // damage +sfx_posact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_POSS_RAISE1 // raisestate +}, + +{ // MT_SHOTGUY +9, // doomednum +S_SPOS_STND, // spawnstate +30, // spawnhealth +S_SPOS_RUN1, // seestate +sfx_posit2, // seesound +8, // reactiontime +0, // attacksound +S_SPOS_PAIN, // painstate +170, // painchance +sfx_popain, // painsound +0, // meleestate +S_SPOS_ATK1, // missilestate +S_SPOS_DIE1, // deathstate +S_SPOS_XDIE1, // xdeathstate +sfx_podth2, // deathsound +8, // speed +20 * FRACUNIT, // radius +56 * FRACUNIT, // height +100, // mass +0, // damage +sfx_posact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_SPOS_RAISE1 // raisestate +}, + +{ // MT_VILE +64, // doomednum +S_VILE_STND, // spawnstate +700, // spawnhealth +S_VILE_RUN1, // seestate +sfx_vilsit, // seesound +8, // reactiontime +0, // attacksound +S_VILE_PAIN, // painstate +10, // painchance +sfx_vipain, // painsound +0, // meleestate +S_VILE_ATK1, // missilestate +S_VILE_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_vildth, // deathsound +15, // speed +20 * FRACUNIT, // radius +56 * FRACUNIT, // height +500, // mass +0, // damage +sfx_vilact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_NULL // raisestate +}, + +{ // MT_FIRE +-1, // doomednum +S_FIRE1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // killough 2/21/98 +S_NULL // raisestate +}, + +{ // MT_UNDEAD +66, // doomednum +S_SKEL_STND, // spawnstate +300, // spawnhealth +S_SKEL_RUN1, // seestate +sfx_skesit, // seesound +8, // reactiontime +0, // attacksound +S_SKEL_PAIN, // painstate +100, // painchance +sfx_popain, // painsound +S_SKEL_FIST1, // meleestate +S_SKEL_MISS1, // missilestate +S_SKEL_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_skedth, // deathsound +10, // speed +20 * FRACUNIT, // radius +56 * FRACUNIT, // height +500, // mass +0, // damage +sfx_skeact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_SKEL_RAISE1 // raisestate +}, + +{ // MT_TRACER +-1, // doomednum +S_TRACER, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_skeatk, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_TRACEEXP1, // deathstate +S_NULL, // xdeathstate +sfx_barexp, // deathsound +10 * FRACUNIT, // speed +11 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +10, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY, // flags +S_NULL // raisestate +}, + +{ // MT_SMOKE +-1, // doomednum +S_SMOKE1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_FATSO +67, // doomednum +S_FATT_STND, // spawnstate +600, // spawnhealth +S_FATT_RUN1, // seestate +sfx_mansit, // seesound +8, // reactiontime +0, // attacksound +S_FATT_PAIN, // painstate +80, // painchance +sfx_mnpain, // painsound +0, // meleestate +S_FATT_ATK1, // missilestate +S_FATT_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_mandth, // deathsound +8, // speed +48 * FRACUNIT, // radius +64 * FRACUNIT, // height +1000, // mass +0, // damage +sfx_posact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_FATT_RAISE1 // raisestate +}, + +{ // MT_FATSHOT +-1, // doomednum +S_FATSHOT1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_firsht, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_FATSHOTX1, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +20 * FRACUNIT, // speed +6 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +8, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_TRANSLUCENT, // flags \\ killough 2/21/98 +S_NULL // raisestate +}, + +{ // MT_CHAINGUY +65, // doomednum +S_CPOS_STND, // spawnstate +70, // spawnhealth +S_CPOS_RUN1, // seestate +sfx_posit2, // seesound +8, // reactiontime +0, // attacksound +S_CPOS_PAIN, // painstate +170, // painchance +sfx_popain, // painsound +0, // meleestate +S_CPOS_ATK1, // missilestate +S_CPOS_DIE1, // deathstate +S_CPOS_XDIE1, // xdeathstate +sfx_podth2, // deathsound +8, // speed +20 * FRACUNIT, // radius +56 * FRACUNIT, // height +100, // mass +0, // damage +sfx_posact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_CPOS_RAISE1 // raisestate +}, + +{ // MT_TROOP +3001, // doomednum +S_TROO_STND, // spawnstate +60, // spawnhealth +S_TROO_RUN1, // seestate +sfx_bgsit1, // seesound +8, // reactiontime +0, // attacksound +S_TROO_PAIN, // painstate +200, // painchance +sfx_popain, // painsound +S_TROO_ATK1, // meleestate +S_TROO_ATK1, // missilestate +S_TROO_DIE1, // deathstate +S_TROO_XDIE1, // xdeathstate +sfx_bgdth1, // deathsound +8, // speed +20 * FRACUNIT, // radius +56 * FRACUNIT, // height +100, // mass +0, // damage +sfx_bgact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // killough |MF_TRANSLUCENT, // flags // phares +S_TROO_RAISE1 // raisestate +}, + +{ // MT_SERGEANT +3002, // doomednum +S_SARG_STND, // spawnstate +150, // spawnhealth +S_SARG_RUN1, // seestate +sfx_sgtsit, // seesound +8, // reactiontime +sfx_sgtatk, // attacksound +S_SARG_PAIN, // painstate +180, // painchance +sfx_dmpain, // painsound +S_SARG_ATK1, // meleestate +0, // missilestate +S_SARG_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_sgtdth, // deathsound +10, // speed +30 * FRACUNIT, // radius +56 * FRACUNIT, // height +400, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_SARG_RAISE1 // raisestate +}, + +{ // MT_SHADOWS +58, // doomednum +S_SARG_STND, // spawnstate +150, // spawnhealth +S_SARG_RUN1, // seestate +sfx_sgtsit, // seesound +8, // reactiontime +sfx_sgtatk, // attacksound +S_SARG_PAIN, // painstate +180, // painchance +sfx_dmpain, // painsound +S_SARG_ATK1, // meleestate +0, // missilestate +S_SARG_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_sgtdth, // deathsound +10, // speed +30 * FRACUNIT, // radius +56 * FRACUNIT, // height +400, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_SHADOW | MF_COUNTKILL, // flags +S_SARG_RAISE1 // raisestate +}, + +{ // MT_HEAD +3005, // doomednum +S_HEAD_STND, // spawnstate +400, // spawnhealth +S_HEAD_RUN1, // seestate +sfx_cacsit, // seesound +8, // reactiontime +0, // attacksound +S_HEAD_PAIN, // painstate +128, // painchance +sfx_dmpain, // painsound +0, // meleestate +S_HEAD_ATK1, // missilestate +S_HEAD_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_cacdth, // deathsound +8, // speed +31 * FRACUNIT, // radius +56 * FRACUNIT, // height +400, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_FLOAT | MF_NOGRAVITY | MF_COUNTKILL, // flags +S_HEAD_RAISE1 // raisestate +}, + +{ // MT_BRUISER +3003, // doomednum +S_BOSS_STND, // spawnstate +1000, // spawnhealth +S_BOSS_RUN1, // seestate +sfx_brssit, // seesound +8, // reactiontime +0, // attacksound +S_BOSS_PAIN, // painstate +50, // painchance +sfx_dmpain, // painsound +S_BOSS_ATK1, // meleestate +S_BOSS_ATK1, // missilestate +S_BOSS_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_brsdth, // deathsound +8, // speed +24 * FRACUNIT, // radius +64 * FRACUNIT, // height +1000, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_BOSS_RAISE1 // raisestate +}, + +{ // MT_BRUISERSHOT +-1, // doomednum +S_BRBALL1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_firsht, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_BRBALLX1, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +15 * FRACUNIT, // speed +6 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +8, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_TRANSLUCENT, // flags killough 2/21/98 +S_NULL // raisestate +}, + +{ // MT_KNIGHT +69, // doomednum +S_BOS2_STND, // spawnstate +500, // spawnhealth +S_BOS2_RUN1, // seestate +sfx_kntsit, // seesound +8, // reactiontime +0, // attacksound +S_BOS2_PAIN, // painstate +50, // painchance +sfx_dmpain, // painsound +S_BOS2_ATK1, // meleestate +S_BOS2_ATK1, // missilestate +S_BOS2_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_kntdth, // deathsound +8, // speed +24 * FRACUNIT, // radius +64 * FRACUNIT, // height +1000, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_BOS2_RAISE1 // raisestate +}, + +{ // MT_SKULL +3006, // doomednum +S_SKULL_STND, // spawnstate +100, // spawnhealth +S_SKULL_RUN1, // seestate +0, // seesound +8, // reactiontime +sfx_sklatk, // attacksound +S_SKULL_PAIN, // painstate +256, // painchance +sfx_dmpain, // painsound +0, // meleestate +S_SKULL_ATK1, // missilestate +S_SKULL_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +8, // speed +16 * FRACUNIT, // radius +56 * FRACUNIT, // height +50, // mass +3, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_FLOAT | MF_NOGRAVITY, // flags +S_NULL // raisestate +}, + +{ // MT_SPIDER +7, // doomednum +S_SPID_STND, // spawnstate +3000, // spawnhealth +S_SPID_RUN1, // seestate +sfx_spisit, // seesound +8, // reactiontime +sfx_shotgn, // attacksound +S_SPID_PAIN, // painstate +40, // painchance +sfx_dmpain, // painsound +0, // meleestate +S_SPID_ATK1, // missilestate +S_SPID_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_spidth, // deathsound +12, // speed +128 * FRACUNIT, // radius +100 * FRACUNIT, // height +1000, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_NULL // raisestate +}, + +{ // MT_BABY +68, // doomednum +S_BSPI_STND, // spawnstate +500, // spawnhealth +S_BSPI_SIGHT, // seestate +sfx_bspsit, // seesound +8, // reactiontime +0, // attacksound +S_BSPI_PAIN, // painstate +128, // painchance +sfx_dmpain, // painsound +0, // meleestate +S_BSPI_ATK1, // missilestate +S_BSPI_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_bspdth, // deathsound +12, // speed +64 * FRACUNIT, // radius +64 * FRACUNIT, // height +600, // mass +0, // damage +sfx_bspact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_BSPI_RAISE1 // raisestate +}, + +{ // MT_CYBORG +16, // doomednum +S_CYBER_STND, // spawnstate +4000, // spawnhealth +S_CYBER_RUN1, // seestate +sfx_cybsit, // seesound +8, // reactiontime +0, // attacksound +S_CYBER_PAIN, // painstate +20, // painchance +sfx_dmpain, // painsound +0, // meleestate +S_CYBER_ATK1, // missilestate +S_CYBER_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_cybdth, // deathsound +16, // speed +40 * FRACUNIT, // radius +110 * FRACUNIT, // height +1000, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_NULL // raisestate +}, + +{ // MT_PAIN +71, // doomednum +S_PAIN_STND, // spawnstate +400, // spawnhealth +S_PAIN_RUN1, // seestate +sfx_pesit, // seesound +8, // reactiontime +0, // attacksound +S_PAIN_PAIN, // painstate +128, // painchance +sfx_pepain, // painsound +0, // meleestate +S_PAIN_ATK1, // missilestate +S_PAIN_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_pedth, // deathsound +8, // speed +31 * FRACUNIT, // radius +56 * FRACUNIT, // height +400, // mass +0, // damage +sfx_dmact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_FLOAT | MF_NOGRAVITY | MF_COUNTKILL, // flags +S_PAIN_RAISE1 // raisestate +}, + +{ // MT_WOLFSS +84, // doomednum +S_SSWV_STND, // spawnstate +50, // spawnhealth +S_SSWV_RUN1, // seestate +sfx_sssit, // seesound +8, // reactiontime +0, // attacksound +S_SSWV_PAIN, // painstate +170, // painchance +sfx_popain, // painsound +0, // meleestate +S_SSWV_ATK1, // missilestate +S_SSWV_DIE1, // deathstate +S_SSWV_XDIE1, // xdeathstate +sfx_ssdth, // deathsound +8, // speed +20 * FRACUNIT, // radius +56 * FRACUNIT, // height +100, // mass +0, // damage +sfx_posact, // activesound +MF_SOLID | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_SSWV_RAISE1 // raisestate +}, + +{ // MT_KEEN +72, // doomednum +S_KEENSTND, // spawnstate +100, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_KEENPAIN, // painstate +256, // painchance +sfx_keenpn, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_COMMKEEN, // deathstate +S_NULL, // xdeathstate +sfx_keendt, // deathsound +0, // speed +16 * FRACUNIT, // radius +72 * FRACUNIT, // height +10000000, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_SHOOTABLE | MF_COUNTKILL, // flags +S_NULL // raisestate +}, + +{ // MT_BOSSBRAIN +88, // doomednum +S_BRAIN, // spawnstate +250, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_BRAIN_PAIN, // painstate +255, // painchance +sfx_bospn, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_BRAIN_DIE1, // deathstate +S_NULL, // xdeathstate +sfx_bosdth, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +10000000, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SHOOTABLE, // flags +S_NULL // raisestate +}, + +{ // MT_BOSSSPIT +89, // doomednum +S_BRAINEYE, // spawnstate +1000, // spawnhealth +S_BRAINEYESEE, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +32 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOSECTOR, // flags +S_NULL // raisestate +}, + +{ // MT_BOSSTARGET +87, // doomednum +S_NULL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +32 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOSECTOR, // flags +S_NULL // raisestate +}, + +{ // MT_SPAWNSHOT +-1, // doomednum +S_SPAWN1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_bospit, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +10 * FRACUNIT, // speed +6 * FRACUNIT, // radius +32 * FRACUNIT, // height +100, // mass +3, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_NOCLIP, // flags +S_NULL // raisestate +}, + +{ // MT_SPAWNFIRE +-1, // doomednum +S_SPAWNFIRE1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_BARREL +2035, // doomednum +S_BAR1, // spawnstate +20, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_BEXP, // deathstate +S_NULL, // xdeathstate +sfx_barexp, // deathsound +0, // speed +10 * FRACUNIT, // radius +42 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SHOOTABLE | MF_NOBLOOD, // flags +S_NULL // raisestate +}, + +{ // MT_TROOPSHOT +-1, // doomednum +S_TBALL1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_firsht, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_TBALLX1, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +10 * FRACUNIT, // speed +6 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +3, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_HEADSHOT +-1, // doomednum +S_RBALL1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_firsht, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_RBALLX1, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +10 * FRACUNIT, // speed +6 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +5, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares, // flags +S_NULL // raisestate +}, + +{ // MT_ROCKET +-1, // doomednum +S_ROCKET, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_EXPLODE1, // deathstate +S_NULL, // xdeathstate +sfx_barexp, // deathsound +20 * FRACUNIT, // speed +11 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +20, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY, // flags +S_NULL // raisestate +}, + +{ // MT_PLASMA +-1, // doomednum +S_PLASBALL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_PLASEXP, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +25 * FRACUNIT, // speed +13 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +5, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_BFG +-1, // doomednum +S_BFGSHOT, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +0, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_BFGLAND, // deathstate +S_NULL, // xdeathstate +sfx_rxplod, // deathsound +25 * FRACUNIT, // speed +13 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +100, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_ARACHPLAZ +-1, // doomednum +S_ARACH_PLAZ, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_plasma, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_ARACH_PLEX, // deathstate +S_NULL, // xdeathstate +sfx_firxpl, // deathsound +25 * FRACUNIT, // speed +13 * FRACUNIT, // radius +8 * FRACUNIT, // height +100, // mass +5, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_MISSILE | MF_DROPOFF | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_PUFF +-1, // doomednum +S_PUFF1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_BLOOD +-1, // doomednum +S_BLOOD1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP, // flags +S_NULL // raisestate +}, + +{ // MT_TFOG +-1, // doomednum +S_TFOG, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_IFOG +-1, // doomednum +S_IFOG, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOGRAVITY | MF_TRANSLUCENT, // flags // phares +S_NULL // raisestate +}, + +{ // MT_TELEPORTMAN +14, // doomednum +S_NULL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOSECTOR, // flags +S_NULL // raisestate +}, + +{ // MT_EXTRABFG +-1, // doomednum +S_BFGEXP, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_NOGRAVITY, // flags +S_NULL // raisestate +}, + +{ // MT_MISC0 +2018, // doomednum +S_ARM1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC1 +2019, // doomednum +S_ARM2, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC2 +2014, // doomednum +S_BON1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM, // flags +S_NULL // raisestate +}, + +{ // MT_MISC3 +2015, // doomednum +S_BON2, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM, // flags +S_NULL // raisestate +}, + +{ // MT_MISC4 +5, // doomednum +S_BKEY, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_NOTDMATCH, // flags +S_NULL // raisestate +}, + +{ // MT_MISC5 +13, // doomednum +S_RKEY, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_NOTDMATCH, // flags +S_NULL // raisestate +}, + +{ // MT_MISC6 +6, // doomednum +S_YKEY, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_NOTDMATCH, // flags +S_NULL // raisestate +}, + +{ // MT_MISC7 +39, // doomednum +S_YSKULL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_NOTDMATCH, // flags +S_NULL // raisestate +}, + +{ // MT_MISC8 +38, // doomednum +S_RSKULL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_NOTDMATCH, // flags +S_NULL // raisestate +}, + +{ // MT_MISC9 +40, // doomednum +S_BSKULL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_NOTDMATCH, // flags +S_NULL // raisestate +}, + +{ // MT_MISC10 +2011, // doomednum +S_STIM, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC11 +2012, // doomednum +S_MEDI, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC12 +2013, // doomednum +S_SOUL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM | MF_TRANSLUCENT, // flags // killough 2/21/98 +S_NULL // raisestate +}, + +{ // MT_INV +2022, // doomednum +S_PINV, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM | MF_TRANSLUCENT, // flags // killough 2/21/98 +S_NULL // raisestate +}, + +{ // MT_MISC13 +2023, // doomednum +S_PSTR, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM, // flags +S_NULL // raisestate +}, + +{ // MT_INS +2024, // doomednum +S_PINS, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM | MF_TRANSLUCENT, // flags // killough 2/21/98 +S_NULL // raisestate +}, + +{ // MT_MISC14 +2025, // doomednum +S_SUIT, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC15 +2026, // doomednum +S_PMAP, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM, // flags +S_NULL // raisestate +}, + +{ // MT_MISC16 +2045, // doomednum +S_PVIS, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM, // flags +S_NULL // raisestate +}, + +{ // MT_MEGA +83, // doomednum +S_MEGA, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL | MF_COUNTITEM | MF_TRANSLUCENT, // flags // killough 2/21/98 +S_NULL // raisestate +}, + +{ // MT_CLIP +2007, // doomednum +S_CLIP, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC17 +2048, // doomednum +S_AMMO, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC18 +2010, // doomednum +S_ROCK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC19 +2046, // doomednum +S_BROK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC20 +2047, // doomednum +S_CELL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC21 +17, // doomednum +S_CELP, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC22 +2008, // doomednum +S_SHEL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC23 +2049, // doomednum +S_SBOX, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC24 +8, // doomednum +S_BPAK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC25 +2006, // doomednum +S_BFUG, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_CHAINGUN +2002, // doomednum +S_MGUN, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC26 +2005, // doomednum +S_CSAW, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC27 +2003, // doomednum +S_LAUN, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC28 +2004, // doomednum +S_PLAS, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_SHOTGUN +2001, // doomednum +S_SHOT, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_SUPERSHOTGUN +82, // doomednum +S_SHOT2, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPECIAL, // flags +S_NULL // raisestate +}, + +{ // MT_MISC29 +85, // doomednum +S_TECHLAMP, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC30 +86, // doomednum +S_TECH2LAMP, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC31 +2028, // doomednum +S_COLU, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC32 +30, // doomednum +S_TALLGRNCOL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC33 +31, // doomednum +S_SHRTGRNCOL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC34 +32, // doomednum +S_TALLREDCOL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC35 +33, // doomednum +S_SHRTREDCOL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC36 +37, // doomednum +S_SKULLCOL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC37 +36, // doomednum +S_HEARTCOL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC38 +41, // doomednum +S_EVILEYE, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC39 +42, // doomednum +S_FLOATSKULL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC40 +43, // doomednum +S_TORCHTREE, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC41 +44, // doomednum +S_BLUETORCH, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC42 +45, // doomednum +S_GREENTORCH, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC43 +46, // doomednum +S_REDTORCH, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC44 +55, // doomednum +S_BTORCHSHRT, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC45 +56, // doomednum +S_GTORCHSHRT, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC46 +57, // doomednum +S_RTORCHSHRT, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC47 +47, // doomednum +S_STALAGTITE, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC48 +48, // doomednum +S_TECHPILLAR, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC49 +34, // doomednum +S_CANDLESTIK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC50 +35, // doomednum +S_CANDELABRA, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC51 +49, // doomednum +S_BLOODYTWITCH, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +68 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC52 +50, // doomednum +S_MEAT2, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +84 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC53 +51, // doomednum +S_MEAT3, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +84 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC54 +52, // doomednum +S_MEAT4, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +68 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC55 +53, // doomednum +S_MEAT5, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +52 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC56 +59, // doomednum +S_MEAT2, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +84 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC57 +60, // doomednum +S_MEAT4, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +68 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC58 +61, // doomednum +S_MEAT3, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +52 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC59 +62, // doomednum +S_MEAT5, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +52 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC60 +63, // doomednum +S_BLOODYTWITCH, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +68 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC61 +22, // doomednum +S_HEAD_DIE6, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC62 +15, // doomednum +S_PLAY_DIE7, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC63 +18, // doomednum +S_POSS_DIE5, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC64 +21, // doomednum +S_SARG_DIE6, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC65 +23, // doomednum +S_SKULL_DIE6, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC66 +20, // doomednum +S_TROO_DIE5, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC67 +19, // doomednum +S_SPOS_DIE5, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC68 +10, // doomednum +S_PLAY_XDIE9, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC69 +12, // doomednum +S_PLAY_XDIE9, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC70 +28, // doomednum +S_HEADSONSTICK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC71 +24, // doomednum +S_GIBS, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +0 | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC72 +27, // doomednum +S_HEADONASTICK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC73 +29, // doomednum +S_HEADCANDLES, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC74 +25, // doomednum +S_DEADSTICK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC75 +26, // doomednum +S_LIVESTICK, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC76 +54, // doomednum +S_BIGTREE, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +32 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC77 +70, // doomednum +S_BBAR1, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC78 +73, // doomednum +S_HANGNOGUTS, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +88 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC79 +74, // doomednum +S_HANGBNOBRAIN, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +88 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC80 +75, // doomednum +S_HANGTLOOKDN, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +64 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC81 +76, // doomednum +S_HANGTSKULL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +64 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC82 +77, // doomednum +S_HANGTLOOKUP, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +64 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC83 +78, // doomednum +S_HANGTNOBRAIN, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +16 * FRACUNIT, // radius +64 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_SOLID | MF_SPAWNCEILING | MF_NOGRAVITY | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC84 +79, // doomednum +S_COLONGIBS, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC85 +80, // doomednum +S_SMALLPOOL, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_DECORATION, // flags +S_NULL // raisestate +}, + +{ // MT_MISC86 +81, // doomednum +S_BRAINSTEM, // spawnstate +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +20 * FRACUNIT, // radius +16 * FRACUNIT, // height +100, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_DECORATION, // flags +S_NULL // raisestate +}, + +// For use with wind and current effects +{ // MT_PUSH // phares +5001, // doomednum // | //jff 5/11/98 deconflict +S_TNT1, // spawnstate // V // with DOSDoom +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +8, // radius +8, // height +10, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_DECORATION, // flags +S_NULL // raisestate +}, + +// For use with wind and current effects +{ // MT_PULL +5002, // doomednum //jff 5/11/98 deconflict +S_TNT1, // spawnstate // with DOSDoom +1000, // spawnhealth +S_NULL, // seestate +sfx_None, // seesound +8, // reactiontime +sfx_None, // attacksound +S_NULL, // painstate +0, // painchance +sfx_None, // painsound +S_NULL, // meleestate +S_NULL, // missilestate +S_NULL, // deathstate +S_NULL, // xdeathstate +sfx_None, // deathsound +0, // speed +8, // radius +8, // height +10, // mass +0, // damage +sfx_None, // activesound +MF_NOBLOCKMAP | MF_DECORATION, // flags +S_NULL // raisestate +}, }; diff --git a/doom/src/pdoom/Doom/source/m_bbox.c b/doom/src/pdoom/Doom/source/m_bbox.c new file mode 100644 index 0000000..8a3df25 --- /dev/null +++ b/doom/src/pdoom/Doom/source/m_bbox.c @@ -0,0 +1,71 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + + * DESCRIPTION: + * Main loop menu stuff. + * Random number LUT. + * Default Config File. + * PCX Screenshots. + * + * next-hack: I don't think the description is accurate... + * Just box structure + *-----------------------------------------------------------------------------*/ + +#ifdef __GNUG__ +#pragma implementation "m_bbox.h" +#endif +#include "m_bbox.h" + +void M_ClearBox(fixed_t *box) +{ + box[BOXTOP] = box[BOXRIGHT] = INT_MIN; + box[BOXBOTTOM] = box[BOXLEFT] = INT_MAX; +} + +void M_AddToBox(fixed_t *box, fixed_t x, fixed_t y) +{ + if (x < box[BOXLEFT]) + box[BOXLEFT] = x; + else if (x > box[BOXRIGHT]) + box[BOXRIGHT] = x; + if (y < box[BOXBOTTOM]) + box[BOXBOTTOM] = y; + else if (y > box[BOXTOP]) + box[BOXTOP] = y; +} diff --git a/doom/src/pdoom/Doom/source/m_cheat.c b/doom/src/pdoom/Doom/source/m_cheat.c new file mode 100644 index 0000000..f52e9ce --- /dev/null +++ b/doom/src/pdoom/Doom/source/m_cheat.c @@ -0,0 +1,307 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + + * DESCRIPTION: + * Cheat (by doomhack?) + * + * next-hack: cheat not supported yet, need to clean up. + */ +#include "m_cheat.h" +#include "doomdef.h" +#include "d_englsh.h" +#include "p_inter.h" +#include "g_game.h" +#include "global_data.h" + +static void cheat_god(void); +static void cheat_choppers(void); +static void cheat_idkfa(void); +static void cheat_ammo(void); +static void cheat_noclip(void); +static void cheat_invincibility(void); +static void cheat_beserk(void); +static void cheat_invisibility(void); +static void cheat_map(void); +static void cheat_goggles(void); +static void cheat_exit(void); +static void cheat_rockets(void); +static void cheat_fps(void); + +typedef struct c_cheat +{ + char *name; + byte sequence[8]; + unsigned int packed_sequence; + void (*cheat_function)(void); +} c_cheat; + +#define CHEAT_PACK(a,b,c,d,e,f,g,h) ((a << 28)|(b << 24)|(c << 20)|(d << 16)|(e << 12)|(f << 8)|(g << 4)|(h)) + +#define CHEAT_SEQ(a,b,c,d,e,f,g,h) {a,b,c,d,e,f,g,h}, CHEAT_PACK(a,b,c,d,e,f,g,h) + +static const c_cheat cheat_def[] = +{ + { "Chainsaw", CHEAT_SEQ(KEYD_ALT, KEYD_UP, KEYD_UP, KEYD_LEFT, KEYD_ALT, KEYD_USE, KEYD_USE, KEYD_UP), cheat_choppers }, + { "Auto-map", CHEAT_SEQ(KEYD_DOWN, KEYD_DOWN, KEYD_LEFT, KEYD_LEFT, KEYD_RIGHT, KEYD_RIGHT, KEYD_LEFT, KEYD_UP), cheat_map }, + { "God mode", CHEAT_SEQ(KEYD_UP, KEYD_UP, KEYD_DOWN, KEYD_DOWN, KEYD_LEFT, KEYD_LEFT, KEYD_RIGHT, KEYD_RIGHT), cheat_god }, + { "Ammo & Keys", CHEAT_SEQ(KEYD_ALT, KEYD_LEFT, KEYD_USE, KEYD_RIGHT, KEYD_USE, KEYD_UP, KEYD_ALT, KEYD_UP), cheat_idkfa }, + { "Ammo", CHEAT_SEQ(KEYD_ALT, KEYD_CHGW, KEYD_ALT, KEYD_CHGW, KEYD_ALT, KEYD_UP, KEYD_UP, KEYD_LEFT), cheat_ammo }, + { "No Clipping", CHEAT_SEQ(KEYD_ALT, KEYD_DOWN, KEYD_LEFT, KEYD_RIGHT, KEYD_UP, KEYD_DOWN, KEYD_LEFT, KEYD_RIGHT), cheat_noclip }, + { "Invincibility", CHEAT_SEQ(KEYD_ALT, KEYD_CHGW, KEYD_ALT, KEYD_RIGHT, KEYD_LEFT, KEYD_RIGHT, KEYD_ALT, KEYD_ALT), cheat_invincibility }, + { "Berserk", CHEAT_SEQ(KEYD_ALT, KEYD_CHGW, KEYD_ALT, KEYD_UP, KEYD_LEFT, KEYD_ALT, KEYD_RIGHT, KEYD_ALT), cheat_beserk }, + { "Invisibility", CHEAT_SEQ(KEYD_CHGW, KEYD_ALT, KEYD_CHGW, KEYD_LEFT, KEYD_LEFT, KEYD_ALT, KEYD_LEFT, KEYD_ALT), cheat_invisibility }, + { "Lite-Amp Goggles", CHEAT_SEQ(KEYD_DOWN, KEYD_LEFT, KEYD_RIGHT, KEYD_ALT, KEYD_RIGHT, KEYD_LEFT, KEYD_LEFT, KEYD_RIGHT), cheat_goggles }, + { "Exit Level", CHEAT_SEQ(KEYD_LEFT, KEYD_LEFT, KEYD_LEFT, KEYD_ALT, KEYD_CHGW, KEYD_USE, KEYD_RIGHT, KEYD_FIRE), cheat_exit }, + //Because Goldeneye! + { "Enemy Rockets", CHEAT_SEQ(KEYD_CHGW, KEYD_ALT, KEYD_CHGW, KEYD_ALT, KEYD_RIGHT, KEYD_ALT, KEYD_ALT, KEYD_RIGHT), cheat_rockets }, + { "FPS Counter Ammo", CHEAT_SEQ(KEYD_RIGHT, KEYD_RIGHT, KEYD_ALT, KEYD_UP, KEYD_DOWN, KEYD_ALT, KEYD_LEFT, KEYD_LEFT), cheat_fps }, +}; + +static const unsigned int num_cheats = sizeof(cheat_def) / sizeof(c_cheat); + +static boolean CheckCheats(unsigned int keybuff) +{ + for (int i = 0; i < num_cheats; i++) + { + if (cheat_def[i].packed_sequence == keybuff) + { + if (cheat_def[i].cheat_function) + cheat_def[i].cheat_function(); + + return true; + } + } + + return false; +} + +boolean C_Responder(event_t *ev) +{ + if (ev->type == ev_keydown) + { + //To enable fast cheat searching without having to + //maintain buffer of keypresses, we ensure that + //cheats are 8 keys long and the key-code is less + //than 16 so they fit in 4 bits. + + //We can store a full 8 presses in a 32bit int. + + //Adding a press to the list just means shifting the + //whole thing by 4 and ORing the next press into the + //low bits. + + //We can test a cheat sequence with a simple int comparison. + + unsigned int cb = _g->cheat_buffer << 4; + cb |= ev->data1 & 0xf; + + _g->cheat_buffer = cb; + + if (CheckCheats(cb)) + return true; //eat last cheat key. + } + + return false; +} + +static void cheat_god() +{ + _g->player.cheats ^= CF_GODMODE; + + if (_g->player.cheats & CF_GODMODE) + { + _g->player.health = god_health; + + _g->player.message = STSTR_DQDON; + } + else + { + _g->player.message = STSTR_DQDOFF; + + } +} + +static void cheat_choppers() +{ + _g->player.weaponowned[wp_chainsaw] = true; + _g->player.pendingweapon = wp_chainsaw; + + P_GivePower(&_g->player, pw_invulnerability); + + _g->player.message = STSTR_CHOPPERS; +} + +static void cheat_idkfa() +{ + int i; + + player_t *plyr = &_g->player; + + if (!plyr->backpack) + { + for (i = 0; i < NUMAMMO; i++) + plyr->maxammo[i] *= 2; + + plyr->backpack = true; + } + + plyr->armorpoints = idfa_armor; // Ty 03/09/98 - deh + plyr->armortype = idfa_armor_class; // Ty 03/09/98 - deh + + // You can't own weapons that aren't in the game // phares 02/27/98 + for (i = 0; i < NUMWEAPONS; i++) + if (!(((i == wp_plasma || i == wp_bfg) && _g->gamemode == shareware) || (i == wp_supershotgun && _g->gamemode != commercial))) + plyr->weaponowned[i] = true; + + for (i = 0; i < NUMAMMO; i++) + if (i != am_cell || _g->gamemode != shareware) + plyr->ammo[i] = plyr->maxammo[i]; + + for (i = 0; i < NUMCARDS; i++) + plyr->cards[i] = true; + + plyr->message = STSTR_KFAADDED; +} + +static void cheat_ammo() +{ + int i; + player_t *plyr = &_g->player; + + if (!plyr->backpack) + { + for (i = 0; i < NUMAMMO; i++) + plyr->maxammo[i] *= 2; + + plyr->backpack = true; + } + + plyr->armorpoints = idfa_armor; // Ty 03/09/98 - deh + plyr->armortype = idfa_armor_class; // Ty 03/09/98 - deh + + // You can't own weapons that aren't in the game // phares 02/27/98 + for (i = 0; i < NUMWEAPONS; i++) + if (!(((i == wp_plasma || i == wp_bfg) && _g->gamemode == shareware) || (i == wp_supershotgun && _g->gamemode != commercial))) + plyr->weaponowned[i] = true; + + for (i = 0; i < NUMAMMO; i++) + if (i != am_cell || _g->gamemode != shareware) + plyr->ammo[i] = plyr->maxammo[i]; + + plyr->message = STSTR_FAADDED; +} + +static void cheat_noclip() +{ + _g->player.cheats ^= CF_NOCLIP; + + if (_g->player.cheats & CF_NOCLIP) + { + _g->player.message = STSTR_NCON; + } + else + { + _g->player.message = STSTR_NCOFF; + + } +} + +static void cheat_invincibility() +{ + P_GivePower(&_g->player, pw_invulnerability); +} + +static void cheat_beserk() +{ + P_GivePower(&_g->player, pw_strength); +} + +static void cheat_invisibility() +{ + P_GivePower(&_g->player, pw_invisibility); +} + +static void cheat_map() +{ + P_GivePower(&_g->player, pw_allmap); +} + +static void cheat_goggles() +{ + P_GivePower(&_g->player, pw_infrared); +} + +static void cheat_exit() +{ + G_ExitLevel(); +} + +static void cheat_rockets() +{ + _g->player.cheats ^= CF_ENEMY_ROCKETS; + + if (_g->player.cheats & CF_ENEMY_ROCKETS) + { + _g->player.health = god_health; + + _g->player.weaponowned[wp_missile] = true; + _g->player.ammo[am_misl] = _g->player.maxammo[am_misl]; + + _g->player.pendingweapon = wp_missile; + + _g->player.message = STSTR_ROCKETON; + } + else + { + _g->player.message = STSTR_ROCKETOFF; + } +} + +static void cheat_fps() +{ + _g->fps_show = !_g->fps_show; + if (_g->fps_show) + { + _g->player.message = STSTR_FPSON; + } + else + { + _g->player.message = STSTR_FPSOFF; + } +} diff --git a/doom/src/pdoom/Doom/source/m_menu.c b/doom/src/pdoom/Doom/source/m_menu.c new file mode 100644 index 0000000..fe9f4ee --- /dev/null +++ b/doom/src/pdoom/Doom/source/m_menu.c @@ -0,0 +1,1291 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * DOOM selection menu, options, episode etc. (aka Big Font menus) + * Sliders and icons. Kinda widget stuff. + * Setup Menus. + * Extended HELP screens. + * Dynamic HELP screen. + * + * next-hack: sped up a little bit, adapted for 160x128 display and modified + * save/load game menu. + *-----------------------------------------------------------------------------*/ + +#include + +#include "doomdef.h" +#include "doomstat.h" +#include "dstrings.h" +#include "d_main.h" +#include "v_video.h" +#include "w_wad.h" +#include "r_main.h" +#include "hu_stuff.h" +#include "g_game.h" +#include "s_sound.h" +#include "sounds.h" +#include "m_menu.h" +#include "m_misc.h" +#include "lprintf.h" +#include "am_map.h" +#include "i_main.h" +#include "i_system.h" +#include "i_video.h" +#include "i_sound.h" + +#include "global_data.h" + +// CPhipps - static const +const char *messageString; // ...and here is the message string! +const menu_t *currentMenu; // current menudef + +char savegamestrings[8][8]; + +static void (*messageRoutine)(int response); + +// we are going to be entering a savegame string + +#define SKULLXOFF -32 +#define LINEHEIGHT 16 + +// graphic name of skulls + +static const char skullName[2][9] = { "M_SKULL1", "M_SKULL2" }; + +// end of externs added for setup menus + +// +// PROTOTYPES +// +void M_NewGame(int choice); +void M_Episode(int choice); +void M_ChooseSkill(int choice); +void M_LoadGame(int choice); +void M_SaveGame(int choice); +void M_Options(int choice); +void M_EndGame(int choice); + +void M_ChangeMessages(int choice); +void M_ChangeAlwaysRun(int choice); +void M_SfxVol(int choice); +void M_MusicVol(int choice); +void M_Sound(int choice); + +void M_LoadSelect(int choice); +void M_SaveSelect(int choice); +void M_ReadSaveStrings(void); + +void M_DrawMainMenu(void); +void M_DrawNewGame(void); +void M_DrawEpisode(void); +void M_DrawOptions(void); +void M_DrawSound(void); +void M_DrawLoad(void); +void M_DrawSave(void); + +void M_DrawSaveLoadBorder(int x, int y); +void M_SetupNextMenu(const menu_t *menudef); +void M_DrawThermo(int x, int y, int thermWidth, int thermDot); +void M_WriteText(int x, int y, const char *string); +int M_StringWidth(const char *string); +int M_StringHeight(const char *string); +void M_StartMessage(const char *string, void *routine, boolean input); +void M_ClearMenus(void); + +short lpatchlump; +short mpatchlump; +short rpatchlump; + +///////////////////////////////////////////////////////////////////////////// +// +// DOOM MENUS +// + +///////////////////////////// +// +// MAIN MENU +// + +// main_e provides numerical values for which Big Font screen you're on + +enum +{ + newgame = 0, + loadgame, + savegame, + options, + main_end +}; + +// +// MainMenu is the definition of what the main menu Screen should look +// like. Each entry shows that the cursor can land on each item (1), the +// built-in graphic lump (i.e. "M_NGAME") that should be displayed, +// the program which takes over when an item is selected, and the hotkey +// associated with the item. +// + +static const menuitem_t MainMenu[] = +{ + { 1, "M_NGAME", M_NewGame }, + { 1, "M_OPTION", M_Options }, + { 1, "M_LOADG", M_LoadGame }, + { 1, "M_SAVEG", M_SaveGame }, +}; + +static const menu_t MainDef = +{ + main_end, // number of menu items + MainMenu, // table that defines menu items + M_DrawMainMenu, // drawing routine + 97, 64, // initial cursor position + NULL, 0, +}; + +// +// M_DrawMainMenu +// + +void M_DrawMainMenu(void) +{ + // CPhipps - patch drawing updated + V_DrawNamePatch(94, 2, 0, "M_DOOM", CR_DEFAULT, VPT_STRETCH); +} + +///////////////////////////// +// +// EPISODE SELECT +// + +// +// episodes_e provides numbers for the episode menu items. The default is +// 4, to accomodate Ultimate Doom. If the user is running anything else, +// this is accounted for in the code. +// + +enum +{ + ep1, + ep2, + ep3, + ep4, + ep_end +}; + +// The definitions of the Registered/Shareware Episodes menu + +static const menuitem_t EpisodeMenu3[] = +{ + { 1, "M_EPI1", M_Episode }, + { 1, "M_EPI2", M_Episode }, + { 1, "M_EPI3", M_Episode } +}; + +static const menu_t EpiDef3 = +{ + ep_end - 1, // # of menu items + EpisodeMenu3, // menuitem_t -> + M_DrawEpisode, // drawing routine -> + 48, 63, // x,y + &MainDef, 0, +}; + +// The definitions of the Episodes menu + +static const menuitem_t EpisodeMenu[] = +{ + { 1, "M_EPI1", M_Episode }, + { 1, "M_EPI2", M_Episode }, + { 1, "M_EPI3", M_Episode }, + { 1, "M_EPI4", M_Episode } +}; + +static const menu_t EpiDef = +{ + ep_end, // # of menu items + EpisodeMenu, // menuitem_t -> + M_DrawEpisode, // drawing routine -> + 48, 63, // x,y + &MainDef, 0, +}; + +// numerical values for the New Game menu items + +enum +{ + killthings, + toorough, + hurtme, + violence, + nightmare, + newg_end +}; + +// The definitions of the New Game menu + +static const menuitem_t NewGameMenu[] = +{ + { 1, "M_JKILL", M_ChooseSkill }, + { 1, "M_ROUGH", M_ChooseSkill }, + { 1, "M_HURT", M_ChooseSkill }, + { 1, "M_ULTRA", M_ChooseSkill }, + { 1, "M_NMARE", M_ChooseSkill } +}; + +static const menu_t NewDef = +{ + newg_end, // # of menu items + NewGameMenu, // menuitem_t -> + M_DrawNewGame, // drawing routine -> + 48, 63, // x,y + &MainDef,0, +}; + +// +// M_Episode +// + +void M_DrawEpisode(void) +{ + // CPhipps - patch drawing updated + V_DrawNamePatch(54, 38, 0, "M_EPISOD", CR_DEFAULT, VPT_STRETCH); +} + +#ifdef PDM_ONE_EPI +extern int pdm_one_epi; +#endif +void M_Episode(int choice) +{ +#ifdef PDM_ONE_EPI + if (pdm_one_epi) choice = pdm_one_epi - 1; /* Paramix: only this episode is in the WAD */ +#endif + if ((_g->gamemode == shareware) && choice) + { + M_StartMessage(SWSTRING, NULL, false); // Ty 03/27/98 - externalized + _g->itemOn = 0; + return; + } + + // Yet another hack... + if ((_g->gamemode == registered) && (choice > 2)) + { + lprintf(LO_WARN, "M_Episode: 4th episode requires UltimateDOOM\n"); + choice = 0; + } + + _g->epi = choice; + M_SetupNextMenu(&NewDef); + _g->itemOn = 2; //Set hurt me plenty as default difficulty +} + +// +// M_NewGame +// + +void M_DrawNewGame(void) +{ + // CPhipps - patch drawing updated + V_DrawNamePatch(96, 14, 0, "M_NEWG", CR_DEFAULT, VPT_STRETCH); + V_DrawNamePatch(54, 38, 0, "M_SKILL", CR_DEFAULT, VPT_STRETCH); +} + +void M_NewGame(int choice) +{ +#ifdef PDM_ONE_EPI + if (pdm_one_epi && _g->gamemode != commercial) /* Paramix: one episode in the WAD, straight to the skill */ + { + _g->epi = pdm_one_epi - 1; + M_SetupNextMenu(&NewDef); + _g->itemOn = 2; + return; + } +#endif + if (_g->gamemode == commercial) + { + M_SetupNextMenu(&NewDef); + _g->itemOn = 2; //Set hurt me plenty as default difficulty + } + else if ((_g->gamemode == shareware) || (_g->gamemode == registered)) + M_SetupNextMenu(&EpiDef3); + else + M_SetupNextMenu(&EpiDef); +} + +// CPhipps - static +static void M_VerifyNightmare(int ch) +{ + if (ch != key_enter) + return; + + G_DeferedInitNew(nightmare, _g->epi + 1, 1); +} + +void M_ChooseSkill(int choice) +{ + if (choice == nightmare) + { // Ty 03/27/98 - externalized + M_StartMessage(NIGHTMARE, M_VerifyNightmare, true); + _g->itemOn = 0; + } + else + { + G_DeferedInitNew(choice, _g->epi + 1, 1); + M_ClearMenus(); + } +} + +///////////////////////////// +// +// LOAD GAME MENU +// + +// numerical values for the Load Game slots + +enum +{ + load1, + load2, + load3, + load4, + load5, + load6, + load7, + load8, + load_end +}; + +// The definitions of the Load Game screen + +static const menuitem_t LoadMenu[] = +{ + { 1, "", M_LoadSelect }, + { 1, "", M_LoadSelect }, + { 1, "", M_LoadSelect }, + { 1, "", M_LoadSelect }, + { 1, "", M_LoadSelect }, + { 1, "", M_LoadSelect }, + { 1, "", M_LoadSelect }, + { 1, "", M_LoadSelect }, +}; + +static const menu_t LoadDef = +{ + load_end, + LoadMenu, + M_DrawLoad, + 64,34, //jff 3/15/98 move menu up + &MainDef,2, +}; + +#define LOADGRAPHIC_Y 8 + +// +// M_LoadGame & Cie. +// + +static void M_DrawSaveGames(void) +{ + #if 0 + for (int i = 0; i < load_end; i++) + { + if (i < 4) + { + M_DrawSaveLoadBorder(LoadDef.x, 27 + SAVESLOT_SPACING * i); + M_WriteText(LoadDef.x, 27 + SAVESLOT_SPACING * i, savegamestrings[i], scaleX); + } + else + { + M_DrawSaveLoadBorder(LoadDef.x + 240 / 2, 27 + SAVESLOT_SPACING * (i - 4)); + M_WriteText(LoadDef.x + 240 / 2, 27 + SAVESLOT_SPACING * (i - 4), savegamestrings[i], scaleX); + } + } + #else + for (int i = 0 ; i < load_end ; i++) + { + M_DrawSaveLoadBorder(LoadDef. x , 27 + 13 * 240 * (i + 1) / 160); + M_WriteText(LoadDef.x , 27 + 13 * 240 * (i + 1) / 160, savegamestrings[i]); + } + #endif +} + +void M_DrawLoad(void) +{ + //jff 3/15/98 use symbolic load position + // CPhipps - patch drawing updated + V_DrawNamePatch(72, LOADGRAPHIC_Y, 0, "M_LOADG", CR_DEFAULT, VPT_STRETCH); + M_DrawSaveGames(); +} + +// +// Draw border for the savegame description +// + +void M_DrawSaveLoadBorder(int x, int y) +{ + int i; + + // Note: V_DrawPatch* already support drawing data from internal flash. + V_DrawPatchNoScale(x - 8, y + 7, W_CacheLumpNum(lpatchlump)); + + for (i = 0; i < 12; i++) + { + V_DrawPatchNoScale(x, y + 7, W_CacheLumpNum(mpatchlump)); + x += 8; + } + + V_DrawPatchNoScale(x, y + 7, W_CacheLumpNum(rpatchlump)); +} + +// +// User wants to load this game +// + +void M_LoadSelect(int choice) +{ + // CPhipps - Modified so savegame filename is worked out only internal + // to g_game.c, this only passes the slot. + + G_LoadGame(choice, false); // killough 3/16/98, 5/15/98: add slot, cmd + + M_ClearMenus(); +} + +// +// Selected from DOOM menu +// + +void M_LoadGame(int choice) +{ + /* killough 5/26/98: exclude during demo recordings + * cph - unless a new demo */ + + M_SetupNextMenu(&LoadDef); + M_ReadSaveStrings(); +} + +///////////////////////////// +// +// SAVE GAME MENU +// + +// The definitions of the Save Game screen + +const static menuitem_t SaveMenu[] = +{ + { 1, "", M_SaveSelect }, + { 1, "", M_SaveSelect }, + { 1, "", M_SaveSelect }, + { 1, "", M_SaveSelect }, + { 1, "", M_SaveSelect }, + { 1, "", M_SaveSelect }, + { 1, "", M_SaveSelect }, //jff 3/15/98 extend number of slots + { 1, "", M_SaveSelect }, +}; + +const static menu_t SaveDef = +{ + load_end, // same number of slots as the Load Game screen + SaveMenu, + M_DrawSave, + 80,34, //jff 3/15/98 move menu up + &MainDef,3, +}; + +// +// M_ReadSaveStrings +// read the strings from the savegame files +// +void M_ReadSaveStrings(void) +{ + +} + +// +// M_SaveGame & Cie. +// +void M_DrawSave(void) +{ + //jff 3/15/98 use symbolic load position + // CPhipps - patch drawing updated + V_DrawNamePatch(72, LOADGRAPHIC_Y, 0, "M_SAVEG", CR_DEFAULT, VPT_STRETCH); + M_DrawSaveGames(); +} + +// +// M_Responder calls this when user is finished +// +static void M_DoSave(int slot) +{ + G_SaveGame(slot, savegamestrings[slot]); + M_ClearMenus(); +} + +// +// User wants to save. Start string input for M_Responder +// +void M_SaveSelect(int choice) +{ + _g->saveSlot = choice; + + M_DoSave(_g->saveSlot); +} + +// +// Selected from DOOM menu +// +void M_SaveGame(int choice) +{ + // killough 10/6/98: allow savegames during single-player demo playback + if (!_g->usergame && (!_g->demoplayback)) + { + M_StartMessage(SAVEDEAD, NULL, false); // Ty 03/27/98 - externalized + return; + } + + if (_g->gamestate != GS_LEVEL) + return; + + M_SetupNextMenu(&SaveDef); + M_ReadSaveStrings(); +} + +///////////////////////////// +// +// OPTIONS MENU +// + +// numerical values for the Options menu items + +enum +{ // phares 3/21/98 + endgame, + messages, + alwaysrun, + gamma, + soundvol, + opt_end +}; + +// The definitions of the Options menu + +static const menuitem_t OptionsMenu[] = +{ + // killough 4/6/98: move setup to be a sub-menu of OPTIONs + {1,"M_ENDGAM", M_EndGame}, + {1,"M_MESSG", M_ChangeMessages}, + {1,"M_ARUN", M_ChangeAlwaysRun}, + {2,"M_GAMMA", M_ChangeGamma}, + {1,"M_SVOL", M_Sound} +}; + +const static menu_t OptionsDef = +{ + opt_end, + OptionsMenu, + M_DrawOptions, + 60,37, + &MainDef,1, +}; + +// +// M_Options +// +static const char msgNames[2][9] = {"M_MSGOFF","M_MSGON"}; + + +void M_DrawOptions(void) +{ + // CPhipps - patch drawing updated + // proff/nicolas 09/20/98 -- changed for hi-res + V_DrawNamePatch(108, 15, 0, "M_OPTTTL", CR_DEFAULT, VPT_STRETCH); + + V_DrawNamePatch(OptionsDef.x + 120, OptionsDef.y+LINEHEIGHT*messages, 0, msgNames[_g->showMessages], CR_DEFAULT, VPT_STRETCH); + + V_DrawNamePatch(OptionsDef.x + 146, OptionsDef.y+LINEHEIGHT*alwaysrun, 0, msgNames[_g->alwaysRun], CR_DEFAULT, VPT_STRETCH); + + M_DrawThermo(OptionsDef.x + 158, OptionsDef.y + LINEHEIGHT * gamma + 2, 6, _g->gamma); +} + +void M_Options(int choice) +{ + M_SetupNextMenu(&OptionsDef); +} + +///////////////////////////// +// +// SOUND VOLUME MENU +// + +// numerical values for the Sound Volume menu items +// The 'empty' slots are where the sliding scales appear. + +enum +{ + sfx_vol, + sfx_empty1, + music_vol, + sfx_empty2, + sound_end +}; + +// The definitions of the Sound Volume menu + +static const menuitem_t SoundMenu[] = +{ + {2,"M_SFXVOL", M_SfxVol}, + {-1, "", 0}, + {2, "M_MUSVOL", M_MusicVol}, + {-1, "", 0} +}; + +static const menu_t SoundDef = +{ + sound_end, + SoundMenu, + M_DrawSound, + 80,64, + &OptionsDef,4, +}; + +// +// Change Sfx & Music volumes +// + +void M_DrawSound(void) +{ + // CPhipps - patch drawing updated + V_DrawNamePatch(60, 38, 0, "M_SVOL", CR_DEFAULT, VPT_STRETCH); + + M_DrawThermo(SoundDef.x, SoundDef.y + LINEHEIGHT * (sfx_vol + 1), 16, _g->snd_SfxVolume); + + M_DrawThermo(SoundDef.x, SoundDef.y + LINEHEIGHT * (music_vol + 1), 16, _g->snd_MusicVolume); +} + +void M_Sound(int choice) +{ + M_SetupNextMenu(&SoundDef); +} + +void M_SfxVol(int choice) +{ + switch (choice) + { + case 0: + if (_g->snd_SfxVolume) + _g->snd_SfxVolume--; + break; + case 1: + if (_g->snd_SfxVolume < 15) + _g->snd_SfxVolume++; + break; + } + + G_SaveSettings(); + + S_SetSfxVolume(_g->snd_SfxVolume /* *8 */); +} + +void M_MusicVol(int choice) +{ + switch (choice) + { + case 0: + if (_g->snd_MusicVolume) + _g->snd_MusicVolume--; + break; + case 1: + if (_g->snd_MusicVolume < 15) + _g->snd_MusicVolume++; + break; + } + + G_SaveSettings(); + + S_SetMusicVolume(_g->snd_MusicVolume /* *8 */); +} + +///////////////////////////// +// +// M_EndGame +// + +static void M_EndGameResponse(int ch) +{ + if (ch != key_enter) + return; + + // killough 5/26/98: make endgame quit if recording or playing back demo + if (_g->singledemo) + G_CheckDemoStatus(); + + M_ClearMenus(); + D_StartTitle(); +} + +void M_EndGame(int choice) +{ + M_StartMessage(ENDGAME, M_EndGameResponse, true); // Ty 03/27/98 - externalized +} + +///////////////////////////// +// +// Toggle messages on/off +// + +void M_ChangeMessages(int choice) +{ + // warning: unused parameter `int choice' + choice = 0; + _g->showMessages = 1 - _g->showMessages; + + if (!_g->showMessages) + _g->player.message = MSGOFF; // Ty 03/27/98 - externalized + else + _g->player.message = MSGON; // Ty 03/27/98 - externalized + + _g->message_dontfuckwithme = true; + + G_SaveSettings(); +} + +void M_ChangeAlwaysRun(int choice) +{ + // warning: unused parameter `int choice' + choice = 0; + _g->alwaysRun = 1 - _g->alwaysRun; + + if (!_g->alwaysRun) + _g->player.message = RUNOFF; // Ty 03/27/98 - externalized + else + _g->player.message = RUNON; // Ty 03/27/98 - externalized + + G_SaveSettings(); +} + +void M_ChangeGamma(int choice) +{ + switch (choice) + { + case 0: + if (_g->gamma) + _g->gamma--; + break; + case 1: + if (_g->gamma < MAX_GAMMA) + _g->gamma++; + break; + } + V_SetPalLump(_g->gamma); + V_SetPalette(0); + + G_SaveSettings(); +} + +// +// End of Original Menus +// +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////// +// +// General routines used by the Setup screens. +// + +// +// M_InitDefaults() +// +// killough 11/98: +// +// This function converts all setup menu entries consisting of cfg +// variable names, into pointers to the corresponding default[] +// array entry. var.name becomes converted to var.def. +// + +static void M_InitDefaults(void) +{ + +} + +// +// End of Setup Screens. +// +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// +// +// M_Responder +// +// Examines incoming keystrokes and button pushes and determines some +// action based on the state of the system. +// + +boolean M_Responder(event_t *ev) +{ + int ch; + + ch = -1; // will be changed to a legit char if we're going to use it here + + // Mouse input processing removed + + // Process keyboard input + + if (ev->type == ev_keydown) + { + ch = ev->data1; // phares 4/11/98: + } // down so you can get at the !,#, + + if (ch == -1) + return false; // we can't use the event here + + // Take care of any messages that need input + + if (_g->messageToPrint) + { + if (_g->messageNeedsInput == true && !(ch == ' ' || ch == 'n' || ch == 'y' || ch == key_escape || ch == key_fire || ch == key_enter)) // phares + return false; + + _g->menuactive = _g->messageLastMenuActive; + _g->messageToPrint = 0; + if (messageRoutine) + messageRoutine(ch); + + _g->menuactive = false; + S_StartSound(NULL, sfx_swtchx); + return true; + } + + // Pop-up Main menu? + + if (!_g->menuactive) + { + if (ch == key_escape) // phares + { + M_StartControlPanel(); + S_StartSound(NULL, sfx_swtchn); + return true; + } + return false; + } + + // From here on, these navigation keys are used on the BIG FONT menus + // like the Main Menu. + + if (ch == key_menu_down) // phares 3/7/98 + { + do + { + if (_g->itemOn + 1 > currentMenu->numitems - 1) + _g->itemOn = 0; + else + _g->itemOn++; + S_StartSound(NULL, sfx_pstop); + } while (currentMenu->menuitems[_g->itemOn].status == -1); + return true; + } + + if (ch == key_menu_up) // phares 3/7/98 + { + do + { + if (!_g->itemOn) + _g->itemOn = currentMenu->numitems - 1; + else + _g->itemOn--; + S_StartSound(NULL, sfx_pstop); + } while (currentMenu->menuitems[_g->itemOn].status == -1); + return true; + } + + if (ch == key_menu_left) // phares 3/7/98 + { + if (currentMenu->menuitems[_g->itemOn].routine && currentMenu->menuitems[_g->itemOn].status == 2) + { + S_StartSound(NULL, sfx_stnmov); + currentMenu->menuitems[_g->itemOn].routine(0); + } + return true; + } + + if (ch == key_menu_right) // phares 3/7/98 + { + if (currentMenu->menuitems[_g->itemOn].routine && currentMenu->menuitems[_g->itemOn].status == 2) + { + S_StartSound(NULL, sfx_stnmov); + currentMenu->menuitems[_g->itemOn].routine(1); + } + return true; + } + + if (ch == key_menu_enter) // phares 3/7/98 + { + if (currentMenu->menuitems[_g->itemOn].routine && currentMenu->menuitems[_g->itemOn].status) + { + if (currentMenu->menuitems[_g->itemOn].status == 2) + { + currentMenu->menuitems[_g->itemOn].routine(1); // right arrow + S_StartSound(NULL, sfx_stnmov); + } + else + { + S_StartSound(NULL, sfx_pistol); + currentMenu->menuitems[_g->itemOn].routine(_g->itemOn); + } + } + //jff 3/24/98 remember last skill selected + // killough 10/98 moved to skill-specific functions + return true; + } + + if (ch == key_menu_escape) // phares 3/7/98 + { + M_ClearMenus(); + S_StartSound(NULL, sfx_swtchx); + return true; + } + + //Allow being able to go back in menus ~Kippykip + if (ch == key_fire) // phares 3/7/98 + { + //If the prevMenu == NULL (Such as main menu screen), then just get out of the menu altogether + if (currentMenu->prevMenu == NULL) + { + M_ClearMenus(); + } + else //Otherwise, change to the parent menu and match the row used to get there. + { + short previtemOn = currentMenu->previtemOn; //Temporarily store this so after menu change, we store the last row it was on. + M_SetupNextMenu(currentMenu->prevMenu); + _g->itemOn = previtemOn; + } + S_StartSound(NULL, sfx_swtchx); + return true; + } + + return false; +} + +// +// End of M_Responder +// +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// +// +// General Routines +// +// This displays the Main menu and gets the menu screens rolling. +// Plus a variety of routines that control the Big Font menu display. +// Plus some initialization for game-dependant situations. + +void M_StartControlPanel(void) +{ + // intro might call this repeatedly + + if (_g->menuactive) + return; + + //jff 3/24/98 make default skill menu choice follow -skill or defaultskill + //from command line or config file + // + // killough 10/98: + // Fix to make "always floating" with menu selections, and to always follow + // defaultskill, instead of -skill. + + _g->menuactive = 1; + currentMenu = &MainDef; // JDC +} + +// +// M_Drawer +// Called after the view has been rendered, +// but before it has been blitted. +// +// killough 9/29/98: Significantly reformatted source +// + +void M_Drawer(void) +{ + // Horiz. & Vertically center string and print it. + // killough 9/29/98: simplified code, removed 40-character width limit + if (_g->messageToPrint) + { + /* cph - strdup string to writable memory */ + char *ms = strdup(messageString); + char *p = ms; + + int y = 80 - M_StringHeight(messageString)/2; + while (*p) + { + char *string = p, c; + while ((c = *p) && *p != '\n') + p++; + *p = 0; + + M_WriteText(120 - M_StringWidth(string) / 2, y, string); + y += hu_font[0]->height; + if ((*p = c)) + p++; + } + free(ms); + } + else if (_g->menuactive) + { + int x, y, max, i; + + if (currentMenu->routine) + currentMenu->routine(); // call Draw routine + + // DRAW MENU + + x = currentMenu->x; + y = currentMenu->y; + max = currentMenu->numitems; + + for (i = 0; i < max; i++) + { + if (currentMenu->menuitems[i].name[0]) + V_DrawNamePatch(x, y, 0, currentMenu->menuitems[i].name, CR_DEFAULT, VPT_STRETCH); + y += LINEHEIGHT; + } + + // DRAW SKULL + + // CPhipps - patch drawing updated + V_DrawNamePatch(x + SKULLXOFF, currentMenu->y - 5 + _g->itemOn*LINEHEIGHT,0, + skullName[_g->whichSkull], CR_DEFAULT, VPT_STRETCH); + } +} + +// +// M_ClearMenus +// +// Called when leaving the menu screens for the real world + +void M_ClearMenus(void) +{ + _g->menuactive = 0; + _g->itemOn = 0; +} + +// +// M_SetupNextMenu +// +void M_SetupNextMenu(const menu_t *menudef) +{ + currentMenu = menudef; + _g->itemOn = 0; +} + +///////////////////////////// +// +// M_Ticker +// +void M_Ticker(void) +{ + if (--_g->skullAnimCounter <= 0) + { + _g->whichSkull ^= 1; + _g->skullAnimCounter = 8; + } +} + +///////////////////////////// +// +// Message Routines +// + +void M_StartMessage(const char *string, void *routine, boolean input) +{ + _g->messageLastMenuActive = _g->menuactive; + _g->messageToPrint = 1; + messageString = string; + messageRoutine = routine; + _g->messageNeedsInput = input; + _g->menuactive = true; + return; +} + +///////////////////////////// +// +// Thermometer Routines +// + +// +// M_DrawThermo draws the thermometer graphic for Mouse Sensitivity, +// Sound Volume, etc. +// +// proff/nicolas 09/20/98 -- changed for hi-res +// CPhipps - patch drawing updated +// +void M_DrawThermo(int x, int y, int thermWidth, int thermDot) +{ + int xx; + int i; + /* + * Modification By Barry Mead to allow the Thermometer to have vastly + * larger ranges. (the thermWidth parameter can now have a value as + * large as 200. Modified 1-9-2000 Originally I used it to make + * the sensitivity range for the mouse better. It could however also + * be used to improve the dynamic range of music and sound affect + * volume controls for example. + */ + int horizScaler; //Used to allow more thermo range for mouse sensitivity. + thermWidth = (thermWidth > 200) ? 200 : thermWidth; //Clamp to 200 max + horizScaler = (thermWidth > 23) ? (200 / thermWidth) : 8; //Dynamic range + xx = x; + + int thermm_lump = W_GetNumForName("M_THERMM"); + + V_DrawNamePatch(xx, y, 0, "M_THERML", CR_DEFAULT, VPT_STRETCH); + + xx += 8; + for (i = 0; i < thermWidth; i++) + { + V_DrawNumPatch(xx, y, 0, thermm_lump, CR_DEFAULT, VPT_STRETCH); + xx += horizScaler; + } + + xx += (8 - horizScaler); /* make the right end look even */ + + V_DrawNamePatch(xx, y, 0, "M_THERMR", CR_DEFAULT, VPT_STRETCH); + V_DrawNamePatch((x + 8) + thermDot * horizScaler, y, 0, "M_THERMO", CR_DEFAULT, VPT_STRETCH); +} + +///////////////////////////// +// +// String-drawing Routines +// + +// +// Find string width from hu_font chars +// + +int M_StringWidth(const char *string) +{ + int i, c, w = 0; + for (i = 0; (size_t) i < strlen(string); i++) + w += (c = toupper(string[i]) - HU_FONTSTART) < 0 || c >= HU_FONTSIZE ? 4 : hu_font[c]->width; + return w; +} + +// +// Find string height from hu_font chars +// + +int M_StringHeight(const char *string) +{ + int i, h, height = h = hu_font[0]->height; + for (i = 0; string[i]; i++) // killough 1/31/98 + if (string[i] == '\n') + h += height; + return h; +} + +// +// Write a string using the hu_font +// +void M_WriteText (int x,int y,const char* string) +{ + int w; + const char *ch; + int c; + int cx; + int cy; + + ch = string; + cx = x; + cy = y; + + while (1) + { + c = *ch++; + if (!c) + break; + if (c == '\n') + { + cx = x; + cy += 12; + continue; + } + + c = toupper(c) - HU_FONTSTART; + if (c < 0 || c >= HU_FONTSIZE) + { + cx += 4; + continue; + } + + w = hu_font[c]->width; + V_DrawPatchNoScale(cx, cy, hu_font[c]); + cx+=w; + } +} + +///////////////////////////// +// +// Initialization Routines to take care of one-time setup +// + +// +// M_Init +// +void M_Init(void) +{ + M_InitDefaults(); // killough 11/98 + currentMenu = &MainDef; + _g->menuactive = 0; + _g->whichSkull = 0; + _g->skullAnimCounter = 10; + _g->messageToPrint = 0; + messageString = NULL; + _g->messageLastMenuActive = _g->menuactive; + + G_UpdateSaveGameStrings(); + // + lpatchlump = W_GetNumForName("M_LSLEFT"); + mpatchlump = W_GetNumForName("M_LSCNTR"); + rpatchlump = W_GetNumForName("M_LSRGHT"); + +} + +// +// End of General Routines +// +///////////////////////////////////////////////////////////////////////////// diff --git a/doom/src/pdoom/Doom/source/m_random.c b/doom/src/pdoom/Doom/source/m_random.c new file mode 100644 index 0000000..df1a750 --- /dev/null +++ b/doom/src/pdoom/Doom/source/m_random.c @@ -0,0 +1,97 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Random number LUT. + * + * 1/19/98 killough: Rewrote random number generator for better randomness, + * while at the same time maintaining demo sync and backward compatibility. + * + * 2/16/98 killough: Made each RNG local to each control-equivalent block, + * to reduce the chances of demo sync problems. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "m_random.h" +#include "lprintf.h" + +#include "global_data.h" + +// +// M_Random +// Returns a 0-255 number +// next-hack: why using 18 rows of 14 numbers and then 4 ? 16 by 16 was bad? +static const unsigned char rndtable[256] = +{ + 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66 , + 74, 21, 211, 47, 80, 242, 154, 27, 205, 128, 161, 89, 77, 36 , + 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188 , + 52, 140, 202, 120, 68, 145, 62, 70, 184, 190, 91, 197, 152, 224 , + 149, 104, 25, 178, 252, 182, 202, 182, 141, 197, 4, 81, 181, 242 , + 145, 42, 39, 227, 156, 198, 225, 193, 219, 93, 122, 175, 249, 0 , + 175, 143, 70, 239, 46, 246, 163, 53, 163, 109, 168, 135, 2, 235 , + 25, 92, 20, 145, 138, 77, 69, 166, 78, 176, 173, 212, 166, 113 , + 94, 161, 41, 50, 239, 49, 111, 164, 70, 60, 2, 37, 171, 75 , + 136, 156, 11, 56, 42, 146, 138, 229, 73, 146, 77, 61, 98, 196 , + 135, 106, 63, 197, 195, 86, 96, 203, 113, 101, 170, 247, 181, 113 , + 80, 250, 108, 7, 255, 237, 129, 226, 79, 107, 112, 166, 103, 241 , + 24, 223, 239, 120, 198, 58, 60, 82, 128, 3, 184, 66, 143, 224 , + 145, 224, 81, 206, 163, 45, 63, 90, 168, 114, 59, 33, 159, 95 , + 28, 139, 123, 98, 125, 196, 15, 70, 194, 253, 54, 14, 109, 226 , + 71, 17, 161, 93, 186, 87, 244, 138, 20, 52, 123, 251, 26, 36 , + 17, 46, 52, 231, 232, 76, 31, 221, 84, 37, 216, 165, 212, 106 , + 197, 242, 98, 43, 39, 175, 254, 145, 190, 84, 118, 222, 187, 136 , + 120, 163, 236, 249 +}; +// Which one is deterministic? +int P_Random(const char *file, int line, const char *func) +{ + _g->prndindex = (_g->prndindex + 1) & 0xff; + if (PRND_SCAN && _g->gametic >= MIN_DEMO_GAMETIC_TO_PRINT) + { + // get only last path + int l = strlen(file); + file += l - 1; + while (*file != '\\') + file--; + demodbgprintf ("File %s, Line %d, func %s MR %x\r\n", file, line, func, _g->prndindex); + } + return rndtable[_g->prndindex]; +} + +int M_Random(void) +{ + _g->rndindex = (_g->rndindex + 1) & 0xff; + return rndtable[_g->rndindex]; +} + +void M_ClearRandom(void) +{ + _g->rndindex = _g->prndindex = 0; +} diff --git a/doom/src/pdoom/Doom/source/p_ceilng.c b/doom/src/pdoom/Doom/source/p_ceilng.c new file mode 100644 index 0000000..96d77cf --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_ceilng.c @@ -0,0 +1,467 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Ceiling aninmation (lowering, crushing, raising) + * + * next-hack: modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "r_main.h" +#include "p_spec.h" +#include "p_tick.h" +#include "s_sound.h" +#include "sounds.h" + +#include "global_data.h" + +///////////////////////////////////////////////////////////////// +// +// Ceiling action routine and linedef type handler +// +///////////////////////////////////////////////////////////////// + +// +// T_MoveCeiling +// +// Action routine that moves ceilings. Called once per tick. +// +// Passed a ceiling_t structure that contains all the info about the move. +// see P_SPEC.H for fields. No return. +// +// jff 02/08/98 all cases with labels beginning with gen added to support +// generalized line type behaviors. +// +void T_MoveCeiling(ceiling_t *ceiling) +{ + result_e res; + + switch (ceiling->direction) + { + case 0: + // If ceiling in stasis, do nothing + break; + + case 1: + // Ceiling is moving up + res = T_MovePlane(ceiling->sector, ceiling->speed, ceiling->topheight, + false, 1, ceiling->direction); + + // if not a silent crusher, make moving sound + if (!(_g->leveltime & 7)) + { + switch (ceiling->type) + { + case silentCrushAndRaise: + case genSilentCrusher: + break; + default: + S_StartSound2(&ceiling->sector->soundorg, sfx_stnmov); + break; + } + } + + // handle reaching destination height + if (res == pastdest) + { + switch (ceiling->type) + { + // plain movers are just removed + case raiseToHighest: + case genCeiling: + P_RemoveActiveCeiling(ceiling); + break; + + // movers with texture change, change the texture then get removed + case genCeilingChgT: + case genCeilingChg0: + ceiling->sector->special = ceiling->newspecial; + //jff 3/14/98 transfer old special field as well + ceiling->sector->oldspecial = ceiling->oldspecial; + case genCeilingChg: + ceiling->sector->ceilingpic = ceiling->texture; + P_RemoveActiveCeiling(ceiling); + break; + + // crushers reverse direction at the top + case silentCrushAndRaise: + S_StartSound2(&ceiling->sector->soundorg, sfx_pstop); + case genSilentCrusher: + case genCrusher: + case fastCrushAndRaise: + case crushAndRaise: + ceiling->direction = -1; + break; + + default: + break; + } + } + break; + + case -1: + // Ceiling moving down + res = T_MovePlane(ceiling->sector, ceiling->speed, ceiling->bottomheight, ceiling->crush, 1, ceiling->direction); + + // if not silent crusher type make moving sound + if (!(_g->leveltime & 7)) + { + switch (ceiling->type) + { + case silentCrushAndRaise: + case genSilentCrusher: + break; + default: + S_StartSound2(&ceiling->sector->soundorg, sfx_stnmov); + } + } + + // handle reaching destination height + if (res == pastdest) + { + switch (ceiling->type) + { + // 02/09/98 jff change slow crushers' speed back to normal + // start back up + case genSilentCrusher: + case genCrusher: + if (ceiling->oldspeed < CEILSPEED * 3) + ceiling->speed = ceiling->oldspeed; + ceiling->direction = 1; //jff 2/22/98 make it go back up! + break; + + // make platform stop at bottom of all crusher strokes + // except generalized ones, reset speed, start back up + case silentCrushAndRaise: + S_StartSound2(&ceiling->sector->soundorg, sfx_pstop); + case crushAndRaise: + ceiling->speed = CEILSPEED; + case fastCrushAndRaise: + ceiling->direction = 1; + break; + + // in the case of ceiling mover/changer, change the texture + // then remove the active ceiling + case genCeilingChgT: + case genCeilingChg0: + ceiling->sector->special = ceiling->newspecial; + //jff add to fix bug in special transfers from changes + ceiling->sector->oldspecial = ceiling->oldspecial; + case genCeilingChg: + ceiling->sector->ceilingpic = ceiling->texture; + P_RemoveActiveCeiling(ceiling); + break; + + // all other case, just remove the active ceiling + case lowerAndCrush: + case lowerToFloor: + case lowerToLowest: + case lowerToMaxFloor: + case genCeiling: + P_RemoveActiveCeiling(ceiling); + break; + + default: + break; + } + } + else // ( res != pastdest ) + { + // handle the crusher encountering an obstacle + if (res == crushed) + { + switch (ceiling->type) + { + //jff 02/08/98 slow down slow crushers on obstacle + case genCrusher: + case genSilentCrusher: + if (ceiling->oldspeed < CEILSPEED * 3) + ceiling->speed = CEILSPEED / 8; + break; + case silentCrushAndRaise: + case crushAndRaise: + case lowerAndCrush: + ceiling->speed = CEILSPEED / 8; + break; + + default: + break; + } + } + } + break; + } +} + +// +// EV_DoCeiling +// +// Move a ceiling up/down or start a crusher +// +// Passed the linedef activating the function and the type of function desired +// returns true if a thinker started +// +int EV_DoCeiling(const line_t *line, ceiling_e type) +{ + int secnum; + int rtn; + sector_t *sec; + ceiling_t *ceiling; + + secnum = -1; + rtn = 0; + + // Reactivate in-stasis ceilings...for certain types. + // This restarts a crusher after it has been stopped + switch (type) + { + case fastCrushAndRaise: + case silentCrushAndRaise: + case crushAndRaise: + //jff 4/5/98 return if activated + rtn = P_ActivateInStasisCeiling(line); + default: + break; + } + + // affects all sectors with the same tag as the linedef + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + // if ceiling already moving, don't start a second function on it + if (P_SectorActive(ceiling_special, sec)) //jff 2/22/98 + continue; + + // create a new ceiling thinker + rtn = 1; + ceiling = Z_Malloc(sizeof(*ceiling), PU_LEVSPEC, 0); + memset(ceiling, 0, sizeof(*ceiling)); + P_AddThinker(&ceiling->thinker); + sec->ceilingdata_sptr = getShortPtr(ceiling); //jff 2/22/98 + ceiling->thinker.function = T_MoveCeiling; + ceiling->sector = sec; + ceiling->crush = false; + + // setup ceiling structure according to type of function + switch (type) + { + case fastCrushAndRaise: + ceiling->crush = true; + ceiling->topheight = sec->ceilingheight; + ceiling->bottomheight = sec->floorheight + (8 * FRACUNIT); + ceiling->direction = -1; + ceiling->speed = CEILSPEED * 2; + break; + + case silentCrushAndRaise: + case crushAndRaise: + ceiling->crush = true; + ceiling->topheight = sec->ceilingheight; + case lowerAndCrush: + case lowerToFloor: + ceiling->bottomheight = sec->floorheight; + if (type != lowerToFloor) + ceiling->bottomheight += 8 * FRACUNIT; + ceiling->direction = -1; + ceiling->speed = CEILSPEED; + break; + + case raiseToHighest: + ceiling->topheight = P_FindHighestCeilingSurrounding(sec); + ceiling->direction = 1; + ceiling->speed = CEILSPEED; + break; + + case lowerToLowest: + ceiling->bottomheight = P_FindLowestCeilingSurrounding(sec); + ceiling->direction = -1; + ceiling->speed = CEILSPEED; + break; + + case lowerToMaxFloor: + ceiling->bottomheight = P_FindHighestFloorSurrounding(sec); + ceiling->direction = -1; + ceiling->speed = CEILSPEED; + break; + + default: + break; + } + + // add the ceiling to the active list + ceiling->tag = sec->tag; + ceiling->type = type; + P_AddActiveCeiling(ceiling); + } + return rtn; +} + +////////////////////////////////////////////////////////////////////// +// +// Active ceiling list primitives +// +///////////////////////////////////////////////////////////////////// + +// jff 2/22/98 - modified Lee's plat code to work for ceilings +// +// The following were all rewritten by Lee Killough +// to use the new structure which places no limits +// on active ceilings. It also avoids spending as much +// time searching for active ceilings. Previously a +// fixed-size array was used, with NULL indicating +// empty entries, while now a doubly-linked list +// is used. + +// +// P_ActivateInStasisCeiling() +// +// Reactivates all stopped crushers with the right tag +// +// Passed the line reactivating the crusher +// Returns true if a ceiling reactivated +// +//jff 4/5/98 return if activated +int P_ActivateInStasisCeiling(const line_t *line) +{ + ceilinglist_t *cl; + int rtn = 0; + + for (cl = _g->activeceilings; cl; cl = cl->next) + { + ceiling_t *ceiling = cl->ceiling; + if (ceiling->tag == line->tag && ceiling->direction == 0) + { + ceiling->direction = ceiling->olddirection; + ceiling->thinker.function = T_MoveCeiling; + //jff 4/5/98 return if activated + rtn = 1; + } + } + return rtn; +} + +// +// EV_CeilingCrushStop() +// +// Stops all active ceilings with the right tag +// +// Passed the linedef stopping the ceilings +// Returns true if a ceiling put in stasis +// +int EV_CeilingCrushStop(const line_t *line) +{ + int rtn = 0; + + ceilinglist_t *cl; + for (cl = _g->activeceilings; cl; cl = cl->next) + { + ceiling_t *ceiling = cl->ceiling; + if (ceiling->direction != 0 && ceiling->tag == line->tag) + { + ceiling->olddirection = ceiling->direction; + ceiling->direction = 0; + ceiling->thinker.function = NULL; + rtn = 1; + } + } + return rtn; +} + +// +// P_AddActiveCeiling() +// +// Adds a ceiling to the head of the list of active ceilings +// +// Passed the ceiling motion structure +// Returns nothing +// +void P_AddActiveCeiling(ceiling_t *ceiling) +{ + ceilinglist_t *old_head = _g->activeceilings; + + ceilinglist_t *list = Z_Malloc(sizeof *list, PU_LEVEL, (void** ) &_g->activeceilings); + list->ceiling = ceiling; + ceiling->list = list; + + if ((list->next = old_head)) + list->next->prev = &list->next; + + list->prev = (ceilinglist_t**) old_head; +} + +// +// P_RemoveActiveCeiling() +// +// Removes a ceiling from the list of active ceilings +// +// Passed the ceiling motion structure +// Returns nothing +// +void P_RemoveActiveCeiling(ceiling_t *ceiling) +{ + ceilinglist_t *list = ceiling->list; + ceiling->sector->ceilingdata_sptr = 0; //jff 2/22/98 + + P_RemoveThinker(&ceiling->thinker); + + if ((list->prev && (*list->prev = list->next))) + list->next->prev = list->prev; + + free(list); +} + +// +// P_RemoveAllActiveCeilings() +// +// Removes all ceilings from the active ceiling list +// +// Passed nothing, returns nothing +// +void P_RemoveAllActiveCeilings(void) +{ + while (_g->activeceilings) + { + ceilinglist_t *next = _g->activeceilings->next; + free(_g->activeceilings); + _g->activeceilings = next; + } +} diff --git a/doom/src/pdoom/Doom/source/p_doors.c b/doom/src/pdoom/Doom/source/p_doors.c new file mode 100644 index 0000000..1118351 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_doors.c @@ -0,0 +1,679 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * + * DESCRIPTION: + * Door animation code (opening/closing) + * + * next-hack: modified code to work with short pointers. + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "p_spec.h" +#include "p_tick.h" +#include "s_sound.h" +#include "sounds.h" +#include "r_main.h" +#include "dstrings.h" +#include "lprintf.h" + +#include "global_data.h" + +/////////////////////////////////////////////////////////////// +// +// Door action routines, called once per tick +// +/////////////////////////////////////////////////////////////// + +// +// T_VerticalDoor +// +// Passed a door structure containing all info about the door. +// See P_SPEC.H for fields. +// Returns nothing. +// +// jff 02/08/98 all cases with labels beginning with gen added to support +// generalized line type behaviors. + +void T_VerticalDoor(vldoor_t *door) +{ + result_e res; + + // Is the door waiting, going up, or going down? + switch (door->direction) + { + case 0: + // Door is waiting + if (!--door->topcountdown) // downcount and check + { + switch (door->type) + { + case blazeRaise: + case genBlazeRaise: + door->direction = -1; // time to go back down + S_StartSound2(&door->sector->soundorg, sfx_bdcls); + break; + + case normal: + case genRaise: + door->direction = -1; // time to go back down + S_StartSound2(&door->sector->soundorg, sfx_dorcls); + break; + + case close30ThenOpen: + case genCdO: + door->direction = 1; // time to go back up + S_StartSound2(&door->sector->soundorg, sfx_doropn); + break; + + case genBlazeCdO: + door->direction = 1; // time to go back up + S_StartSound2(&door->sector->soundorg, sfx_bdopn); + break; + + default: + break; + } + } + break; + + case 2: + // Special case for sector type door that opens in 5 mins + if (!--door->topcountdown) // 5 minutes up? + { + switch (door->type) + { + case raiseIn5Mins: + door->direction = 1; // time to raise then + door->type = normal; // door acts just like normal 1 DR door now + S_StartSound2(&door->sector->soundorg, sfx_doropn); + break; + + default: + break; + } + } + break; + + case -1: + // Door is moving down + res = T_MovePlane(door->sector, door->speed, door->sector->floorheight, + false, 1, door->direction); + + /* killough 10/98: implement gradual lighting effects */ + // e6y: "Tagged doors don't trigger special lighting" handled wrong + // http://sourceforge.net/tracker/index.php?func=detail&aid=1411400&group_id=148658&atid=772943 + // Old code: if (door->lighttag && door->topheight - door->sector->floorheight) + if (door->lighttag && door->topheight - door->sector->floorheight) + EV_LightTurnOnPartway(door->line, FixedDiv(door->sector->ceilingheight - door->sector->floorheight, door->topheight - door->sector->floorheight)); + + // handle door reaching bottom + if (res == pastdest) + { + switch (door->type) + { + // regular open and close doors are all done, remove them + case blazeRaise: + case blazeClose: + case genBlazeRaise: + case genBlazeClose: + door->sector->ceilingdata_sptr = 0; //jff 2/22/98 + P_RemoveThinker(&door->thinker); // unlink and free + // killough 4/15/98: remove double-closing sound of blazing doors + break; + + case normal: + case dclose: + case genRaise: + case genClose: + door->sector->ceilingdata_sptr = 0; //jff 2/22/98 + P_RemoveThinker(&door->thinker); // unlink and free + break; + + // close then open doors start waiting + case close30ThenOpen: + door->direction = 0; + door->topcountdown = TICRATE * 30; + break; + + case genCdO: + case genBlazeCdO: + door->direction = 0; + door->topcountdown = door->topwait; // jff 5/8/98 insert delay + break; + + default: + break; + } + } + /* jff 1/31/98 turn lighting off in tagged sectors of manual doors + * killough 10/98: replaced with gradual lighting code + */ + else if (res == crushed) // handle door meeting obstruction on way down + { + switch (door->type) + { + case genClose: + case genBlazeClose: + case blazeClose: + case dclose: // Close types do not bounce, merely wait + break; + + case blazeRaise: + case genBlazeRaise: + door->direction = 1; + S_StartSound2(&door->sector->soundorg, sfx_bdopn); + break; + + default: // other types bounce off the obstruction + door->direction = 1; + S_StartSound2(&door->sector->soundorg, sfx_doropn); + break; + } + } + break; + + case 1: + // Door is moving up + res = T_MovePlane(door->sector, door->speed, door->topheight, + false, 1, door->direction); + + /* killough 10/98: implement gradual lighting effects */ + // e6y: "Tagged doors don't trigger special lighting" handled wrong + // http://sourceforge.net/tracker/index.php?func=detail&aid=1411400&group_id=148658&atid=772943 + // Old code: if (door->lighttag && door->topheight - door->sector->floorheight) + if (door->lighttag && door->topheight - door->sector->floorheight) + EV_LightTurnOnPartway(door->line, FixedDiv(door->sector->ceilingheight - door->sector->floorheight, door->topheight - door->sector->floorheight)); + + // handle door reaching the top + if (res == pastdest) + { + switch (door->type) + { + case blazeRaise: // regular open/close doors start waiting + case normal: + case genRaise: + case genBlazeRaise: + door->direction = 0; // wait at top with delay + door->topcountdown = door->topwait; + break; + + case close30ThenOpen: // close and close/open doors are done + case blazeOpen: + case dopen: + case genBlazeOpen: + case genOpen: + case genCdO: + case genBlazeCdO: + door->sector->ceilingdata_sptr = 0; //jff 2/22/98 + P_RemoveThinker(&door->thinker); // unlink and free + break; + + default: + break; + } + } + break; + } +} + +/////////////////////////////////////////////////////////////// +// +// Door linedef handlers +// +/////////////////////////////////////////////////////////////// + +// +// EV_DoLockedDoor +// +// Handle opening a tagged locked door +// +// Passed the line activating the door, the type of door, +// and the thing that activated the line +// Returns true if a thinker created +// +int EV_DoLockedDoor(const line_t *line, vldoor_e type, mobj_t *thing) +{ + player_t *p; + + // only players can open locked doors + p = getMobjPlayer(thing); + if (!p) + return 0; + + // check type of linedef, and if key is possessed to open it + switch (LN_SPECIAL(line)) + { + case 99: // Blue Lock + case 133: + if (!p->cards[it_bluecard] && !p->cards[it_blueskull]) + { + p->message = PD_BLUEO; // Ty 03/27/98 - externalized + S_StartSound(p->mo, sfx_oof); // killough 3/20/98 + return 0; + } + break; + + case 134: // Red Lock + case 135: + if (!p->cards[it_redcard] && !p->cards[it_redskull]) + { + p->message = PD_REDO; // Ty 03/27/98 - externalized + S_StartSound(p->mo, sfx_oof); // killough 3/20/98 + return 0; + } + break; + + case 136: // Yellow Lock + case 137: + if (!p->cards[it_yellowcard] && !p->cards[it_yellowskull]) + { + p->message = PD_YELLOWO; // Ty 03/27/98 - externalized + S_StartSound(p->mo, sfx_oof); // killough 3/20/98 + return 0; + } + break; + } + + // got the key, so open the door + return EV_DoDoor(line, type); +} + +// +// EV_DoDoor +// +// Handle opening a tagged door +// +// Passed the line activating the door and the type of door +// Returns true if a thinker created +// +int EV_DoDoor(const line_t *line, vldoor_e type) +{ + int secnum, rtn; + sector_t *sec; + vldoor_t *door; + + secnum = -1; + rtn = 0; + + // open all doors with the same tag as the activating line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + // if the ceiling already moving, don't start the door action + if (P_SectorActive(ceiling_special, sec)) //jff 2/22/98 + continue; + + // new door thinker + rtn = 1; + door = Z_Malloc(sizeof(*door), PU_LEVSPEC, 0); + memset(door, 0, sizeof(*door)); + P_AddThinker(&door->thinker); + sec->ceilingdata_sptr = getShortPtr(door); //jff 2/22/98 + + door->thinker.function = T_VerticalDoor; + door->sector = sec; + door->type = type; + door->topwait = VDOORWAIT; + door->speed = VDOORSPEED; + door->line = line; // jff 1/31/98 remember line that triggered us + door->lighttag = 0; /* killough 10/98: no light effects with tagged doors */ + + // setup door parameters according to type of door + switch (type) + { + case blazeClose: + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + door->direction = -1; + door->speed = VDOORSPEED * 4; + S_StartSound2(&door->sector->soundorg, sfx_bdcls); + break; + + case dclose: + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + door->direction = -1; + S_StartSound2(&door->sector->soundorg, sfx_dorcls); + break; + + case close30ThenOpen: + door->topheight = sec->ceilingheight; + door->direction = -1; + S_StartSound2(&door->sector->soundorg, sfx_dorcls); + break; + + case blazeRaise: + case blazeOpen: + door->direction = 1; + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + door->speed = VDOORSPEED * 4; + if (door->topheight != sec->ceilingheight) + S_StartSound2(&door->sector->soundorg, sfx_bdopn); + break; + + case normal: + case dopen: + door->direction = 1; + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + if (door->topheight != sec->ceilingheight) + S_StartSound2(&door->sector->soundorg, sfx_doropn); + break; + + default: + break; + } + } + return rtn; +} + +// +// EV_VerticalDoor +// +// Handle opening a door manually, no tag value +// +// Passed the line activating the door and the thing activating it +// Returns true if a thinker created +// +// jff 2/12/98 added int return value, fixed all returns +// +int EV_VerticalDoor(const line_t *line, mobj_t *thing) +{ + player_t *player; + //int secnum; + sector_t *sec; + vldoor_t *door; + + // Check for locks + player = getMobjPlayer(thing); + + switch (LN_SPECIAL(line)) + { + case 26: // Blue Lock + case 32: + if (!player) + return 0; + if (!player->cards[it_bluecard] && !player->cards[it_blueskull]) + { + player->message = PD_BLUEK; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return 0; + } + break; + + case 27: // Yellow Lock + case 34: + if (!player) + return 0; + if (!player->cards[it_yellowcard] && !player->cards[it_yellowskull]) + { + player->message = PD_YELLOWK; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return 0; + } + break; + + case 28: // Red Lock + case 33: + if (!player) + return 0; + if (!player->cards[it_redcard] && !player->cards[it_redskull]) + { + player->message = PD_REDK; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return 0; + } + break; + + default: + break; + } + + // if the wrong side of door is pushed, give oof sound + if (line->sidenum[1] == NO_INDEX) // killough + { + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return 0; + } + + // get the sector on the second side of activating linedef + sec = &_g->sectors[_g->sides[line->sidenum[1]].sector_num]; + //secnum = sec-_g->sectors; + + /* if door already has a thinker, use it + * cph 2001/04/05 - + * Ok, this is a disaster area. We're assuming that sec->ceilingdata + * is a vldoor_t! What if this door is controlled by both DR lines + * and by switches? I don't know how to fix that. + * Secondly, original Doom didn't distinguish floor/lighting/ceiling + * actions, so we need to do the same in demo compatibility mode. + */ + door = getSectorCeilingData(sec); + + /* If this is a repeatable line, and the door is already moving, then we can just reverse the current action. Note that in prboom 2.3.0 I erroneously removed the if-this-is-repeatable check, hence the prboom_4_compatibility clause below (foolishly assumed that already moving implies repeatable - but it could be moving due to another switch, e.g. lv19-509) */ + if (door && ((LN_SPECIAL(line) == 1) || (LN_SPECIAL(line) == 117) || (LN_SPECIAL(line) == 26) || (LN_SPECIAL(line) == 27) || (LN_SPECIAL(line) == 28))) + { + /* For old demos we have to emulate the old buggy behavior and + * mess up non-T_VerticalDoor actions. + */ + if (door->thinker.function == T_VerticalDoor) + { + /* cph - we are writing outval to door->direction iff it is non-zero */ + signed int outval = 0; + + /* An already moving repeatable door which is being re-pressed, or a + * monster is trying to open a closing door - so change direction + * DEMOSYNC: we only read door->direction now if it really is a door. + */ + if (door->thinker.function == T_VerticalDoor && door->direction == -1) + { + outval = 1; /* go back up */ + } + else if (player) + { + outval = -1; /* go back down */ + } + + /* Write this to the thinker. In demo compatibility mode, we might be + * overwriting a field of a non-vldoor_t thinker - we need to add any + * other thinker types here if any demos depend on specific fields + * being corrupted by this. + */ + if (outval) + { + if (door->thinker.function == T_VerticalDoor) + { + door->direction = outval; + } + else if (door->thinker.function == T_PlatRaise) + { + plat_t *p = (plat_t*) door; + p->wait = outval; + } + else + { + lprintf(LO_DEBUG, "EV_VerticalDoor: unknown thinker.function in thinker corruption emulation"); + } + + return 1; + } + } + /* Either we're in prboom >=v2.3 and it's not a door, or it's a door but + * we're a monster and don't want to shut it; exit with no action. + */ + return 0; + } + + // emit proper sound + switch (LN_SPECIAL(line)) + { + case 117: // blazing door raise + case 118: // blazing door open + S_StartSound2(&sec->soundorg, sfx_bdopn); + break; + + default: // normal or locked door sound + S_StartSound2(&sec->soundorg, sfx_doropn); + break; + } + + // new door thinker + door = Z_Malloc(sizeof(*door), PU_LEVSPEC, 0); + memset(door, 0, sizeof(*door)); + P_AddThinker(&door->thinker); + sec->ceilingdata_sptr = getShortPtr(door); //jff 2/22/98 + door->thinker.function = T_VerticalDoor; + door->sector = sec; + door->direction = 1; + door->speed = VDOORSPEED; + door->topwait = VDOORWAIT; + door->line = line; // jff 1/31/98 remember line that triggered us + + /* killough 10/98: use gradual lighting changes if nonzero tag given */ + door->lighttag = line->tag; + + // set the type of door from the activating linedef type + switch (LN_SPECIAL(line)) + { + case 1: + case 26: + case 27: + case 28: + door->type = normal; + break; + + case 31: + case 32: + case 33: + case 34: + door->type = dopen; + LN_SPECIAL(line) = 0; + break; + + case 117: // blazing door raise + door->type = blazeRaise; + door->speed = VDOORSPEED * 4; + break; + case 118: // blazing door open + door->type = blazeOpen; + LN_SPECIAL(line) = 0; + door->speed = VDOORSPEED * 4; + break; + + default: + door->lighttag = 0; // killough 10/98 + break; + } + + // find the top and bottom of the movement range + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + return 1; +} + +/////////////////////////////////////////////////////////////// +// +// Sector type door spawners +// +/////////////////////////////////////////////////////////////// + +// +// P_SpawnDoorCloseIn30() +// +// Spawn a door that closes after 30 seconds (called at level init) +// +// Passed the sector of the door, whose type specified the door action +// Returns nothing +// +void P_SpawnDoorCloseIn30(sector_t *sec) +{ + vldoor_t *door; + + door = Z_Malloc(sizeof(*door), PU_LEVSPEC, 0); + + memset(door, 0, sizeof(*door)); + P_AddThinker(&door->thinker); + + sec->ceilingdata_sptr = getShortPtr(door); //jff 2/22/98 + sec->special = 0; + + door->thinker.function = T_VerticalDoor; + door->sector = sec; + door->direction = 0; + door->type = normal; + door->speed = VDOORSPEED; + door->topcountdown = 30 * 35; + door->line = NULL; // jff 1/31/98 remember line that triggered us + door->lighttag = 0; /* killough 10/98: no lighting changes */ +} + +// +// P_SpawnDoorRaiseIn5Mins() +// +// Spawn a door that opens after 5 minutes (called at level init) +// +// Passed the sector of the door, whose type specified the door action +// Returns nothing +// +void P_SpawnDoorRaiseIn5Mins(sector_t *sec, int secnum) +{ + vldoor_t *door; + + door = Z_Malloc(sizeof(*door), PU_LEVSPEC, 0); + + memset(door, 0, sizeof(*door)); + P_AddThinker(&door->thinker); + + sec->ceilingdata_sptr = getShortPtr(door); //jff 2/22/98 + sec->special = 0; + + door->thinker.function = T_VerticalDoor; + door->sector = sec; + door->direction = 2; + door->type = raiseIn5Mins; + door->speed = VDOORSPEED; + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + door->topwait = VDOORWAIT; + door->topcountdown = 5 * 60 * 35; + door->line = NULL; // jff 1/31/98 remember line that triggered us + door->lighttag = 0; /* killough 10/98: no lighting changes */ +} diff --git a/doom/src/pdoom/Doom/source/p_enemy.c b/doom/src/pdoom/Doom/source/p_enemy.c new file mode 100644 index 0000000..0f6523e --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_enemy.c @@ -0,0 +1,2197 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Enemy thinking, AI. + * Action Pointer Functions + * that are associated with states/frames. + * + * next-hack: modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "m_random.h" +#include "r_main.h" +#include "p_maputl.h" +#include "p_map.h" +#include "p_setup.h" +#include "p_spec.h" +#include "s_sound.h" +#include "sounds.h" +#include "p_inter.h" +#include "g_game.h" +#include "p_enemy.h" +#include "p_tick.h" +#include "m_bbox.h" +#include "lprintf.h" + +#include "global_data.h" + +const int distfriend = 128; + +typedef enum +{ + DI_EAST, + DI_NORTHEAST, + DI_NORTH, + DI_NORTHWEST, + DI_WEST, + DI_SOUTHWEST, + DI_SOUTH, + DI_SOUTHEAST, + DI_NODIR, + NUMDIRS +} dirtype_t; + +static void P_NewChaseDir(mobj_t *actor); + +// +// ENEMY THINKING +// Enemies are allways spawned +// with targetplayer = -1, threshold = 0 +// Most monsters are spawned unaware of all players, +// but some can be made preaware +// + +// +// Called by P_NoiseAlert. +// Recursively traverse adjacent sectors, +// sound blocking lines cut off traversal. +// +// killough 5/5/98: reformatted, cleaned up + +static void P_RecursiveSound(sector_t *sec, int soundblocks, mobj_t *soundtarget) +{ + // int i; + short i; + // wake up all monsters in this sector + if (sec->validcount == _g->validcount && sec->soundtraversed <= soundblocks + 1) + return; // already flooded + + sec->validcount = _g->validcount; + sec->soundtraversed = soundblocks + 1; + //P_SetTarget(&sec->soundtarget, soundtarget); + sec->soundtarget_sptr = getShortPtr(soundtarget); + for (i = 0; i < sec->linecount; i++) + { + sector_t *other; +// const line_t *check = sec->lines[i]; + const line_t *check = getSectorLineByIndex(sec, i); + + if (!(check->flags & ML_TWOSIDED)) + continue; + + P_LineOpening(check); + + if (_g->openrange <= 0) + continue; // closed door + + other = &_g->sectors[_g->sides[check->sidenum[&_g->sectors[_g->sides[check->sidenum[0]].sector_num] == sec]].sector_num]; + + if (!(check->flags & ML_SOUNDBLOCK)) + P_RecursiveSound(other, soundblocks, soundtarget); + else if (!soundblocks) + P_RecursiveSound(other, 1, soundtarget); + } +} + +// +// P_NoiseAlert +// If a monster yells at a player, +// it will alert other monsters to the player. +// +void P_NoiseAlert(mobj_t *target, mobj_t *emitter) +{ + _g->validcount++; + P_RecursiveSound(getMobjSubsector(emitter)->sector, 0, target); +} + +// +// P_CheckMeleeRange +// + +static boolean P_CheckMeleeRange(mobj_t *actor) +{ + mobj_t *pl = getTarget(actor); + if (!pl) + return false; + fixed_t dist = P_AproxDistance (pl->x-actor->x, pl->y-actor->y); + + if (dist >= MELEERANGE - 20 * FRACUNIT + getMobjInfo(pl)->radius) + return false; + + if (! P_CheckSight (actor, pl) ) + return false; + + return true; + + /* next-hack: removed this unreadable sh*t + + return // killough 7/18/98: friendly monsters don't attack other friends + pl && !(actor->flags & pl->flags & MF_FRIEND ) && + (P_AproxDistance(pl->x - actor->x, pl->y - actor->y) < + MELEERANGE - 20 * FRACUNIT + getMobjInfo(pl)->radius) + && P_CheckSight(actor, getTarget(actor)); + + */ +} + +// +// P_HitFriend() +// +// killough 12/98 +// This function tries to prevent shooting at friends + +static boolean P_HitFriend(mobj_t *actor) +{ + return (actor->flags & MF_FRIEND ) && actor->target_sptr + && (P_AimLineAttack(actor, R_PointToAngle2(actor->x, actor->y, getTarget(actor)->x, getTarget(actor)->y), P_AproxDistance(actor->x - getTarget(actor)->x, actor->y - getTarget(actor)->y), 0), _g->linetarget) && _g->linetarget != getTarget(actor) && !((_g->linetarget->flags ^ actor->flags) & MF_FRIEND ); +} + +// +// P_CheckMissileRange +// +static boolean P_CheckMissileRange(mobj_t *actor) +{ + fixed_t dist; + + if (!P_CheckSight(actor, getTarget(actor))) + return false; + + if (actor->flags & MF_JUSTHIT) + { // the target just hit the enemy, so fight back! + actor->flags &= ~MF_JUSTHIT; + + /* killough 7/18/98: no friendly fire at corpses + * killough 11/98: prevent too much infighting among friends + * cph - yikes, talk about fitting everything on one line... */ + if (demo_compatibility) + return true; + return !(actor->flags & MF_FRIEND ) || (getTarget(actor)->health > 0 && (!(getTarget(actor)->flags & MF_FRIEND ) || ( + getMobjPlayer(getTarget(actor)) ? true : !(getTarget(actor)->flags & MF_JUSTHIT ) && P_Random(__FILE__, __LINE__, __FUNCTION__) > 128))); + } + + /* killough 7/18/98: friendly monsters don't attack other friendly + * monsters or players (except when attacked, and then only once) + */ +#warning compatibility + // if (actor->flags & getTarget(actor)->flags & MF_FRIEND) + // return false; + + if (actor->reactiontime) + return false; // do not attack yet + + // OPTIMIZE: get this from a global checksight + dist = P_AproxDistance(actor->x - getTarget(actor)->x, actor->y - getTarget(actor)->y) - 64 * FRACUNIT; + + if (!getMobjInfo(actor)->meleestate) + dist -= 128 * FRACUNIT; // no melee attack, so fire more + + dist >>= FRACBITS; + + if (actor->type == MT_VILE) + if (dist > 14 * 64) + return false; // too far away + + if (actor->type == MT_UNDEAD) + { + if (dist < 196) + return false; // close for fist attack + dist >>= 1; + } + + if (actor->type == MT_CYBORG || actor->type == MT_SPIDER || actor->type == MT_SKULL) + dist >>= 1; + + if (dist > 200) + dist = 200; + + if (actor->type == MT_CYBORG && dist > 160) + dist = 160; + + if (P_Random(__FILE__, __LINE__, __FUNCTION__) < dist) + return false; + + if (!demo_compatibility && P_HitFriend(actor)) + return false; + + return true; +} + +/* + * P_IsOnLift + * + * killough 9/9/98: + * + * Returns true if the object is on a lift. Used for AI, + * since it may indicate the need for crowded conditions, + * or that a monster should stay on the lift for a while + * while it goes up or down. + */ + +static boolean P_IsOnLift(const mobj_t *actor) +{ + sector_t *sec = getMobjSubsector((mobj_t*) actor)->sector; + + // Short-circuit: it's on a lift which is active. + if (sec->floordata_sptr && ((thinker_t*) getSectorFloorData(sec))->function == T_PlatRaise) + return true; + + return false; +} + +/* + * P_IsUnderDamage + * + * killough 9/9/98: + * + * Returns nonzero if the object is under damage based on + * their current position. Returns 1 if the damage is moderate, + * -1 if it is serious. Used for AI. + */ + +static int P_IsUnderDamage(mobj_t *actor) +{ + const struct msecnode_s *seclist; + const ceiling_t *cl; // Crushing ceiling + int dir = 0; + for (seclist = getTouchingSectorList(actor); seclist; + seclist = getMsecnodeTNext(seclist)) + if ((cl = getSectorCeilingData(getMsecnodeSector(seclist))) && cl->thinker.function == T_MoveCeiling) + dir |= cl->direction; + return dir; +} + +// +// P_Move +// Move in the current direction, +// returns false if the move is blocked. +// + +static const fixed_t xspeed[8] = +{ FRACUNIT, 47000, 0, -47000, -FRACUNIT, -47000, 0, 47000 }; +static const fixed_t yspeed[8] = +{ 0, 47000, FRACUNIT, 47000, 0, -47000, -FRACUNIT, -47000 }; + +static boolean P_Move(mobj_t *actor, boolean dropoff) /* killough 9/12/98 */ +{ + fixed_t tryx, tryy, deltax, deltay, origx, origy; + boolean try_ok; + int speed; + + if (actor->movedir == DI_NODIR) + return false; + +#ifdef RANGECHECK + if ((unsigned)actor->movedir >= 8) + I_Error ("P_Move: Weird actor->movedir!"); +#endif + + speed = getMobjInfo(actor)->speed; + + tryx = (origx = actor->x) + (deltax = speed * xspeed[actor->movedir]); + tryy = (origy = actor->y) + (deltay = speed * yspeed[actor->movedir]); + + try_ok = P_TryMove(actor, tryx, tryy, dropoff); + + if (!try_ok) + { // open any specials + int good; + + if ((actor->flags & MF_FLOAT ) && _g->floatok) + { + if (actor->z < _g->tmfloorz) // must adjust height + actor->z += FLOATSPEED; + else + actor->z -= FLOATSPEED; + + actor->flags |= MF_INFLOAT; + + return true; + } + + if (!_g->numspechit) + return false; + + actor->movedir = DI_NODIR; + + /* if the special is not a door that can be opened, return false + * + * killough 8/9/98: this is what caused monsters to get stuck in + * doortracks, because it thought that the monster freed itself + * by opening a door, even if it was moving towards the doortrack, + * and not the door itself. + * + * killough 9/9/98: If a line blocking the monster is activated, + * return true 90% of the time. If a line blocking the monster is + * not activated, but some other line is, return false 90% of the + * time. A bit of randomness is needed to ensure it's free from + * lockups, but for most cases, it returns the correct result. + * + * Do NOT simply return false 1/4th of the time (causes monsters to + * back out when they shouldn't, and creates secondary stickiness). + */ + + for (good = false; _g->numspechit--;) + if (P_UseSpecialLine(actor, _g->spechit[_g->numspechit], 0)) + good |= _g->spechit[_g->numspechit] == _g->blockline ? 1 : 2; + + /* cph - compatibility maze here + * Boom v2.01 and orig. Doom return "good" + * Boom v2.02 and LxDoom return good && (P_Random(pr_trywalk)&3) + * MBF plays even more games + */ + #warning changed to add compatibility +// if (!good) + return good; +// return ((P_Random(__FILE__, __LINE__) >= 230) ^ (good & 1)); + } + else + actor->flags &= ~MF_INFLOAT; + + /* killough 11/98: fall more slowly, under gravity, if felldown==true */ + if (!(actor->flags & MF_FLOAT ) && (!_g->felldown)) + actor->z = actor->floorz; + + return true; +} + +/* + * P_SmartMove + * + * killough 9/12/98: Same as P_Move, except smarter + */ + +static boolean P_SmartMove(mobj_t *actor) +{ + if (demo_compatibility) + return P_Move(actor, false); + mobj_t *target = getTarget(actor); + int on_lift, dropoff = false, under_damage; + + /* killough 9/12/98: Stay on a lift if target is on one */ + on_lift = target && target->health > 0 && getMobjSubsector(target)->sector->tag == getMobjSubsector(actor)->sector->tag && P_IsOnLift(actor); + + if (!P_Move(actor, dropoff)) + return false; + + under_damage = P_IsUnderDamage(actor); + + // killough 9/9/98: avoid crushing ceilings or other damaging areas + if ((on_lift && P_Random(__FILE__, __LINE__, __FUNCTION__) < 230 && // Stay on lift + !P_IsOnLift(actor)) || (!under_damage && // Get away from damage + (under_damage = P_IsUnderDamage(actor)) && (under_damage < 0 || P_Random(__FILE__, __LINE__, __FUNCTION__) < 200))) + actor->movedir = DI_NODIR; // avoid the area (most of the time anyway) + + return true; +} + +// +// TryWalk +// Attempts to move actor on +// in its current (ob->moveangle) direction. +// If blocked by either a wall or an actor +// returns FALSE +// If move is either clear or blocked only by a door, +// returns TRUE and sets... +// If a door is in the way, +// an OpenDoor call is made to start it opening. +// + +static boolean P_TryWalk(mobj_t *actor) +{ + if (!P_SmartMove(actor)) + return false; + actor->movecount = P_Random(__FILE__, __LINE__, __FUNCTION__) & 15; + return true; +} + +// +// P_DoNewChaseDir +// +// killough 9/8/98: +// +// Most of P_NewChaseDir(), except for what +// determines the new direction to take +// + +static void P_DoNewChaseDir(mobj_t *actor, fixed_t deltax, fixed_t deltay) +{ + int xdir, ydir, tdir; + int olddir = actor->movedir; + int turnaround = olddir; + + if (turnaround != DI_NODIR) // find reverse direction + turnaround ^= 4; + + xdir = deltax > 10 * FRACUNIT ? DI_EAST : + deltax < -10 * FRACUNIT ? DI_WEST : DI_NODIR; + + ydir = deltay < -10 * FRACUNIT ? DI_SOUTH : + deltay > 10 * FRACUNIT ? DI_NORTH : DI_NODIR; + + // try direct route + if (xdir != DI_NODIR && ydir != DI_NODIR && turnaround != (actor->movedir = + deltay < 0 ? deltax > 0 ? DI_SOUTHEAST : DI_SOUTHWEST : + deltax > 0 ? DI_NORTHEAST : DI_NORTHWEST) && P_TryWalk(actor)) + return; + + // try other directions + if (P_Random(__FILE__, __LINE__, __FUNCTION__) > 200 || D_abs(deltay) > D_abs(deltax)) + tdir = xdir, xdir = ydir, ydir = tdir; + + if ((xdir == turnaround ? xdir = DI_NODIR : xdir) != DI_NODIR && (actor->movedir = xdir, P_TryWalk(actor))) + return; // either moved forward or attacked + + if ((ydir == turnaround ? ydir = DI_NODIR : ydir) != DI_NODIR && (actor->movedir = ydir, P_TryWalk(actor))) + return; + + // there is no direct path to the player, so pick another direction. + if (olddir != DI_NODIR && (actor->movedir = olddir, P_TryWalk(actor))) + return; + + // randomly determine direction of search + if (P_Random(__FILE__, __LINE__, __FUNCTION__) & 1) + { + for (tdir = DI_EAST; tdir <= DI_SOUTHEAST; tdir++) + if (tdir != turnaround && (actor->movedir = tdir, P_TryWalk(actor))) + return; + } + else + { + for (tdir = DI_SOUTHEAST; tdir >= DI_EAST; tdir--) + if (tdir != turnaround && (actor->movedir = tdir, P_TryWalk(actor))) + return; + } + + if ((actor->movedir = turnaround) != DI_NODIR && !P_TryWalk(actor)) + actor->movedir = DI_NODIR; +} + +// +// killough 11/98: +// +// Monsters try to move away from tall dropoffs. +// +// In Doom, they were never allowed to hang over dropoffs, +// and would remain stuck if involuntarily forced over one. +// This logic, combined with p_map.c (P_TryMove), allows +// monsters to free themselves without making them tend to +// hang over dropoffs. + +static boolean PIT_AvoidDropoff(const line_t *line) +{ + if (LN_BACKSECTOR(line) && // Ignore one-sided linedefs + _g->tmbbox[BOXRIGHT] > line->bbox[BOXLEFT] && _g->tmbbox[BOXLEFT] < line->bbox[BOXRIGHT] && _g->tmbbox[BOXTOP] > line->bbox[BOXBOTTOM] && // Linedef must be contacted + _g->tmbbox[BOXBOTTOM] < line->bbox[BOXTOP] && P_BoxOnLineSide(_g->tmbbox, line) == -1) + { + fixed_t front = LN_FRONTSECTOR(line)->floorheight; + fixed_t back = LN_BACKSECTOR(line)->floorheight; + angle_t angle; + + // The monster must contact one of the two floors, + // and the other must be a tall dropoff (more than 24). + + if (back == _g->floorz && front < _g->floorz - FRACUNIT * 24) + angle = R_PointToAngle2(0, 0, line->dx, line->dy); // front side dropoff + else if (front == _g->floorz && back < _g->floorz - FRACUNIT * 24) + angle = R_PointToAngle2(line->dx, line->dy, 0, 0); // back side dropoff + else + return true; + + // Move away from dropoff at a standard speed. + // Multiple contacted linedefs are cumulative (e.g. hanging over corner) + _g->dropoff_deltax -= finesine[angle >> ANGLETOFINESHIFT] * 32; + _g->dropoff_deltay += finecosine[angle >> ANGLETOFINESHIFT] * 32; + } + return true; +} + +// +// Driver for above +// + +static fixed_t P_AvoidDropoff(mobj_t *actor) +{ + int yh = ((_g->tmbbox[BOXTOP] = actor->y + (getMobjRadius(actor))) - _g->bmaporgy) >> MAPBLOCKSHIFT; + int yl = ((_g->tmbbox[BOXBOTTOM] = actor->y - (getMobjRadius(actor))) - _g->bmaporgy) >> MAPBLOCKSHIFT; + int xh = ((_g->tmbbox[BOXRIGHT] = actor->x + (getMobjRadius(actor))) - _g->bmaporgx) >> MAPBLOCKSHIFT; + int xl = ((_g->tmbbox[BOXLEFT] = actor->x - (getMobjRadius(actor))) - _g->bmaporgx) >> MAPBLOCKSHIFT; + int bx, by; + + _g->floorz = actor->z; // remember floor height + + _g->dropoff_deltax = _g->dropoff_deltay = 0; + + // check lines + + _g->validcount++; + for (bx = xl; bx <= xh; bx++) + for (by = yl; by <= yh; by++) + P_BlockLinesIterator(bx, by, PIT_AvoidDropoff); // all contacted lines + + return _g->dropoff_deltax | _g->dropoff_deltay; // Non-zero if movement prescribed +} + +// +// P_NewChaseDir +// +// killough 9/8/98: Split into two functions +// + +static void P_NewChaseDir(mobj_t *actor) +{ + mobj_t *target = getTarget(actor); + fixed_t deltax = target->x - actor->x; + fixed_t deltay = target->y - actor->y; + + // killough 8/8/98: sometimes move away from target, keeping distance + // + // 1) Stay a certain distance away from a friend, to avoid being in their way + // 2) Take advantage over an enemy without missiles, by keeping distance + + actor->strafecount = 0; + if (!demo_compatibility) + { + if (actor->floorz - actor->dropoffz > FRACUNIT * 24 && actor->z <= actor->floorz && !(actor->flags & (MF_DROPOFF | MF_FLOAT )) && P_AvoidDropoff(actor)) /* Move away from dropoff */ + { + P_DoNewChaseDir(actor, _g->dropoff_deltax, _g->dropoff_deltay); + + // If moving away from dropoff, set movecount to 1 so that + // small steps are taken to get monster away from dropoff. + + actor->movecount = 1; + return; + } + else + { + fixed_t dist = P_AproxDistance(deltax, deltay); + + // Move away from friends when too close, except + // in certain situations (e.g. a crowded lift) + + if ((actor->flags & target->flags & MF_FRIEND ) && distfriend << FRACBITS > dist && !P_IsOnLift(target) && !P_IsUnderDamage(actor)) + { + deltax = -deltax, deltay = -deltay; + } + + } + } + P_DoNewChaseDir(actor, deltax, deltay); + // If strafing, set movecount to strafecount so that old Doom + // logic still works the same, except in the strafing part + if (actor->strafecount) + actor->movecount = actor->strafecount; +} + +// +// P_IsVisible +// +// killough 9/9/98: whether a target is visible to a monster +// + +static boolean P_IsVisible(mobj_t *actor, mobj_t *mo, boolean allaround) +{ + fixed_t dist = P_AproxDistance(mo->x - actor->x, mo->y - actor->y); + + //Fix for icon of sin being blind, and having the others have bad depth perception ~Kippykip +// if ((dist > LOOKRANGE) && actor->type != MT_BOSSSPIT && actor->type != MT_CYBORG && actor->type != MT_SPIDER) +// return false; + + if (!allaround) + { + angle_t an = R_PointToAngle2(actor->x, actor->y, mo->x, mo->y) - actor->angle; + + if (an > ANG90 && an < ANG270 && dist > MELEERANGE) + return false; + } + return P_CheckSight(actor, mo); +} + +// +// P_LookForPlayers +// If allaround is false, only look 180 degrees in front. +// Returns true if a player is targeted. +// + +static boolean P_LookForPlayers(mobj_t *actor, boolean allaround) +{ + player_t *player; + // TODO: restore multiplayer + if (_g->playeringame) + { + player = &_g->player; + + if (player->health <= 0) + return false; // dead + + if (!P_IsVisible(actor, player->mo, allaround)) + return false; + + //P_SetTarget(&actor->target, player->mo); + actor->target_sptr = getShortPtr(player->mo); + /* killough 9/9/98: give monsters a threshold towards getting players + * (we don't want it to be too easy for a player with dogs :) + */ + actor->threshold = 60; + + return true; + } + + return false; +} + +// +// P_LookForTargets +// +// killough 9/5/98: look for targets to go after, depending on kind of monster +// + +static boolean P_LookForTargets(mobj_t *actor, int allaround) +{ + return P_LookForPlayers(actor, allaround); +} + +// +// A_KeenDie +// DOOM II special, map 32. +// Uses special tag 666. +// +void A_KeenDie(mobj_t *mo) +{ + thinker_t *th; + line_t junk; + + A_Fall(mo); + + // scan the remaining thinkers to see if all Keens are dead + + for (th = getThinkerNext(&thinkercap); th != &thinkercap; th=getThinkerNext(th)) + if (th->function == P_MobjThinker) + { + mobj_t *mo2 = (mobj_t *) th; + if (mo2 != mo && mo2->type == mo->type && mo2->health > 0) + return; // other Keen not dead + } + + junk.tag = 666; + EV_DoDoor(&junk, dopen); +} + +// +// ACTION ROUTINES +// + +// +// A_Look +// Stay in state until a player is sighted. +// + +void A_Look(mobj_t *actor) +{ + mobj_t *targ = getSectorSoundTarget(getMobjSubsector(actor)->sector); + actor->threshold = 0; // any shot will wake up + + /* killough 7/18/98: + * Friendly monsters go after other monsters first, but + * also return to player, without attacking them, if they + * cannot find any targets. A marine's best friend :) + */ + actor->pursuecount = 0; + + boolean seen = false; + + if (targ && (targ->flags & MF_SHOOTABLE )) + { + //actor->target = targ; + actor->target_sptr = getShortPtr(targ); + if (actor->flags & MF_AMBUSH) + { + demodbgprintf("Ambush\r\n"); + fixed_t dist = P_AproxDistance(actor->x - targ->x, actor->y - targ->y); + + if (P_CheckSight(actor, getTarget(actor))) + { + seen = true; + demodbgprintf("Seen CS\r\n"); + } + } + else + { + seen = true; + demodbgprintf("Seen not ambush\r\n"); + + } + } + if (!seen) + demodbgprintf("Check for player "); + if ((!seen) && (!P_LookForPlayers(actor, false))) + { + demodbgprintf("not found player\r\n"); + return; + } + + // go into chase state + demodbgprintf("Seen 1\r\n"); + if (getMobjInfo(actor)->seesound) + { + int sound; + switch (getMobjInfo(actor)->seesound) + { + case sfx_posit1: + case sfx_posit2: + case sfx_posit3: + sound = sfx_posit1 + P_Random(__FILE__, __LINE__, __FUNCTION__) % 3; + break; + + case sfx_bgsit1: + case sfx_bgsit2: + sound = sfx_bgsit1 + P_Random(__FILE__, __LINE__, __FUNCTION__) % 2; + break; + + default: + sound = getMobjInfo(actor)->seesound; + break; + } + if (actor->type == MT_SPIDER || actor->type == MT_CYBORG) + S_StartSound(NULL, sound); // full volume + else + S_StartSound(actor, sound); + } + P_SetMobjState(actor, getMobjInfo(actor)->seestate); +} + +// +// A_Chase +// Actor has a melee attack, +// so it tries to close as fast as possible +// + +void A_Chase(mobj_t *actor) +{ + if (actor->reactiontime) + actor->reactiontime--; + + if (actor->threshold) + { /* modify target threshold */ + if (!getTarget(actor) || getTarget(actor)->health <= 0) + actor->threshold = 0; + else + actor->threshold--; + } + + /* turn towards movement direction if not there yet + * killough 9/7/98: keep facing towards target if strafing or backing out + */ + + if (actor->strafecount) + A_FaceTarget(actor); + else if (actor->movedir < 8) + { + int delta = (actor->angle &= (7 << 29)) - (actor->movedir << 29); + if (delta > 0) + actor->angle -= ANG90 / 2; + else if (delta < 0) + actor->angle += ANG90 / 2; + } + + if (!getTarget(actor) || !(getTarget(actor)->flags & MF_SHOOTABLE )) + { + if (!P_LookForTargets(actor, true)) // look for a new target + P_SetMobjState(actor, getMobjInfo(actor)->spawnstate); // no new target + return; + } + + // do not attack twice in a row + if (actor->flags & MF_JUSTATTACKED) + { + actor->flags &= ~MF_JUSTATTACKED; + if (_g->gameskill != sk_nightmare) + P_NewChaseDir(actor); + return; + } + + // check for melee attack + if (getMobjInfo(actor)->meleestate && P_CheckMeleeRange(actor)) + { + if (getMobjInfo(actor)->attacksound) + S_StartSound(actor, getMobjInfo(actor)->attacksound); + + P_SetMobjState(actor, getMobjInfo(actor)->meleestate); + /* killough 8/98: remember an attack + * cph - DEMOSYNC? */ + if (!demo_compatibility && !getMobjInfo(actor)->missilestate) + actor->flags |= MF_JUSTHIT; + return; + } + + // check for missile attack + if (getMobjInfo(actor)->missilestate) + { + if (!(_g->gameskill < sk_nightmare && actor->movecount)) + { + if (P_CheckMissileRange(actor)) + { + P_SetMobjState(actor, getMobjInfo(actor)->missilestate); + actor->flags |= MF_JUSTATTACKED; + return; + } + } + } + + if (!actor->threshold) + { + if (actor->pursuecount) + actor->pursuecount--; + else + { + /* Our pursuit time has expired. We're going to think about + * changing targets */ + actor->pursuecount = BASETHRESHOLD; + + /* Unless (we have a live target + * and it's not friendly + * and we can see it) + * try to find a new one; return if sucessful */ + + if (!(getTarget(actor) && getTarget(actor)->health > 0 && + ( + (((getTarget(actor)->flags ^ actor->flags) & MF_FRIEND + || (!(actor->flags & MF_FRIEND ))) && P_CheckSight(actor, getTarget(actor))))) && P_LookForTargets(actor, true)) + return; + + /* (Current target was good, or no new target was found.) + * + * If monster is a missile-less friend, give up pursuit and + * return to player, if no attacks have occurred recently. + */ + + if (!getMobjInfo(actor)->missilestate && (actor->flags & MF_FRIEND )) + { + if (actor->flags & MF_JUSTHIT) /* if recent action, */ + actor->flags &= ~MF_JUSTHIT; /* keep fighting */ + else if (P_LookForPlayers(actor, true)) /* else return to player */ + return; + } + } + } + + if (actor->strafecount) + actor->strafecount--; + + // chase towards player + if (--actor->movecount < 0 || !P_SmartMove(actor)) + P_NewChaseDir(actor); + + // make active sound + if (getMobjInfo(actor)->activesound && P_Random(__FILE__, __LINE__, __FUNCTION__) < 3) + S_StartSound(actor, getMobjInfo(actor)->activesound); +} + +// +// A_FaceTarget +// +void A_FaceTarget(mobj_t *actor) +{ +// if (!actor->target) + if (!actor->target_sptr) + return; + actor->flags &= ~MF_AMBUSH; + actor->angle = R_PointToAngle2(actor->x, actor->y, getTarget(actor)->x, getTarget(actor)->y); + if (getTarget(actor)->flags & MF_SHADOW) + { // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + actor->angle += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 21; + } +} + +// +// A_PosAttack +// + +void A_PosAttack(mobj_t *actor) +{ + int angle, damage, slope, t; + + // if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + angle = actor->angle; + slope = P_AimLineAttack(actor, angle, MISSILERANGE, 0); /* killough 8/2/98 */ + S_StartSound(actor, sfx_pistol); + + // killough 5/5/98: remove dependence on order of evaluation: + t = P_Random(__FILE__, __LINE__, __FUNCTION__); + angle += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 20; + damage = (P_Random(__FILE__, __LINE__, __FUNCTION__) % 5 + 1) * 3; + P_LineAttack(actor, angle, MISSILERANGE, slope, damage); +} + +void A_SPosAttack(mobj_t *actor) +{ + int i, bangle, slope; + + // if (!actor->target) + if (!actor->target_sptr) + return; + S_StartSound(actor, sfx_shotgn); + A_FaceTarget(actor); + bangle = actor->angle; + slope = P_AimLineAttack(actor, bangle, MISSILERANGE, 0); /* killough 8/2/98 */ + for (i = 0; i < 3; i++) + { // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + int angle = bangle + ((t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 20); + int damage = ((P_Random(__FILE__, __LINE__, __FUNCTION__) % 5) + 1) * 3; + P_LineAttack(actor, angle, MISSILERANGE, slope, damage); + } +} + +void A_CPosAttack(mobj_t *actor) +{ + int angle, bangle, damage, slope, t; + + //if (!actor->target) + if (!actor->target_sptr) + return; + S_StartSound(actor, sfx_shotgn); + A_FaceTarget(actor); + bangle = actor->angle; + slope = P_AimLineAttack(actor, bangle, MISSILERANGE, 0); /* killough 8/2/98 */ + + // killough 5/5/98: remove dependence on order of evaluation: + t = P_Random(__FILE__, __LINE__, __FUNCTION__); + angle = bangle + ((t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 20); + damage = ((P_Random(__FILE__, __LINE__, __FUNCTION__) % 5) + 1) * 3; + P_LineAttack(actor, angle, MISSILERANGE, slope, damage); +} + +void A_CPosRefire(mobj_t *actor) +{ + // keep firing unless target got out of sight + A_FaceTarget(actor); + + /* killough 12/98: Stop firing if a friend has gotten in the way */ + if (P_HitFriend(actor)) + goto stop; + + /* killough 11/98: prevent refiring on friends continuously */ + if (P_Random(__FILE__, __LINE__, __FUNCTION__) < 40) + { + if (getTarget(actor) && (actor->flags & getTarget(actor)->flags & MF_FRIEND )) + goto stop; + else + return; + } + + if (!getTarget(actor) || getTarget(actor)->health <= 0 || !P_CheckSight(actor, getTarget(actor))) + stop: P_SetMobjState(actor, getMobjInfo(actor)->seestate); +} + +void A_SpidRefire(mobj_t *actor) +{ + // keep firing unless target got out of sight + A_FaceTarget(actor); + + /* killough 12/98: Stop firing if a friend has gotten in the way */ + if (P_HitFriend(actor)) + goto stop; + + if (P_Random(__FILE__, __LINE__, __FUNCTION__) < 10) + return; + + // killough 11/98: prevent refiring on friends continuously + if (!getTarget(actor) || getTarget(actor)->health <= 0 || (actor->flags & getTarget(actor)->flags & MF_FRIEND ) || !P_CheckSight(actor, getTarget(actor))) + stop: P_SetMobjState(actor, getMobjInfo(actor)->seestate); +} + +void A_BspiAttack(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + P_SpawnMissile(actor, getTarget(actor), MT_ARACHPLAZ); // launch a missile +} + +// +// A_TroopAttack +// + +void A_TroopAttack(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + if (P_CheckMeleeRange(actor)) + { + int damage; + S_StartSound(actor, sfx_claw); + damage = (P_Random(__FILE__, __LINE__, __FUNCTION__) % 8 + 1) * 3; + P_DamageMobj(getTarget(actor), actor, actor, damage); + return; + } + P_SpawnMissile(actor, getTarget(actor), MT_TROOPSHOT); // launch a missile +} + +void A_SargAttack(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + if (P_CheckMeleeRange(actor)) + { + int damage = ((P_Random(__FILE__, __LINE__, __FUNCTION__) % 10) + 1) * 4; + P_DamageMobj(getTarget(actor), actor, actor, damage); + } +} + +void A_HeadAttack(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + if (P_CheckMeleeRange(actor)) + { + int damage = (P_Random(__FILE__, __LINE__, __FUNCTION__) % 6 + 1) * 10; + P_DamageMobj(getTarget(actor), actor, actor, damage); + return; + } + P_SpawnMissile(actor, getTarget(actor), MT_HEADSHOT); // launch a missile +} + +void A_CyberAttack(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + S_StartSound(actor, sfx_rlaunc); + P_SpawnMissile(actor, getTarget(actor), MT_ROCKET); +} + +void A_BruisAttack(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + if (P_CheckMeleeRange(actor)) + { + int damage; + S_StartSound(actor, sfx_claw); + damage = (P_Random(__FILE__, __LINE__, __FUNCTION__) % 8 + 1) * 10; + P_DamageMobj(getTarget(actor), actor, actor, damage); + return; + } + P_SpawnMissile(actor, getTarget(actor), MT_BRUISERSHOT); // launch a missile +} + +// +// A_SkelMissile +// + +void A_SkelMissile(mobj_t *actor) +{ + mobj_t *mo; + + //if (!actor->target) + if (!actor->target_sptr) + return; + + A_FaceTarget(actor); + actor->z += 16 * FRACUNIT; // so missile spawns higher + mo = P_SpawnMissile(actor, getTarget(actor), MT_TRACER); + actor->z -= 16 * FRACUNIT; // back to normal + + mo->x += mo->momx; + mo->y += mo->momy; + //P_SetTarget(&mo->tracer, actor->target); + mo->tracer_sptr = actor->target_sptr; +} + +static const int TRACEANGLE = 0xc000000; + +void A_Tracer(mobj_t *actor) +{ + angle_t exact; + fixed_t dist; + fixed_t slope; + mobj_t *dest; + mobj_t *th; + + /* killough 1/18/98: this is why some missiles do not have smoke + * and some do. Also, internal demos start at random gametics, thus + * the bug in which revenants cause internal demos to go out of sync. + * + * killough 3/6/98: fix revenant internal demo bug by subtracting + * levelstarttic from gametic. + * + * killough 9/29/98: use new "basetic" so that demos stay in sync + * during pauses and menu activations, while retaining old demo sync. + * + * leveltime would have been better to use to start with in Doom, but + * since old demos were recorded using gametic, we must stick with it, + * and improvise around it (using leveltime causes desync across levels). + */ + + if ((_g->gametic - _g->basetic) & 3) + return; + + // spawn a puff of smoke behind the rocket + P_SpawnPuff(actor->x, actor->y, actor->z); + + th = P_SpawnMobj(actor->x - actor->momx, actor->y - actor->momy, actor->z, MT_SMOKE); + + th->momz = FRACUNIT; + th->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 3; + if (th->tics < 1) + th->tics = 1; + + // adjust direction + dest = getTracer(actor); + + if (!dest || dest->health <= 0) + return; + + // change angle + exact = R_PointToAngle2(actor->x, actor->y, dest->x, dest->y); + + if (exact != actor->angle) + { + if (exact - actor->angle > 0x80000000) + { + actor->angle -= TRACEANGLE; + if (exact - actor->angle < 0x80000000) + actor->angle = exact; + } + else + { + actor->angle += TRACEANGLE; + if (exact - actor->angle > 0x80000000) + actor->angle = exact; + } + } + + exact = actor->angle >> ANGLETOFINESHIFT; + actor->momx = FixedMul(getMobjInfo(actor)->speed, finecosine[exact]); + actor->momy = FixedMul(getMobjInfo(actor)->speed, finesine[exact]); + + // change slope + dist = P_AproxDistance(dest->x - actor->x, dest->y - actor->y); + + dist = dist / getMobjInfo(actor)->speed; + + if (dist < 1) + dist = 1; + + slope = (dest->z + 40 * FRACUNIT - actor->z) / dist; + + if (slope < actor->momz) + actor->momz -= FRACUNIT / 8; + else + actor->momz += FRACUNIT / 8; +} + +void A_SkelWhoosh(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + S_StartSound(actor, sfx_skeswg); +} + +void A_SkelFist(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + if (P_CheckMeleeRange(actor)) + { + int damage = ((P_Random(__FILE__, __LINE__, __FUNCTION__) % 10) + 1) * 6; + S_StartSound(actor, sfx_skepch); + P_DamageMobj(getTarget(actor), actor, actor, damage); + } +} + +// +// PIT_VileCheck +// Detect a corpse that could be raised. +// + +static boolean PIT_VileCheck(mobj_t *thing) +{ + int maxdist; + boolean check; + + if (!(thing->flags & MF_CORPSE )) + return true; // not a monster + + if (thing->tics != -1) + return true; // not lying still yet + + if (getMobjInfo(thing)->raisestate == S_NULL) + return true; // monster doesn't have a raise state + + maxdist = getMobjInfo(thing)->radius + mobjinfo[MT_VILE].radius; + + if (D_abs(thing->x - _g->viletryx) > maxdist || D_abs(thing->y - _g->viletryy) > maxdist) + return true; // not actually touching + +// Check to see if the radius and height are zero. If they are // phares +// then this is a crushed monster that has been turned into a // | +// gib. One of the options may be to ignore this guy. // V + +// Option 1: the original, buggy method, -> ghost (compatibility) +// Option 2: ressurect the monster, but not as a ghost +// Option 3: ignore the gib + +// if (Option3) // ^ +// if ((thing->height == 0) && (thing->radius == 0)) // | +// return true; // phares + + _g->corpsehit = thing; + _g->corpsehit->momx = _g->corpsehit->momy = 0; + { + int height, radius; + + height = _g->corpsehit->height_s; // save temporarily + radius = _g->corpsehit->radiusb; // save temporarily + _g->corpsehit->height_s = getMobjInfo(_g->corpsehit)->height >> FRACBITS; + _g->corpsehit->radiusb = getMobjInfo(_g->corpsehit)->radius >> FRACBITS; + _g->corpsehit->flags |= MF_SOLID; + check = P_CheckPosition(_g->corpsehit, _g->corpsehit->x, _g->corpsehit->y); + _g->corpsehit->height_s = height; // restore + _g->corpsehit->radiusb = radius; // restore // ^ + _g->corpsehit->flags &= ~MF_SOLID; + } // | + // phares + if (!check) + return true; // doesn't fit here + return false; // got one, so stop checking +} + +// +// A_VileChase +// Check for ressurecting a body +// + +void A_VileChase(mobj_t *actor) +{ + int xl, xh; + int yl, yh; + int bx, by; + + if (actor->movedir != DI_NODIR) + { + // check for corpses to raise + _g->viletryx = actor->x + getMobjInfo(actor)->speed * xspeed[actor->movedir]; + _g->viletryy = actor->y + getMobjInfo(actor)->speed * yspeed[actor->movedir]; + + xl = (_g->viletryx - _g->bmaporgx - MAXRADIUS * 2) >> MAPBLOCKSHIFT; + xh = (_g->viletryx - _g->bmaporgx + MAXRADIUS * 2) >> MAPBLOCKSHIFT; + yl = (_g->viletryy - _g->bmaporgy - MAXRADIUS * 2) >> MAPBLOCKSHIFT; + yh = (_g->viletryy - _g->bmaporgy + MAXRADIUS * 2) >> MAPBLOCKSHIFT; + + for (bx = xl; bx <= xh; bx++) + { + for (by = yl; by <= yh; by++) + { + // Call PIT_VileCheck to check + // whether object is a corpse + // that canbe raised. + if (!P_BlockThingsIterator(bx, by, PIT_VileCheck)) + { + const mobjinfo_t *info; + + // got one! + mobj_t *temp = getTarget(actor); + //actor->target = _g->corpsehit; + actor->target_sptr = getShortPtr(_g->corpsehit); + A_FaceTarget(actor); + //actor->target = temp; + actor->target_sptr = getShortPtr(temp); + P_SetMobjState(actor, S_VILE_HEAL1); + S_StartSound(_g->corpsehit, sfx_slop); + info = getMobjInfo(_g->corpsehit); + + P_SetMobjState(_g->corpsehit, info->raisestate); + + { + _g->corpsehit->height_s = info->height >> FRACBITS; // fix Ghost bug + _g->corpsehit->radiusb = info->radius >> FRACBITS; // fix Ghost bug + } // phares + + /* killough 7/18/98: + * friendliness is transferred from AV to raised corpse + */ + _g->corpsehit->flags = (info->flags & ~MF_FRIEND ) | (actor->flags & MF_FRIEND ); + + if (!((_g->corpsehit->flags ^ MF_COUNTKILL ) & (MF_FRIEND | MF_COUNTKILL ))) + _g->totallive++; + + _g->corpsehit->health = info->spawnhealth; +// P_SetTarget(&_g->corpsehit->target, NULL); // killough 11/98 + _g->corpsehit->target_sptr = 0; + + //P_SetTarget(&_g->corpsehit->lastenemy, NULL); + _g->corpsehit->lastenemy_sptr = 0; + _g->corpsehit->flags &= ~MF_JUSTHIT; + + return; + } + } + } + } + A_Chase(actor); // Return to normal attack. +} + +// +// A_VileStart +// + +void A_VileStart(mobj_t *actor) +{ + S_StartSound(actor, sfx_vilatk); +} + +// +// A_Fire +// Keep fire in front of player unless out of sight +// + +void A_StartFire(mobj_t *actor) +{ + S_StartSound(actor, sfx_flamst); + A_Fire(actor); +} + +void A_FireCrackle(mobj_t *actor) +{ + S_StartSound(actor, sfx_flame); + A_Fire(actor); +} + +void A_Fire(mobj_t *actor) +{ + unsigned an; + mobj_t *dest = getTracer(actor); + + if (!dest) + return; + + // don't move it if the vile lost sight + if (!P_CheckSight(getTarget(actor), dest)) + return; + + an = dest->angle >> ANGLETOFINESHIFT; + + P_UnsetThingPosition(actor); + actor->x = dest->x + FixedMul(24 * FRACUNIT, finecosine[an]); + actor->y = dest->y + FixedMul(24 * FRACUNIT, finesine[an]); + actor->z = dest->z; + P_SetThingPosition(actor); +} + +// +// A_VileTarget +// Spawn the hellfire +// + +void A_VileTarget(mobj_t *actor) +{ + mobj_t *fog; + + //if (!actor->target) + if (!actor->target_sptr) + return; + + A_FaceTarget(actor); + + // killough 12/98: fix Vile fog coordinates // CPhipps - compatibility optioned + fog = P_SpawnMobj(getTarget(actor)->x, getTarget(actor)->y, getTarget(actor)->z, MT_FIRE); + + //P_SetTarget(&actor->tracer, fog); + actor->tracer_sptr = getShortPtr(fog); + //P_SetTarget(&fog->target, actor); + fog->target_sptr = getShortPtr(actor); + //P_SetTarget(&fog->tracer, actor->target); + fog->tracer_sptr = actor->target_sptr; //getShortPtr(actor->target); + A_Fire(fog); +} + +// +// A_VileAttack +// + +void A_VileAttack(mobj_t *actor) +{ + mobj_t *fire; + int an; + + //if (!actor->target) + if (!actor->target_sptr) + return; + + A_FaceTarget(actor); + + if (!P_CheckSight(actor, getTarget(actor))) + return; + + S_StartSound(actor, sfx_barexp); + P_DamageMobj(getTarget(actor), actor, actor, 20); + getTarget(actor)->momz = 1000 * FRACUNIT / getMobjInfo(getTarget(actor))->mass; + + an = actor->angle >> ANGLETOFINESHIFT; + + fire = getTracer(actor); + + if (!fire) + return; + + // move the fire between the vile and the player + fire->x = getTarget(actor)->x - FixedMul(24 * FRACUNIT, finecosine[an]); + fire->y = getTarget(actor)->y - FixedMul(24 * FRACUNIT, finesine[an]); + P_RadiusAttack(fire, actor, 70); +} + +// +// Mancubus attack, +// firing three missiles (bruisers) +// in three different directions? +// Doesn't look like it. +// + +#define FATSPREAD (ANG90/8) + +void A_FatRaise(mobj_t *actor) +{ + A_FaceTarget(actor); + S_StartSound(actor, sfx_manatk); +} + +void A_FatAttack1(mobj_t *actor) +{ + mobj_t *mo; + int an; + + //if (!actor->target) + if (!actor->target_sptr) + return; + + A_FaceTarget(actor); + + // Change direction to ... + actor->angle += FATSPREAD; + + P_SpawnMissile(actor, getTarget(actor), MT_FATSHOT); + + mo = P_SpawnMissile(actor, getTarget(actor), MT_FATSHOT); + mo->angle += FATSPREAD; + an = mo->angle >> ANGLETOFINESHIFT; + mo->momx = FixedMul(getMobjInfo(mo)->speed, finecosine[an]); + mo->momy = FixedMul(getMobjInfo(mo)->speed, finesine[an]); +} + +void A_FatAttack2(mobj_t *actor) +{ + mobj_t *mo; + int an; + + //if (!actor->target) + if (!actor->target_sptr) + return; + + A_FaceTarget(actor); + // Now here choose opposite deviation. + actor->angle -= FATSPREAD; + P_SpawnMissile(actor, getTarget(actor), MT_FATSHOT); + + mo = P_SpawnMissile(actor, getTarget(actor), MT_FATSHOT); + mo->angle -= FATSPREAD * 2; + an = mo->angle >> ANGLETOFINESHIFT; + mo->momx = FixedMul(getMobjInfo(mo)->speed, finecosine[an]); + mo->momy = FixedMul(getMobjInfo(mo)->speed, finesine[an]); +} + +void A_FatAttack3(mobj_t *actor) +{ + mobj_t *mo; + int an; + + //if (!actor->target) + if (!actor->target_sptr) + return; + + A_FaceTarget(actor); + + mo = P_SpawnMissile(actor, getTarget(actor), MT_FATSHOT); + mo->angle -= FATSPREAD / 2; + an = mo->angle >> ANGLETOFINESHIFT; + mo->momx = FixedMul(getMobjInfo(mo)->speed, finecosine[an]); + mo->momy = FixedMul(getMobjInfo(mo)->speed, finesine[an]); + + mo = P_SpawnMissile(actor, getTarget(actor), MT_FATSHOT); + mo->angle += FATSPREAD / 2; + an = mo->angle >> ANGLETOFINESHIFT; + mo->momx = FixedMul(getMobjInfo(mo)->speed, finecosine[an]); + mo->momy = FixedMul(getMobjInfo(mo)->speed, finesine[an]); +} + +// +// SkullAttack +// Fly at the player like a missile. +// +#define SKULLSPEED (20*FRACUNIT) + +void A_SkullAttack(mobj_t *actor) +{ + mobj_t *dest; + angle_t an; + int dist; + + //if (!actor->target) + if (!actor->target_sptr) + return; + + dest = getTarget(actor); + actor->flags |= MF_SKULLFLY; + + S_StartSound(actor, getMobjInfo(actor)->attacksound); + A_FaceTarget(actor); + an = actor->angle >> ANGLETOFINESHIFT; + actor->momx = FixedMul(SKULLSPEED, finecosine[an]); + actor->momy = FixedMul(SKULLSPEED, finesine[an]); + dist = P_AproxDistance(dest->x - actor->x, dest->y - actor->y); + dist = dist / SKULLSPEED; + + if (dist < 1) + dist = 1; + actor->momz = (dest->z + (getMobjHeight(dest) >> 1) - actor->z) / dist; +} + +// +// A_PainShootSkull +// Spawn a lost soul and launch it at the target +// + +static void A_PainShootSkull(mobj_t *actor, angle_t angle) +{ + fixed_t x, y, z; + mobj_t *newmobj; + angle_t an; + int prestep; + +// The original code checked for 20 skulls on the level, // phares +// and wouldn't spit another one if there were. If not in // phares +// compatibility mode, we remove the limit. // phares + // phares + // okay, there's room for another one + + an = angle >> ANGLETOFINESHIFT; + + prestep = 4 * FRACUNIT + 3 * (getMobjInfo(actor)->radius + mobjinfo[MT_SKULL].radius) / 2; + + x = actor->x + FixedMul(prestep, finecosine[an]); + y = actor->y + FixedMul(prestep, finesine[an]); + z = actor->z + 8 * FRACUNIT; + // V + { + // Check whether the Lost Soul is being fired through a 1-sided + // wall or an impassible line, or a "monsters can't cross" line. + // If it is, then we don't allow the spawn. This is a bug fix, but + // it should be considered an enhancement, since it may disturb + // existing demos, so don't do it in compatibility mode. + + if (Check_Sides(actor, x, y)) + return; + + newmobj = P_SpawnMobj(x, y, z, MT_SKULL); + + // Check to see if the new Lost Soul's z value is above the + // ceiling of its new sector, or below the floor. If so, kill it. + + if ((newmobj->z > (getMobjSubsector(newmobj)->sector->ceilingheight - getMobjHeight(newmobj))) || (newmobj->z < getMobjSubsector(newmobj)->sector->floorheight)) + { + // kill it immediately + P_DamageMobj(newmobj, actor, actor, 10000); + return; // ^ + } // | + } // phares + + /* killough 7/20/98: PEs shoot lost souls with the same friendliness */ + newmobj->flags = (newmobj->flags & ~MF_FRIEND ) | (actor->flags & MF_FRIEND ); + + // Check for movements. + // killough 3/15/98: don't jump over dropoffs: + + if (!P_TryMove(newmobj, newmobj->x, newmobj->y, false)) + { + // kill it immediately + P_DamageMobj(newmobj, actor, actor, 10000); + return; + } + + //P_SetTarget(&newmobj->target, actor->target); + newmobj->target_sptr = actor->target_sptr; + A_SkullAttack(newmobj); +} + +// +// A_PainAttack +// Spawn a lost soul and launch it at the target +// + +void A_PainAttack(mobj_t *actor) +{ + //if (!actor->target) + if (!actor->target_sptr) + return; + A_FaceTarget(actor); + A_PainShootSkull(actor, actor->angle); +} + +void A_PainDie(mobj_t *actor) +{ + A_Fall(actor); + A_PainShootSkull(actor, actor->angle + ANG90); + A_PainShootSkull(actor, actor->angle + ANG180); + A_PainShootSkull(actor, actor->angle + ANG270); +} + +void A_Scream(mobj_t *actor) +{ + int sound; + + switch (getMobjInfo(actor)->deathsound) + { + case 0: + return; + + case sfx_podth1: + case sfx_podth2: + case sfx_podth3: + sound = sfx_podth1 + P_Random(__FILE__, __LINE__, __FUNCTION__) % 3; + break; + + case sfx_bgdth1: + case sfx_bgdth2: + sound = sfx_bgdth1 + P_Random(__FILE__, __LINE__, __FUNCTION__) % 2; + break; + + default: + sound = getMobjInfo(actor)->deathsound; + break; + } + + // Check for bosses. + if (actor->type == MT_SPIDER || actor->type == MT_CYBORG) + S_StartSound(NULL, sound); // full volume + else + S_StartSound(actor, sound); +} + +void A_XScream(mobj_t *actor) +{ + S_StartSound(actor, sfx_slop); +} + +void A_Pain(mobj_t *actor) +{ + if (getMobjInfo(actor)->painsound) + S_StartSound(actor, getMobjInfo(actor)->painsound); +} + +void A_Fall(mobj_t *actor) +{ + // actor is on ground, it can be walked over + actor->flags &= ~MF_SOLID; +} + +// +// A_Explode +// +void A_Explode(mobj_t *thingy) +{ + P_RadiusAttack(thingy, getTarget(thingy), 128); +} + +// +// A_BossDeath +// Possibly trigger special effects +// if on first boss level +// + +void A_BossDeath(mobj_t *mo) +{ + thinker_t *th; + line_t junk; + + if (_g->gamemode == commercial) + { + if (_g->gamemap != 7) + return; + + if ((mo->type != MT_FATSO) && (mo->type != MT_BABY)) + return; + } + else + { + { + switch (_g->gameepisode) + { + case 1: + if (_g->gamemap != 8) + return; + + if (mo->type != MT_BRUISER) + return; + break; + + case 2: + if (_g->gamemap != 8) + return; + + if (mo->type != MT_CYBORG) + return; + break; + + case 3: + if (_g->gamemap != 8) + return; + + if (mo->type != MT_SPIDER) + return; + + break; + + case 4: + switch (_g->gamemap) + { + case 6: + if (mo->type != MT_CYBORG) + return; + break; + + case 8: + if (mo->type != MT_SPIDER) + return; + break; + + default: + return; + } + break; + + default: + if (_g->gamemap != 8) + return; + break; + } + } + + } + + if (!(_g->playeringame && _g->player.health > 0)) + return; // no one left alive, so do not end game + + // scan the remaining thinkers to see + // if all bosses are dead + for (th = getThinkerNext(&thinkercap); th != &thinkercap; th= getThinkerNext(th)) + if (th->function == P_MobjThinker) + { + mobj_t *mo2 = (mobj_t *) th; + if (mo2 != mo && mo2->type == mo->type && mo2->health > 0) + return; // other boss not dead + } + + // victory! + if ( _g->gamemode == commercial) + { + if (_g->gamemap == 7) + { + if (mo->type == MT_FATSO) + { + junk.tag = 666; + EV_DoFloor(&junk, lowerFloorToLowest); + return; + } + + if (mo->type == MT_BABY) + { + junk.tag = 667; + EV_DoFloor(&junk, raiseToTexture); + return; + } + } + } + else + { + switch (_g->gameepisode) + { + case 1: + junk.tag = 666; + EV_DoFloor(&junk, lowerFloorToLowest); + return; + + case 4: + switch (_g->gamemap) + { + case 6: + junk.tag = 666; + EV_DoDoor(&junk, blazeOpen); + return; + + case 8: + junk.tag = 666; + EV_DoFloor(&junk, lowerFloorToLowest); + return; + } + } + } + G_ExitLevel(); +} + +void A_Hoof(mobj_t *mo) +{ + S_StartSound(mo, sfx_hoof); + A_Chase(mo); +} + +void A_Metal(mobj_t *mo) +{ + S_StartSound(mo, sfx_metal); + A_Chase(mo); +} + +void A_BabyMetal(mobj_t *mo) +{ + S_StartSound(mo, sfx_bspwlk); + A_Chase(mo); +} + +void A_OpenShotgun2(player_t *player, pspdef_t *psp) +{ + S_StartSound(player->mo, sfx_dbopn); +} + +void A_LoadShotgun2(player_t *player, pspdef_t *psp) +{ + S_StartSound(player->mo, sfx_dbload); +} + +void A_CloseShotgun2(player_t *player, pspdef_t *psp) +{ + S_StartSound(player->mo, sfx_dbcls); + A_ReFire(player, psp); +} + +// killough 3/26/98: initialize icon landings at level startup, +// rather than at boss wakeup, to prevent savegame-related crashes + +void P_SpawnBrainTargets(void) // killough 3/26/98: renamed old function +{ + thinker_t *thinker; + + // find all the target spots + _g->numbraintargets = 0; + _g->brain.targeton = 0; + _g->brain.easy = 0; // killough 3/26/98: always init easy to 0 + + for (thinker = getThinkerNext(&thinkercap); + thinker != &thinkercap; + thinker = getThinkerNext(thinker)) + if (thinker->function == P_MobjThinker) + { + mobj_t *m = (mobj_t *) thinker; + + if (m->type == MT_BOSSTARGET ) + { // killough 2/7/98: remove limit on icon landings: + if (_g->numbraintargets >= _g->numbraintargets_alloc) + _g->braintargets = realloc(_g->braintargets, + (_g->numbraintargets_alloc = _g->numbraintargets_alloc ? + _g->numbraintargets_alloc*2 : 32) *sizeof *_g->braintargets); + _g->braintargets[_g->numbraintargets++] = m; + } + } +} + +void A_BrainAwake(mobj_t *mo) +{ + S_StartSound(NULL, sfx_bossit); // killough 3/26/98: only generates sound now +} + +void A_BrainPain(mobj_t *mo) +{ + S_StartSound(NULL, sfx_bospn); +} + +void A_BrainScream(mobj_t *mo) +{ + int x; + for (x = mo->x - 196 * FRACUNIT; x < mo->x + 320 * FRACUNIT; + x += FRACUNIT * 8) + { + int y = mo->y - 320 * FRACUNIT; + int z = 128 + P_Random(__FILE__, __LINE__, __FUNCTION__) * 2 * FRACUNIT; + mobj_t *th = P_SpawnMobj(x, y, z, MT_ROCKET); + th->momz = P_Random(__FILE__, __LINE__, __FUNCTION__) * 512; + P_SetMobjState(th, S_BRAINEXPLODE1); + th->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 7; + if (th->tics < 1) + th->tics = 1; + } + S_StartSound(NULL, sfx_bosdth); +} + +void A_BrainExplode(mobj_t *mo) +{ // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + int x = mo->x + (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) * 2048; + int y = mo->y; + int z = 128 + P_Random(__FILE__, __LINE__, __FUNCTION__) * 2 * FRACUNIT; + mobj_t *th = P_SpawnMobj(x, y, z, MT_ROCKET); + th->momz = P_Random(__FILE__, __LINE__, __FUNCTION__) * 512; + P_SetMobjState(th, S_BRAINEXPLODE1); + th->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 7; + if (th->tics < 1) + th->tics = 1; +} + +void A_BrainDie(mobj_t *mo) +{ + G_ExitLevel(); +} + +void A_BrainSpit(mobj_t *mo) +{ + mobj_t *targ, *newmobj; + + if (!_g->numbraintargets) // killough 4/1/98: ignore if no targets + return; + + _g->brain.easy ^= 1; // killough 3/26/98: use brain struct + if (_g->gameskill <= sk_easy && !_g->brain.easy) + return; + + // shoot a cube at current target + targ = _g->braintargets[_g->brain.targeton++]; // killough 3/26/98: + _g->brain.targeton %= _g->numbraintargets; // Use brain struct for targets + + // spawn brain missile + newmobj = P_SpawnMissile(mo, targ, MT_SPAWNSHOT); + //P_SetTarget(&newmobj->target, targ); + newmobj->target_sptr = getShortPtr(targ); + newmobj->reactiontime = (short) (((targ->y - mo->y) / newmobj->momy) / getMobjState(newmobj)->tics); + + // killough 7/18/98: brain friendliness is transferred + newmobj->flags = (newmobj->flags & ~MF_FRIEND ) | (mo->flags & MF_FRIEND ); + + S_StartSound(NULL, sfx_bospit); +} + +// travelling cube sound +void A_SpawnSound(mobj_t *mo) +{ + S_StartSound(mo, sfx_boscub); + A_SpawnFly(mo); +} + +void A_SpawnFly(mobj_t *mo) +{ + mobj_t *newmobj; + mobj_t *fog; + mobj_t *targ; + int r; + mobjtype_t type; + + if (--mo->reactiontime) + return; // still flying + + targ = getTarget(mo); + + // First spawn teleport fog. + fog = P_SpawnMobj(targ->x, targ->y, targ->z, MT_SPAWNFIRE); + S_StartSound(fog, sfx_telept); + + // Randomly select monster to spawn. + r = P_Random(__FILE__, __LINE__, __FUNCTION__); + + // Probability distribution (kind of :), decreasing likelihood. + if (r < 50) + type = MT_TROOP; + else if (r < 90) + type = MT_SERGEANT; + else if (r < 120) + type = MT_SHADOWS; + else if (r < 130) + type = MT_PAIN; + else if (r < 160) + type = MT_HEAD; + else if (r < 162) + type = MT_VILE; + else if (r < 172) + type = MT_UNDEAD; + else if (r < 192) + type = MT_BABY; + else if (r < 222) + type = MT_FATSO; + else if (r < 246) + type = MT_KNIGHT; + else + type = MT_BRUISER; + + newmobj = P_SpawnMobj(targ->x, targ->y, targ->z, type); + + /* killough 7/18/98: brain friendliness is transferred */ + newmobj->flags = (newmobj->flags & ~MF_FRIEND ) | (mo->flags & MF_FRIEND ); + + if (P_LookForTargets(newmobj, true)) /* killough 9/4/98 */ + P_SetMobjState(newmobj, getMobjInfo(newmobj)->seestate); + + // telefrag anything in this spot + P_TeleportMove(newmobj, newmobj->x, newmobj->y, true); /* killough 8/9/98 */ + + // remove self (i.e., cube). + P_RemoveMobj(mo); +} + +void A_PlayerScream(mobj_t *mo) +{ + int sound = sfx_pldeth; // Default death sound. + if (_g->gamemode != shareware && mo->health < -50) + sound = sfx_pdiehi; // IF THE PLAYER DIES LESS THAN -50% WITHOUT GIBBING + S_StartSound(mo, sound); +} + +/* cph - MBF-added codepointer functions */ + +// killough 11/98: kill an object +void A_Die(mobj_t *actor) +{ + P_DamageMobj(actor, NULL, NULL, actor->health); +} + +// +// A_Detonate +// killough 8/9/98: same as A_Explode, except that the damage is variable +// + +void A_Detonate(mobj_t *mo) +{ + P_RadiusAttack(mo, getTarget(mo), getMobjInfo(mo)->damage); +} + +// +// killough 9/98: a mushroom explosion effect, sorta :) +// Original idea: Linguica +// + +void A_Mushroom(mobj_t *actor) +{ + int i, j, n = getMobjInfo(actor)->damage; + + A_Explode(actor); // First make normal explosion + + // Now launch mushroom cloud + for (i = -n; i <= n; i += 8) + for (j = -n; j <= n; j += 8) + { + mobj_t target = *actor, *mo; + target.x += i << FRACBITS; // Aim in many directions from source + target.y += j << FRACBITS; + target.z += P_AproxDistance(i, j) << (FRACBITS + 2); // Aim up fairly high + mo = P_SpawnMissile(actor, &target, MT_FATSHOT); // Launch fireball + mo->momx >>= 1; + mo->momy >>= 1; // Slow it down a bit + mo->momz >>= 1; + mo->flags &= ~MF_NOGRAVITY; // Make debris fall under gravity + } +} + +// +// killough 11/98 +// +// The following were inspired by Len Pitre +// +// A small set of highly-sought-after code pointers +// + +void A_Spawn(mobj_t *mo) +{ + if (getMobjState(mo)->misc1) + { + P_SpawnMobj(mo->x, mo->y, (getMobjState(mo)->misc2 << FRACBITS) + mo->z, getMobjState(mo)->misc1 - 1); + } +} + +void A_Turn(mobj_t *mo) +{ + mo->angle += (unsigned int) (((uint_64_t) getMobjState(mo)->misc1 << 32) / 360); +} + +void A_Face(mobj_t *mo) +{ + mo->angle = (unsigned int) (((uint_64_t) getMobjState(mo)->misc1 << 32) / 360); +} + +void A_Scratch(mobj_t *mo) +{ +// mo->target && (A_FaceTarget(mo), P_CheckMeleeRange(mo)) ? + mo->target_sptr && (A_FaceTarget(mo), P_CheckMeleeRange(mo)) ? + getMobjState(mo)->misc2 ? S_StartSound(mo, getMobjState(mo)->misc2) : (void) 0, P_DamageMobj(getTarget(mo), mo, mo, getMobjState(mo)->misc1) : (void) 0; +} + +void A_PlaySound(mobj_t *mo) +{ + S_StartSound(getMobjState(mo)->misc2 ? NULL : mo, getMobjState(mo)->misc1); +} + +void A_RandomJump(mobj_t *mo) +{ + if (P_Random(__FILE__, __LINE__, __FUNCTION__) < getMobjState(mo)->misc2) + P_SetMobjState(mo, getMobjState(mo)->misc1); +} + diff --git a/doom/src/pdoom/Doom/source/p_floor.c b/doom/src/pdoom/Doom/source/p_floor.c new file mode 100644 index 0000000..16c2a7f --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_floor.c @@ -0,0 +1,933 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * General plane mover and floor mover action routines + * Floor motion, pure changer types, raising stairs. donuts, elevators + * + * next-hack: modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ +#include "doomstat.h" +#include "r_main.h" +#include "p_map.h" +#include "p_spec.h" +#include "p_tick.h" +#include "s_sound.h" +#include "sounds.h" + +#include "global_data.h" + +/////////////////////////////////////////////////////////////////////// +// +// Plane (floor or ceiling), Floor motion and Elevator action routines +// +/////////////////////////////////////////////////////////////////////// + +// +// T_MovePlane() +// +// Move a plane (floor or ceiling) and check for crushing. Called +// every tick by all actions that move floors or ceilings. +// +// Passed the sector to move a plane in, the speed to move it at, +// the dest height it is to achieve, whether it crushes obstacles, +// whether it moves a floor or ceiling, and the direction up or down +// to move. +// +// Returns a result_e: +// ok - plane moved normally, has not achieved destination yet +// pastdest - plane moved normally and is now at destination height +// crushed - plane encountered an obstacle, is holding until removed +// +result_e T_MovePlane(sector_t *sector, fixed_t speed, fixed_t dest, boolean crush, int floorOrCeiling, int direction) +{ + boolean flag; + fixed_t lastpos; + fixed_t destheight; //jff 02/04/98 used to keep floors/ceilings + // from moving thru each other + + switch (floorOrCeiling) + { + case 0: + // Moving a floor + switch (direction) + { + case -1: + // Moving a floor down + if (sector->floorheight - speed < dest) + { + lastpos = sector->floorheight; + sector->floorheight = dest; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + if (flag == true) + { + sector->floorheight = lastpos; + P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + } + return pastdest; + } + else + { + lastpos = sector->floorheight; + sector->floorheight -= speed; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + /* cph - make more compatible with original Doom, by + * reintroducing this code. This means floors can't lower + * if objects are stuck in the ceiling */ + } + break; + + case 1: + // Moving a floor up + // jff 02/04/98 keep floor from moving thru ceilings + // jff 2/22/98 weaken check to demo_compatibility + destheight = + (dest < sector->ceilingheight) ? dest : sector->ceilingheight; + if (sector->floorheight + speed > destheight) + { + lastpos = sector->floorheight; + sector->floorheight = destheight; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + if (flag == true) + { + sector->floorheight = lastpos; + P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + } + return pastdest; + } + else + { + // crushing is possible + lastpos = sector->floorheight; + sector->floorheight += speed; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + if (flag == true) + { + + sector->floorheight = lastpos; + P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + return crushed; + } + } + break; + } + break; + + case 1: + // moving a ceiling + switch (direction) + { + case -1: + // moving a ceiling down + // jff 02/04/98 keep ceiling from moving thru floors + // jff 2/22/98 weaken check to demo_compatibility + destheight = + (dest > sector->floorheight) ? dest : sector->floorheight; + if (sector->ceilingheight - speed < destheight) + { + lastpos = sector->ceilingheight; + sector->ceilingheight = destheight; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + + if (flag == true) + { + sector->ceilingheight = lastpos; + P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + } + return pastdest; + } + else + { + // crushing is possible + lastpos = sector->ceilingheight; + sector->ceilingheight -= speed; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + + if (flag == true) + { + if (crush == true) + return crushed; + sector->ceilingheight = lastpos; + P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + return crushed; + } + } + break; + + case 1: + // moving a ceiling up + if (sector->ceilingheight + speed > dest) + { + lastpos = sector->ceilingheight; + sector->ceilingheight = dest; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + if (flag == true) + { + sector->ceilingheight = lastpos; + P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + } + return pastdest; + } + else + { + lastpos = sector->ceilingheight; + sector->ceilingheight += speed; + flag = P_CheckSector(sector, crush); //jff 3/19/98 use faster chk + } + break; + } + break; + } + return ok; +} + +// +// T_MoveFloor() +// +// Move a floor to it's destination (up or down). +// Called once per tick for each moving floor. +// +// Passed a floormove_t structure that contains all pertinent info about the +// move. See P_SPEC.H for fields. +// No return. +// +// jff 02/08/98 all cases with labels beginning with gen added to support +// generalized line type behaviors. + +void T_MoveFloor(floormove_t *floor) +{ + result_e res; + + res = T_MovePlane // move the floor + (getFloorMoveSector(floor), floor->speed, floor->floordestheight, floor->crush, 0, floor->direction); + + if (!(_g->leveltime & 7)) // make the floormove sound + S_StartSound2(&getFloorMoveSector(floor)->soundorg, sfx_stnmov); + + if (res == pastdest) // if destination height is reached + { + if (floor->direction == 1) // going up + { + switch (floor->type) + // handle texture/type changes + { + case donutRaise: + getFloorMoveSector(floor)->special = floor->newspecial; + getFloorMoveSector(floor)->floorpic = floor->texture; + break; + case genFloorChgT: + case genFloorChg0: + getFloorMoveSector(floor)->special = floor->newspecial; + //jff add to fix bug in special transfers from changes + getFloorMoveSector(floor)->oldspecial = floor->oldspecial; + // fall through + case genFloorChg: + getFloorMoveSector(floor)->floorpic = floor->texture; + break; + default: + break; + } + } + else if (floor->direction == -1) // going down + { + switch (floor->type) + // handle texture/type changes + { + case lowerAndChange: + getFloorMoveSector(floor)->special = floor->newspecial; + //jff add to fix bug in special transfers from changes + getFloorMoveSector(floor)->oldspecial = floor->oldspecial; + getFloorMoveSector(floor)->floorpic = floor->texture; + break; + case genFloorChgT: + case genFloorChg0: + getFloorMoveSector(floor)->special = floor->newspecial; + //jff add to fix bug in special transfers from changes + getFloorMoveSector(floor)->oldspecial = floor->oldspecial; + //fall thru + case genFloorChg: + getFloorMoveSector(floor)->floorpic = floor->texture; + break; + default: + break; + } + } + + getFloorMoveSector(floor)->floordata_sptr = 0; //jff 2/22/98 + P_RemoveThinker(&floor->thinker); //remove this floor from list of movers + + // make floor stop sound + S_StartSound2(&getFloorMoveSector(floor)->soundorg, sfx_pstop); + } +} + +// +// T_MoveElevator() +// +// Move an elevator to it's destination (up or down) +// Called once per tick for each moving floor. +// +// Passed an elevator_t structure that contains all pertinent info about the +// move. See P_SPEC.H for fields. +// No return. +// +// jff 02/22/98 added to support parallel floor/ceiling motion +// +void T_MoveElevator(elevator_t *elevator) +{ + result_e res; + + if (elevator->direction < 0) // moving down + { + res = T_MovePlane //jff 4/7/98 reverse order of ceiling/floor + (elevator->sector, elevator->speed, elevator->ceilingdestheight, 0, 1, // move floor + elevator->direction); + if (res == ok || res == pastdest) // jff 4/7/98 don't move ceil if blocked + T_MovePlane(elevator->sector, elevator->speed, elevator->floordestheight, 0, 0, // move ceiling + elevator->direction); + } + else // up + { + res = T_MovePlane //jff 4/7/98 reverse order of ceiling/floor + (elevator->sector, elevator->speed, elevator->floordestheight, 0, 0, // move ceiling + elevator->direction); + if (res == ok || res == pastdest) // jff 4/7/98 don't move floor if blocked + T_MovePlane(elevator->sector, elevator->speed, elevator->ceilingdestheight, 0, 1, // move floor + elevator->direction); + } + + // make floor move sound + if (!(_g->leveltime & 7)) + S_StartSound2(&elevator->sector->soundorg, sfx_stnmov); + + if (res == pastdest) // if destination height acheived + { + elevator->sector->floordata_sptr = 0; //jff 2/22/98 + elevator->sector->ceilingdata_sptr = 0; //jff 2/22/98 + P_RemoveThinker(&elevator->thinker); // remove elevator from actives + + // make floor stop sound + S_StartSound2(&elevator->sector->soundorg, sfx_pstop); + } +} + +/////////////////////////////////////////////////////////////////////// +// +// Floor motion linedef handlers +// +/////////////////////////////////////////////////////////////////////// + +// +// EV_DoFloor() +// +// Handle regular and extended floor types +// +// Passed the line that activated the floor and the type of floor motion +// Returns true if a thinker was created. +// +int EV_DoFloor(const line_t *line, floor_e floortype) +{ + int secnum; + int rtn; + int i; + sector_t *sec; + floormove_t *floor; + + secnum = -1; + rtn = 0; + // move all floors with the same tag as the linedef + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + // Don't start a second thinker on the same floor + if (P_SectorActive(floor_special, sec)) //jff 2/23/98 + continue; + + // new floor thinker + rtn = 1; + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + sec->floordata_sptr = getShortPtr(floor); //jff 2/22/98 + floor->thinker.function = T_MoveFloor; + floor->type = floortype; + floor->crush = false; + + // setup the thinker according to the linedef type + switch (floortype) + { + case lowerFloor: + floor->direction = -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = P_FindHighestFloorSurrounding(sec); + break; + + //jff 02/03/30 support lowering floor by 24 absolute + case lowerFloor24: + floor->direction = -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = getFloorMoveSector(floor)->floorheight + 24 * FRACUNIT; + break; + + //jff 02/03/30 support lowering floor by 32 absolute (fast) + case lowerFloor32Turbo: + floor->direction = -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED * 4; + floor->floordestheight = getFloorMoveSector(floor)->floorheight + 32 * FRACUNIT; + break; + + case lowerFloorToLowest: + floor->direction = -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = P_FindLowestFloorSurrounding(sec); + break; + + //jff 02/03/30 support lowering floor to next lowest floor + case lowerFloorToNearest: + floor->direction = -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = P_FindNextLowestFloor(sec, getFloorMoveSector(floor)->floorheight); + break; + + case turboLower: + floor->direction = -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED * 4; + floor->floordestheight = P_FindHighestFloorSurrounding(sec); + if (floor->floordestheight != sec->floorheight) + floor->floordestheight += 8 * FRACUNIT; + break; + + case raiseFloorCrush: + floor->crush = true; + case raiseFloor: + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = P_FindLowestCeilingSurrounding(sec); + if (floor->floordestheight > sec->ceilingheight) + floor->floordestheight = sec->ceilingheight; + floor->floordestheight -= (8 * FRACUNIT) * (floortype == raiseFloorCrush); + break; + + case raiseFloorTurbo: + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED * 4; + floor->floordestheight = P_FindNextHighestFloor(sec, sec->floorheight); + break; + + case raiseFloorToNearest: + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = P_FindNextHighestFloor(sec, sec->floorheight); + break; + + case raiseFloor24: + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = getFloorMoveSector(floor)->floorheight + 24 * FRACUNIT; + break; + + // jff 2/03/30 support straight raise by 32 (fast) + case raiseFloor32Turbo: + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED * 4; + floor->floordestheight = getFloorMoveSector(floor)->floorheight + 32 * FRACUNIT; + break; + + case raiseFloor512: + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = getFloorMoveSector(floor)->floorheight + 512 * FRACUNIT; + break; + + case raiseFloor24AndChange: + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = getFloorMoveSector(floor)->floorheight + 24 * FRACUNIT; + sec->floorpic = LN_FRONTSECTOR(line)->floorpic; + sec->special = LN_FRONTSECTOR(line)->special; + //jff 3/14/98 transfer both old and new special + sec->oldspecial = LN_FRONTSECTOR(line)->oldspecial; + break; + + case raiseToTexture: + { + int minsize = INT_MAX; + side_t *side; + + /* jff 3/13/98 no ovf */ + + minsize = 32000 << FRACBITS; + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + for (i = 0; i < sec->linecount; i++) + { + if (twoSided(secnum, i)) + { + side = getSide(secnum, i, 0); + // jff 8/14/98 don't scan texture 0, its not real + if (side->bottomtexture > 0) + if (textureheight[side->bottomtexture] < minsize) + minsize = textureheight[side->bottomtexture]; + side = getSide(secnum, i, 1); + // jff 8/14/98 don't scan texture 0, its not real + if (side->bottomtexture > 0) + if (textureheight[side->bottomtexture] < minsize) + minsize = textureheight[side->bottomtexture]; + } + } + { + floor->floordestheight = (getFloorMoveSector(floor)->floorheight >> FRACBITS) + (minsize >> FRACBITS); + if (floor->floordestheight > 32000) + floor->floordestheight = 32000; //jff 3/13/98 do not + floor->floordestheight <<= FRACBITS; // allow height overflow + } + } + break; + + case lowerAndChange: + floor->direction = -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = FLOORSPEED; + floor->floordestheight = P_FindLowestFloorSurrounding(sec); + floor->texture = sec->floorpic; + + // jff 1/24/98 make sure floor->newspecial gets initialized + // in case no surrounding sector is at floordestheight + // --> should not affect compatibility <-- + floor->newspecial = sec->special; + //jff 3/14/98 transfer both old and new special + floor->oldspecial = sec->oldspecial; + + //jff 5/23/98 use model subroutine to unify fixes and handling + sec = P_FindModelFloorSector(floor->floordestheight, sec - _g->sectors); + if (sec) + { + floor->texture = sec->floorpic; + floor->newspecial = sec->special; + //jff 3/14/98 transfer both old and new special + floor->oldspecial = sec->oldspecial; + } + break; + default: + break; + } + } + return rtn; +} + +// +// EV_DoChange() +// +// Handle pure change types. These change floor texture and sector type +// by trigger or numeric model without moving the floor. +// +// The linedef causing the change and the type of change is passed +// Returns true if any sector changes +// +// jff 3/15/98 added to better support generalized sector types +// +int EV_DoChange(const line_t *line, change_e changetype) +{ + int secnum; + int rtn; + sector_t *sec; + sector_t *secm; + + secnum = -1; + rtn = 0; + // change all sectors with the same tag as the linedef + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + rtn = 1; + + // handle trigger or numeric change type + switch (changetype) + { + case trigChangeOnly: + sec->floorpic = LN_FRONTSECTOR(line)->floorpic; + sec->special = LN_FRONTSECTOR(line)->special; + sec->oldspecial = LN_FRONTSECTOR(line)->oldspecial; + break; + case numChangeOnly: + secm = P_FindModelFloorSector(sec->floorheight, secnum); + if (secm) // if no model, no change + { + sec->floorpic = secm->floorpic; + sec->special = secm->special; + sec->oldspecial = secm->oldspecial; + } + break; + default: + break; + } + } + return rtn; +} + +/* + * EV_BuildStairs() + * + * Handles staircase building. A sequence of sectors chosen by algorithm + * rise at a speed indicated to a height that increases by the stepsize + * each step. + * + * Passed the linedef triggering the stairs and the type of stair rise + * Returns true if any thinkers are created + * + * cph 2001/09/21 - compatibility nightmares again + * There are three different ways this function has, during its history, stepped + * through all the stairs to be triggered by the single switch + * - original Doom used a linear P_FindSectorFromLineTag, but failed to preserve + * the index of the previous sector found, so instead it would restart its + * linear search from the last sector of the previous staircase + * - MBF/PrBoom with comp_stairs fail to emulate this, because their + * P_FindSectorFromLineTag is a chained hash table implementation. Instead they + * start following the hash chain from the last sector of the previous + * staircase, which will (probably) have the wrong tag, so they miss any further + * stairs + * - Boom fixed the bug, and MBF/PrBoom without comp_stairs work right + */ +static inline int P_FindSectorFromLineTagWithLowerBound(const line_t *l, int start, int min) +{ + /* Emulate original Doom's linear lower-bounded P_FindSectorFromLineTag + * as needed */ + do + { + start = P_FindSectorFromLineTag(l, start); + } while (start >= 0 && start <= min); + return start; +} + +int EV_BuildStairs(const line_t *line, stair_e type) +{ + /* cph 2001/09/22 - cleaned up this function to save my sanity. A separate + * outer loop index makes the logic much cleared, and local variables moved + * into the inner blocks helps too */ + int ssec = -1; + int minssec = -1; + int rtn = 0; + + // start a stair at each sector tagged the same as the linedef + while ((ssec = P_FindSectorFromLineTagWithLowerBound(line, ssec, minssec)) >= 0) + { + int secnum = ssec; + sector_t *sec = &_g->sectors[secnum]; + + // don't start a stair if the first step's floor is already moving + if (!P_SectorActive(floor_special, sec)) + { //jff 2/22/98 + floormove_t *floor; + int texture, height; + fixed_t stairsize; + fixed_t speed; + int ok; + + // create new floor thinker for first step + rtn = 1; + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + sec->floordata_sptr = getShortPtr(floor); + floor->thinker.function = T_MoveFloor; + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->type = buildStair; //jff 3/31/98 do not leave uninited + + // set up the speed and stepsize according to the stairs type + switch (type) + { + default: // killough -- prevent compiler warning + case build8: + speed = FLOORSPEED / 4; + stairsize = 8 * FRACUNIT; + floor->crush = false; //jff 2/27/98 fix uninitialized crush field + break; + case turbo16: + speed = FLOORSPEED * 4; + stairsize = 16 * FRACUNIT; + floor->crush = true; //jff 2/27/98 fix uninitialized crush field + break; + } + floor->speed = speed; + height = sec->floorheight + stairsize; + floor->floordestheight = height; + + texture = sec->floorpic; + + // Find next sector to raise + // 1. Find 2-sided line with same sector side[0] (lowest numbered) + // 2. Other side is the next sector to raise + // 3. Unless already moving, or different texture, then stop building + do + { + int i; + ok = 0; + + for (i = 0; i < sec->linecount; i++) + { +// sector_t* tsec = LN_FRONTSECTOR((sec->lines[i])); + sector_t *tsec = LN_FRONTSECTOR(getSectorLineByIndex(sec, i)); + int newsecnum; + if (!(getSectorLineByIndex(sec, i)->flags & ML_TWOSIDED)) + continue; + + newsecnum = tsec - _g->sectors; + + if (secnum != newsecnum) + continue; + + tsec = LN_BACKSECTOR((getSectorLineByIndex(sec, i))); + if (!tsec) + continue; //jff 5/7/98 if no backside, continue + newsecnum = tsec - _g->sectors; + + // if sector's floor is different texture, look for another + if (tsec->floorpic != texture) + continue; + + // if sector's floor already moving, look for another + if (P_SectorActive(floor_special, tsec)) //jff 2/22/98 + continue; + + height += stairsize; + + sec = tsec; + secnum = newsecnum; + + // create and initialize a thinker for the next step + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + + sec->floordata_sptr = getShortPtr(floor); //jff 2/22/98 + floor->thinker.function = T_MoveFloor; + floor->direction = 1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = speed; + floor->floordestheight = height; + floor->type = buildStair; //jff 3/31/98 do not leave uninited + //jff 2/27/98 fix uninitialized crush field + floor->crush = type == build8 ? false : true; + ok = 1; + break; + } + } while (ok); // continue until no next step is found + + } + } + return rtn; +} + +// +// EV_DoDonut() +// +// Handle donut function: lower pillar, raise surrounding pool, both to height, +// texture and type of the sector surrounding the pool. +// +// Passed the linedef that triggered the donut +// Returns whether a thinker was created +// +int EV_DoDonut(const line_t *line) +{ + sector_t *s1; + sector_t *s2; + sector_t *s3; + int secnum; + int rtn; + int i; + floormove_t *floor; + + secnum = -1; + rtn = 0; + // do function on all sectors with same tag as linedef + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + s1 = &_g->sectors[secnum]; // s1 is pillar's sector + + // do not start the donut if the pillar is already moving + if (P_SectorActive(floor_special, s1)) //jff 2/22/98 + continue; + +// s2 = getNextSector(s1->lines[0],s1); // s2 is pool's sector + s2 = getNextSector(getSectorLineByIndex(s1, 0), s1); // s2 is pool's sector + if (!s2) + continue; // note lowest numbered line around + // pillar must be two-sided + + /* do not start the donut if the pool is already moving + * cph - DEMOSYNC - was !compatibility */ + if (P_SectorActive(floor_special, s2)) + continue; //jff 5/7/98 + + // find a two sided line around the pool whose other side isn't the pillar + for (i = 0; i < s2->linecount; i++) + { + + if (!LN_BACKSECTOR((getSectorLineByIndex(s2, i))) || LN_BACKSECTOR((getSectorLineByIndex(s2,i))) == s1) + continue; + + rtn = 1; //jff 1/26/98 no donut action - no switch change on return + + s3 = LN_BACKSECTOR((getSectorLineByIndex(s2, i))); // s3 is model sector for changes + + // Spawn rising slime + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + s2->floordata_sptr = getShortPtr(floor); //jff 2/22/98 + floor->thinker.function = T_MoveFloor; + floor->type = donutRaise; + floor->crush = false; + floor->direction = 1; + floor->sector_sptr = getShortPtr(s2); + floor->speed = FLOORSPEED / 2; + floor->texture = s3->floorpic; + floor->newspecial = 0; + floor->floordestheight = s3->floorheight; + + // Spawn lowering donut-hole pillar + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + s1->floordata_sptr = getShortPtr(floor); //jff 2/22/98 + floor->thinker.function = T_MoveFloor; + floor->type = lowerFloor; + floor->crush = false; + floor->direction = -1; + floor->sector_sptr = getShortPtr(s1); + floor->speed = FLOORSPEED / 2; + floor->floordestheight = s3->floorheight; + break; + } + } + return rtn; +} + +// +// EV_DoElevator +// +// Handle elevator linedef types +// +// Passed the linedef that triggered the elevator and the elevator action +// +// jff 2/22/98 new type to move floor and ceiling in parallel +// +int EV_DoElevator(const line_t *line, elevator_e elevtype) +{ + int secnum; + int rtn; + sector_t *sec; + elevator_t *elevator; + + secnum = -1; + rtn = 0; + // act on all sectors with the same tag as the triggering linedef + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + // If either floor or ceiling is already activated, skip it + if (sec->floordata_sptr || sec->ceilingdata_sptr) //jff 2/22/98 + continue; + + // create and initialize new elevator thinker + rtn = 1; + elevator = Z_Malloc(sizeof(*elevator), PU_LEVSPEC, 0); + memset(elevator, 0, sizeof(*elevator)); + P_AddThinker(&elevator->thinker); + sec->floordata_sptr = getShortPtr(elevator); //jff 2/22/98 + sec->ceilingdata_sptr = getShortPtr(elevator); //jff 2/22/98 + elevator->thinker.function = T_MoveElevator; + elevator->type = elevtype; + + // set up the fields according to the type of elevator action + switch (elevtype) + { + // elevator down to next floor + case elevateDown: + elevator->direction = -1; + elevator->sector = sec; + elevator->speed = ELEVATORSPEED; + elevator->floordestheight = P_FindNextLowestFloor(sec, sec->floorheight); + elevator->ceilingdestheight = elevator->floordestheight + sec->ceilingheight - sec->floorheight; + break; + + // elevator up to next floor + case elevateUp: + elevator->direction = 1; + elevator->sector = sec; + elevator->speed = ELEVATORSPEED; + elevator->floordestheight = P_FindNextHighestFloor(sec, sec->floorheight); + elevator->ceilingdestheight = elevator->floordestheight + sec->ceilingheight - sec->floorheight; + break; + + // elevator to floor height of activating switch's front sector + case elevateCurrent: + elevator->sector = sec; + elevator->speed = ELEVATORSPEED; + elevator->floordestheight = LN_FRONTSECTOR(line)->floorheight; + elevator->ceilingdestheight = elevator->floordestheight + sec->ceilingheight - sec->floorheight; + elevator->direction = + elevator->floordestheight > sec->floorheight ? 1 : -1; + break; + + default: + break; + } + } + return rtn; +} diff --git a/doom/src/pdoom/Doom/source/p_genlin.c b/doom/src/pdoom/Doom/source/p_genlin.c new file mode 100644 index 0000000..d13a6a2 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_genlin.c @@ -0,0 +1,1148 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Generalized linedef type handlers + * Floors, Ceilings, Doors, Locked Doors, Lifts, Stairs, Crushers + * + * next-hack: modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" //jff 6/19/98 for demo_compatibility +#include "r_main.h" +#include "p_spec.h" +#include "p_tick.h" +#include "m_random.h" +#include "s_sound.h" +#include "sounds.h" + +#include "global_data.h" + +////////////////////////////////////////////////////////// +// +// Generalized Linedef Type handlers +// +////////////////////////////////////////////////////////// + +// +// EV_DoGenFloor() +// +// Handle generalized floor types +// +// Passed the line activating the generalized floor function +// Returns true if a thinker is created +// +// jff 02/04/98 Added this routine (and file) to handle generalized +// floor movers using bit fields in the line special type. +// +int EV_DoGenFloor(const line_t *line) +{ + int secnum; + int rtn; + boolean manual; + sector_t *sec; + floormove_t *floor; + unsigned value = (unsigned) LN_SPECIAL(line) - GenFloorBase; + + // parse the bit fields in the line's special type + + int Crsh = (value & FloorCrush) >> FloorCrushShift; + int ChgT = (value & FloorChange) >> FloorChangeShift; + int Targ = (value & FloorTarget) >> FloorTargetShift; + int Dirn = (value & FloorDirection) >> FloorDirectionShift; + int ChgM = (value & FloorModel) >> FloorModelShift; + int Sped = (value & FloorSpeed) >> FloorSpeedShift; + int Trig = (value & TriggerType) >> TriggerTypeShift; + + rtn = 0; + + // check if a manual trigger, if so do just the sector on the backside + manual = false; + if (Trig == PushOnce || Trig == PushMany) + { + if (!(sec = LN_BACKSECTOR(line))) + return rtn; + secnum = sec - _g->sectors; + manual = true; + goto manual_floor; + } + + secnum = -1; + // if not manual do all sectors tagged the same as the line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + manual_floor: + // Do not start another function if floor already moving + if (P_SectorActive(floor_special, sec)) + { + if (!manual) + continue; + else + return rtn; + } + + // new floor thinker + rtn = 1; + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + sec->floordata_sptr = getShortPtr(floor); + floor->thinker.function = T_MoveFloor; + floor->crush = Crsh; + floor->direction = Dirn ? 1 : -1; + floor->sector_sptr = getShortPtr(sec); + floor->texture = sec->floorpic; + floor->newspecial = sec->special; + //jff 3/14/98 transfer old special field too + floor->oldspecial = sec->oldspecial; + floor->type = genFloor; + + // set the speed of motion + switch (Sped) + { + case SpeedSlow: + floor->speed = FLOORSPEED; + break; + case SpeedNormal: + floor->speed = FLOORSPEED * 2; + break; + case SpeedFast: + floor->speed = FLOORSPEED * 4; + break; + case SpeedTurbo: + floor->speed = FLOORSPEED * 8; + break; + default: + break; + } + + // set the destination height + switch (Targ) + { + case FtoHnF: + floor->floordestheight = P_FindHighestFloorSurrounding(sec); + break; + case FtoLnF: + floor->floordestheight = P_FindLowestFloorSurrounding(sec); + break; + case FtoNnF: + floor->floordestheight = + Dirn ? P_FindNextHighestFloor(sec, sec->floorheight) : P_FindNextLowestFloor(sec, sec->floorheight); + break; + case FtoLnC: + floor->floordestheight = P_FindLowestCeilingSurrounding(sec); + break; + case FtoC: + floor->floordestheight = sec->ceilingheight; + break; + case FbyST: + floor->floordestheight = (getFloorMoveSector(floor)->floorheight >> FRACBITS) + floor->direction * (P_FindShortestTextureAround(secnum) >> FRACBITS); + if (floor->floordestheight > 32000) //jff 3/13/98 prevent overflow + floor->floordestheight = 32000; // wraparound in floor height + if (floor->floordestheight < -32000) + floor->floordestheight = -32000; + floor->floordestheight <<= FRACBITS; + break; + case Fby24: + floor->floordestheight = getFloorMoveSector(floor)->floorheight + floor->direction * 24 * FRACUNIT; + break; + case Fby32: + floor->floordestheight = getFloorMoveSector(floor)->floorheight + floor->direction * 32 * FRACUNIT; + break; + default: + break; + } + + // set texture/type change properties + if (ChgT) // if a texture change is indicated + { + if (ChgM) // if a numeric model change + { + sector_t *sec; + + //jff 5/23/98 find model with ceiling at target height if target + //is a ceiling type + sec = (Targ == FtoLnC || Targ == FtoC) ? P_FindModelCeilingSector(floor->floordestheight, secnum) : P_FindModelFloorSector(floor->floordestheight, secnum); + if (sec) + { + floor->texture = sec->floorpic; + switch (ChgT) + { + case FChgZero: // zero type + floor->newspecial = 0; + //jff 3/14/98 change old field too + floor->oldspecial = 0; + floor->type = genFloorChg0; + break; + case FChgTyp: // copy type + floor->newspecial = sec->special; + //jff 3/14/98 change old field too + floor->oldspecial = sec->oldspecial; + floor->type = genFloorChgT; + break; + case FChgTxt: // leave type be + floor->type = genFloorChg; + break; + default: + break; + } + } + } + else // else if a trigger model change + { + floor->texture = LN_FRONTSECTOR(line)->floorpic; + switch (ChgT) + { + case FChgZero: // zero type + floor->newspecial = 0; + //jff 3/14/98 change old field too + floor->oldspecial = 0; + floor->type = genFloorChg0; + break; + case FChgTyp: // copy type + floor->newspecial = LN_FRONTSECTOR(line)->special; + //jff 3/14/98 change old field too + floor->oldspecial = LN_FRONTSECTOR(line)->oldspecial; + floor->type = genFloorChgT; + break; + case FChgTxt: // leave type be + floor->type = genFloorChg; + default: + break; + } + } + } + if (manual) + return rtn; + } + return rtn; +} + +// +// EV_DoGenCeiling() +// +// Handle generalized ceiling types +// +// Passed the linedef activating the ceiling function +// Returns true if a thinker created +// +// jff 02/04/98 Added this routine (and file) to handle generalized +// floor movers using bit fields in the line special type. +// +int EV_DoGenCeiling(const line_t *line) +{ + int secnum; + int rtn; + boolean manual; + fixed_t targheight; + sector_t *sec; + ceiling_t *ceiling; + unsigned value = (unsigned) LN_SPECIAL(line) - GenCeilingBase; + + // parse the bit fields in the line's special type + + int Crsh = (value & CeilingCrush) >> CeilingCrushShift; + int ChgT = (value & CeilingChange) >> CeilingChangeShift; + int Targ = (value & CeilingTarget) >> CeilingTargetShift; + int Dirn = (value & CeilingDirection) >> CeilingDirectionShift; + int ChgM = (value & CeilingModel) >> CeilingModelShift; + int Sped = (value & CeilingSpeed) >> CeilingSpeedShift; + int Trig = (value & TriggerType) >> TriggerTypeShift; + + rtn = 0; + + // check if a manual trigger, if so do just the sector on the backside + manual = false; + if (Trig == PushOnce || Trig == PushMany) + { + if (!(sec = LN_BACKSECTOR(line))) + return rtn; + secnum = sec - _g->sectors; + manual = true; + goto manual_ceiling; + } + + secnum = -1; + // if not manual do all sectors tagged the same as the line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + manual_ceiling: + // Do not start another function if ceiling already moving + if (P_SectorActive(ceiling_special, sec)) //jff 2/22/98 + { + if (!manual) + continue; + else + return rtn; + } + + // new ceiling thinker + rtn = 1; + ceiling = Z_Malloc(sizeof(*ceiling), PU_LEVSPEC, 0); + memset(ceiling, 0, sizeof(*ceiling)); + P_AddThinker(&ceiling->thinker); + sec->ceilingdata_sptr = getShortPtr(ceiling); //jff 2/22/98 + ceiling->thinker.function = T_MoveCeiling; + ceiling->crush = Crsh; + ceiling->direction = Dirn ? 1 : -1; + ceiling->sector = sec; + ceiling->texture = sec->ceilingpic; + ceiling->newspecial = sec->special; + //jff 3/14/98 change old field too + ceiling->oldspecial = sec->oldspecial; + ceiling->tag = sec->tag; + ceiling->type = genCeiling; + + // set speed of motion + switch (Sped) + { + case SpeedSlow: + ceiling->speed = CEILSPEED; + break; + case SpeedNormal: + ceiling->speed = CEILSPEED * 2; + break; + case SpeedFast: + ceiling->speed = CEILSPEED * 4; + break; + case SpeedTurbo: + ceiling->speed = CEILSPEED * 8; + break; + default: + break; + } + + // set destination target height + targheight = sec->ceilingheight; + switch (Targ) + { + case CtoHnC: + targheight = P_FindHighestCeilingSurrounding(sec); + break; + case CtoLnC: + targheight = P_FindLowestCeilingSurrounding(sec); + break; + case CtoNnC: + targheight = + Dirn ? P_FindNextHighestCeiling(sec, sec->ceilingheight) : P_FindNextLowestCeiling(sec, sec->ceilingheight); + break; + case CtoHnF: + targheight = P_FindHighestFloorSurrounding(sec); + break; + case CtoF: + targheight = sec->floorheight; + break; + case CbyST: + targheight = (ceiling->sector->ceilingheight >> FRACBITS) + ceiling->direction * (P_FindShortestUpperAround(secnum) >> FRACBITS); + if (targheight > 32000) //jff 3/13/98 prevent overflow + targheight = 32000; // wraparound in ceiling height + if (targheight < -32000) + targheight = -32000; + targheight <<= FRACBITS; + break; + case Cby24: + targheight = ceiling->sector->ceilingheight + ceiling->direction * 24 * FRACUNIT; + break; + case Cby32: + targheight = ceiling->sector->ceilingheight + ceiling->direction * 32 * FRACUNIT; + break; + default: + break; + } + if (Dirn) + ceiling->topheight = targheight; + else + ceiling->bottomheight = targheight; + + // set texture/type change properties + if (ChgT) // if a texture change is indicated + { + if (ChgM) // if a numeric model change + { + sector_t *sec; + + //jff 5/23/98 find model with floor at target height if target + //is a floor type + sec = (Targ == CtoHnF || Targ == CtoF) ? P_FindModelFloorSector(targheight, secnum) : P_FindModelCeilingSector(targheight, secnum); + if (sec) + { + ceiling->texture = sec->ceilingpic; + switch (ChgT) + { + case CChgZero: // type is zeroed + ceiling->newspecial = 0; + //jff 3/14/98 change old field too + ceiling->oldspecial = 0; + ceiling->type = genCeilingChg0; + break; + case CChgTyp: // type is copied + ceiling->newspecial = sec->special; + //jff 3/14/98 change old field too + ceiling->oldspecial = sec->oldspecial; + ceiling->type = genCeilingChgT; + break; + case CChgTxt: // type is left alone + ceiling->type = genCeilingChg; + break; + default: + break; + } + } + } + else // else if a trigger model change + { + ceiling->texture = LN_FRONTSECTOR(line)->ceilingpic; + switch (ChgT) + { + case CChgZero: // type is zeroed + ceiling->newspecial = 0; + //jff 3/14/98 change old field too + ceiling->oldspecial = 0; + ceiling->type = genCeilingChg0; + break; + case CChgTyp: // type is copied + ceiling->newspecial = LN_FRONTSECTOR(line)->special; + //jff 3/14/98 change old field too + ceiling->oldspecial = LN_FRONTSECTOR(line)->oldspecial; + ceiling->type = genCeilingChgT; + break; + case CChgTxt: // type is left alone + ceiling->type = genCeilingChg; + break; + default: + break; + } + } + } + P_AddActiveCeiling(ceiling); // add this ceiling to the active list + if (manual) + return rtn; + } + return rtn; +} + +// +// EV_DoGenLift() +// +// Handle generalized lift types +// +// Passed the linedef activating the lift +// Returns true if a thinker is created +// +int EV_DoGenLift(const line_t *line) +{ + plat_t *plat; + int secnum; + int rtn; + boolean manual; + sector_t *sec; + unsigned value = (unsigned) LN_SPECIAL(line) - GenLiftBase; + + // parse the bit fields in the line's special type + + int Targ = (value & LiftTarget) >> LiftTargetShift; + int Dely = (value & LiftDelay) >> LiftDelayShift; + int Sped = (value & LiftSpeed) >> LiftSpeedShift; + int Trig = (value & TriggerType) >> TriggerTypeShift; + + secnum = -1; + rtn = 0; + + // Activate all plats that are in_stasis + + if (Targ == LnF2HnF) + P_ActivateInStasis(line->tag); + + // check if a manual trigger, if so do just the sector on the backside + manual = false; + if (Trig == PushOnce || Trig == PushMany) + { + if (!(sec = LN_BACKSECTOR(line))) + return rtn; + secnum = sec - _g->sectors; + manual = true; + goto manual_lift; + } + + // if not manual do all sectors tagged the same as the line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + manual_lift: + // Do not start another function if floor already moving + if (P_SectorActive(floor_special, sec)) + { + if (!manual) + continue; + else + return rtn; + } + + // Setup the plat thinker + rtn = 1; + plat = Z_Malloc(sizeof(*plat), PU_LEVSPEC, 0); + memset(plat, 0, sizeof(*plat)); + P_AddThinker(&plat->thinker); + + plat->sector = sec; + plat->sector->floordata_sptr = getShortPtr(plat); + plat->thinker.function = T_PlatRaise; + plat->crush = false; + plat->tag = line->tag; + + plat->type = genLift; + plat->high = sec->floorheight; + plat->status = down; + + // setup the target destination height + switch (Targ) + { + case F2LnF: + plat->low = P_FindLowestFloorSurrounding(sec); + if (plat->low > sec->floorheight) + plat->low = sec->floorheight; + break; + case F2NnF: + plat->low = P_FindNextLowestFloor(sec, sec->floorheight); + break; + case F2LnC: + plat->low = P_FindLowestCeilingSurrounding(sec); + if (plat->low > sec->floorheight) + plat->low = sec->floorheight; + break; + case LnF2HnF: + plat->type = genPerpetual; + plat->low = P_FindLowestFloorSurrounding(sec); + if (plat->low > sec->floorheight) + plat->low = sec->floorheight; + plat->high = P_FindHighestFloorSurrounding(sec); + if (plat->high < sec->floorheight) + plat->high = sec->floorheight; + plat->status = P_Random(__FILE__, __LINE__, __FUNCTION__) & 1; + break; + default: + break; + } + + // setup the speed of motion + switch (Sped) + { + case SpeedSlow: + plat->speed = PLATSPEED * 2; + break; + case SpeedNormal: + plat->speed = PLATSPEED * 4; + break; + case SpeedFast: + plat->speed = PLATSPEED * 8; + break; + case SpeedTurbo: + plat->speed = PLATSPEED * 16; + break; + default: + break; + } + + // setup the delay time before the floor returns + switch (Dely) + { + case 0: + plat->wait = 1 * 35; + break; + case 1: + plat->wait = PLATWAIT * 35; + break; + case 2: + plat->wait = 5 * 35; + break; + case 3: + plat->wait = 10 * 35; + break; + } + + S_StartSound2(&sec->soundorg, sfx_pstart); + P_AddActivePlat(plat); // add this plat to the list of active plats + + if (manual) + return rtn; + } + return rtn; +} + +// +// EV_DoGenStairs() +// +// Handle generalized stair building +// +// Passed the linedef activating the stairs +// Returns true if a thinker is created +// +int EV_DoGenStairs(const line_t *line) +{ + int secnum; + int osecnum; //jff 3/4/98 preserve loop index + int height; + int i; + int newsecnum; + int texture; + int ok; + int rtn; + boolean manual; + + sector_t *sec; + sector_t *tsec; + + floormove_t *floor; + + fixed_t stairsize; + fixed_t speed; + + unsigned value = (unsigned) LN_SPECIAL(line) - GenStairsBase; + + // parse the bit fields in the line's special type + + int Igno = (value & StairIgnore) >> StairIgnoreShift; + int Dirn = (value & StairDirection) >> StairDirectionShift; + int Step = (value & StairStep) >> StairStepShift; + int Sped = (value & StairSpeed) >> StairSpeedShift; + int Trig = (value & TriggerType) >> TriggerTypeShift; + + rtn = 0; + + // check if a manual trigger, if so do just the sector on the backside + manual = false; + if (Trig == PushOnce || Trig == PushMany) + { + if (!(sec = LN_BACKSECTOR(line))) + return rtn; + secnum = sec - _g->sectors; + manual = true; + goto manual_stair; + } + + secnum = -1; + // if not manual do all sectors tagged the same as the line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + manual_stair: + //Do not start another function if floor already moving + //jff 2/26/98 add special lockout condition to wait for entire + //staircase to build before retriggering + if (P_SectorActive(floor_special, sec)) + { + if (!manual) + continue; + else + return rtn; + } + + // new floor thinker + rtn = 1; + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + sec->floordata_sptr = getShortPtr(floor); + floor->thinker.function = T_MoveFloor; + floor->direction = Dirn ? 1 : -1; + floor->sector_sptr = getShortPtr(sec); + + // setup speed of stair building + switch (Sped) + { + default: + case SpeedSlow: + floor->speed = FLOORSPEED / 4; + break; + case SpeedNormal: + floor->speed = FLOORSPEED / 2; + break; + case SpeedFast: + floor->speed = FLOORSPEED * 2; + break; + case SpeedTurbo: + floor->speed = FLOORSPEED * 4; + break; + } + + // setup stepsize for stairs + switch (Step) + { + default: + case 0: + stairsize = 4 * FRACUNIT; + break; + case 1: + stairsize = 8 * FRACUNIT; + break; + case 2: + stairsize = 16 * FRACUNIT; + break; + case 3: + stairsize = 24 * FRACUNIT; + break; + } + + speed = floor->speed; + height = sec->floorheight + floor->direction * stairsize; + floor->floordestheight = height; + texture = sec->floorpic; + floor->crush = false; + floor->type = genBuildStair; // jff 3/31/98 do not leave uninited + + osecnum = secnum; //jff 3/4/98 preserve loop index + // Find next sector to raise + // 1. Find 2-sided line with same sector side[0] + // 2. Other side is the next sector to raise + do + { + ok = 0; + for (i = 0; i < sec->linecount; i++) + { + + if (!LN_BACKSECTOR((getSectorLineByIndex(sec, i)))) + continue; + + tsec = LN_FRONTSECTOR((getSectorLineByIndex(sec, i))); + newsecnum = tsec - _g->sectors; + + if (secnum != newsecnum) + continue; + + tsec = LN_BACKSECTOR((getSectorLineByIndex(sec, i))); + newsecnum = tsec - _g->sectors; + + if (!Igno && tsec->floorpic != texture) + continue; + + //jff 2/26/98 special lockout condition for retriggering + if (P_SectorActive(floor_special, tsec)) + continue; + + height += floor->direction * stairsize; + + sec = tsec; + secnum = newsecnum; + floor = Z_Malloc(sizeof(*floor), PU_LEVSPEC, 0); + + memset(floor, 0, sizeof(*floor)); + P_AddThinker(&floor->thinker); + + sec->floordata_sptr = getShortPtr(floor); + floor->thinker.function = T_MoveFloor; + floor->direction = Dirn ? 1 : -1; + floor->sector_sptr = getShortPtr(sec); + floor->speed = speed; + floor->floordestheight = height; + floor->crush = false; + floor->type = genBuildStair; // jff 3/31/98 do not leave uninited + + ok = 1; + break; + } + } while (ok); + if (manual) + return rtn; + secnum = osecnum; //jff 3/4/98 restore old loop index + } + // retriggerable generalized stairs build up or down alternately + if (rtn) + LN_SPECIAL(line) ^= StairDirection; // alternate dir on succ activations + return rtn; +} + +// +// EV_DoGenCrusher() +// +// Handle generalized crusher types +// +// Passed the linedef activating the crusher +// Returns true if a thinker created +// +int EV_DoGenCrusher(const line_t *line) +{ + int secnum; + int rtn; + boolean manual; + sector_t *sec; + ceiling_t *ceiling; + unsigned value = (unsigned) LN_SPECIAL(line) - GenCrusherBase; + + // parse the bit fields in the line's special type + + int Slnt = (value & CrusherSilent) >> CrusherSilentShift; + int Sped = (value & CrusherSpeed) >> CrusherSpeedShift; + int Trig = (value & TriggerType) >> TriggerTypeShift; + + //jff 2/22/98 Reactivate in-stasis ceilings...for certain types. + //jff 4/5/98 return if activated + rtn = P_ActivateInStasisCeiling(line); + + // check if a manual trigger, if so do just the sector on the backside + manual = false; + if (Trig == PushOnce || Trig == PushMany) + { + if (!(sec = LN_BACKSECTOR(line))) + return rtn; + secnum = sec - _g->sectors; + manual = true; + goto manual_crusher; + } + + secnum = -1; + // if not manual do all sectors tagged the same as the line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + manual_crusher: + // Do not start another function if ceiling already moving + if (P_SectorActive(ceiling_special, sec)) //jff 2/22/98 + { + if (!manual) + continue; + else + return rtn; + } + + // new ceiling thinker + rtn = 1; + ceiling = Z_Malloc(sizeof(*ceiling), PU_LEVSPEC, 0); + memset(ceiling, 0, sizeof(*ceiling)); + P_AddThinker(&ceiling->thinker); + sec->ceilingdata_sptr = getShortPtr(ceiling); //jff 2/22/98 + ceiling->thinker.function = T_MoveCeiling; + ceiling->crush = true; + ceiling->direction = -1; + ceiling->sector = sec; + ceiling->texture = sec->ceilingpic; + ceiling->newspecial = sec->special; + ceiling->tag = sec->tag; + ceiling->type = Slnt ? genSilentCrusher : genCrusher; + ceiling->topheight = sec->ceilingheight; + ceiling->bottomheight = sec->floorheight + (8 * FRACUNIT); + + // setup ceiling motion speed + switch (Sped) + { + case SpeedSlow: + ceiling->speed = CEILSPEED; + break; + case SpeedNormal: + ceiling->speed = CEILSPEED * 2; + break; + case SpeedFast: + ceiling->speed = CEILSPEED * 4; + break; + case SpeedTurbo: + ceiling->speed = CEILSPEED * 8; + break; + default: + break; + } + ceiling->oldspeed = ceiling->speed; + + P_AddActiveCeiling(ceiling); // add to list of active ceilings + if (manual) + return rtn; + } + return rtn; +} + +// +// EV_DoGenLockedDoor() +// +// Handle generalized locked door types +// +// Passed the linedef activating the generalized locked door +// Returns true if a thinker created +// +int EV_DoGenLockedDoor(const line_t *line) +{ + int secnum, rtn; + sector_t *sec; + vldoor_t *door; + boolean manual; + unsigned value = (unsigned) LN_SPECIAL(line) - GenLockedBase; + + // parse the bit fields in the line's special type + + int Kind = (value & LockedKind) >> LockedKindShift; + int Sped = (value & LockedSpeed) >> LockedSpeedShift; + int Trig = (value & TriggerType) >> TriggerTypeShift; + + rtn = 0; + + // check if a manual trigger, if so do just the sector on the backside + manual = false; + if (Trig == PushOnce || Trig == PushMany) + { + if (!(sec = LN_BACKSECTOR(line))) + return rtn; + secnum = sec - _g->sectors; + manual = true; + goto manual_locked; + } + + secnum = -1; + rtn = 0; + + // if not manual do all sectors tagged the same as the line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + manual_locked: + // Do not start another function if ceiling already moving + if (P_SectorActive(ceiling_special, sec)) //jff 2/22/98 + { + if (!manual) + continue; + else + return rtn; + } + + // new door thinker + rtn = 1; + door = Z_Malloc(sizeof(*door), PU_LEVSPEC, 0); + memset(door, 0, sizeof(*door)); + P_AddThinker(&door->thinker); + sec->ceilingdata_sptr = getShortPtr(door); //jff 2/22/98 + + door->thinker.function = T_VerticalDoor; + door->sector = sec; + door->topwait = VDOORWAIT; + door->line = line; + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + door->direction = 1; + + /* killough 10/98: implement gradual lighting */ + door->lighttag = (LN_SPECIAL(line) & 6) == 6 && + LN_SPECIAL(line) > GenLockedBase ? line->tag : 0; + + // setup speed of door motion + switch (Sped) + { + default: + case SpeedSlow: + door->type = Kind ? genOpen : genRaise; + door->speed = VDOORSPEED; + break; + case SpeedNormal: + door->type = Kind ? genOpen : genRaise; + door->speed = VDOORSPEED * 2; + break; + case SpeedFast: + door->type = Kind ? genBlazeOpen : genBlazeRaise; + door->speed = VDOORSPEED * 4; + break; + case SpeedTurbo: + door->type = Kind ? genBlazeOpen : genBlazeRaise; + door->speed = VDOORSPEED * 8; + + break; + } + + // killough 4/15/98: fix generalized door opening sounds + // (previously they always had the blazing door close sound) + + S_StartSound2(&door->sector->soundorg, // killough 4/15/98 + door->speed >= VDOORSPEED * 4 ? sfx_bdopn : sfx_doropn); + + if (manual) + return rtn; + } + return rtn; +} + +// +// EV_DoGenDoor() +// +// Handle generalized door types +// +// Passed the linedef activating the generalized door +// Returns true if a thinker created +// +int EV_DoGenDoor(const line_t *line) +{ + int secnum, rtn; + sector_t *sec; + boolean manual; + vldoor_t *door; + unsigned value = (unsigned) LN_SPECIAL(line) - GenDoorBase; + + // parse the bit fields in the line's special type + + int Dely = (value & DoorDelay) >> DoorDelayShift; + int Kind = (value & DoorKind) >> DoorKindShift; + int Sped = (value & DoorSpeed) >> DoorSpeedShift; + int Trig = (value & TriggerType) >> TriggerTypeShift; + + rtn = 0; + + // check if a manual trigger, if so do just the sector on the backside + manual = false; + if (Trig == PushOnce || Trig == PushMany) + { + if (!(sec = LN_BACKSECTOR(line))) + return rtn; + secnum = sec - _g->sectors; + manual = true; + goto manual_door; + } + + secnum = -1; + rtn = 0; + + // if not manual do all sectors tagged the same as the line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + manual_door: + // Do not start another function if ceiling already moving + if (P_SectorActive(ceiling_special, sec)) //jff 2/22/98 + { + if (!manual) + continue; + else + return rtn; + } + + // new door thinker + rtn = 1; + door = Z_Malloc(sizeof(*door), PU_LEVSPEC, 0); + memset(door, 0, sizeof(*door)); + P_AddThinker(&door->thinker); + sec->ceilingdata_sptr = getShortPtr(door); //jff 2/22/98 + + door->thinker.function = T_VerticalDoor; + door->sector = sec; + // setup delay for door remaining open/closed + switch (Dely) + { + default: + case 0: + door->topwait = 35; + break; + case 1: + door->topwait = VDOORWAIT; + break; + case 2: + door->topwait = 2 * VDOORWAIT; + break; + case 3: + door->topwait = 7 * VDOORWAIT; + break; + } + + // setup speed of door motion + switch (Sped) + { + default: + case SpeedSlow: + door->speed = VDOORSPEED; + break; + case SpeedNormal: + door->speed = VDOORSPEED * 2; + break; + case SpeedFast: + door->speed = VDOORSPEED * 4; + break; + case SpeedTurbo: + door->speed = VDOORSPEED * 8; + break; + } + door->line = line; // jff 1/31/98 remember line that triggered us + + /* killough 10/98: implement gradual lighting */ + door->lighttag = (LN_SPECIAL(line) & 6) == 6 && + LN_SPECIAL(line) > GenLockedBase ? line->tag : 0; + + // set kind of door, whether it opens then close, opens, closes etc. + // assign target heights accordingly + switch (Kind) + { + case OdCDoor: + door->direction = 1; + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + if (door->topheight != sec->ceilingheight) + S_StartSound2(&door->sector->soundorg, + Sped >= SpeedFast ? sfx_bdopn : sfx_doropn); + door->type = Sped >= SpeedFast ? genBlazeRaise : genRaise; + break; + case ODoor: + door->direction = 1; + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + if (door->topheight != sec->ceilingheight) + S_StartSound2(&door->sector->soundorg, + Sped >= SpeedFast ? sfx_bdopn : sfx_doropn); + door->type = Sped >= SpeedFast ? genBlazeOpen : genOpen; + break; + case CdODoor: + door->topheight = sec->ceilingheight; + door->direction = -1; + S_StartSound2(&door->sector->soundorg, + Sped >= SpeedFast ? sfx_bdcls : sfx_dorcls); + door->type = Sped >= SpeedFast ? genBlazeCdO : genCdO; + break; + case CDoor: + door->topheight = P_FindLowestCeilingSurrounding(sec); + door->topheight -= 4 * FRACUNIT; + door->direction = -1; + S_StartSound2(&door->sector->soundorg, + Sped >= SpeedFast ? sfx_bdcls : sfx_dorcls); + door->type = Sped >= SpeedFast ? genBlazeClose : genClose; + break; + default: + break; + } + if (manual) + return rtn; + } + return rtn; +} diff --git a/doom/src/pdoom/Doom/source/p_inter.c b/doom/src/pdoom/Doom/source/p_inter.c new file mode 100644 index 0000000..3d3323a --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_inter.c @@ -0,0 +1,866 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Handling interactions (i.e., collisions). + * + * next-hack: modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "dstrings.h" +#include "m_random.h" +#include "am_map.h" +#include "r_main.h" +#include "s_sound.h" +#include "sounds.h" +#include "p_tick.h" +#include "lprintf.h" + +#include "p_inter.h" +#include "p_enemy.h" + +#include "global_data.h" + +#ifdef __GNUG__ +#pragma implementation "p_inter.h" +#endif +#include "p_inter.h" + +#define BONUSADD 6 + +// Ty 03/07/98 - add deh externals +// Maximums and such were hardcoded values. Need to externalize those for +// dehacked support (and future flexibility). Most var names came from the key +// strings used in dehacked. + +const int initial_health = 100; +const int initial_bullets = 50; +const int maxhealth = 100; // was MAXHEALTH as a #define, used only in this module +const int max_armor = 200; +const int green_armor_class = 1; // these are involved with armortype below +const int blue_armor_class = 2; +const int max_soul = 200; +const int soul_health = 100; +const int mega_health = 200; +const int god_health = 100; // these are used in cheats (see st_stuff.c) +const int idfa_armor = 200; +const int idfa_armor_class = 2; +// not actually used due to pairing of cheat_k and cheat_fa +const int idkfa_armor = 200; +const int idkfa_armor_class = 2; + +const int bfgcells = 40; // used in p_pspr.c +// Ty 03/07/98 - end deh externals + +// a weapon is found with two clip loads, +// a big item has five clip loads +const int maxammo[NUMAMMO] = { 200, 50, 300, 50 }; +const int clipammo[NUMAMMO] = { 10, 4, 20, 1 }; + +// +// GET STUFF +// + +// +// P_GiveAmmo +// Num is the number of clip loads, +// not the individual count (0= 1/2 clip). +// Returns false if the ammo can't be picked up at all +// + +static boolean P_GiveAmmo(player_t *player, ammotype_t ammo, int num) +{ + int oldammo; + + if (ammo == am_noammo) + return false; + +#ifdef RANGECHECK + if (ammo < 0 || ammo > NUMAMMO) + I_Error ("P_GiveAmmo: bad type %i", ammo); +#endif + + if (player->ammo[ammo] == player->maxammo[ammo]) + return false; + + if (num) + num *= clipammo[ammo]; + else + num = clipammo[ammo] / 2; + + // give double ammo in trainer mode, you'll need in nightmare + if (_g->gameskill == sk_baby || _g->gameskill == sk_nightmare) + num <<= 1; + + oldammo = player->ammo[ammo]; + player->ammo[ammo] += num; + + if (player->ammo[ammo] > player->maxammo[ammo]) + player->ammo[ammo] = player->maxammo[ammo]; + + // If non zero ammo, don't change up weapons, player was lower on purpose. + if (oldammo) + return true; + + // We were down to zero, so select a new weapon. + // Preferences are not user selectable. + + switch (ammo) + { + case am_clip: + if (player->readyweapon == wp_fist) + { + if (player->weaponowned[wp_chaingun]) + player->pendingweapon = wp_chaingun; + else + player->pendingweapon = wp_pistol; + } + break; + + case am_shell: + if (player->readyweapon == wp_fist || player->readyweapon == wp_pistol) + { + if (player->weaponowned[wp_shotgun]) + player->pendingweapon = wp_shotgun; + } + break; + + case am_cell: + if (player->readyweapon == wp_fist || player->readyweapon == wp_pistol) + { + if (player->weaponowned[wp_plasma]) + player->pendingweapon = wp_plasma; + } + break; + + case am_misl: + if (player->readyweapon == wp_fist) + { + if (player->weaponowned[wp_missile]) + player->pendingweapon = wp_missile; + } + break; + default: + break; + } + return true; +} + +// +// P_GiveWeapon +// The weapon name may have a MF_DROPPED flag ored in. +// + +static boolean P_GiveWeapon(player_t *player, weapontype_t weapon, boolean dropped) +{ + boolean gaveammo; + boolean gaveweapon; + + if (weaponinfo[weapon].ammo != am_noammo) + { + // give one clip with a dropped weapon, + // two clips with a found weapon + gaveammo = P_GiveAmmo(player, weaponinfo[weapon].ammo, dropped ? 1 : 2); + } + else + gaveammo = false; + + if (player->weaponowned[weapon]) + gaveweapon = false; + else + { + gaveweapon = true; + player->weaponowned[weapon] = true; + player->pendingweapon = weapon; + } + return gaveweapon || gaveammo; +} + +// +// P_GiveBody +// Returns false if the body isn't needed at all +// + +static boolean P_GiveBody(player_t *player, int num) +{ + if (player->health >= maxhealth) + return false; // Ty 03/09/98 externalized MAXHEALTH to maxhealth + player->health += num; + if (player->health > maxhealth) + player->health = maxhealth; + player->mo->health = player->health; + return true; +} + +// +// P_GiveArmor +// Returns false if the armor is worse +// than the current armor. +// + +static boolean P_GiveArmor(player_t *player, int armortype) +{ + int hits = armortype * 100; + if (player->armorpoints >= hits) + return false; // don't pick up + player->armortype = armortype; + player->armorpoints = hits; + return true; +} + +// +// P_GiveCard +// + +static void P_GiveCard(player_t *player, card_t card) +{ + if (player->cards[card]) + return; + player->bonuscount = BONUSADD; + player->cards[card] = 1; +} + +// +// P_GivePower +// +// Rewritten by Lee Killough +// + +boolean P_GivePower(player_t *player, int power) +{ + static const int tics[NUMPOWERS] = + { INVULNTICS, 1 /* strength */, INVISTICS, IRONTICS, 1 /* allmap */, INFRATICS, }; + + switch (power) + { + case pw_invisibility: + player->mo->flags |= MF_SHADOW; + break; + case pw_allmap: + if (player->powers[pw_allmap]) + return false; + break; + case pw_strength: + P_GiveBody(player, 100); + break; + } + + // Unless player has infinite duration cheat, set duration (killough) + + if (player->powers[power] >= 0) + player->powers[power] = tics[power]; + return true; +} + +// +// P_TouchSpecialThing +// +void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher) +{ + player_t *player; + int i; + int sound; + fixed_t delta = special->z - toucher->z; + + if (delta > getMobjHeight(toucher) || delta < -8 * FRACUNIT) + return; // out of reach + + sound = sfx_itemup; + player = getMobjPlayer(toucher); + + // Dead thing touching. + // Can happen with a sliding player corpse. + if (toucher->health <= 0) + return; + + // Identify by sprite. + switch (special->sprite) + { + // armor + case SPR_ARM1: + if (!P_GiveArmor(player, green_armor_class)) + return; + player->message = GOTARMOR; // Ty 03/22/98 - externalized + break; + + case SPR_ARM2: + if (!P_GiveArmor(player, blue_armor_class)) + return; + player->message = GOTMEGA; // Ty 03/22/98 - externalized + break; + + // bonus items + case SPR_BON1: + player->health++; // can go over 100% + if (player->health > (maxhealth * 2)) + player->health = (maxhealth * 2); + player->mo->health = player->health; + player->message = GOTHTHBONUS; // Ty 03/22/98 - externalized + break; + + case SPR_BON2: + player->armorpoints++; // can go over 100% + if (player->armorpoints > max_armor) + player->armorpoints = max_armor; + if (!player->armortype) + player->armortype = green_armor_class; + player->message = GOTARMBONUS; // Ty 03/22/98 - externalized + break; + + case SPR_SOUL: + player->health += soul_health; + if (player->health > max_soul) + player->health = max_soul; + player->mo->health = player->health; + player->message = GOTSUPER; // Ty 03/22/98 - externalized + sound = sfx_getpow; + break; + + case SPR_MEGA: + if (_g->gamemode != commercial) + return; + player->health = mega_health; + player->mo->health = player->health; + P_GiveArmor(player, blue_armor_class); + player->message = GOTMSPHERE; // Ty 03/22/98 - externalized + sound = sfx_getpow; + break; + + // cards + // leave cards for everyone + case SPR_BKEY: + if (!player->cards[it_bluecard]) + player->message = GOTBLUECARD; // Ty 03/22/98 - externalized + P_GiveCard(player, it_bluecard); + break; + + case SPR_YKEY: + if (!player->cards[it_yellowcard]) + player->message = GOTYELWCARD; // Ty 03/22/98 - externalized + P_GiveCard(player, it_yellowcard); + break; + + case SPR_RKEY: + if (!player->cards[it_redcard]) + player->message = GOTREDCARD; // Ty 03/22/98 - externalized + P_GiveCard(player, it_redcard); + break; + + case SPR_BSKU: + if (!player->cards[it_blueskull]) + player->message = GOTBLUESKUL; // Ty 03/22/98 - externalized + P_GiveCard(player, it_blueskull); + break; + + case SPR_YSKU: + if (!player->cards[it_yellowskull]) + player->message = GOTYELWSKUL; // Ty 03/22/98 - externalized + P_GiveCard(player, it_yellowskull); + break; + + case SPR_RSKU: + if (!player->cards[it_redskull]) + player->message = GOTREDSKULL; // Ty 03/22/98 - externalized + P_GiveCard(player, it_redskull); + break; + + // medikits, heals + case SPR_STIM: + if (!P_GiveBody(player, 10)) + return; + player->message = GOTSTIM; // Ty 03/22/98 - externalized + break; + + case SPR_MEDI: + if (!P_GiveBody(player, 25)) + return; + + if (player->health < 50) // cph - 25 + the 25 just added, thanks to Quasar for reporting this bug + player->message = GOTMEDINEED; // Ty 03/22/98 - externalized + else + player->message = GOTMEDIKIT; // Ty 03/22/98 - externalized + break; + + // power ups + case SPR_PINV: + if (!P_GivePower(player, pw_invulnerability)) + return; + player->message = GOTINVUL; // Ty 03/22/98 - externalized + sound = sfx_getpow; + break; + + case SPR_PSTR: + if (!P_GivePower(player, pw_strength)) + return; + player->message = GOTBERSERK; // Ty 03/22/98 - externalized + if (player->readyweapon != wp_fist) + player->pendingweapon = wp_fist; + sound = sfx_getpow; + break; + + case SPR_PINS: + if (!P_GivePower(player, pw_invisibility)) + return; + player->message = GOTINVIS; // Ty 03/22/98 - externalized + sound = sfx_getpow; + break; + + case SPR_SUIT: + if (!P_GivePower(player, pw_ironfeet)) + return; + player->message = GOTSUIT; // Ty 03/22/98 - externalized + sound = sfx_getpow; + break; + + case SPR_PMAP: + if (!P_GivePower(player, pw_allmap)) + return; + player->message = GOTMAP; // Ty 03/22/98 - externalized + sound = sfx_getpow; + break; + + case SPR_PVIS: + if (!P_GivePower(player, pw_infrared)) + return; + player->message = GOTVISOR; // Ty 03/22/98 - externalized + sound = sfx_getpow; + break; + + // ammo + case SPR_CLIP: + if (special->flags & MF_DROPPED) + { + if (!P_GiveAmmo(player, am_clip, 0)) + return; + } + else + { + if (!P_GiveAmmo(player, am_clip, 1)) + return; + } + player->message = GOTCLIP; // Ty 03/22/98 - externalized + break; + + case SPR_AMMO: + if (!P_GiveAmmo(player, am_clip, 5)) + return; + player->message = GOTCLIPBOX; // Ty 03/22/98 - externalized + break; + + case SPR_ROCK: + if (!P_GiveAmmo(player, am_misl, 1)) + return; + player->message = GOTROCKET; // Ty 03/22/98 - externalized + break; + + case SPR_BROK: + if (!P_GiveAmmo(player, am_misl, 5)) + return; + player->message = GOTROCKBOX; // Ty 03/22/98 - externalized + break; + + case SPR_CELL: + if (!P_GiveAmmo(player, am_cell, 1)) + return; + player->message = GOTCELL; // Ty 03/22/98 - externalized + break; + + case SPR_CELP: + if (!P_GiveAmmo(player, am_cell, 5)) + return; + player->message = GOTCELLBOX; // Ty 03/22/98 - externalized + break; + + case SPR_SHEL: + if (!P_GiveAmmo(player, am_shell, 1)) + return; + player->message = GOTSHELLS; // Ty 03/22/98 - externalized + break; + + case SPR_SBOX: + if (!P_GiveAmmo(player, am_shell, 5)) + return; + player->message = GOTSHELLBOX; // Ty 03/22/98 - externalized + break; + + case SPR_BPAK: + if (!player->backpack) + { + for (i = 0; i < NUMAMMO; i++) + player->maxammo[i] *= 2; + player->backpack = true; + } + for (i = 0; i < NUMAMMO; i++) + P_GiveAmmo(player, i, 1); + player->message = GOTBACKPACK; // Ty 03/22/98 - externalized + break; + + // weapons + case SPR_BFUG: + if (!P_GiveWeapon(player, wp_bfg, false)) + return; + player->message = GOTBFG9000; // Ty 03/22/98 - externalized + sound = sfx_wpnup; + break; + + case SPR_MGUN: + if (!P_GiveWeapon(player, wp_chaingun, (special->flags & MF_DROPPED ) != 0)) + return; + player->message = GOTCHAINGUN; // Ty 03/22/98 - externalized + sound = sfx_wpnup; + break; + + case SPR_CSAW: + if (!P_GiveWeapon(player, wp_chainsaw, false)) + return; + player->message = GOTCHAINSAW; // Ty 03/22/98 - externalized + sound = sfx_wpnup; + break; + + case SPR_LAUN: + if (!P_GiveWeapon(player, wp_missile, false)) + return; + player->message = GOTLAUNCHER; // Ty 03/22/98 - externalized + sound = sfx_wpnup; + break; + + case SPR_PLAS: + if (!P_GiveWeapon(player, wp_plasma, false)) + return; + player->message = GOTPLASMA; // Ty 03/22/98 - externalized + sound = sfx_wpnup; + break; + + case SPR_SHOT: + if (!P_GiveWeapon(player, wp_shotgun, (special->flags & MF_DROPPED ) != 0)) + return; + player->message = GOTSHOTGUN; // Ty 03/22/98 - externalized + sound = sfx_wpnup; + break; + + case SPR_SGN2: + if (!P_GiveWeapon(player, wp_supershotgun, (special->flags & MF_DROPPED ) != 0)) + return; + player->message = GOTSHOTGUN2; // Ty 03/22/98 - externalized + sound = sfx_wpnup; + break; + + default: + I_Error("P_SpecialThing: Unknown gettable thing"); + } + + if (special->flags & MF_COUNTITEM) + player->itemcount++; + P_RemoveMobj(special); + player->bonuscount += BONUSADD; + + /* cph 20028/10 - for old-school DM addicts, allow old behavior + * where only consoleplayer's pickup sounds are heard */ + // displayplayer, not consoleplayer, for viewing multiplayer demos + if (player == &_g->player) + S_StartSound(player->mo, sound | PICKUP_SOUND); // killough 4/25/98 +} + +// +// KillMobj +// +// killough 11/98: make static +static void P_KillMobj(mobj_t *source, mobj_t *target) +{ + mobjtype_t item; + mobj_t *mo; + + target->flags &= ~(MF_SHOOTABLE | MF_FLOAT | MF_SKULLFLY ); + demodbgprintf("KillMobj target type %d\r\n",target->type); + + if (target->type != MT_SKULL) + target->flags &= ~MF_NOGRAVITY; + // TODO: we can exploit MF_CORPSE to reuse mobjs + target->flags |= MF_CORPSE | MF_DROPOFF; + target->height_s >>= 2; + + if (!((target->flags ^ MF_COUNTKILL ) & (MF_FRIEND | MF_COUNTKILL ))) + _g->totallive--; + + if (source && getMobjPlayer(source)) + { + // count for intermission + if (target->flags & MF_COUNTKILL) + getMobjPlayer(source)->killcount++; + if (getMobjPlayer(target)) + getMobjPlayer(source)->frags[getMobjPlayer(target) - &_g->player]++; + } + else if (target->flags & MF_COUNTKILL) + { /* Add to kills tally */ + + // count all monster deaths, + // even those caused by other monsters + _g->player.killcount++; + + } + + if (target->player_sptr) + { + // count environment kills against you + if (!source) + getMobjPlayer(target)->frags[getMobjPlayer(target) - &_g->player]++; + + target->flags &= ~MF_SOLID; + getMobjPlayer(target)->playerstate = PST_DEAD; + P_DropWeapon(getMobjPlayer(target)); + + if (getMobjPlayer(target) == &_g->player && (_g->automapmode & am_active)) + AM_Stop(); // don't die in auto map; switch view prior to dying + } + + if (target->health < -getMobjInfo(target)->spawnhealth && getMobjInfo(target)->xdeathstate) + P_SetMobjState(target, getMobjInfo(target)->xdeathstate); + else + P_SetMobjState(target, getMobjInfo(target)->deathstate); + + target->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 3; + + if (target->tics < 1) + target->tics = 1; + + // Drop stuff. + // This determines the kind of object spawned + // during the death frame of a thing. + + if ((_g->player.cheats & CF_ENEMY_ROCKETS) && (target->type >= MT_POSSESSED) && (target->type <= MT_KEEN)) + { + item = MT_MISC27; //Everyone drops a rocket launcher. + } + else + { + switch (target->type) + { + case MT_WOLFSS: + case MT_POSSESSED: + item = MT_CLIP; + break; + + case MT_SHOTGUY: + item = MT_SHOTGUN; + break; + + case MT_CHAINGUY: + item = MT_CHAINGUN; + break; + + default: + return; + } + } + mo = P_SpawnMobj(target->x, target->y, ONFLOORZ, item); + mo->flags |= MF_DROPPED; // special versions of items +} + +// +// P_DamageMobj +// Damages both enemies and players +// "inflictor" is the thing that caused the damage +// creature or missile, can be NULL (slime, etc) +// "source" is the thing to target after taking damage +// creature or NULL +// Source and inflictor are the same for melee attacks. +// Source can be NULL for slime, barrel explosions +// and other environmental stuff. +// + +void P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, int damage) +{ + player_t *player; + boolean justhit = false; /* killough 11/98 */ + + /* killough 8/31/98: allow bouncers to take damage */ + if (!(target->flags & (MF_SHOOTABLE ))) + return; // shouldn't happen... + + if (target->health <= 0) + return; + + if (target->flags & MF_SKULLFLY) + target->momx = target->momy = target->momz = 0; + + player = getMobjPlayer(target); + if (player && _g->gameskill == sk_baby) + damage >>= 1; // take half damage in trainer mode + + // Some close combat weapons should not + // inflict thrust and push the victim out of reach, + // thus kick away unless using the chainsaw. + + if (inflictor && !(target->flags & MF_NOCLIP ) && (!source || !getMobjPlayer(source) || getMobjPlayer(source)->readyweapon != wp_chainsaw)) + { + unsigned ang = R_PointToAngle2(inflictor->x, inflictor->y, target->x, target->y); + + fixed_t thrust = damage * (FRACUNIT >> 3) * 100 / getMobjInfo(target)->mass; + + // make fall forwards sometimes + if (damage < 40 && damage > target->health && target->z - inflictor->z > 64 * FRACUNIT && (P_Random(__FILE__, __LINE__, __FUNCTION__) & 1)) + { + ang += ANG180; + thrust *= 4; + } + + ang >>= ANGLETOFINESHIFT; + target->momx += FixedMul(thrust, finecosine[ang]); + target->momy += FixedMul(thrust, finesine[ang]); + } + + // player specific + if (player) + { + demodbgprintf("DamageMobj: health %d, damage %d, attacker x,y %d, %d\r\n", player->health, damage, source != NULL ? source->x : -1, source != NULL ? source->y : 0); + // end of game hell hack + if (getMobjSubsector(target)->sector->special == 11 && damage >= target->health) + damage = target->health - 1; + + // Below certain threshold, + // ignore damage in GOD mode, or with INVUL power. + // killough 3/26/98: make god mode 100% god mode in non-compat mode + + if ((damage < 1000 || ((player->cheats & CF_GODMODE))) && ((player->cheats & CF_GODMODE) || player->powers[pw_invulnerability])) + return; + + if (player->armortype) + { + int saved = player->armortype == 1 ? damage / 3 : damage / 2; + if (player->armorpoints <= saved) + { + // armor is used up + saved = player->armorpoints; + player->armortype = 0; + } + player->armorpoints -= saved; + damage -= saved; + } + + player->health -= damage; // mirror mobj health here for Dave + if (player->health < 0) + player->health = 0; + + player->attacker = source; + player->damagecount += damage; // add damage after armor / invuln + + if (player->damagecount > 100) + player->damagecount = 100; // teleport stomp does 10k points... + } + + // do the damage + target->health -= damage; + if (target->health <= 0) + { + P_KillMobj(source, target); + return; + } + + if (!demo_compatibility) + { + /* If target is a player, set player's target to source, + * so that a friend can tell who's hurting a player + */ + if (player) + //P_SetTarget(&target->target, source); + target->target_sptr = getShortPtr(source); + if (P_Random(__FILE__, __LINE__, __FUNCTION__) < getMobjInfo(target)->painchance && !(target->flags & MF_SKULLFLY )) + { //killough 11/98: see below + justhit = true; + + P_SetMobjState(target, getMobjInfo(target)->painstate); + } + + target->reactiontime = 0; // we're awake now... + + /* killough 9/9/98: cleaned up, made more consistent: */ + + if (source && source != target && source->type != MT_VILE && (!target->threshold || target->type == MT_VILE)) + { + /* if not intent on another player, chase after this one + * + * killough 2/15/98: remember last enemy, to prevent + * sleeping early; 2/21/98: Place priority on players + * killough 9/9/98: cleaned up, made more consistent: + */ + #warning this can be removed + if (0 == target->lastenemy_sptr || getLastEnemy(target)->health <= 0 || (!((target->flags ^ getLastEnemy(target)->flags) & MF_FRIEND ) && getTarget(target) != source)) // remember last enemy - killough + { + //P_SetTarget(getLastEnemy(target), target->target); + target->lastenemy_sptr = target->target_sptr; + } + // P_SetTarget(&target->target, source); // killough 11/98 + target->target_sptr = getShortPtr(source); + target->threshold = BASETHRESHOLD; + if (getMobjState(target) == &states[getMobjInfo(target)->spawnstate] && getMobjInfo(target)->seestate != S_NULL) + P_SetMobjState(target, getMobjInfo(target)->seestate); + } + + /* killough 11/98: Don't attack a friend, unless hit by that friend. + * cph 2006/04/01 - implicitly this is only if mbf_features */ + { + if (justhit && (getTarget(target) == source || !getTarget(target) || !(target->flags & getTarget(target)->flags & MF_FRIEND ))) + target->flags |= MF_JUSTHIT; // fight back! + } + } + else + { + if (P_Random(__FILE__, __LINE__, __FUNCTION__) < getMobjInfo(target)->painchance && !(target->flags & MF_SKULLFLY )) + { + target->flags |= MF_JUSTHIT; // fight back! + + P_SetMobjState (target, getMobjInfo(target)->painstate); + } + target->reactiontime = 0; // we're awake now... + + if ( (!target->threshold || target->type == MT_VILE) + && source && source != target + && source->type != MT_VILE) + { + // if not intent on another player, + // chase after this one + target->target_sptr = getShortPtr(source); + target->threshold = BASETHRESHOLD; + if (getMobjState(target) == &states[getMobjInfo(target)->spawnstate] && getMobjInfo(target)->seestate != S_NULL) + P_SetMobjState(target, getMobjInfo(target)->seestate); + } + } +} diff --git a/doom/src/pdoom/Doom/source/p_lights.c b/doom/src/pdoom/Doom/source/p_lights.c new file mode 100644 index 0000000..62fc084 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_lights.c @@ -0,0 +1,447 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Action routines for lighting thinkers + * Spawn sector based lighting effects. + * Handle lighting linedef types + * + * next-hack: modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" //jff 5/18/98 +#include "doomdef.h" +#include "m_random.h" +#include "r_main.h" +#include "p_spec.h" +#include "p_tick.h" + +#include "global_data.h" + +////////////////////////////////////////////////////////// +// +// Lighting action routines, called once per tick +// +////////////////////////////////////////////////////////// + +// +// T_FireFlicker() +// +// Firelight flicker action routine, called once per tick +// +// Passed a fireflicker_t structure containing light levels and timing +// Returns nothing +// +void T_FireFlicker(fireflicker_t *flick) +{ + int amount; + + if (--flick->count) + return; + + amount = (P_Random(__FILE__, __LINE__, __FUNCTION__) & 3) * 16; + + if (flick->sector->lightlevel - amount < flick->minlight) + flick->sector->lightlevel = flick->minlight; + else + flick->sector->lightlevel = flick->maxlight - amount; + + flick->count = 4; +} + +// +// T_LightFlash() +// +// Broken light flashing action routine, called once per tick +// +// Passed a lightflash_t structure containing light levels and timing +// Returns nothing +// +void T_LightFlash(lightflash_t *flash) +{ + if (--flash->count) + return; + + if (flash->sector->lightlevel == flash->maxlight) + { + flash->sector->lightlevel = flash->minlight; + flash->count = (P_Random(__FILE__, __LINE__, __FUNCTION__) & flash->mintime) + 1; + } + else + { + flash->sector->lightlevel = flash->maxlight; + flash->count = (P_Random(__FILE__, __LINE__, __FUNCTION__) & flash->maxtime) + 1; + } + +} + +// +// T_StrobeFlash() +// +// Strobe light flashing action routine, called once per tick +// +// Passed a strobe_t structure containing light levels and timing +// Returns nothing +// +void T_StrobeFlash(strobe_t *flash) +{ + if (--flash->count) + return; + + if (flash->sector->lightlevel == flash->minlight) + { + flash->sector->lightlevel = flash->maxlight; + flash->count = flash->brighttime; + } + else + { + flash->sector->lightlevel = flash->minlight; + flash->count = flash->darktime; + } +} + +// +// T_Glow() +// +// Glowing light action routine, called once per tick +// +// Passed a glow_t structure containing light levels and timing +// Returns nothing +// + +void T_Glow(glow_t *g) +{ + switch (g->direction) + { + case -1: + // light dims + g->sector->lightlevel -= GLOWSPEED; + if (g->sector->lightlevel <= g->minlight) + { + g->sector->lightlevel += GLOWSPEED; + g->direction = 1; + } + break; + + case 1: + // light brightens + g->sector->lightlevel += GLOWSPEED; + if (g->sector->lightlevel >= g->maxlight) + { + g->sector->lightlevel -= GLOWSPEED; + g->direction = -1; + } + break; + } +} + +////////////////////////////////////////////////////////// +// +// Sector lighting type spawners +// +// After the map has been loaded, each sector is scanned +// for specials that spawn thinkers +// +////////////////////////////////////////////////////////// + +// +// P_SpawnFireFlicker() +// +// Spawns a fire flicker lighting thinker +// +// Passed the sector that spawned the thinker +// Returns nothing +// +void P_SpawnFireFlicker(sector_t *sector) +{ + fireflicker_t *flick; + + // Note that we are resetting sector attributes. + // Nothing special about it during gameplay. + sector->special &= ~31; //jff 3/14/98 clear non-generalized sector type + + flick = Z_Malloc(sizeof(*flick), PU_LEVSPEC, 0); + + memset(flick, 0, sizeof(*flick)); + P_AddThinker(&flick->thinker); + + flick->thinker.function = T_FireFlicker; + flick->sector = sector; + flick->maxlight = sector->lightlevel; + flick->minlight = P_FindMinSurroundingLight(sector, sector->lightlevel) + 16; + flick->count = 4; +} + +// +// P_SpawnLightFlash() +// +// Spawns a broken light flash lighting thinker +// +// Passed the sector that spawned the thinker +// Returns nothing +// +void P_SpawnLightFlash(sector_t *sector) +{ + lightflash_t *flash; + + // nothing special about it during gameplay + sector->special &= ~31; //jff 3/14/98 clear non-generalized sector type + + flash = Z_Malloc(sizeof(*flash), PU_LEVSPEC, 0); + + memset(flash, 0, sizeof(*flash)); + P_AddThinker(&flash->thinker); + + flash->thinker.function = T_LightFlash; + flash->sector = sector; + flash->maxlight = sector->lightlevel; + + flash->minlight = P_FindMinSurroundingLight(sector, sector->lightlevel); + flash->maxtime = 64; + flash->mintime = 7; + flash->count = (P_Random(__FILE__, __LINE__, __FUNCTION__) & flash->maxtime) + 1; +} + +// +// P_SpawnStrobeFlash +// +// Spawns a blinking light thinker +// +// Passed the sector that spawned the thinker, speed of blinking +// and whether blinking is to by syncrhonous with other sectors +// +// Returns nothing +// +void P_SpawnStrobeFlash(sector_t *sector, int fastOrSlow, int inSync) +{ + strobe_t *flash; + + flash = Z_Malloc(sizeof(*flash), PU_LEVSPEC, 0); + + memset(flash, 0, sizeof(*flash)); + P_AddThinker(&flash->thinker); + + flash->sector = sector; + flash->darktime = fastOrSlow; + flash->brighttime = STROBEBRIGHT; + flash->thinker.function = T_StrobeFlash; + flash->maxlight = sector->lightlevel; + flash->minlight = P_FindMinSurroundingLight(sector, sector->lightlevel); + + if (flash->minlight == flash->maxlight) + flash->minlight = 0; + + // nothing special about it during gameplay + sector->special &= ~31; //jff 3/14/98 clear non-generalized sector type + + if (!inSync) + flash->count = (P_Random(__FILE__, __LINE__, __FUNCTION__) & 7) + 1; + else + flash->count = 1; +} + +// +// P_SpawnGlowingLight() +// +// Spawns a glowing light (smooth oscillation from min to max) thinker +// +// Passed the sector that spawned the thinker +// Returns nothing +// +void P_SpawnGlowingLight(sector_t *sector) +{ + glow_t *g; + + g = Z_Malloc(sizeof(*g), PU_LEVSPEC, 0); + + memset(g, 0, sizeof(*g)); + P_AddThinker(&g->thinker); + + g->sector = sector; + g->minlight = P_FindMinSurroundingLight(sector, sector->lightlevel); + g->maxlight = sector->lightlevel; + g->thinker.function = T_Glow; + g->direction = -1; + + sector->special &= ~31; //jff 3/14/98 clear non-generalized sector type +} + +////////////////////////////////////////////////////////// +// +// Linedef lighting function handlers +// +////////////////////////////////////////////////////////// + +// +// EV_StartLightStrobing() +// +// Start strobing lights (usually from a trigger) +// +// Passed the line that activated the strobing +// Returns true +// +// jff 2/12/98 added int return value, fixed return +// +int EV_StartLightStrobing(const line_t *line) +{ + int secnum; + sector_t *sec; + + secnum = -1; + // start lights strobing in all sectors tagged same as line + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + // if already doing a lighting function, don't start a second + if (P_SectorActive(lighting_special, sec)) //jff 2/22/98 + continue; + + P_SpawnStrobeFlash(sec, SLOWDARK, 0); + } + return 1; +} + +// +// EV_TurnTagLightsOff() +// +// Turn line's tagged sector's lights to min adjacent neighbor level +// +// Passed the line that activated the lights being turned off +// Returns true +// +// jff 2/12/98 added int return value, fixed return +// +int EV_TurnTagLightsOff(const line_t *line) +{ + int j; + + // search sectors for those with same tag as activating line + + // killough 10/98: replaced inefficient search with fast search + for (j = -1; (j = P_FindSectorFromLineTag(line, j)) >= 0;) + { + sector_t *sector = _g->sectors + j, *tsec; + int i, min = sector->lightlevel; + // find min neighbor light level + for (i = 0; i < sector->linecount; i++) + if ((tsec = getNextSector(getSectorLineByIndex(sector, i), sector)) && tsec->lightlevel < min) + min = tsec->lightlevel; + sector->lightlevel = min; + } + return 1; +} + +// +// EV_LightTurnOn() +// +// Turn sectors tagged to line lights on to specified or max neighbor level +// +// Passed the activating line, and a level to set the light to +// If level passed is 0, the maximum neighbor lighting is used +// Returns true +// +// jff 2/12/98 added int return value, fixed return +// +int EV_LightTurnOn(const line_t *line, int bright) +{ + int i; + // search all sectors for ones with same tag as activating line + // killough 10/98: replace inefficient search with fast search + for (i = -1; (i = P_FindSectorFromLineTag(line, i)) >= 0;) + { + sector_t *temp, *sector = _g->sectors + i; + int j, tbright = bright; //jff 5/17/98 search for maximum PER sector + // bright = 0 means to search for highest light level surrounding sector + if (!bright) + for (j = 0; j < sector->linecount; j++) + { + if ((temp = getNextSector(getSectorLineByIndex(sector, j), sector)) && temp->lightlevel > tbright) + { + tbright = temp->lightlevel; + } + sector->lightlevel = tbright; + } + } + return 1; +} + +/* killough 10/98: + * + * EV_LightTurnOnPartway() + * + * Turn sectors tagged to line lights on to specified or max neighbor level + * + * Passed the activating line, and a light level fraction between 0 and 1. + * Sets the light to min on 0, max on 1, and interpolates in-between. + * Used for doors with gradual lighting effects. + * + * Returns true + */ + +int EV_LightTurnOnPartway(const line_t *line, fixed_t level) +{ + int i; + + if (level < 0) // clip at extremes + level = 0; + if (level > FRACUNIT) + level = FRACUNIT; + + // search all sectors for ones with same tag as activating line + for (i = -1; (i = P_FindSectorFromLineTag(line, i)) >= 0;) + { + sector_t *temp, *sector = _g->sectors + i; + int j, bright = 0, min = sector->lightlevel; + + for (j = 0; j < sector->linecount; j++) + if ((temp = getNextSector(getSectorLineByIndex(sector, j), sector))) + { + if (temp->lightlevel > bright) + bright = temp->lightlevel; + if (temp->lightlevel < min) + min = temp->lightlevel; + } + + sector->lightlevel = // Set level in-between extremes + (level * bright + (FRACUNIT - level) * min) >> FRACBITS; + } + return 1; +} + diff --git a/doom/src/pdoom/Doom/source/p_map.c b/doom/src/pdoom/Doom/source/p_map.c new file mode 100644 index 0000000..e951de8 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_map.c @@ -0,0 +1,1885 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Movement, collision handling. + * Shooting and aiming. + * + * next-hack: modified code to work with short pointers. + * some memory optimization + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "r_main.h" +#include "p_mobj.h" +#include "p_maputl.h" +#include "p_map.h" +#include "p_setup.h" +#include "p_spec.h" +#include "s_sound.h" +#include "sounds.h" +#include "p_inter.h" +#include "m_random.h" +#include "m_bbox.h" +#include "lprintf.h" + +#include "global_data.h" + +// +// TELEPORT MOVE +// + +// +// PIT_StompThing +// +void checkInterceptIndex(int i) +{ + if (i >= MAXINTERCEPTS || i < 0) + { + printf("Intercept out of rance %d, blocking\r\n",i); + while (1); + } +} +boolean PIT_StompThing(mobj_t *thing) +{ + fixed_t blockdist; + + // phares 9/10/98: moved this self-check to start of routine + + // don't clip against self + + if (thing == _g->tmthing) + return true; + + if (!(thing->flags & MF_SHOOTABLE )) // Can't shoot it? Can't stomp it! + return true; + + blockdist = getMobjRadius(thing) + getMobjRadius(_g->tmthing); + + if (D_abs(thing->x - _g->tmx) >= blockdist || D_abs(thing->y - _g->tmy) >= blockdist) + return true; // didn't hit it + + // monsters don't stomp things except on boss level + if (!_g->telefrag) // killough 8/9/98: make consistent across all levels + return false; + + P_DamageMobj(thing, _g->tmthing, _g->tmthing, 10000); // Stomp! + + return true; +} + +// +// P_TeleportMove +// + +boolean P_TeleportMove(mobj_t *thing, fixed_t x, fixed_t y, boolean boss) +{ + int xl; + int xh; + int yl; + int yh; + int bx; + int by; + + if (thing->flags & MF_STATIC) + printf("P_TeleportMove static\r\n"); + subsector_t *newsubsec; + + /* killough 8/9/98: make telefragging more consistent, preserve compatibility */ + _g->telefrag = thing->player_sptr || boss; + + // kill anything occupying the position + + _g->tmthing = thing; + + _g->tmx = x; + _g->tmy = y; + + _g->tmbbox[BOXTOP] = y + getMobjRadius(_g->tmthing); + _g->tmbbox[BOXBOTTOM] = y - getMobjRadius(_g->tmthing); + _g->tmbbox[BOXRIGHT] = x + getMobjRadius(_g->tmthing); + _g->tmbbox[BOXLEFT] = x - getMobjRadius(_g->tmthing); + + newsubsec = R_PointInSubsector(x, y); + _g->ceilingline = NULL; + + // The base floor/ceiling is from the subsector + // that contains the point. + // Any contacted lines the step closer together + // will adjust them. + + _g->tmfloorz = _g->tmdropoffz = newsubsec->sector->floorheight; + _g->tmceilingz = newsubsec->sector->ceilingheight; + + _g->validcount++; + _g->numspechit = 0; + + // stomp on any things contacted + + xl = (_g->tmbbox[BOXLEFT] - _g->bmaporgx - MAXRADIUS) >> MAPBLOCKSHIFT; + xh = (_g->tmbbox[BOXRIGHT] - _g->bmaporgx + MAXRADIUS) >> MAPBLOCKSHIFT; + yl = (_g->tmbbox[BOXBOTTOM] - _g->bmaporgy - MAXRADIUS) >> MAPBLOCKSHIFT; + yh = (_g->tmbbox[BOXTOP] - _g->bmaporgy + MAXRADIUS) >> MAPBLOCKSHIFT; + + for (bx = xl; bx <= xh; bx++) + for (by = yl; by <= yh; by++) + if (!P_BlockThingsIterator(bx, by, PIT_StompThing)) + return false; + + // the move is ok, + // so unlink from the old position & link into the new position + + P_UnsetThingPosition(thing); + + thing->floorz = _g->tmfloorz; + thing->ceilingz = _g->tmceilingz; + thing->dropoffz = _g->tmdropoffz; // killough 11/98 + + thing->x = x; + thing->y = y; + + P_SetThingPosition(thing); + + //thing->PrevX = x; + //thing->PrevY = y; + //thing->PrevZ = thing->floorz; + + return true; +} + +// +// MOVEMENT ITERATOR FUNCTIONS +// + +// // phares +// PIT_CrossLine // | +// Checks to see if a PE->LS trajectory line crosses a blocking // V +// line. Returns false if it does. +// +// tmbbox holds the bounding box of the trajectory. If that box +// does not touch the bounding box of the line in question, +// then the trajectory is not blocked. If the PE is on one side +// of the line and the LS is on the other side, then the +// trajectory is blocked. +// +// Currently this assumes an infinite line, which is not quite +// correct. A more correct solution would be to check for an +// intersection of the trajectory and the line, but that takes +// longer and probably really isn't worth the effort. +// + +static // killough 3/26/98: make static +boolean PIT_CrossLine(const line_t *ld) +{ + if (!(ld->flags & ML_TWOSIDED) || (ld->flags & (ML_BLOCKING | ML_BLOCKMONSTERS))) + if (!(_g->tmbbox[BOXLEFT] > ld->bbox[BOXRIGHT] || _g->tmbbox[BOXRIGHT] < ld->bbox[BOXLEFT] || _g->tmbbox[BOXTOP] < ld->bbox[BOXBOTTOM] || _g->tmbbox[BOXBOTTOM] > ld->bbox[BOXTOP])) + if (P_PointOnLineSide(_g->pe_x, _g->pe_y, ld) != P_PointOnLineSide(_g->ls_x, _g->ls_y, ld)) + return (false); // line blocks trajectory // ^ + return (true); // line doesn't block trajectory // | +} // phares + +/* killough 8/1/98: used to test intersection between thing and line + * assuming NO movement occurs -- used to avoid sticky situations. + */ + +static int untouched(const line_t *ld) +{ + fixed_t x, y, tmbbox[4]; + return (tmbbox[BOXRIGHT] = (x = _g->tmthing->x) + getMobjRadius(_g->tmthing)) <= ld->bbox[BOXLEFT] || (tmbbox[BOXLEFT] = x - getMobjRadius(_g->tmthing)) >= ld->bbox[BOXRIGHT] || (tmbbox[BOXTOP] = (y = _g->tmthing->y) + getMobjRadius(_g->tmthing)) <= ld->bbox[BOXBOTTOM] || (tmbbox[BOXBOTTOM] = y - getMobjRadius(_g->tmthing)) >= ld->bbox[BOXTOP] || P_BoxOnLineSide(tmbbox, ld) != -1; +} + +// +// PIT_CheckLine +// Adjusts tmfloorz and tmceilingz as lines are contacted +// + +static // killough 3/26/98: make static +boolean PIT_CheckLine(const line_t *ld) +{ + if (_g->tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || _g->tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || _g->tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || _g->tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) + return true; // didn't hit it + + if (P_BoxOnLineSide(_g->tmbbox, ld) != -1) + return true; // didn't hit it + + // A line has been hit + + // The moving thing's destination position will cross the given line. + // If this should not be allowed, return false. + // If the line is special, keep track of it + // to process later if the move is proven ok. + // NOTE: specials are NOT sorted by order, + // so two special lines that are only 8 pixels apart + // could be crossed in either order. + + // killough 7/24/98: allow player to move out of 1s wall, to prevent sticking + if (!LN_BACKSECTOR(ld)) // one sided line + { + _g->blockline = ld; + return _g->tmunstuck && !untouched(ld) && FixedMul(_g->tmx - _g->tmthing->x, ld->dy) > FixedMul(_g->tmy - _g->tmthing->y, ld->dx); + } + + // killough 8/10/98: allow bouncing objects to pass through as missiles + if (!(_g->tmthing->flags & (MF_MISSILE ))) + { + if (ld->flags & ML_BLOCKING) // explicitly blocking everything + return _g->tmunstuck && !untouched(ld); // killough 8/1/98: allow escape + + // killough 8/9/98: monster-blockers don't affect friends + if (!((_g->tmthing->flags & MF_FRIEND ) || _g->tmthing->player_sptr) && (ld->flags & ML_BLOCKMONSTERS)) + return false; // block monsters only + } + + // set openrange, opentop, openbottom + // these define a 'window' from one sector to another across this line + + P_LineOpening(ld); + + // adjust floor & ceiling heights + + if (_g->opentop < _g->tmceilingz) + { + _g->tmceilingz = _g->opentop; + _g->ceilingline = ld; + _g->blockline = ld; + } + + if (_g->openbottom > _g->tmfloorz) + { + _g->tmfloorz = _g->openbottom; + _g->floorline = ld; // killough 8/1/98: remember floor linedef + _g->blockline = ld; + } + + if (_g->lowfloor < _g->tmdropoffz) + _g->tmdropoffz = _g->lowfloor; + + // if contacted a special line, add it to the list + + if (LN_SPECIAL(ld)) + { + // 1/11/98 killough: remove limit on lines hit, by array doubling + if (_g->numspechit < 4) + { + _g->spechit[_g->numspechit++] = ld; + } + } + + return true; +} + +// +// PIT_CheckThing +// + +static boolean PIT_CheckThing(mobj_t *thing) // killough 3/26/98: make static +{ + fixed_t blockdist; + int damage; + + // killough 11/98: add touchy things + if (!(thing->flags & (MF_SOLID | MF_SPECIAL | MF_SHOOTABLE ))) + return true; + + blockdist = getMobjRadius(thing) + getMobjRadius(_g->tmthing); + + if (D_abs(thing->x - _g->tmx) >= blockdist || D_abs(thing->y - _g->tmy) >= blockdist) + return true; // didn't hit it + + // killough 11/98: + // + // This test has less information content (it's almost always false), so it + // should not be moved up to first, as it adds more overhead than it removes. + + // don't clip against self + + if (thing == _g->tmthing) + return true; + + // check for skulls slamming into things + + if (_g->tmthing->flags & MF_SKULLFLY) + { + // A flying skull is smacking something. + // Determine damage amount, and the skull comes to a dead stop. + + int damage = ((P_Random(__FILE__, __LINE__, __FUNCTION__) % 8) + 1) * getMobjInfo(_g->tmthing)->damage; + + P_DamageMobj(thing, _g->tmthing, _g->tmthing, damage); + + _g->tmthing->flags &= ~MF_SKULLFLY; + _g->tmthing->momx = _g->tmthing->momy = _g->tmthing->momz = 0; + + P_SetMobjState(_g->tmthing, getMobjInfo(_g->tmthing)->spawnstate); + + return false; // stop moving + } + + // missiles can hit other things + // killough 8/10/98: bouncing non-solid things can hit other things too + + if (_g->tmthing->flags & MF_MISSILE) + { + // see if it went over / under + + if (_g->tmthing->z > thing->z + getMobjHeight(thing)) + return true; // overhead + + if (_g->tmthing->z + getMobjHeight(_g->tmthing) < thing->z) + return true; // underneath + + if (getTarget(_g->tmthing) && (getTarget(_g->tmthing)->type == thing->type || (getTarget(_g->tmthing)->type == MT_KNIGHT && thing->type == MT_BRUISER) || (getTarget(_g->tmthing)->type == MT_BRUISER && thing->type == MT_KNIGHT))) + { + if (thing == getTarget(_g->tmthing)) + return true; // Don't hit same species as originator. + else if (thing->type != MT_PLAYER) // Explode, but do no damage. + return false; // Let players missile other players. + } + + // killough 8/10/98: if moving thing is not a missile, no damage + // is inflicted, and momentum is reduced if object hit is solid. + + if (!(_g->tmthing->flags & MF_MISSILE )) + { + if (!(thing->flags & MF_SOLID )) + { + return true; + } + else + { + _g->tmthing->momx = -_g->tmthing->momx; + _g->tmthing->momy = -_g->tmthing->momy; + if (!(_g->tmthing->flags & MF_NOGRAVITY )) + { + _g->tmthing->momx >>= 2; + _g->tmthing->momy >>= 2; + } + return false; + } + } + + if (!(thing->flags & MF_SHOOTABLE )) + return !(thing->flags & MF_SOLID ); // didn't do any damage + + // damage / explode + + damage = ((P_Random(__FILE__, __LINE__, __FUNCTION__) % 8) + 1) * getMobjInfo(_g->tmthing)->damage; + P_DamageMobj(thing, _g->tmthing, getTarget(_g->tmthing), damage); + + // don't traverse any more + return false; + } + + // check for special pickup + + if (thing->flags & MF_SPECIAL) + { + unsigned int solid = thing->flags & MF_SOLID; + if (_g->tmthing->flags & MF_PICKUP) + P_TouchSpecialThing(thing, _g->tmthing); // can remove thing + return !solid; + } + + // killough 3/16/98: Allow non-solid moving objects to move through solid + // ones, by allowing the moving thing (tmthing) to move if it's non-solid, + // despite another solid thing being in the way. + // killough 4/11/98: Treat no-clipping things as not blocking + // ...but not in demo_compatibility mode + // e6y + // Correction of wrong return value with demo_compatibility. + // There is no more synch on http://www.doomworld.com/sda/dwdemo/w303-115.zip + // (with correction in setMobjInfoValue) + if (demo_compatibility) + return !(thing->flags & MF_SOLID); + else + return !(thing->flags & MF_SOLID ) || (((thing->flags & MF_NOCLIP ) || !(_g->tmthing->flags & MF_SOLID ))); + // return !(thing->flags & MF_SOLID); // old code -- killough +} + +// This routine checks for Lost Souls trying to be spawned // phares +// across 1-sided lines, impassible lines, or "monsters can't // | +// cross" lines. Draw an imaginary line between the PE // V +// and the new Lost Soul spawn spot. If that line crosses +// a 'blocking' line, then disallow the spawn. Only search +// lines in the blocks of the blockmap where the bounding box +// of the trajectory line resides. Then check bounding box +// of the trajectory vs. the bounding box of each blocking +// line to see if the trajectory and the blocking line cross. +// Then check the PE and LS to see if they're on different +// sides of the blocking line. If so, return true, otherwise +// false. + +boolean Check_Sides(mobj_t *actor, int x, int y) +{ + int bx, by, xl, xh, yl, yh; + + _g->pe_x = actor->x; + _g->pe_y = actor->y; + _g->ls_x = x; + _g->ls_y = y; + + // Here is the bounding box of the trajectory + + _g->tmbbox[BOXLEFT] = _g->pe_x < x ? _g->pe_x : x; + _g->tmbbox[BOXRIGHT] = _g->pe_x > x ? _g->pe_x : x; + _g->tmbbox[BOXTOP] = _g->pe_y > y ? _g->pe_y : y; + _g->tmbbox[BOXBOTTOM] = _g->pe_y < y ? _g->pe_y : y; + + // Determine which blocks to look in for blocking lines + + xl = (_g->tmbbox[BOXLEFT] - _g->bmaporgx) >> MAPBLOCKSHIFT; + xh = (_g->tmbbox[BOXRIGHT] - _g->bmaporgx) >> MAPBLOCKSHIFT; + yl = (_g->tmbbox[BOXBOTTOM] - _g->bmaporgy) >> MAPBLOCKSHIFT; + yh = (_g->tmbbox[BOXTOP] - _g->bmaporgy) >> MAPBLOCKSHIFT; + + // xl->xh, yl->yh determine the mapblock set to search + + _g->validcount++; // prevents checking same line twice + for (bx = xl; bx <= xh; bx++) + for (by = yl; by <= yh; by++) + if (!P_BlockLinesIterator(bx, by, PIT_CrossLine)) + return true; // ^ + return (false); // | +} // phares + +// +// MOVEMENT CLIPPING +// + +// +// P_CheckPosition +// This is purely informative, nothing is modified +// (except things picked up). +// +// in: +// a mobj_t (can be valid or invalid) +// a position to be checked +// (doesn't need to be related to the mobj_t->x,y) +// +// during: +// special things are touched if MF_PICKUP +// early out on solid lines? +// +// out: +// newsubsec +// floorz +// ceilingz +// tmdropoffz +// the lowest point contacted +// (monsters won't move to a dropoff) +// speciallines[] +// numspeciallines +// + +boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) +{ + int xl; + int xh; + int yl; + int yh; + int bx; + int by; + subsector_t *newsubsec; + + _g->tmthing = thing; + + _g->tmx = x; + _g->tmy = y; + + _g->tmbbox[BOXTOP] = y + getMobjRadius(_g->tmthing); + _g->tmbbox[BOXBOTTOM] = y - getMobjRadius(_g->tmthing); + _g->tmbbox[BOXRIGHT] = x + getMobjRadius(_g->tmthing); + _g->tmbbox[BOXLEFT] = x - getMobjRadius(_g->tmthing); + + newsubsec = R_PointInSubsector(x, y); + _g->floorline = _g->blockline = _g->ceilingline = NULL; // killough 8/1/98 + + // Whether object can get out of a sticky situation: + _g->tmunstuck = !(thing->flags & MF_STATIC) && getMobjPlayer(thing) && /* only players */ + getMobjPlayer(thing)->mo == thing && !demo_compatibility; /* not under old demos */ + // The base floor / ceiling is from the subsector + // that contains the point. + // Any contacted lines the step closer together + // will adjust them. + + _g->tmfloorz = _g->tmdropoffz = newsubsec->sector->floorheight; + _g->tmceilingz = newsubsec->sector->ceilingheight; + _g->validcount++; + _g->numspechit = 0; + + if (_g->tmthing->flags & MF_NOCLIP) + return true; + + // Check things first, possibly picking things up. + // The bounding box is extended by MAXRADIUS + // because mobj_ts are grouped into mapblocks + // based on their origin point, and can overlap + // into adjacent blocks by up to MAXRADIUS units. + + xl = (_g->tmbbox[BOXLEFT] - _g->bmaporgx - MAXRADIUS) >> MAPBLOCKSHIFT; + xh = (_g->tmbbox[BOXRIGHT] - _g->bmaporgx + MAXRADIUS) >> MAPBLOCKSHIFT; + yl = (_g->tmbbox[BOXBOTTOM] - _g->bmaporgy - MAXRADIUS) >> MAPBLOCKSHIFT; + yh = (_g->tmbbox[BOXTOP] - _g->bmaporgy + MAXRADIUS) >> MAPBLOCKSHIFT; + + for (bx = xl; bx <= xh; bx++) + for (by = yl; by <= yh; by++) + if (!P_BlockThingsIterator(bx, by, PIT_CheckThing)) + return false; + + // check lines + + xl = (_g->tmbbox[BOXLEFT] - _g->bmaporgx) >> MAPBLOCKSHIFT; + xh = (_g->tmbbox[BOXRIGHT] - _g->bmaporgx) >> MAPBLOCKSHIFT; + yl = (_g->tmbbox[BOXBOTTOM] - _g->bmaporgy) >> MAPBLOCKSHIFT; + yh = (_g->tmbbox[BOXTOP] - _g->bmaporgy) >> MAPBLOCKSHIFT; + + for (bx = xl; bx <= xh; bx++) + for (by = yl; by <= yh; by++) + if (!P_BlockLinesIterator(bx, by, PIT_CheckLine)) + return false; // doesn't fit + + return true; +} + +// +// P_TryMove +// Attempt to move to a new position, +// crossing special lines unless MF_TELEPORT is set. +// +boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean dropoff) // killough 3/15/98: allow dropoff as option +{ + fixed_t oldx; + fixed_t oldy; + + _g->felldown = _g->floatok = false; // killough 11/98 + + if (!P_CheckPosition(thing, x, y)) + return false; // solid wall or thing + + if (demo_compatibility) + { + if ( !(thing->flags & MF_NOCLIP) ) + { + if (_g->tmceilingz - _g->tmfloorz < getMobjHeight(thing)) + return false; // doesn't fit + + _g->floatok = true; + + if ( !(thing->flags & MF_TELEPORT) + && _g->tmceilingz - thing->z < getMobjHeight(thing)) + return false; // mobj must lower itself to fit + + if ( !(thing->flags & MF_TELEPORT) + && _g->tmfloorz - thing->z > 24*FRACUNIT ) + return false; // too big a step up + + if ( !(thing->flags & (MF_DROPOFF|MF_FLOAT)) + && _g->tmfloorz - _g->tmdropoffz > 24*FRACUNIT ) + return false; // don't stand over a dropoff + } + } + else + { + if (!(thing->flags & MF_NOCLIP )) + { + // killough 7/26/98: reformatted slightly + // killough 8/1/98: Possibly allow escape if otherwise stuck + + if (_g->tmceilingz - _g->tmfloorz < getMobjHeight(thing) || // doesn't fit + // mobj must lower to fit + (_g->floatok = true, !(thing->flags & MF_TELEPORT ) && _g->tmceilingz - thing->z < getMobjHeight(thing)) || + // too big a step up + (!(thing->flags & MF_TELEPORT ) && _g->tmfloorz - thing->z > 24 * FRACUNIT)) + return _g->tmunstuck && !(_g->ceilingline && untouched(_g->ceilingline)) && !(_g->floorline && untouched(_g->floorline)); + + /* killough 3/15/98: Allow certain objects to drop off + * killough 7/24/98, 8/1/98: + * Prevent monsters from getting stuck hanging off ledges + * killough 10/98: Allow dropoffs in controlled circumstances + * killough 11/98: Improve symmetry of clipping on stairs + */ + + if (!(thing->flags & (MF_DROPOFF | MF_FLOAT ))) + { + if (!dropoff || (dropoff == 2 && // large jump down (e.g. dogs) + (_g->tmfloorz - _g->tmdropoffz > 128 * FRACUNIT || !getTarget(thing) || getTarget(thing)->z > _g->tmdropoffz))) + { + if (_g->tmfloorz - _g->tmdropoffz > 24 * FRACUNIT) + return false; + } + else + { /* dropoff allowed -- check for whether it fell more than 24 */ + _g->felldown = !(thing->flags & MF_NOGRAVITY ) && thing->z - _g->tmfloorz > 24 * FRACUNIT; + } + } + } + } + + // the move is ok, + // so unlink from the old position and link into the new position + + P_UnsetThingPosition(thing); + + oldx = thing->x; + oldy = thing->y; + thing->floorz = _g->tmfloorz; + thing->ceilingz = _g->tmceilingz; + thing->dropoffz = _g->tmdropoffz; // killough 11/98: keep track of dropoffs + thing->x = x; + thing->y = y; + + P_SetThingPosition(thing); + + // if any special lines were hit, do the effect + + if (!(thing->flags & (MF_TELEPORT | MF_NOCLIP ))) + while (_g->numspechit--) + if (LN_SPECIAL(_g->spechit[_g->numspechit])) // see if the line was crossed + { + int oldside; + if ((oldside = P_PointOnLineSide(oldx, oldy, _g->spechit[_g->numspechit])) != P_PointOnLineSide(thing->x, thing->y, _g->spechit[_g->numspechit])) + P_CrossSpecialLine(_g->spechit[_g->numspechit], oldside, thing); + } + + return true; +} + +// +// P_ThingHeightClip +// Takes a valid thing and adjusts the thing->floorz, +// thing->ceilingz, and possibly thing->z. +// This is called for all nearby monsters +// whenever a sector changes height. +// If the thing doesn't fit, +// the z will be set to the lowest value +// and false will be returned. +// + +boolean P_ThingHeightClip(mobj_t *thing) +{ + if (thing->flags & MF_STATIC) + { + if (!(thing->flags & MF_NOGRAVITY )) + { + P_CheckPosition(thing, thing->x, thing->y); + // subsector_t* newsubsec = R_PointInSubsector(thing->x, thing->y); + // if it is not floating then put it on the floor + thing->z = _g->tmfloorz; // newsubsec->sector->floorheight; + + } + return _g->tmceilingz - _g->tmfloorz >= getMobjHeight(thing); + } + boolean onfloor; + + onfloor = (thing->z == thing->floorz); + + P_CheckPosition(thing, thing->x, thing->y); + + /* what about stranding a monster partially off an edge? + * killough 11/98: Answer: see below (upset balance if hanging off ledge) + */ + + thing->floorz = _g->tmfloorz; + thing->ceilingz = _g->tmceilingz; + thing->dropoffz = _g->tmdropoffz; /* killough 11/98: remember dropoffs */ + + if (onfloor) + { + + // walking monsters rise and fall with the floor + + thing->z = thing->floorz; + } + else + { + + // don't adjust a floating monster unless forced to + + if (thing->z + getMobjHeight(thing) > thing->ceilingz) + thing->z = thing->ceilingz - getMobjHeight(thing); + } + + return thing->ceilingz - thing->floorz >= getMobjHeight(thing); +} + +// +// SLIDE MOVE +// Allows the player to slide along any angled walls. +// + +// +// P_HitSlideLine +// Adjusts the xmove / ymove +// so that the next move will slide along the wall. +// If the floor is icy, then you can bounce off a wall. // phares +// + +void P_HitSlideLine(const line_t *ld) +{ + int side; + angle_t lineangle; + angle_t moveangle; + angle_t deltaangle; + fixed_t movelen; + fixed_t newlen; + // | + // Under icy conditions, if the angle of approach to the wall // V + // is more than 45 degrees, then you'll bounce and lose half + // your momentum. If less than 45 degrees, you'll slide along + // the wall. 45 is arbitrary and is believable. + + // Check for the special cases of horz or vert walls. + + /* killough 10/98: only bounce if hit hard (prevents wobbling) + * cph - DEMOSYNC - should only affect players in Boom demos? */ + + if (ld->slopetype == ST_HORIZONTAL) + { + _g->tmymove = 0; // no more movement in the Y direction + return; + } + + if (ld->slopetype == ST_VERTICAL) + { // phares + _g->tmxmove = 0; // no more movement in the X direction + return; + } + + // The wall is angled. Bounce if the angle of approach is // phares + // less than 45 degrees. // phares + + side = P_PointOnLineSide(_g->slidemo->x, _g->slidemo->y, ld); + + lineangle = R_PointToAngle2(0, 0, ld->dx, ld->dy); + if (side == 1) + lineangle += ANG180; + + moveangle = R_PointToAngle2(0, 0, _g->tmxmove, _g->tmymove); + + // killough 3/2/98: + // The moveangle+=10 breaks v1.9 demo compatibility in + // some demos, so it needs demo_compatibility switch. + if (!demo_compatibility) + moveangle += 10; // prevents sudden path reversal due to // phares + // rounding error // | + deltaangle = moveangle - lineangle; // V + movelen = P_AproxDistance(_g->tmxmove, _g->tmymove); + // | + // phares + if (deltaangle > ANG180) + deltaangle += ANG180; + + // I_Error ("SlideLine: ang>ANG180"); + + lineangle >>= ANGLETOFINESHIFT; + deltaangle >>= ANGLETOFINESHIFT; + newlen = FixedMul(movelen, finecosine[deltaangle]); + _g->tmxmove = FixedMul(newlen, finecosine[lineangle]); + _g->tmymove = FixedMul(newlen, finesine[lineangle]); + // phares +} + +// +// PTR_SlideTraverse +// + +boolean PTR_SlideTraverse(intercept_t *in) +{ + const line_t *li; + int index = (int) (in - intercepts); + checkInterceptIndex(index); + + boolean isaline = interceptIsALine[index]; + //if (!in->isaline) + if (!isaline) + I_Error("PTR_SlideTraverse: not a line?"); + + li = in->d.line; + + if (!(li->flags & ML_TWOSIDED)) + { + if (P_PointOnLineSide(_g->slidemo->x, _g->slidemo->y, li)) + return true; // don't hit the back side + goto isblocking; + } + + // set openrange, opentop, openbottom. + // These define a 'window' from one sector to another across a line + + P_LineOpening(li); + + if (_g->openrange < getMobjHeight(_g->slidemo)) + goto isblocking; + // doesn't fit + + if (_g->opentop - _g->slidemo->z < getMobjHeight(_g->slidemo)) + goto isblocking; + // mobj is too high + + if (_g->openbottom - _g->slidemo->z > 24 * FRACUNIT) + goto isblocking; + // too big a step up + + // this line doesn't block movement + + return true; + + // the line does block movement, + // see if it is closer than best so far + + isblocking: + + if (in->frac < _g->bestslidefrac) + { + _g->bestslidefrac = in->frac; + _g->bestslideline = li; + } + + return false; // stop +} + +// +// P_SlideMove +// The momx / momy move is bad, so try to slide +// along a wall. +// Find the first line hit, move flush to it, +// and slide along it +// +// This is a kludgy mess. +// +// killough 11/98: reformatted + +void P_SlideMove(mobj_t *mo) +{ + int hitcount = 3; + + _g->slidemo = mo; // the object that's sliding + + do + { + fixed_t leadx, leady, trailx, traily; + + if (!--hitcount) + goto stairstep; + // don't loop forever + + // trace along the three leading corners + + if (mo->momx > 0) + leadx = mo->x + getMobjRadius(mo), trailx = mo->x - getMobjRadius(mo); + else + leadx = mo->x - getMobjRadius(mo), trailx = mo->x + getMobjRadius(mo); + + if (mo->momy > 0) + leady = mo->y + getMobjRadius(mo), traily = mo->y - getMobjRadius(mo); + else + leady = mo->y - getMobjRadius(mo), traily = mo->y + getMobjRadius(mo); + + _g->bestslidefrac = FRACUNIT + 1; + + P_PathTraverse(leadx, leady, leadx + mo->momx, leady + mo->momy, + PT_ADDLINES, PTR_SlideTraverse); + P_PathTraverse(trailx, leady, trailx + mo->momx, leady + mo->momy, + PT_ADDLINES, PTR_SlideTraverse); + P_PathTraverse(leadx, traily, leadx + mo->momx, traily + mo->momy, + PT_ADDLINES, PTR_SlideTraverse); + + // move up to the wall + + if (_g->bestslidefrac == FRACUNIT + 1) + { + // the move must have hit the middle, so stairstep + + stairstep: + + /* killough 3/15/98: Allow objects to drop off ledges + * + * phares 5/4/98: kill momentum if you can't move at all + * This eliminates player bobbing if pressed against a wall + * while on ice. + * + * killough 10/98: keep buggy code around for old Boom demos + * + * cph 2000/09//23: buggy code was only in Boom v2.01 + */ + + if (!P_TryMove(mo, mo->x, mo->y + mo->momy, true)) + P_TryMove(mo, mo->x + mo->momx, mo->y, true); + + break; + } + + // fudge a bit to make sure it doesn't hit + + if ((_g->bestslidefrac -= 0x800) > 0) + { + fixed_t newx = FixedMul(mo->momx, _g->bestslidefrac); + fixed_t newy = FixedMul(mo->momy, _g->bestslidefrac); + + // killough 3/15/98: Allow objects to drop off ledges + + if (!P_TryMove(mo, mo->x + newx, mo->y + newy, true)) + goto stairstep; + } + + // Now continue along the wall. + // First calculate remainder. + + _g->bestslidefrac = FRACUNIT - (_g->bestslidefrac + 0x800); + + if (_g->bestslidefrac > FRACUNIT) + _g->bestslidefrac = FRACUNIT; + + if (_g->bestslidefrac <= 0) + break; + + _g->tmxmove = FixedMul(mo->momx, _g->bestslidefrac); + _g->tmymove = FixedMul(mo->momy, _g->bestslidefrac); + + P_HitSlideLine(_g->bestslideline); // clip the moves + + mo->momx = _g->tmxmove; + mo->momy = _g->tmymove; + + /* killough 10/98: affect the bobbing the same way (but not voodoo dolls) + * cph - DEMOSYNC? */ + if (mo->player_sptr && getMobjPlayer(mo)->mo == mo) + { + if (D_abs(getMobjPlayer(mo)->momx) > D_abs(_g->tmxmove)) + getMobjPlayer(mo)->momx = _g->tmxmove; + if (D_abs(getMobjPlayer(mo)->momy) > D_abs(_g->tmymove)) + getMobjPlayer(mo)->momy = _g->tmymove; + } + } // killough 3/15/98: Allow objects to drop off ledges: + while (!P_TryMove(mo, mo->x + _g->tmxmove, mo->y + _g->tmymove, true)); +} + +// +// P_LineAttack +// + +// +// PTR_AimTraverse +// Sets linetaget and aimslope when a target is aimed at. +// +boolean PTR_AimTraverse(intercept_t *in) +{ + const line_t *li; + mobj_t *th; + fixed_t slope; + fixed_t thingtopslope; + fixed_t thingbottomslope; + fixed_t dist; + int index = (int) (in - intercepts); + checkInterceptIndex(index); + boolean isaline = interceptIsALine[index]; + //if (in->isaline) + if (isaline) + { + li = in->d.line; + + if (!(li->flags & ML_TWOSIDED)) + return false; // stop + + // Crosses a two sided line. + // A two sided line will restrict + // the possible target ranges. + + P_LineOpening(li); + + if (_g->openbottom >= _g->opentop) + return false; // stop + + dist = FixedMul(_g->attackrange, in->frac); + + if (LN_FRONTSECTOR(li)->floorheight != LN_BACKSECTOR(li)->floorheight) + { + slope = FixedDiv(_g->openbottom - _g->shootz, dist); + + if (slope > _g->bottomslope) + _g->bottomslope = slope; + } + + if (LN_FRONTSECTOR(li)->ceilingheight != LN_BACKSECTOR(li)->ceilingheight) + { + slope = FixedDiv(_g->opentop - _g->shootz, dist); + if (slope < _g->topslope) + _g->topslope = slope; + } + + if (_g->topslope <= _g->bottomslope) + return false; // stop + + return true; // shot continues + } + + // shoot a thing + + th = in->d.thing; + if (th == _g->shootthing) + return true; // can't shoot self + + if (!(th->flags & MF_SHOOTABLE )) + return true; // corpse or something + + /* killough 7/19/98, 8/2/98: + * friends don't aim at friends (except players), at least not first + */ + if ((th->flags & _g->shootthing->flags & _g->aim_flags_mask) && !th->player_sptr) + return true; + + // check angles to see if the thing can be aimed at + + dist = FixedMul(_g->attackrange, in->frac); + thingtopslope = FixedDiv(th->z + getMobjHeight(th) - _g->shootz, dist); + + if (thingtopslope < _g->bottomslope) + return true; // shot over the thing + + thingbottomslope = FixedDiv(th->z - _g->shootz, dist); + + if (thingbottomslope > _g->topslope) + return true; // shot under the thing + + // this thing can be hit! + + if (thingtopslope > _g->topslope) + thingtopslope = _g->topslope; + + if (thingbottomslope < _g->bottomslope) + thingbottomslope = _g->bottomslope; + + _g->aimslope = (thingtopslope + thingbottomslope) / 2; + _g->linetarget = th; + + return false; // don't go any farther +} + +// +// PTR_ShootTraverse +// +boolean PTR_ShootTraverse(intercept_t *in) +{ + fixed_t x; + fixed_t y; + fixed_t z; + fixed_t frac; + + mobj_t *th; + + fixed_t slope; + fixed_t dist; + fixed_t thingtopslope; + fixed_t thingbottomslope; + int index = (int) (in - intercepts); + checkInterceptIndex(index); + boolean isaline = interceptIsALine[index]; + //if (in->isaline) + if (isaline) + { + const line_t *li = in->d.line; + + if (LN_SPECIAL(li)) + P_ShootSpecialLine(_g->shootthing, li); + + if (li->flags & ML_TWOSIDED) + { // crosses a two sided (really 2s) line + P_LineOpening(li); + dist = FixedMul(_g->attackrange, in->frac); + + // killough 11/98: simplify + // e6y: emulation of missed back side on two-sided lines. + // backsector can be NULL if overrun_missedbackside_emulate is 1 + if (!LN_BACKSECTOR(li)) + { + if ((slope = FixedDiv(_g->openbottom - _g->shootz , dist)) <= _g->aimslope && + (slope = FixedDiv(_g->opentop - _g->shootz , dist)) >= _g->aimslope) + return true; // shot continues + } + else if ((LN_FRONTSECTOR(li)->floorheight == LN_BACKSECTOR(li)->floorheight || (slope = FixedDiv(_g->openbottom - _g->shootz, dist)) <= _g->aimslope) && (LN_FRONTSECTOR(li)->ceilingheight == LN_BACKSECTOR(li)->ceilingheight || (slope = FixedDiv(_g->opentop - _g->shootz, dist)) >= _g->aimslope)) + return true; // shot continues + } + + // hit line + // position a bit closer + + frac = in->frac - FixedDiv(4 * FRACUNIT, _g->attackrange); + x = _g->trace.x + FixedMul(_g->trace.dx, frac); + y = _g->trace.y + FixedMul(_g->trace.dy, frac); + z = _g->shootz + FixedMul(_g->aimslope, FixedMul(frac, _g->attackrange)); + + if (LN_FRONTSECTOR(li)->ceilingpic == _g->skyflatnum) + { + // don't shoot the sky! + + if (z > LN_FRONTSECTOR(li)->ceilingheight) + return false; + + // it's a sky hack wall + + if (LN_BACKSECTOR(li) && LN_BACKSECTOR(li)->ceilingpic == _g->skyflatnum) + + // fix bullet-eaters -- killough: + // WARNING: Almost all demos will lose sync without this + // demo_compatibility flag check!!! killough 1/18/98 + if (demo_compatibility || LN_BACKSECTOR(li)->ceilingheight < z) + return false; + } + + // Spawn bullet puffs. + + P_SpawnPuff(x, y, z); + + // don't go any farther + + return false; + } + + // shoot a thing + + th = in->d.thing; + if (th == _g->shootthing) + return true; // can't shoot self + + if (!(th->flags & MF_SHOOTABLE )) + return true; // corpse or something + + // check angles to see if the thing can be aimed at + + dist = FixedMul(_g->attackrange, in->frac); + thingtopslope = FixedDiv(th->z + getMobjHeight(th) - _g->shootz, dist); + + if (thingtopslope < _g->aimslope) + return true; // shot over the thing + + thingbottomslope = FixedDiv(th->z - _g->shootz, dist); + + if (thingbottomslope > _g->aimslope) + return true; // shot under the thing + + // hit thing + // position a bit closer + + frac = in->frac - FixedDiv(10 * FRACUNIT, _g->attackrange); + + x = _g->trace.x + FixedMul(_g->trace.dx, frac); + y = _g->trace.y + FixedMul(_g->trace.dy, frac); + z = _g->shootz + FixedMul(_g->aimslope, FixedMul(frac, _g->attackrange)); + + // Spawn bullet puffs or blod spots, + // depending on target type. + if (in->d.thing->flags & MF_NOBLOOD) + P_SpawnPuff(x, y, z); + else + P_SpawnBlood(x, y, z, _g->la_damage); + + if (_g->la_damage) + P_DamageMobj(th, _g->shootthing, _g->shootthing, _g->la_damage); + + // don't go any farther + return false; +} + +// +// P_AimLineAttack +// +fixed_t P_AimLineAttack(mobj_t *t1, angle_t angle, fixed_t distance, uint_64_t mask) +{ + fixed_t x2; + fixed_t y2; + + angle >>= ANGLETOFINESHIFT; + _g->shootthing = t1; + + x2 = t1->x + (distance >> FRACBITS) * finecosine[angle]; + y2 = t1->y + (distance >> FRACBITS) * finesine[angle]; + _g->shootz = t1->z + (getMobjHeight(t1) >> 1) + 8 * FRACUNIT; + + // can't shoot outside view angles + if (demo_compatibility) // nexthack: demo_compatibilty + { + _g->topslope = 100 * FRACUNIT / 160; + _g->bottomslope = -100 * FRACUNIT / 160; + } + else + { + _g->topslope = (SCREENHEIGHT / 2) * FRACUNIT / (SCREENWIDTH / 2); + _g->bottomslope = -(SCREENHEIGHT / 2) * FRACUNIT / (SCREENWIDTH / 2); + } + _g->attackrange = distance; + _g->linetarget = NULL; + + /* killough 8/2/98: prevent friends from aiming at friends */ + _g->aim_flags_mask = mask; + + P_PathTraverse(t1->x, t1->y, x2, y2, PT_ADDLINES | PT_ADDTHINGS, PTR_AimTraverse); + + if (_g->linetarget) + return _g->aimslope; + + return 0; +} + +// +// P_LineAttack +// If damage == 0, it is just a test trace +// that will leave linetarget set. +// + +void P_LineAttack(mobj_t *t1, angle_t angle, fixed_t distance, fixed_t slope, int damage) +{ + fixed_t x2; + fixed_t y2; + + angle >>= ANGLETOFINESHIFT; + _g->shootthing = t1; + _g->la_damage = damage; + x2 = t1->x + (distance >> FRACBITS) * finecosine[angle]; + y2 = t1->y + (distance >> FRACBITS) * finesine[angle]; + _g->shootz = t1->z + (getMobjHeight(t1) >> 1) + 8 * FRACUNIT; + _g->attackrange = distance; + _g->aimslope = slope; + + P_PathTraverse(t1->x, t1->y, x2, y2, PT_ADDLINES | PT_ADDTHINGS, PTR_ShootTraverse); +} + +// +// USE LINES +// + +boolean PTR_UseTraverse(intercept_t *in) +{ + int side; + + if (!LN_SPECIAL(in->d.line)) + { + P_LineOpening(in->d.line); + if (_g->openrange <= 0) + { + S_StartSound(_g->usething, sfx_noway); + + // can't use through a wall + return false; + } + + // not a special line, but keep checking + + return true; + } + + side = 0; + if (P_PointOnLineSide(_g->usething->x, _g->usething->y, in->d.line) == 1) + side = 1; + + // return false; // don't use back side + + P_UseSpecialLine(_g->usething, in->d.line, side); + + //WAS can't use for than one special line in a row + //jff 3/21/98 NOW multiple use allowed with enabling line flag + + return ((in->d.line->flags & ML_PASSUSE)) ? + true : false; +} + +// Returns false if a "oof" sound should be made because of a blocking +// linedef. Makes 2s middles which are impassable, as well as 2s uppers +// and lowers which block the player, cause the sound effect when the +// player tries to activate them. Specials are excluded, although it is +// assumed that all special linedefs within reach have been considered +// and rejected already (see P_UseLines). +// +// by Lee Killough +// + +boolean PTR_NoWayTraverse(intercept_t *in) +{ + const line_t *ld = in->d.line; + // This linedef + return LN_SPECIAL(ld) || !( // Ignore specials + (ld->flags & ML_BLOCKING) || ( // Always blocking + P_LineOpening(ld), // Find openings + _g->openrange <= 0 || // No opening + _g->openbottom > _g->usething->z + 24 * FRACUNIT || // Too high it blocks + _g->opentop < _g->usething->z + getMobjHeight(_g->usething) // Too low it blocks + )); +} + +// +// P_UseLines +// Looks for special lines in front of the player to activate. +// +void P_UseLines(player_t *player) +{ + int angle; + fixed_t x1; + fixed_t y1; + fixed_t x2; + fixed_t y2; + + _g->usething = player->mo; + + angle = player->mo->angle >> ANGLETOFINESHIFT; + + x1 = player->mo->x; + y1 = player->mo->y; + x2 = x1 + (USERANGE >> FRACBITS) * finecosine[angle]; + y2 = y1 + (USERANGE >> FRACBITS) * finesine[angle]; + + // old code: + // + // P_PathTraverse ( x1, y1, x2, y2, PT_ADDLINES, PTR_UseTraverse ); + // + // This added test makes the "oof" sound work on 2s lines -- killough: + + if (P_PathTraverse(x1, y1, x2, y2, PT_ADDLINES, PTR_UseTraverse)) + if (!P_PathTraverse(x1, y1, x2, y2, PT_ADDLINES, PTR_NoWayTraverse)) + S_StartSound(_g->usething, sfx_noway); +} + +// +// RADIUS ATTACK +// + +// +// PIT_RadiusAttack +// "bombsource" is the creature +// that caused the explosion at "bombspot". +// + +boolean PIT_RadiusAttack(mobj_t *thing) +{ + fixed_t dx; + fixed_t dy; + fixed_t dist; + + /* killough 8/20/98: allow bouncers to take damage + * (missile bouncers are already excluded with MF_NOBLOCKMAP) + */ + + if (!(thing->flags & MF_SHOOTABLE )) + return true; + + // Boss spider and cyborg + // take no damage from concussion. + + // killough 8/10/98: allow grenades to hurt anyone, unless + // fired by Cyberdemons, in which case it won't hurt Cybers. + + if (thing->type == MT_CYBORG || thing->type == MT_SPIDER) + return true; + + dx = D_abs(thing->x - _g->bombspot->x); + dy = D_abs(thing->y - _g->bombspot->y); + + dist = dx > dy ? dx : dy; + dist = (dist - getMobjRadius(thing)) >> FRACBITS; + + if (dist < 0) + dist = 0; + + if (dist >= _g->bombdamage) + return true; // out of range + + if (P_CheckSight(thing, _g->bombspot)) + { + // must be in direct path + P_DamageMobj(thing, _g->bombspot, _g->bombsource, _g->bombdamage - dist); + } + + return true; +} + +// +// P_RadiusAttack +// Source is the creature that caused the explosion at spot. +// +void P_RadiusAttack(mobj_t *spot, mobj_t *source, int damage) +{ + int x; + int y; + + int xl; + int xh; + int yl; + int yh; + + fixed_t dist; + + dist = (damage + MAXRADIUS) << FRACBITS; + yh = (spot->y + dist - _g->bmaporgy) >> MAPBLOCKSHIFT; + yl = (spot->y - dist - _g->bmaporgy) >> MAPBLOCKSHIFT; + xh = (spot->x + dist - _g->bmaporgx) >> MAPBLOCKSHIFT; + xl = (spot->x - dist - _g->bmaporgx) >> MAPBLOCKSHIFT; + _g->bombspot = spot; + _g->bombsource = source; + _g->bombdamage = damage; + + for (y = yl; y <= yh; y++) + for (x = xl; x <= xh; x++) + P_BlockThingsIterator(x, y, PIT_RadiusAttack); +} + +// +// SECTOR HEIGHT CHANGING +// After modifying a sectors floor or ceiling height, +// call this routine to adjust the positions +// of all things that touch the sector. +// +// If anything doesn't fit anymore, true will be returned. +// If crunch is true, they will take damage +// as they are being crushed. +// If Crunch is false, you should set the sector height back +// the way it was and call P_ChangeSector again +// to undo the changes. +// + +// +// PIT_ChangeSector +// + +boolean PIT_ChangeSector(mobj_t *thing) +{ + mobj_t *mo; + + if (P_ThingHeightClip(thing)) + return true; // keep checking + + // crunch bodies to giblets + if (!(thing->flags & MF_STATIC) && thing->health <= 0) + { + P_SetMobjState(thing, S_GIBS); + + thing->flags &= ~MF_SOLID; + if (!(thing->flags & MF_STATIC)) + { + thing->height_s = 0; + thing->radiusb = 0; + } + return true; // keep checking + } + + // crunch dropped items + + if (thing->flags & MF_DROPPED) + { + P_RemoveMobj(thing); + + // keep checking + return true; + } + + if (!(thing->flags & MF_SHOOTABLE )) + { + // assume it is bloody gibs or something + return true; + } + + _g->nofit = true; + + if (!(thing->flags & MF_STATIC) && (_g->crushchange && !(_g->leveltime & 3))) + { + int t; + P_DamageMobj(thing, NULL, NULL, 10); + + // spray blood in a random direction + mo = P_SpawnMobj(thing->x, thing->y, thing->z + getMobjHeight(thing) / 2, MT_BLOOD); + + /* killough 8/10/98: remove dependence on order of evaluation */ + t = P_Random(__FILE__, __LINE__, __FUNCTION__); + mo->momx = (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 12; + t = P_Random(__FILE__, __LINE__, __FUNCTION__); + mo->momy = (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 12; + } + + // keep checking (crush other things) + return true; +} + +// +// P_CheckSector +// jff 3/19/98 added to just check monsters on the periphery +// of a moving sector instead of all in bounding box of the +// sector. Both more accurate and faster. +// + +boolean P_CheckSector(sector_t *sector, boolean crunch) +{ + msecnode_t *n; + + _g->nofit = false; + _g->crushchange = crunch; + + // killough 4/4/98: scan list front-to-back until empty or exhausted, + // restarting from beginning after each thing is processed. Avoids + // crashes, and is sure to examine all things in the sector, and only + // the things which are in the sector, until a steady-state is reached. + // Things can arbitrarily be inserted and removed and it won't mess up. + // + // killough 4/7/98: simplified to avoid using complicated counter + + // Mark all things invalid + // 2021-02-28 next-hack. Removed boolean and used the most significant bit + // of one address (not used) +// for (n=sector->touching_thinglist; n; n=n->m_snext) +#if 0 + for (n=getSectorTouchingThingList(sector); n; n=getMsecnodeSNext(n)) + { + n->visited = false; + } + do +// for (n=sector->touching_thinglist; n; n=n->m_snext) // go through list + for (n=getSectorTouchingThingList(sector); n; n= getMsecnodeSNext(n)) // go through list + + if (!n->visited) // unprocessed thing found + { + n->visited = true; // mark thing as processed + if (!(getMsecnodeThing(n)->flags & MF_NOBLOCKMAP)) //jff 4/7/98 don't do these + PIT_ChangeSector(getMsecnodeThing(n)); // process it + break; // exit and start over + } + while (n); // repeat from scratch until all things left are marked valid +#else + uint8_t highBitBackup[1024 / 8] = + { 0 }; // 1024 nodes are enough. + // + uint32_t number = 0; + // save most signiicant bit + for (n = getSectorTouchingThingList(sector); n; n = getMsecnodeSNext(n)) + { + if (n->m_tprev_sptr & 0x8000) + { + // save bit in backup + highBitBackup[number / 8] |= (1 << (number % 8)); + // clear it to use it as visited + n->m_tprev_sptr &= ~0x8000; + } + number++; + } + do + { + for (n = getSectorTouchingThingList(sector); n; n = getMsecnodeSNext(n)) // go through list + { + if (!(n->m_tprev_sptr & 0x8000)) + { + n->m_tprev_sptr |= 0x8000; // mark thing as processed + if (!(getMsecnodeThing(n)->flags & MF_NOBLOCKMAP )) //jff 4/7/98 don't do these + PIT_ChangeSector(getMsecnodeThing(n)); // process it + break; // exit and start over + } + } + } while (n); // repeat from scratch until all things left are marked valid + // restore high bits + number = 0; + for (n = getSectorTouchingThingList(sector); n; n = getMsecnodeSNext(n)) + { + if (highBitBackup[number / 8] & (1 << (number % 8))) + { + n->m_tprev_sptr |= 0x8000; + } + else + { + n->m_tprev_sptr &= ~0x8000; + } + number++; + } +#endif + return _g->nofit; +} + +// CPhipps - +// Use block memory allocator here + +#include "z_bmalloc.h" + +IMPLEMENT_BLOCK_MEMORY_ALLOC_ZONE(secnodezone, sizeof(msecnode_t), PU_LEVEL, 32, "SecNodes"); + +inline static msecnode_t* P_GetSecnode(void) +{ + return (msecnode_t*) Z_BMalloc(&secnodezone); +} + +// P_PutSecnode() returns a node to the freelist. + +inline static void P_PutSecnode(msecnode_t *node) +{ + Z_BFree(&secnodezone, node); +} + +// phares 3/16/98 +// +// P_AddSecnode() searches the current list to see if this sector is +// already there. If not, it adds a sector node at the head of the list of +// sectors this object appears in. This is called when creating a list of +// nodes that will get linked in later. Returns a pointer to the new node. + +msecnode_t* P_AddSecnode(sector_t *s, mobj_t *thing, msecnode_t *nextnode) +{ + msecnode_t *node; + + node = nextnode; + while (node) + { + if (getMsecnodeSector(node) == s) // Already have a node for this sector? + { + node->m_thing_sptr = getShortPtr(thing); // Yes. Setting m_thing says 'keep it'. + return (nextnode); + } + node = getMsecnodeTNext(node); + } + + // Couldn't find an existing node for this sector. Add one at the head + // of the list. + + node = P_GetSecnode(); + + // killough 4/4/98, 4/7/98: mark new nodes unvisited. + //node->visited = 0; + + node->m_sector_sptr = getShortPtr(s); // sector + node->m_thing_sptr = getShortPtr(thing); // mobj + node->m_tprev_sptr = 0L; // prev node on Thing thread + node->m_tnext_sptr = getShortPtr(nextnode); // next node on Thing thread + if (nextnode) + nextnode->m_tprev_sptr = getShortPtr(node); // set back link on Thing + + // Add new node at head of sector thread starting at s->touching_thinglist + + node->m_sprev_sptr = 0; // prev node on sector thread + //node->m_snext = s->touching_thinglist; // next node on sector thread +// node->m_snext = getLongPtr(s->touching_thinglist_sptr); // next node on sector thread + node->m_snext_sptr = s->touching_thinglist_sptr; // next node on sector thread + + //if (s->touching_thinglist) + if (s->touching_thinglist_sptr) + getMsecnodeSNext(node)->m_sprev_sptr = getShortPtr(node); +// s->touching_thinglist = node; + s->touching_thinglist_sptr = getShortPtr(node); + return (node); +} + +// P_DelSecnode() deletes a sector node from the list of +// sectors this object appears in. Returns a pointer to the next node +// on the linked list, or NULL. + +msecnode_t* P_DelSecnode(msecnode_t *node) +{ + msecnode_t *tp; // prev node on thing thread + msecnode_t *tn; // next node on thing thread + msecnode_t *sp; // prev node on sector thread + msecnode_t *sn; // next node on sector thread + + if (node) + { + + // Unlink from the Thing thread. The Thing thread begins at + // sector_list and not from mobj_t->touching_sectorlist. + + tp = getMsecnodeTPrev(node); + tn = getMsecnodeTNext(node); + if (tp) + tp->m_tnext_sptr = getShortPtr(tn); + if (tn) + tn->m_tprev_sptr = getShortPtr(tp); + + // Unlink from the sector thread. This thread begins at + // sector_t->touching_thinglist. + + sp = getMsecnodeSPrev(node); + sn = getLongPtr(node->m_snext_sptr); + if (sp) + sp->m_snext_sptr = getShortPtr(sn); + else + { +// node->m_sector->touching_thinglist = sn; + getMsecnodeSector(node)->touching_thinglist_sptr = getShortPtr(sn); + } + if (sn) + sn->m_sprev_sptr = getShortPtr(sp); + + // Return this node to the freelist + + P_PutSecnode(node); + return (tn); + } + return (NULL); +} // phares 3/13/98 + +// Delete an entire sector list + +void P_DelSeclist(msecnode_t *node) + +{ + while (node) + node = P_DelSecnode(node); +} + +// phares 3/14/98 +// +// PIT_GetSectors +// Locates all the sectors the object is in by looking at the lines that +// cross through it. You have already decided that the object is allowed +// at this location, so don't bother with checking impassable or +// blocking lines. + +boolean PIT_GetSectors(const line_t *ld) +{ + if (_g->tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || _g->tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || _g->tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || _g->tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) + return true; + + if (P_BoxOnLineSide(_g->tmbbox, ld) != -1) + return true; + + // This line crosses through the object. + + // Collect the sector(s) from the line and add to the + // sector_list you're examining. If the Thing ends up being + // allowed to move to this position, then the sector_list + // will be attached to the Thing's mobj_t at touching_sectorlist. + + _g->sector_list = P_AddSecnode(LN_FRONTSECTOR(ld), _g->tmthing, _g->sector_list); + + /* Don't assume all lines are 2-sided, since some Things + * like MT_TFOG are allowed regardless of whether their radius takes + * them beyond an impassable linedef. + * + * killough 3/27/98, 4/4/98: + * Use sidedefs instead of 2s flag to determine two-sidedness. + * killough 8/1/98: avoid duplicate if same sector on both sides + * cph - DEMOSYNC? */ + + if (LN_BACKSECTOR(ld) && LN_BACKSECTOR(ld) != LN_FRONTSECTOR(ld)) + _g->sector_list = P_AddSecnode(LN_BACKSECTOR(ld), _g->tmthing, _g->sector_list); + + return true; +} + +// phares 3/14/98 +// +// P_CreateSecNodeList alters/creates the sector_list that shows what sectors +// the object resides in. + +void P_CreateSecNodeList(mobj_t *thing, fixed_t x, fixed_t y) +{ + int xl; + int xh; + int yl; + int yh; + int bx; + int by; + msecnode_t *node; + mobj_t *saved_tmthing = _g->tmthing; /* cph - see comment at func end */ + + // First, clear out the existing m_thing fields. As each node is + // added or verified as needed, m_thing will be set properly. When + // finished, delete all nodes where m_thing is still NULL. These + // represent the sectors the Thing has vacated. + + node = _g->sector_list; + while (node) + { + node->m_thing_sptr = 0; + node = getMsecnodeTNext(node); + } + + _g->tmthing = thing; + + _g->tmx = x; + _g->tmy = y; + + _g->tmbbox[BOXTOP] = y + getMobjRadius(_g->tmthing); + _g->tmbbox[BOXBOTTOM] = y - getMobjRadius(_g->tmthing); + _g->tmbbox[BOXRIGHT] = x + getMobjRadius(_g->tmthing); + _g->tmbbox[BOXLEFT] = x - getMobjRadius(_g->tmthing); + + _g->validcount++; // used to make sure we only process a line once + + xl = (_g->tmbbox[BOXLEFT] - _g->bmaporgx) >> MAPBLOCKSHIFT; + xh = (_g->tmbbox[BOXRIGHT] - _g->bmaporgx) >> MAPBLOCKSHIFT; + yl = (_g->tmbbox[BOXBOTTOM] - _g->bmaporgy) >> MAPBLOCKSHIFT; + yh = (_g->tmbbox[BOXTOP] - _g->bmaporgy) >> MAPBLOCKSHIFT; + + for (bx = xl; bx <= xh; bx++) + for (by = yl; by <= yh; by++) + P_BlockLinesIterator(bx, by, PIT_GetSectors); + + // Add the sector of the (x,y) point to sector_list. + + _g->sector_list = P_AddSecnode(getMobjSubsector(thing)->sector, thing, _g->sector_list); + + // Now delete any nodes that won't be used. These are the ones where + // m_thing is still NULL. + + node = _g->sector_list; + while (node) + { + if (node->m_thing_sptr == 0) + { + if (node == _g->sector_list) + _g->sector_list = getMsecnodeTNext(node); + node = P_DelSecnode(node); + } + else + node = getMsecnodeTNext(node); + } + + /* cph - + * This is the strife we get into for using global variables. tmthing + * is being used by several different functions calling + * P_BlockThingIterator, including functions that can be called *from* + * P_BlockThingIterator. Using a global tmthing is not reentrant. + * OTOH for Boom/MBF demos we have to preserve the buggy behavior. + * Fun. We restore its previous value unless we're in a Boom/MBF demo. + */ + _g->tmthing = saved_tmthing; +} + +/* cphipps 2004/08/30 - + * Must clear tmthing at tic end, as it might contain a pointer to a removed thinker, or the level might have ended/been ended and we clear the objects it was pointing too. Hopefully we don't need to carry this between tics for sync. */ +void P_MapStart(void) +{ + if (_g->tmthing) + I_Error("P_MapStart: tmthing set!"); +} + +void P_MapEnd(void) +{ + _g->tmthing = NULL; +} diff --git a/doom/src/pdoom/Doom/source/p_maputl.c b/doom/src/pdoom/Doom/source/p_maputl.c new file mode 100644 index 0000000..cf15f23 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_maputl.c @@ -0,0 +1,962 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Movement/collision utility functions, + * as used by function in p_map.c. + * BLOCKMAP Iterator functions, + * and some PIT_* functions to use for iteration. + * + * next-hack: + * modified code to work with short pointers. + * also reverted pointer-to-pointer scheme back to original because + * it is simpler to handle with short pointers. + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "m_bbox.h" +#include "r_main.h" +#include "p_maputl.h" +#include "p_map.h" +#include "p_setup.h" + +#include "global_data.h" +intercept_t intercepts[MAXINTERCEPTS]; +boolean interceptIsALine[MAXINTERCEPTS]; +intercept_t *intercept_p; +// +// P_AproxDistance +// Gives an estimation of distance (not exact) +// + +fixed_t CONSTFUNC P_AproxDistance(fixed_t dx, fixed_t dy) +{ + dx = D_abs(dx); + dy = D_abs(dy); + if (dx < dy) + return dx + dy - (dx >> 1); + return dx + dy - (dy >> 1); +} + +// +// P_PointOnLineSide +// Returns 0 or 1 +// +// killough 5/3/98: reformatted, cleaned up + +int PUREFUNC P_PointOnLineSide(fixed_t x, fixed_t y, const line_t *line) +{ + return !line->dx ? x <= line->v1.x ? line->dy > 0 : line->dy < 0 + : + !line->dy ? y <= line->v1.y ? line->dx < 0 : line->dx > 0: + FixedMul(y - line->v1.y, line->dx >> FRACBITS) >= FixedMul(line->dy >> FRACBITS, x - line->v1.x); +} + +// +// P_BoxOnLineSide +// Considers the line to be infinite +// Returns side 0 or 1, -1 if box crosses the line. +// +// killough 5/3/98: reformatted, cleaned up + +int PUREFUNC P_BoxOnLineSide(const fixed_t *tmbox, const line_t *ld) +{ + int p; + switch (ld->slopetype) + { + + default: // shut up compiler warnings -- killough + case ST_HORIZONTAL: + return (tmbox[BOXBOTTOM] > ld->v1.y) == (p = tmbox[BOXTOP] > ld->v1.y) ? p ^ (ld->dx < 0) : -1; + case ST_VERTICAL: + return (tmbox[BOXLEFT] < ld->v1.x) == (p = tmbox[BOXRIGHT] < ld->v1.x) ? p ^ (ld->dy < 0) : -1; + case ST_POSITIVE: + return P_PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXBOTTOM], ld) == (p = P_PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXTOP], ld)) ? p : -1; + case ST_NEGATIVE: + return (P_PointOnLineSide(tmbox[BOXLEFT], tmbox[BOXBOTTOM], ld)) == (p = P_PointOnLineSide(tmbox[BOXRIGHT], tmbox[BOXTOP], ld)) ? p : -1; + } +} + +// +// P_PointOnDivlineSide +// Returns 0 or 1. +// +// killough 5/3/98: reformatted, cleaned up + +static int PUREFUNC P_PointOnDivlineSide(fixed_t x, fixed_t y, const divline_t *line) +{ + return !line->dx ? x <= line->x ? line->dy > 0 : line->dy < 0 + : + !line->dy ? y <= line->y ? line->dx < 0 : line->dx > 0 + : + (line->dy ^ line->dx ^ (x -= line->x) ^ (y -= line->y)) < 0 ? (line->dy ^ x) < 0 : FixedMul(y >> 8, line->dx >> 8) >= FixedMul(line->dy >> 8, x >> 8); +} + +// +// P_MakeDivline +// + +static void P_MakeDivline(const line_t *li, divline_t *dl) +{ + dl->x = li->v1.x; + dl->y = li->v1.y; + dl->dx = li->dx; + dl->dy = li->dy; +} + +// +// P_InterceptVector +// Returns the fractional intercept point +// along the first divline. +// This is only called by the addthings +// and addlines traversers. +// + +/* cph - this is killough's 4/19/98 version of P_InterceptVector and + * P_InterceptVector2 (which were interchangeable). We still use this + * in compatibility mode. */ +fixed_t PUREFUNC P_InterceptVector2(const divline_t *v2, const divline_t *v1) +{ + fixed_t den; + return ((den = FixedMul(v1->dy >> 8, v2->dx) - FixedMul(v1->dx >> 8, v2->dy))) ? FixedDiv(FixedMul((v1->x - v2->x) >> 8, v1->dy) + FixedMul((v2->y - v1->y) >> 8, v1->dx), den) : 0; +} + +// +// P_LineOpening +// Sets opentop and openbottom to the window +// through a two sided line. +// OPTIMIZE: keep this precalculated +// + +void P_LineOpening(const line_t *linedef) +{ + if (linedef->sidenum[1] == NO_INDEX) // single sided line + { + _g->openrange = 0; + return; + } + + _g->openfrontsector = LN_FRONTSECTOR(linedef); + _g->openbacksector = LN_BACKSECTOR(linedef); + + if (_g->openfrontsector->ceilingheight < _g->openbacksector->ceilingheight) + _g->opentop = _g->openfrontsector->ceilingheight; + else + _g->opentop = _g->openbacksector->ceilingheight; + + if (_g->openfrontsector->floorheight > _g->openbacksector->floorheight) + { + _g->openbottom = _g->openfrontsector->floorheight; + _g->lowfloor = _g->openbacksector->floorheight; + } + else + { + _g->openbottom = _g->openbacksector->floorheight; + _g->lowfloor = _g->openfrontsector->floorheight; + } + _g->openrange = _g->opentop - _g->openbottom; +} + +// +// THING POSITION SETTING +// + +// +// P_UnsetThingPosition +// Unlinks a thing from block map and sectors. +// On each position change, BLOCKMAP and other +// lookups maintaining lists ot things inside +// these structures need to be updated. +// + +void P_UnsetThingPosition(mobj_t *thing) +{ + if (!(thing->flags & MF_NOSECTOR )) + { + // invisible things don't need to be in sector list + // unlink from subsector + if (thing->snext_sptr) + getSNext(thing)->sprev_sptr = thing->sprev_sptr; + if (thing->sprev_sptr) + getSPrev(thing)->snext_sptr = thing->snext_sptr; + else + { + // getMobjSubsector(thing)->sector->thinglist = getLongPtr(thing->snext_sptr); + getMobjSubsector(thing)->sector->thinglist_sptr = thing->snext_sptr; + } + // phares 3/14/98 + // + // Save the sector list pointed to by touching_sectorlist. + // In P_SetThingPosition, we'll keep any nodes that represent + // sectors the Thing still touches. We'll add new ones then, and + // delete any nodes for sectors the Thing has vacated. Then we'll + // put it back into touching_sectorlist. It's done this way to + // avoid a lot of deleting/creating for nodes, when most of the + // time you just get back what you deleted anyway. + // + // If this Thing is being removed entirely, then the calling + // routine will clear out the nodes in sector_list. + + _g->sector_list = getTouchingSectorList(thing); + thing->touching_sectorlist_sptr = 0; + } + + if (!(thing->flags & MF_NOBLOCKMAP )) + { + /* inert things don't need to be in blockmap + */ + int blockx; + int blocky; + if (thing->bnext_sptr) + getBNext(thing)->bprev_sptr = thing->bprev_sptr; + + if (thing->bprev_sptr) + getBPrev(thing)->bnext_sptr = thing->bnext_sptr; + else + { + blockx = (thing->x - _g->bmaporgx) >> MAPBLOCKSHIFT; + blocky = (thing->y - _g->bmaporgy) >> MAPBLOCKSHIFT; + + if (blockx >= 0 && blockx < _g->bmapwidth && blocky >= 0 && blocky < _g->bmapheight) + { + _g->blocklinks_sptrs[blocky * _g->bmapwidth + blockx] = thing->bnext_sptr; + } + } + } +} + +// +// P_SetThingPosition +// Links a thing into both a block and a subsector +// based on it's x y. +// Sets thing->subsector properly +// +// killough 5/3/98: reformatted, cleaned up +void P_SetThingPosition(mobj_t *thing) +{ // link into subsector + subsector_t *ss = setMobjSubesctor(thing, R_PointInSubsector(thing->x, thing->y)); + if (!(thing->flags & MF_NOSECTOR )) + { + // invisible things don't go into the sector links + sector_t *sec = ss->sector; + + thing->sprev_sptr = 0; + thing->snext_sptr = sec->thinglist_sptr; + if (sec->thinglist_sptr) + getSectorThingList(sec)->sprev_sptr = getShortPtr(thing); + sec->thinglist_sptr = getShortPtr(thing); + + // phares 3/16/98 + // + // If sector_list isn't NULL, it has a collection of sector + // nodes that were just removed from this Thing. + + // Collect the sectors the object will live in by looking at + // the existing sector_list and adding new nodes and deleting + // obsolete ones. + + // When a node is deleted, its sector links (the links starting + // at sector_t->touching_thinglist) are broken. When a node is + // added, new sector links are created. + + P_CreateSecNodeList(thing, thing->x, thing->y); + thing->touching_sectorlist_sptr = getShortPtr(_g->sector_list); // Attach to Thing's mobj_t + _g->sector_list = NULL; // clear for next time + } + + // link into blockmap + if (!(thing->flags & MF_NOBLOCKMAP )) + { + // inert things don't need to be in blockmap + int blockx = (thing->x - _g->bmaporgx) >> MAPBLOCKSHIFT; + int blocky = (thing->y - _g->bmaporgy) >> MAPBLOCKSHIFT; + if (blockx >= 0 && blockx < _g->bmapwidth && blocky >= 0 && blocky < _g->bmapheight) + { + unsigned short *link = &_g->blocklinks_sptrs[blocky * _g->bmapwidth + blockx]; + thing->bprev_sptr = 0; + thing->bnext_sptr = *link; + if (*link) + ((mobj_t*) getLongPtr(*link))->bprev_sptr = getShortPtr(thing); + *link = getShortPtr(thing); + } + else + { + // thing is off the map + thing->bnext_sptr = thing->bprev_sptr = 0; + } + } +} + +// +// BLOCK MAP ITERATORS +// For each line/thing in the given mapblock, +// call the passed PIT_* function. +// If the function returns false, +// exit with false without checking anything else. +// + +// +// P_BlockLinesIterator +// The validcount flags are used to avoid checking lines +// that are marked in multiple mapblocks, +// so increment validcount before the first call +// to P_BlockLinesIterator, then make one or more calls +// to it. +// +// killough 5/3/98: reformatted, cleaned up + +boolean P_BlockLinesIterator(int x, int y, boolean func(const line_t*)) +{ + + if (x < 0 || y < 0 || x >= _g->bmapwidth || y >= _g->bmapheight) + return true; + + const int offset = _g->blockmap[y * _g->bmapwidth + x]; + const short *list = _g->blockmaplump + offset; // original was reading // phares + + // delmiting 0 as linedef 0 // phares + + // killough 1/31/98: for compatibility we need to use the old method. + // Most demos go out of sync, and maybe other problems happen, if we + // don't consider linedef 0. For safety this should be qualified. + if (!demo_compatibility) // killough 2/22/98: demo_compatibility check + list++; // skip 0 starting delimiter // phares + + const uint16_t vcount = _g->validcount; + + for (; *list != -1; list++) // phares + { + const int lineno = *list; + + linedata_t *lt = &_g->linedata[lineno]; + + if (lt->validcount == vcount) + continue; // line has already been checked + + lt->validcount = vcount; + + const line_t *ld = &_g->lines[lineno]; + + if (!func(ld)) + return false; + } + + return true; // everything was checked +} + +// +// P_BlockThingsIterator +// +// killough 5/3/98: reformatted, cleaned up + +boolean P_BlockThingsIterator(int x, int y, boolean func(mobj_t*)) +{ + mobj_t *mobj; + if (!(x < 0 || y < 0 || x >= _g->bmapwidth || y >= _g->bmapheight)) + for (mobj = getLongPtr(_g->blocklinks_sptrs[y * _g->bmapwidth + x]); + mobj; mobj = getBNext(mobj)) + { + if (!func(mobj)) + return false; + } + return true; +} + +// +// INTERCEPT ROUTINES +// + +// Check for limit and double size if necessary -- killough +static boolean check_intercept(void) +{ + size_t offset = intercept_p - intercepts; + if (offset >= MAXINTERCEPTS) + { + printf ("Too many intercepts, blocking"); + while(1); + } + return (offset < MAXINTERCEPTS); +} + +// PIT_AddLineIntercepts. +// Looks for lines in the given block +// that intercept the given trace +// to add to the intercepts list. +// +// A line is crossed if its endpoints +// are on opposite sides of the trace. +// +// killough 5/3/98: reformatted, cleaned up + +boolean PIT_AddLineIntercepts(const line_t *ld) +{ + int s1; + int s2; + fixed_t frac; + divline_t dl; + + // avoid precision problems with two routines + if (_g->trace.dx > FRACUNIT * 16 || _g->trace.dy > FRACUNIT * 16 || _g->trace.dx < -FRACUNIT * 16 || _g->trace.dy < -FRACUNIT * 16) + { + s1 = P_PointOnDivlineSide(ld->v1.x, ld->v1.y, &_g->trace); + s2 = P_PointOnDivlineSide(ld->v2.x, ld->v2.y, &_g->trace); + } + else + { + s1 = P_PointOnLineSide(_g->trace.x, _g->trace.y, ld); + s2 = P_PointOnLineSide(_g->trace.x + _g->trace.dx, _g->trace.y + _g->trace.dy, ld); + } + + if (s1 == s2) + return true; // line isn't crossed + + // hit the line + P_MakeDivline(ld, &dl); + frac = P_InterceptVector2(&_g->trace, &dl); + + if (frac < 0) + return true; // behind source + + if (!check_intercept()) + return false; + + int index = (int) (intercept_p - intercepts); + checkInterceptIndex(index); + interceptIsALine[index] = true; + // + + intercept_p->frac = frac; + //intercept_p->isaline = true; + intercept_p->d.line = ld; + intercept_p++; + + return true; // continue +} + +// +// PIT_AddThingIntercepts +// +// killough 5/3/98: reformatted, cleaned up + +boolean PIT_AddThingIntercepts(mobj_t *thing) +{ + fixed_t x1, y1; + fixed_t x2, y2; + int s1, s2; + divline_t dl; + fixed_t frac; + + // check a corner to corner crossection for hit + if ((_g->trace.dx ^ _g->trace.dy) > 0) + { + x1 = thing->x - getMobjRadius(thing); + y1 = thing->y + getMobjRadius(thing); + x2 = thing->x + getMobjRadius(thing); + y2 = thing->y - getMobjRadius(thing); + } + else + { + x1 = thing->x - getMobjRadius(thing); + y1 = thing->y - getMobjRadius(thing); + x2 = thing->x + getMobjRadius(thing); + y2 = thing->y + getMobjRadius(thing); + } + + s1 = P_PointOnDivlineSide(x1, y1, &_g->trace); + s2 = P_PointOnDivlineSide(x2, y2, &_g->trace); + + if (s1 == s2) + return true; // line isn't crossed + + dl.x = x1; + dl.y = y1; + dl.dx = x2 - x1; + dl.dy = y2 - y1; + + frac = P_InterceptVector2(&_g->trace, &dl); + + if (frac < 0) + return true; // behind source + + if (!check_intercept()) + return false; + int index = (int) (intercept_p - intercepts); + checkInterceptIndex(index); + interceptIsALine[index] = false; + + intercept_p->frac = frac; +// intercept_p->isaline = false; + intercept_p->d.thing = thing; + intercept_p++; + + return true; // keep going +} + +// +// P_TraverseIntercepts +// Returns true if the traverser function returns true +// for all lines. +// +// killough 5/3/98: reformatted, cleaned up + +boolean P_TraverseIntercepts(traverser_t func, fixed_t maxfrac) +{ + intercept_t *in = NULL; + int count = intercept_p - intercepts; + while (count--) + { + fixed_t dist = INT_MAX; + intercept_t *scan; + for (scan = intercepts; scan < intercept_p; scan++) + if (scan->frac < dist) + dist = (in = scan)->frac; + if (dist > maxfrac) + return true; // checked everything in range + if (!func(in)) + return false; // don't bother going farther + in->frac = INT_MAX; + } + return true; // everything was traversed +} + +// +// P_PathTraverse +// Traces a line from x1,y1 to x2,y2, +// calling the traverser function for each. +// Returns true if the traverser function returns true +// for all lines. +// +// killough 5/3/98: reformatted, cleaned up +#if 1 +boolean P_PathTraverse(fixed_t x1, fixed_t y1, fixed_t x2, fixed_t y2, int flags, boolean trav(intercept_t*)) +{ + fixed_t xt1, yt1; + fixed_t xt2, yt2; + fixed_t xstep, ystep; + fixed_t partial; + fixed_t xintercept, yintercept; + int mapx, mapy; + int mapxstep, mapystep; + int count; + + _g->validcount++; + intercept_p = intercepts; + + if (!((x1 - _g->bmaporgx) & (MAPBLOCKSIZE - 1))) + x1 += FRACUNIT; // don't side exactly on a line + + if (!((y1 - _g->bmaporgy) & (MAPBLOCKSIZE - 1))) + y1 += FRACUNIT; // don't side exactly on a line + + _g->trace.x = x1; + _g->trace.y = y1; + _g->trace.dx = x2 - x1; + _g->trace.dy = y2 - y1; + + x1 -= _g->bmaporgx; + y1 -= _g->bmaporgy; + xt1 = x1 >> MAPBLOCKSHIFT; + yt1 = y1 >> MAPBLOCKSHIFT; + + x2 -= _g->bmaporgx; + y2 -= _g->bmaporgy; + xt2 = x2 >> MAPBLOCKSHIFT; + yt2 = y2 >> MAPBLOCKSHIFT; + + if (xt2 > xt1) + { + mapxstep = 1; + partial = FRACUNIT - ((x1 >> MAPBTOFRAC) & (FRACUNIT - 1)); + ystep = FixedDiv(y2 - y1, D_abs(x2 - x1)); + } + else if (xt2 < xt1) + { + mapxstep = -1; + partial = (x1 >> MAPBTOFRAC) & (FRACUNIT - 1); + ystep = FixedDiv(y2 - y1, D_abs(x2 - x1)); + } + else + { + mapxstep = 0; + partial = FRACUNIT; + ystep = 256 * FRACUNIT; + } + + yintercept = (y1 >> MAPBTOFRAC) + FixedMul(partial, ystep); + + if (yt2 > yt1) + { + mapystep = 1; + partial = FRACUNIT - ((y1 >> MAPBTOFRAC) & (FRACUNIT - 1)); + xstep = FixedDiv(x2 - x1, D_abs(y2 - y1)); + } + else if (yt2 < yt1) + { + mapystep = -1; + partial = (y1 >> MAPBTOFRAC) & (FRACUNIT - 1); + xstep = FixedDiv(x2 - x1, D_abs(y2 - y1)); + } + else + { + mapystep = 0; + partial = FRACUNIT; + xstep = 256 * FRACUNIT; + } + + xintercept = (x1 >> MAPBTOFRAC) + FixedMul(partial, xstep); + + // Step through map blocks. + // Count is present to prevent a round off error + // from skipping the break. + + mapx = xt1; + mapy = yt1; + + for (count = 0; count < 64; count++) + { + if (flags & PT_ADDLINES) + if (!P_BlockLinesIterator(mapx, mapy, PIT_AddLineIntercepts)) + return false; // early out + + if (flags & PT_ADDTHINGS) + if (!P_BlockThingsIterator(mapx, mapy, PIT_AddThingIntercepts)) + return false; // early out + + if (mapx == xt2 && mapy == yt2) + break; + + if ((yintercept >> FRACBITS) == mapy) + { + yintercept += ystep; + mapx += mapxstep; + } + else if ((xintercept >> FRACBITS) == mapx) + { + xintercept += xstep; + mapy += mapystep; + } + } + + // go through the sorted list + return P_TraverseIntercepts(trav, FRACUNIT); +} +#elif 0 +boolean P_PathTraverse(fixed_t x1, fixed_t y1, fixed_t x2, fixed_t y2, int flags, boolean trav(intercept_t*)) +{ + fixed_t xt1, yt1; + fixed_t xt2, yt2; + fixed_t xstep, ystep; + fixed_t partial; + fixed_t xintercept, yintercept; + int mapx, mapy; + int mapx1, mapy1; + int mapxstep, mapystep; + int count; + + _g->validcount++; + intercept_p = intercepts; + + if (!((x1 - _g->bmaporgx) & (MAPBLOCKSIZE - 1))) + x1 += FRACUNIT; // don't side exactly on a line + + if (!((y1 - _g->bmaporgy) & (MAPBLOCKSIZE - 1))) + y1 += FRACUNIT; // don't side exactly on a line + + _g->trace.x = x1; + _g->trace.y = y1; + _g->trace.dx = x2 - x1; + _g->trace.dy = y2 - y1; + + if (demo_compatibility) + { + int_64_t _x1, _x2, _y1, _y2; + + _x1 = (int_64_t)x1 - _g->bmaporgx; + _y1 = (int_64_t)y1 - _g->bmaporgy; + xt1 = (int)(_x1>>MAPBLOCKSHIFT); + yt1 = (int)(_y1>>MAPBLOCKSHIFT); + + mapx1 = (int)(_x1>>MAPBTOFRAC); + mapy1 = (int)(_y1>>MAPBTOFRAC); + + _x2 = (int_64_t)x2 - _g->bmaporgx; + _y2 = (int_64_t)y2 - _g->bmaporgy; + xt2 = (int)(_x2>>MAPBLOCKSHIFT); + yt2 = (int)(_y2>>MAPBLOCKSHIFT); + + x1 -= _g->bmaporgx; + y1 -= _g->bmaporgy; + x2 -= _g->bmaporgx; + y2 -= _g->bmaporgy; + } + else + { + x1 -= _g->bmaporgx; + y1 -= _g->bmaporgy; + xt1 = x1>>MAPBLOCKSHIFT; + yt1 = y1>>MAPBLOCKSHIFT; + + mapx1 = x1>>MAPBTOFRAC; + mapy1 = y1>>MAPBTOFRAC; + + x2 -= _g->bmaporgx; + y2 -= _g->bmaporgy; + xt2 = x2>>MAPBLOCKSHIFT; + yt2 = y2>>MAPBLOCKSHIFT; + } + if (xt2 > xt1) + { + mapxstep = 1; + partial = FRACUNIT - (mapx1&(FRACUNIT-1)); + ystep = FixedDiv (y2-y1,D_abs(x2-x1)); + } + else + if (xt2 < xt1) + { + mapxstep = -1; + partial = mapx1&(FRACUNIT-1); + ystep = FixedDiv (y2-y1,D_abs(x2-x1)); + } + else + { + mapxstep = 0; + partial = FRACUNIT; + ystep = 256 * FRACUNIT; + } + + yintercept = mapy1 + FixedMul(partial, ystep); + + if (yt2 > yt1) + { + mapystep = 1; + partial = FRACUNIT - (mapy1&(FRACUNIT-1)); + xstep = FixedDiv (x2-x1,D_abs(y2-y1)); + } + else if (yt2 < yt1) + { + mapystep = -1; + partial = mapy1&(FRACUNIT-1); + xstep = FixedDiv (x2-x1,D_abs(y2-y1)); + } + else + { + mapystep = 0; + partial = FRACUNIT; + xstep = 256 * FRACUNIT; + } + + xintercept = mapx1 + FixedMul(partial, xstep); + + // Step through map blocks. + // Count is present to prevent a round off error + // from skipping the break. + + mapx = xt1; + mapy = yt1; + + for (count = 0; count < 64; count++) + { + if (flags & PT_ADDLINES) + if (!P_BlockLinesIterator(mapx, mapy, PIT_AddLineIntercepts)) + return false; // early out + + if (flags & PT_ADDTHINGS) + if (!P_BlockThingsIterator(mapx, mapy, PIT_AddThingIntercepts)) + return false; // early out + + if (mapx == xt2 && mapy == yt2) + break; + + if ((yintercept >> FRACBITS) == mapy) + { + yintercept += ystep; + mapx += mapxstep; + } + else if ((xintercept >> FRACBITS) == mapx) + { + xintercept += xstep; + mapy += mapystep; + } + } + + // go through the sorted list + return P_TraverseIntercepts(trav, FRACUNIT); +} +#else +boolean +P_PathTraverse +( fixed_t x1, + fixed_t y1, + fixed_t x2, + fixed_t y2, + int flags, + boolean (*trav) (intercept_t *)) +{ + fixed_t xt1; + fixed_t yt1; + fixed_t xt2; + fixed_t yt2; + + fixed_t xstep; + fixed_t ystep; + + fixed_t partial; + + fixed_t xintercept; + fixed_t yintercept; + + int mapx; + int mapy; + + int mapxstep; + int mapystep; + + int count; + + //earlyout = (flags & PT_EARLYOUT) != 0; + + _g->validcount++; + intercept_p = intercepts; + + if ( ((x1-_g->bmaporgx)&(MAPBLOCKSIZE-1)) == 0) + x1 += FRACUNIT; // don't side exactly on a line + + if ( ((y1-_g->bmaporgy)&(MAPBLOCKSIZE-1)) == 0) + y1 += FRACUNIT; // don't side exactly on a line + + _g->trace.x = x1; + _g->trace.y = y1; + _g->trace.dx = x2 - x1; + _g->trace.dy = y2 - y1; + + x1 -= _g->bmaporgx; + y1 -=_g-> bmaporgy; + xt1 = x1>>MAPBLOCKSHIFT; + yt1 = y1>>MAPBLOCKSHIFT; + + x2 -= _g->bmaporgx; + y2 -= _g->bmaporgy; + xt2 = x2>>MAPBLOCKSHIFT; + yt2 = y2>>MAPBLOCKSHIFT; + + if (xt2 > xt1) + { + mapxstep = 1; + partial = FRACUNIT - ((x1>>MAPBTOFRAC)&(FRACUNIT-1)); + ystep = FixedDiv (y2-y1,abs(x2-x1)); + } + else if (xt2 < xt1) + { + mapxstep = -1; + partial = (x1>>MAPBTOFRAC)&(FRACUNIT-1); + ystep = FixedDiv (y2-y1,abs(x2-x1)); + } + else + { + mapxstep = 0; + partial = FRACUNIT; + ystep = 256*FRACUNIT; + } + + yintercept = (y1>>MAPBTOFRAC) + FixedMul (partial, ystep); + + + if (yt2 > yt1) + { + mapystep = 1; + partial = FRACUNIT - ((y1>>MAPBTOFRAC)&(FRACUNIT-1)); + xstep = FixedDiv (x2-x1,abs(y2-y1)); + } + else if (yt2 < yt1) + { + mapystep = -1; + partial = (y1>>MAPBTOFRAC)&(FRACUNIT-1); + xstep = FixedDiv (x2-x1,abs(y2-y1)); + } + else + { + mapystep = 0; + partial = FRACUNIT; + xstep = 256*FRACUNIT; + } + xintercept = (x1>>MAPBTOFRAC) + FixedMul (partial, xstep); + + // Step through map blocks. + // Count is present to prevent a round off error + // from skipping the break. + mapx = xt1; + mapy = yt1; + + for (count = 0 ; count < 64 ; count++) + { + if (flags & PT_ADDLINES) + { + if (!P_BlockLinesIterator (mapx, mapy,PIT_AddLineIntercepts)) + return false; // early out + } + + if (flags & PT_ADDTHINGS) + { + if (!P_BlockThingsIterator (mapx, mapy,PIT_AddThingIntercepts)) + return false; // early out + } + + if (mapx == xt2 + && mapy == yt2) + { + break; + } + + if ( (yintercept >> FRACBITS) == mapy) + { + yintercept += ystep; + mapx += mapxstep; + } + else if ( (xintercept >> FRACBITS) == mapx) + { + xintercept += xstep; + mapy += mapystep; + } + + } + // go through the sorted list + return P_TraverseIntercepts ( trav, FRACUNIT ); +} + +#endif \ No newline at end of file diff --git a/doom/src/pdoom/Doom/source/p_mobj.c b/doom/src/pdoom/Doom/source/p_mobj.c new file mode 100644 index 0000000..5ff2ac0 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_mobj.c @@ -0,0 +1,1120 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Moving object handling. Spawn functions. + * + * next-hack: modified code to work with short pointers + * added support for static_mobj_t, which are reduced size + * mobj_t structures, for unmovable objects. + * + *-----------------------------------------------------------------------------*/ + +#include "doomdef.h" +#include "doomstat.h" +#include "m_random.h" +#include "r_main.h" +#include "p_maputl.h" +#include "p_map.h" +#include "p_tick.h" +#include "sounds.h" +#include "st_stuff.h" +#include "hu_stuff.h" +#include "s_sound.h" +#include "info.h" +#include "g_game.h" +#include "p_inter.h" +#include "lprintf.h" + +#include "global_data.h" +// 18-06-2021 next-hack: static assert to check mobj_t and static_mobj_t size +// if you get an error, make sure that you did not mess up with different versions +const char dummy1[(MOBJ_SIZE == sizeof(mobj_t)) - 1]; +const char dummy2[(STATIC_MOBJ_SIZE == sizeof(static_mobj_t)) - 1]; + +// +// P_ExplodeMissile +// + +void P_ExplodeMissile(mobj_t *mo) +{ + mo->momx = mo->momy = mo->momz = 0; + + P_SetMobjState(mo, mobjinfo[mo->type].deathstate); + + mo->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 3; + + if (mo->tics < 1) + mo->tics = 1; + + mo->flags &= ~MF_MISSILE; + + if (getMobjInfo(mo)->deathsound) + S_StartSound(mo, getMobjInfo(mo)->deathsound); +} + +// +// P_XYMovement +// +// Attempts to move something if it has momentum. +// + +void P_XYMovement(mobj_t *mo) +{ + if (mo->flags & MF_STATIC) + printf("Move on static object!\r\n"); + player_t *player; + fixed_t xmove, ymove; + + if (!(mo->momx | mo->momy)) // Any momentum? + { + if (mo->flags & MF_SKULLFLY) + { + + // the skull slammed into something + + mo->flags &= ~MF_SKULLFLY; + mo->momz = 0; + + P_SetMobjState(mo, getMobjInfo(mo)->spawnstate); + } + return; + } + + player = getMobjPlayer(mo); + + if (mo->momx > MAXMOVE) + mo->momx = MAXMOVE; + else if (mo->momx < -MAXMOVE) + mo->momx = -MAXMOVE; + + if (mo->momy > MAXMOVE) + mo->momy = MAXMOVE; + else if (mo->momy < -MAXMOVE) + mo->momy = -MAXMOVE; + + xmove = mo->momx; + ymove = mo->momy; + + do + { + fixed_t ptryx, ptryy; + // killough 8/9/98: fix bug in original Doom source: + // Large negative displacements were never considered. + // This explains the tendency for Mancubus fireballs + // to pass through walls. + // CPhipps - compatibility optioned + + if (xmove > MAXMOVE / 2 || ymove > MAXMOVE / 2 || (!demo_compatibility) && ((xmove < -MAXMOVE / 2 || ymove < -MAXMOVE / 2))) + { + ptryx = mo->x + xmove / 2; + ptryy = mo->y + ymove / 2; + xmove >>= 1; + ymove >>= 1; + } + else + { + ptryx = mo->x + xmove; + ptryy = mo->y + ymove; + xmove = ymove = 0; + } + + // killough 3/15/98: Allow objects to drop off + + if (!P_TryMove(mo, ptryx, ptryy, true)) + { + // blocked move + + if (player) // try to slide along it + P_SlideMove(mo); + else + { + if (mo->flags & MF_MISSILE) + { + // explode a missile + + if (_g->ceilingline) + { + const sector_t *ceilingBackSector = LN_BACKSECTOR(_g->ceilingline); + + if (ceilingBackSector && ceilingBackSector->ceilingpic == _g->skyflatnum) + { + if (demo_compatibility || // killough + mo->z > ceilingBackSector->ceilingheight) + { + // Hack to prevent missiles exploding + // against the sky. + // Does not handle sky floors. + + P_RemoveMobj(mo); + return; + } + } + } + + P_ExplodeMissile(mo); + } + else // whatever else it is, it is now standing still in (x,y) + { + mo->momx = mo->momy = 0; + } + } + } + } while (xmove || ymove); + + // slow down + + /* no friction for missiles or skulls ever, no friction when airborne */ + if ((mo->flags & (MF_MISSILE | MF_SKULLFLY )) || mo->z > mo->floorz) + return; + + /* killough 8/11/98: add bouncers + * killough 9/15/98: add objects falling off ledges + * killough 11/98: only include bouncers hanging off ledges + */ + if ((mo->flags & MF_CORPSE ) && (mo->momx > FRACUNIT / 4 || mo->momx < -FRACUNIT / 4 || mo->momy > FRACUNIT / 4 || mo->momy < -FRACUNIT / 4) && mo->floorz != getMobjSubsector(mo)->sector->floorheight) + return; // do not stop sliding if halfway off a step with some momentum + + // killough 11/98: + // Stop voodoo dolls that have come to rest, despite any + // moving corresponding player, except in old demos: + + if (mo->momx > -STOPSPEED && mo->momx < STOPSPEED && mo->momy > -STOPSPEED && mo->momy < STOPSPEED && (!player || !(player->cmd.forwardmove | player->cmd.sidemove) || (player->mo != mo))) + { + // if in a walking frame, stop moving + + // killough 10/98: + // Don't affect main player when voodoo dolls stop, except in old demos: + + // if ( player&&(unsigned)((player->mo->state - states)- S_PLAY_RUN1) < 4) + // P_SetMobjState (player->mo, S_PLAY); + if (player && (unsigned) (getMobjState(player->mo) - states - S_PLAY_RUN1) < 4 && (player->mo == mo)) + P_SetMobjState(player->mo, S_PLAY); + + mo->momx = mo->momy = 0; + + /* killough 10/98: kill any bobbing momentum too (except in voodoo dolls) + * cph - DEMOSYNC - needs compatibility check? + */ + if (player && player->mo == mo) + player->momx = player->momy = 0; + } + else + { + /* phares 3/17/98 + * + * Friction will have been adjusted by friction thinkers for + * icy or muddy floors. Otherwise it was never touched and + * remained set at ORIG_FRICTION + * + * killough 8/28/98: removed inefficient thinker algorithm, + * instead using touching_sectorlist in P_GetFriction() to + * determine friction (and thus only when it is needed). + * + * killough 10/98: changed to work with new bobbing method. + * Reducing player momentum is no longer needed to reduce + * bobbing, so ice works much better now. + * + * cph - DEMOSYNC - need old code for Boom demos? + */ + + fixed_t friction = ORIG_FRICTION; + + mo->momx = FixedMul(mo->momx, friction); + mo->momy = FixedMul(mo->momy, friction); + + /* killough 10/98: Always decrease player bobbing by ORIG_FRICTION. + * This prevents problems with bobbing on ice, where it was not being + * reduced fast enough, leading to all sorts of kludges being developed. + */ + + if (player && player->mo == mo) /* Not voodoo dolls */ + { + player->momx = FixedMul(player->momx, ORIG_FRICTION); + player->momy = FixedMul(player->momy, ORIG_FRICTION); + } + } +} + +// +// P_ZMovement +// +// Attempt vertical movement. + +void P_ZMovement(mobj_t *mo) +{ + if (mo->flags & MF_STATIC) + printf("P_ZMovement static\r\n"); + // check for smooth step up + + if (mo->player_sptr && getMobjPlayer(mo)->mo == mo && // killough 5/12/98: exclude voodoo dolls + mo->z < mo->floorz) + { + getMobjPlayer(mo)->viewheight -= mo->floorz - mo->z; + getMobjPlayer(mo)->deltaviewheight = (VIEWHEIGHT - getMobjPlayer(mo)->viewheight) >> 3; + } + + // adjust altitude + + mo->z += mo->momz; + + if ((mo->flags & MF_FLOAT ) && getTarget(mo)) + + // float down towards target if too close + + if (!((mo->flags ^ MF_FLOAT ) & (MF_FLOAT | MF_SKULLFLY | MF_INFLOAT )) && getTarget(mo)) /* killough 11/98: simplify */ + { + fixed_t delta; + if (P_AproxDistance(mo->x - getTarget(mo)->x, mo->y - getTarget(mo)->y) < D_abs(delta = getTarget(mo)->z + (getMobjHeight(mo) >> 1) - mo->z) * 3) + mo->z += delta < 0 ? -FLOATSPEED : FLOATSPEED; + } + + // clip movement + + if (mo->z <= mo->floorz) + { + // hit the floor + + /* Note (id): + * somebody left this after the setting momz to 0, + * kinda useless there. + * cph - This was the a bug in the linuxdoom-1.10 source which + * caused it not to sync Doom 2 v1.9 demos. Someone + * added the above comment and moved up the following code. So + * demos would desync in close lost soul fights. + * cph - revised 2001/04/15 - + * This was a bug in the Doom/Doom 2 source; the following code + * is meant to make charging lost souls bounce off of floors, but it + * was incorrectly placed after momz was set to 0. + * However, this bug was fixed in Doom95, Final/Ultimate Doom, and + * the v1.10 source release (which is one reason why it failed to sync + * some Doom2 v1.9 demos) + * I've added a comp_soul compatibility option to make this behavior + * selectable for PrBoom v2.3+. For older demos, we do this here only + * if we're in a compatibility level above Doom 2 v1.9 (in which case we + * mimic the bug and do it further down instead) + */ + + if (mo->flags & MF_SKULLFLY) + mo->momz = -mo->momz; // the skull slammed into something + + if (mo->momz < 0) + { + if (mo->player_sptr && /* killough 5/12/98: exclude voodoo dolls */ + getMobjPlayer(mo)->mo == mo && mo->momz < -GRAVITY * 8) + { + // Squat down. + // Decrease viewheight for a moment + // after hitting the ground (hard), + // and utter appropriate sound. + + getMobjPlayer(mo)->deltaviewheight = mo->momz >> 3; + if (mo->health > 0) /* cph - prevent "oof" when dead */ + S_StartSound(mo, sfx_oof); + } + mo->momz = 0; + } + mo->z = mo->floorz; + + if ((mo->flags & MF_MISSILE ) && !(mo->flags & MF_NOCLIP )) + { + P_ExplodeMissile(mo); + return; + } + } + else // still above the floor // phares + if (!(mo->flags & MF_NOGRAVITY )) + { + if (!mo->momz) + mo->momz = -GRAVITY; + mo->momz -= GRAVITY; + } + + if (mo->z + getMobjHeight(mo) > mo->ceilingz) + { + /* cph 2001/04/15 - + * Lost souls were meant to bounce off of ceilings; + * new comp_soul compatibility option added + */ + if (mo->flags & MF_SKULLFLY) + mo->momz = -mo->momz; // the skull slammed into something + + // hit the ceiling + + if (mo->momz > 0) + mo->momz = 0; + + mo->z = mo->ceilingz - getMobjHeight(mo); + + if ((mo->flags & MF_MISSILE ) && !(mo->flags & MF_NOCLIP )) + { + P_ExplodeMissile(mo); + return; + } + } +} + +// +// P_NightmareRespawn +// + +void P_NightmareRespawn(mobj_t *mobj) +{ + fixed_t x; + fixed_t y; + fixed_t z; + subsector_t *ss; + mobj_t *mo; + + /* haleyjd: stupid nightmare respawning bug fix + * + * 08/09/00: compatibility added, time to ramble :) + * This fixes the notorious nightmare respawning bug that causes monsters + * that didn't spawn at level startup to respawn at the point (0,0) + * regardless of that point's nature. SMMU and Eternity need this for + * script-spawned things like Halif Swordsmythe, as well. + * + * cph - copied from eternity, except comp_respawnfix becomes comp_respawn + * and the logic is reversed (i.e. like the rest of comp_ it *disables* + * the fix) + */ + + //ZLB: Everything respawns at its death point. + //The spawnpoint is removed from the mobj. + x = mobj->x; + y = mobj->y; + + if (!x && !y) + { + return; + } + + // something is occupying its position? + + if (!P_CheckPosition(mobj, x, y)) + return; // no respwan + + // spawn a teleport fog at old spot + // because of removal of the body? + + mo = P_SpawnMobj(mobj->x, mobj->y, getMobjSubsector(mobj)->sector->floorheight, MT_TFOG); + + // initiate teleport sound + + S_StartSound(mo, sfx_telept); + + // spawn a teleport fog at the new spot + + ss = R_PointInSubsector(x, y); + + mo = P_SpawnMobj(x, y, ss->sector->floorheight, MT_TFOG); + + S_StartSound(mo, sfx_telept); + + // spawn the new monster + + //mthing = &mobj->spawnpoint; + if (getMobjInfo(mobj)->flags & MF_SPAWNCEILING) + z = ONCEILINGZ; + else + z = ONFLOORZ; + + // inherit attributes from deceased one + + mo = P_SpawnMobj(x, y, z, mobj->type); + mo->angle = mobj->angle; + + /* killough 11/98: transfer friendliness from deceased */ + mo->flags = (mo->flags & ~MF_FRIEND ) | (mobj->flags & MF_FRIEND ); + + mo->reactiontime = 18; + + // remove the old monster, + + P_RemoveMobj(mobj); +} + +//Thinker function for stuff that doesn't need to do anything +//interesting. +//Just cycles through the states. Allows sprite animation to work. +void P_MobjBrainlessThinker(mobj_t *mobj) +{ + // cycle through states, + // calling action functions at transitions + + if (mobj->tics != -1) + { + mobj->tics--; + + // you can cycle through multiple states in a tic + + if (!mobj->tics) + P_SetMobjState(mobj, getMobjState(mobj)->nextstate); + } +} + +static think_t P_ThinkerFunctionForType(mobjtype_t type, mobj_t *mobj) +{ + //Full thinking ability. + if (type < MT_MISC0) + return P_MobjThinker; + + //Just state cycles. + if (mobj->tics != -1) + return P_MobjBrainlessThinker; + + //No thinking at all. + return NULL; +} +// +#include "z_bmalloc.h" +IMPLEMENT_BLOCK_MEMORY_ALLOC_ZONE(mobjzone, ((sizeof(mobj_t) + 3) / 4) * 4, PU_LEVEL, 16, "Mobj"); +IMPLEMENT_BLOCK_MEMORY_ALLOC_ZONE(static_mobjzone, ((sizeof(static_mobj_t) + 3) / 4) * 4, PU_LEVEL, 16, "Mobj"); +inline static static_mobj_t* P_GetStaticMobj(void) +{ + return (static_mobj_t*) Z_BMalloc(&static_mobjzone); +} + +inline static mobj_t* P_GetMobj(void) +{ + return (mobj_t*) Z_BMalloc(&mobjzone); +} + +// +// P_SpawnMobj +// +mobj_t* P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type) +{ + mobj_t *mobj; + const state_t *st; + const mobjinfo_t *info; + info = &mobjinfo[type]; + + if (info->flags & MF_STATIC) + return (mobj_t*) P_SpawnStaticMobj(x, y, z, type); + mobj = P_GetMobj(); //*/ Z_Malloc (sizeof(*mobj), PU_LEVEL, NULL); + //printf("Mobj 0x%08X\r\n", (uint32_t) mobj); + memset(mobj, 0, sizeof(*mobj)); + // info removed. Redundant and consumes 4 bytes per mobj. + mobj->type = type; + // mobj->info = info; + mobj->x = x; + mobj->y = y; + mobj->radiusb = info->radius >> FRACBITS; + mobj->height_s = info->height >> FRACBITS; // phares + mobj->flags = info->flags; + + if (type == MT_PLAYER) // Except in old demos, players + mobj->flags |= MF_FRIEND; // are always friends. + + mobj->health = info->spawnhealth; + + if (_g->gameskill != sk_nightmare) + mobj->reactiontime = info->reactiontime; + + mobj->lastlook = P_Random (__FILE__,__LINE__, __FUNCTION__) % MAXPLAYERS; + // do not set the state with P_SetMobjState, + // because action routines can not be called yet + + st = &states[info->spawnstate]; + + //mobj->state = st; + mobj->state_idx = info->spawnstate; + mobj->tics = st->tics; + mobj->sprite = st->sprite; + mobj->frame = st->frame; + //mobj->touching_sectorlist = NULL; // NULL head of sector list // phares 3/13/98 + mobj->touching_sectorlist_sptr = 0; + // set subsector and/or block links + + P_SetThingPosition(mobj); + + mobj->dropoffz = /* killough 11/98: for tracking dropoffs */ + mobj->floorz = getMobjSubsector(mobj)->sector->floorheight; + mobj->ceilingz = getMobjSubsector(mobj)->sector->ceilingheight; + + mobj->z = z == ONFLOORZ ? mobj->floorz : + z == ONCEILINGZ ? mobj->ceilingz - getMobjHeight(mobj) : z; + + mobj->thinker.function = P_ThinkerFunctionForType(type, mobj); + + //mobj->target = NULL; + mobj->target_sptr = 0; + mobj->tracer_sptr = 0; + mobj->lastenemy_sptr = 0; + P_AddThinker(&mobj->thinker); + if (!((mobj->flags ^ MF_COUNTKILL ) & (MF_FRIEND | MF_COUNTKILL ))) + _g->totallive++; + return mobj; +} +// +// +// +// 2021-03-13 next-hack +// P_SpawnStaticMobj +// +static_mobj_t* P_SpawnStaticMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type) +{ + static_mobj_t *mobj; + const state_t *st; + const mobjinfo_t *info; + + mobj = P_GetStaticMobj(); //*/ Z_Malloc (sizeof(*mobj), PU_LEVEL, NULL); + memset(mobj, 0, sizeof(*mobj)); + // info removed. Redundant and consumes 4 bytes per mobj. + info = &mobjinfo[type]; + mobj->type = type; + // mobj->info = info; + mobj->x = x; + mobj->y = y; + //mobj->radiusb = info->radius >> FRACBITS; + //mobj->height_s = info->height >> FRACBITS; // phares + mobj->flags = info->flags; + + if (type == MT_PLAYER) // Except in old demos, players + mobj->flags |= MF_FRIEND; // are always friends. + + st = &states[info->spawnstate]; + + //mobj->state = st; + mobj->state_idx = info->spawnstate; + mobj->tics = st->tics; + mobj->sprite = st->sprite; + mobj->frame = st->frame; + //mobj->touching_sectorlist = NULL; // NULL head of sector list // phares 3/13/98 + mobj->touching_sectorlist_sptr = 0; + // set subsector and/or block links + mobj->lastlook = P_Random (__FILE__,__LINE__, __FUNCTION__) % MAXPLAYERS; // only to call random for compatibiltiy + // + P_SetThingPosition((mobj_t*) mobj); + +// mobj->dropoffz = /* killough 11/98: for tracking dropoffs */ +//mobj->floorz = getMobjSubsector(mobj)->sector->floorheight; +// mobj->ceilingz = getMobjSubsector(mobj)->sector->ceilingheight; + +// mobj->z = z == ONFLOORZ ? mobj->floorz : z == ONCEILINGZ ? mobj->ceilingz - getMobjHeight(mobj) : z; + mobj->z = + z == ONFLOORZ ? getMobjSubsector((mobj_t*) mobj)->sector->floorheight : + z == ONCEILINGZ ? getMobjSubsector((mobj_t*) mobj)->sector->ceilingheight - getMobjHeight((mobj_t*) mobj) : z; + + mobj->thinker.function = P_ThinkerFunctionForType(type, (mobj_t*) mobj); + + //mobj->target = NULL; + P_AddThinker(&mobj->thinker); +// if (!((mobj->flags ^ MF_COUNTKILL) & (MF_FRIEND | MF_COUNTKILL))) +// _g->totallive++; + _g->totalstatic++; + return mobj; +} + +// +// P_RemoveMobj +// + +void P_RemoveMobj(mobj_t *mobj) +{ + if (mobj->flags & MF_STATIC) + { + P_RemoveStaticMobj((static_mobj_t*) mobj); // this will also unset thing position. + return; + } + P_UnsetThingPosition(mobj); + + // Delete all nodes on the current sector_list phares 3/16/98 + + if (_g->sector_list) + { + P_DelSeclist(_g->sector_list); + _g->sector_list = NULL; + } + + // stop any playing sound + + S_StopSound(mobj); + + // killough 11/98: + // + // Remove any references to other mobjs. + // + // Older demos might depend on the fields being left alone, however, + // if multiple thinkers reference each other indirectly before the + // end of the current tic. + // CPhipps - only leave dead references in old demos; I hope lxdoom_1 level + // demos are rare and don't rely on this. I hope. + + if (!_g->demoplayback) + { + //P_SetTarget(&mobj->target, NULL); + mobj->target_sptr = 0; + //P_SetTarget(&mobj->tracer, NULL); + mobj->tracer_sptr = 0; + //P_SetTarget(getLastEnemy(mobj), NULL); + mobj->lastenemy_sptr = 0; + } + // free block + P_RemoveThinker(&mobj->thinker); +} +// 2021-03-13 next-hack special function for bonus or other unmovable objects +void P_RemoveStaticMobj(static_mobj_t *mobj) +{ + P_UnsetThingPosition((mobj_t*) mobj); + + // Delete all nodes on the current sector_list phares 3/16/98 + + if (_g->sector_list) + { + P_DelSeclist(_g->sector_list); + _g->sector_list = NULL; + } + + // killough 11/98: + // + // Remove any references to other mobjs. + // + // Older demos might depend on the fields being left alone, however, + // if multiple thinkers reference each other indirectly before the + // end of the current tic. + // CPhipps - only leave dead references in old demos; I hope lxdoom_1 level + // demos are rare and don't rely on this. I hope. + + P_RemoveStaticThinker(&mobj->thinker); +} + +/* + * P_FindDoomedNum + * + * Finds a mobj type with a matching doomednum + * + * killough 8/24/98: rewrote to use hashing + */ + +static PUREFUNC int P_FindDoomedNum(unsigned int type) +{ + // find which type to spawn + for (int i = 0; i < NUMMOBJTYPES; i++) + { + if (type == mobjinfo[i].doomednum) + return i; + } + + return NUMMOBJTYPES; +} + +// +// P_RespawnSpecials +// + +void P_RespawnSpecials(void) +{ +} + +// +// P_SpawnPlayer +// Called when a player is spawned on the level. +// Most of the player structure stays unchanged +// between levels. +// + +void P_SpawnPlayer(int n, const mapthing_t *mthing) +{ + player_t *p; + fixed_t x; + fixed_t y; + fixed_t z; + mobj_t *mobj; + + // not playing? + + if (!_g->playeringame) + return; + + p = &_g->player; + + if (p->playerstate == PST_REBORN) + G_PlayerReborn(mthing->type - 1); + + /* cph 2001/08/14 - use the options field of memorised player starts to + * indicate whether the start really exists in the level. + */ + if (!mthing->options) + I_Error("P_SpawnPlayer: attempt to spawn player at unavailable start point"); + + x = mthing->x << FRACBITS; + y = mthing->y << FRACBITS; + z = ONFLOORZ; + mobj = P_SpawnMobj(x, y, z, MT_PLAYER); + + // set color translations for player sprites + + mobj->angle = ANG45 * (mthing->angle / 45); + + mobj->player_sptr = getShortPtr(p); + mobj->health = p->health; + + p->mo = mobj; + p->playerstate = PST_LIVE; + p->refire = 0; + p->message = NULL; + p->damagecount = 0; + p->bonuscount = 0; + p->extralight = 0; + p->fixedcolormap = 0; + p->viewheight = VIEWHEIGHT; + + p->momx = p->momy = 0; // killough 10/98: initialize bobbing to 0. + + // setup gun psprite + + P_SetupPsprites(p); + + if (mthing->type - 1 == 0) + { + ST_Start(); // wake up the status bar + HU_Start(); // wake up the heads up text + } +} + +/* + * P_IsDoomnumAllowed() + * Based on code taken from P_LoadThings() in src/p_setup.c Return TRUE + * if the thing in question is expected to be available in the gamemode used. + */ + +boolean P_IsDoomnumAllowed(int doomnum) +{ + // Do not spawn cool, new monsters if !commercial + if (_g->gamemode != commercial) + switch (doomnum) + { + case 64: // Archvile + case 65: // Former Human Commando + case 66: // Revenant + case 67: // Mancubus + case 68: // Arachnotron + case 69: // Hell Knight + case 71: // Pain Elemental + case 84: // Wolf SS + case 88: // Boss Brain + case 89: // Boss Shooter + return false; + } + + return true; +} + +// +// P_SpawnMapThing +// The fields of the mapthing should +// already be in host byte order. +// + +void P_SpawnMapThing(const mapthing_t *mthing) +{ + int i; + //int bit; + mobj_t *mobj; + fixed_t x; + fixed_t y; + fixed_t z; + int options = mthing->options; /* cph 2001/07/07 - make writable copy */ + + // killough 2/26/98: Ignore type-0 things as NOPs + // phares 5/14/98: Ignore Player 5-8 starts (for now) + + switch (mthing->type) + { + case 0: + case DEN_PLAYER5: + case DEN_PLAYER6: + case DEN_PLAYER7: + case DEN_PLAYER8: + return; + } + + // killough 11/98: clear flags unused by Doom + // + // We clear the flags unused in Doom if we see flag mask 256 set, since + // it is reserved to be 0 under the new scheme. A 1 in this reserved bit + // indicates it's a Doom wad made by a Doom editor which puts 1's in + // bits that weren't used in Doom (such as HellMaker wads). So we should + // then simply ignore all upper bits. + + if (options & MTF_RESERVED) + { + lprintf(LO_WARN, "P_SpawnMapThing: correcting bad flags (%u) (thing type %d)\n", options, mthing->type); + options &= MTF_EASY | MTF_NORMAL | MTF_HARD | MTF_AMBUSH | MTF_NOTSINGLE; + } + + // check for players specially + + //Only care about start spot for player 1. + if (mthing->type == 1) + { + _g->playerstarts[0] = *mthing; + _g->playerstarts[0].options = 1; + P_SpawnPlayer(0, &_g->playerstarts[0]); + printf("spawn player\r\n"); + return; + } + + // check for apropriate skill level + + /* jff "not single" thing flag */ + if (options & MTF_NOTSINGLE) + return; + + // killough 11/98: simplify + if (_g->gameskill == sk_baby || _g->gameskill == sk_easy ? !(options & MTF_EASY) : + _g->gameskill == sk_hard || _g->gameskill == sk_nightmare ? !(options & MTF_HARD) : !(options & MTF_NORMAL)) + return; + + // find which type to spawn + + // killough 8/23/98: use table for faster lookup + i = P_FindDoomedNum(mthing->type); + + // phares 5/16/98: + // Do not abort because of an unknown thing. Ignore it, but post a + // warning message for the player. + + if (i == NUMMOBJTYPES) + { + return; + } + + x = mthing->x << FRACBITS; + y = mthing->y << FRACBITS; + + if (mobjinfo[i].flags & MF_SPAWNCEILING) + z = ONCEILINGZ; + else + z = ONFLOORZ; + mobj = P_SpawnMobj(x, y, z, i); + //mobj->spawnpoint = *mthing; + if (mobj->tics > 0) + mobj->tics = 1 + (P_Random(__FILE__, __LINE__, __FUNCTION__) % mobj->tics); + + if (!(mobj->flags & MF_FRIEND ) && (options & MTF_FRIEND)) + { + mobj->flags |= MF_FRIEND; // killough 10/98: + } + + /* killough 7/20/98: exclude friends */ + if (!((mobj->flags ^ MF_COUNTKILL ) & (MF_FRIEND | MF_COUNTKILL ))) + _g->totalkills++; + + if (mobj->flags & MF_COUNTITEM) + _g->totalitems++; + if (!(mobj->flags & MF_STATIC)) + mobj->angle = ANG45 * (mthing->angle / 45); + if (options & MTF_AMBUSH) + mobj->flags |= MF_AMBUSH; +} + +// +// GAME SPAWN FUNCTIONS +// + +// +// P_SpawnPuff +// +void P_SpawnPuff(fixed_t x, fixed_t y, fixed_t z) +{ + mobj_t *th; + // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + z += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 10; + + th = P_SpawnMobj(x, y, z, MT_PUFF); + th->momz = FRACUNIT; + th->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 3; + + if (th->tics < 1) + th->tics = 1; + + // don't make punches spark on the wall + + if (_g->attackrange == MELEERANGE) + P_SetMobjState(th, S_PUFF3); +} + +// +// P_SpawnBlood +// +void P_SpawnBlood(fixed_t x, fixed_t y, fixed_t z, int damage) +{ + mobj_t *th; + // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + z += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 10; + th = P_SpawnMobj(x, y, z, MT_BLOOD); + th->momz = FRACUNIT * 2; + th->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 3; + + if (th->tics < 1) + th->tics = 1; + + if (damage <= 12 && damage >= 9) + P_SetMobjState(th, S_BLOOD2); + else if (damage < 9) + P_SetMobjState(th, S_BLOOD3); +} + +// +// P_CheckMissileSpawn +// Moves the missile forward a bit +// and possibly explodes it right there. +// + +void P_CheckMissileSpawn(mobj_t *th) +{ + th->tics -= P_Random(__FILE__, __LINE__, __FUNCTION__) & 3; + if (th->tics < 1) + th->tics = 1; + + // move a little forward so an angle can + // be computed if it immediately explodes + + th->x += (th->momx >> 1); + th->y += (th->momy >> 1); + th->z += (th->momz >> 1); + + // killough 8/12/98: for non-missile objects (e.g. grenades) + if (!(th->flags & MF_MISSILE )) + return; + + // killough 3/15/98: no dropoff (really = don't care for missiles) + + if (!P_TryMove(th, th->x, th->y, false)) + P_ExplodeMissile(th); +} + +// +// P_SpawnMissile +// + +mobj_t* P_SpawnMissile(mobj_t *source, mobj_t *dest, mobjtype_t type) +{ + mobj_t *th; + angle_t an; + int dist; + + th = P_SpawnMobj(source->x, source->y, source->z + 4 * 8 * FRACUNIT, type); + + if (getMobjInfo(th)->seesound) + S_StartSound(th, getMobjInfo(th)->seesound); + + //P_SetTarget(&th->target, source); // where it came from + th->target_sptr = getShortPtr(source); + an = R_PointToAngle2(source->x, source->y, dest->x, dest->y); + + // fuzzy player + + if (dest->flags & MF_SHADOW) + { // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + an += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 20; + } + + th->angle = an; + an >>= ANGLETOFINESHIFT; + th->momx = FixedMul(getMobjInfo(th)->speed, finecosine[an]); + th->momy = FixedMul(getMobjInfo(th)->speed, finesine[an]); + + dist = P_AproxDistance(dest->x - source->x, dest->y - source->y); + dist = dist / getMobjInfo(th)->speed; + + if (dist < 1) + dist = 1; + + th->momz = (dest->z - source->z) / dist; + P_CheckMissileSpawn(th); + + return th; +} + +// +// P_SpawnPlayerMissile +// Tries to aim at a nearby monster +// + +void P_SpawnPlayerMissile(mobj_t *source, mobjtype_t type) +{ + mobj_t *th; + fixed_t x, y, z, slope = 0; + + // see which target is to be aimed at + + angle_t an = source->angle; + + // killough 7/19/98: autoaiming was not in original beta + { + // killough 8/2/98: prefer autoaiming at enemies + unsigned int mask = MF_FRIEND; + + do + { + slope = P_AimLineAttack(source, an, 16 * 64 * FRACUNIT, mask); + if (!_g->linetarget) + slope = P_AimLineAttack(source, an += 1 << 26, 16 * 64 * FRACUNIT, mask); + if (!_g->linetarget) + slope = P_AimLineAttack(source, an -= 2 << 26, 16 * 64 * FRACUNIT, mask); + if (!_g->linetarget) + an = source->angle, slope = 0; + } while (mask && (mask = 0, !_g->linetarget)); // killough 8/2/98 + } + + x = source->x; + y = source->y; + z = source->z + 4 * 8 * FRACUNIT; + + th = P_SpawnMobj(x, y, z, type); + + if (getMobjInfo(th)->seesound) + S_StartSound(th, getMobjInfo(th)->seesound); + + //P_SetTarget(&th->target, source); + th->target_sptr = getShortPtr(source); + th->angle = an; + th->momx = FixedMul(getMobjInfo(th)->speed, finecosine[an >> ANGLETOFINESHIFT]); + th->momy = FixedMul(getMobjInfo(th)->speed, finesine[an >> ANGLETOFINESHIFT]); + th->momz = FixedMul(getMobjInfo(th)->speed, slope); + + P_CheckMissileSpawn(th); +} diff --git a/doom/src/pdoom/Doom/source/p_plats.c b/doom/src/pdoom/Doom/source/p_plats.c new file mode 100644 index 0000000..eba767f --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_plats.c @@ -0,0 +1,448 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Plats (i.e. elevator platforms) code, raising/lowering. + * + * next-hack: modified code to work with short pointers. + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "m_random.h" +#include "r_main.h" +#include "p_spec.h" +#include "p_tick.h" +#include "s_sound.h" +#include "sounds.h" + +#include "global_data.h" + +platlist_t *activeplats; // killough 2/14/98: made global again + +// +// T_PlatRaise() +// +// Action routine to move a plat up and down +// +// Passed a plat structure containing all pertinent information about the move +// No return +// +// jff 02/08/98 all cases with labels beginning with gen added to support +// generalized line type behaviors. + +void T_PlatRaise(plat_t *plat) +{ + result_e res; + + // handle plat moving, up, down, waiting, or in stasis, + switch (plat->status) + { + case up: // plat moving up + res = T_MovePlane(plat->sector, plat->speed, plat->high, plat->crush, 0, 1); + + // if a pure raise type, make the plat moving sound + if (plat->type == raiseAndChange || plat->type == raiseToNearestAndChange) + { + if (!(_g->leveltime & 7)) + S_StartSound2(&plat->sector->soundorg, sfx_stnmov); + } + + // if encountered an obstacle, and not a crush type, reverse direction + if (res == crushed && (!plat->crush)) + { + plat->count = plat->wait; + plat->status = down; + S_StartSound2(&plat->sector->soundorg, sfx_pstart); + } + else // else handle reaching end of up stroke + { + if (res == pastdest) // end of stroke + { + // if not an instant toggle type, wait, make plat stop sound + if (plat->type != toggleUpDn) + { + plat->count = plat->wait; + plat->status = waiting; + S_StartSound2(&plat->sector->soundorg, sfx_pstop); + } + else // else go into stasis awaiting next toggle activation + { + plat->oldstatus = plat->status; //jff 3/14/98 after action wait + plat->status = in_stasis; //for reactivation of toggle + } + + // lift types and pure raise types are done at end of up stroke + // only the perpetual type waits then goes back up + switch (plat->type) + { + case blazeDWUS: + case downWaitUpStay: + case raiseAndChange: + case raiseToNearestAndChange: + case genLift: + P_RemoveActivePlat(plat); // killough + default: + break; + } + } + } + break; + + case down: // plat moving down + res = T_MovePlane(plat->sector, plat->speed, plat->low, false, 0, -1); + + // handle reaching end of down stroke + if (res == pastdest) + { + // if not an instant toggle, start waiting, make plat stop sound + if (plat->type != toggleUpDn) //jff 3/14/98 toggle up down + { // is silent, instant, no waiting + plat->count = plat->wait; + plat->status = waiting; + S_StartSound2(&plat->sector->soundorg, sfx_pstop); + } + else // instant toggles go into stasis awaiting next activation + { + plat->oldstatus = plat->status; //jff 3/14/98 after action wait + plat->status = in_stasis; //for reactivation of toggle + } + + //jff 1/26/98 remove the plat if it bounced so it can be tried again + //only affects plats that raise and bounce + //killough 1/31/98: relax compatibility to demo_compatibility + + switch (plat->type) + { + case raiseAndChange: + case raiseToNearestAndChange: + P_RemoveActivePlat(plat); + default: + break; + } + + } + break; + + case waiting: // plat is waiting + if (!--plat->count) // downcount and check for delay elapsed + { + if (plat->sector->floorheight == plat->low) + plat->status = up; // if at bottom, start up + else + plat->status = down; // if at top, start down + + // make plat start sound + S_StartSound2(&plat->sector->soundorg, sfx_pstart); + } + break; //jff 1/27/98 don't pickup code added later to in_stasis + + case in_stasis: // do nothing if in stasis + break; + } +} + +// +// EV_DoPlat +// +// Handle Plat linedef types +// +// Passed the linedef that activated the plat, the type of plat action, +// and for some plat types, an amount to raise +// Returns true if a thinker is started, or restarted from stasis +// +int EV_DoPlat(const line_t *line, plattype_e type, int amount) +{ + plat_t *plat; + int secnum; + int rtn; + sector_t *sec; + + secnum = -1; + rtn = 0; + + // Activate all plats that are in_stasis + switch (type) + { + case perpetualRaise: + P_ActivateInStasis(line->tag); + break; + + case toggleUpDn: + P_ActivateInStasis(line->tag); + rtn = 1; + break; + + default: + break; + } + + // act on all sectors tagged the same as the activating linedef + while ((secnum = P_FindSectorFromLineTag(line, secnum)) >= 0) + { + sec = &_g->sectors[secnum]; + + // don't start a second floor function if already moving + if (P_SectorActive(floor_special, sec)) //jff 2/23/98 multiple thinkers + continue; + + // Create a thinker + rtn = 1; + plat = Z_Malloc(sizeof(*plat), PU_LEVSPEC, 0); + memset(plat, 0, sizeof(*plat)); + P_AddThinker(&plat->thinker); + + plat->type = type; + plat->sector = sec; + plat->sector->floordata_sptr = getShortPtr(plat); //jff 2/23/98 multiple thinkers + plat->thinker.function = T_PlatRaise; + plat->crush = false; + plat->tag = line->tag; + + //jff 1/26/98 Avoid raise plat bouncing a head off a ceiling and then + //going down forever -- default low to plat height when triggered + plat->low = sec->floorheight; + + // set up plat according to type + switch (type) + { + case raiseToNearestAndChange: + plat->speed = PLATSPEED / 2; + sec->floorpic = _g->sectors[_g->sides[line->sidenum[0]].sector_num].floorpic; + plat->high = P_FindNextHighestFloor(sec, sec->floorheight); + plat->wait = 0; + plat->status = up; + sec->special = 0; + //jff 3/14/98 clear old field as well + sec->oldspecial = 0; + + S_StartSound2(&sec->soundorg, sfx_stnmov); + break; + + case raiseAndChange: + plat->speed = PLATSPEED / 2; + sec->floorpic = _g->sectors[_g->sides[line->sidenum[0]].sector_num].floorpic; + plat->high = sec->floorheight + amount * FRACUNIT; + plat->wait = 0; + plat->status = up; + + S_StartSound2(&sec->soundorg, sfx_stnmov); + break; + + case downWaitUpStay: + plat->speed = PLATSPEED * 4; + plat->low = P_FindLowestFloorSurrounding(sec); + + if (plat->low > sec->floorheight) + plat->low = sec->floorheight; + + plat->high = sec->floorheight; + plat->wait = 35 * PLATWAIT; + plat->status = down; + S_StartSound2(&sec->soundorg, sfx_pstart); + break; + + case blazeDWUS: + plat->speed = PLATSPEED * 8; + plat->low = P_FindLowestFloorSurrounding(sec); + + if (plat->low > sec->floorheight) + plat->low = sec->floorheight; + + plat->high = sec->floorheight; + plat->wait = 35 * PLATWAIT; + plat->status = down; + S_StartSound2(&sec->soundorg, sfx_pstart); + break; + + case perpetualRaise: + plat->speed = PLATSPEED; + plat->low = P_FindLowestFloorSurrounding(sec); + + if (plat->low > sec->floorheight) + plat->low = sec->floorheight; + + plat->high = P_FindHighestFloorSurrounding(sec); + + if (plat->high < sec->floorheight) + plat->high = sec->floorheight; + + plat->wait = 35 * PLATWAIT; + plat->status = P_Random(__FILE__, __LINE__, __FUNCTION__) & 1; + + S_StartSound2(&sec->soundorg, sfx_pstart); + break; + + case toggleUpDn: //jff 3/14/98 add new type to support instant toggle + plat->speed = PLATSPEED; //not used + plat->wait = 35 * PLATWAIT; //not used + plat->crush = true; //jff 3/14/98 crush anything in the way + + // set up toggling between ceiling, floor inclusive + plat->low = sec->ceilingheight; + plat->high = sec->floorheight; + plat->status = down; + break; + + default: + break; + } + P_AddActivePlat(plat); // add plat to list of active plats + } + return rtn; +} + +// The following were all rewritten by Lee Killough +// to use the new structure which places no limits +// on active plats. It also avoids spending as much +// time searching for active plats. Previously a +// fixed-size array was used, with NULL indicating +// empty entries, while now a doubly-linked list +// is used. + +// +// P_ActivateInStasis() +// +// Activate a plat that has been put in stasis +// (stopped perpetual floor, instant floor/ceil toggle) +// +// Passed the tag of the plat that should be reactivated +// Returns nothing +// +void P_ActivateInStasis(int tag) +{ + platlist_t *pl; + for (pl = activeplats; pl; pl = pl->next) // search the active plats + { + plat_t *plat = pl->plat; // for one in stasis with right tag + if (plat->tag == tag && plat->status == in_stasis) + { + if (plat->type == toggleUpDn) //jff 3/14/98 reactivate toggle type + plat->status = plat->oldstatus == up ? down : up; + else + plat->status = plat->oldstatus; + plat->thinker.function = T_PlatRaise; + } + } +} + +// +// EV_StopPlat() +// +// Handler for "stop perpetual floor" linedef type +// +// Passed the linedef that stopped the plat +// Returns true if a plat was put in stasis +// +// jff 2/12/98 added int return value, fixed return +// +int EV_StopPlat(const line_t *line) +{ + platlist_t *pl; + for (pl = activeplats; pl; pl = pl->next) // search the active plats + { + plat_t *plat = pl->plat; // for one with the tag not in stasis + if (plat->status != in_stasis && plat->tag == line->tag) + { + plat->oldstatus = plat->status; // put it in stasis + plat->status = in_stasis; + plat->thinker.function = NULL; + } + } + return 1; +} + +// +// P_AddActivePlat() +// +// Add a plat to the head of the active plat list +// +// Passed a pointer to the plat to add +// Returns nothing +// +void P_AddActivePlat(plat_t *plat) +{ + platlist_t *old_head = activeplats; + // + platlist_t *list = Z_Malloc(sizeof *list, PU_LEVEL, (void** ) &activeplats); + list->plat = plat; + plat->list = list; + if ((list->next = old_head)) + list->next->prev = &list->next; + + list->prev = (platlist_t**) old_head; +} + +// +// P_RemoveActivePlat() +// +// Remove a plat from the active plat list +// +// Passed a pointer to the plat to remove +// Returns nothing +// +void P_RemoveActivePlat(plat_t *plat) +{ + platlist_t *list = plat->list; + plat->sector->floordata_sptr = 0; //jff 2/23/98 multiple thinkers + + P_RemoveThinker(&plat->thinker); + + if (list->prev && (*list->prev = list->next)) + list->next->prev = list->prev; + + free(list); +} + +// +// P_RemoveAllActivePlats() +// +// Remove all plats from the active plat list +// +// Passed nothing, returns nothing +// +void P_RemoveAllActivePlats(void) +{ + while (activeplats) + { + printf("Remove %x\r\n", activeplats); + platlist_t *next = activeplats->next; + free(activeplats); + activeplats = next; + } +} diff --git a/doom/src/pdoom/Doom/source/p_pspr.c b/doom/src/pdoom/Doom/source/p_pspr.c new file mode 100644 index 0000000..aa3023e --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_pspr.c @@ -0,0 +1,995 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Weapon sprite animation, weapon objects. + * Action functions for weapons. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "r_main.h" +#include "p_map.h" +#include "p_inter.h" +#include "p_pspr.h" +#include "p_enemy.h" +#include "m_random.h" +#include "s_sound.h" +#include "sounds.h" +#include "d_event.h" +#include "lprintf.h" + +#include "global_data.h" + +#define LOWERSPEED (FRACUNIT*6) +#define RAISESPEED (FRACUNIT*6) +#define WEAPONBOTTOM (FRACUNIT*128) +#define WEAPONTOP (FRACUNIT*32) + +#define BFGCELLS bfgcells /* Ty 03/09/98 externalized in p_inter.c */ + +// +// P_SetPsprite +// + +static void P_SetPsprite(player_t *player, int position, statenum_t stnum) +{ + pspdef_t *psp = &player->psprites[position]; + + do + { + const state_t *state; + + if (!stnum) + { + // object removed itself + psp->state = NULL; + break; + } + + state = &states[stnum]; + psp->state = state; + psp->tics = state->tics; // could be 0 + + if (state->misc1) + { + // coordinate set + psp->sx = state->misc1 << FRACBITS; + psp->sy = state->misc2 << FRACBITS; + } + + // Call action routine. + // Modified handling. + if (state->action) + { + state->action(player, psp); + if (!psp->state) + break; + } + stnum = psp->state->nextstate; + } while (!psp->tics); // an initial state of 0 could cycle through +} + +// +// P_BringUpWeapon +// Starts bringing the pending weapon up +// from the bottom of the screen. +// Uses player +// + +static void P_BringUpWeapon(player_t *player) +{ + statenum_t newstate; + + if (player->pendingweapon == wp_nochange) + player->pendingweapon = player->readyweapon; + + if (player->pendingweapon == wp_chainsaw) + S_StartSound(player->mo, sfx_sawup); + + newstate = weaponinfo[player->pendingweapon].upstate; + + player->pendingweapon = wp_nochange; + // killough 12/98: prevent pistol from starting visibly at bottom of screen: + player->psprites[ps_weapon].sy = + WEAPONBOTTOM; // next-hack: this causes demo desync + FRACUNIT * 2; + + P_SetPsprite(player, ps_weapon, newstate); +} + +// The first set is where the weapon preferences from // killough, +// default.cfg are stored. These values represent the keys used // phares +// in DOOM2 to bring up the weapon, i.e. 6 = plasma gun. These // | +// are NOT the wp_* constants. // V + +const int weapon_preferences[NUMWEAPONS + 1] = +{ 6, 9, 4, 3, 2, 8, 5, 7, 1, // !compatibility preferences +}; + +// P_SwitchWeapon checks current ammo levels and gives you the +// most preferred weapon with ammo. It will not pick the currently +// raised weapon. When called from P_CheckAmmo this won't matter, +// because the raised weapon has no ammo anyway. When called from +// G_BuildTiccmd you want to toggle to a different weapon regardless. + +int P_SwitchWeapon(player_t *player) +{ + const int *prefer = &weapon_preferences[0]; // killough 3/22/98 + int currentweapon = player->readyweapon; + int newweapon = currentweapon; + int i = NUMWEAPONS + 1; // killough 5/2/98 + + // killough 2/8/98: follow preferences and fix BFG/SSG bugs + + do + switch (*prefer++) + { + case 1: + if (!player->powers[pw_strength]) // allow chainsaw override + break; + case 0: + newweapon = wp_fist; + break; + case 2: + if (player->ammo[am_clip]) + newweapon = wp_pistol; + break; + case 3: + if (player->weaponowned[wp_shotgun] && player->ammo[am_shell]) + newweapon = wp_shotgun; + break; + case 4: + if (player->weaponowned[wp_chaingun] && player->ammo[am_clip]) + newweapon = wp_chaingun; + break; + case 5: + if (player->weaponowned[wp_missile] && player->ammo[am_misl]) + newweapon = wp_missile; + break; + case 6: + if (player->weaponowned[wp_plasma] && player->ammo[am_cell] && _g->gamemode != shareware) + newweapon = wp_plasma; + break; + case 7: + if (player->weaponowned[wp_bfg] && _g->gamemode != shareware && player->ammo[am_cell] >= (40)) + newweapon = wp_bfg; + break; + case 8: + if (player->weaponowned[wp_chainsaw]) + newweapon = wp_chainsaw; + break; + case 9: + if (player->weaponowned[wp_supershotgun] && _g->gamemode == commercial && player->ammo[am_shell] >= (2)) + newweapon = wp_supershotgun; + break; + } while (newweapon == currentweapon && --i); // killough 5/2/98 + return newweapon; +} + +// killough 5/2/98: whether consoleplayer prefers weapon w1 over weapon w2. +int P_WeaponPreferred(int w1, int w2) +{ + return (weapon_preferences[0] != ++w2 && (weapon_preferences[0] == ++w1 || (weapon_preferences[1] != w2 && (weapon_preferences[1] == w1 || (weapon_preferences[2] != w2 && (weapon_preferences[2] == w1 || (weapon_preferences[3] != w2 && (weapon_preferences[3] == w1 || (weapon_preferences[4] != w2 && (weapon_preferences[4] == w1 || (weapon_preferences[5] != w2 && (weapon_preferences[5] == w1 || (weapon_preferences[6] != w2 && (weapon_preferences[6] == w1 || (weapon_preferences[7] != w2 && (weapon_preferences[7] == w1)))))))))))))))); +} + +int P_CheckCanSwitchWeapon(weapontype_t weapon, player_t *player) +{ + switch (weapon) + { + case wp_fist: + { + return wp_fist; + } + break; + + case wp_pistol: + { + if (player->ammo[am_clip]) + return wp_pistol; + } + break; + + case wp_shotgun: + { + if (player->ammo[am_shell]) + return wp_shotgun; + } + break; + + case wp_chaingun: + { + if (player->ammo[am_clip]) + return wp_chaingun; + } + break; + + case wp_missile: + { + if (player->ammo[am_misl]) + return wp_missile; + } + break; + + case wp_plasma: + { + if (player->ammo[am_cell]) + return wp_plasma; + } + break; + + case wp_bfg: + { + if ((player->ammo[am_cell] >= 40) && (_g->gamemode != shareware)) + return wp_bfg; + } + break; + + case wp_chainsaw: + { + return wp_chainsaw; + } + break; + + case wp_supershotgun: + { + if ((player->ammo[am_shell] >= 2) && (_g->gamemode == commercial)) + return wp_supershotgun; + } + break; + case wp_nochange: // don't do anything + default: + break; + } + + return wp_nochange; +} + +int P_WeaponCycleUp(player_t *player) +{ + int w = player->readyweapon; + + for (int i = 0; i < NUMWEAPONS; i++) + { + w++; + if (w >= NUMWEAPONS) + w = 0; + + //Dumb hack to fix weapon order to be like PSXDoom ~Kippykip + switch (w) + { + case wp_chaingun: + { + w = wp_supershotgun; + } + break; + case wp_fist: + { + w = wp_chaingun; + } + break; + case wp_chainsaw: + { + w = wp_fist; + } + break; + case wp_pistol: + { + w = wp_chainsaw; + } + break; + case wp_supershotgun: + { + w = wp_pistol; + } + break; + } + + if (!player->weaponowned[w]) + continue; + + if (P_CheckCanSwitchWeapon(w, player) != wp_nochange) + return w; + + } + + return player->readyweapon; +} + +int P_WeaponCycleDown(player_t *player) +{ + int w = player->readyweapon; + + for (int i = 0; i < NUMWEAPONS; i++) + { + w--; + if (w < 0) + w = NUMWEAPONS - 1; + + //Dumb hack to fix weapon order to be like PSXDoom ~Kippykip + switch (w) + { + case wp_shotgun: + { + w = wp_supershotgun; + } + break; + case wp_chainsaw: + { + w = wp_shotgun; + } + break; + case wp_fist: + { + w = wp_chainsaw; + } + break; + case wp_bfg: + { + w = wp_fist; + } + break; + case wp_supershotgun: + { + w = wp_bfg; + } + break; + } + + if (!player->weaponowned[w]) + continue; + + if (P_CheckCanSwitchWeapon(w, player) != wp_nochange) + return w; + } + + return player->readyweapon; +} + +// +// P_CheckAmmo +// Returns true if there is enough ammo to shoot. +// If not, selects the next weapon to use. +// (only in demo_compatibility mode -- killough 3/22/98) +// + +boolean P_CheckAmmo(player_t *player) +{ + ammotype_t ammo = weaponinfo[player->readyweapon].ammo; + int count = 1; // Regular + + if (player->readyweapon == wp_bfg) // Minimal amount for one shot varies. + count = BFGCELLS; + else if (player->readyweapon == wp_supershotgun) // Double barrel. + count = 2; + + // Some do not need ammunition anyway. + // Return if current ammunition sufficient. + + if (ammo == am_noammo || player->ammo[ammo] >= count) + return true; + + if (demo_compatibility) // next-hack added for compatibility with demos + { + // Out of ammo, pick a weapon to change to. + // Preferences are set here. + do + { + if (player->weaponowned[wp_plasma] + && player->ammo[am_cell] + && (_g->gamemode != shareware) ) + { + player->pendingweapon = wp_plasma; + } + else if (player->weaponowned[wp_supershotgun] + && player->ammo[am_shell]>2 + && (_g->gamemode == commercial) ) + { + player->pendingweapon = wp_supershotgun; + } + else if (player->weaponowned[wp_chaingun] + && player->ammo[am_clip]) + { + player->pendingweapon = wp_chaingun; + } + else if (player->weaponowned[wp_shotgun] + && player->ammo[am_shell]) + { + player->pendingweapon = wp_shotgun; + } + else if (player->ammo[am_clip]) + { + player->pendingweapon = wp_pistol; + } + else if (player->weaponowned[wp_chainsaw]) + { + player->pendingweapon = wp_chainsaw; + } + else if (player->weaponowned[wp_missile] + && player->ammo[am_misl]) + { + player->pendingweapon = wp_missile; + } + else if (player->weaponowned[wp_bfg] + && player->ammo[am_cell]>40 + && (_g->gamemode != shareware) ) + { + player->pendingweapon = wp_bfg; + } + else + { + // If everything fails. + player->pendingweapon = wp_fist; + } + } while (player->pendingweapon == wp_nochange); + + // Now set appropriate weapon overlay. + P_SetPsprite (player, ps_weapon, weaponinfo[player->readyweapon].downstate); + + } + return false; +} + +// +// P_FireWeapon. +// + +static void P_FireWeapon(player_t *player) +{ + statenum_t newstate; + + if (!P_CheckAmmo(player)) + return; + + P_SetMobjState(player->mo, S_PLAY_ATK1); + newstate = weaponinfo[player->readyweapon].atkstate; + P_SetPsprite(player, ps_weapon, newstate); + P_NoiseAlert(player->mo, player->mo); +} + +// +// P_DropWeapon +// Player died, so put the weapon away. +// + +void P_DropWeapon(player_t *player) +{ + P_SetPsprite(player, ps_weapon, weaponinfo[player->readyweapon].downstate); +} + +// +// A_WeaponReady +// The player can fire the weapon +// or change to another weapon at this time. +// Follows after getting weapon up, +// or after previous attack/fire sequence. +// + +void A_WeaponReady(player_t *player, pspdef_t *psp) +{ + // get out of attack state + if (getMobjState(player->mo) == &states[S_PLAY_ATK1] || getMobjState(player->mo) == &states[S_PLAY_ATK2]) + P_SetMobjState(player->mo, S_PLAY); + + if (player->readyweapon == wp_chainsaw && psp->state == &states[S_SAW]) + S_StartSound(player->mo, sfx_sawidl); + + // check for change + // if player is dead, put the weapon away + + if (player->pendingweapon != wp_nochange || !player->health) + { + // change weapon (pending weapon should already be validated) + statenum_t newstate = weaponinfo[player->readyweapon].downstate; + P_SetPsprite(player, ps_weapon, newstate); + return; + } + + // check for fire + // the missile launcher and bfg do not auto fire + + if (player->cmd.buttons & BT_ATTACK) + { + if (!player->attackdown || (player->readyweapon != wp_missile && player->readyweapon != wp_bfg)) + { + player->attackdown = true; + P_FireWeapon(player); + return; + } + } + else + player->attackdown = false; + + // bob the weapon based on movement speed + { + int angle = (128 * _g->leveltime) & FINEMASK; + psp->sx = FRACUNIT + FixedMul(player->bob, finecosine[angle]); + angle &= FINEANGLES / 2 - 1; + psp->sy = WEAPONTOP + FixedMul(player->bob, finesine[angle]); + } +} + +// +// A_ReFire +// The player can re-fire the weapon +// without lowering it entirely. +// + +void A_ReFire(player_t *player, pspdef_t *psp) +{ + // check for fire + // (if a weaponchange is pending, let it go through instead) + + if ((player->cmd.buttons & BT_ATTACK) && player->pendingweapon == wp_nochange && player->health) + { + //player->refire++; + player->refire = 1; // changed to 1. + P_FireWeapon(player); + } + else + { + player->refire = 0; + P_CheckAmmo(player); + } +} + +void A_CheckReload(player_t *player, pspdef_t *psp) +{ + if (!P_CheckAmmo(player)) + { + /* cph 2002/08/08 - In old Doom, P_CheckAmmo would start the weapon lowering + * immediately. This was lost in Boom when the weapon switching logic was + * rewritten. But we must tell Doom that we don't need to complete the + * reload frames for the weapon here. G_BuildTiccmd will set ->pendingweapon + * for us later on. */ + P_SetPsprite(player, ps_weapon, weaponinfo[player->readyweapon].downstate); + } +} + +// +// A_Lower +// Lowers current weapon, +// and changes weapon at bottom. +// + +void A_Lower(player_t *player, pspdef_t *psp) +{ + psp->sy += LOWERSPEED; + + // Is already down. + if (psp->sy < WEAPONBOTTOM) + return; + + // Player is dead. + if (player->playerstate == PST_DEAD) + { + psp->sy = WEAPONBOTTOM; + return; // don't bring weapon back up + } + + // The old weapon has been lowered off the screen, + // so change the weapon and start raising it + + if (!player->health) + { // Player is dead, so keep the weapon off screen. + P_SetPsprite(player, ps_weapon, S_NULL); + return; + } + + player->readyweapon = player->pendingweapon; + + P_BringUpWeapon(player); +} + +// +// A_Raise +// + +void A_Raise(player_t *player, pspdef_t *psp) +{ + statenum_t newstate; + + psp->sy -= RAISESPEED; + demodbgprintf("Raise: %x\r\n", psp->sy); + if (psp->sy > WEAPONTOP) + return; + + psp->sy = WEAPONTOP; + + // The weapon has been raised all the way, + // so change to the ready state. + + newstate = weaponinfo[player->readyweapon].readystate; + + P_SetPsprite(player, ps_weapon, newstate); +} + +// Weapons now recoil, amount depending on the weapon. // phares +// // | +// The P_SetPsprite call in each of the weapon firing routines // V +// was moved here so the recoil could be synched with the +// muzzle flash, rather than the pressing of the trigger. +// The BFG delay caused this to be necessary. + +static void A_FireSomething(player_t *player, int adder) +{ + P_SetPsprite(player, ps_flash, weaponinfo[player->readyweapon].flashstate + adder); +} + +// +// A_GunFlash +// + +void A_GunFlash(player_t *player, pspdef_t *psp) +{ + P_SetMobjState(player->mo, S_PLAY_ATK2); + + A_FireSomething(player, 0); // phares +} + +// +// WEAPON ATTACKS +// + +// +// A_Punch +// + +void A_Punch(player_t *player, pspdef_t *psp) +{ + angle_t angle; + int t, slope, damage = (P_Random(__FILE__, __LINE__, __FUNCTION__) % 10 + 1) << 1; + + if (player->powers[pw_strength]) + damage *= 10; + + angle = player->mo->angle; + + // killough 5/5/98: remove dependence on order of evaluation: + t = P_Random(__FILE__, __LINE__, __FUNCTION__); + angle += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 18; + + /* killough 8/2/98: make autoaiming prefer enemies */ + if ((slope = P_AimLineAttack(player->mo, angle, MELEERANGE, MF_FRIEND), !_g->linetarget)) + slope = P_AimLineAttack(player->mo, angle, MELEERANGE, 0); + + P_LineAttack(player->mo, angle, MELEERANGE, slope, damage); + + if (!_g->linetarget) + return; + + S_StartSound(player->mo, sfx_punch); + + // turn to face target + + player->mo->angle = R_PointToAngle2(player->mo->x, player->mo->y, _g->linetarget->x, _g->linetarget->y); +} + +// +// A_Saw +// + +void A_Saw(player_t *player, pspdef_t *psp) +{ + int slope, damage = 2 * (P_Random(__FILE__, __LINE__, __FUNCTION__) % 10 + 1); + angle_t angle = player->mo->angle; + // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + angle += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 18; + + /* Use meleerange + 1 so that the puff doesn't skip the flash + * killough 8/2/98: make autoaiming prefer enemies */ + if ((slope = P_AimLineAttack(player->mo, angle, MELEERANGE + 1, MF_FRIEND), !_g->linetarget)) + slope = P_AimLineAttack(player->mo, angle, MELEERANGE + 1, 0); + + P_LineAttack(player->mo, angle, MELEERANGE + 1, slope, damage); + + if (!_g->linetarget) + { + S_StartSound(player->mo, sfx_sawful); + return; + } + + S_StartSound(player->mo, sfx_sawhit); + + // turn to face target + angle = R_PointToAngle2(player->mo->x, player->mo->y, _g->linetarget->x, _g->linetarget->y); + + if (angle - player->mo->angle > ANG180) + { + if (angle - player->mo->angle < -ANG90 / 20) + player->mo->angle = angle + ANG90 / 21; + else + player->mo->angle -= ANG90 / 20; + } + else + { + if (angle - player->mo->angle > ANG90 / 20) + player->mo->angle = angle - ANG90 / 21; + else + player->mo->angle += ANG90 / 20; + } + + player->mo->flags |= MF_JUSTATTACKED; +} + +// +// A_FireMissile +// + +void A_FireMissile(player_t *player, pspdef_t *psp) +{ + S_StartSound(player->mo, sfx_rlaunc); + player->ammo[weaponinfo[player->readyweapon].ammo]--; + P_SpawnPlayerMissile(player->mo, MT_ROCKET); +} + +// +// A_FireBFG +// + +void A_FireBFG(player_t *player, pspdef_t *psp) +{ + player->ammo[weaponinfo[player->readyweapon].ammo] -= BFGCELLS; + P_SpawnPlayerMissile(player->mo, MT_BFG); +} + +// +// A_FirePlasma +// + +void A_FirePlasma(player_t *player, pspdef_t *psp) +{ + S_StartSound(player->mo, sfx_plasma); + player->ammo[weaponinfo[player->readyweapon].ammo]--; + + A_FireSomething(player, P_Random(__FILE__, __LINE__, __FUNCTION__) & 1); // phares + P_SpawnPlayerMissile(player->mo, MT_PLASMA); +} + +// +// P_BulletSlope +// Sets a slope so a near miss is at aproximately +// the height of the intended target +// +static void P_BulletSlope(mobj_t *mo) +{ + angle_t an = mo->angle; // see which target is to be aimed at + + /* killough 8/2/98: make autoaiming prefer enemies */ + unsigned int mask = MF_FRIEND; + + do + { + _g->bulletslope = P_AimLineAttack(mo, an, 16 * 64 * FRACUNIT, mask); + if (!_g->linetarget) + _g->bulletslope = P_AimLineAttack(mo, an += 1 << 26, 16 * 64 * FRACUNIT, mask); + if (!_g->linetarget) + _g->bulletslope = P_AimLineAttack(mo, an -= 2 << 26, 16 * 64 * FRACUNIT, mask); + } while (mask && (mask = 0, !_g->linetarget)); /* killough 8/2/98 */ +} + +// +// P_GunShot +// + +static void P_GunShot(mobj_t *mo, boolean accurate) +{ + int damage = 5 * (P_Random(__FILE__, __LINE__, __FUNCTION__) % 3 + 1); + angle_t angle = mo->angle; + + if (!accurate) + { // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + angle += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 18; + } + + P_LineAttack(mo, angle, MISSILERANGE, _g->bulletslope, damage); +} + +// +// A_FirePistol +// + +void A_FirePistol(player_t *player, pspdef_t *psp) +{ + S_StartSound(player->mo, sfx_pistol); + + P_SetMobjState(player->mo, S_PLAY_ATK2); + player->ammo[weaponinfo[player->readyweapon].ammo]--; + + A_FireSomething(player, 0); // phares + P_BulletSlope(player->mo); + P_GunShot(player->mo, !player->refire); +} + +// +// A_FireShotgun +// + +void A_FireShotgun(player_t *player, pspdef_t *psp) +{ + int i; + + S_StartSound(player->mo, sfx_shotgn); + P_SetMobjState(player->mo, S_PLAY_ATK2); + + player->ammo[weaponinfo[player->readyweapon].ammo]--; + + A_FireSomething(player, 0); // phares + + P_BulletSlope(player->mo); + + for (i = 0; i < 7; i++) + P_GunShot(player->mo, false); +} + +// +// A_FireShotgun2 +// + +void A_FireShotgun2(player_t *player, pspdef_t *psp) +{ + int i; + + S_StartSound(player->mo, sfx_dshtgn); + P_SetMobjState(player->mo, S_PLAY_ATK2); + player->ammo[weaponinfo[player->readyweapon].ammo] -= 2; + + A_FireSomething(player, 0); // phares + + P_BulletSlope(player->mo); + + for (i = 0; i < 20; i++) + { + int damage = 5 * (P_Random(__FILE__, __LINE__, __FUNCTION__) % 3 + 1); + angle_t angle = player->mo->angle; + // killough 5/5/98: remove dependence on order of evaluation: + int t = P_Random(__FILE__, __LINE__, __FUNCTION__); + angle += (t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 19; + t = P_Random(__FILE__, __LINE__, __FUNCTION__); + P_LineAttack(player->mo, angle, MISSILERANGE, _g->bulletslope + ((t - P_Random(__FILE__, __LINE__, __FUNCTION__)) << 5), damage); + } +} + +// +// A_FireCGun +// + +void A_FireCGun(player_t *player, pspdef_t *psp) +{ + if (player->ammo[weaponinfo[player->readyweapon].ammo]) + S_StartSound(player->mo, sfx_pistol); + + if (!player->ammo[weaponinfo[player->readyweapon].ammo]) + return; + + P_SetMobjState(player->mo, S_PLAY_ATK2); + player->ammo[weaponinfo[player->readyweapon].ammo]--; + + A_FireSomething(player, psp->state - &states[S_CHAIN1]); // phares + + P_BulletSlope(player->mo); + + P_GunShot(player->mo, !player->refire); +} + +void A_Light0(player_t *player, pspdef_t *psp) +{ + player->extralight = 0; +} + +void A_Light1(player_t *player, pspdef_t *psp) +{ + player->extralight = 1; +} + +void A_Light2(player_t *player, pspdef_t *psp) +{ + player->extralight = 2; +} + +// +// A_BFGSpray +// Spawn a BFG explosion on every monster in view +// + +void A_BFGSpray(mobj_t *mo) +{ + int i; + + for (i = 0; i < 40; i++) // offset angles from its attack angle + { + int j, damage; + angle_t an = mo->angle - ANG90 / 2 + ANG90 / 40 * i; + + // mo->target is the originator (player) of the missile + + // killough 8/2/98: make autoaiming prefer enemies + if ((P_AimLineAttack(getTarget(mo), an, 16 * 64 * FRACUNIT, MF_FRIEND), !_g->linetarget)) + P_AimLineAttack(getTarget(mo), an, 16 * 64 * FRACUNIT, 0); + + if (!_g->linetarget) + continue; + + P_SpawnMobj(_g->linetarget->x, _g->linetarget->y, _g->linetarget->z + (getMobjHeight(_g->linetarget) >> 2), MT_EXTRABFG); + + for (damage = j = 0; j < 15; j++) + damage += (P_Random(__FILE__, __LINE__, __FUNCTION__) & 7) + 1; + + P_DamageMobj(_g->linetarget, getTarget(mo), getTarget(mo), damage); + } +} + +// +// A_BFGsound +// + +void A_BFGsound(player_t *player, pspdef_t *psp) +{ + S_StartSound(player->mo, sfx_bfg); +} + +// +// P_SetupPsprites +// Called at start of level for each player. +// + +void P_SetupPsprites(player_t *player) +{ + int i; + + // remove all psprites + for (i = 0; i < NUMPSPRITES; i++) + player->psprites[i].state = NULL; + + // spawn the gun + player->pendingweapon = player->readyweapon; + P_BringUpWeapon(player); +} + +// +// P_MovePsprites +// Called every tic by player thinking routine. +// + +void P_MovePsprites(player_t *player) +{ + pspdef_t *psp = player->psprites; + int i; + + // a null state means not active + // drop tic count and possibly change state + // a -1 tic count never changes + + for (i = 0; i < NUMPSPRITES; i++, psp++) + if (psp->state && psp->tics != -1 && !--psp->tics) + P_SetPsprite(player, i, psp->state->nextstate); + + player->psprites[ps_flash].sx = player->psprites[ps_weapon].sx; + player->psprites[ps_flash].sy = player->psprites[ps_weapon].sy; +} diff --git a/doom/src/pdoom/Doom/source/p_setup.c b/doom/src/pdoom/Doom/source/p_setup.c new file mode 100644 index 0000000..c793646 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_setup.c @@ -0,0 +1,929 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Do all the WAD I/O, get map description, + * set up initial state and misc. LUTs. + * + * next-hack: heavily modified load functions to support caching of WAD-wise + * and level-wise constant data to flash, saving tons of RAM. + *-----------------------------------------------------------------------------*/ + +#include + +#include "doomstat.h" +#include "m_bbox.h" +#include "g_game.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_things.h" +#include "p_maputl.h" +#include "p_map.h" +#include "p_setup.h" +#include "p_spec.h" +#include "p_tick.h" +#include "p_enemy.h" +#include "s_sound.h" +#include "lprintf.h" //jff 10/6/98 for debug outputs +#include "v_video.h" + +#include "global_data.h" +#include "r_sky.h" +#include "i_spi_support.h" +#include "pwm_audio.h" +extern patch_t * cachedColumnOffsetDataPatch; +// +// P_LoadVertexes +// +// killough 5/3/98: reformatted, cleaned up +// +static void P_LoadVertexes(int lump) +{ + // TODO: remove _g->vertexes and _g->numvertexes and use the values in p_wad_level_flash_data instead + // Determine number of lumps: + // total lump length / vertex record length. + _g->numvertexes = W_LumpLength(lump) / sizeof(vertex_t); + p_wad_level_flash_data->numvertex = W_LumpLength(lump) / sizeof(vertex_t); + // Allocate zone memory for buffer. + p_wad_level_flash_data->vertexes = writeLumpToFlashRegion(lump, FLASH_LEVEL_REGION, true); + _g->vertexes = p_wad_level_flash_data->vertexes; + +} + +// +// P_LoadSegs +// +// killough 5/3/98: reformatted, cleaned up + +static void P_LoadSegs(int lump) +{ + // TODO: remove _g->numsegs and _g->segs and use the values in p_wad_level_flash_data instead + _g->numsegs = W_LumpLength(lump) / sizeof(seg_t); + p_wad_level_flash_data->numsegs = W_LumpLength(lump) / sizeof(seg_t); + p_wad_level_flash_data->segs = writeLumpToFlashRegion(lump, FLASH_LEVEL_REGION, true); + _g->segs = (const seg_t*) p_wad_level_flash_data->segs; + +// if (!_g->numsegs) +// I_Error("P_LoadSegs: no segs in level"); +} + +// +// P_LoadSubsectors +// +// killough 5/3/98: reformatted, cleaned up + +static void P_LoadSubsectors(int lump) +{ + /* cph 2006/07/29 - make data a const mapsubsector_t *, so the loop below is simpler & gives no constness warnings */ + const mapsubsector_t *data; + int i; + + _g->numsubsectors = W_LumpLength(lump) / sizeof(mapsubsector_t); + _g->subsectors = Z_Calloc(_g->numsubsectors, sizeof(subsector_t), PU_LEVEL, 0); + data = (const mapsubsector_t*) W_CacheLumpNum(lump); + + if ((!data) || (!_g->numsubsectors)) + I_Error("P_LoadSubsectors: no subsectors in level"); + + spiFlashSetAddress((uint32_t) data); + for (i = 0; i < _g->numsubsectors; i++) + { + mapsubsector_t subsector; + spiFlashGetData(&subsector, sizeof(subsector)); + //_g->subsectors[i].numlines = (unsigned short)SHORT(data[i].numsegs ); + //_g->subsectors[i].firstline = (unsigned short)SHORT(data[i].firstseg); + _g->subsectors[i].numlines = (unsigned short) SHORT(subsector.numsegs); + _g->subsectors[i].firstline = (unsigned short) SHORT(subsector.firstseg); + } +} + +#ifdef PDM_SSFLASH +/* Paramix 1.7.3 test17: the subsectors (8 bytes each, 4000 on the big Sigil maps = 32 KB) no longer in RAM: they are + * read only after loading, so they go straight to the level data in flash, in pieces, with their sector already found + * (as P_GroupLines did; the segs are loaded first for that) */ +static void P_LoadSubsectorsFlash(int lump) +{ + const mapsubsector_t *data; + _g->numsubsectors = W_LumpLength(lump) / sizeof(mapsubsector_t); + data = (const mapsubsector_t*) W_CacheLumpNum(lump); + if ((!data) || (!_g->numsubsectors)) + I_Error("P_LoadSubsectors: no subsectors in level"); + const int CH = 64; + subsector_t *buf = Z_Malloc(CH * sizeof(subsector_t), PU_STATIC, 0), *first = NULL; + for (int i0 = 0; i0 < _g->numsubsectors; i0 += CH) + { + int n = _g->numsubsectors - i0 < CH ? _g->numsubsectors - i0 : CH; + for (int k = 0; k < n; k++) + { + mapsubsector_t ms; + spiFlashSetAddress((uint32_t) &data[i0 + k]); + spiFlashGetData(&ms, sizeof(ms)); + subsector_t *ss = &buf[k]; + memset(ss, 0, sizeof(*ss)); + ss->numlines = (unsigned short) SHORT(ms.numsegs); + ss->firstline = (unsigned short) SHORT(ms.firstseg); + const seg_t *seg = &_g->segs[ss->firstline]; + ss->sector = NULL; + for (int j = 0; j < ss->numlines; j++, seg++) + if (seg->sidenum != NO_INDEX) + { + ss->sector = &_g->sectors[_g->sides[seg->sidenum].sector_num]; + break; + } + if (ss->sector == NULL) + I_Error("P_GroupLines: Subsector a part of no sector!\n"); + } + subsector_t *fa = writeBufferToFlashRegion(buf, n * sizeof(subsector_t), FLASH_LEVEL_REGION, true); + if (!first) + first = fa; + } + Z_Free(buf); + _g->subsectors = first; +} +#endif + +// +// P_LoadSectors +// +// killough 5/3/98: reformatted, cleaned up + +static void P_LoadSectors(int lump) +{ + const byte *data; // cph - const* + int i; + + _g->numsectors = W_LumpLength(lump) / sizeof(mapsector_t); + _g->sectors = Z_Calloc(_g->numsectors, sizeof(sector_t), PU_LEVEL, 0); + data = W_CacheLumpNum(lump); // cph - wad lump handling updated + + spiFlashSetAddress((uint32_t) data); + + for (i = 0; i < _g->numsectors; i++) + { +#if 0 + sector_t *ss = _g->sectors + i; + + const mapsector_t *ms = (const mapsector_t *) data + i; + + ss->floorheight = SHORT(ms->floorheight)<ceilingheight = SHORT(ms->ceilingheight)<floorpic = R_FlatNumForName(ms->floorpic); + ss->ceilingpic = R_FlatNumForName(ms->ceilingpic); + + ss->lightlevel = SHORT(ms->lightlevel); + ss->special = SHORT(ms->special); + ss->oldspecial = SHORT(ms->special); + ss->tag = SHORT(ms->tag); + + ss->thinglist_sptr = 0; + ss->touching_thinglist_sptr = 0; // phares 3/14/98 +#else + sector_t *ss = _g->sectors + i; + // we must set the address each time, as it is changed by R_FlatNumForName + spiFlashSetAddress((uint32_t) data + i * sizeof(mapsector_t)); + mapsector_t ms; + spiFlashGetData(&ms, sizeof(mapsector_t)); + ss->floorheight = SHORT(ms.floorheight) << FRACBITS; + ss->ceilingheight = SHORT(ms.ceilingheight) << FRACBITS; + // this will change the spi address. + ss->floorpic = R_FlatNumForName(ms.floorpic); + ss->ceilingpic = R_FlatNumForName(ms.ceilingpic); + + ss->lightlevel = SHORT(ms.lightlevel); + ss->special = SHORT(ms.special); + ss->oldspecial = SHORT(ms.special); + ss->tag = SHORT(ms.tag); + + ss->thinglist_sptr = 0; + ss->touching_thinglist_sptr = 0; // phares 3/14/98 +#endif + } +} + +// +// P_LoadNodes +// +// killough 5/3/98: reformatted, cleaned up + +static void P_LoadNodes(int lump) +{ + // TODO: remove numnodes and nodes and use p_wad_level + numnodes = W_LumpLength(lump) / sizeof(mapnode_t); + p_wad_level_flash_data->numnodes = W_LumpLength(lump) / sizeof(mapnode_t); + // + p_wad_level_flash_data->nodes = writeLumpToFlashRegion(lump, FLASH_LEVEL_REGION, true); + nodes = p_wad_level_flash_data->nodes; // cph - wad lump handling updated + + if ((!nodes) || (!numnodes)) + { + // allow trivial maps + if (_g->numsubsectors == 1) + lprintf(LO_INFO, "P_LoadNodes: trivial map (no nodes, one subsector)\n"); + else + I_Error("P_LoadNodes: no nodes in level"); + } +} + +/* + * P_LoadThings + * + * killough 5/3/98: reformatted, cleaned up + * cph 2001/07/07 - don't write into the lump cache, especially non-idepotent + * changes like byte order reversals. Take a copy to edit. + */ + +static void P_LoadThings(int lump) +{ + int i, numthings = W_LumpLength(lump) / sizeof(mapthing_t); + const mapthing_t *data = W_CacheLumpNum(lump); +// + if ((!data) || (!numthings)) + I_Error("P_LoadThings: no things in level"); + printf("Num things %d\r\n", numthings); + _g->totalstatic = 0; + spiFlashSetAddress((uint32_t) data); + for (i = 0; i < numthings; i++) + { + + // mapthing_t mt = data[i]; + mapthing_t mt; + spiFlashGetData(&mt, sizeof(mt)); + mt.x = SHORT(mt.x); + mt.y = SHORT(mt.y); + mt.angle = SHORT(mt.angle); + mt.type = SHORT(mt.type); + mt.options = SHORT(mt.options); + + if (!P_IsDoomnumAllowed(mt.type)) + continue; + + // Do spawn all other stuff. + P_SpawnMapThing(&mt); + } + printf("Num static things %d\r\n", _g->totalstatic); + +} + +// +// P_LoadLineDefs +// Also counts secret lines for intermissions. +// ^^^ +// ??? killough ??? +// Does this mean secrets used to be linedef-based, rather than sector-based? +// +// killough 4/4/98: split into two functions, to allow sidedef overloading +// +// killough 5/3/98: reformatted, cleaned up + +static void P_LoadLineDefs(int lump) +{ + int i; + // TODO: remove _g->numlines and _g->lines and use the values in p_wad_level_flash_data instead + _g->numlines = W_LumpLength(lump) / sizeof(line_t); + p_wad_level_flash_data->numlines = W_LumpLength(lump) / sizeof(line_t); + p_wad_level_flash_data->lines = writeLumpToFlashRegion(lump, FLASH_LEVEL_REGION, true); + _g->lines = p_wad_level_flash_data->lines; + + _g->linedata = Z_Calloc(_g->numlines, sizeof(linedata_t), PU_LEVEL, 0); + + for (i = 0; i < _g->numlines; i++) + { + _g->linedata[i].special = _g->lines[i].const_special; + } +} + +// +// P_LoadSideDefs +// killough 4/4/98: delay using texture names until +// after linedefs are loaded, to allow overloading. +// killough 5/3/98: reformatted, cleaned up + +static void P_LoadSideDefs(int lump) +{ + // 2021-02-13 next-hack + // It is stupid to copy everything to ram. therefore we use everything which is in ROM + // except texture offset, which needs to be copied to ram (it might change). + // In this way, we save 12 bytes for each side def. + // now we use only ROM. It is up to the wad to have correct data. + p_wad_level_flash_data->numsides = W_LumpLength(lump) / sizeof(mapsidedef_t); + _g->numsides = p_wad_level_flash_data->numsides; + _g->textureoffsets = Z_Calloc(_g->numsides, sizeof(*_g->textureoffsets), PU_LEVEL, 0); + // TODO: remove _g->numsides and _g->sides and use the values in p_wad_level_flash_data instead. + p_wad_level_flash_data->sides = writeLumpToFlashRegion(lump, FLASH_LEVEL_REGION, true); + _g->sides = (side_t*) p_wad_level_flash_data->sides; + int i; + int n = 0, ma = 0, mi = 0; + for (i = 0; i < _g->numsides; i++) + { + register side_t *sd = _g->sides + i; + _g->textureoffsets[i] = sd->textureoffset; + // nh: to count how much we can squeeze + if (n < sd->midtexture) + n = sd->midtexture; + if (n < sd->toptexture) + n = sd->toptexture; + if (n < sd->bottomtexture) + n = sd->bottomtexture; + if (ma < sd->textureoffset) + ma = sd->textureoffset; + if (mi > sd->textureoffset) + mi = sd->textureoffset; + } + // 2021-03-13: forgot that switches have changeable textures... + // is a line special? Then we must reserve a memory location to store its texture numbers + // first count how many specials we have + int l = 0; + for (i = 0; i < _g->numlines; i++) + { + if (_g->lines[i].const_special) + { + l++; + } + } + // then allocate spaces + _g->linesChangeableTextureIndex = Z_Calloc(_g->numlines, sizeof(*_g->linesChangeableTextureIndex), PU_LEVEL, 0); + _g->switch_texture_top = Z_Calloc(l, sizeof(*_g->switch_texture_top), PU_LEVEL, 0); + _g->switch_texture_mid = Z_Calloc(l, sizeof(*_g->switch_texture_mid), PU_LEVEL, 0); + _g->switch_texture_bot = Z_Calloc(l, sizeof(*_g->switch_texture_bot), PU_LEVEL, 0); + l = 0; + for (i = 0; i < _g->numlines; i++) + { + if (_g->lines[i].const_special) + { + // set the changeableTextureIndex + _g->linesChangeableTextureIndex[i] = l; + int side0num = _g->lines[i].sidenum[0]; + side_t *sd = _g->sides + side0num; + // set texture index + _g->switch_texture_top[l] = sd->toptexture; + _g->switch_texture_mid[l] = sd->midtexture; + _g->switch_texture_bot[l] = sd->bottomtexture; + // point to next slot + l++; + } + } + printf("Number of textures %d, max offset %d, min offset %d. Special %d\r\n", n, ma, mi, l); +} + +static void P_LoadSideDefsTextures() +{ + // 2021-03-23 next-hack + // This function is called after we stored all the important level data. Here we try to cache (in flash) as many textures as possible + // _g->sides, _g->numsides shall be already initialized by P_LoadSideDefs. + int i; + uint32_t size = 0; + int32_t *texSizes = Z_Malloc(sizeof(*texSizes) * _g->numtextures, PU_STATIC, NULL); + memset(texSizes, 0, sizeof(*texSizes) * _g->numtextures); + for (i = 0; i < _g->numsides; i++) + { + // TODO: instead of loading finding everytime TEXTUREx lumps by name we could cache it + // it would save some time. + register side_t *sd = _g->sides + i; + if (!texSizes[sd->midtexture]) + { + texSizes[sd->midtexture] = getTextureStructSize(sd->midtexture); + size += texSizes[sd->midtexture]; + } + if (!texSizes[sd->bottomtexture]) + { + texSizes[sd->bottomtexture] = getTextureStructSize(sd->bottomtexture); + size += texSizes[sd->bottomtexture]; + } + if (!texSizes[sd->toptexture]) + { + texSizes[sd->toptexture] = getTextureStructSize(sd->toptexture); + size += texSizes[sd->toptexture]; + } + } + Z_Free(texSizes); + printf(">>>Size before %d\r\n", size); + for (i = 0; i < _g->numsides; i++) + { + register side_t *sd = _g->sides + i; + R_GetTexture(sd->midtexture, true, &size); + R_GetTexture(sd->toptexture, true, &size); + R_GetTexture(sd->bottomtexture, true, &size); + } + printf(">>>Size after %d\r\n", size); +} + +// +// jff 10/6/98 +// New code added to speed up calculation of internal blockmap +// Algorithm is order of nlines*(ncols+nrows) not nlines*ncols*nrows +// + +#define blkshift 7 /* places to shift rel position for cell num */ +#define blkmask ((1<0 +// jff 10/12/98 0 ok with + 1 in rows,cols + +typedef struct linelist_t // type used to list lines in each block +{ + long num; + struct linelist_t *next; +} linelist_t; + +// +// P_LoadBlockMap +// +// killough 3/1/98: substantially modified to work +// towards removing blockmap limit (a wad limitation) +// +// killough 3/30/98: Rewritten to remove blockmap limit, +// though current algorithm is brute-force and unoptimal. +// + +static void P_LoadBlockMap(int lump) +{ + + // TODO: remove _g->blockmaplump and use p_wad_level_flash_data->blockmaplump instead. + p_wad_level_flash_data->blockmaplump = writeLumpToFlashRegion(lump, FLASH_LEVEL_REGION, true); + _g->blockmaplump = p_wad_level_flash_data->blockmaplump; + + _g->bmaporgx = _g->blockmaplump[0] << FRACBITS; + _g->bmaporgy = _g->blockmaplump[1] << FRACBITS; + _g->bmapwidth = _g->blockmaplump[2]; + _g->bmapheight = _g->blockmaplump[3]; + + // clear out mobj chains - CPhipps - use calloc + _g->blocklinks_sptrs = Z_Calloc(_g->bmapwidth * _g->bmapheight, sizeof(*_g->blocklinks_sptrs), PU_LEVEL, 0); + + _g->blockmap = _g->blockmaplump + 4; +} + +// +// P_LoadReject - load the reject table, padding it if it is too short +// totallines must be the number returned by P_GroupLines() +// an underflow will be padded with zeroes, or a doom.exe z_zone header +// +// this function incorporates e6y's RejectOverrunAddInt code: +// e6y: REJECT overrun emulation code +// It's emulated successfully if the size of overflow no more than 16 bytes. +// No more desync on teeth-32.wad\teeth-32.lmp. +// http://www.doomworld.com/vb/showthread.php?s=&threadid=35214 + +static void P_LoadReject(int lumpnum) +{ + int lump = lumpnum + ML_REJECT; + p_wad_level_flash_data->rejectmatrix = writeLumpToFlashRegion(lump, FLASH_LEVEL_REGION, true); + _g->rejectmatrix = p_wad_level_flash_data->rejectmatrix; +} + +// +// P_GroupLines +// Builds sector line lists and subsector sector numbers. +// Finds block bounding boxes for sectors. +// +// killough 5/3/98: reformatted, cleaned up +// cph 18/8/99: rewritten to avoid O(numlines * numsectors) section +// It makes things more complicated, but saves seconds on big levels +// figgi 09/18/00 -- adapted for gl-nodes + +// cph - convenient sub-function +static void P_AddLineToSector(const line_t *li, sector_t *sector) +{ + //sector->lines[sector->linecount++] = li; + getSectorLines(sector)[sector->linecount++] = li; // getPackedAddress(li); +} +// modified to return totallines (needed by P_LoadReject) +static int P_GroupLines(void) +{ + register const line_t *li; + register sector_t *sector; + int i, j, total = _g->numlines; + + // figgi +#ifdef PDM_SSFLASH + if (0) /* the subsectors are in flash with their sector already (P_LoadSubsectorsFlash) */ +#endif + for (i = 0; i < _g->numsubsectors; i++) + { + const seg_t *seg = &_g->segs[_g->subsectors[i].firstline]; + _g->subsectors[i].sector = NULL; + for (j = 0; j < _g->subsectors[i].numlines; j++) + { + if (seg->sidenum != NO_INDEX) + { + _g->subsectors[i].sector = &_g->sectors[_g->sides[seg->sidenum].sector_num]; + break; + } + seg++; + } + if (_g->subsectors[i].sector == NULL) + I_Error("P_GroupLines: Subsector a part of no sector!\n"); + } + + // count number of lines in each sector + for (i = 0, li = _g->lines; i < _g->numlines; i++, li++) + { + LN_FRONTSECTOR(li)->linecount++; + if (LN_BACKSECTOR(li) && LN_BACKSECTOR(li) != LN_FRONTSECTOR(li)) + { + LN_BACKSECTOR(li)->linecount++; + total++; + } + } +#ifdef PDM_GROUPCHUNK + /* Paramix 1.7.3 test17: big maps (one-humanity, Sigil) ran out of memory here: the line lists of all sectors were + * built in one RAM buffer (4 bytes per line side) before going to flash. Now in pieces of up to 2 KB: the sectors of + * a piece take their lines (all lines are looked at for each piece), the piece goes to flash right after the one + * before, so the flash holds the same lists in the same order as before. */ + { + const int CH = 512; /* pointers per piece */ + line_t **buf = Z_Malloc(CH * sizeof(line_t*), PU_STATIC, 0); + line_t **flashFirst = NULL; + int s0 = 0; + while (s0 < _g->numsectors) + { + int s1 = s0, n = 0; + while (s1 < _g->numsectors && (n + _g->sectors[s1].linecount <= CH || s1 == s0)) + n += _g->sectors[s1++].linecount; + if (n > CH) + { /* one sector with more lines than a piece: bigger buffer for it */ + Z_Free(buf); + buf = Z_Malloc(n * sizeof(line_t*), PU_STATIC, 0); + } + { /* the lists of this piece in the buffer, in the order of the lines (as before) */ + line_t **pos = buf; + for (int q = s0; q < s1; q++) { _g->sectors[q].lines_ppptr = getPackedAddress(pos); pos += _g->sectors[q].linecount; _g->sectors[q].linecount = 0; } + sector_t *lo = &_g->sectors[s0], *hi = &_g->sectors[s1]; + for (i = 0, li = _g->lines; i < _g->numlines; i++, li++) + { + sector_t *f = LN_FRONTSECTOR(li), *b = LN_BACKSECTOR(li); + if (f >= lo && f < hi) P_AddLineToSector(li, f); + if (b && b != f && b >= lo && b < hi) P_AddLineToSector(li, b); + } + } + line_t **fa = writeBufferToFlashRegion(buf, n * sizeof(line_t*), FLASH_LEVEL_REGION, true); + if (!flashFirst) + flashFirst = fa; + for (int q = s0; q < s1; q++) + { + _g->sectors[q].lines_ppptr = getPackedAddress(fa); + fa += _g->sectors[q].linecount; + } + if (n > CH) + { + Z_Free(buf); + buf = Z_Malloc(CH * sizeof(line_t*), PU_STATIC, 0); + } + s0 = s1; + } + Z_Free(buf); + (void) flashFirst; + } +#else +// now we have the total number of lines. + line_t **linebuffer = Z_Malloc(total * sizeof(line_t*), PU_STATIC, 0); + line_t **lineBufferArray = linebuffer; + { // allocate line tables for each sector + +// packedAddress_t *linebuffer_ppptr = Z_Malloc(total*sizeof(packedAddress_t), PU_LEVEL, 0); + // e6y: REJECT overrun emulation code + // moved to P_LoadReject + + for (i = 0, sector = _g->sectors; i < _g->numsectors; i++, sector++) + { + sector->lines_ppptr = getPackedAddress(linebuffer); + linebuffer += sector->linecount; + //linebuffer_ppptr += sector->linecount; + sector->linecount = 0; + } + } + + // Enter those lines + for (i = 0, li = _g->lines; i < _g->numlines; i++, li++) + { + P_AddLineToSector(li, LN_FRONTSECTOR(li)); + if (LN_BACKSECTOR(li) && LN_BACKSECTOR(li) != LN_FRONTSECTOR(li)) + P_AddLineToSector(li, LN_BACKSECTOR(li)); + } + + // store buffer to flash + line_t **flashArrayAddress = writeBufferToFlashRegion(lineBufferArray, total * sizeof(line_t*), FLASH_LEVEL_REGION, true); + // now we need to update again all the pointers + for (i = 0, sector = _g->sectors; i < _g->numsectors; i++, sector++) + { + sector->lines_ppptr = getPackedAddress(flashArrayAddress); + flashArrayAddress += sector->linecount; + } + // now we can free the buffer + Z_Free(lineBufferArray); +#endif + // calculate the box that contains each sector. + // sound will be generated from the center of this box. + for (i = 0, sector = _g->sectors; i < _g->numsectors; i++, sector++) + { + fixed_t bbox[4]; + M_ClearBox(bbox); + + for (int l = 0; l < sector->linecount; l++) + { + const line_t *pline = getSectorLineByIndex(sector, l); + + M_AddToBox(bbox, pline->v1.x, pline->v1.y); + M_AddToBox(bbox, pline->v2.x, pline->v2.y); + } + sector->soundorg.x = bbox[BOXRIGHT] / 2 + bbox[BOXLEFT] / 2; + sector->soundorg.y = bbox[BOXTOP] / 2 + bbox[BOXBOTTOM] / 2; + } + + return total; // this value is needed by the reject overrun emulation code +} + +void P_FreeLevelData() +{ + R_ResetPlanes(); + + Z_FreeTags(PU_LEVEL, PU_PURGELEVEL - 1); + + Z_Free(_g->braintargets); + _g->braintargets = NULL; + _g->numbraintargets_alloc = _g->numbraintargets = 0; +} + +// +// P_SetupLevel +// +// killough 5/3/98: reformatted, cleaned up +void P_SetupLevel(int episode, int map, int playermask, skill_t skill) +{ + // + disableWirelessAudio(); + // + cachedColumnOffsetDataPatch = NULL; + // every boot, we need to refresh level data, to be sure that corrupted data + // due to resets or power down wont screw up everything. + static boolean levelDataAlreadyInitialized = false; + char lumpname[9]; + int lumpnum; + printf("Setup level\r\n"); + _g->totallive = _g->totalkills = _g->totalitems = _g->totalsecret = _g->wminfo.maxfrags = 0; + _g->wminfo.partime = 180; + + _g->player.killcount = 0; + _g->player.secretcount = 0; + _g->player.itemcount = 0; + + // Initial height of PointOfView will be set by player think. + _g->player.viewz = 1; + + // Make sure all sounds are stopped before Z_FreeTags. + S_Start(); + P_FreeLevelData(); + + // now that we have freed level data, we can allocate new temporary buffers. + initLumpPtrTable(); + + // let's check if we are changing level + boolean differentLevel = false; + if (levelDataAlreadyInitialized) // && (uint32_t) p_wad_immutable_flash_data->levelData > (uint32_t) p_wad_immutable_flash_data && p_wad_immutable_flash_data->levelData < FLASH_SIZE) + { + if (p_wad_level_flash_data->map != map || p_wad_level_flash_data->episode != episode || false == levelDataAlreadyInitialized) + { + differentLevel = true; + } + } + else + { + differentLevel = true; + } + if (differentLevel) + { + // reset texture pointers, so that they will be reloaded again. + memset(textures, 0, _g->numtextures * sizeof *textures); + } + else + { + // reset only those pointer in ram + for (int i = 0; i < _g->numtextures; i++) + { + if (isRamPtr(textures[i])) + { + textures[i] = 0; + } + } + } + /* if (false == levelDataAlreadyInitialized || p_wad_level_flash_data->map != map || p_wad_level_flash_data->episode != episode || false == levelDataAlreadyInitialized) + { + differentLevel = true; + }*/ + p_wad_level_flash_data = initLevelFlashRegion(); + p_wad_level_flash_data->map = map; + p_wad_level_flash_data->episode = episode; + //Load the sky texture. + // Set the sky map. + // First thing, we have a dummy sky texture name, + // a flat. The data is in the WAD only because + // we look for an actual index, instead of simply + // setting one. + + _g->skyflatnum = R_FlatNumForName( SKYFLATNAME); + + P_InitThinkers(); + + // find map name + if (_g->gamemode == commercial) + { + sprintf(lumpname, "MAP%02d", map); // killough 1/24/98: simplify + } + else + { + sprintf(lumpname, "E%dM%d", episode, map); // killough 1/24/98: simplify + } + + lumpnum = W_GetNumForName(lumpname); + + _g->leveltime = 0; + _g->totallive = 0; + + printf("P_LoadVertexes\r\n"); + // vertex in flash + P_LoadVertexes(lumpnum + ML_VERTEXES); + // sectors: in RAM + printf("P_LoadSectors\r\n"); + P_LoadSectors(lumpnum + ML_SECTORS); + printf("P_LoadLineDefs\r\n"); + // Line Defs, stored in flash, but some info in RAM + P_LoadLineDefs(lumpnum + ML_LINEDEFS); + // Side defs in flash but some info in RAM + printf("P_LoadSideDefs\r\n"); + P_LoadSideDefs(lumpnum + ML_SIDEDEFS); + printf("P_LoadBlockMap\r\n"); + // block ram in MAP + P_LoadBlockMap(lumpnum + ML_BLOCKMAP); + printf("P_LoadSubsectors\r\n"); + // subsectors in ram +#ifdef PDM_SSFLASH + P_LoadSegs(lumpnum + ML_SEGS); // first: the subsectors find their sector through them + P_LoadSubsectorsFlash(lumpnum + ML_SSECTORS); +#else + P_LoadSubsectors(lumpnum + ML_SSECTORS); +#endif + printf("P_LoadNodes\r\n"); + // nodes in flash + P_LoadNodes(lumpnum + ML_NODES); // 0k + printf("P_LoadSegs\r\n"); + // segs in flash +#ifndef PDM_SSFLASH + P_LoadSegs(lumpnum + ML_SEGS); // 0k +#endif + // line in ram + printf("P_GroupLines\r\n"); + P_GroupLines(); + printf("P_LoadReject\r\n"); + // reject loading and underflow padding separated out into new function + // P_GroupLines modified to return a number the underflow padding needs + // P_grouplines in falash + P_LoadReject(lumpnum); // 0k + + // Note: you don't need to clear player queue slots -- + // a much simpler fix is in g_game.c -- killough 10/98 + + /* cph - reset all multiplayer starts */ + memset(_g->playerstarts, 0, sizeof(_g->playerstarts)); + + for (int i = 0; i < MAXPLAYERS; i++) + _g->player.mo = NULL; + + P_MapStart(); + + P_LoadThings(lumpnum + ML_THINGS); + + if (_g->playeringame && !_g->player.mo) + { + I_Error("P_SetupLevel: missing player start\n"); + } + + // killough 3/26/98: Spawn icon landings: + if (_g->gamemode == commercial) + P_SpawnBrainTargets(); + + // set up world state + P_SpawnSpecials(); // 1k + + P_MapEnd(); + + // caching, different level + if (differentLevel) + { + lprintf(LO_INFO, "P_InitPicAnims"); + P_InitPicAnims(); + + // now cache sky + // DOOM determines the sky texture to be used + // depending on the current episode, and the game version. + if (_g->gamemode == commercial) + // || gamemode == pack_tnt //jff 3/27/98 sorry guys pack_tnt,pack_plut + // || gamemode == pack_plut) //aren't gamemodes, this was matching retail + { + _g->skytexture = R_LoadTextureByName("SKY3", true); + if (_g->gamemap < 12) + _g->skytexture = R_LoadTextureByName("SKY1", true); + else if (_g->gamemap < 21) + _g->skytexture = R_LoadTextureByName("SKY2", true); + } + else + //jff 3/27/98 and lets not forget about DOOM and Ultimate DOOM huh? + switch (_g->gameepisode) + { + case 1: + _g->skytexture = R_LoadTextureByName("SKY1", true); + break; + case 2: + _g->skytexture = R_LoadTextureByName("SKY2", true); + break; + case 3: + _g->skytexture = R_LoadTextureByName("SKY3", true); + break; + case 4: // Special Edition sky + _g->skytexture = R_LoadTextureByName("SKY4", true); + break; + } //jff 3/27/98 end sky setting fix + + for (int j = 0; j < _g->numsectors; j++) + { + int picnum; +#if PRINT_ADDRESSES + void *addr; + picnum = _g->sectors[j].ceilingpic + _g->firstflat; + addr = getAddressOrCacheLumpNum(picnum, true, FLASH_LEVEL_REGION); + printf("Cache C flat num %d 0x%02x\r\n",picnum, (uint32_t) addr); + picnum = _g->sectors[j].floorpic + _g->firstflat; + addr = getAddressOrCacheLumpNum(picnum, true, FLASH_LEVEL_REGION); + printf("Cache F flat num %d 0x%02x\r\n",picnum, (uint32_t) addr); +#else + picnum = _g->sectors[j].ceilingpic + _g->firstflat; + getAddressOrCacheLumpNum(picnum, true, FLASH_LEVEL_REGION); + picnum = _g->sectors[j].floorpic + _g->firstflat; + getAddressOrCacheLumpNum(picnum, true, FLASH_LEVEL_REGION); +#endif + } + // cache as many texture and flats as possible; + P_LoadSideDefsTextures(); + } + // now cache every pointer so that in game we do not need to save to flash. + for (int i = 0; i < _g->numlumps; i++) + { + getAddressOrCacheLumpNum(i, false, FLASH_LEVEL_REGION); + } + p_wad_level_flash_data->lumpAddressTable = storeLumpArrayToFlash(differentLevel); + p_wad_level_flash_data = storeLevelValues(differentLevel); + // + levelDataAlreadyInitialized = true; + // enable back audio + restoreWirelessAudio(); +} + +// +// P_Init +// +void P_Init(void) +{ + lprintf(LO_INFO, "P_InitSwitchList"); + P_InitSwitchList(); +// moved to setup level +// lprintf(LO_INFO, "P_InitPicAnims"); +// P_InitPicAnims(); + + lprintf(LO_INFO, "R_InitSprites"); + R_InitSprites(sprnames); +} diff --git a/doom/src/pdoom/Doom/source/p_sight.c b/doom/src/pdoom/Doom/source/p_sight.c new file mode 100644 index 0000000..26f17ef --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_sight.c @@ -0,0 +1,114 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * LineOfSight/Visibility checks, uses REJECT Lookup Table. + * + * next-hack: modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "r_main.h" +#include "p_map.h" +#include "p_maputl.h" +#include "p_setup.h" +#include "m_bbox.h" +#include "lprintf.h" + +#include "global_data.h" + +// +// P_CheckSight +// Returns true +// if a straight line between t1 and t2 is unobstructed. +// Uses REJECT. +// +// killough 4/20/98: cleaned up, made to use new LOS struct +los_t los; // cph - made static + +boolean P_CrossBSPNode(int bspnum); + +boolean P_CheckSight(mobj_t *t1, mobj_t *t2) +{ + const sector_t *s1 = getMobjSubsector(t1)->sector; + const sector_t *s2 = getMobjSubsector(t2)->sector; + int pnum = (s1 - _g->sectors) * _g->numsectors + (s2 - _g->sectors); + + // First check for trivial rejection. + // Determine subsector entries in REJECT table. + // + // Check in REJECT table. + + if (_g->rejectmatrix[pnum >> 3] & (1 << (pnum & 7))) // can't possibly be connected + { + return false; + } + /* killough 11/98: shortcut for melee situations + * same subsector? obviously visible + * cph - compatibility optioned for demo sync, cf HR06-UV.LMP */ + if (t1->subsector_sptr == t2->subsector_sptr) + return true; + + // An unobstructed LOS is possible. + // Now look from eyes of t1 to any part of t2. + + _g->validcount++; + + los.topslope = (los.bottomslope = t2->z - (los.sightzstart = t1->z + getMobjHeight(t1) - (getMobjHeight(t1) >> 2))) + getMobjHeight(t2); + los.strace.dx = (los.t2x = t2->x) - (los.strace.x = t1->x); + los.strace.dy = (los.t2y = t2->y) - (los.strace.y = t1->y); + + if (t1->x > t2->x) + los.bbox[BOXRIGHT] = t1->x, los.bbox[BOXLEFT] = t2->x; + else + los.bbox[BOXRIGHT] = t2->x, los.bbox[BOXLEFT] = t1->x; + + if (t1->y > t2->y) + los.bbox[BOXTOP] = t1->y, los.bbox[BOXBOTTOM] = t2->y; + else + { + los.bbox[BOXTOP] = t2->y, los.bbox[BOXBOTTOM] = t1->y; + } + los.maxz = INT_MAX; + los.minz = INT_MIN; + + // the head node is the last node output + return P_CrossBSPNode(numnodes - 1); +} diff --git a/doom/src/pdoom/Doom/source/p_spec.c b/doom/src/pdoom/Doom/source/p_spec.c new file mode 100644 index 0000000..0c4fbb4 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_spec.c @@ -0,0 +1,2409 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * -Loads and initializes texture and flat animation sequences + * -Implements utility functions for all linedef/sector special handlers + * -Dispatches walkover and gun line triggers + * -Initializes and implements special sector types + * -Implements donut linedef triggers + * -Initializes and implements BOOM linedef triggers for + * Scrollers/Conveyors + * Friction + * Wind/Current + * + * next-hack: modified code to work with short pointers. + * added caching to flash support. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "p_spec.h" +#include "p_tick.h" +#include "p_setup.h" +#include "m_random.h" +#include "d_englsh.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_data.h" +#include "p_maputl.h" +#include "p_map.h" +#include "g_game.h" +#include "p_inter.h" +#include "s_sound.h" +#include "sounds.h" +#include "m_bbox.h" // phares 3/20/98 +#include "r_plane.h" +#include "lprintf.h" + +#include "global_data.h" +#define DOOM2SUPPORT +// +// P_InitPicAnims +// + +// Floor/ceiling animation sequences, +// defined by first and last frame, +// i.e. the flat (64x64 tile) name to +// be used. +// The full animation sequence is given +// using all the flats between the start +// and end entry, in the order found in +// the WAD file. +// +const animdef_t animdefs[] = +{ + { false, "NUKAGE3", "NUKAGE1", 8 }, + { false, "FWATER4", "FWATER1", 8 }, + { false, "SWATER4", "SWATER1", 8 }, + { false, "LAVA4", "LAVA1", 8 }, + { false, "BLOOD3", "BLOOD1", 8 }, +#ifdef DOOM2SUPPORT + // DOOM II flat animations. + {false, "RROCK08", "RROCK05", 8}, + {false, "SLIME04", "SLIME01", 8}, + {false, "SLIME08", "SLIME05", 8}, + {false, "SLIME12", "SLIME09", 8}, + + {true, "BLODGR4", "BLODGR1", 8}, + {true, "SLADRIP3", "SLADRIP1", 8}, + + {true, "BLODRIP4", "BLODRIP1", 8}, + {true, "FIREWALL", "FIREWALA", 8}, + {true, "GSTFONT3", "GSTFONT1", 8}, + {true, "FIRELAVA", "FIRELAV3", 8}, + {true, "FIREMAG3", "FIREMAG1", 8}, + {true, "FIREBLU2", "FIREBLU1", 8}, + {true, "ROCKRED3", "ROCKRED1", 8}, + + {true, "BFALL4", "BFALL1", 8}, + {true, "SFALL4", "SFALL1", 8}, + {true, "WFALL4", "WFALL1", 8}, + {true, "DBRAIN4", "DBRAIN1", 8}, +#endif + { -1 } +}; + +// killough 3/7/98: Initialize generalized scrolling +static void P_SpawnScrollers(void); + +// +// P_InitPicAnims +// +// Load the table of animation definitions, checking for existence of +// the start and end of each frame. If the start doesn't exist the sequence +// is skipped, if the last doesn't exist, BOOM exits. +// +// Wall/Flat animation sequences, defined by name of first and last frame, +// The full animation sequence is given using all lumps between the start +// and end entry, in the order found in the WAD file. +// +// This routine modified to read its data from a predefined lump or +// PWAD lump called ANIMATED rather than a static table in this module to +// allow wad designers to insert or modify animation sequences. +// +// Lump format is an array of byte packed animdef_t structures, terminated +// by a structure with istexture == -1. The lump can be generated from a +// text source file using SWANTBLS.EXE, distributed with the BOOM utils. +// The standard list of switches and animations is contained in the example +// source text file DEFSWANI.DAT also in the BOOM util distribution. +// +// +void P_InitPicAnims(void) +{ + int i; + + // Init animation + _g->lastanim = _g->anims; + for (i = 0; animdefs[i].istexture != -1; i++) + { + if (animdefs[i].istexture) + { + // different episode ? + if (R_CheckTextureNumForName(animdefs[i].startname) == -1) + continue; + _g->lastanim->picnum = R_CheckTextureNumForName(animdefs[i].endname); + _g->lastanim->basepic = R_CheckTextureNumForName(animdefs[i].startname); + /* 2021-10-23 next-hack: we are not caching to flash these anims. Too complicated and expensive. + for (int j = 0; j < _g->lastanim->picnum; j++) + { + printf("Getting text %d\r\n", j); + R_GetTexture(_g->lastanim->basepic + j, true, NULL); + }*/ + } + else + { + if (W_CheckNumForName(animdefs[i].startname) == -1) + continue; + + _g->lastanim->picnum = R_FlatNumForName(animdefs[i].endname); + _g->lastanim->basepic = R_FlatNumForName(animdefs[i].startname); + // 2021/04/02 next-hack: store also animation flats. + for (int picnum = _g->lastanim->basepic; + picnum <= _g->lastanim->picnum; picnum++) + { + getAddressOrCacheLumpNum(picnum + _g->firstflat, true, FLASH_LEVEL_REGION); + } + + } + + _g->lastanim->istexture = animdefs[i].istexture; + _g->lastanim->numpics = _g->lastanim->picnum - _g->lastanim->basepic + 1; + + if (_g->lastanim->numpics < 2) + I_Error("P_InitPicAnims: bad cycle from %s to %s", animdefs[i].startname, animdefs[i].endname); + + _g->lastanim->speed = animdefs[i].speed; + + _g->lastanim++; + } +} + +/////////////////////////////////////////////////////////////// +// +// Linedef and Sector Special Implementation Utility Functions +// +/////////////////////////////////////////////////////////////// + +// +// getSide() +// +// Will return a side_t* +// given the number of the current sector, +// the line number, and the side (0/1) that you want. +// +// Note: if side=1 is specified, it must exist or results undefined +// +side_t* getSide(int currentSector, int line, int side) +{ + return &_g->sides[(getSectorLineByIndex(&_g->sectors[currentSector], line))->sidenum[side]]; +} + +// +// getSector() +// +// Will return a sector_t* +// given the number of the current sector, +// the line number and the side (0/1) that you want. +// +// Note: if side=1 is specified, it must exist or results undefined +// +static sector_t* getSector(int currentSector, int line, int side) +{ + return &_g->sectors[_g->sides[(getSectorLineByIndex(&_g->sectors[currentSector], line))->sidenum[side]].sector_num]; +} + +// +// twoSided() +// +// Given the sector number and the line number, +// it will tell you whether the line is two-sided or not. +// +// modified to return actual two-sidedness rather than presence +// of 2S flag unless compatibility optioned +// +int twoSided(int sector, int line) +{ + //jff 1/26/98 return what is actually needed, whether the line + //has two sidedefs, rather than whether the 2S flag is set + + return (getSectorLineByIndex(&_g->sectors[sector], line))->sidenum[1] != NO_INDEX; +} + +// +// getNextSector() +// +// Return sector_t * of sector next to current across line. +// +// Note: returns NULL if not two-sided line, or both sides refer to sector +// +sector_t* getNextSector(const line_t *line, sector_t *sec) +{ + + if (LN_FRONTSECTOR(line) == sec) + { + if (LN_BACKSECTOR(line) != sec) + return LN_BACKSECTOR(line); //jff 5/3/98 don't retn sec unless compatibility + else + // fixes an intra-sector line breaking functions + return NULL; // like floor->highest floor + } + return LN_FRONTSECTOR(line); +} + +// +// P_FindLowestFloorSurrounding() +// +// Returns the fixed point value of the lowest floor height +// in the sector passed or its surrounding sectors. +// +fixed_t P_FindLowestFloorSurrounding(sector_t *sec) +{ + int i; + const line_t *check; + sector_t *other; + fixed_t floor = sec->floorheight; + + for (i = 0; i < sec->linecount; i++) + { + check = getSectorLineByIndex(sec, i); + other = getNextSector(check, sec); + + if (!other) + continue; + + if (other->floorheight < floor) + floor = other->floorheight; + } + return floor; +} + +// +// P_FindHighestFloorSurrounding() +// +// Passed a sector, returns the fixed point value of the largest +// floor height in the surrounding sectors, not including that passed +// +// NOTE: if no surrounding sector exists -32000*FRACUINT is returned +// if compatibility then -500*FRACUNIT is the smallest return possible +// +fixed_t P_FindHighestFloorSurrounding(sector_t *sec) +{ + int i; + const line_t *check; + sector_t *other; + fixed_t floor = -500 * FRACUNIT; + + //jff 1/26/98 Fix initial value for floor to not act differently + //in sections of wad that are below -500 units + floor = -32000 * FRACUNIT; // in height calculations + + for (i = 0; i < sec->linecount; i++) + { + check = getSectorLineByIndex(sec, i); + other = getNextSector(check, sec); + + if (!other) + continue; + + if (other->floorheight > floor) + floor = other->floorheight; + } + return floor; +} + +// +// P_FindNextHighestFloor() +// +// Passed a sector and a floor height, returns the fixed point value +// of the smallest floor height in a surrounding sector larger than +// the floor height passed. If no such height exists the floorheight +// passed is returned. +// +// Rewritten by Lee Killough to avoid fixed array and to be faster +// +fixed_t P_FindNextHighestFloor(sector_t *sec, int currentheight) +{ + sector_t *other; + int i; + + for (i = 0; i < sec->linecount; i++) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->floorheight > currentheight) + { + int height = other->floorheight; + while (++i < sec->linecount) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->floorheight < height && other->floorheight > currentheight) + height = other->floorheight; + return height; + } + /* cph - my guess at doom v1.2 - 1.4beta compatibility here. + * If there are no higher neighbouring sectors, Heretic just returned + * heightlist[0] (local variable), i.e. noise off the stack. 0 is right for + * RETURN01 E1M2, so let's take that. */ + return (currentheight); +} + +// +// P_FindNextLowestFloor() +// +// Passed a sector and a floor height, returns the fixed point value +// of the largest floor height in a surrounding sector smaller than +// the floor height passed. If no such height exists the floorheight +// passed is returned. +// +// jff 02/03/98 Twiddled Lee's P_FindNextHighestFloor to make this +// +fixed_t P_FindNextLowestFloor(sector_t *sec, int currentheight) +{ + sector_t *other; + int i; + + for (i = 0; i < sec->linecount; i++) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->floorheight < currentheight) + { + int height = other->floorheight; + while (++i < sec->linecount) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->floorheight > height && other->floorheight < currentheight) + height = other->floorheight; + return height; + } + return currentheight; +} + +// +// P_FindNextLowestCeiling() +// +// Passed a sector and a ceiling height, returns the fixed point value +// of the largest ceiling height in a surrounding sector smaller than +// the ceiling height passed. If no such height exists the ceiling height +// passed is returned. +// +// jff 02/03/98 Twiddled Lee's P_FindNextHighestFloor to make this +// +fixed_t P_FindNextLowestCeiling(sector_t *sec, int currentheight) +{ + sector_t *other; + int i; + + for (i = 0; i < sec->linecount; i++) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->ceilingheight < currentheight) + { + int height = other->ceilingheight; + while (++i < sec->linecount) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->ceilingheight > height && other->ceilingheight < currentheight) + height = other->ceilingheight; + return height; + } + return currentheight; +} + +// +// P_FindNextHighestCeiling() +// +// Passed a sector and a ceiling height, returns the fixed point value +// of the smallest ceiling height in a surrounding sector larger than +// the ceiling height passed. If no such height exists the ceiling height +// passed is returned. +// +// jff 02/03/98 Twiddled Lee's P_FindNextHighestFloor to make this +// +fixed_t P_FindNextHighestCeiling(sector_t *sec, int currentheight) +{ + sector_t *other; + int i; + + for (i = 0; i < sec->linecount; i++) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->ceilingheight > currentheight) + { + int height = other->ceilingheight; + while (++i < sec->linecount) + if ((other = getNextSector(getSectorLineByIndex(sec, i), sec)) && other->ceilingheight < height && other->ceilingheight > currentheight) + height = other->ceilingheight; + return height; + } + return currentheight; +} + +// +// P_FindLowestCeilingSurrounding() +// +// Passed a sector, returns the fixed point value of the smallest +// ceiling height in the surrounding sectors, not including that passed +// +// NOTE: if no surrounding sector exists 32000*FRACUINT is returned +// but if compatibility then INT_MAX is the return +// +fixed_t P_FindLowestCeilingSurrounding(sector_t *sec) +{ + int i; + const line_t *check; + sector_t *other; + fixed_t height = INT_MAX; + + /* jff 3/12/98 avoid ovf in height calculations */ + height = 32000 * FRACUNIT; + + for (i = 0; i < sec->linecount; i++) + { + check = getSectorLineByIndex(sec, i); + other = getNextSector(check, sec); + + if (!other) + continue; + + if (other->ceilingheight < height) + height = other->ceilingheight; + } + return height; +} + +// +// P_FindHighestCeilingSurrounding() +// +// Passed a sector, returns the fixed point value of the largest +// ceiling height in the surrounding sectors, not including that passed +// +// NOTE: if no surrounding sector exists -32000*FRACUINT is returned +// but if compatibility then 0 is the smallest return possible +// +fixed_t P_FindHighestCeilingSurrounding(sector_t *sec) +{ + int i; + const line_t *check; + sector_t *other; + fixed_t height = 0; + + /* jff 1/26/98 Fix initial value for floor to not act differently + * in sections of wad that are below 0 units + * jff 3/12/98 avoid ovf in height calculations */ + height = -32000 * FRACUNIT; + + for (i = 0; i < sec->linecount; i++) + { + check = getSectorLineByIndex(sec, i); + other = getNextSector(check, sec); + + if (!other) + continue; + + if (other->ceilingheight > height) + height = other->ceilingheight; + } + return height; +} + +// +// P_FindShortestTextureAround() +// +// Passed a sector number, returns the shortest lower texture on a +// linedef bounding the sector. +// +// Note: If no lower texture exists 32000*FRACUNIT is returned. +// but if compatibility then INT_MAX is returned +// +// jff 02/03/98 Add routine to find shortest lower texture +// +fixed_t P_FindShortestTextureAround(int secnum) +{ + int minsize = INT_MAX; + side_t *side; + int i; + sector_t *sec = &_g->sectors[secnum]; + + minsize = 32000 << FRACBITS; //jff 3/13/98 prevent overflow in height calcs + + for (i = 0; i < sec->linecount; i++) + { + if (twoSided(secnum, i)) + { + side = getSide(secnum, i, 0); + if (side->bottomtexture > 0) //jff 8/14/98 texture 0 is a placeholder + if (textureheight[side->bottomtexture] < minsize) + minsize = textureheight[side->bottomtexture]; + side = getSide(secnum, i, 1); + if (side->bottomtexture > 0) //jff 8/14/98 texture 0 is a placeholder + if (textureheight[side->bottomtexture] < minsize) + minsize = textureheight[side->bottomtexture]; + } + } + return minsize; +} + +// +// P_FindShortestUpperAround() +// +// Passed a sector number, returns the shortest upper texture on a +// linedef bounding the sector. +// +// Note: If no upper texture exists 32000*FRACUNIT is returned. +// but if compatibility then INT_MAX is returned +// +// jff 03/20/98 Add routine to find shortest upper texture +// +fixed_t P_FindShortestUpperAround(int secnum) +{ + int minsize = INT_MAX; + side_t *side; + int i; + sector_t *sec = &_g->sectors[secnum]; + + minsize = 32000 << FRACBITS; //jff 3/13/98 prevent overflow + // in height calcs + for (i = 0; i < sec->linecount; i++) + { + if (twoSided(secnum, i)) + { + side = getSide(secnum, i, 0); + if (side->toptexture > 0) //jff 8/14/98 texture 0 is a placeholder + if (textureheight[side->toptexture] < minsize) + minsize = textureheight[side->toptexture]; + side = getSide(secnum, i, 1); + if (side->toptexture > 0) //jff 8/14/98 texture 0 is a placeholder + if (textureheight[side->toptexture] < minsize) + minsize = textureheight[side->toptexture]; + } + } + return minsize; +} + +// +// P_FindModelFloorSector() +// +// Passed a floor height and a sector number, return a pointer to a +// a sector with that floor height across the lowest numbered two sided +// line surrounding the sector. +// +// Note: If no sector at that height bounds the sector passed, return NULL +// +// jff 02/03/98 Add routine to find numeric model floor +// around a sector specified by sector number +// jff 3/14/98 change first parameter to plain height to allow call +// from routine not using floormove_t +// +sector_t* P_FindModelFloorSector(fixed_t floordestheight, int secnum) +{ + int i; + sector_t *sec = NULL; + int linecount; + + sec = &_g->sectors[secnum]; //jff 3/2/98 woops! better do this + //jff 5/23/98 don't disturb sec->linecount while searching + // but allow early exit in old demos + linecount = sec->linecount; + for (i = 0; i < (linecount); i++) + { + if (twoSided(secnum, i)) + { + if (&_g->sectors[getSide(secnum, i, 0)->sector_num] - _g->sectors == secnum) + sec = getSector(secnum, i, 1); + else + sec = getSector(secnum, i, 0); + + if (sec->floorheight == floordestheight) + return sec; + } + } + return NULL; +} + +// +// P_FindModelCeilingSector() +// +// Passed a ceiling height and a sector number, return a pointer to a +// a sector with that ceiling height across the lowest numbered two sided +// line surrounding the sector. +// +// Note: If no sector at that height bounds the sector passed, return NULL +// +// jff 02/03/98 Add routine to find numeric model ceiling +// around a sector specified by sector number +// used only from generalized ceiling types +// jff 3/14/98 change first parameter to plain height to allow call +// from routine not using ceiling_t +// +sector_t* P_FindModelCeilingSector(fixed_t ceildestheight, int secnum) +{ + int i; + sector_t *sec = NULL; + int linecount; + + sec = &_g->sectors[secnum]; //jff 3/2/98 woops! better do this + //jff 5/23/98 don't disturb sec->linecount while searching + // but allow early exit in old demos + linecount = sec->linecount; + for (i = 0; i < (linecount); i++) + { + if (twoSided(secnum, i)) + { + if (&_g->sectors[getSide(secnum, i, 0)->sector_num] - _g->sectors == secnum) + sec = getSector(secnum, i, 1); + else + sec = getSector(secnum, i, 0); + + if (sec->ceilingheight == ceildestheight) + return sec; + } + } + return NULL; +} + +// +// RETURN NEXT SECTOR # THAT LINE TAG REFERS TO +// +int P_FindSectorFromLineTag(const line_t *line, int start) +{ + int i; + + for (i = start + 1; i < _g->numsectors; i++) + { + if (_g->sectors[i].tag == line->tag) + return i; + } + + return -1; +} + +// killough 4/16/98: Same thing, only for linedefs + +int P_FindLineFromLineTag(const line_t *line, int start) +{ + + int i; + + for (i = start + 1; i < _g->numlines; i++) + { + if (_g->lines[i].tag == line->tag) + return i; + } + + return -1; +} + +// Hash the sector tags across the sectors and linedefs. +static void P_InitTagLists(void) +{ + +} + +// +// P_FindMinSurroundingLight() +// +// Passed a sector and a light level, returns the smallest light level +// in a surrounding sector less than that passed. If no smaller light +// level exists, the light level passed is returned. +// +int P_FindMinSurroundingLight(sector_t *sector, int max) +{ + int i; + int min; + const line_t *line; + sector_t *check; + + min = max; + for (i = 0; i < sector->linecount; i++) + { + line = getSectorLineByIndex(sector, i); + check = getNextSector(line, sector); + + if (!check) + continue; + + if (check->lightlevel < min) + min = check->lightlevel; + } + return min; +} + +// +// P_CanUnlockGenDoor() +// +// Passed a generalized locked door linedef and a player, returns whether +// the player has the keys necessary to unlock that door. +// +// Note: The linedef passed MUST be a generalized locked door type +// or results are undefined. +// +// jff 02/05/98 routine added to test for unlockability of +// generalized locked doors +// +boolean P_CanUnlockGenDoor(const line_t *line, player_t *player) +{ + // does this line special distinguish between skulls and keys? + int skulliscard = (LN_SPECIAL(line) & LockedNKeys) >> LockedNKeysShift; + + // determine for each case of lock type if player's keys are adequate + switch ((LN_SPECIAL(line) & LockedKey) >> LockedKeyShift) + { + case AnyKey: + if (!player->cards[it_redcard] && !player->cards[it_redskull] && !player->cards[it_bluecard] && !player->cards[it_blueskull] && !player->cards[it_yellowcard] && !player->cards[it_yellowskull]) + { + player->message = PD_ANY; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + case RCard: + if (!player->cards[it_redcard] && (!skulliscard || !player->cards[it_redskull])) + { + player->message = skulliscard ? PD_REDK : PD_REDC; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + case BCard: + if (!player->cards[it_bluecard] && (!skulliscard || !player->cards[it_blueskull])) + { + player->message = skulliscard ? PD_BLUEK : PD_BLUEC; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + case YCard: + if (!player->cards[it_yellowcard] && (!skulliscard || !player->cards[it_yellowskull])) + { + player->message = skulliscard ? PD_YELLOWK : PD_YELLOWC; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + case RSkull: + if (!player->cards[it_redskull] && (!skulliscard || !player->cards[it_redcard])) + { + player->message = skulliscard ? PD_REDK : PD_REDS; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + case BSkull: + if (!player->cards[it_blueskull] && (!skulliscard || !player->cards[it_bluecard])) + { + player->message = skulliscard ? PD_BLUEK : PD_BLUES; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + case YSkull: + if (!player->cards[it_yellowskull] && (!skulliscard || !player->cards[it_yellowcard])) + { + player->message = skulliscard ? PD_YELLOWK : PD_YELLOWS; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + case AllKeys: + if (!skulliscard && (!player->cards[it_redcard] || !player->cards[it_redskull] || !player->cards[it_bluecard] || !player->cards[it_blueskull] || !player->cards[it_yellowcard] || !player->cards[it_yellowskull])) + { + player->message = PD_ALL6; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + if (skulliscard && ((!player->cards[it_redcard] && !player->cards[it_redskull]) || (!player->cards[it_bluecard] && !player->cards[it_blueskull]) || (!player->cards[it_yellowcard] && !player->cards[it_yellowskull]))) + { + player->message = PD_ALL3; // Ty 03/27/98 - externalized + S_StartSound(player->mo, sfx_oof); // killough 3/20/98 + return false; + } + break; + } + return true; +} + +// +// P_SectorActive() +// +// Passed a linedef special class (floor, ceiling, lighting) and a sector +// returns whether the sector is already busy with a linedef special of the +// same class. If old demo compatibility true, all linedef special classes +// are the same. +// +// jff 2/23/98 added to prevent old demos from +// succeeding in starting multiple specials on one sector +// +boolean PUREFUNC P_SectorActive(special_e t, const sector_t *sec) +{ + switch (t) + // return whether thinker of same type is active + { + case floor_special: + return sec->floordata_sptr != 0; + case ceiling_special: + return sec->ceilingdata_sptr != 0; + case lighting_special: + return false; + } + return true; // don't know which special, must be active, shouldn't be here +} + +// +// P_CheckTag() +// +// Passed a line, returns true if the tag is non-zero or the line special +// allows no tag without harm. If compatibility, all linedef specials are +// allowed to have zero tag. +// +// Note: Only line specials activated by walkover, pushing, or shooting are +// checked by this routine. +// +// jff 2/27/98 Added to check for zero tag allowed for regular special types +// +int P_CheckTag(const line_t *line) +{ + /* tag not zero, allowed, or + * killough 11/98: compatibility option */ + if (line->tag) + return 1; + + switch (LN_SPECIAL(line)) + { + case 1: // Manual door specials + case 26: + case 27: + case 28: + case 31: + case 32: + case 33: + case 34: + case 117: + case 118: + + case 139: // Lighting specials + case 170: + case 79: + case 35: + case 138: + case 171: + case 81: + case 13: + case 192: + case 169: + case 80: + case 12: + case 194: + case 173: + case 157: + case 104: + case 193: + case 172: + case 156: + case 17: + + case 195: // Thing teleporters + case 174: + case 97: + case 39: + case 126: + case 125: + case 210: + case 209: + case 208: + case 207: + + case 11: // Exits + case 52: + case 197: + case 51: + case 124: + case 198: + + case 48: // Scrolling walls + case 85: + return 1; // zero tag allowed + + default: + break; + } + return 0; // zero tag not allowed +} + +// +// P_IsSecret() +// +// Passed a sector, returns if the sector secret type is still active, i.e. +// secret type is set and the secret has not yet been obtained. +// +// jff 3/14/98 added to simplify checks for whether sector is secret +// in automap and other places +// +boolean PUREFUNC P_IsSecret(const sector_t *sec) +{ + return (sec->special == 9 || (sec->special & SECRET_MASK)); +} + +// +// P_WasSecret() +// +// Passed a sector, returns if the sector secret type is was active, i.e. +// secret type was set and the secret has been obtained already. +// +// jff 3/14/98 added to simplify checks for whether sector is secret +// in automap and other places +// +boolean PUREFUNC P_WasSecret(const sector_t *sec) +{ + return (sec->oldspecial == 9 || (sec->oldspecial & SECRET_MASK)); +} + +////////////////////////////////////////////////////////////////////////// +// +// Events +// +// Events are operations triggered by using, crossing, +// or shooting special lines, or by timed thinkers. +// +///////////////////////////////////////////////////////////////////////// + +// +// P_CrossSpecialLine - Walkover Trigger Dispatcher +// +// Called every time a thing origin is about +// to cross a line with a non 0 special, whether a walkover type or not. +// +// jff 02/12/98 all W1 lines were fixed to check the result from the EV_ +// function before clearing the special. This avoids losing the function +// of the line, should the sector already be active when the line is +// crossed. Change is qualified by demo_compatibility. +// +// CPhipps - take a line_t pointer instead of a line number, as in MBF +void P_CrossSpecialLine(const line_t *line, int side, mobj_t *thing) +{ + int ok; + + // Things that should never trigger lines + if (!thing->player_sptr) + { + // Things that should NOT trigger specials... + switch (thing->type) + { + case MT_ROCKET: + case MT_PLASMA: + case MT_BFG: + case MT_TROOPSHOT: + case MT_HEADSHOT: + case MT_BRUISERSHOT: + return; + + default: + break; + } + } + + // pointer to line function is NULL by default, set non-null if + // line special is walkover generalized linedef type + int (*linefunc)(const line_t *line) = NULL; + + // check each range of generalized linedefs + if ((unsigned) LN_SPECIAL(line) >= GenEnd) + { + // Out of range for GenFloors + } + else if ((unsigned) LN_SPECIAL(line) >= GenFloorBase) + { + if (!thing->player_sptr) + if ((LN_SPECIAL(line) & FloorChange) || !(LN_SPECIAL(line) & FloorModel)) + return; // FloorModel is "Allow Monsters" if FloorChange is 0 + if (!line->tag) //jff 2/27/98 all walk generalized types require tag + return; + linefunc = EV_DoGenFloor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenCeilingBase) + { + if (!thing->player_sptr) + if ((LN_SPECIAL(line) & CeilingChange) || !(LN_SPECIAL(line) & CeilingModel)) + return; // CeilingModel is "Allow Monsters" if CeilingChange is 0 + if (!line->tag) //jff 2/27/98 all walk generalized types require tag + return; + linefunc = EV_DoGenCeiling; + } + else if ((unsigned) LN_SPECIAL(line) >= GenDoorBase) + { + if (!thing->player_sptr) + { + if (!(LN_SPECIAL(line) & DoorMonster)) + return; // monsters disallowed from this door + if (line->flags & ML_SECRET) // they can't open secret doors either + return; + } + if (!line->tag) //3/2/98 move outside the monster check + return; + linefunc = EV_DoGenDoor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenLockedBase) + { + if (!thing->player_sptr) + return; // monsters disallowed from unlocking doors + if (((LN_SPECIAL(line) & TriggerType) == WalkOnce) || ((LN_SPECIAL(line) & TriggerType) == WalkMany)) + { //jff 4/1/98 check for being a walk type before reporting door type + if (!P_CanUnlockGenDoor(line, getMobjPlayer(thing))) + return; + } + else + return; + linefunc = EV_DoGenLockedDoor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenLiftBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & LiftMonster)) + return; // monsters disallowed + if (!line->tag) //jff 2/27/98 all walk generalized types require tag + return; + linefunc = EV_DoGenLift; + } + else if ((unsigned) LN_SPECIAL(line) >= GenStairsBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & StairMonster)) + return; // monsters disallowed + if (!line->tag) //jff 2/27/98 all walk generalized types require tag + return; + linefunc = EV_DoGenStairs; + } + + if (linefunc) // if it was a valid generalized type + switch ((LN_SPECIAL(line) & TriggerType) >> TriggerTypeShift) + { + case WalkOnce: + if (linefunc(line)) + LN_SPECIAL(line) = 0; // clear special if a walk once type + return; + case WalkMany: + linefunc(line); + return; + default: // if not a walk type, do nothing here + return; + } + + if (!thing->player_sptr) + { + ok = 0; + switch (LN_SPECIAL(line)) + { + case 39: // teleport trigger + case 97: // teleport retrigger + case 125: // teleport monsteronly trigger + case 126: // teleport monsteronly retrigger + case 4: // raise door + case 10: // plat down-wait-up-stay trigger + case 88: // plat down-wait-up-stay retrigger + //jff 3/5/98 add ability of monsters etc. to use teleporters + case 208: //silent thing teleporters + case 207: + case 243: //silent line-line teleporter + case 244: //jff 3/6/98 make fit within DCK's 256 linedef types + case 262: //jff 4/14/98 add monster only + case 263: //jff 4/14/98 silent thing,line,line rev types + case 264: //jff 4/14/98 plus player/monster silent line + case 265: // reversed types + case 266: + case 267: + case 268: + case 269: + ok = 1; + break; + } + if (!ok) + return; + } + + if (!P_CheckTag(line)) //jff 2/27/98 disallow zero tag on some types + return; + + // Dispatch on the line special value to the line's action routine + // If a once only function, and successful, clear the line special + + switch (LN_SPECIAL(line)) + { + // Regular walk once triggers + + case 2: + // Open Door + if (EV_DoDoor(line, dopen)) + LN_SPECIAL(line) = 0; + break; + + case 3: + // Close Door + if (EV_DoDoor(line, dclose)) + LN_SPECIAL(line) = 0; + break; + + case 4: + // Raise Door + if (EV_DoDoor(line, normal)) + LN_SPECIAL(line) = 0; + break; + + case 5: + // Raise Floor + if (EV_DoFloor(line, raiseFloor)) + LN_SPECIAL(line) = 0; + break; + + case 6: + // Fast Ceiling Crush & Raise + if (EV_DoCeiling(line, fastCrushAndRaise)) + LN_SPECIAL(line) = 0; + break; + + case 8: + // Build Stairs + if (EV_BuildStairs(line, build8)) + LN_SPECIAL(line) = 0; + break; + + case 10: + // PlatDownWaitUp + if (EV_DoPlat(line, downWaitUpStay, 0)) + LN_SPECIAL(line) = 0; + break; + + case 12: + // Light Turn On - brightest near + if (EV_LightTurnOn(line, 0)) + LN_SPECIAL(line) = 0; + break; + + case 13: + // Light Turn On 255 + if (EV_LightTurnOn(line, 255)) + LN_SPECIAL(line) = 0; + break; + + case 16: + // Close Door 30 + if (EV_DoDoor(line, close30ThenOpen)) + LN_SPECIAL(line) = 0; + break; + + case 17: + // Start Light Strobing + if (EV_StartLightStrobing(line)) + LN_SPECIAL(line) = 0; + break; + + case 19: + // Lower Floor + if (EV_DoFloor(line, lowerFloor)) + LN_SPECIAL(line) = 0; + break; + + case 22: + // Raise floor to nearest height and change texture + if (EV_DoPlat(line, raiseToNearestAndChange, 0)) + LN_SPECIAL(line) = 0; + break; + + case 25: + // Ceiling Crush and Raise + if (EV_DoCeiling(line, crushAndRaise)) + LN_SPECIAL(line) = 0; + break; + + case 30: + // Raise floor to shortest texture height + // on either side of lines. + if (EV_DoFloor(line, raiseToTexture)) + LN_SPECIAL(line) = 0; + break; + + case 35: + // Lights Very Dark + if (EV_LightTurnOn(line, 35)) + LN_SPECIAL(line) = 0; + break; + + case 36: + // Lower Floor (TURBO) + if (EV_DoFloor(line, turboLower)) + LN_SPECIAL(line) = 0; + break; + + case 37: + // LowerAndChange + if (EV_DoFloor(line, lowerAndChange)) + LN_SPECIAL(line) = 0; + break; + + case 38: + // Lower Floor To Lowest + if (EV_DoFloor(line, lowerFloorToLowest)) + LN_SPECIAL(line) = 0; + break; + + case 39: + // TELEPORT! //jff 02/09/98 fix using up with wrong side crossing + if (EV_Teleport(line, side, thing)) + LN_SPECIAL(line) = 0; + break; + + case 40: + // RaiseCeilingLowerFloor + if (EV_DoCeiling(line, raiseToHighest)) + LN_SPECIAL(line) = 0; + break; + + case 44: + // Ceiling Crush + if (EV_DoCeiling(line, lowerAndCrush)) + LN_SPECIAL(line) = 0; + break; + + case 52: + // EXIT! + // killough 10/98: prevent zombies from exiting levels + if (!(getMobjPlayer(thing) && getMobjPlayer(thing)->health <= 0)) + G_ExitLevel(); + break; + + case 53: + // Perpetual Platform Raise + if (EV_DoPlat(line, perpetualRaise, 0)) + LN_SPECIAL(line) = 0; + break; + + case 54: + // Platform Stop + if (EV_StopPlat(line)) + LN_SPECIAL(line) = 0; + break; + + case 56: + // Raise Floor Crush + if (EV_DoFloor(line, raiseFloorCrush)) + LN_SPECIAL(line) = 0; + break; + + case 57: + // Ceiling Crush Stop + if (EV_CeilingCrushStop(line)) + LN_SPECIAL(line) = 0; + break; + + case 58: + // Raise Floor 24 + if (EV_DoFloor(line, raiseFloor24)) + LN_SPECIAL(line) = 0; + break; + + case 59: + // Raise Floor 24 And Change + if (EV_DoFloor(line, raiseFloor24AndChange)) + LN_SPECIAL(line) = 0; + break; + + case 100: + // Build Stairs Turbo 16 + if (EV_BuildStairs(line, turbo16)) + LN_SPECIAL(line) = 0; + break; + + case 104: + // Turn lights off in sector(tag) + if (EV_TurnTagLightsOff(line)) + LN_SPECIAL(line) = 0; + break; + + case 108: + // Blazing Door Raise (faster than TURBO!) + if (EV_DoDoor(line, blazeRaise)) + LN_SPECIAL(line) = 0; + break; + + case 109: + // Blazing Door Open (faster than TURBO!) + if (EV_DoDoor(line, blazeOpen)) + LN_SPECIAL(line) = 0; + break; + + case 110: + // Blazing Door Close (faster than TURBO!) + if (EV_DoDoor(line, blazeClose)) + LN_SPECIAL(line) = 0; + break; + + case 119: + // Raise floor to nearest surr. floor + if (EV_DoFloor(line, raiseFloorToNearest)) + LN_SPECIAL(line) = 0; + break; + + case 121: + // Blazing PlatDownWaitUpStay + if (EV_DoPlat(line, blazeDWUS, 0)) + LN_SPECIAL(line) = 0; + break; + + case 124: + // Secret EXIT + // killough 10/98: prevent zombies from exiting levels + // CPhipps - change for lxdoom's compatibility handling + if (!(getMobjPlayer(thing) && getMobjPlayer(thing)->health <= 0)) + G_SecretExitLevel(); + break; + + case 125: + // TELEPORT MonsterONLY + if (!thing->player_sptr && (EV_Teleport(line, side, thing))) + LN_SPECIAL(line) = 0; + break; + + case 130: + // Raise Floor Turbo + if (EV_DoFloor(line, raiseFloorTurbo)) + LN_SPECIAL(line) = 0; + break; + + case 141: + // Silent Ceiling Crush & Raise + if (EV_DoCeiling(line, silentCrushAndRaise)) + LN_SPECIAL(line) = 0; + break; + + // Regular walk many retriggerable + + case 72: + // Ceiling Crush + EV_DoCeiling(line, lowerAndCrush); + break; + + case 73: + // Ceiling Crush and Raise + EV_DoCeiling(line, crushAndRaise); + break; + + case 74: + // Ceiling Crush Stop + EV_CeilingCrushStop(line); + break; + + case 75: + // Close Door + EV_DoDoor(line, dclose); + break; + + case 76: + // Close Door 30 + EV_DoDoor(line, close30ThenOpen); + break; + + case 77: + // Fast Ceiling Crush & Raise + EV_DoCeiling(line, fastCrushAndRaise); + break; + + case 79: + // Lights Very Dark + EV_LightTurnOn(line, 35); + break; + + case 80: + // Light Turn On - brightest near + EV_LightTurnOn(line, 0); + break; + + case 81: + // Light Turn On 255 + EV_LightTurnOn(line, 255); + break; + + case 82: + // Lower Floor To Lowest + EV_DoFloor(line, lowerFloorToLowest); + break; + + case 83: + // Lower Floor + EV_DoFloor(line, lowerFloor); + break; + + case 84: + // LowerAndChange + EV_DoFloor(line, lowerAndChange); + break; + + case 86: + // Open Door + EV_DoDoor(line, dopen); + break; + + case 87: + // Perpetual Platform Raise + EV_DoPlat(line, perpetualRaise, 0); + break; + + case 88: + // PlatDownWaitUp + EV_DoPlat(line, downWaitUpStay, 0); + break; + + case 89: + // Platform Stop + EV_StopPlat(line); + break; + + case 90: + // Raise Door + EV_DoDoor(line, normal); + break; + + case 91: + // Raise Floor + EV_DoFloor(line, raiseFloor); + break; + + case 92: + // Raise Floor 24 + EV_DoFloor(line, raiseFloor24); + break; + + case 93: + // Raise Floor 24 And Change + EV_DoFloor(line, raiseFloor24AndChange); + break; + + case 94: + // Raise Floor Crush + EV_DoFloor(line, raiseFloorCrush); + break; + + case 95: + // Raise floor to nearest height + // and change texture. + EV_DoPlat(line, raiseToNearestAndChange, 0); + break; + + case 96: + // Raise floor to shortest texture height + // on either side of lines. + EV_DoFloor(line, raiseToTexture); + break; + + case 97: + // TELEPORT! + EV_Teleport(line, side, thing); + break; + + case 98: + // Lower Floor (TURBO) + EV_DoFloor(line, turboLower); + break; + + case 105: + // Blazing Door Raise (faster than TURBO!) + EV_DoDoor(line, blazeRaise); + break; + + case 106: + // Blazing Door Open (faster than TURBO!) + EV_DoDoor(line, blazeOpen); + break; + + case 107: + // Blazing Door Close (faster than TURBO!) + EV_DoDoor(line, blazeClose); + break; + + case 120: + // Blazing PlatDownWaitUpStay. + EV_DoPlat(line, blazeDWUS, 0); + break; + + case 126: + // TELEPORT MonsterONLY. + if (!thing->player_sptr) + EV_Teleport(line, side, thing); + break; + + case 128: + // Raise To Nearest Floor + EV_DoFloor(line, raiseFloorToNearest); + break; + + case 129: + // Raise Floor Turbo + EV_DoFloor(line, raiseFloorTurbo); + break; + + // Extended walk triggers + + // jff 1/29/98 added new linedef types to fill all functions out so that + // all have varieties SR, S1, WR, W1 + + // killough 1/31/98: "factor out" compatibility test, by + // adding inner switch qualified by compatibility flag. + // relax test to demo_compatibility + + // killough 2/16/98: Fix problems with W1 types being cleared too early + + default: + switch (LN_SPECIAL(line)) + { + // Extended walk once triggers + + case 142: + // Raise Floor 512 + // 142 W1 EV_DoFloor(raiseFloor512) + if (EV_DoFloor(line, raiseFloor512)) + LN_SPECIAL(line) = 0; + break; + + case 143: + // Raise Floor 24 and change + // 143 W1 EV_DoPlat(raiseAndChange,24) + if (EV_DoPlat(line, raiseAndChange, 24)) + LN_SPECIAL(line) = 0; + break; + + case 144: + // Raise Floor 32 and change + // 144 W1 EV_DoPlat(raiseAndChange,32) + if (EV_DoPlat(line, raiseAndChange, 32)) + LN_SPECIAL(line) = 0; + break; + + case 145: + // Lower Ceiling to Floor + // 145 W1 EV_DoCeiling(lowerToFloor) + if (EV_DoCeiling(line, lowerToFloor)) + LN_SPECIAL(line) = 0; + break; + + case 146: + // Lower Pillar, Raise Donut + // 146 W1 EV_DoDonut() + if (EV_DoDonut(line)) + LN_SPECIAL(line) = 0; + break; + + case 199: + // Lower ceiling to lowest surrounding ceiling + // 199 W1 EV_DoCeiling(lowerToLowest) + if (EV_DoCeiling(line, lowerToLowest)) + LN_SPECIAL(line) = 0; + break; + + case 200: + // Lower ceiling to highest surrounding floor + // 200 W1 EV_DoCeiling(lowerToMaxFloor) + if (EV_DoCeiling(line, lowerToMaxFloor)) + LN_SPECIAL(line) = 0; + break; + + case 207: + // killough 2/16/98: W1 silent teleporter (normal kind) + if (EV_SilentTeleport(line, side, thing)) + LN_SPECIAL(line) = 0; + break; + + //jff 3/16/98 renumber 215->153 + case 153: //jff 3/15/98 create texture change no motion type + // Texture/Type Change Only (Trig) + // 153 W1 Change Texture/Type Only + if (EV_DoChange(line, trigChangeOnly)) + LN_SPECIAL(line) = 0; + break; + + case 239: //jff 3/15/98 create texture change no motion type + // Texture/Type Change Only (Numeric) + // 239 W1 Change Texture/Type Only + if (EV_DoChange(line, numChangeOnly)) + LN_SPECIAL(line) = 0; + break; + + case 219: + // Lower floor to next lower neighbor + // 219 W1 Lower Floor Next Lower Neighbor + if (EV_DoFloor(line, lowerFloorToNearest)) + LN_SPECIAL(line) = 0; + break; + + case 227: + // Raise elevator next floor + // 227 W1 Raise Elevator next floor + if (EV_DoElevator(line, elevateUp)) + LN_SPECIAL(line) = 0; + break; + + case 231: + // Lower elevator next floor + // 231 W1 Lower Elevator next floor + if (EV_DoElevator(line, elevateDown)) + LN_SPECIAL(line) = 0; + break; + + case 235: + // Elevator to current floor + // 235 W1 Elevator to current floor + if (EV_DoElevator(line, elevateCurrent)) + LN_SPECIAL(line) = 0; + break; + + case 243: //jff 3/6/98 make fit within DCK's 256 linedef types + // killough 2/16/98: W1 silent teleporter (linedef-linedef kind) + if (EV_SilentLineTeleport(line, side, thing, false)) + LN_SPECIAL(line) = 0; + break; + + case 262: //jff 4/14/98 add silent line-line reversed + if (EV_SilentLineTeleport(line, side, thing, true)) + LN_SPECIAL(line) = 0; + break; + + case 264: //jff 4/14/98 add monster-only silent line-line reversed + if (!thing->player_sptr && EV_SilentLineTeleport(line, side, thing, true)) + LN_SPECIAL(line) = 0; + break; + + case 266: //jff 4/14/98 add monster-only silent line-line + if (!thing->player_sptr && EV_SilentLineTeleport(line, side, thing, false)) + LN_SPECIAL(line) = 0; + break; + + case 268: //jff 4/14/98 add monster-only silent + if (!thing->player_sptr && EV_SilentTeleport(line, side, thing)) + LN_SPECIAL(line) = 0; + break; + + //jff 1/29/98 end of added W1 linedef types + + // Extended walk many retriggerable + + //jff 1/29/98 added new linedef types to fill all functions + //out so that all have varieties SR, S1, WR, W1 + + case 147: + // Raise Floor 512 + // 147 WR EV_DoFloor(raiseFloor512) + EV_DoFloor(line, raiseFloor512); + break; + + case 148: + // Raise Floor 24 and Change + // 148 WR EV_DoPlat(raiseAndChange,24) + EV_DoPlat(line, raiseAndChange, 24); + break; + + case 149: + // Raise Floor 32 and Change + // 149 WR EV_DoPlat(raiseAndChange,32) + EV_DoPlat(line, raiseAndChange, 32); + break; + + case 150: + // Start slow silent crusher + // 150 WR EV_DoCeiling(silentCrushAndRaise) + EV_DoCeiling(line, silentCrushAndRaise); + break; + + case 151: + // RaiseCeilingLowerFloor + // 151 WR EV_DoCeiling(raiseToHighest), + // EV_DoFloor(lowerFloortoLowest) + EV_DoCeiling(line, raiseToHighest); + EV_DoFloor(line, lowerFloorToLowest); + break; + + case 152: + // Lower Ceiling to Floor + // 152 WR EV_DoCeiling(lowerToFloor) + EV_DoCeiling(line, lowerToFloor); + break; + + //jff 3/16/98 renumber 153->256 + case 256: + // Build stairs, step 8 + // 256 WR EV_BuildStairs(build8) + EV_BuildStairs(line, build8); + break; + + //jff 3/16/98 renumber 154->257 + case 257: + // Build stairs, step 16 + // 257 WR EV_BuildStairs(turbo16) + EV_BuildStairs(line, turbo16); + break; + + case 155: + // Lower Pillar, Raise Donut + // 155 WR EV_DoDonut() + EV_DoDonut(line); + break; + + case 156: + // Start lights strobing + // 156 WR Lights EV_StartLightStrobing() + EV_StartLightStrobing(line); + break; + + case 157: + // Lights to dimmest near + // 157 WR Lights EV_TurnTagLightsOff() + EV_TurnTagLightsOff(line); + break; + + case 201: + // Lower ceiling to lowest surrounding ceiling + // 201 WR EV_DoCeiling(lowerToLowest) + EV_DoCeiling(line, lowerToLowest); + break; + + case 202: + // Lower ceiling to highest surrounding floor + // 202 WR EV_DoCeiling(lowerToMaxFloor) + EV_DoCeiling(line, lowerToMaxFloor); + break; + + case 208: + // killough 2/16/98: WR silent teleporter (normal kind) + EV_SilentTeleport(line, side, thing); + break; + + case 212: //jff 3/14/98 create instant toggle floor type + // Toggle floor between C and F instantly + // 212 WR Instant Toggle Floor + EV_DoPlat(line, toggleUpDn, 0); + break; + + //jff 3/16/98 renumber 216->154 + case 154: //jff 3/15/98 create texture change no motion type + // Texture/Type Change Only (Trigger) + // 154 WR Change Texture/Type Only + EV_DoChange(line, trigChangeOnly); + break; + + case 240: //jff 3/15/98 create texture change no motion type + // Texture/Type Change Only (Numeric) + // 240 WR Change Texture/Type Only + EV_DoChange(line, numChangeOnly); + break; + + case 220: + // Lower floor to next lower neighbor + // 220 WR Lower Floor Next Lower Neighbor + EV_DoFloor(line, lowerFloorToNearest); + break; + + case 228: + // Raise elevator next floor + // 228 WR Raise Elevator next floor + EV_DoElevator(line, elevateUp); + break; + + case 232: + // Lower elevator next floor + // 232 WR Lower Elevator next floor + EV_DoElevator(line, elevateDown); + break; + + case 236: + // Elevator to current floor + // 236 WR Elevator to current floor + EV_DoElevator(line, elevateCurrent); + break; + + case 244: //jff 3/6/98 make fit within DCK's 256 linedef types + // killough 2/16/98: WR silent teleporter (linedef-linedef kind) + EV_SilentLineTeleport(line, side, thing, false); + break; + + case 263: //jff 4/14/98 add silent line-line reversed + EV_SilentLineTeleport(line, side, thing, true); + break; + + case 265: //jff 4/14/98 add monster-only silent line-line reversed + if (!thing->player_sptr) + EV_SilentLineTeleport(line, side, thing, true); + break; + + case 267: //jff 4/14/98 add monster-only silent line-line + if (!thing->player_sptr) + EV_SilentLineTeleport(line, side, thing, false); + break; + + case 269: //jff 4/14/98 add monster-only silent + if (!thing->player_sptr) + EV_SilentTeleport(line, side, thing); + break; + + //jff 1/29/98 end of added WR linedef types + } + break; + } +} + +// +// P_ShootSpecialLine - Gun trigger special dispatcher +// +// Called when a thing shoots a special line with bullet, shell, saw, or fist. +// +// jff 02/12/98 all G1 lines were fixed to check the result from the EV_ +// function before clearing the special. This avoids losing the function +// of the line, should the sector already be in motion when the line is +// impacted. Change is qualified by demo_compatibility. +// +void P_ShootSpecialLine(mobj_t *thing, const line_t *line) +{ + // pointer to line function is NULL by default, set non-null if + // line special is gun triggered generalized linedef type + int (*linefunc)(const line_t *line) = NULL; + + // check each range of generalized linedefs + if ((unsigned) LN_SPECIAL(line) >= GenEnd) + { + // Out of range for GenFloors + } + else if ((unsigned) LN_SPECIAL(line) >= GenFloorBase) + { + if (!thing->player_sptr) + if ((LN_SPECIAL(line) & FloorChange) || !(LN_SPECIAL(line) & FloorModel)) + return; // FloorModel is "Allow Monsters" if FloorChange is 0 + if (!line->tag) //jff 2/27/98 all gun generalized types require tag + return; + + linefunc = EV_DoGenFloor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenCeilingBase) + { + if (!thing->player_sptr) + if ((LN_SPECIAL(line) & CeilingChange) || !(LN_SPECIAL(line) & CeilingModel)) + return; // CeilingModel is "Allow Monsters" if CeilingChange is 0 + if (!line->tag) //jff 2/27/98 all gun generalized types require tag + return; + linefunc = EV_DoGenCeiling; + } + else if ((unsigned) LN_SPECIAL(line) >= GenDoorBase) + { + if (!thing->player_sptr) + { + if (!(LN_SPECIAL(line) & DoorMonster)) + return; // monsters disallowed from this door + if (line->flags & ML_SECRET) // they can't open secret doors either + return; + } + if (!line->tag) //jff 3/2/98 all gun generalized types require tag + return; + linefunc = EV_DoGenDoor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenLockedBase) + { + if (!thing->player_sptr) + return; // monsters disallowed from unlocking doors + if (((LN_SPECIAL(line) & TriggerType) == GunOnce) || ((LN_SPECIAL(line) & TriggerType) == GunMany)) + { //jff 4/1/98 check for being a gun type before reporting door type + if (!P_CanUnlockGenDoor(line, getMobjPlayer(thing))) + return; + } + else + return; + if (!line->tag) //jff 2/27/98 all gun generalized types require tag + return; + + linefunc = EV_DoGenLockedDoor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenLiftBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & LiftMonster)) + return; // monsters disallowed + linefunc = EV_DoGenLift; + } + else if ((unsigned) LN_SPECIAL(line) >= GenStairsBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & StairMonster)) + return; // monsters disallowed + if (!line->tag) //jff 2/27/98 all gun generalized types require tag + return; + linefunc = EV_DoGenStairs; + } + else if ((unsigned) LN_SPECIAL(line) >= GenCrusherBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & StairMonster)) + return; // monsters disallowed + if (!line->tag) //jff 2/27/98 all gun generalized types require tag + return; + linefunc = EV_DoGenCrusher; + } + + if (linefunc) + switch ((LN_SPECIAL(line) & TriggerType) >> TriggerTypeShift) + { + case GunOnce: + if (linefunc(line)) + P_ChangeSwitchTexture(line, 0); + return; + case GunMany: + if (linefunc(line)) + P_ChangeSwitchTexture(line, 1); + return; + default: // if not a gun type, do nothing here + return; + } + + // Impacts that other things can activate. + if (!thing->player_sptr) + { + int ok = 0; + switch (LN_SPECIAL(line)) + { + case 46: + // 46 GR Open door on impact weapon is monster activatable + ok = 1; + break; + } + if (!ok) + return; + } + + if (!P_CheckTag(line)) //jff 2/27/98 disallow zero tag on some types + return; + + switch (LN_SPECIAL(line)) + { + case 24: + // 24 G1 raise floor to highest adjacent + if (EV_DoFloor(line, raiseFloor)) + P_ChangeSwitchTexture(line, 0); + break; + + case 46: + // 46 GR open door, stay open + EV_DoDoor(line, dopen); + P_ChangeSwitchTexture(line, 1); + break; + + case 47: + // 47 G1 raise floor to nearest and change texture and type + if (EV_DoPlat(line, raiseToNearestAndChange, 0)) + P_ChangeSwitchTexture(line, 0); + break; + + //jff 1/30/98 added new gun linedefs here + // killough 1/31/98: added demo_compatibility check, added inner switch + + default: + switch (LN_SPECIAL(line)) + { + case 197: + // Exit to next level + // killough 10/98: prevent zombies from exiting levels + if (thing->player_sptr && getMobjPlayer(thing)->health <= 0) + break; + P_ChangeSwitchTexture(line, 0); + G_ExitLevel(); + break; + + case 198: + // Exit to secret level + // killough 10/98: prevent zombies from exiting levels + if (thing->player_sptr && getMobjPlayer(thing)->health <= 0) + break; + P_ChangeSwitchTexture(line, 0); + G_SecretExitLevel(); + break; + //jff end addition of new gun linedefs + } + break; + } +} + +// +// P_PlayerInSpecialSector() +// +// Called every tick frame +// that the player origin is in a special sector +// +// Changed to ignore sector types the engine does not recognize +// +void P_PlayerInSpecialSector(player_t *player) +{ + sector_t *sector; + + sector = getMobjSubsector(player->mo)->sector; + + // Falling, not all the way down yet? + // Sector specials don't apply in mid-air + if (player->mo->z != sector->floorheight) + return; + + // Has hit ground. + //jff add if to handle old vs generalized types + if (sector->special < 32) // regular sector specials + { + switch (sector->special) + { + case 5: + // 5/10 unit damage per 31 ticks + if (!player->powers[pw_ironfeet]) + if (!(_g->leveltime & 0x1f)) + P_DamageMobj(player->mo, NULL, NULL, 10); + break; + + case 7: + // 2/5 unit damage per 31 ticks + if (!player->powers[pw_ironfeet]) + if (!(_g->leveltime & 0x1f)) + P_DamageMobj(player->mo, NULL, NULL, 5); + break; + + case 16: + // 10/20 unit damage per 31 ticks + case 4: + // 10/20 unit damage plus blinking light (light already spawned) + if (!player->powers[pw_ironfeet] || (P_Random(__FILE__, __LINE__, __FUNCTION__) < 5)) // even with suit, take damage + { + if (!(_g->leveltime & 0x1f)) + P_DamageMobj(player->mo, NULL, NULL, 20); + } + break; + + case 9: + // Tally player in secret sector, clear secret special + player->secretcount++; + sector->special = 0; + break; + + case 11: + if (!(_g->leveltime & 0x1f)) + P_DamageMobj(player->mo, NULL, NULL, 20); + + if (player->health <= 10) + G_ExitLevel(); + break; + + default: + //jff 1/24/98 Don't exit as DOOM2 did, just ignore + break; + } + } + else //jff 3/14/98 handle extended sector types for secrets and damage + { + switch ((sector->special & DAMAGE_MASK) >> DAMAGE_SHIFT) + { + case 0: // no damage + break; + case 1: // 2/5 damage per 31 ticks + if (!player->powers[pw_ironfeet]) + if (!(_g->leveltime & 0x1f)) + P_DamageMobj(player->mo, NULL, NULL, 5); + break; + case 2: // 5/10 damage per 31 ticks + if (!player->powers[pw_ironfeet]) + if (!(_g->leveltime & 0x1f)) + P_DamageMobj(player->mo, NULL, NULL, 10); + break; + case 3: // 10/20 damage per 31 ticks + if (!player->powers[pw_ironfeet] || (P_Random(__FILE__, __LINE__, __FUNCTION__) < 5)) // take damage even with suit + { + if (!(_g->leveltime & 0x1f)) + P_DamageMobj(player->mo, NULL, NULL, 20); + } + break; + } + if (sector->special & SECRET_MASK) + { + player->secretcount++; + sector->special &= ~SECRET_MASK; + if (sector->special < 32) // if all extended bits clear, + sector->special = 0; // sector is not special anymore + } + + // phares 3/19/98: + // + // If FRICTION_MASK or PUSH_MASK is set, we don't care at this + // point, since the code to deal with those situations is + // handled by Thinkers. + + } +} + +// +// P_UpdateSpecials() +// +// Check level timer, frag counter, +// animate flats, scroll walls, +// change button textures +// +// Reads and modifies globals: +// levelTimer, levelTimeCount, +// levelFragLimit, levelFragLimitCount +// + +void P_UpdateSpecials(void) +{ + anim_t *anim; + int pic; + int i; + + // Animate flats and textures globally + for (anim = _g->anims; anim < _g->lastanim; anim++) + { + unsigned int t = (_g->leveltime >> 3); + unsigned int n = anim->numpics; + + if ((n & (n - 1)) == 0) + pic = anim->basepic + (t & (n - 1)); + else + pic = anim->basepic + (t % n); + + for (i = anim->basepic; i < anim->basepic + anim->numpics; i++) + { + if (anim->istexture) + texturetranslation[i] = pic; + else + flattranslation[i] = pic; + } + } + + // Check buttons (retriggerable switches) and change texture on timeout + for (i = 0; i < MAXBUTTONS; i++) + { + if (_g->buttonlist[i].btimer) + { + _g->buttonlist[i].btimer--; + + if (!_g->buttonlist[i].btimer) + { + // 2021/09/26 next-hack: oops, forgot to translate lineno to actual array index... + uint16_t idx = _g->linesChangeableTextureIndex[_g->buttonlist[i].line->lineno]; + switch (_g->buttonlist[i].where) + { + /* + case top: + _g->sides[_g->buttonlist[i].line->sidenum[0]].toptexture = + _g->buttonlist[i].btexture; + break; + + case middle: + _g->sides[_g->buttonlist[i].line->sidenum[0]].midtexture = + _g->buttonlist[i].btexture; + break; + + case bottom: + _g->sides[_g->buttonlist[i].line->sidenum[0]].bottomtexture = + _g->buttonlist[i].btexture; + break; + default: + break; + */ + case top: + _g->switch_texture_top[idx] = _g->buttonlist[i].btexture; + break; + + case middle: + _g->switch_texture_mid[idx] = _g->buttonlist[i].btexture; + break; + + case bottom: + _g->switch_texture_bot[idx] = _g->buttonlist[i].btexture; + break; + default: + break; + } + + S_StartSound2(_g->buttonlist[i].soundorg, sfx_swtchn); + memset(&_g->buttonlist[i], 0, sizeof(button_t)); + } + } + } +} + +////////////////////////////////////////////////////////////////////// +// +// Sector and Line special thinker spawning at level startup +// +////////////////////////////////////////////////////////////////////// + +// +// P_SpawnSpecials +// After the map has been loaded, +// scan for specials that spawn thinkers +// + +// Parses command line parameters. +void P_SpawnSpecials(void) +{ + sector_t *sector; + int i; +// int episode; + +// episode = 1; +// if (W_CheckNumForName("texture2") >= 0) +// episode = 2; + + // Init special sectors. + sector = _g->sectors; + for (i = 0; i < _g->numsectors; i++, sector++) + { + if (!sector->special) + continue; + + if (sector->special & SECRET_MASK) //jff 3/15/98 count extended + _g->totalsecret++; // secret sectors too + + switch (sector->special & 31) + { + case 1: + // random off + P_SpawnLightFlash(sector); + break; + + case 2: + // strobe fast + P_SpawnStrobeFlash(sector, FASTDARK, 0); + break; + + case 3: + // strobe slow + P_SpawnStrobeFlash(sector, SLOWDARK, 0); + break; + + case 4: + // strobe fast/death slime + P_SpawnStrobeFlash(sector, FASTDARK, 0); + sector->special |= 3 << DAMAGE_SHIFT; //jff 3/14/98 put damage bits in + break; + + case 8: + // glowing light + P_SpawnGlowingLight(sector); + break; + case 9: + // secret sector + if (sector->special < 32) //jff 3/14/98 bits don't count unless not + _g->totalsecret++; // a generalized sector type + break; + + case 10: + // door close in 30 seconds + P_SpawnDoorCloseIn30(sector); + break; + + case 12: + // sync strobe slow + P_SpawnStrobeFlash(sector, SLOWDARK, 1); + break; + + case 13: + // sync strobe fast + P_SpawnStrobeFlash(sector, FASTDARK, 1); + break; + + case 14: + // door raise in 5 minutes + P_SpawnDoorRaiseIn5Mins(sector, i); + break; + + case 17: + // fire flickering + P_SpawnFireFlicker(sector); + break; + } + } + printf("Remove all active ceiling\r\n"); + P_RemoveAllActiveCeilings(); // jff 2/22/98 use killough's scheme + printf("Remove all active plats\r\n"); + P_RemoveAllActivePlats(); // killough + printf("Memset\r\n"); + for (i = 0; i < MAXBUTTONS; i++) + memset(&_g->buttonlist[i], 0, sizeof(button_t)); + + // P_InitTagLists() must be called before P_FindSectorFromLineTag() + // or P_FindLineFromLineTag() can be called. + printf("Init tag list\r\n"); + P_InitTagLists(); // killough 1/30/98: Create xref tables for tags + + printf("Spawn scrollers\r\n"); + P_SpawnScrollers(); // killough 3/7/98: Add generalized scrollers +} + +// killough 2/28/98: +// +// This function, with the help of r_plane.c and r_bsp.c, supports generalized +// scrolling floors and walls, with optional mobj-carrying properties, e.g. +// conveyor belts, rivers, etc. A linedef with a special type affects all +// tagged sectors the same way, by creating scrolling and/or object-carrying +// properties. Multiple linedefs may be used on the same sector and are +// cumulative, although the special case of scrolling a floor and carrying +// things on it, requires only one linedef. The linedef's direction determines +// the scrolling direction, and the linedef's length determines the scrolling +// speed. This was designed so that an edge around the sector could be used to +// control the direction of the sector's scrolling, which is usually what is +// desired. +// +// Process the active scrollers. +// +// This is the main scrolling code +// killough 3/7/98 + +void T_Scroll(scroll_t *s) +{ + // 2021-02-13 next-hack: now the side texture offset is collected in an array pointed by _g->textureoffsets + // side_t *side =_g->sides + s->affectee; + // side->textureoffset++; + _g->textureoffsets[s->affectee]++; +} + +// +// Add_Scroller() +// +// Add a generalized scroller to the thinker list. +// +// type: the enumerated type of scrolling: floor, ceiling, floor carrier, +// wall, floor carrier & scroller +// +// (dx,dy): the direction and speed of the scrolling or its acceleration +// +// control: the sector whose heights control this scroller's effect +// remotely, or -1 if no control sector +// +// affectee: the index of the affected object (sector or sidedef) +// +// accel: non-zero if this is an accelerative effect +// + +static void Add_Scroller(int affectee) +{ + scroll_t *s = Z_Malloc(sizeof *s, PU_LEVSPEC, 0); + s->thinker.function = T_Scroll; + s->affectee = affectee; + P_AddThinker(&s->thinker); +} + +// Initialize the scrollers +static void P_SpawnScrollers(void) +{ + int i; + const line_t *l = _g->lines; + + for (i = 0; i < _g->numlines; i++, l++) + { + int special = LN_SPECIAL(l); + + switch (special) + { + case 48: // scroll first side + Add_Scroller(_g->lines[i].sidenum[0]); + break; + + } + } +} + diff --git a/doom/src/pdoom/Doom/source/p_switch.c b/doom/src/pdoom/Doom/source/p_switch.c new file mode 100644 index 0000000..2dfe84e --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_switch.c @@ -0,0 +1,1167 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Switches, buttons. Two-state animation. Exits. + * + * next-hack: switch list is now in immutable flash region (wad-dependent), + * saving few hundred bytes of RAM. + * modified code to work with short pointers. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "w_wad.h" +#include "r_main.h" +#include "p_spec.h" +#include "g_game.h" +#include "s_sound.h" +#include "sounds.h" +#include "lprintf.h" + +#include "global_data.h" + +static const switchlist_t alphSwitchList[] = +{ + // Doom shareware episode 1 switches + { "SW1BRCOM", "SW2BRCOM", 1 }, + { "SW1BRN1", "SW2BRN1", 1 }, + { "SW1BRN2", "SW2BRN2", 1 }, + { "SW1BRNGN", "SW2BRNGN", 1 }, + { "SW1BROWN", "SW2BROWN", 1 }, + { "SW1COMM", "SW2COMM", 1 }, + { "SW1COMP", "SW2COMP", 1 }, + { "SW1DIRT", "SW2DIRT", 1 }, + { "SW1EXIT", "SW2EXIT", 1 }, + { "SW1GRAY", "SW2GRAY", 1 }, + { "SW1GRAY1", "SW2GRAY1", 1 }, + { "SW1METAL", "SW2METAL", 1 }, + { "SW1PIPE", "SW2PIPE", 1 }, + { "SW1SLAD", "SW2SLAD", 1 }, + { "SW1STARG", "SW2STARG", 1 }, + { "SW1STON1", "SW2STON1", 1 }, + { "SW1STON2", "SW2STON2", 1 }, + { "SW1STONE", "SW2STONE", 1 }, + { "SW1STRTN", "SW2STRTN", 1 }, + + // Doom registered episodes 2&3 switches + { "SW1BLUE", "SW2BLUE", 2 }, + { "SW1CMT", "SW2CMT", 2 }, + { "SW1GARG", "SW2GARG", 2 }, + { "SW1GSTON", "SW2GSTON", 2 }, + { "SW1HOT", "SW2HOT", 2 }, + { "SW1LION", "SW2LION", 2 }, + { "SW1SATYR", "SW2SATYR", 2 }, + { "SW1SKIN", "SW2SKIN", 2 }, + { "SW1VINE", "SW2VINE", 2 }, + { "SW1WOOD", "SW2WOOD", 2 }, + + // Doom II switches + { "SW1PANEL", "SW2PANEL", 3 }, + { "SW1ROCK", "SW2ROCK", 3 }, + { "SW1MET2", "SW2MET2", 3 }, + { "SW1WDMET", "SW2WDMET", 3 }, + { "SW1BRIK", "SW2BRIK", 3 }, + { "SW1MOD1", "SW2MOD1", 3 }, + { "SW1ZIM", "SW2ZIM", 3 }, + { "SW1STON6", "SW2STON6", 3 }, + { "SW1TEK", "SW2TEK", 3 }, + { "SW1MARB", "SW2MARB", 3 }, + { "SW1SKULL", "SW2SKULL", 3 }, + + { "\0", "\0", 0 } +}; + +// +// P_InitSwitchList +// Only called at game initialization. +// +void P_InitSwitchList(void) +{ + int i; + int index; + int episode; + + episode = 1; + short *switchlist = Z_Malloc(sizeof (*switchlist) * 2 * MAXSWITCHES, PU_STATIC, NULL); + + if (_g->gamemode == registered || _g->gamemode == retail) + episode = 2; + else if (_g->gamemode == commercial) + episode = 3; + + for (index = 0, i = 0; i < MAXSWITCHES; i++) + { + if (!alphSwitchList[i].episode) + { + _g->numswitches = index / 2; + switchlist[index] = -1; + break; + } + + if (alphSwitchList[i].episode <= episode) + { + switchlist[index++] = R_CheckTextureNumForName(alphSwitchList[i].name1); + switchlist[index++] = R_CheckTextureNumForName(alphSwitchList[i].name2); + } + } + p_wad_immutable_flash_data->switchlist = writeBufferToFlashRegion(switchlist, sizeof(*switchlist) * 2 * MAXSWITCHES, FLASH_IMMUTABLE_REGION, true); + Z_Free(switchlist); +} +// +// P_StartButton() +// +// Start a button (retriggerable switch) counting down till it turns off. +// +// Passed the linedef the button is on, which texture on the sidedef contains +// the button, the texture number of the button, and the time the button is +// to remain active in gametics. +// No return. +// +static void P_StartButton(const line_t *line, bwhere_e w, int texture, int time) +{ + int i; + + // See if button is already pressed + for (i = 0; i < MAXBUTTONS; i++) + if (_g->buttonlist[i].btimer && _g->buttonlist[i].line == line) + return; + + for (i = 0; i < MAXBUTTONS; i++) + if (!_g->buttonlist[i].btimer) // use first unused element of list + { + _g->buttonlist[i].line = line; + _g->buttonlist[i].where = w; + _g->buttonlist[i].btexture = texture; + _g->buttonlist[i].btimer = time; + /* use sound origin of line itself - no need to compatibility-wrap + * as the popout code gets it wrong whatever its value */ + _g->buttonlist[i].soundorg = &LN_FRONTSECTOR(line)->soundorg; + return; + } + + I_Error("P_StartButton: no button slots left!"); +} + +// +// P_ChangeSwitchTexture() +// +// Function that changes switch wall texture on activation. +// +// Passed the line which the switch is on, and whether its retriggerable. +// If not retriggerable, this function clears the line special to insure that +// +// No return +// +void P_ChangeSwitchTexture(const line_t *line, int useAgain) +{ + /* Rearranged a bit to avoid too much code duplication */ + int i, sound; + // 2021-03-13: forgot that switches have changeable textures... + uint16_t *texture, *ttop, *tmid, *tbot; + bwhere_e position; + + // ttop = &_g->sides[line->sidenum[0]].toptexture; + //tmid = &_g->sides[line->sidenum[0]].midtexture; + //tbot = &_g->sides[line->sidenum[0]].bottomtexture; + ttop = &_g->switch_texture_top[_g->linesChangeableTextureIndex[line->lineno]]; + tmid = &_g->switch_texture_mid[_g->linesChangeableTextureIndex[line->lineno]]; + tbot = &_g->switch_texture_bot[_g->linesChangeableTextureIndex[line->lineno]]; + // + sound = sfx_swtchn; + + /* don't zero line->special until after exit switch test */ + if (!useAgain) + LN_SPECIAL(line) = 0; + + /* search for a texture to change */ + texture = NULL; + position = 0; + for (i = 0; i < _g->numswitches * 2; i++) + { /* this could be more efficient... */ + if (p_wad_immutable_flash_data->switchlist[i] == *ttop) + { + texture = ttop; + position = top; + break; + } + else if (p_wad_immutable_flash_data->switchlist[i] == *tmid) + { + texture = tmid; + position = middle; + break; + } + else if (p_wad_immutable_flash_data->switchlist[i] == *tbot) + { + texture = tbot; + position = bottom; + break; + } + } + if (texture == NULL) + return; /* no switch texture was found to change */ + *texture = p_wad_immutable_flash_data->switchlist[i ^ 1]; + + S_StartSound2(&LN_FRONTSECTOR(line)->soundorg, sound); + + if (useAgain) + P_StartButton(line, position, p_wad_immutable_flash_data->switchlist[i], BUTTONTIME); +} + +// +// P_UseSpecialLine +// +// +// Called when a thing uses (pushes) a special line. +// Only the front sides of lines are usable. +// Dispatches to the appropriate linedef function handler. +// +// Passed the thing using the line, the line being used, and the side used +// Returns true if a thinker was created +// +boolean P_UseSpecialLine(mobj_t *thing, const line_t *line, int side) +{ + + // e6y + // b.m. side test was broken in boom201 + if ((_g->demoplayback ? (_g->demover != 201) : (true))) + if (side) //jff 6/1/98 fix inadvertent deletion of side test + return false; + + //jff 02/04/98 add check here for generalized floor/ceil mover + { + // pointer to line function is NULL by default, set non-null if + // line special is push or switch generalized linedef type + int (*linefunc)(const line_t *line) = NULL; + + // check each range of generalized linedefs + if ((unsigned) LN_SPECIAL(line) >= GenEnd) + { + // Out of range for GenFloors + } + else if ((unsigned) LN_SPECIAL(line) >= GenFloorBase) + { + if (!thing->player_sptr) + if ((LN_SPECIAL(line) & FloorChange) || !(LN_SPECIAL(line) & FloorModel)) + return false; // FloorModel is "Allow Monsters" if FloorChange is 0 + if (!line->tag && ((LN_SPECIAL(line) & 6) != 6)) //jff 2/27/98 all non-manual + return false; // generalized types require tag + linefunc = EV_DoGenFloor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenCeilingBase) + { + if (!thing->player_sptr) + if ((LN_SPECIAL(line) & CeilingChange) || !(LN_SPECIAL(line) & CeilingModel)) + return false; // CeilingModel is "Allow Monsters" if CeilingChange is 0 + if (!line->tag && ((LN_SPECIAL(line) & 6) != 6)) //jff 2/27/98 all non-manual + return false; // generalized types require tag + linefunc = EV_DoGenCeiling; + } + else if ((unsigned) LN_SPECIAL(line) >= GenDoorBase) + { + if (!thing->player_sptr) + { + if (!(LN_SPECIAL(line) & DoorMonster)) + return false; // monsters disallowed from this door + if (line->flags & ML_SECRET) // they can't open secret doors either + return false; + } + if (!line->tag && ((LN_SPECIAL(line) & 6) != 6)) //jff 3/2/98 all non-manual + return false; // generalized types require tag + linefunc = EV_DoGenDoor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenLockedBase) + { + if (!thing->player_sptr) + return false; // monsters disallowed from unlocking doors + if (!P_CanUnlockGenDoor(line, getMobjPlayer(thing))) + return false; + if (!line->tag && ((LN_SPECIAL(line) & 6) != 6)) //jff 2/27/98 all non-manual + return false; // generalized types require tag + + linefunc = EV_DoGenLockedDoor; + } + else if ((unsigned) LN_SPECIAL(line) >= GenLiftBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & LiftMonster)) + return false; // monsters disallowed + if (!line->tag && ((LN_SPECIAL(line) & 6) != 6)) //jff 2/27/98 all non-manual + return false; // generalized types require tag + linefunc = EV_DoGenLift; + } + else if ((unsigned) LN_SPECIAL(line) >= GenStairsBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & StairMonster)) + return false; // monsters disallowed + if (!line->tag && ((LN_SPECIAL(line) & 6) != 6)) //jff 2/27/98 all non-manual + return false; // generalized types require tag + linefunc = EV_DoGenStairs; + } + else if ((unsigned) LN_SPECIAL(line) >= GenCrusherBase) + { + if (!thing->player_sptr) + if (!(LN_SPECIAL(line) & CrusherMonster)) + return false; // monsters disallowed + if (!line->tag && ((LN_SPECIAL(line) & 6) != 6)) //jff 2/27/98 all non-manual + return false; // generalized types require tag + linefunc = EV_DoGenCrusher; + } + + if (linefunc) + switch ((LN_SPECIAL(line) & TriggerType) >> TriggerTypeShift) + { + case PushOnce: + if (!side) + if (linefunc(line)) + LN_SPECIAL(line) = 0; + return true; + case PushMany: + if (!side) + linefunc(line); + return true; + case SwitchOnce: + if (linefunc(line)) + P_ChangeSwitchTexture(line, 0); + return true; + case SwitchMany: + if (linefunc(line)) + P_ChangeSwitchTexture(line, 1); + return true; + default: // if not a switch/push type, do nothing here + return false; + } + } + + // Switches that other things can activate. + if (!thing->player_sptr) + { + // never open secret doors + if (line->flags & ML_SECRET) + return false; + + switch (LN_SPECIAL(line)) + { + case 1: // MANUAL DOOR RAISE + case 32: // MANUAL BLUE + case 33: // MANUAL RED + case 34: // MANUAL YELLOW + //jff 3/5/98 add ability to use teleporters for monsters + case 195: // switch teleporters + case 174: + case 210: // silent switch teleporters + case 209: + break; + + default: + return false; + } + } + + if (!P_CheckTag(line)) //jff 2/27/98 disallow zero tag on some types + return false; + + // Dispatch to handler according to linedef type + switch (LN_SPECIAL(line)) + { + // Manual doors, push type with no tag + case 1: // Vertical Door + case 26: // Blue Door/Locked + case 27: // Yellow Door /Locked + case 28: // Red Door /Locked + + case 31: // Manual door open + case 32: // Blue locked door open + case 33: // Red locked door open + case 34: // Yellow locked door open + + case 117: // Blazing door raise + case 118: // Blazing door open + EV_VerticalDoor(line, thing); + break; + + // Switches (non-retriggerable) + case 7: + // Build Stairs + if (EV_BuildStairs(line, build8)) + P_ChangeSwitchTexture(line, 0); + break; + + case 9: + // Change Donut + if (EV_DoDonut(line)) + P_ChangeSwitchTexture(line, 0); + break; + + case 11: + /* Exit level + * killough 10/98: prevent zombies from exiting levels + */ + if (thing->player_sptr && getMobjPlayer(thing)->health <= 0) + { + S_StartSound(thing, sfx_noway); + return false; + } + + P_ChangeSwitchTexture(line, 0); + G_ExitLevel(); + break; + + case 14: + // Raise Floor 32 and change texture + if (EV_DoPlat(line, raiseAndChange, 32)) + P_ChangeSwitchTexture(line, 0); + break; + + case 15: + // Raise Floor 24 and change texture + if (EV_DoPlat(line, raiseAndChange, 24)) + P_ChangeSwitchTexture(line, 0); + break; + + case 18: + // Raise Floor to next highest floor + if (EV_DoFloor(line, raiseFloorToNearest)) + P_ChangeSwitchTexture(line, 0); + break; + + case 20: + // Raise Plat next highest floor and change texture + if (EV_DoPlat(line, raiseToNearestAndChange, 0)) + P_ChangeSwitchTexture(line, 0); + break; + + case 21: + // PlatDownWaitUpStay + if (EV_DoPlat(line, downWaitUpStay, 0)) + P_ChangeSwitchTexture(line, 0); + break; + + case 23: + // Lower Floor to Lowest + if (EV_DoFloor(line, lowerFloorToLowest)) + P_ChangeSwitchTexture(line, 0); + break; + + case 29: + // Raise Door + if (EV_DoDoor(line, normal)) + P_ChangeSwitchTexture(line, 0); + break; + + case 41: + // Lower Ceiling to Floor + if (EV_DoCeiling(line, lowerToFloor)) + P_ChangeSwitchTexture(line, 0); + break; + + case 71: + // Turbo Lower Floor + if (EV_DoFloor(line, turboLower)) + P_ChangeSwitchTexture(line, 0); + break; + + case 49: + // Ceiling Crush And Raise + if (EV_DoCeiling(line, crushAndRaise)) + P_ChangeSwitchTexture(line, 0); + break; + + case 50: + // Close Door + if (EV_DoDoor(line, dclose)) + P_ChangeSwitchTexture(line, 0); + break; + + case 51: + /* Secret EXIT + * killough 10/98: prevent zombies from exiting levels + */ + if (thing->player_sptr && getMobjPlayer(thing)->health <= 0) + { + S_StartSound(thing, sfx_noway); + return false; + } + + P_ChangeSwitchTexture(line, 0); + G_SecretExitLevel(); + break; + + case 55: + // Raise Floor Crush + if (EV_DoFloor(line, raiseFloorCrush)) + P_ChangeSwitchTexture(line, 0); + break; + + case 101: + // Raise Floor + if (EV_DoFloor(line, raiseFloor)) + P_ChangeSwitchTexture(line, 0); + break; + + case 102: + // Lower Floor to Surrounding floor height + if (EV_DoFloor(line, lowerFloor)) + P_ChangeSwitchTexture(line, 0); + break; + + case 103: + // Open Door + if (EV_DoDoor(line, dopen)) + P_ChangeSwitchTexture(line, 0); + break; + + case 111: + // Blazing Door Raise (faster than TURBO!) + if (EV_DoDoor(line, blazeRaise)) + P_ChangeSwitchTexture(line, 0); + break; + + case 112: + // Blazing Door Open (faster than TURBO!) + if (EV_DoDoor(line, blazeOpen)) + P_ChangeSwitchTexture(line, 0); + break; + + case 113: + // Blazing Door Close (faster than TURBO!) + if (EV_DoDoor(line, blazeClose)) + P_ChangeSwitchTexture(line, 0); + break; + + case 122: + // Blazing PlatDownWaitUpStay + if (EV_DoPlat(line, blazeDWUS, 0)) + P_ChangeSwitchTexture(line, 0); + break; + + case 127: + // Build Stairs Turbo 16 + if (EV_BuildStairs(line, turbo16)) + P_ChangeSwitchTexture(line, 0); + break; + + case 131: + // Raise Floor Turbo + if (EV_DoFloor(line, raiseFloorTurbo)) + P_ChangeSwitchTexture(line, 0); + break; + + case 133: + // BlzOpenDoor BLUE + case 135: + // BlzOpenDoor RED + case 137: + // BlzOpenDoor YELLOW + if (EV_DoLockedDoor(line, blazeOpen, thing)) + P_ChangeSwitchTexture(line, 0); + break; + + case 140: + // Raise Floor 512 + if (EV_DoFloor(line, raiseFloor512)) + P_ChangeSwitchTexture(line, 0); + break; + + // killough 1/31/98: factored out compatibility check; + // added inner switch, relaxed check to demo_compatibility + + default: + switch (LN_SPECIAL(line)) + { + //jff 1/29/98 added linedef types to fill all functions out so that + // all possess SR, S1, WR, W1 types + + case 158: + // Raise Floor to shortest lower texture + // 158 S1 EV_DoFloor(raiseToTexture), CSW(0) + if (EV_DoFloor(line, raiseToTexture)) + P_ChangeSwitchTexture(line, 0); + break; + + case 159: + // Raise Floor to shortest lower texture + // 159 S1 EV_DoFloor(lowerAndChange) + if (EV_DoFloor(line, lowerAndChange)) + P_ChangeSwitchTexture(line, 0); + break; + + case 160: + // Raise Floor 24 and change + // 160 S1 EV_DoFloor(raiseFloor24AndChange) + if (EV_DoFloor(line, raiseFloor24AndChange)) + P_ChangeSwitchTexture(line, 0); + break; + + case 161: + // Raise Floor 24 + // 161 S1 EV_DoFloor(raiseFloor24) + if (EV_DoFloor(line, raiseFloor24)) + P_ChangeSwitchTexture(line, 0); + break; + + case 162: + // Moving floor min n to max n + // 162 S1 EV_DoPlat(perpetualRaise,0) + if (EV_DoPlat(line, perpetualRaise, 0)) + P_ChangeSwitchTexture(line, 0); + break; + + case 163: + // Stop Moving floor + // 163 S1 EV_DoPlat(perpetualRaise,0) + EV_StopPlat(line); + P_ChangeSwitchTexture(line, 0); + break; + + case 164: + // Start fast crusher + // 164 S1 EV_DoCeiling(fastCrushAndRaise) + if (EV_DoCeiling(line, fastCrushAndRaise)) + P_ChangeSwitchTexture(line, 0); + break; + + case 165: + // Start slow silent crusher + // 165 S1 EV_DoCeiling(silentCrushAndRaise) + if (EV_DoCeiling(line, silentCrushAndRaise)) + P_ChangeSwitchTexture(line, 0); + break; + + case 166: + // Raise ceiling, Lower floor + // 166 S1 EV_DoCeiling(raiseToHighest), EV_DoFloor(lowerFloortoLowest) + if (EV_DoCeiling(line, raiseToHighest) || EV_DoFloor(line, lowerFloorToLowest)) + P_ChangeSwitchTexture(line, 0); + break; + + case 167: + // Lower floor and Crush + // 167 S1 EV_DoCeiling(lowerAndCrush) + if (EV_DoCeiling(line, lowerAndCrush)) + P_ChangeSwitchTexture(line, 0); + break; + + case 168: + // Stop crusher + // 168 S1 EV_CeilingCrushStop() + if (EV_CeilingCrushStop(line)) + P_ChangeSwitchTexture(line, 0); + break; + + case 169: + // Lights to brightest neighbor sector + // 169 S1 EV_LightTurnOn(0) + EV_LightTurnOn(line, 0); + P_ChangeSwitchTexture(line, 0); + break; + + case 170: + // Lights to near dark + // 170 S1 EV_LightTurnOn(35) + EV_LightTurnOn(line, 35); + P_ChangeSwitchTexture(line, 0); + break; + + case 171: + // Lights on full + // 171 S1 EV_LightTurnOn(255) + EV_LightTurnOn(line, 255); + P_ChangeSwitchTexture(line, 0); + break; + + case 172: + // Start Lights Strobing + // 172 S1 EV_StartLightStrobing() + EV_StartLightStrobing(line); + P_ChangeSwitchTexture(line, 0); + break; + + case 173: + // Lights to Dimmest Near + // 173 S1 EV_TurnTagLightsOff() + EV_TurnTagLightsOff(line); + P_ChangeSwitchTexture(line, 0); + break; + + case 174: + // Teleport + // 174 S1 EV_Teleport(side,thing) + if (EV_Teleport(line, side, thing)) + P_ChangeSwitchTexture(line, 0); + break; + + case 175: + // Close Door, Open in 30 secs + // 175 S1 EV_DoDoor(close30ThenOpen) + if (EV_DoDoor(line, close30ThenOpen)) + P_ChangeSwitchTexture(line, 0); + break; + + case 189: //jff 3/15/98 create texture change no motion type + // Texture Change Only (Trigger) + // 189 S1 Change Texture/Type Only + if (EV_DoChange(line, trigChangeOnly)) + P_ChangeSwitchTexture(line, 0); + break; + + case 203: + // Lower ceiling to lowest surrounding ceiling + // 203 S1 EV_DoCeiling(lowerToLowest) + if (EV_DoCeiling(line, lowerToLowest)) + P_ChangeSwitchTexture(line, 0); + break; + + case 204: + // Lower ceiling to highest surrounding floor + // 204 S1 EV_DoCeiling(lowerToMaxFloor) + if (EV_DoCeiling(line, lowerToMaxFloor)) + P_ChangeSwitchTexture(line, 0); + break; + + case 209: + // killough 1/31/98: silent teleporter + //jff 209 S1 SilentTeleport + if (EV_SilentTeleport(line, side, thing)) + P_ChangeSwitchTexture(line, 0); + break; + + case 241: //jff 3/15/98 create texture change no motion type + // Texture Change Only (Numeric) + // 241 S1 Change Texture/Type Only + if (EV_DoChange(line, numChangeOnly)) + P_ChangeSwitchTexture(line, 0); + break; + + case 221: + // Lower floor to next lowest floor + // 221 S1 Lower Floor To Nearest Floor + if (EV_DoFloor(line, lowerFloorToNearest)) + P_ChangeSwitchTexture(line, 0); + break; + + case 229: + // Raise elevator next floor + // 229 S1 Raise Elevator next floor + if (EV_DoElevator(line, elevateUp)) + P_ChangeSwitchTexture(line, 0); + break; + + case 233: + // Lower elevator next floor + // 233 S1 Lower Elevator next floor + if (EV_DoElevator(line, elevateDown)) + P_ChangeSwitchTexture(line, 0); + break; + + case 237: + // Elevator to current floor + // 237 S1 Elevator to current floor + if (EV_DoElevator(line, elevateCurrent)) + P_ChangeSwitchTexture(line, 0); + break; + + // jff 1/29/98 end of added S1 linedef types + + //jff 1/29/98 added linedef types to fill all functions out so that + // all possess SR, S1, WR, W1 types + + case 78: //jff 3/15/98 create texture change no motion type + // Texture Change Only (Numeric) + // 78 SR Change Texture/Type Only + if (EV_DoChange(line, numChangeOnly)) + P_ChangeSwitchTexture(line, 1); + break; + + case 176: + // Raise Floor to shortest lower texture + // 176 SR EV_DoFloor(raiseToTexture), CSW(1) + if (EV_DoFloor(line, raiseToTexture)) + P_ChangeSwitchTexture(line, 1); + break; + + case 177: + // Raise Floor to shortest lower texture + // 177 SR EV_DoFloor(lowerAndChange) + if (EV_DoFloor(line, lowerAndChange)) + P_ChangeSwitchTexture(line, 1); + break; + + case 178: + // Raise Floor 512 + // 178 SR EV_DoFloor(raiseFloor512) + if (EV_DoFloor(line, raiseFloor512)) + P_ChangeSwitchTexture(line, 1); + break; + + case 179: + // Raise Floor 24 and change + // 179 SR EV_DoFloor(raiseFloor24AndChange) + if (EV_DoFloor(line, raiseFloor24AndChange)) + P_ChangeSwitchTexture(line, 1); + break; + + case 180: + // Raise Floor 24 + // 180 SR EV_DoFloor(raiseFloor24) + if (EV_DoFloor(line, raiseFloor24)) + P_ChangeSwitchTexture(line, 1); + break; + + case 181: + // Moving floor min n to max n + // 181 SR EV_DoPlat(perpetualRaise,0) + + EV_DoPlat(line, perpetualRaise, 0); + P_ChangeSwitchTexture(line, 1); + break; + + case 182: + // Stop Moving floor + // 182 SR EV_DoPlat(perpetualRaise,0) + EV_StopPlat(line); + P_ChangeSwitchTexture(line, 1); + break; + + case 183: + // Start fast crusher + // 183 SR EV_DoCeiling(fastCrushAndRaise) + if (EV_DoCeiling(line, fastCrushAndRaise)) + P_ChangeSwitchTexture(line, 1); + break; + + case 184: + // Start slow crusher + // 184 SR EV_DoCeiling(crushAndRaise) + if (EV_DoCeiling(line, crushAndRaise)) + P_ChangeSwitchTexture(line, 1); + break; + + case 185: + // Start slow silent crusher + // 185 SR EV_DoCeiling(silentCrushAndRaise) + if (EV_DoCeiling(line, silentCrushAndRaise)) + P_ChangeSwitchTexture(line, 1); + break; + + case 186: + // Raise ceiling, Lower floor + // 186 SR EV_DoCeiling(raiseToHighest), EV_DoFloor(lowerFloortoLowest) + if (EV_DoCeiling(line, raiseToHighest) || EV_DoFloor(line, lowerFloorToLowest)) + P_ChangeSwitchTexture(line, 1); + break; + + case 187: + // Lower floor and Crush + // 187 SR EV_DoCeiling(lowerAndCrush) + if (EV_DoCeiling(line, lowerAndCrush)) + P_ChangeSwitchTexture(line, 1); + break; + + case 188: + // Stop crusher + // 188 SR EV_CeilingCrushStop() + if (EV_CeilingCrushStop(line)) + P_ChangeSwitchTexture(line, 1); + break; + + case 190: //jff 3/15/98 create texture change no motion type + // Texture Change Only (Trigger) + // 190 SR Change Texture/Type Only + if (EV_DoChange(line, trigChangeOnly)) + P_ChangeSwitchTexture(line, 1); + break; + + case 191: + // Lower Pillar, Raise Donut + // 191 SR EV_DoDonut() + if (EV_DoDonut(line)) + P_ChangeSwitchTexture(line, 1); + break; + + case 192: + // Lights to brightest neighbor sector + // 192 SR EV_LightTurnOn(0) + EV_LightTurnOn(line, 0); + P_ChangeSwitchTexture(line, 1); + break; + + case 193: + // Start Lights Strobing + // 193 SR EV_StartLightStrobing() + EV_StartLightStrobing(line); + P_ChangeSwitchTexture(line, 1); + break; + + case 194: + // Lights to Dimmest Near + // 194 SR EV_TurnTagLightsOff() + EV_TurnTagLightsOff(line); + P_ChangeSwitchTexture(line, 1); + break; + + case 195: + // Teleport + // 195 SR EV_Teleport(side,thing) + if (EV_Teleport(line, side, thing)) + P_ChangeSwitchTexture(line, 1); + break; + + case 196: + // Close Door, Open in 30 secs + // 196 SR EV_DoDoor(close30ThenOpen) + if (EV_DoDoor(line, close30ThenOpen)) + P_ChangeSwitchTexture(line, 1); + break; + + case 205: + // Lower ceiling to lowest surrounding ceiling + // 205 SR EV_DoCeiling(lowerToLowest) + if (EV_DoCeiling(line, lowerToLowest)) + P_ChangeSwitchTexture(line, 1); + break; + + case 206: + // Lower ceiling to highest surrounding floor + // 206 SR EV_DoCeiling(lowerToMaxFloor) + if (EV_DoCeiling(line, lowerToMaxFloor)) + P_ChangeSwitchTexture(line, 1); + break; + + case 210: + // killough 1/31/98: silent teleporter + //jff 210 SR SilentTeleport + if (EV_SilentTeleport(line, side, thing)) + P_ChangeSwitchTexture(line, 1); + break; + + case 211: //jff 3/14/98 create instant toggle floor type + // Toggle Floor Between C and F Instantly + // 211 SR Toggle Floor Instant + if (EV_DoPlat(line, toggleUpDn, 0)) + P_ChangeSwitchTexture(line, 1); + break; + + case 222: + // Lower floor to next lowest floor + // 222 SR Lower Floor To Nearest Floor + if (EV_DoFloor(line, lowerFloorToNearest)) + P_ChangeSwitchTexture(line, 1); + break; + + case 230: + // Raise elevator next floor + // 230 SR Raise Elevator next floor + if (EV_DoElevator(line, elevateUp)) + P_ChangeSwitchTexture(line, 1); + break; + + case 234: + // Lower elevator next floor + // 234 SR Lower Elevator next floor + if (EV_DoElevator(line, elevateDown)) + P_ChangeSwitchTexture(line, 1); + break; + + case 238: + // Elevator to current floor + // 238 SR Elevator to current floor + if (EV_DoElevator(line, elevateCurrent)) + P_ChangeSwitchTexture(line, 1); + break; + + case 258: + // Build stairs, step 8 + // 258 SR EV_BuildStairs(build8) + if (EV_BuildStairs(line, build8)) + P_ChangeSwitchTexture(line, 1); + break; + + case 259: + // Build stairs, step 16 + // 259 SR EV_BuildStairs(turbo16) + if (EV_BuildStairs(line, turbo16)) + P_ChangeSwitchTexture(line, 1); + break; + + // 1/29/98 jff end of added SR linedef types + + } + break; + + // Buttons (retriggerable switches) + case 42: + // Close Door + if (EV_DoDoor(line, dclose)) + P_ChangeSwitchTexture(line, 1); + break; + + case 43: + // Lower Ceiling to Floor + if (EV_DoCeiling(line, lowerToFloor)) + P_ChangeSwitchTexture(line, 1); + break; + + case 45: + // Lower Floor to Surrounding floor height + if (EV_DoFloor(line, lowerFloor)) + P_ChangeSwitchTexture(line, 1); + break; + + case 60: + // Lower Floor to Lowest + if (EV_DoFloor(line, lowerFloorToLowest)) + P_ChangeSwitchTexture(line, 1); + break; + + case 61: + // Open Door + if (EV_DoDoor(line, dopen)) + P_ChangeSwitchTexture(line, 1); + break; + + case 62: + // PlatDownWaitUpStay + if (EV_DoPlat(line, downWaitUpStay, 1)) + P_ChangeSwitchTexture(line, 1); + break; + + case 63: + // Raise Door + if (EV_DoDoor(line, normal)) + P_ChangeSwitchTexture(line, 1); + break; + + case 64: + // Raise Floor to ceiling + if (EV_DoFloor(line, raiseFloor)) + P_ChangeSwitchTexture(line, 1); + break; + + case 66: + // Raise Floor 24 and change texture + if (EV_DoPlat(line, raiseAndChange, 24)) + P_ChangeSwitchTexture(line, 1); + break; + + case 67: + // Raise Floor 32 and change texture + if (EV_DoPlat(line, raiseAndChange, 32)) + P_ChangeSwitchTexture(line, 1); + break; + + case 65: + // Raise Floor Crush + if (EV_DoFloor(line, raiseFloorCrush)) + P_ChangeSwitchTexture(line, 1); + break; + + case 68: + // Raise Plat to next highest floor and change texture + if (EV_DoPlat(line, raiseToNearestAndChange, 0)) + P_ChangeSwitchTexture(line, 1); + break; + + case 69: + // Raise Floor to next highest floor + if (EV_DoFloor(line, raiseFloorToNearest)) + P_ChangeSwitchTexture(line, 1); + break; + + case 70: + // Turbo Lower Floor + if (EV_DoFloor(line, turboLower)) + P_ChangeSwitchTexture(line, 1); + break; + + case 114: + // Blazing Door Raise (faster than TURBO!) + if (EV_DoDoor(line, blazeRaise)) + P_ChangeSwitchTexture(line, 1); + break; + + case 115: + // Blazing Door Open (faster than TURBO!) + if (EV_DoDoor(line, blazeOpen)) + P_ChangeSwitchTexture(line, 1); + break; + + case 116: + // Blazing Door Close (faster than TURBO!) + if (EV_DoDoor(line, blazeClose)) + P_ChangeSwitchTexture(line, 1); + break; + + case 123: + // Blazing PlatDownWaitUpStay + if (EV_DoPlat(line, blazeDWUS, 0)) + P_ChangeSwitchTexture(line, 1); + break; + + case 132: + // Raise Floor Turbo + if (EV_DoFloor(line, raiseFloorTurbo)) + P_ChangeSwitchTexture(line, 1); + break; + + case 99: + // BlzOpenDoor BLUE + case 134: + // BlzOpenDoor RED + case 136: + // BlzOpenDoor YELLOW + if (EV_DoLockedDoor(line, blazeOpen, thing)) + P_ChangeSwitchTexture(line, 1); + break; + + case 138: + // Light Turn On + EV_LightTurnOn(line, 255); + P_ChangeSwitchTexture(line, 1); + break; + + case 139: + // Light Turn Off + EV_LightTurnOn(line, 35); + P_ChangeSwitchTexture(line, 1); + break; + } + return true; +} diff --git a/doom/src/pdoom/Doom/source/p_telept.c b/doom/src/pdoom/Doom/source/p_telept.c new file mode 100644 index 0000000..6d5ef41 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_telept.c @@ -0,0 +1,334 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Teleportation. + * + * next-hack: modified code to work with short pointers. + * code not tested so far... + * + *-----------------------------------------------------------------------------*/ + +#include "doomdef.h" +#include "doomstat.h" +#include "p_spec.h" +#include "p_maputl.h" +#include "p_map.h" +#include "r_main.h" +#include "p_tick.h" +#include "s_sound.h" +#include "sounds.h" +#include "p_user.h" + +#include "global_data.h" + +static mobj_t* P_TeleportDestination(const line_t *line) +{ + int i; + for (i = -1; (i = P_FindSectorFromLineTag(line, i)) >= 0;) + { + register thinker_t *th = NULL; + while ((th = P_NextThinker(th)) != NULL) + if (th->function == P_MobjThinker) + { + register mobj_t *m = (mobj_t*) th; + if (m->type == MT_TELEPORTMAN && getMobjSubsector(m)->sector - _g->sectors == i) + return m; + } + } + return NULL; +} +// +// TELEPORTATION +// +// killough 5/3/98: reformatted, cleaned up + +int EV_Teleport(const line_t *line, int side, mobj_t *thing) +{ + mobj_t *m; + + // don't teleport missiles + // Don't teleport if hit back of line, + // so you can get out of teleporter. + if (side || (thing->flags & MF_MISSILE)) + return 0; + + // killough 1/31/98: improve performance by using + // P_FindSectorFromLineTag instead of simple linear search. + + if ((m = P_TeleportDestination(line)) != NULL) + { + fixed_t oldx = thing->x, oldy = thing->y, oldz = thing->z; + player_t *player = getMobjPlayer(thing); + + // killough 5/12/98: exclude voodoo dolls: + if (player && player->mo != thing) + player = NULL; + + if (!P_TeleportMove(thing, m->x, m->y, false)) /* killough 8/9/98 */ + return 0; + + thing->z = thing->floorz; + + if (player) + player->viewz = thing->z + player->viewheight; + + // spawn teleport fog and emit sound at source + S_StartSound(P_SpawnMobj(oldx, oldy, oldz, MT_TFOG), sfx_telept); + + // spawn teleport fog and emit sound at destination + S_StartSound(P_SpawnMobj(m->x + 20 * finecosine[m->angle >> ANGLETOFINESHIFT], m->y + 20 * finesine[m->angle >> ANGLETOFINESHIFT], thing->z, MT_TFOG), sfx_telept); + + /* don't move for a bit + * cph - DEMOSYNC - BOOM had (player) here? */ + if (thing->player_sptr) + thing->reactiontime = 18; + + thing->angle = m->angle; + + thing->momx = thing->momy = thing->momz = 0; + + /* killough 10/98: kill all bobbing momentum too */ + if (player) + player->momx = player->momy = 0; + + return 1; + } + return 0; +} + +// +// Silent TELEPORTATION, by Lee Killough +// Primarily for rooms-over-rooms etc. +// + +int EV_SilentTeleport(const line_t *line, int side, mobj_t *thing) +{ + mobj_t *m; + + // don't teleport missiles + // Don't teleport if hit back of line, + // so you can get out of teleporter. + + if (side || (thing->flags & MF_MISSILE)) + return 0; + + if ((m = P_TeleportDestination(line)) != NULL) + { + // Height of thing above ground, in case of mid-air teleports: + fixed_t z = thing->z - thing->floorz; + + // Get the angle between the exit thing and source linedef. + // Rotate 90 degrees, so that walking perpendicularly across + // teleporter linedef causes thing to exit in the direction + // indicated by the exit thing. + angle_t angle = R_PointToAngle2(0, 0, line->dx, line->dy) - m->angle + ANG90; + + // Sine, cosine of angle adjustment + fixed_t s = finesine[angle >> ANGLETOFINESHIFT]; + fixed_t c = finecosine[angle >> ANGLETOFINESHIFT]; + + // Momentum of thing crossing teleporter linedef + fixed_t momx = thing->momx; + fixed_t momy = thing->momy; + + // Whether this is a player, and if so, a pointer to its player_t + player_t *player = getMobjPlayer(thing); + + // Attempt to teleport, aborting if blocked + if (!P_TeleportMove(thing, m->x, m->y, false)) /* killough 8/9/98 */ + return 0; + + // Rotate thing according to difference in angles + thing->angle += angle; + + // Adjust z position to be same height above ground as before + thing->z = z + thing->floorz; + + // Rotate thing's momentum to come out of exit just like it entered + thing->momx = FixedMul(momx, c) - FixedMul(momy, s); + thing->momy = FixedMul(momy, c) + FixedMul(momx, s); + + // Adjust player's view, in case there has been a height change + // Voodoo dolls are excluded by making sure player->mo == thing. + if (player && player->mo == thing) + { + // Save the current deltaviewheight, used in stepping + fixed_t deltaviewheight = player->deltaviewheight; + + // Clear deltaviewheight, since we don't want any changes + player->deltaviewheight = 0; + + // Set player's view according to the newly set parameters + P_CalcHeight(player); + + // Reset the delta to have the same dynamics as before + player->deltaviewheight = deltaviewheight; + } + + return 1; + } + return 0; +} + +// +// Silent linedef-based TELEPORTATION, by Lee Killough +// Primarily for rooms-over-rooms etc. +// This is the complete player-preserving kind of teleporter. +// It has advantages over the teleporter with thing exits. +// + +// maximum fixed_t units to move object to avoid hiccups +#define FUDGEFACTOR 10 + +int EV_SilentLineTeleport(const line_t *line, int side, mobj_t *thing, boolean reverse) +{ + int i; + const line_t *l; + + if (side || (thing->flags & MF_MISSILE)) + return 0; + + for (i = -1; (i = P_FindLineFromLineTag(line, i)) >= 0;) + if ((l = _g->lines + i) != line && LN_BACKSECTOR(l)) + { + // Get the thing's position along the source linedef + fixed_t pos = + D_abs(line->dx) > D_abs(line->dy) ? FixedDiv(thing->x - line->v1.x, line->dx) : FixedDiv(thing->y - line->v1.y, line->dy); + + // Get the angle between the two linedefs, for rotating + // orientation and momentum. Rotate 180 degrees, and flip + // the position across the exit linedef, if reversed. + angle_t angle = (reverse ? pos = FRACUNIT - pos, 0 : ANG180) + R_PointToAngle2(0, 0, l->dx, l->dy) - R_PointToAngle2(0, 0, line->dx, line->dy); + + // Interpolate position across the exit linedef + fixed_t x = l->v2.x - FixedMul(pos, l->dx); + fixed_t y = l->v2.y - FixedMul(pos, l->dy); + + // Sine, cosine of angle adjustment + fixed_t s = finesine[angle >> ANGLETOFINESHIFT]; + fixed_t c = finecosine[angle >> ANGLETOFINESHIFT]; + + // Maximum distance thing can be moved away from interpolated + // exit, to ensure that it is on the correct side of exit linedef + int fudge = FUDGEFACTOR; + + // Whether this is a player, and if so, a pointer to its player_t. + // Voodoo dolls are excluded by making sure thing->player->mo==thing. + player_t *player = + getMobjPlayer(thing) && getMobjPlayer(thing)->mo == thing ? getMobjPlayer(thing) : NULL; + + // Whether walking towards first side of exit linedef steps down + int stepdown = + LN_FRONTSECTOR(l)->floorheight < LN_BACKSECTOR(l)->floorheight; + + // Height of thing above ground + fixed_t z = thing->z - thing->floorz; + + // Side to exit the linedef on positionally. + // + // Notes: + // + // This flag concerns exit position, not momentum. Due to + // roundoff error, the thing can land on either the left or + // the right side of the exit linedef, and steps must be + // taken to make sure it does not end up on the wrong side. + // + // Exit momentum is always towards side 1 in a reversed + // teleporter, and always towards side 0 otherwise. + // + // Exiting positionally on side 1 is always safe, as far + // as avoiding oscillations and stuck-in-wall problems, + // but may not be optimum for non-reversed teleporters. + // + // Exiting on side 0 can cause oscillations if momentum + // is towards side 1, as it is with reversed teleporters. + // + // Exiting on side 1 slightly improves player viewing + // when going down a step on a non-reversed teleporter. + + int side = reverse || (player && stepdown); + + // Make sure we are on correct side of exit linedef. + while (P_PointOnLineSide(x, y, l) != side && --fudge >= 0) + if (D_abs(l->dx) > D_abs(l->dy)) + y -= (l->dx < 0) != side ? -1 : 1; + else + x += (l->dy < 0) != side ? -1 : 1; + + // Attempt to teleport, aborting if blocked + if (!P_TeleportMove(thing, x, y, false)) /* killough 8/9/98 */ + return 0; + + // Adjust z position to be same height above ground as before. + // Ground level at the exit is measured as the higher of the + // two floor heights at the exit linedef. + thing->z = z + _g->sectors[_g->sides[l->sidenum[stepdown]].sector_num].floorheight; + + // Rotate thing's orientation according to difference in linedef angles + thing->angle += angle; + + // Momentum of thing crossing teleporter linedef + x = thing->momx; + y = thing->momy; + + // Rotate thing's momentum to come out of exit just like it entered + thing->momx = FixedMul(x, c) - FixedMul(y, s); + thing->momy = FixedMul(y, c) + FixedMul(x, s); + + // Adjust a player's view, in case there has been a height change + if (player) + { + // Save the current deltaviewheight, used in stepping + fixed_t deltaviewheight = player->deltaviewheight; + + // Clear deltaviewheight, since we don't want any changes now + player->deltaviewheight = 0; + + // Set player's view according to the newly set parameters + P_CalcHeight(player); + + // Reset the delta to have the same dynamics as before + player->deltaviewheight = deltaviewheight; + } + + return 1; + } + return 0; +} diff --git a/doom/src/pdoom/Doom/source/p_tick.c b/doom/src/pdoom/Doom/source/p_tick.c new file mode 100644 index 0000000..5ad7e27 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_tick.c @@ -0,0 +1,222 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Thinker, Ticker. + * + * next-hack: modified code to work with short pointers. + * added support for static objects. + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "p_user.h" +#include "p_spec.h" +#include "p_tick.h" +#include "p_map.h" +#include "z_bmalloc.h" + +#include "global_data.h" + +// +// THINKERS +// All thinkers should be allocated by Z_Malloc +// so they can be operated on uniformly. +// The actual structures will vary in size, +// but the first element must be thinker_t. +// + +// +// P_InitThinkers +// + +void P_InitThinkers(void) +{ +// thinkercap.prev = thinkercap.next = &thinkercap; + //thinkercap.next = &thinkercap; + thinkercap.next_sptr = getShortPtr(&thinkercap); + thinkercap.prev_sptr = getShortPtr(&thinkercap); +} + +// +// P_AddThinker +// Adds a new thinker at the end of the list. +// + +void P_AddThinker(thinker_t *thinker) +{ + getThinkerPrev(&thinkercap)->next_sptr = getShortPtr(thinker); + thinker->next_sptr = getShortPtr(&thinkercap); +// thinker->prev = thinkercap.prev; + thinker->prev_sptr = thinkercap.prev_sptr; + thinkercap.prev_sptr = getShortPtr(thinker); +} + +// +// killough 11/98: +// +// Make currentthinker external, so that P_RemoveThinkerDelayed +// can adjust currentthinker when thinkers self-remove. + +// +// P_RemoveThinkerDelayed() +// +// Called automatically as part of the thinker loop in P_RunThinkers(), +// on nodes which are pending deletion. +// +// If this thinker has no more pointers referencing it indirectly, +// remove it, and set currentthinker to one node preceeding it, so +// that the next step in P_RunThinkers() will get its successor. +// + +void P_RemoveThinkerDelayed(thinker_t *thinker) +{ + + thinker_t *next = getThinkerNext(thinker); + /* Note that currentthinker is guaranteed to point to us, + * and since we're freeing our memory, we had better change that. So + * point it to thinker->prev, so the iterator will correctly move on to + * thinker->prev->next = thinker->next */ + + //(next->prev = thinker->prev)->next = next; + next->prev_sptr = thinker->prev_sptr; + getThinkerPrev(thinker)->next_sptr = getShortPtr(next); + //Z_Free(thinker); + if (!Z_BFree(&mobjzone, thinker)) + Z_Free(thinker); +} +// +void P_RemoveStaticThinkerDelayed(thinker_t *thinker) +{ + + thinker_t *next = getThinkerNext(thinker); + /* Note that currentthinker is guaranteed to point to us, + * and since we're freeing our memory, we had better change that. So + * point it to thinker->prev, so the iterator will correctly move on to + * thinker->prev->next = thinker->next */ + + //(next->prev = thinker->prev)->next = next; + next->prev_sptr = thinker->prev_sptr; + getThinkerPrev(thinker)->next_sptr = getShortPtr(next); + //Z_Free(thinker); + Z_BFree(&static_mobjzone, thinker); +} + +// +// P_RemoveThinker +// +// Deallocation is lazy -- it will not actually be freed +// until its thinking turn comes up. +// +// killough 4/25/98: +// +// Instead of marking the function with -1 value cast to a function pointer, +// set the function to P_RemoveThinkerDelayed(), so that later, it will be +// removed automatically as part of the thinker process. +// + +void P_RemoveThinker(thinker_t *thinker) +{ + thinker->function = P_RemoveThinkerDelayed; + +} + +void P_RemoveStaticThinker(thinker_t *thinker) +{ + thinker->function = P_RemoveStaticThinkerDelayed; + +} + +/* cph 2002/01/13 - iterator for thinker list + * WARNING: Do not modify thinkers between calls to this function + */ +thinker_t* P_NextThinker(thinker_t *th) +{ + thinker_t *top = &_g->thinkerclasscap[th_all]; + if (!th) + { + th = top; + } + th = getThinkerNext(th); + return th == top ? NULL : th; +} + +/* + * P_SetTarget + * + * This function is used to keep track of pointer references to mobj thinkers. + * In Doom, objects such as lost souls could sometimes be removed despite + * their still being referenced. In Boom, 'target' mobj fields were tested + * during each gametic, and any objects pointed to by them would be prevented + * from being removed. But this was incomplete, and was slow (every mobj was + * checked during every gametic). Now, we keep a count of the number of + * references, and delay removal until the count is 0. + */ + +void P_SetTarget(mobj_t **mop, mobj_t *targ) +{ + *mop = targ; // Set new target and if non-NULL, increase its counter +} + +void P_Ticker(void) +{ + /* pause if in menu and at least one tic has been run + * + * killough 9/29/98: note that this ties in with basetic, + * since G_Ticker does the pausing during recording or + * playback, and compenates by incrementing basetic. + * + * All of this complicated mess is used to preserve demo sync. + */ + + if (_g->paused || (_g->menuactive && !_g->demoplayback && _g->player.viewz != 1)) + return; // + + P_MapStart(); + // not if this is an intermission screen + if (_g->gamestate == GS_LEVEL) + if (_g->playeringame) + P_PlayerThink(&_g->player); + + P_RunThinkers(); + P_UpdateSpecials(); + P_RespawnSpecials(); + P_MapEnd(); + _g->leveltime++; // for par times +} + diff --git a/doom/src/pdoom/Doom/source/p_user.c b/doom/src/pdoom/Doom/source/p_user.c new file mode 100644 index 0000000..0ded125 --- /dev/null +++ b/doom/src/pdoom/Doom/source/p_user.c @@ -0,0 +1,414 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Player related stuff. + * Bobbing POV/weapon, movement. + * Pending weapon. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "d_event.h" +#include "r_main.h" +#include "p_map.h" +#include "p_spec.h" +#include "p_user.h" + +#include "global_data.h" + +// Index of the special effects (INVUL inverse) map. + +#define INVERSECOLORMAP 32 + +// +// Movement. +// + +// 16 pixels of bob + +#define MAXBOB 0x100000 + +// +// P_Thrust +// Moves the given origin along a given angle. +// + +void P_Thrust(player_t *player, angle_t angle, fixed_t move) +{ + angle >>= ANGLETOFINESHIFT; + player->mo->momx += FixedMul(move, finecosine[angle]); + player->mo->momy += FixedMul(move, finesine[angle]); +} + +/* + * P_Bob + * Same as P_Thrust, but only affects bobbing. + * + * killough 10/98: We apply thrust separately between the real physical player + * and the part which affects bobbing. This way, bobbing only comes from player + * motion, nothing external, avoiding many problems, e.g. bobbing should not + * occur on conveyors, unless the player walks on one, and bobbing should be + * reduced at a regular rate, even on ice (where the player coasts). + */ + +static void P_Bob(player_t *player, angle_t angle, fixed_t move) +{ + player->momx += FixedMul(move, finecosine[angle >>= ANGLETOFINESHIFT]); + player->momy += FixedMul(move, finesine[angle]); +} + +// +// P_CalcHeight +// Calculate the walking / running height adjustment +// + +void P_CalcHeight(player_t *player) +{ + int angle; + fixed_t bob; + + // Regular movement bobbing + // (needs to be calculated for gun swing + // even if not on ground) + // OPTIMIZE: tablify angle + // Note: a LUT allows for effects + // like a ramp with low health. + + /* killough 10/98: Make bobbing depend only on player-applied motion. + * + * Note: don't reduce bobbing here if on ice: if you reduce bobbing here, + * it causes bobbing jerkiness when the player moves from ice to non-ice, + * and vice-versa. + */ + player->bob = (FixedMul(player->momx, player->momx) + FixedMul(player->momy, player->momy)) >> 2; + + if (player->bob > MAXBOB) + player->bob = MAXBOB; + + if (!_g->onground || (player->cheats & CF_NOMOMENTUM)) + { + player->viewz = player->mo->z + VIEWHEIGHT; + + if (player->viewz > player->mo->ceilingz - 4 * FRACUNIT) + player->viewz = player->mo->ceilingz - 4 * FRACUNIT; + +// The following line was in the Id source and appears // phares 2/25/98 +// to be a bug. player->viewz is checked in a similar +// manner at a different exit below. + +// player->viewz = player->mo->z + player->viewheight; + return; + } + + angle = (FINEANGLES / 20 * _g->leveltime) & FINEMASK; + bob = FixedMul(player->bob / 2, finesine[angle]); + + // move viewheight + + if (player->playerstate == PST_LIVE) + { + player->viewheight += player->deltaviewheight; + + if (player->viewheight > VIEWHEIGHT) + { + player->viewheight = VIEWHEIGHT; + player->deltaviewheight = 0; + } + + if (player->viewheight < VIEWHEIGHT / 2) + { + player->viewheight = VIEWHEIGHT / 2; + if (player->deltaviewheight <= 0) + player->deltaviewheight = 1; + } + + if (player->deltaviewheight) + { + player->deltaviewheight += FRACUNIT / 4; + if (!player->deltaviewheight) + player->deltaviewheight = 1; + } + } + + player->viewz = player->mo->z + player->viewheight + bob; + + if (player->viewz > player->mo->ceilingz - 4 * FRACUNIT) + player->viewz = player->mo->ceilingz - 4 * FRACUNIT; +} + +// +// P_MovePlayer +// +// Adds momentum if the player is not in the air +// +// killough 10/98: simplified +#if 0 +void P_MovePlayer (player_t* player) +{ + ticcmd_t* cmd; + + cmd = &player->cmd; + + player->mo->angle += (cmd->angleturn<onground = (player->mo->z <= player->mo->floorz); + + if (cmd->forwardmove && _g->onground) + P_Thrust (player, player->mo->angle, cmd->forwardmove*2048); + + if (cmd->sidemove && _g->onground) + P_Thrust (player, player->mo->angle-ANG90, cmd->sidemove*2048); + + if ( (cmd->forwardmove || cmd->sidemove) + && getMobjState(player->mo) == &states[S_PLAY] ) + { + P_SetMobjState (player->mo, S_PLAY_RUN1); + } +} +#else +static void P_MovePlayer(player_t *player) +{ + ticcmd_t *cmd = &player->cmd; + mobj_t *mo = player->mo; + + mo->angle += cmd->angleturn << 16; + _g->onground = mo->z <= mo->floorz; + + // killough 10/98: + // + // We must apply thrust to the player and bobbing separately, to avoid + // anomalies. The thrust applied to bobbing is always the same strength on + // ice, because the player still "works just as hard" to move, while the + // thrust applied to the movement varies with 'movefactor'. + + //e6y + if ((cmd->forwardmove | cmd->sidemove)) // killough 10/98 + { + if (_g->onground) // killough 8/9/98 + { + int movefactor = ORIG_FRICTION_FACTOR; + + if (cmd->forwardmove) + { + P_Bob(player, mo->angle, cmd->forwardmove * movefactor); + P_Thrust(player, mo->angle, cmd->forwardmove * movefactor); + } + + if (cmd->sidemove) + { + P_Bob(player, mo->angle - ANG90, cmd->sidemove * movefactor); + P_Thrust(player, mo->angle - ANG90, cmd->sidemove * movefactor); + } + } + //if (mo->state == states+S_PLAY) + if (mo->state_idx == S_PLAY) + P_SetMobjState(mo, S_PLAY_RUN1); + } +} + +#endif +#define ANG5 (ANG90/18) + +// +// P_DeathThink +// Fall on your face when dying. +// Decrease POV height to floor height. +// + +static void P_DeathThink(player_t *player) +{ + angle_t angle; + angle_t delta; + + P_MovePsprites(player); + + // fall to the ground + + if (player->viewheight > 6 * FRACUNIT) + player->viewheight -= FRACUNIT; + + if (player->viewheight < 6 * FRACUNIT) + player->viewheight = 6 * FRACUNIT; + + player->deltaviewheight = 0; + _g->onground = (player->mo->z <= player->mo->floorz); + P_CalcHeight(player); + + if (player->attacker && player->attacker != player->mo) + { + angle = R_PointToAngle2(player->mo->x, player->mo->y, player->attacker->x, player->attacker->y); + + delta = angle - player->mo->angle; + + if (delta < ANG5 || delta > (unsigned) -ANG5) + { + // Looking at killer, + // so fade damage flash down. + + player->mo->angle = angle; + + if (player->damagecount) + player->damagecount--; + } + else if (delta < ANG180) + player->mo->angle += ANG5; + else + player->mo->angle -= ANG5; + } + else if (player->damagecount) + player->damagecount--; + + if (player->cmd.buttons & BT_USE) + player->playerstate = PST_REBORN; + +} + +// +// P_PlayerThink +// + +void P_PlayerThink(player_t *player) +{ + ticcmd_t *cmd; + weapontype_t newweapon; + + // killough 2/8/98, 3/21/98: + if (player->cheats & CF_NOCLIP) + player->mo->flags |= MF_NOCLIP; + else + player->mo->flags &= ~MF_NOCLIP; + + // chain saw run forward + + cmd = &player->cmd; + if (player->mo->flags & MF_JUSTATTACKED) + { + cmd->angleturn = 0; + cmd->forwardmove = 0xc800 / 512; + cmd->sidemove = 0; + player->mo->flags &= ~MF_JUSTATTACKED; + } + + if (player->playerstate == PST_DEAD) + { + P_DeathThink(player); + return; + } + + // Move around. + // Reactiontime is used to prevent movement + // for a bit after a teleport. + + if (player->mo->reactiontime) + player->mo->reactiontime--; + else + P_MovePlayer(player); + + P_CalcHeight(player); // Determines view height and bobbing + + // Determine if there's anything about the sector you're in that's + // going to affect you, like painful floors. + + if (getMobjSubsector(player->mo)->sector->special) + P_PlayerInSpecialSector(player); + + // Check for weapon change. + + if (cmd->buttons & BT_CHANGE) + { + // The actual changing of the weapon is done + // when the weapon psprite can do it + // (read: not in the middle of an attack). + + newweapon = (cmd->buttons & BT_WEAPONMASK) >> BT_WEAPONSHIFT; + + // killough 2/8/98, 3/22/98 -- end of weapon selection changes + + if (player->weaponowned[newweapon] && newweapon != player->readyweapon) + + // Do not go to plasma or BFG in shareware, + // even if cheated. + + if ((newweapon != wp_plasma && newweapon != wp_bfg) || (_g->gamemode != shareware)) + player->pendingweapon = newweapon; + } + + // check for use + + if (cmd->buttons & BT_USE) + { + if (!player->usedown) + { + P_UseLines(player); + player->usedown = true; + } + } + else + player->usedown = false; + + // cycle psprites + + P_MovePsprites(player); + + // Counters, time dependent power ups. + + // Strength counts up to diminish fade. + + if (player->powers[pw_strength]) + player->powers[pw_strength]++; + + // killough 1/98: Make idbeholdx toggle: + + if (player->powers[pw_invulnerability] > 0) // killough + player->powers[pw_invulnerability]--; + + if (player->powers[pw_invisibility] > 0) // killough + if (!--player->powers[pw_invisibility]) + player->mo->flags &= ~MF_SHADOW; + + if (player->powers[pw_infrared] > 0) // killough + player->powers[pw_infrared]--; + + if (player->powers[pw_ironfeet] > 0) // killough + player->powers[pw_ironfeet]--; + + if (player->damagecount) + player->damagecount--; + + if (player->bonuscount) + player->bonuscount--; + + // Handling colormaps. + // killough 3/20/98: reformat to terse C syntax + + player->fixedcolormap = + player->powers[pw_invulnerability] > 4 * 32 || (player->powers[pw_invulnerability] & 8) ? INVERSECOLORMAP : player->powers[pw_infrared] > 4 * 32 || (player->powers[pw_infrared] & 8); +} diff --git a/doom/src/pdoom/Doom/source/r_data.c b/doom/src/pdoom/Doom/source/r_data.c new file mode 100644 index 0000000..aa4c442 --- /dev/null +++ b/doom/src/pdoom/Doom/source/r_data.c @@ -0,0 +1,651 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Preparation of data for rendering, + * generation of lookups, caching, retrieval by name. + * + * next-hack: code for caching texture and texture data to flash. + * modified load texture to support caching to flash. + * texture heights array stored to flash to save some hundreds bytes. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "w_wad.h" +#include "r_draw.h" +#include "r_main.h" +#include "r_sky.h" +#include "i_system.h" +#include "r_things.h" +#include "p_tick.h" +#include "lprintf.h" // jff 08/03/98 - declaration of lprintf +#include "p_tick.h" + +#include "global_data.h" +#include "i_spi_support.h" +// +// Graphics. +// DOOM graphics for walls and sprites +// is stored in vertical runs of opaque pixels (posts). +// A column is composed of zero or more posts, +// a patch or sprite is composed of zero or more columns. +// + +// +// Texture definition. +// Each texture is composed of one or more patches, +// with patches being lumps stored in the WAD. +// The lumps are referenced by number, and patched +// into the rectangular texture space using origin +// and possibly other attributes. +// + +typedef struct +{ + short originx; + short originy; + short patch; + short stepdir; // unused in Doom but might be used in Phase 2 Boom + short colormap; // unused in Doom but might be used in Phase 2 Boom +} PACKEDATTR mappatch_t; + +typedef struct +{ + char name[8]; + char pad2[4]; // unused + short width; + short height; + char pad[4]; // unused in Doom but might be used in Boom Phase 2 + short patchcount; + mappatch_t patches[1]; +} PACKEDATTR maptexture_t; +// +// this to suppress compiler warnings, as strupr is not always implemented. +// +#define strupr d_strupr +static char* strupr(char *string) +{ + int i = 0; + while (string[i] != 0) + { + if (string[i] >= 'a' && string[i] <= 'z') + { + string[i] = string[i] - 'a' + 'A'; + } + i++; + } + return string; +} +// A maptexturedef_t describes a rectangular texture, which is composed +// of one or more mappatch_t structures that arrange graphic patches. + +uint32_t getTextureStructSize(int texture_num) +{ + const int *maptex1, *maptex2; + int numtextures1, numtextures2; + const int *directory1, *directory2; + + maptex1 = W_CacheLumpName("TEXTURE1"); + spiFlashSetAddress((uint32_t) maptex1); + spiFlashGetData(&numtextures1, sizeof(numtextures1)); + //numtextures1 = *maptex1; + directory1 = maptex1 + 1; + + if (W_CheckNumForName("TEXTURE2") != -1) + { + maptex2 = W_CacheLumpName("TEXTURE2"); + spiFlashSetAddress((uint32_t) maptex2); + spiFlashGetData(&numtextures2, sizeof(numtextures2)); + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + numtextures2 = 0; + directory2 = NULL; + } + + int offset = 0; + const int *maptex = maptex1; + + if (texture_num < numtextures1) + { + + //offset = directory1[texture_num]; + spiFlashSetAddress((uint32_t) directory1 + texture_num * sizeof(directory1[0])); + spiFlashGetData(&offset, sizeof(offset)); + } + else if (maptex2 && ((texture_num - numtextures1) < numtextures2)) + { + maptex = maptex2; + //offset = directory2[texture_num-numtextures1]; + spiFlashSetAddress((uint32_t) directory2 + (texture_num - numtextures1) * sizeof(directory2[0])); + spiFlashGetData(&offset, sizeof(offset)); + } + + const maptexture_t *mtexture = (const maptexture_t*) ((const byte*) maptex + offset); + spiFlashSetAddress((uint32_t) &mtexture->patchcount); + short patchcount = spiFlashGetShort(); + int size = sizeof(const texture_t) + sizeof(const texpatch_t) * (patchcount - 1); + printf("Size text %d\r\n", size); + return size; +} +/** + * This will fill the textureheight array. This must be called when textureheight is in RAM, + * i.e. only in the init function! + */ +void R_FillTextureHeightData() +{ + const byte *pnames = W_CacheLumpName("PNAMES"); + + //Skip to list of names. + pnames += 4; + + const int *maptex1, *maptex2; + int numtextures1, numtextures2; + const int *directory1, *directory2; + + maptex1 = W_CacheLumpName("TEXTURE1"); + spiFlashSetAddress((uint32_t) maptex1); + spiFlashGetData(&numtextures1, sizeof(numtextures1)); + //numtextures1 = *maptex1; + directory1 = maptex1 + 1; + + if (W_CheckNumForName("TEXTURE2") != -1) + { + maptex2 = W_CacheLumpName("TEXTURE2"); + spiFlashSetAddress((uint32_t) maptex2); + spiFlashGetData(&numtextures2, sizeof(numtextures2)); + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + numtextures2 = 0; + directory2 = NULL; + } + for (int texture_num = 0; texture_num < _g->numtextures; texture_num++) + { + int offset = 0; + const int *maptex = maptex1; + if (texture_num < numtextures1) + { + + //offset = directory1[texture_num]; + spiFlashSetAddress((uint32_t) directory1 + texture_num * sizeof(directory1[0])); + spiFlashGetData(&offset, sizeof(offset)); + } + else if (maptex2 && ((texture_num - numtextures1) < numtextures2)) + { + maptex = maptex2; + //offset = directory2[texture_num-numtextures1]; + spiFlashSetAddress((uint32_t) directory2 + (texture_num - numtextures1) * sizeof(directory2[0])); + spiFlashGetData(&offset, sizeof(offset)); + } + else + { + I_Error("R_LoadTexture: Texture %d not in range.", texture_num); + } + maptexture_t *mtexture_addr = (maptexture_t*) ((const byte*) maptex + offset); + maptexture_t mtexture; + spiFlashSetAddress((uint32_t) mtexture_addr); + spiFlashGetData(&mtexture, sizeof(mtexture)); + textureheight[texture_num] = mtexture.height << FRACBITS; + if (mtexture.height > 128) + { + printf(">>>>Warning, found a texture %d with height %d > 128.\r\n" + " >>>> This will cause problem in drawcolumnInCache()\r\n" + " >>>> To solve this issue, increase columnCacheBuffer size and reduce MAX_STATIC_ZONE to fit RAM\r\n", texture_num, mtexture.height); + } + } +} +static const texture_t* R_LoadTexture(int texture_num, boolean cacheToFlash, uint32_t *spaceRequired) +{ + uint32_t spaceReq = 0; + if (spaceRequired == NULL) + spaceRequired = &spaceReq; + const byte *pnames = W_CacheLumpName("PNAMES"); + + //Skip to list of names. + pnames += 4; + + const int *maptex1, *maptex2; + int numtextures1, numtextures2; + const int *directory1, *directory2; + + maptex1 = W_CacheLumpName("TEXTURE1"); + spiFlashSetAddress((uint32_t) maptex1); + spiFlashGetData(&numtextures1, sizeof(numtextures1)); + //numtextures1 = *maptex1; + directory1 = maptex1 + 1; + + if (W_CheckNumForName("TEXTURE2") != -1) + { + maptex2 = W_CacheLumpName("TEXTURE2"); + spiFlashSetAddress((uint32_t) maptex2); + spiFlashGetData(&numtextures2, sizeof(numtextures2)); + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + numtextures2 = 0; + directory2 = NULL; + } + + int offset = 0; + const int *maptex = maptex1; + if (texture_num < numtextures1) + { + + //offset = directory1[texture_num]; + spiFlashSetAddress((uint32_t) directory1 + texture_num * sizeof(directory1[0])); + spiFlashGetData(&offset, sizeof(offset)); + } + else if (maptex2 && ((texture_num - numtextures1) < numtextures2)) + { + maptex = maptex2; + //offset = directory2[texture_num-numtextures1]; + spiFlashSetAddress((uint32_t) directory2 + (texture_num - numtextures1) * sizeof(directory2[0])); + spiFlashGetData(&offset, sizeof(offset)); + } + else + { + I_Error("R_LoadTexture: Texture %d not in range.", texture_num); + } + maptexture_t *mtexture_addr = (maptexture_t*) ((const byte*) maptex + offset); + maptexture_t mtexture; + spiFlashSetAddress((uint32_t) mtexture_addr); + spiFlashGetData(&mtexture, sizeof(mtexture)); + texture_t *texture; + if (cacheToFlash) + { + texture = Z_Malloc(sizeof(texture_t) + sizeof(texpatch_t) * (mtexture.patchcount - 1), PU_STATIC, NULL); + } + else + { + texture = Z_Malloc(sizeof(texture_t) + sizeof(texpatch_t) * (mtexture.patchcount - 1), PU_LEVEL, (void** )&textures[texture_num]); + } + texture->width = mtexture.width; + texture->height = mtexture.height; + texture->patchcount = mtexture.patchcount; + // texture->name = mtexture->name; // 2021/03/06: next-hack removed, useless + + texpatch_t *patch = texture->patches; + const mappatch_t *mpatch_addr = mtexture_addr->patches; + + texture->overlapped = 0; + + for (int j = 0; j < texture->patchcount; j++, mpatch_addr++, patch++) + { + mappatch_t mpatch; + spiFlashSetAddress((uint32_t) mpatch_addr); + spiFlashGetData(&mpatch, sizeof(mpatch)); + patch->originx = mpatch.originx; + patch->originy = mpatch.originy; +// printf ("data: 0x%08x, ox,y: %d,%d\r\n",(uint32_t)mpatch_addr, mpatch.originx, mpatch.originy); + char pname[8]; + char mpatchpname[8]; + spiFlashSetAddress((uint32_t) &pnames[mpatch.patch * 8]); + spiFlashGetData(mpatchpname, sizeof(mpatchpname)); + strncpy(pname, (const char*) mpatchpname, 8); + int lumpNum = W_GetNumForName(pname); + filelump_t fl; + getFileLumpByNum(lumpNum, &fl); + // will the texture fit in flash? + if (getUserFlashRegionRemainingSpace() >= *spaceRequired + fl.size) + { + patch->patch = getAddressOrCacheLumpNum(lumpNum, true, FLASH_LEVEL_REGION); + } + else + { + patch->patch = (const patch_t*) W_CacheLumpNum(lumpNum); + } + } + for (int j = 0; j < texture->patchcount; j++) + { + const texpatch_t *patch = &texture->patches[j]; + //Check for patch overlaps. + int l1 = patch->originx; + short ppw; + if (isOnExternalFlash(&patch->patch->width)) + { + spiFlashSetAddress((uint32_t) &patch->patch->width); + ppw = spiFlashGetShort(); + } + else + { + ppw = patch->patch->width; + } + int r1 = l1 + ppw; + + for (int k = j + 1; k < texture->patchcount; k++) + { + if (k == j) + continue; + + const texpatch_t *p2 = &texture->patches[k]; + + //Check for patch overlaps. + int l2 = p2->originx; + if (isOnExternalFlash(&p2->patch->width)) + { + spiFlashSetAddress((uint32_t) &p2->patch->width); + ppw = spiFlashGetShort(); + } + else + { + ppw = p2->patch->width; + } + int r2 = l2 + ppw; + if (r1 > l2 && l1 < r2) + { + texture->overlapped = 1; + break; + } + } + + if (texture->overlapped) + break; + } + + int w; + + for (w = 1; w * 2 <= texture->width; w <<= 1); + texture->widthmask = w - 1; + // Removed below, it is done in R_FillTextureHeightData() + //textureheight[texture_num] = texture->height<= _g->numtextures) + return NULL; + + if (textures[texture]) + return textures[texture]; + + const texture_t *t = R_LoadTexture(texture, cacheToFlash, spaceRequired); + + textures[texture] = t; + + return t; +} + +static int R_GetTextureNumForName(const char *tex_name) +{ + const int *maptex1, *maptex2; + int numtextures1; + const int *directory1, *directory2; + + //Convert name to uppercase for comparison. + char tex_name_upper[9]; + + strncpy(tex_name_upper, tex_name, 8); + tex_name_upper[8] = 0; //Ensure null terminated. + + strupr(tex_name_upper); + + //if(_g->tex_lookup_last_name && (!strncmp(_g->tex_lookup_last_name, tex_name_upper, 8))) + if (_g->tex_lookup_valid && (!strncmp((char*__restrict) _g->tex_lookup_last_name, tex_name_upper, 8))) + { + return _g->tex_lookup_last_num; + } + + maptex1 = W_CacheLumpName("TEXTURE1"); + spiFlashSetAddress((uint32_t) maptex1); + //numtextures1 = *maptex1; + spiFlashGetData(&numtextures1, sizeof(numtextures1)); + directory1 = maptex1 + 1; + + if (W_CheckNumForName("TEXTURE2") != -1) + { + maptex2 = W_CacheLumpName("TEXTURE2"); + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + directory2 = NULL; + } + + const int *directory = directory1; + const int *maptex = maptex1; + + for (int i = 0; i < _g->numtextures; i++, directory++) + { + if (i == numtextures1) + { + // Start looking in second texture file. + maptex = maptex2; + directory = directory2; + } + + int offset; //= *directory; + spiFlashSetAddress((uint32_t) directory); + spiFlashGetData(&offset, sizeof(offset)); + const maptexture_t *mtexture = (const maptexture_t*) ((const byte*) maptex + offset); + spiFlashSetAddress((uint32_t) &mtexture->name); + char texturename[8]; + spiFlashGetData(texturename, sizeof(texturename)); + if (!strncmp(tex_name_upper, texturename, 8)) + { + strncpy((char*__restrict) _g->tex_lookup_last_name, texturename, 8); + _g->tex_lookup_valid = true; + _g->tex_lookup_last_num = i; + return i; + } + } + return -1; +} + +int R_LoadTextureByName(const char *tex_name, boolean cacheToFlash) +{ + if (tex_name[0] == '-') + return NO_TEXTURE; + + int tnum = R_GetTextureNumForName(tex_name); + + if (tnum == -1) + { + printf("texture name: %s not found.\n", tex_name); + return NO_TEXTURE; + } + + R_GetTexture(tnum, cacheToFlash, NULL); + + return tnum; +} + +// +// R_InitTextures +// Initializes the texture list +// with the textures from the world map. +// + +static void R_InitTextures() +{ + const int *mtex1 = W_CacheLumpName("TEXTURE1"); + spiFlashSetAddress((uint32_t) mtex1); + int numtextures1 = 0; + spiFlashGetData(&numtextures1, sizeof(numtextures1)); + // + int numtextures2 = 0; + if (W_CheckNumForName("TEXTURE2") != -1) + { + const int *mtex2 = W_CacheLumpName("TEXTURE2"); + spiFlashSetAddress((uint32_t) mtex2); + spiFlashGetData(&numtextures2, sizeof(numtextures2)); + } + printf("Numtextures %d %d add %x\r\n", numtextures1, numtextures2, mtex1); + _g->numtextures = numtextures1 + numtextures2; + p_wad_immutable_flash_data->numtextures = _g->numtextures; + // + textures = Z_Malloc(_g->numtextures * sizeof *textures, PU_STATIC, 0); + memset(textures, 0, _g->numtextures * sizeof *textures); + // + textureheight = Z_Malloc(_g->numtextures * sizeof *textureheight, PU_STATIC, 0); + memset(textureheight, 0, _g->numtextures * sizeof *textureheight); + + texturetranslation = Z_Malloc((_g->numtextures + 1) * sizeof *texturetranslation, PU_STATIC, 0); + + for (int i = 0; i < _g->numtextures; i++) + { + texturetranslation[i] = i; + } + // get texture height, and store them in flash; + R_FillTextureHeightData(); + p_wad_immutable_flash_data->textureheight = writeBufferToFlashRegion(textureheight, _g->numtextures * sizeof *textureheight, FLASH_IMMUTABLE_REGION, true); + Z_Free(textureheight); + textureheight = p_wad_immutable_flash_data->textureheight; +} +// +// R_InitFlats +// +static void R_InitFlats(void) +{ + int i; + + _g->firstflat = W_GetNumForName("F_START") + 1; + _g->lastflat = W_GetNumForName("F_END") - 1; + _g->numflats = _g->lastflat - _g->firstflat + 1; + + // Create translation table for global animation. + // killough 4/9/98: make column offsets 32-bit; + // clean up malloc-ing to use sizeof + + flattranslation = Z_Malloc((_g->numflats + 1) * sizeof(*flattranslation), PU_STATIC, 0); + + for (i = 0; i < _g->numflats; i++) + flattranslation[i] = i; +} + +// +// R_InitSpriteLumps +// Finds the width and hoffset of all sprites in the wad, +// so the sprite does not need to be cached completely +// just for having the header info ready during rendering. +// +static void R_InitSpriteLumps(void) +{ + _g->firstspritelump = W_GetNumForName("S_START") + 1; + _g->lastspritelump = W_GetNumForName("S_END") - 1; + _g->numspritelumps = _g->lastspritelump - _g->firstspritelump + 1; +} + +// +// R_InitColormaps +// +/* + void R_InitColormaps (void) + { + int lump = W_GetNumForName("COLORMAP"); + colormaps = W_CacheLumpNum(lump); + } + */ +// +// R_InitData +// Locates all the lumps +// that will be used by all views +// Must be called after W_Init. +// +void R_InitData(void) +{ + initImmutableFlashRegion(); + lprintf(LO_INFO, "Textures"); + R_InitTextures(); + lprintf(LO_INFO, "Flats"); + R_InitFlats(); + lprintf(LO_INFO, "Sprites"); + R_InitSpriteLumps(); + //lprintf(LO_INFO, "Colormaps"); + //R_InitColormaps(); // killough 3/20/98 +} + +// +// R_FlatNumForName +// Retrieval, get a flat number for a flat name. +// +// killough 4/17/98: changed to use ns_flats namespace +// + +int R_FlatNumForName(const char *name) // killough -- const added +{ + int i = W_CheckNumForName(name); + + if (i == -1) + I_Error("R_FlatNumForName: %.8s not found", name); + return i - _g->firstflat; +} + +// +// R_CheckTextureNumForName +// Check whether texture is available. +// Filter out NoTexture indicator. +// +// Rewritten by Lee Killough to use hash table for fast lookup. Considerably +// reduces the time needed to start new levels. See w_wad.c for comments on +// the hashing algorithm, which is also used for lump searches. +// +// killough 1/21/98, 1/31/98 +// + +int PUREFUNC R_CheckTextureNumForName(const char *name) +{ + // "NoTexture" marker. + if (name[0] == '-') + return 0; + + return R_GetTextureNumForName(name); +} diff --git a/doom/src/pdoom/Doom/source/r_draw.c b/doom/src/pdoom/Doom/source/r_draw.c new file mode 100644 index 0000000..086902e --- /dev/null +++ b/doom/src/pdoom/Doom/source/r_draw.c @@ -0,0 +1,95 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * The actual span/column drawing functions. + * Here find the main potential for optimization, + * e.g. inline assembly, different algorithms. + * + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_draw.h" +#include "v_video.h" +#include "st_stuff.h" +#include "g_game.h" +#include "am_map.h" +#include "lprintf.h" +#include "i_video.h" + +#include "global_data.h" + +// +// All drawing to the view buffer is accomplished in this file. +// The other refresh files only know about ccordinates, +// not the architecture of the frame buffer. +// Conveniently, the frame buffer is a linear one, +// and we need only the base address, +// and the total size == width*height*depth/8., +// + +// +// Spectre/Invisibility. +// + +void R_SetDefaultDrawColumnVars(draw_column_vars_t *dcvars) +{ + dcvars->x = dcvars->yl = dcvars->yh = 0; + dcvars->iscale = dcvars->texturemid = 0; + dcvars->source = NULL; + dcvars->colormap = p_wad_immutable_flash_data->colormaps; + dcvars->translation = NULL; +} + +// +// R_InitBuffer +// Creats lookup tables that avoid +// multiplies and other hazzles +// for getting the framebuffer address +// of a pixel to draw. +// + +void R_InitBuffer() +{ + // Same with base row offset. + I_StartDisplay(); + drawvars.byte_topleft = _g->screens[0].data; +} diff --git a/doom/src/pdoom/Doom/source/r_fast_stuff.c b/doom/src/pdoom/Doom/source/r_fast_stuff.c new file mode 100644 index 0000000..1944668 --- /dev/null +++ b/doom/src/pdoom/Doom/source/r_fast_stuff.c @@ -0,0 +1,5890 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * next-hack: originally doomhack moved in this file (he named it + * r_hotpath.iwram.c) many functions taken from various files (r_draw.c, + * r_main.c, p_tick.c etc.) to be put on GBA IWRAM for speed. + * Now, there is no IWRAM on this system, so this file has been renamed + * to r_fast_Stuff.c. Progressively all the functions and corresponding + * variables will be brought back home (to their original positions). + * modifications: + * - Ton of modified code to work with short pointers. + * - removed texture cache (occupied 16kB) + * - Added back Z-depth Light (almost no ram penalty) + * - Added support for partial framebuffer. + * - Adapted to 240x240 display + * - Added support to fetch graphics data from SPI (sprites and patches) + * - Data from QSPI is fetched by DMA and this is done while the previous + * column is being drawn, speeding up everything. + * - Openings are copied by words and not bytes. + * - Removed composite textures: the wad converter already prerenders + * the composite texture to a single patch. + * - Current color map is copied to ram if the number of pixel being + * drawn is larger than 16. If the next column/span to be drawn has the + * same flash address as before, then the cached palette on RAM is used + * without copying and regardless the drawing size. + * - flats drawn to buffer at 4 pixels at once. + * - better ASM code when drawing column, to avoid unaligned 32 bit instructions. + * - and more. + * + *-----------------------------------------------------------------------------*/ + +#pragma GCC optimize ("Ofast") // we need to compile this code to be as fast as possible. +#pragma GCC optimize ("align-functions=16") +#include "main.h" +#include "nrf.h" +#define D_SHRT_MAX 0x7FFF + +#define PITCH_STR2(x) #x +#define PITCH_STR1(x) PITCH_STR2(x) +#define PITCH_STR PITCH_STR1(SCREENWIDTH_PHYSICAL) +#define FASTFUN //__attribute__((used, section(".data"))) + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define CURRENT_COLOR_MAP_IDX 253 +#define FIXED_COLOR_MAP_IDX 254 +#define SHADOW_COLOR_MAP_IDX 255 +#define FULL_COLOR_MAP_IDX 0 + +#include "i_spi_support.h" +#include "doomstat.h" +#include "d_net.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_things.h" +#include "r_plane.h" +#include "r_draw.h" +#include "m_bbox.h" +#include "r_sky.h" +#include "v_video.h" +#include "lprintf.h" +#include "st_stuff.h" +#include "i_main.h" +#include "i_system.h" +#include "g_game.h" +#include "m_random.h" + +#include "global_data.h" +#include "printf.h" +#include "i_memory.h" +// Note about openings. These are also used to store the column of the texture. +// We cannot use a byte, because it would give only 0 trough 255, but textures +// as wide as 256 exist, and we need an n+1 value to mark the opening as +// already checked. +#define NEGONEARRAY_PTR 1 +#define SCREENHEIGHTARRAY_PTR 2 +// let's put openings-related data in .openings_bss section +// this to make sure that openings are in the lower 128k so we can use short ptr +__attribute__ ((section(".openings_bss"))) short openings[MAXOPENINGS]; +__attribute__ ((section(".openings_bss"))) short floorclip[SCREENWIDTH]; +__attribute__ ((section(".openings_bss"))) short ceilingclip[SCREENWIDTH]; +// +#define MAX_PATCH_WIDTH 320 +// colormap cching +// note: for a single column or span, 16 pixel is sub optimal. But the likelyhood that the same color map will be used again is high +// therefore we sacrifice the first drawing, for the sake of the next ones. +#define MIN_PIXEL_TO_DRAW_FOR_CACHING_COLORMAP 16 +static uint8_t colorMap[256]; // for faster drawing +static uint8_t *currentCachedColorMap = NULL; +static uint8_t columnBuffer[2][MAX_COLUMN_DATA]; +// +patch_t * cachedColumnOffsetDataPatch = NULL; +static uint32_t columnOffsetData[MAX_PATCH_WIDTH]; + + +#define MAX_BSP_DEPTH 128 +short bspstack[MAX_BSP_DEPTH]; // see R_RenderBSPNode for description + +#if MMULTIPATCH_TEXTURE_SUPPORTULT +uint8_t columnCacheBuffer[128]; +#endif +// next-hack +short draw_starty; // inclusive +short draw_stopy; // inclusive +// + + +//***************************************** +//Globals. +//***************************************** +typedef int16_t small_int_t; //to optimize. +short numnodes; +const mapnode_t *nodes; + +fixed_t viewx, viewy, viewz; + +angle_t viewangle; + +static byte solidcol[MAX_SCREENWIDTH]; + +static byte spanstart[MAX_SCREENHEIGHT - ST_SCALED_HEIGHT]; // killough 2/8/98 + +static const seg_t *curline; +static side_t *sidedef; +static const line_t *linedef; +static sector_t *frontsector; +static sector_t *backsector; +static drawseg_t *ds_p; + +static visplane_t *floorplane, *ceilingplane; +static int rw_angle1; + +static angle_t rw_normalangle; // angle to line origin +static fixed_t rw_distance; + +static small_int_t rw_stopx; + +static fixed_t rw_scale; +static fixed_t rw_scalestep; + +static int worldtop; +static int worldbottom; + +static boolean didsolidcol; /* True if at least one column was marked solid */ + +// True if any of the segs textures might be visible. +static boolean segtextured; +static boolean markfloor; // False if the back side is the same plane. +static boolean markceiling; +static boolean maskedtexture; +static small_int_t toptexture; +static small_int_t bottomtexture; +static small_int_t midtexture; + +static fixed_t rw_midtexturemid; +static fixed_t rw_toptexturemid; +static fixed_t rw_bottomtexturemid; + +const lighttable_t *fullcolormap; +const lighttable_t *fixedcolormap; + +byte extralight; // bumped light from gun blasts +draw_vars_t drawvars; + +static ycoord_t *mfloorclip; // dropoff overflow +static ycoord_t *mceilingclip; // dropoff overflow +static volatile uint8_t mfloorceiling_ptr_size = sizeof(ycoord_t); +static fixed_t spryscale; +static fixed_t sprtopscreen; + +static angle_t rw_centerangle; +static fixed_t rw_offset; +static small_int_t rw_lightlevel; + +static short *maskedtexturecol; // dropoff overflow + +const texture_t **textures; // proff - 04/05/2000 removed static for OpenGL +fixed_t *textureheight; //needed for texture pegging (and TFE fix - killough) + +short *flattranslation; // for global animation +short *texturetranslation; + +fixed_t basexscale, baseyscale; + +fixed_t viewcos, viewsin; + +static fixed_t topfrac; +static fixed_t topstep; +static fixed_t bottomfrac; +static fixed_t bottomstep; + +static fixed_t pixhigh; +static fixed_t pixlow; + +static fixed_t pixhighstep; +static fixed_t pixlowstep; + +static int worldhigh; +static int worldlow; + +//static lighttable_t current_colormap[256]; // why do we need this anyway? +static const lighttable_t *current_colormap_ptr; + +static uint8_t planezlight; +static uint8_t spritelights; +static uint8_t walllights; + +static fixed_t planeheight; + +size_t num_vissprite; + +extern los_t los; + +//***************************************** +// Constants +//***************************************** + +const int viewheight = SCREENHEIGHT - ST_SCALED_HEIGHT; +const int centery = (SCREENHEIGHT - ST_SCALED_HEIGHT) / 2; +#define CHEIGHT (SCREENHEIGHT / SCREENHEIGHT * SCREENWIDTH * 3 / 4 ) // yes, I know, it makes SCREENWIDTH*3/4, just to remember. +#define BASEYCENTER (100 * CHEIGHT / SCREENHEIGHT) + +static const int centerxfrac = (SCREENWIDTH / 2) << FRACBITS; + +static const int centeryfrac = ((SCREENHEIGHT - ST_SCALED_HEIGHT) / 2) << FRACBITS; + +const fixed_t projection = (SCREENWIDTH / 2) << FRACBITS; +const fixed_t iprojection = ( FRACUNIT / (SCREENWIDTH / 2)); + +static const fixed_t projectiony = (((int64_t)(CHEIGHT * (SCREENWIDTH / 2) * 320) / 200) * FRACUNIT / SCREENWIDTH); + +static const fixed_t pspritescale = FRACUNIT * SCREENWIDTH / 320; +static const fixed_t pspriteiscale = FRACUNIT * 320 / SCREENWIDTH; + +static const fixed_t pspriteyscale = (((CHEIGHT * SCREENWIDTH) / SCREENWIDTH) << FRACBITS) / 200; + +static const angle_t clipangle = 537395200; //xtoviewangle[0]; + +static const int skytexturemid = 100 * FRACUNIT; +static const fixed_t skyiscale = (FRACUNIT * 200) / (SCREENHEIGHT - ST_SCALED_HEIGHT); + +#ifdef HIGHRES +typedef byte pixel; +#else +typedef short pixel; +#endif +// + +#define check_limits(ptr) (((uint32_t) ptr) > RAM_PTR_BASE && ((uint32_t)ptr) < RAM_PTR_BASE + 524288) +#define check_rom_limits(ptr) (((uint32_t) ptr) > EXT_FLASH_BASE && ((uint32_t)ptr) < EXT_FLASH_BASE + 1024*1024*4) +static inline void fastOpeningsCopy(short *dest, short * source, int num); + +FASTFUN inline static void* ByteFind(byte *mem, byte val, unsigned int count) +{ + do + { + if (*mem == val) + return mem; + + mem++; + } while (--count); + + return NULL; +} + +FASTFUN inline fixed_t CONSTFUNC FixedMul(fixed_t a, fixed_t b) +{ + return (fixed_t) ((int_64_t) a * b >> FRACBITS); +} + +// killough 5/3/98: reformatted + +FASTFUN static CONSTFUNC int SlopeDiv(unsigned num, unsigned den) +{ + unsigned int ans; + + if (den < 512) + return SLOPERANGE; + + ans = (num << 3) / (den >> 8); + + return ans <= SLOPERANGE ? ans : SLOPERANGE; +} + +// +// R_PointOnSide +// Traverse BSP (sub) tree, +// check point against partition plane. +// Returns side 0 (front) or 1 (back). +// +// killough 5/2/98: reformatted +// + +FASTFUN static PUREFUNC int R_PointOnSide(fixed_t x, fixed_t y, const mapnode_t *node) +{ + fixed_t dx = (fixed_t) node->dx << FRACBITS; + fixed_t dy = (fixed_t) node->dy << FRACBITS; + + fixed_t nx = (fixed_t) node->x << FRACBITS; + fixed_t ny = (fixed_t) node->y << FRACBITS; + + if (!dx) + return x <= nx ? node->dy > 0 : node->dy < 0; + + if (!dy) + return y <= ny ? node->dx < 0 : node->dx > 0; + + x -= nx; + y -= ny; + + // Try to quickly decide by looking at sign bits. + if ((dy ^ dx ^ x ^ y) < 0) + return (dy ^ x) < 0; // (left is negative) + + return FixedMul(y, node->dx) >= FixedMul(node->dy, x); +} +// +// 2021-03-13: forgot that switches have changeable textures... +FASTFUN static inline short getSideTopTexture(const line_t *line, const side_t *side) +{ + if (!line->const_special || side == &_g->sides[line->sidenum[1]]) + return side->toptexture; + // otherwise we are asking for side 0 of a special texture. + return _g->switch_texture_top[_g->linesChangeableTextureIndex[line->lineno]]; +} +FASTFUN static inline short getSideMidTexture(const line_t *line, const side_t *side) +{ + if (!line->const_special || side == &_g->sides[line->sidenum[1]]) + return side->midtexture; + // otherwise we are asking for side 0 of a special texture. + return _g->switch_texture_mid[_g->linesChangeableTextureIndex[line->lineno]]; +} +FASTFUN static inline short getSideBottomTexture(const line_t *line, const side_t *side) +{ + if (!line->const_special || side == &_g->sides[line->sidenum[1]]) + return side->bottomtexture; + // otherwise we are asking for side 0 of a special texture. + return _g->switch_texture_bot[_g->linesChangeableTextureIndex[line->lineno]]; +} +// +// R_PointInSubsector +// +// killough 5/2/98: reformatted, cleaned up +FASTFUN subsector_t* R_PointInSubsector(fixed_t x, fixed_t y) +{ + int nodenum = numnodes - 1; + + // special case for trivial maps (single subsector, no nodes) + if (numnodes == 0) + return _g->subsectors; + + while (!(nodenum & NF_SUBSECTOR)) + nodenum = nodes[nodenum].children[R_PointOnSide(x, y, nodes + nodenum)]; + return &_g->subsectors[nodenum & ~NF_SUBSECTOR]; +} + +// +// R_PointToAngle +// To get a global angle from cartesian coordinates, +// the coordinates are flipped until they are in +// the first octant of the coordinate system, then +// the y (<=x) is scaled and divided by x to get a +// tangent (slope) value which is looked up in the +// tantoangle[] table. +// + +FASTFUN CONSTFUNC angle_t R_PointToAngle2(fixed_t vx, fixed_t vy, fixed_t x, fixed_t y) +{ + x -= vx; + y -= vy; + + if ((!x) && (!y)) + return 0; + + if (x >= 0) + { + // x >=0 + if (y >= 0) + { + // y>= 0 + + if (x > y) + { + // octant 0 + return tantoangle[SlopeDiv(y, x)]; + } + else + { + // octant 1 + return ANG90 - 1 - tantoangle[SlopeDiv(x, y)]; + } + } + else + { + // y<0 + y = -y; + + if (x > y) + { + // octant 8 + return -tantoangle[SlopeDiv(y, x)]; + } + else + { + // octant 7 + return ANG270 + tantoangle[SlopeDiv(x, y)]; + } + } + } + else + { + // x<0 + x = -x; + + if (y >= 0) + { + // y>= 0 + if (x > y) + { + // octant 3 + return ANG180 - 1 - tantoangle[SlopeDiv(y, x)]; + } + else + { + // octant 2 + return ANG90 + tantoangle[SlopeDiv(x, y)]; + } + } + else + { + // y<0 + y = -y; + + if (x > y) + { + // octant 4 + return ANG180 + tantoangle[SlopeDiv(y, x)]; + } + else + { + // octant 5 + return ANG270 - 1 - tantoangle[SlopeDiv(x, y)]; + } + } + } +} + +FASTFUN static CONSTFUNC angle_t R_PointToAngle(fixed_t x, fixed_t y) +{ + return R_PointToAngle2(viewx, viewy, x, y); +} + +// killough 5/2/98: move from r_main.c, made static, simplified + +FASTFUN static CONSTFUNC fixed_t R_PointToDist(fixed_t x, fixed_t y) +{ + fixed_t dx = D_abs(x - viewx); + fixed_t dy = D_abs(y - viewy); + + if (dy > dx) + { + fixed_t t = dx; + dx = dy; + dy = t; + } + + return FixedApproxDiv(dx, finesine[(tantoangle[FixedApproxDiv(dy, dx) >> DBITS] + ANG90) >> ANGLETOFINESHIFT]); +} + +FASTFUN static const lighttable_t* R_ColourMap(int lightlevel) +{ + if (fixedcolormap) + return fixedcolormap; + else + { + if (curline) + { + if (curline->v1.y == curline->v2.y) + lightlevel -= 1 << LIGHTSEGSHIFT; + else if (curline->v1.x == curline->v2.x) + lightlevel += 1 << LIGHTSEGSHIFT; + } + + lightlevel += (extralight + _g->gamma) << LIGHTSEGSHIFT; + + int cm = ((256 - lightlevel) >> 2) - 24; + + if (cm >= NUMCOLORMAPS) + cm = NUMCOLORMAPS - 1; + else if (cm < 0) + cm = 0; + + return fullcolormap + cm * 256; + } +} + +/* 2021/05/11 next-hack removed, not used + static const lighttable_t* R_LoadColorMap(int lightlevel) + { + const lighttable_t* lm = R_ColourMap(lightlevel); + current_colormap_ptr = lm; + return current_colormap_ptr; + }*/ + +// +// A column is a vertical slice/span from a wall texture that, +// given the DOOM style restrictions on the view orientation, +// will always have constant z depth. +// Thus a special case loop for very fast rendering can +// be used. It has also been used with Wolfenstein 3D. +// +#define COLEXTRABITS 9 +#define COLBITS (FRACBITS + COLEXTRABITS) + +FASTFUN inline static void R_DrawColumnPixel(pixel *dest, const byte *source, const byte *colormap, unsigned int frac) +{ + *dest = colormap[source[frac >> COLBITS]]; +} + +FASTFUN /*__attribute__((used, section(".data")))*/ static void R_DrawColumn(const draw_column_vars_t *dcvars) +{ +#if 0 + int clip_yh = dcvars->yh > draw_stopy ? draw_stopy : dcvars->yh; + int clip_yl = dcvars->yl < draw_starty ? draw_starty : dcvars->yl; + // + // int count = (dcvars->yh - dcvars->yl) + 1; + int count = (clip_yh - clip_yl) + 1; + // Zero length, column does not exceed a pixel. + if (count <= 0) + return; + if (isOnExternalFlash(dcvars->source)) + { + printf("Error address on external flash\r\n"); + } + const byte *source = dcvars->source; + const byte *colormap = dcvars->colormap; + + pixel* dest = (( pixel*) drawvars.byte_topleft) + ScreenYToOffset(clip_yl) + dcvars->x; + + const unsigned int fracstep = (dcvars->iscale << COLEXTRABITS); + unsigned int frac = (dcvars->texturemid + (dcvars->yl - centery)*dcvars->iscale) << COLEXTRABITS; + // + frac += fracstep * (clip_yl - dcvars->yl); +#else + // + int count = (dcvars->yh - dcvars->yl) + 1; + // Zero length, column does not exceed a pixel. + + if (count <= 0) + return; + const byte *colormap; +#if CACHE_ALL_COLORMAP_TO_RAM + colormap = dcvars->colormap; +#else + // 2021-09-18 next-hack: faster ram access time + if (currentCachedColorMap == dcvars->colormap) + { + colormap =colorMap; + } + else if (count > MIN_PIXEL_TO_DRAW_FOR_CACHING_COLORMAP) + { + memcpy(colorMap, dcvars->colormap, 256); + currentCachedColorMap = (uint8_t*) dcvars->colormap; + colormap = colorMap; + } + else + { + colormap = dcvars->colormap; + } +#endif +#if CHECK_CACHING + if (isOnExternalFlash(dcvars->source)) + { + printf("Error address on external flash\r\n"); + } +#endif + const byte *source = dcvars->source; + + + pixel *dest = ((pixel*) drawvars.byte_topleft) + ScreenYToOffset(dcvars->yl) + dcvars->x; + + unsigned int fracstep = (dcvars->iscale << COLEXTRABITS); + unsigned int frac = (dcvars->texturemid + (dcvars->yl - centery) * dcvars->iscale) << COLEXTRABITS; + // + +#endif + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets. + + unsigned int l = (count >> 4); +#define BETTER_ASM_CODE 1 + #if BETTER_ASM_CODE + while (l--) + { + uint32_t fracShift; + uint32_t dummyTmp; + asm volatile + ( + ".align(2)\n\t" + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + "lsrs %[dummyTmp], %[frac], #25\n\t" + "add %[frac], %[fracStep]\n\t" + "ldrb %[dummyTmp], [%[source], %[dummyTmp]]\n\t" + "ldrb %[dummyTmp], [%[colormap], %[dummyTmp]]\n\t" + "strb %[dummyTmp], [%[dest]], #" PITCH_STR "\n\t" + + + : + [fracShift] "+l" (fracShift), + [frac] "+l" (frac), + [fracStep] "+r" (fracstep), + [dummyTmp] "+l" (dummyTmp), + [dest] "+l" (dest), + [colormap] "+l" (colormap), + [source] "+l" (source) + : : "cc" // TODO: we might avoid using -s istructions, and remove this. + ); +} + #else + while (l--) + { + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + } +#endif + unsigned int r = (count & 15); + + switch (r) + { + case 15: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 14: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 13: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 12: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 11: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 10: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 9: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 8: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 7: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 6: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 5: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 4: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 3: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 2: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 1: + R_DrawColumnPixel((pixel*) dest, source, colormap, frac); + } +} + +#define FUZZOFF (SCREENWIDTH) +#define FUZZTABLE 50 + +static const int fuzzoffset[FUZZTABLE] = +{ + FUZZOFF, -FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, + FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, + FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, + FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, + FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, + FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, + FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF, FUZZOFF, -FUZZOFF, FUZZOFF +}; + +// +// Framebuffer postprocessing. +// Creates a fuzzy image by copying pixels +// from adjacent ones to left and right. +// Used with an all black colormap, this +// could create the SHADOW effect, +// i.e. spectres and invisible players. +// +FASTFUN static void R_DrawFuzzColumn(const draw_column_vars_t *dcvars) +{ + int dc_yl = dcvars->yl; + int dc_yh = dcvars->yh; + + // Adjust borders. Low... + if (dc_yl <= 0) + dc_yl = 1; + + // .. and high. + if (dc_yh >= viewheight - 1) + dc_yh = viewheight - 2; + + int count = (dc_yh - dc_yl) + 1; + + // Zero length, column does not exceed a pixel. + if (count <= 0) + return; + + const byte *colormap = &fullcolormap[6 * 256]; + + pixel *dest = ((pixel*) drawvars.byte_topleft) + ScreenYToOffset(dc_yl) + dcvars->x; + + unsigned int fuzzpos = _g->fuzzpos; + + do + { + R_DrawColumnPixel((pixel*) dest, (const byte*) &dest[fuzzoffset[fuzzpos]], colormap, 0); + dest += SCREENWIDTH; + fuzzpos++; + + if (fuzzpos >= 50) + fuzzpos = 0; + + } while (--count); + + _g->fuzzpos = fuzzpos; +} + +// +// R_DrawMaskedColumn +// Used for sprites and masked mid textures. +// Masked means: partly transparent, i.e. stored +// in posts/runs of opaque pixels. +// +FASTFUN static inline void R_DrawMaskedColumn(R_DrawColumn_f colfunc, draw_column_vars_t *dcvars, const column_t *column) +{ +#if CHECK_CACHING + if (isOnExternalFlash(column)) + { + printf("Column in ext flash\r\n"); + while(1); + } +#endif + const fixed_t basetexturemid = dcvars->texturemid; + int fclip_x; //= ((byte*)mfloorclip)[dcvars->x]; + int cclip_x; //= ((byte*)mceilingclip)[dcvars->x]; +/* if (mfloorceiling_ptr_size == 1) + { + printf("pter size 1 can't clip. Blocking"); + while (1); + } + else*/ + { + fclip_x = mfloorclip[dcvars->x]; + cclip_x = mceilingclip[dcvars->x]; + } + while (column->topdelta != 0xff) + { + // calculate unclipped screen coordinates for post + const int topscreen = sprtopscreen + spryscale * column->topdelta; + const int bottomscreen = topscreen + spryscale * column->length; + + int yh = (bottomscreen - 1) >> FRACBITS; + int yl = (topscreen + FRACUNIT - 1) >> FRACBITS; +// if (!((yh < draw_starty ) || (yl > draw_stopy))) // if at least a part is within range of current buffer + { + if (yh >= fclip_x) + yh = fclip_x - 1; + + if (yl <= cclip_x) + yl = cclip_x + 1; + + // killough 3/2/98, 3/27/98: Failsafe against overflow/crash: + if (yh < viewheight && yl <= yh) + { + dcvars->source = (const byte*) column + 3; + + dcvars->texturemid = basetexturemid - (column->topdelta << FRACBITS); + + dcvars->yh = yh; + dcvars->yl = yl; + + // Drawn by either R_DrawColumn + // or (SHADOW) R_DrawFuzzColumn. + colfunc(dcvars); + } + } + column = (const column_t*) ((const byte*) column + column->length + 4); + } + + dcvars->texturemid = basetexturemid; +} +static inline uint32_t getColumnOffsetData(patch_t *patch, int colindex) +{ + if (cachedColumnOffsetDataPatch == patch) + { + return columnOffsetData[colindex]; + } + else + { + return *((uint32_t*) ((uint32_t) patch + 8 + 4 * colindex)); + } +} +static inline void getColumnDataNonBlocking(const patch_t *patch, int colindex, uint8_t *columnData) +{ + uint32_t co = getColumnOffsetData((patch_t*) patch, colindex); + uint32_t cnt = co >> 24; + co = co & 0xFFFFFF; + FLASH_MEMCPY(columnData, (const uint8_t *) patch + co, cnt); + plat_qspi.EVENTS_READY = 1; +} +FASTFUN static inline column_t* getColumnData(const patch_t *patch, int colindex, uint8_t *columnData) +{ + + +#if 0 + uint32_t co = getColumnOffsetData((patch_t *) patch, colindex); + uint32_t cnt = co >> 24; + co = co & 0xFFFFFF; + NRF_QSPI->READ.CNT = cnt; + NRF_QSPI->READ.SRC = ((uint32_t) patch + co); + NRF_QSPI->READ.DST = (uint32_t) columnData; + NRF_QSPI->EVENTS_READY = 0; + plat_qspi_read(); + while (NRF_QSPI->EVENTS_READY == 0); + NRF_QSPI->EVENTS_READY = 0; + return (column_t*) columnData; +#elif 1 + uint32_t co = getColumnOffsetData((patch_t *) patch, colindex); + FLASH_MEMCPY(columnData, (uint8_t *) patch + (co & 0xFFFFFF), co >> 24); + return (column_t*) columnData; +#else + // there is no major benefit using this + uint32_t co = getColumnOffsetData((patch_t *) patch, colindex);; + //spiFlashSetAddress((uint32_t) patch + 8 + 4 * colindex); + //uint32_t co = (uint16_t) spiFlashGetShort(); + uint32_t cnt = co >> 24; + co = co & 0xFFFFFF; + if (cnt <= 136) + { + memcpy(columnData, (uint8_t *) patch + co, cnt); + } + else + { + NRF_QSPI->READ.CNT = cnt; + NRF_QSPI->READ.SRC = ((uint32_t) patch + co); + NRF_QSPI->READ.DST = (uint32_t) columnData; + NRF_QSPI->EVENTS_READY = 0; + plat_qspi_read(); + while (NRF_QSPI->EVENTS_READY == 0); + NRF_QSPI->EVENTS_READY = 0; + } + return (column_t*) columnData; +#endif +} +static inline void cachePatchColumnOffsetData(patch_t *patch, int width, int startX, int stopX) +{ + // this function will cache the whole coloffset data, but only when needed + if (!isOnExternalFlash(patch)) + return; // do not cache data already in flash + if (patch == cachedColumnOffsetDataPatch) + return; // do not recache cached data. + // get how many bytes we need to get + int cnt = (stopX - startX); +#if 1 + // cache only when convenient. Each random access of words would take about 260 cycles. + // Also memcpy takes about 290 cycles + about 4 per byte. Therefore we have 290 + (4 * width) * 4 + // the disequation is 260 * (cnt + 1) > 340 + width * 16 + if ( 260 * cnt > 30 + width * 16) + { + // set cached address + cachedColumnOffsetDataPatch = patch; + memcpy(columnOffsetData, (void*) ((uint32_t) patch + 8), 4 * width); + } +#else + // cache only when convenient. Each random access of words would take about 260 cycles. + // Also the Easy DMA takes about 340 cycles. The time later taken by the DMA is about (width * 4) * 4 (we have 16 B per us) + // the disequation is 260 * cnt > 340 + width * 16 + if ( 260 * cnt > 340 + width * 16) + { + + NRF_QSPI->READ.CNT = width * 4; // set t read the whole columnoffset + NRF_QSPI->READ.SRC = ((uint32_t) patch + 8 ); + NRF_QSPI->READ.DST = (uint32_t) columnOffsetData; + NRF_QSPI->EVENTS_READY = 0; + plat_qspi_read(); + // set cached address + cachedColumnOffsetDataPatch = patch; + while (NRF_QSPI->EVENTS_READY == 0); + NRF_QSPI->EVENTS_READY = 0; + } + +#endif +} +// +// R_DrawVisSprite +// mfloorclip and mceilingclip should also be set. +// +// CPhipps - new wad lump handling, *'s to const*'s +FASTFUN static void R_DrawVisSprite(const vissprite_t *vis) +{ + fixed_t frac; + + R_DrawColumn_f colfunc; + draw_column_vars_t dcvars; + + R_SetDefaultDrawColumnVars(&dcvars); + + switch (vis->colormap_idx) + { + case CURRENT_COLOR_MAP_IDX: + dcvars.colormap = current_colormap_ptr; + break; + case FIXED_COLOR_MAP_IDX: + dcvars.colormap = fixedcolormap; + break; + case SHADOW_COLOR_MAP_IDX: + dcvars.colormap = NULL; + break; + case FULL_COLOR_MAP_IDX: + dcvars.colormap = fullcolormap; + break; + default: + dcvars.colormap = fullcolormap + 256 * vis->colormap_idx; + } + // killough 4/11/98: rearrange and handle translucent sprites + // mixed with translucent/non-translucenct 2s normals + + if (!dcvars.colormap) // NULL colormap = shadow draw + colfunc = R_DrawFuzzColumn; // killough 3/14/98 + else + { + // 2021/02/13 next-hack. To save some bytes, vissprites will have only a byte mobjflags. + // also, multiplayer is not enabled, so MF_TRANSLATION is never present. +#if 0 + if (vis->mobjflags & (MF_TRANSLATION >> MF_TRANSSHIFT)) + { + // next-hack: multiplayer not supported. + printf("Draw Translated column, blocking\r\n"); + while(1); + //colfunc = R_DrawTranslatedColumn; + //dcvars.translation = translationtables + ((vis->mobjflags & (MF_TRANSLATION >> MF_TRANSSHIFT)) << 8 ); + } + else +#endif + colfunc = R_DrawColumn; // killough 3/14/98, 4/11/98 + + } + + // proff 11/06/98: Changed for high-res + dcvars.iscale = FixedReciprocal(vis->scale); + dcvars.texturemid = vis->texturemid; + frac = vis->startfrac; + + spryscale = vis->scale; + sprtopscreen = centeryfrac - FixedMul(dcvars.texturemid, spryscale); + + //const patch_t *patch = vis->patch; + const patch_t *patch = W_CacheLumpNum(vis->lumpNum); + if (false == isOnExternalFlash(patch)) + { + for (dcvars.x = vis->x1; dcvars.x <= vis->x2; dcvars.x++, frac += vis->xiscale) + { + const column_t *column = (const column_t*) ((const byte*) patch + (0xFFFFFF & patch->columnofs[frac >> FRACBITS])); + R_DrawMaskedColumn(colfunc, &dcvars, column); + } + } + else + { // sprite is in Spi flash. different approach here! + // note that columnOfs are typically less than 64kB, therefore we only read shorts. + // furthermore: + // for sprites very up or down scaled (the majority of the cases), reading all the columns is counterproductive. + // It is better to read directly the single column ofs. + // furthermore, for mirrored sprites, xiscale might be negative. + if (vis->x1 <= vis->x2) + { +// uint32_t oldColindex = 0xFFFFFFFF; // invalid index + //uint8_t columnData[MAX_COLUMN_DATA]; + // get first column + uint32_t colindex = frac >> FRACBITS; + //oldColindex = colindex; + // calculate already next position + frac += vis->xiscale; + // set first buffer + uint32_t bufferNumber = 0; + cachePatchColumnOffsetData((patch_t*) patch, p_wad_immutable_flash_data->patchLumpSizeOffsets[vis->lumpNum].width, vis->x1 , vis->x2); + getColumnDataNonBlocking(patch, colindex, columnBuffer[bufferNumber]); + // Check if we are going to draw a column twice. TODO: improve this! + fixed_t absXiscale = D_abs(vis->xiscale); + if (absXiscale >= 0x10000) + { + for (dcvars.x = vis->x1; dcvars.x < vis->x2; dcvars.x++, frac += vis->xiscale) + { + // get current column + colindex = frac >> FRACBITS; + + // wait till DMA has finished loading the column + while(!NRF_QSPI->EVENTS_READY) {}; + NRF_QSPI->EVENTS_READY = 0; + + getColumnDataNonBlocking(patch, colindex, columnBuffer[1 -bufferNumber]); + R_DrawMaskedColumn(colfunc, &dcvars, (column_t*) columnBuffer[bufferNumber]); + // swap buffers + bufferNumber = 1 - bufferNumber; + } + // draw last column! We need to wait last DMA first + while(!NRF_QSPI->EVENTS_READY) {}; + NRF_QSPI->EVENTS_READY = 0; + R_DrawMaskedColumn(colfunc, &dcvars, (column_t*) columnBuffer[bufferNumber]); + } + else + { + // the sprite is magnified, so at least one column would be drawn twice. Not loading a column might save us 1 us, offsetting the + // additional checks + for (uint8_t x = vis->x1; x <= vis->x2; ) + { + // set start x + dcvars.x = x; + uint32_t newColindex; + // get current column + colindex = frac >> FRACBITS; + // calculate how many columns we should draw with the same clumn data. + do + { + // calculate the new column + newColindex = frac >> FRACBITS; + x++; + frac += vis->xiscale; + newColindex++; + } while ( newColindex == colindex && x <= vis->x2); + // x now contains the first column not equal with the data pointed in colindex + // if x is x2 or less, then there is still one more column to be loaded. Otherwise, if it is x2+1, it means that this + // last column will be drawn outside of this loop. + if (x <= vis->x2) + { + // wait till DMA has finished loading the column + while(!NRF_QSPI->EVENTS_READY) {}; + NRF_QSPI->EVENTS_READY = 0; + getColumnDataNonBlocking(patch, colindex, columnBuffer[1 -bufferNumber]); + // draw all the columns with the same data + for (; dcvars.x < x; dcvars.x++) + { + R_DrawMaskedColumn(colfunc, &dcvars, (column_t*) columnBuffer[bufferNumber]); + } + // swap buffers + bufferNumber = 1 - bufferNumber; + } + + } + // draw last column or group of column, if needed. We need to wait last DMA first + if (dcvars.x <= vis->x2) + { + while(!NRF_QSPI->EVENTS_READY) {}; + NRF_QSPI->EVENTS_READY = 0; + for (; dcvars.x <= vis->x2; dcvars.x++) + { + R_DrawMaskedColumn(colfunc, &dcvars, (column_t*) columnBuffer[bufferNumber]); + } + } + + } + } + } +} +#if MULTIPATCH_TEXTURE_SUPPORT +FASTFUN static inline column_t* R_GetColumn(const texture_t *texture, int texcolumn, uint8_t *columnData) +{ + const unsigned int patchcount = texture->patchcount; + const unsigned int widthmask = texture->widthmask; + + const int xc = texcolumn & widthmask; + + if (patchcount == 1) + { + //simple texture. + const patch_t *patch = texture->patches[0].patch; + if (!isOnExternalFlash(patch)) + { + return (column_t*) ((byte*) patch + (0xFFFFFF & patch->columnofs[xc])); + } + else + { + return getColumnData(patch, xc, columnData); + } + } + else + { + unsigned int i = 0; + + do + { + + const texpatch_t *patch = &texture->patches[i]; + + const patch_t *realpatch = patch->patch; + + const int x1 = patch->originx; + + if (xc < x1) + continue; + short width; + + if (isOnExternalFlash(realpatch)) + { + spiFlashSetAddress((uint32_t) &realpatch->width); + width = spiFlashGetShort(); + } + else + { + width = realpatch->width; + } + const int x2 = x1 + width; + + if (xc < x2) + { + if (isOnExternalFlash(realpatch)) + { + return getColumnData(realpatch, xc - x1, columnData); + } + else + { + return (column_t*) ((byte*) realpatch + (realpatch->columnofs[xc - x1] & 0xFFFFFF) ); + } + } + + } while (++i < patchcount); + } + return NULL; +} +#else +FASTFUN static inline column_t* R_GetColumn(const texture_t *texture, int texcolumn, uint8_t *columnData) +{ + const unsigned int widthmask = texture->widthmask; + + const int xc = texcolumn & widthmask; + //simple texture. + const patch_t *patch = texture->patches[0].patch; + if (!isOnExternalFlash(patch)) + { + return (column_t*) ((byte*) patch + (0xFFFFFF & patch->columnofs[xc])); + } + else + { + return getColumnData(patch, xc, columnData); + } +} + +#endif + +FASTFUN inline static column_t* R_GetColumnNonBlocking(const texture_t *texture, int texcolumn, uint8_t *columnData, bool *wasOnExternalFlash) +{ + const unsigned int widthmask = texture->widthmask; + + const int xc = texcolumn & widthmask; +#if MULTIPATCH_TEXTURE_SUPPORT + const unsigned int patchcount = texture->patchcount; + + if (patchcount == 1) + { + //simple texture. + const patch_t *patch = texture->patches[0].patch; + if (!isOnExternalFlash(patch)) + { + *wasOnExternalFlash = false; + return (column_t*) ((byte*) patch + (0xFFFFFF & patch->columnofs[xc])); + } + else + { + *wasOnExternalFlash = true; + getColumnDataNonBlocking(patch, xc, columnData); + return (column_t*) columnData; + } + } + else + { + unsigned int i = 0; + + do + { + + const texpatch_t *patch = &texture->patches[i]; + + const patch_t *realpatch = patch->patch; + + const int x1 = patch->originx; + + if (xc < x1) + continue; + short width; + + if (isOnExternalFlash(realpatch)) + { + spiFlashSetAddress((uint32_t) &realpatch->width); + width = spiFlashGetShort(); + const int x2 = x1 + width; + if (xc < x2) + { + *wasOnExternalFlash = true; + getColumnDataNonBlocking(realpatch, xc - x1, columnData); + return (column_t*) columnData; + } + } + else + { + width = realpatch->width; + const int x2 = x1 + width; + if (xc < x2) + { + *wasOnExternalFlash = false; + return (column_t*) ((byte*) realpatch + (realpatch->columnofs[xc - x1] & 0xFFFFFF) ); + } + } + } while (++i < patchcount); + } + *wasOnExternalFlash = false; + return NULL; + #else + //simple texture. + const patch_t *patch = texture->patches[0].patch; + if (!isOnExternalFlash(patch)) + { + *wasOnExternalFlash = false; + return (column_t*) ((byte*) patch + (0xFFFFFF & patch->columnofs[xc])); + } + else + { + *wasOnExternalFlash = true; + getColumnDataNonBlocking(patch, xc, columnData); + return (column_t*) columnData; + } + + #endif +} + + + +FASTFUN static inline const texture_t* R_GetOrLoadTexture(int tex_num) +{ + const texture_t *tex = textures[tex_num]; + if (!tex) + { + // we are in the middle of a level. No saving to flash. + tex = R_GetTexture(tex_num, false, NULL); + } + return tex; +} +static const uint32_t openingPtrs[] = {0, (uint32_t) negonearray, (uint32_t) screenheightarray}; +FASTFUN static inline short* openingSsptrToAddr(unsigned short ssptr) +{ + if (ssptr <= SCREENHEIGHTARRAY_PTR) + return (short*) openingPtrs[ssptr]; + + /* + if (ssptr == 0) + return NULL; + else if (ssptr == NEGONEARRAY_PTR) + return (short*) negonearray; + else if (ssptr == SCREENHEIGHTARRAY_PTR) + return (short*) screenheightarray;*/ + else + { + return (short*) (RAM_PTR_BASE | (ssptr << 1)); +// return &openings[ssptr - 1]; + } +} +FASTFUN static inline unsigned short openingAddrToSsptr(short *ptr) +{ + +/* if ((uint32_t) ptr & 0x20001) + { + printf("Warning opening outside 128k, blocking \r\n"); + while (1); + }*/ + return ((unsigned int) ptr) >> 1; + + //return 1 + ((((uint32_t) ptr) - ( (uint32_t) &openings[0])) >> 1); +} +// +// R_RenderMaskedSegRange +// +FASTFUN static void R_RenderMaskedSegRange(const drawseg_t *ds, int x1, int x2) +{ + int texnum; + draw_column_vars_t dcvars; + + R_SetDefaultDrawColumnVars(&dcvars); + + // Calculate light table. + // Use different light tables + // for horizontal / vertical / diagonal. Diagonal? + + curline = ds->curline; // OPTIMIZE: get rid of LIGHTSEGSHIFT globally + + frontsector = SG_FRONTSECTOR(curline); + backsector = SG_BACKSECTOR(curline); + + texnum = getSideMidTexture(&_g->lines[curline->linenum], &_g->sides[curline->sidenum]); + texnum = texturetranslation[texnum]; + // next-hack: added back lighting + + int lightnum = (frontsector->lightlevel >> LIGHTSEGSHIFT) + extralight; + + if (curline->v1.y == curline->v2.y) + lightnum--; + else if (curline->v1.x == curline->v2.x) + lightnum++; + + if (lightnum < 0) + walllights = 0; + else if (lightnum >= LIGHTLEVELS) + walllights = LIGHTLEVELS - 1; + else + walllights = lightnum; + + // killough 4/13/98: get correct lightlevel for 2s normal textures + rw_lightlevel = frontsector->lightlevel; + + maskedtexturecol = ds->maskedtexturecol; + + rw_scalestep = ds->scalestep; + spryscale = ds->scale1 + (x1 - ds->x1) * rw_scalestep; + // to save some bytes, we might mfloorclip and mceilingclip as chars, some times. + // In this case, we are pointing to short, so we need to tell also the size of what + // mfloorclip and mceilingclip are pointing to. + mfloorclip = (ycoord_t*) openingSsptrToAddr(ds->sprbottomclip_ssptr); + mceilingclip = (ycoord_t*) openingSsptrToAddr(ds->sprtopclip_ssptr); + mfloorceiling_ptr_size = sizeof(short); + // find positioning + if (_g->lines[curline->linenum].flags & ML_DONTPEGBOTTOM) + { + dcvars.texturemid = + frontsector->floorheight > backsector->floorheight ? frontsector->floorheight : backsector->floorheight; + dcvars.texturemid = dcvars.texturemid + textureheight[texnum] - viewz; + } + else + { + dcvars.texturemid = + frontsector->ceilingheight < backsector->ceilingheight ? frontsector->ceilingheight : backsector->ceilingheight; + dcvars.texturemid = dcvars.texturemid - viewz; + } + dcvars.texturemid += (_g->sides[curline->sidenum].rowoffset << FRACBITS); + const texture_t *texture = R_GetOrLoadTexture(texnum); + if (fixedcolormap) + dcvars.colormap = fixedcolormap; +#if 0 + // draw the columns + column_t *column = column; // self assign to suppress uninit warning without code generation + int oldXc = 0xFF000000; + uint8_t columnData[MAX_COLUMN_DATA]; + for (dcvars.x = x1; dcvars.x <= x2; dcvars.x++, spryscale += rw_scalestep) + { + const int xc = maskedtexturecol[dcvars.x]; + + if (xc != D_SHRT_MAX) // dropoff overflow + { + if (!fixedcolormap) + { + int index = spryscale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + + dcvars.colormap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + } + sprtopscreen = centeryfrac - FixedMul(dcvars.texturemid, spryscale); + // + dcvars.iscale = FixedReciprocal((unsigned) spryscale); + + // draw the texture + if (oldXc != xc) + { + oldXc = xc; + column = R_GetColumn(texture, xc, columnData); + } + R_DrawMaskedColumn(R_DrawColumn, &dcvars, column); + + maskedtexturecol[dcvars.x] = D_SHRT_MAX; // dropoff overflow + } + } + #else + // draw the columns + column_t *column = column; // self assign to suppress uninit warning without code generation + column_t *nextColumn = column; + if (x1 <= x2) // is there any column to draw? + { + int x = x1; + bool wasOnExternalFlash = false; + uint32_t bufferNumber = 0; + int xc = maskedtexturecol[x]; + // get the first column + // + cachePatchColumnOffsetData( (patch_t*) texture->patches[0].patch, texture->width, x1 , x2); + // + column = R_GetColumnNonBlocking(texture, xc, columnBuffer[bufferNumber], &wasOnExternalFlash); + // + for (dcvars.x = x1; dcvars.x < x2; dcvars.x++, spryscale += rw_scalestep) + { + if (xc != D_SHRT_MAX) // dropoff overflow + { + if (!fixedcolormap) + { + int index = spryscale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + + dcvars.colormap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + } + sprtopscreen = centeryfrac - FixedMul(dcvars.texturemid, spryscale); + // + dcvars.iscale = FixedReciprocal((unsigned) spryscale); + // draw the texture + if (wasOnExternalFlash) + { + while (!NRF_QSPI->EVENTS_READY) {}; + NRF_QSPI->EVENTS_READY = 0; + } + nextColumn = R_GetColumnNonBlocking(texture, xc, columnBuffer[1 - bufferNumber], &wasOnExternalFlash); + R_DrawMaskedColumn(R_DrawColumn, &dcvars, column); + column = nextColumn; + maskedtexturecol[dcvars.x] = D_SHRT_MAX; // dropoff overflow + bufferNumber = 1 - bufferNumber; + } + xc = maskedtexturecol[dcvars.x + 1]; + } + // draw last column + if (xc != D_SHRT_MAX) // dropoff overflow + { + if (!fixedcolormap) + { + int index = spryscale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + + dcvars.colormap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + } + sprtopscreen = centeryfrac - FixedMul(dcvars.texturemid, spryscale); + // + dcvars.iscale = FixedReciprocal((unsigned) spryscale); + // draw the texture. However, wait till the buffer is ready, if we read if from external flash. + if (wasOnExternalFlash) + { + while (!NRF_QSPI->EVENTS_READY) {}; + NRF_QSPI->EVENTS_READY = 0; + } + R_DrawMaskedColumn(R_DrawColumn, &dcvars, column); + maskedtexturecol[dcvars.x] = D_SHRT_MAX; // dropoff overflow + } + + } + #endif + curline = NULL; /* cph 2001/11/18 - must clear curline now we're done with it, so R_ColourMap doesn't try using it for other things */ +} + +// killough 5/2/98: reformatted + +FASTFUN static PUREFUNC int R_PointOnSegSide(fixed_t x, fixed_t y, const seg_t *line) +{ + const fixed_t lx = line->v1.x; + const fixed_t ly = line->v1.y; + const fixed_t ldx = line->v2.x - lx; + const fixed_t ldy = line->v2.y - ly; + + if (!ldx) + return x <= lx ? ldy > 0 : ldy < 0; + + if (!ldy) + return y <= ly ? ldx < 0 : ldx > 0; + + x -= lx; + y -= ly; + + // Try to quickly decide by looking at sign bits. + if ((ldy ^ ldx ^ x ^ y) < 0) + return (ldy ^ x) < 0; // (left is negative) + + return FixedMul(y, ldx >> FRACBITS) >= FixedMul(ldy >> FRACBITS, x); +} + +// +// R_DrawSprite +// + +FASTFUN static void R_DrawSprite(const vissprite_t *spr) +{ + ycoord_t *clipbot = floorclip; + ycoord_t *cliptop = ceilingclip; + + fixed_t scale; + fixed_t lowscale; + for (int x = spr->x1; x <= spr->x2; x++) + { + clipbot[x] = draw_stopy + 1; + cliptop[x] = draw_starty - 1; + } + + // Scan drawsegs from end to start for obscuring segs. + // The first drawseg that has a greater scale is the clip seg. + + // Modified by Lee Killough: + // (pointer check was originally nonportable + // and buggy, by going past LEFT end of array): + + const drawseg_t *drawsegs = _g->drawsegs; + + for (const drawseg_t *ds = ds_p; ds-- > drawsegs;) // new -- killough + { + // determine if the drawseg obscures the sprite + if (ds->x1 > spr->x2 || ds->x2 < spr->x1 || (!ds->silhouette && !ds->maskedtexturecol)) + continue; // does not cover sprite + + const int r1 = ds->x1 < spr->x1 ? spr->x1 : ds->x1; + const int r2 = ds->x2 > spr->x2 ? spr->x2 : ds->x2; + + if (ds->scale1 > ds->scale2) + { + lowscale = ds->scale2; + scale = ds->scale1; + } + else + { + lowscale = ds->scale1; + scale = ds->scale2; + } + + if (scale < spr->scale || (lowscale < spr->scale && !R_PointOnSegSide(spr->gx, spr->gy, ds->curline))) + { + if (ds->maskedtexturecol) // masked mid texture? + R_RenderMaskedSegRange(ds, r1, r2); + + continue; // seg is behind sprite + } + + // clip this piece of the sprite + // killough 3/27/98: optimized and made much shorter + + if ((ds->silhouette & SIL_BOTTOM) && spr->gz < ds->bsilheight) //bottom sil + { + for (int x = r1; x <= r2; x++) + { + if (clipbot[x] == draw_stopy + 1) + { + clipbot[x] = openingSsptrToAddr(ds->sprbottomclip_ssptr)[x]; + } + } + + } + + if ((ds->silhouette & SIL_TOP) && spr->gzt > ds->tsilheight) // top sil + { + for (int x = r1; x <= r2; x++) + { + if (cliptop[x] == draw_starty - 1) + { + cliptop[x] = openingSsptrToAddr(ds->sprtopclip_ssptr)[x]; + } + } + } + } + + // all clipping has been performed, so draw the sprite + mfloorclip = clipbot; + mceilingclip = cliptop; + mfloorceiling_ptr_size = sizeof(*clipbot); + R_DrawVisSprite(spr); +} + +// +// R_DrawPSprite +// + +FASTFUN static void R_DrawPSprite(pspdef_t *psp, int lightlevel) +{ + int x1, x2; + spritedef_t *sprdef; + spriteframe_t *sprframe; + boolean flip; + vissprite_t *vis; + vissprite_t avis; + int width; + fixed_t topoffset; + + // decide which patch to use + sprdef = &p_wad_immutable_flash_data->sprites[psp->state->sprite]; + + sprframe = &(getSpriteFrames(sprdef)[psp->state->frame & FF_FRAMEMASK]); + + flip = (boolean) SPR_FLIPPED(sprframe, 0); + patchsizeoffsets_t *patch; + /* + patch_t *cachedPatch = (patch_t*) W_CacheLumpNum(sprframe->lump[0] + _g->firstspritelump); + patch_t ramPatch; + if (isOnExternalFlash(cachedPatch)) + { + spiFlashSetAddress((uint32_t) cachedPatch); + spiFlashGetData(&ramPatch, 8); // only first 4 shorts + + patch = &ramPatch; + } + else + { + patch = cachedPatch; + }*/ + uint32_t lumpNum = sprframe->lump[0] + _g->firstspritelump; + patch = &p_wad_immutable_flash_data->patchLumpSizeOffsets[lumpNum]; + // calculate edges of the shape + fixed_t tx; + tx = psp->sx - 160 * FRACUNIT; + + tx -= patch->leftoffset << FRACBITS; + x1 = (centerxfrac + FixedMul(tx, pspritescale)) >> FRACBITS; + + tx += patch->width << FRACBITS; + x2 = ((centerxfrac + FixedMul(tx, pspritescale)) >> FRACBITS) - 1; + + width = patch->width; + topoffset = patch->topoffset << FRACBITS; + + // off the side + if (x2 < 0 || x1 > SCREENWIDTH) + return; + + // store information in a vissprite + vis = &avis; + vis->mobjflags = 0; + // killough 12/98: fix psprite positioning problem + vis->texturemid = (BASEYCENTER << FRACBITS) /* + FRACUNIT/2 */- (psp->sy - topoffset); + vis->x1 = x1 < 0 ? 0 : x1; + vis->x2 = x2 >= SCREENWIDTH ? SCREENWIDTH - 1 : x2; + // proff 11/06/98: Added for high-res + vis->scale = pspriteyscale; + // vis->iscale = pspriteyiscale; + + if (flip) + { + vis->xiscale = -pspriteiscale; + vis->startfrac = (width << FRACBITS) - 1; + } + else + { + vis->xiscale = pspriteiscale; + vis->startfrac = 0; + } + + if (vis->x1 > x1) + vis->startfrac += vis->xiscale * (vis->x1 - x1); + + //vis->patch = cachedPatch; + vis->lumpNum = lumpNum; + /* + if (_g->viewplayer->powers[pw_invisibility] > 4*32 || _g->viewplayer->powers[pw_invisibility] & 8) + vis->colormap = NULL; // shadow draw + else if (fixedcolormap) + vis->colormap = fixedcolormap; // fixed color + else if (psp->state->frame & FF_FULLBRIGHT) + vis->colormap = fullcolormap; // full bright // killough 3/20/98 + else + vis->colormap = R_LoadColorMap(lightlevel); // local light + */ + if (_g->viewplayer->powers[pw_invisibility] > 4 * 32 || (_g->viewplayer->powers[pw_invisibility] & 8)) + vis->colormap_idx = SHADOW_COLOR_MAP_IDX; // shadow draw + else if (fixedcolormap) + vis->colormap_idx = FIXED_COLOR_MAP_IDX; // fixed color + else if (psp->state->frame & FF_FULLBRIGHT) + vis->colormap_idx = FULL_COLOR_MAP_IDX; // full bright // killough 3/20/98 + else + { + current_colormap_ptr = p_wad_immutable_flash_data->colormaps + 256 * scalelight[spritelights][0]; + vis->colormap_idx = CURRENT_COLOR_MAP_IDX; + } + R_DrawVisSprite(vis); +} + +// +// R_DrawPlayerSprites +// + +FASTFUN static void R_DrawPlayerSprites(void) +{ + int i, + lightlevel = getMobjSubsector(_g->viewplayer->mo)->sector->lightlevel; + pspdef_t *psp; + + int lightnum = (lightlevel >> LIGHTSEGSHIFT) + extralight; + + if (lightnum < 0) + spritelights = 0; //scalelight[0]; + else if (lightnum >= LIGHTLEVELS) + spritelights = LIGHTLEVELS - 1; //scalelight[LIGHTLEVELS-1]; + else + spritelights = lightnum; //scalelight[lightnum]; + // clip to screen bounds + + mfloorclip = floorclip; + mceilingclip = ceilingclip; + mfloorceiling_ptr_size = sizeof(*floorclip); + + #if 0 + for (int i = 0; i < sizeof(floorclip) / sizeof(floorclip[0]); i++) + { + floorclip[i] = draw_stopy + 1; + ceilingclip[i] = draw_starty - 1; + } + #else + uint32_t *p_fc = (uint32_t*) floorclip; + uint32_t *p_cc = (uint32_t*) ceilingclip; + const uint16_t fcv = draw_stopy + 1; + const uint16_t ccv = draw_starty - 1; + + for (i = 0; i < SCREENWIDTH / 2; i++) + { + *p_fc++ = fcv | (fcv << 16); + *p_cc++ = ccv | (ccv << 16); + } + #endif + + // mfloorclip = screenheightarray; + // mceilingclip = negonearray; + // add all active psprites + for (i = 0, psp = _g->viewplayer->psprites; i < NUMPSPRITES; i++, psp++) + if (psp->state) + R_DrawPSprite(psp, lightlevel); +} + +// +// R_SortVisSprites +// +// Rewritten by Lee Killough to avoid using unnecessary +// linked lists, and to use faster sorting algorithm. +// +// killough 9/2/98: merge sort + +// 2021-02-13 next-hack changed using indexes. +FASTFUN static void msort(uint8_t *s, uint8_t *t, int n) +{ + if (n >= 16) + { + int n1 = n / 2, n2 = n - n1; + uint8_t *s1 = s, *s2 = s + n1, *d = t; + + msort(s1, t, n1); + msort(s2, t, n2); + + while (_g->vissprites[*s1].scale > _g->vissprites[*s2].scale ? (*d++ = *s1++, --n1) : (*d++ = *s2++, --n2)); + + if (n2) + memcpy(d, s2, n2 * sizeof(*d)); + else + memcpy(d, s1, n1 * sizeof(*d)); + + memcpy(s, t, n * sizeof(*s)); + } + else + { + int i; + for (i = 1; i < n; i++) + { + uint8_t temp = s[i]; + if (_g->vissprites[s[i - 1]].scale < _g->vissprites[temp].scale) + { + int j = i; + while (_g->vissprites[(s[j] = s[j - 1])].scale < _g->vissprites[temp].scale && --j); + s[j] = temp; + } + } + } +} +FASTFUN static void R_SortVisSprites(void) +{ + int i = num_vissprite; + + if (i) + { + // 2021-02-13 next-hack. It is cheaper to store a byte index, instead of a 4 - byte ptr + // while (--i>=0) + // _g->vissprite_ptrs[i] = _g->vissprites+i; + while (--i >= 0) + _g->vissprite_indexes[i] = i; + // killough 9/22/98: replace qsort with merge sort, since the keys + // are roughly in order to begin with, due to BSP rendering. + + // msort(_g->vissprite_ptrs, _g->vissprite_ptrs + num_vissprite, num_vissprite); + msort(_g->vissprite_indexes, _g->vissprite_indexes + num_vissprite, num_vissprite); + } +} + +// +// R_DrawMasked +// + +FASTFUN static void R_DrawMasked(void) +{ + int i; + drawseg_t *ds; + drawseg_t *drawsegs = _g->drawsegs; + + R_SortVisSprites(); + + // draw all vissprites back to front + for (i = num_vissprite; --i >= 0;) + { + //2021-02-13 next-hack instead of pointers, we use idnexes. Slower, but saves ram + // R_DrawSprite(_g->vissprite_ptrs[i]); // killough + vissprite_t *vs = &_g->vissprites[_g->vissprite_indexes[i]]; +#if DEBUGLIMITS + if (!check_limits(vs)) + printf("VisSprite error num %d, tot %d, addr 0x%08X\r\n", i, num_vissprite , (uint32_t)vs); +#endif + R_DrawSprite(vs); + } + + // render any remaining masked mid textures + + // Modified by Lee Killough: + // (pointer check was originally nonportable + // and buggy, by going past LEFT end of array): + for (ds = ds_p; ds-- > drawsegs;) // new -- killough + if (ds->maskedtexturecol) + R_RenderMaskedSegRange(ds, ds->x1, ds->x2); + + R_DrawPlayerSprites(); +} + +// +// R_DrawSpan +// With DOOM style restrictions on view orientation, +// the floors and ceilings consist of horizontal slices +// or spans with constant z depth. +// However, rotation around the world z axis is possible, +// thus this mapping, while simpler and faster than +// perspective correct texture mapping, has to traverse +// the texture at an angle in all but a few cases. +// In consequence, flats are not stored by column (like walls), +// and the inner loop has to step in texture space u and v. +// + +FASTFUN inline static void R_DrawSpanPixel(pixel *dest, const byte *source, const byte *colormap, unsigned int position) +{ +#ifdef HIGHRES + *dest = colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]; +#else + unsigned int color = colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]; + + *dest = (color | (color << 8)); +#endif +} + +FASTFUN static inline void R_DrawSpan(unsigned int y, unsigned int x1, unsigned int x2, const draw_span_vars_t *dsvars) +{ + unsigned int count = (x2 - x1); + const byte *source = dsvars->source; + const byte *colormap; +#if CACHE_ALL_COLORMAP_TO_RAM + colormap = dsvars->colormap; +#else + // 2021/09/18 next-hack this will improve a lot plane drawing due to better RAM speed + if (currentCachedColorMap == dsvars->colormap) + { + colormap = colorMap; + } + else if (x2 - x1 > MIN_PIXEL_TO_DRAW_FOR_CACHING_COLORMAP) + { + memcpy(colorMap, dsvars->colormap, 256); + currentCachedColorMap = (uint8_t*) dsvars->colormap; + colormap = colorMap; + } + else + { + colormap = dsvars->colormap; + } +#endif + pixel *dest = ((pixel*) drawvars.byte_topleft) + ScreenYToOffset(y) + x1; + uint32_t * qDest = (uint32_t*) dest; + const unsigned int step = dsvars->step; + unsigned int position = dsvars->position; + + unsigned int l = (count >> 4); + while (l--) + { + #if 0 + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + #else + uint32_t quadPix; + + quadPix = colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 8; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 16; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 24; + position += step; + *qDest++ = quadPix; + + quadPix = colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 8; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 16; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 24; + position += step; + *qDest++ = quadPix; + + quadPix = colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 8; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 16; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 24; + position += step; + *qDest++ = quadPix; + + quadPix = colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 8; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 16; + position += step; + quadPix |= (colormap[source[((position >> 4) & 0x0fc0) | (position >> 26)]]) << 24; + position += step; + *qDest++ = quadPix; + + #endif + } + dest = (pixel*) qDest; + unsigned int r = (count & 15); + + switch (r) + { + case 15: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 14: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 13: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 12: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 11: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 10: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 9: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 8: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 7: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 6: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 5: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 4: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 3: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 2: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + dest += 1; + position += step; + // fall through, no break + case 1: + R_DrawSpanPixel((pixel*) dest, source, colormap, position); + // fall through, no break + } +} + +FASTFUN static void R_MapPlane(unsigned int y, unsigned int x1, unsigned int x2, draw_span_vars_t *dsvars) +{ + const fixed_t distance = FixedMul(planeheight, yslope[y]); + + dsvars->step = ((FixedMul(distance, basexscale) << 10) & 0xffff0000) | ((FixedMul(distance, baseyscale) >> 6) & 0x0000ffff); + + fixed_t length = FixedMul(distance, distscale[x1]); + angle_t angle = (viewangle + xtoviewangle[x1]) >> ANGLETOFINESHIFT; + + // killough 2/28/98: Add offsets + unsigned int xfrac = viewx + FixedMul(finecosine[angle], length); + unsigned int yfrac = -viewy - FixedMul(finesine[angle], length); + + dsvars->position = ((xfrac << 10) & 0xffff0000) | ((yfrac >> 6) & 0x0000ffff); + int index; + if (fixedcolormap) + { + dsvars->colormap = fixedcolormap; + } + else + { + index = distance >> LIGHTZSHIFT; + + if (index >= MAXLIGHTZ) + index = MAXLIGHTZ - 1; + + dsvars->colormap = p_wad_immutable_flash_data->colormaps + 256 * zlight[planezlight][index]; + } + R_DrawSpan(y, x1, x2, dsvars); +} +#ifdef OPTIMIZESIZE +#pragma GCC optimize ("Os") +#endif +// +// R_MakeSpans +// + +FASTFUN static void R_MakeSpans(int x, unsigned int t1, unsigned int b1, unsigned int t2, unsigned int b2, draw_span_vars_t *dsvars) +{ + for (; t1 < t2 && t1 <= b1; t1++) + { + //if (t1 >= viewheight) + // printf("t1 > 96 %d\r\n", t1); + R_MapPlane(t1, spanstart[t1], x, dsvars); + } + + for (; b1 > b2 && b1 >= t1; b1--) + { + //if (b1 >= viewheight) + // printf("b1 > 96 %d\r\n", b1); + R_MapPlane(b1, spanstart[b1], x, dsvars); + } + while (t2 < t1 && t2 <= b2) + { + + //if (t2 >= viewheight) + // printf("t2 > 96 %d\r\n", t2); + spanstart[t2++] = x; + } + while (b2 > b1 && b2 >= t2) + { + //if (b2 >= viewheight) + // printf("b2 > 96 %d\r\n", b2); + spanstart[b2--] = x; + } +} + +// New function, by Lee Killough + +FASTFUN static void R_DoDrawPlane(visplane_t *pl) +{ + register int x; + draw_column_vars_t dcvars; + + R_SetDefaultDrawColumnVars(&dcvars); + + if (pl->minx <= pl->maxx) + { + if (pl->picnum == _g->skyflatnum) + { // sky flat + + // Normal Doom sky, only one allowed per level + dcvars.texturemid = skytexturemid; // Default y-offset + + /* Sky is always drawn full bright, i.e. colormaps[0] is used. + * Because of this hack, sky is not affected by INVUL inverse mapping. + * Until Boom fixed this. Compat option added in MBF. */ + + if (!(dcvars.colormap = fixedcolormap)) + dcvars.colormap = fullcolormap; // killough 3/20/98 + + // proff 09/21/98: Changed for high-res + dcvars.iscale = skyiscale; + // sky drawing not optimized, because it is likely to be in the internal flash. + const texture_t *tex = R_GetOrLoadTexture(_g->skytexture); + cachePatchColumnOffsetData((patch_t *) tex->patches[0].patch, tex->width, pl->minx, pl->maxx); + uint8_t columnData[MAX_COLUMN_DATA]; + int oldXc = 0xFF000000; + const column_t *column = column; // self assignment to suppress warning without code generation + // killough 10/98: Use sky scrolling offset + for (x = pl->minx; (dcvars.x = x) <= pl->maxx; x++) + { + if ((dcvars.yl = pl->top[x]) != -1 && dcvars.yl <= (dcvars.yh = pl->bottom[x])) // dropoff overflow + { + int xc = ((viewangle + xtoviewangle[x]) >> ANGLETOSKYSHIFT); + if (oldXc != xc) + { + oldXc = xc; + column = R_GetColumn(tex, xc, columnData); + } + dcvars.source = (const byte*) column + 3; + R_DrawColumn(&dcvars); + } + } + } + else + { // regular flat + + draw_span_vars_t dsvars; + uint8_t light; + dsvars.source = W_CacheLumpNum(_g->firstflat + flattranslation[pl->picnum]); +#ifdef PARADISE_DEV + { extern const byte *plat_flat(int lump, const byte *src); + dsvars.source = plat_flat(_g->firstflat + flattranslation[pl->picnum], dsvars.source); } +#endif + if (isOnExternalFlash(dsvars.source)) + { + printf("Error, found a lump %d at address 0x%08X, picnum %d, name %s \r\n", (unsigned int) (_g->firstflat + flattranslation[pl->picnum]), (unsigned int) W_CacheLumpNum(_g->firstflat + flattranslation[pl->picnum]), flattranslation[pl->picnum], W_GetNameForNum(_g->firstflat + flattranslation[pl->picnum])); + while (1); + } +// NOTE: removed! + //dsvars.colormap = R_LoadColorMap(pl->lightlevel); + + planeheight = D_abs(pl->height - viewz); + + light = (pl->lightlevel >> LIGHTSEGSHIFT) + extralight; + + if (light >= LIGHTLEVELS) + light = LIGHTLEVELS - 1; + + if (light < 0) + light = 0; + + planezlight = light; + + const int stop = pl->maxx + 1; + + pl->top[pl->minx - 1] = pl->top[stop] = 0xff; // dropoff overflow + + for (x = pl->minx; x <= stop; x++) + { + int t1 = pl->top[x - 1]; + int b1 = pl->bottom[x - 1]; + int t2 = pl->top[x]; + int b2 = pl->bottom[x]; + + R_MakeSpans(x, t1, b1, t2, b2, &dsvars); + } + } + } +} + +//******************************************* + +// +// R_ScaleFromGlobalAngle +// Returns the texture mapping scale +// for the current line (horizontal span) +// at the given angle. +// rw_distance must be calculated first. +// +// killough 5/2/98: reformatted, cleaned up +// CPhipps - moved here from r_main.c + +FASTFUN static fixed_t R_ScaleFromGlobalAngle(angle_t visangle) +{ + int anglea = ANG90 + (visangle - viewangle); + int angleb = ANG90 + (visangle - rw_normalangle); + + int den = FixedMul(rw_distance, finesine[anglea >> ANGLETOFINESHIFT]); + +// proff 11/06/98: Changed for high-res + fixed_t num = FixedMul(projectiony, finesine[angleb >> ANGLETOFINESHIFT]); + + return den > num >> 16 ? + (num = FixedDiv(num, den)) > 64 * FRACUNIT ? 64 * FRACUNIT : + num < 256 ? 256 : num : 64 * FRACUNIT; +} + +// +// R_NewVisSprite +// + +static vissprite_t* R_NewVisSprite(void) +{ + if (num_vissprite >= MAXVISSPRITES) + { +#ifdef RANGECHECK + I_Error("Vissprite overflow.\r\n"); +#endif + return NULL; + } + + return _g->vissprites + num_vissprite++; +} + +// +// R_ProjectSprite +// Generates a vissprite for a thing if it might be visible. +// + +FASTFUN static void R_ProjectSprite(mobj_t *thing, int lightlevel) +{ + const fixed_t fx = thing->x; + const fixed_t fy = thing->y; + const fixed_t fz = thing->z; + + const fixed_t tr_x = fx - viewx; + const fixed_t tr_y = fy - viewy; + + const fixed_t tz = FixedMul(tr_x, viewcos) - (-FixedMul(tr_y, viewsin)); + + // thing is behind view plane? + if (tz < MINZ) + return; + + //Too far away. Always draw Cyberdemon and Spiderdemon. They are big sprites! + if ((tz > MAXZ) && (thing->type != MT_CYBORG) && (thing->type != MT_SPIDER)) + return; + + fixed_t tx = -(FixedMul(tr_y, viewcos) + (-FixedMul(tr_x, viewsin))); + + // too far off the side? + if (D_abs(tx) > (tz << 2)) + return; + + // decide which patch to use for sprite relative to player + const spritedef_t *sprdef = &p_wad_immutable_flash_data->sprites[thing->sprite]; + const spriteframe_t *sprframe = (const spriteframe_t*) &(getSpriteFrames(sprdef)[thing->frame & FF_FRAMEMASK]); + + unsigned int rot = 0; + + if (sprframe->rotate) + { + // choose a different rotation based on player view + angle_t ang = R_PointToAngle(fx, fy); + rot = (ang - thing->angle + (unsigned) (ANG45 / 2) * 9) >> 29; + } + + const boolean flip = (boolean) SPR_FLIPPED(sprframe, rot); + uint32_t lumpNum = sprframe->lump[rot] + _g->firstspritelump; + + + + patchsizeoffsets_t *patch; + patch = &p_wad_immutable_flash_data->patchLumpSizeOffsets[lumpNum]; +/* + patch_t *p_patch = (patch_t*) W_CacheLumpNum(lumpNum); + patch_t tpatch; + if (isOnExternalFlash(p_patch)) + { + spiFlashSetAddress((uint32_t) p_patch); + spiFlashGetData(&tpatch, 8); + patch = &tpatch; + } + else + { + patch = p_patch; + }*/ + + /* calculate edges of the shape + * cph 2003/08/1 - fraggle points out that this offset must be flipped + * if the sprite is flipped; e.g. FreeDoom imp is messed up by this. */ + if (flip) + tx -= (patch->width - patch->leftoffset) << FRACBITS; + else + tx -= patch->leftoffset << FRACBITS; + + const fixed_t xscale = FixedDiv(projection, tz); + + fixed_t xl = (centerxfrac + FixedMul(tx, xscale)); + + // off the side? + if (xl > (SCREENWIDTH << FRACBITS)) + return; + + fixed_t xr = (centerxfrac + FixedMul(tx + (patch->width << FRACBITS), xscale)) - FRACUNIT; + + // off the side? + if (xr < 0) + return; + + //Too small. + if (xr <= (xl + (FRACUNIT >> 2))) + return; + + const int x1 = (xl >> FRACBITS); + const int x2 = (xr >> FRACBITS); + + // store information in a vissprite + vissprite_t *vis = R_NewVisSprite(); + + //No more vissprites. + if (!vis) + return; +// 2021-02-13 next-hack: useless having to store 32 bit, when you need only 2... + vis->mobjflags = thing->flags >> MF_TRANSSHIFT; + + // proff 11/06/98: Changed for high-res + vis->scale = FixedDiv(projectiony, tz); + //vis->iscale = FixedReciprocal(vis->scale); + //vis->patch = p_patch; + vis->lumpNum = lumpNum; + vis->gx = fx; + vis->gy = fy; + vis->gz = fz; + vis->gzt = fz + (patch->topoffset << FRACBITS); // killough 3/27/98 + vis->texturemid = vis->gzt - viewz; + vis->x1 = x1 < 0 ? 0 : x1; + vis->x2 = x2 >= SCREENWIDTH ? SCREENWIDTH - 1 : x2; + + const fixed_t iscale = FixedDiv(FRACUNIT, xscale); + + if (flip) + { + vis->startfrac = (patch->width << FRACBITS) - 1; + vis->xiscale = -iscale; + } + else + { + vis->startfrac = 0; + vis->xiscale = iscale; + } + + if (vis->x1 > x1) + vis->startfrac += vis->xiscale * (vis->x1 - x1); + + // get light level + /* if (thing->flags & MF_SHADOW) + + vis->colormap = NULL; // shadow draw + else if (fixedcolormap) + vis->colormap = fixedcolormap; // fixed map + else if (thing->frame & FF_FULLBRIGHT) + vis->colormap = fullcolormap; // full bright // killough 3/20/98 + else + { // diminished light + vis->colormap = R_ColourMap(lightlevel); + }*/ + // get light level + if (thing->flags & MF_SHADOW) + vis->colormap_idx = SHADOW_COLOR_MAP_IDX; // shadow draw + else if (fixedcolormap) + vis->colormap_idx = FIXED_COLOR_MAP_IDX; // fixed map + else if (thing->frame & FF_FULLBRIGHT) + vis->colormap_idx = FULL_COLOR_MAP_IDX; // full bright // killough 3/20/98 + else + { // diminished light + + const lighttable_t *cm = R_ColourMap(lightlevel); + if (cm == fixedcolormap) + vis->colormap_idx = FIXED_COLOR_MAP_IDX; + else + { + //uint32_t n = (((uint32_t) cm) - ((uint32_t) fullcolormap)) / 256; + int index = xscale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + { + index = MAXLIGHTSCALE - 1; + } + //vis->colormap_idx = n; + vis->colormap_idx = scalelight[spritelights][index]; + } + } +} + +// +// R_AddSprites +// During BSP traversal, this adds sprites by sector. +// +// killough 9/18/98: add lightlevel as parameter, fixing underwater lighting +static void R_AddSprites(subsector_t *subsec, int lightlevel) +{ + sector_t *sec = subsec->sector; + mobj_t *thing; + + // BSP is traversed by subsector. + // A sector might have been split into several + // subsectors during BSP building. + // Thus we check whether its already added. + + if (sec->validcount == _g->validcount) + return; + + // Well, now it will be done. + sec->validcount = _g->validcount; + + // light + + int lightnum = (lightlevel >> LIGHTSEGSHIFT) + extralight; + + if (lightnum < 0) + spritelights = 0; //scalelight[0]; + else if (lightnum >= LIGHTLEVELS) + spritelights = LIGHTLEVELS - 1; //scalelight[LIGHTLEVELS-1]; + else + spritelights = lightnum; // scalelight[lightnum]; + + // Handle all things in sector. + + for (thing = getSectorThingList(sec); thing; thing = getSNext(thing)) + R_ProjectSprite(thing, lightlevel); +} + +// +// R_FindPlane +// +// killough 2/28/98: Add offsets + +// New function, by Lee Killough + +static visplane_t* new_visplane(unsigned hash) +{ + static int allocatedVp = 0; + visplane_t *check = _g->freetail; + + if (!check) + { + allocatedVp++; + check = Z_Calloc(1, sizeof(visplane_t), PU_LEVEL, NULL); + //printf("NewVispl. %d\r\n", allocatedVp); + } + else + { + if (!(_g->freetail = _g->freetail->next)) + _g->freehead = &_g->freetail; + } + + check->next = _g->visplanes[hash]; + _g->visplanes[hash] = check; + + return check; +} + +static visplane_t* R_FindPlane(fixed_t height, int picnum, int lightlevel) +{ + visplane_t *check; + unsigned hash; // killough + + if (picnum == _g->skyflatnum) + height = lightlevel = 0; // killough 7/19/98: most skies map together + + // New visplane algorithm uses hash table -- killough + hash = visplane_hash(picnum, lightlevel, height); + + for (check = _g->visplanes[hash]; check; check = check->next) // killough + if (height == check->height && picnum == check->picnum && lightlevel == check->lightlevel) + return check; + + check = new_visplane(hash); // killough + + check->height = height; + check->picnum = picnum; + check->lightlevel = lightlevel; + check->minx = SCREENWIDTH; // Was SCREENWIDTH -- killough 11/98 + check->maxx = -1; + + memset(check->top, UINT_MAX, sizeof(check->top)); + + check->modified = 0; + + return check; +} + +/* + * R_DupPlane + * + * cph 2003/04/18 - create duplicate of existing visplane and set initial range + */ +static visplane_t* R_DupPlane(const visplane_t *pl, int start, int stop) +{ + unsigned hash = visplane_hash(pl->picnum, pl->lightlevel, pl->height); + visplane_t *new_pl = new_visplane(hash); + + new_pl->height = pl->height; + new_pl->picnum = pl->picnum; + new_pl->lightlevel = pl->lightlevel; + new_pl->minx = start; + new_pl->maxx = stop; + + memset(new_pl->top, UINT_MAX, sizeof(new_pl->top)); + + new_pl->modified = false; + + return new_pl; +} + +// +// R_CheckPlane +// +static visplane_t* R_CheckPlane(visplane_t *pl, int start, int stop) +{ + int intrl, intrh, unionl, unionh, x; + + if (start < pl->minx) + intrl = pl->minx, unionl = start; + else + unionl = pl->minx, intrl = start; + + if (stop > pl->maxx) + intrh = pl->maxx, unionh = stop; + else + unionh = pl->maxx, intrh = stop; + + for (x = intrl; x <= intrh && pl->top[x] == 0xff; x++) // dropoff overflow + ; + + if (x > intrh) + { /* Can use existing plane; extend range */ + pl->minx = unionl; + pl->maxx = unionh; + return pl; + } + else + /* Cannot use existing plane; create a new one */ + return R_DupPlane(pl, start, stop); +} +#if MULTIPATCH_TEXTURE_SUPPORT +static inline void R_DrawColumnInCache(const column_t *patch, byte *cache, int originy, int cacheheight) +{ + while (patch->topdelta != 0xff) + { + const byte *source = (const byte*) patch + 3; + int count = patch->length; + int position = originy + patch->topdelta; + + if (position < 0) + { + count += position; + position = 0; + } + + if (position + count > cacheheight) + count = cacheheight - position; + + if (count > 0) + memcpy(cache + position, source, count); + + patch = (const column_t*) ((const byte*) patch + patch->length + 4); + } +} +#endif + +/* + * Draw a column of pixels of the specified texture. + * If the texture is simple (1 patch, full height) then just draw + * straight from const patch_t*. + */ +#if MULTIPATCH_TEXTURE_SUPPORT +FASTFUN static inline const byte* R_ComposeColumn(const texture_t *tex, int texcolumn, unsigned int iscale) +{ + // TODO: clean up this mess +/* if (isOnExternalFlash(tex)) + { + printf("Error, found a texture at address 0x%08X\r\n", (unsigned int) tex); + while (1); + }*/ +#if ENABLE_MIPMAP + int colmask = 0xfffe; + if (tex->width > 8) + { + if (iscale > (4 << FRACBITS)) + colmask = 0xfff0; + else if (iscale > (3 << FRACBITS)) + colmask = 0xfff8; + else if (iscale > (2 << FRACBITS)) + colmask = 0xfffc; + } + + const int xc = (texcolumn & colmask) & tex->widthmask; +#else + // 2021/06/05 next-hack: since we do not implement any cache, there is no point of mip-mapping + // in fact mip-mapping was probably added by doomhack to increase hit/miss ratio. + const int xc = (texcolumn & tex->widthmask); +#endif + unsigned int i = 0; + unsigned int patchcount = tex->patchcount; + + do + { + // note: all texetures and patch addresses are cached in flash. + const texpatch_t *patch = &tex->patches[i]; + const patch_t *realpatch = patch->patch; + const int x1 = patch->originx; + + if (xc < x1) + continue; + short width; + if (isOnExternalFlash(realpatch)) + { + spiFlashSetAddress((uint32_t) &realpatch->width); + width = spiFlashGetShort(); + } + else + { + width = realpatch->width; + } + const int x2 = x1 + width; + + if (xc < x2) + { + #if 0 + const column_t *patchcol; + if (isOnExternalFlash(realpatch)) + { + // 2021-08-13 next-hack: we can directly load the column data to the dest column buffer + uint32_t ofs = realpatch->columnofs[xc - x1]; + patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & ofs)); + unsigned int length = ((ofs >> 24) - 8); + int position = patch->originy + patchcol->topdelta; + + if (position < 0) + { + length += position; + position = 0; + } + + if (position + length > tex->height) + length = tex->height - position; + + + NRF_QSPI->READ.CNT = length; + NRF_QSPI->READ.SRC = (uint32_t) (((uint8_t*)patchcol) + 3); + NRF_QSPI->READ.DST = (uint32_t) ((uint8_t*) columnCacheBuffer + position);; + NRF_QSPI->EVENTS_READY = 0; + plat_qspi_read(); + while (NRF_QSPI->EVENTS_READY == 0); + NRF_QSPI->EVENTS_READY = 0; + } + else + { + // 2021-08-13 next-hack: if the patch is in internal flash, we copy it to the dest column buffer by words and not bytes. Huge boost! + patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1])); + + unsigned int length = patchcol->length; //((realpatch->columnofs[xc - x1] >> 24) - 8); + //printf("L %d I %d\r\n", patchcol->length ,((realpatch->columnofs[xc - x1] >> 24) - 8)); + int position = patch->originy + patchcol->topdelta; + + + if (position < 0) + { + length += position; + position = 0; + } + + if (position + length > tex->height) + length = tex->height - position; + uint32_t *d = (uint32_t* )((uint8_t*) columnCacheBuffer + position); + uint32_t *s = (uint32_t* )(((uint8_t*)patchcol) + 3); + for (int j = 0; j < length >> 2; j++) + *d++ = *s++; + } + + #elif 1 + const column_t *patchcol; + if (isOnExternalFlash(realpatch)) + { + // in most of the cases, the patch will be a single post, multiple of 4 bytes and 4-bytes aligned. + // therefore we can directly draw to the buffer. + // 2021-08-13 next-hack: we can directly load the column data to the dest column buffer + uint32_t ofs = realpatch->columnofs[xc - x1]; + patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & ofs)); + unsigned int columnLength = ((ofs >> 24) - 8); + unsigned int postLength = patchcol->length; + bool done = false; + if (postLength == columnLength) + { + unsigned int length = postLength; + int position = patch->originy + patchcol->topdelta; + + if (position < 0) + { + length += position; + position = 0; + } + + if (position + length > tex->height) + length = tex->height - position; + + if ((position & 3) == 0 && (length & 3) == 0) + { + done = true; + NRF_QSPI->READ.CNT = length; + NRF_QSPI->READ.SRC = (uint32_t) (((uint8_t*)patchcol) + 3); + NRF_QSPI->READ.DST = (uint32_t) ((uint8_t*) columnCacheBuffer + position);; + NRF_QSPI->EVENTS_READY = 0; + plat_qspi_read(); + while (NRF_QSPI->EVENTS_READY == 0); + NRF_QSPI->EVENTS_READY = 0; + } + } + if (!done) + { + // we were not able to optimize. What a pity. + uint8_t columnData[MAX_COLUMN_DATA]; + const column_t *patchcol; + patchcol = getColumnData(realpatch, xc - x1, columnData); + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch->originy, tex->height); + } + } + else + { + // 2021-08-13 next-hack: if the patch is in internal flash, we copy it to the dest column buffer by words and not bytes. Huge boost! + patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1])); + + unsigned int columnLength = ((realpatch->columnofs[xc - x1] >> 24) - 8); + int position = patch->originy + patchcol->topdelta; + + unsigned int postLength = patchcol->length; + bool done = false; + if (postLength == columnLength) + { + unsigned int length = postLength; + if (position < 0) + { + length += position; + position = 0; + } + + if (position + length > tex->height) + length = tex->height - position; + + if ((position & 3) == 0 && (length & 3) == 0) + { + done = true; + uint32_t *d = (uint32_t* )((uint8_t*) columnCacheBuffer + position); + uint32_t *s = (uint32_t* )(((uint8_t*)patchcol) + 3); + for (int j = 0; j < length >> 2; j++) + *d++ = *s++; + } + } + if (!done) + { + patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1])); + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch->originy, tex->height); + } + + + } + #else + uint8_t columnData[MAX_COLUMN_DATA]; + const column_t *patchcol; + if (isOnExternalFlash(realpatch)) + { + patchcol = getColumnData(realpatch, xc - x1, columnData); + } + else + { + patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1])); + } + // TODO: not sure if this does not overflow. + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch->originy, tex->height); + #endif + } + + } while (++i < patchcount); + return columnCacheBuffer; +} +#endif +#if 0 +uint8_t composeColumnBuffer[2][MAX_COLUMN_DATA]; +FASTFUN static inline const byte* R_ComposeColumnNonBlocking(const texture_t *tex, int texcolumn) +{ + // TODO: clean up this mess + const int xc = (texcolumn & tex->widthmask); + unsigned int i = 0; + unsigned int patchcount = tex->patchcount; + bool wasOnExternalFlash = false; + uint32_t bufferNumber = 0; + bool validColumn = false; + int patch_originy, tex_height; + column_t *patchcol, *next_patchcol; + texpatch_t *patch; + + // get the first column + do + { + // note: all texetures and patch addresses are cached in flash. + patch = &tex->patches[i]; + const patch_t *realpatch = patch->patch; + const int x1 = patch->originx; + + if (xc < x1) + continue; + short width; + if (isOnExternalFlash(realpatch)) + { + spiFlashSetAddress((uint32_t) &realpatch->width); + width = spiFlashGetShort(); + } + else + { + width = realpatch->width; + } + const int x2 = x1 + width; + + if (xc < x2) + { + uint8_t columnData[MAX_COLUMN_DATA]; + const column_t *patchcol; + if (isOnExternalFlash(realpatch)) + { + getColumnDataNonBlocking(realpatch, xc - x1, composeColumnBuffer[bufferNumber]); + patchcol = composeColumnBuffer[bufferNumber]; + wasOnExternalFlash = true; + } + else + { + patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1])); + wasOnExternalFlash = false; + } + i++; + validColumn = true; + break; + } + } while (++i < patchcount); + // now we got the first good patch column + if (validColumn) + { + patch_originy = patch->originy; + tex_height = tex->height; + // now the next ones + do + { + // note: all texetures and patch addresses are cached in flash. + patch = &tex->patches[i]; + const patch_t *realpatch = patch->patch; + const int x1 = patch->originx; + + if (xc < x1) + { + + continue; + } + short width; + if (isOnExternalFlash(realpatch)) + { + // before accessing the external flash, wait + if (wasOnExternalFlash) + { + while (!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } + spiFlashSetAddress((uint32_t) &realpatch->width); + width = spiFlashGetShort(); + } + else + { + width = realpatch->width; + } + const int x2 = x1 + width; + + if (xc < x2) + { + if (isOnExternalFlash(realpatch)) + { + getColumnDataNonBlocking(realpatch, xc - x1, composeColumnBuffer[1 - bufferNumber]); + next_patchcol = composeColumnBuffer[1 - bufferNumber]; + wasOnExternalFlash = true; + } + else + { + next_patchcol = (const column_t*) ((const byte*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1])); + wasOnExternalFlash = false; + } + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch_originy, tex_height); + validColumn = true; + patch_originy = patch->originy; + tex_height = tex->height; + patchcol = next_patchcol; + bufferNumber = 1 - bufferNumber; + } +/* else + { + if (validColumn) + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch_originy, tex_height); + validColumn = false; + }*/ + } while (++i < patchcount); + + if (wasOnExternalFlash) + { + while (!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } + // draw last patch? only if valid + if (validColumn) + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch_originy, tex_height); + } + return columnCacheBuffer; +} +#endif +#if MULTIPATCH_TEXTURE_SUPPORT +FASTFUN inline static void R_DrawSegTextureColumn(const texture_t *tex, int texcolumn, draw_column_vars_t *dcvars, uint8_t *columnData) +{ + if (tex->patchcount == 1) + { +#if 0 + const column_t *column = R_GetColumn(tex, texcolumn, columnData); +#else + // very minimal performance increase. Well, better than nothing. + const column_t *column; + if ((dcvars->yh - dcvars->yl) > 8) + //if (dcvars->iscale > 0x10000) + { + column = R_GetColumn(tex, texcolumn, columnData); + } + else + { + const unsigned int widthmask = tex->widthmask; + const int xc = texcolumn & widthmask; + const patch_t *patch = tex->patches[0].patch; + column = (column_t*) ((byte*) patch + (0xFFFFFF & patch->columnofs[xc])); + } +#endif + dcvars->source = (const byte*) column + 3; + } + else if (tex->overlapped == 0) + { + const column_t *column = R_GetColumn(tex, texcolumn, columnData); + dcvars->source = (const byte*) column + 3; + } + else + { + dcvars->source = R_ComposeColumn(tex, texcolumn, dcvars->iscale); + } + R_DrawColumn(dcvars); +} +#endif +// +FASTFUN inline static void* R_GetSegTextureColumnNonBlocking(const texture_t *tex, int texcolumn, uint8_t *columnData, bool *wasOnExternalFlash, fixed_t iscale) +{ +#if MULTIPATCH_TEXTURE_SUPPORT + + if (tex->overlapped == 0) + { + const column_t *column = R_GetColumnNonBlocking(tex, texcolumn, columnData, wasOnExternalFlash); + return (byte*) column + 3; + } + else + { + return (void*) R_ComposeColumn(tex, texcolumn, iscale); + } +#else + const column_t *column = R_GetColumnNonBlocking(tex, texcolumn, columnData, wasOnExternalFlash); + return (byte*) column + 3; +#endif +} +// +typedef union +{ + struct + { + uint8_t topTextureLoadByDma; + uint8_t bottomTextureLoadByDma; + }; + uint16_t pendingDmaOperation; +} dmaOperation_t; + +FASTFUN inline static void* R_GetSinglePatchTextureColumnNonBlocking(const texture_t *texture, int texcolumn, uint8_t *columnData, fixed_t iscale, dmaOperation_t *dmaOperation, uint32_t isTop) +{ + const unsigned int widthmask = texture->widthmask; + + const int xc = texcolumn & widthmask; + //simple texture. + const patch_t *patch = texture->patches[0].patch; + if (!isOnExternalFlash(patch)) + { + return ((byte*) patch + (0xFFFFFF & patch->columnofs[xc]) + 3); + } + else + { + // was there any pending DMA operation ? + if (dmaOperation->pendingDmaOperation) + { + while(!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } +#define GET_SIZE_FROM_TEXTURE_DATA 1 +#if GET_SIZE_FROM_TEXTURE_DATA + + NRF_QSPI->READ.CNT = texture->height; + NRF_QSPI->READ.SRC = (uint32_t) patch + + 8 // first 8 bytes are patch data + + 4 * texture->width // column offset data + + xc * (texture->height + 5) // each column has topdelta, length, pad, height> data, pad, invalid topdelta. + + 3; // point to data + NRF_QSPI->READ.DST = (uint32_t) columnData; + NRF_QSPI->EVENTS_READY = 0; + plat_qspi_read(); +#else + uint32_t co = getColumnOffsetData((patch_t*) patch, xc); + uint32_t cnt = co >> 24; + co = co & 0xFFFFFF; + NRF_QSPI->READ.CNT = cnt - 4; + NRF_QSPI->READ.SRC = (uint32_t) patch + co + 3; + NRF_QSPI->READ.DST = (uint32_t) columnData; + NRF_QSPI->EVENTS_READY = 0; + plat_qspi_read(); +#endif + if (isTop) + { + dmaOperation->pendingDmaOperation = 0x0001; + } + else + { + dmaOperation->pendingDmaOperation = 0x0100; + } + return columnData; + } +} + +// +// R_RenderSegLoop +// Draws zero, one, or two textures (and possibly a masked texture) for walls. +// Can draw or mark the starting pixel of floor and ceiling textures. +// CALLED: CORE LOOPING ROUTINE. +// + +#define HEIGHTBITS 12 +#define HEIGHTUNIT (1<> HEIGHTBITS; + int yl = (topfrac + HEIGHTUNIT - 1) >> HEIGHTBITS; + + int cc_rwx = ceilingclip[rw_x]; + int fc_rwx = floorclip[rw_x]; + + // no space above wall? + int bottom, top = cc_rwx + 1; + + if (yl < top) + yl = top; + + if (yl < draw_starty) + yl = draw_starty; + + if (yh > draw_stopy) + yh = draw_stopy; + + if (markceiling) + { + bottom = yl - 1; + + if (bottom >= fc_rwx) + bottom = fc_rwx - 1; + + if (top <= bottom) + { + ceilingplane->top[rw_x] = top; + ceilingplane->bottom[rw_x] = bottom; + ceilingplane->modified = 1; + } + // SoM: this should be set here + cc_rwx = bottom; + } + + bottom = fc_rwx - 1; + if (yh > bottom) + yh = bottom; + + if (markfloor) + { + + top = yh < cc_rwx ? cc_rwx : yh; + + if (++top <= bottom) + { + floorplane->top[rw_x] = top; + floorplane->bottom[rw_x] = bottom; + floorplane->modified = 1; + } + // SoM: This should be set here to prevent overdraw + fc_rwx = top; + } + + // texturecolumn and lighting are independent of wall tiers + if (segtextured) + { + // calculate texture offset + angle_t angle = (rw_centerangle + xtoviewangle[rw_x]) >> ANGLETOFINESHIFT; + + texturecolumn = rw_offset - FixedMul(finetangent[angle], rw_distance); + + texturecolumn >>= FRACBITS; + + // calculate lighting + int index = rw_scale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + + dcvars.colormap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + + dcvars.x = rw_x; + + dcvars.iscale = FixedReciprocal((unsigned) rw_scale); + } + + // draw the wall tiers + if (midtexture) + { + + dcvars.yl = yl; // single sided line + dcvars.yh = yh; + dcvars.texturemid = rw_midtexturemid; + // + const texture_t *tex = R_GetOrLoadTexture(midtexture); + if (texturecolumn != oldTextureColumn || tex->overlapped) + { + oldTextureColumn = texturecolumn; + R_DrawSegTextureColumn(tex, texturecolumn, &dcvars, columnData); + } + R_DrawColumn(&dcvars); + cc_rwx = draw_stopy + 1; + fc_rwx = draw_starty - 1; + } + else + { + + // two sided line + if (toptexture) + { + // top wall + int mid = pixhigh >> HEIGHTBITS; + pixhigh += pixhighstep; + + if (mid >= fc_rwx) + mid = fc_rwx - 1; + + if (mid >= yl) + { + dcvars.yl = yl; + dcvars.yh = mid; + dcvars.texturemid = rw_toptexturemid; + const texture_t *tex = R_GetOrLoadTexture(toptexture); + R_DrawSegTextureColumn(tex, texturecolumn, &dcvars, columnData); + R_DrawColumn(&dcvars); + + cc_rwx = mid; + } + else + cc_rwx = yl - 1; + } + else // no top wall + { + + if (markceiling) + cc_rwx = yl - 1; + } + + if (bottomtexture) // bottom wall + { + int mid = (pixlow + HEIGHTUNIT - 1) >> HEIGHTBITS; + pixlow += pixlowstep; + + // no space above wall? + if (mid <= cc_rwx) + mid = cc_rwx + 1; + + if (mid <= yh) + { + dcvars.yl = mid; + dcvars.yh = yh; + dcvars.texturemid = rw_bottomtexturemid; + const texture_t *tex = R_GetOrLoadTexture(bottomtexture); + R_DrawSegTextureColumn(tex, texturecolumn, &dcvars, columnData); + R_DrawColumn(&dcvars); + + fc_rwx = mid; + } + else + fc_rwx = yh + 1; + } + else // no bottom wall + { + if (markfloor) + fc_rwx = yh + 1; + } + + // cph - if we completely blocked further sight through this column, + // add this info to the solid columns array for r_bsp.c + if ((markceiling || markfloor) && (fc_rwx <= cc_rwx + 1)) + { + + solidcol[rw_x] = 1; + didsolidcol = 1; + } + + // save texturecol for backdrawing of masked mid texture + if (maskedtexture) + maskedtexturecol[rw_x] = texturecolumn; + } + + rw_scale += rw_scalestep; + topfrac += topstep; + bottomfrac += bottomstep; + + floorclip[rw_x] = fc_rwx; + ceilingclip[rw_x] = cc_rwx; + } +#else +#if MULTIPATCH_TEXTURE_SUPPORT + if (midtexture) + { + if (rw_x >= rw_stopx) + return; + //uint8_t columnData[MAX_COLUMN_DATA]; + void *columnDataPtr, *nextColumnDataPtr; + bool wasOnExternalFlash = false; + int bufferNumber = 0; + fixed_t iscale = FixedReciprocal((unsigned) rw_scale); + const texture_t *tex = R_GetOrLoadTexture(midtexture); + cachePatchColumnOffsetData((patch_t*) tex->patches[0].patch, tex->width, rw_x , rw_stopx); + // texturecolumn and lighting are independent of wall tiers + if (segtextured) + { + // calculate texture offset + angle_t angle = (rw_centerangle + xtoviewangle[rw_x]) >> ANGLETOFINESHIFT; + + texturecolumn = rw_offset - FixedMul(finetangent[angle], rw_distance); + + texturecolumn >>= FRACBITS; + } + + columnDataPtr = R_GetSegTextureColumnNonBlocking(tex, texturecolumn, columnBuffer[1 - bufferNumber], &wasOnExternalFlash, iscale); + + for (; rw_x < rw_stopx; rw_x++) + { + // mark floor / ceiling areas + + int yh = bottomfrac >> HEIGHTBITS; + int yl = (topfrac + HEIGHTUNIT - 1) >> HEIGHTBITS; + + int cc_rwx = ceilingclip[rw_x]; + int fc_rwx = floorclip[rw_x]; + + // no space above wall? + int bottom, top = cc_rwx + 1; + + if (yl < top) + yl = top; + + if (yl < draw_starty) + yl = draw_starty; + + if (yh > draw_stopy) + yh = draw_stopy; + + if (markceiling) + { + bottom = yl - 1; + + if (bottom >= fc_rwx) + bottom = fc_rwx - 1; + + if (top <= bottom) + { + ceilingplane->top[rw_x] = top; + ceilingplane->bottom[rw_x] = bottom; + ceilingplane->modified = 1; + } + // SoM: this should be set here + cc_rwx = bottom; + } + + bottom = fc_rwx - 1; + if (yh > bottom) + yh = bottom; + + if (markfloor) + { + + top = yh < cc_rwx ? cc_rwx : yh; + + if (++top <= bottom) + { + floorplane->top[rw_x] = top; + floorplane->bottom[rw_x] = bottom; + floorplane->modified = 1; + } + // SoM: This should be set here to prevent overdraw + fc_rwx = top; + } + + + // draw the wall tiers + + dcvars.yl = yl; // single sided line + dcvars.yh = yh; + dcvars.texturemid = rw_midtexturemid; + // + const texture_t *tex = R_GetOrLoadTexture(midtexture); + dcvars.source = columnDataPtr; + + + // calculate dcvars for NEXT column + // texturecolumn and lighting are independent of wall tiers + if (segtextured) + { + // calculate next texture offset + angle_t angle = (rw_centerangle + xtoviewangle[rw_x + 1]) >> ANGLETOFINESHIFT; + + texturecolumn = rw_offset - FixedMul(finetangent[angle], rw_distance); + + texturecolumn >>= FRACBITS; + + // calculate lighting + int index = rw_scale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + + dcvars.colormap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + + dcvars.x = rw_x; + + dcvars.iscale = iscale; + iscale = FixedReciprocal((unsigned)rw_scale + rw_scalestep) ; + } + + if (wasOnExternalFlash) + { + while(!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } + + // load next column. Only if this is not the last one! + if (rw_x < rw_stopx - 1) + { + nextColumnDataPtr = R_GetSegTextureColumnNonBlocking(tex, texturecolumn, columnBuffer[1 - bufferNumber], &wasOnExternalFlash, iscale); + } + bufferNumber = 1 - bufferNumber; + R_DrawColumn(&dcvars); + columnDataPtr = nextColumnDataPtr; + cc_rwx = draw_stopy + 1; + fc_rwx = draw_starty - 1; + + rw_scale += rw_scalestep; + topfrac += topstep; + bottomfrac += bottomstep; + + floorclip[rw_x] = fc_rwx; + ceilingclip[rw_x] = cc_rwx; + + } + #else + if (midtexture) + { + if (rw_x >= rw_stopx) + return; + //uint8_t columnData[MAX_COLUMN_DATA]; + void *nextColumnDataPtr; + dmaOperation_t dmaOperation = {.pendingDmaOperation = 0}; + int bufferNumber = 0; + fixed_t iscale = FixedReciprocal((unsigned) rw_scale); + const texture_t *tex = R_GetOrLoadTexture(midtexture); + //cachePatchColumnOffsetData((patch_t*) tex->patches[0].patch, tex->width, rw_x , rw_stopx); + // texturecolumn and lighting are independent of wall tiers + //if (segtextured) midtexture already means it is segtextured + { + // calculate texture offset + angle_t angle = (rw_centerangle + xtoviewangle[rw_x]) >> ANGLETOFINESHIFT; + + texturecolumn = rw_offset - FixedMul(finetangent[angle], rw_distance); + + texturecolumn >>= FRACBITS; + } + + dcvars.source = R_GetSinglePatchTextureColumnNonBlocking (tex, texturecolumn, columnBuffer[bufferNumber], iscale, &dmaOperation, 1); + // R_GetSegTextureColumnNonBlocking(tex, texturecolumn, columnBuffer[1 - bufferNumber], &wasOnExternalFlash, iscale); + + for (; rw_x < rw_stopx; rw_x++) + { + // mark floor / ceiling areas + + int yh = bottomfrac >> HEIGHTBITS; + int yl = (topfrac + HEIGHTUNIT - 1) >> HEIGHTBITS; + + int cc_rwx = ceilingclip[rw_x]; + int fc_rwx = floorclip[rw_x]; + + // no space above wall? + int bottom, top = cc_rwx + 1; + + if (yl < top) + yl = top; + + if (yl < draw_starty) + yl = draw_starty; + + if (yh > draw_stopy) + yh = draw_stopy; + + if (markceiling) + { + bottom = yl - 1; + + if (bottom >= fc_rwx) + bottom = fc_rwx - 1; + + if (top <= bottom) + { + ceilingplane->top[rw_x] = top; + ceilingplane->bottom[rw_x] = bottom; + ceilingplane->modified = 1; + } + // SoM: this should be set here + cc_rwx = bottom; + } + + bottom = fc_rwx - 1; + if (yh > bottom) + yh = bottom; + + if (markfloor) + { + + top = yh < cc_rwx ? cc_rwx : yh; + + if (++top <= bottom) + { + floorplane->top[rw_x] = top; + floorplane->bottom[rw_x] = bottom; + floorplane->modified = 1; + } + // SoM: This should be set here to prevent overdraw + fc_rwx = top; + } + + + // draw the wall tiers + + dcvars.yl = yl; // single sided line + dcvars.yh = yh; + dcvars.texturemid = rw_midtexturemid; + // + //const texture_t *tex = R_GetOrLoadTexture(midtexture); + //dcvars.source = columnDataPtr; + + + // calculate dcvars for NEXT column + // texturecolumn and lighting are independent of wall tiers + // if (segtextured) // midtexture implied segtextured. + { + // calculate next texture offset + angle_t angle = (rw_centerangle + xtoviewangle[rw_x + 1]) >> ANGLETOFINESHIFT; + + texturecolumn = rw_offset - FixedMul(finetangent[angle], rw_distance); + + texturecolumn >>= FRACBITS; + + // calculate lighting + int index = rw_scale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + + dcvars.colormap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + + dcvars.x = rw_x; + + dcvars.iscale = iscale; + iscale = FixedReciprocal((unsigned)rw_scale + rw_scalestep) ; + } + + // load next column. Only if this is not the last one! + if (rw_x < rw_stopx - 1) + { + bufferNumber = 1 - bufferNumber; + nextColumnDataPtr = R_GetSinglePatchTextureColumnNonBlocking (tex, texturecolumn, columnBuffer[bufferNumber], iscale, &dmaOperation, 1); + } + R_DrawColumn(&dcvars); + dcvars.source = nextColumnDataPtr; + cc_rwx = draw_stopy + 1; + fc_rwx = draw_starty - 1; + + rw_scale += rw_scalestep; + topfrac += topstep; + bottomfrac += bottomstep; + + floorclip[rw_x] = fc_rwx; + ceilingclip[rw_x] = cc_rwx; + + } + #endif + } + else + { +#if 1 + // + dmaOperation_t dmaOperation = {.pendingDmaOperation = 0}; + bool validTop = false; + bool validBot = false; + bool wasOnExternalFlash = false; + uint32_t nBuff = 0; + draw_column_vars_t topDcvars; + draw_column_vars_t botDcvars; + void *nextTopColumnPtr, *nextBotColumnPtr; + // + texture_t *toptex, *bottex; + if (toptexture) + { + toptex = (texture_t*) R_GetOrLoadTexture(toptexture); + //cachePatchColumnOffsetData((patch_t*) toptex->patches[0].patch, toptex->width, rw_x , rw_stopx); + } + if (bottomtexture) + { + bottex = (texture_t*) R_GetOrLoadTexture(bottomtexture); +// cachePatchColumnOffsetData((patch_t*) bottex->patches[0].patch, bottex->width, rw_x , rw_stopx); + } + for (; rw_x < rw_stopx; rw_x++) + { + // mark floor / ceiling areas + + int yh = bottomfrac >> HEIGHTBITS; + int yl = (topfrac + HEIGHTUNIT - 1) >> HEIGHTBITS; + + int cc_rwx = ceilingclip[rw_x]; + int fc_rwx = floorclip[rw_x]; + + // no space above wall? + int bottom, top = cc_rwx + 1; + + if (yl < top) + yl = top; + + if (yl < draw_starty) + yl = draw_starty; + + if (yh > draw_stopy) + yh = draw_stopy; + + if (markceiling) + { + bottom = yl - 1; + + if (bottom >= fc_rwx) + bottom = fc_rwx - 1; + + if (top <= bottom) + { + ceilingplane->top[rw_x] = top; + ceilingplane->bottom[rw_x] = bottom; + ceilingplane->modified = 1; + } + // SoM: this should be set here + cc_rwx = bottom; + } + + bottom = fc_rwx - 1; + if (yh > bottom) + yh = bottom; + + if (markfloor) + { + + top = yh < cc_rwx ? cc_rwx : yh; + + if (++top <= bottom) + { + floorplane->top[rw_x] = top; + floorplane->bottom[rw_x] = bottom; + floorplane->modified = 1; + } + // SoM: This should be set here to prevent overdraw + fc_rwx = top; + } + + // texturecolumn and lighting are independent of wall tiers + lighttable_t *nextColorMap; + fixed_t iscale; + if (segtextured) + { + uint32_t index; + // calculate texture offset + angle_t angle = (rw_centerangle + xtoviewangle[rw_x]) >> ANGLETOFINESHIFT; + + texturecolumn = rw_offset - FixedMul(finetangent[angle], rw_distance); + + texturecolumn >>= FRACBITS; + + // calculate lighting + index = rw_scale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + nextColorMap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + iscale = FixedReciprocal((unsigned) rw_scale); + } + + // draw the wall tiers + { + + // two sided line + if (toptexture) + { + + // top wall + int mid = pixhigh >> HEIGHTBITS; + pixhigh += pixhighstep; + + if (mid >= fc_rwx) + mid = fc_rwx - 1; + + if (mid >= yl) + { + nextTopColumnPtr = R_GetSinglePatchTextureColumnNonBlocking(toptex, texturecolumn, columnBuffer[nBuff], iscale, &dmaOperation, 1); + cc_rwx = mid; + if (validTop) + { + R_DrawColumn(&topDcvars); + } + topDcvars.source = nextTopColumnPtr; + topDcvars.colormap = nextColorMap; + topDcvars.iscale = iscale; + topDcvars.yl = yl; + topDcvars.yh = mid; + topDcvars.texturemid = rw_toptexturemid; + topDcvars.x = rw_x; + validTop = true; + } + else + { + cc_rwx = yl - 1; + if (validTop) + { + // no column must be loaded but before we had to load via DMA and we did not wait (e.g. no bottom texture is present) + // we must make sure the column has been loaded + if (dmaOperation.topTextureLoadByDma) + { + while(!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } + dmaOperation.pendingDmaOperation = 0; // after this, for sure it has been loaded + R_DrawColumn(&topDcvars); + } + validTop = false; + } + } + else // no top wall + { + + if (markceiling) + cc_rwx = yl - 1; + } + + if (bottomtexture) // bottom wall + { + + int mid = (pixlow + HEIGHTUNIT - 1) >> HEIGHTBITS; + pixlow += pixlowstep; + + // no space above wall? + if (mid <= cc_rwx) + mid = cc_rwx + 1; + + if (mid <= yh) + { + nextBotColumnPtr = R_GetSinglePatchTextureColumnNonBlocking(bottex, texturecolumn, (uint8_t*) columnBuffer[nBuff] + 128, iscale, &dmaOperation, 0); + fc_rwx = mid; + if (validBot) + { + R_DrawColumn(&botDcvars); + } + validBot = true; + botDcvars.source = nextBotColumnPtr; + botDcvars.colormap = nextColorMap; + botDcvars.yl = mid; + botDcvars.yh = yh; + botDcvars.iscale = iscale; + botDcvars.texturemid = rw_bottomtexturemid; + botDcvars.x = rw_x; + } + else + { + fc_rwx = yh + 1; + if (validBot) + { + // no column must be loaded but before we had to load via DMA and we did not wait (e.g. no top texture is present) + // we must make sure the column has been loaded + if (dmaOperation.bottomTextureLoadByDma) + { + while(!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } + dmaOperation.pendingDmaOperation = 0; // after this, for sure it has been loaded + + R_DrawColumn(&botDcvars); + } + validBot = false; + } + + } + else // no bottom wall + { + if (markfloor) + fc_rwx = yh + 1; + } + + // cph - if we completely blocked further sight through this column, + // add this info to the solid columns array for r_bsp.c + if ((markceiling || markfloor) && (fc_rwx <= cc_rwx + 1)) + { + + solidcol[rw_x] = 1; + didsolidcol = 1; + } + // + nBuff = 1 - nBuff; + + // save texturecol for backdrawing of masked mid texture + if (maskedtexture) + maskedtexturecol[rw_x] = texturecolumn; + } + + rw_scale += rw_scalestep; + topfrac += topstep; + bottomfrac += bottomstep; + + floorclip[rw_x] = fc_rwx; + ceilingclip[rw_x] = cc_rwx; + } + if (validTop) + { + // no column must be loaded but before we had to load via DMA and we did not wait (e.g. no bottom texture is present) + // we must make sure the column has been loaded + if (dmaOperation.topTextureLoadByDma) + { + while(!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } + dmaOperation.pendingDmaOperation = 0; // after this, for sure it has been loaded + R_DrawColumn(&topDcvars); + } + if (validBot) + { + // no column must be loaded but before we had to load via DMA and we did not wait (e.g. no top texture is present) + // we must make sure the column has been loaded + if (dmaOperation.bottomTextureLoadByDma) + { + while(!NRF_QSPI->EVENTS_READY); + NRF_QSPI->EVENTS_READY = 0; + } + dmaOperation.pendingDmaOperation = 0; // after this, for sure it has been loaded + + R_DrawColumn(&botDcvars); + } + #else + uint8_t columnData[MAX_COLUMN_DATA]; + /* if (bottomtexture) + { + const texture_t *tex = R_GetOrLoadTexture(bottomtexture); + cachePatchColumnOffsetData((patch_t *) tex->patches[0].patch, tex->width, rw_x , rw_stopx); + }*/ + + for (; rw_x < rw_stopx; rw_x++) + { + // mark floor / ceiling areas + + int yh = bottomfrac >> HEIGHTBITS; + int yl = (topfrac + HEIGHTUNIT - 1) >> HEIGHTBITS; + + int cc_rwx = ceilingclip[rw_x]; + int fc_rwx = floorclip[rw_x]; + + // no space above wall? + int bottom, top = cc_rwx + 1; + + if (yl < top) + yl = top; + + if (yl < draw_starty) + yl = draw_starty; + + if (yh > draw_stopy) + yh = draw_stopy; + + if (markceiling) + { + bottom = yl - 1; + + if (bottom >= fc_rwx) + bottom = fc_rwx - 1; + + if (top <= bottom) + { + ceilingplane->top[rw_x] = top; + ceilingplane->bottom[rw_x] = bottom; + ceilingplane->modified = 1; + } + // SoM: this should be set here + cc_rwx = bottom; + } + + bottom = fc_rwx - 1; + if (yh > bottom) + yh = bottom; + + if (markfloor) + { + + top = yh < cc_rwx ? cc_rwx : yh; + + if (++top <= bottom) + { + floorplane->top[rw_x] = top; + floorplane->bottom[rw_x] = bottom; + floorplane->modified = 1; + } + // SoM: This should be set here to prevent overdraw + fc_rwx = top; + } + + // texturecolumn and lighting are independent of wall tiers + if (segtextured) + { + // calculate texture offset + angle_t angle = (rw_centerangle + xtoviewangle[rw_x]) >> ANGLETOFINESHIFT; + + texturecolumn = rw_offset - FixedMul(finetangent[angle], rw_distance); + + texturecolumn >>= FRACBITS; + + // calculate lighting + int index = rw_scale >> LIGHTSCALESHIFT; + + if (index >= MAXLIGHTSCALE) + index = MAXLIGHTSCALE - 1; + + dcvars.colormap = p_wad_immutable_flash_data->colormaps + 256 * scalelight[walllights][index]; + + dcvars.x = rw_x; + + dcvars.iscale = FixedReciprocal((unsigned) rw_scale); + } + + // draw the wall tiers + { + + // two sided line + if (toptexture) + { + // top wall + int mid = pixhigh >> HEIGHTBITS; + pixhigh += pixhighstep; + + if (mid >= fc_rwx) + mid = fc_rwx - 1; + + if (mid >= yl) + { + dcvars.yl = yl; + dcvars.yh = mid; + dcvars.texturemid = rw_toptexturemid; + const texture_t *tex = R_GetOrLoadTexture(toptexture); + R_DrawSegTextureColumn(tex, texturecolumn, &dcvars, columnData); + + cc_rwx = mid; + } + else + cc_rwx = yl - 1; + } + else // no top wall + { + + if (markceiling) + cc_rwx = yl - 1; + } + + if (bottomtexture) // bottom wall + { + int mid = (pixlow + HEIGHTUNIT - 1) >> HEIGHTBITS; + pixlow += pixlowstep; + + // no space above wall? + if (mid <= cc_rwx) + mid = cc_rwx + 1; + + if (mid <= yh) + { + dcvars.yl = mid; + dcvars.yh = yh; + dcvars.texturemid = rw_bottomtexturemid; + const texture_t *tex = R_GetOrLoadTexture(bottomtexture); + R_DrawSegTextureColumn(tex, texturecolumn, &dcvars, columnData); + + fc_rwx = mid; + } + else + fc_rwx = yh + 1; + } + else // no bottom wall + { + if (markfloor) + fc_rwx = yh + 1; + } + + // cph - if we completely blocked further sight through this column, + // add this info to the solid columns array for r_bsp.c + if ((markceiling || markfloor) && (fc_rwx <= cc_rwx + 1)) + { + + solidcol[rw_x] = 1; + didsolidcol = 1; + } + + // save texturecol for backdrawing of masked mid texture + if (maskedtexture) + maskedtexturecol[rw_x] = texturecolumn; + } + + rw_scale += rw_scalestep; + topfrac += topstep; + bottomfrac += bottomstep; + + floorclip[rw_x] = fc_rwx; + ceilingclip[rw_x] = cc_rwx; + } + #endif + } + #endif +} +// 2021-13-08 next-hack: created this function to copy openings by word and not by halfword +static inline void fastOpeningsCopy(short *dest, short * source, int num) +{ +#ifdef PARADISE + /* v0.2.3: source and destination are often only 2 byte aligned. GCC turns the word loop into LDRD/STRD, + * which always fault on Cortex-M3 at such addresses (seen on the device at game start). */ + if ((((uint32_t) dest | (uint32_t) source) & 3) != 0) + { + volatile short *vd = dest; + for (int i = 0; i < num; i++) + vd[i] = source[i]; + return; + } +#endif + int32_t *s = (int32_t*) source; + int32_t *d = (int32_t*) dest; + for (int i = 0; i < num / 2; i++) + { + *d++ = *s++; + } + // copy any odd opening + if (num & 1) + *((short*)d) = *((short*)s); +} + +static boolean R_CheckOpenings(const int start) +{ + int pos = _g->lastopening - openings; + int need = (rw_stopx - start) * 4 + pos; + +//#ifdef RANGECHECK + if (need > MAXOPENINGS) + printf("Openings overflow. Need = %d", need); +//#endif + + return need <= MAXOPENINGS; +} + +// +// R_StoreWallRange +// A wall segment will be drawn +// between start and stop pixels (inclusive). +// +FASTFUN static void R_StoreWallRange(const int start, const int stop) +{ + fixed_t hyp; + angle_t offsetangle; + + // don't overflow and crash + if (ds_p == &_g->drawsegs[MAXDRAWSEGS]) + { +#ifdef RANGECHECK + I_Error("Drawsegs overflow."); +#endif + return; + } + + linedata_t *linedata = &_g->linedata[curline->linenum]; + + // mark the segment as visible for auto map + linedata->r_flags |= RF_MAPPED; // 2020-03-14 next-hack was ML_MAPPED, changed to RF_MAPPED + + sidedef = &_g->sides[curline->sidenum]; + linedef = &_g->lines[curline->linenum]; + + // calculate rw_distance for scale calculation + rw_normalangle = curline->angle + ANG90; + + offsetangle = rw_normalangle - rw_angle1; + + if (D_abs(offsetangle) > ANG90) + offsetangle = ANG90; + + hyp = (viewx == curline->v1.x && viewy == curline->v1.y) ? 0 : R_PointToDist(curline->v1.x, curline->v1.y); + + rw_distance = FixedMul(hyp, finecosine[offsetangle >> ANGLETOFINESHIFT]); + + int rw_x = ds_p->x1 = start; + ds_p->x2 = stop; + ds_p->curline = curline; + rw_stopx = stop + 1; + + //Openings overflow. Nevermind. + if (!R_CheckOpenings(start)) + return; + + // calculate scale at both ends and step + ds_p->scale1 = rw_scale = R_ScaleFromGlobalAngle(viewangle + xtoviewangle[start]); + + if (stop > start) + { + ds_p->scale2 = R_ScaleFromGlobalAngle(viewangle + xtoviewangle[stop]); + ds_p->scalestep = rw_scalestep = (ds_p->scale2 - rw_scale) / (stop - start); + } + else + ds_p->scale2 = ds_p->scale1; + + // calculate texture boundaries + // and decide if floor / ceiling marks are needed + + worldtop = frontsector->ceilingheight - viewz; + worldbottom = frontsector->floorheight - viewz; + + midtexture = toptexture = bottomtexture = maskedtexture = 0; + ds_p->maskedtexturecol = NULL; + + if (!backsector) + { + // single sided line + midtexture = texturetranslation[getSideMidTexture(&_g->lines[curline->linenum], sidedef)]; + + // a single sided line is terminal, so it must mark ends + markfloor = markceiling = true; + + if (linedef->flags & ML_DONTPEGBOTTOM) + { // bottom of texture at bottom + fixed_t vtop = frontsector->floorheight + textureheight[getSideMidTexture(&_g->lines[curline->linenum], sidedef)]; + rw_midtexturemid = vtop - viewz; + } + else + // top of texture at top + rw_midtexturemid = worldtop; + + rw_midtexturemid += FixedMod((sidedef->rowoffset << FRACBITS), textureheight[midtexture]); + + ds_p->silhouette = SIL_BOTH; + ds_p->sprtopclip_ssptr = SCREENHEIGHTARRAY_PTR; //(short *) screenheightarray; + ds_p->sprbottomclip_ssptr = NEGONEARRAY_PTR; //(short *) negonearray; + ds_p->bsilheight = INT_MAX; + ds_p->tsilheight = INT_MIN; + } + else // two sided line + { + ds_p->sprtopclip_ssptr = ds_p->sprbottomclip_ssptr = 0; + ds_p->silhouette = 0; + + if (linedata->r_flags & RF_CLOSED) + { /* cph - closed 2S line e.g. door */ + // cph - killough's (outdated) comment follows - this deals with both + // "automap fixes", his and mine + // killough 1/17/98: this test is required if the fix + // for the automap bug (r_bsp.c) is used, or else some + // sprites will be displayed behind closed doors. That + // fix prevents lines behind closed doors with dropoffs + // from being displayed on the automap. + + ds_p->silhouette = SIL_BOTH; + ds_p->sprbottomclip_ssptr = NEGONEARRAY_PTR; //(short *) negonearray; + ds_p->bsilheight = INT_MAX; + ds_p->sprtopclip_ssptr = SCREENHEIGHTARRAY_PTR; //(short *) screenheightarray; + ds_p->tsilheight = INT_MIN; + + } + else + { /* not solid - old code */ + + if (frontsector->floorheight > backsector->floorheight) + { + ds_p->silhouette = SIL_BOTTOM; + ds_p->bsilheight = frontsector->floorheight; + } + else if (backsector->floorheight > viewz) + { + ds_p->silhouette = SIL_BOTTOM; + ds_p->bsilheight = INT_MAX; + } + + if (frontsector->ceilingheight < backsector->ceilingheight) + { + ds_p->silhouette |= SIL_TOP; + ds_p->tsilheight = frontsector->ceilingheight; + } + else if (backsector->ceilingheight < viewz) + { + ds_p->silhouette |= SIL_TOP; + ds_p->tsilheight = INT_MIN; + } + } + + worldhigh = backsector->ceilingheight - viewz; + worldlow = backsector->floorheight - viewz; + + // hack to allow height changes in outdoor areas + if (frontsector->ceilingpic == _g->skyflatnum && backsector->ceilingpic == _g->skyflatnum) + worldtop = worldhigh; + + markfloor = worldlow != worldbottom || backsector->floorpic != frontsector->floorpic || backsector->lightlevel != frontsector->lightlevel; + + markceiling = worldhigh != worldtop || backsector->ceilingpic != frontsector->ceilingpic || backsector->lightlevel != frontsector->lightlevel; + + if (backsector->ceilingheight <= frontsector->floorheight || backsector->floorheight >= frontsector->ceilingheight) + markceiling = markfloor = true; // closed door + + if (worldhigh < worldtop) // top texture + { + toptexture = texturetranslation[getSideTopTexture(linedef, sidedef)]; + rw_toptexturemid = + linedef->flags & ML_DONTPEGTOP ? worldtop : backsector->ceilingheight + textureheight[getSideTopTexture(linedef, sidedef)] - viewz; + rw_toptexturemid += FixedMod((sidedef->rowoffset << FRACBITS), textureheight[toptexture]); + } + + if (worldlow > worldbottom) // bottom texture + { + bottomtexture = texturetranslation[getSideBottomTexture(linedef, sidedef)]; + rw_bottomtexturemid = + linedef->flags & ML_DONTPEGBOTTOM ? worldtop : worldlow; + + rw_bottomtexturemid += FixedMod((sidedef->rowoffset << FRACBITS), textureheight[bottomtexture]); + } + + // allocate space for masked texture tables + if (getSideMidTexture(&_g->lines[curline->linenum], sidedef)) // masked midtexture + { + maskedtexture = true; + ds_p->maskedtexturecol = maskedtexturecol = _g->lastopening - rw_x; + _g->lastopening += rw_stopx - rw_x; + } + } + + // calculate rw_offset (only needed for textured lines) + segtextured = ((midtexture | toptexture | bottomtexture | maskedtexture) > 0); + + if (segtextured) + { + rw_offset = FixedMul(hyp, -finesine[offsetangle >> ANGLETOFINESHIFT]); + +// rw_offset += (sidedef->textureoffset << FRACBITS) + curline->offset; +// 2021-02-13 next-hack: now textureoffsets are stored in RAM in a separate array. sides are stored in flash + rw_offset += (_g->textureoffsets[curline->sidenum] << FRACBITS) + curline->offset; + + rw_centerangle = ANG90 + viewangle - rw_normalangle; + + rw_lightlevel = frontsector->lightlevel; + // calculate light table + // use different light tables + // for horizontal / vertical / diagonal + // OPTIMIZE: get rid of LIGHTSEGSHIFT globally + if (!fixedcolormap) + { + int lightnum = (rw_lightlevel >> LIGHTSEGSHIFT) + extralight; + + if (curline->v1.y == curline->v2.y) + lightnum--; + else if (curline->v1.x == curline->v2.x) + lightnum++; + + if (lightnum < 0) + walllights = 0; //scalelight[0]; + else if (lightnum >= LIGHTLEVELS) + walllights = LIGHTLEVELS - 1; //scalelight[LIGHTLEVELS-1]; + else + walllights = lightnum; //scalelight[lightnum]; + } + } + + // if a floor / ceiling plane is on the wrong side of the view + // plane, it is definitely invisible and doesn't need to be marked. + if (frontsector->floorheight >= viewz) // above view plane + markfloor = false; + if (frontsector->ceilingheight <= viewz && frontsector->ceilingpic != _g->skyflatnum) // below view plane + markceiling = false; + + // calculate incremental stepping values for texture edges + worldtop >>= 4; + worldbottom >>= 4; + + topstep = -FixedMul(rw_scalestep, worldtop); + topfrac = (centeryfrac >> 4) - FixedMul(worldtop, rw_scale); + // + bottomstep = -FixedMul(rw_scalestep, worldbottom); + bottomfrac = (centeryfrac >> 4) - FixedMul(worldbottom, rw_scale); + + if (backsector) + { + worldhigh >>= 4; + worldlow >>= 4; + + if (worldhigh < worldtop) + { + pixhigh = (centeryfrac >> 4) - FixedMul(worldhigh, rw_scale); + pixhighstep = -FixedMul(rw_scalestep, worldhigh); + } + if (worldlow > worldbottom) + { + pixlow = (centeryfrac >> 4) - FixedMul(worldlow, rw_scale); + pixlowstep = -FixedMul(rw_scalestep, worldlow); + } + } + + // render it + if (markceiling) + { + if (ceilingplane) // killough 4/11/98: add NULL ptr checks + ceilingplane = R_CheckPlane(ceilingplane, rw_x, rw_stopx - 1); + else + markceiling = 0; + } + + if (markfloor) + { + if (floorplane) // killough 4/11/98: add NULL ptr checks + /* cph 2003/04/18 - ceilingplane and floorplane might be the same + * visplane (e.g. if both skies); R_CheckPlane doesn't know about + * modifications to the plane that might happen in parallel with the check + * being made, so we have to override it and split them anyway if that is + * a possibility, otherwise the floor marking would overwrite the ceiling + * marking, resulting in HOM. */ + if (markceiling && ceilingplane == floorplane) + floorplane = R_DupPlane(floorplane, rw_x, rw_stopx - 1); + else + floorplane = R_CheckPlane(floorplane, rw_x, rw_stopx - 1); + else + markfloor = 0; + } + + didsolidcol = 0; + R_RenderSegLoop(rw_x); + + /* cph - if a column was made solid by this wall, we _must_ save full clipping info */ + if (backsector && didsolidcol) + { + if (!(ds_p->silhouette & SIL_BOTTOM)) + { + ds_p->silhouette |= SIL_BOTTOM; + ds_p->bsilheight = backsector->floorheight; + } + if (!(ds_p->silhouette & SIL_TOP)) + { + ds_p->silhouette |= SIL_TOP; + ds_p->tsilheight = backsector->ceilingheight; + } + } + + // save sprite clipping info + if (((ds_p->silhouette & SIL_TOP) || maskedtexture) && !ds_p->sprtopclip_ssptr) + { + #if 1 + fastOpeningsCopy(_g->lastopening, &ceilingclip[start], (rw_stopx - start)); + #else + for (int f = 0; f < (rw_stopx - start); f++) + { + _g->lastopening[f] = ceilingclip[f + start]; + } + #endif + ds_p->sprtopclip_ssptr = openingAddrToSsptr(_g->lastopening - start); + _g->lastopening += rw_stopx - start; + } + + if (((ds_p->silhouette & SIL_BOTTOM) || maskedtexture) && !ds_p->sprbottomclip_ssptr) + { +#if 1 + fastOpeningsCopy(_g->lastopening, &floorclip[start], (rw_stopx - start)); +#else + for (int f = 0; f < (rw_stopx - start); f++) + { + _g->lastopening[f] = floorclip[f + start]; + } +#endif + ds_p->sprbottomclip_ssptr = openingAddrToSsptr(_g->lastopening - start); + _g->lastopening += rw_stopx - start; + } + if (maskedtexture && !(ds_p->silhouette & SIL_TOP)) + { + ds_p->silhouette |= SIL_TOP; + ds_p->tsilheight = INT_MIN; + } + + if (maskedtexture && !(ds_p->silhouette & SIL_BOTTOM)) + { + ds_p->silhouette |= SIL_BOTTOM; + ds_p->bsilheight = INT_MAX; + } + + ds_p++; +} + +// killough 1/18/98 -- This function is used to fix the automap bug which +// showed lines behind closed doors simply because the door had a dropoff. +// +// cph - converted to R_RecalcLineFlags. This recalculates all the flags for +// a line, including closure and texture tiling. +static void R_RecalcLineFlags(void) +{ + linedata_t *linedata = &_g->linedata[linedef->lineno]; + + const side_t *side = &_g->sides[curline->sidenum]; + + linedata->r_validcount = (_g->gametic & VALIDCOUNT_MASK); + + /* First decide if the line is closed, normal, or invisible */ + if (!(linedef->flags & ML_TWOSIDED) || backsector->ceilingheight <= frontsector->floorheight || backsector->floorheight >= frontsector->ceilingheight || ( + // if door is closed because back is shut: + backsector->ceilingheight <= backsector->floorheight + + // preserve a kind of transparent door/lift special effect: + && (backsector->ceilingheight >= frontsector->ceilingheight || getSideTopTexture(linedef, side)) + + && (backsector->floorheight <= frontsector->floorheight || getSideBottomTexture(linedef, side)) + + // properly render skies (consider door "open" if both ceilings are sky): + && (backsector->ceilingpic != _g->skyflatnum || frontsector->ceilingpic != _g->skyflatnum))) + linedata->r_flags = (RF_CLOSED | (linedata->r_flags & RF_MAPPED)); // 2020-03-14 next-hack was ML_MAPPED, changed to RF_MAPPED + else + { + // Reject empty lines used for triggers + // and special events. + // Identical floor and ceiling on both sides, + // identical light levels on both sides, + // and no middle texture. + // CPhipps - recode for speed, not certain if this is portable though + if (backsector->ceilingheight != frontsector->ceilingheight || backsector->floorheight != frontsector->floorheight || getSideMidTexture(linedef, side) || backsector->ceilingpic != frontsector->ceilingpic || backsector->floorpic != frontsector->floorpic || backsector->lightlevel != frontsector->lightlevel) + { + linedata->r_flags = (linedata->r_flags & RF_MAPPED); + return; // 2020-03-14 next-hack was ML_MAPPED, changed to RF_MAPPED + } + else + linedata->r_flags = (RF_IGNORE | (linedata->r_flags & RF_MAPPED)); // 2020-03-14 next-hack was ML_MAPPED, changed to RF_MAPPED + } +} + +// CPhipps - +// R_ClipWallSegment +// +// Replaces the old R_Clip*WallSegment functions. It draws bits of walls in those +// columns which aren't solid, and updates the solidcol[] array appropriately + +static void R_ClipWallSegment(int first, int last, boolean solid) +{ + byte *p; + while (first < last) + { + if (solidcol[first]) + { + if (!(p = ByteFind(solidcol + first, 0, last - first))) + return; // All solid + + first = p - solidcol; + } + else + { + int to; + if (!(p = ByteFind(solidcol + first, 1, last - first))) + to = last; + else + to = p - solidcol; + + R_StoreWallRange(first, to - 1); + + if (solid) + { + memset(solidcol + first, 1, to - first); + } + + first = to; + } + } +} + +// +// R_ClearClipSegs +// + +// +// R_AddLine +// Clips the given segment +// and adds any visible pieces to the line list. +// + +static void R_AddLine(const seg_t *line) +{ + int x1; + int x2; + angle_t angle1; + angle_t angle2; + angle_t span; + angle_t tspan; + + curline = line; + + angle1 = R_PointToAngle(line->v1.x, line->v1.y); + angle2 = R_PointToAngle(line->v2.x, line->v2.y); + + // Clip to view edges. + span = angle1 - angle2; + + // Back side, i.e. backface culling + if (span >= ANG180) + return; + + // Global angle needed by segcalc. + rw_angle1 = angle1; + angle1 -= viewangle; + angle2 -= viewangle; + + tspan = angle1 + clipangle; + if (tspan > 2 * clipangle) + { + tspan -= 2 * clipangle; + + // Totally off the left edge? + if (tspan >= span) + return; + + angle1 = clipangle; + } + + tspan = clipangle - angle2; + if (tspan > 2 * clipangle) + { + tspan -= 2 * clipangle; + + // Totally off the left edge? + if (tspan >= span) + return; + angle2 = 0 - clipangle; + } + + // The seg is in the view range, + // but not necessarily visible. + + angle1 = (angle1 + ANG90) >> ANGLETOFINESHIFT; + angle2 = (angle2 + ANG90) >> ANGLETOFINESHIFT; + + // killough 1/31/98: Here is where "slime trails" can SOMETIMES occur: + x1 = viewangletox[angle1]; + x2 = viewangletox[angle2]; + + // Does not cross a pixel? + if (x1 >= x2) // killough 1/31/98 -- change == to >= for robustness + return; + + backsector = SG_BACKSECTOR(line); + + /* cph - roll up linedef properties in flags */ + linedef = &_g->lines[curline->linenum]; + linedata_t *linedata = &_g->linedata[linedef->lineno]; + + if (linedata->r_validcount != (_g->gametic & VALIDCOUNT_MASK)) + R_RecalcLineFlags(); + + if (linedata->r_flags & RF_IGNORE) + { + return; + } + else + R_ClipWallSegment(x1, x2, linedata->r_flags & RF_CLOSED); +} + +// +// R_Subsector +// Determine floor/ceiling planes. +// Add sprites of things in sector. +// Draw one or more line segments. +// +// killough 1/31/98 -- made static, polished + +static void R_Subsector(int num) +{ + int count; + const seg_t *line; + subsector_t *sub; + + sub = &_g->subsectors[num]; + frontsector = sub->sector; + count = sub->numlines; + line = &_g->segs[sub->firstline]; + if (frontsector->floorheight < viewz) + { + floorplane = R_FindPlane(frontsector->floorheight, frontsector->floorpic, frontsector->lightlevel // killough 3/16/98 + ); + } + else + { + floorplane = NULL; + } + + if (frontsector->ceilingheight > viewz || (frontsector->ceilingpic == _g->skyflatnum)) + { + ceilingplane = R_FindPlane(frontsector->ceilingheight, // killough 3/8/98 + frontsector->ceilingpic, frontsector->lightlevel); + } + else + { + ceilingplane = NULL; + } + + R_AddSprites(sub, frontsector->lightlevel); + while (count--) + { + R_AddLine(line); + line++; + curline = NULL; /* cph 2001/11/18 - must clear curline now we're done with it, so R_ColourMap doesn't try using it for other things */ + } +} + +// +// R_CheckBBox +// Checks BSP node/subtree bounding box. +// Returns true +// if some part of the bbox might be visible. +// + +static const byte checkcoord[12][4] = // killough -- static const +{ + { 3, 0, 2, 1 }, + { 3, 0, 2, 0 }, + { 3, 1, 2, 0 }, + { 0 }, + { 2, 0, 2, 1 }, + { 0, 0, 0, 0 }, + { 3, 1, 3, 0 }, + { 0 }, + { 2, 0, 3, 1 }, + { 2, 1, 3, 1 }, + { 2, 1, 3, 0 } +}; + +// killough 1/28/98: static // CPhipps - const parameter, reformatted +static boolean R_CheckBBox(const short *bspcoord) +{ + angle_t angle1, angle2; + + { + int boxpos; + const byte *check; + + // Find the corners of the box + // that define the edges from current viewpoint. + boxpos = (viewx <= ((fixed_t) bspcoord[BOXLEFT] << FRACBITS) ? 0 : + viewx < ((fixed_t) bspcoord[BOXRIGHT] << FRACBITS) ? 1 : 2) + ( + viewy >= ((fixed_t) bspcoord[BOXTOP] << FRACBITS) ? 0 : + viewy > ((fixed_t) bspcoord[BOXBOTTOM] << FRACBITS) ? 4 : 8); + + if (boxpos == 5) + return true; + + check = checkcoord[boxpos]; + angle1 = R_PointToAngle(((fixed_t) bspcoord[check[0]] << FRACBITS), ((fixed_t) bspcoord[check[1]] << FRACBITS)) - viewangle; + angle2 = R_PointToAngle(((fixed_t) bspcoord[check[2]] << FRACBITS), ((fixed_t) bspcoord[check[3]] << FRACBITS)) - viewangle; + } + + // cph - replaced old code, which was unclear and badly commented + // Much more efficient code now + if ((signed) angle1 < (signed) angle2) + { /* it's "behind" us */ + /* Either angle1 or angle2 is behind us, so it doesn't matter if we + * change it to the corect sign + */ + if ((angle1 >= ANG180) && (angle1 < ANG270)) + angle1 = INT_MAX; /* which is ANG180-1 */ + else + angle2 = INT_MIN; + } + + if ((signed) angle2 >= (signed) clipangle) + return false; // Both off left edge + if ((signed) angle1 <= -(signed) clipangle) + return false; // Both off right edge + if ((signed) angle1 >= (signed) clipangle) + angle1 = clipangle; // Clip at left edge + if ((signed) angle2 <= -(signed) clipangle) + angle2 = 0 - clipangle; // Clip at right edge + + // Find the first clippost + // that touches the source post + // (adjacent pixels are touching). + angle1 = (angle1 + ANG90) >> ANGLETOFINESHIFT; + angle2 = (angle2 + ANG90) >> ANGLETOFINESHIFT; + { + int sx1 = viewangletox[angle1]; + int sx2 = viewangletox[angle2]; + // const cliprange_t *start; + + // Does not cross a pixel. + if (sx1 == sx2) + return false; + + if (!ByteFind(solidcol + sx1, 0, sx2 - sx1)) + return false; + // All columns it covers are already solidly covered + } + + return true; +} + +//Render a BSP subsector if bspnum is a leaf node. +//Return false if bspnum is frame node. + +static boolean R_RenderBspSubsector(int bspnum) +{ + // Found a subsector? + if (bspnum & NF_SUBSECTOR) + { + if (bspnum == -1) + R_Subsector(0); + else + R_Subsector(bspnum & (~NF_SUBSECTOR)); + + return true; + } + + return false; +} + +// RenderBSPNode +// Renders all subsectors below a given node, +// traversing subtree recursively. +// Just call with BSP root. + +//Non recursive version. +//constant stack space used and easier to +//performance profile. + +static void R_RenderBSPNode(int bspnum) +{ + // 2021/05/22 next-hack: converted to short [] to avoid having a huge stack. + // after all, all the quantities are less than 32k. + // short bspstack[MAX_BSP_DEPTH]; + int sp = 0; + + const mapnode_t *bsp; + int side = 0; + + while (true) + { + //Front sides. + while (!R_RenderBspSubsector(bspnum)) + { + if (sp == MAX_BSP_DEPTH) + break; + + bsp = &nodes[bspnum]; + + side = R_PointOnSide(viewx, viewy, bsp); + + bspstack[sp++] = bspnum; + bspstack[sp++] = side; + + bspnum = bsp->children[side]; + } + + if (sp == 0) + { + //back at root node and not visible. All done! + return; + } + + //Back sides. + side = bspstack[--sp]; + bspnum = bspstack[--sp]; + bsp = &nodes[bspnum]; + + // Possibly divide back space. + //Walk back up the tree until we find + //a node that has a visible backspace. + while (!R_CheckBBox(bsp->bbox[side ^ 1])) + { + if (sp == 0) + { + //back at root node and not visible. All done! + return; + } + + //Back side next. + side = bspstack[--sp]; + bspnum = bspstack[--sp]; + + bsp = &nodes[bspnum]; + } + + bspnum = bsp->children[side ^ 1]; + } +} + +static void R_ClearDrawSegs(void) +{ + ds_p = _g->drawsegs; +} + +static void R_ClearClipSegs(void) +{ + memset(solidcol, 0, SCREENWIDTH); +} + +// +// R_ClearSprites +// Called at frame start. +// + +static void R_ClearSprites(void) +{ + num_vissprite = 0; // killough +} + +// +// RDrawPlanes +// At the end of each frame. +// + +static void R_DrawPlanes(void) +{ + for (int i = 0; i < MAXVISPLANES; i++) + { + visplane_t *pl = _g->visplanes[i]; + + while (pl) + { + if (pl->modified) + R_DoDrawPlane(pl); + + pl = pl->next; + } + } +} + +// +// R_ClearPlanes +// At begining of frame. +// + +static void R_ClearPlanes(void) +{ + int i; + + // opening / clipping determination + #if 1 + uint32_t *p_fc = (uint32_t*) floorclip; + uint32_t *p_cc = (uint32_t*) ceilingclip; + const uint16_t fcv = draw_stopy + 1; + const uint16_t ccv = draw_starty - 1; + + for (i = 0; i < SCREENWIDTH / 2; i++) + { + *p_fc++ = fcv | (fcv << 16); + *p_cc++ = ccv | (ccv << 16); + } +#else + for (i = 0; i < SCREENWIDTH; i++) + { + floorclip[i] = draw_stopy + 1, ceilingclip[i] = draw_starty - 1; + } +#endif + for (i = 0; i < MAXVISPLANES; i++) // new code -- killough + for (*_g->freehead = _g->visplanes[i], _g->visplanes[i] = NULL; *_g->freehead;) + _g->freehead = &(*_g->freehead)->next; + + _g->lastopening = openings; + + // scale will be unit scale at SCREENWIDTH/2 distance + //basexscale = FixedDiv (viewsin,projection); + //baseyscale = FixedDiv (viewcos,projection); + + basexscale = FixedMul(viewsin, iprojection); + baseyscale = FixedMul(viewcos, iprojection); +} + +// +// R_RenderView +// +void R_RenderPlayerView(player_t *player) +{ + + uint32_t tn; + + tn = I_GetTimeMicrosecs(); + + R_SetupFrame(player); + + + // Clear buffers. + R_ClearClipSegs(); + R_ClearDrawSegs(); + R_ClearPlanes(); + R_ClearSprites(); + + tn = I_GetTimeMicrosecs() - tn; + #define PROFILE_DRAWING 0 +#if PROFILE_DRAWING + printf("CL: %d us\r\n", tn); +#endif + tn = I_GetTimeMicrosecs(); + + // The head node is the last node output. + R_RenderBSPNode(numnodes - 1); + tn = I_GetTimeMicrosecs() - tn; +#if PROFILE_DRAWING + printf("RB: %d us\r\n", tn); +#endif + tn = I_GetTimeMicrosecs(); + + R_DrawPlanes(); + + tn = I_GetTimeMicrosecs() - tn; + +#if PROFILE_DRAWING + printf("DP: %d us\r\n", tn); +#endif + tn = I_GetTimeMicrosecs(); + + + R_DrawMasked(); + + tn = I_GetTimeMicrosecs() - tn; +#if PROFILE_DRAWING + printf("DM: %d us\r\n", tn); +#endif +} + +void V_DrawPatchNoScale(int x, int y, const patch_t *patch) +{ + + if (false == isOnExternalFlash(patch)) + { + y -= patch->topoffset; + x -= patch->leftoffset; + byte *desttop = (byte*) _g->screens[0].data; +#ifndef HIGHRES + desttop += (ScreenYToOffset(y) << 1) + x; + #else + desttop += (ScreenYToOffset(y)) + x; +#endif + unsigned int width = patch->width; + + for (unsigned int col = 0; col < width; col++, desttop++) + { + const column_t *column = (const column_t*) ((const byte*) patch + (0xFFFFFF & patch->columnofs[col])); + // step through the posts in a column + while (column->topdelta != 0xff) + { + const byte *source = (const byte*) column + 3; + byte *dest = desttop + (ScreenYToOffset(column->topdelta)); + + // next-hack 2021-03-15: clip to boundary + int starty = column->topdelta + y; + int stopy = column->topdelta + y + column->length - 1; + int count = column->length; + + // + if (starty < draw_starty) + { + int delta = draw_starty - starty; + source += delta; + count -= delta; + } + if (stopy > draw_stopy) + { + int delta = stopy - draw_stopy; + count -= delta; + } + // + #if 0 + if (count > 0) + { + unsigned int l = (count >> 4); + + while (l--) + { + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + } + unsigned int r = (count & 15); + + switch (r) + { + case 15: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 14: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 13: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 12: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 11: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 10: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 9: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 8: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 7: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 6: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 5: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 4: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 3: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 2: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 1: + *dest = *source++; + } + } + #else + if (count > 0) + { + while (count--) + { + unsigned int color = *source++; + *dest = color; + dest += v_pitch; + } + } + #endif + column = (const column_t*) ((const byte*) column + column->length + 4); + } + } + } + else + { +#if 1 + // data in spi flash. we need a different strategy + // + // get patch address; + spiFlashSetAddress((uint32_t) patch); + // now we need to load patch width, offsets and columnoffset + short width, height; + width = spiFlashGetShort(); + height = spiFlashGetShort(); // height, not used, but getting 2 bytes is cheaper than set the address again. + (void) height; // remove unused compiler warning + // remove offset + x -= spiFlashGetShort(); // patch->leftoffset; + y -= spiFlashGetShort(); // patch->topoffset; + + // actually we should create a much smaller size. But we reserved a good deed of stack for this + + int columnofs[MAX_PATCH_COLOFFS]; + // read column offs + // read column offs + if (width <= MAX_PATCH_COLOFFS) + { + spiFlashGetData(columnofs, width * sizeof(columnofs[0])); + } + else + { + spiFlashGetData(columnofs, MAX_PATCH_COLOFFS * sizeof(columnofs[0])); + } + byte *desttop = (byte*) _g->screens[0].data; + + desttop += (ScreenYToOffset(y)) + x; + + int coloffset = 0; + for (unsigned int colindex = 0; colindex < width; colindex++, desttop++) + { + // point to column + // workaround for too much wide patches + if (colindex - coloffset >= MAX_PATCH_COLOFFS) + { + // reload columnofs at the right point + coloffset = colindex; + spiFlashSetAddress((uint32_t) patch + 8 + 4 * coloffset); + if (width - coloffset <= MAX_PATCH_COLOFFS) + { + spiFlashGetData(columnofs, (width - coloffset) * sizeof(columnofs[0])); + } + else + { + spiFlashGetData(columnofs, MAX_PATCH_COLOFFS * sizeof(columnofs[0])); + } + } + spiFlashSetAddress((uint32_t) patch + (0xFFFFFF & columnofs[colindex - coloffset])); + + // + column_t columnInfo; + // read column info + spiFlashGetData(&columnInfo, sizeof(columnInfo)); + uint8_t columnData[MAX_COLUMN_DATA]; + + // step through the posts in a column + while (columnInfo.topdelta != 0xff) + { + // ignore first byte. + spiFlashGetByte(); + // get SPI data based on length + + spiFlashGetData(columnData, columnInfo.length); + // + const byte *source = (const byte*) columnData; + + byte *dest = desttop + (ScreenYToOffset(columnInfo.topdelta)); + + // next-hack 2021-03-15: clip to boundary + int starty = columnInfo.topdelta + y; + int stopy = columnInfo.topdelta + y + columnInfo.length - 1; + int count = columnInfo.length; + // + if (starty < draw_starty) + { + int delta = draw_starty - starty; + source += delta; + count -= delta; + } + if (stopy > draw_stopy) + { + int delta = stopy - draw_stopy; + count -= delta; + } + // + if (count > 0) + { + while (count--) + { + unsigned int color = *source++; + *dest = color; + dest += v_pitch; + } + } + // read again the column information + // ignore last post byte. + spiFlashGetByte(); + // read next info data (topdelta and length) + spiFlashGetData(&columnInfo, sizeof(columnInfo)); + } + } +#else + // data in spi flash. we need a different strategy + // + // get patch address; + spiFlashSetAddress((uint32_t) patch); + patchsizeoffsets_t pso; + spiFlashGetData((uint32_t) &pso, sizeof(pso)); + // now we need to load patch width, offsets and columnoffset + short width, height; + width = pso.width; + height = pso.height; + // remove offset + x -= pso.leftoffset; + y -= pso.topoffset; + + // actually we should create a much smaller size. But we reserved a good deed of stack for this + + // read column offs + // read column offs + cachePatchColumnOffsetData(patch, width, 0, width); + byte *desttop = (byte*) _g->screens[0].data; + + desttop += (ScreenYToOffset(y)) + x; + + for (unsigned int colindex = 0; colindex < width; colindex++, desttop++) + { + uint8_t columnData[MAX_COLUMN_DATA]; + const column_t *column = getColumnData(patch, colindex, columnData); + // step through the posts in a column + while (column->topdelta != 0xff) + { + const byte *source = (const byte*) column + 3; + byte *dest = desttop + (ScreenYToOffset(column->topdelta)); + + // next-hack 2021-03-15: clip to boundary + int starty = column->topdelta + y; + int stopy = column->topdelta + y + column->length - 1; + int count = column->length; + + // + if (starty < draw_starty) + { + int delta = draw_starty - starty; + source += delta; + count -= delta; + } + if (stopy > draw_stopy) + { + int delta = stopy - draw_stopy; + count -= delta; + } + // + #if 1 + if (count > 0) + { + unsigned int l = (count >> 4); + + while (l--) + { + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + *dest = *source++; + dest += v_pitch; + // + } + unsigned int r = (count & 15); + + switch (r) + { + case 15: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 14: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 13: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 12: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 11: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 10: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 9: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 8: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 7: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 6: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 5: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 4: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 3: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 2: + *dest = *source++; + dest += v_pitch; + // fall through, no break + case 1: + *dest = *source++; + } + } + #else + if (count > 0) + { + while (count--) + { + unsigned int color = *source++; + *dest = color; + dest += v_pitch; + } + } + #endif + column = (const column_t*) ((const byte*) column + column->length + 4); + } + } + + + #endif + + } +} + +// +// P_DivlineSide +// Returns side 0 (front), 1 (back), or 2 (on). +// +// killough 4/19/98: made static, cleaned up + +static int P_DivlineSide(fixed_t x, fixed_t y, const divline_t *node) +{ + fixed_t left, right; + return !node->dx ? x == node->x ? 2 : + x <= node->x ? node->dy > 0 : node->dy < 0 + : + !node->dy ? (y) == node->y ? 2 : + y <= node->y ? node->dx < 0 : node->dx > 0 + : + (right = ((y - node->y) >> FRACBITS) * (node->dx >> FRACBITS)) < (left = ((x - node->x) >> FRACBITS) * (node->dy >> FRACBITS)) ? 0 : + right == left ? 2 : 1; +} + +// +// P_CrossSubsector +// Returns true +// if strace crosses the given subsector successfully. +// +// killough 4/19/98: made static and cleaned up + +static boolean P_CrossSubsector(int num) +{ + const seg_t *seg = _g->segs + _g->subsectors[num].firstline; + int count; + fixed_t opentop = 0, openbottom = 0; + const sector_t *front = NULL, *back = NULL; + + for (count = _g->subsectors[num].numlines; --count >= 0; seg++) + { // check lines + int linenum = seg->linenum; + + const line_t *line = &_g->lines[linenum]; + divline_t divl; + + // allready checked other side? + if (_g->linedata[linenum].validcount == (_g->validcount)) + continue; + + _g->linedata[linenum].validcount = _g->validcount; + + if (line->bbox[BOXLEFT] > los.bbox[BOXRIGHT] || line->bbox[BOXRIGHT] < los.bbox[BOXLEFT] || line->bbox[BOXBOTTOM] > los.bbox[BOXTOP] || line->bbox[BOXTOP] < los.bbox[BOXBOTTOM]) + continue; + + // cph - do what we can before forced to check intersection + if (line->flags & ML_TWOSIDED) + { + + // no wall to block sight with? + if ((front = SG_FRONTSECTOR(seg))->floorheight == (back = SG_BACKSECTOR(seg))->floorheight && front->ceilingheight == back->ceilingheight) + continue; + + // possible occluder + // because of ceiling height differences + opentop = + front->ceilingheight < back->ceilingheight ? front->ceilingheight : back->ceilingheight; + + // because of floor height differences + openbottom = + front->floorheight > back->floorheight ? front->floorheight : back->floorheight; + + // cph - reject if does not intrude in the z-space of the possible LOS + if ((opentop >= los.maxz) && (openbottom <= los.minz)) + continue; + } + + // Forget this line if it doesn't cross the line of sight + const vertex_t *v1, *v2; + + v1 = &line->v1; + v2 = &line->v2; + + if (P_DivlineSide(v1->x, v1->y, &los.strace) == P_DivlineSide(v2->x, v2->y, &los.strace)) + continue; + + divl.dx = v2->x - (divl.x = v1->x); + divl.dy = v2->y - (divl.y = v1->y); + + // line isn't crossed? + if (P_DivlineSide(los.strace.x, los.strace.y, &divl) == P_DivlineSide(los.t2x, los.t2y, &divl)) + continue; + + // cph - if bottom >= top or top < minz or bottom > maxz then it must be + // solid wrt this LOS + if (!(line->flags & ML_TWOSIDED) || (openbottom >= opentop) || (opentop < los.minz) || (openbottom > los.maxz)) + return false; + + // crosses a two sided line + /* cph 2006/07/15 - oops, we missed this in 2.4.0 & .1; + * use P_InterceptVector2 for those compat levels only. */ + fixed_t frac = P_InterceptVector2(&los.strace, &divl); + + if (front->floorheight != back->floorheight) + { + fixed_t slope = FixedDiv(openbottom - los.sightzstart, frac); + if (slope > los.bottomslope) + los.bottomslope = slope; + } + + if (front->ceilingheight != back->ceilingheight) + { + fixed_t slope = FixedDiv(opentop - los.sightzstart, frac); + if (slope < los.topslope) + los.topslope = slope; + } + + if (los.topslope <= los.bottomslope) + return false; // stop + + } + // passed the subsector ok + return true; +} + +boolean P_CrossBSPNode(int bspnum) +{ + while (!(bspnum & NF_SUBSECTOR)) + { + const mapnode_t *bsp = nodes + bspnum; + + divline_t dl; + dl.x = ((fixed_t) bsp->x << FRACBITS); + dl.y = ((fixed_t) bsp->y << FRACBITS); + dl.dx = ((fixed_t) bsp->dx << FRACBITS); + dl.dy = ((fixed_t) bsp->dy << FRACBITS); + + int side, side2; + side = P_DivlineSide(los.strace.x, los.strace.y, &dl) & 1; + side2 = P_DivlineSide(los.t2x, los.t2y, &dl); + + if (side == side2) + bspnum = bsp->children[side]; // doesn't touch the other side + else // the partition plane is crossed here + if (!P_CrossBSPNode(bsp->children[side])) + return 0; // cross the starting side + else + bspnum = bsp->children[side ^ 1]; // cross the ending side + } + return P_CrossSubsector(bspnum == -1 ? 0 : bspnum & ~NF_SUBSECTOR); +} + +// +// P_MobjThinker +// + +void P_NightmareRespawn(mobj_t *mobj); +void P_XYMovement(mobj_t *mo); +void P_ZMovement(mobj_t *mo); + +// +// P_SetMobjState +// Returns true if the mobj is still present. +// + +boolean P_SetMobjState(mobj_t *mobj, statenum_t state) +{ + const state_t *st; + + do + { + if (state == S_NULL) + { + //mobj->state = (state_t *) S_NULL; + mobj->state_idx = state; + P_RemoveMobj(mobj); + return false; + } + // + //if (mobj->flags & MF_STATIC) + //{ + // printf("attempt to set mobjs state on static\r\n"); + // return false; + //} + st = &states[state]; + //mobj->state = st; + mobj->state_idx = state; + mobj->tics = st->tics; + mobj->sprite = st->sprite; + mobj->frame = st->frame; + + // Modified handling. + // Call action functions when the state is set + if (st->action) + { + if (!(_g->player.cheats & CF_ENEMY_ROCKETS)) + { + st->action(mobj); + } + else + { + if (getMobjInfo(mobj)->missilestate && (state >= getMobjInfo(mobj)->missilestate) && (state < getMobjInfo(mobj)->painstate)) + A_CyberAttack(mobj); + else + st->action(mobj); + } + } + + state = st->nextstate; + + } while (!mobj->tics); + + return true; +} + +void P_MobjThinker(mobj_t *mobj) +{ + // killough 11/98: + // removed old code which looked at target references + // (we use pointer reference counting now) + if (mobj->flags & MF_STATIC) + printf("Thinker on static object!\r\n"); + // momentum movement + if (mobj->momx || mobj->momy || (mobj->flags & MF_SKULLFLY )) // it was momx | momy, but it should have been || + { + P_XYMovement(mobj); + if (mobj->thinker.function != P_MobjThinker) // cph - Must've been removed + return; // killough - mobj was removed + } + + if (mobj->z != mobj->floorz || mobj->momz) + { + P_ZMovement(mobj); + if (mobj->thinker.function != P_MobjThinker) // cph - Must've been removed + return; // killough - mobj was removed + } + + // cycle through states, + // calling action functions at transitions + + if (mobj->tics != -1) + { + mobj->tics--; + + // you can cycle through multiple states in a tic + + if (!mobj->tics) + if (!P_SetMobjState(mobj, getMobjState(mobj)->nextstate)) + return; // freed itself + } + else + { + + // check for nightmare respawn + + if (!(mobj->flags & MF_COUNTKILL )) + return; + + if (!_g->respawnmonsters) + return; + + mobj->movecount++; + + if (mobj->movecount < 12 * 35) + return; + + if (_g->leveltime & 31) + return; + + if (P_Random(__FILE__, __LINE__, __FUNCTION__) > 4) + return; + + P_NightmareRespawn(mobj); + } + +} + +// +// P_RunThinkers +// +// killough 4/25/98: +// +// Fix deallocator to stop using "next" pointer after node has been freed +// (a Doom bug). +// +// Process each thinker. For thinkers which are marked deleted, we must +// load the "next" pointer prior to freeing the node. In Doom, the "next" +// pointer was loaded AFTER the thinker was freed, which could have caused +// crashes. +// +// But if we are not deleting the thinker, we should reload the "next" +// pointer after calling the function, in case additional thinkers are +// added at the end of the list. +// +// killough 11/98: +// +// Rewritten to delete nodes implicitly, by making currentthinker +// external and using P_RemoveThinkerDelayed() implicitly. +// + +void P_RunThinkers(void) +{ + thinker_t *th = getThinkerNext(&thinkercap); + thinker_t* th_end = &thinkercap; + + while(th != th_end) + { + thinker_t* th_next = getThinkerNext(th); + if(th->function) + th->function(th); + + th = th_next; + } +} + diff --git a/doom/src/pdoom/Doom/source/r_main.c b/doom/src/pdoom/Doom/source/r_main.c new file mode 100644 index 0000000..7767167 --- /dev/null +++ b/doom/src/pdoom/Doom/source/r_main.c @@ -0,0 +1,256 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * + * DESCRIPTION: + * Rendering main loop and setup functions, + * utility functions (BSP, geometry, trigonometry). + * See tables.c, too. + * + * next-hack: put here where tabulated values come from! + * restored zlight. + *-----------------------------------------------------------------------------*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "doomstat.h" +#include "d_net.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_things.h" +#include "r_plane.h" +#include "r_draw.h" +#include "m_bbox.h" +#include "r_sky.h" +#include "v_video.h" +#include "lprintf.h" +#include "st_stuff.h" +#include "i_main.h" +#include "i_system.h" +#include "g_game.h" +#include "tables.h" +#include "global_data.h" + +// Fineangles in the SCREENWIDTH wide window. +// uint8_t scalelight[LIGHTLEVELS][MAXLIGHTSCALE]; +// uint8_t zlight[LIGHTLEVELS][MAXLIGHTZ]; +#define FIELDOFVIEW 2048 +#define DISTMAP 2 +void R_InitTextureMapping(void) +{ +#if TABULATED_VALUES +#else + int i; + int x; + int t; + fixed_t focallength; + const int viewwidth = SCREENWIDTH; + const int centerx = viewwidth / 2; + const int centerxfrac = centerx << FRACBITS; + // Use tangent table to generate viewangletox: + // viewangletox will give the next greatest x + // after the view angle. + // + // Calc focallength + // so FIELDOFVIEW angles covers SCREENWIDTH. + focallength = FixedDiv(centerxfrac, finetangent[FINEANGLES / 4 + FIELDOFVIEW / 2]); + + for (i = 0; i < FINEANGLES / 2; i++) + { + if (finetangent[i] > FRACUNIT * 2) + t = -1; + else if (finetangent[i] < -FRACUNIT * 2) + t = viewwidth + 1; + else + { + t = FixedMul(finetangent[i], focallength); + t = (centerxfrac - t + FRACUNIT - 1) >> FRACBITS; + + if (t < -1) + t = -1; + else if (t > viewwidth + 1) + t = viewwidth + 1; + } + viewangletox[i] = t; + } + + // Scan viewangletox[] to generate xtoviewangle[]: + // xtoviewangle will give the smallest view angle + // that maps to x. + for (x = 0; x <= viewwidth; x++) + { + i = 0; + while (viewangletox[i] > x) + i++; + xtoviewangle[x] = (i << ANGLETOFINESHIFT) - ANG90; + } + + // Take out the fencepost cases from viewangletox. + for (i = 0; i < FINEANGLES / 2; i++) + { + t = FixedMul(finetangent[i], focallength); + t = centerx - t; + + if (viewangletox[i] == -1) + viewangletox[i] = 0; + else if (viewangletox[i] == viewwidth + 1) + viewangletox[i] = viewwidth; + } + printf("clip angle %d", xtoviewangle[0]); + // clipangle = xtoviewangle[0]; + // + const int detailshift = 0; + // planes + fixed_t dy; + for (i = 0; i < viewheight; i++) + { + dy = ((i - viewheight / 2) << FRACBITS) + FRACUNIT / 2; + dy = abs(dy); + yslope[i] = FixedDiv(projectiony, dy); + } + // + fixed_t cosadj; + for (i = 0; i < viewwidth; i++) + { + cosadj = abs(finecosine[xtoviewangle[i] >> ANGLETOFINESHIFT]); + distscale[i] = FixedDiv(FRACUNIT, cosadj); + } + // Calculate the light levels to use + // for each level / scale combination. + + int i; + int j; + int level; + int startmap; + int scale; + + for (i = 0; i < LIGHTLEVELS; i++) + { + startmap = ((LIGHTLEVELS - 1 - i) * 2) * NUMCOLORMAPS / LIGHTLEVELS; + for (j = 0; j < MAXLIGHTSCALE; j++) + { + level = startmap - j / DISTMAP; + + if (level < 0) + { + level = 0; + } + + if (level >= NUMCOLORMAPS) + { + level = NUMCOLORMAPS - 1; + } + + scalelight[i][j] = level; // colormaps + level*256; + } + } + // zlight + for (i = 0; i < LIGHTLEVELS; i++) + { + startmap = ((LIGHTLEVELS - 1 - i) * 2) * NUMCOLORMAPS / LIGHTLEVELS; + for (j = 0; j < MAXLIGHTZ; j++) + { + scale = FixedDiv((SCREENWIDTH / 2 * FRACUNIT), (j + 1) << LIGHTZSHIFT); + scale >>= LIGHTSCALESHIFT; + level = startmap - scale / DISTMAP; + + if (level < 0) + { + level = 0; + } + if (level >= NUMCOLORMAPS) + { + level = NUMCOLORMAPS - 1; + } + zlight[i][j] = level; // colormaps + level*256; + } + } +#endif +} + +// +// R_Init +// + +void R_Init(void) +{ + // trig tables in rom + // lprintf(LO_INFO, "R_LoadTrigTables"); + // R_LoadTrigTables(); + // Data are tabulated. This call is kept to show where tabulated values come from + R_InitTextureMapping(); + // + lprintf(LO_INFO, "R_InitData"); + R_InitData(); + lprintf(LO_INFO, "R_InitBuffer"); + R_InitBuffer(); +} + +// +// R_SetupFrame +// + +void R_SetupFrame(player_t * player) +{ + _g->viewplayer = player; + + viewx = player->mo->x; + viewy = player->mo->y; + viewz = player->viewz; + viewangle = player->mo->angle; + + extralight = player->extralight; + + viewsin = finesine[viewangle >> ANGLETOFINESHIFT]; + viewcos = finecosine[viewangle >> ANGLETOFINESHIFT]; + + fullcolormap = &p_wad_immutable_flash_data->colormaps[0]; + if (player->fixedcolormap) + { + fixedcolormap = fullcolormap // killough 3/20/98: use fullcolormap + + player->fixedcolormap * 256 * sizeof(lighttable_t); + } + else + fixedcolormap = 0; + + _g->validcount++; + // +} \ No newline at end of file diff --git a/doom/src/pdoom/Doom/source/r_patch.c b/doom/src/pdoom/Doom/source/r_patch.c new file mode 100644 index 0000000..6275949 --- /dev/null +++ b/doom/src/pdoom/Doom/source/r_patch.c @@ -0,0 +1,73 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * next-hack: support for patches i external flash + * + *-----------------------------------------------------------------------------*/ + +#include "z_zone.h" +#include "doomstat.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_sky.h" +#include "r_things.h" +#include "p_tick.h" +#include "i_system.h" +#include "r_draw.h" +#include "lprintf.h" +#include "r_patch.h" +#include +#include "i_spi_support.h" +#include "global_data.h" +#include "r_patch.h" +#include "i_memory.h" + +//--------------------------------------------------------------------------- +int R_NumPatchWidth(int lump) +{ + + return p_wad_immutable_flash_data->patchLumpSizeOffsets[lump].width; +} + +//--------------------------------------------------------------------------- +int R_NumPatchHeight(int lump) +{ + return p_wad_immutable_flash_data->patchLumpSizeOffsets[lump].height; +} + diff --git a/doom/src/pdoom/Doom/source/r_plane.c b/doom/src/pdoom/Doom/source/r_plane.c new file mode 100644 index 0000000..20c6363 --- /dev/null +++ b/doom/src/pdoom/Doom/source/r_plane.c @@ -0,0 +1,85 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Here is a core component: drawing the floors and ceilings, + * while maintaining a per column clipping list only. + * Moreover, the sky areas have to be determined. + * + * MAXVISPLANES is no longer a limit on the number of visplanes, + * but a limit on the number of hash slots; larger numbers mean + * better performance usually but after a point they are wasted, + * and memory and time overheads creep in. + * + * For more information on visplanes, see: + * + * http://classicgaming.com/doom/editing/ + * + * Lee Killough + * + *-----------------------------------------------------------------------------*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "z_zone.h" /* memory allocation wrappers -- killough */ + +#include "doomstat.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_draw.h" +#include "r_things.h" +#include "r_sky.h" +#include "r_plane.h" +#include "v_video.h" +#include "lprintf.h" + +#include "global_data.h" + + + +//Planes are alloc'd with PU_LEVEL tag so are dumped at level +//end. This function resets the visplane arrays. +void R_ResetPlanes() +{ + memset(_g->visplanes, 0, sizeof(_g->visplanes)); + _g->freetail = NULL; + _g->freehead = &_g->freetail; +} diff --git a/doom/src/pdoom/Doom/source/r_things.c b/doom/src/pdoom/Doom/source/r_things.c new file mode 100644 index 0000000..64c325c --- /dev/null +++ b/doom/src/pdoom/Doom/source/r_things.c @@ -0,0 +1,278 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Refresh of things, i.e. objects represented by sprites. + * + * next-hack: + * - init sprite def now uses stack, instead of a global variable, + * saving few hundred bytes of RAM. + * - init sprite calculate the sprites arrays and save it to immutable flash + * region, saving several kB of RAM + *-----------------------------------------------------------------------------*/ + +#include "doomstat.h" +#include "w_wad.h" +#include "r_main.h" +#include "r_segs.h" +#include "r_draw.h" +#include "r_things.h" +#include "v_video.h" +#include "lprintf.h" +#include "z_zone.h" + +#include "global_data.h" +#include "i_spi_support.h" + +// +// Sprite rotation 0 is facing the viewer, +// rotation 1 is one angle turn CLOCKWISE around the axis. +// This is not the same as the angle, +// which increases counter clockwise (protractor). +// There was a lot of stuff grabbed wrong, so I changed it... +// + +// +// INITIALIZATION FUNCTIONS +// + +// +// R_InstallSpriteLump +// Local function for R_InitSprites. +// + +static void R_InstallSpriteLump(int lump, unsigned frame, unsigned rotation, boolean flipped, spriteframe_t *sprtemp) // 2021/03/20 next-hack: the sprtemp is declared on the calling function, no need to use a global static var +{ + if (frame >= MAX_SPRITE_FRAMES || rotation > 8) + I_Error("R_InstallSpriteLump: Bad frame characters in lump %i", lump); + + if ((int) frame > _g->maxframe) + _g->maxframe = frame; + + if (rotation == 0) + { // the lump should be used for all rotations + int r; + + sprtemp[frame].flipmask = 0; + + for (r = 0; r < 8; r++) + { + if (sprtemp[frame].lump[r] == -1) + { + sprtemp[frame].lump[r] = lump - _g->firstspritelump; + + if (flipped) + sprtemp[frame].flipmask |= (1 << r); + + sprtemp[frame].rotate = false; //jff 4/24/98 if any subbed, rotless + } + } + return; + } + + // the lump is only used for one rotation + + if (sprtemp[frame].lump[--rotation] == -1) + { + sprtemp[frame].lump[rotation] = lump - _g->firstspritelump; + + if (flipped) + sprtemp[frame].flipmask |= (1 << rotation); + else + sprtemp[frame].flipmask &= (~(1 << rotation)); + + sprtemp[frame].rotate = true; //jff 4/24/98 only change if rot used + } +} + +// +// R_InitSpriteDefs +// Pass a null terminated list of sprite names +// (4 chars exactly) to be used. +// +// Builds the sprite rotation matrixes to account +// for horizontally flipped sprites. +// +// Will report an error if the lumps are inconsistent. +// Only called at startup. +// +// Sprite lump names are 4 characters for the actor, +// a letter for the frame, and a number for the rotation. +// +// A sprite that is flippable will have an additional +// letter/number appended. +// +// The rotation character can be 0 to signify no rotations. +// +// 1/25/98, 1/31/98 killough : Rewritten for performance +// +// Empirically verified to have excellent hash +// properties across standard Doom sprites: + +#define R_SpriteNameHash(s) ((unsigned)((s)[0]-((s)[1]*3-(s)[3]*2-(s)[2])*2)) + +static void R_InitSpriteDefs(const char *const*namelist) +{ + // 2021/03/20 next-hack. Instead of statically using _g->sprtemp[], that we only use here, we use the stack + spriteframe_t sprtemp[MAX_SPRITE_FRAMES]; + size_t numentries = _g->lastspritelump - _g->firstspritelump + 1; + struct + { + int index, next; + } *hash; + int i, numsprites; + + if (!numentries || !*namelist) + return; + + // count the number of sprite names + for (i = 0; namelist[i]; i++); + // + numsprites = i; + // + p_wad_immutable_flash_data->numsprites = i; + // + spritedef_t *sprites = Z_Malloc(numsprites * sizeof(*sprites), PU_STATIC, NULL); // sprite_data_ptr; + + memset(sprites, 0, numsprites * sizeof(*sprites)); + + // Create hash table based on just the first four letters of each sprite + // killough 1/31/98 + + hash = malloc(sizeof(*hash) * numentries); // allocate hash table + + for (i = 0; (size_t) i < numentries; i++) // initialize hash table as empty + hash[i].index = -1; + + for (i = 0; (size_t) i < numentries; i++) // Prepend each sprite to hash chain + { // prepend so that later ones win + char sn[8]; + spiFlashSetAddress((uint32_t) W_GetNameForNum(i + _g->firstspritelump)); + spiFlashGetData(sn, sizeof(sn)); + int j = R_SpriteNameHash(sn) % numentries; + hash[i].next = hash[j].index; + hash[j].index = i; + } + + // scan all the lump names for each of the names, + // noting the highest frame letter. + + for (i = 0; i < numsprites; i++) + { + const char *spritename = namelist[i]; + int j = hash[R_SpriteNameHash(spritename) % numentries].index; + + if (j >= 0) + { + memset(sprtemp, -1, sizeof(sprtemp)); + _g->maxframe = -1; + do + { + char sn[8]; + spiFlashSetAddress((uint32_t) W_GetNameForNum(j + _g->firstspritelump)); + spiFlashGetData(sn, sizeof(sn)); + // Fast portable comparison -- killough + // (using int pointer cast is nonportable): + + if (!((sn[0] ^ spritename[0]) | (sn[1] ^ spritename[1]) | (sn[2] ^ spritename[2]) | (sn[3] ^ spritename[3]))) + { + R_InstallSpriteLump(j + _g->firstspritelump, sn[4] - 'A', sn[5] - '0', + false, sprtemp); + if (sn[6]) + R_InstallSpriteLump(j + _g->firstspritelump, sn[6] - 'A', sn[7] - '0', + true, sprtemp); + } + } while ((j = hash[j].next) >= 0); + + // check the frames that were found for completeness + if ((sprites[i].numframes = ++_g->maxframe)) // killough 1/31/98 + { + int frame; + for (frame = 0; frame < _g->maxframe; frame++) + { + switch ((int) sprtemp[frame].rotate) + { + case -1: + // no rotations were found for that frame at all + I_Error("R_InitSprites: No patches found " + "for %.8s frame %c", namelist[i], frame + 'A'); + break; + + case 0: + // only the first rotation is needed + break; + + case 1: + // must have all 8 frames + { + int rotation; + for (rotation = 0; rotation < 8; rotation++) + if (sprtemp[frame].lump[rotation] == -1) + I_Error("R_InitSprites: Sprite %.8s frame %c " + "is missing rotations", namelist[i], frame + 'A'); + break; + } + } + } + + sprites[i].spriteframes = writeBufferToFlashRegion(sprtemp, _g->maxframe * sizeof(spriteframe_t), FLASH_IMMUTABLE_REGION, true); + } + } + } + // copy array to flash + p_wad_immutable_flash_data->sprites = writeBufferToFlashRegion(sprites, numsprites * sizeof(*sprites), FLASH_IMMUTABLE_REGION, true); + Z_Free(sprites); + printf("Saved %d sprites\r\n", numsprites); + free(hash); // free hash table +} + +// +// GAME FUNCTIONS +// + +// +// R_InitSprites +// Called at program start. +// + +void R_InitSprites(const char *const*namelist) +{ + R_InitSpriteDefs(namelist); +} + diff --git a/doom/src/pdoom/Doom/source/s_sound.c b/doom/src/pdoom/Doom/source/s_sound.c new file mode 100644 index 0000000..64cd6e1 --- /dev/null +++ b/doom/src/pdoom/Doom/source/s_sound.c @@ -0,0 +1,653 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: Platform-independent sound code + * + * next-hack: sounds lump are now pre-cached in immutable flash region, + * so there is no need to find lump by name, but just using a index. + * Tweaked some functions. + * + *-----------------------------------------------------------------------------*/ + +// killough 3/7/98: modified to allow arbitrary listeners in spy mode +// killough 5/2/98: reindented, removed useless code, beautified +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "doomstat.h" +#include "s_sound.h" +#include "i_sound.h" +#include "i_system.h" +#include "d_main.h" +#include "r_main.h" +#include "m_random.h" +#include "w_wad.h" +#include "lprintf.h" + +#include "global_data.h" +#include "pwm_audio.h" +// when to clip out sounds +// Does not fit the large outdoor areas. +#define S_CLIPPING_DIST (1200<>FRACBITS) + +// Adjustable by menu. +#define NORM_PRIORITY 64 +#define NORM_SEP 128 + +#define S_STEREO_SWING (96*0x10000) + +// number of channels available +static const unsigned int numChannels = MAX_CHANNELS; + +// +// Internals. +// + +void S_StopChannel(int cnum); + +int S_AdjustSoundParams(mobj_t *listener, mobj_t *source, int *vol, int *sep); + +static int S_getChannel(void *origin, const sfxinfo_t *sfxinfo, int is_pickup); + +// Initializes sound stuff, including volume +// Sets channels, SFX and music volume, +// allocates channel buffer, sets S_sfx lookup. +// + +void S_Init(int sfxVolume, int musicVolume) +{ + // next-hack preload all sound lump number + uint32_t *soundLumps = Z_Malloc(NUMSFX * sizeof(uint32_t), PU_STATIC, NULL); + for (int i = 0; i < NUMSFX; i++) + { + soundLumps[i] = W_CheckNumForName(S_sfx[i].name); + } + p_wad_immutable_flash_data->soundLumps = writeBufferToFlashRegion(soundLumps, NUMSFX * sizeof(uint32_t), FLASH_IMMUTABLE_REGION, true); + Z_Free(soundLumps); + //jff 1/22/98 skip sound init if sound not enabled + if (!nosfxparm) + { + + lprintf(LO_CONFIRM, "S_Init: default sfx volume %d", sfxVolume); + + S_SetSfxVolume(sfxVolume); + + // Allocating the internal channels for mixing + // (the maximum numer of sounds rendered + // simultaneously) within zone memory. + // CPhipps - calloc + _g->channels = (channel_t*) calloc(numChannels, sizeof(channel_t)); + } + + // CPhipps - music init reformatted + if (!nomusicparm) + { + S_SetMusicVolume(musicVolume); + + // no sounds are playing, and they are not mus_paused + _g->mus_paused = 0; + } +} + +void S_Stop(void) +{ + unsigned int cnum; + + //jff 1/22/98 skip sound init if sound not enabled + if (!nosfxparm) + { + for (cnum = 0; cnum < numChannels; cnum++) + { + if (_g->channels[cnum].sfxinfo) + { + S_StopChannel(cnum); + } + } + muteSound(); + } +} + +// +// Per level startup code. +// Kills playing sounds at start of level, +// determines music if any, changes music. +// +void S_Start(void) +{ + int mnum; + + // kill all playing sounds at start of level + // (trust me - a good idea) + + S_Stop(); + + //jff 1/22/98 return if music is not enabled + if (nomusicparm) + return; + + // start new music for the level + _g->mus_paused = 0; + + if (_g->idmusnum != -1) + mnum = _g->idmusnum; //jff 3/17/98 reload IDMUS music if not -1 + else if (_g->gamemode == commercial) + mnum = mus_runnin + _g->gamemap - 1; + else + { + static const int spmus[] = // Song - Who? - Where? + { mus_e3m4, // American e4m1 + mus_e3m2, // Romero e4m2 + mus_e3m3, // Shawn e4m3 + mus_e1m5, // American e4m4 + mus_e2m7, // Tim e4m5 + mus_e2m4, // Romero e4m6 + mus_e2m6, // J.Anderson e4m7 CHIRON.WAD + mus_e2m5, // Shawn e4m8 + mus_e1m9 // Tim e4m9 + }; + + if (_g->gameepisode < 4) + mnum = mus_e1m1 + (_g->gameepisode - 1) * 9 + _g->gamemap - 1; + else + mnum = spmus[_g->gamemap - 1]; + } +#ifdef PDM_LUMPTXT + /* Paramix 1.7.3 test17: an episode put in the place of E4 (Sigil) brings its own songs D_E4M1..: the song number + * stays (the engine knows no more), the name of the lump changes for it (plat_mus_name) */ + { + extern int pdm_mus_h; extern char pdm_mus_n[9]; + pdm_mus_h = 0; + if (_g->gamemode != commercial && _g->gameepisode == 4 && _g->gamemap >= 1 && _g->gamemap <= 9) + { + pdm_mus_n[0] = 'D'; pdm_mus_n[1] = '_'; pdm_mus_n[2] = 'E'; pdm_mus_n[3] = '4'; pdm_mus_n[4] = 'M'; + pdm_mus_n[5] = (char) ('0' + _g->gamemap); pdm_mus_n[6] = 0; + if (W_CheckNumForName(pdm_mus_n) >= 0) + pdm_mus_h = mnum; + } + } +#endif + S_ChangeMusic(mnum, true); +} + +void S_StartSoundAtVolume(mobj_t *origin, int sfx_id, int volume) +{ + int /*priority, */cnum, is_pickup; + const sfxinfo_t *sfx; + + int sep = NORM_SEP; + + //jff 1/22/98 return if sound is not enabled + if (nosfxparm) + return; + + is_pickup = (sfx_id & PICKUP_SOUND) || sfx_id == sfx_oof || (sfx_id == sfx_noway); // killough 4/25/98 + sfx_id &= ~PICKUP_SOUND; + + // check for bogus sound # + if (sfx_id < 1 || sfx_id > NUMSFX) + I_Error("S_StartSoundAtVolume: Bad sfx #: %d", sfx_id); + + sfx = &S_sfx[sfx_id]; + + // Initialize sound parameters + if (sfx->link) + { +// priority = sfx->priority; + volume += sfx->volume; + + if (volume < 1) + return; + + if (volume > _g->snd_SfxVolume) + volume = _g->snd_SfxVolume; + } + else + { +// priority = NORM_PRIORITY; + } + + // Check to see if it is audible, modify the params + // killough 3/7/98, 4/25/98: code rearranged slightly + + if (!origin || origin == _g->player.mo) + { + volume *= 8; + } + else + { + if (!S_AdjustSoundParams(_g->player.mo, origin, &volume, &sep)) + { + return; + } + } + + // kill old sound + for (cnum = 0; cnum < numChannels; cnum++) + { + if (_g->channels[cnum].sfxinfo && _g->channels[cnum].origin == origin && (_g->channels[cnum].is_pickup == is_pickup)) + { + + S_StopChannel(cnum); + break; + } + } + // try to find a channel + cnum = S_getChannel(origin, sfx, is_pickup); + + if (cnum < 0) + { + return; + } + int h = I_StartSound(sfx_id, cnum, volume, sep); + if (h != -1) + { + _g->channels[cnum].handle = h; + _g->channels[cnum].tickend = (_g->gametic + sfx->ticks); + } + +} + +void S_StartSound(mobj_t *origin, int sfx_id) +{ + S_StartSoundAtVolume(origin, sfx_id, _g->snd_SfxVolume); +} + +void S_StartSound2(degenmobj_t *origin, int sfx_id) +{ + //Look at this mess. + + //Originally, the degenmobj_t had + //a thinker_t at the start of the struct + //so that it could be passed around and + //cast to a mobj_t* in the sound code + //for non-mobj sound makers like doors. + + //This also meant that each and every sector_t + //struct has 24 bytes wasted. I can't afford + //to waste memory like that so we have a seperate + //function for these cases which cobbles toget a temp + //mobj_t-like struct to pass to the sound code. + + static_mobj_t tmpMobj; +// next-hack: due to mobj_t member reordering, this stuff cannot be used. We can use a static_mobj_t instead, +// which is smaller than a regular mobj_t + /* struct fake_mobj + { + thinker_t ununsed; + degenmobj_t origin; + } fm;*/ + + tmpMobj.x = origin->x; + tmpMobj.y = origin->y; + S_StartSoundAtVolume((mobj_t*) &tmpMobj, sfx_id, _g->snd_SfxVolume); +} + +void S_StopSound(void *origin) +{ + int cnum; + + //jff 1/22/98 return if sound is not enabled + if (nosfxparm) + return; + + for (cnum = 0; cnum < numChannels; cnum++) + { + if (_g->channels[cnum].sfxinfo && _g->channels[cnum].origin == origin) + { + S_StopChannel(cnum); + break; + } + } +} + +// +// Stop and resume music, during game PAUSE. +// +void S_PauseSound(void) +{ + //jff 1/22/98 return if music is not enabled + if (nomusicparm) + return; + + if (_g->mus_playing && !_g->mus_paused) + { + I_PauseSong(0); + _g->mus_paused = true; + } +} + +void S_ResumeSound(void) +{ + //jff 1/22/98 return if music is not enabled + if (nomusicparm) + return; + + if (_g->mus_playing && _g->mus_paused) + { + I_ResumeSong(0); + _g->mus_paused = false; + } +} + +static boolean S_SoundIsPlaying(int cnum) +{ + const channel_t *channel = &_g->channels[cnum]; + + if (channel->sfxinfo) + { + // next-hack: warning this is very bugged, because it does not count overflow. + // On the other side, I don't think anyone is playing the same level for + // 61,356,675 seconds (two years). + int ticknow = _g->gametic; + return (channel->tickend >= ticknow); // this was bugged anyway, was < + } + + return false; +} + +// +// Updates music & sounds +// +void S_UpdateSounds(void *listener_p) +{ + //mobj_t *listener = (mobj_t*) listener_p; + int cnum; + //int sep = NORM_SEP; + + //jff 1/22/98 return if sound is not enabled + if (nosfxparm) + return; + + for (cnum = 0; cnum < numChannels; cnum++) + { + const sfxinfo_t *sfx; + channel_t *c = &_g->channels[cnum]; + + if ((sfx = c->sfxinfo)) + { + if (S_SoundIsPlaying(c->handle)) + { + // initialize parameters + int volume = _g->snd_SfxVolume; + + if (sfx->link) + { + volume += sfx->volume; + + if (volume < 1) + { + S_StopChannel(cnum); + continue; + } + else + { + if (volume > _g->snd_SfxVolume) + volume = _g->snd_SfxVolume; + } + } + } + else // if channel is allocated but sound has stopped, free it + { + S_StopChannel(cnum); + } + } + } +} + +void S_SetMusicVolume(int volume) +{ + //jff 1/22/98 return if music is not enabled + if (nomusicparm) + return; + if (volume < 0 || volume > 15) + I_Error("S_SetMusicVolume: Attempt to set music volume at %d", volume); + I_SetMusicVolume(volume); + _g->snd_MusicVolume = volume; +} + +void S_SetSfxVolume(int volume) +{ + //jff 1/22/98 return if sound is not enabled + if (nosfxparm) + return; + if (volume < 0 || volume > 127) + I_Error("S_SetSfxVolume: Attempt to set sfx volume at %d", volume); + _g->snd_SfxVolume = volume; +} + +// Starts some music with the music id found in sounds.h. +// +void S_StartMusic(int m_id) +{ + //jff 1/22/98 return if music is not enabled + if (nomusicparm) + return; + S_ChangeMusic(m_id, false); +} + +void S_ChangeMusic(int musicnum, int looping) +{ + //jff 1/22/98 return if music is not enabled + if (nomusicparm) + return; + + if (musicnum <= mus_None || musicnum >= NUMMUSIC) + I_Error("S_ChangeMusic: Bad music number %d", musicnum); + + if (_g->mus_playing == musicnum) + return; + + // shutdown old music + S_StopMusic(); + + // play it + I_PlaySong(musicnum, looping); + + _g->mus_playing = musicnum; +} + +void S_StopMusic(void) +{ + //jff 1/22/98 return if music is not enabled + if (nomusicparm) + return; + + if (_g->mus_playing) + { + if (_g->mus_paused) + I_ResumeSong(0); + + I_StopSong(0); + + _g->mus_playing = 0; + } +} + +void S_StopChannel(int cnum) +{ + int i; + channel_t *c = &_g->channels[cnum]; + + //jff 1/22/98 return if sound is not enabled + if (nosfxparm) + return; + + if (c->sfxinfo) + { + // check to see + // if other channels are playing the sound + for (i = 0; i < numChannels; i++) + if (cnum != i && c->sfxinfo == _g->channels[i].sfxinfo) + break; + + // degrade usefulness of sound data + c->sfxinfo = 0; + c->tickend = 0; + } + soundChannels[cnum].sfxIdx = 0; + soundChannels[cnum].volume = 0; +} + +// +// Changes volume, stereo-separation, and pitch variables +// from the norm of a sound effect to be played. +// If the sound is not audible, returns a 0. +// Otherwise, modifies parameters and returns 1. +// + +int S_AdjustSoundParams(mobj_t *listener, mobj_t *source, int *vol, int *sep) +{ + fixed_t adx, ady, approx_dist; + + //jff 1/22/98 return if sound is not enabled + if (nosfxparm) + return 0; + + // e6y + // Fix crash when the program wants to S_AdjustSoundParams() for player + // which is not displayplayer and displayplayer was not spawned at the moment. + // It happens in multiplayer demos only. + // + // Stack trace is: + // P_SetupLevel() - P_LoadThings() - P_SpawnMapThing() - P_SpawnPlayer(players[0]) - + // P_SetupPsprites() - P_BringUpWeapon() - S_StartSound(players[0]->mo, sfx_sawup) - + // S_StartSoundAtVolume() - S_AdjustSoundParams(players[displayplayer]->mo, ...); + // players[displayplayer]->mo is NULL + // + // There is no more crash on e1cmnet3.lmp between e1m2 and e1m3 + // http://competn.doom2.net/pub/compet-n/doom/coop/movies/e1cmnet3.zip + + if (!listener) + return 0; + + // calculate the distance to sound origin + // and clip it if necessary + adx = D_abs(listener->x - source->x); + ady = D_abs(listener->y - source->y); + + // From _GG1_ p.428. Appox. eucledian distance fast. + approx_dist = adx + ady - ((adx < ady ? adx : ady) >> 1); + + if (!approx_dist) // killough 11/98: handle zero-distance as special case + { + *vol = _g->snd_SfxVolume; + return *vol > 0; + } + + if (approx_dist > S_CLIPPING_DIST) + { + return 0; + } + + // angle of source to listener + angle_t angle = R_PointToAngle2(listener->x, listener->y, source->x, source->y); + + if (angle <= listener->angle) + angle += 0xffffffff; + + angle -= listener->angle; + angle >>= ANGLETOFINESHIFT; + + // stereo separation + *sep = 128 - (FixedMul(S_STEREO_SWING, finesine[angle]) >> FRACBITS); + + // volume calculation + if (approx_dist < S_CLOSE_DIST) + *vol = _g->snd_SfxVolume * 8; + else + // distance effect + *vol = (_g->snd_SfxVolume * ((S_CLIPPING_DIST - approx_dist) >> FRACBITS) * 8) / S_ATTENUATOR; + + return (*vol > 0); +} + +// +// S_getChannel : +// If none available, return -1. Otherwise channel #. +// +// killough 4/25/98: made static, added is_pickup argument + +static int S_getChannel(void *origin, const sfxinfo_t *sfxinfo, int is_pickup) +{ + // channel number to use + int cnum; + channel_t *c; + + //jff 1/22/98 return if sound is not enabled + if (nosfxparm) + return -1; + + // Find an open channel + for (cnum = 0; cnum < numChannels && _g->channels[cnum].sfxinfo; cnum++) + if (origin && _g->channels[cnum].origin == origin && _g->channels[cnum].is_pickup == is_pickup) + { + S_StopChannel(cnum); + break; + } + + // None available + if (cnum == numChannels) + { // Look for lower priority + for (cnum = 0; cnum < numChannels; cnum++) + if (_g->channels[cnum].sfxinfo->priority >= sfxinfo->priority) + break; + if (cnum == numChannels) + return -1; // No lower priority. Sorry, Charlie. + else + { + S_StopChannel(cnum); // Otherwise, kick out lower priority. + } + } + + c = &_g->channels[cnum]; // channel is decided to be cnum. + c->sfxinfo = sfxinfo; + c->origin = origin; + c->is_pickup = is_pickup; // killough 4/25/98 + return cnum; +} + diff --git a/doom/src/pdoom/Doom/source/sounds.c b/doom/src/pdoom/Doom/source/sounds.c new file mode 100644 index 0000000..d0a363f --- /dev/null +++ b/doom/src/pdoom/Doom/source/sounds.c @@ -0,0 +1,174 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Created by a sound utility. + * Kept as a sample, DOOM2 sounds. + * + * next-hack: added to each sound the DS. Actually, now that sound lumps + * are pre-cached, we might restore old num and add "DS" at runtime during + * pre-caching, but whatever. + * + *-----------------------------------------------------------------------------*/ + +// killough 5/3/98: reformatted +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "doomtype.h" +#include "sounds.h" + +// +// Information about all the sfx +// next-hack: upper cased and added DS + +const sfxinfo_t S_sfx[] = +{ + // S_sfx[0] needs to be a dummy for odd reasons. + { "NONE", false, 0, 0, -1, 0 }, + { "DSPISTOL", false, 64, 0, -1, 18 }, + { "DSSHOTGN", false, 64, 0, -1, 30 }, + { "DSSGCOCK", false, 64, 0, -1, 19 }, + { "DSDSHTGN", false, 64, 0, -1, 28 }, + { "DSDBOPN", false, 64, 0, -1, 6 }, + { "DSDBCLS", false, 64, 0, -1, 7 }, + { "DSDBLOAD", false, 64, 0, -1, 8 }, + { "DSPLASMA", false, 64, 0, -1, 18 }, + { "DSBFG", false, 64, 0, -1, 58 }, + { "DSSAWUP", false, 64, 0, -1, 52 }, + { "DSSAWIDL", false, 118, 0, -1, 24 }, + { "DSSAWFUL", false, 64, 0, -1, 58 }, + { "DSSAWHIT", false, 64, 0, -1, 26 }, + { "DSRLAUNC", false, 64, 0, -1, 49 }, + { "DSRXPLOD", false, 70, 0, -1, 46 }, + { "DSFIRSHT", false, 70, 0, -1, 47 }, + { "DSFIRXPL", false, 70, 0, -1, 38 }, + { "DSPSTART", false, 100, 0, -1, 26 }, + { "DSPSTOP", false, 100, 0, -1, 21 }, + { "DSDOROPN", false, 100, 0, -1, 44 }, + { "DSDORCLS", false, 100, 0, -1, 45 }, + { "DSSTNMOV", false, 119, 0, -1, 10 }, + { "DSSWTCHN", false, 78, 0, -1, 20 }, + { "DSSWTCHX", false, 78, 0, -1, 18 }, + { "DSPLPAIN", false, 96, 0, -1, 48 }, + { "DSDMPAIN", false, 96, 0, -1, 31 }, + { "DSPOPAIN", false, 96, 0, -1, 28 }, + { "DSVIPAIN", false, 96, 0, -1, 34 }, + { "DSMNPAIN", false, 96, 0, -1, 37 }, + { "DSPEPAIN", false, 96, 0, -1, 26 }, + { "DSSLOP", false, 78, 0, -1, 36 }, + { "DSITEMUP", true, 78, 0, -1, 7 }, + { "DSWPNUP", true, 78, 0, -1, 19 }, + { "DSOOF", false, 96, 0, -1, 13 }, + { "DSTELEPT", false, 32, 0, -1, 49 }, + { "DSPOSIT1", true, 98, 0, -1, 17 }, + { "DSPOSIT2", true, 98, 0, -1, 36 }, + { "DSPOSIT3", true, 98, 0, -1, 35 }, + { "DSBGSIT1", true, 98, 0, -1, 44 }, + { "DSBGSIT2", true, 98, 0, -1, 52 }, + { "DSSGTSIT", true, 98, 0, -1, 36 }, + { "DSCACSIT", true, 98, 0, -1, 55 }, + { "DSBRSSIT", true, 94, 0, -1, 44 }, + { "DSCYBSIT", true, 92, 0, -1, 42 }, + { "DSSPISIT", true, 90, 0, -1, 40 }, + { "DSBSPSIT", true, 90, 0, -1, 35 }, + { "DSKNTSIT", true, 90, 0, -1, 44 }, + { "DSVILSIT", true, 90, 0, -1, 57 }, + { "DSMANSIT", true, 90, 0, -1, 42 }, + { "DSPESIT", true, 90, 0, -1, 39 }, + { "DSSKLATK", false, 70, 0, -1, 28 }, + { "DSSGTATK", false, 70, 0, -1, 30 }, + { "DSSKEPCH", false, 70, 0, -1, 10 }, + { "DSVILATK", false, 70, 0, -1, 54 }, + { "DSCLAW", false, 70, 0, -1, 21 }, + { "DSSKESWG", false, 70, 0, -1, 8 }, + { "DSPLDETH", false, 32, 0, -1, 35 }, + { "DSPDIEHI", false, 32, 0, -1, 35 }, + { "DSPODTH1", false, 70, 0, -1, 41 }, + { "DSPODTH2", false, 70, 0, -1, 30 }, + { "DSPODTH3", false, 70, 0, -1, 35 }, + { "DSBGDTH1", false, 70, 0, -1, 23 }, + { "DSBGDTH2", false, 70, 0, -1, 30 }, + { "DSSGTDTH", false, 70, 0, -1, 39 }, + { "DSCACDTH", false, 70, 0, -1, 33 }, + { "DSSKLDTH", false, 70, 0, -1, 13 }, + { "DSBRSDTH", false, 32, 0, -1, 35 }, + { "DSCYBDTH", false, 32, 0, -1, 53 }, + { "DSSPIDTH", false, 32, 0, -1, 108 }, + { "DSBSPDTH", false, 32, 0, -1, 58 }, + { "DSVILDTH", false, 32, 0, -1, 40 }, + { "DSKNTDTH", false, 32, 0, -1, 23 }, + { "DSPEDTH", false, 32, 0, -1, 53 }, + { "DSSKEDTH", false, 32, 0, -1, 47 }, + { "DSPOSACT", true, 120, 0, -1, 34 }, + { "DSBGACT", true, 120, 0, -1, 32 }, + { "DSDMACT", true, 120, 0, -1, 38 }, + { "DSBSPACT", true, 100, 0, -1, 42 }, + { "DSBSPWLK", true, 100, 0, -1, 17 }, + { "DSVILACT", true, 100, 0, -1, 42 }, + { "DSNOWAY", false, 78, 0, -1, 13 }, + { "DSBAREXP", false, 60, 0, -1, 59 }, + { "DSPUNCH", false, 64, 0, -1, 8 }, + { "DSHOOF", false, 70, 0, -1, 13 }, + { "DSMETAL", false, 70, 0, -1, 26 }, + { "DSCHGUN", false, 64, &S_sfx[sfx_pistol], 150, 18 }, + { "DSTINK", false, 60, 0, -1, 1 }, + { "DSBDOPN", false, 100, 0, -1, 14 }, + { "DSBDCLS", false, 100, 0, -1, 14 }, + { "DSITMBK", false, 100, 0, -1, 18 }, + { "DSFLAME", false, 32, 0, -1, 36 }, + { "DSFLAMST", false, 32, 0, -1, 18 }, + { "DSGETPOW", false, 60, 0, -1, 26 }, + { "DSBOSPIT", false, 70, 0, -1, 139 }, + { "DSBOSCUB", false, 70, 0, -1, 39 }, + { "DSBOSSIT", false, 70, 0, -1, 181 }, + { "DSBOSPN", false, 70, 0, -1, 137 }, + { "DSBOSDTH", false, 70, 0, -1, 132 }, + { "DSMANATK", false, 70, 0, -1, 38 }, + { "DSMANDTH", false, 70, 0, -1, 69 }, + { "DSSSSIT", false, 70, 0, -1, 23 }, + { "DSSSDTH", false, 70, 0, -1, 26 }, + { "DSKEENPN", false, 70, 0, -1, 14 }, + { "DSKEENDT", false, 70, 0, -1, 28 }, + { "DSSKEACT", false, 70, 0, -1, 34 }, + { "DSSKESIT", false, 70, 0, -1, 38 }, + { "DSSKEATK", false, 70, 0, -1, 47 }, + { "DSRADIO", false, 60, 0, -1, 8 }, +}; diff --git a/doom/src/pdoom/Doom/source/st_gfx.c b/doom/src/pdoom/Doom/source/st_gfx.c new file mode 100644 index 0000000..7a1ea1e --- /dev/null +++ b/doom/src/pdoom/Doom/source/st_gfx.c @@ -0,0 +1,11 @@ +/* + * st_gfx.c + * This file used to hold the 240x32 status bar of the GBA version as image data. + * Since v0.3.1 (switch STBAR_LUMP) the ROM builder makes the bar from your own WAD + * (lump STBARGBA, see tools/gbaextras.py or Paramix Studio doom.js). So there is + * no graphics data here any more. + */ +#include "doomdef.h" +#ifndef STBAR_LUMP +#error "Without STBAR_LUMP there is no status bar: the image data is no longer in the source" +#endif diff --git a/doom/src/pdoom/Doom/source/st_lib.c b/doom/src/pdoom/Doom/source/st_lib.c new file mode 100644 index 0000000..214beb0 --- /dev/null +++ b/doom/src/pdoom/Doom/source/st_lib.c @@ -0,0 +1,322 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * The status bar widget code. + * + * next-hack: modified status bar update code and added support for digit stored + * in external flash. + * + *-----------------------------------------------------------------------------*/ + +#include "doomdef.h" +#include "doomstat.h" +#include "v_video.h" +#include "w_wad.h" +#include "st_stuff.h" +#include "st_lib.h" +#include "r_main.h" +#include "lprintf.h" +#include "global_data.h" + +#include "i_spi_support.h" + +extern const unsigned char gfx_stbar[240 * 32]; +#ifdef ST_SMALL +extern uint8_t st_buf[240 * 32]; +#endif +// +// STlib_init() +// +void STlib_init(void) +{ + // cph - no longer hold STMINUS pointer +} + +// +// STlib_initNum() +// +// Initializes an st_number_t widget +// +// Passed the widget, its position, the patches for the digits, a pointer +// to the value displayed, a pointer to the on/off control, and the width +// Returns nothing +// +void STlib_initNum(st_number_t *n, int x, int y, const patch_t **pl, short *num, boolean *on, int width) +{ + n->x = x; + n->y = y; + n->oldnum = 0; + n->width = width; + n->num = num; + n->on = on; + n->p = pl; +} + +/* + * STlib_drawNum() + * + * A fairly efficient way to draw a number based on differences from the + * old number. + * + * Passed a st_number_t widget, a color range for output, and a flag + * indicating whether refresh is needed. + * Returns nothing + * + * jff 2/16/98 add color translation to digit output + * cphipps 10/99 - const pointer to colour trans table, made function static + */ +static void STlib_drawNum(st_number_t *n, int cm, boolean refresh) +{ + + int numdigits = n->width; + int num = *n->num; + + int w; + if (isOnExternalFlash(&n->p[0]->width)) + { + spiFlashSetAddress((uint32_t) &n->p[0]->width); + w = spiFlashGetShort(); + } + else + w = n->p[0]->width; + int x = n->x; + + int neg; + + // CPhipps - compact some code, use num instead of *n->num + if ((neg = (n->oldnum = num) < 0)) + { + if (numdigits == 2 && num < -9) + num = -9; + else if (numdigits == 3 && num < -99) + num = -99; + + num = -num; + } + + // clear the area + x = n->x - numdigits * w; + + // if non-number, do not draw it + if (num == 1994) + return; + + x = n->x; + + //jff 2/16/98 add color translation to digit output + // in the special case of 0, you draw 0 + if (!num) + // CPhipps - patch drawing updated, reformatted + V_DrawPatchNoScale(x - w, n->y, n->p[0]); + + // draw the new number + //jff 2/16/98 add color translation to digit output + while (num && numdigits--) + { + // CPhipps - patch drawing updated, reformatted + x -= w; + V_DrawPatchNoScale(x, n->y, n->p[num % 10]); + num /= 10; + } +} + +/* + * STlib_updateNum() + * + * Draws a number conditionally based on the widget's enable + * + * Passed a number widget, the output color range, and a refresh flag + * Returns nothing + * + * jff 2/16/98 add color translation to digit output + * cphipps 10/99 - make that pointer const + */ +void STlib_updateNum(st_number_t *n, int cm, boolean refresh) +{ + if (*n->on) + STlib_drawNum(n, cm, refresh); +} + +// +// STlib_initPercent() +// +// Initialize a st_percent_t number with percent sign widget +// +// Passed a st_percent_t widget, the position, the digit patches, a pointer +// to the number to display, a pointer to the enable flag, and patch +// for the percent sign. +// Returns nothing. +// +void STlib_initPercent(st_percent_t *p, int x, int y, const patch_t **pl, short *num, boolean *on, const patch_t *percent) +{ + STlib_initNum(&p->n, x, y, pl, num, on, 3); + p->p = percent; +} + +/* + * STlib_updatePercent() + * + * Draws a number/percent conditionally based on the widget's enable + * + * Passed a precent widget, the output color range, and a refresh flag + * Returns nothing + * + * jff 2/16/98 add color translation to digit output + * cphipps - const for pointer to the colour translation table + */ + +void STlib_updatePercent(st_percent_t *per, int cm, int refresh) +{ + STlib_updateNum(&per->n, cm, refresh); + //V_DrawPatchNoScale(per->n.x, per->n.y, per->p); - Percentage is in the GBA Doom II Hud graphic ~Kippykip +} + +// +// STlib_initMultIcon() +// +// Initialize a st_multicon_t widget, used for a multigraphic display +// like the status bar's keys. +// +// Passed a st_multicon_t widget, the position, the graphic patches, a pointer +// to the numbers representing what to display, and pointer to the enable flag +// Returns nothing. +// +void STlib_initMultIcon(st_multicon_t *i, int x, int y, const patch_t **il, short *inum, boolean *on) +{ + i->x = x; + i->y = y; + i->oldinum = -1; + i->inum = inum; + i->on = on; + i->p = il; +} + +// +// STlib_updateMultIcon() +// +// Draw a st_multicon_t widget, used for a multigraphic display +// like the status bar's keys. Displays each when the control +// numbers change or refresh is true +// +// Passed a st_multicon_t widget, and a refresh flag +// Returns nothing. +// +void STlib_updateMultIcon(st_multicon_t *mi, boolean refresh) +{ + if (!mi->p) + return; + + if (*mi->inum != -1) // killough 2/16/98: redraw only if != -1 + V_DrawPatchNoScale(mi->x, mi->y, mi->p[*mi->inum]); + + mi->oldinum = *mi->inum; + +} + +// +// STlib_initBinIcon() +// +// Initialize a st_binicon_t widget, used for a multinumber display +// like the status bar's weapons, that are present or not. +// +// Passed a st_binicon_t widget, the position, the digit patches, a pointer +// to the flags representing what is displayed, and pointer to the enable flag +// Returns nothing. +// +void STlib_initBinIcon(st_binicon_t *b, int x, int y, const patch_t *i, boolean *val, boolean *on) +{ + b->x = x; + b->y = y; + b->oldval = 0; + b->val = val; + b->on = on; + b->p = i; +} + +// +// STlib_updateBinIcon() +// +// DInitialize a st_binicon_t widget, used for a multinumber display +// like the status bar's weapons, that are present or not. +// +// Draw a st_binicon_t widget, used for a multinumber display +// like the status bar's weapons that are present or not. Displays each +// when the control flag changes or refresh is true +// +// Passed a st_binicon_t widget, and a refresh flag +// Returns nothing. +// +void STlib_updateBinIcon(st_binicon_t *bi, boolean refresh) +{ + if (*bi->on && (bi->oldval != *bi->val || refresh)) + { + if (*bi->val) + V_DrawPatch(bi->x, bi->y, ST_FG, bi->p); + + bi->oldval = *bi->val; + } +} + +void ST_refreshBackground(void) +{ + if (_g->st_statusbaron) + { + +#ifdef ST_SMALL + uint32_t *d = (uint32_t*) st_buf; +#else + const unsigned int st_offset = ((SCREENHEIGHT - ST_SCALED_HEIGHT) * SCREENWIDTH_PHYSICAL); + uint32_t *d = (uint32_t*) (((uint8_t*) _g->screens[0].data) + st_offset); +#endif +#ifdef STBAR_LUMP + static const uint32_t *stbar_lump; + if (!stbar_lump) stbar_lump = (const uint32_t*) W_CacheLumpName("STBARGBA"); + const uint32_t *s = stbar_lump; + for (int i = 0; i < 240 * 32 / sizeof(uint32_t); i++) +#else + uint32_t *s = (uint32_t*) gfx_stbar; + for (int i = 0; i < sizeof(gfx_stbar) / sizeof(uint32_t); i++) +#endif + { + + *d++ = *s++; + } + } +} diff --git a/doom/src/pdoom/Doom/source/st_stuff.c b/doom/src/pdoom/Doom/source/st_stuff.c new file mode 100644 index 0000000..a71a80b --- /dev/null +++ b/doom/src/pdoom/Doom/source/st_stuff.c @@ -0,0 +1,745 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Status bar code. + * Does the face/direction indicator animation. + * Does palette indicators as well (red pain/berserk, bright pickup) + * + * next-hack: + * pointers to patches now stored in immutable flash region, saving a few + * hundred bytes of RAM. + * modified so that instead of re-rendering, if no + * changes are required, and the status bar is already rendered in + * the previous frame buffer (but not on the current one), then the + * previous frame is copied to the current frame buffer. + * + *-----------------------------------------------------------------------------*/ + +#include "doomdef.h" +#include "doomstat.h" +#include "m_random.h" +#include "i_video.h" +#include "w_wad.h" +#include "st_stuff.h" +#include "st_lib.h" +#include "r_main.h" +#include "am_map.h" +#include "s_sound.h" +#include "sounds.h" +#include "dstrings.h" +#include "r_draw.h" + +#include "global_data.h" + +#include "st_gfx.h" +#include "graphics.h" + +// +// STATUS BAR CODE +// + +static void ST_Stop(void); + +// Respond to keyboard input events, +// intercept cheats. +boolean ST_Responder(const event_t *ev) +{ + // Filter automap on/off. + if (ev->type == ev_keyup && (ev->data1 & 0xffff0000) == AM_MSGHEADER) + { + switch (ev->data1) + { + case AM_MSGENTERED: + break; + + case AM_MSGEXITED: + break; + } + } + + return false; +} + +static int ST_calcPainOffset(void) +{ + static int lastcalc; + static int oldhealth = -1; + int health = _g->plyr->health > 100 ? 100 : _g->plyr->health; + + if (health != oldhealth) + { + lastcalc = ST_FACESTRIDE * (((100 - health) * ST_NUMPAINFACES) / 101); + oldhealth = health; + } + return lastcalc; +} + +// +// This is a not-very-pretty routine which handles +// the face states and their timing. +// the precedence of expressions is: +// dead > evil grin > turned head > straight ahead +// + +static void ST_updateFaceWidget(void) +{ + int i; + angle_t badguyangle; + angle_t diffang; + static int lastattackdown = -1; + static int priority = 0; + boolean doevilgrin; + + if (priority < 10) + { + // dead + if (!_g->plyr->health) + { + priority = 9; + _g->st_faceindex = ST_DEADFACE; + _g->st_facecount = 1; + } + } + + if (priority < 9) + { + if (_g->plyr->bonuscount) + { + // picking up bonus + doevilgrin = false; + + for (i = 0; i < NUMWEAPONS; i++) + { + if (_g->oldweaponsowned[i] != _g->plyr->weaponowned[i]) + { + doevilgrin = true; + _g->oldweaponsowned[i] = _g->plyr->weaponowned[i]; + } + } + if (doevilgrin) + { + // evil grin if just picked up weapon + priority = 8; + _g->st_facecount = ST_EVILGRINCOUNT; + _g->st_faceindex = ST_calcPainOffset() + ST_EVILGRINOFFSET; + } + } + + } + + //Restore the face looking at enemies direction in this SVN... Cause it's handy! ~Kippykip + if (priority < 8) + { + if (_g->plyr->damagecount && _g->plyr->attacker && _g->plyr->attacker != _g->plyr->mo) + { + // being attacked + priority = 7; + + // haleyjd 10/12/03: classic DOOM problem of missing OUCH face + // was due to inversion of this test: + // if(plyr->health - st_oldhealth > ST_MUCHPAIN) + if (_g->st_oldhealth - _g->plyr->health > ST_MUCHPAIN) + { + _g->st_facecount = ST_TURNCOUNT; + _g->st_faceindex = ST_calcPainOffset() + ST_OUCHOFFSET; + } + else + { + badguyangle = R_PointToAngle2(_g->plyr->mo->x, _g->plyr->mo->y, _g->plyr->attacker->x, _g->plyr->attacker->y); + + if (badguyangle > _g->plyr->mo->angle) + { + // whether right or left + diffang = badguyangle - _g->plyr->mo->angle; + i = diffang > ANG180; + } + else + { + // whether left or right + diffang = _g->plyr->mo->angle - badguyangle; + i = diffang <= ANG180; + } // confusing, aint it? + + _g->st_facecount = ST_TURNCOUNT; + _g->st_faceindex = ST_calcPainOffset(); + + if (diffang < ANG45) + { + // head-on + _g->st_faceindex += ST_RAMPAGEOFFSET; + } + else if (i) + { + // turn face right + _g->st_faceindex += ST_TURNOFFSET; + } + else + { + // turn face left + _g->st_faceindex += ST_TURNOFFSET + 1; + } + } + } + } + + if (priority < 7) + { + if (_g->plyr->damagecount) + { + // haleyjd 10/12/03: classic DOOM problem of missing OUCH face + // was due to inversion of this test: + // if(plyr->health - st_oldhealth > ST_MUCHPAIN) + if (_g->st_oldhealth - _g->plyr->health > ST_MUCHPAIN) + { + priority = 7; + _g->st_facecount = ST_TURNCOUNT; + _g->st_faceindex = ST_calcPainOffset() + ST_OUCHOFFSET; + } + else + { + priority = 6; + _g->st_facecount = ST_TURNCOUNT; + _g->st_faceindex = ST_calcPainOffset() + ST_RAMPAGEOFFSET; + } + + } + } + + if (priority < 6) + { + // rapid firing + if (_g->plyr->attackdown) + { + if (lastattackdown == -1) + lastattackdown = ST_RAMPAGEDELAY; + else if (!--lastattackdown) + { + priority = 5; + _g->st_faceindex = ST_calcPainOffset() + ST_RAMPAGEOFFSET; + _g->st_facecount = 1; + lastattackdown = 1; + } + } + else + lastattackdown = -1; + + } + + if (priority < 5) + { + // invulnerability + if ((_g->plyr->cheats & CF_GODMODE) || _g->plyr->powers[pw_invulnerability]) + { + priority = 4; + + _g->st_faceindex = ST_GODFACE; + _g->st_facecount = 1; + + } + + } + + // look left or look right if the facecount has timed out + if (!_g->st_facecount) + { + _g->st_faceindex = ST_calcPainOffset() + (_g->st_randomnumber % 3); + _g->st_facecount = ST_STRAIGHTFACECOUNT; + priority = 0; + } + + _g->st_facecount--; + +} + +static void ST_updateWidgets(void) +{ + const static int largeammo = 1994; // means "n/a" + int i; + + if (_g->fps_show) + _g->w_ready.num = (short*) &_g->fps_framerate; + else if (weaponinfo[_g->plyr->readyweapon].ammo == am_noammo) + _g->w_ready.num = (short*) &largeammo; + else + _g->w_ready.num = &_g->plyr->ammo[weaponinfo[_g->plyr->readyweapon].ammo]; + + // update keycard multiple widgets + for (i = 0; i < 3; i++) + { + _g->keyboxes[i] = _g->plyr->cards[i] ? i : -1; + + //jff 2/24/98 select double key + //killough 2/28/98: preserve traditional keys by config option + + if (_g->plyr->cards[i + 3]) + _g->keyboxes[i] = i + 3; + } + + // refresh everything if this is him coming back to life + ST_updateFaceWidget(); +} + +void ST_Ticker(void) +{ + _g->st_randomnumber = M_Random(); + ST_updateWidgets(); + _g->st_oldhealth = _g->plyr->health; +} + +static void ST_doPaletteStuff(void) +{ + int palette; + int cnt = _g->plyr->damagecount; + + if (_g->plyr->powers[pw_strength]) + { + // slowly fade the berzerk out + int bzc = 12 - (_g->plyr->powers[pw_strength] >> 6); + if (bzc > cnt) + cnt = bzc; + } + + if (cnt) + { + palette = (cnt + 7) >> 3; + if (palette >= NUMREDPALS) + palette = NUMREDPALS - 1; + + /* cph 2006/08/06 - if in the menu, reduce the red tint - navigating to + * load a game can be tricky if the screen is all red */ + if (_g->menuactive) + palette >>= 1; + + palette += STARTREDPALS; + } + else if (_g->plyr->bonuscount) + { + palette = (_g->plyr->bonuscount + 7) >> 3; + if (palette >= NUMBONUSPALS) + palette = NUMBONUSPALS - 1; + palette += STARTBONUSPALS; + } + else if (_g->plyr->powers[pw_ironfeet] > 4 * 32 || (_g->plyr->powers[pw_ironfeet] & 8)) + palette = RADIATIONPAL; + else + palette = 0; + + if (palette != _g->st_palette) + { + V_SetPalette(_g->st_palette = palette); // CPhipps - use new palette function + } +} + +static void ST_drawWidgets(boolean refresh) +{ + + // Restore the ammo numbers for backpack stats I guess, etc ~Kippykip + for (int i = 0; i < 4; i++) + { + STlib_updateNum(&_g->w_ammo[i], CR_DEFAULT, refresh); + STlib_updateNum(&_g->w_maxammo[i], CR_DEFAULT, refresh); + } + STlib_updateNum(&_g->w_ready, CR_RED, refresh); + + STlib_updatePercent(&_g->st_health, CR_RED, refresh); + + STlib_updatePercent(&_g->st_armor, CR_RED, refresh); + + STlib_updateMultIcon(&_g->w_faces, refresh); + + for (int i = 0; i < 3; i++) + STlib_updateMultIcon(&_g->w_keyboxes[i], refresh); + + for (int i = 0; i < 6; i++) + STlib_updateMultIcon(&_g->w_arms[i], refresh); + +} + +static void ST_doRefresh(void) +{ + // draw status bar background to off-screen buff + ST_refreshBackground(); + + // and refresh all widgets + ST_drawWidgets(true); + +} + +static boolean ST_NeedUpdate() +{ + // ready weapon ammo + if (_g->w_ready.oldnum != *_g->w_ready.num) + return true; + + if (_g->st_health.n.oldnum != *_g->st_health.n.num) + return true; + + if (_g->st_armor.n.oldnum != *_g->st_armor.n.num) + return true; + + if (_g->w_faces.oldinum != *_g->w_faces.inum) + return true; + + // ammo + for (int i = 0; i < 4; i++) + { + if (_g->w_ammo[i].oldnum != *_g->w_ammo[i].num) + return true; + if (_g->w_maxammo[i].oldnum != *_g->w_maxammo[i].num) + return true; + } + + // weapons owned + for (int i = 0; i < 6; i++) + { + if (_g->w_arms[i].oldinum != *_g->w_arms[i].inum) + return true; + } + + for (int i = 0; i < 3; i++) + { + if (_g->w_keyboxes[i].oldinum != *_g->w_keyboxes[i].inum) + return true; + } + + return false; +} + +#ifdef ST_SMALL +/* Paradise: the bar is drawn at 240x32 (like the original) into st_buf and copied scaled down to the screen */ +#ifdef PARADISE_DEV +__attribute__((section(".ram20_bss"), aligned(4))) +#endif +uint8_t st_buf[240 * 32] __attribute__((aligned(4))); +int v_pitch = SCREENWIDTH; +static void ST_scaleToScreen(void) +{ + uint8_t *d = (uint8_t*) _g->screens[0].data + ST_SCALED_Y * SCREENPITCH; + for (int y = 0; y < ST_SCALED_HEIGHT; y++) + { + const uint8_t *s = st_buf + ((y * 32 + 16) / ST_SCALED_HEIGHT) * 240; + for (int x = 0; x < SCREENWIDTH; x++) + d[x] = s[(x * 240 + 120) / SCREENWIDTH]; + d += SCREENPITCH; + } +} +void ST_Drawer(boolean statusbaron, boolean refresh) +{ + ST_doPaletteStuff(); + if (!statusbaron) + return; + if (refresh || ST_NeedUpdate() || _g->st_needrefresh) + { + byte *old = _g->screens[0].data; + short sy0 = draw_starty, sy1 = draw_stopy; + _g->screens[0].data = st_buf - ST_Y * 240; + v_pitch = 240; draw_starty = ST_Y; draw_stopy = ST_Y + 31; + ST_doRefresh(); + _g->screens[0].data = old; v_pitch = SCREENWIDTH; draw_starty = sy0; draw_stopy = sy1; + _g->st_needrefresh = 0; + } + ST_scaleToScreen(); +} +#else +int v_pitch = SCREENWIDTH; +void ST_Drawer(boolean statusbaron, boolean refresh) +{ + /* cph - let status bar on be controlled + * completely by the call from D_Display + * proff - really do it + */ + + ST_doPaletteStuff(); // Do red-/gold-shifts from damage/items + + if (statusbaron) + { +// boolean needupdate = false; + + if (refresh) + { +// needupdate = true; + _g->st_needrefresh = 2; + } + else if (ST_NeedUpdate()) + { +// needupdate = true; + _g->st_needrefresh = 2; + } + /* else if (_g->st_needrefresh) + { + needupdate = true; + }*/ + + ///if (needupdate) + //{ + if (_g->st_needrefresh == 2) +// if (_g->st_needrefresh) + { + ST_doRefresh(); + _g->st_needrefresh = 1; + } + else if (_g->st_needrefresh == 1) + { + // copy from old frame buffer. + uint32_t *d = (uint32_t*) ((uint8_t*) displayData.displayFrameBuffer[displayData.workingBuffer] + ST_SCALED_Y * SCREENPITCH); + uint32_t *s = (uint32_t*) ((uint8_t*) displayData.displayFrameBuffer[1 - displayData.workingBuffer] + ST_SCALED_Y * SCREENPITCH); +#if 0 + for (int i = 0; i < ST_SCALED_HEIGHT * SCREENPITCH / 4; i++) + *d++ = *s++; +#else + // memcpy is faster + memcpy(d, s, ST_SCALED_HEIGHT * SCREENPITCH); +#endif + _g->st_needrefresh = 0; + } + } +} +#endif + +// +// ST_loadGraphics +// +// CPhipps - Loads graphics needed for status bar if doload is true, +// unloads them otherwise +// +static void ST_loadGraphics(boolean doload) +{ + int i, facenum; + char namebuf[9]; + + // Load the numbers, tall and short + for (i = 0; i < 10; i++) + { + //sprintf(namebuf, "STTNUM%d", i); + snprintf(namebuf, sizeof(namebuf), "STGANUM%c", i + '0'); //Special GBA Doom II Red Numbers ~Kippykip + p_wad_immutable_flash_data->tallnum[i] = (const patch_t*) W_CacheLumpName(namebuf); + + snprintf(namebuf, sizeof(namebuf), "STYSNUM%c", i + '0'); + p_wad_immutable_flash_data->shortnum[i] = (const patch_t*) W_CacheLumpName(namebuf); + } + + // Load percent key. + //Note: why not load STMINUS here, too? + p_wad_immutable_flash_data->tallpercent = (const patch_t*) W_CacheLumpName("STTPRCNT"); + + // key cards + for (i = 0; i < NUMCARDS; i++) + { + snprintf(namebuf, sizeof(namebuf), "STKEYS%d", i); + p_wad_immutable_flash_data->keys[i] = (const patch_t*) W_CacheLumpName(namebuf); + } + + // arms ownership widgets + for (i = 0; i < 6; i++) + { + snprintf(namebuf, sizeof(namebuf), "STGNUM%d", i + 2); + + // gray # + p_wad_immutable_flash_data->arms[i][0] = (const patch_t*) W_CacheLumpName(namebuf); + + // yellow # + p_wad_immutable_flash_data->arms[i][1] = (const patch_t*) p_wad_immutable_flash_data->shortnum[i + 2]; + + } + + // face states + facenum = 0; + + for (i = 0; i < ST_NUMPAINFACES; i++) + { + for (int j = 0; j < ST_NUMSTRAIGHTFACES; j++) + { + sprintf(namebuf, "STFST%d%d", i, j); + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName(namebuf); + } + snprintf(namebuf, sizeof(namebuf), "STFTR%d0", i); // turn right + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName(namebuf); + snprintf(namebuf, sizeof(namebuf), "STFTL%d0", i); // turn left + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName(namebuf); + snprintf(namebuf, sizeof(namebuf), "STFOUCH%d", i); // ouch! + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName(namebuf); + snprintf(namebuf, sizeof(namebuf), "STFEVL%d", i); // evil grin ;) + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName(namebuf); + snprintf(namebuf, sizeof(namebuf), "STFKILL%d", i); // pissed off + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName(namebuf); + } + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName("STFGOD0"); + p_wad_immutable_flash_data->faces[facenum++] = W_CacheLumpName("STFDEAD0"); +} + +static void ST_loadData(void) +{ + ST_loadGraphics(true); +} + +static void ST_initData(void) +{ + int i; + + _g->plyr = &_g->player; // killough 3/7/98 + + _g->st_statusbaron = true; + + _g->st_faceindex = 0; + _g->st_palette = -1; + + _g->st_oldhealth = -1; + + for (i = 0; i < NUMWEAPONS; i++) + _g->oldweaponsowned[i] = _g->plyr->weaponowned[i]; + + for (i = 0; i < 3; i++) + _g->keyboxes[i] = -1; + + STlib_init(); +} + +static void ST_createWidgets(void) +{ + int i; + + // ready weapon ammo + STlib_initNum(&_g->w_ready, + ST_AMMOX, + ST_AMMOY, p_wad_immutable_flash_data->tallnum, &_g->plyr->ammo[weaponinfo[_g->plyr->readyweapon].ammo], &_g->st_statusbaron, + ST_AMMOWIDTH); + + // health percentage + STlib_initPercent(&_g->st_health, + ST_HEALTHX, + ST_HEALTHY, p_wad_immutable_flash_data->tallnum, &_g->plyr->health, &_g->st_statusbaron, p_wad_immutable_flash_data->tallpercent); + + // armor percentage - should be colored later + STlib_initPercent(&_g->st_armor, + ST_ARMORX, + ST_ARMORY, p_wad_immutable_flash_data->tallnum, &_g->plyr->armorpoints, &_g->st_statusbaron, p_wad_immutable_flash_data->tallpercent); + + // weapons owned + for (i = 0; i < 6; i++) + { + STlib_initMultIcon(&_g->w_arms[i], + ST_ARMSX + (i % 3) * ST_ARMSXSPACE, + ST_ARMSY + (i / 3) * ST_ARMSYSPACE, p_wad_immutable_flash_data->arms[i], &_g->plyr->weaponowned[i + 1], &_g->st_statusbaron); + } + + // keyboxes 0-2 + STlib_initMultIcon(&_g->w_keyboxes[0], + ST_KEY0X, + ST_KEY0Y, p_wad_immutable_flash_data->keys, &_g->keyboxes[0], &_g->st_statusbaron); + + STlib_initMultIcon(&_g->w_keyboxes[1], + ST_KEY1X, + ST_KEY1Y, p_wad_immutable_flash_data->keys, &_g->keyboxes[1], &_g->st_statusbaron); + + STlib_initMultIcon(&_g->w_keyboxes[2], + ST_KEY2X, + ST_KEY2Y, p_wad_immutable_flash_data->keys, &_g->keyboxes[2], &_g->st_statusbaron); + + // ammo count (all four kinds) + STlib_initNum(&_g->w_ammo[0], + ST_AMMO0X, + ST_AMMO0Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->ammo[0], &_g->st_statusbaron, + ST_AMMO0WIDTH); + + STlib_initNum(&_g->w_ammo[1], + ST_AMMO1X, + ST_AMMO1Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->ammo[1], &_g->st_statusbaron, + ST_AMMO1WIDTH); + + STlib_initNum(&_g->w_ammo[2], + ST_AMMO2X, + ST_AMMO2Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->ammo[2], &_g->st_statusbaron, + ST_AMMO2WIDTH); + + STlib_initNum(&_g->w_ammo[3], + ST_AMMO3X, + ST_AMMO3Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->ammo[3], &_g->st_statusbaron, + ST_AMMO3WIDTH); + + // max ammo count (all four kinds) + STlib_initNum(&_g->w_maxammo[0], + ST_MAXAMMO0X, + ST_MAXAMMO0Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->maxammo[0], &_g->st_statusbaron, + ST_MAXAMMO0WIDTH); + + STlib_initNum(&_g->w_maxammo[1], + ST_MAXAMMO1X, + ST_MAXAMMO1Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->maxammo[1], &_g->st_statusbaron, + ST_MAXAMMO1WIDTH); + + STlib_initNum(&_g->w_maxammo[2], + ST_MAXAMMO2X, + ST_MAXAMMO2Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->maxammo[2], &_g->st_statusbaron, + ST_MAXAMMO2WIDTH); + + STlib_initNum(&_g->w_maxammo[3], + ST_MAXAMMO3X, + ST_MAXAMMO3Y, p_wad_immutable_flash_data->shortnum, &_g->plyr->maxammo[3], &_g->st_statusbaron, + ST_MAXAMMO3WIDTH); + + // faces + STlib_initMultIcon(&_g->w_faces, + ST_FACESX, + ST_FACESY, p_wad_immutable_flash_data->faces, &_g->st_faceindex, &_g->st_statusbaron); +} + +static boolean st_stopped = true; + +void ST_Start(void) +{ + if (!st_stopped) + ST_Stop(); + ST_initData(); + ST_createWidgets(); + st_stopped = false; +} + +static void ST_Stop(void) +{ + if (st_stopped) + return; + V_SetPalette(0); + st_stopped = true; +} + +void ST_Init(void) +{ + ST_loadData(); +} diff --git a/doom/src/pdoom/Doom/source/tables.c b/doom/src/pdoom/Doom/source/tables.c new file mode 100644 index 0000000..d3577e0 --- /dev/null +++ b/doom/src/pdoom/Doom/source/tables.c @@ -0,0 +1,628 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Lookup tables. + * Do not try to look them up :-). + * In the order of appearance: + * + * int finetangent[4096] - Tangens LUT. + * Should work with BAM fairly well (12 of 16bit, + * effectively, by shifting). + * + * int finesine[10240] - Sine lookup. + * Guess what, serves as cosine, too. + * Remarkable thing is, how to use BAMs with this? + * + * int tantoangle[2049] - ArcTan LUT, + * maps tan(angle) to angle fast. Gotta search. + * + * next-hack: + * - adjusted tables to work with 160x128 screens (old code, left for + * hystoric reasons... + * - added constant tables to bring back Z-Depth Light (removed in GBA port) + * - adjusted tables for 240x240 screens. + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "w_wad.h" +#include "tables.h" + +const fixed_t finetangent[4096] = +{ -170910304, -56965752, -34178904, -24413316, -18988036, -15535599, -13145455, -11392683, -10052327, -8994149, -8137527, -7429880, -6835455, -6329090, -5892567, -5512368, -5178251, -4882318, -4618375, -4381502, -4167737, -3973855, -3797206, -3635590, -3487165, -3350381, -3223918, -3106651, -2997613, -2895966, -2800983, -2712030, -2628549, -2550052, -2476104, -2406322, -2340362, -2277919, -2218719, -2162516, -2109087, -2058233, -2009771, -1963536, -1919378, -1877161, -1836758, -1798063, -1760956, -1725348, -1691149, -1658278, -1626658, -1596220, -1566898, -1538632, -1511367, -1485049, -1459630, -1435065, -1411312, -1388330, -1366084, -1344537, -1323658, -1303416, -1283783, -1264730, -1246234, -1228269, -1210813, -1193846, -1177345, -1161294, -1145673, -1130465, -1115654, -1101225, -1087164, -1073455, -1060087, -1047046, -1034322, -1021901, -1009774, -997931, -986361, -975054, -964003, -953199, -942633, -932298, -922186, -912289, -902602, -893117, -883829, -874730, -865817, -857081, -848520, -840127, -831898, -823827, -815910, -808143, -800521, -793041, -785699, -778490, -771411, -764460, -757631, -750922, -744331, -737853, -731486, -725227, -719074, -713023, -707072, -701219, -695462, -689797, -684223, -678737, -673338, -668024, -662792, -657640, -652568, -647572, -642651, -637803, -633028, -628323, -623686, -619117, -614613, -610174, -605798, -601483, -597229, -593033, -588896, -584815, -580789, -576818, -572901, -569035, -565221, -561456, -557741, -554074, -550455, -546881, -543354, -539870, -536431, -533034, -529680, -526366, -523094, -519861, -516667, -513512, -510394, -507313, -504269, -501261, -498287, -495348, -492443, -489571, -486732, -483925, -481150, -478406, -475692, -473009, -470355, -467730, -465133, -462565, -460024, -457511, -455024, -452564, -450129, -447720, -445337, -442978, -440643, -438332, -436045, -433781, -431540, -429321, -427125, -424951, -422798, -420666, -418555, -416465, -414395, -412344, -410314, -408303, -406311, -404338, -402384, -400448, -398530, -396630, -394747, -392882, -391034, -389202, -387387, -385589, -383807, -382040, -380290, -378555, -376835, -375130, -373440, -371765, -370105, -368459, -366826, -365208, -363604, -362013, -360436, -358872, -357321, -355783, -354257, -352744, -351244, -349756, -348280, -346816, -345364, -343924, -342495, -341078, -339671, -338276, -336892, -335519, -334157, -332805, -331464, -330133, -328812, -327502, -326201, -324910, -323629, -322358, -321097, -319844, -318601, -317368, -316143, -314928, -313721, -312524, -311335, -310154, -308983, -307819, -306664, -305517, -304379, -303248, -302126, -301011, -299904, -298805, -297714, -296630, -295554, -294485, -293423, -292369, -291322, -290282, -289249, -288223, -287204, -286192, -285186, -284188, -283195, -282210, -281231, -280258, -279292, -278332, -277378, -276430, -275489, -274553, -273624, -272700, -271782, -270871, -269965, -269064, -268169, -267280, -266397, -265519, -264646, -263779, -262917, -262060, -261209, -260363, -259522, -258686, -257855, -257029, -256208, -255392, -254581, -253774, -252973, -252176, -251384, -250596, -249813, -249035, -248261, -247492, -246727, -245966, -245210, -244458, -243711, -242967, -242228, -241493, -240763, -240036, -239314, -238595, -237881, -237170, -236463, -235761, -235062, -234367, -233676, -232988, -232304, -231624, -230948, -230275, -229606, -228941, -228279, -227621, -226966, -226314, -225666, -225022, -224381, -223743, -223108, -222477, -221849, -221225, -220603, -219985, -219370, -218758, -218149, -217544, -216941, -216341, -215745, -215151, -214561, -213973, -213389, -212807, -212228, -211652, -211079, -210509, -209941, -209376, -208815, -208255, -207699, -207145, -206594, -206045, -205500, -204956, -204416, -203878, -203342, -202809, -202279, -201751, -201226, -200703, -200182, -199664, -199149, -198636, -198125, -197616, -197110, -196606, -196105, -195606, -195109, -194614, -194122, -193631, -193143, -192658, -192174, -191693, -191213, -190736, -190261, -189789, -189318, -188849, -188382, -187918, -187455, -186995, -186536, -186080, -185625, -185173, -184722, -184274, -183827, -183382, -182939, -182498, -182059, -181622, -181186, -180753, -180321, -179891, -179463, -179037, -178612, -178190, -177769, -177349, -176932, -176516, -176102, -175690, -175279, -174870, -174463, -174057, -173653, -173251, -172850, -172451, -172053, -171657, -171263, -170870, -170479, -170089, -169701, -169315, -168930, -168546, -168164, -167784, -167405, -167027, -166651, -166277, -165904, -165532, -165162, -164793, -164426, -164060, -163695, -163332, -162970, -162610, -162251, -161893, -161537, -161182, -160828, -160476, -160125, -159775, -159427, -159079, -158734, -158389, -158046, -157704, -157363, -157024, -156686, -156349, -156013, -155678, -155345, -155013, -154682, -154352, -154024, -153697, -153370, -153045, -152722, -152399, -152077, -151757, -151438, -151120, -150803, -150487, -150172, -149859, -149546, -149235, -148924, -148615, -148307, -148000, -147693, -147388, -147084, -146782, -146480, -146179, -145879, -145580, -145282, -144986, -144690, -144395, -144101, -143808, -143517, -143226, -142936, -142647, -142359, -142072, -141786, -141501, -141217, -140934, -140651, -140370, -140090, -139810, -139532, -139254, -138977, -138701, -138426, -138152, -137879, -137607, -137335, -137065, -136795, -136526, -136258, -135991, -135725, -135459, -135195, -134931, -134668, -134406, -134145, -133884, -133625, -133366, -133108, -132851, -132594, -132339, -132084, -131830, -131576, -131324, -131072, -130821, -130571, -130322, -130073, -129825, -129578, -129332, -129086, -128841, -128597, -128353, -128111, -127869, -127627, -127387, -127147, -126908, -126669, -126432, -126195, -125959, -125723, -125488, -125254, -125020, -124787, -124555, -124324, -124093, -123863, -123633, -123404, -123176, -122949, -122722, -122496, -122270, -122045, -121821, -121597, -121374, -121152, -120930, -120709, -120489, -120269, -120050, -119831, -119613, -119396, -119179, -118963, -118747, -118532, -118318, -118104, -117891, -117678, -117466, -117254, -117044, -116833, -116623, -116414, -116206, -115998, -115790, -115583, -115377, -115171, -114966, -114761, -114557, -114354, -114151, -113948, -113746, -113545, -113344, -113143, -112944, -112744, -112546, -112347, -112150, -111952, -111756, -111560, -111364, -111169, -110974, -110780, -110586, -110393, -110200, -110008, -109817, -109626, -109435, -109245, -109055, -108866, -108677, -108489, -108301, -108114, -107927, -107741, -107555, -107369, -107184, -107000, -106816, -106632, -106449, -106266, -106084, -105902, -105721, -105540, -105360, -105180, -105000, -104821, -104643, -104465, -104287, -104109, -103933, -103756, -103580, -103404, -103229, -103054, -102880, -102706, -102533, -102360, -102187, -102015, -101843, -101671, -101500, -101330, -101159, -100990, -100820, -100651, -100482, -100314, -100146, -99979, -99812, -99645, -99479, -99313, -99148, -98982, -98818, -98653, -98489, -98326, -98163, -98000, -97837, -97675, -97513, -97352, -97191, -97030, -96870, -96710, -96551, -96391, -96233, -96074, -95916, -95758, -95601, -95444, -95287, -95131, -94975, -94819, -94664, -94509, -94354, -94200, -94046, -93892, -93739, -93586, -93434, -93281, -93129, -92978, -92826, -92675, -92525, -92375, -92225, -92075, -91926, -91777, -91628, -91480, -91332, -91184, -91036, -90889, -90742, -90596, -90450, -90304, -90158, -90013, -89868, -89724, -89579, -89435, -89292, -89148, -89005, -88862, -88720, -88577, -88435, -88294, -88152, -88011, -87871, -87730, -87590, -87450, -87310, -87171, -87032, -86893, -86755, -86616, -86479, -86341, -86204, -86066, -85930, -85793, -85657, -85521, -85385, -85250, -85114, -84980, -84845, -84710, -84576, -84443, -84309, -84176, -84043, -83910, -83777, -83645, -83513, -83381, -83250, -83118, -82987, -82857, -82726, -82596, -82466, -82336, -82207, -82078, -81949, -81820, -81691, -81563, -81435, -81307, -81180, -81053, -80925, -80799, -80672, -80546, -80420, -80294, -80168, -80043, -79918, -79793, -79668, -79544, -79420, -79296, -79172, -79048, -78925, -78802, -78679, -78557, -78434, -78312, -78190, -78068, -77947, -77826, -77705, -77584, -77463, -77343, -77223, -77103, -76983, -76864, -76744, -76625, -76506, -76388, -76269, -76151, -76033, -75915, -75797, -75680, -75563, -75446, -75329, -75213, -75096, -74980, -74864, -74748, -74633, -74517, -74402, -74287, -74172, -74058, -73944, -73829, -73715, -73602, -73488, -73375, -73262, -73149, -73036, -72923, -72811, -72699, -72587, -72475, -72363, -72252, -72140, -72029, -71918, -71808, -71697, -71587, -71477, -71367, -71257, -71147, -71038, -70929, -70820, -70711, -70602, -70494, -70385, -70277, -70169, -70061, -69954, -69846, -69739, -69632, -69525, -69418, -69312, -69205, -69099, -68993, -68887, -68781, -68676, -68570, -68465, -68360, -68255, -68151, -68046, -67942, -67837, -67733, -67629, -67526, -67422, -67319, -67216, -67113, -67010, -66907, -66804, -66702, -66600, -66498, -66396, -66294, -66192, -66091, -65989, -65888, -65787, -65686, -65586, -65485, -65385, -65285, -65185, -65085, -64985, -64885, -64786, -64687, -64587, -64488, -64389, -64291, -64192, -64094, -63996, -63897, -63799, -63702, -63604, -63506, -63409, -63312, -63215, -63118, -63021, -62924, -62828, -62731, -62635, -62539, -62443, -62347, -62251, -62156, -62060, -61965, -61870, -61775, -61680, -61585, -61491, -61396, -61302, -61208, -61114, -61020, -60926, -60833, -60739, -60646, -60552, -60459, -60366, -60273, -60181, -60088, -59996, -59903, -59811, -59719, -59627, -59535, -59444, -59352, -59261, -59169, -59078, -58987, -58896, -58805, -58715, -58624, -58534, -58443, -58353, -58263, -58173, -58083, -57994, -57904, -57815, -57725, -57636, -57547, -57458, -57369, -57281, -57192, -57104, -57015, -56927, -56839, -56751, -56663, -56575, -56487, -56400, -56312, -56225, -56138, -56051, -55964, -55877, -55790, -55704, -55617, -55531, -55444, -55358, -55272, -55186, -55100, -55015, -54929, -54843, -54758, -54673, -54587, -54502, -54417, -54333, -54248, -54163, -54079, -53994, -53910, -53826, -53741, -53657, -53574, -53490, -53406, -53322, -53239, -53156, -53072, -52989, -52906, -52823, -52740, -52657, -52575, -52492, -52410, -52327, -52245, -52163, -52081, -51999, -51917, -51835, -51754, -51672, -51591, -51509, -51428, -51347, -51266, -51185, -51104, -51023, -50942, -50862, -50781, -50701, -50621, -50540, -50460, -50380, -50300, -50221, -50141, -50061, -49982, -49902, -49823, -49744, -49664, -49585, -49506, -49427, -49349, -49270, -49191, -49113, -49034, -48956, -48878, -48799, -48721, -48643, -48565, -48488, -48410, -48332, -48255, -48177, -48100, -48022, -47945, -47868, -47791, -47714, -47637, -47560, -47484, -47407, -47331, -47254, -47178, -47102, -47025, -46949, -46873, -46797, -46721, -46646, -46570, -46494, -46419, -46343, -46268, -46193, -46118, -46042, -45967, -45892, -45818, -45743, -45668, -45593, -45519, -45444, -45370, -45296, -45221, -45147, -45073, -44999, -44925, -44851, -44778, -44704, -44630, -44557, -44483, -44410, -44337, -44263, -44190, -44117, -44044, -43971, -43898, -43826, -43753, -43680, -43608, -43535, -43463, -43390, -43318, -43246, -43174, -43102, -43030, -42958, -42886, -42814, -42743, -42671, -42600, -42528, -42457, -42385, -42314, -42243, -42172, -42101, -42030, -41959, -41888, -41817, -41747, -41676, -41605, -41535, -41465, -41394, -41324, -41254, -41184, -41113, -41043, -40973, -40904, -40834, -40764, -40694, -40625, -40555, -40486, -40416, -40347, -40278, -40208, -40139, -40070, -40001, -39932, -39863, -39794, -39726, -39657, -39588, -39520, -39451, -39383, -39314, -39246, -39178, -39110, -39042, -38973, -38905, -38837, -38770, -38702, -38634, -38566, -38499, -38431, -38364, -38296, -38229, -38161, -38094, -38027, -37960, -37893, -37826, -37759, -37692, -37625, -37558, -37491, -37425, -37358, -37291, -37225, -37158, -37092, -37026, -36959, -36893, -36827, -36761, -36695, -36629, -36563, -36497, -36431, -36365, -36300, -36234, -36168, -36103, -36037, -35972, -35907, -35841, -35776, -35711, -35646, -35580, -35515, -35450, -35385, -35321, -35256, -35191, -35126, -35062, -34997, -34932, -34868, -34803, -34739, -34675, -34610, -34546, -34482, -34418, -34354, -34289, -34225, -34162, -34098, -34034, -33970, -33906, -33843, -33779, -33715, -33652, -33588, -33525, -33461, -33398, -33335, -33272, -33208, -33145, -33082, -33019, -32956, -32893, -32830, -32767, -32705, -32642, -32579, -32516, -32454, -32391, -32329, -32266, -32204, -32141, -32079, -32017, -31955, -31892, -31830, -31768, -31706, -31644, -31582, -31520, -31458, -31396, -31335, -31273, -31211, -31150, -31088, -31026, -30965, -30904, -30842, -30781, -30719, -30658, -30597, -30536, -30474, -30413, -30352, -30291, -30230, -30169, -30108, -30048, -29987, -29926, -29865, -29805, -29744, -29683, -29623, -29562, -29502, -29441, -29381, -29321, -29260, -29200, -29140, -29080, -29020, -28959, -28899, -28839, -28779, -28719, -28660, -28600, -28540, -28480, -28420, -28361, -28301, -28241, -28182, -28122, -28063, -28003, -27944, -27884, -27825, -27766, -27707, -27647, -27588, -27529, -27470, -27411, -27352, -27293, -27234, -27175, -27116, -27057, -26998, -26940, -26881, -26822, -26763, -26705, -26646, -26588, -26529, -26471, -26412, -26354, -26295, -26237, -26179, -26120, -26062, -26004, -25946, -25888, -25830, -25772, -25714, -25656, -25598, -25540, -25482, -25424, -25366, -25308, -25251, -25193, -25135, -25078, -25020, -24962, -24905, -24847, -24790, -24732, -24675, -24618, -24560, -24503, -24446, -24389, -24331, -24274, -24217, -24160, -24103, -24046, -23989, -23932, -23875, -23818, -23761, -23704, -23647, -23591, -23534, -23477, -23420, -23364, -23307, -23250, -23194, -23137, -23081, -23024, -22968, -22911, -22855, -22799, -22742, -22686, -22630, -22573, -22517, -22461, -22405, -22349, -22293, -22237, -22181, -22125, -22069, -22013, -21957, -21901, -21845, -21789, -21733, -21678, -21622, -21566, -21510, -21455, -21399, -21343, -21288, -21232, -21177, -21121, -21066, -21010, -20955, -20900, -20844, -20789, -20734, -20678, -20623, -20568, -20513, -20457, -20402, -20347, -20292, -20237, -20182, -20127, -20072, -20017, -19962, -19907, -19852, -19797, -19742, -19688, -19633, -19578, -19523, -19469, -19414, -19359, -19305, -19250, -19195, -19141, -19086, -19032, -18977, -18923, -18868, -18814, -18760, -18705, -18651, -18597, -18542, -18488, -18434, -18380, -18325, -18271, -18217, -18163, -18109, -18055, -18001, -17946, -17892, -17838, -17784, -17731, -17677, -17623, -17569, -17515, -17461, -17407, -17353, -17300, -17246, -17192, -17138, -17085, -17031, -16977, -16924, -16870, -16817, -16763, -16710, -16656, -16603, -16549, -16496, -16442, -16389, -16335, -16282, -16229, -16175, -16122, -16069, -16015, -15962, -15909, -15856, -15802, -15749, -15696, -15643, -15590, -15537, -15484, -15431, -15378, -15325, -15272, -15219, -15166, -15113, -15060, -15007, -14954, -14901, -14848, -14795, -14743, -14690, -14637, -14584, -14531, -14479, -14426, -14373, -14321, -14268, -14215, -14163, -14110, -14057, -14005, -13952, -13900, -13847, -13795, -13742, -13690, -13637, -13585, -13533, -13480, -13428, -13375, -13323, -13271, -13218, -13166, -13114, -13062, -13009, -12957, -12905, -12853, -12800, -12748, -12696, -12644, -12592, -12540, -12488, -12436, -12383, -12331, -12279, -12227, -12175, -12123, -12071, -12019, -11967, -11916, -11864, -11812, -11760, -11708, -11656, -11604, -11552, -11501, -11449, -11397, -11345, -11293, -11242, -11190, -11138, -11086, -11035, -10983, -10931, -10880, -10828, -10777, -10725, -10673, -10622, -10570, -10519, -10467, -10415, -10364, -10312, -10261, -10209, -10158, -10106, -10055, -10004, -9952, -9901, -9849, -9798, -9747, -9695, -9644, -9592, -9541, -9490, -9438, -9387, -9336, -9285, -9233, -9182, -9131, -9080, -9028, -8977, -8926, -8875, -8824, -8772, -8721, -8670, -8619, -8568, -8517, -8466, -8414, -8363, -8312, -8261, -8210, -8159, -8108, -8057, -8006, -7955, -7904, -7853, -7802, -7751, -7700, -7649, -7598, -7547, -7496, -7445, -7395, -7344, -7293, -7242, -7191, -7140, -7089, -7038, -6988, -6937, -6886, -6835, -6784, -6733, -6683, -6632, -6581, -6530, -6480, -6429, -6378, -6327, -6277, -6226, -6175, -6124, -6074, -6023, -5972, -5922, -5871, -5820, -5770, -5719, -5668, -5618, -5567, -5517, -5466, -5415, -5365, -5314, -5264, -5213, -5162, -5112, -5061, -5011, -4960, -4910, -4859, -4808, -4758, -4707, -4657, -4606, -4556, -4505, -4455, -4404, -4354, -4303, -4253, -4202, -4152, -4101, -4051, -4001, -3950, -3900, -3849, -3799, -3748, -3698, -3648, -3597, -3547, -3496, -3446, -3395, -3345, -3295, -3244, -3194, -3144, -3093, -3043, -2992, -2942, -2892, -2841, -2791, -2741, -2690, -2640, -2590, -2539, -2489, -2439, -2388, -2338, -2288, -2237, -2187, -2137, -2086, -2036, -1986, -1935, -1885, -1835, -1784, -1734, -1684, -1633, -1583, -1533, -1483, -1432, -1382, -1332, -1281, -1231, -1181, -1131, -1080, -1030, -980, -929, -879, -829, -779, -728, -678, -628, -578, -527, -477, -427, -376, -326, -276, -226, -175, -125, -75, -25, 25, 75, 125, 175, 226, 276, 326, 376, 427, 477, 527, 578, 628, 678, 728, 779, 829, 879, 929, 980, 1030, 1080, 1131, 1181, 1231, 1281, 1332, 1382, 1432, 1483, 1533, 1583, 1633, 1684, 1734, 1784, 1835, 1885, 1935, 1986, 2036, 2086, 2137, 2187, 2237, 2288, 2338, 2388, 2439, 2489, 2539, 2590, 2640, 2690, 2741, 2791, 2841, 2892, 2942, 2992, 3043, 3093, 3144, 3194, 3244, 3295, 3345, 3395, 3446, 3496, 3547, 3597, 3648, 3698, 3748, 3799, 3849, 3900, 3950, 4001, 4051, 4101, 4152, 4202, 4253, 4303, 4354, 4404, 4455, 4505, 4556, 4606, 4657, 4707, 4758, 4808, 4859, 4910, 4960, 5011, 5061, 5112, 5162, 5213, 5264, 5314, 5365, 5415, 5466, 5517, 5567, 5618, 5668, 5719, 5770, 5820, 5871, 5922, 5972, 6023, 6074, 6124, 6175, 6226, 6277, 6327, 6378, 6429, 6480, 6530, 6581, 6632, 6683, 6733, 6784, 6835, 6886, 6937, 6988, 7038, 7089, 7140, 7191, 7242, 7293, 7344, 7395, 7445, 7496, 7547, 7598, 7649, 7700, 7751, 7802, 7853, 7904, 7955, 8006, 8057, 8108, 8159, 8210, 8261, 8312, 8363, 8414, 8466, 8517, 8568, 8619, 8670, 8721, 8772, 8824, 8875, 8926, 8977, 9028, 9080, 9131, 9182, 9233, 9285, 9336, 9387, 9438, 9490, 9541, 9592, 9644, 9695, 9747, 9798, 9849, 9901, 9952, 10004, 10055, 10106, 10158, 10209, 10261, 10312, 10364, 10415, 10467, 10519, 10570, 10622, 10673, 10725, 10777, 10828, 10880, 10931, 10983, 11035, 11086, 11138, 11190, 11242, 11293, 11345, 11397, 11449, 11501, 11552, 11604, 11656, 11708, 11760, 11812, 11864, 11916, 11967, 12019, 12071, 12123, 12175, 12227, 12279, 12331, 12383, 12436, 12488, 12540, 12592, 12644, 12696, 12748, 12800, 12853, 12905, 12957, 13009, 13062, 13114, 13166, 13218, 13271, 13323, 13375, 13428, 13480, 13533, 13585, 13637, 13690, 13742, 13795, 13847, 13900, 13952, 14005, 14057, 14110, 14163, 14215, 14268, 14321, 14373, 14426, 14479, 14531, 14584, 14637, 14690, 14743, 14795, 14848, 14901, 14954, 15007, 15060, 15113, 15166, 15219, 15272, 15325, 15378, 15431, 15484, 15537, 15590, 15643, 15696, 15749, 15802, 15856, 15909, 15962, 16015, 16069, 16122, 16175, 16229, 16282, 16335, 16389, 16442, 16496, 16549, 16603, 16656, 16710, 16763, 16817, 16870, 16924, 16977, 17031, 17085, 17138, 17192, 17246, 17300, 17353, 17407, 17461, 17515, 17569, 17623, 17677, 17731, 17784, 17838, 17892, 17946, 18001, 18055, 18109, 18163, 18217, 18271, 18325, 18380, 18434, 18488, 18542, 18597, 18651, 18705, 18760, 18814, 18868, 18923, 18977, 19032, 19086, 19141, 19195, 19250, 19305, 19359, 19414, 19469, 19523, 19578, 19633, 19688, 19742, 19797, 19852, 19907, 19962, 20017, 20072, 20127, 20182, 20237, 20292, 20347, 20402, 20457, 20513, 20568, 20623, 20678, 20734, 20789, 20844, 20900, 20955, 21010, 21066, 21121, 21177, 21232, 21288, 21343, 21399, 21455, 21510, 21566, 21622, 21678, 21733, 21789, 21845, 21901, 21957, 22013, 22069, 22125, 22181, 22237, 22293, 22349, 22405, 22461, 22517, 22573, 22630, 22686, 22742, 22799, 22855, 22911, 22968, 23024, 23081, 23137, 23194, 23250, 23307, 23364, 23420, 23477, 23534, 23591, 23647, 23704, 23761, 23818, 23875, 23932, 23989, 24046, 24103, 24160, 24217, 24274, 24331, 24389, 24446, 24503, 24560, 24618, 24675, 24732, 24790, 24847, 24905, 24962, 25020, 25078, 25135, 25193, 25251, 25308, 25366, 25424, 25482, 25540, 25598, 25656, 25714, 25772, 25830, 25888, 25946, 26004, 26062, 26120, 26179, 26237, 26295, 26354, 26412, 26471, 26529, 26588, 26646, 26705, 26763, 26822, 26881, 26940, 26998, 27057, 27116, 27175, 27234, 27293, 27352, 27411, 27470, 27529, 27588, 27647, 27707, 27766, 27825, 27884, 27944, 28003, 28063, 28122, 28182, 28241, 28301, 28361, 28420, 28480, 28540, 28600, 28660, 28719, 28779, 28839, 28899, 28959, 29020, 29080, 29140, 29200, 29260, 29321, 29381, 29441, 29502, 29562, 29623, 29683, 29744, 29805, 29865, 29926, 29987, 30048, 30108, 30169, 30230, 30291, 30352, 30413, 30474, 30536, 30597, 30658, 30719, 30781, 30842, 30904, 30965, 31026, 31088, 31150, 31211, 31273, 31335, 31396, 31458, 31520, 31582, 31644, 31706, 31768, 31830, 31892, 31955, 32017, 32079, 32141, 32204, 32266, 32329, 32391, 32454, 32516, 32579, 32642, 32705, 32767, 32830, 32893, 32956, 33019, 33082, 33145, 33208, 33272, 33335, 33398, 33461, 33525, 33588, 33652, 33715, 33779, 33843, 33906, 33970, 34034, 34098, 34162, 34225, 34289, 34354, 34418, 34482, 34546, 34610, 34675, 34739, 34803, 34868, 34932, 34997, 35062, 35126, 35191, 35256, 35321, 35385, 35450, 35515, 35580, 35646, 35711, 35776, 35841, 35907, 35972, 36037, 36103, 36168, 36234, 36300, 36365, 36431, 36497, 36563, 36629, 36695, 36761, 36827, 36893, 36959, 37026, 37092, 37158, 37225, 37291, 37358, 37425, 37491, 37558, 37625, 37692, 37759, 37826, 37893, 37960, 38027, 38094, 38161, 38229, 38296, 38364, 38431, 38499, 38566, 38634, 38702, 38770, 38837, 38905, 38973, 39042, 39110, 39178, 39246, 39314, 39383, 39451, 39520, 39588, 39657, 39726, 39794, 39863, 39932, 40001, 40070, 40139, 40208, 40278, 40347, 40416, 40486, 40555, 40625, 40694, 40764, 40834, 40904, 40973, 41043, 41113, 41184, 41254, 41324, 41394, 41465, 41535, 41605, 41676, 41747, 41817, 41888, 41959, 42030, 42101, 42172, 42243, 42314, 42385, 42457, 42528, 42600, 42671, 42743, 42814, 42886, 42958, 43030, 43102, 43174, 43246, 43318, 43390, 43463, 43535, 43608, 43680, 43753, 43826, 43898, 43971, 44044, 44117, 44190, 44263, 44337, 44410, 44483, 44557, 44630, 44704, 44778, 44851, 44925, 44999, 45073, 45147, 45221, 45296, 45370, 45444, 45519, 45593, 45668, 45743, 45818, 45892, 45967, 46042, 46118, 46193, 46268, 46343, 46419, 46494, 46570, 46646, 46721, 46797, 46873, 46949, 47025, 47102, 47178, 47254, 47331, 47407, 47484, 47560, 47637, 47714, 47791, 47868, 47945, 48022, 48100, 48177, 48255, 48332, 48410, 48488, 48565, 48643, 48721, 48799, 48878, 48956, 49034, 49113, 49191, 49270, 49349, 49427, 49506, 49585, 49664, 49744, 49823, 49902, 49982, 50061, 50141, 50221, 50300, 50380, 50460, 50540, 50621, 50701, 50781, 50862, 50942, 51023, 51104, 51185, 51266, 51347, 51428, 51509, 51591, 51672, 51754, 51835, 51917, 51999, 52081, 52163, 52245, 52327, 52410, 52492, 52575, 52657, 52740, 52823, 52906, 52989, 53072, 53156, 53239, 53322, 53406, 53490, 53574, 53657, 53741, 53826, 53910, 53994, 54079, 54163, 54248, 54333, 54417, 54502, 54587, 54673, 54758, 54843, 54929, 55015, 55100, 55186, 55272, 55358, 55444, 55531, 55617, 55704, 55790, 55877, 55964, 56051, 56138, 56225, 56312, 56400, 56487, 56575, 56663, 56751, 56839, 56927, 57015, 57104, 57192, 57281, 57369, 57458, 57547, 57636, 57725, 57815, 57904, 57994, 58083, 58173, 58263, 58353, 58443, 58534, 58624, 58715, 58805, 58896, 58987, 59078, 59169, 59261, 59352, 59444, 59535, 59627, 59719, 59811, 59903, 59996, 60088, 60181, 60273, 60366, 60459, 60552, 60646, 60739, 60833, 60926, 61020, 61114, 61208, 61302, 61396, 61491, 61585, 61680, 61775, 61870, 61965, 62060, 62156, 62251, 62347, 62443, 62539, 62635, 62731, 62828, 62924, 63021, 63118, 63215, 63312, 63409, 63506, 63604, 63702, 63799, 63897, 63996, 64094, 64192, 64291, 64389, 64488, 64587, 64687, 64786, 64885, 64985, 65085, 65185, 65285, 65385, 65485, 65586, 65686, 65787, 65888, 65989, 66091, 66192, 66294, 66396, 66498, 66600, 66702, 66804, 66907, 67010, 67113, 67216, 67319, 67422, 67526, 67629, 67733, 67837, 67942, 68046, 68151, 68255, 68360, 68465, 68570, 68676, 68781, 68887, 68993, 69099, 69205, 69312, 69418, 69525, 69632, 69739, 69846, 69954, 70061, 70169, 70277, 70385, 70494, 70602, 70711, 70820, 70929, 71038, 71147, 71257, 71367, 71477, 71587, 71697, 71808, 71918, 72029, 72140, 72252, 72363, 72475, 72587, 72699, 72811, 72923, 73036, 73149, 73262, 73375, 73488, 73602, 73715, 73829, 73944, 74058, 74172, 74287, 74402, 74517, 74633, 74748, 74864, 74980, 75096, 75213, 75329, 75446, 75563, 75680, 75797, 75915, 76033, 76151, 76269, 76388, 76506, 76625, 76744, 76864, 76983, 77103, 77223, 77343, 77463, 77584, 77705, 77826, 77947, 78068, 78190, 78312, 78434, 78557, 78679, 78802, 78925, 79048, 79172, 79296, 79420, 79544, 79668, 79793, 79918, 80043, 80168, 80294, 80420, 80546, 80672, 80799, 80925, 81053, 81180, 81307, 81435, 81563, 81691, 81820, 81949, 82078, 82207, 82336, 82466, 82596, 82726, 82857, 82987, 83118, 83250, 83381, 83513, 83645, 83777, 83910, 84043, 84176, 84309, 84443, 84576, 84710, 84845, 84980, 85114, 85250, 85385, 85521, 85657, 85793, 85930, 86066, 86204, 86341, 86479, 86616, 86755, 86893, 87032, 87171, 87310, 87450, 87590, 87730, 87871, 88011, 88152, 88294, 88435, 88577, 88720, 88862, 89005, 89148, 89292, 89435, 89579, 89724, 89868, 90013, 90158, 90304, 90450, 90596, 90742, 90889, 91036, 91184, 91332, 91480, 91628, 91777, 91926, 92075, 92225, 92375, 92525, 92675, 92826, 92978, 93129, 93281, 93434, 93586, 93739, 93892, 94046, 94200, 94354, 94509, 94664, 94819, 94975, 95131, 95287, 95444, 95601, 95758, 95916, 96074, 96233, 96391, 96551, 96710, 96870, 97030, 97191, 97352, 97513, 97675, 97837, 98000, 98163, 98326, 98489, 98653, 98818, 98982, 99148, 99313, 99479, 99645, 99812, 99979, 100146, 100314, 100482, 100651, 100820, 100990, 101159, 101330, 101500, 101671, 101843, 102015, 102187, 102360, 102533, 102706, 102880, 103054, 103229, 103404, 103580, 103756, 103933, 104109, 104287, 104465, 104643, 104821, 105000, 105180, 105360, 105540, 105721, 105902, 106084, 106266, 106449, 106632, 106816, 107000, 107184, 107369, 107555, 107741, 107927, 108114, 108301, 108489, 108677, 108866, 109055, 109245, 109435, 109626, 109817, 110008, 110200, 110393, 110586, 110780, 110974, 111169, 111364, 111560, 111756, 111952, 112150, 112347, 112546, 112744, 112944, 113143, 113344, 113545, 113746, 113948, 114151, 114354, 114557, 114761, 114966, 115171, 115377, 115583, 115790, 115998, 116206, 116414, 116623, 116833, 117044, 117254, 117466, 117678, 117891, 118104, 118318, 118532, 118747, 118963, 119179, 119396, 119613, 119831, 120050, 120269, 120489, 120709, 120930, 121152, 121374, 121597, 121821, 122045, 122270, 122496, 122722, 122949, 123176, 123404, 123633, 123863, 124093, 124324, 124555, 124787, 125020, 125254, 125488, 125723, 125959, 126195, 126432, 126669, 126908, 127147, 127387, 127627, 127869, 128111, 128353, 128597, 128841, 129086, 129332, 129578, 129825, 130073, 130322, 130571, 130821, 131072, 131324, 131576, 131830, 132084, 132339, 132594, 132851, 133108, 133366, 133625, 133884, 134145, 134406, 134668, 134931, 135195, 135459, 135725, 135991, 136258, 136526, 136795, 137065, 137335, 137607, 137879, 138152, 138426, 138701, 138977, 139254, 139532, 139810, 140090, 140370, 140651, 140934, 141217, 141501, 141786, 142072, 142359, 142647, 142936, 143226, 143517, 143808, 144101, 144395, 144690, 144986, 145282, 145580, 145879, 146179, 146480, 146782, 147084, 147388, 147693, 148000, 148307, 148615, 148924, 149235, 149546, 149859, 150172, 150487, 150803, 151120, 151438, 151757, 152077, 152399, 152722, 153045, 153370, 153697, 154024, 154352, 154682, 155013, 155345, 155678, 156013, 156349, 156686, 157024, 157363, 157704, 158046, 158389, 158734, 159079, 159427, 159775, 160125, 160476, 160828, 161182, 161537, 161893, 162251, 162610, 162970, 163332, 163695, 164060, 164426, 164793, 165162, 165532, 165904, 166277, 166651, 167027, 167405, 167784, 168164, 168546, 168930, 169315, 169701, 170089, 170479, 170870, 171263, 171657, 172053, 172451, 172850, 173251, 173653, 174057, 174463, 174870, 175279, 175690, 176102, 176516, 176932, 177349, 177769, 178190, 178612, 179037, 179463, 179891, 180321, 180753, 181186, 181622, 182059, 182498, 182939, 183382, 183827, 184274, 184722, 185173, 185625, 186080, 186536, 186995, 187455, 187918, 188382, 188849, 189318, 189789, 190261, 190736, 191213, 191693, 192174, 192658, 193143, 193631, 194122, 194614, 195109, 195606, 196105, 196606, 197110, 197616, 198125, 198636, 199149, 199664, 200182, 200703, 201226, 201751, 202279, 202809, 203342, 203878, 204416, 204956, 205500, 206045, 206594, 207145, 207699, 208255, 208815, 209376, 209941, 210509, 211079, 211652, 212228, 212807, 213389, 213973, 214561, 215151, 215745, 216341, 216941, 217544, 218149, 218758, 219370, 219985, 220603, 221225, 221849, 222477, 223108, 223743, 224381, 225022, 225666, 226314, 226966, 227621, 228279, 228941, 229606, 230275, 230948, 231624, 232304, 232988, 233676, 234367, 235062, 235761, 236463, 237170, 237881, 238595, 239314, 240036, 240763, 241493, 242228, 242967, 243711, 244458, 245210, 245966, 246727, 247492, 248261, 249035, 249813, 250596, 251384, 252176, 252973, 253774, 254581, 255392, 256208, 257029, 257855, 258686, 259522, 260363, 261209, 262060, 262917, 263779, 264646, 265519, 266397, 267280, 268169, 269064, 269965, 270871, 271782, 272700, 273624, 274553, 275489, 276430, 277378, 278332, 279292, 280258, 281231, 282210, 283195, 284188, 285186, 286192, 287204, 288223, 289249, 290282, 291322, 292369, 293423, 294485, 295554, 296630, 297714, 298805, 299904, 301011, 302126, 303248, 304379, 305517, 306664, 307819, 308983, 310154, 311335, 312524, 313721, 314928, 316143, 317368, 318601, 319844, 321097, 322358, 323629, 324910, 326201, 327502, 328812, 330133, 331464, 332805, 334157, 335519, 336892, 338276, 339671, 341078, 342495, 343924, 345364, 346816, 348280, 349756, 351244, 352744, 354257, 355783, 357321, 358872, 360436, 362013, 363604, 365208, 366826, 368459, 370105, 371765, 373440, 375130, 376835, 378555, 380290, 382040, 383807, 385589, 387387, 389202, 391034, 392882, 394747, 396630, 398530, 400448, 402384, 404338, 406311, 408303, 410314, 412344, 414395, 416465, 418555, 420666, 422798, 424951, 427125, 429321, 431540, 433781, 436045, 438332, 440643, 442978, 445337, 447720, 450129, 452564, 455024, 457511, 460024, 462565, 465133, 467730, 470355, 473009, 475692, 478406, 481150, 483925, 486732, 489571, 492443, 495348, 498287, 501261, 504269, 507313, 510394, 513512, 516667, 519861, 523094, 526366, 529680, 533034, 536431, 539870, 543354, 546881, 550455, 554074, 557741, 561456, 565221, 569035, 572901, 576818, 580789, 584815, 588896, 593033, 597229, 601483, 605798, 610174, 614613, 619117, 623686, 628323, 633028, 637803, 642651, 647572, 652568, 657640, 662792, 668024, 673338, 678737, 684223, 689797, 695462, 701219, 707072, 713023, 719074, 725227, 731486, 737853, 744331, 750922, 757631, 764460, 771411, 778490, 785699, 793041, 800521, 808143, 815910, 823827, 831898, 840127, 848520, 857081, 865817, 874730, 883829, 893117, 902602, 912289, 922186, 932298, 942633, 953199, 964003, 975054, 986361, 997931, 1009774, 1021901, 1034322, 1047046, 1060087, 1073455, 1087164, 1101225, 1115654, 1130465, 1145673, 1161294, 1177345, 1193846, 1210813, 1228269, 1246234, 1264730, 1283783, 1303416, 1323658, 1344537, 1366084, 1388330, 1411312, 1435065, 1459630, 1485049, 1511367, 1538632, 1566898, 1596220, 1626658, 1658278, 1691149, 1725348, 1760956, 1798063, 1836758, 1877161, 1919378, 1963536, 2009771, 2058233, 2109087, 2162516, 2218719, 2277919, 2340362, 2406322, 2476104, 2550052, 2628549, 2712030, 2800983, 2895966, 2997613, 3106651, 3223918, 3350381, 3487165, 3635590, 3797206, 3973855, 4167737, 4381502, 4618375, 4882318, 5178251, 5512368, 5892567, 6329090, 6835455, 7429880, 8137527, 8994149, 10052327, 11392683, 13145455, 15535599, 18988036, 24413316, 34178904, 56965752, 170910304 }; + +//const fixed_t *const finecosine = &finesine[FINEANGLES/4]; + +const fixed_t finesine[10240] = +{ 25, 75, 125, 175, 226, 276, 326, 376, 427, 477, 527, 578, 628, 678, 728, 779, 829, 879, 929, 980, 1030, 1080, 1130, 1181, 1231, 1281, 1331, 1382, 1432, 1482, 1532, 1583, 1633, 1683, 1733, 1784, 1834, 1884, 1934, 1985, 2035, 2085, 2135, 2186, 2236, 2286, 2336, 2387, 2437, 2487, 2537, 2587, 2638, 2688, 2738, 2788, 2839, 2889, 2939, 2989, 3039, 3090, 3140, 3190, 3240, 3291, 3341, 3391, 3441, 3491, 3541, 3592, 3642, 3692, 3742, 3792, 3843, 3893, 3943, 3993, 4043, 4093, 4144, 4194, 4244, 4294, 4344, 4394, 4445, 4495, 4545, 4595, 4645, 4695, 4745, 4796, 4846, 4896, 4946, 4996, 5046, 5096, 5146, 5197, 5247, 5297, 5347, 5397, 5447, 5497, 5547, 5597, 5647, 5697, 5748, 5798, 5848, 5898, 5948, 5998, 6048, 6098, 6148, 6198, 6248, 6298, 6348, 6398, 6448, 6498, 6548, 6598, 6648, 6698, 6748, 6798, 6848, 6898, 6948, 6998, 7048, 7098, 7148, 7198, 7248, 7298, 7348, 7398, 7448, 7498, 7548, 7598, 7648, 7697, 7747, 7797, 7847, 7897, 7947, 7997, 8047, 8097, 8147, 8196, 8246, 8296, 8346, 8396, 8446, 8496, 8545, 8595, 8645, 8695, 8745, 8794, 8844, 8894, 8944, 8994, 9043, 9093, 9143, 9193, 9243, 9292, 9342, 9392, 9442, 9491, 9541, 9591, 9640, 9690, 9740, 9790, 9839, 9889, 9939, 9988, 10038, 10088, 10137, 10187, 10237, 10286, 10336, 10386, 10435, 10485, 10534, 10584, 10634, 10683, 10733, 10782, 10832, 10882, 10931, 10981, 11030, 11080, 11129, 11179, 11228, 11278, 11327, 11377, 11426, 11476, 11525, 11575, 11624, 11674, 11723, 11773, 11822, 11872, 11921, 11970, 12020, 12069, 12119, 12168, 12218, 12267, 12316, 12366, 12415, 12464, 12514, 12563, 12612, 12662, 12711, 12760, 12810, 12859, 12908, 12957, 13007, 13056, 13105, 13154, 13204, 13253, 13302, 13351, 13401, 13450, 13499, 13548, 13597, 13647, 13696, 13745, 13794, 13843, 13892, 13941, 13990, 14040, 14089, 14138, 14187, 14236, 14285, 14334, 14383, 14432, 14481, 14530, 14579, 14628, 14677, 14726, 14775, 14824, 14873, 14922, 14971, 15020, 15069, 15118, 15167, 15215, 15264, 15313, 15362, 15411, 15460, 15509, 15557, 15606, 15655, 15704, 15753, 15802, 15850, 15899, 15948, 15997, 16045, 16094, 16143, 16191, 16240, 16289, 16338, 16386, 16435, 16484, 16532, 16581, 16629, 16678, 16727, 16775, 16824, 16872, 16921, 16970, 17018, 17067, 17115, 17164, 17212, 17261, 17309, 17358, 17406, 17455, 17503, 17551, 17600, 17648, 17697, 17745, 17793, 17842, 17890, 17939, 17987, 18035, 18084, 18132, 18180, 18228, 18277, 18325, 18373, 18421, 18470, 18518, 18566, 18614, 18663, 18711, 18759, 18807, 18855, 18903, 18951, 19000, 19048, 19096, 19144, 19192, 19240, 19288, 19336, 19384, 19432, 19480, 19528, 19576, 19624, 19672, 19720, 19768, 19816, 19864, 19912, 19959, 20007, 20055, 20103, 20151, 20199, 20246, 20294, 20342, 20390, 20438, 20485, 20533, 20581, 20629, 20676, 20724, 20772, 20819, 20867, 20915, 20962, 21010, 21057, 21105, 21153, 21200, 21248, 21295, 21343, 21390, 21438, 21485, 21533, 21580, 21628, 21675, 21723, 21770, 21817, 21865, 21912, 21960, 22007, 22054, 22102, 22149, 22196, 22243, 22291, 22338, 22385, 22433, 22480, 22527, 22574, 22621, 22668, 22716, 22763, 22810, 22857, 22904, 22951, 22998, 23045, 23092, 23139, 23186, 23233, 23280, 23327, 23374, 23421, 23468, 23515, 23562, 23609, 23656, 23703, 23750, 23796, 23843, 23890, 23937, 23984, 24030, 24077, 24124, 24171, 24217, 24264, 24311, 24357, 24404, 24451, 24497, 24544, 24591, 24637, 24684, 24730, 24777, 24823, 24870, 24916, 24963, 25009, 25056, 25102, 25149, 25195, 25241, 25288, 25334, 25381, 25427, 25473, 25520, 25566, 25612, 25658, 25705, 25751, 25797, 25843, 25889, 25936, 25982, 26028, 26074, 26120, 26166, 26212, 26258, 26304, 26350, 26396, 26442, 26488, 26534, 26580, 26626, 26672, 26718, 26764, 26810, 26856, 26902, 26947, 26993, 27039, 27085, 27131, 27176, 27222, 27268, 27313, 27359, 27405, 27450, 27496, 27542, 27587, 27633, 27678, 27724, 27770, 27815, 27861, 27906, 27952, 27997, 28042, 28088, 28133, 28179, 28224, 28269, 28315, 28360, 28405, 28451, 28496, 28541, 28586, 28632, 28677, 28722, 28767, 28812, 28858, 28903, 28948, 28993, 29038, 29083, 29128, 29173, 29218, 29263, 29308, 29353, 29398, 29443, 29488, 29533, 29577, 29622, 29667, 29712, 29757, 29801, 29846, 29891, 29936, 29980, 30025, 30070, 30114, 30159, 30204, 30248, 30293, 30337, 30382, 30426, 30471, 30515, 30560, 30604, 30649, 30693, 30738, 30782, 30826, 30871, 30915, 30959, 31004, 31048, 31092, 31136, 31181, 31225, 31269, 31313, 31357, 31402, 31446, 31490, 31534, 31578, 31622, 31666, 31710, 31754, 31798, 31842, 31886, 31930, 31974, 32017, 32061, 32105, 32149, 32193, 32236, 32280, 32324, 32368, 32411, 32455, 32499, 32542, 32586, 32630, 32673, 32717, 32760, 32804, 32847, 32891, 32934, 32978, 33021, 33065, 33108, 33151, 33195, 33238, 33281, 33325, 33368, 33411, 33454, 33498, 33541, 33584, 33627, 33670, 33713, 33756, 33799, 33843, 33886, 33929, 33972, 34015, 34057, 34100, 34143, 34186, 34229, 34272, 34315, 34358, 34400, 34443, 34486, 34529, 34571, 34614, 34657, 34699, 34742, 34785, 34827, 34870, 34912, 34955, 34997, 35040, 35082, 35125, 35167, 35210, 35252, 35294, 35337, 35379, 35421, 35464, 35506, 35548, 35590, 35633, 35675, 35717, 35759, 35801, 35843, 35885, 35927, 35969, 36011, 36053, 36095, 36137, 36179, 36221, 36263, 36305, 36347, 36388, 36430, 36472, 36514, 36555, 36597, 36639, 36681, 36722, 36764, 36805, 36847, 36889, 36930, 36972, 37013, 37055, 37096, 37137, 37179, 37220, 37262, 37303, 37344, 37386, 37427, 37468, 37509, 37551, 37592, 37633, 37674, 37715, 37756, 37797, 37838, 37879, 37920, 37961, 38002, 38043, 38084, 38125, 38166, 38207, 38248, 38288, 38329, 38370, 38411, 38451, 38492, 38533, 38573, 38614, 38655, 38695, 38736, 38776, 38817, 38857, 38898, 38938, 38979, 39019, 39059, 39100, 39140, 39180, 39221, 39261, 39301, 39341, 39382, 39422, 39462, 39502, 39542, 39582, 39622, 39662, 39702, 39742, 39782, 39822, 39862, 39902, 39942, 39982, 40021, 40061, 40101, 40141, 40180, 40220, 40260, 40300, 40339, 40379, 40418, 40458, 40497, 40537, 40576, 40616, 40655, 40695, 40734, 40773, 40813, 40852, 40891, 40931, 40970, 41009, 41048, 41087, 41127, 41166, 41205, 41244, 41283, 41322, 41361, 41400, 41439, 41478, 41517, 41556, 41595, 41633, 41672, 41711, 41750, 41788, 41827, 41866, 41904, 41943, 41982, 42020, 42059, 42097, 42136, 42174, 42213, 42251, 42290, 42328, 42366, 42405, 42443, 42481, 42520, 42558, 42596, 42634, 42672, 42711, 42749, 42787, 42825, 42863, 42901, 42939, 42977, 43015, 43053, 43091, 43128, 43166, 43204, 43242, 43280, 43317, 43355, 43393, 43430, 43468, 43506, 43543, 43581, 43618, 43656, 43693, 43731, 43768, 43806, 43843, 43880, 43918, 43955, 43992, 44029, 44067, 44104, 44141, 44178, 44215, 44252, 44289, 44326, 44363, 44400, 44437, 44474, 44511, 44548, 44585, 44622, 44659, 44695, 44732, 44769, 44806, 44842, 44879, 44915, 44952, 44989, 45025, 45062, 45098, 45135, 45171, 45207, 45244, 45280, 45316, 45353, 45389, 45425, 45462, 45498, 45534, 45570, 45606, 45642, 45678, 45714, 45750, 45786, 45822, 45858, 45894, 45930, 45966, 46002, 46037, 46073, 46109, 46145, 46180, 46216, 46252, 46287, 46323, 46358, 46394, 46429, 46465, 46500, 46536, 46571, 46606, 46642, 46677, 46712, 46747, 46783, 46818, 46853, 46888, 46923, 46958, 46993, 47028, 47063, 47098, 47133, 47168, 47203, 47238, 47273, 47308, 47342, 47377, 47412, 47446, 47481, 47516, 47550, 47585, 47619, 47654, 47688, 47723, 47757, 47792, 47826, 47860, 47895, 47929, 47963, 47998, 48032, 48066, 48100, 48134, 48168, 48202, 48237, 48271, 48305, 48338, 48372, 48406, 48440, 48474, 48508, 48542, 48575, 48609, 48643, 48676, 48710, 48744, 48777, 48811, 48844, 48878, 48911, 48945, 48978, 49012, 49045, 49078, 49112, 49145, 49178, 49211, 49244, 49278, 49311, 49344, 49377, 49410, 49443, 49476, 49509, 49542, 49575, 49608, 49640, 49673, 49706, 49739, 49771, 49804, 49837, 49869, 49902, 49935, 49967, 50000, 50032, 50065, 50097, 50129, 50162, 50194, 50226, 50259, 50291, 50323, 50355, 50387, 50420, 50452, 50484, 50516, 50548, 50580, 50612, 50644, 50675, 50707, 50739, 50771, 50803, 50834, 50866, 50898, 50929, 50961, 50993, 51024, 51056, 51087, 51119, 51150, 51182, 51213, 51244, 51276, 51307, 51338, 51369, 51401, 51432, 51463, 51494, 51525, 51556, 51587, 51618, 51649, 51680, 51711, 51742, 51773, 51803, 51834, 51865, 51896, 51926, 51957, 51988, 52018, 52049, 52079, 52110, 52140, 52171, 52201, 52231, 52262, 52292, 52322, 52353, 52383, 52413, 52443, 52473, 52503, 52534, 52564, 52594, 52624, 52653, 52683, 52713, 52743, 52773, 52803, 52832, 52862, 52892, 52922, 52951, 52981, 53010, 53040, 53069, 53099, 53128, 53158, 53187, 53216, 53246, 53275, 53304, 53334, 53363, 53392, 53421, 53450, 53479, 53508, 53537, 53566, 53595, 53624, 53653, 53682, 53711, 53739, 53768, 53797, 53826, 53854, 53883, 53911, 53940, 53969, 53997, 54026, 54054, 54082, 54111, 54139, 54167, 54196, 54224, 54252, 54280, 54308, 54337, 54365, 54393, 54421, 54449, 54477, 54505, 54533, 54560, 54588, 54616, 54644, 54672, 54699, 54727, 54755, 54782, 54810, 54837, 54865, 54892, 54920, 54947, 54974, 55002, 55029, 55056, 55084, 55111, 55138, 55165, 55192, 55219, 55246, 55274, 55300, 55327, 55354, 55381, 55408, 55435, 55462, 55489, 55515, 55542, 55569, 55595, 55622, 55648, 55675, 55701, 55728, 55754, 55781, 55807, 55833, 55860, 55886, 55912, 55938, 55965, 55991, 56017, 56043, 56069, 56095, 56121, 56147, 56173, 56199, 56225, 56250, 56276, 56302, 56328, 56353, 56379, 56404, 56430, 56456, 56481, 56507, 56532, 56557, 56583, 56608, 56633, 56659, 56684, 56709, 56734, 56760, 56785, 56810, 56835, 56860, 56885, 56910, 56935, 56959, 56984, 57009, 57034, 57059, 57083, 57108, 57133, 57157, 57182, 57206, 57231, 57255, 57280, 57304, 57329, 57353, 57377, 57402, 57426, 57450, 57474, 57498, 57522, 57546, 57570, 57594, 57618, 57642, 57666, 57690, 57714, 57738, 57762, 57785, 57809, 57833, 57856, 57880, 57903, 57927, 57950, 57974, 57997, 58021, 58044, 58067, 58091, 58114, 58137, 58160, 58183, 58207, 58230, 58253, 58276, 58299, 58322, 58345, 58367, 58390, 58413, 58436, 58459, 58481, 58504, 58527, 58549, 58572, 58594, 58617, 58639, 58662, 58684, 58706, 58729, 58751, 58773, 58795, 58818, 58840, 58862, 58884, 58906, 58928, 58950, 58972, 58994, 59016, 59038, 59059, 59081, 59103, 59125, 59146, 59168, 59190, 59211, 59233, 59254, 59276, 59297, 59318, 59340, 59361, 59382, 59404, 59425, 59446, 59467, 59488, 59509, 59530, 59551, 59572, 59593, 59614, 59635, 59656, 59677, 59697, 59718, 59739, 59759, 59780, 59801, 59821, 59842, 59862, 59883, 59903, 59923, 59944, 59964, 59984, 60004, 60025, 60045, 60065, 60085, 60105, 60125, 60145, 60165, 60185, 60205, 60225, 60244, 60264, 60284, 60304, 60323, 60343, 60363, 60382, 60402, 60421, 60441, 60460, 60479, 60499, 60518, 60537, 60556, 60576, 60595, 60614, 60633, 60652, 60671, 60690, 60709, 60728, 60747, 60766, 60785, 60803, 60822, 60841, 60859, 60878, 60897, 60915, 60934, 60952, 60971, 60989, 61007, 61026, 61044, 61062, 61081, 61099, 61117, 61135, 61153, 61171, 61189, 61207, 61225, 61243, 61261, 61279, 61297, 61314, 61332, 61350, 61367, 61385, 61403, 61420, 61438, 61455, 61473, 61490, 61507, 61525, 61542, 61559, 61577, 61594, 61611, 61628, 61645, 61662, 61679, 61696, 61713, 61730, 61747, 61764, 61780, 61797, 61814, 61831, 61847, 61864, 61880, 61897, 61913, 61930, 61946, 61963, 61979, 61995, 62012, 62028, 62044, 62060, 62076, 62092, 62108, 62125, 62141, 62156, 62172, 62188, 62204, 62220, 62236, 62251, 62267, 62283, 62298, 62314, 62329, 62345, 62360, 62376, 62391, 62407, 62422, 62437, 62453, 62468, 62483, 62498, 62513, 62528, 62543, 62558, 62573, 62588, 62603, 62618, 62633, 62648, 62662, 62677, 62692, 62706, 62721, 62735, 62750, 62764, 62779, 62793, 62808, 62822, 62836, 62850, 62865, 62879, 62893, 62907, 62921, 62935, 62949, 62963, 62977, 62991, 63005, 63019, 63032, 63046, 63060, 63074, 63087, 63101, 63114, 63128, 63141, 63155, 63168, 63182, 63195, 63208, 63221, 63235, 63248, 63261, 63274, 63287, 63300, 63313, 63326, 63339, 63352, 63365, 63378, 63390, 63403, 63416, 63429, 63441, 63454, 63466, 63479, 63491, 63504, 63516, 63528, 63541, 63553, 63565, 63578, 63590, 63602, 63614, 63626, 63638, 63650, 63662, 63674, 63686, 63698, 63709, 63721, 63733, 63745, 63756, 63768, 63779, 63791, 63803, 63814, 63825, 63837, 63848, 63859, 63871, 63882, 63893, 63904, 63915, 63927, 63938, 63949, 63960, 63971, 63981, 63992, 64003, 64014, 64025, 64035, 64046, 64057, 64067, 64078, 64088, 64099, 64109, 64120, 64130, 64140, 64151, 64161, 64171, 64181, 64192, 64202, 64212, 64222, 64232, 64242, 64252, 64261, 64271, 64281, 64291, 64301, 64310, 64320, 64330, 64339, 64349, 64358, 64368, 64377, 64387, 64396, 64405, 64414, 64424, 64433, 64442, 64451, 64460, 64469, 64478, 64487, 64496, 64505, 64514, 64523, 64532, 64540, 64549, 64558, 64566, 64575, 64584, 64592, 64601, 64609, 64617, 64626, 64634, 64642, 64651, 64659, 64667, 64675, 64683, 64691, 64699, 64707, 64715, 64723, 64731, 64739, 64747, 64754, 64762, 64770, 64777, 64785, 64793, 64800, 64808, 64815, 64822, 64830, 64837, 64844, 64852, 64859, 64866, 64873, 64880, 64887, 64895, 64902, 64908, 64915, 64922, 64929, 64936, 64943, 64949, 64956, 64963, 64969, 64976, 64982, 64989, 64995, 65002, 65008, 65015, 65021, 65027, 65033, 65040, 65046, 65052, 65058, 65064, 65070, 65076, 65082, 65088, 65094, 65099, 65105, 65111, 65117, 65122, 65128, 65133, 65139, 65144, 65150, 65155, 65161, 65166, 65171, 65177, 65182, 65187, 65192, 65197, 65202, 65207, 65212, 65217, 65222, 65227, 65232, 65237, 65242, 65246, 65251, 65256, 65260, 65265, 65270, 65274, 65279, 65283, 65287, 65292, 65296, 65300, 65305, 65309, 65313, 65317, 65321, 65325, 65329, 65333, 65337, 65341, 65345, 65349, 65352, 65356, 65360, 65363, 65367, 65371, 65374, 65378, 65381, 65385, 65388, 65391, 65395, 65398, 65401, 65404, 65408, 65411, 65414, 65417, 65420, 65423, 65426, 65429, 65431, 65434, 65437, 65440, 65442, 65445, 65448, 65450, 65453, 65455, 65458, 65460, 65463, 65465, 65467, 65470, 65472, 65474, 65476, 65478, 65480, 65482, 65484, 65486, 65488, 65490, 65492, 65494, 65496, 65497, 65499, 65501, 65502, 65504, 65505, 65507, 65508, 65510, 65511, 65513, 65514, 65515, 65516, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65527, 65528, 65529, 65530, 65530, 65531, 65531, 65532, 65532, 65533, 65533, 65534, 65534, 65534, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65534, 65534, 65534, 65533, 65533, 65532, 65532, 65531, 65531, 65530, 65530, 65529, 65528, 65527, 65527, 65526, 65525, 65524, 65523, 65522, 65521, 65520, 65519, 65518, 65516, 65515, 65514, 65513, 65511, 65510, 65508, 65507, 65505, 65504, 65502, 65501, 65499, 65497, 65496, 65494, 65492, 65490, 65488, 65486, 65484, 65482, 65480, 65478, 65476, 65474, 65472, 65470, 65467, 65465, 65463, 65460, 65458, 65455, 65453, 65450, 65448, 65445, 65442, 65440, 65437, 65434, 65431, 65429, 65426, 65423, 65420, 65417, 65414, 65411, 65408, 65404, 65401, 65398, 65395, 65391, 65388, 65385, 65381, 65378, 65374, 65371, 65367, 65363, 65360, 65356, 65352, 65349, 65345, 65341, 65337, 65333, 65329, 65325, 65321, 65317, 65313, 65309, 65305, 65300, 65296, 65292, 65287, 65283, 65279, 65274, 65270, 65265, 65260, 65256, 65251, 65246, 65242, 65237, 65232, 65227, 65222, 65217, 65212, 65207, 65202, 65197, 65192, 65187, 65182, 65177, 65171, 65166, 65161, 65155, 65150, 65144, 65139, 65133, 65128, 65122, 65117, 65111, 65105, 65099, 65094, 65088, 65082, 65076, 65070, 65064, 65058, 65052, 65046, 65040, 65033, 65027, 65021, 65015, 65008, 65002, 64995, 64989, 64982, 64976, 64969, 64963, 64956, 64949, 64943, 64936, 64929, 64922, 64915, 64908, 64902, 64895, 64887, 64880, 64873, 64866, 64859, 64852, 64844, 64837, 64830, 64822, 64815, 64808, 64800, 64793, 64785, 64777, 64770, 64762, 64754, 64747, 64739, 64731, 64723, 64715, 64707, 64699, 64691, 64683, 64675, 64667, 64659, 64651, 64642, 64634, 64626, 64617, 64609, 64600, 64592, 64584, 64575, 64566, 64558, 64549, 64540, 64532, 64523, 64514, 64505, 64496, 64487, 64478, 64469, 64460, 64451, 64442, 64433, 64424, 64414, 64405, 64396, 64387, 64377, 64368, 64358, 64349, 64339, 64330, 64320, 64310, 64301, 64291, 64281, 64271, 64261, 64252, 64242, 64232, 64222, 64212, 64202, 64192, 64181, 64171, 64161, 64151, 64140, 64130, 64120, 64109, 64099, 64088, 64078, 64067, 64057, 64046, 64035, 64025, 64014, 64003, 63992, 63981, 63971, 63960, 63949, 63938, 63927, 63915, 63904, 63893, 63882, 63871, 63859, 63848, 63837, 63825, 63814, 63803, 63791, 63779, 63768, 63756, 63745, 63733, 63721, 63709, 63698, 63686, 63674, 63662, 63650, 63638, 63626, 63614, 63602, 63590, 63578, 63565, 63553, 63541, 63528, 63516, 63504, 63491, 63479, 63466, 63454, 63441, 63429, 63416, 63403, 63390, 63378, 63365, 63352, 63339, 63326, 63313, 63300, 63287, 63274, 63261, 63248, 63235, 63221, 63208, 63195, 63182, 63168, 63155, 63141, 63128, 63114, 63101, 63087, 63074, 63060, 63046, 63032, 63019, 63005, 62991, 62977, 62963, 62949, 62935, 62921, 62907, 62893, 62879, 62865, 62850, 62836, 62822, 62808, 62793, 62779, 62764, 62750, 62735, 62721, 62706, 62692, 62677, 62662, 62648, 62633, 62618, 62603, 62588, 62573, 62558, 62543, 62528, 62513, 62498, 62483, 62468, 62453, 62437, 62422, 62407, 62391, 62376, 62360, 62345, 62329, 62314, 62298, 62283, 62267, 62251, 62236, 62220, 62204, 62188, 62172, 62156, 62141, 62125, 62108, 62092, 62076, 62060, 62044, 62028, 62012, 61995, 61979, 61963, 61946, 61930, 61913, 61897, 61880, 61864, 61847, 61831, 61814, 61797, 61780, 61764, 61747, 61730, 61713, 61696, 61679, 61662, 61645, 61628, 61611, 61594, 61577, 61559, 61542, 61525, 61507, 61490, 61473, 61455, 61438, 61420, 61403, 61385, 61367, 61350, 61332, 61314, 61297, 61279, 61261, 61243, 61225, 61207, 61189, 61171, 61153, 61135, 61117, 61099, 61081, 61062, 61044, 61026, 61007, 60989, 60971, 60952, 60934, 60915, 60897, 60878, 60859, 60841, 60822, 60803, 60785, 60766, 60747, 60728, 60709, 60690, 60671, 60652, 60633, 60614, 60595, 60576, 60556, 60537, 60518, 60499, 60479, 60460, 60441, 60421, 60402, 60382, 60363, 60343, 60323, 60304, 60284, 60264, 60244, 60225, 60205, 60185, 60165, 60145, 60125, 60105, 60085, 60065, 60045, 60025, 60004, 59984, 59964, 59944, 59923, 59903, 59883, 59862, 59842, 59821, 59801, 59780, 59759, 59739, 59718, 59697, 59677, 59656, 59635, 59614, 59593, 59572, 59551, 59530, 59509, 59488, 59467, 59446, 59425, 59404, 59382, 59361, 59340, 59318, 59297, 59276, 59254, 59233, 59211, 59190, 59168, 59146, 59125, 59103, 59081, 59059, 59038, 59016, 58994, 58972, 58950, 58928, 58906, 58884, 58862, 58840, 58818, 58795, 58773, 58751, 58729, 58706, 58684, 58662, 58639, 58617, 58594, 58572, 58549, 58527, 58504, 58481, 58459, 58436, 58413, 58390, 58367, 58345, 58322, 58299, 58276, 58253, 58230, 58207, 58183, 58160, 58137, 58114, 58091, 58067, 58044, 58021, 57997, 57974, 57950, 57927, 57903, 57880, 57856, 57833, 57809, 57785, 57762, 57738, 57714, 57690, 57666, 57642, 57618, 57594, 57570, 57546, 57522, 57498, 57474, 57450, 57426, 57402, 57377, 57353, 57329, 57304, 57280, 57255, 57231, 57206, 57182, 57157, 57133, 57108, 57083, 57059, 57034, 57009, 56984, 56959, 56935, 56910, 56885, 56860, 56835, 56810, 56785, 56760, 56734, 56709, 56684, 56659, 56633, 56608, 56583, 56557, 56532, 56507, 56481, 56456, 56430, 56404, 56379, 56353, 56328, 56302, 56276, 56250, 56225, 56199, 56173, 56147, 56121, 56095, 56069, 56043, 56017, 55991, 55965, 55938, 55912, 55886, 55860, 55833, 55807, 55781, 55754, 55728, 55701, 55675, 55648, 55622, 55595, 55569, 55542, 55515, 55489, 55462, 55435, 55408, 55381, 55354, 55327, 55300, 55274, 55246, 55219, 55192, 55165, 55138, 55111, 55084, 55056, 55029, 55002, 54974, 54947, 54920, 54892, 54865, 54837, 54810, 54782, 54755, 54727, 54699, 54672, 54644, 54616, 54588, 54560, 54533, 54505, 54477, 54449, 54421, 54393, 54365, 54337, 54308, 54280, 54252, 54224, 54196, 54167, 54139, 54111, 54082, 54054, 54026, 53997, 53969, 53940, 53911, 53883, 53854, 53826, 53797, 53768, 53739, 53711, 53682, 53653, 53624, 53595, 53566, 53537, 53508, 53479, 53450, 53421, 53392, 53363, 53334, 53304, 53275, 53246, 53216, 53187, 53158, 53128, 53099, 53069, 53040, 53010, 52981, 52951, 52922, 52892, 52862, 52832, 52803, 52773, 52743, 52713, 52683, 52653, 52624, 52594, 52564, 52534, 52503, 52473, 52443, 52413, 52383, 52353, 52322, 52292, 52262, 52231, 52201, 52171, 52140, 52110, 52079, 52049, 52018, 51988, 51957, 51926, 51896, 51865, 51834, 51803, 51773, 51742, 51711, 51680, 51649, 51618, 51587, 51556, 51525, 51494, 51463, 51432, 51401, 51369, 51338, 51307, 51276, 51244, 51213, 51182, 51150, 51119, 51087, 51056, 51024, 50993, 50961, 50929, 50898, 50866, 50834, 50803, 50771, 50739, 50707, 50675, 50644, 50612, 50580, 50548, 50516, 50484, 50452, 50420, 50387, 50355, 50323, 50291, 50259, 50226, 50194, 50162, 50129, 50097, 50065, 50032, 50000, 49967, 49935, 49902, 49869, 49837, 49804, 49771, 49739, 49706, 49673, 49640, 49608, 49575, 49542, 49509, 49476, 49443, 49410, 49377, 49344, 49311, 49278, 49244, 49211, 49178, 49145, 49112, 49078, 49045, 49012, 48978, 48945, 48911, 48878, 48844, 48811, 48777, 48744, 48710, 48676, 48643, 48609, 48575, 48542, 48508, 48474, 48440, 48406, 48372, 48338, 48304, 48271, 48237, 48202, 48168, 48134, 48100, 48066, 48032, 47998, 47963, 47929, 47895, 47860, 47826, 47792, 47757, 47723, 47688, 47654, 47619, 47585, 47550, 47516, 47481, 47446, 47412, 47377, 47342, 47308, 47273, 47238, 47203, 47168, 47133, 47098, 47063, 47028, 46993, 46958, 46923, 46888, 46853, 46818, 46783, 46747, 46712, 46677, 46642, 46606, 46571, 46536, 46500, 46465, 46429, 46394, 46358, 46323, 46287, 46252, 46216, 46180, 46145, 46109, 46073, 46037, 46002, 45966, 45930, 45894, 45858, 45822, 45786, 45750, 45714, 45678, 45642, 45606, 45570, 45534, 45498, 45462, 45425, 45389, 45353, 45316, 45280, 45244, 45207, 45171, 45135, 45098, 45062, 45025, 44989, 44952, 44915, 44879, 44842, 44806, 44769, 44732, 44695, 44659, 44622, 44585, 44548, 44511, 44474, 44437, 44400, 44363, 44326, 44289, 44252, 44215, 44178, 44141, 44104, 44067, 44029, 43992, 43955, 43918, 43880, 43843, 43806, 43768, 43731, 43693, 43656, 43618, 43581, 43543, 43506, 43468, 43430, 43393, 43355, 43317, 43280, 43242, 43204, 43166, 43128, 43091, 43053, 43015, 42977, 42939, 42901, 42863, 42825, 42787, 42749, 42711, 42672, 42634, 42596, 42558, 42520, 42481, 42443, 42405, 42366, 42328, 42290, 42251, 42213, 42174, 42136, 42097, 42059, 42020, 41982, 41943, 41904, 41866, 41827, 41788, 41750, 41711, 41672, 41633, 41595, 41556, 41517, 41478, 41439, 41400, 41361, 41322, 41283, 41244, 41205, 41166, 41127, 41088, 41048, 41009, 40970, 40931, 40891, 40852, 40813, 40773, 40734, 40695, 40655, 40616, 40576, 40537, 40497, 40458, 40418, 40379, 40339, 40300, 40260, 40220, 40180, 40141, 40101, 40061, 40021, 39982, 39942, 39902, 39862, 39822, 39782, 39742, 39702, 39662, 39622, 39582, 39542, 39502, 39462, 39422, 39382, 39341, 39301, 39261, 39221, 39180, 39140, 39100, 39059, 39019, 38979, 38938, 38898, 38857, 38817, 38776, 38736, 38695, 38655, 38614, 38573, 38533, 38492, 38451, 38411, 38370, 38329, 38288, 38248, 38207, 38166, 38125, 38084, 38043, 38002, 37961, 37920, 37879, 37838, 37797, 37756, 37715, 37674, 37633, 37592, 37551, 37509, 37468, 37427, 37386, 37344, 37303, 37262, 37220, 37179, 37137, 37096, 37055, 37013, 36972, 36930, 36889, 36847, 36805, 36764, 36722, 36681, 36639, 36597, 36556, 36514, 36472, 36430, 36388, 36347, 36305, 36263, 36221, 36179, 36137, 36095, 36053, 36011, 35969, 35927, 35885, 35843, 35801, 35759, 35717, 35675, 35633, 35590, 35548, 35506, 35464, 35421, 35379, 35337, 35294, 35252, 35210, 35167, 35125, 35082, 35040, 34997, 34955, 34912, 34870, 34827, 34785, 34742, 34699, 34657, 34614, 34571, 34529, 34486, 34443, 34400, 34358, 34315, 34272, 34229, 34186, 34143, 34100, 34057, 34015, 33972, 33929, 33886, 33843, 33799, 33756, 33713, 33670, 33627, 33584, 33541, 33498, 33454, 33411, 33368, 33325, 33281, 33238, 33195, 33151, 33108, 33065, 33021, 32978, 32934, 32891, 32847, 32804, 32760, 32717, 32673, 32630, 32586, 32542, 32499, 32455, 32411, 32368, 32324, 32280, 32236, 32193, 32149, 32105, 32061, 32017, 31974, 31930, 31886, 31842, 31798, 31754, 31710, 31666, 31622, 31578, 31534, 31490, 31446, 31402, 31357, 31313, 31269, 31225, 31181, 31136, 31092, 31048, 31004, 30959, 30915, 30871, 30826, 30782, 30738, 30693, 30649, 30604, 30560, 30515, 30471, 30426, 30382, 30337, 30293, 30248, 30204, 30159, 30114, 30070, 30025, 29980, 29936, 29891, 29846, 29801, 29757, 29712, 29667, 29622, 29577, 29533, 29488, 29443, 29398, 29353, 29308, 29263, 29218, 29173, 29128, 29083, 29038, 28993, 28948, 28903, 28858, 28812, 28767, 28722, 28677, 28632, 28586, 28541, 28496, 28451, 28405, 28360, 28315, 28269, 28224, 28179, 28133, 28088, 28042, 27997, 27952, 27906, 27861, 27815, 27770, 27724, 27678, 27633, 27587, 27542, 27496, 27450, 27405, 27359, 27313, 27268, 27222, 27176, 27131, 27085, 27039, 26993, 26947, 26902, 26856, 26810, 26764, 26718, 26672, 26626, 26580, 26534, 26488, 26442, 26396, 26350, 26304, 26258, 26212, 26166, 26120, 26074, 26028, 25982, 25936, 25889, 25843, 25797, 25751, 25705, 25658, 25612, 25566, 25520, 25473, 25427, 25381, 25334, 25288, 25241, 25195, 25149, 25102, 25056, 25009, 24963, 24916, 24870, 24823, 24777, 24730, 24684, 24637, 24591, 24544, 24497, 24451, 24404, 24357, 24311, 24264, 24217, 24171, 24124, 24077, 24030, 23984, 23937, 23890, 23843, 23796, 23750, 23703, 23656, 23609, 23562, 23515, 23468, 23421, 23374, 23327, 23280, 23233, 23186, 23139, 23092, 23045, 22998, 22951, 22904, 22857, 22810, 22763, 22716, 22668, 22621, 22574, 22527, 22480, 22433, 22385, 22338, 22291, 22243, 22196, 22149, 22102, 22054, 22007, 21960, 21912, 21865, 21817, 21770, 21723, 21675, 21628, 21580, 21533, 21485, 21438, 21390, 21343, 21295, 21248, 21200, 21153, 21105, 21057, 21010, 20962, 20915, 20867, 20819, 20772, 20724, 20676, 20629, 20581, 20533, 20485, 20438, 20390, 20342, 20294, 20246, 20199, 20151, 20103, 20055, 20007, 19959, 19912, 19864, 19816, 19768, 19720, 19672, 19624, 19576, 19528, 19480, 19432, 19384, 19336, 19288, 19240, 19192, 19144, 19096, 19048, 19000, 18951, 18903, 18855, 18807, 18759, 18711, 18663, 18614, 18566, 18518, 18470, 18421, 18373, 18325, 18277, 18228, 18180, 18132, 18084, 18035, 17987, 17939, 17890, 17842, 17793, 17745, 17697, 17648, 17600, 17551, 17503, 17455, 17406, 17358, 17309, 17261, 17212, 17164, 17115, 17067, 17018, 16970, 16921, 16872, 16824, 16775, 16727, 16678, 16629, 16581, 16532, 16484, 16435, 16386, 16338, 16289, 16240, 16191, 16143, 16094, 16045, 15997, 15948, 15899, 15850, 15802, 15753, 15704, 15655, 15606, 15557, 15509, 15460, 15411, 15362, 15313, 15264, 15215, 15167, 15118, 15069, 15020, 14971, 14922, 14873, 14824, 14775, 14726, 14677, 14628, 14579, 14530, 14481, 14432, 14383, 14334, 14285, 14236, 14187, 14138, 14089, 14040, 13990, 13941, 13892, 13843, 13794, 13745, 13696, 13646, 13597, 13548, 13499, 13450, 13401, 13351, 13302, 13253, 13204, 13154, 13105, 13056, 13007, 12957, 12908, 12859, 12810, 12760, 12711, 12662, 12612, 12563, 12514, 12464, 12415, 12366, 12316, 12267, 12218, 12168, 12119, 12069, 12020, 11970, 11921, 11872, 11822, 11773, 11723, 11674, 11624, 11575, 11525, 11476, 11426, 11377, 11327, 11278, 11228, 11179, 11129, 11080, 11030, 10981, 10931, 10882, 10832, 10782, 10733, 10683, 10634, 10584, 10534, 10485, 10435, 10386, 10336, 10286, 10237, 10187, 10137, 10088, 10038, 9988, 9939, 9889, 9839, 9790, 9740, 9690, 9640, 9591, 9541, 9491, 9442, 9392, 9342, 9292, 9243, 9193, 9143, 9093, 9043, 8994, 8944, 8894, 8844, 8794, 8745, 8695, 8645, 8595, 8545, 8496, 8446, 8396, 8346, 8296, 8246, 8196, 8147, 8097, 8047, 7997, 7947, 7897, 7847, 7797, 7747, 7697, 7648, 7598, 7548, 7498, 7448, 7398, 7348, 7298, 7248, 7198, 7148, 7098, 7048, 6998, 6948, 6898, 6848, 6798, 6748, 6698, 6648, 6598, 6548, 6498, 6448, 6398, 6348, 6298, 6248, 6198, 6148, 6098, 6048, 5998, 5948, 5898, 5848, 5798, 5748, 5697, 5647, 5597, 5547, 5497, 5447, 5397, 5347, 5297, 5247, 5197, 5146, 5096, 5046, 4996, 4946, 4896, 4846, 4796, 4745, 4695, 4645, 4595, 4545, 4495, 4445, 4394, 4344, 4294, 4244, 4194, 4144, 4093, 4043, 3993, 3943, 3893, 3843, 3792, 3742, 3692, 3642, 3592, 3541, 3491, 3441, 3391, 3341, 3291, 3240, 3190, 3140, 3090, 3039, 2989, 2939, 2889, 2839, 2788, 2738, 2688, 2638, 2587, 2537, 2487, 2437, 2387, 2336, 2286, 2236, 2186, 2135, 2085, 2035, 1985, 1934, 1884, 1834, 1784, 1733, 1683, 1633, 1583, 1532, 1482, 1432, 1382, 1331, 1281, 1231, 1181, 1130, 1080, 1030, 980, 929, 879, 829, 779, 728, 678, 628, 578, 527, 477, 427, 376, 326, 276, 226, 175, 125, 75, 25, -25, -75, -125, -175, -226, -276, -326, -376, -427, -477, -527, -578, -628, -678, -728, -779, -829, -879, -929, -980, -1030, -1080, -1130, -1181, -1231, -1281, -1331, -1382, -1432, -1482, -1532, -1583, -1633, -1683, -1733, -1784, -1834, -1884, -1934, -1985, -2035, -2085, -2135, -2186, -2236, -2286, -2336, -2387, -2437, -2487, -2537, -2588, -2638, -2688, -2738, -2788, -2839, -2889, -2939, -2989, -3039, -3090, -3140, -3190, -3240, -3291, -3341, -3391, -3441, -3491, -3541, -3592, -3642, -3692, -3742, -3792, -3843, -3893, -3943, -3993, -4043, -4093, -4144, -4194, -4244, -4294, -4344, -4394, -4445, -4495, -4545, -4595, -4645, -4695, -4745, -4796, -4846, -4896, -4946, -4996, -5046, -5096, -5146, -5197, -5247, -5297, -5347, -5397, -5447, -5497, -5547, -5597, -5647, -5697, -5748, -5798, -5848, -5898, -5948, -5998, -6048, -6098, -6148, -6198, -6248, -6298, -6348, -6398, -6448, -6498, -6548, -6598, -6648, -6698, -6748, -6798, -6848, -6898, -6948, -6998, -7048, -7098, -7148, -7198, -7248, -7298, -7348, -7398, -7448, -7498, -7548, -7598, -7648, -7697, -7747, -7797, -7847, -7897, -7947, -7997, -8047, -8097, -8147, -8196, -8246, -8296, -8346, -8396, -8446, -8496, -8545, -8595, -8645, -8695, -8745, -8794, -8844, -8894, -8944, -8994, -9043, -9093, -9143, -9193, -9243, -9292, -9342, -9392, -9442, -9491, -9541, -9591, -9640, -9690, -9740, -9790, -9839, -9889, -9939, -9988, -10038, -10088, -10137, -10187, -10237, -10286, -10336, -10386, -10435, -10485, -10534, -10584, -10634, -10683, -10733, -10782, -10832, -10882, -10931, -10981, -11030, -11080, -11129, -11179, -11228, -11278, -11327, -11377, -11426, -11476, -11525, -11575, -11624, -11674, -11723, -11773, -11822, -11872, -11921, -11970, -12020, -12069, -12119, -12168, -12218, -12267, -12316, -12366, -12415, -12464, -12514, -12563, -12612, -12662, -12711, -12760, -12810, -12859, -12908, -12957, -13007, -13056, -13105, -13154, -13204, -13253, -13302, -13351, -13401, -13450, -13499, -13548, -13597, -13647, -13696, -13745, -13794, -13843, -13892, -13941, -13990, -14040, -14089, -14138, -14187, -14236, -14285, -14334, -14383, -14432, -14481, -14530, -14579, -14628, -14677, -14726, -14775, -14824, -14873, -14922, -14971, -15020, -15069, -15118, -15167, -15215, -15264, -15313, -15362, -15411, -15460, -15509, -15557, -15606, -15655, -15704, -15753, -15802, -15850, -15899, -15948, -15997, -16045, -16094, -16143, -16191, -16240, -16289, -16338, -16386, -16435, -16484, -16532, -16581, -16629, -16678, -16727, -16775, -16824, -16872, -16921, -16970, -17018, -17067, -17115, -17164, -17212, -17261, -17309, -17358, -17406, -17455, -17503, -17551, -17600, -17648, -17697, -17745, -17793, -17842, -17890, -17939, -17987, -18035, -18084, -18132, -18180, -18228, -18277, -18325, -18373, -18421, -18470, -18518, -18566, -18614, -18663, -18711, -18759, -18807, -18855, -18903, -18951, -19000, -19048, -19096, -19144, -19192, -19240, -19288, -19336, -19384, -19432, -19480, -19528, -19576, -19624, -19672, -19720, -19768, -19816, -19864, -19912, -19959, -20007, -20055, -20103, -20151, -20199, -20246, -20294, -20342, -20390, -20438, -20485, -20533, -20581, -20629, -20676, -20724, -20772, -20819, -20867, -20915, -20962, -21010, -21057, -21105, -21153, -21200, -21248, -21295, -21343, -21390, -21438, -21485, -21533, -21580, -21628, -21675, -21723, -21770, -21817, -21865, -21912, -21960, -22007, -22054, -22102, -22149, -22196, -22243, -22291, -22338, -22385, -22433, -22480, -22527, -22574, -22621, -22668, -22716, -22763, -22810, -22857, -22904, -22951, -22998, -23045, -23092, -23139, -23186, -23233, -23280, -23327, -23374, -23421, -23468, -23515, -23562, -23609, -23656, -23703, -23750, -23796, -23843, -23890, -23937, -23984, -24030, -24077, -24124, -24171, -24217, -24264, -24311, -24357, -24404, -24451, -24497, -24544, -24591, -24637, -24684, -24730, -24777, -24823, -24870, -24916, -24963, -25009, -25056, -25102, -25149, -25195, -25241, -25288, -25334, -25381, -25427, -25473, -25520, -25566, -25612, -25658, -25705, -25751, -25797, -25843, -25889, -25936, -25982, -26028, -26074, -26120, -26166, -26212, -26258, -26304, -26350, -26396, -26442, -26488, -26534, -26580, -26626, -26672, -26718, -26764, -26810, -26856, -26902, -26947, -26993, -27039, -27085, -27131, -27176, -27222, -27268, -27313, -27359, -27405, -27450, -27496, -27542, -27587, -27633, -27678, -27724, -27770, -27815, -27861, -27906, -27952, -27997, -28042, -28088, -28133, -28179, -28224, -28269, -28315, -28360, -28405, -28451, -28496, -28541, -28586, -28632, -28677, -28722, -28767, -28812, -28858, -28903, -28948, -28993, -29038, -29083, -29128, -29173, -29218, -29263, -29308, -29353, -29398, -29443, -29488, -29533, -29577, -29622, -29667, -29712, -29757, -29801, -29846, -29891, -29936, -29980, -30025, -30070, -30114, -30159, -30204, -30248, -30293, -30337, -30382, -30426, -30471, -30515, -30560, -30604, -30649, -30693, -30738, -30782, -30826, -30871, -30915, -30959, -31004, -31048, -31092, -31136, -31181, -31225, -31269, -31313, -31357, -31402, -31446, -31490, -31534, -31578, -31622, -31666, -31710, -31754, -31798, -31842, -31886, -31930, -31974, -32017, -32061, -32105, -32149, -32193, -32236, -32280, -32324, -32368, -32411, -32455, -32499, -32542, -32586, -32630, -32673, -32717, -32760, -32804, -32847, -32891, -32934, -32978, -33021, -33065, -33108, -33151, -33195, -33238, -33281, -33325, -33368, -33411, -33454, -33498, -33541, -33584, -33627, -33670, -33713, -33756, -33799, -33843, -33886, -33929, -33972, -34015, -34057, -34100, -34143, -34186, -34229, -34272, -34315, -34358, -34400, -34443, -34486, -34529, -34571, -34614, -34657, -34699, -34742, -34785, -34827, -34870, -34912, -34955, -34997, -35040, -35082, -35125, -35167, -35210, -35252, -35294, -35337, -35379, -35421, -35464, -35506, -35548, -35590, -35633, -35675, -35717, -35759, -35801, -35843, -35885, -35927, -35969, -36011, -36053, -36095, -36137, -36179, -36221, -36263, -36305, -36347, -36388, -36430, -36472, -36514, -36555, -36597, -36639, -36681, -36722, -36764, -36805, -36847, -36889, -36930, -36972, -37013, -37055, -37096, -37137, -37179, -37220, -37262, -37303, -37344, -37386, -37427, -37468, -37509, -37551, -37592, -37633, -37674, -37715, -37756, -37797, -37838, -37879, -37920, -37961, -38002, -38043, -38084, -38125, -38166, -38207, -38248, -38288, -38329, -38370, -38411, -38451, -38492, -38533, -38573, -38614, -38655, -38695, -38736, -38776, -38817, -38857, -38898, -38938, -38979, -39019, -39059, -39100, -39140, -39180, -39221, -39261, -39301, -39341, -39382, -39422, -39462, -39502, -39542, -39582, -39622, -39662, -39702, -39742, -39782, -39822, -39862, -39902, -39942, -39982, -40021, -40061, -40101, -40141, -40180, -40220, -40260, -40299, -40339, -40379, -40418, -40458, -40497, -40537, -40576, -40616, -40655, -40695, -40734, -40773, -40813, -40852, -40891, -40931, -40970, -41009, -41048, -41087, -41127, -41166, -41205, -41244, -41283, -41322, -41361, -41400, -41439, -41478, -41517, -41556, -41595, -41633, -41672, -41711, -41750, -41788, -41827, -41866, -41904, -41943, -41982, -42020, -42059, -42097, -42136, -42174, -42213, -42251, -42290, -42328, -42366, -42405, -42443, -42481, -42520, -42558, -42596, -42634, -42672, -42711, -42749, -42787, -42825, -42863, -42901, -42939, -42977, -43015, -43053, -43091, -43128, -43166, -43204, -43242, -43280, -43317, -43355, -43393, -43430, -43468, -43506, -43543, -43581, -43618, -43656, -43693, -43731, -43768, -43806, -43843, -43880, -43918, -43955, -43992, -44029, -44067, -44104, -44141, -44178, -44215, -44252, -44289, -44326, -44363, -44400, -44437, -44474, -44511, -44548, -44585, -44622, -44659, -44695, -44732, -44769, -44806, -44842, -44879, -44915, -44952, -44989, -45025, -45062, -45098, -45135, -45171, -45207, -45244, -45280, -45316, -45353, -45389, -45425, -45462, -45498, -45534, -45570, -45606, -45642, -45678, -45714, -45750, -45786, -45822, -45858, -45894, -45930, -45966, -46002, -46037, -46073, -46109, -46145, -46180, -46216, -46252, -46287, -46323, -46358, -46394, -46429, -46465, -46500, -46536, -46571, -46606, -46642, -46677, -46712, -46747, -46783, -46818, -46853, -46888, -46923, -46958, -46993, -47028, -47063, -47098, -47133, -47168, -47203, -47238, -47273, -47308, -47342, -47377, -47412, -47446, -47481, -47516, -47550, -47585, -47619, -47654, -47688, -47723, -47757, -47792, -47826, -47860, -47895, -47929, -47963, -47998, -48032, -48066, -48100, -48134, -48168, -48202, -48236, -48271, -48304, -48338, -48372, -48406, -48440, -48474, -48508, -48542, -48575, -48609, -48643, -48676, -48710, -48744, -48777, -48811, -48844, -48878, -48911, -48945, -48978, -49012, -49045, -49078, -49112, -49145, -49178, -49211, -49244, -49278, -49311, -49344, -49377, -49410, -49443, -49476, -49509, -49542, -49575, -49608, -49640, -49673, -49706, -49739, -49771, -49804, -49837, -49869, -49902, -49935, -49967, -50000, -50032, -50065, -50097, -50129, -50162, -50194, -50226, -50259, -50291, -50323, -50355, -50387, -50420, -50452, -50484, -50516, -50548, -50580, -50612, -50644, -50675, -50707, -50739, -50771, -50803, -50834, -50866, -50898, -50929, -50961, -50993, -51024, -51056, -51087, -51119, -51150, -51182, -51213, -51244, -51276, -51307, -51338, -51369, -51401, -51432, -51463, -51494, -51525, -51556, -51587, -51618, -51649, -51680, -51711, -51742, -51773, -51803, -51834, -51865, -51896, -51926, -51957, -51988, -52018, -52049, -52079, -52110, -52140, -52171, -52201, -52231, -52262, -52292, -52322, -52353, -52383, -52413, -52443, -52473, -52503, -52534, -52564, -52594, -52624, -52653, -52683, -52713, -52743, -52773, -52803, -52832, -52862, -52892, -52922, -52951, -52981, -53010, -53040, -53069, -53099, -53128, -53158, -53187, -53216, -53246, -53275, -53304, -53334, -53363, -53392, -53421, -53450, -53479, -53508, -53537, -53566, -53595, -53624, -53653, -53682, -53711, -53739, -53768, -53797, -53826, -53854, -53883, -53911, -53940, -53969, -53997, -54026, -54054, -54082, -54111, -54139, -54167, -54196, -54224, -54252, -54280, -54308, -54337, -54365, -54393, -54421, -54449, -54477, -54505, -54533, -54560, -54588, -54616, -54644, -54672, -54699, -54727, -54755, -54782, -54810, -54837, -54865, -54892, -54920, -54947, -54974, -55002, -55029, -55056, -55084, -55111, -55138, -55165, -55192, -55219, -55246, -55274, -55300, -55327, -55354, -55381, -55408, -55435, -55462, -55489, -55515, -55542, -55569, -55595, -55622, -55648, -55675, -55701, -55728, -55754, -55781, -55807, -55833, -55860, -55886, -55912, -55938, -55965, -55991, -56017, -56043, -56069, -56095, -56121, -56147, -56173, -56199, -56225, -56250, -56276, -56302, -56328, -56353, -56379, -56404, -56430, -56456, -56481, -56507, -56532, -56557, -56583, -56608, -56633, -56659, -56684, -56709, -56734, -56760, -56785, -56810, -56835, -56860, -56885, -56910, -56935, -56959, -56984, -57009, -57034, -57059, -57083, -57108, -57133, -57157, -57182, -57206, -57231, -57255, -57280, -57304, -57329, -57353, -57377, -57402, -57426, -57450, -57474, -57498, -57522, -57546, -57570, -57594, -57618, -57642, -57666, -57690, -57714, -57738, -57762, -57785, -57809, -57833, -57856, -57880, -57903, -57927, -57950, -57974, -57997, -58021, -58044, -58067, -58091, -58114, -58137, -58160, -58183, -58207, -58230, -58253, -58276, -58299, -58322, -58345, -58367, -58390, -58413, -58436, -58459, -58481, -58504, -58527, -58549, -58572, -58594, -58617, -58639, -58662, -58684, -58706, -58729, -58751, -58773, -58795, -58818, -58840, -58862, -58884, -58906, -58928, -58950, -58972, -58994, -59016, -59038, -59059, -59081, -59103, -59125, -59146, -59168, -59190, -59211, -59233, -59254, -59276, -59297, -59318, -59340, -59361, -59382, -59404, -59425, -59446, -59467, -59488, -59509, -59530, -59551, -59572, -59593, -59614, -59635, -59656, -59677, -59697, -59718, -59739, -59759, -59780, -59801, -59821, -59842, -59862, -59883, -59903, -59923, -59944, -59964, -59984, -60004, -60025, -60045, -60065, -60085, -60105, -60125, -60145, -60165, -60185, -60205, -60225, -60244, -60264, -60284, -60304, -60323, -60343, -60363, -60382, -60402, -60421, -60441, -60460, -60479, -60499, -60518, -60537, -60556, -60576, -60595, -60614, -60633, -60652, -60671, -60690, -60709, -60728, -60747, -60766, -60785, -60803, -60822, -60841, -60859, -60878, -60897, -60915, -60934, -60952, -60971, -60989, -61007, -61026, -61044, -61062, -61081, -61099, -61117, -61135, -61153, -61171, -61189, -61207, -61225, -61243, -61261, -61279, -61297, -61314, -61332, -61350, -61367, -61385, -61403, -61420, -61438, -61455, -61473, -61490, -61507, -61525, -61542, -61559, -61577, -61594, -61611, -61628, -61645, -61662, -61679, -61696, -61713, -61730, -61747, -61764, -61780, -61797, -61814, -61831, -61847, -61864, -61880, -61897, -61913, -61930, -61946, -61963, -61979, -61995, -62012, -62028, -62044, -62060, -62076, -62092, -62108, -62125, -62141, -62156, -62172, -62188, -62204, -62220, -62236, -62251, -62267, -62283, -62298, -62314, -62329, -62345, -62360, -62376, -62391, -62407, -62422, -62437, -62453, -62468, -62483, -62498, -62513, -62528, -62543, -62558, -62573, -62588, -62603, -62618, -62633, -62648, -62662, -62677, -62692, -62706, -62721, -62735, -62750, -62764, -62779, -62793, -62808, -62822, -62836, -62850, -62865, -62879, -62893, -62907, -62921, -62935, -62949, -62963, -62977, -62991, -63005, -63019, -63032, -63046, -63060, -63074, -63087, -63101, -63114, -63128, -63141, -63155, -63168, -63182, -63195, -63208, -63221, -63235, -63248, -63261, -63274, -63287, -63300, -63313, -63326, -63339, -63352, -63365, -63378, -63390, -63403, -63416, -63429, -63441, -63454, -63466, -63479, -63491, -63504, -63516, -63528, -63541, -63553, -63565, -63578, -63590, -63602, -63614, -63626, -63638, -63650, -63662, -63674, -63686, -63698, -63709, -63721, -63733, -63745, -63756, -63768, -63779, -63791, -63803, -63814, -63825, -63837, -63848, -63859, -63871, -63882, -63893, -63904, -63915, -63927, -63938, -63949, -63960, -63971, -63981, -63992, -64003, -64014, -64025, -64035, -64046, -64057, -64067, -64078, -64088, -64099, -64109, -64120, -64130, -64140, -64151, -64161, -64171, -64181, -64192, -64202, -64212, -64222, -64232, -64242, -64252, -64261, -64271, -64281, -64291, -64301, -64310, -64320, -64330, -64339, -64349, -64358, -64368, -64377, -64387, -64396, -64405, -64414, -64424, -64433, -64442, -64451, -64460, -64469, -64478, -64487, -64496, -64505, -64514, -64523, -64532, -64540, -64549, -64558, -64566, -64575, -64584, -64592, -64601, -64609, -64617, -64626, -64634, -64642, -64651, -64659, -64667, -64675, -64683, -64691, -64699, -64707, -64715, -64723, -64731, -64739, -64747, -64754, -64762, -64770, -64777, -64785, -64793, -64800, -64808, -64815, -64822, -64830, -64837, -64844, -64852, -64859, -64866, -64873, -64880, -64887, -64895, -64902, -64908, -64915, -64922, -64929, -64936, -64943, -64949, -64956, -64963, -64969, -64976, -64982, -64989, -64995, -65002, -65008, -65015, -65021, -65027, -65033, -65040, -65046, -65052, -65058, -65064, -65070, -65076, -65082, -65088, -65094, -65099, -65105, -65111, -65117, -65122, -65128, -65133, -65139, -65144, -65150, -65155, -65161, -65166, -65171, -65177, -65182, -65187, -65192, -65197, -65202, -65207, -65212, -65217, -65222, -65227, -65232, -65237, -65242, -65246, -65251, -65256, -65260, -65265, -65270, -65274, -65279, -65283, -65287, -65292, -65296, -65300, -65305, -65309, -65313, -65317, -65321, -65325, -65329, -65333, -65337, -65341, -65345, -65349, -65352, -65356, -65360, -65363, -65367, -65371, -65374, -65378, -65381, -65385, -65388, -65391, -65395, -65398, -65401, -65404, -65408, -65411, -65414, -65417, -65420, -65423, -65426, -65429, -65431, -65434, -65437, -65440, -65442, -65445, -65448, -65450, -65453, -65455, -65458, -65460, -65463, -65465, -65467, -65470, -65472, -65474, -65476, -65478, -65480, -65482, -65484, -65486, -65488, -65490, -65492, -65494, -65496, -65497, -65499, -65501, -65502, -65504, -65505, -65507, -65508, -65510, -65511, -65513, -65514, -65515, -65516, -65518, -65519, -65520, -65521, -65522, -65523, -65524, -65525, -65526, -65527, -65527, -65528, -65529, -65530, -65530, -65531, -65531, -65532, -65532, -65533, -65533, -65534, -65534, -65534, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65535, -65534, -65534, -65534, -65533, -65533, -65532, -65532, -65531, -65531, -65530, -65530, -65529, -65528, -65527, -65527, -65526, -65525, -65524, -65523, -65522, -65521, -65520, -65519, -65518, -65516, -65515, -65514, -65513, -65511, -65510, -65508, -65507, -65505, -65504, -65502, -65501, -65499, -65497, -65496, -65494, -65492, -65490, -65488, -65486, -65484, -65482, -65480, -65478, -65476, -65474, -65472, -65470, -65467, -65465, -65463, -65460, -65458, -65455, -65453, -65450, -65448, -65445, -65442, -65440, -65437, -65434, -65431, -65429, -65426, -65423, -65420, -65417, -65414, -65411, -65408, -65404, -65401, -65398, -65395, -65391, -65388, -65385, -65381, -65378, -65374, -65371, -65367, -65363, -65360, -65356, -65352, -65349, -65345, -65341, -65337, -65333, -65329, -65325, -65321, -65317, -65313, -65309, -65305, -65300, -65296, -65292, -65287, -65283, -65279, -65274, -65270, -65265, -65260, -65256, -65251, -65246, -65242, -65237, -65232, -65227, -65222, -65217, -65212, -65207, -65202, -65197, -65192, -65187, -65182, -65177, -65171, -65166, -65161, -65155, -65150, -65144, -65139, -65133, -65128, -65122, -65117, -65111, -65105, -65099, -65094, -65088, -65082, -65076, -65070, -65064, -65058, -65052, -65046, -65040, -65033, -65027, -65021, -65015, -65008, -65002, -64995, -64989, -64982, -64976, -64969, -64963, -64956, -64949, -64943, -64936, -64929, -64922, -64915, -64908, -64902, -64895, -64887, -64880, -64873, -64866, -64859, -64852, -64844, -64837, -64830, -64822, -64815, -64808, -64800, -64793, -64785, -64777, -64770, -64762, -64754, -64747, -64739, -64731, -64723, -64715, -64707, -64699, -64691, -64683, -64675, -64667, -64659, -64651, -64642, -64634, -64626, -64617, -64609, -64601, -64592, -64584, -64575, -64566, -64558, -64549, -64540, -64532, -64523, -64514, -64505, -64496, -64487, -64478, -64469, -64460, -64451, -64442, -64433, -64424, -64414, -64405, -64396, -64387, -64377, -64368, -64358, -64349, -64339, -64330, -64320, -64310, -64301, -64291, -64281, -64271, -64261, -64252, -64242, -64232, -64222, -64212, -64202, -64192, -64181, -64171, -64161, -64151, -64140, -64130, -64120, -64109, -64099, -64088, -64078, -64067, -64057, -64046, -64035, -64025, -64014, -64003, -63992, -63981, -63971, -63960, -63949, -63938, -63927, -63915, -63904, -63893, -63882, -63871, -63859, -63848, -63837, -63825, -63814, -63803, -63791, -63779, -63768, -63756, -63745, -63733, -63721, -63709, -63698, -63686, -63674, -63662, -63650, -63638, -63626, -63614, -63602, -63590, -63578, -63565, -63553, -63541, -63528, -63516, -63504, -63491, -63479, -63466, -63454, -63441, -63429, -63416, -63403, -63390, -63378, -63365, -63352, -63339, -63326, -63313, -63300, -63287, -63274, -63261, -63248, -63235, -63221, -63208, -63195, -63182, -63168, -63155, -63141, -63128, -63114, -63101, -63087, -63074, -63060, -63046, -63032, -63019, -63005, -62991, -62977, -62963, -62949, -62935, -62921, -62907, -62893, -62879, -62865, -62850, -62836, -62822, -62808, -62793, -62779, -62764, -62750, -62735, -62721, -62706, -62692, -62677, -62662, -62648, -62633, -62618, -62603, -62588, -62573, -62558, -62543, -62528, -62513, -62498, -62483, -62468, -62453, -62437, -62422, -62407, -62391, -62376, -62360, -62345, -62329, -62314, -62298, -62283, -62267, -62251, -62236, -62220, -62204, -62188, -62172, -62156, -62141, -62125, -62108, -62092, -62076, -62060, -62044, -62028, -62012, -61995, -61979, -61963, -61946, -61930, -61913, -61897, -61880, -61864, -61847, -61831, -61814, -61797, -61780, -61764, -61747, -61730, -61713, -61696, -61679, -61662, -61645, -61628, -61611, -61594, -61577, -61559, -61542, -61525, -61507, -61490, -61473, -61455, -61438, -61420, -61403, -61385, -61367, -61350, -61332, -61314, -61297, -61279, -61261, -61243, -61225, -61207, -61189, -61171, -61153, -61135, -61117, -61099, -61081, -61062, -61044, -61026, -61007, -60989, -60971, -60952, -60934, -60915, -60897, -60878, -60859, -60841, -60822, -60803, -60785, -60766, -60747, -60728, -60709, -60690, -60671, -60652, -60633, -60614, -60595, -60576, -60556, -60537, -60518, -60499, -60479, -60460, -60441, -60421, -60402, -60382, -60363, -60343, -60323, -60304, -60284, -60264, -60244, -60225, -60205, -60185, -60165, -60145, -60125, -60105, -60085, -60065, -60045, -60025, -60004, -59984, -59964, -59944, -59923, -59903, -59883, -59862, -59842, -59821, -59801, -59780, -59759, -59739, -59718, -59697, -59677, -59656, -59635, -59614, -59593, -59572, -59551, -59530, -59509, -59488, -59467, -59446, -59425, -59404, -59382, -59361, -59340, -59318, -59297, -59276, -59254, -59233, -59211, -59189, -59168, -59146, -59125, -59103, -59081, -59059, -59038, -59016, -58994, -58972, -58950, -58928, -58906, -58884, -58862, -58840, -58818, -58795, -58773, -58751, -58729, -58706, -58684, -58662, -58639, -58617, -58594, -58572, -58549, -58527, -58504, -58481, -58459, -58436, -58413, -58390, -58367, -58345, -58322, -58299, -58276, -58253, -58230, -58207, -58183, -58160, -58137, -58114, -58091, -58067, -58044, -58021, -57997, -57974, -57950, -57927, -57903, -57880, -57856, -57833, -57809, -57785, -57762, -57738, -57714, -57690, -57666, -57642, -57618, -57594, -57570, -57546, -57522, -57498, -57474, -57450, -57426, -57402, -57377, -57353, -57329, -57304, -57280, -57255, -57231, -57206, -57182, -57157, -57133, -57108, -57083, -57059, -57034, -57009, -56984, -56959, -56935, -56910, -56885, -56860, -56835, -56810, -56785, -56760, -56734, -56709, -56684, -56659, -56633, -56608, -56583, -56557, -56532, -56507, -56481, -56456, -56430, -56404, -56379, -56353, -56328, -56302, -56276, -56250, -56225, -56199, -56173, -56147, -56121, -56095, -56069, -56043, -56017, -55991, -55965, -55938, -55912, -55886, -55860, -55833, -55807, -55781, -55754, -55728, -55701, -55675, -55648, -55622, -55595, -55569, -55542, -55515, -55489, -55462, -55435, -55408, -55381, -55354, -55327, -55300, -55274, -55246, -55219, -55192, -55165, -55138, -55111, -55084, -55056, -55029, -55002, -54974, -54947, -54920, -54892, -54865, -54837, -54810, -54782, -54755, -54727, -54699, -54672, -54644, -54616, -54588, -54560, -54533, -54505, -54477, -54449, -54421, -54393, -54365, -54337, -54308, -54280, -54252, -54224, -54196, -54167, -54139, -54111, -54082, -54054, -54026, -53997, -53969, -53940, -53911, -53883, -53854, -53826, -53797, -53768, -53739, -53711, -53682, -53653, -53624, -53595, -53566, -53537, -53508, -53479, -53450, -53421, -53392, -53363, -53334, -53304, -53275, -53246, -53216, -53187, -53158, -53128, -53099, -53069, -53040, -53010, -52981, -52951, -52922, -52892, -52862, -52832, -52803, -52773, -52743, -52713, -52683, -52653, -52624, -52594, -52564, -52534, -52503, -52473, -52443, -52413, -52383, -52353, -52322, -52292, -52262, -52231, -52201, -52171, -52140, -52110, -52079, -52049, -52018, -51988, -51957, -51926, -51896, -51865, -51834, -51803, -51773, -51742, -51711, -51680, -51649, -51618, -51587, -51556, -51525, -51494, -51463, -51432, -51401, -51369, -51338, -51307, -51276, -51244, -51213, -51182, -51150, -51119, -51087, -51056, -51024, -50993, -50961, -50929, -50898, -50866, -50834, -50803, -50771, -50739, -50707, -50675, -50644, -50612, -50580, -50548, -50516, -50484, -50452, -50420, -50387, -50355, -50323, -50291, -50259, -50226, -50194, -50162, -50129, -50097, -50065, -50032, -50000, -49967, -49935, -49902, -49869, -49837, -49804, -49771, -49739, -49706, -49673, -49640, -49608, -49575, -49542, -49509, -49476, -49443, -49410, -49377, -49344, -49311, -49278, -49244, -49211, -49178, -49145, -49112, -49078, -49045, -49012, -48978, -48945, -48911, -48878, -48844, -48811, -48777, -48744, -48710, -48676, -48643, -48609, -48575, -48542, -48508, -48474, -48440, -48406, -48372, -48338, -48305, -48271, -48237, -48202, -48168, -48134, -48100, -48066, -48032, -47998, -47963, -47929, -47895, -47860, -47826, -47792, -47757, -47723, -47688, -47654, -47619, -47585, -47550, -47516, -47481, -47446, -47412, -47377, -47342, -47307, -47273, -47238, -47203, -47168, -47133, -47098, -47063, -47028, -46993, -46958, -46923, -46888, -46853, -46818, -46783, -46747, -46712, -46677, -46642, -46606, -46571, -46536, -46500, -46465, -46429, -46394, -46358, -46323, -46287, -46251, -46216, -46180, -46145, -46109, -46073, -46037, -46002, -45966, -45930, -45894, -45858, -45822, -45786, -45750, -45714, -45678, -45642, -45606, -45570, -45534, -45498, -45462, -45425, -45389, -45353, -45316, -45280, -45244, -45207, -45171, -45135, -45098, -45062, -45025, -44989, -44952, -44915, -44879, -44842, -44806, -44769, -44732, -44695, -44659, -44622, -44585, -44548, -44511, -44474, -44437, -44400, -44363, -44326, -44289, -44252, -44215, -44178, -44141, -44104, -44067, -44029, -43992, -43955, -43918, -43880, -43843, -43806, -43768, -43731, -43693, -43656, -43618, -43581, -43543, -43506, -43468, -43430, -43393, -43355, -43317, -43280, -43242, -43204, -43166, -43128, -43091, -43053, -43015, -42977, -42939, -42901, -42863, -42825, -42787, -42749, -42711, -42672, -42634, -42596, -42558, -42520, -42481, -42443, -42405, -42366, -42328, -42290, -42251, -42213, -42174, -42136, -42097, -42059, -42020, -41982, -41943, -41904, -41866, -41827, -41788, -41750, -41711, -41672, -41633, -41595, -41556, -41517, -41478, -41439, -41400, -41361, -41322, -41283, -41244, -41205, -41166, -41127, -41087, -41048, -41009, -40970, -40931, -40891, -40852, -40813, -40773, -40734, -40695, -40655, -40616, -40576, -40537, -40497, -40458, -40418, -40379, -40339, -40299, -40260, -40220, -40180, -40141, -40101, -40061, -40021, -39982, -39942, -39902, -39862, -39822, -39782, -39742, -39702, -39662, -39622, -39582, -39542, -39502, -39462, -39422, -39382, -39341, -39301, -39261, -39221, -39180, -39140, -39100, -39059, -39019, -38979, -38938, -38898, -38857, -38817, -38776, -38736, -38695, -38655, -38614, -38573, -38533, -38492, -38451, -38411, -38370, -38329, -38288, -38248, -38207, -38166, -38125, -38084, -38043, -38002, -37961, -37920, -37879, -37838, -37797, -37756, -37715, -37674, -37633, -37592, -37550, -37509, -37468, -37427, -37386, -37344, -37303, -37262, -37220, -37179, -37137, -37096, -37055, -37013, -36972, -36930, -36889, -36847, -36805, -36764, -36722, -36681, -36639, -36597, -36556, -36514, -36472, -36430, -36388, -36347, -36305, -36263, -36221, -36179, -36137, -36095, -36053, -36011, -35969, -35927, -35885, -35843, -35801, -35759, -35717, -35675, -35633, -35590, -35548, -35506, -35464, -35421, -35379, -35337, -35294, -35252, -35210, -35167, -35125, -35082, -35040, -34997, -34955, -34912, -34870, -34827, -34785, -34742, -34699, -34657, -34614, -34571, -34529, -34486, -34443, -34400, -34358, -34315, -34272, -34229, -34186, -34143, -34100, -34057, -34015, -33972, -33929, -33886, -33843, -33799, -33756, -33713, -33670, -33627, -33584, -33541, -33498, -33454, -33411, -33368, -33325, -33281, -33238, -33195, -33151, -33108, -33065, -33021, -32978, -32934, -32891, -32847, -32804, -32760, -32717, -32673, -32630, -32586, -32542, -32499, -32455, -32411, -32368, -32324, -32280, -32236, -32193, -32149, -32105, -32061, -32017, -31974, -31930, -31886, -31842, -31798, -31754, -31710, -31666, -31622, -31578, -31534, -31490, -31446, -31402, -31357, -31313, -31269, -31225, -31181, -31136, -31092, -31048, -31004, -30959, -30915, -30871, -30826, -30782, -30738, -30693, -30649, -30604, -30560, -30515, -30471, -30426, -30382, -30337, -30293, -30248, -30204, -30159, -30114, -30070, -30025, -29980, -29936, -29891, -29846, -29801, -29757, -29712, -29667, -29622, -29577, -29533, -29488, -29443, -29398, -29353, -29308, -29263, -29218, -29173, -29128, -29083, -29038, -28993, -28948, -28903, -28858, -28812, -28767, -28722, -28677, -28632, -28586, -28541, -28496, -28451, -28405, -28360, -28315, -28269, -28224, -28179, -28133, -28088, -28042, -27997, -27952, -27906, -27861, -27815, -27770, -27724, -27678, -27633, -27587, -27542, -27496, -27450, -27405, -27359, -27313, -27268, -27222, -27176, -27131, -27085, -27039, -26993, -26947, -26902, -26856, -26810, -26764, -26718, -26672, -26626, -26580, -26534, -26488, -26442, -26396, -26350, -26304, -26258, -26212, -26166, -26120, -26074, -26028, -25982, -25936, -25889, -25843, -25797, -25751, -25705, -25658, -25612, -25566, -25520, -25473, -25427, -25381, -25334, -25288, -25241, -25195, -25149, -25102, -25056, -25009, -24963, -24916, -24870, -24823, -24777, -24730, -24684, -24637, -24591, -24544, -24497, -24451, -24404, -24357, -24311, -24264, -24217, -24171, -24124, -24077, -24030, -23984, -23937, -23890, -23843, -23796, -23750, -23703, -23656, -23609, -23562, -23515, -23468, -23421, -23374, -23327, -23280, -23233, -23186, -23139, -23092, -23045, -22998, -22951, -22904, -22857, -22810, -22763, -22716, -22668, -22621, -22574, -22527, -22480, -22432, -22385, -22338, -22291, -22243, -22196, -22149, -22102, -22054, -22007, -21960, -21912, -21865, -21817, -21770, -21723, -21675, -21628, -21580, -21533, -21485, -21438, -21390, -21343, -21295, -21248, -21200, -21153, -21105, -21057, -21010, -20962, -20915, -20867, -20819, -20772, -20724, -20676, -20629, -20581, -20533, -20485, -20438, -20390, -20342, -20294, -20246, -20199, -20151, -20103, -20055, -20007, -19959, -19912, -19864, -19816, -19768, -19720, -19672, -19624, -19576, -19528, -19480, -19432, -19384, -19336, -19288, -19240, -19192, -19144, -19096, -19048, -19000, -18951, -18903, -18855, -18807, -18759, -18711, -18663, -18614, -18566, -18518, -18470, -18421, -18373, -18325, -18277, -18228, -18180, -18132, -18084, -18035, -17987, -17939, -17890, -17842, -17793, -17745, -17697, -17648, -17600, -17551, -17503, -17455, -17406, -17358, -17309, -17261, -17212, -17164, -17115, -17067, -17018, -16970, -16921, -16872, -16824, -16775, -16727, -16678, -16629, -16581, -16532, -16484, -16435, -16386, -16338, -16289, -16240, -16191, -16143, -16094, -16045, -15997, -15948, -15899, -15850, -15802, -15753, -15704, -15655, -15606, -15557, -15509, -15460, -15411, -15362, -15313, -15264, -15215, -15167, -15118, -15069, -15020, -14971, -14922, -14873, -14824, -14775, -14726, -14677, -14628, -14579, -14530, -14481, -14432, -14383, -14334, -14285, -14236, -14187, -14138, -14089, -14040, -13990, -13941, -13892, -13843, -13794, -13745, -13696, -13647, -13597, -13548, -13499, -13450, -13401, -13351, -13302, -13253, -13204, -13154, -13105, -13056, -13007, -12957, -12908, -12859, -12810, -12760, -12711, -12662, -12612, -12563, -12514, -12464, -12415, -12366, -12316, -12267, -12217, -12168, -12119, -12069, -12020, -11970, -11921, -11872, -11822, -11773, -11723, -11674, -11624, -11575, -11525, -11476, -11426, -11377, -11327, -11278, -11228, -11179, -11129, -11080, -11030, -10981, -10931, -10882, -10832, -10782, -10733, -10683, -10634, -10584, -10534, -10485, -10435, -10386, -10336, -10286, -10237, -10187, -10137, -10088, -10038, -9988, -9939, -9889, -9839, -9790, -9740, -9690, -9640, -9591, -9541, -9491, -9442, -9392, -9342, -9292, -9243, -9193, -9143, -9093, -9043, -8994, -8944, -8894, -8844, -8794, -8745, -8695, -8645, -8595, -8545, -8496, -8446, -8396, -8346, -8296, -8246, -8196, -8147, -8097, -8047, -7997, -7947, -7897, -7847, -7797, -7747, -7697, -7648, -7598, -7548, -7498, -7448, -7398, -7348, -7298, -7248, -7198, -7148, -7098, -7048, -6998, -6948, -6898, -6848, -6798, -6748, -6698, -6648, -6598, -6548, -6498, -6448, -6398, -6348, -6298, -6248, -6198, -6148, -6098, -6048, -5998, -5948, -5898, -5848, -5798, -5747, -5697, -5647, -5597, -5547, -5497, -5447, -5397, -5347, -5297, -5247, -5197, -5146, -5096, -5046, -4996, -4946, -4896, -4846, -4796, -4745, -4695, -4645, -4595, -4545, -4495, -4445, -4394, -4344, -4294, -4244, -4194, -4144, -4093, -4043, -3993, -3943, -3893, -3843, -3792, -3742, -3692, -3642, -3592, -3541, -3491, -3441, -3391, -3341, -3291, -3240, -3190, -3140, -3090, -3039, -2989, -2939, -2889, -2839, -2788, -2738, -2688, -2638, -2588, -2537, -2487, -2437, -2387, -2336, -2286, -2236, -2186, -2135, -2085, -2035, -1985, -1934, -1884, -1834, -1784, -1733, -1683, -1633, -1583, -1532, -1482, -1432, -1382, -1331, -1281, -1231, -1181, -1130, -1080, -1030, -980, -929, -879, -829, -779, -728, -678, -628, -578, -527, -477, -427, -376, -326, -276, -226, -175, -125, -75, -25, 25, 75, 125, 175, 226, 276, 326, 376, 427, 477, 527, 578, 628, 678, 728, 779, 829, 879, 929, 980, 1030, 1080, 1130, 1181, 1231, 1281, 1331, 1382, 1432, 1482, 1532, 1583, 1633, 1683, 1733, 1784, 1834, 1884, 1934, 1985, 2035, 2085, 2135, 2186, 2236, 2286, 2336, 2387, 2437, 2487, 2537, 2587, 2638, 2688, 2738, 2788, 2839, 2889, 2939, 2989, 3039, 3090, 3140, 3190, 3240, 3291, 3341, 3391, 3441, 3491, 3542, 3592, 3642, 3692, 3742, 3792, 3843, 3893, 3943, 3993, 4043, 4093, 4144, 4194, 4244, 4294, 4344, 4394, 4445, 4495, 4545, 4595, 4645, 4695, 4745, 4796, 4846, 4896, 4946, 4996, 5046, 5096, 5146, 5197, 5247, 5297, 5347, 5397, 5447, 5497, 5547, 5597, 5647, 5697, 5747, 5798, 5848, 5898, 5948, 5998, 6048, 6098, 6148, 6198, 6248, 6298, 6348, 6398, 6448, 6498, 6548, 6598, 6648, 6698, 6748, 6798, 6848, 6898, 6948, 6998, 7048, 7098, 7148, 7198, 7248, 7298, 7348, 7398, 7448, 7498, 7548, 7598, 7648, 7697, 7747, 7797, 7847, 7897, 7947, 7997, 8047, 8097, 8147, 8196, 8246, 8296, 8346, 8396, 8446, 8496, 8545, 8595, 8645, 8695, 8745, 8794, 8844, 8894, 8944, 8994, 9043, 9093, 9143, 9193, 9243, 9292, 9342, 9392, 9442, 9491, 9541, 9591, 9640, 9690, 9740, 9790, 9839, 9889, 9939, 9988, 10038, 10088, 10137, 10187, 10237, 10286, 10336, 10386, 10435, 10485, 10534, 10584, 10634, 10683, 10733, 10782, 10832, 10882, 10931, 10981, 11030, 11080, 11129, 11179, 11228, 11278, 11327, 11377, 11426, 11476, 11525, 11575, 11624, 11674, 11723, 11773, 11822, 11872, 11921, 11970, 12020, 12069, 12119, 12168, 12218, 12267, 12316, 12366, 12415, 12464, 12514, 12563, 12612, 12662, 12711, 12760, 12810, 12859, 12908, 12957, 13007, 13056, 13105, 13154, 13204, 13253, 13302, 13351, 13401, 13450, 13499, 13548, 13597, 13647, 13696, 13745, 13794, 13843, 13892, 13941, 13990, 14040, 14089, 14138, 14187, 14236, 14285, 14334, 14383, 14432, 14481, 14530, 14579, 14628, 14677, 14726, 14775, 14824, 14873, 14922, 14971, 15020, 15069, 15118, 15167, 15215, 15264, 15313, 15362, 15411, 15460, 15509, 15557, 15606, 15655, 15704, 15753, 15802, 15850, 15899, 15948, 15997, 16045, 16094, 16143, 16191, 16240, 16289, 16338, 16386, 16435, 16484, 16532, 16581, 16629, 16678, 16727, 16775, 16824, 16872, 16921, 16970, 17018, 17067, 17115, 17164, 17212, 17261, 17309, 17358, 17406, 17455, 17503, 17551, 17600, 17648, 17697, 17745, 17793, 17842, 17890, 17939, 17987, 18035, 18084, 18132, 18180, 18228, 18277, 18325, 18373, 18421, 18470, 18518, 18566, 18614, 18663, 18711, 18759, 18807, 18855, 18903, 18951, 19000, 19048, 19096, 19144, 19192, 19240, 19288, 19336, 19384, 19432, 19480, 19528, 19576, 19624, 19672, 19720, 19768, 19816, 19864, 19912, 19959, 20007, 20055, 20103, 20151, 20199, 20246, 20294, 20342, 20390, 20438, 20485, 20533, 20581, 20629, 20676, 20724, 20772, 20819, 20867, 20915, 20962, 21010, 21057, 21105, 21153, 21200, 21248, 21295, 21343, 21390, 21438, 21485, 21533, 21580, 21628, 21675, 21723, 21770, 21817, 21865, 21912, 21960, 22007, 22054, 22102, 22149, 22196, 22243, 22291, 22338, 22385, 22432, 22480, 22527, 22574, 22621, 22668, 22716, 22763, 22810, 22857, 22904, 22951, 22998, 23045, 23092, 23139, 23186, 23233, 23280, 23327, 23374, 23421, 23468, 23515, 23562, 23609, 23656, 23703, 23750, 23796, 23843, 23890, 23937, 23984, 24030, 24077, 24124, 24171, 24217, 24264, 24311, 24357, 24404, 24451, 24497, 24544, 24591, 24637, 24684, 24730, 24777, 24823, 24870, 24916, 24963, 25009, 25056, 25102, 25149, 25195, 25241, 25288, 25334, 25381, 25427, 25473, 25520, 25566, 25612, 25658, 25705, 25751, 25797, 25843, 25889, 25936, 25982, 26028, 26074, 26120, 26166, 26212, 26258, 26304, 26350, 26396, 26442, 26488, 26534, 26580, 26626, 26672, 26718, 26764, 26810, 26856, 26902, 26947, 26993, 27039, 27085, 27131, 27176, 27222, 27268, 27313, 27359, 27405, 27450, 27496, 27542, 27587, 27633, 27678, 27724, 27770, 27815, 27861, 27906, 27952, 27997, 28042, 28088, 28133, 28179, 28224, 28269, 28315, 28360, 28405, 28451, 28496, 28541, 28586, 28632, 28677, 28722, 28767, 28812, 28858, 28903, 28948, 28993, 29038, 29083, 29128, 29173, 29218, 29263, 29308, 29353, 29398, 29443, 29488, 29533, 29577, 29622, 29667, 29712, 29757, 29801, 29846, 29891, 29936, 29980, 30025, 30070, 30114, 30159, 30204, 30248, 30293, 30337, 30382, 30427, 30471, 30516, 30560, 30604, 30649, 30693, 30738, 30782, 30826, 30871, 30915, 30959, 31004, 31048, 31092, 31136, 31181, 31225, 31269, 31313, 31357, 31402, 31446, 31490, 31534, 31578, 31622, 31666, 31710, 31754, 31798, 31842, 31886, 31930, 31974, 32017, 32061, 32105, 32149, 32193, 32236, 32280, 32324, 32368, 32411, 32455, 32499, 32542, 32586, 32630, 32673, 32717, 32760, 32804, 32847, 32891, 32934, 32978, 33021, 33065, 33108, 33151, 33195, 33238, 33281, 33325, 33368, 33411, 33454, 33498, 33541, 33584, 33627, 33670, 33713, 33756, 33799, 33843, 33886, 33929, 33972, 34015, 34057, 34100, 34143, 34186, 34229, 34272, 34315, 34358, 34400, 34443, 34486, 34529, 34571, 34614, 34657, 34699, 34742, 34785, 34827, 34870, 34912, 34955, 34997, 35040, 35082, 35125, 35167, 35210, 35252, 35294, 35337, 35379, 35421, 35464, 35506, 35548, 35590, 35633, 35675, 35717, 35759, 35801, 35843, 35885, 35927, 35969, 36011, 36053, 36095, 36137, 36179, 36221, 36263, 36305, 36347, 36388, 36430, 36472, 36514, 36556, 36597, 36639, 36681, 36722, 36764, 36805, 36847, 36889, 36930, 36972, 37013, 37055, 37096, 37137, 37179, 37220, 37262, 37303, 37344, 37386, 37427, 37468, 37509, 37551, 37592, 37633, 37674, 37715, 37756, 37797, 37838, 37879, 37920, 37961, 38002, 38043, 38084, 38125, 38166, 38207, 38248, 38288, 38329, 38370, 38411, 38451, 38492, 38533, 38573, 38614, 38655, 38695, 38736, 38776, 38817, 38857, 38898, 38938, 38979, 39019, 39059, 39100, 39140, 39180, 39221, 39261, 39301, 39341, 39382, 39422, 39462, 39502, 39542, 39582, 39622, 39662, 39702, 39742, 39782, 39822, 39862, 39902, 39942, 39982, 40021, 40061, 40101, 40141, 40180, 40220, 40260, 40299, 40339, 40379, 40418, 40458, 40497, 40537, 40576, 40616, 40655, 40695, 40734, 40773, 40813, 40852, 40891, 40931, 40970, 41009, 41048, 41087, 41127, 41166, 41205, 41244, 41283, 41322, 41361, 41400, 41439, 41478, 41517, 41556, 41595, 41633, 41672, 41711, 41750, 41788, 41827, 41866, 41904, 41943, 41982, 42020, 42059, 42097, 42136, 42174, 42213, 42251, 42290, 42328, 42366, 42405, 42443, 42481, 42520, 42558, 42596, 42634, 42672, 42711, 42749, 42787, 42825, 42863, 42901, 42939, 42977, 43015, 43053, 43091, 43128, 43166, 43204, 43242, 43280, 43317, 43355, 43393, 43430, 43468, 43506, 43543, 43581, 43618, 43656, 43693, 43731, 43768, 43806, 43843, 43880, 43918, 43955, 43992, 44029, 44067, 44104, 44141, 44178, 44215, 44252, 44289, 44326, 44363, 44400, 44437, 44474, 44511, 44548, 44585, 44622, 44659, 44695, 44732, 44769, 44806, 44842, 44879, 44915, 44952, 44989, 45025, 45062, 45098, 45135, 45171, 45207, 45244, 45280, 45316, 45353, 45389, 45425, 45462, 45498, 45534, 45570, 45606, 45642, 45678, 45714, 45750, 45786, 45822, 45858, 45894, 45930, 45966, 46002, 46037, 46073, 46109, 46145, 46180, 46216, 46252, 46287, 46323, 46358, 46394, 46429, 46465, 46500, 46536, 46571, 46606, 46642, 46677, 46712, 46747, 46783, 46818, 46853, 46888, 46923, 46958, 46993, 47028, 47063, 47098, 47133, 47168, 47203, 47238, 47273, 47308, 47342, 47377, 47412, 47446, 47481, 47516, 47550, 47585, 47619, 47654, 47688, 47723, 47757, 47792, 47826, 47861, 47895, 47929, 47963, 47998, 48032, 48066, 48100, 48134, 48168, 48202, 48237, 48271, 48305, 48338, 48372, 48406, 48440, 48474, 48508, 48542, 48575, 48609, 48643, 48676, 48710, 48744, 48777, 48811, 48844, 48878, 48911, 48945, 48978, 49012, 49045, 49078, 49112, 49145, 49178, 49211, 49244, 49278, 49311, 49344, 49377, 49410, 49443, 49476, 49509, 49542, 49575, 49608, 49640, 49673, 49706, 49739, 49771, 49804, 49837, 49869, 49902, 49935, 49967, 50000, 50032, 50064, 50097, 50129, 50162, 50194, 50226, 50259, 50291, 50323, 50355, 50387, 50420, 50452, 50484, 50516, 50548, 50580, 50612, 50644, 50675, 50707, 50739, 50771, 50803, 50834, 50866, 50898, 50929, 50961, 50993, 51024, 51056, 51087, 51119, 51150, 51182, 51213, 51244, 51276, 51307, 51338, 51369, 51401, 51432, 51463, 51494, 51525, 51556, 51587, 51618, 51649, 51680, 51711, 51742, 51773, 51803, 51834, 51865, 51896, 51926, 51957, 51988, 52018, 52049, 52079, 52110, 52140, 52171, 52201, 52231, 52262, 52292, 52322, 52353, 52383, 52413, 52443, 52473, 52503, 52534, 52564, 52594, 52624, 52653, 52683, 52713, 52743, 52773, 52803, 52832, 52862, 52892, 52922, 52951, 52981, 53010, 53040, 53069, 53099, 53128, 53158, 53187, 53216, 53246, 53275, 53304, 53334, 53363, 53392, 53421, 53450, 53479, 53508, 53537, 53566, 53595, 53624, 53653, 53682, 53711, 53739, 53768, 53797, 53826, 53854, 53883, 53912, 53940, 53969, 53997, 54026, 54054, 54082, 54111, 54139, 54167, 54196, 54224, 54252, 54280, 54309, 54337, 54365, 54393, 54421, 54449, 54477, 54505, 54533, 54560, 54588, 54616, 54644, 54672, 54699, 54727, 54755, 54782, 54810, 54837, 54865, 54892, 54920, 54947, 54974, 55002, 55029, 55056, 55084, 55111, 55138, 55165, 55192, 55219, 55246, 55274, 55300, 55327, 55354, 55381, 55408, 55435, 55462, 55489, 55515, 55542, 55569, 55595, 55622, 55648, 55675, 55701, 55728, 55754, 55781, 55807, 55833, 55860, 55886, 55912, 55938, 55965, 55991, 56017, 56043, 56069, 56095, 56121, 56147, 56173, 56199, 56225, 56250, 56276, 56302, 56328, 56353, 56379, 56404, 56430, 56456, 56481, 56507, 56532, 56557, 56583, 56608, 56633, 56659, 56684, 56709, 56734, 56760, 56785, 56810, 56835, 56860, 56885, 56910, 56935, 56959, 56984, 57009, 57034, 57059, 57083, 57108, 57133, 57157, 57182, 57206, 57231, 57255, 57280, 57304, 57329, 57353, 57377, 57402, 57426, 57450, 57474, 57498, 57522, 57546, 57570, 57594, 57618, 57642, 57666, 57690, 57714, 57738, 57762, 57785, 57809, 57833, 57856, 57880, 57903, 57927, 57950, 57974, 57997, 58021, 58044, 58067, 58091, 58114, 58137, 58160, 58183, 58207, 58230, 58253, 58276, 58299, 58322, 58345, 58367, 58390, 58413, 58436, 58459, 58481, 58504, 58527, 58549, 58572, 58594, 58617, 58639, 58662, 58684, 58706, 58729, 58751, 58773, 58795, 58818, 58840, 58862, 58884, 58906, 58928, 58950, 58972, 58994, 59016, 59038, 59059, 59081, 59103, 59125, 59146, 59168, 59190, 59211, 59233, 59254, 59276, 59297, 59318, 59340, 59361, 59382, 59404, 59425, 59446, 59467, 59488, 59509, 59530, 59551, 59572, 59593, 59614, 59635, 59656, 59677, 59697, 59718, 59739, 59759, 59780, 59801, 59821, 59842, 59862, 59883, 59903, 59923, 59944, 59964, 59984, 60004, 60025, 60045, 60065, 60085, 60105, 60125, 60145, 60165, 60185, 60205, 60225, 60244, 60264, 60284, 60304, 60323, 60343, 60363, 60382, 60402, 60421, 60441, 60460, 60479, 60499, 60518, 60537, 60556, 60576, 60595, 60614, 60633, 60652, 60671, 60690, 60709, 60728, 60747, 60766, 60785, 60803, 60822, 60841, 60859, 60878, 60897, 60915, 60934, 60952, 60971, 60989, 61007, 61026, 61044, 61062, 61081, 61099, 61117, 61135, 61153, 61171, 61189, 61207, 61225, 61243, 61261, 61279, 61297, 61314, 61332, 61350, 61367, 61385, 61403, 61420, 61438, 61455, 61473, 61490, 61507, 61525, 61542, 61559, 61577, 61594, 61611, 61628, 61645, 61662, 61679, 61696, 61713, 61730, 61747, 61764, 61780, 61797, 61814, 61831, 61847, 61864, 61880, 61897, 61913, 61930, 61946, 61963, 61979, 61995, 62012, 62028, 62044, 62060, 62076, 62092, 62108, 62125, 62141, 62156, 62172, 62188, 62204, 62220, 62236, 62251, 62267, 62283, 62298, 62314, 62329, 62345, 62360, 62376, 62391, 62407, 62422, 62437, 62453, 62468, 62483, 62498, 62513, 62528, 62543, 62558, 62573, 62588, 62603, 62618, 62633, 62648, 62662, 62677, 62692, 62706, 62721, 62735, 62750, 62764, 62779, 62793, 62808, 62822, 62836, 62850, 62865, 62879, 62893, 62907, 62921, 62935, 62949, 62963, 62977, 62991, 63005, 63019, 63032, 63046, 63060, 63074, 63087, 63101, 63114, 63128, 63141, 63155, 63168, 63182, 63195, 63208, 63221, 63235, 63248, 63261, 63274, 63287, 63300, 63313, 63326, 63339, 63352, 63365, 63378, 63390, 63403, 63416, 63429, 63441, 63454, 63466, 63479, 63491, 63504, 63516, 63528, 63541, 63553, 63565, 63578, 63590, 63602, 63614, 63626, 63638, 63650, 63662, 63674, 63686, 63698, 63709, 63721, 63733, 63745, 63756, 63768, 63779, 63791, 63803, 63814, 63825, 63837, 63848, 63859, 63871, 63882, 63893, 63904, 63915, 63927, 63938, 63949, 63960, 63971, 63981, 63992, 64003, 64014, 64025, 64035, 64046, 64057, 64067, 64078, 64088, 64099, 64109, 64120, 64130, 64140, 64151, 64161, 64171, 64181, 64192, 64202, 64212, 64222, 64232, 64242, 64252, 64261, 64271, 64281, 64291, 64301, 64310, 64320, 64330, 64339, 64349, 64358, 64368, 64377, 64387, 64396, 64405, 64414, 64424, 64433, 64442, 64451, 64460, 64469, 64478, 64487, 64496, 64505, 64514, 64523, 64532, 64540, 64549, 64558, 64566, 64575, 64584, 64592, 64600, 64609, 64617, 64626, 64634, 64642, 64651, 64659, 64667, 64675, 64683, 64691, 64699, 64707, 64715, 64723, 64731, 64739, 64747, 64754, 64762, 64770, 64777, 64785, 64793, 64800, 64808, 64815, 64822, 64830, 64837, 64844, 64852, 64859, 64866, 64873, 64880, 64887, 64895, 64902, 64908, 64915, 64922, 64929, 64936, 64943, 64949, 64956, 64963, 64969, 64976, 64982, 64989, 64995, 65002, 65008, 65015, 65021, 65027, 65033, 65040, 65046, 65052, 65058, 65064, 65070, 65076, 65082, 65088, 65094, 65099, 65105, 65111, 65117, 65122, 65128, 65133, 65139, 65144, 65150, 65155, 65161, 65166, 65171, 65177, 65182, 65187, 65192, 65197, 65202, 65207, 65212, 65217, 65222, 65227, 65232, 65237, 65242, 65246, 65251, 65256, 65260, 65265, 65270, 65274, 65279, 65283, 65287, 65292, 65296, 65300, 65305, 65309, 65313, 65317, 65321, 65325, 65329, 65333, 65337, 65341, 65345, 65349, 65352, 65356, 65360, 65363, 65367, 65371, 65374, 65378, 65381, 65385, 65388, 65391, 65395, 65398, 65401, 65404, 65408, 65411, 65414, 65417, 65420, 65423, 65426, 65429, 65431, 65434, 65437, 65440, 65442, 65445, 65448, 65450, 65453, 65455, 65458, 65460, 65463, 65465, 65467, 65470, 65472, 65474, 65476, 65478, 65480, 65482, 65484, 65486, 65488, 65490, 65492, 65494, 65496, 65497, 65499, 65501, 65502, 65504, 65505, 65507, 65508, 65510, 65511, 65513, 65514, 65515, 65516, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65527, 65528, 65529, 65530, 65530, 65531, 65531, 65532, 65532, 65533, 65533, 65534, 65534, 65534, 65535, 65535, 65535, 65535, 65535, 65535, 65535 }; + +const fixed_t *const finecosine = finesine + (FINEANGLES / 4); + +const angle_t tantoangle[2049] = +{ 0, 333772, 667544, 1001315, 1335086, 1668857, 2002626, 2336395, 2670163, 3003929, 3337694, 3671457, 4005219, 4338979, 4672736, 5006492, 5340245, 5673995, 6007743, 6341488, 6675230, 7008968, 7342704, 7676435, 8010164, 8343888, 8677609, 9011325, 9345037, 9678744, 10012447, 10346145, 10679838, 11013526, 11347209, 11680887, 12014558, 12348225, 12681885, 13015539, 13349187, 13682829, 14016464, 14350092, 14683714, 15017328, 15350936, 15684536, 16018129, 16351714, 16685291, 17018860, 17352422, 17685974, 18019518, 18353054, 18686582, 19020100, 19353610, 19687110, 20020600, 20354080, 20687552, 21021014, 21354466, 21687906, 22021338, 22354758, 22688168, 23021568, 23354956, 23688332, 24021698, 24355052, 24688396, 25021726, 25355046, 25688352, 26021648, 26354930, 26688200, 27021456, 27354702, 27687932, 28021150, 28354356, 28687548, 29020724, 29353888, 29687038, 30020174, 30353296, 30686404, 31019496, 31352574, 31685636, 32018684, 32351718, 32684734, 33017736, 33350722, 33683692, 34016648, 34349584, 34682508, 35015412, 35348300, 35681172, 36014028, 36346868, 36679688, 37012492, 37345276, 37678044, 38010792, 38343524, 38676240, 39008936, 39341612, 39674272, 40006912, 40339532, 40672132, 41004716, 41337276, 41669820, 42002344, 42334848, 42667332, 42999796, 43332236, 43664660, 43997060, 44329444, 44661800, 44994140, 45326456, 45658752, 45991028, 46323280, 46655512, 46987720, 47319908, 47652072, 47984212, 48316332, 48648428, 48980500, 49312548, 49644576, 49976580, 50308556, 50640512, 50972444, 51304352, 51636236, 51968096, 52299928, 52631740, 52963524, 53295284, 53627020, 53958728, 54290412, 54622068, 54953704, 55285308, 55616888, 55948444, 56279972, 56611472, 56942948, 57274396, 57605816, 57937212, 58268576, 58599916, 58931228, 59262512, 59593768, 59924992, 60256192, 60587364, 60918508, 61249620, 61580704, 61911760, 62242788, 62573788, 62904756, 63235692, 63566604, 63897480, 64228332, 64559148, 64889940, 65220696, 65551424, 65882120, 66212788, 66543420, 66874024, 67204600, 67535136, 67865648, 68196120, 68526568, 68856984, 69187360, 69517712, 69848024, 70178304, 70508560, 70838776, 71168960, 71499112, 71829224, 72159312, 72489360, 72819376, 73149360, 73479304, 73809216, 74139096, 74468936, 74798744, 75128520, 75458264, 75787968, 76117632, 76447264, 76776864, 77106424, 77435952, 77765440, 78094888, 78424304, 78753688, 79083032, 79412336, 79741608, 80070840, 80400032, 80729192, 81058312, 81387392, 81716432, 82045440, 82374408, 82703336, 83032224, 83361080, 83689896, 84018664, 84347400, 84676096, 85004760, 85333376, 85661952, 85990488, 86318984, 86647448, 86975864, 87304240, 87632576, 87960872, 88289128, 88617344, 88945520, 89273648, 89601736, 89929792, 90257792, 90585760, 90913688, 91241568, 91569408, 91897200, 92224960, 92552672, 92880336, 93207968, 93535552, 93863088, 94190584, 94518040, 94845448, 95172816, 95500136, 95827416, 96154648, 96481832, 96808976, 97136080, 97463136, 97790144, 98117112, 98444032, 98770904, 99097736, 99424520, 99751256, 100077944, 100404592, 100731192, 101057744, 101384248, 101710712, 102037128, 102363488, 102689808, 103016080, 103342312, 103668488, 103994616, 104320696, 104646736, 104972720, 105298656, 105624552, 105950392, 106276184, 106601928, 106927624, 107253272, 107578872, 107904416, 108229920, 108555368, 108880768, 109206120, 109531416, 109856664, 110181872, 110507016, 110832120, 111157168, 111482168, 111807112, 112132008, 112456856, 112781648, 113106392, 113431080, 113755720, 114080312, 114404848, 114729328, 115053760, 115378136, 115702464, 116026744, 116350960, 116675128, 116999248, 117323312, 117647320, 117971272, 118295176, 118619024, 118942816, 119266560, 119590248, 119913880, 120237456, 120560984, 120884456, 121207864, 121531224, 121854528, 122177784, 122500976, 122824112, 123147200, 123470224, 123793200, 124116120, 124438976, 124761784, 125084528, 125407224, 125729856, 126052432, 126374960, 126697424, 127019832, 127342184, 127664472, 127986712, 128308888, 128631008, 128953072, 129275080, 129597024, 129918912, 130240744, 130562520, 130884232, 131205888, 131527480, 131849016, 132170496, 132491912, 132813272, 133134576, 133455816, 133776992, 134098120, 134419184, 134740176, 135061120, 135382000, 135702816, 136023584, 136344272, 136664912, 136985488, 137306016, 137626464, 137946864, 138267184, 138587456, 138907664, 139227808, 139547904, 139867920, 140187888, 140507776, 140827616, 141147392, 141467104, 141786752, 142106336, 142425856, 142745312, 143064720, 143384048, 143703312, 144022512, 144341664, 144660736, 144979744, 145298704, 145617584, 145936400, 146255168, 146573856, 146892480, 147211040, 147529536, 147847968, 148166336, 148484640, 148802880, 149121056, 149439152, 149757200, 150075168, 150393072, 150710912, 151028688, 151346400, 151664048, 151981616, 152299136, 152616576, 152933952, 153251264, 153568496, 153885680, 154202784, 154519824, 154836784, 155153696, 155470528, 155787296, 156104000, 156420624, 156737200, 157053696, 157370112, 157686480, 158002768, 158318976, 158635136, 158951216, 159267232, 159583168, 159899040, 160214848, 160530592, 160846256, 161161840, 161477376, 161792832, 162108208, 162423520, 162738768, 163053952, 163369040, 163684080, 163999040, 164313936, 164628752, 164943504, 165258176, 165572784, 165887312, 166201776, 166516160, 166830480, 167144736, 167458912, 167773008, 168087040, 168400992, 168714880, 169028688, 169342432, 169656096, 169969696, 170283216, 170596672, 170910032, 171223344, 171536576, 171849728, 172162800, 172475808, 172788736, 173101600, 173414384, 173727104, 174039728, 174352288, 174664784, 174977200, 175289536, 175601792, 175913984, 176226096, 176538144, 176850096, 177161984, 177473792, 177785536, 178097200, 178408784, 178720288, 179031728, 179343088, 179654368, 179965568, 180276704, 180587744, 180898720, 181209616, 181520448, 181831184, 182141856, 182452448, 182762960, 183073408, 183383760, 183694048, 184004240, 184314368, 184624416, 184934400, 185244288, 185554096, 185863840, 186173504, 186483072, 186792576, 187102000, 187411344, 187720608, 188029808, 188338912, 188647936, 188956896, 189265760, 189574560, 189883264, 190191904, 190500448, 190808928, 191117312, 191425632, 191733872, 192042016, 192350096, 192658096, 192966000, 193273840, 193581584, 193889264, 194196848, 194504352, 194811792, 195119136, 195426400, 195733584, 196040688, 196347712, 196654656, 196961520, 197268304, 197574992, 197881616, 198188144, 198494592, 198800960, 199107248, 199413456, 199719584, 200025616, 200331584, 200637456, 200943248, 201248960, 201554576, 201860128, 202165584, 202470960, 202776256, 203081456, 203386592, 203691632, 203996592, 204301472, 204606256, 204910976, 205215600, 205520144, 205824592, 206128960, 206433248, 206737456, 207041584, 207345616, 207649568, 207953424, 208257216, 208560912, 208864512, 209168048, 209471488, 209774832, 210078112, 210381296, 210684384, 210987408, 211290336, 211593184, 211895936, 212198608, 212501184, 212803680, 213106096, 213408432, 213710672, 214012816, 214314880, 214616864, 214918768, 215220576, 215522288, 215823920, 216125472, 216426928, 216728304, 217029584, 217330784, 217631904, 217932928, 218233856, 218534704, 218835472, 219136144, 219436720, 219737216, 220037632, 220337952, 220638192, 220938336, 221238384, 221538352, 221838240, 222138032, 222437728, 222737344, 223036880, 223336304, 223635664, 223934912, 224234096, 224533168, 224832160, 225131072, 225429872, 225728608, 226027232, 226325776, 226624240, 226922608, 227220880, 227519056, 227817152, 228115168, 228413088, 228710912, 229008640, 229306288, 229603840, 229901312, 230198688, 230495968, 230793152, 231090256, 231387280, 231684192, 231981024, 232277760, 232574416, 232870960, 233167440, 233463808, 233760096, 234056288, 234352384, 234648384, 234944304, 235240128, 235535872, 235831504, 236127056, 236422512, 236717888, 237013152, 237308336, 237603424, 237898416, 238193328, 238488144, 238782864, 239077488, 239372016, 239666464, 239960816, 240255072, 240549232, 240843312, 241137280, 241431168, 241724960, 242018656, 242312256, 242605776, 242899200, 243192512, 243485744, 243778896, 244071936, 244364880, 244657744, 244950496, 245243168, 245535744, 245828224, 246120608, 246412912, 246705104, 246997216, 247289216, 247581136, 247872960, 248164688, 248456320, 248747856, 249039296, 249330640, 249621904, 249913056, 250204128, 250495088, 250785968, 251076736, 251367424, 251658016, 251948512, 252238912, 252529200, 252819408, 253109520, 253399536, 253689456, 253979280, 254269008, 254558640, 254848176, 255137632, 255426976, 255716224, 256005376, 256294432, 256583392, 256872256, 257161024, 257449696, 257738272, 258026752, 258315136, 258603424, 258891600, 259179696, 259467696, 259755600, 260043392, 260331104, 260618704, 260906224, 261193632, 261480960, 261768176, 262055296, 262342320, 262629248, 262916080, 263202816, 263489456, 263776000, 264062432, 264348784, 264635024, 264921168, 265207216, 265493168, 265779024, 266064784, 266350448, 266636000, 266921472, 267206832, 267492096, 267777264, 268062336, 268347312, 268632192, 268916960, 269201632, 269486208, 269770688, 270055072, 270339360, 270623552, 270907616, 271191616, 271475488, 271759296, 272042976, 272326560, 272610048, 272893440, 273176736, 273459936, 273743040, 274026048, 274308928, 274591744, 274874432, 275157024, 275439520, 275721920, 276004224, 276286432, 276568512, 276850528, 277132416, 277414240, 277695936, 277977536, 278259040, 278540448, 278821728, 279102944, 279384032, 279665056, 279945952, 280226752, 280507456, 280788064, 281068544, 281348960, 281629248, 281909472, 282189568, 282469568, 282749440, 283029248, 283308960, 283588544, 283868032, 284147424, 284426720, 284705920, 284985024, 285264000, 285542912, 285821696, 286100384, 286378976, 286657440, 286935840, 287214112, 287492320, 287770400, 288048384, 288326240, 288604032, 288881696, 289159264, 289436768, 289714112, 289991392, 290268576, 290545632, 290822592, 291099456, 291376224, 291652896, 291929440, 292205888, 292482272, 292758528, 293034656, 293310720, 293586656, 293862496, 294138240, 294413888, 294689440, 294964864, 295240192, 295515424, 295790560, 296065600, 296340512, 296615360, 296890080, 297164704, 297439200, 297713632, 297987936, 298262144, 298536256, 298810240, 299084160, 299357952, 299631648, 299905248, 300178720, 300452128, 300725408, 300998592, 301271680, 301544640, 301817536, 302090304, 302362976, 302635520, 302908000, 303180352, 303452608, 303724768, 303996800, 304268768, 304540608, 304812320, 305083968, 305355520, 305626944, 305898272, 306169472, 306440608, 306711616, 306982528, 307253344, 307524064, 307794656, 308065152, 308335552, 308605856, 308876032, 309146112, 309416096, 309685984, 309955744, 310225408, 310494976, 310764448, 311033824, 311303072, 311572224, 311841280, 312110208, 312379040, 312647776, 312916416, 313184960, 313453376, 313721696, 313989920, 314258016, 314526016, 314793920, 315061728, 315329408, 315597024, 315864512, 316131872, 316399168, 316666336, 316933408, 317200384, 317467232, 317733984, 318000640, 318267200, 318533632, 318799968, 319066208, 319332352, 319598368, 319864288, 320130112, 320395808, 320661408, 320926912, 321192320, 321457632, 321722816, 321987904, 322252864, 322517760, 322782528, 323047200, 323311744, 323576192, 323840544, 324104800, 324368928, 324632992, 324896928, 325160736, 325424448, 325688096, 325951584, 326215008, 326478304, 326741504, 327004608, 327267584, 327530464, 327793248, 328055904, 328318496, 328580960, 328843296, 329105568, 329367712, 329629760, 329891680, 330153536, 330415264, 330676864, 330938400, 331199808, 331461120, 331722304, 331983392, 332244384, 332505280, 332766048, 333026752, 333287296, 333547776, 333808128, 334068384, 334328544, 334588576, 334848512, 335108352, 335368064, 335627712, 335887200, 336146624, 336405920, 336665120, 336924224, 337183200, 337442112, 337700864, 337959552, 338218112, 338476576, 338734944, 338993184, 339251328, 339509376, 339767296, 340025120, 340282848, 340540480, 340797984, 341055392, 341312704, 341569888, 341826976, 342083968, 342340832, 342597600, 342854272, 343110848, 343367296, 343623648, 343879904, 344136032, 344392064, 344648000, 344903808, 345159520, 345415136, 345670656, 345926048, 346181344, 346436512, 346691616, 346946592, 347201440, 347456224, 347710880, 347965440, 348219872, 348474208, 348728448, 348982592, 349236608, 349490528, 349744320, 349998048, 350251648, 350505152, 350758528, 351011808, 351264992, 351518048, 351771040, 352023872, 352276640, 352529280, 352781824, 353034272, 353286592, 353538816, 353790944, 354042944, 354294880, 354546656, 354798368, 355049952, 355301440, 355552800, 355804096, 356055264, 356306304, 356557280, 356808128, 357058848, 357309504, 357560032, 357810464, 358060768, 358311008, 358561088, 358811104, 359060992, 359310784, 359560480, 359810048, 360059520, 360308896, 360558144, 360807296, 361056352, 361305312, 361554144, 361802880, 362051488, 362300032, 362548448, 362796736, 363044960, 363293056, 363541024, 363788928, 364036704, 364284384, 364531936, 364779392, 365026752, 365274016, 365521152, 365768192, 366015136, 366261952, 366508672, 366755296, 367001792, 367248192, 367494496, 367740704, 367986784, 368232768, 368478656, 368724416, 368970080, 369215648, 369461088, 369706432, 369951680, 370196800, 370441824, 370686752, 370931584, 371176288, 371420896, 371665408, 371909792, 372154080, 372398272, 372642336, 372886304, 373130176, 373373952, 373617600, 373861152, 374104608, 374347936, 374591168, 374834304, 375077312, 375320224, 375563040, 375805760, 376048352, 376290848, 376533248, 376775520, 377017696, 377259776, 377501728, 377743584, 377985344, 378227008, 378468544, 378709984, 378951328, 379192544, 379433664, 379674688, 379915584, 380156416, 380397088, 380637696, 380878176, 381118560, 381358848, 381599040, 381839104, 382079072, 382318912, 382558656, 382798304, 383037856, 383277280, 383516640, 383755840, 383994976, 384233984, 384472896, 384711712, 384950400, 385188992, 385427488, 385665888, 385904160, 386142336, 386380384, 386618368, 386856224, 387093984, 387331616, 387569152, 387806592, 388043936, 388281152, 388518272, 388755296, 388992224, 389229024, 389465728, 389702336, 389938816, 390175200, 390411488, 390647680, 390883744, 391119712, 391355584, 391591328, 391826976, 392062528, 392297984, 392533312, 392768544, 393003680, 393238720, 393473632, 393708448, 393943168, 394177760, 394412256, 394646656, 394880960, 395115136, 395349216, 395583200, 395817088, 396050848, 396284512, 396518080, 396751520, 396984864, 397218112, 397451264, 397684288, 397917248, 398150080, 398382784, 398615424, 398847936, 399080320, 399312640, 399544832, 399776928, 400008928, 400240832, 400472608, 400704288, 400935872, 401167328, 401398720, 401629984, 401861120, 402092192, 402323136, 402553984, 402784736, 403015360, 403245888, 403476320, 403706656, 403936896, 404167008, 404397024, 404626944, 404856736, 405086432, 405316032, 405545536, 405774912, 406004224, 406233408, 406462464, 406691456, 406920320, 407149088, 407377760, 407606336, 407834784, 408063136, 408291392, 408519520, 408747584, 408975520, 409203360, 409431072, 409658720, 409886240, 410113664, 410340992, 410568192, 410795296, 411022304, 411249216, 411476032, 411702720, 411929312, 412155808, 412382176, 412608480, 412834656, 413060736, 413286720, 413512576, 413738336, 413964000, 414189568, 414415040, 414640384, 414865632, 415090784, 415315840, 415540800, 415765632, 415990368, 416215008, 416439552, 416663968, 416888288, 417112512, 417336640, 417560672, 417784576, 418008384, 418232096, 418455712, 418679200, 418902624, 419125920, 419349120, 419572192, 419795200, 420018080, 420240864, 420463552, 420686144, 420908608, 421130976, 421353280, 421575424, 421797504, 422019488, 422241344, 422463104, 422684768, 422906336, 423127776, 423349120, 423570400, 423791520, 424012576, 424233536, 424454368, 424675104, 424895744, 425116288, 425336736, 425557056, 425777280, 425997408, 426217440, 426437376, 426657184, 426876928, 427096544, 427316064, 427535488, 427754784, 427974016, 428193120, 428412128, 428631040, 428849856, 429068544, 429287168, 429505664, 429724064, 429942368, 430160576, 430378656, 430596672, 430814560, 431032352, 431250048, 431467616, 431685120, 431902496, 432119808, 432336992, 432554080, 432771040, 432987936, 433204736, 433421408, 433637984, 433854464, 434070848, 434287104, 434503296, 434719360, 434935360, 435151232, 435367008, 435582656, 435798240, 436013696, 436229088, 436444352, 436659520, 436874592, 437089568, 437304416, 437519200, 437733856, 437948416, 438162880, 438377248, 438591520, 438805696, 439019744, 439233728, 439447584, 439661344, 439875008, 440088576, 440302048, 440515392, 440728672, 440941824, 441154880, 441367872, 441580736, 441793472, 442006144, 442218720, 442431168, 442643552, 442855808, 443067968, 443280032, 443492000, 443703872, 443915648, 444127296, 444338880, 444550336, 444761696, 444972992, 445184160, 445395232, 445606176, 445817056, 446027840, 446238496, 446449088, 446659552, 446869920, 447080192, 447290400, 447500448, 447710432, 447920320, 448130112, 448339776, 448549376, 448758848, 448968224, 449177536, 449386720, 449595808, 449804800, 450013664, 450222464, 450431168, 450639776, 450848256, 451056640, 451264960, 451473152, 451681248, 451889248, 452097152, 452304960, 452512672, 452720288, 452927808, 453135232, 453342528, 453549760, 453756864, 453963904, 454170816, 454377632, 454584384, 454791008, 454997536, 455203968, 455410304, 455616544, 455822688, 456028704, 456234656, 456440512, 456646240, 456851904, 457057472, 457262912, 457468256, 457673536, 457878688, 458083744, 458288736, 458493600, 458698368, 458903040, 459107616, 459312096, 459516480, 459720768, 459924960, 460129056, 460333056, 460536960, 460740736, 460944448, 461148064, 461351584, 461554976, 461758304, 461961536, 462164640, 462367680, 462570592, 462773440, 462976160, 463178816, 463381344, 463583776, 463786144, 463988384, 464190560, 464392608, 464594560, 464796448, 464998208, 465199872, 465401472, 465602944, 465804320, 466005600, 466206816, 466407904, 466608896, 466809824, 467010624, 467211328, 467411936, 467612480, 467812896, 468013216, 468213440, 468413600, 468613632, 468813568, 469013440, 469213184, 469412832, 469612416, 469811872, 470011232, 470210528, 470409696, 470608800, 470807776, 471006688, 471205472, 471404192, 471602784, 471801312, 471999712, 472198048, 472396288, 472594400, 472792448, 472990400, 473188256, 473385984, 473583648, 473781216, 473978688, 474176064, 474373344, 474570528, 474767616, 474964608, 475161504, 475358336, 475555040, 475751648, 475948192, 476144608, 476340928, 476537184, 476733312, 476929376, 477125344, 477321184, 477516960, 477712640, 477908224, 478103712, 478299104, 478494400, 478689600, 478884704, 479079744, 479274656, 479469504, 479664224, 479858880, 480053408, 480247872, 480442240, 480636512, 480830656, 481024736, 481218752, 481412640, 481606432, 481800128, 481993760, 482187264, 482380704, 482574016, 482767264, 482960416, 483153472, 483346432, 483539296, 483732064, 483924768, 484117344, 484309856, 484502240, 484694560, 484886784, 485078912, 485270944, 485462880, 485654720, 485846464, 486038144, 486229696, 486421184, 486612576, 486803840, 486995040, 487186176, 487377184, 487568096, 487758912, 487949664, 488140320, 488330880, 488521312, 488711712, 488901984, 489092160, 489282240, 489472256, 489662176, 489851968, 490041696, 490231328, 490420896, 490610336, 490799712, 490988960, 491178144, 491367232, 491556224, 491745120, 491933920, 492122656, 492311264, 492499808, 492688256, 492876608, 493064864, 493253056, 493441120, 493629120, 493817024, 494004832, 494192544, 494380160, 494567712, 494755136, 494942496, 495129760, 495316928, 495504000, 495691008, 495877888, 496064704, 496251424, 496438048, 496624608, 496811040, 496997408, 497183680, 497369856, 497555936, 497741920, 497927840, 498113632, 498299360, 498484992, 498670560, 498856000, 499041376, 499226656, 499411840, 499596928, 499781920, 499966848, 500151680, 500336416, 500521056, 500705600, 500890080, 501074464, 501258752, 501442944, 501627040, 501811072, 501995008, 502178848, 502362592, 502546240, 502729824, 502913312, 503096704, 503280000, 503463232, 503646368, 503829408, 504012352, 504195200, 504377984, 504560672, 504743264, 504925760, 505108192, 505290496, 505472736, 505654912, 505836960, 506018944, 506200832, 506382624, 506564320, 506745952, 506927488, 507108928, 507290272, 507471552, 507652736, 507833824, 508014816, 508195744, 508376576, 508557312, 508737952, 508918528, 509099008, 509279392, 509459680, 509639904, 509820032, 510000064, 510180000, 510359872, 510539648, 510719328, 510898944, 511078432, 511257856, 511437216, 511616448, 511795616, 511974688, 512153664, 512332576, 512511392, 512690112, 512868768, 513047296, 513225792, 513404160, 513582432, 513760640, 513938784, 514116800, 514294752, 514472608, 514650368, 514828064, 515005664, 515183168, 515360608, 515537952, 515715200, 515892352, 516069440, 516246432, 516423328, 516600160, 516776896, 516953536, 517130112, 517306592, 517482976, 517659264, 517835488, 518011616, 518187680, 518363648, 518539520, 518715296, 518891008, 519066624, 519242144, 519417600, 519592960, 519768256, 519943424, 520118528, 520293568, 520468480, 520643328, 520818112, 520992800, 521167392, 521341888, 521516320, 521690656, 521864896, 522039072, 522213152, 522387168, 522561056, 522734912, 522908640, 523082304, 523255872, 523429376, 523602784, 523776096, 523949312, 524122464, 524295552, 524468512, 524641440, 524814240, 524986976, 525159616, 525332192, 525504640, 525677056, 525849344, 526021568, 526193728, 526365792, 526537760, 526709632, 526881440, 527053152, 527224800, 527396352, 527567840, 527739200, 527910528, 528081728, 528252864, 528423936, 528594880, 528765760, 528936576, 529107296, 529277920, 529448480, 529618944, 529789344, 529959648, 530129856, 530300000, 530470048, 530640000, 530809888, 530979712, 531149440, 531319072, 531488608, 531658080, 531827488, 531996800, 532166016, 532335168, 532504224, 532673184, 532842080, 533010912, 533179616, 533348288, 533516832, 533685312, 533853728, 534022048, 534190272, 534358432, 534526496, 534694496, 534862400, 535030240, 535197984, 535365632, 535533216, 535700704, 535868128, 536035456, 536202720, 536369888, 536536992, 536704000, 536870912 }; +#if TABULATED_VALUES +const short viewangletox[4096] = +#if SCREENWIDTH == 160 +{ 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 159, 159, 159, 159, 159, 159, 159, 159, 158, 158, 158, 158, 158, 158, 158, 158, 157, 157, 157, 157, 157, 157, 157, 157, 157, 156, 156, 156, 156, 156, 156, 156, 156, 156, 155, 155, 155, 155, 155, 155, 155, 155, 154, 154, 154, 154, 154, 154, 154, 154, 154, 153, 153, 153, 153, 153, 153, 153, 153, 153, 152, 152, 152, 152, 152, 152, 152, 152, 152, 151, 151, 151, 151, 151, 151, 151, 151, 151, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 149, 149, 149, 149, 149, 149, 149, 149, 149, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 147, 147, 147, 147, 147, 147, 147, 147, 147, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 145, 145, 145, 145, 145, 145, 145, 145, 145, 145, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 134, 134, 134, 134, 134, 134, 134, 134, 134, 134, 134, 134, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 14, 14, 14, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; +#elif SCREENWIDTH == 240 +{ + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240,240, + 240,240,240,240,240,239,239,239,239,239,238,238,238,238,238,238,237,237,237,237,237,237,236,236,236,236,236,235,235,235,235,235, + 235,234,234,234,234,234,234,233,233,233,233,233,232,232,232,232,232,232,231,231,231,231,231,231,230,230,230,230,230,230,229,229, + 229,229,229,229,228,228,228,228,228,228,227,227,227,227,227,227,226,226,226,226,226,226,225,225,225,225,225,225,224,224,224,224, + 224,224,224,223,223,223,223,223,223,222,222,222,222,222,222,221,221,221,221,221,221,221,220,220,220,220,220,220,219,219,219,219, + 219,219,219,218,218,218,218,218,218,217,217,217,217,217,217,217,216,216,216,216,216,216,215,215,215,215,215,215,215,214,214,214, + 214,214,214,214,213,213,213,213,213,213,213,212,212,212,212,212,212,212,211,211,211,211,211,211,211,210,210,210,210,210,210,210, + 209,209,209,209,209,209,209,208,208,208,208,208,208,208,207,207,207,207,207,207,207,206,206,206,206,206,206,206,205,205,205,205, + 205,205,205,204,204,204,204,204,204,204,204,203,203,203,203,203,203,203,202,202,202,202,202,202,202,201,201,201,201,201,201,201, + 201,200,200,200,200,200,200,200,199,199,199,199,199,199,199,199,198,198,198,198,198,198,198,198,197,197,197,197,197,197,197,196, + 196,196,196,196,196,196,196,195,195,195,195,195,195,195,195,194,194,194,194,194,194,194,194,193,193,193,193,193,193,193,193,192, + 192,192,192,192,192,192,192,191,191,191,191,191,191,191,191,190,190,190,190,190,190,190,190,189,189,189,189,189,189,189,189,188, + 188,188,188,188,188,188,188,188,187,187,187,187,187,187,187,187,186,186,186,186,186,186,186,186,185,185,185,185,185,185,185,185, + 185,184,184,184,184,184,184,184,184,183,183,183,183,183,183,183,183,183,182,182,182,182,182,182,182,182,181,181,181,181,181,181, + 181,181,181,180,180,180,180,180,180,180,180,180,179,179,179,179,179,179,179,179,179,178,178,178,178,178,178,178,178,177,177,177, + 177,177,177,177,177,177,176,176,176,176,176,176,176,176,176,175,175,175,175,175,175,175,175,175,174,174,174,174,174,174,174,174, + 174,173,173,173,173,173,173,173,173,173,172,172,172,172,172,172,172,172,172,172,171,171,171,171,171,171,171,171,171,170,170,170, + 170,170,170,170,170,170,169,169,169,169,169,169,169,169,169,169,168,168,168,168,168,168,168,168,168,167,167,167,167,167,167,167, + 167,167,166,166,166,166,166,166,166,166,166,166,165,165,165,165,165,165,165,165,165,164,164,164,164,164,164,164,164,164,164,163, + 163,163,163,163,163,163,163,163,163,162,162,162,162,162,162,162,162,162,161,161,161,161,161,161,161,161,161,161,160,160,160,160, + 160,160,160,160,160,160,159,159,159,159,159,159,159,159,159,159,158,158,158,158,158,158,158,158,158,158,157,157,157,157,157,157, + 157,157,157,157,156,156,156,156,156,156,156,156,156,156,155,155,155,155,155,155,155,155,155,155,154,154,154,154,154,154,154,154, + 154,154,153,153,153,153,153,153,153,153,153,153,152,152,152,152,152,152,152,152,152,152,151,151,151,151,151,151,151,151,151,151, + 150,150,150,150,150,150,150,150,150,150,150,149,149,149,149,149,149,149,149,149,149,148,148,148,148,148,148,148,148,148,148,147, + 147,147,147,147,147,147,147,147,147,147,146,146,146,146,146,146,146,146,146,146,145,145,145,145,145,145,145,145,145,145,144,144, + 144,144,144,144,144,144,144,144,144,143,143,143,143,143,143,143,143,143,143,142,142,142,142,142,142,142,142,142,142,142,141,141, + 141,141,141,141,141,141,141,141,140,140,140,140,140,140,140,140,140,140,140,139,139,139,139,139,139,139,139,139,139,139,138,138, + 138,138,138,138,138,138,138,138,137,137,137,137,137,137,137,137,137,137,137,136,136,136,136,136,136,136,136,136,136,136,135,135, + 135,135,135,135,135,135,135,135,134,134,134,134,134,134,134,134,134,134,134,133,133,133,133,133,133,133,133,133,133,133,132,132, + 132,132,132,132,132,132,132,132,132,131,131,131,131,131,131,131,131,131,131,131,130,130,130,130,130,130,130,130,130,130,129,129, + 129,129,129,129,129,129,129,129,129,128,128,128,128,128,128,128,128,128,128,128,127,127,127,127,127,127,127,127,127,127,127,126, + 126,126,126,126,126,126,126,126,126,126,125,125,125,125,125,125,125,125,125,125,125,124,124,124,124,124,124,124,124,124,124,123, + 123,123,123,123,123,123,123,123,123,123,122,122,122,122,122,122,122,122,122,122,122,121,121,121,121,121,121,121,121,121,121,121, + 120,120,120,120,120,120,120,120,120,120,120,119,119,119,119,119,119,119,119,119,119,119,118,118,118,118,118,118,118,118,118,118, + 118,117,117,117,117,117,117,117,117,117,117,116,116,116,116,116,116,116,116,116,116,116,115,115,115,115,115,115,115,115,115,115, + 115,114,114,114,114,114,114,114,114,114,114,114,113,113,113,113,113,113,113,113,113,113,113,112,112,112,112,112,112,112,112,112, + 112,112,111,111,111,111,111,111,111,111,111,111,110,110,110,110,110,110,110,110,110,110,110,109,109,109,109,109,109,109,109,109, + 109,109,108,108,108,108,108,108,108,108,108,108,108,107,107,107,107,107,107,107,107,107,107,107,106,106,106,106,106,106,106,106, + 106,106,105,105,105,105,105,105,105,105,105,105,105,104,104,104,104,104,104,104,104,104,104,104,103,103,103,103,103,103,103,103, + 103,103,102,102,102,102,102,102,102,102,102,102,102,101,101,101,101,101,101,101,101,101,101,101,100,100,100,100,100,100,100,100, + 100,100,99,99,99,99,99,99,99,99,99,99,99,98,98,98,98,98,98,98,98,98,98,97,97,97,97,97,97,97,97,97, + 97,97,96,96,96,96,96,96,96,96,96,96,95,95,95,95,95,95,95,95,95,95,94,94,94,94,94,94,94,94,94,94, + 94,93,93,93,93,93,93,93,93,93,93,92,92,92,92,92,92,92,92,92,92,91,91,91,91,91,91,91,91,91,91,91, + 90,90,90,90,90,90,90,90,90,90,89,89,89,89,89,89,89,89,89,89,88,88,88,88,88,88,88,88,88,88,87,87, + 87,87,87,87,87,87,87,87,86,86,86,86,86,86,86,86,86,86,85,85,85,85,85,85,85,85,85,85,84,84,84,84, + 84,84,84,84,84,84,83,83,83,83,83,83,83,83,83,83,82,82,82,82,82,82,82,82,82,82,81,81,81,81,81,81, + 81,81,81,81,80,80,80,80,80,80,80,80,80,80,79,79,79,79,79,79,79,79,79,78,78,78,78,78,78,78,78,78, + 78,77,77,77,77,77,77,77,77,77,77,76,76,76,76,76,76,76,76,76,75,75,75,75,75,75,75,75,75,75,74,74, + 74,74,74,74,74,74,74,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,72,72,72,71,71,71,71,71,71, + 71,71,71,70,70,70,70,70,70,70,70,70,69,69,69,69,69,69,69,69,69,69,68,68,68,68,68,68,68,68,68,67, + 67,67,67,67,67,67,67,67,66,66,66,66,66,66,66,66,66,65,65,65,65,65,65,65,65,65,64,64,64,64,64,64, + 64,64,64,63,63,63,63,63,63,63,63,62,62,62,62,62,62,62,62,62,61,61,61,61,61,61,61,61,61,60,60,60, + 60,60,60,60,60,60,59,59,59,59,59,59,59,59,58,58,58,58,58,58,58,58,58,57,57,57,57,57,57,57,57,56, + 56,56,56,56,56,56,56,56,55,55,55,55,55,55,55,55,54,54,54,54,54,54,54,54,53,53,53,53,53,53,53,53, + 53,52,52,52,52,52,52,52,52,51,51,51,51,51,51,51,51,50,50,50,50,50,50,50,50,49,49,49,49,49,49,49, + 49,48,48,48,48,48,48,48,48,47,47,47,47,47,47,47,47,46,46,46,46,46,46,46,46,45,45,45,45,45,45,45, + 45,44,44,44,44,44,44,44,43,43,43,43,43,43,43,43,42,42,42,42,42,42,42,42,41,41,41,41,41,41,41,40, + 40,40,40,40,40,40,40,39,39,39,39,39,39,39,38,38,38,38,38,38,38,37,37,37,37,37,37,37,37,36,36,36, + 36,36,36,36,35,35,35,35,35,35,35,34,34,34,34,34,34,34,33,33,33,33,33,33,33,32,32,32,32,32,32,32, + 31,31,31,31,31,31,31,30,30,30,30,30,30,30,29,29,29,29,29,29,29,28,28,28,28,28,28,28,27,27,27,27, + 27,27,27,26,26,26,26,26,26,26,25,25,25,25,25,25,24,24,24,24,24,24,24,23,23,23,23,23,23,22,22,22, + 22,22,22,22,21,21,21,21,21,21,20,20,20,20,20,20,20,19,19,19,19,19,19,18,18,18,18,18,18,17,17,17, + 17,17,17,17,16,16,16,16,16,16,15,15,15,15,15,15,14,14,14,14,14,14,13,13,13,13,13,13,12,12,12,12, + 12,12,11,11,11,11,11,11,10,10,10,10,10,10,9,9,9,9,9,9,8,8,8,8,8,7,7,7,7,7,7,6, + 6,6,6,6,6,5,5,5,5,5,4,4,4,4,4,4,3,3,3,3,3,3,2,2,2,2,2,1,1,1,1,1, + 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; +#elif SCREENWIDTH == 128 +{ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 71, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; +#else +#error resolution not supported +#endif +const angle_t xtoviewangle[SCREENWIDTH + 1] = +#if SCREENWIDTH == 160 +{ 537395200, 532676608, 528482304, 524288000, 519569408, 514850816, 510656512, 505937920, 501219328, 496500736, 491782144, 486539264, 481820672, 476577792, 471859200, 466616320, 461373440, 456130560, 450887680, 445644800, 439877632, 434634752, 428867584, 423624704, 417857536, 412090368, 406323200, 400031744, 394264576, 387973120, 382205952, 375914496, 369623040, 363331584, 357040128, 350224384, 343932928, 337117184, 330825728, 324009984, 317194240, 310378496, 303562752, 296222720, 289406976, 282066944, 274726912, 267386880, 260046848, 252706816, 245366784, 238026752, 230162432, 222822400, 214958080, 207093760, 199229440, 191365120, 183500800, 175636480, 167772160, 159383552, 151519232, 143130624, 135266304, 126877696, 118489088, 110100480, 101711872, 93323264, 84934656, 76546048, 68157440, 59768832, 51380224, 42467328, 34078720, 25690112, 17301504, 8388608, 0, -8388608, -17301504, -25690112, -34078720, -42467328, -51380224, -59768832, -68157440, -76546048, -84934656, -93323264, -101711872, -110100480, -118489088, -126877696, -135266304, -143130624, -151519232, -159383552, -167772160, -175636480, -183500800, -191365120, -199229440, -207093760, -214958080, -222822400, -230162432, -238026752, -245366784, -252706816, -260046848, -267386880, -274726912, -282066944, -289406976, -296222720, -303562752, -310378496, -317194240, -324009984, -330825728, -337117184, -343932928, -350224384, -357040128, -363331584, -369623040, -375914496, -382205952, -387973120, -394264576, -400031744, -406323200, -412090368, -417857536, -423624704, -428867584, -434634752, -439877632, -445644800, -450887680, -456130560, -461373440, -466616320, -471859200, -476577792, -481820672, -486539264, -491782144, -496500736, -501219328, -505937920, -510656512, -514850816, -519569408, -524288000, -528482304, -532676608, -537395200, }; +#elif SCREENWIDTH == 240 +{ + 537395200,534249472,531628032,528482304,525336576,522715136,519569408,516423680, + 513802240,510656512,507510784,504365056,501219328,498073600,494927872,491782144, + 488636416,484966400,481820672,478674944,475004928,471859200,468189184,465043456, + 461373440,458227712,454557696,450887680,447217664,443547648,439877632,436207616, + 432537600,428867584,425197568,421527552,417857536,413663232,409993216,406323200, + 402128896,398458880,394264576,390070272,386400256,382205952,378011648,373817344, + 369623040,365428736,361234432,357040128,352845824,348127232,343932928,339738624, + 335020032,330825728,326107136,321912832,317194240,312475648,307757056,303562752, + 298844160,294125568,289406976,284688384,279969792,274726912,270008320,265289728, + 260046848,255328256,250609664,245366784,240648192,235405312,230162432,225443840, + 220200960,214958080,209715200,204472320,199229440,193986560,188743680,183500800, + 178257920,173015040,167772160,162004992,156762112,151519232,145752064,140509184, + 135266304,129499136,124256256,118489088,113246208,107479040,101711872,96468992, + 90701824,84934656,79691776,73924608,68157440,62390272,56623104,51380224, + 45613056,39845888,34078720,28311552,22544384,17301504,11534336,5767168, + 0,-5767168,-11534336,-17301504,-22544384,-28311552,-34078720,-39845888, + -45613056,-51380224,-56623104,-62390272,-68157440,-73924608,-79691776,-84934656, + -90701824,-96468992,-101711872,-107479040,-113246208,-118489088,-124256256,-129499136, + -135266304,-140509184,-145752064,-151519232,-156762112,-162004992,-167772160,-173015040, + -178257920,-183500800,-188743680,-193986560,-199229440,-204472320,-209715200,-214958080, + -220200960,-225443840,-230162432,-235405312,-240648192,-245366784,-250609664,-255328256, + -260046848,-265289728,-270008320,-274726912,-279969792,-284688384,-289406976,-294125568, + -298844160,-303562752,-307757056,-312475648,-317194240,-321912832,-326107136,-330825728, + -335020032,-339738624,-343932928,-348127232,-352845824,-357040128,-361234432,-365428736, + -369623040,-373817344,-378011648,-382205952,-386400256,-390070272,-394264576,-398458880, + -402128896,-406323200,-409993216,-413663232,-417857536,-421527552,-425197568,-428867584, + -432537600,-436207616,-439877632,-443547648,-447217664,-450887680,-454557696,-458227712, + -461373440,-465043456,-468189184,-471859200,-475004928,-478674944,-481820672,-484966400, + -488636416,-491782144,-494927872,-498073600,-501219328,-504365056,-507510784,-510656512, + -513802240,-516423680,-519569408,-522715136,-525336576,-528482304,-531628032,-534249472, + -537395200, +}; +#elif SCREENWIDTH == 128 +{ 537395200, 531628032, 526385152, 520617984, 514850816, 509607936, 503316480, 497549312, 491782144, 485490688, 479199232, 472907776, 466616320, 460324864, 453509120, 446693376, 439877632, 433061888, 426246144, 418906112, 412090368, 404750336, 397410304, 389545984, 382205952, 374341632, 366477312, 358612992, 350224384, 342360064, 333971456, 325582848, 317194240, 308805632, 299892736, 290979840, 282066944, 273154048, 263716864, 254803968, 245366784, 235929600, 226492416, 217055232, 207093760, 197656576, 187695104, 177733632, 167772160, 157286400, 147324928, 136839168, 126877696, 116391936, 105906176, 95420416, 84934656, 74448896, 63963136, 53477376, 42467328, 31981568, 21495808, 10485760, 0, -10485760, -21495808, -31981568, -42467328, -53477376, -63963136, -74448896, -84934656, -95420416, -105906176, -116391936, -126877696, -136839168, -147324928, -157286400, -167772160, -177733632, -187695104, -197656576, -207093760, -217055232, -226492416, -235929600, -245366784, -254803968, -263716864, -273154048, -282066944, -290979840, -299892736, -308805632, -317194240, -325582848, -333971456, -342360064, -350224384, -358612992, -366477312, -374341632, -382205952, -389545984, -397410304, -404750336, -412090368, -418906112, -426246144, -433061888, -439877632, -446693376, -453509120, -460324864, -466616320, -472907776, -479199232, -485490688, -491782144, -497549312, -503316480, -509607936, -514850816, -520617984, -526385152, -531628032, -537395200 }; +#else + #error resolution not supported +#endif +// TODO: maybe these value are not correct. +const fixed_t yslope[SCREENHEIGHT] = +#if SCREENHEIGHT == 128 && SCREENWIDTH == 160 +{ 110376, 112750, 115228, 117817, 120525, 123361, 126334, 129453, 132731, 136178, 139810, 143640, 147686, 151967, 156503, 161319, 166440, 171897, 177724, 183960, 190650, 197844, 205603, 213995, 223101, 233016, 243854, 255750, 268865, 283398, 299593, 317750, 338250, 361577, 388361, 419430, 455902, 499321, 551882, 616809, 699050, 806596, 953250, 1165084, 1497965, 2097152, 3495253, 10485760, 10485760, 3495253, 2097152, 1497965, 1165084, 953250, 806596, 699050, 616809, 551882, 499321, 455902, 419430, 388361, 361577, 338250, 317750, 299593, 283398, 268865, 255750, 243854, 233016, 223101, 213995, 205603, 197844, 190650, 183960, 177724, 171897, 166440, 161319, 156503, 151967, 147686, 143640, 139810, 136178, 132731, 129453, 126334, 123361, 120525, 117817, 115228, 112750, 110376, }; +#elif SCREENHEIGHT == 240 +{ + 91180,92070,92977,93902,94846,95808,96791,97794,98818,99864,100932,102023,103138,104278,105443,106634,107853,109100,110376,111682,113020,114390,115793,117232,118706,120218,121770,123361,124995,126673,128397,130168, + 131988,133860,135786,137769,139810,141912,144079,146312,148617,150994,153450,155986,158608,161319,164124,167029,170039,173159,176395,179755,183246,186874,190650,194581,198677,202950,207410,212071,216946,222051,227402,233016, + 238916,245121,251658,258552,265836,273541,281707,290374,299593,309415,319904,331129,343170,356120,370085,385191,401582,419430,438938,460350,483958,510118,539267,571950,608850,650840,699050,754974,820624,898779,993387,1110257, + 1258291,1451874,1715851,2097152,2696338,3774873,6291456,18874368,18874368,6291456,3774873,2696338,2097152,1715851,1451874,1258291,1110257,993387,898779,820624,754974,699050,650840,608850,571950,539267,510118,483958,460350,438938,419430,401582, + 385191,370085,356120,343170,331129,319904,309415,299593,290374,281707,273541,265836,258552,251658,245121,238916,233016,227402,222051,216946,212071,207410,202950,198677,194581,190650,186874,183246,179755,176395,173159,170039, + 167029,164124,161319,158608,155986,153450,150994,148617,146312,144079,141912,139810,137769,135786,133860,131988,130168,128397,126673,124995,123361,121770,120218,118706,117232,115793,114390,113020,111682,110376,109100,107853, + 106634,105443,104278,103138,102023,100932,99864,98818,97794,96791,95808,94846,93902,92977,92070,91180, +}; +#elif SCREENHEIGHT == 128 +{ 92347, 94074, 95865, 97727, 99662, 101675, 103772, 105957, 108235, 110614, 113100, 115700, 118422, 121276, 124270, 127416, 130726, 134212, 137889, 141773, 145882, 150237, 154860, 159776, 165015, 170608, 176595, 183016, 189923, 197370, 205426, 214168, 223687, 234091, 245510, 258100, 272051, 287597, 305027, 324707, 347100, 372811, 402636, 437648, 479329, 529785, 592112, 671061, 774301, 915083, 1118435, 1437988, 2013184, 3355306, 10065920, 10065920, 3355306, 2013184, 1437988, 1118435, 915083, 774301, 671061, 592112, 529785, 479329, 437648, 402636, 372811, 347100, 324707, 305027, 287597, 272051, 258100, 245510, 234091, 223687, 214168, 205426, 197370, 189923, 183016, 176595, 170608, 165015, 159776, 154860, 150237, 145882, 141773, 137889, 134212, 130726, 127416, 124270, 121276, 118422, 115700, 113100, 110614, 108235, 105957, 103772, 101675, 99662, 97727, 95865, 94074, 92347, 90683, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; +#else +//#error resolution not supported +{ 110376, 112750, 115228, 117817, 120525, 123361, 126334, 129453, 132731, 136178, 139810, 143640, 147686, 151967, 156503, 161319, 166440, 171897, 177724, 183960, 190650, 197844, 205603, 213995, 223101, 233016, 243854, 255750, 268865, 283398, 299593, 317750, 338250, 361577, 388361, 419430, 455902, 499321, 551882, 616809, 699050, 806596, 953250, 1165084, 1497965, 2097152, 3495253, 10485760, 10485760, 3495253, 2097152, 1497965, 1165084, 953250, 806596, 699050, 616809, 551882, 499321, 455902, 419430, 388361, 361577, 338250, 317750, 299593, 283398, 268865, 255750, 243854, 233016, 223101, 213995, 205603, 197844, 190650, 183960, 177724, 171897, 166440, 161319, 156503, 151967, 147686, 143640, 139810, 136178, 132731, 129453, 126334, 123361, 120525, 117817, 115228, 112750, 110376, }; + +#endif +const fixed_t distscale[SCREENWIDTH] = +#if SCREENWIDTH == 160 +{ 92789, 92154, 91600, 91056, 90456, 89867, 89355, 88790, 88235, 87691, 87157, 86578, 86068, 85512, 85021, 84490, 83968, 83457, 82957, 82470, 81944, 81478, 80976, 80529, 80050, 79582, 79126, 78639, 78204, 77742, 77328, 76888, 76459, 76042, 75635, 75207, 74822, 74418, 74054, 73671, 73300, 72939, 72589, 72224, 71895, 71552, 71221, 70902, 70593, 70295, 70007, 69730, 69445, 69188, 68924, 68672, 68430, 68198, 67977, 67767, 67568, 67365, 67185, 67005, 66845, 66686, 66538, 66400, 66272, 66155, 66048, 65952, 65866, 65789, 65723, 65664, 65619, 65584, 65558, 65542, 65537, 65541, 65557, 65582, 65617, 65661, 65720, 65785, 65861, 65946, 66042, 66148, 66265, 66392, 66528, 66677, 66836, 66994, 67173, 67353, 67554, 67754, 67963, 68183, 68414, 68655, 68908, 69171, 69425, 69711, 69988, 70274, 70572, 70879, 71199, 71529, 71871, 72198, 72562, 72912, 73271, 73642, 74024, 74387, 74791, 75174, 75602, 76007, 76424, 76852, 77290, 77703, 78165, 78599, 79083, 79540, 80007, 80485, 80931, 81431, 81897, 82421, 82909, 83407, 83915, 84436, 84968, 85456, 86011, 86522, 87099, 87630, 88174, 88727, 89292, 89804, 90389, 90989, 91532, 92083, }; +#elif SCREENWIDTH == 240 +{ + 92789,92364,92014,91600,91192,90854,90456,90063,89740,89355,88976,88603,88235,87871,87513,87157,86809,86407,86068,85733,85348,85021,84648,84332,83968,83660,83306,82957,82614,82277,81944,81616, + 81294,80976,80662,80354,80050,79709,79415,79126,78799,78520,78204,77894,77628,77328,77034,76743,76459,76180,75905,75635,75371,75078,74822,74573,74295,74054,73787,73556,73300,73049,72803,72589, + 72353,72122,71895,71674,71457,71221,71015,70813,70593,70401,70212,70007,69828,69634,69445,69279,69099,68924,68754,68589,68430,68274,68124,67977,67837,67700,67568,67427,67304,67185,67060,66950, + 66845,66735,66639,66538,66450,66359,66272,66198,66121,66048,65987,65924,65866,65813,65763,65723,65684,65649,65619,65594,65573,65558,65546,65539,65537,65539,65545,65557,65571,65592,65617,65646, + 65681,65720,65759,65808,65861,65919,65981,66042,66114,66191,66265,66351,66442,66528,66629,66725,66836,66940,67049,67173,67292,67415,67554,67686,67823,67963,68109,68259,68414,68573,68738,68908, + 69082,69260,69425,69615,69808,69988,70191,70379,70572,70791,70992,71199,71433,71649,71871,72097,72327,72562,72776,73021,73271,73527,73758,74024,74264,74542,74791,75046,75338,75602,75872,76146, + 76424,76708,76996,77290,77590,77856,78165,78479,78759,79083,79373,79666,80007,80311,80618,80931,81248,81571,81897,82230,82566,82909,83256,83610,83915,84279,84594,84968,85293,85678,86011,86350, + 86751,87099,87452,87811,88174,88541,88913,89292,89674,89997,90389,90787,91124,91532,91945,92293, +}; +#elif SCREENWIDTH == 128 +{ 92789, 92014, 91327, 90588, 89867, 89229, 88479, 87811, 87157, 86464, 85787, 85129, 84490, 83864, 83206, 82566, 81944, 81339, 80752, 80137, 79582, 79002, 78439, 77856, 77328, 76780, 76249, 75736, 75207, 74728, 74235, 73758, 73300, 72857, 72405, 71970, 71552, 71152, 70746, 70379, 70007, 69653, 69315, 68994, 68672, 68382, 68094, 67823, 67568, 67316, 67094, 66876, 66686, 66502, 66334, 66183, 66048, 65930, 65827, 65739, 65664, 65609, 65570, 65545, 65537, 65544, 65568, 65607, 65661, 65735, 65822, 65924, 66042, 66176, 66327, 66493, 66677, 66866, 67082, 67304, 67554, 67809, 68080, 68367, 68655, 68976, 69297, 69634, 69988, 70358, 70724, 71129, 71529, 71946, 72378, 72830, 73271, 73729, 74204, 74697, 75174, 75703, 76215, 76743, 77290, 77818, 78401, 78961, 79540, 80094, 80708, 81294, 81897, 82517, 83156, 83814, 84436, 85075, 85733, 86407, 87099, 87750, 88419, 89166, 89804, 90523, 91259, 91945 }; +#else +#error resolution not supported +#endif +#else +int viewangletox[4096]; +angle_t xtoviewangle[SCREENWIDTH + 1]; +fixed_t yslope[SCREENHEIGHT]; +fixed_t distscale[SCREENWIDTH]; +#endif + +//This must be SCREENHEIGHT - Status bar height. +const short screenheightarray[SCREENWIDTH_PHYSICAL] = +#if SCREENWIDTH_PHYSICAL == 160 +{ 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, }; +#elif SCREENWIDTH_PHYSICAL == 240 +{ + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, +}; +#elif SCREENWIDTH_PHYSICAL == 128 +{ 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111 }; +#else +#error resolution not supported +#endif + +const short negonearray[SCREENWIDTH_PHYSICAL] = +#if SCREENWIDTH_PHYSICAL == 160 +{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; +#elif SCREENWIDTH_PHYSICAL == 240 +{ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +}; +#elif SCREENWIDTH_PHYSICAL == 128 +{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; +#else +#error resolution not supported +#endif + + +const unsigned char translationtables[1023] = +{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 13, 240, 173, 186, 171, 171, 171, 171, 171, 171, 171, 171, 238, 254, 238, 254, 0, 0, 0, 0, 0, 0, 0, 0, 211, 182, 94, 166, 95, 130, 1, 28, 120, 0, 62, 1, 192, 111, 60, 1, 88, 140, 1, 0, 0, 0, 0 }; +#if SCREENWIDTH == 128 +const uint8_t scalelight[LIGHTLEVELS][MAXLIGHTSCALE] = +{ +{31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,30,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16}, +{31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,30,29,28,27,26,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12}, +{31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,30,29,28,27,26,25,24,23,22,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8}, +{31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,30,29,28,27,26,25,24,23,22,21,20,19,18,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4}, +{31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,30,29,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0}, +{31,31,31,31,31,31,31,31,31,31,31,30,29,28,27,26,25,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,10,9,8,7,6,5,4,3,2,1,0,0,0,0,0}, +{31,31,31,31,31,31,31,30,29,28,27,26,25,24,23,22,21,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,6,5,4,3,2,1,0,0,0,0,0,0,0,0,0}, +{31,31,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{28,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,13,12,11,10,9,8,7,6,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{24,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,9,8,7,6,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{20,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{16,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{12,12,11,10,9,8,7,6,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{8,8,7,6,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{4,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} +}; +#else +const uint8_t scalelight[LIGHTLEVELS][MAXLIGHTSCALE] = +{ + { + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1e,0x1e,0x1d,0x1d, + }, + { + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1e,0x1e,0x1d,0x1d,0x1c,0x1c,0x1b,0x1b,0x1a,0x1a,0x19,0x19, + }, + { + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1e,0x1e,0x1d,0x1d, + 0x1c,0x1c,0x1b,0x1b,0x1a,0x1a,0x19,0x19,0x18,0x18,0x17,0x17,0x16,0x16,0x15,0x15, + }, + { + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1e,0x1e,0x1d,0x1d,0x1c,0x1c,0x1b,0x1b,0x1a,0x1a,0x19,0x19, + 0x18,0x18,0x17,0x17,0x16,0x16,0x15,0x15,0x14,0x14,0x13,0x13,0x12,0x12,0x11,0x11, + }, + { + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1e,0x1e,0x1d,0x1d, + 0x1c,0x1c,0x1b,0x1b,0x1a,0x1a,0x19,0x19,0x18,0x18,0x17,0x17,0x16,0x16,0x15,0x15, + 0x14,0x14,0x13,0x13,0x12,0x12,0x11,0x11,0x10,0x10,0x0f,0x0f,0x0e,0x0e,0x0d,0x0d, + }, + { + 0x1f,0x1f,0x1f,0x1f,0x1e,0x1e,0x1d,0x1d,0x1c,0x1c,0x1b,0x1b,0x1a,0x1a,0x19,0x19, + 0x18,0x18,0x17,0x17,0x16,0x16,0x15,0x15,0x14,0x14,0x13,0x13,0x12,0x12,0x11,0x11, + 0x10,0x10,0x0f,0x0f,0x0e,0x0e,0x0d,0x0d,0x0c,0x0c,0x0b,0x0b,0x0a,0x0a,0x09,0x09, + }, + { + 0x1c,0x1c,0x1b,0x1b,0x1a,0x1a,0x19,0x19,0x18,0x18,0x17,0x17,0x16,0x16,0x15,0x15, + 0x14,0x14,0x13,0x13,0x12,0x12,0x11,0x11,0x10,0x10,0x0f,0x0f,0x0e,0x0e,0x0d,0x0d, + 0x0c,0x0c,0x0b,0x0b,0x0a,0x0a,0x09,0x09,0x08,0x08,0x07,0x07,0x06,0x06,0x05,0x05, + }, + { + 0x18,0x18,0x17,0x17,0x16,0x16,0x15,0x15,0x14,0x14,0x13,0x13,0x12,0x12,0x11,0x11, + 0x10,0x10,0x0f,0x0f,0x0e,0x0e,0x0d,0x0d,0x0c,0x0c,0x0b,0x0b,0x0a,0x0a,0x09,0x09, + 0x08,0x08,0x07,0x07,0x06,0x06,0x05,0x05,0x04,0x04,0x03,0x03,0x02,0x02,0x01,0x01, + }, + { + 0x14,0x14,0x13,0x13,0x12,0x12,0x11,0x11,0x10,0x10,0x0f,0x0f,0x0e,0x0e,0x0d,0x0d, + 0x0c,0x0c,0x0b,0x0b,0x0a,0x0a,0x09,0x09,0x08,0x08,0x07,0x07,0x06,0x06,0x05,0x05, + 0x04,0x04,0x03,0x03,0x02,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + }, + { + 0x10,0x10,0x0f,0x0f,0x0e,0x0e,0x0d,0x0d,0x0c,0x0c,0x0b,0x0b,0x0a,0x0a,0x09,0x09, + 0x08,0x08,0x07,0x07,0x06,0x06,0x05,0x05,0x04,0x04,0x03,0x03,0x02,0x02,0x01,0x01, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + }, + { + 0x0c,0x0c,0x0b,0x0b,0x0a,0x0a,0x09,0x09,0x08,0x08,0x07,0x07,0x06,0x06,0x05,0x05, + 0x04,0x04,0x03,0x03,0x02,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + }, + { + 0x08,0x08,0x07,0x07,0x06,0x06,0x05,0x05,0x04,0x04,0x03,0x03,0x02,0x02,0x01,0x01, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + }, + { + 0x04,0x04,0x03,0x03,0x02,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + }, + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + } +}; +#endif +const uint8_t zlight[LIGHTLEVELS][MAXLIGHTZ] = +{ + { + 0x00,0x1e,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x1a,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x16,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x12,0x1c,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x0e,0x18,0x1d,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x0a,0x14,0x19,0x1c,0x1e,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x06,0x10,0x15,0x18,0x1a,0x1c,0x1d,0x1e,0x1e,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x02,0x0c,0x11,0x14,0x16,0x18,0x19,0x1a,0x1a,0x1b,0x1b,0x1c,0x1c,0x1c,0x1d, + 0x1d,0x1d,0x1d,0x1d,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1e,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, + }, + { + 0x00,0x00,0x08,0x0d,0x10,0x12,0x14,0x15,0x16,0x16,0x17,0x17,0x18,0x18,0x18,0x19, + 0x19,0x19,0x19,0x19,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x1b,0x1b, + 0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b, + 0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1b,0x1c,0x1c,0x1c,0x1c, + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, + }, + { + 0x00,0x00,0x04,0x09,0x0c,0x0e,0x10,0x11,0x12,0x12,0x13,0x13,0x14,0x14,0x14,0x15, + 0x15,0x15,0x15,0x15,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x17,0x17, + 0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17, + 0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x18,0x18,0x18,0x18, + 0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18, + 0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18, + 0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18, + 0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18, + }, + { + 0x00,0x00,0x00,0x05,0x08,0x0a,0x0c,0x0d,0x0e,0x0e,0x0f,0x0f,0x10,0x10,0x10,0x11, + 0x11,0x11,0x11,0x11,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x13,0x13, + 0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13, + 0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x13,0x14,0x14,0x14,0x14, + 0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14, + 0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14, + 0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14, + 0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14,0x14, + }, + { + 0x00,0x00,0x00,0x01,0x04,0x06,0x08,0x09,0x0a,0x0a,0x0b,0x0b,0x0c,0x0c,0x0c,0x0d, + 0x0d,0x0d,0x0d,0x0d,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,0x0f,0x0f, + 0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f, + 0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x10,0x10,0x10,0x10, + 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, + 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, + 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, + 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, + }, + { + 0x00,0x00,0x00,0x00,0x00,0x02,0x04,0x05,0x06,0x06,0x07,0x07,0x08,0x08,0x08,0x09, + 0x09,0x09,0x09,0x09,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0b,0x0b, + 0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b, + 0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0c,0x0c,0x0c,0x0c, + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, + }, + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x02,0x03,0x03,0x04,0x04,0x04,0x05, + 0x05,0x05,0x05,0x05,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x07,0x07, + 0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07, + 0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x07,0x08,0x08,0x08,0x08, + 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, + 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, + 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, + 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08, + }, + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01, + 0x01,0x01,0x01,0x01,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x03,0x03, + 0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03, + 0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x04,0x04,0x04,0x04, + 0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04, + 0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04, + 0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04, + 0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04, + }, + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + }, +}; \ No newline at end of file diff --git a/doom/src/pdoom/Doom/source/v_video.c b/doom/src/pdoom/Doom/source/v_video.c new file mode 100644 index 0000000..ff20f36 --- /dev/null +++ b/doom/src/pdoom/Doom/source/v_video.c @@ -0,0 +1,897 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * + * DESCRIPTION: + * Gamma correction LUT stuff. + * Color range translation support + * Functions to draw patches (by post) directly to screen. + * Functions to blit a block to the screen. + * + * next-hack: + * restored gamma tables. + * Patches can be directly load from external flash. + * Adapted to 160x128 pix screen. + * Added support of partial framebuffer (Drawing limits) + * + *----------------------------------------------------------------------------- + */ +#pragma GCC optimize ("Ofast") // we need to compile this code to be as fast as possible. + +#include "doomdef.h" +#include "r_main.h" +#include "r_draw.h" +#include "m_bbox.h" +#include "w_wad.h" /* needed for color translation lump lookup */ +#include "v_video.h" +#include "i_video.h" +#include "lprintf.h" + +#include "global_data.h" + +#include "i_spi_support.h" + +// Now where did these came from? +const byte gammatable[5][256] = +{ +{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }, + +{ 2, 4, 5, 7, 8, 10, 11, 12, 14, 15, 16, 18, 19, 20, 21, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 214, 215, 216, 217, 218, 219, 220, 221, 222, 222, 223, 224, 225, 226, 227, 228, 229, 230, 230, 231, 232, 233, 234, 235, 236, 237, 237, 238, 239, 240, 241, 242, 243, 244, 245, 245, 246, 247, 248, 249, 250, 251, 252, 252, 253, 254, 255 }, + +{ 4, 7, 9, 11, 13, 15, 17, 19, 21, 22, 24, 26, 27, 29, 30, 32, 33, 35, 36, 38, 39, 40, 42, 43, 45, 46, 47, 48, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 153, 154, 155, 156, 157, 158, 159, 160, 160, 161, 162, 163, 164, 165, 166, 166, 167, 168, 169, 170, 171, 172, 172, 173, 174, 175, 176, 177, 178, 178, 179, 180, 181, 182, 183, 183, 184, 185, 186, 187, 188, 188, 189, 190, 191, 192, 193, 193, 194, 195, 196, 197, 197, 198, 199, 200, 201, 201, 202, 203, 204, 205, 206, 206, 207, 208, 209, 210, 210, 211, 212, 213, 213, 214, 215, 216, 217, 217, 218, 219, 220, 221, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231, 232, 233, 234, 235, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 250, 251, 251, 252, 253, 254, 254, 255 }, + +{ 8, 12, 16, 19, 22, 24, 27, 29, 31, 34, 36, 38, 40, 41, 43, 45, 47, 49, 50, 52, 53, 55, 57, 58, 60, 61, 63, 64, 65, 67, 68, 70, 71, 72, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 135, 136, 137, 138, 139, 140, 141, 142, 143, 143, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 160, 161, 162, 163, 164, 165, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 179, 180, 180, 181, 182, 183, 183, 184, 185, 186, 186, 187, 188, 189, 189, 190, 191, 192, 192, 193, 194, 195, 195, 196, 197, 197, 198, 199, 200, 200, 201, 202, 202, 203, 204, 205, 205, 206, 207, 207, 208, 209, 210, 210, 211, 212, 212, 213, 214, 214, 215, 216, 216, 217, 218, 219, 219, 220, 221, 221, 222, 223, 223, 224, 225, 225, 226, 227, 227, 228, 229, 229, 230, 231, 231, 232, 233, 233, 234, 235, 235, 236, 237, 237, 238, 238, 239, 240, 240, 241, 242, 242, 243, 244, 244, 245, 246, 246, 247, 247, 248, 249, 249, 250, 251, 251, 252, 253, 253, 254, 254, 255 }, + +{ 16, 23, 28, 32, 36, 39, 42, 45, 48, 50, 53, 55, 57, 60, 62, 64, 66, 68, 69, 71, 73, 75, 76, 78, 80, 81, 83, 84, 86, 87, 89, 90, 92, 93, 94, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 143, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 159, 160, 161, 162, 163, 163, 164, 165, 166, 166, 167, 168, 169, 169, 170, 171, 172, 172, 173, 174, 175, 175, 176, 177, 177, 178, 179, 180, 180, 181, 182, 182, 183, 184, 184, 185, 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194, 195, 195, 196, 196, 197, 198, 198, 199, 200, 200, 201, 202, 202, 203, 203, 204, 205, 205, 206, 207, 207, 208, 208, 209, 210, 210, 211, 211, 212, 213, 213, 214, 214, 215, 216, 216, 217, 217, 218, 219, 219, 220, 220, 221, 221, 222, 223, 223, 224, 224, 225, 225, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 239, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 254, 254, 255, 255 } }; + +/* + * V_DrawBackground tiles a 64x64 patch over the entire screen, providing the + * background for the Help and Setup screens, and plot text betwen levels. + * cphipps - used to have M_DrawBackground, but that was used the framebuffer + * directly, so this is my code from the equivalent function in f_finale.c + */ +void V_DrawBackground(const char *flatname) +{ + /* erase the entire screen to a tiled background */ + const byte *src; + int lump; + + uint8_t *dest = _g->screens[0].data; + + // killough 4/17/98: + src = W_CacheLumpNum(lump = _g->firstflat + R_FlatNumForName(flatname)); + + for (unsigned int y = draw_starty; y <= draw_stopy; y++) + { + byte srcdata[64]; + spiFlashSetAddress((uint32_t) src + ((y & 63) * 64)); + spiFlashGetData(srcdata, sizeof(srcdata)); + for (unsigned int x = 0; x < SCREENWIDTH_PHYSICAL; x += 64) + { + uint8_t *d = &dest[ ScreenYToOffset(y) + x]; + const byte *s = &srcdata[x & 63]; //&src[((y & 63) * 64) + (x & 63)]; + + unsigned int len = 64; + + if ((SCREENWIDTH_PHYSICAL - x) < 64) + len = SCREENWIDTH_PHYSICAL - x; + + memcpy(d, s, len); + } + } +} + +inline static void PatchDrawColPix(byte *dest, const byte *source, unsigned int frac) +{ + *dest = source[frac >> FRACBITS]; +} + +inline static void PatchDrawColumn(byte *dest, const byte *source, unsigned int frac, fixed_t fracstep, unsigned int count) +{ + unsigned int l = (count >> 4); + + while (l--) + { + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // + } + + unsigned int r = (count & 15); + + switch (r) + { + case 15: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 14: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 13: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 12: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 11: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 10: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 9: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 8: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 7: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 6: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 5: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 4: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 3: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 2: + PatchDrawColPix(dest, source, frac); + dest += SCREENWIDTH; + frac += fracstep; + // fall through, no break + case 1: + PatchDrawColPix(dest, source, frac); + } + +} + +/* + * This function draws at full resoulution (ie. not pixel doubled) + * so the st bar and menus don't look like garbage. + */ + +void V_DrawPatch(int x, int y, int scrn, const patch_t* patch) +{ + /* Paradise: full screen images are already at screen size and are drawn 1:1 */ + if (patch->width == SCREENWIDTH && patch->height == SCREENHEIGHT) + { + byte *dst = (byte*)_g->screens[scrn].data; + for (int cx = 0; cx < SCREENWIDTH; cx++) + { + const column_t *column = (const column_t *)((const byte*)patch + (0xFFFFFF & patch->columnofs[cx])); + const byte *src = (const byte*)column + 3; + for (int cy = 0; cy < SCREENHEIGHT; cy++) + dst[cy * SCREENPITCH + cx] = src[cy]; + } + return; + } + y -= patch->topoffset; + x -= patch->leftoffset; + + int col = 0; + + const int DX = (SCREENWIDTH<<16) / 320; + const int DXI = (320<<16) / SCREENWIDTH; + const int DY = ((SCREENHEIGHT<<16)) / 200; + const int DYI = (200<<16) / SCREENHEIGHT; + + byte* byte_topleft = (byte*)_g->screens[scrn].data; + const int byte_pitch = (SCREENPITCH); + + const int left = ( x * DX ) >> FRACBITS; + const int right = ((x + patch->width) * DX) >> FRACBITS; + const int bottom = ((y + patch->height) * DY) >> FRACBITS; + + + for (int dc_x=left; dc_x>16); + + if(dc_x < 0) + continue; + + const column_t* column = (const column_t *)((const byte*)patch + (0xFFFFFF & patch->columnofs[colindex])); + + if (dc_x >= SCREENWIDTH) + break; + + // step through the posts in a column + while (column->topdelta != 0xff) + { + const byte* source = (const byte*)column + 3; + const int topdelta = column->topdelta; + int dc_yl = (((y + topdelta) * DY) >> FRACBITS); + int dc_yh = (((y + topdelta + column->length) * DY) >> FRACBITS); + + if ((dc_yl >= SCREENHEIGHT) || (dc_yl > bottom)) + { + break; + } + int count = (dc_yh - dc_yl); + + byte* dest = byte_topleft + (dc_yl*byte_pitch) + dc_x; + + const fixed_t fracstep = DYI; + fixed_t frac = 0; + + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets. + + if (count > 0) + { + PatchDrawColumn(dest, source, frac, fracstep, count); + } + + column = (const column_t *)((const byte *)column + column->length + 4 ); + } + } +} + +// next-hack: this is used to convert GBA-specific graphics or coordinates +// (240 pix wide) to 160 pixel wide screens. TODO: instead of using this, we +// might want to use already resized graphics and/or already recalculated x +// values. This would improve both WAD size and drawing speed. +void V_DrawPatchXScale(int x, int y, const patch_t *patch) +{ + V_DrawPatchNoScale(x, y, patch); + return; + // + if (false == isOnExternalFlash(patch)) + { + x -= patch->leftoffset; + y -= patch->topoffset; + + int col = 0; + + const int DX = (SCREENWIDTH_PHYSICAL << 16) / 240; + const int DXI = (240 << 16) / SCREENWIDTH_PHYSICAL; + + byte *byte_topleft = (byte*) _g->screens[0].data; + const int byte_pitch = SCREENWIDTH_PHYSICAL; + + const int left = (x * DX) >> FRACBITS; + const int right = ((x + patch->width) * DX) >> FRACBITS; + const int bottom = (y + patch->height); + + for (int dc_x = left; dc_x < right; dc_x++, col += DXI) + { + + if (dc_x < 0) + continue; + if (dc_x >= SCREENWIDTH_PHYSICAL) + break; + + int colindex = (col >> 16); + + const column_t *column = (const column_t*) ((const byte*) patch + (patch->columnofs[colindex] & 0xFFFFFF) ); + + // step through the posts in a column + while (column->topdelta != 0xff) + { + const byte *source = (const byte*) column + 3; + const int topdelta = column->topdelta; + + int dc_yl = (y + topdelta); // (((y + topdelta) * DY) >> FRACBITS); + int dc_yh = (y + topdelta + column->length); //(((y + topdelta + column->length) * DY) >> FRACBITS); + + // 2021-03-15 next-hack clip to drawing buffer boundary + if (dc_yh > draw_stopy + 1) + { + dc_yh = draw_stopy + 1; + } + + if ((dc_yl > draw_stopy + 1) || (dc_yl > bottom)) + break; + + // and also update source + if (dc_yl < draw_starty) + { + int delta = draw_starty - dc_yl; + source += delta; + dc_yl = draw_starty; + } + // + int count = (dc_yh - dc_yl); + byte *dest = byte_topleft + (dc_yl * byte_pitch) + dc_x; + + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets + if (count > 0) + { + // PatchDrawColumn(dest, source, frac, fracstep, count); + unsigned int l = (count >> 4); + + while (l--) + { + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + } + unsigned int r = (count & 15); + + switch (r) + { + case 15: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 14: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 13: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 12: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 11: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 10: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 9: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 8: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 7: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 6: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 5: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 4: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 3: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 2: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 1: + *dest = *source++; + } + + } + column = (const column_t*) ((const byte*) column + column->length + 4); + } + } + } + else + { + // data in spi flash. we need a different strategy + // + // get patch address; + uint32_t address = spiFlashSetAddress((uint32_t) patch); + // now we need to load patch width, offsets and columnoffset + short width, height; + width = spiFlashGetShort(); + height = spiFlashGetShort(); // height, not used, but getting 2 bytes is cheaper than set the address again. + // remove offset + x -= spiFlashGetShort(); // patch->leftoffset; + y -= spiFlashGetShort(); // patch->topoffset; + // actually we should create a much smaller size. But we reserved a good deed of stack for this + + int columnofs[MAX_PATCH_COLOFFS]; + // read column offs + if (width <= MAX_PATCH_COLOFFS) + { + spiFlashGetData(columnofs, width * sizeof(columnofs[0])); + } + else + { + spiFlashGetData(columnofs, MAX_PATCH_COLOFFS * sizeof(columnofs[0])); + } + + int col = 0; + + const int DX = (SCREENWIDTH_PHYSICAL << 16) / 240; + const int DXI = (240 << 16) / SCREENWIDTH_PHYSICAL; + + byte *byte_topleft = (byte*) _g->screens[0].data; + const int byte_pitch = SCREENWIDTH_PHYSICAL; + + const int left = (x * DX) >> FRACBITS; + const int right = ((x + width) * DX) >> FRACBITS; + const int bottom = (y + height); + int coloffset = 0; + for (int dc_x = left; dc_x < right; dc_x++, col += DXI) + { + + if (dc_x < 0) + continue; + + if (dc_x >= SCREENWIDTH_PHYSICAL) + break; + + int colindex = (col >> 16); + + // workaround for too much wide patches + if (colindex - coloffset >= MAX_PATCH_COLOFFS) + { + // reload columnofs at the right point + coloffset = colindex; + spiFlashSetAddress((uint32_t) patch + 8 + 4 * coloffset); + if (width - coloffset <= MAX_PATCH_COLOFFS) + { + spiFlashGetData(columnofs, (width - coloffset) * sizeof(columnofs[0])); + } + else + { + spiFlashGetData(columnofs, MAX_PATCH_COLOFFS * sizeof(columnofs[0])); + } + } + spiFlashSetAddress(address + (columnofs[colindex - coloffset] & 0xFFFFFF)); + // + column_t columnInfo; + // read column info + spiFlashGetData(&columnInfo, sizeof(columnInfo)); + // reserve buffer in stack + uint8_t columnData[MAX_COLUMN_DATA]; + + // step through the posts in a column + while (columnInfo.topdelta != 0xff) + { + // ignore first byte. + spiFlashGetByte(); + // get SPI data based on length + spiFlashGetData(columnData, columnInfo.length); + // + const byte *source = (const byte*) columnData; + + const int topdelta = columnInfo.topdelta; + + int dc_yl = (y + topdelta); + int dc_yh = (y + topdelta + columnInfo.length); + + // 2021-03-15 next-hack clip to drawing buffer boundary + if (dc_yh > draw_stopy + 1) + { + dc_yh = draw_stopy + 1; + } + + if ((dc_yl > draw_stopy + 1) || (dc_yl > bottom)) + break; + + // and also update source + if (dc_yl < draw_starty) + { + int delta = draw_starty - dc_yl; + source += delta; + dc_yl = draw_starty; + } + // + int count = (dc_yh - dc_yl); + byte *dest = byte_topleft + (dc_yl * byte_pitch) + dc_x; + + // Inner loop that does the actual texture mapping, + // e.g. a DDA-lile scaling. + // This is as fast as it gets + if (count > 0) + { + unsigned int l = (count >> 4); + while (l--) + { + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // + } + unsigned int r = (count & 15); + + switch (r) + { + case 15: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 14: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 13: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 12: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 11: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 10: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 9: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 8: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 7: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 6: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 5: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 4: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 3: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 2: + *dest = *source++; + dest += SCREENWIDTH_PHYSICAL; + // fall through, no break + case 1: + *dest = *source++; + } + + } + // read again the column information + // ignore last post byte. + spiFlashGetByte(); + // read next info data (topdelta and length) + spiFlashGetData(&columnInfo, sizeof(columnInfo)); + } + } + } +} + +// CPhipps - some simple, useful wrappers for that function, for drawing patches from wads + +// CPhipps - GNU C only suppresses generating a copy of a function if it is +// static inline; other compilers have different behaviour. +// This inline is _only_ for the function below + +void V_DrawNumPatch(int x, int y, int scrn, int lump, int cm, enum patch_translation_e flags) +{ + V_DrawPatch(x, y, scrn, W_CacheLumpNum(lump)); +} + +// +// V_SetPalette +// +// CPhipps - New function to set the palette to palette number pal. +// Handles loading of PLAYPAL and calls I_SetPalette + +void V_SetPalette(int pal) +{ + I_SetPalette(pal); +} + +//Colour corrected PLAYPAL lumps ~ Kippykip +void V_SetPalLump(int index) +{ + if (index < 0) + index = 0; + else if (index > MAX_GAMMA) + index = MAX_GAMMA; +#if 0 + char lumpName[9] = "PLAYPAL0"; + + if(index == 0) + lumpName[7] = 0; + else + lumpName[7] = '0' + index; + + _g->palette_lump = W_CacheLumpName(lumpName); +#endif +} + +// +// V_FillRect +// +// CPhipps - New function to fill a rectangle with a given colour +void V_FillRect(int x, int y, int width, int height, byte colour) +{ + byte *fb = (byte*) _g->screens[0].data; + + byte *dest = &fb[(ScreenYToOffset(y) << 1) + x]; + + // 2021-03-15 next-hack: clip to boundary + + int ystop = y + height - 1; + + if (y < draw_starty) + { + // adjust height too; + height -= draw_starty - y; + y = draw_starty; + } + if (ystop > draw_stopy) + { + height -= ystop - draw_stopy; + } + if (height <= 0) + return; + while (height--) + { + memset(dest, colour, width); +#ifndef HIGHRES + dest += (SCREENPITCH << 1); +#else + dest += SCREENPITCH; +#endif + } +} + +static void V_PlotPixel(int x, int y, int color) +{ + byte *fb = (byte*) _g->screens[0].data; +#ifndef HIGHRES + uint16_t* dest = (uint16_t *) &fb[y * SCREENWIDTH_PHYSICAL + x * 2]; + *dest = color | ((uint16_t)color << 8); +#else + if (y > draw_stopy || y < draw_starty) + return; + byte *dest = &fb[y * SCREENWIDTH_PHYSICAL + x]; + *dest = color; +#endif +} + +// +// WRAP_V_DrawLine() +// +// Draw a line in the frame buffer. +// Classic Bresenham w/ whatever optimizations needed for speed +// +// Passed the frame coordinates of line, and the color to be drawn +// Returns nothing +// +void V_DrawLine(fline_t *fl, int color) +{ + + int x0 = fl->a.x; + int x1 = fl->b.x; + + int y0 = fl->a.y; + int y1 = fl->b.y; + + int dx = D_abs(x1 - x0); + int sx = x0 < x1 ? 1 : -1; + + int dy = -D_abs(y1 - y0); + int sy = y0 < y1 ? 1 : -1; + + int err = dx + dy; + + while (true) + { + V_PlotPixel(x0, y0, color); + + if (x0 == x1 && y0 == y1) + break; + + int e2 = 2 * err; + + if (e2 >= dy) + { + err += dy; + x0 += sx; + } + + if (e2 <= dx) + { + err += dx; + y0 += sy; + } + } +} diff --git a/doom/src/pdoom/Doom/source/version.c b/doom/src/pdoom/Doom/source/version.c new file mode 100644 index 0000000..1412dcb --- /dev/null +++ b/doom/src/pdoom/Doom/source/version.c @@ -0,0 +1,37 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Date stamp + * + *----------------------------------------------------------------------------- + */ + +#include "version.h" + +const char version_date[] = __DATE__; diff --git a/doom/src/pdoom/Doom/source/w_wad.c b/doom/src/pdoom/Doom/source/w_wad.c new file mode 100644 index 0000000..352e937 --- /dev/null +++ b/doom/src/pdoom/Doom/source/w_wad.c @@ -0,0 +1,735 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Handles WAD file header, directory, lump I/O. + * + * next-hack: + * Added code to load data from external flash. + * Added code to store/cache some wad data (And more) to internal flash. + * This latter might be moved sooner or later to a better place. + *----------------------------------------------------------------------------- + */ + +// use config.h if autoconf made one -- josh +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#ifdef HAVE_UNISTD_H +#include +#endif + +#include "doomstat.h" +#include "d_net.h" +#include "doomtype.h" +#include "i_system.h" + +#include "doom_iwad.h" + +#include "w_wad.h" +#include "lprintf.h" + +#include "global_data.h" +#include +#include "i_spi_support.h" +#include "nrf.h" +#include "main.h" +#define FLASH_ALIGNMENT 4 +/* Flash organization + * After 256k, 8k Aligned + * (4-byte word alignment) + * Wad CRC - used to determine, together with length, if the Wad has been changed. + * Wad Length - + * Wad immutableData CRC - To determine if the cache is ok, to speed up boot time. + * wad immutableDataLength + * Wad Number Of Lumps + * Address to Lump Offset Table + * Address to Lump Lengths Table + * Number of Sprite + * Address to Sprite Def table + * Address to level table + * + * Lump Offset Table + * Lump Offset Length + * + * + * + * Level Table Address: (origin 8kB alignd) + * Cached addresses + * + */ +#define getNumberOfLumps() (_g->numlumps) +uint32_t currentImmutableFlashOffset = 0; +uint32_t currentLevelFlashOffset = 0; +wad_immutable_flash_data_t *p_wad_immutable_flash_data; +wad_level_flash_data_t *p_wad_level_flash_data; +void **lumpPtrArray; +boolean lumpPtrArrayStoredInFlash = false; +void setCurrentImmutableFlashOffset(uint32_t offset) +{ + currentImmutableFlashOffset = offset; +} + +void** storeLumpArrayToFlash(boolean levelChanged) +{ + lumpPtrArrayStoredInFlash = true; + void **oldLumpPtrArrayAddress = lumpPtrArray; + if (levelChanged) + { + lumpPtrArray = writeBufferToFlashRegion(lumpPtrArray, getNumberOfLumps() * sizeof(void*), FLASH_LEVEL_REGION, true); + printf("changed, updated lumpAddressTable 0x%x\r\n", lumpPtrArray); + } + else + { // do not reload + lumpPtrArray = p_wad_immutable_flash_data->levelData->lumpAddressTable; + printf("level not changed, retrieving old lumpAddressTable 0x%x\r\n", lumpPtrArray); + } + Z_Free(oldLumpPtrArrayAddress); + return lumpPtrArray; +} +#if CACHE_ALL_COLORMAP_TO_RAM && defined(PDM_CMAPXIP) +/* 1.7.3 test17: no RAM copy (8.5 KB more for the zone): the Studio puts a copy of COLORMAP into the program part, read + * through the cached program window like the program's own tables */ +#include "pdmcfg.h" +#elif CACHE_ALL_COLORMAP_TO_RAM +#ifdef PARADISE_DEV +__attribute__((section(".ram20_bss"))) uint8_t ramColorMap[256 * 34]; +#else +uint8_t ramColorMap[256 * 34]; +#endif // this gives only marginal gain: about 500 us per frame on average. +#endif +void initImmutableFlashRegion() +{ + // use a temporary region in RAM + p_wad_immutable_flash_data = Z_Malloc(sizeof(*p_wad_immutable_flash_data), PU_STATIC, NULL); + spiFlashSetAddress(EXT_FLASH_BASE); // just to init SPI address + // create temporary lumpptr + lumpPtrArrayStoredInFlash = false; + lumpPtrArray = NULL; // this will force all cache functions to look everytime from the external flash + // get wad size + currentImmutableFlashOffset = 0; + spiFlashSetAddress((uint32_t) p_doom_iwad_len); + spiFlashGetData(&p_wad_immutable_flash_data->wadSize, 4); + spiFlashSetAddress((uint32_t) doom_iwad); + // get wad header (includes also number of lumps and lump table offset) + spiFlashGetData(&p_wad_immutable_flash_data->wadHeader, sizeof(p_wad_immutable_flash_data->wadHeader)); + // set size of this structure + p_wad_immutable_flash_data->immutableDataLength = sizeof(wad_immutable_flash_data_t); + currentImmutableFlashOffset = sizeof(wad_immutable_flash_data_t); + // get the palette + p_wad_immutable_flash_data->palette_lump = writeLumpToFlashRegion(W_GetNumForName("PLAYPAL"), FLASH_IMMUTABLE_REGION, true); + // get the colormap + p_wad_immutable_flash_data->colormaps = writeLumpToFlashRegion(W_GetNumForName("COLORMAP"), FLASH_IMMUTABLE_REGION, true); + // + #if CACHE_ALL_COLORMAP_TO_RAM && defined(PDM_CMAPXIP) + if (g_dcfg.version >= 3u && g_dcfg.cmap_off && g_dcfg.cmap_off != 0xFFFFFFFFu) + p_wad_immutable_flash_data->colormaps = (lighttable_t*) (0x100A0000u + g_dcfg.cmap_off - g_dcfg.code_off); + #elif CACHE_ALL_COLORMAP_TO_RAM +#ifdef PARADISE_DEV + { extern void plat_pram_copy(void *d, const void *s, unsigned n); plat_pram_copy(ramColorMap, p_wad_immutable_flash_data->colormaps, sizeof (ramColorMap)); } +#else + memcpy (ramColorMap, p_wad_immutable_flash_data->colormaps, sizeof (ramColorMap)); +#endif + p_wad_immutable_flash_data->colormaps = ramColorMap; + #endif +} +wad_level_flash_data_t* initLevelFlashRegion() +{ + p_wad_level_flash_data = Z_Malloc(sizeof(*p_wad_level_flash_data), PU_STATIC, NULL); + memset(p_wad_level_flash_data, 0, sizeof(*p_wad_level_flash_data)); + currentLevelFlashOffset = sizeof(*p_wad_level_flash_data); + return p_wad_level_flash_data; +} +void initLumpPtrTable(void) +{ + printf("Init ram lump table\r\n"); + lumpPtrArray = Z_Malloc(getNumberOfLumps() * sizeof(void*), PU_STATIC, NULL); + // init to 0xFF + memset(lumpPtrArray, 0xFF, getNumberOfLumps() * sizeof(void*)); + // + lumpPtrArrayStoredInFlash = false; + // update - just for sake of completeness, but we actually won't use it - colormaps and playpal lumps + lumpPtrArray[W_GetNumForName("COLORMAP")] = p_wad_immutable_flash_data->colormaps; + lumpPtrArray[W_GetNumForName("PLAYPAL")] = p_wad_immutable_flash_data->palette_lump; + // +} +void getFileLumpByNum(int n, filelump_t *fl) +{ + spiFlashSetAddress(WAD_ADDRESS + p_wad_immutable_flash_data->wadHeader.infotableofs + n * sizeof(filelump_t)); + spiFlashGetData(fl, sizeof(filelump_t)); +} +// get how much space we have in flash, taking into account if we already stored the lump pointer table or not. +int getUserFlashRegionRemainingSpace() +{ + int size = FLASH_CACHE_REGION_SIZE - (currentLevelFlashOffset + ((currentImmutableFlashOffset + FLASH_BLOCK_SIZE - 1) & ~(FLASH_BLOCK_SIZE - 1))); + // we need to take into account that we will need to store also the lumpPtrArray. + if (lumpPtrArrayStoredInFlash == 0) + size -= getNumberOfLumps() * sizeof(void*); + if (size < 0) + return 0; + return size; +} + +/* Paradise: erasing and writing is done by the platform (SPI flash) */ +void plat_flash_erase4k(uint32_t addr); +void plat_flash_word(uint32_t addr, uint32_t word); +void flashErasePage(uint32_t *pageAddress) +{ + plat_flash_erase4k((uint32_t) pageAddress); +} +void programFlashWord(uint32_t *address, uint32_t word) +{ + if (*address == 0xFFFFFFFF) + plat_flash_word((uint32_t) address, word); +} +void storeWordToFlash(uint32_t *dest, uint32_t word, uint8_t flashRegion, boolean isHeader) +{ + // first check if dest is compatible, i.e. is the same as sourceo r it is erased + if (!(*dest == word || *dest == 0xFFFFFFFF)) + { + // we need to erase before writing. However we need to find the limits... + uint32_t pageAddress = ((uint32_t) dest) & ~(FLASH_BLOCK_SIZE - 1); // page that will be erased + uint32_t startCopyAddress = pageAddress; + uint32_t stopCopyAddress = (uint32_t) dest; // copy up to the previous word. + // if we are writing in the same page as header, and it is not a header, then we need to skip the first bytes that will be used by the header + if (pageAddress == FLASH_IMMUTABLE_REGION_ADDRESS && !isHeader) + { + startCopyAddress = pageAddress + sizeof(wad_immutable_flash_data_t); + } + else if (flashRegion == FLASH_LEVEL_REGION && pageAddress == (uint32_t) p_wad_immutable_flash_data->levelData && !isHeader) + { + startCopyAddress = pageAddress + sizeof(wad_level_flash_data_t); + } + // now that we know from where to where (stop non inclusive) we need to copy, we can allocate enough buffer + // note! addresses are 4-byte aligned! + uint32_t *tmp = Z_Malloc((stopCopyAddress - startCopyAddress), PU_STATIC, NULL); + for (int i = 0; + i < (stopCopyAddress - startCopyAddress) / sizeof(uint32_t); + i++) + { + tmp[i] = *((uint32_t*) startCopyAddress + i); + } + // erase + printf("Erasing page 0x%08X Start Copy Addr 0x%08X Stop Copy Addr 0x%08X\r\n. ", pageAddress, startCopyAddress, stopCopyAddress); + flashErasePage((uint32_t*) pageAddress); + // write back everything + for (int i = 0; + i < (stopCopyAddress - startCopyAddress) / sizeof(uint32_t); + i++) + { + programFlashWord(((uint32_t*) startCopyAddress + i), tmp[i]); + } + // free buffer + Z_Free(tmp); + } + // write word + if (!(*dest == word)) + { + if (*dest == 0xFFFFFFFF) + programFlashWord(dest, word); + else + { + printf("trying to overwrite a non blank word: addr: 0x%08X old: 0x%08X new 0x%08X. Is Header: %d flash Region %d Blocking", dest, *dest, word, isHeader, flashRegion); + while (1); + } + } + // +} +/** + * @brief write the buffer to the flash region + */ + +void* writeBufferToFlashRegion(void *buffer, int size, uint8_t flashRegion, boolean updateSize) +{ + // todo check and eventually erase + uint32_t *address; + size = (size + FLASH_ALIGNMENT - 1) & ~(FLASH_ALIGNMENT - 1); + if (flashRegion == FLASH_IMMUTABLE_REGION) + { + address = (uint32_t*) (FLASH_ADDRESS + currentImmutableFlashOffset); + } + else + { + address = (uint32_t*) (FLASH_ADDRESS + currentLevelFlashOffset + ((currentImmutableFlashOffset + FLASH_BLOCK_SIZE - 1) & ~(FLASH_BLOCK_SIZE - 1))); + } + uint32_t *s = buffer; + uint32_t *d = address; + for (int i = 0; i < size / 4; i++) + { + storeWordToFlash(d++, *s++, flashRegion, false); + } + if (flashRegion == FLASH_IMMUTABLE_REGION) + { + currentImmutableFlashOffset += size; + } + else + { + currentLevelFlashOffset += size; + } + + if (updateSize) + { + if (flashRegion == FLASH_IMMUTABLE_REGION) + { + p_wad_immutable_flash_data->immutableDataLength += size; + } + else + { + p_wad_level_flash_data->dataLength += size; + } + + } + return address; +} + +void updateLumpAddresses(int lump, void *address) +{ + if (lumpPtrArray) + { + if (lumpPtrArrayStoredInFlash) + { + printf("Updating lump %d, address 0x%08X\r\n", lump, address); + if ((uint32_t) lumpPtrArray[lump] != 0xFFFFFFFF) + { + if (lumpPtrArray[lump] == address) + printf("Same lump address stored\r\n"); + else + { + printf("Different lump address! old: 0x%08X new: 0x%08X. Blocking \r\n", lumpPtrArray[lump], address); + while (1); + } + } + else + { + printf("Programming\r\n"); + programFlashWord((uint32_t*) &lumpPtrArray[lump], (uint32_t) address); + } + printf("Value now in Flash: 0x%08X\r\n", lumpPtrArray[lump]); + } + else + lumpPtrArray[lump] = address; + } +} +void* writeLumpToFlashRegion(int lumpnum, uint8_t flashRegion, boolean updateSize) +{ + uint32_t *address = 0; + filelump_t fl; + getFileLumpByNum(lumpnum, &fl); + // adjust to boundary + fl.size = (fl.size + FLASH_ALIGNMENT - 1) & ~(FLASH_ALIGNMENT - 1); + + // will it fit in flash? + if (fl.size > getUserFlashRegionRemainingSpace() && flashRegion != FLASH_IMMUTABLE_REGION) + { + address = (uint32_t*) (WAD_ADDRESS + fl.filepos); + updateLumpAddresses(lumpnum, address); + return address; + } + spiFlashSetAddress(WAD_ADDRESS + fl.filepos); + for (int i = 0; i < fl.size / 4; i++) + { + uint32_t data; + spiFlashGetData(&data, 4); + uint32_t *a = writeBufferToFlashRegion(&data, 4, flashRegion, updateSize); + if (i == 0) + { + address = a; + } + } + updateLumpAddresses(lumpnum, address); + return address; +} +/* + * @brief stores to flash the wad_immutable_flash_data_t. + * This function shall be called after all immutable data has been stored + * This also updates the position of where level data will start + * @param + * @return the address where it has been stored. + */ +void* storeFlashImmutableValues() +{ + // store header + uint32_t *src = (uint32_t*) p_wad_immutable_flash_data; + // update pointer to where the level data are going to be stored + + p_wad_immutable_flash_data->levelData = (wad_level_flash_data_t*) ((uint8_t*) FLASH_ADDRESS + ((p_wad_immutable_flash_data->immutableDataLength + FLASH_BLOCK_SIZE - 1) & ~(FLASH_BLOCK_SIZE - 1))); + for (int i = 0; i < sizeof(*p_wad_immutable_flash_data) / sizeof(uint32_t); + i++) + { + storeWordToFlash((uint32_t*) FLASH_ADDRESS + i, src[i], FLASH_IMMUTABLE_REGION, true); + } + // free block + Z_Free(p_wad_immutable_flash_data); + p_wad_immutable_flash_data = (void*) FLASH_ADDRESS; + return (uint32_t*) FLASH_ADDRESS; +} +void* storeLevelValues(boolean levelChanged) +{ + if (levelChanged) + { + // store header + uint32_t *src = (uint32_t*) p_wad_level_flash_data; + for (int i = 0; i < sizeof(*p_wad_level_flash_data) / sizeof(uint32_t); + i++) + { + storeWordToFlash((uint32_t*) p_wad_immutable_flash_data->levelData + i, src[i], FLASH_LEVEL_REGION, true); + } + } + printf("Freeing p_wad_level_flash_data %0x\r\n", (uint32_t) p_wad_level_flash_data); + Z_Free(p_wad_level_flash_data); + return (uint32_t*) p_wad_immutable_flash_data->levelData; +} +// +// GLOBALS +// +void ExtractFileBase(const char *path, char *dest) +{ + const char *src = path + strlen(path) - 1; + int length; + + // back up until a \ or the start + while (src != path && src[-1] != ':' // killough 3/22/98: allow c:filename + && *(src - 1) != '\\' && *(src - 1) != '/') + { + src--; + } + + // copy up to eight characters + memset(dest, 0, 8); + length = 0; + + while ((*src) && (*src != '.') && (++length < 9)) + { + *dest++ = toupper(*src); + src++; //nh fixed, it was *src++. + } + /* cph - length check removed, just truncate at 8 chars. + * If there are 8 or more chars, we'll copy 8, and no zero termination + */ +} + +// +// LUMP BASED ROUTINES. +// + +// +// W_AddFile +// All files are optional, but at least one file must be +// found (PWAD, if all required lumps are present). +// Files with a .wad extension are wadlink files +// with multiple lumps. +// Other files are single lumps with the base filename +// for the lump name. +// +// Reload hack removed by Lee Killough +// CPhipps - source is an enum +// +// proff - changed using pointer to wadfile_info_t +static void W_AddFile() +{ + + wadinfo_t header; + spiFlashSetAddress((uint32_t) p_doom_iwad_len); + uint32_t length; + spiFlashGetData(&length, sizeof(length)); + spiFlashSetAddress((uint32_t) doom_iwad); + if (length) + { + spiFlashGetData(&header, sizeof(header)); + if (strncmp(header.identification, "IWAD", 4)) + I_Error("W_AddFile: Wad file doesn't have IWAD id"); + + _g->numlumps = header.numlumps; + } +} + +//Return -1 if not found. +//Set lump ptr if found. +int lumpByNameRequest; +static int PUREFUNC FindLumpByName(const char *name, const filelump_t **lump) +{ + lumpByNameRequest++; + const wadinfo_t *header = (const wadinfo_t*) WAD_ADDRESS; + + spiFlashSetAddress((uint32_t) p_doom_iwad_len); + + uint32_t wadsize; + spiFlashGetData(&wadsize, sizeof(wadsize)); + + if (wadsize) + { + spiFlashSetAddress((uint32_t) &header->infotableofs); + + int infotableofs; + spiFlashGetData(&infotableofs, sizeof(infotableofs)); + + filelump_t fileinfo; + int_64_t nameint = 0; + strncpy((char*) &nameint, name, 8); +#if 0 + // next-hack: why is the "for" reversed? Oh, now I read the + // old doom code: to give priority to patches. However, reading + // in reverse order will kill speed drastically (some menu were drawn + // with single digit, generating also audio issues. Now we got 20fps. + for(int i = _g->numlumps - 1; i >= 0; i--) + { + //This is a bit naughty with alignment. + //For x86 doesn't matter because unaligned loads + //are fine. + //On ARM, unaligned loads are not fine but since it + //doesn't have a 64bit load, the compiler will generate + //32 bit loads. These vars are 32 aligned. + spiFlashSetAddress(infotableofs + WAD_ADDRESS + i * sizeof(filelump_t)); + spiFlashGetData(&fileinfo, sizeof (filelump_t)); + int_64_t nameint2 = *(int_64_t*)fileinfo.name; + + if(nameint == nameint2) + { + *lump = (filelump_t*) (infotableofs + WAD_ADDRESS) + i; + return i; + } + } +#else + spiFlashSetAddress(infotableofs + WAD_ADDRESS); + for (int i = 0; i < _g->numlumps; i++) + { + //This is a bit naughty with alignment. + //For x86 doesn't matter because unaligned loads + //are fine. + //On ARM, unaligned loads are not fine but since it + //doesn't have a 64bit load, the compiler will generate + //32 bit loads. These vars are 32 aligned. + spiFlashGetData(&fileinfo, sizeof(filelump_t)); + int_64_t nameint2 = *(int_64_t*) fileinfo.name; + + if (nameint == nameint2) + { + *lump = (filelump_t*) (infotableofs + WAD_ADDRESS) + i; + return i; + } + } +#endif + } + else + { + printf("Zero Wad Size!\r\n"); + } + *lump = NULL; + return -1; +} + +static const filelump_t* PUREFUNC FindLumpByNum(int num) +{ + wadinfo_t header; + if (num < 0) + return NULL; + spiFlashSetAddress((uint32_t) p_doom_iwad_len); + uint32_t wadLength; + spiFlashGetData(&wadLength, sizeof(uint32_t)); + if (wadLength) + { + spiFlashSetAddress((uint32_t) doom_iwad); + spiFlashGetData(&header, sizeof(header)); + + if (num >= header.numlumps) + { + return NULL; + } + return (filelump_t*) (WAD_ADDRESS + header.infotableofs + num * sizeof(filelump_t)); + } + return NULL; +} + +// +// W_CheckNumForName +// Returns -1 if name not found. +// +// Rewritten by Lee Killough to use hash table for performance. Significantly +// cuts down on time -- increases Doom performance over 300%. This is the +// single most important optimization of the original Doom sources, because +// lump name lookup is used so often, and the original Doom used a sequential +// search. For large wads with > 1000 lumps this meant an average of over +// 500 were probed during every search. Now the average is under 2 probes per +// search. There is no significant benefit to packing the names into longwords +// with this new hashing algorithm, because the work to do the packing is +// just as much work as simply doing the string comparisons with the new +// algorithm, which minimizes the expected number of comparisons to under 2. +// +// killough 4/17/98: add namespace parameter to prevent collisions +// between different resources such as flats, sprites, colormaps +// + +int PUREFUNC W_CheckNumForName(const char *name) +{ + const filelump_t *lump = NULL; + + return FindLumpByName(name, &lump); +} + +// W_GetNumForName +// Calls W_CheckNumForName, but bombs out if not found. +// +int PUREFUNC W_GetNumForName(const char *name) // killough -- const added +{ + int i = W_CheckNumForName(name); + + if (i == -1) + I_Error("W_GetNumForName: %.8s not found", name); + + return i; +} + +const char* PUREFUNC W_GetNameForNum(int lump) +{ + const filelump_t *l = FindLumpByNum(lump); + if (l) + { + return l->name; + } + + return NULL; +} + +// W_Init +// Loads each of the files in the wadfiles array. +// All files are optional, but at least one file +// must be found. +// Files with a .wad extension are idlink files +// with multiple lumps. +// Other files are single lumps with the base filename +// for the lump name. +// Lump names can appear multiple times. +// The name searcher looks backwards, so a later file +// does override all earlier ones. +// +// CPhipps - modified to use the new wadfiles array +// + +void W_Init(void) +{ + // CPhipps - start with nothing + + _g->numlumps = 0; + + W_AddFile(); + + if (!_g->numlumps) + I_Error("W_Init: No files found"); +} + +// +// W_LumpLength +// Returns the buffer size needed to load the given lump. +// + +int PUREFUNC W_LumpLength(int lump) +{ + const filelump_t *l = FindLumpByNum(lump); + + if (l) + { + spiFlashSetAddress((uint32_t) &l->size); + int size; + spiFlashGetData(&size, sizeof(size)); + return size; + } + + I_Error("W_LumpLength: %i >= numlumps", lump); + + return 0; +} + +static const void* PUREFUNC W_GetLumpPtr(int lump) +{ + const filelump_t *l = FindLumpByNum(lump); + + if (l) + { + spiFlashSetAddress((uint32_t) &l->filepos); + int filepos; + spiFlashGetData(&filepos, sizeof(filepos)); + return (const uint8_t*) WAD_ADDRESS + filepos; + } + return NULL; +} +void* getAddressOrCacheLumpNum(int lump, boolean storeInFlash, uint8_t flashRegion) +{ +#ifdef PARADISE + /* Paradise: all flash areas are equally fast, copying textures and flats gains nothing */ + if (flashRegion == FLASH_LEVEL_REGION) + storeInFlash = false; +#endif +// printf("Get addr: %d 0x%08x 0x%08x Lump Array in Flash %s\r\n", lump, lumpPtrArray[lump], lumpPtrArray, lumpPtrArrayStoredInFlash ? "yes" : "no"); + if (lump > _g->numlumps) + { + printf("Attempt to load a non existent lump. %d Blocking\r\n", lump); + while (1); + } + if (lumpPtrArray == NULL && !storeInFlash) + { + return (void*) W_GetLumpPtr(lump); + } + // + if (lumpPtrArray[lump] != (void*) 0xFFFFFFFF && lumpPtrArray[lump]) + return lumpPtrArray[lump]; + + void *address; + if (storeInFlash) + { + printf("Storing in flash\r\n"); + address = writeLumpToFlashRegion(lump, flashRegion, true); + } + else + { + address = (void*) W_GetLumpPtr(lump); + updateLumpAddresses(lump, address); + } + return address; + +} + +const void* /*PUREFUNC*/W_CacheLumpNum(int lump) +{ + + //return W_GetLumpPtr(lump); + // printf("Caching lump %d ... ", lump); + void *addr = getAddressOrCacheLumpNum(lump, false, 0); + // printf("cached to --> 0x%08x\r\n", addr); + return addr; +} diff --git a/doom/src/pdoom/Doom/source/wi_stuff.c b/doom/src/pdoom/Doom/source/wi_stuff.c new file mode 100644 index 0000000..796528b --- /dev/null +++ b/doom/src/pdoom/Doom/source/wi_stuff.c @@ -0,0 +1,1137 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * + * DESCRIPTION: + * Intermission screens. + * + * next-hack: + * added support for loading from external flash. + * Improved speed by loading most of the patches by number, and not by name. + * (the name to num conversion is done at startup) + *----------------------------------------------------------------------------- + */ + +#include "doomstat.h" +#include "m_random.h" +#include "w_wad.h" +#include "g_game.h" +#include "r_main.h" +#include "v_video.h" +#include "wi_stuff.h" +#include "s_sound.h" +#include "sounds.h" +#include "lprintf.h" // jff 08/03/98 - declaration of lprintf +#include "r_draw.h" + +#include "global_data.h" +#include "i_spi_support.h" +// +// Data needed to add patches to full screen intermission pics. +// Patches are statistics messages, and animations. +// Loads of by-pixel layout and placement, offsets etc. +// + +// +// Different vetween registered DOOM (1994) and +// Ultimate DOOM - Final edition (retail, 1995?). +// This is supposedly ignored for commercial +// release (aka DOOM II), which had 34 maps +// in one episode. So there. +#define NUMEPISODES 4 +#define NUMMAPS 9 + +// Not used +// in tics +//U #define PAUSELEN (TICRATE*2) +//U #define SCORESTEP 100 +//U #define ANIMPERIOD 32 +// pixel distance from "(YOU)" to "PLAYER N" +//U #define STARDIST 10 +//U #define WK 1 + +// GLOBAL LOCATIONS +#define WI_TITLEY 2 +#define WI_SPACINGY 33 + +// SINGLE-PLAYER STUFF +#define SP_STATSX 50 +#define SP_STATSY 50 + +#define SP_TIMEX 8 +// proff/nicolas 09/20/98 -- changed for hi-res +#define SP_TIMEY 160 +//#define SP_TIMEY (SCREENHEIGHT-32) + +// NET GAME STUFF +#define NG_STATSY 50 +#define NG_STATSX (32 + V_NamePatchWidth(star)/2 + 32*!dofrags) + +#define NG_SPACINGX 64 + +// Used to display the frags matrix at endgame +// DEATHMATCH STUFF +#define DM_MATRIXX 42 +#define DM_MATRIXY 68 + +#define DM_SPACINGX 40 + +#define DM_TOTALSX 269 + +#define DM_KILLERSX 10 +#define DM_KILLERSY 100 +#define DM_VICTIMSX 5 +#define DM_VICTIMSY 50 + +typedef struct +{ + int x; // x/y coordinate pair structure + int y; +} point_t; + +static const point_t lnodes[NUMEPISODES][NUMMAPS] = +{ + // Episode 0 World Map + { + { 185, 164 }, // location of level 0 (CJ) + { 148, 143 }, // location of level 1 (CJ) + { 69, 122 }, // location of level 2 (CJ) + { 209, 102 }, // location of level 3 (CJ) + { 116, 89 }, // location of level 4 (CJ) + { 166, 55 }, // location of level 5 (CJ) + { 71, 56 }, // location of level 6 (CJ) + { 135, 29 }, // location of level 7 (CJ) + { 71, 24 } // location of level 8 (CJ) + }, + + // Episode 1 World Map should go here + { + { 254, 25 }, // location of level 0 (CJ) + { 97, 50 }, // location of level 1 (CJ) + { 188, 64 }, // location of level 2 (CJ) + { 128, 78 }, // location of level 3 (CJ) + { 214, 92 }, // location of level 4 (CJ) + { 133, 130 }, // location of level 5 (CJ) + { 208, 136 }, // location of level 6 (CJ) + { 148, 140 }, // location of level 7 (CJ) + { 235, 158 } // location of level 8 (CJ) + }, + + // Episode 2 World Map should go here + { + { 156, 168 }, // location of level 0 (CJ) + { 48, 154 }, // location of level 1 (CJ) + { 174, 95 }, // location of level 2 (CJ) + { 265, 75 }, // location of level 3 (CJ) + { 130, 48 }, // location of level 4 (CJ) + { 279, 23 }, // location of level 5 (CJ) + { 198, 48 }, // location of level 6 (CJ) + { 140, 25 }, // location of level 7 (CJ) + { 281, 136 } // location of level 8 (CJ) + } +}; + +// +// GENERAL DATA +// + +// +// Locally used stuff. +// +#define FB 0 + +// States for single-player +#define SP_KILLS 0 +#define SP_ITEMS 2 +#define SP_SECRET 4 +#define SP_FRAGS 6 +#define SP_TIME 8 +#define SP_PAR ST_TIME + +#define SP_PAUSE 1 + +// in seconds +#define SHOWNEXTLOCDELAY 4 +//#define SHOWLASTLOCDELAY SHOWNEXTLOCDELAY + +// +// GRAPHICS +// + +// You Are Here graphic +static const char *const yah_names[2] = +{ "WIURH0", "WIURH1" }; + +// splat +static const char *const splat_name = "WISPLAT"; +// %, : graphics +static const char *percent_name = "WIPCNT"; +static const char *colon_name = "WICOLON"; + +// minus sign +static const char *wiminus_name = "WIMINUS"; + +// "Finished!" graphics +static const char *finished_name = "WIF"; + +// "Entering" graphic +static const char *entering_name = "WIENTER"; + +// "secret" +static const char *sp_secret_name = "WISCRT2"; + +// "Kills", "Scrt", "Items", "Frags" +static const char *kills_name = "WIOSTK"; +static const char *items_name = "WIOSTI"; + +// Time sucks. +static const char *time1_name = "WITIME"; +static const char *par_name = "WIPAR"; +static const char *sucks_name = "WISUCKS"; + +// "Total", your face, your dead face +static const char *total_name = "WIMSTT"; + +// lump numbers + +// You Are Here graphic +short yah_lumps[2]; + +// splat +short splat_lump; +// %, : graphics +short percent_lump; +short colon_lump; + +// minus sign +short wiminus_lump; + +// "Finished!" graphics +short finished_lump; + +// "Entering" graphic +short entering_lump; + +// "secret" +short sp_secret_lump; + +// "Kills", "Scrt", "Items", "Frags" +short kills_lump; +short items_lump; + +// Time sucks. +short time1_lump; +short par_lump; +short sucks_lump; + +// "Total", your face, your dead face +short total_lump; + +// +// CODE +// + +static void WI_endNetgameStats(void); +#define WI_endStats WI_endNetgameStats + +#define getPatchLump(patch) patch##_lump = W_GetNumForName(patch##_name) +void WI_Init(void) +{ + // You Are Here graphic + yah_lumps[0] = W_GetNumForName(yah_names[0]); + yah_lumps[1] = W_GetNumForName(yah_names[1]); + // splat + getPatchLump(splat); + // %, : graphics + getPatchLump(percent); + getPatchLump(colon); + + // minus sign + getPatchLump(wiminus); + + // "Finished!" graphics + getPatchLump(finished); + + // "Entering" graphic + getPatchLump(entering); + + // "secret" + getPatchLump(sp_secret); + + // "Kills", "Scrt", "Items", "Frags" + getPatchLump(kills); + getPatchLump(items); + + // Time sucks. + getPatchLump(time1); + getPatchLump(par); + getPatchLump(sucks); + + // "Total", your face, your dead face + getPatchLump(total); +} + +// ==================================================================== +// CPhipps - WI_endNetgameStats +// Purpose: Clean up coop game stats +// Args: none +// Returns: void +// +static void WI_endNetgameStats(void) +{ + _g->cnt_kills = -1; + _g->cnt_secret = -1; + _g->cnt_items = -1; +} + +/* ==================================================================== + * WI_levelNameLump + * Purpore: Returns the name of the graphic lump containing the name of + * the given level. + * Args: Episode and level, and buffer (must by 9 chars) to write to + * Returns: void + */ +void WI_levelNameLump(int epis, int map, char *buf) +{ + if (_g->gamemode == commercial) + { + sprintf(buf, "CWILV%2.2d", map); + } + else + { + sprintf(buf, "WILV%d%d", epis, map); + } +} + +// ==================================================================== +// WI_slamBackground +// Purpose: Put the full-screen background up prior to patches +// Args: none +// Returns: void +// +static void WI_slamBackground(void) +{ + char name[9]; // limited to 8 characters + + if (_g->gamemode == commercial || (_g->gamemode == retail && _g->wbs->epsd == 3)) + strcpy(name, "INTERPIC"); + else + sprintf(name, "WIMAP%d", _g->wbs->epsd); + + // background + V_DrawNamePatch(0, 0, FB, name, CR_DEFAULT, VPT_STRETCH); +} + +// ==================================================================== +// WI_Responder +// Purpose: Draw animations on intermission background screen +// Args: ev -- event pointer, not actually used here. +// Returns: False -- dummy routine +// +// The ticker is used to detect keys +// because of timing issues in netgames. +boolean WI_Responder(event_t *ev) +{ + return false; +} + +// ==================================================================== +// WI_drawLF +// Purpose: Draw the "Finished" level name before showing stats +// Args: none +// Returns: void +// +void WI_drawLF(void) +{ + int y = WI_TITLEY; + char lname[9]; + + // draw + /* cph - get the graphic lump name and use it */ + WI_levelNameLump(_g->wbs->epsd, _g->wbs->last, lname); + // CPhipps - patch drawing updated + V_DrawNamePatch((320 - V_NamePatchWidth(lname))/2, y, FB, lname, CR_DEFAULT, VPT_STRETCH); + + // draw "Finished!" + y += (5 * V_NamePatchHeight(lname)) / 4; + + // CPhipps - patch drawing updated +// V_DrawNamePatch((320 - V_NamePatchWidth(finished))/2, y, FB, finished, CR_DEFAULT, VPT_STRETCH); + V_DrawNumPatch((320 - R_NumPatchWidth(finished_lump)) / 2, y, FB, finished_lump, CR_DEFAULT, VPT_STRETCH); +} + +// ==================================================================== +// WI_drawEL +// Purpose: Draw introductory "Entering" and level name +// Args: none +// Returns: void +// +void WI_drawEL(void) +{ + int y = WI_TITLEY; + char lname[9]; + + /* cph - get the graphic lump name */ + WI_levelNameLump(_g->wbs->epsd, _g->wbs->next, lname); + + // draw "Entering" + // CPhipps - patch drawing updated + // V_DrawNamePatch((320 - V_NamePatchWidth(entering))/2, y, FB, entering, CR_DEFAULT, VPT_STRETCH); + V_DrawNumPatch((320 - R_NumPatchWidth(entering_lump)) / 2, y, FB, entering_lump, CR_DEFAULT, VPT_STRETCH); + // draw level + y += (5 * V_NamePatchHeight(lname)) / 4; + + // CPhipps - patch drawing updated + V_DrawNamePatch((320 - V_NamePatchWidth(lname))/2, y, FB, lname, CR_DEFAULT, VPT_STRETCH); +} + +/* ==================================================================== + * WI_drawOnLnode + * Purpose: Draw patches at a location based on episode/map + * Args: n -- index to map# within episode + * c[] -- array of names of patches to be drawn + * Returns: void + */ +void WI_drawOnLnode // draw stuff at a location by episode/map# +(int n, short *lumps) +{ + int i; + boolean fits = false; + + i = 0; + do + { + int left; + int top; + int right; + int bottom; + const patch_t *patch = W_CacheLumpNum(lumps[i]); //Name(c[i]); + patch_t tmpPatch; + // support for patch on external flash + if (isOnExternalFlash(patch)) + { + spiFlashSetAddress((uint32_t) patch); + spiFlashGetData(&tmpPatch, sizeof(tmpPatch)); + patch = &tmpPatch; + } + left = lnodes[_g->wbs->epsd][n].x - patch->leftoffset; + top = lnodes[_g->wbs->epsd][n].y - patch->topoffset; + right = left + patch->width; + bottom = top + patch->height; + if (left >= 0 && right < 320 && top >= 0 && bottom < 200) + { + fits = true; + } + else + { + i++; + } + } while (!fits && i != 2); + + if (fits && i < 2) + { + // CPhipps - patch drawing updated + V_DrawNumPatch(lnodes[_g->wbs->epsd][n].x, lnodes[_g->wbs->epsd][n].y, FB, lumps[i], CR_DEFAULT, VPT_STRETCH); + } + else + { + // DEBUG + //jff 8/3/98 use logical output routine + lprintf(LO_DEBUG, "Could not place patch on level %d", n + 1); + } +} + +// ==================================================================== +// WI_drawNum +// Purpose: Draws a number. If digits > 0, then use that many digits +// minimum, otherwise only use as many as necessary +// Args: x, y -- location +// n -- the number to be drawn +// digits -- number of digits minimum or zero +// Returns: new x position after drawing (note we are going to the left) +// CPhipps - static +static int WI_drawNum(int x, int y, int n, int digits) +{ + int fontwidth; + if (isOnExternalFlash(&_g->num[0]->width)) + { + spiFlashSetAddress((uint32_t) &_g->num[0]->width); + fontwidth = spiFlashGetShort(); + } + else + { + fontwidth = _g->num[0]->width; + } + int neg; + int temp; + + if (digits < 0) + { + if (!n) + { + // make variable-length zeros 1 digit long + digits = 1; + } + else + { + // figure out # of digits in # + digits = 0; + temp = n; + + while (temp) + { + temp /= 10; + digits++; + } + } + } + + neg = n < 0; + if (neg) + n = -n; + + // if non-number, do not draw it + if (n == 1994) + return 0; + + // draw the new number + while (digits--) + { + x -= fontwidth; + // CPhipps - patch drawing updated + V_DrawPatch(x, y, FB, _g->num[n % 10]); + n /= 10; + } + + // draw a minus sign if necessary + if (neg) + // CPhipps - patch drawing updated + V_DrawNumPatch(x -= 8, y, FB, wiminus_lump, CR_DEFAULT, VPT_STRETCH); + + return x; +} + +// ==================================================================== +// WI_drawPercent +// Purpose: Draws a percentage, really just a call to WI_drawNum +// after putting a percent sign out there +// Args: x, y -- location +// p -- the percentage value to be drawn, no negatives +// Returns: void +// CPhipps - static +static void WI_drawPercent(int x, int y, int p) +{ + if (p < 0) + return; + // CPhipps - patch drawing updated + V_DrawNumPatch(x, y, FB, percent_lump, CR_DEFAULT, VPT_STRETCH); + + WI_drawNum(x, y, p, -1); + +} + +// ==================================================================== +// WI_drawTime +// Purpose: Draws the level completion time or par time, or "Sucks" +// if 1 hour or more +// Args: x, y -- location +// t -- the time value to be drawn +// Returns: void +// +// CPhipps - static +// - largely rewritten to display hours and use slightly better algorithm + +static void WI_drawTime(int x, int y, int t) +{ + int n; + + if (t < 0) + return; + + if (t < 100 * 60 * 60) + for (;;) + { + n = t % 60; + t /= 60; + x = WI_drawNum(x, y, n, (t || n > 9) ? 2 : 1) - R_NumPatchWidth(colon_lump); + + // draw + if (t) + // CPhipps - patch drawing updated + V_DrawNumPatch(x, y, FB, colon_lump, CR_DEFAULT, VPT_STRETCH); + else + break; + } + else + // "sucks" (maybe should be "addicted", even I've never had a 100 hour game ;) + V_DrawNumPatch(x - R_NumPatchWidth(sucks_lump), y, FB, sucks_lump, CR_DEFAULT, VPT_STRETCH); +} + +// ==================================================================== +// WI_End +// Purpose: Unloads data structures (inverse of WI_Start) +// Args: none +// Returns: void +// +void WI_End(void) +{ + WI_endStats(); +} + +// ==================================================================== +// WI_initNoState +// Purpose: Clear state, ready for end of level activity +// Args: none +// Returns: void +// +void WI_initNoState(void) +{ + _g->state = NoState; + _g->acceleratestage = 0; + _g->cnt = 10; +} + +// ==================================================================== +// WI_drawTimeStats +// Purpose: Put the times on the screen +// Args: time, total time, par time, in seconds +// Returns: void +// +// cph - pulled from WI_drawStats below + +static void WI_drawTimeStats(int cnt_time, int cnt_total_time, int cnt_par) +{ + V_DrawNumPatch(SP_TIMEX, SP_TIMEY, FB, time1_lump, CR_DEFAULT, VPT_STRETCH); + WI_drawTime(320 / 2 - SP_TIMEX, SP_TIMEY, cnt_time); + + V_DrawNumPatch(SP_TIMEX, (SP_TIMEY + 200) / 2, FB, total_lump, CR_DEFAULT, VPT_STRETCH); + WI_drawTime(320 / 2 - SP_TIMEX, (SP_TIMEY + 200) / 2, cnt_total_time); + + // Ty 04/11/98: redid logic: should skip only if with pwad but + // without deh patch + // killough 2/22/98: skip drawing par times on pwads + // Ty 03/17/98: unless pars changed with deh patch + + if (_g->wbs->epsd < 3) + { + V_DrawNumPatch(320 / 2 + SP_TIMEX, SP_TIMEY, FB, par_lump, CR_DEFAULT, VPT_STRETCH); + WI_drawTime(320 - SP_TIMEX, SP_TIMEY, cnt_par); + } + +} + +// ==================================================================== +// WI_updateNoState +// Purpose: Cycle until end of level activity is done +// Args: none +// Returns: void +// +void WI_updateNoState(void) +{ + + if (!--_g->cnt) + G_WorldDone(); +} + +// ==================================================================== +// WI_initShowNextLoc +// Purpose: Prepare to show the next level's location +// Args: none +// Returns: void +// +void WI_initShowNextLoc(void) +{ + if ((_g->gamemode != commercial) && (_g->gamemap == 8)) + { + G_WorldDone(); + return; + } + + _g->state = ShowNextLoc; + _g->acceleratestage = 0; + + // e6y: That was pretty easy - only a HEX editor and luck + // There is no more desync on ddt-tas.zip\e4tux231.lmp + // --------- tasdoom.idb --------- + // .text:00031194 loc_31194: ; CODE XREF: WI_updateStats+3A9j + // .text:00031194 mov ds:state, 1 + // .text:0003119E mov ds:acceleratestage, 0 + // .text:000311A8 mov ds:cnt, 3Ch + // nowhere no hide + _g->cnt = SHOWNEXTLOCDELAY * TICRATE; + +} + +// ==================================================================== +// WI_updateShowNextLoc +// Purpose: Prepare to show the next level's location +// Args: none +// Returns: void +// +void WI_updateShowNextLoc(void) +{ + + if (!--_g->cnt || _g->acceleratestage) + WI_initNoState(); + else + _g->snl_pointeron = (_g->cnt & 31) < 20; +} + +// ==================================================================== +// WI_drawShowNextLoc +// Purpose: Show the next level's location on animated backgrounds +// Args: none +// Returns: void +// +void WI_drawShowNextLoc(void) +{ + int i; + int last; + + WI_slamBackground(); + + if (_g->gamemode != commercial) + { + if (_g->wbs->epsd > 2) + { + WI_drawEL(); // "Entering..." if not E1 or E2 + return; + } + + last = (_g->wbs->last == 8) ? _g->wbs->next - 1 : _g->wbs->last; + // draw a splat on taken cities. + for (i = 0; i <= last; i++) + WI_drawOnLnode(i, &splat_lump); + // splat the secret level? + if (_g->wbs->didsecret) + WI_drawOnLnode(8, &splat_lump); + // draw flashing ptr + if (_g->snl_pointeron) + WI_drawOnLnode(_g->wbs->next, yah_lumps); + } + + // draws which level you are entering.. + if ((_g->gamemode != commercial) || _g->wbs->next != 30) // check for MAP30 end game + WI_drawEL(); +} + +// ==================================================================== +// WI_drawNoState +// Purpose: Draw the pointer and next location +// Args: none +// Returns: void +// +void WI_drawNoState(void) +{ + _g->snl_pointeron = true; + WI_drawShowNextLoc(); +} + +// ==================================================================== +// WI_fragSum +// Purpose: Calculate frags for this player based on the current totals +// of all the other players. Subtract self-frags. +// Args: playernum -- the player to be calculated +// Returns: the total frags for this player +// +int WI_fragSum(int playernum) +{ + int frags = 0; + + // JDC hack - negative frags. + frags -= _g->plrs[playernum].frags[playernum]; + + return frags; +} + +// ==================================================================== +// WI_initStats +// Purpose: Get ready for single player stats +// Args: none +// Returns: void +// Comment: Seems like we could do all these stats in a more generic +// set of routines that weren't duplicated for dm, coop, sp +// + +void WI_initStats(void) +{ + _g->state = StatCount; + _g->acceleratestage = 0; + _g->sp_state = 1; + + _g->cnt_kills = -1; + _g->cnt_secret = -1; + _g->cnt_items = -1; + + _g->cnt_time = _g->cnt_par = _g->cnt_total_time = -1; + _g->cnt_pause = TICRATE; + +} + +// ==================================================================== +// WI_updateStats +// Purpose: Calculate solo stats +// Args: none +// Returns: void +// +void WI_updateStats(void) +{ + + if (_g->acceleratestage && _g->sp_state != 10) + { + _g->acceleratestage = 0; + _g->cnt_kills = (_g->plrs[_g->me].skills * 100) / _g->wbs->maxkills; + _g->cnt_items = (_g->plrs[_g->me].sitems * 100) / _g->wbs->maxitems; + + // killough 2/22/98: Make secrets = 100% if maxsecret = 0: + _g->cnt_secret = ( + _g->wbs->maxsecret ? (_g->plrs[_g->me].ssecret * 100) / _g->wbs->maxsecret : 100); + + _g->cnt_total_time = _g->wbs->totaltimes / TICRATE; + _g->cnt_time = _g->plrs[_g->me].stime / TICRATE; + _g->cnt_par = _g->wbs->partime / TICRATE; + S_StartSound(0, sfx_barexp); + _g->sp_state = 10; + } + + if (_g->sp_state == 2) + { + _g->cnt_kills += 2; + + if (!(_g->bcnt & 3)) + S_StartSound(0, sfx_pistol); + + if (_g->cnt_kills >= (_g->plrs[_g->me].skills * 100) / _g->wbs->maxkills) + { + _g->cnt_kills = (_g->plrs[_g->me].skills * 100) / _g->wbs->maxkills; + S_StartSound(0, sfx_barexp); + _g->sp_state++; + } + } + else if (_g->sp_state == 4) + { + _g->cnt_items += 2; + + if (!(_g->bcnt & 3)) + S_StartSound(0, sfx_pistol); + + if (_g->cnt_items >= (_g->plrs[_g->me].sitems * 100) / _g->wbs->maxitems) + { + _g->cnt_items = (_g->plrs[_g->me].sitems * 100) / _g->wbs->maxitems; + S_StartSound(0, sfx_barexp); + _g->sp_state++; + } + } + else if (_g->sp_state == 6) + { + _g->cnt_secret += 2; + + if (!(_g->bcnt & 3)) + S_StartSound(0, sfx_pistol); + + // killough 2/22/98: Make secrets = 100% if maxsecret = 0: + if (_g->cnt_secret >= ( + _g->wbs->maxsecret ? (_g->plrs[_g->me].ssecret * 100) / _g->wbs->maxsecret : 100)) + { + _g->cnt_secret = ( + _g->wbs->maxsecret ? (_g->plrs[_g->me].ssecret * 100) / _g->wbs->maxsecret : 100); + S_StartSound(0, sfx_barexp); + _g->sp_state++; + } + } + else if (_g->sp_state == 8) + { + if (!(_g->bcnt & 3)) + S_StartSound(0, sfx_pistol); + + _g->cnt_time += 3; + + if (_g->cnt_time >= _g->plrs[_g->me].stime / TICRATE) + _g->cnt_time = _g->plrs[_g->me].stime / TICRATE; + + _g->cnt_total_time += 3; + + if (_g->cnt_total_time >= _g->wbs->totaltimes / TICRATE) + _g->cnt_total_time = _g->wbs->totaltimes / TICRATE; + + _g->cnt_par += 3; + + if (_g->cnt_par >= _g->wbs->partime / TICRATE) + { + _g->cnt_par = _g->wbs->partime / TICRATE; + + if ((_g->cnt_time >= _g->plrs[_g->me].stime / TICRATE) && (_g->cnt_total_time >= _g->wbs->totaltimes / TICRATE)) + { + S_StartSound(0, sfx_barexp); + _g->sp_state++; + } + } + } + else if (_g->sp_state == 10) + { + if (_g->acceleratestage) + { + S_StartSound(0, sfx_sgcock); + + if (_g->gamemode == commercial) + WI_initNoState(); + else + WI_initShowNextLoc(); + } + } + else if (_g->sp_state & 1) + { + if (!--_g->cnt_pause) + { + _g->sp_state++; + _g->cnt_pause = TICRATE; + } + } +} + +// ==================================================================== +// WI_drawStats +// Purpose: Put the solo stats on the screen +// Args: none +// Returns: void +// +// proff/nicolas 09/20/98 -- changed for hi-res +// CPhipps - patch drawing updated +void WI_drawStats(void) +{ + // line height + int lh; + if (isOnExternalFlash(&_g->num[0]->height)) + { + spiFlashSetAddress((uint32_t) &_g->num[0]->height); + lh = (3 * spiFlashGetShort()) / 2; + } + else + { + lh = (3 * _g->num[0]->height) / 2; + } + + WI_slamBackground(); + + WI_drawLF(); + V_DrawNumPatch(SP_STATSX, SP_STATSY, FB, kills_lump, CR_DEFAULT, VPT_STRETCH); + if (_g->cnt_kills) + WI_drawPercent(320 - SP_STATSX, SP_STATSY, _g->cnt_kills); + + V_DrawNumPatch(SP_STATSX, SP_STATSY + lh, FB, items_lump, CR_DEFAULT, VPT_STRETCH); + + if (_g->cnt_items) + WI_drawPercent(320 - SP_STATSX, SP_STATSY + lh, _g->cnt_items); + + V_DrawNumPatch(SP_STATSX, SP_STATSY + 2 * lh, FB, sp_secret_lump, CR_DEFAULT, VPT_STRETCH); + + if (_g->cnt_secret) + WI_drawPercent(320 - SP_STATSX, SP_STATSY + 2 * lh, _g->cnt_secret); + + WI_drawTimeStats(_g->cnt_time, _g->cnt_total_time, _g->cnt_par); +} + +// ==================================================================== +// WI_checkForAccelerate +// Purpose: See if the player has hit either the attack or use key +// or mouse button. If so we set acceleratestage to 1 and +// all those display routines above jump right to the end. +// Args: none +// Returns: void +// +void WI_checkForAccelerate(void) +{ + player_t *player = &_g->player; + + if (_g->playeringame) + { + if (player->cmd.buttons & BT_ATTACK) + { + if (!player->attackdown) + _g->acceleratestage = 1; + player->attackdown = true; + } + else + player->attackdown = false; + + if (player->cmd.buttons & BT_USE) + { + if (!player->usedown) + _g->acceleratestage = 1; + player->usedown = true; + } + else + player->usedown = false; + } +} + +// ==================================================================== +// WI_Ticker +// Purpose: Do various updates every gametic, for stats, animation, +// checking that intermission music is running, etc. +// Args: none +// Returns: void +// +void WI_Ticker(void) +{ + // counter for general background animation + _g->bcnt++; + + if (_g->bcnt == 1) + { + // intermission music + if (_g->gamemode == commercial) + S_ChangeMusic(mus_dm2int, true); + else + S_ChangeMusic(mus_inter, true); + } + + WI_checkForAccelerate(); + + switch (_g->state) + { + case StatCount: + WI_updateStats(); + break; + + case ShowNextLoc: + WI_updateShowNextLoc(); + break; + + case NoState: + WI_updateNoState(); + break; + } +} + +/* ==================================================================== + * WI_loadData + * Purpose: Initialize intermission data such as background graphics, + * patches, map names, etc. + * Args: none + * Returns: void + * + * CPhipps - modified for new wad lump handling. + * - no longer preload most graphics, other funcs can use + * them by name + */ + +void WI_loadData(void) +{ + int i; + char name[9]; // limited to 8 characters + + for (i = 0; i < 10; i++) + { + // numbers 0-9 + sprintf(name, "WINUM%d", i); + + _g->num[i] = W_CacheLumpName(name); + } +} + +// ==================================================================== +// WI_Drawer +// Purpose: Call the appropriate stats drawing routine depending on +// what kind of game is being played (DM, coop, solo) +// Args: none +// Returns: void +// +void WI_Drawer(void) +{ + switch (_g->state) + { + case StatCount: + WI_drawStats(); + break; + + case ShowNextLoc: + WI_drawShowNextLoc(); + break; + + case NoState: + WI_drawNoState(); + break; + } +} + +// ==================================================================== +// WI_initVariables +// Purpose: Initialize the intermission information structure +// Note: wbstartstruct_t is defined in d_player.h +// Args: wbstartstruct -- pointer to the structure with the data +// Returns: void +// +void WI_initVariables(wbstartstruct_t *wbstartstruct) +{ + + _g->wbs = wbstartstruct; + + _g->acceleratestage = 0; + _g->cnt = _g->bcnt = 0; + _g->me = _g->wbs->pnum; + _g->plrs = _g->wbs->plyr; + + if (!_g->wbs->maxkills) + _g->wbs->maxkills = 1; // probably only useful in MAP30 + + if (!_g->wbs->maxitems) + _g->wbs->maxitems = 1; + + if (_g->gamemode != retail) + if (_g->wbs->epsd > 2) + _g->wbs->epsd -= 3; +} + +// ==================================================================== +// WI_Start +// Purpose: Call the various init routines +// Note: wbstartstruct_t is defined in d_player.h +// Args: wbstartstruct -- pointer to the structure with the +// intermission data +// Returns: void +// +void WI_Start(wbstartstruct_t *wbstartstruct) +{ + + WI_initVariables(wbstartstruct); + WI_loadData(); + + WI_initStats(); +} diff --git a/doom/src/pdoom/Doom/source/z_bmalloc.c b/doom/src/pdoom/Doom/source/z_bmalloc.c new file mode 100644 index 0000000..1b638ef --- /dev/null +++ b/doom/src/pdoom/Doom/source/z_bmalloc.c @@ -0,0 +1,165 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * This is designed to be a fast allocator for small, regularly used block sizes + * + * next-hack: modified to have low memory-overhead. Also removed block size + * (useless, as the zone already has the block size in its structure) and used + * bitwise flags to assess if a block is allocated) + *----------------------------------------------------------------------------- + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "doomtype.h" +#include "z_zone.h" +#include "z_bmalloc.h" +#include "lprintf.h" + +typedef struct bmalpool_s +{ + struct bmalpool_s *nextpool; + byte used[0]; +} bmalpool_t; + +#define numberOfBlocksToNumberOfBytes(n) (4 * ((n + 31)/32)) +__inline static void* getelem(bmalpool_t *p, size_t size, size_t n, struct block_memory_alloc_s *pzone) +{ + return (((byte*) p) + sizeof(bmalpool_t) + sizeof(byte) * numberOfBlocksToNumberOfBytes(pzone->perpool) + size * n); + +} + +__inline static PUREFUNC int iselem(const bmalpool_t *pool, size_t size, const void *p, struct block_memory_alloc_s *pzone) +{ + // CPhipps - need portable # of bytes between pointers + int dif = (const char*) p - (const char*) pool; + + dif -= sizeof(bmalpool_t); + dif -= sizeof(byte) * numberOfBlocksToNumberOfBytes(pzone->perpool); + if (dif < 0) + return -1; + dif /= size; + return (((size_t) dif >= pzone->perpool) ? -1 : dif); + +} + +enum +{ + unused_block = 0, used_block = 1 +}; +void setBlockUsageStatus(byte *usedArray, int n, int state) +{ + if (state == unused_block) + { + usedArray[n / 8] &= ~(1 << (n % 8)); + + } + else + { + usedArray[n / 8] |= (1 << (n % 8)); + } +} +int checkForBlockUsageStatus(byte *usedArray, int state, int number_to_check) +{ + for (int i = 0; i < number_to_check; i++) + { + int bit = usedArray[i / 8] & (1 << (i % 8)); + if ((state && bit) || (state == 0 && bit == 0)) + { + return i; + } + } + // not found + return -1; +} +void* Z_BMalloc(struct block_memory_alloc_s *pzone) +{ + register bmalpool_t **pool = (bmalpool_t**) &(pzone->firstpool); + while (*pool != NULL) + { + int n = checkForBlockUsageStatus((*pool)->used, unused_block, pzone->perpool); // Scan for unused marker + if (n != -1) + { + setBlockUsageStatus((*pool)->used, n, used_block); + return getelem(*pool, pzone->size, n, pzone); + } + else + pool = &((*pool)->nextpool); + } + { + // Nothing available, must allocate a new pool + bmalpool_t *newpool; + + // CPhipps: Allocate new memory, initialised to 0 + *pool = newpool = Z_Calloc(sizeof(*newpool) + (pzone->size) * (pzone->perpool) + numberOfBlocksToNumberOfBytes(pzone->perpool), 1, pzone->tag, NULL); + newpool->nextpool = NULL; + + // Return element 0 from this pool to satisfy the request + setBlockUsageStatus(newpool->used, 0, used_block); + return getelem(newpool, pzone->size, 0, pzone); + } +} + +boolean Z_BFree(struct block_memory_alloc_s *pzone, void *p) +{ + register bmalpool_t **pool = (bmalpool_t**) &(pzone->firstpool); + + while (*pool != NULL) + { + int n = iselem(*pool, pzone->size, p, pzone); + if (n >= 0) + { + setBlockUsageStatus((*pool)->used, n, unused_block); + if (-1 == checkForBlockUsageStatus(((*pool)->used), used_block, pzone->perpool)) + { + // Block is all unused, can be freed + bmalpool_t *oldpool = *pool; + *pool = (*pool)->nextpool; + Z_Free(oldpool); + } + return true; + } + else + pool = &((*pool)->nextpool); + } + return 0; +} diff --git a/doom/src/pdoom/Doom/source/z_zone.c b/doom/src/pdoom/Doom/source/z_zone.c new file mode 100644 index 0000000..f3d614d --- /dev/null +++ b/doom/src/pdoom/Doom/source/z_zone.c @@ -0,0 +1,421 @@ +/** + * Doom Port to the nRF52840 by Nicola Wrachien (next-hack in the comments) + * + * This port is based on the excellent doomhack's GBA Doom Port, + * with Kippykip additions. + * + * Several data structures and functions have been optimized + * to fit in only 256kB RAM of nRF52840 (GBA has 384 kB RAM). + * Z-Depth Light has been restored with almost no RAM consumption! + * Tons of speed optimizations have been done, and the game now + * runs extremely fast, despite the much higher 3D resolution with + * respect to GBA. + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * Copyright (C) 2021 Nicola Wrachien (next-hack in the comments) + * on nRF52840 port. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * DESCRIPTION: + * Zone Memory Allocation. Neat. + * + * Neat enough to be rewritten by Lee Killough... + * + * Must not have been real neat :) + * + * Made faster and more general, and added wrappers for all of Doom's + * memory allocation functions, including malloc() and similar functions. + * + * + * next-hack + * Changed back to old Zone.c because it makes no sense to use malloc, which + * also requires additional memory to store malloc'ed block information! + * Removed unused tags to keep the structure at a minimum size. + * Used short pointers and bitfields to reduce overhead to 8 bytes/block instead + * of 20 + malloc overhead (typically 8). + *----------------------------------------------------------------------------- + */ +#ifdef CPLUSPLUS +#error +#endif + +// use config.h if autoconf made one -- josh +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include "z_zone.h" +#include "doomstat.h" +#include "v_video.h" +#include "g_game.h" +#include "lprintf.h" +// +#include "global_data.h" +// Tunables + +// Minimum chunk size at which blocks are allocated. +// note: having 8 bytes per block allows using 15:bit pointers +// even for 256kB ram. On one hand, on some blocks it will waste +// 4 bytes, on the other, we keey the overhead under 8 bytes/block +// instead of having to switch to 12 bytes/block. +#define CHUNK_SIZE 8 +#ifndef MAX_STATIC_ZONE +#define MAX_STATIC_ZONE (113600) +#endif +#define MEM_ALIGN CHUNK_SIZE +//#define ZMALLOC_STAT + +// End Tunables + +typedef struct memblock +{ + unsigned int next_sptrdw:15; + unsigned int tag :2; + unsigned int prev_sptrdw:15; + unsigned short user_spptr; // short pointer to pointer. + unsigned short ssize; // short size +} memblock_t; +/* size of block header + * cph - base on sizeof(memblock_t), which can be larger than CHUNK_SIZE on + * 64bit architectures */ +static const int HEADER_SIZE = (sizeof(memblock_t) + CHUNK_SIZE - 1) & ~(CHUNK_SIZE - 1); + +static int free_memory = 0; +int zone_min_free = 0x7FFFFFFF; +static int largest_occupied = 0; + +typedef struct +{ + // start / end cap for linked list + memblock_t blocklist; + + // total bytes malloced, including header + int size; + + memblock_t *rover; + +} memzone_t; + +__attribute__ ((section(".displayData_bss"), aligned (CHUNK_SIZE))) uint8_t staticZone[MAX_STATIC_ZONE]; + +memzone_t *mainzone; +void* I_ZoneBase(int *size) +{ + *size = sizeof(staticZone); + return staticZone; +} +static inline unsigned short getShortPtrDW(void *ptr) +{ + return ( (unsigned int) ptr >> 3) & 0x7FFF; +} +static inline void *getLongPtrDW(unsigned short ptrdw) +{ + if (!ptrdw) + return 0; + return (void*) (RAM_PTR_BASE | ( ptrdw << 3)); +} +// +// Z_ClearZone +// +void Z_ClearZone(memzone_t *zone) +{ + memblock_t *block; + + // set the entire zone to one free block + block = (memblock_t*) ((byte*) zone + sizeof(memzone_t)); + + zone->blocklist.next_sptrdw = zone->blocklist.prev_sptrdw = getShortPtrDW(block); + + zone->blocklist.user_spptr = getShortPtr((void*) zone); + zone->blocklist.tag = PU_STATIC; + zone->rover = block; + + block->prev_sptrdw = block->next_sptrdw = getShortPtrDW(&zone->blocklist); + + // a free block. + block->tag = PU_FREE; + + block->ssize = (zone->size - sizeof(memzone_t)) >> 2; +} + +// +// Z_Init +// +void Z_Init(void) +{ + memblock_t *block; + int size; + + mainzone = (memzone_t*) I_ZoneBase(&size); + mainzone->size = size; + + // set the entire zone to one free block + block = (memblock_t*) ((byte*) mainzone + sizeof(memzone_t)); + mainzone->blocklist.next_sptrdw = mainzone->blocklist.prev_sptrdw = getShortPtrDW(block); + + mainzone->blocklist.user_spptr = getShortPtr((void*) mainzone); + mainzone->blocklist.tag = PU_STATIC; + mainzone->rover = block; + + block->prev_sptrdw = block->next_sptrdw = getShortPtrDW(&mainzone->blocklist); + + // free block + block->tag = PU_FREE; + + block->ssize = (mainzone->size - sizeof(memzone_t)) >> 2; +} + +extern inline unsigned short getShortPtr(void *longPtr); +static inline memblock_t* getMemblockPrev(memblock_t *mb) +{ + return (memblock_t*) getLongPtrDW(mb->prev_sptrdw); +} +static inline void** getMemblockUser(memblock_t *mb) +{ + return (void**) getLongPtr(mb->user_spptr); +} +static inline memblock_t* getMemblockNext(memblock_t *mb) +{ + return (memblock_t*) getLongPtrDW(mb->next_sptrdw); +} +// +// Z_Malloc +// You can pass a NULL user if the tag is < PU_PURGELEVEL. +// +#define MINFRAGMENT 32 + +void* Z_Malloc2(int size, int tag, void **user, const char *sz) +{ + int extra; + memblock_t *start; + memblock_t *rover; + memblock_t *newblock; + memblock_t *base; + void *result; + + if (!size) + return user ? *user = NULL : NULL; // malloc(0) returns NULL + + size = (size + MEM_ALIGN - 1) & ~(MEM_ALIGN - 1); + + // scan through the block list, + // looking for the first free block + // of sufficient size, + // throwing out any purgable blocks along the way. + + // account for size of block header + size += sizeof(memblock_t); + + // if there is a free block behind the rover, + // back up over them + base = mainzone->rover; + + if (getMemblockPrev(base)->tag == PU_FREE) + base = getMemblockPrev(base); + + rover = base; + start = getMemblockPrev(base); + + do + { + if (rover == start) + { + // scanned all the way around the list + printf("Z_Malloc: failed on allocation of %i bytes", size); +#ifdef PDM_MOREZONE + { extern void plat_oom(unsigned size, int used); plat_oom((unsigned) size, -free_memory); } /* 1.7.3 test17: a map too big for the RAM: show it, the wheel goes back */ +#endif + while (1); + } + if (rover->tag != PU_FREE) + { + if (rover->tag < PU_PURGELEVEL) + { + // hit a block that can't be purged, + // so move base past it + base = rover = getMemblockNext(rover); + } + else + { + // free the rover block (adding the size to base) + + // the rover can be the base block + base = getMemblockPrev(base); + Z_Free((byte*) rover + sizeof(memblock_t)); + base = getMemblockNext(base); + rover = getMemblockNext(base); + } + } + else + { + rover = getMemblockNext(rover); + } + + } while (base->tag != PU_FREE || (base->ssize << 2) < size); + + // found a block big enough + extra = (base->ssize << 2) - size; + + if (extra > MINFRAGMENT) + { + // there will be a free fragment after the allocated block + newblock = (memblock_t*) ((byte*) base + size); + newblock->ssize = extra >> 2; + + newblock->tag = PU_FREE; + newblock->user_spptr = 0; + newblock->prev_sptrdw = getShortPtrDW(base); + newblock->next_sptrdw = base->next_sptrdw; + getMemblockNext(newblock)->prev_sptrdw = getShortPtrDW(newblock); + + base->next_sptrdw = getShortPtrDW(newblock); + base->ssize = size >> 2; + } + free_memory -= base->ssize << 2; + if (free_memory < zone_min_free) zone_min_free = free_memory; + // no need to write else base->ssize = base->ssize... + // + + if (user == NULL && tag >= PU_PURGELEVEL) + { + printf("Z_Malloc: an owner is required for purgable blocks"); + while (1); + } + uint16_t userspptr = getShortPtr(user); + + base->user_spptr = userspptr; + base->tag = tag; + + result = (void*) ((byte*) base + sizeof(memblock_t)); + + if (user) // if there is a user + *user = result; // set user to point to new block + + // next allocation will start looking here + mainzone->rover = getMemblockNext(base); + +#ifdef ZMALLOC_STAT + if (free_memory < largest_occupied) + largest_occupied = free_memory; + printf("Mall: occ. %d lrgst %d Addr %04x. BlkSz %d %s\r\n", -free_memory, -largest_occupied, getShortPtr(base), (base->ssize << 2), sz); +#endif + + return result; +} + +void (Z_Free)(void *p) +{ + memblock_t *block = (memblock_t*) ((char*) p - HEADER_SIZE); + + if (!p) + return; + + if (block->user_spptr && block->tag != PU_FREE) // Nullify user if one exists + { + *(getMemblockUser(block)) = NULL; + } + // free memory + free_memory += (block->ssize << 2); + + // mark this block as free + block->tag = PU_FREE; + block->user_spptr = 0; + + // + memblock_t *other = getMemblockPrev(block); + // + if (other->tag == PU_FREE) + { + // merge with previous free block + other->ssize += block->ssize; + other->next_sptrdw = block->next_sptrdw; + getMemblockNext(other)->prev_sptrdw = getShortPtrDW(other); + + if (block == mainzone->rover) + mainzone->rover = other; + + block = other; + } + + other = getMemblockNext(block); + if (other->tag == PU_FREE) + { + // merge the next free block onto the end + block->ssize += other->ssize; + block->next_sptrdw = other->next_sptrdw; + getMemblockNext(block)->prev_sptrdw = getShortPtrDW(block); + + if (other == mainzone->rover) + mainzone->rover = block; + } +#ifdef ZMALLOC_STAT + printf("Free: occ. %d lrgst %d Addr %04x. BlkSz %d\r\n", -free_memory, -largest_occupied, getShortPtr(block), (block->ssize << 2)); +#endif +} + +void Z_FreeTags(int lowtag, int hightag) +{ + memblock_t *block; + memblock_t *next; + + for (block = getMemblockNext(&mainzone->blocklist); + block != &mainzone->blocklist; block = next) + { + // get link before freeing + next = getMemblockNext(block); + + // free block? + if (block->tag == PU_FREE) + continue; + + if (block->tag >= lowtag && block->tag <= hightag) + Z_Free((byte*) block + sizeof(memblock_t)); + } +} + +void* (Z_Realloc)(void *ptr, size_t n, int tag, void **user) +{ + void *p = Z_Malloc(n, tag, user DA(file, line)); + if (ptr) + { + memblock_t *block = (memblock_t*) ((char*) ptr - HEADER_SIZE); + memcpy(p, ptr, n <= (block->ssize << 2) ? n : (block->ssize << 2)); + (Z_Free)(ptr DA(file, line)); + if (user) // in case Z_Free nullified same user + *user = p; + } + return p; +} + +void* (Z_Calloc)(size_t n1, size_t n2, int tag, void **user) +{ + return (n1 *= n2) ? memset(Z_Malloc(n1, tag, user DA(file, line)), 0, n1) : NULL; +} + +char* (Z_Strdup)(const char *s, int tag, void **user) +{ + return strcpy(Z_Malloc(strlen(s) + 1, tag, user DA(file, line)), s); +} diff --git a/doom/src/pdoom/dev/build_dev.sh b/doom/src/pdoom/dev/build_dev.sh new file mode 100644 index 0000000..760e8c5 --- /dev/null +++ b/doom/src/pdoom/dev/build_dev.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Build DOOM for the Paradise: pram.bin (into program memory, loaded by the stub) and xip.bin (flash window) +set -e +cd "$(dirname "$0")/.." +# 1.7.3 test17 PDM_MOREZONE (menu build without the Paradise): one flat cache, fault stack at 0x20000800, zone 64 KB +ZDEF=57344; case "$XCF" in *DOOM_FREE*) ZDEF=74240; XCF="$XCF -DPDM_MOREZONE -DPDM_CMAPXIP -DPDM_SSFLASH";; esac +CF="-mcpu=cortex-m3 -mthumb -O2 -ffunction-sections -fdata-sections -IDoom/include -Iplat -Idev -w -DPARADISE -DPARADISE_DEV -DPDOOM_W=128 -DPDOOM_H=128 -DMAX_STATIC_ZONE=${ZONE:-$ZDEF} -DCACHE_ALL_COLORMAP_TO_RAM=1 -DXIP_FLUSH -DFRAME_ROW -DFAST_LCD -DLCD_FASTCLK -DTONE_FIX -DBL_SLEEP -DNO_STACK_SWITCH -DSINGLE_FB -DUA_FIX -DCHG_WITH_C -DMUS_PLAY -DSND_TOGGLE -DCLEAN -DSTBAR_LUMP -DKEYMAP -DPMXL_BACK -DPARA_BACK -DGPLAY -DDOOM_EXITKEY -DPDM_ONE_EPI -DPDM_E4 -DPDM_PKREG -DPDM_LUMPTXT -DPDM_GROUPCHUNK $XCF" +mkdir -p dev/obj; rm -f dev/obj/*.o +for f in Doom/source/*.c plat/printf.c dev/paradise.c dev/glue.c dev/hw.c dev/flash.c dev/libc_extra.c; do + [ -f $f ] || continue + n=$(basename $f .c); arm-none-eabi-gcc $CF -c $f -o dev/obj/$n.o; done +cd dev +arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -nostartfiles --specs=nano.specs -Wl,--gc-sections -Wl,-Map=doom.map -T ${LDS:-paradise_sram.ld} obj/*.o -lc -lgcc -lnosys -o doom.elf 2>&1 | grep -v "warning\|note:" || true +# 1.7.2 DOOM_FREE: what runs before hw_init (the flash window only works after it) must be in the PRAM +case "$XCF" in *DOOM_FREE*) for f in Reset_Handler para_clock para_mailbox para_leave_mark hw_init; do + a=$(arm-none-eabi-nm doom.elf | awk -v f=$f '$3==f || index($3, f".")==1 {print $1; exit}') + [ -z "$a" ] || [ $((0x$a)) -lt $((0x10000000)) ] || { echo "build_dev.sh: $f is in the flash window (0x$a)"; exit 1; } +done;; esac +arm-none-eabi-objcopy -O binary -j .pram -j .data doom.elf pram.bin +arm-none-eabi-objcopy -O binary -j .r20 -j .xip -j .ARM.exidx doom.elf xip.bin +arm-none-eabi-size -A doom.elf | grep -v "debug\|^$" +ls -l pram.bin xip.bin diff --git a/doom/src/pdoom/dev/disp_power.h b/doom/src/pdoom/dev/disp_power.h new file mode 100644 index 0000000..d8ecb83 --- /dev/null +++ b/doom/src/pdoom/dev/disp_power.h @@ -0,0 +1,5 @@ +// Taken from the original flash utility (same PRAM/post-reset context as +// our app). Order kept exactly. The clk tail (reset release) comes first, +// then the display/GPIO/backlight registers. +__attribute__((section(".initdata"))) static const unsigned int disp_power_seq[][2]={{0x45000020,0x40},{0x45000210,0x0},{0x45000214,0x0},{0x45000218,0x0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000020,0x42},{0x4003a000,0x8000},{0x4003a004,0x8000},{0x4003a004,0x8001},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40007034,0x0},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x4001803c,0xffffffff},{0x4001903c,0xfffff5df},{0x4001a03c,0xffffffff},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a56},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a59},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a65},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a95},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a55},{0x40018004,0x20},{0x40018000,0xffffffef},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xffffffef},{0x40018008,0x15008855},{0x40018004,0x10},{0x40018000,0xffffffcf},{0x40018008,0x15008855},{0x40018004,0x30},{0x40018000,0xffffffcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15028055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15088055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15208055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15808055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x16008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x19008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x25008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x15008055},{0x40019004,0xa00},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55996800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55999800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x559a5800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x55995800},{0x40019004,0x820},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800},{0x40019004,0x220},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x56995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x59995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x65995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x95995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x55995800},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x52},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x58},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x60},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x90},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x50},{0x40003000,0x0},{0x40003018,0x0},{0x4000301c,0x0},{0x40003020,0x0},{0x40003024,0x0},{0x40003014,0x0},{0x40003000,0x2},{0x40003008,0x0},{0x4000303c,0x1f},{0x40003000,0x1},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800}}; +#define DISP_POWER_N 262 diff --git a/doom/src/pdoom/dev/flash.c b/doom/src/pdoom/dev/flash.c new file mode 100644 index 0000000..64720d7 --- /dev/null +++ b/doom/src/pdoom/dev/flash.c @@ -0,0 +1,113 @@ +/* Write the Paradise flash: erase and program a sector, exactly like the + * mameise flash app (confirmed on the device). Runs from PRAM; nothing may be + * read from the XIP window while writing. */ +#include "io.h" +#include "flash.h" +#define F_DMEM REG(FCTL+0x100) +#define F_DLEN REG(FCTL+0x104) +#define F_DCTL REG(FCTL+0x108) +#define F_DFLA REG(FCTL+0x10C) + +static void feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } +static void wait_loop(u32 n){ for(volatile u32 i=0;i>1; + u32 hi=(a1>>16)&0xFFFFu; + u32 lo=a1 & 0xFFFFu; + /* erase */ + REG(FCTL+0x008)=hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + for(u32 g=0; (REG(FCTL+0x004)&0x400u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + for(u32 g=0; (REG(FCTL+0x004)&0x2u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); + /* program */ + REG(FCTL+0x008)=0x3000u | hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; + REG(FCTL+0x000)=0x0000d080u; + REG(FCTL+0x020)=0; + REG(FCTL+0x010)=0; + REG(FCTL+0x000)=0x0000d082u; + F_DFLA=0x60000000u | (addr & 0x00FFFFFFu); + F_DLEN=0x1000u; F_DMEM=(u32)src; + F_DCTL=0u; + F_DCTL=1u; + for(u32 g=0; (F_DCTL & 1u) && g<20000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); +} + +void flash_read(u32 addr, void *dst, u32 len) +{ + const volatile u8 *s=(const volatile u8*)(0x60000000u + (addr & 0x00FFFFFFu)); + u8 *d=(u8*)dst; + for(u32 i=0;i>1, hi=(a1>>16)&0xFFFFu, lo=a1 & 0xFFFFu; + REG(FCTL+0x008)=hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + for(u32 g=0; (REG(FCTL+0x004)&0x400u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + for(u32 g=0; (REG(FCTL+0x004)&0x2u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); +} +void flash_prog(u32 addr, const void *src, u32 len) +{ + u32 a1=addr>>1, hi=(a1>>16)&0xFFFFu, lo=a1 & 0xFFFFu; + REG(FCTL+0x008)=0x3000u | hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; + REG(FCTL+0x000)=0x0000d080u; + REG(FCTL+0x020)=0; + REG(FCTL+0x010)=0; + REG(FCTL+0x000)=0x0000d082u; + F_DFLA=0x60000000u | (addr & 0x00FFFFFFu); + F_DLEN=len; F_DMEM=(u32)src; + F_DCTL=0u; + F_DCTL=1u; + for(u32 g=0; (F_DCTL & 1u) && g<20000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); +} diff --git a/doom/src/pdoom/dev/flash.h b/doom/src/pdoom/dev/flash.h new file mode 100644 index 0000000..3ed5d92 --- /dev/null +++ b/doom/src/pdoom/dev/flash.h @@ -0,0 +1,10 @@ +#ifndef FLASH_H +#define FLASH_H +#include "io.h" +void flash_prog4k(u32 addr, const void *src); +void flash_read(u32 addr, void *dst, u32 len); +int flash_same(u32 addr, const void *src, u32 len); +int flash_update4k(u32 addr, const void *src); +void flash_erase4k(u32 addr); +void flash_prog(u32 addr, const void *src, u32 len); +#endif diff --git a/doom/src/pdoom/dev/glue.c b/doom/src/pdoom/dev/glue.c new file mode 100644 index 0000000..f4f8314 --- /dev/null +++ b/doom/src/pdoom/dev/glue.c @@ -0,0 +1,49 @@ +/* Glue between the core and the Paradise platform */ +#include "doomstat.h" +#include "sounds.h" +#include "global_data.h" +const char *plat_sfx_name(int id) +{ + if (id <= 0 || id >= NUMSFX) return 0; + const sfxinfo_t *s = &S_sfx[id]; + if (s->link) s = s->link; + return s->name; +} +void plat_toggle_run(void) { _g->alwaysRun = 1 - _g->alwaysRun; } +#include "w_wad.h" +/* v0.2.0: values for the diagnostics page before the first frame */ +void plat_diag_info(unsigned int *o) +{ + o[0] = _g->gamma; o[1] = _g->newpal; + o[2] = (unsigned int) p_wad_immutable_flash_data; + o[3] = p_wad_immutable_flash_data ? (unsigned int) p_wad_immutable_flash_data->palette_lump : 0; + o[4] = p_wad_immutable_flash_data ? (unsigned int) p_wad_immutable_flash_data->colormaps : 0; + o[5] = (unsigned int) _g->current_palette; + o[6] = _g->gamestate; o[7] = _g->gametic; +} + +/* v0.2.5: music lump name (D_xxx) for a number from musicenum_t */ +static const char *const mus_names[] = { 0, + "D_E1M1","D_E1M2","D_E1M3","D_E1M4","D_E1M5","D_E1M6","D_E1M7","D_E1M8","D_E1M9", + "D_E2M1","D_E2M2","D_E2M3","D_E2M4","D_E2M5","D_E2M6","D_E2M7","D_E2M8","D_E2M9", + "D_E3M1","D_E3M2","D_E3M3","D_E3M4","D_E3M5","D_E3M6","D_E3M7","D_E3M8","D_E3M9", + "D_INTER","D_INTRO","D_BUNNY","D_VICTOR","D_INTROA" +#ifdef PDM_LUMPTXT + /* 1.7.3 test17: DOOM II's songs (were missing: DOOM II played no music) */ + ,"D_RUNNIN","D_STALKS","D_COUNTD","D_BETWEE","D_DOOM","D_THE_DA","D_SHAWN","D_DDTBLU","D_IN_CIT","D_DEAD", + "D_STLKS2","D_THEDA2","D_DOOM2","D_DDTBL2","D_RUNNI2","D_DEAD2","D_STLKS3","D_ROMERO","D_SHAWN2","D_MESSAG", + "D_COUNT2","D_DDTBL3","D_AMPIE","D_THEDA3","D_ADRIAN","D_MESSG2","D_ROMER2","D_TENSE","D_SHAWN3","D_OPENIN", + "D_EVIL","D_ULTIMA","D_READ_M","D_DM2TTL","D_DM2INT" +#endif + }; +#ifdef PDM_LUMPTXT +int pdm_mus_h; char pdm_mus_n[9]; /* s_sound.c: this song number plays the lump pdm_mus_n (own E4 songs) */ +#endif +const char *plat_mus_name(int h) +{ +#ifdef PDM_LUMPTXT + if (h && h == pdm_mus_h) return pdm_mus_n; +#endif + if (h <= 0 || h >= (int)(sizeof(mus_names) / sizeof(mus_names[0]))) return 0; + return mus_names[h]; +} diff --git a/doom/src/pdoom/dev/hw.c b/doom/src/pdoom/dev/hw.c new file mode 100644 index 0000000..61eefc9 --- /dev/null +++ b/doom/src/pdoom/dev/hw.c @@ -0,0 +1,317 @@ +/* Paradise hardware (SNC73410), taken over from the mameise flash app + * (display confirmed on the device). Runs from PRAM 0 after SYSRESETREQ. */ +#include "io.h" +#include "hw.h" +#include "disp_power.h" +#include "pdmcfg.h" +#define PANEL 0x4000E000u +#define FCTL_ 0x40022000u +#define F_STAT REG(FCTL_+0x000) +static void udelay(volatile u32 n){ while(n--) __asm__ volatile("nop"); } +#define MS(x) udelay((u32)(x)*16000u) +#define BB(reg,bit) (*(volatile u32*)(0x42000000u + (((u32)(reg)-0x40000000u)<<5) + ((u32)(bit)<<2))) +#define GPIO0 0x40018000u +#define GPIO1 0x40019000u +#define GPIO2 0x4001A000u +#define LCD_RST(v) (BB(GPIO0+0x00,4)=(v)) +#define LCD_DC(v) (BB(GPIO0+0x00,5)=(v)) +#define SPI_CTRL REG(PANEL+0x00) +#define SPI_STAT REG(PANEL+0x0C) +#define SPI_DATA REG(PANEL+0x1C) +#define SPIWAIT 200000u +#define CT2 0x40002000u +TC_INIT static void clock_init(void){ + REG(CLK+0x00) |= 1u; + REG(CLK+0x0C) = 0; + REG(CLK+0x00) = 0x41u; + { u32 r = (REG(CLK+0x34) & 0xF00u) | 0xA55A0000u; REG(CLK+0x04) = r; } + REG(CLK+0x18) = 0x21u; + REG(CLK+0x50) = 0; + REG(CLK+0x10C) = 0x001FFFFDu; + REG(CLK+0x110) = 0; + REG(CLK+0x108) = 0; + REG(CLK+0x10) = 0; + REG(CLK+0x00) |= 0x10u; + for(u32 g=0; !((REG(CLK+0x08) >> 4) & 1u) && g<4000000u; g++){} + REG(CLK+0x00) |= 0x4000u; + REG(CLK+0x04) &= ~1u; + REG(CLK+0x00) |= 0x8000u; + for(u32 g=0; !((REG(CLK+0x08) >> 6) & 1u) && g<4000000u; g++){} + { u32 r = (REG(CLK+0x0C) & ~7u) | 4u; REG(CLK+0x0C) = r; } + for(u32 g=0; ((REG(CLK+0x0C) >> 4) & 7u) != (REG(CLK+0x0C) & 7u) && g<4000000u; g++){} /* bounded: never hang forever */ + REG(CLK+0x100) = 0x00157EB7u; +} +TC_INIT static void flashctl_init(void){ + /* 1.4.2: enable XIP. We read through the 0x60000000 window that the XIP block + * maps in. Without XIP that window only shows the config register (0x40), not + * the flash data. The original flash utility does this at startup, our app did + * not do it after reset until now. That was exactly what was missing. */ + REG(0x4002F004u)=0x60011000u; /* DOOM_FREE: moved to its program part after hw_init (as Wolf3D and the emulators) */ + REG(0x4002F000u)=0x00000003u; + /* 1.4.1: controller init exactly like the original flash utility (0x40022000). + * This includes setting the read command/mode in 0x008 and 0x00c (0x3077 / 0xf000), + * otherwise the chip only returns its config register (0x40) instead of the flash data. */ + F_STAT=0x0000d018u; + F_STAT=0x0000d000u; + F_STAT=0x0000d080u; + F_STAT=0x0000d088u; + REG(FCTL+0x008)=0x00003077u; /* read command/mode */ + REG(FCTL+0x00C)=0x0000f000u; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; +} +TC_INIT static void wdt_off(void){ + /* Set up the system/power block EXACTLY like the original flash utility. The + only place where we deliberately differed before (bit0 of 0x40008000) might + be the master enable for the display domain. The FU runs with bit0=1 without + a reset, so we copy it 1:1 and feed the watchdog in the loop. */ + REG(0x4000900Cu)=0x5AFA55AAu; REG(0x40009000u)=0x5AFA0000u; /* WDT1 */ + REG(0x40008000u)=0x5AFA0000u; /* unlock */ + REG(0x40008004u)=0x5AFA0002u; + REG(0x40008008u)=0x5AFA00FFu; /* power/clock domains on (incl. display) */ + REG(0x4000800Cu)=0x5AFA55AAu; /* feed the watchdog */ + /* Do NOT set bit0 (watchdog enable): otherwise it reset the Tama during + display init (back to the planet). */ +} +TC_INIT static void mailbox_clear(void){ + REG(0x20000000u)=0; REG(0x20000004u)=0; REG(0x20000008u)=0; REG(0x2000000Cu)=0; +} +TC_INIT static void periph_enable(void){ REG(CLK+0x20)=0x40u; } +TC_INIT static void pin_set(u8 id, u8 mode){ *(volatile u8*)(0xE000E400u + id) = (u8)(mode<<4); } +TC_INIT static void pin_mux(void){ + static const u8 m12[]={6,7,8,9,0xf,0x10,0x11,0x12,0x13,0x14,0x19,0x1f,0x20,0x22, + 0x24,0x25,0x2e,0x2f,0x35,0x36,0x1a,0x1b,0x1c,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x3a,0x3f}; + static const u8 m8[]={0,1,2,3}; + static const u8 m4[]={0x15,0x17}; + for(unsigned i=0;i=0x45000210u && a<=0x45000218u) v=REG(0x4001803Cu + ((a-0x45000210u)>>2)*0x1000u); + REG(a)=v; + } + /* Make sure the panel pins are outputs: reset, D/C, CS (P1.5 low), power (P1.9 low) */ + LCD_RST(1); BB(GPIO0+0x04,4)=1; + LCD_DC(0); BB(GPIO0+0x04,5)=1; + BB(GPIO1+0x00,5)=0; BB(GPIO1+0x04,5)=1; + BB(GPIO1+0x00,9)=0; BB(GPIO1+0x04,9)=1; + MS(20); +} +TC_INIT static void spi_init(void){ + /* like FU 0x3f44, as read-modify-write */ +#ifdef LCD_FASTCLK + REG(PANEL+0x08)=0; /* clock divider: test v0.8.18, twice as fast? */ +#else + REG(PANEL+0x08)=1; /* clock divider */ +#endif + SPI_CTRL &= ~(1u<<18); + REG(PANEL+0x04) &= ~6u; REG(PANEL+0x04) &= ~1u; + SPI_CTRL &= ~0x10u; SPI_CTRL &= ~0x08u; + REG(PANEL+0x20)=0; + SPI_CTRL = (SPI_CTRL & ~0xF00u) | 0x700u; /* 8 bit */ + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFF0000u; + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFFu; + SPI_CTRL |= 1u; /* SPI on */ + SPI_CTRL |= 0xC0u; /* clear FIFOs */ +} +static void spi_tx(const u8* p, u32 n){ + for(u32 i=0;i>8),(u8)r[x]}; + spi_tx(&two[0],1); spi_tx(&two[1],1); /* byte by byte like the FU (1.3.8) */ + } + } + LCD_DC(0); +} + +#ifdef FAST_LCD +/* v0.8.17: pixel output in one go per rectangle, 16 bytes per SPI pass (like the gamma tables + * of the display setup, which work this way on the device). Before, per byte: wait, pause of 8, wait. */ +void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1){ + u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)}; + u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)}; + lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4); + LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); } + LCD_DC(1); +} +void hw_px_row(const u16* r, u32 n){ + u8 b[16]; u32 k=0; + for(u32 i=0;i>8); b[k++]=(u8)r[i]; if(k==16u){ spi_tx(b,16); k=0; } } + if(k) spi_tx(b,k); +} +void hw_px_end(void){ LCD_DC(0); } +#endif + +/* Back to the Paradise: firmware routine that reloads the encrypted PRAM image + and restarts (flash 0x110568, XIP 0x100FF569). */ +void hw_back_to_paradise(void){ + __asm__ volatile("cpsid i"); + ((void(*)(void))(PARADISE_REBOOT|1u))(); + for(;;){} +} + +/* DOOM: pixels as ready-made bytes (palette already in send order), 16 bytes per SPI pass */ +void hw_px_raw(const u8* p, u32 n){ + while(n>=16u){ spi_tx(p,16); p+=16; n-=16u; } + if(n) spi_tx(p,n); +} diff --git a/doom/src/pdoom/dev/hw.h b/doom/src/pdoom/dev/hw.h new file mode 100644 index 0000000..2be25dd --- /dev/null +++ b/doom/src/pdoom/dev/hw.h @@ -0,0 +1,25 @@ +#ifndef HW_H +#define HW_H +#include "io.h" +#define BTN_A 1u +#define BTN_B 2u +#define BTN_C 4u +#define BTN_WHEEL 8u +#ifndef PARADISE_REBOOT +#define PARADISE_REBOOT 0x100FF568u +#endif +void hw_init(void); +void hw_wdt_feed(void); +u32 hw_buttons(void); +void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1); +void hw_back_to_paradise(void); +void hw_backlight(int on); +void hw_bl_pwm_off(void); +void hw_tone(u32 hz); /* 0 = off */ +#ifdef FAST_LCD +void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1); +void hw_px_row(const u16* r, u32 n); +void hw_px_end(void); +void hw_px_raw(const u8* p, u32 n); +#endif +#endif diff --git a/doom/src/pdoom/dev/io.h b/doom/src/pdoom/dev/io.h new file mode 100644 index 0000000..9f7e513 --- /dev/null +++ b/doom/src/pdoom/dev/io.h @@ -0,0 +1,13 @@ +#ifndef IO_H +#define IO_H +typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; +#define REG(a) (*(volatile u32*)(a)) +#define UART 0x4000B000u +#define FCTL 0x40022000u +#define CLK 0x45000000u +static inline void dsb(void){ __asm__ volatile("dsb":::"memory"); } + +#ifndef TC_INIT +#define TC_INIT __attribute__((section(".initcode"), noinline)) +#endif +#endif diff --git a/doom/src/pdoom/dev/paradise.c b/doom/src/pdoom/dev/paradise.c new file mode 100644 index 0000000..757011d --- /dev/null +++ b/doom/src/pdoom/dev/paradise.c @@ -0,0 +1,847 @@ +/* DOOM for the Tamagotchi Paradise: platform layer (startup, time, buttons and wheel, display, sound, flash). + * Core: next-hack nRF52840 Doom (GBADoom, PrBoom), GPL. This file: mameise, GPL. */ +#include "io.h" +#include "hw.h" +#include "flash.h" +#include +#include +#include "graphics.h" +#include "pwm_audio.h" +#include "nrf.h" +#include "keyboard.h" +#ifdef PARA_BACK +/* 1.6.8: the Paradise does not live while DOOM runs (see paraback.h); in the program memory, not the window */ +#define PARA_ATTR __attribute__((section(".pram_text"))) +#define PB_ATTR __attribute__((section(".pram_text"))) +#ifdef DOOM_FREE +#define PB_MARK_ATTR __attribute__((section(".pram_text"))) /* runs before hw_init: the window still shows the program before */ +#endif +#include "../../../../emu/src/emu/paraclock.h" +#include "../../../../emu/src/emu/paraback.h" +#ifdef GPLAY +#define GP_POINTS +#include "../../../../emu/src/emu/gplay.h" +#endif +#endif + +#define PRAMF __attribute__((section(".pram_text"), noinline)) +static volatile unsigned int g_stage, g_fl_words; +void plat_log_raw(unsigned int w); void plat_log(unsigned int type, unsigned int val); +void plat_stage(unsigned int st); +#define R20B __attribute__((section(".ram20_bss"))) + +/* ---- Settings, filled in by the ROM builder ---- + * PMXC: required by the stub (like for the emulator), contents do not matter here. + * PDMC: DOOM. Button bits see below. */ +typedef struct { u32 magic, version, guest_off, guest_size, save_off, device; u8 map[128]; } PmxCfg; +__attribute__((section(".pmxcfg"), used)) volatile const PmxCfg g_cfg = { 0x43584D50u, 1, 0, 0, 0, 0, {0} }; +#include "pdmcfg.h" +__attribute__((section(".pdmcfg"), used)) volatile const PdmCfg g_dcfg = +#ifdef PDM_CMAPXIP + { 0x434D4450u, 3, 0x830004u, 0, 0xCA0000u, 0xA8000u, 0x10E000u, 0xB1000u, 1, 3, 1, 1, + BTN_A, BTN_B, BTN_C, BTN_WHEEL, BTN_C, 1, 0 }; +#else + { 0x434D4450u, 2, 0x830004u, 0, 0xCA0000u, 0xA8000u, 0x10E000u, 0xB1000u, 1, 3, 1, 1, /* v0.2.4: wheel reversed by default */ + BTN_A, BTN_B, BTN_C, BTN_WHEEL, BTN_C, 1 }; +#endif + +#define XIP_BASE_REG REG(0x4002F004u) +#define XIP_CTRL_REG REG(0x4002F000u) +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +#define GPIO2 0x4001A000u + +/* ---- Time ---- */ +static volatile u32 g_ms; +/* v0.1.5: time also works without the timer interrupt. The counter bit (COUNTFLAG) is polled on every call; + * the larger of the two counters wins. If the interrupt never comes, DOOM still runs. */ +static volatile u32 g_poll_ms, g_diag_t; +static volatile u32 g_frames, g_last_frame, g_in_push, g_beep; +PRAMF void plat_line(u32 row, const u32 *v, const u8 *nd, u32 cnt); +PRAMF static u32 now_ms(void){ + if(SYST_CSR & 0x10000u) g_poll_ms++; + return g_ms > g_poll_ms ? g_ms : g_poll_ms; +} +PRAMF unsigned int plat_micros(void){ + u32 m=now_ms(), v=SYST_CVR; + REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; +#ifdef DIAG_OVL + /* Sign of life without the interrupt: while no frame has come, line 3 every second after 8 s */ + if(!g_frames && m>8000u && m-g_diag_t>=1000u){ g_diag_t=m; + u32 pm; __asm__ volatile("mrs %0, primask" : "=r"(pm)); + u32 vv[5]={3, g_ms & 0xFFFFu, g_poll_ms & 0xFFFFu, pm, (SYST_CSR & 7u)}; static const u8 n[5]={1,4,4,1,1}; plat_line(3, vv, n, 5); } +#endif + return m*1000u + (95999u - v)/96u; } +PRAMF void delay(unsigned int ms){ u32 t=now_ms(); while(now_ms()-t=g_mus_end){ g_mus_on=0; return 0; } return *g_mus_pos++; } +PRAMF static void mus_alloff(void){ for(u32 i=0;i<128u;i++) g_mus_st[i]=0; } +PRAMF static void mus_tick(void){ + if(g_mus_delay){ g_mus_delay--; if(g_mus_delay) return; } + for(u32 guard=0; guard<64u && g_mus_on; guard++){ + u32 b=mus_rd(), t=(b>>4)&7u, ch=b&15u, x; + switch(t){ + case 0: x=mus_rd()&127u; if(ch!=15u) g_mus_st[x]=0; break; + case 1: x=mus_rd(); if(x&0x80u){ u32 v=mus_rd(); if(!v && ch!=15u){ g_mus_st[x&127u]=0; break; } } + if(ch!=15u){ g_mus_stamp++; if(!(g_mus_stamp & 0xFFFFu)) g_mus_stamp=1; g_mus_st[x&127u]=(uint16_t)g_mus_stamp; g_mus_chn[ch]=(uint8_t)(x&127u); } break; + case 2: mus_rd(); break; + case 3: x=mus_rd(); if(x==10u || x==11u) mus_alloff(); break; + case 4: mus_rd(); mus_rd(); break; + case 6: mus_alloff(); if(g_mus_loop){ g_mus_pos=g_mus_start; g_mus_delay=1; return; } g_mus_on=0; return; + default: break; + } + if(b & 0x80u){ u32 d=0; do{ x=mus_rd(); d=(d<<7)|(x&127u); } while((x & 0x80u) && g_mus_on); if(d){ g_mus_delay=d; return; } } + } +} +PRAMF static void mus_ms(void){ + if(!g_mus_on) { if(g_mus_cur>=0 && !g_snd){ hw_tone(0); g_mus_cur=-1; } return; } + g_mus_acc+=140u; if(g_mus_acc<1000u) return; g_mus_acc-=1000u; + mus_tick(); + if(g_snd) return; /* game sounds take priority */ + int best=-1; u32 bs=0; + if(g_mus_vol && !g_snd_mode) for(u32 i=0;i<128u;i++){ u32 s2=g_mus_st[i]; if(s2){ u32 age=(g_mus_stamp-s2)&0xFFFFu; if(best<0 || age=0 ? g_note_hz[best] : 0); } +} +#endif +/* ---- Wheel button, sampled every millisecond (v0.4.1) ---- + * DOOM reads the keys only once per frame. Quick taps on the wheel (looking for secret doors) + * then fell between two frames, the releases were missed and the taps added up to a long press + * (back to the Paradise). The timer now follows the button on its own: a change counts after + * 8 ms without bouncing, every press is counted, the long press measures from the last press. */ +static volatile u32 g_wh_down, g_wh_cand, g_wh_t0, g_wh_press; +PRAMF static void wheel_poll(u32 ms, u32 down){ + if(down==g_wh_down){ g_wh_cand=0; return; } + if(!g_wh_cand){ g_wh_cand=ms|1u; return; } + if((int)(ms-g_wh_cand)<8) return; + g_wh_cand=0; g_wh_down=down; + if(down){ g_wh_t0=ms|1u; g_wh_press++; } else g_wh_t0=0; +} +PRAMF void plat_hang(u32 *fr); +PRAMF void systick_c(u32 *fr){ + g_ms++; + wheel_poll(g_ms, (REG(0x40018000u) & (1u<<8)) ? 0u : 1u); +#ifdef DIAG_OVL + /* If execution hangs (no frame for 3 s, not in the middle of a frame output): show where it was interrupted */ + if(g_ms>6000u && g_ms-g_last_frame>3000u && (g_ms & 1023u)==0){ plat_hang(fr); hw_tone(880); g_beep=40; } + if(g_beep && !--g_beep && !g_snd) hw_tone(0); +#endif + REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; + u32 n=REG(GPIO2) & 3u; + if(n!=g_enc_last){ g_enc_acc+=g_qd[(g_enc_last<<2)|n]; g_enc_last=n; + int d=(int)g_dcfg.detent; if(d<1) d=2; + while(g_enc_acc>=d){ g_enc_acc-=d; g_enc_det++; } + while(g_enc_acc<=-d){ g_enc_acc+=d; g_enc_det--; } } + if(g_snd && ++g_snd_t>=7u){ g_snd_t=0; /* about 140 per s */ + if(g_snd_n){ u32 v=*g_snd++; g_snd_n--; hw_tone(v ? snd_hz(v) : 0); } + else { g_snd=0; hw_tone(0); +#ifdef MUS_PLAY + g_mus_cur=-2; /* restart the music afterwards */ +#endif + } } +#ifdef MUS_PLAY + mus_ms(); +#endif +} +__attribute__((naked, section(".pram_text"))) void SysTick_Handler(void){ __asm__ volatile("tst lr, #4\n ite eq\n mrseq r0, msp\n mrsne r0, psp\n b systick_c\n"); } + +/* ---- Sound ---- */ +soundChannel_t soundChannels[MAX_CHANNELS]; +extern int W_CheckNumForName(const char *name); +extern const void *W_CacheLumpNum(int lump); +extern const char *plat_sfx_name(int id); +void plat_sound_mode_next(void){ + g_snd_mode = (g_snd_mode + 1u) % 3u; + __asm__ volatile("cpsid i"); + if(g_snd_mode==2u){ g_snd=0; g_snd_n=0; hw_tone(0); } +#ifdef MUS_PLAY + g_mus_cur=-2; +#endif + __asm__ volatile("cpsie i"); +} +void plat_sound(int id){ + if(!g_dcfg.sound || g_snd_mode==2u) return; + const char *nm=plat_sfx_name(id); if(!nm) return; + if((nm[0]=='D'||nm[0]=='d') && (nm[1]=='S'||nm[1]=='s')) nm+=2; /* v0.2.4: names here already come as DSxxxx */ + char b[9]={'D','P',0}; for(int i=0;i<6 && nm[i];i++){ char c=nm[i]; if(c>='a'&&c<='z') c-=32; b[2+i]=c; b[3+i]=0; } + int l=W_CheckNumForName(b); if(l<0) return; + const uint8_t *p=(const uint8_t*)W_CacheLumpNum(l); + u32 cnt=p[2] | (p[3]<<8); + __asm__ volatile("cpsid i"); g_snd_n=cnt; g_snd_t=7; g_snd=p+4; __asm__ volatile("cpsie i"); +} + +#ifdef MUS_PLAY +extern const char *plat_mus_name(int handle); +void plat_music_play(int handle, int looping){ + __asm__ volatile("cpsid i"); g_mus_on=0; __asm__ volatile("cpsie i"); + if(!g_dcfg.sound) return; + const char *nm=plat_mus_name(handle); if(!nm) return; + int l=W_CheckNumForName(nm); if(l<0) return; + const uint8_t *p=(const uint8_t*)W_CacheLumpNum(l); + if(p[0]!='M' || p[1]!='U' || p[2]!='S') return; + u32 len=p[4] | (p[5]<<8), st=p[6] | (p[7]<<8); + __asm__ volatile("cpsid i"); + mus_alloff(); g_mus_start=p+st; g_mus_pos=p+st; g_mus_end=p+st+len; g_mus_loop=(u32)looping; + g_mus_delay=0; g_mus_acc=0; g_mus_cur=-2; g_mus_on=1; + __asm__ volatile("cpsie i"); +} +void plat_music_stop(void){ __asm__ volatile("cpsid i"); g_mus_on=0; mus_alloff(); __asm__ volatile("cpsie i"); } +void plat_music_pause(int p){ static u32 was; __asm__ volatile("cpsid i"); if(p){ was=g_mus_on; g_mus_on=0; } else if(was && g_mus_start){ g_mus_on=1; g_mus_cur=-2; } __asm__ volatile("cpsie i"); } +void plat_music_volume(int v){ g_mus_vol = v>0; g_mus_cur=-2; } +#endif +void muteSound(void){ __asm__ volatile("cpsid i"); g_snd=0; g_snd_n=0; __asm__ volatile("cpsie i"); hw_tone(0); } +void updateSound(void){} +void SetBacklight(int x){ (void)x; } +void disableWirelessAudio(void){} +void restoreWirelessAudio(void){} + +/* ---- Display ---- */ +R20B displayData_t displayData; +#ifdef SINGLE_FB +__attribute__((aligned(8))) static uint8_t g_fb[PDOOM_W * PDOOM_H]; +#endif +plat_qspi_t plat_qspi; +static u16 g_line[128]; +PRAMF void plat_line(u32 row, const u32 *v, const u8 *nd, u32 cnt); +PRAMF void startDisplayRefresh(uint8_t b){ + const uint8_t *fb=displayData.displayFrameBuffer[b]; + volatile uint16_t *pal=displayData.pPalette; + g_frames++; g_last_frame=g_ms; + if(!pal) return; + g_in_push=1; +#ifdef DIAG_OVL +#ifndef SIM_NODIAG + if(g_frames==1){ + /* v0.2.0: diagnostics page before the first frame, waits for B (at most 60 s) */ + extern void plat_diag_info(unsigned int *o); + u32 sp; __asm__ volatile("mov %0, sp" : "=r"(sp)); + u32 di[8]; plat_diag_info(di); + { u32 v[4]={0xF, di[0], di[1], sp}; static const u8 n[4]={1,2,2,8}; plat_line(0, v, n, 4); } + { u32 v[4]={pal[0], pal[1], pal[2], pal[3]}; static const u8 n[4]={4,4,4,4}; plat_line(1, v, n, 4); } + { u32 v[4]={pal[4], pal[5], pal[6], pal[7]}; static const u8 n[4]={4,4,4,4}; plat_line(2, v, n, 4); } + { u32 v[2]={di[3], di[5]}; static const u8 n[2]={8,6}; plat_line(3, v, n, 2); } + { const volatile u8 *pb=(const volatile u8*)di[3]; u32 v[6]={0,0,0,0,0,0}; + if(di[3]) for(u32 i=0;i<6;i++) v[i]=pb[i]; static const u8 n[6]={2,2,2,2,2,2}; plat_line(4, v, n, 6); } + { const volatile u32 *pw=(const volatile u32*)(di[3] & ~3u); u32 v[2]={0,0}; + if(di[3]){ v[0]=pw[0]; v[1]=pw[1]; } static const u8 n[2]={8,8}; plat_line(5, v, n, 2); } + { extern int zone_min_free; u32 v[2]={0xA, (u32)(-zone_min_free)}; static const u8 n[2]={1,6}; plat_line(6, v, n, 2); } + { u32 nz0=0, nz1=0; for(u32 i=0;i<128u*128u;i++){ if(displayData.displayFrameBuffer[0][i]) nz0++; if(displayData.displayFrameBuffer[1][i]) nz1++; } + u32 v[4]={b, nz0, nz1, (u32)fb}; static const u8 n[4]={1,4,4,8}; plat_line(7, v, n, 4); } + { const volatile u8 *cm=(const volatile u8*)di[4]; u32 v[6]={0,0,0,0,0,0}; + if(di[4]) for(u32 i=0;i<6;i++) v[i]=cm[0x40+i]; static const u8 n[6]={2,2,2,2,2,2}; plat_line(8, v, n, 6); } + { u32 v[3]={di[4], di[6], di[7]}; static const u8 n[3]={8,1,4}; plat_line(9, v, n, 3); } + { u32 v[1]={0xB}; static const u8 n[1]={1}; plat_line(10, v, n, 1); } + u32 t0=now_ms(); + while((hw_buttons() & BTN_B)==0 && now_ms()-t0<3000u){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } + t0=now_ms(); while((hw_buttons() & BTN_B) && now_ms()-t0<5000u){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } + } +#endif +#endif +#ifdef FRAME_ROW + /* v0.1.7: output through the same path as the number lines (hw_px_row, one window per line) */ + for(u32 y=0;y<128;y++){ + for(u32 x=0;x<128;x++){ u16 c=pal[fb[x]]; g_line[x]=(u16)((c>>8)|(c<<8)); } + hw_px_begin(0,y,128,y+1); hw_px_row(g_line,128); hw_px_end(); + fb+=128; + } +#else + hw_px_begin(0,0,128,128); + for(u32 y=0;y<128;y++){ + for(u32 x=0;x<128;x++) g_line[x]=pal[fb[x]]; + hw_px_raw((const u8*)g_line, 256u); + fb+=128; + } + hw_px_end(); +#endif +#ifdef DIAG_OVL + /* v0.1.3: bottom line: frames, seconds, palette color 0, color 1, first frame byte */ + { u32 nz=0; const uint8_t *f2=displayData.displayFrameBuffer[b]; for(u32 i=0;i<128u*128u;i+=4u) if(*(const u32*)(f2+i)) nz++; + u32 v[5]={g_frames & 0xFFFu, (g_ms/1000u) & 0xFFFu, nz, pal[1], f2[64*128+64]}; static const u8 n[5]={3,3,4,4,2}; + plat_line(11, v, n, 5); } +#endif + g_in_push=0; +} + +/* ---- Exit ---- */ +#ifdef PDM_MOREZONE +/* 1.7.3 test17: out of memory (a map too big for the Paradise's RAM, like the biggest Sigil maps): a line "9 + * " on the screen, holding the wheel 2 s goes back to the menu (before it hung) */ +void plat_leave(void); +void plat_oom(unsigned size, int used){ + { u32 v[3]={0x9, size & 0xFFFFFu, (u32)used & 0xFFFFFu}; static const u8 n[3]={1,5,5}; plat_line(3, v, n, 3); } + __asm__ volatile("cpsie i"); + for(u32 t=0;;t++){ hw_wdt_feed(); if(hw_buttons() & BTN_WHEEL){ if(t>2000000u) break; } else t=0; } + plat_leave(); +} +#endif +PRAMF void plat_leave(void){ + hw_tone(0); + __asm__ volatile("cpsid i"); + SYST_CSR=0; + REG(0x20000FF8u)=0; +#ifdef PMXL_BACK + REG(0x20000FFCu)=0x4C584D50u; /* 1.6.8 "PMXL": back on purpose, the autostart stays off (as the emulators) */ +#endif +#ifdef PARA_BACK +#ifdef GPLAY + para_points((uint8_t *)g_fb); /* 1.7.2 test14: play time to Tamapoints */ +#endif + para_back_fix(g_fb); +#endif + hw_bl_pwm_off(); + for(u32 t=0; hw_buttons() && t<20000000u; t++) if((t & 0xFFFFu)==0) hw_wdt_feed(); + XIP_BASE_REG=0x60011000u; XIP_CTRL_REG=3u; + __asm__ volatile("dsb\n isb"); + { volatile u32 sum=0; for(u32 i=0;i<0x4000u;i++) sum+=*(volatile u32*)(0x10080000u+4u*i); (void)sum; } + hw_back_to_paradise(); +} + +/* ---- Buttons ---- + * B forward, C back, A fire, turn wheel left/right, short wheel press door/use, + * hold A + turn wheel: switch weapon, B twice quickly: run on/off, + * A+C together: menu, B+C together: map, wheel 2 s: back to the Paradise. */ +#define KEY_SPEED 0x0400 +extern void plat_toggle_run(void); void plat_sound_mode_next(void); +#ifdef KEYMAP +/* v0.4.0: mapping from g_dcfg (configurable in the studio). Default as before: A fire, B forward, + * C back, press wheel use, hold C + wheel weapon, hold C + press wheel sound, 2x B run. + * Fixed: A+C menu, B+C map, wheel 2 s back to the Paradise. + * The hold key (k_mod) only does its own action after 120 ms and only while the wheel + * has not been turned, otherwise every weapon switch would also be a step back. */ +#ifdef DOOM_EXITKEY +/* 1.7.3 test12: the way back chosen in the Studio (tab Menu, "EX" << 16 | mode in the vector table at 0x13C, as + * emu/src/emu/exitkey.h): 0 wheel 2 s, 1 wheel and A, 2 wheel and C (1 s: the hold key + a short wheel press stays the + * sound), 3 wheel 5 s. Before DOOM always went back after 2 s of wheel. */ +static int doom_exit(u32 held, u32 b){ + u32 v=*(volatile const u32 *)0x13Cu, m=(v>>16)==0x5845u ? (v&3u) : 0u; + if(m==1u || m==2u) return held>1000u && (b & (m==1u ? BTN_A : BTN_C))!=0u; + return held>(m==3u ? 5000u : 2000u); +} +#endif +void getKeys(pkey_t *keys){ + static u32 mod_t0, b_last, b_prev, use_left, turn_left, menu_hold, chg_left, chg_dir, wh_seen; + static int turn_dir, det_seen; + u32 now=now_ms(), b=hw_buttons(); pkey_t k=0; + u32 kf=g_dcfg.k_fire, kv=g_dcfg.k_fwd, kz=g_dcfg.k_back, ku=g_dcfg.k_use, km=g_dcfg.k_mod; + if(g_dcfg.version<2u){ kf=BTN_A; kv=BTN_B; kz=BTN_C; ku=BTN_WHEEL; km=BTN_C; } + /* Wheel pressed: with hold key = sound, otherwise use (if mapped so); held 2 s from the last press = exit. + * Presses and the time come from the millisecond timer (wheel_poll); this call only adds a sample + * in case the timer interrupt does not run. */ + u32 np, wdown, wt0; + __asm__ volatile("cpsid i"); + wheel_poll(now, (b & BTN_WHEEL) ? 1u : 0u); + np=g_wh_press-wh_seen; wh_seen+=np; wdown=g_wh_down; wt0=g_wh_t0; + __asm__ volatile("cpsie i"); +#ifdef DOOM_EXITKEY + /* the sound only when the wheel comes up (held with the hold key it can be the way back) */ + static u32 snd_pend; + if(np){ if(b & km){ det_seen=1; snd_pend=1; } else if(ku==BTN_WHEEL) use_left=3; } + if(snd_pend && !wdown){ snd_pend=0; plat_sound_mode_next(); } + if(wdown && wt0 && doom_exit(now-wt0, b)) plat_leave(); +#else + if(np){ if(b & km){ det_seen=1; plat_sound_mode_next(); } else if(ku==BTN_WHEEL) use_left=3; } + if(wdown && wt0 && now-wt0>2000u) plat_leave(); +#endif + int det; __asm__ volatile("cpsid i"); det=g_enc_det; g_enc_det=0; __asm__ volatile("cpsie i"); + if(g_dcfg.invert) det=-det; + if(det){ + if(b & km){ chg_left=2; chg_dir = det>0 ? 1u : 0u; det_seen=1; } + else { if((det>0) != (turn_dir>0)) turn_left=0; turn_dir = det>0 ? 1 : -1; turn_left += (u32)(det>0?det:-det) * g_dcfg.turn_tics; } + } + int ac = (b & BTN_A) && (b & BTN_C), bc = (b & BTN_B) && (b & BTN_C); + if(ac) menu_hold++; else menu_hold=0; + if(ac){ if(menu_hold<=2) k|=KEY_MENU; } + else if(bc){ k|=KEY_MAP; } + else { + /* pressed, unless the hold key is still in its waiting time */ + u32 eff = b & ~km; + if((b & km) && !det_seen){ if(!mod_t0) mod_t0=now|1u; if((int)(now-mod_t0)>=120) eff |= km; } /* v0.4.0: signed, otherwise a step already came in the first tick (now even) */ + if(eff & kv) k|=KEY_UP; + if(eff & kz) k|=KEY_DOWN; + if(eff & kf) k|=KEY_FIRE; + if(ku!=BTN_WHEEL && (eff & ku) && !(b_last & ku)) use_left=3; + } + if(!(b & km)){ mod_t0=0; det_seen=0; } + if(g_dcfg.run_dbl || g_dcfg.version<2u){ + if((b & kv) && !(b_last & kv)){ if(b_prev && now-b_prev<300u){ plat_toggle_run(); b_prev=0; } else b_prev=now; } + } + b_last = b; + if(use_left){ use_left--; k|=KEY_USE; } + if(turn_left){ turn_left--; k |= turn_dir>0 ? KEY_RIGHT : KEY_LEFT; } + if(chg_left){ chg_left--; k |= chg_dir ? KEY_CHGW : (KEY_CHGW|KEY_USE); } + *keys=k; +} +#else +void getKeys(pkey_t *keys){ + static u32 wheel_t0, a_t0, b_last, b_prev, use_left, turn_left, menu_hold, chg_left, chg_dir; + static int turn_dir, det_seen; + u32 now=now_ms(), b=hw_buttons(); pkey_t k=0; + /* Wheel pressed: short = use, long = exit */ +#ifdef SND_TOGGLE + /* v0.2.6: hold C + press wheel: cycle sound (all on, music off, all off) */ + static u32 wheel_c; + if((b & BTN_WHEEL) && !wheel_t0 && (b & BTN_C)){ wheel_c=1; det_seen=1; plat_sound_mode_next(); } +#endif + if(b & BTN_WHEEL){ if(!wheel_t0) wheel_t0=now|1u; else if(now-wheel_t0>2000u) plat_leave(); } + else { +#ifdef SND_TOGGLE + if(wheel_c){ wheel_c=0; wheel_t0=0; } else +#endif + { if(wheel_t0 && now-wheel_t0<800u) use_left=3; wheel_t0=0; } } + /* Turns */ + int det; __asm__ volatile("cpsid i"); det=g_enc_det; g_enc_det=0; __asm__ volatile("cpsie i"); + if(g_dcfg.invert) det=-det; + if(det){ +#ifdef CHG_WITH_C + if(b & BTN_C){ chg_left=2; chg_dir = det>0 ? 1u : 0u; det_seen=1; } /* v0.2.4: hold C + wheel: weapon */ +#else + if(b & BTN_A){ chg_left=2; chg_dir = det>0 ? 1u : 0u; det_seen=1; } +#endif + else { if((det>0) != (turn_dir>0)) turn_left=0; turn_dir = det>0 ? 1 : -1; turn_left += (u32)(det>0?det:-det) * g_dcfg.turn_tics; } + } + /* Combinations */ + int ac = (b & BTN_A) && (b & BTN_C), bc = (b & BTN_B) && (b & BTN_C); + if(ac){ menu_hold++; } + else menu_hold=0; + if(ac){ if(menu_hold<=2) k|=KEY_MENU; } + else if(bc){ k|=KEY_MAP; } + else { + if(b & BTN_B) k|=KEY_UP; +#ifdef CHG_WITH_C + /* C: back only after 120 ms and only while the wheel has not been turned (otherwise weapon switch) */ + if((b & BTN_C) && !det_seen){ if(!a_t0) a_t0=now|1u; if(now-a_t0>=120u) k|=KEY_DOWN; } + if(b & BTN_A) k|=KEY_FIRE; +#else + if(b & BTN_C) k|=KEY_DOWN; + if((b & BTN_A) && !det_seen){ if(!a_t0) a_t0=now|1u; if(now-a_t0>=40u) k|=KEY_FIRE; } +#endif + } +#ifdef CHG_WITH_C + if(!(b & BTN_C)){ a_t0=0; det_seen=0; } +#else + if(!(b & BTN_A)){ a_t0=0; det_seen=0; } +#endif + /* B twice quickly: toggle run */ + if((b & BTN_B) && !b_last){ if(b_prev && now-b_prev<300u){ plat_toggle_run(); b_prev=0; } else b_prev=now; } + b_last = b & BTN_B; + if(use_left){ use_left--; k|=KEY_USE; } + if(turn_left){ turn_left--; k |= turn_dir>0 ? KEY_RIGHT : KEY_LEFT; } + if(chg_left){ chg_left--; k |= chg_dir ? KEY_CHGW : (KEY_CHGW|KEY_USE); } + *keys=k; +} +#endif + +/* ---- Flash for the precomputed data (addresses in the uncached window 0x6...) ---- */ +PRAMF static void fl_erase(u32 off){ __asm__ volatile("cpsid i"); flash_erase4k(off); __asm__ volatile("cpsie i"); } +PRAMF static void fl_prog(u32 off, const void *p, u32 n){ __asm__ volatile("cpsid i"); flash_prog(off, p, n); __asm__ volatile("cpsie i"); } +/* Check and if needed rewrite the whole sector (the method the emulator uses on the device) */ +#define g_sect ((u32*)displayData.displayFrameBuffer[1]) /* v0.1.4: fallback buffer in the second framebuffer */ +PRAMF static void fl_rmw(u32 off, u32 word){ + u32 base=off & 0x00FFF000u; + for(u32 i=0;i<1024;i++) g_sect[i]=*(volatile u32*)(0x60000000u+base+4u*i); + g_sect[(off & 0xFFFu)>>2] &= word; + __asm__ volatile("cpsid i"); flash_prog4k(base, g_sect); __asm__ volatile("cpsie i"); +} +u32 plat_flash_fixes; extern u32 g_in_fault; +void plat_flash_erase4k(uint32_t a){ + u32 off=a & 0x00FFF000u; g_last_frame=g_ms; fl_erase(off); + for(u32 i=0;i<1024;i++) if(*(volatile u32*)(0x60000000u+off+4u*i)!=0xFFFFFFFFu){ + for(u32 k=0;k<1024;k++) g_sect[k]=0xFFFFFFFFu; + __asm__ volatile("cpsid i"); flash_prog4k(off, g_sect); __asm__ volatile("cpsie i"); plat_flash_fixes++; break; } +} +void plat_flash_word(uint32_t a, uint32_t w){ + static u32 buf; u32 off=a & 0x00FFFFFCu; + g_last_frame=g_ms; /* v0.2.4: writing flash (level start) is not a hang, no beep */ + if((++g_fl_words & 1023u)==0) plat_stage(g_stage); + u32 want=*(volatile u32*)(0x60000000u+off) & w; + buf=w; fl_prog(off, &buf, 4u); + if(*(volatile u32*)(0x60000000u+off)!=want && !g_in_fault){ fl_rmw(off, w); plat_flash_fixes++; } +} +uint32_t qspiFlashGetSize(void){ return 0x1000000u; } +void qspiFlashErasePage4k(uint32_t a){ fl_erase(a & 0x00FFF000u); } +void qspiFlashProgram(uint32_t a, const void *b, uint32_t s){ + const u8 *p=(const u8*)b; a&=0x00FFFFFFu; + while(s){ u32 n=256u-(a & 255u); if(n>s) n=s; fl_prog(a, p, n); a+=n; p+=n; s-=n; } } +void _putchar(char c){ (void)c; } + +/* ---- Diagnostics display (v0.1.1): lines of hex digits, runs entirely from PRAM ---- */ +__attribute__((section(".pram_rodata"))) static const u16 g_font[16]={0x7B6F,0x2C97,0x73E7,0x73CF,0x5BC9,0x79CF,0x79EF,0x7249,0x7BEF,0x7BCF,0x7BED,0x6BAE,0x7927,0x6B6E,0x79E7,0x79E4}; +static u16 g_drow[128]; +#ifdef CLEAN +#define BG 0x0000u /* v0.2.6: release build, black instead of blue */ +#else +#define BG 0x0010u +#endif +PRAMF void plat_line(u32 row, const u32 *v, const u8 *nd, u32 cnt){ +#ifdef CLEAN + (void)row; (void)v; (void)nd; (void)cnt; return; /* v0.2.6: no more number lines */ +#endif + for(u32 y=0;y<10;y++){ + u32 ry = y<8u ? (y*5u)/8u : 9u; + for(u32 x=0;x<128;x++) g_drow[x]=0x0010u; + u32 cx=1; + for(u32 k=0;k=0; d--){ + u32 bits=g_font[(v[k]>>(4u*(u32)d))&15u]; + if(cx+6<128 && ry<5) for(u32 c=0;c<3;c++) if((bits>>(14-(ry*3+c)))&1u){ g_drow[cx+2*c]=0xFFFFu; g_drow[cx+2*c+1]=0xFFFFu; } + cx+=8; + } + cx+=4; + } + hw_px_begin(0,row*10u+y,128,row*10u+y+1); hw_px_row(g_drow,128); hw_px_end(); + } +} +extern u32 plat_flash_fixes; +PRAMF void plat_stage(unsigned int st){ + g_stage=st; +#ifdef CLEAN + /* v0.2.6: a loading bar at the bottom instead of numbers, until the first frame (first start writes about 32000 words) */ + if(!g_frames){ u32 w=(g_fl_words*128u)>>15; if(w>128u) w=128u; + for(u32 x=0;x<128;x++) g_drow[x]= x / / frames, stage */ +static u32 g_hang_logged; +PRAMF void plat_hang(u32 *fr){ + if(g_hang_logged<6u){ g_hang_logged++; plat_log(5, g_frames); plat_log_raw(fr[6]); plat_log_raw(fr[5]); } + { u32 v[2]={0x8, fr[6]}; static const u8 n[2]={1,8}; plat_line(8, v, n, 2); } + { u32 v[2]={0xA, fr[5]}; static const u8 n[2]={1,8}; plat_line(9, v, n, 2); } + { u32 v[5]={0xB, g_frames & 0xFFFu, g_stage, g_in_push, (u32)fr}; static const u8 n[5]={1,3,2,1,8}; plat_line(10, v, n, 5); } +} + +/* ---- v0.1.8: event log in flash (0x108000 to 0x10DFFF, empty in the ROM) ---- + * Word = . Type 1 checkpoint (source line), 2 PLOG number, 3 I_Error (line), + * 4 fault (next word pc), 5 hang (next word pc), F restart. On the next start with A+C the + * latest entries are shown (until a key is pressed). */ +#define LOG_BASE 0x60108000u +#define LOG_N 6144u +static u32 g_log_i; +void plat_log_raw(u32 w){ +#ifdef CLEAN + (void)w; return; /* v0.2.6: no event log */ +#endif + if(g_log_i>=LOG_N) return; + plat_flash_word(LOG_BASE + 4u*g_log_i, w); g_log_i++; +} +void plat_log(u32 type, u32 val){ plat_log_raw((type<<28) | ((val & 0xFFFu)<<16) | (g_ms & 0xFFFFu)); } +void plat_plog(int n){ plat_log(2, (u32)n); } +static void log_show_previous(void){ +#ifdef CLEAN + return; +#endif + u32 n=0; while(n 11u*page ? n-11u*page : 0u; + u32 first = end>11u ? end-11u : 0u; + { u32 v[3]={0xC, n, page}; static const u8 nn[3]={1,4,2}; plat_line(0, v, nn, 3); } + for(u32 k=first;k0u) { page++; continue; } + if(b & BTN_A) { page=0; continue; } + break; + } +} + +/* Checkpoints from the core (lprintf) and errors (I_Error): line 1 . + * The file id is the sum of the characters of the file name (16 bit). */ +static volatile u32 g_marks; +PRAMF static u32 fhash(const char *f){ u32 h=0; while(*f) h+=(u8)*f++; return h & 0xFFFFu; } +PRAMF void plat_mark(int line, const char *file){ + REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; + g_marks++; + plat_log(1, (u32)line); + u32 v[5]={g_marks & 0xFFu, (u32)line & 0xFFFu, fhash(file), g_ms & 0xFFFFu, g_poll_ms & 0xFFFFu}; static const u8 n[5]={2,3,4,4,4}; + plat_line(2, v, n, 5); +} +PRAMF void plat_error(int line, const char *file){ + plat_log(3, (u32)line); + u32 v[3]={0xE, (u32)line & 0xFFFu, fhash(file)}; static const u8 n[3]={1,3,4}; + plat_line(4, v, n, 3); /* only show it and keep running (the core also reports harmless things, e.g. missing WIMINUS) */ +} + + +/* v0.2.1: alias test of RAM 0x20000000..0x2000FFFF in 1 KB blocks. Each block gets a marker at +0x200, + * then we read back which marker is there. Line 1/2: for each 4 KB block the number (4 KB) of the marker read, + * line 3: number of wrong 1 KB blocks, first wrong block, the marker read there, check word. */ +PRAMF static void ram20_alias_test(void){ + static u32 sv[64]; u32 rb[64]; + __asm__ volatile("cpsid i"); + for(u32 i=0;i<64u;i++) sv[i]=*(volatile u32*)(0x20000200u+0x400u*i); + for(u32 i=0;i<64u;i++){ *(volatile u32*)(0x20000200u+0x400u*i)=0xC0DE0000u|i; __asm__ volatile("dsb"); } + for(u32 i=0;i<64u;i++) rb[i]=*(volatile u32*)(0x20000200u+0x400u*i); + for(int i=63;i>=0;i--) *(volatile u32*)(0x20000200u+0x400u*(u32)i)=sv[i]; + __asm__ volatile("dsb\n cpsie i"); + u32 bad=0, fb=0, fv=0; + for(u32 i=0;i<64u;i++) if(rb[i]!=(0xC0DE0000u|i)){ if(!bad){ fb=i; fv=rb[i]; } bad++; } + u32 a[8], c[8]; + for(u32 i=0;i<8u;i++){ u32 r=rb[4u*i]; a[i]=((r>>16)==0xC0DEu) ? ((r & 0x3Fu)>>2) : 0xEu; } + for(u32 i=0;i<8u;i++){ u32 r=rb[32u+4u*i]; c[i]=((r>>16)==0xC0DEu) ? ((r & 0x3Fu)>>2) : 0xEu; } + static const u8 n8[8]={1,1,1,1,1,1,1,1}; + plat_line(5, a, n8, 8); plat_line(6, c, n8, 8); + { u32 v[4]={bad, fb, fv & 0xFFu, fv>>16}; static const u8 n[4]={2,2,2,4}; plat_line(7, v, n, 4); } + { u32 v[1]={0xB}; static const u8 n[1]={1}; plat_line(8, v, n, 1); } + for(u32 t=0;t<0x4000000u;t++){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; if(hw_buttons() & BTN_B) break; } + for(u32 t=0;t<0x800000u && (hw_buttons() & BTN_B);t++){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } +} +/* ---- Start ---- */ +extern u32 __data_load, __data_start, __data_end, __bss_start, __bss_end; +extern u32 __r20_load, __r20_start, __r20_end, __r20b_start, __r20b_end; +extern void D_DoomMain(void); extern void Z_Init(void); extern void InitGlobals(void); +#ifdef DOOM_FREE +uint32_t g_pk_lo=0x60800000u, g_pk_hi=0x60C00000u; +extern const unsigned char *doom_iwad; extern const unsigned int *p_doom_iwad_len; +#endif +__attribute__((section(".pram_text"), noinline, used)) void Reset_Handler(void){ + __asm__ volatile("cpsid i"); +#ifdef PARA_BACK + { u32 cnt=REG(0x45000304u), t=para_clock(cnt, 0, 0x1F000u, 0, 0); if(!t) t=para_mailbox(cnt); para_leave_mark(cnt, t); } +#endif + REG(0xE000ED14u) &= ~(1u<<3); /* v0.2.3: UNALIGN_TRP off (plain LDR/STR may be unaligned) */ +#ifdef UA_FIX + REG(0xE000ED24u) |= (1u<<18); /* UsageFault on its own (vector 6) */ +#endif + hw_init(); +#ifdef DOOM_FREE + /* 1.7.2 test6: only now (after hw_init) the flash window can be moved to DOOM's program part (as Wolf3D and the + * emulators do); its cache still holds lines of the program before at the same addresses: reading 64 KB evicts them */ + XIP_BASE_REG = PD_XIP_BASE; XIP_CTRL_REG = 3u; + __asm__ volatile("dsb\n isb"); + { volatile u32 sum=0; for(u32 i=0;i<0x4000u;i++) sum+=*(volatile u32*)(0x10040000u+4u*i); (void)sum; } + __asm__ volatile("dsb\n isb"); +#endif + for(u32 y=0;y<128;y++){ for(u32 x=0;x<128;x++) g_drow[x]=BG; hw_px_begin(0,y,128,y+1); hw_px_row(g_drow,128); hw_px_end(); } + log_show_previous(); +#ifdef ALIAS_TEST + ram20_alias_test(); +#endif + for(u32 y=0;y<128;y++){ for(u32 x=0;x<128;x++) g_drow[x]=BG; hw_px_begin(0,y,128,y+1); hw_px_row(g_drow,128); hw_px_end(); } + plat_stage(1); + plat_log(0xF, 0); + /* v0.1.2: the window stays at the firmware base (0x60011000), our program part sits in it at 0x100A0000 + * (flash 0x0B1000). No switching, so no stale lines in the cache. */ + XIP_BASE_REG = PD_XIP_BASE; XIP_CTRL_REG = 3u; + __asm__ volatile("dsb\n isb"); + u32 bad0=0; for(u32 i=0;i<0x4000u;i++) if(*(volatile u32*)(0x100A0000u+4u*i)!=*(volatile u32*)(PD_XIP_BASE+0xA0000u+4u*i)) bad0++; +#ifdef XIP_FLUSH + /* The window cache keeps stale lines even after the base is changed: reading 64 KB evicts everything */ + { volatile u32 sum=0; for(u32 i=0;i<0x4000u;i++) sum+=*(volatile u32*)(0x10040000u+4u*i); (void)sum; } +#endif + { u32 bad=0; for(u32 i=0;i<0x4000u;i++) if(*(volatile u32*)(0x100A0000u+4u*i)!=*(volatile u32*)(PD_XIP_BASE+0xA0000u+4u*i)) bad++; + u32 v[3]={2, bad0, bad}; static const u8 n[3]={2,5,5}; plat_line(1, v, n, 3); } + { const u32 *s=&__data_load; for(u32 *p=&__data_start;p<&__data_end;p++) *p=*s++; } + for(u32 *p=&__bss_start;p<&__bss_end;p++) *p=0; + { const u32 *s=&__r20_load; for(u32 *p=&__r20_start;p<&__r20_end;p++) *p=*s++; } + for(u32 *p=&__r20b_start;p<&__r20b_end;p++) *p=0; +#ifdef SINGLE_FB + displayData.displayFrameBuffer[0]=g_fb; displayData.displayFrameBuffer[1]=g_fb; +#endif + __asm__ volatile("dsb\n isb"); + plat_stage(3); + for(u32 i=0;i<4;i++){ REG(0xE000E180u+4u*i)=0xFFFFFFFFu; REG(0xE000E280u+4u*i)=0xFFFFFFFFu; } /* all IRQs off, nothing pending */ + REG(GPIO2+0x04) &= ~3u; g_enc_last=REG(GPIO2) & 3u; + SYST_RVR=96000u-1u; SYST_CVR=0; SYST_CSR=7; + __asm__ volatile("cpsie i"); + /* wait until the start keys (A+C) are released */ + for(u32 t=0; (hw_buttons() & (BTN_A|BTN_C)) && t<3000u; t++) delay(1); +#ifdef DOOM_FREE + /* packed flash pointers reach two 4 MB windows: the ones that hold the WAD and the level data */ +#ifdef PDM_PKREG + /* 1.7.3 test15: only the level data (sector line lists) is reached by packed pointers, the WAD by full ones: the + * windows follow the level data, so the WAD can be bigger than 8 MB (whole DOOM.WAD in one piece) */ + g_pk_lo = 0x60000000u + (g_dcfg.region_off & ~0x3FFFFFu); g_pk_hi = g_pk_lo + 0x400000u; +#else + g_pk_lo = 0x60000000u + ((g_dcfg.wad_off - 4u) & ~0x3FFFFFu); g_pk_hi = g_pk_lo + 0x400000u; +#endif + doom_iwad = (const unsigned char*) (0x60000000u + g_dcfg.wad_off); p_doom_iwad_len = (const unsigned int*) (0x60000000u + g_dcfg.wad_off - 4u); +#endif + plat_stage(4); Z_Init(); plat_stage(5); InitGlobals(); plat_stage(6); D_DoomMain(); + plat_leave(); +} + +/* v0.1.9: separate stack for fault handling, in case the broken stack itself is the cause */ +#ifdef PDM_MOREZONE +/* 1.7.3 test17: the fault stack in the small RAM at 0x20000000 (below the mailbox), its 1 KB goes to the zone */ +__attribute__((naked, section(".pram_text"))) static void Fault_Handler(void){ + __asm__ volatile("mrs r0, msp\n mov r1, lr\n ldr r2, =0x20000800\n mov sp, r2\n b plat_fault\n .ltorg\n"); } +#else +__attribute__((section(".bss"), aligned(8))) u32 g_fault_stack[256]; +__attribute__((naked, section(".pram_text"))) static void Fault_Handler(void){ + __asm__ volatile("mrs r0, msp\n mov r1, lr\n ldr r2, =g_fault_stack+1024\n mov sp, r2\n b plat_fault\n .ltorg\n"); } +#endif +static int fr_ok(u32 *fr){ u32 a=(u32)fr; + return ((a>=0x18000000u && a<=0x18020000u-32u) || (a>=0x20001000u && a<=0x20010000u-32u)) && !(a&3u); } +u32 g_in_fault; +/* Fault screen: F , , ,
, stage. Wheel 2 s: return to normal mode and from there back to the Paradise. */ + +#ifdef UA_FIX +/* v0.2.3: emulate unaligned LDRD/STRD/LDM/STM (always a fault on Cortex-M3) in the UsageFault and keep running. + * The first 8 locations go into the event log (type 6, counter, then pc) so they can be fixed in the source. */ +static u32 g_ua_n, g_ua_pc[8]; +static int ua_rd(u32 *fr, u32 *r48, u32 n, u32 *v){ + if(n<4u){ *v=fr[n]; return 1; } if(n<12u){ *v=r48[n-4u]; return 1; } if(n==12u){ *v=fr[4]; return 1; } if(n==14u){ *v=fr[5]; return 1; } return 0; } +static int ua_wr(u32 *fr, u32 *r48, u32 n, u32 v){ + if(n<4u){ fr[n]=v; return 1; } if(n<12u){ r48[n-4u]=v; return 1; } if(n==12u){ fr[4]=v; return 1; } if(n==14u){ fr[5]=v; return 1; } return 0; } +static u32 ua_ld(u32 a){ const volatile u8 *p=(const volatile u8*)a; return (u32)p[0] | ((u32)p[1]<<8) | ((u32)p[2]<<16) | ((u32)p[3]<<24); } +static void ua_st(u32 a, u32 v){ volatile u8 *p=(volatile u8*)a; p[0]=(u8)v; p[1]=(u8)(v>>8); p[2]=(u8)(v>>16); p[3]=(u8)(v>>24); } +__attribute__((used, section(".pram_text"))) u32 ua_fix(u32 *fr, u32 exc, u32 *r48){ + (void)exc; + if(!(REG(0xE000ED28u) & (1u<<24))) return 0; + if(fr[7] & 0x0600FC00u) return 0; /* inside an IT block: do not emulate */ + u32 pc=fr[6]; u32 h1=*(const volatile u16*)pc, h2=*(const volatile u16*)(pc+2u), len=4; + u32 rn, base; + if((h1 & 0xFE40u)==0xE840u){ /* LDRD/STRD (immediate) */ + rn=h1 & 15u; u32 P=(h1>>8)&1u, U=(h1>>7)&1u, W=(h1>>5)&1u, L=(h1>>4)&1u, rt=h2>>12, rt2=(h2>>8)&15u, imm=(h2 & 0xFFu)<<2; + if(!ua_rd(fr,r48,rn,&base)) return 0; + u32 off = U ? base+imm : base-imm, a = P ? off : base, v1, v2; + if(L){ v1=ua_ld(a); v2=ua_ld(a+4u); if(!ua_wr(fr,r48,rt,v1) || !ua_wr(fr,r48,rt2,v2)) return 0; } + else { if(!ua_rd(fr,r48,rt,&v1) || !ua_rd(fr,r48,rt2,&v2)) return 0; ua_st(a,v1); ua_st(a+4u,v2); } + if(W && !ua_wr(fr,r48,rn,off)) return 0; + } else if((h1 & 0xFF80u)==0xE880u || (h1 & 0xFF80u)==0xE900u){ /* LDM/STM IA or DB */ + rn=h1 & 15u; u32 W=(h1>>5)&1u, L=(h1>>4)&1u, db=(h1 & 0xFF80u)==0xE900u, list=h2 & 0xDFFFu, cnt=0; + if(!ua_rd(fr,r48,rn,&base)) return 0; + for(u32 i=0;i<16u;i++) if(list & (1u<>8)&7u; u32 L=(h1>>11)&1u, list=h1 & 0xFFu, cnt=0; + if(!ua_rd(fr,r48,rn,&base)) return 0; + u32 a=base; + for(u32 i=0;i<8u;i++) if(list & (1u<> 16}; static const u8 n[3]={1,8,4}; plat_line(5, v, n, 3); } + { u32 v[2]={0xD, adr}; static const u8 n[2]={1,8}; plat_line(6, v, n, 2); } + { u32 v[3]={0xE, g_stage, g_fl_words}; static const u8 n[3]={1,2,6}; plat_line(7, v, n, 3); } + for(u32 t=0;;t++){ hw_wdt_feed(); if(hw_buttons() & BTN_WHEEL){ if(t>2000000u) break; } else t=0; } + if(!frgood) plat_leave(); + /* back to thread mode, straight into plat_leave */ + fr[6]=((u32)plat_leave) & ~1u; fr[7]=0x01000000u; + REG(0xE000ED28u)=cfsr; REG(0xE000ED2Cu)=hfsr; + __asm__ volatile("mov lr, %0\n bx lr\n" :: "r"(exc)); +} +/* v0.1.5: unexpected interrupt (e.g. end of flash DMA, IRQ 58): disable only this one in the NVIC. + * Before, this was "cpsid i": after that the timer (SysTick) stopped too, and DOOM waited forever for the next tick. */ +__attribute__((used, section(".pram_text"))) void irq_off_c(void){ + u32 ipsr; __asm__ volatile("mrs %0, ipsr" : "=r"(ipsr)); + u32 n=(ipsr & 0x1FFu); + if(n>=16u){ n-=16u; REG(0xE000E180u + 4u*(n>>5)) = 1u<<(n&31u); REG(0xE000E280u + 4u*(n>>5)) = 1u<<(n&31u); } +} +__attribute__((naked, section(".pram_text"))) static void Irq_Off(void){ __asm__ volatile("b irq_off_c\n"); } +__attribute__((naked, section(".pram_text"))) static void Exc_Off(void){ __asm__ volatile("bx lr\n"); } +__attribute__((section(".vectors"), used)) +const void* const g_vectors[16+64] = { (void*)0x18020000u, (void*)Reset_Handler, + [2 ... 14] = (void*)Fault_Handler, [11] = (void*)Exc_Off, [14] = (void*)Exc_Off, +#ifdef UA_FIX + [6] = (void*)Usage_Handler, +#endif + [15] = (void*)SysTick_Handler, [16 ... 79] = (void*)Irq_Off }; + +/* ---- Reading from flash: aligned words (single uncached bytes are about 8x slower) ---- */ +void plat_fcopy(void *dst, const void *src, unsigned int n){ + u32 s=(u32)src; u8 *d=(u8*)dst; + if(s - 0x60000000u >= 0x01000000u){ memcpy(dst, src, n); return; } + if(!n) return; + const volatile u32 *w=(const volatile u32*)(s & ~3u); u32 sh=s & 3u; + u32 v=*w++ >> (8u*sh); + u32 k=4u-sh; + while(n && k){ *d++=(u8)v; v>>=8; n--; k--; } + if(!(((u32)d) & 3u)){ u32 *dw=(u32*)d; while(n>=4u){ *dw++=*w++; n-=4u; } d=(u8*)dw; } + else while(n>=4u){ u32 x=*w++; d[0]=(u8)x; d[1]=(u8)(x>>8); d[2]=(u8)(x>>16); d[3]=(u8)(x>>24); d+=4; n-=4u; } + if(n){ u32 x=*w; while(n--){ *d++=(u8)x; x>>=8; } } +} +/* Copy into PRAM: only from code outside PRAM and with interrupts off (otherwise instruction fetch gets corrupted) */ +void plat_pram_copy(void *d, const void *s, unsigned n){ + __asm__ volatile("cpsid i"); + plat_fcopy(d, s, n); + __asm__ volatile("dsb\n isb\n cpsie i"); +} +/* Flats: 4 slots of 4 KB in PRAM, the least recently used one is replaced */ +#ifdef PDM_MOREZONE +#define NFLAT 1 /* 1.7.3 test17: one flat in RAM, the 4 KB go to the zone (big maps like Sigil ran out of memory) */ +#else +#define NFLAT 2 /* v0.1.4: in RAM at 0x2000xxxx instead of PRAM (writing to PRAM is unreliable on the device) */ +#endif +__attribute__((section(".ram20_bss"), aligned(4))) static uint8_t g_flat[NFLAT][4096]; +#ifdef PDM_MOREZONE +static int g_flat_lump[NFLAT] = { -1 }; +#else +static int g_flat_lump[NFLAT] = { -1, -1 }; +#endif +static u32 g_flat_use[NFLAT], g_flat_clock; +const uint8_t *plat_flat(int lump, const uint8_t *src){ + g_flat_clock++; + for(int i=0;i PRAM + .pbss (NOLOAD) : { . = ALIGN(4); *(.pram_bss*) . = ALIGN(4); __pbss_end = .; } > PRAM + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + __pram_end = LOADADDR(.data) + SIZEOF(.data); + .r20 : { + __r20_start = .; + INCLUDE r20_hot.ld + . = ALIGN(4); + __r20_end = .; + } > RAM20 AT > XIP + __r20_load = LOADADDR(.r20); + .xip : { *(.text*) *(.rodata*) . = ALIGN(4); } > XIP + .ARM.exidx : { *(.ARM.exidx*) } > XIP + .r20bss (NOLOAD) : { __r20b_start = .; *(.ram20_bss*) . = ALIGN(4); __r20b_end = .; } > RAM20 + .bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) *(.openings_bss*) . = ALIGN(8); *(.displayData_bss*) . = ALIGN(4); __bss_end = .; } > SRAM + /DISCARD/ : { *(.init) *(.fini) *(.init_array*) *(.fini_array*) *(.eh_frame) *(.comment) *(.ARM.attributes) } +} diff --git a/doom/src/pdoom/dev/paradise_sram.ld b/doom/src/pdoom/dev/paradise_sram.ld new file mode 100644 index 0000000..edf5f07 --- /dev/null +++ b/doom/src/pdoom/dev/paradise_sram.ld @@ -0,0 +1,35 @@ +/* DOOM on the Paradise: PRAM (loaded by the stub), RAM at 0x20001000, program window 0x10000000, SRAM */ +ENTRY(Reset_Handler) +MEMORY { + PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000 + RAM20 (rwx) : ORIGIN = 0x20001000, LENGTH = 0xF000 + XIP (rx) : ORIGIN = 0x100A0000, LENGTH = 0x5D000 + SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F400 +} +SECTIONS { + .pram : { + KEEP(*(.vectors)) + KEEP(*(.pmxcfg)) + KEEP(*(.pdmcfg)) + *(.pram_text*) *(.pram_rodata*) *(.initcode*) *(.initdata*) + *hw.o(.text* .rodata*) *flash.o(.text* .rodata*) + INCLUDE pram_hot.ld + . = ALIGN(4); + } > PRAM + .pbss (NOLOAD) : { . = ALIGN(4); *(.pram_bss*) . = ALIGN(4); __pbss_end = .; } > PRAM + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + __pram_end = LOADADDR(.data) + SIZEOF(.data); + .r20 : { + __r20_start = .; + INCLUDE r20_hot.ld + . = ALIGN(4); + __r20_end = .; + } > RAM20 AT > XIP + __r20_load = LOADADDR(.r20); + .xip : { *(.text*) *(.rodata*) . = ALIGN(4); } > XIP + .ARM.exidx : { *(.ARM.exidx*) } > XIP + .r20bss (NOLOAD) : { __r20b_start = .; *(.ram20_bss*) . = ALIGN(4); __r20b_end = .; } > SRAM + .bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) *(.openings_bss*) . = ALIGN(8); *(.displayData_bss*) . = ALIGN(4); __bss_end = .; } > SRAM + /DISCARD/ : { *(.init) *(.fini) *(.init_array*) *(.fini_array*) *(.eh_frame) *(.comment) *(.ARM.attributes) } +} diff --git a/doom/src/pdoom/dev/pdmcfg.h b/doom/src/pdoom/dev/pdmcfg.h new file mode 100644 index 0000000..fe046a4 --- /dev/null +++ b/doom/src/pdoom/dev/pdmcfg.h @@ -0,0 +1,32 @@ +/* DOOM settings block (PDMC), filled in by the Studio. Shared with the core for DOOM_FREE (1.7.2 test3): the places + * of the WAD, the level data, the save and the program part are read from here instead of being fixed. */ +#ifndef PDMCFG_H +#define PDMCFG_H +#include +typedef struct { + uint32_t magic, version; + uint32_t wad_off, wad_len; /* WAD in flash (offset), 4 byte length before the WAD */ + uint32_t region_off, region_len; /* area for precomputed data (the core writes it itself) */ + uint32_t save_off; /* 2 x 4 KB: settings, save */ + uint32_t code_off; /* program part in the flash window */ + uint32_t detent; /* encoder steps per detent (2 or 4) */ + uint32_t turn_tics; /* turn duration per detent in game tics */ + uint32_t sound; /* 1 = sound on */ + uint32_t invert; /* 1 = wheel reversed */ + /* from version 2 (KEYMAP): key mapping as button masks (BTN_A 1, BTN_B 2, BTN_C 4, BTN_WHEEL 8) */ + uint32_t k_fire, k_fwd, k_back, k_use, k_mod; /* k_mod: hold + wheel = switch weapon, hold + press wheel = sound */ + uint32_t run_dbl; /* 1 = double tap forward toggles run */ +#ifdef PDM_CMAPXIP + uint32_t cmap_off; /* version 3 (1.7.3 test17): flash place of a COLORMAP copy in the program part (0: none) */ +#endif +} PdmCfg; +extern volatile const PdmCfg g_dcfg; +#ifdef DOOM_FREE +/* the two 4 MB windows of the packed flash pointers (set at start from wad_off) */ +extern uint32_t g_pk_lo, g_pk_hi; +/* the program part sits at XIP 0x100A0000: the window base follows code_off */ +#define PD_XIP_BASE (0x60000000u + g_dcfg.code_off - 0xA0000u) +#else +#define PD_XIP_BASE 0x60011000u +#endif +#endif diff --git a/doom/src/pdoom/dev/pram_hot.ld b/doom/src/pdoom/dev/pram_hot.ld new file mode 100644 index 0000000..32bade7 --- /dev/null +++ b/doom/src/pdoom/dev/pram_hot.ld @@ -0,0 +1,6 @@ +*r_fast_stuff.o(.text* .rodata*) +*libgcc.a:*(.text*) +*libc_a-memcpy*.o(.text*) +*libc_a-memset*.o(.text*) +*i_main.o(.text*) +*m_fixed.o(.text*) diff --git a/doom/src/pdoom/dev/r20_hot.ld b/doom/src/pdoom/dev/r20_hot.ld new file mode 100644 index 0000000..d3f5a12 --- /dev/null +++ b/doom/src/pdoom/dev/r20_hot.ld @@ -0,0 +1 @@ + diff --git a/doom/src/pdoom/plat/delay.h b/doom/src/pdoom/plat/delay.h new file mode 100644 index 0000000..a8ad594 --- /dev/null +++ b/doom/src/pdoom/plat/delay.h @@ -0,0 +1,4 @@ +#ifndef DELAY_H +#define DELAY_H +void delay(unsigned int ms); +#endif diff --git a/doom/src/pdoom/plat/display.h b/doom/src/pdoom/plat/display.h new file mode 100644 index 0000000..e57b048 --- /dev/null +++ b/doom/src/pdoom/plat/display.h @@ -0,0 +1,4 @@ +#ifndef DISPLAYH +#define DISPLAYH +#include "main.h" +#endif diff --git a/doom/src/pdoom/plat/graphics.h b/doom/src/pdoom/plat/graphics.h new file mode 100644 index 0000000..3bab0fa --- /dev/null +++ b/doom/src/pdoom/plat/graphics.h @@ -0,0 +1,28 @@ +#ifndef SRC_GRAPHICS_H_ +#define SRC_GRAPHICS_H_ +#include +#include +#ifndef PDOOM_W +#define PDOOM_W 128 +#define PDOOM_H 128 +#endif +typedef struct +{ + volatile uint16_t * pPalette; +#ifdef SINGLE_FB + uint8_t *displayFrameBuffer[2]; /* v0.2.2: both point to the same framebuffer in SRAM */ +#else + uint8_t displayFrameBuffer[2][PDOOM_W * PDOOM_H]; +#endif + uint8_t workingBuffer; + uint8_t displayMode; + volatile uint8_t dmaBusy; +} displayData_t; +extern displayData_t displayData; +void displayPrintf(int x, int y, const char * format, ...); +void startDisplayRefresh(uint8_t bufferNumber); +void setDisplayPen(int color, int background); +void clearScreen4bpp(void); +void displayPrintln(bool update, const char * format, ...); +void initGraphics(void); +#endif diff --git a/doom/src/pdoom/plat/keyboard.h b/doom/src/pdoom/plat/keyboard.h new file mode 100644 index 0000000..253c6af --- /dev/null +++ b/doom/src/pdoom/plat/keyboard.h @@ -0,0 +1,16 @@ +#ifndef KEYBOARD_H +#define KEYBOARD_H +#include +#include "main.h" +#define KEY_MAP 0x0001 +#define KEY_ALT 0x0002 +#define KEY_USE 0x0004 +#define KEY_LEFT 0x0008 +#define KEY_DOWN 0x0010 +#define KEY_FIRE 0x0020 +#define KEY_CHGW 0x0040 +#define KEY_UP 0x0080 +#define KEY_MENU 0x0100 +#define KEY_RIGHT 0x0200 +void getKeys(pkey_t *keys); +#endif diff --git a/doom/src/pdoom/plat/main.h b/doom/src/pdoom/plat/main.h new file mode 100644 index 0000000..0abd69a --- /dev/null +++ b/doom/src/pdoom/plat/main.h @@ -0,0 +1,29 @@ +/* Paradise: settings for the DOOM core (replaces main.h of the nRF52840 version) */ +#ifndef MAIN_H +#define MAIN_H +#include +#include +#include "graphics.h" +#ifndef CACHE_ALL_COLORMAP_TO_RAM +#define CACHE_ALL_COLORMAP_TO_RAM 0 +#endif +#ifndef DEBUG_SETUP +#define DEBUG_SETUP 0 +#endif +#ifndef START_MAP +#define START_MAP 1 +#endif +#ifndef SHOW_FPS +#define SHOW_FPS false +#endif +#ifndef AUTOSTART_GAME +#define AUTOSTART_GAME 0 +#endif +#define GAMMA_CORRECTION 0 +#define I2C_GAMEPAD 4 +#ifdef PARADISE_DEV +#define KEYBOARD I2C_GAMEPAD +#endif +typedef uint16_t pkey_t; +#define key_t pkey_t +#endif diff --git a/doom/src/pdoom/plat/nrf.h b/doom/src/pdoom/plat/nrf.h new file mode 100644 index 0000000..a9977cf --- /dev/null +++ b/doom/src/pdoom/plat/nrf.h @@ -0,0 +1,13 @@ +#ifndef PARADISE_NRF_SHIM +#define PARADISE_NRF_SHIM +#include +#define __DMB() __asm__ volatile("dmb" ::: "memory") +#define __DSB() __asm__ volatile("dsb" ::: "memory") +#define __ISB() __asm__ volatile("isb" ::: "memory") +#endif +/* Paradise: stand-in for the nRF52840 QSPI DMA. The flash is directly readable, reads happen immediately. */ +#include +typedef struct { struct { volatile uint32_t CNT, SRC, DST; } READ; volatile uint32_t EVENTS_READY; } plat_qspi_t; +extern plat_qspi_t plat_qspi; +#define NRF_QSPI (&plat_qspi) +static inline void plat_qspi_read(void){ memcpy((void*)plat_qspi.READ.DST, (const void*)plat_qspi.READ.SRC, plat_qspi.READ.CNT); plat_qspi.EVENTS_READY = 1; } diff --git a/doom/src/pdoom/plat/plat_stub.c b/doom/src/pdoom/plat/plat_stub.c new file mode 100644 index 0000000..21eac9d --- /dev/null +++ b/doom/src/pdoom/plat/plat_stub.c @@ -0,0 +1,24 @@ +/* Temporary placeholders, only for measuring sizes */ +#include +#include "graphics.h" +#include "pwm_audio.h" +#include "nrf.h" +displayData_t displayData; +soundChannel_t soundChannels[MAX_CHANNELS]; +plat_qspi_t plat_qspi; +void SetBacklight(int x){(void)x;} +void delay(unsigned int ms){(void)ms;} +void disableWirelessAudio(void){} +void restoreWirelessAudio(void){} +void getKeys(uint16_t *k){*k=0;} +void muteSound(void){} +void updateSound(void){} +void plat_flash_erase4k(uint32_t a){(void)a;} +void plat_flash_word(uint32_t a, uint32_t w){(void)a;(void)w;} +unsigned int plat_micros(void){return 0;} +uint32_t qspiFlashGetSize(void){return 0x1000000;} +void qspiFlashErasePage4k(uint32_t a){(void)a;} +void qspiFlashProgram(uint32_t a, const void *b, uint32_t s){(void)a;(void)b;(void)s;} +void startDisplayRefresh(uint8_t b){(void)b;} +void _putchar(char c){(void)c;} +int main(void){ extern void D_DoomMain(void); D_DoomMain(); return 0; } diff --git a/doom/src/pdoom/plat/printf.c b/doom/src/pdoom/plat/printf.c new file mode 100644 index 0000000..9af97a7 --- /dev/null +++ b/doom/src/pdoom/plat/printf.c @@ -0,0 +1,917 @@ +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. These routines are thread +// safe and reentrant! +// Use this instead of the bloated standard/newlib printf cause these use +// malloc for printf (and may not be thread safe). +// +/////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "printf.h" + +#define PRINTF_DISABLE_SUPPORT_FLOAT +#define PRINTF_DISABLE_SUPPORT_EXPONENTIAL +#define PRINTF_DISABLE_SUPPORT_LONG_LONG +#define PRINTF_DISABLE_SUPPORT_PTRDIFF_T +// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the +// printf_config.h header file +// default: undefined +#ifdef PRINTF_INCLUDE_CONFIG_H +#include "printf_config.h" +#endif + + +// 'ntoa' conversion buffer size, this must be big enough to hold one converted +// numeric number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_NTOA_BUFFER_SIZE +#define PRINTF_NTOA_BUFFER_SIZE 16U // 16 is enough for 32 bit integers. +#endif + +// 'ftoa' conversion buffer size, this must be big enough to hold one converted +// float number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_FTOA_BUFFER_SIZE +#define PRINTF_FTOA_BUFFER_SIZE 16U +#endif + +// support for the floating point type (%f) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_FLOAT +#define PRINTF_SUPPORT_FLOAT +#endif + +// support for exponential floating point notation (%e/%g) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL +#define PRINTF_SUPPORT_EXPONENTIAL +#endif + +// define the default floating point precision +// default: 6 digits +#ifndef PRINTF_DEFAULT_FLOAT_PRECISION +#define PRINTF_DEFAULT_FLOAT_PRECISION 6U +#endif + +// define the largest float suitable to print with %f +// default: 1e9 +#ifndef PRINTF_MAX_FLOAT +#define PRINTF_MAX_FLOAT 1e9 +#endif + +// support for the long long types (%llu or %p) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG +#define PRINTF_SUPPORT_LONG_LONG +#endif + +// support for the ptrdiff_t type (%t) +// ptrdiff_t is normally defined in as long or long long type +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T +#define PRINTF_SUPPORT_PTRDIFF_T +#endif + +/////////////////////////////////////////////////////////////////////////////// + +// internal flag definitions +#define FLAGS_ZEROPAD (1U << 0U) +#define FLAGS_LEFT (1U << 1U) +#define FLAGS_PLUS (1U << 2U) +#define FLAGS_SPACE (1U << 3U) +#define FLAGS_HASH (1U << 4U) +#define FLAGS_UPPERCASE (1U << 5U) +#define FLAGS_CHAR (1U << 6U) +#define FLAGS_SHORT (1U << 7U) +#define FLAGS_LONG (1U << 8U) +#define FLAGS_LONG_LONG (1U << 9U) +#define FLAGS_PRECISION (1U << 10U) +#define FLAGS_ADAPT_EXP (1U << 11U) + + +// import float.h for DBL_MAX +#if defined(PRINTF_SUPPORT_FLOAT) +#include +#endif + + +// output function type +typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen); + + +// wrapper (used as buffer) for output function type +typedef struct { + void (*fct)(char character, void* arg); + void* arg; +} out_fct_wrap_type; + + +// internal buffer output +static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen) +{ + if (idx < maxlen) { + ((char*)buffer)[idx] = character; + } +} + + +// internal null output +static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)character; (void)buffer; (void)idx; (void)maxlen; +} + + +// internal _putchar wrapper +static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)buffer; (void)idx; (void)maxlen; + if (character) { + _putchar(character); + } +} + + +// internal output function wrapper +static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)idx; (void)maxlen; + if (character) { + // buffer is the output fct pointer + ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg); + } +} + + +// internal secure strlen +// \return The length of the string (excluding the terminating 0) limited by 'maxsize' +static inline unsigned int _strnlen_s(const char* str, size_t maxsize) +{ + const char* s; + for (s = str; *s && maxsize--; ++s); + return (unsigned int)(s - str); +} + + +// internal test if char is a digit (0-9) +// \return true if char is a digit +static inline bool _is_digit(char ch) +{ + return (ch >= '0') && (ch <= '9'); +} + + +// internal ASCII string to unsigned int conversion +static unsigned int _atoi(const char** str) +{ + unsigned int i = 0U; + while (_is_digit(**str)) { + i = i * 10U + (unsigned int)(*((*str)++) - '0'); + } + return i; +} + + +// output the specified string in reverse, taking care of any zero-padding +static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags) +{ + const size_t start_idx = idx; + + // pad spaces up to given width + if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) { + for (size_t i = len; i < width; i++) { + out(' ', buffer, idx++, maxlen); + } + } + + // reverse string + while (len) { + out(buf[--len], buffer, idx++, maxlen); + } + + // append pad spaces up to given width + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) { + out(' ', buffer, idx++, maxlen); + } + } + + return idx; +} + + +// internal itoa format +static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags) +{ + // pad leading zeros + if (!(flags & FLAGS_LEFT)) { + if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + // handle hash + if (flags & FLAGS_HASH) { + if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) { + len--; + if (len && (base == 16U)) { + len--; + } + } + if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'x'; + } + else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'X'; + } + else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'b'; + } + if (len < PRINTF_NTOA_BUFFER_SIZE) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_NTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +// internal itoa for 'long' type +static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} + + +// internal itoa for 'long long' type +#if defined(PRINTF_SUPPORT_LONG_LONG) +static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} +#endif // PRINTF_SUPPORT_LONG_LONG + + +#if defined(PRINTF_SUPPORT_FLOAT) + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags); +#endif + + +// internal ftoa for fixed decimal floating point +static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_FTOA_BUFFER_SIZE]; + size_t len = 0U; + double diff = 0.0; + + // powers of 10 + static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + + // test for special values + if (value != value) + return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags); + if (value < -DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags); + if (value > DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags); + + // test for very large values + // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad + if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) { + #if defined(PRINTF_SUPPORT_EXPONENTIAL) + return _etoa(out, buffer, idx, maxlen, value, prec, width, flags); + #else + return 0U; + #endif + } + + // test for negative + bool negative = false; + if (value < 0) { + negative = true; + value = 0 - value; + } + + // set default precision, if not set explicitly + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + // limit precision to 9, cause a prec >= 10 can lead to overflow errors + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) { + buf[len++] = '0'; + prec--; + } + + int whole = (int)value; + double tmp = (value - whole) * pow10[prec]; + unsigned long frac = (unsigned long)tmp; + diff = tmp - frac; + + if (diff > 0.5) { + ++frac; + // handle rollover, e.g. case 0.99 with prec 1 is 1.0 + if (frac >= pow10[prec]) { + frac = 0; + ++whole; + } + } + else if (diff < 0.5) { + } + else if ((frac == 0U) || (frac & 1U)) { + // if halfway, round up if odd OR if last digit is 0 + ++frac; + } + + if (prec == 0U) { + diff = value - (double)whole; + if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) { + // exactly 0.5 and ODD, then round up + // 1.5 -> 2, but 2.5 -> 2 + ++whole; + } + } + else { + unsigned int count = prec; + // now do fractional part, as an unsigned number + while (len < PRINTF_FTOA_BUFFER_SIZE) { + --count; + buf[len++] = (char)(48U + (frac % 10U)); + if (!(frac /= 10U)) { + break; + } + } + // add extra 0s + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) { + buf[len++] = '0'; + } + if (len < PRINTF_FTOA_BUFFER_SIZE) { + // add decimal + buf[len++] = '.'; + } + } + + // do whole part, number is reversed + while (len < PRINTF_FTOA_BUFFER_SIZE) { + buf[len++] = (char)(48 + (whole % 10)); + if (!(whole /= 10)) { + break; + } + } + + // pad leading zeros + if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) { + if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_FTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + // check for NaN and special values + if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) { + return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags); + } + + // determine the sign + const bool negative = value < 0; + if (negative) { + value = -value; + } + + // default precision + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + + // determine the decimal exponent + // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c) + union { + uint64_t U; + double F; + } conv; + + conv.F = value; + int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2 + conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2) + // now approximate log10 from the log2 integer part and an expansion of ln around 1.5 + int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168); + // now we want to compute 10^expval but we want to be sure it won't overflow + exp2 = (int)(expval * 3.321928094887362 + 0.5); + const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453; + const double z2 = z * z; + conv.U = (uint64_t)(exp2 + 1023) << 52U; + // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex + conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14))))); + // correct for rounding errors + if (value < conv.F) { + expval--; + conv.F /= 10; + } + + // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters + unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U; + + // in "%g" mode, "prec" is the number of *significant figures* not decimals + if (flags & FLAGS_ADAPT_EXP) { + // do we want to fall-back to "%f" mode? + if ((value >= 1e-4) && (value < 1e6)) { + if ((int)prec > expval) { + prec = (unsigned)((int)prec - expval - 1); + } + else { + prec = 0; + } + flags |= FLAGS_PRECISION; // make sure _ftoa respects precision + // no characters in exponent + minwidth = 0U; + expval = 0; + } + else { + // we use one sigfig for the whole part + if ((prec > 0) && (flags & FLAGS_PRECISION)) { + --prec; + } + } + } + + // will everything fit? + unsigned int fwidth = width; + if (width > minwidth) { + // we didn't fall-back so subtract the characters required for the exponent + fwidth -= minwidth; + } else { + // not enough characters, so go back to default sizing + fwidth = 0U; + } + if ((flags & FLAGS_LEFT) && minwidth) { + // if we're padding on the right, DON'T pad the floating part + fwidth = 0U; + } + + // rescale the float value + if (expval) { + value /= conv.F; + } + + // output the floating part + const size_t start_idx = idx; + idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP); + + // output the exponent part + if (minwidth) { + // output the exponential symbol + out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen); + // output the exponent value + idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS); + // might need to right-pad spaces + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) out(' ', buffer, idx++, maxlen); + } + } + return idx; +} +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + + +// internal vsnprintf +static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va) +{ + unsigned int flags, width, precision, n; + size_t idx = 0U; + + if (!buffer) { + // use null output function + out = _out_null; + } + + while (*format) + { + // format specifier? %[flags][width][.precision][length] + if (*format != '%') { + // no + out(*format, buffer, idx++, maxlen); + format++; + continue; + } + else { + // yes, evaluate it + format++; + } + + // evaluate flags + flags = 0U; + do { + switch (*format) { + case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break; + case '-': flags |= FLAGS_LEFT; format++; n = 1U; break; + case '+': flags |= FLAGS_PLUS; format++; n = 1U; break; + case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break; + case '#': flags |= FLAGS_HASH; format++; n = 1U; break; + default : n = 0U; break; + } + } while (n); + + // evaluate width field + width = 0U; + if (_is_digit(*format)) { + width = _atoi(&format); + } + else if (*format == '*') { + const int w = va_arg(va, int); + if (w < 0) { + flags |= FLAGS_LEFT; // reverse padding + width = (unsigned int)-w; + } + else { + width = (unsigned int)w; + } + format++; + } + + // evaluate precision field + precision = 0U; + if (*format == '.') { + flags |= FLAGS_PRECISION; + format++; + if (_is_digit(*format)) { + precision = _atoi(&format); + } + else if (*format == '*') { + const int prec = (int)va_arg(va, int); + precision = prec > 0 ? (unsigned int)prec : 0U; + format++; + } + } + + // evaluate length field + switch (*format) { + case 'l' : + flags |= FLAGS_LONG; + format++; + if (*format == 'l') { + flags |= FLAGS_LONG_LONG; + format++; + } + break; + case 'h' : + flags |= FLAGS_SHORT; + format++; + if (*format == 'h') { + flags |= FLAGS_CHAR; + format++; + } + break; + #if defined(PRINTF_SUPPORT_PTRDIFF_T) + case 't' : + flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + #endif + case 'j' : + flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + case 'z' : + flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + default : + break; + } + + // evaluate specifier + switch (*format) { + case 'd' : + case 'i' : + case 'u' : + case 'x' : + case 'X' : + case 'o' : + case 'b' : { + // set the base + unsigned int base; + if (*format == 'x' || *format == 'X') { + base = 16U; + } + else if (*format == 'o') { + base = 8U; + } + else if (*format == 'b') { + base = 2U; + } + else { + base = 10U; + flags &= ~FLAGS_HASH; // no hash for dec format + } + // uppercase + if (*format == 'X') { + flags |= FLAGS_UPPERCASE; + } + + // no plus or space flag for u, x, X, o, b + if ((*format != 'i') && (*format != 'd')) { + flags &= ~(FLAGS_PLUS | FLAGS_SPACE); + } + + // ignore '0' flag when precision is given + if (flags & FLAGS_PRECISION) { + flags &= ~FLAGS_ZEROPAD; + } + + // convert the integer + if ((*format == 'i') || (*format == 'd')) { + // signed + if (flags & FLAGS_LONG_LONG) { + #if defined(PRINTF_SUPPORT_LONG_LONG) + const long long value = va_arg(va, long long); + idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + #endif + } + else if (flags & FLAGS_LONG) { + const long value = va_arg(va, long); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + else { + const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + } + else { + // unsigned + if (flags & FLAGS_LONG_LONG) { + #if defined(PRINTF_SUPPORT_LONG_LONG) + idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags); + #endif + } + else if (flags & FLAGS_LONG) { + idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags); + } + else { + const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int); + idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags); + } + } + format++; + break; + } + #if defined(PRINTF_SUPPORT_FLOAT) + case 'f' : + case 'F' : + if (*format == 'F') flags |= FLAGS_UPPERCASE; + idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; + #if defined(PRINTF_SUPPORT_EXPONENTIAL) + case 'e': + case 'E': + case 'g': + case 'G': + if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP; + if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE; + idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; + #endif // PRINTF_SUPPORT_EXPONENTIAL + #endif // PRINTF_SUPPORT_FLOAT + case 'c' : { + unsigned int l = 1U; + // pre padding + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // char output + out((char)va_arg(va, int), buffer, idx++, maxlen); + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 's' : { + const char* p = va_arg(va, char*); + unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1); + // pre padding + if (flags & FLAGS_PRECISION) { + l = (l < precision ? l : precision); + } + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // string output + while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) { + out(*(p++), buffer, idx++, maxlen); + } + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 'p' : { + width = sizeof(void*) * 2U; + flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE; + #if defined(PRINTF_SUPPORT_LONG_LONG) + const bool is_ll = sizeof(uintptr_t) == sizeof(long long); + if (is_ll) { + idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags); + } + else { + #endif + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags); + #if defined(PRINTF_SUPPORT_LONG_LONG) + } + #endif + format++; + break; + } + + case '%' : + out('%', buffer, idx++, maxlen); + format++; + break; + + default : + out(*format, buffer, idx++, maxlen); + format++; + break; + } + } + + // termination + out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen); + + // return written chars without terminating \0 + return (int)idx; +} + + +/////////////////////////////////////////////////////////////////////////////// + +int printf_(const char* format, ...) +{ + va_list va; + va_start(va, format); + char buffer[1]; + const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int sprintf_(char* buffer, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int snprintf_(char* buffer, size_t count, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, count, format, va); + va_end(va); + return ret; +} + + +int vprintf_(const char* format, va_list va) +{ + char buffer[1]; + return _vsnprintf(_out_char, buffer, (size_t)-1, format, va); +} + + +int vsnprintf_(char* buffer, size_t count, const char* format, va_list va) +{ + return _vsnprintf(_out_buffer, buffer, count, format, va); +} + + +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...) +{ + va_list va; + va_start(va, format); + const out_fct_wrap_type out_fct_wrap = { out, arg }; + const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va); + va_end(va); + return ret; +} diff --git a/doom/src/pdoom/plat/printf.h b/doom/src/pdoom/plat/printf.h new file mode 100644 index 0000000..602bd52 --- /dev/null +++ b/doom/src/pdoom/plat/printf.h @@ -0,0 +1,122 @@ +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. +// Use this instead of bloated standard/newlib printf. +// These routines are thread safe and reentrant. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _PRINTF_H_ +#define _PRINTF_H_ + +#include +#include +#include "main.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * Output a character to a custom device like UART, used by the printf() function + * This function is declared here only. You have to write your custom implementation somewhere + * \param character Character to output + */ +void _putchar(char character); + + +/** + * Tiny printf implementation + * You have to implement _putchar if you use printf() + * To avoid conflicts with the regular printf() API it is overridden by macro defines + * and internal underscore-appended functions like printf_() are used + * \param format A string that specifies the format of the output + * \return The number of characters that are written into the array, not counting the terminating null character + */ +#if DEBUG_OUT_PRINTF +#define printf printf_ +#else +#define printf(...) +#endif +int printf_(const char* format, ...); + + +/** + * Tiny sprintf implementation + * Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD! + * \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output! + * \param format A string that specifies the format of the output + * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character + */ +#define sprintf sprintf_ +int sprintf_(char* buffer, const char* format, ...); + + +/** + * Tiny snprintf/vsnprintf implementation + * \param buffer A pointer to the buffer where to store the formatted string + * \param count The maximum number of characters to store in the buffer, including a terminating null character + * \param format A string that specifies the format of the output + * \param va A value identifying a variable arguments list + * \return The number of characters that COULD have been written into the buffer, not counting the terminating + * null character. A value equal or larger than count indicates truncation. Only when the returned value + * is non-negative and less than count, the string has been completely written. + */ +#define snprintf snprintf_ +#define vsnprintf vsnprintf_ +int snprintf_(char* buffer, size_t count, const char* format, ...); +int vsnprintf_(char* buffer, size_t count, const char* format, va_list va); + + +/** + * Tiny vprintf implementation + * \param format A string that specifies the format of the output + * \param va A value identifying a variable arguments list + * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character + */ +#define vprintf vprintf_ +int vprintf_(const char* format, va_list va); + + +/** + * printf with output function + * You may use this as dynamic alternative to printf() with its fixed _putchar() output + * \param out An output function which takes one character and an argument pointer + * \param arg An argument pointer for user data passed to output function + * \param format A string that specifies the format of the output + * \return The number of characters that are sent to the output function, not counting the terminating null character + */ +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...); + + +#ifdef __cplusplus +} +#endif + + +#endif // _PRINTF_H_ \ No newline at end of file diff --git a/doom/src/pdoom/plat/pwm_audio.h b/doom/src/pdoom/plat/pwm_audio.h new file mode 100644 index 0000000..4fd44be --- /dev/null +++ b/doom/src/pdoom/plat/pwm_audio.h @@ -0,0 +1,10 @@ +#ifndef SRC_PWM_AUDIO_H_ +#define SRC_PWM_AUDIO_H_ +#include "main.h" +#define MAX_CHANNELS 8 +typedef struct { uint16_t lastAudioBufferIdx; uint16_t offset; uint8_t sfxIdx; int8_t volume; } soundChannel_t; +void initPwmAudio(void); +void updateSound(void); +void muteSound(void); +extern soundChannel_t soundChannels[MAX_CHANNELS]; +#endif diff --git a/doom/src/pdoom/plat/qspi.h b/doom/src/pdoom/plat/qspi.h new file mode 100644 index 0000000..2543ac1 --- /dev/null +++ b/doom/src/pdoom/plat/qspi.h @@ -0,0 +1,7 @@ +#ifndef QSPI_H +#define QSPI_H +#include +uint32_t qspiFlashGetSize(void); +void qspiFlashErasePage4k(uint32_t address); +void qspiFlashProgram(uint32_t address, const void *buffer, uint32_t size); +#endif diff --git a/doom/src/pdoom/test/tasten_test.c b/doom/src/pdoom/test/tasten_test.c new file mode 100644 index 0000000..624482c --- /dev/null +++ b/doom/src/pdoom/test/tasten_test.c @@ -0,0 +1,99 @@ + +#include +typedef unsigned int u32; typedef unsigned short pkey_t; +#define BTN_A 1u +#define BTN_B 2u +#define BTN_C 4u +#define BTN_WHEEL 8u +enum { KEY_UP=1, KEY_DOWN=2, KEY_LEFT=4, KEY_RIGHT=8, KEY_FIRE=16, KEY_USE=32, KEY_MENU=64, KEY_MAP=128, KEY_CHGW=256 }; +static u32 T, BTN; static volatile int g_enc_det; static int runs, snd, left; +static u32 now_ms(void){ return T; } static u32 hw_buttons(void){ return BTN; } +static void plat_toggle_run(void){ runs++; } static void plat_sound_mode_next(void){ snd++; } static void plat_leave(void){ left++; } +typedef struct { u32 magic, version, a,b,c,d,e,f, detent, turn_tics, sound, invert, k_fire,k_fwd,k_back,k_use,k_mod,run_dbl; } PdmCfg; +static PdmCfg g_dcfg={0,2,0,0,0,0,0,0,1,3,1,0, BTN_A,BTN_B,BTN_C,BTN_WHEEL,BTN_C,1}; +#define cpsid +static volatile u32 g_wh_down, g_wh_cand, g_wh_t0, g_wh_press; +static void wheel_poll(u32 ms, u32 down){ + if(down==g_wh_down){ g_wh_cand=0; return; } + if(!g_wh_cand){ g_wh_cand=ms|1u; return; } + if((int)(ms-g_wh_cand)<8) return; + g_wh_cand=0; g_wh_down=down; + if(down){ g_wh_t0=ms|1u; g_wh_press++; } else g_wh_t0=0; +} +void getKeys(pkey_t *keys){ + static u32 mod_t0, b_last, b_prev, use_left, turn_left, menu_hold, chg_left, chg_dir, wh_seen; + static int turn_dir, det_seen; + u32 now=now_ms(), b=hw_buttons(); pkey_t k=0; + u32 kf=g_dcfg.k_fire, kv=g_dcfg.k_fwd, kz=g_dcfg.k_back, ku=g_dcfg.k_use, km=g_dcfg.k_mod; + if(g_dcfg.version<2u){ kf=BTN_A; kv=BTN_B; kz=BTN_C; ku=BTN_WHEEL; km=BTN_C; } + /* Wheel pressed: with hold key = sound, otherwise use (if mapped so); held 2 s from the last press = exit. + * Presses and the time come from the millisecond timer (wheel_poll); this call only adds a sample + * in case the timer interrupt does not run. */ + u32 np, wdown, wt0; + + wheel_poll(now, (b & BTN_WHEEL) ? 1u : 0u); + np=g_wh_press-wh_seen; wh_seen+=np; wdown=g_wh_down; wt0=g_wh_t0; + + if(np){ if(b & km){ det_seen=1; plat_sound_mode_next(); } else if(ku==BTN_WHEEL) use_left=3; } + if(wdown && wt0 && now-wt0>2000u) plat_leave(); + int det; det=g_enc_det; g_enc_det=0; + if(g_dcfg.invert) det=-det; + if(det){ + if(b & km){ chg_left=2; chg_dir = det>0 ? 1u : 0u; det_seen=1; } + else { if((det>0) != (turn_dir>0)) turn_left=0; turn_dir = det>0 ? 1 : -1; turn_left += (u32)(det>0?det:-det) * g_dcfg.turn_tics; } + } + int ac = (b & BTN_A) && (b & BTN_C), bc = (b & BTN_B) && (b & BTN_C); + if(ac) menu_hold++; else menu_hold=0; + if(ac){ if(menu_hold<=2) k|=KEY_MENU; } + else if(bc){ k|=KEY_MAP; } + else { + /* pressed, unless the hold key is still in its waiting time */ + u32 eff = b & ~km; + if((b & km) && !det_seen){ if(!mod_t0) mod_t0=now|1u; if((int)(now-mod_t0)>=120) eff |= km; } /* v0.4.0: signed, otherwise a step already came in the first tick (now even) */ + if(eff & kv) k|=KEY_UP; + if(eff & kz) k|=KEY_DOWN; + if(eff & kf) k|=KEY_FIRE; + if(ku!=BTN_WHEEL && (eff & ku) && !(b_last & ku)) use_left=3; + } + if(!(b & km)){ mod_t0=0; det_seen=0; } + if(g_dcfg.run_dbl || g_dcfg.version<2u){ + if((b & kv) && !(b_last & kv)){ if(b_prev && now-b_prev<300u){ plat_toggle_run(); b_prev=0; } else b_prev=now; } + } + b_last = b; + if(use_left){ use_left--; k|=KEY_USE; } + if(turn_left){ turn_left--; k |= turn_dir>0 ? KEY_RIGHT : KEY_LEFT; } + if(chg_left){ chg_left--; k |= chg_dir ? KEY_CHGW : (KEY_CHGW|KEY_USE); } + *keys=k; +} +static void tick(u32 b){ BTN=b; T++; wheel_poll(T,(b&BTN_WHEEL)?1u:0u); } +static pkey_t step(u32 b,int det){ BTN=b; g_enc_det=det; pkey_t k; getKeys(&k); for(int i=0;i<10;i++) tick(b); return k; } +/* one frame of 100 ms with a quick tap: up 30 ms, then down; the frame itself only sees "down" */ +static pkey_t frame_tap(void){ pkey_t k=0; for(int i=0;i<100;i++) tick(i>=30?BTN_WHEEL:0); getKeys(&k); return k; } +static pkey_t run(u32 b,int n){ pkey_t acc=0; for(int i=0;i=20, "quick taps: use comes"); } + run(0,50); left=0; run(BTN_WHEEL,150); CHECK(left==0, "wheel 1.5 s: still in"); run(BTN_WHEEL,60); CHECK(left>0, "wheel over 2 s: exit"); + printf(bad?"%d wrong\n":"all good\n",bad); return bad; +} diff --git a/doom/src/pdoom/tools/gbaextras.py b/doom/src/pdoom/tools/gbaextras.py new file mode 100644 index 0000000..4c7a526 --- /dev/null +++ b/doom/src/pdoom/tools/gbaextras.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Replacement for gbadoom.wad, built only from your own DOOM.WAD (no third-party graphics). +gbaextras.py +Lumps: CREDITS (empty), M_ARUN, M_GAMMA (from STCFN letters), STGANUM0..9 (narrower STTNUM), +PLAYPAL1..5 (copies, the core computes gamma itself), STBARGBA (240x32 status bar, raw, from STBAR/STARMS/STTPRCNT).""" +import struct, sys + +def read_wad(path): + d = open(path, 'rb').read(); n, o = struct.unpack('> 16) +def FixedDiv(a, b): + if (abs(a) >> 14) >= abs(b): return -0x80000000 if (a ^ b) < 0 else 0x7FFFFFFF + q = abs(a << 16) // abs(b) + return s32(q if (a < 0) == (b < 0) else -q) +centerx = W // 2; centerxfrac = centerx << FRACBITS +focallength = FixedDiv(centerxfrac, finetangent[FINEANGLES // 4 + FIELDOFVIEW // 2]) +v2x = [] +for i in range(FINEANGLES // 2): + if finetangent[i] > FRACUNIT * 2: t = -1 + elif finetangent[i] < -FRACUNIT * 2: t = W + 1 + else: + t = FixedMul(finetangent[i], focallength) + t = (centerxfrac - t + FRACUNIT - 1) >> FRACBITS + t = max(-1, min(W + 1, t)) + v2x.append(t) +x2v = [] +for x in range(W + 1): + i = 0 + while v2x[i] > x: i += 1 + x2v.append(s32((i << ANGLETOFINESHIFT) - ANG90)) +v2x = [0 if t == -1 else (W if t == W + 1 else t) for t in v2x] +CHEIGHT = W * 3 // 4 +projectiony = ((CHEIGHT * (W // 2) * 320) // 200) * FRACUNIT // W +ys = [] +for i in range(H): + if i < VH: + dy = abs(((i - VH // 2) << FRACBITS) + FRACUNIT // 2) + ys.append(FixedDiv(projectiony, dy)) + else: ys.append(0) +ds = [] +for i in range(W): + cosadj = abs(finesine[(x2v[i] & 0xFFFFFFFF) >> ANGLETOFINESHIFT if False else ((x2v[i] & 0xFFFFFFFF) >> ANGLETOFINESHIFT) + FINEANGLES // 4]) + ds.append(FixedDiv(FRACUNIT, cosadj)) +def out(name, vals): return '#elif ' + name + '\n{ ' + ', '.join(str(v) for v in vals) + ' };\n' +print('/* viewangletox */'); print(out('SCREENWIDTH == %d' % W, v2x)) +print('/* xtoviewangle */'); print(out('SCREENWIDTH == %d' % W, x2v)) +print('/* yslope */'); print(out('SCREENHEIGHT == %d' % H, ys)) +print('/* distscale */'); print(out('SCREENWIDTH == %d' % W, ds)) +print('/* clipangle', x2v[0], '*/') diff --git a/doom/src/pdoom/tools/mkdoomrom.py b/doom/src/pdoom/tools/mkdoomrom.py new file mode 100644 index 0000000..84804a7 --- /dev/null +++ b/doom/src/pdoom/tools/mkdoomrom.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# Assemble the DOOM ROM: base ROM with stub (from mkrom1.js), program window part, WAD. +# mkdoomrom.py +import sys, struct +rom = bytearray(open(sys.argv[1], 'rb').read()) +xip = open(sys.argv[2], 'rb').read() +wad = open(sys.argv[3], 'rb').read() +CODE_OFF, SAVE_OFF = 0xB1000, 0x10E000 +WAD_OFF, REGION_OFF, REGION_END = 0x830000, 0xCA0000, 0xD48000 +assert len(rom) == 0x1000000 +assert CODE_OFF + len(xip) <= SAVE_OFF, 'program part too big' +assert WAD_OFF + 4 + len(wad) <= REGION_OFF, 'WAD too big: %d bytes, room %d' % (len(wad), REGION_OFF - WAD_OFF - 4) +rom[CODE_OFF:SAVE_OFF] = b'\xff' * (SAVE_OFF - CODE_OFF) +rom[CODE_OFF:CODE_OFF + len(xip)] = xip +rom[SAVE_OFF:0x110000] = b'\xff' * (0x110000 - SAVE_OFF) +rom[WAD_OFF:REGION_END] = b'\xff' * (REGION_END - WAD_OFF) +rom[WAD_OFF:WAD_OFF + 4] = struct.pack(' [musik] +import struct, sys, re +src, dst, eps = sys.argv[1], sys.argv[2], sys.argv[3] +MUSIK = len(sys.argv) > 4 and sys.argv[4] == 'musik' # v0.2.5: keep the episode music (D_ lumps, MUS) +d = open(src, 'rb').read() +ident, n, off = struct.unpack_from('<4sII', d, 0) +L = [] +for i in range(n): + o, s, nm = struct.unpack_from(' +*/ +#ifndef DOOMTYPES_H +#define DOOMTYPES_H +#include +#include + +typedef int32_t fixed_t; +typedef uint32_t angle_t; + + +#define FRACBITS 16 +#define FRACUNIT (1<> (8*sizeof _t-1); + return (_t^_s)-_s; +} + +inline static fixed_t FixedDiv(fixed_t a, fixed_t b) +{ + return ((unsigned)D_abs(a)>>14) >= (unsigned)D_abs(b) ? ((a^b)>>31) ^ INT_MAX : + (fixed_t)(((int64_t) a << FRACBITS) / b); +} + +//************************************************************************************* +//WAD file structs from Doom sources. +//************************************************************************************* + +#pragma pack(push,1) + +typedef struct +{ + char identification[4]; // Should be "IWAD" or "PWAD". + int32_t numlumps; + int32_t infotableofs; +} wadinfo_t; + +typedef struct +{ + int32_t filepos; + int32_t size; + char name[8]; +} filelump_t; + + + +// +// Map level types. +// The following data structures define the persistent format +// used in the lumps of the WAD files. +// + +// Lump order in a map WAD: each map needs a couple of lumps +// to provide a complete scene geometry description. +enum { + ML_LABEL, // A separator, name, ExMx or MAPxx + ML_THINGS, // Monsters, items.. + ML_LINEDEFS, // LineDefs, from editing + ML_SIDEDEFS, // SideDefs, from editing + ML_VERTEXES, // Vertices, edited and BSP splits generated + ML_SEGS, // LineSegs, from LineDefs split by BSP + ML_SSECTORS, // SubSectors, list of LineSegs + ML_NODES, // BSP nodes + ML_SECTORS, // Sectors, from editing + ML_REJECT, // LUT, sector-sector visibility + ML_BLOCKMAP // LUT, motion clipping, walls/grid element +}; + + + +//************************************************************************************* +//r_defs structs from Doom sources. +//************************************************************************************* + +typedef struct +{ + fixed_t x, y; +} vertex_t; + +// A single Vertex. +typedef struct +{ + short x,y; +} mapvertex_t; + + +#define NO_INDEX ((unsigned short)-1) + +#define ML_TWOSIDED 4 + + +typedef enum +{ + ST_HORIZONTAL, + ST_VERTICAL, + ST_POSITIVE, + ST_NEGATIVE +} slopetype_t; + +typedef enum +{ // cph: + RF_TOP_TILE = 1, // Upper texture needs tiling + RF_MID_TILE = 2, // Mid texture needs tiling + RF_BOT_TILE = 4, // Lower texture needs tiling + RF_IGNORE = 8, // Renderer can skip this line + RF_CLOSED =16, // Line blocks view +} r_flags; + + +/* Bounding box coordinate storage. */ +enum +{ + BOXTOP, + BOXBOTTOM, + BOXLEFT, + BOXRIGHT +}; /* bbox coordinates */ + + +typedef struct line_s +{ + vertex_t v1; + vertex_t v2; // Vertices, from v1 to v2. + uint32_t lineno; //line number. + fixed_t dx, dy; // Precalculated v2 - v1 for side checking. + + uint16_t sidenum[2]; // Visual appearance: SideDefs. + + fixed_t bbox[4]; //Line bounding box. + + uint16_t flags; // Animation related. + int16_t special; + int16_t tag; + uint16_t slopetype; // To aid move clipping. + +} line_t; + +typedef struct { + unsigned short v1; + unsigned short v2; + unsigned short flags; + short special; + short tag; + // proff 07/23/2006 - support more than 32768 sidedefs + // use the unsigned value and special case the -1 + // sidenum[1] will be -1 (NO_INDEX) if one sided + unsigned short sidenum[2]; +} maplinedef_t; + + +// LineSeg, generated by splitting LineDefs +// using partition lines selected by BSP builder. +typedef struct { + unsigned short v1; + unsigned short v2; + short angle; + unsigned short linedef; + short side; + short offset; +} mapseg_t; + + +// +// The LineSeg. +// +typedef struct +{ + vertex_t v1; + vertex_t v2; // Vertices, from v1 to v2. + + fixed_t offset; + angle_t angle; + + uint16_t sidenum; + uint16_t linenum; + + uint16_t frontsectornum; + uint16_t backsectornum; +} seg_t; + + + +// A SideDef, defining the visual appearance of a wall, +// by setting textures and offsets. +typedef struct +{ + short textureoffset; + short rowoffset; + char toptexture[8]; + char bottomtexture[8]; + char midtexture[8]; + short sector; // Front sector, towards viewer. +} mapsidedef_t; + +// A SideDef, defining the visual appearance of a wall, +// by setting textures and offsets. +typedef struct +{ + short textureoffset; + short rowoffset; + short toptexture; + short bottomtexture; + short midtexture; + short sector; // Front sector, towards viewer. +} sidedef_t; + +typedef struct +{ + short originx; + short originy; + short patch; + short stepdir; // unused in Doom but might be used in Phase 2 Boom + short colormap; // unused in Doom but might be used in Phase 2 Boom +} mappatch_t; + +typedef struct +{ + char name[8]; + char pad2[4]; // unused + short width; + short height; + char pad[4]; // unused in Doom but might be used in Boom Phase 2 + short patchcount; + mappatch_t patches[1]; +} maptexture_t; + +typedef struct +{ + union + { + struct + { + uint8_t offset0; + uint8_t offset1; + uint8_t offset2; + uint8_t length; + }; + uint32_t offset; + }; +} packed_offset_and_length_t; + +typedef struct +{ + short width; // bounding box size + short height; + short leftoffset; // pixels to the left of origin + short topoffset; // pixels below the origin + packed_offset_and_length_t columnofs[8]; // only [width] used + // the [0] is &columnofs[width] +} patch_t; + +// posts are runs of non masked source pixels +typedef struct +{ + uint8_t topdelta; // -1 is the last post in a column + uint8_t length; // length data bytes follows +} post_t; + +// column_t is a list of 0 or more post_t, (byte)-1 terminated +typedef post_t column_t; + +#pragma pack(pop) + +#endif // DOOMTYPES_H diff --git a/doom/src/umwandler/main.c b/doom/src/umwandler/main.c new file mode 100644 index 0000000..3187628 --- /dev/null +++ b/doom/src/umwandler/main.c @@ -0,0 +1,52 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#include +#include +#include "wadfile.h" +#include "wadprocessor.h" +#define VERSIONSTR "0.3" // fix for single patch textures. +int main(int argc, char *argv[]) +{ + wadfile_t wadfile; + wadfile_t gbawadfile; + printf("MCUDoomWadutil by Nicola Wrachien V%s.\r\nOriginal source by doomhack.\r\n", VERSIONSTR); + // process input + if (argc != 3) + { + printf("Usage: %s \r\n", argv[0]); + return 0; + } + if (!loadWad("gbadoom.wad", &gbawadfile)) + { + printf("Error, gbadoom.wad must reside on the same directory of this program.\r\n"); + return 1; + } + if (!loadWad(argv[1], &wadfile )) + { + printf("Cannot open %s\r\n", argv[1]); + return 1; + } + // we merge first because we need to process the additional gbawadfile patches. + mergeWadFile(&wadfile, &gbawadfile); + processWad(&wadfile, false, true); // do not remove sound, convert patches + // + if (saveWad(argv[2], &wadfile, 'I')) + { + printf("Saved %s.\r\n", argv[2]); + } + else + { + printf("Cannt save %s.\r\n", argv[2]); + } + return 0; +} diff --git a/doom/src/umwandler/wadfile.c b/doom/src/umwandler/wadfile.c new file mode 100644 index 0000000..31fc0e3 --- /dev/null +++ b/doom/src/umwandler/wadfile.c @@ -0,0 +1,218 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#include "wadfile.h" +#include "doomtypes.h" +#include + +#define WAD_ALIGN 4 + +bool loadWad(const char *fileName, wadfile_t *wadfile) +{ + bool res = true; + FILE * fp; + // open file + fp = fopen (fileName, "rb"); + if (fp == NULL) + return false; + // get size + fseek(fp, 0L, SEEK_END); + size_t sz = ftell(fp); + printf("file size %d\r\n",sz); + rewind(fp); + // read whole file in memory for convenience. + uint8_t *tmpBuffer; + tmpBuffer = malloc(sz); + // + + int read = 0; + while (read < sz) + { + read += fread(tmpBuffer + read , 1, sz, fp); + } + printf("read %d bytes \r\n", read); + fclose(fp); + // copy header + memcpy(&wadfile->header, tmpBuffer, sizeof (wadinfo_t)); + if (memcmp(&wadfile->header.identification[1], "WAD", 3) == 0) + { + if (wadfile->header.identification[0] == 'I') + printf("Found IWAD\r\n"); + else if (wadfile->header.identification[0] == 'P') + printf("Found PWAD\r\n"); + else + { + printf("Unknown header\r\n"); + res = false; + } + } + else + { + res = false; + printf("Unknown header %c%c%c%c", + wadfile->header.identification[0], + wadfile->header.identification[1], + wadfile->header.identification[2], + wadfile->header.identification[3]); + } + if (res) + { + // read table offset + // *lumps = malloc(sizeof (int32_t) * *lumpFound ); + // + // memcpy(*lumps, sizeof (int32_t) * *lumpFound , &tmpBuffer[header.infotableofs]); + // + filelump_t *fileLumpTable = (filelump_t *) &tmpBuffer[wadfile->header.infotableofs]; + wadfile->lumps = malloc(wadfile->header.numlumps * sizeof(lump_t)); + lump_t *lumpTable = wadfile->lumps; + for (int i = 0; i < wadfile->header.numlumps; i++) + { + size_t lumpSize = (fileLumpTable[i].size + (WAD_ALIGN - 1)) & ~(WAD_ALIGN - 1); // +// printf("Lump %d, size %d, name %s, orig size %d\r\n", i, lumpSize, fileLumpTable[i].name, fileLumpTable[i].size); + // copy data + lumpTable[i].lump.size = fileLumpTable[i].size; // we need to put the original size + memcpy(lumpTable[i].lump.name, fileLumpTable[i].name, sizeof(lumpTable[i].lump.name)); + lumpTable[i].data = malloc(lumpSize); + memset(lumpTable[i].data, 0, lumpSize); + memcpy(lumpTable[i].data, &tmpBuffer[fileLumpTable[i].filepos], lumpSize); + } + } + free(tmpBuffer); + return res; +} +bool saveWad(const char *fileName, wadfile_t *wadfile, char wadType) +{ + size_t size; + FILE * fp; + // open file + fp = fopen (fileName, "wb"); + if (fp == NULL) + return false; + wadfile->header.identification[0] = wadType; + wadfile->header.identification[1] = 'W'; + wadfile->header.identification[2] = 'A'; + wadfile->header.identification[3] = 'D'; + wadfile->header.infotableofs = sizeof(wadfile->header); + fwrite(&wadfile->header, 1, sizeof(wadfile->header),fp); + // + int ptr = wadfile->header.infotableofs + sizeof (filelump_t) * wadfile->header.numlumps; + for (int i = 0; i < wadfile->header.numlumps; i++) + { + size = (wadfile->lumps[i].lump.size + (WAD_ALIGN - 1)) & ~(WAD_ALIGN - 1); // size is multiple of 4 + filelump_t fl; + fl.filepos = ptr; + fl.size = wadfile->lumps[i].lump.size; // need to put original size + memcpy(fl.name, wadfile->lumps[i].lump.name, sizeof (wadfile->lumps[i].lump.name)); + fwrite(&fl, 1, sizeof (fl), fp); + ptr += size; // need to use aligned size + } + // now store a the lumps + for (int i = 0; i < wadfile->header.numlumps; i++) + { + size = (wadfile->lumps[i].lump.size + (WAD_ALIGN - 1)) & ~(WAD_ALIGN - 1); // size is multiple of 4 + /* v0.3.1: padding bytes always 0 (before: leftover memory) */ + static const uint8_t zero[4] = {0, 0, 0, 0}; + fwrite(wadfile->lumps[i].data, 1, wadfile->lumps[i].lump.size, fp); + fwrite(zero, 1, size - wadfile->lumps[i].lump.size, fp); + } + fclose(fp); + return true; +} +int getLumpNumByName(wadfile_t *wadfile, const char *name) +{ + for (int i = 0; i < wadfile->header.numlumps; i++) + { + if (0 == strncmp(wadfile->lumps[i].lump.name, name, sizeof(wadfile->lumps[i].lump.name))) + return i; + } + return -1; +} +lump_t * getLumpByNum(wadfile_t *wadfile, int lumpNum) +{ + if (lumpNum >= wadfile->header.numlumps) + { + printf("Error, cannot find lum %d, max %d", lumpNum, wadfile->header.numlumps); + return NULL; + } + else + return &wadfile->lumps[lumpNum]; +} +void replaceLump(wadfile_t *wadfile, lump_t *newLump, int index) +{ + if (index >= wadfile->header.numlumps) + { + //printf("Lump %d >= numLumps %d\r\n", index, wadfile->header.numlumps); + return; + } + // free old lump data, not needed anymore + free(wadfile->lumps[index].data); + memcpy(&wadfile->lumps[index], newLump, sizeof(lump_t)); + //printf("new lump %d size %d\r\n", index, newLump->lump.size); +} +void insertLump(wadfile_t *wadfile, lump_t *newLump, int index) +{ + // create new table + lump_t *newTable = malloc((wadfile->header.numlumps + 1) * sizeof(lump_t)); + lump_t *oldTable = wadfile->lumps; + // copy all lumps before index + int i = 0; + if (index > wadfile->header.numlumps) + index = wadfile->header.numlumps; + for (; i < index; i++) + { + memcpy(&newTable[i], &oldTable[i], sizeof(lump_t) ); + } + // insert + memcpy(&newTable[i], newLump, sizeof(lump_t)); + // copy remaining + for (; i < wadfile->header.numlumps; i++) + { + memcpy(&newTable[i + 1], &oldTable[i], sizeof(lump_t) ); + } + wadfile->lumps = newTable; + free(oldTable); + // update numlumps + wadfile->header.numlumps++; +} +void removeLump(wadfile_t * wadfile, int index) +{ + if (index >= wadfile->header.numlumps) + return; + // create new table + // create new table + lump_t *newTable = malloc((wadfile->header.numlumps - 1) * sizeof(lump_t)); + lump_t *oldTable = wadfile->lumps; + // copy all lumps before index + int i = 0; + for (; i < index; i++) + { + memcpy(&newTable[i], &oldTable[i], sizeof(lump_t) ); + } + // remove + free(oldTable[i].data); + // copy remaining + for (; i < wadfile->header.numlumps - 1; i++) + { + memcpy(&newTable[i], &oldTable[i + 1], sizeof(lump_t) ); + } + wadfile->lumps = newTable; + free(oldTable); + // update numlumps + wadfile->header.numlumps--; +} +void mergeWadFile(wadfile_t *wad1, wadfile_t *wad2) +{ + for (int i = 0; i < wad2->header.numlumps; i++) + { + insertLump(wad1, &wad2->lumps[i], 0xFFFF); + } +} diff --git a/doom/src/umwandler/wadfile.h b/doom/src/umwandler/wadfile.h new file mode 100644 index 0000000..5753256 --- /dev/null +++ b/doom/src/umwandler/wadfile.h @@ -0,0 +1,41 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#ifndef WADFILE_H +#define WADFILE_H +#include "doomtypes.h" +#include +#include +#include +#include + +typedef struct +{ + filelump_t lump; + void *data; +} lump_t; +typedef struct +{ + wadinfo_t header; + lump_t *lumps; +} wadfile_t; +//bool loadWad(const char *fileName, uint32_t *lumpFound, lump_t **lumps, wadinfo_t *header); +bool loadWad(const char *fileName, wadfile_t *wadfile); +bool saveWad(const char *fileName, wadfile_t *wadfile, char wadType); +void mergeWadFile(wadfile_t *wad1, wadfile_t *wad2); +void removeLump(wadfile_t * wadfile, int index); +void insertLump(wadfile_t *wadfile, lump_t *newLump, int index); +int getLumpNumByName(wadfile_t *wadfile, const char *name); +lump_t * getLumpByNum(wadfile_t *wadfile, int lumpNum); +void replaceLump(wadfile_t *wadfile, lump_t *newLump, int index); + +#endif // WADFILE_H diff --git a/doom/src/umwandler/wadprocessor.c b/doom/src/umwandler/wadprocessor.c new file mode 100644 index 0000000..7ad8f8f --- /dev/null +++ b/doom/src/umwandler/wadprocessor.c @@ -0,0 +1,948 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#include "wadprocessor.h" +#include "doomtypes.h" +#include "wadfile.h" +#include +#include +static void convertCompositeTextures(wadfile_t *wadfile); +static bool processD2Levels(wadfile_t *wadfile); +static bool processD1Levels(wadfile_t *wadfile); + +static bool processLevel(wadfile_t *wadfile, uint32_t lumpNum); + +static bool processVertexes(wadfile_t *wadfile, uint32_t lumpNum); +static bool processLines(wadfile_t *wadfile, uint32_t lumpNum); +static bool processSegs(wadfile_t *wadfile, uint32_t lumpNum); +static bool processSides(wadfile_t *wadfile, uint32_t lumpNum); +static bool processPatches(wadfile_t *wadfile, int firstLump, int lastLump); +static void removeUnusedPatches(wadfile_t *wadfile); +static bool processPNames(); +static bool removeUnusedLumps(wadfile_t *wadfile, bool removeSound); + +int getTextureNumForName(wadfile_t *wadfile, const char* tex_name); + +bool processWad(wadfile_t *wadfile, bool removeSound, bool convertPatches) +{ + removeUnusedLumps(wadfile, removeSound); + convertCompositeTextures(wadfile); + // + removeUnusedPatches(wadfile); + if (!convertPatches) + { + printf("WARNING, NOT CONVERTING PATCHES\r\n"); + } + else + { + // for each patch, change it. Note, marksers are skipped. + int firstLump = getLumpNumByName(wadfile, "HELP1"); + if (firstLump == -1) // for DOOM2 + firstLump = getLumpNumByName(wadfile, "HELP"); + int lastLump = getLumpNumByName(wadfile, "P_END"); + processPatches(wadfile, firstLump, lastLump); + // process gba specific patches, added at the end + firstLump = getLumpNumByName(wadfile, "M_ARUN"); + lastLump = getLumpNumByName(wadfile, "STGANUM9") + 1; + + processPatches(wadfile, firstLump, lastLump); + } + int lumpNum = getLumpNumByName(wadfile, "MAP01"); + //Figure out if our IWAD is Doom or Doom2. (E1M1 or MAP01) + if(lumpNum != -1) + { + printf("Doom 2 level found\r\n"); + return processD2Levels(wadfile); + } + else + { + int lumpNum = getLumpNumByName(wadfile, "E1M1"); + /* v0.3.1: a partial WAD with only one episode (e.g. E2) has no E1M1 */ + for (int e = 2; e <= 4 && lumpNum == -1; e++) + { + char nm[8] = { 'E', (char)('0' + e), 'M', '1', 0, 0, 0, 0 }; + lumpNum = getLumpNumByName(wadfile, nm); + } + + //Can't find any maps. + if(lumpNum == -1) + { + printf("No maps found\r\n"); + return false; + } + printf("Doom 1 level found\r\n"); + } + + return processD1Levels(wadfile); +} +bool processD2Levels(wadfile_t *wadfile) +{ + for(int m = 1; m <= 32; m++) + { + char mapName[9]; + snprintf(mapName, sizeof(mapName), "MAP%02d",m); + int lumpNum = getLumpNumByName(wadfile, mapName); + + if(lumpNum != -1) + { + processLevel(wadfile, lumpNum); + } + } + return true; +} + +bool processD1Levels(wadfile_t *wadfile) +{ + for(int e = 1; e <= 4; e++) + { + for(int m = 1; m <= 9; m++) + { + char mapName[9]; + snprintf(mapName, sizeof(mapName), "E%dM%d",e,m); + + int lumpNum = getLumpNumByName(wadfile, mapName); + + if(lumpNum != -1) + { + printf("processing %s\r\n", mapName); + processLevel(wadfile, lumpNum); + } + else + { + printf("cannot find %s\r\n", mapName); + + } + } + } + + return true; +} + +bool processLevel(wadfile_t *wadfile, uint32_t lumpNum) +{ + processVertexes(wadfile, lumpNum); + processLines(wadfile, lumpNum); + processSegs(wadfile, lumpNum); + processSides(wadfile, lumpNum); + processPNames(wadfile); + return true; +} + +bool processVertexes(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t vtxLumpNum = lumpNum + ML_VERTEXES; + + lump_t *vxl; + + vxl = getLumpByNum(wadfile, vtxLumpNum); + + if (NULL == vxl) + return false; + + if(vxl->lump.size == 0) + return false; + // get number of vertex + uint32_t vtxCount = vxl->lump.size / sizeof(mapvertex_t); + // allocate new vertex + vertex_t* newVtx = malloc( sizeof (vertex_t) * vtxCount); + // + mapvertex_t* oldVtx = (mapvertex_t*) vxl->data; + // precalculate vertex + for(uint32_t i = 0; i < vtxCount; i++) + { + newVtx[i].x = (oldVtx[i].x << 16); + newVtx[i].y = (oldVtx[i].y << 16); + } + // allocate new lump info + lump_t *newVxl = malloc(sizeof (lump_t)); + // copy name + memcpy(newVxl->lump.name, vxl->lump.name, sizeof (vxl->lump.name)); + // change data and size information + newVxl->data = newVtx; + newVxl->lump.size = vtxCount * sizeof(vertex_t); + // replace lum + replaceLump(wadfile, newVxl, vtxLumpNum); + + return true; +} + +bool processLines(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t lineLumpNum = lumpNum+ML_LINEDEFS; + + lump_t *lines; + + lines = getLumpByNum(wadfile, lineLumpNum); + + if (NULL == lines) + return false; + + if(lines->lump.size == 0) + return false; + + uint32_t lineCount = lines->lump.size / sizeof(maplinedef_t); + + line_t* newLines = malloc (sizeof(line_t) * lineCount); + + maplinedef_t* oldLines = (maplinedef_t*) lines->data; + + //We need vertexes for this... + + uint32_t vtxLumpNum = lumpNum+ML_VERTEXES; + + lump_t *vxl; + + vxl = getLumpByNum(wadfile, vtxLumpNum); + + if (NULL == vxl) + return false; + + if(vxl->lump.size == 0) + return false; + + vertex_t* vtx = (vertex_t*)vxl->data; + + for(unsigned int i = 0; i < lineCount; i++) + { + newLines[i].v1.x = vtx[oldLines[i].v1].x; + newLines[i].v1.y = vtx[oldLines[i].v1].y; + + newLines[i].v2.x = vtx[oldLines[i].v2].x; + newLines[i].v2.y = vtx[oldLines[i].v2].y; + + newLines[i].special = oldLines[i].special; + newLines[i].flags = oldLines[i].flags; + newLines[i].tag = oldLines[i].tag; + + newLines[i].dx = newLines[i].v2.x - newLines[i].v1.x; + newLines[i].dy = newLines[i].v2.y - newLines[i].v1.y; + + newLines[i].slopetype = + !newLines[i].dx ? ST_VERTICAL : !newLines[i].dy ? ST_HORIZONTAL : + FixedDiv(newLines[i].dy, newLines[i].dx) > 0 ? ST_POSITIVE : ST_NEGATIVE; + + newLines[i].sidenum[0] = oldLines[i].sidenum[0]; + newLines[i].sidenum[1] = oldLines[i].sidenum[1]; + + newLines[i].bbox[BOXLEFT] = (newLines[i].v1.x < newLines[i].v2.x ? newLines[i].v1.x : newLines[i].v2.x); + newLines[i].bbox[BOXRIGHT] = (newLines[i].v1.x < newLines[i].v2.x ? newLines[i].v2.x : newLines[i].v1.x); + + newLines[i].bbox[BOXTOP] = (newLines[i].v1.y < newLines[i].v2.y ? newLines[i].v2.y : newLines[i].v1.y); + newLines[i].bbox[BOXBOTTOM] = (newLines[i].v1.y < newLines[i].v2.y ? newLines[i].v1.y : newLines[i].v2.y); + + newLines[i].lineno = i; + + } + + + // allocate new lump info + lump_t *newLine = malloc(sizeof (lump_t)); + // copy name + memcpy(newLine->lump.name, lines->lump.name, sizeof (lines->lump.name)); + // change data and size information + newLine->data = newLines; + newLine->lump.size = lineCount * sizeof(line_t); + // replace lum + replaceLump(wadfile, newLine, lineLumpNum); + + return true; +} + +bool processSegs(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t segsLumpNum = lumpNum+ML_SEGS; + + lump_t *segs; + + segs = getLumpByNum(wadfile, segsLumpNum); + + if (NULL == segs) + return false; + + if(segs->lump.size == 0) + return false; + + uint32_t segCount = segs->lump.size / sizeof(mapseg_t); + + seg_t* newSegs = malloc(sizeof(seg_t) * segCount); + + mapseg_t* oldSegs = (mapseg_t*) segs->data; + + //We need vertexes for this... + + uint32_t vtxLumpNum = lumpNum+ML_VERTEXES; + + lump_t *vxl; + + vxl = getLumpByNum(wadfile, vtxLumpNum); + + if (NULL == vxl) + return false; + + if(vxl->lump.size == 0) + return false; + + vertex_t* vtx = (vertex_t*)vxl->data; + + //And LineDefs. Must process lines first. + + uint32_t linesLumpNum = lumpNum+ML_LINEDEFS; + + lump_t * lxl; + + lxl = getLumpByNum(wadfile, linesLumpNum); + + if (NULL == lxl) + return false; + + if(lxl->lump.size == 0) + return false; + + + line_t* lines = (line_t *) lxl->data; + + //And sides too... + + uint32_t sidesLumpNum = lumpNum+ML_SIDEDEFS; + + lump_t * sxl; + + sxl = getLumpByNum(wadfile, sidesLumpNum); + + if (NULL == sxl) + return false; + + if(sxl->lump.size == 0) + return false; + + mapsidedef_t* sides = (mapsidedef_t*) sxl->data; + + + //**************************** + + for(unsigned int i = 0; i < segCount; i++) + { + newSegs[i].v1.x = vtx[oldSegs[i].v1].x; + newSegs[i].v1.y = vtx[oldSegs[i].v1].y; + + newSegs[i].v2.x = vtx[oldSegs[i].v2].x; + newSegs[i].v2.y = vtx[oldSegs[i].v2].y; + + newSegs[i].angle = oldSegs[i].angle << 16; + newSegs[i].offset = oldSegs[i].offset << 16; + + newSegs[i].linenum = oldSegs[i].linedef; + + const line_t* ldef = &lines[newSegs[i].linenum]; + + int side = oldSegs[i].side; + + newSegs[i].sidenum = ldef->sidenum[side]; + + if(newSegs[i].sidenum != NO_INDEX) + { + newSegs[i].frontsectornum = sides[newSegs[i].sidenum].sector; + } + else + { + newSegs[i].frontsectornum = NO_INDEX; + } + + newSegs[i].backsectornum = NO_INDEX; + + if(ldef->flags & ML_TWOSIDED) + { + if(ldef->sidenum[side^1] != NO_INDEX) + { + newSegs[i].backsectornum = sides[ldef->sidenum[side^1]].sector; + } + } + } + + + // allocate new lump info + lump_t *newSeg = malloc(sizeof (lump_t)); + // copy name + memcpy(newSeg->lump.name, segs->lump.name, sizeof (segs->lump.name)); + // change data and size information + newSeg->data = newSegs; + newSeg->lump.size = segCount * sizeof(seg_t); + // replace lum + replaceLump(wadfile, newSeg, segsLumpNum); + + return true; +} + +bool processSides(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t sidesLumpNum = lumpNum+ML_SIDEDEFS; + + lump_t *sides; + + sides = getLumpByNum(wadfile, sidesLumpNum); + + if (NULL == sides) + return false; + + if(sides->lump.size == 0) + return false; + + uint32_t sideCount = sides->lump.size / sizeof(mapsidedef_t); + + sidedef_t* newSides = malloc(sizeof(sidedef_t) * sideCount); + + mapsidedef_t* oldSides = (mapsidedef_t*) sides->data; + + for(unsigned int i = 0; i < sideCount; i++) + { + newSides[i].textureoffset = oldSides[i].textureoffset; + newSides[i].rowoffset = oldSides[i].rowoffset; + + newSides[i].toptexture = getTextureNumForName(wadfile, oldSides[i].toptexture); + newSides[i].bottomtexture = getTextureNumForName(wadfile, oldSides[i].bottomtexture); + newSides[i].midtexture = getTextureNumForName(wadfile, oldSides[i].midtexture); + + newSides[i].sector = oldSides[i].sector; + } + + // allocate new lump info + lump_t *newSide = malloc(sizeof (lump_t)); + // copy name + memcpy(newSide->lump.name, sides->lump.name, sizeof (sides->lump.name)); + // change data and size information + newSide->data = newSides; + newSide->lump.size = sideCount * sizeof(sidedef_t); + // replace lum + replaceLump(wadfile, newSide, sidesLumpNum); + + return true; +} + +int getTextureNumForName(wadfile_t *wadfile, const char* tex_name) +{ + + const int *maptex1, *maptex2; + int numtextures1, numtextures2 = 0; + const int *directory1, *directory2; + + + //Convert name to uppercase for comparison. + char tex_name_upper[9]; + + strncpy(tex_name_upper, tex_name, 8); + tex_name_upper[8] = 0; //Ensure null terminated. + + for (int i = 0; i < 8; i++) + { + tex_name_upper[i] = toupper(tex_name_upper[i]); + } + + lump_t * tex1lump; + int tex1LumpNum = getLumpNumByName(wadfile, "TEXTURE1"); + tex1lump = getLumpByNum(wadfile, tex1LumpNum); + + maptex1 = (const int*)tex1lump->data; + numtextures1 = *maptex1; + directory1 = maptex1+1; + + lump_t * tex2lump; + int tex2LumpNum = getLumpNumByName(wadfile, "TEXTURE2"); + + if (tex2LumpNum != -1) + { + tex2lump = getLumpByNum(wadfile, tex2LumpNum); + + maptex2 = (const int*)tex2lump->data; + directory2 = maptex2+1; + numtextures2 = *maptex2; + } + else + { + maptex2 = NULL; + directory2 = NULL; + } + + const int *directory = directory1; + const int *maptex = maptex1; + + int numtextures = (numtextures1 + numtextures2); + + for (int i=0 ; iname, 8)) + { + return i; + } + } + + return 0; +} +static uint16_t getColumnLength(column_t* column) +{ + uint8_t *columnData = (uint8_t *) column; + uint16_t n = 1; + while (column->topdelta != 0xff) + { + // get length + unsigned int length = column->length; + n++; + n += length + 3; + // get next top delta. + column = (column_t*) &columnData[n - 1]; + } + return n; +} +static bool processPatches(wadfile_t *wadfile, int firstLump, int lastLump) +{ + printf("First %d, last %d\r\n", firstLump, lastLump); + for(uint32_t patchLumpNum = firstLump; patchLumpNum < lastLump; patchLumpNum++) + { + // get next patch lump + lump_t * patchLump = getLumpByNum(wadfile, patchLumpNum); + if (0 == patchLump->lump.size) // sprites and texture patches share the same format. However they are separted by 0-length markers + continue; + // allocate new lump info + lump_t *newPatchLump = malloc(sizeof (lump_t)); + // create an empty patch whose size is the same as the old patch + patch_t *newPatch = (patch_t *) malloc (patchLump->lump.size); + // make an exact copy of the old ump + memcpy (newPatch, patchLump->data, patchLump->lump.size); + // + for (int c = 0; c < newPatch->width; c++) + { + // set the length on the upper part of the old columnOfs word. + int l = (getColumnLength(((uint8_t*)newPatch + newPatch->columnofs[c].offset)) + 3) & ~3; + if (l > 255) + printf("WARNING!!! FOUND A LENGTH > 255. (%d) on lump %d\r\n", l, patchLumpNum); + newPatch->columnofs[c].length = l; + } + // copy name + memcpy(newPatchLump->lump.name, patchLump->lump.name, sizeof (patchLump->lump.name)); + // change data and size informationColumn length + newPatchLump->data = newPatch; + newPatchLump->lump.size = patchLump->lump.size; + // replace lump + replaceLump(wadfile, newPatchLump, patchLumpNum); + + + + } + return true; + + +} + +bool processPNames(wadfile_t *wadfile) +{ + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return false; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnamesData = (char*)pnamesLump->data; + + uint32_t count = *((uint32_t*)pnamesData); + + pnamesData += 4; //Fist 4 bytes are count. + // uppercase everything + for(uint32_t i = 0; i < count; i++) + { + bool nullChar = false; + for (int j = 0; j < 8; j++) + { + uint8_t c; + if (nullChar) + c = 0; + else + c = toupper(pnamesData[i*8 + j]); + pnamesData[i*8 + j] = c; + if (0 == c) + { + nullChar = true; + } + + } + } + return true; +} +static volatile bool startsWith(char *string, char *prefix) +{ + return strncmp(string, prefix, strlen(prefix)) == 0; +} +bool removeUnusedLumps(wadfile_t *wadfile, bool removeSound) +{ + for(uint32_t i = 0; i < wadfile->header.numlumps; i++) + { + lump_t *l; + + l = getLumpByNum(wadfile, i); + char *name = l->lump.name; + if ( +#ifndef KEEP_MUS + startsWith(name, "D_") || +#endif + 0 || +#ifndef KEEP_DP + startsWith(name, "DP") || +#endif + (startsWith(name, "DS") && removeSound && !startsWith(name, "DSPISTOL"))|| + startsWith(name, "GENMIDI")) + { + //printf("removing lump %s\r\n", l->lump.name); + removeLump(wadfile, i); + i--; + } + } + return true; +} + +static inline void R_DrawColumnInCache(const column_t *patch, uint8_t *cache, int originy, int cacheheight) +{ + while (patch->topdelta != 0xff) + { + const uint8_t *source = (const uint8_t*) patch + 3; + int count = patch->length; + int position = originy + patch->topdelta; + + if (position < 0) + { + count += position; + position = 0; + } + + if (position + count > cacheheight) + count = cacheheight - position; + + if (count > 0) + memcpy(cache + position, source, count); + + patch = (const column_t*) ((const uint8_t*) patch + patch->length + 4); + } +} + + + +const uint8_t* R_ComposeColumn(wadfile_t *wadfile, const maptexture_t *tex, int xc, uint8_t* columnCacheBuffer) +{ + unsigned int i = 0; + unsigned int patchcount = tex->patchcount; + do + { + // note: all texetures and patch addresses are cached in flash. + const mappatch_t *patch = &tex->patches[i]; + + // get pnames + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + { + printf("Error, cannot find pnames\r\n"); + return NULL; + } + + lump_t *pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnames = (char*)pnamesLump->data + 4; + + int patchLumpNum = getLumpNumByName(wadfile, &pnames[patch->patch * 8]); + + if (patchLumpNum == -1) + { + printf("Error, cannot find patch lump\r\n"); + return NULL; + } + lump_t *patchLump = getLumpByNum(wadfile, patchLumpNum); + + const patch_t *realpatch = patchLump->data; + + const int x1 = patch->originx; + + if (xc < x1) + continue; + short width; + width = realpatch->width; + const int x2 = x1 + width; + + if (xc < x2) + { + const column_t *patchcol; + patchcol = (const column_t*) ((const uint8_t*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1].offset)); + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch->originy, tex->height); + } + } while (++i < patchcount); + return columnCacheBuffer; +} +void convertRectangularBitmapToPatch(lump_t * lump, uint8_t *textureBuffer, int width, int height) +{ + // patch header: 8 + columnofs[width] + int size = 8 + 4 * width; + // add topdelta, length, pad, data[heigth], pad, topdelta + size += (1 + 1 + 1 + height + 1 + 1) * width; + // + patch_t *patchData = malloc(size); + // already set lump size and data ptr + lump->lump.size = size; + lump->data = patchData; + // set up size etc + patchData->leftoffset = 0; + patchData->topoffset = 0; + patchData->width = width; + patchData->height = height; + // set column offsets and copy data + for (int i = 0; i < width; i++) + { + patchData->columnofs[i].offset = 8 + 4 * width + (1 + 1 + 1 + height + 1 + 1) * i; + uint8_t *data = (uint8_t*)patchData + patchData->columnofs[i].offset; + *data++ = 0; // top delta + *data++ = height; // post length + *data++ = 0; // pad + memcpy(data, &textureBuffer[i * height], height); + data += height; + *data++ = 0; // pad + *data++ = 0xFF; // last top delta + } +} +int addPatchToPnames(wadfile_t *wadfile, char *name) +{ + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return 0; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + uint8_t *newPnamesData = malloc(pnamesLump->lump.size + 8); + + memcpy (newPnamesData, pnamesLump->data, pnamesLump->lump.size); + + uint32_t count = *((uint32_t*)pnamesLump->data); + + // increase count + *((uint32_t*)newPnamesData) = count + 1; + + // copy new name + memcpy (newPnamesData + 4 + count * 8, name, 8); + + // allocate new lump info + lump_t *newPnames = malloc(sizeof (lump_t)); + // copy name + memcpy(newPnames->lump.name, pnamesLump->lump.name, sizeof (pnamesLump->lump.name)); + // change data and size information + newPnames->data = newPnamesData; + // increase size by 8, i.e. new name + newPnames->lump.size = pnamesLump->lump.size + 8; + // replace lum + replaceLump(wadfile, newPnames, lumpNum); + return count; +} + +static void convertCompositeTextures(wadfile_t *wadfile) +{ + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnamesData = (char*)pnamesLump->data; + + uint32_t count = *((uint32_t*)pnamesData); + + pnamesData += 4; //Fist 4 bytes are count. + + const int *maptex1, *maptex2; + int numtextures1, numtextures2; + const int *directory1, *directory2; + // get texture lump + lumpNum = getLumpNumByName(wadfile, "TEXTURE1"); + // load it + maptex1 = getLumpByNum(wadfile, lumpNum)->data; + // + numtextures1 = *maptex1; + + directory1 = maptex1 + 1; + + + if ( (lumpNum = getLumpNumByName(wadfile, "TEXTURE2")) != -1) + { + maptex2 = getLumpByNum(wadfile, lumpNum)->data; + numtextures2 = *maptex2; + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + numtextures2 = 0; + directory2 = NULL; + } + + int offset = 0; + + // now scan all the textures + uint32_t size = 0; + for (int texture_num = 0; texture_num < numtextures2 + numtextures1; texture_num++) + { + const int *maptex = maptex1; + if (texture_num < numtextures1) + { + offset = directory1[texture_num]; + } + else if (maptex2 && ((texture_num - numtextures1) < numtextures2)) + { + maptex = maptex2; + offset = directory2[texture_num-numtextures1]; + } + maptexture_t *mtexture = (maptexture_t*) ((const uint8_t*) maptex + offset); + + // 2022-04-19: removed check with patch < 2, as textures with 1 patches need to be addressed as well, as they might have different offsets. + // 2022-04-24: this screwed up masked textures. Modified so that we only change textures with 2 patches or single patch with 0 offset + // FIXME: this is not perfect solution anyway, as we might have some masked textures with offset. TO be checked. + if (mtexture->patchcount < 2 && mtexture->patches[0].originx == 0 && mtexture->patches[0].originy == 0) + continue; // we are interested only in composite textures. + uint8_t columnData[256]; // this should be enough. + size += mtexture->height * mtexture->width; + if (mtexture->height & 3) + printf("Warning, texture %d has height %d\r\n", texture_num, mtexture->height); + // allocate buffer for texture. Nofte that this has x-y swapped + uint8_t *textureBuffer = malloc(mtexture->height * mtexture->width); + memset(textureBuffer, 0, mtexture->height * mtexture->width); /* v0.3.1: otherwise gaps are random (leftover memory) */ + for (int x = 0; x < mtexture->width; x++) + { + R_ComposeColumn(wadfile,mtexture, x, &textureBuffer[mtexture->height * x]); + } + lump_t newPatchLump; + convertRectangularBitmapToPatch(&newPatchLump ,textureBuffer, mtexture->width, mtexture->height); + int endPatchLumpNum = getLumpNumByName(wadfile, "P_END") - 1; + char newName[9]; + snprintf(newName,9, "SPTE%04X", texture_num); // Note X must be UPPERCASE! + memcpy(newPatchLump.lump.name, newName, 8); + printf("New patch added: %d SPTE%04X\r\n", texture_num, texture_num); + insertLump(wadfile, &newPatchLump, endPatchLumpNum); + // add entry to pname + int newPatchNum = addPatchToPnames(wadfile, newPatchLump.lump.name); + + // now change texture data. Since offsets are used, we do not need to worry about resizing. + mtexture->patchcount = 1; + mtexture->patches[0].originx = 0; + mtexture->patches[0].originy = 0; + mtexture->patches[0].patch = newPatchNum; + // free textureBuffer + free(textureBuffer); + // + } + printf("Converting composite will increas size by %d bytes\r\n", size); +} +static void removeUnusedPatches(wadfile_t *wadfile) +{ + // scan for all patches in pnames. For each patch, see if it is listed in any texture + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnamesData = (char*)pnamesLump->data; + + uint32_t count = *((uint32_t*)pnamesData); + + pnamesData += 4; //Fist 4 bytes are count. + // + // Load texture lumps + // + const int *maptex1, *maptex2; + int numtextures1, numtextures2; + const int *directory1, *directory2; + // get texture lump + lumpNum = getLumpNumByName(wadfile, "TEXTURE1"); + // load it + maptex1 = getLumpByNum(wadfile, lumpNum)->data; + // + numtextures1 = *maptex1; + + directory1 = maptex1 + 1; + + if ( (lumpNum = getLumpNumByName(wadfile, "TEXTURE2")) != -1) + { + maptex2 = getLumpByNum(wadfile, lumpNum)->data; + numtextures2 = *maptex2; + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + numtextures2 = 0; + directory2 = NULL; + } + + int offset = 0; + + uint32_t patchRemoved = 0; + uint32_t sizeSaved = 0; + // get texture data + for (int i = 0; i < count; i++) + { + + bool patchUsed = false; + for (int texture_num = 0; texture_num < numtextures2 + numtextures1; texture_num++) + { + const int *maptex = maptex1; + if (texture_num < numtextures1) + { + offset = directory1[texture_num]; + } + else if (maptex2 && ((texture_num - numtextures1) < numtextures2)) + { + maptex = maptex2; + offset = directory2[texture_num-numtextures1]; + } + maptexture_t *mtexture = (maptexture_t*) ((const uint8_t*) maptex + offset); + if (mtexture->patches[0].patch == i) + { + patchUsed = true; + break; + } + } + if (false == patchUsed) + { + int patchLumpNum = getLumpNumByName(wadfile, pnamesData); + if (-1 != patchLumpNum) + { + lump_t * lump = getLumpByNum(wadfile, patchLumpNum); + sizeSaved += lump->lump.size; + removeLump(wadfile, patchLumpNum); + patchRemoved++; + } + } + // point to next name + pnamesData += 8; + } + printf("Removed %d patches. Saved %d bytes\r\n", patchRemoved, sizeSaved); +} diff --git a/doom/src/umwandler/wadprocessor.h b/doom/src/umwandler/wadprocessor.h new file mode 100644 index 0000000..743fa17 --- /dev/null +++ b/doom/src/umwandler/wadprocessor.h @@ -0,0 +1,19 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#ifndef WADPROCESSOR_H +#define WADPROCESSOR_H + +#include "wadfile.h" +bool processWad(wadfile_t *wadfile, bool removeSound, bool convertPatches); + +#endif // WADPROCESSOR_H diff --git a/doom/src/wasm/conv.c b/doom/src/wasm/conv.c new file mode 100644 index 0000000..94a5c01 --- /dev/null +++ b/doom/src/wasm/conv.c @@ -0,0 +1,18 @@ +/* Entry point for the browser: like main.c of MCUDoomWadUtil, but in memory */ +#include "wadfile.h" +#include "wadprocessor.h" +extern void heap_reset(void); +static size_t g_out_len; +__attribute__((export_name("out_len"))) size_t out_len(void){ return g_out_len; } +__attribute__((export_name("alloc"))) void *alloc(size_t n){ return malloc(n); } +__attribute__((export_name("reset"))) void reset(void){ heap_reset(); } +__attribute__((export_name("convert"))) uint8_t *convert(const uint8_t *wad, size_t wadLen, const uint8_t *gba, size_t gbaLen) +{ + wadfile_t wadfile, gbawadfile; + g_out_len = 0; + if (!loadWadMem(gba, gbaLen, &gbawadfile)) return 0; + if (!loadWadMem(wad, wadLen, &wadfile)) return 0; + mergeWadFile(&wadfile, &gbawadfile); + if (!processWad(&wadfile, false, true)) return 0; + return saveWadMem(&wadfile, 'I', &g_out_len); +} diff --git a/doom/src/wasm/doomtypes.h b/doom/src/wasm/doomtypes.h new file mode 100644 index 0000000..61f4715 --- /dev/null +++ b/doom/src/wasm/doomtypes.h @@ -0,0 +1,277 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#ifndef DOOMTYPES_H +#define DOOMTYPES_H +#include +#include + +typedef int32_t fixed_t; +typedef uint32_t angle_t; + + +#define FRACBITS 16 +#define FRACUNIT (1<> (8*sizeof _t-1); + return (_t^_s)-_s; +} + +inline static fixed_t FixedDiv(fixed_t a, fixed_t b) +{ + return ((unsigned)D_abs(a)>>14) >= (unsigned)D_abs(b) ? ((a^b)>>31) ^ INT_MAX : + (fixed_t)(((int64_t) a << FRACBITS) / b); +} + +//************************************************************************************* +//WAD file structs from Doom sources. +//************************************************************************************* + +#pragma pack(push,1) + +typedef struct +{ + char identification[4]; // Should be "IWAD" or "PWAD". + int32_t numlumps; + int32_t infotableofs; +} wadinfo_t; + +typedef struct +{ + int32_t filepos; + int32_t size; + char name[8]; +} filelump_t; + + + +// +// Map level types. +// The following data structures define the persistent format +// used in the lumps of the WAD files. +// + +// Lump order in a map WAD: each map needs a couple of lumps +// to provide a complete scene geometry description. +enum { + ML_LABEL, // A separator, name, ExMx or MAPxx + ML_THINGS, // Monsters, items.. + ML_LINEDEFS, // LineDefs, from editing + ML_SIDEDEFS, // SideDefs, from editing + ML_VERTEXES, // Vertices, edited and BSP splits generated + ML_SEGS, // LineSegs, from LineDefs split by BSP + ML_SSECTORS, // SubSectors, list of LineSegs + ML_NODES, // BSP nodes + ML_SECTORS, // Sectors, from editing + ML_REJECT, // LUT, sector-sector visibility + ML_BLOCKMAP // LUT, motion clipping, walls/grid element +}; + + + +//************************************************************************************* +//r_defs structs from Doom sources. +//************************************************************************************* + +typedef struct +{ + fixed_t x, y; +} vertex_t; + +// A single Vertex. +typedef struct +{ + short x,y; +} mapvertex_t; + + +#define NO_INDEX ((unsigned short)-1) + +#define ML_TWOSIDED 4 + + +typedef enum +{ + ST_HORIZONTAL, + ST_VERTICAL, + ST_POSITIVE, + ST_NEGATIVE +} slopetype_t; + +typedef enum +{ // cph: + RF_TOP_TILE = 1, // Upper texture needs tiling + RF_MID_TILE = 2, // Mid texture needs tiling + RF_BOT_TILE = 4, // Lower texture needs tiling + RF_IGNORE = 8, // Renderer can skip this line + RF_CLOSED =16, // Line blocks view +} r_flags; + + +/* Bounding box coordinate storage. */ +enum +{ + BOXTOP, + BOXBOTTOM, + BOXLEFT, + BOXRIGHT +}; /* bbox coordinates */ + + +typedef struct line_s +{ + vertex_t v1; + vertex_t v2; // Vertices, from v1 to v2. + uint32_t lineno; //line number. + fixed_t dx, dy; // Precalculated v2 - v1 for side checking. + + uint16_t sidenum[2]; // Visual appearance: SideDefs. + + fixed_t bbox[4]; //Line bounding box. + + uint16_t flags; // Animation related. + int16_t special; + int16_t tag; + uint16_t slopetype; // To aid move clipping. + +} line_t; + +typedef struct { + unsigned short v1; + unsigned short v2; + unsigned short flags; + short special; + short tag; + // proff 07/23/2006 - support more than 32768 sidedefs + // use the unsigned value and special case the -1 + // sidenum[1] will be -1 (NO_INDEX) if one sided + unsigned short sidenum[2]; +} maplinedef_t; + + +// LineSeg, generated by splitting LineDefs +// using partition lines selected by BSP builder. +typedef struct { + unsigned short v1; + unsigned short v2; + short angle; + unsigned short linedef; + short side; + short offset; +} mapseg_t; + + +// +// The LineSeg. +// +typedef struct +{ + vertex_t v1; + vertex_t v2; // Vertices, from v1 to v2. + + fixed_t offset; + angle_t angle; + + uint16_t sidenum; + uint16_t linenum; + + uint16_t frontsectornum; + uint16_t backsectornum; +} seg_t; + + + +// A SideDef, defining the visual appearance of a wall, +// by setting textures and offsets. +typedef struct +{ + short textureoffset; + short rowoffset; + char toptexture[8]; + char bottomtexture[8]; + char midtexture[8]; + short sector; // Front sector, towards viewer. +} mapsidedef_t; + +// A SideDef, defining the visual appearance of a wall, +// by setting textures and offsets. +typedef struct +{ + short textureoffset; + short rowoffset; + short toptexture; + short bottomtexture; + short midtexture; + short sector; // Front sector, towards viewer. +} sidedef_t; + +typedef struct +{ + short originx; + short originy; + short patch; + short stepdir; // unused in Doom but might be used in Phase 2 Boom + short colormap; // unused in Doom but might be used in Phase 2 Boom +} mappatch_t; + +typedef struct +{ + char name[8]; + char pad2[4]; // unused + short width; + short height; + char pad[4]; // unused in Doom but might be used in Boom Phase 2 + short patchcount; + mappatch_t patches[1]; +} maptexture_t; + +typedef struct +{ + union + { + struct + { + uint8_t offset0; + uint8_t offset1; + uint8_t offset2; + uint8_t length; + }; + uint32_t offset; + }; +} packed_offset_and_length_t; + +typedef struct +{ + short width; // bounding box size + short height; + short leftoffset; // pixels to the left of origin + short topoffset; // pixels below the origin + packed_offset_and_length_t columnofs[8]; // only [width] used + // the [0] is &columnofs[width] +} patch_t; + +// posts are runs of non masked source pixels +typedef struct +{ + uint8_t topdelta; // -1 is the last post in a column + uint8_t length; // length data bytes follows +} post_t; + +// column_t is a list of 0 or more post_t, (byte)-1 terminated +typedef post_t column_t; + +#pragma pack(pop) + +#endif // DOOMTYPES_H diff --git a/doom/src/wasm/inc/ctype.h b/doom/src/wasm/inc/ctype.h new file mode 100644 index 0000000..e7aec21 --- /dev/null +++ b/doom/src/wasm/inc/ctype.h @@ -0,0 +1,2 @@ +#pragma once +static inline int toupper(int c){ return (c>='a'&&c<='z') ? c-32 : c; } diff --git a/doom/src/wasm/inc/stdio.h b/doom/src/wasm/inc/stdio.h new file mode 100644 index 0000000..cde697a --- /dev/null +++ b/doom/src/wasm/inc/stdio.h @@ -0,0 +1,5 @@ +#pragma once +#include +typedef struct FILE FILE; +int printf(const char *f, ...); +int snprintf(char *b, size_t n, const char *f, ...); diff --git a/doom/src/wasm/inc/stdlib.h b/doom/src/wasm/inc/stdlib.h new file mode 100644 index 0000000..d7c4381 --- /dev/null +++ b/doom/src/wasm/inc/stdlib.h @@ -0,0 +1,3 @@ +#pragma once +#include +void *malloc(size_t n); void free(void *p); diff --git a/doom/src/wasm/inc/string.h b/doom/src/wasm/inc/string.h new file mode 100644 index 0000000..d08bda0 --- /dev/null +++ b/doom/src/wasm/inc/string.h @@ -0,0 +1,5 @@ +#pragma once +#include +void *memcpy(void *d, const void *s, size_t n); void *memset(void *d, int c, size_t n); void *memmove(void *d, const void *s, size_t n); +int memcmp(const void *a, const void *b, size_t n); int strncmp(const char *a, const char *b, size_t n); size_t strlen(const char *s); +char *strncpy(char *d, const char *s, size_t n); diff --git a/doom/src/wasm/libc.c b/doom/src/wasm/libc.c new file mode 100644 index 0000000..95f0ccd --- /dev/null +++ b/doom/src/wasm/libc.c @@ -0,0 +1,42 @@ +/* Minimal C library for the WAD converter in the browser (WebAssembly) */ +#include +#include +extern unsigned char __heap_base; +static unsigned long heap_top; +void *malloc(size_t n){ + if(!heap_top) heap_top=(unsigned long)&__heap_base; + heap_top=(heap_top+7)&~7ul; + unsigned long p=heap_top; heap_top+=n; + unsigned long need=(heap_top+65535)>>16, have=__builtin_wasm_memory_size(0); + if(need>have && __builtin_wasm_memory_grow(0, need-have)==(size_t)-1) return 0; + return (void*)p; +} +void free(void *p){ (void)p; } +void heap_reset(void){ heap_top=0; } +void *memcpy(void *d, const void *s, size_t n){ unsigned char *a=d; const unsigned char *b=s; while(n--) *a++=*b++; return d; } +void *memmove(void *d, const void *s, size_t n){ unsigned char *a=d; const unsigned char *b=s; if(a='0'&&*f<='9') w=w*10+(*f++-'0'); + char t=*f++; unsigned v; int neg=0; char tmp[16]; int k=0; unsigned base=10; + if(t=='d'){ int x=va_arg(ap,int); if(x<0){neg=1; v=(unsigned)-x;} else v=(unsigned)x; } + else if(t=='X'||t=='x'){ v=va_arg(ap,unsigned); base=16; } + else if(t=='s'){ const char *s=va_arg(ap,const char*); while(*s) PUT(*s++); continue; } + else { PUT(t); continue; } + do{ unsigned dgt=v%base; tmp[k++]= dgt<10 ? '0'+dgt : (t=='X' ? 'A' : 'a')+dgt-10; v/=base; } while(v); + if(neg) PUT('-'); + for(int p=k; p +*/ +#include "wadfile.h" +#include "doomtypes.h" +#include + +#define WAD_ALIGN 4 + +/* Browser: read the WAD from memory and write it to memory (instead of files) */ +bool loadWadMem(const uint8_t *tmpBuffer, size_t sz, wadfile_t *wadfile) +{ + bool res = true; + memcpy(&wadfile->header, tmpBuffer, sizeof (wadinfo_t)); + if (memcmp(&wadfile->header.identification[1], "WAD", 3) != 0 || (wadfile->header.identification[0] != 'I' && wadfile->header.identification[0] != 'P')) + return false; + filelump_t *fileLumpTable = (filelump_t *) &tmpBuffer[wadfile->header.infotableofs]; + wadfile->lumps = malloc(wadfile->header.numlumps * sizeof(lump_t)); + lump_t *lumpTable = wadfile->lumps; + for (int i = 0; i < wadfile->header.numlumps; i++) + { + size_t lumpSize = (fileLumpTable[i].size + (WAD_ALIGN - 1)) & ~(WAD_ALIGN - 1); + lumpTable[i].lump.size = fileLumpTable[i].size; + memcpy(lumpTable[i].lump.name, fileLumpTable[i].name, sizeof(lumpTable[i].lump.name)); + lumpTable[i].data = malloc(lumpSize); + memset(lumpTable[i].data, 0, lumpSize); + size_t avail = fileLumpTable[i].filepos < sz ? sz - fileLumpTable[i].filepos : 0; + memcpy(lumpTable[i].data, &tmpBuffer[fileLumpTable[i].filepos], lumpSize < avail ? lumpSize : avail); + } + return res; +} +uint8_t *saveWadMem(wadfile_t *wadfile, char wadType, size_t *outLen) +{ + size_t total = sizeof(wadfile->header) + sizeof(filelump_t) * wadfile->header.numlumps; + for (int i = 0; i < wadfile->header.numlumps; i++) total += (wadfile->lumps[i].lump.size + (WAD_ALIGN - 1)) & ~(WAD_ALIGN - 1); + uint8_t *out = malloc(total), *p = out; + wadfile->header.identification[0] = wadType; + wadfile->header.identification[1] = 'W'; + wadfile->header.identification[2] = 'A'; + wadfile->header.identification[3] = 'D'; + wadfile->header.infotableofs = sizeof(wadfile->header); + memcpy(p, &wadfile->header, sizeof(wadfile->header)); p += sizeof(wadfile->header); + int ptr = wadfile->header.infotableofs + sizeof (filelump_t) * wadfile->header.numlumps; + for (int i = 0; i < wadfile->header.numlumps; i++) + { + size_t size = (wadfile->lumps[i].lump.size + (WAD_ALIGN - 1)) & ~(WAD_ALIGN - 1); + filelump_t fl; + fl.filepos = ptr; + fl.size = wadfile->lumps[i].lump.size; + memcpy(fl.name, wadfile->lumps[i].lump.name, sizeof (wadfile->lumps[i].lump.name)); + memcpy(p, &fl, sizeof(fl)); p += sizeof(fl); + ptr += size; + } + for (int i = 0; i < wadfile->header.numlumps; i++) + { + size_t size = (wadfile->lumps[i].lump.size + (WAD_ALIGN - 1)) & ~(WAD_ALIGN - 1); + memcpy(p, wadfile->lumps[i].data, wadfile->lumps[i].lump.size); + memset(p + wadfile->lumps[i].lump.size, 0, size - wadfile->lumps[i].lump.size); p += size; + } + *outLen = total; + return out; +} +int getLumpNumByName(wadfile_t *wadfile, const char *name) +{ + for (int i = 0; i < wadfile->header.numlumps; i++) + { + if (0 == strncmp(wadfile->lumps[i].lump.name, name, sizeof(wadfile->lumps[i].lump.name))) + return i; + } + return -1; +} +lump_t * getLumpByNum(wadfile_t *wadfile, int lumpNum) +{ + if (lumpNum >= wadfile->header.numlumps) + { + printf("Error, cannot find lum %d, max %d", lumpNum, wadfile->header.numlumps); + return NULL; + } + else + return &wadfile->lumps[lumpNum]; +} +void replaceLump(wadfile_t *wadfile, lump_t *newLump, int index) +{ + if (index >= wadfile->header.numlumps) + { + //printf("Lump %d >= numLumps %d\r\n", index, wadfile->header.numlumps); + return; + } + // free old lump data, not needed anymore + free(wadfile->lumps[index].data); + memcpy(&wadfile->lumps[index], newLump, sizeof(lump_t)); + //printf("new lump %d size %d\r\n", index, newLump->lump.size); +} +void insertLump(wadfile_t *wadfile, lump_t *newLump, int index) +{ + // create new table + lump_t *newTable = malloc((wadfile->header.numlumps + 1) * sizeof(lump_t)); + lump_t *oldTable = wadfile->lumps; + // copy all lumps before index + int i = 0; + if (index > wadfile->header.numlumps) + index = wadfile->header.numlumps; + for (; i < index; i++) + { + memcpy(&newTable[i], &oldTable[i], sizeof(lump_t) ); + } + // insert + memcpy(&newTable[i], newLump, sizeof(lump_t)); + // copy remaining + for (; i < wadfile->header.numlumps; i++) + { + memcpy(&newTable[i + 1], &oldTable[i], sizeof(lump_t) ); + } + wadfile->lumps = newTable; + free(oldTable); + // update numlumps + wadfile->header.numlumps++; +} +void removeLump(wadfile_t * wadfile, int index) +{ + if (index >= wadfile->header.numlumps) + return; + // create new table + // create new table + lump_t *newTable = malloc((wadfile->header.numlumps - 1) * sizeof(lump_t)); + lump_t *oldTable = wadfile->lumps; + // copy all lumps before index + int i = 0; + for (; i < index; i++) + { + memcpy(&newTable[i], &oldTable[i], sizeof(lump_t) ); + } + // remove + free(oldTable[i].data); + // copy remaining + for (; i < wadfile->header.numlumps - 1; i++) + { + memcpy(&newTable[i], &oldTable[i + 1], sizeof(lump_t) ); + } + wadfile->lumps = newTable; + free(oldTable); + // update numlumps + wadfile->header.numlumps--; +} +void mergeWadFile(wadfile_t *wad1, wadfile_t *wad2) +{ + for (int i = 0; i < wad2->header.numlumps; i++) + { + insertLump(wad1, &wad2->lumps[i], 0xFFFF); + } +} diff --git a/doom/src/wasm/wadfile.h b/doom/src/wasm/wadfile.h new file mode 100644 index 0000000..71bea6b --- /dev/null +++ b/doom/src/wasm/wadfile.h @@ -0,0 +1,43 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#ifndef WADFILE_H +#define WADFILE_H +#include "doomtypes.h" +#include +#include +#include +#include + +typedef struct +{ + filelump_t lump; + void *data; +} lump_t; +typedef struct +{ + wadinfo_t header; + lump_t *lumps; +} wadfile_t; +//bool loadWad(const char *fileName, uint32_t *lumpFound, lump_t **lumps, wadinfo_t *header); +bool loadWad(const char *fileName, wadfile_t *wadfile); +bool loadWadMem(const uint8_t *buf, size_t sz, wadfile_t *wadfile); +uint8_t *saveWadMem(wadfile_t *wadfile, char wadType, size_t *outLen); +bool saveWad(const char *fileName, wadfile_t *wadfile, char wadType); +void mergeWadFile(wadfile_t *wad1, wadfile_t *wad2); +void removeLump(wadfile_t * wadfile, int index); +void insertLump(wadfile_t *wadfile, lump_t *newLump, int index); +int getLumpNumByName(wadfile_t *wadfile, const char *name); +lump_t * getLumpByNum(wadfile_t *wadfile, int lumpNum); +void replaceLump(wadfile_t *wadfile, lump_t *newLump, int index); + +#endif // WADFILE_H diff --git a/doom/src/wasm/wadprocessor.c b/doom/src/wasm/wadprocessor.c new file mode 100644 index 0000000..7ad8f8f --- /dev/null +++ b/doom/src/wasm/wadprocessor.c @@ -0,0 +1,948 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#include "wadprocessor.h" +#include "doomtypes.h" +#include "wadfile.h" +#include +#include +static void convertCompositeTextures(wadfile_t *wadfile); +static bool processD2Levels(wadfile_t *wadfile); +static bool processD1Levels(wadfile_t *wadfile); + +static bool processLevel(wadfile_t *wadfile, uint32_t lumpNum); + +static bool processVertexes(wadfile_t *wadfile, uint32_t lumpNum); +static bool processLines(wadfile_t *wadfile, uint32_t lumpNum); +static bool processSegs(wadfile_t *wadfile, uint32_t lumpNum); +static bool processSides(wadfile_t *wadfile, uint32_t lumpNum); +static bool processPatches(wadfile_t *wadfile, int firstLump, int lastLump); +static void removeUnusedPatches(wadfile_t *wadfile); +static bool processPNames(); +static bool removeUnusedLumps(wadfile_t *wadfile, bool removeSound); + +int getTextureNumForName(wadfile_t *wadfile, const char* tex_name); + +bool processWad(wadfile_t *wadfile, bool removeSound, bool convertPatches) +{ + removeUnusedLumps(wadfile, removeSound); + convertCompositeTextures(wadfile); + // + removeUnusedPatches(wadfile); + if (!convertPatches) + { + printf("WARNING, NOT CONVERTING PATCHES\r\n"); + } + else + { + // for each patch, change it. Note, marksers are skipped. + int firstLump = getLumpNumByName(wadfile, "HELP1"); + if (firstLump == -1) // for DOOM2 + firstLump = getLumpNumByName(wadfile, "HELP"); + int lastLump = getLumpNumByName(wadfile, "P_END"); + processPatches(wadfile, firstLump, lastLump); + // process gba specific patches, added at the end + firstLump = getLumpNumByName(wadfile, "M_ARUN"); + lastLump = getLumpNumByName(wadfile, "STGANUM9") + 1; + + processPatches(wadfile, firstLump, lastLump); + } + int lumpNum = getLumpNumByName(wadfile, "MAP01"); + //Figure out if our IWAD is Doom or Doom2. (E1M1 or MAP01) + if(lumpNum != -1) + { + printf("Doom 2 level found\r\n"); + return processD2Levels(wadfile); + } + else + { + int lumpNum = getLumpNumByName(wadfile, "E1M1"); + /* v0.3.1: a partial WAD with only one episode (e.g. E2) has no E1M1 */ + for (int e = 2; e <= 4 && lumpNum == -1; e++) + { + char nm[8] = { 'E', (char)('0' + e), 'M', '1', 0, 0, 0, 0 }; + lumpNum = getLumpNumByName(wadfile, nm); + } + + //Can't find any maps. + if(lumpNum == -1) + { + printf("No maps found\r\n"); + return false; + } + printf("Doom 1 level found\r\n"); + } + + return processD1Levels(wadfile); +} +bool processD2Levels(wadfile_t *wadfile) +{ + for(int m = 1; m <= 32; m++) + { + char mapName[9]; + snprintf(mapName, sizeof(mapName), "MAP%02d",m); + int lumpNum = getLumpNumByName(wadfile, mapName); + + if(lumpNum != -1) + { + processLevel(wadfile, lumpNum); + } + } + return true; +} + +bool processD1Levels(wadfile_t *wadfile) +{ + for(int e = 1; e <= 4; e++) + { + for(int m = 1; m <= 9; m++) + { + char mapName[9]; + snprintf(mapName, sizeof(mapName), "E%dM%d",e,m); + + int lumpNum = getLumpNumByName(wadfile, mapName); + + if(lumpNum != -1) + { + printf("processing %s\r\n", mapName); + processLevel(wadfile, lumpNum); + } + else + { + printf("cannot find %s\r\n", mapName); + + } + } + } + + return true; +} + +bool processLevel(wadfile_t *wadfile, uint32_t lumpNum) +{ + processVertexes(wadfile, lumpNum); + processLines(wadfile, lumpNum); + processSegs(wadfile, lumpNum); + processSides(wadfile, lumpNum); + processPNames(wadfile); + return true; +} + +bool processVertexes(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t vtxLumpNum = lumpNum + ML_VERTEXES; + + lump_t *vxl; + + vxl = getLumpByNum(wadfile, vtxLumpNum); + + if (NULL == vxl) + return false; + + if(vxl->lump.size == 0) + return false; + // get number of vertex + uint32_t vtxCount = vxl->lump.size / sizeof(mapvertex_t); + // allocate new vertex + vertex_t* newVtx = malloc( sizeof (vertex_t) * vtxCount); + // + mapvertex_t* oldVtx = (mapvertex_t*) vxl->data; + // precalculate vertex + for(uint32_t i = 0; i < vtxCount; i++) + { + newVtx[i].x = (oldVtx[i].x << 16); + newVtx[i].y = (oldVtx[i].y << 16); + } + // allocate new lump info + lump_t *newVxl = malloc(sizeof (lump_t)); + // copy name + memcpy(newVxl->lump.name, vxl->lump.name, sizeof (vxl->lump.name)); + // change data and size information + newVxl->data = newVtx; + newVxl->lump.size = vtxCount * sizeof(vertex_t); + // replace lum + replaceLump(wadfile, newVxl, vtxLumpNum); + + return true; +} + +bool processLines(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t lineLumpNum = lumpNum+ML_LINEDEFS; + + lump_t *lines; + + lines = getLumpByNum(wadfile, lineLumpNum); + + if (NULL == lines) + return false; + + if(lines->lump.size == 0) + return false; + + uint32_t lineCount = lines->lump.size / sizeof(maplinedef_t); + + line_t* newLines = malloc (sizeof(line_t) * lineCount); + + maplinedef_t* oldLines = (maplinedef_t*) lines->data; + + //We need vertexes for this... + + uint32_t vtxLumpNum = lumpNum+ML_VERTEXES; + + lump_t *vxl; + + vxl = getLumpByNum(wadfile, vtxLumpNum); + + if (NULL == vxl) + return false; + + if(vxl->lump.size == 0) + return false; + + vertex_t* vtx = (vertex_t*)vxl->data; + + for(unsigned int i = 0; i < lineCount; i++) + { + newLines[i].v1.x = vtx[oldLines[i].v1].x; + newLines[i].v1.y = vtx[oldLines[i].v1].y; + + newLines[i].v2.x = vtx[oldLines[i].v2].x; + newLines[i].v2.y = vtx[oldLines[i].v2].y; + + newLines[i].special = oldLines[i].special; + newLines[i].flags = oldLines[i].flags; + newLines[i].tag = oldLines[i].tag; + + newLines[i].dx = newLines[i].v2.x - newLines[i].v1.x; + newLines[i].dy = newLines[i].v2.y - newLines[i].v1.y; + + newLines[i].slopetype = + !newLines[i].dx ? ST_VERTICAL : !newLines[i].dy ? ST_HORIZONTAL : + FixedDiv(newLines[i].dy, newLines[i].dx) > 0 ? ST_POSITIVE : ST_NEGATIVE; + + newLines[i].sidenum[0] = oldLines[i].sidenum[0]; + newLines[i].sidenum[1] = oldLines[i].sidenum[1]; + + newLines[i].bbox[BOXLEFT] = (newLines[i].v1.x < newLines[i].v2.x ? newLines[i].v1.x : newLines[i].v2.x); + newLines[i].bbox[BOXRIGHT] = (newLines[i].v1.x < newLines[i].v2.x ? newLines[i].v2.x : newLines[i].v1.x); + + newLines[i].bbox[BOXTOP] = (newLines[i].v1.y < newLines[i].v2.y ? newLines[i].v2.y : newLines[i].v1.y); + newLines[i].bbox[BOXBOTTOM] = (newLines[i].v1.y < newLines[i].v2.y ? newLines[i].v1.y : newLines[i].v2.y); + + newLines[i].lineno = i; + + } + + + // allocate new lump info + lump_t *newLine = malloc(sizeof (lump_t)); + // copy name + memcpy(newLine->lump.name, lines->lump.name, sizeof (lines->lump.name)); + // change data and size information + newLine->data = newLines; + newLine->lump.size = lineCount * sizeof(line_t); + // replace lum + replaceLump(wadfile, newLine, lineLumpNum); + + return true; +} + +bool processSegs(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t segsLumpNum = lumpNum+ML_SEGS; + + lump_t *segs; + + segs = getLumpByNum(wadfile, segsLumpNum); + + if (NULL == segs) + return false; + + if(segs->lump.size == 0) + return false; + + uint32_t segCount = segs->lump.size / sizeof(mapseg_t); + + seg_t* newSegs = malloc(sizeof(seg_t) * segCount); + + mapseg_t* oldSegs = (mapseg_t*) segs->data; + + //We need vertexes for this... + + uint32_t vtxLumpNum = lumpNum+ML_VERTEXES; + + lump_t *vxl; + + vxl = getLumpByNum(wadfile, vtxLumpNum); + + if (NULL == vxl) + return false; + + if(vxl->lump.size == 0) + return false; + + vertex_t* vtx = (vertex_t*)vxl->data; + + //And LineDefs. Must process lines first. + + uint32_t linesLumpNum = lumpNum+ML_LINEDEFS; + + lump_t * lxl; + + lxl = getLumpByNum(wadfile, linesLumpNum); + + if (NULL == lxl) + return false; + + if(lxl->lump.size == 0) + return false; + + + line_t* lines = (line_t *) lxl->data; + + //And sides too... + + uint32_t sidesLumpNum = lumpNum+ML_SIDEDEFS; + + lump_t * sxl; + + sxl = getLumpByNum(wadfile, sidesLumpNum); + + if (NULL == sxl) + return false; + + if(sxl->lump.size == 0) + return false; + + mapsidedef_t* sides = (mapsidedef_t*) sxl->data; + + + //**************************** + + for(unsigned int i = 0; i < segCount; i++) + { + newSegs[i].v1.x = vtx[oldSegs[i].v1].x; + newSegs[i].v1.y = vtx[oldSegs[i].v1].y; + + newSegs[i].v2.x = vtx[oldSegs[i].v2].x; + newSegs[i].v2.y = vtx[oldSegs[i].v2].y; + + newSegs[i].angle = oldSegs[i].angle << 16; + newSegs[i].offset = oldSegs[i].offset << 16; + + newSegs[i].linenum = oldSegs[i].linedef; + + const line_t* ldef = &lines[newSegs[i].linenum]; + + int side = oldSegs[i].side; + + newSegs[i].sidenum = ldef->sidenum[side]; + + if(newSegs[i].sidenum != NO_INDEX) + { + newSegs[i].frontsectornum = sides[newSegs[i].sidenum].sector; + } + else + { + newSegs[i].frontsectornum = NO_INDEX; + } + + newSegs[i].backsectornum = NO_INDEX; + + if(ldef->flags & ML_TWOSIDED) + { + if(ldef->sidenum[side^1] != NO_INDEX) + { + newSegs[i].backsectornum = sides[ldef->sidenum[side^1]].sector; + } + } + } + + + // allocate new lump info + lump_t *newSeg = malloc(sizeof (lump_t)); + // copy name + memcpy(newSeg->lump.name, segs->lump.name, sizeof (segs->lump.name)); + // change data and size information + newSeg->data = newSegs; + newSeg->lump.size = segCount * sizeof(seg_t); + // replace lum + replaceLump(wadfile, newSeg, segsLumpNum); + + return true; +} + +bool processSides(wadfile_t *wadfile, uint32_t lumpNum) +{ + uint32_t sidesLumpNum = lumpNum+ML_SIDEDEFS; + + lump_t *sides; + + sides = getLumpByNum(wadfile, sidesLumpNum); + + if (NULL == sides) + return false; + + if(sides->lump.size == 0) + return false; + + uint32_t sideCount = sides->lump.size / sizeof(mapsidedef_t); + + sidedef_t* newSides = malloc(sizeof(sidedef_t) * sideCount); + + mapsidedef_t* oldSides = (mapsidedef_t*) sides->data; + + for(unsigned int i = 0; i < sideCount; i++) + { + newSides[i].textureoffset = oldSides[i].textureoffset; + newSides[i].rowoffset = oldSides[i].rowoffset; + + newSides[i].toptexture = getTextureNumForName(wadfile, oldSides[i].toptexture); + newSides[i].bottomtexture = getTextureNumForName(wadfile, oldSides[i].bottomtexture); + newSides[i].midtexture = getTextureNumForName(wadfile, oldSides[i].midtexture); + + newSides[i].sector = oldSides[i].sector; + } + + // allocate new lump info + lump_t *newSide = malloc(sizeof (lump_t)); + // copy name + memcpy(newSide->lump.name, sides->lump.name, sizeof (sides->lump.name)); + // change data and size information + newSide->data = newSides; + newSide->lump.size = sideCount * sizeof(sidedef_t); + // replace lum + replaceLump(wadfile, newSide, sidesLumpNum); + + return true; +} + +int getTextureNumForName(wadfile_t *wadfile, const char* tex_name) +{ + + const int *maptex1, *maptex2; + int numtextures1, numtextures2 = 0; + const int *directory1, *directory2; + + + //Convert name to uppercase for comparison. + char tex_name_upper[9]; + + strncpy(tex_name_upper, tex_name, 8); + tex_name_upper[8] = 0; //Ensure null terminated. + + for (int i = 0; i < 8; i++) + { + tex_name_upper[i] = toupper(tex_name_upper[i]); + } + + lump_t * tex1lump; + int tex1LumpNum = getLumpNumByName(wadfile, "TEXTURE1"); + tex1lump = getLumpByNum(wadfile, tex1LumpNum); + + maptex1 = (const int*)tex1lump->data; + numtextures1 = *maptex1; + directory1 = maptex1+1; + + lump_t * tex2lump; + int tex2LumpNum = getLumpNumByName(wadfile, "TEXTURE2"); + + if (tex2LumpNum != -1) + { + tex2lump = getLumpByNum(wadfile, tex2LumpNum); + + maptex2 = (const int*)tex2lump->data; + directory2 = maptex2+1; + numtextures2 = *maptex2; + } + else + { + maptex2 = NULL; + directory2 = NULL; + } + + const int *directory = directory1; + const int *maptex = maptex1; + + int numtextures = (numtextures1 + numtextures2); + + for (int i=0 ; iname, 8)) + { + return i; + } + } + + return 0; +} +static uint16_t getColumnLength(column_t* column) +{ + uint8_t *columnData = (uint8_t *) column; + uint16_t n = 1; + while (column->topdelta != 0xff) + { + // get length + unsigned int length = column->length; + n++; + n += length + 3; + // get next top delta. + column = (column_t*) &columnData[n - 1]; + } + return n; +} +static bool processPatches(wadfile_t *wadfile, int firstLump, int lastLump) +{ + printf("First %d, last %d\r\n", firstLump, lastLump); + for(uint32_t patchLumpNum = firstLump; patchLumpNum < lastLump; patchLumpNum++) + { + // get next patch lump + lump_t * patchLump = getLumpByNum(wadfile, patchLumpNum); + if (0 == patchLump->lump.size) // sprites and texture patches share the same format. However they are separted by 0-length markers + continue; + // allocate new lump info + lump_t *newPatchLump = malloc(sizeof (lump_t)); + // create an empty patch whose size is the same as the old patch + patch_t *newPatch = (patch_t *) malloc (patchLump->lump.size); + // make an exact copy of the old ump + memcpy (newPatch, patchLump->data, patchLump->lump.size); + // + for (int c = 0; c < newPatch->width; c++) + { + // set the length on the upper part of the old columnOfs word. + int l = (getColumnLength(((uint8_t*)newPatch + newPatch->columnofs[c].offset)) + 3) & ~3; + if (l > 255) + printf("WARNING!!! FOUND A LENGTH > 255. (%d) on lump %d\r\n", l, patchLumpNum); + newPatch->columnofs[c].length = l; + } + // copy name + memcpy(newPatchLump->lump.name, patchLump->lump.name, sizeof (patchLump->lump.name)); + // change data and size informationColumn length + newPatchLump->data = newPatch; + newPatchLump->lump.size = patchLump->lump.size; + // replace lump + replaceLump(wadfile, newPatchLump, patchLumpNum); + + + + } + return true; + + +} + +bool processPNames(wadfile_t *wadfile) +{ + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return false; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnamesData = (char*)pnamesLump->data; + + uint32_t count = *((uint32_t*)pnamesData); + + pnamesData += 4; //Fist 4 bytes are count. + // uppercase everything + for(uint32_t i = 0; i < count; i++) + { + bool nullChar = false; + for (int j = 0; j < 8; j++) + { + uint8_t c; + if (nullChar) + c = 0; + else + c = toupper(pnamesData[i*8 + j]); + pnamesData[i*8 + j] = c; + if (0 == c) + { + nullChar = true; + } + + } + } + return true; +} +static volatile bool startsWith(char *string, char *prefix) +{ + return strncmp(string, prefix, strlen(prefix)) == 0; +} +bool removeUnusedLumps(wadfile_t *wadfile, bool removeSound) +{ + for(uint32_t i = 0; i < wadfile->header.numlumps; i++) + { + lump_t *l; + + l = getLumpByNum(wadfile, i); + char *name = l->lump.name; + if ( +#ifndef KEEP_MUS + startsWith(name, "D_") || +#endif + 0 || +#ifndef KEEP_DP + startsWith(name, "DP") || +#endif + (startsWith(name, "DS") && removeSound && !startsWith(name, "DSPISTOL"))|| + startsWith(name, "GENMIDI")) + { + //printf("removing lump %s\r\n", l->lump.name); + removeLump(wadfile, i); + i--; + } + } + return true; +} + +static inline void R_DrawColumnInCache(const column_t *patch, uint8_t *cache, int originy, int cacheheight) +{ + while (patch->topdelta != 0xff) + { + const uint8_t *source = (const uint8_t*) patch + 3; + int count = patch->length; + int position = originy + patch->topdelta; + + if (position < 0) + { + count += position; + position = 0; + } + + if (position + count > cacheheight) + count = cacheheight - position; + + if (count > 0) + memcpy(cache + position, source, count); + + patch = (const column_t*) ((const uint8_t*) patch + patch->length + 4); + } +} + + + +const uint8_t* R_ComposeColumn(wadfile_t *wadfile, const maptexture_t *tex, int xc, uint8_t* columnCacheBuffer) +{ + unsigned int i = 0; + unsigned int patchcount = tex->patchcount; + do + { + // note: all texetures and patch addresses are cached in flash. + const mappatch_t *patch = &tex->patches[i]; + + // get pnames + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + { + printf("Error, cannot find pnames\r\n"); + return NULL; + } + + lump_t *pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnames = (char*)pnamesLump->data + 4; + + int patchLumpNum = getLumpNumByName(wadfile, &pnames[patch->patch * 8]); + + if (patchLumpNum == -1) + { + printf("Error, cannot find patch lump\r\n"); + return NULL; + } + lump_t *patchLump = getLumpByNum(wadfile, patchLumpNum); + + const patch_t *realpatch = patchLump->data; + + const int x1 = patch->originx; + + if (xc < x1) + continue; + short width; + width = realpatch->width; + const int x2 = x1 + width; + + if (xc < x2) + { + const column_t *patchcol; + patchcol = (const column_t*) ((const uint8_t*) realpatch + (0xFFFFFF & realpatch->columnofs[xc - x1].offset)); + R_DrawColumnInCache(patchcol, columnCacheBuffer, patch->originy, tex->height); + } + } while (++i < patchcount); + return columnCacheBuffer; +} +void convertRectangularBitmapToPatch(lump_t * lump, uint8_t *textureBuffer, int width, int height) +{ + // patch header: 8 + columnofs[width] + int size = 8 + 4 * width; + // add topdelta, length, pad, data[heigth], pad, topdelta + size += (1 + 1 + 1 + height + 1 + 1) * width; + // + patch_t *patchData = malloc(size); + // already set lump size and data ptr + lump->lump.size = size; + lump->data = patchData; + // set up size etc + patchData->leftoffset = 0; + patchData->topoffset = 0; + patchData->width = width; + patchData->height = height; + // set column offsets and copy data + for (int i = 0; i < width; i++) + { + patchData->columnofs[i].offset = 8 + 4 * width + (1 + 1 + 1 + height + 1 + 1) * i; + uint8_t *data = (uint8_t*)patchData + patchData->columnofs[i].offset; + *data++ = 0; // top delta + *data++ = height; // post length + *data++ = 0; // pad + memcpy(data, &textureBuffer[i * height], height); + data += height; + *data++ = 0; // pad + *data++ = 0xFF; // last top delta + } +} +int addPatchToPnames(wadfile_t *wadfile, char *name) +{ + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return 0; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + uint8_t *newPnamesData = malloc(pnamesLump->lump.size + 8); + + memcpy (newPnamesData, pnamesLump->data, pnamesLump->lump.size); + + uint32_t count = *((uint32_t*)pnamesLump->data); + + // increase count + *((uint32_t*)newPnamesData) = count + 1; + + // copy new name + memcpy (newPnamesData + 4 + count * 8, name, 8); + + // allocate new lump info + lump_t *newPnames = malloc(sizeof (lump_t)); + // copy name + memcpy(newPnames->lump.name, pnamesLump->lump.name, sizeof (pnamesLump->lump.name)); + // change data and size information + newPnames->data = newPnamesData; + // increase size by 8, i.e. new name + newPnames->lump.size = pnamesLump->lump.size + 8; + // replace lum + replaceLump(wadfile, newPnames, lumpNum); + return count; +} + +static void convertCompositeTextures(wadfile_t *wadfile) +{ + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnamesData = (char*)pnamesLump->data; + + uint32_t count = *((uint32_t*)pnamesData); + + pnamesData += 4; //Fist 4 bytes are count. + + const int *maptex1, *maptex2; + int numtextures1, numtextures2; + const int *directory1, *directory2; + // get texture lump + lumpNum = getLumpNumByName(wadfile, "TEXTURE1"); + // load it + maptex1 = getLumpByNum(wadfile, lumpNum)->data; + // + numtextures1 = *maptex1; + + directory1 = maptex1 + 1; + + + if ( (lumpNum = getLumpNumByName(wadfile, "TEXTURE2")) != -1) + { + maptex2 = getLumpByNum(wadfile, lumpNum)->data; + numtextures2 = *maptex2; + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + numtextures2 = 0; + directory2 = NULL; + } + + int offset = 0; + + // now scan all the textures + uint32_t size = 0; + for (int texture_num = 0; texture_num < numtextures2 + numtextures1; texture_num++) + { + const int *maptex = maptex1; + if (texture_num < numtextures1) + { + offset = directory1[texture_num]; + } + else if (maptex2 && ((texture_num - numtextures1) < numtextures2)) + { + maptex = maptex2; + offset = directory2[texture_num-numtextures1]; + } + maptexture_t *mtexture = (maptexture_t*) ((const uint8_t*) maptex + offset); + + // 2022-04-19: removed check with patch < 2, as textures with 1 patches need to be addressed as well, as they might have different offsets. + // 2022-04-24: this screwed up masked textures. Modified so that we only change textures with 2 patches or single patch with 0 offset + // FIXME: this is not perfect solution anyway, as we might have some masked textures with offset. TO be checked. + if (mtexture->patchcount < 2 && mtexture->patches[0].originx == 0 && mtexture->patches[0].originy == 0) + continue; // we are interested only in composite textures. + uint8_t columnData[256]; // this should be enough. + size += mtexture->height * mtexture->width; + if (mtexture->height & 3) + printf("Warning, texture %d has height %d\r\n", texture_num, mtexture->height); + // allocate buffer for texture. Nofte that this has x-y swapped + uint8_t *textureBuffer = malloc(mtexture->height * mtexture->width); + memset(textureBuffer, 0, mtexture->height * mtexture->width); /* v0.3.1: otherwise gaps are random (leftover memory) */ + for (int x = 0; x < mtexture->width; x++) + { + R_ComposeColumn(wadfile,mtexture, x, &textureBuffer[mtexture->height * x]); + } + lump_t newPatchLump; + convertRectangularBitmapToPatch(&newPatchLump ,textureBuffer, mtexture->width, mtexture->height); + int endPatchLumpNum = getLumpNumByName(wadfile, "P_END") - 1; + char newName[9]; + snprintf(newName,9, "SPTE%04X", texture_num); // Note X must be UPPERCASE! + memcpy(newPatchLump.lump.name, newName, 8); + printf("New patch added: %d SPTE%04X\r\n", texture_num, texture_num); + insertLump(wadfile, &newPatchLump, endPatchLumpNum); + // add entry to pname + int newPatchNum = addPatchToPnames(wadfile, newPatchLump.lump.name); + + // now change texture data. Since offsets are used, we do not need to worry about resizing. + mtexture->patchcount = 1; + mtexture->patches[0].originx = 0; + mtexture->patches[0].originy = 0; + mtexture->patches[0].patch = newPatchNum; + // free textureBuffer + free(textureBuffer); + // + } + printf("Converting composite will increas size by %d bytes\r\n", size); +} +static void removeUnusedPatches(wadfile_t *wadfile) +{ + // scan for all patches in pnames. For each patch, see if it is listed in any texture + lump_t * pnamesLump; + int32_t lumpNum = getLumpNumByName(wadfile, "PNAMES"); + + if(lumpNum == -1) + return; + + pnamesLump = getLumpByNum(wadfile, lumpNum); + + char* pnamesData = (char*)pnamesLump->data; + + uint32_t count = *((uint32_t*)pnamesData); + + pnamesData += 4; //Fist 4 bytes are count. + // + // Load texture lumps + // + const int *maptex1, *maptex2; + int numtextures1, numtextures2; + const int *directory1, *directory2; + // get texture lump + lumpNum = getLumpNumByName(wadfile, "TEXTURE1"); + // load it + maptex1 = getLumpByNum(wadfile, lumpNum)->data; + // + numtextures1 = *maptex1; + + directory1 = maptex1 + 1; + + if ( (lumpNum = getLumpNumByName(wadfile, "TEXTURE2")) != -1) + { + maptex2 = getLumpByNum(wadfile, lumpNum)->data; + numtextures2 = *maptex2; + directory2 = maptex2 + 1; + } + else + { + maptex2 = NULL; + numtextures2 = 0; + directory2 = NULL; + } + + int offset = 0; + + uint32_t patchRemoved = 0; + uint32_t sizeSaved = 0; + // get texture data + for (int i = 0; i < count; i++) + { + + bool patchUsed = false; + for (int texture_num = 0; texture_num < numtextures2 + numtextures1; texture_num++) + { + const int *maptex = maptex1; + if (texture_num < numtextures1) + { + offset = directory1[texture_num]; + } + else if (maptex2 && ((texture_num - numtextures1) < numtextures2)) + { + maptex = maptex2; + offset = directory2[texture_num-numtextures1]; + } + maptexture_t *mtexture = (maptexture_t*) ((const uint8_t*) maptex + offset); + if (mtexture->patches[0].patch == i) + { + patchUsed = true; + break; + } + } + if (false == patchUsed) + { + int patchLumpNum = getLumpNumByName(wadfile, pnamesData); + if (-1 != patchLumpNum) + { + lump_t * lump = getLumpByNum(wadfile, patchLumpNum); + sizeSaved += lump->lump.size; + removeLump(wadfile, patchLumpNum); + patchRemoved++; + } + } + // point to next name + pnamesData += 8; + } + printf("Removed %d patches. Saved %d bytes\r\n", patchRemoved, sizeSaved); +} diff --git a/doom/src/wasm/wadprocessor.h b/doom/src/wasm/wadprocessor.h new file mode 100644 index 0000000..743fa17 --- /dev/null +++ b/doom/src/wasm/wadprocessor.h @@ -0,0 +1,19 @@ +/* + MCUDoomWadutil by Nicola Wrachien. + + Based on doomhack's GBAWadutil + Original source: https://github.com/doomhack/GbaWadUtil + + This command line utility allows to convert your wad file + to a format convenient for MCU-based Doom ports. + + Usage: + MCUDoomWadutil +*/ +#ifndef WADPROCESSOR_H +#define WADPROCESSOR_H + +#include "wadfile.h" +bool processWad(wadfile_t *wadfile, bool removeSound, bool convertPatches); + +#endif // WADPROCESSOR_H diff --git a/emu/LICENSE b/emu/LICENSE new file mode 100644 index 0000000..818433e --- /dev/null +++ b/emu/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/emu/README.md b/emu/README.md new file mode 100644 index 0000000..f16077b --- /dev/null +++ b/emu/README.md @@ -0,0 +1,186 @@ +# TamaEmu for the Tamagotchi Paradise + +An emulator for colour Tamagotchis (Epson S1C33) that runs on the Paradise. +The Studio builds it into the ROM together with the user's own firmware. + +- `emu.bin`: the emulator program. It is copied to PRAM by the launcher and + runs from there. +- `stub_tpl.bin`: the launcher (hooks on the home screen, A+C held) with + placeholders that the Studio fills in. +- `src/core`: the emulator core, derived from + [tamaemu](https://github.com/maragotchi/tamaemu) by maragotchi (GPL-3.0), + with a JIT translator to Thumb-2 (`tc_jit.c`). +- `src/emu`: the Paradise side (display, keys, sound, flash, saving the state). +- `src/stub/stub.S`: the launcher. +- `src/tools`: Python versions of the ROM patching steps (for tests). + +## Layout in the Paradise flash + +| Offset | What | +| --- | --- | +| 0x0A0000 | emulator program (64 KB, copied to PRAM on start) | +| 0x0B0000 | launcher and home screen hooks | +| 0x0C0000 | run state (written by the emulator) | +| 0x940000 | guest firmware, packed in 64 KB blocks; blocks the guest writes stay unpacked and hold its save | +| packed cold blocks (1.7.3, menu only) | table (128 u32), per block 65 u32 part starts, LZ4 data in 1 KB parts | +| behind it, up to 0xD40000 | spare pages: a table (4 KB) and 8 KB pages for blocks that are empty in the firmware but written by the guest | +| 0x840000 to 0xD48000 | instead of the two rows above, for firmware that does not fit there (P's, 4U+, 4U); the menu's field saves then have no room | + +## Writing the guest flash + +The guest erases and programs its flash like the real chip. Parameter sectors +(8 KB) and, since v0.9.2, the 64 KB sectors are kept as 8 KB copies in RAM and +written back to the Paradise flash when the slots run out or the game is +quiet. Erasing a 64 KB sector erases the stored block right away. Blocks that +are empty in the firmware are not stored by the Studio; their written 8 KB +parts go into spare pages behind the packed firmware. The table (magic +"PMXP", checksum) is written after the page, so a power cut leaves either the +old or the new state. + +Before v0.9.2 writes to 64 KB sectors were lost. The iD L then hung when it +saved something there, for example buying the mop in the Tamadepa (daily +items), and the long press saved that hung state. + +Leaving with a long press does not save the session if the core stopped or +guest writes were lost. Pressing the wheel within the first 3 seconds after a +resumed start drops the saved session. + +Settings flags bit 12 (0x1000, version 4 and up, build switch `SESS_FLAG`, 1.7.3 test7): no session. Leaving, the +autosave and an empty battery write only the guest flash (the toy's own save), never the run state; a session found at +the start is dropped and the guest boots from its own save. + +## Autostart + +With "Start when switched on" the stub decides once per boot, at the first +home screen call. Mailbox word 0x20000FFC survives a restart and the reset +button but not the Paradise's deep sleep: "PMXL" (written by the emulator when +going back) keeps the Paradise, "PMXR" (written by the stub) means a restart +while running, so the emulator starts. Without either, the seconds counter +0x45000304 tells power-on (counter new) from waking up (counter ran). The +"decided" flag is the UsageFault priority byte, which every reset clears. + +## Clock + +Each millisecond of the Paradise runs the guest for one millisecond of its +current clock. Since v0.9.3 the remainder of that division is carried over +(at 32768 Hz the guest used to get 32 instead of 32.768 cycles per ms, its +clock lost 2.3 percent). About once a second the emulator also compares the +guest time with the seconds counter of the Paradise (0x45000304) and adds +whole seconds to the guest clock when it fell behind, for example when busy +scenes (shopping, flash writes) made the emulator drop time. Implausible jumps +of the counter are ignored. + +At the start (settings version 4, flag bit 1, set by the Studio's "Take the +clock from the Paradise at the start"): the emulator reads the Paradise's own +time from the SRAM before it overwrites it (`paraclock.h`: the base of days and +seconds next to the six display fields, checked against the seconds counter) +and sets the guest's RTC registers to it, after a resumed session and on a +fresh start. Nothing is caught up. Without the flag, or when the time is not +found, a resumed session moves the clock on by the pause as before. + +## Download content (8 MB firmware) + +Stores and routing follow tamaemu `tools/dlc.c`: a record is a TAMAGO block, +routed by type (0x4E), category (0x50) and flag (0x51) into one of nine stores +(meals, snacks, clothing, accessories, items, daily items, wallpapers, games, +destinations). A new record goes into the first erased slot. + +## Build + +``` +sh src/emu/build.sh # clang, ld.lld, llvm-objcopy -> src/emu/emu.bin +``` + +Copy `src/emu/emu.bin` to `emu/emu.bin` (the Studio embeds that one). With `EMU_OVL` (on since 1.6.13 test10) the +build links with `link_ovl.ld`: the settings menus and the save code sit at the end of the image, in the translator's +room, and are copied back from the flash when they are needed. + +Device simulation (Unicorn, private ROMs only): `node test/mkimg.js emu.bin out.bin`, then +`python3 test/devemu.py src/emu/emu.elf out.bin ` with `KEYS`, `SHOTS`, `OUT`, `LAGLOG`, `PROF`, `ROMHIST`. + +Launcher template (link address 0x1009F000): + +``` +clang --target=thumbv7m-none-eabi -mcpu=cortex-m3 -x assembler-with-cpp -c src/stub/stub.S -o stub.o \ + -DHOOKS=1 -DLIMIT=90 -DAPP_SRC=0x1234ABCD -DORIG0=0x22222221 -DORIG1=0x33333331 -DORIG2=0x44444441 -DORIG3=0x55555551 +ld.lld --no-rosegment -Ttext=0x1009F000 -e start stub.o -o stub.elf +llvm-objcopy -O binary stub.elf stub_tpl.bin +``` + +Both results are byte-identical to the files shipped here. + +With `-DFELD=1` (menu launcher) the stub has a second entry at +0x0C +(`start_src`, 1.6.0): it copies the 64 KB image at the XIP address in r0 to +PRAM and restarts, like `start` does with its own program. The menu starts +further programs through it. Since 1.6.6 it reads from the uncached flash +(r0 + 0x50011000): the cached window shows only 1 MB. Build the menu launcher +with the same line plus `-DFELD=1 -DFELD_SRC=0x6789EF01 -DAUTO=0x66666661`. +Since 1.6.8 the menu launcher also has the entry `launch` at +0x20 (start the +menu), keeps the menu address at +0x28 and has at +0x2C the entry for the start +device's trampolines (menu once the Paradise has a save, otherwise the original +handler in r12). + +License: GNU GPL version 3 (see `LICENSE`). + +## Code that overwrites itself + +The translator throws away all translated code when the guest writes to an +a0ram page that holds translated code. Since v0.9.6 a page that causes this 8 +times within about 0.1 s of guest time is run by the interpreter only, for +about 5 s, then it gets another chance. Before, Connect to a Plus Color on the +iD L (code at 0xC00 next to its data) caused thousands of flushes per second +and the emulator stood still on the device. Build switch `JIT_WHOT`. + +## 4U NFC chip and the clock (1.6.8) + +The 4U and 4U+ firmware polls its PN512 NFC chip over the IR UART all the time (about 4000 bytes per +second to 0x300B10). The Paradise has no such chip, so every poll ran into a timeout and the menus needed +two presses. `tc_periph.c` now answers like an idle PN512 (register writes acknowledged, commands done at +once, empty FIFO). On for device kinds 3 and 4; PMXC flags bit 2 switches it off (Studio: "4U: emulate the +NFC chip"). + +The guest's real-time clock counted in guest cycles. When the guest changed its clock (fast clock to +32768 Hz, for example the iD L when its display goes off) the part of a second already counted at the fast +clock counted as many seconds at the slow one: the clock jumped by minutes. With `RTC_MS` (build.sh) the +seconds and the 1 s / 1 min / 1 h interrupts follow the real milliseconds of the main loop +(`periph_rtc_ms`); only the 1/64 s interrupt stays in cycles. `clock_sync` keeps the comparison with the +Paradise's crystal: missing seconds are added, a guest clock ahead skips one ms in 16. + +## Pictures and the Paradise's clock from the menu (1.6.8) + +`LCD_QUIET`: the screen is updated only when the guest has written nothing to its LCD for 2 ms (at most every +40 ms, at the latest after 120 ms), so a picture is never shown half drawn. + +The Paramix menu uses the Paradise's SRAM, where the Paradise keeps its clock. It looks the clock up at its own +start and leaves it in the mailbox at 0x20000FC0 (`paraclock.h`: `para_mailbox_put`, `para_mailbox`); a +program started from the menu takes it from there when its own search finds nothing. + +- 1.6.8-test5 APP_SELF: the start check (pram_check: PRAM against the image in the flash) uses the program's own image. A further + TamaEmu of the menu has it right behind its guest area (spare_end, the settings there name the same guest and save); before, it + compared with 0x0A0000 and copied the main TamaEmu's settings over its own. Its own settings block is never replaced. +- 1.6.8-test5 BL_GUEST_PWM: the colour Tamas light their screen with T16 channel 2 (0x300796 bit 0, clock 0x3007E4 bit 3). The P's + sends Sleep Out every 20 minutes for about 9 s without starting it (PC test: 36 times in a night); the backlight now goes on only + with the guest's light, a key or a tone in the last second, and stays on while the LCD stays on. + +## Infrared between two Paradise (TC_IRLINK, 1.6.9) + +P's and iD L: the bytes the toy writes to its infrared UART (0x300B10, also SIO_TX 0x301704) go out as 'E' frames +over the UART on the contacts (`src/emu/plink.h`, 460800 8N1). Received bytes come in at the toy's byte rate +(divisor at 0x300B16/17, 576 kHz clock, 10 bits per byte) with the RX interrupt, only while the receiver is armed +(0x300B15); the P's also only in a session (its byte 0xDB3, as tamaemu's ir_mode_flag), otherwise the byte is +lost and the peer-detect flag (0x300287 bit 3) rises. TX ready (0x300B12 bit 1) and the TX interrupt follow the byte +time. All as in tamaemu's periph.c (Android TamaEmu), the bytes from the platform instead of link.c (no time stamps: +the devices pass them on at once). State outside `Emu`, so saved sessions stay valid. Not for the Plus Color (its +infrared is a GPIO) and the 4U/4U+ (their UART talks to the NFC chip). + +Checked on the PC with two P's cores in lockstep (host harness): あそぶ, one あそびにいく, the other ともだちをよぶ, +ふたりで, かくれんぼ: both play, the guest goes home, the host gets Gotchi points. With 15 ms delay each way it still +works, with 30 ms it ends in つうしん しっぱい. + +Room: `boot()` (everything before the translator starts) runs from `.initcode`, the translator's area later, and a +few rarely used functions are built small (minsize). The translator area is 11772 bytes (before: 11608). + +Key with the screen dark (1.7.3 test7, switch EMU_KEY_AWAKE): a key woke the chip from deep sleep and reached the +guest, but once it was let go the program slept again before the guest had switched its screen on; the guest's +wake-up then waited for the next RTC second. Now the chip stays awake for 2 s after a key (g_btn_ms). devemu.py, iD L +dark at 200 s, key 150 ms in the middle of an RTC second: picture 663 ms after the key before. diff --git a/emu/emu.bin b/emu/emu.bin new file mode 100644 index 0000000..0185319 Binary files /dev/null and b/emu/emu.bin differ diff --git a/emu/src/core/LICENSE-tamaemu b/emu/src/core/LICENSE-tamaemu new file mode 100644 index 0000000..818433e --- /dev/null +++ b/emu/src/core/LICENSE-tamaemu @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/emu/src/core/tc.h b/emu/src/core/tc.h new file mode 100644 index 0000000..e015f39 --- /dev/null +++ b/emu/src/core/tc.h @@ -0,0 +1,232 @@ +/* Lean core for colour Tamagotchis (S1C33), derived from tamaemu + * (github.com/maragotchi/tamaemu, GPL-3.0). For Paradise apps without an + * operating system: no stdio, no floating point, fixed memory blocks. */ +#ifndef TC_H +#define TC_H +#include +#include +/* Only needed at startup: placed at the end of the image, the translator takes the space afterwards */ +#if defined(__arm__) && !defined(TC_HOST) +#ifdef EMU_OVL +/* 1.6.13 test10: start code for size (the program image is full) */ +#define TC_INIT __attribute__((section(".initcode"), noinline, minsize)) +#define TC_INIT_LAST __attribute__((section(".initcode_z"), noinline, minsize)) +#else +#define TC_INIT __attribute__((section(".initcode"), noinline)) +/* at the very end: writes the fixed routines to the start of the area */ +#define TC_INIT_LAST __attribute__((section(".initcode_z"), noinline)) +#endif +/* 1.6.8: rarely run code, small (0x20000000 is only 4 KB, mirrored; the SRAM is full) */ +#define TC_SRAM __attribute__((noinline, minsize)) +#else +#define TC_SRAM +#define TC_INIT +#define TC_INIT_LAST +#endif +#include +#ifdef TC_HOST +#include +#else +void *memset(void *d, int c, size_t n); +void *memcpy(void *d, const void *s, size_t n); +#endif + +typedef struct DeviceProfile { + uint32_t rom_base, rom_size; + uint32_t a0ram_base, a0ram_size; + uint32_t ivram_base, ivram_size; + uint32_t dstram_base, dstram_size; + uint32_t io_base, io_end, io_size; + uint32_t lcd_cmd_addr, lcd_data_addr; + bool flash_top_boot; + bool debug_strap_high; + bool has_sleep_flag; + uint32_t sleep_flag; + uint32_t ttbr_reset; + uint32_t osc3_hz; + uint8_t ir_gpio_rx_bit; + bool ir_gpio; + bool nfc_pn512; /* 4U/4U+: the PN512 NFC chip answers on the IR UART (1.6.8) */ +} DeviceProfile; + +#define A0RAM_MAX 0x00008000u +#define IVRAM_MAX 0x00003000u +#define DSTRAM_MAX 0x00001000u +#define IORAM_MAX 0x00002000u +#define GRAM_W 128 +#define GRAM_H 128 + +typedef struct Lcd { + uint16_t (*gram)[GRAM_W]; /* 128x128, located in fast PRAM */ + uint8_t cmd; + int argc; + uint8_t args[16]; + int xs, xe, ys, ye, cx, cy; + uint8_t madctl, colmod; + bool sleep_out, disp_on, inverted; + uint8_t pix_buf[3]; + int pix_n; + /* changed area since the last fetch */ + int dx0, dy0, dx1, dy1; +} Lcd; + +typedef struct Cmu { + uint8_t unlocked; + uint32_t sccr, pllc, opt; + uint32_t osc3_hz, mclk_hz; +} Cmu; + +typedef struct T16 { uint16_t counter; uint8_t a_fired; uint32_t accum; } T16; + +/* Writable flash sectors live in RAM (overlay), the rest is read + * directly from the Paradise flash (XIP). */ +#define OVL_SLOTS 8 +#define OVL_SIZE 0x2000u /* one 8 KB parameter sector per slot */ +typedef struct Overlay { + uint32_t base[OVL_SLOTS]; /* ROM offset of the sector, 0xFFFFFFFF = free */ + uint8_t *mem[OVL_SLOTS]; + int n; +} Overlay; + +typedef struct Emu { + uint32_t r[16]; + uint32_t sp, alr, ahr, ttbr, idir, dbbr; + uint32_t pc; + /* Translator (tc_jit.c): fields near the start so the generated code + * reaches them with short offsets. */ + uint32_t nzcv; /* flags in ARM format, C = not guest C */ + int32_t jit_left; /* remaining cycles (r10) */ + uint32_t jit_bias; /* exit request from a helper */ + uint32_t jit_a0; /* target address of a0ram */ + uint32_t jit_h[9]; /* target addresses of the helpers */ + uint32_t jit_flush; /* flush the cache at the next stop */ + int flash_busy; /* kept up front: the translator reads ROM directly */ + bool flash_autoselect; /* as long as both are zero */ + uint32_t jit_rom[128]; /* ROM per 64 KB as target address (0 = helper), see jit_rom_update */ + uint32_t jit_par[8]; /* parameter block per 8 KB (overlay or original) */ + uint32_t jit_parb; /* offset of the parameter block */ + uint8_t jit_map[128]; /* a0ram pages (256 B) with translated code */ + uint32_t jit_slot[600]; /* jump targets of the exits (chaining without changing code) */ + uint32_t jit_itab[2 * 256];/* jump targets: (guest pc, code|1), direct mapped */ + uint8_t f_n, f_z, f_v, f_c, f_ie; + uint8_t il; + uint32_t psr_rest; + int ext_count; + uint32_t ext_val[2]; + bool halted, halt_hard; + uint64_t wake_at; + uint64_t cycles; + uint64_t evt; /* next stop of the fast core */ + bool stopped; + uint32_t stop_pc, stop_code; + DeviceProfile dev; + const uint8_t *rom; /* original in flash (uncached window) */ + const uint8_t *rom_fast; /* only for tc_cpu.c (reference on the host) */ + uint32_t rom_fast_len; + /* ROM in 64 KB blocks: rom_src = data (0 = erased, reads 0xFF), + * rom_blk = fast read pointer (0 = via mem_read, e.g. parameter block) */ + const uint8_t *rom_src[128]; + const uint8_t *rom_blk[128]; + uint32_t par_base; /* 64 KB with 8 KB parameter sectors */ + /* Instruction window: host pointer for pc in [fw_lo, fw_lo+fw_len) */ + const uint8_t *fw_ptr; uint32_t fw_lo, fw_len; + Overlay ovl; + uint8_t a0ram[A0RAM_MAX]; + uint8_t ivram[IVRAM_MAX]; + uint8_t dstram[DSTRAM_MAX]; + uint8_t ioram[IORAM_MAX]; + Cmu cmu; + Lcd lcd; + T16 t16[6]; + uint32_t pending_irq; + uint8_t pending_level; + bool wake_req; + uint64_t last_tick; + uint8_t btn_mask; + uint32_t rtc_cyc, rtc_irq_cyc; + int flash_state; + bool flash_dirty; + uint16_t flash_op_data; + bool flash_toggle; + uint32_t flash_lost_writes; /* write attempts without a free slot */ + uint64_t lcd_writes; + uint32_t ovl_blk[4]; /* 64 KB blocks outside the parameter block with a written copy (bit per block) */ + uint32_t flash_big_ops; /* erases and writes in 64 KB sectors (for the display) */ + /* Blocks without their own storage (erased in the original): written 8 KB parts live in + * spare pages (device). pg_blk: bit per block, pg_map: page index per 8 KB (0xFF = erased). */ + const uint8_t *pg_base; + uint32_t pg_blk[4]; + uint8_t pg_map[1024]; +} Emu; + +/* cpu */ +void cpu_reset(Emu *e); +void cpu_step(Emu *e); +/* mem */ +uint8_t mem_read8 (Emu *e, uint32_t a); +uint16_t mem_read16(Emu *e, uint32_t a); +uint32_t mem_read32(Emu *e, uint32_t a); +void mem_write8 (Emu *e, uint32_t a, uint8_t v); +void mem_write16(Emu *e, uint32_t a, uint16_t v); +void mem_write32(Emu *e, uint32_t a, uint32_t v); +void tc_fetch_window(Emu *e, uint32_t pc); +/* periph */ +uint8_t periph_read8 (Emu *e, uint32_t a); +uint32_t periph_read32(Emu *e, uint32_t a); +void periph_write8 (Emu *e, uint32_t a, uint8_t v); +void periph_write32(Emu *e, uint32_t a, uint32_t v); +void periph_tick(Emu *e, uint32_t cycles); +uint32_t periph_next(Emu *e); +void periph_rtc_advance(Emu *e, uint32_t n); +void periph_rtc_ms(Emu *e); +extern uint32_t g_tc_rtc_wr; /* writes of the guest to its clock registers (1.6.8) */ +#ifdef TC_IRLINK +/* 1.6.9: infrared to another Paradise (tc_periph.c); the platform passes the bytes */ +void tc_ir_setup(uint32_t mode_flag, uint32_t ctx_ptr); +int tc_ir_avail(void); +int tc_ir_in(void); +void tc_ir_out(uint8_t b); +#endif +void periph_rtc_set(Emu *e, uint32_t t); /* local time, seconds since 1970 */ +uint32_t periph_rtc_get(Emu *e); /* 1.7.2 test16: the guest clock, 0 = stopped or not a date */ +void periph_buttons(Emu *e, uint8_t mask); +void periph_init(Emu *e); +/* lcd */ +void lcd_cmd (Emu *e, uint8_t c); +void lcd_data(Emu *e, uint8_t d); +/* device */ +void tc_profile_plus_color(DeviceProfile *d); +void tc_profile_idl(DeviceProfile *d); +void tc_rom_linear(Emu *e, const uint8_t *rom); +void tc_init(Emu *e, const uint8_t *rom_xip, uint16_t (*gram)[GRAM_W], uint8_t *ovl_pool, int slots); +/* Runs until cycles >= ziel; returns true if stopped (error). */ +bool tc_run(Emu *e, uint64_t ziel); +void tc_exec(Emu *e, uint64_t ziel); +/* translator */ +void jit_init(Emu *e, uint8_t *buf, uint32_t tgt, uint32_t size); +void jit_exec(Emu *e, uint64_t ziel); +void jit_flush_all(Emu *e); +uint32_t periph_tone_hz(Emu *e); /* guest tone in Hz, 0 = silent */ +/* All overlay slots in use: write one back and free it (device). */ +extern int (*tc_ovl_evict)(Emu *e); +/* Erase a 64 KB sector of the guest in the backing store (host image or Paradise flash). + * Returns 1 if done. Without it, such erases are lost as before. */ +extern int (*tc_big_erase)(Emu *e, uint32_t base); +#ifdef TC_LZ +extern const uint8_t *tc_lz_tab; /* 1.7.3 GUEST_LZ: table of the packed cold blocks (0 = none) */ +extern uint32_t tc_lz_gone[4]; +#endif +void tc_ovl_free(Emu *e, int i); /* release a slot without writing it back */ +void tc_blk_update(Emu *e, uint32_t blk); /* fast pointers of a 64 KB block after a change */ +void jit_rom_update(Emu *e, uint32_t off); /* ROM offset: recompute the entry */ +extern uint32_t (*jit_tgt_of)(const uint8_t *p); /* host pointer -> target address (test bench) */ +extern int jit_enabled; +/* Platform: enter generated code, or sync the instruction cache */ +uint32_t jit_enter(Emu *e, uint32_t code); +extern volatile uint32_t jit_dbg[44]; +void jit_stage_setup(uint8_t *stage, uint32_t size); +extern uint32_t jit_st_copy; +extern void (*jit_bad_hook)(Emu *e); +void jit_sync(uint32_t lo, uint32_t hi); +void tc_exec(Emu *e, uint64_t ziel); +#endif diff --git a/emu/src/core/tc_all.c b/emu/src/core/tc_all.c new file mode 100644 index 0000000..3d0b389 --- /dev/null +++ b/emu/src/core/tc_all.c @@ -0,0 +1,9 @@ +/* One translation unit for the whole core, so the compiler can inline. */ +#include "tc_mem.c" +#include "tc_periph.c" +#include "tc_lcd.c" +#include "tc_core.c" +#include "tc_fast.c" +#ifdef TC_JIT +#include "tc_jit.c" +#endif diff --git a/emu/src/core/tc_core.c b/emu/src/core/tc_core.c new file mode 100644 index 0000000..4c205fd --- /dev/null +++ b/emu/src/core/tc_core.c @@ -0,0 +1,100 @@ +#include "tc.h" + +TC_INIT void tc_profile_idl(DeviceProfile *d) +{ + memset(d, 0, sizeof *d); + d->rom_base = 0x02000000u; d->rom_size = 0x00800000u; + d->a0ram_base = 0x00000000u; d->a0ram_size = 0x00008000u; + d->ivram_base = 0x00080000u; d->ivram_size = 0x00003000u; + d->dstram_base = 0x00084000u; d->dstram_size = 0x00001000u; + d->io_base = 0x00300000u; d->io_end = 0x00302000u; d->io_size = 0x2000u; + d->lcd_cmd_addr = 0x00600000u; d->lcd_data_addr = 0x00600001u; + d->flash_top_boot = false; + d->debug_strap_high = false; + d->has_sleep_flag = true; d->sleep_flag = 0x00000FD8u; + d->ttbr_reset = 0x02400000u; + d->osc3_hz = 18432000u; +} + +TC_INIT void tc_profile_plus_color(DeviceProfile *d) +{ + memset(d, 0, sizeof *d); + d->rom_base = 0x00C00000u; d->rom_size = 0x00400000u; + d->a0ram_base = 0x00000000u; d->a0ram_size = 0x00008000u; + d->ivram_base = 0x00080000u; d->ivram_size = 0x00003000u; + d->dstram_base = 0x00084000u; d->dstram_size = 0x00001000u; + d->io_base = 0x00300000u; d->io_end = 0x00302000u; d->io_size = 0x2000u; + d->lcd_cmd_addr = 0x00600000u; d->lcd_data_addr = 0x00600001u; + d->flash_top_boot = true; +#ifdef TC_STRAP_TEST + d->debug_strap_high = false; /* test only */ +#else + d->debug_strap_high = true; +#endif + d->has_sleep_flag = true; d->sleep_flag = 0x00000368u; + d->ttbr_reset = 0x00C00000u; + d->osc3_hz = 20000000u; + d->ir_gpio = true; d->ir_gpio_rx_bit = 5; +} + +TC_INIT void tc_init(Emu *e, const uint8_t *rom_xip, uint16_t (*gram)[GRAM_W], uint8_t *ovl_pool, int slots) +{ + DeviceProfile d = e->dev; + memset(e, 0, sizeof *e); + e->dev = d; + e->rom = rom_xip; + e->rom_fast = rom_xip; e->rom_fast_len = 0; + e->par_base = d.flash_top_boot ? d.rom_size - 0x10000u : 0; + if (rom_xip) tc_rom_linear(e, rom_xip); + e->lcd.gram = gram; + for (int i = 0; i < OVL_SLOTS; i++) { e->ovl.base[i] = 0xFFFFFFFFu; e->ovl.mem[i] = 0; } + for (int i = 0; i < slots && i < OVL_SLOTS; i++) e->ovl.mem[i] = ovl_pool + (uint32_t)i * OVL_SIZE; + e->ovl.n = 0; + e->lcd.xe = 131; e->lcd.ye = 161; + e->lcd.dx0 = 0; e->lcd.dy0 = 0; e->lcd.dx1 = 127; e->lcd.dy1 = 127; + e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; + periph_init(e); + cpu_reset(e); +} + +uint32_t tc_halt_steps; +/* ROM is contiguous from rom (fill the block tables). */ +TC_INIT __attribute__((minsize)) void tc_rom_linear(Emu *e, const uint8_t *rom) +{ + for (uint32_t i = 0; i < 128; i++) { + e->rom_src[i] = (i << 16) < e->dev.rom_size ? rom + (i << 16) : 0; + e->rom_blk[i] = e->rom_src[i]; + } + e->rom_blk[e->par_base >> 16] = 0; +} + +bool tc_run(Emu *e, uint64_t ziel) +{ + while (e->cycles < ziel) { + if (e->stopped) return true; + if (e->halted) { + if (e->pending_irq || e->wake_req || (!e->halt_hard && e->cycles >= e->wake_at)) { + e->halted = false; + } else { + /* Sleeping CPU: fast forward time in steps instead of cycle by cycle. */ + uint64_t step = ziel - e->cycles; +#ifdef TC_JIT + { uint32_t nx = periph_next(e); if (step > nx) step = nx; tc_halt_steps++; } +#else + if (step > 1024) step = 1024; +#endif + if (!e->halt_hard && e->wake_at > e->cycles && e->wake_at - e->cycles < step) step = e->wake_at - e->cycles; + if (!step) step = 1; + e->cycles += step; + periph_tick(e, (uint32_t)(e->cycles - e->last_tick)); + e->last_tick = e->cycles; + continue; + } + } +#ifdef TC_JIT + if (jit_enabled) { jit_exec(e, ziel); continue; } +#endif + tc_exec(e, ziel); + } + return e->stopped; +} diff --git a/emu/src/core/tc_cpu.c b/emu/src/core/tc_cpu.c new file mode 100644 index 0000000..86d297b --- /dev/null +++ b/emu/src/core/tc_cpu.c @@ -0,0 +1,629 @@ +/* S1C33 PE interpreter implemented with reference to GMMan's SLEIGH definition: + * https://github.com/GMMan/s1c33_sleigh + */ + +#include "tc.h" + + +/* Fast paths for the most common accesses: A0RAM at 0, IVRAM at 0x80000 + * (stack), DSTRAM at 0x84000, cached ROM. */ +#ifdef TC_STATS +void stat_acc(uint32_t a, int w); +#define ST(a, w) stat_acc((a), (w)) +#else +#define ST(a, w) ((void)0) +#endif +static inline uint8_t *ramp(Emu *e, uint32_t a, uint32_t n) +{ + if (a <= A0RAM_MAX - n) return e->a0ram + a; + uint32_t o = a - 0x80000u; + if (o <= IVRAM_MAX - n) return e->ivram + o; + o = a - 0x84000u; + if (o <= DSTRAM_MAX - n) return e->dstram + o; + return 0; +} +static inline uint8_t rd8(Emu *e, uint32_t a) +{ + ST(a, 0); + uint8_t *p = ramp(e, a, 1); if (p) return *p; + uint32_t o = a - e->dev.rom_base; + if (o < e->rom_fast_len && !e->flash_busy && !e->flash_autoselect) return e->rom_fast[o]; + return mem_read8(e, a); +} +static inline uint16_t rd16(Emu *e, uint32_t a) +{ + ST(a, 0); + uint8_t *p = ramp(e, a, 2); if (p) return (uint16_t)(p[0] | (p[1] << 8)); + uint32_t o = a - e->dev.rom_base; + if (o < e->rom_fast_len - 1 && e->rom_fast_len && !e->flash_busy && !e->flash_autoselect) { const uint8_t *q = e->rom_fast + o; return (uint16_t)(q[0] | (q[1] << 8)); } + return mem_read16(e, a); +} +static inline uint32_t rd32(Emu *e, uint32_t a) +{ + ST(a, 0); + uint8_t *p = ramp(e, a, 4); if (p) return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + uint32_t o = a - e->dev.rom_base; + if (o < e->rom_fast_len - 3 && e->rom_fast_len && !e->flash_busy && !e->flash_autoselect) { const uint8_t *q = e->rom_fast + o; return (uint32_t)q[0] | ((uint32_t)q[1] << 8) | ((uint32_t)q[2] << 16) | ((uint32_t)q[3] << 24); } + return mem_read32(e, a); +} +static inline void wr8(Emu *e, uint32_t a, uint8_t v) { ST(a, 1); uint8_t *p = ramp(e, a, 1); if (p) *p = v; else mem_write8(e, a, v); } +static inline void wr16(Emu *e, uint32_t a, uint16_t v) { ST(a, 1); uint8_t *p = ramp(e, a, 2); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); } else mem_write16(e, a, v); } +static inline void wr32(Emu *e, uint32_t a, uint32_t v) { ST(a, 1); uint8_t *p = ramp(e, a, 4); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); } else mem_write32(e, a, v); } + +static uint32_t sext(uint32_t v, int bits) +{ + uint32_t m = 1u << (bits - 1); + return (v ^ m) - m; +} + +/* ---- flag helpers (s1c33_macros.sinc) ---- */ +static void result_flags(Emu *e, uint32_t r) +{ + e->f_n = (r >> 31) & 1; + e->f_z = (r == 0); +} + +static uint8_t scarry(uint32_t a, uint32_t b) +{ + uint32_t s = a + b; + return ((~(a ^ b)) & (a ^ s)) >> 31; +} + +static uint8_t sborrow(uint32_t a, uint32_t b) +{ + uint32_t d = a - b; + return ((a ^ b) & (a ^ d)) >> 31; +} + +static uint32_t add_op(Emu *e, uint32_t a, uint32_t b) +{ + e->f_v = scarry(a, b); + e->f_c = (a + b) < a; + uint32_t r = a + b; + result_flags(e, r); + return r; +} + +static uint32_t adc_op(Emu *e, uint32_t a, uint32_t b) +{ + uint32_t cz = e->f_c, s = a + b; + e->f_v = scarry(a, b) ^ scarry(s, cz); + e->f_c = ((a + b) < a) || ((s + cz) < s); + uint32_t r = s + cz; + result_flags(e, r); + return r; +} + +static uint32_t sub_op(Emu *e, uint32_t a, uint32_t b) +{ + e->f_v = sborrow(a, b); + e->f_c = a < b; + uint32_t r = a - b; + result_flags(e, r); + return r; +} + +static uint32_t sbc_op(Emu *e, uint32_t a, uint32_t b) +{ + uint32_t cz = e->f_c, d = a - b; + e->f_v = sborrow(a, b) || sborrow(d, cz); + e->f_c = (a < b) || (d < cz); + uint32_t r = d - cz; + result_flags(e, r); + return r; +} + +static void cmp_op(Emu *e, uint32_t a, uint32_t b) +{ + e->f_v = sborrow(a, b); + e->f_c = a < b; + result_flags(e, a - b); +} + +static uint32_t log_flags(Emu *e, uint32_t r) +{ + result_flags(e, r); + e->f_v = 0; + return r; +} + +static uint32_t sl_op(Emu *e, uint32_t a, uint32_t n) +{ + n &= 31; + uint32_t r = a << n; + result_flags(e, r); + return r; +} + +static uint32_t srl_op(Emu *e, uint32_t a, uint32_t n) +{ + n &= 31; + uint32_t r = a >> n; + result_flags(e, r); + return r; +} + +static uint32_t sra_op(Emu *e, uint32_t a, uint32_t n) +{ + n &= 31; + uint32_t r = (uint32_t)((int32_t)a >> n); + result_flags(e, r); + return r; +} + +static uint32_t rr_op(Emu *e, uint32_t a, uint32_t n) +{ + n &= 31; + uint32_t r = n ? ((a >> n) | (a << (32 - n))) : a; + result_flags(e, r); + return r; +} + +static uint32_t rl_op(Emu *e, uint32_t a, uint32_t n) +{ + n &= 31; + uint32_t r = n ? ((a << n) | (a >> (32 - n))) : a; + result_flags(e, r); + return r; +} + +/* ---- PSR pack/unpack (bit0 N,1 Z,2 V,3 C,4 IE, 8-11 IL) ---- */ +static uint32_t psr_pack(Emu *e) +{ + return (e->psr_rest & ~0xF1Fu) | e->f_n | (e->f_z << 1) | (e->f_v << 2) | + (e->f_c << 3) | (e->f_ie << 4) | ((uint32_t)(e->il & 0xF) << 8); +} + +static void psr_unpack(Emu *e, uint32_t v) +{ + e->f_n = v & 1; + e->f_z = (v >> 1) & 1; + e->f_v = (v >> 2) & 1; + e->f_c = (v >> 3) & 1; + e->f_ie = (v >> 4) & 1; + e->il = (v >> 8) & 0xF; + e->psr_rest = v; +} + +static void push32(Emu *e, uint32_t v) +{ + e->sp -= 4; + wr32(e, e->sp, v); +} + +static uint32_t pop32(Emu *e) +{ + uint32_t v = rd32(e, e->sp); + e->sp += 4; + return v; +} + +static void stop(Emu *e, uint32_t iaddr, const char *why, uint32_t detail) +{ + (void)why; + e->stopped = true; e->stop_pc = iaddr; e->stop_code = detail; +} + +/* Trap instruction fetches outside ROM and RAM. Unmapped reads return zero, + * which otherwise turns a wild jump into an endless stream of valid NOPs. */ +static int pc_mapped(Emu *e, uint32_t a) +{ + const DeviceProfile *d = &e->dev; + return a - d->rom_base < d->rom_size || a - d->a0ram_base < d->a0ram_size || + a - d->ivram_base < d->ivram_size || a - d->dstram_base < d->dstram_size; +} + +#define trace_call(e,t,f) ((void)0) +#define trace_jump(e,t,f) ((void)0) +#define trace_ret(e,t) ((void)0) + +static void bad_pc(Emu *e) +{ + stop(e, e->pc, "fetch from unmapped memory", e->pc); +} + +/* special register file for class 5 moves: sd=(0,3) / ss=(4,7) index */ +static uint32_t sreg_read(Emu *e, int idx, uint32_t iaddr) +{ + switch (idx) { + case 0: return psr_pack(e); + case 1: return e->sp; + case 2: return e->alr; + case 3: return e->ahr; + case 8: return e->ttbr; + case 10: return e->idir; + case 11: return e->dbbr; + case 15: return iaddr; + default: stop(e, iaddr, "read of invalid special reg", idx); return 0; + } +} + +static void sreg_write(Emu *e, int idx, uint32_t v, uint32_t iaddr) +{ + switch (idx) { + case 0: psr_unpack(e, v); break; + case 1: e->sp = v; break; + case 2: e->alr = v; break; + case 3: e->ahr = v; break; + case 8: e->ttbr = v; break; + case 10: e->idir = v; break; + case 11: e->dbbr = v; break; + case 15: e->pc = v; break; /* ld.w %pc,%rs acts as a jump */ + default: stop(e, iaddr, "write of invalid special reg", idx); break; + } +} + +/* conditional branch predicates, c0_op1 4..13 */ +static int cond_true(Emu *e, int op) +{ + switch (op) { + case 4: return !e->f_z && e->f_n == e->f_v; /* jrgt */ + case 5: return e->f_n == e->f_v; /* jrge */ + case 6: return e->f_n != e->f_v; /* jrlt */ + case 7: return e->f_z || e->f_n != e->f_v; /* jrle */ + case 8: return !e->f_z && !e->f_c; /* jrugt */ + case 9: return !e->f_c; /* jruge */ + case 10: return e->f_c; /* jrult */ + case 11: return e->f_z || e->f_c; /* jrule */ + case 12: return e->f_z; /* jreq */ + case 13: return !e->f_z; /* jrne */ + default: return 1; /* call/jp */ + } +} + +static void exec_insn(Emu *e, uint16_t hw, uint32_t iaddr, int in_slot); + +/* execute exactly one instruction (ext prefixes folded) at e->pc; no irq check */ +static void step_one(Emu *e, int in_slot) +{ + e->pc &= 0x0FFFFFFFu; /* 28-bit address bus */ + if (e->pc - e->fw_lo >= e->fw_len) { + if (!pc_mapped(e, e->pc)) { bad_pc(e); return; } + tc_fetch_window(e, e->pc); + } + uint16_t hw = e->fw_len ? *(const uint16_t *)(e->fw_ptr + (e->pc - e->fw_lo)) : rd16(e, e->pc); + int guard = 0; + while ((hw >> 13) == 6) { /* class 6 = ext prefix */ + if (in_slot && guard == 0) + ((void)0); + if (e->ext_count < 2) e->ext_val[e->ext_count] = hw & 0x1FFF; + e->ext_count++; + e->pc += 2; e->cycles++; + hw = (e->pc - e->fw_lo < e->fw_len) ? *(const uint16_t *)(e->fw_ptr + (e->pc - e->fw_lo)) : rd16(e, e->pc); + if (++guard > 2) { stop(e, e->pc, "more than two ext prefixes", hw); return; } + } + uint32_t iaddr = e->pc; + e->pc += 2; e->cycles++; + exec_insn(e, hw, iaddr, in_slot); +} + +/* run the delay slot of a .d instruction */ +static void run_slot(Emu *e) +{ + if (e->stopped) return; + step_one(e, 1); +} + +static void exec_insn(Emu *e, uint16_t hw, uint32_t iaddr, int in_slot) +{ + int cls = hw >> 13; + int rd = hw & 0xF, rs = (hw >> 4) & 0xF; + int ext_n = e->ext_count > 2 ? 2 : e->ext_count; + uint32_t ext0 = e->ext_val[0], ext1 = e->ext_val[1]; + e->ext_count = 0; + + switch (cls) { + + case 0: { + int op1 = (hw >> 9) & 0xF, d = (hw >> 8) & 1; + if (op1 <= 3) { + int cnst = (hw >> 4) & 3; + if (cnst == 0) { + int op2 = (hw >> 6) & 3; + switch (op1 * 8 + d * 4 + op2) { + case 0: /* nop */ break; + case 1: /* slp */ { + const int force_wake = 0; + e->halted = true; + /* OSC-stabilization auto-wake only when the CMU Clock Option + * register is armed for it (boot/PLL flow writes 0x3E00 before + * slp). A normal idle slp sleeps until a real interrupt. */ + e->halt_hard = !(e->cmu.opt & 0x3E00) && !force_wake; + e->wake_at = e->cycles + 20000; + break; } + case 2: /* halt */ e->halted = true; e->halt_hard = true; break; + case 8: { /* pushn rd */ for (int i = rd; i >= 0; i--) push32(e, e->r[i]); break; } + case 9: { /* popn rd */ for (int i = 0; i <= rd; i++) e->r[i] = pop32(e); break; } + case 11: /* jpr rd */ e->pc = iaddr + e->r[rd]; + trace_jump(e, e->pc, iaddr); break; + case 15: { /* jpr.d */ uint32_t t = iaddr + e->r[rd]; run_slot(e); e->pc = t; + trace_jump(e, t, iaddr); break; } + case 16: /* brk */ stop(e, iaddr, "brk", 0); break; + case 17: /* retd */ stop(e, iaddr, "retd (debug) unsupported", 0); break; + case 18: { /* int imm2 */ + uint32_t vec = 12 + (hw & 3); /* software exceptions int0-3 */ + ((void)0); + push32(e, e->pc); + push32(e, psr_pack(e)); + e->f_ie = 0; + e->pc = rd32(e, e->ttbr + vec * 4); + break; } + case 19: { /* reti */ psr_unpack(e, pop32(e)); e->pc = pop32(e); + trace_ret(e, e->pc); break; } + case 24: /* call rd */ push32(e, e->pc); trace_call(e, e->r[rd], iaddr); + e->pc = e->r[rd]; break; + case 25: /* ret */ e->pc = pop32(e); trace_ret(e, e->pc); break; + case 26: /* jp rd */ e->pc = e->r[rd]; trace_jump(e, e->pc, iaddr); break; + case 28: { /* call.d rd */ uint32_t t = e->r[rd]; run_slot(e); push32(e, e->pc); + trace_call(e, t, iaddr); e->pc = t; break; } + case 29: { /* ret.d */ run_slot(e); e->pc = pop32(e); trace_ret(e, e->pc); break; } + case 30: { /* jp.d rd */ uint32_t t = e->r[rd]; run_slot(e); e->pc = t; + trace_jump(e, t, iaddr); break; } + default: stop(e, iaddr, "bad class0 group", hw); break; + } + } else if (cnst == 1 && op1 == 0) { + int op2 = (hw >> 6) & 7; + switch (op2) { + case 0: push32(e, e->r[rd]); break; + case 1: e->r[rd] = pop32(e); break; + case 2: /* pushs */ + if ((hw & 0xF) == 2) push32(e, e->alr); + else if ((hw & 0xF) == 3) { push32(e, e->ahr); push32(e, e->alr); } + else stop(e, iaddr, "pushs bad sx", hw); + break; + case 3: /* pops */ + if ((hw & 0xF) == 2) e->alr = pop32(e); + else if ((hw & 0xF) == 3) { e->alr = pop32(e); e->ahr = pop32(e); } + else stop(e, iaddr, "pops bad sx", hw); + break; + case 7: /* ld.cf: coprocessor flags - none present */ + e->f_n = e->f_z = e->f_v = e->f_c = 0; break; + default: stop(e, iaddr, "bad class0 const1", hw); break; + } + } else stop(e, iaddr, "bad class0 encoding", hw); + } else { + /* rel8 branches, c0_op1 4..15 */ + uint32_t u8 = hw & 0xFF; + uint32_t target; + if (ext_n == 0) target = iaddr + sext(u8, 8) * 2; + else if (ext_n == 1) target = iaddr + ((sext(ext0, 13) << 9) | (u8 << 1)); + else target = iaddr + (((ext0 & 0x1ff8) << 19) | (ext1 << 9) | (u8 << 1)); + int taken = cond_true(e, op1); + if (in_slot) { ((void)0); return; } + if (op1 == 14) { /* call / call.d */ + if (d) { run_slot(e); push32(e, e->pc); trace_call(e, target, iaddr); e->pc = target; } + else { push32(e, e->pc); trace_call(e, target, iaddr); e->pc = target; } + } else if (op1 == 15) { /* jp / jp.d */ + if (d) { run_slot(e); } + e->pc = target; + } else { /* conditional */ + if (d) { run_slot(e); } + if (taken) e->pc = target; + } + break; + } + break; + } + + case 1: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + if (op2 == 3) { /* shifts by DoubleImm5 = imm4+16 */ + uint32_t n = ((hw >> 4) & 0xF) + 16; + switch (op1) { + case 0: e->r[rd] = srl_op(e, e->r[rd], n); break; + case 1: e->r[rd] = sl_op (e, e->r[rd], n); break; + case 2: e->r[rd] = sra_op(e, e->r[rd], n); break; + case 3: e->r[rd] = sl_op (e, e->r[rd], n); break; /* sla */ + case 4: e->r[rd] = rr_op (e, e->r[rd], n); break; + case 5: e->r[rd] = rl_op (e, e->r[rd], n); break; + default: stop(e, iaddr, "bad class1 shift", hw); break; + } + break; + } + if (op2 == 2) { /* reg-reg ALU; with ext -> rd = rs OP imm */ + uint32_t imm = (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1); + switch (op1) { + case 0: e->r[rd] = ext_n ? add_op(e, e->r[rs], imm) : add_op(e, e->r[rd], e->r[rs]); break; + case 1: e->r[rd] = ext_n ? sub_op(e, e->r[rs], imm) : sub_op(e, e->r[rd], e->r[rs]); break; + case 2: if (ext_n) cmp_op(e, e->r[rs], imm); else cmp_op(e, e->r[rd], e->r[rs]); break; + case 3: if (ext_n) { stop(e, iaddr, "ext on ld.w rd,rs", hw); break; } + e->r[rd] = e->r[rs]; break; + case 4: e->r[rd] = ext_n ? log_flags(e, e->r[rs] & imm) : log_flags(e, e->r[rd] & e->r[rs]); break; + case 5: e->r[rd] = ext_n ? log_flags(e, e->r[rs] | imm) : log_flags(e, e->r[rd] | e->r[rs]); break; + case 6: e->r[rd] = ext_n ? log_flags(e, e->r[rs] ^ imm) : log_flags(e, e->r[rd] ^ e->r[rs]); break; + case 7: if (ext_n) { stop(e, iaddr, "ext on not rd,rs", hw); break; } + e->r[rd] = log_flags(e, ~e->r[rs]); break; + } + break; + } + /* op2 0/1: memory ops. ext (op2==0 only) -> [rs+imm], no post-inc */ + { + uint32_t addr = e->r[rs]; + int postinc = (op2 == 1); + if (ext_n) { + if (postinc) { stop(e, iaddr, "ext on post-inc load", hw); break; } + addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1); + } + switch (op1) { + case 0: e->r[rd] = sext(rd8(e, addr), 8); if (postinc) e->r[rs] += 1; break; + case 1: e->r[rd] = rd8(e, addr); if (postinc) e->r[rs] += 1; break; + case 2: e->r[rd] = sext(rd16(e, addr), 16); if (postinc) e->r[rs] += 2; break; + case 3: e->r[rd] = rd16(e, addr); if (postinc) e->r[rs] += 2; break; + case 4: e->r[rd] = rd32(e, addr); if (postinc) e->r[rs] += 4; break; + case 5: mem_write8 (e, addr, (uint8_t)e->r[rd]); if (postinc) e->r[rs] += 1; break; + case 6: wr16(e, addr, (uint16_t)e->r[rd]); if (postinc) e->r[rs] += 2; break; + case 7: wr32(e, addr, e->r[rd]); if (postinc) e->r[rs] += 4; break; + } + break; + } + } + + case 2: { /* SP-relative; base form scales by size, ext form does not */ + int op1 = (hw >> 10) & 7; + uint32_t imm6 = (hw >> 4) & 0x3F; + uint32_t off; + if (ext_n == 0) { + static const uint8_t scale[8] = {1,1,2,2,4,1,2,4}; + off = imm6 * scale[op1]; + } else if (ext_n == 1) off = (ext0 << 6) | imm6; + else off = (ext0 << 19) | (ext1 << 6) | imm6; + uint32_t addr = e->sp + off; + switch (op1) { + case 0: e->r[rd] = sext(rd8(e, addr), 8); break; + case 1: e->r[rd] = rd8(e, addr); break; + case 2: e->r[rd] = sext(rd16(e, addr), 16); break; + case 3: e->r[rd] = rd16(e, addr); break; + case 4: e->r[rd] = rd32(e, addr); break; + case 5: mem_write8 (e, addr, (uint8_t)e->r[rd]); break; + case 6: wr16(e, addr, (uint16_t)e->r[rd]); break; + case 7: wr32(e, addr, e->r[rd]); break; + } + break; + } + + case 3: { /* imm6 ALU */ + int op1 = (hw >> 10) & 7; + uint32_t imm6 = (hw >> 4) & 0x3F; + uint32_t imm; + if (ext_n == 0) + imm = (op1 == 0 || op1 == 1) ? imm6 : sext(imm6, 6); + else if (ext_n == 1) { + imm = (ext0 << 6) | imm6; + if (!(op1 == 0 || op1 == 1)) imm = sext(imm, 19); + } else + imm = (ext0 << 19) | (ext1 << 6) | imm6; + switch (op1) { + case 0: e->r[rd] = add_op(e, e->r[rd], imm); break; + case 1: e->r[rd] = sub_op(e, e->r[rd], imm); break; + case 2: cmp_op(e, e->r[rd], imm); break; + case 3: e->r[rd] = imm; break; /* ld.w / xld.w imm */ + case 4: e->r[rd] = log_flags(e, e->r[rd] & imm); break; + case 5: e->r[rd] = log_flags(e, e->r[rd] | imm); break; + case 6: e->r[rd] = log_flags(e, e->r[rd] ^ imm); break; + case 7: e->r[rd] = log_flags(e, ~imm); break; + } + break; + } + + case 4: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + uint32_t imm4 = (hw >> 4) & 0xF; + if (op1 == 0) { e->sp += (uint32_t)(hw & 0x3FF) * 4; break; } + if (op1 == 1) { e->sp -= (uint32_t)(hw & 0x3FF) * 4; break; } + uint32_t amt = (op2 == 0) ? imm4 : e->r[rs]; + switch (op1) { + case 2: e->r[rd] = srl_op(e, e->r[rd], amt); break; + case 3: e->r[rd] = sl_op (e, e->r[rd], amt); break; + case 4: + if (op2 == 2) { uint32_t v = e->r[rs]; + e->r[rd] = (v << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | (v >> 24); } + else e->r[rd] = sra_op(e, e->r[rd], amt); + break; + case 5: e->r[rd] = sl_op(e, e->r[rd], amt); break; /* sla */ + case 6: + if (op2 == 2) { uint32_t v = e->r[rs]; /* swaph */ + e->r[rd] = ((v & 0x00FF0000) << 8) | ((v >> 8) & 0x00FF0000) | + ((v & 0x000000FF) << 8) | ((v >> 8) & 0x000000FF); } + else e->r[rd] = rr_op(e, e->r[rd], amt); + break; + case 7: e->r[rd] = rl_op(e, e->r[rd], amt); break; + } + break; + } + + case 5: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + switch (op1 * 4 + op2) { + case 0*4+0: sreg_write(e, hw & 0xF, e->r[rs], iaddr); break; /* ld.w %sd,%rs */ + case 0*4+1: e->r[rd] = sext(e->r[rs] & 0xFF, 8); break; /* ld.b rd,rs */ + case 0*4+2: e->alr = (uint32_t)((int32_t)sext(e->r[rd] & 0xFFFF, 16) * + (int32_t)sext(e->r[rs] & 0xFFFF, 16)); break; /* mlt.h */ + case 1*4+0: e->r[rd] = sreg_read(e, rs, iaddr); break; /* ld.w rd,%ss */ + case 1*4+1: e->r[rd] = e->r[rs] & 0xFF; break; /* ld.ub */ + case 1*4+2: e->alr = (e->r[rd] & 0xFFFF) * (e->r[rs] & 0xFFFF); break; /* mltu.h */ + case 2*4+0: case 3*4+0: case 4*4+0: case 5*4+0: { /* bit ops */ + uint32_t addr = e->r[rs]; + if (ext_n) addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1); + int pos = hw & 7; + uint8_t b = rd8(e, addr); + switch (op1) { + case 2: e->f_z = ((b >> pos) & 1) == 0; break; /* btst */ + case 3: wr8(e, addr, b & ~(1u << pos)); break; /* bclr */ + case 4: wr8(e, addr, b | (1u << pos)); break; /* bset */ + case 5: wr8(e, addr, b ^ (1u << pos)); break; /* bnot */ + } + break; } + case 2*4+1: e->r[rd] = sext(e->r[rs] & 0xFFFF, 16); break; /* ld.h */ + case 2*4+2: { int64_t p = (int64_t)(int32_t)e->r[rd] * (int32_t)e->r[rs]; + e->alr = (uint32_t)p; e->ahr = (uint32_t)((uint64_t)p >> 32); break; } /* mlt.w */ + case 3*4+1: e->r[rd] = e->r[rs] & 0xFFFF; break; /* ld.uh */ + case 3*4+2: { uint64_t p = (uint64_t)e->r[rd] * e->r[rs]; + e->alr = (uint32_t)p; e->ahr = (uint32_t)(p >> 32); break; } /* mltu.w */ + case 4*4+1: case 5*4+1: /* ld.c: coprocessor */ + ((void)0); break; + case 6*4+0: e->r[rd] = adc_op(e, e->r[rd], e->r[rs]); break; + case 7*4+0: e->r[rd] = sbc_op(e, e->r[rd], e->r[rs]); break; + case 7*4+3: { /* class 5 (2): do.c / psrset / psrclr */ + int op3 = (hw >> 6) & 3, imm5 = hw & 0x1F; + if (op3 == 0) { ((void)0); break; } + if (op3 == 1 || op3 == 2) { + int val = (op3 == 1); + switch (imm5) { + case 0: e->f_n = val; break; + case 1: e->f_z = val; break; + case 2: e->f_v = val; break; + case 3: e->f_c = val; break; + case 4: e->f_ie = val; break; + default: ((void)0); break; + } + break; + } + stop(e, iaddr, "bad class5(2)", hw); break; } + default: stop(e, iaddr, "bad class5 encoding", hw); break; + } + break; + } + + default: + stop(e, iaddr, "unreachable class", hw); + break; + } + (void)in_slot; +} + +void cpu_reset(Emu *e) +{ + memset(e->r, 0, sizeof e->r); + e->sp = 0; e->alr = e->ahr = 0; + e->ttbr = e->dev.ttbr_reset; + e->idir = e->dbbr = 0; + e->f_n = e->f_z = e->f_v = e->f_c = e->f_ie = 0; + e->il = 0; e->psr_rest = 0; + e->ext_count = 0; + e->halted = false; e->halt_hard = false; + e->stopped = false; + e->pc = rd32(e, e->ttbr); /* reset vector */ +} + +void cpu_step(Emu *e) +{ + if (e->stopped) return; + if (e->halted) { + e->cycles += 16; + if (e->pending_irq || e->wake_req || (!e->halt_hard && e->cycles >= e->wake_at)) { + e->halted = false; + } else + return; + } + /* interrupt accept point (never between ext and target: ext consumed inside step_one) */ + if (e->pending_irq && e->f_ie && e->pending_level > e->il) { + uint32_t vec = e->pending_irq; + push32(e, e->pc); + push32(e, psr_pack(e)); + e->f_ie = 0; + e->il = e->pending_level; + e->pc = rd32(e, e->ttbr + vec * 4); + e->pending_irq = 0; + } + step_one(e, 0); +} diff --git a/emu/src/core/tc_fast.c b/emu/src/core/tc_fast.c new file mode 100644 index 0000000..ff8c0f6 --- /dev/null +++ b/emu/src/core/tc_fast.c @@ -0,0 +1,500 @@ +/* Fast interpreter for S1C33 (same semantics as tc_cpu.c, which is derived + * from tamaemu cpu.c). Hot state lives in local variables so the compiler + * keeps it in registers. Verified by lockstep runs against tc_cpu.c. */ +#include "tc.h" +#ifdef ROMSTAT +__attribute__((section(".stats"), used)) volatile uint32_t tc_rom_hits[128]; /* stats build: reads per 64 KB guest block */ +#define ROMHIT(o) (tc_rom_hits[((o) >> 16) & 127]++) +#else +#define ROMHIT(o) ((void)0) +#endif + +#define SEXT(v, bits) ((uint32_t)(((uint32_t)(v) ^ (1u << ((bits) - 1))) - (1u << ((bits) - 1)))) + +static inline uint8_t *f_ramp(Emu *e, uint32_t a, uint32_t n) +{ + if (a <= A0RAM_MAX - n) return e->a0ram + a; + uint32_t o = a - 0x80000u; + if (o <= IVRAM_MAX - n) return e->ivram + o; + o = a - 0x84000u; + if (o <= DSTRAM_MAX - n) return e->dstram + o; + return 0; +} +#ifdef TC_JIT +/* Write to RAM that has already been translated: discard all translations */ +#ifdef JIT_WHOT +/* v0.9.6: a0ram pages whose code keeps getting overwritten (iD L, Connect to Plus Color: code at 0xC00 + * next to its data) are no longer translated. Before, every write threw away all translations, thousands + * of times per second, and the emulator stood still on the device. */ +uint8_t jit_wcnt[128], jit_nojit[128]; +uint64_t jit_wwin, jit_nojit_at; +#define JIT_WWIN 2000000u /* window for counting (about 0.1 s of guest time) */ +#define JIT_NOJIT 100000000u /* after about 5 s the pages get another chance */ +static void jit_cw_note(Emu *e, uint32_t a, uint32_t n) +{ + if (e->cycles - jit_wwin > JIT_WWIN) { memset(jit_wcnt, 0, sizeof jit_wcnt); jit_wwin = e->cycles; } + for (uint32_t p = a >> 8; p <= ((a + n - 1) >> 8) && p < 128u; p++) + if (e->jit_map[p] && ++jit_wcnt[p] >= 8u) { jit_nojit[p] = 1; jit_wcnt[p] = 0; jit_nojit_at = e->cycles; } +} +static int jit_nojit_pc(Emu *e, uint32_t pc) +{ + if (!jit_nojit[pc >> 8]) return 0; + if (e->cycles - jit_nojit_at > JIT_NOJIT) { memset(jit_nojit, 0, sizeof jit_nojit); return 0; } + return 1; +} +#else +#define jit_cw_note(e, a, n) ((void)0) +#endif +__attribute__((noinline)) static void jit_cw_chk(Emu *e, uint32_t a, uint32_t n) +{ + if (e->jit_map[a >> 8] | e->jit_map[(a + n - 1) >> 8]) { jit_cw_note(e, a, n); e->jit_flush = 1; memset(e->jit_map, 0, sizeof e->jit_map); } +} +#endif +#ifdef TC_STATS +void stat_acc(uint32_t a, int w); +#define FST(a, w) stat_acc((a), (w)) +#else +#define FST(a, w) ((void)0) +#endif +static inline uint32_t f_rd8(Emu *e, uint32_t a) +{ + FST(a, 0); + uint8_t *p = f_ramp(e, a, 1); if (p) return *p; + uint32_t o = a - e->dev.rom_base; + if (o < e->dev.rom_size && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) return b[o & 0xFFFFu]; } + return mem_read8(e, a); +} +static inline uint32_t f_rd16(Emu *e, uint32_t a) +{ + FST(a, 0); + uint8_t *p = f_ramp(e, a, 2); if (p) return (uint32_t)(p[0] | (p[1] << 8)); + uint32_t o = a - e->dev.rom_base; + if (o < e->dev.rom_size && (o & 0xFFFFu) <= 0xFFFEu && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) { const uint8_t *q = b + (o & 0xFFFFu); return (uint32_t)(q[0] | (q[1] << 8)); } } + return mem_read16(e, a); +} +static inline uint32_t f_rd32(Emu *e, uint32_t a) +{ + FST(a, 0); + uint8_t *p = f_ramp(e, a, 4); if (p) return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + uint32_t o = a - e->dev.rom_base; + if (o < e->dev.rom_size && (o & 0xFFFFu) <= 0xFFFCu && !e->flash_busy && !e->flash_autoselect) { ROMHIT(o); const uint8_t *b = e->rom_blk[o >> 16]; if (b) { const uint8_t *q = b + (o & 0xFFFFu); return (uint32_t)q[0] | ((uint32_t)q[1] << 8) | ((uint32_t)q[2] << 16) | ((uint32_t)q[3] << 24); } } + return mem_read32(e, a); +} +static inline void f_wr8(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 1); if (p) *p = (uint8_t)v; else mem_write8(e, a, (uint8_t)v); } +static inline void f_wr16(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 2); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); } else mem_write16(e, a, (uint16_t)v); } +static inline void f_wr32(Emu *e, uint32_t a, uint32_t v) { uint8_t *p = f_ramp(e, a, 4); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); } else mem_write32(e, a, v); } + +/* Flags in one word: bit3 N, bit2 Z, bit1 V, bit0 C */ +#define FN (fl >> 3 & 1) +#define FZ (fl >> 2 & 1) +#define FV (fl >> 1 & 1) +#define FC (fl & 1) +#define NZ(r) do { uint32_t _r = (r); fl = (fl & 3u) | ((_r >> 31) << 3) | ((uint32_t)(_r == 0) << 2); } while (0) +#define SCARRY(a, b) ((((~((a) ^ (b))) & ((a) ^ ((a) + (b)))) >> 31)) +#define SBORROW(a, b) (((((a) ^ (b)) & ((a) ^ ((a) - (b)))) >> 31)) +#define PUSH(v) do { sp -= 4; WR32(sp, (v)); } while (0) +#define POP() (sp += 4, f_rd32(e, sp - 4)) +#define PSR_PACK() ((e->psr_rest & ~0xF1Fu) | FN | (FZ << 1) | (FV << 2) | (FC << 3) | ((uint32_t)e->f_ie << 4) | ((uint32_t)(e->il & 0xF) << 8)) +#define PSR_UNPACK(v) do { uint32_t _v = (v); fl = ((_v & 1) << 3) | (((_v >> 1) & 1) << 2) | (((_v >> 2) & 1) << 1) | ((_v >> 3) & 1); \ + e->f_ie = (_v >> 4) & 1; e->il = (_v >> 8) & 0xF; e->psr_rest = _v; chk = 1; } while (0) + +static inline uint32_t op_add(uint32_t a, uint32_t b, uint32_t *fl) +{ uint32_t r = a + b; *fl = ((r >> 31) << 3) | ((uint32_t)(r == 0) << 2) | (SCARRY(a, b) << 1) | (uint32_t)(r < a); return r; } +static inline uint32_t op_sub(uint32_t a, uint32_t b, uint32_t *fl) +{ uint32_t r = a - b; *fl = ((r >> 31) << 3) | ((uint32_t)(r == 0) << 2) | (SBORROW(a, b) << 1) | (uint32_t)(a < b); return r; } +#define ADD(a, b) op_add((a), (b), &fl) +#define SUB(a, b) op_sub((a), (b), &fl) +#define CMP(a, b) ((void)op_sub((a), (b), &fl)) +#define LOG(r) ({ uint32_t _q = (r); fl = (fl & 1u) | ((_q >> 31) << 3) | ((uint32_t)(_q == 0) << 2); _q; }) + +/* Deferred jump effect after the delay slot */ +enum { D_NONE, D_JP, D_CALL, D_RET }; + +static inline int cond_ok(int op, uint32_t fl) +{ + uint32_t fn = fl >> 3 & 1, fz = fl >> 2 & 1, fv = fl >> 1 & 1, fc = fl & 1; + switch (op) { + case 4: return !fz && fn == fv; + case 5: return fn == fv; + case 6: return fn != fv; + case 7: return fz || fn != fv; + case 8: return !fz && !fc; + case 9: return !fc; + case 10: return fc; + case 11: return fz || fc; + case 12: return fz; + case 13: return !fz; + default: return 1; + } +} + +static int pc_ok(Emu *e, uint32_t a) +{ + const DeviceProfile *d = &e->dev; + return a - d->rom_base < d->rom_size || a - d->a0ram_base < d->a0ram_size || + a - d->ivram_base < d->ivram_size || a - d->dstram_base < d->dstram_size; +} + +/* Runs until cycles >= ziel (target), or the CPU sleeps or stops. Peripherals + * are ticked every TICK cycles. */ +#define TICK 256 +__attribute__((minsize)) void tc_exec(Emu *e, uint64_t ziel) +{ + uint32_t pc = e->pc, sp = e->sp; + uint32_t fl = ((uint32_t)e->f_n << 3) | ((uint32_t)e->f_z << 2) | ((uint32_t)e->f_v << 1) | e->f_c; + int32_t left; +#define CYC() (e->evt - (uint64_t)(int64_t)left) +#define r (e->r) + const uint8_t *fwp = e->fw_ptr; uint32_t fwlo = e->fw_lo, fwlen = e->fw_len; + int slot = 0; +#define dkind (e->ext_count) +#define dtarget (e->ext_val[0]) + dkind = D_NONE; + +#define SYNC_OUT() do { e->pc = pc; e->sp = sp; e->f_n = FN; e->f_z = FZ; e->f_v = FV; e->f_c = FC; e->cycles = CYC(); } while (0) +#define SYNC_IN() do { pc = e->pc; sp = e->sp; fl = ((uint32_t)e->f_n << 3) | ((uint32_t)e->f_z << 2) | ((uint32_t)e->f_v << 1) | e->f_c; left = (int32_t)(e->evt - e->cycles); \ + fwp = e->fw_ptr; fwlo = e->fw_lo; fwlen = e->fw_len; } while (0) + +/* Write to RAM that has already been translated: discard all translations */ +#ifdef TC_JIT +#define JCW(a, n) do { if ((a) <= A0RAM_MAX - (n)) jit_cw_chk(e, (a), (n)); } while (0) +#else +#define JCW(a, n) ((void)0) +#endif +#define WR8(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 1); if (_p) { *_p = (uint8_t)_v; JCW(_a, 1); } \ + else { SYNC_OUT(); mem_write8(e, _a, (uint8_t)_v); SYNC_IN(); chk = 1; } } while (0) +#define WR16(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 2); if (_p) { _p[0] = (uint8_t)_v; _p[1] = (uint8_t)(_v >> 8); JCW(_a, 2); } \ + else { SYNC_OUT(); mem_write16(e, _a, (uint16_t)_v); SYNC_IN(); chk = 1; } } while (0) +#define WR32(a, v) do { uint32_t _a = (a), _v = (v); uint8_t *_p = f_ramp(e, _a, 4); if (_p) { _p[0] = (uint8_t)_v; _p[1] = (uint8_t)(_v >> 8); _p[2] = (uint8_t)(_v >> 16); _p[3] = (uint8_t)(_v >> 24); JCW(_a, 4); } \ + else { SYNC_OUT(); mem_write32(e, _a, _v); SYNC_IN(); chk = 1; } } while (0) + +#define NEXT_EVT(c) do { uint64_t _n = (e->last_tick + TICK < ziel) ? e->last_tick + TICK : ziel; e->evt = _n; left = (int32_t)(_n - (c)); } while (0) +#define FORCE_EVT() do { uint64_t _c = CYC(); e->evt = _c; left = 0; } while (0) + NEXT_EVT(e->cycles); + int chk = 1; /* check for interrupts (after peripherals, I/O, PSR) */ + if (e->halted || e->stopped) goto out; + for (;;) { + int in_slot = slot; slot = 0; + if (!in_slot && chk) { + chk = 0; + if (e->pending_irq && e->f_ie && e->pending_level > e->il) { + uint32_t vec = e->pending_irq; + PUSH(pc); + PUSH(PSR_PACK()); + e->f_ie = 0; + e->il = e->pending_level; + pc = f_rd32(e, e->ttbr + vec * 4); + e->pending_irq = 0; + } + } + /* Fetch */ + if (pc - fwlo >= fwlen) { + pc &= 0x0FFFFFFFu; + if (!pc_ok(e, pc)) { e->stopped = true; FORCE_EVT(); e->stop_pc = pc; e->stop_code = pc; break; } + tc_fetch_window(e, pc); fwp = e->fw_ptr; fwlo = e->fw_lo; fwlen = e->fw_len; + } +#define FETCH(a) ((a) - fwlo < fwlen ? *(const uint16_t *)(fwp + ((a) - fwlo)) : (uint16_t)f_rd16(e, (a))) + uint32_t hw = FETCH(pc); + int ext_n = 0; uint32_t ext0 = 0, ext1 = 0; + while ((hw >> 13) == 6) { + if (ext_n == 0) ext0 = hw & 0x1FFF; else if (ext_n == 1) ext1 = hw & 0x1FFF; + ext_n++; + pc += 2; left--; + hw = FETCH(pc); + if (ext_n > 2) { e->stopped = true; FORCE_EVT(); e->stop_pc = pc; e->stop_code = hw; goto out; } + } + if (ext_n > 2) ext_n = 2; + uint32_t iaddr = pc; + pc += 2; left--; + int rd = hw & 0xF, rs = (hw >> 4) & 0xF; + + switch (hw >> 13) { + case 0: { + int op1 = (hw >> 9) & 0xF, d = (hw >> 8) & 1; + if (op1 <= 3) { + int cnst = (hw >> 4) & 3; + if (cnst == 0) { + int op2 = (hw >> 6) & 3; + switch (op1 * 8 + d * 4 + op2) { + case 0: break; + case 1: e->halted = true; e->halt_hard = !(e->cmu.opt & 0x3E00); e->wake_at = CYC() + 20000; FORCE_EVT(); break; + case 2: e->halted = true; e->halt_hard = true; FORCE_EVT(); break; + case 8: for (int i = rd; i >= 0; i--) PUSH(r[i]); break; + case 9: for (int i = 0; i <= rd; i++) r[i] = POP(); break; + case 11: pc = iaddr + r[rd]; break; + case 15: dkind = D_JP; dtarget = iaddr + r[rd]; slot = 1; break; + case 16: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; + case 17: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; + case 18: { uint32_t vec = 12 + (hw & 3); + PUSH(pc); PUSH(PSR_PACK()); e->f_ie = 0; + pc = f_rd32(e, e->ttbr + vec * 4); break; } + case 19: { PSR_UNPACK(POP()); pc = POP(); break; } + case 24: { uint32_t t = r[rd]; PUSH(pc); pc = t; break; } + case 25: pc = POP(); break; + case 26: pc = r[rd]; break; + case 28: dkind = D_CALL; dtarget = r[rd]; slot = 1; break; + case 29: dkind = D_RET; slot = 1; break; + case 30: dkind = D_JP; dtarget = r[rd]; slot = 1; break; + default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break; + } + } else if (cnst == 1 && op1 == 0) { + switch ((hw >> 6) & 7) { + case 0: PUSH(r[rd]); break; + case 1: r[rd] = POP(); break; + case 2: if ((hw & 0xF) == 2) PUSH(e->alr); + else if ((hw & 0xF) == 3) { PUSH(e->ahr); PUSH(e->alr); } + else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; } break; + case 3: if ((hw & 0xF) == 2) e->alr = POP(); + else if ((hw & 0xF) == 3) { e->alr = POP(); e->ahr = POP(); } + else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; } break; + case 7: fl = 0; break; + default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break; + } + } else { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; } + } else { + uint32_t u8 = hw & 0xFF, target; + if (ext_n == 0) target = iaddr + SEXT(u8, 8) * 2; + else if (ext_n == 1) target = iaddr + ((SEXT(ext0, 13) << 9) | (u8 << 1)); + else target = iaddr + (((ext0 & 0x1ff8) << 19) | (ext1 << 9) | (u8 << 1)); + if (in_slot) break; /* branch in a delay slot: ignored, like the original */ + if (op1 == 14) { + if (d) { dkind = D_CALL; dtarget = target; slot = 1; } + else { PUSH(pc); pc = target; } + } else if (op1 == 15) { + if (d) { dkind = D_JP; dtarget = target; slot = 1; } else pc = target; + } else { + int taken = cond_ok(op1, fl); + if (d) { dkind = taken ? D_JP : D_NONE; dtarget = target; slot = 1; } + else if (taken) pc = target; + } + } + break; + } + case 1: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + if (op2 == 3) { + uint32_t n = ((hw >> 4) & 0xF) + 16, a = r[rd], q; + switch (op1) { + case 0: q = a >> n; break; + case 1: case 3: q = a << n; break; + case 2: q = (uint32_t)((int32_t)a >> n); break; + case 4: q = (a >> n) | (a << (32 - n)); break; + case 5: q = (a << n) | (a >> (32 - n)); break; + default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; q = a; break; + } + r[rd] = q; NZ(q); + break; + } + if (op2 == 2) { + uint32_t imm = (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1); + switch (op1) { + case 0: r[rd] = ext_n ? ADD(r[rs], imm) : ADD(r[rd], r[rs]); break; + case 1: r[rd] = ext_n ? SUB(r[rs], imm) : SUB(r[rd], r[rs]); break; + case 2: if (ext_n) CMP(r[rs], imm); else CMP(r[rd], r[rs]); break; + case 3: if (ext_n) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } r[rd] = r[rs]; break; + case 4: r[rd] = ext_n ? LOG(r[rs] & imm) : LOG(r[rd] & r[rs]); break; + case 5: r[rd] = ext_n ? LOG(r[rs] | imm) : LOG(r[rd] | r[rs]); break; + case 6: r[rd] = ext_n ? LOG(r[rs] ^ imm) : LOG(r[rd] ^ r[rs]); break; + case 7: if (ext_n) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } r[rd] = LOG(~r[rs]); break; + } + break; + } + { + uint32_t addr = r[rs]; + int postinc = (op2 == 1); + if (ext_n) { + if (postinc) { e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } + addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1); + } + switch (op1) { + case 0: r[rd] = SEXT(f_rd8(e, addr), 8); if (postinc) r[rs] += 1; break; + case 1: r[rd] = f_rd8(e, addr); if (postinc) r[rs] += 1; break; + case 2: r[rd] = SEXT(f_rd16(e, addr), 16); if (postinc) r[rs] += 2; break; + case 3: r[rd] = f_rd16(e, addr); if (postinc) r[rs] += 2; break; + case 4: r[rd] = f_rd32(e, addr); if (postinc) r[rs] += 4; break; + case 5: WR8(addr, r[rd]); if (postinc) r[rs] += 1; break; + case 6: WR16(addr, r[rd]); if (postinc) r[rs] += 2; break; + case 7: WR32(addr, r[rd]); if (postinc) r[rs] += 4; break; + } + break; + } + } + case 2: { + int op1 = (hw >> 10) & 7; + uint32_t imm6 = (hw >> 4) & 0x3F, off; + if (ext_n == 0) { static const uint8_t scale[8] = {1,1,2,2,4,1,2,4}; off = imm6 * scale[op1]; } + else if (ext_n == 1) off = (ext0 << 6) | imm6; + else off = (ext0 << 19) | (ext1 << 6) | imm6; + uint32_t addr = sp + off; + switch (op1) { + case 0: r[rd] = SEXT(f_rd8(e, addr), 8); break; + case 1: r[rd] = f_rd8(e, addr); break; + case 2: r[rd] = SEXT(f_rd16(e, addr), 16); break; + case 3: r[rd] = f_rd16(e, addr); break; + case 4: r[rd] = f_rd32(e, addr); break; + case 5: WR8(addr, r[rd]); break; + case 6: WR16(addr, r[rd]); break; + case 7: WR32(addr, r[rd]); break; + } + break; + } + case 3: { + int op1 = (hw >> 10) & 7; + uint32_t imm6 = (hw >> 4) & 0x3F, imm; + if (ext_n == 0) imm = (op1 == 0 || op1 == 1) ? imm6 : SEXT(imm6, 6); + else if (ext_n == 1) { imm = (ext0 << 6) | imm6; if (!(op1 == 0 || op1 == 1)) imm = SEXT(imm, 19); } + else imm = (ext0 << 19) | (ext1 << 6) | imm6; + switch (op1) { + case 0: r[rd] = ADD(r[rd], imm); break; + case 1: r[rd] = SUB(r[rd], imm); break; + case 2: CMP(r[rd], imm); break; + case 3: r[rd] = imm; break; + case 4: r[rd] = LOG(r[rd] & imm); break; + case 5: r[rd] = LOG(r[rd] | imm); break; + case 6: r[rd] = LOG(r[rd] ^ imm); break; + case 7: r[rd] = LOG(~imm); break; + } + break; + } + case 4: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + if (op1 == 0) { sp += (uint32_t)(hw & 0x3FF) * 4; break; } + if (op1 == 1) { sp -= (uint32_t)(hw & 0x3FF) * 4; break; } + uint32_t amt = ((op2 == 0) ? ((hw >> 4) & 0xF) : r[rs]) & 31, a = r[rd], q; + switch (op1) { + case 2: q = a >> amt; r[rd] = q; NZ(q); break; + case 3: case 5: q = a << amt; r[rd] = q; NZ(q); break; + case 4: + if (op2 == 2) { uint32_t v = r[rs]; r[rd] = (v << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | (v >> 24); } + else { q = (uint32_t)((int32_t)a >> amt); r[rd] = q; NZ(q); } + break; + case 6: + if (op2 == 2) { uint32_t v = r[rs]; + r[rd] = ((v & 0x00FF0000) << 8) | ((v >> 8) & 0x00FF0000) | ((v & 0x000000FF) << 8) | ((v >> 8) & 0x000000FF); } + else { q = amt ? ((a >> amt) | (a << (32 - amt))) : a; r[rd] = q; NZ(q); } + break; + case 7: q = amt ? ((a << amt) | (a >> (32 - amt))) : a; r[rd] = q; NZ(q); break; + } + break; + } + case 5: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + switch (op1 * 4 + op2) { + case 0: { uint32_t v = r[rs]; + switch (hw & 0xF) { + case 0: PSR_UNPACK(v); break; + case 1: sp = v; break; + case 2: e->alr = v; break; + case 3: e->ahr = v; break; + case 8: e->ttbr = v; break; + case 10: e->idir = v; break; + case 11: e->dbbr = v; break; + case 15: pc = v; break; + default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; + } break; } + case 1: r[rd] = SEXT(r[rs] & 0xFF, 8); break; + case 2: e->alr = (uint32_t)((int32_t)SEXT(r[rd] & 0xFFFF, 16) * (int32_t)SEXT(r[rs] & 0xFFFF, 16)); break; + case 4: { + uint32_t v; + switch (rs) { + case 0: v = PSR_PACK(); break; + case 1: v = sp; break; + case 2: v = e->alr; break; + case 3: v = e->ahr; break; + case 8: v = e->ttbr; break; + case 10: v = e->idir; break; + case 11: v = e->dbbr; break; + case 15: v = iaddr; break; + default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; v = 0; break; + } + r[rd] = v; break; } + case 5: r[rd] = r[rs] & 0xFF; break; + case 6: e->alr = (r[rd] & 0xFFFF) * (r[rs] & 0xFFFF); break; + case 8: case 12: case 16: case 20: { + uint32_t addr = r[rs]; + if (ext_n) addr += (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1); + int pos = hw & 7; + uint32_t b = f_rd8(e, addr); + switch (op1) { + case 2: fl = (fl & ~4u) | ((uint32_t)(((b >> pos) & 1) == 0) << 2); break; + case 3: WR8(addr, b & ~(1u << pos)); break; + case 4: WR8(addr, b | (1u << pos)); break; + case 5: WR8(addr, b ^ (1u << pos)); break; + } + break; } + case 9: r[rd] = SEXT(r[rs] & 0xFFFF, 16); break; + case 10: { int64_t p = (int64_t)(int32_t)r[rd] * (int32_t)r[rs]; + e->alr = (uint32_t)p; e->ahr = (uint32_t)((uint64_t)p >> 32); break; } + case 13: r[rd] = r[rs] & 0xFFFF; break; + case 14: { uint64_t p = (uint64_t)r[rd] * r[rs]; e->alr = (uint32_t)p; e->ahr = (uint32_t)(p >> 32); break; } + case 17: case 21: break; + case 24: { uint32_t a = r[rd], b = r[rs], cz = FC, s = a + b; + uint32_t v = SCARRY(a, b) ^ SCARRY(s, cz), c = (s < a) || ((s + cz) < s); + uint32_t q = s + cz; fl = ((q >> 31) << 3) | ((uint32_t)(q == 0) << 2) | (v << 1) | c; r[rd] = q; break; } + case 28: { uint32_t a = r[rd], b = r[rs], cz = FC, dd = a - b; + uint32_t v = SBORROW(a, b) || SBORROW(dd, cz), c = (a < b) || (dd < cz); + uint32_t q = dd - cz; fl = ((q >> 31) << 3) | ((uint32_t)(q == 0) << 2) | (v << 1) | c; r[rd] = q; break; } + case 31: { + int op3 = (hw >> 6) & 3, imm5 = hw & 0x1F; + if (op3 == 0) break; + if (op3 == 1 || op3 == 2) { + int val = (op3 == 1); + switch (imm5) { + case 0: fl = (fl & ~8u) | ((uint32_t)val << 3); break; + case 1: fl = (fl & ~4u) | ((uint32_t)val << 2); break; + case 2: fl = (fl & ~2u) | ((uint32_t)val << 1); break; + case 3: fl = (fl & ~1u) | (uint32_t)val; break; + case 4: e->f_ie = val; chk = 1; break; + default: break; + } + break; + } + e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; break; } + default: e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break; + } + break; + } + default: + e->stopped = true; FORCE_EVT(); e->stop_pc = iaddr; e->stop_code = hw; break; + } + if (in_slot) { + int k = dkind; dkind = D_NONE; + if (k == D_JP) pc = dtarget; + else if (k == D_CALL) { PUSH(pc); pc = dtarget; } + else if (k == D_RET) pc = POP(); + } + if (left <= 0 && !slot) { + uint64_t cyc = CYC(); + if (e->halted || e->stopped) break; + if (cyc - e->last_tick >= TICK) { + SYNC_OUT(); + periph_tick(e, (uint32_t)(cyc - e->last_tick)); + e->last_tick = cyc; + SYNC_IN(); + chk = 1; + } + if (cyc >= ziel) break; + NEXT_EVT(cyc); + } + } +out: +#undef r + SYNC_OUT(); + e->fw_ptr = fwp; e->fw_lo = fwlo; e->fw_len = fwlen; +} + +#ifndef TC_WITH_REF +void cpu_reset(Emu *e) +{ + memset(e->r, 0, sizeof e->r); + e->sp = 0; e->alr = e->ahr = 0; + e->ttbr = e->dev.ttbr_reset; + e->idir = e->dbbr = 0; + e->f_n = e->f_z = e->f_v = e->f_c = e->f_ie = 0; + e->il = 0; e->psr_rest = 0; + e->ext_count = 0; + e->halted = false; e->halt_hard = false; + e->stopped = false; + e->pc = mem_read32(e, e->ttbr); +} +#endif diff --git a/emu/src/core/tc_jit.c b/emu/src/core/tc_jit.c new file mode 100644 index 0000000..b43e645 --- /dev/null +++ b/emu/src/core/tc_jit.c @@ -0,0 +1,1793 @@ +/* Translator S1C33 -> Thumb-2 for Cortex-M4. Same semantics as tc_fast.c + * (verified by per-block lockstep runs against tc_exec). Included into the + * same compilation unit as tc_all.c and uses its static helpers. + * + * Register allocation in generated code: + * r11 = Emu* r10 = remaining cycles r9 = a0ram r4..r7 survive helpers + * r0..r3, r12, lr = free (memory accesses clobber them) + * Flags live in e->nzcv in ARM format, with C meaning "no borrow" + * (= not guest C), so CMP/SUB produce them directly. */ +#include "tc.h" +#ifdef JIT_RSTAT +#include +#endif + +int jit_enabled = 1; +uint32_t jit_st_cw; + +/* ---------- Memory for code and mapping ---------- */ +#ifndef JIT_HASH +#define JIT_HASH 1024u +#endif +#define JIT_MAXI 32 /* guest instructions per block */ +#define JIT_INTERP 1u /* marker: use the interpreter */ +#ifndef JIT_TICK +#define JIT_TICK 1024u /* peripheral tick interval of the translator */ +#endif + +static uint8_t *J_buf; /* host pointer */ + +static uint32_t J_tgt, J_size; /* target address and size */ +#ifdef JIT_STAGE +/* v0.8.16: Code is generated in SRAM (J_stage) and copied to PRAM only when complete, by a small + * copy loop that itself runs from SRAM (interrupts off). On the device, writing to PRAM corrupts + * instructions if the CPU is fetching code from PRAM at the same time. J_lim caps to the staging buffer. */ +static uint8_t *J_stage; static uint32_t J_stage_sz, J_lo, J_lim; +static void (*J_copy)(uint32_t dst, const uint8_t *src, uint32_t n); +uint32_t jit_st_copy; +static void stage_begin(uint32_t lo) { J_lo = lo; J_buf = J_stage - lo; J_lim = lo + J_stage_sz; if (J_lim > J_size) J_lim = J_size; } +static void stage_commit(uint32_t lo, uint32_t hi) +{ + if (hi <= lo) return; + uint32_t pm; __asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory"); + J_copy(J_tgt + lo, J_stage, (hi - lo + 1u) & ~1u); + __asm__ volatile("msr primask, %0" :: "r"(pm) : "memory"); + jit_st_copy++; +} +#define J_LIMIT J_lim +#else +#define J_LIMIT J_size +#endif +static uint32_t J_pos, J_fixed; /* fill level, end of the fixed part */ +static int J_full; +static uint32_t J_entry, J_exit; /* entry/exit addresses */ +static uint32_t J_chainx, J_plainx, J_idlex; /* exits with target pc as a literal after the bl */ +int jit_idle_on = 1; +#define JIT_CNT 2048 +static uint8_t jit_cnt[JIT_CNT]; +#ifndef JIT_HOT +#define JIT_HOT 32 /* 1.6.13 test10 (TamaEmu, bigger code buffer): 8, fewer runs in the interpreter */ +#endif +int jit_hot = JIT_HOT, jit_interp_run = 1; +static uint32_t jit_prev_pc = 0xFFFFFFF0u; +uint32_t jit_st_patch; /* skip idle loops until the next event */ +uint32_t jit_st_idle; +static uint32_t J_slow[8]; /* shared slow paths */ +static uint32_t J_stn, J_slown, J_st[3], J_pushn, J_popn, J_lds[5][7]; /* writes (fast+slow), pushn/popn */ +static uint32_t jh_pc[JIT_HASH], jh_code[JIT_HASH]; + +/* field offsets in Emu */ +#define OFF(f) ((uint32_t)offsetof(Emu, f)) +#define O_R(i) (OFF(r) + 4u * (uint32_t)(i)) + +/* ---------- Emission ---------- */ +#pragma clang attribute push (__attribute__((minsize)), apply_to = function) +static inline uint32_t HERE(void) { return J_tgt + J_pos; } +static void E16(uint32_t h) +{ + if (J_pos + 2 > J_LIMIT) { J_full = 1; return; } +#ifdef JIT_HWRITE + *(volatile uint16_t *)(J_buf + J_pos) = (uint16_t)h; J_pos += 2; /* halfword writes only into PRAM */ +#else + J_buf[J_pos] = (uint8_t)h; J_buf[J_pos + 1] = (uint8_t)(h >> 8); J_pos += 2; +#endif +} +static void E32(uint32_t h1, uint32_t h2) { E16(h1); E16(h2); } +static void P16(uint32_t tgt, uint32_t h) { uint32_t o = tgt - J_tgt; if (o + 2 > J_LIMIT +#ifdef JIT_STAGE + || o < J_lo +#endif + ) { J_full = 1; return; } +#ifdef JIT_HWRITE + *(volatile uint16_t *)(J_buf + o) = (uint16_t)h; } +#else + J_buf[o] = (uint8_t)h; J_buf[o + 1] = (uint8_t)(h >> 8); } +#endif + +enum { R0, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, SPR, LR, PCR }; +enum { EQ, NE, CS, CC, MI, PL, VS, VC, HI, LS, GE, LT, GT, LE, AL }; +enum { AND = 0, BIC = 1, ORR = 2, ORN = 3, EOR = 4, ADD = 8, ADC = 10, SBC = 11, SUB = 13, RSB = 14 }; +enum { LSL, LSR, ASR, ROR }; +#define NPOOL 7 +#define G_SP 16 +#define G_ALR 17 +#define G_AHR 18 +#define NG 19 +static const int8_t pool_reg[NPOOL] = { R4, R5, R6, R7, R8, R2, R3 }; +static int pool_idx(int r) { for (int i = 0; i < NPOOL; i++) if (pool_reg[i] == r) return i; return 0; } + +static int modimm(uint32_t v) +{ + if (v < 256) return (int)v; + uint32_t b = v & 0xFF; + if (b && v == (b | (b << 16))) return 0x100 | (int)b; + b = (v >> 8) & 0xFF; + if (b && v == ((b << 8) | (b << 24))) return 0x200 | (int)b; + b = v & 0xFF; + if (b && v == b * 0x01010101u) return 0x300 | (int)b; + { /* 1xxxxxxx rotated right by rot (8..31): rot follows from the highest set bit */ + int lz = __builtin_clz(v); + if (lz > 23) return -1; + int rot = lz + 8; + uint32_t u = (v << rot) | (v >> (32 - rot)); + if (u < 256) return (rot << 7) | (int)(u & 0x7F); + } + return -1; +} +static void dpi(int op, int s, int rd, int rn, int imm12) +{ + E32(0xF000u | ((uint32_t)(imm12 >> 11) << 10) | ((uint32_t)op << 5) | ((uint32_t)s << 4) | (uint32_t)rn, + ((uint32_t)((imm12 >> 8) & 7) << 12) | ((uint32_t)rd << 8) | (uint32_t)(imm12 & 0xFF)); +} +static void dpr(int op, int s, int rd, int rn, int rm, int type, int imm5) +{ + E32(0xEA00u | ((uint32_t)op << 5) | ((uint32_t)s << 4) | (uint32_t)rn, + ((uint32_t)(imm5 >> 2) << 12) | ((uint32_t)rd << 8) | ((uint32_t)(imm5 & 3) << 6) | ((uint32_t)type << 4) | (uint32_t)rm); +} +static void movw_t(int rd, uint32_t v, int top) +{ + E32((top ? 0xF2C0u : 0xF240u) | (((v >> 11) & 1) << 10) | ((v >> 12) & 0xF), + (((v >> 8) & 7) << 12) | ((uint32_t)rd << 8) | (v & 0xFF)); +} +static void mov32(int rd, uint32_t v) +{ + int m = modimm(v); + if (m >= 0) { dpi(ORR, 0, rd, PCR, m); return; } + m = modimm(~v); + if (m >= 0) { dpi(ORN, 0, rd, PCR, m); return; } + movw_t(rd, v & 0xFFFF, 0); + if (v >> 16) movw_t(rd, v >> 16, 1); +} +static void movr(int rd, int rm) { E16(0x4600u | ((uint32_t)(rd >> 3) << 7) | ((uint32_t)rm << 3) | (uint32_t)(rd & 7)); } +/* rd = rn OP imm, falling back to r12 */ +static void opi(int op, int s, int rd, int rn, uint32_t imm) +{ + int m = modimm(imm); + if (m >= 0) { dpi(op, s, rd, rn, m); return; } + mov32(R12, imm); + dpr(op, s, rd, rn, R12, LSL, 0); +} +/* Load/store with 12-bit offset or register */ +enum { STRB_I = 0xF880, STRH_I = 0xF8A0, STR_I = 0xF8C0, LDRB_I = 0xF890, LDRH_I = 0xF8B0, LDR_I = 0xF8D0, LDRSB_I = 0xF990, LDRSH_I = 0xF9B0 }; +enum { STRB_R = 0xF800, STRH_R = 0xF820, STR_R = 0xF840, LDRB_R = 0xF810, LDRH_R = 0xF830, LDR_R = 0xF850, LDRSB_R = 0xF910, LDRSH_R = 0xF930 }; +static void ldsti(uint32_t base, int rt, int rn, uint32_t imm) { E32(base | (uint32_t)rn, ((uint32_t)rt << 12) | (imm & 0xFFF)); } +static void ldstr(uint32_t base, int rt, int rn, int rm) { E32(base | (uint32_t)rn, ((uint32_t)rt << 12) | (uint32_t)rm); } +static void ldf(int r, uint32_t off) { ldsti(LDR_I, r, R11, off); } +static void stf(uint32_t off, int r) { ldsti(STR_I, r, R11, off); } +static void shreg(int type, int s, int rd, int rn, int rm) { E32(0xFA00u | ((uint32_t)type << 5) | ((uint32_t)s << 4) | (uint32_t)rn, 0xF000u | ((uint32_t)rd << 8) | (uint32_t)rm); } +static void ext16(uint32_t h1, int rd, int rm) { E32(h1, 0xF080u | ((uint32_t)rd << 8) | (uint32_t)rm); } +#define SXTB(d, m) ext16(0xFA4F, d, m) +#define SXTH(d, m) ext16(0xFA0F, d, m) +#define UXTB(d, m) ext16(0xFA5F, d, m) +#define UXTH(d, m) ext16(0xFA1F, d, m) +#ifdef JIT_RSTAT +uint16_t jit_line_map[0x8000]; +#define LINEMARK(l) do { if (J_pos / 2 < 0x8000u) jit_line_map[J_pos / 2] = (uint16_t)(l); } while (0) +#else +#define LINEMARK(l) do {} while (0) +#endif +static void mrs_(int rd, int l) { LINEMARK(l); E32(0xF3EF, 0x8000u | ((uint32_t)rd << 8)); } +static void msr_(int rn, int l) { LINEMARK(l); E32(0xF380u | (uint32_t)rn, 0x8800); } +#define mrs(r) mrs_(r, __LINE__) +#define msr(r) msr_(r, __LINE__) +static void it(int cond, uint32_t mask) { E16(0xBF00u | ((uint32_t)cond << 4) | mask); } +#define IT1(c) it((c), 0x8) +#define ITE(c) it((c), (((~(uint32_t)(c)) & 1u) << 3) | 4u) +#define ITT(c) it((c), (((uint32_t)(c) & 1u) << 3) | 4u) + +/* Branches */ +static void enc_b(uint32_t at, uint32_t to, int link, uint32_t *h1, uint32_t *h2) +{ + int32_t off = (int32_t)(to - (at + 4)); + uint32_t S = ((uint32_t)off >> 24) & 1, I1 = ((uint32_t)off >> 23) & 1, I2 = ((uint32_t)off >> 22) & 1; + uint32_t J1 = (~I1 ^ S) & 1, J2 = (~I2 ^ S) & 1; + *h1 = 0xF000u | (S << 10) | (((uint32_t)off >> 12) & 0x3FF); + *h2 = (link ? 0xD000u : 0x9000u) | (J1 << 13) | (J2 << 11) | (((uint32_t)off >> 1) & 0x7FF); +} +static void enc_bc(uint32_t at, uint32_t to, int cond, uint32_t *h1, uint32_t *h2) +{ + int32_t off = (int32_t)(to - (at + 4)); + uint32_t u = (uint32_t)off; + *h1 = 0xF000u | (((u >> 20) & 1) << 10) | ((uint32_t)cond << 6) | ((u >> 12) & 0x3F); + *h2 = 0x8000u | (((u >> 18) & 1) << 13) | (((u >> 19) & 1) << 11) | ((u >> 1) & 0x7FF); +} +static void b_to(uint32_t to) { uint32_t h1, h2; enc_b(HERE(), to, 0, &h1, &h2); E32(h1, h2); } +static void bl_to(uint32_t to) { uint32_t h1, h2; enc_b(HERE(), to, 1, &h1, &h2); E32(h1, h2); } +static void bc_to(int c, uint32_t to) { uint32_t h1, h2; enc_bc(HERE(), to, c, &h1, &h2); E32(h1, h2); } +static void patch_b(uint32_t at, uint32_t to) { uint32_t h1, h2; enc_b(at, to, 0, &h1, &h2); P16(at, h1); P16(at + 2, h2); } +static void patch_bc(uint32_t at, int c, uint32_t to) { uint32_t h1, h2; enc_bc(at, to, c, &h1, &h2); P16(at, h1); P16(at + 2, h2); } + +#pragma clang attribute pop +/* ---------- Helpers (called from generated code) ---------- */ +static uint32_t jit_req(Emu *e) { if (e->jit_bias) return 0; e->jit_bias = 0x40000000u; return 1; } +static uint32_t jit_codewrite(Emu *e, uint32_t a, uint32_t n) +{ + if (a > A0RAM_MAX - n) return 0; + if (!(e->jit_map[a >> 8] | e->jit_map[(a + n - 1) >> 8])) return 0; + jit_cw_note(e, a, n); + e->jit_flush = 1; jit_st_cw++; + memset(e->jit_map, 0, sizeof e->jit_map); + return 1; +} +static uint32_t jit_irq_ready(Emu *e) { return e->pending_irq && e->f_ie && e->pending_level > e->il; } +#ifdef JIT_RSTAT +uint64_t jit_rstat[8][8]; +static int rreg(Emu *e, uint32_t a){ if(a<0x8000)return 0; if(a-0x80000u<0x5000u)return 1; if(a-0x300000u<0x2000u)return 2; if(a-0x600000u<2u)return 3; if(a-e->dev.rom_basedev.rom_size)return 4; return 5; } +#define RST(k,a) jit_rstat[k][rreg(e,a)]++ +#else +#define RST(k,a) (void)0 +#endif +#ifdef JIT_RSTAT +uint64_t jit_romhist[2048]; +#endif +uint32_t jh_rd8(Emu *e, uint32_t a) { RST(0,a); +#ifdef JIT_RSTAT + if (a - e->dev.rom_base < e->dev.rom_size) jit_romhist[(a - e->dev.rom_base) >> 12]++; +#endif + return f_rd8(e, a); } +uint32_t jh_rd16(Emu *e, uint32_t a) { RST(1,a); return f_rd16(e, a); } +uint32_t jh_rd32(Emu *e, uint32_t a) { RST(2,a); return f_rd32(e, a); } +static uint32_t jh_after_wr(Emu *e, uint32_t cw, int slow) +{ + if (cw || (slow && jit_irq_ready(e))) return jit_req(e); + return 0; +} +uint32_t jh_wr8(Emu *e, uint32_t a, uint32_t v) +{ + RST(3,a); + uint32_t cw = jit_codewrite(e, a, 1); + uint8_t *p = f_ramp(e, a, 1); if (p) { *p = (uint8_t)v; return jh_after_wr(e, cw, 0); } + mem_write8(e, a, (uint8_t)v); return jh_after_wr(e, cw, 1); +} +uint32_t jh_wr16(Emu *e, uint32_t a, uint32_t v) +{ + RST(4,a); + uint32_t cw = jit_codewrite(e, a, 2); + uint8_t *p = f_ramp(e, a, 2); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); return jh_after_wr(e, cw, 0); } + mem_write16(e, a, (uint16_t)v); return jh_after_wr(e, cw, 1); +} +uint32_t jh_wr32(Emu *e, uint32_t a, uint32_t v) +{ + RST(5,a); + uint32_t cw = jit_codewrite(e, a, 4); + uint8_t *p = f_ramp(e, a, 4); if (p) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); return jh_after_wr(e, cw, 0); } + mem_write32(e, a, v); return jh_after_wr(e, cw, 1); +} +/* Byte to LCD data (the most common peripheral access in games) */ +uint32_t jh_lcd8(Emu *e, uint32_t a, uint32_t v) +{ + (void)a; RST(3, e->dev.lcd_data_addr); + e->lcd_writes++; lcd_data(e, (uint8_t)v); + return 0; +} +uint32_t jh_pushn(Emu *e, uint32_t last) +{ + RST(6,e->sp); + uint32_t q = 0; + for (int i = (int)last; i >= 0; i--) { e->sp -= 4; q |= jh_wr32(e, e->sp, e->r[i]); } + return q; +} +uint32_t jh_popn(Emu *e, uint32_t last) +{ + RST(7,e->sp); + for (uint32_t i = 0; i <= last; i++) { e->r[i] = f_rd32(e, e->sp); e->sp += 4; } + return 0; +} +enum { H_RD8, H_RD16, H_RD32, H_WR8, H_WR16, H_WR32, H_PUSHN, H_POPN, H_LCD }; +/* Slow paths: read 8u 8s 16u 16s 32, write 8 16 32 */ +enum { S_RD8U, S_RD8S, S_RD16U, S_RD16S, S_RD32, S_WR8, S_WR16, S_WR32 }; + +#pragma clang attribute push (__attribute__((minsize)), apply_to = function) +/* ---------- fixed part: entry, exit, slow paths ---------- + * In generated code APSR always holds the guest flags (C as "no borrow"). + * All routines here leave APSR unchanged (helper calls are wrapped in + * mrs/msr). */ +static uint32_t J_exitn; /* exit, flags already saved */ +static void cbz_fwd(int rn, int nz, uint32_t to) /* cbz/cbnz forward, target <= 126 bytes */ +{ + uint32_t off = to - (HERE() + 4); + E16((nz ? 0xB900u : 0xB100u) | (((off >> 6) & 1) << 9) | (((off >> 1) & 31) << 3) | (uint32_t)rn); +} +/* Patch cbz/cbnz into a reserved slot */ +uint32_t jit_cbz_bad, jit_cbz_bad_stub; int jit_cbz_site; +static void patch_cbz(uint32_t at, int rn, int nz, uint32_t to) +{ + if (to < at + 4 || to - (at + 4) > 126u) { jit_cbz_bad++; if (jit_cbz_site) jit_cbz_bad_stub++; J_full = 1; +#ifdef JIT_RSTAT + fprintf(stderr, "cbz too far: %u bytes, caller %p\n", to - (at + 4), __builtin_return_address(0)); +#endif + return; } + uint32_t o = J_pos; J_pos = at - J_tgt; cbz_fwd(rn, nz, to); J_pos = o; +} +static uint32_t hole(void) { uint32_t at = HERE(); E16(0); return at; } +#define LDR_POST(rt, rn) E32(0xF850u | (uint32_t)(rn), ((uint32_t)(rt) << 12) | 0x0B04u) +#define STR_POST(rt, rn) E32(0xF840u | (uint32_t)(rn), ((uint32_t)(rt) << 12) | 0x0B04u) +#define LSRW(rd, rm, n) dpr(ORR, 0, (rd), PCR, (rm), LSR, (n)) +/* Read without helper, without flags: ROM block, ivram, dstram. Address r0, + * value r1, bx lr. Otherwise falls through to the helper call after it. */ +static void fast_rd(Emu *e, uint32_t ld, uint32_t n) +{ + uint32_t sz = e->dev.rom_size; int sh = 0; while ((1u << sh) < sz) sh++; + if ((1u << sh) != sz || OFF(jit_parb) > 4000u || OFF(flash_autoselect) > 4000u) return; + uint32_t b_al = 0; + if (n > 1) { /* aligned only: then it cannot cross a boundary */ + dpi(AND, 0, R1, R0, (int)(n - 1)); + E16(0xB100u | (1u << 3) | R1); /* cbz r1, +4 */ + b_al = HERE(); E16(0); E16(0); /* b.w helper (patched later) */ + } + mov32(R2, e->dev.rom_base); + dpr(SUB, 0, R2, R0, R2, LSL, 0); /* r2 = a - rom_base */ + LSRW(R3, R2, sh); uint32_t c_norom = hole(); /* cbnz r3 -> not ROM */ + ldf(R3, OFF(flash_busy)); + ldsti(LDRB_I, R12, R11, OFF(flash_autoselect)); + dpr(ORR, 0, R3, R3, R12, LSL, 0); uint32_t c_busy = hole(); /* cbnz r3 -> helper */ + LSRW(R3, R2, 16); + dpr(ADD, 0, R3, R11, R3, LSL, 2); + ldsti(LDR_I, R3, R3, OFF(jit_rom)); uint32_t c_blk = hole(); /* cbz r3 -> parameter block */ + UXTH(R2, R2); + ldstr(ld, R1, R3, R2); + E16(0x4770); /* bx lr */ + uint32_t par = HERE(); + ldf(R3, OFF(jit_parb)); + dpr(SUB, 0, R3, R2, R3, LSL, 0); /* r3 = o - par */ + LSRW(R1, R3, 16); uint32_t c_np = hole(); /* cbnz r1 -> helper */ + LSRW(R3, R3, 13); + dpr(ADD, 0, R3, R11, R3, LSL, 2); + ldsti(LDR_I, R3, R3, OFF(jit_par)); uint32_t c_ps = hole(); /* cbz r3 -> helper */ + E32(0xF3C0u | R2, (R2 << 8) | 12u); /* ubfx r2, r2, #0, #13 */ + ldstr(ld, R1, R3, R2); + E16(0x4770); /* bx lr */ + uint32_t norom = HERE(); + dpi(SUB, 0, R2, R0, modimm(0x80000u)); /* r2 = a - 0x80000 */ + LSRW(R3, R2, 15); uint32_t c_far = hole(); /* cbnz r3 -> helper */ + LSRW(R3, R2, 12); + E32(0xE8DF, 0xF000u | R3); /* tbb [pc, r3] */ + uint32_t tab = HERE(); E16(0); E16(0); E16(0); E16(0); + uint32_t iv = HERE(); + dpi(ADD, 0, R3, R9, modimm(0x8000u)); ldstr(ld, R1, R3, R2); E16(0x4770); + uint32_t ds = HERE(); /* dstram = a0ram + 0xB000, offset r2 - 0x4000 */ + dpi(ADD, 0, R3, R9, modimm(0x7000u)); ldstr(ld, R1, R3, R2); E16(0x4770); + uint32_t help = HERE(); + if (b_al) patch_b(b_al, help); + patch_cbz(c_norom, R3, 1, norom); + patch_cbz(c_busy, R3, 1, help); + patch_cbz(c_blk, R3, 0, par); + patch_cbz(c_np, R1, 1, help); + patch_cbz(c_ps, R3, 0, help); + patch_cbz(c_far, R3, 1, help); + { uint32_t t[8] = { iv, iv, iv, help, ds, help, help, help }; + for (int i = 0; i < 8; i++) { uint32_t o = (t[i] - tab) / 2; uint32_t at = tab + (uint32_t)i - J_tgt; + if (at < J_LIMIT && !J_full) { +#ifdef JIT_HWRITE + volatile uint16_t *hp = (volatile uint16_t *)(J_buf + (at & ~1u)); + *hp = (at & 1u) ? (uint16_t)((*hp & 0x00FFu) | (o << 8)) : (uint16_t)((*hp & 0xFF00u) | (o & 0xFFu)); +#else + J_buf[at] = (uint8_t)o; +#endif + } } } +} +/* pushn (k=0) / popn (k=1) in a0ram without helper. r1 = last register. + * Otherwise falls through to the helper call after it. */ +static void fast_pushpop(int k) +{ + ldf(R0, OFF(sp)); + dpi(ADD, 0, R2, R1, 1); dpr(ORR, 0, R2, PCR, R2, LSL, 2); /* r2 = 4*(n+1) */ + uint32_t c1, c2, c3 = 0, c4 = 0; + if (k == 0) { + dpr(SUB, 0, R3, R0, R2, LSL, 0); /* new sp */ + LSRW(R2, R3, 15); c1 = hole(); + dpi(SUB, 0, R2, R0, 1); LSRW(R2, R2, 15); c2 = hole(); + dpr(ADD, 0, R2, R11, R3, LSR, 8); ldsti(LDRB_I, R2, R2, OFF(jit_map)); c3 = hole(); + dpi(SUB, 0, R2, R0, 1); dpr(ADD, 0, R2, R11, R2, LSR, 8); ldsti(LDRB_I, R2, R2, OFF(jit_map)); c4 = hole(); + stf(OFF(sp), R3); + dpr(ADD, 0, R0, R9, R3, LSL, 0); /* destination in a0ram */ + movr(R2, R11); /* e->r[0] */ + uint32_t lp = HERE(); + LDR_POST(R3, R2); STR_POST(R3, R0); + uint32_t cd = hole(); dpi(SUB, 0, R1, R1, 1); b_to(lp); + patch_cbz(cd, R1, 0, HERE()); + } else { + dpr(ADD, 0, R3, R0, R2, LSL, 0); /* new sp */ + dpi(SUB, 0, R2, R3, 1); LSRW(R2, R2, 15); c1 = hole(); + LSRW(R2, R0, 15); c2 = hole(); + stf(OFF(sp), R3); + dpr(ADD, 0, R0, R9, R0, LSL, 0); + movr(R2, R11); + uint32_t lp = HERE(); + LDR_POST(R3, R0); STR_POST(R3, R2); + uint32_t cd = hole(); dpi(SUB, 0, R1, R1, 1); b_to(lp); + patch_cbz(cd, R1, 0, HERE()); + } + E16(0x4770); /* bx lr */ + uint32_t slow = HERE(); + patch_cbz(c1, R2, 1, slow); patch_cbz(c2, R2, 1, slow); + if (k == 0) { patch_cbz(c3, R2, 1, slow); patch_cbz(c4, R2, 1, slow); } +} +static void call_helper2(int h, int keep) /* r0..r2 = arguments, result r0; APSR preserved if keep */ +{ + if (keep) mrs(R12); + E32(0xE92D, 0x500C); /* push {r2, r3, r12, lr} */ + ldf(R12, OFF(jit_h) + 4u * (uint32_t)h); + E16(0x4780 | (R12 << 3)); /* blx r12 */ + E32(0xE8BD, 0x500C); /* pop {r2, r3, r12, lr} */ + if (keep) msr(R12); +} +#define call_helper(h) call_helper2(h, 1) +static void emit_fixed(Emu *e) +{ + J_pos = 0; + /* Entry: jit_enter(e, code|1) */ + J_entry = HERE(); + E32(0xE92D, 0x4FF8); /* push {r3-r11, lr} */ + movr(R11, R0); + ldf(R10, OFF(jit_left)); + ldf(R9, OFF(jit_a0)); + ldf(R12, OFF(nzcv)); msr(R12); + E16(0x4708); /* bx r1 */ + /* Exit: r0 = reason */ + J_exit = HERE(); + mrs(R12); stf(OFF(nzcv), R12); + J_exitn = HERE(); + stf(OFF(jit_left), R10); + E32(0xE8BD, 0x8FF8); /* pop {r3-r11, pc} */ + /* Exit with chaining: bl here, followed by .word pc. r0 = address of the bl */ + J_chainx = HERE(); + dpi(SUB, 0, R0, LR, 5); + ldsti(LDR_I, R1, R0, 4); + stf(OFF(pc), R1); + b_to(J_exit); + /* Exit without chaining (cycles used up) */ + J_plainx = HERE(); + dpi(SUB, 0, R0, LR, 1); + ldsti(LDR_I, R1, R0, 0); + stf(OFF(pc), R1); + dpi(ORR, 0, R0, PCR, 0); /* mov.w r0, #0 (no flags) */ + b_to(J_exit); + /* Exit from an idle loop (jump to itself, waiting on memory) */ + J_idlex = HERE(); + dpi(SUB, 0, R0, LR, 1); + ldsti(LDR_I, R1, R0, 0); + stf(OFF(pc), R1); + dpi(ORR, 0, R0, PCR, 1); /* mov.w r0, #1 */ + b_to(J_exit); + /* All fixed routines called from a block preserve r2/r3 + * (they belong to the register cache): slow paths go through a wrapper + * push {r2,r3,lr}; bl inner; pop {r2,r3,pc}. */ +#define HUELLE(lbl, inner) do { lbl = HERE(); E16(0xB50C); bl_to(inner); E16(0xBD0C); } while (0) + /* Slow read (inner): address r0 -> value r1 */ + static const int rh[5] = { H_RD8, H_RD8, H_RD16, H_RD16, H_RD32 }; + uint32_t in_rd[5], in_wr[3], in_pp[2]; + for (int k = 0; k < 5; k++) { + in_rd[k] = HERE(); + { static const uint32_t lo[5] = { LDRB_R, LDRSB_R, LDRH_R, LDRSH_R, LDR_R }, ln[5] = { 1, 1, 2, 2, 4 }; + fast_rd(e, lo[k], ln[k]); } + movr(R1, R0); movr(R0, R11); + call_helper(rh[k]); + if (k == S_RD8S) SXTB(R1, R0); + else if (k == S_RD16S) SXTH(R1, R0); + else movr(R1, R0); + E16(0x4770); /* bx lr */ + } + for (int k = 0; k < 5; k++) HUELLE(J_slow[k], in_rd[k]); + /* Slow read into a pool register: bl here, returns 4 bytes further (past the ldr) */ + for (int k = 0; k < 5; k++) + for (int d = 0; d < NPOOL; d++) { + J_lds[k][d] = HERE(); + E16(0xB500); /* push {lr} */ + bl_to(J_slow[k]); + movr(pool_reg[d], R1); + E16(0xBC01); /* pop {r0} */ + dpi(ADD, 0, R0, R0, 4); /* add.w r0, r0, #4 (no flags) */ + E16(0x4700); /* bx r0 */ + } + /* Slow write (inner): address r0, value r1. Byte: LCD data directly */ + static const int wh[3] = { H_WR8, H_WR16, H_WR32 }; + for (int k = 0; k < 3; k++) { + in_wr[k] = HERE(); + if (k == 0) { + mov32(R2, e->dev.lcd_data_addr); + dpr(SUB, 0, R2, R0, R2, LSL, 0); + uint32_t c3 = HERE(); E16(0); /* cbnz r2 -> generic */ + movr(R2, R1); movr(R1, R0); movr(R0, R11); + call_helper(H_LCD); + E16(0x4770); + patch_cbz(c3, R2, 1, HERE()); + } + movr(R2, R1); movr(R1, R0); movr(R0, R11); + call_helper(wh[k]); + { uint32_t at = HERE(); E16(0); dpi(SUB, 0, R10, R10, modimm(0x40000000u)); + uint32_t o = J_pos; J_pos = at - J_tgt; cbz_fwd(R0, 0, J_tgt + o); J_pos = o; } + E16(0x4770); /* bx lr */ + } + for (int k = 0; k < 3; k++) HUELLE(J_slow[S_WR8 + k], in_wr[k]); + /* Byte write when no flag is live afterwards: LCD data without mrs/msr + * (in T25Emu these are fallbacks into its interpreter) */ + uint32_t in_wrn = HERE(); + { + mov32(R2, e->dev.lcd_data_addr); + dpr(SUB, 0, R2, R0, R2, LSL, 0); + uint32_t c3 = HERE(); E16(0); /* cbnz r2 -> generic */ + movr(R2, R1); movr(R1, R0); movr(R0, R11); + call_helper2(H_LCD, 0); + E16(0x4770); + patch_cbz(c3, R2, 1, HERE()); + b_to(in_wr[0]); + } + HUELLE(J_slown, in_wrn); + /* Write with fast path: address r0, value r1. Only r0, r1, r12 (no flags) */ + static const uint32_t sop[3] = { STRB_R, STRH_R, STR_R }; + for (int k = 0; k < 3; k++) { + J_st[k] = HERE(); + movr(R12, R0); + dpr(ORR, 0, R0, PCR, R0, LSR, 15); /* lsr.w r0, r0, #15 */ + uint32_t c1 = HERE(); E16(0); /* cbnz r0, slow */ + dpr(ADD, 0, R0, R11, R12, LSR, 8); + ldsti(LDRB_I, R0, R0, OFF(jit_map)); + uint32_t c2 = HERE(); E16(0); /* cbnz r0, slow */ + ldstr(sop[k], R1, R9, R12); + E16(0x4770); /* bx lr */ + uint32_t sl = HERE(); + movr(R0, R12); + b_to(J_slow[S_WR8 + k]); + patch_cbz(c1, R0, 1, sl); + patch_cbz(c2, R0, 1, sl); + } + { + J_stn = HERE(); + movr(R12, R0); + dpr(ORR, 0, R0, PCR, R0, LSR, 15); + uint32_t c1 = HERE(); E16(0); + dpr(ADD, 0, R0, R11, R12, LSR, 8); + ldsti(LDRB_I, R0, R0, OFF(jit_map)); + uint32_t c2 = HERE(); E16(0); + ldstr(STRB_R, R1, R9, R12); + E16(0x4770); + uint32_t sl = HERE(); + movr(R0, R12); + b_to(J_slown); + patch_cbz(c1, R0, 1, sl); + patch_cbz(c2, R0, 1, sl); + } + /* pushn/popn: fast path in a0ram, otherwise helper. r1 = last register */ + for (int k = 0; k < 2; k++) { + in_pp[k] = HERE(); + fast_pushpop(k); + movr(R0, R11); + call_helper(k == 0 ? H_PUSHN : H_POPN); + { uint32_t at = HERE(); E16(0); dpi(SUB, 0, R10, R10, modimm(0x40000000u)); + uint32_t o = J_pos; J_pos = at - J_tgt; cbz_fwd(R0, 0, J_tgt + o); J_pos = o; } + E16(0x4770); /* bx lr */ + } + HUELLE(J_pushn, in_pp[0]); + HUELLE(J_popn, in_pp[1]); +#undef HUELLE + (void)e; + J_fixed = J_pos; +} + +/* ---------- Decoding ---------- */ +enum { + K_NOP, K_INTERP, + K_ALU_RR, /* rd = rd op rs (op 0..7 as in class 1) */ + K_ALU_RX, /* rd = rs op imm (with ext) */ + K_ALU_I, /* rd = rd op imm */ + K_SHI, /* rd = shift(rd, imm) */ + K_SHR, /* rd = shift(rd, r[rs]&31) */ + K_SWAP, K_MIRROR, + K_SPADJ, /* sp += imm (two's complement) */ + K_LD, K_ST, /* size, sign, base (rs or sp), offset, post-increment */ + K_EXT, /* rd = sxtb/uxtb/sxth/uxth(rs) */ + K_MLTH, K_MLTUH, K_MLTW, K_MLTUW, + K_ADC, K_SBC, + K_BIT, /* op: 2 btst 3 bclr 4 bset 5 bnot */ + K_LDSR, /* rd = special register */ + K_STSR, /* special register = r[rs] */ + K_PUSH, K_POP, K_PUSHN, K_POPN, K_PUSHS, K_POPS, K_CLRF, + K_JR, K_JP, K_CALL, /* direct, cc / always / call */ + K_JPR, K_JPREG, K_CALLREG, K_RET +}; +enum { SH_SRL, SH_SLL, SH_SRA, SH_RR, SH_RL }; +enum { O_ADD, O_SUB, O_CMP, O_MOV, O_AND, O_OR, O_XOR, O_NOT }; +#define FN_ 8 +#define FZ_ 4 +#define FV_ 2 +#define FC_ 1 + +typedef struct DI { + uint32_t addr, next; /* start (with ext), next address */ + uint8_t len; /* halfwords */ + uint8_t kind, op, rd, rs, size, sgn, base_sp, post, dly, cond; + uint32_t imm, target; + uint8_t fdef, fuse, fpart, live; +} DI; + +static const uint8_t cond_need[16] = { + [4] = FN_ | FZ_ | FV_, [5] = FN_ | FV_, [6] = FN_ | FV_, [7] = FN_ | FZ_ | FV_, + [8] = FZ_ | FC_, [9] = FC_, [10] = FC_, [11] = FZ_ | FC_, [12] = FZ_, [13] = FZ_ }; +static const uint8_t cond_arm[16] = { [4] = GT, [5] = GE, [6] = LT, [7] = LE, [8] = HI, [9] = CS, [10] = CC, [11] = LS, [12] = EQ, [13] = NE }; + +static int code_ok(Emu *e, uint32_t a) +{ + return a - e->dev.rom_base < e->dev.rom_size - 2 || a < A0RAM_MAX - 2; +} +static uint32_t code16(Emu *e, uint32_t a) +{ + if (a < A0RAM_MAX - 1) return (uint32_t)(e->a0ram[a] | (e->a0ram[a + 1] << 8)); + const uint8_t *p = rom_ptr(e, a - e->dev.rom_base); + return (uint32_t)(p[0] | (p[1] << 8)); +} + +/* One instruction at a. Returns 0 if not readable. */ +static int decode(Emu *e, uint32_t a, DI *d) +{ + memset(d, 0, sizeof *d); + d->addr = a; + if (!code_ok(e, a)) return 0; + uint32_t hw = code16(e, a), pc = a; + int ext_n = 0; uint32_t ext0 = 0, ext1 = 0; + while ((hw >> 13) == 6) { + if (ext_n == 0) ext0 = hw & 0x1FFF; else if (ext_n == 1) ext1 = hw & 0x1FFF; + ext_n++; pc += 2; + if (ext_n > 2 || !code_ok(e, pc)) { d->kind = K_INTERP; d->len = (uint8_t)((pc - a) / 2 + 1); d->next = pc + 2; return 1; } + hw = code16(e, pc); + } + uint32_t iaddr = pc; + d->next = pc + 2; + d->len = (uint8_t)((d->next - a) / 2); + int rd = hw & 0xF, rs = (hw >> 4) & 0xF; + d->rd = (uint8_t)rd; d->rs = (uint8_t)rs; + d->kind = K_INTERP; + switch (hw >> 13) { + case 0: { + int op1 = (hw >> 9) & 0xF, dd = (hw >> 8) & 1; + if (op1 <= 3) { + int cnst = (hw >> 4) & 3; + if (cnst == 0) { + int op2 = (hw >> 6) & 3; + switch (op1 * 8 + dd * 4 + op2) { + case 0: d->kind = K_NOP; break; + case 8: d->kind = K_PUSHN; break; + case 9: d->kind = K_POPN; break; + case 11: d->kind = K_JPR; d->target = iaddr; break; + case 15: d->kind = K_JPR; d->target = iaddr; d->dly = 1; break; + case 24: d->kind = K_CALLREG; break; + case 25: d->kind = K_RET; break; + case 26: d->kind = K_JPREG; break; + case 28: d->kind = K_CALLREG; d->dly = 1; break; + case 29: d->kind = K_RET; d->dly = 1; break; + case 30: d->kind = K_JPREG; d->dly = 1; break; + default: break; + } + } else if (cnst == 1 && op1 == 0) { + switch ((hw >> 6) & 7) { + case 0: d->kind = K_PUSH; break; + case 1: d->kind = K_POP; break; + case 2: if ((hw & 0xF) == 2 || (hw & 0xF) == 3) d->kind = K_PUSHS; break; + case 3: if ((hw & 0xF) == 2 || (hw & 0xF) == 3) d->kind = K_POPS; break; + case 7: d->kind = K_CLRF; d->fdef = 0xF; break; + } + } + } else { + uint32_t u8 = hw & 0xFF, target; + if (ext_n == 0) target = iaddr + SEXT(u8, 8) * 2; + else if (ext_n == 1) target = iaddr + ((SEXT(ext0, 13) << 9) | (u8 << 1)); + else target = iaddr + (((ext0 & 0x1ff8) << 19) | (ext1 << 9) | (u8 << 1)); + d->target = target; d->dly = (uint8_t)dd; + if (op1 == 14) d->kind = K_CALL; + else if (op1 == 15) d->kind = K_JP; + else { d->kind = K_JR; d->cond = (uint8_t)op1; d->fuse = cond_need[op1]; } + } + break; + } + case 1: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + if (op2 == 3) { + static const int8_t m[8] = { SH_SRL, SH_SLL, SH_SRA, SH_SLL, SH_RR, SH_RL, -1, -1 }; + if (m[op1] < 0) break; + d->kind = K_SHI; d->op = (uint8_t)m[op1]; d->imm = ((hw >> 4) & 0xF) + 16; + d->fdef = FN_ | FZ_; d->fpart = 1; + break; + } + if (op2 == 2) { + uint32_t imm = (ext_n == 1) ? ext0 : ((ext0 << 13) | ext1); + if (ext_n && (op1 == 3 || op1 == 7)) break; + d->kind = ext_n ? K_ALU_RX : K_ALU_RR; d->op = (uint8_t)op1; d->imm = imm; + if (op1 <= 2) d->fdef = 0xF; + else if (op1 >= 4) { d->fdef = FN_ | FZ_ | FV_; d->fpart = 1; } + break; + } + if (ext_n && op2 == 1) break; + { + static const uint8_t sz[8] = { 1, 1, 2, 2, 4, 1, 2, 4 }, sg[8] = { 1, 0, 1, 0, 0, 0, 0, 0 }; + d->kind = op1 >= 5 ? K_ST : K_LD; d->size = sz[op1]; d->sgn = sg[op1]; + d->imm = ext_n ? ((ext_n == 1) ? ext0 : ((ext0 << 13) | ext1)) : 0; + d->post = (op2 == 1) ? sz[op1] : 0; + } + break; + } + case 2: { + int op1 = (hw >> 10) & 7; + uint32_t imm6 = (hw >> 4) & 0x3F, off; + static const uint8_t sz[8] = { 1, 1, 2, 2, 4, 1, 2, 4 }, sg[8] = { 1, 0, 1, 0, 0, 0, 0, 0 }; + if (ext_n == 0) off = imm6 * sz[op1]; + else if (ext_n == 1) off = (ext0 << 6) | imm6; + else off = (ext0 << 19) | (ext1 << 6) | imm6; + d->kind = op1 >= 5 ? K_ST : K_LD; d->size = sz[op1]; d->sgn = sg[op1]; d->imm = off; d->base_sp = 1; + break; + } + case 3: { + int op1 = (hw >> 10) & 7; + uint32_t imm6 = (hw >> 4) & 0x3F, imm; + if (ext_n == 0) imm = (op1 == 0 || op1 == 1) ? imm6 : SEXT(imm6, 6); + else if (ext_n == 1) { imm = (ext0 << 6) | imm6; if (!(op1 == 0 || op1 == 1)) imm = SEXT(imm, 19); } + else imm = (ext0 << 19) | (ext1 << 6) | imm6; + d->kind = K_ALU_I; d->op = (uint8_t)op1; d->imm = imm; + if (op1 <= 2) d->fdef = 0xF; + else if (op1 >= 4) { d->fdef = FN_ | FZ_ | FV_; d->fpart = 1; } + break; + } + case 4: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + if (op1 == 0) { d->kind = K_SPADJ; d->imm = (uint32_t)(hw & 0x3FF) * 4; break; } + if (op1 == 1) { d->kind = K_SPADJ; d->imm = 0u - (uint32_t)(hw & 0x3FF) * 4; break; } + if (op2 == 2 && op1 == 4) { d->kind = K_SWAP; break; } + if (op2 == 2 && op1 == 6) { d->kind = K_MIRROR; break; } + static const uint8_t m[8] = { 0, 0, SH_SRL, SH_SLL, SH_SRA, SH_SLL, SH_RR, SH_RL }; + d->op = m[op1]; + if (op2 == 0) { d->kind = K_SHI; d->imm = (hw >> 4) & 0xF; } + else d->kind = K_SHR; + d->fdef = FN_ | FZ_; d->fpart = 1; + break; + } + case 5: { + int op1 = (hw >> 10) & 7, op2 = (hw >> 8) & 3; + switch (op1 * 4 + op2) { + case 0: if (rd == 1 || rd == 2 || rd == 3) { d->kind = K_STSR; d->op = (uint8_t)rd; } break; + case 1: d->kind = K_EXT; d->op = 0; break; /* sxtb */ + case 2: d->kind = K_MLTH; break; + case 4: if (rs == 1 || rs == 2 || rs == 3 || rs == 8 || rs == 10 || rs == 11 || rs == 15) { d->kind = K_LDSR; d->op = (uint8_t)rs; d->imm = iaddr; } break; + case 5: d->kind = K_EXT; d->op = 1; break; /* uxtb */ + case 6: d->kind = K_MLTUH; break; + case 8: case 12: case 16: case 20: + d->kind = K_BIT; d->op = (uint8_t)op1; d->imm = ext_n ? ((ext_n == 1) ? ext0 : ((ext0 << 13) | ext1)) : 0; + d->size = (uint8_t)(hw & 7); + if (op1 == 2) { d->fdef = FZ_; d->fpart = 1; } + break; + case 9: d->kind = K_EXT; d->op = 2; break; /* sxth */ + case 10: d->kind = K_MLTW; break; + case 13: d->kind = K_EXT; d->op = 3; break; /* uxth */ + case 14: d->kind = K_MLTUW; break; + case 17: case 21: d->kind = K_NOP; break; + case 24: d->kind = K_ADC; d->fdef = 0xF; d->fuse = FC_; break; + case 28: d->kind = K_SBC; d->fdef = 0xF; d->fuse = FC_; break; + default: break; + } + break; + } + default: break; + } + return 1; +} +static int is_branch(int k) { return k >= K_JR; } + +/* Which flags does the code at t need before it sets them itself? Scans up + * to the first branch (after that unknown = all). Fixed ROM only: RAM and the + * parameter sectors may change later. Saves fixing up flags at exits that + * the target overwrites anyway. */ +#ifdef JIT_NOXL +int jit_xlive = 0; +#else +int jit_xlive = 1; +#endif +static uint8_t xl_pg[16]; static int xl_np; /* RAM pages read by the lookahead */ +static int live_fest(Emu *e, uint32_t a) +{ + if (a < A0RAM_MAX - 8u) { /* RAM: remember page, a write there flushes */ + for (uint32_t p = a >> 8; p <= (a + 7) >> 8; p++) { + int q = 0; while (q < xl_np && xl_pg[q] != p) q++; + if (q == xl_np) { if (xl_np >= (int)sizeof xl_pg) return 0; xl_pg[xl_np++] = (uint8_t)p; } + } + return 1; + } + if (a < A0RAM_MAX) return 0; + uint32_t off = a - e->dev.rom_base; + if (off >= e->dev.rom_size - 4) return 0; + return off - e->par_base >= 0x10000u + 64u && off + 64u - e->par_base >= 0x10000u + 64u; +} +static uint8_t exit_live(Emu *e, uint32_t t) +{ + uint8_t need = 0, def = 0; + if (!jit_xlive) return 0xF; + for (int k = 0; k < 12; k++) { + DI d; + if (!live_fest(e, t) || !decode(e, t, &d) || d.kind == K_INTERP) break; + need |= (uint8_t)(d.fuse & ~def); + if (is_branch(d.kind)) { + if (d.dly) { + DI s2; + if (!live_fest(e, d.next) || !decode(e, d.next, &s2) || s2.kind == K_INTERP) break; + need |= (uint8_t)(s2.fuse & ~def); def |= s2.fdef; + if ((def & 0xF) == 0xF) return need; + } + if (d.kind == K_JP || d.kind == K_CALL) { t = d.target; continue; } /* fixed jump: continue there */ + break; + } + def |= d.fdef; + if ((def & 0xF) == 0xF) return need; + t = d.next; + } + return (uint8_t)((need | ~def) & 0xF); +} +#ifdef JIT_TEST +uint8_t jit_exit_live(Emu *e, uint32_t t) { xl_np = 0; return exit_live(e, t); } +#endif + +/* ---------- Code generation ---------- */ + +/* Register cache: guest registers 0..15, 16 = sp, 17 = alr, 18 = ahr live + * in r4..r8 during a block (preserved across helper calls). + * Written back at the end of the block. */ +static int8_t rc_g[NPOOL]; /* guest register, -1 free, -2 temp register */ +static uint8_t rc_dirty[NPOOL]; +static uint32_t rc_use[NPOOL], rc_clock; +static int8_t rc_of[NG]; +static uint32_t goff(int g) +{ + if (g < 16) return O_R(g); + return g == G_SP ? OFF(sp) : g == G_ALR ? OFF(alr) : OFF(ahr); +} +static void rc_reset(void) +{ + for (int i = 0; i < NPOOL; i++) { rc_g[i] = -1; rc_dirty[i] = 0; rc_use[i] = 0; } + for (int g = 0; g < NG; g++) rc_of[g] = -1; + rc_clock = 1; +} +static void rc_next(void) { rc_clock++; } /* new instruction: old entries can be evicted */ +static int rc_slot(void) +{ + int best = -1; + for (int i = 0; i < NPOOL; i++) if (rc_g[i] == -1) return i; + for (int i = 0; i < NPOOL; i++) + if (rc_g[i] >= 0 && rc_use[i] < rc_clock && (best < 0 || rc_use[i] < rc_use[best])) best = i; + if (best < 0) { J_full = 1; return 0; } /* must not happen */ + int g = rc_g[best]; + if (rc_dirty[best]) stf(goff(g), pool_reg[best]); + rc_of[g] = -1; rc_g[best] = -1; rc_dirty[best] = 0; + return best; +} +static int rget(int g, int load, int write) +{ + int i = rc_of[g]; + if (i < 0) { + i = rc_slot(); + rc_g[i] = (int8_t)g; rc_of[g] = (int8_t)i; rc_dirty[i] = 0; + if (load) ldf(pool_reg[i], goff(g)); + } + rc_use[i] = rc_clock; + if (write) rc_dirty[i] = 1; + return pool_reg[i]; +} +#define RR(g) rget((g), 1, 0) /* read */ +#define RW(g) rget((g), 0, 1) /* write only */ +#define RRW(g) rget((g), 1, 1) /* read and write */ +static int tmp_get(void) +{ + int i = rc_slot(); + rc_g[i] = -2; rc_use[i] = 0xFFFFFFFFu; + return pool_reg[i]; +} +static int tmp_get_low(void) /* temp register r2..r7 (for cbz) */ +{ + int i = -1; + for (int k = 0; k < NPOOL; k++) if (pool_reg[k] != R8 && rc_g[k] == -1) { i = k; break; } + if (i < 0) { + for (int k = 0; k < NPOOL; k++) + if (pool_reg[k] != R8 && rc_g[k] >= 0 && rc_use[k] < rc_clock && (i < 0 || rc_use[k] < rc_use[i])) i = k; + if (i < 0) { J_full = 1; return R4; } + int g = rc_g[i]; + if (rc_dirty[i]) stf(goff(g), pool_reg[i]); + rc_of[g] = -1; rc_dirty[i] = 0; + } + rc_g[i] = -2; rc_use[i] = 0xFFFFFFFFu; + return pool_reg[i]; +} +static void tmp_put(int r) +{ + for (int i = 0; i < NPOOL; i++) if (pool_reg[i] == r && rc_g[i] == -2) { rc_g[i] = -1; rc_use[i] = 0; } +} +static void rc_wb(int g) /* write back a single register, it stays in the cache */ +{ + int i = rc_of[g]; + if (i >= 0 && rc_dirty[i]) { stf(goff(g), pool_reg[i]); rc_dirty[i] = 0; } +} +static void rc_drop(int g) /* discard entry (memory is newer) */ +{ + int i = rc_of[g]; + if (i >= 0) { rc_g[i] = -1; rc_dirty[i] = 0; rc_use[i] = 0; rc_of[g] = -1; } +} +static void rc_flush(void) /* write back everything modified (sets no flags) */ +{ + for (int i = 0; i < NPOOL; i++) + if (rc_g[i] >= 0 && rc_dirty[i]) { stf(goff(rc_g[i]), pool_reg[i]); rc_dirty[i] = 0; } +} + +/* Memory access: address in r0. Read -> r1, write from r1. */ +static void mem_rd(int size, int sgn) +{ + /* fast path without flags: a < 0x8000 -> ldr from a0ram, otherwise slow path */ + int k = size == 1 ? (sgn ? S_RD8S : S_RD8U) : size == 2 ? (sgn ? S_RD16S : S_RD16U) : S_RD32; + static const uint32_t ops[5] = { LDRB_R, LDRSB_R, LDRH_R, LDRSH_R, LDR_R }; + dpr(ORR, 0, R1, PCR, R0, LSR, 15); /* lsr.w r1, r0, #15 */ + E16(0xB100u | (2u << 3) | R1); /* cbz r1, +4 -> fast path */ + bl_to(J_slow[k]); + E16(0xE000u | 1u); /* b +2 (past the ldr) */ + ldstr(ops[k], R1, R9, R0); +} +/* like mem_rd, result directly in dst (r4..r8): fast path without going through r1 */ +static void mem_rd_to(int dst, int size, int sgn, int base) /* base: address register (r0 = copy only on the slow path) */ +{ + if (base != R0) { + int k = size == 1 ? (sgn ? S_RD8S : S_RD8U) : size == 2 ? (sgn ? S_RD16S : S_RD16U) : S_RD32; + static const uint32_t ops[5] = { LDRB_R, LDRSB_R, LDRH_R, LDRSH_R, LDR_R }; + dpr(ORR, 0, R1, PCR, base, LSR, 15); /* lsr.w r1, base, #15 */ + E16(0xB100u | (2u << 3) | R1); /* cbz r1, past mov and bl -> fast path */ + movr(R0, base); + bl_to(J_lds[k][pool_idx(dst)]); + ldstr(ops[k], dst, R9, base); + return; + } + int k = size == 1 ? (sgn ? S_RD8S : S_RD8U) : size == 2 ? (sgn ? S_RD16S : S_RD16U) : S_RD32; + static const uint32_t ops[5] = { LDRB_R, LDRSB_R, LDRH_R, LDRSH_R, LDR_R }; + dpr(ORR, 0, R1, PCR, R0, LSR, 15); /* lsr.w r1, r0, #15 */ + E16(0xB100u | (1u << 3) | R1); /* cbz r1, +2 -> fast path */ + bl_to(J_lds[k][pool_idx(dst)]); /* slow path, returns past the ldr */ + ldstr(ops[k], dst, R9, R0); +} +static uint32_t J_wlive = 0xF; /* flags a write must preserve */ +static void mem_wr(int size) +{ + bl_to(size == 1 && !J_wlive ? J_stn : J_st[size == 1 ? 0 : size == 2 ? 1 : 2]); +} + +#define A_N 0x80000000u +#define A_Z 0x40000000u +#define A_C 0x20000000u +#define A_V 0x10000000u +/* Invert C (guest C = carry, stored as "no borrow"); now only used for adc */ +static void fl_inv_c(void) +{ + mrs(R12); dpi(EOR, 0, R12, R12, modimm(A_C)); msr(R12); +} +/* ALU: dst = a OP (b | imm). a, b are ARM registers (already loaded). */ +static int imm_keeps_c(uint32_t imm) { int m = modimm(imm); return m >= 0 && m < 0x400; } +static void gen_alu(const DI *d, int op, int ra, int has_imm, uint32_t imm, int rb) +{ + int live = d->live & d->fdef; + switch (op) { + case O_ADD: case O_SUB: case O_CMP: { + int aop = (op == O_ADD) ? ADD : SUB; + int s = live ? 1 : 0; + if (op == O_CMP && !live) break; + int dst = (op == O_CMP) ? PCR : RW(d->rd); + if (live && op == O_ADD && (d->live & FC_)) { + /* Guest C after add = no carry. cmp ~b, a gives exactly that as C, + * and V as for add; N, Z then from the result (tst keeps C, V). + * Without mrs/msr (fallbacks in T25Emu). */ + if (has_imm) mov32(R12, ~imm); else dpr(ORN, 0, R12, PCR, rb, LSL, 0); /* r12 = ~b */ + dpr(SUB, 1, PCR, R12, ra, LSL, 0); /* cmp r12, a */ + if (has_imm) opi(ADD, 0, dst, ra, imm); else dpr(ADD, 0, dst, ra, rb, LSL, 0); + if (d->live & (FN_ | FZ_)) dpr(AND, 1, PCR, dst, dst, LSL, 0); /* tst */ + break; + } + if (has_imm) opi(aop, s, dst, ra, imm); else dpr(aop, s, dst, ra, rb, LSL, 0); + break; + } + case O_MOV: { + int dst = RW(d->rd); + if (has_imm) mov32(dst, imm); else movr(dst, rb); + break; + } + default: { + int lop = op == O_AND ? AND : op == O_OR ? ORR : op == O_XOR ? EOR : ORN; + int vfix = live && (d->live & FV_); /* clear V: without mrs/msr, see below */ + int s = live && !vfix ? 1 : 0; + int dst = RW(d->rd); + if (op == O_NOT) { + if (has_imm) { mov32(dst, ~imm); if (s) dpr(AND, 1, PCR, dst, dst, LSL, 0); } /* tst dst, dst */ + else dpr(ORN, s, dst, PCR, rb, LSL, 0); /* mvns */ + } else if (has_imm) { + if (!s || imm_keeps_c(imm)) opi(lop, s, dst, ra, imm); + else { mov32(R12, imm); dpr(lop, 1, dst, ra, R12, LSL, 0); } + } else dpr(lop, s, dst, ra, rb, LSL, 0); + if (vfix) { + if (d->live & FC_) { + /* save C: r12 = C (adc), cmp r12, #1 sets C = r12 and V = 0, then tst sets N, Z */ + dpi(ORR, 0, R12, PCR, 0); + dpi(ADC, 0, R12, R12, 0); + dpi(SUB, 1, PCR, R12, 1); + } else + dpi(SUB, 1, PCR, dst, 0); /* cmp dst, #0: N, Z, V = 0 */ + if (d->live & FC_) dpr(AND, 1, PCR, dst, dst, LSL, 0); /* tst dst, dst */ + } + break; + } + } +} + +static void gen_shift(const DI *d, int byreg) +{ + int a = RR(d->rd); + if (byreg) { + int rs = RR(d->rs); + dpi(AND, 0, R1, rs, 31); + a = RRW(d->rd); + switch (d->op) { + case SH_SRL: shreg(LSR, 0, a, a, R1); break; + case SH_SLL: shreg(LSL, 0, a, a, R1); break; + case SH_SRA: shreg(ASR, 0, a, a, R1); break; + case SH_RR: shreg(ROR, 0, a, a, R1); break; + case SH_RL: dpi(RSB, 0, R1, R1, 32); shreg(ROR, 0, a, a, R1); break; + } + } else { + int n = (int)d->imm; + a = RRW(d->rd); + if (n) switch (d->op) { + case SH_SRL: dpr(ORR, 0, a, PCR, a, LSR, n); break; + case SH_SLL: dpr(ORR, 0, a, PCR, a, LSL, n); break; + case SH_SRA: dpr(ORR, 0, a, PCR, a, ASR, n); break; + case SH_RR: dpr(ORR, 0, a, PCR, a, ROR, n); break; + case SH_RL: dpr(ORR, 0, a, PCR, a, ROR, 32 - n); break; + } + } + if (d->live & d->fdef) dpr(AND, 1, PCR, a, a, LSL, 0); /* tst a, a: N, Z; C, V unchanged */ +} + +/* Address into r0 */ +static void addr_of(const DI *d) +{ + int b = RR(d->base_sp ? G_SP : d->rs); + if (d->imm) opi(ADD, 0, R0, b, d->imm); else movr(R0, b); +} + +/* sp -= 4; [sp] = value in r1 */ +static void push_r1(void) +{ + int sp = RRW(G_SP); + dpi(SUB, 0, sp, sp, 4); + movr(R0, sp); + mem_wr(4); +} + +/* Exits: bl J_chainx with pc after it, becomes b.w target when chained */ +/* Exit with fixed target: ldr pc,[r11,#slot] jumps through a slot in + * jit_slot. Initially it points to the bl J_chainx after it; chaining only + * rewrites the slot (data), the code stays unchanged. This keeps the + * instruction cache clean and matters in T25Emu: there, any change to + * code that has already run discards all translations. */ +static Emu *J_e; +static uint32_t J_nslot; +static void exit_direct(uint32_t pc) +{ + if (J_nslot >= 600u || OFF(jit_slot) + 4u * 600u > 4095u) { J_full = 1; return; } + uint32_t sl = J_nslot++; + /* ldr.w r12, [r11, #slot]; bx r12. Not ldr pc: T25Emu cannot translate + * that and falls back to its interpreter every time. */ + E32(0xF8D0u | R11, ((uint32_t)R12 << 12) | (OFF(jit_slot) + 4u * sl)); + E16(0x4700u | (R12 << 3)); + J_e->jit_slot[sl] = HERE() | 1u; + bl_to(J_chainx); E16(pc & 0xFFFFu); E16(pc >> 16); +} +static void exit_reg(int r) /* pc from register (r1 or pool); the target checks cycles */ +{ + /* without touching flags (no mrs/msr: a fallback in T25Emu) */ + stf(OFF(pc), r); + E32(0xF3C0u | (uint32_t)r, (0u << 12) | (R0 << 8) | (1u << 6) | 7u); /* ubfx r0, r, #1, #8 */ + dpr(ADD, 0, R0, R11, R0, LSL, 3); + ldsti(LDR_I, LR, R0, OFF(jit_itab) + 4); /* code */ + ldsti(LDR_I, R0, R0, OFF(jit_itab)); /* guest pc */ + dpr(SUB, 0, R0, R0, r, LSL, 0); /* r0 = r0 - r */ + E16(0xB900u | R0); /* cbnz r0, +0 -> exit */ + E16(0x4700u | (LR << 3)); /* bx lr */ + mrs(R12); + stf(OFF(nzcv), R12); + dpi(ORR, 0, R0, PCR, 0); /* mov.w r0, #0 */ + b_to(J_exitn); +} +/* Place the block entry's bail-out (cycles used up) in dead code */ +static uint32_t E_cb, E_pc, E_lim = 90; +static void entry_stub_place(void) +{ + if (!E_cb) return; + if (HERE() - (E_cb + 4) > 126u) return; + patch_cbz(E_cb, R3, 1, HERE()); + bl_to(J_plainx); E16(E_pc & 0xFFFFu); E16(E_pc >> 16); + E_cb = 0; +} +static void entry_stub_maybe(void) /* if it gets too far: place it with a jump over it */ +{ + if (!E_cb || HERE() - E_cb < E_lim) return; + uint32_t at = HERE(); E16(0); + entry_stub_place(); + P16(at, 0xE000u | (((HERE() - (at + 4)) >> 1) & 0x7FFu)); +} +uint32_t jit_st_kb[48], jit_st_kn[48]; +static void gen_insn2(Emu *e, const DI *d); +static void gen_insn(Emu *e, const DI *d) +{ + entry_stub_maybe(); + uint32_t h0 = J_pos; + J_wlive = (uint8_t)(d->live | d->fuse); gen_insn2(e, d); J_wlive = 0xF; + int k = d->kind; if (k == K_ALU_RR || k == K_ALU_RX || k == K_ALU_I) k = 32 + (d->op) + (d->live & d->fdef ? 8 : 0); + jit_st_kb[k] += J_pos - h0; jit_st_kn[k]++; +} +static void gen_insn2(Emu *e, const DI *d) +{ + (void)e; + rc_next(); + switch (d->kind) { + case K_NOP: break; + case K_ALU_RR: { + int a = (d->op == O_MOV || d->op == O_NOT) ? 0 : RR(d->rd); + int b = RR(d->rs); + gen_alu(d, d->op, a, 0, 0, b); + break; + } + case K_ALU_RX: + gen_alu(d, d->op, RR(d->rs), 1, d->imm, 0); + break; + case K_ALU_I: { + int a = (d->op != O_MOV && d->op != O_NOT) ? RR(d->rd) : 0; + gen_alu(d, d->op, a, 1, d->imm, 0); + break; + } + case K_SHI: gen_shift(d, 0); break; + case K_SHR: gen_shift(d, 1); break; + case K_SWAP: case K_MIRROR: { + int s = RR(d->rs), t = RW(d->rd); + E32(0xFA90u | (uint32_t)s, (d->kind == K_SWAP ? 0xF080u : 0xF090u) | ((uint32_t)t << 8) | (uint32_t)s); + break; + } + case K_SPADJ: { int sp = RRW(G_SP); opi(ADD, 0, sp, sp, d->imm); break; } + case K_LD: { + int base = R0; + if (d->imm) addr_of(d); else base = RR(d->base_sp ? G_SP : d->rs); + rc_next(); + { int dst = RW(d->rd); mem_rd_to(dst, d->size, d->sgn, base); } + if (d->post) { int b = RRW(d->rs); dpi(ADD, 0, b, b, d->post); } + break; + } + case K_ST: { + addr_of(d); + movr(R1, RR(d->rd)); + mem_wr(d->size); + if (d->post) { int b = RRW(d->rs); dpi(ADD, 0, b, b, d->post); } + break; + } + case K_EXT: { + int s = RR(d->rs), t = RW(d->rd); + if (d->op == 0) SXTB(t, s); else if (d->op == 1) UXTB(t, s); + else if (d->op == 2) SXTH(t, s); else UXTH(t, s); + break; + } + case K_MLTH: case K_MLTUH: { + int a = RR(d->rd), b = RR(d->rs); + if (d->kind == K_MLTH) { SXTH(R0, a); SXTH(R1, b); } else { UXTH(R0, a); UXTH(R1, b); } + int t = RW(G_ALR); + E32(0xFB00u | R0, 0xF000u | ((uint32_t)t << 8) | R1); /* mul t, r0, r1 */ + break; + } + case K_MLTW: case K_MLTUW: { + int a = RR(d->rd), b = RR(d->rs); + E32((d->kind == K_MLTW ? 0xFB80u : 0xFBA0u) | (uint32_t)a, (R0 << 12) | (R1 << 8) | (uint32_t)b); + movr(RW(G_ALR), R0); movr(RW(G_AHR), R1); + break; + } + case K_ADC: case K_SBC: { + int a = RRW(d->rd), b = RR(d->rs); + if (d->kind == K_ADC) fl_inv_c(); /* ARM C = guest C for adcs */ + dpr(d->kind == K_ADC ? ADC : SBC, 1, a, a, b, LSL, 0); + if (d->kind == K_ADC) fl_inv_c(); + break; + } + case K_BIT: { + int b = RR(d->rs); + if (d->imm) opi(ADD, 0, R0, b, d->imm); else movr(R0, b); + int t = tmp_get(); + movr(t, R0); + mem_rd(1, 0); + uint32_t m = 1u << d->size; + if (d->op == 2) { + if (d->live & FZ_) { + mrs(R12); dpi(BIC, 0, R12, R12, modimm(A_Z)); + dpi(AND, 0, R1, R1, (int)m); /* r1 &= m (no flags) */ + E16(0xB900u | (1u << 3) | R1); /* cbnz r1, past the orr */ + dpi(ORR, 0, R12, R12, modimm(A_Z)); + msr(R12); + } + } else { + int op = d->op == 3 ? BIC : d->op == 4 ? ORR : EOR; + dpi(op, 0, R1, R1, (int)m); + movr(R0, t); + mem_wr(1); + } + tmp_put(t); + break; + } + case K_LDSR: { + switch (d->op) { + case 1: { int s = RR(G_SP); movr(RW(d->rd), s); break; } + case 2: { int s = RR(G_ALR); movr(RW(d->rd), s); break; } + case 3: { int s = RR(G_AHR); movr(RW(d->rd), s); break; } + case 8: ldf(RW(d->rd), OFF(ttbr)); break; + case 10: ldf(RW(d->rd), OFF(idir)); break; + case 11: ldf(RW(d->rd), OFF(dbbr)); break; + default: mov32(RW(d->rd), d->imm); break; + } + break; + } + case K_STSR: { + int s = RR(d->rs); + movr(RW(d->op == 1 ? G_SP : d->op == 2 ? G_ALR : G_AHR), s); + break; + } + case K_PUSH: movr(R1, RR(d->rd)); push_r1(); break; + case K_POP: { + int sp = RRW(G_SP); + movr(R0, sp); dpi(ADD, 0, sp, sp, 4); + mem_rd(4, 0); + rc_next(); + movr(RW(d->rd), R1); + break; + } + case K_PUSHN: + for (int i = 0; i <= d->rd; i++) rc_wb(i); + rc_wb(G_SP); rc_drop(G_SP); + mov32(R1, d->rd); bl_to(J_pushn); + break; + case K_POPN: + rc_wb(G_SP); rc_drop(G_SP); + for (int i = 0; i <= d->rd; i++) rc_drop(i); + mov32(R1, d->rd); bl_to(J_popn); + break; + case K_PUSHS: + if (d->rd == 3) { movr(R1, RR(G_AHR)); push_r1(); rc_next(); } + movr(R1, RR(G_ALR)); push_r1(); + break; + case K_POPS: { + int sp = RRW(G_SP); + movr(R0, sp); dpi(ADD, 0, sp, sp, 4); + mem_rd(4, 0); rc_next(); movr(RW(G_ALR), R1); + if (d->rd == 3) { + rc_next(); + sp = RRW(G_SP); + movr(R0, sp); dpi(ADD, 0, sp, sp, 4); + mem_rd(4, 0); rc_next(); movr(RW(G_AHR), R1); + } + break; + } + case K_CLRF: + mov32(R12, A_C); msr(R12); + break; + default: break; + } +} + +/* ---------- Mapping ---------- */ +static uint32_t hslot(uint32_t pc) { return ((pc >> 1) ^ (pc >> 11)) & (JIT_HASH - 1); } +static uint32_t lookup(uint32_t pc) +{ + for (uint32_t i = hslot(pc), n = 0; n < JIT_HASH; n++, i = (i + 1) & (JIT_HASH - 1)) { + if (jh_pc[i] == pc) return jh_code[i]; + if (jh_pc[i] == 0xFFFFFFFFu) return 0; + } + return 0; +} +static int insert(uint32_t pc, uint32_t code) +{ + for (uint32_t i = hslot(pc), n = 0; n < JIT_HASH / 2; n++, i = (i + 1) & (JIT_HASH - 1)) + if (jh_pc[i] == 0xFFFFFFFFu) { jh_pc[i] = pc; jh_code[i] = code; return 1; } + return 0; +} +static uint32_t jit_count, jit_gen; +uint32_t jit_st_insns, jit_st_flush, jit_st_blocks, jit_st_bytes; +void jit_flush_all(Emu *e) +{ + memset(jh_pc, 0xFF, sizeof jh_pc); + memset(e->jit_itab, 0xFF, sizeof e->jit_itab); + J_pos = J_fixed; J_full = 0; jit_count = 0; jit_gen++; jit_st_flush++; J_nslot = 0; +#ifndef JIT_KEEPCNT + memset(jit_cnt, 0, sizeof jit_cnt); /* KEEPCNT: retranslate hot blocks right after a flush */ +#endif + memset(e->jit_map, 0, sizeof e->jit_map); + e->jit_flush = 0; +} + +/* Store modified registers without changing the cache state (side exit) */ +static void rc_store_dirty(void) +{ + for (int i = 0; i < NPOOL; i++) + if (rc_g[i] >= 0 && rc_dirty[i]) stf(goff(rc_g[i]), pool_reg[i]); +} +#ifndef JIT_SUPER +#define JIT_SUPER 1 /* conditional branches inside a block: side exit instead of block end */ +#endif +int jit_super = JIT_SUPER; +/* Translate the block at pc. 0 = no space, JIT_INTERP = interpreter. + * A block continues past conditional branches (superblock): a taken + * branch leaves it as a side exit, and the register cache is kept for the + * fall-through. Cycles are deducted per section so that a side exit costs + * exactly as much as in the interpreter. */ +static uint32_t translate(Emu *e, uint32_t pc) +{ + static DI di[JIT_MAXI + 2]; + static uint8_t side[JIT_MAXI + 2]; /* 1: a section ends here with a conditional branch */ + int n = 0, end_kind = 0; /* 0 = fall-through, 1 = branch */ + uint32_t a = pc; + int ram = pc < A0RAM_MAX; + while (n < JIT_MAXI) { + DI *d = &di[n]; + side[n] = 0; + if (!decode(e, a, d) || d->kind == K_INTERP) break; + if (ram && d->next > A0RAM_MAX - 2) break; + if (is_branch(d->kind)) { + int m = 1; + if (d->dly) { + DI *s = &di[n + 1]; + side[n + 1] = 0; + if (!decode(e, d->next, s) || s->kind == K_INTERP || is_branch(s->kind)) break; + if (ram && s->next > A0RAM_MAX - 2) break; + m = 2; + } + if (jit_super && d->kind == K_JR && n + m < JIT_MAXI - 1) { + side[n] = 1; /* continue on the fall-through */ + n += m; + a = di[n - 1].next; + continue; + } + n += m; + end_kind = 1; + break; + } + n++; + a = d->next; + } + if (n == 0) return JIT_INTERP; + uint32_t next = di[n - 1].next; + /* Idle loop: the first section jumps to itself, only reads memory + * and compares. Its result only changes when an interrupt or a + * peripheral writes something; until then time may fast-forward. Counter + * loops (registers change) do not qualify. */ + int idle_at = -1; + { + int j = 0; while (j < n && !is_branch(di[j].kind)) j++; + if (j < n && j >= 1 && di[j].kind == K_JR && !di[j].dly && di[j].target == pc) { + uint32_t bases = 0, dsts = 0; int ok = 1; + for (int i = 0; i < j && ok; i++) { + DI *d = &di[i]; + if (d->kind == K_LD && !d->post) { bases |= 1u << (d->base_sp ? 16 : d->rs); dsts |= 1u << d->rd; } + else if ((d->kind == K_ALU_RR || d->kind == K_ALU_RX || d->kind == K_ALU_I) && d->op == O_CMP) {} + else if (d->kind == K_BIT && d->op == 2) {} + else if (d->kind == K_NOP) {} + else ok = 0; + } + if (ok && !(bases & dsts)) idle_at = j; + } + } + /* Flag liveness, backwards; all live at every side exit */ + uint8_t live; + xl_np = 0; + if (!end_kind) live = exit_live(e, next); + else { + DI *b = is_branch(di[n - 1].kind) || n < 2 ? &di[n - 1] : &di[n - 2]; + if (b->kind == K_JR) live = exit_live(e, b->target) | exit_live(e, next); + else if (b->kind == K_JP || b->kind == K_CALL) live = exit_live(e, b->target); + else live = 0xF; + } + for (int i = n - 1; i >= 0; i--) { + int exit_after = side[i] ? !di[i].dly : (i > 0 && side[i - 1] && di[i - 1].dly); + if (exit_after) live |= exit_live(e, side[i] ? di[i].target : di[i - 1].target); + di[i].live = live; + live = (uint8_t)((live & ~di[i].fdef) | di[i].fuse); + } + /* Code */ + /* new block in a fresh 64-byte line: otherwise T25Emu discards + * everything when a line with already executed code is written to */ + J_pos += (0u - HERE()) & 63u; /* only advance, write nothing */ + if (J_pos >= J_size) { J_full = 1; return 0; } +#ifdef JIT_STAGE + stage_begin(J_pos); +#endif + uint32_t start = HERE(), nslot0 = J_nslot; + E_lim = 90; +again: + J_e = e; + rc_reset(); + /* Entry: cycles used up (left < 0) -> return. The bail-out is placed + * later in dead code (after an exit), so the normal path runs through + * without a taken branch. The cost of the whole block is deducted once, + * and a side exit refunds the rest. */ + dpr(ORR, 0, R3, PCR, R10, ASR, 31); /* r3 = left < 0 ? -1 : 0 */ + E_cb = HERE(); E16(0); /* cbnz r3 -> bail out */ + E_pc = pc; + uint32_t total = 0, done = 0; + for (int j = 0; j < n; j++) total += di[j].len; + opi(SUB, 0, R10, R10, total); + int i = 0; + while (i < n) { + /* Section i..k-1: up to and including the conditional branch (and delay slot) */ + int k = i; + while (k < n && !side[k] && !(end_kind && is_branch(di[k].kind))) k++; + int last; /* last instruction of the section */ + if (k < n) last = di[k].dly ? k + 1 : k; else last = n - 1; + for (int j = i; j <= last; j++) done += di[j].len; + if (k >= n) { /* end without branch */ + for (int j = i; j < n; j++) gen_insn(e, &di[j]); + rc_flush(); + exit_direct(next); + break; + } + for (int j = i; j < k; j++) gen_insn(e, &di[j]); + DI *b = &di[k], *sl = b->dly ? &di[k + 1] : 0; + uint32_t ret = sl ? sl->next : b->next; + rc_next(); + if (side[k]) { + int c = cond_arm[b->cond]; + uint32_t skip; + int t = -1; + if (sl && sl->fdef) { + t = tmp_get_low(); + ITE(c); dpi(ORR, 0, t, PCR, 1); dpi(ORR, 0, t, PCR, 0); /* t = taken */ + gen_insn(e, sl); + skip = HERE(); E16(0); /* cbz t -> continue */ + } else { + if (sl) { sl->live |= b->fuse; gen_insn(e, sl); rc_next(); } /* delay slot keeps flags; the branch reads them afterwards */ + skip = HERE(); E16(0); /* b -> continue */ + } + rc_store_dirty(); + if (total > done) opi(ADD, 0, R10, R10, total - done); /* refund the part not executed */ + if (k == idle_at) { bl_to(J_idlex); E16(b->target & 0xFFFFu); E16(b->target >> 16); } + else exit_direct(b->target); + entry_stub_place(); + if (t >= 0) { patch_cbz(skip, t, 0, HERE()); tmp_put(t); } + else { + uint32_t off = HERE() - (skip + 4); + if (off > 254u) { J_full = 1; } else P16(skip, 0xD000u | ((uint32_t)(c ^ 1) << 8) | (off >> 1)); + } + i = sl ? k + 2 : k + 1; + if (i >= n) { rc_flush(); exit_direct(next); break; } + continue; + } + switch (b->kind) { + case K_JR: { + int c = cond_arm[b->cond]; + if (sl && !sl->fdef) { sl->live |= b->fuse; gen_insn(e, sl); rc_next(); sl = 0; } + if (sl) { + int t = tmp_get_low(); + ITE(c); dpi(ORR, 0, t, PCR, 1); dpi(ORR, 0, t, PCR, 0); /* t = taken */ + gen_insn(e, sl); + rc_flush(); + E16(0xB900u | (6u << 3) | (uint32_t)t); /* cbnz t, +12 -> taken (past exit_direct, 14 bytes) */ + tmp_put(t); + } else { + rc_flush(); + E16(0xD000u | ((uint32_t)c << 8) | 6u); /* b +12 -> taken */ + } + exit_direct(ret); + if (k == idle_at) { bl_to(J_idlex); E16(b->target & 0xFFFFu); E16(b->target >> 16); } + else exit_direct(b->target); + break; + } + case K_JP: + if (sl) gen_insn(e, sl); + rc_flush(); + exit_direct(b->target); + break; + case K_CALL: + if (sl) gen_insn(e, sl); + rc_next(); + mov32(R1, ret); push_r1(); + rc_flush(); + exit_direct(b->target); + break; + case K_JPR: case K_JPREG: case K_CALLREG: { + int t = tmp_get(); + int r = RR(b->rd); + if (b->kind == K_JPR) opi(ADD, 0, t, r, b->target); else movr(t, r); + if (sl) gen_insn(e, sl); + rc_next(); + if (b->kind == K_CALLREG) { mov32(R1, ret); push_r1(); } + rc_flush(); + exit_reg(t); + tmp_put(t); + break; + } + case K_RET: { + if (sl) gen_insn(e, sl); + rc_next(); + int sp = RRW(G_SP); + movr(R0, sp); dpi(ADD, 0, sp, sp, 4); + mem_rd(4, 0); + rc_flush(); + exit_reg(R1); + break; + } + } + break; + } + entry_stub_place(); + if (E_cb && !J_full && E_lim) { /* bail-out too far away: redo with a tighter limit */ + E_lim = E_lim > 40u ? 40u : 0u; + J_pos = start - J_tgt; J_nslot = nslot0; E_cb = 0; + goto again; + } + if (E_cb) J_full = 1; + if (J_full) return 0; +#ifdef JIT_STAGE + stage_commit(start - J_tgt, J_pos); +#endif + if (ram) for (uint32_t p = pc >> 8; p <= ((next - 1) >> 8) && p < 128; p++) e->jit_map[p] = 1; + for (int q = 0; q < xl_np; q++) if (xl_pg[q] < 128) e->jit_map[xl_pg[q]] = 1; + jit_sync(start, HERE()); + jit_count++; jit_st_blocks++; jit_st_insns += (uint32_t)n; jit_st_bytes += HERE() - start; + return start; +} + +static uint32_t get_block(Emu *e, uint32_t pc) +{ + uint32_t c = lookup(pc); + if (c) return c; + c = translate(e, pc); + if (!c) { jit_flush_all(e); c = translate(e, pc); if (!c) return JIT_INTERP; } + if (!insert(pc, c)) { jit_flush_all(e); c = translate(e, pc); if (!c) return JIT_INTERP; insert(pc, c); } + return c; +} + +#ifdef JIT_STAGE +/* Copy loop as fixed instructions in SRAM: r0 = destination (PRAM), r1 = source, r2 = length (even). */ +static uint16_t J_cpcode[12] __attribute__((aligned(4))); +void jit_stage_setup(uint8_t *stage, uint32_t size) +{ + static const uint16_t c[12] = { 0xF831, 0x3B02, /* ldrh.w r3, [r1], #2 */ + 0xF820, 0x3B02, /* strh.w r3, [r0], #2 */ + 0x3A02, /* subs r2, #2 */ + 0xD1F9, /* bne start */ + 0xF3BF, 0x8F4F, /* dsb */ + 0xF3BF, 0x8F6F, /* isb */ + 0x4770, 0xBF00 }; /* bx lr */ + for (int i = 0; i < 12; i++) J_cpcode[i] = c[i]; + __asm__ volatile("dsb\n isb" ::: "memory"); + J_copy = (void (*)(uint32_t, const uint8_t *, uint32_t))((uint32_t)J_cpcode | 1u); + J_stage = stage; J_stage_sz = size; +} +#endif +#ifdef JIT_STAGE +/* 1.6.13 test10 (EMU_OVL): copy into the PRAM (the app's overlay from the flash), the same way as translated code */ +void jit_pram_load(uint32_t dst, const void *src, uint32_t n) +{ + uint32_t pm; __asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory"); + J_copy(dst, (const uint8_t *)src, (n + 1u) & ~1u); + __asm__ volatile("msr primask, %0" :: "r"(pm) : "memory"); +} +#endif +/* ---------- Platform-independent setup ---------- */ +TC_INIT_LAST void jit_init(Emu *e, uint8_t *buf, uint32_t tgt, uint32_t size) +{ + J_buf = buf; J_tgt = tgt; J_size = size; +#ifdef JIT_WHOT + memset(jit_wcnt, 0, sizeof jit_wcnt); memset(jit_nojit, 0, sizeof jit_nojit); jit_wwin = jit_nojit_at = 0; +#endif +#ifdef JIT_STAGE + stage_begin(0); + emit_fixed(e); + stage_commit(0, J_pos); +#else + emit_fixed(e); +#endif + jit_flush_all(e); + jit_sync(J_tgt, J_tgt + J_fixed); +#ifndef TC_HOST + e->jit_a0 = (uint32_t)e->a0ram; + e->jit_h[H_RD8] = (uint32_t)jh_rd8; e->jit_h[H_RD16] = (uint32_t)jh_rd16; e->jit_h[H_RD32] = (uint32_t)jh_rd32; + e->jit_h[H_WR8] = (uint32_t)jh_wr8; e->jit_h[H_WR16] = (uint32_t)jh_wr16; e->jit_h[H_WR32] = (uint32_t)jh_wr32; + e->jit_h[H_PUSHN] = (uint32_t)jh_pushn; e->jit_h[H_POPN] = (uint32_t)jh_popn; e->jit_h[H_LCD] = (uint32_t)jh_lcd8; +#endif + e->jit_parb = e->par_base; + for (uint32_t o = 0; o < e->dev.rom_size && o < 0x800000u; o += 0x2000u) jit_rom_update(e, o); +} +uint32_t (*jit_tgt_of)(const uint8_t *p); +static uint32_t jit_tgt(const uint8_t *p) { return !p ? 0 : jit_tgt_of ? jit_tgt_of(p) : (uint32_t)(uintptr_t)p; } +/* Read pointer for ROM offset off: outside the parameter block, the fast + * block (64 KB); inside it, the overlay or the original per 8 KB. 0 = helper. */ +__attribute__((noinline)) void jit_rom_update(Emu *e, uint32_t off) +{ + if (off >= 0x800000u) return; + uint32_t b = off & ~0x1FFFu; + if (b - e->par_base < 0x10000u) { + const uint8_t *p = 0; + for (int k = 0; k < e->ovl.n; k++) if (e->ovl.base[k] == b) p = e->ovl.mem[k]; + if (!p && e->rom_src[b >> 16]) p = e->rom_src[b >> 16] + (b & 0xFFFFu); + e->jit_par[(b - e->par_base) >> 13] = jit_tgt(p); + e->jit_rom[b >> 16] = 0; + } else e->jit_rom[b >> 16] = jit_tgt(e->rom_blk[b >> 16]); +#ifdef ROMSTAT + e->jit_rom[b >> 16] = 0; /* stats build: all ROM reads go through the helpers (countable) */ +#endif +} +uint32_t jit_entry_addr(void) { return J_entry; } +uint32_t jit_used(void) { return J_pos; } +uint32_t jit_lookup_dbg(uint32_t pc) { return lookup(pc); } +#ifndef TC_HOST +#ifdef JIT_GUARD +/* Guard around entry (device debugging v0.8.8): own frame with r3..r11/lr, + * records sp before and after the block. If the block returns with a wrong sp + * (without the exit's pop), sp is restored and jit_dbg[4] is set so the + * caller's registers stay intact and the display can report it. + * jit_dbg: 0 sp before, 1 sp after, 2 code, 3 return value, 4 error (1 sp, 2 r10/r11), + * 5 counter (entries), 6/7 r10/r11 before, 8..23 ring of the last 8 entries + * (guest pc, code), 24 r10 after on error 2, 28..35 r4..r11 before, 36..43 r4..r11 after. */ +volatile uint32_t jit_dbg[44]; +void (*jit_bad_hook)(Emu *e); +__attribute__((naked, noinline)) static uint32_t jit_tramp(Emu *e, uint32_t code, uint32_t entry) +{ + __asm__ volatile( + "push {r3-r11, lr}\n" + "movw r3, #:lower16:jit_dbg\n movt r3, #:upper16:jit_dbg\n" + "mov r12, sp\n str r12, [r3, #0]\n" + "str r10, [r3, #24]\n str r11, [r3, #28]\n" + "add r12, r3, #112\n stmia r12, {r4-r11}\n" + "blx r2\n" + "movw r3, #:lower16:jit_dbg\n movt r3, #:upper16:jit_dbg\n" + "add r12, r3, #144\n stmia r12, {r4-r11}\n" + "mov r12, sp\n str r12, [r3, #4]\n str r0, [r3, #12]\n" + "ldr r2, [r3, #0]\n cmp r2, r12\n beq 1f\n" + "mov sp, r2\n movs r1, #1\n str r1, [r3, #16]\n b 3f\n" + "1: ldr r2, [r3, #24]\n cmp r2, r10\n bne 2f\n" + "ldr r2, [r3, #28]\n cmp r2, r11\n beq 3f\n" + "2: str r10, [r3, #96]\n movs r1, #2\n str r1, [r3, #16]\n" + "3: pop {r3-r11, pc}\n"); +} +uint32_t jit_enter(Emu *e, uint32_t code) +{ + uint32_t k = jit_dbg[5]++ & 7u; + jit_dbg[8 + 2 * k] = e->pc; jit_dbg[9 + 2 * k] = code; jit_dbg[2] = code; + uint32_t r = jit_tramp(e, code, J_entry | 1u); + if (jit_dbg[4] && jit_bad_hook) jit_bad_hook(e); + return r; +} +#else +uint32_t jit_enter(Emu *e, uint32_t code) { return ((uint32_t (*)(Emu *, uint32_t))(J_entry | 1u))(e, code); } +#endif +void jit_sync(uint32_t lo, uint32_t hi) { (void)lo; (void)hi; __asm__ volatile("dsb\n isb" ::: "memory"); } +#endif + +#pragma clang attribute pop +static inline uint32_t pack_fl(Emu *e) +{ + return ((uint32_t)e->f_n << 31) | ((uint32_t)e->f_z << 30) | ((uint32_t)(!e->f_c) << 29) | ((uint32_t)e->f_v << 28); +} +static inline void unpack_fl(Emu *e) +{ + uint32_t f = e->nzcv; + e->f_n = (uint8_t)(f >> 31); e->f_z = (uint8_t)((f >> 30) & 1); e->f_c = (uint8_t)(!((f >> 29) & 1)); e->f_v = (uint8_t)((f >> 28) & 1); +} + +#ifdef JIT_TEST +/* Test mode: run only one block without chaining */ +int jit_test_single = 0; +uint32_t jit_test_cost; +void (*jit_test_hook)(Emu *e, uint32_t pc); +#endif + +/* Like tc_exec: until cycles >= ziel (target), halt or stop. */ +void jit_exec(Emu *e, uint64_t ziel) +{ + int32_t left; +#define JCYC() (e->evt - (uint64_t)(int64_t)left) +#define JNEXT(c) do { uint64_t _n = (e->last_tick + JIT_TICK < ziel) ? e->last_tick + JIT_TICK : ziel; e->evt = _n; left = (int32_t)(_n - (c)); } while (0) + JNEXT(e->cycles); + if (e->halted || e->stopped) return; + for (;;) { + if (left <= 0) { + uint64_t cyc = JCYC(); + if (cyc - e->last_tick >= JIT_TICK) { + e->cycles = cyc; + periph_tick(e, (uint32_t)(cyc - e->last_tick)); + e->last_tick = cyc; + } + if (cyc >= ziel) { e->cycles = cyc; break; } + JNEXT(cyc); + } + if (e->jit_flush) jit_flush_all(e); + if (e->pending_irq && e->f_ie && e->pending_level > e->il) { + uint32_t vec = e->pending_irq; + uint32_t psr = (e->psr_rest & ~0xF1Fu) | e->f_n | ((uint32_t)e->f_z << 1) | ((uint32_t)e->f_v << 2) | ((uint32_t)e->f_c << 3) | ((uint32_t)e->f_ie << 4) | ((uint32_t)(e->il & 0xF) << 8); + e->sp -= 4; jh_wr32(e, e->sp, e->pc); + e->sp -= 4; jh_wr32(e, e->sp, psr); + e->jit_bias = 0; + e->f_ie = 0; + e->il = e->pending_level; + e->pc = f_rd32(e, e->ttbr + vec * 4); + e->pending_irq = 0; + jit_prev_pc = 0xFFFFFFF0u; + if (e->jit_flush) jit_flush_all(e); + } + uint32_t pc = e->pc & 0x0FFFFFFFu; + uint32_t code = lookup(pc); + if (!code) { + /* Translate only once the block runs often: rare code stays in the + * interpreter and does not evict hot blocks from the buffer. */ + uint8_t *cn = &jit_cnt[((pc >> 1) ^ (pc >> 11)) & (JIT_CNT - 1)]; + if (pc > jit_prev_pc && pc - jit_prev_pc <= 6u) code = JIT_INTERP; /* in the middle of a sequence: keep interpreting */ +#ifdef JIT_WHOT + else if (pc < A0RAM_MAX && jit_nojit_pc(e, pc)) code = JIT_INTERP; /* code there keeps being overwritten */ +#endif + else if (*cn < jit_hot) { (*cn)++; code = JIT_INTERP; } + else code = get_block(e, pc); + } + if (code == JIT_INTERP) { + e->cycles = JCYC(); e->pc = pc; + jit_prev_pc = pc; + tc_exec(e, e->cycles + jit_interp_run); + left = (int32_t)(e->evt - e->cycles); + if (e->halted || e->stopped) break; + if (e->cycles >= ziel) break; + JNEXT(e->cycles); +#ifdef JIT_TEST + if (jit_test_single) { jit_test_cost = 0; break; } +#endif + continue; + } +#ifdef JIT_TEST + if (jit_test_hook) { e->cycles = JCYC(); e->pc = pc; jit_test_hook(e, pc); } +#endif +#ifdef JIT_TEST + if (!jit_test_single) +#endif + { uint32_t k = (pc >> 1) & 255u; e->jit_itab[2 * k] = pc; e->jit_itab[2 * k + 1] = code | 1u; } + e->nzcv = pack_fl(e); + e->jit_left = left; e->jit_bias = 0; + uint32_t r = jit_enter(e, code | 1u); + jit_prev_pc = 0xFFFFFFF0u; + left = e->jit_left + (int32_t)e->jit_bias; e->jit_bias = 0; + unpack_fl(e); +#ifdef JIT_TEST + if (jit_test_single) { e->cycles = JCYC(); jit_test_cost = 1; break; } +#endif + if (r == 1 && jit_idle_on) { + /* Idle loop: fast-forward to the next peripheral event */ + uint64_t cyc = JCYC(), t = e->last_tick + periph_next(e); + if (t > ziel) t = ziel; + if (t > cyc) { left = (int32_t)(e->evt - t); jit_st_idle++; } + continue; + } + if (r > 1 && jit_enabled != 2) { + /* Chaining: point the exit's slot (in the ldr before it) at the target block */ + uint32_t t = e->pc & 0x0FFFFFFFu; + uint32_t c = lookup(t); /* only chain targets already translated */ + uint32_t o = r - 4 - J_tgt; /* second half of the ldr.w */ + if (c && c != JIT_INTERP && o < J_size) { +#ifdef JIT_STAGE + const volatile uint8_t *cb = (const volatile uint8_t *)(uintptr_t)(J_tgt + o); /* finished code in PRAM */ + uint32_t imm = (uint32_t)(cb[0] | (cb[1] << 8)) & 0xFFFu; +#else + uint32_t imm = (uint32_t)(J_buf[o] | (J_buf[o + 1] << 8)) & 0xFFFu; +#endif + uint32_t sl = (imm - OFF(jit_slot)) / 4u; + if (sl < 600u) { e->jit_slot[sl] = c | 1u; jit_st_patch++; } + } + } + } + e->cycles = JCYC(); +#undef JCYC +#undef JNEXT +} diff --git a/emu/src/core/tc_lcd.c b/emu/src/core/tc_lcd.c new file mode 100644 index 0000000..a35effa --- /dev/null +++ b/emu/src/core/tc_lcd.c @@ -0,0 +1,90 @@ +/* LCD controller of the colour Tamagotchi, based on tamaemu lcd.c. Tracks the + * changed area so only that part is sent to the Paradise panel. */ +#include "tc.h" + +static void finish_cmd(Emu *e) +{ + Lcd *l = &e->lcd; + switch (l->cmd) { + case 0x2A: if (l->argc >= 4) { l->xs = (l->args[0] << 8) | l->args[1]; + l->xe = (l->args[2] << 8) | l->args[3]; + l->cx = l->xs; } break; + case 0x2B: if (l->argc >= 4) { l->ys = (l->args[0] << 8) | l->args[1]; + l->ye = (l->args[2] << 8) | l->args[3]; + l->cy = l->ys; } break; + default: break; + } +} + +#ifdef LCD_ROWS +/* v0.8.19: additionally the changed range per row (outside of Emu, so the save format stays the same). + * lcd_rall: redraw the whole frame (commands like invert, sleep). */ +uint8_t lcd_rx0[GRAM_H], lcd_rx1[GRAM_H], lcd_rall = 1; +#endif +static void mark(Lcd *l, int x, int y) +{ + if (x < l->dx0) l->dx0 = x; + if (x > l->dx1) l->dx1 = x; + if (y < l->dy0) l->dy0 = y; + if (y > l->dy1) l->dy1 = y; +#ifdef LCD_ROWS + if ((unsigned)y < GRAM_H) { if (x < lcd_rx0[y]) lcd_rx0[y] = (uint8_t)x; if (x > lcd_rx1[y]) lcd_rx1[y] = (uint8_t)x; } +#endif +} +static void mark_all(Lcd *l) +{ + mark(l, 0, 0); mark(l, 127, 127); +#ifdef LCD_ROWS + lcd_rall = 1; +#endif +} + +void lcd_cmd(Emu *e, uint8_t c) +{ + Lcd *l = &e->lcd; +#ifdef LCDCMD_DEBUG + if(c==1||c==0x10||c==0x11||c==0x28||c==0x29) printf("LCDCMD %02x at %.3f\n", c, (double)e->cycles/e->dev.osc3_hz); +#endif + finish_cmd(e); + l->cmd = c; l->argc = 0; l->pix_n = 0; + switch (c) { + case 0x01: l->madctl = 0; l->sleep_out = false; l->disp_on = false; l->inverted = false; + l->xs = 0; l->xe = 131; l->ys = 0; l->ye = 161; break; + case 0x10: l->sleep_out = false; mark_all(l); break; + case 0x11: l->sleep_out = true; mark_all(l); break; + case 0x20: l->inverted = false; mark_all(l); break; + case 0x21: l->inverted = true; mark_all(l); break; + case 0x28: l->disp_on = false; mark_all(l); break; + case 0x29: l->disp_on = true; mark_all(l); break; + case 0x2C: l->cx = l->xs; l->cy = l->ys; break; + default: break; + } +} + +void lcd_data(Emu *e, uint8_t d) +{ + Lcd *l = &e->lcd; + if (l->cmd == 0x2C) { + int bpp = ((l->colmod & 0x0F) == 0x05) ? 2 : 3; + l->pix_buf[l->pix_n++] = d; + if (l->pix_n >= bpp) { + uint16_t p; + if (bpp == 2) p = (uint16_t)((l->pix_buf[0] << 8) | l->pix_buf[1]); + else { + uint32_t r6 = l->pix_buf[0] >> 2, g6 = l->pix_buf[1] >> 2, b6 = l->pix_buf[2] >> 2; + p = (uint16_t)(((r6 >> 1) << 11) | (g6 << 5) | (b6 >> 1)); + } + l->pix_n = 0; + int x = l->cx, y = l->cy; + if (x >= 0 && x < GRAM_W && y >= 0 && y < GRAM_H) { + if (l->gram[y][x] != p) { l->gram[y][x] = p; mark(l, x, y); } + } + if (++l->cx > l->xe) { l->cx = l->xs; if (++l->cy > l->ye) l->cy = l->ys; } + } + return; + } + if (l->argc < 16) l->args[l->argc] = d; + l->argc++; + if (l->cmd == 0x36 && l->argc == 1) { l->madctl = d; mark_all(l); } + if (l->cmd == 0x3A && l->argc == 1) l->colmod = d; +} diff --git a/emu/src/core/tc_mem.c b/emu/src/core/tc_mem.c new file mode 100644 index 0000000..8c9d117 --- /dev/null +++ b/emu/src/core/tc_mem.c @@ -0,0 +1,372 @@ +/* Memory map, based on tamaemu mem.c. ROM reads directly from the Paradise flash, + * written sectors are kept as a copy in RAM. */ +#include "tc.h" +#define DEV const DeviceProfile *dev = &e->dev +#define FLASH_BUSY_READS 3 + +/* Sector for a ROM offset (top 64 KB: 8 KB sectors, otherwise 64 KB). */ +static void sector_of(Emu *e, uint32_t off, uint32_t *base, uint32_t *size) +{ + DEV; + if (dev->flash_top_boot && off >= dev->rom_size - 0x10000) { *base = off & ~0x1FFFu; *size = 0x2000; } + else if (!dev->flash_top_boot && off < 0x10000) { *base = off & ~0x1FFFu; *size = 0x2000; } + else { *base = off & ~0xFFFFu; *size = 0x10000; } +} + +/* Pointer to the current byte (overlay or original). Erased + * blocks read 0xFF. */ +static const uint8_t rom_ff[4] = { 0xFF, 0xFF, 0xFF, 0xFF }; +/* Start of the stored 8 KB part (0 = erased). */ +static inline const uint8_t *rom_chunk(Emu *e, uint32_t base) +{ + uint32_t b = (base >> 16) & 127u; + if ((e->pg_blk[b >> 5] >> (b & 31u)) & 1u) { + uint8_t k = e->pg_map[(base >> 13) & 1023u]; + return k == 0xFFu ? 0 : e->pg_base + (uint32_t)k * 0x2000u; + } + const uint8_t *p = e->rom_src[b]; + return p ? p + (base & 0xE000u) : 0; +} +#ifdef TC_LZ +/* 1.7.3 GUEST_LZ: cold blocks of the firmware packed in 1 KB parts (LZ4 blocks, written by the Studio). A part the guest + * reads is unpacked into one of two 1 KB buffers in the RAM at 0x20000400 (free there: 0x20000000..0x400 belongs to the + * boot, the mailboxes are at 0x20000FC0). Table: 128 u32 offsets of the block's part list (0 = not packed), per block + * 65 u32 starts (same start as the next one = erased part, 1024 bytes = stored as is). Written parts (spare pages) win. */ +const uint8_t *tc_lz_tab; +uint32_t tc_lz_gone[4]; /* packed blocks the guest erased: they read empty */ +#define LZ_RAM ((uint8_t *)0x20000400u) +static uint32_t lz_tag[2], lz_rr; /* part number + 1 in each buffer (0 = empty) */ +static uint32_t lz_n(const uint8_t **ps, uint32_t n) +{ + if (n == 15u) { uint32_t x; do { x = *(*ps)++; n += x; } while (x == 255u); } + return n; +} +__attribute__((noinline, minsize)) static void lz_dec(uint8_t *d, const uint8_t *s) +{ + uint8_t *end = d + 0x400u; + for (;;) { + uint32_t t = *s++, n = lz_n(&s, t >> 4); + while (n-- && d < end) *d++ = *s++; + if (d >= end) return; + const uint8_t *m = d - ((uint32_t)s[0] | ((uint32_t)s[1] << 8)); s += 2; + n = lz_n(&s, t & 15u) + 4u; + while (n-- && d < end) *d++ = *m++; + } +} +/* the 1 KB part at ROM offset off, unpacked (0 = the block is not packed) */ +__attribute__((noinline, minsize)) static const uint8_t *lz_part(uint32_t off) +{ + uint32_t b = (off >> 16) & 127u, tag = (off >> 10) + 1u; + const uint32_t *t = (const uint32_t *)tc_lz_tab; + if (!t || ((tc_lz_gone[b >> 5] >> (b & 31u)) & 1u) || !t[b]) return 0; + for (uint32_t k = 0; k < 2u; k++) if (lz_tag[k] == tag) return LZ_RAM + (k << 10); + const uint32_t *l = (const uint32_t *)(tc_lz_tab + t[b]) + ((off >> 10) & 63u); + uint32_t a = l[0], z = l[1], i = lz_rr; lz_rr ^= 1u; + uint8_t *d = LZ_RAM + (i << 10); + if (z == a) memset(d, 0xFF, 0x400u); + else if (z - a >= 0x400u) memcpy(d, tc_lz_tab + a, 0x400u); + else lz_dec(d, tc_lz_tab + a); + lz_tag[i] = tag; + return d; +} +/* an 8 KB copy for a written sector (0 = the block is not packed) */ +__attribute__((noinline, minsize)) static int lz_fill(uint8_t *d, uint32_t base) +{ + if (!lz_part(base)) return 0; + for (uint32_t k = 0; k < OVL_SIZE; k += 0x400u) memcpy(d + k, lz_part(base + k), 0x400u); + return 1; +} +#endif +static inline const uint8_t *rom_src_ptr(Emu *e, uint32_t off) +{ + uint32_t b = (off >> 16) & 127u; + if ((e->pg_blk[b >> 5] >> (b & 31u)) & 1u) { + const uint8_t *c = rom_chunk(e, off & ~0x1FFFu); +#ifdef TC_LZ + if (!c) { const uint8_t *z = lz_part(off); if (z) return z + (off & 0x3FFu); } +#endif + return c ? c + (off & 0x1FFFu) : rom_ff; + } + const uint8_t *p = e->rom_src[b]; + return p ? p + (off & 0xFFFFu) : rom_ff; +} +/* Slow path: parameter block, written copies, spare pages, erased blocks. */ +__attribute__((noinline)) static const uint8_t *rom_slow(Emu *e, uint32_t off) +{ + for (int i = 0; i < e->ovl.n; i++) + if (off - e->ovl.base[i] < OVL_SIZE) return e->ovl.mem[i] + (off - e->ovl.base[i]); + return rom_src_ptr(e, off); +} +/* rom_blk is set only for blocks without written copies (see tc_blk_update). */ +static inline const uint8_t *rom_ptr(Emu *e, uint32_t off) +{ + const uint8_t *b = e->rom_blk[(off >> 16) & 127u]; + return b ? b + (off & 0xFFFFu) : rom_slow(e, off); +} + +/* Get a writable copy of the sector (create it if needed). Only + * 8 KB sectors fit in a slot; writes to larger sectors are lost. */ +int (*tc_ovl_evict)(Emu *e); +#ifdef TC_LZ +__attribute__((noinline, minsize)) /* 1.7.3: room for the unpacking (only when the guest writes its flash) */ +#endif +static uint8_t *rom_wptr(Emu *e, uint32_t off) +{ + for (int i = 0; i < e->ovl.n; i++) + if (off - e->ovl.base[i] < OVL_SIZE) return e->ovl.mem[i] + (off - e->ovl.base[i]); + uint32_t base, size; sector_of(e, off, &base, &size); + if (size > OVL_SIZE) { + /* 64 KB sector: kept in 8 KB parts like the parameter sectors (v0.9.2). Before, these + * writes were lost and the guest could hang or crash (for example when buying an item). */ + if (!tc_big_erase) { e->flash_lost_writes++; return 0; } + base = off & ~(OVL_SIZE - 1u); + } + for (int pass = 0; pass < 2; pass++) { + if (pass && !(tc_ovl_evict && tc_ovl_evict(e))) break; + for (int i = 0; i < OVL_SLOTS; i++) + if (e->ovl.mem[i] && e->ovl.base[i] == 0xFFFFFFFFu) { + e->ovl.base[i] = base; + { const uint8_t *c = rom_chunk(e, base); + if (c) memcpy(e->ovl.mem[i], c, OVL_SIZE); +#ifdef TC_LZ + else if (lz_fill(e->ovl.mem[i], base)) {} +#endif + else memset(e->ovl.mem[i], 0xFF, OVL_SIZE); } + if (i >= e->ovl.n) e->ovl.n = i + 1; + if (base - e->par_base >= 0x10000u) { + uint32_t b = (base >> 16) & 127u; + e->ovl_blk[b >> 5] |= 1u << (b & 31u); + tc_blk_update(e, b); + } +#ifdef TC_JIT + else jit_rom_update(e, base); +#endif + return e->ovl.mem[i] + (off - base); + } + } + e->flash_lost_writes++; + return 0; +} + +int (*tc_big_erase)(Emu *e, uint32_t base); +/* Fast read pointers of a 64 KB block: direct only while no written copy exists. */ +__attribute__((noinline)) void tc_blk_update(Emu *e, uint32_t b) +{ + b &= 127u; + if ((b << 16) - e->par_base < 0x10000u) return; + int busy = (int)(((e->ovl_blk[b >> 5] | e->pg_blk[b >> 5]) >> (b & 31u)) & 1u); + e->rom_blk[b] = busy ? 0 : e->rom_src[b]; + e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; +#ifdef TC_JIT + jit_rom_update(e, b << 16); + e->jit_flush = 1; /* translated code may have read this block */ +#endif +} +__attribute__((noinline)) void tc_ovl_free(Emu *e, int i) +{ + uint32_t base = e->ovl.base[i]; + if (base == 0xFFFFFFFFu) return; + e->ovl.base[i] = 0xFFFFFFFFu; + e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; + if (base - e->par_base < 0x10000u) { +#ifdef TC_JIT + jit_rom_update(e, base); +#endif + return; + } + uint32_t b = (base >> 16) & 127u; + for (int k = 0; k < e->ovl.n; k++) if (e->ovl.base[k] != 0xFFFFFFFFu && ((e->ovl.base[k] >> 16) & 127u) == b) return; + e->ovl_blk[b >> 5] &= ~(1u << (b & 31u)); + tc_blk_update(e, b); +} +static void flash_erase_sector(Emu *e, uint32_t off) +{ + uint32_t base, size; sector_of(e, off, &base, &size); + uint8_t *p = 0; + if (size > OVL_SIZE) { + /* drop the written copies of this sector, then erase the backing store */ + for (int i = 0; i < e->ovl.n; i++) if (e->ovl.base[i] - base < size) tc_ovl_free(e, i); + e->flash_big_ops++; + if (!(tc_big_erase && tc_big_erase(e, base))) e->flash_lost_writes++; + tc_blk_update(e, base >> 16); + } else p = rom_wptr(e, base); + if (p) memset(p, 0xFF, size); + e->flash_dirty = true; + e->flash_busy = FLASH_BUSY_READS; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; + e->flash_op_data = 0xFFFF; + e->flash_toggle = false; +} + +static uint16_t flash_status(Emu *e) +{ + e->flash_toggle = !e->flash_toggle; + uint16_t s = 0; + if (!((e->flash_op_data >> 7) & 1)) s |= 0x80; + if (e->flash_toggle) s |= 0x40; + if (--e->flash_busy <= 0) e->flash_busy = 0; + return s; +} + +static void flash_write(Emu *e, uint32_t a, uint32_t v, int size) +{ + DEV; + uint32_t off = a - dev->rom_base; + uint8_t d = (uint8_t)v; + if (e->flash_state == 3) { + uint16_t final = 0; + for (int i = 0; i < size; i++) { + uint32_t o = (off + (uint32_t)i) & (dev->rom_size - 1); + uint8_t *p = rom_wptr(e, o); + uint8_t nb = p ? (*p &= (uint8_t)(v >> (8 * i))) : rom_ptr(e, o)[0]; + final |= (uint16_t)nb << (8 * i); + } + e->flash_dirty = true; + e->flash_state = 0; + e->flash_busy = FLASH_BUSY_READS; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; + e->flash_op_data = size >= 2 ? final : (uint16_t)(0xFF00 | final); + e->flash_toggle = false; + return; + } + if (d == 0xF0) { e->flash_state = 0; e->flash_autoselect = false; return; } + switch (e->flash_state) { + case 0: if (d == 0xAA) e->flash_state = 1; break; + case 1: e->flash_state = (d == 0x55) ? 2 : 0; break; + case 2: + if (d == 0xA0) e->flash_state = 3; + else if (d == 0x80) e->flash_state = 4; + else if (d == 0x90) { e->flash_autoselect = true; e->flash_state = 0; e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; } + else e->flash_state = 0; + break; + case 4: e->flash_state = (d == 0xAA) ? 5 : 0; break; + case 5: e->flash_state = (d == 0x55) ? 6 : 0; break; + case 6: + if (d == 0x30) flash_erase_sector(e, off); + e->flash_state = 0; /* chip erase (0x10) is ignored */ + break; + default: e->flash_state = 0; break; + } +} + +static uint8_t flash_read8(Emu *e, uint32_t a) +{ + DEV; + if (e->flash_busy) return (uint8_t)flash_status(e); + if (e->flash_autoselect) { + uint32_t w = (a - dev->rom_base) >> 1; + if ((w & 0xFF) == 0) return (a & 1) ? 0x00 : 0x01; + return (a & 1) ? 0x22 : 0xF6; + } + return *rom_ptr(e, a - dev->rom_base); +} + +#ifdef LCDRD_DEBUG +extern uint32_t g_lcdrd, g_lcdrd_pc[16]; extern int g_np; +#endif +uint8_t mem_read8(Emu *e, uint32_t a) +{ + DEV; +#ifdef LCDRD_DEBUG + if (a == dev->lcd_cmd_addr || a == dev->lcd_data_addr) { g_lcdrd++; int k; for (k = 0; k < g_np && g_lcdrd_pc[k] != e->pc; k++); if (k == g_np && g_np < 16) g_lcdrd_pc[g_np++] = e->pc; } +#endif + if (a - dev->rom_base < dev->rom_size) { + if (e->flash_busy || e->flash_autoselect) return flash_read8(e, a); + return *rom_ptr(e, a - dev->rom_base); + } + if (a - dev->a0ram_base < dev->a0ram_size) return e->a0ram[a - dev->a0ram_base]; + if (a - dev->io_base < dev->io_size) return periph_read8(e, a); + if (a - dev->ivram_base < dev->ivram_size) return e->ivram[a - dev->ivram_base]; + if (a - dev->dstram_base < dev->dstram_size) return e->dstram[a - dev->dstram_base]; + return 0; +} + +void mem_write8(Emu *e, uint32_t a, uint8_t v) +{ + DEV; + if (a - dev->a0ram_base < dev->a0ram_size) { e->a0ram[a - dev->a0ram_base] = v; return; } + if (a == dev->lcd_cmd_addr) { e->lcd_writes++; lcd_cmd(e, v); return; } + if (a == dev->lcd_data_addr) { e->lcd_writes++; lcd_data(e, v); return; } + if (a - dev->io_base < dev->io_size) { periph_write8(e, a, v); return; } + if (a - dev->ivram_base < dev->ivram_size) { e->ivram[a - dev->ivram_base] = v; return; } + if (a - dev->dstram_base < dev->dstram_size) { e->dstram[a - dev->dstram_base] = v; return; } + if (a - dev->rom_base < dev->rom_size) { flash_write(e, a, v, 1); return; } +} + +uint16_t mem_read16(Emu *e, uint32_t a) +{ + DEV; + if (a - dev->rom_base < dev->rom_size - 1) { + if (e->flash_busy) return flash_status(e); + if (e->flash_autoselect) + return (uint16_t)(flash_read8(e, a) | (flash_read8(e, a + 1) << 8)); + const uint8_t *p = rom_ptr(e, a - dev->rom_base); + return (uint16_t)(p[0] | (p[1] << 8)); + } + if (a - dev->a0ram_base < dev->a0ram_size - 1) { + const uint8_t *p = e->a0ram + (a - dev->a0ram_base); + return (uint16_t)(p[0] | (p[1] << 8)); + } + return (uint16_t)(mem_read8(e, a) | (mem_read8(e, a + 1) << 8)); +} + +uint32_t mem_read32(Emu *e, uint32_t a) +{ + DEV; + if (a - dev->rom_base < dev->rom_size - 3) { + if (e->flash_busy || e->flash_autoselect) + return (uint32_t)mem_read16(e, a) | ((uint32_t)mem_read16(e, a + 2) << 16); + const uint8_t *p = rom_ptr(e, a - dev->rom_base); + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + } + if (a - dev->a0ram_base < dev->a0ram_size - 3) { + const uint8_t *p = e->a0ram + (a - dev->a0ram_base); + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + } + if (a - dev->io_base < dev->io_size - 3) return periph_read32(e, a); + return (uint32_t)mem_read16(e, a) | ((uint32_t)mem_read16(e, a + 2) << 16); +} + +void mem_write16(Emu *e, uint32_t a, uint16_t v) +{ + DEV; + if (a - dev->a0ram_base < dev->a0ram_size - 1) { + e->a0ram[a - dev->a0ram_base] = (uint8_t)v; + e->a0ram[a - dev->a0ram_base + 1] = (uint8_t)(v >> 8); + return; + } + if (a - dev->rom_base < dev->rom_size - 1) { flash_write(e, a, v, 2); return; } + mem_write8(e, a, (uint8_t)v); + mem_write8(e, a + 1, (uint8_t)(v >> 8)); +} + +void mem_write32(Emu *e, uint32_t a, uint32_t v) +{ + DEV; + if (a - dev->a0ram_base < dev->a0ram_size - 3) { + uint8_t *p = e->a0ram + (a - dev->a0ram_base); + p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); + return; + } + if (a - dev->io_base < dev->io_size - 3) { periph_write32(e, a, v); return; } + if (a - dev->rom_base < dev->rom_size - 3) { + flash_write(e, a, v & 0xFFFF, 2); + flash_write(e, a + 2, v >> 16, 2); + return; + } + mem_write16(e, a, (uint16_t)v); + mem_write16(e, a + 2, (uint16_t)(v >> 16)); +} + +/* Set the instruction window for fast fetch (or clear it if none fits). */ +void tc_fetch_window(Emu *e, uint32_t pc) +{ + DEV; + e->fw_len = 0; e->fw_lo = 0xFFFFFFFFu; + if (pc - dev->rom_base < dev->rom_size && !e->flash_busy && !e->flash_autoselect) { + /* 64 KB window of the block */ + const uint8_t *b = e->rom_blk[(pc - dev->rom_base) >> 16]; + if (!b) return; + e->fw_ptr = b; e->fw_lo = pc & ~0xFFFFu; e->fw_len = 0x10000u; return; } + if (pc - dev->a0ram_base < dev->a0ram_size) { e->fw_ptr = e->a0ram; e->fw_lo = dev->a0ram_base; e->fw_len = dev->a0ram_size; return; } + if (pc - dev->ivram_base < dev->ivram_size) { e->fw_ptr = e->ivram; e->fw_lo = dev->ivram_base; e->fw_len = dev->ivram_size; return; } + if (pc - dev->dstram_base < dev->dstram_size) { e->fw_ptr = e->dstram; e->fw_lo = dev->dstram_base; e->fw_len = dev->dstram_size; return; } +} diff --git a/emu/src/core/tc_periph.c b/emu/src/core/tc_periph.c new file mode 100644 index 0000000..a7538f3 --- /dev/null +++ b/emu/src/core/tc_periph.c @@ -0,0 +1,583 @@ +/* Peripherals based on tamaemu periph.c, without infrared/NFC/sound protocols and + * without floating point. Time comes from counted cycles. */ +#include "tc.h" +#define CMU_BASE 0x301B00u +#define IOB(a) e->ioram[(a) - e->dev.io_base] +#define IR_BASE 0x300B10u +#define IR_RXDATA (IR_BASE + 1u) +#define IR_STAT (IR_BASE + 2u) +#define IR_LAST (IR_BASE + 7u) +#define SIO_RX 0x301700u +#define SIO_STAT 0x301714u + +static uint32_t ioram_r32(Emu *e, uint32_t a) +{ + uint8_t *p = e->ioram + (a - e->dev.io_base); + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} +static void ioram_w32(Emu *e, uint32_t a, uint32_t v) +{ + uint8_t *p = e->ioram + (a - e->dev.io_base); + p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); +} + +TC_SRAM static void cmu_recalc(Emu *e) +{ + Cmu *c = &e->cmu; + uint32_t oscsel = (c->sccr >> 2) & 3; + uint32_t osc3div = (c->sccr >> 8) & 7; + uint32_t mclkdiv = (c->sccr >> 12) & 1; + uint32_t pllindiv = (c->sccr >> 20) & 0xF; + uint32_t pllpowr = c->pllc & 1; + uint32_t plln = (c->pllc >> 4) & 0xF; + uint32_t f; + if (oscsel == 1) f = 32768u; + else if (oscsel == 3 && pllpowr) f = c->osc3_hz / (pllindiv + 1) * (plln + 1); + else f = c->osc3_hz >> osc3div; + if (mclkdiv) f >>= 1; + c->mclk_hz = f ? f : 1; +} + +static uint32_t mclk(Emu *e) { return e->cmu.mclk_hz ? e->cmu.mclk_hz : e->dev.osc3_hz; } + +TC_SRAM static void cmu_write32(Emu *e, uint32_t a, uint32_t v) +{ + Cmu *c = &e->cmu; + uint32_t off = a - CMU_BASE; + if (off == 0x24) { c->unlocked = ((v & 0xFF) == 0x96); ioram_w32(e, a, v); return; } + if (off <= 0x14 && !c->unlocked) return; + ioram_w32(e, a, v); + switch (off) { + case 0x08: c->sccr = v; cmu_recalc(e); break; + case 0x0C: c->pllc = v; cmu_recalc(e); break; + case 0x14: c->opt = v; break; + default: break; + } +} + +static void itc_scan(Emu *e); + +/* ---- PN512 NFC chip of the 4U/4U+ (1.6.8) -------------------------------------------------- + * The 4U firmware talks to its PN512 over the IR UART (0x300B10 TX, 0x300B11 RX) all the time: it + * wakes the chip, arms field detection and waits for answers. Without a chip every read ran into + * a long spin timeout, the firmware hardly ever went idle and buttons felt slow (two presses). + * Like tamaemu's pn512.c, without radio: a register file, commands finish at once, every write is + * acknowledged with its address, a read returns the register. Not saved with the session (the chip + * powers up again). */ +#define IR_TRIG (IR_BASE + 5u) +static struct { uint8_t reg[0x40], q[16], fifo_n, q_n, wr, tx; } g_pn; +static const uint8_t pn_init[] = { 0x01, 0x20, 0x11, 0x3F, 0x14, 0x80, 0x15, 0x40, 0x18, 0x84, 0x19, 0x4D, 0x1F, 0xEB, 0x26, 0x48, 0x27, 0x88, 0x37, 0x82 }; +TC_SRAM static void pn_host_byte(Emu *e, uint8_t b) +{ + (void)e; + uint8_t *r = g_pn.reg, a = g_pn.wr & 0x3F, v; + if (!r[0x37]) for (unsigned i = 0; i < sizeof pn_init; i += 2) r[pn_init[i]] = pn_init[i + 1]; /* power up */ + if (g_pn.wr) { /* register write, acknowledged with the address */ + g_pn.wr = 0; v = b; + if (a == 0x01) { /* Command: everything finishes at once */ + uint8_t c = v & 0x0F; + if (c == 0x0F) { r[0x37] = 0; g_pn.fifo_n = 0; } /* SoftReset: power-up values again */ + else r[1] = (uint8_t)((v & 0x30) | ((c == 0x0C || c == 0x08 || c == 0x0D) ? c : 0)); + if (c == 0x03) r[5] |= 0x04; /* CalcCRC done */ + if (c == 0x04) r[4] |= 0x50; /* Transmit: Tx, Idle */ + } else if (a == 0x04 || a == 0x05) { if (v & 0x80) r[a] |= v & 0x7F; else r[a] &= (uint8_t)~v; } + else if (a == 0x09) { if (g_pn.fifo_n < 64) g_pn.fifo_n++; } + else if (a == 0x0A) { if (v & 0x80) g_pn.fifo_n = 0; } + else if (a == 0x0C) { if (v & 0x40) r[4] |= 0x01; if (v & 0x20) g_pn.fifo_n = 10; r[a] = v & 0x1F; } + else if (a < 0x06 || a > 0x08) r[a] = v; + } else if (b & 0x80) { /* register read */ + a = b & 0x3F; v = r[a]; + if (a == 0x09) { v = (uint8_t)(0xF0 ^ g_pn.fifo_n); if (g_pn.fifo_n) g_pn.fifo_n--; } /* FIFO: some ID bytes */ + else if (a == 0x0A) v = g_pn.fifo_n; + else if (a == 0x07) v = 0x60; + else if (a == 0x08) v = ((r[1] & 0x0F) == 0x0C || (r[1] & 0x0F) == 0x08) ? 0x05 : 0x00; + a = v; + } else { g_pn.wr = (uint8_t)(0x40 | b); return; } + if (g_pn.q_n < sizeof g_pn.q) g_pn.q[g_pn.q_n++] = a; + g_pn.tx = 1; +} +TC_SRAM static void pn_tick(Emu *e) +{ + uint8_t f = 0; + if (g_pn.tx) { g_pn.tx = 0; f = 0x20; } /* TX done */ + if (g_pn.q_n && IOB(IR_TRIG) && !(IOB(IR_STAT) & 0x01u)) { /* next answer byte, RX */ + IOB(IR_RXDATA) = g_pn.q[0]; g_pn.q_n--; + for (unsigned i = 0; i < g_pn.q_n; i++) g_pn.q[i] = g_pn.q[i + 1]; + IOB(IR_STAT) |= 0x01u; f |= 0x10; + } + if (f) { IOB(0x300286) |= f; itc_scan(e); } +} + +#ifdef TC_IRLINK +/* ---- 1.6.9: infrared to another Paradise --------------------------------------------------------- + * As tamaemu's periph.c (ir_tx_byte, ir_rx_poll, the session gating of the P's and the peer-detect flag), + * but the bytes go to the platform (tc_ir_out) and come from it (tc_ir_avail, tc_ir_in) instead of + * tamaemu's link.c (no time stamps or collisions: the two devices pass the bytes on at once). State outside + * Emu, so saved sessions stay valid. Off until tc_ir_setup (then also the TX-ready bit follows the byte time). */ +#define IR_BAUD_LO (IR_BASE + 6u) +#define IR_BAUD_HI (IR_BASE + 7u) +#define SIO_TX 0x301704u +#define IR_CTX_STATE 0x4E4u +int tc_ir_avail(void); +int tc_ir_in(void); +void tc_ir_out(uint8_t b); +static struct { uint64_t tx_ready_at, rx_next_at; uint32_t mode_flag, ctx_ptr; uint8_t on; } g_ir; +void tc_ir_setup(uint32_t mode_flag, uint32_t ctx_ptr) { g_ir.mode_flag = mode_flag; g_ir.ctx_ptr = ctx_ptr; g_ir.on = 1; } +/* 8N1 byte time: the IR divisor clock is 576 kHz (tamaemu: base / (div + 1), 300..1000000 baud, else 115200) */ +TC_SRAM static uint64_t ir_byte_cycles(Emu *e) +{ + uint32_t div = (uint32_t)IOB(IR_BAUD_LO) | ((uint32_t)(IOB(IR_BAUD_HI) & 0xF) << 16); + uint32_t c = div + 1u > 1920u ? mclk(e) / 11520u : mclk(e) / 1000u * 10u * (div + 1u) / 576u; /* 32 bit: no 64-bit division on the device */ + return c ? c : 1u; +} +TC_SRAM static void ir_raise(Emu *e, int bit) { IOB(0x300286) |= (uint8_t)(1u << bit); itc_scan(e); } +TC_SRAM static void ir_tx_done_raise(Emu *e) +{ + uint8_t en = IOB(0x300276); + if (en & 0x20) ir_raise(e, 5); else if (en & 0x08) ir_raise(e, 3); else if (en & 0x10) ir_raise(e, 4); +} +TC_SRAM static void ir_tx_byte(Emu *e, uint8_t b) +{ + tc_ir_out(b); + IOB(IR_STAT) &= (uint8_t)~0x20u; /* TX busy off, TX ready after one byte time */ + g_ir.tx_ready_at = e->cycles + ir_byte_cycles(e); +} +TC_SRAM static uint8_t ram_peek8(Emu *e, uint32_t a) +{ + const DeviceProfile *d = &e->dev; + if (a - d->a0ram_base < d->a0ram_size) return e->a0ram[a - d->a0ram_base]; + if (a - d->ivram_base < d->ivram_size) return e->ivram[a - d->ivram_base]; + if (a - d->dstram_base < d->dstram_size) return e->dstram[a - d->dstram_base]; + return 0; +} +/* session state: a byte (P's: 2 visit/connect, 1 item exchange) or one reached through a context pointer (iD L) */ +TC_SRAM static uint8_t ir_session(Emu *e) +{ + if (g_ir.mode_flag) return ram_peek8(e, g_ir.mode_flag); + if (!g_ir.ctx_ptr) return 0; + uint32_t p = g_ir.ctx_ptr, c = (uint32_t)ram_peek8(e, p) | (uint32_t)ram_peek8(e, p + 1) << 8 | (uint32_t)ram_peek8(e, p + 2) << 16 | (uint32_t)ram_peek8(e, p + 3) << 24; + const DeviceProfile *d = &e->dev; + if (!c || (c - d->a0ram_base >= d->a0ram_size && c - d->ivram_base >= d->ivram_size && c - d->dstram_base >= d->dstram_size)) return 0; + return ram_peek8(e, c + IR_CTX_STATE); +} +TC_SRAM static void ir_rx_poll(Emu *e) +{ + /* receiver not armed (or the P's not in a session): the byte is lost, but the peer-detect flag rises */ + if ((g_ir.mode_flag && !ir_session(e)) || !IOB(IR_TRIG)) { + while (tc_ir_avail()) { + (void)tc_ir_in(); + if (ir_session(e) != 1) { IOB(0x300287) |= 0x08u; itc_scan(e); } + } + return; + } + if (e->cycles < g_ir.rx_next_at) return; + if ((IOB(IR_STAT) & 0x01u) && e->cycles < g_ir.rx_next_at + 64u * ir_byte_cycles(e)) return; /* unread: wait, then overrun */ + if (!tc_ir_avail()) return; + uint8_t b = (uint8_t)tc_ir_in(); + IOB(SIO_RX) = b; IOB(IR_RXDATA) = b; + IOB(IR_STAT) |= 0x01u; + g_ir.rx_next_at = e->cycles + ir_byte_cycles(e); /* one byte per byte time */ + ir_raise(e, 4); +} +TC_SRAM static void ir_tick(Emu *e) +{ + if (g_ir.tx_ready_at && e->cycles >= g_ir.tx_ready_at) { g_ir.tx_ready_at = 0; ir_tx_done_raise(e); } + if (!e->dev.ir_gpio && !e->dev.nfc_pn512) ir_rx_poll(e); +} +TC_SRAM static void ir_write8(Emu *e, uint32_t a, uint8_t v) +{ + uint8_t old_trig = IOB(IR_TRIG); + e->ioram[a - e->dev.io_base] = v; + if (a == IR_BASE) ir_tx_byte(e, v); + if (a == IR_TRIG && v && !old_trig) g_ir.rx_next_at = e->cycles + ir_byte_cycles(e); /* receiver start: one byte time */ +} +#endif + +uint32_t g_tc_rtc_wr; +void periph_write32(Emu *e, uint32_t a, uint32_t v) +{ +#ifdef TC_IRLINK + if (g_ir.on && a == SIO_TX) { ioram_w32(e, a, v); ir_tx_byte(e, (uint8_t)v); return; } +#endif + if (a >= 0x301910 && a <= 0x30192B) g_tc_rtc_wr++; + if (a - CMU_BASE <= 0x24) { cmu_write32(e, a, v); return; } + if (a == 0x301900) { if (v & 1) IOB(0x301900) &= (uint8_t)~1u; return; } + ioram_w32(e, a, v); +} + +uint32_t periph_read32(Emu *e, uint32_t a) +{ + if (a == SIO_STAT) return ioram_r32(e, a) & ~0x40u; + if (a == SIO_RX) { uint32_t b = ioram_r32(e, a); IOB(IR_STAT) &= (uint8_t)~0x01u; return b; } + return ioram_r32(e, a); +} + +#ifdef IOLOG +extern int g_iolog; +#endif +void periph_write8(Emu *e, uint32_t a, uint8_t v) +{ +#ifdef IOLOG + if (g_iolog) printf("IO %.4f %06x <- %02x pc=%08x\n", (double)e->cycles / e->dev.osc3_hz, a, v, e->pc); +#endif +#ifndef NO_PN + if (e->dev.nfc_pn512 && a == IR_BASE) { e->ioram[a - e->dev.io_base] = v; pn_host_byte(e, v); return; } +#endif +#ifdef TC_IRLINK + if (g_ir.on && a >= IR_BASE && a <= IR_LAST && !e->dev.nfc_pn512) { ir_write8(e, a, v); return; } +#endif + if (a - CMU_BASE <= 0x27) { + uint32_t word = a & ~3u; + uint32_t cur = ioram_r32(e, word); + int sh = (a & 3) * 8; + cmu_write32(e, word, (cur & ~(0xFFu << sh)) | ((uint32_t)v << sh)); + return; + } + if (a >= 0x300280 && a <= 0x30028F) { e->ioram[a - e->dev.io_base] &= (uint8_t)~v; itc_scan(e); return; } + if (a == 0x3002A9) { e->ioram[a - e->dev.io_base] &= (uint8_t)~v; itc_scan(e); return; } + if (a == 0x301900) { if (v & 1) e->ioram[a - e->dev.io_base] &= (uint8_t)~1u; return; } + if (a >= 0x301910 && a <= 0x30192B) g_tc_rtc_wr++; /* 1.6.8: the game sets its clock (main.c puts the Paradise's time back) */ + if (a == 0x300544 && (v & 0x06)) { /* battery measurement: immediate, healthy */ + e->ioram[a - e->dev.io_base] = v; + IOB(0x300540) = 0x50; IOB(0x300541) = 0x03; + IOB(0x300548) = 0x50; IOB(0x300549) = 0x03; + IOB(0x300287) |= 2; + itc_scan(e); + return; + } + if (a >= 0x300780 && a <= 0x3007AF) { + int x = (int)((a - 0x300780) / 8); + int off = (int)((a - 0x300780) % 8); + if (off == 6) { + if (v & 2) { e->t16[x].counter = 0; e->t16[x].accum = 0; } + e->ioram[a - e->dev.io_base] = v & (uint8_t)~2u; + return; + } + if (off == 4) { + e->t16[x].counter = (uint16_t)((e->t16[x].counter & 0xFF00) | v); + e->t16[x].a_fired = 0; + e->ioram[a - e->dev.io_base] = v; + return; + } + if (off == 5) { + e->t16[x].counter = (uint16_t)((e->t16[x].counter & 0x00FF) | ((uint16_t)v << 8)); + e->ioram[a - e->dev.io_base] = v; + return; + } + } + e->ioram[a - e->dev.io_base] = v; + if ((a >= 0x300270 && a <= 0x30027F) || a == 0x3002A6) itc_scan(e); +} + +uint8_t periph_read8(Emu *e, uint32_t a) +{ + if (a == 0x300380) { + uint8_t p06 = e->dev.debug_strap_high ? 0x00 : 0x40; /* charger, no debug */ + uint8_t v = (uint8_t)((0x07u | p06) & ~(e->btn_mask & 7)); + if (e->dev.ir_gpio) v |= (uint8_t)(1u << e->dev.ir_gpio_rx_bit); /* IR idles high */ + return v; + } + if (a == IR_RXDATA) { uint8_t v = e->ioram[a - e->dev.io_base]; IOB(IR_STAT) &= (uint8_t)~0x01u; return v; } +#ifdef TC_IRLINK + if (a == IR_STAT && g_ir.on) { uint8_t st = e->ioram[a - e->dev.io_base]; return (uint8_t)(e->cycles >= g_ir.tx_ready_at ? st | 0x02u : st & ~0x02u); } +#endif + if (a == IR_STAT) return (uint8_t)(e->ioram[a - e->dev.io_base] | 0x02u); + return e->ioram[a - e->dev.io_base]; +} + +void periph_buttons(Emu *e, uint8_t mask) +{ + uint8_t newly = mask & (uint8_t)~e->btn_mask & 7; + e->btn_mask = mask & 7; + if (newly) { IOB(0x300280) |= newly; itc_scan(e); } +} + +static const uint32_t presc_div[8] = {1, 2, 4, 16, 64, 256, 1024, 4096}; + +static void t16_set_flag(Emu *e, int x, int is_a) +{ + uint32_t freg = 0x300282 + (uint32_t)(x / 2); + int bit = (x & 1) ? (is_a ? 7 : 6) : (is_a ? 3 : 2); + IOB(freg) |= (uint8_t)(1u << bit); +} + +/* Like the counting loop in the original, but in jumps instead of cycle by cycle. */ +static void t16_run(Emu *e, int x, uint32_t clocks) +{ + uint32_t base = 0x300780 + (uint32_t)x * 8; + uint16_t cra = (uint16_t)(IOB(base) | (IOB(base + 1) << 8)); + uint16_t crb = (uint16_t)(IOB(base + 2) | (IOB(base + 3) << 8)); + T16 *t = &e->t16[x]; + uint32_t c = t->counter; + while (clocks) { + uint32_t to_b = (crb > c) ? (uint32_t)crb - c : 1u; + if (clocks < to_b) { + c += clocks; clocks = 0; + if (cra && !t->a_fired && c >= cra) { t16_set_flag(e, x, 1); t->a_fired = 1; } + break; + } + c += to_b; clocks -= to_b; + if (cra && !t->a_fired && c >= cra) t16_set_flag(e, x, 1); + t16_set_flag(e, x, 0); + c = 0; t->a_fired = 0; + if (crb && clocks >= crb) { /* whole periods: flags are already set */ + if (cra && cra <= crb) t16_set_flag(e, x, 1); + clocks %= crb; + } + } + t->counter = (uint16_t)c; + IOB(base + 4) = (uint8_t)c; + IOB(base + 5) = (uint8_t)(c >> 8); +} + +static void itc_consider(Emu *e, uint32_t vec, uint8_t lvl) +{ + e->wake_req = true; + if (lvl > e->pending_level || !e->pending_irq) { e->pending_irq = vec; e->pending_level = lvl; } +} + +static void itc_scan(Emu *e) +{ + static const uint8_t vec_b[6] = {30, 34, 38, 42, 46, 50}; + e->pending_irq = 0; e->pending_level = 0; e->wake_req = false; + { + uint8_t act = IOB(0x300270) & IOB(0x300280) & 0x0F; + for (int p = 0; p < 4; p++) { + if (!(act & (1u << p))) continue; + uint8_t lr = IOB(0x300260 + (uint32_t)(p / 2)); + uint8_t lvl = (p & 1) ? (lr >> 4) & 7 : lr & 7; + itc_consider(e, 16u + (uint32_t)p, lvl); + } + } + for (int x = 0; x < 6; x++) { + uint32_t en = 0x300272 + (uint32_t)(x / 2), fl = 0x300282 + (uint32_t)(x / 2); + uint8_t act = IOB(en) & IOB(fl); + int b_bit = (x & 1) ? 6 : 2, a_bit = (x & 1) ? 7 : 3; + uint8_t lvl_reg = IOB(0x300266 + (uint32_t)(x / 2)); + uint8_t lvl = (x & 1) ? (lvl_reg >> 4) & 7 : lvl_reg & 7; + if (act & (1u << b_bit)) itc_consider(e, vec_b[x], lvl); + if (act & (1u << a_bit)) itc_consider(e, vec_b[x] + 1u, lvl); + } + if (IOB(0x300277) & IOB(0x300287) & 4) { uint8_t lvl = (IOB(0x30026A) >> 4) & 7; itc_consider(e, 65, lvl ? lvl : 1); } + if (IOB(0x300277) & IOB(0x300287) & 2) { uint8_t lvl = IOB(0x30026A) & 7; itc_consider(e, 64, lvl ? lvl : 1); } + if (IOB(0x300277) & IOB(0x300287) & 0x08u) itc_consider(e, 68, 4); + { + uint8_t act = IOB(0x300276) & IOB(0x300286); + for (int b = 3; b <= 5; b++) + if (act & (uint8_t)(1u << b)) itc_consider(e, (uint32_t)(57 + b), 4); + } +} + +static uint8_t bcd_inc(uint8_t v, uint8_t wrap_after) +{ + v++; + if ((v & 0xF) > 9) v = (uint8_t)((v & 0xF0) + 0x10); + if (v > wrap_after) return 0xFF; + return v; +} +static const uint8_t month_days[13] = {0,0x31,0x28,0x31,0x30,0x31,0x30,0x31,0x31,0x30,0x31,0x30,0x31}; + +#ifdef HOST +uint32_t g_host_rtc_secs; +#endif +TC_SRAM static void rtc_count_second(Emu *e) +{ +#ifdef HOST + g_host_rtc_secs++; +#endif + uint8_t v = bcd_inc(IOB(0x301910), 0x59); + IOB(0x301910) = (v == 0xFF) ? 0 : v; if (v != 0xFF) return; + v = bcd_inc(IOB(0x301914), 0x59); + IOB(0x301914) = (v == 0xFF) ? 0 : v; if (v != 0xFF) return; + v = bcd_inc(IOB(0x301918), 0x23); + IOB(0x301918) = (v == 0xFF) ? 0 : v; if (v != 0xFF) return; + IOB(0x301928) = (uint8_t)((IOB(0x301928) + 1) % 7); + uint8_t mon = IOB(0x301920); + int mi = ((mon >> 4) & 1) * 10 + (mon & 0xF); + uint8_t dim = (mi >= 1 && mi <= 12) ? month_days[mi] : 0x31; + if (mi == 2 && ((IOB(0x301924) & 0xF) % 4 == 0)) dim = 0x29; + v = bcd_inc(IOB(0x30191C), dim); + IOB(0x30191C) = (v == 0xFF) ? 1 : v; if (v != 0xFF) return; + v = bcd_inc(IOB(0x301920), 0x12); + IOB(0x301920) = (v == 0xFF) ? 1 : v; if (v != 0xFF) return; + v = bcd_inc(IOB(0x301924), 0x99); + IOB(0x301924) = (v == 0xFF) ? 0 : v; +} + +/* Set the guest clock to local time t (seconds since 1970), e.g. the Paradise's time at the start. + * The weekday moves by the days between the old date and the new one. */ +static uint8_t to_bcd(uint32_t v) { return (uint8_t)(((v / 10u) << 4) | (v % 10u)); } +static uint32_t from_bcd(uint8_t v) { return (uint32_t)(v >> 4) * 10u + (v & 15u); } +TC_SRAM static int32_t days_from(int32_t y, int32_t m, int32_t d) +{ + y -= m <= 2; int32_t era = (y >= 0 ? y : y - 399) / 400, yoe = y - era * 400; + int32_t doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return era * 146097 + doe - 719468; +} +TC_SRAM void periph_rtc_set(Emu *e, uint32_t t) +{ + if ((IOB(0x301908) & 2) || (IOB(0x30190C) & 1)) return; /* stopped or being set by the game */ + uint32_t days = t / 86400u, sod = t % 86400u; + uint32_t z = days + 719468u, era = z / 146097u, doe = z - era * 146097u; + uint32_t yoe = (doe - doe / 1460u + doe / 36524u - doe / 146096u) / 365u, doy = doe - (365u * yoe + yoe / 4u - yoe / 100u); + uint32_t mp = (5u * doy + 2u) / 153u, d = doy - (153u * mp + 2u) / 5u + 1u, m = mp < 10u ? mp + 3u : mp - 9u, y = yoe + era * 400u + (m <= 2u); + uint32_t oy = 2000u + from_bcd(IOB(0x301924)), om = from_bcd(IOB(0x301920)), od = from_bcd(IOB(0x30191C)), wd; + if (om >= 1u && om <= 12u && od >= 1u && od <= 31u && IOB(0x301928) < 7u) { + int32_t diff = (int32_t)days - days_from((int32_t)oy, (int32_t)om, (int32_t)od); + wd = (uint32_t)(((int32_t)IOB(0x301928) + diff % 7 + 7) % 7); + } else wd = (days + 4u) % 7u; /* 1970-01-01 was a Thursday (0 = Sunday) */ + IOB(0x301910) = to_bcd(sod % 60u); IOB(0x301914) = to_bcd((sod / 60u) % 60u); IOB(0x301918) = to_bcd(sod / 3600u); + IOB(0x30191C) = to_bcd(d); IOB(0x301920) = to_bcd(m); IOB(0x301924) = to_bcd(y % 100u); IOB(0x301928) = (uint8_t)wd; + e->rtc_cyc = 0; +} + +/* 1.7.2 test16: the guest clock as local time (seconds since 1970), 0 = stopped, being set or not a date */ +TC_SRAM uint32_t periph_rtc_get(Emu *e) +{ + if ((IOB(0x301908) & 2) || (IOB(0x30190C) & 1)) return 0; + uint32_t s = from_bcd(IOB(0x301910)), mi = from_bcd(IOB(0x301914)), h = from_bcd(IOB(0x301918)); + uint32_t d = from_bcd(IOB(0x30191C)), m = from_bcd(IOB(0x301920)), y = 2000u + from_bcd(IOB(0x301924)); + if (m < 1u || m > 12u || d < 1u || d > 31u || h > 23u || mi > 59u || s > 59u) return 0; + return (uint32_t)days_from((int32_t)y, (int32_t)m, (int32_t)d) * 86400u + h * 3600u + mi * 60u + s; +} + +/* Advance the guest clock by n seconds (after a pause). */ +TC_SRAM void periph_rtc_advance(Emu *e, uint32_t n) +{ + if ((IOB(0x301908) & 2) || (IOB(0x30190C) & 1)) return; + while (n--) rtc_count_second(e); +} + +static void rtc_tick(Emu *e, uint32_t cycles) +{ + uint32_t hz = mclk(e); +#ifdef RTC_MS + /* 1.6.8: seconds and the 1 s / 1 min / 1 h interrupt come from periph_rtc_ms (real milliseconds of the + * main loop). Counted in guest cycles they went wrong whenever the guest changed its clock: a part of a + * second at 18 MHz counted as minutes at 16 kHz (iD L: clock jumped when its display went off). */ + uint32_t sel = (IOB(0x301904) >> 2) & 3; + if (sel) return; +#else + if (!(IOB(0x301908) & 2) && !(IOB(0x30190C) & 1)) { + e->rtc_cyc += cycles; + while (e->rtc_cyc >= hz) { e->rtc_cyc -= hz; rtc_count_second(e); } + } + uint32_t sel = (IOB(0x301904) >> 2) & 3; +#endif + uint64_t p = sel == 0 ? hz / 64 : sel == 1 ? hz : sel == 2 ? (uint64_t)hz * 60 : (uint64_t)hz * 3600; + e->rtc_irq_cyc += cycles; +#ifdef RTC_MS + if (e->rtc_irq_cyc >= 2u * (uint32_t)p) e->rtc_irq_cyc = (uint32_t)p; /* clock switched down: no burst */ +#endif + if (e->rtc_irq_cyc >= p) { + e->rtc_irq_cyc -= (uint32_t)(p > 0xFFFFFFFFu ? 0xFFFFFFFFu : p); + IOB(0x301900) |= 1; + if (IOB(0x301904) & 1) IOB(0x300287) |= 4; + } +} + +#ifdef RTC_MS +/* one real millisecond (called by the main loop for every guest ms) */ +void periph_rtc_ms(Emu *e) +{ + if (!(IOB(0x301908) & 2) && !(IOB(0x30190C) & 1)) { + if (++e->rtc_cyc >= 1000u) { e->rtc_cyc = 0; rtc_count_second(e); } + } + uint32_t sel = (IOB(0x301904) >> 2) & 3; + if (!sel) return; + uint32_t p = sel == 1 ? 1000u : sel == 2 ? 60000u : 3600000u; + if (++e->rtc_irq_cyc >= p) { + e->rtc_irq_cyc = 0; + IOB(0x301900) |= 1; + if (IOB(0x301904) & 1) { IOB(0x300287) |= 4; itc_scan(e); } + } +} +#endif +void periph_tick(Emu *e, uint32_t cycles) +{ + rtc_tick(e, cycles); +#ifdef TC_IRLINK + if (g_ir.on) ir_tick(e); +#endif +#ifndef NO_PN + if (e->dev.nfc_pn512) pn_tick(e); +#endif + for (int x = 0; x < 6; x++) { + uint8_t c = IOB(0x300780 + (uint32_t)x * 8 + 6); + if (!(c & 1)) continue; + T16 *t = &e->t16[x]; + uint8_t ck = IOB(0x3007E0 + (uint32_t)x * 2); + if (!(ck & 8)) continue; + t->accum += cycles; + uint32_t div = presc_div[ck & 7]; + uint32_t clocks = t->accum / div; + t->accum -= clocks * div; + if (clocks) t16_run(e, x, clocks); + } + itc_scan(e); +} + +/* Cycles until the next peripheral event (timers, clock). */ +uint32_t periph_next(Emu *e) +{ + uint64_t best = 0xFFFFFFFFu; + uint32_t hz = mclk(e); + if ((IOB(0x301904) & 1) && (IOB(0x300277) & 4) +#ifdef RTC_MS + && !((IOB(0x301904) >> 2) & 3) +#endif + ) { + uint32_t sel = (IOB(0x301904) >> 2) & 3; + uint64_t p = sel == 0 ? hz / 64 : sel == 1 ? hz : sel == 2 ? (uint64_t)hz * 60 : (uint64_t)hz * 3600; + if (p > e->rtc_irq_cyc && p - e->rtc_irq_cyc < best) best = p - e->rtc_irq_cyc; + else if (p <= e->rtc_irq_cyc) best = 1; + } + for (int x = 0; x < 6; x++) { + uint8_t c = IOB(0x300780 + (uint32_t)x * 8 + 6); + if (!(c & 1)) continue; + uint8_t ck = IOB(0x3007E0 + (uint32_t)x * 2); + if (!(ck & 8)) continue; + uint8_t en = IOB(0x300272 + (uint32_t)(x / 2)); + int ea = (en >> ((x & 1) ? 7 : 3)) & 1, eb = (en >> ((x & 1) ? 6 : 2)) & 1; + if (!ea && !eb) continue; + uint32_t base = 0x300780 + (uint32_t)x * 8; + uint32_t cra = (uint32_t)(IOB(base) | (IOB(base + 1) << 8)); + uint32_t crb = (uint32_t)(IOB(base + 2) | (IOB(base + 3) << 8)); + T16 *t = &e->t16[x]; + uint32_t cnt = t->counter; + uint32_t n = (crb > cnt) ? crb - cnt : 1u; + if (!eb) n = 0xFFFFFu; + if (ea && cra && !t->a_fired && cra > cnt && cra - cnt < n) n = cra - cnt; + if (n == 0xFFFFFu) continue; + uint64_t cyc = (uint64_t)n * presc_div[ck & 7]; + cyc = cyc > t->accum ? cyc - t->accum : 1; + if (cyc < best) best = cyc; + } +#ifdef TC_IRLINK + if (g_ir.on) { /* TX done, next received byte */ + uint64_t now = e->last_tick; + if (g_ir.tx_ready_at) { uint64_t d = g_ir.tx_ready_at > now ? g_ir.tx_ready_at - now : 1u; if (d < best) best = d; } + if (IOB(IR_TRIG) && tc_ir_avail()) { uint64_t d = g_ir.rx_next_at > now ? g_ir.rx_next_at - now : 1u; if (d < best) best = d; } + } +#endif + return best ? (uint32_t)best : 1u; +} + +/* Guest sound: T16 channel 0 drives the buzzer. If it runs and its output + * toggles (compare A below B), the frequency is clock / divider / (B+1). */ +uint32_t periph_tone_hz(Emu *e) +{ + uint8_t c = IOB(0x300786), ck = IOB(0x3007E0); + if (!(c & 1) || !(ck & 8)) return 0; + uint32_t cra = (uint32_t)(IOB(0x300780) | (IOB(0x300781) << 8)); + uint32_t crb = (uint32_t)(IOB(0x300782) | (IOB(0x300783) << 8)); + if (!cra || cra >= crb) return 0; + uint32_t hz = mclk(e) / presc_div[ck & 7] / (crb + 1); + return (hz >= 20 && hz <= 12000) ? hz : 0; +} + +void periph_init(Emu *e) +{ + e->cmu.osc3_hz = e->dev.osc3_hz; + e->cmu.mclk_hz = 0; +} diff --git a/emu/src/emu/ask.c b/emu/src/emu/ask.c new file mode 100644 index 0000000..5c5045c --- /dev/null +++ b/emu/src/emu/ask.c @@ -0,0 +1,319 @@ +/* 1.6.6: "reset?" question when the wheel is pressed in the first 3 s after a resumed start (TamaEmu, + * T18Emu). Before, the session was thrown away at once, a press meant for the menu lost the game. + * A = yes, B or the wheel = no. + * 1.6.8 (OPT_MENU): settings on the device with a short press on the wheel (volume, brightness, screen off), + * drawn like the menu of T7Emu and V1Emu: its 5x7 font, its colours (green screen, dark ink), title, line, + * the chosen line dark. */ +#include "hw.h" +#include "ask.h" +#ifdef BAT_SHOW +#include "batt.h" +#endif +static const char FK[] = " %\'-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +static const u8 FG[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x19,0x19,0x02,0x04,0x08,0x13,0x13,0x04,0x04,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x0c,0x01,0x01,0x02,0x04,0x08,0x10,0x10,0x0e,0x11,0x13,0x15,0x19,0x11,0x0e,0x04,0x0c,0x04,0x04,0x04,0x04,0x0e,0x0e,0x11,0x01,0x02,0x04,0x08,0x1f,0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e,0x02,0x06,0x0a,0x12,0x1f,0x02,0x02,0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e,0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e,0x1f,0x01,0x02,0x04,0x08,0x08,0x08,0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e,0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e,0x00,0x04,0x04,0x00,0x04,0x04,0x00,0x0e,0x11,0x01,0x02,0x04,0x00,0x04,0x0e,0x11,0x11,0x1f,0x11,0x11,0x11,0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e,0x0e,0x11,0x10,0x10,0x10,0x11,0x0e,0x1e,0x11,0x11,0x11,0x11,0x11,0x1e,0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f,0x1f,0x10,0x10,0x1e,0x10,0x10,0x10,0x0e,0x11,0x10,0x17,0x11,0x11,0x0f,0x11,0x11,0x11,0x1f,0x11,0x11,0x11,0x0e,0x04,0x04,0x04,0x04,0x04,0x0e,0x07,0x02,0x02,0x02,0x02,0x12,0x0c,0x11,0x12,0x14,0x18,0x14,0x12,0x11,0x10,0x10,0x10,0x10,0x10,0x10,0x1f,0x11,0x1b,0x15,0x15,0x11,0x11,0x11,0x11,0x19,0x15,0x13,0x11,0x11,0x11,0x0e,0x11,0x11,0x11,0x11,0x11,0x0e,0x1e,0x11,0x11,0x1e,0x10,0x10,0x10,0x0e,0x11,0x11,0x11,0x15,0x12,0x0d,0x1e,0x11,0x11,0x1e,0x14,0x12,0x11,0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e,0x1f,0x04,0x04,0x04,0x04,0x04,0x04,0x11,0x11,0x11,0x11,0x11,0x11,0x0e,0x11,0x11,0x11,0x11,0x11,0x0a,0x04,0x11,0x11,0x11,0x15,0x15,0x15,0x0a,0x11,0x11,0x0a,0x04,0x0a,0x11,0x11,0x11,0x11,0x0a,0x04,0x04,0x04,0x04,0x1f,0x01,0x02,0x04,0x08,0x10,0x1f}; +static const u8 *ask_glyph(char c) { if (c >= 'a' && c <= 'z') c = (char)(c - 32); for (int i = 0; FK[i]; i++) if (FK[i] == c) return FG + 7 * i; return FG; } +static int slen(const char *s) { int n = 0; while (s && s[n]) n++; return n; } +/* one text line from y0 (7 rows, scale 1 or 2); x0 < 0: centred */ +static void ask_line(u16 *row, int y, int y0, const char *s, u16 fg, int x0, int sc) +{ + if (!s || y < y0 || y >= y0 + 7 * sc) return; + int n = slen(s); + if (x0 < 0) x0 = (128 - n * 6 * sc + sc) / 2; + int gy = (y - y0) / sc; + for (int i = 0; i < n; i++) { + u8 g = ask_glyph(s[i])[gy]; + for (int cx = 0; cx < 5 * sc; cx++) if (g & (0x10 >> (cx / sc))) { int x = x0 + i * 6 * sc + cx; if (x >= 0 && x < 128) row[x] = fg; } + } +} +static void ask_release(void) { for (u32 t = 0; hw_buttons() && t < 50000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); } +#if defined(OPT_MENU) || defined(ASK_NUM) +/* 1.6.8 (test41): the keys bounce; one press of B counted once or twice. A state counts only when it held for + * 20 samples about 1 ms apart. */ +static void ask_ms(void) { for (volatile u32 i = 0; i < 16000u; i++) { } hw_wdt_feed(); } +static u32 ask_stable(void) +{ + u32 v = hw_buttons(); + for (int n = 0; n < 20; ) { ask_ms(); u32 w = hw_buttons(); if (w == v) n++; else { v = w; n = 0; } } + return v; +} +static void ask_release_db(void) { while (ask_stable()) { } } +static u32 ask_press_db(void) { u32 b; while (!(b = ask_stable())) { } return b; } +#endif +/* colours of the T7Emu menu with its default screen colour: background, 90 %, 60 %, ink */ +#define C_BG 0xAE66u +#define C_LINE 0x6BE4u +#define C_INK 0x0000u +int hw_ask_reset(int en) +{ + const char *l1 = en ? "RESET?" : "ZURUECKSETZEN?", *l2 = en ? "A YES" : "A JA", *l3 = en ? "B NO" : "B NEIN"; + u16 row[128]; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + for (int x = 0; x < 128; x++) row[x] = C_BG; + ask_line(row, y, 36, l1, C_INK, -1, 1); ask_line(row, y, 60, l2, C_INK, -1, 1); ask_line(row, y, 76, l3, C_INK, -1, 1); + hw_px_row(row, 128); + } + hw_px_end(); + hw_backlight(1); + ask_release(); /* the wheel let go first */ + int r = 0; + for (u32 t = 0; ; t++) { + if ((t & 0xFFFFu) == 0) hw_wdt_feed(); + u32 b = hw_buttons(); + if (b & BTN_A) { r = 1; break; } + if (b & (BTN_B | BTN_WHEEL)) { r = 0; break; } + } + ask_release(); + return r; +} + +#ifdef ASK_NUM +/* test30: a number on the device (Gotchi Points, Tamapoints): A next digit, B the digit + 1, C keep, the wheel + * back without change. Returns 1 when kept (*v is the new value, at most max). */ +int hw_num_edit(const char *title, u32 *v, int digits, u32 max, int en) +{ + u8 dg[8]; u32 t = *v > max ? max : *v; int pos = 0; + if (digits > 8) digits = 8; + for (int i = digits - 1; i >= 0; i--) { dg[i] = (u8)(t % 10u); t /= 10u; } + ask_release_db(); + for (;;) { + char num[9]; for (int i = 0; i < digits; i++) num[i] = (char)('0' + dg[i]); num[digits] = 0; + int x0 = (128 - digits * 12 + 2) / 2; + u16 row[128]; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + for (int x = 0; x < 128; x++) row[x] = C_BG; + if (y == 32) for (int x = 0; x < 128; x++) row[x] = C_LINE; + if (y >= 50 && y < 66) for (int x = x0 + pos * 12 - 1; x < x0 + pos * 12 + 11; x++) if (x >= 0 && x < 128) row[x] = C_INK; + ask_line(row, y, 22, title, C_INK, -1, 1); + for (int i = 0; i < digits; i++) { char c[2] = { num[i], 0 }; ask_line(row, y, 51, c, i == pos ? C_BG : C_INK, x0 + i * 12, 2); } + ask_line(row, y, 80, en ? "A NEXT B CHANGE" : "A WEITER B AENDERN", C_INK, -1, 1); + ask_line(row, y, 92, en ? "C OK" : "C OK", C_INK, -1, 1); + hw_px_row(row, 128); + } + hw_px_end(); + u32 b = ask_press_db(); + ask_release_db(); + if (b & BTN_WHEEL) return 0; + if (b & BTN_C) { + u32 n = 0; for (int i = 0; i < digits; i++) n = n * 10u + dg[i]; + *v = n > max ? max : n; return 1; + } + if (b & BTN_A) pos = (pos + 1) % digits; + if (b & BTN_B) dg[pos] = (u8)((dg[pos] + 1u) % 10u); + } +} +#endif +#ifdef OPT_MENU +/* Settings: o holds them as the flags of the program (bits 16-17 volume, 18-19 brightness, 20-22 screen off). + * A next line, B change, C or the wheel: close. Returns the new bits. */ +static const char *const VOL_DE[4] = { "Normal", "Leise", "Laut", "Aus" }, *const VOL_EN[4] = { "Normal", "Quiet", "Loud", "Off" }; +/* 1.6.8 (test45): the light in 11 steps, bits 24-27 = step + 1 (0 = the old bits 18-19: 100, 75, 50, 25 %). + * Step 0 = 100 %, then 5, 10, 20 .. 90 %: B goes up, after 100 % it starts at 5 % again. */ +#ifdef ASK_OVL +/* 1.6.13 test10 (TamaEmu EMU_OVL): the menus live in the program's overlay (loaded when opened); these few are needed + * while the game runs and stay */ +#define ASK_KEEP __attribute__((section(".text.keep_ask"))) +#define ASK_KEEPD __attribute__((section(".rodata.keep_ask"))) +#else +#define ASK_KEEP +#define ASK_KEEPD +#endif +ASK_KEEPD static const u8 OPT_LV[11] = { 100, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90 }; +ASK_KEEPD static const u8 OPT_OLD[4] = { 0, 8, 6, 3 }; /* the old bits 18-19: 100, 75, 50, 25 % */ +ASK_KEEP static u32 opt_step(u32 o) { u32 n = (o >> 24) & 15u; if (n && n <= 11u) return n - 1u; return OPT_OLD[(o >> 18) & 3u]; } +ASK_KEEP u32 opt_light_pct(u32 o) { return OPT_LV[opt_step(o)]; } +static void pct_txt(char *t, u32 p) { u32 n = 0; if (p >= 100u) t[n++] = '1'; if (p >= 10u) t[n++] = (char)('0' + (p / 10u) % 10u); t[n++] = (char)('0' + p % 10u); t[n++] = '%'; t[n] = 0; } +#ifdef ASK_DIM +/* 1.6.13 test7 (T18Emu): dimming as in T7Emu, device-only bits: 12-14 dim after (0 never, then as the screen off + * times), 8-11 dim to (DIM_P[(n + 4) mod 10], 0 = 10 %, at most the light). Screen off 0 = never (the game still turns the + * picture off itself, as the original); bit 15 never: the screen stays on (the game does not fall asleep). */ +ASK_KEEPD static const u8 DIM_P[10] = { 1, 2, 3, 5, 10, 15, 20, 30, 40, 50 }; +ASK_KEEP u32 opt_dim_pct(u32 o) { u32 p = DIM_P[(((o >> 8) & 15u) + 4u) % 10u], l = opt_light_pct(o); return p < l ? p : l; } +#ifdef ASK_NEVER +/* T18Emu: screen off "never" (bit 15), the game kept awake */ +static const char *const OFF_DE[9] = { "Auto", "Nie", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" }; +static const char *const OFF_EN[9] = { "Auto", "Never", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" }; +#define OFF_K 9u +#else +/* TamaEmu (test10): Auto (as the game) and the times */ +static const char *const OFF_DE[8] = { "Auto", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" }; +static const char *const OFF_EN[8] = { "Auto", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" }; +#define OFF_K 8u +#endif +#define MY 4 +#else +static const char *const OFF_DE[8] = { "Auto", "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" }; +static const char *const OFF_EN[8] = { "Auto", "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" }; +#define MY 22 +#endif +#ifdef ASK_EXTRA +static u32 opts_menu(u32 o, int en, const char *const *ex, int nex); +u32 hw_opts_menu(u32 o, int en) { return opts_menu(o, en, 0, 0); } +/* 1.6.8 (test47): one more line (T18Emu: grow up); chosen with B: the result has bit 31 set */ +u32 hw_opts_menu_x(u32 o, int en, const char *extra) { return opts_menu(o, en, &extra, extra ? 1 : 0); } +/* test30: up to 3 more lines (0 = left out); the chosen one: bit 31 and its index in bits 28-30 */ +u32 hw_opts_menu_xn(u32 o, int en, const char *const *ex, int nex) { return opts_menu(o, en, ex, nex); } +#ifndef ASK_SLIM /* test30: TamaEmu only needs the extra lines (its program space is nearly full) */ +/* a list to choose from (up to 8 lines at a time, scrolls): A next, B take, C or the wheel back (-1) */ +int hw_list_menu(const char *title, const char *const *it, int n) +{ + int sel = 0, top = 0; + ask_release_db(); + for (;;) { + if (sel < top) top = sel; + if (sel >= top + 8) top = sel - 7; + u16 row[128]; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + int my = y - 14; + int k = (my - 12) / 10, in = my >= 12 && k >= 0 && k < 8 && top + k < n && (my - 12) % 10 < 9; + u16 bg = (in && top + k == sel) ? C_INK : C_BG; + for (int x = 0; x < 128; x++) row[x] = (my == 10) ? C_LINE : bg; + ask_line(row, my, 1, title, C_INK, 2, 1); + for (int i = 0; i < 8 && top + i < n; i++) ask_line(row, my, 13 + i * 10, it[top + i], top + i == sel ? C_BG : C_INK, 2, 1); + if (top > 0 && my >= 2 && my < 6) for (int x = 122 - (my - 2); x <= 122 + (my - 2); x++) row[x] = C_LINE; /* more above */ + if (top + 8 < n && my >= 2 && my < 6) for (int x = 114 - (5 - my); x <= 114 + (5 - my); x++) row[x] = C_LINE; /* more below */ + hw_px_row(row, 128); + } + hw_px_end(); + u32 b = ask_press_db(); + ask_release_db(); + if (b & (BTN_C | BTN_WHEEL)) return -1; + if (b & BTN_A) sel = (sel + 1) % n; + if (b & BTN_B) return sel; + } +} +/* test47: a 64x64 picture (256 colours RGB565, then 4096 indices; p in the flash, read uncached) twice as big, with + * "B OK C BACK" below. 1 = B, 0 = C or the wheel. */ +int hw_pic_ask(const volatile u8 *p, int en) +{ + u16 row[128], pal[256]; + for (int i = 0; i < 256; i++) pal[i] = (u16)(p[2 * i] | (p[2 * i + 1] << 8)); + ask_release_db(); + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + if (y < 116) { const volatile u8 *q = p + 512 + (y >> 1) * 64; for (int x = 0; x < 128; x++) row[x] = pal[q[x >> 1]]; } + else { for (int x = 0; x < 128; x++) row[x] = C_BG; ask_line(row, y, 118, en ? "B OK C BACK" : "B OK C ZURUECK", C_INK, -1, 1); } + hw_px_row(row, 128); + } + hw_px_end(); + u32 b = ask_press_db(); + ask_release_db(); + return (b & BTN_B) ? 1 : 0; +} +#endif +static u32 opts_menu(u32 o, int en, const char *const *ex, int nex) +#else +u32 hw_opts_menu(u32 o, int en) +#endif +{ + int sel = 0; +#ifdef ASK_EXTRA + const char *xl[3]; int nx = 0, xi[3]; + for (int i = 0; i < nex && nx < 3; i++) if (ex[i]) { xl[nx] = ex[i]; xi[nx] = i; nx++; } +#else + const int nx = 0; +#endif + ask_release_db(); + for (;;) { + u32 v = (o >> 16) & 3u, d = opt_step(o), s = (o >> 20) & 7u; +#ifdef ASK_DIM +#ifdef ASK_NEVER + u32 a = (o >> 12) & 7u, ok = (o & 0x8000u) ? 1u : s ? s + 1u : 0u; /* screen off: Auto, Never, the times */ +#define OFF_TIMES (OFF_EN + 1) +#else + u32 a = (o >> 12) & 7u, ok = s; +#define OFF_TIMES OFF_EN +#endif + u8 it[6]; int ns = 0; it[ns++] = 0; it[ns++] = 1; it[ns++] = 3; if (a) it[ns++] = 4; it[ns++] = 2; /* dim to: only when dimming */ +#ifdef ASK_LANG + it[ns++] = 5; /* test8: the language, set on the device (bits 0-1: 0 as the Studio, 1 German, 2 English) */ +#endif + char pt[6]; pct_txt(pt, opt_dim_pct(o)); + static const char *const TD[8] = { 0, "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" }; + const char *lab[6] = { en ? "Volume" : "Lautstaerke", en ? "Brightness" : "Helligkeit", en ? "Screen off" : "Bild aus nach", + en ? "Dim after" : "Dimmen nach", en ? "Dim to" : "Dimmen auf", en ? "Language" : "Sprache" }; + const char *val[6] = { (en ? VOL_EN : VOL_DE)[v], 0, (en ? OFF_EN : OFF_DE)[ok], a ? (en ? OFF_TIMES : TD)[a] : (en ? "Never" : "Nie"), pt, + en ? "English" : "Deutsch" }; +#else + static const u8 it[3] = { 0, 1, 2 }; const int ns = 3; + const char *lab[3] = { en ? "Volume" : "Lautstaerke", en ? "Brightness" : "Helligkeit", en ? "Screen off" : "Bild aus nach" }; + const char *val[3] = { (en ? VOL_EN : VOL_DE)[v], 0, (en ? OFF_EN : OFF_DE)[s] }; +#endif + int nl = ns + nx; if (sel >= nl) sel = 0; + char dt[6]; pct_txt(dt, OPT_LV[d]); val[1] = dt; +#ifdef BAT_SHOW + char bt[12]; bat_text(bt); /* test17: the battery, below the lines (not chosen) */ + int by = 13 + nl * 10 + 8; +#endif + u16 row[128]; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + int my = y - MY; + u16 bg = C_BG; + int k = (my - 12) / 10, in = my >= 12 && k >= 0 && k < nl && (my - 12) % 10 < 9; /* the chosen line: rows y-1 .. y+7 */ + if (in && k == sel) bg = C_INK; + for (int x = 0; x < 128; x++) row[x] = (my == 10) ? C_LINE : bg; + ask_line(row, my, 1, en ? "SETTINGS" : "EINSTELLUNGEN", C_INK, 2, 1); + for (int i = 0; i < ns; i++) { + u16 fg = i == sel ? C_BG : C_INK; int yy = 13 + i * 10; const char *vv = val[it[i]]; + ask_line(row, my, yy, lab[it[i]], fg, 2, 1); + ask_line(row, my, yy, vv, fg, 128 - 2 - 6 * slen(vv), 1); + } +#ifdef ASK_EXTRA + for (int i = 0; i < nx; i++) { +#ifdef ASK_LANG + /* test9: "German|English" in one line, so it follows the language right away */ + char xt[20]; { const char *p = xl[i], *q = p; while (*q && *q != '|') q++; + if (*q && en) p = q + 1, q = p + slen(p); + int n = 0; while (p < q && n < 19) xt[n++] = *p++; xt[n] = 0; } + ask_line(row, my, 13 + 10 * (ns + i), xt, sel == ns + i ? C_BG : C_INK, 2, 1); +#else + ask_line(row, my, 13 + 10 * (ns + i), xl[i], sel == ns + i ? C_BG : C_INK, 2, 1); +#endif + } +#endif +#ifdef BAT_SHOW + ask_line(row, my, by, en ? "Battery" : "Batterie", C_LINE, 2, 1); + ask_line(row, my, by, bt, C_LINE, 128 - 2 - 6 * slen(bt), 1); +#endif + hw_px_row(row, 128); + } + hw_px_end(); + u32 b = ask_press_db(); + ask_release_db(); + if (b & (BTN_C | BTN_WHEEL)) return o; + if (b & BTN_A) sel = (sel + 1) % nl; +#ifdef ASK_EXTRA + if ((b & BTN_B) && sel >= ns) return o | 0x80000000u | ((u32)xi[sel - ns] << 28); +#endif + if (b & BTN_B) { + int w = it[sel]; + if (w == 0) o = (o & ~(3u << 16)) | (((v + 1) & 3u) << 16); + else if (w == 1) { + o = (o & ~((3u << 18) | (15u << 24))) | ((((d + 1u) % 11u) + 1u) << 24); +#ifdef BL_PWM + hw_bl_set(opt_light_pct(o)); /* 1.6.8: seen right away */ +#endif + } +#ifdef ASK_DIM + else if (w == 3) { a = (a + 1) & 7u; if (a && s && s <= a) s = a < 7u ? a + 1u : 0u; /* off stays after dimming */ + o = (o & ~((7u << 12) | (7u << 20))) | (a << 12) | (s << 20); } + else if (w == 4) o = (o & ~(15u << 8)) | (((((o >> 8) & 15u) + 1u) % 10u) << 8); +#ifdef ASK_LANG + else if (w == 5) { en = !en; o = (o & ~3u) | (en ? 2u : 1u); } +#endif +#ifdef ASK_NEVER + else { do { ok = (ok + 1u) % OFF_K; s = ok >= 2u ? ok - 1u : 0u; } while (s && a && s <= a); + o = (o & ~((7u << 20) | 0x8000u)) | (s << 20) | (ok == 1u ? 0x8000u : 0u); } +#else + else { do s = (s + 1u) & 7u; while (s && a && s <= a); o = (o & ~(7u << 20)) | (s << 20); } +#endif +#else + else o = (o & ~(7u << 20)) | (((s + 1) & 7u) << 20); +#endif + } + } +} +#endif diff --git a/emu/src/emu/ask.h b/emu/src/emu/ask.h new file mode 100644 index 0000000..99a1875 --- /dev/null +++ b/emu/src/emu/ask.h @@ -0,0 +1,16 @@ +#ifndef ASK_H +#define ASK_H +int hw_ask_reset(int en); /* 1 = yes (A), 0 = no (B or wheel); waits for the keys to be released */ +#ifdef ASK_NUM +int hw_num_edit(const char *title, u32 *v, int digits, u32 max, int en); /* test30: 1 = kept */ +#endif +#ifdef OPT_MENU +u32 hw_opts_menu(u32 o, int en); +u32 hw_opts_menu_xn(u32 o, int en, const char *const *ex, int nex); /* test30: chosen extra: bit 31, index in 28-30 */ +u32 opt_light_pct(u32 o); +u32 opt_dim_pct(u32 o); /* ASK_DIM: the dim level, at most the light */ +u32 hw_opts_menu_x(u32 o, int en, const char *extra); /* ASK_EXTRA (T18Emu): one more line, bit 31 = chosen */ +int hw_list_menu(const char *title, const char *const *it, int n); +int hw_pic_ask(const volatile u8 *p, int en); /* test47: a 64x64 picture, B ok (1), C back (0) */ /* 1.6.8 (test45): the light in percent from the flag bits */ /* 1.6.8: settings on the device; o, result: flag bits 16..22 */ +#endif +#endif diff --git a/emu/src/emu/batt.h b/emu/src/emu/batt.h new file mode 100644 index 0000000..6c9cc0c --- /dev/null +++ b/emu/src/emu/batt.h @@ -0,0 +1,97 @@ +/* batt.h - 1.6.9 test17 (switch BAT_SHOW): the battery voltage, as the Paradise firmware measures it. + * Found in the firmware (and the Paradise emulator capybara): SAR ADC at 0x4003A000, channel 4 (P0.6, ADP bits 13..15), + * ADM bit 15 on and bit 0 starts a conversion, the result in ADR bits 6..15 (10 bits). The firmware takes + * volts = sample * 0xD33300 / 2^32 (3.3 V for 1024) and switches off below 2.2 V ("replace the battery"). + * Header only. Author: mameise */ +#ifndef BATT_H +#define BATT_H +#include "io.h" +#define BAT_ADP REG(0x4003A000u) +#define BAT_ADM REG(0x4003A004u) +#define BAT_ADR REG(0x4003A008u) +/* millivolts, 0 = no reading (8 conversions, each waited for at most about 2 ms) */ +__attribute__((noinline, unused)) static u32 bat_mv(void) +{ + REG(0x45000100u) |= 1u << 12; /* SAR ADC clock */ + BAT_ADP = (BAT_ADP & ~0xE000u) | 0x8000u; /* channel 4 */ + BAT_ADM |= 0x8000u; /* on */ + u32 sum = 0, n = 0; + for (int i = 0; i < 8; i++) { + BAT_ADM |= 1u; + u32 t = 0; while (!(BAT_ADM & 2u) && ++t < 100000u) { } + if (t >= 100000u) break; + sum += (BAT_ADR >> 6) & 0x3FFu; n++; + } + return n ? sum * 3300u / (n * 1024u) : 0u; +} +/* 2 x AAA: 3.0 V and more full, 2.2 V the Paradise switches off */ +static inline u32 bat_pct(u32 mv) { return mv >= 3000u ? 100u : mv <= 2200u ? 0u : (mv - 2200u) * 100u / 800u; } +/* "2.84V 80%" (or "?" without a reading) into s (12 bytes) */ +__attribute__((noinline, unused)) static void bat_text(char *s) +{ + u32 mv = bat_mv(), k = 0; + if (!mv) { s[0] = '?'; s[1] = 0; return; } +#ifdef BAT_SMOOTH + /* 1.6.13 test7: steadier (the reading moved with the load, e.g. while scrolling a menu): v = f v + (1 - f) new, + * f = 7/8, in 1/16 mV; the first reading is taken as it is */ + { static u32 g_bat16; u32 n = mv << 4; g_bat16 = g_bat16 ? (g_bat16 * 7u + n + 4u) >> 3 : n; mv = (g_bat16 + 8u) >> 4; } +#endif + u32 p = bat_pct(mv); + s[k++] = (char)('0' + mv / 1000u); s[k++] = '.'; s[k++] = (char)('0' + (mv / 100u) % 10u); s[k++] = (char)('0' + (mv / 10u) % 10u); s[k++] = 'V'; s[k++] = ' '; + if (p >= 100u) s[k++] = '1'; + if (p >= 10u) s[k++] = (char)('0' + (p / 10u) % 10u); + s[k++] = (char)('0' + p % 10u); s[k++] = '%'; s[k] = 0; +} +#ifdef BAT_GUARD +/* test21 (switch BAT_GUARD): the Paradise firmware switches itself off below 2.2 V; under an emulator it ran on until + * the power broke down, perhaps in the middle of a flash write (a lost save). Read every 20 s: two readings in a row + * below BAT_LOW_MV and the app saves everything once and switches off (nothing is written any more). */ +#ifndef BAT_LOW_MV +#define BAT_LOW_MV 2210u /* test23: 2.21 V (was 2.25 V), the Paradise itself goes off at 2.2 V */ +#endif +__attribute__((noinline, unused, minsize)) static int bat_is_low(void) +{ + REG(0x45000100u) |= 1u << 12; BAT_ADP = (BAT_ADP & ~0xE000u) | 0x8000u; BAT_ADM |= 0x8000u; + u32 s = 0; + for (int i = 0; i < 4; i++) { BAT_ADM |= 1u; u32 t = 0; while (!(BAT_ADM & 2u)) if (++t > 100000u) return 0; s += (BAT_ADR >> 6) & 0x3FFu; } + return s < BAT_LOW_MV * 4096u / 3300u; +} +#ifdef BAT_PIC +/* test23 (switch BAT_PIC): the Paradise's own "battery empty" picture (sprite 53 of the ROM) before switching off, as + * the Paradise does. The Studio puts it at 0xFFF000 (last sector of the rescue block): "BAT1", byte count, 16 colours + * (RGB565), then one byte per run: colour << 4 | (length - 1), 128 x 128 pixels row by row. Shown for about 3 s (the caller is at full clock). */ +#include "hw.h" +#ifndef BAT_PIC_ATTR +#define BAT_PIC_ATTR __attribute__((noinline, unused, minsize)) +#endif +BAT_PIC_ATTR static void bat_pic(void) +{ + const volatile u32 *h = (const volatile u32 *)0x60FFF000u; + u32 n = h[1]; + if (h[0] != 0x31544142u || n > 4000u) return; + u16 pal[16], row[128]; u32 x = 0, y = 0; + for (u32 i = 0; i < 8u; i++) { u32 w = h[2 + i]; pal[2 * i] = (u16)w; pal[2 * i + 1] = (u16)(w >> 16); } + hw_px_begin(0, 0, 128, 128); + for (u32 i = 0; i < n && y < 128u; i++) { + u32 b = (h[10 + (i >> 2)] >> ((i & 3u) * 8u)) & 0xFFu, k = (b & 15u) + 1u; + while (k--) { row[x++] = pal[b >> 4]; if (x == 128u) { hw_px_row(row, 128); x = 0; y++; } } + } + hw_px_end(); + hw_backlight(1); + REG(0xE000EDFCu) |= 1u << 24; REG(0xE0001000u) |= 1u; /* cycle counter: about 3 s at 96 MHz */ + for (u32 c0 = REG(0xE0001004u); REG(0xE0001004u) - c0 < 288000000u; ) hw_wdt_feed(); +} +#define BAT_PIC_SHOW() bat_pic() +#else +#define BAT_PIC_SHOW() ((void)0) +#endif +/* called every second or so: 1 once the battery is low */ +__attribute__((noinline, unused, minsize)) static int bat_guard_tick(void) +{ + static u8 c, n; + if (++c < 20u) return 0; + c = 0; n = bat_is_low() ? (u8)(n + 1u) : 0u; + return n >= 2u; +} +#endif +#endif diff --git a/emu/src/emu/build.sh b/emu/src/emu/build.sh new file mode 100644 index 0000000..bea4c0c --- /dev/null +++ b/emu/src/emu/build.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -e +cd "$(dirname "$0")" +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -O2 -g -fno-common -Wall -Wno-initializer-overrides -Wno-unused-const-variable -fno-builtin-memset -DTC_JIT -DJIT_HASH=512 -DJIT_HWRITE -DNOSRAMWATCH -DJIT_STAGE -DROM_CACHED -DTONE_FIX -DHW_TONE_RESTART -DWAKE_WHEEL -DBL_BLACK -DBL_OFFFIX -DBL_SLEEP -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DLCD_ROWS -DLCD_SKIP -DGFLUSH_STEP -DCLEAN -DGFLUSH_DARK -DGFLUSH_IDLE -DJIT_WHOT -DRTC_MS -DLCD_QUIET -DHW_OPTS -DSESS_ONCE -DSESS_AUTO -DOPT_MENU -DASK_EXTRA -DASK_SLIM -DASK_NUM -DEMU_CARE -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DAPP_SELF -DBL_GUEST_PWM -DTC_IRLINK -DBAT_SHOW -DCLK_ECO -DECO_LAG=50 -DEMU_OVL -DASK_OVL -DDISP_PACK -DASK_DIM -DEMU_DIM -DASK_LANG -DBAT_SMOOTH -DEMU_PW -DJIT_HOT=8 -DEMU_TONE_Q -DEMU_TONE_GAP -DEMU_TQ_DROP -DTONE_SAFE -DEMU_DATE_FIX -DBAT_GUARD -DBAT_PIC -DLIBC_ALIAS -DHW_COLD_MIN -DLK_SYNC -DTC_LZ -DCLK_DISC -DSESS_FLAG -DEMU_KEY_AWAKE -DLZ_GONE -DLIBC_WORD -DID_STRAP -mllvm -arm-load-store-opt=false $XCF" +O="" +for f in main.c hw.c ask.c libc.c flash.c state.c ../core/tc_all.c; do + n=$(basename $f .c); X=""; [ "$n" = ask ] && X=-Oz; [ "$n" = hw ] && X=-Os; [ "$n" = state ] && X=-Os; [ "$n" = flash ] && X=-Os; case "$CF" in *-DLIBC_WORD*) [ "$n" = libc ] && X=-Os;; esac; case "$CF" in *-DEMU_TONE_Q*) [ "$n" = state ] && X=-Oz; [ "$n" = flash ] && X=-Oz;; esac; case "$CF" in *-DEMU_OVL*) [ "$n" != tc_all ] && X="$X -mno-outline";; esac; clang $CF $X -c $f -o $n.o; O="$O $n.o"; done +LDS=link.ld; case "$CF" in *-DEMU_OVL*) LDS=link_ovl.ld;; esac +ld.lld -T $LDS --no-rosegment $O -o emu.elf +llvm-objcopy -O binary -j .text -j .data -j .init emu.elf emu.bin +llvm-size emu.elf; ls -l emu.bin diff --git a/emu/src/emu/disp_pack.h b/emu/src/emu/disp_pack.h new file mode 100644 index 0000000..d96d9a9 --- /dev/null +++ b/emu/src/emu/disp_pack.h @@ -0,0 +1,6 @@ +/* disp_pack.h - generated from disp_power.h (the same sequence, packed: switch DISP_PACK). 1.6.13 (TamaEmu: room in the + * program): addresses and values each from a table, one byte per index. Author: mameise */ +#define DISP_PACK_N 262 +__attribute__((section(".initdata"))) static const unsigned int disp_pack_a[36]={0x45000020,0x45000210,0x45000214,0x45000218,0x45000204,0x45000200,0x4003a000,0x4003a004,0x40038000,0x40038014,0x40038018,0x40038004,0x40038008,0x4003800c,0x40038010,0x40007034,0x4001803c,0x4001903c,0x4001a03c,0x40018004,0x40018000,0x40018008,0x40019004,0x40019000,0x40019008,0x4001a004,0x4001a000,0x4001a008,0x40003000,0x40003018,0x4000301c,0x40003020,0x40003024,0x40003014,0x40003008,0x4000303c}; +__attribute__((section(".initdata"))) static const unsigned int disp_pack_v[73]={0x40,0x0,0xe0,0x42,0x8000,0x8001,0xf0,0xa001,0x18005da0,0xffc,0x1,0x10,0x18000ba0,0xffffffff,0xfffff5df,0x30,0xfffffffe,0x15008a56,0x15008a55,0xfffffffd,0x15008a59,0xfffffffb,0x15008a65,0xfffffff7,0x15008a95,0x20,0xffffffef,0x15008855,0xffffffcf,0x15008055,0xffffff4f,0xfffffecf,0x15028055,0xfffffdcf,0x15088055,0xfffffbcf,0x15208055,0xfffff7cf,0x15808055,0xffffefcf,0x16008055,0xffffdfcf,0x19008055,0xffffbfcf,0x25008055,0xa00,0x55995800,0xa20,0xfffff59f,0x55996800,0xfffff55f,0x55999800,0xfffff4df,0x559a5800,0x820,0xfffff1df,0x55a95800,0x220,0xffffe5df,0x56995800,0xffffd5df,0x59995800,0xffffb5df,0x65995800,0xffff75df,0x95995800,0x52,0x50,0x58,0x60,0x90,0x2,0x1f}; +__attribute__((section(".initdata"))) static const unsigned char disp_pack_i[262][2]={{0,0},{1,1},{2,1},{3,1},{4,1},{5,2},{4,1},{5,2},{0,3},{6,4},{7,4},{7,5},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,12},{12,9},{13,10},{14,10},{8,11},{8,1},{15,1},{8,1},{9,6},{10,7},{9,6},{11,12},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{9,6},{10,7},{9,6},{11,8},{12,9},{13,10},{14,10},{8,11},{8,1},{16,13},{17,14},{18,13},{19,15},{20,16},{21,17},{19,15},{20,16},{21,18},{19,15},{20,19},{21,20},{19,15},{20,19},{21,18},{19,15},{20,21},{21,22},{19,15},{20,21},{21,18},{19,15},{20,23},{21,24},{19,15},{20,23},{21,18},{19,25},{20,26},{21,18},{19,15},{20,26},{21,27},{19,11},{20,28},{21,27},{19,15},{20,28},{21,29},{19,15},{20,30},{21,29},{19,15},{20,30},{21,29},{19,15},{20,31},{21,32},{19,15},{20,31},{21,29},{19,15},{20,33},{21,34},{19,15},{20,33},{21,29},{19,15},{20,35},{21,36},{19,15},{20,35},{21,29},{19,15},{20,37},{21,38},{19,15},{20,37},{21,29},{19,15},{20,39},{21,40},{19,15},{20,39},{21,29},{19,15},{20,41},{21,42},{19,15},{20,41},{21,29},{19,15},{20,43},{21,44},{19,15},{20,43},{21,29},{22,45},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,48},{24,49},{22,47},{23,48},{24,46},{22,47},{23,50},{24,51},{22,47},{23,50},{24,46},{22,47},{23,52},{24,53},{22,47},{23,52},{24,46},{22,54},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,55},{24,56},{22,47},{23,55},{24,46},{22,57},{23,14},{24,46},{22,47},{23,14},{24,46},{22,47},{23,58},{24,59},{22,47},{23,58},{24,46},{22,47},{23,60},{24,61},{22,47},{23,60},{24,46},{22,47},{23,62},{24,63},{22,47},{23,62},{24,46},{22,47},{23,64},{24,65},{22,47},{23,64},{24,46},{25,1},{26,16},{27,66},{25,1},{26,16},{27,67},{25,1},{26,19},{27,68},{25,1},{26,19},{27,67},{25,1},{26,21},{27,69},{25,1},{26,21},{27,67},{25,1},{26,23},{27,70},{25,1},{26,23},{27,67},{28,1},{29,1},{30,1},{31,1},{32,1},{33,1},{28,71},{34,1},{35,72},{28,10},{22,47},{23,55},{24,56},{22,47},{23,55},{24,46}}; diff --git a/emu/src/emu/disp_power.h b/emu/src/emu/disp_power.h new file mode 100644 index 0000000..7e6f6f2 --- /dev/null +++ b/emu/src/emu/disp_power.h @@ -0,0 +1,5 @@ +// Extracted from the REAL Flash Utility (same PRAM/post-reset context as +// our app). Order kept word for word. clk tail (reset release) first, +// then display/GPIO/backlight registers. +__attribute__((section(".initdata"))) static const unsigned int disp_power_seq[][2]={{0x45000020,0x40},{0x45000210,0x0},{0x45000214,0x0},{0x45000218,0x0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000020,0x42},{0x4003a000,0x8000},{0x4003a004,0x8000},{0x4003a004,0x8001},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40007034,0x0},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x4001803c,0xffffffff},{0x4001903c,0xfffff5df},{0x4001a03c,0xffffffff},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a56},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a59},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a65},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a95},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a55},{0x40018004,0x20},{0x40018000,0xffffffef},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xffffffef},{0x40018008,0x15008855},{0x40018004,0x10},{0x40018000,0xffffffcf},{0x40018008,0x15008855},{0x40018004,0x30},{0x40018000,0xffffffcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15028055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15088055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15208055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15808055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x16008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x19008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x25008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x15008055},{0x40019004,0xa00},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55996800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55999800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x559a5800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x55995800},{0x40019004,0x820},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800},{0x40019004,0x220},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x56995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x59995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x65995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x95995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x55995800},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x52},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x58},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x60},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x90},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x50},{0x40003000,0x0},{0x40003018,0x0},{0x4000301c,0x0},{0x40003020,0x0},{0x40003024,0x0},{0x40003014,0x0},{0x40003000,0x2},{0x40003008,0x0},{0x4000303c,0x1f},{0x40003000,0x1},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800}}; +#define DISP_POWER_N 262 diff --git a/emu/src/emu/eco.h b/emu/src/emu/eco.h new file mode 100644 index 0000000..bfecf4d --- /dev/null +++ b/emu/src/emu/eco.h @@ -0,0 +1,80 @@ +/* eco.h - 1.6.9 test22 (switch CLK_ECO): a lower clock while the screen is off, to save the batteries. + * The Paradise runs at 96 MHz; the old toys need a fraction of it when nothing is drawn. Every 500 ms the core's own + * cycle counter (DWT CYCCNT, it stands while the core sleeps in WFI) tells how busy the emulation was: below 35 % one + * step down (half the clock), above 80 % one step up, down to 12 MHz (AHB / 8). If the emulation falls behind anyway, + * straight back to full speed and for 5 minutes one step less deep. Full speed at once + * for a key, the screen on, a tone or link traffic. Header only. Author: mameise */ +#ifndef ECO_H +#define ECO_H +#include "hw.h" +#ifndef ECO_SH +#define ECO_SH 3u /* lowest: 96 MHz >> 3 = 12 MHz */ +#endif +#ifndef ECO_LAG +#define ECO_LAG 25 /* ms behind: too slow (the apps drop time only beyond 50 ms) */ +#endif +#define ECO_DEMCR REG(0xE000EDFCu) +#define ECO_DWT_CTRL REG(0xE0001000u) +#define ECO_CYC REG(0xE0001004u) +#ifdef ECO_DEBUG +__attribute__((used)) volatile u32 g_eco_dbg[4]; /* tests: ups, last lag, last busy, want_low drops */ +#endif +static u32 g_eco_hold, g_eco_t0, g_eco_c0, g_eco_on, g_eco_max = ECO_SH, g_eco_max_until; +/* too slow: full speed, wait longer before the next try. Also called from the apps' catch-up loops. */ +__attribute__((noinline, unused, minsize)) static void eco_up(u32 now, u32 core_hz) +{ + /* this step was too slow: back to full speed at once, then at most one step less deep for 5 minutes */ +#ifdef ECO_DEBUG + g_eco_dbg[0]++; +#endif + if (g_hw_clk_sh) { g_eco_max = g_hw_clk_sh - 1u; g_eco_max_until = now + 300000u; hw_clk_shift(0, core_hz); g_eco_hold = now + 2000u; } + g_eco_t0 = now; g_eco_c0 = ECO_CYC; +} +#define ECO_CHECK(now, lag, hz) do { if (g_hw_clk_sh && (int)(lag) > ECO_LAG) eco_up((now), (hz)); } while (0) +#ifdef ECO_RTC +/* test27 (switch ECO_RTC): the millisecond tick against the Paradise's seconds counter (crystal). Every 4 whole + * seconds at one clock step: if fewer than 3800 ms were counted, the missing ms are returned (the program adds them + * to its tick, the emulation catches up) and that clock step is not used again until the next start. */ +static u32 g_er_s, g_er_ms, g_er_n, g_er_sh; +__attribute__((used)) volatile u32 g_eco_bad, g_eco_fix[2]; /* clock steps found wrong; corrections, ms added */ +__attribute__((noinline, unused, minsize)) static u32 eco_rtc(u32 now, u32 core_hz) +{ + u32 s = REG(0x45000304u), add = 0; + if (s == g_er_s) return 0; + if (s - g_er_s == 1u && g_er_sh == g_hw_clk_sh) { + if (!g_er_n) { g_er_n = 1; g_er_ms = now; } /* a window starts at a change of the second */ + else if (++g_er_n >= 5u) { + u32 d = now - g_er_ms; + if (d + 200u < 4000u) { + add = 4000u - d; g_eco_fix[0]++; g_eco_fix[1] += add; + if (g_hw_clk_sh) { g_eco_bad |= 1u << g_hw_clk_sh; hw_clk_shift(0, core_hz); } + } + g_er_n = 1; g_er_ms = now + add; g_er_sh = g_hw_clk_sh; + } + } else { g_er_n = 0; g_er_sh = g_hw_clk_sh; } /* first call, a second missed or another clock step: wait */ + g_er_s = s; + return add; +} +#define ECO_BAD(sh) ((g_eco_bad >> (sh)) & 1u) +#else +#define ECO_BAD(sh) 0u +#endif +/* want_low: screen off, no key, no tone, no link; lag: how many ms the emulation is behind now; core_hz: SysTick base */ +__attribute__((noinline, unused, minsize)) static void eco_poll(u32 now, int want_low, int lag, u32 core_hz) +{ + u32 sh = g_hw_clk_sh; + if (!g_eco_on) { ECO_DEMCR |= 1u << 24; ECO_DWT_CTRL |= 1u; g_eco_on = 1; g_eco_t0 = now; g_eco_c0 = ECO_CYC; } +#ifdef ECO_DEBUG + if (!want_low && sh) g_eco_dbg[3]++; + if (lag > (int)g_eco_dbg[1]) g_eco_dbg[1] = (u32)lag; +#endif + if (!want_low) { if (sh) hw_clk_shift(0, core_hz); g_eco_hold = now + 1000u; g_eco_t0 = now; g_eco_c0 = ECO_CYC; return; } + if (lag > ECO_LAG) { eco_up(now, core_hz); return; } + if (now - g_eco_t0 < 500u) return; + u32 cyc = ECO_CYC - g_eco_c0, avail = (core_hz >> sh) / 1000u * (now - g_eco_t0), busy = avail >= 100u ? cyc / (avail / 100u) : 100u; + g_eco_t0 = now; g_eco_c0 = ECO_CYC; + if (busy > 80u && sh) { hw_clk_shift(sh - 1u, core_hz); g_eco_hold = now + 2000u; return; } + if (g_eco_max < ECO_SH && (int)(now - g_eco_max_until) >= 0) g_eco_max++; + if (busy < 35u && sh < g_eco_max && !ECO_BAD(sh + 1u) && (int)(now - g_eco_hold) >= 0) hw_clk_shift(sh + 1u, core_hz); +} +#endif diff --git a/emu/src/emu/exitkey.h b/emu/src/emu/exitkey.h new file mode 100644 index 0000000..99d00e2 --- /dev/null +++ b/emu/src/emu/exitkey.h @@ -0,0 +1,20 @@ +/* exitkey.h - test24 (switch EXIT_KEY): how to go back to the Paradise or the menu, chosen in the Studio (tab Menu) for + * every program. The Studio writes "EX" << 16 | mode into the last word of the program's vector table (0x13C, IRQ 63, + * never used); without it the program's own way stays. Modes: 0 wheel held (as before), 1 wheel and A held, 2 wheel + * and C held, 3 wheel held 5 s. Header only. Author: mameise */ +#ifndef EXITKEY_H +#define EXITKEY_H +#include "hw.h" +#ifdef EXIT_KEY +/* the wheel held for held ms (def: the program's own time): 1 = go back */ +__attribute__((noinline, unused, minsize)) static int exit_now(u32 held, u32 def) +{ + u32 v = *(volatile const u32 *)0x13Cu, m = (v >> 16) == 0x5845u ? (v & 3u) : 0u; + if (m == 1u || m == 2u) return held > 300u && (hw_buttons() & (m == 1u ? BTN_A : BTN_C)) != 0u; + return held > (m == 3u ? 5000u : def); +} +#define EXIT_NOW(held, def) exit_now((held), (def)) +#else +#define EXIT_NOW(held, def) ((held) > (def)) +#endif +#endif diff --git a/emu/src/emu/flash.c b/emu/src/emu/flash.c new file mode 100644 index 0000000..a679430 --- /dev/null +++ b/emu/src/emu/flash.c @@ -0,0 +1,95 @@ +/* Write the Paradise flash: erase and program a sector, exactly like the + * mameise flash app (confirmed on the device). Runs from PRAM; nothing may be + * read from the XIP window while writing. */ +#include "io.h" +#include "flash.h" +#define F_DMEM REG(FCTL+0x100) +#define F_DLEN REG(FCTL+0x104) +#define F_DCTL REG(FCTL+0x108) +#define F_DFLA REG(FCTL+0x10C) + +static void feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } +static void wait_loop(u32 n){ for(volatile u32 i=0;i>1; + REG(FCTL+0x008)=(a1>>16)&0xFFFFu; + REG(FCTL+0x00C)=a1 & 0xFFFFu; + REG(FCTL+0x004)=0x00000400u; + for(u32 g=0; (REG(FCTL+0x004)&0x400u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + for(u32 g=0; (REG(FCTL+0x004)&0x2u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); +} + +void flash_prog4k(u32 addr, const void *src) +{ + u32 a1=addr>>1; + u32 hi=(a1>>16)&0xFFFFu; + u32 lo=a1 & 0xFFFFu; + flash_erase4k(addr); + /* program */ + REG(FCTL+0x008)=0x3000u | hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; + REG(FCTL+0x000)=0x0000d080u; + REG(FCTL+0x020)=0; + REG(FCTL+0x010)=0; + REG(FCTL+0x000)=0x0000d082u; + F_DFLA=0x60000000u | (addr & 0x00FFFFFFu); + F_DLEN=0x1000u; F_DMEM=(u32)src; + F_DCTL=0u; + F_DCTL=1u; + for(u32 g=0; (F_DCTL & 1u) && g<20000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); +} + +void flash_read(u32 addr, void *dst, u32 len) +{ + const volatile u8 *s=(const volatile u8*)(0x60000000u + (addr & 0x00FFFFFFu)); + u8 *d=(u8*)dst; + for(u32 i=0;i +extern uint32_t g_gp_secs, g_gp_last; +#define GP_CNT (*(volatile uint32_t *)0x45000304u) +#define GP_RATE 10u +#define GP_MAX 99999u +#define GP_F 64u +static inline void gp_key(uint32_t b) +{ + if (!b) return; + uint32_t s = GP_CNT, d = s - g_gp_last; + if (g_gp_last && d <= 60u) g_gp_secs += d; + g_gp_last = s; +} +#ifdef GP_POINTS /* the part that writes (with paraback.h: flash_read, flash_update4k, pb_crc) */ +static inline uint32_t gp_u32(const uint8_t *b, uint32_t o) { return b[o] | (uint32_t)b[o + 1] << 8 | (uint32_t)b[o + 2] << 16 | (uint32_t)b[o + 3] << 24; } +/* b: 4 KB buffer. Returns the points added. */ +__attribute__((noinline, unused, minsize)) PB_ATTR static uint32_t para_points(uint8_t *b) +{ + uint32_t add = g_gp_secs / 60u * GP_RATE, mo = 0; + if (!add) return 0; + for (uint32_t p = 0x90000u; p < 0x110000u && !mo; p += 0x1000u) { + flash_read(p + 0x140u, b, 264u); + if (gp_u32(b, 0) == 0x444C4546u && gp_u32(b, 4) >= 9u && (gp_u32(b, 36) & GP_F)) mo = gp_u32(b, 260); + } + if (!mo || mo + 4u > 0x1000u) return 0; + flash_read(0xEFE000u, b, 0x1000u); + uint32_t c = pb_crc(b); + if (pb_u16(b, 0) != c || pb_u16(b, 2) != (~c & 0xFFFFu)) return 0; + uint32_t m = gp_u32(b, mo), n = m + add; + if (m > GP_MAX) return 0; /* not a money field as we know it */ + if (n > GP_MAX) n = GP_MAX; + b[mo] = (uint8_t)n; b[mo + 1] = (uint8_t)(n >> 8); b[mo + 2] = (uint8_t)(n >> 16); b[mo + 3] = (uint8_t)(n >> 24); + c = pb_crc(b); + pb_w16(b, 0, c); pb_w16(b, 2, ~c & 0xFFFFu); + flash_update4k(0xEFE000u, b); + flash_update4k(0xEFF000u, b); + g_gp_secs %= 60u; + return n - m; +} +#endif +#endif diff --git a/emu/src/emu/hw.c b/emu/src/emu/hw.c new file mode 100644 index 0000000..590eba7 --- /dev/null +++ b/emu/src/emu/hw.c @@ -0,0 +1,471 @@ +/* Paradise hardware (SNC73410), taken from the mameise flash app + * (display confirmed on the device). Runs from PRAM 0 after SYSRESETREQ. */ +#include "io.h" +#ifdef HW_COLD_MIN +#define HCOLD __attribute__((minsize)) /* test21: rarely called, smaller (room in TamaEmu's 64 KB) */ +#else +#define HCOLD +#endif +#include "hw.h" +#ifdef DISP_PACK +#include "disp_pack.h" +#else +#include "disp_power.h" +#endif +#define PANEL 0x4000E000u +#define FCTL_ 0x40022000u +#define F_STAT REG(FCTL_+0x000) +static void udelay(volatile u32 n){ while(n--) __asm__ volatile("nop"); } +#define MS(x) udelay((u32)(x)*16000u) +#define BB(reg,bit) (*(volatile u32*)(0x42000000u + (((u32)(reg)-0x40000000u)<<5) + ((u32)(bit)<<2))) +#define GPIO0 0x40018000u +#define GPIO1 0x40019000u +#define GPIO2 0x4001A000u +#define LCD_RST(v) (BB(GPIO0+0x00,4)=(v)) +#define LCD_DC(v) (BB(GPIO0+0x00,5)=(v)) +#define SPI_CTRL REG(PANEL+0x00) +#define SPI_STAT REG(PANEL+0x0C) +#define SPI_DATA REG(PANEL+0x1C) +#define SPIWAIT 200000u +#define CT2 0x40002000u +TC_INIT static void clock_init(void){ + REG(CLK+0x00) |= 1u; + REG(CLK+0x0C) = 0; + REG(CLK+0x00) = 0x41u; + { u32 r = (REG(CLK+0x34) & 0xF00u) | 0xA55A0000u; REG(CLK+0x04) = r; } + REG(CLK+0x18) = 0x21u; + REG(CLK+0x50) = 0; + REG(CLK+0x10C) = 0x001FFFFDu; + REG(CLK+0x110) = 0; + REG(CLK+0x108) = 0; + REG(CLK+0x10) = 0; + REG(CLK+0x00) |= 0x10u; + for(u32 g=0; !((REG(CLK+0x08) >> 4) & 1u) && g<4000000u; g++){} + REG(CLK+0x00) |= 0x4000u; + REG(CLK+0x04) &= ~1u; + REG(CLK+0x00) |= 0x8000u; + for(u32 g=0; !((REG(CLK+0x08) >> 6) & 1u) && g<4000000u; g++){} + { u32 r = (REG(CLK+0x0C) & ~7u) | 4u; REG(CLK+0x0C) = r; } + for(u32 g=0; ((REG(CLK+0x0C) >> 4) & 7u) != (REG(CLK+0x0C) & 7u) && g<4000000u; g++){} /* bounded: never hang forever */ + REG(CLK+0x100) = 0x00157EB7u; +} +TC_INIT static void flashctl_init(void){ + /* 1.4.2: enable XIP. We read through the 0x60000000 window that the + * XIP block maps in. Without XIP, only the config register (0x40) shows there, not + * the flash data. The real Flash Utility does this at startup; our app did not + * do it after reset until now. That was exactly what was missing. */ + REG(0x4002F004u)=0x60011000u; + REG(0x4002F000u)=0x00000003u; + /* 1.4.1: controller init word for word like the real Flash Utility (0x40022000). + * This includes setting the read command/mode in 0x008 and 0x00c (0x3077 / 0xf000), otherwise + * the chip only returns its config register (0x40) instead of the flash data. */ + F_STAT=0x0000d018u; + F_STAT=0x0000d000u; + F_STAT=0x0000d080u; + F_STAT=0x0000d088u; + REG(FCTL+0x008)=0x00003077u; /* read command/mode */ + REG(FCTL+0x00C)=0x0000f000u; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; +} +TC_INIT static void wdt_off(void){ + /* Set up the system/power block EXACTLY like the real Flash Utility. The only + point where we deliberately deviated before (bit0 of 0x40008000) could be the + master enable for the display domain. The FU runs with bit0=1 without a + reset, so we copy it 1:1 and feed the watchdog in the loop. */ + REG(0x4000900Cu)=0x5AFA55AAu; REG(0x40009000u)=0x5AFA0000u; /* WDT1 */ + REG(0x40008000u)=0x5AFA0000u; /* unlock */ + REG(0x40008004u)=0x5AFA0002u; + REG(0x40008008u)=0x5AFA00FFu; /* power/clock domains on (incl. display) */ + REG(0x4000800Cu)=0x5AFA55AAu; /* feed the watchdog */ + /* Do NOT set bit0 (watchdog enable): otherwise it reset the Tama during + display initialisation (back to the planet). */ +} +TC_INIT static void mailbox_clear(void){ + REG(0x20000000u)=0; REG(0x20000004u)=0; REG(0x20000008u)=0; REG(0x2000000Cu)=0; +} +TC_INIT static void periph_enable(void){ REG(CLK+0x20)=0x40u; } +TC_INIT static void pin_set(u8 id, u8 mode){ *(volatile u8*)(0xE000E400u + id) = (u8)(mode<<4); } +TC_INIT static void pin_mux(void){ + static const u8 m12[]={6,7,8,9,0xf,0x10,0x11,0x12,0x13,0x14,0x19,0x1f,0x20,0x22, + 0x24,0x25,0x2e,0x2f,0x35,0x36,0x1a,0x1b,0x1c,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x3a,0x3f}; + static const u8 m8[]={0,1,2,3}; + static const u8 m4[]={0x15,0x17}; + for(unsigned i=0;i=0x45000210u && a<=0x45000218u) v=REG(0x4001803Cu + ((a-0x45000210u)>>2)*0x1000u); + REG(a)=v; + } + /* make sure the panel pins are outputs: reset, D/C, CS (P1.5 low), supply (P1.9 low) */ + LCD_RST(1); BB(GPIO0+0x04,4)=1; + LCD_DC(0); BB(GPIO0+0x04,5)=1; + BB(GPIO1+0x00,5)=0; BB(GPIO1+0x04,5)=1; + BB(GPIO1+0x00,9)=0; BB(GPIO1+0x04,9)=1; + MS(20); +} +TC_INIT static void spi_init(void){ + /* like FU 0x3f44, as read-modify-write */ +#ifdef LCD_FASTCLK + REG(PANEL+0x08)=0; /* clock divider: experiment v0.8.18, twice as fast? */ +#else + REG(PANEL+0x08)=1; /* clock divider */ +#endif + SPI_CTRL &= ~(1u<<18); + REG(PANEL+0x04) &= ~6u; REG(PANEL+0x04) &= ~1u; + SPI_CTRL &= ~0x10u; SPI_CTRL &= ~0x08u; + REG(PANEL+0x20)=0; + SPI_CTRL = (SPI_CTRL & ~0xF00u) | 0x700u; /* 8 bit */ + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFF0000u; + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFFu; + SPI_CTRL |= 1u; /* SPI on */ + SPI_CTRL |= 0xC0u; /* clear FIFOs */ +} +static void spi_tx(const u8* p, u32 n){ + for(u32 i=0;i= 100u){ g_pwm_mctrl = 0u; pwm2(0x17700u, first); return; } /* full: exactly as before */ + g_pwm_mctrl = 0x400u; pwm2(0x17700u - 0x17700u * p / 100u, first); g_pwm_mctrl = 0u; } +#else +static void bl_apply(int first){ u32 p = g_bl_pct; pwm2(p >= 100u ? 0x17700u : (0x17700u * p / 100u ? 0x17700u * p / 100u : 1u), first); } +#endif +void hw_bl_set(u32 pct){ if(pct > 100u) pct = 100u; if(pct == g_bl_pct) return; g_bl_pct = pct; if(g_bl_on) bl_apply(0); } +#endif +TC_INIT static void backlight_on(void){ + REG(0x40007034u)=0; + pwm2(0x17700u,1); + REG(0x40009000u)=0x5AFA0000u; REG(0x40008000u)=0x5AFA0000u; /* like FU */ + REG(0x40018034u)=0x15555155u; REG(0x40019034u)=0x55540140u; +#ifdef BL_PWM + bl_apply(0); +#else + pwm2(0,0); +#endif + REG(CLK+0x20)=0x42u; +} + +/* ---------------- own additions ---------------- */ +/* Buzzer on timer 7, started and stopped exactly like the firmware does: + * period in 72 MHz cycles, short pulse (quiet, as on the Paradise). */ +#define CT7 0x40007000u +#ifdef TONE_FIX +/* v0.8.15: the counter runs periodically (MCTRL bit 10 = restart at MR3, like the backlight with 0x400). + * Before, MCTRL ended up at 0: only a single pulse per call, so a click instead of a tone. + * If only the pitch changes, only MR0/MR3 are updated (no restart, no click). */ +#ifdef HW_OPTS +/* 1.6.8: volume and brightness set in the Studio (TamaEmu, T18Emu). Volume: pulse length (0 off, 1 quiet 1/128, + * 2 normal 1/32 as before, 3 loud 1/8 of the period). Brightness: the pixels darkened (0 = 100 %, 1 75, 2 50, 3 25 %). */ +u32 g_hw_vol = 2u, g_hw_dim = 0u; +static const u8 VOL_SH[4] = { 5, 7, 5, 3 }; +#endif +#ifdef HW_VOL5 +/* 1.6.12 test3 (T7Emu): volume in 5 steps by the pulse length: 0 off, 1 1/32 of the period (as before), 2 1/8, + * 3 1/4, 4 1/2 (a square wave, the loudest the buzzer gets) */ +u32 g_hw_vol5 = 1u; +static const u8 VOL5_SH[5] = { 5, 5, 3, 2, 1 }; +#endif +#ifdef CLK_ECO +u32 g_hw_clk_sh; /* 1.6.9 test22: AHB clock divided by 2^sh (eco.h); the tone timer runs on the divided clock too */ +u32 g_hw_tone_hz; +#define TONE_CLK (72000000u >> g_hw_clk_sh) +#else +#define TONE_CLK 72000000u +#endif +#ifdef HW_TONE_IRQSAFE +/* 1.6.12 test4 (T7Emu): the tone is also set from the SysTick (T7_TONE_ISR); a call from the main loop must not be + * cut in the middle of the register writes */ +static void hw_tone_raw(u32 hz); +void hw_tone(u32 hz){ u32 pm; __asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory"); hw_tone_raw(hz); __asm__ volatile("msr primask, %0" :: "r"(pm) : "memory"); } +HCOLD static void hw_tone_raw(u32 hz){ +#else +HCOLD void hw_tone(u32 hz){ +#endif + static u32 on; +#ifdef HW_OPTS + if(!g_hw_vol) hz = 0; +#endif +#ifdef HW_VOL5 + if(!g_hw_vol5) hz = 0; +#endif +#ifdef CLK_ECO + g_hw_tone_hz = hz; +#endif + if(!hz){ REG(CT7+0x34)=0; REG(CT7+0x00)=0; on=0; return; } +#ifdef HW_OPTS + u32 per = TONE_CLK / hz, mr0 = per - (per >> VOL_SH[g_hw_vol & 3u]); +#elif defined(HW_VOL5) + u32 per = TONE_CLK / hz, mr0 = per - (per >> VOL5_SH[g_hw_vol5 > 4u ? 4u : g_hw_vol5]); +#else + u32 per = TONE_CLK / hz, mr0 = per - per/32u; +#endif +#ifndef HW_TONE_RESTART + /* 1.7.4 HW_TONE_RESTART: a new pitch written into the running timer left the buzzer silent on the device (GBEmu + * test39; users: the sound cuts off in the emulators). With it every new pitch starts the timer anew below. */ + if(on){ REG(CT7+0x24)=per; REG(CT7+0x18)=mr0; +#ifdef TONE_SAFE /* 1.6.9 test38 (GBEmu): a shorter period below the running counter left the buzzer silent until the + * 32-bit counter wrapped (~60 s); then the counter starts again */ + if(REG(CT7+0x08) >= per){ REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=1; } +#endif + return; } +#endif + REG(CT7+0x34)=0; + REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=0; + REG(CT7+0x18)=mr0; REG(CT7+0x1C)=0; REG(CT7+0x20)=0; + REG(CT7+0x24)=per; + REG(CT7+0x14)=0x400u; + REG(CT7+0x34)=0x00100001u; + REG(CT7+0x3C)=0x1Fu; + REG(CT7+0x00)=1; + on=1; +} +#else +void hw_tone(u32 hz){ + if(!hz){ REG(CT7+0x34)=0; return; } + u32 per = 72000000u / hz, mr0 = per - per/32u; + REG(CT7+0x34)=0; + REG(CT7+0x00)=0; + REG(CT7+0x18)=0; REG(CT7+0x1C)=0; REG(CT7+0x20)=0; REG(CT7+0x24)=0; + REG(CT7+0x14)=0; + REG(CT7+0x00)=2; REG(CT7+0x08)=0; REG(CT7+0x00)=0; + REG(CT7+0x14)=0x600u; + REG(CT7+0x24)=per; + REG(CT7+0x18)=mr0; + REG(CT7+0x14)=0; + REG(CT7+0x34)=0x00100001u; + REG(CT7+0x00)=2; + REG(CT7+0x3C)=0x1Fu; + REG(CT7+0x00)=1; +} +#endif +void hw_bl_pwm_off(void){ REG(CT2+0x00)=0; REG(CT2+0x34)=0; } /* backlight off only (when leaving) */ +#ifdef HW_BL_LEVELS /* 1.6.6 tests (T7 dimming): the PWM had no visible effect on the device */ +/* 1.6.6 test: backlight in percent through the PWM (MR1: 0 = full; near the period = dark), panel stays on */ +void hw_bl_level(u32 pct){ if(pct>=100u) pwm2(0u,0); else pwm2(0x17700u - 0x17700u*pct/100u, 0); } +/* 1.6.6 test: which setting dims on the device? m bit 0: MR1 = pct of the period (else the rest of it), + * bit 1: 20 kHz (else 750 Hz like the Paradise firmware) */ +void hw_bl_test(u32 m, u32 pct){ + u32 per = (m & 2u) ? 3600u : 0x17700u; + u32 mr1 = (m & 1u) ? per*pct/100u : per - per*pct/100u; + pwm2p(mr1, per, 0); +} +#endif +#ifdef BL_SLEEP +/* v0.8.18: off = put the display to sleep (DISPOFF, SLPIN) and stop the backlight timer, + * PWM output off (like panel_down in the Flash Tool). On = SLPOUT, short wait, DISPON, backlight restart. + * MR1 values alone (v0.8.17) had no effect on the device. */ +static int is_on=1; +#ifdef WAKE_ASYNC +/* test14: switching the panel on in steps from the main loop (SLPOUT, 125 ms later DISPON, 20 ms later the light), + * hw_backlight(1) waited 145 ms and the emulator fell behind (the ring of a call in standby ran slow). + * Returns 0 when the panel is on already. */ +int hw_wake_step(int ph){ +#ifdef HW_WAKE_ABORT + if(ph==0){ if(is_on) return 0; lcd_cmd(0x28,0,0); lcd_cmd(0x10,0,0); return 1; } /* 1.7.2 test17: woken ahead, nobody came: asleep again */ +#endif + if(ph==1){ if(is_on) return 0; lcd_cmd(0x11,0,0); return 1; } + if(ph==2){ lcd_cmd(0x29,0,0); return 1; } +#ifdef BL_PWM + g_bl_on=1u; bl_apply(1); +#else + pwm2(0u,1); +#endif + is_on=1; return 1; +} +#endif +HCOLD void hw_backlight(int on){ +#ifndef WAKE_QUICK + /* 1.6.8: the panel needs 120 ms after SLPOUT; switched on earlier it showed white for a moment. Its picture is + * kept while it sleeps, so after the wait it shows the old picture, the light comes last. */ +#ifdef BL_PWM + if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(125); hw_wdt_feed(); lcd_cmd(0x29,0,0); MS(20); g_bl_on=1u; bl_apply(1); is_on=1; } +#else + if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(125); hw_wdt_feed(); lcd_cmd(0x29,0,0); MS(20); pwm2(0u,1); is_on=1; } +#endif +#else + if(on){ if(is_on) return; lcd_cmd(0x11,0,0); MS(10); lcd_cmd(0x29,0,0); pwm2(0u,1); is_on=1; } +#endif + else { if(!is_on) return; REG(CT2+0x00)=0; REG(CT2+0x34)=0; lcd_cmd(0x28,0,0); lcd_cmd(0x10,0,0); is_on=0; +#ifdef BL_PWM + g_bl_on=0u; +#endif + } +} +#elif defined(BL_OFFFIX) +/* v0.8.17: duty 0 = full brightness. MR1 equal to the period (0x17700) never matches, so it stayed bright. + * One cycle before the end of the period is practically dark. */ +void hw_backlight(int on){ pwm2(on ? 0u : 0x176FFu, 0); } +#else +void hw_backlight(int on){ pwm2(on ? 0u : 0x17700u, 0); } +#endif +void hw_wdt_feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } + +TC_INIT void hw_init(void){ + wdt_off(); mailbox_clear(); clock_init(); periph_enable(); flashctl_init(); pin_mux(); + display_power(); display_init(); backlight_on(); + /* buttons: P0.8 wheel, P0.9 A, P0.10 C, P0.11 B as inputs (active low) */ + REG(GPIO0+0x04) &= ~((1u<<8)|(1u<<9)|(1u<<10)|(1u<<11)); + flashctl_init(); +} + +#ifdef GPLAY +#include "gplay.h" +uint32_t g_gp_secs, g_gp_last; +#endif +u32 hw_buttons(void){ + u32 d = REG(GPIO0+0x00); + u32 b = 0; + if(!(d & (1u<<9))) b |= BTN_A; + if(!(d & (1u<<11))) b |= BTN_B; + if(!(d & (1u<<10))) b |= BTN_C; + if(!(d & (1u<<8))) b |= BTN_WHEEL; +#ifdef GPLAY + gp_key(b); +#endif + return b; +} + +/* Send rectangle x0..x1-1, y0..y1-1 from a 128-wide framebuffer (RGB565) to the panel. */ +void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1){ + u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)}; + u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)}; + lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4); + LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); } + LCD_DC(1); + for(u32 y=y0;y>8),(u8)r[x]}; + spi_tx(&two[0],1); spi_tx(&two[1],1); /* byte by byte like the FU (1.3.8) */ + } + } + LCD_DC(0); +} + +#ifdef FAST_LCD +/* v0.8.17: display output in one piece per rectangle and 16 bytes per SPI pass (like the gamma tables + * of the display setup, which run this way on the device). Before, per byte: wait, delay of 8, wait. */ +void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1){ + u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)}; + u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)}; + lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4); + LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); } + LCD_DC(1); +} +#ifdef HW_OPTS +__attribute__((noinline, minsize)) static u32 px_dim(u32 v, u32 d){ u32 q=(v>>2)&0x39E7u; return d==1u ? v-q : d==2u ? (v>>1)&0x7BEFu : q; } +#endif +void hw_px_row(const u16* r, u32 n){ + u8 b[16]; u32 k=0; +#ifdef HW_OPTS +#ifdef BL_PWM + u32 d=0; /* the light is dimmed instead */ +#else + u32 d=g_hw_dim; +#endif + #pragma clang loop unroll(disable) + for(u32 i=0;i>8); b[k++]=(u8)v; if(k==16u){ spi_tx(b,16); k=0; } } +#else + for(u32 i=0;i>8); b[k++]=(u8)r[i]; if(k==16u){ spi_tx(b,16); k=0; } } +#endif + if(k) spi_tx(b,k); +} +void hw_px_end(void){ LCD_DC(0); } +#endif + +/* Back to the Paradise: firmware routine that reloads the encrypted PRAM image + and restarts (flash 0x110568, XIP 0x100FF569). */ +#ifdef CLK_ECO +/* 1.6.9 test22: the AHB prescaler (SYS_AHBCP 0x45000010, Sonix TRM: SYSCLK / 2^sh for the core, the memory and, through + * APB, the peripherals). SysTick keeps its 1 ms, a playing tone keeps its pitch. Only while the screen is off. */ +__attribute__((minsize)) void hw_clk_shift(u32 sh, u32 core_hz){ + if(sh > 3u) sh = 3u; + if(sh == g_hw_clk_sh) return; + REG(0x45000010u) = sh; g_hw_clk_sh = sh; + __asm__ volatile("dsb\n isb"); + REG(0xE000E014u) = (core_hz >> sh) / 1000u - 1u; REG(0xE000E018u) = 0; + if(g_hw_tone_hz) hw_tone(g_hw_tone_hz); +} +#endif +void hw_back_to_paradise(void){ + __asm__ volatile("cpsid i"); +#ifdef CLK_ECO + REG(0x45000010u) = 0; /* the Paradise runs at full speed again */ +#endif + ((void(*)(void))(PARADISE_REBOOT|1u))(); + for(;;){} +} diff --git a/emu/src/emu/hw.h b/emu/src/emu/hw.h new file mode 100644 index 0000000..1cf33dc --- /dev/null +++ b/emu/src/emu/hw.h @@ -0,0 +1,38 @@ +#ifndef HW_H +#define HW_H +#include "io.h" +#define BTN_A 1u +#define BTN_B 2u +#define BTN_C 4u +#define BTN_WHEEL 8u +#ifndef PARADISE_REBOOT +#define PARADISE_REBOOT 0x100FF568u +#endif +void hw_init(void); +void hw_wdt_feed(void); +u32 hw_buttons(void); +void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1); +void hw_back_to_paradise(void); +void hw_backlight(int on); +int hw_wake_step(int ph); /* WAKE_ASYNC: 1 SLPOUT, 2 DISPON, 3 light (HW_WAKE_ABORT: 0 asleep again) */ +void hw_bl_pwm_off(void); +void hw_bl_level(u32 pct); +void hw_bl_test(u32 m, u32 pct); +void hw_tone(u32 hz); /* 0 = off */ +#ifdef HW_VOL5 +extern u32 g_hw_vol5; /* 1.6.12 test3: 0 off .. 4 loudest, 1 as before */ +#endif +#ifdef HW_OPTS +extern u32 g_hw_vol, g_hw_dim; /* 1.6.8: volume 0..3 (2 = as before), brightness 0..3 (0 = full) */ +#endif +void hw_bl_set(u32 pct); +#ifdef CLK_ECO +extern u32 g_hw_clk_sh, g_hw_tone_hz; +void hw_clk_shift(u32 sh, u32 core_hz); /* 1.6.9: AHB clock / 2^sh (0..3), SysTick stays 1 ms */ +#endif /* 1.6.8 BL_PWM: light 0..100 % */ +#ifdef FAST_LCD +void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1); +void hw_px_row(const u16* r, u32 n); +void hw_px_end(void); +#endif +#endif diff --git a/emu/src/emu/io.h b/emu/src/emu/io.h new file mode 100644 index 0000000..af5970c --- /dev/null +++ b/emu/src/emu/io.h @@ -0,0 +1,23 @@ +#ifndef IO_H +#define IO_H +typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; +#ifndef REG +#define REG(a) (*(volatile u32*)(a)) +#endif +/* Paradise flash through the uncached XIP window (the host test maps it to an array) */ +#ifndef XIP_PTR +#define XIP_PTR(a) ((const volatile u8*)(0x60000000u + (a))) +#endif +#define UART 0x4000B000u +#define FCTL 0x40022000u +#define CLK 0x45000000u +static inline void dsb(void){ __asm__ volatile("dsb":::"memory"); } + +#ifndef TC_INIT +#ifdef EMU_OVL +#define TC_INIT __attribute__((section(".initcode"), noinline, minsize)) +#else +#define TC_INIT __attribute__((section(".initcode"), noinline)) +#endif +#endif +#endif diff --git a/emu/src/emu/libc.c b/emu/src/emu/libc.c new file mode 100644 index 0000000..a0f6247 --- /dev/null +++ b/emu/src/emu/libc.c @@ -0,0 +1,31 @@ +#include +#ifdef LIBC_WORD +/* 1.7.3 test21: small (-Os) with a word loop when aligned, instead of the unrolled byte loops of -O2 (room in TamaEmu) */ +void *memset(void *d, int c, size_t n){ unsigned char *p=d; unsigned w=(unsigned char)c*0x01010101u; + if(!((unsigned)p&3u)) for(;n>=4;n-=4,p+=4) *(volatile unsigned*)p=w; + while(n--) *p++=(unsigned char)c; return d; } +void *memcpy(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s; + if(!(((unsigned)p|(unsigned)q)&3u)) for(;n>=4;n-=4,p+=4,q+=4) *(volatile unsigned*)p=*(const unsigned*)q; + while(n--) *p++=*q++; return d; } +#else +void *memset(void *d, int c, size_t n){ unsigned char *p=d; while(n--) *p++=(unsigned char)c; return d; } +void *memcpy(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s; while(n--) *p++=*q++; return d; } +#endif +void *memmove(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s; + if(p PRAM + .bss (NOLOAD) : { __bss_start = .; KEEP(*(.stats)) *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM + /* v0.8.16: mutable data lives in SRAM (initial values in PRAM, copied at startup). Writing to + * PRAM while code runs from PRAM corrupts the fetched instructions on the device. */ + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + __ram_end = __data_end; + .init : { + . = ALIGN(4); + __initcode_start = .; + KEEP(*(.initcode)) + KEEP(*(.initdata*)) + __initlast = .; + KEEP(*(.initcode_z)) + . = ALIGN(4); + } > PRAM + /* jit_init writes the fixed routines (just over 2 KB) from __initcode_start while + * it is running itself: it must be placed far enough behind them */ + ASSERT(__initlast - __initcode_start >= 0x1000, "jit_init is too close to the start of the slot") + .jit (NOLOAD) : { . = ALIGN(4); __jit_start = .; . = 0x10000; } > PRAM + __jit_end = 0x10000; + /DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/emu/src/emu/link_ovl.ld b/emu/src/emu/link_ovl.ld new file mode 100644 index 0000000..ecf77d6 --- /dev/null +++ b/emu/src/emu/link_ovl.ld @@ -0,0 +1,44 @@ +/* TamaEmu with EMU_OVL (1.6.13 test10): like link.ld, but the settings menus (ask.c) and the code that runs only when + * leaving or in the settings (.ovltext) sit at the end of the image, in the translator's room (the overlay). The app + * copies them back from its image in the flash when they are needed (ovl_load). */ +ENTRY(Reset_Handler) +MEMORY { + PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000 + SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000 +} +SECTIONS { + .text : { + KEEP(*(.vectors)) + KEEP(*(.pmxcfg)) + *ask.o(.text.keep*) + *(EXCLUDE_FILE(*ask.o) .text*) + *ask.o(.rodata.keep*) + *(EXCLUDE_FILE(*ask.o) .rodata*) + . = ALIGN(4); + __pdata_start = .; + } > PRAM + .bss (NOLOAD) : { __bss_start = .; KEEP(*(.stats)) *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + __ram_end = __data_end; + .init : { + . = ALIGN(4); + __initcode_start = .; + KEEP(*(.initcode)) + KEEP(*(.initdata*)) + __initlast = .; + KEEP(*(.initcode_z)) + . = ALIGN(4); + __ovl_start = .; + *(.ovltext*) + *(.ovlrodata*) + *ask.o(.text* .rodata*) + . = ALIGN(4); + __ovl_end = .; + } > PRAM + ASSERT(__initlast - __initcode_start >= 0x1000, "jit_init is too close to the start of the slot") + ASSERT(__ovl_start - __initcode_start >= 0x1400, "the overlay must lie behind the translator's fixed routines") + .jit (NOLOAD) : { . = ALIGN(4); __jit_start = .; . = 0x10000; } > PRAM + __jit_end = 0x10000; + /DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/emu/src/emu/main.c b/emu/src/emu/main.c new file mode 100644 index 0000000..f8eeba6 --- /dev/null +++ b/emu/src/emu/main.c @@ -0,0 +1,1530 @@ +/* Paramix emulator app for the Tamagotchi Paradise: runs a colour + * Tamagotchi core (tamaemu, GPL-3.0) directly on the device. + * Long press on the wheel: save state and return to the Paradise. */ +#include "hw.h" +#include "exitkey.h" +#include "ask.h" +#include "flash.h" +#include "../core/tc.h" +#include "state.h" +#ifdef TC_IRLINK +#define PL_ATTR __attribute__((noinline, minsize)) +#ifdef EMU_TONE_Q +#define PL_INIT_ATTR __attribute__((section(".initcode"), noinline, minsize)) /* test20: room for the tone queue */ +#endif +#include "plink.h" +#ifdef CLK_ECO +#include "eco.h" +#endif +/* 1.6.9: the guest's infrared bytes to the other Paradise ('E' frames over the contacts) and back */ +static u8 g_irq[512], g_irtxn; +static u16 g_irh, g_irt; +int tc_ir_avail(void) { return g_irh != g_irt; } +int tc_ir_in(void) { if (g_irh == g_irt) return -1; u8 b = g_irq[g_irh & 511u]; g_irh++; return b; } +#ifdef LK_SYNC +/* 1.7.1 LK_SYNC: two iD L (or P's) only connect when each answers within about 10 ms of the other's game time. The + * emulators run on their own: a busy moment (drawing, translating, the flash) put one of them 20 ms or more behind and + * the visit failed ("FAILED"). Now, while infrared bytes go back and forth, each frame ('F') carries how many game ms + * the sender has run; the one that is more than LK_SLACK ms ahead waits here for the other (at most 500 ms without a + * frame from it). Without bytes for 2 s each runs on its own again. */ +#define LK_SLACK 3 +static volatile u32 g_ms; +static u8 g_irtx[64]; /* [0..3] game ms run, then the bytes */ +static u32 g_lk_run, g_lk_off, g_lk_peer, g_lk_act; static u8 g_lk_on; +__attribute__((minsize)) void tc_ir_out(u8 b) { g_lk_act = g_ms; if (g_irtxn < 60u) g_irtx[4 + g_irtxn++] = b; } /* a few bytes per ms: sent after each game ms */ +__attribute__((noinline, minsize)) static void ir_got(u8 ty, const u8 *d, int n) +{ + if (ty != 'F') return; /* our frames carry at least the 4 bytes */ + u32 p; memcpy(&p, d, 4); + if (!g_lk_on) { g_lk_on = 1; g_lk_off = p - g_lk_run; } /* a new exchange: both counts from here */ + g_lk_peer = p; + if (n > 4) g_lk_act = g_ms; + for (int i = 4; i < n; i++) if ((u16)(g_irt - g_irh) < 512u) { g_irq[g_irt & 511u] = d[i]; g_irt++; } +} +/* after each game ms */ +__attribute__((noinline, minsize)) static void ir_link_tick(u32 now) +{ + g_lk_run++; + if (now - g_lk_act >= 2000u) g_lk_on = 0; + else { memcpy(g_irtx, &g_lk_run, 4); plink_send('F', g_irtx, 4 + g_irtxn); g_irtxn = 0; } + do { plink_poll(g_ms, 0, ir_got); hw_wdt_feed(); } + while (g_lk_on && g_ms - g_pl.last_rx < 500u && (int32_t)(g_lk_run + g_lk_off - g_lk_peer) > LK_SLACK); +} +#else +static u8 g_irtx[60]; +__attribute__((minsize)) void tc_ir_out(u8 b) { g_irtx[g_irtxn++] = b; if (g_irtxn >= sizeof g_irtx) { plink_send('E', g_irtx, g_irtxn); g_irtxn = 0; } } +__attribute__((noinline, minsize)) static void ir_got(u8 ty, const u8 *d, int n) +{ + if (ty != 'E') return; + for (int i = 0; i < n; i++) if ((u16)(g_irt - g_irh) < 512u) { g_irq[g_irt & 511u] = d[i]; g_irt++; } +} +__attribute__((noinline, minsize)) static void ir_link_tick(u32 now) { if (g_irtxn) { plink_send('E', g_irtx, g_irtxn); g_irtxn = 0; } plink_poll(now, 0, ir_got); } +#endif +#endif +#ifdef LK_SYNC +#define PARA_ATTR __attribute__((section(".initcode"), minsize)) /* 1.7.1: start code, small (room for LK_SYNC) */ +#else +#define PARA_ATTR __attribute__((section(".initcode"))) +#endif +#ifdef EMU_OVL +/* 1.6.13 test10: code that only runs in the settings or when leaving lives in the overlay at the end of the program + * image, inside the translator's room: ovl_load copies it back from the flash when it is needed (the translator starts + * over afterwards). The translator gets that much more room. */ +#ifdef LK_SYNC +#define OVL_FN __attribute__((section(".ovltext"), noinline, minsize)) /* 1.7.1: settings and leaving, small */ +#else +#define OVL_FN __attribute__((section(".ovltext"), noinline)) +#endif +#define OVL_RO __attribute__((section(".ovlrodata"))) +#define PB_ATTR __attribute__((section(".ovltext"))) +#else +#define OVL_FN +#define OVL_RO +#endif +#include "paraclock.h" +#ifdef PARA_BACK +#ifdef EMU_TONE_Q +#define PB_MARK_ATTR __attribute__((section(".initcode"), minsize)) /* test20: only at the start (in the PRAM image) */ +#endif +#include "paraback.h" +#ifdef BAT_GUARD +#define BAT_PIC_ATTR OVL_FN __attribute__((minsize)) /* test23: in the overlay, PRAM is full */ +#include "batt.h" +static volatile u8 g_bat_go; +#endif +#endif +uint32_t jit_used(void); + +/* Settings, filled in by the ROM builder (magic "PMXC"). */ +#ifdef TC_LZ +typedef struct { u32 magic, version, guest_off, guest_size, save_off, device; u8 map[128]; u32 spare_end, flags, lz_off; } PmxCfg; +#define PMX_VER 5u /* 1.7.3 (GUEST_LZ): lz_off = table of the packed cold blocks (0 = none); the template says 5: the Studio may pack */ +#else +typedef struct { u32 magic, version, guest_off, guest_size, save_off, device; u8 map[128]; u32 spare_end, flags; } PmxCfg; +#define PMX_VER 1u +#endif +/* version 4 (1.5.1): flags bit 1 = at every start the guest clock is set to the Paradise's time */ +/* 1.7.3 test7 (SESS_FLAG): flags bit 12 = no session: leaving, SESS_AUTO and battery empty write only the guest flash */ +/* version 3 (v0.9.2): spare_end = end of the guest area; the room behind the packed firmware holds spare pages */ +__attribute__((section(".pmxcfg"), used)) +volatile const PmxCfg g_cfg = { 0x43584D50u, PMX_VER, 0x940000u, 0x400000u, 0xC0000u, 0, + { [0 ... 63] = 0xFE, [64 ... 127] = 0xFF }, 0, 0 }; /* 0xFE: linear (old layout) */ +static u32 g_para, g_para_cnt; /* the Paradise's time at the start (seconds since 1970, 0 = not found), its counter then */ +#ifdef TC_LZ +TC_INIT static void lz_setup(void){ + tc_lz_tab= g_cfg.version>=5u && g_cfg.lz_off ? (const uint8_t*)(0x60000000u+g_cfg.lz_off) : 0; +} +#endif +static int para_hard(void) { return g_cfg.version >= 4u && (g_cfg.flags & 2u) && g_para; } + +static uint16_t g_gram[GRAM_H][GRAM_W] __attribute__((aligned(4))); /* also a flash source (para_back_fix): the DMA takes words */ +static Emu g_emu; +#define NSLOT 2 +static uint8_t g_pool[NSLOT * OVL_SIZE] __attribute__((aligned(4))); /* flash DMA source */ +#ifdef OVL_RAM20 +/* v0.9.1: extra slots for the guest's modified flash sectors in RAM at 0x20004000 (64 KB on the device, + * the first 16 KB stay free). With 8 slots instead of 2, eviction mid-game is almost never needed. */ +#define R20_SLOTS 6 +#define R20_POOL 0x20004000u +static void ovl_extra(Emu *e){ for(int i=0;iovl.mem[NSLOT+i]=(uint8_t*)(R20_POOL+(u32)i*OVL_SIZE); } +#endif +static int g_bl=1; /* backlight on (guest display visible) */ +extern uint8_t __jit_start[], __jit_end[], __initcode_start[], __pdata_start[]; +static u16 g_row[128]; +static StCfg g_sc; +static u32 g_restored; +static u32 g_still; /* ms without a change to the guest frame */ +__attribute__((section(".stats"), used)) static volatile u32 g_st[16]; /* measurements, located at 0x18000000 */ + +/* ---- Time: SysTick as millisecond counter ---- */ +static volatile u32 g_ms; +static u32 g_run_ms, g_hold_ms; /* see clock_sync */ + +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +typedef int32_t s32; +#define CORE_HZ 96000000u +static void systick_init(void){ SYST_RVR = CORE_HZ/1000u - 1u; SYST_CVR = 0; SYST_CSR = 7; } +#ifdef EMU_PW +/* ---- 1.6.13 test10: power saving while the guest sleeps (as T7Emu T7_PW and T18Emu T18_PW) ---- + * Screen dark and the guest asleep on its 32 kHz clock (it only counts its time): the chip runs from its internal + * 12 MHz RC with PLL and crystal off (datasheet: 1.6 mA instead of 9 to 12 mA) and goes to deep sleep (0.4 mA) once + * the emulation has caught up; the RTC (1 s, set by the Paradise) or a key wakes it, the ms tick continues from the + * RTC. The guest's sleeping time then passes in a tight loop (pw_steps), never dropped. */ +#define OSC_CTRL REG(0x45000000u) +#define OSC_STAT REG(0x45000008u) +#define SYS_CLKCFG REG(0x4500000Cu) +#define SYS_AHBCP REG(0x45000010u) +#define ISO_CTRL REG(0x45000200u) +#define PMU_CTRL REG(0x45000300u) +#define GP0(o) REG(0x40018000u + (o)) +#define NVIC_ISER0 REG(0xE000E100u) +#define NVIC_ICER0 REG(0xE000E180u) +#define NVIC_ICPR0 REG(0xE000E280u) +#define PW_KEYS 0xF00u /* P0.8 wheel, P0.9 A, P0.10 C, P0.11 B */ +#define PW_IRQS ((1u << 2) | (1u << 26)) /* RTC, GPIO0 */ +static int g_pw_low; +static u32 g_pw_rtc, g_pw_rtcms, g_pw_skip; +static volatile u8 g_pw_rtcw; /* the RTC woke the chip (its interrupt ran) */ +static u8 g_pw_kw; /* woken by a key before the next RTC second: that part of a second is not counted yet */ +__attribute__((used, noinline)) void pw_rtc_irq(void) { PMU_CTRL = (PMU_CTRL & ~0x47u) | 0x10u; g_pw_rtcw = 1; } /* RTC_FLAG: write 1 */ +__attribute__((used, noinline)) void pw_gpio_irq(void) { GP0(0x20) = PW_KEYS; } +__attribute__((noinline, minsize)) static void pw_full(void) +{ + if (!g_pw_low) return; + OSC_CTRL |= 1u << 4; /* crystal on (the PLL's source, as hw_init sets it) */ + for (u32 t = 0; !(OSC_STAT & (1u << 4)) && t < 2000000u; t++) {} + OSC_CTRL |= 1u << 15; /* PLL on */ + for (u32 t = 0; !(OSC_STAT & (1u << 6)) && t < 2000000u; t++) {} + SYS_CLKCFG = 4u; /* system clock from the PLL */ + for (u32 t = 0; ((SYS_CLKCFG >> 4) & 7u) != 4u && t < 2000000u; t++) {} + SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; + g_pw_low = 0; +} +__attribute__((noinline, minsize)) static void pw_low(void) +{ + if (g_pw_low) return; + SYS_AHBCP = 0; + SYS_CLKCFG = 0; /* system clock from the IHRC (12 MHz) */ + for (u32 t = 0; ((SYS_CLKCFG >> 4) & 7u) != 0u && t < 2000000u; t++) {} + if (((SYS_CLKCFG >> 4) & 7u) != 0u) { SYS_CLKCFG = 4u; return; } /* did not switch: stay as it was */ + OSC_CTRL &= ~((1u << 15) | (1u << 4)); /* PLL and crystal off */ + SYST_RVR = 12000000u / 1000u - 1u; SYST_CVR = 0; + g_pw_low = 1; +} +#ifdef EMU_TONE_Q +/* test20: tone queue (as T18_TONE_Q): changes with their game time, played on the real clock 150 ms after the first of + * a sequence; late by more than 200 ms the timing starts anew. A tone always at the full clock (the buzzer's timer + * counts the system clock: at 12 MHz a call began as a long low tone). */ +#ifdef EMU_TQ_DROP +#define TQ_N 64u /* test22: a call melody caught up from seconds behind fits */ +static u32 tq_drop; /* game ms dropped so far: the queue's game time stays continuous */ +#else +#define TQ_N 32u +#endif +#define TQ_LAT 250u +static u32 tq_t[TQ_N]; static u16 tq_hz[TQ_N]; static u32 tq_h, tq_w, tq_g0, tq_r0, tq_on, tq_last; +static void pw_full(void); +__attribute__((minsize)) static void tq_put(u32 hz, u32 gms) { +#ifdef EMU_TQ_DROP + gms -= tq_drop; +#endif + if (tq_w - tq_h >= TQ_N) tq_h++; tq_t[tq_w % TQ_N] = gms; tq_hz[tq_w % TQ_N] = (u16)(hz > 0xFFFFu ? 0xFFFFu : hz); tq_w++; } +__attribute__((noinline, minsize)) static void tq_pump(void) +{ + u32 now = g_ms; + while (tq_h != tq_w) { + u32 i = tq_h % TQ_N; + if (!tq_on) { tq_on = 1; tq_g0 = tq_t[i]; tq_r0 = now + TQ_LAT; } + s32 late = (s32)(now - (tq_r0 + (tq_t[i] - tq_g0))); + if (late < 0) return; + if (late > 200) { tq_g0 = tq_t[i]; tq_r0 = now; } + u32 hz = tq_hz[i]; + if (hz) { pw_full(); +#ifdef CLK_ECO + if (g_hw_clk_sh) hw_clk_shift(0, CORE_HZ); /* the lower eco clock would lower the tone as well */ +#endif + } + hw_tone(hz); tq_h++; tq_last = now; + } + if (!g_hw_tone_hz && now - tq_last > 1000u) tq_on = 0; /* quiet for a second: the next note starts a new sequence */ +} +#endif +/* deep sleep until the next RTC second or a key; returns the seconds that passed */ +__attribute__((noinline, minsize)) static u32 pw_sleep(void) +{ + u32 iso = ISO_CTRL; + if (!(iso & 0x80u) || (iso & 7u) != 0u) { __asm__ volatile("wfi"); return 0; } /* the RTC is not on 1 s: no deep sleep */ + ISO_CTRL = iso & ~8u; /* RTC_WKP 0: the RTC interrupt wakes */ + GP0(0x0C) &= ~PW_KEYS; GP0(0x10) |= PW_KEYS; GP0(0x20) = PW_KEYS; GP0(0x18) |= PW_KEYS; /* edges, both */ + NVIC_ICPR0 = PW_IRQS; NVIC_ISER0 = PW_IRQS; + u32 r0 = REG(0x45000304u), csr = SYST_CSR; + SYST_CSR = 0; + g_pw_rtcw = 0; + PMU_CTRL = (PMU_CTRL & ~0x47u) | 2u; /* DSLEEP_EN */ + __asm__ volatile("dsb\n wfi\n isb" ::: "memory"); + PMU_CTRL = PMU_CTRL & ~0x47u; + NVIC_ICER0 = PW_IRQS; GP0(0x18) &= ~PW_KEYS; GP0(0x20) = PW_KEYS; + ISO_CTRL = (ISO_CTRL & ~8u) | (iso & 8u); + SYST_CVR = 0; SYST_CSR = csr; + /* woken by the RTC: wait until the counter (32 kHz domain) shows the new second (as T18Emu test3) */ + u32 r = REG(0x45000304u); + if (g_pw_rtcw) for (u32 t = 0; r == r0 && t < 200000u; t++) r = REG(0x45000304u); + u32 n = r - r0; + if (!n) g_pw_kw = 1; + return n > 3600u ? 0u : n; +} +#endif + +/* XIP window: 1 MB cached from 0x10000000, base freely selectable. */ +#define XIP_BASE_REG REG(0x4002F004u) +#define XIP_CTRL_REG REG(0x4002F000u) +#define MPU_TYPE REG(0xE000ED90u) +#define MPU_CTRL REG(0xE000ED94u) +#define MPU_RNR REG(0xE000ED98u) +#define MPU_RBAR REG(0xE000ED9Cu) +#define MPU_RASR REG(0xE000EDA0u) +#define SHCSR REG(0xE000ED24u) + +/* Check PRAM against the app image in flash (uncached window, confirmed on + * the device) and replace any differences. On the device, v0.8.3 hit an + * "undefined instruction" fault at a valid address (0x41A6): suspected that + * PRAM did not match the image. */ +#define APP_FLASH 0x600A0000u +static volatile u32 g_zero; +static u32 g_pc_n, g_pc_first, g_pc_last, g_pc_rt; +#ifdef APP_SELF +/* test5: where this program's image lies in the flash. A further TamaEmu of the menu has its image right behind its + * guest area (spare_end), not at 0x0A0000; checking against 0x0A0000 copied the main TamaEmu's settings over its own + * and the other ROM started (Bernd: iD L and P's, always the one added first). */ +static u32 app_flash(void){ + if(g_cfg.version>=3u){ u32 a=g_cfg.spare_end; + if(a && a<0x1000000u && !(a & 0xFFFFu) && a!=0xA0000u){ + volatile const u32 *c=(volatile const u32*)(0x60000000u + a + 0x140u); + if(c[0]==0x43584D50u && c[2]==g_cfg.guest_off && c[4]==g_cfg.save_off) return 0x60000000u + a; } } + return APP_FLASH; +} +#else +#define app_flash() APP_FLASH +#endif +static u32 pram_check(u32 end, int fix){ + volatile u32 *dst=(volatile u32*)g_zero; + volatile const u32 *src=(volatile const u32*)app_flash(); + if(src[0]!=dst[0] || src[1]!=dst[1]) return 0xFFFFFFFFu; /* window does not read the image */ + u32 n=0; + for(u32 i=0;i=0x140u/4u && i<(0x140u+sizeof(PmxCfg))/4u) continue; /* its own settings stay, whatever the image there says */ +#endif + if(dst[i]!=v){ if(!g_pc_n && !n) g_pc_first=i*4u; g_pc_last=i*4u; n++; if(fix) dst[i]=v; } + } + if(n && fix){ __asm__ volatile("dsb\n isb" ::: "memory"); } + return n; +} +#ifdef EMU_OVL +extern uint8_t __ovl_start[], __ovl_end[]; +void jit_pram_load(uint32_t dst, const void *src, uint32_t n); +/* the overlay back from this program's image in the flash (the translator wrote its code over it); the translator + * then starts over */ +__attribute__((noinline, minsize)) static void ovl_load(void){ jit_pram_load((u32)__ovl_start, (const void *)(app_flash() + (u32)__ovl_start), (u32)(__ovl_end - __ovl_start)); g_emu.jit_flush = 1; } +#endif +/* Startup display: until the guest has sent a frame, two rows of numbers (hex) + * are shown at the bottom. Shows on the device how far startup gets. */ +#if !defined(CLEAN) || defined(MESS) +static const u16 g_font[16]={0x7B6F,0x2C97,0x73E7,0x73CF,0x5BC9,0x79CF,0x79EF,0x7249,0x7BEF,0x7BCF,0x7BED,0x6BAE,0x7927,0x6B6E,0x79E7,0x79E4}; +static void diag_line(u32 y0, const u32 *v, const u8 *n, int cnt){ + for(u32 y=0;y<10;y++){ + for(u32 x=0;x<128;x++) g_row[x]=0x0010u; + u32 cx=2; + for(int k=0;k=0; d--){ + u32 h=(v[k]>>(4*d))&15u, bits=g_font[h], ry=y/2; + for(u32 c=0;c<3;c++) if(ry<5 && ((bits>>(14-(ry*3+c)))&1u)){ g_row[cx+2*c]=0xFFFFu; g_row[cx+2*c+1]=0xFFFFu; } + cx+=8; + } + cx+=6; + } + hw_push(g_row, 0, 0, y0+y, 128, y0+y+1); + } +} +#endif +#ifndef CLEAN +static volatile u32 g_stage, g_guest_drawn, g_loops; +static void diag(Emu *e, u32 emu_ms){ + if(g_guest_drawn) return; + u32 a[3]={g_stage, g_ms, emu_ms}; static const u8 na[3]={1,5,5}; + u32 b[3]={e->pc, (u32)(e->cycles>>20), g_loops}; static const u8 nb[3]={7,4,3}; + diag_line(104, a, na, 3); diag_line(116, b, nb, 3); + { u32 c[4]={g_pc_n, g_pc_first, g_pc_last, g_pc_rt}; static const u8 nc[4]={3,4,4,3}; diag_line(32, c, nc, 4); } +} +/* Fault screen: on a CPU fault (F) or when the main loop stalls for 3 s (E), + * four rows: kind and pc of the location, lr, CFSR and HFSR, BFAR and guest pc. */ +static u32 g_loops_seen, g_loops_ms; +static u32 g_r9; +static volatile u32 g_probe, g_probe_hit; /* memory probe with caught bus fault */ +static void fault_show(u32 kind, const u32 *fr){ + { u32 q[3]={9, g_r9, g_r9==g_emu.jit_a0}; static const u8 nq[3]={1,8,1}; diag_line(32, q, nq, 3); } + u32 a[2]={kind, fr[6]}; static const u8 na[2]={1,8}; + u32 b[1]={fr[5]}; static const u8 nb[1]={8}; + u32 c[2]={REG(0xE000ED28u), REG(0xE000ED2Cu)}; static const u8 nc[2]={8,4}; + u32 d[2]={ (REG(0xE000ED28u) & 0x80u) ? REG(0xE000ED34u) : REG(0xE000ED38u), g_emu.pc}; static const u8 nd[2]={8,7}; + diag_line(68, a, na, 2); diag_line(80, b, nb, 1); diag_line(92, c, nc, 2); diag_line(104, d, nd, 2); + { u32 pc=fr[6] & ~3u; u32 x[2]={0,0}; static const u8 nx[2]={8,8}; + if(pc < 0x10000u){ x[0]=*(volatile const u32*)(g_zero+pc); x[1]=*(volatile const u32*)(APP_FLASH+pc); } + diag_line(20, x, nx, 2); + /* y=8 stays free for the 5 row (memory test) */ } +} +/* The JIT entry guard has triggered (display since v0.8.10): + * y=68 A , y=80 , + * y=92 last three codes, y=104 guest pc now and at entry, + * y=20/32/44/56: r4 r5 / r6 r7 / r8 r9 / r10 r11 AFTER the block (lower 6 digits), + * y=116: r10 r11 BEFORE (y=8 stays the write test row). + */ +static void leave(void); +static void jit_bad(Emu *e){ + g_stage=8; /* E screen off, otherwise it covers this display */ + volatile u32 *d=jit_dbg; u32 k=(d[5]-1u)&7u, mask=0; + for(u32 i=0;i<8;i++) if(d[28+i]!=d[36+i]) mask |= 1u<pc, d[8+2*k]}; static const u8 nf[2]={7,7}; + static const u8 n6[2]={6,6}; + u32 r45[2]={d[36]&0xFFFFFFu, d[37]&0xFFFFFFu}, r67[2]={d[38]&0xFFFFFFu, d[39]&0xFFFFFFu}; + u32 r89[2]={d[40]&0xFFFFFFu, d[41]&0xFFFFFFu}, rab[2]={d[42]&0xFFFFFFu, d[43]&0xFFFFFFu}; + diag_line(68, a, na, 4); diag_line(80, b, nb, 3); diag_line(92, c, nc, 3); diag_line(104, f, nf, 2); + diag_line(20, r45, n6, 2); diag_line(32, r67, n6, 2); diag_line(44, r89, n6, 2); diag_line(56, rab, n6, 2); + { u32 v2[2]={d[34]&0xFFFFFFu, d[35]&0xFFFFFFu}; + diag_line(116, v2, n6, 2); } /* before: r10 r11; y=8 stays the write test */ + for(;;){ hw_wdt_feed(); if(hw_buttons()&BTN_WHEEL) leave(); } +} +__attribute__((used)) void fault_c(u32 *fr, u32 r9){ + if(g_probe){ g_probe_hit=1; g_probe=0; fr[6]+=2u; REG(0xE000ED28u)=REG(0xE000ED28u); REG(0xE000ED2Cu)=REG(0xE000ED2Cu); return; } + g_r9=r9; + fault_show(0xF, fr); + for(u32 t=0;;t++){ hw_wdt_feed(); if(hw_buttons()&BTN_WHEEL){ if(t>2000000u) leave(); } else t=0; } +} +#else +/* Release build (v0.9.0): no diagnostics. On a CPU fault, sound off and wait; + * a long press on the wheel returns to the Paradise (without saving, the state is unreliable). */ +static volatile u32 g_stage, g_guest_drawn; +#define diag(e,m) ((void)0) +static void leave(void); +static void leave_nosave(void); +__attribute__((used)) void fault_c(u32 *fr, u32 r9){ + (void)fr; (void)r9; hw_tone(0); + for(u32 t=0;;t++){ hw_wdt_feed(); if(hw_buttons()&BTN_WHEEL){ if(t>2000000u) leave_nosave(); } else t=0; } +} +#endif +#ifdef PROF +/* v0.8.21: one sample per ms: where was the CPU (pc) at the interrupt? 256-byte buckets in PRAM. */ +static u16 g_prof[256]; static u32 g_prof_other; +#endif +__attribute__((used)) void systick_c(u32 *fr, u32 r9){ + g_ms++; +#if defined(PROF) && defined(MESS) && defined(CLEAN) + { u32 pc=fr[6]; if(pc<0x10000u){ if(g_prof[pc>>8]<0xFFFFu) g_prof[pc>>8]++; } else g_prof_other++; } +#endif +#ifndef CLEAN +#ifdef PROF + if(g_stage==7){ u32 pc=fr[6]; if(pc<0x10000u){ if(g_prof[pc>>8]<0xFFFFu) g_prof[pc>>8]++; } else g_prof_other++; } +#endif + if(g_stage==7 && !g_guest_drawn){ + if(g_loops!=g_loops_seen){ g_loops_seen=g_loops; g_loops_ms=g_ms; } + else if(g_ms-g_loops_ms>3000u && (g_ms & 511u)==0){ g_r9=r9; fault_show(0xE, fr); } + } +#else + (void)fr; (void)r9; +#endif +} +__attribute__((naked)) void SysTick_Handler(void){ __asm__ volatile("mrs r0, msp\n mov r1, r9\n b systick_c\n"); } +__attribute__((naked)) static void Fault_Handler(void){ __asm__ volatile("mrs r0, msp\n mov r1, r9\n b fault_c\n"); } +#ifdef LCD_ROWS +extern uint8_t lcd_rall; +#define LCD_ALL() (lcd_rall=1) +#else +#define LCD_ALL() ((void)0) +#endif +static void push_dirty(Emu *e){ + Lcd *l=&e->lcd; + if(l->dx1 < l->dx0 || l->dy1 < l->dy0){ g_still+=40; return; } + g_still=0; + int x0=l->dx0, y0=l->dy0, x1=l->dx1+1, y1=l->dy1+1; + if(x1>128) x1=128; if(y1>128) y1=128; + l->dx0=1000; l->dy0=1000; l->dx1=-1; l->dy1=-1; + if(x0>=x1 || y0>=y1) return; + g_guest_drawn=1; + int on = l->sleep_out && l->disp_on; + int bgr = l->madctl & 0x08, inv = l->inverted; +#ifdef LCD_ROWS + /* v0.8.19: if the changes are scattered (two characters in different corners), send only the changed + * pieces of each row instead of the whole bounding rectangle. Cost roughly estimated in bytes. */ + { extern uint8_t lcd_rx0[], lcd_rx1[], lcd_rall; + int rows=0; + if(!lcd_rall){ + u32 cr=(u32)(x1-x0)*(u32)(y1-y0)*2u + 30u, cs=0; + for(int y=y0;ylcd_rx1[y]) continue; + int a=lcd_rx0[y], b=lcd_rx1[y]+1; if(b>128) b=128; + for(int x=a;xgram[y][x] : 0; + if(on && inv) p=(u16)~p; + if(bgr) p=(u16)(((p&0x1F)<<11)|(p&0x07E0)|(p>>11)); + g_row[x]=p; + } + hw_px_begin((u32)a,(u32)y,(u32)b,(u32)y+1u); hw_px_row(g_row + a, (u32)(b-a)); hw_px_end(); + } + } + if(lcd_rall){ for(int y=0;y<128;y++){ lcd_rx0[y]=255; lcd_rx1[y]=0; } lcd_rall=0; } + else for(int y=y0;ygram[y][x] : 0; + if(on && inv) p=(u16)~p; + if(bgr) p=(u16)(((p&0x1F)<<11)|(p&0x07E0)|(p>>11)); + g_row[x]=p; + } +#ifdef FAST_LCD + hw_px_row(g_row + x0, (u32)(x1-x0)); +#else + hw_push(g_row - 0 , 0, x0, y, x1, y+1); /* stride 0: one row */ +#endif + } +#ifdef FAST_LCD + hw_px_end(); +#endif +} + +#ifdef BAT_GUARD +/* test21: battery empty: everything saved (guest flash, run state), then off until new batteries (BAT_GUARD) */ +OVL_FN static void bat_end(void){ + st_save(&g_emu, &g_sc, g_gram); + BAT_PIC_SHOW(); + hw_backlight(0); + for(;;){ hw_wdt_feed(); __asm__ volatile("wfi"); } +} +#endif +__attribute__((minsize)) static void leave_go(int save){ +#ifdef EMU_PW + pw_full(); +#endif +#ifdef CLK_ECO + hw_clk_shift(0, CORE_HZ); +#endif + hw_tone(0); +#ifdef EMU_OVL + ovl_load(); +#endif + REG(0x20000FF8u)=0; /* start counter of the home hooks */ + REG(0x20000FFCu)=0x4C584D50u; /* "PMXL": back on purpose, the autostart of the stub stays off (v0.9.4) */ + if(save) +#ifdef DBGLEAVE + g_st[15]=0x1EA0; +#endif + st_save(&g_emu, &g_sc, g_gram); +#ifdef DBGLEAVE + g_st[15]=0x1EA1; + for(;;) hw_wdt_feed(); +#endif +#ifdef PARA_BACK + para_back_fix((uint8_t *)g_gram); /* 1.6.8: the Paradise skips the time spent here */ +#endif + /* Only restart once the wheel is released: otherwise the Paradise sees a + * pressed button while booting. Screen off as a sign that the save is done. */ +#ifdef BL_SLEEP + hw_bl_pwm_off(); /* do not put the display to sleep: the firmware restarts right away */ +#else + hw_backlight(0); +#endif + for(u32 t=0; hw_buttons() && t<20000000u; t++) if((t & 0xFFFFu)==0) hw_wdt_feed(); + MPU_CTRL = 0u; __asm__ volatile("dsb\n isb" ::: "memory"); /* start the firmware without protection */ + XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u; + hw_back_to_paradise(); +} +/* v0.9.2: if guest writes were lost, the guest may be stuck: do not keep that state */ +static void leave(void){ leave_go(g_emu.flash_lost_writes==0u); } +static void leave_nosave(void){ leave_go(0); } + +/* ROM blocks: packed from guest_off, the first 16 are in the cached window */ +TC_INIT static void setup_rom(Emu *e){ + for(u32 i=0;i<128;i++){ + u32 k=g_cfg.map[i]; + if(k==0xFE) k=i; /* old layout: linear */ + if(k==0xFF || (i<<16)>=e->dev.rom_size){ e->rom_src[i]=0; e->rom_blk[i]=0; continue; } + e->rom_src[i]=(const uint8_t*)(0x60000000u + g_cfg.guest_off + (k<<16)); +#ifdef ROM_CACHED + e->rom_blk[i]= k<16 ? (const uint8_t*)(0x10000000u + (k<<16)) : e->rom_src[i]; +#else + /* On the device: after changing the base, the cached window sometimes returns + * stale lines (suspected, v0.8.4). So everything goes through the uncached window. */ + e->rom_blk[i]= e->rom_src[i]; +#endif + } + e->rom_blk[e->par_base>>16]=0; +} + +/* Self test on the device: does the CPU see code that was newly written to PRAM? + * The translator (JIT) keeps writing code to PRAM and executing it. If instruction + * fetch returns stale contents (cache), the guest runs into nowhere. + * Result (row y=68): C a b c d e (expected 11 22 33 44 55). + * a: first call, b: after overwriting, c/d/e: after overwriting and + * a nop sled of 1/4/8 KB (evicts a cache). */ +static u32 g_ct_ok; +#ifndef CLEAN +#define CT_X 0xFF00u +static u32 ct_call(u32 v){ + volatile u16 *x=(volatile u16*)(g_zero+CT_X); + x[0]=(u16)(0x2000u | (v & 0xFFu)); x[1]=0x4770u; /* movs r0,#v ; bx lr */ + __asm__ volatile("dsb\n isb" ::: "memory"); + return 0; +} +static u32 ct_run(void){ u32 (*f)(void)=(u32(*)(void))(g_zero+CT_X+1u); return f(); } +static void ct_sled(u32 n){ + u32 base=((u32)__jit_start + 0xFFu) & ~0xFFu; /* free space, never executed before */ + if(base + n > CT_X) n = CT_X - base; + volatile u16 *s=(volatile u16*)(g_zero+base); + for(u32 i=0;i <1 = protection on>. */ +static void mpu_guard(void){ + u32 t=MPU_TYPE, on=0; + u32 end=(u32)__pdata_start & ~0xFFFu; /* up to the data, rounded to 4 KB */ +#ifndef NOMPU + if(((t>>8)&0xFFu) >= 2u && end >= 0x8000u && end <= 0x10000u){ + const u32 ro=(6u<<24) | (1u<<17); /* read only, normal memory */ + MPU_RNR=0; MPU_RBAR=0x00000000u; MPU_RASR=ro | (14u<<1) | 1u; /* 0..0x8000 */ + u32 n=(end-0x8000u)/0x1000u; /* active 4 KB parts from 0x8000 */ + MPU_RNR=1; MPU_RBAR=0x00008000u; MPU_RASR=ro | (((0xFFu< <1 if 0x20000000.. has changed>. */ +#ifndef CLEAN +__attribute__((noinline)) static u32 sram_watch(u32 *first, u32 *c2){ + u32 sp; __asm__ volatile("mov %0, sp" : "=r"(sp)); + volatile u32 *p=(volatile u32*)0x18000000u; u32 n=(sp-0x200u-0x18000000u)/4u; + /* only read and compare 0x20000000 (contents belong to the stub/firmware) */ + volatile u32 *q=(volatile u32*)0x20000000u; const u32 m=0x400u/4u; u32 snap=0; + for(u32 i=0;idev.ttbr_reset); for(u32 i=0;idstram+(a & 0x7FFFu) : e->a0ram+a; } +#endif +static u32 g_ovl; /* speed display on (short wheel press) */ +/* Timing (v0.8.20): cycles from SysTick (g_ms * 96000 + elapsed part of the current ms). + * MESS: release build plus only the speed display (short wheel press), for measuring on the device. */ +#if !defined(CLEAN) || defined(MESS) +static u32 g_cy_emu, g_cy_disp; +static u32 cyc_now(void){ u32 m, v; do { m=g_ms; v=SYST_CVR; } while(m!=g_ms); return m*96000u + (95999u - v); } +#endif +extern uint32_t jit_st_flush, jit_st_blocks; +extern u32 st_n_evict; +static u32 g_n_gflash; /* counter: guest save written to flash */ +static u32 g_btn_ms; /* last key (GFLUSH_IDLE) */ +#ifdef HW_OPTS +static u32 g_scr_ms; static int g_scr_dark; /* 1.6.8: screen off after (Studio), off now */ +static const u16 OPT_SM[8]={0,10,20,30,60,120,300,600}; /* screen off after, seconds */ +#ifdef EMU_DIM +/* 1.6.13 test10: dimming as in T7Emu and T18Emu (bits 12-14 dim after, 8-11 dim to, set on the device): the light goes + * down to the chosen percent after that time without a key; the first key then only brings the light back */ +static u32 g_dim_ms, g_dim_t; static int g_dimd; +#endif +__attribute__((minsize)) static void opt_apply(u32 f){ g_hw_vol=(0x0312u>>(((f>>16)&3u)*4u))&15u; g_hw_dim=(f>>18)&3u; g_scr_ms=OPT_SM[(f>>20)&7u]*1000u; +#ifdef EMU_DIM + g_dim_ms=OPT_SM[(f>>12)&7u]*1000u; g_dimd=0; +#endif +#ifdef BL_PWM + hw_bl_set(opt_light_pct(f)); /* 1.6.8: the light, not the colours */ +#endif +} +#ifdef OPT_MENU +/* 1.6.8: settings changed on the device (wheel short), in the last sector of the save area: magic, the Studio's + * bits when they were changed, the bits, check. The Studio's bits win again once they are changed there. */ +#define OPT_SEC (g_cfg.save_off+0x4F000u) +#define OPT_MAGIC 0x4F584D50u /* "PMXO" */ +static u32 g_opt, g_optsec[4]; +static u32 opt_studio(void){ return (g_cfg.version>=4u ? g_cfg.flags : 0u) & 0xF7F0000u; } +#ifdef EMU_DIM +/* the device-only bits (dim 8-14, language 0-1) stay when the Studio's bits were changed */ +static void opt_load(void){ u32 *s=g_optsec; flash_read(OPT_SEC, s, 16); + int ok = s[0]==OPT_MAGIC && s[3]==(s[0]^s[1]^s[2]) && !(s[2]&~0xF7F7F03u); + g_opt = ok && s[1]==opt_studio() ? s[2] : opt_studio() | (ok ? s[2] & 0x7F03u : 0u); } +#else +static void opt_load(void){ u32 *s=g_optsec; flash_read(OPT_SEC, s, 16); + g_opt = (s[0]==OPT_MAGIC && s[1]==opt_studio() && s[3]==(s[0]^s[1]^s[2]) && !(s[2]&~0xF7F0000u)) ? s[2] : opt_studio(); } +#endif +#ifdef ASK_LANG +/* test10: the language of the settings, set on the device (bits 0-1: 0 as the Studio, 1 German, 2 English) */ +#define EMU_EN() ((g_opt & 3u) ? (g_opt & 3u) == 2u : (g_cfg.flags & 1u) != 0u) +#endif +OVL_FN static void opt_store(void){ u32 *s=g_optsec; s[0]=OPT_MAGIC; s[1]=opt_studio(); s[2]=g_opt; s[3]=s[0]^s[1]^s[2]; + hw_tone(0); flash_prog4k(OPT_SEC, s); } /* the DMA takes 4 KB from here: only the first 16 bytes count */ +#endif +#endif +/* Measure the size of the RAM at 0x20000000 (v0.8.15): read and write from 0x20001000 in 2 KB steps. + * A bus fault on read is caught in the fault handler (g_probe); that marks the end. + * Result in KB (0x20000000 up to the first missing step), at most 64. */ +#ifndef CLEAN +static u32 g_ram20; +__attribute__((noinline)) static u32 probe_rd(u32 a){ u32 v; __asm__ volatile("ldr %0, [%1]\n nop" : "=l"(v) : "l"(a) : "memory"); return v; } +static void ram20_size(void){ + u32 kb=4; + for(u32 a=0x20001000u; a<0x20010000u; a+=0x800u){ + g_probe_hit=0; g_probe=1; u32 old=probe_rd(a); g_probe=0; + if(g_probe_hit) break; + volatile u32 *p=(volatile u32*)a; *p=0xC3A55A3Cu ^ a; __asm__ volatile("dsb" ::: "memory"); + u32 ok = *p==(0xC3A55A3Cu ^ a); *p=old; + if(!ok) break; + kb += 2; + } + g_ram20=kb; +} +#ifdef PROBE +/* Memory probe (v0.8.13, build with -DPROBE): answers three questions on the device without JIT. + * y=20 1 Mirroring: write a marker to PRAM at 0xE000/0xFF80, search the whole SRAM + * (0x18000000..0x1801FFFF) and 0x20000000..0x20000FFF; a hit only counts if the location + * also shows the changed marker. Address (lower 5 digits, 8xxxx = 0x20000xxx; 0 = nowhere). + * y=32 2 Reverse: marker in SRAM at 0x1801E000/0x1801FC00, searched in PRAM 0xD000..0xFFFF. + * y=44 4 Is code in SRAM (0x1801E800) or at 0x20000E00 executable? 66 = yes (return value). + * Then it halts; holding the wheel for 2 s returns. */ +static u32 probe_exec(u32 at){ + volatile u16 *x=(volatile u16*)at; x[0]=0x2066u; x[1]=0x4770u; /* movs r0,#0x66 ; bx lr */ + __asm__ volatile("dsb\n isb" ::: "memory"); + u32 (*f)(void)=(u32(*)(void))(at|1u); return f(); +} +static void probe_all(void){ + static const u8 n5[4]={1,5,5,5}; + u32 sp; __asm__ volatile("mov %0, sp" : "=r"(sp)); + { static const u32 pa[2]={0xE000u,0xFF80u}; u32 r[3]={1,0,0}; static const u8 n3[3]={1,5,5}; + for(u32 k=0;k<2;k++){ volatile u32 *pp=(volatile u32*)(g_zero+pa[k]); u32 mk=0x6D4B5A5Au ^ (k*0x1111u); + *pp=mk; __asm__ volatile("dsb" ::: "memory"); + for(u32 a=0x18000000u; a<0x18020000u && !r[k+1]; a+=4) if(*(volatile u32*)a==mk){ + *pp=~mk; __asm__ volatile("dsb" ::: "memory"); + if(*(volatile u32*)a==~mk) r[k+1]=a&0xFFFFFu; else *pp=mk; } + if(!r[k+1]) for(u32 a=0x20000000u; a<0x20001000u && !r[k+1]; a+=4) if(*(volatile u32*)a==*pp){ + u32 o=*pp; *pp=~o; __asm__ volatile("dsb" ::: "memory"); + if(*(volatile u32*)a==~o) r[k+1]=0x80000u|(a&0xFFFu); else *pp=o; } } + diag_line(20, r, n3, 3); } + { static const u32 sa[2]={0x1801E000u,0x1801FC00u}; u32 r[3]={2,0,0}; static const u8 n3[3]={1,5,5}; + for(u32 k=0;k<2;k++){ if(sa[k] >= sp-0x40u) { r[k+1]=0xFFFFFu; continue; } + volatile u32 *sp_=(volatile u32*)sa[k]; u32 mk=0x3C7EA5A5u ^ (k*0x2222u); *sp_=mk; __asm__ volatile("dsb" ::: "memory"); + for(u32 a=0xD000u; a<0x10000u && !r[k+1]; a+=4) if(*(volatile u32*)(g_zero+a)==mk){ + *sp_=~mk; __asm__ volatile("dsb" ::: "memory"); + if(*(volatile u32*)(g_zero+a)==~mk) r[k+1]=a; else *sp_=mk; } } + diag_line(32, r, n3, 3); } + { u32 r[3]={4, 0xEE, 0xEE}; static const u8 n2[3]={1,2,2}; + diag_line(44, r, n2, 3); /* EE = not run yet (if the call hangs, EE stays) */ + r[1]=probe_exec(0x1801E800u); diag_line(44, r, n2, 3); + r[2]=probe_exec(0x20000E00u); diag_line(44, r, n2, 3); } + for(u32 t=0;;t++){ hw_wdt_feed(); if(hw_buttons()&BTN_WHEEL){ if(t>2000000u) leave(); } else t=0; } +} +#endif +/* PRAM write test (v0.8.12): word pattern in 64 bytes at 0xFF40, then write one byte (offset 0..3) or one + * halfword (0, 2) into word 8 and read everything back. Per test: number of wrong bytes OUTSIDE + * the target, plus 0x80 if the target itself is wrong. Display y=8: W b0 b1 b2 b3 h0 h2 (00 = correct). */ +static void pram_wtest(void){ + volatile u32 *w=(volatile u32*)(g_zero+0xFF40u); volatile u8 *b=(volatile u8*)w; volatile u16 *h=(volatile u16*)w; + u32 r[6]; u8 exp[64]; + for(u32 t=0;t<6;t++){ + for(u32 i=0;i<16;i++){ u32 v=0x11223344u ^ (i*0x01010101u) ^ (t<<28); w[i]=v; + exp[4*i]=(u8)v; exp[4*i+1]=(u8)(v>>8); exp[4*i+2]=(u8)(v>>16); exp[4*i+3]=(u8)(v>>24); } + __asm__ volatile("dsb" ::: "memory"); + u32 lo, n; + if(t<4){ lo=32u+t; n=1; b[lo]=0xA5u; exp[lo]=0xA5u; } + else { lo=32u+(t-4u)*2u; n=2; h[lo/2u]=0xA55Au; exp[lo]=0x5Au; exp[lo+1]=0xA5u; } + __asm__ volatile("dsb" ::: "memory"); + u32 bad=0, tbad=0; + for(u32 i=0;i<16;i++){ u32 v=w[i]; + for(u32 k=0;k<4;k++){ u32 j=4*i+k; if((u8)(v>>(8*k))!=exp[j]){ if(j>=lo && j0x7Fu?0x7Fu:bad) | (tbad?0x80u:0u); + } + u32 v[7]={0x3 /* no W in the font: 3 as in third probe */, r[0],r[1],r[2],r[3],r[4],r[5]}; static const u8 nv[7]={1,2,2,2,2,2,2}; + diag_line(8, v, nv, 7); +} +#endif + +extern u32 __bss_start, __bss_end, __ram_end; +/* v0.9.3: keep the guest clock on the Paradise's own seconds counter. g_run_ms: ms the guest ran, plus the + * dropped ones already added in the main loop (1.6.8). Called every 1024 ms. */ +#ifdef EMU_DATE_FIX +/* test20: the games keep the date in their own RAM (iD L: year, month, day, hour, minute at dstram 0x27E) and take only + * the time from the clock chip: with the clock from the Paradise the time was right, the date stayed the game's own + * (1/2 instead of 10/26). The clock record is found by the time the game copied in (hour and minute as on the chip, + * a month and a day before them); found exactly once, its month and day are set. */ +static u32 g_date_n; +__attribute__((noinline, minsize)) static int date_fix(Emu *e){ + const u8 *io = e->ioram - e->dev.io_base; + #define BCD(x) (((x) >> 4) * 10u + ((x) & 15u)) + u32 h = BCD(io[0x301918]), mi = BCD(io[0x301914]), d = BCD(io[0x30191C]), mo = BCD(io[0x301920]); + u8 *b = e->dstram; u32 n = 0, at = 0; + for (u32 i = 2; i + 1 < e->dev.dstram_size; i++) + if (b[i] == h && b[i + 1] == mi && b[i - 1] >= 1u && b[i - 1] <= 31u && b[i - 2] >= 1u && b[i - 2] <= 12u) { n++; at = i; } + if (n != 1) return 0; + b[at - 2] = (u8)mo; b[at - 1] = (u8)d; + return 1; +} +#endif +#ifdef CLK_DISC +/* 1.7.2 test16: the guest clock follows the Paradise's seconds counter 0x45000304 (crystal, runs always), as T7Emu + * does: about every 10 s, when the emulation is not behind on purpose. With the clock from the Paradise the guest + * should show the Paradise's time, else its own time from the first check on. Behind: the missing seconds are + * added (the guest lives them), ahead: the clock goes back. A jump of the guest clock (set in the game, or the + * Paradise's time put back after it) is a new reference. Before (clock_sync) a long standby could leave the guest + * clock far behind: gaps the counter made in one go were taken as implausible and dropped. */ +static u32 g_cd[4]; /* reference: guest time, counter; last check: guest time, counter (0 = none) */ +__attribute__((noinline, minsize)) static void clock_disc(Emu *e, s32 behind){ + u32 r = REG(0x45000304u); + if(g_cd[0] && r - g_cd[3] < 10u) return; + if(behind > 300 || (REG(0x45000200u) & 7u)) return; + u32 obs = periph_rtc_get(e); + if(!obs){ g_cd[0] = 0; return; } + if(!g_cd[0]){ + if(para_hard()){ g_cd[0] = g_para; g_cd[1] = g_para_cnt; } else { g_cd[0] = obs; g_cd[1] = r; } + g_cd[2] = obs; g_cd[3] = r; + } + s32 el = (s32)(r - g_cd[3]), mv = (s32)(obs - g_cd[2]); + if(mv < -5 || mv > el + 5){ g_cd[0] = obs; g_cd[1] = r; g_cd[2] = obs; g_cd[3] = r; return; } + s32 d = (s32)(g_cd[0] + (r - g_cd[1]) - obs); + if(d >= 2){ periph_rtc_advance(e, (u32)d); obs += (u32)d; } + else if(d <= -2){ obs += (u32)d; periph_rtc_set(e, obs); } + g_cd[2] = periph_rtc_get(e) ? periph_rtc_get(e) : obs; g_cd[3] = r; +} +#endif +__attribute__((noinline, minsize)) static void clock_sync(Emu *e){ + u32 run_ms = g_run_ms; +#ifdef BAT_GUARD + if (bat_guard_tick()) g_bat_go = 1; +#endif +#ifdef EMU_DATE_FIX + if (g_date_n < 150u && para_hard() && g_cfg.device == 1u) { /* iD L only (checked there) */ g_date_n++; if (date_fix(e)) g_date_n = 150u; } +#endif + static u32 r0, m0, have; static s32 owe; + u32 r = REG(0x45000304u); +#ifndef CLOCK_DOUBLE + if(REG(0x45000200u) & 7u) have=0; /* 1.6.8 (Sonix SDK): 0x45000304 counts RTC periods, seconds only with timeout 0 (1 s) */ + else +#endif +#ifdef CLK_DISC + (void)run_ms; /* 1.7.2 test16: clock_disc keeps the guest clock */ + if(1){} +#else + if(!have){ r0=r; m0=run_ms; have=1; } +#endif + else if(r - r0 >= 30u){ + u32 dr = r - r0, dm = run_ms - m0; + if(dr <= dm/1000u + 600u && dm/1000u <= dr + 5u){ /* plausible: no jump of the counter */ + owe += (s32)(dr*1000u) - (s32)dm; + if(owe >= 1000){ u32 n=(u32)owe/1000u; periph_rtc_advance(e, n); owe -= (s32)(n*1000u); } +#ifndef CLOCK_DOUBLE + /* 1.6.8: tick fast (the core clock comes from the internal RC, up to 2 %): the guest clock ran ahead. + * Hold the guest back for the extra time, 1 ms in 16, instead of letting it run fast for good. */ + if(owe <= -1000){ u32 n=(u32)(-owe)/1000u; g_hold_ms += n*1000u; owe += (s32)(n*1000u); } + if(g_hold_ms > 60000u) g_hold_ms = 60000u; +#else + if(owe < -2000) owe = -2000; /* tick fast: nothing to take back */ +#endif + } + r0=r; m0=run_ms; + } +} +#ifdef EMU_PW +static u32 g_cy_rest; /* rest of the guest cycles per ms (see the main loop) */ +/* one ms of the sleeping guest, as in the main loop: its cycles, its clock */ +__attribute__((noinline)) static void pw_step(Emu *e){ + u32 mhz = e->cmu.mclk_hz ? e->cmu.mclk_hz : e->dev.osc3_hz; + u32 t = mhz + g_cy_rest, cy_ms = t / 1000u; g_cy_rest = t % 1000u; + tc_run(e, e->cycles + cy_ms); +#ifdef RTC_MS + if(g_hold_ms && ((g_run_ms + 1u) & 15u)==0u) g_hold_ms--; else periph_rtc_ms(e); +#endif + if(((++g_run_ms) & 1023u)==0u) clock_sync(e); +} +#endif +/* 1.6.9: everything up to the translator runs once, from the startup area (.initcode, later the translator's): + * frees PRAM for the infrared link */ +#ifdef EMU_OVL +__attribute__((section(".initcode"), noinline, minsize)) +#else +__attribute__((section(".initcode"), noinline)) +#endif +static void boot(void){ + u32 swf=0, swk=0, swn=0; + /* the Paradise's clock, before its SRAM is overwritten (the stack is in the top 4 KB) */ + u32 pcnt=REG(0x45000304u), para=para_clock(pcnt, 0, 0x1F000u, 0, 0); + if(!para) para=para_mailbox(pcnt); /* 1.6.8: started from the menu */ +#if defined(PARA_FLASH) && !defined(PARA_FLASH_LATE) + if(!para) para=para_flash(pcnt); /* 1.6.9 test37 */ +#endif +#ifdef PARA_BACK + para_leave_mark(pcnt, para); /* 1.6.8: the Paradise does not live meanwhile */ +#endif + __asm__ volatile("" ::: "memory"); +#ifndef NOSRAMWATCH + swn=sram_watch(&swf, &swk); +#endif + for(u32* p=&__bss_start; p<&__bss_end; p++) *p=0; + { extern u32 __data_start, __data_end, __data_load; /* initial data values into SRAM */ + const u32 *src=&__data_load; for(u32* p=&__data_start; p<&__data_end; p++) *p=*src++; } + g_para=para; g_para_cnt=pcnt; +#ifndef CLEAN + g_sw_n=swn; g_sw_f=swf; g_sw_k=swk; +#else + (void)swn; (void)swf; (void)swk; +#endif + g_sc.guest_off=g_cfg.guest_off; g_sc.guest_size=g_cfg.guest_size; g_sc.save_off=g_cfg.save_off; g_sc.device=g_cfg.device; g_sc.map=g_cfg.map; g_sc.spare_end = g_cfg.version>=3u ? g_cfg.spare_end : 0u; +#ifdef SESS_FLAG + g_sc.nosess = g_cfg.version>=4u && (g_cfg.flags & 0x1000u); /* 1.7.3 test7: flags bit 12 = no session (run state) */ +#endif + hw_init(); +#ifdef PARA_FLASH_LATE + /* 1.7.2 test16: neither SRAM nor mailbox: the base in the Paradise's settings page (readable only after hw_init), as T7Emu */ + if(!g_para){ u32 c2=REG(0x45000304u), t2=para_flash(c2); if(t2){ g_para=t2; g_para_cnt=c2; para_mailbox_put(t2, c2); } } +#endif +#ifndef CLEAN + g_pc_n=pram_check((u32)__pdata_start, 1); +#else + pram_check((u32)__pdata_start, 1); +#endif /* after flashctl_init: code up to the data */ + /* Sign on the device: screen dark blue as soon as the display is set up. If the + * Paradise screen stays after A+C, startup never got this far. */ +#ifdef CLEAN + for(u32 x=0;x<128;x++) g_row[x]=0; /* black until the guest draws */ +#else + for(u32 x=0;x<128;x++) g_row[x]=0x0010u; +#endif + for(u32 y=0;y<128;y++) hw_push(g_row, 0, 0, y, 128, y+1); + /* Guest ROM: map the first MB cached, the rest uncached. */ + g_stage=1; diag(&g_emu,0); +#ifndef CLEAN + pram_wtest(); +#ifdef RAM20 + ram20_size(); /* harmful in Capybara (slows down), so off */ +#endif +#ifdef PROBE + probe_all(); +#endif +#ifndef NOSRAMWATCH + { u32 v[4]={5, g_sw_n>0xFFFFu?0xFFFFu:g_sw_n, g_sw_f&0xFFFFFu, g_sw_k>0xFFFu?0xFFFu:g_sw_k}; static const u8 nv[4]={1,4,5,3}; diag_line(8, v, nv, 4); } +#endif +#ifdef JIT_FRESHBUF + g_ct_ok=1; /* experiment: execute nothing in the JIT area beforehand */ +#else + code_test(); +#endif +#else + g_ct_ok=1; +#endif + mpu_guard(); +#ifdef NOJIT + jit_enabled=0; /* test build: interpreter only */ +#else + if(!g_ct_ok) jit_enabled=0; /* new code is not seen: run without JIT */ +#endif + XIP_BASE_REG = 0x60000000u | g_cfg.guest_off; + XIP_CTRL_REG = 3u; + Emu *e=&g_emu; + g_stage=2; diag(e,0); + /* device: 0 Plus Color (4 MB), 1 iD L, 2 P's, 3 4U+, 4 4U (all 8 MB, same map as the iD L; the 4U runs at 30 MHz) */ + if(g_cfg.device>=1){ tc_profile_idl(&e->dev); if(g_cfg.device>=3) e->dev.osc3_hz=30000000u; } + else tc_profile_plus_color(&e->dev); +#ifdef ID_STRAP + /* 1.7.4 test2: Tamagotchi iD firmwares (flags bit 13 from the Studio): debug pin P06 reads "no debug" like on the iD L */ + if(g_cfg.version>=4u && (g_cfg.flags & 0x2000u)) e->dev.debug_strap_high=false; +#endif + /* 1.6.8: 4U/4U+ get an answering NFC chip (flags bit 2 switches it off again) */ + if(g_cfg.device>=3u && g_cfg.device<=4u && !(g_cfg.flags & 4u)) e->dev.nfc_pn512=true; +#ifdef TC_IRLINK + /* 1.6.9: infrared to another Paradise over the contacts (iD L: session through its context pointer, P's: its mode byte) */ + if(g_cfg.device==1u){ tc_ir_setup(0, 0x84350u); plink_init(); } + else if(g_cfg.device==2u){ tc_ir_setup(0xDB3u, 0); plink_init(); } +#endif +#ifdef HW_OPTS + /* 1.6.8: volume (bits 16-17: 0 normal, 1 quiet, 2 loud, 3 off), brightness (18-19), screen off after (20-23) */ +#ifdef OPT_MENU + opt_load(); opt_apply(g_opt); +#else + opt_apply(g_cfg.version>=4u ? g_cfg.flags : 0u); +#endif +#endif + tc_init(e, 0, g_gram, g_pool, NSLOT); + tc_ovl_evict = st_evict; tc_big_erase = st_big_erase; st_init(&g_sc, g_pool); +#ifdef OVL_RAM20 + ovl_extra(e); +#endif + setup_rom(e); + cpu_reset(e); + if(para_hard()) periph_rtc_set(e, g_para + (REG(0x45000304u) - g_para_cnt)); /* fresh start: the Paradise's time too */ + g_stage=3; diag(e,0); + { u32 pause=0; + if(st_load(e, &g_sc, g_gram, &pause)){ + g_restored=1+pause; +#ifdef SESS_ONCE + st_drop(&g_sc); /* 1.6.8: used once; power gone without leaving: next start from the Tama's own save */ +#endif + /* reset pointers: everything that points into this run */ + e->lcd.gram=g_gram; + for(int i=0;iovl.base[i]=0xFFFFFFFFu; e->ovl.mem[i]= iovl.n=0; for(int i=0;i<4;i++) e->ovl_blk[i]=0; + e->rom=0; e->rom_fast=0; e->rom_fast_len=0; + e->fw_len=0; e->fw_lo=0xFFFFFFFFu; + setup_rom(e); + if(para_hard()) periph_rtc_set(e, g_para + (REG(0x45000304u) - g_para_cnt)); /* the Paradise's time, nothing caught up */ + else { if(pause > 400u*86400u) pause=400u*86400u; periph_rtc_advance(e, pause); } + e->lcd.dx0=0; e->lcd.dy0=0; e->lcd.dx1=127; e->lcd.dy1=127; LCD_ALL(); + } + } + st_pages(e, &g_sc); /* spare pages for written empty blocks (after a restore as well) */ +#ifdef TC_LZ + lz_setup(); +#endif +} +#if defined(OPT_MENU) && defined(EMU_OVL) +/* 1.6.8: wheel short: settings (the game stands still meanwhile); 1.6.13 test10: from the overlay */ +OVL_FN static void menu_run(Emu *e){ +#ifdef EMU_CARE +#ifdef ASK_LANG + const EmuCare *c=care_find(e); int en=EMU_EN(); + const char *cx[2]={ c ? "GOTCHI POINTS" : 0, c ? "PFLEGE VOLL|FULL CARE" : 0 }; + u32 n=hw_opts_menu_xn(g_opt, en, cx, 2); + if(n & 3u) en=(n & 3u)==2u; /* the language may have been changed in the menu */ +#else + const EmuCare *c=care_find(e); int en=(int)(g_cfg.flags & 1u); + const char *cx[2]={ c ? "GOTCHI POINTS" : 0, c ? (en ? "FULL CARE" : "PFLEGE VOLL") : 0 }; + u32 n=hw_opts_menu_xn(g_opt, en, cx, 2); +#endif + if(n & 0x80000000u){ u8 *p=care_p(e,c->pts); + if(n & (1u<<28)){ u8 *h=care_p(e,c->hun); if(*hhmax) *h=c->hmax; { u32 m=*care_p(e,c->med), cap; if(c->mask){ m&=c->mask; cap=0; while(m){ cap+=c->mul; m&=m-1u; } cap+=c->add; } else cap=m>2u?100u:30u; h=care_p(e,c->hap); if(*h>8); p[2]=(u8)(v>>16); p[3]=0; } } + n&=0x0FFFFFFFu; } +#else + u32 n=hw_opts_menu(g_opt, (int)(g_cfg.flags & 1u)); +#endif + if(n!=g_opt){ g_opt=n; opt_apply(n); opt_store(); } +} +#endif +/* test26 CLK_ECO: the main loop for size (the 64 KB were full); the hot paths (core, JIT, LCD push) stay -O2 */ +#ifdef CLK_ECO +__attribute__((minsize)) +#endif +void Reset_Handler(void){ + __asm__ volatile("cpsid i"); + boot(); + Emu *e=&g_emu; + /* startup code is done: the translator gets its space as well */ + g_stage=4; diag(e,0); +#if defined(JIT_STAGE) + /* v0.8.16: buffer back in PRAM (large, fast); code is generated in SRAM (3 KB after .bss) and copied by + * a loop running in SRAM. This way no PRAM code writes to PRAM any more. */ + { u32 lo=((u32)&__ram_end + 31u) & ~31u; + jit_stage_setup((uint8_t*)lo, 0xC00u); + jit_init(e, __initcode_start, (u32)__initcode_start, (u32)(__jit_end - __initcode_start)); } +#elif defined(JIT_SRAMBUF) + /* v0.8.14: translated code in SRAM between .bss and the stack (2 KB stack). On the device, code in + * SRAM is executable (probe v0.8.13: 66). Writing to PRAM while the CPU fetches instructions from PRAM + * is suspected of corrupting the fetched instructions. This way nothing writes to PRAM any more. */ + { u32 lo=((u32)&__ram_end + 31u) & ~31u, hi=0x18020000u - 0x800u; + jit_init(e, (uint8_t*)lo, lo, hi-lo); } +#elif defined(JIT_FRESHBUF) + /* Experiment v0.8.11: JIT area only in the never executed part (from __jit_start), not over the + * startup code. Smaller, but it never held code the CPU had already fetched. */ + jit_init(e, __jit_start, (u32)__jit_start, (u32)(__jit_end - __jit_start)); +#else + jit_init(e, __initcode_start, (u32)__initcode_start, (u32)(__jit_end - __initcode_start)); +#endif +#if defined(JIT_GUARD) && !defined(CLEAN) + jit_bad_hook = jit_bad; +#endif + g_stage=5; diag(e,0); + systick_init(); + __asm__ volatile("cpsie i"); + g_stage=6; diag(e,0); + u32 emu_ms=g_ms, last_push=g_ms, wheel_ms=0, dropped=0, idle=0, busy_ms=0; + g_btn_ms=g_ms; + for(;;){ + hw_wdt_feed(); +#ifndef CLEAN + if(!g_guest_drawn && (++g_loops & 0x3FFu)==1){ g_stage=7; diag(e, emu_ms); } +#endif +#ifdef DETERM + u32 now=emu_ms+1; +#else + u32 now=g_ms; +#endif +#ifdef BAT_GUARD + if(g_bat_go){ pw_full(); +#ifdef CLK_ECO + hw_clk_shift(0, CORE_HZ); +#endif + hw_tone(0); ovl_load(); bat_end(); } +#endif +#ifdef EMU_PW + /* screen dark, no key, tone or link traffic: 12 MHz from the internal RC, deep sleep once caught up (below). The + * guest's time runs on behind (nobody sees it); more than 2.5 s behind: full clock until caught up */ +#ifdef EMU_KEY_AWAKE + /* 1.7.3 test7: a key with the screen dark woke the chip, the guest got it, but once the key was let go the program + * went back to deep sleep before the guest had switched its screen on: the guest's wake-up then waited for the + * next RTC second (up to 1 s, more when the ms tick was behind). Now it stays awake for 2 s after a key + * (g_btn_ms: the last key the guest got). */ +#endif + int pw_quiet = !g_bl && !g_hw_tone_hz && !periph_tone_hz(e) && !wheel_ms +#ifdef EMU_TONE_Q + && tq_h == tq_w +#endif +#ifdef TC_IRLINK + && !(g_pl.last_rx && now-g_pl.last_rx<30000u) && !g_irtxn +#endif + && !hw_buttons() +#ifdef EMU_KEY_AWAKE + && now-g_btn_ms>2000u +#endif + ; + if(pw_quiet && (s32)(now-emu_ms)<2500){ /* after a deep sleep 1 s behind: caught up at 12 MHz */ +#ifdef CLK_ECO + if(!g_pw_low) hw_clk_shift(0, CORE_HZ); +#endif + pw_low(); + } else pw_full(); + { u32 r=REG(0x45000304u); /* when the RTC last stepped */ + if(r!=g_pw_rtc){ + /* after a wake by a key the part of a second slept is still missing: the step comes exactly whole seconds + * after the last one measured */ + if(g_pw_kw){ u32 t=g_pw_rtcms + (r-g_pw_rtc)*1000u; + __asm__ volatile("cpsid i" ::: "memory"); if((s32)(t-g_ms)>0) g_ms=t; __asm__ volatile("cpsie i" ::: "memory"); + now=g_ms; g_pw_kw=0; } + g_pw_rtc=r; g_pw_rtcms=now; } } + /* the screen dark: the guest's time passes in a tight loop up to the last ms (that one runs the whole loop: keys, + * light, saves), within 40 ms of real time; up to 5 s behind before time is dropped */ + if(pw_quiet){ u32 t1=g_ms; + while((s32)(now-emu_ms)>=2 && g_ms-t1<40u && !e->stopped +#ifdef EMU_TONE_Q + && !periph_tone_hz(e) /* test20: a tone (a call) begins: out to the main loop, which plays it at full clock */ +#endif + ){ pw_step(e); emu_ms++; g_pw_skip++; } } + if((s32)(now-emu_ms) > (g_bl ? 100 : 5000)){ +#else + if((s32)(now-emu_ms) > 100){ +#endif /* too far behind: drop time */ + u32 d=now-emu_ms-100; dropped += d; emu_ms = now-100; +#ifdef EMU_TQ_DROP + tq_drop += d; /* test22: else the note before the jump lasted as long as the jump (the long tone at a call) */ +#endif + { static u32 lost; lost += d; if(lost>=1000u){ periph_rtc_advance(e, lost/1000u); lost%=1000u; } } /* guest clock stays correct anyway */ +#ifndef CLOCK_DOUBLE + g_run_ms += d; /* 1.6.8: those ms are paid already, the comparison with the seconds counter below must not add them a second time */ +#endif + } + if(emu_ms == now){ /* caught up: sleep until the next tick */ +#ifdef EMU_TONE_Q + tq_pump(); +#endif + idle += SYST_CVR; + /* Only sleep once the SysTick interrupt is known to arrive. Otherwise poll the + * counter directly (COUNTFLAG) so the loop never gets stuck in wfi. */ + { static u32 g0=0xFFFFFFFFu; static int tick_ok; + if(g0==0xFFFFFFFFu) g0=g_ms; + if(!tick_ok && g_ms!=g0) tick_ok=1; +#ifdef EMU_PW + if(tick_ok && pw_quiet && g_pw_low && !hw_buttons()){ + /* deep sleep until the next RTC second or a key; the ms tick then continues from the time of the last RTC step */ + if(pw_sleep()){ u32 r=REG(0x45000304u), t=g_pw_rtcms + (r-g_pw_rtc)*1000u; + __asm__ volatile("cpsid i" ::: "memory"); if((s32)(t-g_ms)>0) g_ms=t; __asm__ volatile("cpsie i" ::: "memory"); + g_pw_rtc=r; g_pw_rtcms=t; } + } else +#endif + if(tick_ok) __asm__ volatile("wfi"); + else { u32 m=g_ms; if((SYST_CSR & 0x10000u) && g_ms==m) g_ms++; } } + continue; + } +#if !defined(CLOCK_DOUBLE) && !defined(RTC_MS) + if(g_hold_ms && (emu_ms & 15u)==0u){ g_hold_ms--; emu_ms++; continue; } /* guest clock ahead: one ms off */ +#endif + /* one millisecond of guest time */ + u32 mhz = e->cmu.mclk_hz ? e->cmu.mclk_hz : e->dev.osc3_hz; + /* v0.9.3: carry the rest of the division. With the 32768 Hz clock (the guest sleeping) + * mhz/1000 gave 32 instead of 32.768 cycles per ms: the guest clock lost 2.3 percent. */ +#ifdef EMU_PW + u32 cy_ms; { u32 t = mhz + g_cy_rest; cy_ms = t / 1000u; g_cy_rest = t % 1000u; } +#else + static u32 cy_rest; + u32 cy_ms; { u32 t = mhz + cy_rest; cy_ms = t / 1000u; cy_rest = t % 1000u; } +#endif +#if defined(CLEAN) && !defined(MESS) + u32 tr_stop=tc_run(e, e->cycles + cy_ms); +#else + u32 pc0=cyc_now(); + u32 tr_stop=tc_run(e, e->cycles + cy_ms); + g_cy_emu += cyc_now()-pc0; +#endif + if(tr_stop){ /* core stopped: show the error and wait */ + { volatile u32* st=g_st; st[0]=0x53544F50u; st[6]=e->stop_pc; st[7]=e->stop_code; st[2]=(u32)e->cycles; } + for(int y=0;y<128;y++) for(int x=0;x<128;x++) g_gram[y][x]=(u16)0xF800; + e->lcd.dx0=0; e->lcd.dy0=0; e->lcd.dx1=127; e->lcd.dy1=127; LCD_ALL(); + e->lcd.sleep_out=1; e->lcd.disp_on=1; e->lcd.madctl=0; + push_dirty(e); + for(;;){ hw_wdt_feed(); if(hw_buttons()&BTN_WHEEL) leave_nosave(); } + } + emu_ms++; busy_ms++; +#ifdef CLK_ECO + ECO_CHECK(g_ms, g_ms-emu_ms, CORE_HZ); +#endif +#ifdef TC_IRLINK + ir_link_tick(g_ms); +#endif +#ifdef RTC_MS + /* 1.6.8: the guest's clock counts real milliseconds (not guest cycles). Guest clock ahead of the + * Paradise's crystal (g_hold_ms from clock_sync): one ms in 16 is not counted. */ + if(g_hold_ms && (emu_ms & 15u)==0u) g_hold_ms--; else periph_rtc_ms(e); +#endif + /* v0.9.3: keep the guest clock on the Paradise's own seconds counter (crystal). If the + * millisecond tick runs slow, or busy scenes (shop, flash writes) make the emulator drop + * time, the missing seconds are added to the guest clock. */ + if(((++g_run_ms) & 1023u)==0u) clock_sync(e); +#ifdef CLK_DISC + clock_disc(e, (s32)(now - emu_ms)); +#endif +#ifndef RTC_KEEP_GUEST + /* 1.6.8: with the clock taken from the Paradise, a time the game sets itself (its first setup, after a reset) + * is replaced by the Paradise's time once the game has not touched its clock for 2 s */ + { static u32 wr0, wr_ms; + if(g_tc_rtc_wr!=wr0){ wr0=g_tc_rtc_wr; wr_ms=emu_ms?emu_ms:1; } + else if(wr_ms && emu_ms-wr_ms>2000u){ wr_ms=0; if(para_hard()) periph_rtc_set(e, g_para + (REG(0x45000304u) - g_para_cnt)); } } +#endif + /* Guest save into the Paradise flash: writing briefly stalls everything. + * So only once nothing has been written for 3 s AND the screen has been still + * for a moment (no game running), at the latest after 2 minutes. */ + { static u32 quiet; static int pend; +#ifdef GFLUSH_IDLE + static u32 pend_ms; + if(e->flash_dirty && !pend) pend_ms=now; +#endif +#ifdef EMU_PW + /* the ms passed in pw_steps count as quiet ones; the next one is a step of 250 */ + if(g_pw_skip){ if(pend){ quiet+=g_pw_skip; quiet-=(quiet+1u)%250u; } g_pw_skip=0; } +#endif + if(e->flash_dirty){ e->flash_dirty=false; quiet=0; pend=1; } + #ifdef GFLUSH_STEP + /* v0.8.22: after 3 s without new writes, at most one changed 4 KB part to flash every 250 ms, + * instead of everything at once (that caused stalls of half a second and more). */ +#ifdef GFLUSH_DARK + /* v0.9.1: only write while the screen is dark (then the pause goes unnoticed); + * after 10 minutes at the latest anyway, in case it never goes dark */ +#ifdef GFLUSH_IDLE + /* 1.6.6: with the screen always on it never went dark, and a guest that writes again within 10 minutes + * was never saved (power gone = save gone). Now also when no key was pressed for 20 s, and at the latest + * 10 minutes after the first unsaved write. */ + else if(pend && ++quiet>3000u && (quiet % 250u)==0u && (!g_bl || quiet>600000u || now-g_btn_ms>20000u || now-pend_ms>600000u) && !e->flash_busy && !e->flash_state +#ifdef LK_SYNC + && !g_lk_on /* not while a visit runs: writing stops the emulator */ +#endif + ){ if(st_flush_step(e, &g_sc)){ pend=0; g_n_gflash++; } } } +#else + else if(pend && ++quiet>3000u && (quiet % 250u)==0u && (!g_bl || quiet>600000u) && !e->flash_busy && !e->flash_state){ if(st_flush_step(e, &g_sc)){ pend=0; g_n_gflash++; } } } +#endif +#else + else if(pend && ++quiet>3000u && (quiet % 250u)==0u && !e->flash_busy && !e->flash_state){ if(st_flush_step(e, &g_sc)){ pend=0; g_n_gflash++; } } } +#endif +#else + else if(pend && ++quiet>3000u && (g_still>600u || quiet>120000u) && !e->flash_busy && !e->flash_state){ st_flush_guest(e, &g_sc); pend=0; g_n_gflash++; } } +#endif + u32 b=hw_buttons(); + { static int lock=1; /* wait for the start buttons (A+C) to be released */ + g_st[14]=b | ((u32)lock<<8); + if(lock){ if(b) b=0; else lock=0; } } +#ifdef CLK_ECO + /* test26: screen dark, no key, no tone, no link traffic for 30 s: a lower clock (eco.h) */ +#ifdef EMU_PW + if(!g_pw_low) +#endif + eco_poll(now, !g_bl && !b && !g_hw_tone_hz && !(g_pl.last_rx && now-g_pl.last_rx<30000u), (int)(now-emu_ms), CORE_HZ); +#endif + /* v0.9.5: guest screen dark right after the start (its own screen saver ran out while the clock + * caught up, often after the autostart): one short press of C wakes it, like the user would. + * Only once, only after resuming a session, in the first 8 s, while dark and nothing is pressed. */ + { static u32 t0, wk_ms; static int wk; + if(!t0) t0=now?now:1; + if(wk==0){ if(g_restored && !g_bl && !b && now-t0>1000u) { wk=1; wk_ms=now; } else if(now-t0>8000u) wk=2; } + if(wk==1){ if(now-wk_ms<150u) b|=BTN_C; else wk=2; } } +#ifdef HW_OPTS + /* screen off after a while without a key (set in the Studio): the first key only wakes it */ + { static int swallow; + if(g_scr_dark && b){ g_scr_dark=0; swallow=1; g_btn_ms=now; } +#ifdef EMU_DIM + if(b){ if(g_dimd && g_bl){ swallow=1; g_btn_ms=now; } g_dim_t=now; } +#endif + if(swallow){ if(b) b=0; else swallow=0; } } +#endif +#ifdef WAKE_WHEEL + /* 1.7.2: the wheel with the screen dark only wakes it: no settings, the Tama gets a short C (its screen comes on, + * as after resuming) */ + { static int ww; static u32 wc; + if(ww){ if(b&BTN_WHEEL) b&=~BTN_WHEEL; else { ww=0; wc=now?now:1; } } + else if((b&BTN_WHEEL) && !g_bl && !wheel_ms){ ww=1; b&=~BTN_WHEEL; } + if(wc){ if(now-wc<150u) b|=BTN_C; else wc=0; } } +#endif + periph_buttons(e,(uint8_t)(b&7)); + if(b) g_btn_ms=now; + /* v0.9.2: wheel within the first 3 s after resuming a saved session: throw the session away + * and go back to the Paradise. The next start begins fresh from the Tamagotchi's own save. */ + { static u32 t_start; if(!t_start) t_start=now?now:1; + if(g_restored && (b&BTN_WHEEL) && now-t_start<3000u){ + /* 1.6.6: ask first (a press meant for the speed display lost the game) */ +#ifdef EMU_OVL + ovl_load(); +#endif +#ifdef ASK_LANG + if(hw_ask_reset(EMU_EN())){ +#else + if(hw_ask_reset((int)(g_cfg.flags & 1u))){ +#endif + st_drop(&g_sc); leave_nosave(); } + g_restored=0; b=0; e->lcd.dx0=0; e->lcd.dy0=0; e->lcd.dx1=127; e->lcd.dy1=59; LCD_ALL(); } } + #ifndef NOWHEEL + if(b&BTN_WHEEL){ if(!wheel_ms) wheel_ms=now?now:1; else if(EXIT_NOW(now-wheel_ms, 1500u)) leave(); } +#if defined(OPT_MENU) + /* 1.6.8: wheel short: settings (the game stands still meanwhile) */ + else { if(wheel_ms && now-wheel_ms<1000u){ +#ifdef EMU_OVL + ovl_load(); menu_run(e); +#else +#ifdef EMU_CARE +#ifdef ASK_LANG + const EmuCare *c=care_find(e); int en=EMU_EN(); + const char *cx[2]={ c ? "GOTCHI POINTS" : 0, c ? "PFLEGE VOLL|FULL CARE" : 0 }; + u32 n=hw_opts_menu_xn(g_opt, en, cx, 2); + if(n & 3u) en=(n & 3u)==2u; /* the language may have been changed in the menu */ +#else + const EmuCare *c=care_find(e); int en=(int)(g_cfg.flags & 1u); + const char *cx[2]={ c ? "GOTCHI POINTS" : 0, c ? (en ? "FULL CARE" : "PFLEGE VOLL") : 0 }; + u32 n=hw_opts_menu_xn(g_opt, en, cx, 2); +#endif + if(n & 0x80000000u){ u8 *p=care_p(e,c->pts); + if(n & (1u<<28)){ u8 *h=care_p(e,c->hun); if(*hhmax) *h=c->hmax; { u32 m=*care_p(e,c->med), cap; if(c->mask){ m&=c->mask; cap=0; while(m){ cap+=c->mul; m&=m-1u; } cap+=c->add; } else cap=m>2u?100u:30u; h=care_p(e,c->hap); if(*h>8); p[2]=(u8)(v>>16); p[3]=0; } } + n&=0x0FFFFFFFu; } +#else + u32 n=hw_opts_menu(g_opt, (int)(g_cfg.flags & 1u)); +#endif + if(n!=g_opt){ g_opt=n; opt_apply(n); opt_store(); } +#endif + g_scr_dark=0; g_btn_ms=g_ms; +#ifdef EMU_DIM + g_dim_t=g_ms; +#endif + e->lcd.dx0=0; e->lcd.dy0=0; e->lcd.dx1=127; e->lcd.dy1=127; LCD_ALL(); } wheel_ms=0; } +#elif defined(CLEAN) && !defined(MESS) + else wheel_ms=0; +#else + else { if(wheel_ms && now-wheel_ms<1000u){ g_ovl^=1u; if(!g_ovl){ e->lcd.dx0=0; e->lcd.dy0=0; e->lcd.dx1=127; e->lcd.dy1=59; LCD_ALL(); } } wheel_ms=0; } +#endif +#endif +#ifdef LCD_QUIET + /* 1.6.8: only show finished pictures. The guest draws a picture in one burst of LCD writes; push once it + * has written nothing for 2 ms (at most every 40 ms, at the latest after 120 ms), not in the middle of a + * burst (the picture was seen building up from the top). */ + static u32 lw_last, lw_quiet; + { u32 lw=(u32)e->lcd_writes; if(lw!=lw_last){ lw_last=lw; lw_quiet=0; } else if(lw_quiet<1000u) lw_quiet++; } + if(emu_ms-last_push >= (((s32)(g_ms-emu_ms) > 20) ? 80u : 40u) && (lw_quiet>=2u || emu_ms-last_push>=120u)){ last_push=emu_ms; + push_dirty(e); } +#elif defined(LCD_SKIP) + /* v0.8.19: if emulation lags behind (more than 20 ms), only one frame every 80 ms instead of every 40 ms */ + if(emu_ms-last_push >= (((s32)(g_ms-emu_ms) > 20) ? 80u : 40u)){ last_push=emu_ms; +#if defined(CLEAN) && !defined(MESS) + push_dirty(e); } +#else + u32 c0=cyc_now(); push_dirty(e); g_cy_disp += cyc_now()-c0; } +#endif +#else + if(emu_ms-last_push>=40){ last_push=emu_ms; push_dirty(e); } +#endif + /* Speed display (short wheel press): top row, every 0.5 s. + * 5 + * 6 */ +#if !defined(CLEAN) || defined(MESS) + { static u32 t0, e0, d0, f0, i0, b0, v0, g0, ce0, cd0; + if(now-t0>=500u){ + if(g_ovl && t0){ u32 dt=now-t0, de=(emu_ms-e0)-(dropped-d0); u32 pct=de*100u/(dt?dt:1u); if(pct>999u) pct=999u; + u32 bcd=((pct/100u)<<8)|(((pct/10u)%10u)<<4)|(pct%10u); u32 fl=(jit_st_flush-f0)*2u; if(fl>0xFFu) fl=0xFFu; + u32 ip=(idle-i0)/(dt*960u+1u); if(ip>99u) ip=99u; ip=((ip/10u)<<4)|(ip%10u); + u32 v[5]={5, bcd, jit_used()>>8, fl, ip}; static const u8 nv[5]={1,3,2,2,2}; diag_line(0, v, nv, 5); + u32 nb=(jit_st_blocks-b0)*2u, ne=(st_n_evict-v0)*2u, nf=(st_n_step-g0)*2u; if(nb>0xFFFu) nb=0xFFFu; if(ne>0xFFu) ne=0xFFu; if(nf>0xFFu) nf=0xFFu; + u32 w[4]={6, nb, ne, nf}; static const u8 nw[4]={1,3,2,2}; diag_line(10, w, nw, 4); + /* 7 of CPU time (decimal) */ + u32 tot=dt*960u+1u, pe_=(g_cy_emu-ce0)/tot, pd=(g_cy_disp-cd0)/tot; if(pe_>99u) pe_=99u; if(pd>99u) pd=99u; + u32 rest = 100u>pe_+pd ? 100u-pe_-pd : 0u; if(rest>99u) rest=99u; + u32 z[4]={7, ((pe_/10u)<<4)|(pe_%10u), ((pd/10u)<<4)|(pd%10u), ((rest/10u)<<4)|(rest%10u)}; static const u8 nz[4]={1,2,2,2}; + diag_line(20, z, nz, 4); +#ifdef PROF + /* 8/9: the four most hit 256-byte locations (address, percent). A: share in the JIT buffer + * (from __initcode_start), share outside PRAM (SRAM copy loop and others). */ + { u32 tot2=g_prof_other; for(u32 i=0;i<256;i++) tot2+=g_prof[i]; if(!tot2) tot2=1; + u32 top[4]={0,0,0,0}, tv[4]={0,0,0,0}; + for(u32 i=0;i<256;i++){ u32 v=g_prof[i]; for(u32 k=0;k<4;k++) if(v>tv[k]){ for(u32 m=3;m>k;m--){ tv[m]=tv[m-1]; top[m]=top[m-1]; } tv[k]=v; top[k]=i; break; } } + u32 jit=0; for(u32 i=((u32)__initcode_start)>>8;i<256;i++) jit+=g_prof[i]; + #define PCT(x) ({ u32 _p=(x)*100u/tot2; if(_p>99u) _p=99u; ((_p/10u)<<4)|(_p%10u); }) + u32 a8[5]={8, top[0]<<8, PCT(tv[0]), top[1]<<8, PCT(tv[1])}; static const u8 n8[5]={1,4,2,4,2}; + u32 a9[5]={9, top[2]<<8, PCT(tv[2]), top[3]<<8, PCT(tv[3])}; + u32 aa[3]={0xA, PCT(jit), PCT(g_prof_other)}; static const u8 na_[3]={1,2,2}; + diag_line(30, a8, n8, 5); diag_line(40, a9, n8, 5); diag_line(50, aa, na_, 3); + for(u32 i=0;i<256;i++) g_prof[i]=0; g_prof_other=0; } +#endif + } + t0=now; e0=emu_ms; d0=dropped; f0=jit_st_flush; i0=idle; b0=jit_st_blocks; v0=st_n_evict; g0=st_n_step; ce0=g_cy_emu; cd0=g_cy_disp; } } +#endif +#if defined(TONE_FIX) && defined(EMU_TONE_Q) + /* test20: as T18Emu and T7Emu: the tone changes go into a queue with the game time and are played on the real + * clock (tq_pump), so a slow moment of the emulator no longer stretches or swallows notes */ + { static u32 tone, offc; u32 t=periph_tone_hz(e); +#ifdef EMU_TONE_GAP + /* test22: a pause of 4 ms or more is a pause (the B key: four notes with 8 ms between them, bridged they ran + * into one sliding tone); shorter ones are still bridged */ + if(t && tone && offc>=4u){ tq_put(0, emu_ms-offc); tone=0; } +#endif + if(t){ offc=0; if(t!=tone){ tone=t; tq_put(t, emu_ms); } } + else if(tone && ++offc>=30u){ tone=0; tq_put(0, emu_ms - 29u); } } + tq_pump(); +#elif defined(TONE_FIX) + /* Guest sound to the buzzer. Short gaps (under 30 ms of guest time) are bridged, + * otherwise the timer keeps restarting and it crackles. */ + { static u32 tone, offc; u32 t=periph_tone_hz(e); + if(t){ offc=0; if(t!=tone){ tone=t; hw_tone(t); } } + else if(tone && ++offc>=30u){ tone=0; hw_tone(0); } } +#else + { static u32 tone; u32 t=periph_tone_hz(e); /* guest sound to the buzzer */ + if(t!=tone){ tone=t; +#ifndef NOTONE + hw_tone(t); +#endif + } } +#endif + { static u32 dark; int bl=g_bl; /* guest display off: backlight off */ + int on = e->lcd.sleep_out && e->lcd.disp_on; +#ifdef BL_BLACK + /* v0.8.16: the guest often just turns its screen black instead of off. Every 0.5 s check + * whether the whole frame is black; if so, treat it as "off". */ + { static u32 bt; static int black; + if(now-bt>=500u){ bt=now; u16 z = e->lcd.inverted ? 0xFFFFu : 0u; black=1; + const u16 *g=&g_gram[0][0]; for(u32 i=0;i(s32)g_scr_ms) g_scr_dark=1; /* signed: right after the menu */ + if(g_scr_dark) on=0; +#endif +#ifdef BL_GUEST_PWM + /* 1.6.9: the colour Tamas light their screen with T16 channel 2 (PWM, all four models). The P's wakes its LCD + * every 20 minutes for about 9 s while the screen is dark, without that light (a dark refresh, also a silent + * reminder now and then); on the Paradise this lit the screen all night. The light now goes on only with the + * guest's own light, or with a key or a tone in the last second (a call stays visible), and stays on while + * the LCD stays on. */ + { static u32 tone_ms; static int ok; + if(periph_tone_hz(e)) tone_ms=now?now:1; + int gl=(e->ioram[0x300796u-e->dev.io_base] & 1u) && (e->ioram[0x3007E4u-e->dev.io_base] & 8u); + if(!on) ok=0; + else if(gl || now-g_btn_ms<1000u || (tone_ms && now-tone_ms<1000u)) ok=1; + if(!ok) on=0; } +#endif + if(on){ dark=0; if(!bl){ bl=1; hw_backlight(1); e->lcd.dx0=0; e->lcd.dy0=0; e->lcd.dx1=127; e->lcd.dy1=127; LCD_ALL(); +#ifdef EMU_DIM + g_dim_t=now; /* the game lit the screen (a call): full light, the dim time starts again */ +#endif + } } + else if(bl && ++dark>500u){ bl=0; hw_backlight(0); } + g_bl=bl; } +#ifdef EMU_DIM + /* signed: after the menu g_dim_t is later than now */ + if(g_dimd && ((s32)(now-g_dim_t)<=(s32)g_dim_ms || !g_bl)){ g_dimd=0; hw_bl_set(opt_light_pct(g_opt)); } /* a key, the menu, dark */ + else if(!g_dimd && g_dim_ms && g_bl && (s32)(now-g_dim_t)>(s32)g_dim_ms){ g_dimd=1; hw_bl_set(opt_dim_pct(g_opt)); } +#endif +#ifdef SESS_AUTO +#ifndef SESS_T1 +#define SESS_T1 600000u /* screen dark: 10 minutes after the last time at the earliest */ +#define SESS_T2 1800000u /* otherwise every 30 minutes */ +#endif + /* 1.6.8: the run state now and then, without leaving (battery empty or out while playing): when the screen + * goes dark (10 minutes after the last time at the earliest), otherwise every 30 minutes after 10 s without + * a key. st_save writes the guest flash back first (its slots are free then) */ + { static u32 last; static int bl0=1; + int went=bl0 && !g_bl; bl0=g_bl; + if(((went && now-last>SESS_T1) || (now-last>SESS_T2 && now-g_btn_ms>10000u)) && !e->flash_busy && !e->flash_state){ + hw_tone(0); +#ifdef EMU_OVL + ovl_load(); +#endif + st_save(e, &g_sc, g_gram); last=now; } } +#endif + { volatile u32* st=g_st; st[0]=0x53544154u; st[1]=now; st[2]=(u32)e->cycles; st[3]=(u32)(e->cycles>>32); + st[4]=e->cmu.mclk_hz; st[5]=e->flash_lost_writes; st[6]=e->pc; st[7]=e->halted; st[8]=jit_used(); + st[9]=emu_ms; st[10]=dropped; st[11]=idle; st[12]=busy_ms; st[13]=g_restored; } + } +} + +__attribute__((naked)) static void Default_Handler(void){ __asm__ volatile("1: b 1b\n"); } +__attribute__((naked)) static void Irq_Off(void){ __asm__ volatile("cpsid i\n bx lr\n"); } +__attribute__((section(".vectors"), used)) +const void* const g_vectors[16+64] = { (void*)0x18020000u, (void*)Reset_Handler, + [2 ... 14] = (void*)Default_Handler, [3 ... 6] = (void*)Fault_Handler, [11] = (void*)Irq_Off, [14] = (void*)Irq_Off, + [15] = (void*)SysTick_Handler, [16 ... 79] = (void*)Irq_Off +#ifdef TC_IRLINK + , [16 + 37] = (void*)plink_irq +#endif +#ifdef EMU_PW + , [16 + 2] = (void*)pw_rtc_irq, [16 + 26] = (void*)pw_gpio_irq +#endif +}; diff --git a/emu/src/emu/paraback.h b/emu/src/emu/paraback.h new file mode 100644 index 0000000..852cf6d --- /dev/null +++ b/emu/src/emu/paraback.h @@ -0,0 +1,91 @@ +/* 1.6.8 (PARA_BACK): the Paradise does not live while a program runs. + * The Paradise keeps no time of its own while a program runs, but its seconds counter 0x45000304 does. + * Back in the Paradise, its firmware compares "now" (base plus counter) with the time it lived up to + * (the six date fields at +0x1C of the settings block 0xEFE000/0xEFF000, year .. second, u16 each) and + * lives the whole gap at once: hunger, mood, care misses, even death. Same as TamaParadise v83. + * So: when a program starts, it notes the counter and the Paradise's time in the clock mailbox of paraclock.h + * ("PCLK" at 0x20000FC0, kept over the restart; the menu fills it at its start, a program started + * straight from the Paradise fills it itself). When it goes back, the date fields move forward by the time + * spent outside (never past now), both copies, new CRC, and the mailbox is cleared. + * (A first try with its own words at 0x20000FE0 made the Paradise start the program again: those words + * are not free.) + * Header only; needs flash_read and flash_update4k, a 4 KB buffer from the caller. */ +#ifndef PARABACK_H +#define PARABACK_H +#include +#ifndef PB_ATTR +#define PB_ATTR +#endif +#ifndef PB_MARK_ATTR +#define PB_MARK_ATTR /* para_leave_mark runs first thing at the start, before the flash window is set up: never in the flash */ +#endif +#ifndef PB_MB +#define PB_MB ((volatile uint32_t *)0x20000FC0u) /* same as PARA_MB: magic, time, counter, ~time */ +#endif +#define PB_MAGIC 0x4B4C4350u /* "PCLK" */ +#ifndef PB_CNT +#define PB_CNT (*(volatile uint32_t *)0x45000304u) +#endif + +/* t: the Paradise's local time (seconds since 1970) when the program started, cnt: the counter then */ +__attribute__((noinline, unused)) PB_MARK_ATTR static void para_leave_mark(uint32_t cnt, uint32_t t) +{ + volatile uint32_t *m = PB_MB; + if (m[0] == PB_MAGIC && m[3] == ~m[1] && m[1] && cnt - m[2] <= 400u * 86400u) return; /* noted by the menu */ + if (!t) { m[0] = 0; return; } + m[1] = t; m[2] = cnt; m[3] = ~t; m[0] = PB_MAGIC; +} + +static inline uint32_t pb_days(int32_t y, int32_t mo, int32_t d) /* days since 1970-01-01 */ +{ + y -= mo <= 2; int32_t era = (y >= 0 ? y : y - 399) / 400; int32_t yoe = y - era * 400; + int32_t doy = (153 * (mo + (mo > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return (uint32_t)(era * 146097 + doe - 719468); +} +__attribute__((minsize, noinline)) PB_ATTR static uint32_t pb_crc(const uint8_t *b) +{ + uint32_t c = 0; + for (uint32_t i = 4; i < 0x1000u; i++) { c ^= b[i]; for (int k = 0; k < 8; k++) c = (c & 1u) ? (c >> 1) ^ 0xA001u : c >> 1; } + return c; +} +static inline uint32_t pb_u16(const uint8_t *b, uint32_t o) { return b[o] | (uint32_t)b[o + 1] << 8; } +static inline void pb_w16(uint8_t *b, uint32_t o, uint32_t v) { b[o] = (uint8_t)v; b[o + 1] = (uint8_t)(v >> 8); } + +/* Before going back. Returns 1 when the fields were moved. */ +__attribute__((noinline, unused, minsize)) PB_ATTR static int para_back_fix(uint8_t *b) +{ + volatile uint32_t *m = PB_MB; + if (m[0] != PB_MAGIC || m[3] != ~m[1] || !m[1]) return 0; + uint32_t gap = PB_CNT - m[2], now = m[1] + gap; +#ifdef PARA_MB_KEEP + /* test29: the time stays in the mailbox, moved to now. A start device goes back to the menu, not to the + * Paradise: the SRAM then holds no Paradise clock, and the next program started without a time. */ + m[1] = now; m[2] = PB_CNT; m[3] = ~now; +#else + m[0] = 0; +#endif + if (gap < 60u || gap > 400u * 86400u) return 0; + flash_read(0xEFE000u, b, 0x1000u); + uint32_t c = pb_crc(b); + if (pb_u16(b, 0) != c || pb_u16(b, 2) != (~c & 0xFFFFu)) return 0; + uint32_t y = pb_u16(b, 0x1C), mo = pb_u16(b, 0x1E), d = pb_u16(b, 0x20); + uint32_t hh = pb_u16(b, 0x22), mi = pb_u16(b, 0x24), se = pb_u16(b, 0x26); + if (y < 2000u || y > 2100u || mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) return 0; + uint32_t f = pb_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + hh * 3600u + mi * 60u + se; + if (f >= now) return 0; + uint32_t nf = f + gap; if (nf > now) nf = now; + /* back to a date (civil from days) */ + int32_t z = (int32_t)(nf / 86400u) + 719468, era = (z >= 0 ? z : z - 146096) / 146097; + uint32_t doe = (uint32_t)(z - era * 146097), yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + int32_t yy = (int32_t)yoe + era * 400; uint32_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100), mp = (5 * doy + 2) / 153; + uint32_t dd = doy - (153 * mp + 2) / 5 + 1, mm = mp < 10 ? mp + 3 : mp - 9; yy += mm <= 2; + uint32_t s = nf % 86400u; + pb_w16(b, 0x1C, (uint32_t)yy); pb_w16(b, 0x1E, mm); pb_w16(b, 0x20, dd); + pb_w16(b, 0x22, s / 3600u); pb_w16(b, 0x24, s / 60u % 60u); pb_w16(b, 0x26, s % 60u); + c = pb_crc(b); + pb_w16(b, 0, c); pb_w16(b, 2, ~c & 0xFFFFu); + flash_update4k(0xEFE000u, b); + flash_update4k(0xEFF000u, b); + return 1; +} +#endif diff --git a/emu/src/emu/paraclock.h b/emu/src/emu/paraclock.h new file mode 100644 index 0000000..113e6c7 --- /dev/null +++ b/emu/src/emu/paraclock.h @@ -0,0 +1,118 @@ +/* The Paradise's own clock, read from its SRAM when an emulator starts (before the emulator uses + * the SRAM). The Paradise keeps the time as a base (days, seconds of the day) plus its seconds + * counter 0x45000304; next to it the six fields it shows (year, month, day, hour, minute, second, + * u16 each). Where this lies differs between the editions, so it is searched: a place counts only + * if base plus counter give the time of day the fields show (chance 1 in 86400). The fields may + * lag the counter by a few seconds; that is added. Same method as TamaParadise (uhrstellen). + * Only for the emulators' start; header only, shared by TamaEmu, T7Emu and T18Emu. */ +#ifndef PARACLOCK_H +#define PARACLOCK_H +#include +#ifndef PARA_ATTR +#define PARA_ATTR /* TamaEmu: start-up code only (its translator takes the space afterwards) */ +#endif + +/* days since 1970-01-01 */ +static inline int32_t para_days(int32_t y, int32_t m, int32_t d) +{ + y -= m <= 2; int32_t era = (y >= 0 ? y : y - 399) / 400; int32_t yoe = y - era * 400; + int32_t doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return era * 146097 + doe - 719468; +} +/* Search [lo, hi) (byte offsets in the SRAM at 0x18000000) for the clock, skip [skip_lo, skip_hi). + * Returns local time as seconds since 1970 (0 = not found). cnt: the seconds counter now. Must not + * use anything but registers and the stack: it runs before the emulator sets up its memory. */ +__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_clock(uint32_t cnt, uint32_t lo, uint32_t hi, uint32_t skip_lo, uint32_t skip_hi) +{ + const volatile uint16_t *h = (const volatile uint16_t *)0x18000000u; + uint32_t best = 0, best_lag = 600; + if (lo < 0x10) lo = 0x10; + for (uint32_t o = lo; o + 12 <= hi; o += 2) { + if (o + 12 > skip_lo && o - 0x10 < skip_hi) continue; + uint32_t y = h[o / 2]; + if (y < 2000u || y > 2100u) continue; + uint32_t mo = h[o / 2 + 1], d = h[o / 2 + 2], hh = h[o / 2 + 3], mi = h[o / 2 + 4], se = h[o / 2 + 5]; + if (mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) continue; + uint32_t days = h[(o - 0x10) / 2] | (uint32_t)h[(o - 0x10) / 2 + 1] << 16; + uint32_t sek = h[(o - 0x0C) / 2] | (uint32_t)h[(o - 0x0C) / 2 + 1] << 16; + if (sek >= 86400u || days >= 40000u) continue; + uint32_t tod = (sek + cnt % 86400u) % 86400u; /* days * 86400 drops out */ + uint32_t shown = hh * 3600u + mi * 60u + se; + uint32_t lag = (tod + 86400u - shown) % 86400u; /* fields behind the clock by this much */ + if (lag < best_lag) { + best_lag = lag; + best = (uint32_t)para_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + shown + lag; + } + } + return best; +} +/* 1.6.8: the Paramix menu runs before a program and uses the SRAM itself, so it looks the clock up at + * its own start and leaves it in the mailbox (0x20000FC0: "PCLK", time, counter, ~time). A program + * started from the menu takes it from there when its own search finds nothing. One day at most. */ +#define PARA_MB ((volatile uint32_t *)0x20000FC0u) +#define PARA_MB_MAGIC 0x4B4C4350u +__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_mailbox(uint32_t cnt) +{ + volatile uint32_t *m = PARA_MB; +#ifdef PARA_MB_KEEP + if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 400u * 86400u) return 0; /* test29: kept, see paraback.h */ +#else + if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 86400u) return 0; +#endif + return m[1] + (cnt - m[2]); +} +/* 1.7.2 test17: the mailbox written in the last two minutes (the menu right before starting the program, or its clock in a + * start device without the Paradise): it comes first, before the search in the SRAM, which may find old leftovers there */ +__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_mailbox_fresh(uint32_t cnt) +{ + volatile uint32_t *m = PARA_MB; + if (m[0] != PARA_MB_MAGIC || m[3] != ~m[1] || !m[1] || cnt - m[2] > 120u) return 0; + return m[1] + (cnt - m[2]); +} +#ifdef PARA_FLASH +/* 1.6.9 test37 (PARA_FLASH): the Paradise keeps the base of its clock in its settings page 0xEFE000 (copy at 0xEFF000): + * days since 2025-01-01 at +0x0C and seconds at +0x10; now = base + the seconds counter 0x45000304, which runs on + * while programs run. Found in the TamaParadise runs: the same base as in the SRAM clock (block in the SRAM at + * 0x18000B9C is this page). Used when neither the SRAM nor the mailbox give the time (the Paradise restarted and the + * mailbox was gone: reported, the clock of V3Emu and Tama-Go was not set now and then). The page must have a good + * CRC and its date fields (+0x1C, the time the Paradise lived up to) must lie within a year before that time. */ +__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_flash(uint32_t cnt) +{ + for (uint32_t pg = 0x60EFE000u; pg <= 0x60EFF000u; pg += 0x1000u) { + const volatile uint8_t *b = (const volatile uint8_t *)pg; + uint32_t c = 0; + for (uint32_t i = 4; i < 0x1000u; i++) { c ^= b[i]; for (int k = 0; k < 8; k++) c = (c & 1u) ? (c >> 1) ^ 0xA001u : c >> 1; } + if ((b[0] | (uint32_t)b[1] << 8) != c || (b[2] | (uint32_t)b[3] << 8) != (~c & 0xFFFFu)) continue; + uint32_t days = b[0x0C] | (uint32_t)b[0x0D] << 8 | (uint32_t)b[0x0E] << 16 | (uint32_t)b[0x0F] << 24; + uint32_t sek = b[0x10] | (uint32_t)b[0x11] << 8 | (uint32_t)b[0x12] << 16 | (uint32_t)b[0x13] << 24; + if (days > 40000u || sek >= 86400u) continue; + uint32_t y = b[0x1C] | (uint32_t)b[0x1D] << 8, mo = b[0x1E] | (uint32_t)b[0x1F] << 8, d = b[0x20] | (uint32_t)b[0x21] << 8; + uint32_t hh = b[0x22] | (uint32_t)b[0x23] << 8, mi = b[0x24] | (uint32_t)b[0x25] << 8, se = b[0x26] | (uint32_t)b[0x27] << 8; + if (y < 2000u || y > 2100u || mo < 1u || mo > 12u || d < 1u || d > 31u || hh > 23u || mi > 59u || se > 59u) continue; + uint32_t t = (20089u + days) * 86400u + sek + cnt; /* 20089: days from 1970 to 2025-01-01 */ + uint32_t f = (uint32_t)para_days((int32_t)y, (int32_t)mo, (int32_t)d) * 86400u + hh * 3600u + mi * 60u + se; + if (f > t + 600u || t - f > 366u * 86400u) continue; + return t; + } + return 0; +} +#endif +#ifdef PARA_CLEAN_CLK +/* 1.7.2 test17 (PARA_CLEAN_CLK): start device without the Paradise: nobody but the menu keeps the time, in its clock + * sector 0x0C0000 ("PMXK", time, counter then, idle, check = xor of the four). A program that starts first (autostart, + * the menu did not run) found no time before. Readable only after hw_init. */ +__attribute__((noinline, unused)) PARA_ATTR static uint32_t para_cleanclk(uint32_t cnt) +{ + const volatile uint32_t *p = (const volatile uint32_t *)0x600C0000u; + uint32_t m = p[0], t = p[1], c = p[2], i = p[3], k = p[4]; + if (m != 0x4B584D50u || k != (m ^ t ^ c ^ i) || !t || cnt < c) return 0; + return t + (cnt - c); +} +#endif +__attribute__((noinline, unused)) static void para_mailbox_put(uint32_t t, uint32_t cnt) +{ + volatile uint32_t *m = PARA_MB; + if (!t) return; + m[1] = t; m[2] = cnt; m[3] = ~t; m[0] = PARA_MB_MAGIC; +} +#endif diff --git a/emu/src/emu/plink.h b/emu/src/emu/plink.h new file mode 100644 index 0000000..2d87cdd --- /dev/null +++ b/emu/src/emu/plink.h @@ -0,0 +1,80 @@ +/* plink.h - 1.6.9: link to another Paradise over the UART on the contacts (as T18Emu's T18_LINK). + * UART1 0x4000B000, IRQ 37, 460800 8N1 like the flash program. Frames: A5 type len data sum (sum = type + len + data, + * low byte), 5A as start byte is taken too (from the PC). Every second a hello 'H' (ignored by the other side). + * Two Paradise plugged together at the top (their connector crosses TX and RX). + * Header only: include once in the program's main.c, put plink_irq at vector 16 + 37, call plink_init once and + * plink_poll in the main loop. Author: mameise */ +#ifndef PLINK_H +#define PLINK_H +#include "io.h" +#ifndef PL_ATTR +#define PL_ATTR __attribute__((noinline)) +#endif +#ifndef PL_INIT_ATTR +#define PL_INIT_ATTR PL_ATTR +#endif + +#define PL_U1 0x4000B000u +#define PL_DATA REG(PL_U1 + 0x00) +#define PL_IER REG(PL_U1 + 0x04) +#define PL_FCR REG(PL_U1 + 0x08) +#define PL_LCR REG(PL_U1 + 0x0C) +#define PL_LSR REG(PL_U1 + 0x14) +#define PL_FDR REG(PL_U1 + 0x28) +#define PL_CTRL REG(PL_U1 + 0x30) + +typedef void (*plink_fn)(u8 ty, const u8 *d, int n); +static struct { + u8 rx[256]; volatile u8 rh, rt; + u8 st, ty, len, pos, sum, on; + u8 f[64]; + u32 hello, last_rx; +} g_pl; + +__attribute__((used)) static void plink_irq(void) +{ + while (PL_LSR & 1u) { u8 b = (u8)PL_DATA; u8 nt = (u8)(g_pl.rt + 1u); if (nt != g_pl.rh) { g_pl.rx[g_pl.rt] = b; g_pl.rt = nt; } } +} +PL_INIT_ATTR static void plink_init(void) +{ + g_pl.rh = g_pl.rt = 0; g_pl.st = 0; g_pl.hello = 0; g_pl.last_rx = 0; + PL_IER = 0; + PL_LCR = 0x83; PL_DATA = 0x1A; PL_IER = 0x00; PL_LCR = 0x03; PL_FDR = 0x100; PL_FCR = 0x07; PL_CTRL = 0xC1; /* 460800 8N1 */ + while (PL_LSR & 1u) (void)PL_DATA; + PL_IER = 0x01; /* received data */ + REG(0xE000E104u) = 1u << (37 - 32); /* NVIC: UART1 */ + g_pl.on = 1; +} +PL_ATTR static void plink_send(u8 ty, const u8 *d, int n) +{ + if (!g_pl.on) return; + u8 h[3] = { 0xA5, ty, (u8)n }, s = (u8)(ty + n); + for (int i = 0; i < n + 4; i++) { + u8 v = i < 3 ? h[i] : i < n + 3 ? d[i - 3] : s; + if (i >= 3 && i < n + 3) s = (u8)(s + v); + for (u32 w = 0; !(PL_LSR & 0x20u); w++) if (w > 20000u) { g_pl.on = 0; return; } /* no UART: off, the game runs on */ + PL_DATA = v; + } +} +/* flags for the hello: bit 0 = in the connection screen (ready) */ +PL_ATTR static void plink_poll(u32 now, u8 flags, plink_fn fn) +{ + if (!g_pl.on) return; + while (g_pl.rh != g_pl.rt) { + u8 b = g_pl.rx[g_pl.rh]; g_pl.rh = (u8)(g_pl.rh + 1u); + switch (g_pl.st) { + case 0: if (b == 0xA5 || b == 0x5A) g_pl.st = 1; break; + case 1: g_pl.ty = b; g_pl.sum = b; g_pl.st = 2; break; + case 2: if (b > 64) { g_pl.st = 0; break; } g_pl.len = b; g_pl.pos = 0; g_pl.sum = (u8)(g_pl.sum + b); g_pl.st = b ? 3 : 4; break; + case 3: g_pl.f[g_pl.pos++] = b; g_pl.sum = (u8)(g_pl.sum + b); if (g_pl.pos >= g_pl.len) g_pl.st = 4; break; + default: + g_pl.st = 0; + if (b != g_pl.sum) break; /* noise on an open contact */ + g_pl.last_rx = now ? now : 1u; + if (g_pl.ty != 'H' && g_pl.ty != 'P') fn(g_pl.ty, g_pl.f, g_pl.len); + break; + } + } + if (now - g_pl.hello >= 1000u) { g_pl.hello = now; plink_send('H', &flags, 1); } +} +#endif diff --git a/emu/src/emu/pstate.h b/emu/src/emu/pstate.h new file mode 100644 index 0000000..f1b2a22 --- /dev/null +++ b/emu/src/emu/pstate.h @@ -0,0 +1,58 @@ +/* Paramix: an emulator's whole state in the flash (1.6.11 test2, GBEmu and SMSEmu). Stored on leaving, read once at the + * next start and dropped right after reading, so a power cut later starts from the game's own save as the real + * hardware would. Layout: header (magic "PMST", tag, length, sum) and the parts one after the other; the sectors behind + * the first are written first, the one with the header last (a cut while storing leaves no valid state). + * tag: anything that changes with the program build or the game (a state of another build is not taken). + * Header only. Author: mameise */ +#ifndef PSTATE_H +#define PSTATE_H +typedef struct { void *p; u32 n; } StPart; +#define ST_MAGIC 0x54534D50u /* "PMST" */ +#define ST_HEAD 16u + +/* byte i of the parts behind the header */ +static inline u8 st_byte(const StPart *pt, int np, u32 i) +{ + for (int k = 0; k < np; k++) { if (i < pt[k].n) return ((const u8 *)pt[k].p)[i]; i -= pt[k].n; } + return 0xFF; +} +static u32 st_len(const StPart *pt, int np) { u32 n = 0; for (int k = 0; k < np; k++) n += pt[k].n; return n; } + +/* sec: 4 KB buffer. Returns 1 when stored. */ +static int st_store(u32 at, u32 max, u32 tag, const StPart *pt, int np, u8 *sec) +{ + u32 len = st_len(pt, np), tot = ST_HEAD + len; + if (tot > max) return 0; + u32 sum = 0x5157u; + for (int k = 0; k < np; k++) { const u8 *p = (const u8 *)pt[k].p; for (u32 i = 0; i < pt[k].n; i++) sum = sum * 31u + p[i]; } + u32 ns = (tot + 0xFFFu) >> 12; + for (u32 s = ns; s-- > 0; ) { /* the last sector first, the header sector at the end */ + hw_wdt_feed(); + for (u32 i = 0; i < 0x1000u; i++) { + u32 o = (s << 12) + i; + u8 v = 0xFF; + if (o < ST_HEAD) { u32 w = o < 4 ? ST_MAGIC : o < 8 ? tag : o < 12 ? len : sum; v = (u8)(w >> (8 * (o & 3u))); } + else if (o < tot) v = st_byte(pt, np, o - ST_HEAD); + sec[i] = v; + } + flash_update4k(at + (s << 12), sec); + } + return 1; +} +static u32 st_rd32(const volatile u8 *p) { return p[0] | (u32)p[1] << 8 | (u32)p[2] << 16 | (u32)p[3] << 24; } +/* Returns 1 when a state of this tag was read into the parts (sizes must match). */ +static int st_load(u32 at, u32 max, u32 tag, const StPart *pt, int np) +{ + const volatile u8 *f = XIP_PTR(at); + u32 len = st_len(pt, np); + if (st_rd32(f) != ST_MAGIC || st_rd32(f + 4) != tag || st_rd32(f + 8) != len || ST_HEAD + len > max) return 0; + u32 sum = 0x5157u; + for (u32 i = 0; i < len; i++) { sum = sum * 31u + f[ST_HEAD + i]; if ((i & 0xFFFu) == 0) hw_wdt_feed(); } + if (sum != st_rd32(f + 12)) return 0; + u32 o = ST_HEAD; + for (int k = 0; k < np; k++) { u8 *p = (u8 *)pt[k].p; for (u32 i = 0; i < pt[k].n; i++) p[i] = f[o++]; } + return 1; +} +/* the header away: the state is used once */ +static void st_drop(u32 at) { if (st_rd32(XIP_PTR(at)) != 0xFFFFFFFFu) flash_erase4k(at); } +#endif diff --git a/emu/src/emu/state.c b/emu/src/emu/state.c new file mode 100644 index 0000000..37403bd --- /dev/null +++ b/emu/src/emu/state.c @@ -0,0 +1,269 @@ +/* Save and restore state. + * 1. Written flash sectors of the guest go back into its image in the + * Paradise flash (that is where the Tamagotchi's save lives). + * 2. The run state (CPU, RAM, peripherals, screen) is packed into the + * backup area; the next start resumes from there. */ +#include "hw.h" +#include "flash.h" +#include "../core/tc.h" +#include "state.h" +#ifdef EMU_OVL +#define ST_OVL __attribute__((section(".ovltext"))) /* 1.6.13 test10: the save when leaving, from the overlay */ +#else +#define ST_OVL +#endif + +#define MAGIC 0x53584D50u /* "PMXS" */ +#define SVER 3u /* 2: Emu fields rearranged for the translator (v0.7), 3: 64 KB sectors and spare pages (v0.9.2) */ +static u8 *g_sec; /* 4 KB buffer: first overlay slot (empty when saving) */ + +/* ---- Spare pages (v0.9.2) ---- + * The guest also writes 64 KB sectors that are empty in its firmware (item stores and others). + * The Studio does not store empty blocks, so these written 8 KB parts go into spare pages + * behind the packed firmware. A table in the first 4 KB says which page holds which part. + * Order when writing: page first, then table. A table that does not check out counts as empty. */ +#define PG_MAX 64 +#define PG_MAGIC 0x50584D50u /* "PMXP" */ +#ifndef PT_PAD +#define PT_PAD 4 /* host test: 4096, so the 4 KB read stays inside the variable */ +#endif +#if defined(LZ_GONE) && defined(TC_LZ) +/* 1.7.3 test21 LZ_GONE: packed blocks the guest erased, kept behind the table (own check word: older tables have + * whatever followed in RAM there). Before, they counted only until the next start: then the parts not written again + * read the old packed data, mixed with the new ones (items gone wrong, the game slow, odd pictures and sounds). */ +#define GONE_W 5u +#define GONE_MAGIC 0x454E4F47u +#else +#define GONE_W 0u +#endif +static struct { u32 magic, n, chk, pad; u16 vp[PG_MAX]; u32 gone[GONE_W]; u8 tail[PT_PAD]; } g_pt; +#define PT_LEN (16u+2u*PG_MAX+4u*GONE_W) +static u32 g_pg_tab, g_pg_data, g_pg_n; +u32 st_n_pages, st_n_free; +__attribute__((noinline)) static u32 pt_chk(void){ u32 x=g_pt.magic ^ (g_pt.n*0x9E3779B1u); for(u32 i=0;i>27) ^ g_pt.vp[i]; return x; } +__attribute__((noinline)) static void pt_save(void){ + g_pt.magic=PG_MAGIC; g_pt.n=g_pg_n; g_pt.chk=pt_chk(); + /* The DMA reads 4 KB from the table: what follows it in RAM is ignored when reading back. */ + if(g_pg_n && !flash_same(g_pg_tab, &g_pt, PT_LEN)) flash_prog4k(g_pg_tab, &g_pt); +} +__attribute__((noinline)) static void pt_count(void){ u32 n=0; for(u32 i=0;imap[blk & 127u] != 0xFFu; } + +TC_INIT void st_pages(Emu *e, const StCfg *c) +{ + u32 lo=(c->guest_off + c->guest_size + 0x1FFFu) & ~0x1FFFu, hi=c->spare_end & ~0x1FFFu; + g_pg_n=0; + if(hi >= lo + 0x4000u){ g_pg_tab=lo; g_pg_data=lo+0x2000u; g_pg_n=(hi-g_pg_data)>>13; if(g_pg_n>PG_MAX) g_pg_n=PG_MAX; } + flash_read(g_pg_tab, &g_pt, PT_LEN); + int bad=!g_pg_n || g_pt.magic!=PG_MAGIC || g_pt.n!=g_pg_n || g_pt.chk!=pt_chk(); + if(bad) + for(u32 i=0;ipg_base=(const uint8_t*)XIP_PTR(g_pg_data); + for(u32 i=0;i<4;i++) e->pg_blk[i]=0; + for(u32 i=0;i<1024;i++) e->pg_map[i]=0xFFu; + u32 nb=e->dev.rom_size>>16; if(nb>128) nb=128; + for(u32 b=0;bpar_base>=0x10000u) e->pg_blk[b>>5] |= 1u<<(b&31u); + for(u32 i=0;ipg_blk[v>>8]>>((v>>3)&31u))&1u) && e->pg_map[v]==0xFFu) e->pg_map[v]=(u8)i; else g_pt.vp[i]=0xFFFFu; } + pt_count(); +} + +/* Address in the Paradise flash of a stored block (0 = none). */ +__attribute__((noinline)) static u32 blk_addr(const StCfg *c, u32 off) +{ + u32 k=c->map[(off>>16)&127]; + if(k==0xFE) k=off>>16; + if(k==0xFF) return 0; + return c->guest_off + (k<<16) + (off & 0xFFFFu); +} +__attribute__((noinline)) static int all_ff(const u8 *p){ const u32 *w=(const u32*)p; for(u32 i=0;i>13)&1023u, i=e->pg_map[v]; + if(!((e->pg_blk[v>>8]>>((v>>3)&31u))&1u)) return 0; +#if defined(LZ_GONE) && defined(TC_LZ) + u32 lb=(base>>16)&127u; /* LZ_GONE: a part of a packed block keeps its page even when empty, else the old data comes back */ + if(all_ff(mem) && !(tc_lz_tab && ((const u32*)tc_lz_tab)[lb] && !((tc_lz_gone[lb>>5]>>(lb&31u))&1u))){ +#else + if(all_ff(mem)){ /* erased: release the page */ +#endif + if(i==0xFFu) return 0; + g_pt.vp[i]=0xFFFFu; e->pg_map[v]=0xFFu; pt_save(); pt_count(); return 1; + } + if(i==0xFFu){ /* new page */ + for(i=0;i=g_pg_n){ e->flash_lost_writes++; return 0; } + a=g_pg_data + (i<<13); + flash_update4k(a, mem); flash_update4k(a+0x1000u, mem+0x1000u); + g_pt.vp[i]=(u16)v; e->pg_map[v]=(u8)i; pt_save(); pt_count(); + return 3; + } + a=g_pg_data + (i<<13); + } + if(step){ + for(u32 h=0;h<2;h++) if(!flash_same(a+h*0x1000u, mem+h*0x1000u, 0x1000u)){ flash_prog4k(a+h*0x1000u, mem+h*0x1000u); return 1; } + return 0; + } + return flash_update4k(a, mem) + flash_update4k(a+0x1000u, mem+0x1000u); +} + +/* Erase a 64 KB sector of the guest (hook tc_big_erase). */ +static const StCfg *g_evcfg; +int st_big_erase(Emu *e, uint32_t base) +{ + const StCfg *c=g_evcfg; if(!c) return 0; + u32 a=blk_addr(c, base & ~0xFFFFu); + if(a){ + for(u32 s=0;s<16u;s++) if(!flash_isff(a+s*0x1000u, 0x1000u)) flash_erase4k(a+s*0x1000u); + return 1; + } +#ifdef TC_LZ + { u32 b=(base>>16)&127u; tc_lz_gone[b>>5] |= 1u<<(b&31u); } /* 1.7.3: an erased packed block reads empty */ +#endif + u32 v0=((base>>16)&127u)*8u; int ch=0; +#if GONE_W + { u32 b=(base>>16)&127u, m=1u<<(b&31u); + if(tc_lz_tab && ((const u32*)tc_lz_tab)[b] && !(g_pt.gone[b>>5]&m)){ g_pt.gone[b>>5]|=m; g_pt.gone[4]^=m; ch=1; } } +#endif + for(u32 v=v0; vpg_map[v]; if(i!=0xFFu){ g_pt.vp[i]=0xFFFFu; e->pg_map[v]=0xFFu; ch=1; } } + if(ch){ pt_save(); pt_count(); } + return 1; +} + +/* ---- Writing back the guest flash ---- */ +ST_OVL int st_flush_guest(Emu *e, const StCfg *c) +{ + int n=0; + if(e->flash_busy || e->flash_state) return 0; + for(int i=0;iovl.n;i++){ + if(e->ovl.base[i]==0xFFFFFFFFu) continue; + n+=wb_part(e, c, e->ovl.base[i], e->ovl.mem[i], 0); + tc_ovl_free(e, i); /* slot free, reads go to flash again */ + } + e->ovl.n=0; + e->fw_len=0; e->fw_lo=0xFFFFFFFFu; + return n; +} + +/* v0.8.22: write back step by step. At most one changed 4 KB part per call; the slots + * stay in use (no copying again). Returns 1 when everything in flash is already up to date. */ +u32 st_n_step; +int st_flush_step(Emu *e, const StCfg *c) +{ + static int cur; + if(e->flash_busy || e->flash_state) return 0; + int total=e->ovl.n; + for(int t=0;tovl.base[i]==0xFFFFFFFFu) continue; + if(wb_part(e, c, e->ovl.base[i], e->ovl.mem[i], 1)){ st_n_step++; cur=i; return 0; } + } + return 1; +} + +/* All slots in use: write one (round robin) to the image and free it. + * Costs one flash write; the guest only sees a short pause. */ +void st_init(const StCfg *c, u8 *buf4k){ g_evcfg=c; g_sec=buf4k; } +u32 st_n_evict; /* counter for the speed display */ +int st_evict(Emu *e) +{ + static int next; + if(!g_evcfg) return 0; + for(int t=0;tovl.mem[i] || e->ovl.base[i]==0xFFFFFFFFu) continue; + wb_part(e, g_evcfg, e->ovl.base[i], e->ovl.mem[i], 0); + st_n_evict++; + tc_ovl_free(e, i); + e->fw_len=0; e->fw_lo=0xFFFFFFFFu; + next=i+1; + return 1; + } + return 0; +} + +/* ---- packed data stream (PackBits) ---- */ +typedef struct { u32 addr, n, sec, total; } Wr; +ST_OVL static void w_flush(Wr *w){ if(!w->n) return; for(u32 i=w->n;i<0x1000u;i++) g_sec[i]=0xFF; flash_update4k(w->addr+w->sec*0x1000u, g_sec); w->sec++; w->n=0; } +ST_OVL static void w_byte(Wr *w, u8 b){ g_sec[w->n++]=b; w->total++; if(w->n==0x1000u) w_flush(w); } +ST_OVL static void w_block(Wr *w, const u8 *p, u32 len) +{ + u32 i=0; + while(i=3){ w_byte(w,(u8)(0x80+r-3)); w_byte(w,p[i]); i+=r; continue; } + u32 s=i, l=0; + while(i=3) break; + i++; l++; + } + w_byte(w,(u8)(l-1)); for(u32 k=0;kp>=r->end){ r->bad=1; return 0; } return *r->p++; } +static void r_block(Rd *r, u8 *d, u32 len) +{ + u32 i=0; + while(ibad){ + u8 c=r_byte(r); + if(c&0x80){ u32 n=(u32)(c-0x80)+3; u8 v=r_byte(r); for(u32 k=0;kdevice<<24) ^ (c->guest_size<<4) ^ 0x5A17u; } +static u32 rtc_now(void){ return REG(0x45000304u); } + +void st_drop(const StCfg *c){ if(!flash_isff(c->save_off, 0x1000u)) flash_erase4k(c->save_off); } + +ST_OVL void st_save(Emu *e, const StCfg *c, u16 (*gram)[128]) +{ + st_flush_guest(e, c); +#ifdef SESS_FLAG + if(c->nosess) return; /* 1.7.3 test7 NOSESS: only the guest's own save (its flash), no run state */ +#endif + /* invalidate the old header first */ + for(u32 i=0;i<0x1000u;i++) g_sec[i]=0xFF; + flash_update4k(c->save_off, g_sec); + Wr w={ c->save_off+0x1000u, 0, 0, 0 }; + w_block(&w, (const u8*)e, sizeof(Emu)); + w_block(&w, (const u8*)gram, 128u*128u*2u); + w_flush(&w); + Hdr h={ MAGIC, SVER, st_key(c), rtc_now(), w.total, w.sec, 0 }; + h.chk = h.magic ^ h.ver ^ h.key ^ h.rtc ^ h.bytes ^ h.sectors; + for(u32 i=0;i<0x1000u;i++) g_sec[i]=0xFF; + u8 *hp=(u8*)&h; for(u32 i=0;isave_off, g_sec); +} + +/* Returns 1 if a state was loaded. The caller sets the pointers in Emu. */ +TC_INIT int st_load(Emu *e, const StCfg *c, u16 (*gram)[128], u32 *pause_s) +{ +#ifdef SESS_FLAG + if(c->nosess){ st_drop(c); return 0; } /* 1.7.3 test7 NOSESS: an old session is thrown away, the guest boots from its own save */ +#endif + Hdr h; flash_read(c->save_off, &h, sizeof h); + if(h.magic!=MAGIC || h.ver!=SVER || h.key!=st_key(c)) return 0; + if(h.chk != (h.magic ^ h.ver ^ h.key ^ h.rtc ^ h.bytes ^ h.sectors)) return 0; + if(h.sectors > 0x4F) return 0; + Rd r={ XIP_PTR(c->save_off + 0x1000u), 0, 0 }; + r.end = r.p + h.bytes; + r_block(&r, (u8*)e, sizeof(Emu)); + r_block(&r, (u8*)gram, 128u*128u*2u); + if(r.bad) return 0; + u32 now=rtc_now(); + *pause_s = (now>=h.rtc) ? now-h.rtc : 0; + return 1; +} diff --git a/emu/src/emu/state.h b/emu/src/emu/state.h new file mode 100644 index 0000000..61b22b8 --- /dev/null +++ b/emu/src/emu/state.h @@ -0,0 +1,21 @@ +#ifndef STATE_H +#define STATE_H +#include "io.h" +#include "../core/tc.h" +#ifdef SESS_FLAG +typedef struct { u32 guest_off, guest_size, save_off, device; const volatile u8 *map; u32 spare_end, nosess; } StCfg; /* 1.7.3 test7: nosess = flags bit 12 */ +#else +typedef struct { u32 guest_off, guest_size, save_off, device; const volatile u8 *map; u32 spare_end; } StCfg; +#endif +int st_flush_guest(Emu *e, const StCfg *c); +int st_evict(Emu *e); +int st_flush_step(Emu *e, const StCfg *c); /* one part per call, 1 = done */ +extern u32 st_n_step; +void st_init(const StCfg *c, u8 *buf4k); /* buf4k: buffer for save/load */ +void st_pages(Emu *e, const StCfg *c); /* spare pages: load the table, set the pointers */ +int st_big_erase(Emu *e, uint32_t base); /* hook tc_big_erase */ +void st_drop(const StCfg *c); /* throw the run state away */ +extern u32 st_n_pages, st_n_free; +void st_save(Emu *e, const StCfg *c, u16 (*gram)[128]); +int st_load(Emu *e, const StCfg *c, u16 (*gram)[128], u32 *pause_s); +#endif diff --git a/emu/src/stub/stub.S b/emu/src/stub/stub.S new file mode 100644 index 0000000..0d0bfc4 --- /dev/null +++ b/emu/src/stub/stub.S @@ -0,0 +1,346 @@ +@ Stub in XIP flash: copies the app image to PRAM 0 and restarts. +@ APP_SRC (XIP address of the image) is set at build time. +@ With HOOKS: four entry points for the home screen handlers. They count how +@ long A and C are held together, start the emulator after LIMIT calls and +@ otherwise call the original handler. + .syntax unified + .thumb + +@ Autostart (v1.2.8): with AUTO set, the stub decides once per boot (first home screen call) +@ whether to start the emulator right away. Mailbox word 0x20000FFC (kept over a restart and +@ the reset button, lost in the Paradise's deep sleep): +@ "PMXL" written by the emulator when going back: stay in the Paradise +@ "PMXR" written here: any later restart with it (reset button) starts the emulator +@ other power-on or waking from deep sleep: the Paradise's seconds counter tells them +@ apart (it starts at 0 after power-on and when the clock is set) +@ Holding B skips the emulator. "Decided this boot" is kept in the UsageFault priority +@ (SHPR1 byte 2): it is cleared by every reset and the firmware does not use it. +@ AUTO is a placeholder the Studio sets to 0 or 1. +#ifndef AUTO +#define AUTO 0 +#endif + .macro AUTOSTART +#if defined(HOOKS) + ldr r2, =AUTO + cbz r2, 7f + ldr r2, =0xE000ED18 + ldrb r3, [r2, #2] + cbnz r3, 7f @ already decided in this boot + movs r3, #0xFF + strb r3, [r2, #2] + ldrb r3, [r2, #2] + cbz r3, 7f @ cannot keep the flag: never autostart + ldr r2, =0x20000FFC + ldr r3, [r2] + ldr r0, =0x4C584D50 @ "PMXL": back from the emulator + cmp r3, r0 + beq 8f + ldr r0, =0x52584D50 @ "PMXR": restart while running + cmp r3, r0 + beq 9f + ldr r0, =0x45000304 @ mailbox lost: deep sleep (clock ran) or power-on (clock new) + ldr r0, [r0] + cmp r0, #30 + bhs 8f +9: + ldr r0, =0x52584D50 + str r0, [r2] + tst r1, #0x800 @ B (P0.11) held: stay in the Paradise + beq 7f + b start +8: + ldr r0, =0x52584D50 + str r0, [r2] +7: + ldr r0, =0x40018000 +#endif + .endm +@ 1.7.2 test19 (BFALL): C held when the Paradise comes up after switching on (or after the reset button) starts +@ the flash app of the write protection (0xFF0000, its load table at 0xFFE000), a way back when a program or a +@ save leaves the screen black. Once per boot (BusFault priority byte as the flag, the firmware does not use it); +@ not when back from a program on purpose ("PMXL") and not after waking from deep sleep (mailbox lost, clock ran). +#ifndef NO_BFALL + .macro BFALL + ldr r2, =0xE000ED19 + ldrb r3, [r2] + cbnz r3, 7f + movs r3, #0xFF + strb r3, [r2] + ldrb r3, [r2] + cbz r3, 7f + tst r1, #0x400 @ C (P0.10); B at switching on already skips the autostart + bne 7f +#ifndef BFALL_WITH_A +@ 1.7.3 test29 (BFALL_NOA): not with A held too. A and C is the program key on the home screen; the first home +@ handler call of a boot with A+C held (within 30 s of switching on, or after a reset) started the flash app instead. + tst r1, #0x200 @ A (P0.9) held: the menu key, no way back + beq 7f +#endif + ldr r2, =0x20000FFC + ldr r2, [r2] + ldr r0, =0x4C584D50 + cmp r2, r0 + beq 7f + ldr r0, =0x45000304 + ldr r0, [r0] + cmp r0, #30 + blo 6f + ldr r0, =0x52584D50 @ "PMXR" / "PMXM": a reset, the mailbox was kept + cmp r2, r0 + beq 6f + ldr r0, =0x4D584D50 + cmp r2, r0 + bne 7f +6:ldr r0, =0x60FFE000 @ load table of the flash app, uncached flash + ldr r2, [r0] + ldr r3, =0x494E4F53 @ "SONI" + cmp r2, r3 + bne 7f + ldr r2, [r0, #0x10] + ldr r3, =0x60FF0000 + cmp r2, r3 + bne 7f + cpsid i + mov r4, r3 + b realstart +7: + ldr r0, =0x40018000 + ldr r1, [r0] + .endm +#else + .macro BFALL + .endm +#endif + .global start + .thumb_func +start: + cpsid i +#ifdef FELD + ldr r4, app_src + b.w realstart + .align 2 +app_src: .word APP_SRC +@ 1.6.0: start the program image at r0 (XIP address), fixed at +0x0C. The menu starts its +@ other programs (more emulators) through here. + .global start_src + .thumb_func +start_src: + cpsid i + mov r4, r0 +@ 1.6.6: the cached window (0x10000000) shows only 1 MB from 0x11000; programs further up (more emulators +@ from 0xD40000 down) came out as garbage. Copy from the uncached flash (0x60000000 + offset) instead. + add r4, r4, #0x50000000 + add r4, r4, #0x11000 + b.w realstart +@ 1.6.8: launcher ROM ("only a start device for programs"): the Studio points the handlers of every +@ scene after the setup (home, events, care ...) here, so the menu starts instead of the Paradise game. + .org 0x20 + .global launch + .thumb_func +launch: + cpsid i + ldr r4, feld_src + b.w realstart + .align 2 +feld_src: .word FELD_SRC +@ 1.6.8: entry for the start device's trampolines (r12 = the scene's original handler): the menu starts +@ only once the Paradise has a save (settings block 0xEFE000 stamped, date set), otherwise the original +@ handler runs, so a setup after "reset" can finish in the Paradise itself. + .org 0x2C + .global lcheck_e + .thumb_func +lcheck_e: + b.w lcheck +#else + ldr r4, =APP_SRC + b.w realstart + .ltorg +#endif + +#if defined(HOOKS) && !defined(FELD) + .org 0x40 @ hooks fixed at 0x40 (Studio: HOOK_OFF), original handlers at 0x94 + .global hook0, hook1, hook2, hook3 + .thumb_func +hook0: ldr.w r12, orig0 + b check + .thumb_func +hook1: ldr.w r12, orig1 + b check + .thumb_func +hook2: ldr.w r12, orig2 + b check + .thumb_func +hook3: ldr.w r12, orig3 + b check + .org 0x94 +orig0: .word ORIG0 +orig1: .word ORIG1 +orig2: .word ORIG2 +orig3: .word ORIG3 + .thumb_func +check: + push {r0-r3, r12, lr} + ldr r0, =0x40018000 @ GPIO0: A = P0.9, C = P0.10, pressed = 0 + ldr r1, [r0] + BFALL + AUTOSTART + ldr r2, =0x20000FF8 @ counter at the end of the mailbox + ldr r3, [r2] + tst r1, #0x600 + bne 5f + lsrs r0, r3, #16 + movw r1, #0xE7A1 + cmp r0, r1 + beq 4f + movw r3, #0 + movt r3, #0xE7A1 +4: + adds r3, #1 + str r3, [r2] + uxth r0, r3 + cmp r0, #LIMIT + bhs start + b 6f +5: + movs r3, #0 + str r3, [r2] +6: + pop {r0-r3, r12, lr} + bx r12 + .ltorg +#endif +#if defined(HOOKS) && defined(FELD) +@ With field switch: A+C starts the field switch (FELD_SRC), which in turn also +@ offers the program (APP_SRC). Return targets fixed at 0x94 as before. + .org 0x40 + .global hook0, hook1, hook2, hook3 + .thumb_func +hook0: ldr.w r12, orig0 + b check + .thumb_func +hook1: ldr.w r12, orig1 + b check + .thumb_func +hook2: ldr.w r12, orig2 + b check + .thumb_func +hook3: ldr.w r12, orig3 + b check + .org 0x94 +orig0: .word ORIG0 +orig1: .word ORIG1 +orig2: .word ORIG2 +orig3: .word ORIG3 + .thumb_func +check: + push {r0-r3, r12, lr} + ldr r0, =0x40018000 @ GPIO0: A = P0.9, C = P0.10, pressed = 0 + ldr r1, [r0] + BFALL + AUTOSTART + ldr r2, =0x20000FF8 @ counter at the end of the mailbox + ldr r3, [r2] +#ifndef HOOK_TEST + tst r1, #0x600 + bne 5f +#endif + lsrs r0, r3, #16 + movw r1, #0xE7A1 + cmp r0, r1 + beq 4f + movw r3, #0 + movt r3, #0xE7A1 +4: + adds r3, #1 + str r3, [r2] + uxth r0, r3 + cmp r0, #LIMIT + blo 6f + ldr.w r4, feld_src + cmp r4, #0 + beq start + cpsid i + b realstart +5: + movs r3, #0 + str r3, [r2] +6: + pop {r0-r3, r12, lr} + bx r12 + .ltorg +#endif + +#if defined(HOOKS) && defined(FELD) + .thumb_func +lcheck: + push {r0-r3, r12, lr} + ldr r0, =0x60EFE000 @ settings block, uncached flash + ldrh r1, [r0, #0] + ldrh r2, [r0, #2] + mvns r2, r2 + uxth r2, r2 + cmp r1, r2 @ stamp: CRC and its inverse + bne 1f + ldrh r1, [r0, #0x1C] @ year 2020..2099 + movw r2, #2020 + cmp r1, r2 + blo 1f + movw r2, #2099 + cmp r1, r2 + bhi 1f + ldrh r1, [r0, #0x1E] @ month 1..12 + subs r1, #1 + cmp r1, #12 + bhs 1f + cpsid i + ldr.w r4, feld_src + b realstart +1: + pop {r0-r3, r12, lr} + bx r12 + .ltorg +#endif + +@ Restart like the firmware itself (routine at flash 0x110568): first switch the +@ clock to source 4 (0x45000000 = 0x8041, 0x4500000C = 4, wait for 0x44), then +@ copy the image to PRAM 0, then SYSRESETREQ. v0.8 without this sequence froze +@ the real device after A+C (suspected: clock), the emulator did not show it. + .thumb_func +realstart: + cpsid i + ldr r3, =0x45000000 + movw r2, #0x8041 + str r2, [r3] + movs r2, #4 + str r2, [r3, #0xC] + ldr r1, =0x400000 +3: + ldr r2, [r3, #0xC] + cmp r2, #0x44 + beq 4f + subs r1, #1 + bne 3b +4: + mov r0, r4 + movs r1, #0 + ldr r2, =0x10000 +1: + ldr r3, [r0], #4 + str r3, [r1], #4 + subs r2, #4 + bne 1b + dsb + isb + ldr r0, =0xE000ED08 @ VTOR = 0, as after a real reset + movs r1, #0 + str r1, [r0] + ldr r0, =0xE000ED0C @ AIRCR: keep priority grouping, SYSRESETREQ + ldr r1, [r0] + and r1, r1, #0x700 + ldr r2, =0x05FA0004 + orrs r1, r2 + str r1, [r0] + dsb +2: + b 2b + .ltorg diff --git a/emu/src/tools/dlc.py b/emu/src/tools/dlc.py new file mode 100644 index 0000000..658d004 --- /dev/null +++ b/emu/src/tools/dlc.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Install download content (TAMAGO records from .jpg) into an 8 MB image. +dlc.py [--fach N] (games: slot 0 or 1) +dlc.py --liste""" +import sys +GAMES = (0x7A0000, 0x8000, 2) +KINDS = [('Essen', 0x590000, 0x800, 20), ('Snacks', 0x5A0000, 0x800, 20), ('Kleidung', 0x600000, 0x4000, 5), + ('Zubehoer', 0x650000, 0x2000, 10), ('Sachen', 0x6A0000, 0x2000, 10), ('Alltag', 0x740000, 0x8000, 5), + ('Tapeten', 0x780000, 0x2000, 10), ('Spiele', 0x7A0000, 0x8000, 2), ('Reiseziele', 0x7B0000, 0x8000, 2)] + +def payload(data): + if data[:6] == b'TAMAGO': blob = data + else: + e = data.find(b'\xff\xd9'); m = data.find(b'TAMAGO', e + 2 if e >= 0 else 0) + if m < 0: raise SystemExit('no TAMAGO record in the file') + blob = data[m:] + def ok(n): return n >= 3 and (sum(blob[:n - 2]) & 0xFFFF) == int.from_bytes(blob[n - 2:n], 'big') + ln = int.from_bytes(blob[0x48:0x4C], 'big') if len(blob) >= 0x4C else 0 + if 0x60 <= ln <= len(blob) and ok(ln): return blob[:ln] + for s in range(17): + n = len(blob) - s + if n >= max(0x60, ln) and ok(n): return blob[:n] + raise SystemExit('record checksum does not match') + +def info(rec): + name = rec[6:0x34].decode('utf-16-be', 'replace').rstrip('\0').strip() + return rec[0x34:0x48].split(b'\0')[0].decode('latin1'), name + +def liste(img): + for l, b, sz, n in KINDS: + for s in range(n): + o = b + s * sz + if img[o:o + 6] == b'TAMAGO': print('%-10s Fach %d %s %s' % (l, s, *info(img[o:o + sz]))) + +def main(): + img = bytearray(open(sys.argv[1], 'rb').read()); img += b'\xff' * (0x800000 - len(img)) + if '--liste' in sys.argv: liste(img); return + rec = payload(open(sys.argv[2], 'rb').read()) + if rec[0x4E] != 0x94 or rec[0x50] != 0x5B: raise SystemExit('not a game (type %02x cat %02x)' % (rec[0x4E], rec[0x50])) + base, sz, n = GAMES + fach = int(sys.argv[sys.argv.index('--fach') + 1]) if '--fach' in sys.argv else n - 1 + o = base + fach * sz + print('ersetze', info(img[o:o + sz]) if img[o:o + 6] == b'TAMAGO' else 'leer', '->', info(rec)) + img[o:o + sz] = rec + b'\xff' * (sz - len(rec)) + open(sys.argv[3], 'wb').write(img) + +if __name__ == '__main__': main() diff --git a/emu/src/tools/feld_rom.py b/emu/src/tools/feld_rom.py new file mode 100644 index 0000000..ff7dea5 --- /dev/null +++ b/emu/src/tools/feld_rom.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Install the field switch into the Paradise ROM (Land/Water/Sky, firmware v1). +feld_rom.py [--app app.bin] [--feld feld.bin] +Holding B+C on the home screen starts the field switch, A+C (if --app) +starts the program as before. The three save slots sit after the characters.""" +import sys, struct, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from patch_rom import scene_table, xip, APP_OFF, STUB_OFF +import subprocess, tempfile + +FELD_OFF = 0xB1000 +SLOT_SIZE = 0x58000 +FELD_MAGIC = 0x444C4546 + +def build_stub(app_src, feld_src, origs, limit=90): + here = os.path.dirname(os.path.abspath(__file__)) + S = os.path.join(here, '..', 'stub', 'stub.S') + t = tempfile.mkdtemp() + defs = ['-DAPP_SRC=%d' % app_src, '-DFELD=1', '-DFELD_SRC=%d' % feld_src, '-DHOOKS=1', '-DLIMIT=%d' % limit] + defs += ['-DORIG%d=%d' % (i, v) for i, v in enumerate(origs)] + if os.environ.get('HOOK_TEST'): defs.append('-DHOOK_TEST=1') + subprocess.check_call(['clang', '--target=thumbv7em-none-eabi', '-mcpu=cortex-m4', '-x', 'assembler-with-cpp', '-c', S, '-o', t + '/s.o'] + defs) + subprocess.check_call(['ld.lld', '--no-rosegment', '-Ttext=%#x' % xip(STUB_OFF), '-e', 'start', t + '/s.o', '-o', t + '/s.elf']) + subprocess.check_call(['llvm-objcopy', '-O', 'binary', t + '/s.elf', t + '/s.bin']) + return open(t + '/s.bin', 'rb').read() + +def slot_off(d): + asset_end = (0x111000 + 16 + struct.unpack_from('= 0 + so = slot_off(d) + assert so + 3 * SLOT_SIZE <= 0x940000, 'no room for the slots' + struct.pack_into('0x1000000: ok=False;break + prev=w + if ok: + k=o+e0 + if k+240 and d[k+9]>0: return o + o+=4 + return -1 +def itemtab(d,nb): + best,bn=-1,0; o=0 + while o+SATZ=nb or k in seen: break + seen.add(k); n+=1 + if n>bn: bn,best=n,o + if n>8: o+=n*SATZ-2 + o+=2 + return best,bn +def s_at(d,t,n): + ab=u16(d,t+2*n) + if ab<=0 or ab>0x8000: return '' + o=t+2*ab; s='' + while len(s)<40: + c=u16(d,o) + if c==0: break + if A<=c0x8000: return False + return all(A<=u16(d,t+2*ab+2*k)n and u16(d,o+4)>u16(d,o+2) and u16(d,o+6)>u16(d,o+4) and word3(d,o,1): + prev=n;ok=True + for i in range(1,min(n,200)): + w=u16(d,o+2*i) + if w0x8000: ok=False;break + prev=w + if ok: + p=sum(1 for k in range(1,120) if s_at(d,o,k) in WORDS) + if p>bp: bp,best=p,o + o+=2 + return best if bp>=2 else None +def catalog(d): + bt=bildtab(d); nb=u32(d,bt)//4 + it,n=itemtab(d,nb) + lt=langtab(d) + out=[] + for i in range(n): + o=it+i*SATZ; k=u16(d,o); nm=u16(d,o+2)+1; price=u16(d,o+24) + if not (5001<=k<=8999): continue + name=s_at(d,lt,nm) if lt is not None else '' + out.append((k,price==0xFFFF,name)) + return sorted(out),hex(bt),hex(it),n,lt +if __name__=='__main__': + for f in sys.argv[1:]: + d=open(f,'rb').read() + c,bt,it,n,lt=catalog(d) + print(f.split('/')[-1],bt,it,n,hex(lt) if lt else None,len(c),'fixed',[x[0] for x in c if x[1]],'without name',sum(1 for x in c if not x[2])) + print(' ',c[:3],c[-3:], max(len(x[2]) for x in c)) diff --git a/emu/src/tools/patch_rom.py b/emu/src/tools/patch_rom.py new file mode 100644 index 0000000..7d72bf8 --- /dev/null +++ b/emu/src/tools/patch_rom.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Installs the stub into the Paradise ROM. +patch_rom.py [--scene PSID_NAME] [--guest fw.bin --device pc|idl] +Places the app image (max 64 KB) at APP_OFF and the stub at STUB_OFF and +redirects all four handlers of the chosen scene to the stub.""" +import sys, struct, re, subprocess, os, tempfile +XIP_DEC = 0x11000 +def xip(off): return 0x10000000 + off - XIP_DEC +APP_OFF, STUB_OFF = 0xA0000, 0xB0000 + +def scene_table(d): + names = {xip(m.start()): m.group()[:-1].decode() for m in re.finditer(rb'PSID_[A-Z0-9_]+\x00', d)} + ptrs = [(o, w) for o in range(0, len(d) - 4, 4) for w in [struct.unpack_from(' len(best): best = run + run = [b] + if len(run) > len(best): best = run + base = best[0][0] - 4 + return {names[w]: base + i * 28 for i, (o, w) in enumerate(best)} + +def build_stub(app_src, origs=None, limit=90): + here = os.path.dirname(os.path.abspath(__file__)) + S = os.path.join(here, '..', 'stub', 'stub.S') + t = tempfile.mkdtemp() + defs = ['-DAPP_SRC=%d' % app_src] + if origs: + defs += ['-DHOOKS=1', '-DLIMIT=%d' % limit] + ['-DORIG%d=%d' % (i, v) for i, v in enumerate(origs)] + subprocess.check_call(['clang', '--target=thumbv7em-none-eabi', '-mcpu=cortex-m4', '-x', 'assembler-with-cpp', '-c', S, '-o', t + '/s.o'] + defs) + subprocess.check_call(['ld.lld', '--no-rosegment', '-Ttext=%#x' % xip(STUB_OFF), '-e', 'start', t + '/s.o', '-o', t + '/s.elf']) + subprocess.check_call(['llvm-objcopy', '-O', 'binary', t + '/s.elf', t + '/s.bin']) + syms = {} + for l in subprocess.run(['llvm-nm', t + '/s.elf'], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 3: syms[p[2]] = int(p[0], 16) + return open(t + '/s.bin', 'rb').read(), syms + +GUEST_OFF, GUEST_END = 0x940000, 0xD40000 +DEVICES = {'pc': (0, 0x400000), 'idl': (1, 0x800000)} +# Blocks with many data accesses first: they end up in the cached 1 MB window +HOT = {'pc': [0x25, 0x21, 0x04, 0x02, 0x01, 0x03, 0x05, 0x20, 0x22, 0x23, 0x24, 0x26, 0x27, 0x28, 0x29, 0x2a], + 'idl': [0x0e, 0x0b, 0x19, 0x16, 0x0d, 0x18, 0x0c, 0x4f, 0x50, 0x15, 0x40, 0x4c, 0x4d, 0x0f, 0x17, 0x1a]} + +def pack_guest(fw, dev): + kind, size = DEVICES[dev] + fw = fw[:size] + b'\xff' * (size - min(len(fw), size)) + nblk = size >> 16 + par = nblk - 1 if dev == 'pc' else 0 # always include the parameter block (save) + used = [i for i in range(nblk) if i == par or fw[i << 16:(i + 1) << 16] != b'\xff' * 0x10000] + order = [b for b in HOT[dev] if b in used] + [b for b in used if b not in HOT[dev]] + m = bytearray(b'\xff' * 128) + blob = bytearray() + for idx, b in enumerate(order): + m[b] = idx + blob += fw[b << 16:(b + 1) << 16] + assert GUEST_OFF + len(blob) <= GUEST_END, 'guest ROM too big: %d blocks' % len(order) + return kind, bytes(m), bytes(blob) + +def set_cfg(app, kind, guest_size, m): + i = app.find(struct.pack('= 0, 'PMXC not found' + a = bytearray(app) + struct.pack_into('<6I', a, i, 0x43584D50, 2, GUEST_OFF, guest_size, 0xC0000, kind) + a[i + 24:i + 24 + 128] = m + return bytes(a) + +def main(): + rin, app, rout = sys.argv[1:4] + scene = None # default: hold A+C on the home screen + if '--scene' in sys.argv: scene = sys.argv[sys.argv.index('--scene') + 1] + d = bytearray(open(rin, 'rb').read()) + a = open(app, 'rb').read() + if '--guest' in sys.argv: + dev = sys.argv[sys.argv.index('--device') + 1] if '--device' in sys.argv else 'pc' + kind, m, blob = pack_guest(open(sys.argv[sys.argv.index('--guest') + 1], 'rb').read(), dev) + d[GUEST_OFF:GUEST_OFF + len(blob)] = blob + a = set_cfg(a, kind, len(blob), m) + print('Gast', dev, len(blob) >> 16, 'Bloecke ab', hex(GUEST_OFF)) + assert len(a) <= 0x10000, 'App groesser als 64 KB' + for off, n in ((APP_OFF, 0x10000), (STUB_OFF, 0x1000)): + assert d[off:off + n] == b'\xff' * n or True + d[APP_OFF:APP_OFF + 0x10000] = a + b'\x00' * (0x10000 - len(a)) + tab = scene_table(bytes(d)) + if scene: + st, _ = build_stub(xip(APP_OFF)) + d[STUB_OFF:STUB_OFF + len(st)] = st + o = tab[scene] + for k in range(3, 7): + struct.pack_into(' Starter', hex(xip(STUB_OFF) | 1), 'Stub', len(st), 'Byte') + else: + o = tab['PSID_HOME'] + origs = list(struct.unpack_from('<4I', d, o + 12)) + if any(xip(STUB_OFF) <= v < xip(STUB_OFF) + 0x1000 for v in origs): + raise SystemExit('ROM ist schon gepatcht (Heimbildschirm zeigt auf den Starter)') + st, sy = build_stub(xip(APP_OFF), origs) + d[STUB_OFF:STUB_OFF + len(st)] = st + for k in range(4): + struct.pack_into(' [KEYS="t:mask,..."] [SHOTS="t,..."] [OUT=dir] +# load: the code run per ms until the main loop waits (wfi), against RT instructions +# LAGLOG=n: every n ms the emulated and dropped ms in that time +import sys, struct, subprocess, os +from unicorn import * +from unicorn.arm_const import * +elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3]) +RT = int(os.environ.get('RT', '64000')) +out = os.environ.get('OUT', '.') +syms = {} +for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 3: syms[p[2]] = int(p[0], 16) +fl = bytearray(open(img, 'rb').read()) +u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS) +u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4) +APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) +u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000])) +u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000) +u.mem_map(0x10000000, 0x100000) +u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl)) +u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) +u.mem_write(0x4000B014, struct.pack('= t: m = v + return m +def ret(uc, v=None): + if v is not None: uc.reg_write(UC_ARM_REG_R0, v) + uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1) +def h_begin(uc): + x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3)) + rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc) +def h_row(uc): + p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n)) + for v in d: + if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v + rect['x'] += 1 + if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1 + state['rows'] = state.get('rows', 0) + 1; ret(uc) +def h_push(uc): + p = uc.reg_read(UC_ARM_REG_R0); x0, y0, x1, y1 = uc.reg_read(UC_ARM_REG_R2), uc.reg_read(UC_ARM_REG_R3), *struct.unpack('= syms.get('__initcode_start', 0x10000): # start code: its room becomes the translator's afterwards + u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: not state.get('jit') and f(uc))(f), begin=a, end=a) + else: u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a) +def bad(uc, access, addr, size, value, ud): + print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False +u.hook_add(UC_HOOK_MEM_UNMAPPED, bad) +if os.environ.get('ROMHIST'): # reads of the guest firmware per flash block: cached window and direct (uncached) + _cfg = APPOFF + 0x140; _go = struct.unpack_from('= 0x60000000: k = ((a & 0xFFFFFF) - _go) >> 16; RH[('u', k)] = RH.get(('u', k), 0) + 1 + else: k = ((WIN[0] & 0xFFFFFF) + (a - 0x10000000) - _go) >> 16; RH[('c', k)] = RH.get(('c', k), 0) + 1 + u.hook_add(UC_HOOK_MEM_READ, _rh, begin=0x60000000 + _go, end=0x60000000 + _go + _gl - 1) + u.hook_add(UC_HOOK_MEM_READ, _rh, begin=0x10000000, end=0x100FFFFF) + import atexit + def _rhp(): + _map = bytes(fl[_cfg + 24:_cfg + 152]); inv = {m: b for b, m in enumerate(_map) if m != 0xFF} + tot = {} + for (w, k), n in RH.items(): tot[k] = tot.get(k, 0) + n + print('romhist (flash slot: guest block, reads, uncached reads):') + print(' '.join('%d:%02x:%d:%d' % (k, inv.get(k, 0xFF), n, RH.get(('u', k), 0)) for k, n in sorted(tot.items(), key=lambda kv: -kv[1])[:40])) + atexit.register(_rhp) +if os.environ.get('INSTRACE'): # INSTRACE=ms: every instruction from that ms on, the last 300 (pc, sp) + import collections, atexit + TI = collections.deque(maxlen=300); _it = int(os.environ['INSTRACE']) + def _ih(uc, a, sz, ud): + if state['ms'] >= _it: TI.append((a, uc.reg_read(UC_ARM_REG_SP), uc.reg_read(UC_ARM_REG_LR))) + u.hook_add(UC_HOOK_CODE, _ih) + atexit.register(lambda: print('\n'.join('I %x sp %x lr %x' % t for t in TI))) +if os.environ.get('PWLOG'): # writes into the PRAM from elsewhere than the copy loop + _jcc = syms.get('J_cpcode', 0) & ~1 + def _pwl(uc, acc, a, sz, v, ud): + p = uc.reg_read(UC_ARM_REG_PC) + if not (_jcc <= p < _jcc + 24): print('PRAM write %x = %x size %d by pc %x at ms %d' % (a, v, sz, p, state['ms'])) + u.hook_add(UC_HOOK_MEM_WRITE, _pwl, begin=0, end=0xFFFF) +if os.environ.get('BLKTRACE'): + import collections + TR = collections.deque(maxlen=int(os.environ['BLKTRACE'])) + u.hook_add(UC_HOOK_BLOCK, lambda uc, a, sz, ud: TR.append((a, sz))) + import atexit; atexit.register(lambda: print('last blocks', ' '.join('%x/%d' % t for t in TR))) + atexit.register(lambda: open(os.path.join(out, 'pram.bin'), 'wb').write(bytes(u.mem_read(0, 0x10000)))) + atexit.register(lambda: open(os.path.join(out, 'sram.bin'), 'wb').write(bytes(u.mem_read(0x18000000, 0x20000)))) + atexit.register(lambda: print('regs', ' '.join('%x' % u.reg_read(r) for r in [UC_ARM_REG_R0 + i for i in range(13)] + [UC_ARM_REG_SP, UC_ARM_REG_LR]))) +# AHB prescaler (CLK_ECO) and the clock source (PW): RT >> sh instructions per ms +state['sh'] = 0; state['shms'] = [0, 0, 0, 0] +def _ahb(uc, acc, a, sz, v, ud): state['sh'] = v & 7 +u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013) +u.mem_write(0x4500000C, struct.pack('= total_ms or any(t / 1000.0 >= kt > state['ms'] / 1000.0 for kt, _ in KS): break + state['dsleep'] = t + if t % 1000 == 0 and 'g_pw_rtcw' in syms: uc.mem_write(syms['g_pw_rtcw'], b'\x01') + uc.mem_write(0x45000304, struct.pack('> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3)) + im.save(os.path.join(out, name)) +def st(i): return struct.unpack('> _sh); ch = max(1, n // NCH) + err = 0; k = 0 + while k < NCH and not state['waited'] and 'back' not in state and not state.get('dsleep'): + if state['pw_dirty']: + _a, _n = state["pw_dirty"]; (u.ctl_flush_tb() if os.environ.get("FULLFLUSH") else u.ctl_remove_cache(_a & ~1, _a + _n + 2)); state['pw_dirty'] = 0; state['jcopies'] = state.get('jcopies', 0) + 1 + try: u.emu_start(pc | 1, 0xFFFFFFF0, count=ch) + except UcError as ex: + print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); err = 1; break + pc = u.reg_read(UC_ARM_REG_PC) + if PROF is not None and not state['waited'] and (not PROFFROM or state['ms'] >= PROFFROM): PROF[pc] = PROF.get(pc, 0) + 1 + if not state['pw_dirty']: k += 1 + if err: break + state['shms'][min(_sh, 3)] += 1; state['pw']['ihrc' if state['ihrc'] else 'full'] += 1 + state['busy'] += k; state['busyn'] += 1 + if state['waited']: pc = (pc + 2) & ~1 # past the wfi: the tick comes + _ds = state.pop('dsleep', 0) + if _ds: + n = _ds - state['ms']; state['ms'] = _ds; state['pw']['sleep'] += n + u.mem_write(0x45000304, struct.pack('= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1 + if CL and state['ms'] % CL == 0: + _io = bytes(u.mem_read(syms['g_emu'] + IOOFF + 0x1910, 0x10)); b = lambda x: (x >> 4) * 10 + (x & 15) + print('clock', state['ms'], 'guest %02d:%02d:%02d' % (b(_io[8]), b(_io[4]), b(_io[0])), flush=True) + if LL and state['ms'] % LL == 0: + cur = (st(9), st(10)); p0 = llp or cur + print('lag', state['ms'], cur[0] - p0[0], cur[1] - p0[1], 'pw', dict(state['pw']), flush=True); llp = cur +print('emulated ms', st(9), 'dropped ms', st(10), 'busy loop ms', st(12), 'guest pc %x' % st(6), 'mclk', st(4)) +print('ms', state['ms'], 'tones', len(state['tone']), 'flash writes', state['flashw'], 'back' if 'back' in state else '', 'pc', hex(pc)) +print('ms per clock step (96, 48, 24, 12 MHz):', state['shms']) +print('power ms: full', state['pw']['full'], 'ihrc', state['pw']['ihrc'], 'deep sleep', state['pw']['sleep']) +print('backlight', state['bl'][-6:], 'light %', state['blpct'][-4:]) +print('translator copies', state.get('jcopies', 0), ' '.join('%s %d' % (n, struct.unpack('= 0 else '?' + if a >= syms.get('__initcode_start', 0x10000) and a < 0x10000: nm = 'JIT code' + if a >= 0x18000000: nm = 'SRAM code' + agg[nm] = agg.get(nm, 0) + n + tot = sum(agg.values()) + if os.environ.get('PROFPC'): print('top pcs', ' '.join('%x:%d' % kv for kv in sorted(PROF.items(), key=lambda kv: -kv[1])[:12])) + print('profile (%d samples):' % tot, ', '.join('%s %.1f%%' % (k, 100.0 * v / tot) for k, v in sorted(agg.items(), key=lambda kv: -kv[1])[:16])) +open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl) +shot('shot_end.png') diff --git a/emu/test/keys.py b/emu/test/keys.py new file mode 100644 index 0000000..f88cc70 --- /dev/null +++ b/emu/test/keys.py @@ -0,0 +1,15 @@ +# keys.py "5:B 1.5:B*10 5:A 1:B 360: 0:W2000" -> KEYS for devemu.py: each item :[*n], key A B C W (wheel), +# W holds the wheel that long; a press lasts 150 ms. Prints KEYS and the total seconds. +import sys +M = {'A': 1, 'B': 2, 'C': 4, 'W': 8} +t = 0.0; out = [] +for it in sys.argv[1].split(): + w, k = it.split(':'); n = 1 + if '*' in k: k, n = k.split('*'); n = int(n) + for _ in range(n): + t += float(w) + if not k: continue + hold = 0.15 + if len(k) > 1: hold = int(k[1:]) / 1000.0 + out.append('%.3f:%d' % (t, M[k[0]])); out.append('%.3f:0' % (t + hold)); t += hold +print(','.join(out)); print(int(t * 1000) + 3000, file=sys.stderr) diff --git a/emu/test/mkimg.js b/emu/test/mkimg.js new file mode 100644 index 0000000..696182d --- /dev/null +++ b/emu/test/mkimg.js @@ -0,0 +1,9 @@ +// node mkimg.js [lang en|de] +// The Paradise image with TamaEmu as the main program (as the Studio builds it), for devemu.py +const fs = require('fs'); +const E = require('../../src/emu.js'); +const rd = (p) => new Uint8Array(fs.readFileSync(p)); +const [rom, fw, app, out, lang] = process.argv.slice(2); +const r = E.emuPatch(rd(rom), rd(fw), rd(app), rd(__dirname + '/../stub_tpl.bin'), { lang: lang || 'de' }); +fs.writeFileSync(out, r.rom); +console.log('device', r.device, 'blocks', r.blocks, 'big', r.big); diff --git a/emu/test/upg.js b/emu/test/upg.js new file mode 100644 index 0000000..f7e4d4d --- /dev/null +++ b/emu/test/upg.js @@ -0,0 +1,6 @@ +// node upg.js : the program replaced as the Studio does (emuUpgrade), session kept +const fs = require('fs'); +const E = require('../../src/emu.js'); +const [img, app, out] = process.argv.slice(2); +const r = E.emuUpgrade(new Uint8Array(fs.readFileSync(img)), new Uint8Array(fs.readFileSync(app))); +fs.writeFileSync(out, r || fs.readFileSync(img)); console.log(r ? 'upgraded' : 'same'); diff --git a/feld/README.md b/feld/README.md new file mode 100644 index 0000000..eb7747a --- /dev/null +++ b/feld/README.md @@ -0,0 +1,114 @@ +# Paramix menu (field switch, items, Tamapoints, Tama) + +A small program for the Paradise, started by the launcher (A+C held on the home +screen). Texts on the device are English, the font and graphics are our own. + +- `feld.bin`: the menu program, runs from PRAM. +- `feldc.bin` (1.7.2): the same with `FELD_CLEAN`, only for ROMs without the Paradise (own clock, settings version 10). +- `stub_feld_tpl.bin`: the launcher with menu support and placeholders. +- `src/feld`: source of the menu, `src/stub/stub.S`: source of the launcher. + +## What it does + +- **Field switch:** the save of the active field is packed (LZSS per 4 KB page) + into its own slot, the save of the chosen field is restored (or the factory + settings pages 0xEFE000/0xEFF000 are written for a fresh field), then the + device restarts. The settings pages are written last, so an interrupted switch + is detected and the menu offers to restore the old save. +- The active field lives in the settings block (byte 439 on Land/Water/Sky, 443 + on Jade Forest, 499 on Tropical/Glacier), not in the ID page. Every edition has + three fields; their names are texts 14 to 16 in the ROM. +- **Saves (1.6.8, flag 8, default):** the slots hold saves, not fields. The menu lists SAVE 1 to n + (n = number of fields) with field and Tama; the number of the live save is in the settings block + (0xF06, number + 1). An empty save starts a new game on a field the user picks. A Tama that moves + to another field in the game stays the same save. Without flag 8 the menu works per field as before. + A switch marks the header of the stored save with "PEND" (res[2]) until it is complete; only then + does the menu offer to restore after an interruption. +- **Tama:** planet level, full care (hunger 6, happiness 20, not sick) and a new character (kid, + young or adult of the ROM's character table). The character goes into the settings block and + into the pet's own file (pages of the save with the old character in their header). +- **Items and Tamapoints:** edits the settings block 0xEFE000 (copy at 0xEFF000) + and its CRC-16/ARC. The item catalog is built by the Studio from the user's + own ROM (28 bytes per entry); pictures are drawn straight from the ROM's image + table. + +Settings block of the program (372 bytes at program + 0x140, version 4): slots, +ID page (footer, constant), fields (ID, name, colour), factory settings per +edition and field, positions of money, item list, counts, catalog. Version 4 +adds fields 5 and 6, the set byte of six fields (see `six/README.md`) and a +second slot region. Version 5 (1.6.0, 492 bytes) adds the name of the launcher's +own program (380, 12 bytes), the number of further programs (392) and up to six +entries (396, 16 bytes each: XIP address of the 64 KB program image, name). +The menu starts them through the launcher entry at +0x0C (r0 = image). Version 6 (1.6.8, 500 bytes) +adds the TAMA menu (flag 4): offset of the pet (492) and of the planet level (496) in the settings +block; the characters come with the catalog (fixed byte 2, +6 stage, +7 field index + 1). The Studio fills it in (`src/feld.js`, profiles gen1, +jade, gen3). + +**Start device (1.6.8, flag 16):** the Studio's "start device only" switch. The menu is the home screen: +it lists the programs and, as the last entry, DOWNLOAD (the Studio's flash app as its own 64 KB image, +settings version 7 at offset 500), so the PC can write the ROM again without the Paradise's own download +screen. C does nothing at the top; after two minutes without a key the display goes dark until the next +key. The Studio shrinks every picture of the game that the setup does not need (`launcherChanges` in +`src/core.js`). The handlers of the game's scenes (home, care, events, lab, shop, space) go through +trampolines behind the menu program: "ldr.w r12, original; b.w launcher + 0x2C". The launcher starts the +menu once the Paradise has a save (settings block 0xEFE000 stamped, year and month set), otherwise it +runs the original handler, so a setup after "reset" finishes in the Paradise itself. Measured in the +Paradise emulator: the four handlers 8 bytes behind a scene's name belong to the next scene of the table. +The launcher page holds at +0x400 "PLNC", the count and the offset of the trampoline pages (52 bytes per +scene: table offset, four original handlers, four trampolines); removing the menu restores the handlers. +Further programs may then also be TamaEmu (a colour Tama firmware) and T18Emu (one only), see `src/emu.js` +(`appsPlace`). With DOOM, DOOM is the program at 0x0A0000 and the emulators are further programs. +An entry SETTINGS (before DOWNLOAD, build switch `NO_LSET` removes it) changes the Paradise's sound level +(settings block byte 8, bits 3..4: 0 off .. 3 loud, found with the firmware's own sound screen) and the +display time of the menu (settings block byte 0xF07: 0 = 2 minutes, else index + 1 of 30 s, 1, 2, 5 min, +never). Both are written to 0xEFE000 and 0xEFF000 with the stamp. Programs that fit go behind the +Paradise's save (0xF00000..0xFFFFFF, never written by the Paradise) when there is no T18Emu. + +Main program of the start device (1.6.9 test13, settings version 9, switch `FELD_AUTO`): DOOM must stay at +0x0A0000, so the main program can also be one of the list. `main_src` (offset 600) names it: the menu shows it +first. `vflags` bit 0 (offset 604): start it when switched on instead of showing the menu, once per switching on, +with the stub's mailbox at 0x20000FFC ("PMXL" a program went back, "PMXM" the menu decided, "PMXR" restart while it +ran, else the seconds counter at 0x45000304 below 30 means switched on). B held while switching on: the menu. +Host test: `AUTO_CNT=5 AUTO_MB=... AUTO_GPIO=... ./menu_host ...` (build with `-DFELD_AUTO`). + +Location: launcher 0x0B0000, program and catalog from 0x0B1000, slots behind the +character data. Tropical and Glacier still have firmware code there, so launcher +and program move to the first free page (0x0B6000). With DOOM, program, catalog +and slots use the free end of the DOOM program area. With six fields the six +slots lie behind the menu (up to 0x10F000, where the helper page starts) and +behind the character data. + +Clean ROM, clock not asked (1.7.3 test7, switch `FELD_NOCLK`): `vflags` bit 1 set by the Studio ("Set the clock at the +start" off): a missing clock is not asked for when switched on (nor before the autostart); it is set under SETTINGS. + +## Clock for the programs (PARA_FLASH, 1.6.9 test37) + +At its start the menu looks the Paradise's time up in the SRAM (`para_clock`) and puts it in the mailbox 0x20000FC0 +for the programs. When the SRAM has no clock and the mailbox is empty, it takes the base of the Paradise's clock +from the settings page 0xEFE000 (copy 0xEFF000): days since 2025-01-01 at +0x0C, seconds at +0x10, plus the seconds +counter 0x45000304 (`para_flash` in `emu/src/emu/paraclock.h`; page CRC and date fields at +0x1C are checked). + +## Build + +``` +sh src/feld/build.sh # clang, ld.lld, llvm-objcopy -> src/feld/feld.bin and feldc.bin (copy them to feld/) +``` + +Launcher template: as in `emu/README.md`, plus `-DFELD=1 -DFELD_SRC=0x6789EF01`. +Without `-DFELD` the same source gives `emu/stub_tpl.bin`. + +PC test without a device: + +``` +cd src/feld && cc -DHOST -DFELD_AUTO -w -I. host.c main.c -o menu_host +./menu_host "" # keys: n p a b c +``` + +License: GNU GPL version 3 or later. + +Autostart after a reset (clean ROM, 1.7.3 test9, switches FELD_SEEN, FELD_BSETTLE, FELD_AUTODBG): on the device the +mailbox still held "PMXL" at a reset after a program had gone back and the menu was shown, so the reset showed the menu +again. The menu now writes "PMXS" into 0x20000FF8 when it shows itself for a "PMXL" (the programs set that word to 0 +with every "PMXL"): a "PMXL" with "PMXS" (test12: with any word other than 0 there, e.g. the Paradise stub's counter) is an old one and the main program starts. B counts as held only over five +looks a few ms apart. AUTODBG (test builds): bottom middle of the home screen: mailbox (L M R 0 ?), GPIO0 bits 8..11, +B held or "-", seen mark (S 0 ?). diff --git a/feld/feld-ko.bin b/feld/feld-ko.bin new file mode 100644 index 0000000..4d42500 Binary files /dev/null and b/feld/feld-ko.bin differ diff --git a/feld/feld.bin b/feld/feld.bin new file mode 100644 index 0000000..fd6453a Binary files /dev/null and b/feld/feld.bin differ diff --git a/feld/feldc-ko.bin b/feld/feldc-ko.bin new file mode 100644 index 0000000..5b16aca Binary files /dev/null and b/feld/feldc-ko.bin differ diff --git a/feld/feldc.bin b/feld/feldc.bin new file mode 100644 index 0000000..5547ba1 Binary files /dev/null and b/feld/feldc.bin differ diff --git a/feld/src/feld/build-ko.sh b/feld/src/feld/build-ko.sh new file mode 100644 index 0000000..3935527 --- /dev/null +++ b/feld/src/feld/build-ko.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Build the Paramix field switch (feld.bin, runs from PRAM 0) +set -e +cd "$(dirname "$0")" +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -flto -ffreestanding -nostdlib -Oz -fno-common -Wall -Wno-initializer-overrides -Wno-unused-const-variable -fno-builtin-memset -DTONE_FIX -DBL_BLACK -DBL_OFFFIX -DBL_SLEEP -DFAST_LCD -DLCD_FASTCLK -DCLEAN -DPARA_BACK -DPARA_MB_KEEP -DPARA_FLASH -DPARA_FLASH_LATE -DFELD_AUTO -DFELD_BFALL -DFELD_BFALL_NOA -DCLEAN_AUTO -DBAT_SHOW -DBAG_DEL -DFELD_PW -DFELD_TAMA_ANY -DFELD_NOCLK -DFELD_BSETTLE -DFELD_SEEN $XCF" +O="" +for f in main-ko.c hw.c libc.c flash.c; do n=$(basename $f .c); OPT=; [ "$n" = main-ko ] && OPT=-Oz; clang $CF $OPT -c $f -o $n.o; O="$O $n.o"; done # 1.6.8: main with -Oz (menu code, size before speed) +N=${OUT:-feld-ko} +ld.lld -T link.ld --no-rosegment $O -o $N.elf +llvm-objcopy -O binary -j .text $N.elf $N.bin +python3 -c 'import pathlib,sys; p=pathlib.Path(sys.argv[1]); p.write_bytes(p.read_bytes()+b"ITOSM_KO_MENU_V1\x00")' "$N.bin" +llvm-size $N.elf; ls -l $N.bin +# 1.7.2 CLEAN_ROM: a second build for ROMs without the Paradise (own clock); the start device keeps the build above +if [ -z "$XCF" ]; then XCF=-DFELD_CLEAN OUT=feldc-ko sh ./build-ko.sh --inner; fi diff --git a/feld/src/feld/build.sh b/feld/src/feld/build.sh new file mode 100644 index 0000000..a682d6f --- /dev/null +++ b/feld/src/feld/build.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Build the Paramix field switch (feld.bin, runs from PRAM 0) +set -e +cd "$(dirname "$0")" +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -Os -fno-common -Wall -Wno-initializer-overrides -Wno-unused-const-variable -fno-builtin-memset -DTONE_FIX -DBL_BLACK -DBL_OFFFIX -DBL_SLEEP -DFAST_LCD -DLCD_FASTCLK -DCLEAN -DPARA_BACK -DPARA_MB_KEEP -DPARA_FLASH -DPARA_FLASH_LATE -DFELD_AUTO -DFELD_BFALL -DFELD_BFALL_NOA -DCLEAN_AUTO -DBAT_SHOW -DBAG_DEL -DFELD_PW -DFELD_TAMA_ANY -DFELD_NOCLK -DFELD_BSETTLE -DFELD_SEEN $XCF" +O="" +for f in main.c hw.c libc.c flash.c; do n=$(basename $f .c); OPT=; [ "$n" = main ] && OPT=-Oz; clang $CF $OPT -c $f -o $n.o; O="$O $n.o"; done # 1.6.8: main with -Oz (menu code, size before speed) +N=${OUT:-feld} +ld.lld -T link.ld --no-rosegment $O -o $N.elf +llvm-objcopy -O binary -j .text $N.elf $N.bin +llvm-size $N.elf; ls -l $N.bin +# 1.7.2 CLEAN_ROM: a second build for ROMs without the Paradise (own clock); the start device keeps the build above +if [ -z "$XCF" ]; then XCF=-DFELD_CLEAN OUT=feldc sh "$0" --inner; fi diff --git a/feld/src/feld/disp_power.h b/feld/src/feld/disp_power.h new file mode 100644 index 0000000..61f629d --- /dev/null +++ b/feld/src/feld/disp_power.h @@ -0,0 +1,5 @@ +// Captured from the REAL Flash Utility (same PRAM/post-reset context as +// our app). Order kept word for word. clk tail (reset release) first, +// then display/GPIO/backlight registers. +__attribute__((section(".initdata"))) static const unsigned int disp_power_seq[][2]={{0x45000020,0x40},{0x45000210,0x0},{0x45000214,0x0},{0x45000218,0x0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000020,0x42},{0x4003a000,0x8000},{0x4003a004,0x8000},{0x4003a004,0x8001},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40007034,0x0},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x4001803c,0xffffffff},{0x4001903c,0xfffff5df},{0x4001a03c,0xffffffff},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a56},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a59},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a65},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a95},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a55},{0x40018004,0x20},{0x40018000,0xffffffef},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xffffffef},{0x40018008,0x15008855},{0x40018004,0x10},{0x40018000,0xffffffcf},{0x40018008,0x15008855},{0x40018004,0x30},{0x40018000,0xffffffcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15028055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15088055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15208055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15808055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x16008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x19008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x25008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x15008055},{0x40019004,0xa00},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55996800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55999800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x559a5800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x55995800},{0x40019004,0x820},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800},{0x40019004,0x220},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x56995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x59995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x65995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x95995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x55995800},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x52},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x58},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x60},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x90},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x50},{0x40003000,0x0},{0x40003018,0x0},{0x4000301c,0x0},{0x40003020,0x0},{0x40003024,0x0},{0x40003014,0x0},{0x40003000,0x2},{0x40003008,0x0},{0x4000303c,0x1f},{0x40003000,0x1},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800}}; +#define DISP_POWER_N 262 diff --git a/feld/src/feld/flash.c b/feld/src/feld/flash.c new file mode 100644 index 0000000..bd19854 --- /dev/null +++ b/feld/src/feld/flash.c @@ -0,0 +1,90 @@ +/* Write the Paradise flash: erase and program a sector, exactly like the + * mameise flash app (confirmed on the device). Runs from PRAM; nothing may be + * read from the XIP window while writing. */ +#include "io.h" +#include "flash.h" +#define F_DMEM REG(FCTL+0x100) +#define F_DLEN REG(FCTL+0x104) +#define F_DCTL REG(FCTL+0x108) +#define F_DFLA REG(FCTL+0x10C) + +static void feed(void){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } +static void wait_loop(u32 n){ for(volatile u32 i=0;i>1; + u32 hi=(a1>>16)&0xFFFFu; + u32 lo=a1 & 0xFFFFu; + REG(FCTL+0x008)=hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + for(u32 g=0; (REG(FCTL+0x004)&0x400u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + for(u32 g=0; (REG(FCTL+0x004)&0x2u) && g<60000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); +} + +void flash_prog4k(u32 addr, const void *src) +{ + u32 a1=addr>>1; + u32 hi=(a1>>16)&0xFFFFu; + u32 lo=a1 & 0xFFFFu; + flash_erase4k(addr); + /* program */ + REG(FCTL+0x008)=0x3000u | hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; + REG(FCTL+0x000)=0x0000d080u; + REG(FCTL+0x020)=0; + REG(FCTL+0x010)=0; + REG(FCTL+0x000)=0x0000d082u; + F_DFLA=0x60000000u | (addr & 0x00FFFFFFu); + F_DLEN=0x1000u; F_DMEM=(u32)src; + F_DCTL=0u; + F_DCTL=1u; + for(u32 g=0; (F_DCTL & 1u) && g<20000000u; g++){ if((g & 0xFFFFu)==0) feed(); } + wait_ready(); +} + +void flash_read(u32 addr, void *dst, u32 len) +{ + const volatile u8 *s=(const volatile u8*)(0x60000000u + (addr & 0x00FFFFFFu)); + u8 *d=(u8*)dst; + for(u32 i=0;i':[".#...","..#..","...#.","....#","...#.","..#..",".#..."], +'<':["...#.","..#..",".#...","#....",".#...","..#..","...#."], +'+':[".....","..#..","..#..","#####","..#..","..#..","....."], +'&':[".##..","#..#.","#.#..",".#...","#.#.#","#..#.",".##.#"], +"'":["..#..","..#..",".#...",".....",".....",".....","....."], +'x':[".....",".....","#...#",".#.#.","..#..",".#.#.","#...#"], +',':[".....",".....",".....",".....",".##..","..#..",".#..."], +'(':["...#.","..#..",".#...",".#...",".#...","..#..","...#."], +')':[".#...","..#..","...#.","...#.","...#.","..#..",".#..."], +'\x01':["#...#",".###.","#...#","#####","#...#","#...#","#...#"], # A umlaut +'\x02':["#...#",".###.","#...#","#...#","#...#","#...#",".###."], # O umlaut +'\x03':["#...#",".....","#...#","#...#","#...#","#...#",".###."], # U umlaut +} +lo=0;hi=127 +out=['/* generated by gen/font.py: custom 5x7 font */','static const unsigned char g_font[96][7]={'] +codes={} +for c,rows in G.items(): + k=ord(c) + codes[k]=[sum((1<<(4-i)) for i,ch in enumerate(r) if ch=='#') for r in rows] +def idx(k): + return k-32 if k>=32 else 92+k # \x01..\x03 -> 93..95 +tab=[[0]*7 for _ in range(96)] +for k,v in codes.items(): tab[idx(k)]=v +for i,v in enumerate(tab): out.append(' {%s},'%(','.join('0x%02x'%x for x in v))) +out.append('};') +open('font.h','w').write('\n'.join(out)+'\n') diff --git a/feld/src/feld/host.c b/feld/src/feld/host.c new file mode 100644 index 0000000..85ee13d --- /dev/null +++ b/feld/src/feld/host.c @@ -0,0 +1,45 @@ +/* PC test of the Paramix menu: cc -DHOST host.c main.c -o menu_host + * menu_host "" + * Sequence: n (wheel forward), p (wheel back), a, b, c. One PPM image after each screen update. */ +#include +#include +#include +#include +typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; +unsigned char *host_flash; +static const char *g_seq; static int g_pos; static const char *g_dir; static int g_frame; static const char *g_out; +static jmp_buf g_jb; +void hw_init(void){} +void hw_wdt_feed(void){} +u32 hw_buttons(void){ return 0; } +void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1){ + (void)stride;(void)x0;(void)y0;(void)x1;(void)y1; + char p[512]; snprintf(p,sizeof p,"%s/%03d.ppm",g_dir,g_frame++); + FILE *f=fopen(p,"wb"); fprintf(f,"P6 128 128 255\n"); + for(int i=0;i<128*128;i++){ u16 c=fb[i]; u8 r=(u8)((c>>11)<<3), g=(u8)(((c>>5)&63)<<2), b=(u8)((c&31)<<3); fputc(r,f); fputc(g,f); fputc(b,f); } + fclose(f); +} +void hw_back_to_paradise(void){ printf("BACK TO PARADISE\n"); longjmp(g_jb,1); } +void host_exit(const char *why){ printf("ENDE %s\n",why); longjmp(g_jb,1); } +void hw_tone(u32 hz){(void)hz;} void hw_backlight(int on){(void)on;} void hw_bl_pwm_off(void){} +void flash_prog4k(u32 addr, const void *src){ memcpy(host_flash+(addr&0xFFFFFF),src,0x1000); } +void flash_erase4k(u32 addr){ memset(host_flash+(addr&0xFFFFFF),0xFF,0x1000); } +void flash_read(u32 addr, void *dst, u32 len){ memcpy(dst,host_flash+(addr&0xFFFFFF),len); } +int flash_same(u32 addr, const void *src, u32 len){ return !memcmp(host_flash+(addr&0xFFFFFF),src,len); } +int flash_update4k(u32 addr, const void *src){ if(flash_same(addr,src,0x1000)) return 0; flash_prog4k(addr,src); return 1; } +int host_input(int *step){ + for(;;){ + char c=g_seq[g_pos]; if(!c){ printf("FOLGE ZU ENDE\n"); longjmp(g_jb,1); } + g_pos++; + switch(c){ case 'n': *step=1; return 1; case 'p': *step=-1; return 1; case 'a': return 10; case 'b': return 2; case 'c': return 3; default: break; } + } +} +void host_main(void); +int main(int argc,char**argv){ + if(argc<5){ fprintf(stderr,"menu_host in out dir folge\n"); return 1; } + host_flash=malloc(0x1000000); FILE *f=fopen(argv[1],"rb"); fread(host_flash,1,0x1000000,f); fclose(f); + g_out=argv[2]; g_dir=argv[3]; g_seq=argv[4]; + if(!setjmp(g_jb)) host_main(); + f=fopen(g_out,"wb"); fwrite(host_flash,1,0x1000000,f); fclose(f); + printf("%d Bilder\n",g_frame); return 0; +} diff --git a/feld/src/feld/host.h b/feld/src/feld/host.h new file mode 100644 index 0000000..a21d51b --- /dev/null +++ b/feld/src/feld/host.h @@ -0,0 +1,5 @@ +/* Only for the PC test (host.c): flash as a memory array, input from a sequence. */ +extern unsigned char *host_flash; +#define FLASH_BASE ((volatile u8*)host_flash) +int host_input(int *step); +void host_exit(const char *why); diff --git a/feld/src/feld/hw.c b/feld/src/feld/hw.c new file mode 100644 index 0000000..25077ea --- /dev/null +++ b/feld/src/feld/hw.c @@ -0,0 +1,303 @@ +/* Paradise hardware (SNC73410), taken from the mameise flash app + * (display confirmed on the device). Runs from PRAM 0 after SYSRESETREQ. */ +#include "io.h" +#include "hw.h" +#include "disp_power.h" +#define PANEL 0x4000E000u +#define FCTL_ 0x40022000u +#define F_STAT REG(FCTL_+0x000) +static void udelay(volatile u32 n){ while(n--) __asm__ volatile("nop"); } +#define MS(x) udelay((u32)(x)*16000u) +#define BB(reg,bit) (*(volatile u32*)(0x42000000u + (((u32)(reg)-0x40000000u)<<5) + ((u32)(bit)<<2))) +#define GPIO0 0x40018000u +#define GPIO1 0x40019000u +#define GPIO2 0x4001A000u +#define LCD_RST(v) (BB(GPIO0+0x00,4)=(v)) +#define LCD_DC(v) (BB(GPIO0+0x00,5)=(v)) +#define SPI_CTRL REG(PANEL+0x00) +#define SPI_STAT REG(PANEL+0x0C) +#define SPI_DATA REG(PANEL+0x1C) +#define SPIWAIT 200000u +#define CT2 0x40002000u +TC_INIT static void clock_init(void){ + REG(CLK+0x00) |= 1u; + REG(CLK+0x0C) = 0; + REG(CLK+0x00) = 0x41u; + { u32 r = (REG(CLK+0x34) & 0xF00u) | 0xA55A0000u; REG(CLK+0x04) = r; } + REG(CLK+0x18) = 0x21u; + REG(CLK+0x50) = 0; + REG(CLK+0x10C) = 0x001FFFFDu; + REG(CLK+0x110) = 0; + REG(CLK+0x108) = 0; + REG(CLK+0x10) = 0; + REG(CLK+0x00) |= 0x10u; + for(u32 g=0; !((REG(CLK+0x08) >> 4) & 1u) && g<4000000u; g++){} + REG(CLK+0x00) |= 0x4000u; + REG(CLK+0x04) &= ~1u; + REG(CLK+0x00) |= 0x8000u; + for(u32 g=0; !((REG(CLK+0x08) >> 6) & 1u) && g<4000000u; g++){} + { u32 r = (REG(CLK+0x0C) & ~7u) | 4u; REG(CLK+0x0C) = r; } + for(u32 g=0; ((REG(CLK+0x0C) >> 4) & 7u) != (REG(CLK+0x0C) & 7u) && g<4000000u; g++){} /* bounded: never hang forever */ + REG(CLK+0x100) = 0x00157EB7u; +} +TC_INIT static void flashctl_init(void){ + /* 1.4.2: enable XIP. We read through the 0x60000000 window that the XIP block + * maps in. Without XIP that window only shows the config register (0x40), not + * the flash data. The real Flash Utility does this at startup, our app did not + * do it after reset until now. That is exactly what was missing. */ + REG(0x4002F004u)=0x60011000u; + REG(0x4002F000u)=0x00000003u; + /* 1.4.1: controller init word for word like the real Flash Utility (0x40022000). + * This includes setting the read command/mode in 0x008 and 0x00c (0x3077 / 0xf000), + * otherwise the chip only returns its config register (0x40) instead of flash data. */ + F_STAT=0x0000d018u; + F_STAT=0x0000d000u; + F_STAT=0x0000d080u; + F_STAT=0x0000d088u; + REG(FCTL+0x008)=0x00003077u; /* read command/mode */ + REG(FCTL+0x00C)=0x0000f000u; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; +} +TC_INIT static void wdt_off(void){ + /* Set up the system/power block EXACTLY like the real Flash Utility. The only + point where we deliberately differed before (bit0 of 0x40008000) might be the + master enable for the display domain. The FU runs with bit0=1 without a + reset, so we copy it 1:1 and feed the watchdog in the loop. */ + REG(0x4000900Cu)=0x5AFA55AAu; REG(0x40009000u)=0x5AFA0000u; /* WDT1 */ + REG(0x40008000u)=0x5AFA0000u; /* unlock */ + REG(0x40008004u)=0x5AFA0002u; + REG(0x40008008u)=0x5AFA00FFu; /* power/clock domains on (incl. display) */ + REG(0x4000800Cu)=0x5AFA55AAu; /* feed the watchdog */ + /* Do NOT set bit0 (watchdog enable): otherwise it resets the Tama during + display init (back to the planet). */ +} +TC_INIT static void mailbox_clear(void){ + REG(0x20000000u)=0; REG(0x20000004u)=0; REG(0x20000008u)=0; REG(0x2000000Cu)=0; +} +TC_INIT static void periph_enable(void){ REG(CLK+0x20)=0x40u; } +TC_INIT static void pin_set(u8 id, u8 mode){ *(volatile u8*)(0xE000E400u + id) = (u8)(mode<<4); } +TC_INIT static void pin_mux(void){ + static const u8 m12[]={6,7,8,9,0xf,0x10,0x11,0x12,0x13,0x14,0x19,0x1f,0x20,0x22, + 0x24,0x25,0x2e,0x2f,0x35,0x36,0x1a,0x1b,0x1c,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x3a,0x3f}; + static const u8 m8[]={0,1,2,3}; + static const u8 m4[]={0x15,0x17}; + for(unsigned i=0;i=0x45000210u && a<=0x45000218u) v=REG(0x4001803Cu + ((a-0x45000210u)>>2)*0x1000u); + REG(a)=v; + } + /* Make sure the panel pins are outputs: reset, D/C, CS (P1.5 low), supply (P1.9 low) */ + LCD_RST(1); BB(GPIO0+0x04,4)=1; + LCD_DC(0); BB(GPIO0+0x04,5)=1; + BB(GPIO1+0x00,5)=0; BB(GPIO1+0x04,5)=1; + BB(GPIO1+0x00,9)=0; BB(GPIO1+0x04,9)=1; + MS(20); +} +TC_INIT static void spi_init(void){ + /* like FU 0x3f44, as read-modify-write */ +#ifdef LCD_FASTCLK + REG(PANEL+0x08)=0; /* clock divider: test in v0.8.18, twice as fast? */ +#else + REG(PANEL+0x08)=1; /* clock divider */ +#endif + SPI_CTRL &= ~(1u<<18); + REG(PANEL+0x04) &= ~6u; REG(PANEL+0x04) &= ~1u; + SPI_CTRL &= ~0x10u; SPI_CTRL &= ~0x08u; + REG(PANEL+0x20)=0; + SPI_CTRL = (SPI_CTRL & ~0xF00u) | 0x700u; /* 8 bit */ + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFF0000u; + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFFu; + SPI_CTRL |= 1u; /* SPI on */ + SPI_CTRL |= 0xC0u; /* flush FIFOs */ +} +static void spi_tx(const u8* p, u32 n){ + for(u32 i=0;i>8),(u8)r[x]}; + spi_tx(&two[0],1); spi_tx(&two[1],1); /* byte by byte like the FU (1.3.8) */ + } + } + LCD_DC(0); +} + +#ifdef FAST_LCD +/* v0.8.17: pixel output in one go per rectangle, 16 bytes per SPI pass (like the gamma tables + * in display init, which work this way on the device). Before, per byte: wait, pause of 8, wait. */ +void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1){ + u8 ca[4]={0x00,(u8)(x0+2),0x00,(u8)(x1+1)}; + u8 ra[4]={0x00,(u8)(y0+1),0x00,(u8)(y1)}; + lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4); + LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); } + LCD_DC(1); +} +void hw_px_row(const u16* r, u32 n){ + u8 b[16]; u32 k=0; + for(u32 i=0;i>8); b[k++]=(u8)r[i]; if(k==16u){ spi_tx(b,16); k=0; } } + if(k) spi_tx(b,k); +} +void hw_px_end(void){ LCD_DC(0); } +#endif + +/* Back to the Paradise: firmware routine that reloads the encrypted PRAM image + and restarts (flash 0x110568, XIP 0x100FF569). */ +void hw_back_to_paradise(void){ + __asm__ volatile("cpsid i"); + ((void(*)(void))(PARADISE_REBOOT|1u))(); + for(;;){} +} diff --git a/feld/src/feld/hw.h b/feld/src/feld/hw.h new file mode 100644 index 0000000..4d9da02 --- /dev/null +++ b/feld/src/feld/hw.h @@ -0,0 +1,24 @@ +#ifndef HW_H +#define HW_H +#include "io.h" +#define BTN_A 1u +#define BTN_B 2u +#define BTN_C 4u +#define BTN_WHEEL 8u +#ifndef PARADISE_REBOOT +#define PARADISE_REBOOT 0x100FF568u +#endif +void hw_init(void); +void hw_wdt_feed(void); +u32 hw_buttons(void); +void hw_push(const u16* fb, u32 stride, u32 x0, u32 y0, u32 x1, u32 y1); +void hw_back_to_paradise(void); +void hw_backlight(int on); +void hw_bl_pwm_off(void); +void hw_tone(u32 hz); /* 0 = off */ +#ifdef FAST_LCD +void hw_px_begin(u32 x0, u32 y0, u32 x1, u32 y1); +void hw_px_row(const u16* r, u32 n); +void hw_px_end(void); +#endif +#endif diff --git a/feld/src/feld/io.h b/feld/src/feld/io.h new file mode 100644 index 0000000..9f7e513 --- /dev/null +++ b/feld/src/feld/io.h @@ -0,0 +1,13 @@ +#ifndef IO_H +#define IO_H +typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; +#define REG(a) (*(volatile u32*)(a)) +#define UART 0x4000B000u +#define FCTL 0x40022000u +#define CLK 0x45000000u +static inline void dsb(void){ __asm__ volatile("dsb":::"memory"); } + +#ifndef TC_INIT +#define TC_INIT __attribute__((section(".initcode"), noinline)) +#endif +#endif diff --git a/feld/src/feld/ko-encoding.json b/feld/src/feld/ko-encoding.json new file mode 100644 index 0000000..0da7131 --- /dev/null +++ b/feld/src/feld/ko-encoding.json @@ -0,0 +1,326 @@ +{ + "chars": [ + "·", + "가", + "간", + "감", + "값", + "강", + "개", + "거", + "건", + "게", + "경", + "계", + "고", + "과", + "관", + "그", + "글", + "금", + "기", + "까", + "꺼", + "끄", + "끔", + "난", + "남", + "뉴", + "는", + "니", + "다", + "단", + "대", + "데", + "도", + "돌", + "동", + "되", + "됨", + "됩", + "뒤", + "드", + "득", + "때", + "랜", + "램", + "량", + "러", + "레", + "력", + "로", + "록", + "료", + "류", + "름", + "리", + "릭", + "마", + "메", + "면", + "목", + "미", + "방", + "배", + "벨", + "변", + "보", + "복", + "본", + "봄", + "부", + "분", + "불", + "비", + "사", + "삭", + "상", + "새", + "서", + "선", + "설", + "성", + "세", + "셔", + "소", + "손", + "수", + "숫", + "스", + "습", + "시", + "식", + "실", + "아", + "않", + "알", + "았", + "어", + "업", + "없", + "었", + "에", + "역", + "열", + "예", + "오", + "옵", + "완", + "요", + "용", + "운", + "워", + "원", + "유", + "으", + "을", + "음", + "의", + "이", + "인", + "읽", + "임", + "입", + "있", + "자", + "작", + "잠", + "장", + "재", + "저", + "적", + "전", + "정", + "제", + "조", + "존", + "중", + "지", + "짐", + "집", + "참", + "체", + "초", + "추", + "취", + "치", + "카", + "캐", + "컬", + "코", + "크", + "타", + "택", + "터", + "템", + "통", + "트", + "패", + "편", + "포", + "품", + "프", + "플", + "픔", + "피", + "하", + "한", + "할", + "함", + "합", + "행", + "현", + "형", + "화", + "확", + "환", + "회", + "후", + "휠" + ], + "translations": { + "SAVING": "저장 중", + "CHECKING": "확인 중", + "LOADING": "불러오는 중", + "ERROR": "오류", + "CODE 00": "코드 00", + "SAVE TOO BIG": "저장 용량 초과", + "B OR C: BACK": "B/C 돌아가기", + "C BACK": "C 뒤로", + "DONE": "완료", + "PROGRAM": "프로그램", + "SETTINGS": "설정", + "DOWNLOAD": "다운로드", + "PLEASE WAIT": "잠시 기다리세요", + "DO NOT SWITCH OFF": "전원을 유지하세요", + "SWITCH TO": "전환 대상", + "SAVED GAME": "보관한 저장을", + "FIELD STARTS": "이 지역에서", + "WILL BE LOADED": "불러옵니다", + "FROM SCRATCH": "새로 시작합니다", + "B = YES": "B 예", + "C = NO": "C 아니요", + "1 MIN": "1분", + "2 MIN": "2분", + "5 MIN": "5분", + "NEVER": "끄지 않음", + "CLOCK, DISPLAY": "시계·화면", + "SOUND, DISPLAY": "소리·화면", + "PROGRAMS": "프로그램", + "OPEN": "열기", + "START": "시작", + "PC FLASH": "PC 기록", + "B START": "B 시작", + "B OK C BACK": "B 확인 C 뒤로", + "FIELD": "지역", + "CHOOSE": "선택", + "ACTIVE": "사용 중", + "SAVED": "저장됨", + "NEW": "새로", + "SAVE DATA": "저장 데이터가", + "IS DAMAGED": "손상되었습니다", + "NOTHING CHANGED": "변경하지 않았습니다", + "NO SAVE YET": "저장 데이터 없음", + "PLAY A LITTLE": "조금 플레이한 뒤", + "AND TRY AGAIN": "다시 시도하세요", + "SAVE FORMAT": "저장 형식을", + "UNKNOWN": "알 수 없습니다", + "SET THE CLOCK": "시계 설정", + "WHEEL: CHANGE": "휠 변경", + "A: NEXT B: SAVE": "A 다음 B 저장", + "C: BACK": "C 뒤로", + "NOT SET": "미설정", + "CLOCK": "시계", + "DISPLAY": "화면", + "DISPLAY: DARK": "화면 꺼짐", + "WITHOUT A KEY": "입력이 없을 때", + "B CHANGE": "B 변경", + "C SAVE AND BACK": "C 저장 후 뒤로", + "OFF": "끔", + "LOW": "작게", + "MEDIUM": "보통", + "LOUD": "크게", + "SOUND": "소리", + "SOUND: THE PARADISE": "소리: 본편 적용", + "DISPLAY: THIS MENU,": "화면: 이 메뉴에서", + "DARK WITHOUT A KEY": "입력 없으면 꺼짐", + "NO PICS": "이미지 없음", + "FOOD": "식사", + "SNACKS": "간식", + "TOYS": "장난감", + "GOODS": "용품", + "OTHER": "기타", + "+ ADD ITEM": "+ 아이템 추가", + "REMOVE": "제거", + "WHEEL: COUNT": "휠 수량", + "NO ITEM LIST": "아이템 목록 없음", + "IN THIS ROM": "현재 ROM에", + "ADD: ": "추가: ", + "A NEXT GROUP C BACK": "A 분류 C 뒤로", + "BAG IS FULL": "가방이 가득 참", + "ITEMS": "아이템", + "B EDIT C BACK": "B 편집 C 뒤로", + "SAVE CHANGES?": "변경을 저장할까요?", + "THE TAMA RESTARTS": "본체가 재시작됩니다", + "ITEMS SAVED": "아이템 저장 완료", + "TAMAPOINTS": "다마포인트", + "WHEEL: DIGIT": "휠 숫자 변경", + "B NEXT A BACK": "B 다음 A 이전", + "C CANCEL": "C 취소", + "SET TAMAPOINTS TO": "포인트 설정값", + "TAMAPOINTS SAVED": "포인트 저장 완료", + "EGG": "알", + "BABY": "아기", + "KID": "유아기", + "YOUNG": "성장기", + "ADULT": "성체", + "NO CHARACTERS": "캐릭터 없음", + "TAMA: ": "다마: ", + "A STAGE B OK C BACK": "A 단계 B 확인 C 뒤로", + "YOUR TAMA BECOMES": "변경할 다마고치", + "TAMA NOT FOUND": "다마고치 없음", + "TAMA CHANGED": "다마고치 변경됨", + "PLANET LEVEL": "행성 레벨", + "WHEEL: LEVEL": "휠 레벨 변경", + "LEVEL SAVED": "레벨 저장 완료", + "FULL CARE:": "돌봄 회복", + "FED, HAPPY, HEALTHY": "배부름·행복·건강", + "TAMA CARED FOR": "돌봄 회복 완료", + "TAMA": "다마고치", + "LEVEL": "레벨", + "CHANGE": "변경", + "FOOD ": "배부름 ", + " JOY ": " 행복 ", + " SICK": " 아픔", + "CARE": "돌봄", + "START ON FIELD": "시작할 지역", + "SAVES": "저장 목록", + "SAVE ": "저장 ", + "EMPTY": "비어 있음", + "SAVE": "저장", + "UNREADABLE": "읽기 실패", + "LOAD": "불러오기", + "NEW GAME IN": "새 게임 지역", + "YOUR GAME IS KEPT": "기존 저장 유지", + " IN BAG": "개 보유", + "POINTS": "포인트", + "THE TAMA MOVED TO": "다마고치 이동 지역", + "IN THE GAME": "게임에서 이동함", + "AN OLDER SAVE OF": "이전 지역의", + "IS STILL STORED": "저장이 남아 있음", + "B = DELETE IT": "B 삭제", + "C = KEEP IT": "C 유지", + "SWITCH WAS": "전환 작업이", + "INTERRUPTED": "중단되었습니다", + "RESTORE SAVE OF": "저장을 복원할까요", + "NO PROGRAMS": "프로그램 없음" + }, + "fields": { + "LAND": "랜드", + "WATER": "워터", + "SKY": "스카이", + "FOREST": "포레스트", + "TROPICAL": "트로피컬", + "GLACIER": "글레이셔" + } +} \ No newline at end of file diff --git a/feld/src/feld/ko.tsv b/feld/src/feld/ko.tsv new file mode 100644 index 0000000..7cf2f71 --- /dev/null +++ b/feld/src/feld/ko.tsv @@ -0,0 +1,135 @@ +SAVING 저장 중 +CHECKING 확인 중 +LOADING 불러오는 중 +ERROR 오류 +CODE 00 코드 00 +SAVE TOO BIG 저장 용량 초과 +B OR C: BACK B/C 돌아가기 +C BACK C 뒤로 +DONE 완료 +PROGRAM 프로그램 +SETTINGS 설정 +DOWNLOAD 다운로드 +PLEASE WAIT 잠시 기다리세요 +DO NOT SWITCH OFF 전원을 유지하세요 +SWITCH TO 전환 대상 +SAVED GAME 보관한 저장을 +FIELD STARTS 이 지역에서 +WILL BE LOADED 불러옵니다 +FROM SCRATCH 새로 시작합니다 +B = YES B 예 +C = NO C 아니요 +1 MIN 1분 +2 MIN 2분 +5 MIN 5분 +NEVER 끄지 않음 +CLOCK, DISPLAY 시계·화면 +SOUND, DISPLAY 소리·화면 +PROGRAMS 프로그램 +OPEN 열기 +START 시작 +PC FLASH PC 기록 +B START B 시작 +B OK C BACK B 확인 C 뒤로 +FIELD 지역 +CHOOSE 선택 +ACTIVE 사용 중 +SAVED 저장됨 +NEW 새로 +SAVE DATA 저장 데이터가 +IS DAMAGED 손상되었습니다 +NOTHING CHANGED 변경하지 않았습니다 +NO SAVE YET 저장 데이터 없음 +PLAY A LITTLE 조금 플레이한 뒤 +AND TRY AGAIN 다시 시도하세요 +SAVE FORMAT 저장 형식을 +UNKNOWN 알 수 없습니다 +SET THE CLOCK 시계 설정 +WHEEL: CHANGE 휠 변경 +A: NEXT B: SAVE A 다음 B 저장 +C: BACK C 뒤로 +NOT SET 미설정 +CLOCK 시계 +DISPLAY 화면 +DISPLAY: DARK 화면 꺼짐 +WITHOUT A KEY 입력이 없을 때 +B CHANGE B 변경 +C SAVE AND BACK C 저장 후 뒤로 +OFF 끔 +LOW 작게 +MEDIUM 보통 +LOUD 크게 +SOUND 소리 +SOUND: THE PARADISE 소리: 본편 적용 +DISPLAY: THIS MENU, 화면: 이 메뉴에서 +DARK WITHOUT A KEY 입력 없으면 꺼짐 +NO PICS 이미지 없음 +FOOD 식사 +SNACKS 간식 +TOYS 장난감 +GOODS 용품 +OTHER 기타 ++ ADD ITEM + 아이템 추가 +REMOVE 제거 +WHEEL: COUNT 휠 수량 +NO ITEM LIST 아이템 목록 없음 +IN THIS ROM 현재 ROM에 +ADD: 추가: +A NEXT GROUP C BACK A 분류 C 뒤로 +BAG IS FULL 가방이 가득 참 +ITEMS 아이템 +B EDIT C BACK B 편집 C 뒤로 +SAVE CHANGES? 변경을 저장할까요? +THE TAMA RESTARTS 본체가 재시작됩니다 +ITEMS SAVED 아이템 저장 완료 +TAMAPOINTS 다마포인트 +WHEEL: DIGIT 휠 숫자 변경 +B NEXT A BACK B 다음 A 이전 +C CANCEL C 취소 +SET TAMAPOINTS TO 포인트 설정값 +TAMAPOINTS SAVED 포인트 저장 완료 +EGG 알 +BABY 아기 +KID 유아기 +YOUNG 성장기 +ADULT 성체 +NO CHARACTERS 캐릭터 없음 +TAMA: 다마: +A STAGE B OK C BACK A 단계 B 확인 C 뒤로 +YOUR TAMA BECOMES 변경할 다마고치 +TAMA NOT FOUND 다마고치 없음 +TAMA CHANGED 다마고치 변경됨 +PLANET LEVEL 행성 레벨 +WHEEL: LEVEL 휠 레벨 변경 +LEVEL SAVED 레벨 저장 완료 +FULL CARE: 돌봄 회복 +FED, HAPPY, HEALTHY 배부름·행복·건강 +TAMA CARED FOR 돌봄 회복 완료 +TAMA 다마고치 +LEVEL 레벨 +CHANGE 변경 +FOOD 배부름 + JOY 행복 + SICK 아픔 +CARE 돌봄 +START ON FIELD 시작할 지역 +SAVES 저장 목록 +SAVE 저장 +EMPTY 비어 있음 +SAVE 저장 +UNREADABLE 읽기 실패 +LOAD 불러오기 +NEW GAME IN 새 게임 지역 +YOUR GAME IS KEPT 기존 저장 유지 + IN BAG 개 보유 +POINTS 포인트 +THE TAMA MOVED TO 다마고치 이동 지역 +IN THE GAME 게임에서 이동함 +AN OLDER SAVE OF 이전 지역의 +IS STILL STORED 저장이 남아 있음 +B = DELETE IT B 삭제 +C = KEEP IT C 유지 +SWITCH WAS 전환 작업이 +INTERRUPTED 중단되었습니다 +RESTORE SAVE OF 저장을 복원할까요 +NO PROGRAMS 프로그램 없음 diff --git a/feld/src/feld/libc.c b/feld/src/feld/libc.c new file mode 100644 index 0000000..47ee19f --- /dev/null +++ b/feld/src/feld/libc.c @@ -0,0 +1,14 @@ +#include +void *memset(void *d, int c, size_t n){ unsigned char *p=d; while(n--) *p++=(unsigned char)c; return d; } +void *memcpy(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s; while(n--) *p++=*q++; return d; } +void *memmove(void *d, const void *s, size_t n){ unsigned char *p=d; const unsigned char *q=s; + if(p PRAM + .bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM + ASSERT(SIZEOF(.data) == 0, "no initialised data allowed") + .data : { *(.data*) } > SRAM + /DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/feld/src/feld/main-ko.c b/feld/src/feld/main-ko.c new file mode 100644 index 0000000..b5cc253 --- /dev/null +++ b/feld/src/feld/main-ko.c @@ -0,0 +1,1862 @@ +/* Paramix menu for the Paradise (field switch, items, Tamapoints, app launch). + * + * Started by the stub (A+C on the home screen), runs from PRAM. + * Everything that depends on the edition (ID page, fields, factory settings, + * location of bag and money, item catalog) lives in the settings block + * g_cfg and is filled in by the Studio when it installs the menu. The + * defaults here are for Land. + * + * Switching from field cur to field tgt: + * 1. Compress the save (all used pages from user_start on) into slot[cur] + * and verify it by reading it back. + * 2. Rewrite the save area: contents of slot[tgt], or, if the field has + * never run, the factory settings pages for tgt. + * 3. Set the ID page to tgt. + * 4. Free slot[tgt], restart. + * If power fails between 1 and 4, the old save is still in slot[cur] and the + * ID still points to cur: on the next start the program offers to restore it. + * + * Items and Tamapoints: the settings block 0xEFE000 (copy at 0xEFF000) holds + * money (u32), the item list (u16 per slot, ends at 0) and the counts + * (4 bits per slot). Protected by CRC-16/ARC over bytes 4 to 4096 (at 0, + * inverse at 2). Same as in the TamaParadise app: counts 1 to 15 only, new + * items go into the first free slot, nothing is deleted. */ +#include "io.h" +#include "hw.h" +#include "flash.h" +#include "font.h" +#include "font_ko.h" +#if !defined(HOST) || defined(FELD_CLEAN) +#include "../../../emu/src/emu/paraclock.h" +#endif +#ifndef HOST +#ifdef PARA_BACK +#include "../../../emu/src/emu/paraback.h" +#endif +#endif + +#define FELD_MAGIC 0x444C4546u /* "FELD" */ +#define SLOT_MAGIC 0x544C5346u /* "FSLT" */ +#define CAT_MAGIC 0x54414350u /* "PCAT" */ +#define PAGE 0x1000u +#define NPAGE_MAX 500u +#define SET_A 0xEFE000u +#define SET_B 0xEFF000u +#define F_FIELDS 1u +#define F_BAG 2u +#define F_TAMA 4u /* 1.6.8: TAMA menu (level, care, character) */ +#define F_SAVES 8u /* 1.6.8: the slots are saves (any field), not fields */ +#define F_LAUNCH 16u /* 1.6.8: launcher ROM: the menu is the home screen (C stays, display off when idle) */ +#define F_CLEAN 32u /* 1.7.2: ROM without the Paradise: the menu starts by itself and keeps the clock */ +#define SAVE_OFF 0xF06u /* settings block: number of the active save + 1 (save mode) */ + +#define APPS_MAX 6 +typedef struct { u16 off; u8 val; u8 pad; } Patch; +typedef struct { + u32 magic, version; + u32 slot_off, slot_size, nslots; + u32 user_start, user_end, id_page; + u32 stub_off; /* stub: word +8 = program source (XIP), 0 = none */ + u32 flags; + u32 id_c; u16 id_h0, id_h1; /* ID page: footer u16 h0, u16 h1, C-id, ~(C-id) */ + u32 nfields; + u32 field_id[4]; + char field_name[4][12]; + u32 field_col[4]; + Patch fac_common[16]; /* factory settings: off 0 = end of list */ + Patch fac_field[4][4]; + u32 money_off, list_off, count_off; + u32 cat_off, cat_n; /* catalog: 8 byte header, then 28 bytes per entry (u16 id, u8 fixed, u8 len, u16 image, u16 0, 20 chars) */ + u32 field_byte; /* offset of the field in the settings block (Land 439, Jade 443, Tropical 499) */ + u32 pack_off; /* image table in flash (for the item pictures), 0 = none */ + /* from version 4: fields 5 and 6 (six fields: Land, Water, Sky next to Tropical, Glacier, Forest) */ + u32 six_off; /* offset of the field set byte in the settings block, 0 = none */ + u32 field_id2[2]; + char field_name2[2][12]; + u32 field_col2[2]; + Patch fac_field2[2][4]; + u32 slot_off2, slot_n1; /* slots slot_n1.. lie at slot_off2 (0 = all at slot_off) */ + u8 six_map[8]; /* field of (set byte * 4 + field byte), 0xFF = none */ + /* from version 5 (1.6.0): more programs (each a full PRAM image in the flash, started through the + * stub entry at +0x0C), and the name of the stub's own program ("" = by its kind) */ + char name0[12]; + u32 napps; + struct { u32 src; char name[12]; } apps[APPS_MAX]; + /* from version 6 (1.6.8): TAMA menu. tama_off: the pet in the settings block (+4/+6 character, + * +0x10 sickness, +0x18 bits 2..4 stage, +0x1C hunger 0..6, +0x1D happiness 0..20), level_off: + * planet level (low nibble = level, high nibble = level already celebrated) */ + u32 tama_off, level_off; + /* from version 7 (1.6.8): the flash app as a 64 KB image (start device: menu entry DOWNLOAD), 0 = none */ + u32 dl_src; + /* from version 8 (1.6.8): six more programs (the small V1Emu ones fit many times) */ + struct { u32 src; char name[12]; } apps2[6]; + /* from version 9 (1.6.9 test13): the main program of the start device when it is one of the list (DOOM stays + * at 0x0A0000): shown first and started by itself when vflags bit 0 is set (0 = the stub's own) */ + u32 main_src, vflags; + /* from version 10 (1.7.2 FELD_CLEAN): a ROM without the Paradise (flag F_CLEAN): the menu's own clock sector + * ("PMXK": time base, seconds counter at that time, display time, check), 0 = none */ +#ifdef FELD_CLEAN + u32 clock_sec; +#endif +} Cfg; + +#ifdef HOST +#define CFG_QUAL +#else +#define CFG_QUAL const +#endif +__attribute__((section(".pmxcfg"), used)) +#ifdef FELD_CLEAN +#define CFG_SIZE_OK (sizeof(Cfg)==612 && offsetof(Cfg,clock_sec)==608) +#define CFG_VER 10 +#define CFG_TAIL , 0 +#else +#define CFG_SIZE_OK (sizeof(Cfg)==608) +#define CFG_VER 9 +#define CFG_TAIL +#endif +volatile CFG_QUAL Cfg g_cfg = { FELD_MAGIC, CFG_VER, 0x830000u, 0x58000u, 3, 0xD4A000u, 0x1000000u, 0xD49000u, 0xB0000u, + F_FIELDS|F_BAG, 0x70169E2Cu, 1, 4, 3, {1,2,3,0}, {"LAND","WATER","SKY",""}, + {0x5647u, 0x2BDFu, 0x7E9Fu, 0xFD45u}, + {{8,0x11,0},{16,0xc0,0},{17,0xa8,0},{168,1,0},{576,0x3f,0},{577,0x1f,0},{1856,1,0}}, + {{{4,0x0c,0},{170,2,0},{439,0,0}}, {{4,4,0},{170,1,0},{439,1,0}}, {{4,4,0},{170,1,0},{439,2,0}}}, + 0xb4u, 0x240u, 0x740u, 0, 0, 439u, 0, 0, {0,0}, {"",""}, {0,0}, {{{0,0,0}}}, 0, 0, {0}, "", 0, {{0,""}}, 0, 0, 0, {{0,""}}, 0, 0 CFG_TAIL }; +#define XIP_DEC 0x11000u +#include +_Static_assert(offsetof(Cfg,flags)==36 && offsetof(Cfg,id_c)==40 && offsetof(Cfg,nfields)==48 && offsetof(Cfg,field_name)==68 + && offsetof(Cfg,field_col)==116 && offsetof(Cfg,fac_common)==132 && offsetof(Cfg,fac_field)==196 + && offsetof(Cfg,money_off)==260 && offsetof(Cfg,cat_n)==276 && offsetof(Cfg,field_byte)==280 && offsetof(Cfg,six_off)==288 && offsetof(Cfg,field_name2)==300 + && offsetof(Cfg,field_col2)==324 && offsetof(Cfg,fac_field2)==332 && offsetof(Cfg,slot_off2)==364 && offsetof(Cfg,six_map)==372 && CFG_SIZE_OK && offsetof(Cfg,main_src)==600 && offsetof(Cfg,dl_src)==500 && offsetof(Cfg,tama_off)==492 && offsetof(Cfg,name0)==380 && offsetof(Cfg,napps)==392 && offsetof(Cfg,apps)==396, "settings block layout"); +#define NF_MAX 6u + +/* Saved field (header page at the start of its slot). res[0] = POOL_MAGIC (1.2.12): the + * packed data lies in the pages dpg[0..res[1]-1] of the shared pool (all slot pages except + * the header pages), so one field can use the room the other fields do not need. Without + * it (older menus) the data follows the header in the field's own slot. */ +#define POOL_MAGIC 0x4C4F4F50u /* "POOL" */ +#define PEND_MAGIC 0x444E4550u /* "PEND" in res[2]: switch from this field under way (1.6.8) */ +#define DPG_MAX 1024u +typedef struct { + u32 magic, field, npages, bytes, sum, res[3]; + struct { u16 page, clen; } e[NPAGE_MAX]; + u16 dpg[DPG_MAX]; +} SlotHdr; +_Static_assert(sizeof(SlotHdr)<=4096u, "slot header fits one page"); + +#define GPIO2 0x4001A000u + +static u16 g_fb[128*128]; +static u8 g_page[PAGE] __attribute__((aligned(4))); /* uncompressed page (1.6.8: all flash buffers word aligned, the flash DMA needs it: error 41) */ +static u8 g_cmp[PAGE+PAGE/8+16] __attribute__((aligned(4))); /* one compressed page */ +static u8 g_out[PAGE] __attribute__((aligned(4))); /* write buffer */ +static SlotHdr g_hdr; +static u16 g_head[4096], g_prev[4096]; +static u8 g_ff[PAGE] __attribute__((aligned(4))); /* empty page: erase = write an empty page */ +static u8 g_set[PAGE] __attribute__((aligned(4))); /* settings block being edited */ + +#ifdef HOST +#include "host.h" +#else +#define FLASH_BASE ((volatile u8*)0x60000000u) +#endif +static u32 rd32(u32 a){ return *(const volatile u32*)(FLASH_BASE + a); } +static u32 rd16(u32 a){ return *(const volatile u16*)(FLASH_BASE + a); } +static const volatile u8* fl(u32 a){ return (const volatile u8*)(FLASH_BASE + a); } + +/* ---------------------------------------------------------------- Display */ +#define RGB(r,g,b) ((u16)((((r)>>3)<<11)|(((g)>>2)<<5)|((b)>>3))) +static void rect(int x0,int y0,int x1,int y1,u16 c){ + if(x0<0)x0=0; if(y0<0)y0=0; if(x1>128)x1=128; if(y1>128)y1=128; + for(int y=y0;y= 128. Never interpret truncated input as an index. */ +static int ko_pair(const char *s){ return (u8)s[0]>=128 && (u8)s[1]>=128; } +static int ko_scale(const char *s,int sc){ for(int i=0;s[i];i++) if((u8)s[i]>=128) return 1; return sc; } +static int text_w(const char *s,int sc){ sc=ko_scale(s,sc); int w=0; for(int i=0;s[i];i++){if(ko_pair(s+i)){w+=10*sc;i++;}else w+=6*sc;}return w?w-sc:0; } +static void textn(int x,int y,const char *s,int n,u16 c,int sc){ + sc=ko_scale(s,sc); const int limit=x+n*6*sc; + for(int i=0;ilimit || x+10*sc>128)break; + const volatile u8 *g=0; + if(k>3]&(128>>(p&7)))rect(x+q*sc,y+r*sc,x+(q+1)*sc,y+(r+1)*sc,c);} + x+=10*sc; + }else{ + if(x+5*sc>limit || x+5*sc>128)break; + int ch=(u8)s[i];if(ch>=128)ch='?';if(ch>=0x60 && ch!='x')ch-=32; + int k=glyph(ch);if(k<0||k>=96)k='?'-32; + const u8 *g=g_font[k]; + for(int r=0;r<7;r++)for(int q=0;q<5;q++)if(g[r]&(16>>q))rect(x+q*sc,y+r*sc,x+(q+1)*sc,y+(r+1)*sc,c); + x+=6*sc; + } + } +} +static void text(int x,int y,const char *s,u16 c,int sc){ textn(x,y,s,999,c,sc); } +static void ctext(int y,const char *s,u16 c,int sc){ text((128-text_w(s,sc))/2,y,s,c,sc); } +static void show(void){ hw_push(g_fb,128,0,0,128,128); } +static void utoa_(u32 v, char *s){ char t[12]; int n=0; do{ t[n++]=(char)('0'+v%10u); v/=10u; }while(v); for(int i=0;iNF_MAX ? NF_MAX : g_cfg.nfields; } + +static void progress(const char *what, u32 n, u32 tot){ + rect(0,40,128,100,BG); + ctext(44,what,WHITE,1); + rect(14,62,114,72,GREY); rect(15,63,113,71,BG); + u32 w = tot ? (98u*n)/tot : 0; if(w>98u) w=98u; + rect(15,63,15+(int)w,71,RGB(40,120,255)); + hw_push(g_fb,128,0,40,128,100); +} + +/* ---------------------------------------------------------------- Buttons */ +static const signed char g_qd[16]={0,-1,1,0, 1,0,0,-1, -1,0,0,1, 0,1,-1,0}; +static u32 g_enc_last; static int g_enc_acc; +static u32 g_btn_last; +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +static u32 g_tick_last, g_ms, g_sub, g_enc_t; +static void clock_start(void){ SYST_RVR=0xFFFFFFu; SYST_CVR=0; SYST_CSR=5u; g_tick_last=SYST_CVR; } +static void clock_poll(void){ + u32 c=SYST_CVR, d=(g_tick_last-c)&0xFFFFFFu; g_tick_last=c; + g_sub+=d; while(g_sub>=96000u){ g_sub-=96000u; g_ms++; } +} +#define K_A 10 +#define K_OK 2 +#define K_BACK 3 +/* returns: wheel steps (+n/-n, 1..9), K_OK (B or wheel), K_BACK (C), K_A (A), 0 nothing. + * The wheel counts once it has been still for 25 ms after a movement, so it does + * not matter how many edges one detent produces. Fast turning gives several steps. */ +static int g_step; +#ifdef HOST +static int input(void){ return host_input(&g_step); } +#else +static int input(void){ + hw_wdt_feed(); clock_poll(); + u32 n=REG(GPIO2) & 3u; + if(n!=g_enc_last){ g_enc_acc+=g_qd[(g_enc_last<<2)|n]; g_enc_last=n; g_enc_t=g_ms; } + else if(g_enc_acc && g_ms-g_enc_t>=25u){ + int a=g_enc_acc<0 ? -g_enc_acc : g_enc_acc; int st=(a+2)/4; if(st<1) st=1; if(st>9) st=9; + g_step = g_enc_acc>0 ? st : -st; g_enc_acc=0; return 1; } + u32 b=hw_buttons(), dn=b & ~g_btn_last; g_btn_last=b; + if(dn & BTN_A) return K_A; + if(dn & (BTN_B|BTN_WHEEL)) return K_OK; + if(dn & BTN_C) return K_BACK; + return 0; +} +#endif +#ifdef HOST +static void delay_loop(u32 n){ (void)n; } +#else +static void delay_loop(u32 n){ for(volatile u32 i=0;ibest){ best=l; boff=i-j; if(l==LZ_MAX) break; } + j=g_prev[j]; tries++; + } + } + u32 step = best>=3u ? best : 1u; + if(best>=3u){ + u32 ln=best-3u; + out[fpos]|=(u8)(1u<>8); } + else { u32 v=((boff-1u)<<4)|15u; out[o++]=(u8)v; out[o++]=(u8)(v>>8); out[o++]=(u8)(ln-15u); } + } else out[o++]=in[i]; + bit++; + for(u32 k=0;k=n) return 1; + u32 f=in[i++]; + for(u32 b=0;b<8u && on) return 2; + u32 v=in[i] | ((u32)in[i+1]<<8); i+=2; + u32 off=(v>>4)+1u, len=(v&15u)+3u; + if((v&15u)==15u){ if(i>=n) return 2; len+=in[i++]; } + if(off>o || o+len>PAGE) return 3; + for(u32 k=0;k=n) return 4; out[o++]=in[i++]; } + } + } + return i==n ? 0 : 5; +} + +/* ---------------------------------------------------------------- Flash */ +/* Erase by programming an empty page: the program command also erases on the + * device (confirmed), a plain erase has not been tested. */ +static void erase_page(u32 a){ flash_prog4k(a, g_ff); } +static int page_ff(u32 a){ const volatile u32 *p=(const volatile u32*)(FLASH_BASE+a); for(u32 i=0;i>1)^0xA001u : c>>1; } + return c & 0xFFFFu; +} +static void stamp(u8 *p){ u32 c=crc16arc(p,4,PAGE); p[0]=(u8)c; p[1]=(u8)(c>>8); p[2]=(u8)~c; p[3]=(u8)(~c>>8); } + +/* Fields: index 0..nfields-1, ID g_cfg.field_id[i] */ +static u32 cur_id(void){ return rd32(g_cfg.id_page); } +static int field_index(u32 id){ for(u32 i=0;i=0 ? f : field_index(cur_id()); +} +static u32 slot_base(u32 i){ + if(g_cfg.slot_off2 && g_cfg.slot_n1 && i>=g_cfg.slot_n1) return g_cfg.slot_off2 + (i-g_cfg.slot_n1)*g_cfg.slot_size; + return g_cfg.slot_off + i*g_cfg.slot_size; } +static u32 spp(void){ return g_cfg.slot_size/PAGE - 1u; } /* pool pages per slot */ +static u32 pool_n(void){ return g_cfg.nslots*spp(); } +static u32 pool_addr(u32 k){ return slot_base(k/spp()) + (k%spp()+1u)*PAGE; } +static int slot_pool(u32 b){ return rd32(b+20)==POOL_MAGIC; } +static int slot_valid(u32 i){ + u32 b=slot_base(i); + if(rd32(b)!=SLOT_MAGIC || rd32(b+4)!=i+1u) return 0; /* slot ID = field number + 1 */ + u32 np=rd32(b+8), by=rd32(b+12); + if(np>NPAGE_MAX) return 0; + if(!slot_pool(b)) return by<=g_cfg.slot_size-PAGE; + u32 nd=rd32(b+24); + if(nd>DPG_MAX || by>nd*PAGE) return 0; + for(u32 k=0;k=pool_n()) return 0; + return 1; +} +/* Read n bytes of the packed data of slot i from position pos. */ +static void slot_get(u32 i, u32 pos, u32 n, u8 *dst){ + u32 b=slot_base(i); int pool=slot_pool(b); + while(n){ + u32 pg=pos/PAGE, o=pos%PAGE, c=PAGE-o; if(c>n) c=n; + u32 a = pool ? pool_addr(rd16(b+offsetof(SlotHdr,dpg)+2u*pg)) : b+PAGE+pg*PAGE; + for(u32 k=0;k>3]|=(u8)(1u<<(x&7u)); } } + else { u32 nd=(rd32(b+12)+PAGE-1u)/PAGE; for(u32 k=0;k>3]|=(u8)(1u<<(x&7u)); } } + } +} +/* Next free pool page for slot fi (its own pages first), marks it. 0xFFFF = full. */ +static u32 pool_take(u32 fi){ + u32 n=pool_n(); if(n>sizeof(g_used)*8u) n=sizeof(g_used)*8u; + for(u32 r=0;r>3]&(1u<<(x&7u)))){ g_used[x>>3]|=(u8)(1u<<(x&7u)); return x; } + } + return 0xFFFFu; +} +static void write_id(u32 id){ + u32 *w=(u32*)g_out; + for(u32 i=0;iNPAGE_MAX) return 10; + erase_page(b); /* invalidate the header first */ + for(u32 i=0;i>12); g_hdr.e[np].clen=(u16)n; np++; + for(u32 k=0;k=DPG_MAX) return 11; + flash_prog4k(pool_addr(x),g_out); g_hdr.dpg[nd++]=(u16)x; on=0; } } + by+=n; + progress("\200\377\200\375 \201\206", ++done, tot*2u); + } + if(on){ u32 x=pool_take(fi); if(x==0xFFFFu || nd>=DPG_MAX) return 11; + for(u32 k=on;k>12)){ + u32 n=rd16(b+34+ix2*4); + if(set==(int)pass){ slot_get(fi,o2,n,g_cmp); if(lz_unpack(g_cmp, n, g_page)) return 21; want=1; } + o2+=n; ix2++; + if(!want) continue; + } else if(set!=(int)pass) continue; + if(want){ if(!flash_same(a,g_page,PAGE)) flash_prog4k(a,g_page); if(!flash_same(a,g_page,PAGE)) return 22; } + else if(!page_ff(a)){ erase_page(a); if(!page_ff(a)) return 23; } + if(!pass && !(++done & 7u)) progress("\200\306\200\255\200\347\200\232 \201\206", done, tot); + } + if(!fresh && ix2!=np) return 24; + } + (void)ix; + return 0; +} + +/* ---------------------------------------------------------------- Screens */ +static void leave(void){ + rect(0,0,128,128,0); show(); +#ifdef PARA_BACK + para_back_fix(g_set); +#endif + hw_back_to_paradise(); +} +static void error_screen(int code){ + rect(0,0,128,128,BG); + ctext(30,"\200\347\200\263",RED,2); + char s[12]="\201\223\200\247 00"; s[5]=(char)('0'+code/10); s[6]=(char)('0'+code%10); + ctext(56,s,WHITE,1); + if(code==10||code==11) ctext(68,"\200\377\200\375 \200\353\200\254 \201\214\200\215",WHITE,1); /* the field stays as it is */ + ctext(84,"B/C \200\241\200\333\200\201\200\222",GREY,1); + show(); wait_release(); + for(;;){ int k=input(); if(k==K_OK||k==K_BACK) leave(); } +} +static void message(const char *l1, const char *l2, const char *l3){ + rect(0,0,128,128,BG); + ctext(34,l1,WHITE,1); ctext(48,l2,WHITE,1); ctext(62,l3,WHITE,1); + ctext(100,"C \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ int k=input(); if(k==K_OK||k==K_BACK) return; } +} +static void done_screen(const char *what, u16 col){ + rect(0,0,128,128,BG); + ctext(40,"\200\351\200\262",WHITE,2); + ctext(66,what,col,1); + show(); + delay_loop(6000000u); + leave(); +} + +/* Program in the stub? 0 = none, 1 = DOOM, 2 = TamaEmu, 3 = other, 4 = T7Emu */ +static u32 g_app; +static void app_detect(void){ + u32 src=rd32(g_cfg.stub_off+8u); + if(src<0x10000000u || src>=0x11000000u){ g_app=0; return; } + u32 off=src-0x10000000u+XIP_DEC; + u32 m=rd32(off+0x140u); + g_app = m==0x43584D50u ? 2u : m==0x37584D50u ? 4u : m==0x38584D50u ? 5u : 3u; + for(u32 i=0x140u;i<0x400u;i+=4u) if(rd32(off+i)==0x434D4450u){ g_app=1u; break; } +} +static const char *const g_appname[6]={"","DOOM","TAMAEMU","\201\237\200\260\200\217\200\253","T7EMU","T18EMU"}; +static void start_app(void){ + rect(0,0,128,128,0); show(); +#ifdef HOST + host_exit("APP"); +#endif + ((void(*)(void))(0x10000000u + g_cfg.stub_off - XIP_DEC + 1u))(); + for(;;){} +} +/* All programs: 0 = the stub's own (if any), then the ones of the settings block (version 5) */ +static u32 g_napp, g_appsrc[APPS_MAX+9], g_dl, g_sx; /* g_dl: index of DOWNLOAD + 1, g_sx: of SETTINGS + 1 (start device) */ +static char g_appnm[APPS_MAX+9][13]; +static void apps_detect(void){ + g_napp=0; + if(g_app){ + const volatile char *n=g_cfg.version>=5u && g_cfg.name0[0] ? g_cfg.name0 : g_appname[g_app]; + for(int k=0;k<12;k++){ g_appnm[0][k]=n[k]; if(!n[k]) break; } g_appnm[0][12]=0; + g_appsrc[0]=0; g_napp=1; + } + /* the stub must have the entry at +0x0C (cpsid i; mov r4, r0) */ + if(g_cfg.version<5u || rd32(g_cfg.stub_off+0x0Cu)!=0x4604B672u) return; + for(u32 i=0;i=8u ? 6u : 0u);i++){ + const volatile char *nm = i=0x11000000u) continue; + for(int k=0;k<12;k++){ g_appnm[g_napp][k]=nm[k]; } g_appnm[g_napp][12]=0; + g_appsrc[g_napp++]=s; + } +#ifdef FELD_AUTO + /* 1.6.9 test13: the chosen main program first */ + if(g_cfg.version>=9u && g_cfg.main_src){ + for(u32 j=1;j0;m--){ g_appsrc[m]=g_appsrc[m-1]; for(int k=0;k<13;k++) g_appnm[m][k]=g_appnm[m-1][k]; } + g_appsrc[0]=s; for(int k=0;k<13;k++) g_appnm[0][k]=t[k]; + break; + } + } +#endif + /* start device: our flash app as the last entry, so the PC can write the ROM again (the Paradise's own + * download screen is not reachable any more) */ + g_dl=0; g_sx=0; +#ifndef NO_LSET + /* start device (1.6.8): sound and display time, the Paradise's own settings screens are gone */ + if(g_cfg.flags & 16u){ + const char *d="\200\316\201\202"; int k=0; while(d[k]){ g_appnm[g_napp][k]=d[k]; k++; } g_appnm[g_napp][k]=0; + g_appsrc[g_napp++]=0; g_sx=g_napp; + } +#endif + if((g_cfg.flags & 16u) && g_cfg.version>=7u && g_cfg.dl_src>=0x10000000u && g_cfg.dl_src<0x11000000u){ + const char *d="\200\234\200\354\200\260\200\247"; int k=0; while(d[k]){ g_appnm[g_napp][k]=d[k]; k++; } g_appnm[g_napp][k]=0; + g_appsrc[g_napp++]=g_cfg.dl_src; g_dl=g_napp; + } +} +#ifdef FELD_AUTO +/* 1.6.9 test13: start the main program by itself in the start device, once per switching on (as the stub's autostart, + * same mailbox 0x20000FFC): "PMXL" a program went back on purpose, "PMXM" the menu decided already, "PMXR" restart + * while the main program ran (reset button); anything else: switched on (seconds counter below 30) or woken from deep + * sleep. B held: stay in the menu. */ +#ifdef HOST +#include +static u32 h_mb, h_gpio=0xFFFFFFFFu, h_cnt; /* host: from the environment (AUTO_MB, AUTO_GPIO, AUTO_CNT) */ +#define AUTO_MB (&h_mb) +static u32 h_seen; +#define AUTO_SEEN h_seen +#define AUTO_GPIO h_gpio +#define AUTO_CNT h_cnt +#else +#define AUTO_MB ((volatile u32*)0x20000FFCu) +#define AUTO_SEEN REG(0x20000FF8u) +#define AUTO_GPIO REG(0x40018000u) +#define AUTO_CNT REG(0x45000304u) +#endif +#define MB_L 0x4C584D50u +#define MB_S 0x53584D50u /* "PMXS": this "PMXL" was seen (FELD_SEEN) */ +#define MB_M 0x4D584D50u +#define MB_R 0x52584D50u +static void start_app_i(u32 i); +#ifdef FELD_CLEAN +static int clean_mode(void); +#endif +#ifdef FELD_BFALL +/* 1.7.2 test19: C held after switching on (or after the reset button) starts the flash app (B there already means: no + * autostart) (DOWNLOAD): a way back + * when a program or a save leaves the screen black. Not when a program went back on purpose ("PMXL"), not when the + * Paradise woke from deep sleep (mailbox lost, clock ran). Without the Paradise the menu only starts at switching on, + * after a reset or when a program went back. */ +static void b_fallback(void){ + if(!g_dl || (AUTO_GPIO & 0x400u)) return; +#ifdef FELD_BFALL_NOA + if(!(AUTO_GPIO & 0x200u)) return; /* 1.7.3 test29: not with A held too (A and C: the program key) */ +#endif + volatile u32 *mb=AUTO_MB; u32 m=*mb; + if(m==MB_L) return; +#ifdef FELD_CLEAN + if(!clean_mode()) +#endif + if(AUTO_CNT>=30u && m!=MB_R && m!=MB_M) return; + *mb=MB_M; + start_app_i(g_dl-1u); +} +#endif +#ifdef FELD_AUTODBG +static u32 g_adbg[4]; /* 1.7.3 test8: the autostart's mailbox, GPIO0 and B decision, shown small on the home screen */ +#endif +static int auto_go(void){ + if(g_cfg.version<9u || !(g_cfg.vflags & 1u) || !g_napp || !(g_cfg.flags & F_LAUNCH)) return 0; + volatile u32 *mb=AUTO_MB; u32 m=*mb; +#if defined(FELD_CLEAN) && defined(CLEAN_AUTO) + /* 1.7.2 test19: without the Paradise the seconds counter says nothing about switching on (Bernd: the main program + * did not start). The menu only starts at switching on, after a reset or when a program went back: start the main + * program unless a program went back ("PMXL"). test21: "PMXM" of an earlier menu stays in the RAM over a write and + * a reset (Bernd: clock set, then the menu): it no longer counts, and "PMXL" counts once. */ + if(clean_mode()){ +#ifdef FELD_BSETTLE + /* 1.7.3 test8: B is only "held" when it reads low over 5 looks a few ms apart (the pins may not have settled + * right after the start, a reset could take that for B and show the menu) */ + int bh=1; for(u32 k=0;k<5u && bh;k++){ for(volatile u32 t=0;t<60000u;t++){} if(AUTO_GPIO & 0x800u) bh=0; } +#else + int bh=!(AUTO_GPIO & 0x800u); +#endif +#ifdef FELD_AUTODBG + g_adbg[0]=m; g_adbg[1]=AUTO_GPIO; g_adbg[2]=1u+(u32)bh; g_adbg[3]=AUTO_SEEN; +#endif +#ifdef FELD_SEEN + /* 1.7.3 test9: Bernd: back from T18Emu with the wheel, then reset: the mailbox still said "PMXL" at the reset (menu + * instead of the autostart). The menu notes that it has shown itself for this "PMXL" in the word before the mailbox + * (the programs set it to 0 when they write "PMXL"); a "PMXL" seen already is an old one: a reset, autostart. */ + if(m==MB_L && AUTO_SEEN) m=0; /* test12: any other word there is old too (the Paradise's stub counts in it: a device + * written right after a program had gone back to the Paradise showed the menu once) */ + if(m==MB_L) AUTO_SEEN=MB_S; +#endif + if(bh || m==MB_L){ *mb=0; return 0; } + *mb=MB_R; return 1; + } +#endif + if(!(AUTO_GPIO & 0x800u)){ *mb=0x4D584D50u; return 0; } + if(m==0x4C584D50u || m==0x4D584D50u) return 0; + if(m!=0x52584D50u && AUTO_CNT>=30u){ *mb=0x4D584D50u; return 0; } + *mb=0x52584D50u; return 1; +} +#endif +static void start_app_i(u32 i){ + if(!g_appsrc[i]){ start_app(); return; } + rect(0,0,128,128,0); show(); +#ifdef HOST + host_exit(g_appnm[i]); +#endif + ((void(*)(u32))(0x10000000u + g_cfg.stub_off - XIP_DEC + 0x0Cu + 1u))(g_appsrc[i]); + for(;;){} +} + +/* Large menu entry: name in large text, state in small text below. */ +static int g_small; /* five entries: lower boxes, state at the right */ +static void big_entry(int y, int sel, const char *name, const char *st, u16 c, u16 stc){ + if(g_small){ + if(sel){ rect(3,y,125,y+22,c); rect(4,y+1,124,y+21,BG); } + text(9,y+2,name,c,1); + textn(9,y+12,st,19,stc,1); + return; + } + if(sel){ rect(3,y,125,y+28,c); rect(5,y+2,123,y+26,BG); } + text(9,y+4,name,c,2); + text(9,y+17,st,stc,1); +} + +/* ---------------------------------------------------------------- Fields */ +static int g_cur; /* index of the active field, -1 = not a field in the list */ +static int g_act; /* slot of the live save: field mode = g_cur, save mode = its save number */ +static int saves_mode(void){ return (g_cfg.flags & F_SAVES) && g_cfg.version>=6u && g_cfg.nslots>=2u; } +/* save mode: the number of the live save goes into its settings block */ +static void act_mark(u32 j){ + flash_read(SET_A, g_page, PAGE); + if(!set_ok(g_page) || g_page[SAVE_OFF]==j+1u) return; + g_page[SAVE_OFF]=(u8)(j+1u); stamp(g_page); + flash_prog4k(SET_A, g_page); flash_prog4k(SET_B, g_page); +} +/* Live save to slot g_act, then slot tgt (has) or a fresh start on field fld into the live area. */ +static void field_switch2(u32 tgt, int has, u32 fld){ + rect(0,0,128,128,BG); ctext(8,"\200\374\200\330 \200\222\200\234\200\265\200\320\200\352",WHITE,1); ctext(20,"\201\201\200\356\200\361 \200\357\201\207\201\243\200\320\200\352",GREY,1); show(); + int e=stash((u32)g_act); + if(e){ erase_page(slot_base((u32)g_act)); error_screen(e); } + e=restore(has ? tgt : fld,!has); + if(e) error_screen(e); + if(fid(fld)){ write_id(fid(fld)); if(cur_id()!=fid(fld)) error_screen(30); } + if(field_now()!=(int)fld) error_screen(31); + if(saves_mode()) act_mark(tgt); + { u32 b=slot_base((u32)g_act); flash_read(b, g_out, PAGE); g_out[28]=g_out[29]=g_out[30]=g_out[31]=0; flash_prog4k(b, g_out); } /* switch done */ + if(has) erase_page(slot_base(tgt)); + done_screen(fname(fld), fcol(fld)); +} +static void field_switch(u32 tgt, int has){ field_switch2(tgt, has, tgt); } +static int field_confirm(u32 tgt, int has){ + rect(0,0,128,128,BG); + ctext(14,"\201\201\201\255 \200\236\200\312",WHITE,1); + ctext(30,fname(tgt),fcol(tgt),2); + ctext(54, has ? "\200\300\200\216\201\244 \200\377\200\375\200\361" : "\200\364 \201\207\200\344\200\343\200\314", WHITE,1); + ctext(66, has ? "\200\306\200\255\200\350\200\233\200\234" : "\200\313\200\260 \200\330\200\373\201\247\200\233\200\234", WHITE,1); + ctext(92,"B \200\346",WHITE,1); + ctext(106,"C \200\333\200\233\200\352",GREY,1); + show(); + return yes_no(); +} +static void big_entry(int y, int sel, const char *name, const char *st, u16 c, u16 stc); +static int launch_mode(void){ return (g_cfg.flags & F_LAUNCH) != 0u; } +/* Launcher ROM: after g_idle_ms without a key the display goes dark until the next key (1.6.8). + * The time is kept in the Paradise's settings block at IDLE_OFF (0 = 2 minutes, else index + 1). */ +#define IDLE_OFF 0xF07u +static const u32 g_idle_tab[5]={30000u,60000u,120000u,300000u,0u}; +static const char *const g_idle_nm[5]={"30 S","1\200\305","2\200\305","5\200\305","\200\225\201\207 \200\334\200\362"}; +static u32 g_idle_t, g_idle_ms; +#ifdef BAT_SHOW +#ifdef HOST +static void bat_text(char *s){ const char *t="2.84V 80%"; int i=0; while((s[i]=t[i])) i++; } +#else +#include "../../../emu/src/emu/batt.h" +#endif +#endif +static void lset_menu(void); +#ifdef FELD_CLEAN +static int clean_mode(void); +#define SX_TEXT (clean_mode() ? "\200\330\200\213\200\200\201\253\200\271" : "\200\322\200\265\200\200\201\253\200\271") +#else +#define SX_TEXT "\200\322\200\265\200\200\201\253\200\271" +#endif +#if defined(FELD_PW) && !defined(HOST) +/* test23 (switch FELD_PW): the display dark, the menu waited for a key in a tight loop at the full clock and used + * about as much power as with the display on. Now deep sleep (as TamaEmu, EMU_PW) between the polls: a key wakes at + * once (edge interrupt on P0.8..11, the wheel on P2.0/P2.1), the RTC every second when it runs on 1 s (the wheel is seen then). The interrupts + * stay masked: the pending one only ends the WFI, its flags are cleared here. */ +#define FP_ISO REG(0x45000200u) +#define FP_PMU REG(0x45000300u) +#define FP_GP0(o) REG(0x40018000u + (o)) +#define FP_KEYS 0xF00u +#define FP_GP2(o) REG(0x4001A000u + (o)) +#define FP_IRQS ((1u << 2) | (1u << 26) | (1u << 28)) /* RTC, GPIO0, GPIO2 (the wheel, P2.0/P2.1) */ +__attribute__((noinline)) static void dark_wait(void){ + u32 pm; __asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory"); + for(;;){ + if(input()) break; + if(hw_buttons() || g_enc_acc) continue; /* a key or the wheel being read: poll on */ + u32 iso=FP_ISO, rtc=(iso & 0x80u) && !(iso & 7u), csr=SYST_CSR; + if(rtc) FP_ISO = iso & ~8u; /* RTC_WKP 0: the RTC wakes */ + FP_GP0(0x0C) &= ~FP_KEYS; FP_GP0(0x10) |= FP_KEYS; FP_GP0(0x20) = FP_KEYS; FP_GP0(0x18) |= FP_KEYS; /* both edges */ + FP_GP2(0x0C) &= ~3u; FP_GP2(0x10) |= 3u; FP_GP2(0x20) = 3u; FP_GP2(0x18) |= 3u; + REG(0xE000E280u) = FP_IRQS; REG(0xE000E100u) = rtc ? FP_IRQS : FP_IRQS & ~(1u << 2); + SYST_CSR = 0; + FP_PMU = (FP_PMU & ~0x47u) | 2u; /* DSLEEP_EN */ + __asm__ volatile("dsb\n wfi\n isb" ::: "memory"); + FP_PMU = FP_PMU & ~0x47u; + REG(0xE000E180u) = FP_IRQS; FP_GP0(0x18) &= ~FP_KEYS; FP_GP0(0x20) = FP_KEYS; FP_GP2(0x18) &= ~3u; FP_GP2(0x20) = 3u; + FP_PMU = (FP_PMU & ~0x47u) | 0x10u; /* RTC_FLAG: write 1 */ + REG(0xE000E280u) = FP_IRQS; + if(rtc) FP_ISO = (FP_ISO & ~8u) | (iso & 8u); + SYST_CVR = 0; SYST_CSR = csr; g_tick_last = SYST_CVR; + for(u32 t=0;t<20000u;t++) if(hw_buttons()) break; /* the pins settle after the wake */ + } + __asm__ volatile("msr primask, %0" :: "r"(pm) : "memory"); +} +#elif defined(FELD_PW) +static void dark_wait(void){ while(!input()){} } +#endif +static int idle_input(void){ + int k=input(); + if(k){ g_idle_t=g_ms; return k; } +#ifndef HOST + if(launch_mode() && g_idle_ms && g_ms-g_idle_t>=g_idle_ms){ + hw_backlight(0); +#ifdef FELD_PW + dark_wait(); +#else + while(!input()){} +#endif + hw_backlight(1); wait_release(); g_idle_t=g_ms; + return -1; /* redraw */ + } +#endif + return 0; +} +/* Program list (more than one program, or the launcher's home screen). Returns on C unless top. */ +static void apps_menu(int top){ + u32 n=g_napp, sel=0, first=0; /* first: top row of the list (1.6.8: more than 8 entries scroll) */ + g_idle_t=g_ms; + for(;;){ + rect(0,0,128,128,BG); + int y0 = n>=4u ? 1 : 12; + if(n<4u) ctext(2, launch_mode() ? "PARAMIX" : "\201\237\200\260\200\217\200\253",WHITE,1); + if(n>8u){ if(sel=first+8u) first=sel-7u; } else first=0; + for(u32 i=first;i8u?8u:n);i++){ + int sx = g_sx && i+1u==g_sx; + u16 c = (g_dl && i+1u==g_dl) || sx ? GREY : ORANGE; + if(n>4u){ + int dy = n>7u ? 14 : 16, y=2+(int)(i-first)*dy; + if(i==sel){ rect(1,y,127,y+dy-1,c); rect(2,y+1,126,y+dy-2,BG); } + text(5,y+(dy-8)/2+1,g_appnm[i],c,1); + const char *st = sx ? "\200\345\200\222" : "\200\330\200\373"; + text(123-text_w(st,1),y+(dy-8)/2+1,st,GREY,1); + } else big_entry(y0+(int)i*29, i==sel, g_appnm[i], g_dl && i+1u==g_dl ? "PC \200\222\200\261" : sx ? SX_TEXT : "\200\330\200\373", c, GREY); + } +#ifdef BAT_SHOW + /* test17: the start device's home screen shows the battery bottom right */ + if(top && launch_mode()){ char bt[12]; bat_text(bt); text(5,117,"B \200\330\200\373",GREY,1); if(n<=8u) text(123-text_w(bt,1),119,bt,GREY,1); +#ifdef FELD_AUTODBG + if(g_adbg[2]){ static const char hx[]="0123456789ABCDEF"; char d[8]; u32 mm=g_adbg[0]; + d[0]= mm==MB_L ? 'L' : mm==MB_M ? 'M' : mm==MB_R ? 'R' : mm ? '?' : '0'; d[1]=hx[(g_adbg[1]>>8)&15u]; d[2]=g_adbg[2]==2u ? 'B' : '-'; d[3]= g_adbg[3]==MB_S ? 'S' : g_adbg[3] ? '?' : '0'; d[4]=0; + text(58,119,d,GREY,1); } +#endif + } + else +#endif + ctext(117, top && launch_mode() ? "B \200\330\200\373" : "B \201\254\200\365 C \200\246\200\260",GREY,1); + if(n>8u){ char sc[8]; u32 a=sel+1u; int k=0; if(a>=10u) sc[k++]=(char)('0'+a/10u); sc[k++]=(char)('0'+a%10u); sc[k++]='/'; if(n>=10u) sc[k++]=(char)('0'+n/10u); sc[k++]=(char)('0'+n%10u); sc[k]=0; text(123-text_w(sc,1),119,sc,GREY,1); } + show(); wait_release(); + for(;;){ + int k=idle_input(); + if(k<0) break; + if(k==1){ sel=(u32)((int)sel + (g_step>0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK){ if(top && launch_mode()) continue; if(top) leave(); return; } + if(k==K_OK){ if(g_sx && sel+1u==g_sx){ lset_menu(); g_idle_t=g_ms; break; } start_app_i(sel); } + } + } +} +/* Field list. with_app: program as the last entry (when there is no main menu). + * Returns when C is pressed and there is a main menu. */ +static void field_menu(int with_app, int top){ + int has[NF_MAX]; u32 nf=nfields(); for(u32 i=0;i1u ? 1u : g_napp) : 0u; + u32 n = nf + na; + u32 sel = na ? nf : (u32)g_cur; + for(;;){ + rect(0,0,128,128,BG); + int y0 = n>=4u ? 1 : 12; + if(n<4u) ctext(2, top ? "PARAMIX" : "\201\207\200\344", WHITE,1); + for(u32 i=0;i1u ? "\201\237\200\260\200\217\200\253" : g_appnm[0]; + const char *st = i>=nf ? (g_napp>1u ? "\200\315\201\226" : "\200\330\200\373") : ((int)i==g_cur) ? "\200\310\200\353 \201\206" : has[i] ? "\200\377\200\375\200\244" : "\200\313\200\260"; + u16 c = i4u){ /* six fields: compact rows */ + int y=2+(int)i*16; + if(i==sel){ rect(1,y,127,y+15,c); rect(2,y+1,126,y+14,BG); } + text(5,y+4,nm,c,1); + text(123-text_w(st,1),y+4,st,stc,1); + } else big_entry(y0+(int)i*29, i==sel, nm, st, c, stc); + } + ctext(117,"B \201\254\200\365 C \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ sel=(u32)((int)sel + (g_step>0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK){ if(top) leave(); return; } + if(k==K_OK){ + if(sel>=nf){ if(g_napp>1u) apps_menu(0); else start_app_i(0); break; } + if((int)sel==g_cur){ if(top) leave(); return; } + if(field_confirm(sel,has[sel])) field_switch(sel,has[sel]); + break; + } + } + } +} + +/* ---------------------------------------------------------------- Items and Tamapoints */ +static int set_load(void){ + flash_read(SET_A, g_set, PAGE); + u32 c=crc16arc(g_set,4,PAGE); + if((g_set[0]|(g_set[1]<<8))!=c || (g_set[2]|(g_set[3]<<8))!=(~c&0xFFFFu)) return 1; + u32 y=g_set[0x1c]|(g_set[0x1d]<<8), m=g_set[0x1e]|(g_set[0x1f]<<8), d=g_set[0x20]|(g_set[0x21]<<8); + if(y<2020u || y>2035u || m<1u || m>12u || d<1u || d>31u) return 2; /* nothing saved yet */ + if(g_cfg.list_off+1280u>PAGE || g_cfg.count_off+320u>PAGE || g_cfg.money_off+4u>PAGE) return 3; + return 0; +} +static int set_check_msg(void){ + int e=set_load(); + if(e==1){ message("\200\377\200\375 \200\237\200\364\201\227\200\201","\200\323\200\312\200\243\200\342\200\327\200\233\200\234","\200\277\200\212\201\243\201\207 \200\334\200\336\200\327\200\233\200\234"); return 1; } + if(e==2){ message("\200\377\200\375 \200\237\200\364\201\227 \200\341\200\362","\201\204\200\221 \201\240\200\256\200\364\201\244 \200\246","\200\234\200\330 \200\330\200\240\201\243\200\320\200\352"); return 1; } + if(e){ message("\200\377\200\375 \201\252\200\331\200\361","\200\335 \200\324 \200\341\200\327\200\233\200\234",""); return 1; } + return 0; +} +static void set_write(const char *what){ + rect(0,0,128,128,BG); ctext(40,"\200\377\200\375 \201\206",WHITE,1); ctext(54,"\201\201\200\356\200\361 \200\357\201\207\201\243\200\320\200\352",GREY,1); show(); + stamp(g_set); + flash_prog4k(SET_A, g_set); + flash_prog4k(SET_B, g_set); + if(!flash_same(SET_A,g_set,PAGE) || !flash_same(SET_B,g_set,PAGE)) error_screen(40); + done_screen(what, GOLD); +} +/* Start device settings (1.6.8): sound level of the Paradise (settings byte 8, bits 3..4: 0 off .. 3 loud, + * found with the sound screen of the firmware) and the display time of this menu. */ +#define SND_OFF 8u +#ifdef FELD_CLEAN +/* ---------------------------------------------------------------- 1.7.2 FELD_CLEAN: ROM without the Paradise + * Nobody else keeps the time: the menu's own clock sector holds a time base (seconds since 1970, local) and the + * seconds counter 0x45000304 at that moment (it runs on through deep sleep and resets, it starts at 0 when the + * batteries come in). The programs get the time through the mailbox 0x20000FC0 as before. */ +#define CK_MAGIC 0x4B584D50u /* "PMXK" */ +typedef struct { u32 magic, t0, c0, idle, chk; } Clk; +static int clean_mode(void){ return g_cfg.version>=10u && (g_cfg.flags & F_CLEAN) && g_cfg.clock_sec; } +#ifdef FELD_NOCLK +/* 1.7.3 test7: vflags bit 1 = the Studio's "set the clock at the start" off: the clock is only set under SETTINGS + * (the programs keep their own clocks, as the real toys) */ +#define CLK_ASK() (!(g_cfg.vflags & 2u)) +#else +#define CLK_ASK() 1 +#endif +#ifdef HOST +static u32 rtc_cnt(void){ return 100u; } +#else +static u32 rtc_cnt(void){ return REG(0x45000304u); } +#endif +static int clk_load(Clk *k){ + const volatile u32 *p=(const volatile u32*)(FLASH_BASE+g_cfg.clock_sec); + k->magic=p[0]; k->t0=p[1]; k->c0=p[2]; k->idle=p[3]; k->chk=p[4]; + return k->magic==CK_MAGIC && k->chk==(k->magic^k->t0^k->c0^k->idle); +} +/* the time now (0 = not set, or the batteries were out since) */ +static u32 clk_now(void){ + Clk k; if(!clk_load(&k) || !k.t0) return 0; + u32 c=rtc_cnt(); if(cmagic=CK_MAGIC; k->t0=t; k->c0=t ? rtc_cnt() : 0; k->idle=idle; k->chk=k->magic^k->t0^k->c0^k->idle; + flash_prog4k(g_cfg.clock_sec, g_out); +#ifndef HOST + if(t) para_mailbox_put(t, k->c0); +#endif +} +/* days since 1970 -> date */ +static void civil(u32 z, u32 *y, u32 *m, u32 *d){ + z+=719468u; u32 era=z/146097u, doe=z-era*146097u, yoe=(doe-doe/1460u+doe/36524u-doe/146096u)/365u; + u32 doy=doe-(365u*yoe+yoe/4u-yoe/100u), mp=(5u*doy+2u)/153u; + *d=doy-(153u*mp+2u)/5u+1u; *m=mp<10u ? mp+3u : mp-9u; *y=yoe+era*400u+(*m<=2u); +} +static u32 mdays(u32 y, u32 m){ static const u8 n[12]={31,28,31,30,31,30,31,31,30,31,30,31}; return m==2u && !(y%4u) && (y%100u || !(y%400u)) ? 29u : n[m-1u]; } +static void two(char *s, u32 v){ s[0]=(char)('0'+v/10u%10u); s[1]=(char)('0'+v%10u); } +static void hhmm(u32 t, char *s){ u32 x=t%86400u; two(s,x/3600u); s[2]=':'; two(s+3,x/60u%60u); s[5]=0; } +/* set the clock: wheel changes, A goes to the next part, B saves, C back (not when must) */ +static void clock_menu(int must){ + u32 t=clk_now(), y=2026u, mo=1u, d=1u, h=12u, mi=0u, sel=0; + if(t){ civil(t/86400u,&y,&mo,&d); h=t%86400u/3600u; mi=t%3600u/60u; } + for(;;){ + if(d>mdays(y,mo)) d=mdays(y,mo); + rect(0,0,128,128,BG); + ctext(4,"\200\330\200\213 \200\316\201\202",WHITE,1); + char s[6]; + utoa_(y,s); text(5,26,s,sel==0u?ORANGE:WHITE,2); + s[0]='-'; s[1]=0; text(52,26,s,GREY,2); + two(s,mo); s[2]=0; text(65,26,s,sel==1u?ORANGE:WHITE,2); + s[0]='-'; s[1]=0; text(89,26,s,GREY,2); + two(s,d); s[2]=0; text(102,26,s,sel==2u?ORANGE:WHITE,2); + two(s,h); s[2]=0; text(34,52,s,sel==3u?ORANGE:WHITE,2); + s[0]=':'; s[1]=0; text(58,52,s,GREY,2); + two(s,mi); s[2]=0; text(70,52,s,sel==4u?ORANGE:WHITE,2); + ctext(84,"\201\260 \200\277\200\212",GREY,1); + ctext(96,"A \200\234\200\362 B \200\377\200\375",GREY,1); + if(!must) ctext(108,"C \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ + int st=g_step; + if(sel==0u){ int v=(int)y+st; if(v<2024) v=2099; if(v>2099) v=2024; y=(u32)v; } + else if(sel==1u){ mo=(u32)(((int)mo-1+st%12+12)%12)+1u; } + else if(sel==2u){ u32 n=mdays(y,mo); d=(u32)(((int)d-1+st%(int)n+(int)n)%(int)n)+1u; } + else if(sel==3u){ h=(u32)(((int)h+st%24+24)%24); } + else { mi=(u32)(((int)mi+st%60+60)%60); } + break; + } + if(k==K_A){ sel=(sel+1u)%5u; break; } + if(k==K_BACK && !must) return; + if(k==K_OK){ + Clk c; u32 idle=clk_load(&c) ? c.idle : 0u; + rect(0,0,128,128,BG); ctext(54,"\200\377\200\375 \201\206",WHITE,1); show(); + clk_store((u32)para_days((int32_t)y,(int32_t)mo,(int32_t)d)*86400u+h*3600u+mi*60u, idle); + return; + } + } + } +} +#endif +static void lset_load(void){ + g_idle_ms=120000u; +#ifdef FELD_CLEAN + if(clean_mode()){ Clk k; if(clk_load(&k) && k.idle>=1u && k.idle<=5u) g_idle_ms=g_idle_tab[k.idle-1u]; return; } +#endif + if(set_load()==1) return; + u32 v=g_set[IDLE_OFF]; if(v>=1u && v<=5u) g_idle_ms=g_idle_tab[v-1u]; +} +#ifdef FELD_CLEAN +/* clean ROM: the clock and this menu's display time */ +static void lset_clean(void){ + Clk k; u32 idl = clk_load(&k) && k.idle>=1u && k.idle<=5u ? k.idle-1u : 2u, idl0=idl, sel=0; + for(;;){ + char tm[8]; u32 t=clk_now(); if(t) hhmm(t,tm); else { const char *n="\200\273\200\316\201\202"; int i=0; while((tm[i]=n[i])) i++; } + rect(0,0,128,128,BG); + ctext(2,"\200\316\201\202",WHITE,1); + big_entry(16, sel==0u, "\200\330\200\213", tm, ORANGE, WHITE); + big_entry(45, sel==1u, "\201\253\200\271", g_idle_nm[idl], ORANGE, WHITE); + text(9,84,"\201\253\200\271 \200\224\201\210",GREY,1); + text(9,94,"\200\370\200\257\200\364 \200\341\200\361 \200\251",GREY,1); + ctext(108,"B \200\277\200\212",GREY,1); + ctext(117,"C \200\377\200\375 \201\257 \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ + int c=input(); + if(c==1 || c==K_A){ sel^=1u; break; } + if(c==K_OK){ if(sel==0u) clock_menu(0); else idl=(idl+1u)%5u; break; } + if(c==K_BACK){ + if(idl!=idl0){ + rect(0,0,128,128,BG); ctext(54,"\200\377\200\375 \201\206",WHITE,1); show(); + u32 t2=clk_now(); clk_store(t2, idl+1u); + g_idle_ms=g_idle_tab[idl]; + } + return; + } + } + } +} +#endif +static void lset_menu(void){ +#ifdef FELD_CLEAN + if(clean_mode()){ lset_clean(); return; } +#endif + int e=set_load(); + if(e==1 || e==2){ set_check_msg(); return; } + static const char *const snd_nm[4]={"\200\226","\200\373\200\211","\200\300\201\231","\201\224\200\211"}; + u32 snd=(g_set[SND_OFF]>>3)&3u, snd0=snd; + u32 idl=g_set[IDLE_OFF]; idl = idl>=1u && idl<=5u ? idl-1u : 2u; u32 idl0=idl; + u32 sel=0; + for(;;){ + rect(0,0,128,128,BG); + ctext(2,"\200\316\201\202",WHITE,1); + big_entry(16, sel==0u, "\200\322\200\265", snd_nm[snd], ORANGE, WHITE); + big_entry(45, sel==1u, "\201\253\200\271", g_idle_nm[idl], ORANGE, WHITE); + text(9,74,"\200\322\200\265: \200\302\201\234 \201\200\200\353",GREY,1); + text(9,84,"\201\253\200\271: \200\364 \200\270\200\231\200\343\200\314",GREY,1); + text(9,94,"\200\370\200\257 \200\341\200\360\200\271 \200\224\201\210",GREY,1); + ctext(108,"B \200\277\200\212",GREY,1); + ctext(117,"C \200\377\200\375 \201\257 \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1 || k==K_A){ sel^=1u; break; } + if(k==K_OK){ if(sel==0u) snd=(snd+1u)&3u; else idl=(idl+1u)%5u; break; } + if(k==K_BACK){ + if(snd!=snd0 || idl!=idl0){ + g_set[SND_OFF]=(u8)((g_set[SND_OFF]&~0x18u)|(snd<<3)); + g_set[IDLE_OFF]=(u8)(idl+1u); + rect(0,0,128,128,BG); ctext(40,"\200\377\200\375 \201\206",WHITE,1); ctext(54,"\201\201\200\356\200\361 \200\357\201\207\201\243\200\320\200\352",GREY,1); show(); + stamp(g_set); + flash_prog4k(SET_A, g_set); + flash_prog4k(SET_B, g_set); + if(!flash_same(SET_A,g_set,PAGE) || !flash_same(SET_B,g_set,PAGE)) error_screen(41); + g_idle_ms=g_idle_tab[idl]; + } + return; + } + } + } +} +static u32 money_get(void){ u32 o=g_cfg.money_off; return g_set[o]|(g_set[o+1]<<8)|(g_set[o+2]<<16)|((u32)g_set[o+3]<<24); } +static void money_put(u32 v){ u32 o=g_cfg.money_off; g_set[o]=(u8)v; g_set[o+1]=(u8)(v>>8); g_set[o+2]=(u8)(v>>16); g_set[o+3]=(u8)(v>>24); } +static u32 list_id(u32 i){ u32 o=g_cfg.list_off+2u*i; return g_set[o]|(g_set[o+1]<<8); } +static void list_set(u32 i, u32 id){ u32 o=g_cfg.list_off+2u*i; g_set[o]=(u8)id; g_set[o+1]=(u8)(id>>8); } +static u32 count_get(u32 i){ u8 b=g_set[g_cfg.count_off+i/2u]; return (i&1u) ? (b>>4) : (b&15u); } +static void count_set(u32 i, u32 v){ u32 o=g_cfg.count_off+i/2u; u8 b=g_set[o]; g_set[o]=(u8)((i&1u) ? ((b&0x0F)|(v<<4)) : ((b&0xF0)|(v&15u))); } +static u32 list_len(void){ u32 n=0; while(n<640u && list_id(n)) n++; return n; } + +/* Catalog in flash: 28 bytes per entry, sorted by ID */ +static int cat_find(u32 id){ + int lo=0, hi=(int)g_cfg.cat_n-1; + while(lo<=hi){ int m=(lo+hi)/2; u32 v=rd16(g_cfg.cat_off+8u+28u*(u32)m); if(v==id) return m; if(v=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]; } +static char g_nm[64]; +static void ko_title(const char *s,int y){int n=0,w=0;while(s[n]){int z=ko_pair(s+n)?2:1,px=z==2?10:6;if(w+px>116)break;w+=px;n+=z;}textn((128-w)/2,y,s,n,WHITE,1);if(s[n])ctext(y+11,s+n,WHITE,1);} +static const char *item_name(u32 id){ + int k=cat_find(id); + if(k>=0){ u32 o=g_cfg.cat_off+8u+28u*(u32)k; u32 n=fl(o+3)[0]; if(n==255u){u32 a=g_cfg.cat_off+rd32(o+8);u32 i=0;while(i<60u&&fl(a+i)[0]){g_nm[i]=(char)fl(a+i)[0];i++;}g_nm[i]=0;return g_nm;} if(n>20u) n=20u; if(n){ for(u32 i=0;i g_pic[0..n) */ + const volatile u32 *s=(const volatile u32*)(FLASH_BASE + a); + for(u32 i=0;i<(n+3u)/4u;i++) g_picw[i]=s[i]; +} +static u32 pr16(u32 o){ return g_pic[o]|(g_pic[o+1]<<8); } +static u32 pr32(u32 o){ return g_pic[o]|(g_pic[o+1]<<8)|(g_pic[o+2]<<16)|((u32)g_pic[o+3]<<24); } +static u32 spr_rle(u32 src, u32 ln, int x, int word, u8 *out, u32 cap){ + u32 i=0, o=0; +#define SB(k) ((u8)(g_pic[src+(k)] ^ (x?0x53u:0u))) + if(!word){ + while(i>(12-4*i))&15u]; } +static void pic_hex(int cy, u32 a, u32 b){ + char t[12]; hex4(t,a); t[4]=' '; hex4(t+5,b); t[9]=0; + ctext(cy+8, t, GREY, 1); +} +static void copy_bytes(u32 a, u32 n){ for(u32 i=0;iPIC_MAX){ pic_code(cy,"P7"); return; } + /* three ways to read, the first whose sum matches wins: + W = 32-bit reads in the 0x60000000 window, B = byte reads there, + X = cached XIP window at 0x10000000 pointed at the picture (menu runs from PRAM) */ + u32 sW, sB=0, sX=0; + copy_words(e, end); sW=pic_sum(end); + if(sW!=want){ copy_bytes(e, end); sB=pic_sum(end); } + if(sW!=want && sB!=want){ copy_xip(e, end); sX=pic_sum(end); } + if(sW!=want && sB!=want && sX!=want){ + char t[12]; + ctext(cy-12,"RD",GREY,1); + hex4(t,sW); t[4]=' '; hex4(t+5,want); t[9]=0; ctext(cy-2,t,GREY,1); + hex4(t,sB); t[4]=' '; hex4(t+5,sX); t[9]=0; ctext(cy+8,t,GREY,1); + copy_words(e,4u); hex4(t,pr16(0)); t[4]=' '; hex4(t+5,rd32(q+8u)&0xFFFFu); t[9]=0; ctext(cy+18,t,GREY,1); + return; + } + } else { + u32 P=g_cfg.pack_off, n=rd32(P)/4u; if(pic>=n){ pic_code(cy,"P2"); return; } + e=P+rd32(P+4u*pic); + if(e&3u){ pic_code(cy,"P6"); return; } + } + if(!end) copy_words(e, 64u); /* header */ + u32 flags=g_pic[4], bpp=g_pic[5], sw=g_pic[8], sh=g_pic[9], iw=g_pic[12], ih=g_pic[13]; + u32 tr=pr16(16), po=pr16(18), px=pr16(20); + if(bpp>3u || !sw || !sh){ pic_code(cy,"P3"); return; } + if(!iw) iw=1; if(!ih) ih=1; + u32 cnt=iw*ih, bits=1u<sizeof(g_spr)){ pic_code(cy,"P4"); return; } + if(!end){ + u32 hdr=px+8u*cnt; if(hdr>PIC_MAX || po+2u*(mask+1u)>PIC_MAX){ pic_code(cy,"P5"); return; } + copy_words(e, hdr); /* header and sub-image table */ + end=hdr; + for(u32 c=0;cend) end=x; + } + u32 pend=po+2u*(mask+1u); if(pend>end) end=pend; + if(end>PIC_MAX){ pic_code(cy,"P5"); return; } + copy_words(e, end); /* whole entry */ + if(want && pic_sum(end)!=want){ pic_code(cy,"RD"); pic_hex(cy,pic_sum(end),want); return; } + } + /* every offset used below must lie inside the copied entry */ + if(px+8u*cnt>end || po+2u*(mask+1u)>end){ pic_code(cy,"P5"); return; } + int W=(int)(sw*iw), H=(int)(sh*ih), sc=1, dn=1; + while(W/dn>box || H/dn>box) dn*=2; + if(dn==1 && W*2<=box && H*2<=box) sc=2; + int x0=cx-(W/dn*sc)/2, y0=cy-(H/dn*sc)/2; + int xr=(flags&0x80u)!=0; + for(u32 c=0;c>3]>>(bit&7u))&mask; + if((flags&4u) && v==tr) continue; + u16 col=(u16)pr16(po+2u*v); + int X=x0+x/dn*sc, Y=y0+y/dn*sc; + rect(X,Y,X+sc,Y+sc,col); + } + } +} +static const char *group_name(u32 id){ switch(id/1000u){ case 5: return "\200\331\200\310"; case 6: return "\200\202\200\331"; case 7: return "\200\375\200\227\200\203"; case 8: return "\200\353\201\236"; default: return "\200\222\201\225"; } } + +/* Draw a list: title, 10 rows from y=12, footer. */ +static void list_draw(const char *title, u32 n, u32 sel, u32 top, int (*row)(u32 i, char *name, char *right, u16 *col), const char *foot){ + rect(0,0,128,128,BG); + ctext(2,title,WHITE,1); + for(u32 r=0;r<10u && top+r10u){ int h=100*10/(int)n; if(h<6) h=6; int y=12+(int)(100-h)*(int)top/(int)(n-10u); rect(126,y,128,y+h,GREY); } + ctext(118,foot,GREY,1); + show(); +} + +/* Bag list: index -> slot (only items that are not fixed), entry 0 = add */ +static u16 g_bag[640]; static u32 g_bagn; +#ifdef BAG_DEL +#define BAG_SHOWN(i) (count_get(i) != 0u) +/* 1.6.9: count 0 = the game has the item no more (its own list keeps such entries, e.g. an apple eaten up); they are + * not shown, a count can be set to 0 to take an item out again */ +static void bag_build(void){ g_bagn=0; u32 n=list_len(); for(u32 i=0;i15u) v=15u; +#else +static u32 count_edit(u32 id, u32 v){ + const u32 lo=1u; + if(v<1u) v=1u; if(v>15u) v=15u; +#endif + for(;;){ + rect(0,0,128,128,BG); + const char *nm=item_name(id); int L=slen(nm); + ko_title(nm,2); + rect(30,20,98,84,BG); + draw_item_pic(id,64,52,64); + char s[8]; s[0]='x'; utoa_(v,s+1); +#ifdef BAG_DEL + if(!v) ctext(90,"\201\203\200\207",GOLD,2); else +#endif + ctext(90,s,GOLD,2); + ctext(108,"\201\260 \200\324\200\254",GREY,1); + ctext(117,"B \201\254\200\365 C \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ int nv=(int)v+(g_step>0?1:-1); if(nv<(int)lo) nv=(int)lo; if(nv>15) nv=15; v=(u32)nv; break; } + if(k==K_A){ v = v>=15u ? lo : v+1u; break; } + if(k==K_OK) return v; +#ifdef BAG_DEL + if(k==K_BACK) return 16u; +#else + if(k==K_BACK) return 0; +#endif + } + } +} +static int g_dirty; +static void cat_pick(void){ + cat_build(); + if(!g_catn){ message("\200\333\200\364\201\230 \200\272\200\261 \200\341\200\362","\201\251\200\376 ROM\200\343",""); return; } + u32 sel=0, top=0; + for(;;){ + if(sel=top+10u) top=sel-9u; + char t[64]; const char *g=group_name(g_cat[sel]); int k=0; const char *a="\201\215\200\201: "; while(a[k]){ t[k]=a[k]; k++; } int j=0; while(g[j]){ t[k++]=g[j++]; } t[k]=0; + rect(0,0,128,128,BG);ctext(3,t,WHITE,1);draw_item_pic(g_cat[sel],64,54,64);ko_title(item_name(g_cat[sel]),94);ctext(117,"A \200\305\200\263 B \200\315\201\226 C \200\246\200\260",GREY,1);show(); + wait_release(); + for(;;){ + int c=input(); + if(c==1){ int s=(int)sel+g_step; if(s<0) s=0; if(s>=(int)g_catn) s=(int)g_catn-1; sel=(u32)s; break; } + if(c==K_A){ u32 gr=g_cat[sel]/1000u; u32 s=sel; while(s=640u){ message("\200\201\200\274\200\364 \200\201\200\250 \201\212","",""); return; } +#ifdef BAG_DEL + u32 v=count_edit(id, slot=n) sel=n-1u; + if(sel=top+10u) top=sel-9u; + list_draw("\200\333\200\364\201\230", n, sel, top, bag_row, "B \201\234\201\211 C \200\246\200\260"); + wait_release(); + for(;;){ + int c=input(); + if(c==1){ int s=(int)sel+g_step; if(s<0) s=0; if(s>=(int)n) s=(int)n-1; sel=(u32)s; break; } + if(c==K_A){ sel=(sel+1u)%n; break; } + if(c==K_OK){ + if(sel==0){ cat_pick(); } +#ifdef BAG_DEL + else { u32 slot=g_bag[sel-1]; u32 v=count_edit(list_id(slot), count_get(slot), 0u); if(v<16u && v!=count_get(slot)){ count_set(slot,v); g_dirty=1; } } +#else + else { u32 slot=g_bag[sel-1]; u32 v=count_edit(list_id(slot), count_get(slot)); if(v && v!=count_get(slot)){ count_set(slot,v); g_dirty=1; } } +#endif + break; + } + if(c==K_BACK){ + if(!g_dirty) return; + rect(0,0,128,128,BG); ctext(34,"\200\277\200\212\200\361 \200\377\200\375\201\245\200\223\200\352?",WHITE,1); ctext(60,"\200\302\201\213\200\201 \200\376\200\330\200\373\200\245\200\233\200\234",GREY,1); + ctext(92,"B \200\346",WHITE,1); ctext(106,"C \200\333\200\233\200\352",GREY,1); show(); + if(yes_no()) set_write("\200\333\200\364\201\230 \200\377\200\375 \200\351\200\262"); + return; + } + } + } +} +static void points_menu(void){ + if(set_check_msg()) return; + u32 v=money_get(); if(v>99999u) v=99999u; + u8 dg[5]; { u32 t=v; for(int i=4;i>=0;i--){ dg[i]=(u8)(t%10u); t/=10u; } } + int pos=0; + for(;;){ + rect(0,0,128,128,BG); + ctext(10,"\200\234\200\267\201\235\200\365\201\232",GOLD,1); + for(int i=0;i<5;i++){ + int x=14+i*21; char s[2]={(char)('0'+dg[i]),0}; + if(i==pos) rect(x-2,40,x+17,68,RGB(60,60,110)); + text(x,43,s,i==pos?GOLD:WHITE,3); + } + ctext(80,"\201\260 \200\325\200\372 \200\277\200\212",GREY,1); + ctext(92,"B \200\234\200\362 A \200\364\201\201",GREY,1); + ctext(106,"C \201\216\200\322",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ dg[pos]=(u8)((dg[pos]+10+(g_step>0?1:-1))%10); break; } + if(k==K_A){ if(pos>0) pos--; break; } + if(k==K_BACK) return; + if(k==K_OK){ + if(pos<4){ pos++; break; } + u32 nv=0; for(int i=0;i<5;i++) nv=nv*10u+dg[i]; + if(nv==money_get()) return; + rect(0,0,128,128,BG); ctext(24,"\201\235\200\365\201\232 \200\316\201\202\200\204",WHITE,1); + char s[8]; utoa_(nv,s); ctext(44,s,GOLD,2); ctext(70,"\200\302\201\213\200\201 \200\376\200\330\200\373\200\245\200\233\200\234",GREY,1); + ctext(92,"B \200\346",WHITE,1); ctext(106,"C \200\333\200\233\200\352",GREY,1); show(); + if(yes_no()){ money_put(nv); set_write("\201\235\200\365\201\232 \200\377\200\375 \200\351\200\262"); } + return; + } + } + } +} + +/* ---------------------------------------------------------------- TAMA (1.6.8) */ +/* Characters come with the catalog (fixed byte 2): +6 stage (3 kid, 4 young, 5 adult), +7 field index + 1 (0 = none). */ +static int tama_ok(void){ return (g_cfg.flags & F_TAMA) && g_cfg.version>=6u && g_cfg.tama_off && g_cfg.tama_off+0x20u>2)&7u; } +static const char *stage_name(u32 st){ switch(st){ case 1: return "\200\335"; case 2: return "\200\333\200\222"; case 3: return "\200\357\200\333\200\222"; case 4: return "\200\317\200\375\200\222"; case 5: return "\200\317\201\213"; default: return "?"; } } +static u16 g_chr[256]; static u32 g_chrn; +static void chr_build(u32 st){ g_chrn=0; for(u32 k=0;k255u || (rd16(a+14u)!=old && rd16(a+12u)!=old)) continue; } +#else + if(rd32(a+8u)!=1u || rd16(a+14u)!=old) continue; +#endif + flash_read(a, g_page, PAGE); + u32 before=0;for(u32 z=8;z<0x180;z+=4)before+=*(u32*)(g_page+z); +#ifdef FELD_TAMA_ANY + if((g_page[14]|(g_page[15]<<8))==old) +#endif + { g_page[14]=(u8)nw; g_page[15]=(u8)(nw>>8); } + if((g_page[12]|(g_page[13]<<8))==old){ g_page[12]=(u8)nw; g_page[13]=(u8)(nw>>8); } + if((g_page[0x10A]|(g_page[0x10B]<<8))==old){ g_page[0x10A]=(u8)nw; g_page[0x10B]=(u8)(nw>>8); } + if(rd32(a)+rd32(a+4u)==0u){ + int k=cat_find(nw);u32 names=ko_names();if(k>=0&&names){for(u32 j=0;j<26;j++)g_page[226u+j]=fl(names+26u*(u32)k+j)[0];g_page[0xfcu]=fl(g_cfg.cat_off+8u+28u*(u32)k+6u)[0];g_page[0xfdu]=0;} + u32 sum=rd32(a)-before;for(u32 z=8;z<0x180;z+=4)sum+=*(u32*)(g_page+z);*(u32*)g_page=sum;*(u32*)(g_page+4u)=0u-sum; + } + flash_prog4k(a, g_page); n++; + } + return n; +} +static u32 ko_names(void){u32 a=g_cfg.cat_off+12u+40u*g_cfg.cat_n;return rd32(a)==0x31464f4bu?a+8u+13u*rd32(a+4u):0;} +static void ko_portrait(u32 k){u32 a=ko_names();if(!a)return;u32 o=rd32(a+26u*g_cfg.cat_n+4u*k);if(!o)return;for(u32 y=0;y<32;y++)for(u32 x=0;x<32;x++){u32 c=rd16(g_cfg.cat_off+o+2u*(y*32u+x));if(c!=0xf81fu)rect(32+x*2,27+y*2,34+x*2,29+y*2,(u16)c);}} +static void chr_pick(void){ + static const u8 st_list[3]={3,4,5}; u32 si=t_stage()>=3u && t_stage()<=5u ? t_stage()-3u : 2u; + u32 sel=0, top=0; + chr_build(st_list[si]); + for(;;){ + if(!g_chrn){ message("\201\221\200\266\201\227 \200\341\200\362","\201\251\200\376 ROM\200\343",""); return; } + if(sel>=g_chrn) sel=g_chrn-1u; + if(sel=top+10u) top=sel-9u; + char t[64]; const char *a="\200\234\200\267: "; int k=0; while(a[k]){ t[k]=a[k]; k++; } const char *b=stage_name(st_list[si]); int j=0; while(b[j]) t[k++]=b[j++]; t[k]=0; + rect(0,0,128,128,BG);ctext(3,t,WHITE,1);ko_portrait(g_chr[sel]);char name[64];chr_name(g_chr[sel],name);ko_title(name,94);ctext(117,"A \200\235\200\213 B \200\315\201\226 C \200\246\200\260",GREY,1);show(); + wait_release(); + for(;;){ + int c=input(); + if(c==1){ int s=(int)sel+g_step; if(s<0) s=0; if(s>=(int)g_chrn) s=(int)g_chrn-1; sel=(u32)s; break; } + if(c==K_A){ si=(si+1u)%3u; chr_build(st_list[si]); sel=0; top=0; break; } + if(c==K_BACK) return; + if(c==K_OK){ + u32 kk=g_chr[sel], o=g_cfg.cat_off+8u+28u*kk, nw=rd16(o), st=fl(o+6)[0], old=t_id(); + char nm[64]; chr_name(kk,nm); + rect(0,0,128,128,BG); ctext(24,"\200\277\200\212\201\245 \200\234\200\267\200\214\201\217",WHITE,1); ctext(42,nm,GOLD,1); ctext(54,stage_name(st),GREY,1); + ctext(76,"\200\302\201\213\200\201 \200\376\200\330\200\373\200\245\200\233\200\234",GREY,1); ctext(96,"B \200\346",WHITE,1); ctext(108,"C \200\333\200\233\200\352",GREY,1); show(); + if(!yes_no()) break; + u32 to=g_cfg.tama_off; +#ifdef FELD_TAMA_ANY + /* without the Tama's file the game keeps showing the old Tama: say so instead of "changed" (files first, the + * settings block in RAM stays untouched then) */ + if(old && old!=nw && !tama_files(old, nw)){ message("\200\234\200\267\200\214\201\217 \200\341\200\362","\200\277\200\212\201\243\201\207 \200\334\200\336\200\327\200\233\200\234",""); return; } +#endif + g_set[to+4]=(u8)nw; g_set[to+5]=(u8)(nw>>8); g_set[to+6]=(u8)nw; g_set[to+7]=(u8)(nw>>8); + g_set[to+0x18u]=(u8)((g_set[to+0x18u]&~0x1Cu)|((st&7u)<<2)); +#ifdef FELD_TAMA_ANY +#else + if(old && old!=nw) tama_files(old, nw); +#endif + set_write("\200\234\200\267\200\214\201\217 \200\277\200\212\200\244"); + return; + } + } + } +} +static void level_edit(void){ + u32 v=lv_get(), old=v; + for(;;){ + rect(0,0,128,128,BG); ctext(10,"\201\250\200\317 \200\256\200\276",GOLD,1); + char s[4]; utoa_(v,s); ctext(40,s,WHITE,4); + ctext(80,"\201\260 \200\256\200\276 \200\277\200\212",GREY,1); ctext(94,"B \201\254\200\365 C \200\246\200\260",GREY,1); show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ int nv=(int)v+(g_step>0?1:-1); if(nv<0) nv=0; if(nv>10) nv=10; v=(u32)nv; break; } + if(k==K_A){ v=v>=10u?0u:v+1u; break; } + if(k==K_BACK) return; + if(k==K_OK){ + if(v==old) return; + u32 o=g_cfg.level_off, b=g_set[o]; + /* up: the game celebrates the new level itself; down: nothing to celebrate */ + g_set[o]=(u8)(v>old ? ((b&0xF0u)|v) : ((v<<4)|v)); + set_write("\200\256\200\276 \200\377\200\375 \200\351\200\262"); + return; + } + } + } +} +static void care_full(void){ + rect(0,0,128,128,BG); ctext(24,"\200\241\200\303 \201\256\200\301",WHITE,1); ctext(40,"\200\275\200\304\200\264\200\200\201\250\200\301\200\200\200\210\200\205",GOLD,1); + ctext(70,"\200\302\201\213\200\201 \200\376\200\330\200\373\200\245\200\233\200\234",GREY,1); ctext(92,"B \200\346",WHITE,1); ctext(106,"C \200\333\200\233\200\352",GREY,1); show(); + if(!yes_no()) return; + u32 to=g_cfg.tama_off; + g_set[to+0x1Cu]=6u; g_set[to+0x1Du]=20u; g_set[to+0x10u]=0u; + set_write("\200\241\200\303 \201\256\200\301 \200\351\200\262"); +} +static void big_entry(int y, int sel, const char *name, const char *st, u16 c, u16 stc); +static void tama_menu(void){ + if(set_check_msg()) return; + u32 sel=0; + for(;;){ + rect(0,0,128,128,BG); ctext(2,"\200\234\200\267\200\214\201\217",WHITE,1); + char st[64], nm[64]; nm[0]=0; + utoa_(lv_get(),st); big_entry(12,sel==0,"\200\256\200\276",st,GOLD,GREY); + { u32 id=t_id(); int k=cat_find(id); if(k>=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]==2u) chr_name((u32)k,nm); else utoa_(id,nm); } + big_entry(41,sel==1,"\200\277\200\212",nm,PINK,GREY); + { u32 to=g_cfg.tama_off; char *p=st; const char *a="\200\275\200\304\200\264 "; while(*a) *p++=*a++; utoa_(g_set[to+0x1Cu],p); while(*p) p++; a=" \201\250\200\301 "; while(*a) *p++=*a++; utoa_(g_set[to+0x1Du],p); while(*p) p++; if(g_set[to+0x10u]){ a=" \200\333\201\241"; while(*a) *p++=*a++; } *p=0; } + big_entry(70,sel==2,"\200\241\200\303",st,ORANGE,GREY); + ctext(117,"B \201\254\200\365 C \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ sel=(u32)((int)sel+(g_step>0?1:-1)+3)%3u; break; } + if(k==K_A){ sel=(sel+1u)%3u; break; } + if(k==K_BACK) return; + if(k==K_OK){ if(sel==0) level_edit(); else if(sel==1) chr_pick(); else care_full(); break; } + } + } +} + +/* ---------------------------------------------------------------- Saves (1.6.8) */ +/* settings block of the save in slot i (unpacked into out). 0 = ok */ +static int slot_set(u32 i, u8 *out){ + if(!slot_valid(i)) return 1; + u32 b=slot_base(i), np=rd32(b+8), pos=0; + for(u32 k=0;k>12)){ slot_get(i,pos,n,g_cmp); return lz_unpack(g_cmp,n,out) ? 2 : 0; } + pos+=n; + } + return 3; +} +static int g_sfld[NF_MAX]; static char g_snm[NF_MAX][16]; +/* field and Tama name of each save */ +static void saves_scan(void){ + for(u32 i=0;i=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]==2u){ char t[64]; chr_name((u32)k,t); int z=0;while(t[z]&&z+(ko_pair(t+z)?2:1)<=14)z+=ko_pair(t+z)?2:1;t[z]=0; for(int q=0;q<16;q++){ g_snm[i][q]=t[q]; if(!t[q]) break; } } + } + } +} +static u32 field_pick(void){ /* field for a new game, 0xFF = back */ + u32 nf=nfields(), sel=0; + for(;;){ + rect(0,0,128,128,BG); ctext(2,"\200\330\200\373\201\245 \201\207\200\344",WHITE,1); + for(u32 i=0;i0?1:-1)+(int)nf)%nf; break; } + if(k==K_A){ sel=(sel+1u)%nf; break; } + if(k==K_BACK) return 0xFFu; + if(k==K_OK) return sel; } + } +} +static void saves_menu(int with_app, int top){ + saves_scan(); + u32 ns=g_cfg.nslots>NF_MAX?NF_MAX:g_cfg.nslots; + u32 na = with_app ? (g_napp>1u ? 1u : g_napp) : 0u, n=ns+na, sel = na ? ns : (u32)g_act; + for(;;){ + rect(0,0,128,128,BG); + if(n<=4u) ctext(2, top ? "PARAMIX" : "\200\377\200\375 \200\272\200\261", WHITE,1); + for(u32 i=0;i4u && g_snm[i][0]){ for(int q=0;g_snm[i][q];q++) *p++=g_snm[i][q]; if(f>=0) c=fcol((u32)f); } /* compact: the Tama, field by colour */ + else { const char *e=f>=0 ? fname((u32)f) : "?"; while(*e) *p++=*e++; if(g_snm[i][0]){ *p++=' '; for(int q=0;g_snm[i][q];q++) *p++=g_snm[i][q]; } if(f>=0) c=fcol((u32)f); } + *p=0; if((int)i==g_act) stc=WHITE; + } else { const char *e=g_napp>1u ? "\201\237\200\260\200\217\200\253" : g_appnm[0]; int k=0; while(e[k] && k<11){ nm[k]=e[k]; k++; } nm[k]=0; e=g_napp>1u?"\200\315\201\226":"\200\330\200\373"; int q=0; while(e[q]){ st[q]=e[q]; q++; } st[q]=0; } + if(n>4u){ + int y=2+(int)i*16; + if(i==sel){ rect(1,y,127,y+15,c); rect(2,y+1,126,y+14,BG); } + text(5,y+4,nm,c,1); int w=text_w(st,1); int x=123-w; if(x<48) x=48; textn(x,y+4,st,(124-x)/6,stc,1); + } else big_entry((n<4u?12:1)+(int)i*29, i==sel, nm, st, c, stc); + } + ctext(117,"B \201\254\200\365 C \200\246\200\260",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ sel=(u32)((int)sel + (g_step>0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK){ if(top) leave(); return; } + if(k==K_OK){ + if(sel>=ns){ if(g_napp>1u) apps_menu(0); else start_app_i(0); break; } + if((int)sel==g_act){ if(top) leave(); return; } + int has=slot_valid(sel); u32 fld; + if(has){ fld=(u32)g_sfld[sel]; if(g_sfld[sel]<0){ message("\200\377\200\375","\200\366\200\222 \200\332\201\233",""); break; } } + else { fld=field_pick(); if(fld==0xFFu) break; } + rect(0,0,128,128,BG); + char t[8]="\200\377\200\375 "; t[5]=(char)('1'+sel); t[6]=0; + ctext(14, has ? "\200\306\200\255\200\347\200\222" : "\200\313 \200\211\200\367 \201\207\200\344", WHITE,1); ctext(28,t,WHITE,2); + ctext(52,fname(fld),fcol(fld),1); if(has && g_snm[sel][0]) ctext(64,g_snm[sel],GREY,1); + ctext(80,"\200\222\201\205 \200\377\200\375 \200\357\201\207",GREY,1); + ctext(96,"B \200\346",WHITE,1); ctext(108,"C \200\333\200\233\200\352",GREY,1); show(); + if(yes_no()) field_switch2(sel, has, fld); + break; + } + } + } +} + +/* ---------------------------------------------------------------- Main menu */ +static void main_menu(void){ + int fields = (g_cfg.flags & F_FIELDS) && g_cur>=0 && g_cfg.nfields>=2u; + u32 kinds[5], n=0; /* 0 field, 1 items, 2 Tamapoints, 3 program, 4 Tama */ + if(fields) kinds[n++]=0; + if(g_cfg.flags & F_BAG){ kinds[n++]=1; kinds[n++]=2; } + if(tama_ok()) kinds[n++]=4; + if(g_napp) kinds[n++]=3; + u32 sel = g_napp ? n-1u : 0u; + for(;;){ + int ok=set_load()==0; + rect(0,0,128,128,BG); + ctext(3,"\200\234\200\267\200\214\201\217 \201\234\201\211",WHITE,1); + for(u32 i=0;i0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK) leave(); + if(k==K_OK){ + switch(kinds[sel]){ case 0: if(saves_mode()) saves_menu(0,0); else field_menu(0,0); break; case 1: items_menu(); break; case 2: points_menu(); break; case 4: tama_menu(); break; default: if(g_napp>1u) apps_menu(0); else start_app_i(0); } + break; + } + } + } +} + +static void run(void){ + rect(0,0,128,128,BG); show(); +#ifndef HOST + REG(GPIO2+0x04) &= ~3u; g_enc_last=REG(GPIO2) & 3u; + clock_start(); +#endif + app_detect(); + apps_detect(); +#ifdef FELD_AUTO +#ifdef HOST + { const char *e; if((e=getenv("AUTO_MB"))) h_mb=(u32)strtoul(e,0,16); if((e=getenv("AUTO_GPIO"))) h_gpio=(u32)strtoul(e,0,16); if((e=getenv("AUTO_CNT"))) h_cnt=(u32)strtoul(e,0,10); +#ifdef FELD_SEEN + if((e=getenv("AUTO_SEEN"))) h_seen=(u32)strtoul(e,0,16); +#endif + } +#endif +#ifdef FELD_BFALL + b_fallback(); +#endif + if(auto_go()){ +#if defined(FELD_CLEAN) && defined(CLEAN_AUTO) + if(clean_mode() && !clk_now() && CLK_ASK()){ lset_load(); clock_menu(1); } /* new batteries: the time first, then the main program */ +#endif + start_app_i(0); + } +#endif + g_cur = field_now(); + int fields = (g_cfg.flags & F_FIELDS) && g_cur>=0 && g_cfg.nfields>=2u; + g_act=g_cur; + if(fields && saves_mode()){ + /* the live save's number: from its settings block, else (menus before 1.6.8, or a save that never + * met this menu) the field's slot if it is free, else the first free slot */ + flash_read(SET_A, g_page, PAGE); + u32 v=set_ok(g_page) ? g_page[SAVE_OFF] : 0u; + if(v>=1u && v<=g_cfg.nslots) g_act=(int)v-1; + else { + if((u32)g_act>=g_cfg.nslots || slot_valid((u32)g_act)){ g_act=0; for(u32 j=0;j1u) apps_menu(1); + if(g_napp) start_app_i(0); + leave(); +} + +#ifdef HOST +void host_main(void){ + for(u32 i=0;i +_Static_assert(offsetof(Cfg,flags)==36 && offsetof(Cfg,id_c)==40 && offsetof(Cfg,nfields)==48 && offsetof(Cfg,field_name)==68 + && offsetof(Cfg,field_col)==116 && offsetof(Cfg,fac_common)==132 && offsetof(Cfg,fac_field)==196 + && offsetof(Cfg,money_off)==260 && offsetof(Cfg,cat_n)==276 && offsetof(Cfg,field_byte)==280 && offsetof(Cfg,six_off)==288 && offsetof(Cfg,field_name2)==300 + && offsetof(Cfg,field_col2)==324 && offsetof(Cfg,fac_field2)==332 && offsetof(Cfg,slot_off2)==364 && offsetof(Cfg,six_map)==372 && CFG_SIZE_OK && offsetof(Cfg,main_src)==600 && offsetof(Cfg,dl_src)==500 && offsetof(Cfg,tama_off)==492 && offsetof(Cfg,name0)==380 && offsetof(Cfg,napps)==392 && offsetof(Cfg,apps)==396, "settings block layout"); +#define NF_MAX 6u + +/* Saved field (header page at the start of its slot). res[0] = POOL_MAGIC (1.2.12): the + * packed data lies in the pages dpg[0..res[1]-1] of the shared pool (all slot pages except + * the header pages), so one field can use the room the other fields do not need. Without + * it (older menus) the data follows the header in the field's own slot. */ +#define POOL_MAGIC 0x4C4F4F50u /* "POOL" */ +#define PEND_MAGIC 0x444E4550u /* "PEND" in res[2]: switch from this field under way (1.6.8) */ +#define DPG_MAX 1024u +typedef struct { + u32 magic, field, npages, bytes, sum, res[3]; + struct { u16 page, clen; } e[NPAGE_MAX]; + u16 dpg[DPG_MAX]; +} SlotHdr; +_Static_assert(sizeof(SlotHdr)<=4096u, "slot header fits one page"); + +#define GPIO2 0x4001A000u + +static u16 g_fb[128*128]; +static u8 g_page[PAGE] __attribute__((aligned(4))); /* uncompressed page (1.6.8: all flash buffers word aligned, the flash DMA needs it: error 41) */ +static u8 g_cmp[PAGE+PAGE/8+16] __attribute__((aligned(4))); /* one compressed page */ +static u8 g_out[PAGE] __attribute__((aligned(4))); /* write buffer */ +static SlotHdr g_hdr; +static u16 g_head[4096], g_prev[4096]; +static u8 g_ff[PAGE] __attribute__((aligned(4))); /* empty page: erase = write an empty page */ +static u8 g_set[PAGE] __attribute__((aligned(4))); /* settings block being edited */ + +#ifdef HOST +#include "host.h" +#else +#define FLASH_BASE ((volatile u8*)0x60000000u) +#endif +static u32 rd32(u32 a){ return *(const volatile u32*)(FLASH_BASE + a); } +static u32 rd16(u32 a){ return *(const volatile u16*)(FLASH_BASE + a); } +static const volatile u8* fl(u32 a){ return (const volatile u8*)(FLASH_BASE + a); } + +/* ---------------------------------------------------------------- Display */ +#define RGB(r,g,b) ((u16)((((r)>>3)<<11)|(((g)>>2)<<5)|((b)>>3))) +static void rect(int x0,int y0,int x1,int y1,u16 c){ + if(x0<0)x0=0; if(y0<0)y0=0; if(x1>128)x1=128; if(y1>128)y1=128; + for(int y=y0;y=0x60 && ch!='x') ch-=32; + const u8 *g=g_font[glyph(ch)&127]; + for(int r=0;r<7;r++) for(int k=0;k<5;k++) if(g[r]&(16>>k)) rect(x+k*sc,y+r*sc,x+k*sc+sc,y+r*sc+sc,c); + } +} +static void text(int x,int y,const char *s,u16 c,int sc){ textn(x,y,s,999,c,sc); } +static void ctext(int y,const char *s,u16 c,int sc){ text((128-text_w(s,sc))/2,y,s,c,sc); } +static void show(void){ hw_push(g_fb,128,0,0,128,128); } +static void utoa_(u32 v, char *s){ char t[12]; int n=0; do{ t[n++]=(char)('0'+v%10u); v/=10u; }while(v); for(int i=0;iNF_MAX ? NF_MAX : g_cfg.nfields; } + +static void progress(const char *what, u32 n, u32 tot){ + rect(0,40,128,100,BG); + ctext(44,what,WHITE,1); + rect(14,62,114,72,GREY); rect(15,63,113,71,BG); + u32 w = tot ? (98u*n)/tot : 0; if(w>98u) w=98u; + rect(15,63,15+(int)w,71,RGB(40,120,255)); + hw_push(g_fb,128,0,40,128,100); +} + +/* ---------------------------------------------------------------- Buttons */ +static const signed char g_qd[16]={0,-1,1,0, 1,0,0,-1, -1,0,0,1, 0,1,-1,0}; +static u32 g_enc_last; static int g_enc_acc; +static u32 g_btn_last; +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +static u32 g_tick_last, g_ms, g_sub, g_enc_t; +static void clock_start(void){ SYST_RVR=0xFFFFFFu; SYST_CVR=0; SYST_CSR=5u; g_tick_last=SYST_CVR; } +static void clock_poll(void){ + u32 c=SYST_CVR, d=(g_tick_last-c)&0xFFFFFFu; g_tick_last=c; + g_sub+=d; while(g_sub>=96000u){ g_sub-=96000u; g_ms++; } +} +#define K_A 10 +#define K_OK 2 +#define K_BACK 3 +/* returns: wheel steps (+n/-n, 1..9), K_OK (B or wheel), K_BACK (C), K_A (A), 0 nothing. + * The wheel counts once it has been still for 25 ms after a movement, so it does + * not matter how many edges one detent produces. Fast turning gives several steps. */ +static int g_step; +#ifdef HOST +static int input(void){ return host_input(&g_step); } +#else +static int input(void){ + hw_wdt_feed(); clock_poll(); + u32 n=REG(GPIO2) & 3u; + if(n!=g_enc_last){ g_enc_acc+=g_qd[(g_enc_last<<2)|n]; g_enc_last=n; g_enc_t=g_ms; } + else if(g_enc_acc && g_ms-g_enc_t>=25u){ + int a=g_enc_acc<0 ? -g_enc_acc : g_enc_acc; int st=(a+2)/4; if(st<1) st=1; if(st>9) st=9; + g_step = g_enc_acc>0 ? st : -st; g_enc_acc=0; return 1; } + u32 b=hw_buttons(), dn=b & ~g_btn_last; g_btn_last=b; + if(dn & BTN_A) return K_A; + if(dn & (BTN_B|BTN_WHEEL)) return K_OK; + if(dn & BTN_C) return K_BACK; + return 0; +} +#endif +#ifdef HOST +static void delay_loop(u32 n){ (void)n; } +#else +static void delay_loop(u32 n){ for(volatile u32 i=0;ibest){ best=l; boff=i-j; if(l==LZ_MAX) break; } + j=g_prev[j]; tries++; + } + } + u32 step = best>=3u ? best : 1u; + if(best>=3u){ + u32 ln=best-3u; + out[fpos]|=(u8)(1u<>8); } + else { u32 v=((boff-1u)<<4)|15u; out[o++]=(u8)v; out[o++]=(u8)(v>>8); out[o++]=(u8)(ln-15u); } + } else out[o++]=in[i]; + bit++; + for(u32 k=0;k=n) return 1; + u32 f=in[i++]; + for(u32 b=0;b<8u && on) return 2; + u32 v=in[i] | ((u32)in[i+1]<<8); i+=2; + u32 off=(v>>4)+1u, len=(v&15u)+3u; + if((v&15u)==15u){ if(i>=n) return 2; len+=in[i++]; } + if(off>o || o+len>PAGE) return 3; + for(u32 k=0;k=n) return 4; out[o++]=in[i++]; } + } + } + return i==n ? 0 : 5; +} + +/* ---------------------------------------------------------------- Flash */ +/* Erase by programming an empty page: the program command also erases on the + * device (confirmed), a plain erase has not been tested. */ +static void erase_page(u32 a){ flash_prog4k(a, g_ff); } +static int page_ff(u32 a){ const volatile u32 *p=(const volatile u32*)(FLASH_BASE+a); for(u32 i=0;i>1)^0xA001u : c>>1; } + return c & 0xFFFFu; +} +static void stamp(u8 *p){ u32 c=crc16arc(p,4,PAGE); p[0]=(u8)c; p[1]=(u8)(c>>8); p[2]=(u8)~c; p[3]=(u8)(~c>>8); } + +/* Fields: index 0..nfields-1, ID g_cfg.field_id[i] */ +static u32 cur_id(void){ return rd32(g_cfg.id_page); } +static int field_index(u32 id){ for(u32 i=0;i=0 ? f : field_index(cur_id()); +} +static u32 slot_base(u32 i){ + if(g_cfg.slot_off2 && g_cfg.slot_n1 && i>=g_cfg.slot_n1) return g_cfg.slot_off2 + (i-g_cfg.slot_n1)*g_cfg.slot_size; + return g_cfg.slot_off + i*g_cfg.slot_size; } +static u32 spp(void){ return g_cfg.slot_size/PAGE - 1u; } /* pool pages per slot */ +static u32 pool_n(void){ return g_cfg.nslots*spp(); } +static u32 pool_addr(u32 k){ return slot_base(k/spp()) + (k%spp()+1u)*PAGE; } +static int slot_pool(u32 b){ return rd32(b+20)==POOL_MAGIC; } +static int slot_valid(u32 i){ + u32 b=slot_base(i); + if(rd32(b)!=SLOT_MAGIC || rd32(b+4)!=i+1u) return 0; /* slot ID = field number + 1 */ + u32 np=rd32(b+8), by=rd32(b+12); + if(np>NPAGE_MAX) return 0; + if(!slot_pool(b)) return by<=g_cfg.slot_size-PAGE; + u32 nd=rd32(b+24); + if(nd>DPG_MAX || by>nd*PAGE) return 0; + for(u32 k=0;k=pool_n()) return 0; + return 1; +} +/* Read n bytes of the packed data of slot i from position pos. */ +static void slot_get(u32 i, u32 pos, u32 n, u8 *dst){ + u32 b=slot_base(i); int pool=slot_pool(b); + while(n){ + u32 pg=pos/PAGE, o=pos%PAGE, c=PAGE-o; if(c>n) c=n; + u32 a = pool ? pool_addr(rd16(b+offsetof(SlotHdr,dpg)+2u*pg)) : b+PAGE+pg*PAGE; + for(u32 k=0;k>3]|=(u8)(1u<<(x&7u)); } } + else { u32 nd=(rd32(b+12)+PAGE-1u)/PAGE; for(u32 k=0;k>3]|=(u8)(1u<<(x&7u)); } } + } +} +/* Next free pool page for slot fi (its own pages first), marks it. 0xFFFF = full. */ +static u32 pool_take(u32 fi){ + u32 n=pool_n(); if(n>sizeof(g_used)*8u) n=sizeof(g_used)*8u; + for(u32 r=0;r>3]&(1u<<(x&7u)))){ g_used[x>>3]|=(u8)(1u<<(x&7u)); return x; } + } + return 0xFFFFu; +} +static void write_id(u32 id){ + u32 *w=(u32*)g_out; + for(u32 i=0;iNPAGE_MAX) return 10; + erase_page(b); /* invalidate the header first */ + for(u32 i=0;i>12); g_hdr.e[np].clen=(u16)n; np++; + for(u32 k=0;k=DPG_MAX) return 11; + flash_prog4k(pool_addr(x),g_out); g_hdr.dpg[nd++]=(u16)x; on=0; } } + by+=n; + progress("SAVING", ++done, tot*2u); + } + if(on){ u32 x=pool_take(fi); if(x==0xFFFFu || nd>=DPG_MAX) return 11; + for(u32 k=on;k>12)){ + u32 n=rd16(b+34+ix2*4); + if(set==(int)pass){ slot_get(fi,o2,n,g_cmp); if(lz_unpack(g_cmp, n, g_page)) return 21; want=1; } + o2+=n; ix2++; + if(!want) continue; + } else if(set!=(int)pass) continue; + if(want){ if(!flash_same(a,g_page,PAGE)) flash_prog4k(a,g_page); if(!flash_same(a,g_page,PAGE)) return 22; } + else if(!page_ff(a)){ erase_page(a); if(!page_ff(a)) return 23; } + if(!pass && !(++done & 7u)) progress("LOADING", done, tot); + } + if(!fresh && ix2!=np) return 24; + } + (void)ix; + return 0; +} + +/* ---------------------------------------------------------------- Screens */ +static void leave(void){ + rect(0,0,128,128,0); show(); +#ifdef PARA_BACK + para_back_fix(g_set); +#endif + hw_back_to_paradise(); +} +static void error_screen(int code){ + rect(0,0,128,128,BG); + ctext(30,"ERROR",RED,2); + char s[12]="CODE 00"; s[5]=(char)('0'+code/10); s[6]=(char)('0'+code%10); + ctext(56,s,WHITE,1); + if(code==10||code==11) ctext(68,"SAVE TOO BIG",WHITE,1); /* the field stays as it is */ + ctext(84,"B OR C: BACK",GREY,1); + show(); wait_release(); + for(;;){ int k=input(); if(k==K_OK||k==K_BACK) leave(); } +} +static void message(const char *l1, const char *l2, const char *l3){ + rect(0,0,128,128,BG); + ctext(34,l1,WHITE,1); ctext(48,l2,WHITE,1); ctext(62,l3,WHITE,1); + ctext(100,"C BACK",GREY,1); + show(); wait_release(); + for(;;){ int k=input(); if(k==K_OK||k==K_BACK) return; } +} +static void done_screen(const char *what, u16 col){ + rect(0,0,128,128,BG); + ctext(40,"DONE",WHITE,2); + ctext(66,what,col,1); + show(); + delay_loop(6000000u); + leave(); +} + +/* Program in the stub? 0 = none, 1 = DOOM, 2 = TamaEmu, 3 = other, 4 = T7Emu */ +static u32 g_app; +static void app_detect(void){ + u32 src=rd32(g_cfg.stub_off+8u); + if(src<0x10000000u || src>=0x11000000u){ g_app=0; return; } + u32 off=src-0x10000000u+XIP_DEC; + u32 m=rd32(off+0x140u); + g_app = m==0x43584D50u ? 2u : m==0x37584D50u ? 4u : m==0x38584D50u ? 5u : 3u; + for(u32 i=0x140u;i<0x400u;i+=4u) if(rd32(off+i)==0x434D4450u){ g_app=1u; break; } +} +static const char *const g_appname[6]={"","DOOM","TAMAEMU","PROGRAM","T7EMU","T18EMU"}; +static void start_app(void){ + rect(0,0,128,128,0); show(); +#ifdef HOST + host_exit("APP"); +#endif + ((void(*)(void))(0x10000000u + g_cfg.stub_off - XIP_DEC + 1u))(); + for(;;){} +} +/* All programs: 0 = the stub's own (if any), then the ones of the settings block (version 5) */ +static u32 g_napp, g_appsrc[APPS_MAX+9], g_dl, g_sx; /* g_dl: index of DOWNLOAD + 1, g_sx: of SETTINGS + 1 (start device) */ +static char g_appnm[APPS_MAX+9][13]; +static void apps_detect(void){ + g_napp=0; + if(g_app){ + const volatile char *n=g_cfg.version>=5u && g_cfg.name0[0] ? g_cfg.name0 : g_appname[g_app]; + for(int k=0;k<12;k++){ g_appnm[0][k]=n[k]; if(!n[k]) break; } g_appnm[0][12]=0; + g_appsrc[0]=0; g_napp=1; + } + /* the stub must have the entry at +0x0C (cpsid i; mov r4, r0) */ + if(g_cfg.version<5u || rd32(g_cfg.stub_off+0x0Cu)!=0x4604B672u) return; + for(u32 i=0;i=8u ? 6u : 0u);i++){ + const volatile char *nm = i=0x11000000u) continue; + for(int k=0;k<12;k++){ g_appnm[g_napp][k]=nm[k]; } g_appnm[g_napp][12]=0; + g_appsrc[g_napp++]=s; + } +#ifdef FELD_AUTO + /* 1.6.9 test13: the chosen main program first */ + if(g_cfg.version>=9u && g_cfg.main_src){ + for(u32 j=1;j0;m--){ g_appsrc[m]=g_appsrc[m-1]; for(int k=0;k<13;k++) g_appnm[m][k]=g_appnm[m-1][k]; } + g_appsrc[0]=s; for(int k=0;k<13;k++) g_appnm[0][k]=t[k]; + break; + } + } +#endif + /* start device: our flash app as the last entry, so the PC can write the ROM again (the Paradise's own + * download screen is not reachable any more) */ + g_dl=0; g_sx=0; +#ifndef NO_LSET + /* start device (1.6.8): sound and display time, the Paradise's own settings screens are gone */ + if(g_cfg.flags & 16u){ + const char *d="SETTINGS"; int k=0; while(d[k]){ g_appnm[g_napp][k]=d[k]; k++; } g_appnm[g_napp][k]=0; + g_appsrc[g_napp++]=0; g_sx=g_napp; + } +#endif + if((g_cfg.flags & 16u) && g_cfg.version>=7u && g_cfg.dl_src>=0x10000000u && g_cfg.dl_src<0x11000000u){ + const char *d="DOWNLOAD"; int k=0; while(d[k]){ g_appnm[g_napp][k]=d[k]; k++; } g_appnm[g_napp][k]=0; + g_appsrc[g_napp++]=g_cfg.dl_src; g_dl=g_napp; + } +} +#ifdef FELD_AUTO +/* 1.6.9 test13: start the main program by itself in the start device, once per switching on (as the stub's autostart, + * same mailbox 0x20000FFC): "PMXL" a program went back on purpose, "PMXM" the menu decided already, "PMXR" restart + * while the main program ran (reset button); anything else: switched on (seconds counter below 30) or woken from deep + * sleep. B held: stay in the menu. */ +#ifdef HOST +#include +static u32 h_mb, h_gpio=0xFFFFFFFFu, h_cnt; /* host: from the environment (AUTO_MB, AUTO_GPIO, AUTO_CNT) */ +#define AUTO_MB (&h_mb) +static u32 h_seen; +#define AUTO_SEEN h_seen +#define AUTO_GPIO h_gpio +#define AUTO_CNT h_cnt +#else +#define AUTO_MB ((volatile u32*)0x20000FFCu) +#define AUTO_SEEN REG(0x20000FF8u) +#define AUTO_GPIO REG(0x40018000u) +#define AUTO_CNT REG(0x45000304u) +#endif +#define MB_L 0x4C584D50u +#define MB_S 0x53584D50u /* "PMXS": this "PMXL" was seen (FELD_SEEN) */ +#define MB_M 0x4D584D50u +#define MB_R 0x52584D50u +static void start_app_i(u32 i); +#ifdef FELD_CLEAN +static int clean_mode(void); +#endif +#ifdef FELD_BFALL +/* 1.7.2 test19: C held after switching on (or after the reset button) starts the flash app (B there already means: no + * autostart) (DOWNLOAD): a way back + * when a program or a save leaves the screen black. Not when a program went back on purpose ("PMXL"), not when the + * Paradise woke from deep sleep (mailbox lost, clock ran). Without the Paradise the menu only starts at switching on, + * after a reset or when a program went back. */ +static void b_fallback(void){ + if(!g_dl || (AUTO_GPIO & 0x400u)) return; +#ifdef FELD_BFALL_NOA + if(!(AUTO_GPIO & 0x200u)) return; /* 1.7.3 test29: not with A held too (A and C: the program key) */ +#endif + volatile u32 *mb=AUTO_MB; u32 m=*mb; + if(m==MB_L) return; +#ifdef FELD_CLEAN + if(!clean_mode()) +#endif + if(AUTO_CNT>=30u && m!=MB_R && m!=MB_M) return; + *mb=MB_M; + start_app_i(g_dl-1u); +} +#endif +#ifdef FELD_AUTODBG +static u32 g_adbg[4]; /* 1.7.3 test8: the autostart's mailbox, GPIO0 and B decision, shown small on the home screen */ +#endif +static int auto_go(void){ + if(g_cfg.version<9u || !(g_cfg.vflags & 1u) || !g_napp || !(g_cfg.flags & F_LAUNCH)) return 0; + volatile u32 *mb=AUTO_MB; u32 m=*mb; +#if defined(FELD_CLEAN) && defined(CLEAN_AUTO) + /* 1.7.2 test19: without the Paradise the seconds counter says nothing about switching on (Bernd: the main program + * did not start). The menu only starts at switching on, after a reset or when a program went back: start the main + * program unless a program went back ("PMXL"). test21: "PMXM" of an earlier menu stays in the RAM over a write and + * a reset (Bernd: clock set, then the menu): it no longer counts, and "PMXL" counts once. */ + if(clean_mode()){ +#ifdef FELD_BSETTLE + /* 1.7.3 test8: B is only "held" when it reads low over 5 looks a few ms apart (the pins may not have settled + * right after the start, a reset could take that for B and show the menu) */ + int bh=1; for(u32 k=0;k<5u && bh;k++){ for(volatile u32 t=0;t<60000u;t++){} if(AUTO_GPIO & 0x800u) bh=0; } +#else + int bh=!(AUTO_GPIO & 0x800u); +#endif +#ifdef FELD_AUTODBG + g_adbg[0]=m; g_adbg[1]=AUTO_GPIO; g_adbg[2]=1u+(u32)bh; g_adbg[3]=AUTO_SEEN; +#endif +#ifdef FELD_SEEN + /* 1.7.3 test9: Bernd: back from T18Emu with the wheel, then reset: the mailbox still said "PMXL" at the reset (menu + * instead of the autostart). The menu notes that it has shown itself for this "PMXL" in the word before the mailbox + * (the programs set it to 0 when they write "PMXL"); a "PMXL" seen already is an old one: a reset, autostart. */ + if(m==MB_L && AUTO_SEEN) m=0; /* test12: any other word there is old too (the Paradise's stub counts in it: a device + * written right after a program had gone back to the Paradise showed the menu once) */ + if(m==MB_L) AUTO_SEEN=MB_S; +#endif + if(bh || m==MB_L){ *mb=0; return 0; } + *mb=MB_R; return 1; + } +#endif + if(!(AUTO_GPIO & 0x800u)){ *mb=0x4D584D50u; return 0; } + if(m==0x4C584D50u || m==0x4D584D50u) return 0; + if(m!=0x52584D50u && AUTO_CNT>=30u){ *mb=0x4D584D50u; return 0; } + *mb=0x52584D50u; return 1; +} +#endif +static void start_app_i(u32 i){ + if(!g_appsrc[i]){ start_app(); return; } + rect(0,0,128,128,0); show(); +#ifdef HOST + host_exit(g_appnm[i]); +#endif + ((void(*)(u32))(0x10000000u + g_cfg.stub_off - XIP_DEC + 0x0Cu + 1u))(g_appsrc[i]); + for(;;){} +} + +/* Large menu entry: name in large text, state in small text below. */ +static int g_small; /* five entries: lower boxes, state at the right */ +static void big_entry(int y, int sel, const char *name, const char *st, u16 c, u16 stc){ + if(g_small){ + if(sel){ rect(3,y,125,y+22,c); rect(5,y+2,123,y+20,BG); } + text(9,y+4,name,c,2); + int w=text_w(st,1), x=121-w, nx=9+text_w(name,2)+4; if(x=6u && g_cfg.nslots>=2u; } +/* save mode: the number of the live save goes into its settings block */ +static void act_mark(u32 j){ + flash_read(SET_A, g_page, PAGE); + if(!set_ok(g_page) || g_page[SAVE_OFF]==j+1u) return; + g_page[SAVE_OFF]=(u8)(j+1u); stamp(g_page); + flash_prog4k(SET_A, g_page); flash_prog4k(SET_B, g_page); +} +/* Live save to slot g_act, then slot tgt (has) or a fresh start on field fld into the live area. */ +static void field_switch2(u32 tgt, int has, u32 fld){ + rect(0,0,128,128,BG); ctext(8,"PLEASE WAIT",WHITE,1); ctext(20,"DO NOT SWITCH OFF",GREY,1); show(); + int e=stash((u32)g_act); + if(e){ erase_page(slot_base((u32)g_act)); error_screen(e); } + e=restore(has ? tgt : fld,!has); + if(e) error_screen(e); + if(fid(fld)){ write_id(fid(fld)); if(cur_id()!=fid(fld)) error_screen(30); } + if(field_now()!=(int)fld) error_screen(31); + if(saves_mode()) act_mark(tgt); + { u32 b=slot_base((u32)g_act); flash_read(b, g_out, PAGE); g_out[28]=g_out[29]=g_out[30]=g_out[31]=0; flash_prog4k(b, g_out); } /* switch done */ + if(has) erase_page(slot_base(tgt)); + done_screen(fname(fld), fcol(fld)); +} +static void field_switch(u32 tgt, int has){ field_switch2(tgt, has, tgt); } +static int field_confirm(u32 tgt, int has){ + rect(0,0,128,128,BG); + ctext(14,"SWITCH TO",WHITE,1); + ctext(30,fname(tgt),fcol(tgt),2); + ctext(54, has ? "SAVED GAME" : "FIELD STARTS", WHITE,1); + ctext(66, has ? "WILL BE LOADED" : "FROM SCRATCH", WHITE,1); + ctext(92,"B = YES",WHITE,1); + ctext(106,"C = NO",GREY,1); + show(); + return yes_no(); +} +static void big_entry(int y, int sel, const char *name, const char *st, u16 c, u16 stc); +static int launch_mode(void){ return (g_cfg.flags & F_LAUNCH) != 0u; } +/* Launcher ROM: after g_idle_ms without a key the display goes dark until the next key (1.6.8). + * The time is kept in the Paradise's settings block at IDLE_OFF (0 = 2 minutes, else index + 1). */ +#define IDLE_OFF 0xF07u +static const u32 g_idle_tab[5]={30000u,60000u,120000u,300000u,0u}; +static const char *const g_idle_nm[5]={"30 S","1 MIN","2 MIN","5 MIN","NEVER"}; +static u32 g_idle_t, g_idle_ms; +#ifdef BAT_SHOW +#ifdef HOST +static void bat_text(char *s){ const char *t="2.84V 80%"; int i=0; while((s[i]=t[i])) i++; } +#else +#include "../../../emu/src/emu/batt.h" +#endif +#endif +static void lset_menu(void); +#ifdef FELD_CLEAN +static int clean_mode(void); +#define SX_TEXT (clean_mode() ? "CLOCK, DISPLAY" : "SOUND, DISPLAY") +#else +#define SX_TEXT "SOUND, DISPLAY" +#endif +#if defined(FELD_PW) && !defined(HOST) +/* test23 (switch FELD_PW): the display dark, the menu waited for a key in a tight loop at the full clock and used + * about as much power as with the display on. Now deep sleep (as TamaEmu, EMU_PW) between the polls: a key wakes at + * once (edge interrupt on P0.8..11, the wheel on P2.0/P2.1), the RTC every second when it runs on 1 s (the wheel is seen then). The interrupts + * stay masked: the pending one only ends the WFI, its flags are cleared here. */ +#define FP_ISO REG(0x45000200u) +#define FP_PMU REG(0x45000300u) +#define FP_GP0(o) REG(0x40018000u + (o)) +#define FP_KEYS 0xF00u +#define FP_GP2(o) REG(0x4001A000u + (o)) +#define FP_IRQS ((1u << 2) | (1u << 26) | (1u << 28)) /* RTC, GPIO0, GPIO2 (the wheel, P2.0/P2.1) */ +__attribute__((noinline)) static void dark_wait(void){ + u32 pm; __asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory"); + for(;;){ + if(input()) break; + if(hw_buttons() || g_enc_acc) continue; /* a key or the wheel being read: poll on */ + u32 iso=FP_ISO, rtc=(iso & 0x80u) && !(iso & 7u), csr=SYST_CSR; + if(rtc) FP_ISO = iso & ~8u; /* RTC_WKP 0: the RTC wakes */ + FP_GP0(0x0C) &= ~FP_KEYS; FP_GP0(0x10) |= FP_KEYS; FP_GP0(0x20) = FP_KEYS; FP_GP0(0x18) |= FP_KEYS; /* both edges */ + FP_GP2(0x0C) &= ~3u; FP_GP2(0x10) |= 3u; FP_GP2(0x20) = 3u; FP_GP2(0x18) |= 3u; + REG(0xE000E280u) = FP_IRQS; REG(0xE000E100u) = rtc ? FP_IRQS : FP_IRQS & ~(1u << 2); + SYST_CSR = 0; + FP_PMU = (FP_PMU & ~0x47u) | 2u; /* DSLEEP_EN */ + __asm__ volatile("dsb\n wfi\n isb" ::: "memory"); + FP_PMU = FP_PMU & ~0x47u; + REG(0xE000E180u) = FP_IRQS; FP_GP0(0x18) &= ~FP_KEYS; FP_GP0(0x20) = FP_KEYS; FP_GP2(0x18) &= ~3u; FP_GP2(0x20) = 3u; + FP_PMU = (FP_PMU & ~0x47u) | 0x10u; /* RTC_FLAG: write 1 */ + REG(0xE000E280u) = FP_IRQS; + if(rtc) FP_ISO = (FP_ISO & ~8u) | (iso & 8u); + SYST_CVR = 0; SYST_CSR = csr; g_tick_last = SYST_CVR; + for(u32 t=0;t<20000u;t++) if(hw_buttons()) break; /* the pins settle after the wake */ + } + __asm__ volatile("msr primask, %0" :: "r"(pm) : "memory"); +} +#elif defined(FELD_PW) +static void dark_wait(void){ while(!input()){} } +#endif +static int idle_input(void){ + int k=input(); + if(k){ g_idle_t=g_ms; return k; } +#ifndef HOST + if(launch_mode() && g_idle_ms && g_ms-g_idle_t>=g_idle_ms){ + hw_backlight(0); +#ifdef FELD_PW + dark_wait(); +#else + while(!input()){} +#endif + hw_backlight(1); wait_release(); g_idle_t=g_ms; + return -1; /* redraw */ + } +#endif + return 0; +} +/* Program list (more than one program, or the launcher's home screen). Returns on C unless top. */ +static void apps_menu(int top){ + u32 n=g_napp, sel=0, first=0; /* first: top row of the list (1.6.8: more than 8 entries scroll) */ + g_idle_t=g_ms; + for(;;){ + rect(0,0,128,128,BG); + int y0 = n>=4u ? 1 : 12; + if(n<4u) ctext(2, launch_mode() ? "PARAMIX" : "PROGRAMS",WHITE,1); + if(n>8u){ if(sel=first+8u) first=sel-7u; } else first=0; + for(u32 i=first;i8u?8u:n);i++){ + int sx = g_sx && i+1u==g_sx; + u16 c = (g_dl && i+1u==g_dl) || sx ? GREY : ORANGE; + if(n>4u){ + int dy = n>7u ? 14 : 16, y=2+(int)(i-first)*dy; + if(i==sel){ rect(1,y,127,y+dy-1,c); rect(2,y+1,126,y+dy-2,BG); } + text(5,y+(dy-8)/2+1,g_appnm[i],c,1); + const char *st = sx ? "OPEN" : "START"; + text(123-text_w(st,1),y+(dy-8)/2+1,st,GREY,1); + } else big_entry(y0+(int)i*29, i==sel, g_appnm[i], g_dl && i+1u==g_dl ? "PC FLASH" : sx ? SX_TEXT : "START", c, GREY); + } +#ifdef BAT_SHOW + /* test17: the start device's home screen shows the battery bottom right */ + if(top && launch_mode()){ char bt[12]; bat_text(bt); text(5,119,"B START",GREY,1); if(n<=8u) text(123-text_w(bt,1),119,bt,GREY,1); +#ifdef FELD_AUTODBG + if(g_adbg[2]){ static const char hx[]="0123456789ABCDEF"; char d[8]; u32 mm=g_adbg[0]; + d[0]= mm==MB_L ? 'L' : mm==MB_M ? 'M' : mm==MB_R ? 'R' : mm ? '?' : '0'; d[1]=hx[(g_adbg[1]>>8)&15u]; d[2]=g_adbg[2]==2u ? 'B' : '-'; d[3]= g_adbg[3]==MB_S ? 'S' : g_adbg[3] ? '?' : '0'; d[4]=0; + text(58,119,d,GREY,1); } +#endif + } + else +#endif + ctext(119, top && launch_mode() ? "B START" : "B OK C BACK",GREY,1); + if(n>8u){ char sc[8]; u32 a=sel+1u; int k=0; if(a>=10u) sc[k++]=(char)('0'+a/10u); sc[k++]=(char)('0'+a%10u); sc[k++]='/'; if(n>=10u) sc[k++]=(char)('0'+n/10u); sc[k++]=(char)('0'+n%10u); sc[k]=0; text(123-text_w(sc,1),119,sc,GREY,1); } + show(); wait_release(); + for(;;){ + int k=idle_input(); + if(k<0) break; + if(k==1){ sel=(u32)((int)sel + (g_step>0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK){ if(top && launch_mode()) continue; if(top) leave(); return; } + if(k==K_OK){ if(g_sx && sel+1u==g_sx){ lset_menu(); g_idle_t=g_ms; break; } start_app_i(sel); } + } + } +} +/* Field list. with_app: program as the last entry (when there is no main menu). + * Returns when C is pressed and there is a main menu. */ +static void field_menu(int with_app, int top){ + int has[NF_MAX]; u32 nf=nfields(); for(u32 i=0;i1u ? 1u : g_napp) : 0u; + u32 n = nf + na; + u32 sel = na ? nf : (u32)g_cur; + for(;;){ + rect(0,0,128,128,BG); + int y0 = n>=4u ? 1 : 12; + if(n<4u) ctext(2, top ? "PARAMIX" : "FIELD", WHITE,1); + for(u32 i=0;i1u ? "PROGRAMS" : g_appnm[0]; + const char *st = i>=nf ? (g_napp>1u ? "CHOOSE" : "START") : ((int)i==g_cur) ? "ACTIVE" : has[i] ? "SAVED" : "NEW"; + u16 c = i4u){ /* six fields: compact rows */ + int y=2+(int)i*16; + if(i==sel){ rect(1,y,127,y+15,c); rect(2,y+1,126,y+14,BG); } + text(5,y+4,nm,c,1); + text(123-text_w(st,1),y+4,st,stc,1); + } else big_entry(y0+(int)i*29, i==sel, nm, st, c, stc); + } + ctext(119,"B OK C BACK",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ sel=(u32)((int)sel + (g_step>0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK){ if(top) leave(); return; } + if(k==K_OK){ + if(sel>=nf){ if(g_napp>1u) apps_menu(0); else start_app_i(0); break; } + if((int)sel==g_cur){ if(top) leave(); return; } + if(field_confirm(sel,has[sel])) field_switch(sel,has[sel]); + break; + } + } + } +} + +/* ---------------------------------------------------------------- Items and Tamapoints */ +static int set_load(void){ + flash_read(SET_A, g_set, PAGE); + u32 c=crc16arc(g_set,4,PAGE); + if((g_set[0]|(g_set[1]<<8))!=c || (g_set[2]|(g_set[3]<<8))!=(~c&0xFFFFu)) return 1; + u32 y=g_set[0x1c]|(g_set[0x1d]<<8), m=g_set[0x1e]|(g_set[0x1f]<<8), d=g_set[0x20]|(g_set[0x21]<<8); + if(y<2020u || y>2035u || m<1u || m>12u || d<1u || d>31u) return 2; /* nothing saved yet */ + if(g_cfg.list_off+1280u>PAGE || g_cfg.count_off+320u>PAGE || g_cfg.money_off+4u>PAGE) return 3; + return 0; +} +static int set_check_msg(void){ + int e=set_load(); + if(e==1){ message("SAVE DATA","IS DAMAGED","NOTHING CHANGED"); return 1; } + if(e==2){ message("NO SAVE YET","PLAY A LITTLE","AND TRY AGAIN"); return 1; } + if(e){ message("SAVE FORMAT","UNKNOWN",""); return 1; } + return 0; +} +static void set_write(const char *what){ + rect(0,0,128,128,BG); ctext(40,"SAVING",WHITE,1); ctext(54,"DO NOT SWITCH OFF",GREY,1); show(); + stamp(g_set); + flash_prog4k(SET_A, g_set); + flash_prog4k(SET_B, g_set); + if(!flash_same(SET_A,g_set,PAGE) || !flash_same(SET_B,g_set,PAGE)) error_screen(40); + done_screen(what, GOLD); +} +/* Start device settings (1.6.8): sound level of the Paradise (settings byte 8, bits 3..4: 0 off .. 3 loud, + * found with the sound screen of the firmware) and the display time of this menu. */ +#define SND_OFF 8u +#ifdef FELD_CLEAN +/* ---------------------------------------------------------------- 1.7.2 FELD_CLEAN: ROM without the Paradise + * Nobody else keeps the time: the menu's own clock sector holds a time base (seconds since 1970, local) and the + * seconds counter 0x45000304 at that moment (it runs on through deep sleep and resets, it starts at 0 when the + * batteries come in). The programs get the time through the mailbox 0x20000FC0 as before. */ +#define CK_MAGIC 0x4B584D50u /* "PMXK" */ +typedef struct { u32 magic, t0, c0, idle, chk; } Clk; +static int clean_mode(void){ return g_cfg.version>=10u && (g_cfg.flags & F_CLEAN) && g_cfg.clock_sec; } +#ifdef FELD_NOCLK +/* 1.7.3 test7: vflags bit 1 = the Studio's "set the clock at the start" off: the clock is only set under SETTINGS + * (the programs keep their own clocks, as the real toys) */ +#define CLK_ASK() (!(g_cfg.vflags & 2u)) +#else +#define CLK_ASK() 1 +#endif +#ifdef HOST +static u32 rtc_cnt(void){ return 100u; } +#else +static u32 rtc_cnt(void){ return REG(0x45000304u); } +#endif +static int clk_load(Clk *k){ + const volatile u32 *p=(const volatile u32*)(FLASH_BASE+g_cfg.clock_sec); + k->magic=p[0]; k->t0=p[1]; k->c0=p[2]; k->idle=p[3]; k->chk=p[4]; + return k->magic==CK_MAGIC && k->chk==(k->magic^k->t0^k->c0^k->idle); +} +/* the time now (0 = not set, or the batteries were out since) */ +static u32 clk_now(void){ + Clk k; if(!clk_load(&k) || !k.t0) return 0; + u32 c=rtc_cnt(); if(cmagic=CK_MAGIC; k->t0=t; k->c0=t ? rtc_cnt() : 0; k->idle=idle; k->chk=k->magic^k->t0^k->c0^k->idle; + flash_prog4k(g_cfg.clock_sec, g_out); +#ifndef HOST + if(t) para_mailbox_put(t, k->c0); +#endif +} +/* days since 1970 -> date */ +static void civil(u32 z, u32 *y, u32 *m, u32 *d){ + z+=719468u; u32 era=z/146097u, doe=z-era*146097u, yoe=(doe-doe/1460u+doe/36524u-doe/146096u)/365u; + u32 doy=doe-(365u*yoe+yoe/4u-yoe/100u), mp=(5u*doy+2u)/153u; + *d=doy-(153u*mp+2u)/5u+1u; *m=mp<10u ? mp+3u : mp-9u; *y=yoe+era*400u+(*m<=2u); +} +static u32 mdays(u32 y, u32 m){ static const u8 n[12]={31,28,31,30,31,30,31,31,30,31,30,31}; return m==2u && !(y%4u) && (y%100u || !(y%400u)) ? 29u : n[m-1u]; } +static void two(char *s, u32 v){ s[0]=(char)('0'+v/10u%10u); s[1]=(char)('0'+v%10u); } +static void hhmm(u32 t, char *s){ u32 x=t%86400u; two(s,x/3600u); s[2]=':'; two(s+3,x/60u%60u); s[5]=0; } +/* set the clock: wheel changes, A goes to the next part, B saves, C back (not when must) */ +static void clock_menu(int must){ + u32 t=clk_now(), y=2026u, mo=1u, d=1u, h=12u, mi=0u, sel=0; + if(t){ civil(t/86400u,&y,&mo,&d); h=t%86400u/3600u; mi=t%3600u/60u; } + for(;;){ + if(d>mdays(y,mo)) d=mdays(y,mo); + rect(0,0,128,128,BG); + ctext(4,"SET THE CLOCK",WHITE,1); + char s[6]; + utoa_(y,s); text(5,26,s,sel==0u?ORANGE:WHITE,2); + s[0]='-'; s[1]=0; text(52,26,s,GREY,2); + two(s,mo); s[2]=0; text(65,26,s,sel==1u?ORANGE:WHITE,2); + s[0]='-'; s[1]=0; text(89,26,s,GREY,2); + two(s,d); s[2]=0; text(102,26,s,sel==2u?ORANGE:WHITE,2); + two(s,h); s[2]=0; text(34,52,s,sel==3u?ORANGE:WHITE,2); + s[0]=':'; s[1]=0; text(58,52,s,GREY,2); + two(s,mi); s[2]=0; text(70,52,s,sel==4u?ORANGE:WHITE,2); + ctext(84,"WHEEL: CHANGE",GREY,1); + ctext(96,"A: NEXT B: SAVE",GREY,1); + if(!must) ctext(108,"C: BACK",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ + int st=g_step; + if(sel==0u){ int v=(int)y+st; if(v<2024) v=2099; if(v>2099) v=2024; y=(u32)v; } + else if(sel==1u){ mo=(u32)(((int)mo-1+st%12+12)%12)+1u; } + else if(sel==2u){ u32 n=mdays(y,mo); d=(u32)(((int)d-1+st%(int)n+(int)n)%(int)n)+1u; } + else if(sel==3u){ h=(u32)(((int)h+st%24+24)%24); } + else { mi=(u32)(((int)mi+st%60+60)%60); } + break; + } + if(k==K_A){ sel=(sel+1u)%5u; break; } + if(k==K_BACK && !must) return; + if(k==K_OK){ + Clk c; u32 idle=clk_load(&c) ? c.idle : 0u; + rect(0,0,128,128,BG); ctext(54,"SAVING",WHITE,1); show(); + clk_store((u32)para_days((int32_t)y,(int32_t)mo,(int32_t)d)*86400u+h*3600u+mi*60u, idle); + return; + } + } + } +} +#endif +static void lset_load(void){ + g_idle_ms=120000u; +#ifdef FELD_CLEAN + if(clean_mode()){ Clk k; if(clk_load(&k) && k.idle>=1u && k.idle<=5u) g_idle_ms=g_idle_tab[k.idle-1u]; return; } +#endif + if(set_load()==1) return; + u32 v=g_set[IDLE_OFF]; if(v>=1u && v<=5u) g_idle_ms=g_idle_tab[v-1u]; +} +#ifdef FELD_CLEAN +/* clean ROM: the clock and this menu's display time */ +static void lset_clean(void){ + Clk k; u32 idl = clk_load(&k) && k.idle>=1u && k.idle<=5u ? k.idle-1u : 2u, idl0=idl, sel=0; + for(;;){ + char tm[8]; u32 t=clk_now(); if(t) hhmm(t,tm); else { const char *n="NOT SET"; int i=0; while((tm[i]=n[i])) i++; } + rect(0,0,128,128,BG); + ctext(2,"SETTINGS",WHITE,1); + big_entry(16, sel==0u, "CLOCK", tm, ORANGE, WHITE); + big_entry(45, sel==1u, "DISPLAY", g_idle_nm[idl], ORANGE, WHITE); + text(9,84,"DISPLAY: DARK",GREY,1); + text(9,94,"WITHOUT A KEY",GREY,1); + ctext(108,"B CHANGE",GREY,1); + ctext(119,"C SAVE AND BACK",GREY,1); + show(); wait_release(); + for(;;){ + int c=input(); + if(c==1 || c==K_A){ sel^=1u; break; } + if(c==K_OK){ if(sel==0u) clock_menu(0); else idl=(idl+1u)%5u; break; } + if(c==K_BACK){ + if(idl!=idl0){ + rect(0,0,128,128,BG); ctext(54,"SAVING",WHITE,1); show(); + u32 t2=clk_now(); clk_store(t2, idl+1u); + g_idle_ms=g_idle_tab[idl]; + } + return; + } + } + } +} +#endif +static void lset_menu(void){ +#ifdef FELD_CLEAN + if(clean_mode()){ lset_clean(); return; } +#endif + int e=set_load(); + if(e==1 || e==2){ set_check_msg(); return; } + static const char *const snd_nm[4]={"OFF","LOW","MEDIUM","LOUD"}; + u32 snd=(g_set[SND_OFF]>>3)&3u, snd0=snd; + u32 idl=g_set[IDLE_OFF]; idl = idl>=1u && idl<=5u ? idl-1u : 2u; u32 idl0=idl; + u32 sel=0; + for(;;){ + rect(0,0,128,128,BG); + ctext(2,"SETTINGS",WHITE,1); + big_entry(16, sel==0u, "SOUND", snd_nm[snd], ORANGE, WHITE); + big_entry(45, sel==1u, "DISPLAY", g_idle_nm[idl], ORANGE, WHITE); + text(9,74,"SOUND: THE PARADISE",GREY,1); + text(9,84,"DISPLAY: THIS MENU,",GREY,1); + text(9,94,"DARK WITHOUT A KEY",GREY,1); + ctext(108,"B CHANGE",GREY,1); + ctext(119,"C SAVE AND BACK",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1 || k==K_A){ sel^=1u; break; } + if(k==K_OK){ if(sel==0u) snd=(snd+1u)&3u; else idl=(idl+1u)%5u; break; } + if(k==K_BACK){ + if(snd!=snd0 || idl!=idl0){ + g_set[SND_OFF]=(u8)((g_set[SND_OFF]&~0x18u)|(snd<<3)); + g_set[IDLE_OFF]=(u8)(idl+1u); + rect(0,0,128,128,BG); ctext(40,"SAVING",WHITE,1); ctext(54,"DO NOT SWITCH OFF",GREY,1); show(); + stamp(g_set); + flash_prog4k(SET_A, g_set); + flash_prog4k(SET_B, g_set); + if(!flash_same(SET_A,g_set,PAGE) || !flash_same(SET_B,g_set,PAGE)) error_screen(41); + g_idle_ms=g_idle_tab[idl]; + } + return; + } + } + } +} +static u32 money_get(void){ u32 o=g_cfg.money_off; return g_set[o]|(g_set[o+1]<<8)|(g_set[o+2]<<16)|((u32)g_set[o+3]<<24); } +static void money_put(u32 v){ u32 o=g_cfg.money_off; g_set[o]=(u8)v; g_set[o+1]=(u8)(v>>8); g_set[o+2]=(u8)(v>>16); g_set[o+3]=(u8)(v>>24); } +static u32 list_id(u32 i){ u32 o=g_cfg.list_off+2u*i; return g_set[o]|(g_set[o+1]<<8); } +static void list_set(u32 i, u32 id){ u32 o=g_cfg.list_off+2u*i; g_set[o]=(u8)id; g_set[o+1]=(u8)(id>>8); } +static u32 count_get(u32 i){ u8 b=g_set[g_cfg.count_off+i/2u]; return (i&1u) ? (b>>4) : (b&15u); } +static void count_set(u32 i, u32 v){ u32 o=g_cfg.count_off+i/2u; u8 b=g_set[o]; g_set[o]=(u8)((i&1u) ? ((b&0x0F)|(v<<4)) : ((b&0xF0)|(v&15u))); } +static u32 list_len(void){ u32 n=0; while(n<640u && list_id(n)) n++; return n; } + +/* Catalog in flash: 28 bytes per entry, sorted by ID */ +static int cat_find(u32 id){ + int lo=0, hi=(int)g_cfg.cat_n-1; + while(lo<=hi){ int m=(lo+hi)/2; u32 v=rd16(g_cfg.cat_off+8u+28u*(u32)m); if(v==id) return m; if(v=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]; } +static char g_nm[24]; +static const char *item_name(u32 id){ + int k=cat_find(id); + if(k>=0){ u32 o=g_cfg.cat_off+8u+28u*(u32)k; u32 n=fl(o+3)[0]; if(n>20u) n=20u; if(n){ for(u32 i=0;i g_pic[0..n) */ + const volatile u32 *s=(const volatile u32*)(FLASH_BASE + a); + for(u32 i=0;i<(n+3u)/4u;i++) g_picw[i]=s[i]; +} +static u32 pr16(u32 o){ return g_pic[o]|(g_pic[o+1]<<8); } +static u32 pr32(u32 o){ return g_pic[o]|(g_pic[o+1]<<8)|(g_pic[o+2]<<16)|((u32)g_pic[o+3]<<24); } +static u32 spr_rle(u32 src, u32 ln, int x, int word, u8 *out, u32 cap){ + u32 i=0, o=0; +#define SB(k) ((u8)(g_pic[src+(k)] ^ (x?0x53u:0u))) + if(!word){ + while(i>(12-4*i))&15u]; } +static void pic_hex(int cy, u32 a, u32 b){ + char t[12]; hex4(t,a); t[4]=' '; hex4(t+5,b); t[9]=0; + ctext(cy+8, t, GREY, 1); +} +static void copy_bytes(u32 a, u32 n){ for(u32 i=0;iPIC_MAX){ pic_code(cy,"P7"); return; } + /* three ways to read, the first whose sum matches wins: + W = 32-bit reads in the 0x60000000 window, B = byte reads there, + X = cached XIP window at 0x10000000 pointed at the picture (menu runs from PRAM) */ + u32 sW, sB=0, sX=0; + copy_words(e, end); sW=pic_sum(end); + if(sW!=want){ copy_bytes(e, end); sB=pic_sum(end); } + if(sW!=want && sB!=want){ copy_xip(e, end); sX=pic_sum(end); } + if(sW!=want && sB!=want && sX!=want){ + char t[12]; + ctext(cy-12,"RD",GREY,1); + hex4(t,sW); t[4]=' '; hex4(t+5,want); t[9]=0; ctext(cy-2,t,GREY,1); + hex4(t,sB); t[4]=' '; hex4(t+5,sX); t[9]=0; ctext(cy+8,t,GREY,1); + copy_words(e,4u); hex4(t,pr16(0)); t[4]=' '; hex4(t+5,rd32(q+8u)&0xFFFFu); t[9]=0; ctext(cy+18,t,GREY,1); + return; + } + } else { + u32 P=g_cfg.pack_off, n=rd32(P)/4u; if(pic>=n){ pic_code(cy,"P2"); return; } + e=P+rd32(P+4u*pic); + if(e&3u){ pic_code(cy,"P6"); return; } + } + if(!end) copy_words(e, 64u); /* header */ + u32 flags=g_pic[4], bpp=g_pic[5], sw=g_pic[8], sh=g_pic[9], iw=g_pic[12], ih=g_pic[13]; + u32 tr=pr16(16), po=pr16(18), px=pr16(20); + if(bpp>3u || !sw || !sh){ pic_code(cy,"P3"); return; } + if(!iw) iw=1; if(!ih) ih=1; + u32 cnt=iw*ih, bits=1u<sizeof(g_spr)){ pic_code(cy,"P4"); return; } + if(!end){ + u32 hdr=px+8u*cnt; if(hdr>PIC_MAX || po+2u*(mask+1u)>PIC_MAX){ pic_code(cy,"P5"); return; } + copy_words(e, hdr); /* header and sub-image table */ + end=hdr; + for(u32 c=0;cend) end=x; + } + u32 pend=po+2u*(mask+1u); if(pend>end) end=pend; + if(end>PIC_MAX){ pic_code(cy,"P5"); return; } + copy_words(e, end); /* whole entry */ + if(want && pic_sum(end)!=want){ pic_code(cy,"RD"); pic_hex(cy,pic_sum(end),want); return; } + } + /* every offset used below must lie inside the copied entry */ + if(px+8u*cnt>end || po+2u*(mask+1u)>end){ pic_code(cy,"P5"); return; } + int W=(int)(sw*iw), H=(int)(sh*ih), sc=1, dn=1; + while(W/dn>box || H/dn>box) dn*=2; + if(dn==1 && W*2<=box && H*2<=box) sc=2; + int x0=cx-(W/dn*sc)/2, y0=cy-(H/dn*sc)/2; + int xr=(flags&0x80u)!=0; + for(u32 c=0;c>3]>>(bit&7u))&mask; + if((flags&4u) && v==tr) continue; + u16 col=(u16)pr16(po+2u*v); + int X=x0+x/dn*sc, Y=y0+y/dn*sc; + rect(X,Y,X+sc,Y+sc,col); + } + } +} +static const char *group_name(u32 id){ switch(id/1000u){ case 5: return "FOOD"; case 6: return "SNACKS"; case 7: return "TOYS"; case 8: return "GOODS"; default: return "OTHER"; } } + +/* Draw a list: title, 10 rows from y=12, footer. */ +static void list_draw(const char *title, u32 n, u32 sel, u32 top, int (*row)(u32 i, char *name, char *right, u16 *col), const char *foot){ + rect(0,0,128,128,BG); + ctext(2,title,WHITE,1); + for(u32 r=0;r<10u && top+r10u){ int h=100*10/(int)n; if(h<6) h=6; int y=12+(int)(100-h)*(int)top/(int)(n-10u); rect(126,y,128,y+h,GREY); } + ctext(118,foot,GREY,1); + show(); +} + +/* Bag list: index -> slot (only items that are not fixed), entry 0 = add */ +static u16 g_bag[640]; static u32 g_bagn; +#ifdef BAG_DEL +#define BAG_SHOWN(i) (count_get(i) != 0u) +/* 1.6.9: count 0 = the game has the item no more (its own list keeps such entries, e.g. an apple eaten up); they are + * not shown, a count can be set to 0 to take an item out again */ +static void bag_build(void){ g_bagn=0; u32 n=list_len(); for(u32 i=0;i15u) v=15u; +#else +static u32 count_edit(u32 id, u32 v){ + const u32 lo=1u; + if(v<1u) v=1u; if(v>15u) v=15u; +#endif + for(;;){ + rect(0,0,128,128,BG); + const char *nm=item_name(id); int L=slen(nm); + if(L<=20) ctext(4,nm,WHITE,1); else { textn(4,2,nm,20,WHITE,1); textn(4,11,nm+20,20,WHITE,1); } + rect(30,20,98,84,RGB(40,40,70)); + draw_item_pic(id,64,52,64); + char s[8]; s[0]='x'; utoa_(v,s+1); +#ifdef BAG_DEL + if(!v) ctext(90,"REMOVE",GOLD,2); else +#endif + ctext(90,s,GOLD,2); + ctext(108,"WHEEL: COUNT",GREY,1); + ctext(119,"B OK C BACK",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ int nv=(int)v+(g_step>0?1:-1); if(nv<(int)lo) nv=(int)lo; if(nv>15) nv=15; v=(u32)nv; break; } + if(k==K_A){ v = v>=15u ? lo : v+1u; break; } + if(k==K_OK) return v; +#ifdef BAG_DEL + if(k==K_BACK) return 16u; +#else + if(k==K_BACK) return 0; +#endif + } + } +} +static int g_dirty; +static void cat_pick(void){ + cat_build(); + if(!g_catn){ message("NO ITEM LIST","IN THIS ROM",""); return; } + u32 sel=0, top=0; + for(;;){ + if(sel=top+10u) top=sel-9u; + char t[24]; const char *g=group_name(g_cat[sel]); int k=0; const char *a="ADD: "; while(a[k]){ t[k]=a[k]; k++; } int j=0; while(g[j]){ t[k++]=g[j++]; } t[k]=0; + list_draw(t, g_catn, sel, top, cat_row, "A NEXT GROUP C BACK"); + wait_release(); + for(;;){ + int c=input(); + if(c==1){ int s=(int)sel+g_step; if(s<0) s=0; if(s>=(int)g_catn) s=(int)g_catn-1; sel=(u32)s; break; } + if(c==K_A){ u32 gr=g_cat[sel]/1000u; u32 s=sel; while(s=640u){ message("BAG IS FULL","",""); return; } +#ifdef BAG_DEL + u32 v=count_edit(id, slot=n) sel=n-1u; + if(sel=top+10u) top=sel-9u; + list_draw("ITEMS", n, sel, top, bag_row, "B EDIT C BACK"); + wait_release(); + for(;;){ + int c=input(); + if(c==1){ int s=(int)sel+g_step; if(s<0) s=0; if(s>=(int)n) s=(int)n-1; sel=(u32)s; break; } + if(c==K_A){ sel=(sel+1u)%n; break; } + if(c==K_OK){ + if(sel==0){ cat_pick(); } +#ifdef BAG_DEL + else { u32 slot=g_bag[sel-1]; u32 v=count_edit(list_id(slot), count_get(slot), 0u); if(v<16u && v!=count_get(slot)){ count_set(slot,v); g_dirty=1; } } +#else + else { u32 slot=g_bag[sel-1]; u32 v=count_edit(list_id(slot), count_get(slot)); if(v && v!=count_get(slot)){ count_set(slot,v); g_dirty=1; } } +#endif + break; + } + if(c==K_BACK){ + if(!g_dirty) return; + rect(0,0,128,128,BG); ctext(34,"SAVE CHANGES?",WHITE,1); ctext(60,"THE TAMA RESTARTS",GREY,1); + ctext(92,"B = YES",WHITE,1); ctext(106,"C = NO",GREY,1); show(); + if(yes_no()) set_write("ITEMS SAVED"); + return; + } + } + } +} +static void points_menu(void){ + if(set_check_msg()) return; + u32 v=money_get(); if(v>99999u) v=99999u; + u8 dg[5]; { u32 t=v; for(int i=4;i>=0;i--){ dg[i]=(u8)(t%10u); t/=10u; } } + int pos=0; + for(;;){ + rect(0,0,128,128,BG); + ctext(10,"TAMAPOINTS",GOLD,1); + for(int i=0;i<5;i++){ + int x=14+i*21; char s[2]={(char)('0'+dg[i]),0}; + if(i==pos) rect(x-2,40,x+17,68,RGB(60,60,110)); + text(x,43,s,i==pos?GOLD:WHITE,3); + } + ctext(80,"WHEEL: DIGIT",GREY,1); + ctext(92,"B NEXT A BACK",GREY,1); + ctext(106,"C CANCEL",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ dg[pos]=(u8)((dg[pos]+10+(g_step>0?1:-1))%10); break; } + if(k==K_A){ if(pos>0) pos--; break; } + if(k==K_BACK) return; + if(k==K_OK){ + if(pos<4){ pos++; break; } + u32 nv=0; for(int i=0;i<5;i++) nv=nv*10u+dg[i]; + if(nv==money_get()) return; + rect(0,0,128,128,BG); ctext(24,"SET TAMAPOINTS TO",WHITE,1); + char s[8]; utoa_(nv,s); ctext(44,s,GOLD,2); ctext(70,"THE TAMA RESTARTS",GREY,1); + ctext(92,"B = YES",WHITE,1); ctext(106,"C = NO",GREY,1); show(); + if(yes_no()){ money_put(nv); set_write("TAMAPOINTS SAVED"); } + return; + } + } + } +} + +/* ---------------------------------------------------------------- TAMA (1.6.8) */ +/* Characters come with the catalog (fixed byte 2): +6 stage (3 kid, 4 young, 5 adult), +7 field index + 1 (0 = none). */ +static int tama_ok(void){ return (g_cfg.flags & F_TAMA) && g_cfg.version>=6u && g_cfg.tama_off && g_cfg.tama_off+0x20u>2)&7u; } +static const char *stage_name(u32 st){ switch(st){ case 1: return "EGG"; case 2: return "BABY"; case 3: return "KID"; case 4: return "YOUNG"; case 5: return "ADULT"; default: return "?"; } } +static u16 g_chr[256]; static u32 g_chrn; +static void chr_build(u32 st){ g_chrn=0; for(u32 k=0;k20u) n=20u; for(u32 i=0;i255u || (rd16(a+14u)!=old && rd16(a+12u)!=old)) continue; } +#else + if(rd32(a+8u)!=1u || rd16(a+14u)!=old) continue; +#endif + flash_read(a, g_page, PAGE); +#ifdef FELD_TAMA_ANY + if((g_page[14]|(g_page[15]<<8))==old) +#endif + { g_page[14]=(u8)nw; g_page[15]=(u8)(nw>>8); } + if((g_page[12]|(g_page[13]<<8))==old){ g_page[12]=(u8)nw; g_page[13]=(u8)(nw>>8); } + if((g_page[0x10A]|(g_page[0x10B]<<8))==old){ g_page[0x10A]=(u8)nw; g_page[0x10B]=(u8)(nw>>8); } + flash_prog4k(a, g_page); n++; + } + return n; +} +static void chr_pick(void){ + static const u8 st_list[3]={3,4,5}; u32 si=t_stage()>=3u && t_stage()<=5u ? t_stage()-3u : 2u; + u32 sel=0, top=0; + chr_build(st_list[si]); + for(;;){ + if(!g_chrn){ message("NO CHARACTERS","IN THIS ROM",""); return; } + if(sel>=g_chrn) sel=g_chrn-1u; + if(sel=top+10u) top=sel-9u; + char t[24]; const char *a="TAMA: "; int k=0; while(a[k]){ t[k]=a[k]; k++; } const char *b=stage_name(st_list[si]); int j=0; while(b[j]) t[k++]=b[j++]; t[k]=0; + list_draw(t, g_chrn, sel, top, chr_row, "A STAGE B OK C BACK"); + wait_release(); + for(;;){ + int c=input(); + if(c==1){ int s=(int)sel+g_step; if(s<0) s=0; if(s>=(int)g_chrn) s=(int)g_chrn-1; sel=(u32)s; break; } + if(c==K_A){ si=(si+1u)%3u; chr_build(st_list[si]); sel=0; top=0; break; } + if(c==K_BACK) return; + if(c==K_OK){ + u32 kk=g_chr[sel], o=g_cfg.cat_off+8u+28u*kk, nw=rd16(o), st=fl(o+6)[0], old=t_id(); + char nm[24]; chr_name(kk,nm); + rect(0,0,128,128,BG); ctext(24,"YOUR TAMA BECOMES",WHITE,1); ctext(42,nm,GOLD,1); ctext(54,stage_name(st),GREY,1); + ctext(76,"THE TAMA RESTARTS",GREY,1); ctext(96,"B = YES",WHITE,1); ctext(108,"C = NO",GREY,1); show(); + if(!yes_no()) break; + u32 to=g_cfg.tama_off; +#ifdef FELD_TAMA_ANY + /* without the Tama's file the game keeps showing the old Tama: say so instead of "changed" (files first, the + * settings block in RAM stays untouched then) */ + if(old && old!=nw && !tama_files(old, nw)){ message("TAMA NOT FOUND","NOTHING CHANGED",""); return; } +#endif + g_set[to+4]=(u8)nw; g_set[to+5]=(u8)(nw>>8); g_set[to+6]=(u8)nw; g_set[to+7]=(u8)(nw>>8); + g_set[to+0x18u]=(u8)((g_set[to+0x18u]&~0x1Cu)|((st&7u)<<2)); +#ifdef FELD_TAMA_ANY +#else + if(old && old!=nw) tama_files(old, nw); +#endif + set_write("TAMA CHANGED"); + return; + } + } + } +} +static void level_edit(void){ + u32 v=lv_get(), old=v; + for(;;){ + rect(0,0,128,128,BG); ctext(10,"PLANET LEVEL",GOLD,1); + char s[4]; utoa_(v,s); ctext(40,s,WHITE,4); + ctext(80,"WHEEL: LEVEL",GREY,1); ctext(94,"B OK C BACK",GREY,1); show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ int nv=(int)v+(g_step>0?1:-1); if(nv<0) nv=0; if(nv>10) nv=10; v=(u32)nv; break; } + if(k==K_A){ v=v>=10u?0u:v+1u; break; } + if(k==K_BACK) return; + if(k==K_OK){ + if(v==old) return; + u32 o=g_cfg.level_off, b=g_set[o]; + /* up: the game celebrates the new level itself; down: nothing to celebrate */ + g_set[o]=(u8)(v>old ? ((b&0xF0u)|v) : ((v<<4)|v)); + set_write("LEVEL SAVED"); + return; + } + } + } +} +static void care_full(void){ + rect(0,0,128,128,BG); ctext(24,"FULL CARE:",WHITE,1); ctext(40,"FED, HAPPY, HEALTHY",GOLD,1); + ctext(70,"THE TAMA RESTARTS",GREY,1); ctext(92,"B = YES",WHITE,1); ctext(106,"C = NO",GREY,1); show(); + if(!yes_no()) return; + u32 to=g_cfg.tama_off; + g_set[to+0x1Cu]=6u; g_set[to+0x1Du]=20u; g_set[to+0x10u]=0u; + set_write("TAMA CARED FOR"); +} +static void big_entry(int y, int sel, const char *name, const char *st, u16 c, u16 stc); +static void tama_menu(void){ + if(set_check_msg()) return; + u32 sel=0; + for(;;){ + rect(0,0,128,128,BG); ctext(2,"TAMA",WHITE,1); + char st[24], nm[24]; nm[0]=0; + utoa_(lv_get(),st); big_entry(12,sel==0,"LEVEL",st,GOLD,GREY); + { u32 id=t_id(); int k=cat_find(id); if(k>=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]==2u) chr_name((u32)k,nm); else utoa_(id,nm); } + big_entry(41,sel==1,"CHANGE",nm,PINK,GREY); + { u32 to=g_cfg.tama_off; char *p=st; const char *a="FOOD "; while(*a) *p++=*a++; utoa_(g_set[to+0x1Cu],p); while(*p) p++; a=" JOY "; while(*a) *p++=*a++; utoa_(g_set[to+0x1Du],p); while(*p) p++; if(g_set[to+0x10u]){ a=" SICK"; while(*a) *p++=*a++; } *p=0; } + big_entry(70,sel==2,"CARE",st,ORANGE,GREY); + ctext(119,"B OK C BACK",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ sel=(u32)((int)sel+(g_step>0?1:-1)+3)%3u; break; } + if(k==K_A){ sel=(sel+1u)%3u; break; } + if(k==K_BACK) return; + if(k==K_OK){ if(sel==0) level_edit(); else if(sel==1) chr_pick(); else care_full(); break; } + } + } +} + +/* ---------------------------------------------------------------- Saves (1.6.8) */ +/* settings block of the save in slot i (unpacked into out). 0 = ok */ +static int slot_set(u32 i, u8 *out){ + if(!slot_valid(i)) return 1; + u32 b=slot_base(i), np=rd32(b+8), pos=0; + for(u32 k=0;k>12)){ slot_get(i,pos,n,g_cmp); return lz_unpack(g_cmp,n,out) ? 2 : 0; } + pos+=n; + } + return 3; +} +static int g_sfld[NF_MAX]; static char g_snm[NF_MAX][16]; +/* field and Tama name of each save */ +static void saves_scan(void){ + for(u32 i=0;i=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]==2u){ char t[24]; chr_name((u32)k,t); t[15]=0; for(int q=0;q<16;q++){ g_snm[i][q]=t[q]; if(!t[q]) break; } } + } + } +} +static u32 field_pick(void){ /* field for a new game, 0xFF = back */ + u32 nf=nfields(), sel=0; + for(;;){ + rect(0,0,128,128,BG); ctext(2,"START ON FIELD",WHITE,1); + for(u32 i=0;i0?1:-1)+(int)nf)%nf; break; } + if(k==K_A){ sel=(sel+1u)%nf; break; } + if(k==K_BACK) return 0xFFu; + if(k==K_OK) return sel; } + } +} +static void saves_menu(int with_app, int top){ + saves_scan(); + u32 ns=g_cfg.nslots>NF_MAX?NF_MAX:g_cfg.nslots; + u32 na = with_app ? (g_napp>1u ? 1u : g_napp) : 0u, n=ns+na, sel = na ? ns : (u32)g_act; + for(;;){ + rect(0,0,128,128,BG); + if(n<=4u) ctext(2, top ? "PARAMIX" : "SAVES", WHITE,1); + for(u32 i=0;i4u && g_snm[i][0]){ for(int q=0;g_snm[i][q];q++) *p++=g_snm[i][q]; if(f>=0) c=fcol((u32)f); } /* compact: the Tama, field by colour */ + else { const char *e=f>=0 ? fname((u32)f) : "?"; while(*e) *p++=*e++; if(g_snm[i][0]){ *p++=' '; for(int q=0;g_snm[i][q];q++) *p++=g_snm[i][q]; } if(f>=0) c=fcol((u32)f); } + *p=0; if((int)i==g_act) stc=WHITE; + } else { const char *e=g_napp>1u ? "PROGRAMS" : g_appnm[0]; int k=0; while(e[k] && k<11){ nm[k]=e[k]; k++; } nm[k]=0; e=g_napp>1u?"CHOOSE":"START"; int q=0; while(e[q]){ st[q]=e[q]; q++; } st[q]=0; } + if(n>4u){ + int y=2+(int)i*16; + if(i==sel){ rect(1,y,127,y+15,c); rect(2,y+1,126,y+14,BG); } + text(5,y+4,nm,c,1); int w=text_w(st,1); int x=123-w; if(x<48) x=48; textn(x,y+4,st,(124-x)/6,stc,1); + } else big_entry((n<4u?12:1)+(int)i*29, i==sel, nm, st, c, stc); + } + ctext(119,"B OK C BACK",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ sel=(u32)((int)sel + (g_step>0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK){ if(top) leave(); return; } + if(k==K_OK){ + if(sel>=ns){ if(g_napp>1u) apps_menu(0); else start_app_i(0); break; } + if((int)sel==g_act){ if(top) leave(); return; } + int has=slot_valid(sel); u32 fld; + if(has){ fld=(u32)g_sfld[sel]; if(g_sfld[sel]<0){ message("SAVE","UNREADABLE",""); break; } } + else { fld=field_pick(); if(fld==0xFFu) break; } + rect(0,0,128,128,BG); + char t[8]="SAVE "; t[5]=(char)('1'+sel); t[6]=0; + ctext(14, has ? "LOAD" : "NEW GAME IN", WHITE,1); ctext(28,t,WHITE,2); + ctext(52,fname(fld),fcol(fld),1); if(has && g_snm[sel][0]) ctext(64,g_snm[sel],GREY,1); + ctext(80,"YOUR GAME IS KEPT",GREY,1); + ctext(96,"B = YES",WHITE,1); ctext(108,"C = NO",GREY,1); show(); + if(yes_no()) field_switch2(sel, has, fld); + break; + } + } + } +} + +/* ---------------------------------------------------------------- Main menu */ +static void main_menu(void){ + int fields = (g_cfg.flags & F_FIELDS) && g_cur>=0 && g_cfg.nfields>=2u; + u32 kinds[5], n=0; /* 0 field, 1 items, 2 Tamapoints, 3 program, 4 Tama */ + if(fields) kinds[n++]=0; + if(g_cfg.flags & F_BAG){ kinds[n++]=1; kinds[n++]=2; } + if(tama_ok()) kinds[n++]=4; + if(g_napp) kinds[n++]=3; + u32 sel = g_napp ? n-1u : 0u; + for(;;){ + int ok=set_load()==0; + rect(0,0,128,128,BG); + int y0 = n>=4u ? 1 : 12, dy = n>=5u ? 23 : 29; + if(n<4u) ctext(2,"PARAMIX",WHITE,1); + g_small = n>=5u; + for(u32 i=0;i=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]==2u) chr_name((u32)k,st); else if(ok) utoa_(t_id(),st); else { st[0]='-'; st[1]=0; } + big_entry(y,i==sel,"TAMA",st,RGB(120,220,120),GREY); } break; + default: big_entry(y,i==sel,g_napp>1u ? "PROGRAMS" : g_appnm[0],g_napp>1u ? "CHOOSE" : "START",ORANGE,GREY); break; + } + } + g_small = 0; + ctext(119,"B OK C BACK",GREY,1); + show(); wait_release(); + for(;;){ + int k=input(); + if(k==1){ sel=(u32)((int)sel + (g_step>0?1:-1) + (int)n) % n; break; } + if(k==K_A){ sel=(sel+1u)%n; break; } + if(k==K_BACK) leave(); + if(k==K_OK){ + switch(kinds[sel]){ case 0: if(saves_mode()) saves_menu(0,0); else field_menu(0,0); break; case 1: items_menu(); break; case 2: points_menu(); break; case 4: tama_menu(); break; default: if(g_napp>1u) apps_menu(0); else start_app_i(0); } + break; + } + } + } +} + +static void run(void){ + rect(0,0,128,128,BG); show(); +#ifndef HOST + REG(GPIO2+0x04) &= ~3u; g_enc_last=REG(GPIO2) & 3u; + clock_start(); +#endif + app_detect(); + apps_detect(); +#ifdef FELD_AUTO +#ifdef HOST + { const char *e; if((e=getenv("AUTO_MB"))) h_mb=(u32)strtoul(e,0,16); if((e=getenv("AUTO_GPIO"))) h_gpio=(u32)strtoul(e,0,16); if((e=getenv("AUTO_CNT"))) h_cnt=(u32)strtoul(e,0,10); +#ifdef FELD_SEEN + if((e=getenv("AUTO_SEEN"))) h_seen=(u32)strtoul(e,0,16); +#endif + } +#endif +#ifdef FELD_BFALL + b_fallback(); +#endif + if(auto_go()){ +#if defined(FELD_CLEAN) && defined(CLEAN_AUTO) + if(clean_mode() && !clk_now() && CLK_ASK()){ lset_load(); clock_menu(1); } /* new batteries: the time first, then the main program */ +#endif + start_app_i(0); + } +#endif + g_cur = field_now(); + int fields = (g_cfg.flags & F_FIELDS) && g_cur>=0 && g_cfg.nfields>=2u; + g_act=g_cur; + if(fields && saves_mode()){ + /* the live save's number: from its settings block, else (menus before 1.6.8, or a save that never + * met this menu) the field's slot if it is free, else the first free slot */ + flash_read(SET_A, g_page, PAGE); + u32 v=set_ok(g_page) ? g_page[SAVE_OFF] : 0u; + if(v>=1u && v<=g_cfg.nslots) g_act=(int)v-1; + else { + if((u32)g_act>=g_cfg.nslots || slot_valid((u32)g_act)){ g_act=0; for(u32 j=0;j1u) apps_menu(1); + if(g_napp) start_app_i(0); + leave(); +} + +#ifdef HOST +void host_main(void){ + for(u32 i=0;i>8;g_set[0x1e]=11;g_set[0x20]=10; + g_set[g_cfg.tama_off+0x1c]=6;g_set[g_cfg.tama_off+0x1d]=20;g_set[g_cfg.level_off]=5; + g_set[g_cfg.money_off]=0x39;g_set[g_cfg.money_off+1]=0x30; + stamp(g_set);memcpy(host_flash+SET_A,g_set,PAGE);memcpy(host_flash+SET_B,g_set,PAGE); + scenario(main_menu,"nnnnc");scenario(tama_menu,"nnc");scenario(show_fields,"nc"); + scenario(points_menu,"c");scenario(level_edit,"c");scenario(care_full,"c"); + printf("Synthetic menu frames: %d\n",g_frame); + free(host_flash);return 0; +} diff --git a/feld/src/feld/qa-native-ko.c b/feld/src/feld/qa-native-ko.c new file mode 100644 index 0000000..df5e5ed --- /dev/null +++ b/feld/src/feld/qa-native-ko.c @@ -0,0 +1,19 @@ +/* Offline renderer. Supply your own private ROM; never distribute that image. */ +#define HOST +#include "main-ko.c" +#define main upstream_host_main +#define g_out host_output_path +#include "host.c" +#undef main +#undef g_out +static void scenario(void (*fn)(void),const char *keys){g_seq=keys;g_pos=0;if(!setjmp(g_jb))fn();} +static void fields(void){field_menu(0,0);} +int main(int argc,char **argv){ + if(argc!=4)return 2; + host_flash=malloc(0x1000000);FILE *f=fopen(argv[1],"rb");if(!f)return 3; + if(fread(host_flash,1,0x1000000,f)!=0x1000000)return 4;fclose(f); + u32 offset=(u32)strtoul(argv[2],0,0);memcpy((void*)&g_cfg,host_flash+offset+0x140,sizeof g_cfg); + g_dir=argv[3];for(u32 i=0;i flashapp.bin (byte-identical) +``` + +License: GNU GPL version 3 or later. diff --git a/flash/flashapp.bin b/flash/flashapp.bin new file mode 100644 index 0000000..ea1aae9 Binary files /dev/null and b/flash/flashapp.bin differ diff --git a/flash/src/assets.h b/flash/src/assets.h new file mode 100644 index 0000000..044e608 --- /dev/null +++ b/flash/src/assets.h @@ -0,0 +1,20 @@ +#ifndef ASSETS_H +#define ASSETS_H +#define SCR_W 128 +#define SCR_H 128 +#define BAR_X0 16 +#define BAR_X1 112 +#define BAR_Y0 84 +#define BAR_Y1 92 +#define ACC565 0x1bd4 +#define STATUS_Y 62 +static const unsigned short static_bg[16384]={0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xef9e,0xffff,0x6d58,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xef9e,0xffff,0x6d58,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xefbf,0xffff,0x95fa,0xcefd,0xf7df,0xdf5d,0x5cf7,0x9e3a,0xf7bf,0xf7bf,0xa65b,0x1bd4,0x1bd4,0x1bd4,0xd73d,0xffff,0xffff,0xffff,0xdf5e,0x85b9,0x1bd4,0x1bd4,0xefbf,0xffff,0x95fa,0xcefd,0xf7df,0xdf5d,0x5cf7,0x9e3a,0xf7bf,0xf7bf,0xa65b,0x1bd4,0x1bd4,0x1bd4,0x2c14,0x9e3a,0xdf7e,0xf7df,0xdf5e,0x85b9,0x1bd4,0x1bd4,0x1bd4,0xef9e,0xffff,0x6d58,0x1bd4,0x8599,0xdf5e,0xf7df,0xe77e,0xa65b,0x3435,0x1bd4,0x1bd4,0x2c14,0x9e3a,0xdf7e,0xf7df,0xdf5e,0x85b9,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xefbf,0xffff,0xd73d,0x2c15,0x9e3a,0xffff,0xffff,0x85b9,0x3435,0xefbf,0xffff,0x6d58,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x3c55,0xdf5e,0xffff,0x6517,0x1bd4,0xefbf,0xffff,0xd73d,0x2c15,0x9e3a,0xffff,0xffff,0x85b9,0x3435,0xefbf,0xffff,0x6d58,0x1bd4,0x23d4,0xd73d,0xffff,0x95fa,0x2c14,0xae7b,0xffff,0xa63a,0x1bd4,0x1bd4,0xef9e,0xffff,0x6d58,0x4c96,0xffff,0xd73d,0x2c14,0x3435,0x7d78,0x961a,0x1bd4,0x23d4,0xd73d,0xffff,0x95fa,0x2c14,0xae7b,0xffff,0xa63a,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xefbf,0xffff,0x8599,0x1bd4,0x7558,0xffff,0xffff,0x23f4,0x1bd4,0xcf1d,0xffff,0x8dfa,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x9e3a,0xffff,0xae7b,0x1bd4,0xefbf,0xffff,0x8599,0x1bd4,0x7558,0xffff,0xffff,0x23f4,0x1bd4,0xcf1d,0xffff,0x8dfa,0x1bd4,0x6517,0xffff,0xffff,0x23f4,0x1bd4,0x4cb6,0xffff,0xffff,0x2bf4,0x1bd4,0xef9e,0xffff,0x6d58,0x54d7,0xffff,0xf7bf,0x7d99,0x54d6,0x2c14,0x1bd4,0x1bd4,0x6517,0xffff,0xffff,0x23f4,0x1bd4,0x4cb6,0xffff,0xffff,0x2bf4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x1bd4,0x85d9,0xdf5d,0xf7df,0xffff,0xffff,0xffff,0xc6fc,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x7d99,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0x4476,0x1bd4,0xef9e,0xffff,0x6d58,0x1bd4,0xb69b,0xffff,0xffff,0xffff,0xffff,0x961a,0x1bd4,0x7d99,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0xffff,0x4476,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x6517,0xffff,0xf7df,0x4476,0x1bd4,0xa63b,0xffff,0xc6fd,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x6517,0xffff,0xf7df,0x23d4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xef9e,0xffff,0x6d58,0x1bd4,0x1bd4,0x2c14,0x54d6,0x961a,0xffff,0xffff,0x2c14,0x6517,0xffff,0xf7df,0x23d4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x6537,0xffff,0xf7bf,0x3c75,0x4476,0xefbe,0xffff,0xc6fd,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x23d4,0xdf5d,0xffff,0x9e1a,0x2bf4,0x3435,0x6d58,0xb6bc,0x1bd4,0x1bd4,0xef9e,0xffff,0x6d58,0x4cb6,0xa65b,0x4c96,0x23f4,0x54d7,0xffff,0xf7df,0x23d4,0x23d4,0xdf5d,0xffff,0x9e1a,0x2bf4,0x3435,0x6d58,0xb6bc,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x1bd4,0x9e3a,0xefbf,0xefbf,0xbebc,0xae7b,0xffff,0xc6fd,0x1bd4,0xefbf,0xffff,0x6d58,0x1bd4,0x6d38,0xffff,0xf7bf,0x1bd4,0x1bd4,0xcf1d,0xffff,0x95fa,0x1bd4,0x1bd4,0x2c14,0x9e1a,0xdf5e,0xf7df,0xe77e,0xae7b,0x4476,0x1bd4,0x1bd4,0xef9e,0xffff,0x6d58,0x1bd4,0x6d58,0xcefd,0xf7df,0xf7bf,0xcefd,0x54d7,0x1bd4,0x1bd4,0x2c14,0x9e1a,0xdf5e,0xf7df,0xe77e,0xae7b,0x4476,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x1bd4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xbdf8,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xd6dc,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x39c8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xbdf8,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xd6dc,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x39c8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x5b0d,0xef7e,0xef7e,0xef7e,0xef7e,0xe73d,0xc639,0x8411,0x18e4,0x0883,0x0883,0x0883,0x0883,0x10c4,0x7c11,0xc65a,0xe73d,0xe73d,0xc65a,0x9cf4,0x4a8b,0x10a3,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x2125,0x9d15,0xdf1d,0xd6dc,0xa535,0x2146,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x0883,0x0883,0x10c4,0x73d0,0xbe19,0xe73d,0xe75e,0xd69b,0x9cd4,0x31a8,0x0883,0x0883,0x0883,0x0883,0x10c4,0x73d0,0xbe19,0xe73d,0xe75e,0xd69b,0x9cd4,0x31a8,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x5b0d,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xc639,0x10c4,0x0883,0x0883,0x0883,0xa535,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x39e9,0x0883,0x7bf0,0xef7e,0xef7e,0xad97,0xce7a,0xef7e,0xef7e,0xef7e,0xef7e,0xc639,0x10a3,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x0883,0x1905,0xc65a,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xe75d,0x52ab,0x0883,0x0883,0x1905,0xc65a,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xe75d,0x52ab,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x6b8f,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x10c4,0x39c8,0xc639,0xef7e,0xef7e,0x632d,0x0883,0x0883,0x10a4,0xef5e,0xef7e,0xce9b,0x2987,0x10c4,0x2987,0x5b0d,0xb597,0x39e8,0x0883,0x7bf0,0xef7e,0xef7e,0xef7e,0x8c72,0x1905,0x4a8b,0xe75e,0xef7e,0xef7e,0x3a09,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x0883,0x9cf5,0xef7e,0xef7e,0xc65a,0x31a8,0x1905,0x8c72,0xef7e,0xef7e,0xdf1d,0x1905,0x0883,0x9cf5,0xef7e,0xef7e,0xc65a,0x31a8,0x1905,0x8c72,0xef7e,0xef7e,0xdf1d,0x1905,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x6b8f,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x73b0,0xef7e,0xef7e,0x9cf4,0x0883,0x0883,0x10a3,0xe73d,0xef7e,0xd6dc,0x4a8b,0x2146,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xd6db,0x10a3,0x0883,0x0883,0xc639,0xef7e,0xef7e,0x5b0d,0x0883,0x10c4,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x7c11,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x18c4,0xe75e,0xef7e,0xef7e,0x4a8b,0x0883,0x0883,0x10a4,0xdedc,0xef7e,0xef7e,0x634e,0x18c4,0xe75e,0xef7e,0xef7e,0x4a8b,0x0883,0x0883,0x10a4,0xdedc,0xef7e,0xef7e,0x634e,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x18c4,0x7bf0,0xbe19,0xdf1d,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xad97,0x0883,0x0883,0x0883,0x94d4,0xef7e,0xef7e,0xef7e,0xef7e,0xe71d,0xb5b7,0x632d,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xad76,0x0883,0x0883,0x0883,0xb5d8,0xef7e,0xef7e,0x6b6e,0x0883,0x10c4,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x7c11,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x31c8,0xef7e,0xef7e,0xef7e,0x2146,0x0883,0x0883,0x0883,0xb5b7,0xef7e,0xef7e,0x8c72,0x31c8,0xef7e,0xef7e,0xef7e,0x2146,0x0883,0x0883,0x0883,0xb5b7,0xef7e,0xef7e,0x8c72,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0xb5d8,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xb5b7,0x0883,0x0883,0x0883,0x10a4,0x738f,0xbdd8,0xe71d,0xef7e,0xef7e,0xef7e,0xef7e,0x6b8f,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0xb5d7,0xef7e,0xef7e,0x6b6e,0x0883,0x10c4,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x7c11,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x31c8,0xef7e,0xef7e,0xef7e,0x2146,0x0883,0x0883,0x0883,0xb5b7,0xef7e,0xef7e,0x8c72,0x31c8,0xef7e,0xef7e,0xef7e,0x2146,0x0883,0x0883,0x0883,0xb5b7,0xef7e,0xef7e,0x8c72,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x2987,0xef7e,0xef7e,0xef7e,0x52ab,0x10c4,0x0883,0x7c11,0xef7e,0xef7e,0xb5b7,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x2125,0x73d0,0xef7e,0xef7e,0xbdf8,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0xb5d7,0xef7e,0xef7e,0x6b6e,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x18c4,0xe75e,0xef7e,0xef7e,0x4a8b,0x0883,0x0883,0x10a4,0xd6dc,0xef7e,0xef7e,0x634e,0x18c4,0xe75e,0xef7e,0xef7e,0x4a8b,0x0883,0x0883,0x10a4,0xd6dc,0xef7e,0xef7e,0x634e,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x2967,0xef7e,0xef7e,0xef7e,0x422a,0x10c4,0x424a,0xdefc,0xef7e,0xef7e,0xb5b7,0x0883,0x0883,0x0883,0xb5d7,0x738f,0x39c8,0x1905,0x10c4,0x6b8f,0xef7e,0xef7e,0xbe19,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0xb5d7,0xef7e,0xef7e,0x6b6e,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x0883,0x9cf5,0xef7e,0xef7e,0xc639,0x31a8,0x1905,0x8c72,0xef7e,0xef7e,0xdf1d,0x1905,0x0883,0x9cf5,0xef7e,0xef7e,0xc639,0x31a8,0x1905,0x8c72,0xef7e,0xef7e,0xdf1d,0x1905,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0xbdf8,0xef7e,0xef7e,0xef7e,0xef7e,0xe75e,0x9d15,0xef7e,0xef7e,0xb5b7,0x0883,0x0883,0x0883,0xdefc,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x6b6e,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0xb5d7,0xef7e,0xef7e,0x6b6e,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x0883,0x1905,0xc65a,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xe75d,0x52ab,0x0883,0x0883,0x1905,0xc65a,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xe75d,0x52ab,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x5aec,0xef7e,0xef7e,0xef7e,0x10c4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x2125,0x94d4,0xd6db,0xe73d,0xbdf8,0x424a,0x6b8f,0xef7e,0xef7e,0xb5b7,0x0883,0x0883,0x0883,0x2987,0x7c11,0xbdf8,0xdedc,0xef5e,0xdefc,0xb597,0x52cc,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0xb5d7,0xef7e,0xef7e,0x6b6e,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x8452,0xef7e,0xef7e,0xc65a,0x0883,0x0883,0x0883,0x0883,0x18c4,0x73d0,0xc619,0xe73d,0xe75e,0xd6bb,0x9cf4,0x31a8,0x0883,0x0883,0x0883,0x0883,0x18c4,0x73d0,0xc619,0xe73d,0xe75e,0xd6bb,0x9cf4,0x31a8,0x0883,0x0883,0x0883,0x0883,0x7bf0,0xef7e,0xef7e,0xa515,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x2988,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x3a2b,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883}; +static const unsigned short st_bereit[2048]={0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x76b1,0x65ef,0x438a,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x658e,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7670,0x658e,0x32c8,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x658e,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x7690,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x65ae,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x21c6,0x76d1,0x7ef1,0x32c8,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x08a3,0x32a8,0x7ef1,0x7ed1,0x2206,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x6e0f,0x7ef1,0x4c2b,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x7690,0x7ef1,0x438a,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x21a6,0x76d1,0x7ef1,0x32c8,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x7690,0x7ef1,0x3b69,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x658e,0x10e4,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x4c0b,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x08a3,0x32a8,0x7ef1,0x7670,0x1945,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x4c0b,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x1104,0x656e,0x7ef1,0x5d0d,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x76b1,0x2a67,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x43aa,0x7ef1,0x7690,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x10e4,0x3b8a,0x7ef1,0x76b1,0x2206,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x1104,0x656e,0x7ef1,0x5d4e,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x5d2d,0x7ef1,0x65ef,0x10a3,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x76b1,0x6e2f,0x548c,0x1924,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7670,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x1985,0x76d1,0x7ef1,0x3b69,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7670,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883}; +static const unsigned short st_lesen[2048]={0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xbdf8,0x0883,0x0883,0x1905,0x9493,0xd6bb,0xe75e,0xe73d,0xd6bb,0x94d4,0x0883,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xbdf8,0x0883,0xc639,0xef7e,0xef7e,0x39e9,0x0883,0x0883,0x9cf4,0xef7e,0xa556,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xad76,0xef7e,0x7bf0,0x10c4,0x2966,0x632d,0x9cf4,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xb5d8,0x0883,0x0883,0x9cf4,0xef7e,0xa556,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0x10a3,0xe75e,0xef7e,0x424a,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0x52cc,0x0883,0x9cf4,0xef7e,0xa556,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xdf1d,0xef7e,0xe73d,0x9d15,0x6b6e,0x2987,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9d15,0xe75e,0xce7a,0x10a4,0x9cf4,0xef7e,0xa556,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x8452,0x0883,0x0883,0x632e,0xe75e,0xef7e,0xef7e,0xef7e,0xef7e,0x9cf4,0x10a3,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0x8452,0x0883,0xc639,0xef7e,0x8431,0x8c72,0xef7e,0x6b8f,0x9cf4,0xef7e,0xa556,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x2966,0x738f,0xad76,0xe73d,0xef7e,0xef7e,0x4a8b,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x8431,0x1905,0xdefc,0xdefc,0xa556,0xef7e,0xa556,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x2146,0xef5e,0xef7e,0x5aec,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x8431,0x0883,0x738f,0xef7e,0xef7e,0xef7e,0xa556,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xbdf8,0x5b0d,0x2967,0x10c4,0x4a6b,0xef7e,0xdf1d,0x2146,0x0883,0x0883,0xc639,0xef7e,0x9cf5,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0x8431,0x0883,0x10a4,0xce9a,0xef7e,0xef7e,0xa556,0x0883,0x0883,0xa535,0xef7e,0x94d4,0x0883,0x0883,0xa535,0xef7e,0x94d4,0x0883,0x0883,0xa535,0xef7e,0x94d4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xdefc,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xdefc,0x0883,0x0883,0xa556,0xce7a,0xdf1d,0xef5e,0xdedc,0xad97,0x3a09,0x0883,0x0883,0x0883,0xc639,0xef7e,0xef7e,0xef7e,0xef7e,0xef7e,0xdefc,0x0883,0xc639,0xef7e,0x8431,0x0883,0x0883,0x52cc,0xef7e,0xef7e,0xa556,0x0883,0x0883,0xa535,0xef7e,0x94d4,0x0883,0x0883,0xa535,0xef7e,0x94d4,0x0883,0x0883,0xa535,0xef7e,0x94d4,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883}; +static const unsigned short st_schreiben[2048]={0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x18e4,0x9388,0xd50a,0xed8b,0xe56b,0xd50a,0x93a8,0x0883,0x0883,0x0883,0x3144,0x9ba8,0xd50a,0xed8b,0xe56a,0xccca,0x7ae7,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xe54a,0xc489,0x5a46,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xbc89,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xed8b,0xccca,0x7ae7,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xbc89,0x0883,0x0883,0xc4a9,0xf5ab,0xed8b,0x3985,0x0883,0x0883,0x9bc8,0xf5ab,0xac08,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xac29,0xf5ab,0x7b07,0x10c3,0x2924,0x6286,0x9bc8,0x0883,0x0883,0x49e5,0xed6b,0xed8b,0x7b07,0x2104,0x2104,0x5a46,0x8b47,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x1083,0x5a46,0xf5ab,0xed8b,0x41a5,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x3985,0xed8b,0xf5ab,0x5a66,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xbc69,0x0883,0x0883,0x9bc8,0xf5ab,0xac08,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x10a3,0xed8b,0xf5ab,0x49e5,0x0883,0x0883,0x0883,0x0883,0x0883,0x10a3,0xdd0a,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xe56a,0xf5ab,0x7b07,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xd50a,0xf5ab,0x8b67,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0xed8b,0xf5ab,0x5226,0x0883,0x9bc8,0xf5ab,0xac08,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xe54a,0xf5ab,0xe56a,0xa3e8,0x6aa6,0x2944,0x0883,0x0883,0x41c5,0xf5ab,0xf5ab,0x5205,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xe56a,0xf5ab,0x72e7,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x3164,0xed8b,0xf5ab,0x5a46,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0xa3c8,0xed8b,0xd4ea,0x10a3,0x9bc8,0xf5ab,0xac08,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x6286,0xed8b,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0x9bc8,0x1083,0x5a46,0xf5ab,0xf5ab,0x3985,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x1083,0x5a46,0xf5ab,0xe54a,0x2924,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0x8b47,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xc489,0x18c3,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0x8b47,0x0883,0x0883,0xc4a9,0xf5ab,0x8327,0x8b67,0xf5ab,0x72c6,0x9bc8,0xf5ab,0xac08,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x2924,0x72c6,0xac29,0xed6b,0xf5ab,0xf5ab,0x4a05,0x41c5,0xf5ab,0xf5ab,0x5205,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xed6b,0x4a05,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x20e4,0xbc69,0xf5ab,0xac29,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x8327,0x18e4,0xe54a,0xe54a,0xac08,0xf5ab,0xac08,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x2924,0xed8b,0xf5ab,0x5a46,0x10a3,0xdd0a,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x18c3,0x72e7,0xf5ab,0xed8b,0x41c5,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x7b07,0xf5ab,0xe56a,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x8327,0x0883,0x72c6,0xf5ab,0xed8b,0xf5ab,0xac08,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xbc89,0x6266,0x2944,0x10a3,0x49e5,0xed8b,0xe54a,0x2104,0x0883,0x49e5,0xed6b,0xed8b,0x7b07,0x2104,0x2104,0x5226,0x8347,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xb449,0xf5ab,0xccca,0x10a3,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x20e4,0xbc69,0xf5ab,0xb449,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xc4a9,0xf5ab,0x8327,0x0883,0x10a3,0xd4ea,0xf5ab,0xf5ab,0xac08,0x0883,0x0883,0xa3e8,0xf5ab,0x9ba8,0x0883,0x0883,0xa3e8,0xf5ab,0x9ba8,0x0883,0x0883,0xa3e8,0xf5ab,0x9ba8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0xac08,0xccea,0xe54a,0xed8b,0xdd2a,0xb429,0x41a5,0x0883,0x0883,0x0883,0x3164,0x9ba8,0xd50a,0xed8b,0xe56b,0xd4ea,0x7b07,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x0883,0xbc69,0xf5ab,0xac08,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0x3164,0xed8b,0xf5ab,0x72e7,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xdd4a,0x0883,0x0883,0xc4a9,0xf5ab,0x9bc8,0x0883,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xed8b,0xd50a,0x9bc8,0x2104,0x0883,0xc4a9,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xf5ab,0xdd4a,0x0883,0x0883,0xc4a9,0xf5ab,0x8327,0x0883,0x0883,0x5a26,0xf5ab,0xf5ab,0xac08,0x0883,0x0883,0xa3e8,0xf5ab,0x9ba8,0x0883,0x0883,0xa3e8,0xf5ab,0x9ba8,0x0883,0x0883,0xa3e8,0xf5ab,0x9ba8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883}; +static const unsigned short st_fertig[2048]={0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x658e,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x658e,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7670,0x658e,0x32c8,0x0883,0x7690,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x65ae,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x1965,0x4c4b,0x6e0f,0x76b1,0x76b1,0x6e50,0x5d4e,0x2206,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x08a3,0x32a8,0x7ef1,0x7ed1,0x2206,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x2a27,0x76b1,0x7ed1,0x43ea,0x1945,0x10e4,0x21e6,0x4c4b,0x32a8,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x7690,0x7ef1,0x438a,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x10a3,0x6e30,0x7ef1,0x548c,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x7690,0x7ef1,0x3b69,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x2a06,0x7ef1,0x7ef1,0x2a67,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x4c0b,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x4c0b,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x08a3,0x32a8,0x7ef1,0x7670,0x1945,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x32a8,0x7ef1,0x7ef1,0x21c6,0x0883,0x1924,0x7ef1,0x7ef1,0x7ef1,0x5d2d,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x76b1,0x2a67,0x0883,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x2a06,0x7ef1,0x7ef1,0x2a67,0x0883,0x0883,0x0883,0x4c6c,0x7ef1,0x5d2d,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x10e4,0x3b8a,0x7ef1,0x76b1,0x2206,0x0883,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x10a3,0x6e30,0x7ef1,0x546c,0x0883,0x0883,0x0883,0x4c6c,0x7ef1,0x5d2d,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x5d2d,0x7ef1,0x65ef,0x10a3,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x2a47,0x76b1,0x76d1,0x43aa,0x1925,0x10c4,0x5ced,0x7ef1,0x5d2d,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7ef1,0x7670,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x1985,0x76d1,0x7ef1,0x3b69,0x0883,0x0883,0x658e,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x0883,0x65ae,0x7ef1,0x54ac,0x0883,0x0883,0x0883,0x1985,0x548c,0x6e2f,0x76d1,0x76b1,0x6e30,0x5d4d,0x3b29,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883,0x0883}; +#endif + +/* Panel init sequence (offset,val), taken from the firmware, replayed as is */ +static const unsigned int panel_init[][2]={{0x8,0x1},{0x0,0x0},{0x4,0x0},{0x0,0x0},{0x20,0x0},{0x0,0x700},{0x24,0x80000000},{0x24,0x0},{0x24,0x80000000},{0x24,0x0},{0x0,0x1},{0x0,0xc0},{0x1c,0x11},{0x0,0xc0},{0x1c,0x36},{0x0,0xc0},{0x1c,0x8},{0x0,0xc0},{0x1c,0x3a},{0x0,0xc0},{0x1c,0x5},{0x0,0xc0},{0x1c,0x26},{0x0,0xc0},{0x1c,0x1},{0x0,0xc0},{0x1c,0x20},{0x0,0xc0},{0x1c,0xb1},{0x0,0xc0},{0x1c,0x8},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0xb2},{0x0,0xc0},{0x1c,0x8},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0xb3},{0x0,0xc0},{0x1c,0x8},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0x8},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0x3b},{0x0,0xc0},{0x1c,0xb4},{0x0,0xc0},{0x1c,0x3},{0x0,0xc0},{0x1c,0xc0},{0x0,0xc0},{0x1c,0xe0},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x84},{0x0,0xc0},{0x1c,0xc1},{0x0,0xc0},{0x1c,0xc4},{0x0,0xc0},{0x1c,0xc2},{0x0,0xc0},{0x1c,0xd},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0xc3},{0x0,0xc0},{0x1c,0x8d},{0x0,0xc0},{0x1c,0x2a},{0x0,0xc0},{0x1c,0xc4},{0x0,0xc0},{0x1c,0x8d},{0x0,0xc0},{0x1c,0xee},{0x0,0xc0},{0x1c,0xc5},{0x0,0xc0},{0x1c,0x6},{0x0,0xc0},{0x1c,0xe0},{0x0,0xc0},{0x1c,0xd},{0x0,0xc0},{0x1c,0x17},{0x0,0xc0},{0x1c,0x16},{0x0,0xc0},{0x1c,0x28},{0x0,0xc0},{0x1c,0x3f},{0x0,0xc0},{0x1c,0x39},{0x0,0xc0},{0x1c,0x30},{0x0,0xc0},{0x1c,0x31},{0x0,0xc0},{0x1c,0x2c},{0x0,0xc0},{0x1c,0x28},{0x0,0xc0},{0x1c,0x2f},{0x0,0xc0},{0x1c,0x39},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x4},{0x0,0xc0},{0x1c,0x1},{0x0,0xc0},{0x1c,0x10},{0x0,0xc0},{0x1c,0xe1},{0x0,0xc0},{0x1c,0xa},{0x0,0xc0},{0x1c,0x15},{0x0,0xc0},{0x1c,0x18},{0x0,0xc0},{0x1c,0x25},{0x0,0xc0},{0x1c,0x3f},{0x0,0xc0},{0x1c,0x37},{0x0,0xc0},{0x1c,0x2e},{0x0,0xc0},{0x1c,0x30},{0x0,0xc0},{0x1c,0x2f},{0x0,0xc0},{0x1c,0x2c},{0x0,0xc0},{0x1c,0x33},{0x0,0xc0},{0x1c,0x3f},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x3},{0x0,0xc0},{0x1c,0x4},{0x0,0xc0},{0x1c,0x10},{0x0,0xc0},{0x1c,0x35},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x29},{0x0,0xc0},{0x1c,0x2a},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x2},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x83},{0x0,0xc0},{0x1c,0x2b},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x1},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x81},{0x0,0xc0},{0x1c,0x11},{0x0,0xc0},{0x8,0x1},{0x0,0x0},{0x4,0x0},{0x0,0x0},{0x20,0x0},{0x0,0x700},{0x24,0x80000000},{0x24,0x0},{0x24,0x80000000},{0x24,0x0},{0x0,0x1},{0x0,0xc0},{0x1c,0x2a},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x2},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x81},{0x0,0xc0},{0x1c,0x2b},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x1},{0x0,0xc0},{0x1c,0x0},{0x0,0xc0},{0x1c,0x80},{0x0,0xc0},{0x8,0x1},{0x0,0x0},{0x4,0x0},{0x0,0x0},{0x20,0x0},{0x0,0x700},{0x24,0x80000000},{0x24,0x0},{0x24,0x80000000},{0x24,0x0},{0x0,0x1},{0x0,0xc0},{0x1c,0x2c},{0x0,0xc0}}; +#define PANEL_INIT_N 238 diff --git a/flash/src/build.sh b/flash/src/build.sh new file mode 100644 index 0000000..426dbba --- /dev/null +++ b/flash/src/build.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Builds the flash app (Cortex-M4, Thumb) into ../flashapp.bin. +# Needs clang, ld.lld and llvm-objcopy. The result is byte-identical to the +# flashapp.bin shipped in this folder. +set -e +cd "$(dirname "$0")" +clang --target=thumbv7em-none-eabi -mcpu=cortex-m4 -mthumb -ffreestanding -nostdlib -Os -fno-common -DFW_PRECHECK -c fw.c -o /tmp/fw.o +ld.lld -T link.ld --no-rosegment /tmp/fw.o -o /tmp/fw.elf +llvm-objcopy -O binary /tmp/fw.elf ../flashapp.bin +echo "done: flashapp.bin" diff --git a/flash/src/disp_power.h b/flash/src/disp_power.h new file mode 100644 index 0000000..5e7e060 --- /dev/null +++ b/flash/src/disp_power.h @@ -0,0 +1,5 @@ +// Taken from the original flash utility (same PRAM/post-reset context as +// our app). Order kept exactly. The clk tail (reset release) comes first, +// then the display/GPIO/backlight registers. +static const unsigned int disp_power_seq[][2]={{0x45000020,0x40},{0x45000210,0x0},{0x45000214,0x0},{0x45000218,0x0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000204,0x0},{0x45000200,0xe0},{0x45000020,0x42},{0x4003a000,0x8000},{0x4003a004,0x8000},{0x4003a004,0x8001},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40007034,0x0},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18000ba0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x40038014,0xf0},{0x40038018,0xa001},{0x40038014,0xf0},{0x40038004,0x18005da0},{0x40038008,0xffc},{0x4003800c,0x1},{0x40038010,0x1},{0x40038000,0x10},{0x40038000,0x0},{0x4001803c,0xffffffff},{0x4001903c,0xfffff5df},{0x4001a03c,0xffffffff},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a56},{0x40018004,0x30},{0x40018000,0xfffffffe},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a59},{0x40018004,0x30},{0x40018000,0xfffffffd},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a65},{0x40018004,0x30},{0x40018000,0xfffffffb},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a95},{0x40018004,0x30},{0x40018000,0xfffffff7},{0x40018008,0x15008a55},{0x40018004,0x20},{0x40018000,0xffffffef},{0x40018008,0x15008a55},{0x40018004,0x30},{0x40018000,0xffffffef},{0x40018008,0x15008855},{0x40018004,0x10},{0x40018000,0xffffffcf},{0x40018008,0x15008855},{0x40018004,0x30},{0x40018000,0xffffffcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffff4f},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15028055},{0x40018004,0x30},{0x40018000,0xfffffecf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15088055},{0x40018004,0x30},{0x40018000,0xfffffdcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15208055},{0x40018004,0x30},{0x40018000,0xfffffbcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15808055},{0x40018004,0x30},{0x40018000,0xfffff7cf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x16008055},{0x40018004,0x30},{0x40018000,0xffffefcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x19008055},{0x40018004,0x30},{0x40018000,0xffffdfcf},{0x40018008,0x15008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x25008055},{0x40018004,0x30},{0x40018000,0xffffbfcf},{0x40018008,0x15008055},{0x40019004,0xa00},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55996800},{0x40019004,0xa20},{0x40019000,0xfffff59f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55999800},{0x40019004,0xa20},{0x40019000,0xfffff55f},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x559a5800},{0x40019004,0xa20},{0x40019000,0xfffff4df},{0x40019008,0x55995800},{0x40019004,0x820},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800},{0x40019004,0x220},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xfffff5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x56995800},{0x40019004,0xa20},{0x40019000,0xffffe5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x59995800},{0x40019004,0xa20},{0x40019000,0xffffd5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x65995800},{0x40019004,0xa20},{0x40019000,0xffffb5df},{0x40019008,0x55995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x95995800},{0x40019004,0xa20},{0x40019000,0xffff75df},{0x40019008,0x55995800},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x52},{0x4001a004,0x0},{0x4001a000,0xfffffffe},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x58},{0x4001a004,0x0},{0x4001a000,0xfffffffd},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x60},{0x4001a004,0x0},{0x4001a000,0xfffffffb},{0x4001a008,0x50},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x90},{0x4001a004,0x0},{0x4001a000,0xfffffff7},{0x4001a008,0x50},{0x40003000,0x0},{0x40003018,0x0},{0x4000301c,0x0},{0x40003020,0x0},{0x40003024,0x0},{0x40003014,0x0},{0x40003000,0x2},{0x40003008,0x0},{0x4000303c,0x1f},{0x40003000,0x1},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55a95800},{0x40019004,0xa20},{0x40019000,0xfffff1df},{0x40019008,0x55995800}}; +#define DISP_POWER_N 262 diff --git a/flash/src/fw.c b/flash/src/fw.c new file mode 100644 index 0000000..54bacaf --- /dev/null +++ b/flash/src/fw.c @@ -0,0 +1,739 @@ +#include "io.h" +#ifndef ANZEIGE +#define ANZEIGE 1 +#endif +#ifndef PIX_BURST +#define PIX_BURST 0 /* 1 = old block transfer (1.3.7) */ +#endif +#ifndef HALTBILD +/* 1 = default: the panel stays on while reading/writing and the progress bar is + * updated live, like the original flash utility. Confirmed on the device + * (dump with persistent screen is byte-identical to the P-COM reference). + * 0 = proven fallback: screen only while idle, the panel turns off during access. */ +#define HALTBILD 1 +#endif +/* + * Custom flash app for the Tamagotchi Paradise (mameise). + * Runs from PRAM 0, loaded through the dongle via PDLO. Speaks PAU1 over UART1, + * so the existing Windows tool (dump, write back) works unchanged. + * + * Only constants (.rodata) and fixed SRAM addresses, no .data/.bss, so no + * copy at load time is needed. + */ + +/* ---- UART1 (0x4000B000) ---- */ +#define U_DATA REG(UART+0x00) +#define U_IER REG(UART+0x04) +#define U_FCR REG(UART+0x08) +#define U_LCR REG(UART+0x0C) +#define U_LSR REG(UART+0x14) +#define U_FDR REG(UART+0x28) +#define U_CTRL REG(UART+0x30) + +/* ---- Flash controller (0x40022000) ---- */ +#define F_STAT REG(FCTL+0x000) +#define F_CMD REG(FCTL+0x004) +#define F_IDX REG(FCTL+0x010) +#define F_DATA REG(FCTL+0x014) +#define F_JED REG(FCTL+0x018) +#define F_DMEM REG(FCTL+0x100) +#define F_DLEN REG(FCTL+0x104) +#define F_DCTL REG(FCTL+0x108) +#define F_DFLA REG(FCTL+0x10C) + +/* ---- fixed SRAM buffers (128 KB SRAM at 0x18000000, stack at 0x1801F000) ---- + * 1.8.0: blocks grown to 4 KB (MAXP), so the I/O buffers are now 8 KB apart. + * A 4 KB payload frame is 28+4096+4 = 4128 bytes, slightly more when COBS + * encoded, and fits in 8 KB with room to spare. The layout does not overlap and + * the stack stays free (COBSO ends at 0x19FFF, the stack grows down from 0x1F000). */ +#define DMABUF 0x18010000u /* 4 KB, target/source of the flash DMA */ +#define SECBUF 0x18011000u /* 4 KB, sector staging for writes */ +#define RXACC 0x18012000u /* 8 KB, raw COBS buffer */ +#define FRAME 0x18014000u /* 8 KB, decoded frame */ +#define OUTF 0x18016000u /* 8 KB, reply frame */ +#define COBSO 0x18018000u /* 8 KB, COBS encoded reply */ + +#define FLASH_SIZE 0x1000000u +#ifndef MAXP +#define MAXP 4096u /* Block size. 1024 = proven fallback. */ +#endif + +static u8* const dma = (u8*)DMABUF; +static u8* const sec = (u8*)SECBUF; +static u8* const rxac = (u8*)RXACC; +static u8* const frm = (u8*)FRAME; +static u8* const outf = (u8*)OUTF; +static u8* const cob = (u8*)COBSO; + +/* ============================ Hardware init ============================ */ +/* Faithful to the firmware (SystemInit, clock routine 0x8c38+0x8a58). XIP is + * NOT needed: we run from PRAM and read the flash via DMA. */ +static void clock_init(void){ + REG(CLK+0x00) |= 1u; + REG(CLK+0x0C) = 0; + REG(CLK+0x00) = 0x41u; + { u32 r = (REG(CLK+0x34) & 0xF00u) | 0xA55A0000u; REG(CLK+0x04) = r; } + REG(CLK+0x18) = 0x21u; + REG(CLK+0x50) = 0; + REG(CLK+0x10C) = 0x001FFFFDu; + REG(CLK+0x110) = 0; + REG(CLK+0x108) = 0; + REG(CLK+0x10) = 0; + REG(CLK+0x00) |= 0x10u; + while(!((REG(CLK+0x08) >> 4) & 1u)){} + REG(CLK+0x00) |= 0x4000u; + REG(CLK+0x04) &= ~1u; + REG(CLK+0x00) |= 0x8000u; + while(!((REG(CLK+0x08) >> 6) & 1u)){} + { u32 r = (REG(CLK+0x0C) & ~7u) | 4u; REG(CLK+0x0C) = r; } + while( ((REG(CLK+0x0C) >> 4) & 7u) != (REG(CLK+0x0C) & 7u) ){} + REG(CLK+0x100) = 0x00157EB7u; +} +static void flashctl_init(void){ + /* 1.4.2: enable XIP. We read through the 0x60000000 window that the XIP block + * maps in. Without XIP that window only shows the config register (0x40), not + * the flash data. The original flash utility does this at startup, our app did + * not do it after reset until now. That was exactly what was missing. */ + REG(0x4002F004u)=0x60011000u; + REG(0x4002F000u)=0x00000003u; + /* 1.4.1: controller init exactly like the original flash utility (0x40022000). + * This includes setting the read command/mode in 0x008 and 0x00c (0x3077 / 0xf000), + * otherwise the chip only returns its config register (0x40) instead of the flash data. */ + F_STAT=0x0000d018u; + F_STAT=0x0000d000u; + F_STAT=0x0000d080u; + F_STAT=0x0000d088u; + REG(FCTL+0x008)=0x00003077u; /* read command/mode */ + REG(FCTL+0x00C)=0x0000f000u; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; +} +#if ANZEIGE +static void arm_for_dump(void); +#endif +static void uart_init(void){ + U_LCR=0x83; U_DATA=0x1A; U_IER=0x00; U_LCR=0x03; U_FDR=0x100; U_FCR=0x07; U_CTRL=0xC1; +} + +/* ============================ UART input/output ============================ */ +static void putb(u8 c){ while(!(U_LSR & 0x20u)){} U_DATA=c; } +static int getb(void){ + u32 g=0; + while(!(U_LSR & 0x01u)){ + if((++g & 0x3FFFFu)==0){ REG(0x4000800Cu)=0x5AFA55AAu; REG(0x4000900Cu)=0x5AFA55AAu; } /* feed the watchdog */ + } + return (int)(U_DATA & 0xFF); +} + +/* ============================ Flash via DMA ============================ */ +static void fctl_bracket(void){ /* like the firmware before each transfer */ + u32 r=F_STAT; F_STAT=r & ~0x10u; REG(FCTL+0x020)=0; F_IDX=0; F_STAT=r | 0x10u; +} +#define SPIN 2000000u +/* 1.4.0: read EXACTLY like the original flash utility (taken from its trace). + * Two things we had wrong so far, hidden by the emulator (it masks the flash + * address and reads directly, so it always read correctly): + * 1. The flash address is given with the XIP base 0x60000000 (60xxxxxx), + * not bare. Without the base the real chip reads nothing -> all 0xFF. + * 2. Status sequence at 0x40022000: d008 (read mode) -> 0x20=0, 0x10=0 -> d088, + * only then the DMA. */ +/* 1.4.3: read through direct CPU access to the XIP window 0x60000000. + * Tested against four methods on the device: only this one returns real data + * (SONIXDEV), the controller DMA only gave the config register 0x40. Word by + * word for speed. */ +static void flash_read(u32 foff, u32 dst, u32 len){ + const volatile u32* s=(const volatile u32*)(0x60000000u + (foff & 0x00FFFFFFu)); + u32* d=(u32*)dst; + u32 w=len>>2; + for(u32 i=0;i>1; + u32 hi=(a1>>16)&0xFFFFu; /* = addr>>17 */ + u32 lo=a1 & 0xFFFFu; /* = (addr>>1)&0xFFFF */ + /* Step 1: ERASE the sector - command WITHOUT mode bit (like 0x38b0 in the FU). */ + REG(FCTL+0x008)=hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + for(u32 g=0; (REG(FCTL+0x004)&0x400u) && g<60000000u; g++){} + for(volatile u32 i=0;i<2000000u;i++){} + /* Step 2: PROGRAM - command WITH mode bit 0x3000, then DMA. */ + REG(FCTL+0x008)=0x3000u | hi; + REG(FCTL+0x00C)=lo; + REG(FCTL+0x004)=0x00000400u; + REG(FCTL+0x004)=0x00004000u; + REG(FCTL+0x000)=0x0000d080u; + REG(FCTL+0x020)=0; + REG(FCTL+0x010)=0; + REG(FCTL+0x000)=0x0000d082u; + F_DFLA=0x60000000u | (addr & 0x00FFFFFFu); + F_DLEN=0x1000u; F_DMEM=src; + F_DCTL=0u; + F_DCTL=1u; + for(u32 g=0; (F_DCTL & 1u) && g<20000000u; g++){} + for(volatile u32 i=0;i<2000000u;i++){} +} +static void flash_program(u32 foff, u32 src, u32 len){ + fctl_bracket(); + flash_write_enable(); + F_DFLA=0x60000000u | (foff & 0x00FFFFFFu); F_DLEN=len; F_DMEM=src; + F_DCTL=0u; /* direction memory -> flash */ + F_DCTL=1u; /* Start */ + for(u32 g=0; (F_DCTL & 1u) && g>1)) : (crc>>1); } + return crc; +} +static u32 crc32_flash(u32 foff, u32 len){ + u32 crc=0xFFFFFFFFu; + for(u32 o=0;o=0x45000210u && a<=0x45000218u) v=REG(0x4001803Cu + ((a-0x45000210u)>>2)*0x1000u); + REG(a)=v; + } + /* Make sure the panel pins are outputs: reset, D/C, CS (P1.5 low), power (P1.9 low) */ + LCD_RST(1); BB(GPIO0+0x04,4)=1; + LCD_DC(0); BB(GPIO0+0x04,5)=1; + BB(GPIO1+0x00,5)=0; BB(GPIO1+0x04,5)=1; + BB(GPIO1+0x00,9)=0; BB(GPIO1+0x04,9)=1; + MS(20); +} + +#define SPI_CTRL REG(PANEL+0x00) +#define SPI_STAT REG(PANEL+0x0C) +#define SPI_DATA REG(PANEL+0x1C) +#define SPIWAIT 200000u +static void spi_init(void){ + /* like FU 0x3f44, as read-modify-write */ + REG(PANEL+0x08)=1; /* clock divider */ + SPI_CTRL &= ~(1u<<18); + REG(PANEL+0x04) &= ~6u; REG(PANEL+0x04) &= ~1u; + SPI_CTRL &= ~0x10u; SPI_CTRL &= ~0x08u; + REG(PANEL+0x20)=0; + SPI_CTRL = (SPI_CTRL & ~0xF00u) | 0x700u; /* 8 bit */ + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFF0000u; + REG(PANEL+0x24) |= 0x80000000u; + REG(PANEL+0x24) &= ~0xFFu; + SPI_CTRL |= 1u; /* SPI on */ + SPI_CTRL |= 0xC0u; /* clear FIFOs */ +} +/* Send n bytes like FU 0x40e0: before each byte wait until TX is not full (bit1), + at the end wait until no longer busy (bit4), then clear the FIFOs. */ +static void spi_tx(const u8* p, u32 n){ + for(u32 i=0;i>8); row[2*x+1]=(u8)p; } +#if PIX_BURST + spi_tx(row, SCR_W*2); +#else + /* 1.3.8: byte by byte like the FU (each byte on its own, wait for the end). + In block mode bytes got lost (FIFO), every line shifted = skewed image. */ + for(u32 i=0;i>8),(u8)rs,(u8)(re>>8),(u8)re}; + lcd_cmd(0x2a,ca,4); lcd_cmd(0x2b,ra,4); + LCD_DC(0); { u8 c=0x2c; spi_tx(&c,1); } + LCD_DC(1); + u8* row=(u8*)0x1801A000u; + for(u32 y=y0;y>8); row[2*x+1]=(u8)p; } + for(u32 i=0;i>8; p[2]=v>>16; p[3]=v>>24; } +static void wr16(u8* p, u16 v){ p[0]=v; p[1]=v>>8; } + +/* sends a finished frame (without CRC/COBS) of length body in outf */ +static void send_frame(u32 bodylen){ + wr32(outf+bodylen-4, crc32_buf(0xFFFFFFFFu, outf, bodylen-4) ^ 0xFFFFFFFFu); + u32 cl=cobs_encode(outf, bodylen, cob); + putb(0); /* frame delimiter */ + for(u32 i=0;i INFO 44 bytes */ + u8* p=reply_head(1,seq,off,0,44); + for(int i=0;i<44;i++) p[i]=0; + wr32(p+0, 0x00010000u); /* appRevision */ + wr32(p+4, 0x00010000u); /* loaderRevision */ + p[8]=1; /* edition (land, display) */ + p[9]=1; /* wave */ + wr16(p+10, (u16)MAXP); /* maxBlock */ + wr32(p+16, 460800u); /* baud */ + wr32(p+24, 0x00C22018u); /* jedecId MX25L12833F */ + wr32(p+32, FLASH_SIZE); /* capacity */ + wr32(p+36, 0); /* flashError */ + send_frame(28+44); return; + } + if(type==5){ /* READ len@payload at off */ +#if WRITETEST + if(off==0){ + u8* p=reply_head(5,seq,0,0,(u16)(plen>=4?rd32(pl):1024)); u32 L=plen>=4?rd32(pl):1024; if(L>MAXP)L=MAXP; + for(u32 i=0;i=4?rd32(pl):MAXP; if(len>MAXP) len=MAXP; +#if WRITEPROBE + /* READ-ONLY PROBE: shows the real controller registers so the write path + * can be built from real values. Does not write or erase anything. */ + if(off==0){ + u8* p=reply_head(5,seq,off,0,(u16)len); + for(u32 i=0;i= FLASH_SIZE) draw_live(st_fertig, 1, 1); +#endif + return; + } + if(type==6){ /* CRC len@payload at off -> 4 bytes */ +#if ANZEIGE + arm_for_dump(); +#if HALTBILD + if((off & 0x000FFFFFu)==0) draw_live(st_schreiben, off, FLASH_SIZE); +#endif +#endif + u32 len=plen>=4?rd32(pl):0; + u32 c=crc32_flash(off,len); + u8* p=reply_head(6,seq,off,0,4); wr32(p,c); + send_frame(28+4); return; + } + if(type==13){ /* WRITE_STATE -> 16 bytes, tested=1 (skip self test) */ + u8* p=reply_head(13,seq,off,0,16); + for(int i=0;i<16;i++) p[i]=0; wr32(p+12,1); + send_frame(28+16); return; + } + if(type==8){ /* WRITE_TEST */ + u8* p=reply_head(8,seq,off,0,4); wr32(p,0); send_frame(28+4); return; + } + if(type==9){ /* WRITE_BEGIN -> startSector 0 */ +#if ANZEIGE && HALTBILD + /* Switch to "writing" right away, otherwise the "done" from the dump stays + on screen until the first sector on a 1 MB boundary. */ + *g_wrcnt=0; draw_live(st_schreiben, 0, 1); +#endif + u8* p=reply_head(9,seq,off,0,4); wr32(p,0); send_frame(28+4); return; + } + if(type==10){ /* WRITE_DATA: payload to SECBUF at off&0xFFF */ + u32 so=off & 0xFFFu; + for(u32 i=0;i=4){ + u32 want=rd32(pl), have=crc32_buf(0xFFFFFFFFu, sec, 0x1000u)^0xFFFFFFFFu; + if(have!=want){ u8* p=reply_head(11,seq,off,0,8); wr32(p,have); wr32(p+4,2); send_frame(28+8); return; } + } +#endif + prog_sector_fu(base, SECBUF); /* erase + program (our own code) */ +#if ANZEIGE && HALTBILD + /* Bar based on counted sectors (keeps the display moving forward, since the + write order is not sequential). Redraw every 16 sectors. */ + { u32 n=++(*g_wrcnt); if((n & 0x0Fu)==0) draw_live(st_schreiben, n, FLASH_SIZE/0x1000u); } +#endif + u32 c=crc32_flash(base, 0x1000u); /* CRC read back (XIP), checked by the tool */ + /* Byte compare on the device: 0 = sector matches, otherwise error status 1 */ + u32 bad=0; flash_read(base, DMABUF, 0x1000u); + for(u32 i=0;i<0x1000u;i++){ if(dma[i]!=sec[i]){ bad=1; break; } } + u8* p=reply_head(11,seq,off,0,8); wr32(p,c); wr32(p+4,bad); + send_frame(28+8); return; + } + if(type==12){ /* WRITE_FINISH */ +#if ANZEIGE && HALTBILD + draw_live(st_fertig, 1, 1); +#endif + u8* p=reply_head(12,seq,off,0,0); send_frame(28+0); return; + } + if(type==14){ /* CLOCK_READ (1.3.0): the Paradise's seconds counter and RTC control -> 8 bytes */ + u8* p=reply_head(14,seq,off,0,8); wr32(p, REG(0x45000304u)); wr32(p+4, REG(0x45000200u)); + send_frame(28+8); return; + } + if(type==15){ /* CLOCK_SET (1.3.0): seconds counter := payload (only with the RTC running) -> 4 bytes back */ + u32 ok=0; + if(plen>=4 && (REG(0x45000200u) & 0x80u)){ REG(0x45000304u)=rd32(pl); ok=1; } + u8* p=reply_head(15,seq,off,ok?0:1,4); wr32(p, REG(0x45000304u)); + send_frame(28+4); return; + } + if(type==3){ /* CANCEL */ + u8* p=reply_head(3,seq,off,0,0); send_frame(28+0); return; + } +} + +static void pau1_loop(void){ + u32 w=0; + for(;;){ + int b=getb(); + if(b==0){ if(w>0){ u32 dl=cobs_decode(rxac,w,frm); handle(frm,dl); } w=0; } + else { if(w<8000u) rxac[w++]=(u8)b; else w=0; } /* RXACC 8 KB */ + } +} + +/* ===== full startup sequence, following the firmware (SystemInit) ===== */ +/* Quiet the watchdog AND set up the key-protected system/power block (0x40008000) + * like the original flash utility. 0x40008008=0x5AFA00FF enables the + * peripheral/display power domains (without it the display has no power and + * the screen stays dark). We leave the watchdog enable bit (0x40008000 bit0) + * at 0 so the long dump is not interrupted by a watchdog reset. */ +static void wdt_off(void){ + /* Set up the system/power block EXACTLY like the original flash utility. The + only place where we deliberately differed before (bit0 of 0x40008000) might + be the master enable for the display domain. The FU runs with bit0=1 without + a reset, so we copy it 1:1 and feed the watchdog in the loop. */ + REG(0x4000900Cu)=0x5AFA55AAu; REG(0x40009000u)=0x5AFA0000u; /* WDT1 */ + REG(0x40008000u)=0x5AFA0000u; /* unlock */ + REG(0x40008004u)=0x5AFA0002u; + REG(0x40008008u)=0x5AFA00FFu; /* power/clock domains on (incl. display) */ + REG(0x4000800Cu)=0x5AFA55AAu; /* feed the watchdog */ + /* Do NOT set bit0 (watchdog enable): otherwise it reset the Tama during + display init (back to the planet). */ +} +/* Clear the mailbox RAM (like 0x8b9c). */ +static void mailbox_clear(void){ + REG(0x20000000u)=0; REG(0x20000004u)=0; REG(0x20000008u)=0; REG(0x2000000Cu)=0; +} +/* Enable the peripheral clock (like 0x8bc0: 0x45000020 = 0x40). */ +static void periph_enable(void){ REG(CLK+0x20)=0x40u; } +/* Pin mux (like 0x899c, tables from the firmware). Without this the UART + contacts are not connected. Writes (mode<<4) to 0xE000E400 + pinId. */ +static void pin_set(u8 id, u8 mode){ *(volatile u8*)(0xE000E400u + id) = (u8)(mode<<4); } +static void pin_mux(void){ + static const u8 m12[]={6,7,8,9,0xf,0x10,0x11,0x12,0x13,0x14,0x19,0x1f,0x20,0x22, + 0x24,0x25,0x2e,0x2f,0x35,0x36,0x1a,0x1b,0x1c,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x3a,0x3f}; + static const u8 m8[]={0,1,2,3}; + static const u8 m4[]={0x15,0x17}; + for(unsigned i=0;i the Tama stopped answering). */ +#if ANZEIGE +/* Take the panel off the bus completely while dumping: display off, sleep, panel + * SPI controller off (frees SCLK/MOSI), CS high, reset held, backlight off. The + * flash shares the SPI bus with the panel, so reading and drawing cannot run at + * the same time. The screen goes dark during the dump, that is intended. */ +#if !HALTBILD +static void panel_down(void){ + lcd_cmd(0x28,0,0); /* DISPON off */ + lcd_cmd(0x10,0,0); MS(20); /* SLPIN */ + SPI_CTRL &= ~0xC0u; /* FIFOs */ + SPI_CTRL &= ~1u; /* panel SPI off, SCLK/MOSI free */ + BB(GPIO1+0x00,5)=1; /* panel CS off (P1.5 high) */ + LCD_RST(0); /* hold panel in reset */ + REG(CT2+0x00)=0; /* backlight PWM off */ + MS(5); +} +#endif +static u8* const g_armed=(u8*)0x1801A800u; /* flag in fixed SRAM, no .bss */ +/* On the first dump command, restore ONCE the complete, known good environment + * of the dumper without display: panel off the bus, then the full boot setup + * incl. clock_init. Then set up the UART again, otherwise the baud rate is wrong + * after clock_init and the Tama does not answer (that was the bug in 1.3.10). + * This way the flash reads again like in the version without display. */ +static void arm_for_dump(void){ + if(*g_armed) return; + *g_armed=1; +#if HALTBILD + /* Keep the panel on. Only confirm the flash controller/XIP once more, in case + the display setup changed something. Deliberately NO clock_init, pin_mux or + uart_init: that would disturb the baud rate and the backlight. */ + flashctl_init(); +#else + panel_down(); + clock_init(); + periph_enable(); + flashctl_init(); + pin_mux(); + uart_init(); +#endif +} +#endif + +void Reset_Handler(void){ + wdt_off(); + mailbox_clear(); + clock_init(); + periph_enable(); + flashctl_init(); + pin_mux(); + uart_init(); +#if ANZEIGE + display_power(); + display_init(); + draw(st_bereit, 0, 1); + backlight_on(); + *g_armed=0; /* dump switch not done yet; screen stays on while idle */ +#endif + pau1_loop(); + for(;;){} +} + +__attribute__((section(".vectors"), used)) +const void* const g_vectors[] = { (void*)0x1801F000u, (void*)Reset_Handler }; diff --git a/flash/src/io.h b/flash/src/io.h new file mode 100644 index 0000000..a3d0e81 --- /dev/null +++ b/flash/src/io.h @@ -0,0 +1,9 @@ +#ifndef IO_H +#define IO_H +typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; +#define REG(a) (*(volatile u32*)(a)) +#define UART 0x4000B000u +#define FCTL 0x40022000u +#define CLK 0x45000000u +static inline void dsb(void){ __asm__ volatile("dsb":::"memory"); } +#endif diff --git a/flash/src/link.ld b/flash/src/link.ld new file mode 100644 index 0000000..51152f7 --- /dev/null +++ b/flash/src/link.ld @@ -0,0 +1,10 @@ +ENTRY(Reset_Handler) +SECTIONS { + .text 0x0 : { + KEEP(*(.vectors)) + *(.text*) + *(.rodata*) + . = ALIGN(4); + } + /DISCARD/ : { *(.data*) *(.bss*) *(COMMON) *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/gb/README.md b/gb/README.md new file mode 100644 index 0000000..6f90634 --- /dev/null +++ b/gb/README.md @@ -0,0 +1,57 @@ +# GBEmu + +The Game Boy (DMG, black and white) on the Tamagotchi Paradise, as a further program of the Paramix menu. +No ROM here: bring your own game (.gb). Game Boy Color games are refused by the Studio. + +- `src/core/peanut_gb.h`: Peanut-GB by Mahyar Koshkouei (MIT License, notice in the file), commit d0bcca7. + Changes for the Paradise: the ROM is read straight from the cached flash window (`PGB_ROM`, two places marked + "Paramix"), `__gb_read` can take an attribute (`PGB_READ_ATTR`, unused). +- `src/stub`: three small headers so Peanut-GB builds without a C library. +- `src/app/main.c`: the Paradise program (PRAM, about 34 KB). Settings block "PMXG" at 0x140: ROM, length, save + (4 KB settings of the device, then the cartridge RAM, up to 32 KB), flags (bit 0 English, bit 1 wheel the other + way round), name, keys (9 bytes, see below). +- Screen: 160 x 144 shrunk to 128 x 115, every 5 x 5 dots mixed into 4 x 4 (weights 4/1, 3/2, 2/3, 1/4 both ways), + so thin lines stay visible as a lighter shade; nothing is cut off. Black bars above and below. Every second frame + is drawn (the display takes about 30 pictures a second), only the rows that changed are sent. +- Keys: `keys[i]` are Game Boy buttons (1 A, 2 B, 4 SELECT, 8 START, 16 RIGHT, 32 LEFT, 64 UP, 128 DOWN) for the + Paradise input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. A pair that has a + meaning takes its two keys while both are held. One wheel step holds up or down for 150 ms (steps add up). The + wheel's encoder is read in the 1 ms tick, so no step is lost while a frame runs. + Default (test37): A left, B = B, C right, wheel press = A, wheel up/down, A+C START. B+C and A+B are free, so B with + a direction works (run). SELECT is a line in the settings (pressed for 200 ms when the menu closes). + Fixed: A+B+C together = settings (select, colour, sound, light, dim, screen off, restart game, language); wheel held + 2 s = save and back to the Paradise. +- Save: the cartridge RAM goes to the flash 3 s after the game wrote it (1 s without a key), when the screen goes + off and on leaving. With the screen off the game waits. +- Sound (switch GB_SOUND, test37): the Paradise has one square-wave buzzer. The core keeps the sound registers; a hook + (`PGB_APU_WRITE`, marked "Paramix" in the core) sees triggers. Once per Game Boy frame the program follows length, + volume envelope and the sweep of channel 1, and plays the louder of the two square channels (channel 1 first at the + same loudness, it carries most effects). The wave channel (mostly the bass) only when both are quiet, the noise + channel never. Setting "Sound" in the device's settings. TONE_SAFE (test38, hw.c): when the new period is below the + running counter, the counter starts again (before, the buzzer stayed silent until the 32-bit counter wrapped). + GB_TONE_RESTART (test39): every new pitch stops and starts the timer (on the device a pitch changed in the running + timer stayed silent); changes below about 1.5 % (vibrato) are left out. +- Speed (test38): PGB_FAST_LINE draws background and window a tile at a time (`pgb_spread`, `pgb_pal4`, marked + "Paramix" in the core), GB_FAST shrinks four dots at once (table `g_h5`), GB_SKIP_ADAPT leaves out up to three frames + in a row when the game falls behind (normally every second frame is drawn). Same picture dot for dot. + +- State (GB_STATE, 1.6.11 test2): on leaving (wheel held) the whole Game Boy goes to the flash behind the cartridge + RAM (`emu/src/emu/pstate.h`), read once at the next start and dropped right after. +- Link cable (GB_LINK, 1.6.11 test2, `src/app/gb_link.h`): the serial port between two Paradise plugged together at the + top (plink over the contacts, 460800 baud, frames 'G'). The clocking side sends its byte ('M') and keeps the transfer + open (PGB_SERIAL_WAIT, marked "Paramix" in the core) until the other side's game is ready to receive and answers with + its own byte ('R'); both clocking: 'B', both get 0xFF; no answer within 400 ms: 0xFF. Without a partner everything + is as before. Tested: `test/link2.c` (two cores on the PC, a Pokemon trade from the Cable Club to the end), and two + devgb.py joined by pipes (LINKW, LINKR) with `test/mklinkrom.py` (an own small program, 256 bytes both ways). + +Speed (Unicorn simulation, 96 MHz): Super Mario Land and Kirby's Dream Land 2 at full speed (59.7 frames a second); +Blargg's cpu_instrs (no HALT at all) at about 75 %. + +Build: `sh src/app/build.sh` (clang, lld) gives `gb.bin`. +Test: `python3 test/mkimg.py gb.bin game.gb img.bin` then `python3 test/devgb.py src/app/gb.elf img.bin ` +(KEYS="t:mask,...", WHEEL="t:steps", SHOTS="t,...", OUT=dir); `test/prof.py` counts instructions per function. + +Author: mameise + +No session (1.7.3 test7, switch SESS_FLAG): flags bit 12 set by the Studio ("Remember where you left off" off): leaving writes +no state, a start drops an old one; only the game's own save (cartridge RAM or EEPROM) is kept. diff --git a/gb/gb.bin b/gb/gb.bin new file mode 100644 index 0000000..1763dcd Binary files /dev/null and b/gb/gb.bin differ diff --git a/gb/gbc.bin b/gb/gbc.bin new file mode 100644 index 0000000..bb8ec71 Binary files /dev/null and b/gb/gbc.bin differ diff --git a/gb/src/app/build.sh b/gb/src/app/build.sh new file mode 100644 index 0000000..87bf431 --- /dev/null +++ b/gb/src/app/build.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Build GBEmu for the Paradise (clang/lld, Cortex-M3). Output: ../../gb.bin +set -e +cd "$(dirname "$0")" +E=../../../emu/src/emu +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -Wno-unused-variable -fno-builtin-memset -isystem ../stub -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DBL_SLEEP -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DGB_SOUND -DTONE_SAFE -DGB_FAST -DPGB_FAST_LINE -DGB_SKIP_ADAPT -DGB_TONE_RESTART -DGB_STATE -DGB_LINK -DPGB_SERIAL_WAIT -DGB_TRIM -DGPLAY -DSESS_FLAG $XCF" +O="" +for f in main.c $E/hw.c $E/flash.c $E/libc.c; do + n=$(basename $f .c); OPT=-Os; [ "$n" = main ] && OPT=-O2; clang $CF $OPT -c $f -o $n.o; O="$O $n.o"; done +ld.lld -T link.ld --no-rosegment $O -o gb.elf +llvm-objcopy -O binary -j .text -j .data -j .init gb.elf gb.bin +cp gb.bin ../../gb.bin; rm -f *.o gb.bin; [ -n "$KEEPELF" ] || rm -f gb.elf; ls -l ../../gb.bin diff --git a/gb/src/app/build_gbc.sh b/gb/src/app/build_gbc.sh new file mode 100644 index 0000000..de7e303 --- /dev/null +++ b/gb/src/app/build_gbc.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Build GBCEmu (Game Boy Color) for the Paradise. Output: ../../gbc.bin +set -e +cd "$(dirname "$0")" +E=../../../emu/src/emu +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -Wno-unused-variable -fno-builtin-memset -isystem ../stub -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DBL_SLEEP -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DGB_SOUND -DTONE_SAFE -DGB_SKIP_ADAPT -DGB_TONE_RESTART -DGB_STATE -DGB_LINK -DPGB_SERIAL_WAIT -DGB_TRIM -DGBC -DGB_PAGES -DGPLAY -DSESS_FLAG -DPGB_BATCH -DPGB_FAST_CGB $XCF" +O="" +for f in main.c $E/hw.c $E/flash.c $E/libc.c; do + n=$(basename $f .c); OPT=-Os; [ "$n" = main ] && OPT=-O2; clang $CF $OPT -c $f -o c_$n.o; O="$O c_$n.o"; done +ld.lld -T link.ld --no-rosegment $O -o gbc.elf +llvm-objcopy -O binary -j .text -j .data -j .init gbc.elf gbc.bin +cp gbc.bin ../../gbc.bin; rm -f c_*.o gbc.bin; [ -n "$KEEPELF" ] || rm -f gbc.elf; ls -l ../../gbc.bin diff --git a/gb/src/app/font.h b/gb/src/app/font.h new file mode 100644 index 0000000..b01afaa --- /dev/null +++ b/gb/src/app/font.h @@ -0,0 +1,99 @@ +/* generated by gen/font.py: custom 5x7 font */ +static const unsigned char g_font[96][7]={ + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x04,0x04,0x04,0x04,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x19,0x19,0x02,0x04,0x08,0x13,0x13}, + {0x0c,0x12,0x14,0x08,0x15,0x12,0x0d}, + {0x04,0x04,0x08,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x08,0x08,0x04,0x02}, + {0x08,0x04,0x02,0x02,0x02,0x04,0x08}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x04,0x04,0x1f,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x0c,0x04,0x08}, + {0x00,0x00,0x00,0x1f,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x0c,0x0c}, + {0x01,0x01,0x02,0x04,0x08,0x10,0x10}, + {0x0e,0x11,0x13,0x15,0x19,0x11,0x0e}, + {0x04,0x0c,0x04,0x04,0x04,0x04,0x0e}, + {0x0e,0x11,0x01,0x02,0x04,0x08,0x1f}, + {0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e}, + {0x02,0x06,0x0a,0x12,0x1f,0x02,0x02}, + {0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e}, + {0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e}, + {0x1f,0x01,0x02,0x04,0x08,0x08,0x08}, + {0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e}, + {0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e}, + {0x00,0x04,0x04,0x00,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x10,0x08,0x04,0x02}, + {0x00,0x00,0x1f,0x00,0x1f,0x00,0x00}, + {0x08,0x04,0x02,0x01,0x02,0x04,0x08}, + {0x0e,0x11,0x01,0x02,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x0e,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e}, + {0x0e,0x11,0x10,0x10,0x10,0x11,0x0e}, + {0x1e,0x11,0x11,0x11,0x11,0x11,0x1e}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x10,0x17,0x11,0x11,0x0f}, + {0x11,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x0e,0x04,0x04,0x04,0x04,0x04,0x0e}, + {0x07,0x02,0x02,0x02,0x02,0x12,0x0c}, + {0x11,0x12,0x14,0x18,0x14,0x12,0x11}, + {0x10,0x10,0x10,0x10,0x10,0x10,0x1f}, + {0x11,0x1b,0x15,0x15,0x11,0x11,0x11}, + {0x11,0x19,0x15,0x13,0x11,0x11,0x11}, + {0x0e,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x1e,0x11,0x11,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x11,0x11,0x15,0x12,0x0d}, + {0x1e,0x11,0x11,0x1e,0x14,0x12,0x11}, + {0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e}, + {0x1f,0x04,0x04,0x04,0x04,0x04,0x04}, + {0x11,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x11,0x11,0x11,0x11,0x0a,0x04}, + {0x11,0x11,0x11,0x15,0x15,0x15,0x0a}, + {0x11,0x11,0x0a,0x04,0x0a,0x11,0x11}, + {0x11,0x11,0x0a,0x04,0x04,0x04,0x04}, + {0x1f,0x01,0x02,0x04,0x08,0x10,0x1f}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x11,0x0a,0x04,0x0a,0x11}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x11,0x0e,0x11,0x1f,0x11,0x11,0x11}, + {0x11,0x0e,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x00,0x11,0x11,0x11,0x11,0x0e}, +}; diff --git a/gb/src/app/gb_link.h b/gb/src/app/gb_link.h new file mode 100644 index 0000000..692e07e --- /dev/null +++ b/gb/src/app/gb_link.h @@ -0,0 +1,83 @@ +/* GBEmu link (GB_LINK, 1.6.11 test2): the Game Boy's serial port between two Paradise, as with a link cable. + * The side that clocks (SC = 0x81) sends its byte ('M') and waits; the other side answers with its own byte ('R') as + * soon as its game is ready to receive (SC = 0x80); until then it keeps the byte. Both clocking at once: each answers + * 'B' (busy) and both get 0xFF, as with two clocks on a real cable. Without a partner (no hello for 2 s) everything + * is as before: a clocking side gets 0xFF, a receiving side waits. + * The transport and the clock come from the includer: + * GL_SEND(kind, byte) send one frame to the other side + * GL_POLL() take in what arrived (calls gl_got) + * GL_NOW() milliseconds + * GL_PARTNER() 1 when the other side is there + * Header only, one link. Author: mameise */ +#ifndef GB_LINK_H +#define GB_LINK_H + +#define GL_WAIT_MAX 400u /* ms the clocking side waits for an answer, then 0xFF */ +#define GL_PEND_MAX 600u /* ms a received byte waits for the game to get ready, then 'B' */ + +typedef struct GlState { + uint8_t waiting, got, reply; /* clocking side: waiting for the answer, it came, its byte */ + uint8_t pend, pend_byte; /* receiving side: a byte of the other side waits */ + uint32_t t0, pend_t; + uint32_t n_tx, n_rx; /* bytes (for the tests) */ +} GlState; +#ifndef GL_S /* the PC test runs two: it points GL_S at the one running */ +static GlState g_gl_one; +#define GL_S g_gl_one +#endif + +/* a frame from the other side */ +static void gl_got(uint8_t kind, uint8_t b) +{ + if (kind == 'M') { + if (GL_S.waiting) { GL_SEND('B', 0xFF); return; } /* both clocking */ + GL_S.pend = 1; GL_S.pend_byte = b; GL_S.pend_t = GL_NOW(); + } else if (kind == 'R' || kind == 'B') { + if (GL_S.waiting) { GL_S.got = 1; GL_S.reply = kind == 'R' ? b : 0xFF; } + } +} + +/* Peanut-GB: a transfer starts */ +static void gl_tx(struct gb_s *gb, const uint8_t tx) +{ + if (!GL_PARTNER()) return; + if (!(gb->hram_io[IO_SC] & 1u)) { /* receiving side gets ready */ + GL_S.waiting = 0; /* (a clocking try of this side is over) */ + GL_POLL(); + if (GL_S.pend) { /* the other side clocked already: done at once */ + GL_SEND('R', tx); GL_S.pend = 0; GL_S.n_rx++; + gb->hram_io[IO_SB] = GL_S.pend_byte; + gb->hram_io[IO_SC] &= 0x01; + gb->hram_io[IO_IF] |= SERIAL_INTR; + } + return; + } + if (GL_S.pend) { GL_SEND('B', 0xFF); GL_S.pend = 0; } /* the other one clocked too */ + GL_S.waiting = 1; GL_S.got = 0; GL_S.t0 = GL_NOW(); + GL_SEND('M', tx); GL_S.n_tx++; +} +/* Peanut-GB: the transfer's 8 bits are through (called again and again while it returns GB_SERIAL_RX_WAIT) */ +static enum gb_serial_rx_ret_e gl_rx(struct gb_s *gb, uint8_t *rx) +{ + GL_POLL(); + if (gb->hram_io[IO_SC] & 1u) { /* clocking side */ + if (!GL_S.waiting) return GB_SERIAL_RX_NO_CONNECTION; /* no partner: 0xFF */ + if (GL_S.got) { GL_S.waiting = 0; *rx = GL_S.reply; GL_S.n_rx++; return GB_SERIAL_RX_SUCCESS; } + if (GL_NOW() - GL_S.t0 > GL_WAIT_MAX) { GL_S.waiting = 0; *rx = 0xFF; return GB_SERIAL_RX_SUCCESS; } + return GB_SERIAL_RX_WAIT; + } + /* receiving side: done when the other side's byte is there */ + if (GL_S.pend) { + GL_SEND('R', gb->hram_io[IO_SB]); GL_S.pend = 0; + *rx = GL_S.pend_byte; GL_S.n_rx++; + return GB_SERIAL_RX_SUCCESS; + } + return GB_SERIAL_RX_NO_CONNECTION; /* keeps waiting, SB stays */ +} +/* from the main loop: a byte nobody took for long is refused (the other side goes on with 0xFF) */ +static void gl_tick(void) +{ + GL_POLL(); + if (GL_S.pend && GL_NOW() - GL_S.pend_t > GL_PEND_MAX) { GL_SEND('B', 0xFF); GL_S.pend = 0; } +} +#endif diff --git a/gb/src/app/link.ld b/gb/src/app/link.ld new file mode 100644 index 0000000..106ae96 --- /dev/null +++ b/gb/src/app/link.ld @@ -0,0 +1,23 @@ +ENTRY(Reset_Handler) +MEMORY { + PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000 + SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000 +} +SECTIONS { + .text : { + KEEP(*(.vectors)) + KEEP(*(.pmxcfg)) + *(.text*) + *(.rodata*) + . = ALIGN(4); + __pdata_start = .; + } > PRAM + .bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM + /* mutable data in SRAM (initial values in PRAM, copied at startup), as in TamaEmu */ + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + .init : { . = ALIGN(4); KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); __prog_end = .; } > PRAM + ASSERT(__prog_end <= 0x10000, "program too big for PRAM") + ASSERT(__bss_end <= 0x1801F000, "RAM full") + /DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/gb/src/app/main.c b/gb/src/app/main.c new file mode 100644 index 0000000..877b583 --- /dev/null +++ b/gb/src/app/main.c @@ -0,0 +1,737 @@ +/* GBEmu: the Game Boy (DMG) on the Tamagotchi Paradise. Core: Peanut-GB by Mahyar Koshkouei (MIT), see ../core. + * Started from the Paramix menu like the other further programs. Bring your own ROM (.gb). + * Screen: 160 x 144 shrunk to 128 x 115 (5 dots to 4, mixed, nothing cut off), black bars above and below. + * Keys: set in the Studio (tab Game Boy), stored in the settings block. A+B+C together: settings (also SELECT and + * sound); wheel held 2 s: save and back to the Paradise. Sound (GB_SOUND): the Paradise's buzzer plays one channel. + * Save: the cartridge RAM (battery save) goes to the flash a few seconds after the game wrote it, and on leaving. + * Author: mameise */ +#include "../../../emu/src/emu/hw.h" +#include "../../../emu/src/emu/exitkey.h" +#include "../../../emu/src/emu/flash.h" +#define PARA_ATTR +#include "../../../emu/src/emu/paraclock.h" +#ifdef PARA_BACK +#include "../../../emu/src/emu/paraback.h" +#ifdef GPLAY +#define GP_POINTS +#include "../../../emu/src/emu/gplay.h" +#endif +#endif +typedef int s32; + +/* ---- settings block at 0x140, filled in by the Studio ---- + * keys[i]: Game Boy buttons (Peanut-GB joypad bits: 1 A, 2 B, 4 SELECT, 8 START, 16 RIGHT, 32 LEFT, 64 UP, 128 DOWN) + * for the Paradise input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. + * flags: bit 0 English, bit 1 wheel the other way round. + * save_off: 4 KB settings of the device, then the cartridge RAM (up to 32 KB). */ +#define NIN 9 +typedef struct { u32 magic, version, rom_off, rom_len, save_off, flags; char name[16]; u8 keys[12]; } GbCfg; +#define GB_MAGIC 0x47584D50u /* "PMXG" */ +__attribute__((section(".pmxcfg"), used)) +volatile const GbCfg g_cfg = { GB_MAGIC, 1, 0, 0, 0, 0, {0}, { 0x20, 0x02, 0x10, 0x01, 0x40, 0x80, 0x08, 0x00, 0x00 } }; +#define SETTINGS (g_cfg.save_off) +#define CRAM_AT (g_cfg.save_off + 0x1000u) +#define CRAM_MAX 0x8000u +#define XIP_BASE_REG REG(0x4002F004u) +#define XIP_CTRL_REG REG(0x4002F000u) +#define ROMWIN ((const u8 *)0x10000000u) + +#define PGB_ROM ROMWIN +#define ENABLE_SOUND 0 +#define PEANUT_GB_HIGH_LCD_ACCURACY 0 +#ifdef GB_SOUND +static void apu_write(u32 addr, u8 val); +#define PGB_APU_WRITE(a, v) apu_write((u32)(a), (u8)(v)) +#endif +#ifdef GB_TRIM +/* 1.7.1: the offset of the switchable ROM bank is worked out when the game switches the bank (before: on every read). + * Banks behind the stored part of the game read the last stored one (the Studio keeps equal end banks once). */ +struct gb_s; +static u32 g_romoff, g_blast = 0xFFFFu; +#ifdef GB_PAGES +static u32 g_page; +#endif +static void bank_set(struct gb_s *gb); +#define PGB_ROMOFF g_romoff +#define PGB_BANKSET(gb) bank_set(gb) +#endif +#ifdef GBC +/* 1.7.2: Game Boy Color (the core's cgb branch, PEANUT_FULL_GBC_SUPPORT): colours, two VRAM banks, eight WRAM banks, + * double speed. A DMG game runs in this program as well (as on the real Game Boy Color). */ +#define PEANUT_FULL_GBC_SUPPORT 1 +static int g_pal_dirty = 1; +#define PGB_PALW(gb) (g_pal_dirty = 1) +#include "../core/peanut_gbc.h" +#else +#include "../core/peanut_gb.h" +#endif +#include "font.h" +#ifdef GB_TRIM +__attribute__((noinline)) static void bank_set(struct gb_s *gb) +{ + u32 b = (gb->mbc == 1 && gb->cart_mode_select) ? (gb->selected_rom_bank & 0x1Fu) : gb->selected_rom_bank; +#ifdef GB_PAGES + /* 1.7.2: games over 1 MB (the cached window shows 1 MB): stored as pages of 1 MB, each bank 0 and 63 switchable + * banks (flags bit 2); the window moves when the game switches to a bank of another page */ + if (g_cfg.flags & 4u) { + if (!b) b = 1u; + u32 pg = (b - 1u) / 63u; + if (pg != g_page) { g_page = pg; XIP_BASE_REG = 0x60000000u | (g_cfg.rom_off + (pg << 20)); XIP_CTRL_REG = 3u; __asm__ volatile("dsb\n isb" ::: "memory"); } + g_romoff = ((b - 1u) % 63u) * ROM_BANK_SIZE; + return; + } +#endif + if (b > g_blast) b = g_blast; + g_romoff = (b - 1u) * ROM_BANK_SIZE; +} +#define ROM_LEN_FULL ((g_cfg.flags >> 16) ? (g_cfg.flags >> 16) * ROM_BANK_SIZE : g_cfg.rom_len) +#else +#define ROM_LEN_FULL g_cfg.rom_len +#endif + +/* ---- time: SysTick 1 ms; the wheel's encoder is read here too, so no step is lost while a frame runs ---- */ +static volatile u32 g_ms; +static u32 g_tone_now; /* buzzer frequency now (GB_SOUND) */ +static volatile s32 g_enc_acc; static u32 g_enc_last; +static const signed char QD[16] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 }; +#define GPIO2 0x4001A000u +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +#define CORE_HZ 96000000u +__attribute__((used)) void systick_c(void) +{ + g_ms++; + u32 n = REG(GPIO2) & 3u; + if (n != g_enc_last) { g_enc_acc += QD[(g_enc_last << 2) | n]; g_enc_last = n; } +} +__attribute__((naked)) void SysTick_Handler(void) { __asm__ volatile("b systick_c\n"); } +void abort(void) { for (;;) hw_wdt_feed(); } + +/* ---- settings on the device ---- */ +typedef struct { u8 magic[4]; u8 pal, dim, lang, dimto, off, r0, skip, mute; } GbSet; /* mute: 0 = sound on */ +static GbSet g_set = { {'G','B','S','1'}, 0, 7, 0, 6, 3, 0x80, 0, 0 }; +/* light to dark: DMG green, pocket grey, light (yellow), blue */ +static const u16 PAL[4][4] = { + { 0x9DE1u, 0x8D61u, 0x3324u, 0x0981u }, + { 0xE71Cu, 0xAD55u, 0x5ACBu, 0x10A2u }, + { 0xFFF4u, 0xCE4Cu, 0x7B46u, 0x2100u }, + { 0xDF5Fu, 0x8D3Cu, 0x3A92u, 0x0846u } }; +static const char *const PAL_NM[2][4] = { { "GRUEN", "GRAU", "GELB", "BLAU" }, { "GREEN", "GREY", "YELLOW", "BLUE" } }; +#define T_N 7 +static const u32 T_MS[T_N] = { 10000u, 20000u, 30000u, 60000u, 120000u, 300000u, 600000u }; +static const char *const T_NM[2][T_N + 1] = { { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NIE" }, { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NEVER" } }; +#define LV_N 11 +#define DIM2_N 10 +static const u8 LV_PCT[LV_N] = { 100u, 5u, 10u, 20u, 30u, 40u, 50u, 60u, 70u, 80u, 90u }; +static const u8 DIM2_PCT[DIM2_N] = { 1u, 2u, 3u, 5u, 10u, 15u, 20u, 30u, 40u, 50u }; +static int en(void) { return g_set.lang ? g_set.lang == 2u : (int)(g_cfg.flags & 1u); } +static u16 BG, INK, OFF; +#ifdef GBC +static void gbc_colours(const u16 *p); +#endif +static u16 g_lut[76]; /* mixed brightness 0..75 (25 weights x shade 0..3) to colour */ +static int g_dimmed; +static u16 mix(u16 a, u16 b, int p, int q) /* a + (b - a) * p / q */ +{ + int r = (a >> 11) + (((b >> 11) - (a >> 11)) * p) / q, g = ((a >> 5) & 63) + ((((b >> 5) & 63) - ((a >> 5) & 63)) * p) / q; + int bl = (a & 31) + (((b & 31) - (a & 31)) * p) / q; + return (u16)((r << 11) | (g << 5) | bl); +} +static void colours(void) +{ + const u16 *p = PAL[g_set.pal & 3u]; + for (int v = 0; v < 76; v++) { int s = v / 25, f = v % 25; g_lut[v] = s >= 3 ? p[3] : mix(p[s], p[s + 1], f, 25); } + BG = p[0]; INK = p[3]; OFF = p[2]; +#ifdef GBC + gbc_colours(p); +#endif +#ifdef BL_PWM + { u32 l = LV_PCT[(g_set.r0 & 15u) % LV_N], d = DIM2_PCT[g_set.dimto % DIM2_N]; + hw_bl_set(g_dimmed ? (d < l ? d : l) : l); } +#endif +} +static u8 g_sec[0x1000] __attribute__((aligned(4))); +static void set_load(void) +{ + const volatile u8 *p = XIP_PTR(SETTINGS); GbSet t; u8 *d = (u8 *)&t; + for (u32 i = 0; i < sizeof t; i++) d[i] = p[i]; + if (t.magic[0] == 'G' && t.magic[1] == 'B' && t.magic[2] == 'S' && t.magic[3] == '1' && t.pal < 4u && t.dim <= T_N && t.off <= T_N && t.lang < 3u) g_set = t; + colours(); +} +static void set_store(void) +{ + for (u32 i = 0; i < sizeof g_sec; i++) g_sec[i] = 0xFF; + const u8 *s = (const u8 *)&g_set; for (u32 i = 0; i < sizeof g_set; i++) g_sec[i] = s[i]; + flash_update4k(SETTINGS, g_sec); +} + +/* ---- the Game Boy ---- */ +static struct gb_s g_gb; +static u8 g_cram[CRAM_MAX] __attribute__((aligned(4))); +static u32 g_cram_len; static int g_cram_dirty; +static u8 gb_rom_rd(struct gb_s *gb, const uint_fast32_t a) { (void)gb; return ROMWIN[a]; } +static u8 gb_cram_rd(struct gb_s *gb, const uint_fast32_t a) { (void)gb; return a < CRAM_MAX ? g_cram[a] : 0xFF; } +static void gb_cram_wr(struct gb_s *gb, const uint_fast32_t a, const u8 v) { (void)gb; if (a < CRAM_MAX && g_cram[a] != v) { g_cram[a] = v; g_cram_dirty = 1; } } +static volatile u32 g_err; +static void gb_err(struct gb_s *gb, const enum gb_error_e e, const uint16_t a) { (void)gb; g_err = 0x80000000u | (u32)e << 16 | a; } +static void cram_load(void) +{ + const volatile u8 *p = XIP_PTR(CRAM_AT); + for (u32 i = 0; i < g_cram_len; i++) g_cram[i] = p[i]; + /* a fresh save area (all 0xFF) is what a new cartridge has too */ +} +static void cram_store(void) +{ + for (u32 o = 0; o < g_cram_len; o += 0x1000u) { + u32 n = g_cram_len - o < 0x1000u ? g_cram_len - o : 0x1000u; + for (u32 i = 0; i < 0x1000u; i++) g_sec[i] = i < n ? g_cram[o + i] : 0xFF; + hw_tone(0); g_tone_now = 0; + flash_update4k(CRAM_AT + o, g_sec); + } + g_cram_dirty = 0; +} + +#ifdef GB_SOUND +/* ---- sound (GB_SOUND, test37): the Paradise has one square-wave buzzer, so of the Game Boy's four channels the + * loudest of the two square channels plays (the wave channel when they are quiet; the noise channel never). + * The registers are kept by the core (hram_io); triggers, length, volume envelope and the sweep of channel 1 are + * followed here once per Game Boy frame (16.7 ms). ---- */ +typedef struct { u8 on, vol, env_dir, env_per, env_t; u16 len_ms; u8 len_on; u16 freq; u8 sw_t; } ApuCh; +static ApuCh g_ch[3]; +static u8 *io(u32 a) { return &g_gb.hram_io[a - 0xFF00u]; } +static void apu_write(u32 addr, u8 val) +{ + int c = addr >= 0xFF10u && addr <= 0xFF14u ? 0 : addr >= 0xFF15u && addr <= 0xFF19u ? 1 : addr >= 0xFF1Au && addr <= 0xFF1Eu ? 2 : -1; + if (addr == 0xFF26u && !(val & 0x80u)) { g_ch[0].on = g_ch[1].on = g_ch[2].on = 0; return; } + if (c < 0) return; + u32 base = c == 0 ? 0xFF10u : c == 1 ? 0xFF15u : 0xFF1Au; + ApuCh *h = &g_ch[c]; + if (addr == base + 4u) { + h->len_on = (val & 0x40u) != 0; + if (val & 0x80u) { /* trigger */ + if (c < 2) { u8 e = *io(base + 2u); h->vol = e >> 4; h->env_dir = (e & 8u) != 0; h->env_per = e & 7u; h->env_t = 0; h->on = (e & 0xF8u) != 0; + h->len_ms = (u16)((64u - (*io(base + 1u) & 63u)) * 1000u / 256u); } + else { h->on = (*io(0xFF1Au) & 0x80u) != 0; h->len_ms = (u16)((256u - *io(0xFF1Bu)) * 1000u / 256u); } + h->freq = (u16)(*io(base + 3u) | (val & 7u) << 8); h->sw_t = 0; + } + } + if (c < 2 && addr == base + 2u && !(val & 0xF8u)) h->on = 0; /* DAC off */ + if (c == 2 && addr == 0xFF1Au && !(val & 0x80u)) h->on = 0; +} +/* one Game Boy frame (16.74 ms) on: length, envelope (steps of 1/64 s), sweep (steps of 1/128 s); then the buzzer */ +static void apu_frame(void) +{ + for (int c = 0; c < 3; c++) { + ApuCh *h = &g_ch[c]; if (!h->on) continue; + u32 base = c == 0 ? 0xFF10u : c == 1 ? 0xFF15u : 0xFF1Au; + if (!h->sw_t || c) h->freq = (u16)(*io(base + 3u) | (*io(base + 4u) & 7u) << 8); /* vibrato: the game changes the registers */ + if (h->len_on) { if (h->len_ms <= 17u) { h->on = 0; continue; } h->len_ms = (u16)(h->len_ms - 17u); } + if (c < 2 && h->env_per) { h->env_t++; if (h->env_t >= h->env_per) { h->env_t = 0; if (h->env_dir) { if (h->vol < 15u) h->vol++; } else if (h->vol) h->vol--; } } + if (c == 0) { /* sweep: two 128 Hz steps per frame */ + u8 sw = *io(0xFF10u); u32 per = (sw >> 4) & 7u, sh = sw & 7u; + if (per && sh) for (int k = 0; k < 2; k++) { if (++h->sw_t >= per) { h->sw_t = 1; u32 d = h->freq >> sh, f = (sw & 8u) ? h->freq - d : h->freq + d; if (f > 2047u) { h->on = 0; break; } h->freq = (u16)f; } } + } + } + u32 hz = 0; + if (!g_set.mute && (*io(0xFF26u) & 0x80u)) { + u8 pan = *io(0xFF25u); int best = -1; u32 bv = 0; + for (int c = 0; c < 3; c++) { + ApuCh *h = &g_ch[c]; if (!h->on || !(pan & (0x11u << c))) continue; + u32 v = c < 2 ? h->vol : ((*io(0xFF1Cu) >> 5) & 3u) == 1u ? 15u : ((*io(0xFF1Cu) >> 5) & 3u) == 2u ? 7u : ((*io(0xFF1Cu) >> 5) & 3u) == 3u ? 3u : 0u; + if (c == 2 && best >= 0) continue; /* the wave channel (mostly the bass) only when both square channels are quiet */ + if (v > bv) { bv = v; best = c; } + } + if (best >= 0) { u32 x = g_ch[best].freq & 2047u; hz = best < 2 ? 131072u / (2048u - x) : 65536u / (2048u - x); if (hz < 40u || hz > 10000u) hz = 0; } + } +#ifdef GB_TONE_RESTART + /* test39: on the device a new pitch written into the running timer left the buzzer silent (the first notes with + * silence between them played, later notes did not). Now every new pitch starts the timer anew; changes below + * about 1.5 % (vibrato) are left out so it does not restart every frame. */ + if (hz && g_tone_now) { u32 d = hz > g_tone_now ? hz - g_tone_now : g_tone_now - hz; if (d * 64u < g_tone_now) return; } + if (hz != g_tone_now) { if (hz && g_tone_now) hw_tone(0); g_tone_now = hz; hw_tone(hz); } +#else + if (hz != g_tone_now) { g_tone_now = hz; hw_tone(hz); } +#endif +} +static void apu_quiet(void) { if (g_tone_now) { g_tone_now = 0; hw_tone(0); } } +#else +static void apu_quiet(void) {} +#endif + +/* ---- screen: 5 x 5 Game Boy dots to 4 x 4 (weights 4/1, 3/2, 2/3, 1/4), 128 x 115 from y 6 ---- */ +#define OY 6 +#define OH 115 +static int g_frame_drawn, g_dirty_lo = OH, g_dirty_hi = -1; +#ifdef GBC +/* 1.7.2 GBC: colour dots (RGB 5:6:5 in the picture), mixed per channel with the same weights */ +static u16 g_fbc[OH][128] __attribute__((aligned(4))); +/* one colour packed in a word: red bits 0..9, green 10..20, blue 21..30 (room for the sums of 25 weights) */ +static u32 g_hc[128]; /* the current line, shrunk across (sums of 5 weights) */ +static u32 g_ac[2][128]; /* rows being summed (25 weights) */ +static u32 g_pk[64]; /* the palette packed */ +static u16 g_d25r[776], g_d25g[1576]; static u8 g_d25b[776]; /* sum of 25 weights to the 5:6:5 field */ +static void d25_init(void) { for (u32 i = 0; i < 776u; i++) { g_d25r[i] = (u16)((i / 25u) << 11); g_d25b[i] = (u8)(i / 25u); } for (u32 i = 0; i < 1576u; i++) g_d25g[i] = (u16)((i / 25u) << 5); } +static u16 g_dmgc[4]; /* a DMG game: its four shades in the chosen colours */ +static void crow_out(int r, const u32 *a) +{ + if (r >= OH) return; + u16 *f = g_fbc[r]; u32 d = 0; + for (int x = 0; x < 128; x++) { /* / 25 through tables */ + u32 c = a[x]; + u16 v = (u16)(g_d25r[c & 1023u] | g_d25g[(c >> 10) & 2047u] | g_d25b[c >> 21]); + d |= f[x] ^ v; f[x] = v; + } + if (d) { if (r < g_dirty_lo) g_dirty_lo = r; if (r > g_dirty_hi) g_dirty_hi = r; } +} +static void lcd_line(struct gb_s *gb, const uint8_t px[160], const uint_fast8_t line) +{ + static int cgb0 = -1; + if (g_pal_dirty || cgb0 != gb->cgb.cgbMode) { g_pal_dirty = 0; cgb0 = gb->cgb.cgbMode; + if (gb->cgb.cgbMode) for (int i = 0; i < 64; i++) { u32 v = gb->cgb.fixPalette[i]; g_pk[i] = ((v >> 10) & 31u) | ((v >> 5) & 31u) << 11 | (v & 31u) << 21; } + else for (int i = 0; i < 64; i++) { u32 v = g_dmgc[i & 3]; g_pk[i] = (v >> 11) | ((v >> 5) & 63u) << 10 | (v & 31u) << 21; } } + const uint8_t *s = px; u32 *h = g_hc; + for (int k = 0; k < 32; k++, s += 5, h += 4) { + u32 a = g_pk[s[0] & 63u], b = g_pk[s[1] & 63u], c = g_pk[s[2] & 63u], d = g_pk[s[3] & 63u], e = g_pk[s[4] & 63u]; + h[0] = 4u * a + b; h[1] = 3u * b + 2u * c; h[2] = 2u * c + 3u * d; h[3] = d + 4u * e; + } + int g = line / 5, l = line % 5, r = g * 4; + u32 *a0 = g_ac[0], *a1 = g_ac[1]; const u32 *hc = g_hc; + switch (l) { + case 0: for (int x = 0; x < 128; x++) a0[x] = hc[x] << 2; break; + case 1: for (int x = 0; x < 128; x++) { a0[x] += hc[x]; a1[x] = 3u * hc[x]; } crow_out(r, a0); break; + case 2: for (int x = 0; x < 128; x++) { a1[x] += 2u * hc[x]; a0[x] = 2u * hc[x]; } crow_out(r + 1, a1); break; + case 3: for (int x = 0; x < 128; x++) { a0[x] += 3u * hc[x]; a1[x] = hc[x]; } crow_out(r + 2, a0); break; + default: for (int x = 0; x < 128; x++) a1[x] += hc[x] << 2; crow_out(r + 3, a1); break; + } + if (line == 143) g_frame_drawn = 1; +} +static void gbc_colours(const u16 *p) +{ + for (int k = 0; k < 4; k++) g_dmgc[k] = p[k]; + g_pal_dirty = 1; + g_dirty_lo = 0; g_dirty_hi = OH - 1; +} +#else +static u8 g_fb[OH][128] __attribute__((aligned(4))); +#endif +#if defined(GB_FAST) && !defined(GBC) +/* test38: the same weights four dots at a time (each byte of a word is one dot, sums stay below 256) */ +static u32 g_hlw[32], g_accw[2][32]; +static u32 g_h5[1024]; /* five dots (2 bits each) to their four shrunk dots */ +static void h5_init(void) +{ + for (u32 i = 0; i < 1024u; i++) { + u32 a = i & 3u, b = (i >> 2) & 3u, c = (i >> 4) & 3u, d = (i >> 6) & 3u, e = i >> 8; + g_h5[i] = (4u * a + b) | (3u * b + 2u * c) << 8 | (2u * c + 3u * d) << 16 | (d + 4u * e) << 24; + } +} +static void row_out(int r, const u32 *a) +{ + if (r >= OH) return; + u32 *f = (u32 *)g_fb[r], d = 0; + for (int x = 0; x < 32; x++) { d |= f[x] ^ a[x]; f[x] = a[x]; } + if (d) { if (r < g_dirty_lo) g_dirty_lo = r; if (r > g_dirty_hi) g_dirty_hi = r; } +} +static void lcd_line(struct gb_s *gb, const uint8_t px[160], const uint_fast8_t line) +{ + (void)gb; + const uint8_t *s = px; + for (int k = 0; k < 32; k++, s += 5) + g_hlw[k] = g_h5[(s[0] & 3u) | (s[1] & 3u) << 2 | (s[2] & 3u) << 4 | (s[3] & 3u) << 6 | (s[4] & 3u) << 8]; + int g = line / 5, l = line % 5, r = g * 4; + u32 *a0 = g_accw[0], *a1 = g_accw[1]; const u32 *h = g_hlw; + switch (l) { + case 0: for (int x = 0; x < 32; x++) a0[x] = h[x] << 2; break; + case 1: for (int x = 0; x < 32; x++) { a0[x] += h[x]; a1[x] = 3u * h[x]; } row_out(r, a0); break; + case 2: for (int x = 0; x < 32; x++) { a1[x] += 2u * h[x]; a0[x] = 2u * h[x]; } row_out(r + 1, a1); break; + case 3: for (int x = 0; x < 32; x++) { a0[x] += 3u * h[x]; a1[x] = h[x]; } row_out(r + 2, a0); break; + default: for (int x = 0; x < 32; x++) a1[x] += h[x] << 2; row_out(r + 3, a1); break; + } + if (line == 143) g_frame_drawn = 1; +} +#elif !defined(GBC) +static u8 g_hl[128]; /* the current line, shrunk across (0..15) */ +static u8 g_acc[2][128]; /* rows being summed */ +static void lcd_line(struct gb_s *gb, const uint8_t px[160], const uint_fast8_t line) +{ + (void)gb; + const uint8_t *s = px; u8 *h = g_hl; + for (int k = 0; k < 32; k++, s += 5, h += 4) { + u32 a = s[0] & 3u, b = s[1] & 3u, c = s[2] & 3u, d = s[3] & 3u, e = s[4] & 3u; + h[0] = (u8)(4u * a + b); h[1] = (u8)(3u * b + 2u * c); h[2] = (u8)(2u * c + 3u * d); h[3] = (u8)(d + 4u * e); + } + int g = line / 5, l = line % 5, r = g * 4; /* out rows r..r+3 */ + u8 *a0 = g_acc[0], *a1 = g_acc[1]; + switch (l) { + case 0: for (int x = 0; x < 128; x++) a0[x] = (u8)(4u * g_hl[x]); break; + case 1: for (int x = 0; x < 128; x++) { a0[x] = (u8)(a0[x] + g_hl[x]); a1[x] = (u8)(3u * g_hl[x]); } if (r < OH) { for (int x = 0; x < 128; x++) if (g_fb[r][x] != a0[x]) { g_fb[r][x] = a0[x]; if (r < g_dirty_lo) g_dirty_lo = r; if (r > g_dirty_hi) g_dirty_hi = r; } } break; + case 2: for (int x = 0; x < 128; x++) { a1[x] = (u8)(a1[x] + 2u * g_hl[x]); a0[x] = (u8)(2u * g_hl[x]); } r += 1; if (r < OH) { for (int x = 0; x < 128; x++) if (g_fb[r][x] != a1[x]) { g_fb[r][x] = a1[x]; if (r < g_dirty_lo) g_dirty_lo = r; if (r > g_dirty_hi) g_dirty_hi = r; } } break; + case 3: for (int x = 0; x < 128; x++) { a0[x] = (u8)(a0[x] + 3u * g_hl[x]); a1[x] = g_hl[x]; } r += 2; if (r < OH) { for (int x = 0; x < 128; x++) if (g_fb[r][x] != a0[x]) { g_fb[r][x] = a0[x]; if (r < g_dirty_lo) g_dirty_lo = r; if (r > g_dirty_hi) g_dirty_hi = r; } } break; + default: for (int x = 0; x < 128; x++) a1[x] = (u8)(a1[x] + 4u * g_hl[x]); r += 3; if (r < OH) { for (int x = 0; x < 128; x++) if (g_fb[r][x] != a1[x]) { g_fb[r][x] = a1[x]; if (r < g_dirty_lo) g_dirty_lo = r; if (r > g_dirty_hi) g_dirty_hi = r; } } break; + } + if (line == 143) g_frame_drawn = 1; +} +#endif +static u16 g_row[128] __attribute__((aligned(4))); +static void push(int all) +{ + int lo = all ? 0 : g_dirty_lo, hi = all ? OH - 1 : g_dirty_hi; + if (all) { /* the bars */ + for (int x = 0; x < 128; x++) g_row[x] = 0; + hw_px_begin(0, 0, 128, OY); for (int y = 0; y < OY; y++) hw_px_row(g_row, 128); hw_px_end(); + hw_px_begin(0, OY + OH, 128, 128); for (int y = OY + OH; y < 128; y++) hw_px_row(g_row, 128); hw_px_end(); + } + if (lo > hi) return; + hw_px_begin(0, (u32)(OY + lo), 128, (u32)(OY + hi + 1)); +#ifdef GBC + for (int y = lo; y <= hi; y++) hw_px_row(g_fbc[y], 128); +#else + for (int y = lo; y <= hi; y++) { const u8 *f = g_fb[y]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; hw_px_row(g_row, 128); } +#endif + hw_px_end(); + g_dirty_lo = OH; g_dirty_hi = -1; +} + +/* ---- the settings menu (A+B+C): A next line, B change, C close ---- */ +static int g_menu, g_msel, g_mtop; +static void text(int x, int y, const char *s, u16 col, u16 *row, int ry) +{ + for (; *s; s++, x += 6) { + int c = (unsigned char)*s; if (c >= 97 && c <= 122) c -= 32; c = (c < 32 || c > 127) ? 0 : c - 32; + if (ry < y || ry >= y + 7) continue; + u8 bits = g_font[c][ry - y]; + for (int k = 0; k < 5; k++) if ((bits & (0x10 >> k)) && x + k >= 0 && x + k < 128) row[x + k] = col; + } +} +enum { M_SEL, M_PAL, +#ifdef GB_SOUND + M_SND, +#endif + M_LIGHT, M_DIM, M_DIMTO, M_OFF, M_RESET, M_LANG, M_N }; +static u32 g_select_until; /* menu line SELECT: pressed for 200 ms after the menu closes */ +static int g_items[M_N], g_nitems; +static void menu_items(void) +{ + g_nitems = 0; + for (int k = 0; k < M_N; k++) { if (k == M_DIMTO && g_set.dim >= T_N) continue; g_items[g_nitems++] = k; } + if (g_msel >= g_nitems) g_msel = g_nitems - 1; +} +static void pct(char *o, int v) { int n = 0; if (v >= 100) o[n++] = '1'; if (v >= 10) o[n++] = (char)('0' + (v / 10) % 10); o[n++] = (char)('0' + v % 10); o[n++] = '%'; o[n] = 0; } +static int g_reset_ask; +static void menu_line(int it, const char **a, char *b) +{ + int e = en(); const char *v = 0; b[0] = 0; + switch (it) { + case M_SEL: *a = e ? "PRESS SELECT" : "SELECT DRUECKEN"; v = "B"; break; + case M_PAL: *a = e ? "COLOUR" : "FARBE"; v = PAL_NM[e][g_set.pal & 3u]; break; +#ifdef GB_SOUND + case M_SND: *a = e ? "SOUND" : "TON"; v = g_set.mute ? (e ? "OFF" : "AUS") : (e ? "ON" : "AN"); break; +#endif + case M_LIGHT: *a = e ? "LIGHT" : "LICHT"; pct(b, LV_PCT[(g_set.r0 & 15u) % LV_N]); break; + case M_DIM: *a = e ? "DIM AFTER" : "DIMMEN NACH"; v = T_NM[e][g_set.dim <= T_N ? g_set.dim : T_N]; break; + case M_DIMTO: *a = e ? "DIM TO" : "DIMMEN AUF"; pct(b, DIM2_PCT[g_set.dimto % DIM2_N]); break; + case M_OFF: *a = e ? "SCREEN OFF" : "BILD AUS NACH"; v = T_NM[e][g_set.off <= T_N ? g_set.off : T_N]; break; + case M_RESET: *a = e ? "RESTART GAME" : "SPIEL NEU"; v = g_reset_ask ? (e ? "SURE? B" : "SICHER? B") : ""; break; + default: *a = e ? "LANGUAGE" : "SPRACHE"; v = e ? "ENGLISH" : "DEUTSCH"; break; + } + if (v) { int n = 0; while (v[n] && n < 11) { b[n] = v[n]; n++; } b[n] = 0; } +} +#define ROWS 9 +static void menu_draw(void) +{ + if (g_msel < g_mtop) g_mtop = g_msel; + if (g_msel >= g_mtop + ROWS) g_mtop = g_msel - ROWS + 1; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + for (int x = 0; x < 128; x++) g_row[x] = BG; + text(4, 3, en() ? "SETTINGS" : "EINSTELLUNGEN", INK, g_row, y); + if (y == 12) for (int x = 0; x < 128; x++) g_row[x] = OFF; + for (int k = 0; k < ROWS && g_mtop + k < g_nitems; k++) { + int i = g_mtop + k, ly = 16 + k * 11; const char *a; char b[12]; menu_line(g_items[i], &a, b); + if (i == g_msel && y >= ly - 2 && y < ly + 9) for (int x = 0; x < 128; x++) g_row[x] = INK; + u16 c = i == g_msel ? BG : INK; + text(4, ly, a, c, g_row, y); int w = 0; while (b[w]) w++; text(124 - w * 6, ly, b, c, g_row, y); + } + text(4, 118, en() ? "A NEXT B SET C OK" : "A ZEILE B SETZEN C OK", OFF, g_row, y); + hw_px_row(g_row, 128); + } + hw_px_end(); +} +static int g_set_dirty; +static void menu_close(void) { g_menu = 0; g_reset_ask = 0; if (g_set_dirty) { set_store(); g_set_dirty = 0; } push(1); } +static void menu_key(u32 k) +{ + if (k & BTN_A) { g_msel = (g_msel + 1) % g_nitems; g_reset_ask = 0; } + if (k & BTN_B) { + switch (g_items[g_msel]) { + case M_SEL: g_select_until = g_ms + 200u; menu_close(); return; + case M_PAL: g_set.pal = (u8)((g_set.pal + 1u) & 3u); break; +#ifdef GB_SOUND + case M_SND: g_set.mute ^= 1u; break; +#endif + case M_LIGHT: g_set.r0 = (u8)(0x80u | (((g_set.r0 & 15u) + 1u) % LV_N)); break; + case M_DIM: g_set.dim = (u8)((g_set.dim + 1u) % (T_N + 1u)); if (g_set.dim < T_N && g_set.off < T_N && g_set.off <= g_set.dim) g_set.off = (u8)(g_set.dim + 1u); break; + case M_DIMTO: g_set.dimto = (u8)((g_set.dimto + 1u) % DIM2_N); break; + case M_OFF: do g_set.off = (u8)((g_set.off + 1u) % (T_N + 1u)); while (g_set.off < T_N && g_set.dim < T_N && g_set.off <= g_set.dim); break; + case M_RESET: if (g_reset_ask) { g_reset_ask = 0; gb_reset(&g_gb); menu_close(); return; } g_reset_ask = 1; break; + default: g_set.lang = (u8)(en() ? 1u : 2u); break; + } + if (g_items[g_msel] != M_RESET && g_items[g_msel] != M_SEL) g_set_dirty = 1; + colours(); menu_items(); + } + if (k & BTN_C) { menu_close(); return; } + menu_draw(); +} +static void message(const char *a, const char *b) +{ + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { for (int x = 0; x < 128; x++) g_row[x] = BG; text(4, 50, a, INK, g_row, y); text(4, 62, b, INK, g_row, y); hw_px_row(g_row, 128); } + hw_px_end(); +} + +/* ---- keys: the Paradise inputs to the Game Boy's buttons (map from the Studio) ---- */ +static u32 g_wheel_until[2]; /* wheel up / down held until (ms) */ +static u32 gb_keys(u32 b, u32 now) +{ + u32 in = 0; + int ac = (b & (BTN_A | BTN_C)) == (BTN_A | BTN_C), bc = (b & (BTN_B | BTN_C)) == (BTN_B | BTN_C), ab = (b & (BTN_A | BTN_B)) == (BTN_A | BTN_B); + /* a pair held: its two keys count as the pair only (if the pair has a meaning) */ + u32 used = 0; + if (ac && g_cfg.keys[6]) { in |= 1u << 6; used |= BTN_A | BTN_C; } + if (bc && g_cfg.keys[7]) { in |= 1u << 7; used |= BTN_B | BTN_C; } + if (ab && g_cfg.keys[8]) { in |= 1u << 8; used |= BTN_A | BTN_B; } + u32 r = b & ~used; + if (r & BTN_A) in |= 1u; if (r & BTN_B) in |= 2u; if (r & BTN_C) in |= 4u; if (b & BTN_WHEEL) in |= 8u; + if ((s32)(g_wheel_until[0] - now) > 0) in |= 16u; + if ((s32)(g_wheel_until[1] - now) > 0) in |= 32u; + u32 gb = 0; + for (int i = 0; i < NIN; i++) if (in & (1u << i)) gb |= g_cfg.keys[i]; + if ((s32)(g_select_until - now) > 0) gb |= 4u; + return gb; +} + +#ifdef GB_LINK +/* ---- 1.6.11 test2: link cable between two Paradise (plink over the contacts), e.g. trading in Pokemon ---- */ +#include "../../../emu/src/emu/plink.h" +static void gl_send2(u8 k, u8 b) { u8 d[2] = { k, b }; plink_send('G', d, 2); } +static void gl_poll2(void); +#define GL_SEND(k, b) gl_send2((k), (b)) +#define GL_POLL() gl_poll2() +#define GL_NOW() g_ms +#define GL_PARTNER() (g_pl.last_rx && g_ms - g_pl.last_rx < 2500u) +#include "gb_link.h" +static void gl_got2(u8 ty, const u8 *d, int n) { if (ty == 'G' && n == 2) gl_got(d[0], d[1]); } +static void gl_poll2(void) { plink_poll(g_ms, 0, gl_got2); } +#endif + +#ifdef GB_STATE +/* ---- 1.6.11 test2: the whole Game Boy on leaving (wheel held), read once at the next start ---- */ +#include "../../../emu/src/emu/pstate.h" +#ifdef SESS_FLAG +#define NOSESS ((g_cfg.flags & 0x1000u) != 0u) /* 1.7.3 test7: the Studio's "remember on leaving" off: only the game's own save */ +#else +#define NOSESS 0 +#endif +#define STATE_AT (g_cfg.save_off + 0x9000u) +#ifdef GBC +#define STATE_MAX 0xF000u /* 1.7.2: save area 96 KB (settings, cartridge RAM, state) */ +#else +#define STATE_MAX 0x7000u +#endif +static int g_running; +static u32 st_tag(void) { return 0x47420001u ^ (u32)&g_gb ^ ((u32)sizeof(struct gb_s) << 8) ^ ROM_LEN_FULL ^ (u32)lcd_line; } /* GB_TRIM: the whole game's length, so a stored state stays valid */ +static int st_parts(StPart *pt) +{ + int n = 0; pt[n].p = &g_gb; pt[n++].n = sizeof g_gb; +#ifdef GB_SOUND + pt[n].p = g_ch; pt[n++].n = sizeof g_ch; +#endif + return n; +} +static void state_store(void) { StPart pt[2]; int n = st_parts(pt); if (g_running) st_store(STATE_AT, STATE_MAX, st_tag(), pt, n, g_sec); } +static int state_load(void) +{ + if (NOSESS) { st_drop(STATE_AT); return 0; } + StPart pt[2]; int n = st_parts(pt); + struct gb_s keep = g_gb; /* the pointers of this program stay */ + int ok = st_load(STATE_AT, STATE_MAX, st_tag(), pt, n); + if (ok) { + g_gb.gb_rom_read = keep.gb_rom_read; g_gb.gb_cart_ram_read = keep.gb_cart_ram_read; g_gb.gb_cart_ram_write = keep.gb_cart_ram_write; + g_gb.gb_error = keep.gb_error; g_gb.gb_serial_tx = keep.gb_serial_tx; g_gb.gb_serial_rx = keep.gb_serial_rx; + g_gb.gb_bootrom_read = keep.gb_bootrom_read; g_gb.display.lcd_draw_line = keep.display.lcd_draw_line; g_gb.direct.priv = keep.direct.priv; + } + PGB_BANKSET(&g_gb); + st_drop(STATE_AT); + return ok; +} +#endif + +/* ---- leaving ---- */ +static void leave(void) +{ + apu_quiet(); hw_tone(0); + if (g_set_dirty) set_store(); + REG(0x20000FF8u) = 0; + REG(0x20000FFCu) = 0x4C584D50u; /* "PMXL": back on purpose, the autostart stays off */ +#ifdef GB_STATE + if (g_running && !NOSESS) { message(en() ? "SAVING" : "SPEICHERN", ""); state_store(); } +#endif + if (g_cram_dirty) cram_store(); +#ifdef PARA_BACK +#ifdef GPLAY + para_points((uint8_t *)g_sec); /* 1.7.2 test14: play time to Tamapoints */ +#endif + para_back_fix(g_sec); +#endif + hw_bl_pwm_off(); + for (u32 t = 0; hw_buttons() && t < 20000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); + XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u; + hw_back_to_paradise(); +} + +__attribute__((used)) volatile u32 g_gbst[4]; /* frames run, frames drawn, frames dropped, last frame in ms (for the tests) */ +extern u32 __bss_start, __bss_end; +void Reset_Handler(void) +{ + __asm__ volatile("cpsid i"); + u32 cnt = REG(0x45000304u), para = para_clock(cnt, 0, 0x1F000u, 0, 0); + if (!para) para = para_mailbox(cnt); +#ifdef PARA_FLASH + if (!para) para = para_flash(cnt); /* 1.6.9 test37 */ +#endif +#ifdef PARA_BACK + para_leave_mark(cnt, para); +#endif + __asm__ volatile("" ::: "memory"); + for (u32 *p = &__bss_start; p < &__bss_end; p++) *p = 0; + { extern u32 __data_start, __data_end, __data_load; + const u32 *src = &__data_load; for (u32 *p = &__data_start; p < &__data_end; p++) *p = *src++; } + (void)para; + hw_init(); + hw_tone(0); + XIP_BASE_REG = 0x60000000u | g_cfg.rom_off; /* the ROM in the cached window from 0x10000000 */ + XIP_CTRL_REG = 3u; + REG(GPIO2 + 0x04) &= ~3u; g_enc_last = REG(GPIO2) & 3u; + set_load(); +#ifdef GB_TRIM + if ((g_cfg.flags >> 16) && g_cfg.rom_len >= ROM_BANK_SIZE) g_blast = g_cfg.rom_len / ROM_BANK_SIZE - 1u; +#endif + enum gb_init_error_e ie = gb_init(&g_gb, gb_rom_rd, gb_cram_rd, gb_cram_wr, gb_err, 0); + if (ie != GB_INIT_NO_ERROR) { + message(en() ? "ROM NOT USABLE" : "ROM GEHT NICHT", ie == GB_INIT_CARTRIDGE_UNSUPPORTED ? (en() ? "CARTRIDGE TYPE" : "MODUL-TYP") : (en() ? "CHECKSUM" : "PRUEFSUMME")); + for (u32 t = 0; t < 30000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); + leave(); + } +#ifdef GBC + { size_t n = gb_get_save_size(&g_gb); +#else + { size_t n = 0; if (gb_get_save_size_s(&g_gb, &n) != 0) n = 0; +#endif + g_cram_len = n > CRAM_MAX ? CRAM_MAX : (u32)n; } + cram_load(); +#ifdef GB_FAST + h5_init(); +#endif +#ifdef GBC + d25_init(); +#endif + gb_init_lcd(&g_gb, lcd_line); +#ifdef GB_LINK + plink_init(); gb_init_serial(&g_gb, gl_tx, gl_rx); +#endif +#ifdef GB_STATE + state_load(); g_running = 1; +#endif + push(1); + SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; SYST_CSR = 7; + __asm__ volatile("cpsie i"); + + u32 last_in = g_ms, wheel_ms = 0, cram_ms = 0, next_ms = g_ms, last_push = g_ms, mk0 = 0; + u32 frac = 0; +#ifdef GB_SKIP_ADAPT + int skip_run = 0; +#endif + int bl = 1, lock = 1, menu_lock = 0; + for (;;) { + hw_wdt_feed(); + u32 now = g_ms; + u32 b = hw_buttons(); + if (lock) { if (b) b = 0; else lock = 0; } + /* wheel steps: one step = 4 phases; each step holds up or down for 150 ms */ + { s32 a = g_enc_acc; + if (a >= 4 || a <= -4) { + __asm__ volatile("cpsid i"); g_enc_acc -= a >= 4 ? 4 : -4; __asm__ volatile("cpsie i"); + int up = (a > 0) ^ ((g_cfg.flags & 2u) != 0); + u32 *u = &g_wheel_until[up ? 0 : 1]; *u = ((s32)(*u - now) > 0 ? *u : now) + 150u; + last_in = now; + if (g_menu) { g_msel = up ? (g_msel + g_nitems - 1) % g_nitems : (g_msel + 1) % g_nitems; menu_draw(); } + } } + if (b) { + last_in = now; + if (!bl || g_dimmed) { /* the key only wakes */ + bl = 1; hw_backlight(1); if (g_dimmed) { g_dimmed = 0; colours(); } + if (g_menu) menu_draw(); else push(1); + while (hw_buttons()) hw_wdt_feed(); + continue; + } + } + /* wheel held 2 s: save and back */ + if (b & BTN_WHEEL) { if (!wheel_ms) wheel_ms = now ? now : 1; else if (EXIT_NOW(now - wheel_ms, 2000u)) leave(); } else wheel_ms = 0; + /* A+B+C: settings */ + if ((b & (BTN_A | BTN_B | BTN_C)) == (BTN_A | BTN_B | BTN_C) && !g_menu && !menu_lock) { + apu_quiet(); g_menu = 1; menu_lock = 1; g_msel = 1; g_mtop = 0; menu_items(); menu_draw(); mk0 = BTN_A | BTN_B | BTN_C; g_gb.direct.joypad = 0xFF; + } + if (!(b & (BTN_A | BTN_B | BTN_C))) menu_lock = 0; + if (g_menu) { + u32 k = b & (BTN_A | BTN_B | BTN_C), nk = k & ~mk0; mk0 = k; if (nk) menu_key(nk); + next_ms = now; + __asm__ volatile("wfi"); + continue; + } + if (!bl) { apu_quiet(); next_ms = now; __asm__ volatile("wfi"); continue; } /* screen off: the game waits (battery) */ + g_gb.direct.joypad = (u8)~gb_keys(b, now); + /* one Game Boy frame every 16.74 ms (70224 cycles at 4.194304 MHz); drawn only when there is time */ + if ((s32)(now - next_ms) >= 0) { + if ((s32)(now - next_ms) > 100) { g_gbst[2] += (now - next_ms) / 17u; next_ms = now; } /* too far behind: drop the time */ + int late = (s32)(now - next_ms) > 8; + (void)late; g_gb.direct.frame_skip = 1; /* every second frame is drawn: the display takes 30 pictures a second anyway */ + g_frame_drawn = 0; + u32 t0 = g_ms; + gb_run_frame(&g_gb); + g_gbst[0]++; g_gbst[3] = g_ms - t0; +#ifdef GB_SOUND + apu_frame(); +#endif + frac += 740u; next_ms += 16u + frac / 1000u; frac %= 1000u; /* 16.74 ms */ +#ifdef GB_SKIP_ADAPT + /* test38: normally every second frame is drawn; when the game falls behind (many sprites), up to three in a row + * are left out, so the game keeps its speed and only the picture gets fewer updates */ + { int behind = (s32)(g_ms - next_ms) > 0, draw = skip_run >= 3 || (skip_run >= 1 && !behind); + skip_run = draw ? 0 : skip_run + 1; g_gb.display.frame_skip_count = draw; } +#endif + if (g_frame_drawn) g_gbst[1]++; + if (g_err) { message(en() ? "GAME BOY ERROR" : "GAME BOY FEHLER", ""); g_err = 0; } + if (bl && g_frame_drawn && now - last_push >= 30u) { last_push = now; push(0); } + } +#ifdef GB_LINK + gl_tick(); +#endif + if (g_cram_dirty && !cram_ms) cram_ms = now ? now : 1; + if (cram_ms && now - cram_ms > 3000u && now - last_in > 1000u) { cram_ms = 0; cram_store(); } + if (bl && !g_dimmed && g_set.dim < T_N && now - last_in > T_MS[g_set.dim]) { g_dimmed = 1; colours(); push(1); } + if (bl && g_set.off < T_N && now - last_in > T_MS[g_set.off]) { bl = 0; hw_backlight(0); if (g_cram_dirty) { cram_ms = 0; cram_store(); } } + if ((s32)(next_ms - g_ms) > 0) __asm__ volatile("wfi"); + } +} + +__attribute__((naked)) static void Default_Handler(void) { __asm__ volatile("1: b 1b\n"); } +__attribute__((naked)) static void Irq_Off(void) { __asm__ volatile("cpsid i\n bx lr\n"); } +__attribute__((section(".vectors"), used)) +const void *const g_vectors[16 + 64] = { (void *)0x18020000u, (void *)Reset_Handler, + [2 ... 10] = (void *)Default_Handler, [11] = (void *)Irq_Off, [12 ... 13] = (void *)Default_Handler, [14] = (void *)Irq_Off, + [15] = (void *)SysTick_Handler, [16 ... 79] = (void *)Irq_Off +#ifdef GB_LINK + , [16 + 37] = (void *)plink_irq +#endif +}; diff --git a/gb/src/core/peanut_gb.h b/gb/src/core/peanut_gb.h new file mode 100644 index 0000000..1b04dff --- /dev/null +++ b/gb/src/core/peanut_gb.h @@ -0,0 +1,4167 @@ +/** + * MIT License + * + * Copyright (c) 2018-2023 Mahyar Koshkouei + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Please note that at least two parts of source code within this project was + * taken from the SameBoy project at https://github.com/LIJI32/SameBoy/ which at + * the time of this writing is released under the MIT License. Occurrences of + * this code is marked as being taken from SameBoy with a comment. + * SameBoy, and code marked as being taken from SameBoy, + * is Copyright (c) 2015-2019 Lior Halphon. + */ + +#ifndef PEANUT_GB_H +#define PEANUT_GB_H + +#if defined(__has_include) +# if __has_include("version.all") +# include "version.all" /* Version information */ +# endif +#else +/* Stub __has_include for later. */ +# define __has_include(x) 0 +#endif + +#include /* Required for abort */ +#include /* Required for bool types */ +#include /* Required for int types */ +#include /* Required for memset */ +#include /* Required for tm struct */ + +/** +* If PEANUT_GB_IS_LITTLE_ENDIAN is positive, then Peanut-GB will be configured +* for a little endian platform. If 0, then big endian. +*/ +#if !defined(PEANUT_GB_IS_LITTLE_ENDIAN) +/* If endian is not defined, then attempt to detect it. */ +# if defined(__BYTE_ORDER__) +# if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ +/* Building for a big endian platform. */ +# define PEANUT_GB_IS_LITTLE_ENDIAN 0 +# else +# define PEANUT_GB_IS_LITTLE_ENDIAN 1 +# endif /* __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ */ +# elif defined(_WIN32) +/* We assume that Windows is always little endian by default. */ +# define PEANUT_GB_IS_LITTLE_ENDIAN 1 +# elif !defined(PEANUT_GB_IS_LITTLE_ENDIAN) +# error "Could not detect target platform endian. Please define PEANUT_GB_IS_LITTLE_ENDIAN" +# endif +#endif /* !defined(PEANUT_GB_IS_LITTLE_ENDIAN) */ + +#if PEANUT_GB_IS_LITTLE_ENDIAN == 0 +# error "Peanut-GB only supports little endian targets" +/* This is because the logic has been written with assumption of little + * endian byte order. */ +#endif + +/** Definitions for compile-time setting of features. **/ +/** + * Sound support must be provided by an external library. When audio_read() and + * audio_write() functions are provided, define ENABLE_SOUND to a non-zero value + * before including peanut_gb.h in order for these functions to be used. + */ +#ifndef ENABLE_SOUND +# define ENABLE_SOUND 0 +#endif + +/* Enable LCD drawing. On by default. May be turned off for testing purposes. */ +#ifndef ENABLE_LCD +# define ENABLE_LCD 1 +#endif + +/* Enable 16 bit colour palette. If disabled, only four colour shades are set in + * pixel data. */ +#ifndef PEANUT_GB_12_COLOUR +# define PEANUT_GB_12_COLOUR 1 +#endif + +/* Adds more code to improve LCD rendering accuracy. */ +#ifndef PEANUT_GB_HIGH_LCD_ACCURACY +# define PEANUT_GB_HIGH_LCD_ACCURACY 1 +#endif + +/* Use intrinsic functions. This may produce smaller and faster code. */ +#ifndef PEANUT_GB_USE_INTRINSICS +# define PEANUT_GB_USE_INTRINSICS 1 +#endif + +/* Only include function prototypes. At least one file must *not* have this + * defined. */ +// #define PEANUT_GB_HEADER_ONLY + +/** Internal source code. **/ +/* Interrupt masks */ +#define VBLANK_INTR 0x01 +#define LCDC_INTR 0x02 +#define TIMER_INTR 0x04 +#define SERIAL_INTR 0x08 +#define CONTROL_INTR 0x10 +#define ANY_INTR 0x1F + +/* Memory section sizes for DMG */ +#define WRAM_SIZE 0x2000 +#define VRAM_SIZE 0x2000 +#define HRAM_IO_SIZE 0x0100 +#define OAM_SIZE 0x00A0 + +/* Memory addresses */ +#define ROM_0_ADDR 0x0000 +#define ROM_N_ADDR 0x4000 +#define VRAM_ADDR 0x8000 +#define CART_RAM_ADDR 0xA000 +#define WRAM_0_ADDR 0xC000 +#define WRAM_1_ADDR 0xD000 +#define ECHO_ADDR 0xE000 +#define OAM_ADDR 0xFE00 +#define UNUSED_ADDR 0xFEA0 +#define IO_ADDR 0xFF00 +#define HRAM_ADDR 0xFF80 +#define INTR_EN_ADDR 0xFFFF + +/* Cart section sizes */ +#define ROM_BANK_SIZE 0x4000 +#ifndef PGB_BANKSET /* Paramix: called when the switchable ROM bank changes */ +#define PGB_BANKSET(gb) ((void)0) +#endif +#define WRAM_BANK_SIZE 0x1000 +#define CRAM_BANK_SIZE 0x2000 +#define VRAM_BANK_SIZE 0x2000 + +/* DIV Register is incremented at rate of 16384Hz. + * 4194304 / 16384 = 256 clock cycles for one increment. */ +#define DIV_CYCLES 256 + +/* Serial clock locked to 8192Hz on DMG. + * 4194304 / (8192 / 8) = 4096 clock cycles for sending 1 byte. */ +#define SERIAL_CYCLES 4096 + +/* Calculating VSYNC. */ +#define DMG_CLOCK_FREQ 4194304.0 +#define SCREEN_REFRESH_CYCLES 70224.0 +#define VERTICAL_SYNC (DMG_CLOCK_FREQ/SCREEN_REFRESH_CYCLES) + +/* Real Time Clock is locked to 1Hz. */ +#define RTC_CYCLES ((uint_fast32_t)DMG_CLOCK_FREQ) + +/* SERIAL SC register masks. */ +#define SERIAL_SC_TX_START 0x80 +#define SERIAL_SC_CLOCK_SRC 0x01 + +/* STAT register masks */ +#define STAT_LYC_INTR 0x40 +#define STAT_MODE_2_INTR 0x20 +#define STAT_MODE_1_INTR 0x10 +#define STAT_MODE_0_INTR 0x08 +#define STAT_LYC_COINC 0x04 +#define STAT_MODE 0x03 +#define STAT_USER_BITS 0xF8 + +/* LCDC control masks */ +#define LCDC_ENABLE 0x80 +#define LCDC_WINDOW_MAP 0x40 +#define LCDC_WINDOW_ENABLE 0x20 +#define LCDC_TILE_SELECT 0x10 +#define LCDC_BG_MAP 0x08 +#define LCDC_OBJ_SIZE 0x04 +#define LCDC_OBJ_ENABLE 0x02 +#define LCDC_BG_ENABLE 0x01 + +/** LCD characteristics **/ +/* There are 154 scanlines. LY < 154. */ +#define LCD_VERT_LINES 154 +#define LCD_WIDTH 160 +#define LCD_HEIGHT 144 +/* PPU cycles through modes every 456 cycles. */ +#define LCD_LINE_CYCLES 456 +#define LCD_MODE0_HBLANK_MAX_DRUATION 204 +#define LCD_MODE0_HBLANK_MIN_DRUATION 87 +#define LCD_MODE2_OAM_SCAN_DURATION 80 +#define LCD_MODE3_LCD_DRAW_MIN_DURATION 172 +#define LCD_MODE3_LCD_DRAW_MAX_DURATION 289 +#define LCD_MODE1_VBLANK_DURATION (LCD_LINE_CYCLES * (LCD_VERT_LINES - LCD_HEIGHT)) +#define LCD_FRAME_CYCLES (LCD_LINE_CYCLES * LCD_VERT_LINES) +/* The following assumes that Hblank starts on cycle 0. */ +/* Mode 2 (OAM Scan) starts on cycle 204 (although this is dependent on the + * duration of Mode 3 (LCD Draw). */ +#define LCD_MODE_2_CYCLES LCD_MODE0_HBLANK_MAX_DRUATION +/* Mode 3 starts on cycle 284. */ +#define LCD_MODE_3_CYCLES (LCD_MODE_2_CYCLES + LCD_MODE2_OAM_SCAN_DURATION) +/* Mode 0 starts on cycle 376. */ +#define LCD_MODE_0_CYCLES (LCD_MODE_3_CYCLES + LCD_MODE3_LCD_DRAW_MIN_DURATION) + +#define LCD_MODE2_OAM_SCAN_START 0 +#define LCD_MODE2_OAM_SCAN_END (LCD_MODE2_OAM_SCAN_DURATION) +#define LCD_MODE3_LCD_DRAW_END (LCD_MODE2_OAM_SCAN_END + LCD_MODE3_LCD_DRAW_MIN_DURATION) +#define LCD_MODE0_HBLANK_END (LCD_MODE3_LCD_DRAW_END + LCD_MODE0_HBLANK_MAX_DRUATION) +#if LCD_MODE0_HBLANK_END != LCD_LINE_CYCLES +#error "LCD length not equal" +#endif + +/* VRAM Locations */ +#define VRAM_TILES_1 (0x8000 - VRAM_ADDR) +#define VRAM_TILES_2 (0x8800 - VRAM_ADDR) +#define VRAM_BMAP_1 (0x9800 - VRAM_ADDR) +#define VRAM_BMAP_2 (0x9C00 - VRAM_ADDR) +#define VRAM_TILES_3 (0x8000 - VRAM_ADDR + VRAM_BANK_SIZE) +#define VRAM_TILES_4 (0x8800 - VRAM_ADDR + VRAM_BANK_SIZE) + +/* Interrupt jump addresses */ +#define VBLANK_INTR_ADDR 0x0040 +#define LCDC_INTR_ADDR 0x0048 +#define TIMER_INTR_ADDR 0x0050 +#define SERIAL_INTR_ADDR 0x0058 +#define CONTROL_INTR_ADDR 0x0060 + +/* SPRITE controls */ +#define NUM_SPRITES 0x28 +#define MAX_SPRITES_LINE 0x0A +#define OBJ_PRIORITY 0x80 +#define OBJ_FLIP_Y 0x40 +#define OBJ_FLIP_X 0x20 +#define OBJ_PALETTE 0x10 + +/* Joypad buttons */ +#define JOYPAD_A 0x01 +#define JOYPAD_B 0x02 +#define JOYPAD_SELECT 0x04 +#define JOYPAD_START 0x08 +#define JOYPAD_RIGHT 0x10 +#define JOYPAD_LEFT 0x20 +#define JOYPAD_UP 0x40 +#define JOYPAD_DOWN 0x80 + +#define ROM_HEADER_CHECKSUM_LOC 0x014D + +/* Local macros. */ +#ifndef MIN +# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#define PEANUT_GB_ARRAYSIZE(array) (sizeof(array)/sizeof(array[0])) + +/** Allow setting deprecated functions and variables. */ +#if (defined(__GNUC__) && __GNUC__ >= 6) || (defined(__clang__) && __clang_major__ >= 4) +# define PGB_DEPRECATED(msg) __attribute__((deprecated(msg))) +#else +# define PGB_DEPRECATED(msg) +#endif + +#if !defined(__has_builtin) +/* Stub __has_builtin if it isn't available. */ +# define __has_builtin(x) 0 +#endif + +/* The PGB_UNREACHABLE() macro tells the compiler that the code path will never + * be reached, allowing for further optimisation. */ +#if !defined(PGB_UNREACHABLE) +# if __has_builtin(__builtin_unreachable) +# define PGB_UNREACHABLE() __builtin_unreachable() +# elif defined(_MSC_VER) && _MSC_VER >= 1200 +# /* __assume is not available before VC6. */ +# define PGB_UNREACHABLE() __assume(0) +# else +# define PGB_UNREACHABLE() abort() +# endif +#endif /* !defined(PGB_UNREACHABLE) */ + +#if !defined(PGB_UNLIKELY) +# if __has_builtin(__builtin_expect) +# define PGB_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +# else +# define PGB_UNLIKELY(expr) (expr) +# endif +#endif /* !defined(PGB_UNLIKELY) */ +#if !defined(PGB_LIKELY) +# if __has_builtin(__builtin_expect) +# define PGB_LIKELY(expr) __builtin_expect(!!(expr), 1) +# else +# define PGB_LIKELY(expr) (expr) +# endif +#endif /* !defined(PGB_LIKELY) */ + +#if PEANUT_GB_USE_INTRINSICS +/* If using MSVC, only enable intrinsics for x86 platforms*/ +# if defined(_MSC_VER) && __has_include("intrin.h") && \ + (defined(_M_IX86_FP) || defined(_M_AMD64) || defined(_M_X64)) +/* Define intrinsic functions for MSVC. */ +# include +# define PGB_INTRIN_SBC(x,y,cin,res) _subborrow_u8(cin,x,y,&res) +# define PGB_INTRIN_ADC(x,y,cin,res) _addcarry_u8(cin,x,y,&res) +# endif /* MSVC */ + +/* Check for intrinsic functions in GCC and Clang. */ +# if __has_builtin(__builtin_sub_overflow) +# define PGB_INTRIN_SBC(x,y,cin,res) __builtin_sub_overflow(x,y+cin,&res) +# define PGB_INTRIN_ADC(x,y,cin,res) __builtin_add_overflow(x,y+cin,&res) +# endif +#endif /* PEANUT_GB_USE_INTRINSICS */ + +#if defined(PGB_INTRIN_SBC) +# define PGB_INSTR_SBC_R8(r,cin) \ + { \ + uint8_t temp; \ + gb->cpu_reg.f.f_bits.c = PGB_INTRIN_SBC(gb->cpu_reg.a,r,cin,temp);\ + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0;\ + gb->cpu_reg.f.f_bits.n = 1; \ + gb->cpu_reg.f.f_bits.z = (temp == 0x00); \ + gb->cpu_reg.a = temp; \ + } + +# define PGB_INSTR_CP_R8(r) \ + { \ + uint8_t temp; \ + gb->cpu_reg.f.f_bits.c = PGB_INTRIN_SBC(gb->cpu_reg.a,r,0,temp);\ + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0;\ + gb->cpu_reg.f.f_bits.n = 1; \ + gb->cpu_reg.f.f_bits.z = (temp == 0x00); \ + } +#else +# define PGB_INSTR_SBC_R8(r,cin) \ + { \ + uint16_t temp = gb->cpu_reg.a - (r + cin); \ + gb->cpu_reg.f.f_bits.c = (temp & 0xFF00) ? 1 : 0; \ + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f.f_bits.n = 1; \ + gb->cpu_reg.f.f_bits.z = ((temp & 0xFF) == 0x00); \ + gb->cpu_reg.a = (temp & 0xFF); \ + } + +# define PGB_INSTR_CP_R8(r) \ + { \ + uint16_t temp = gb->cpu_reg.a - r; \ + gb->cpu_reg.f.f_bits.c = (temp & 0xFF00) ? 1 : 0; \ + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f.f_bits.n = 1; \ + gb->cpu_reg.f.f_bits.z = ((temp & 0xFF) == 0x00); \ + } +#endif /* PGB_INTRIN_SBC */ + +#if defined(PGB_INTRIN_ADC) +# define PGB_INSTR_ADC_R8(r,cin) \ + { \ + uint8_t temp; \ + gb->cpu_reg.f.f_bits.c = PGB_INTRIN_ADC(gb->cpu_reg.a,r,cin,temp);\ + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f.f_bits.n = 0; \ + gb->cpu_reg.f.f_bits.z = (temp == 0x00); \ + gb->cpu_reg.a = temp; \ + } +#else +# define PGB_INSTR_ADC_R8(r,cin) \ + { \ + uint16_t temp = gb->cpu_reg.a + r + cin; \ + gb->cpu_reg.f.f_bits.c = (temp & 0xFF00) ? 1 : 0; \ + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f.f_bits.n = 0; \ + gb->cpu_reg.f.f_bits.z = ((temp & 0xFF) == 0x00); \ + gb->cpu_reg.a = (temp & 0xFF); \ + } +#endif /* PGB_INTRIN_ADC */ + +#define PGB_INSTR_INC_R8(r) \ + r++; \ + gb->cpu_reg.f.f_bits.h = ((r & 0x0F) == 0x00); \ + gb->cpu_reg.f.f_bits.n = 0; \ + gb->cpu_reg.f.f_bits.z = (r == 0x00) + +#define PGB_INSTR_DEC_R8(r) \ + r--; \ + gb->cpu_reg.f.f_bits.h = ((r & 0x0F) == 0x0F); \ + gb->cpu_reg.f.f_bits.n = 1; \ + gb->cpu_reg.f.f_bits.z = (r == 0x00) + +#define PGB_INSTR_XOR_R8(r) \ + gb->cpu_reg.a ^= r; \ + gb->cpu_reg.f.reg = 0; \ + gb->cpu_reg.f.f_bits.z = (gb->cpu_reg.a == 0x00) + +#define PGB_INSTR_OR_R8(r) \ + gb->cpu_reg.a |= r; \ + gb->cpu_reg.f.reg = 0; \ + gb->cpu_reg.f.f_bits.z = (gb->cpu_reg.a == 0x00) + +#define PGB_INSTR_AND_R8(r) \ + gb->cpu_reg.a &= r; \ + gb->cpu_reg.f.reg = 0; \ + gb->cpu_reg.f.f_bits.z = (gb->cpu_reg.a == 0x00); \ + gb->cpu_reg.f.f_bits.h = 1 + +#if PEANUT_GB_IS_LITTLE_ENDIAN +# define PEANUT_GB_GET_LSB16(x) (x & 0xFF) +# define PEANUT_GB_GET_MSB16(x) (x >> 8) +# define PEANUT_GB_GET_MSN16(x) (x >> 12) +# define PEANUT_GB_U8_TO_U16(h,l) ((l) | ((h) << 8)) +#else +# define PEANUT_GB_GET_LSB16(x) (x >> 8) +# define PEANUT_GB_GET_MSB16(x) (x & 0xFF) +# define PEANUT_GB_GET_MSN16(x) ((x & 0xF0) >> 4) +# define PEANUT_GB_U8_TO_U16(h,l) ((h) | ((l) << 8)) +#endif + +struct cpu_registers_s +{ +/* Change register order if big endian. + * Macro receives registers in little endian order. */ +#if PEANUT_GB_IS_LITTLE_ENDIAN +# define PEANUT_GB_LE_REG(x,y) x,y +#else +# define PEANUT_GB_LE_REG(x,y) y,x +#endif + /* Define specific bits of Flag register. */ + union { + struct { + uint8_t : 4; /* Unused. */ + uint8_t c: 1; /* Carry flag. */ + uint8_t h: 1; /* Half carry flag. */ + uint8_t n: 1; /* Add/sub flag. */ + uint8_t z: 1; /* Zero flag. */ + } f_bits; + uint8_t reg; + } f; + uint8_t a; + + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(c,b); + } bytes; + uint16_t reg; + } bc; + + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(e,d); + } bytes; + uint16_t reg; + } de; + + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(l,h); + } bytes; + uint16_t reg; + } hl; + + /* Stack pointer */ + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(p, s); + } bytes; + uint16_t reg; + } sp; + + /* Program counter */ + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(c, p); + } bytes; + uint16_t reg; + } pc; +#undef PEANUT_GB_LE_REG +}; + +struct count_s +{ + uint_fast16_t lcd_count; /* LCD Timing */ + uint_fast16_t div_count; /* Divider Register Counter */ + uint_fast16_t tima_count; /* Timer Counter */ + uint_fast16_t serial_count; /* Serial Counter */ + uint_fast32_t rtc_count; /* RTC Counter */ + uint_fast32_t lcd_off_count; /* Cycles LCD has been disabled */ +}; + +#if ENABLE_LCD + /* Bit mask for the shade of pixel to display */ + #define LCD_COLOUR 0x03 + +# if PEANUT_GB_12_COLOUR + /** + * Bit mask for whether a pixel is OBJ0, OBJ1, or BG. Each may have a different + * palette when playing a DMG game on CGB. + */ + #define LCD_PALETTE_OBJ 0x10 + #define LCD_PALETTE_BG 0x20 + /** + * Bit mask for the two bits listed above. + * LCD_PALETTE_ALL == 0b00 --> OBJ0 + * LCD_PALETTE_ALL == 0b01 --> OBJ1 + * LCD_PALETTE_ALL == 0b10 --> BG + * LCD_PALETTE_ALL == 0b11 --> NOT POSSIBLE + */ + #define LCD_PALETTE_ALL 0x30 +# endif +#endif + +/** + * Errors that may occur during emulation. + */ +enum gb_error_e +{ + GB_UNKNOWN_ERROR = 0, + GB_INVALID_OPCODE = 1, + GB_INVALID_READ = 2, + GB_INVALID_WRITE = 3, + + /* GB_HALT_FOREVER is deprecated and will no longer be issued as an + * error by Peanut-GB. */ + GB_HALT_FOREVER PGB_DEPRECATED("Error no longer issued by Peanut-GB") = 4, + + GB_INVALID_MAX = 5 +}; + +/** + * Errors that may occur during library initialisation. + */ +enum gb_init_error_e +{ + GB_INIT_NO_ERROR = 0, + GB_INIT_CARTRIDGE_UNSUPPORTED, + GB_INIT_INVALID_CHECKSUM, + + GB_INIT_INVALID_MAX +}; + +/** + * Return codes for serial receive function, mainly for clarity. + */ +enum gb_serial_rx_ret_e +{ + GB_SERIAL_RX_SUCCESS = 0, + GB_SERIAL_RX_NO_CONNECTION = 1, + /* Paramix (PGB_SERIAL_WAIT): the answer is not there yet, ask again at the next instruction */ + GB_SERIAL_RX_WAIT = 2 +}; + +union cart_rtc +{ + struct + { + uint8_t sec; + uint8_t min; + uint8_t hour; + uint8_t yday; + uint8_t high; + } reg; + uint8_t bytes[5]; +}; + +/** + * Emulator context. + * + * Only values within the `direct` struct may be modified directly by the + * front-end implementation. Other variables must not be modified. + */ +struct gb_s +{ + /** + * Return byte from ROM at given address. + * + * \param gb_s emulator context + * \param addr address + * \return byte at address in ROM + */ + uint8_t (*gb_rom_read)(struct gb_s*, const uint_fast32_t addr); + + /** + * Return byte from cart RAM at given address. + * + * \param gb_s emulator context + * \param addr address + * \return byte at address in RAM + */ + uint8_t (*gb_cart_ram_read)(struct gb_s*, const uint_fast32_t addr); + + /** + * Write byte to cart RAM at given address. + * + * \param gb_s emulator context + * \param addr address + * \param val value to write to address in RAM + */ + void (*gb_cart_ram_write)(struct gb_s*, const uint_fast32_t addr, + const uint8_t val); + + /** + * Notify front-end of error. + * + * \param gb_s emulator context + * \param gb_error_e error code + * \param addr address of where error occurred + */ + void (*gb_error)(struct gb_s*, const enum gb_error_e, const uint16_t addr); + + /* Transmit one byte and return the received byte. */ + void (*gb_serial_tx)(struct gb_s*, const uint8_t tx); + enum gb_serial_rx_ret_e (*gb_serial_rx)(struct gb_s*, uint8_t* rx); + + /* Read byte from boot ROM at given address. */ + uint8_t (*gb_bootrom_read)(struct gb_s*, const uint_fast16_t addr); + + struct + { + bool gb_halt : 1; + bool gb_ime : 1; + /* gb_frame is set when 0.016742706298828125 seconds have + * passed. It is likely that a new frame has been drawn since + * then, but it is possible that the LCD was switched off and + * nothing was drawn. */ + bool gb_frame : 1; + bool lcd_blank : 1; + /* Set if MBC3O cart is used. */ + bool cart_is_mbc3O : 1; + }; + + /* Cartridge information: + * Memory Bank Controller (MBC) type. */ + int8_t mbc; + /* Whether the MBC has internal RAM. */ + uint8_t cart_ram; + /* Number of ROM banks in cartridge. */ + uint16_t num_rom_banks_mask; + /* Number of RAM banks in cartridge. Ignore for MBC2. */ + uint8_t num_ram_banks; + + uint16_t selected_rom_bank; + /* WRAM and VRAM bank selection not available. */ + uint8_t cart_ram_bank; + uint8_t enable_cart_ram; + /* Cartridge ROM/RAM mode select. */ + uint8_t cart_mode_select; + + union cart_rtc rtc_latched, rtc_real; + + struct cpu_registers_s cpu_reg; + //struct gb_registers_s gb_reg; + struct count_s counter; + + /* TODO: Allow implementation to allocate WRAM, VRAM and Frame Buffer. */ + uint8_t wram[WRAM_SIZE]; + uint8_t vram[VRAM_SIZE]; + uint8_t oam[OAM_SIZE]; + uint8_t hram_io[HRAM_IO_SIZE]; + + struct + { + /** + * Draw line on screen. + * + * \param gb_s emulator context + * \param pixels The 160 pixels to draw. + * Bits 1-0 are the colour to draw. + * Bits 5-4 are the palette, where: + * OBJ0 = 0b00, + * OBJ1 = 0b01, + * BG = 0b10 + * Other bits are undefined. + * Bits 5-4 are only required by front-ends + * which want to use a different colour for + * different object palettes. This is what + * the Game Boy Color (CGB) does to DMG + * games. + * \param line Line to draw pixels on. This is + * guaranteed to be between 0-144 inclusive. + */ + void (*lcd_draw_line)(struct gb_s *gb, + const uint8_t *pixels, + const uint_fast8_t line); + + /* Palettes */ + uint8_t bg_palette[4]; + uint8_t sp_palette[8]; + + uint8_t window_clear; + uint8_t WY; + + /* Only support 30fps frame skip. */ + bool frame_skip_count : 1; + bool interlace_count : 1; + } display; + + /** + * Variables that may be modified directly by the front-end. + * This method seems to be easier and possibly less overhead than + * calling a function to modify these variables each time. + * + * None of this is thread-safe. + */ + struct + { + /* Set to enable interlacing. Interlacing will start immediately + * (at the next line drawing). + */ + bool interlace : 1; + bool frame_skip : 1; + + union + { + struct + { + /* Using this bitfield is deprecated due to + * portability concerns. It is recommended to + * use the JOYPAD_* defines instead. + */ + bool a : 1; + bool b : 1; + bool select : 1; + bool start : 1; + bool right : 1; + bool left : 1; + bool up : 1; + bool down : 1; + } joypad_bits; + uint8_t joypad; + }; + + /* Implementation defined data. Set to NULL if not required. */ + void *priv; + } direct; +}; + +#ifndef PEANUT_GB_HEADER_ONLY + +#define IO_JOYP 0x00 +#define IO_SB 0x01 +#define IO_SC 0x02 +#define IO_DIV 0x04 +#define IO_TIMA 0x05 +#define IO_TMA 0x06 +#define IO_TAC 0x07 +#define IO_IF 0x0F +#define IO_LCDC 0x40 +#define IO_STAT 0x41 +#define IO_SCY 0x42 +#define IO_SCX 0x43 +#define IO_LY 0x44 +#define IO_LYC 0x45 +#define IO_DMA 0x46 +#define IO_BGP 0x47 +#define IO_OBP0 0x48 +#define IO_OBP1 0x49 +#define IO_WY 0x4A +#define IO_WX 0x4B +#define IO_BOOT 0x50 +#define IO_IE 0xFF + +#define IO_TAC_RATE_MASK 0x3 +#define IO_TAC_ENABLE_MASK 0x4 + +/* LCD Mode defines. */ +#define IO_STAT_MODE_HBLANK 0 +#define IO_STAT_MODE_VBLANK 1 +#define IO_STAT_MODE_OAM_SCAN 2 +#define IO_STAT_MODE_LCD_DRAW 3 +#define IO_STAT_MODE_VBLANK_OR_TRANSFER_MASK 0x1 + +/** + * Internal function used to read bytes. + * addr is host platform endian. + */ +#ifndef PGB_READ_ATTR +#define PGB_READ_ATTR +#endif +PGB_READ_ATTR uint8_t __gb_read(struct gb_s *gb, uint16_t addr) +{ + switch(PEANUT_GB_GET_MSN16(addr)) + { + case 0x0: + /* IO_BOOT is only set to 1 if gb->gb_bootrom_read was not NULL + * on reset. */ + if(gb->hram_io[IO_BOOT] == 0 && addr < 0x0100) + { + return gb->gb_bootrom_read(gb, addr); + } + + /* Fallthrough */ + case 0x1: + case 0x2: + case 0x3: +#ifdef PGB_ROM /* Paramix: the ROM straight from the cached flash window */ + return PGB_ROM[addr]; +#else + return gb->gb_rom_read(gb, addr); +#endif + + case 0x4: + case 0x5: + case 0x6: + case 0x7: +#if defined(PGB_ROM) && defined(PGB_ROMOFF) /* Paramix GB_TRIM: offset of the switchable bank, set when it changes */ + return PGB_ROM[addr + PGB_ROMOFF]; +#elif defined(PGB_ROM) /* Paramix */ + if(gb->mbc == 1 && gb->cart_mode_select) + return PGB_ROM[addr + ((gb->selected_rom_bank & 0x1F) - 1) * ROM_BANK_SIZE]; + else + return PGB_ROM[addr + (gb->selected_rom_bank - 1) * ROM_BANK_SIZE]; +#else + if(gb->mbc == 1 && gb->cart_mode_select) + return gb->gb_rom_read(gb, + addr + ((gb->selected_rom_bank & 0x1F) - 1) * ROM_BANK_SIZE); + else + return gb->gb_rom_read(gb, addr + (gb->selected_rom_bank - 1) * ROM_BANK_SIZE); +#endif + + case 0x8: + case 0x9: + return gb->vram[addr - VRAM_ADDR]; + + case 0xA: + case 0xB: + if(gb->mbc == 3 && gb->cart_ram_bank >= 0x08) + { + return gb->rtc_latched.bytes[gb->cart_ram_bank - 0x08]; + } + else if(gb->cart_ram && gb->enable_cart_ram) + { + if(gb->mbc == 2) + { + /* Only 9 bits are available in address. */ + addr &= 0x1FF; + return gb->gb_cart_ram_read(gb, addr); + } + else if((gb->cart_mode_select || gb->mbc != 1) && + gb->cart_ram_bank < gb->num_ram_banks) + { + return gb->gb_cart_ram_read(gb, addr - CART_RAM_ADDR + + (gb->cart_ram_bank * CRAM_BANK_SIZE)); + } + else + return gb->gb_cart_ram_read(gb, addr - CART_RAM_ADDR); + } + + return 0xFF; + + case 0xC: + case 0xD: + return gb->wram[addr - WRAM_0_ADDR]; + + case 0xE: + return gb->wram[addr - ECHO_ADDR]; + + case 0xF: + if(addr < OAM_ADDR) + return gb->wram[addr - ECHO_ADDR]; + + if(addr < UNUSED_ADDR) + return gb->oam[addr - OAM_ADDR]; + + /* Unusable memory area. Reading from this area returns 0xFF.*/ + if(addr < IO_ADDR) + return 0xFF; + + /* APU registers. */ + if((addr >= 0xFF10) && (addr <= 0xFF3F)) + { +#if ENABLE_SOUND + return audio_read(addr); +#else + static const uint8_t ortab[] = { + 0x80, 0x3f, 0x00, 0xff, 0xbf, + 0xff, 0x3f, 0x00, 0xff, 0xbf, + 0x7f, 0xff, 0x9f, 0xff, 0xbf, + 0xff, 0xff, 0x00, 0x00, 0xbf, + 0x00, 0x00, 0x70, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + return gb->hram_io[addr - IO_ADDR] | ortab[addr - IO_ADDR]; +#endif + } + + /* HRAM */ + if(addr >= IO_ADDR) + return gb->hram_io[addr - IO_ADDR]; + } + + + /* Return address that caused read error. */ + (gb->gb_error)(gb, GB_INVALID_READ, addr); + PGB_UNREACHABLE(); +} + +/** + * Internal function used to write bytes. + */ +void __gb_write(struct gb_s *gb, uint_fast16_t addr, uint8_t val) +{ + switch(PEANUT_GB_GET_MSN16(addr)) + { + case 0x0: + case 0x1: + /* Set RAM enable bit. MBC2 is handled in fall-through. */ + if (gb->mbc > 0 && gb->mbc != 2) + { + if (gb->cart_ram) + gb->enable_cart_ram = ((val & 0x0F) == 0x0A); + return; + } + + /* Intentional fall through. */ + case 0x2: + if (gb->mbc == 5) + { + gb->selected_rom_bank = + (gb->selected_rom_bank & 0x100) | val; + gb->selected_rom_bank = + gb->selected_rom_bank & gb->num_rom_banks_mask; + PGB_BANKSET(gb); + return; + } + + /* Intentional fall through. */ + case 0x3: + if(gb->mbc == 1) + { + //selected_rom_bank = val & 0x7; + gb->selected_rom_bank = (val & 0x1F) | (gb->selected_rom_bank & 0x60); + + if((gb->selected_rom_bank & 0x1F) == 0x00) + gb->selected_rom_bank++; + } + else if(gb->mbc == 2) + { + /* If bit 8 is 1, then set ROM bank number. */ + if(addr & 0x100) + { + gb->selected_rom_bank = val & 0x0F; + /* Setting ROM bank to 0, sets it to 1. */ + if(!gb->selected_rom_bank) + gb->selected_rom_bank++; + } + /* Otherwise set whether RAM is enabled or not. */ + else + { + gb->enable_cart_ram = ((val & 0x0F) == 0x0A); + return; + } + } + else if(gb->mbc == 3) + { + gb->selected_rom_bank = val; + if(!gb->cart_is_mbc3O) + gb->selected_rom_bank = val & 0x7F; + + if(!gb->selected_rom_bank) + gb->selected_rom_bank++; + } + else if(gb->mbc == 5) + gb->selected_rom_bank = (val & 0x01) << 8 | (gb->selected_rom_bank & 0xFF); + + gb->selected_rom_bank = gb->selected_rom_bank & gb->num_rom_banks_mask; + PGB_BANKSET(gb); + return; + + case 0x4: + case 0x5: + if(gb->mbc == 1) + { + gb->cart_ram_bank = (val & 3); + gb->selected_rom_bank = ((val & 3) << 5) | (gb->selected_rom_bank & 0x1F); + gb->selected_rom_bank = gb->selected_rom_bank & gb->num_rom_banks_mask; + PGB_BANKSET(gb); + } + else if(gb->mbc == 3) + { + gb->cart_ram_bank = val; + /* If not using MBC3, only the first 4 cart RAM banks are useable. + * If cart RAM bank 0x8-0xC are selected, then the corresponding + * RTC register is selected instead of cart RAM. */ + if(!gb->cart_is_mbc3O && gb->cart_ram_bank < 0x8) + gb->cart_ram_bank &= 0x3; + } + + else if(gb->mbc == 5) + gb->cart_ram_bank = (val & 0x0F); + + return; + + case 0x6: + case 0x7: + val &= 1; + if(gb->mbc == 3 && val && gb->cart_mode_select == 0) + memcpy(&gb->rtc_latched.bytes, &gb->rtc_real.bytes, sizeof(gb->rtc_latched.bytes)); + + /* Set banking mode select. */ + gb->cart_mode_select = val; + PGB_BANKSET(gb); + return; + + case 0x8: + case 0x9: + gb->vram[addr - VRAM_ADDR] = val; + return; + + case 0xA: + case 0xB: + if(gb->mbc == 3 && gb->cart_ram_bank >= 0x08) + { + const uint8_t rtc_reg_mask[5] = { + 0x3F, 0x3F, 0x1F, 0xFF, 0xC1 + }; + uint8_t reg = gb->cart_ram_bank - 0x08; + //if(reg == 0) gb->counter.rtc_count = 0; + + gb->rtc_real.bytes[reg] = val & rtc_reg_mask[reg]; + } + /* Do not write to RAM if unavailable or disabled. */ + else if(gb->cart_ram && gb->enable_cart_ram) + { + if(gb->mbc == 2) + { + /* Only 9 bits are available in address. */ + addr &= 0x1FF; + /* Data is only 4 bits wide in MBC2 RAM. */ + val &= 0x0F; + /* Upper nibble is set to high. */ + val |= 0xF0; + gb->gb_cart_ram_write(gb, addr, val); + } + /* If cart has RAM, use this. If MBC1, only the first + * RAM bank can be written to if the advanced banking + * mode is selected. */ + else if(((gb->mbc == 1 && gb->cart_mode_select) || gb->mbc != 1) && + gb->cart_ram_bank < gb->num_ram_banks) + { + gb->gb_cart_ram_write(gb, + addr - CART_RAM_ADDR + (gb->cart_ram_bank * CRAM_BANK_SIZE), val); + } + else if(gb->num_ram_banks) + gb->gb_cart_ram_write(gb, addr - CART_RAM_ADDR, val); + } + + return; + + case 0xC: + gb->wram[addr - WRAM_0_ADDR] = val; + return; + + case 0xD: + gb->wram[addr - WRAM_1_ADDR + WRAM_BANK_SIZE] = val; + return; + + case 0xE: + gb->wram[addr - ECHO_ADDR] = val; + return; + + case 0xF: + if(addr < OAM_ADDR) + { + gb->wram[addr - ECHO_ADDR] = val; + return; + } + + if(addr < UNUSED_ADDR) + { + gb->oam[addr - OAM_ADDR] = val; + return; + } + + /* Unusable memory area. */ + if(addr < IO_ADDR) + return; + + if(HRAM_ADDR <= addr && addr < INTR_EN_ADDR) + { + gb->hram_io[addr - IO_ADDR] = val; + return; + } + + if((addr >= 0xFF10) && (addr <= 0xFF3F)) + { +#if ENABLE_SOUND + audio_write(addr, val); +#else + gb->hram_io[addr - IO_ADDR] = val; +#ifdef PGB_APU_WRITE /* Paramix: the sound registers seen by the Paradise's buzzer */ + PGB_APU_WRITE(addr, val); +#endif +#endif + return; + } + + /* IO and Interrupts. */ + switch(PEANUT_GB_GET_LSB16(addr)) + { + /* Joypad */ + case 0x00: + /* Only bits 5 and 4 are R/W. + * The lower bits are overwritten later. + * The two most significant bits are unused, + * but they must always be read as 1. */ + gb->hram_io[IO_JOYP] = val | 0xC0; + + /* Direction keys selected */ + if((gb->hram_io[IO_JOYP] & 0x10) == 0) + gb->hram_io[IO_JOYP] |= (gb->direct.joypad >> 4); + /* Button keys selected */ + else + gb->hram_io[IO_JOYP] |= (gb->direct.joypad & 0x0F); + + return; + + /* Serial */ + case 0x01: + gb->hram_io[IO_SB] = val; + return; + + case 0x02: + gb->hram_io[IO_SC] = val; +#ifdef PGB_SERIAL_WAIT + /* Paramix: writing the start bit begins a new transfer (the link sees each one) */ + if(val & SERIAL_SC_TX_START) + gb->counter.serial_count = 0; +#endif + return; + + /* Timer Registers */ + case 0x04: + gb->hram_io[IO_DIV] = 0x00; + return; + + case 0x05: + gb->hram_io[IO_TIMA] = val; + return; + + case 0x06: + gb->hram_io[IO_TMA] = val; + return; + + case 0x07: + gb->hram_io[IO_TAC] = val; + return; + + /* Interrupt Flag Register */ + case 0x0F: + gb->hram_io[IO_IF] = (val | 0xE0); + return; + + /* LCD Registers */ + case 0x40: + { + uint8_t lcd_enabled; + + /* Check if LCD is already enabled. */ + lcd_enabled = (gb->hram_io[IO_LCDC] & LCDC_ENABLE); + + gb->hram_io[IO_LCDC] = val; + + /* Check if LCD is going to be switched on. */ + if (!lcd_enabled && (val & LCDC_ENABLE)) + { + gb->lcd_blank = true; + } + /* Check if LCD is being switched off. */ + else if (lcd_enabled && !(val & LCDC_ENABLE)) + { + /* Peanut-GB will happily turn off LCD outside + * of VBLANK even though this damages real + * hardware. */ + + /* Set LCD to Mode 0. */ + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | + IO_STAT_MODE_HBLANK; + /* LY fixed to 0 when LCD turned off. */ + gb->hram_io[IO_LY] = 0; + /* Keep track of lcd_count to correctly track + * passing time. */ + gb->counter.lcd_off_count += gb->counter.lcd_count; + /* Reset LCD timer, since the LCD starts from + * the beginning on power on. */ + gb->counter.lcd_count = 0; + } + return; + } + + case 0x41: + gb->hram_io[IO_STAT] = (val & STAT_USER_BITS) | (gb->hram_io[IO_STAT] & STAT_MODE) | 0x80; + return; + + case 0x42: + gb->hram_io[IO_SCY] = val; + return; + + case 0x43: + gb->hram_io[IO_SCX] = val; + return; + + /* LY (0xFF44) is read only. */ + case 0x45: + gb->hram_io[IO_LYC] = val; + return; + + /* DMA Register */ + case 0x46: + { + uint16_t dma_addr; + uint16_t i; + + dma_addr = (uint_fast16_t)val << 8; + gb->hram_io[IO_DMA] = val; + + for(i = 0; i < OAM_SIZE; i++) + { + gb->oam[i] = __gb_read(gb, dma_addr + i); + } + + return; + } + + /* DMG Palette Registers */ + case 0x47: + gb->hram_io[IO_BGP] = val; + gb->display.bg_palette[0] = (gb->hram_io[IO_BGP] & 0x03); + gb->display.bg_palette[1] = (gb->hram_io[IO_BGP] >> 2) & 0x03; + gb->display.bg_palette[2] = (gb->hram_io[IO_BGP] >> 4) & 0x03; + gb->display.bg_palette[3] = (gb->hram_io[IO_BGP] >> 6) & 0x03; + return; + + case 0x48: + gb->hram_io[IO_OBP0] = val; + gb->display.sp_palette[0] = (gb->hram_io[IO_OBP0] & 0x03); + gb->display.sp_palette[1] = (gb->hram_io[IO_OBP0] >> 2) & 0x03; + gb->display.sp_palette[2] = (gb->hram_io[IO_OBP0] >> 4) & 0x03; + gb->display.sp_palette[3] = (gb->hram_io[IO_OBP0] >> 6) & 0x03; + return; + + case 0x49: + gb->hram_io[IO_OBP1] = val; + gb->display.sp_palette[4] = (gb->hram_io[IO_OBP1] & 0x03); + gb->display.sp_palette[5] = (gb->hram_io[IO_OBP1] >> 2) & 0x03; + gb->display.sp_palette[6] = (gb->hram_io[IO_OBP1] >> 4) & 0x03; + gb->display.sp_palette[7] = (gb->hram_io[IO_OBP1] >> 6) & 0x03; + return; + + /* Window Position Registers */ + case 0x4A: + gb->hram_io[IO_WY] = val; + return; + + case 0x4B: + gb->hram_io[IO_WX] = val; + return; + + /* Turn off boot ROM */ + case 0x50: + gb->hram_io[IO_BOOT] = 0x01; + return; + + /* Interrupt Enable Register */ + case 0xFF: + gb->hram_io[IO_IE] = val; + return; + } + } + + /* Invalid writes are ignored. */ + return; +} + +uint8_t __gb_execute_cb(struct gb_s *gb) +{ + uint8_t inst_cycles; + uint8_t cbop = __gb_read(gb, gb->cpu_reg.pc.reg++); + uint8_t r = (cbop & 0x7); + uint8_t b = (cbop >> 3) & 0x7; + uint8_t d = (cbop >> 3) & 0x1; + uint8_t val; + uint8_t writeback = 1; + + inst_cycles = 8; + /* Add an additional 8 cycles to these sets of instructions. */ + switch(cbop & 0xC7) + { + case 0x06: + case 0x86: + case 0xC6: + inst_cycles += 8; + break; + case 0x46: + inst_cycles += 4; + break; + } + + switch(r) + { + case 0: + val = gb->cpu_reg.bc.bytes.b; + break; + + case 1: + val = gb->cpu_reg.bc.bytes.c; + break; + + case 2: + val = gb->cpu_reg.de.bytes.d; + break; + + case 3: + val = gb->cpu_reg.de.bytes.e; + break; + + case 4: + val = gb->cpu_reg.hl.bytes.h; + break; + + case 5: + val = gb->cpu_reg.hl.bytes.l; + break; + + case 6: + val = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + /* Only values 0-7 are possible here, so we make the final case + * default to satisfy -Wmaybe-uninitialized warning. */ + default: + val = gb->cpu_reg.a; + break; + } + + switch(cbop >> 6) + { + case 0x0: + cbop = (cbop >> 4) & 0x3; + + switch(cbop) + { + case 0x0: /* RdC R */ + case 0x1: /* Rd R */ + if(d) /* RRC R / RR R */ + { + uint8_t temp = val; + val = (val >> 1); + val |= cbop ? (gb->cpu_reg.f.f_bits.c << 7) : (temp << 7); + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.z = (val == 0x00); + gb->cpu_reg.f.f_bits.c = (temp & 0x01); + } + else /* RLC R / RL R */ + { + uint8_t temp = val; + val = (val << 1); + val |= cbop ? gb->cpu_reg.f.f_bits.c : (temp >> 7); + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.z = (val == 0x00); + gb->cpu_reg.f.f_bits.c = (temp >> 7); + } + + break; + + case 0x2: + if(d) /* SRA R */ + { + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.c = val & 0x01; + val = (val >> 1) | (val & 0x80); + gb->cpu_reg.f.f_bits.z = (val == 0x00); + } + else /* SLA R */ + { + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.c = (val >> 7); + val = val << 1; + gb->cpu_reg.f.f_bits.z = (val == 0x00); + } + + break; + + case 0x3: + if(d) /* SRL R */ + { + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.c = val & 0x01; + val = val >> 1; + gb->cpu_reg.f.f_bits.z = (val == 0x00); + } + else /* SWAP R */ + { + uint8_t temp = (val >> 4) & 0x0F; + temp |= (val << 4) & 0xF0; + val = temp; + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.z = (val == 0x00); + } + + break; + } + + break; + + case 0x1: /* BIT B, R */ + gb->cpu_reg.f.f_bits.z = !((val >> b) & 0x1); + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = 1; + writeback = 0; + break; + + case 0x2: /* RES B, R */ + val &= (0xFE << b) | (0xFF >> (8 - b)); + break; + + case 0x3: /* SET B, R */ + val |= (0x1 << b); + break; + } + + if(writeback) + { + switch(r) + { + case 0: + gb->cpu_reg.bc.bytes.b = val; + break; + + case 1: + gb->cpu_reg.bc.bytes.c = val; + break; + + case 2: + gb->cpu_reg.de.bytes.d = val; + break; + + case 3: + gb->cpu_reg.de.bytes.e = val; + break; + + case 4: + gb->cpu_reg.hl.bytes.h = val; + break; + + case 5: + gb->cpu_reg.hl.bytes.l = val; + break; + + case 6: + __gb_write(gb, gb->cpu_reg.hl.reg, val); + break; + + case 7: + gb->cpu_reg.a = val; + break; + } + } + return inst_cycles; +} + +#if ENABLE_LCD +struct sprite_data { + uint8_t sprite_number; + uint8_t x; +}; + +#if PEANUT_GB_HIGH_LCD_ACCURACY +static int compare_sprites(const struct sprite_data *const sd1, const struct sprite_data *const sd2) +{ + int x_res; + + x_res = (int)sd1->x - (int)sd2->x; + if(x_res != 0) + return x_res; + + return (int)sd1->sprite_number - (int)sd2->sprite_number; +} +#endif + +#ifdef PGB_FAST_LINE +/* Paramix test38: background and window a tile at a time (8 dots from one table lookup per byte) */ +static const uint16_t pgb_spread[256] = { +#define S1(t) (uint16_t)(((t)&1)|((t)&2)<<1|((t)&4)<<2|((t)&8)<<3|((t)&16)<<4|((t)&32)<<5|((t)&64)<<6|((t)&128)<<7) +#define S4(t) S1(t),S1(t+1),S1(t+2),S1(t+3) +#define S16(t) S4(t),S4(t+4),S4(t+8),S4(t+12) +#define S64(t) S16(t),S16(t+16),S16(t+32),S16(t+48) + S64(0),S64(64),S64(128),S64(192) +#undef S1 +#undef S4 +#undef S16 +#undef S64 +}; +/* palette as four dots per byte of the index (leftmost dot in the top bits), rebuilt when BGP changes */ +static uint32_t pgb_pal4[256], pgb_pal4_key = 0xFFFFFFFFu; +static void pgb_pal4_check(struct gb_s *gb) +{ + const uint8_t *p = gb->display.bg_palette; + uint32_t key = p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; + if(key == pgb_pal4_key) return; + pgb_pal4_key = key; + for(unsigned i = 0; i < 256; i++) + { + uint32_t v = p[i >> 6] | p[(i >> 4) & 3] << 8 | p[(i >> 2) & 3] << 16 | (uint32_t)p[i & 3] << 24; +#if PEANUT_GB_12_COLOUR + v |= LCD_PALETTE_BG * 0x01010101u; +#endif + pgb_pal4[i] = v; + } +} +/* whole tiles from pix (may start up to 7 dots left of the line and end up to 7 dots right of it) */ +static void pgb_tiles(struct gb_s *gb, uint8_t *pix, unsigned ntiles, uint16_t map, uint8_t tx, uint8_t py) +{ + const uint8_t sel = gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT; + const uint8_t *vr = gb->vram; + for(; ntiles; ntiles--, tx = (tx + 1) & 31, pix += 8) + { + uint8_t idx = vr[map + tx]; + const uint8_t *t = vr + (sel ? VRAM_TILES_1 + idx * 0x10 : VRAM_TILES_2 + ((idx + 0x80) & 0xFF) * 0x10) + 2 * py; + uint32_t w = pgb_spread[t[0]] | (uint32_t)pgb_spread[t[1]] << 1; + uint32_t v0 = pgb_pal4[w >> 8], v1 = pgb_pal4[w & 0xFF]; + __builtin_memcpy(pix, &v0, 4); + __builtin_memcpy(pix + 4, &v1, 4); + } +} +#endif + +void __gb_draw_line(struct gb_s *gb) +{ +#ifdef PGB_FAST_LINE + uint32_t pixw[44]; /* 8 dots spare on each side for whole tiles */ + uint8_t *const pixels = (uint8_t *)pixw + 8; +#else + uint8_t pixels[160] = {0}; +#endif + + /* If LCD not initialised by front-end, don't render anything. */ + if(gb->display.lcd_draw_line == NULL) + return; + + if(gb->direct.frame_skip && !gb->display.frame_skip_count) + return; + + /* If interlaced mode is activated, check if we need to draw the current + * line. */ + if(gb->direct.interlace) + { + if((!gb->display.interlace_count + && (gb->hram_io[IO_LY] & 1) == 0) + || (gb->display.interlace_count + && (gb->hram_io[IO_LY] & 1) == 1)) + { + /* Compensate for missing window draw if required. */ + if(gb->hram_io[IO_LCDC] & LCDC_WINDOW_ENABLE + && gb->hram_io[IO_LY] >= gb->display.WY + && gb->hram_io[IO_WX] <= 166) + gb->display.window_clear++; + + return; + } + } + +#ifdef PGB_FAST_LINE + if(!(gb->hram_io[IO_LCDC] & LCDC_BG_ENABLE)) + for(int k = 2; k < 42; k++) pixw[k] = 0; + else + { + uint8_t bg_y = gb->hram_io[IO_LY] + gb->hram_io[IO_SCY], scx = gb->hram_io[IO_SCX]; + uint16_t map = ((gb->hram_io[IO_LCDC] & LCDC_BG_MAP) ? VRAM_BMAP_2 : VRAM_BMAP_1) + (bg_y >> 3) * 0x20; + pgb_pal4_check(gb); + pgb_tiles(gb, pixels - (scx & 7), (scx & 7) ? 21 : 20, map, scx >> 3, bg_y & 7); + } + if(gb->hram_io[IO_LCDC] & LCDC_WINDOW_ENABLE + && gb->hram_io[IO_LY] >= gb->display.WY + && gb->hram_io[IO_WX] <= 166) + { + uint16_t map = ((gb->hram_io[IO_LCDC] & LCDC_WINDOW_MAP) ? VRAM_BMAP_2 : VRAM_BMAP_1) + + (gb->display.window_clear >> 3) * 0x20; + int x0 = (int)gb->hram_io[IO_WX] - 7; /* -7..159: the window's first dot (left of the line when below 0) */ + pgb_pal4_check(gb); + pgb_tiles(gb, pixels + x0, (unsigned)(160 - x0 + 7) >> 3, map, 0, gb->display.window_clear & 7); + gb->display.window_clear++; + } +#else + /* If background is enabled, draw it. */ + if(gb->hram_io[IO_LCDC] & LCDC_BG_ENABLE) + { + uint8_t bg_y, disp_x, bg_x, idx, py, px, t1, t2; + uint16_t bg_map, tile; + + /* Calculate current background line to draw. Constant because + * this function draws only this one line each time it is + * called. */ + bg_y = gb->hram_io[IO_LY] + gb->hram_io[IO_SCY]; + + /* Get selected background map address for first tile + * corresponding to current line. + * 0x20 (32) is the width of a background tile, and the bit + * shift is to calculate the address. */ + bg_map = + ((gb->hram_io[IO_LCDC] & LCDC_BG_MAP) ? + VRAM_BMAP_2 : VRAM_BMAP_1) + + (bg_y >> 3) * 0x20; + + /* The displays (what the player sees) X coordinate, drawn right + * to left. */ + disp_x = LCD_WIDTH - 1; + + /* The X coordinate to begin drawing the background at. */ + bg_x = disp_x + gb->hram_io[IO_SCX]; + + /* Get tile index for current background tile. */ + idx = gb->vram[bg_map + (bg_x >> 3)]; + /* Y coordinate of tile pixel to draw. */ + py = (bg_y & 0x07); + /* X coordinate of tile pixel to draw. */ + px = 7 - (bg_x & 0x07); + + /* Select addressing mode. */ + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + + tile += 2 * py; + + /* fetch first tile */ + t1 = gb->vram[tile] >> px; + t2 = gb->vram[tile + 1] >> px; + + for(; disp_x != 0xFF; disp_x--) + { + uint8_t c; + + if(px == 8) + { + /* fetch next tile */ + px = 0; + bg_x = disp_x + gb->hram_io[IO_SCX]; + idx = gb->vram[bg_map + (bg_x >> 3)]; + + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + + tile += 2 * py; + t1 = gb->vram[tile]; + t2 = gb->vram[tile + 1]; + } + + /* copy background */ + c = (t1 & 0x1) | ((t2 & 0x1) << 1); + pixels[disp_x] = gb->display.bg_palette[c]; +#if PEANUT_GB_12_COLOUR + pixels[disp_x] |= LCD_PALETTE_BG; +#endif + t1 = t1 >> 1; + t2 = t2 >> 1; + px++; + } + } + + /* draw window */ + if(gb->hram_io[IO_LCDC] & LCDC_WINDOW_ENABLE + && gb->hram_io[IO_LY] >= gb->display.WY + && gb->hram_io[IO_WX] <= 166) + { + uint16_t win_line, tile; + uint8_t disp_x, win_x, py, px, idx, t1, t2, end; + + /* Calculate Window Map Address. */ + win_line = (gb->hram_io[IO_LCDC] & LCDC_WINDOW_MAP) ? + VRAM_BMAP_2 : VRAM_BMAP_1; + win_line += (gb->display.window_clear >> 3) * 0x20; + + disp_x = LCD_WIDTH - 1; + win_x = disp_x - gb->hram_io[IO_WX] + 7; + + // look up tile + py = gb->display.window_clear & 0x07; + px = 7 - (win_x & 0x07); + idx = gb->vram[win_line + (win_x >> 3)]; + + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + + tile += 2 * py; + + // fetch first tile + t1 = gb->vram[tile] >> px; + t2 = gb->vram[tile + 1] >> px; + + // loop & copy window + end = (gb->hram_io[IO_WX] < 7 ? 0 : gb->hram_io[IO_WX] - 7) - 1; + + for(; disp_x != end; disp_x--) + { + uint8_t c; + + if(px == 8) + { + // fetch next tile + px = 0; + win_x = disp_x - gb->hram_io[IO_WX] + 7; + idx = gb->vram[win_line + (win_x >> 3)]; + + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + + tile += 2 * py; + t1 = gb->vram[tile]; + t2 = gb->vram[tile + 1]; + } + + // copy window + c = (t1 & 0x1) | ((t2 & 0x1) << 1); + pixels[disp_x] = gb->display.bg_palette[c]; +#if PEANUT_GB_12_COLOUR + pixels[disp_x] |= LCD_PALETTE_BG; +#endif + t1 = t1 >> 1; + t2 = t2 >> 1; + px++; + } + + gb->display.window_clear++; // advance window line + } +#endif + + // draw sprites + if(gb->hram_io[IO_LCDC] & LCDC_OBJ_ENABLE) + { + uint8_t sprite_number; +#if PEANUT_GB_HIGH_LCD_ACCURACY + uint8_t number_of_sprites = 0; + + struct sprite_data sprites_to_render[MAX_SPRITES_LINE]; + + /* Record number of sprites on the line being rendered, limited + * to the maximum number sprites that the Game Boy is able to + * render on each line (10 sprites). */ + for(sprite_number = 0; + sprite_number < NUM_SPRITES; + sprite_number++) + { + /* Sprite Y position. */ + uint8_t OY = gb->oam[4 * sprite_number + 0]; + /* Sprite X position. */ + uint8_t OX = gb->oam[4 * sprite_number + 1]; + + /* If sprite isn't on this line, continue. */ + if (gb->hram_io[IO_LY] + + (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 0 : 8) >= OY + || gb->hram_io[IO_LY] + 16 < OY) + continue; + + struct sprite_data current; + + current.sprite_number = sprite_number; + current.x = OX; + + uint8_t place; + for (place = number_of_sprites; place != 0; place--) + { + if(compare_sprites(&sprites_to_render[place - 1], ¤t) < 0) + break; + } + if(place >= MAX_SPRITES_LINE) + continue; + for (uint8_t i = number_of_sprites; i > place; --i) { + sprites_to_render[i] = sprites_to_render[i - 1]; + } + if(number_of_sprites < MAX_SPRITES_LINE) + number_of_sprites++; + sprites_to_render[place] = current; + } +#endif + + /* Render each sprite, from low priority to high priority. */ +#if PEANUT_GB_HIGH_LCD_ACCURACY + /* Render the top ten prioritised sprites on this scanline. */ + for(sprite_number = number_of_sprites - 1; + sprite_number != 0xFF; + sprite_number--) + { + uint8_t s = sprites_to_render[sprite_number].sprite_number; +#else + for (sprite_number = NUM_SPRITES - 1; + sprite_number != 0xFF; + sprite_number--) + { + uint8_t s = sprite_number; +#endif + uint8_t py, t1, t2, dir, start, end, shift, disp_x; + /* Sprite Y position. */ + uint8_t OY = gb->oam[4 * s + 0]; + /* Sprite X position. */ + uint8_t OX = gb->oam[4 * s + 1]; + /* Sprite Tile/Pattern Number. */ + uint8_t OT = gb->oam[4 * s + 2] + & (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 0xFE : 0xFF); + /* Additional attributes. */ + uint8_t OF = gb->oam[4 * s + 3]; + +#if !PEANUT_GB_HIGH_LCD_ACCURACY + /* If sprite isn't on this line, continue. */ + if(gb->hram_io[IO_LY] + + (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 0 : 8) >= OY || + gb->hram_io[IO_LY] + 16 < OY) + continue; +#endif + + /* Continue if sprite not visible. */ + if(OX == 0 || OX >= 168) + continue; + + // y flip + py = gb->hram_io[IO_LY] - OY + 16; + + if(OF & OBJ_FLIP_Y) + py = (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 15 : 7) - py; + + // fetch the tile + t1 = gb->vram[VRAM_TILES_1 + OT * 0x10 + 2 * py]; + t2 = gb->vram[VRAM_TILES_1 + OT * 0x10 + 2 * py + 1]; + + // handle x flip + if(OF & OBJ_FLIP_X) + { + dir = 1; + start = (OX < 8 ? 0 : OX - 8); + end = MIN(OX, LCD_WIDTH); + shift = 8 - OX + start; + } + else + { + dir = (uint8_t)-1; + start = MIN(OX, LCD_WIDTH) - 1; + end = (OX < 8 ? 0 : OX - 8) - 1; + shift = OX - (start + 1); + } + + // copy tile + t1 >>= shift; + t2 >>= shift; + + /* TODO: Put for loop within the to if statements + * because the BG priority bit will be the same for + * all the pixels in the tile. */ + for(disp_x = start; disp_x != end; disp_x += dir) + { + uint8_t c = (t1 & 0x1) | ((t2 & 0x1) << 1); + // check transparency / sprite overlap / background overlap + + if(c && !(OF & OBJ_PRIORITY && !((pixels[disp_x] & 0x3) == gb->display.bg_palette[0]))) + { + /* Set pixel colour. */ + pixels[disp_x] = (OF & OBJ_PALETTE) + ? gb->display.sp_palette[c + 4] + : gb->display.sp_palette[c]; +#if PEANUT_GB_12_COLOUR + /* Set pixel palette (OBJ0 or OBJ1). */ + pixels[disp_x] |= (OF & OBJ_PALETTE); +#endif + } + + t1 = t1 >> 1; + t2 = t2 >> 1; + } + } + } + + gb->display.lcd_draw_line(gb, pixels, gb->hram_io[IO_LY]); +} +#endif + +/** + * Internal function used to step the CPU. + */ +void __gb_step_cpu(struct gb_s *gb) +{ + uint8_t opcode; + uint_fast16_t inst_cycles; + static const uint8_t op_cycles[0x100] = + { + /* *INDENT-OFF* */ + /*0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 4,12, 8, 8, 4, 4, 8, 4,20, 8, 8, 8, 4, 4, 8, 4, /* 0x00 */ + 4,12, 8, 8, 4, 4, 8, 4,12, 8, 8, 8, 4, 4, 8, 4, /* 0x10 */ + 8,12, 8, 8, 4, 4, 8, 4, 8, 8, 8, 8, 4, 4, 8, 4, /* 0x20 */ + 8,12, 8, 8,12,12,12, 4, 8, 8, 8, 8, 4, 4, 8, 4, /* 0x30 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x40 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x50 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x60 */ + 8, 8, 8, 8, 8, 8, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x70 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x80 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x90 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0xA0 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0xB0 */ + 8,12,12,16,12,16, 8,16, 8,16,12, 8,12,24, 8,16, /* 0xC0 */ + 8,12,12, 0,12,16, 8,16, 8,16,12, 0,12, 0, 8,16, /* 0xD0 */ + 12,12,8, 0, 0,16, 8,16,16, 4,16, 0, 0, 0, 8,16, /* 0xE0 */ + 12,12,8, 4, 0,16, 8,16,12, 8,16, 4, 0, 0, 8,16 /* 0xF0 */ + /* *INDENT-ON* */ + }; + static const uint_fast16_t TAC_CYCLES[4] = {1024, 16, 64, 256}; + + /* Handle interrupts */ + /* If gb_halt is positive, then an interrupt must have occurred by the + * time we reach here, because on HALT, we jump to the next interrupt + * immediately. */ + while(gb->gb_halt || (gb->gb_ime && + gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & ANY_INTR)) + { + gb->gb_halt = false; + + if(!gb->gb_ime) + break; + + /* Disable interrupts */ + gb->gb_ime = false; + + /* Push Program Counter */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + + /* Call interrupt handler if required. */ + if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & VBLANK_INTR) + { + gb->cpu_reg.pc.reg = VBLANK_INTR_ADDR; + gb->hram_io[IO_IF] ^= VBLANK_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & LCDC_INTR) + { + gb->cpu_reg.pc.reg = LCDC_INTR_ADDR; + gb->hram_io[IO_IF] ^= LCDC_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & TIMER_INTR) + { + gb->cpu_reg.pc.reg = TIMER_INTR_ADDR; + gb->hram_io[IO_IF] ^= TIMER_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & SERIAL_INTR) + { + gb->cpu_reg.pc.reg = SERIAL_INTR_ADDR; + gb->hram_io[IO_IF] ^= SERIAL_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & CONTROL_INTR) + { + gb->cpu_reg.pc.reg = CONTROL_INTR_ADDR; + gb->hram_io[IO_IF] ^= CONTROL_INTR; + } + + break; + } + + /* Obtain opcode */ + opcode = __gb_read(gb, gb->cpu_reg.pc.reg++); + inst_cycles = op_cycles[opcode]; + + /* Execute opcode */ + switch(opcode) + { + case 0x00: /* NOP */ + break; + + case 0x01: /* LD BC, imm */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x02: /* LD (BC), A */ + __gb_write(gb, gb->cpu_reg.bc.reg, gb->cpu_reg.a); + break; + + case 0x03: /* INC BC */ + gb->cpu_reg.bc.reg++; + break; + + case 0x04: /* INC B */ + PGB_INSTR_INC_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0x05: /* DEC B */ + PGB_INSTR_DEC_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0x06: /* LD B, imm */ + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x07: /* RLCA */ + gb->cpu_reg.a = (gb->cpu_reg.a << 1) | (gb->cpu_reg.a >> 7); + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.c = (gb->cpu_reg.a & 0x01); + break; + + case 0x08: /* LD (imm), SP */ + { + uint8_t h, l; + uint16_t temp; + l = __gb_read(gb, gb->cpu_reg.pc.reg++); + h = __gb_read(gb, gb->cpu_reg.pc.reg++); + temp = PEANUT_GB_U8_TO_U16(h,l); + __gb_write(gb, temp++, gb->cpu_reg.sp.bytes.p); + __gb_write(gb, temp, gb->cpu_reg.sp.bytes.s); + break; + } + + case 0x09: /* ADD HL, BC */ + { + uint_fast32_t temp = gb->cpu_reg.hl.reg + gb->cpu_reg.bc.reg; + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = + (temp ^ gb->cpu_reg.hl.reg ^ gb->cpu_reg.bc.reg) & 0x1000 ? 1 : 0; + gb->cpu_reg.f.f_bits.c = (temp & 0xFFFF0000) ? 1 : 0; + gb->cpu_reg.hl.reg = (temp & 0x0000FFFF); + break; + } + + case 0x0A: /* LD A, (BC) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.bc.reg); + break; + + case 0x0B: /* DEC BC */ + gb->cpu_reg.bc.reg--; + break; + + case 0x0C: /* INC C */ + PGB_INSTR_INC_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0x0D: /* DEC C */ + PGB_INSTR_DEC_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0x0E: /* LD C, imm */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x0F: /* RRCA */ + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.c = gb->cpu_reg.a & 0x01; + gb->cpu_reg.a = (gb->cpu_reg.a >> 1) | (gb->cpu_reg.a << 7); + break; + + case 0x10: /* STOP */ + //gb->gb_halt = true; + break; + + case 0x11: /* LD DE, imm */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x12: /* LD (DE), A */ + __gb_write(gb, gb->cpu_reg.de.reg, gb->cpu_reg.a); + break; + + case 0x13: /* INC DE */ + gb->cpu_reg.de.reg++; + break; + + case 0x14: /* INC D */ + PGB_INSTR_INC_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0x15: /* DEC D */ + PGB_INSTR_DEC_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0x16: /* LD D, imm */ + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x17: /* RLA */ + { + uint8_t temp = gb->cpu_reg.a; + gb->cpu_reg.a = (gb->cpu_reg.a << 1) | gb->cpu_reg.f.f_bits.c; + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.c = (temp >> 7) & 0x01; + break; + } + + case 0x18: /* JR imm */ + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + break; + } + + case 0x19: /* ADD HL, DE */ + { + uint_fast32_t temp = gb->cpu_reg.hl.reg + gb->cpu_reg.de.reg; + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = + (temp ^ gb->cpu_reg.hl.reg ^ gb->cpu_reg.de.reg) & 0x1000 ? 1 : 0; + gb->cpu_reg.f.f_bits.c = (temp & 0xFFFF0000) ? 1 : 0; + gb->cpu_reg.hl.reg = (temp & 0x0000FFFF); + break; + } + + case 0x1A: /* LD A, (DE) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.de.reg); + break; + + case 0x1B: /* DEC DE */ + gb->cpu_reg.de.reg--; + break; + + case 0x1C: /* INC E */ + PGB_INSTR_INC_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0x1D: /* DEC E */ + PGB_INSTR_DEC_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0x1E: /* LD E, imm */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x1F: /* RRA */ + { + uint8_t temp = gb->cpu_reg.a; + gb->cpu_reg.a = gb->cpu_reg.a >> 1 | (gb->cpu_reg.f.f_bits.c << 7); + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.c = temp & 0x1; + break; + } + + case 0x20: /* JR NZ, imm */ + if(!gb->cpu_reg.f.f_bits.z) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x21: /* LD HL, imm */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x22: /* LDI (HL), A */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.a); + gb->cpu_reg.hl.reg++; + break; + + case 0x23: /* INC HL */ + gb->cpu_reg.hl.reg++; + break; + + case 0x24: /* INC H */ + PGB_INSTR_INC_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0x25: /* DEC H */ + PGB_INSTR_DEC_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0x26: /* LD H, imm */ + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x27: /* DAA */ + { + /* The following is from SameBoy. MIT License. */ + int16_t a = gb->cpu_reg.a; + + if(gb->cpu_reg.f.f_bits.n) + { + if(gb->cpu_reg.f.f_bits.h) + a = (a - 0x06) & 0xFF; + + if(gb->cpu_reg.f.f_bits.c) + a -= 0x60; + } + else + { + if(gb->cpu_reg.f.f_bits.h || (a & 0x0F) > 9) + a += 0x06; + + if(gb->cpu_reg.f.f_bits.c || a > 0x9F) + a += 0x60; + } + + if((a & 0x100) == 0x100) + gb->cpu_reg.f.f_bits.c = 1; + + gb->cpu_reg.a = a; + gb->cpu_reg.f.f_bits.z = (gb->cpu_reg.a == 0); + gb->cpu_reg.f.f_bits.h = 0; + + break; + } + + case 0x28: /* JR Z, imm */ + if(gb->cpu_reg.f.f_bits.z) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x29: /* ADD HL, HL */ + { + gb->cpu_reg.f.f_bits.c = (gb->cpu_reg.hl.reg & 0x8000) > 0; + gb->cpu_reg.hl.reg <<= 1; + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = (gb->cpu_reg.hl.reg & 0x1000) > 0; + break; + } + + case 0x2A: /* LD A, (HL+) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.hl.reg++); + break; + + case 0x2B: /* DEC HL */ + gb->cpu_reg.hl.reg--; + break; + + case 0x2C: /* INC L */ + PGB_INSTR_INC_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0x2D: /* DEC L */ + PGB_INSTR_DEC_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0x2E: /* LD L, imm */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x2F: /* CPL */ + gb->cpu_reg.a = ~gb->cpu_reg.a; + gb->cpu_reg.f.f_bits.n = 1; + gb->cpu_reg.f.f_bits.h = 1; + break; + + case 0x30: /* JR NC, imm */ + if(!gb->cpu_reg.f.f_bits.c) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x31: /* LD SP, imm */ + gb->cpu_reg.sp.bytes.p = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.sp.bytes.s = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x32: /* LD (HL), A */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.a); + gb->cpu_reg.hl.reg--; + break; + + case 0x33: /* INC SP */ + gb->cpu_reg.sp.reg++; + break; + + case 0x34: /* INC (HL) */ + { + uint8_t temp = __gb_read(gb, gb->cpu_reg.hl.reg); + PGB_INSTR_INC_R8(temp); + __gb_write(gb, gb->cpu_reg.hl.reg, temp); + break; + } + + case 0x35: /* DEC (HL) */ + { + uint8_t temp = __gb_read(gb, gb->cpu_reg.hl.reg); + PGB_INSTR_DEC_R8(temp); + __gb_write(gb, gb->cpu_reg.hl.reg, temp); + break; + } + + case 0x36: /* LD (HL), imm */ + __gb_write(gb, gb->cpu_reg.hl.reg, __gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0x37: /* SCF */ + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = 0; + gb->cpu_reg.f.f_bits.c = 1; + break; + + case 0x38: /* JR C, imm */ + if(gb->cpu_reg.f.f_bits.c) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x39: /* ADD HL, SP */ + { + uint_fast32_t temp = gb->cpu_reg.hl.reg + gb->cpu_reg.sp.reg; + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = + ((gb->cpu_reg.hl.reg & 0xFFF) + (gb->cpu_reg.sp.reg & 0xFFF)) & 0x1000 ? 1 : 0; + gb->cpu_reg.f.f_bits.c = temp & 0x10000 ? 1 : 0; + gb->cpu_reg.hl.reg = (uint16_t)temp; + break; + } + + case 0x3A: /* LD A, (HL) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.hl.reg--); + break; + + case 0x3B: /* DEC SP */ + gb->cpu_reg.sp.reg--; + break; + + case 0x3C: /* INC A */ + PGB_INSTR_INC_R8(gb->cpu_reg.a); + break; + + case 0x3D: /* DEC A */ + PGB_INSTR_DEC_R8(gb->cpu_reg.a); + break; + + case 0x3E: /* LD A, imm */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x3F: /* CCF */ + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = 0; + gb->cpu_reg.f.f_bits.c = ~gb->cpu_reg.f.f_bits.c; + break; + + case 0x40: /* LD B, B */ + break; + + case 0x41: /* LD B, C */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.bc.bytes.c; + break; + + case 0x42: /* LD B, D */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.de.bytes.d; + break; + + case 0x43: /* LD B, E */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.de.bytes.e; + break; + + case 0x44: /* LD B, H */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.hl.bytes.h; + break; + + case 0x45: /* LD B, L */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.hl.bytes.l; + break; + + case 0x46: /* LD B, (HL) */ + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x47: /* LD B, A */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.a; + break; + + case 0x48: /* LD C, B */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.bc.bytes.b; + break; + + case 0x49: /* LD C, C */ + break; + + case 0x4A: /* LD C, D */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.de.bytes.d; + break; + + case 0x4B: /* LD C, E */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.de.bytes.e; + break; + + case 0x4C: /* LD C, H */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.hl.bytes.h; + break; + + case 0x4D: /* LD C, L */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.hl.bytes.l; + break; + + case 0x4E: /* LD C, (HL) */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x4F: /* LD C, A */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.a; + break; + + case 0x50: /* LD D, B */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.bc.bytes.b; + break; + + case 0x51: /* LD D, C */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.bc.bytes.c; + break; + + case 0x52: /* LD D, D */ + break; + + case 0x53: /* LD D, E */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.de.bytes.e; + break; + + case 0x54: /* LD D, H */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.hl.bytes.h; + break; + + case 0x55: /* LD D, L */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.hl.bytes.l; + break; + + case 0x56: /* LD D, (HL) */ + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x57: /* LD D, A */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.a; + break; + + case 0x58: /* LD E, B */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.bc.bytes.b; + break; + + case 0x59: /* LD E, C */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.bc.bytes.c; + break; + + case 0x5A: /* LD E, D */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.de.bytes.d; + break; + + case 0x5B: /* LD E, E */ + break; + + case 0x5C: /* LD E, H */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.hl.bytes.h; + break; + + case 0x5D: /* LD E, L */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.hl.bytes.l; + break; + + case 0x5E: /* LD E, (HL) */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x5F: /* LD E, A */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.a; + break; + + case 0x60: /* LD H, B */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.bc.bytes.b; + break; + + case 0x61: /* LD H, C */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.bc.bytes.c; + break; + + case 0x62: /* LD H, D */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.de.bytes.d; + break; + + case 0x63: /* LD H, E */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.de.bytes.e; + break; + + case 0x64: /* LD H, H */ + break; + + case 0x65: /* LD H, L */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.hl.bytes.l; + break; + + case 0x66: /* LD H, (HL) */ + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x67: /* LD H, A */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.a; + break; + + case 0x68: /* LD L, B */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.bc.bytes.b; + break; + + case 0x69: /* LD L, C */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.bc.bytes.c; + break; + + case 0x6A: /* LD L, D */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.de.bytes.d; + break; + + case 0x6B: /* LD L, E */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.de.bytes.e; + break; + + case 0x6C: /* LD L, H */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.hl.bytes.h; + break; + + case 0x6D: /* LD L, L */ + break; + + case 0x6E: /* LD L, (HL) */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x6F: /* LD L, A */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.a; + break; + + case 0x70: /* LD (HL), B */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.bc.bytes.b); + break; + + case 0x71: /* LD (HL), C */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.bc.bytes.c); + break; + + case 0x72: /* LD (HL), D */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.de.bytes.d); + break; + + case 0x73: /* LD (HL), E */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.de.bytes.e); + break; + + case 0x74: /* LD (HL), H */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.hl.bytes.h); + break; + + case 0x75: /* LD (HL), L */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.hl.bytes.l); + break; + + case 0x76: /* HALT */ + { + int_fast16_t halt_cycles = INT_FAST16_MAX; + + /* TODO: Emulate HALT bug? */ + gb->gb_halt = true; + + if(gb->hram_io[IO_SC] & SERIAL_SC_TX_START) + { + int serial_cycles = SERIAL_CYCLES - + gb->counter.serial_count; + + if(serial_cycles < halt_cycles) + halt_cycles = serial_cycles; + } + + if(gb->hram_io[IO_TAC] & IO_TAC_ENABLE_MASK) + { + int tac_cycles = TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK] - + gb->counter.tima_count; + + if(tac_cycles < halt_cycles) + halt_cycles = tac_cycles; + } + + if((gb->hram_io[IO_LCDC] & LCDC_ENABLE)) + { + int lcd_cycles; + + /* If LCD is in HBlank, calculate the number of cycles + * until the end of HBlank and the start of mode 2 or + * mode 1. */ + if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_HBLANK) + { + lcd_cycles = LCD_MODE0_HBLANK_MAX_DRUATION - gb->counter.lcd_count; + } + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_OAM_SCAN) + { + lcd_cycles = LCD_MODE3_LCD_DRAW_MIN_DURATION - gb->counter.lcd_count; + } + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_LCD_DRAW) + { + lcd_cycles = LCD_MODE0_HBLANK_MAX_DRUATION - gb->counter.lcd_count; + } + else + { + /* VBlank */ + lcd_cycles = LCD_LINE_CYCLES - gb->counter.lcd_count; + } + + if(lcd_cycles < halt_cycles) + halt_cycles = lcd_cycles; + } + + /* Some halt cycles may already be very high, so make sure we + * don't underflow here. */ + if(halt_cycles <= 0) + halt_cycles = 4; + + inst_cycles = (uint_fast16_t)halt_cycles; + break; + } + + case 0x77: /* LD (HL), A */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.a); + break; + + case 0x78: /* LD A, B */ + gb->cpu_reg.a = gb->cpu_reg.bc.bytes.b; + break; + + case 0x79: /* LD A, C */ + gb->cpu_reg.a = gb->cpu_reg.bc.bytes.c; + break; + + case 0x7A: /* LD A, D */ + gb->cpu_reg.a = gb->cpu_reg.de.bytes.d; + break; + + case 0x7B: /* LD A, E */ + gb->cpu_reg.a = gb->cpu_reg.de.bytes.e; + break; + + case 0x7C: /* LD A, H */ + gb->cpu_reg.a = gb->cpu_reg.hl.bytes.h; + break; + + case 0x7D: /* LD A, L */ + gb->cpu_reg.a = gb->cpu_reg.hl.bytes.l; + break; + + case 0x7E: /* LD A, (HL) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x7F: /* LD A, A */ + break; + + case 0x80: /* ADD A, B */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.b, 0); + break; + + case 0x81: /* ADD A, C */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.c, 0); + break; + + case 0x82: /* ADD A, D */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.d, 0); + break; + + case 0x83: /* ADD A, E */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.e, 0); + break; + + case 0x84: /* ADD A, H */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.h, 0); + break; + + case 0x85: /* ADD A, L */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.l, 0); + break; + + case 0x86: /* ADD A, (HL) */ + PGB_INSTR_ADC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), 0); + break; + + case 0x87: /* ADD A, A */ + PGB_INSTR_ADC_R8(gb->cpu_reg.a, 0); + break; + + case 0x88: /* ADC A, B */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.b, gb->cpu_reg.f.f_bits.c); + break; + + case 0x89: /* ADC A, C */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.c, gb->cpu_reg.f.f_bits.c); + break; + + case 0x8A: /* ADC A, D */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.d, gb->cpu_reg.f.f_bits.c); + break; + + case 0x8B: /* ADC A, E */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.e, gb->cpu_reg.f.f_bits.c); + break; + + case 0x8C: /* ADC A, H */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.h, gb->cpu_reg.f.f_bits.c); + break; + + case 0x8D: /* ADC A, L */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.l, gb->cpu_reg.f.f_bits.c); + break; + + case 0x8E: /* ADC A, (HL) */ + PGB_INSTR_ADC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), gb->cpu_reg.f.f_bits.c); + break; + + case 0x8F: /* ADC A, A */ + PGB_INSTR_ADC_R8(gb->cpu_reg.a, gb->cpu_reg.f.f_bits.c); + break; + + case 0x90: /* SUB B */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.b, 0); + break; + + case 0x91: /* SUB C */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.c, 0); + break; + + case 0x92: /* SUB D */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.d, 0); + break; + + case 0x93: /* SUB E */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.e, 0); + break; + + case 0x94: /* SUB H */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.h, 0); + break; + + case 0x95: /* SUB L */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.l, 0); + break; + + case 0x96: /* SUB (HL) */ + PGB_INSTR_SBC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), 0); + break; + + case 0x97: /* SUB A */ + gb->cpu_reg.a = 0; + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.z = 1; + gb->cpu_reg.f.f_bits.n = 1; + break; + + case 0x98: /* SBC A, B */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.b, gb->cpu_reg.f.f_bits.c); + break; + + case 0x99: /* SBC A, C */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.c, gb->cpu_reg.f.f_bits.c); + break; + + case 0x9A: /* SBC A, D */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.d, gb->cpu_reg.f.f_bits.c); + break; + + case 0x9B: /* SBC A, E */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.e, gb->cpu_reg.f.f_bits.c); + break; + + case 0x9C: /* SBC A, H */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.h, gb->cpu_reg.f.f_bits.c); + break; + + case 0x9D: /* SBC A, L */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.l, gb->cpu_reg.f.f_bits.c); + break; + + case 0x9E: /* SBC A, (HL) */ + PGB_INSTR_SBC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), gb->cpu_reg.f.f_bits.c); + break; + + case 0x9F: /* SBC A, A */ + gb->cpu_reg.a = gb->cpu_reg.f.f_bits.c ? 0xFF : 0x00; + gb->cpu_reg.f.f_bits.z = !gb->cpu_reg.f.f_bits.c; + gb->cpu_reg.f.f_bits.n = 1; + gb->cpu_reg.f.f_bits.h = gb->cpu_reg.f.f_bits.c; + break; + + case 0xA0: /* AND B */ + PGB_INSTR_AND_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xA1: /* AND C */ + PGB_INSTR_AND_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xA2: /* AND D */ + PGB_INSTR_AND_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xA3: /* AND E */ + PGB_INSTR_AND_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xA4: /* AND H */ + PGB_INSTR_AND_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xA5: /* AND L */ + PGB_INSTR_AND_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xA6: /* AND (HL) */ + PGB_INSTR_AND_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xA7: /* AND A */ + PGB_INSTR_AND_R8(gb->cpu_reg.a); + break; + + case 0xA8: /* XOR B */ + PGB_INSTR_XOR_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xA9: /* XOR C */ + PGB_INSTR_XOR_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xAA: /* XOR D */ + PGB_INSTR_XOR_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xAB: /* XOR E */ + PGB_INSTR_XOR_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xAC: /* XOR H */ + PGB_INSTR_XOR_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xAD: /* XOR L */ + PGB_INSTR_XOR_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xAE: /* XOR (HL) */ + PGB_INSTR_XOR_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xAF: /* XOR A */ + PGB_INSTR_XOR_R8(gb->cpu_reg.a); + break; + + case 0xB0: /* OR B */ + PGB_INSTR_OR_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xB1: /* OR C */ + PGB_INSTR_OR_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xB2: /* OR D */ + PGB_INSTR_OR_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xB3: /* OR E */ + PGB_INSTR_OR_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xB4: /* OR H */ + PGB_INSTR_OR_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xB5: /* OR L */ + PGB_INSTR_OR_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xB6: /* OR (HL) */ + PGB_INSTR_OR_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xB7: /* OR A */ + PGB_INSTR_OR_R8(gb->cpu_reg.a); + break; + + case 0xB8: /* CP B */ + PGB_INSTR_CP_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xB9: /* CP C */ + PGB_INSTR_CP_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xBA: /* CP D */ + PGB_INSTR_CP_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xBB: /* CP E */ + PGB_INSTR_CP_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xBC: /* CP H */ + PGB_INSTR_CP_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xBD: /* CP L */ + PGB_INSTR_CP_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xBE: /* CP (HL) */ + PGB_INSTR_CP_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xBF: /* CP A */ + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.z = 1; + gb->cpu_reg.f.f_bits.n = 1; + break; + + case 0xC0: /* RET NZ */ + if(!gb->cpu_reg.f.f_bits.z) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + + break; + + case 0xC1: /* POP BC */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + + case 0xC2: /* JP NZ, imm */ + if(!gb->cpu_reg.f.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xC3: /* JP imm */ + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + break; + } + + case 0xC4: /* CALL NZ imm */ + if(!gb->cpu_reg.f.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xC5: /* PUSH BC */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.bc.bytes.b); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.bc.bytes.c); + break; + + case 0xC6: /* ADD A, imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_ADC_R8(val, 0); + break; + } + + case 0xC7: /* RST 0x0000 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0000; + break; + + case 0xC8: /* RET Z */ + if(gb->cpu_reg.f.f_bits.z) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + break; + + case 0xC9: /* RET */ + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + } + + case 0xCA: /* JP Z, imm */ + if(gb->cpu_reg.f.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xCB: /* CB INST */ + inst_cycles = __gb_execute_cb(gb); + break; + + case 0xCC: /* CALL Z, imm */ + if(gb->cpu_reg.f.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xCD: /* CALL imm */ + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + } + break; + + case 0xCE: /* ADC A, imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_ADC_R8(val, gb->cpu_reg.f.f_bits.c); + break; + } + + case 0xCF: /* RST 0x0008 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0008; + break; + + case 0xD0: /* RET NC */ + if(!gb->cpu_reg.f.f_bits.c) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + + break; + + case 0xD1: /* POP DE */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + + case 0xD2: /* JP NC, imm */ + if(!gb->cpu_reg.f.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xD4: /* CALL NC, imm */ + if(!gb->cpu_reg.f.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xD5: /* PUSH DE */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.de.bytes.d); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.de.bytes.e); + break; + + case 0xD6: /* SUB imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + uint16_t temp = gb->cpu_reg.a - val; + gb->cpu_reg.f.f_bits.z = ((temp & 0xFF) == 0x00); + gb->cpu_reg.f.f_bits.n = 1; + gb->cpu_reg.f.f_bits.h = + (gb->cpu_reg.a ^ val ^ temp) & 0x10 ? 1 : 0; + gb->cpu_reg.f.f_bits.c = (temp & 0xFF00) ? 1 : 0; + gb->cpu_reg.a = (temp & 0xFF); + break; + } + + case 0xD7: /* RST 0x0010 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0010; + break; + + case 0xD8: /* RET C */ + if(gb->cpu_reg.f.f_bits.c) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + + break; + + case 0xD9: /* RETI */ + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->gb_ime = true; + } + break; + + case 0xDA: /* JP C, imm */ + if(gb->cpu_reg.f.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xDC: /* CALL C, imm */ + if(gb->cpu_reg.f.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xDE: /* SBC A, imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_SBC_R8(val, gb->cpu_reg.f.f_bits.c); + break; + } + + case 0xDF: /* RST 0x0018 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0018; + break; + + case 0xE0: /* LD (0xFF00+imm), A */ + __gb_write(gb, 0xFF00 | __gb_read(gb, gb->cpu_reg.pc.reg++), + gb->cpu_reg.a); + break; + + case 0xE1: /* POP HL */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + + case 0xE2: /* LD (C), A */ + __gb_write(gb, 0xFF00 | gb->cpu_reg.bc.bytes.c, gb->cpu_reg.a); + break; + + case 0xE5: /* PUSH HL */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.hl.bytes.h); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.hl.bytes.l); + break; + + case 0xE6: /* AND imm */ + { + uint8_t temp = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_AND_R8(temp); + break; + } + + case 0xE7: /* RST 0x0020 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0020; + break; + + case 0xE8: /* ADD SP, imm */ + { + int8_t offset = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.sp.reg & 0xF) + (offset & 0xF) > 0xF) ? 1 : 0; + gb->cpu_reg.f.f_bits.c = ((gb->cpu_reg.sp.reg & 0xFF) + (offset & 0xFF) > 0xFF); + gb->cpu_reg.sp.reg += offset; + break; + } + + case 0xE9: /* JP (HL) */ + gb->cpu_reg.pc.reg = gb->cpu_reg.hl.reg; + break; + + case 0xEA: /* LD (imm), A */ + { + uint8_t h, l; + uint16_t addr; + l = __gb_read(gb, gb->cpu_reg.pc.reg++); + h = __gb_read(gb, gb->cpu_reg.pc.reg++); + addr = PEANUT_GB_U8_TO_U16(h, l); + __gb_write(gb, addr, gb->cpu_reg.a); + break; + } + + case 0xEE: /* XOR imm */ + PGB_INSTR_XOR_R8(__gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0xEF: /* RST 0x0028 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0028; + break; + + case 0xF0: /* LD A, (0xFF00+imm) */ + gb->cpu_reg.a = + __gb_read(gb, 0xFF00 | __gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0xF1: /* POP AF */ + { + uint8_t temp_8 = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.f.f_bits.z = (temp_8 >> 7) & 1; + gb->cpu_reg.f.f_bits.n = (temp_8 >> 6) & 1; + gb->cpu_reg.f.f_bits.h = (temp_8 >> 5) & 1; + gb->cpu_reg.f.f_bits.c = (temp_8 >> 4) & 1; + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + } + + case 0xF2: /* LD A, (C) */ + gb->cpu_reg.a = __gb_read(gb, 0xFF00 | gb->cpu_reg.bc.bytes.c); + break; + + case 0xF3: /* DI */ + gb->gb_ime = false; + break; + + case 0xF5: /* PUSH AF */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.a); + __gb_write(gb, --gb->cpu_reg.sp.reg, + gb->cpu_reg.f.f_bits.z << 7 | gb->cpu_reg.f.f_bits.n << 6 | + gb->cpu_reg.f.f_bits.h << 5 | gb->cpu_reg.f.f_bits.c << 4); + break; + + case 0xF6: /* OR imm */ + PGB_INSTR_OR_R8(__gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0xF7: /* PUSH AF */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0030; + break; + + case 0xF8: /* LD HL, SP+/-imm */ + { + /* Taken from SameBoy, which is released under MIT Licence. */ + int8_t offset = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.hl.reg = gb->cpu_reg.sp.reg + offset; + gb->cpu_reg.f.reg = 0; + gb->cpu_reg.f.f_bits.h = ((gb->cpu_reg.sp.reg & 0xF) + (offset & 0xF) > 0xF) ? 1 : 0; + gb->cpu_reg.f.f_bits.c = ((gb->cpu_reg.sp.reg & 0xFF) + (offset & 0xFF) > 0xFF) ? 1 : 0; + break; + } + + case 0xF9: /* LD SP, HL */ + gb->cpu_reg.sp.reg = gb->cpu_reg.hl.reg; + break; + + case 0xFA: /* LD A, (imm) */ + { + uint8_t h, l; + uint16_t addr; + l = __gb_read(gb, gb->cpu_reg.pc.reg++); + h = __gb_read(gb, gb->cpu_reg.pc.reg++); + addr = PEANUT_GB_U8_TO_U16(h, l); + gb->cpu_reg.a = __gb_read(gb, addr); + break; + } + + case 0xFB: /* EI */ + gb->gb_ime = true; + break; + + case 0xFE: /* CP imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_CP_R8(val); + break; + } + + case 0xFF: /* RST 0x0038 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0038; + break; + + default: + /* Return address where invalid opcode that was read. */ + (gb->gb_error)(gb, GB_INVALID_OPCODE, gb->cpu_reg.pc.reg - 1); + PGB_UNREACHABLE(); + } + + do + { + /* DIV register timing */ + gb->counter.div_count += inst_cycles; + while(gb->counter.div_count >= DIV_CYCLES) + { + gb->hram_io[IO_DIV]++; + gb->counter.div_count -= DIV_CYCLES; + } + + /* Check for RTC tick. */ + if(gb->mbc == 3 && (gb->rtc_real.reg.high & 0x40) == 0) + { + gb->counter.rtc_count += inst_cycles; + while(PGB_UNLIKELY(gb->counter.rtc_count >= RTC_CYCLES)) + { + gb->counter.rtc_count -= RTC_CYCLES; + + /* Detect invalid rollover. */ + if(PGB_UNLIKELY(gb->rtc_real.reg.sec == 63)) + { + gb->rtc_real.reg.sec = 0; + continue; + } + + if(++gb->rtc_real.reg.sec != 60) + continue; + + gb->rtc_real.reg.sec = 0; + if(gb->rtc_real.reg.min == 63) + { + gb->rtc_real.reg.min = 0; + continue; + } + if(++gb->rtc_real.reg.min != 60) + continue; + + gb->rtc_real.reg.min = 0; + if(gb->rtc_real.reg.hour == 31) + { + gb->rtc_real.reg.hour = 0; + continue; + } + if(++gb->rtc_real.reg.hour != 24) + continue; + + gb->rtc_real.reg.hour = 0; + if(++gb->rtc_real.reg.yday != 0) + continue; + + if(gb->rtc_real.reg.high & 1) /* Bit 8 of days*/ + gb->rtc_real.reg.high |= 0x80; /* Overflow bit */ + + gb->rtc_real.reg.high ^= 1; + } + } + + /* Check serial transmission. */ + if(gb->hram_io[IO_SC] & SERIAL_SC_TX_START) + { + /* If new transfer, call TX function. */ + if(gb->counter.serial_count == 0 && + gb->gb_serial_tx != NULL) + (gb->gb_serial_tx)(gb, gb->hram_io[IO_SB]); + + gb->counter.serial_count += inst_cycles; + + /* If it's time to receive byte, call RX function. */ + if(gb->counter.serial_count >= SERIAL_CYCLES) + { + /* If RX can be done, do it. */ + /* If RX failed, do not change SB if using external + * clock, or set to 0xFF if using internal clock. */ + uint8_t rx; +#ifdef PGB_SERIAL_WAIT + enum gb_serial_rx_ret_e rr = gb->gb_serial_rx != NULL ? gb->gb_serial_rx(gb, &rx) : GB_SERIAL_RX_NO_CONNECTION; + if(rr == GB_SERIAL_RX_WAIT) + { + /* Paramix: keep the transfer just before its end (asked again after the next + * instruction; a HALT waits 4 cycles at a time), nothing changes yet */ + gb->counter.serial_count = SERIAL_CYCLES - 4; + } + else if(rr == GB_SERIAL_RX_SUCCESS) +#else + if(gb->gb_serial_rx != NULL && + (gb->gb_serial_rx(gb, &rx) == + GB_SERIAL_RX_SUCCESS)) +#endif + { + gb->hram_io[IO_SB] = rx; + + /* Inform game of serial TX/RX completion. */ + gb->hram_io[IO_SC] &= 0x01; + gb->hram_io[IO_IF] |= SERIAL_INTR; + } + else if(gb->hram_io[IO_SC] & SERIAL_SC_CLOCK_SRC) + { + /* If using internal clock, and console is not + * attached to any external peripheral, shifted + * bits are replaced with logic 1. */ + gb->hram_io[IO_SB] = 0xFF; + + /* Inform game of serial TX/RX completion. */ + gb->hram_io[IO_SC] &= 0x01; + gb->hram_io[IO_IF] |= SERIAL_INTR; + } + else + { + /* If using external clock, and console is not + * attached to any external peripheral, bits are + * not shifted, so SB is not modified. */ + } + +#ifdef PGB_SERIAL_WAIT + if(rr != GB_SERIAL_RX_WAIT) +#endif + gb->counter.serial_count = 0; + } + } + + /* TIMA register timing */ + /* TODO: Change tac_enable to struct of TAC timer control bits. */ + if(gb->hram_io[IO_TAC] & IO_TAC_ENABLE_MASK) + { + gb->counter.tima_count += inst_cycles; + + while(gb->counter.tima_count >= + TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK]) + { + gb->counter.tima_count -= + TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK]; + + if(++gb->hram_io[IO_TIMA] == 0) + { + gb->hram_io[IO_IF] |= TIMER_INTR; + /* On overflow, set TMA to TIMA. */ + gb->hram_io[IO_TIMA] = gb->hram_io[IO_TMA]; + } + } + } + + /* If LCD is off, don't update LCD state or increase the LCD + * ticks. Instead, keep track of the amount of time that is + * being passed. */ + if(!(gb->hram_io[IO_LCDC] & LCDC_ENABLE)) + { + gb->counter.lcd_off_count += inst_cycles; + if(gb->counter.lcd_off_count >= LCD_FRAME_CYCLES) + { + gb->counter.lcd_off_count -= LCD_FRAME_CYCLES; + gb->gb_frame = true; + } + continue; + } + + /* LCD Timing */ + gb->counter.lcd_count += inst_cycles; + + /* New Scanline. HBlank -> VBlank or OAM Scan */ + if(gb->counter.lcd_count >= LCD_LINE_CYCLES) + { + gb->counter.lcd_count -= LCD_LINE_CYCLES; + + /* Next line */ + gb->hram_io[IO_LY] = gb->hram_io[IO_LY] + 1; + if (gb->hram_io[IO_LY] == LCD_VERT_LINES) + gb->hram_io[IO_LY] = 0; + + /* LYC Update */ + if(gb->hram_io[IO_LY] == gb->hram_io[IO_LYC]) + { + gb->hram_io[IO_STAT] |= STAT_LYC_COINC; + + if(gb->hram_io[IO_STAT] & STAT_LYC_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + } + else + gb->hram_io[IO_STAT] &= 0xFB; + + /* Check if LCD should be in Mode 1 (VBLANK) state */ + if(gb->hram_io[IO_LY] == LCD_HEIGHT) + { + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_VBLANK; + gb->gb_frame = true; + gb->hram_io[IO_IF] |= VBLANK_INTR; + gb->lcd_blank = false; + + if(gb->hram_io[IO_STAT] & STAT_MODE_1_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + +#if ENABLE_LCD + /* If frame skip is activated, check if we need to draw + * the frame or skip it. */ + if(gb->direct.frame_skip) + { + gb->display.frame_skip_count = + !gb->display.frame_skip_count; + } + + /* If interlaced is activated, change which lines get + * updated. Also, only update lines on frames that are + * actually drawn when frame skip is enabled. */ + if(gb->direct.interlace && + (!gb->direct.frame_skip || + gb->display.frame_skip_count)) + { + gb->display.interlace_count = + !gb->display.interlace_count; + } +#endif + /* If halted forever, then return on VBLANK. */ + if(gb->gb_halt && !gb->hram_io[IO_IE]) + break; + } + /* Start of normal Line (not in VBLANK) */ + else if(gb->hram_io[IO_LY] < LCD_HEIGHT) + { + if(gb->hram_io[IO_LY] == 0) + { + /* Clear Screen */ + gb->display.WY = gb->hram_io[IO_WY]; + gb->display.window_clear = 0; + } + + /* OAM Search occurs at the start of the line. */ + gb->hram_io[IO_STAT] = (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_OAM_SCAN; + gb->counter.lcd_count = 0; + + if(gb->hram_io[IO_STAT] & STAT_MODE_2_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + + /* If halted immediately jump to next LCD mode. + * From OAM Search to LCD Draw. */ + //if(gb->counter.lcd_count < LCD_MODE2_OAM_SCAN_END) + // inst_cycles = LCD_MODE2_OAM_SCAN_END - gb->counter.lcd_count; + inst_cycles = LCD_MODE2_OAM_SCAN_DURATION; + } + } + /* Go from Mode 3 (LCD Draw) to Mode 0 (HBLANK). */ + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_LCD_DRAW && + gb->counter.lcd_count >= LCD_MODE3_LCD_DRAW_END) + { + gb->hram_io[IO_STAT] = (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_HBLANK; + + if(gb->hram_io[IO_STAT] & STAT_MODE_0_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + + /* If halted immediately, jump from OAM Scan to LCD Draw. */ + if (gb->counter.lcd_count < LCD_MODE0_HBLANK_MAX_DRUATION) + inst_cycles = LCD_MODE0_HBLANK_MAX_DRUATION - gb->counter.lcd_count; + } + /* Go from Mode 2 (OAM Scan) to Mode 3 (LCD Draw). */ + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_OAM_SCAN && + gb->counter.lcd_count >= LCD_MODE2_OAM_SCAN_END) + { + gb->hram_io[IO_STAT] = (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_LCD_DRAW; +#if ENABLE_LCD + if(!gb->lcd_blank) + __gb_draw_line(gb); +#endif + /* If halted immediately jump to next LCD mode. */ + if (gb->counter.lcd_count < LCD_MODE3_LCD_DRAW_MIN_DURATION) + inst_cycles = LCD_MODE3_LCD_DRAW_MIN_DURATION - gb->counter.lcd_count; + } + } while(gb->gb_halt && (gb->hram_io[IO_IF] & gb->hram_io[IO_IE]) == 0); + /* If halted, loop until an interrupt occurs. */ +} + +void gb_run_frame(struct gb_s *gb) +{ + gb->gb_frame = false; + + while(!gb->gb_frame) + __gb_step_cpu(gb); +} + +int gb_get_save_size_s(struct gb_s *gb, size_t *ram_size) +{ + const uint_fast16_t ram_size_location = 0x0149; + const uint_fast32_t ram_sizes[] = + { + /* 0, 2KiB, 8KiB, 32KiB, 128KiB, 64KiB */ + 0x00, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 + }; + uint8_t ram_size_code = gb->gb_rom_read(gb, ram_size_location); + + /* MBC2 always has 512 half-bytes of cart RAM. + * This assumes that only the lower nibble of each byte is used; the + * nibbles are not packed. */ + if(gb->mbc == 2) + { + *ram_size = 0x200; + return 0; + } + + /* Return -1 on invalid or unsupported RAM size. */ + if(ram_size_code >= PEANUT_GB_ARRAYSIZE(ram_sizes)) + return -1; + + *ram_size = ram_sizes[ram_size_code]; + return 0; +} + +PGB_DEPRECATED("Does not return error code. Use gb_get_save_size_s instead.") +uint_fast32_t gb_get_save_size(struct gb_s *gb) +{ + const uint_fast16_t ram_size_location = 0x0149; + const uint_fast32_t ram_sizes[] = + { + /* 0, 2KiB, 8KiB, 32KiB, 128KiB, 64KiB */ + 0x00, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 + }; + uint8_t ram_size_code = gb->gb_rom_read(gb, ram_size_location); + + /* MBC2 always has 512 half-bytes of cart RAM. + * This assumes that only the lower nibble of each byte is used; the + * nibbles are not packed. */ + if(gb->mbc == 2) + return 0x200; + + /* Return 0 on invalid or unsupported RAM size. */ + if(ram_size_code >= PEANUT_GB_ARRAYSIZE(ram_sizes)) + return 0; + + return ram_sizes[ram_size_code]; +} + +void gb_init_serial(struct gb_s *gb, + void (*gb_serial_tx)(struct gb_s*, const uint8_t), + enum gb_serial_rx_ret_e (*gb_serial_rx)(struct gb_s*, + uint8_t*)) +{ + gb->gb_serial_tx = gb_serial_tx; + gb->gb_serial_rx = gb_serial_rx; +} + +uint8_t gb_colour_hash(struct gb_s *gb) +{ +#define ROM_TITLE_START_ADDR 0x0134 +#define ROM_TITLE_END_ADDR 0x0143 + + uint8_t x = 0; + uint16_t i; + + for(i = ROM_TITLE_START_ADDR; i <= ROM_TITLE_END_ADDR; i++) + x += gb->gb_rom_read(gb, i); + + return x; +} + +/** + * Resets the context, and initialises startup values for a DMG console. + */ +void gb_reset(struct gb_s *gb) +{ + gb->gb_halt = false; + gb->gb_ime = true; + + /* Initialise MBC values. */ + gb->selected_rom_bank = 1; + gb->cart_ram_bank = 0; + gb->enable_cart_ram = 0; + gb->cart_mode_select = 0; + PGB_BANKSET(gb); + + /* Use values as though the boot ROM was already executed. */ + if(gb->gb_bootrom_read == NULL) + { + uint8_t hdr_chk; + hdr_chk = gb->gb_rom_read(gb, ROM_HEADER_CHECKSUM_LOC) != 0; + + gb->cpu_reg.a = 0x01; + gb->cpu_reg.f.f_bits.z = 1; + gb->cpu_reg.f.f_bits.n = 0; + gb->cpu_reg.f.f_bits.h = hdr_chk; + gb->cpu_reg.f.f_bits.c = hdr_chk; + gb->cpu_reg.bc.reg = 0x0013; + gb->cpu_reg.de.reg = 0x00D8; + gb->cpu_reg.hl.reg = 0x014D; + gb->cpu_reg.sp.reg = 0xFFFE; + gb->cpu_reg.pc.reg = 0x0100; + + gb->hram_io[IO_DIV ] = 0xAB; + gb->hram_io[IO_LCDC] = 0x91; + gb->hram_io[IO_STAT] = 0x85; + gb->hram_io[IO_BOOT] = 0x01; + + __gb_write(gb, 0xFF26, 0xF1); + + memset(gb->vram, 0x00, VRAM_SIZE); + } + else + { + /* Set value as though the console was just switched on. + * CPU registers are uninitialised. */ + gb->cpu_reg.pc.reg = 0x0000; + gb->hram_io[IO_DIV ] = 0x00; + gb->hram_io[IO_LCDC] = 0x00; + gb->hram_io[IO_STAT] = 0x84; + gb->hram_io[IO_BOOT] = 0x00; + } + + gb->counter.lcd_count = 0; + gb->counter.div_count = 0; + gb->counter.tima_count = 0; + gb->counter.serial_count = 0; + gb->counter.rtc_count = 0; + gb->counter.lcd_off_count = 0; + + gb->direct.joypad = 0xFF; + gb->hram_io[IO_JOYP] = 0xCF; + gb->hram_io[IO_SB ] = 0x00; + gb->hram_io[IO_SC ] = 0x7E; + /* DIV */ + gb->hram_io[IO_TIMA] = 0x00; + gb->hram_io[IO_TMA ] = 0x00; + gb->hram_io[IO_TAC ] = 0xF8; + gb->hram_io[IO_IF ] = 0xE1; + + /* LCDC */ + /* STAT */ + gb->hram_io[IO_SCY ] = 0x00; + gb->hram_io[IO_SCX ] = 0x00; + gb->hram_io[IO_LY ] = 0x00; + gb->hram_io[IO_LYC ] = 0x00; + __gb_write(gb, 0xFF47, 0xFC); // BGP + __gb_write(gb, 0xFF48, 0xFF); // OBJP0 + __gb_write(gb, 0xFF49, 0xFF); // OBJP1 + gb->hram_io[IO_WY] = 0x00; + gb->hram_io[IO_WX] = 0x00; + gb->hram_io[IO_IE] = 0x00; + gb->hram_io[IO_IF] = 0xE1; +} + +enum gb_init_error_e gb_init(struct gb_s *gb, + uint8_t (*gb_rom_read)(struct gb_s*, const uint_fast32_t), + uint8_t (*gb_cart_ram_read)(struct gb_s*, const uint_fast32_t), + void (*gb_cart_ram_write)(struct gb_s*, const uint_fast32_t, const uint8_t), + void (*gb_error)(struct gb_s*, const enum gb_error_e, const uint16_t), + void *priv) +{ + const uint16_t mbc_location = 0x0147; + const uint16_t bank_count_location = 0x0148; + const uint16_t ram_size_location = 0x0149; + /** + * Table for cartridge type (MBC). -1 if invalid. + * TODO: MMM01 is untested. + * TODO: MBC6 is untested. + * TODO: MBC7 is unsupported. + * TODO: POCKET CAMERA is unsupported. + * TODO: BANDAI TAMA5 is unsupported. + * TODO: HuC3 is unsupported. + * TODO: HuC1 is unsupported. + **/ + const int8_t cart_mbc[] = + { + 0, 1, 1, 1, -1, 2, 2, -1, 0, 0, -1, 0, 0, 0, -1, 3, + 3, 3, 3, 3, -1, -1, -1, -1, -1, 5, 5, 5, 5, 5, 5, -1 + }; + /* Whether cart has RAM. */ + const uint8_t cart_ram[] = + { + 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, + 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 + }; + /* How large the ROM is in banks of 16 KiB. */ + const uint16_t num_rom_banks_mask[] = + { + 2, 4, 8, 16, 32, 64, 128, 256, 512 + }; + /* How large the cart RAM is in banks of 8 KiB. Code $01 is unused, but + * some early homebrew ROMs supposedly may use this value. */ + const uint8_t num_ram_banks[] = { 0, 1, 1, 4, 16, 8 }; + + gb->gb_rom_read = gb_rom_read; + gb->gb_cart_ram_read = gb_cart_ram_read; + gb->gb_cart_ram_write = gb_cart_ram_write; + gb->gb_error = gb_error; + gb->direct.priv = priv; + + /* Initialise serial transfer function to NULL. If the front-end does + * not provide serial support, Peanut-GB will emulate no cable connected + * automatically. */ + gb->gb_serial_tx = NULL; + gb->gb_serial_rx = NULL; + + gb->gb_bootrom_read = NULL; + + /* Check valid ROM using checksum value. */ + { + uint8_t x = 0; + uint16_t i; + + for(i = 0x0134; i <= 0x014C; i++) + x = x - gb->gb_rom_read(gb, i) - 1; + + if(x != gb->gb_rom_read(gb, ROM_HEADER_CHECKSUM_LOC)) + return GB_INIT_INVALID_CHECKSUM; + } + + /* Check if cartridge type is supported, and set MBC type. */ + { + const uint8_t mbc_value = gb->gb_rom_read(gb, mbc_location); + + if(mbc_value > sizeof(cart_mbc) - 1 || + (gb->mbc = cart_mbc[mbc_value]) == -1) + return GB_INIT_CARTRIDGE_UNSUPPORTED; + } + + gb->num_rom_banks_mask = num_rom_banks_mask[gb->gb_rom_read(gb, bank_count_location)] - 1; + gb->cart_ram = cart_ram[gb->gb_rom_read(gb, mbc_location)]; + gb->num_ram_banks = num_ram_banks[gb->gb_rom_read(gb, ram_size_location)]; + + /* If the ROM says that it support RAM, but has 0 RAM banks, then + * disable RAM reads from the cartridge. */ + if(gb->cart_ram == 0 || gb->num_ram_banks == 0) + { + gb->cart_ram = 0; + gb->num_ram_banks = 0; + } + + /* If MBC3 and number of ROM or RAM banks are larger than 128 or 8, + * respectively, then select MBC3O mode. */ + if(gb->mbc == 3) + gb->cart_is_mbc3O = gb->num_rom_banks_mask > 128 || gb->num_ram_banks > 4; + + /* Note that MBC2 will appear to have no RAM banks, but it actually + * always has 512 half-bytes of RAM. Hence, gb->num_ram_banks must be + * ignored for MBC2. */ + + gb->lcd_blank = false; + gb->display.lcd_draw_line = NULL; + + gb_reset(gb); + + return GB_INIT_NO_ERROR; +} + +const char* gb_get_rom_name(struct gb_s* gb, char *title_str) +{ + uint_fast16_t title_loc = 0x134; + /* End of title may be 0x13E for newer games. */ + const uint_fast16_t title_end = 0x143; + const char* title_start = title_str; + + for(; title_loc <= title_end; title_loc++) + { + const char title_char = gb->gb_rom_read(gb, title_loc); + + if(title_char >= ' ' && title_char <= '_') + { + *title_str = title_char; + title_str++; + } + else + break; + } + + *title_str = '\0'; + return title_start; +} + +#if ENABLE_LCD +void gb_init_lcd(struct gb_s *gb, + void (*lcd_draw_line)(struct gb_s *gb, + const uint8_t *pixels, + const uint_fast8_t line)) +{ + gb->display.lcd_draw_line = lcd_draw_line; + + gb->direct.interlace = false; + gb->display.interlace_count = false; + gb->direct.frame_skip = false; + gb->display.frame_skip_count = false; + + gb->display.window_clear = 0; + gb->display.WY = 0; + + return; +} +#endif + +void gb_set_bootrom(struct gb_s *gb, + uint8_t (*gb_bootrom_read)(struct gb_s*, const uint_fast16_t)) +{ + gb->gb_bootrom_read = gb_bootrom_read; +} + +/** + * Deprecated. Will be removed in the next major version. + */ +PGB_DEPRECATED("RTC is now ticked internally; this function has no effect") +void gb_tick_rtc(struct gb_s *gb) +{ + (void) gb; + return; +} + +void gb_set_rtc(struct gb_s *gb, const struct tm * const time) +{ + gb->rtc_real.bytes[0] = time->tm_sec; + gb->rtc_real.bytes[1] = time->tm_min; + gb->rtc_real.bytes[2] = time->tm_hour; + gb->rtc_real.bytes[3] = time->tm_yday & 0xFF; /* Low 8 bits of day counter. */ + gb->rtc_real.bytes[4] = time->tm_yday >> 8; /* High 1 bit of day counter. */ +} +#endif // PEANUT_GB_HEADER_ONLY + +/** Function prototypes: Required functions **/ +/** + * Initialises the emulator context to a known state. Call this before calling + * any other peanut-gb function. + * To reset the emulator, you can call gb_reset() instead. + * + * \param gb Allocated emulator context. Must not be NULL. + * \param gb_rom_read Pointer to function that reads ROM data. ROM banking is + * already handled by Peanut-GB. Must not be NULL. + * \param gb_cart_ram_read Pointer to function that reads Cart RAM. Must not be + * NULL. + * \param gb_cart_ram_write Pointer to function to writes to Cart RAM. Must not + * be NULL. + * \param gb_error Pointer to function that is called when an unrecoverable + * error occurs. Must not be NULL. Returning from this + * function is undefined and will result in SIGABRT. + * \param priv Private data that is stored within the emulator context. Set to + * NULL if unused. + * \returns 0 on success or an enum that describes the error. + */ +enum gb_init_error_e gb_init(struct gb_s *gb, + uint8_t (*gb_rom_read)(struct gb_s*, const uint_fast32_t), + uint8_t (*gb_cart_ram_read)(struct gb_s*, const uint_fast32_t), + void (*gb_cart_ram_write)(struct gb_s*, const uint_fast32_t, const uint8_t), + void (*gb_error)(struct gb_s*, const enum gb_error_e, const uint16_t), + void *priv); + +/** + * Executes the emulator and runs for the duration of time equal to one frame. + * + * \param An initialised emulator context. Must not be NULL. + */ +void gb_run_frame(struct gb_s *gb); + +/** + * Internal function used to step the CPU. Used mainly for testing. + * Use gb_run_frame() instead. + * + * \param An initialised emulator context. Must not be NULL. + */ +void __gb_step_cpu(struct gb_s *gb); + +/** Function prototypes: Optional Functions **/ +/** + * Reset the emulator, like turning the Game Boy off and on again. + * This function can be called at any time. + * + * \param An initialised emulator context. Must not be NULL. + */ +void gb_reset(struct gb_s *gb); + +/** + * Initialises the display context of the emulator. Only available when + * ENABLE_LCD is defined to a non-zero value. + * The pixel data sent to lcd_draw_line comes with both shade and layer data. + * The first two least significant bits are the shade data (black, dark, light, + * white). Bits 4 and 5 are layer data (OBJ0, OBJ1, BG), which can be used to + * add more colours to the game in the same way that the Game Boy Color does to + * older Game Boy games. + * This function can be called at any time. + * + * \param gb An initialised emulator context. Must not be NULL. + * \param lcd_draw_line Pointer to function that draws the 2-bit pixel data on the line + * "line". Must not be NULL. + */ +#if ENABLE_LCD +void gb_init_lcd(struct gb_s *gb, + void (*lcd_draw_line)(struct gb_s *gb, + const uint8_t *pixels, + const uint_fast8_t line)); +#endif + +/** + * Initialises the serial connection of the emulator. This function is optional, + * and if not called, the emulator will assume that no link cable is connected + * to the game. + * + * \param gb An initialised emulator context. Must not be NULL. + * \param gb_serial_tx Pointer to function that transmits a byte of data over + * the serial connection. Must not be NULL. + * \param gb_serial_rx Pointer to function that receives a byte of data over the + * serial connection. If no byte is received, + * return GB_SERIAL_RX_NO_CONNECTION. Must not be NULL. + */ +void gb_init_serial(struct gb_s *gb, + void (*gb_serial_tx)(struct gb_s*, const uint8_t), + enum gb_serial_rx_ret_e (*gb_serial_rx)(struct gb_s*, + uint8_t*)); + +/** + * Obtains the save size of the game (size of the Cart RAM). Required by the + * frontend to allocate enough memory for the Cart RAM. + * + * \param gb An initialised emulator context. Must not be NULL. + * \param ram_size Pointer to size_t variable that will be set to the size of + * the Cart RAM in bytes. Must not be NULL. + * If the Cart RAM is not battery backed, this will be set to 0. + * If the Cart RAM size is invalid or unknown, this will not be + * set. + * \returns 0 on success, or -1 if the RAM size is invalid or unknown. + */ +int gb_get_save_size_s(struct gb_s *gb, size_t *ram_size); + +/** + * Deprecated. Use gb_get_save_size_s() instead. + * Obtains the save size of the game (size of the Cart RAM). Required by the + * frontend to allocate enough memory for the Cart RAM. + * + * \param gb An initialised emulator context. Must not be NULL. + * \returns Size of the Cart RAM in bytes. 0 if Cartridge has not battery + * backed RAM. + * 0 is also returned on invalid or unknown RAM size. + */ +uint_fast32_t gb_get_save_size(struct gb_s *gb); + +/** + * Calculates and returns a hash of the game header in the same way the Game + * Boy Color does for colourising old Game Boy games. The frontend can use this + * hash to automatically set a colour palette. + * + * \param gb An initialised emulator context. Must not be NULL. + * \returns Hash of the game header. + */ +uint8_t gb_colour_hash(struct gb_s *gb); + +/** + * Returns the title of ROM. + * + * \param gb An initialised emulator context. Must not be NULL. + * \param title_str Allocated string at least 16 characters. + * \returns Pointer to start of string, null terminated. + */ +const char* gb_get_rom_name(struct gb_s* gb, char *title_str); + +/** + * Deprecated. Will be removed in the next major version. + * RTC is ticked internally and this function has no effect. + */ +void gb_tick_rtc(struct gb_s *gb); + +/** + * Set initial values in RTC. + * Should be called after gb_init(). + * + * \param gb An initialised emulator context. Must not be NULL. + * \param time Time structure with date and time. + */ +void gb_set_rtc(struct gb_s *gb, const struct tm * const time); + +/** + * Use boot ROM on reset. gb_reset() must be called for this to take affect. + * \param gb An initialised emulator context. Must not be NULL. + * \param gb_bootrom_read Function pointer to read boot ROM binary. + */ +void gb_set_bootrom(struct gb_s *gb, + uint8_t (*gb_bootrom_read)(struct gb_s*, const uint_fast16_t)); + +/* Undefine CPU Flag helper functions. */ +#undef PEANUT_GB_CPUFLAG_MASK_CARRY +#undef PEANUT_GB_CPUFLAG_MASK_HALFC +#undef PEANUT_GB_CPUFLAG_MASK_ARITH +#undef PEANUT_GB_CPUFLAG_MASK_ZERO +#undef PEANUT_GB_CPUFLAG_BIT_CARRY +#undef PEANUT_GB_CPUFLAG_BIT_HALFC +#undef PEANUT_GB_CPUFLAG_BIT_ARITH +#undef PEANUT_GB_CPUFLAG_BIT_ZERO +#undef PGB_SET_CARRY +#undef PGB_SET_HALFC +#undef PGB_SET_ARITH +#undef PGB_SET_ZERO +#undef PGB_GET_CARRY +#undef PGB_GET_HALFC +#undef PGB_GET_ARITH +#undef PGB_GET_ZERO +#endif //PEANUT_GB_H diff --git a/gb/src/core/peanut_gbc.h b/gb/src/core/peanut_gbc.h new file mode 100644 index 0000000..3f13fc7 --- /dev/null +++ b/gb/src/core/peanut_gbc.h @@ -0,0 +1,4881 @@ +/** + * MIT License + * + * Copyright (c) 2018-2023 Mahyar Koshkouei + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Please note that at least three parts of source code within this project was + * taken from the SameBoy project at https://github.com/LIJI32/SameBoy/ which at + * the time of this writing is released under the MIT License. Occurrences of + * this code is marked as being taken from SameBoy with a comment. + * SameBoy, and code marked as being taken from SameBoy, + * is Copyright (c) 2015-2019 Lior Halphon. + */ + +#ifndef PEANUT_GB_H +#define PEANUT_GB_H + +#if defined(__has_include) +# if __has_include("version.all") +# include "version.all" /* Version information */ +# endif +#else +/* Stub __has_include for later. */ +# define __has_include(x) 0 +#endif + +#include /* Required for qsort and abort */ +#include /* Required for int types */ +#include /* Required for memset */ +#include /* Required for tm struct */ + +/** +* If PEANUT_GB_IS_LITTLE_ENDIAN is positive, then Peanut-GB will be configured +* for a little endian platform. If 0, then big endian. +*/ +#if !defined(PEANUT_GB_IS_LITTLE_ENDIAN) +/* If endian is not defined, then attempt to detect it. */ +# if defined(__BYTE_ORDER__) +# if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ +/* Building for a big endian platform. */ +# define PEANUT_GB_IS_LITTLE_ENDIAN 0 +# else +# define PEANUT_GB_IS_LITTLE_ENDIAN 1 +# endif /* __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ */ +# elif defined(_WIN32) +/* We assume that Windows is always little endian by default. */ +# define PEANUT_GB_IS_LITTLE_ENDIAN 1 +# elif !defined(PEANUT_GB_IS_LITTLE_ENDIAN) +# error "Could not detect target platform endian. Please define PEANUT_GB_IS_LITTLE_ENDIAN" +# endif +#endif /* !defined(PEANUT_GB_IS_LITTLE_ENDIAN) */ + +#if PEANUT_GB_IS_LITTLE_ENDIAN == 0 +# error "Peanut-GB only supports little endian targets" +/* This is because the logic has been written with assumption of little + * endian byte order. */ +#endif + +/** Definitions for compile-time setting of features. **/ +/** + * Sound support must be provided by an external library. When audio_read() and + * audio_write() functions are provided, define ENABLE_SOUND to a non-zero value + * before including peanut_gb.h in order for these functions to be used. + */ +#ifndef ENABLE_SOUND +# define ENABLE_SOUND 0 +#endif + +/* Enable LCD drawing. On by default. May be turned off for testing purposes. */ +#ifndef ENABLE_LCD +# define ENABLE_LCD 1 +#endif + +/* Enable 16 bit colour palette. If disabled, only four colour shades are set in + * pixel data. */ +#ifndef PEANUT_GB_12_COLOUR +# define PEANUT_GB_12_COLOUR 1 +#endif + +/* Adds more code to improve LCD rendering accuracy. */ +#ifndef PEANUT_GB_HIGH_LCD_ACCURACY +# define PEANUT_GB_HIGH_LCD_ACCURACY 1 +#endif + +/* Use intrinsic functions. This may produce smaller and faster code. */ +#ifndef PEANUT_GB_USE_INTRINSICS +# define PEANUT_GB_USE_INTRINSICS 1 +#endif + +#ifndef PEANUT_FULL_GBC_SUPPORT +# define PEANUT_FULL_GBC_SUPPORT 0 +#endif + +/* Only include function prototypes. At least one file must *not* have this + * defined. */ +// #define PEANUT_GB_HEADER_ONLY + +/** Internal source code. **/ +/* Interrupt masks */ +#define VBLANK_INTR 0x01 +#define LCDC_INTR 0x02 +#define TIMER_INTR 0x04 +#define SERIAL_INTR 0x08 +#define CONTROL_INTR 0x10 +#define ANY_INTR 0x1F + +/* Memory section sizes for DMG */ +#if PEANUT_FULL_GBC_SUPPORT +#define WRAM_SIZE 0x8000 +#define VRAM_SIZE 0x4000 +#else +#define WRAM_SIZE 0x2000 +#define VRAM_SIZE 0x2000 +#endif +#define HRAM_IO_SIZE 0x0100 +#define OAM_SIZE 0x00A0 + +/* Memory addresses */ +#define ROM_0_ADDR 0x0000 +#define ROM_N_ADDR 0x4000 +#define VRAM_ADDR 0x8000 +#define CART_RAM_ADDR 0xA000 +#define WRAM_0_ADDR 0xC000 +#define WRAM_1_ADDR 0xD000 +#define ECHO_ADDR 0xE000 +#define OAM_ADDR 0xFE00 +#define UNUSED_ADDR 0xFEA0 +#define IO_ADDR 0xFF00 +#define HRAM_ADDR 0xFF80 +#define INTR_EN_ADDR 0xFFFF + +/* Cart section sizes */ +#define ROM_BANK_SIZE 0x4000 +#ifndef PGB_PALW /* Paramix: a colour palette entry changed (GBC) */ +#define PGB_PALW(gb) ((void)0) +#endif +#ifndef PGB_BANKSET /* Paramix: called when the switchable ROM bank changes */ +#define PGB_BANKSET(gb) ((void)0) +#endif +#define WRAM_BANK_SIZE 0x1000 +#define CRAM_BANK_SIZE 0x2000 +#define VRAM_BANK_SIZE 0x2000 + +/* DIV Register is incremented at rate of 16384Hz. + * 4194304 / 16384 = 256 clock cycles for one increment. */ +#define DIV_CYCLES 256 + +/* Serial clock locked to 8192Hz on DMG. + * 4194304 / (8192 / 8) = 4096 clock cycles for sending 1 byte. */ +#define SERIAL_CYCLES 4096 +#define SERIAL_CYCLES_1KB (SERIAL_CYCLES/1ul) +#define SERIAL_CYCLES_2KB (SERIAL_CYCLES/2ul) +#define SERIAL_CYCLES_32KB (SERIAL_CYCLES/32ul) +#define SERIAL_CYCLES_64KB (SERIAL_CYCLES/64ul) + +/* Calculating VSYNC. */ +#define DMG_CLOCK_FREQ 4194304.0 +#define SCREEN_REFRESH_CYCLES 70224.0 +#define VERTICAL_SYNC (DMG_CLOCK_FREQ/SCREEN_REFRESH_CYCLES) + +/* SERIAL SC register masks. */ +#define SERIAL_SC_TX_START 0x80 +#define SERIAL_SC_CLOCK_SRC 0x01 + +/* STAT register masks */ +#define STAT_LYC_INTR 0x40 +#define STAT_MODE_2_INTR 0x20 +#define STAT_MODE_1_INTR 0x10 +#define STAT_MODE_0_INTR 0x08 +#define STAT_LYC_COINC 0x04 +#define STAT_MODE 0x03 +#define STAT_USER_BITS 0xF8 + +/* LCDC control masks */ +#define LCDC_ENABLE 0x80 +#define LCDC_WINDOW_MAP 0x40 +#define LCDC_WINDOW_ENABLE 0x20 +#define LCDC_TILE_SELECT 0x10 +#define LCDC_BG_MAP 0x08 +#define LCDC_OBJ_SIZE 0x04 +#define LCDC_OBJ_ENABLE 0x02 +#define LCDC_BG_ENABLE 0x01 + +/** LCD characteristics **/ +/* PPU cycles through modes every 456 cycles. */ +#define LCD_LINE_CYCLES 456 +/* Mode 0 starts on cycle 372. */ +#define LCD_MODE_0_CYCLES 372 +/* Mode 2 starts on cycle 204. */ +#define LCD_MODE_2_CYCLES 204 +/* Mode 3 starts on cycle 284. */ +#define LCD_MODE_3_CYCLES 284 +/* There are 154 scanlines. LY < 154. */ +#define LCD_VERT_LINES 154 +#define LCD_WIDTH 160 +#define LCD_HEIGHT 144 + +/* VRAM Locations */ +#define VRAM_TILES_1 (0x8000 - VRAM_ADDR) +#define VRAM_TILES_2 (0x8800 - VRAM_ADDR) +#define VRAM_BMAP_1 (0x9800 - VRAM_ADDR) +#define VRAM_BMAP_2 (0x9C00 - VRAM_ADDR) +#define VRAM_TILES_3 (0x8000 - VRAM_ADDR + VRAM_BANK_SIZE) +#define VRAM_TILES_4 (0x8800 - VRAM_ADDR + VRAM_BANK_SIZE) + +/* Interrupt jump addresses */ +#define VBLANK_INTR_ADDR 0x0040 +#define LCDC_INTR_ADDR 0x0048 +#define TIMER_INTR_ADDR 0x0050 +#define SERIAL_INTR_ADDR 0x0058 +#define CONTROL_INTR_ADDR 0x0060 + +/* SPRITE controls */ +#define NUM_SPRITES 0x28 +#define MAX_SPRITES_LINE 0x0A +#define OBJ_PRIORITY 0x80 +#define OBJ_FLIP_Y 0x40 +#define OBJ_FLIP_X 0x20 +#define OBJ_PALETTE 0x10 +#if PEANUT_FULL_GBC_SUPPORT +#define OBJ_BANK 0x08 +#define OBJ_CGB_PALETTE 0x07 +#endif + +#define ROM_HEADER_CHECKSUM_LOC 0x014D + +/* Local macros. */ +#ifndef MIN +# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#define PEANUT_GB_ARRAYSIZE(array) (sizeof(array)/sizeof(array[0])) + +#if !defined(__has_builtin) +/* Stub __has_builtin if it isn't available. */ +# define __has_builtin(x) 0 +#endif + +/* The PGB_UNREACHABLE() macro tells the compiler that the code path will never + * be reached, allowing for further optimisation. */ +#if !defined(PGB_UNREACHABLE) +# if __has_builtin(__builtin_unreachable) +# define PGB_UNREACHABLE() __builtin_unreachable() +# elif defined(_MSC_VER) && _MSC_VER >= 1200 +# /* __assume is not available before VC6. */ +# define PGB_UNREACHABLE() __assume(0) +# else +# define PGB_UNREACHABLE() abort() +# endif +#endif /* !defined(PGB_UNREACHABLE) */ + +#if PEANUT_GB_USE_INTRINSICS +/* If using MSVC, only enable intrinsics for x86 platforms*/ +# if defined(_MSC_VER) && __has_include("intrin.h") && \ + (defined(_M_IX86_FP) || defined(_M_AMD64) || defined(_M_X64)) +/* Define intrinsic functions for MSVC. */ +# include +# define PGB_INTRIN_SBC(x,y,cin,res) _subborrow_u8(cin,x,y,&res) +# define PGB_INTRIN_ADC(x,y,cin,res) _addcarry_u8(cin,x,y,&res) +# endif /* MSVC */ + +/* Check for intrinsic functions in GCC and Clang. */ +# if __has_builtin(__builtin_sub_overflow) +# define PGB_INTRIN_SBC(x,y,cin,res) __builtin_sub_overflow(x,y+cin,&res) +# define PGB_INTRIN_ADC(x,y,cin,res) __builtin_add_overflow(x,y+cin,&res) +# endif +#endif /* PEANUT_GB_USE_INTRINSICS */ + +#if defined(PGB_INTRIN_SBC) +# define PGB_INSTR_SBC_R8(r,cin) \ + { \ + uint8_t temp; \ + gb->cpu_reg.f_bits.c = PGB_INTRIN_SBC(gb->cpu_reg.a,r,cin,temp);\ + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f_bits.n = 1; \ + gb->cpu_reg.f_bits.z = (temp == 0x00); \ + gb->cpu_reg.a = temp; \ + } + +# define PGB_INSTR_CP_R8(r) \ + { \ + uint8_t temp; \ + gb->cpu_reg.f_bits.c = PGB_INTRIN_SBC(gb->cpu_reg.a,r,0,temp); \ + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f_bits.n = 1; \ + gb->cpu_reg.f_bits.z = (temp == 0x00); \ + } +#else +# define PGB_INSTR_SBC_R8(r,cin) \ + { \ + uint16_t temp = gb->cpu_reg.a - (r + cin); \ + gb->cpu_reg.f_bits.c = (temp & 0xFF00) ? 1 : 0; \ + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f_bits.n = 1; \ + gb->cpu_reg.f_bits.z = ((temp & 0xFF) == 0x00); \ + gb->cpu_reg.a = (temp & 0xFF); \ + } + +# define PGB_INSTR_CP_R8(r) \ + { \ + uint16_t temp = gb->cpu_reg.a - r; \ + gb->cpu_reg.f_bits.c = (temp & 0xFF00) ? 1 : 0; \ + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f_bits.n = 1; \ + gb->cpu_reg.f_bits.z = ((temp & 0xFF) == 0x00); \ + } +#endif /* PGB_INTRIN_SBC */ + +#if defined(PGB_INTRIN_ADC) +# define PGB_INSTR_ADC_R8(r,cin) \ + { \ + uint8_t temp; \ + gb->cpu_reg.f_bits.c = PGB_INTRIN_ADC(gb->cpu_reg.a,r,cin,temp);\ + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f_bits.n = 0; \ + gb->cpu_reg.f_bits.z = (temp == 0x00); \ + gb->cpu_reg.a = temp; \ + } +#else +# define PGB_INSTR_ADC_R8(r,cin) \ + { \ + uint16_t temp = gb->cpu_reg.a + r + cin; \ + gb->cpu_reg.f_bits.c = (temp & 0xFF00) ? 1 : 0; \ + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a ^ r ^ temp) & 0x10) > 0; \ + gb->cpu_reg.f_bits.n = 0; \ + gb->cpu_reg.f_bits.z = ((temp & 0xFF) == 0x00); \ + gb->cpu_reg.a = (temp & 0xFF); \ + } +#endif /* PGB_INTRIN_ADC */ + +#define PGB_INSTR_DEC_R8(r) \ + r--; \ + gb->cpu_reg.f_bits.h = ((r & 0x0F) == 0x0F); \ + gb->cpu_reg.f_bits.n = 1; \ + gb->cpu_reg.f_bits.z = (r == 0x00); + +#define PGB_INSTR_XOR_R8(r) \ + gb->cpu_reg.a ^= r; \ + gb->cpu_reg.f_bits.z = (gb->cpu_reg.a == 0x00); \ + gb->cpu_reg.f_bits.n = 0; \ + gb->cpu_reg.f_bits.h = 0; \ + gb->cpu_reg.f_bits.c = 0; + +#define PGB_INSTR_OR_R8(r) \ + gb->cpu_reg.a |= r; \ + gb->cpu_reg.f_bits.z = (gb->cpu_reg.a == 0x00); \ + gb->cpu_reg.f_bits.n = 0; \ + gb->cpu_reg.f_bits.h = 0; \ + gb->cpu_reg.f_bits.c = 0; + +#define PGB_INSTR_AND_R8(r) \ + gb->cpu_reg.a &= r; \ + gb->cpu_reg.f_bits.z = (gb->cpu_reg.a == 0x00); \ + gb->cpu_reg.f_bits.n = 0; \ + gb->cpu_reg.f_bits.h = 1; \ + gb->cpu_reg.f_bits.c = 0; + +#if PEANUT_GB_IS_LITTLE_ENDIAN +# define PEANUT_GB_GET_LSB16(x) (x & 0xFF) +# define PEANUT_GB_GET_MSB16(x) (x >> 8) +# define PEANUT_GB_GET_MSN16(x) (x >> 12) +# define PEANUT_GB_U8_TO_U16(h,l) ((l) | ((h) << 8)) +#else +# define PEANUT_GB_GET_LSB16(x) (x >> 8) +# define PEANUT_GB_GET_MSB16(x) (x & 0xFF) +# define PEANUT_GB_GET_MSN16(x) ((x & 0xF0) >> 4) +# define PEANUT_GB_U8_TO_U16(h,l) ((h) | ((l) << 8)) +#endif + +struct cpu_registers_s +{ +/* Change register order if big endian. + * Macro receives registers in little endian order. */ +#if PEANUT_GB_IS_LITTLE_ENDIAN +# define PEANUT_GB_LE_REG(x,y) x,y +#else +# define PEANUT_GB_LE_REG(x,y) y,x +#endif + /* Define specific bits of Flag register. */ + struct + { + uint8_t c : 1; /* Carry flag. */ + uint8_t h : 1; /* Half carry flag. */ + uint8_t n : 1; /* Add/sub flag. */ + uint8_t z : 1; /* Zero flag. */ + } f_bits; + uint8_t a; + + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(c,b); + } bytes; + uint16_t reg; + } bc; + + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(e,d); + } bytes; + uint16_t reg; + } de; + + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(l,h); + } bytes; + uint16_t reg; + } hl; + + /* Stack pointer */ + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(p, s); + } bytes; + uint16_t reg; + } sp; + + /* Program counter */ + union + { + struct + { + uint8_t PEANUT_GB_LE_REG(c, p); + } bytes; + uint16_t reg; + } pc; +#undef PEANUT_GB_LE_REG +}; + +struct count_s +{ + uint_fast16_t lcd_count; /* LCD Timing */ + uint_fast16_t div_count; /* Divider Register Counter */ + uint_fast16_t tima_count; /* Timer Counter */ + uint_fast16_t serial_count; /* Serial Counter */ +#ifdef PGB_BATCH + uint_fast32_t pend; /* Paramix: cycles not yet given to the timers and the LCD */ + uint_fast32_t slack; /* Paramix: cycles until the next of them changes anything */ +#endif +}; + +#if ENABLE_LCD + /* Bit mask for the shade of pixel to display */ + #define LCD_COLOUR 0x03 + +# if PEANUT_GB_12_COLOUR + /** + * Bit mask for whether a pixel is OBJ0, OBJ1, or BG. Each may have a different + * palette when playing a DMG game on CGB. + */ + #define LCD_PALETTE_OBJ 0x10 + #define LCD_PALETTE_BG 0x20 + /** + * Bit mask for the two bits listed above. + * LCD_PALETTE_ALL == 0b00 --> OBJ0 + * LCD_PALETTE_ALL == 0b01 --> OBJ1 + * LCD_PALETTE_ALL == 0b10 --> BG + * LCD_PALETTE_ALL == 0b11 --> NOT POSSIBLE + */ + #define LCD_PALETTE_ALL 0x30 +# endif +#endif + +/** + * Errors that may occur during emulation. + */ +enum gb_error_e +{ + GB_UNKNOWN_ERROR = 0, + GB_INVALID_OPCODE, + GB_INVALID_READ, + GB_INVALID_WRITE, + GB_HALT_FOREVER, + + GB_INVALID_MAX +}; + +/** + * Errors that may occur during library initialisation. + */ +enum gb_init_error_e +{ + GB_INIT_NO_ERROR = 0, + GB_INIT_CARTRIDGE_UNSUPPORTED, + GB_INIT_INVALID_CHECKSUM +}; + +/** + * Return codes for serial receive function, mainly for clarity. + */ +enum gb_serial_rx_ret_e +{ + GB_SERIAL_RX_SUCCESS = 0, + GB_SERIAL_RX_NO_CONNECTION = 1, + /* Paramix (PGB_SERIAL_WAIT): the answer is not there yet, ask again at the next instruction */ + GB_SERIAL_RX_WAIT = 2 +}; + +/** + * Emulator context. + * + * Only values within the `direct` struct may be modified directly by the + * front-end implementation. Other variables must not be modified. + */ +struct gb_s +{ + /** + * Return byte from ROM at given address. + * + * \param gb_s emulator context + * \param addr address + * \return byte at address in ROM + */ + uint8_t (*gb_rom_read)(struct gb_s*, const uint_fast32_t addr); + + /** + * Return byte from cart RAM at given address. + * + * \param gb_s emulator context + * \param addr address + * \return byte at address in RAM + */ + uint8_t (*gb_cart_ram_read)(struct gb_s*, const uint_fast32_t addr); + + /** + * Write byte to cart RAM at given address. + * + * \param gb_s emulator context + * \param addr address + * \param val value to write to address in RAM + */ + void (*gb_cart_ram_write)(struct gb_s*, const uint_fast32_t addr, + const uint8_t val); + + /** + * Notify front-end of error. + * + * \param gb_s emulator context + * \param gb_error_e error code + * \param addr address of where error occurred + */ + void (*gb_error)(struct gb_s*, const enum gb_error_e, const uint16_t addr); + + /* Transmit one byte and return the received byte. */ + void (*gb_serial_tx)(struct gb_s*, const uint8_t tx); + enum gb_serial_rx_ret_e (*gb_serial_rx)(struct gb_s*, uint8_t* rx); + + /* Read byte from boot ROM at given address. */ + uint8_t (*gb_bootrom_read)(struct gb_s*, const uint_fast16_t addr); + + struct + { + uint8_t gb_halt : 1; + uint8_t gb_ime : 1; + uint8_t gb_frame : 1; /* New frame drawn. */ + uint8_t lcd_blank : 1; + }; + + /* Cartridge information: + * Memory Bank Controller (MBC) type. */ + int8_t mbc; + /* Whether the MBC has internal RAM. */ + uint8_t cart_ram; + /* Number of ROM banks in cartridge. */ + uint16_t num_rom_banks_mask; + /* Number of RAM banks in cartridge. Ignore for MBC2. */ + uint8_t num_ram_banks; + + uint16_t selected_rom_bank; + /* WRAM and VRAM bank selection not available. */ + uint8_t cart_ram_bank; + uint8_t enable_cart_ram; + /* Cartridge ROM/RAM mode select. */ + uint8_t cart_mode_select; + union + { + struct + { + uint8_t sec; + uint8_t min; + uint8_t hour; + uint8_t yday; + uint8_t high; + } rtc_bits; + uint8_t cart_rtc[5]; + }; + + struct cpu_registers_s cpu_reg; + //struct gb_registers_s gb_reg; + struct count_s counter; + + /* TODO: Allow implementation to allocate WRAM, VRAM and Frame Buffer. */ + uint8_t wram[WRAM_SIZE]; + uint8_t vram[VRAM_SIZE]; + uint8_t oam[OAM_SIZE]; + uint8_t hram_io[HRAM_IO_SIZE]; + + struct + { + /** + * Draw line on screen. + * + * \param gb_s emulator context + * \param pixels The 160 pixels to draw. + * Bits 1-0 are the colour to draw. + * Bits 5-4 are the palette, where: + * OBJ0 = 0b00, + * OBJ1 = 0b01, + * BG = 0b10 + * Other bits are undefined. + * Bits 5-4 are only required by front-ends + * which want to use a different colour for + * different object palettes. This is what + * the Game Boy Color (CGB) does to DMG + * games. + * \param line Line to draw pixels on. This is + * guaranteed to be between 0-144 inclusive. + */ + void (*lcd_draw_line)(struct gb_s *gb, + const uint8_t *pixels, + const uint_fast8_t line); + + /* Palettes */ + uint8_t bg_palette[4]; + uint8_t sp_palette[8]; + + uint8_t window_clear; + uint8_t WY; + + /* Only support 30fps frame skip. */ + uint8_t frame_skip_count : 1; + uint8_t interlace_count : 1; + } display; + +#if PEANUT_FULL_GBC_SUPPORT + /* Game Boy Color Mode*/ + struct { + uint8_t cgbMode; + uint8_t doubleSpeed; + uint8_t doubleSpeedPrep; + uint8_t wramBank; + uint16_t wramBankOffset; + uint8_t vramBank; + uint16_t vramBankOffset; + uint16_t fixPalette[0x40]; //BG then OAM palettes fixed for the screen + uint8_t OAMPalette[0x40]; + uint8_t BGPalette[0x40]; + uint8_t OAMPaletteID; + uint8_t BGPaletteID; + uint8_t OAMPaletteInc; + uint8_t BGPaletteInc; + uint8_t dmaActive; + uint8_t dmaMode; + uint8_t dmaSize; + uint16_t dmaSource; + uint16_t dmaDest; + } cgb; +#endif + + /** + * Variables that may be modified directly by the front-end. + * This method seems to be easier and possibly less overhead than + * calling a function to modify these variables each time. + * + * None of this is thread-safe. + */ + struct + { + /* Set to enable interlacing. Interlacing will start immediately + * (at the next line drawing). + */ + uint8_t interlace : 1; + uint8_t frame_skip : 1; + + union + { + struct + { + uint8_t a : 1; + uint8_t b : 1; + uint8_t select : 1; + uint8_t start : 1; + uint8_t right : 1; + uint8_t left : 1; + uint8_t up : 1; + uint8_t down : 1; + } joypad_bits; + uint8_t joypad; + }; + + /* Implementation defined data. Set to NULL if not required. */ + void *priv; + } direct; +}; + +#ifndef PEANUT_GB_HEADER_ONLY + +#define IO_JOYP 0x00 +#define IO_SB 0x01 +#define IO_SC 0x02 +#define IO_DIV 0x04 +#define IO_TIMA 0x05 +#define IO_TMA 0x06 +#define IO_TAC 0x07 +#define IO_IF 0x0F +#define IO_BOOT 0x50 +#define IO_LCDC 0x40 +#define IO_STAT 0x41 +#define IO_SCY 0x42 +#define IO_SCX 0x43 +#define IO_LY 0x44 +#define IO_LYC 0x45 +#define IO_DMA 0x46 +#define IO_BGP 0x47 +#define IO_OBP0 0x48 +#define IO_OBP1 0x49 +#define IO_WY 0x4A +#define IO_WX 0x4B +#define IO_BANK 0x50 +#define IO_IE 0xFF + +#define IO_TAC_RATE_MASK 0x3 +#define IO_TAC_ENABLE_MASK 0x4 + +/* LCD Mode defines. */ +#define IO_STAT_MODE_HBLANK 0 +#define IO_STAT_MODE_VBLANK 1 +#define IO_STAT_MODE_SEARCH_OAM 2 +#define IO_STAT_MODE_SEARCH_TRANSFER 3 +#define IO_STAT_MODE_VBLANK_OR_TRANSFER_MASK 0x1 + +/** + * Internal function used to read bytes. + * addr is host platform endian. + */ +#ifndef PGB_READ_ATTR +#define PGB_READ_ATTR +#endif +#ifdef PGB_BATCH +static void __gb_flush(struct gb_s *gb); +/* Paramix PGB_BATCH: registers 0xFF00..0xFF7F (without the sound registers) and IE see the timers and the LCD as + * after every instruction: the cycles kept back are handed over first */ +#define PGB_SYNC(gb, addr) do { if(((addr) < 0xFF10 || (addr) > 0xFF3F) && ((addr) < HRAM_ADDR || (addr) == INTR_EN_ADDR)) \ + { if((gb)->counter.pend) __gb_flush(gb); (gb)->counter.slack = 0; } } while(0) +#endif +PGB_READ_ATTR uint8_t __gb_read(struct gb_s *gb, uint16_t addr) +{ + switch(PEANUT_GB_GET_MSN16(addr)) + { + case 0x0: + /* IO_BANK is only set to 1 if gb->gb_bootrom_read was not NULL + * on reset. */ + if(gb->hram_io[IO_BANK] == 0 && addr < 0x0100) + { + return gb->gb_bootrom_read(gb, addr); + } + + /* Fallthrough */ + case 0x1: + case 0x2: + case 0x3: +#ifdef PGB_ROM /* Paramix: the ROM straight from the cached flash window */ + return PGB_ROM[addr]; +#else + return gb->gb_rom_read(gb, addr); +#endif + + case 0x4: + case 0x5: + case 0x6: + case 0x7: +#if defined(PGB_ROM) && defined(PGB_ROMOFF) /* Paramix GB_TRIM: offset of the switchable bank, set when it changes */ + return PGB_ROM[addr + PGB_ROMOFF]; +#elif defined(PGB_ROM) /* Paramix */ + if(gb->mbc == 1 && gb->cart_mode_select) + return PGB_ROM[addr + ((gb->selected_rom_bank & 0x1F) - 1) * ROM_BANK_SIZE]; + else + return PGB_ROM[addr + (gb->selected_rom_bank - 1) * ROM_BANK_SIZE]; +#else + if(gb->mbc == 1 && gb->cart_mode_select) + return gb->gb_rom_read(gb, + addr + ((gb->selected_rom_bank & 0x1F) - 1) * ROM_BANK_SIZE); + else + return gb->gb_rom_read(gb, addr + (gb->selected_rom_bank - 1) * ROM_BANK_SIZE); +#endif + + case 0x8: + case 0x9: +#if PEANUT_FULL_GBC_SUPPORT + return gb->vram[addr - gb->cgb.vramBankOffset]; +#else + return gb->vram[addr - VRAM_ADDR]; +#endif + case 0xA: + case 0xB: + if(gb->mbc == 3 && gb->cart_ram_bank >= 0x08) + { + return gb->cart_rtc[gb->cart_ram_bank - 0x08]; + } + else if(gb->cart_ram && gb->enable_cart_ram) + { + if(gb->mbc == 2) + { + /* Only 9 bits are available in address. */ + addr &= 0x1FF; + return gb->gb_cart_ram_read(gb, addr); + } + else if((gb->cart_mode_select || gb->mbc != 1) && + gb->cart_ram_bank < gb->num_ram_banks) + { + return gb->gb_cart_ram_read(gb, addr - CART_RAM_ADDR + + (gb->cart_ram_bank * CRAM_BANK_SIZE)); + } + else + return gb->gb_cart_ram_read(gb, addr - CART_RAM_ADDR); + } + + return 0xFF; + + case 0xC: + case 0xD: +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode && addr >= WRAM_1_ADDR) + return gb->wram[addr - gb->cgb.wramBankOffset]; +#endif + return gb->wram[addr - WRAM_0_ADDR]; + + case 0xE: + return gb->wram[addr - ECHO_ADDR]; + + case 0xF: + if(addr < OAM_ADDR) +#if PEANUT_FULL_GBC_SUPPORT + return gb->wram[(addr - 0x2000) - gb->cgb.wramBankOffset]; +#else + return gb->wram[addr - ECHO_ADDR]; +#endif + + if(addr < UNUSED_ADDR) + return gb->oam[addr - OAM_ADDR]; + + /* Unusable memory area. Reading from this area returns 0xFF.*/ + if(addr < IO_ADDR) + return 0xFF; +#ifdef PGB_BATCH + PGB_SYNC(gb, addr); +#endif + + /* APU registers. */ + if((addr >= 0xFF10) && (addr <= 0xFF3F)) + { +#if ENABLE_SOUND + return audio_read(addr); +#else + static const uint8_t ortab[] = { + 0x80, 0x3f, 0x00, 0xff, 0xbf, + 0xff, 0x3f, 0x00, 0xff, 0xbf, + 0x7f, 0xff, 0x9f, 0xff, 0xbf, + 0xff, 0xff, 0x00, 0x00, 0xbf, + 0x00, 0x00, 0x70, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + return gb->hram_io[addr - IO_ADDR] | ortab[addr - IO_ADDR]; +#endif + } + +#if PEANUT_FULL_GBC_SUPPORT + /* IO and Interrupts. */ + switch (addr & 0xFF) + { + /* Speed Switch*/ + case 0x4D: + return (gb->cgb.doubleSpeed << 7) + gb->cgb.doubleSpeedPrep; + /* CGB VRAM Bank*/ + case 0x4F: + return gb->cgb.vramBank | 0xFE; + /* CGB DMA*/ + case 0x51: + return (gb->cgb.dmaSource >> 8); + case 0x52: + return (gb->cgb.dmaSource & 0xF0); + case 0x53: + return (gb->cgb.dmaDest >> 8); + case 0x54: + return (gb->cgb.dmaDest & 0xF0); + case 0x55: + return (gb->cgb.dmaActive << 7) | (gb->cgb.dmaSize - 1); + /* IR Register*/ + case 0x56: + return gb->hram_io[0x56]; + /* CGB BG Palette Index*/ + case 0x68: + return (gb->cgb.BGPaletteID & 0x3F) + (gb->cgb.BGPaletteInc << 7); + /* CGB BG Palette*/ + case 0x69: + return gb->cgb.BGPalette[(gb->cgb.BGPaletteID & 0x3F)]; + /* CGB OAM Palette Index*/ + case 0x6A: + return (gb->cgb.OAMPaletteID & 0x3F) + (gb->cgb.OAMPaletteInc << 7); + /* CGB OAM Palette*/ + case 0x6B: + return gb->cgb.OAMPalette[(gb->cgb.OAMPaletteID & 0x3F)]; + /* CGB WRAM Bank*/ + case 0x70: + return gb->cgb.wramBank; + default: +#endif + /* HRAM */ + if(addr >= IO_ADDR) + return gb->hram_io[addr - IO_ADDR]; +#if PEANUT_FULL_GBC_SUPPORT + } +#endif + } + + + /* Return address that caused read error. */ + (gb->gb_error)(gb, GB_INVALID_READ, addr); + PGB_UNREACHABLE(); +} + +/** + * Internal function used to write bytes. + */ +void __gb_write(struct gb_s *gb, uint_fast16_t addr, uint8_t val) +{ + switch(PEANUT_GB_GET_MSN16(addr)) + { + case 0x0: + case 0x1: + /* Set RAM enable bit. MBC2 is handled in fall-through. */ + if(gb->mbc > 0 && gb->mbc != 2 && gb->cart_ram) + { + gb->enable_cart_ram = ((val & 0x0F) == 0x0A); + return; + } + + /* Intentional fall through. */ + case 0x2: + if(gb->mbc == 5) + { + gb->selected_rom_bank = (gb->selected_rom_bank & 0x100) | val; + gb->selected_rom_bank = + gb->selected_rom_bank & gb->num_rom_banks_mask; + PGB_BANKSET(gb); + return; + } + + /* Intentional fall through. */ + case 0x3: + if(gb->mbc == 1) + { + //selected_rom_bank = val & 0x7; + gb->selected_rom_bank = (val & 0x1F) | (gb->selected_rom_bank & 0x60); + + if((gb->selected_rom_bank & 0x1F) == 0x00) + gb->selected_rom_bank++; + } + else if(gb->mbc == 2) + { + /* If bit 8 is 1, then set ROM bank number. */ + if(addr & 0x100) + { + gb->selected_rom_bank = val & 0x0F; + /* Setting ROM bank to 0, sets it to 1. */ + if(!gb->selected_rom_bank) + gb->selected_rom_bank++; + } + /* Otherwise set whether RAM is enabled or not. */ + else + { + gb->enable_cart_ram = ((val & 0x0F) == 0x0A); + return; + } + } + else if(gb->mbc == 3) + { + gb->selected_rom_bank = val & 0x7F; + + if(!gb->selected_rom_bank) + gb->selected_rom_bank++; + } + else if(gb->mbc == 5) + gb->selected_rom_bank = (val & 0x01) << 8 | (gb->selected_rom_bank & 0xFF); + + gb->selected_rom_bank = gb->selected_rom_bank & gb->num_rom_banks_mask; + PGB_BANKSET(gb); + return; + + case 0x4: + case 0x5: + if(gb->mbc == 1) + { + gb->cart_ram_bank = (val & 3); + gb->selected_rom_bank = ((val & 3) << 5) | (gb->selected_rom_bank & 0x1F); + gb->selected_rom_bank = gb->selected_rom_bank & gb->num_rom_banks_mask; + PGB_BANKSET(gb); + } + else if(gb->mbc == 3) + gb->cart_ram_bank = val; + else if(gb->mbc == 5) + gb->cart_ram_bank = (val & 0x0F); + + return; + + case 0x6: + case 0x7: + gb->cart_mode_select = (val & 1); + PGB_BANKSET(gb); + return; + + case 0x8: + case 0x9: +#if PEANUT_FULL_GBC_SUPPORT + gb->vram[addr - gb->cgb.vramBankOffset] = val; +#else + gb->vram[addr - VRAM_ADDR] = val; +#endif + return; + + case 0xA: + case 0xB: + if(gb->mbc == 3 && gb->cart_ram_bank >= 0x08) + { + gb->cart_rtc[gb->cart_ram_bank - 0x08] = val; + } + /* Do not write to RAM if unavailable or disabled. */ + else if(gb->cart_ram && gb->enable_cart_ram) + { + if(gb->mbc == 2) + { + /* Only 9 bits are available in address. */ + addr &= 0x1FF; + /* Data is only 4 bits wide in MBC2 RAM. */ + val &= 0x0F; + gb->gb_cart_ram_write(gb, addr, val); + } + else if(gb->cart_mode_select && + gb->cart_ram_bank < gb->num_ram_banks) + { + gb->gb_cart_ram_write(gb, + addr - CART_RAM_ADDR + (gb->cart_ram_bank * CRAM_BANK_SIZE), val); + } + else if(gb->num_ram_banks) + gb->gb_cart_ram_write(gb, addr - CART_RAM_ADDR, val); + } + + return; + + case 0xC: + gb->wram[addr - WRAM_0_ADDR] = val; + return; + + case 0xD: +#if PEANUT_FULL_GBC_SUPPORT + gb->wram[addr - gb->cgb.wramBankOffset] = val; +#else + gb->wram[addr - WRAM_1_ADDR + WRAM_BANK_SIZE] = val; +#endif + return; + + case 0xE: + gb->wram[addr - ECHO_ADDR] = val; + return; + + case 0xF: + if(addr < OAM_ADDR) + { +#if PEANUT_FULL_GBC_SUPPORT + gb->wram[(addr - 0x2000) - gb->cgb.wramBankOffset] = val; +#else + gb->wram[addr - ECHO_ADDR] = val; +#endif + return; + } + + if(addr < UNUSED_ADDR) + { + gb->oam[addr - OAM_ADDR] = val; + return; + } + + /* Unusable memory area. */ + if(addr < IO_ADDR) + return; +#ifdef PGB_BATCH + PGB_SYNC(gb, addr); +#endif + + if(HRAM_ADDR <= addr && addr < INTR_EN_ADDR) + { + gb->hram_io[addr - IO_ADDR] = val; + return; + } + + if((addr >= 0xFF10) && (addr <= 0xFF3F)) + { +#if ENABLE_SOUND + audio_write(addr, val); +#else + gb->hram_io[addr - IO_ADDR] = val; +#ifdef PGB_APU_WRITE /* Paramix: the sound registers seen by the Paradise's buzzer */ + PGB_APU_WRITE(addr, val); +#endif +#endif + return; + } +#if PEANUT_FULL_GBC_SUPPORT + uint16_t fixPaletteTemp; +#endif + /* IO and Interrupts. */ + switch(PEANUT_GB_GET_LSB16(addr)) + { + /* Joypad */ + case 0x00: + /* Only bits 5 and 4 are R/W. + * The lower bits are overwritten later, and the two most + * significant bits are unused. */ + gb->hram_io[IO_JOYP] = val; + + /* Direction keys selected */ + if((gb->hram_io[IO_JOYP] & 0x10) == 0) + gb->hram_io[IO_JOYP] |= (gb->direct.joypad >> 4); + /* Button keys selected */ + else + gb->hram_io[IO_JOYP] |= (gb->direct.joypad & 0x0F); + + return; + + /* Serial */ + case 0x01: + gb->hram_io[IO_SB] = val; + return; + + case 0x02: + gb->hram_io[IO_SC] = val; +#ifdef PGB_SERIAL_WAIT + /* Paramix: writing the start bit begins a new transfer (the link sees each one) */ + if(val & SERIAL_SC_TX_START) + gb->counter.serial_count = 0; +#endif + return; + + /* Timer Registers */ + case 0x04: + gb->hram_io[IO_DIV] = 0x00; + return; + + case 0x05: + gb->hram_io[IO_TIMA] = val; + return; + + case 0x06: + gb->hram_io[IO_TMA] = val; + return; + + case 0x07: + gb->hram_io[IO_TAC] = val; + return; + + /* Interrupt Flag Register */ + case 0x0F: + gb->hram_io[IO_IF] = (val | 0xE0); + return; + + /* LCD Registers */ + case 0x40: + { + uint8_t lcd_enabled; + + /* Check if LCD is already enabled. */ + lcd_enabled = (gb->hram_io[IO_LCDC] & LCDC_ENABLE); + + gb->hram_io[IO_LCDC] = val; + + /* Check if LCD is going to be switched on. */ + if (!lcd_enabled && (val & LCDC_ENABLE)) + { + gb->lcd_blank = 1; + } + /* Check if LCD is being switched off. */ + else if (lcd_enabled && !(val & LCDC_ENABLE)) + { + /* Peanut-GB will happily turn off LCD outside + * of VBLANK even though this damages real + * hardware. */ + + /* Set LCD to Mode 0. */ + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | + IO_STAT_MODE_HBLANK; + /* LY fixed to 0 when LCD turned off. */ + gb->hram_io[IO_LY] = 0; + /* Reset LCD timer. */ + gb->counter.lcd_count = 0; + } + return; + } + + case 0x41: + gb->hram_io[IO_STAT] = (val & STAT_USER_BITS) | (gb->hram_io[IO_STAT] & STAT_MODE); + return; + + case 0x42: + gb->hram_io[IO_SCY] = val; + return; + + case 0x43: + gb->hram_io[IO_SCX] = val; + return; + + /* LY (0xFF44) is read only. */ + case 0x45: + gb->hram_io[IO_LYC] = val; + return; + + /* DMA Register */ + case 0x46: + { + uint16_t dma_addr; + uint16_t i; +#if PEANUT_FULL_GBC_SUPPORT + dma_addr = (uint_fast16_t)(val % 0xF1) << 8; + gb->hram_io[IO_DMA] = (val % 0xF1); +#else + dma_addr = (uint_fast16_t)val << 8; + gb->hram_io[IO_DMA] = val; +#endif + for(i = 0; i < OAM_SIZE; i++) + { + gb->oam[i] = __gb_read(gb, dma_addr + i); + } + + return; + } + + /* DMG Palette Registers */ + case 0x47: + gb->hram_io[IO_BGP] = val; + gb->display.bg_palette[0] = (gb->hram_io[IO_BGP] & 0x03); + gb->display.bg_palette[1] = (gb->hram_io[IO_BGP] >> 2) & 0x03; + gb->display.bg_palette[2] = (gb->hram_io[IO_BGP] >> 4) & 0x03; + gb->display.bg_palette[3] = (gb->hram_io[IO_BGP] >> 6) & 0x03; + return; + + case 0x48: + gb->hram_io[IO_OBP0] = val; + gb->display.sp_palette[0] = (gb->hram_io[IO_OBP0] & 0x03); + gb->display.sp_palette[1] = (gb->hram_io[IO_OBP0] >> 2) & 0x03; + gb->display.sp_palette[2] = (gb->hram_io[IO_OBP0] >> 4) & 0x03; + gb->display.sp_palette[3] = (gb->hram_io[IO_OBP0] >> 6) & 0x03; + return; + + case 0x49: + gb->hram_io[IO_OBP1] = val; + gb->display.sp_palette[4] = (gb->hram_io[IO_OBP1] & 0x03); + gb->display.sp_palette[5] = (gb->hram_io[IO_OBP1] >> 2) & 0x03; + gb->display.sp_palette[6] = (gb->hram_io[IO_OBP1] >> 4) & 0x03; + gb->display.sp_palette[7] = (gb->hram_io[IO_OBP1] >> 6) & 0x03; + return; + + /* Window Position Registers */ + case 0x4A: + gb->hram_io[IO_WY] = val; + return; + + case 0x4B: + gb->hram_io[IO_WX] = val; + return; + +#if PEANUT_FULL_GBC_SUPPORT + /* Prepare Speed Switch*/ + case 0x4D: + gb->cgb.doubleSpeedPrep = val & 1; + return; + + /* CGB VRAM Bank*/ + case 0x4F: + gb->cgb.vramBank = val & 0x01; + if(gb->cgb.cgbMode) gb->cgb.vramBankOffset = VRAM_ADDR - (gb->cgb.vramBank << 13); + return; +#endif + /* Turn off boot ROM */ + case 0x50: + gb->hram_io[IO_BANK] = val; + return; +#if PEANUT_FULL_GBC_SUPPORT + /* DMA Register */ + case 0x51: + gb->cgb.dmaSource = (gb->cgb.dmaSource & 0xFF) + (val << 8); + return; + case 0x52: + gb->cgb.dmaSource = (gb->cgb.dmaSource & 0xFF00) + val; + return; + case 0x53: + gb->cgb.dmaDest = (gb->cgb.dmaDest & 0xFF) + (val << 8); + return; + case 0x54: + gb->cgb.dmaDest = (gb->cgb.dmaDest & 0xFF00) + val; + return; + + /* DMA Register*/ + case 0x55: + gb->cgb.dmaSize = (val & 0x7F) + 1; + gb->cgb.dmaMode = val >> 7; + //DMA GBC + if(gb->cgb.dmaActive) + { // Only transfer if dma is not active (=1) otherwise treat it as a termination + if(gb->cgb.cgbMode && (!gb->cgb.dmaMode)) + { + for (int i = 0; i < (gb->cgb.dmaSize << 4); i++) + { + __gb_write(gb, ((gb->cgb.dmaDest & 0x1FF0) | 0x8000) + i, __gb_read(gb, (gb->cgb.dmaSource & 0xFFF0) + i)); + } + gb->cgb.dmaSource += (gb->cgb.dmaSize << 4); + gb->cgb.dmaDest += (gb->cgb.dmaSize << 4); + gb->cgb.dmaSize = 0; + } + } + gb->cgb.dmaActive = gb->cgb.dmaMode ^ 1; // set active if it's an HBlank DMA + return; + + /* IR Register*/ + case 0x56: + gb->hram_io[0x56] = val; + return; + + /* CGB BG Palette Index*/ + case 0x68: + gb->cgb.BGPaletteID = val & 0x3F; + gb->cgb.BGPaletteInc = val >> 7; + return; + + /* CGB BG Palette*/ + case 0x69: + gb->cgb.BGPalette[(gb->cgb.BGPaletteID & 0x3F)] = val; + fixPaletteTemp = (gb->cgb.BGPalette[(gb->cgb.BGPaletteID & 0x3E) + 1] << 8) + (gb->cgb.BGPalette[(gb->cgb.BGPaletteID & 0x3E)]); + gb->cgb.fixPalette[((gb->cgb.BGPaletteID & 0x3E) >> 1)] = ((fixPaletteTemp & 0x7C00) >> 10) | (fixPaletteTemp & 0x03E0) | ((fixPaletteTemp & 0x001F) << 10); // swap Red and Blue + PGB_PALW(gb); /* Paramix */ + if(gb->cgb.BGPaletteInc) gb->cgb.BGPaletteID = (++gb->cgb.BGPaletteID) & 0x3F; + return; + + /* CGB OAM Palette Index*/ + case 0x6A: + gb->cgb.OAMPaletteID = val & 0x3F; + gb->cgb.OAMPaletteInc = val >> 7; + return; + + /* CGB OAM Palette*/ + case 0x6B: + gb->cgb.OAMPalette[(gb->cgb.OAMPaletteID & 0x3F)] = val; + fixPaletteTemp = (gb->cgb.OAMPalette[(gb->cgb.OAMPaletteID & 0x3E) + 1] << 8) + (gb->cgb.OAMPalette[(gb->cgb.OAMPaletteID & 0x3E)]); + gb->cgb.fixPalette[0x20 + ((gb->cgb.OAMPaletteID & 0x3E) >> 1)] = ((fixPaletteTemp & 0x7C00) >> 10) | (fixPaletteTemp & 0x03E0) | ((fixPaletteTemp & 0x001F) << 10); // swap Red and Blue + PGB_PALW(gb); /* Paramix */ + if(gb->cgb.OAMPaletteInc) gb->cgb.OAMPaletteID = (++gb->cgb.OAMPaletteID) & 0x3F; + return; + + /* CGB WRAM Bank*/ + case 0x70: + gb->cgb.wramBank = val; + gb->cgb.wramBankOffset = WRAM_1_ADDR - (1 << 12); + if(gb->cgb.cgbMode && (gb->cgb.wramBank & 7) > 0) gb->cgb.wramBankOffset = WRAM_1_ADDR - ((gb->cgb.wramBank & 7) << 12); + return; +#endif + + /* Interrupt Enable Register */ + case 0xFF: + gb->hram_io[IO_IE] = val; + return; + } + } + + /* Invalid writes are ignored. */ + return; +} + +uint8_t __gb_execute_cb(struct gb_s *gb) +{ + uint8_t inst_cycles; + uint8_t cbop = __gb_read(gb, gb->cpu_reg.pc.reg++); + uint8_t r = (cbop & 0x7); + uint8_t b = (cbop >> 3) & 0x7; + uint8_t d = (cbop >> 3) & 0x1; + uint8_t val; + uint8_t writeback = 1; + + inst_cycles = 8; + /* Add an additional 8 cycles to these sets of instructions. */ + switch(cbop & 0xC7) + { + case 0x06: + case 0x86: + case 0xC6: + inst_cycles += 8; + break; + case 0x46: + inst_cycles += 4; + break; + } + + switch(r) + { + case 0: + val = gb->cpu_reg.bc.bytes.b; + break; + + case 1: + val = gb->cpu_reg.bc.bytes.c; + break; + + case 2: + val = gb->cpu_reg.de.bytes.d; + break; + + case 3: + val = gb->cpu_reg.de.bytes.e; + break; + + case 4: + val = gb->cpu_reg.hl.bytes.h; + break; + + case 5: + val = gb->cpu_reg.hl.bytes.l; + break; + + case 6: + val = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + /* Only values 0-7 are possible here, so we make the final case + * default to satisfy -Wmaybe-uninitialized warning. */ + default: + val = gb->cpu_reg.a; + break; + } + + /* TODO: Find out WTF this is doing. */ + switch(cbop >> 6) + { + case 0x0: + cbop = (cbop >> 4) & 0x3; + + switch(cbop) + { + case 0x0: /* RdC R */ + case 0x1: /* Rd R */ + if(d) /* RRC R / RR R */ + { + uint8_t temp = val; + val = (val >> 1); + val |= cbop ? (gb->cpu_reg.f_bits.c << 7) : (temp << 7); + gb->cpu_reg.f_bits.z = (val == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = (temp & 0x01); + } + else /* RLC R / RL R */ + { + uint8_t temp = val; + val = (val << 1); + val |= cbop ? gb->cpu_reg.f_bits.c : (temp >> 7); + gb->cpu_reg.f_bits.z = (val == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = (temp >> 7); + } + + break; + + case 0x2: + if(d) /* SRA R */ + { + gb->cpu_reg.f_bits.c = val & 0x01; + val = (val >> 1) | (val & 0x80); + gb->cpu_reg.f_bits.z = (val == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + } + else /* SLA R */ + { + gb->cpu_reg.f_bits.c = (val >> 7); + val = val << 1; + gb->cpu_reg.f_bits.z = (val == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + } + + break; + + case 0x3: + if(d) /* SRL R */ + { + gb->cpu_reg.f_bits.c = val & 0x01; + val = val >> 1; + gb->cpu_reg.f_bits.z = (val == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + } + else /* SWAP R */ + { + uint8_t temp = (val >> 4) & 0x0F; + temp |= (val << 4) & 0xF0; + val = temp; + gb->cpu_reg.f_bits.z = (val == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = 0; + } + + break; + } + + break; + + case 0x1: /* BIT B, R */ + gb->cpu_reg.f_bits.z = !((val >> b) & 0x1); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 1; + writeback = 0; + break; + + case 0x2: /* RES B, R */ + val &= (0xFE << b) | (0xFF >> (8 - b)); + break; + + case 0x3: /* SET B, R */ + val |= (0x1 << b); + break; + } + + if(writeback) + { + switch(r) + { + case 0: + gb->cpu_reg.bc.bytes.b = val; + break; + + case 1: + gb->cpu_reg.bc.bytes.c = val; + break; + + case 2: + gb->cpu_reg.de.bytes.d = val; + break; + + case 3: + gb->cpu_reg.de.bytes.e = val; + break; + + case 4: + gb->cpu_reg.hl.bytes.h = val; + break; + + case 5: + gb->cpu_reg.hl.bytes.l = val; + break; + + case 6: + __gb_write(gb, gb->cpu_reg.hl.reg, val); + break; + + case 7: + gb->cpu_reg.a = val; + break; + } + } + return inst_cycles; +} + +#if ENABLE_LCD +struct sprite_data { + uint8_t sprite_number; + uint8_t x; +}; + +#if PEANUT_GB_HIGH_LCD_ACCURACY +static int compare_sprites(const void *in1, const void *in2) +{ + const struct sprite_data *sd1, *sd2; + int x_res; + + sd1 = (struct sprite_data *)in1; + sd2 = (struct sprite_data *)in2; + x_res = (int)sd1->x - (int)sd2->x; + if(x_res != 0) + return x_res; + + return (int)sd1->sprite_number - (int)sd2->sprite_number; +} +#endif + +#ifdef PGB_FAST_LINE +/* Paramix test38: background and window a tile at a time (8 dots from one table lookup per byte) */ +static const uint16_t pgb_spread[256] = { +#define S1(t) (uint16_t)(((t)&1)|((t)&2)<<1|((t)&4)<<2|((t)&8)<<3|((t)&16)<<4|((t)&32)<<5|((t)&64)<<6|((t)&128)<<7) +#define S4(t) S1(t),S1(t+1),S1(t+2),S1(t+3) +#define S16(t) S4(t),S4(t+4),S4(t+8),S4(t+12) +#define S64(t) S16(t),S16(t+16),S16(t+32),S16(t+48) + S64(0),S64(64),S64(128),S64(192) +#undef S1 +#undef S4 +#undef S16 +#undef S64 +}; +/* palette as four dots per byte of the index (leftmost dot in the top bits), rebuilt when BGP changes */ +static uint32_t pgb_pal4[256], pgb_pal4_key = 0xFFFFFFFFu; +static void pgb_pal4_check(struct gb_s *gb) +{ + const uint8_t *p = gb->display.bg_palette; + uint32_t key = p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; + if(key == pgb_pal4_key) return; + pgb_pal4_key = key; + for(unsigned i = 0; i < 256; i++) + { + uint32_t v = p[i >> 6] | p[(i >> 4) & 3] << 8 | p[(i >> 2) & 3] << 16 | (uint32_t)p[i & 3] << 24; +#if PEANUT_GB_12_COLOUR + v |= LCD_PALETTE_BG * 0x01010101u; +#endif + pgb_pal4[i] = v; + } +} +/* whole tiles from pix (may start up to 7 dots left of the line and end up to 7 dots right of it) */ +static void pgb_tiles(struct gb_s *gb, uint8_t *pix, unsigned ntiles, uint16_t map, uint8_t tx, uint8_t py) +{ + const uint8_t sel = gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT; + const uint8_t *vr = gb->vram; + for(; ntiles; ntiles--, tx = (tx + 1) & 31, pix += 8) + { + uint8_t idx = vr[map + tx]; + const uint8_t *t = vr + (sel ? VRAM_TILES_1 + idx * 0x10 : VRAM_TILES_2 + ((idx + 0x80) & 0xFF) * 0x10) + 2 * py; + uint32_t w = pgb_spread[t[0]] | (uint32_t)pgb_spread[t[1]] << 1; + uint32_t v0 = pgb_pal4[w >> 8], v1 = pgb_pal4[w & 0xFF]; + __builtin_memcpy(pix, &v0, 4); + __builtin_memcpy(pix + 4, &v1, 4); + } +} +#endif + +#ifdef PGB_FAST_CGB +/* Paramix: a tile row byte to its 8 dots (left first): bits as bytes 0/1 in two words, and the byte reversed */ +#define PGB_S4(b) ((((b) >> 3) & 1u) | (((b) >> 2) & 1u) << 8 | (((b) >> 1) & 1u) << 16 | ((b) & 1u) << 24) +#define PGB_SP(b) { PGB_S4((b) >> 4), PGB_S4((b) & 15) } +#define PGB_SP4(b) PGB_SP(b), PGB_SP(b + 1), PGB_SP(b + 2), PGB_SP(b + 3) +#define PGB_SP16(b) PGB_SP4(b), PGB_SP4(b + 4), PGB_SP4(b + 8), PGB_SP4(b + 12) +#define PGB_SP64(b) PGB_SP16(b), PGB_SP16(b + 16), PGB_SP16(b + 32), PGB_SP16(b + 48) +static const uint32_t pgb_spread[256][2] = { PGB_SP64(0), PGB_SP64(64), PGB_SP64(128), PGB_SP64(192) }; +#define PGB_RV(b) (uint8_t)((((b) & 1) << 7) | (((b) & 2) << 5) | (((b) & 4) << 3) | (((b) & 8) << 1) | (((b) & 16) >> 1) | (((b) & 32) >> 3) | (((b) & 64) >> 5) | (((b) & 128) >> 7)) +#define PGB_RV4(b) PGB_RV(b), PGB_RV(b + 1), PGB_RV(b + 2), PGB_RV(b + 3) +#define PGB_RV16(b) PGB_RV4(b), PGB_RV4(b + 4), PGB_RV4(b + 8), PGB_RV4(b + 12) +#define PGB_RV64(b) PGB_RV16(b), PGB_RV16(b + 16), PGB_RV16(b + 32), PGB_RV16(b + 48) +static const uint8_t pgb_rev[256] = { PGB_RV64(0), PGB_RV64(64), PGB_RV64(128), PGB_RV64(192) }; +/* one background or window tile (map entry at vram[m], its attributes in bank 1) into 8 dots and their priority */ +static inline void pgb_ctile(struct gb_s *gb, uint8_t *d, uint8_t *pr, uint16_t m, uint8_t py) +{ + uint8_t idx = gb->vram[m], att = gb->vram[m + 0x2000]; + uint16_t tile = (gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) ? VRAM_TILES_1 + idx * 0x10 : VRAM_TILES_2 + ((idx + 0x80) & 0xFF) * 0x10; + if(att & 0x08) tile += 0x2000; + tile += 2 * ((att & 0x40) ? 7 - py : py); + uint8_t b1 = gb->vram[tile], b2 = gb->vram[tile + 1]; + if(att & 0x20) { b1 = pgb_rev[b1]; b2 = pgb_rev[b2]; } + uint32_t pal = (uint32_t)((att & 7) << 2) * 0x01010101u, pv = (uint32_t)(att >> 7) * 0x01010101u; + uint32_t lo = pgb_spread[b1][0] | pgb_spread[b2][0] << 1 | pal, hi = pgb_spread[b1][1] | pgb_spread[b2][1] << 1 | pal; + __builtin_memcpy(d, &lo, 4); __builtin_memcpy(d + 4, &hi, 4); + __builtin_memcpy(pr, &pv, 4); __builtin_memcpy(pr + 4, &pv, 4); +} +#endif +void __gb_draw_line(struct gb_s *gb) +{ +#ifdef PGB_FAST_LINE + uint32_t pixw[44]; /* 8 dots spare on each side for whole tiles */ + uint8_t *const pixels = (uint8_t *)pixw + 8; +#elif defined(PGB_FAST_CGB) + uint32_t pixw[44], priw[44]; /* Paramix: 8 dots spare on each side for whole tiles */ + uint8_t *const pixels = (uint8_t *)pixw + 8; +#else + uint8_t pixels[160] = {0}; +#endif + + /* If LCD not initialised by front-end, don't render anything. */ + if(gb->display.lcd_draw_line == NULL) + return; + + if(gb->direct.frame_skip && !gb->display.frame_skip_count) + return; + +#if PEANUT_FULL_GBC_SUPPORT +#ifdef PGB_FAST_CGB + uint8_t *const pixelsPrio = (uint8_t *)priw + 8; +#else + uint8_t pixelsPrio[160] = {0}; //do these pixels have priority over OAM? +#endif +#endif + /* If interlaced mode is activated, check if we need to draw the current + * line. */ + if(gb->direct.interlace) + { + if((gb->display.interlace_count == 0 + && (gb->hram_io[IO_LY] & 1) == 0) + || (gb->display.interlace_count == 1 + && (gb->hram_io[IO_LY] & 1) == 1)) + { + /* Compensate for missing window draw if required. */ + if(gb->hram_io[IO_LCDC] & LCDC_WINDOW_ENABLE + && gb->hram_io[IO_LY] >= gb->display.WY + && gb->hram_io[IO_WX] <= 166) + gb->display.window_clear++; + + return; + } + } + +#ifdef PGB_FAST_LINE + if(!(gb->hram_io[IO_LCDC] & LCDC_BG_ENABLE)) + for(int k = 2; k < 42; k++) pixw[k] = 0; + else + { + uint8_t bg_y = gb->hram_io[IO_LY] + gb->hram_io[IO_SCY], scx = gb->hram_io[IO_SCX]; + uint16_t map = ((gb->hram_io[IO_LCDC] & LCDC_BG_MAP) ? VRAM_BMAP_2 : VRAM_BMAP_1) + (bg_y >> 3) * 0x20; + pgb_pal4_check(gb); + pgb_tiles(gb, pixels - (scx & 7), (scx & 7) ? 21 : 20, map, scx >> 3, bg_y & 7); + } + if(gb->hram_io[IO_LCDC] & LCDC_WINDOW_ENABLE + && gb->hram_io[IO_LY] >= gb->display.WY + && gb->hram_io[IO_WX] <= 166) + { + uint16_t map = ((gb->hram_io[IO_LCDC] & LCDC_WINDOW_MAP) ? VRAM_BMAP_2 : VRAM_BMAP_1) + + (gb->display.window_clear >> 3) * 0x20; + int x0 = (int)gb->hram_io[IO_WX] - 7; /* -7..159: the window's first dot (left of the line when below 0) */ + pgb_pal4_check(gb); + pgb_tiles(gb, pixels + x0, (unsigned)(160 - x0 + 7) >> 3, map, 0, gb->display.window_clear & 7); + gb->display.window_clear++; + } +#else +#ifdef PGB_FAST_CGB + if(gb->cgb.cgbMode) + { + /* Paramix: a colour game's background and window a whole tile at a time */ + uint8_t bg_y = gb->hram_io[IO_LY] + gb->hram_io[IO_SCY], scx = gb->hram_io[IO_SCX]; + uint16_t map = ((gb->hram_io[IO_LCDC] & LCDC_BG_MAP) ? VRAM_BMAP_2 : VRAM_BMAP_1) + (bg_y >> 3) * 0x20; + int x = -(int)(scx & 7); + for(uint8_t col = scx >> 3; x < LCD_WIDTH; x += 8, col = (col + 1) & 31) + pgb_ctile(gb, pixels + x, pixelsPrio + x, map + col, bg_y & 7); + if(gb->hram_io[IO_LCDC] & LCDC_WINDOW_ENABLE + && gb->hram_io[IO_LY] >= gb->display.WY + && gb->hram_io[IO_WX] <= 166) + { + uint16_t wmap = ((gb->hram_io[IO_LCDC] & LCDC_WINDOW_MAP) ? VRAM_BMAP_2 : VRAM_BMAP_1) + + (gb->display.window_clear >> 3) * 0x20; + x = (int)gb->hram_io[IO_WX] - 7; + for(uint8_t col = 0; x < LCD_WIDTH; x += 8, col++) + pgb_ctile(gb, pixels + x, pixelsPrio + x, wmap + col, gb->display.window_clear & 7); + gb->display.window_clear++; + } + } + else +#endif + { +#ifdef PGB_FAST_CGB + for(int k = 0; k < 44; k++) { pixw[k] = 0; priw[k] = 0; } +#endif + /* If background is enabled, draw it. */ +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode || gb->hram_io[IO_LCDC] & LCDC_BG_ENABLE) +#else + if(gb->hram_io[IO_LCDC] & LCDC_BG_ENABLE) +#endif + { + uint8_t bg_y, disp_x, bg_x, idx, py, px, t1, t2; + uint16_t bg_map, tile; + + /* Calculate current background line to draw. Constant because + * this function draws only this one line each time it is + * called. */ + bg_y = gb->hram_io[IO_LY] + gb->hram_io[IO_SCY]; + + /* Get selected background map address for first tile + * corresponding to current line. + * 0x20 (32) is the width of a background tile, and the bit + * shift is to calculate the address. */ + bg_map = + ((gb->hram_io[IO_LCDC] & LCDC_BG_MAP) ? + VRAM_BMAP_2 : VRAM_BMAP_1) + + (bg_y >> 3) * 0x20; + + /* The displays (what the player sees) X coordinate, drawn right + * to left. */ + disp_x = LCD_WIDTH - 1; + + /* The X coordinate to begin drawing the background at. */ + bg_x = disp_x + gb->hram_io[IO_SCX]; + + /* Get tile index for current background tile. */ + idx = gb->vram[bg_map + (bg_x >> 3)]; +#if PEANUT_FULL_GBC_SUPPORT + uint8_t idxAtt = gb->vram[bg_map + (bg_x >> 3) + 0x2000]; +#endif + /* Y coordinate of tile pixel to draw. */ + py = (bg_y & 0x07); + /* X coordinate of tile pixel to draw. */ + px = 7 - (bg_x & 0x07); + + /* Select addressing mode. */ + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) + { + if(idxAtt & 0x08) tile += 0x2000; //VRAM bank 2 + if(idxAtt & 0x40) tile += 2 * (7 - py); + } + if(!(idxAtt & 0x40)) + { + tile += 2 * py; + } + + /* fetch first tile */ + if(gb->cgb.cgbMode && (idxAtt & 0x20)) + { //Horizantal Flip + t1 = gb->vram[tile] << px; + t2 = gb->vram[tile + 1] << px; + } + else + { + t1 = gb->vram[tile] >> px; + t2 = gb->vram[tile + 1] >> px; + } +#else + tile += 2 * py; + + /* fetch first tile */ + t1 = gb->vram[tile] >> px; + t2 = gb->vram[tile + 1] >> px; +#endif + for(; disp_x != 0xFF; disp_x--) + { + uint8_t c; + + if(px == 8) + { + /* fetch next tile */ + px = 0; + bg_x = disp_x + gb->hram_io[IO_SCX]; + idx = gb->vram[bg_map + (bg_x >> 3)]; +#if PEANUT_FULL_GBC_SUPPORT + idxAtt = gb->vram[bg_map + (bg_x >> 3) + 0x2000]; +#endif + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) + { + if(idxAtt & 0x08) tile += 0x2000; //VRAM bank 2 + if(idxAtt & 0x40) tile += 2 * (7 - py); + } + if(!(idxAtt & 0x40)) + { + tile += 2 * py; + } +#else + tile += 2 * py; +#endif + t1 = gb->vram[tile]; + t2 = gb->vram[tile + 1]; + } + + /* copy background */ +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode && (idxAtt & 0x20)) + { //Horizantal Flip + c = (((t1 & 0x80) >> 1) | (t2 & 0x80)) >> 6; + pixels[disp_x] = ((idxAtt & 0x07) << 2) + c; + pixelsPrio[disp_x] = (idxAtt >> 7); + t1 = t1 << 1; + t2 = t2 << 1; + } + else + { + c = (t1 & 0x1) | ((t2 & 0x1) << 1); + if(gb->cgb.cgbMode) + { + pixels[disp_x] = ((idxAtt & 0x07) << 2) + c; + pixelsPrio[disp_x] = (idxAtt >> 7); + } + else + { + pixels[disp_x] = gb->display.bg_palette[c]; +#if PEANUT_GB_12_COLOUR + pixels[disp_x] |= LCD_PALETTE_BG; +#endif + } + t1 = t1 >> 1; + t2 = t2 >> 1; + } +#else + c = (t1 & 0x1) | ((t2 & 0x1) << 1); + pixels[disp_x] = gb->display.bg_palette[c]; +#if PEANUT_GB_12_COLOUR + pixels[disp_x] |= LCD_PALETTE_BG; +#endif + t1 = t1 >> 1; + t2 = t2 >> 1; +#endif + px++; + } + } + + /* draw window */ + if(gb->hram_io[IO_LCDC] & LCDC_WINDOW_ENABLE + && gb->hram_io[IO_LY] >= gb->display.WY + && gb->hram_io[IO_WX] <= 166) + { + uint16_t win_line, tile; + uint8_t disp_x, win_x, py, px, idx, t1, t2, end; + + /* Calculate Window Map Address. */ + win_line = (gb->hram_io[IO_LCDC] & LCDC_WINDOW_MAP) ? + VRAM_BMAP_2 : VRAM_BMAP_1; + win_line += (gb->display.window_clear >> 3) * 0x20; + + disp_x = LCD_WIDTH - 1; + win_x = disp_x - gb->hram_io[IO_WX] + 7; + + // look up tile + py = gb->display.window_clear & 0x07; + px = 7 - (win_x & 0x07); + idx = gb->vram[win_line + (win_x >> 3)]; +#if PEANUT_FULL_GBC_SUPPORT + uint8_t idxAtt = gb->vram[win_line + (win_x >> 3) + 0x2000]; +#endif + + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) + { + if(idxAtt & 0x08) tile += 0x2000; //VRAM bank 2 + if(idxAtt & 0x40) tile += 2 * (7 - py); + } + if(!(idxAtt & 0x40)) + { + tile += 2 * py; + } + + // fetch first tile + if(gb->cgb.cgbMode && (idxAtt & 0x20)) + { //Horizantal Flip + t1 = gb->vram[tile] << px; + t2 = gb->vram[tile + 1] << px; + } + else + { + t1 = gb->vram[tile] >> px; + t2 = gb->vram[tile + 1] >> px; + } +#else + tile += 2 * py; + + // fetch first tile + t1 = gb->vram[tile] >> px; + t2 = gb->vram[tile + 1] >> px; +#endif + // loop & copy window + end = (gb->hram_io[IO_WX] < 7 ? 0 : gb->hram_io[IO_WX] - 7) - 1; + + for(; disp_x != end; disp_x--) + { + uint8_t c; + + if(px == 8) + { + // fetch next tile + px = 0; + win_x = disp_x - gb->hram_io[IO_WX] + 7; + idx = gb->vram[win_line + (win_x >> 3)]; +#if PEANUT_FULL_GBC_SUPPORT + idxAtt = gb->vram[win_line + (win_x >> 3) + 0x2000]; +#endif + + if(gb->hram_io[IO_LCDC] & LCDC_TILE_SELECT) + tile = VRAM_TILES_1 + idx * 0x10; + else + tile = VRAM_TILES_2 + ((idx + 0x80) % 0x100) * 0x10; + +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) + { + if(idxAtt & 0x08) tile += 0x2000; //VRAM bank 2 + if(idxAtt & 0x40) tile += 2 * (7 - py); + } + if(!(idxAtt & 0x40)) + { + tile += 2 * py; + } +#else + tile += 2 * py; +#endif + t1 = gb->vram[tile]; + t2 = gb->vram[tile + 1]; + } + + // copy window +#if PEANUT_FULL_GBC_SUPPORT + if(idxAtt & 0x20) + { //Horizantal Flip + c = (((t1 & 0x80) >> 1) | (t2 & 0x80)) >> 6; + pixels[disp_x] = ((idxAtt & 0x07) << 2) + c; + pixelsPrio[disp_x] = (idxAtt >> 7); + t1 = t1 << 1; + t2 = t2 << 1; + } + else + { + c = (t1 & 0x1) | ((t2 & 0x1) << 1); + if(gb->cgb.cgbMode) + { + pixels[disp_x] = ((idxAtt & 0x07) << 2) + c; + pixelsPrio[disp_x] = (idxAtt >> 7); + } + else + { + pixels[disp_x] = gb->display.bg_palette[c]; +#if PEANUT_GB_12_COLOUR + pixels[disp_x] |= LCD_PALETTE_BG; +#endif + } + t1 = t1 >> 1; + t2 = t2 >> 1; + } +#else + c = (t1 & 0x1) | ((t2 & 0x1) << 1); + pixels[disp_x] = gb->display.bg_palette[c]; +#if PEANUT_GB_12_COLOUR + pixels[disp_x] |= LCD_PALETTE_BG; +#endif + t1 = t1 >> 1; + t2 = t2 >> 1; +#endif + px++; + } + + gb->display.window_clear++; // advance window line + } + } +#endif + + // draw sprites + if(gb->hram_io[IO_LCDC] & LCDC_OBJ_ENABLE) + { + uint8_t sprite_number; +#if PEANUT_GB_HIGH_LCD_ACCURACY + uint8_t number_of_sprites = 0; + + struct sprite_data sprites_to_render[NUM_SPRITES]; + + /* Record number of sprites on the line being rendered, limited + * to the maximum number sprites that the Game Boy is able to + * render on each line (10 sprites). */ + for(sprite_number = 0; + sprite_number < PEANUT_GB_ARRAYSIZE(sprites_to_render); + sprite_number++) + { + /* Sprite Y position. */ + uint8_t OY = gb->oam[4 * sprite_number + 0]; + /* Sprite X position. */ + uint8_t OX = gb->oam[4 * sprite_number + 1]; + + /* If sprite isn't on this line, continue. */ + if(gb->hram_io[IO_LY] + + (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 0 : 8) >= OY + || gb->hram_io[IO_LY] + 16 < OY) + continue; + + + sprites_to_render[number_of_sprites].sprite_number = sprite_number; + sprites_to_render[number_of_sprites].x = OX; + number_of_sprites++; + } +#if PEANUT_FULL_GBC_SUPPORT + if(!gb->cgb.cgbMode) + { +#endif + /* If maximum number of sprites reached, prioritise X + * coordinate and object location in OAM. */ + qsort(&sprites_to_render[0], number_of_sprites, + sizeof(sprites_to_render[0]), compare_sprites); +#if PEANUT_FULL_GBC_SUPPORT + } +#endif + if(number_of_sprites > MAX_SPRITES_LINE) + number_of_sprites = MAX_SPRITES_LINE; +#endif + + /* Render each sprite, from low priority to high priority. */ +#if PEANUT_GB_HIGH_LCD_ACCURACY + /* Render the top ten prioritised sprites on this scanline. */ + for(sprite_number = number_of_sprites - 1; + sprite_number != 0xFF; + sprite_number--) + { + uint8_t s = sprites_to_render[sprite_number].sprite_number; +#else + for (sprite_number = NUM_SPRITES - 1; + sprite_number != 0xFF; + sprite_number--) + { + uint8_t s = sprite_number; +#endif + uint8_t py, t1, t2, dir, start, end, shift, disp_x; + /* Sprite Y position. */ + uint8_t OY = gb->oam[4 * s + 0]; + /* Sprite X position. */ + uint8_t OX = gb->oam[4 * s + 1]; + /* Sprite Tile/Pattern Number. */ + uint8_t OT = gb->oam[4 * s + 2] + & (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 0xFE : 0xFF); + /* Additional attributes. */ + uint8_t OF = gb->oam[4 * s + 3]; + +#if !PEANUT_GB_HIGH_LCD_ACCURACY + /* If sprite isn't on this line, continue. */ + if(gb->hram_io[IO_LY] + + (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 0 : 8) >= OY || + gb->hram_io[IO_LY] + 16 < OY) + continue; +#endif + + /* Continue if sprite not visible. */ + if(OX == 0 || OX >= 168) + continue; + + // y flip + py = gb->hram_io[IO_LY] - OY + 16; + + if(OF & OBJ_FLIP_Y) + py = (gb->hram_io[IO_LCDC] & LCDC_OBJ_SIZE ? 15 : 7) - py; + + // fetch the tile +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) + { + t1 = gb->vram[((OF & OBJ_BANK) << 10) + VRAM_TILES_1 + OT * 0x10 + 2 * py]; + t2 = gb->vram[((OF & OBJ_BANK) << 10) + VRAM_TILES_1 + OT * 0x10 + 2 * py + 1]; + } + else +#endif + { + t1 = gb->vram[VRAM_TILES_1 + OT * 0x10 + 2 * py]; + t2 = gb->vram[VRAM_TILES_1 + OT * 0x10 + 2 * py + 1]; + } + + // handle x flip + if(OF & OBJ_FLIP_X) + { + dir = 1; + start = (OX < 8 ? 0 : OX - 8); + end = MIN(OX, LCD_WIDTH); + shift = 8 - OX + start; + } + else + { + dir = (uint8_t)-1; + start = MIN(OX, LCD_WIDTH) - 1; + end = (OX < 8 ? 0 : OX - 8) - 1; + shift = OX - (start + 1); + } + + // copy tile + t1 >>= shift; + t2 >>= shift; + + /* TODO: Put for loop within the to if statements + * because the BG priority bit will be the same for + * all the pixels in the tile. */ + for(disp_x = start; disp_x != end; disp_x += dir) + { + uint8_t c = (t1 & 0x1) | ((t2 & 0x1) << 1); + // check transparency / sprite overlap / background overlap +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) + { + uint8_t isBackgroundDisabled = c && !(gb->hram_io[IO_LCDC] & LCDC_BG_ENABLE); + uint8_t isPixelPriorityNonConflicting = c && + !(pixelsPrio[disp_x] && (pixels[disp_x] & 0x3)) && + !((OF & OBJ_PRIORITY) && (pixels[disp_x] & 0x3)); + + if(isBackgroundDisabled || isPixelPriorityNonConflicting) + { + /* Set pixel colour. */ + pixels[disp_x] = ((OF & OBJ_CGB_PALETTE) << 2) + c + 0x20; // add 0x20 to differentiate from BG + } + } + else +#endif + if(c && !(OF & OBJ_PRIORITY && !((pixels[disp_x] & 0x3) == gb->display.bg_palette[0]))) + { + /* Set pixel colour. */ + pixels[disp_x] = (OF & OBJ_PALETTE) + ? gb->display.sp_palette[c + 4] + : gb->display.sp_palette[c]; +#if PEANUT_GB_12_COLOUR + /* Set pixel palette (OBJ0 or OBJ1). */ + pixels[disp_x] |= (OF & OBJ_PALETTE); +#endif +#if PEANUT_FULL_GBC_SUPPORT + /* Deselect BG palette. */ + pixels[disp_x] &= ~LCD_PALETTE_BG; +#endif + } + + t1 = t1 >> 1; + t2 = t2 >> 1; + } + } + } + + gb->display.lcd_draw_line(gb, pixels, gb->hram_io[IO_LY]); +} +#endif + +/** + * Internal function used to step the CPU. + */ +#ifdef PGB_BATCH +static const uint_fast16_t PGB_TAC_CYCLES[4] = {1024, 16, 64, 256}; +/* Paramix PGB_BATCH: the timers and the LCD for inst_cycles cycles (the part of __gb_step_cpu after an instruction). + * Returns the cycles (changed while halted, to jump to the next LCD mode). */ +static uint_fast16_t __gb_tick(struct gb_s *gb, uint_fast16_t inst_cycles) +{ + const uint_fast16_t *TAC_CYCLES = PGB_TAC_CYCLES; + /* DIV register timing */ + gb->counter.div_count += inst_cycles; + while(gb->counter.div_count >= DIV_CYCLES) + { + gb->hram_io[IO_DIV]++; + gb->counter.div_count -= DIV_CYCLES; + } + + /* Check serial transmission. */ + if(gb->hram_io[IO_SC] & SERIAL_SC_TX_START) + { + unsigned int serial_cycles = SERIAL_CYCLES_1KB; + + /* If new transfer, call TX function. */ + if(gb->counter.serial_count == 0 && + gb->gb_serial_tx != NULL) + (gb->gb_serial_tx)(gb, gb->hram_io[IO_SB]); + +#if PEANUT_FULL_GBC_SUPPORT + if(gb->hram_io[IO_SC] & 0x3) + serial_cycles = SERIAL_CYCLES_32KB; +#endif + + gb->counter.serial_count += inst_cycles; + + /* If it's time to receive byte, call RX function. */ + if(gb->counter.serial_count >= serial_cycles) + { + /* If RX can be done, do it. */ + /* If RX failed, do not change SB if using external + * clock, or set to 0xFF if using internal clock. */ + uint8_t rx; +#ifdef PGB_SERIAL_WAIT + enum gb_serial_rx_ret_e rr = gb->gb_serial_rx != NULL ? gb->gb_serial_rx(gb, &rx) : GB_SERIAL_RX_NO_CONNECTION; + if(rr == GB_SERIAL_RX_WAIT) + { + /* Paramix: keep the transfer just before its end (asked again after the next + * instruction; a HALT waits 4 cycles at a time), nothing changes yet */ + gb->counter.serial_count = SERIAL_CYCLES - 4; + } + else if(rr == GB_SERIAL_RX_SUCCESS) +#else + if(gb->gb_serial_rx != NULL && + (gb->gb_serial_rx(gb, &rx) == + GB_SERIAL_RX_SUCCESS)) +#endif + { + gb->hram_io[IO_SB] = rx; + + /* Inform game of serial TX/RX completion. */ + gb->hram_io[IO_SC] &= 0x01; + gb->hram_io[IO_IF] |= SERIAL_INTR; + } + else if(gb->hram_io[IO_SC] & SERIAL_SC_CLOCK_SRC) + { + /* If using internal clock, and console is not + * attached to any external peripheral, shifted + * bits are replaced with logic 1. */ + gb->hram_io[IO_SB] = 0xFF; + + /* Inform game of serial TX/RX completion. */ + gb->hram_io[IO_SC] &= 0x01; + gb->hram_io[IO_IF] |= SERIAL_INTR; + } + else + { + /* If using external clock, and console is not + * attached to any external peripheral, bits are + * not shifted, so SB is not modified. */ + } + +#ifdef PGB_SERIAL_WAIT + if(rr != GB_SERIAL_RX_WAIT) +#endif + gb->counter.serial_count = 0; + } + } + + /* TIMA register timing */ + /* TODO: Change tac_enable to struct of TAC timer control bits. */ + if(gb->hram_io[IO_TAC] & IO_TAC_ENABLE_MASK) + { + gb->counter.tima_count += inst_cycles; + + while(gb->counter.tima_count >= + TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK]) + { + gb->counter.tima_count -= + TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK]; + + if(++gb->hram_io[IO_TIMA] == 0) + { + gb->hram_io[IO_IF] |= TIMER_INTR; + /* On overflow, set TMA to TIMA. */ + gb->hram_io[IO_TIMA] = gb->hram_io[IO_TMA]; + } + } + } + + /* If LCD is off, don't update LCD state or increase the LCD + * ticks. */ + if(!(gb->hram_io[IO_LCDC] & LCDC_ENABLE)) + return inst_cycles; + + /* LCD Timing */ +#if PEANUT_FULL_GBC_SUPPORT + if (inst_cycles > 1) + gb->counter.lcd_count += (inst_cycles >> gb->cgb.doubleSpeed); + else +#endif + gb->counter.lcd_count += inst_cycles; + + /* New Scanline */ + if(gb->counter.lcd_count >= LCD_LINE_CYCLES) + { + gb->counter.lcd_count -= LCD_LINE_CYCLES; + + /* Next line */ + gb->hram_io[IO_LY] = (gb->hram_io[IO_LY] + 1) % LCD_VERT_LINES; + + /* LYC Update */ + if(gb->hram_io[IO_LY] == gb->hram_io[IO_LYC]) + { + gb->hram_io[IO_STAT] |= STAT_LYC_COINC; + + if(gb->hram_io[IO_STAT] & STAT_LYC_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + } + else + gb->hram_io[IO_STAT] &= 0xFB; + + /* VBLANK Start */ + if(gb->hram_io[IO_LY] == LCD_HEIGHT) + { + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_VBLANK; + gb->gb_frame = 1; + gb->hram_io[IO_IF] |= VBLANK_INTR; + gb->lcd_blank = 0; + + if(gb->hram_io[IO_STAT] & STAT_MODE_1_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + +#if ENABLE_LCD + /* If frame skip is activated, check if we need to draw + * the frame or skip it. */ + if(gb->direct.frame_skip) + { + gb->display.frame_skip_count = + !gb->display.frame_skip_count; + } + + /* If interlaced is activated, change which lines get + * updated. Also, only update lines on frames that are + * actually drawn when frame skip is enabled. */ + if(gb->direct.interlace && + (!gb->direct.frame_skip || + gb->display.frame_skip_count)) + { + gb->display.interlace_count = + !gb->display.interlace_count; + } +#endif + } + /* Normal Line */ + else if(gb->hram_io[IO_LY] < LCD_HEIGHT) + { + if(gb->hram_io[IO_LY] == 0) + { + /* Clear Screen */ + gb->display.WY = gb->hram_io[IO_WY]; + gb->display.window_clear = 0; + } + + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_HBLANK; + +#if PEANUT_FULL_GBC_SUPPORT + //DMA GBC + if(gb->cgb.cgbMode && !gb->cgb.dmaActive && gb->cgb.dmaMode) + { + for (uint8_t i = 0; i < 0x10; i++) + { + __gb_write(gb, ((gb->cgb.dmaDest & 0x1FF0) | 0x8000) + i, + __gb_read(gb, (gb->cgb.dmaSource & 0xFFF0) + i)); + } + gb->cgb.dmaSource += 0x10; + gb->cgb.dmaDest += 0x10; + if(!(--gb->cgb.dmaSize)) gb->cgb.dmaActive = 1; + } +#endif + if(gb->hram_io[IO_STAT] & STAT_MODE_0_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + + /* If halted immediately jump to next LCD mode. */ + if(gb->counter.lcd_count < LCD_MODE_2_CYCLES) + inst_cycles = LCD_MODE_2_CYCLES - gb->counter.lcd_count; + } + } + /* OAM access */ + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_HBLANK && + gb->counter.lcd_count >= LCD_MODE_2_CYCLES) + { + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_SEARCH_OAM; + + if(gb->hram_io[IO_STAT] & STAT_MODE_2_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + + /* If halted immediately jump to next LCD mode. */ + if (gb->counter.lcd_count < LCD_MODE_3_CYCLES) + inst_cycles = LCD_MODE_3_CYCLES - gb->counter.lcd_count; + } + /* Update LCD */ + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_SEARCH_OAM && + gb->counter.lcd_count >= LCD_MODE_3_CYCLES) + { + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_SEARCH_TRANSFER; +#if ENABLE_LCD + if(!gb->lcd_blank) + __gb_draw_line(gb); +#endif + /* If halted immediately jump to next LCD mode. */ + if (gb->counter.lcd_count < LCD_MODE_0_CYCLES) + inst_cycles = LCD_MODE_0_CYCLES - gb->counter.lcd_count; + } + return inst_cycles; +} +/* cycles until the timers or the LCD change anything a game can see without reading their registers (an interrupt + * flag, a line drawn, a frame done, a transfer); serial transfers go instruction by instruction */ +static uint_fast32_t __gb_slack(struct gb_s *gb) +{ + uint_fast32_t s = 0xFFFFu; + if(gb->hram_io[IO_SC] & SERIAL_SC_TX_START) + { + /* a transfer: the next look at the other side (sending starts at the first hand-over) */ + uint_fast32_t sc = SERIAL_CYCLES_1KB; +#if PEANUT_FULL_GBC_SUPPORT + if(gb->hram_io[IO_SC] & 0x3) + sc = SERIAL_CYCLES_32KB; +#endif + if(gb->counter.serial_count == 0 || gb->counter.serial_count >= sc) + return 0; + s = sc - gb->counter.serial_count; +#ifdef PGB_SERIAL_WAIT + if(s <= 4) + s = 64; /* waiting for the other side: asked every 64 cycles */ +#endif + } + if(gb->hram_io[IO_TAC] & IO_TAC_ENABLE_MASK) + { + uint_fast32_t t = PGB_TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK]; + uint_fast32_t c = (t > gb->counter.tima_count ? t - gb->counter.tima_count : 0) + (uint_fast32_t)(0xFF - gb->hram_io[IO_TIMA]) * t; + if(c < s) s = c; + } + if(gb->hram_io[IO_LCDC] & LCDC_ENABLE) + { + uint_fast32_t lc = gb->counter.lcd_count, th; + uint8_t m = gb->hram_io[IO_STAT] & STAT_MODE; + if(m == IO_STAT_MODE_HBLANK && lc >= LCD_MODE_2_CYCLES) return 0; + if(m == IO_STAT_MODE_SEARCH_OAM && lc >= LCD_MODE_3_CYCLES) return 0; + if(m == IO_STAT_MODE_HBLANK) th = LCD_MODE_2_CYCLES; + else if(m == IO_STAT_MODE_SEARCH_OAM) th = LCD_MODE_3_CYCLES; + else th = LCD_LINE_CYCLES; + if(th <= lc) return 0; +#if PEANUT_FULL_GBC_SUPPORT + th = (th - lc) << gb->cgb.doubleSpeed; +#else + th = th - lc; +#endif + if(th < s) s = th; + } + return s; +} +static void __gb_flush(struct gb_s *gb) +{ + uint_fast32_t p = gb->counter.pend; + gb->counter.pend = 0; + __gb_tick(gb, (uint_fast16_t)p); +} +#endif +void __gb_step_cpu(struct gb_s *gb) +{ + uint8_t opcode; + uint_fast16_t inst_cycles; + static const uint8_t op_cycles[0x100] = + { + /* *INDENT-OFF* */ + /*0 1 2 3 4 5 6 7 8 9 A B C D E F */ + 4,12, 8, 8, 4, 4, 8, 4,20, 8, 8, 8, 4, 4, 8, 4, /* 0x00 */ + 4,12, 8, 8, 4, 4, 8, 4,12, 8, 8, 8, 4, 4, 8, 4, /* 0x10 */ + 8,12, 8, 8, 4, 4, 8, 4, 8, 8, 8, 8, 4, 4, 8, 4, /* 0x20 */ + 8,12, 8, 8,12,12,12, 4, 8, 8, 8, 8, 4, 4, 8, 4, /* 0x30 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x40 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x50 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x60 */ + 8, 8, 8, 8, 8, 8, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x70 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x80 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0x90 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0xA0 */ + 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, /* 0xB0 */ + 8,12,12,16,12,16, 8,16, 8,16,12, 8,12,24, 8,16, /* 0xC0 */ + 8,12,12, 0,12,16, 8,16, 8,16,12, 0,12, 0, 8,16, /* 0xD0 */ + 12,12,8, 0, 0,16, 8,16,16, 4,16, 0, 0, 0, 8,16, /* 0xE0 */ + 12,12,8, 4, 0,16, 8,16,12, 8,16, 4, 0, 0, 8,16 /* 0xF0 */ + /* *INDENT-ON* */ + }; + static const uint_fast16_t TAC_CYCLES[4] = {1024, 16, 64, 256}; + + /* Handle interrupts */ + /* If gb_halt is positive, then an interrupt must have occured by the + * time we reach here, becuase on HALT, we jump to the next interrupt + * immediately. */ + while(gb->gb_halt || (gb->gb_ime && + gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & ANY_INTR)) + { + gb->gb_halt = 0; + + if(!gb->gb_ime) + break; + + /* Disable interrupts */ + gb->gb_ime = 0; + + /* Push Program Counter */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + + /* Call interrupt handler if required. */ + if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & VBLANK_INTR) + { + gb->cpu_reg.pc.reg = VBLANK_INTR_ADDR; + gb->hram_io[IO_IF] ^= VBLANK_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & LCDC_INTR) + { + gb->cpu_reg.pc.reg = LCDC_INTR_ADDR; + gb->hram_io[IO_IF] ^= LCDC_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & TIMER_INTR) + { + gb->cpu_reg.pc.reg = TIMER_INTR_ADDR; + gb->hram_io[IO_IF] ^= TIMER_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & SERIAL_INTR) + { + gb->cpu_reg.pc.reg = SERIAL_INTR_ADDR; + gb->hram_io[IO_IF] ^= SERIAL_INTR; + } + else if(gb->hram_io[IO_IF] & gb->hram_io[IO_IE] & CONTROL_INTR) + { + gb->cpu_reg.pc.reg = CONTROL_INTR_ADDR; + gb->hram_io[IO_IF] ^= CONTROL_INTR; + } + + break; + } + + /* Obtain opcode */ + opcode = __gb_read(gb, gb->cpu_reg.pc.reg++); + inst_cycles = op_cycles[opcode]; + + /* Execute opcode */ + switch(opcode) + { + case 0x00: /* NOP */ + break; + + case 0x01: /* LD BC, imm */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x02: /* LD (BC), A */ + __gb_write(gb, gb->cpu_reg.bc.reg, gb->cpu_reg.a); + break; + + case 0x03: /* INC BC */ + gb->cpu_reg.bc.reg++; + break; + + case 0x04: /* INC B */ + gb->cpu_reg.bc.bytes.b++; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.bc.bytes.b == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.bc.bytes.b & 0x0F) == 0x00); + break; + + case 0x05: /* DEC B */ + PGB_INSTR_DEC_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0x06: /* LD B, imm */ + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x07: /* RLCA */ + gb->cpu_reg.a = (gb->cpu_reg.a << 1) | (gb->cpu_reg.a >> 7); + gb->cpu_reg.f_bits.z = 0; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = (gb->cpu_reg.a & 0x01); + break; + + case 0x08: /* LD (imm), SP */ + { + uint8_t h, l; + uint16_t temp; + l = __gb_read(gb, gb->cpu_reg.pc.reg++); + h = __gb_read(gb, gb->cpu_reg.pc.reg++); + temp = PEANUT_GB_U8_TO_U16(h,l); + __gb_write(gb, temp++, gb->cpu_reg.sp.bytes.p); + __gb_write(gb, temp, gb->cpu_reg.sp.bytes.s); + break; + } + + case 0x09: /* ADD HL, BC */ + { + uint_fast32_t temp = gb->cpu_reg.hl.reg + gb->cpu_reg.bc.reg; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = + (temp ^ gb->cpu_reg.hl.reg ^ gb->cpu_reg.bc.reg) & 0x1000 ? 1 : 0; + gb->cpu_reg.f_bits.c = (temp & 0xFFFF0000) ? 1 : 0; + gb->cpu_reg.hl.reg = (temp & 0x0000FFFF); + break; + } + + case 0x0A: /* LD A, (BC) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.bc.reg); + break; + + case 0x0B: /* DEC BC */ + gb->cpu_reg.bc.reg--; + break; + + case 0x0C: /* INC C */ + gb->cpu_reg.bc.bytes.c++; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.bc.bytes.c == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.bc.bytes.c & 0x0F) == 0x00); + break; + + case 0x0D: /* DEC C */ + PGB_INSTR_DEC_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0x0E: /* LD C, imm */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x0F: /* RRCA */ + gb->cpu_reg.f_bits.c = gb->cpu_reg.a & 0x01; + gb->cpu_reg.a = (gb->cpu_reg.a >> 1) | (gb->cpu_reg.a << 7); + gb->cpu_reg.f_bits.z = 0; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + break; + + case 0x10: /* STOP */ + //gb->gb_halt = 1; +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode & gb->cgb.doubleSpeedPrep) + { +#ifdef PGB_BATCH + if(gb->counter.pend) __gb_flush(gb); /* the cycles before at the old speed */ + gb->counter.slack = 0; +#endif + gb->cgb.doubleSpeedPrep = 0; + gb->cgb.doubleSpeed ^= 1; + } +#endif + break; + + case 0x11: /* LD DE, imm */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x12: /* LD (DE), A */ + __gb_write(gb, gb->cpu_reg.de.reg, gb->cpu_reg.a); + break; + + case 0x13: /* INC DE */ + gb->cpu_reg.de.reg++; + break; + + case 0x14: /* INC D */ + gb->cpu_reg.de.bytes.d++; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.de.bytes.d == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.de.bytes.d & 0x0F) == 0x00); + break; + + case 0x15: /* DEC D */ + PGB_INSTR_DEC_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0x16: /* LD D, imm */ + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x17: /* RLA */ + { + uint8_t temp = gb->cpu_reg.a; + gb->cpu_reg.a = (gb->cpu_reg.a << 1) | gb->cpu_reg.f_bits.c; + gb->cpu_reg.f_bits.z = 0; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = (temp >> 7) & 0x01; + break; + } + + case 0x18: /* JR imm */ + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + break; + } + + case 0x19: /* ADD HL, DE */ + { + uint_fast32_t temp = gb->cpu_reg.hl.reg + gb->cpu_reg.de.reg; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = + (temp ^ gb->cpu_reg.hl.reg ^ gb->cpu_reg.de.reg) & 0x1000 ? 1 : 0; + gb->cpu_reg.f_bits.c = (temp & 0xFFFF0000) ? 1 : 0; + gb->cpu_reg.hl.reg = (temp & 0x0000FFFF); + break; + } + + case 0x1A: /* LD A, (DE) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.de.reg); + break; + + case 0x1B: /* DEC DE */ + gb->cpu_reg.de.reg--; + break; + + case 0x1C: /* INC E */ + gb->cpu_reg.de.bytes.e++; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.de.bytes.e == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.de.bytes.e & 0x0F) == 0x00); + break; + + case 0x1D: /* DEC E */ + PGB_INSTR_DEC_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0x1E: /* LD E, imm */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x1F: /* RRA */ + { + uint8_t temp = gb->cpu_reg.a; + gb->cpu_reg.a = gb->cpu_reg.a >> 1 | (gb->cpu_reg.f_bits.c << 7); + gb->cpu_reg.f_bits.z = 0; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = temp & 0x1; + break; + } + + case 0x20: /* JR NZ, imm */ + if(!gb->cpu_reg.f_bits.z) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x21: /* LD HL, imm */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x22: /* LDI (HL), A */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.a); + gb->cpu_reg.hl.reg++; + break; + + case 0x23: /* INC HL */ + gb->cpu_reg.hl.reg++; + break; + + case 0x24: /* INC H */ + gb->cpu_reg.hl.bytes.h++; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.hl.bytes.h == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.hl.bytes.h & 0x0F) == 0x00); + break; + + case 0x25: /* DEC H */ + PGB_INSTR_DEC_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0x26: /* LD H, imm */ + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x27: /* DAA */ + { + /* The following is from SameBoy. MIT License. */ + int16_t a = gb->cpu_reg.a; + + if(gb->cpu_reg.f_bits.n) + { + if(gb->cpu_reg.f_bits.h) + a = (a - 0x06) & 0xFF; + + if(gb->cpu_reg.f_bits.c) + a -= 0x60; + } + else + { + if(gb->cpu_reg.f_bits.h || (a & 0x0F) > 9) + a += 0x06; + + if(gb->cpu_reg.f_bits.c || a > 0x9F) + a += 0x60; + } + + if((a & 0x100) == 0x100) + gb->cpu_reg.f_bits.c = 1; + + gb->cpu_reg.a = a; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.a == 0); + gb->cpu_reg.f_bits.h = 0; + + break; + } + + case 0x28: /* JR Z, imm */ + if(gb->cpu_reg.f_bits.z) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x29: /* ADD HL, HL */ + { + gb->cpu_reg.f_bits.c = (gb->cpu_reg.hl.reg & 0x8000) > 0; + gb->cpu_reg.hl.reg <<= 1; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = (gb->cpu_reg.hl.reg & 0x1000) > 0; + break; + } + + case 0x2A: /* LD A, (HL+) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.hl.reg++); + break; + + case 0x2B: /* DEC HL */ + gb->cpu_reg.hl.reg--; + break; + + case 0x2C: /* INC L */ + gb->cpu_reg.hl.bytes.l++; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.hl.bytes.l == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.hl.bytes.l & 0x0F) == 0x00); + break; + + case 0x2D: /* DEC L */ + PGB_INSTR_DEC_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0x2E: /* LD L, imm */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x2F: /* CPL */ + gb->cpu_reg.a = ~gb->cpu_reg.a; + gb->cpu_reg.f_bits.n = 1; + gb->cpu_reg.f_bits.h = 1; + break; + + case 0x30: /* JR NC, imm */ + if(!gb->cpu_reg.f_bits.c) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x31: /* LD SP, imm */ + gb->cpu_reg.sp.bytes.p = __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.sp.bytes.s = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x32: /* LD (HL), A */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.a); + gb->cpu_reg.hl.reg--; + break; + + case 0x33: /* INC SP */ + gb->cpu_reg.sp.reg++; + break; + + case 0x34: /* INC (HL) */ + { + uint8_t temp = __gb_read(gb, gb->cpu_reg.hl.reg) + 1; + gb->cpu_reg.f_bits.z = (temp == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((temp & 0x0F) == 0x00); + __gb_write(gb, gb->cpu_reg.hl.reg, temp); + break; + } + + case 0x35: /* DEC (HL) */ + { + uint8_t temp = __gb_read(gb, gb->cpu_reg.hl.reg) - 1; + gb->cpu_reg.f_bits.z = (temp == 0x00); + gb->cpu_reg.f_bits.n = 1; + gb->cpu_reg.f_bits.h = ((temp & 0x0F) == 0x0F); + __gb_write(gb, gb->cpu_reg.hl.reg, temp); + break; + } + + case 0x36: /* LD (HL), imm */ + __gb_write(gb, gb->cpu_reg.hl.reg, __gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0x37: /* SCF */ + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = 1; + break; + + case 0x38: /* JR C, imm */ + if(gb->cpu_reg.f_bits.c) + { + int8_t temp = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.pc.reg += temp; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg++; + + break; + + case 0x39: /* ADD HL, SP */ + { + uint_fast32_t temp = gb->cpu_reg.hl.reg + gb->cpu_reg.sp.reg; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = + ((gb->cpu_reg.hl.reg & 0xFFF) + (gb->cpu_reg.sp.reg & 0xFFF)) & 0x1000 ? 1 : 0; + gb->cpu_reg.f_bits.c = temp & 0x10000 ? 1 : 0; + gb->cpu_reg.hl.reg = (uint16_t)temp; + break; + } + + case 0x3A: /* LD A, (HL) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.hl.reg--); + break; + + case 0x3B: /* DEC SP */ + gb->cpu_reg.sp.reg--; + break; + + case 0x3C: /* INC A */ + gb->cpu_reg.a++; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.a == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a & 0x0F) == 0x00); + break; + + case 0x3D: /* DEC A */ + gb->cpu_reg.a--; + gb->cpu_reg.f_bits.z = (gb->cpu_reg.a == 0x00); + gb->cpu_reg.f_bits.n = 1; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.a & 0x0F) == 0x0F); + break; + + case 0x3E: /* LD A, imm */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.pc.reg++); + break; + + case 0x3F: /* CCF */ + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = ~gb->cpu_reg.f_bits.c; + break; + + case 0x40: /* LD B, B */ + break; + + case 0x41: /* LD B, C */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.bc.bytes.c; + break; + + case 0x42: /* LD B, D */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.de.bytes.d; + break; + + case 0x43: /* LD B, E */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.de.bytes.e; + break; + + case 0x44: /* LD B, H */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.hl.bytes.h; + break; + + case 0x45: /* LD B, L */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.hl.bytes.l; + break; + + case 0x46: /* LD B, (HL) */ + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x47: /* LD B, A */ + gb->cpu_reg.bc.bytes.b = gb->cpu_reg.a; + break; + + case 0x48: /* LD C, B */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.bc.bytes.b; + break; + + case 0x49: /* LD C, C */ + break; + + case 0x4A: /* LD C, D */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.de.bytes.d; + break; + + case 0x4B: /* LD C, E */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.de.bytes.e; + break; + + case 0x4C: /* LD C, H */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.hl.bytes.h; + break; + + case 0x4D: /* LD C, L */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.hl.bytes.l; + break; + + case 0x4E: /* LD C, (HL) */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x4F: /* LD C, A */ + gb->cpu_reg.bc.bytes.c = gb->cpu_reg.a; + break; + + case 0x50: /* LD D, B */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.bc.bytes.b; + break; + + case 0x51: /* LD D, C */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.bc.bytes.c; + break; + + case 0x52: /* LD D, D */ + break; + + case 0x53: /* LD D, E */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.de.bytes.e; + break; + + case 0x54: /* LD D, H */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.hl.bytes.h; + break; + + case 0x55: /* LD D, L */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.hl.bytes.l; + break; + + case 0x56: /* LD D, (HL) */ + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x57: /* LD D, A */ + gb->cpu_reg.de.bytes.d = gb->cpu_reg.a; + break; + + case 0x58: /* LD E, B */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.bc.bytes.b; + break; + + case 0x59: /* LD E, C */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.bc.bytes.c; + break; + + case 0x5A: /* LD E, D */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.de.bytes.d; + break; + + case 0x5B: /* LD E, E */ + break; + + case 0x5C: /* LD E, H */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.hl.bytes.h; + break; + + case 0x5D: /* LD E, L */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.hl.bytes.l; + break; + + case 0x5E: /* LD E, (HL) */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x5F: /* LD E, A */ + gb->cpu_reg.de.bytes.e = gb->cpu_reg.a; + break; + + case 0x60: /* LD H, B */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.bc.bytes.b; + break; + + case 0x61: /* LD H, C */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.bc.bytes.c; + break; + + case 0x62: /* LD H, D */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.de.bytes.d; + break; + + case 0x63: /* LD H, E */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.de.bytes.e; + break; + + case 0x64: /* LD H, H */ + break; + + case 0x65: /* LD H, L */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.hl.bytes.l; + break; + + case 0x66: /* LD H, (HL) */ + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x67: /* LD H, A */ + gb->cpu_reg.hl.bytes.h = gb->cpu_reg.a; + break; + + case 0x68: /* LD L, B */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.bc.bytes.b; + break; + + case 0x69: /* LD L, C */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.bc.bytes.c; + break; + + case 0x6A: /* LD L, D */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.de.bytes.d; + break; + + case 0x6B: /* LD L, E */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.de.bytes.e; + break; + + case 0x6C: /* LD L, H */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.hl.bytes.h; + break; + + case 0x6D: /* LD L, L */ + break; + + case 0x6E: /* LD L, (HL) */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x6F: /* LD L, A */ + gb->cpu_reg.hl.bytes.l = gb->cpu_reg.a; + break; + + case 0x70: /* LD (HL), B */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.bc.bytes.b); + break; + + case 0x71: /* LD (HL), C */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.bc.bytes.c); + break; + + case 0x72: /* LD (HL), D */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.de.bytes.d); + break; + + case 0x73: /* LD (HL), E */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.de.bytes.e); + break; + + case 0x74: /* LD (HL), H */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.hl.bytes.h); + break; + + case 0x75: /* LD (HL), L */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.hl.bytes.l); + break; + + case 0x76: /* HALT */ + { + int_fast16_t halt_cycles = INT_FAST16_MAX; + +#ifdef PGB_BATCH + if(gb->counter.pend) __gb_flush(gb); /* the wait below starts from the counters as they are now */ +#endif + /* TODO: Emulate HALT bug? */ + gb->gb_halt = 1; + + if (gb->hram_io[IO_IE] == 0) + { + /* Return program counter where this halt forever state started. */ + /* This may be intentional, but this is required to stop an infinite + * loop. */ + (gb->gb_error)(gb, GB_HALT_FOREVER, gb->cpu_reg.pc.reg - 1); + PGB_UNREACHABLE(); + } + + if(gb->hram_io[IO_SC] & SERIAL_SC_TX_START) + { + int serial_cycles = SERIAL_CYCLES - + gb->counter.serial_count; + + if(serial_cycles < halt_cycles) + halt_cycles = serial_cycles; + } + + if(gb->hram_io[IO_TAC] & IO_TAC_ENABLE_MASK) + { + int tac_cycles = TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK] - + gb->counter.tima_count; + + if(tac_cycles < halt_cycles) + halt_cycles = tac_cycles; + } + + if((gb->hram_io[IO_LCDC] & LCDC_ENABLE)) + { + int lcd_cycles; + + /* If LCD is in HBlank, calculate the number of cycles + * until the end of HBlank and the start of mode 2 or + * mode 1. */ + if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_HBLANK) + { + lcd_cycles = LCD_MODE_2_CYCLES - + gb->counter.lcd_count; + } + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_SEARCH_OAM) + { + lcd_cycles = LCD_MODE_3_CYCLES - + gb->counter.lcd_count; + } + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_SEARCH_TRANSFER) + { + lcd_cycles = LCD_MODE_0_CYCLES - + gb->counter.lcd_count; + } + else + { + /* VBlank */ + lcd_cycles = + LCD_LINE_CYCLES - gb->counter.lcd_count; + } + + if(lcd_cycles < halt_cycles) + halt_cycles = lcd_cycles; + } + + /* Some halt cycles may already be very high, so make sure we + * don't underflow here. */ + if(halt_cycles <= 0) + halt_cycles = 4; + + inst_cycles = (uint_fast16_t)halt_cycles; + break; + } + + case 0x77: /* LD (HL), A */ + __gb_write(gb, gb->cpu_reg.hl.reg, gb->cpu_reg.a); + break; + + case 0x78: /* LD A, B */ + gb->cpu_reg.a = gb->cpu_reg.bc.bytes.b; + break; + + case 0x79: /* LD A, C */ + gb->cpu_reg.a = gb->cpu_reg.bc.bytes.c; + break; + + case 0x7A: /* LD A, D */ + gb->cpu_reg.a = gb->cpu_reg.de.bytes.d; + break; + + case 0x7B: /* LD A, E */ + gb->cpu_reg.a = gb->cpu_reg.de.bytes.e; + break; + + case 0x7C: /* LD A, H */ + gb->cpu_reg.a = gb->cpu_reg.hl.bytes.h; + break; + + case 0x7D: /* LD A, L */ + gb->cpu_reg.a = gb->cpu_reg.hl.bytes.l; + break; + + case 0x7E: /* LD A, (HL) */ + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.hl.reg); + break; + + case 0x7F: /* LD A, A */ + break; + + case 0x80: /* ADD A, B */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.b, 0); + break; + + case 0x81: /* ADD A, C */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.c, 0); + break; + + case 0x82: /* ADD A, D */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.d, 0); + break; + + case 0x83: /* ADD A, E */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.e, 0); + break; + + case 0x84: /* ADD A, H */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.h, 0); + break; + + case 0x85: /* ADD A, L */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.l, 0); + break; + + case 0x86: /* ADD A, (HL) */ + PGB_INSTR_ADC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), 0); + break; + + case 0x87: /* ADD A, A */ + PGB_INSTR_ADC_R8(gb->cpu_reg.a, 0); + break; + + case 0x88: /* ADC A, B */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.b, gb->cpu_reg.f_bits.c); + break; + + case 0x89: /* ADC A, C */ + PGB_INSTR_ADC_R8(gb->cpu_reg.bc.bytes.c, gb->cpu_reg.f_bits.c); + break; + + case 0x8A: /* ADC A, D */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.d, gb->cpu_reg.f_bits.c); + break; + + case 0x8B: /* ADC A, E */ + PGB_INSTR_ADC_R8(gb->cpu_reg.de.bytes.e, gb->cpu_reg.f_bits.c); + break; + + case 0x8C: /* ADC A, H */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.h, gb->cpu_reg.f_bits.c); + break; + + case 0x8D: /* ADC A, L */ + PGB_INSTR_ADC_R8(gb->cpu_reg.hl.bytes.l, gb->cpu_reg.f_bits.c); + break; + + case 0x8E: /* ADC A, (HL) */ + PGB_INSTR_ADC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), gb->cpu_reg.f_bits.c); + break; + + case 0x8F: /* ADC A, A */ + PGB_INSTR_ADC_R8(gb->cpu_reg.a, gb->cpu_reg.f_bits.c); + break; + + case 0x90: /* SUB B */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.b, 0); + break; + + case 0x91: /* SUB C */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.c, 0); + break; + + case 0x92: /* SUB D */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.d, 0); + break; + + case 0x93: /* SUB E */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.e, 0); + break; + + case 0x94: /* SUB H */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.h, 0); + break; + + case 0x95: /* SUB L */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.l, 0); + break; + + case 0x96: /* SUB (HL) */ + PGB_INSTR_SBC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), 0); + break; + + case 0x97: /* SUB A */ + gb->cpu_reg.a = 0; + gb->cpu_reg.f_bits.z = 1; + gb->cpu_reg.f_bits.n = 1; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = 0; + break; + + case 0x98: /* SBC A, B */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.b, gb->cpu_reg.f_bits.c); + break; + + case 0x99: /* SBC A, C */ + PGB_INSTR_SBC_R8(gb->cpu_reg.bc.bytes.c, gb->cpu_reg.f_bits.c); + break; + + case 0x9A: /* SBC A, D */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.d, gb->cpu_reg.f_bits.c); + break; + + case 0x9B: /* SBC A, E */ + PGB_INSTR_SBC_R8(gb->cpu_reg.de.bytes.e, gb->cpu_reg.f_bits.c); + break; + + case 0x9C: /* SBC A, H */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.h, gb->cpu_reg.f_bits.c); + break; + + case 0x9D: /* SBC A, L */ + PGB_INSTR_SBC_R8(gb->cpu_reg.hl.bytes.l, gb->cpu_reg.f_bits.c); + break; + + case 0x9E: /* SBC A, (HL) */ + PGB_INSTR_SBC_R8(__gb_read(gb, gb->cpu_reg.hl.reg), gb->cpu_reg.f_bits.c); + break; + + case 0x9F: /* SBC A, A */ + gb->cpu_reg.a = gb->cpu_reg.f_bits.c ? 0xFF : 0x00; + gb->cpu_reg.f_bits.z = !gb->cpu_reg.f_bits.c; + gb->cpu_reg.f_bits.n = 1; + gb->cpu_reg.f_bits.h = gb->cpu_reg.f_bits.c; + break; + + case 0xA0: /* AND B */ + PGB_INSTR_AND_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xA1: /* AND C */ + PGB_INSTR_AND_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xA2: /* AND D */ + PGB_INSTR_AND_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xA3: /* AND E */ + PGB_INSTR_AND_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xA4: /* AND H */ + PGB_INSTR_AND_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xA5: /* AND L */ + PGB_INSTR_AND_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xA6: /* AND (HL) */ + PGB_INSTR_AND_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xA7: /* AND A */ + PGB_INSTR_AND_R8(gb->cpu_reg.a); + break; + + case 0xA8: /* XOR B */ + PGB_INSTR_XOR_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xA9: /* XOR C */ + PGB_INSTR_XOR_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xAA: /* XOR D */ + PGB_INSTR_XOR_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xAB: /* XOR E */ + PGB_INSTR_XOR_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xAC: /* XOR H */ + PGB_INSTR_XOR_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xAD: /* XOR L */ + PGB_INSTR_XOR_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xAE: /* XOR (HL) */ + PGB_INSTR_XOR_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xAF: /* XOR A */ + PGB_INSTR_XOR_R8(gb->cpu_reg.a); + break; + + case 0xB0: /* OR B */ + PGB_INSTR_OR_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xB1: /* OR C */ + PGB_INSTR_OR_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xB2: /* OR D */ + PGB_INSTR_OR_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xB3: /* OR E */ + PGB_INSTR_OR_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xB4: /* OR H */ + PGB_INSTR_OR_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xB5: /* OR L */ + PGB_INSTR_OR_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xB6: /* OR (HL) */ + PGB_INSTR_OR_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xB7: /* OR A */ + PGB_INSTR_OR_R8(gb->cpu_reg.a); + break; + + case 0xB8: /* CP B */ + PGB_INSTR_CP_R8(gb->cpu_reg.bc.bytes.b); + break; + + case 0xB9: /* CP C */ + PGB_INSTR_CP_R8(gb->cpu_reg.bc.bytes.c); + break; + + case 0xBA: /* CP D */ + PGB_INSTR_CP_R8(gb->cpu_reg.de.bytes.d); + break; + + case 0xBB: /* CP E */ + PGB_INSTR_CP_R8(gb->cpu_reg.de.bytes.e); + break; + + case 0xBC: /* CP H */ + PGB_INSTR_CP_R8(gb->cpu_reg.hl.bytes.h); + break; + + case 0xBD: /* CP L */ + PGB_INSTR_CP_R8(gb->cpu_reg.hl.bytes.l); + break; + + case 0xBE: /* CP (HL) */ + PGB_INSTR_CP_R8(__gb_read(gb, gb->cpu_reg.hl.reg)); + break; + + case 0xBF: /* CP A */ + gb->cpu_reg.f_bits.z = 1; + gb->cpu_reg.f_bits.n = 1; + gb->cpu_reg.f_bits.h = 0; + gb->cpu_reg.f_bits.c = 0; + break; + + case 0xC0: /* RET NZ */ + if(!gb->cpu_reg.f_bits.z) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + + break; + + case 0xC1: /* POP BC */ + gb->cpu_reg.bc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.bc.bytes.b = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + + case 0xC2: /* JP NZ, imm */ + if(!gb->cpu_reg.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xC3: /* JP imm */ + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + break; + } + + case 0xC4: /* CALL NZ imm */ + if(!gb->cpu_reg.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xC5: /* PUSH BC */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.bc.bytes.b); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.bc.bytes.c); + break; + + case 0xC6: /* ADD A, imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_ADC_R8(val, 0); + break; + } + + case 0xC7: /* RST 0x0000 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0000; + break; + + case 0xC8: /* RET Z */ + if(gb->cpu_reg.f_bits.z) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + break; + + case 0xC9: /* RET */ + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + } + + case 0xCA: /* JP Z, imm */ + if(gb->cpu_reg.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xCB: /* CB INST */ + inst_cycles = __gb_execute_cb(gb); + break; + + case 0xCC: /* CALL Z, imm */ + if(gb->cpu_reg.f_bits.z) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xCD: /* CALL imm */ + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + } + break; + + case 0xCE: /* ADC A, imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_ADC_R8(val, gb->cpu_reg.f_bits.c); + break; + } + + case 0xCF: /* RST 0x0008 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0008; + break; + + case 0xD0: /* RET NC */ + if(!gb->cpu_reg.f_bits.c) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + + break; + + case 0xD1: /* POP DE */ + gb->cpu_reg.de.bytes.e = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.de.bytes.d = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + + case 0xD2: /* JP NC, imm */ + if(!gb->cpu_reg.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xD4: /* CALL NC, imm */ + if(!gb->cpu_reg.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xD5: /* PUSH DE */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.de.bytes.d); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.de.bytes.e); + break; + + case 0xD6: /* SUB imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + uint16_t temp = gb->cpu_reg.a - val; + gb->cpu_reg.f_bits.z = ((temp & 0xFF) == 0x00); + gb->cpu_reg.f_bits.n = 1; + gb->cpu_reg.f_bits.h = + (gb->cpu_reg.a ^ val ^ temp) & 0x10 ? 1 : 0; + gb->cpu_reg.f_bits.c = (temp & 0xFF00) ? 1 : 0; + gb->cpu_reg.a = (temp & 0xFF); + break; + } + + case 0xD7: /* RST 0x0010 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0010; + break; + + case 0xD8: /* RET C */ + if(gb->cpu_reg.f_bits.c) + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + inst_cycles += 12; + } + + break; + + case 0xD9: /* RETI */ + { + gb->cpu_reg.pc.bytes.c = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.pc.bytes.p = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->gb_ime = 1; + } + break; + + case 0xDA: /* JP C, imm */ + if(gb->cpu_reg.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 4; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xDC: /* CALL C, imm */ + if(gb->cpu_reg.f_bits.c) + { + uint8_t p, c; + c = __gb_read(gb, gb->cpu_reg.pc.reg++); + p = __gb_read(gb, gb->cpu_reg.pc.reg++); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.bytes.c = c; + gb->cpu_reg.pc.bytes.p = p; + inst_cycles += 12; + } + else + gb->cpu_reg.pc.reg += 2; + + break; + + case 0xDE: /* SBC A, imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_SBC_R8(val, gb->cpu_reg.f_bits.c); + break; + } + + case 0xDF: /* RST 0x0018 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0018; + break; + + case 0xE0: /* LD (0xFF00+imm), A */ + __gb_write(gb, 0xFF00 | __gb_read(gb, gb->cpu_reg.pc.reg++), + gb->cpu_reg.a); + break; + + case 0xE1: /* POP HL */ + gb->cpu_reg.hl.bytes.l = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.hl.bytes.h = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + + case 0xE2: /* LD (C), A */ + __gb_write(gb, 0xFF00 | gb->cpu_reg.bc.bytes.c, gb->cpu_reg.a); + break; + + case 0xE5: /* PUSH HL */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.hl.bytes.h); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.hl.bytes.l); + break; + + case 0xE6: /* AND imm */ + /* TODO: Optimisation? */ + gb->cpu_reg.a = gb->cpu_reg.a & __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.f_bits.z = (gb->cpu_reg.a == 0x00); + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = 1; + gb->cpu_reg.f_bits.c = 0; + break; + + case 0xE7: /* RST 0x0020 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0020; + break; + + case 0xE8: /* ADD SP, imm */ + { + int8_t offset = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.f_bits.z = 0; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.sp.reg & 0xF) + (offset & 0xF) > 0xF) ? 1 : 0; + gb->cpu_reg.f_bits.c = ((gb->cpu_reg.sp.reg & 0xFF) + (offset & 0xFF) > 0xFF); + gb->cpu_reg.sp.reg += offset; + break; + } + + case 0xE9: /* JP (HL) */ + gb->cpu_reg.pc.reg = gb->cpu_reg.hl.reg; + break; + + case 0xEA: /* LD (imm), A */ + { + uint8_t h, l; + uint16_t addr; + l = __gb_read(gb, gb->cpu_reg.pc.reg++); + h = __gb_read(gb, gb->cpu_reg.pc.reg++); + addr = PEANUT_GB_U8_TO_U16(h, l); + __gb_write(gb, addr, gb->cpu_reg.a); + break; + } + + case 0xEE: /* XOR imm */ + PGB_INSTR_XOR_R8(__gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0xEF: /* RST 0x0028 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0028; + break; + + case 0xF0: /* LD A, (0xFF00+imm) */ + gb->cpu_reg.a = + __gb_read(gb, 0xFF00 | __gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0xF1: /* POP AF */ + { + uint8_t temp_8 = __gb_read(gb, gb->cpu_reg.sp.reg++); + gb->cpu_reg.f_bits.z = (temp_8 >> 7) & 1; + gb->cpu_reg.f_bits.n = (temp_8 >> 6) & 1; + gb->cpu_reg.f_bits.h = (temp_8 >> 5) & 1; + gb->cpu_reg.f_bits.c = (temp_8 >> 4) & 1; + gb->cpu_reg.a = __gb_read(gb, gb->cpu_reg.sp.reg++); + break; + } + + case 0xF2: /* LD A, (C) */ + gb->cpu_reg.a = __gb_read(gb, 0xFF00 | gb->cpu_reg.bc.bytes.c); + break; + + case 0xF3: /* DI */ + gb->gb_ime = 0; + break; + + case 0xF5: /* PUSH AF */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.a); + __gb_write(gb, --gb->cpu_reg.sp.reg, + gb->cpu_reg.f_bits.z << 7 | gb->cpu_reg.f_bits.n << 6 | + gb->cpu_reg.f_bits.h << 5 | gb->cpu_reg.f_bits.c << 4); + break; + + case 0xF6: /* OR imm */ + PGB_INSTR_OR_R8(__gb_read(gb, gb->cpu_reg.pc.reg++)); + break; + + case 0xF7: /* PUSH AF */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0030; + break; + + case 0xF8: /* LD HL, SP+/-imm */ + { + /* Taken from SameBoy, which is released under MIT Licence. */ + int8_t offset = (int8_t) __gb_read(gb, gb->cpu_reg.pc.reg++); + gb->cpu_reg.hl.reg = gb->cpu_reg.sp.reg + offset; + gb->cpu_reg.f_bits.z = 0; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = ((gb->cpu_reg.sp.reg & 0xF) + (offset & 0xF) > 0xF) ? 1 : 0; + gb->cpu_reg.f_bits.c = ((gb->cpu_reg.sp.reg & 0xFF) + (offset & 0xFF) > 0xFF) ? 1 : + 0; + break; + } + + case 0xF9: /* LD SP, HL */ + gb->cpu_reg.sp.reg = gb->cpu_reg.hl.reg; + break; + + case 0xFA: /* LD A, (imm) */ + { + uint8_t h, l; + uint16_t addr; + l = __gb_read(gb, gb->cpu_reg.pc.reg++); + h = __gb_read(gb, gb->cpu_reg.pc.reg++); + addr = PEANUT_GB_U8_TO_U16(h, l); + gb->cpu_reg.a = __gb_read(gb, addr); + break; + } + + case 0xFB: /* EI */ + gb->gb_ime = 1; + break; + + case 0xFE: /* CP imm */ + { + uint8_t val = __gb_read(gb, gb->cpu_reg.pc.reg++); + PGB_INSTR_CP_R8(val); + break; + } + + case 0xFF: /* RST 0x0038 */ + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.p); + __gb_write(gb, --gb->cpu_reg.sp.reg, gb->cpu_reg.pc.bytes.c); + gb->cpu_reg.pc.reg = 0x0038; + break; + + default: + /* Return address where invlid opcode that was read. */ + (gb->gb_error)(gb, GB_INVALID_OPCODE, gb->cpu_reg.pc.reg - 1); + PGB_UNREACHABLE(); + } + +#ifdef PGB_BATCH + if(!gb->gb_halt) + { + gb->counter.pend += inst_cycles; + if(gb->counter.pend < gb->counter.slack) + return; + inst_cycles = (uint_fast16_t)gb->counter.pend; + gb->counter.pend = 0; + __gb_tick(gb, inst_cycles); + gb->counter.slack = __gb_slack(gb); + return; + } + if(gb->counter.pend) + __gb_flush(gb); + do + inst_cycles = __gb_tick(gb, inst_cycles); + while(gb->gb_halt && (gb->hram_io[IO_IF] & gb->hram_io[IO_IE]) == 0); + gb->counter.slack = __gb_slack(gb); + return; +#else + do + { + /* DIV register timing */ + gb->counter.div_count += inst_cycles; + while(gb->counter.div_count >= DIV_CYCLES) + { + gb->hram_io[IO_DIV]++; + gb->counter.div_count -= DIV_CYCLES; + } + + /* Check serial transmission. */ + if(gb->hram_io[IO_SC] & SERIAL_SC_TX_START) + { + unsigned int serial_cycles = SERIAL_CYCLES_1KB; + + /* If new transfer, call TX function. */ + if(gb->counter.serial_count == 0 && + gb->gb_serial_tx != NULL) + (gb->gb_serial_tx)(gb, gb->hram_io[IO_SB]); + +#if PEANUT_FULL_GBC_SUPPORT + if(gb->hram_io[IO_SC] & 0x3) + serial_cycles = SERIAL_CYCLES_32KB; +#endif + + gb->counter.serial_count += inst_cycles; + + /* If it's time to receive byte, call RX function. */ + if(gb->counter.serial_count >= serial_cycles) + { + /* If RX can be done, do it. */ + /* If RX failed, do not change SB if using external + * clock, or set to 0xFF if using internal clock. */ + uint8_t rx; +#ifdef PGB_SERIAL_WAIT + enum gb_serial_rx_ret_e rr = gb->gb_serial_rx != NULL ? gb->gb_serial_rx(gb, &rx) : GB_SERIAL_RX_NO_CONNECTION; + if(rr == GB_SERIAL_RX_WAIT) + { + /* Paramix: keep the transfer just before its end (asked again after the next + * instruction; a HALT waits 4 cycles at a time), nothing changes yet */ + gb->counter.serial_count = SERIAL_CYCLES - 4; + } + else if(rr == GB_SERIAL_RX_SUCCESS) +#else + if(gb->gb_serial_rx != NULL && + (gb->gb_serial_rx(gb, &rx) == + GB_SERIAL_RX_SUCCESS)) +#endif + { + gb->hram_io[IO_SB] = rx; + + /* Inform game of serial TX/RX completion. */ + gb->hram_io[IO_SC] &= 0x01; + gb->hram_io[IO_IF] |= SERIAL_INTR; + } + else if(gb->hram_io[IO_SC] & SERIAL_SC_CLOCK_SRC) + { + /* If using internal clock, and console is not + * attached to any external peripheral, shifted + * bits are replaced with logic 1. */ + gb->hram_io[IO_SB] = 0xFF; + + /* Inform game of serial TX/RX completion. */ + gb->hram_io[IO_SC] &= 0x01; + gb->hram_io[IO_IF] |= SERIAL_INTR; + } + else + { + /* If using external clock, and console is not + * attached to any external peripheral, bits are + * not shifted, so SB is not modified. */ + } + +#ifdef PGB_SERIAL_WAIT + if(rr != GB_SERIAL_RX_WAIT) +#endif + gb->counter.serial_count = 0; + } + } + + /* TIMA register timing */ + /* TODO: Change tac_enable to struct of TAC timer control bits. */ + if(gb->hram_io[IO_TAC] & IO_TAC_ENABLE_MASK) + { + gb->counter.tima_count += inst_cycles; + + while(gb->counter.tima_count >= + TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK]) + { + gb->counter.tima_count -= + TAC_CYCLES[gb->hram_io[IO_TAC] & IO_TAC_RATE_MASK]; + + if(++gb->hram_io[IO_TIMA] == 0) + { + gb->hram_io[IO_IF] |= TIMER_INTR; + /* On overflow, set TMA to TIMA. */ + gb->hram_io[IO_TIMA] = gb->hram_io[IO_TMA]; + } + } + } + + /* If LCD is off, don't update LCD state or increase the LCD + * ticks. */ + if(!(gb->hram_io[IO_LCDC] & LCDC_ENABLE)) + continue; + + /* LCD Timing */ +#if PEANUT_FULL_GBC_SUPPORT + if (inst_cycles > 1) + gb->counter.lcd_count += (inst_cycles >> gb->cgb.doubleSpeed); + else +#endif + gb->counter.lcd_count += inst_cycles; + + /* New Scanline */ + if(gb->counter.lcd_count >= LCD_LINE_CYCLES) + { + gb->counter.lcd_count -= LCD_LINE_CYCLES; + + /* Next line */ + gb->hram_io[IO_LY] = (gb->hram_io[IO_LY] + 1) % LCD_VERT_LINES; + + /* LYC Update */ + if(gb->hram_io[IO_LY] == gb->hram_io[IO_LYC]) + { + gb->hram_io[IO_STAT] |= STAT_LYC_COINC; + + if(gb->hram_io[IO_STAT] & STAT_LYC_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + } + else + gb->hram_io[IO_STAT] &= 0xFB; + + /* VBLANK Start */ + if(gb->hram_io[IO_LY] == LCD_HEIGHT) + { + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_VBLANK; + gb->gb_frame = 1; + gb->hram_io[IO_IF] |= VBLANK_INTR; + gb->lcd_blank = 0; + + if(gb->hram_io[IO_STAT] & STAT_MODE_1_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + +#if ENABLE_LCD + /* If frame skip is activated, check if we need to draw + * the frame or skip it. */ + if(gb->direct.frame_skip) + { + gb->display.frame_skip_count = + !gb->display.frame_skip_count; + } + + /* If interlaced is activated, change which lines get + * updated. Also, only update lines on frames that are + * actually drawn when frame skip is enabled. */ + if(gb->direct.interlace && + (!gb->direct.frame_skip || + gb->display.frame_skip_count)) + { + gb->display.interlace_count = + !gb->display.interlace_count; + } +#endif + } + /* Normal Line */ + else if(gb->hram_io[IO_LY] < LCD_HEIGHT) + { + if(gb->hram_io[IO_LY] == 0) + { + /* Clear Screen */ + gb->display.WY = gb->hram_io[IO_WY]; + gb->display.window_clear = 0; + } + + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_HBLANK; + +#if PEANUT_FULL_GBC_SUPPORT + //DMA GBC + if(gb->cgb.cgbMode && !gb->cgb.dmaActive && gb->cgb.dmaMode) + { + for (uint8_t i = 0; i < 0x10; i++) + { + __gb_write(gb, ((gb->cgb.dmaDest & 0x1FF0) | 0x8000) + i, + __gb_read(gb, (gb->cgb.dmaSource & 0xFFF0) + i)); + } + gb->cgb.dmaSource += 0x10; + gb->cgb.dmaDest += 0x10; + if(!(--gb->cgb.dmaSize)) gb->cgb.dmaActive = 1; + } +#endif + if(gb->hram_io[IO_STAT] & STAT_MODE_0_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + + /* If halted immediately jump to next LCD mode. */ + if(gb->counter.lcd_count < LCD_MODE_2_CYCLES) + inst_cycles = LCD_MODE_2_CYCLES - gb->counter.lcd_count; + } + } + /* OAM access */ + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_HBLANK && + gb->counter.lcd_count >= LCD_MODE_2_CYCLES) + { + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_SEARCH_OAM; + + if(gb->hram_io[IO_STAT] & STAT_MODE_2_INTR) + gb->hram_io[IO_IF] |= LCDC_INTR; + + /* If halted immediately jump to next LCD mode. */ + if (gb->counter.lcd_count < LCD_MODE_3_CYCLES) + inst_cycles = LCD_MODE_3_CYCLES - gb->counter.lcd_count; + } + /* Update LCD */ + else if((gb->hram_io[IO_STAT] & STAT_MODE) == IO_STAT_MODE_SEARCH_OAM && + gb->counter.lcd_count >= LCD_MODE_3_CYCLES) + { + gb->hram_io[IO_STAT] = + (gb->hram_io[IO_STAT] & ~STAT_MODE) | IO_STAT_MODE_SEARCH_TRANSFER; +#if ENABLE_LCD + if(!gb->lcd_blank) + __gb_draw_line(gb); +#endif + /* If halted immediately jump to next LCD mode. */ + if (gb->counter.lcd_count < LCD_MODE_0_CYCLES) + inst_cycles = LCD_MODE_0_CYCLES - gb->counter.lcd_count; + } + } while(gb->gb_halt && (gb->hram_io[IO_IF] & gb->hram_io[IO_IE]) == 0); + /* If halted, loop until an interrupt occurs. */ +#endif +} + +void gb_run_frame(struct gb_s *gb) +{ + gb->gb_frame = 0; + + while(!gb->gb_frame) + __gb_step_cpu(gb); +} + +/** + * Gets the size of the save file required for the ROM. + */ +uint_fast32_t gb_get_save_size(struct gb_s *gb) +{ + const uint_fast16_t ram_size_location = 0x0149; + const uint_fast32_t ram_sizes[] = + { + 0x00, 0x800, 0x2000, 0x8000, 0x20000 + }; + uint8_t ram_size = gb->gb_rom_read(gb, ram_size_location); + + /* MBC2 always has 512 half-bytes of cart RAM. */ + if(gb->mbc == 2) + return 0x200; + + return ram_sizes[ram_size]; +} + +void gb_init_serial(struct gb_s *gb, + void (*gb_serial_tx)(struct gb_s*, const uint8_t), + enum gb_serial_rx_ret_e (*gb_serial_rx)(struct gb_s*, + uint8_t*)) +{ + gb->gb_serial_tx = gb_serial_tx; + gb->gb_serial_rx = gb_serial_rx; +} + +uint8_t gb_colour_hash(struct gb_s *gb) +{ +#define ROM_TITLE_START_ADDR 0x0134 +#define ROM_TITLE_END_ADDR 0x0143 + + uint8_t x = 0; + uint16_t i; + + for(i = ROM_TITLE_START_ADDR; i <= ROM_TITLE_END_ADDR; i++) + x += gb->gb_rom_read(gb, i); + + return x; +} + +/** + * Resets the context, and initialises startup values for a DMG console. + */ +void gb_reset(struct gb_s *gb) +{ + gb->gb_halt = 0; + gb->gb_ime = 1; + + /* Initialise MBC values. */ + gb->selected_rom_bank = 1; + gb->cart_ram_bank = 0; + gb->enable_cart_ram = 0; + gb->cart_mode_select = 0; + PGB_BANKSET(gb); + + /* Use values as though the boot ROM was already executed. */ + if(gb->gb_bootrom_read == NULL) + { + uint8_t hdr_chk; + hdr_chk = gb->gb_rom_read(gb, ROM_HEADER_CHECKSUM_LOC) != 0; + + gb->cpu_reg.a = 0x01; + gb->cpu_reg.f_bits.z = 1; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = hdr_chk; + gb->cpu_reg.f_bits.c = hdr_chk; + gb->cpu_reg.bc.reg = 0x0013; + gb->cpu_reg.de.reg = 0x00D8; + gb->cpu_reg.hl.reg = 0x014D; + gb->cpu_reg.sp.reg = 0xFFFE; + gb->cpu_reg.pc.reg = 0x0100; + + gb->hram_io[IO_DIV ] = 0xAB; + gb->hram_io[IO_LCDC] = 0x91; + gb->hram_io[IO_STAT] = 0x85; + gb->hram_io[IO_BANK] = 0x01; +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) + { + gb->cpu_reg.a = 0x11; + gb->cpu_reg.f_bits.z = 1; + gb->cpu_reg.f_bits.n = 0; + gb->cpu_reg.f_bits.h = hdr_chk; + gb->cpu_reg.f_bits.c = hdr_chk; + gb->cpu_reg.bc.reg = 0x0000; + gb->cpu_reg.de.reg = 0x0008; + gb->cpu_reg.hl.reg = 0x007C; + gb->hram_io[IO_DIV] = 0xFF; + } +#endif + + memset(gb->vram, 0x00, VRAM_SIZE); + } + else + { + /* Set value as though the console was just switched on. + * CPU registers are uninitialised. */ + gb->cpu_reg.pc.reg = 0x0000; + gb->hram_io[IO_DIV ] = 0x00; + gb->hram_io[IO_LCDC] = 0x00; + gb->hram_io[IO_STAT] = 0x84; + gb->hram_io[IO_BANK] = 0x00; + } + + gb->counter.lcd_count = 0; + gb->counter.div_count = 0; + gb->counter.tima_count = 0; + gb->counter.serial_count = 0; +#ifdef PGB_BATCH + gb->counter.pend = 0; + gb->counter.slack = 0; +#endif + + gb->direct.joypad = 0xFF; + gb->hram_io[IO_JOYP] = 0xCF; + gb->hram_io[IO_SB ] = 0x00; + gb->hram_io[IO_SC ] = 0x7E; +#if PEANUT_FULL_GBC_SUPPORT + if(gb->cgb.cgbMode) gb->hram_io[IO_SC] = 0x7F; +#endif + /* DIV */ + gb->hram_io[IO_TIMA] = 0x00; + gb->hram_io[IO_TMA ] = 0x00; + gb->hram_io[IO_TAC ] = 0xF8; + gb->hram_io[IO_IF ] = 0xE1; + + /* LCDC */ + /* STAT */ + gb->hram_io[IO_SCY ] = 0x00; + gb->hram_io[IO_SCX ] = 0x00; + gb->hram_io[IO_LY ] = 0x00; + gb->hram_io[IO_LYC ] = 0x00; + __gb_write(gb, 0xFF47, 0xFC); // BGP + __gb_write(gb, 0xFF48, 0xFF); // OBJP0 + __gb_write(gb, 0xFF49, 0xFF); // OBJP1 + gb->hram_io[IO_WY] = 0x00; + gb->hram_io[IO_WX] = 0x00; + gb->hram_io[IO_IE] = 0x00; + gb->hram_io[IO_IF] = 0xE1; +#if PEANUT_FULL_GBC_SUPPORT + /* Initialize some CGB registers */ + gb->cgb.doubleSpeed = 0; + gb->cgb.doubleSpeedPrep = 0; + gb->cgb.wramBank = 1; + gb->cgb.wramBankOffset = WRAM_0_ADDR; + gb->cgb.vramBank = 0; + gb->cgb.vramBankOffset = VRAM_ADDR; + for (int i = 0; i < 0x20; i++) + { + gb->cgb.OAMPalette[(i << 1)] = gb->cgb.BGPalette[(i << 1)] = 0x7F; + gb->cgb.OAMPalette[(i << 1) + 1] = gb->cgb.BGPalette[(i << 1) + 1] = 0xFF; + } + gb->cgb.OAMPaletteID = 0; + gb->cgb.BGPaletteID = 0; + gb->cgb.OAMPaletteInc = 0; + gb->cgb.BGPaletteInc = 0; + gb->cgb.dmaActive = 1; // Not active + gb->cgb.dmaMode = 0; + gb->cgb.dmaSize = 0; + gb->cgb.dmaSource = 0; + gb->cgb.dmaDest = 0; +#endif +} + +enum gb_init_error_e gb_init(struct gb_s *gb, + uint8_t (*gb_rom_read)(struct gb_s*, const uint_fast32_t), + uint8_t (*gb_cart_ram_read)(struct gb_s*, const uint_fast32_t), + void (*gb_cart_ram_write)(struct gb_s*, const uint_fast32_t, const uint8_t), + void (*gb_error)(struct gb_s*, const enum gb_error_e, const uint16_t), + void *priv) +{ +#if PEANUT_FULL_GBC_SUPPORT + const uint16_t cgb_flag = 0x0143; +#endif + const uint16_t mbc_location = 0x0147; + const uint16_t bank_count_location = 0x0148; + const uint16_t ram_size_location = 0x0149; + /** + * Table for cartridge type (MBC). -1 if invalid. + * TODO: MMM01 is untested. + * TODO: MBC6 is untested. + * TODO: MBC7 is unsupported. + * TODO: POCKET CAMERA is unsupported. + * TODO: BANDAI TAMA5 is unsupported. + * TODO: HuC3 is unsupported. + * TODO: HuC1 is unsupported. + **/ + const int8_t cart_mbc[] = + { + 0, 1, 1, 1, -1, 2, 2, -1, 0, 0, -1, 0, 0, 0, -1, 3, + 3, 3, 3, 3, -1, -1, -1, -1, -1, 5, 5, 5, 5, 5, 5, -1 + }; + const uint8_t cart_ram[] = + { + 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, + 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 + }; + const uint16_t num_rom_banks_mask[] = + { + 2, 4, 8, 16, 32, 64, 128, 256, 512 + }; + const uint8_t num_ram_banks[] = { 0, 1, 1, 4, 16, 8 }; + + gb->gb_rom_read = gb_rom_read; + gb->gb_cart_ram_read = gb_cart_ram_read; + gb->gb_cart_ram_write = gb_cart_ram_write; + gb->gb_error = gb_error; + gb->direct.priv = priv; + + /* Initialise serial transfer function to NULL. If the front-end does + * not provide serial support, Peanut-GB will emulate no cable connected + * automatically. */ + gb->gb_serial_tx = NULL; + gb->gb_serial_rx = NULL; + + gb->gb_bootrom_read = NULL; + + /* Check valid ROM using checksum value. */ + { + uint8_t x = 0; + uint16_t i; + + for(i = 0x0134; i <= 0x014C; i++) + x = x - gb->gb_rom_read(gb, i) - 1; + + if(x != gb->gb_rom_read(gb, ROM_HEADER_CHECKSUM_LOC)) + return GB_INIT_INVALID_CHECKSUM; + } + + /* Check if cartridge type is supported, and set MBC type. */ + { +#if PEANUT_FULL_GBC_SUPPORT + gb->cgb.cgbMode = (gb->gb_rom_read(gb, cgb_flag) & 0x80) >> 7; +#endif + const uint8_t mbc_value = gb->gb_rom_read(gb, mbc_location); + + if(mbc_value > sizeof(cart_mbc) - 1 || + (gb->mbc = cart_mbc[mbc_value]) == -1) + return GB_INIT_CARTRIDGE_UNSUPPORTED; + } + + gb->cart_ram = cart_ram[gb->gb_rom_read(gb, mbc_location)]; + gb->num_rom_banks_mask = num_rom_banks_mask[gb->gb_rom_read(gb, bank_count_location)] - 1; + gb->num_ram_banks = num_ram_banks[gb->gb_rom_read(gb, ram_size_location)]; + + /* Note that MBC2 will appear to have no RAM banks, but it actually + * always has 512 half-bytes of RAM. Hence, gb->num_ram_banks must be + * ignored for MBC2. */ + + gb->lcd_blank = 0; + gb->display.lcd_draw_line = NULL; + + gb_reset(gb); + + return GB_INIT_NO_ERROR; +} + +const char* gb_get_rom_name(struct gb_s* gb, char *title_str) +{ + uint_fast16_t title_loc = 0x134; + /* End of title may be 0x13E for newer games. */ + const uint_fast16_t title_end = 0x143; + const char* title_start = title_str; + + for(; title_loc <= title_end; title_loc++) + { + const char title_char = gb->gb_rom_read(gb, title_loc); + + if(title_char >= ' ' && title_char <= '_') + { + *title_str = title_char; + title_str++; + } + else + break; + } + + *title_str = '\0'; + return title_start; +} + +#if ENABLE_LCD +void gb_init_lcd(struct gb_s *gb, + void (*lcd_draw_line)(struct gb_s *gb, + const uint8_t *pixels, + const uint_fast8_t line)) +{ + gb->display.lcd_draw_line = lcd_draw_line; + + gb->direct.interlace = 0; + gb->display.interlace_count = 0; + gb->direct.frame_skip = 0; + gb->display.frame_skip_count = 0; + + gb->display.window_clear = 0; + gb->display.WY = 0; + + return; +} +#endif + +void gb_set_bootrom(struct gb_s *gb, + uint8_t (*gb_bootrom_read)(struct gb_s*, const uint_fast16_t)) +{ + gb->gb_bootrom_read = gb_bootrom_read; +} + +/** + * This was taken from SameBoy, which is released under MIT Licence. + */ +void gb_tick_rtc(struct gb_s *gb) +{ + /* is timer running? */ + if((gb->cart_rtc[4] & 0x40) == 0) + { + if(++gb->rtc_bits.sec == 60) + { + gb->rtc_bits.sec = 0; + + if(++gb->rtc_bits.min == 60) + { + gb->rtc_bits.min = 0; + + if(++gb->rtc_bits.hour == 24) + { + gb->rtc_bits.hour = 0; + + if(++gb->rtc_bits.yday == 0) + { + if(gb->rtc_bits.high & 1) /* Bit 8 of days*/ + { + gb->rtc_bits.high |= 0x80; /* Overflow bit */ + } + + gb->rtc_bits.high ^= 1; + } + } + } + } + } +} + +void gb_set_rtc(struct gb_s *gb, const struct tm * const time) +{ + gb->cart_rtc[0] = time->tm_sec; + gb->cart_rtc[1] = time->tm_min; + gb->cart_rtc[2] = time->tm_hour; + gb->cart_rtc[3] = time->tm_yday & 0xFF; /* Low 8 bits of day counter. */ + gb->cart_rtc[4] = time->tm_yday >> 8; /* High 1 bit of day counter. */ +} +#endif // PEANUT_GB_HEADER_ONLY + +/** Function prototypes: Required functions **/ +/** + * Initialises the emulator context to a known state. Call this before calling + * any other peanut-gb function. + * To reset the emulator, you can call gb_reset() instead. + * + * \param gb Allocated emulator context. Must not be NULL. + * \param gb_rom_read Pointer to function that reads ROM data. ROM banking is + * already handled by Peanut-GB. Must not be NULL. + * \param gb_cart_ram_read Pointer to function that reads Cart RAM. Must not be + * NULL. + * \param gb_cart_ram_write Pointer to function to writes to Cart RAM. Must not + * be NULL. + * \param gb_error Pointer to function that is called when an unrecoverable + * error occurs. Must not be NULL. Returning from this + * function is undefined and will result in SIGABRT. + * \param priv Private data that is stored within the emulator context. Set to + * NULL if unused. + * \returns 0 on success or an enum that describes the error. + */ +enum gb_init_error_e gb_init(struct gb_s *gb, + uint8_t (*gb_rom_read)(struct gb_s*, const uint_fast32_t), + uint8_t (*gb_cart_ram_read)(struct gb_s*, const uint_fast32_t), + void (*gb_cart_ram_write)(struct gb_s*, const uint_fast32_t, const uint8_t), + void (*gb_error)(struct gb_s*, const enum gb_error_e, const uint16_t), + void *priv); + +/** + * Executes the emulator and runs for one frame. + * + * \param An initialised emulator context. Must not be NULL. + */ +void gb_run_frame(struct gb_s *gb); + +/** + * Internal function used to step the CPU. Used mainly for testing. + * Use gb_run_frame() instead. + * + * \param An initialised emulator context. Must not be NULL. + */ +void __gb_step_cpu(struct gb_s *gb); + +/** Function prototypes: Optional Functions **/ +/** + * Reset the emulator, like turning the Game Boy off and on again. + * This function can be called at any time. + * + * \param An initialised emulator context. Must not be NULL. + */ +void gb_reset(struct gb_s *gb); + +/** + * Initialises the display context of the emulator. Only available when + * ENABLE_LCD is defined to a non-zero value. + * The pixel data sent to lcd_draw_line comes with both shade and layer data. + * The first two least significant bits are the shade data (black, dark, light, + * white). Bits 4 and 5 are layer data (OBJ0, OBJ1, BG), which can be used to + * add more colours to the game in the same way that the Game Boy Color does to + * older Game Boy games. + * This function can be called at any time. + * + * \param gb An initialised emulator context. Must not be NULL. + * \param lcd_draw_line Pointer to function that draws the 2-bit pixel data on the line + * "line". Must not be NULL. + */ +#if ENABLE_LCD +void gb_init_lcd(struct gb_s *gb, + void (*lcd_draw_line)(struct gb_s *gb, + const uint8_t *pixels, + const uint_fast8_t line)); +#endif + +/** + * Initialises the serial connection of the emulator. This function is optional, + * and if not called, the emulator will assume that no link cable is connected + * to the game. + * + * \param gb An initialised emulator context. Must not be NULL. + * \param gb_serial_tx Pointer to function that transmits a byte of data over + * the serial connection. Must not be NULL. + * \param gb_serial_rx Pointer to function that receives a byte of data over the + * serial connection. If no byte is received, + * return GB_SERIAL_RX_NO_CONNECTION. Must not be NULL. + */ +void gb_init_serial(struct gb_s *gb, + void (*gb_serial_tx)(struct gb_s*, const uint8_t), + enum gb_serial_rx_ret_e (*gb_serial_rx)(struct gb_s*, + uint8_t*)); + +/** + * Obtains the save size of the game (size of the Cart RAM). Required by the + * frontend to allocate enough memory for the Cart RAM. + * + * \param gb An initialised emulator context. Must not be NULL. + * \returns Size of the Cart RAM in bytes. 0 if Cartridge has not battery + * backed RAM. + */ +uint_fast32_t gb_get_save_size(struct gb_s *gb); + +/** + * Calculates and returns a hash of the game header in the same way the Game + * Boy Color does for colourising old Game Boy games. The frontend can use this + * hash to automatically set a colour palette. + * + * \param gb An initialised emulator context. Must not be NULL. + * \returns Hash of the game header. + */ +uint8_t gb_colour_hash(struct gb_s *gb); + +/** + * Returns the title of ROM. + * + * \param gb An initialised emulator context. Must not be NULL. + * \param title_str Allocated string at least 16 characters. + * \returns Pointer to start of string, null terminated. + */ +const char* gb_get_rom_name(struct gb_s* gb, char *title_str); + +/** + * Tick the internal RTC by one second. This does not affect games with no RTC + * support. + * + * \param gb An initialised emulator context. Must not be NULL. + */ +void gb_tick_rtc(struct gb_s *gb); + +/** + * Set initial values in RTC. + * Should be called after gb_init(). + * + * \param gb An initialised emulator context. Must not be NULL. + * \param time Time structure with date and time. + */ +void gb_set_rtc(struct gb_s *gb, const struct tm * const time); + +/** + * Use boot ROM on reset. gb_reset() must be called for this to take affect. + * \param gb An initialised emulator context. Must not be NULL. + * \param gb_bootrom_read Function pointer to read boot ROM binary. + */ +void gb_set_bootrom(struct gb_s *gb, + uint8_t (*gb_bootrom_read)(struct gb_s*, const uint_fast16_t)); + +/* Undefine CPU Flag helper functions. */ +#undef PEANUT_GB_CPUFLAG_MASK_CARRY +#undef PEANUT_GB_CPUFLAG_MASK_HALFC +#undef PEANUT_GB_CPUFLAG_MASK_ARITH +#undef PEANUT_GB_CPUFLAG_MASK_ZERO +#undef PEANUT_GB_CPUFLAG_BIT_CARRY +#undef PEANUT_GB_CPUFLAG_BIT_HALFC +#undef PEANUT_GB_CPUFLAG_BIT_ARITH +#undef PEANUT_GB_CPUFLAG_BIT_ZERO +#undef PGB_SET_CARRY +#undef PGB_SET_HALFC +#undef PGB_SET_ARITH +#undef PGB_SET_ZERO +#undef PGB_GET_CARRY +#undef PGB_GET_HALFC +#undef PGB_GET_ARITH +#undef PGB_GET_ZERO +#endif //PEANUT_GB_H diff --git a/gb/src/stub/stdlib.h b/gb/src/stub/stdlib.h new file mode 100644 index 0000000..0a10636 --- /dev/null +++ b/gb/src/stub/stdlib.h @@ -0,0 +1,4 @@ +/* freestanding stubs for Peanut-GB on the Paradise */ +#pragma once +#include +void abort(void) __attribute__((noreturn)); diff --git a/gb/src/stub/string.h b/gb/src/stub/string.h new file mode 100644 index 0000000..6678933 --- /dev/null +++ b/gb/src/stub/string.h @@ -0,0 +1,4 @@ +#pragma once +#include +void *memset(void *d, int c, size_t n); +void *memcpy(void *d, const void *s, size_t n); diff --git a/gb/src/stub/time.h b/gb/src/stub/time.h new file mode 100644 index 0000000..1564590 --- /dev/null +++ b/gb/src/stub/time.h @@ -0,0 +1,2 @@ +#pragma once +struct tm { int tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year, tm_wday, tm_yday, tm_isdst; }; diff --git a/gb/test/devgb.py b/gb/test/devgb.py new file mode 100644 index 0000000..8175360 --- /dev/null +++ b/gb/test/devgb.py @@ -0,0 +1,181 @@ +# GBEmu (gb.bin) in Unicorn, as devt7.py: hardware calls caught, the screen into a picture. +# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms). +# python3 devv3.py [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir] +import sys, struct, subprocess, os +from unicorn import * +from unicorn.arm_const import * +elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3]) +RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each) +out = os.environ.get('OUT', '.') +syms = {} +for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 3: syms[p[2]] = int(p[0], 16) +fl = bytearray(open(img, 'rb').read()) +u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS) +u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4) +APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere) +u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000])) +u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000) +u.mem_map(0x10000000, 0x100000) +u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl)) +u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here) +u.mem_write(0x4000B014, struct.pack('= t: m = v + return m +def ret(uc, v=None): + if v is not None: uc.reg_write(UC_ARM_REG_R0, v) + uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1) +def h_begin(uc, *a): + x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3)) + rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc) +def h_row(uc, *a): + p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n)) + for v in d: + if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v + rect['x'] += 1 + if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1 + ret(uc) +def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc) +def h_btn(uc, *a): ret(uc, keys()) +def h_prog(uc, *a): + ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = bytes(uc.mem_read(src, 0x1000)); a = ad & 0xFFFFFF + uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc) +def h_erase(uc, *a): + a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF + uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc) +def h_back(uc, *a): state['back'] = 1; uc.emu_stop() +def h_nop(uc, *a): ret(uc) +H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn, + 'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop, + 'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop} +for n, f in H.items(): + a = syms[n] & ~1 + u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a) +import builtins +if hasattr(builtins, '__gbprof'): u.hook_add(UC_HOOK_BLOCK, builtins.__gbprof[0]) +if os.environ.get('CACHESIM'): # test38: the I-cache of the flash window (16 KB, 32-byte lines, WAYS ways, LRU): misses per frame + _ways = int(os.environ.get('WAYS', '4')); _sets = 16384 // 32 // _ways + _cs = [[] for _ in range(_sets)]; state['miss'] = 0; state['acc'] = 0 + def _cr(uc, acc, a, sz, v, ud): + state['acc'] += 1 + ln = (a - 0x10000000) >> 5; s = _cs[ln % _sets] + if ln in s: s.remove(ln); s.append(ln); return + state['miss'] += 1; s.append(ln) + if len(s) > _ways: s.pop(0) + u.hook_add(UC_HOOK_MEM_READ, _cr, begin=0x10000000, end=0x100FFFFF) +def bad(uc, access, addr, size, value, ud): + print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False +u.hook_add(UC_HOOK_MEM_UNMAPPED, bad) +# 1.6.9 test22 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms +state['sh'] = 0; state['shms'] = [0, 0, 0, 0] +def _ahb(uc, acc, a, sz, v, ud): + state['sh'] = v & 7 + if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms']) +u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013) +if os.environ.get('MEMW'): + _mw = int(os.environ['MEMW'], 16) + u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F) +def shot(name): + from PIL import Image + im = Image.new('RGB', (128, 128)) + for y in range(128): + for x in range(128): + v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3)) + im.save(os.path.join(out, name)) +if os.environ.get('PMB'): # test: the Paradise's time in the mailbox (seconds since 1970, local) + _t = int(os.environ['PMB']); _c = int(os.environ.get('RTC0', '5000')) + u.mem_write(0x20000FC0, struct.pack(' 1: LK['tx'].append(v & 0xFF) # the first is the baud divisor + u.hook_add(UC_HOOK_MEM_WRITE, _uw, begin=0x4000B000, end=0x4000B000) + LK['w'] = os.fdopen(os.open(os.environ['LINKW'], os.O_RDWR), 'wb', buffering=0); LK['r'] = os.fdopen(os.open(os.environ['LINKR'], os.O_RDWR), 'rb', buffering=0) # (O_RDWR: no wait for the other end) +def link_ms(): + d = bytes(LK['tx']); LK['tx'] = bytearray() + LK['w'].write(struct.pack('> state['sh'])); state['shms'][min(state['sh'], 3)] += 1 + except UcError as ex: + print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break + pc = u.reg_read(UC_ARM_REG_PC) + state['ms'] += 1 + if 'w' in LK: link_ms() + v = struct.unpack('= w[0]: + d = 1 if w[1] > 0 else -1; state_enc['ph'] = (state_enc['ph'] + d) % 4; w[0] += 0.004 if (state_enc['ph'] % 4) else 0.02 + if state_enc['ph'] == 0: w[1] -= d + u.mem_write(0x4001A000, struct.pack('= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1 + if 'miss' in state and state['ms'] % 1000 == 0: + _f = struct.unpack(' + * script: lines "frame keys" (keys: Peanut joypad bits pressed, 1 A 2 B 4 SELECT 8 START 16 R 32 L 64 U 128 D), + * "frame shot". Saves the cartridge RAM of both at the end (out/save0.sav, save1.sav). Test only. */ +#include +#include +#include +#include +static uint8_t *g_rom; static size_t g_rom_n; +#define PGB_ROM g_rom +#define ENABLE_SOUND 0 +#define PEANUT_GB_HIGH_LCD_ACCURACY 1 +#define PGB_SERIAL_WAIT +#include "../src/core/peanut_gb.h" +static struct gb_s G[2]; +static uint8_t cram[2][0x8000]; +static uint8_t fb[2][144][160]; +static int cur; /* which one runs */ +static long lines[2]; /* scanlines run (time) */ +#define LAT (getenv("LAT") ? atoi(getenv("LAT")) : 20) +typedef struct { long at; int to; uint8_t k, b; } Msg; +static Msg q[4096]; static int qn; +static long now_lines(void) { return lines[cur]; } +struct GlState; static struct GlState *gl_cur; +#define GL_S (*gl_cur) +static void gl_got(uint8_t kind, uint8_t b); +static void send_to(int to, uint8_t k, uint8_t b) { if (getenv("DBG")) fprintf(stderr, "%ld gb%d -> %c %02x\n", lines[cur], cur, k, b); if (qn < 4096) { q[qn].at = lines[cur] + LAT; q[qn].to = to; q[qn].k = k; q[qn].b = b; qn++; } } +static void poll_cur(void) +{ + for (int i = 0; i < qn; i++) if (q[i].to == cur && q[i].at <= lines[cur]) { Msg m = q[i]; memmove(&q[i], &q[i + 1], (size_t)(qn - i - 1) * sizeof(Msg)); qn--; i--; gl_got(m.k, m.b); } +} +static int g_partner = 1; +#define GL_SEND(k, b) send_to(1 - cur, (k), (b)) +#define GL_POLL() poll_cur() +#define GL_NOW() ((uint32_t)(lines[cur] * 1000 / 9198)) +#define GL_PARTNER() g_partner +#include "../src/app/gb_link.h" +static GlState gls[2]; +static uint8_t rom_rd(struct gb_s *gb, const uint_fast32_t a) { (void)gb; return a < g_rom_n ? g_rom[a] : 0xFF; } +static uint8_t cram_rd(struct gb_s *gb, const uint_fast32_t a) { return cram[gb == &G[1]][a & 0x7FFF]; } +static void cram_wr(struct gb_s *gb, const uint_fast32_t a, const uint8_t v) { cram[gb == &G[1]][a & 0x7FFF] = v; } +static void err(struct gb_s *gb, const enum gb_error_e e, const uint16_t a) { fprintf(stderr, "gb%d error %d at %04x\n", gb == &G[1], e, a); } +static void lcd(struct gb_s *gb, const uint8_t px[160], const uint_fast8_t line) { int i = gb == &G[1]; for (int x = 0; x < 160; x++) fb[i][line][x] = px[x] & 3; } +static void shot(const char *dir, int i, int f) +{ + char p[512]; snprintf(p, sizeof p, "%s/g%d_%05d.pgm", dir, i, f); FILE *o = fopen(p, "wb"); fprintf(o, "P5 160 144 255\n"); + static const uint8_t sh[4] = { 0xE0, 0xA8, 0x60, 0x18 }; + for (int y = 0; y < 144; y++) for (int x = 0; x < 160; x++) fputc(sh[fb[i][y][x]], o); fclose(o); +} +typedef struct { int f; int keys; int shot; int pa, pv; } Ev; +static int load_script(const char *fn, Ev *ev, int max) +{ + int n = 0; if (!strcmp(fn, "-")) return 0; FILE *f = fopen(fn, "r"); char l[128]; + while (n < max && fgets(l, sizeof l, f)) { int fr; char w[32], a[32], v[32]; int k = sscanf(l, "%d %31s %31s %31s", &fr, w, a, v); if (k < 2) continue; ev[n].f = fr; ev[n].pa = 0; + if (!strcmp(w, "peek") && k >= 3) { ev[n].pa = (int)strtol(a, 0, 16); ev[n].pv = -1; ev[n].shot = 0; ev[n].keys = -1; n++; continue; } + if (!strcmp(w, "poke") && k == 4) { ev[n].pa = (int)strtol(a, 0, 16); ev[n].pv = (int)strtol(v, 0, 16); ev[n].shot = 0; ev[n].keys = -1; n++; continue; } + ev[n].shot = !strcmp(w, "shot"); ev[n].keys = ev[n].shot ? 0 : (int)strtol(w, 0, 0); n++; } + fclose(f); return n; +} +static uint8_t *rd(const char *f, size_t *n) { FILE *x = fopen(f, "rb"); if (!x) return 0; fseek(x, 0, 2); *n = (size_t)ftell(x); fseek(x, 0, 0); uint8_t *p = malloc(*n); if (fread(p, 1, *n, x) != *n) {} fclose(x); return p; } +int main(int argc, char **argv) +{ + g_rom = rd(argv[1], &g_rom_n); + for (int i = 0; i < 2; i++) { + memset(cram[i], 0xFF, sizeof cram[i]); + if (strcmp(argv[2 + i], "-")) { size_t n; uint8_t *s = rd(argv[2 + i], &n); if (s) { memcpy(cram[i], s, n > 0x8000 ? 0x8000 : n); free(s); } } + if (gb_init(&G[i], rom_rd, cram_rd, cram_wr, err, 0) != GB_INIT_NO_ERROR) { printf("init\n"); return 1; } + gb_init_lcd(&G[i], lcd); gb_init_serial(&G[i], gl_tx, gl_rx); + G[i].direct.joypad = 0xFF; + } + static Ev ev[2][4096]; int ne[2]; ne[0] = load_script(argv[4], ev[0], 4096); ne[1] = load_script(argv[5], ev[1], 4096); + int frames = atoi(argv[6]); const char *out = argv[7]; + if (getenv("SOLO")) g_partner = 0; + int fr[2] = { 0, 0 }, ei[2] = { 0, 0 }; + while (fr[0] < frames || fr[1] < frames) { + for (int i = 0; i < 2; i++) { + if (fr[i] >= frames) continue; + cur = i; gl_cur = &gls[i]; + uint8_t ly = G[i].hram_io[IO_LY]; + G[i].gb_frame = false; + long guard = 0; + while (G[i].hram_io[IO_LY] == ly && !G[i].gb_frame && guard++ < 200000) __gb_step_cpu(&G[i]); + lines[i]++; + if (G[i].gb_frame || (G[i].hram_io[IO_LY] == 0 && ly == 153)) { + fr[i]++; + gl_tick(); + while (ei[i] < ne[i] && ev[i][ei[i]].f <= fr[i]) { Ev *e = &ev[i][ei[i]++]; if (e->pa && e->pv < 0) printf("gb%d f%d peek %04x = %02x\n", i, fr[i], e->pa, __gb_read(&G[i], (uint16_t)e->pa)); else if (e->pa) __gb_write(&G[i], (uint16_t)e->pa, (uint8_t)e->pv); else if (e->shot) shot(out, i, fr[i]); else G[i].direct.joypad = (uint8_t)~e->keys; } + } + } + } + for (int i = 0; i < 2; i++) { char p[512]; snprintf(p, sizeof p, "%s/save%d.sav", out, i); FILE *o = fopen(p, "wb"); fwrite(cram[i], 1, 0x8000, o); fclose(o); + printf("gb%d frames %d tx %u rx %u\n", i, fr[i], gls[i].n_tx, gls[i].n_rx); } + return 0; +} diff --git a/gb/test/mkimg.py b/gb/test/mkimg.py new file mode 100644 index 0000000..372e477 --- /dev/null +++ b/gb/test/mkimg.py @@ -0,0 +1,9 @@ +# test image: gb.bin at 0xA0000 with its settings block, the ROM at 0x200000, the saves at 0x300000 (64 KB) +import sys, struct +app, rom, out = sys.argv[1], sys.argv[2], sys.argv[3] +fl = bytearray(b'\xff' * 0x400000) +a = open(app, 'rb').read(); r = open(rom, 'rb').read() +fl[0xA0000:0xA0000 + len(a)] = a; fl[0x200000:0x200000 + len(r)] = r +struct.pack_into('<6I16s', fl, 0xA0000 + 0x140, 0x47584D50, 1, 0x200000, len(r), 0x300000, int(sys.argv[4]) if len(sys.argv) > 4 else 0, b'GAME BOY') +fl[0xA0000 + 0x140 + 40:0xA0000 + 0x140 + 43] = bytes([1, 2, 8]) # keys A, B, C: Game Boy A, B, START (as the Studio's defaults) +open(out, 'wb').write(fl) diff --git a/gb/test/mklinkrom.py b/gb/test/mklinkrom.py new file mode 100644 index 0000000..62edfc3 --- /dev/null +++ b/gb/test/mklinkrom.py @@ -0,0 +1,22 @@ +# A tiny own Game Boy program for the link test (no game data): 256 bytes over the serial port. +# Starts with the A button. role m: clocks (SC=0x81) and sends 0,1,2..; role s: answers (SC=0x80) with 0x80,0x81,..; both keep what they get at C000. +# python3 mklinkrom.py m|s out.gb +import sys +m = sys.argv[1] == 'm' +r = bytearray(32768) +r[0x100:0x104] = bytes([0x00, 0xC3, 0x50, 0x01]) +r[0x134:0x13C] = b'LINKTEST' +code = [0xF3, + 0x3E, 0x10, 0xE0, 0x00, 0xF0, 0x00, 0xCB, 0x47, 0x20, 0xF6, # wait for A (both sides know each other by then) + 0x21, 0x00, 0xC0, 0x06, 0x00, + 0x78, 0xEE, 0x00 if m else 0x80, 0xE0, 0x01, 0x3E, 0x81 if m else 0x80, 0xE0, 0x02, + 0xF0, 0x02, 0xCB, 0x7F, 0x20, 0xFA, + 0xF0, 0x01, 0x22, 0x04, + 0x0E, 0x00, 0x0D, 0x20, 0xFD, + 0x7C, 0xFE, 0xC1, 0x20, 0xE3, + 0x18, 0xFE] +r[0x150:0x150 + len(code)] = bytes(code) +x = 0 +for i in range(0x134, 0x14D): x = (x - r[i] - 1) & 0xFF +r[0x14D] = x +open(sys.argv[2], 'wb').write(r) diff --git a/gb/test/prof.py b/gb/test/prof.py new file mode 100644 index 0000000..72fe224 --- /dev/null +++ b/gb/test/prof.py @@ -0,0 +1,19 @@ +# count instructions per function (PROF=1 in devgb): exec devgb with a block hook +import os, sys, subprocess, bisect, collections +elf = sys.argv[1] +fs = [] +for l in subprocess.run(['llvm-nm', '-S', '--size-sort', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 4 and p[2] in 'tT': fs.append((int(p[0], 16) & ~1, int(p[1], 16), p[3])) +fs.sort(); starts = [f[0] for f in fs] +cnt = collections.Counter() +def blk(uc, addr, size, ud): + i = bisect.bisect_right(starts, addr) - 1 + if i >= 0 and addr < fs[i][0] + fs[i][1]: cnt[fs[i][2]] += size // 2 + else: cnt['?'] += size // 2 +import builtins +builtins.__gbprof = (blk, cnt) + +exec(open(os.path.join(os.path.dirname(__file__), 'devgb.py')).read()) +tot = sum(cnt.values()) +for n, c in cnt.most_common(25): print('%6.2f%% %s' % (100 * c / tot, n)) diff --git a/guide.html b/guide.html new file mode 100644 index 0000000..53fa68d --- /dev/null +++ b/guide.html @@ -0,0 +1,9 @@ + +사용 안내 · 다마고치 연구소 + +← 편집 도구로 돌아가기

ITOSM · Paramix Studio 한국어판

다마고치 연구소 사용 안내

+

먼저 파일 열기

이미 작업한 기기라면 현재 상태의 ROM과 저장 데이터를 먼저 읽어 보관하세요. 원본 ROM 또는 현재 읽은 16 MB 파일을 열면 캐릭터·저장·본체 메뉴 등의 탭이 나타납니다. 파일 열기·편집은 PC 브라우저 안에서 처리합니다.

기기 연결은 PC의 Chrome 또는 Edge에서 지원합니다. 장비는 서버가 아니라 사용 중인 PC에 연결하세요.

+

A+C 본체 메뉴를 한국어로

  1. 현재 기기에서 읽은 ROM을 엽니다.
  2. 본체 메뉴 탭에서 본체 A+C 메뉴를 한국어로 만들기를 선택합니다.
  3. 저장 슬롯·아이템·다마고치 수정 등 필요한 메뉴 기능을 켭니다.
  4. 새 ROM 저장으로 결과를 보관합니다. 파일 저장만으로 본체가 바뀌지는 않습니다.
  5. 기기에 적용하려면 ‘기기’에서 기록합니다. 안내되는 저장 보존 조건을 확인하세요.

영문으로 돌아가려면 같은 옵션을 끄고 다시 구성합니다. 한글 메뉴가 들어간 ROM은 열 때 자동으로 한글 옵션을 선택합니다. 한국어판 ROM에 있는 다마고치 이름과 아이템 이름을 본편과 A+C 메뉴에서 사용합니다. 이름 탭에서 수정한 한글도 새 ROM에 반영합니다. 본체가 지원하는 완성형 한글 2350자 범위를 벗어나면 입력 오류를 안내합니다.

첫 화면에서는 A 버튼이나 휠로 이동합니다. B 버튼은 선택이고 C 버튼은 뒤로입니다. 다마고치와 아이템 선택 화면에서는 휠로 대상을 고릅니다. A 버튼으로 성장 단계나 아이템 분류를 바꿀 수 있습니다.

한국어 아이콘 메뉴
아이콘으로 고르는 본체 메뉴
다마고치 그림과 한국어 이름
다마고치 그림과 한국어 이름
아이템 그림과 한국어 이름
아이템 선택 화면
다마포인트 편집 화면
다마포인트 편집 화면
+

육성 데이터 편집

저장 관리에서 ROM의 저장 데이터를 열면 레벨과 다마고치 종류 및 성장 단계를 수정할 수 있습니다. 배부름은 0~6이고 행복은 0~20입니다. 숫자가 클수록 배부르고 행복한 상태입니다. 건강 회복도 선택할 수 있습니다.

서버 우선 백업

관리자가 서버 우선 방식을 선택하면 회원과 비회원 모두 기기에서 읽은 데이터를 서버에 저장합니다. 서버에서 내려받은 파일의 크기와 확인값을 검사한 뒤 PC에 저장하고 편집에 사용합니다. 임시 파일은 업로드한 브라우저의 쿠키로만 받을 수 있으며 기본 보관 기간은 24시간입니다.

서버 저장에 실패하면 다운로드하지 않고 읽은 데이터를 현재 탭에 유지합니다. 탭을 닫지 말고 서버 저장 재시도를 누르세요. 관리자는 백업 방식과 임시 저장 용량 및 보관 기간을 바꿀 수 있습니다. 로그인한 회원의 개인 보관함은 별도로 유지됩니다.

추가 프로그램 설정

에뮬레이터와 추가 게임은 기본적으로 꺼져 있습니다. 관리자가 관리자 패널에서 기능별로 켤 수 있습니다.

기종별 원본 복원

로그인한 뒤 기종별 복원 메뉴에서 공개된 파일을 선택하고 파일 검증 → 본체 연결 → 복원을 진행하세요. 제이드 포레스트 최초 원본을 등록했습니다. 복원 시 현재 펌웨어·추가 메뉴·저장 데이터가 백업 당시 상태로 교체됩니다.

여섯 지역 통합 · 회원 전용

  1. 회원가입 또는 로그인합니다.
  2. 상단 기기 메뉴에서 트로피컬 또는 글레이셔 본체를 연결합니다.
  3. 기기 메뉴의 여섯 지역 확장을 열어 ROM 읽기·백업을 마친 뒤 여섯 지역 모두 추가를 선택합니다.
  4. 지역 그림을 가져올 랜드·워터·스카이 중 하나의 원본 ROM을 선택합니다.
  5. 같은 메뉴의 설정한 ROM을 기기에 기록 버튼으로 진행합니다. 기록 전 확인창에서 내용을 확인하세요.

제이드 포레스트 원본만으로는 여섯 지역 통합이 되지 않으며 기존 네 지역 확장만 가능합니다. 두 원본이 필요합니다. 이미 다른 수정을 적용한 펌웨어는 호환 검사에서 차단될 수 있습니다.

회원 개인 보관함

회원가입·내 보관함에서 선택적으로 가입할 수 있습니다. 회원마다 총 160 MiB의 공간에 덤프를 최대 10개까지 보관할 수 있습니다. 비회원도 편집과 추출을 이용할 수 있습니다. 기종별 복원은 로그인 후 이용할 수 있습니다. 로그인 상태에서 본체 ROM을 추출하면 개인 보관함에도 저장됩니다. 서버 우선 방식에서는 서버 저장과 내려받은 파일의 검증을 마친 뒤 PC에 저장합니다. 개인 보관함이 가득 차면 임시 서버 백업을 이용합니다. 임시 서버 백업에 실패하면 현재 탭에서 재시도할 수 있습니다.

보관함에서 PC 덤프 업로드, 다운로드, 이름 변경, 삭제, 편집 도구에서 열기 및 개인 백업 복원을 사용할 수 있습니다. 개인 파일은 본인만 접근하며 자동 공개되지 않습니다. 회원가입 후 표시하는 복구 코드를 보관하면 이메일 없이 비밀번호를 재설정할 수 있습니다.

언어와 배포 자료

상단에서 한국어·EN·DE를 선택할 수 있습니다. 웹 언어와 본체 메뉴 언어는 별도로 선택합니다.

오프라인 HTML 다운로드 · GPL 라이선스 · 저작권 안내 · 한글 글꼴 라이선스

원작: mameise / Paramix Studio. 한글 메뉴 글꼴: quiple / Galmuri9. BANDAI의 공식 도구가 아닙니다.

+ + diff --git a/member-nav.js b/member-nav.js new file mode 100644 index 0000000..aaa7863 --- /dev/null +++ b/member-nav.js @@ -0,0 +1,10 @@ +'use strict'; +async function refreshMemberNavigation() { + let signedIn=false,admin=false; + try { const r=await fetch('/api/member/me',{cache:'no-store'}); const me=r.ok?await r.json():{};signedIn=!!me.authenticated;admin=signedIn && !!me.isAdmin; } catch(e) {} + document.querySelectorAll('[data-member-restore]').forEach(el=>{el.hidden=!signedIn;}); + document.querySelectorAll('[data-member-admin]').forEach(el=>{el.hidden=!admin;}); +} +refreshMemberNavigation(); +window.addEventListener('focus',refreshMemberNavigation); +window.addEventListener('member-session-change',refreshMemberNavigation); diff --git a/nginx-static.conf b/nginx-static.conf new file mode 100644 index 0000000..a3f754d --- /dev/null +++ b/nginx-static.conf @@ -0,0 +1,28 @@ +limit_conn_zone $server_name zone=archive_parallel:1m; +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + charset utf-8; + client_max_body_size 17m; + location /api/ { + limit_conn archive_parallel 4; + resolver 127.0.0.11 valid=10s ipv6=off; + set $backup_host backup; + proxy_pass http://$backup_host:8080; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $http_x_real_ip; + proxy_read_timeout 120s; + proxy_send_timeout 120s; + add_header X-Robots-Tag noindex always; + } + location / { + try_files $uri $uri/ =404; + add_header Cache-Control "no-cache"; + add_header X-Content-Type-Options nosniff; + } + location ~ /\. { deny all; } + gzip on; + gzip_types text/plain application/javascript application/json; +} diff --git a/pm/README.md b/pm/README.md new file mode 100644 index 0000000..a7fb1f0 --- /dev/null +++ b/pm/README.md @@ -0,0 +1,41 @@ +# PokeMiniEmu + +The Pokemon mini on the Tamagotchi Paradise, as a further program of the Paramix menu. +No game and no BIOS here: bring your own games (.min). Without an own BIOS the free BIOS of PokeMini runs. + +- `src/core`: PokeMini by JustBurn (GPL 3 or later, `LICENSE_pokemini`), libretro version, commit 132111b. Taken: + the CPU (MinxCPU*), PRC (picture chip), LCD, timers, IRQ, I/O (keys, EEPROM, RTC), sound registers, Hardware.c, + FreeBIOS. `pm_glue.c` replaces PokeMini.c and PMCommon.c (no files, no colour PRC, no multicart): create, reset, the + cartridge in the flash window (`pm_set_rom`), the clock (`pm_set_time`), the state in a buffer (`pm_state_save`, + `pm_state_load`, PokeMini's sections without the colour part). Changes in the core files are marked "PokeMiniEmu": + `MinxLCD.c` without Video.h, `Hardware.c` with `PM_SYNCCYCLES` and `PM_FASTLCD`, `MinxAudio.c` with `pm_audio_now`. +- `src/stub`: the few C library headers the core needs, and a small memory stream. +- `src/app/main.c`: the Paradise program (PRAM, about 62 KB). Settings block "PMXP" at 0x140: game, length, save + (64 KB: 4 KB settings of the device, 8 KB EEPROM, the state up to 36 KB, an own BIOS at +0xC000), flags (bit 0 + English, bit 1 wheel the other way round, bit 2 own BIOS), name, keys (12 x u16, see below), place of the BIOS. +- Screen: 96 x 64 to 128 x 85 from y 21 (3 dots to 4: a, (a+2b)/3, (2b+c)/3, c, both ways). PM_FASTLCD: the program + reads the LCD memory itself for every second frame and mixes it with the frame before (dot on in one of the two: + grey), the core's per-dot buffers and the analog decay are left out (18 % of the time). The contrast of the game + sets the two shades. +- Keys: `keys[i]` are Pokemon mini buttons (1 A, 2 B, 4 C, 8 up, 16 down, 32 left, 64 right, 128 power, 256 shake) + for the Paradise input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. Default: A + left, B = B, C right, wheel press = A, wheel up/down, A+C = C, A+B shake. Fixed: A+B+C settings (power, colour, + sound, light, dim, screen off, restart game, language); wheel held 2 s = save and back to the Paradise. +- Sound: timer 3 of the Pokemon mini drives its piezo; its frequency (and silence at volume 0 or a pulse of 0 or + 100 %) goes to the Paradise's buzzer once per frame. +- Save: the EEPROM goes to the flash 3 s after the game wrote it (1 s without a key), when the screen goes off and on + leaving. On leaving the whole state too (`emu/src/emu/pstate.h`), read once at the next start. +- Clock: a new start sets the Pokemon mini's clock from the Paradise's time (the games still ask for their own time + once). The seconds counter keeps running while the game waits (settings, screen off, back in the Paradise): the + seconds of the Paradise's counter are added when it goes on. +- Speed (Unicorn simulation, 96 MHz): all 13 tried games at full speed (72 frames a second), 3 to 10 ms per frame. + +Build: `sh src/app/build.sh` (clang, lld) gives `pm.bin`. +Test: `python3 test/mkimg.py pm.bin game.min img.bin [flags] [bios.min]` then +`python3 test/devpm.py src/app/pm.elf img.bin ` (KEYS="t:mask,...", SHOTS="t,...", OUT=dir); `test/prof.py` +counts instructions per function. + +Author: mameise + +No session (1.7.3 test7, switch SESS_FLAG): flags bit 12 set by the Studio ("Remember where you left off" off): leaving writes +no state, a start drops an old one; only the game's own save (cartridge RAM or EEPROM) is kept. diff --git a/pm/pm.bin b/pm/pm.bin new file mode 100644 index 0000000..455cf6e Binary files /dev/null and b/pm/pm.bin differ diff --git a/pm/src/app/build.sh b/pm/src/app/build.sh new file mode 100644 index 0000000..d79fc2e --- /dev/null +++ b/pm/src/app/build.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# Build PokeMiniEmu for the Paradise (clang/lld, Cortex-M3). Output: ../../pm.bin +set -e +cd "$(dirname "$0")" +E=../../../emu/src/emu +C=../core +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -Wno-unused-variable -Wno-unused-but-set-variable -Wno-parentheses -Wno-dangling-else -fno-builtin-memset -ffunction-sections -isystem ../stub -I$C -DPERFORMANCE -DPM_SYNCCYCLES=64 -DPM_FASTLCD -DPM_HEAP=0x7400 -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DHW_TONE_RESTART -DBL_SLEEP -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DTONE_SAFE -DGPLAY -DSESS_FLAG $XCF" +O="" +for f in main.c $C/*.c $E/hw.c $E/flash.c $E/libc.c; do + n=$(basename $f .c); OPT=-Os + case $n in MinxCPU*|Hardware|MinxPRC|MinxTimers|MinxIRQ) OPT=-O2;; esac + clang $CF $OPT -c $f -o $n.o; O="$O $n.o"; done +ld.lld -T link.ld --gc-sections --no-rosegment $O -o pm.elf +llvm-objcopy -O binary -j .text -j .data -j .init pm.elf pm.bin +cp pm.bin ../../pm.bin; rm -f *.o pm.bin; [ -n "$KEEPELF" ] || rm -f pm.elf; ls -l ../../pm.bin diff --git a/pm/src/app/font.h b/pm/src/app/font.h new file mode 100644 index 0000000..b01afaa --- /dev/null +++ b/pm/src/app/font.h @@ -0,0 +1,99 @@ +/* generated by gen/font.py: custom 5x7 font */ +static const unsigned char g_font[96][7]={ + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x04,0x04,0x04,0x04,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x19,0x19,0x02,0x04,0x08,0x13,0x13}, + {0x0c,0x12,0x14,0x08,0x15,0x12,0x0d}, + {0x04,0x04,0x08,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x08,0x08,0x04,0x02}, + {0x08,0x04,0x02,0x02,0x02,0x04,0x08}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x04,0x04,0x1f,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x0c,0x04,0x08}, + {0x00,0x00,0x00,0x1f,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x0c,0x0c}, + {0x01,0x01,0x02,0x04,0x08,0x10,0x10}, + {0x0e,0x11,0x13,0x15,0x19,0x11,0x0e}, + {0x04,0x0c,0x04,0x04,0x04,0x04,0x0e}, + {0x0e,0x11,0x01,0x02,0x04,0x08,0x1f}, + {0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e}, + {0x02,0x06,0x0a,0x12,0x1f,0x02,0x02}, + {0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e}, + {0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e}, + {0x1f,0x01,0x02,0x04,0x08,0x08,0x08}, + {0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e}, + {0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e}, + {0x00,0x04,0x04,0x00,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x10,0x08,0x04,0x02}, + {0x00,0x00,0x1f,0x00,0x1f,0x00,0x00}, + {0x08,0x04,0x02,0x01,0x02,0x04,0x08}, + {0x0e,0x11,0x01,0x02,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x0e,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e}, + {0x0e,0x11,0x10,0x10,0x10,0x11,0x0e}, + {0x1e,0x11,0x11,0x11,0x11,0x11,0x1e}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x10,0x17,0x11,0x11,0x0f}, + {0x11,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x0e,0x04,0x04,0x04,0x04,0x04,0x0e}, + {0x07,0x02,0x02,0x02,0x02,0x12,0x0c}, + {0x11,0x12,0x14,0x18,0x14,0x12,0x11}, + {0x10,0x10,0x10,0x10,0x10,0x10,0x1f}, + {0x11,0x1b,0x15,0x15,0x11,0x11,0x11}, + {0x11,0x19,0x15,0x13,0x11,0x11,0x11}, + {0x0e,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x1e,0x11,0x11,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x11,0x11,0x15,0x12,0x0d}, + {0x1e,0x11,0x11,0x1e,0x14,0x12,0x11}, + {0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e}, + {0x1f,0x04,0x04,0x04,0x04,0x04,0x04}, + {0x11,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x11,0x11,0x11,0x11,0x0a,0x04}, + {0x11,0x11,0x11,0x15,0x15,0x15,0x0a}, + {0x11,0x11,0x0a,0x04,0x0a,0x11,0x11}, + {0x11,0x11,0x0a,0x04,0x04,0x04,0x04}, + {0x1f,0x01,0x02,0x04,0x08,0x10,0x1f}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x11,0x0a,0x04,0x0a,0x11}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x11,0x0e,0x11,0x1f,0x11,0x11,0x11}, + {0x11,0x0e,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x00,0x11,0x11,0x11,0x11,0x0e}, +}; diff --git a/pm/src/app/link.ld b/pm/src/app/link.ld new file mode 100644 index 0000000..106ae96 --- /dev/null +++ b/pm/src/app/link.ld @@ -0,0 +1,23 @@ +ENTRY(Reset_Handler) +MEMORY { + PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000 + SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000 +} +SECTIONS { + .text : { + KEEP(*(.vectors)) + KEEP(*(.pmxcfg)) + *(.text*) + *(.rodata*) + . = ALIGN(4); + __pdata_start = .; + } > PRAM + .bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM + /* mutable data in SRAM (initial values in PRAM, copied at startup), as in TamaEmu */ + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + .init : { . = ALIGN(4); KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); __prog_end = .; } > PRAM + ASSERT(__prog_end <= 0x10000, "program too big for PRAM") + ASSERT(__bss_end <= 0x1801F000, "RAM full") + /DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/pm/src/app/main.c b/pm/src/app/main.c new file mode 100644 index 0000000..50240ec --- /dev/null +++ b/pm/src/app/main.c @@ -0,0 +1,519 @@ +/* PokeMiniEmu: the Pokemon mini on the Tamagotchi Paradise. Core: PokeMini by JustBurn (GPL 3 or later), see ../core. + * Started from the Paramix menu like the other further programs. Bring your own games (.min); the BIOS is the free one + * of PokeMini unless the Studio put your own in. + * Screen: 96 x 64 grown to 128 x 85 (3 dots to 4, mixed), with the grey shades of the real LCD (the core's analog LCD). + * Keys: set in the Studio (tab Pokemon mini), stored in the settings block. A+B+C together: settings (also POWER and + * sound); wheel held 2 s: save and back to the Paradise. Sound: the Paradise's buzzer plays the Pokemon mini's tone. + * Save: the EEPROM (the games' saves) goes to the flash a few seconds after the game wrote it, and on leaving; on + * leaving the whole state too, the next start continues there. + * Author: mameise */ +#include "../../../emu/src/emu/hw.h" +#include "../../../emu/src/emu/exitkey.h" +#include "../../../emu/src/emu/flash.h" +#define PARA_ATTR +#include "../../../emu/src/emu/paraclock.h" +#ifdef PARA_BACK +#include "../../../emu/src/emu/paraback.h" +#ifdef GPLAY +#define GP_POINTS +#include "../../../emu/src/emu/gplay.h" +#endif +#endif +#include "PokeMini.h" +#include "Hardware.h" +#include "font.h" +typedef int s32; + +/* ---- settings block at 0x140, filled in by the Studio ---- + * keys[i]: Pokemon mini buttons (bit 0 A, 1 B, 2 C, 3 UP, 4 DOWN, 5 LEFT, 6 RIGHT, 7 POWER, 8 SHAKE) for the Paradise + * input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. + * flags: bit 0 English, bit 1 wheel the other way round, bit 2 own BIOS at bios_off. + * save_off: 4 KB settings of the device, 8 KB EEPROM, then the state (up to 36 KB). */ +#define NIN 9 +typedef struct { u32 magic, version, rom_off, rom_len, save_off, flags; char name[16]; u16 keys[12]; u32 bios_off; } PmCfg; +#define PM_MAGIC 0x50584D50u /* "PMXP" */ +__attribute__((section(".pmxcfg"), used)) +volatile const PmCfg g_cfg = { PM_MAGIC, 1, 0, 0, 0, 0, {0}, { 0x020, 0x002, 0x040, 0x001, 0x008, 0x010, 0x004, 0x000, 0x100 }, 0 }; +#define SETTINGS (g_cfg.save_off) +#define EEP_AT (g_cfg.save_off + 0x1000u) +#define STATE_AT (g_cfg.save_off + 0x3000u) +#define STATE_MAX 0x9000u +#define STATE_N 0x7400u +#define XIP_BASE_REG REG(0x4002F004u) +#define XIP_CTRL_REG REG(0x4002F000u) +#define ROMWIN ((const u8 *)0x10000000u) +void pm_set_rom(const uint8_t *rom, uint32_t len); +void pm_set_time(int y, int mo, int d, int h, int mi, int s); +uint32_t pm_state_save(uint8_t *buf, uint32_t size); +int pm_state_load(uint8_t *buf, uint32_t size); +void pm_audio_now(int *hz, int *vol); +extern int PokeMini_EEPROMWritten; + +/* ---- time: SysTick 1 ms; the wheel's encoder is read here too ---- */ +static volatile u32 g_ms; +static volatile s32 g_enc_acc; static u32 g_enc_last; +static const signed char QD[16] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 }; +#define GPIO2 0x4001A000u +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +#define CORE_HZ 96000000u +__attribute__((used)) void systick_c(void) +{ + g_ms++; + u32 n = REG(GPIO2) & 3u; + if (n != g_enc_last) { g_enc_acc += QD[(g_enc_last << 2) | n]; g_enc_last = n; } +} +__attribute__((naked)) void SysTick_Handler(void) { __asm__ volatile("b systick_c\n"); } +void abort(void) { for (;;) hw_wdt_feed(); } + +/* ---- settings on the device ---- */ +typedef struct { u8 magic[4]; u8 pal, dim, lang, dimto, off, r0, skip, mute; } PmSet; /* mute: 0 = sound on */ +static PmSet g_set = { {'P','M','S','1'}, 0, 7, 0, 6, 3, 0x80, 0, 0 }; +/* light to dark: grey green (as the real LCD), grey, yellow, blue */ +static const u16 PAL[4][2] = { { 0xB6B1u, 0x1903u }, { 0xE71Cu, 0x10A2u }, { 0xFFF4u, 0x2100u }, { 0xDF5Fu, 0x0846u } }; +static const char *const PAL_NM[2][4] = { { "LCD", "GRAU", "GELB", "BLAU" }, { "LCD", "GREY", "YELLOW", "BLUE" } }; +#define T_N 7 +static const u32 T_MS[T_N] = { 10000u, 20000u, 30000u, 60000u, 120000u, 300000u, 600000u }; +static const char *const T_NM[2][T_N + 1] = { { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NIE" }, { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NEVER" } }; +#define LV_N 11 +#define DIM2_N 10 +static const u8 LV_PCT[LV_N] = { 100u, 5u, 10u, 20u, 30u, 40u, 50u, 60u, 70u, 80u, 90u }; +static const u8 DIM2_PCT[DIM2_N] = { 1u, 2u, 3u, 5u, 10u, 15u, 20u, 30u, 40u, 50u }; +static int en(void) { return g_set.lang ? g_set.lang == 2u : (int)(g_cfg.flags & 1u); } +static u16 BG, INK, OFF; +static u16 g_lut[256]; /* LCD intensity (0 light .. 255 dark) to colour */ +static int g_dimmed, g_redraw; +static u16 mix(u16 a, u16 b, int p, int q) /* a + (b - a) * p / q */ +{ + int r = (a >> 11) + (((b >> 11) - (a >> 11)) * p) / q, g = ((a >> 5) & 63) + ((((b >> 5) & 63) - ((a >> 5) & 63)) * p) / q; + int bl = (a & 31) + (((b & 31) - (a & 31)) * p) / q; + return (u16)((r << 11) | (g << 5) | bl); +} +static void colours(void) +{ + const u16 *p = PAL[g_set.pal & 3u]; + for (int v = 0; v < 256; v++) g_lut[v] = mix(p[0], p[1], v, 255); + BG = p[0]; INK = p[1]; OFF = g_lut[150]; +#ifdef BL_PWM + { u32 l = LV_PCT[(g_set.r0 & 15u) % LV_N], d = DIM2_PCT[g_set.dimto % DIM2_N]; + hw_bl_set(g_dimmed ? (d < l ? d : l) : l); } +#endif + g_redraw = 1; +} +static u8 g_sec[0x1000] __attribute__((aligned(4))); +static void set_load(void) +{ + const volatile u8 *p = XIP_PTR(SETTINGS); PmSet t; u8 *d = (u8 *)&t; + for (u32 i = 0; i < sizeof t; i++) d[i] = p[i]; + if (t.magic[0] == 'P' && t.magic[1] == 'M' && t.magic[2] == 'S' && t.magic[3] == '1' && t.pal < 4u && t.dim <= T_N && t.off <= T_N && t.lang < 3u) g_set = t; + colours(); +} +static void set_store(void) +{ + for (u32 i = 0; i < sizeof g_sec; i++) g_sec[i] = 0xFF; + const u8 *s = (const u8 *)&g_set; for (u32 i = 0; i < sizeof g_set; i++) g_sec[i] = s[i]; + flash_update4k(SETTINGS, g_sec); +} + +/* ---- EEPROM (the games' saves, 8 KB) ---- */ +static u32 g_tone_now; +static void tone(u32 hz) { if (hz != g_tone_now) { if (hz && g_tone_now) hw_tone(0); g_tone_now = hz; hw_tone(hz); } } +static void eep_load(void) +{ + const volatile u8 *p = XIP_PTR(EEP_AT); int any = 0; + for (u32 i = 0; i < 0x2000u; i++) { u8 v = p[i]; EEPROM[i] = v; if (v != 0xFF) any = 1; } + (void)any; /* a fresh area (all 0xFF) is a fresh EEPROM, as PokeMini formats it */ +} +static void eep_store(void) +{ + for (u32 o = 0; o < 0x2000u; o += 0x1000u) { + for (u32 i = 0; i < 0x1000u; i++) g_sec[i] = EEPROM[o + i]; + tone(0); flash_update4k(EEP_AT + o, g_sec); + } + PokeMini_EEPROMWritten = 0; +} + +/* ---- screen: 96 x 64 to 128 x 85 (3 dots to 4: a, (a+2b)/3, (2b+c)/3, c), from y 21 ---- */ +#define OY 21 +#define OH 85 +static u8 g_fb[OH][128] __attribute__((aligned(4))); /* intensity 0..255 */ +static u16 g_row[128] __attribute__((aligned(4))); +static int g_dirty_lo = OH, g_dirty_hi = -1; +static u8 g_hl[3][128]; /* the three source rows of a group, grown across */ +static void grow_row(const u8 *s, u8 *d) +{ + for (int k = 0; k < 32; k++, s += 3, d += 4) { + u32 a = s[0], b = s[1], c = s[2]; + d[0] = (u8)a; d[1] = (u8)((a + 2u * b) / 3u); d[2] = (u8)((2u * b + c) / 3u); d[3] = (u8)c; + } +} +static void out_row(int r, const u8 *v) +{ + if (r >= OH) return; + u32 *f = (u32 *)g_fb[r], d = 0; const u32 *w = (const u32 *)v; + for (int x = 0; x < 32; x++) { d |= f[x] ^ w[x]; f[x] = w[x]; } + if (d) { if (r < g_dirty_lo) g_dirty_lo = r; if (r > g_dirty_hi) g_dirty_hi = r; } +} +#ifdef PM_FASTLCD +/* the LCD memory (8 pages of 96 columns, one bit per dot) of the frame before the shown one: dots on in one of the two + * frames are grey (games make their grey by switching dots every frame) */ +static u8 g_prev[8 * 96], g_src[96 * 64] __attribute__((aligned(4))); +static void lcd_snap(void) { for (int p = 0; p < 8; p++) for (int x = 0; x < 96; x++) g_prev[p * 96 + x] = LCDData[p * 256 + x]; } +static void lcd_mix(void) +{ + if (!MinxLCD.DisplayOn) { for (int i = 0; i < 96 * 64; i++) g_src[i] = 0; return; } + u8 lv[3]; int p0 = MinxLCD.Pixel0Intensity, p1 = MinxLCD.Pixel1Intensity; + lv[0] = (u8)p0; lv[1] = (u8)((p0 + p1) / 2); lv[2] = (u8)p1; + u32 inv = MinxLCD.InvAllPix & 1u, set = MinxLCD.SetAllPix & 1u; + for (int y = 0; y < 64; y++) { + int yp = (y + MinxLCD.StartLine) & 63; if (MinxLCD.RowOrder) yp = 63 - yp; + const u8 *c = LCDData + (yp >> 3) * 256, *q = g_prev + (yp >> 3) * 96; u32 sh = (u32)yp & 7u; u8 *d = g_src + y * 96; + for (int x = 0; x < 96; x++) { u32 a = (((c[x] >> sh) & 1u) ^ inv) | set, b = (((q[x] >> sh) & 1u) ^ inv) | set; d[x] = lv[a + b]; } + } +} +#endif +static void frame_grow(void) +{ +#ifdef PM_FASTLCD + const u8 *src = g_src; +#else + const u8 *src = LCDPixelsA; +#endif + static u8 t[128] __attribute__((aligned(4))); + for (int g = 0; g < 22; g++) { /* rows 3g..3g+2 to 4g..4g+3 (the last group has row 63 only) */ + int n = g < 21 ? 3 : 1; + for (int i = 0; i < n; i++) grow_row(src + (3 * g + i) * 96, g_hl[i]); + out_row(4 * g, g_hl[0]); + if (n < 3) break; + for (int x = 0; x < 128; x++) t[x] = (u8)((g_hl[0][x] + 2u * g_hl[1][x]) / 3u); + out_row(4 * g + 1, t); + for (int x = 0; x < 128; x++) t[x] = (u8)((2u * g_hl[1][x] + g_hl[2][x]) / 3u); + out_row(4 * g + 2, t); + out_row(4 * g + 3, g_hl[2]); + } +} +static void push(int all) +{ + if (g_redraw) { g_redraw = 0; all = 1; } + int lo = all ? 0 : g_dirty_lo, hi = all ? OH - 1 : g_dirty_hi; + if (all) { /* the bars */ + for (int x = 0; x < 128; x++) g_row[x] = BG; + hw_px_begin(0, 0, 128, OY); for (int y = 0; y < OY; y++) hw_px_row(g_row, 128); hw_px_end(); + hw_px_begin(0, OY + OH, 128, 128); for (int y = OY + OH; y < 128; y++) hw_px_row(g_row, 128); hw_px_end(); + } + if (lo > hi) return; + hw_px_begin(0, (u32)(OY + lo), 128, (u32)(OY + hi + 1)); + for (int y = lo; y <= hi; y++) { const u8 *f = g_fb[y]; for (int x = 0; x < 128; x++) g_row[x] = g_lut[f[x]]; hw_px_row(g_row, 128); } + hw_px_end(); + g_dirty_lo = OH; g_dirty_hi = -1; +} + +/* ---- the settings menu (A+B+C): A next line, B change, C close ---- */ +static int g_menu, g_msel, g_mtop; +static void text(int x, int y, const char *s, u16 col, u16 *row, int ry) +{ + for (; *s; s++, x += 6) { + int c = (unsigned char)*s; if (c >= 97 && c <= 122) c -= 32; c = (c < 32 || c > 127) ? 0 : c - 32; + if (ry < y || ry >= y + 7) continue; + u8 bits = g_font[c][ry - y]; + for (int k = 0; k < 5; k++) if ((bits & (0x10 >> k)) && x + k >= 0 && x + k < 128) row[x + k] = col; + } +} +enum { M_POW, M_PAL, M_SND, M_LIGHT, M_DIM, M_DIMTO, M_OFF, M_RESET, M_LANG, M_N }; +static u32 g_power_until; /* menu line POWER: pressed for 200 ms after the menu closes */ +static int g_items[M_N], g_nitems; +static void menu_items(void) +{ + g_nitems = 0; + for (int k = 0; k < M_N; k++) { if (k == M_DIMTO && g_set.dim >= T_N) continue; g_items[g_nitems++] = k; } + if (g_msel >= g_nitems) g_msel = g_nitems - 1; +} +static void pct(char *o, int v) { int n = 0; if (v >= 100) o[n++] = '1'; if (v >= 10) o[n++] = (char)('0' + (v / 10) % 10); o[n++] = (char)('0' + v % 10); o[n++] = '%'; o[n] = 0; } +static int g_reset_ask; +static void menu_line(int it, const char **a, char *b) +{ + int e = en(); const char *v = 0; b[0] = 0; + switch (it) { + case M_POW: *a = e ? "PRESS POWER" : "POWER DRUECKEN"; v = "B"; break; + case M_PAL: *a = e ? "COLOUR" : "FARBE"; v = PAL_NM[e][g_set.pal & 3u]; break; + case M_SND: *a = e ? "SOUND" : "TON"; v = g_set.mute ? (e ? "OFF" : "AUS") : (e ? "ON" : "AN"); break; + case M_LIGHT: *a = e ? "LIGHT" : "LICHT"; pct(b, LV_PCT[(g_set.r0 & 15u) % LV_N]); break; + case M_DIM: *a = e ? "DIM AFTER" : "DIMMEN NACH"; v = T_NM[e][g_set.dim <= T_N ? g_set.dim : T_N]; break; + case M_DIMTO: *a = e ? "DIM TO" : "DIMMEN AUF"; pct(b, DIM2_PCT[g_set.dimto % DIM2_N]); break; + case M_OFF: *a = e ? "SCREEN OFF" : "BILD AUS NACH"; v = T_NM[e][g_set.off <= T_N ? g_set.off : T_N]; break; + case M_RESET: *a = e ? "RESTART GAME" : "SPIEL NEU"; v = g_reset_ask ? (e ? "SURE? B" : "SICHER? B") : ""; break; + default: *a = e ? "LANGUAGE" : "SPRACHE"; v = e ? "ENGLISH" : "DEUTSCH"; break; + } + if (v) { int n = 0; while (v[n] && n < 11) { b[n] = v[n]; n++; } b[n] = 0; } +} +#define ROWS 9 +static void menu_draw(void) +{ + if (g_msel < g_mtop) g_mtop = g_msel; + if (g_msel >= g_mtop + ROWS) g_mtop = g_msel - ROWS + 1; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + for (int x = 0; x < 128; x++) g_row[x] = BG; + text(4, 3, en() ? "SETTINGS" : "EINSTELLUNGEN", INK, g_row, y); + if (y == 12) for (int x = 0; x < 128; x++) g_row[x] = OFF; + for (int k = 0; k < ROWS && g_mtop + k < g_nitems; k++) { + int i = g_mtop + k, ly = 16 + k * 11; const char *a; char b[12]; menu_line(g_items[i], &a, b); + if (i == g_msel && y >= ly - 2 && y < ly + 9) for (int x = 0; x < 128; x++) g_row[x] = INK; + u16 c = i == g_msel ? BG : INK; + text(4, ly, a, c, g_row, y); int w = 0; while (b[w]) w++; text(124 - w * 6, ly, b, c, g_row, y); + } + text(4, 118, en() ? "A NEXT B SET C OK" : "A ZEILE B SETZEN C OK", OFF, g_row, y); + hw_px_row(g_row, 128); + } + hw_px_end(); +} +static int g_set_dirty; +static void pm_fresh(void); +static void pause_end(void); +static void menu_close(void) { pause_end(); g_menu = 0; g_reset_ask = 0; if (g_set_dirty) { set_store(); g_set_dirty = 0; } push(1); } +static void menu_key(u32 k) +{ + if (k & BTN_A) { g_msel = (g_msel + 1) % g_nitems; g_reset_ask = 0; } + if (k & BTN_B) { + switch (g_items[g_msel]) { + case M_POW: g_power_until = g_ms + 200u; menu_close(); return; + case M_PAL: g_set.pal = (u8)((g_set.pal + 1u) & 3u); break; + case M_SND: g_set.mute ^= 1u; break; + case M_LIGHT: g_set.r0 = (u8)(0x80u | (((g_set.r0 & 15u) + 1u) % LV_N)); break; + case M_DIM: g_set.dim = (u8)((g_set.dim + 1u) % (T_N + 1u)); if (g_set.dim < T_N && g_set.off < T_N && g_set.off <= g_set.dim) g_set.off = (u8)(g_set.dim + 1u); break; + case M_DIMTO: g_set.dimto = (u8)((g_set.dimto + 1u) % DIM2_N); break; + case M_OFF: do g_set.off = (u8)((g_set.off + 1u) % (T_N + 1u)); while (g_set.off < T_N && g_set.dim < T_N && g_set.off <= g_set.dim); break; + case M_RESET: if (g_reset_ask) { g_reset_ask = 0; pm_fresh(); menu_close(); return; } g_reset_ask = 1; break; + default: g_set.lang = (u8)(en() ? 1u : 2u); break; + } + if (g_items[g_msel] != M_RESET && g_items[g_msel] != M_POW) g_set_dirty = 1; + colours(); menu_items(); + } + if (k & BTN_C) { menu_close(); return; } + menu_draw(); +} +static void message(const char *a, const char *b) +{ + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { for (int x = 0; x < 128; x++) g_row[x] = BG; text(4, 50, a, INK, g_row, y); text(4, 62, b, INK, g_row, y); hw_px_row(g_row, 128); } + hw_px_end(); +} + +/* ---- keys: the Paradise inputs to the Pokemon mini's buttons (map from the Studio) ---- */ +static u32 g_wheel_until[2]; /* wheel up / down held until (ms) */ +static u32 pm_keys(u32 b, u32 now) +{ + u32 in = 0; + int ac = (b & (BTN_A | BTN_C)) == (BTN_A | BTN_C), bc = (b & (BTN_B | BTN_C)) == (BTN_B | BTN_C), ab = (b & (BTN_A | BTN_B)) == (BTN_A | BTN_B); + u32 used = 0; /* a pair held: its two keys count as the pair only (if the pair has a meaning) */ + if (ac && g_cfg.keys[6]) { in |= 1u << 6; used |= BTN_A | BTN_C; } + if (bc && g_cfg.keys[7]) { in |= 1u << 7; used |= BTN_B | BTN_C; } + if (ab && g_cfg.keys[8]) { in |= 1u << 8; used |= BTN_A | BTN_B; } + u32 r = b & ~used; + if (r & BTN_A) in |= 1u; if (r & BTN_B) in |= 2u; if (r & BTN_C) in |= 4u; if (b & BTN_WHEEL) in |= 8u; + if ((s32)(g_wheel_until[0] - now) > 0) in |= 16u; + if ((s32)(g_wheel_until[1] - now) > 0) in |= 32u; + u32 pm = 0; + for (int i = 0; i < NIN; i++) if (in & (1u << i)) pm |= g_cfg.keys[i]; + if ((s32)(g_power_until - now) > 0) pm |= 0x80u; + return pm; +} +static u32 g_pm_keys; +static void keys_set(u32 k) +{ + u32 ch = k ^ g_pm_keys; if (!ch) return; + for (int i = 0; i < 9; i++) if (ch & (1u << i)) MinxIO_Keypad((u8)(MINX_KEY_A + i), (k >> i) & 1u); /* A, B, C, up, down, left, right, power, shake */ + g_pm_keys = k; +} + +/* ---- the clock of the game from the Paradise's ---- */ +static u32 g_para; +static void time_from_para(void) +{ + if (!g_para) return; + u32 s = g_para, days = s / 86400u, rem = s % 86400u; + s32 z = (s32)days + 719468, era = z / 146097; u32 doe = (u32)(z - era * 146097); + u32 yoe = (doe - doe / 1460u + doe / 36524u - doe / 146096u) / 365u; s32 y = (s32)yoe + era * 400; + u32 doy = doe - (365u * yoe + yoe / 4u - yoe / 100u), mp = (5u * doy + 2u) / 153u, d = doy - (153u * mp + 2u) / 5u + 1u, m = mp < 10u ? mp + 3u : mp - 9u; + if (m <= 2u) y++; + pm_set_time((int)y, (int)m, (int)d, (int)(rem / 3600u), (int)(rem / 60u % 60u), (int)(rem % 60u)); +} +static void bios_load(void) +{ + if ((g_cfg.flags & 4u) && g_cfg.bios_off) { const volatile u8 *p = XIP_PTR(g_cfg.bios_off); for (u32 i = 0; i < 4096u; i++) PM_BIOS[i] = p[i]; PokeMini_FreeBIOS = 0; } + else PokeMini_LoadFreeBIOS(); +} +/* the game anew (settings menu RESTART GAME): the EEPROM stays */ +static void pm_fresh(void) { keys_set(0); PokeMini_Reset(1); time_from_para(); } + +/* ---- the Pokemon mini's clock (its seconds counter) keeps running while the game waits (settings, screen off, back + * in the Paradise): the seconds of the Paradise's counter (it runs always) are added when the game goes on ---- */ +#define PARA_SECS REG(0x45000304u) +static u32 g_pause_cnt; +static void rtc_add(u32 secs) { if (secs && secs < 400u * 86400u && (PMR_SEC_CTRL & 1u)) MinxTimers.SecTimerCnt = (MinxTimers.SecTimerCnt + secs) & 0xFFFFFFu; } +static void pause_begin(void) { if (!g_pause_cnt) g_pause_cnt = PARA_SECS | 0x80000000u; } +static void pause_end(void) { if (g_pause_cnt) { rtc_add((PARA_SECS - g_pause_cnt) & 0x7FFFFFFFu); g_pause_cnt = 0; } } + +/* ---- the whole state on leaving (wheel held), read once at the next start ---- */ +#include "../../../emu/src/emu/pstate.h" +#ifdef SESS_FLAG +#define NOSESS ((g_cfg.flags & 0x1000u) != 0u) /* 1.7.3 test7: the Studio's "remember on leaving" off: only the game's own save */ +#else +#define NOSESS 0 +#endif +static u8 g_st[STATE_N] __attribute__((aligned(4))); +static int g_running; +static u32 st_tag(void) { return 0x504D0001u ^ (u32)STATE_N ^ g_cfg.rom_len ^ (u32)&PM_RAM ^ (u32)PokeMini_EmulateFrame; } +static u32 g_st_cnt; /* the Paradise's seconds counter when the state was stored */ +static void state_store(void) +{ + if (!g_running) return; + pause_end(); + for (u32 i = 0; i < STATE_N; i++) g_st[i] = 0; + if (!pm_state_save(g_st, STATE_N)) return; + g_st_cnt = PARA_SECS; + StPart pt[2] = { { g_st, STATE_N }, { &g_st_cnt, 4 } }; + st_store(STATE_AT, STATE_MAX, st_tag(), pt, 2, g_sec); +} +static int state_load(void) +{ + if (NOSESS) { st_drop(STATE_AT); return 0; } + StPart pt[2] = { { g_st, STATE_N }, { &g_st_cnt, 4 } }; + int ok = st_load(STATE_AT, STATE_MAX, st_tag(), pt, 2) && pm_state_load(g_st, STATE_N); + st_drop(STATE_AT); + if (ok) rtc_add(PARA_SECS - g_st_cnt); /* the time away */ + return ok; +} + +/* ---- leaving ---- */ +static void leave(void) +{ + tone(0); hw_tone(0); + if (g_set_dirty) set_store(); + REG(0x20000FF8u) = 0; + REG(0x20000FFCu) = 0x4C584D50u; /* "PMXL": back on purpose, the autostart stays off */ + if (g_running && !NOSESS) { message(en() ? "SAVING" : "SPEICHERN", ""); state_store(); } + if (PokeMini_EEPROMWritten) eep_store(); +#ifdef PARA_BACK +#ifdef GPLAY + para_points((uint8_t *)g_sec); /* play time to Tamapoints */ +#endif + para_back_fix(g_sec); +#endif + hw_bl_pwm_off(); + for (u32 t = 0; hw_buttons() && t < 20000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); + XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u; + hw_back_to_paradise(); +} + +__attribute__((used)) volatile u32 g_pmst[4]; /* frames run, frames pushed, frames dropped, last frame in ms (for the tests) */ +extern u32 __bss_start, __bss_end; +void Reset_Handler(void) +{ + __asm__ volatile("cpsid i"); + u32 cnt = REG(0x45000304u), para = para_clock(cnt, 0, 0x1F000u, 0, 0); + if (!para) para = para_mailbox(cnt); +#ifdef PARA_FLASH + if (!para) para = para_flash(cnt); +#endif +#ifdef PARA_BACK + para_leave_mark(cnt, para); +#endif + __asm__ volatile("" ::: "memory"); + for (u32 *p = &__bss_start; p < &__bss_end; p++) *p = 0; + { extern u32 __data_start, __data_end, __data_load; + const u32 *src = &__data_load; for (u32 *p = &__data_start; p < &__data_end; p++) *p = *src++; } + g_para = para; + hw_init(); + hw_tone(0); + XIP_BASE_REG = 0x60000000u | g_cfg.rom_off; /* the game in the cached window from 0x10000000 */ + XIP_CTRL_REG = 3u; + REG(GPIO2 + 0x04) &= ~3u; g_enc_last = REG(GPIO2) & 3u; + set_load(); + if (!PokeMini_Create(0, 0)) { message("NO MEMORY", ""); for (u32 t = 0; t < 30000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); leave(); } + PokeMini_LCDMode = LCDMODE_ANALOG; + bios_load(); + pm_set_rom(ROMWIN, g_cfg.rom_len); + eep_load(); + PokeMini_Reset(1); + if (!state_load()) time_from_para(); + PokeMini_EEPROMWritten = 0; + g_running = 1; + push(1); + SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; SYST_CSR = 7; + __asm__ volatile("cpsie i"); + + u32 last_in = g_ms, wheel_ms = 0, eep_ms = 0, next_us = 0, last_push = g_ms, mk0 = 0, t_us0 = g_ms; + int bl = 1, lock = 1, menu_lock = 0, drawn = 0; + for (;;) { + hw_wdt_feed(); + u32 now = g_ms; + u32 b = hw_buttons(); + if (lock) { if (b) b = 0; else lock = 0; } + /* wheel steps: one step = 4 phases; each step holds up or down for 150 ms */ + { s32 a = g_enc_acc; + if (a >= 4 || a <= -4) { + __asm__ volatile("cpsid i"); g_enc_acc -= a >= 4 ? 4 : -4; __asm__ volatile("cpsie i"); + int up = (a > 0) ^ ((g_cfg.flags & 2u) != 0); + u32 *u = &g_wheel_until[up ? 0 : 1]; *u = ((s32)(*u - now) > 0 ? *u : now) + 150u; + last_in = now; + if (g_menu) { g_msel = up ? (g_msel + g_nitems - 1) % g_nitems : (g_msel + 1) % g_nitems; menu_draw(); } + } } + if (b) { + last_in = now; + if (!bl || g_dimmed) { /* the key only wakes */ + bl = 1; hw_backlight(1); pause_end(); if (g_dimmed) { g_dimmed = 0; colours(); } + if (g_menu) menu_draw(); else push(1); + while (hw_buttons()) hw_wdt_feed(); + t_us0 = g_ms; next_us = 0; + continue; + } + } + /* wheel held 2 s: save and back */ + if (b & BTN_WHEEL) { if (!wheel_ms) wheel_ms = now ? now : 1; else if (EXIT_NOW(now - wheel_ms, 2000u)) leave(); } else wheel_ms = 0; + /* A+B+C: settings */ + if ((b & (BTN_A | BTN_B | BTN_C)) == (BTN_A | BTN_B | BTN_C) && !g_menu && !menu_lock) { + tone(0); keys_set(0); pause_begin(); g_menu = 1; menu_lock = 1; g_msel = 1; g_mtop = 0; menu_items(); menu_draw(); mk0 = BTN_A | BTN_B | BTN_C; + } + if (!(b & (BTN_A | BTN_B | BTN_C))) menu_lock = 0; + if (g_menu) { + u32 k = b & (BTN_A | BTN_B | BTN_C), nk = k & ~mk0; mk0 = k; if (nk) menu_key(nk); + t_us0 = g_ms; next_us = 0; + __asm__ volatile("wfi"); + continue; + } + if (!bl) { tone(0); t_us0 = g_ms; next_us = 0; __asm__ volatile("wfi"); continue; } /* screen off: the game waits (battery) */ + keys_set(pm_keys(b, now)); + /* one Pokemon mini frame every 1/72 s (13889 us) */ + u32 el_us = (now - t_us0) * 1000u; + if ((s32)(el_us - next_us) >= 0) { + if ((s32)(el_us - next_us) > 100000) { g_pmst[2] += (el_us - next_us) / 13889u; next_us = el_us; } /* too far behind: drop the time */ + u32 t0 = g_ms; + PokeMini_EmulateFrame(); + g_pmst[0]++; g_pmst[3] = g_ms - t0; + next_us += 13889u; + if (next_us > 1000000000u) { t_us0 += next_us / 1000u; next_us %= 1000u; } + { int hz = 0, vol = 0; pm_audio_now(&hz, &vol); tone(!g_set.mute && vol && hz >= 40 && hz <= 12000 ? (u32)hz : 0u); } + drawn ^= 1; +#ifdef PM_FASTLCD + if (!drawn) lcd_snap(); + else if (now - last_push >= 25u) { last_push = now; lcd_mix(); frame_grow(); push(0); g_pmst[1]++; } +#else + if (drawn && now - last_push >= 25u) { last_push = now; frame_grow(); push(0); g_pmst[1]++; } +#endif + } + if (PokeMini_EEPROMWritten && !eep_ms) eep_ms = now ? now : 1; + if (eep_ms && now - eep_ms > 3000u && now - last_in > 1000u) { eep_ms = 0; eep_store(); } + if (bl && !g_dimmed && g_set.dim < T_N && now - last_in > T_MS[g_set.dim]) { g_dimmed = 1; colours(); push(1); } + if (bl && g_set.off < T_N && now - last_in > T_MS[g_set.off]) { bl = 0; tone(0); hw_backlight(0); pause_begin(); if (PokeMini_EEPROMWritten) { eep_ms = 0; eep_store(); } } + if ((s32)(next_us - (g_ms - t_us0) * 1000u) > 0) __asm__ volatile("wfi"); + } +} + +__attribute__((naked)) static void Default_Handler(void) { __asm__ volatile("1: b 1b\n"); } +__attribute__((naked)) static void Irq_Off(void) { __asm__ volatile("cpsid i\n bx lr\n"); } +__attribute__((section(".vectors"), used)) +const void *const g_vectors[16 + 64] = { (void *)0x18020000u, (void *)Reset_Handler, + [2 ... 10] = (void *)Default_Handler, [11] = (void *)Irq_Off, [12 ... 13] = (void *)Default_Handler, [14] = (void *)Irq_Off, + [15] = (void *)SysTick_Handler, [16 ... 79] = (void *)Irq_Off }; diff --git a/pm/src/core/Hardware.c b/pm/src/core/Hardware.c new file mode 100644 index 0000000..11a0c5a --- /dev/null +++ b/pm/src/core/Hardware.c @@ -0,0 +1,282 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "PokeMini.h" + +/* Emulate 1 frame, return cycles ran */ +static int PokeMini_EmulateFrameRun; + +int PokeMini_EmulateFrame(void) +{ + int lcylc = 0; + int synccylc = PM_SYNCCYCLES; + + PokeMini_EmulateFrameRun = 1; + + if (RequireSoundSync) { + while (PokeMini_EmulateFrameRun) { + PokeHWCycles = 0; + while (PokeHWCycles < synccylc) { + if (StallCPU) PokeHWCycles += StallCycles; + else PokeHWCycles += MinxCPU_Exec(); + } + MinxTimers_Sync(); + MinxPRC_Sync(); + MinxAudio_Sync(); + lcylc += PokeHWCycles; + } + } else { + while (PokeMini_EmulateFrameRun) { + PokeHWCycles = 0; + while (PokeHWCycles < synccylc) { + if (StallCPU) PokeHWCycles += StallCycles; + else PokeHWCycles += MinxCPU_Exec(); + } + MinxTimers_Sync(); + MinxPRC_Sync(); + lcylc += PokeHWCycles; + } + } + + return lcylc; +} + +// ------------------- +// Internal Processing +// ------------------- + +uint8_t MinxCPU_OnRead(int cpu, uint32_t addr) +{ +#ifdef PERFORMANCE + if (addr >= 0x2100) { + // ROM Read (ROM Cartridge) + if (PM_ROM) return PM_ROM[addr & PM_ROM_Mask]; +#else + if (addr >= 0x200000) { + // Open bus + return MinxCPU.IR; + } else if (addr >= 0x2100) { + // ROM Read (Multicard) + return MulticartRead(addr); +#endif + } else if (addr >= 0x2000) { + // I/O Read + uint8_t reg = (uint8_t)addr; + switch(reg) { + // Misc interface + case 0x00: // System Control 1 + return PMR_SYS_CTRL1; + case 0x01: // System Control 2 + return PMR_SYS_CTRL2; + case 0x02: // System Control 3 + return PMR_SYS_CTRL3; + + // IRQ interface + case 0x20: case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2A: + return MinxIRQ_ReadReg(cpu, reg); + + // Timers interface + case 0x08: case 0x09: case 0x0A: case 0x0B: + case 0x18: case 0x19: case 0x1A: case 0x1B: + case 0x1C: case 0x1D: case 0x1E: case 0x1F: + case 0x30: case 0x31: case 0x32: case 0x33: + case 0x34: case 0x35: case 0x36: case 0x37: + case 0x38: case 0x39: case 0x3A: case 0x3B: + case 0x3C: case 0x3D: case 0x3E: case 0x3F: + case 0x40: case 0x41: + case 0x48: case 0x49: case 0x4A: case 0x4B: + case 0x4C: case 0x4D: case 0x4E: case 0x4F: + return MinxTimers_ReadReg(reg); + + // Parallel I/O interface & Power + case 0x10: + case 0x44: case 0x45: case 0x46: case 0x47: + case 0x50: case 0x51: case 0x52: case 0x53: + case 0x54: case 0x55: + case 0x60: case 0x61: case 0x62: + return MinxIO_ReadReg(cpu, reg); + + // Program Rendering Chip interface + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8A: case 0x8B: + case 0x8C: case 0x8D: case 0x8E: case 0x8F: + return MinxPRC_ReadReg(reg); + + // Color PRC interface + case 0xF0: case 0xF1: case 0xF2: case 0xF3: + case 0xF4: case 0xF5: case 0xF6: case 0xF7: + return MinxColorPRC_ReadReg(cpu, reg); + + // LCD interface + case 0xFE: case 0xFF: + return MinxLCD_ReadReg(cpu, reg); + + // Audio interface + case 0x70: case 0x71: + return MinxAudio_ReadReg(reg); + + // Open bus + default: + return MinxCPU.IR; + } + } else if (addr >= 0x1000) { + // RAM Read + return PM_RAM[addr-0x1000]; + } else { + // BIOS Read + return PM_BIOS[addr]; + } + return 0xFF; +} + +void MinxCPU_OnWrite(int cpu, uint32_t addr, uint8_t data) +{ +#ifdef PERFORMANCE + if (addr >= 0x2100) { + // Do nothing... +#else + if (addr >= 0x200000) { + // Open bus + } else if (addr >= 0x2100) { + // ROM Write + MulticartWrite(addr, data); +#endif + return; + } else if (addr >= 0x2000) { + // I/O Write + uint8_t reg = (uint8_t)addr; + switch(reg) { + // Misc interface + case 0x00: // System Control 1 + PMR_SYS_CTRL1 = data; + return; + case 0x01: // System Control 2 + PMR_SYS_CTRL2 = data; + return; + case 0x02: // System Control 3 + PMR_SYS_CTRL3 = data; + return; + + // IRQ interface + case 0x20: case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2A: + MinxIRQ_WriteReg(cpu, reg, data); + return; + + // Timers interface + case 0x08: case 0x09: case 0x0A: case 0x0B: + case 0x18: case 0x19: case 0x1A: case 0x1B: + case 0x1C: case 0x1D: case 0x1E: case 0x1F: + case 0x30: case 0x31: case 0x32: case 0x33: + case 0x34: case 0x35: case 0x36: case 0x37: + case 0x38: case 0x39: case 0x3A: case 0x3B: + case 0x3C: case 0x3D: case 0x3E: case 0x3F: + case 0x40: case 0x41: + case 0x48: case 0x49: case 0x4A: case 0x4B: + case 0x4C: case 0x4D: case 0x4E: case 0x4F: + MinxTimers_WriteReg(reg, data); + return; + + // Parallel I/O interface & Power + case 0x10: + case 0x44: case 0x45: case 0x46: case 0x47: + case 0x50: case 0x51: case 0x52: case 0x53: + case 0x54: case 0x55: + case 0x60: case 0x61: case 0x62: + MinxIO_WriteReg(cpu, reg, data); + return; + + // Program Rendering Chip interface + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8A: + MinxPRC_WriteReg(reg, data); + return; + + // Color PRC interface + case 0xF0: case 0xF1: case 0xF2: case 0xF3: + case 0xF4: case 0xF5: case 0xF6: case 0xF7: + MinxColorPRC_WriteReg(reg, data); + return; + + // LCD interface + case 0xFE: case 0xFF: + MinxLCD_WriteReg(cpu, reg, data); + return; + + // Audio interface + case 0x70: case 0x71: + MinxAudio_WriteReg(reg, data); + return; + } + } else if (addr >= 0x1300) { + // RAM Write + PM_RAM[addr-0x1000] = data; + return; + } else if (addr >= 0x1000) { + // RAM Write / FrameBuffer + PM_RAM[addr-0x1000] = data; + if (PRCColorMap) MinxColorPRC_WriteFramebuffer(addr-0x1000, data); + return; + } +} + +void MinxCPU_OnIRQHandle(uint8_t cpuflag, uint8_t shift_u) +{ + // Disable or enable master interrupt and check for interrupts + if (shift_u) { + MinxIRQ_MasterIRQ = 0; + } else { + if ((cpuflag & 0xC0) == 0xC0) MinxIRQ_MasterIRQ = 0; + else { + MinxIRQ_MasterIRQ = 1; + MinxIRQ_Process(); + } + } +} + +void MinxCPU_OnIRQAct(uint8_t intr) +{ + // Set and process interrupt + MinxIRQ_SetIRQ(intr); +} + +void MinxIRQ_OnIRQ(uint8_t intr) +{ + // From IRQ module, call the CPU interrupt + MinxCPU_CallIRQ(intr << 1); +} + +void MinxPRC_On72HzRefresh(int prcrender) +{ + // Frame rendered +#ifdef PM_FASTLCD + /* PokeMiniEmu: the Paradise program reads the LCD memory itself, only for the frames it shows (and mixes two + * frames for the grey shades); the per-dot buffers and the decay are left out (they took about 18 % of the time) */ + (void)prcrender; LCDDirty = 0; +#else + if ((PokeMini_LCDMode == LCDMODE_3SHADES) && (prcrender)) memcpy(LCDPixelsA, LCDPixelsD, 96*64); + if (LCDDirty) MinxLCD_Render(); + if (PokeMini_LCDMode == LCDMODE_ANALOG) MinxLCD_DecayRefresh(); +#endif + PokeMini_EmulateFrameRun = 0; +} diff --git a/pm/src/core/Hardware.h b/pm/src/core/Hardware.h new file mode 100644 index 0000000..873872f --- /dev/null +++ b/pm/src/core/Hardware.h @@ -0,0 +1,25 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef HARDWARE_EMU +#define HARDWARE_EMU + +/* Emulate 1 frame, return cycles ran */ +int PokeMini_EmulateFrame(void); + +#endif diff --git a/pm/src/core/IOMap.h b/pm/src/core/IOMap.h new file mode 100644 index 0000000..865a185 --- /dev/null +++ b/pm/src/core/IOMap.h @@ -0,0 +1,122 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2014 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef IO_MAP_H +#define IO_MAP_H + +#include "PokeMini.h" + +// Pokemon-Mini I/O Registers +#define PM_IO (&PM_RAM[0x1000]) + +#define PMR_SYS_CTRL1 (PM_RAM[0x1000]) +#define PMR_SYS_CTRL2 (PM_RAM[0x1001]) +#define PMR_SYS_CTRL3 (PM_RAM[0x1002]) + +#define PMR_SEC_CTRL (PM_RAM[0x1008]) +#define PMR_SEC_CNT_LO (PM_RAM[0x1009]) +#define PMR_SEC_CNT_MID (PM_RAM[0x100A]) +#define PMR_SEC_CNT_HI (PM_RAM[0x100B]) + +#define PMR_SYS_BATT (PM_RAM[0x1010]) + +#define PMR_TMR1_SCALE (PM_RAM[0x1018]) +#define PMR_TMR1_ENA_OSC (PM_RAM[0x1019]) +#define PMR_TMR1_OSC (PM_RAM[0x1019]) +#define PMR_TMR2_SCALE (PM_RAM[0x101A]) +#define PMR_TMR2_OSC (PM_RAM[0x101B]) +#define PMR_TMR3_SCALE (PM_RAM[0x101C]) +#define PMR_TMR3_OSC (PM_RAM[0x101D]) + +#define PMR_IRQ_PRI1 (PM_RAM[0x1020]) +#define PMR_IRQ_PRI2 (PM_RAM[0x1021]) +#define PMR_IRQ_PRI3 (PM_RAM[0x1022]) +#define PMR_IRQ_ENA1 (PM_RAM[0x1023]) +#define PMR_IRQ_ENA2 (PM_RAM[0x1024]) +#define PMR_IRQ_ENA3 (PM_RAM[0x1025]) +#define PMR_IRQ_ENA4 (PM_RAM[0x1026]) +#define PMR_IRQ_ACT1 (PM_RAM[0x1027]) +#define PMR_IRQ_ACT2 (PM_RAM[0x1028]) +#define PMR_IRQ_ACT3 (PM_RAM[0x1029]) +#define PMR_IRQ_ACT4 (PM_RAM[0x102A]) + +#define PMR_TMR1_CTRL_L (PM_RAM[0x1030]) +#define PMR_TMR1_CTRL_H (PM_RAM[0x1031]) +#define PMR_TMR1_PRE_L (PM_RAM[0x1032]) +#define PMR_TMR1_PRE_H (PM_RAM[0x1033]) +#define PMR_TMR1_PVT_L (PM_RAM[0x1034]) +#define PMR_TMR1_PVT_H (PM_RAM[0x1035]) +#define PMR_TMR1_CNT_L (PM_RAM[0x1036]) +#define PMR_TMR1_CNT_H (PM_RAM[0x1037]) + +#define PMR_TMR2_CTRL_L (PM_RAM[0x1038]) +#define PMR_TMR2_CTRL_H (PM_RAM[0x1039]) +#define PMR_TMR2_PRE_L (PM_RAM[0x103A]) +#define PMR_TMR2_PRE_H (PM_RAM[0x103B]) +#define PMR_TMR2_PVT_L (PM_RAM[0x103C]) +#define PMR_TMR2_PVT_H (PM_RAM[0x103D]) +#define PMR_TMR2_CNT_L (PM_RAM[0x103E]) +#define PMR_TMR2_CNT_H (PM_RAM[0x103F]) + +#define PMR_TMR256_CTRL (PM_RAM[0x1040]) +#define PMR_TMR256_CNT (PM_RAM[0x1041]) + +#define PMR_REG_44 (PM_RAM[0x1044]) +#define PMR_REG_45 (PM_RAM[0x1045]) +#define PMR_REG_46 (PM_RAM[0x1046]) +#define PMR_REG_47 (PM_RAM[0x1047]) + +#define PMR_TMR3_CTRL_L (PM_RAM[0x1048]) +#define PMR_TMR3_CTRL_H (PM_RAM[0x1049]) +#define PMR_TMR3_PRE_L (PM_RAM[0x104A]) +#define PMR_TMR3_PRE_H (PM_RAM[0x104B]) +#define PMR_TMR3_PVT_L (PM_RAM[0x104C]) +#define PMR_TMR3_PVT_H (PM_RAM[0x104D]) +#define PMR_TMR3_CNT_L (PM_RAM[0x104E]) +#define PMR_TMR3_CNT_H (PM_RAM[0x104F]) + +#define PMR_REG_50 (PM_RAM[0x1050]) +#define PMR_REG_51 (PM_RAM[0x1051]) +#define PMR_KEY_PAD (PM_RAM[0x1052]) +#define PMR_REG_53 (PM_RAM[0x1053]) +#define PMR_REG_54 (PM_RAM[0x1054]) +#define PMR_REG_55 (PM_RAM[0x1055]) + +#define PMR_IO_DIR (PM_RAM[0x1060]) +#define PMR_IO_DATA (PM_RAM[0x1061]) +#define PMR_REG_62 (PM_RAM[0x1062]) + +#define PMR_AUD_CTRL (PM_RAM[0x1070]) +#define PMR_AUD_VOL (PM_RAM[0x1071]) + +#define PMR_PRC_MODE (PM_RAM[0x1080]) +#define PMR_PRC_RATE (PM_RAM[0x1081]) +#define PMR_PRC_MAP_LO (PM_RAM[0x1082]) +#define PMR_PRC_MAP_MID (PM_RAM[0x1083]) +#define PMR_PRC_MAP_HI (PM_RAM[0x1084]) +#define PMR_PRC_SCROLL_Y (PM_RAM[0x1085]) +#define PMR_PRC_SCROLL_X (PM_RAM[0x1086]) +#define PMR_PRC_SPR_LO (PM_RAM[0x1087]) +#define PMR_PRC_SPR_MID (PM_RAM[0x1088]) +#define PMR_PRC_SPR_HI (PM_RAM[0x1089]) +#define PMR_PRC_CNT (PM_RAM[0x108A]) + +#define PMR_LCD_CTRL (PM_RAM[0x10FE]) +#define PMR_LCD_DATA (PM_RAM[0x10FF]) + +#endif diff --git a/pm/src/core/LICENSE_pokemini b/pm/src/core/LICENSE_pokemini new file mode 100644 index 0000000..7cb9ca0 --- /dev/null +++ b/pm/src/core/LICENSE_pokemini @@ -0,0 +1,15 @@ +PokeMini - Pokémon-Mini Emulator +Copyright (C) 2014 JustBurn + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . diff --git a/pm/src/core/MinxAudio.c b/pm/src/core/MinxAudio.c new file mode 100644 index 0000000..1e84f0a --- /dev/null +++ b/pm/src/core/MinxAudio.c @@ -0,0 +1,472 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include "PokeMini.h" + +TMinxAudio MinxAudio; +int AudioEnabled = 0; +int SoundEngine = MINX_AUDIO_DISABLED; +int PiezoFilter = 0; +int RequireSoundSync = 0; +int16_t *MinxAudio_FIFO = NULL; +volatile int MinxAudio_ReadPtr = 0; +volatile int MinxAudio_WritePtr = 0; +int MinxAudio_FIFOSize = 0; +int MinxAudio_FIFOMask = 0; +int MinxAudio_FIFOThreshold = 0; +int16_t (*MinxAudio_AudioProcess)(void) = NULL; + +// Timers counting frequency table +const uint32_t MinxAudio_CountFreq[32] = { + // Osci1 disabled + 1, 0, 0, 0, 0, 0, 0, 0, + // Osci1 Enabled + (4000000/2), (4000000/8), (4000000/32), (4000000/64), + (4000000/128), (4000000/256), (4000000/1024), (4000000/4096), + // Osci2 disabled + 0, 0, 0, 0, 0, 0, 0, 0, + // Osci2 Enabled + (32768/1), (32768/2), (32768/4), (32768/8), + (32768/16), (32768/32), (32768/64), (32768/128) +}; + +// +// FIFO I/O +// + +static INLINE int MinxAudio_iSamplesInBuffer(void) +{ + if (MinxAudio_WritePtr > MinxAudio_ReadPtr) + return MinxAudio_WritePtr - MinxAudio_ReadPtr; + return (MinxAudio_FIFOSize - MinxAudio_ReadPtr) + MinxAudio_WritePtr; +} + +static INLINE void MinxAudio_FIFOWrite(int16_t data) +{ + if (MinxAudio_iSamplesInBuffer() < MinxAudio_FIFOSize) { + MinxAudio_FIFO[MinxAudio_WritePtr] = data; + MinxAudio_WritePtr = (MinxAudio_WritePtr + 1) & MinxAudio_FIFOMask; + } +} + +static INLINE int16_t MinxAudio_FIFORead(void) +{ + if (MinxAudio_iSamplesInBuffer() > 0) + { + int16_t data = MinxAudio_FIFO[MinxAudio_ReadPtr]; + MinxAudio_ReadPtr = (MinxAudio_ReadPtr + 1) & MinxAudio_FIFOMask; + return data; + } + return 0; +} + +// +// Functions +// + +int MinxAudio_Create(int audioenable, int fifosize) +{ + // Init variables + AudioEnabled = audioenable; + SoundEngine = MINX_AUDIO_DISABLED; + RequireSoundSync = 0; + + // Reset + MinxAudio_Reset(1); + + // Init FIFO if audio enabled + MinxAudio_ReadPtr = 0; + MinxAudio_WritePtr = 0; + if (fifosize) + { + MinxAudio_FIFOMask = GetMultiple2Mask(fifosize); + MinxAudio_FIFOSize = MinxAudio_FIFOMask + 1; + MinxAudio_FIFOThreshold = (fifosize * 3) >> 2; // ... at 3 / 4 + } + else + { + MinxAudio_FIFOMask = 0; + MinxAudio_FIFOSize = 0; + MinxAudio_FIFOThreshold = 0; + } + if ((audioenable) && (fifosize)) + { + MinxAudio_FIFO = (int16_t *)malloc(MinxAudio_FIFOSize*2); + if (!MinxAudio_FIFO) return 0; + memset(MinxAudio_FIFO, 0, MinxAudio_FIFOSize*2); + } + + return 1; +} + +void MinxAudio_Destroy(void) +{ + if (MinxAudio_FIFO) { + free(MinxAudio_FIFO); + MinxAudio_FIFO = NULL; + } +} + +void MinxAudio_Reset(int hardreset) +{ + // Initialize State + memset((void *)&MinxAudio, 0, sizeof(TMinxAudio)); +} + +int MinxAudio_LoadStateStream(memstream_t *stream, uint32_t bsize) +{ + POKELOADSS_START(32); + POKELOADSS_STREAM_32(MinxAudio.AudioCCnt); + POKELOADSS_STREAM_32(MinxAudio.AudioSCnt); + POKELOADSS_STREAM_16(MinxAudio.Volume); + POKELOADSS_STREAM_16(MinxAudio.PWMMul); + POKELOADSS_STREAM_X(20); + POKELOADSS_END(32); +} + +int MinxAudio_SaveStateStream(memstream_t *stream) +{ + POKESAVESS_STREAM_START(32); + POKESAVESS_STREAM_32(MinxAudio.AudioCCnt); + POKESAVESS_STREAM_32(MinxAudio.AudioSCnt); + POKESAVESS_STREAM_16(MinxAudio.Volume); + POKESAVESS_STREAM_16(MinxAudio.PWMMul); + POKESAVESS_STREAM_X(20); + POKESAVESS_END(32); +} + +static int16_t MinxAudio_AudioProcessDirectPWM(void) +{ + uint32_t Pwm = 0; + uint16_t TmrCnt = (MinxTimers.Tmr3CntA >> 24) | ((MinxTimers.Tmr3CntB >> 24) << 8); + uint16_t TmrPre = (MinxTimers.Tmr3PreA >> 24) | ((MinxTimers.Tmr3PreB >> 24) << 8); + + // Affect sound based of PWM + if (TmrPre) + Pwm = MinxTimers.Timer3Piv * MINX_AUDIO_PWM_RAG / TmrPre; + if (Pwm > MINX_AUDIO_PWM_RAG) + Pwm = MINX_AUDIO_PWM_RAG-1; // Avoid clipping + if (TmrPre < 128) + TmrCnt = 0; // Avoid high hizz + + // Output + if (TmrCnt <= MinxTimers.Timer3Piv) + return MinxAudio.Volume + Pwm * MinxAudio.PWMMul; + return MINX_AUDIO_SILENCE + Pwm * MinxAudio.PWMMul; +} + + +void MinxAudio_ChangeEngine(int engine) +{ + if (PokeMini_Flags & POKEMINI_GENSOUND) + engine = engine ? 1 : 0; + SoundEngine = engine; + switch (engine) { + case MINX_AUDIO_DIRECTPWM: + RequireSoundSync = 1; + MinxAudio_AudioProcess = MinxAudio_AudioProcessDirectPWM; + break; + case MINX_AUDIO_GENERATED: + default: + RequireSoundSync = 0; + MinxAudio_AudioProcess = NULL; + break; + } +} + +void MinxAudio_ChangeFilter(int piezo) +{ + PiezoFilter = piezo; +} + +void MinxAudio_Sync(void) +{ + // Process single audio sample + MinxAudio.AudioCCnt += MINX_AUDIOINC * PokeHWCycles; + if (MinxAudio.AudioCCnt >= 0x01000000) + { + MinxAudio.AudioCCnt -= 0x01000000; + if (MinxAudio_AudioProcess) + { + if (PiezoFilter) + MinxAudio_FIFOWrite(MinxAudio_PiezoFilter(MinxAudio_AudioProcess())); + else + MinxAudio_FIFOWrite(MinxAudio_AudioProcess()); + } + } +} + +uint8_t MinxAudio_ReadReg(uint8_t reg) +{ + // 0x70 to 0x71 + switch(reg) + { + case 0x70: // Unknown Audio Control + return PMR_AUD_CTRL & 0x07; + case 0x71: // Audio Volume Control + return PMR_AUD_VOL & 0x07; + default: + break; + } + + return 0; +} + +void MinxAudio_WriteReg(uint8_t reg, uint8_t val) +{ + /* 0x70 to 0x71 */ + switch(reg) + { + case 0x70: /* Unknown Audio Control */ + PMR_AUD_CTRL = val & 0x07; + break; + case 0x71: /* Audio Volume Control */ + PMR_AUD_VOL = val & 0x07; + break; + } + + // Calculate volume + if (PMR_AUD_CTRL & 0x03) { + // Mute audio + MinxAudio.Volume = 0; + } else { + switch (PMR_AUD_VOL & 3) { + case 0: + // 0% Sound + MinxAudio.Volume = MINX_AUDIO_SILENCE; + MinxAudio.PWMMul = 0; + break; + case 1: + case 2: + // 50% Sound + MinxAudio.Volume = MINX_AUDIO_MED_VOL; + MinxAudio.PWMMul = 1; + break; + case 3: + // 100% Sound + MinxAudio.Volume = MINX_AUDIO_MAX_VOL; + MinxAudio.PWMMul = 2; + break; + } + } +} + +// Get emulated frequency and pulsewidth +// Sound_Frequency is in Hz +// Pulse_Width is between 0 to 4095 (0% to ~99.99%) +static void MinxAudio_GetEmulated(int *Sound_Frequency, int *Pulse_Width) +{ + int Preset_Value, Sound_Pivot; + // Calculate timer 3 frequency + int Timer3_Frequency = MinxAudio_CountFreq[(PMR_TMR3_SCALE & 0xF) | ((PMR_TMR3_OSC & 0x01) << 4)]; + if (!(PMR_TMR3_CTRL_L & 0x04)) + Timer3_Frequency = 0; + if (PMR_TMR3_OSC & 0x01) + { + // Osci2 + if (!MinxTimers.TmrXEna2) + Timer3_Frequency = 0; + } + else + { + // Osci1 + if (!MinxTimers.TmrXEna1) + Timer3_Frequency = 0; + } + + if (Timer3_Frequency) + { + // Calculate preset value + Preset_Value = (MinxTimers.Tmr3PreA >> 24) + ((MinxTimers.Tmr3PreB >> 24) << 8); + + // Calculate sound frequency + *Sound_Frequency = Timer3_Frequency / (Preset_Value + 1); + + // ... and pulse width + if (Preset_Value) + { + Sound_Pivot = (int)MinxTimers.Timer3Piv; + *Pulse_Width = 4095 - (Sound_Pivot * 4096 / Preset_Value); + if (*Pulse_Width < 0) + *Pulse_Width = 0; + } else *Pulse_Width = 0; + } + else + { + *Sound_Frequency = 0; + *Pulse_Width = 0; + } +} + +int16_t MinxAudio_PiezoFilter(int32_t Sample) +{ + int32_t HP_pCoeff = 40960; + int32_t LP_pCoeff = 4096; + int32_t LP_nCoeff = (65535 - LP_pCoeff); + static int32_t HPSamples[4], LPSamples[4]; + int32_t TmpSamples[4]; + + // High pass to simulate a piezo crystal speaker + TmpSamples[0] = Sample; + TmpSamples[1] = (HP_pCoeff * (TmpSamples[0] + HPSamples[1] - HPSamples[0])) >> 16; + TmpSamples[2] = (HP_pCoeff * (TmpSamples[1] + HPSamples[2] - HPSamples[1])) >> 16; + TmpSamples[3] = (HP_pCoeff * (TmpSamples[2] + HPSamples[3] - HPSamples[2])) >> 16; + memcpy(HPSamples, TmpSamples, sizeof(HPSamples)); + + // Amplify by 4 + Sample = TmpSamples[3] << 2; + if (Sample < -32768) + Sample = -32768; + else if (Sample > 32767) + Sample = 32767; + + // Low pass to kill the spikes in sound + LPSamples[0] = Sample; + LPSamples[1] = (LPSamples[1] * LP_pCoeff + LPSamples[0] * LP_nCoeff) >> 16; + LPSamples[2] = (LPSamples[2] * LP_pCoeff + LPSamples[1] * LP_nCoeff) >> 16; + LPSamples[3] = (LPSamples[3] * LP_pCoeff + LPSamples[2] * LP_nCoeff) >> 16; + + // Amplify by 2, clamp and output + Sample = LPSamples[3] << 1; + if (Sample < -32768) + return -32768; + if (Sample > 32767) + return 32767; + return Sample; +} + +// This doesn't require audio to be created: +static void MinxAudio_GenerateEmulatedS16( + int16_t *soundout, int numsamples, int channels) +{ + int i, j, Sound_Frequency, Pulse_Width; + if (numsamples <= 0) + return; + MinxAudio_GetEmulated(&Sound_Frequency, &Pulse_Width); + if (channels == 1) + { + for (i=0; i= 50) && (Sound_Frequency < 20000)) + { + MinxAudio.AudioSCnt += Sound_Frequency * MINX_AUDIOCONV; + if ((MinxAudio.AudioSCnt & 0xFFF00000) >= (Pulse_Width << 20)) + *soundout++ = PiezoFilter ? MinxAudio_PiezoFilter(MinxAudio.Volume) : MinxAudio.Volume; + else + *soundout++ = PiezoFilter ? MinxAudio_PiezoFilter(MINX_AUDIO_SILENCE) : 0; + } + else + *soundout++ = PiezoFilter ? MinxAudio_PiezoFilter(MINX_AUDIO_SILENCE) : 0; + } + } + else + { + for (i=0; i= 50) && (Sound_Frequency < 20000)) + { + MinxAudio.AudioSCnt += Sound_Frequency * MINX_AUDIOCONV; + if ((MinxAudio.AudioSCnt & 0xFFF00000) >= (Pulse_Width << 20)) + { + if (PiezoFilter) + { + for (j=0; j= 4095) ? 0 : f; +} diff --git a/pm/src/core/MinxAudio.h b/pm/src/core/MinxAudio.h new file mode 100644 index 0000000..cbf5b4a --- /dev/null +++ b/pm/src/core/MinxAudio.h @@ -0,0 +1,100 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXHW_AUDIO +#define MINXHW_AUDIO + +#include "MinxTimers.h" + +#include +#include + +typedef struct { + // Internal processing + int32_t AudioCCnt; // Audio cycle counter 8.24 (Needs signed) + uint32_t AudioSCnt; // Audio sample counter 8.24 (Needs unsigned) + int16_t Volume; // Volume (S16 sample) + int16_t PWMMul; // PWM Multiplication +} TMinxAudio; + +// Export Audio state +extern TMinxAudio MinxAudio; + +// Audio enabled +extern int AudioEnabled; + +// Sound engine +extern int SoundEngine; + +// Piezo Filter +extern int PiezoFilter; + +// Require sound sync +extern int RequireSoundSync; + + +enum { + MINX_AUDIO_DISABLED = 0, // Disabled + MINX_AUDIO_GENERATED, // Generated (Doesn't require sync) + MINX_AUDIO_DIRECTPWM // Direct from Timer 3 with PWM support +}; + +enum { + MINX_AUDIO_SILENCE = 0x0000, + MINX_AUDIO_MED_VOL = 0x2000, + MINX_AUDIO_MAX_VOL = 0x4000, + MINX_AUDIO_PWM_RAG = 0x1FFF // Max + Pwm*2 must not be over 0x7FFF +}; + +#ifndef MINX_AUDIOFREQ +#define MINX_AUDIOFREQ (44100) +#endif + +// Aproximate value of 1 sample per cycle at 44100Hz (16M / ( 4M / 44K )) +#ifndef MINX_AUDIOINC +#define MINX_AUDIOINC (184969) +#endif + +// Conversion for the generator counter +#define MINX_AUDIOCONV (2147483647/(MINX_AUDIOFREQ)*2) + +int MinxAudio_Create(int audioenable, int fifosize); + +void MinxAudio_Destroy(void); + +void MinxAudio_Reset(int hardreset); + +int MinxAudio_LoadStateStream(memstream_t *stream, uint32_t bsize); + +int MinxAudio_SaveStateStream(memstream_t *stream); + +void MinxAudio_ChangeEngine(int engine); + +void MinxAudio_ChangeFilter(int piezo); + +void MinxAudio_Sync(void); + +uint8_t MinxAudio_ReadReg(uint8_t reg); + +void MinxAudio_WriteReg(uint8_t reg, uint8_t val); + +int16_t MinxAudio_PiezoFilter(int32_t Sample); + +void MinxAudio_GetSamplesS16Ch(int16_t *soundout, int numsamples, int channels); + +#endif diff --git a/pm/src/core/MinxCPU.c b/pm/src/core/MinxCPU.c new file mode 100644 index 0000000..3517d7f --- /dev/null +++ b/pm/src/core/MinxCPU.c @@ -0,0 +1,113 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "PokeMini.h" + +TMinxCPU MinxCPU; + +// +// Functions +// + +int MinxCPU_Create(void) +{ + // Init variables + MinxCPU.BA.D = 0; + MinxCPU.HL.D = 0; + MinxCPU.X.D = 0; + MinxCPU.Y.D = 0; + MinxCPU.SP.D = 0; + MinxCPU.PC.D = 0; + MinxCPU.N.D = 0; + MinxCPU.E = 0; + MinxCPU.F = 0xC0; + Set_U(0); + MinxCPU.Status = MINX_STATUS_NORMAL; + return 1; +} + +void MinxCPU_Destroy(void) +{ + // Nothing... +} + +// Reset core, call it after OnRead/OnWrite point to the right BIOS +void MinxCPU_Reset(int hardreset) +{ + MinxCPU.Status = MINX_STATUS_NORMAL; + MinxCPU.PC.W.L = ReadMem16(hardreset ? 0 : 2); + MinxCPU.E = 0x1F; + MinxCPU.F = 0xC0; + Set_U(0); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +// Load State from stream +int MinxCPU_LoadStateStream(memstream_t *stream, uint32_t bsize) +{ + POKELOADSS_START(64); + POKELOADSS_STREAM_32(MinxCPU.BA.D); + POKELOADSS_STREAM_32(MinxCPU.HL.D); + POKELOADSS_STREAM_32(MinxCPU.X.D); + POKELOADSS_STREAM_32(MinxCPU.Y.D); + POKELOADSS_STREAM_32(MinxCPU.SP.D); + POKELOADSS_STREAM_32(MinxCPU.PC.D); + POKELOADSS_STREAM_32(MinxCPU.N.D); + POKELOADSS_STREAM_8(MinxCPU.U1); + POKELOADSS_STREAM_8(MinxCPU.U2); + POKELOADSS_STREAM_8(MinxCPU.F); + POKELOADSS_STREAM_8(MinxCPU.E); + POKELOADSS_STREAM_8(MinxCPU.IR); + POKELOADSS_STREAM_8(MinxCPU.Shift_U); + POKELOADSS_STREAM_8(MinxCPU.Status); + POKELOADSS_STREAM_8(MinxCPU.IRQ_Vector); + POKELOADSS_STREAM_A(MinxCPU.Reserved, 28); + POKELOADSS_END(64); +} + +// Save State to stream +int MinxCPU_SaveStateStream(memstream_t *stream) +{ + POKESAVESS_STREAM_START(64); + POKESAVESS_STREAM_32(MinxCPU.BA.D); + POKESAVESS_STREAM_32(MinxCPU.HL.D); + POKESAVESS_STREAM_32(MinxCPU.X.D); + POKESAVESS_STREAM_32(MinxCPU.Y.D); + POKESAVESS_STREAM_32(MinxCPU.SP.D); + POKESAVESS_STREAM_32(MinxCPU.PC.D); + POKESAVESS_STREAM_32(MinxCPU.N.D); + POKESAVESS_STREAM_8(MinxCPU.U1); + POKESAVESS_STREAM_8(MinxCPU.U2); + POKESAVESS_STREAM_8(MinxCPU.F); + POKESAVESS_STREAM_8(MinxCPU.E); + POKESAVESS_STREAM_8(MinxCPU.IR); + POKESAVESS_STREAM_8(MinxCPU.Shift_U); + POKESAVESS_STREAM_8(MinxCPU.Status); + POKESAVESS_STREAM_8(MinxCPU.IRQ_Vector); + POKESAVESS_STREAM_A(MinxCPU.Reserved, 28); + POKESAVESS_END(64); +} + +// Force call Interrupt by the address +int MinxCPU_CallIRQ(uint8_t addr) +{ + if (MinxCPU.Status == MINX_STATUS_IRQ) return 0; + MinxCPU.Status = MINX_STATUS_IRQ; + MinxCPU.IRQ_Vector = addr; + return 1; +} diff --git a/pm/src/core/MinxCPU.h b/pm/src/core/MinxCPU.h new file mode 100644 index 0000000..86103a0 --- /dev/null +++ b/pm/src/core/MinxCPU.h @@ -0,0 +1,695 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXCPU_CORE +#define MINXCPU_CORE + +#include +#include +#include + +/* For some reason, '_BIG_ENDIAN' is always defined when + * building for 3DS/Switch with devkitarm/a64... */ +#if defined (_BIG_ENDIAN) && !defined (_3DS) && !defined(HAVE_LIBNX) + +typedef union { + struct { + uint8_t X; + uint8_t I; + uint8_t H; + uint8_t L; + } B; + struct { + uint16_t H; + uint16_t L; + } W; + uint32_t D; +} MinxRegx; + +#else + +typedef union { + struct { + uint8_t L; + uint8_t H; + uint8_t I; + uint8_t X; + } B; + struct { + uint16_t L; + uint16_t H; + } W; + uint32_t D; +} MinxRegx; + +#endif + +#define MINX_FLAG_ZERO 0x01 +#define MINX_FLAG_CARRY 0x02 +#define MINX_FLAG_OVERFLOW 0x04 +#define MINX_FLAG_SIGN 0x08 +#define MINX_FLAG_BCD 0x10 +#define MINX_FLAG_NIBBLE 0x20 +#define MINX_FLAG_INTFLG 0x40 +#define MINX_FLAG_INTOFF 0x80 + +#define MINX_FLAG_SAVE_NUL 0xF0 +#define MINX_FLAG_SAVE_O 0xF4 +#define MINX_FLAG_SAVE_CO 0xF6 +#define MINX_FLAG_SAVE_COS 0xFE + +// Status reasons +enum { + MINX_STATUS_NORMAL = 0, // Normal operation + MINX_STATUS_HALT = 1, // CPU during HALT + MINX_STATUS_STOP = 2, // CPU during STOP + MINX_STATUS_IRQ = 3 // Delay caused by hardware IRQ +}; + +// Signed 8-Bits to 16-Bits converter +static INLINE uint16_t S8_TO_16(int8_t a) +{ + return (a & 0x80) ? (0xFF00 | a) : a; +} + +typedef struct { + // Registers + MinxRegx BA; // Registers A, B + MinxRegx HL; // Registers L, H, I + MinxRegx X; // Registers X, XI + MinxRegx Y; // Registers Y, YI + MinxRegx SP; // Register SP + MinxRegx PC; // Registers PC, V + MinxRegx N; // for [N+#nn], I is written here too + uint8_t U1; // V Shadow 1 + uint8_t U2; // V Shadow 2 + uint8_t F; // Flags + uint8_t E; // Exception + uint8_t IR; // Last Instruction Register (for open-bus) + uint8_t Shift_U; // Shift U, set to 2 when: U modify, branch, return + uint8_t Status; // CPU Status (0 = Normal, 1 = Halt, 2 = Stoped, 3 = IRQ) + uint8_t IRQ_Vector; // IRQ Vector when Status is IRQ + uint8_t Reserved[28]; // Reserved bytes +} TMinxCPU; + +// CPU registers +extern TMinxCPU MinxCPU; + +// Callbacks (Must be coded by the user) +uint8_t MinxCPU_OnRead(int cpu, uint32_t addr); +void MinxCPU_OnWrite(int cpu, uint32_t addr, uint8_t data); +void MinxCPU_OnIRQHandle(uint8_t flag, uint8_t shift_u); +void MinxCPU_OnIRQAct(uint8_t intr); + +// Functions +int MinxCPU_Create(void); // Create MinxCPU +void MinxCPU_Destroy(void); // Destroy MinxCPU +void MinxCPU_Reset(int hardreset); // Reset CPU +int MinxCPU_LoadStateStream(memstream_t *stream, uint32_t bsize); // Load State from stream +int MinxCPU_SaveStateStream(memstream_t *stream); // Save State to stream +int MinxCPU_Exec(void); // Execute 1 CPU instruction +int MinxCPU_CallIRQ(uint8_t IRQ); // Call an IRQ + +// Helpers +static INLINE uint16_t ReadMem16(uint32_t addr) +{ + return MinxCPU_OnRead(1, addr) + (MinxCPU_OnRead(1, addr+1) << 8); +} + +static INLINE void WriteMem16(uint32_t addr, uint16_t data) +{ + MinxCPU_OnWrite(1, addr, (uint8_t)data); + MinxCPU_OnWrite(1, addr+1, data >> 8); +} + +static INLINE uint8_t Fetch8(void) +{ + if (MinxCPU.PC.W.L & 0x8000) { + // Banked area + MinxCPU.IR = MinxCPU_OnRead(1, (MinxCPU.PC.W.L++ & 0x7FFF) | (MinxCPU.PC.B.I << 15)); + } else { + // Unbanked area + MinxCPU.IR = MinxCPU_OnRead(1, MinxCPU.PC.W.L++); + } + return MinxCPU.IR; +} + +static INLINE uint16_t Fetch16(void) +{ + uint8_t LB = Fetch8(); + return (Fetch8() << 8) | LB; +} + +static INLINE void Set_U(uint8_t val) +{ + if (val != MinxCPU.U2) MinxCPU.Shift_U = 2; + MinxCPU.U1 = val; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +// Instruction exec. prototypes + +int MinxCPU_ExecCE(void); +int MinxCPU_ExecCF(void); +int MinxCPU_ExecSPCE(void); +int MinxCPU_ExecSPCF(void); + +// Instructions Macros + +static INLINE uint8_t ADD8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A + B; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES < A) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x80) != 0) && (((A ^ B) & 0x80) == 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 128) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) + (B & 15)) >= 10) { + RES = A + B + 6; + } else { + RES = A + B; + } + if (RES >= 0xA0) RES += 0x60; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES < A) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) + (B & 15); + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8) != 0) && (((A ^ B) & 0x8) == 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 8) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) + (B & 15)) >= 10) { + RES = (A & 15) + (B & 15) + 6; + } else { + RES = (A & 15) + (B & 15); + } + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0x0F; + } +} + +static INLINE uint16_t ADD16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A + B; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES < A) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8000) != 0) && (((A ^ B) & 0x8000) == 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 0x8000) MinxCPU.F |= MINX_FLAG_SIGN; + return (uint16_t)RES; +} + +static INLINE uint8_t ADC8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A + B + CARRY; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES < A) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x80) != 0) && (((A ^ B) & 0x80) == 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 128) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) + (B & 15) + CARRY) >= 10) { + RES = A + B + CARRY + 6; + } else { + RES = A + B + CARRY; + } + if (RES >= 0xA0) RES += 0x60; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES < A) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) + (B & 15) + CARRY; + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8) != 0) && (((A ^ B) & 0x8) == 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 8) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) + (B & 15) + CARRY) >= 10) { + RES = (A & 15) + (B & 15) + CARRY + 6; + } else { + RES = (A & 15) + (B & 15) + CARRY; + } + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0x0F; + } +} + +static INLINE uint16_t ADC16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A + B + ((MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0); + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES < A) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8000) != 0) && (((A ^ B) & 0x8000) == 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 0x8000) MinxCPU.F |= MINX_FLAG_SIGN; + return (uint16_t)RES; +} + +static INLINE uint8_t SUB8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A - B; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A < B) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x80) != 0) && (((A ^ B) & 0x80) != 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 128) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) - (B & 15)) >= 10) { + RES = A - B - 6; + } else { + RES = A - B; + } + if (RES >= 0xA0) RES -= 0x60; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A < B) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) - (B & 15); + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8) != 0) && (((A ^ B) & 0x8) != 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 8) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) - (B & 15)) >= 10) { + RES = (A & 15) - (B & 15) - 6; + } else { + RES = (A & 15) - (B & 15); + } + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0x0F; + } +} + +static INLINE uint16_t SUB16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A - B; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A < B) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8000) != 0) && (((A ^ B) & 0x8000) != 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 0x8000) MinxCPU.F |= MINX_FLAG_SIGN; + return (uint16_t)RES; +} + +static INLINE uint8_t SBC8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A - B - CARRY; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A < B) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x80) != 0) && (((A ^ B) & 0x80) != 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 128) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) - (B & 15) - CARRY) >= 10) { + RES = A - B - CARRY - 6; + } else { + RES = A - B - CARRY; + } + if (RES >= 0xA0) RES -= 0x60; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A < B) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) - (B & 15) - CARRY; + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8) != 0) && (((A ^ B) & 0x8) != 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 8) MinxCPU.F |= MINX_FLAG_SIGN; + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) - (B & 15) - CARRY) >= 10) { + RES = (A & 15) - (B & 15) - CARRY - 6; + } else { + RES = (A & 15) - (B & 15) - CARRY; + } + if ((RES & 15) == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (RES >= 16) MinxCPU.F |= MINX_FLAG_CARRY; + return RES & 0x0F; + } +} + +static INLINE uint16_t SBC16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A - B - ((MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0); + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (RES == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A < B) MinxCPU.F |= MINX_FLAG_CARRY; + if ((((A ^ RES) & 0x8000) != 0) && (((A ^ B) & 0x8000) != 0)) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (RES & 0x8000) MinxCPU.F |= MINX_FLAG_SIGN; + return (uint16_t)RES; +} + +static INLINE uint8_t AND8(uint8_t A, uint8_t B) +{ + A &= B; + MinxCPU.F &= MINX_FLAG_SAVE_CO; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 128) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t OR8(uint8_t A, uint8_t B) +{ + A |= B; + MinxCPU.F &= MINX_FLAG_SAVE_CO; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 128) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t XOR8(uint8_t A, uint8_t B) +{ + A ^= B; + MinxCPU.F &= MINX_FLAG_SAVE_CO; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 128) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t INC8(uint8_t A) +{ + A++; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE uint16_t INC16(uint16_t A) +{ + A++; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE uint8_t DEC8(uint8_t A) +{ + A--; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE uint16_t DEC16(uint16_t A) +{ + A--; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE void PUSH(uint8_t A) +{ + MinxCPU.SP.W.L--; + MinxCPU_OnWrite(1, MinxCPU.SP.D, A); +} + +static INLINE uint8_t POP(void) +{ + register uint8_t data; + data = MinxCPU_OnRead(1, MinxCPU.SP.D); + MinxCPU.SP.W.L++; + return data; +} + +static INLINE void CALLS(uint16_t OFFSET) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = MinxCPU.PC.W.L + OFFSET - 1; +} + +static INLINE void JMPS(uint16_t OFFSET) +{ + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = MinxCPU.PC.W.L + OFFSET - 1; +} + +static INLINE void CALLU(uint16_t ADDR) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ADDR; +} + +static INLINE void JMPU(uint16_t ADDR) +{ + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ADDR; +} + +static INLINE void JDBNZ(uint16_t OFFSET) +{ + MinxCPU.BA.B.H = DEC8(MinxCPU.BA.B.H); + if (MinxCPU.BA.B.H != 0) { + JMPS(OFFSET); + } +} + +static INLINE uint8_t SWAP(uint8_t A) +{ + return (A << 4) | (A >> 4); +} + +static INLINE void RET(void) +{ + MinxCPU.PC.B.L = POP(); + MinxCPU.PC.B.H = POP(); + MinxCPU.PC.B.I = POP(); + Set_U(MinxCPU.PC.B.I); +} + +static INLINE void RETI(void) +{ + MinxCPU.F = POP(); + MinxCPU.PC.B.L = POP(); + MinxCPU.PC.B.H = POP(); + MinxCPU.PC.B.I = POP(); + Set_U(MinxCPU.PC.B.I); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +static INLINE void CALLX(uint16_t ADDR) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ReadMem16((MinxCPU.HL.B.I << 16) + ADDR); +} + +static INLINE void CALLI(uint16_t ADDR) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + PUSH(MinxCPU.F); + MinxCPU.F |= 0xC0; + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ReadMem16(ADDR); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +static INLINE void JMPI(uint16_t ADDR) +{ + PUSH(MinxCPU.F); + MinxCPU.F |= 0xC0; + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ReadMem16(ADDR); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +static INLINE uint8_t SAL(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + if ((!(A & 0x40)) != (!(A & 0x80))) MinxCPU.F |= MINX_FLAG_OVERFLOW; + A = A << 1; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t SHL(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + A = A << 1; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t SAR(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A & 0x80) | (A >> 1); + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t SHR(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = A >> 1; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t ROLC(uint8_t A) +{ + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0; + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A << 1) | CARRY; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t ROL(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A << 1) | (A >> 7); + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t RORC(uint8_t A) +{ + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 0x80 : 0x00; + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A >> 1) | CARRY; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t ROR(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A >> 1) | (A << 7); + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t NOT(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_CO; + A = A ^ 0xFF; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE uint8_t NEG(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + A = -A; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; else MinxCPU.F |= MINX_FLAG_CARRY; + if (A == 0x80) MinxCPU.F |= MINX_FLAG_OVERFLOW; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + return A; +} + +static INLINE void HALT(void) +{ + MinxCPU.Status = MINX_STATUS_HALT; +} + +static INLINE void STOP(void) +{ + MinxCPU.Status = MINX_STATUS_STOP; +} + +static INLINE void MUL(void) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + MinxCPU.HL.W.L = (uint16_t)MinxCPU.HL.B.L * (uint16_t)MinxCPU.BA.B.L; + if (MinxCPU.HL.W.L == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (MinxCPU.HL.W.L & 0x8000) MinxCPU.F |= MINX_FLAG_SIGN; +} + +static INLINE void DIV(void) +{ + uint16_t RES; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (MinxCPU.BA.B.L == 0) + return; + RES = MinxCPU.HL.W.L / MinxCPU.BA.B.L; + if (RES < 256) { + MinxCPU.HL.B.H = MinxCPU.HL.W.L % MinxCPU.BA.B.L; + MinxCPU.HL.B.L = (uint8_t)RES; + if (MinxCPU.HL.B.L == 0) MinxCPU.F |= MINX_FLAG_ZERO; + if (MinxCPU.HL.B.L & 0x80) MinxCPU.F |= MINX_FLAG_SIGN; + } else MinxCPU.F |= (MINX_FLAG_OVERFLOW | MINX_FLAG_SIGN); +} + +#endif diff --git a/pm/src/core/MinxCPU_CE.c b/pm/src/core/MinxCPU_CE.c new file mode 100644 index 0000000..0857dcf --- /dev/null +++ b/pm/src/core/MinxCPU_CE.c @@ -0,0 +1,1127 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +// Note: Any write to MinxCPU.HL.B.I needs to be reflected into N.B.I + +#include "MinxCPU.h" + +int MinxCPU_ExecCE(void) +{ + uint8_t I8A; + uint16_t I16; + + // Read IR + MinxCPU.IR = Fetch8(); + + // Process instruction + switch(MinxCPU.IR) { + + case 0x00: // ADD A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x01: // ADD A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x02: // ADD A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x03: // ADD A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x04: // ADD [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADD8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L)); + return 16; + case 0x05: // ADD [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADD8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A)); + return 20; + case 0x06: // ADD [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADD8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D))); + return 20; + case 0x07: // ADD [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADD8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D))); + return 20; + + case 0x08: // ADC A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x09: // ADC A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x0A: // ADC A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x0B: // ADC A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x0C: // ADC [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADC8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L)); + return 16; + case 0x0D: // ADC [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADC8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A)); + return 20; + case 0x0E: // ADC [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADC8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D))); + return 20; + case 0x0F: // ADC [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, ADC8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D))); + return 20; + + case 0x10: // SUB A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x11: // SUB A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x12: // SUB A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x13: // SUB A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x14: // SUB [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L)); + return 16; + case 0x15: // SUB [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A)); + return 20; + case 0x16: // SUB [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D))); + return 20; + case 0x17: // SUB [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D))); + return 20; + + case 0x18: // SBC A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x19: // SBC A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x1A: // SBC A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x1B: // SBC A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x1C: // SBC [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, SBC8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L)); + return 16; + case 0x1D: // SBC [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, SBC8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A)); + return 20; + case 0x1E: // SBC [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SBC8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D))); + return 20; + case 0x1F: // SBC [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SBC8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D))); + return 20; + + case 0x20: // AND A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x21: // AND A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x22: // AND A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x23: // AND A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x24: // AND [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, AND8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L)); + return 16; + case 0x25: // AND [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, AND8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A)); + return 20; + case 0x26: // AND [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, AND8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D))); + return 20; + case 0x27: // AND [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, AND8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D))); + return 20; + + case 0x28: // OR A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x29: // OR A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x2A: // OR A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x2B: // OR A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x2C: // OR [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, OR8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L)); + return 16; + case 0x2D: // OR [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, OR8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A)); + return 20; + case 0x2E: // OR [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, OR8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D))); + return 20; + case 0x2F: // OR [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, OR8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D))); + return 20; + + case 0x30: // CMP A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x31: // CMP A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x32: // CMP A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x33: // CMP A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x34: // CMP [HL], A + SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L); + return 16; + case 0x35: // CMP [HL], #nn + I8A = Fetch8(); + SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A); + return 20; + case 0x36: // CMP [HL], [X] + SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D)); + return 20; + case 0x37: // CMP [HL], [Y] + SUB8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 20; + + case 0x38: // XOR A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x39: // XOR A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + case 0x3A: // XOR A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 16; + case 0x3B: // XOR A, [Y+L] + I16 = MinxCPU.Y.W.L+ S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 16; + + case 0x3C: // XOR [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, XOR8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU.BA.B.L)); + return 16; + case 0x3D: // XOR [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, XOR8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A)); + return 20; + case 0x3E: // XOR [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, XOR8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.X.D))); + return 20; + case 0x3F: // XOR [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, XOR8(MinxCPU_OnRead(1, MinxCPU.HL.D), MinxCPU_OnRead(1, MinxCPU.Y.D))); + return 20; + + case 0x40: // MOV A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x41: // MOV A, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + case 0x42: // MOV A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x43: // MOV A, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + + case 0x44: // MOV [X+#ss], A + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.BA.B.L); + return 16; + case 0x45: // MOV [Y+#ss], A + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.BA.B.L); + return 16; + case 0x46: // MOV [X+L], A + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.BA.B.L); + return 16; + case 0x47: // MOV [Y+L], A + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.BA.B.L); + return 16; + + case 0x48: // MOV B, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x49: // MOV B, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + case 0x4A: // MOV B, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x4B: // MOV B, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + + case 0x4C: // MOV [X+#ss], B + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.BA.B.H); + return 16; + case 0x4D: // MOV [Y+#ss], B + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.BA.B.H); + return 16; + case 0x4E: // MOV [X+L], B + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.BA.B.H); + return 16; + case 0x4F: // MOV [Y+L], B + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.BA.B.H); + return 16; + + case 0x50: // MOV L, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x51: // MOV L, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + case 0x52: // MOV L, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x53: // MOV L, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + + case 0x54: // MOV [X+#ss], L + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.HL.B.L); + return 16; + case 0x55: // MOV [Y+#ss], L + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.HL.B.L); + return 16; + case 0x56: // MOV [X+L], L + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.HL.B.L); + return 16; + case 0x57: // MOV [Y+L], L + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.HL.B.L); + return 16; + + case 0x58: // MOV H, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x59: // MOV H, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + case 0x5A: // MOV H, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 16; + case 0x5B: // MOV H, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 16; + + case 0x5C: // MOV [X+#ss], H + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.HL.B.H); + return 16; + case 0x5D: // MOV [Y+#ss], H + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.HL.B.H); + return 16; + case 0x5E: // MOV [X+L], H + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.HL.B.H); + return 16; + case 0x5F: // MOV [Y+L], H + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.HL.B.H); + return 16; + + case 0x60: // MOV [HL], [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 20; + case 0x61: // MOV [HL], [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 20; + case 0x62: // MOV [HL], [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 20; + case 0x63: // MOV [HL], [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 20; + + case 0x64: // *ADC BA, #nnnn + I16 = Fetch16(); + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, I16); + return 16; + case 0x65: // *ADC HL, #nnnn + I16 = Fetch16(); + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, I16); + return 16; + + case 0x66: // ??? BA, #nn00+L + I8A = Fetch8(); + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, (I8A << 8) | MinxCPU.HL.B.L); + return 24; + case 0x67: // ??? HL, #nn00+L + I8A = Fetch8(); + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, (I8A << 8) | MinxCPU.HL.B.L); + return 24; + + case 0x68: // MOV [X], [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 20; + case 0x69: // MOV [X], [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 20; + case 0x6A: // MOV [X], [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 20; + case 0x6B: // MOV [X], [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 20; + + case 0x6C: // *ADD SP, #nnnn + I16 = Fetch8(); + MinxCPU.SP.W.L = ADD16(MinxCPU.SP.W.L, I16); + + case 0x6D: // ??? HL, #nn + I8A = Fetch8(); + MinxCPU.HL.W.L = ADD16(MinxCPU.X.W.L, ((I8A << 4) * 3) + ((I8A & 0x08) >> 3)); + MinxCPU.F &= ~MINX_FLAG_CARRY; // It seems that carry gets clear? + return 40; + case 0x6E: // ??? SP, #nn00+L + I8A = Fetch8(); + MinxCPU.SP.W.L = ADD16(MinxCPU.SP.W.L, (I8A << 8) | MinxCPU.HL.B.L); + return 16; + case 0x6F: // ??? HL, L + MinxCPU.HL.W.L = ADD16(MinxCPU.X.W.L, ((MinxCPU.HL.B.L << 4) * 3) + ((MinxCPU.HL.B.L & 0x08) >> 3)); + MinxCPU.F &= ~MINX_FLAG_CARRY; // It seems that carry gets clear? + return 40; + + case 0x70: // NOTHING + MinxCPU.PC.W.L++; + return 64; + case 0x71: // NOTHING + MinxCPU.PC.W.L++; + return 64; + case 0x72: // NOTHING + return 64; + case 0x73: // NOTHING + return 64; + + case 0x74: // *MOV A, [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 64; + case 0x75: // *MOV L, [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 64; + case 0x76: // *MOV A, [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 64; + case 0x77: // *MOV L, [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 64; + + case 0x78: // MOV [Y], [X+#ss] + I8A = Fetch8(); + I16 = MinxCPU.X.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 20; + case 0x79: // MOV [Y], [Y+#ss] + I8A = Fetch8(); + I16 = MinxCPU.Y.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 20; + case 0x7A: // MOV [Y], [X+L] + I16 = MinxCPU.X.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16)); + return 20; + case 0x7B: // MOV [Y], [Y+L] + I16 = MinxCPU.Y.W.L + S8_TO_16(MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16)); + return 20; + + case 0x7C: // NOTHING #nn + MinxCPU.PC.W.L++; + return 20; + case 0x7D: // NOTHING #nn + MinxCPU.PC.W.L++; + return 16; + case 0x7E: // NOTHING + return 20; + case 0x7F: // NOTHING + return 16; + + case 0x80: // SAL A + MinxCPU.BA.B.L = SAL(MinxCPU.BA.B.L); + return 12; + case 0x81: // SAL B + MinxCPU.BA.B.H = SAL(MinxCPU.BA.B.H); + return 12; + case 0x82: // SAL [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, SAL(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x83: // SAL [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SAL(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0x84: // SHL A + MinxCPU.BA.B.L = SHL(MinxCPU.BA.B.L); + return 12; + case 0x85: // SHL B + MinxCPU.BA.B.H = SHL(MinxCPU.BA.B.H); + return 12; + case 0x86: // SHL [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, SHL(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x87: // SHL [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SHL(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0x88: // SAR A + MinxCPU.BA.B.L = SAR(MinxCPU.BA.B.L); + return 12; + case 0x89: // SAR B + MinxCPU.BA.B.H = SAR(MinxCPU.BA.B.H); + return 12; + case 0x8A: // SAR [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, SAR(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x8B: // SAR [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SAR(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0x8C: // SHR A + MinxCPU.BA.B.L = SHR(MinxCPU.BA.B.L); + return 12; + case 0x8D: // SHR B + MinxCPU.BA.B.H = SHR(MinxCPU.BA.B.H); + return 12; + case 0x8E: // SHR [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, SHR(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x8F: // SHR [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SHR(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0x90: // ROLC A + MinxCPU.BA.B.L = ROLC(MinxCPU.BA.B.L); + return 12; + case 0x91: // ROLC B + MinxCPU.BA.B.H = ROLC(MinxCPU.BA.B.H); + return 12; + case 0x92: // ROLC [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, ROLC(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x93: // ROLC [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, ROLC(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0x94: // ROL A + MinxCPU.BA.B.L = ROL(MinxCPU.BA.B.L); + return 12; + case 0x95: // ROL B + MinxCPU.BA.B.H = ROL(MinxCPU.BA.B.H); + return 12; + case 0x96: // ROL [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, ROL(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x97: // ROL [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, ROL(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0x98: // RORC A + MinxCPU.BA.B.L = RORC(MinxCPU.BA.B.L); + return 12; + case 0x99: // RORC B + MinxCPU.BA.B.H = RORC(MinxCPU.BA.B.H); + return 12; + case 0x9A: // RORC [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, RORC(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x9B: // RORC [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, RORC(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0x9C: // ROR A + MinxCPU.BA.B.L = ROR(MinxCPU.BA.B.L); + return 12; + case 0x9D: // ROR B + MinxCPU.BA.B.H = ROR(MinxCPU.BA.B.H); + return 12; + case 0x9E: // ROR [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, ROR(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0x9F: // ROR [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, ROR(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0xA0: // NOT A + MinxCPU.BA.B.L = NOT(MinxCPU.BA.B.L); + return 12; + case 0xA1: // NOT B + MinxCPU.BA.B.H = NOT(MinxCPU.BA.B.H); + return 12; + case 0xA2: // NOT [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, NOT(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0xA3: // NOT [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, NOT(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0xA4: // NEG A + MinxCPU.BA.B.L = NEG(MinxCPU.BA.B.L); + return 12; + case 0xA5: // NEG B + MinxCPU.BA.B.H = NEG(MinxCPU.BA.B.H); + return 12; + case 0xA6: // NEG [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D | I8A, NEG(MinxCPU_OnRead(1, MinxCPU.N.D | I8A))); + return 20; + case 0xA7: // NEG [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, NEG(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 16; + + case 0xA8: // EX BA, A + MinxCPU.BA.W.L = S8_TO_16(MinxCPU.BA.B.L); + return 12; + + case 0xA9: // NOTHING + return 8; + case 0xAA: // NOTHING + return 12; + + case 0xAB: // CRASH + case 0xAC: // CRASH + case 0xAD: // CRASH + return 64; + + case 0xAE: // HALT + HALT(); + return 8; + case 0xAF: // STOP + STOP(); + return 8; + + case 0xB0: // AND B, #nn + I8A = Fetch8(); + MinxCPU.BA.B.H = AND8(MinxCPU.BA.B.H, I8A); + return 12; + case 0xB1: // AND L, #nn + I8A = Fetch8(); + MinxCPU.HL.B.L = AND8(MinxCPU.HL.B.L, I8A); + return 12; + case 0xB2: // AND H, #nn + I8A = Fetch8(); + MinxCPU.HL.B.H = AND8(MinxCPU.HL.B.H, I8A); + return 12; + case 0xB3: // MOV H, V + MinxCPU.HL.B.H = MinxCPU.PC.B.I; + return 12; + + case 0xB4: // OR B, #nn + I8A = Fetch8(); + MinxCPU.BA.B.H = OR8(MinxCPU.BA.B.H, I8A); + return 12; + case 0xB5: // OR L, #nn + I8A = Fetch8(); + MinxCPU.HL.B.L = OR8(MinxCPU.HL.B.L, I8A); + return 12; + case 0xB6: // OR H, #nn + I8A = Fetch8(); + MinxCPU.HL.B.H = OR8(MinxCPU.HL.B.H, I8A); + return 12; + case 0xB7: // ??? X + MinxCPU.X.B.H = MinxCPU.PC.B.I; + return 12; + + case 0xB8: // XOR B, #nn + I8A = Fetch8(); + MinxCPU.BA.B.H = XOR8(MinxCPU.BA.B.H, I8A); + return 12; + case 0xB9: // XOR L, #nn + I8A = Fetch8(); + MinxCPU.HL.B.L = XOR8(MinxCPU.HL.B.L, I8A); + return 12; + case 0xBA: // XOR H, #nn + I8A = Fetch8(); + MinxCPU.HL.B.H = XOR8(MinxCPU.HL.B.H, I8A); + return 12; + case 0xBB: // ??? Y + MinxCPU.Y.B.H = MinxCPU.PC.B.I; + return 12; + + case 0xBC: // CMP B, #nn + I8A = Fetch8(); + SUB8(MinxCPU.BA.B.H, I8A); + return 12; + case 0xBD: // CMP L, #nn + I8A = Fetch8(); + SUB8(MinxCPU.HL.B.L, I8A); + return 12; + case 0xBE: // CMP H, #nn + I8A = Fetch8(); + SUB8(MinxCPU.HL.B.H, I8A); + return 12; + case 0xBF: // CMP N, #nn + I8A = Fetch8(); + SUB8(MinxCPU.N.B.H, I8A); + return 12; + + case 0xC0: // MOV A, N + MinxCPU.BA.B.L = MinxCPU.N.B.H; + return 8; + case 0xC1: // MOV A, F + MinxCPU.BA.B.L = MinxCPU.F; + return 8; + case 0xC2: // MOV N, A + MinxCPU.N.B.H = MinxCPU.BA.B.L; + return 8; + case 0xC3: // MOV F, A + MinxCPU.F = MinxCPU.BA.B.L; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); + return 8; + + case 0xC4: // MOV U, #nn + I8A = Fetch8(); + Set_U(I8A); + return 16; + case 0xC5: // MOV I, #nn + I8A = Fetch8(); + MinxCPU.HL.B.I = I8A; + MinxCPU.N.B.I = MinxCPU.HL.B.I; + return 12; + case 0xC6: // MOV XI, #nn + I8A = Fetch8(); + MinxCPU.X.B.I = I8A; + return 12; + case 0xC7: // MOV YI, #nn + I8A = Fetch8(); + MinxCPU.Y.B.I = I8A; + return 12; + + case 0xC8: // MOV A, V + MinxCPU.BA.B.L = MinxCPU.PC.B.I; + return 8; + case 0xC9: // MOV A, I + MinxCPU.BA.B.L = MinxCPU.HL.B.I; + return 8; + case 0xCA: // MOV A, XI + MinxCPU.BA.B.L = MinxCPU.X.B.I; + return 8; + case 0xCB: // MOV A, YI + MinxCPU.BA.B.L = MinxCPU.Y.B.I; + return 8; + + case 0xCC: // MOV U, A + Set_U(MinxCPU.BA.B.L); + return 8; + case 0xCD: // MOV I, A + MinxCPU.HL.B.I = MinxCPU.BA.B.L; + MinxCPU.N.B.I = MinxCPU.HL.B.I; + return 8; + case 0xCE: // MOV XI, A + MinxCPU.X.B.I = MinxCPU.BA.B.L; + return 8; + case 0xCF: // MOV YI, A + MinxCPU.Y.B.I = MinxCPU.BA.B.L; + return 8; + + case 0xD0: // MOV A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, I16); + return 20; + case 0xD1: // MOV B, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, I16); + return 20; + case 0xD2: // MOV L, [#nnnn] + I16 = Fetch16(); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, I16); + return 20; + case 0xD3: // MOV H, [#nnnn] + I16 = Fetch16(); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, I16); + return 20; + + case 0xD4: // MOV [#nnnn], A + I16 = Fetch16(); + MinxCPU_OnWrite(1, I16, MinxCPU.BA.B.L); + return 20; + case 0xD5: // MOV [#nnnn], B + I16 = Fetch16(); + MinxCPU_OnWrite(1, I16, MinxCPU.BA.B.H); + return 20; + case 0xD6: // MOV [#nnnn], L + I16 = Fetch16(); + MinxCPU_OnWrite(1, I16, MinxCPU.HL.B.L); + return 20; + case 0xD7: // MOV [#nnnn], H + I16 = Fetch16(); + MinxCPU_OnWrite(1, I16, MinxCPU.HL.B.H); + return 20; + + case 0xD8: // MUL L, A + MUL(); + return 48; + + case 0xD9: // DIV HL, A + DIV(); + return 52; + + case 0xDA: // ??? #nn + case 0xDB: // ??? #nn + return MinxCPU_ExecSPCE(); + case 0xDC: // CRASH + return 64; + case 0xDD: // NOTHING + return 16; + case 0xDE: // ??? #nn + case 0xDF: // ??? #nn + return MinxCPU_ExecSPCE(); + + case 0xE0: // JL #ss + I8A = Fetch8(); + if ( ((MinxCPU.F & MINX_FLAG_OVERFLOW)!=0) != ((MinxCPU.F & MINX_FLAG_SIGN)!=0) ) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xE1: // JLE #ss + I8A = Fetch8(); + if ( (((MinxCPU.F & MINX_FLAG_OVERFLOW)==0) != ((MinxCPU.F & MINX_FLAG_SIGN)==0)) || ((MinxCPU.F & MINX_FLAG_ZERO)!=0) ) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xE2: // JG #ss + I8A = Fetch8(); + if ( (((MinxCPU.F & MINX_FLAG_OVERFLOW)!=0) == ((MinxCPU.F & MINX_FLAG_SIGN)!=0)) && ((MinxCPU.F & MINX_FLAG_ZERO)==0) ) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xE3: // JGE #ss + I8A = Fetch8(); + if ( ((MinxCPU.F & MINX_FLAG_OVERFLOW)==0) == ((MinxCPU.F & MINX_FLAG_SIGN)==0) ) { + JMPS(S8_TO_16(I8A)); + } + return 12; + + case 0xE4: // JO #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_OVERFLOW) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xE5: // JNO #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_OVERFLOW)) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xE6: // JP #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_SIGN)) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xE7: // JNP #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_SIGN) { + JMPS(S8_TO_16(I8A)); + } + return 12; + + case 0xE8: // JNX0 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x01)) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xE9: // JNX1 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x02)) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xEA: // JNX2 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x04)) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xEB: // JNX3 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x08)) { + JMPS(S8_TO_16(I8A)); + } + return 12; + + case 0xEC: // JX0 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x01) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xED: // JX1 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x02) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xEE: // JX2 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x04) { + JMPS(S8_TO_16(I8A)); + } + return 12; + case 0xEF: // JX3 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x08) { + JMPS(S8_TO_16(I8A)); + } + return 12; + + case 0xF0: // CALLL #ss + I8A = Fetch8(); + if ( ((MinxCPU.F & MINX_FLAG_OVERFLOW)!=0) != ((MinxCPU.F & MINX_FLAG_SIGN)!=0) ) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xF1: // CALLLE #ss + I8A = Fetch8(); + if ( (((MinxCPU.F & MINX_FLAG_OVERFLOW)==0) != ((MinxCPU.F & MINX_FLAG_SIGN)==0)) || ((MinxCPU.F & MINX_FLAG_ZERO)!=0) ) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xF2: // CALLG #ss + I8A = Fetch8(); + if ( (((MinxCPU.F & MINX_FLAG_OVERFLOW)!=0) == ((MinxCPU.F & MINX_FLAG_SIGN)!=0)) && ((MinxCPU.F & MINX_FLAG_ZERO)==0) ) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xF3: // CALLGE #ss + I8A = Fetch8(); + if ( ((MinxCPU.F & MINX_FLAG_OVERFLOW)==0) == ((MinxCPU.F & MINX_FLAG_SIGN)==0) ) { + CALLS(S8_TO_16(I8A)); + } + return 12; + + case 0xF4: // CALLO #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_OVERFLOW) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xF5: // CALLNO #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_OVERFLOW)) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xF6: // CALLNS #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_SIGN)) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xF7: // CALLS #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_SIGN) { + CALLS(S8_TO_16(I8A)); + } + return 12; + + case 0xF8: // CALLNX0 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x01)) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xF9: // CALLNX1 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x02)) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xFA: // CALLNX2 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x04)) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xFB: // CALLNX3 #ss + I8A = Fetch8(); + if (!(MinxCPU.E & 0x08)) { + CALLS(S8_TO_16(I8A)); + } + return 12; + + case 0xFC: // CALLX0 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x01) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xFD: // CALLX1 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x02) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xFE: // CALLX2 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x04) { + CALLS(S8_TO_16(I8A)); + } + return 12; + case 0xFF: // CALLX3 #ss + I8A = Fetch8(); + if (MinxCPU.E & 0x08) { + CALLS(S8_TO_16(I8A)); + } + return 12; + + default: + break; + } + + return 4; +} diff --git a/pm/src/core/MinxCPU_CF.c b/pm/src/core/MinxCPU_CF.c new file mode 100644 index 0000000..03bf357 --- /dev/null +++ b/pm/src/core/MinxCPU_CF.c @@ -0,0 +1,779 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +// Note: Any write to MinxCPU.HL.B.I needs to be reflected into MinxCPU.N.B.I + +#include "MinxCPU.h" + +int MinxCPU_ExecCF(void) +{ + uint8_t I8A; + uint16_t I16; + + // Read IR + MinxCPU.IR = Fetch8(); + + // Process instruction + switch(MinxCPU.IR) { + case 0x00: // ADD BA, BA + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x01: // ADD BA, HL + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x02: // ADD BA, X + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x03: // ADD BA, Y + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x04: // ADC BA, BA + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x05: // ADC BA, HL + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x06: // ADC BA, X + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x07: // ADC BA, Y + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x08: // SUB BA, BA + MinxCPU.BA.W.L = SUB16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x09: // SUB BA, HL + MinxCPU.BA.W.L = SUB16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x0A: // SUB BA, X + MinxCPU.BA.W.L = SUB16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x0B: // SUB BA, Y + MinxCPU.BA.W.L = SUB16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x0C: // SBC BA, BA + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x0D: // SBC BA, HL + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x0E: // SBC BA, X + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x0F: // SBC BA, Y + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x10: // *ADD BA, BA + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x11: // *ADD BA, HL + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x12: // *ADD BA, X + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x13: // *ADD BA, Y + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x14: // *ADC BA, BA + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x15: // *ADC BA, HL + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x16: // *ADC BA, X + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x17: // *ADC BA, Y + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x18: // CMP BA, BA + SUB16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x19: // CMP BA, HL + SUB16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x1A: // CMP BA, X + SUB16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x1B: // CMP BA, Y + SUB16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x1C: // *SBC BA, BA + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x1D: // *SBC BA, HL + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x1E: // *SBC BA, X + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x1F: // *SBC BA, Y + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x20: // ADD HL, BA + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.BA.W.L); + return 16; + case 0x21: // ADD HL, HL + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.HL.W.L); + return 16; + case 0x22: // ADD HL, X + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.X.W.L); + return 16; + case 0x23: // ADD HL, Y + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x24: // ADC HL, BA + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.BA.W.L); + return 16; + case 0x25: // ADC HL, HL + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.HL.W.L); + return 16; + case 0x26: // ADC HL, X + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.X.W.L); + return 16; + case 0x27: // ADC HL, Y + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x28: // SUB HL, BA + MinxCPU.HL.W.L = SUB16(MinxCPU.HL.W.L, MinxCPU.BA.W.L); + return 16; + case 0x29: // SUB HL, HL + MinxCPU.HL.W.L = SUB16(MinxCPU.HL.W.L, MinxCPU.HL.W.L); + return 16; + case 0x2A: // SUB HL, X + MinxCPU.HL.W.L = SUB16(MinxCPU.HL.W.L, MinxCPU.X.W.L); + return 16; + case 0x2B: // SUB HL, Y + MinxCPU.HL.W.L = SUB16(MinxCPU.HL.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x2C: // SBC HL, BA + MinxCPU.HL.W.L = SBC16(MinxCPU.HL.W.L, MinxCPU.BA.W.L); + return 16; + case 0x2D: // SBC HL, HL + MinxCPU.HL.W.L = SBC16(MinxCPU.HL.W.L, MinxCPU.HL.W.L); + return 16; + case 0x2E: // SBC HL, X + MinxCPU.HL.W.L = SBC16(MinxCPU.HL.W.L, MinxCPU.X.W.L); + return 16; + case 0x2F: // SBC HL, Y + MinxCPU.HL.W.L = SBC16(MinxCPU.HL.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x30: // *ADD HL, BA + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.BA.W.L); + return 16; + case 0x31: // *ADD BA, HL + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.HL.W.L); + return 16; + case 0x32: // *ADD BA, X + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.X.W.L); + return 16; + case 0x33: // *ADD BA, Y + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x34: // *ADC HL, BA + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.BA.W.L); + return 16; + case 0x35: // *ADC HL, HL + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.HL.W.L); + return 16; + case 0x36: // *ADC HL, X + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.X.W.L); + return 16; + case 0x37: // *ADC HL, Y + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x38: // CMP HL, BA + SUB16(MinxCPU.HL.W.L, MinxCPU.BA.W.L); + return 16; + case 0x39: // CMP HL, HL + SUB16(MinxCPU.HL.W.L, MinxCPU.HL.W.L); + return 16; + case 0x3A: // CMP HL, X + SUB16(MinxCPU.HL.W.L, MinxCPU.X.W.L); + return 16; + case 0x3B: // CMP HL, Y + SUB16(MinxCPU.HL.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x3C: // *SBC BA, BA + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.BA.W.L); + return 16; + case 0x3D: // *SBC BA, HL + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.HL.W.L); + return 16; + case 0x3E: // *SBC BA, X + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.X.W.L); + return 16; + case 0x3F: // *SBC BA, Y + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, MinxCPU.Y.W.L); + return 16; + + case 0x40: // ADD X, BA + MinxCPU.X.W.L = ADD16(MinxCPU.X.W.L, MinxCPU.BA.W.L); + return 16; + case 0x41: // ADD X, HL + MinxCPU.X.W.L = ADD16(MinxCPU.X.W.L, MinxCPU.HL.W.L); + return 16; + case 0x42: // ADD Y, BA + MinxCPU.Y.W.L = ADD16(MinxCPU.Y.W.L, MinxCPU.BA.W.L); + return 16; + case 0x43: // ADD Y, HL + MinxCPU.Y.W.L = ADD16(MinxCPU.Y.W.L, MinxCPU.HL.W.L); + return 16; + case 0x44: // ADD SP, BA + MinxCPU.SP.W.L = ADD16(MinxCPU.SP.W.L, MinxCPU.BA.W.L); + return 16; + case 0x45: // ADD SP, HL + MinxCPU.SP.W.L = ADD16(MinxCPU.SP.W.L, MinxCPU.HL.W.L); + return 16; + case 0x46: // CRASH + case 0x47: // CRASH + return 16; + + case 0x48: // SUB X, BA + MinxCPU.X.W.L = SUB16(MinxCPU.X.W.L, MinxCPU.BA.W.L); + return 16; + case 0x49: // SUB X, HL + MinxCPU.X.W.L = SUB16(MinxCPU.X.W.L, MinxCPU.HL.W.L); + return 16; + case 0x4A: // SUB Y, BA + MinxCPU.Y.W.L = SUB16(MinxCPU.Y.W.L, MinxCPU.BA.W.L); + return 16; + case 0x4B: // SUB Y, HL + MinxCPU.Y.W.L = SUB16(MinxCPU.Y.W.L, MinxCPU.HL.W.L); + return 16; + case 0x4C: // SUB SP, BA + MinxCPU.SP.W.L = SUB16(MinxCPU.SP.W.L, MinxCPU.BA.W.L); + return 16; + case 0x4D: // SUB SP, HL + MinxCPU.SP.W.L = SUB16(MinxCPU.SP.W.L, MinxCPU.HL.W.L); + return 16; + case 0x4E: // CRASH + case 0x4F: // CRASH + return 16; + + case 0x50: // *ADD X, BA + MinxCPU.X.W.L = ADD16(MinxCPU.X.W.L, MinxCPU.BA.W.L); + return 16; + case 0x51: // *ADD X, HL + MinxCPU.X.W.L = ADD16(MinxCPU.X.W.L, MinxCPU.HL.W.L); + return 16; + case 0x52: // *ADD Y, BA + MinxCPU.Y.W.L = ADD16(MinxCPU.Y.W.L, MinxCPU.BA.W.L); + return 16; + case 0x53: // *ADD Y, HL + MinxCPU.Y.W.L = ADD16(MinxCPU.Y.W.L, MinxCPU.HL.W.L); + return 16; + case 0x54: // *ADD SP, BA + MinxCPU.SP.W.L = ADD16(MinxCPU.SP.W.L, MinxCPU.BA.W.L); + return 16; + case 0x55: // *ADD SP, HL + MinxCPU.SP.W.L = ADD16(MinxCPU.SP.W.L, MinxCPU.HL.W.L); + return 16; + case 0x56: // CRASH + case 0x57: // CRASH + return 16; + + case 0x58: // *SUB X, BA + MinxCPU.X.W.L = SUB16(MinxCPU.X.W.L, MinxCPU.BA.W.L); + return 16; + case 0x59: // *SUB X, HL + MinxCPU.X.W.L = SUB16(MinxCPU.X.W.L, MinxCPU.HL.W.L); + return 16; + case 0x5A: // *SUB Y, BA + MinxCPU.Y.W.L = SUB16(MinxCPU.Y.W.L, MinxCPU.BA.W.L); + return 16; + case 0x5B: // *SUB Y, HL + MinxCPU.Y.W.L = SUB16(MinxCPU.Y.W.L, MinxCPU.HL.W.L); + return 16; + case 0x5C: // CMP SP, BA + SUB16(MinxCPU.SP.W.L, MinxCPU.BA.W.L); + return 16; + case 0x5D: // CMP SP, HL + SUB16(MinxCPU.SP.W.L, MinxCPU.HL.W.L); + return 16; + case 0x5E: // CRASH + case 0x5F: // CRASH + return 16; + + case 0x60: // ADC BA, #nnnn + I16 = Fetch16(); + MinxCPU.BA.W.L = ADC16(MinxCPU.BA.W.L, I16); + return 16; + case 0x61: // ADC HL, #nnnn + I16 = Fetch16(); + MinxCPU.HL.W.L = ADC16(MinxCPU.HL.W.L, I16); + return 16; + case 0x62: // SBC BA, #nnnn + I16 = Fetch16(); + MinxCPU.BA.W.L = SBC16(MinxCPU.BA.W.L, I16); + return 16; + case 0x63: // SBC HL, #nnnn + I16 = Fetch16(); + MinxCPU.HL.W.L = SBC16(MinxCPU.HL.W.L, I16); + return 16; + + case 0x64: // UNSTABLE + case 0x65: // UNSTABLE + case 0x66: // UNSTABLE + case 0x67: // UNSTABLE + return 16; + + case 0x68: // ADD SP, #nnnn + I16 = Fetch16(); + MinxCPU.SP.W.L = ADD16(MinxCPU.SP.W.L, I16); + return 16; + + case 0x6A: // SUB SP, #nnnn + I16 = Fetch16(); + MinxCPU.SP.W.L = SUB16(MinxCPU.SP.W.L, I16); + return 16; + case 0x69: // UNSTABLE + case 0x6B: // UNSTABLE + case 0x6D: // UNSTABLE + case 0x6F: // UNSTABLE + return 16; + + case 0x6C: // CMP SP, #nnnn + I16 = Fetch16(); + SUB16(MinxCPU.SP.W.L, I16); + return 16; + + case 0x6E: // MOV SP, #nnnn + I16 = Fetch16(); + MinxCPU.SP.W.L = I16; + return 16; + + case 0x70: // MOV BA, [SP+#ss] + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, I16++); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, I16); + return 24; + case 0x71: // MOV HL, [SP+#ss] + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, I16++); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, I16); + return 24; + case 0x72: // MOV X, [SP+#ss] + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU.X.B.L = MinxCPU_OnRead(1, I16++); + MinxCPU.X.B.H = MinxCPU_OnRead(1, I16); + return 24; + case 0x73: // MOV Y, [SP+#ss] + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU.Y.B.L = MinxCPU_OnRead(1, I16++); + MinxCPU.Y.B.H = MinxCPU_OnRead(1, I16); + return 24; + + case 0x74: // MOV [SP+#ss], BA + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, I16++, MinxCPU.BA.B.L); + MinxCPU_OnWrite(1, I16, MinxCPU.BA.B.H); + return 24; + case 0x75: // MOV [SP+#ss], HL + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, I16++, MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, I16, MinxCPU.HL.B.H); + return 24; + case 0x76: // MOV [SP+#ss], X + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, I16++, MinxCPU.X.B.L); + MinxCPU_OnWrite(1, I16, MinxCPU.X.B.H); + return 24; + case 0x77: // MOV [SP+#ss], Y + I8A = Fetch8(); + I16 = MinxCPU.SP.W.L + S8_TO_16(I8A); + MinxCPU_OnWrite(1, I16++, MinxCPU.Y.B.L); + MinxCPU_OnWrite(1, I16, MinxCPU.Y.B.H); + return 24; + + case 0x78: // MOV SP, [#nnnn] + I16 = Fetch16(); + MinxCPU.SP.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.SP.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 24; + + case 0x79: // ??? #nn + case 0x7A: // ??? #nn + case 0x7B: // ??? #nn + return MinxCPU_ExecSPCF(); + + case 0x7C: // MOV [#nnnn], SP + I16 = Fetch16(); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.SP.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.SP.B.H); + return 24; + + case 0x7D: case 0x7E: case 0x7F: // ??? #nn + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8A: case 0x8B: + case 0x8C: case 0x8D: case 0x8E: case 0x8F: + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9A: case 0x9B: + case 0x9C: case 0x9D: case 0x9E: case 0x9F: + case 0xA0: case 0xA1: case 0xA2: case 0xA3: + case 0xA4: case 0xA5: case 0xA6: case 0xA7: + case 0xA8: case 0xA9: case 0xAA: case 0xAB: + case 0xAC: case 0xAD: case 0xAE: case 0xAF: + return MinxCPU_ExecSPCF(); + + case 0xB0: // PUSH A + PUSH(MinxCPU.BA.B.L); + return 12; + case 0xB1: // PUSH B + PUSH(MinxCPU.BA.B.H); + return 12; + case 0xB2: // PUSH L + PUSH(MinxCPU.HL.B.L); + return 12; + case 0xB3: // PUSH H + PUSH(MinxCPU.HL.B.H); + return 12; + + case 0xB4: // POP A + MinxCPU.BA.B.L = POP(); + return 12; + case 0xB5: // POP B + MinxCPU.BA.B.H = POP(); + return 12; + case 0xB6: // POP L + MinxCPU.HL.B.L = POP(); + return 12; + case 0xB7: // POP H + MinxCPU.HL.B.H = POP(); + return 12; + case 0xB8: // PUSHA + PUSH(MinxCPU.BA.B.H); + PUSH(MinxCPU.BA.B.L); + PUSH(MinxCPU.HL.B.H); + PUSH(MinxCPU.HL.B.L); + PUSH(MinxCPU.X.B.H); + PUSH(MinxCPU.X.B.L); + PUSH(MinxCPU.Y.B.H); + PUSH(MinxCPU.Y.B.L); + PUSH(MinxCPU.N.B.H); + return 48; + case 0xB9: // PUSHAX + PUSH(MinxCPU.BA.B.H); + PUSH(MinxCPU.BA.B.L); + PUSH(MinxCPU.HL.B.H); + PUSH(MinxCPU.HL.B.L); + PUSH(MinxCPU.X.B.H); + PUSH(MinxCPU.X.B.L); + PUSH(MinxCPU.Y.B.H); + PUSH(MinxCPU.Y.B.L); + PUSH(MinxCPU.N.B.H); + PUSH(MinxCPU.HL.B.I); + PUSH(MinxCPU.X.B.I); + PUSH(MinxCPU.Y.B.I); + return 60; + + case 0xBA: case 0xBB: // ??? #n + return MinxCPU_ExecSPCF(); + + case 0xBC: // POPA + MinxCPU.N.B.H = POP(); + MinxCPU.Y.B.L = POP(); + MinxCPU.Y.B.H = POP(); + MinxCPU.X.B.L = POP(); + MinxCPU.X.B.H = POP(); + MinxCPU.HL.B.L = POP(); + MinxCPU.HL.B.H = POP(); + MinxCPU.BA.B.L = POP(); + MinxCPU.BA.B.H = POP(); + return 44; + + case 0xBD: // POPAX + MinxCPU.Y.B.I = POP(); + MinxCPU.X.B.I = POP(); + MinxCPU.HL.B.I = POP(); + MinxCPU.N.B.I = MinxCPU.HL.B.I; + MinxCPU.N.B.H = POP(); + MinxCPU.Y.B.L = POP(); + MinxCPU.Y.B.H = POP(); + MinxCPU.X.B.L = POP(); + MinxCPU.X.B.H = POP(); + MinxCPU.HL.B.L = POP(); + MinxCPU.HL.B.H = POP(); + MinxCPU.BA.B.L = POP(); + MinxCPU.BA.B.H = POP(); + return 56; + + case 0xBE: case 0xBF: // ??? #n + return MinxCPU_ExecSPCF(); + + case 0xC0: // MOV BA, [HL] + I16 = MinxCPU.HL.W.L; + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + case 0xC1: // MOV HL, [HL] + I16 = MinxCPU.HL.W.L; + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + case 0xC2: // MOV X, [HL] + I16 = MinxCPU.HL.W.L; + MinxCPU.X.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.X.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + case 0xC3: // MOV Y, [HL] + I16 = MinxCPU.HL.W.L; + MinxCPU.Y.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.Y.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + + case 0xC4: // MOV [HL], BA + I16 = MinxCPU.HL.W.L; + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.BA.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.BA.B.H); + return 20; + case 0xC5: // MOV [HL], HL + I16 = MinxCPU.HL.W.L; + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.HL.B.H); + return 20; + case 0xC6: // MOV [HL], X + I16 = MinxCPU.HL.W.L; + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.X.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.X.B.H); + return 20; + case 0xC7: // MOV [HL], Y + I16 = MinxCPU.HL.W.L; + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.Y.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.Y.B.H); + return 20; + + case 0xC8: case 0xC9: case 0xCA: case 0xCB: // MOV B, V + case 0xCC: case 0xCD: case 0xCE: case 0xCF: + MinxCPU.BA.B.H = MinxCPU.PC.B.I; + return 12; + + case 0xD0: // MOV BA, [X] + I16 = MinxCPU.X.W.L; + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16++); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 20; + case 0xD1: // MOV HL, [X] + I16 = MinxCPU.X.W.L; + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16++); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 20; + case 0xD2: // MOV X, [X] + I16 = MinxCPU.X.W.L; + MinxCPU.X.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16++); + MinxCPU.X.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 20; + case 0xD3: // MOV Y, [X] + I16 = MinxCPU.X.W.L; + MinxCPU.Y.B.L = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16++); + MinxCPU.Y.B.H = MinxCPU_OnRead(1, (MinxCPU.X.B.I << 16) | I16); + return 20; + + case 0xD4: // MOV [X], BA + I16 = MinxCPU.X.W.L; + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16++, MinxCPU.BA.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.BA.B.H); + return 20; + case 0xD5: // MOV [X], HL + I16 = MinxCPU.X.W.L; + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16++, MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.HL.B.H); + return 20; + case 0xD6: // MOV [X], X + I16 = MinxCPU.X.W.L; + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16++, MinxCPU.X.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.X.B.H); + return 20; + case 0xD7: // MOV [X], Y + I16 = MinxCPU.X.W.L; + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16++, MinxCPU.Y.B.L); + MinxCPU_OnWrite(1, (MinxCPU.X.B.I << 16) | I16, MinxCPU.Y.B.H); + return 20; + + case 0xD8: // MOV BA, [Y] + I16 = MinxCPU.Y.W.L; + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16++); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 20; + case 0xD9: // MOV HL, [Y] + I16 = MinxCPU.Y.W.L; + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16++); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 20; + case 0xDA: // MOV X, [Y] + I16 = MinxCPU.Y.W.L; + MinxCPU.X.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16++); + MinxCPU.X.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 20; + case 0xDB: // MOV Y, [Y] + I16 = MinxCPU.Y.W.L; + MinxCPU.Y.B.L = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16++); + MinxCPU.Y.B.H = MinxCPU_OnRead(1, (MinxCPU.Y.B.I << 16) | I16); + return 20; + + case 0xDC: // MOV [Y], BA + I16 = MinxCPU.Y.W.L; + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16++, MinxCPU.BA.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.BA.B.H); + return 20; + case 0xDD: // MOV [Y], HL + I16 = MinxCPU.Y.W.L; + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16++, MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.HL.B.H); + return 20; + case 0xDE: // MOV [Y], X + I16 = MinxCPU.Y.W.L; + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16++, MinxCPU.X.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.X.B.H); + return 20; + case 0xDF: // MOV [Y], Y + I16 = MinxCPU.Y.W.L; + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16++, MinxCPU.Y.B.L); + MinxCPU_OnWrite(1, (MinxCPU.Y.B.I << 16) | I16, MinxCPU.Y.B.H); + return 20; + + case 0xE0: // MOV BA, BA + return 8; + case 0xE1: // MOV BA, HL + MinxCPU.BA.W.L = MinxCPU.HL.W.L; + return 8; + case 0xE2: // MOV BA, X + MinxCPU.BA.W.L = MinxCPU.X.W.L; + return 8; + case 0xE3: // MOV BA, Y + MinxCPU.BA.W.L = MinxCPU.Y.W.L; + return 8; + + case 0xE4: // MOV HL, BA + MinxCPU.HL.W.L = MinxCPU.BA.W.L; + return 8; + case 0xE5: // MOV HL, HL + return 8; + case 0xE6: // MOV HL, X + MinxCPU.HL.W.L = MinxCPU.X.W.L; + return 8; + case 0xE7: // MOV HL, Y + MinxCPU.HL.W.L = MinxCPU.Y.W.L; + return 8; + + case 0xE8: // MOV X, BA + MinxCPU.X.W.L = MinxCPU.BA.W.L; + return 8; + case 0xE9: // MOV X, HL + MinxCPU.X.W.L = MinxCPU.HL.W.L; + return 8; + case 0xEA: // MOV X, X + return 8; + case 0xEB: // MOV X, Y + MinxCPU.X.W.L = MinxCPU.Y.W.L; + return 8; + + case 0xEC: // MOV Y, BA + MinxCPU.Y.W.L = MinxCPU.BA.W.L; + return 8; + case 0xED: // MOV Y, HL + MinxCPU.Y.W.L = MinxCPU.HL.W.L; + return 8; + case 0xEE: // MOV Y, X + MinxCPU.Y.W.L = MinxCPU.X.W.L; + return 8; + case 0xEF: // MOV Y, Y + return 8; + + case 0xF0: // MOV SP, BA + MinxCPU.SP.W.L = MinxCPU.BA.W.L; + return 8; + case 0xF1: // MOV SP, HL + MinxCPU.SP.W.L = MinxCPU.HL.W.L; + return 8; + case 0xF2: // MOV SP, X + MinxCPU.SP.W.L = MinxCPU.X.W.L; + return 8; + case 0xF3: // MOV SP, Y + MinxCPU.SP.W.L = MinxCPU.Y.W.L; + return 8; + + case 0xF4: // MOV HL, SP + MinxCPU.HL.W.L = MinxCPU.SP.W.L; + return 8; + case 0xF5: // MOV HL, PC + MinxCPU.HL.W.L = MinxCPU.PC.W.L; + return 8; + case 0xF6: // ??? X + MinxCPU.X.B.H = MinxCPU.PC.B.I; + return 12; + case 0xF7: // ??? Y + MinxCPU.Y.B.H = MinxCPU.PC.B.I; + return 12; + + case 0xF8: // MOV BA, SP + MinxCPU.BA.W.L = MinxCPU.SP.W.L; + return 8; + case 0xF9: // MOV BA, PC + MinxCPU.BA.W.L = MinxCPU.PC.W.L; + return 8; + + case 0xFA: // MOV X, SP + MinxCPU.X.W.L = MinxCPU.SP.W.L; + return 8; + + case 0xFB: // NOTHING + case 0xFC: // NOTHING + return 12; + case 0xFD: // MOV A, E + MinxCPU.BA.B.L = MinxCPU.E; + return 12; + + case 0xFE: // MOV Y, SP + MinxCPU.Y.W.L = MinxCPU.SP.W.L; + return 8; + + case 0xFF: // NOTHING + return 64; + + default: + break; + } + + return 4; +} diff --git a/pm/src/core/MinxCPU_SP.c b/pm/src/core/MinxCPU_SP.c new file mode 100644 index 0000000..79a2237 --- /dev/null +++ b/pm/src/core/MinxCPU_SP.c @@ -0,0 +1,244 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "MinxCPU.h" + +int MinxCPU_ExecSPCE(void) +{ + // Read IR + MinxCPU.IR = Fetch8(); + + return 64; +} + +int MinxCPU_ExecSPCF(void) +{ + // Read IR + MinxCPU.IR = Fetch8(); + + // Process instruction + switch(MinxCPU.IR) { + case 0x00: case 0x01: case 0x02: case 0x03: // Decrement BA + MinxCPU.BA.W.L = DEC16(MinxCPU.BA.W.L); + return 16; + case 0x04: case 0x05: case 0x06: case 0x07: // Decrement BA if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.BA.W.L = DEC16(MinxCPU.BA.W.L); + return 16; + case 0x08: case 0x09: case 0x0A: case 0x0B: // Increment BA + MinxCPU.BA.W.L = INC16(MinxCPU.BA.W.L); + return 16; + case 0x0C: case 0x0D: case 0x0E: case 0x0F: // Increment BA if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.BA.W.L = INC16(MinxCPU.BA.W.L); + return 16; + case 0x10: case 0x11: case 0x12: case 0x13: // Decrement BA + MinxCPU.BA.W.L = DEC16(MinxCPU.BA.W.L); + return 16; + case 0x14: case 0x15: case 0x16: case 0x17: // Decrement BA if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.BA.W.L = DEC16(MinxCPU.BA.W.L); + return 16; + case 0x18: case 0x19: case 0x1A: case 0x1B: // Increment BA (Doesn't save result!!) + INC16(MinxCPU.BA.W.L); + return 16; + case 0x1C: case 0x1D: case 0x1E: case 0x1F: // Increment BA if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.BA.W.L = INC16(MinxCPU.BA.W.L); + return 16; + + case 0x20: case 0x21: case 0x22: case 0x23: // Decrement HL + MinxCPU.HL.W.L = DEC16(MinxCPU.HL.W.L); + return 16; + case 0x24: case 0x25: case 0x26: case 0x27: // Decrement HL if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.HL.W.L = DEC16(MinxCPU.HL.W.L); + return 16; + case 0x28: case 0x29: case 0x2A: case 0x2B: // Increment HL + MinxCPU.HL.W.L = INC16(MinxCPU.HL.W.L); + return 16; + case 0x2C: case 0x2D: case 0x2E: case 0x2F: // Increment HL if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.HL.W.L = INC16(MinxCPU.HL.W.L); + return 16; + case 0x30: case 0x31: case 0x32: case 0x33: // Decrement HL + MinxCPU.HL.W.L = DEC16(MinxCPU.HL.W.L); + return 16; + case 0x34: case 0x35: case 0x36: case 0x37: // Decrement HL if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.HL.W.L = DEC16(MinxCPU.HL.W.L); + return 16; + case 0x38: case 0x39: case 0x3A: case 0x3B: // Increment HL (Doesn't save result!!) + INC16(MinxCPU.HL.W.L); + return 16; + case 0x3C: case 0x3D: case 0x3E: case 0x3F: // Increment HL if Carry = 0 + if (!(MinxCPU.F & MINX_FLAG_CARRY)) MinxCPU.HL.W.L = INC16(MinxCPU.HL.W.L); + return 16; + + case 0x40: case 0x41: // Decrement X + MinxCPU.X.W.L = DEC16(MinxCPU.X.W.L); + return 16; + case 0x42: case 0x43: // Decrement Y + MinxCPU.X.W.L = DEC16(MinxCPU.X.W.L); + return 16; + case 0x44: case 0x45: // Decrement SP + MinxCPU.SP.W.L = DEC16(MinxCPU.SP.W.L); + return 16; + case 0x46: case 0x47: // CRASH + return 16; + + case 0x48: case 0x49: // Increment X + MinxCPU.X.W.L = INC16(MinxCPU.X.W.L); + return 16; + case 0x4A: case 0x4B: // Increment Y + MinxCPU.X.W.L = INC16(MinxCPU.X.W.L); + return 16; + case 0x4C: case 0x4D: // Increment SP + MinxCPU.SP.W.L = INC16(MinxCPU.SP.W.L); + return 16; + case 0x4E: case 0x4F: // CRASH + case 0x56: case 0x57: // CRASH + case 0x5E: case 0x5F: // CRASH + case 0x60: case 0x61: case 0x62: case 0x63: // CRASH + case 0x64: case 0x65: case 0x66: case 0x67: + case 0x68: case 0x69: case 0x6A: case 0x6B: + case 0x6C: case 0x6D: case 0x6E: case 0x6F: + return 16; + + case 0x50: case 0x51: // Decrement X + MinxCPU.X.W.L = DEC16(MinxCPU.X.W.L); + return 16; + case 0x52: case 0x53: // Decrement Y + MinxCPU.X.W.L = DEC16(MinxCPU.X.W.L); + return 16; + case 0x54: case 0x55: // Decrement SP + MinxCPU.SP.W.L = DEC16(MinxCPU.SP.W.L); + return 16; + + case 0x58: case 0x59: // Increment X + MinxCPU.X.W.L = INC16(MinxCPU.X.W.L); + return 16; + case 0x5A: case 0x5B: // Increment Y + MinxCPU.X.W.L = INC16(MinxCPU.X.W.L); + return 16; + case 0x5C: case 0x5D: // Increment SP + MinxCPU.SP.W.L = INC16(MinxCPU.SP.W.L); + return 16; + + + case 0x70: // BA = (0x4D << 8) | V + MinxCPU.BA.W.L = 0x4D00 | MinxCPU.PC.B.I; + return 24; + case 0x71: // HL = (0x4D << 8) | V + MinxCPU.HL.W.L = 0x4D00 | MinxCPU.PC.B.I; + return 24; + case 0x72: // X = (0x4D << 8) | V + MinxCPU.X.W.L = 0x4D00 | MinxCPU.PC.B.I; + return 24; + case 0x73: // Y = (0x4D << 8) | V + MinxCPU.Y.W.L = 0x4D00 | MinxCPU.PC.B.I; + return 24; + + case 0x74: case 0x75: case 0x76: case 0x77: // NOTHING + return 24; + + case 0x78: case 0x79: case 0x7A: case 0x7B: // CRASH + case 0x7C: case 0x7D: case 0x7E: case 0x7F: + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8A: case 0x8B: + case 0x8C: case 0x8D: case 0x8E: case 0x8F: + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9A: case 0x9B: + case 0x9C: case 0x9D: case 0x9E: case 0x9F: + case 0xA0: case 0xA1: case 0xA2: case 0xA3: + case 0xA4: case 0xA5: case 0xA6: case 0xA7: + case 0xA8: case 0xA9: case 0xAA: case 0xAB: + case 0xAC: case 0xAD: case 0xAE: case 0xAF: + return 24; + + case 0xB0: case 0xB1: case 0xB2: case 0xB3: // NOTHING + return 12; + + case 0xB4: case 0xB5: case 0xB6: case 0xB7: // CRASH + case 0xB8: case 0xB9: case 0xBA: case 0xBB: + case 0xBC: case 0xBD: case 0xBE: case 0xBF: + return 12; + + case 0xC0: // BA = (0x20 << 8) | V + MinxCPU.BA.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xC1: // HL = (0x20 << 8) | V + MinxCPU.HL.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xC2: // X = (0x20 << 8) | V + MinxCPU.X.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xC3: // Y = (0x20 << 8) | V + MinxCPU.Y.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + + case 0xC4: case 0xC5: case 0xC6: case 0xC7: // NOTHING + return 20; + + case 0xC8: case 0xC9: case 0xCA: case 0xCB: // CRASH + case 0xCC: case 0xCD: case 0xCE: case 0xCF: + return 20; + + case 0xD0: // BA = (0x20 << 8) | V + MinxCPU.BA.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xD1: // HL = (0x20 << 8) | V + MinxCPU.HL.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xD2: // X = (0x20 << 8) | V + MinxCPU.X.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xD3: // Y = (0x00 << 8) | V ? (EH!?) + MinxCPU.Y.W.L = 0x0000 | MinxCPU.PC.B.I; + return 20; + + case 0xD4: case 0xD5: case 0xD6: case 0xD7: // NOTHING + return 20; + + case 0xD8: // BA = (0x20 << 8) | V + MinxCPU.BA.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xD9: // HL = (0x20 << 8) | V + MinxCPU.HL.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xDA: // X = (0x20 << 8) | V + MinxCPU.X.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + case 0xDB: // Y = (0x20 << 8) | V + MinxCPU.Y.W.L = 0x2000 | MinxCPU.PC.B.I; + return 20; + + case 0xDC: case 0xDD: case 0xDE: case 0xDF: // NOTHING + return 20; + + case 0xE0: case 0xE1: case 0xE2: case 0xE3: // CRASH + case 0xE4: case 0xE5: case 0xE6: case 0xE7: + case 0xE8: case 0xE9: case 0xEA: case 0xEB: + case 0xEC: case 0xED: case 0xEE: case 0xEF: + case 0xF0: case 0xF1: case 0xF2: case 0xF3: + case 0xF4: case 0xF5: case 0xF6: case 0xF7: + case 0xF8: case 0xF9: case 0xFA: case 0xFB: + case 0xFC: case 0xFD: case 0xFE: case 0xFF: + return 24; + + default: + break; + } + + return 64; +} diff --git a/pm/src/core/MinxCPU_XX.c b/pm/src/core/MinxCPU_XX.c new file mode 100644 index 0000000..6bdc1db --- /dev/null +++ b/pm/src/core/MinxCPU_XX.c @@ -0,0 +1,1059 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +// Note: Any write to MinxCPU.HL.B.I needs to be reflected into MinxCPU.N.B.I + +#include "MinxCPU.h" + +int MinxCPU_Exec(void) +{ + uint8_t I8A, I8B; + uint16_t I16; + + // Shift U + if (MinxCPU.Shift_U) { + MinxCPU.U1 = MinxCPU.U2; + MinxCPU.U2 = MinxCPU.PC.B.I; + MinxCPU.Shift_U--; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); + } + + // Check HALT or STOP status + if (MinxCPU.Status != MINX_STATUS_NORMAL) { + if (MinxCPU.Status == MINX_STATUS_IRQ) { + MinxCPU.Status = MINX_STATUS_NORMAL; // Return to normal + CALLI(MinxCPU.IRQ_Vector); // Jump to IRQ vector + return 20; + } else { + return 8; // Cause short NOPs + } + } + + // Read IR + MinxCPU.IR = Fetch8(); + + // Process instruction + switch(MinxCPU.IR) { + + case 0x00: // ADD A, A + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x01: // ADD A, B + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x02: // ADD A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x03: // ADD A, [HL] + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x04: // ADD A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x05: // ADD A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x06: // ADD A, [X] + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x07: // ADD A, [Y] + MinxCPU.BA.B.L = ADD8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x08: // ADC A, A + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x09: // ADC A, B + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x0A: // ADC A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x0B: // ADC A, [HL] + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x0C: // ADC A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x0D: // ADC A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x0E: // ADC A, [X] + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x0F: // ADC A, [Y] + MinxCPU.BA.B.L = ADC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x10: // SUB A, A + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x11: // SUB A, B + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x12: // SUB A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x13: // SUB A, [HL] + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x14: // SUB A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x15: // SUB A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x16: // SUB A, [X] + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x17: // SUB A, [Y] + MinxCPU.BA.B.L = SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x18: // SBC A, A + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x19: // SBC A, B + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x1A: // SBC A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x1B: // SBC A, [HL] + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x1C: // SBC A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x1D: // SBC A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x1E: // SBC A, [X] + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x1F: // SBC A, [Y] + MinxCPU.BA.B.L = SBC8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x20: // AND A, A + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x21: // AND A, B + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x22: // AND A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x23: // AND A, [HL] + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x24: // AND A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x25: // AND A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x26: // AND A, [X] + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x27: // AND A, [Y] + MinxCPU.BA.B.L = AND8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x28: // OR A, A + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x29: // OR A, B + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x2A: // OR A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x2B: // OR A, [HL] + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x2C: // OR A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x2D: // OR A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x2E: // OR A, [X] + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x2F: // OR A, [Y] + MinxCPU.BA.B.L = OR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x30: // CMP A, A + SUB8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x31: // CMP A, B + SUB8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x32: // CMP A, #nn + I8A = Fetch8(); + SUB8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x33: // CMP A, [HL] + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x34: // CMP A, [N+#nn] + I8A = Fetch8(); + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x35: // CMP A, [#nnnn] + I16 = Fetch16(); + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x36: // CMP A, [X] + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x37: // CMP A, [Y] + SUB8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x38: // XOR A, A + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU.BA.B.L); + return 8; + case 0x39: // XOR A, B + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x3A: // XOR A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x3B: // XOR A, [HL] + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 8; + case 0x3C: // XOR A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 12; + case 0x3D: // XOR A, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16)); + return 16; + case 0x3E: // XOR A, [X] + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 8; + case 0x3F: // XOR A, [Y] + MinxCPU.BA.B.L = XOR8(MinxCPU.BA.B.L, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 8; + + case 0x40: // MOV A, A + return 4; + case 0x41: // MOV A, B + MinxCPU.BA.B.L = MinxCPU.BA.B.H; + return 4; + case 0x42: // MOV A, L + MinxCPU.BA.B.L = MinxCPU.HL.B.L; + return 4; + case 0x43: // MOV A, H + MinxCPU.BA.B.L = MinxCPU.HL.B.H; + return 4; + case 0x44: // MOV A, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, MinxCPU.N.D + I8A); + return 12; + case 0x45: // MOV A, [HL] + MinxCPU.BA.B.L = MinxCPU_OnRead(1, MinxCPU.HL.D); + return 8; + case 0x46: // MOV A, [X] + MinxCPU.BA.B.L = MinxCPU_OnRead(1, MinxCPU.X.D); + return 8; + case 0x47: // MOV A, [Y] + MinxCPU.BA.B.L = MinxCPU_OnRead(1, MinxCPU.Y.D); + return 8; + + case 0x48: // MOV B, A + MinxCPU.BA.B.H = MinxCPU.BA.B.L; + return 4; + case 0x49: // MOV B, B + return 4; + case 0x4A: // MOV B, L + MinxCPU.BA.B.H = MinxCPU.HL.B.L; + return 4; + case 0x4B: // MOV B, H + MinxCPU.BA.B.H = MinxCPU.HL.B.H; + return 4; + case 0x4C: // MOV B, [N+#nn] + I8A = Fetch8(); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, MinxCPU.N.D + I8A); + return 12; + case 0x4D: // MOV B, [HL] + MinxCPU.BA.B.H = MinxCPU_OnRead(1, MinxCPU.HL.D); + return 8; + case 0x4E: // MOV B, [X] + MinxCPU.BA.B.H = MinxCPU_OnRead(1, MinxCPU.X.D); + return 8; + case 0x4F: // MOV B, [Y] + MinxCPU.BA.B.H = MinxCPU_OnRead(1, MinxCPU.Y.D); + return 8; + + case 0x50: // MOV L, A + MinxCPU.HL.B.L = MinxCPU.BA.B.L; + return 4; + case 0x51: // MOV L, B + MinxCPU.HL.B.L = MinxCPU.BA.B.H; + return 4; + case 0x52: // MOV L, L + return 4; + case 0x53: // MOV L, H + MinxCPU.HL.B.L = MinxCPU.HL.B.H; + return 4; + case 0x54: // MOV L, [N+#nn] + I8A = Fetch8(); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, MinxCPU.N.D + I8A); + return 12; + case 0x55: // MOV L, [HL] + MinxCPU.HL.B.L = MinxCPU_OnRead(1, MinxCPU.HL.D); + return 8; + case 0x56: // MOV L, [X] + MinxCPU.HL.B.L = MinxCPU_OnRead(1, MinxCPU.X.D); + return 8; + case 0x57: // MOV L, [Y] + MinxCPU.HL.B.L = MinxCPU_OnRead(1, MinxCPU.Y.D); + return 8; + + case 0x58: // MOV H, A + MinxCPU.HL.B.H = MinxCPU.BA.B.L; + return 4; + case 0x59: // MOV H, B + MinxCPU.HL.B.H = MinxCPU.BA.B.H; + return 4; + case 0x5A: // MOV H, L + MinxCPU.HL.B.H = MinxCPU.HL.B.L; + return 4; + case 0x5B: // MOV H, H + return 4; + case 0x5C: // MOV H, [N+#nn] + I8A = Fetch8(); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, MinxCPU.N.D + I8A); + return 12; + case 0x5D: // MOV H, [HL] + MinxCPU.HL.B.H = MinxCPU_OnRead(1, MinxCPU.HL.D); + return 8; + case 0x5E: // MOV H, [X] + MinxCPU.HL.B.H = MinxCPU_OnRead(1, MinxCPU.X.D); + return 8; + case 0x5F: // MOV H, [Y] + MinxCPU.HL.B.H = MinxCPU_OnRead(1, MinxCPU.Y.D); + return 8; + + case 0x60: // MOV [X], A + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU.BA.B.L); + return 8; + case 0x61: // MOV [X], B + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU.BA.B.H); + return 8; + case 0x62: // MOV [X], L + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU.HL.B.L); + return 8; + case 0x63: // MOV [X], H + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU.HL.B.H); + return 8; + case 0x64: // MOV [X], [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 16; + case 0x65: // MOV [X], [HL] + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 12; + case 0x66: // MOV [X], [X] + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 12; + case 0x67: // MOV [X], [Y] + MinxCPU_OnWrite(1, MinxCPU.X.D, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 12; + + case 0x68: // MOV [HL], A + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU.BA.B.L); + return 8; + case 0x69: // MOV [HL], B + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU.BA.B.H); + return 8; + case 0x6A: // MOV [HL], L + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU.HL.B.L); + return 8; + case 0x6B: // MOV [HL], H + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU.HL.B.H); + return 8; + case 0x6C: // MOV [HL], [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 16; + case 0x6D: // MOV [HL], [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 12; + case 0x6E: // MOV [HL], [X] + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 12; + case 0x6F: // MOV [HL], [Y] + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 12; + + case 0x70: // MOV [Y], A + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU.BA.B.L); + return 8; + case 0x71: // MOV [Y], B + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU.BA.B.H); + return 8; + case 0x72: // MOV [Y], L + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU.HL.B.L); + return 8; + case 0x73: // MOV [Y], H + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU.HL.B.H); + return 8; + case 0x74: // MOV [Y], [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, MinxCPU.N.D + I8A)); + return 16; + case 0x75: // MOV [Y], [HL] + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 12; + case 0x76: // MOV [Y], [X] + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 12; + case 0x77: // MOV [Y], [Y] + MinxCPU_OnWrite(1, MinxCPU.Y.D, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 12; + + case 0x78: // MOV [N+#nn], A + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, MinxCPU.BA.B.L); + return 8; + case 0x79: // MOV [N+#nn], B + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, MinxCPU.BA.B.H); + return 8; + case 0x7A: // MOV [N+#nn], L + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, MinxCPU.HL.B.L); + return 8; + case 0x7B: // MOV [N+#nn], H + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, MinxCPU.HL.B.H); + return 8; + case 0x7C: // NOTHING #nn + I8A = Fetch8(); + return 64; + case 0x7D: // MOV [N+#nn], [HL] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, MinxCPU_OnRead(1, MinxCPU.HL.D)); + return 16; + case 0x7E: // MOV [N+#nn], [X] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, MinxCPU_OnRead(1, MinxCPU.X.D)); + return 16; + case 0x7F: // MOV [N+#nn], [Y] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, MinxCPU_OnRead(1, MinxCPU.Y.D)); + return 16; + + case 0x80: // INC A + MinxCPU.BA.B.L = INC8(MinxCPU.BA.B.L); + return 8; + case 0x81: // INC B + MinxCPU.BA.B.H = INC8(MinxCPU.BA.B.H); + return 8; + case 0x82: // INC L + MinxCPU.HL.B.L = INC8(MinxCPU.HL.B.L); + return 8; + case 0x83: // INC H + MinxCPU.HL.B.H = INC8(MinxCPU.HL.B.H); + return 8; + case 0x84: // INC N + MinxCPU.N.B.H = INC8(MinxCPU.N.B.H); + return 8; + case 0x85: // INC [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, INC8(MinxCPU_OnRead(1, MinxCPU.N.D + I8A))); + return 16; + case 0x86: // INC [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, INC8(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 12; + case 0x87: // INC SP + MinxCPU.SP.W.L = INC16(MinxCPU.SP.W.L); + return 8; + + case 0x88: // DEC A + MinxCPU.BA.B.L = DEC8(MinxCPU.BA.B.L); + return 8; + case 0x89: // DEC B + MinxCPU.BA.B.H = DEC8(MinxCPU.BA.B.H); + return 8; + case 0x8A: // DEC L + MinxCPU.HL.B.L = DEC8(MinxCPU.HL.B.L); + return 8; + case 0x8B: // DEC H + MinxCPU.HL.B.H = DEC8(MinxCPU.HL.B.H); + return 8; + case 0x8C: // DEC N + MinxCPU.N.B.H = DEC8(MinxCPU.N.B.H); + return 8; + case 0x8D: // DEC [N+#nn] + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, DEC8(MinxCPU_OnRead(1, MinxCPU.N.D + I8A))); + return 16; + case 0x8E: // DEC [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, DEC8(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 12; + case 0x8F: // DEC SP + MinxCPU.SP.W.L = DEC16(MinxCPU.SP.W.L); + return 8; + + case 0x90: // INC BA + MinxCPU.BA.W.L = INC16(MinxCPU.BA.W.L); + return 8; + case 0x91: // INC HL + MinxCPU.HL.W.L = INC16(MinxCPU.HL.W.L); + return 8; + case 0x92: // INC X + MinxCPU.X.W.L = INC16(MinxCPU.X.W.L); + return 8; + case 0x93: // INC Y + MinxCPU.Y.W.L = INC16(MinxCPU.Y.W.L); + return 8; + + case 0x94: // TST A, B + AND8(MinxCPU.BA.B.L, MinxCPU.BA.B.H); + return 8; + case 0x95: // TST [HL], #nn + I8A = Fetch8(); + AND8(MinxCPU_OnRead(1, MinxCPU.HL.D), I8A); + return 12; + case 0x96: // TST A, #nn + I8A = Fetch8(); + AND8(MinxCPU.BA.B.L, I8A); + return 8; + case 0x97: // TST B, #nn + I8A = Fetch8(); + AND8(MinxCPU.BA.B.H, I8A); + return 8; + + case 0x98: // DEC BA + MinxCPU.BA.W.L = DEC16(MinxCPU.BA.W.L); + return 8; + case 0x99: // DEC HL + MinxCPU.HL.W.L = DEC16(MinxCPU.HL.W.L); + return 8; + case 0x9A: // DEC X + MinxCPU.X.W.L = DEC16(MinxCPU.X.W.L); + return 8; + case 0x9B: // DEC Y + MinxCPU.Y.W.L = DEC16(MinxCPU.Y.W.L); + return 8; + + case 0x9C: // AND F, #nn + I8A = Fetch8(); + MinxCPU.F = MinxCPU.F & I8A; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); + return 12; + case 0x9D: // OR F, #nn + I8A = Fetch8(); + MinxCPU.F = MinxCPU.F | I8A; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); + return 12; + case 0x9E: // XOR F, #nn + I8A = Fetch8(); + MinxCPU.F = MinxCPU.F ^ I8A; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); + return 12; + case 0x9F: // MOV F, #nn + I8A = Fetch8(); + MinxCPU.F = I8A; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); + return 12; + + case 0xA0: // PUSH BA + PUSH(MinxCPU.BA.B.H); + PUSH(MinxCPU.BA.B.L); + return 16; + case 0xA1: // PUSH HL + PUSH(MinxCPU.HL.B.H); + PUSH(MinxCPU.HL.B.L); + return 16; + case 0xA2: // PUSH X + PUSH(MinxCPU.X.B.H); + PUSH(MinxCPU.X.B.L); + return 16; + case 0xA3: // PUSH Y + PUSH(MinxCPU.Y.B.H); + PUSH(MinxCPU.Y.B.L); + return 16; + case 0xA4: // PUSH N + PUSH(MinxCPU.N.B.H); + return 12; + case 0xA5: // PUSH I + PUSH(MinxCPU.HL.B.I); + return 12; + case 0xA6: // PUSHX + PUSH(MinxCPU.X.B.I); + PUSH(MinxCPU.Y.B.I); + return 16; + case 0xA7: // PUSH F + PUSH(MinxCPU.F); + return 12; + + case 0xA8: // POP BA + MinxCPU.BA.B.L = POP(); + MinxCPU.BA.B.H = POP(); + return 12; + case 0xA9: // POP HL + MinxCPU.HL.B.L = POP(); + MinxCPU.HL.B.H = POP(); + return 12; + case 0xAA: // POP X + MinxCPU.X.B.L = POP(); + MinxCPU.X.B.H = POP(); + return 12; + case 0xAB: // POP Y + MinxCPU.Y.B.L = POP(); + MinxCPU.Y.B.H = POP(); + return 12; + case 0xAC: // POP N + MinxCPU.N.B.H = POP(); + return 8; + case 0xAD: // POP I + MinxCPU.HL.B.I = POP(); + MinxCPU.N.B.I = MinxCPU.HL.B.I; + return 8; + case 0xAE: // POPX + MinxCPU.Y.B.I = POP(); + MinxCPU.X.B.I = POP(); + return 12; + case 0xAF: // POP F + MinxCPU.F = POP(); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); + return 8; + + case 0xB0: // MOV A, #nn + I8A = Fetch8(); + MinxCPU.BA.B.L = I8A; + return 8; + case 0xB1: // MOV B, #nn + I8A = Fetch8(); + MinxCPU.BA.B.H = I8A; + return 8; + case 0xB2: // MOV L, #nn + I8A = Fetch8(); + MinxCPU.HL.B.L = I8A; + return 8; + case 0xB3: // MOV H, #nn + I8A = Fetch8(); + MinxCPU.HL.B.H = I8A; + return 8; + case 0xB4: // MOV N, #nn + I8A = Fetch8(); + MinxCPU.N.B.H = I8A; + return 8; + case 0xB5: // MOV [HL], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.HL.D, I8A); + return 12; + case 0xB6: // MOV [X], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.X.D, I8A); + return 12; + case 0xB7: // MOV [Y], #nn + I8A = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.Y.D, I8A); + return 12; + + case 0xB8: // MOV BA, [#nnnn] + I16 = Fetch16(); + MinxCPU.BA.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.BA.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + case 0xB9: // MOV HL, [#nnnn] + I16 = Fetch16(); + MinxCPU.HL.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.HL.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + case 0xBA: // MOV X, [#nnnn] + I16 = Fetch16(); + MinxCPU.X.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.X.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + case 0xBB: // MOV Y, [#nnnn] + I16 = Fetch16(); + MinxCPU.Y.B.L = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16++); + MinxCPU.Y.B.H = MinxCPU_OnRead(1, (MinxCPU.HL.B.I << 16) | I16); + return 20; + + case 0xBC: // MOV [#nnnn], BA + I16 = Fetch16(); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.BA.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.BA.B.H); + return 20; + case 0xBD: // MOV [#nnnn], HL + I16 = Fetch16(); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.HL.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.HL.B.H); + return 20; + case 0xBE: // MOV [#nnnn], X + I16 = Fetch16(); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.X.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.X.B.H); + return 20; + case 0xBF: // MOV [#nnnn], Y + I16 = Fetch16(); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16++, MinxCPU.Y.B.L); + MinxCPU_OnWrite(1, (MinxCPU.HL.B.I << 16) | I16, MinxCPU.Y.B.H); + return 20; + + case 0xC0: // ADD BA, #nnnn + I16 = Fetch16(); + MinxCPU.BA.W.L = ADD16(MinxCPU.BA.W.L, I16); + return 12; + case 0xC1: // ADD HL, #nnnn + I16 = Fetch16(); + MinxCPU.HL.W.L = ADD16(MinxCPU.HL.W.L, I16); + return 12; + case 0xC2: // ADD X, #nnnn + I16 = Fetch16(); + MinxCPU.X.W.L = ADD16(MinxCPU.X.W.L, I16); + return 12; + case 0xC3: // ADD Y, #nnnn + I16 = Fetch16(); + MinxCPU.Y.W.L = ADD16(MinxCPU.Y.W.L, I16); + return 12; + + case 0xC4: // MOV BA, #nnnn + I16 = Fetch16(); + MinxCPU.BA.W.L = I16; + return 12; + case 0xC5: // MOV HL, #nnnn + I16 = Fetch16(); + MinxCPU.HL.W.L = I16; + return 12; + case 0xC6: // MOV X, #nnnn + I16 = Fetch16(); + MinxCPU.X.W.L = I16; + return 12; + case 0xC7: // MOV Y, #nnnn + I16 = Fetch16(); + MinxCPU.Y.W.L = I16; + return 12; + + case 0xC8: // XCHG BA, HL + I16 = MinxCPU.HL.W.L; + MinxCPU.HL.W.L = MinxCPU.BA.W.L; + MinxCPU.BA.W.L = I16; + return 12; + case 0xC9: // XCHG BA, X + I16 = MinxCPU.X.W.L; + MinxCPU.X.W.L = MinxCPU.BA.W.L; + MinxCPU.BA.W.L = I16; + return 12; + case 0xCA: // XCHG BA, Y + I16 = MinxCPU.Y.W.L; + MinxCPU.Y.W.L = MinxCPU.BA.W.L; + MinxCPU.BA.W.L = I16; + return 12; + case 0xCB: // XCHG BA, SP + I16 = MinxCPU.SP.W.L; + MinxCPU.SP.W.L = MinxCPU.BA.W.L; + MinxCPU.BA.W.L = I16; + return 12; + + case 0xCC: // XCHG A, B + I8A = MinxCPU.BA.B.H; + MinxCPU.BA.B.H = MinxCPU.BA.B.L; + MinxCPU.BA.B.L = I8A; + return 8; + case 0xCD: // XCHG A, [HL] + I8A = MinxCPU_OnRead(1, MinxCPU.HL.D); + MinxCPU_OnWrite(1, MinxCPU.HL.D, MinxCPU.BA.B.L); + MinxCPU.BA.B.L = I8A; + return 12; + + case 0xCE: // Expand 0 + return MinxCPU_ExecCE(); + + case 0xCF: // Expand 1 + return MinxCPU_ExecCF(); + + case 0xD0: // SUB BA, #nnnn + I16 = Fetch16(); + MinxCPU.BA.W.L = SUB16(MinxCPU.BA.W.L, I16); + return 12; + case 0xD1: // SUB HL, #nnnn + I16 = Fetch16(); + MinxCPU.HL.W.L = SUB16(MinxCPU.HL.W.L, I16); + return 12; + case 0xD2: // SUB X, #nnnn + I16 = Fetch16(); + MinxCPU.X.W.L = SUB16(MinxCPU.X.W.L, I16); + return 12; + case 0xD3: // SUB Y, #nnnn + I16 = Fetch16(); + MinxCPU.Y.W.L = SUB16(MinxCPU.Y.W.L, I16); + return 12; + + case 0xD4: // CMP BA, #nnnn + I16 = Fetch16(); + SUB16(MinxCPU.BA.W.L, I16); + return 12; + case 0xD5: // CMP HL, #nnnn + I16 = Fetch16(); + SUB16(MinxCPU.HL.W.L, I16); + return 12; + case 0xD6: // CMP X, #nnnn + I16 = Fetch16(); + SUB16(MinxCPU.X.W.L, I16); + return 12; + case 0xD7: // CMP Y, #nnnn + I16 = Fetch16(); + SUB16(MinxCPU.Y.W.L, I16); + return 12; + + case 0xD8: // AND [N+#nn], #nn + I8A = Fetch8(); + I8B = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, AND8(MinxCPU_OnRead(1, MinxCPU.N.D + I8A), I8B)); + return 20; + case 0xD9: // OR [N+#nn], #nn + I8A = Fetch8(); + I8B = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, OR8(MinxCPU_OnRead(1, MinxCPU.N.D + I8A), I8B)); + return 20; + case 0xDA: // XOR [N+#nn], #nn + I8A = Fetch8(); + I8B = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, XOR8(MinxCPU_OnRead(1, MinxCPU.N.D + I8A), I8B)); + return 20; + case 0xDB: // CMP [N+#nn], #nn + I8A = Fetch8(); + I8B = Fetch8(); + SUB8(MinxCPU_OnRead(1, MinxCPU.N.D + I8A), I8B); + return 16; + case 0xDC: // TST [N+#nn], #nn + I8A = Fetch8(); + I8B = Fetch8(); + AND8(MinxCPU_OnRead(1, MinxCPU.N.D + I8A), I8B); + return 16; + case 0xDD: // MOV [N+#nn], #nn + I8A = Fetch8(); + I8B = Fetch8(); + MinxCPU_OnWrite(1, MinxCPU.N.D + I8A, I8B); + return 16; + + case 0xDE: // PACK + MinxCPU.BA.B.L = (MinxCPU.BA.B.L & 0x0F) | (MinxCPU.BA.B.H << 4); + return 8; + + case 0xDF: // UNPACK + MinxCPU.BA.B.H = (MinxCPU.BA.B.L >> 4); + MinxCPU.BA.B.L = MinxCPU.BA.B.L & 0x0F; + return 8; + + case 0xE0: // CALLC #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_CARRY) { + CALLS(S8_TO_16(I8A)); + return 20; + } + return 8; + case 0xE1: // CALLNC #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_CARRY)) { + CALLS(S8_TO_16(I8A)); + return 20; + } + return 8; + case 0xE2: // CALLZ #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_ZERO) { + CALLS(S8_TO_16(I8A)); + return 20; + } + return 8; + case 0xE3: // CALLNZ #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_ZERO)) { + CALLS(S8_TO_16(I8A)); + return 20; + } + return 8; + + case 0xE4: // JC #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_CARRY) { + JMPS(S8_TO_16(I8A)); + } + return 8; + case 0xE5: // JNC #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_CARRY)) { + JMPS(S8_TO_16(I8A)); + } + return 8; + case 0xE6: // JZ #ss + I8A = Fetch8(); + if (MinxCPU.F & MINX_FLAG_ZERO) { + JMPS(S8_TO_16(I8A)); + } + return 8; + case 0xE7: // JNZ #ss + I8A = Fetch8(); + if (!(MinxCPU.F & MINX_FLAG_ZERO)) { + JMPS(S8_TO_16(I8A)); + } + return 8; + + case 0xE8: // CALLC #ssss + I16 = Fetch16(); + if (MinxCPU.F & MINX_FLAG_CARRY) { + CALLS(I16); + return 24; + } + return 12; + case 0xE9: // CALLNC #ssss + I16 = Fetch16(); + if (!(MinxCPU.F & MINX_FLAG_CARRY)) { + CALLS(I16); + return 24; + } + return 12; + case 0xEA: // CALLZ #ssss + I16 = Fetch16(); + if (MinxCPU.F & MINX_FLAG_ZERO) { + CALLS(I16); + return 24; + } + return 12; + case 0xEB: // CALLNZ #ssss + I16 = Fetch16(); + if (!(MinxCPU.F & MINX_FLAG_ZERO)) { + CALLS(I16); + return 24; + } + return 12; + + case 0xEC: // JC #ssss + I16 = Fetch16(); + if (MinxCPU.F & MINX_FLAG_CARRY) { + JMPS(I16); + } + return 12; + case 0xED: // JNC #ssss + I16 = Fetch16(); + if (!(MinxCPU.F & MINX_FLAG_CARRY)) { + JMPS(I16); + } + return 12; + case 0xEE: // JZ #ssss + I16 = Fetch16(); + if (MinxCPU.F & MINX_FLAG_ZERO) { + JMPS(I16); + } + return 12; + case 0xEF: // JNZ #ssss + I16 = Fetch16(); + if (!(MinxCPU.F & MINX_FLAG_ZERO)) { + JMPS(I16); + } + return 12; + + case 0xF0: // CALL #ss + I8A = Fetch8(); + CALLS(S8_TO_16(I8A)); + return 20; + case 0xF1: // JMP #ss + I8A = Fetch8(); + JMPS(S8_TO_16(I8A)); + return 8; + case 0xF2: // CALL #ssss + I16 = Fetch16(); + CALLS(I16); + return 24; + case 0xF3: // JMP #ssss + I16 = Fetch16(); + JMPS(I16); + return 12; + + case 0xF4: // JMP HL + JMPU(MinxCPU.HL.W.L); + return 8; + + case 0xF5: // JDBNZ #ss + I8A = Fetch8(); + JDBNZ(S8_TO_16(I8A)); + return 16; + + case 0xF6: // SWAP A + MinxCPU.BA.B.L = SWAP(MinxCPU.BA.B.L); + return 8; + case 0xF7: // SWAP [HL] + MinxCPU_OnWrite(1, MinxCPU.HL.D, SWAP(MinxCPU_OnRead(1, MinxCPU.HL.D))); + return 12; + + case 0xF8: // RET + RET(); + return 16; + case 0xF9: // RETI + RETI(); + return 16; + case 0xFA: // RETSKIP + RET(); + MinxCPU.PC.W.L = MinxCPU.PC.W.L + 2; + return 16; + + case 0xFB: // CALL [#nnnn] + I16 = Fetch16(); + CALLX(I16); + return 20; + case 0xFC: // CINT #nn + I16 = Fetch8(); + CALLI(I16); + return 20; + case 0xFD: // JINT #nn + I16 = Fetch8(); + JMPI(I16); + return 8; + + case 0xFF: // NOP + return 8; + + case 0xFE: // CRASH + default: + break; + } + + return 4; +} diff --git a/pm/src/core/MinxCPU_noBranch.h b/pm/src/core/MinxCPU_noBranch.h new file mode 100644 index 0000000..ca6f8dc --- /dev/null +++ b/pm/src/core/MinxCPU_noBranch.h @@ -0,0 +1,734 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXCPU_CORE +#define MINXCPU_CORE + +#include +#include + +/* For some reason, '_BIG_ENDIAN' is always defined when + * building for 3DS/Switch with devkitarm/a64... */ +#if defined (_BIG_ENDIAN) && !defined (_3DS) && !defined(HAVE_LIBNX) + +typedef union { + struct { + uint8_t X; + uint8_t I; + uint8_t H; + uint8_t L; + } B; + struct { + uint16_t H; + uint16_t L; + } W; + uint32_t D; +} MinxRegx; + +#else + +typedef union { + struct { + uint8_t L; + uint8_t H; + uint8_t I; + uint8_t X; + } B; + struct { + uint16_t L; + uint16_t H; + } W; + uint32_t D; +} MinxRegx; + +#endif + +#define MINX_FLAG_ZERO 0x01 +#define MINX_FLAG_CARRY 0x02 +#define MINX_FLAG_OVERFLOW 0x04 +#define MINX_FLAG_SIGN 0x08 +#define MINX_FLAG_BCD 0x10 +#define MINX_FLAG_NIBBLE 0x20 +#define MINX_FLAG_INTFLG 0x40 +#define MINX_FLAG_INTOFF 0x80 + +#define MINX_FLAG_SIGN_S4 0 +#define MINX_FLAG_OVER_S4 1 +#define MINX_FLAG_SIGN_S8 4 +#define MINX_FLAG_OVER_S8 5 +#define MINX_FLAG_SIGN_S16 12 +#define MINX_FLAG_OVER_S16 13 + +#define MINX_FLAG_SAVE_NUL 0xF0 +#define MINX_FLAG_SAVE_O 0xF4 +#define MINX_FLAG_SAVE_CO 0xF6 +#define MINX_FLAG_SAVE_COS 0xFE + +// Status reasons +enum { + MINX_STATUS_NORMAL = 0, // Normal operation + MINX_STATUS_HALT = 1, // CPU during HALT + MINX_STATUS_STOP = 2, // CPU during STOP + MINX_STATUS_IRQ = 3 // Delay caused by hardware IRQ +}; + +// Signed 8-Bits to 16-Bits converter +static INLINE uint16_t S8_TO_16(int8_t a) +{ + return (a & 0x80) ? (0xFF00 | a) : a; +} + +typedef struct { + // Registers + MinxRegx BA; // Registers A, B + MinxRegx HL; // Registers L, H, I + MinxRegx X; // Registers X, XI + MinxRegx Y; // Registers Y, YI + MinxRegx SP; // Register SP + MinxRegx PC; // Registers PC, V + MinxRegx N; // for [N+#nn], I is written here too + uint8_t U1; // V Shadow 1 + uint8_t U2; // V Shadow 2 + uint8_t F; // Flags + uint8_t E; // Exception + uint8_t IR; // Last Instruction Register (for open-bus) + uint8_t Shift_U; // Shift U, set to 2 when: U modify, branch, return + uint8_t Status; // CPU Status (0 = Normal, 1 = Halt, 2 = Stoped, 3 = IRQ) + uint8_t IRQ_Vector; // IRQ Vector when Status is IRQ + uint8_t Reserved[28]; // Reserved bytes +} TMinxCPU; + +// CPU registers +extern TMinxCPU MinxCPU; + +// Callbacks (Must be coded by the user) +uint8_t MinxCPU_OnRead(int cpu, uint32_t addr); +void MinxCPU_OnWrite(int cpu, uint32_t addr, uint8_t data); +void MinxCPU_OnIRQHandle(uint8_t flag, uint8_t shift_u); +void MinxCPU_OnIRQAct(uint8_t intr); + +// Functions +int MinxCPU_Create(void); // Create MinxCPU +void MinxCPU_Destroy(void); // Destroy MinxCPU +void MinxCPU_Reset(int hardreset); // Reset CPU +int MinxCPU_Exec(void); // Execute 1 CPU instruction +int MinxCPU_CallIRQ(uint8_t IRQ); // Call an IRQ + +// Helpers +static INLINE uint16_t ReadMem16(uint32_t addr) +{ + return MinxCPU_OnRead(1, addr) + (MinxCPU_OnRead(1, addr+1) << 8); +} + +static INLINE void WriteMem16(uint32_t addr, uint16_t data) +{ + MinxCPU_OnWrite(1, addr, (uint8_t)data); + MinxCPU_OnWrite(1, addr+1, data >> 8); +} + +static INLINE uint8_t Fetch8(void) +{ + if (MinxCPU.PC.W.L & 0x8000) { + // Banked area + MinxCPU.IR = MinxCPU_OnRead(1, (MinxCPU.PC.W.L++ & 0x7FFF) | (MinxCPU.PC.B.I << 15)); + } else { + // Unbanked area + MinxCPU.IR = MinxCPU_OnRead(1, MinxCPU.PC.W.L++); + } + return MinxCPU.IR; +} + +static INLINE uint16_t Fetch16(void) +{ + uint8_t LB = Fetch8(); + return (Fetch8() << 8) | LB; +} + +static INLINE void Set_U(uint8_t val) +{ + if (val != MinxCPU.U2) MinxCPU.Shift_U = 2; + MinxCPU.U1 = val; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +// Instruction exec. prototypes + +int MinxCPU_ExecCE(void); +int MinxCPU_ExecCF(void); +int MinxCPU_ExecSPCE(void); +int MinxCPU_ExecSPCF(void); + +// Instructions Macros + +static INLINE uint8_t ADD8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A + B; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES < A) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B ^ 0x80) & 0x80) >> MINX_FLAG_OVER_S8) | // Overflow + ((RES & 0x80) >> MINX_FLAG_SIGN_S8); // Sign + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) + (B & 15)) >= 10) { + RES = A + B + 6; + } else { + RES = A + B; + } + if (RES >= 0xA0) RES += 0x60; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES < A) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) + (B & 15); + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B ^ 0x08) & 0x08) >> MINX_FLAG_OVER_S4) | // Overflow + ((RES & 0x08) >> MINX_FLAG_SIGN_S4); // Sign + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) + (B & 15)) >= 10) { + RES = (A & 15) + (B & 15) + 6; + } else { + RES = (A & 15) + (B & 15); + } + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0x0F; + } +} + +static INLINE uint16_t ADD16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A + B; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES < A) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B ^ 0x8000) & 0x8000) >> MINX_FLAG_OVER_S16) | // Overflow + ((RES & 0x8000) >> MINX_FLAG_SIGN_S16); // Sign + return (uint16_t)RES; +} + +static INLINE uint8_t ADC8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A + B + CARRY; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES < A) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B ^ 0x80) & 0x80) >> MINX_FLAG_OVER_S8) | // Overflow + ((RES & 0x80) >> MINX_FLAG_SIGN_S8); // Sign + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) + (B & 15) + CARRY) >= 10) { + RES = A + B + CARRY + 6; + } else { + RES = A + B + CARRY; + } + if (RES >= 0xA0) RES += 0x60; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES < A) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) + (B & 15) + CARRY; + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B ^ 0x08) & 0x08) >> MINX_FLAG_OVER_S4) | // Overflow + ((RES & 0x08) >> MINX_FLAG_SIGN_S4); // Sign + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) + (B & 15) + CARRY) >= 10) { + RES = (A & 15) + (B & 15) + CARRY + 6; + } else { + RES = (A & 15) + (B & 15) + CARRY; + } + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0x0F; + } +} + +static INLINE uint16_t ADC16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A + B + ((MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0); + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES < A) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B ^ 0x8000) & 0x8000) >> MINX_FLAG_OVER_S16) | // Overflow + ((RES & 0x8000) >> MINX_FLAG_SIGN_S16); // Sign + return (uint16_t)RES; +} + +static INLINE uint8_t SUB8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A - B; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((A < B) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B) & 0x80) >> MINX_FLAG_OVER_S8) | // Overflow + ((RES & 0x80) >> MINX_FLAG_SIGN_S8); // Sign + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) - (B & 15)) >= 10) { + RES = A - B - 6; + } else { + RES = A - B; + } + if (RES >= 0xA0) RES -= 0x60; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((A < B) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) - (B & 15); + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B) & 0x08) >> MINX_FLAG_OVER_S4) | // Overflow + ((RES & 0x08) >> MINX_FLAG_SIGN_S4); // Sign + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) - (B & 15)) >= 10) { + RES = (A & 15) - (B & 15) - 6; + } else { + RES = (A & 15) - (B & 15); + } + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0x0F; + } +} + +static INLINE uint16_t SUB16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A - B; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((A < B) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B) & 0x8000) >> MINX_FLAG_OVER_S16) | // Overflow + ((RES & 0x8000) >> MINX_FLAG_SIGN_S16); // Sign + return (uint16_t)RES; +} + +static INLINE uint8_t SBC8(uint8_t A, uint8_t B) +{ + register uint8_t RES; + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + switch (MinxCPU.F & 0x30) { + case 0x00: // Normal + RES = A - B - CARRY; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((A < B) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B) & 0x80) >> MINX_FLAG_OVER_S8) | // Overflow + ((RES & 0x80) >> MINX_FLAG_SIGN_S8); // Sign + return RES & 0xFF; + case 0x10: // BCD + if ((uint8_t)((A & 15) - (B & 15) - CARRY) >= 10) { + RES = A - B - CARRY - 6; + } else { + RES = A - B - CARRY; + } + if (RES >= 0xA0) RES -= 0x60; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((A < B) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0xFF; + case 0x20: // Nibble + RES = (A & 15) - (B & 15) - CARRY; + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B) & 0x08) >> MINX_FLAG_OVER_S4) | // Overflow + ((RES & 0x08) >> MINX_FLAG_SIGN_S4); // Sign + return RES & 0x0F; + default: // BCD and Nibble + if ((uint8_t)((A & 15) - (B & 15) - CARRY) >= 10) { + RES = (A & 15) - (B & 15) - CARRY - 6; + } else { + RES = (A & 15) - (B & 15) - CARRY; + } + MinxCPU.F |= + (((RES & 15) == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((RES >= 16) ? MINX_FLAG_CARRY : 0); // Carry + return RES & 0x0F; + } +} + +static INLINE uint16_t SBC16(uint16_t A, uint16_t B) +{ + register uint16_t RES; + RES = A - B - ((MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0); + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + MinxCPU.F |= + ((RES == 0) ? MINX_FLAG_ZERO : 0) | // Zero + ((A < B) ? MINX_FLAG_CARRY : 0) | // Carry + (((A ^ RES) & (A ^ B) & 0x8000) >> MINX_FLAG_OVER_S16) | // Overflow + ((RES & 0x8000) >> MINX_FLAG_SIGN_S16); // Sign + return (uint16_t)RES; +} + +static INLINE uint8_t AND8(uint8_t A, uint8_t B) +{ + A &= B; + MinxCPU.F &= MINX_FLAG_SAVE_CO; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t OR8(uint8_t A, uint8_t B) +{ + A |= B; + MinxCPU.F &= MINX_FLAG_SAVE_CO; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t XOR8(uint8_t A, uint8_t B) +{ + A ^= B; + MinxCPU.F &= MINX_FLAG_SAVE_CO; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t INC8(uint8_t A) +{ + A++; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE uint16_t INC16(uint16_t A) +{ + A++; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE uint8_t DEC8(uint8_t A) +{ + A--; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE uint16_t DEC16(uint16_t A) +{ + A--; + MinxCPU.F &= MINX_FLAG_SAVE_COS; + if (A == 0) MinxCPU.F |= MINX_FLAG_ZERO; + return A; +} + +static INLINE void PUSH(uint8_t A) +{ + MinxCPU.SP.W.L--; + MinxCPU_OnWrite(1, MinxCPU.SP.D, A); +} + +static INLINE uint8_t POP(void) +{ + register uint8_t data; + data = MinxCPU_OnRead(1, MinxCPU.SP.D); + MinxCPU.SP.W.L++; + return data; +} + +static INLINE void CALLS(uint16_t OFFSET) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = MinxCPU.PC.W.L + OFFSET - 1; +} + +static INLINE void JMPS(uint16_t OFFSET) +{ + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = MinxCPU.PC.W.L + OFFSET - 1; +} + +static INLINE void CALLU(uint16_t ADDR) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ADDR; +} + +static INLINE void JMPU(uint16_t ADDR) +{ + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ADDR; +} + +static INLINE void JDBNZ(uint16_t OFFSET) +{ + MinxCPU.BA.B.H = DEC8(MinxCPU.BA.B.H); + if (MinxCPU.BA.B.H != 0) { + JMPS(OFFSET); + } +} + +static INLINE uint8_t SWAP(uint8_t A) +{ + return (A << 4) | (A >> 4); +} + +static INLINE void RET(void) +{ + MinxCPU.PC.B.L = POP(); + MinxCPU.PC.B.H = POP(); + MinxCPU.PC.B.I = POP(); + Set_U(MinxCPU.PC.B.I); +} + +static INLINE void RETI(void) +{ + MinxCPU.F = POP(); + MinxCPU.PC.B.L = POP(); + MinxCPU.PC.B.H = POP(); + MinxCPU.PC.B.I = POP(); + Set_U(MinxCPU.PC.B.I); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +static INLINE void CALLX(uint16_t ADDR) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ReadMem16((MinxCPU.HL.B.I << 16) + ADDR); +} + +static INLINE void CALLI(uint16_t ADDR) +{ + PUSH(MinxCPU.PC.B.I); + PUSH(MinxCPU.PC.B.H); + PUSH(MinxCPU.PC.B.L); + PUSH(MinxCPU.F); + MinxCPU.F |= 0xC0; + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ReadMem16(ADDR); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +static INLINE void JMPI(uint16_t ADDR) +{ + PUSH(MinxCPU.F); + MinxCPU.F |= 0xC0; + MinxCPU.PC.B.I = MinxCPU.U1; + MinxCPU.U2 = MinxCPU.U1; + MinxCPU.PC.W.L = ReadMem16(ADDR); + MinxCPU_OnIRQHandle(MinxCPU.F, MinxCPU.Shift_U); +} + +static INLINE uint8_t SAL(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + if ((!(A & 0x40)) != (!(A & 0x80))) MinxCPU.F |= MINX_FLAG_OVERFLOW; + A = A << 1; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t SHL(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + A = A << 1; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t SAR(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A & 0x80) | (A >> 1); + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t SHR(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = A >> 1; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t ROLC(uint8_t A) +{ + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 1 : 0; + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A << 1) | CARRY; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t ROL(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x80) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A << 1) | (A >> 7); + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t RORC(uint8_t A) +{ + register uint8_t CARRY = (MinxCPU.F & MINX_FLAG_CARRY) ? 0x80 : 0x00; + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A >> 1) | CARRY; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t ROR(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_O; + if (A & 0x01) MinxCPU.F |= MINX_FLAG_CARRY; + A = (A >> 1) | (A << 7); + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t NOT(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_CO; + A = A ^ 0xFF; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE uint8_t NEG(uint8_t A) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + A = -A; + MinxCPU.F |= + ((A == 0) ? MINX_FLAG_ZERO : MINX_FLAG_CARRY) | + ((A == 0x80) ? MINX_FLAG_OVERFLOW : 0) | + ((A & 0x80) >> MINX_FLAG_SIGN_S8); + return A; +} + +static INLINE void HALT(void) +{ + MinxCPU.Status = MINX_STATUS_HALT; +} + +static INLINE void STOP(void) +{ + MinxCPU.Status = MINX_STATUS_STOP; +} + +static INLINE void MUL(void) +{ + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + MinxCPU.HL.W.L = (uint16_t)MinxCPU.HL.B.L * (uint16_t)MinxCPU.BA.B.L; + MinxCPU.F |= + ((MinxCPU.HL.W.L == 0) ? MINX_FLAG_ZERO : 0) | + ((MinxCPU.HL.W.L & 0x8000) ? MINX_FLAG_SIGN : 0); +} + +static INLINE void DIV(void) +{ + uint16_t RES; + MinxCPU.F &= MINX_FLAG_SAVE_NUL; + if (MinxCPU.BA.B.L == 0) + return; + RES = MinxCPU.HL.W.L / MinxCPU.BA.B.L; + if (RES < 256) { + MinxCPU.HL.B.H = MinxCPU.HL.W.L % MinxCPU.BA.B.L; + MinxCPU.HL.B.L = (uint8_t)RES; + MinxCPU.F |= + ((MinxCPU.HL.B.L == 0) ? MINX_FLAG_ZERO : 0) | + ((MinxCPU.HL.B.L & 0x80) ? MINX_FLAG_SIGN : 0); + } else MinxCPU.F |= MINX_FLAG_OVERFLOW | MINX_FLAG_SIGN; +} + +#endif diff --git a/pm/src/core/MinxColorPRC.h b/pm/src/core/MinxColorPRC.h new file mode 100644 index 0000000..22fc33e --- /dev/null +++ b/pm/src/core/MinxColorPRC.h @@ -0,0 +1,85 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXHW_COLORPRC +#define MINXHW_COLORPRC + +#include +#include + +typedef struct { + uint16_t UnlockCode; + uint8_t Unlocked; + uint8_t Access; + uint8_t Modes; + uint8_t ActivePage; + uint16_t Address; + uint8_t LNColor0; + uint8_t HNColor0; + uint8_t LNColor1; + uint8_t HNColor1; +} TMinxColorPRC; + +// Export PRC state +extern TMinxColorPRC MinxColorPRC; + +// For Unofficial Color Pokemon-Mini +extern int PRCColorEnable; +extern uint8_t *PRCColorPixels; +extern uint8_t *PRCColorPixelsOld; +extern uint8_t *PRCColorMap; +extern unsigned int PRCColorOffset; +extern uint8_t *PRCColorTop; +extern uint8_t PRCColorFlags; +extern const uint8_t PRCStaticColorMap[8]; + +// +// Functions +// + +int MinxColorPRC_Create(void); + +void MinxColorPRC_Destroy(void); + +void MinxColorPRC_Reset(int hardreset); + +int MinxColorPRC_LoadStateStream(memstream_t *stream, uint32_t bsize); + +int MinxColorPRC_SaveStateStream(memstream_t *stream); + +uint8_t MinxColorPRC_ReadReg(int cpu, uint8_t reg); + +void MinxColorPRC_WriteReg(uint8_t reg, uint8_t val); + +void MinxColorPRC_WriteFramebuffer(uint16_t addr, uint8_t data); + +void MinxColorPRC_WriteLCD(uint16_t addr, uint8_t data); + +// +// Internals +// + +void MinxColorPRC_WriteCtrl(uint8_t val); + +void MinxPRC_Render_Color8(void); + +void MinxPRC_Render_Color4(void); + +void MinxPRC_NoRender_Color(void); + +#endif diff --git a/pm/src/core/MinxIO.c b/pm/src/core/MinxIO.c new file mode 100644 index 0000000..e3f708c --- /dev/null +++ b/pm/src/core/MinxIO.c @@ -0,0 +1,401 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "PokeMini.h" + +TMinxIO MinxIO; +uint8_t *EEPROM = NULL; +int PokeMini_Rumbling = 0; +int PokeMini_RumblingLatch = 0; +int PokeMini_EEPROMWritten = 0; +int PokeMini_BatteryStatus = 0; // 0 = Full, 1 = Low +int PokeMini_ShockKey = 0; + +uint8_t MinxIO_IODataRead(void); +void MinxIO_IODataWrite(void); +void MinxIO_EEPROM_WEvent(uint8_t bits); +int MinxIO_EEPROM_REvent(void); +void MinxIO_EEPROM_Write(uint8_t data); + +// +// Functions +// + +int MinxIO_Create(void) +{ + // Create EEPROM memory & format it + EEPROM = (uint8_t *)malloc(8192); + if (!EEPROM) return 0; + MinxIO_FormatEEPROM(); + + // Reset + MinxIO_Reset(1); + + return 1; +} + +void MinxIO_Destroy(void) +{ + if (EEPROM) { + free(EEPROM); + EEPROM = NULL; + } +} + +void MinxIO_Reset(int hardreset) +{ + // Initialize State + memset(&MinxIO, 0, sizeof(TMinxIO)); + PokeMini_Rumbling = 0; + PokeMini_RumblingLatch = 0; + PokeMini_ShockKey = 0; + + // Init variables + PMR_KEY_PAD = 0xFF; + MinxIO.ListenState = MINX_EEPROM_IDLE; + MinxIO.OperState = MINX_EEPROM_DEVICE; + + // Restore battery status + MinxIO_BatteryLow(PokeMini_BatteryStatus); +} + +int MinxIO_LoadStateStream(memstream_t *stream, uint32_t bsize) +{ + POKELOADSS_START(32+8192); + PokeMini_Rumbling = 0; + PokeMini_RumblingLatch = 0; + PokeMini_EEPROMWritten = 1; + POKELOADSS_STREAM_8(MinxIO.EEPLastPins); + POKELOADSS_STREAM_8(MinxIO.ListenState); + POKELOADSS_STREAM_8(MinxIO.OperState); + POKELOADSS_STREAM_8(MinxIO.EEPData); + POKELOADSS_STREAM_32(MinxIO.EEPBit); + POKELOADSS_STREAM_16(MinxIO.EEPAddress); + POKELOADSS_STREAM_X(22); + POKELOADSS_STREAM_A(EEPROM, 8192); + POKELOADSS_END(32+8192); +} + +int MinxIO_SaveStateStream(memstream_t *stream) +{ + POKESAVESS_STREAM_START(32+8192); + POKESAVESS_STREAM_8(MinxIO.EEPLastPins); + POKESAVESS_STREAM_8(MinxIO.ListenState); + POKESAVESS_STREAM_8(MinxIO.OperState); + POKESAVESS_STREAM_8(MinxIO.EEPData); + POKESAVESS_STREAM_32(MinxIO.EEPBit); + POKESAVESS_STREAM_16(MinxIO.EEPAddress); + POKESAVESS_STREAM_X(22); + POKESAVESS_STREAM_A(EEPROM, 8192); + POKESAVESS_END(32+8192); +} + +int MinxIO_FormatEEPROM(void) +{ + if (!EEPROM) return 0; + memset(EEPROM, 0xFF, 8192); + return 1; +} + +void MinxIO_Keypad(uint8_t key, int pressed) +{ + if (!EEPROM) return; + switch (key) { + case MINX_KEY_A: // Key A + if (pressed) { + if (!(PMR_KEY_PAD & 0x01)) return; + MinxCPU_OnIRQAct(MINX_INTR_1C); + PMR_KEY_PAD &= ~0x01; + } else PMR_KEY_PAD |= 0x01; + break; + case MINX_KEY_B: // Key B + if (pressed) { + if (!(PMR_KEY_PAD & 0x02)) return; + MinxCPU_OnIRQAct(MINX_INTR_1B); + PMR_KEY_PAD &= ~0x02; + } else PMR_KEY_PAD |= 0x02; + break; + case MINX_KEY_C: // Key C + if (pressed) { + if (!(PMR_KEY_PAD & 0x04)) return; + MinxCPU_OnIRQAct(MINX_INTR_1A); + PMR_KEY_PAD &= ~0x04; + } else PMR_KEY_PAD |= 0x04; + break; + case MINX_KEY_UP: // Dpad Up + if (pressed) { + if (!(PMR_KEY_PAD & 0x08)) return; + MinxCPU_OnIRQAct(MINX_INTR_19); + PMR_KEY_PAD &= ~0x08; + } else PMR_KEY_PAD |= 0x08; + break; + case MINX_KEY_DOWN: // Dpad Down + if (pressed) { + if (!(PMR_KEY_PAD & 0x10)) return; + MinxCPU_OnIRQAct(MINX_INTR_18); + PMR_KEY_PAD &= ~0x10; + } else PMR_KEY_PAD |= 0x10; + break; + case MINX_KEY_LEFT: // Dpad Left + if (pressed) { + if (!(PMR_KEY_PAD & 0x20)) return; + MinxCPU_OnIRQAct(MINX_INTR_17); + PMR_KEY_PAD &= ~0x20; + } else PMR_KEY_PAD |= 0x20; + break; + case MINX_KEY_RIGHT: // Dpad Right + if (pressed) { + if (!(PMR_KEY_PAD & 0x40)) return; + MinxCPU_OnIRQAct(MINX_INTR_16); + PMR_KEY_PAD &= ~0x40; + } else PMR_KEY_PAD |= 0x40; + break; + case MINX_KEY_POWER: // Power key + if (pressed) { + if (!(PMR_KEY_PAD & 0x80)) return; + MinxCPU_OnIRQAct(MINX_INTR_15); + PMR_KEY_PAD &= ~0x80; + } else PMR_KEY_PAD |= 0x80; + break; + case MINX_KEY_SHOCK: // Shock key + if (!PokeMini_ShockKey && pressed) { + MinxCPU_OnIRQAct(MINX_INTR_10); + } + PokeMini_ShockKey = pressed; + break; + } +} + +void MinxIO_BatteryLow(int low) +{ + PokeMini_BatteryStatus = low; + if (low) PMR_SYS_BATT |= 0x20; + else PMR_SYS_BATT &= 0x1F; +} + +void MinxIO_SetTimeStamp(uint8_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) +{ + uint8_t checksum; + if (!EEPROM) return; + checksum = year + month + day + hour + min + sec; + PMR_SYS_CTRL3 |= 0x02; + EEPROM[0x1FF6] = 0x00; + EEPROM[0x1FF7] = 0x00; + EEPROM[0x1FF8] = 0x00; + EEPROM[0x1FF9] = year; + EEPROM[0x1FFA] = month; + EEPROM[0x1FFB] = day; + EEPROM[0x1FFC] = hour; + EEPROM[0x1FFD] = min; + EEPROM[0x1FFE] = sec; + EEPROM[0x1FFF] = checksum; +} + +uint8_t MinxIO_ReadReg(int cpu, uint8_t reg) +{ + // 0x10, 0x52, 0x60 to 0x62 + switch(reg) { + case 0x10: // Low Battery + return PMR_SYS_BATT; + case 0x44: // Unknown + return PMR_REG_44; + case 0x45: // Unknown + return PMR_REG_45; + case 0x46: // Unknown + return PMR_REG_46; + case 0x47: // Unknown + return PMR_REG_47; + case 0x50: // Unknown (related to power management?) + return PMR_REG_50; + case 0x51: // Unknown (related to power management?) + return PMR_REG_51; + case 0x52: // Keypad + return PMR_KEY_PAD; + case 0x53: // Unknown + return PMR_REG_53; + case 0x54: // Unknown + return PMR_REG_54; + case 0x55: // Unknown + return PMR_REG_55; + case 0x60: // I/O Direction Select ( 0 = Input, 1 = Output ) + return PMR_IO_DIR; + case 0x61: // I/O Data Register + return MinxIO_IODataRead(); + case 0x62: // Unknown + return PMR_REG_62; + default: // Unused + break; + } + + return 0; +} + +void MinxIO_WriteReg(int cpu, uint8_t reg, uint8_t val) +{ + // 0x10, 0x52, 0x60 to 0x62 + switch(reg) { + case 0x10: // Low Battery + PMR_SYS_BATT = (PMR_SYS_BATT & 0x20) | (val & 0x1F); + break; + case 0x44: // Unknown + PMR_REG_44 = val & 0xF7; + break; + case 0x45: // Unknown + PMR_REG_45 = val & 0x0F; + break; + case 0x46: // Unknown + PMR_REG_46 = val; + break; + case 0x47: // Unknown + PMR_REG_47 = val & 0x0F; + break; + case 0x50: // Unknown (related to power management?) + PMR_REG_50 = val; + break; + case 0x51: // Unknown (related to power management?) + PMR_REG_51 = val & 0x03; + break; + case 0x52: // Keypad + break; + case 0x53: // Unknown + PMR_REG_53 = 0x00; + /* TODO/FIXME - is fallthrough intentional ?*/ + case 0x54: // Unknown + PMR_REG_54 = val & 0x77; + /* TODO/FIXME - is fallthrough intentional ?*/ + case 0x55: // Unknown + PMR_REG_55 = val & 0x07; + /* TODO/FIXME - is fallthrough intentional ?*/ + case 0x60: // I/O Direction Select ( 0 = Input, 1 = Output ) + PMR_IO_DIR = val; + MinxIO_IODataWrite(); + break; + case 0x61: // I/O Data Register + PMR_IO_DATA = val; + MinxIO_IODataWrite(); + break; + case 0x62: // Unknown + PMR_REG_62 = val & 0xF0; + break; + } +} + +// +// Internal +// + +uint8_t MinxIO_IODataRead(void) +{ + /* Update all I/Os */ + uint8_t Input = MinxIO_EEPROM_REvent() ? MINX_EEPROM_DAT : 0; + + return (PMR_IO_DATA & PMR_IO_DIR) | (Input & ~PMR_IO_DIR); +} + +void MinxIO_IODataWrite(void) +{ + uint8_t Output = (MINX_IO_PULL_UPS & ~PMR_IO_DIR) | (PMR_IO_DATA & PMR_IO_DIR); + + // Update all I/Os + PokeMini_Rumbling = Output & 0x10; + if (PokeMini_Rumbling) PokeMini_RumblingLatch = 1; + MinxIO_EEPROM_WEvent(Output); +} + +void MinxIO_EEPROM_WEvent(uint8_t bits) +{ + uint8_t rise = bits & ~MinxIO.EEPLastPins; + uint8_t fall = ~bits & MinxIO.EEPLastPins; + MinxIO.EEPLastPins = bits; + + // "Start" Command + if ((fall & MINX_EEPROM_DAT) && (bits & MINX_EEPROM_CLK)) { + MinxIO.ListenState = MINX_EEPROM_LISTEN; + MinxIO.OperState = MINX_EEPROM_DEVICE; + MinxIO.EEPBit = 8; + MinxIO.EEPData = 0x00; + return; + } + + // "Stop" Command + if ((rise & MINX_EEPROM_DAT) && (bits & MINX_EEPROM_CLK)) { + MinxIO.ListenState = MINX_EEPROM_IDLE; + return; + } + + // If it's Idle, there's nothing to do... + if (MinxIO.ListenState == MINX_EEPROM_IDLE) return; + + // Process each bit on clock rise + if (rise & MINX_EEPROM_CLK) { + int dat = (bits & MINX_EEPROM_DAT) ? 1 : 0; + if (MinxIO.EEPBit < 0) { + MinxIO_EEPROM_Write(MinxIO.EEPData); + MinxIO.EEPBit = 8; + MinxIO.EEPData = 0x00; + } else MinxIO.EEPData = (MinxIO.EEPData << 1) | dat; + } else if (fall & MINX_EEPROM_CLK) { + MinxIO.EEPBit = MinxIO.EEPBit - 1; + } +} + +int MinxIO_EEPROM_REvent(void) +{ + int valid = (MinxIO.EEPBit >= 0) && (MinxIO.EEPBit < 8); + + // If it's Idle, return high... + if (MinxIO.ListenState == MINX_EEPROM_IDLE) + return 1; + + // Process read + if (MinxIO.OperState == MINX_EEPROM_RBYTE) + { + if (valid) + return (EEPROM[MinxIO.EEPAddress & 0x1FFF] >> MinxIO.EEPBit) & 1; + return 0; + } + + return valid; +} + +void MinxIO_EEPROM_Write(uint8_t data) +{ + switch (MinxIO.OperState) { + case MINX_EEPROM_DEVICE: + // EEPROM Device + if ((data & 0xF0) == 0xA0) + MinxIO.OperState = data & 0x01 ? MINX_EEPROM_RBYTE : MINX_EEPROM_ADDRHI; + break; + case MINX_EEPROM_ADDRHI: + MinxIO.EEPAddress = (MinxIO.EEPAddress & 0x00FF) | (data << 8); + MinxIO.OperState = MINX_EEPROM_ADDRLO; + break; + case MINX_EEPROM_ADDRLO: + MinxIO.EEPAddress = (MinxIO.EEPAddress & 0xFF00) | data; + MinxIO.OperState = MINX_EEPROM_WBYTE; + break; + case MINX_EEPROM_WBYTE: + PokeMini_EEPROMWritten = 1; + EEPROM[MinxIO.EEPAddress & 0x1FFF] = data; + MinxIO.EEPAddress++; + break; + case MINX_EEPROM_RBYTE: + MinxIO.EEPAddress++; + break; + } +} diff --git a/pm/src/core/MinxIO.h b/pm/src/core/MinxIO.h new file mode 100644 index 0000000..8f2156b --- /dev/null +++ b/pm/src/core/MinxIO.h @@ -0,0 +1,114 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXHW_IO +#define MINXHW_IO + +#include +#include + +typedef struct { + // Internal processing + uint8_t EEPLastPins; + uint8_t ListenState; + uint8_t OperState; + uint8_t EEPData; + int32_t EEPBit; + uint16_t EEPAddress; +} TMinxIO; + +// Export IO state +extern TMinxIO MinxIO; + +// EEPROM Data +extern uint8_t *EEPROM; + +// Rumbling & EEPROM written state +extern int PokeMini_Rumbling; +extern int PokeMini_RumblingLatch; +extern int PokeMini_EEPROMWritten; +extern int PokeMini_BatteryStatus; // 0 = Full, 1 = Low + +enum { + // EEPROM Listen State + MINX_EEPROM_IDLE = 0, // Idle + MINX_EEPROM_LISTEN = 1, // Listening + + // EEPROM Data State + MINX_EEPROM_DEVICE = 0, // Device ID + MINX_EEPROM_ADDRHI = 1, // High Address Byte + MINX_EEPROM_ADDRLO = 2, // Low Address Byte + MINX_EEPROM_WBYTE = 3, // Write Byte + MINX_EEPROM_RBYTE = 4, // Read Byte + + // Keypad + MINX_KEY_NONE = 0, + MINX_KEY_A = 1, + MINX_KEY_B = 2, + MINX_KEY_C = 3, + MINX_KEY_UP = 4, + MINX_KEY_DOWN = 5, + MINX_KEY_LEFT = 6, + MINX_KEY_RIGHT = 7, + MINX_KEY_POWER = 8, + MINX_KEY_SHOCK = 9 // Not real key, reserved for handling key event +}; + +// Interrupt table +enum { + MINX_INTR_0F = 0x0F, // IR Receiver + MINX_INTR_10 = 0x10, // Shock Sensor + MINX_INTR_15 = 0x15, // A key + MINX_INTR_16 = 0x16, // B key + MINX_INTR_17 = 0x17, // C key + MINX_INTR_18 = 0x18, // Up key + MINX_INTR_19 = 0x19, // Down key + MINX_INTR_1A = 0x1A, // Left key + MINX_INTR_1B = 0x1B, // Right key + MINX_INTR_1C = 0x1C // Power key +}; + +#define MINX_IO_PULL_UPS 0x40 // Pull-up when direction create a Z + +#define MINX_EEPROM_DAT 0x04 +#define MINX_EEPROM_CLK 0x08 + + +int MinxIO_Create(void); + +void MinxIO_Destroy(void); + +void MinxIO_Reset(int hardreset); + +int MinxIO_LoadStateStream(memstream_t *stream, uint32_t bsize); + +int MinxIO_SaveStateStream(memstream_t *stream); + +int MinxIO_FormatEEPROM(void); + +void MinxIO_Keypad(uint8_t key, int pressed); + +void MinxIO_BatteryLow(int low); + +void MinxIO_SetTimeStamp(uint8_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec); + +uint8_t MinxIO_ReadReg(int cpu, uint8_t reg); + +void MinxIO_WriteReg(int cpu, uint8_t reg, uint8_t val); + +#endif diff --git a/pm/src/core/MinxIRQ.c b/pm/src/core/MinxIRQ.c new file mode 100644 index 0000000..10e5ff4 --- /dev/null +++ b/pm/src/core/MinxIRQ.c @@ -0,0 +1,278 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "PokeMini.h" + +int MinxIRQ_MasterIRQ = 0; + +void MinxIRQ_Process(void); + +// +// Functions +// + +int MinxIRQ_Create(void) +{ + // Reset + MinxIRQ_Reset(1); + + return 1; +} + +void MinxIRQ_Destroy(void) +{ +} + +void MinxIRQ_Reset(int hardreset) +{ + // Master IRQ enable + MinxIRQ_MasterIRQ = 1; + PMR_IRQ_ACT1 = 0x00; + PMR_IRQ_ACT2 = 0x00; + PMR_IRQ_ACT3 = 0x00; + PMR_IRQ_ACT4 = 0x00; +} + +int MinxIRQ_LoadStateStream(memstream_t *stream, uint32_t bsize) +{ + POKELOADSS_START(1); + POKELOADSS_STREAM_8(MinxIRQ_MasterIRQ); + POKELOADSS_END(1); +} + +int MinxIRQ_SaveStateStream(memstream_t *stream) +{ + POKESAVESS_STREAM_START(1); + POKESAVESS_STREAM_8(MinxIRQ_MasterIRQ); + POKESAVESS_END(1); +} + +void MinxIRQ_SetIRQ(uint8_t intr) +{ + switch(intr) { + case 0x03: // PRC Copy Complete + PMR_IRQ_ACT1 |= 0x80; + break; + case 0x04: // PRC Frame Divider Overflow + PMR_IRQ_ACT1 |= 0x40; + break; + case 0x05: // Timer 2-B Underflow + PMR_IRQ_ACT1 |= 0x20; + break; + case 0x06: // Timer 2-A Underflow (8-Bits only) + PMR_IRQ_ACT1 |= 0x10; + break; + case 0x07: // Timer 1-B Underflow + PMR_IRQ_ACT1 |= 0x08; + break; + case 0x08: // Timer 1-A Underflow (8-Bits only) + PMR_IRQ_ACT1 |= 0x04; + break; + case 0x09: // Timer 3 Underflow + PMR_IRQ_ACT1 |= 0x02; + break; + case 0x0A: // Timer 3 Pivot + PMR_IRQ_ACT1 |= 0x01; + break; + case 0x0B: // 32 Hz + PMR_IRQ_ACT2 |= 0x20; + break; + case 0x0C: // 8 Hz + PMR_IRQ_ACT2 |= 0x10; + break; + case 0x0D: // 2 Hz + PMR_IRQ_ACT2 |= 0x08; + break; + case 0x0E: // 1 Hz + PMR_IRQ_ACT2 |= 0x04; + break; + case 0x0F: // IR Receiver + PMR_IRQ_ACT4 |= 0x80; + break; + case 0x10: // Shock Sensor + PMR_IRQ_ACT4 |= 0x40; + break; + case 0x13: // Cartridge Ejected + PMR_IRQ_ACT2 |= 0x02; + break; + case 0x14: // Cartridge IRQ + PMR_IRQ_ACT2 |= 0x01; + break; + case 0x15: // Power Key + PMR_IRQ_ACT3 |= 0x80; + break; + case 0x16: // Right Key + PMR_IRQ_ACT3 |= 0x40; + break; + case 0x17: // Left Key + PMR_IRQ_ACT3 |= 0x20; + break; + case 0x18: // Down Key + PMR_IRQ_ACT3 |= 0x10; + break; + case 0x19: // Up Key + PMR_IRQ_ACT3 |= 0x08; + break; + case 0x1A: // C Key + PMR_IRQ_ACT3 |= 0x04; + break; + case 0x1B: // B Key + PMR_IRQ_ACT3 |= 0x02; + break; + case 0x1C: // A Key + PMR_IRQ_ACT3 |= 0x01; + break; + } + MinxIRQ_Process(); +} + +uint8_t MinxIRQ_ReadReg(int cpu, uint8_t reg) +{ + // 0x20 to 0x2A + switch(reg) { + case 0x20: // IRQ Priority 1 + return PMR_IRQ_PRI1; + case 0x21: // IRQ Priority 2 + return PMR_IRQ_PRI2; + case 0x22: // IRQ Priority 3 + return PMR_IRQ_PRI3 & 0x03; + case 0x23: // IRQ Enable 1 + return PMR_IRQ_ENA1; + case 0x24: // IRQ Enable 2 + return PMR_IRQ_ENA2 & 0x3F; + case 0x25: // IRQ Enable 3 + return PMR_IRQ_ENA3; + case 0x26: // IRQ Enable 4 + return PMR_IRQ_ENA4 & 0xF7; + case 0x27: // IRQ Active 1 + return PMR_IRQ_ACT1; + case 0x28: // IRQ Active 2 + return PMR_IRQ_ACT2 & 0x3F; + case 0x29: // IRQ Active 3 + return PMR_IRQ_ACT3; + case 0x2A: // IRQ Active 4 + return PMR_IRQ_ACT4 & 0xF7; + default: // Unused + return 0; + } +} + +void MinxIRQ_WriteReg(int cpu, uint8_t reg, uint8_t val) +{ + // 0x20 to 0x2A + switch(reg) { + case 0x20: // IRQ Priority 1 + PMR_IRQ_PRI1 = val; + MinxIRQ_Process(); + return; + case 0x21: // IRQ Priority 2 + PMR_IRQ_PRI2 = val; + MinxIRQ_Process(); + return; + case 0x22: // IRQ Priority 3 + PMR_IRQ_PRI3 = val; + MinxIRQ_Process(); + return; + case 0x23: // IRQ Enable 1 + PMR_IRQ_ENA1 = val; + MinxIRQ_Process(); + return; + case 0x24: // IRQ Enable 2 + PMR_IRQ_ENA2 = val & 0x3F; + MinxIRQ_Process(); + return; + case 0x25: // IRQ Enable 3 + PMR_IRQ_ENA3 = val; + MinxIRQ_Process(); + return; + case 0x26: // IRQ Enable 4 + PMR_IRQ_ENA4 = val & 0xF7; + MinxIRQ_Process(); + return; + case 0x27: // IRQ Active 1 + if (cpu) PMR_IRQ_ACT1 &= ~val; + else PMR_IRQ_ACT1 = val; + return; + case 0x28: // IRQ Active 2 + if (cpu) PMR_IRQ_ACT2 &= ~val; + else PMR_IRQ_ACT2 = val & 0x3F; + return; + case 0x29: // IRQ Active 3 + if (cpu) PMR_IRQ_ACT3 &= ~val; + else PMR_IRQ_ACT3 = val; + return; + case 0x2A: // IRQ Active 4 + if (cpu) PMR_IRQ_ACT4 &= ~val; + else PMR_IRQ_ACT4 = val & 0xF7; + return; + default: // Unused + return; + } +} + +void MinxIRQ_Process(void) +{ + // TODO! Need to emulate the priority system... bah... + if (!MinxIRQ_MasterIRQ) return; + + if (PMR_IRQ_PRI1 & 0xC0) { + if ((PMR_IRQ_ENA1 & 0x80) && (PMR_IRQ_ACT1 & 0x80)) { MinxIRQ_OnIRQ(0x03); return; } + if ((PMR_IRQ_ENA1 & 0x40) && (PMR_IRQ_ACT1 & 0x40)) { MinxIRQ_OnIRQ(0x04); return; } + } + if (PMR_IRQ_PRI1 & 0x30) { + if ((PMR_IRQ_ENA1 & 0x20) && (PMR_IRQ_ACT1 & 0x20)) { MinxIRQ_OnIRQ(0x05); return; } + if ((PMR_IRQ_ENA1 & 0x10) && (PMR_IRQ_ACT1 & 0x10)) { MinxIRQ_OnIRQ(0x06); return; } + } + if (PMR_IRQ_PRI1 & 0x0C) { + if ((PMR_IRQ_ENA1 & 0x08) && (PMR_IRQ_ACT1 & 0x08)) { MinxIRQ_OnIRQ(0x07); return; } + if ((PMR_IRQ_ENA1 & 0x04) && (PMR_IRQ_ACT1 & 0x04)) { MinxIRQ_OnIRQ(0x08); return; } + } + if (PMR_IRQ_PRI1 & 0x03) { + if ((PMR_IRQ_ENA1 & 0x02) && (PMR_IRQ_ACT1 & 0x02)) { MinxIRQ_OnIRQ(0x09); return; } + if ((PMR_IRQ_ENA1 & 0x01) && (PMR_IRQ_ACT1 & 0x01)) { MinxIRQ_OnIRQ(0x0A); return; } + } + if (PMR_IRQ_PRI2 & 0xC0) { + if ((PMR_IRQ_ENA2 & 0x20) && (PMR_IRQ_ACT2 & 0x20)) { MinxIRQ_OnIRQ(0x0B); return; } + if ((PMR_IRQ_ENA2 & 0x10) && (PMR_IRQ_ACT2 & 0x10)) { MinxIRQ_OnIRQ(0x0C); return; } + if ((PMR_IRQ_ENA2 & 0x08) && (PMR_IRQ_ACT2 & 0x08)) { MinxIRQ_OnIRQ(0x0D); return; } + if ((PMR_IRQ_ENA2 & 0x04) && (PMR_IRQ_ACT2 & 0x04)) { MinxIRQ_OnIRQ(0x0E); return; } + } + if (PMR_IRQ_PRI3 & 0x03) { + if ((PMR_IRQ_ENA4 & 0x80) && (PMR_IRQ_ACT4 & 0x80)) { MinxIRQ_OnIRQ(0x0F); return; } + if ((PMR_IRQ_ENA4 & 0x40) && (PMR_IRQ_ACT4 & 0x40)) { MinxIRQ_OnIRQ(0x10); return; } + } + if (PMR_IRQ_PRI2 & 0x30) { + if ((PMR_IRQ_ENA2 & 0x02) && (PMR_IRQ_ACT2 & 0x02)) { MinxIRQ_OnIRQ(0x13); return; } + if ((PMR_IRQ_ENA2 & 0x01) && (PMR_IRQ_ACT2 & 0x01)) { MinxIRQ_OnIRQ(0x14); return; } + } + if (PMR_IRQ_PRI2 & 0x0C) { + if ((PMR_IRQ_ENA3 & 0x80) && (PMR_IRQ_ACT3 & 0x80)) { MinxIRQ_OnIRQ(0x15); return; } + if ((PMR_IRQ_ENA3 & 0x40) && (PMR_IRQ_ACT3 & 0x40)) { MinxIRQ_OnIRQ(0x16); return; } + if ((PMR_IRQ_ENA3 & 0x20) && (PMR_IRQ_ACT3 & 0x20)) { MinxIRQ_OnIRQ(0x17); return; } + if ((PMR_IRQ_ENA3 & 0x10) && (PMR_IRQ_ACT3 & 0x10)) { MinxIRQ_OnIRQ(0x18); return; } + if ((PMR_IRQ_ENA3 & 0x08) && (PMR_IRQ_ACT3 & 0x08)) { MinxIRQ_OnIRQ(0x19); return; } + if ((PMR_IRQ_ENA3 & 0x04) && (PMR_IRQ_ACT3 & 0x04)) { MinxIRQ_OnIRQ(0x1A); return; } + if ((PMR_IRQ_ENA3 & 0x02) && (PMR_IRQ_ACT3 & 0x02)) { MinxIRQ_OnIRQ(0x1B); return; } + if ((PMR_IRQ_ENA3 & 0x01) && (PMR_IRQ_ACT3 & 0x01)) { MinxIRQ_OnIRQ(0x1C); return; } + } + if (PMR_IRQ_PRI2 & 0x03) { + if ((PMR_IRQ_ENA4 & 0x04) && (PMR_IRQ_ACT4 & 0x04)) { MinxIRQ_OnIRQ(0x1D); return; } + if ((PMR_IRQ_ENA4 & 0x02) && (PMR_IRQ_ACT4 & 0x02)) { MinxIRQ_OnIRQ(0x1E); return; } + if ((PMR_IRQ_ENA4 & 0x01) && (PMR_IRQ_ACT4 & 0x01)) { MinxIRQ_OnIRQ(0x1F); return; } + } +} diff --git a/pm/src/core/MinxIRQ.h b/pm/src/core/MinxIRQ.h new file mode 100644 index 0000000..e97864d --- /dev/null +++ b/pm/src/core/MinxIRQ.h @@ -0,0 +1,53 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXHW_IRQ +#define MINXHW_IRQ + +#include +#include + +// Master IRQ enable +extern int MinxIRQ_MasterIRQ; + + +int MinxIRQ_Create(void); + +void MinxIRQ_Destroy(void); + +void MinxIRQ_Reset(int hardreset); + +int MinxIRQ_LoadStateStream(memstream_t *stream, uint32_t bsize); + +int MinxIRQ_SaveStateStream(memstream_t *stream); + +void MinxIRQ_SetIRQ(uint8_t intr); + +uint8_t MinxIRQ_ReadReg(int cpu, uint8_t reg); + +void MinxIRQ_WriteReg(int cpu, uint8_t reg, uint8_t val); + +void MinxIRQ_Process(void); + +// +// Callbacks (Written by the user) +// + +void MinxIRQ_OnIRQ(uint8_t intr); + +#endif diff --git a/pm/src/core/MinxLCD.c b/pm/src/core/MinxLCD.c new file mode 100644 index 0000000..e9bdfce --- /dev/null +++ b/pm/src/core/MinxLCD.c @@ -0,0 +1,612 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2014 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "PokeMini.h" +/* PokeMiniEmu: Video.h left out (no host video); its Interpolate8 here */ +static INLINE int Interpolate8(int a, int b, int pos) +{ + return ((255 - pos) * a + pos * b) >> 8; +} + +TMinxLCD MinxLCD; +int LCDDirty = 0; +uint8_t *LCDData = NULL; +uint8_t *LCDPixelsD = NULL; +uint8_t *LCDPixelsA = NULL; +uint8_t *LCDPixelsAS = NULL; + +const int LCDDirtyPixels[4] = { + 4, // LCDMODE_ANALOG + 2, // LCDMODE_3SHADES + 1, // LCDMODE_2SHADES + 2 // LCDMODE_COLORS +}; + +// +// Functions +// + +int MinxLCD_Create(void) +{ + // Create LCD memory + LCDData = (uint8_t *)malloc(256*9); + if (!LCDData) return 0; + LCDPixelsD = (uint8_t *)malloc(96*64); + if (!LCDPixelsD) return 0; + LCDPixelsA = (uint8_t *)malloc(96*64*2); + if (!LCDPixelsA) return 0; + LCDPixelsAS = (uint8_t *)LCDPixelsA + 96*64; + + // Reset + MinxLCD_Reset(1); + + return 1; +} + +void MinxLCD_Destroy(void) +{ + if (LCDData) { + free(LCDData); + LCDData = NULL; + } + if (LCDPixelsD) { + free(LCDPixelsD); + LCDPixelsD = NULL; + } + if (LCDPixelsA) { + free(LCDPixelsA); + LCDPixelsA = NULL; + } +} + +void MinxLCD_Reset(int hardreset) +{ + // Clean up memory + memset(LCDData, 0x00, 256*9); + memset(LCDPixelsD, 0x00, 96*64); + memset(LCDPixelsA, 0x00, 96*64*2); + + // Initialize State + memset((void *)&MinxLCD, 0, sizeof(TMinxLCD)); + + // Initialize variables + MinxLCD_SetContrast(0x1F); +} + +int MinxLCD_LoadStateStream(memstream_t *stream, uint32_t bsize) +{ + POKELOADSS_START(256*9 + 96*64 + 96*64 + 64); + POKELOADSS_STREAM_A(LCDData, 256*9); + POKELOADSS_STREAM_A(LCDPixelsD, 96*64); + POKELOADSS_STREAM_A(LCDPixelsA, 96*64); + POKELOADSS_STREAM_32(MinxLCD.Pixel0Intensity); + POKELOADSS_STREAM_32(MinxLCD.Pixel1Intensity); + POKELOADSS_STREAM_8(MinxLCD.Column); + POKELOADSS_STREAM_8(MinxLCD.StartLine); + POKELOADSS_STREAM_8(MinxLCD.SetContrast); + POKELOADSS_STREAM_8(MinxLCD.Contrast); + POKELOADSS_STREAM_8(MinxLCD.SegmentDir); + POKELOADSS_STREAM_8(MinxLCD.MaxContrast); + POKELOADSS_STREAM_8(MinxLCD.SetAllPix); + POKELOADSS_STREAM_8(MinxLCD.InvAllPix); + POKELOADSS_STREAM_8(MinxLCD.DisplayOn); + POKELOADSS_STREAM_8(MinxLCD.Page); + POKELOADSS_STREAM_8(MinxLCD.RowOrder); + POKELOADSS_STREAM_8(MinxLCD.ReadModifyMode); + POKELOADSS_STREAM_8(MinxLCD.RequireDummyR); + POKELOADSS_STREAM_8(MinxLCD.RMWColumn); + POKELOADSS_STREAM_X(42); + POKELOADSS_END(256*9 + 96*64 + 96*64 + 64); +} + +int MinxLCD_SaveStateStream(memstream_t *stream) +{ + POKESAVESS_STREAM_START(256*9 + 96*64 + 96*64 + 64); + POKESAVESS_STREAM_A(LCDData, 256*9); + POKESAVESS_STREAM_A(LCDPixelsD, 96*64); + POKESAVESS_STREAM_A(LCDPixelsA, 96*64); + POKESAVESS_STREAM_32(MinxLCD.Pixel0Intensity); + POKESAVESS_STREAM_32(MinxLCD.Pixel1Intensity); + POKESAVESS_STREAM_8(MinxLCD.Column); + POKESAVESS_STREAM_8(MinxLCD.StartLine); + POKESAVESS_STREAM_8(MinxLCD.SetContrast); + POKESAVESS_STREAM_8(MinxLCD.Contrast); + POKESAVESS_STREAM_8(MinxLCD.SegmentDir); + POKESAVESS_STREAM_8(MinxLCD.MaxContrast); + POKESAVESS_STREAM_8(MinxLCD.SetAllPix); + POKESAVESS_STREAM_8(MinxLCD.InvAllPix); + POKESAVESS_STREAM_8(MinxLCD.DisplayOn); + POKESAVESS_STREAM_8(MinxLCD.Page); + POKESAVESS_STREAM_8(MinxLCD.RowOrder); + POKESAVESS_STREAM_8(MinxLCD.ReadModifyMode); + POKESAVESS_STREAM_8(MinxLCD.RequireDummyR); + POKESAVESS_STREAM_8(MinxLCD.RMWColumn); + POKESAVESS_STREAM_X(42); + POKESAVESS_END(256*9 + 96*64 + 96*64 + 64); +} + +uint8_t MinxLCD_ReadReg(int cpu, uint8_t reg) +{ + // 0xFE to 0xFF + switch(reg) { + case 0xFE: // Read from LCD with Control Activated + return MinxLCD_LCDReadCtrl(cpu); + case 0xFF: // Read from LCD with Control Desactivated + return MinxLCD_LCDRead(cpu); + default: // Unused + return 0x00; + } +} + +void MinxLCD_WriteReg(int cpu, uint8_t reg, uint8_t val) +{ + // 0xFE to 0xFF + switch(reg) { + case 0xFE: // Write to LCD with Control Activated + MinxLCD_LCDWriteCtrl(val); + return; + case 0xFF: // Write to LCD with Control Desactivated + MinxLCD_LCDWrite(val); + return; + } +} + +#define DECAY_A_OFF 64 +#define DECAY_ARISE 50 +#define DECAY_AFALL 30 +#define DECAY_L_OFF 16 +#define DECAY_LRISE 4 +#define DECAY_LFALL 2 + +void MinxLCD_DecayRefreshOld(void) +{ + int i, amt; + if (MinxLCD.DisplayOn) { + for (i=0; i<96*64; i++) { + if (LCDPixelsD[i]) { + amt = Interpolate8(LCDPixelsA[i], MinxLCD.Pixel1Intensity, DECAY_ARISE) + DECAY_LRISE; + if (amt > MinxLCD.Pixel1Intensity) amt = MinxLCD.Pixel1Intensity; + } else { + amt = Interpolate8(LCDPixelsA[i], MinxLCD.Pixel0Intensity, DECAY_AFALL) - DECAY_LFALL; + if (amt < MinxLCD.Pixel0Intensity) amt = MinxLCD.Pixel0Intensity; + } + LCDPixelsA[i] = amt; + } + } else { + for (i=0; i<96*64; i++) { + amt = Interpolate8(LCDPixelsA[i], 0, DECAY_A_OFF) - DECAY_L_OFF; + if (amt < MinxLCD.Pixel0Intensity) amt = MinxLCD.Pixel0Intensity; + LCDPixelsA[i] = amt; + } + } +} + +static const uint8_t BitsActives[256] = { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 +}; + +void MinxLCD_DecayRefresh(void) +{ + int i, level; + uint8_t sh; + // This is tuned for 5 shades + if (MinxLCD.DisplayOn) { + for (i=0; i<96*64; i++) { + sh = (LCDPixelsD[i] ? 0x08 : 0x00) | (LCDPixelsAS[i] >> 1); + LCDPixelsAS[i] = sh; + level = BitsActives[sh]; + LCDPixelsA[i] = (MinxLCD.Pixel0Intensity * (4 - level) + MinxLCD.Pixel1Intensity * level) >> 2; + } + } else { + for (i=0; i<96*64; i++) { + sh = (LCDPixelsAS[i] >> 1); + LCDPixelsAS[i] = sh; + level = BitsActives[sh]; + LCDPixelsA[i] = (MinxLCD.Pixel0Intensity * (4 - level) + MinxLCD.Pixel1Intensity * level) >> 2; + } + } +} + +void MinxLCD_Render(void) +{ + uint8_t pixel; + int xC, yC, yP; + + if (MinxLCD.DisplayOn) { + for (yC=0; yC<64; yC++) { + yP = (yC + MinxLCD.StartLine) & 63; + if (MinxLCD.RowOrder) yP = 63 - yP; + for (xC=0; xC<96; xC++) { + pixel = (LCDData[((yP >> 3) * 256) + xC] >> (yP & 7)) & 1; + LCDPixelsD[(yC * 96) + xC] = (pixel ^ MinxLCD.InvAllPix) | MinxLCD.SetAllPix; + } + } + } else for (yC=0; yC<96*64; yC++) LCDPixelsD[yC] = 0; +} + +uint8_t MinxLCD_LCDReadCtrl(int cpu) +{ + uint8_t data; + if (MinxLCD.SetContrast) { + MinxLCD.SetContrast = 0; + // Contrast query, cause incorrect value? + MinxLCD_SetContrast(0x3F); + data = 0; + } else { + // Get status + data = 0x40 | (MinxLCD.DisplayOn ? 0x20 : 0x00); + } + return data; +} + +uint8_t MinxLCD_LCDRead(int cpu) +{ + static uint8_t data = 0x40; + if (MinxLCD.SetContrast) { + MinxLCD.SetContrast = 0; + // Contrast query, cause incorrect value? + MinxLCD_SetContrast(0x3F); + data = 0; + } else { + // Get pixel + if (!MinxLCD.RequireDummyR && cpu) { + if (MinxLCD.SegmentDir) { + data = LCDData[131 - MinxLCD.Column + (MinxLCD.Page << 8)]; + } else { + data = LCDData[MinxLCD.Column + (MinxLCD.Page << 8)]; + } + if (MinxLCD.Page >= 8) data &= 0x01; + if (!MinxLCD.ReadModifyMode) { + MinxLCD.Column++; + if (MinxLCD.Column > 131) MinxLCD.Column = 131; + MinxLCD.RequireDummyR = 1; + } + } else MinxLCD.RequireDummyR = 0; + } + return data; +} + +void MinxLCD_LCDWriteCtrl(uint8_t data) +{ + if (MinxLCD.SetContrast) { + MinxLCD.SetContrast = 0; + MinxLCD_SetContrast(data & 0x3F); + return; + } + switch(data) { + case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: + if (!MinxLCD.ReadModifyMode) { + MinxLCD.Column = (MinxLCD.Column & 0xF0) | (data & 0x0F); + MinxLCD.RequireDummyR = 1; + } + return; + case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: + if (!MinxLCD.ReadModifyMode) { + MinxLCD.Column = (MinxLCD.Column & 0x0F) | ((data & 0x0F) << 4); + MinxLCD.RequireDummyR = 1; + } + return; + case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: + // Do nothing? + return; + case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: + // Modify LCD voltage? (2F Default) + // 0x28 = Blank + // 0x29 = Blank + // 0x2A = Blue screen then blank + // 0x2B = Blank + // 0x2C = Blank + // 0x2D = Blank + // 0x2E = Blue screen (overpower?) + // 0x2F = Normal + // User shouldn't mess with this ones as may damage the LCD + return; + case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: + case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: + // Do nothing? + return; + case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: + case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: + case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: + case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: + case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: + case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: + case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: + case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: + // Set starting LCD scanline (cause warp around) + MinxLCD.StartLine = data - 0x40; + LCDDirty = MINX_DIRTYSCR; + return; + case 0x80: + // Do nothing? + return; + case 0x81: + // Set contrast at the next write + MinxLCD.SetContrast = 1; + return; + case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: + case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: + // Do nothing? + return; + case 0xA0: + // Segment Driver Direction Select: Normal + MinxLCD.SegmentDir = 0; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xA1: + // Segment Driver Direction Select: Reverse + MinxLCD.SegmentDir = 1; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xA2: + // Max Contrast: Disable + MinxLCD.MaxContrast = 0; + MinxLCD_SetContrast(MinxLCD.Contrast); + return; + case 0xA3: + // Max Contrast: Enable + MinxLCD.MaxContrast = 1; + MinxLCD_SetContrast(MinxLCD.Contrast); + return; + case 0xA4: + // Set All Pixels: Disable + MinxLCD.SetAllPix = 0; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xA5: + // Set All Pixels: Enable + MinxLCD.SetAllPix = 1; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xA6: + // Invert All Pixels: Disable + MinxLCD.InvAllPix = 0; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xA7: + // Invert All Pixels: Enable + MinxLCD.InvAllPix = 1; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xA8: case 0xA9: case 0xAA: case 0xAB: + // Do nothing!? + return; + case 0xAC: case 0xAD: + // User shouldn't mess with this ones as may damage the LCD + return; + case 0xAE: + // Display Off + MinxLCD.DisplayOn = 0; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xAF: + // Display On + MinxLCD.DisplayOn = 1; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: + case 0xB8: + // Set page (0-8, each page is 8px high) + MinxLCD.Page = data & 15; + return; + case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: + // uh... do nothing? + return; + case 0xC0: case 0xC1: case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: + // Display rows from top to bottom as 0 to 63 + MinxLCD.RowOrder = 0; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: + // Display rows from top to bottom as 63 to 0 + MinxLCD.RowOrder = 1; + LCDDirty = MINX_DIRTYSCR; + return; + case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: + case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: + // Do nothing? + return; + case 0xE0: + // Start "Read Modify Write" + MinxLCD.ReadModifyMode = 1; + MinxLCD.RMWColumn = MinxLCD.Column; + return; + case 0xE2: + // Reset + MinxLCD.SetContrast = 0; + MinxLCD_SetContrast(0x20); + MinxLCD.Column = 0; + MinxLCD.StartLine = 0; + MinxLCD.SegmentDir = 0; + MinxLCD.MaxContrast = 0; + MinxLCD.SetAllPix = 0; + MinxLCD.InvAllPix = 0; + MinxLCD.DisplayOn = 0; + MinxLCD.Page = 0; + MinxLCD.RowOrder = 0; + MinxLCD.ReadModifyMode = 0; + MinxLCD.RequireDummyR = 1; + MinxLCD.RMWColumn = 0; + return; + case 0xE3: + // No operation + return; + case 0xEE: + // End "Read Modify Write" + MinxLCD.ReadModifyMode = 0; + MinxLCD.Column = MinxLCD.RMWColumn; + return; + case 0xE1: case 0xE4: case 0xE5: case 0xE6: case 0xE7: + case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEF: + // User shouldn't mess with this ones as may damage the LCD + return; + case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: case 0xF5: case 0xF6: case 0xF7: + // 0xF1 and 0xF5 freeze LCD and cause malfunction (need to power off the device to restore) + // User shouldn't mess with this ones as may damage the LCD + return; + case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFD: case 0xFE: case 0xFF: + // Contrast voltage control, FC = Default + // User shouldn't mess with this ones as may damage the LCD + return; + } +} + +void MinxLCD_LCDWrite(uint8_t data) +{ + int addr; + if (MinxLCD.SetContrast) { + MinxLCD.SetContrast = 0; + // Set contrast + MinxLCD_SetContrast(data & 0x3F); + } else { + // Set pixel + if (MinxLCD.SegmentDir) { + addr = 131 - MinxLCD.Column + (MinxLCD.Page << 8); + } else { + addr = MinxLCD.Column + (MinxLCD.Page << 8); + } + LCDData[addr] = data; + if (PRCColorMap) MinxColorPRC_WriteLCD(addr, data); + MinxLCD.Column++; + if (MinxLCD.Column > 131) MinxLCD.Column = 131; + MinxLCD.RequireDummyR = 1; + LCDDirty = LCDDirtyPixels[PokeMini_LCDMode]; + } +} + +void MinxLCD_LCDWritefb(uint8_t *fb) +{ + int i; + uint8_t *dst = (uint8_t *)LCDData, pages = 8; + if (MinxLCD.SegmentDir) { + while (pages--) { + for (i=0; i<96; i++) dst[131-i] = fb[i]; + dst += 256; fb += 96; + } + } else { + while (pages--) { + memcpy(dst, fb, 96); + dst += 256; fb += 96; + } + } + MinxLCD.Page = 7; + MinxLCD.Column = 96; + MinxLCD.RequireDummyR = 1; + MinxLCD.ReadModifyMode = 0; + LCDDirty = LCDDirtyPixels[PokeMini_LCDMode]; +} + +// Contrast level on light and dark pixel +const uint8_t MinxLCD_ContrastLvl[64][2] = { + { 0, 4}, // 0 (0x00) + { 0, 4}, // 1 (0x01) + { 0, 4}, // 2 (0x02) + { 0, 4}, // 3 (0x03) + { 0, 6}, // 4 (0x04) + { 0, 11}, // 5 (0x05) + { 0, 17}, // 6 (0x06) + { 0, 24}, // 7 (0x07) + { 0, 31}, // 8 (0x08) + { 0, 40}, // 9 (0x09) + { 0, 48}, // 10 (0x0A) + { 0, 57}, // 11 (0x0B) + { 0, 67}, // 12 (0x0C) + { 0, 77}, // 13 (0x0D) + { 0, 88}, // 14 (0x0E) + { 0, 99}, // 15 (0x0F) + { 0, 110}, // 16 (0x10) + { 0, 122}, // 17 (0x11) + { 0, 133}, // 18 (0x12) + { 0, 146}, // 19 (0x13) + { 0, 158}, // 20 (0x14) + { 0, 171}, // 21 (0x15) + { 0, 184}, // 22 (0x16) + { 0, 198}, // 23 (0x17) + { 0, 212}, // 24 (0x18) + { 0, 226}, // 25 (0x19) + { 0, 240}, // 26 (0x1A) + { 0, 255}, // 27 (0x1B) + { 2, 255}, // 28 (0x1C) + { 5, 255}, // 29 (0x1D) + { 10, 255}, // 30 (0x1E) + { 15, 255}, // 31 (0x1F) + { 21, 255}, // 32 (0x20) + { 27, 255}, // 33 (0x21) + { 34, 255}, // 34 (0x22) + { 41, 255}, // 35 (0x23) + { 48, 255}, // 36 (0x24) + { 56, 255}, // 37 (0x25) + { 64, 255}, // 38 (0x26) + { 73, 255}, // 39 (0x27) + { 81, 255}, // 40 (0x28) + { 90, 255}, // 41 (0x29) + {100, 255}, // 42 (0x2A) + {109, 255}, // 43 (0x2B) + {119, 255}, // 44 (0x2C) + {129, 255}, // 45 (0x2D) + {139, 255}, // 46 (0x2E) + {149, 255}, // 47 (0x2F) + {160, 255}, // 48 (0x30) + {171, 255}, // 49 (0x31) + {182, 255}, // 50 (0x32) + {193, 255}, // 51 (0x33) + {204, 255}, // 52 (0x34) + {216, 255}, // 53 (0x35) + {228, 255}, // 54 (0x36) + {240, 255}, // 55 (0x37) + {240, 255}, // 56 (0x38) + {240, 255}, // 57 (0x39) + {240, 255}, // 58 (0x3A) + {240, 255}, // 59 (0x3B) + {240, 255}, // 60 (0x3C) + {240, 255}, // 61 (0x3D) + {240, 255}, // 62 (0x3E) + {240, 255}, // 63 (0x3F) +}; + +void MinxLCD_SetContrast(uint8_t value) +{ + MinxLCD.Contrast = value & 0x3F; + if (MinxLCD.MaxContrast) { + MinxLCD.Pixel0Intensity = 240; + MinxLCD.Pixel1Intensity = 255; + } else { + MinxLCD.Pixel0Intensity = MinxLCD_ContrastLvl[MinxLCD.Contrast][0]; + MinxLCD.Pixel1Intensity = MinxLCD_ContrastLvl[MinxLCD.Contrast][1]; + } + LCDDirty = MINX_DIRTYSCR; +} diff --git a/pm/src/core/MinxLCD.h b/pm/src/core/MinxLCD.h new file mode 100644 index 0000000..d4aa382 --- /dev/null +++ b/pm/src/core/MinxLCD.h @@ -0,0 +1,99 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXHW_LCD +#define MINXHW_LCD + +#include +#include + +typedef struct { + // Internal processing + int32_t Pixel0Intensity; // Pixel 0 Intensity + int32_t Pixel1Intensity; // Pixel 1 Intensity + uint8_t Column; // Column + uint8_t StartLine; // Start line + uint8_t SetContrast; // Set contrast + uint8_t Contrast; // Contrast level + uint8_t SegmentDir; // Segment Driver Direction Select + uint8_t MaxContrast; // Max Contrast + uint8_t SetAllPix; // Set All Pixels + uint8_t InvAllPix; // Invert All Pixels + uint8_t DisplayOn; // Display On + uint8_t Page; // Page + uint8_t RowOrder; // 0 = Top to bottom, 1 = Bottom to top + uint8_t ReadModifyMode; // Read Modify Write mode + uint8_t RequireDummyR; // Require Dummy Read + uint8_t RMWColumn; // Column when Read Modify Write started +} TMinxLCD; + +#ifndef MINX_DIRTYPIX +#define MINX_DIRTYPIX 4 +#endif + +#ifndef MINX_DIRTYSCR +#define MINX_DIRTYSCR 4 +#endif + +// Export LCD state +extern TMinxLCD MinxLCD; + +// LCD dirty status (1+ = graphics changed) +extern int LCDDirty; + +// LCD Data (132 x 65 x 1bpp), Pitch of 256 bytes +extern uint8_t *LCDData; + +// LCD Pixels Digital (96 x 64, 0 or 1) +extern uint8_t *LCDPixelsD; + +// LCD Pixels Analog (96 x 64, 0 to 255) +extern uint8_t *LCDPixelsA; + + +int MinxLCD_Create(void); + +void MinxLCD_Destroy(void); + +void MinxLCD_Reset(int hardreset); + +int MinxLCD_LoadStateStream(memstream_t *stream, uint32_t bsize); + +int MinxLCD_SaveStateStream(memstream_t *stream); + +uint8_t MinxLCD_ReadReg(int cpu, uint8_t reg); + +void MinxLCD_WriteReg(int cpu, uint8_t reg, uint8_t val); + +void MinxLCD_DecayRefresh(void); + +void MinxLCD_Render(void); + +uint8_t MinxLCD_LCDReadCtrl(int cpu); + +uint8_t MinxLCD_LCDRead(int cpu); + +void MinxLCD_LCDWriteCtrl(uint8_t data); + +void MinxLCD_LCDWrite(uint8_t data); + +void MinxLCD_LCDWritefb(uint8_t *fb); + +void MinxLCD_SetContrast(uint8_t value); + +#endif diff --git a/pm/src/core/MinxPRC.c b/pm/src/core/MinxPRC.c new file mode 100644 index 0000000..40ce7cd --- /dev/null +++ b/pm/src/core/MinxPRC.c @@ -0,0 +1,407 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include "PokeMini.h" + +TMinxPRC MinxPRC; +int PRCAllowStall = 1; // Allow stall CPU? +int StallCPU = 0; // Stall CPU output flag +int PRCRenderBD = 0; // Render backdrop? (Background overrides backdrop) +int PRCRenderBG = 1; // Render background? +int PRCRenderSpr = 1; // Render sprites? + +const uint8_t PRCInvertBit[256] = { // Invert Bit table + 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, + 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, + 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, + 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, + 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, + 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, + 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, + 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, + 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, + 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, + 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, + 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, + 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, + 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, + 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, + 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF +}; + +#ifdef PERFORMANCE +int StallCycles = 64; // Stall CPU cycles +#else +int StallCycles = 32; // Stall CPU cycles +#endif + +TMinxPRC_Render MinxPRC_Render = MinxPRC_Render_Mono; + +// +// Functions +// + +int MinxPRC_Create(void) +{ + // Reset + MinxPRC_Reset(1); + + return 1; +} + +void MinxPRC_Destroy(void) +{ +} + +void MinxPRC_Reset(int hardreset) +{ + // Initialize State + memset((void *)&MinxPRC, 0, sizeof(TMinxPRC)); + + // Initialize variables + StallCPU = 0; + MinxPRC.PRCRateMatch = 0x10; +} + +int MinxPRC_LoadStateStream(memstream_t *stream, uint32_t bsize) +{ + POKELOADSS_START(1+32); + POKELOADSS_STREAM_8(StallCPU); + POKELOADSS_STREAM_32(MinxPRC.PRCCnt); + POKELOADSS_STREAM_32(MinxPRC.PRCBGBase); + POKELOADSS_STREAM_32(MinxPRC.PRCSprBase); + POKELOADSS_STREAM_8(MinxPRC.PRCMode); + POKELOADSS_STREAM_8(MinxPRC.PRCRateMatch); + POKELOADSS_STREAM_8(MinxPRC.PRCMapPX); + POKELOADSS_STREAM_8(MinxPRC.PRCMapPY); + POKELOADSS_STREAM_8(MinxPRC.PRCMapTW); + POKELOADSS_STREAM_8(MinxPRC.PRCMapTH); + POKELOADSS_STREAM_8(MinxPRC.PRCState); + POKELOADSS_STREAM_X(13); + POKELOADSS_END(1+32); +} + +int MinxPRC_SaveStateStream(memstream_t *stream) +{ + POKESAVESS_STREAM_START(1+32); + POKESAVESS_STREAM_8(StallCPU); + POKESAVESS_STREAM_32(MinxPRC.PRCCnt); + POKESAVESS_STREAM_32(MinxPRC.PRCBGBase); + POKESAVESS_STREAM_32(MinxPRC.PRCSprBase); + POKESAVESS_STREAM_8(MinxPRC.PRCMode); + POKESAVESS_STREAM_8(MinxPRC.PRCRateMatch); + POKESAVESS_STREAM_8(MinxPRC.PRCMapPX); + POKESAVESS_STREAM_8(MinxPRC.PRCMapPY); + POKESAVESS_STREAM_8(MinxPRC.PRCMapTW); + POKESAVESS_STREAM_8(MinxPRC.PRCMapTH); + POKESAVESS_STREAM_8(MinxPRC.PRCState); + POKESAVESS_STREAM_X(13); + POKESAVESS_END(1+32); +} + +void MinxPRC_Sync(void) +{ + // Process PRC Counter + MinxPRC.PRCCnt += MINX_PRCTIMERINC * PokeHWCycles; + if ((PMR_PRC_RATE & 0xF0) >= MinxPRC.PRCRateMatch) { + // Active frame + if (MinxPRC.PRCCnt < 0x18000000) { + // CPU Time + MinxPRC.PRCState = 0; + } else if ((MinxPRC.PRCCnt & 0xFF000000) == 0x18000000) { + // PRC BG&SPR Trigger + if (MinxPRC.PRCState == 1) return; + if (MinxPRC.PRCMode == 2) { + if (PRCAllowStall) StallCPU = 1; + MinxPRC_Render(); + MinxPRC.PRCState = 1; + } else if (PRCColorMap) MinxPRC_NoRender_Color(); + } else if ((MinxPRC.PRCCnt & 0xFF000000) == 0x39000000) { + // PRC Copy Trigger + if (MinxPRC.PRCState == 2) return; + if (MinxPRC.PRCMode) { + if (PRCAllowStall) StallCPU = 1; + MinxPRC_CopyToLCD(); + MinxCPU_OnIRQAct(MINX_INTR_03); + MinxPRC.PRCState = 2; + } + } else if (MinxPRC.PRCCnt >= 0x42000000) { + // End-of-frame + StallCPU = 0; + PMR_PRC_RATE &= 0x0F; + MinxPRC.PRCCnt = 0x01000000; + MinxCPU_OnIRQAct(MINX_INTR_04); + MinxPRC_On72HzRefresh(1); + } + } else { + // Non-active frame + if (MinxPRC.PRCCnt >= 0x42000000) { + PMR_PRC_RATE += 0x10; + MinxPRC.PRCCnt = 0x01000000; + MinxPRC_On72HzRefresh(0); + } + } +} + +uint8_t MinxPRC_ReadReg(uint8_t reg) +{ + // 0x80 to 0x8F + switch(reg) { + case 0x80: // PRC Stage Control + return PMR_PRC_MODE & 0x3F; + case 0x81: // PRC Rate Control + return PMR_PRC_RATE; + case 0x82: // PRC Map Tile Base (Lo) + return PMR_PRC_MAP_LO & 0xF8; + case 0x83: // PRC Map Tile Base (Med) + return PMR_PRC_MAP_MID; + case 0x84: // PRC Map Tile Base (Hi) + return PMR_PRC_MAP_HI & 0x1F; + case 0x85: // PRC Map Vertical Scroll + return PMR_PRC_SCROLL_Y & 0x7F; + case 0x86: // PRC Map Horizontal Scroll + return PMR_PRC_SCROLL_X & 0x7F; + case 0x87: // PRC Map Sprite Base (Lo) + return PMR_PRC_SPR_LO & 0xC0; + case 0x88: // PRC Map Sprite Base (Med) + return PMR_PRC_SPR_MID; + case 0x89: // PRC Map Sprite Base (Hi) + return PMR_PRC_SPR_HI & 0x1F; + case 0x8A: // PRC Counter + return MinxPRC.PRCCnt >> 24; + default: // Unused + return 0; + } +} + +void MinxPRC_WriteReg(uint8_t reg, uint8_t val) +{ + // 0x80 to 0x8F + switch(reg) { + case 0x80: // PRC Stage Control + PMR_PRC_MODE = val & 0x3F; + if (val & 0x08) { + MinxPRC.PRCMode = (val & 0x06) ? 2 : 1; + } else MinxPRC.PRCMode = 0; + switch (val & 0x30) { + case 0x00: MinxPRC.PRCMapTW = 12; MinxPRC.PRCMapTH = 16; break; + case 0x10: MinxPRC.PRCMapTW = 16; MinxPRC.PRCMapTH = 12; break; + case 0x20: MinxPRC.PRCMapTW = 24; MinxPRC.PRCMapTH = 8; break; + case 0x30: MinxPRC.PRCMapTW = 24; MinxPRC.PRCMapTH = 16; break; + } + return; + case 0x81: // PRC Rate Control + if ((PMR_PRC_RATE & 0x0E) != (val & 0x0E)) PMR_PRC_RATE = (val & 0x0F); + else PMR_PRC_RATE = (PMR_PRC_RATE & 0xF0) | (val & 0x0F); + switch (val & 0x0E) { + case 0x00: MinxPRC.PRCRateMatch = 0x20; break; // Rate /3 + case 0x02: MinxPRC.PRCRateMatch = 0x50; break; // Rate /6 + case 0x04: MinxPRC.PRCRateMatch = 0x80; break; // Rate /9 + case 0x06: MinxPRC.PRCRateMatch = 0xB0; break; // Rate /12 + case 0x08: MinxPRC.PRCRateMatch = 0x10; break; // Rate /2 + case 0x0A: MinxPRC.PRCRateMatch = 0x30; break; // Rate /4 + case 0x0C: MinxPRC.PRCRateMatch = 0x50; break; // Rate /6 + case 0x0E: MinxPRC.PRCRateMatch = 0x70; break; // Rate /8 + } + return; + case 0x82: // PRC Map Tile Base Low + PMR_PRC_MAP_LO = val & 0xF8; + MinxPRC.PRCBGBase = (MinxPRC.PRCBGBase & 0x1FFF00) | PMR_PRC_MAP_LO; + return; + case 0x83: // PRC Map Tile Base Middle + PMR_PRC_MAP_MID = val; + MinxPRC.PRCBGBase = (MinxPRC.PRCBGBase & 0x1F00F8) | (PMR_PRC_MAP_MID << 8); + return; + case 0x84: // PRC Map Tile Base High + PMR_PRC_MAP_HI = val & 0x1F; + MinxPRC.PRCBGBase = (MinxPRC.PRCBGBase & 0x00FFF8) | (PMR_PRC_MAP_HI << 16); + return; + case 0x85: // PRC Map Vertical Scroll + PMR_PRC_SCROLL_Y = val & 0x7F; + if (PMR_PRC_SCROLL_Y <= (MinxPRC.PRCMapTH*8-64)) MinxPRC.PRCMapPY = PMR_PRC_SCROLL_Y; + return; + case 0x86: // PRC Map Horizontal Scroll + PMR_PRC_SCROLL_X = val & 0x7F; + if (PMR_PRC_SCROLL_X <= (MinxPRC.PRCMapTW*8-96)) MinxPRC.PRCMapPX = PMR_PRC_SCROLL_X; + return; + case 0x87: // PRC Sprite Tile Base Low + PMR_PRC_SPR_LO = val & 0xC0; + MinxPRC.PRCSprBase = (MinxPRC.PRCSprBase & 0x1FFF00) | PMR_PRC_SPR_LO; + return; + case 0x88: // PRC Sprite Tile Base Middle + PMR_PRC_SPR_MID = val; + MinxPRC.PRCSprBase = (MinxPRC.PRCSprBase & 0x1F00C0) | (PMR_PRC_SPR_MID << 8); + return; + case 0x89: // PRC Sprite Tile Base High + PMR_PRC_SPR_HI = val & 0x1F; + MinxPRC.PRCSprBase = (MinxPRC.PRCSprBase & 0x00FFC0) | (PMR_PRC_SPR_HI << 16); + return; + case 0x8A: // PRC Counter + return; + } +} + +// +// Default PRC Rendering +// + +static INLINE void MinxPRC_DrawSprite8x8_Mono(uint8_t cfg, int X, int Y, int DrawT, int MaskT) +{ + int xC, xP, vaddr; + uint8_t vdata, sdata, smask; + uint8_t data; + + // No point to proceed if it's offscreen + if ((X < -7) || (X >= 96)) return; + if ((Y < -7) || (Y >= 64)) return; + + // Pre calculate + vaddr = 0x1000 + ((Y >> 3) * 96) + X; + + // Process top columns + if (Y >= 0) { + for (xC=0; xC<8; xC++) { + if ((X >= 0) && (X < 96)) { + xP = (cfg & 0x01) ? (7 - xC) : xC; + + vdata = MinxPRC_OnRead(0, vaddr + xC); + sdata = MinxPRC_OnRead(0, MinxPRC.PRCSprBase + (DrawT * 8) + xP); + smask = MinxPRC_OnRead(0, MinxPRC.PRCSprBase + (MaskT * 8) + xP); + + if (cfg & 0x02) { + sdata = PRCInvertBit[sdata]; + smask = PRCInvertBit[smask]; + } + if (cfg & 0x04) sdata = ~sdata; + + data = vdata & ((smask << (Y & 7)) | (0xFF >> (8 - (Y & 7)))); + data |= (sdata & ~smask) << (Y & 7); + + MinxPRC_OnWrite(0, vaddr + xC, data); + } + X++; + } + X -= 8; + } + + // Calculate new vaddr; + vaddr += 96; + + // Process bottom columns + if ((Y < 56) && (Y & 7)) { + for (xC=0; xC<8; xC++) { + if ((X >= 0) && (X < 96)) { + xP = (cfg & 0x01) ? (7 - xC) : xC; + + vdata = MinxPRC_OnRead(0, vaddr + xC); + sdata = MinxPRC_OnRead(0, MinxPRC.PRCSprBase + (DrawT * 8) + xP); + smask = MinxPRC_OnRead(0, MinxPRC.PRCSprBase + (MaskT * 8) + xP); + + if (cfg & 0x02) { + sdata = PRCInvertBit[sdata]; + smask = PRCInvertBit[smask]; + } + if (cfg & 0x04) sdata = ~sdata; + + data = vdata & ((smask >> (8-(Y & 7))) | (0xFF << (Y & 7))); + data |= (sdata & ~smask) >> (8-(Y & 7)); + + MinxPRC_OnWrite(0, vaddr + xC, data); + } + X++; + } + } +} + +void MinxPRC_Render_Mono(void) +{ + int xC, yC, tx, ty, ltileidxaddr, tileidxaddr, outaddr; + int tiletopaddr = 0, tilebotaddr = 0; + uint8_t data; + + int SprTB, SprAddr; + int SprX, SprY, SprC; + int SprFX, SprFY; + + if (PRCRenderBD) { + for (xC=0x1000; xC<0x1300; xC++) MinxPRC_OnWrite(0, xC, 0x00); + } + + if ((PRCRenderBG) && (PMR_PRC_MODE & 0x02)) { + outaddr = 0x1000; + ltileidxaddr = -1; + for (yC=0; yC<8; yC++) { + ty = (yC << 3) + MinxPRC.PRCMapPY; + for (xC=0; xC<96; xC++) { + tx = xC + MinxPRC.PRCMapPX; + tileidxaddr = 0x1360 + (ty >> 3) * MinxPRC.PRCMapTW + (tx >> 3); + + // Read tile index + if (ltileidxaddr != tileidxaddr) { + tiletopaddr = MinxPRC.PRCBGBase + (MinxPRC_OnRead(0, tileidxaddr) * 8); + tilebotaddr = MinxPRC.PRCBGBase + (MinxPRC_OnRead(0, tileidxaddr + MinxPRC.PRCMapTW) * 8); + ltileidxaddr = tileidxaddr; + } + + // Read tile data + data = (MinxPRC_OnRead(0, tiletopaddr + (tx & 7)) >> (ty & 7)) + | (MinxPRC_OnRead(0, tilebotaddr + (tx & 7)) << (8 - (ty & 7))); + + // Write to VRAM + MinxPRC_OnWrite(0, outaddr++, (PMR_PRC_MODE & 0x01) ? ~data : data); + } + } + } + + if ((PRCRenderSpr) && (PMR_PRC_MODE & 0x04)) { + SprAddr = 0x1300 + (24 * 4); + do { + SprC = MinxPRC_OnRead(0, --SprAddr); + SprTB = MinxPRC_OnRead(0, --SprAddr) * 8; + SprY = (MinxPRC_OnRead(0, --SprAddr) & 0x7F) - 16; + SprX = (MinxPRC_OnRead(0, --SprAddr) & 0x7F) - 16; + if (SprC & 0x08) { + SprFX = SprC & 0x01 ? 8 : 0; + SprFY = SprC & 0x02 ? 8 : 0; + MinxPRC_DrawSprite8x8_Mono(SprC, SprX + SprFX, SprY + SprFY, SprTB+2, SprTB); + MinxPRC_DrawSprite8x8_Mono(SprC, SprX + SprFX, SprY + 8 - SprFY, SprTB+3, SprTB+1); + MinxPRC_DrawSprite8x8_Mono(SprC, SprX + 8 - SprFX, SprY + SprFY, SprTB+6, SprTB+4); + MinxPRC_DrawSprite8x8_Mono(SprC, SprX + 8 - SprFX, SprY + 8 - SprFY, SprTB+7, SprTB+5); + } + } while (SprAddr > 0x1300); + } +} + +void MinxPRC_CopyToLCD(void) +{ + MinxLCD_LCDWritefb(MinxPRC_LCDfb); +/* + // Can't be used with the new color mode support for LCD + int i, j; + MinxLCD_LCDWriteCtrl(0xEE); + for (i=0; i<8; i++) { + MinxLCD_LCDWriteCtrl(0xB0 + i); + MinxLCD_LCDWriteCtrl(0x00); + MinxLCD_LCDWriteCtrl(0x10); + for (j=0; j<96; j++) { + MinxLCD_LCDWrite(MinxPRC_OnRead(0, 0x1000 + (i * 96) + j)); + } + } +*/ +} diff --git a/pm/src/core/MinxPRC.h b/pm/src/core/MinxPRC.h new file mode 100644 index 0000000..2d37bb6 --- /dev/null +++ b/pm/src/core/MinxPRC.h @@ -0,0 +1,101 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXHW_PRC +#define MINXHW_PRC + +#include +#include + +typedef struct { + // Internal processing + int32_t PRCCnt; // PRC Counter 8.24 (Need signed) + uint32_t PRCBGBase; // PRC Map Tile Base + uint32_t PRCSprBase; // PRC Sprite Base + uint8_t PRCMode; // PRC Mode (0 = Off, 1 = Copy, 3 = BG+Spr+Copy) + uint8_t PRCRateMatch; // PRC Rate Match + uint8_t PRCMapPX; // PRC Map X (Pixels) + uint8_t PRCMapPY; // PRC Map Y (Pixels) + uint8_t PRCMapTW; // PRC Map Width (Tiles) + uint8_t PRCMapTH; // PRC Map Height (Tiles) + uint8_t PRCState; // PRC State +} TMinxPRC; + +typedef void (*TMinxPRC_Render)(void); + +// Export PRC state +extern TMinxPRC MinxPRC; + +// Invert bit table +extern const uint8_t PRCInvertBit[256]; + +// Stall CPU +extern int PRCAllowStall; +extern int StallCPU; +extern int StallCycles; + +// Render backdrop? (Background overrides backdrop) +extern int PRCRenderBD; +// Render background? +extern int PRCRenderBG; +// Render sprites? +extern int PRCRenderSpr; + +// Render callback +extern TMinxPRC_Render MinxPRC_Render; + +enum { + MINX_INTR_03 = 0x03, // PRC Copy Complete + MINX_INTR_04 = 0x04 // PRC Frame Divider Overflow +}; + +// Aproximate value of PRC Timer (~4678 Hz) (16M / ( 4M / 855 )) +#define MINX_PRCTIMERINC (16777216/855) + + +int MinxPRC_Create(void); + +void MinxPRC_Destroy(void); + +void MinxPRC_Reset(int hardreset); + +int MinxPRC_LoadStateStream(memstream_t *stream, uint32_t bsize); + +int MinxPRC_SaveStateStream(memstream_t *stream); + +void MinxPRC_Sync(void); + +uint8_t MinxPRC_ReadReg(uint8_t reg); + +void MinxPRC_WriteReg(uint8_t reg, uint8_t val); + +// +// Internals +// + +void MinxPRC_Render_Mono(void); + +void MinxPRC_CopyToLCD(void); + +// +// Callbacks (Written by the user) +// + +void MinxPRC_On72HzRefresh(int render); + +#endif diff --git a/pm/src/core/MinxTimers.c b/pm/src/core/MinxTimers.c new file mode 100644 index 0000000..7c321e8 --- /dev/null +++ b/pm/src/core/MinxTimers.c @@ -0,0 +1,691 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "PokeMini.h" + +TMinxTimers MinxTimers; + +// Calculate decrease on oscillator 1 +const uint32_t MinxTimers_CalculateDecOsc1[16] = { + // Osci1 disabled + 0, 0, 0, 0, 0, 0, 0, 0, + // Osci1 Enabled + (16777216/2), // 2000000 Hz + (16777216/8), // 500000 Hz + (16777216/32), // 125000 Hz + (16777216/64), // 62500 Hz + (16777216/128), // 31250 Hz + (16777216/256), // 15625 Hz + (16777216/1024), // 3906.25 Hz + (16777216/4096), // 976.5625 Hz +}; + +// Calculate decrease on oscillator 2 +const uint32_t MinxTimers_CalculateDecOsc2[16] = { + // Osci2 disabled + 0, 0, 0, 0, 0, 0, 0, 0, + // Osci2 Enabled (Aproximate values) + (16777216/122), // 32768 Hz + (16777216/244), // 16384 Hz + (16777216/488), // 8192 Hz + (16777216/977), // 4096 Hz + (16777216/1953), // 2048 Hz + (16777216/3906), // 1024 Hz + (16777216/7812), // 512 Hz + (16777216/15625) // 256 Hz +}; + +// Timers counting frequency table +const uint32_t MinxTimers_CountFreq[32] = { + // Osci1 disabled + 0, 0, 0, 0, 0, 0, 0, 0, + // Osci1 Enabled + (4000000/2), (4000000/8), (4000000/32), (4000000/64), + (4000000/128), (4000000/256), (4000000/1024), (4000000/4096), + // Osci2 disabled + 0, 0, 0, 0, 0, 0, 0, 0, + // Osci2 Enabled + (32768/1), (32768/2), (32768/4), (32768/8), + (32768/16), (32768/32), (32768/64), (32768/128) +}; + +// +// Functions +// + +int MinxTimers_Create(void) +{ + // Reset + memset((void *)&MinxTimers, 0, sizeof(TMinxTimers)); + MinxTimers_Reset(1); + + return 1; +} + +void MinxTimers_Destroy(void) +{ +} + +void MinxTimers_Reset(int hardreset) +{ + if (hardreset) { + // Init state + memset((void *)&MinxTimers, 0, sizeof(TMinxTimers)); + } + + // Init variables + MinxTimers.Tmr1PreA = 0xFFFFFFFF; + MinxTimers.Tmr1PreB = 0xFFFFFFFF; + MinxTimers.Tmr2PreA = 0xFFFFFFFF; + MinxTimers.Tmr2PreB = 0xFFFFFFFF; + MinxTimers.Tmr3PreA = 0xFFFFFFFF; + MinxTimers.Tmr3PreB = 0xFFFFFFFF; +} + +int MinxTimers_LoadStateStream(memstream_t *stream, uint32_t bsize) +{ + POKELOADSS_START(128); + POKELOADSS_STREAM_32(MinxTimers.SecTimerCnt); + POKELOADSS_STREAM_32(MinxTimers.TmrSecs); + POKELOADSS_STREAM_32(MinxTimers.Tmr1DecA); + POKELOADSS_STREAM_32(MinxTimers.Tmr1DecB); + POKELOADSS_STREAM_32(MinxTimers.Tmr1CntA); + POKELOADSS_STREAM_32(MinxTimers.Tmr1CntB); + POKELOADSS_STREAM_32(MinxTimers.Tmr1PreA); + POKELOADSS_STREAM_32(MinxTimers.Tmr1PreB); + POKELOADSS_STREAM_32(MinxTimers.Tmr2DecA); + POKELOADSS_STREAM_32(MinxTimers.Tmr2DecB); + POKELOADSS_STREAM_32(MinxTimers.Tmr2CntA); + POKELOADSS_STREAM_32(MinxTimers.Tmr2CntB); + POKELOADSS_STREAM_32(MinxTimers.Tmr2PreA); + POKELOADSS_STREAM_32(MinxTimers.Tmr2PreB); + POKELOADSS_STREAM_32(MinxTimers.Tmr3DecA); + POKELOADSS_STREAM_32(MinxTimers.Tmr3DecB); + POKELOADSS_STREAM_32(MinxTimers.Tmr3CntA); + POKELOADSS_STREAM_32(MinxTimers.Tmr3CntB); + POKELOADSS_STREAM_32(MinxTimers.Tmr3PreA); + POKELOADSS_STREAM_32(MinxTimers.Tmr3PreB); + POKELOADSS_STREAM_32(MinxTimers.Tmr8Cnt); + POKELOADSS_STREAM_32(MinxTimers.PRCCnt); + POKELOADSS_STREAM_16(MinxTimers.Tmr3Cnt16.W); + POKELOADSS_STREAM_16(MinxTimers.Timer3Piv); + POKELOADSS_STREAM_8(MinxTimers.TmrXEna2); + POKELOADSS_STREAM_8(MinxTimers.TmrXEna1); + POKELOADSS_STREAM_X(34); + MinxTimers.Tmr1WMode = PMR_TMR1_CTRL_L & 0x80; + MinxTimers.Tmr1LEna = PMR_TMR1_CTRL_L & 0x04; + MinxTimers.Tmr1HEna = PMR_TMR1_CTRL_H & 0x04; + MinxTimers.Tmr2WMode = PMR_TMR2_CTRL_L & 0x80; + MinxTimers.Tmr2LEna = PMR_TMR2_CTRL_L & 0x04; + MinxTimers.Tmr2HEna = PMR_TMR2_CTRL_H & 0x04; + MinxTimers.Tmr3WMode = PMR_TMR3_CTRL_L & 0x80; + MinxTimers.Tmr3LEna = PMR_TMR3_CTRL_L & 0x04; + MinxTimers.Tmr3HEna = PMR_TMR3_CTRL_H & 0x04; + POKELOADSS_END(128); +} + +int MinxTimers_SaveStateStream(memstream_t *stream) +{ + POKESAVESS_STREAM_START(128); + POKESAVESS_STREAM_32(MinxTimers.SecTimerCnt); + POKESAVESS_STREAM_32(MinxTimers.TmrSecs); + POKESAVESS_STREAM_32(MinxTimers.Tmr1DecA); + POKESAVESS_STREAM_32(MinxTimers.Tmr1DecB); + POKESAVESS_STREAM_32(MinxTimers.Tmr1CntA); + POKESAVESS_STREAM_32(MinxTimers.Tmr1CntB); + POKESAVESS_STREAM_32(MinxTimers.Tmr1PreA); + POKESAVESS_STREAM_32(MinxTimers.Tmr1PreB); + POKESAVESS_STREAM_32(MinxTimers.Tmr2DecA); + POKESAVESS_STREAM_32(MinxTimers.Tmr2DecB); + POKESAVESS_STREAM_32(MinxTimers.Tmr2CntA); + POKESAVESS_STREAM_32(MinxTimers.Tmr2CntB); + POKESAVESS_STREAM_32(MinxTimers.Tmr2PreA); + POKESAVESS_STREAM_32(MinxTimers.Tmr2PreB); + POKESAVESS_STREAM_32(MinxTimers.Tmr3DecA); + POKESAVESS_STREAM_32(MinxTimers.Tmr3DecB); + POKESAVESS_STREAM_32(MinxTimers.Tmr3CntA); + POKESAVESS_STREAM_32(MinxTimers.Tmr3CntB); + POKESAVESS_STREAM_32(MinxTimers.Tmr3PreA); + POKESAVESS_STREAM_32(MinxTimers.Tmr3PreB); + POKESAVESS_STREAM_32(MinxTimers.Tmr8Cnt); + POKESAVESS_STREAM_32(MinxTimers.PRCCnt); + POKESAVESS_STREAM_16(MinxTimers.Tmr3Cnt16.W); + POKESAVESS_STREAM_16(MinxTimers.Timer3Piv); + POKESAVESS_STREAM_8(MinxTimers.TmrXEna2); + POKESAVESS_STREAM_8(MinxTimers.TmrXEna1); + POKESAVESS_STREAM_X(34); + POKESAVESS_END(128); +} + +void MinxTimers_Sync(void) +{ + register uint32_t PreCount; + + // Process 256Hz Timer (Increment) + if (PMR_TMR256_CTRL) { + PreCount = MinxTimers.Tmr8Cnt; + MinxTimers.Tmr8Cnt += MINX_TIMER256INC * PokeHWCycles; + if ((PreCount & 0x08000000) ^ (MinxTimers.Tmr8Cnt & 0x08000000)) { + // 32Hz + MinxCPU_OnIRQAct(MINX_INTR_0B); + } + if ((PreCount & 0x20000000) ^ (MinxTimers.Tmr8Cnt & 0x20000000)) { + // 8Hz + MinxCPU_OnIRQAct(MINX_INTR_0C); + } + if ((PreCount & 0x80000000) ^ (MinxTimers.Tmr8Cnt & 0x80000000)) { + // 2Hz + MinxCPU_OnIRQAct(MINX_INTR_0D); + } + if (PreCount > MinxTimers.Tmr8Cnt) { + // 1Hz + MinxCPU_OnIRQAct(MINX_INTR_0E); + } + } + + // Process Second Timer (Increment) + if (PMR_SEC_CTRL) { + MinxTimers.TmrSecs += PokeHWCycles; + if (MinxTimers.TmrSecs >= 4000000) { + MinxTimers.SecTimerCnt++; + MinxTimers.TmrSecs -= 4000000; + } + } + + // Process Timer 1 (Decrement) + if (MinxTimers.Tmr1WMode) { + // 1x 16-Bits Timer + if (MinxTimers.Tmr1LEna) { + PreCount = MinxTimers.Tmr1CntA; + MinxTimers.Tmr1CntA -= MinxTimers.Tmr1DecA * PokeHWCycles; + if (PreCount < MinxTimers.Tmr1CntA) { + PreCount = MinxTimers.Tmr1CntB; + MinxTimers.Tmr1CntB -= 0x01000000; + if (PreCount < MinxTimers.Tmr1CntB) { + MinxTimers.Tmr1CntA = MinxTimers.Tmr1PreA; + MinxTimers.Tmr1CntB = MinxTimers.Tmr1PreB; + // IRQ Timer 1-Hi underflow + MinxCPU_OnIRQAct(MINX_INTR_07); + } + } + } + } else { + // 2x 8-Bits Timers + if (MinxTimers.Tmr1LEna) { + // Timer Lo + PreCount = MinxTimers.Tmr1CntA; + MinxTimers.Tmr1CntA -= MinxTimers.Tmr1DecA * PokeHWCycles; + if (PreCount < MinxTimers.Tmr1CntA) { + MinxTimers.Tmr1CntA = MinxTimers.Tmr1PreA; + // IRQ Timer 1-Lo underflow + MinxCPU_OnIRQAct(MINX_INTR_08); + } + } + if (MinxTimers.Tmr1HEna) { + // Timer Hi + PreCount = MinxTimers.Tmr1CntB; + MinxTimers.Tmr1CntB -= MinxTimers.Tmr1DecB * PokeHWCycles; + if (PreCount < MinxTimers.Tmr1CntB) { + MinxTimers.Tmr1CntB = MinxTimers.Tmr1PreB; + // IRQ Timer 1-Hi underflow + MinxCPU_OnIRQAct(MINX_INTR_07); + } + } + } + + // Process Timer 2 (Decrement) + if (MinxTimers.Tmr2WMode) { + // 1x 16-Bits Timer + if (MinxTimers.Tmr2LEna) { + PreCount = MinxTimers.Tmr2CntA; + MinxTimers.Tmr2CntA -= MinxTimers.Tmr2DecA * PokeHWCycles; + if (PreCount < MinxTimers.Tmr2CntA) { + PreCount = MinxTimers.Tmr2CntB; + MinxTimers.Tmr2CntB -= 0x01000000; + if (PreCount < MinxTimers.Tmr2CntB) { + MinxTimers.Tmr2CntA = MinxTimers.Tmr2PreA; + MinxTimers.Tmr2CntB = MinxTimers.Tmr2PreB; + // IRQ Timer 2-Hi underflow + MinxCPU_OnIRQAct(MINX_INTR_05); + } + } + } + } else { + // 2x 8-Bits Timers + if (MinxTimers.Tmr2LEna) { + // Timer Lo + PreCount = MinxTimers.Tmr2CntA; + MinxTimers.Tmr2CntA -= MinxTimers.Tmr2DecA * PokeHWCycles; + if (PreCount < MinxTimers.Tmr2CntA) { + MinxTimers.Tmr2CntA = MinxTimers.Tmr2PreA; + // IRQ Timer 2-Lo underflow + MinxCPU_OnIRQAct(MINX_INTR_06); + } + } + if (MinxTimers.Tmr2HEna) { + // Timer Hi + PreCount = MinxTimers.Tmr2CntB; + MinxTimers.Tmr2CntB -= MinxTimers.Tmr2DecB * PokeHWCycles; + if (PreCount < MinxTimers.Tmr2CntB) { + MinxTimers.Tmr2CntB = MinxTimers.Tmr2PreB; + // IRQ Timer 2-Hi underflow + MinxCPU_OnIRQAct(MINX_INTR_05); + } + } + } + + // Process Timer 3 (Decrement) + if (MinxTimers.Tmr3WMode) { + // 1x 16-Bits Timer + if (MinxTimers.Tmr3LEna) { + PreCount = MinxTimers.Tmr3CntA; + MinxTimers.Tmr3CntA -= MinxTimers.Tmr3DecA * PokeHWCycles; + if (PreCount < MinxTimers.Tmr3CntA) { + PreCount = MinxTimers.Tmr3CntB; + MinxTimers.Tmr3CntB -= 0x01000000; + if (PreCount < MinxTimers.Tmr3CntB) { + MinxTimers.Tmr3CntA = MinxTimers.Tmr3PreA; + MinxTimers.Tmr3CntB = MinxTimers.Tmr3PreB; + // IRQ Timer 3 underflow + MinxCPU_OnIRQAct(MINX_INTR_09); + } + MinxTimers.Tmr3Cnt16.B.H = MinxTimers.Tmr3CntB >> 24; + } + // Check pivot + PreCount = MinxTimers.Tmr3Cnt16.W; + MinxTimers.Tmr3Cnt16.B.L = MinxTimers.Tmr3CntA >> 24; + if ((PreCount > MinxTimers.Timer3Piv) && (MinxTimers.Tmr3Cnt16.W <= MinxTimers.Timer3Piv)) { + // IRQ Timer 3 Pivot + MinxCPU_OnIRQAct(MINX_INTR_0A); + } + } + } else { + // 2x 8-Bits Timers + if (MinxTimers.Tmr3LEna) { + // Timer Lo + PreCount = MinxTimers.Tmr3CntA; + MinxTimers.Tmr3CntA -= MinxTimers.Tmr3DecA * PokeHWCycles; // Osci2 + if (PreCount < MinxTimers.Tmr3CntA) { + MinxTimers.Tmr3CntA = MinxTimers.Tmr3PreA; + } + MinxTimers.Tmr3Cnt16.B.L = MinxTimers.Tmr3CntA >> 24; + } + if (MinxTimers.Tmr3HEna) { + // Timer Hi + PreCount = MinxTimers.Tmr3CntB; + MinxTimers.Tmr3CntB -= MinxTimers.Tmr3DecB * PokeHWCycles; // Osci2 + if (PreCount < MinxTimers.Tmr3CntB) { + MinxTimers.Tmr3CntB = MinxTimers.Tmr3PreB; + // IRQ Timer 3 underflow + MinxCPU_OnIRQAct(MINX_INTR_09); + } + // Check pivot + PreCount = MinxTimers.Tmr3Cnt16.W; + MinxTimers.Tmr3Cnt16.B.H = MinxTimers.Tmr3CntB >> 24; + if ((PreCount > MinxTimers.Timer3Piv) && (MinxTimers.Tmr3Cnt16.W <= MinxTimers.Timer3Piv)) { + // IRQ Timer 3 Pivot + MinxCPU_OnIRQAct(MINX_INTR_0A); + } + } + } +} + +uint8_t MinxTimers_ReadReg(uint8_t reg) +{ + // 0x08 to 0x0F, 0x18 to 0x1F, 0x30 to 0x41, 0x48 to 0x4F + switch(reg) { + case 0x08: // Second Counter Control + return PMR_SEC_CTRL & 0x01; + case 0x09: // Second Counter Low + return (uint8_t)MinxTimers.SecTimerCnt; + case 0x0A: // Second Counter Med + return (uint8_t)(MinxTimers.SecTimerCnt >> 8); + case 0x0B: // Second Counter High + return (uint8_t)(MinxTimers.SecTimerCnt >> 16); + case 0x18: // Timer 1 Prescaler + return PMR_TMR1_SCALE; + case 0x19: // Timer 1 Osc. Select + Osc. Enable + return PMR_TMR1_ENA_OSC & 0x33; + case 0x1A: // Timer 2 Prescaler + return PMR_TMR2_SCALE; + case 0x1B: // Timer 2 Osc. Select + return PMR_TMR2_OSC & 0x03; + case 0x1C: // Timer 3 Prescaler + return PMR_TMR3_SCALE; + case 0x1D: // Timer 3 Osc. Select + return PMR_TMR3_OSC & 0x03; + case 0x30: // Timer 1 Control A + if (PMR_TMR1_CTRL_L & 0x80) { + return PMR_TMR1_CTRL_L & 0x85; // 16-Bits + } else { + return PMR_TMR1_CTRL_L & 0x0D; // 8-Bits Mode + } + case 0x31: // Timer 1 Control B + if (PMR_TMR1_CTRL_L & 0x80) { + return PMR_TMR1_CTRL_H & 0x08; // 16-Bits Mode + } else { + return PMR_TMR1_CTRL_H & 0x0D; // 8-Bits Mode + } + case 0x32: // Timer 1 Preset A + return (uint8_t)(MinxTimers.Tmr1PreA >> 24); + case 0x33: // Timer 1 Preset B + return (uint8_t)(MinxTimers.Tmr1PreB >> 24); + case 0x34: // Timer 1 Pivot A + return PMR_TMR1_PVT_L; + case 0x35: // Timer 1 Pivot B + return PMR_TMR1_PVT_H; + case 0x36: // Timer 1 Count A + return (uint8_t)(MinxTimers.Tmr1CntA >> 24); + case 0x37: // Timer 1 Count B + return (uint8_t)(MinxTimers.Tmr1CntB >> 24); + case 0x38: // Timer 2 Control A + if (PMR_TMR2_CTRL_L & 0x80) { + return PMR_TMR2_CTRL_L & 0x85; // 16-Bits + } else { + return PMR_TMR2_CTRL_L & 0x0D; // 8-Bits Mode + } + case 0x39: // Timer 2 Control B + if (PMR_TMR2_CTRL_L & 0x80) { + return PMR_TMR2_CTRL_H & 0x08; // 16-Bits Mode + } else { + return PMR_TMR2_CTRL_H & 0x0D; // 8-Bits Mode + } + case 0x3A: // Timer 2 Preset A + return (uint8_t)(MinxTimers.Tmr2PreA >> 24); + case 0x3B: // Timer 2 Preset B + return (uint8_t)(MinxTimers.Tmr2PreB >> 24); + case 0x3C: // Timer 2 Pivot A + return PMR_TMR2_PVT_L; + case 0x3D: // Timer 2 Pivot B + return PMR_TMR2_PVT_H; + case 0x3E: // Timer 2 Count A + return (uint8_t)(MinxTimers.Tmr2CntA >> 24); + case 0x3F: // Timer 2 Count B + return (uint8_t)(MinxTimers.Tmr2CntB >> 24); + case 0x40: // 256 Hz Timer Control + return PMR_TMR256_CTRL; + case 0x41: // 256 Hz Timer Counter + return MinxTimers.Tmr8Cnt >> 24; + case 0x48: // Timer 3 Control A + if (PMR_TMR3_CTRL_L & 0x80) { + return PMR_TMR3_CTRL_L & 0x85; // 16-Bits + } else { + return PMR_TMR3_CTRL_L & 0x0D; // 8-Bits Mode + } + case 0x49: // Timer 3 Control B + if (PMR_TMR3_CTRL_L & 0x80) { + return PMR_TMR3_CTRL_H & 0x08; // 16-Bits Mode + } else { + return PMR_TMR3_CTRL_H & 0x0D; // 8-Bits Mode + } + case 0x4A: // Timer 3 Preset A + return (uint8_t)(MinxTimers.Tmr3PreA >> 24); + case 0x4B: // Timer 3 Preset B + return (uint8_t)(MinxTimers.Tmr3PreB >> 24); + case 0x4C: // Timer 3 Pivot A + return (uint8_t)MinxTimers.Timer3Piv; + case 0x4D: // Timer 3 Pivot B + return (uint8_t)(MinxTimers.Timer3Piv >> 8); + case 0x4E: // Timer 3 Count A + return (uint8_t)(MinxTimers.Tmr3CntA >> 24); + case 0x4F: // Timer 3 Count B + return (uint8_t)(MinxTimers.Tmr3CntB >> 24); + default: // Unused + return reg; + } +} + +#define MinxTimers_UpdateScalarTimer1() { \ + if (PMR_TMR1_ENA_OSC & 0x01) { \ + if (MinxTimers.TmrXEna2) MinxTimers.Tmr1DecA = MinxTimers_CalculateDecOsc2[(PMR_TMR1_SCALE & 0xF)]; \ + else MinxTimers.Tmr1DecA = 0; \ + } else { \ + if (MinxTimers.TmrXEna1) MinxTimers.Tmr1DecA = MinxTimers_CalculateDecOsc1[(PMR_TMR1_SCALE & 0xF)]; \ + else MinxTimers.Tmr1DecA = 0; \ + } \ + if (PMR_TMR1_ENA_OSC & 0x02) { \ + if (MinxTimers.TmrXEna2) MinxTimers.Tmr1DecB = MinxTimers_CalculateDecOsc2[((PMR_TMR1_SCALE >> 4) & 0xF)]; \ + else MinxTimers.Tmr1DecB = 0; \ + } else { \ + if (MinxTimers.TmrXEna1) MinxTimers.Tmr1DecB = MinxTimers_CalculateDecOsc1[((PMR_TMR1_SCALE >> 4) & 0xF)]; \ + else MinxTimers.Tmr1DecB = 0; \ + } \ +} + +#define MinxTimers_UpdateScalarTimer2() { \ + if (PMR_TMR2_OSC & 0x01) { \ + if (MinxTimers.TmrXEna2) MinxTimers.Tmr2DecA = MinxTimers_CalculateDecOsc2[(PMR_TMR2_SCALE & 0xF)]; \ + else MinxTimers.Tmr2DecA = 0; \ + } else { \ + if (MinxTimers.TmrXEna1) MinxTimers.Tmr2DecA = MinxTimers_CalculateDecOsc1[(PMR_TMR2_SCALE & 0xF)]; \ + else MinxTimers.Tmr2DecA = 0; \ + } \ + if (PMR_TMR2_OSC & 0x02) { \ + if (MinxTimers.TmrXEna2) MinxTimers.Tmr2DecB = MinxTimers_CalculateDecOsc2[((PMR_TMR2_SCALE >> 4) & 0xF)]; \ + else MinxTimers.Tmr2DecB = 0; \ + } else { \ + if (MinxTimers.TmrXEna1) MinxTimers.Tmr2DecB = MinxTimers_CalculateDecOsc1[((PMR_TMR2_SCALE >> 4) & 0xF)]; \ + else MinxTimers.Tmr2DecB = 0; \ + } \ +} + +#define MinxTimers_UpdateScalarTimer3() { \ + if (PMR_TMR3_OSC & 0x01) { \ + if (MinxTimers.TmrXEna2) MinxTimers.Tmr3DecA = MinxTimers_CalculateDecOsc2[(PMR_TMR3_SCALE & 0xF)]; \ + else MinxTimers.Tmr3DecA = 0; \ + } else { \ + if (MinxTimers.TmrXEna1) MinxTimers.Tmr3DecA = MinxTimers_CalculateDecOsc1[(PMR_TMR3_SCALE & 0xF)]; \ + else MinxTimers.Tmr3DecA = 0; \ + } \ + if (PMR_TMR3_OSC & 0x02) { \ + if (MinxTimers.TmrXEna2) MinxTimers.Tmr3DecB = MinxTimers_CalculateDecOsc2[((PMR_TMR3_SCALE >> 4) & 0xF)]; \ + else MinxTimers.Tmr3DecB = 0; \ + } else { \ + if (MinxTimers.TmrXEna1) MinxTimers.Tmr3DecB = MinxTimers_CalculateDecOsc1[((PMR_TMR3_SCALE >> 4) & 0xF)]; \ + else MinxTimers.Tmr3DecB = 0; \ + } \ +} + +void MinxTimers_WriteReg(unsigned char reg, unsigned char val) +{ + // 0x08 to 0x0F, 0x18 to 0x1F, 0x30 to 0x41, 0x48 to 0x4F + switch(reg) { + case 0x08: // Second Counter Control + if (val & 0x02) MinxTimers.SecTimerCnt = 0x000000; + PMR_SEC_CTRL = val & 0x01; + return; + case 0x09: // Second Counter Low + case 0x0A: // Second Counter Med + case 0x0B: // Second Counter High + return; + case 0x18: // Timer 1 Prescaler + PMR_TMR1_SCALE = val; + MinxTimers_UpdateScalarTimer1(); + return; + case 0x19: // Timer 1 Osc. Select + Osc. Enable + PMR_TMR1_ENA_OSC = val & 0x33; + MinxTimers.TmrXEna2 = val & 0x10; + MinxTimers.TmrXEna1 = val & 0x20; + MinxTimers_UpdateScalarTimer1(); + MinxTimers_UpdateScalarTimer2(); // Because of the TmrXEna# + MinxTimers_UpdateScalarTimer3(); // Because of the TmrXEna# + return; + case 0x1A: // Timer 2 Prescaler + PMR_TMR2_SCALE = val; + MinxTimers_UpdateScalarTimer2(); + return; + case 0x1B: // Timer 2 Osc. Select + PMR_TMR2_OSC = val & 0x03; + MinxTimers_UpdateScalarTimer2(); + return; + case 0x1C: // Timer 3 Prescaler + PMR_TMR3_SCALE = val; + MinxTimers_UpdateScalarTimer3(); + return; + case 0x1D: // Timer 3 Osc. Select + PMR_TMR3_OSC = val & 0x03; + MinxTimers_UpdateScalarTimer3(); + return; + case 0x30: // Timer 1 Control A + PMR_TMR1_CTRL_L = val & 0x8D; + MinxTimers.Tmr1LEna = val & 0x04; + if (PMR_TMR1_CTRL_L & 0x80) { + // 16-Bits + MinxTimers.Tmr1WMode = 1; + if (val & 0x02) { + MinxTimers.Tmr1CntA = MinxTimers.Tmr1PreA; + MinxTimers.Tmr1CntB = MinxTimers.Tmr1PreB; + } + } else { + // 8-Bits + MinxTimers.Tmr1WMode = 0; + if (val & 0x02) { + MinxTimers.Tmr1CntA = MinxTimers.Tmr1PreA; + } + } + return; + case 0x31: // Timer 1 Control B + PMR_TMR1_CTRL_H = val & 0x0D; + MinxTimers.Tmr1HEna = val & 0x04; + if (PMR_TMR1_CTRL_L & 0x80) { + // 16-Bits, unused + } else { + // 8-Bits + if (val & 0x02) { + MinxTimers.Tmr1CntB = MinxTimers.Tmr1PreB; + } + } + return; + case 0x32: // Timer 1 Preset A + MinxTimers.Tmr1PreA = val << 24; + return; + case 0x33: // Timer 1 Preset B + MinxTimers.Tmr1PreB = val << 24; + return; + case 0x34: // Timer 1 Pivot A + PMR_TMR1_PVT_L = val; + return; + case 0x35: // Timer 1 Pivot B + PMR_TMR1_PVT_H = val; + return; + case 0x36: // Timer 1 Count A + return; + case 0x37: // Timer 1 Count B + return; + case 0x38: // Timer 2 Control A + PMR_TMR2_CTRL_L = val & 0x8D; + MinxTimers.Tmr2LEna = val & 0x04; + if (PMR_TMR2_CTRL_L & 0x80) { + // 16-Bits + MinxTimers.Tmr2WMode = 1; + if (val & 0x02) { + MinxTimers.Tmr2CntA = MinxTimers.Tmr2PreA; + MinxTimers.Tmr2CntB = MinxTimers.Tmr2PreB; + } + } else { + // 8-Bits + MinxTimers.Tmr2WMode = 0; + if (val & 0x02) { + MinxTimers.Tmr2CntA = MinxTimers.Tmr2PreA; + } + } + return; + case 0x39: // Timer 2 Control B + PMR_TMR2_CTRL_H = val & 0x0D; + MinxTimers.Tmr2HEna = val & 0x04; + if (PMR_TMR2_CTRL_L & 0x80) { + // 16-Bits, unused + } else { + // 8-Bits + if (val & 0x02) { + MinxTimers.Tmr2CntB = MinxTimers.Tmr2PreB; + } + } + return; + case 0x3A: // Timer 2 Preset A + MinxTimers.Tmr2PreA = val << 24; + return; + case 0x3B: // Timer 2 Preset B + MinxTimers.Tmr2PreB = val << 24; + return; + case 0x3C: // Timer 2 Pivot A + PMR_TMR2_PVT_L = val; + return; + case 0x3D: // Timer 2 Pivot B + PMR_TMR2_PVT_H = val; + return; + case 0x3E: // Timer 2 Count A + return; + case 0x3F: // Timer 2 Count B + return; + case 0x40: // 256 Hz Timer Control + PMR_TMR256_CTRL = val & 0x01; + if (val & 0x02) { + MinxTimers.Tmr8Cnt = 0; + } + return; + case 0x41: // 256 Hz Timer Counter + return; + case 0x48: // Timer 3 Control A + PMR_TMR3_CTRL_L = val & 0x8D; + MinxTimers.Tmr3LEna = val & 0x04; + if (PMR_TMR3_CTRL_L & 0x80) { + // 16-Bits + MinxTimers.Tmr3WMode = 1; + if (val & 0x02) { + MinxTimers.Tmr3CntA = MinxTimers.Tmr3PreA; + MinxTimers.Tmr3CntB = MinxTimers.Tmr3PreB; + } + } else { + // 8-Bits + MinxTimers.Tmr3WMode = 0; + if (val & 0x02) { + MinxTimers.Tmr3CntA = MinxTimers.Tmr3PreA; + } + } + return; + case 0x49: // Timer 3 Control B + PMR_TMR3_CTRL_H = val & 0x0D; + MinxTimers.Tmr3HEna = val & 0x04; + if (PMR_TMR3_CTRL_L & 0x80) { + // 16-Bits, unused + } else { + // 8-Bits + if (val & 0x02) { + MinxTimers.Tmr3CntB = MinxTimers.Tmr3PreB; + } + } + return; + case 0x4A: // Timer 3 Preset A + MinxTimers.Tmr3PreA = val << 24; + return; + case 0x4B: // Timer 3 Preset B + MinxTimers.Tmr3PreB = val << 24; + return; + case 0x4C: // Timer 3 Pivot A + MinxTimers.Timer3Piv = (MinxTimers.Timer3Piv & 0xFF00) | val; + return; + case 0x4D: // Timer 3 Pivot B + MinxTimers.Timer3Piv = (MinxTimers.Timer3Piv & 0x00FF) | (val << 8); + return; + case 0x4E: // Timer 3 Count A + return; + case 0x4F: // Timer 3 Count B + return; + } +} diff --git a/pm/src/core/MinxTimers.h b/pm/src/core/MinxTimers.h new file mode 100644 index 0000000..87ba914 --- /dev/null +++ b/pm/src/core/MinxTimers.h @@ -0,0 +1,127 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef MINXHW_TIMERS +#define MINXHW_TIMERS + +#include +#include + +/* For some reason, '_BIG_ENDIAN' is always defined when + * building for 3DS/Switch with devkitarm/a64... */ +#if defined (_BIG_ENDIAN) && !defined (_3DS) && !defined(HAVE_LIBNX) + +typedef union { + struct { + uint8_t H; + uint8_t L; + } B; + uint16_t W; +} MinxWord; + +#else + +typedef union { + struct { + uint8_t L; + uint8_t H; + } B; + uint16_t W; +} MinxWord; + +#endif + +typedef struct { + // Internal processing + uint32_t SecTimerCnt; // Second Timer Counter + int32_t TmrSecs; // Second Timer Fraction (Cycles, needs signed) + uint32_t Tmr1DecA; // Timer 1-Lo Decrement 8.24 + uint32_t Tmr1DecB; // Timer 1-Hi Decrement 8.24 + uint32_t Tmr1CntA; // Timer 1-Lo Counter 8.24 + uint32_t Tmr1CntB; // Timer 1-Hi Counter 8.24 + uint32_t Tmr1PreA; // Timer 1-Lo Preset 8.24 + uint32_t Tmr1PreB; // Timer 1-Hi Preset 8.24 + uint32_t Tmr2DecA; // Timer 2-Lo Decrement 8.24 + uint32_t Tmr2DecB; // Timer 2-Hi Decrement 8.24 + uint32_t Tmr2CntA; // Timer 2-Lo Counter 8.24 + uint32_t Tmr2CntB; // Timer 2-Hi Counter 8.24 + uint32_t Tmr2PreA; // Timer 2-Lo Preset 8.24 + uint32_t Tmr2PreB; // Timer 2-Hi Preset 8.24 + uint32_t Tmr3DecA; // Timer 3-Lo Decrement 8.24 + uint32_t Tmr3DecB; // Timer 3-Hi Decrement 8.24 + uint32_t Tmr3CntA; // Timer 3-Lo Counter 8.24 + uint32_t Tmr3CntB; // Timer 3-Hi Counter 8.24 + uint32_t Tmr3PreA; // Timer 3-Lo Preset 8.24 + uint32_t Tmr3PreB; // Timer 3-Hi Preset 8.24 + uint32_t Tmr8Cnt; // 256Hz Timer Counter 8.24 + uint32_t PRCCnt; // PRC Counter 8.24 + MinxWord Tmr3Cnt16; // Timer 3 16-Bits count + uint16_t Timer3Piv; // Timer 3 Pivot + uint8_t TmrXEna2; // Oscillator 2 Enabled + uint8_t TmrXEna1; // Oscillator 1 Enabled + // Performance cache + int Tmr1WMode; // Timer 1 16-bits mode + int Tmr1LEna; // Timer 1 low enable + int Tmr1HEna; // Timer 1 high enable + int Tmr2WMode; // Timer 2 16-bits mode + int Tmr2LEna; // Timer 2 low enable + int Tmr2HEna; // Timer 2 high enable + int Tmr3WMode; // Timer 3 16-bits mode + int Tmr3LEna; // Timer 3 low enable + int Tmr3HEna; // Timer 3 high enable +} TMinxTimers; + +// Export Timers state +extern TMinxTimers MinxTimers; + +// Interrupt table +enum { + MINX_INTR_05 = 0x05, // Timer 2-B Underflow + MINX_INTR_06 = 0x06, // Timer 2-A Underflow (8-Bits only) + MINX_INTR_07 = 0x07, // Timer 1-B Underflow + MINX_INTR_08 = 0x08, // Timer 1-A Underflow (8-Bits only) + MINX_INTR_09 = 0x09, // Timer 3 Underflow + MINX_INTR_0A = 0x0A, // Timer 3 Pivot + MINX_INTR_0B = 0x0B, // 32 Hz + MINX_INTR_0C = 0x0C, // 8 Hz + MINX_INTR_0D = 0x0D, // 2 Hz + MINX_INTR_0E = 0x0E // 1 Hz +}; + +#define MINX_TIMER256INC (16777216/15625) // Aproximate value of 256Hz Timer (256 Hz) + +// Timers counting frequency table +extern const uint32_t MinxTimers_CountFreq[32]; + +int MinxTimers_Create(void); + +void MinxTimers_Destroy(void); + +void MinxTimers_Reset(int hardreset); + +int MinxTimers_LoadStateStream(memstream_t *stream, uint32_t bsize); + +int MinxTimers_SaveStateStream(memstream_t *stream); + +void MinxTimers_Sync(void); + +uint8_t MinxTimers_ReadReg(uint8_t reg); + +void MinxTimers_WriteReg(unsigned char reg, unsigned char val); + +#endif diff --git a/pm/src/core/Multicart.h b/pm/src/core/Multicart.h new file mode 100644 index 0000000..e19fa3f --- /dev/null +++ b/pm/src/core/Multicart.h @@ -0,0 +1,49 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2012 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef POKEMINI_MULTICART +#define POKEMINI_MULTICART + +#include + +typedef uint8_t (*TMulticartRead)(uint32_t addr); +typedef void (*TMulticartWrite)(uint32_t addr, uint8_t data); + +// Multicart read/write +extern TMulticartRead MulticartRead; +extern TMulticartWrite MulticartWrite; + +// Multicart state +extern int PM_MM_Type; +extern int PM_MM_Dirty; +extern int PM_MM_BusCycle; +extern int PM_MM_GetID; +extern int PM_MM_Bypass; +extern int PM_MM_Command; +extern uint32_t PM_MM_Offset; + +// For misc information +extern uint32_t PM_MM_LastErase_Start; +extern uint32_t PM_MM_LastErase_End; +extern uint32_t PM_MM_LastProg; + +// Set multicart +void NewMulticart(void); +void SetMulticart(int type); + +#endif diff --git a/pm/src/core/PMCommon.h b/pm/src/core/PMCommon.h new file mode 100644 index 0000000..f99a1ec --- /dev/null +++ b/pm/src/core/PMCommon.h @@ -0,0 +1,48 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2014 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef PMCOMMON_H +#define PMCOMMON_H + +#include +#include +#include +#include + +#include + +// Temporary variable length +// Minimum is 128 +// Recommended is 256 +#ifndef PMTMPV +#define PMTMPV 512 +#endif + +// Return true if the string is valid and non-empty +int StringIsSet(char *str); + +// Get multiple of 2 (Mask) +int GetMultiple2Mask(int input); + +// Check if file exist +int FileExist(const char *filename); + +// Directories +void PokeMini_InitDirs(char *argv0, char *exec); + +#endif diff --git a/pm/src/core/PokeMini.h b/pm/src/core/PokeMini.h new file mode 100644 index 0000000..a8340ae --- /dev/null +++ b/pm/src/core/PokeMini.h @@ -0,0 +1,242 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009-2015 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef POKEMINI_EMU +#define POKEMINI_EMU + +#include +#include +#include +#include + +// Common functions +#include "PMCommon.h" + +// Configuration Flags +// Generated sound only +#define POKEMINI_GENSOUND 0x02 + +extern int PokeMini_FreeBIOS; // Using freebios? +extern int PokeMini_Flags; // Configuration flags +extern int PokeMini_Rumbling; // Pokemon-Mini is rumbling +extern uint8_t PM_BIOS[]; // Pokemon-Mini BIOS ($000000 to $000FFF, 4096) +extern uint8_t PM_RAM[]; // Pokemon-Mini RAM ($001000 to $002100, 4096 + 256) +extern uint8_t *PM_ROM; // Pokemon-Mini ROM ($002100 to $1FFFFF, Up to 2MB) +extern int PM_ROM_Alloc; // Pokemon-Mini ROM Allocated on memory? +extern int PM_ROM_Size; // Pokemon-Mini ROM Size +extern int PM_ROM_Mask; // Pokemon-Mini ROM Mask +extern int PokeMini_LCDMode; // LCD Mode +extern int PokeMini_ColorFormat; // Color Format (0 = 8x8, 1 = 4x4) +extern int PokeMini_HostBattStatus; // Host battery status + +// Number of cycles to process on hardware +extern int PokeHWCycles; + + +enum { + LCDMODE_ANALOG = 0, + LCDMODE_3SHADES, + LCDMODE_2SHADES, + LCDMODE_COLORS +}; + +// Include Interfaces +#include "IOMap.h" +#include "MinxCPU.h" +#include "MinxTimers.h" +#include "MinxIO.h" +#include "MinxIRQ.h" +#include "MinxPRC.h" +#include "MinxColorPRC.h" +#include "MinxLCD.h" +#include "MinxAudio.h" +#include "Multicart.h" + +// PRC Read/Write +#ifdef PERFORMANCE + +static INLINE uint8_t MinxPRC_OnRead(int cpu, uint32_t addr) +{ + if (addr >= 0x2100) { + // ROM Read + if (PM_ROM) return PM_ROM[addr & PM_ROM_Mask]; + } else if (addr >= 0x2000) { + // I/O Read (Unused) + return 0xFF; + } else if (addr >= 0x1000) { + // RAM Read + return PM_RAM[addr-0x1000]; + } else { + // BIOS Read + return PM_BIOS[addr]; + } + return 0xFF; +} + +static INLINE void MinxPRC_OnWrite(int cpu, uint32_t addr, uint8_t data) +{ + // RAM Write + if ((addr >= 0x1000) && (addr < 0x2000)) + PM_RAM[addr-0x1000] = data; +} + +#else + +#include "Multicart.h" + +#define MinxPRC_OnRead MinxCPU_OnRead +#define MinxPRC_OnWrite MinxCPU_OnWrite + +#endif + +// LCD Framebuffer +#define MinxPRC_LCDfb PM_RAM + +// Load state safe variables +#define POKELOADSS_START(size)\ + uint32_t rsize = 0;\ + uint32_t tmp32;\ + uint16_t tmp16;\ + if (size != bsize) return 0;\ + { tmp32 = 0; tmp16 = 0; } + +// -- Stream versions START +#define POKELOADSS_STREAM_32(var) {\ + rsize += (uint32_t)memstream_read(stream, (void *)&tmp32, 4);\ + var = tmp32;\ +} + +#define POKELOADSS_STREAM_16(var) {\ + rsize += (uint32_t)memstream_read(stream, (void *)&tmp16, 2);\ + var = tmp16;\ +} + +#define POKELOADSS_STREAM_8(var) {\ + rsize += (uint32_t)memstream_read(stream, (void *)&var, 1);\ +} + +#define POKELOADSS_STREAM_A(array, size) {\ + rsize += (uint32_t)memstream_read(stream, (void *)array, size);\ +} + +#define POKE_SEEK_CUR 1 + +#define POKELOADSS_STREAM_X(size) {\ + rsize += memstream_seek(stream, size, POKE_SEEK_CUR) ? 0 : size;\ +} +// -- Stream versions End + +#define POKELOADSS_END(size) {\ + tmp32 = 0; tmp16 = 0;\ + return (rsize == size) + tmp32 + (uint32_t)tmp16;\ +} + +// -- Stream versions START +#define POKESAVESS_STREAM_START(size)\ + uint32_t wsize = 0;\ + uint32_t tmp32 = size;\ + uint16_t tmp16;\ + if (memstream_write(stream, (void *)&tmp32, 4) != 4) return 0;\ + { tmp32 = 0; tmp16 = 0; } + +#define POKESAVESS_STREAM_32(var) {\ + tmp32 = (uint32_t)var;\ + wsize += (uint32_t)memstream_write(stream, (void *)&tmp32, 4);\ +} + +#define POKESAVESS_STREAM_16(var) {\ + tmp16 = (uint16_t)var;\ + wsize += (uint32_t)memstream_write(stream, (void *)&tmp16, 2);\ +} + +#define POKESAVESS_STREAM_8(var) {\ + wsize += (uint32_t)memstream_write(stream, (void *)&var, 1);\ +} + +#define POKESAVESS_STREAM_A(array, size) {\ + wsize += (uint32_t)memstream_write(stream, (void *)array, size);\ +} + +#define POKESAVESS_STREAM_X(size) {\ + tmp16 = 0;\ + for (tmp32=0; tmp32<(uint32_t)size; tmp32++) {\ + wsize += (uint32_t)memstream_write(stream, (void *)&tmp16, 1);\ + }\ +} +// -- Stream versions End + +#define POKESAVESS_END(size) {\ + tmp32 = 0; tmp16 = 0;\ + return (wsize == size) + tmp32 + (uint32_t)tmp16;\ +} + +// Stream I/O +typedef int TPokeMini_StreamIO(void *data, int size, void *ptr); + +// Create emulator and all interfaces +int PokeMini_Create(int flags, int soundfifo); + +// Destroy emulator and all interfaces +void PokeMini_Destroy(void); + +// Apply changes from command lines +void PokeMini_ApplyChanges(void); + +// Low power battery emulation +void PokeMini_LowPower(int enable); + +// Set LCD mode +void PokeMini_SetLCDMode(int mode); + +// Generate rumble offset +int PokeMini_GenRumbleOffset(int pitch); + +// Load BIOS file +int PokeMini_LoadBIOSFile(const char *filename); + +// Load FreeBIOS +int PokeMini_LoadFreeBIOS(void); + +// Check if file exist +int PokeMini_FileExist(const char *filename); + +// New MIN ROM +int PokeMini_NewMIN(uint32_t size); + +// Synchronize host time +int PokeMini_SyncHostTime(void); + +// Load EEPROM data +int PokeMini_LoadEEPROMFile(const char *filename); + +// Save EEPROM data +int PokeMini_SaveEEPROMFile(const char *filename); + +// Load emulator state from memory stream +int PokeMini_LoadSSStream(uint8_t *buffer, uint64_t size); + +// Save emulator state to memory stream +int PokeMini_SaveSSStream(uint8_t *buffer, uint64_t size); + +// Reset CPU +void PokeMini_Reset(int hardreset); + +// Internals, do not call directly! +void PokeMini_FreeColorInfo(void); + +#endif diff --git a/pm/src/core/freebios.c b/pm/src/core/freebios.c new file mode 100644 index 0000000..3b05404 --- /dev/null +++ b/pm/src/core/freebios.c @@ -0,0 +1,259 @@ +const unsigned char FreeBIOS[] = +{ + 0x9A,0x00,0xAB,0x00,0xAB,0x00,0x2F,0x02,0x41,0x02,0x53,0x02,0x65,0x02,0x77,0x02, + 0x89,0x02,0x9B,0x02,0xAD,0x02,0xBF,0x02,0xD1,0x02,0xE3,0x02,0xF5,0x02,0x07,0x03, + 0x19,0x03,0xAB,0x00,0xAB,0x00,0x60,0x04,0x2B,0x03,0xF1,0x03,0x3D,0x03,0x4F,0x03, + 0x61,0x03,0x73,0x03,0x85,0x03,0x97,0x03,0xA9,0x03,0xBB,0x03,0xCD,0x03,0xDF,0x03, + 0xF1,0xFF,0x9E,0x04,0x60,0x04,0x60,0x04,0xE4,0x04,0x60,0x04,0x0D,0x05,0x24,0x05, + 0x45,0x05,0x4C,0x05,0x5D,0x05,0x7C,0x05,0x92,0x05,0x9F,0x05,0xBB,0x05,0x60,0x04, + 0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04, + 0x60,0x04,0xD6,0x05,0xE3,0x05,0x60,0x04,0x60,0x04,0xF0,0x05,0x00,0x06,0x66,0x06, + 0x7A,0x06,0x8A,0x06,0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04,0x60,0x04, + 0x60,0x04,0x60,0x04,0x60,0x04,0x00,0x00,0x98,0x06,0xB4,0x20,0x38,0xCE,0xCD,0xDD, + 0x08,0x02,0xD9,0x08,0x01,0xDD,0x00,0x7C,0xDD,0x02,0x00,0x9F,0xC0,0xB4,0x20,0x38, + 0xCE,0xCD,0xCE,0xCE,0xCE,0xCF,0xCF,0x6E,0x00,0x20,0xDD,0x80,0x00,0xCE,0xC4,0x01, + 0xF3,0x01,0x00,0xD9,0x00,0x03,0xD9,0x01,0x30,0xD9,0x02,0xC0,0xF2,0xE1,0x00,0xC6, + 0xA0,0x06,0xBE,0x82,0x20,0x79,0x84,0x79,0x85,0x79,0x86,0x79,0x87,0x79,0x88,0x79, + 0x89,0x38,0xC6,0x00,0x10,0x60,0x92,0xD6,0x00,0x20,0xEF,0xF9,0xFF,0xF2,0x05,0x01, + 0xDD,0xFE,0xAF,0xF2,0x1D,0x01,0xD9,0x80,0x0A,0xD9,0x81,0x01,0xDC,0x10,0x20,0xEF, + 0x40,0x00,0xF2,0x2F,0x00,0xEF,0x3A,0x00,0x38,0xDD,0x80,0x00,0xDD,0x81,0x07,0x78, + 0x82,0x78,0x83,0xD8,0x01,0xEF,0xC6,0x00,0x10,0x60,0x92,0xD6,0x00,0x20,0xEF,0xF9, + 0xFF,0xC4,0x00,0x00,0xCF,0xE4,0xCF,0xE8,0xCF,0xEC,0x4C,0x52,0xB0,0xFF,0x9C,0xC0, + 0xF3,0xD0,0x1F,0xCE,0xD0,0x00,0x21,0x32,0x4D,0xF8,0xCE,0xD0,0x01,0x21,0x32,0x4E, + 0xF8,0xB1,0x03,0xA0,0xB0,0x01,0xC6,0x7D,0x13,0xB1,0x03,0xF2,0x51,0x00,0xC6,0x88, + 0x13,0xB1,0x04,0xF2,0x49,0x00,0xDC,0x10,0x20,0xEE,0x0B,0x00,0xC6,0x94,0x13,0xB0, + 0x08,0xB1,0x04,0xF2,0x39,0x00,0xF2,0xCB,0xFF,0xEE,0x0B,0x00,0xC6,0xA0,0x13,0xB0, + 0x0C,0xB1,0x04,0xF2,0x29,0x00,0xF2,0x2C,0x00,0xC6,0x94,0x13,0xB0,0x00,0xB1,0x04, + 0xF2,0x17,0x00,0xF2,0x1F,0x00,0xA8,0xF5,0xBB,0xC6,0xA0,0x13,0xB0,0x00,0xB1,0x04, + 0xF2,0x07,0x00,0xF2,0x0F,0x00,0xF3,0x6A,0xFF,0x60,0x92,0xF5,0xFD,0xF8,0x60,0x92, + 0x80,0xF5,0xFC,0xF8,0xB0,0xFF,0xB1,0xFF,0xF5,0xFF,0x88,0xEF,0xF9,0xFF,0xF8,0xB1, + 0x00,0xDD,0x10,0x08,0xD8,0x19,0xCF,0x79,0x20,0xDD,0x21,0x30,0xDD,0x22,0x02,0x79, + 0x23,0xDD,0x24,0x02,0x79,0x25,0x79,0x26,0x79,0x40,0x79,0x44,0xDD,0x50,0xFF,0x79, + 0x51,0x79,0x54,0x79,0x55,0xD9,0x60,0x0C,0xD8,0x61,0xFB,0xD9,0x61,0x08,0xD9,0x61, + 0x04,0xDD,0x61,0x20,0xDD,0x60,0x32,0x79,0x62,0x79,0x70,0x79,0x71,0xDD,0xFE,0x81, + 0xDD,0xFE,0x1F,0xF8,0xA1,0xC5,0xFE,0x20,0xB5,0xE3,0xB5,0xA4,0xB5,0xAD,0xB5,0x00, + 0xB5,0x10,0xB5,0xEE,0xB5,0x40,0xB5,0xA2,0xB5,0xA0,0xB5,0xC0,0xB5,0xA6,0xB5,0x2F, + 0xA9,0xF8,0xC5,0xFE,0x20,0xB5,0xE3,0xB3,0xB0,0x6B,0xB5,0x00,0xB5,0x10,0xB1,0x60, + 0x91,0xDD,0xFF,0x00,0xF5,0xFC,0x99,0x83,0xCE,0xBE,0xB8,0xEF,0xEC,0xFF,0xF8,0xA5, + 0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0x00,0x02,0xAC,0xAD,0xF3,0xC8, + 0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0xEE,0x01,0xAC,0xAD, + 0xF3,0xBC,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0xDC,0x01, + 0xAC,0xAD,0xF3,0xB0,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA, + 0xCA,0x01,0xAC,0xAD,0xF3,0xA4,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01, + 0x20,0xEA,0xB8,0x01,0xAC,0xAD,0xF3,0x98,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20, + 0xDC,0x01,0x20,0xEA,0xA6,0x01,0xAC,0xAD,0xF3,0x8C,0x1E,0xA5,0xA4,0xCE,0xC5,0x00, + 0xB4,0x20,0xDC,0x01,0x20,0xEA,0x94,0x01,0xAC,0xAD,0xF3,0x80,0x1E,0xA5,0xA4,0xCE, + 0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0x82,0x01,0xAC,0xAD,0xF3,0x74,0x1E,0xA5, + 0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0x70,0x01,0xAC,0xAD,0xF3,0x68, + 0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0x5E,0x01,0xAC,0xAD, + 0xF3,0x5C,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0x4C,0x01, + 0xAC,0xAD,0xF3,0x50,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA, + 0x3A,0x01,0xAC,0xAD,0xF3,0x44,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01, + 0x20,0xEA,0x28,0x01,0xAC,0xAD,0xF3,0x38,0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20, + 0xDC,0x01,0x20,0xEA,0x16,0x01,0xAC,0xAD,0xF3,0x2C,0x1E,0xA5,0xA4,0xCE,0xC5,0x00, + 0xB4,0x20,0xDC,0x01,0x20,0xEA,0x04,0x01,0xAC,0xAD,0xF3,0x62,0x1E,0xA5,0xA4,0xCE, + 0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0xF2,0x00,0xAC,0xAD,0xF3,0x14,0x1E,0xA5, + 0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0xE0,0x00,0xAC,0xAD,0xF3,0x08, + 0x1E,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0xCE,0x00,0xAC,0xAD, + 0xF3,0xFC,0x1D,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0xBC,0x00, + 0xAC,0xAD,0xF3,0xF0,0x1D,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA, + 0xAA,0x00,0xAC,0xAD,0xF3,0xE4,0x1D,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01, + 0x20,0xEA,0x98,0x00,0xAC,0xAD,0xF3,0xD8,0x1D,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20, + 0xDC,0x01,0x20,0xEA,0x86,0x00,0xAC,0xAD,0xF3,0xCC,0x1D,0xA5,0xA4,0xCE,0xC5,0x00, + 0xB4,0x20,0xDC,0x01,0x20,0xEA,0x74,0x00,0xAC,0xAD,0xF3,0xC0,0x1D,0xA5,0xA4,0xCE, + 0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0x62,0x00,0xAC,0xAD,0xF3,0xB4,0x1D,0xA5, + 0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEA,0x50,0x00,0xAC,0xAD,0xF3,0xA8, + 0x1D,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x01,0x20,0xEF,0x2A,0x00,0xDC,0x01, + 0x10,0xEF,0xA8,0xFC,0xDC,0x71,0x04,0xEE,0x0D,0x00,0xDC,0x02,0x40,0xEE,0x07,0x00, + 0xD8,0x71,0xFB,0xD9,0x02,0x80,0xDC,0x01,0x80,0xEE,0x11,0x00,0xDC,0x02,0x20,0xEF, + 0x14,0x00,0xAC,0xAD,0xF3,0xD7,0x1B,0xAC,0xAD,0xF3,0x31,0x1D,0xD9,0x01,0x20,0xDC, + 0x02,0x20,0xEF,0xF3,0xFF,0xDD,0x29,0x80,0xAC,0xAD,0xF9,0xDC,0x71,0x04,0xEE,0x0D, + 0x00,0xDC,0x02,0x40,0xEE,0x07,0x00,0xD8,0x71,0xFB,0xD9,0x02,0x80,0xDC,0x01,0x80, + 0xEE,0x0A,0x00,0xCF,0x68,0x03,0x00,0xAC,0xAD,0xF3,0xA2,0x1B,0xD9,0x01,0x20,0xF8, + 0xF9,0xD8,0x80,0xF7,0xDD,0xFE,0xAE,0xDD,0xFE,0xAC,0xDD,0xFE,0x28,0xDD,0xFE,0xA5, + 0xD8,0x02,0xE3,0xD8,0x81,0xFE,0xD9,0x02,0x01,0xD9,0x24,0x02,0xD9,0x21,0x30,0xD8, + 0x01,0xDF,0xD8,0x02,0xE3,0xA7,0x9F,0x80,0xCE,0xAE,0xAF,0xD9,0x02,0x10,0xD9,0x81, + 0x01,0xF2,0x61,0xFD,0xDD,0xFE,0xAF,0xD8,0x02,0xDF,0xD9,0x00,0x03,0xF8,0xA5,0xA4, + 0x9F,0xC0,0xCE,0xC5,0x00,0xB4,0x20,0x4C,0x80,0x44,0x21,0x22,0x0C,0xA0,0x4C,0x23, + 0x44,0x24,0xA0,0x4C,0x25,0x44,0x26,0xA0,0xDD,0x23,0x00,0xDD,0x24,0x00,0xDD,0x25, + 0x80,0xDD,0x26,0x00,0xD9,0x21,0x0C,0xDD,0x29,0x80,0xDD,0x80,0x00,0xF2,0x92,0xFF, + 0xA8,0x79,0x25,0x78,0x26,0xA8,0x79,0x23,0x78,0x24,0xA8,0x79,0x80,0x22,0xF3,0x78, + 0x21,0xAC,0xAD,0xF9,0x9F,0xC0,0xCF,0x6E,0x00,0x20,0xCE,0xC5,0x00,0xB4,0x20,0xF2, + 0xBE,0xFC,0xDD,0x23,0x00,0xDD,0x24,0x00,0xDD,0x25,0x80,0xDD,0x26,0x00,0xDD,0x29, + 0x80,0xDD,0x80,0x00,0xDD,0x21,0x0C,0xF2,0x58,0xFF,0xF3,0x9F,0xFB,0xAF,0xA5,0xA1, + 0xCE,0xC5,0x00,0xC5,0x00,0x20,0xCE,0x84,0xCE,0x84,0xCE,0x25,0x03,0xCE,0x2C,0xA9, + 0xAD,0xF3,0x23,0x00,0xF2,0x27,0x00,0xAF,0xA7,0xEE,0x0A,0x00,0x32,0x3F,0xEE,0x0D, + 0x00,0x80,0xF3,0x0C,0x00,0x28,0xEE,0x05,0x00,0x88,0xF3,0x04,0x00,0xB0,0xFF,0xF9, + 0xF2,0xCC,0xFF,0x38,0xF9,0xAF,0xF2,0x05,0x00,0xF3,0x13,0x00,0xAF,0xA5,0xA4,0xCE, + 0xC5,0x00,0xB4,0x20,0x44,0x00,0xCE,0x8C,0xCE,0x8C,0xAC,0xAD,0xF8,0xAF,0xA5,0xA4, + 0xCE,0xC5,0x00,0xB4,0x20,0x48,0xDC,0x80,0x08,0xA7,0xD8,0x80,0xF7,0xDD,0xFE,0x81, + 0x79,0xFE,0xAF,0xEE,0x04,0x00,0xD9,0x80,0x08,0xAC,0xAD,0xF8,0xA5,0xA4,0xCE,0xC5, + 0x00,0xB4,0x20,0xF2,0x6F,0xFC,0xDD,0xFE,0xAF,0xD9,0x80,0x04,0xD9,0x81,0x01,0xAC, + 0xAD,0xF9,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xF2,0x59,0xFC,0xAC,0xAD,0xF9,0xA5, + 0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xD8,0x80,0xF7,0xDD,0xFE,0xAE,0xDD,0xFE,0xAC,0xDD, + 0xFE,0x28,0xDD,0xFE,0xA5,0xD8,0x81,0xFE,0xAC,0xAD,0xF9,0xA5,0xA4,0xCE,0xC5,0x00, + 0xB4,0x20,0x9F,0xC0,0xDC,0x01,0x80,0xEF,0x0A,0x00,0xD9,0x01,0x80,0xD9,0x01,0x40, + 0xD8,0x01,0xDF,0xAC,0xAD,0xF9,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xD8,0x00,0xFC, + 0xAC,0xAD,0xF9,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xD9,0x00,0x03,0xAC,0xAD,0xF9, + 0xAF,0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xDC,0x53,0x02,0x9E,0x01,0xAC,0xAD,0xF8, + 0xA5,0xA4,0xCE,0xC5,0x00,0xB4,0x20,0xA6,0xA2,0xA3,0xA1,0xCF,0xB1,0x9F,0xC0,0x46, + 0x96,0x01,0xCE,0xC1,0xEE,0x0E,0x00,0xC2,0x0A,0x00,0x5E,0x9A,0x56,0x9A,0xA1,0x4E, + 0x9A,0xF3,0x04,0x00,0xC2,0x07,0x00,0xA0,0x4E,0x9A,0x46,0x9A,0x5E,0x9A,0x56,0x9A, + 0xCE,0xCF,0xCF,0xED,0x46,0x9A,0x5E,0x9A,0x56,0xCE,0xCE,0xCF,0xE9,0xD9,0x02,0x80, + 0xB6,0xFF,0xD9,0x02,0x80,0x47,0xD9,0x02,0x80,0x31,0xA8,0xCE,0xC3,0xEE,0x0A,0x00, + 0xAF,0x51,0xA8,0x58,0x41,0xA7,0xF2,0x0B,0x00,0xA8,0x22,0x01,0xA9,0xAB,0xAA,0xAE, + 0xAC,0xAD,0xF9,0xCE,0xCC,0xF4,0xA5,0xA1,0xCE,0xC5,0x00,0xC5,0x81,0x20,0xCE,0x25, + 0xF1,0x22,0x07,0xCE,0x84,0xCE,0x2C,0xA9,0xAD,0xF9,0xA5,0xA4,0xCE,0xC5,0x00,0xB4, + 0x20,0x44,0x81,0xCE,0x8C,0x22,0x07,0xAC,0xAD,0xF9,0xAF,0xA5,0xA4,0xCE,0xC5,0x00, + 0xB4,0x20,0xDC,0x01,0x08,0xAC,0xAD,0xF8,0xB7,0x02,0xF5,0xFF,0xB7,0x00,0xF9,0xFF, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF8,0x04,0x82,0xE1,0xE1,0x31,0x31, + 0x39,0x39,0x39,0x39,0x39,0x39,0x31,0x31,0xE1,0xE1,0x82,0x06,0xFA,0x04,0xF8,0x00, + 0xFE,0x82,0xEA,0x3A,0xFE,0x82,0xEA,0x96,0xFC,0xC7,0xAA,0xBB,0xFF,0xC7,0xAA,0xBA, + 0xFE,0x82,0xAA,0xD6,0xFE,0x8A,0xFE,0xC6,0xBB,0xC7,0xFD,0xB6,0xAB,0xAB,0xDA,0x7E, + 0x7C,0x7C,0x40,0x40,0x00,0x38,0x7C,0x44,0x7C,0x38,0x00,0x3C,0x7C,0x20,0x7C,0x3C, + 0x00,0x00,0x7C,0x7C,0x7C,0x74,0x6C,0x54,0x64,0x44,0x44,0x44,0x44,0x6C,0x38,0x00, + 0x7C,0x7C,0x08,0x10,0x7C,0x7C,0x00,0x38,0x7C,0x44,0x7C,0x38,0x00,0x00,0x00,0x38, + 0x44,0x44,0x00,0x78,0x14,0x14,0x78,0x00,0x7C,0x14,0x14,0x68,0x00,0x04,0x7C,0x04, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0x20,0x20,0x20,0x20,0x46,0x72,0x65,0x65,0x77,0x61,0x72,0x65,0x20,0x20,0x20,0x20, + 0x50,0x6F,0x6B,0x65,0x6D,0x6F,0x6E,0x4D,0x69,0x6E,0x69,0x20,0x42,0x49,0x4F,0x53, + 0x20,0x20,0x56,0x65,0x72,0x73,0x69,0x6F,0x6E,0x20,0x20,0x31,0x2E,0x33,0x20,0x20, + 0x20,0x62,0x79,0x20,0x54,0x65,0x61,0x6D,0x20,0x50,0x6F,0x6B,0x65,0x6D,0x65,0x20, +}; diff --git a/pm/src/core/freebios.h b/pm/src/core/freebios.h new file mode 100644 index 0000000..95f83f0 --- /dev/null +++ b/pm/src/core/freebios.h @@ -0,0 +1,25 @@ +/* + PokeMini - Pokémon-Mini Emulator + Copyright (C) 2009 JustBurn + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef FREEBIOS_H +#define FREEBIOS_H + +// Free BIOS (4KB) +extern const unsigned char FreeBIOS[]; + +#endif diff --git a/pm/src/core/pm_glue.c b/pm/src/core/pm_glue.c new file mode 100644 index 0000000..c4a7c32 --- /dev/null +++ b/pm/src/core/pm_glue.c @@ -0,0 +1,132 @@ +/* PokeMiniEmu: what PokeMini.c, PMCommon.c and the colour PRC give the core, cut down for the Paradise (no files, + * no colour, no multicart). The cartridge is read straight from the cached flash window (PM_ROM points there). + * Based on PokeMini by JustBurn (GPL 3 or later), see LICENSE_pokemini. Author of the changes: mameise */ +#include "PokeMini.h" +#include "freebios.h" +#include + +int PokeMini_FreeBIOS = 0, PokeMini_Flags = 0, PokeMini_LCDMode = LCDMODE_ANALOG, PokeMini_ColorFormat = 0, PokeMini_HostBattStatus = 0; +uint8_t PM_BIOS[4096]; +uint8_t PM_RAM[8192]; +uint8_t *PM_ROM; +int PM_ROM_Alloc, PM_ROM_Size, PM_ROM_Mask; +int PokeHWCycles; + +static const uint8_t PM_IO_INIT[256] = { + 0x7F, 0x20, 0x5C, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, + 0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x30, 0x02, 0x00, 0x02, 0x00, 0x00, 0x40, 0x00, 0xC0, 0x40, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, + 0xFF, 0x00, 0xFF, 0x00, 0x01, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x32, 0x64, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x40, 0xFF }; + +/* ---- memory: a small heap for the core's buffers (EEPROM, LCD) ---- */ +#ifndef PM_HEAP +#define PM_HEAP 0x5C00 +#endif +static uint8_t g_heap[PM_HEAP] __attribute__((aligned(8))); +static uint32_t g_heap_n; +#ifndef PM_HOST +void *malloc(size_t n) { n = (n + 7u) & ~7u; if (g_heap_n + n > sizeof g_heap) return 0; void *p = g_heap + g_heap_n; g_heap_n += n; return p; } +void free(void *p) { (void)p; } +#endif + +int GetMultiple2Mask(int input) +{ + if (input) input--; + input |= input >> 1; input |= input >> 2; input |= input >> 4; input |= input >> 8; input |= input >> 16; + return input; +} + +/* ---- the colour PRC is not there ---- */ +int PRCColorEnable; uint8_t *PRCColorPixels, *PRCColorPixelsOld, *PRCColorMap, *PRCColorTop; unsigned int PRCColorOffset; uint8_t PRCColorFlags; +int MinxColorPRC_Create(void) { return 1; } +void MinxColorPRC_Reset(int hardreset) { (void)hardreset; } +uint8_t MinxColorPRC_ReadReg(int cpu, uint8_t reg) { (void)cpu; (void)reg; return 0xFF; } +void MinxColorPRC_WriteReg(uint8_t reg, uint8_t val) { (void)reg; (void)val; } +void MinxColorPRC_WriteFramebuffer(uint16_t addr, uint8_t data) { (void)addr; (void)data; } +void MinxColorPRC_WriteLCD(uint16_t addr, uint8_t data) { (void)addr; (void)data; } +void MinxPRC_NoRender_Color(void) {} + +/* ---- the Pokemon mini ---- */ +int PokeMini_Create(int flags, int soundfifo) +{ + (void)soundfifo; + g_heap_n = 0; + memset(PM_BIOS, 0xFF, 4096); memset(PM_RAM, 0xFF, 8192); + PM_ROM_Mask = 0x1FFF; PM_ROM_Size = 0x2000; PM_ROM = PM_RAM; + memcpy(PM_IO, PM_IO_INIT, 256); + if (!MinxCPU_Create() || !MinxTimers_Create() || !MinxIO_Create() || !MinxIRQ_Create() || !MinxPRC_Create() || !MinxLCD_Create() || !MinxAudio_Create(0, 0)) return 0; + PokeMini_Flags = flags; + return 1; +} +int PokeMini_LoadFreeBIOS(void) { PokeMini_FreeBIOS = 1; memcpy(PM_BIOS, FreeBIOS, 4096); return 1; } +/* the cartridge in the flash window: size rounded up to a power of two (reads behind it repeat the start) */ +void pm_set_rom(const uint8_t *rom, uint32_t len) { PM_ROM = (uint8_t *)rom; PM_ROM_Mask = GetMultiple2Mask((int)len); PM_ROM_Size = PM_ROM_Mask + 1; } +void PokeMini_Reset(int hardreset) +{ + if (hardreset) { memset(PM_RAM, 0xFF, 8192); memcpy(PM_IO, PM_IO_INIT, 256); } + MinxTimers_Reset(hardreset); MinxIRQ_Reset(hardreset); MinxIO_Reset(hardreset); MinxPRC_Reset(hardreset); + MinxLCD_Reset(hardreset); MinxAudio_Reset(hardreset); MinxCPU_Reset(hardreset); +} +/* the clock of the game from the Paradise's (the BIOS then skips asking for the time) */ +void pm_set_time(int y, int mo, int d, int h, int mi, int s) +{ + MinxIO_SetTimeStamp((uint8_t)(y % 100), (uint8_t)mo, (uint8_t)d, (uint8_t)h, (uint8_t)mi, (uint8_t)s); + PMR_SEC_CTRL = 0x01; MinxTimers.SecTimerCnt = 0; +} + +/* ---- the state in a buffer (as PokeMini's state files, without the colour part) ---- */ +uint64_t memstream_read(memstream_t *s, void *d, uint64_t n) { if (s->pos + n > s->size) n = s->size - s->pos; memcpy(d, s->buf + s->pos, (size_t)n); s->pos += (uint32_t)n; return n; } +uint64_t memstream_write(memstream_t *s, const void *d, uint64_t n) { if (s->pos + n > s->size) n = s->size - s->pos; memcpy(s->buf + s->pos, d, (size_t)n); s->pos += (uint32_t)n; return n; } +int64_t memstream_seek(memstream_t *s, int64_t off, int whence) { int64_t p = whence == 1 ? s->pos + off : off; if (p < 0 || p > s->size) return -1; s->pos = (uint32_t)p; return 0; } +uint64_t memstream_pos(memstream_t *s) { return s->pos; } +#define PM_STATE_ID 0x31534D50u /* "PMS1" */ +static void tag(memstream_t *s, const char *t) { memstream_write(s, t, 4); } +uint32_t pm_state_save(uint8_t *buf, uint32_t size) +{ + memstream_t s = { buf, size, 0 }; uint32_t v = PM_STATE_ID, n; + memstream_write(&s, &v, 4); + tag(&s, "RAM-"); n = 0x1000; memstream_write(&s, &n, 4); memstream_write(&s, PM_RAM, 0x1000); + tag(&s, "REG-"); n = 256; memstream_write(&s, &n, 4); memstream_write(&s, PM_IO, 256); + tag(&s, "CPU-"); MinxCPU_SaveStateStream(&s); + tag(&s, "IRQ-"); MinxIRQ_SaveStateStream(&s); + tag(&s, "TMR-"); MinxTimers_SaveStateStream(&s); + tag(&s, "PIO-"); MinxIO_SaveStateStream(&s); + tag(&s, "PRC-"); MinxPRC_SaveStateStream(&s); + tag(&s, "LCD-"); MinxLCD_SaveStateStream(&s); + tag(&s, "AUD-"); MinxAudio_SaveStateStream(&s); + tag(&s, "END-"); n = 0; memstream_write(&s, &n, 4); + return s.pos < size ? s.pos : 0; /* 0: did not fit */ +} +int pm_state_load(uint8_t *buf, uint32_t size) +{ + memstream_t s = { buf, size, 0 }; uint32_t v = 0, n; char t[4]; + if (memstream_read(&s, &v, 4) != 4 || v != PM_STATE_ID) return 0; + for (;;) { + if (memstream_read(&s, t, 4) != 4 || memstream_read(&s, &n, 4) != 4) return 0; + int ok = 1; + if (!memcmp(t, "RAM-", 4)) ok = n == 0x1000 && memstream_read(&s, PM_RAM, 0x1000) == 0x1000; + else if (!memcmp(t, "REG-", 4)) ok = n == 256 && memstream_read(&s, PM_IO, 256) == 256; + else if (!memcmp(t, "CPU-", 4)) ok = MinxCPU_LoadStateStream(&s, n); + else if (!memcmp(t, "IRQ-", 4)) ok = MinxIRQ_LoadStateStream(&s, n); + else if (!memcmp(t, "TMR-", 4)) ok = MinxTimers_LoadStateStream(&s, n); + else if (!memcmp(t, "PIO-", 4)) ok = MinxIO_LoadStateStream(&s, n); + else if (!memcmp(t, "PRC-", 4)) ok = MinxPRC_LoadStateStream(&s, n); + else if (!memcmp(t, "LCD-", 4)) ok = MinxLCD_LoadStateStream(&s, n); + else if (!memcmp(t, "AUD-", 4)) ok = MinxAudio_LoadStateStream(&s, n); + else if (!memcmp(t, "END-", 4)) return 1; + else ok = memstream_seek(&s, n, 1) == 0; + if (!ok) return 0; + } +} diff --git a/pm/src/stub/retro_inline.h b/pm/src/stub/retro_inline.h new file mode 100644 index 0000000..371668a --- /dev/null +++ b/pm/src/stub/retro_inline.h @@ -0,0 +1,3 @@ +#ifndef INLINE +#define INLINE inline +#endif diff --git a/pm/src/stub/stdlib.h b/pm/src/stub/stdlib.h new file mode 100644 index 0000000..2761388 --- /dev/null +++ b/pm/src/stub/stdlib.h @@ -0,0 +1,8 @@ +/* PokeMiniEmu: the few C library parts the PokeMini core needs (no C library on the Paradise) */ +#ifndef PM_STDLIB_H +#define PM_STDLIB_H +#include +void *malloc(size_t n); +void free(void *p); +static inline int abs(int x) { return x < 0 ? -x : x; } +#endif diff --git a/pm/src/stub/streams/memory_stream.h b/pm/src/stub/streams/memory_stream.h new file mode 100644 index 0000000..c9f51f5 --- /dev/null +++ b/pm/src/stub/streams/memory_stream.h @@ -0,0 +1,11 @@ +/* PokeMiniEmu: a small memory stream for the core's state (replaces libretro-common's) */ +#ifndef PM_MEMSTREAM_H +#define PM_MEMSTREAM_H +#include +#include +typedef struct memstream { uint8_t *buf; uint32_t size, pos; } memstream_t; +uint64_t memstream_read(memstream_t *s, void *d, uint64_t n); +uint64_t memstream_write(memstream_t *s, const void *d, uint64_t n); +int64_t memstream_seek(memstream_t *s, int64_t off, int whence); +uint64_t memstream_pos(memstream_t *s); +#endif diff --git a/pm/src/stub/string.h b/pm/src/stub/string.h new file mode 100644 index 0000000..9f89b33 --- /dev/null +++ b/pm/src/stub/string.h @@ -0,0 +1,9 @@ +#ifndef PM_STRING_H +#define PM_STRING_H +#include +void *memcpy(void *d, const void *s, size_t n); +void *memset(void *d, int c, size_t n); +void *memmove(void *d, const void *s, size_t n); +int memcmp(const void *a, const void *b, size_t n); +size_t strlen(const char *s); +#endif diff --git a/pm/test/devpm.py b/pm/test/devpm.py new file mode 100644 index 0000000..1e822a5 --- /dev/null +++ b/pm/test/devpm.py @@ -0,0 +1,181 @@ +# PokeMiniEmu (pm.bin) in Unicorn, as devt7.py: hardware calls caught, the screen into a picture. +# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms). +# python3 devv3.py [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir] +import sys, struct, subprocess, os +from unicorn import * +from unicorn.arm_const import * +elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3]) +RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each) +out = os.environ.get('OUT', '.') +syms = {} +for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 3: syms[p[2]] = int(p[0], 16) +fl = bytearray(open(img, 'rb').read()) +u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS) +u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4) +APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere) +u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000])) +u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000) +u.mem_map(0x10000000, 0x100000) +u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl)) +u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here) +u.mem_write(0x4000B014, struct.pack('= t: m = v + return m +def ret(uc, v=None): + if v is not None: uc.reg_write(UC_ARM_REG_R0, v) + uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1) +def h_begin(uc, *a): + x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3)) + rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc) +def h_row(uc, *a): + p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n)) + for v in d: + if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v + rect['x'] += 1 + if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1 + ret(uc) +def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc) +def h_btn(uc, *a): ret(uc, keys()) +def h_prog(uc, *a): + ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = bytes(uc.mem_read(src, 0x1000)); a = ad & 0xFFFFFF + uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc) +def h_erase(uc, *a): + a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF + uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc) +def h_back(uc, *a): state['back'] = 1; uc.emu_stop() +def h_nop(uc, *a): ret(uc) +H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn, + 'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop, + 'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop} +for n, f in H.items(): + a = syms[n] & ~1 + u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a) +import builtins +if hasattr(builtins, '__gbprof'): u.hook_add(UC_HOOK_BLOCK, builtins.__gbprof[0]) +if os.environ.get('CACHESIM'): # test38: the I-cache of the flash window (16 KB, 32-byte lines, WAYS ways, LRU): misses per frame + _ways = int(os.environ.get('WAYS', '4')); _sets = 16384 // 32 // _ways + _cs = [[] for _ in range(_sets)]; state['miss'] = 0; state['acc'] = 0 + def _cr(uc, acc, a, sz, v, ud): + state['acc'] += 1 + ln = (a - 0x10000000) >> 5; s = _cs[ln % _sets] + if ln in s: s.remove(ln); s.append(ln); return + state['miss'] += 1; s.append(ln) + if len(s) > _ways: s.pop(0) + u.hook_add(UC_HOOK_MEM_READ, _cr, begin=0x10000000, end=0x100FFFFF) +def bad(uc, access, addr, size, value, ud): + print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False +u.hook_add(UC_HOOK_MEM_UNMAPPED, bad) +# 1.6.9 test22 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms +state['sh'] = 0; state['shms'] = [0, 0, 0, 0] +def _ahb(uc, acc, a, sz, v, ud): + state['sh'] = v & 7 + if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms']) +u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013) +if os.environ.get('MEMW'): + _mw = int(os.environ['MEMW'], 16) + u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F) +def shot(name): + from PIL import Image + im = Image.new('RGB', (128, 128)) + for y in range(128): + for x in range(128): + v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3)) + im.save(os.path.join(out, name)) +if os.environ.get('PMB'): # test: the Paradise's time in the mailbox (seconds since 1970, local) + _t = int(os.environ['PMB']); _c = int(os.environ.get('RTC0', '5000')) + u.mem_write(0x20000FC0, struct.pack(' 1: LK['tx'].append(v & 0xFF) # the first is the baud divisor + u.hook_add(UC_HOOK_MEM_WRITE, _uw, begin=0x4000B000, end=0x4000B000) + LK['w'] = os.fdopen(os.open(os.environ['LINKW'], os.O_RDWR), 'wb', buffering=0); LK['r'] = os.fdopen(os.open(os.environ['LINKR'], os.O_RDWR), 'rb', buffering=0) # (O_RDWR: no wait for the other end) +def link_ms(): + d = bytes(LK['tx']); LK['tx'] = bytearray() + LK['w'].write(struct.pack('> state['sh'])); state['shms'][min(state['sh'], 3)] += 1 + except UcError as ex: + print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break + pc = u.reg_read(UC_ARM_REG_PC) + state['ms'] += 1 + if 'w' in LK: link_ms() + v = struct.unpack('= w[0]: + d = 1 if w[1] > 0 else -1; state_enc['ph'] = (state_enc['ph'] + d) % 4; w[0] += 0.004 if (state_enc['ph'] % 4) else 0.02 + if state_enc['ph'] == 0: w[1] -= d + u.mem_write(0x4001A000, struct.pack('= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1 + if 'miss' in state and state['ms'] % 1000 == 0: + _f = struct.unpack(' 4 else 0 +bios = 0 +if len(sys.argv) > 5: b = open(sys.argv[5], 'rb').read(); fl[0x310000:0x310000 + len(b)] = b; bios = 0x310000; flags |= 4 +c = 0xA0000 + 0x140 +struct.pack_into('<6I16s', fl, c, 0x50584D50, 1, 0x200000, len(r), 0x300000, flags, b'POKEMON MINI') +struct.pack_into('<12H', fl, c + 40, 0x020, 0x002, 0x040, 0x001, 0x008, 0x010, 0x004, 0x000, 0x100, 0, 0, 0) +struct.pack_into('= 0 and addr < fs[i][0] + fs[i][1]: cnt[fs[i][2]] += size // 2 + else: cnt['?'] += size // 2 +import builtins +builtins.__gbprof = (blk, cnt) + +exec(open(os.path.join(os.path.dirname(__file__), 'devpm.py')).read()) +tot = sum(cnt.values()) +for n, c in cnt.most_common(25): print('%6.2f%% %s' % (100 * c / tot, n)) diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..e5f42a2 --- /dev/null +++ b/robots.txt @@ -0,0 +1,8 @@ +User-agent: * +Allow: / +Disallow: /api/ +Disallow: /admin.html +Disallow: /account.html +Disallow: /ParamixStudio.html +Disallow: /paramix-studio-ko-source.tar.gz +Sitemap: https://tama.itosm.co.kr/sitemap.xml diff --git a/scripts/build-menu-ko.cjs b/scripts/build-menu-ko.cjs new file mode 100644 index 0000000..77194ff --- /dev/null +++ b/scripts/build-menu-ko.cjs @@ -0,0 +1,85 @@ +// Generate compact two-byte menu strings; storage/config structures stay upstream-compatible. +const fs=require('fs'),path=require('path');const root=path.resolve(__dirname,'..'),dir=path.join(root,'feld/src/feld'); +const tr={};for(const row of fs.readFileSync(dir+'/ko.tsv','utf8').split(/\r?\n/)){if(!row)continue;const p=row.indexOf('\t');tr[row.slice(0,p)]=row.slice(p+1);} +const fields={LAND:'랜드',WATER:'워터',SKY:'스카이',FOREST:'포레스트',TROPICAL:'트로피컬',GLACIER:'글레이셔'}; +const chars=[...new Set((Object.values({...tr,...fields}).join('')+'다마고치 편집지역과 저장다마포인트아이템프로그램A 이동 B 선택 C 뒤로'))].filter(x=>x.charCodeAt(0)>127).sort(); +const native=require('../src/core.js').KO_CHARS; +const wanted=new Set([...chars,...native]); +const glyphs=new Map();const bdf=fs.readFileSync(root+'/third-party/Galmuri9.bdf','utf8'); +for(const block of bdf.split('STARTCHAR ').slice(1)){ + const cp=Number(block.match(/ENCODING (\d+)/)?.[1]);if(!wanted.has(String.fromCodePoint(cp||0)))continue; + const [w,h,x,y]=block.match(/BBX (-?\d+) (-?\d+) (-?\d+) (-?\d+)/).slice(1).map(Number); + const rows=block.split(/BITMAP\r?\n/)[1].split(/\r?\n/).slice(0,h).map(x=>parseInt(x,16)); + // 10x10 canvas with the baseline at y=9; Galmuri9's Hangul is nine pixels tall. + const bits=new Uint8Array(13);for(let r=0;r=10||yy<0||yy>=10)throw Error('Glyph crop: '+String.fromCodePoint(cp)); + const n=yy*10+xx;bits[n>>3]|=128>>(n&7); + } + glyphs.set(cp,[...bits]); +} +for(const c of chars)if(!glyphs.has(c.codePointAt(0)))throw Error('Missing glyph '+c); +for(const c of native)if(!glyphs.has(c.codePointAt(0)))throw Error('Missing native glyph '+c); +const allGlyphs=[...chars,...native]; +const font=Buffer.alloc(8+allGlyphs.length*13);font.writeUInt32LE(0x31464f4b,0);font.writeUInt32LE(allGlyphs.length,4); +allGlyphs.forEach((c,i)=>font.set(glyphs.get(c.codePointAt(0)),8+i*13)); +fs.writeFileSync(root+'/src/menu-font-ko.js',`// Generated Galmuri9 native Korean font. See third-party/Galmuri-OFL.txt. +(function(root){ +const fixed=${JSON.stringify(chars.join(''))}, native=${JSON.stringify(native)}, data=${JSON.stringify(font.toString('base64'))}; +function encode(s,max=255){let out='';for(const c of s){let v=c;if(c.charCodeAt(0)>127){let n=fixed.indexOf(c);if(n<0){let k=native.indexOf(c);if(k<0)throw Error('본체 메뉴에서 지원하지 않는 문자: '+c);n=fixed.length+k;}v=String.fromCharCode(128+(n>>7),128+(n&127));}if(out.length+v.length>max)break;out+=v;}return out;} +function font(){return typeof Buffer!=='undefined'?new Uint8Array(Buffer.from(data,'base64')):Uint8Array.from(atob(data),c=>c.charCodeAt(0));} +root.ParamixKoreanMenu={encode,font,fixed,native}; +if(typeof module!=='undefined')module.exports=root.ParamixKoreanMenu; +})(typeof window!=='undefined'?window:globalThis); +`); +const enc=s=>[...s].map(c=>c.charCodeAt(0)<128?c.replace(/\\/g,'\\\\').replace(/"/g,'\\"'):[128+(chars.indexOf(c)>>7),128+(chars.indexOf(c)&127)].map(x=>'\\'+x.toString(8).padStart(3,'0')).join('')).join(''); +fs.writeFileSync(dir+'/font_ko.h','/* ITOSM Korean menu subset of Galmuri9, quiple, SIL OFL 1.1.\n * See third-party/Galmuri-OFL.txt. Generated by scripts/build-menu-ko.cjs. */\n#define KO_GLYPHS '+chars.length+'\nstatic const unsigned char ko_font[KO_GLYPHS][13]={\n'+chars.map(c=>'{'+glyphs.get(c.codePointAt(0)).join(',')+'}, /* '+c+' */').join('\n')+'\n};\n'); +let s=fs.readFileSync(dir+'/main.c','utf8').replace(/\r\n/g,'\n');const counts={}; +s=s.replace(/"((?:[^"\\]|\\.)*)"/g,(whole,k)=>{if(!(k in tr))return whole;counts[k]=(counts[k]||0)+1;return '"'+enc(tr[k])+'"';}); +for(const k of Object.keys(tr))if(!counts[k])throw Error('Unused menu translation '+k); +s=s.replace('#include "font.h"','#include "font.h"\n#include "font_ko.h"'); +const from=s.indexOf('static int text_w('),to=s.indexOf('static void text(int',from); +s=s.slice(0,from)+`/* Korean pairs have both bytes >= 128. Never interpret truncated input as an index. */ +static int ko_pair(const char *s){ return (u8)s[0]>=128 && (u8)s[1]>=128; } +static int ko_scale(const char *s,int sc){ for(int i=0;s[i];i++) if((u8)s[i]>=128) return 1; return sc; } +static int text_w(const char *s,int sc){ sc=ko_scale(s,sc); int w=0; for(int i=0;s[i];i++){if(ko_pair(s+i)){w+=10*sc;i++;}else w+=6*sc;}return w?w-sc:0; } +static void textn(int x,int y,const char *s,int n,u16 c,int sc){ + sc=ko_scale(s,sc); const int limit=x+n*6*sc; + for(int i=0;ilimit || x+10*sc>128)break; + const volatile u8 *g=0; + if(k>3]&(128>>(p&7)))rect(x+q*sc,y+r*sc,x+(q+1)*sc,y+(r+1)*sc,c);} + x+=10*sc; + }else{ + if(x+5*sc>limit || x+5*sc>128)break; + int ch=(u8)s[i];if(ch>=128)ch='?';if(ch>=0x60 && ch!='x')ch-=32; + int k=glyph(ch);if(k<0||k>=96)k='?'-32; + const u8 *g=g_font[k]; + for(int r=0;r<7;r++)for(int q=0;q<5;q++)if(g[r]&(16>>q))rect(x+q*sc,y+r*sc,x+(q+1)*sc,y+(r+1)*sc,c); + x+=6*sc; + } + } +} +`+s.slice(to); +// Bottom help rows used to be seven pixels tall. Keep the ten-pixel Hangul inside 128px. +s=s.replace(/ctext\(119,/g,'ctext(117,').replace(/text\(5,119,/g,'text(5,117,'); +// In the tall tile the status is below a Korean title (10px vs the original 14px). +s=s.replace('text(9,y+19,st,stc,1);','text(9,y+17,st,stc,1);'); +s=s.replace('text(9,y+4,name,c,2);\n int w=text_w(st,1), x=121-w, nx=9+text_w(name,2)+4; if(x' {const char *a="'+a+'";int i=0;while(a[i]&&s[i]&&a[i]==s[i])i++;if(!a[i]&&!s[i])return "'+enc(b)+'";}').join('\n')+'\nreturn s;}\n'; +s=s.replace('static const char *fname(u32 i){ return i<4u ? (const char*)g_cfg.field_name[i] : (const char*)g_cfg.field_name2[i-4u]; }',nameFunc+'static const char *fname(u32 i){ return ko_field(i<4u ? (const char*)g_cfg.field_name[i] : (const char*)g_cfg.field_name2[i-4u]); }'); +s=require('./native-menu-layout.cjs')(s,enc); +fs.writeFileSync(dir+'/main-ko.c',s); +let sh=fs.readFileSync(dir+'/build.sh','utf8').replace('main.c hw.c','main-ko.c hw.c').replace('[ "$n" = main ]','[ "$n" = main-ko ]').replace('N=${OUT:-feld}','N=${OUT:-feld-ko}').replace('OUT=feldc','OUT=feldc-ko').replace('-ffreestanding','-flto -ffreestanding').replace('sh "$0" --inner','sh ./build-ko.sh --inner'); +sh=sh.replace(' -Os ', ' -Oz '); +sh=sh.replace('llvm-size $N.elf; ls -l $N.bin', 'python3 -c \'import pathlib,sys; p=pathlib.Path(sys.argv[1]); p.write_bytes(p.read_bytes()+b"ITOSM_KO_MENU_V1\\x00")\' "$N.bin"\nllvm-size $N.elf; ls -l $N.bin'); +fs.writeFileSync(dir+'/build-ko.sh',sh.replace(/\r\n/g,'\n')); +fs.writeFileSync(dir+'/ko-encoding.json',JSON.stringify({chars,translations:tr,fields},null,2)); +console.log('Menu:',Object.keys(counts).length,'strings,',chars.length,'glyphs,',chars.length*13,'font bytes'); diff --git a/scripts/deploy-site.sh b/scripts/deploy-site.sh new file mode 100644 index 0000000..1ca34a0 --- /dev/null +++ b/scripts/deploy-site.sh @@ -0,0 +1,21 @@ +#!/bin/sh +set -eu +cd /home/syskiller/docker/tamagotchi +mkdir -p site +cp source/dist/index.html source/dist/ParamixStudio.html source/dist/restore.html source/guide.html site/ +cp source/admin.html source/admin.js source/about.html source/site.css source/robots.txt source/sitemap.xml site/ +cp source/account.html source/account.js site/ +cp source/share.js site/ +cp source/member-nav.js site/ +cp source/feld/src/feld/qa/001.png site/menu-main.png +cp source/feld/src/feld/qa/020.png site/menu-points.png +cp source/feld/src/feld/qa/009.png site/menu-character.png +cp source/feld/src/feld/qa/018.png site/menu-item.png +cp source/LICENSE site/LICENSE.txt +cp source/NOTICE.md site/NOTICE.txt +cp source/third-party/Galmuri-OFL.txt site/Galmuri-OFL.txt +cp source/docker-compose.yaml source/nginx-static.conf . +printf 'ok\n' > site/health.txt +sha256sum site/index.html > deploy-sha256.txt +chmod -R a+rX site +docker compose -f docker-compose.yaml config --quiet diff --git a/scripts/localize-web.cjs b/scripts/localize-web.cjs new file mode 100644 index 0000000..f83c82b --- /dev/null +++ b/scripts/localize-web.cjs @@ -0,0 +1,26 @@ +const fs=require('fs'),vm=require('vm'),path=require('path'); +const root=path.resolve(__dirname,'..'); +const p=path.join(root,'src/app.js'); let s=fs.readFileSync(p,'utf8'); +const ko={}; +for(const line of fs.readFileSync(path.join(root,'src/ko.tsv'),'utf8').trim().split(/\r?\n/)){ + const at=line.indexOf('\t');if(at<1)throw Error('Invalid translation'); + const k=line.slice(0,at);if(k in ko)throw Error('Duplicate '+k); + ko[k]=line.slice(at+1).replace(/\\n/g,'\n'); +} +const T=vm.runInNewContext(s.slice(s.indexOf('const T = {'),s.indexOf('\nlet lang'))+';T'); +for(const [k,v] of Object.entries({...T.de,...T.en})){ + if(!(k in ko))throw Error('Missing '+k); + const vars=x=>(x.match(/\{\w+\}/g)||[]).sort().join('|'); + if(vars(v)!==vars(ko[k]))throw Error('Placeholders: '+k); +} +s=s.replace(/\/\* ITOSM_KO_BEGIN \*\/[\s\S]*?\/\* ITOSM_KO_END \*\/\n?/,''); +s=s.replace("let lang = 'de';",'/* ITOSM_KO_BEGIN */\nT.ko = '+JSON.stringify(ko,null,2)+';\nT.en.menuKo="Korean A+C device menu";\nT.en.menuKoHint="Experimental Korean device menu: PC preview and build checks only; hardware, save and restore are not yet verified. Back up your ROM and saves before applying. Original game, emulator settings and names read from your ROM remain unchanged.";\nT.de.menuKo=T.en.menuKo;T.de.menuKoHint=T.en.menuKoHint;\n/* ITOSM_KO_END */\nlet lang = \'de\';'); +s=s.replace("localStorage.getItem('paramix-lang') || (navigator.language || 'de').slice(0, 2)","localStorage.getItem('paramix-lang') || 'ko'"); +if(!s.includes("if (lang === 'ko')"))s=s.replace("if (lang === 'en') return s;","if (lang === 'en') return s;\n if (lang === 'ko') { for (const [re, ko] of MSG_KO) if(re.test(s)) return s.replace(re,ko); return s; }"); +// Korean module errors are separate from the upstream German dictionary. +if(!s.includes('const MSG_KO ='))s=s.replace('const MSG_DE = [',fs.readFileSync(path.join(root,'src/errors-ko.js'),'utf8')+'\nconst MSG_DE = ['); +fs.writeFileSync(p,s); +const ep=path.join(root,'src/emu.js'); +const emu=fs.readFileSync(ep,'utf8'); +fs.writeFileSync(ep,emu.replaceAll("opts.lang === 'en' ? 1 : 0", "(opts.lang === 'en' || opts.lang === 'ko') ? 1 : 0")); +console.log('Korean translations:',Object.keys(ko).length,'; placeholders checked'); diff --git a/scripts/native-menu-layout.cjs b/scripts/native-menu-layout.cjs new file mode 100644 index 0000000..86ada02 --- /dev/null +++ b/scripts/native-menu-layout.cjs @@ -0,0 +1,57 @@ +// Applied to the generated Korean variant only. Core input and write logic stay intact. +module.exports=function(s,enc){ + const start=s.indexOf('static void main_menu(void){'), end=s.indexOf('\nstatic void run(void)',start); + let menu=s.slice(start,end); + const a=menu.indexOf(' rect(0,0,128,128,BG);'),b=menu.indexOf(' show(); wait_release();',a); + menu=menu.slice(0,a)+` rect(0,0,128,128,BG); + ctext(3,"${enc('다마고치 편집')}",WHITE,1); + for(u32 i=0;i20u) n=20u;', 'u32 n=fl(o+3)[0]; if(n==255u){u32 a=g_cfg.cat_off+rd32(o+8);u32 i=0;while(i<60u&&fl(a+i)[0]){g_nm[i]=(char)fl(a+i)[0];i++;}g_nm[i]=0;return g_nm;} if(n>20u) n=20u;'); + s=s.replace(/static void chr_name\(u32 k, char \*out\)\{[^\n]+/, 'static void chr_name(u32 k, char *out){const char *n=item_name(rd16(g_cfg.cat_off+8u+28u*k));int i=0;while(n[i]&&i<60){out[i]=n[i];i++;}out[i]=0;}'); + s=s.replace(/\b(nm|name|st|t)\[24\]/g,'$1[64]'); + // Wrap by glyph boundaries rather than splitting a two-byte Korean character. + const split=s.indexOf('static const char *item_name'); + s=s.slice(0,split)+`static void ko_title(const char *s,int y){int n=0,w=0;while(s[n]){int z=ko_pair(s+n)?2:1,px=z==2?10:6;if(w+px>116)break;w+=px;n+=z;}textn((128-w)/2,y,s,n,WHITE,1);if(s[n])ctext(y+11,s+n,WHITE,1);}\n`+s.slice(split); + s=s.replace('if(L<=20) ctext(4,nm,WHITE,1); else { textn(4,2,nm,20,WHITE,1); textn(4,11,nm+20,20,WHITE,1); }','ko_title(nm,2);'); + s=s.replace('ctext(98,name,WHITE,1);','ko_title(name,94);'); + s=s.replace(/ list_draw\(t, g_catn, sel, top, cat_row, [^\n]+/,` rect(0,0,128,128,BG);ctext(3,t,WHITE,1);draw_item_pic(g_cat[sel],64,54,64);ko_title(item_name(g_cat[sel]),94);ctext(117,"${enc('A 분류 B 선택 C 뒤로')}",GREY,1);show();`); + s=s.replace('static u32 tama_files(u32 old, u32 nw){','static u32 ko_names(void);\nstatic u32 tama_files(u32 old, u32 nw){'); + s=s.replace(' flash_read(a, g_page, PAGE);\n#ifdef FELD_TAMA_ANY',' flash_read(a, g_page, PAGE);\n u32 before=0;for(u32 z=8;z<0x180;z+=4)before+=*(u32*)(g_page+z);\n#ifdef FELD_TAMA_ANY'); + s=s.replace(' flash_prog4k(a, g_page); n++;',` if(rd32(a)+rd32(a+4u)==0u){ + int k=cat_find(nw);u32 names=ko_names();if(k>=0&&names){for(u32 j=0;j<26;j++)g_page[226u+j]=fl(names+26u*(u32)k+j)[0];g_page[0xfcu]=fl(g_cfg.cat_off+8u+28u*(u32)k+6u)[0];g_page[0xfdu]=0;} + u32 sum=rd32(a)-before;for(u32 z=8;z<0x180;z+=4)sum+=*(u32*)(g_page+z);*(u32*)g_page=sum;*(u32*)(g_page+4u)=0u-sum; + } + flash_prog4k(a, g_page); n++;`); + s=s.replace('RGB(60,60,110)','RGB(205,225,169)').replace('RGB(40,40,70)','BG'); + s=s.replace('if(k>=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]==2u){ char t[64]; chr_name((u32)k,t); t[15]=0;', 'if(k>=0 && fl(g_cfg.cat_off+8u+28u*(u32)k+2u)[0]==2u){ char t[64]; chr_name((u32)k,t); int z=0;while(t[z]&&z+(ko_pair(t+z)?2:1)<=14)z+=ko_pair(t+z)?2:1;t[z]=0;'); + // Keep the current item on a picture screen before confirming a change. + return s; +}; diff --git a/server/app.py b/server/app.py new file mode 100644 index 0000000..a68d851 --- /dev/null +++ b/server/app.py @@ -0,0 +1,354 @@ +"""ITOSM recovery archive. Firmware lives in /data, never in the source archive.""" +import base64 +import hashlib +import hmac +import json +import os +import re +import secrets +import signal +import struct +import threading +import time +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).parent)) +from members import Members +from device_backups import DeviceBackups + +DATA = Path(os.environ.get('BACKUP_DATA', '/data')) +ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'https://tama.itosm.co.kr') +SIZE = 0x1000000 +EDITIONS = {1: '랜드', 2: '워터', 3: '스카이', 4: '제이드 포레스트', 5: '트로피컬', 6: '글레이셔'} +SLUGS = {1: 'land', 2: 'water', 3: 'sky', 4: 'jade-forest', 5: 'tropical', 6: 'glacier'} +CONSTANTS = [0, 0x70169E2C, 0x70169E2C, 0x70169E2C, 0x849633DB, 0x96CB83B8, 0x96CB83B8] +LOCK = threading.RLock() +SESSIONS = {} +ATTEMPTS = {} +DEFAULTS = {'title': '다마고치 연구소', 'description': '다마고치 파라다이스 펌웨어 편집과 한국어 A+C 메뉴, 원본 백업·복원을 한곳에서.', 'autoBackup': True, 'maxStorageMB': 512} +FEATURES = ('emu', 'gb', 'sms', 'pm', 'ab', 'doom', 'wolf', 'standalone', 'cards') +DEFAULTS.update(backupMode='server', deviceStorageMB=512, deviceRetentionHours=24, features={key: False for key in FEATURES}) +MEMBERS = None +DEVICE_BACKUPS = None + + +def device_backups(): + global DEVICE_BACKUPS + with LOCK: + if DEVICE_BACKUPS is None or DEVICE_BACKUPS.folder.parent != DATA: + DEVICE_BACKUPS = DeviceBackups(DATA, config, LOCK, detect) + return DEVICE_BACKUPS + + +def members(): + global MEMBERS + with LOCK: + if MEMBERS is None or MEMBERS.data != DATA: + MEMBERS = Members(DATA, config, password_hash, password_ok, detect, EDITIONS, now) + return MEMBERS + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def password_hash(password, salt=None): + salt = salt or secrets.token_hex(16) + return salt + ':' + hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384, r=8, p=1).hex() + + +def password_ok(password, stored): + try: + return hmac.compare_digest(password_hash(password, stored.split(':')[0]), stored) + except (ValueError, TypeError): + return False + + +def read_json(path): + return json.loads(path.read_text(encoding='utf-8')) + + +def atomic_json(path, value): + temp = path.with_suffix('.tmp') + with temp.open('w', encoding='utf-8') as output: + json.dump(value, output, ensure_ascii=False, indent=2) + output.flush() + os.fsync(output.fileno()) + os.replace(temp, path) + + +def config(): + return dict(DEFAULTS, **read_json(DATA / 'config.json')) + + +def records(): + return [read_json(p) for p in sorted(DATA.glob('*/metadata.json'))] + + +def image_path(record): + return DATA / SLUGS[record['edition']] / (record['sha256'] + '.bin') + + +def detect(data): + if len(data) != SIZE or data[:8] != b'SONIXDEV': + raise ValueError('16 MB 파라다이스 ROM 파일이 아닙니다.') + for address, ids in [(0xD29000, [5, 6]), (0xD49000, [1, 2, 3, 4]), (0xEFD000, [1, 2, 3, 4, 5, 6])]: + edition = struct.unpack_from(' cfg['maxStorageMB'] * 1024 * 1024: + raise ValueError('서버 백업 용량이 가득 찼습니다. PC 파일은 별도로 저장하세요.') + folder.mkdir(parents=True, exist_ok=True) + path = folder / (digest + '.bin') + # A crash after writing the image but before its metadata may leave an orphan. + # Only reuse that exact verified image; never replace an established record. + if not path.exists(): + with path.open('xb') as output: + output.write(data) + output.flush() + os.fsync(output.fileno()) + if hashlib.sha256(path.read_bytes()).hexdigest() != digest: + path.unlink() + raise ValueError('서버 파일 검증에 실패했습니다.') + record = {'edition': edition, 'name': EDITIONS[edition], 'slug': SLUGS[edition], 'sha256': digest, 'size': len(data), 'createdAt': now(), 'sourceDate': source_date, 'label': label or EDITIONS[edition] + ' 추출 백업 (원본 여부 미확인)', 'published': published, 'protected': protected, 'verifiedOnDevice': False} + atomic_json(folder / 'metadata.json', record) + return {'status': 'stored', 'edition': edition, 'name': EDITIONS[edition], 'sha256': digest} + + +class Handler(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + + def log_message(self, fmt, *args): + # Do not log credentials, cookies, client filenames or binary data. + pass + + def reply(self, status, body, content_type='application/json; charset=utf-8', headers=None): + if not isinstance(body, bytes): + body = json.dumps(body, ensure_ascii=False).encode() + self.send_response(status) + self.send_header('Content-Type', content_type) + self.send_header('Content-Length', str(len(body))) + self.send_header('Cache-Control', 'no-store') + self.send_header('X-Content-Type-Options', 'nosniff') + self.send_header('X-Robots-Tag', 'noindex') + for key, val in (headers or {}).items(): + self.send_header(key, val) + self.end_headers() + self.wfile.write(body) + + def authorized(self): + cookie = self.headers.get('Cookie', '') + match = re.search(r'(?:^|;\s*)tama_admin=([a-f0-9]{64})(?:;|$)', cookie) + token = match.group(1) if match else None + with LOCK: + for key, expiry in list(SESSIONS.items()): + if expiry <= time.time(): + del SESSIONS[key] + return bool(token and token in SESSIONS) + + def body(self, limit): + if self.headers.get('Transfer-Encoding'): + raise ValueError('지원하지 않는 전송 방식입니다.') + length = int(self.headers.get('Content-Length', '-1')) + if not 0 <= length <= limit: + raise ValueError('파일 또는 요청 크기가 잘못되었습니다.') + self.connection.settimeout(90) + data = self.rfile.read(length) + if len(data) != length: + raise ValueError('전송이 끝나지 않았습니다.') + return data + + def do_GET(self): + try: + self.get() + except (BrokenPipeError, ConnectionResetError): + pass + except Exception: + self.reply(500, {'error': '서버 요청을 처리하지 못했습니다.'}) + + def get(self): + path = self.path.split('?')[0] + if path.startswith('/api/member/') or path == '/api/admin/members': + return members().get(self, path) + match = re.fullmatch(r'/api/device-backups/([a-f0-9]{32})', path) + if match: + return device_backups().download(self, match[1]) + if path == '/api/health': + return self.reply(200, {'ok': True}) + if path == '/api/catalog': + with LOCK: + items = [r for r in records() if r['published']] + cfg = config() + return self.reply(200, {'items': items, 'title': cfg['title'], 'description': cfg['description'], 'features': cfg['features'], 'backupMode': cfg['backupMode']}) + if path == '/api/backup-status': + with LOCK: + cfg = config() + held = [r['edition'] for r in records()] + return self.reply(200, {'enabled': cfg['autoBackup'], 'held': held, 'mode': cfg['backupMode'], 'retentionHours': cfg['deviceRetentionHours']}) + if path.startswith('/api/admin/') and not self.authorized(): + return self.reply(401, {'error': '관리자 로그인이 필요합니다.'}) + if path == '/api/admin/state': + with LOCK: + cfg = config() + items = records() + return self.reply(200, {'settings': {k: cfg[k] for k in DEFAULTS}, 'username': cfg['username'], 'items': items, 'usedMB': sum(r['size'] for r in items) // 1048576}) + match = re.fullmatch(r'/api/(?:admin/)?file/([a-f0-9]{64})', path) + if match: + with LOCK: + item = next((r for r in records() if r['sha256'] == match.group(1)), None) + if not item or (not item['published'] and not path.startswith('/api/admin/')): + return self.reply(404, {'error': '공개된 복원 파일이 없습니다.'}) + data = image_path(item).read_bytes() + return self.reply(200, data, 'application/octet-stream', {'Content-Disposition': 'attachment; filename="paradise-' + item['slug'] + '-' + item['sha256'][:12] + '.bin"'}) + self.reply(404, {'error': '페이지가 없습니다.'}) + + def do_POST(self): + try: + if self.headers.get('Origin') != ORIGIN: + self.close_connection = True + return self.reply(403, {'error': '홈페이지에서 다시 시도하세요.'}) + self.post() + except (ValueError, KeyError, TypeError) as exc: + self.close_connection = True + self.reply(400, {'error': str(exc)}) + except (BrokenPipeError, ConnectionResetError): + pass + except Exception: + self.close_connection = True + self.reply(500, {'error': '서버 저장에 실패했습니다. PC 백업을 보관하세요.'}) + + def post(self): + path = self.path + if path.startswith('/api/member/') or path == '/api/admin/members': + return members().post(self, path) + if path == '/api/device-backups': + if self.headers.get('Content-Type') != 'application/octet-stream': + self.close_connection = True + return self.reply(400, {'error': '기기 백업 파일이 필요합니다.'}) + result, headers = device_backups().store(self, self.body(SIZE)) + return self.reply(200, result, headers=headers) + if path == '/api/backups': + if self.headers.get('X-Backup-Notice') != 'shown' or self.headers.get('Content-Type') != 'application/octet-stream': + self.close_connection = True + return self.reply(400, {'error': 'ROM 추출 화면에서 백업 안내를 확인하세요.'}) + data = self.body(SIZE) + return self.reply(200, store_image(data)) + if self.headers.get('Content-Type', '').split(';')[0] != 'application/json': + self.close_connection = True + return self.reply(400, {'error': 'JSON 요청이 필요합니다.'}) + if path != '/api/login' and not self.authorized(): + self.close_connection = True + return self.reply(401, {'error': '관리자 로그인이 필요합니다.'}) + body = json.loads(self.body(4096)) + if path == '/api/login': + ip = self.headers.get('X-Real-IP', self.client_address[0]) + with LOCK: + # Bound the table as well as the number of guesses per client. + for key in list(ATTEMPTS): + ATTEMPTS[key] = [t for t in ATTEMPTS[key] if t > time.time() - 900] + if not ATTEMPTS[key]: + del ATTEMPTS[key] + tries = ATTEMPTS.setdefault(ip, []) + if len(tries) >= 8 or len(ATTEMPTS) > 10000: + return self.reply(429, {'error': '로그인 시도가 많습니다. 15분 뒤 다시 시도하세요.'}) + cfg = config() + if body.get('username') != cfg['username'] or not password_ok(str(body.get('password', '')), cfg['passwordHash']): + tries.append(time.time()) + return self.reply(401, {'error': '아이디 또는 비밀번호가 다릅니다.'}) + ATTEMPTS.pop(ip, None) + token = secrets.token_hex(32) + SESSIONS[token] = time.time() + 28800 + return self.reply(200, {'ok': True}, headers={'Set-Cookie': 'tama_admin=' + token + '; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=28800'}) + if path == '/api/admin/logout': + cookie = self.headers.get('Cookie', '') + match = re.search(r'tama_admin=([a-f0-9]{64})', cookie) + with LOCK: + if match: + SESSIONS.pop(match.group(1), None) + return self.reply(200, {'ok': True}, headers={'Set-Cookie': 'tama_admin=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'}) + if path == '/api/admin/settings': + with LOCK: + cfg = config() + title, description = body.get('title', ''), body.get('description', '') + size = body.get('maxStorageMB') + if not isinstance(title, str) or not 1 <= len(title.strip()) <= 60 or not isinstance(description, str) or not 1 <= len(description.strip()) <= 300: + raise ValueError('제목은 1~60자, 소개는 1~300자로 입력하세요.') + if type(size) is not int or not 16 <= size <= 4096 or type(body.get('autoBackup')) is not bool: + raise ValueError('용량은 16~4096 MB로 입력하세요.') + mode = body.get('backupMode', cfg['backupMode']) + capacity = body.get('deviceStorageMB', cfg['deviceStorageMB']) + retention = body.get('deviceRetentionHours', cfg['deviceRetentionHours']) + flags = body.get('features', cfg['features']) + if mode not in ('server', 'local') or type(capacity) is not int or not 16 <= capacity <= 20480 or type(retention) is not int or not 1 <= retention <= 168: + raise ValueError('백업 방식과 임시 보관 용량 및 보관 시간을 확인하세요.') + if not isinstance(flags, dict) or set(flags) - set(FEATURES) or any(type(v) is not bool for v in flags.values()): + raise ValueError('추가 기능 설정이 잘못되었습니다.') + cfg.update(title=title.strip(), description=description.strip(), maxStorageMB=size, autoBackup=body['autoBackup'], backupMode=mode, deviceStorageMB=capacity, deviceRetentionHours=retention, features={key: flags.get(key, False) for key in FEATURES}) + atomic_json(DATA / 'config.json', cfg) + return self.reply(200, {'ok': True}) + if path == '/api/admin/password': + with LOCK: + cfg = config() + password = body.get('newPassword', '') + if not password_ok(str(body.get('currentPassword', '')), cfg['passwordHash']): + raise ValueError('현재 비밀번호가 다릅니다.') + if not isinstance(password, str) or not 10 <= len(password) <= 128: + raise ValueError('새 비밀번호는 10~128자로 입력하세요.') + cfg['passwordHash'] = password_hash(password) + atomic_json(DATA / 'config.json', cfg) + SESSIONS.clear() + with members().db() as db: + db.execute('DELETE FROM sessions WHERE user IN (SELECT id FROM users WHERE username=?)', (cfg['username'].lower(),)) + return self.reply(200, {'ok': True}, headers={'Set-Cookie': 'tama_admin=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'}) + if path == '/api/admin/record': + digest = body.get('sha256') + with LOCK: + item = next((r for r in records() if r['sha256'] == digest), None) + if not item: + raise ValueError('백업을 찾지 못했습니다.') + folder = DATA / item['slug'] + if body.get('action') == 'delete': + if item['protected']: + raise ValueError('최초 원본은 삭제할 수 없습니다.') + if item['published']: + raise ValueError('비공개로 전환한 뒤 삭제하세요.') + image_path(item).unlink() + (folder / 'metadata.json').unlink() + else: + label = body.get('label', '') + if not isinstance(label, str) or not 1 <= len(label.strip()) <= 100 or type(body.get('published')) is not bool: + raise ValueError('표시 이름과 공개 여부를 확인하세요.') + item.update(label=label.strip(), published=body['published']) + atomic_json(folder / 'metadata.json', item) + return self.reply(200, {'ok': True}) + self.reply(404, {'error': '요청 경로가 없습니다.'}) + + +if __name__ == '__main__': + DATA.mkdir(parents=True, exist_ok=True) + if not (DATA / 'config.json').exists(): + raise SystemExit('Initialize protected config.json before starting.') + server = ThreadingHTTPServer(('0.0.0.0', int(os.environ.get('PORT', '8080'))), Handler) + server.daemon_threads = True + signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start()) + try: + server.serve_forever() + finally: + server.server_close() diff --git a/server/device_backups.py b/server/device_backups.py new file mode 100644 index 0000000..928a7f2 --- /dev/null +++ b/server/device_backups.py @@ -0,0 +1,87 @@ +"""Private, expiring device backups. Downloads require the uploader's cookie.""" +import hashlib +import json +import os +import re +import secrets +import time + + +class DeviceBackups: + def __init__(self, data, config, lock, detect): + self.folder = data / 'device-downloads' + self.folder.mkdir(exist_ok=True) + self.config, self.lock, self.detect = config, lock, detect + + def cookie(self, h): + m = re.search(r'(?:^|;\s*)tama_download=([a-f0-9]{64})(?:;|$)', h.headers.get('Cookie', '')) + return m[1] if m else None + + def owner(self, token): + return hashlib.sha256(token.encode()).hexdigest() + + def purge(self): + for p in self.folder.glob('*.json'): + meta = json.loads(p.read_text()) + if meta['expires'] < time.time(): + p.with_suffix('.bin').unlink(missing_ok=True) + p.unlink() + + def store(self, h, data): + cfg = self.config() + if cfg['backupMode'] != 'server': + raise ValueError('백업 방식이 변경되었습니다. 다시 시도하세요.') + kind = h.headers.get('X-Backup-Kind', 'rom') + if kind == 'rom': + edition = self.detect(data) + elif kind == 'save' and data[:8] == b'TAMASAVE' and 56 <= len(data) <= 4 * 1024 * 1024 and data[-16:-12] == b'PMXE': + edition = int.from_bytes(data[-12:-8], 'little') + if edition not in range(1, 7): + raise ValueError('저장 데이터의 기종을 확인할 수 없습니다.') + elif kind == 'aux' and cfg['features'].get('emu') and 1 <= len(data) <= 16 * 1024 * 1024: + edition = 0 + else: + raise ValueError('지원하는 기기 백업 파일이 아닙니다.') + token = self.cookie(h) or secrets.token_hex(32) + owner = self.owner(token) + sha = hashlib.sha256(data).hexdigest() + with self.lock: + self.purge() + items = [json.loads(p.read_text()) for p in self.folder.glob('*.json')] + old = next((m for m in items if m['owner'] == owner and m['sha256'] == sha), None) + if old: + meta = old + else: + if sum(m['size'] for m in items) + len(data) > cfg['deviceStorageMB'] * 1048576: + raise ValueError('서버의 기기 백업 공간이 가득 찼습니다. 읽은 데이터는 현재 화면에 유지됩니다.') + if sum(m['owner'] == owner for m in items) >= 20: + raise ValueError('현재 브라우저의 임시 백업 한도에 도달했습니다. 기존 백업의 보관 기간이 지난 뒤 다시 시도하세요.') + key = secrets.token_hex(16) + meta = dict(id=key, owner=owner, sha256=sha, size=len(data), edition=edition, + kind=kind, expires=time.time() + cfg['deviceRetentionHours'] * 3600) + dest = self.folder / (key + '.bin') + with dest.open('xb') as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + if hashlib.sha256(dest.read_bytes()).hexdigest() != sha: + dest.unlink() + raise ValueError('서버에 저장한 파일의 검증에 실패했습니다.') + (self.folder / (key + '.json')).write_text(json.dumps(meta), encoding='utf-8') + public = {k: v for k, v in meta.items() if k != 'owner'} + public['fileUrl'] = '/api/device-backups/' + meta['id'] + return public, {'Set-Cookie': 'tama_download=' + token + '; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=604800'} + + def download(self, h, key): + with self.lock: + self.purge() + p = self.folder / (key + '.json') + token = self.cookie(h) + meta = json.loads(p.read_text()) if p.exists() else None + if not meta or not token or not secrets.compare_digest(meta['owner'], self.owner(token)): + return h.reply(404, {'error': '이 브라우저에서 저장한 백업이 아니거나 보관 기간이 지났습니다.'}) + data = p.with_suffix('.bin').read_bytes() + if hashlib.sha256(data).hexdigest() != meta['sha256']: + return h.reply(500, {'error': '서버 백업 파일 검증에 실패했습니다.'}) + ext = 'tamasave' if meta['kind'] == 'save' else 'bin' + h.reply(200, data, 'application/octet-stream', {'Content-Disposition': f'attachment; filename="paradise-{key}.{ext}"'}) diff --git a/server/members.py b/server/members.py new file mode 100644 index 0000000..b7f0035 --- /dev/null +++ b/server/members.py @@ -0,0 +1,270 @@ +"""Private member vault; SQLite transactions enforce ownership and capacity.""" +import hashlib +import hmac +import json +import re +import secrets +import shutil +import sqlite3 +import threading +import time +from contextlib import contextmanager +from pathlib import Path + +SIZE = 16777216 +COOKIE = 'tama_member' + + +class Members: + def __init__(self, data, config, password_hash, password_ok, detect, names, now): + self.data, self.config = data, config + self.hash_password, self.check_password = password_hash, password_ok + self.detect, self.names, self.now = detect, names, now + self.attempts, self.lock = {}, threading.RLock() + self.path = data / 'members.sqlite3' + with self.db() as db: + db.execute('PRAGMA journal_mode=WAL') + db.executescript(''' + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, + recovery TEXT NOT NULL, created TEXT NOT NULL, slots INTEGER NOT NULL DEFAULT 10, + disabled INTEGER NOT NULL DEFAULT 0); + CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, user TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires REAL NOT NULL); + CREATE TABLE IF NOT EXISTS files ( + id TEXT PRIMARY KEY, user TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + sha TEXT NOT NULL, label TEXT NOT NULL, edition INTEGER NOT NULL, + created TEXT NOT NULL, size INTEGER NOT NULL, data BLOB NOT NULL, + UNIQUE(user,sha)); + CREATE INDEX IF NOT EXISTS files_user ON files(user); + CREATE INDEX IF NOT EXISTS sessions_user ON sessions(user); + CREATE TABLE IF NOT EXISTS settings (id INTEGER PRIMARY KEY, enabled INTEGER NOT NULL, total_mb INTEGER NOT NULL); + INSERT OR IGNORE INTO settings VALUES(1,1,5120); + ''') + + @contextmanager + def db(self): + db = sqlite3.connect(self.path, timeout=30) + db.row_factory = sqlite3.Row + db.execute('PRAGMA foreign_keys=ON') + try: + with db: + yield db + finally: + db.close() + + def token(self, handler): + found = re.search(r'(?:^|;\s*)tama_member=([a-f0-9]{64})(?:;|$)', handler.headers.get('Cookie', '')) + return hashlib.sha256(found[1].encode()).hexdigest() if found else '' + + def user(self, handler): + with self.db() as db: + return db.execute('SELECT u.* FROM users u JOIN sessions s ON s.user=u.id WHERE s.token=? AND s.expires>? AND u.disabled=0', (self.token(handler), time.time())).fetchone() + + def session(self, handler, user, extra=None): + token = secrets.token_hex(32) + with self.db() as db: + db.execute('DELETE FROM sessions WHERE expires time.time() - 900] + if not self.attempts[k]: + del self.attempts[k] + attempts = self.attempts.setdefault(key, []) + if len(attempts) >= (5 if action == 'register' else 12) or len(self.attempts) > 10000: + handler.reply(429, {'error': '시도가 많습니다. 15분 뒤 다시 시도하세요.'}) + return False + attempts.append(time.time()) + return True + + @staticmethod + def password(value): + if not isinstance(value, str) or not 10 <= len(value) <= 128: + raise ValueError('비밀번호는 10~128자로 입력하세요.') + return value + + @staticmethod + def username(value): + if not isinstance(value, str) or not re.fullmatch(r'[a-zA-Z0-9_]{4,24}', value): + raise ValueError('아이디는 영문·숫자·밑줄 4~24자로 입력하세요.') + return value.lower() + + def info(self, db, user): + used = db.execute('SELECT COUNT(*) n, COALESCE(SUM(size),0) size FROM files WHERE user=?', (user['id'],)).fetchone() + rows = db.execute('SELECT id,sha,label,edition,created,size FROM files WHERE user=? ORDER BY created DESC', (user['id'],)).fetchall() + return {'authenticated': True, 'username': user['username'], 'isAdmin': user['username'] == self.config()['username'].lower(), 'usedBytes': used['size'], 'count': used['n'], 'maxFiles': user['slots'], 'quotaBytes': user['slots'] * SIZE, 'items': [self.file_info(r) for r in rows]} + + def file_info(self, row): + return {'id': row['id'], 'sha256': row['sha'], 'label': row['label'], 'edition': row['edition'], 'name': self.names.get(row['edition'], '기종 미확인'), 'slug': 'personal', 'createdAt': row['created'], 'size': row['size'], 'fileUrl': '/api/member/file/' + row['id'], 'private': True} + + def get(self, h, path): + if path == '/api/admin/members': + if not h.authorized(): + h.reply(401, {'error': '관리자 로그인이 필요합니다.'}); return + with self.db() as db: + settings = dict(db.execute('SELECT enabled,total_mb FROM settings WHERE id=1').fetchone()) + rows = db.execute('SELECT u.id,u.username,u.created,u.slots,u.disabled,COUNT(f.id) count,COALESCE(SUM(f.size),0) usedBytes FROM users u LEFT JOIN files f ON f.user=u.id GROUP BY u.id ORDER BY u.created DESC').fetchall() + h.reply(200, {'items': [dict(r) for r in rows], 'settings': settings}); return + user = self.user(h) + if path == '/api/member/me': + if not user: + h.reply(200, {'authenticated': False}); return + with self.db() as db: + result = self.info(db, user) + h.reply(200, result); return + if not user: + h.reply(401, {'error': '회원 로그인이 필요합니다.'}); return + if path == '/api/member/six.js': + code = (Path(__file__).parent / 'generated/six.js').read_bytes() + h.reply(200, code, 'application/javascript; charset=utf-8'); return + match = re.fullmatch(r'/api/member/file/([a-f0-9]{32})', path) + if match: + with self.db() as db: + row = db.execute('SELECT data,sha FROM files WHERE id=? AND user=?', (match[1], user['id'])).fetchone() + if not row: + h.reply(404, {'error': '내 보관함에서 파일을 찾지 못했습니다.'}); return + h.reply(200, row['data'], 'application/octet-stream', {'Content-Disposition': 'attachment; filename="paradise-personal-' + row['sha'][:12] + '.bin"'}); return + h.reply(404, {'error': '페이지가 없습니다.'}) + + def post(self, h, path): + public = path in ['/api/member/register', '/api/member/login', '/api/member/recover'] + admin = path.startswith('/api/admin/') + user = self.user(h) + if (admin and not h.authorized()) or (not admin and not public and not user): + h.close_connection = True + h.reply(401, {'error': '로그인이 필요합니다.'}); return + if path == '/api/member/files': + if h.headers.get('Content-Type') != 'application/octet-stream': + raise ValueError('ROM 파일 전송 형식이 잘못되었습니다.') + data = h.body(SIZE) + if len(data) != SIZE or data[:8] != b'SONIXDEV': + raise ValueError('16 MiB 파라다이스 덤프 파일을 선택하세요.') + try: + edition = self.detect(data) + except ValueError: + edition = 0 + sha = hashlib.sha256(data).hexdigest() + with self.db() as db: + db.execute('BEGIN IMMEDIATE') + # Recheck account and quota inside the same transaction as the insertion. + current = db.execute('SELECT * FROM users WHERE id=? AND disabled=0', (user['id'],)).fetchone() + if not current: + raise ValueError('사용할 수 없는 계정입니다.') + old = db.execute('SELECT id FROM files WHERE user=? AND sha=?', (user['id'], sha)).fetchone() + if old: + h.reply(200, {'status': 'duplicate', 'sha256': sha, 'id': old['id']}); return + usage = db.execute('SELECT COUNT(*) n,COALESCE(SUM(size),0) size FROM files WHERE user=?', (user['id'],)).fetchone() + if usage['n'] >= current['slots'] or usage['size'] + len(data) > current['slots'] * SIZE: + raise ValueError('개인 보관함이 가득 찼습니다. 기존 파일을 삭제한 뒤 다시 저장하세요.') + cap = db.execute('SELECT total_mb FROM settings WHERE id=1').fetchone()[0] * 1048576 + total = db.execute('SELECT COALESCE(SUM(size),0) FROM files').fetchone()[0] + if total + len(data) > cap or shutil.disk_usage(self.data).free < len(data) * 4 + 2 * 1024 ** 3: + raise ValueError('서버 보관 공간이 부족합니다. PC 파일을 보관하세요.') + file_id = secrets.token_hex(16) + label = self.names.get(edition, '기종 미확인') + ' · ' + self.now()[:19].replace('T', ' ') + db.execute('INSERT INTO files VALUES(?,?,?,?,?,?,?,?)', (file_id, user['id'], sha, label, edition, self.now(), len(data), data)) + h.reply(200, {'status': 'stored', 'sha256': sha, 'id': file_id}); return + if h.headers.get('Content-Type', '').split(';')[0] != 'application/json': + raise ValueError('JSON 요청이 필요합니다.') + body = json.loads(h.body(4096)) + if not isinstance(body, dict): + raise ValueError('요청 형식이 잘못되었습니다.') + if public: + action = path.rsplit('/', 1)[1] + if not self.rate(h, action): return + username = self.username(body.get('username')) + cfg = self.config() + is_admin = username == cfg['username'].lower() + if action == 'register': + password = self.password(body.get('password')) + if is_admin: raise ValueError('예약된 관리자 아이디입니다.') + password_hash = self.hash_password(password) + recovery = secrets.token_urlsafe(24) + user_id = secrets.token_hex(16) + with self.db() as db: + db.execute('BEGIN IMMEDIATE') + if not db.execute('SELECT enabled FROM settings WHERE id=1').fetchone()[0]: + raise ValueError('현재 회원가입을 받지 않습니다.') + if db.execute('SELECT COUNT(*) FROM users').fetchone()[0] >= 1000: + raise ValueError('회원가입 한도에 도달했습니다. 관리자에게 문의하세요.') + if db.execute('SELECT 1 FROM users WHERE username=?', (username,)).fetchone(): + raise ValueError('이미 사용 중인 아이디입니다.') + db.execute('INSERT INTO users(id,username,password,recovery,created) VALUES(?,?,?,?,?)', (user_id, username, password_hash, hashlib.sha256(recovery.encode()).hexdigest(), self.now())) + self.session(h, user_id, {'recoveryCode': recovery}); return + with self.db() as db: + record = db.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone() + if action == 'login': + supplied = body.get('password', '') + if not isinstance(supplied, str) or len(supplied) > 128: + raise ValueError('아이디 또는 비밀번호가 다릅니다.') + stored = cfg['passwordHash'] if is_admin else record['password'] if record else cfg['passwordHash'] + valid = self.check_password(supplied, stored) + if not valid or (not is_admin and not record) or (record and record['disabled']): + raise ValueError('아이디 또는 비밀번호가 다르거나 사용할 수 없는 계정입니다.') + if is_admin and not record: + with self.db() as db: + db.execute('INSERT OR IGNORE INTO users(id,username,password,recovery,created) VALUES(?,?,?,?,?)', (secrets.token_hex(16), username, '', '', self.now())) + record = db.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone() + self.session(h, record['id']); return + password = self.password(body.get('newPassword')) + code = body.get('recoveryCode', '') + if not isinstance(code, str) or len(code) > 128 or not record or is_admin or record['disabled'] or not hmac.compare_digest(hashlib.sha256(code.encode()).hexdigest(), record['recovery']): + raise ValueError('아이디 또는 복구 코드가 다릅니다.') + recovery = secrets.token_urlsafe(24) + with self.db() as db: + db.execute('BEGIN IMMEDIATE') + fresh = db.execute('SELECT recovery,disabled FROM users WHERE id=?', (record['id'],)).fetchone() + if fresh['disabled'] or fresh['recovery'] != record['recovery']: + raise ValueError('이미 사용했거나 만료된 복구 코드입니다.') + db.execute('UPDATE users SET password=?,recovery=? WHERE id=?', (self.hash_password(password), hashlib.sha256(recovery.encode()).hexdigest(), record['id'])) + db.execute('DELETE FROM sessions WHERE user=?', (record['id'],)) + self.session(h, record['id'], {'recoveryCode': recovery}); return + if path == '/api/member/logout': + with self.db() as db: db.execute('DELETE FROM sessions WHERE token=?', (self.token(h),)) + h.reply(200, {'ok': True}, headers={'Set-Cookie': COOKIE + '=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'}); return + if path == '/api/member/file': + with self.db() as db: + if body.get('action') == 'delete': + cur = db.execute('DELETE FROM files WHERE id=? AND user=?', (body.get('id'), user['id'])) + else: + label = body.get('label', '') + if not isinstance(label, str) or not 1 <= len(label.strip()) <= 100: raise ValueError('파일 이름은 1~100자로 입력하세요.') + cur = db.execute('UPDATE files SET label=? WHERE id=? AND user=?', (label.strip(), body.get('id'), user['id'])) + if not cur.rowcount: + h.reply(404, {'error': '내 보관함에서 파일을 찾지 못했습니다.'}); return + h.reply(200, {'ok': True}); return + if path in ['/api/member/password', '/api/member/delete-account']: + if user['username'] == self.config()['username'].lower(): + raise ValueError('관리자 계정은 관리자 페이지에서 비밀번호를 관리하세요.') + if not self.check_password(str(body.get('currentPassword', '')), user['password']): + raise ValueError('현재 비밀번호가 다릅니다.') + with self.db() as db: + if path.endswith('delete-account'): + db.execute('DELETE FROM users WHERE id=?', (user['id'],)) + else: + db.execute('UPDATE users SET password=? WHERE id=?', (self.hash_password(self.password(body.get('newPassword'))), user['id'])) + db.execute('DELETE FROM sessions WHERE user=?', (user['id'],)) + h.reply(200, {'ok': True}, headers={'Set-Cookie': COOKIE + '=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'}); return + if path == '/api/admin/members': + with self.db() as db: + if body.get('action') == 'settings': + total = body.get('totalMB') + if type(body.get('enabled')) is not bool or type(total) is not int or not 160 <= total <= 20480: raise ValueError('회원 보관함 전체 한도는 160~20480 MiB입니다.') + db.execute('UPDATE settings SET enabled=?,total_mb=? WHERE id=1', (int(body['enabled']), total)) + else: + slots, disabled = body.get('slots'), body.get('disabled') + if type(slots) is not int or not 1 <= slots <= 100 or type(disabled) is not bool: raise ValueError('저장 개수는 1~100개로 입력하세요.') + row = db.execute('SELECT * FROM users WHERE id=?', (body.get('id'),)).fetchone() + if not row: raise ValueError('회원을 찾지 못했습니다.') + if row['username'] == self.config()['username'].lower() and disabled: raise ValueError('관리자 계정은 정지할 수 없습니다.') + db.execute('UPDATE users SET slots=?,disabled=? WHERE id=?', (slots, int(disabled), row['id'])) + if disabled: db.execute('DELETE FROM sessions WHERE user=?', (row['id'],)) + h.reply(200, {'ok': True}); return + h.reply(404, {'error': '요청 경로가 없습니다.'}) diff --git a/share.js b/share.js new file mode 100644 index 0000000..1fac5a6 --- /dev/null +++ b/share.js @@ -0,0 +1,29 @@ +(function(){ +'use strict'; +const url='https://tama.itosm.co.kr/about.html'; +const intro=`다마고치 파라다이스 한국어 편집·백업 사이트를 공개했습니다. + +• 한국어 웹 편집 화면과 선택형 한국어 A+C 본체 메뉴 +• 회원별 개인 덤프 보관함: 총 160 MiB(16 MiB 덤프 최대 10개) +• 비회원도 편집과 ROM 추출 이용 가능 +• 로그인한 회원은 기종별 백업 복원 이용 가능 +• 회원 전용 여섯 지역 확장 설정 + +여섯 지역 통합에는 트로피컬 또는 글레이셔 원본과 랜드·워터·스카이 중 하나의 원본이 필요합니다. 해당 원본 보유자의 백업 참여를 기다리고 있습니다. 홈페이지에서 본체 ROM을 추출하면 미확보 기종을 비공개로 보관하고 관리자 확인 후에만 공개합니다. + +다마고치 연구소에서 내 다마고치를 편집하고 백업을 보관하세요. + +${url}`; +const message=document.getElementById('shareStatus'); +async function copy(text){ + try{await navigator.clipboard.writeText(text);message.textContent='복사했습니다. 원하는 곳에 붙여 넣으세요.';} + catch{message.textContent='자동 복사를 지원하지 않습니다. 아래 내용을 선택해 복사하세요.';document.getElementById('shareCopy').hidden=false;document.getElementById('shareCopy').value=text;} +} +document.getElementById('copyLink').onclick=()=>copy(url); +document.getElementById('copyIntro').onclick=()=>copy(intro); +document.getElementById('shareSite').onclick=async()=>{ + if(!navigator.share){await copy(url);return;} + try{await navigator.share({title:'다마고치 연구소',text:'파라다이스 한국어 편집·백업 도구와 회원별 개인 보관함',url});} + catch(error){if(error.name!=='AbortError')message.textContent='공유 창을 열지 못했습니다. 주소 복사를 이용하세요.';} +}; +})(); diff --git a/site.css b/site.css new file mode 100644 index 0000000..bcd245f --- /dev/null +++ b/site.css @@ -0,0 +1 @@ +:root{color-scheme:light;font-family:'Malgun Gothic',system-ui,sans-serif;color:#243b34;background:#eff5f1}*{box-sizing:border-box}body{margin:0}main{max-width:940px;margin:36px auto;padding:0 22px}nav{display:flex;gap:20px;flex-wrap:wrap;margin-bottom:40px}a{color:#146e56}h1{font-size:clamp(30px,5vw,46px);line-height:1.2;letter-spacing:-.04em}h2{font-size:23px;margin-top:0}p,li{line-height:1.8}.lead{font-size:19px;color:#4b655a}.eyebrow{font-size:12px;letter-spacing:.18em;font-weight:bold;color:#16755a}section,.card{background:white;border:1px solid #ceded3;border-radius:18px;padding:26px;margin:22px 0}button,.button{display:inline-block;font:inherit;font-weight:600;border:1px solid #146e56;border-radius:9px;background:#146e56;color:white;padding:12px 16px;cursor:pointer;margin:6px 8px 6px 0;text-decoration:none}button:disabled{opacity:.45;cursor:not-allowed}input:not([type=checkbox]),textarea,select{font:inherit;width:100%;padding:12px;border:1px solid #a6bcb0;border-radius:8px;margin:8px 0 16px;background:#fff;color:#243b34}label{display:block;font-weight:600}.check{display:flex;align-items:flex-start;gap:8px;line-height:1.6;margin:14px 0}.check input{margin-top:6px}progress{width:100%;margin-top:20px;accent-color:#146e56}.hint,footer{font-size:14px;color:#50685d}.hint{overflow-wrap:anywhere;white-space:pre-line}.warning{border-left:4px solid #ce8a23;padding-left:15px}footer{margin:32px 0;line-height:1.8}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:20px}.grid .card{margin:0}.danger{background:#a23a32;border-color:#a23a32}[hidden]{display:none!important}#message,#status{white-space:pre-line;overflow-wrap:anywhere}.badge{display:inline-block;border-radius:30px;background:#e0eee4;color:#276044;padding:3px 10px;font-size:13px}code{overflow-wrap:anywhere}.record{border-top:1px solid #ceded3;padding:22px 0}.record h3{margin-top:0}@media(max-width:480px){section,.card{padding:20px}button,.button{width:100%;text-align:center}main{padding:0 14px}} diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..87384a9 --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,2 @@ + +https://tama.itosm.co.kr/https://tama.itosm.co.kr/about.htmlhttps://tama.itosm.co.kr/restore.htmlhttps://tama.itosm.co.kr/guide.html diff --git a/six/README.md b/six/README.md new file mode 100644 index 0000000..aec9cb8 --- /dev/null +++ b/six/README.md @@ -0,0 +1,42 @@ +# More fields on Tropical, Glacier and Jade Forest + +`six.bin` is one page of helper code that the Studio writes to flash 0x10F000 +(XIP 0x100FE000) for "All 6 fields" (Tropical, Glacier) or "Sky as 4th field" +(Jade Forest). Source: `src/six.s`. + +Build: + +``` +sh src/build.sh # clang and ld.lld (LLVM), writes six.bin +``` + +The firmware keeps the active field slot as 0, 1 or 2 in the settings block +(byte 499 on Tropical/Glacier, 443 on Jade Forest). The Studio adds a set byte +(offset 0xF04): 0 means the original fields, 1 means the alternative ones +(Land, Water, Sky in the three slots on Tropical/Glacier; Sky in slot 1 on +Jade Forest). The firmware is changed in these places (offsets in the +firmware window, flash = offset + 0x11000): + +- the function that returns the background composites of a field + (Tropical 0xAEAC, Jade 0x966C): jumps to `six_bg`, +- the child list in the code (Tropical 0xFD62, Jade 0xE1DA): `six_child`, +- every movw/movt pair that loads a per field table (teens, adults, travel + backgrounds, field eggs, scenes, wagon): `six_tab_r0` / `six_tab_r1`. The + site list at 0x380 (return address, original table, alternative table) + picks the table by the set byte. + +All addresses and the alternative tables are filled in by the Studio +(`src/six.js`). On Tropical/Glacier the Land, Water and Sky field pictures +and scenes are copied from the user's own Land, Water or Sky ROM; the cells +of the rain pictures that the clear ones do not share lie from 0xF00000 +(header "SIXB"). Jade Forest already holds Sky and gets only the tables. +Nothing of any ROM is part of this repository. + +Game field menu (version 6, option bit 1 at 0x20): the firmware's own menu +(planet, zoom in, A, "Fields") lists every field of both sets from planet +level 4 and keeps the Tama. Hooks at 0x830 (`six_fbuild`, `six_fcmp`, +`six_fset`, `six_fprev`); the Studio fills the addresses at 0x800 and +patches the list builder call, the reads of the list, the preview loader +calls and three immediates (count and index moved in the menu object). +An adult gets the three slots of its own set. + diff --git a/six/six.bin b/six/six.bin new file mode 100644 index 0000000..ede1901 Binary files /dev/null and b/six/six.bin differ diff --git a/six/src/build.sh b/six/src/build.sh new file mode 100644 index 0000000..e4a4ebd --- /dev/null +++ b/six/src/build.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Build six.bin (one 4 KB page, linked for XIP 0x100FE000 = flash 0x10F000) +set -e +cd "$(dirname "$0")" +clang --target=thumbv7m-none-eabi -mcpu=cortex-m3 -c six.s -o six.o +ld.lld -Ttext=0x100FE000 -e _start six.o -o six.elf +llvm-objcopy -O binary -j .text six.elf ../six.bin +llvm-objdump -d six.elf | head -80 +ls -l ../six.bin diff --git a/six/src/six.s b/six/src/six.s new file mode 100644 index 0000000..0c685f9 --- /dev/null +++ b/six/src/six.s @@ -0,0 +1,872 @@ +@ Paramix Studio: more fields for Tropical/Glacier (Land, Water, Sky added) and Jade Forest (Sky added). +@ One 4 KB page at flash 0x10F000 (XIP 0x100FE000). The Studio patches the firmware to call +@ the code here and fills in every address and table below. A set byte in the settings block +@ (offset 0xF04) says which tables the field slots use: 0 = the original ones, 1 = the +@ alternative ones (Land, Water, Sky on Tropical/Glacier, Sky in slot 1 on Jade Forest). +@ Version 7: a second byte (0xF05), written only by the Paramix menu when it starts a field, +@ picks the games of the lab: 0 = the firmware's own, 1 = Land/Water/Sky, 2 = Jade Forest. +.syntax unified +.thumb +.text +.global _start +_start: +hdr: .word 0x31584953 @ 0x00 "SIX1" + .word 7 @ 0x04 version (4: plain values in the site list, 5: planet, 6: field menu, 7: games) + .word 0 @ 0x08 flag address (RAM) + .word 0xF04 @ 0x0C flag offset in the settings block + .word 0, 0, 0 @ 0x10 sprites, composites, scripts before (for removing) + .word 0 @ 0x1C kind: 0 Tropical/Glacier, 1 Jade Forest + .word 0 @ 0x20 options: bit 0 planet of the field, bit 1 field menu, bit 2 games per start field + .space 0x40-0x24 + +@ r12 = flag (0 or 1), flags set. Keeps every other register. +.macro FLAG + ldr r12,=_start + ldr r12,[r12,#8] + ldrsb r12,[r12] + cmp r12,#0 +.endm + +@ 0x040: background composites of a field (close-up, field view): b.w from the firmware's +@ function. r0 = field (s8), r1 = variant (u8). Mode 0: table + field*64 + variant*32 +@ (Tropical/Glacier), mode 1: table + field*32 (Jade Forest). +.thumb_func +six_bg: + sxtb r0,r0 + uxtb r1,r1 + push {r4} + ldr r2,=w_bg + ldr r4,[r2,#8] + FLAG + ite ne + ldrne r3,[r2,#4] + ldreq r3,[r2] + cmp r4,#0 + ite eq + addeq r3,r3,r0,lsl #6 + addne r3,r3,r0,lsl #5 + it eq + addeq r3,r3,r1,lsl #5 + mov r0,r3 + pop {r4} + bx lr + +@ child id in r0, the index lies in the caller's stack at the offset w_child+8 +.thumb_func +six_child: + push {r1} + ldr r1,=w_child + ldr r0,[r1,#8] + add r0,sp,r0 + ldr r0,[r0,#4] @ +4: the pushed r1 + FLAG + ite ne + ldrne r1,[r1,#4] + ldreq r1,[r1] + ldrh r0,[r1,r0,lsl #1] + pop {r1} + bx lr + +@ Table base for any place that loaded a per field table with movw/movt into r0 or r1: +@ bl from that place. The return address picks the entry in the site list (return address, +@ original table, alternative table). The entries are plain words, so a place that loads two +@ halfword values (special characters) works the same way. Every other register is kept. +.macro TAB reg, keep + push {\keep,r2,r3} + ldr r2,=t_sites +1:ldr r3,[r2] + cmp r3,#0 + beq 3f + cmp r3,lr + beq 2f + adds r2,#12 + b 1b +2:ldr r3,=_start + ldr r3,[r3,#8] + ldrsb r3,[r3] + cmp r3,#0 + ite ne + ldrne \reg,[r2,#8] + ldreq \reg,[r2,#4] +3:pop {\keep,r2,r3} + bx lr +.endm +.thumb_func +six_tab_r0: + TAB r0, r1 +.thumb_func +six_tab_r1: + TAB r1, r0 + +@ Same for a table loaded into r2 (planet stages). +.thumb_func +six_tab_r2: + push {r0,r3} + ldr r0,=t_sites +1:ldr r3,[r0] + cmp r3,#0 + beq 3f + cmp r3,lr + beq 2f + adds r0,#12 + b 1b +2:ldr r3,=_start + ldr r3,[r3,#8] + ldrsb r3,[r3] + cmp r3,#0 + ite ne + ldrne r2,[r0,#8] + ldreq r2,[r0,#4] +3:pop {r0,r3} + bx lr + +@ Planet row: replaces the call that turns the device edition into a row of the planet +@ tables. With the set byte, the field slot picks the row from w_pmap+8 (0xFF = as before). +.thumb_func +six_pmap: + FLAG + beq 1f + ldr r12,=w_pmap + push {r1} + ldr r1,[r12,#4] + ldrsb r1,[r1] @ field slot 0..2 + cmp r1,#2 + bhi 4f + add r1,r12,r1 + ldrb r1,[r1,#8] + cmp r1,#0xFF + beq 4f + mov r0,r1 + pop {r1} + bx lr +4:pop {r1} +1:ldr r12,=w_pmap + ldr r12,[r12] + bx r12 +.ltorg +.org 0x1b0 +w_pmap: .word 0, 0, 0xFFFFFFFF @ original function, field byte, row per slot (bytes) +.org 0x1c0 +w_bg: .word 0, 0, 0 @ original table, alternative table, mode +w_child: .word 0, 0, 0 @ original list, alternative list, stack offset of the index +.org 0x1e0 + .word six_tab_r0, six_tab_r1, six_bg, six_child, six_pmap, six_tab_r2 +.org 0x200 +t_bg: .space 0x140 @ alternative background table +t_child: .space 8 @ 0x340 alternative child list +t_child_o: .space 8 @ 0x348 original child list (when it is built from code) +.org 0x380 +t_sites: .space 0x180 @ up to 31 sites x 12 bytes, ends with 0 +t_more: .space 0x300 @ 0x500: more alternative tables +.org 0x800 + +@ ---------------------------------------------------------------- field menu (version 6) +@ The game's own field menu (planet, zoom in once, A, "Fields") lists the field slots 0..2 of +@ the current set. These hooks make it list every field of both sets (from planet level 4) and +@ keep the Tama: the list holds the slot (as the firmware expects), the set of entry i is +@ bit 7 of fm_ent[i]. An adult (menu flag bit 0) gets the three slots of its own set. +@ Active when the count byte holds fm_n; otherwise the hooks do what the firmware did. +.org 0x800 +w_fm: .word 0 @ 0x00 address of the menu object pointer + .word 0 @ 0x04 field byte (RAM) + .word 0 @ 0x08 planet level byte (RAM, low nibble) + .word 0 @ 0x0C original list builder (thumb) + .word 0 @ 0x10 original preview loader (thumb) +fm_off: .byte 0, 0, 0, 0 @ 0x14 list, index, count, menu flag offsets in the object +fm_n: .byte 0, 0, 0, 0 @ 0x18 entries +fm_ent: .space 8 @ 0x1C slot | set << 7 +.org 0x830 + .word six_fbuild, six_fcmp, six_fset, six_fprev + +@ r0 = list in the menu object. Replaces the call of the list builder. +.thumb_func +six_fbuild: + push {r3-r7,lr} + mov r4,r0 + ldr r5,=w_fm + ldrb r6,[r5,#0x14] + subs r6,r4,r6 @ object + ldr r1,[r5,#8] + ldrb r1,[r1] + and r1,r1,#15 + ldrb r7,[r5,#0x18] + cmp r1,#4 + blt 8f + cmp r7,#2 + blt 8f + ldr r1,[r5,#4] + ldrsb r1,[r1] @ field slot + ldrb r2,[r5,#0x17] + ldrb r2,[r6,r2] + lsls r2,r2,#31 + beq 2f + @ adult: slots 0..2 of the current set + movs r0,#0 + strb r0,[r4] + movs r0,#1 + strb r0,[r4,#1] + movs r0,#2 + strb r0,[r4,#2] + movs r7,#3 + mov r0,r1 + b 6f +2:ldr r2,=_start + ldr r2,[r2,#8] + ldrsb r2,[r2] @ current set + movs r3,#0 @ i + mov r12,#0xFF @ exact match + mov lr,#0xFF @ same slot +3:cmp r3,r7 + bge 5f + add r0,r5,r3 + ldrb r0,[r0,#0x1C] + push {r0} + and r0,r0,#3 + strb r0,[r4,r3] + cmp r0,r1 + pop {r0} + bne 4f + cmp lr,#0xFF + it eq + moveq lr,r3 + lsrs r0,r0,#7 + cmp r0,r2 + bne 4f + cmp r12,#0xFF + it eq + moveq r12,r3 +4:adds r3,#1 + b 3b +5:mov r0,r12 + cmp r0,#0xFF + it eq + moveq r0,lr + cmp r0,#0xFF + it eq + moveq r0,#0 +6:ldrb r2,[r5,#0x15] + strb r0,[r6,r2] @ index + ldrb r2,[r5,#0x16] + strb r7,[r6,r2] @ count + pop {r3-r7,pc} +8:ldr r1,[r5,#0x0C] @ as before: the firmware's list, then count and index moved + blx r1 + ldrb r2,[r4,#3] + ldrb r1,[r5,#0x16] + strb r2,[r6,r1] + ldrb r2,[r4,#4] + ldrb r1,[r5,#0x15] + strb r2,[r6,r1] + pop {r3-r7,pc} + +@ r0 = object + index, r1 = index. Returns the slot of the entry. The entries of the other set +@ return 0x7F, so the firmware never takes them for the current field. +.thumb_func +six_fcmp: + push {r1-r3,lr} + bl fm_get + beq 1f + ldr r2,=_start + ldr r2,[r2,#8] + ldrsb r2,[r2] + cmp r3,r2 + it ne + movne r0,#0x7F +1:pop {r1-r3,pc} + +@ Same place before the firmware switches the field: switch the set first. +.thumb_func +six_fset: + push {r1-r3,lr} + bl fm_get + beq 1f + ldr r2,=_start + ldr r2,[r2,#8] + strb r3,[r2] +1:pop {r1-r3,pc} + +@ r0 = object + index, r1 = index -> r0 = slot, r3 = set of the entry, Z set when inactive. +@ Uses r2. Keeps r1. +fm_get: + ldr r3,=w_fm + ldrb r2,[r3,#0x14] + ldrsb r0,[r0,r2] + push {r0} + ldr r0,[r3] + ldr r0,[r0] @ object + ldrb r2,[r3,#0x16] + ldrb r2,[r0,r2] @ count + ldrb r0,[r3,#0x18] + cmp r2,r0 + bne 2f + add r3,r3,r1 + ldrb r3,[r3,#0x1C] + lsrs r3,r3,#7 + pop {r0} + movs r2,#1 + cmp r2,#0 @ Z clear: active + bx lr +2:pop {r0} + movs r2,#0 + cmp r2,#0 @ Z set + bx lr + +@ Replaces the call of the preview loader (r0, r1 its arguments): the preview of an entry of +@ the other set loads with that set, then the set goes back. +.thumb_func +six_fprev: + push {r3-r7,lr} + mov r6,r0 + mov r7,r1 + ldr r4,=_start + ldr r4,[r4,#8] + ldrb r5,[r4] @ set before + ldr r3,=w_fm + ldr r0,[r3] + ldr r0,[r0] @ object + ldrb r2,[r3,#0x16] + ldrb r2,[r0,r2] + ldrb r1,[r3,#0x18] + cmp r2,r1 + bne 1f + ldrb r2,[r3,#0x15] + ldrsb r1,[r0,r2] @ index + add r1,r1,r3 + ldrb r1,[r1,#0x1C] + lsrs r1,r1,#7 + strb r1,[r4] +1:mov r0,r6 + mov r1,r7 + ldr r3,=w_fm + ldr r3,[r3,#0x10] + blx r3 + strb r5,[r4] + pop {r3-r7,pc} +.ltorg + +@ ---------------------------------------------------------------- games per start field (version 7) +@ The Paramix menu writes the family byte (settings 0xF05) when it starts a field. In the scenes +@ listed at gm_sc the lab games then use other pictures: every changed place in the firmware +@ calls six_imm, which looks up the return address in the site list and puts the value of the +@ family into the register (for "add rd, rn, #imm" the value is added to rn). The lab card list +@ steps through the cards of the family (six_cnext, six_cprev). +.org 0x980 +w_gm: .word 0 @ 0x00 site list: return address, value 0, 1, 2, rd, rn (0xFF none), flags (bit 0: any scene), 20 bytes, ends with 0 + .word 0 @ 0x04 family byte (RAM) + .word 0 @ 0x08 scene variable (RAM: u16 now, u16 next) +gm_sc: .space 12 @ 0x0C scenes where the family counts (bytes, 0 = end) +gm_seq: .space 16 @ 0x18 lab cards in order for family 1 and 2 (8 bytes each, 0xFF = end) +.org 0x9B0 + .word six_imm, six_cnext, six_cprev + +@ r0 = family in a listed scene, else 0. Uses r1-r3. +gm_fam: + push {r4,lr} + ldr r3,=w_gm + ldr r0,[r3,#4] + cbz r0,8f + ldrb r0,[r0] + cmp r0,#3 + bhs 8f + cbz r0,9f + ldr r1,[r3,#8] + ldrh r2,[r1] + ldrh r1,[r1,#2] + adds r3,#0x0C +1:ldrb r4,[r3],#1 + cbz r4,8f + cmp r4,r2 + beq 9f + cmp r4,r1 + beq 9f + b 1b +8:movs r0,#0 +9:pop {r4,pc} + +@ Replaces a movw/mov.w/addw (bl) or a movw/movt pair (bl + nop). Keeps every other register and the flags. +.thumb_func +six_imm: + push {r0-r12} + mrs r4,apsr + mov r5,lr + bl gm_fam + ldr r3,=w_gm + ldr r3,[r3] +1:ldr r1,[r3] + cbz r1,9f + cmp r1,r5 + beq 2f + adds r3,#20 + b 1b +2:ldrb r1,[r3,#18] @ bit 0: the family counts in every scene + lsls r1,r1,#31 + beq 4f + ldr r0,=w_gm + ldr r0,[r0,#4] + ldrb r0,[r0] + cmp r0,#3 + it hs + movhs r0,#0 +4:add r1,r3,r0,lsl #2 + ldr r1,[r1,#4] + ldrb r2,[r3,#17] + cmp r2,#13 + bhs 3f + ldr r2,[sp,r2,lsl #2] + add r1,r1,r2 +3:ldrb r2,[r3,#16] + str r1,[sp,r2,lsl #2] +9:msr APSR_nzcvq,r4 + mov lr,r5 + pop {r0-r12} + bx lr + +@ r2 = menu object. Replaces "ldrh.w r1,[r2,#126]" before the card number goes up (+1) or down (-1): +@ r1 = next card - 1 or previous card + 1 in the order of the family (as before without a family). +.macro CARD dir + push {r0,r2-r5,lr} + mrs r4,apsr + ldrh r5,[r2,#126] + bl gm_fam + mov r1,r5 + cbz r0,9f + ldr r3,=gm_seq-8 + add r3,r3,r0,lsl #3 + movs r2,#0 +1:ldrb r0,[r3,r2] + cmp r0,#0xFF + beq 9f + cmp r0,r5 + beq 2f + adds r2,#1 + cmp r2,#8 + blo 1b + b 9f +.if \dir > 0 +2:adds r2,#1 + ldrb r0,[r3,r2] + cmp r2,#8 + it hs + movhs r0,#0xFF + cmp r0,#0xFF + it eq + ldrbeq r0,[r3] + subs r1,r0,#1 +.else +2:cbnz r2,3f +4:ldrb r0,[r3,r2] + cmp r0,#0xFF + beq 5f + adds r2,#1 + cmp r2,#8 + blo 4b +5: +3:subs r2,#1 + ldrb r0,[r3,r2] + adds r1,r0,#1 +.endif +9:msr APSR_nzcvq,r4 + pop {r0,r2-r5,pc} +.endm +.thumb_func +six_cnext: + CARD 1 +.thumb_func +six_cprev: + CARD -1 +.ltorg + +@ ---------------------------------------------------------------- DNA per field (option bit 3) +@ The firmware keeps a DNA history of 12 entries: the field slot the Tama lived in, one entry per +@ stretch of time. With the set byte a slot means two fields (Glacier and Water share slot 1), +@ so the history mixed them up. With this option an entry is the field itself: slot + 3 when the +@ set byte is on and the slot is one of the switched ones (mask; Tropical/Glacier all three, Jade +@ Forest slot 1). Every place that writes or reads the history goes through the code here. +@ The firmware also keeps some values per field slot (residents, time in the field and more, +@ the regions at dna_reg). When the game's field menu switches the set, they are swapped with +@ a stash in the settings block, so every field keeps its own. +@ The first call converts an old history once (the entries count for the current set) and clears +@ the stash; the marker byte says it is done. +.org 0xC00 +w_dna: .word 0 @ 0x00 settings block (RAM) + .hword 0, 0 @ 0x04 offset of the DNA count (entries follow), field byte + .hword 0, 0 @ 0x08 stash, marker byte + .hword 0 @ 0x0C byte with per slot bits (0 = none) + .byte 0, 0 @ 0x0E its mask, slots switched by the set byte (bits 0..2) +dna_reg: .space 24 @ 0x10 up to 6 regions (u16 offset, u16 length), length 0 ends +dna_ic: .space 12 @ 0x28 picture per field 0..5 +food_h: .hword 0 @ 0x34 offset of the food history (count, 4 entries) in the settings block +food_b: .space 6 @ 0x36 first food kind (0 based) of the three kinds per field 0..5 +.org 0xC40 + .word dna_maj, dna_maj6, dna_icon, dna_majf, dna_f6_r0, dna_f6_r1_r0, dna_f6_r1_r1, dna_child, dna_hchild, dna_fset + .word dna_fok, dna_fbr + +@ r0 = slot 0..2 -> r0 = field (slot + 3 when the set byte is on and the slot switches). Uses r12. +s2f: + cmp r0,#2 + bhi 1f + FLAG + beq 1f + push {r1} + ldr r1,=w_dna + ldrb r1,[r1,#0x0F] + lsr r1,r1,r0 + lsls r1,r1,#31 + it ne + addne r0,#3 + pop {r1} +1:bx lr + +@ Once per save: old entries count for the current set, the stash starts empty. Keeps all registers. +dna_init: + push {r0-r4,lr} + ldr r4,=w_dna + ldr r0,[r4] + ldrh r1,[r4,#0x0A] + ldrb r2,[r0,r1] + cmp r2,#0x5A + beq 9f + movs r2,#0x5A + strb r2,[r0,r1] + ldrh r1,[r4,#4] + add r1,r1,r0 + ldrb r2,[r1],#1 + cmp r2,#12 + it hi + movhi r2,#12 +1:cbz r2,3f + ldrb r0,[r1] + bl s2f + strb r0,[r1],#1 + subs r2,#1 + b 1b +3:ldr r0,[r4] + ldrh r1,[r4,#8] + add r1,r1,r0 + movs r2,#1 @ the bits byte + add r3,r4,#0x10 +4:ldrh r0,[r3,#2] + cbz r0,5f + add r2,r2,r0 + adds r3,#4 + b 4b +5:movs r0,#0 +6:strb r0,[r1],#1 + subs r2,#1 + bne 6b +9:pop {r0-r4,pc} + +@ r0 = settings block -> r0 = field 0..5 (other values as they are). Uses r12. +f6: + ldr r12,=w_dna + ldrh r12,[r12,#6] + ldrb r0,[r0,r12] + b s2f + +@ r6 = 3: per slot of the current set (an entry counts for slot s when it is the field of s now), +@ r6 = 6: per field. -> r0 = slot/field with at least 4 entries (the last one wins, as in the +@ firmware), else r6. Uses r1-r5, r12. +majc: + push {lr} + bl dna_init + ldr r4,=w_dna + ldr r0,[r4] + ldrh r1,[r4,#4] + add r1,r1,r0 + ldrb r2,[r1],#1 + cmp r2,#12 + it hi + movhi r2,#12 + movs r3,#0 +1:cbz r2,2f + ldrb r5,[r1],#1 + mov r0,r5 + cmp r6,#3 + bne 8f + movs r0,#0 @ which slot has this field now? +7:push {r0} + bl s2f + cmp r0,r5 + pop {r0} + beq 8f + adds r0,#1 + cmp r0,#3 + blo 7b + b 3f +8:cmp r0,r6 + bhs 3f + lsls r0,r0,#2 + mov r12,#1 + lsl r12,r12,r0 + add r3,r3,r12 +3:subs r2,#1 + b 1b +2:mov r0,r6 + movs r1,#0 +4:cmp r1,r6 + bhs 5f + lsls r2,r1,#2 + lsr r12,r3,r2 + and r12,r12,#15 + cmp r12,#4 + it hs + movhs r0,r1 + adds r1,#1 + b 4b +5:pop {pc} + +@ The firmware's majority (b.w): slot 0..2 with at least 4 entries of its current field, else 3. +.thumb_func +dna_maj: + push {r4-r6,lr} + movs r6,#3 + bl majc + pop {r4-r6,pc} + +@ Second copy, used for the DNA picture only: field 0..5, else 6 (the caller shows picture 2 then). +.thumb_func +dna_maj6: + push {r4-r6,lr} + movs r6,#6 + bl majc + pop {r4-r6,pc} + +@ Before the firmware removes the leading field from the history: field 0..5, else 0xFF. +.thumb_func +dna_majf: + push {r4,lr} + bl dna_maj + cmp r0,#3 + bhs 1f + bl s2f + pop {r4,pc} +1:movs r0,#0xFF + pop {r4,pc} + +@ Picture of a field (b.w from the firmware's function, r0 = field). +.thumb_func +dna_icon: + push {r1,lr} + bl dna_init + uxtb r0,r0 + cmp r0,#6 + it hs + movhs r0,#0 + ldr r1,=dna_ic + ldrh r0,[r1,r0,lsl #1] + pop {r1,pc} + +@ In place of "ldrb r0,[r0,#field]": the field 0..5. +.thumb_func +dna_f6_r0: + push {lr} + bl dna_init + bl f6 + pop {pc} + +@ In place of "ldrb r0,[r1,#field]". +.thumb_func +dna_f6_r1_r0: + push {lr} + mov r0,r1 + bl dna_init + bl f6 + pop {pc} + +@ In place of "ldrsb r1,[r1,#field]", r0 is kept. +.thumb_func +dna_f6_r1_r1: + push {r0,lr} + mov r0,r1 + bl dna_init + bl f6 + mov r1,r0 + pop {r0,pc} + +@ Child of the hatching (in place of six_child): the same child, and the index in the caller's +@ stack (written into the history right after) becomes the field. +.thumb_func +dna_child: + push {r1,r2,lr} + ldr r1,=w_child + ldr r0,[r1,#8] + add r2,sp,r0 + adds r2,#12 + ldr r0,[r2] + FLAG + ite ne + ldrne r1,[r1,#4] + ldreq r1,[r1] + ldrh r1,[r1,r0,lsl #1] + bl s2f + str r0,[r2] + mov r0,r1 + pop {r1,r2,pc} + +@ Child from the first history entry (12 bytes of the firmware): r0 = child of that field. +.thumb_func +dna_hchild: + push {r1-r3,lr} + bl dna_init + ldr r3,=w_dna + ldr r0,[r3] + ldrh r1,[r3,#4] + add r0,r0,r1 + ldrb r0,[r0,#1] + ldr r1,=w_child + cmp r0,#3 + ite hs + ldrhs r1,[r1,#4] + ldrlo r1,[r1] + it hs + subhs r0,#3 + cmp r0,#2 + it hi + movhi r0,#0 + ldrh r0,[r1,r0,lsl #1] + pop {r1-r3,pc} + +@ In place of six_fset: when the set changes, the per slot values change places with the stash. +.thumb_func +dna_fset: + push {r1-r3,lr} + bl fm_get + beq 1f + ldr r2,=_start + ldr r2,[r2,#8] + ldrb r1,[r2] + cmp r1,r3 + beq 1f + bl dna_init + strb r3,[r2] + bl dna_swap +1:pop {r1-r3,pc} + +@ Food per field (1.7.4): a food kind is 1..18 (Land 1..3, Water 4..6, Sky 7..9, Forest 10..12, +@ Tropical 13..15, Glacier 16..18). Eating counts a kind only when it belongs to the Tama's field. +@ The firmware knows the field from the character's edition code (Tropical 5, Glacier 6, Forest 4) +@ and took Land, Water, Sky (1, 2, 3) for its own slots, so their food never counted. +@ In place of the firmware's check: r0 = edition code, r1 = food kind -> r0 = 0 counts, 1 not. +.thumb_func +dna_fok: + uxth r0,r0 + subs r2,r0,#1 + cmp r2,#2 + bls 2f + movs r2,#9 + cmp r0,#4 + beq 3f + movs r2,#12 + cmp r0,#5 + beq 3f + movs r2,#15 + cmp r0,#6 + beq 3f + movs r0,#1 + bx lr +2:add r2,r2,r2,lsl #1 +3:subs r1,r1,r2 + subs r1,#1 + movs r0,#0 + cmp r1,#2 + it hi + movhi r0,#1 + bx lr + +@ In place of the firmware's young stage branch (b.w at its entry): counts the last 4 food symbols per +@ kind, the field picks its three kinds (field 0..5, food_b) -> r0 = the kind (0..2) eaten more than +@ both others, else 3 (the plain young stage). +.thumb_func +dna_fbr: + push {r4-r6,lr} + sub sp,#72 + movs r1,#0 + movs r2,#18 + mov r0,sp +1:str r1,[r0],#4 + subs r2,#1 + bne 1b + ldr r4,=w_dna + ldr r5,[r4] + ldrh r1,[r4,#0x34] + add r1,r1,r5 + ldrb r2,[r1],#1 + cmp r2,#4 + it hi + movhi r2,#4 +2:cbz r2,3f + ldrb r3,[r1],#1 + cmp r3,#18 + bhs 4f + ldr r6,[sp,r3,lsl #2] + adds r6,#1 + str r6,[sp,r3,lsl #2] +4:subs r2,#1 + b 2b +3:movs r6,#3 + ldrh r0,[r4,#6] + ldrsb r0,[r5,r0] + cmp r0,#2 + bhi 9f + bl s2f + add r1,r4,#0x36 + ldrb r1,[r1,r0] + add r1,sp,r1,lsl #2 + ldr r2,[r1] + ldr r3,[r1,#4] + ldr r1,[r1,#8] + cmp r2,r3 + ble 5f + cmp r2,r1 + ble 5f + movs r6,#0 + b 9f +5:cmp r3,r2 + ble 6f + cmp r3,r1 + ble 6f + movs r6,#1 + b 9f +6:cmp r1,r2 + ble 9f + cmp r1,r3 + ble 9f + movs r6,#2 +9:mov r0,r6 + add sp,#72 + pop {r4-r6,pc} + +@ Live per slot values <-> stash. Keeps all registers. +dna_swap: + push {r0-r6,lr} + ldr r4,=w_dna + ldr r0,[r4] + ldrh r1,[r4,#8] + add r1,r1,r0 + add r5,r4,#0x10 +1:ldrh r2,[r5,#2] + cbz r2,3f + ldrh r3,[r5] + add r3,r3,r0 +2:ldrb r6,[r3] + ldrb r12,[r1] + strb r6,[r1],#1 + strb r12,[r3],#1 + subs r2,#1 + bne 2b + adds r5,#4 + b 1b +3:ldrh r3,[r4,#0x0C] + cbz r3,9f + add r3,r3,r0 + ldrb r2,[r4,#0x0E] + ldrb r5,[r3] + ldrb r6,[r1] + and r12,r5,r2 + bic r5,r5,r2 + and r6,r6,r2 + orr r5,r5,r6 + strb r5,[r3] + strb r12,[r1] +9:pop {r0-r6,pc} +.ltorg diff --git a/sms/README.md b/sms/README.md new file mode 100644 index 0000000..75c8ff4 --- /dev/null +++ b/sms/README.md @@ -0,0 +1,38 @@ +# SMSEmu + +The Sega Master System on the Tamagotchi Paradise, as a further program of the Paramix menu. +No ROM here: bring your own game (.sms, or .gg for the Game Gear: SMS_GG, 160 x 144 shrunk to 128 x 115, its 12-bit colours, START on port 0). +State (SMS_STATE): on leaving (wheel held) the whole machine goes to the flash (`emu/src/emu/pstate.h`), read once +at the next start. Settings: "Restart game". + +- `src/core/z80.h`: own Z80 interpreter (flags as on the chip, tables for sign, zero and parity). The opcode cases are + generated by `src/core/gen_z80.py` into `z80_ops.inc` and `z80_fns.inc`. Passes zexdoc and zexall. +- `src/core/sms.h`: the machine: memory map with read pages of 1 KB (the ROM is read in place from the flash window), + Sega mapper (FFFC..FFFF, cartridge RAM up to 32 KB), VDP mode 4 (background with scrolling and the locked areas, + priority, sprites 8 x 8 and 8 x 16, zoom, eight per line, overflow and collision flags, line and frame interrupts, + tiles kept decoded), PSG registers, ports (pad, export console). NTSC timing: 262 lines of 228 cycles. +- `src/app/main.c`: the Paradise program (PRAM, about 40 KB). Settings block "PMXS" at 0x140, laid out as GBEmu's: + ROM, length, save (4 KB settings of the device, then the cartridge RAM, 32 KB), flags (bit 0 English, bit 1 wheel + the other way round), name, keys (9 bytes). +- Screen: 256 x 192 to 128 x 96, every 2 x 2 dots mixed, black bars above and below. Lines go to the display while the + frame runs; a row that did not change is not sent again. Normally every second frame is drawn; when the game falls + behind, up to three in a row are left out. +- Keys: `keys[i]` are Master System buttons (1 up, 2 down, 4 left, 8 right, 16 button 1, 32 button 2, 64 pause) for the + Paradise input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. Default: A left, + B button 1, C right, wheel press button 2, wheel up/down, A+C pause. Fixed: A+B+C settings (pause, sound, light, dim, + screen off, restart game, language); wheel held 2 s = save and back to the Paradise. +- Sound: the loudest of the three tone channels on the buzzer (the noise channel never); a new pitch starts the timer + anew (as GB_TONE_RESTART). +- Save: the 4 KB pages of the cartridge RAM the game changed go to the flash 3 s after the last write (1 s without a + key), when the screen goes off and on leaving. + +Build: `sh src/app/build.sh` (clang, lld) gives `sms.bin`. +Test on the PC: `gcc -O2 -o smshost src/host/host.c`, then `SHOTS=100,200 KEYS=700:16,710:0 ./smshost game.sms 1000 outdir`. +Device simulation: `python3 test/mkimg.py sms.bin game.sms img.bin` then `python3 test/devsms.py src/app/sms.elf img.bin ` +(KEYS, WHEEL, SHOTS, OUT as for GBEmu; US_PX = display time per dot in microseconds). `test/zex.c` runs the CP/M +exercisers (not included) on the Z80. + +Author: mameise + +No session (1.7.3 test7, switch SESS_FLAG): flags bit 12 set by the Studio ("Remember where you left off" off): leaving writes +no state, a start drops an old one; only the game's own save (cartridge RAM or EEPROM) is kept. diff --git a/sms/sms.bin b/sms/sms.bin new file mode 100644 index 0000000..8e6b429 Binary files /dev/null and b/sms/sms.bin differ diff --git a/sms/src/app/build.sh b/sms/src/app/build.sh new file mode 100644 index 0000000..1b5448a --- /dev/null +++ b/sms/src/app/build.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Build SMSEmu for the Paradise (clang/lld, Cortex-M3). Output: ../../sms.bin +set -e +cd "$(dirname "$0")" +E=../../../emu/src/emu +CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -Wno-unused-variable -fno-builtin-memset -isystem ../stub -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DBL_SLEEP -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DTONE_SAFE -DSMS_STATE -DSMS_GG -DGPLAY -DSESS_FLAG $XCF" +O="" +for f in main.c $E/hw.c $E/flash.c $E/libc.c; do + n=$(basename $f .c); OPT=-Os; [ "$n" = main ] && OPT=-O2; clang $CF $OPT -c $f -o $n.o; O="$O $n.o"; done +ld.lld -T link.ld --no-rosegment $O -o sms.elf +llvm-objcopy -O binary -j .text -j .data -j .init sms.elf sms.bin +cp sms.bin ../../sms.bin; rm -f *.o sms.bin; [ -n "$KEEPELF" ] || rm -f sms.elf; ls -l ../../sms.bin diff --git a/sms/src/app/font.h b/sms/src/app/font.h new file mode 100644 index 0000000..b01afaa --- /dev/null +++ b/sms/src/app/font.h @@ -0,0 +1,99 @@ +/* generated by gen/font.py: custom 5x7 font */ +static const unsigned char g_font[96][7]={ + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x04,0x04,0x04,0x04,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x19,0x19,0x02,0x04,0x08,0x13,0x13}, + {0x0c,0x12,0x14,0x08,0x15,0x12,0x0d}, + {0x04,0x04,0x08,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x08,0x08,0x04,0x02}, + {0x08,0x04,0x02,0x02,0x02,0x04,0x08}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x04,0x04,0x1f,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x0c,0x04,0x08}, + {0x00,0x00,0x00,0x1f,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x0c,0x0c}, + {0x01,0x01,0x02,0x04,0x08,0x10,0x10}, + {0x0e,0x11,0x13,0x15,0x19,0x11,0x0e}, + {0x04,0x0c,0x04,0x04,0x04,0x04,0x0e}, + {0x0e,0x11,0x01,0x02,0x04,0x08,0x1f}, + {0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e}, + {0x02,0x06,0x0a,0x12,0x1f,0x02,0x02}, + {0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e}, + {0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e}, + {0x1f,0x01,0x02,0x04,0x08,0x08,0x08}, + {0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e}, + {0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e}, + {0x00,0x04,0x04,0x00,0x04,0x04,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x02,0x04,0x08,0x10,0x08,0x04,0x02}, + {0x00,0x00,0x1f,0x00,0x1f,0x00,0x00}, + {0x08,0x04,0x02,0x01,0x02,0x04,0x08}, + {0x0e,0x11,0x01,0x02,0x04,0x00,0x04}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x0e,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e}, + {0x0e,0x11,0x10,0x10,0x10,0x11,0x0e}, + {0x1e,0x11,0x11,0x11,0x11,0x11,0x1e}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f}, + {0x1f,0x10,0x10,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x10,0x17,0x11,0x11,0x0f}, + {0x11,0x11,0x11,0x1f,0x11,0x11,0x11}, + {0x0e,0x04,0x04,0x04,0x04,0x04,0x0e}, + {0x07,0x02,0x02,0x02,0x02,0x12,0x0c}, + {0x11,0x12,0x14,0x18,0x14,0x12,0x11}, + {0x10,0x10,0x10,0x10,0x10,0x10,0x1f}, + {0x11,0x1b,0x15,0x15,0x11,0x11,0x11}, + {0x11,0x19,0x15,0x13,0x11,0x11,0x11}, + {0x0e,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x1e,0x11,0x11,0x1e,0x10,0x10,0x10}, + {0x0e,0x11,0x11,0x11,0x15,0x12,0x0d}, + {0x1e,0x11,0x11,0x1e,0x14,0x12,0x11}, + {0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e}, + {0x1f,0x04,0x04,0x04,0x04,0x04,0x04}, + {0x11,0x11,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x11,0x11,0x11,0x11,0x0a,0x04}, + {0x11,0x11,0x11,0x15,0x15,0x15,0x0a}, + {0x11,0x11,0x0a,0x04,0x0a,0x11,0x11}, + {0x11,0x11,0x0a,0x04,0x04,0x04,0x04}, + {0x1f,0x01,0x02,0x04,0x08,0x10,0x1f}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x11,0x0a,0x04,0x0a,0x11}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x00,0x00,0x00,0x00,0x00,0x00,0x00}, + {0x11,0x0e,0x11,0x1f,0x11,0x11,0x11}, + {0x11,0x0e,0x11,0x11,0x11,0x11,0x0e}, + {0x11,0x00,0x11,0x11,0x11,0x11,0x0e}, +}; diff --git a/sms/src/app/link.ld b/sms/src/app/link.ld new file mode 100644 index 0000000..106ae96 --- /dev/null +++ b/sms/src/app/link.ld @@ -0,0 +1,23 @@ +ENTRY(Reset_Handler) +MEMORY { + PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000 + SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000 +} +SECTIONS { + .text : { + KEEP(*(.vectors)) + KEEP(*(.pmxcfg)) + *(.text*) + *(.rodata*) + . = ALIGN(4); + __pdata_start = .; + } > PRAM + .bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM + /* mutable data in SRAM (initial values in PRAM, copied at startup), as in TamaEmu */ + .data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM + __data_load = LOADADDR(.data); + .init : { . = ALIGN(4); KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); __prog_end = .; } > PRAM + ASSERT(__prog_end <= 0x10000, "program too big for PRAM") + ASSERT(__bss_end <= 0x1801F000, "RAM full") + /DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) } +} diff --git a/sms/src/app/main.c b/sms/src/app/main.c new file mode 100644 index 0000000..19aeb96 --- /dev/null +++ b/sms/src/app/main.c @@ -0,0 +1,480 @@ +/* SMSEmu: the Sega Master System on the Tamagotchi Paradise. Core: ../core (own Z80, VDP mode 4, Sega mapper). + * Started from the Paramix menu like the other further programs. Bring your own ROM (.sms). + * Screen: 256 x 192 shrunk to 128 x 96 (every 2 x 2 dots mixed), black bars above and below. + * Keys: set in the Studio (tab Master System), stored in the settings block. A+B+C together: settings (also + * pause and sound); wheel held 2 s: save and back to the Paradise. Sound: the Paradise's buzzer plays the loudest + * of the three tone channels. Save: the cartridge RAM (battery save) goes to the flash a few seconds after the game + * wrote it, and on leaving. + * Author: mameise */ +#include "../../../emu/src/emu/hw.h" +#include "../../../emu/src/emu/exitkey.h" +#include "../../../emu/src/emu/flash.h" +#define PARA_ATTR +#include "../../../emu/src/emu/paraclock.h" +#ifdef PARA_BACK +#include "../../../emu/src/emu/paraback.h" +#ifdef GPLAY +#define GP_POINTS +#include "../../../emu/src/emu/gplay.h" +#endif +#endif +typedef int s32; + +/* ---- settings block at 0x140, filled in by the Studio ---- + * keys[i]: Master System buttons (1 up, 2 down, 4 left, 8 right, 16 button 1, 32 button 2, 64 pause) + * for the Paradise input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B. + * flags: bit 0 English, bit 1 wheel the other way round. + * save_off: 4 KB settings of the device, then the cartridge RAM (32 KB). */ +#define NIN 9 +typedef struct { u32 magic, version, rom_off, rom_len, save_off, flags; char name[16]; u8 keys[12]; } SmsCfg; +#define SMS_MAGIC 0x53584D50u /* "PMXS" */ +__attribute__((section(".pmxcfg"), used)) +volatile const SmsCfg g_cfg = { SMS_MAGIC, 1, 0, 0, 0, 2, {0}, { 0x04, 0x10, 0x08, 0x20, 0x01, 0x02, 0x40, 0x00, 0x00 } }; +#define SETTINGS (g_cfg.save_off) +#define CRAM_AT (g_cfg.save_off + 0x1000u) +#define CRAM_MAX 0x8000u +#define XIP_BASE_REG REG(0x4002F004u) +#define XIP_CTRL_REG REG(0x4002F000u) +#define ROMWIN ((const u8 *)0x10000000u) + +/* ---- screen: lines come from the core while a frame runs; every two lines give one row of 128 ---- */ +/* Master System 128 x 96 from y 16; Game Gear (SMS_GG): 160 x 144 to 128 x 115 from y 6 */ +static int OY = 16, OH = 96; +#define OH_MAX 115 +static void sms_line(int y, const u8 *lb); +#define SMS_LINE(y, lb) sms_line((y), (lb)) +#include "../core/sms.h" +#include "font.h" + +/* ---- time: SysTick 1 ms; the wheel's encoder is read here too, so no step is lost while a frame runs ---- */ +static volatile u32 g_ms; +static u32 g_tone_now; +static volatile s32 g_enc_acc; static u32 g_enc_last; +static const signed char QD[16] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 }; +#define GPIO2 0x4001A000u +#define SYST_CSR REG(0xE000E010u) +#define SYST_RVR REG(0xE000E014u) +#define SYST_CVR REG(0xE000E018u) +#define CORE_HZ 96000000u +__attribute__((used)) void systick_c(void) +{ + g_ms++; + u32 n = REG(GPIO2) & 3u; + if (n != g_enc_last) { g_enc_acc += QD[(g_enc_last << 2) | n]; g_enc_last = n; } +} +__attribute__((naked)) void SysTick_Handler(void) { __asm__ volatile("b systick_c\n"); } +void abort(void) { for (;;) hw_wdt_feed(); } + +/* ---- settings on the device ---- */ +typedef struct { u8 magic[4]; u8 r1, dim, lang, dimto, off, r0, r2, mute; } SmsSet; /* mute: 0 = sound on */ +static SmsSet g_set = { {'S','M','S','1'}, 0, 7, 0, 6, 3, 0x80, 0, 0 }; +#define T_N 7 +static const u32 T_MS[T_N] = { 10000u, 20000u, 30000u, 60000u, 120000u, 300000u, 600000u }; +static const char *const T_NM[2][T_N + 1] = { { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NIE" }, { "10 S", "20 S", "30 S", "1 MIN", "2 MIN", "5 MIN", "10 MIN", "NEVER" } }; +#define LV_N 11 +#define DIM2_N 10 +static const u8 LV_PCT[LV_N] = { 100u, 5u, 10u, 20u, 30u, 40u, 50u, 60u, 70u, 80u, 90u }; +static const u8 DIM2_PCT[DIM2_N] = { 1u, 2u, 3u, 5u, 10u, 15u, 20u, 30u, 40u, 50u }; +static int en(void) { return g_set.lang ? g_set.lang == 2u : (int)(g_cfg.flags & 1u); } +#define BG 0x0000u +#define INK 0xFFFFu +#define OFF 0x7BEFu +static int g_dimmed; +static void light(void) +{ +#ifdef BL_PWM + u32 l = LV_PCT[(g_set.r0 & 15u) % LV_N], d = DIM2_PCT[g_set.dimto % DIM2_N]; + hw_bl_set(g_dimmed ? (d < l ? d : l) : l); +#endif +} +static u8 g_sec[0x1000] __attribute__((aligned(4))); +static void set_load(void) +{ + const volatile u8 *p = XIP_PTR(SETTINGS); SmsSet t; u8 *d = (u8 *)&t; + for (u32 i = 0; i < sizeof t; i++) d[i] = p[i]; + if (t.magic[0] == 'S' && t.magic[1] == 'M' && t.magic[2] == 'S' && t.magic[3] == '1' && t.dim <= T_N && t.off <= T_N && t.lang < 3u) g_set = t; + light(); +} +static void set_store(void) +{ + for (u32 i = 0; i < sizeof g_sec; i++) g_sec[i] = 0xFF; + const u8 *s = (const u8 *)&g_set; for (u32 i = 0; i < sizeof g_set; i++) g_sec[i] = s[i]; + flash_update4k(SETTINGS, g_sec); +} + +/* ---- the cartridge RAM: 4 KB pages that changed go to the flash ---- */ +static u8 g_cram[CRAM_MAX] __attribute__((aligned(4))); +static u32 g_cram_seen; /* pages the game wrote since the last store */ +static void cram_load(void) +{ + const volatile u8 *p = XIP_PTR(CRAM_AT); + for (u32 i = 0; i < CRAM_MAX; i++) g_cram[i] = p[i]; +} +static void cram_store(void) +{ + u32 m = (u32)g_sms.cram_dirty; g_sms.cram_dirty = 0; g_cram_seen = 0; + for (u32 pg = 0; pg < CRAM_MAX / 0x1000u; pg++) { + if (!(m & (1u << pg))) continue; + for (u32 i = 0; i < 0x1000u; i++) g_sec[i] = g_cram[pg * 0x1000u + i]; + hw_tone(0); g_tone_now = 0; + flash_update4k(CRAM_AT + pg * 0x1000u, g_sec); + } +} + +/* ---- sound: the loudest of the three tone channels (the noise channel never) ---- */ +static void psg_frame(void) +{ + Sms *s = &g_sms; u32 hz = 0; + if (!g_set.mute) { + int best = -1; u32 bv = 15; + for (int c = 0; c < 3; c++) { u32 v = s->vol[c] & 15u, n = s->tone[c]; if (v < bv && n >= 8u) { bv = v; best = c; } } + if (best >= 0) { hz = 3579545u / (32u * s->tone[best]); if (hz < 40u || hz > 10000u) hz = 0; } + } + /* as GB_TONE_RESTART: every new pitch starts the timer anew; changes below about 1.5 % are left out */ + if (hz && g_tone_now) { u32 d = hz > g_tone_now ? hz - g_tone_now : g_tone_now - hz; if (d * 64u < g_tone_now) return; } + if (hz != g_tone_now) { if (hz && g_tone_now) hw_tone(0); g_tone_now = hz; hw_tone(hz); } +} +static void psg_quiet(void) { if (g_tone_now) { g_tone_now = 0; hw_tone(0); } } + +/* ---- screen ---- */ +static u16 g_ha[128] __attribute__((aligned(4))); /* the even line, two dots mixed into one */ +static u16 g_row[128] __attribute__((aligned(4))); +static u32 g_hash[OH_MAX]; +static int g_draw, g_win = -1, g_force; +static inline u32 mix2(u32 a, u32 b) { return (a & b) + (((a ^ b) & 0xF7DEu) >> 1); } +static void row_out(int r, u32 h) +{ + if (h == g_hash[r] && !g_force) return; /* the row as it is on the display */ + g_hash[r] = h; + if (g_win != r) { if (g_win >= 0) hw_px_end(); hw_px_begin(0, (u32)(OY + r), 128, (u32)(OY + OH)); } + hw_px_row(g_row, 128); + g_win = r + 1; +} +#ifdef SMS_GG +/* Game Gear: the 160 x 144 window (from x 48, y 24); 5 dots to 4 across and 5 lines to 4 down: the outer ones as they + * are, the middle ones mixed from two (as GBEmu, nothing is cut off) */ +static u16 g_gl[2][128] __attribute__((aligned(4))); +static void gg_hrow(const u8 *lb, u16 *o) +{ + const u16 *pal = g_sms.pal565; + for (int k = 0; k < 32; k++, lb += 5, o += 4) { + u32 p1 = pal[lb[1]], p2 = pal[lb[2]], p3 = pal[lb[3]]; + o[0] = pal[lb[0]]; o[1] = (u16)mix2(p1, p2); o[2] = (u16)mix2(p2, p3); o[3] = pal[lb[4]]; + } +} +static u32 row_hash(void) { u32 h = 2166136261u; const u32 *w = (const u32 *)g_row; for (int x = 0; x < 64; x++) h = (h ^ w[x]) * 16777619u; return h; } +static void gg_line(int y, const u8 *lb) +{ + int g = y / 5, l = y % 5, r = g * 4; + switch (l) { + case 0: gg_hrow(lb, g_row); break; + case 1: gg_hrow(lb, g_gl[0]); return; + case 2: gg_hrow(lb, g_gl[1]); for (int x = 0; x < 128; x++) g_row[x] = (u16)mix2(g_gl[0][x], g_gl[1][x]); r += 1; break; + case 3: gg_hrow(lb, g_gl[0]); for (int x = 0; x < 128; x++) g_row[x] = (u16)mix2(g_gl[1][x], g_gl[0][x]); r += 2; break; + default: gg_hrow(lb, g_row); r += 3; break; + } + if (r < OH) row_out(r, row_hash()); +} +#endif +static void sms_line(int y, const u8 *lb) +{ + const u16 *pal = g_sms.pal565; +#ifdef SMS_GG + if (g_sms.gg) { if (y >= 24 && y < 168) gg_line(y - 24, lb + 48); return; } +#endif + if (!(y & 1)) { for (int x = 0; x < 128; x++) g_ha[x] = (u16)mix2(pal[lb[2 * x]], pal[lb[2 * x + 1]]); return; } + u32 h = 2166136261u; + for (int x = 0; x < 128; x += 2) { + u32 a = mix2(g_ha[x], mix2(pal[lb[2 * x]], pal[lb[2 * x + 1]])); + u32 b = mix2(g_ha[x + 1], mix2(pal[lb[2 * x + 2]], pal[lb[2 * x + 3]])); + g_row[x] = (u16)a; g_row[x + 1] = (u16)b; + h = (h ^ (a | b << 16)) * 16777619u; + } + row_out(y >> 1, h); +} +static void bars(void) +{ + for (int x = 0; x < 128; x++) g_row[x] = 0; + hw_px_begin(0, 0, 128, (u32)OY); for (int y = 0; y < OY; y++) hw_px_row(g_row, 128); hw_px_end(); + hw_px_begin(0, (u32)(OY + OH), 128, 128); for (int y = OY + OH; y < 128; y++) hw_px_row(g_row, 128); hw_px_end(); +} +static void redraw_all(void) { bars(); g_force = 1; for (int i = 0; i < OH; i++) g_hash[i] = 0; } + +/* ---- the settings menu (A+B+C): A next line, B change, C close ---- */ +static int g_menu, g_msel, g_mtop; +static void text(int x, int y, const char *s, u16 col, u16 *row, int ry) +{ + for (; *s; s++, x += 6) { + int c = (unsigned char)*s; if (c >= 97 && c <= 122) c -= 32; c = (c < 32 || c > 127) ? 0 : c - 32; + if (ry < y || ry >= y + 7) continue; + u8 bits = g_font[c][ry - y]; + for (int k = 0; k < 5; k++) if ((bits & (0x10 >> k)) && x + k >= 0 && x + k < 128) row[x + k] = col; + } +} +enum { M_PAUSE, M_SND, M_LIGHT, M_DIM, M_DIMTO, M_OFF, M_RESET, M_LANG, M_N }; +static u32 g_pause_until; /* menu line PAUSE: pressed for 200 ms after the menu closes */ +static int g_items[M_N], g_nitems; +static void menu_items(void) +{ + g_nitems = 0; + for (int k = 0; k < M_N; k++) { if (k == M_DIMTO && g_set.dim >= T_N) continue; g_items[g_nitems++] = k; } + if (g_msel >= g_nitems) g_msel = g_nitems - 1; +} +static void pct(char *o, int v) { int n = 0; if (v >= 100) o[n++] = '1'; if (v >= 10) o[n++] = (char)('0' + (v / 10) % 10); o[n++] = (char)('0' + v % 10); o[n++] = '%'; o[n] = 0; } +static int g_reset_ask; +static void menu_line(int it, const char **a, char *b) +{ + int e = en(); const char *v = 0; b[0] = 0; + switch (it) { + case M_PAUSE: *a = g_sms.gg ? (e ? "PRESS START" : "START DRUECKEN") : (e ? "PRESS PAUSE" : "PAUSE DRUECKEN"); v = "B"; break; + case M_SND: *a = e ? "SOUND" : "TON"; v = g_set.mute ? (e ? "OFF" : "AUS") : (e ? "ON" : "AN"); break; + case M_LIGHT: *a = e ? "LIGHT" : "LICHT"; pct(b, LV_PCT[(g_set.r0 & 15u) % LV_N]); break; + case M_DIM: *a = e ? "DIM AFTER" : "DIMMEN NACH"; v = T_NM[e][g_set.dim <= T_N ? g_set.dim : T_N]; break; + case M_DIMTO: *a = e ? "DIM TO" : "DIMMEN AUF"; pct(b, DIM2_PCT[g_set.dimto % DIM2_N]); break; + case M_OFF: *a = e ? "SCREEN OFF" : "BILD AUS NACH"; v = T_NM[e][g_set.off <= T_N ? g_set.off : T_N]; break; + case M_RESET: *a = e ? "RESTART GAME" : "SPIEL NEU"; v = g_reset_ask ? (e ? "SURE? B" : "SICHER? B") : ""; break; + default: *a = e ? "LANGUAGE" : "SPRACHE"; v = e ? "ENGLISH" : "DEUTSCH"; break; + } + if (v) { int n = 0; while (v[n] && n < 11) { b[n] = v[n]; n++; } b[n] = 0; } +} +#define ROWS 9 +static void menu_draw(void) +{ + if (g_msel < g_mtop) g_mtop = g_msel; + if (g_msel >= g_mtop + ROWS) g_mtop = g_msel - ROWS + 1; + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { + for (int x = 0; x < 128; x++) g_row[x] = BG; + text(4, 3, en() ? "SETTINGS" : "EINSTELLUNGEN", INK, g_row, y); + if (y == 12) for (int x = 0; x < 128; x++) g_row[x] = OFF; + for (int k = 0; k < ROWS && g_mtop + k < g_nitems; k++) { + int i = g_mtop + k, ly = 16 + k * 11; const char *a; char b[12]; menu_line(g_items[i], &a, b); + if (i == g_msel && y >= ly - 2 && y < ly + 9) for (int x = 0; x < 128; x++) g_row[x] = INK; + u16 c = i == g_msel ? BG : INK; + text(4, ly, a, c, g_row, y); int w = 0; while (b[w]) w++; text(124 - w * 6, ly, b, c, g_row, y); + } + text(4, 118, en() ? "A NEXT B SET C OK" : "A ZEILE B SETZEN C OK", OFF, g_row, y); + hw_px_row(g_row, 128); + } + hw_px_end(); +} +static int g_set_dirty; +static void menu_close(void) { g_menu = 0; g_reset_ask = 0; if (g_set_dirty) { set_store(); g_set_dirty = 0; } redraw_all(); } +static void menu_key(u32 k) +{ + if (k & BTN_A) { g_msel = (g_msel + 1) % g_nitems; g_reset_ask = 0; } + if (k & BTN_B) { + switch (g_items[g_msel]) { + case M_PAUSE: g_pause_until = g_ms + 200u; menu_close(); return; + case M_SND: g_set.mute ^= 1u; break; + case M_LIGHT: g_set.r0 = (u8)(0x80u | (((g_set.r0 & 15u) + 1u) % LV_N)); break; + case M_DIM: g_set.dim = (u8)((g_set.dim + 1u) % (T_N + 1u)); if (g_set.dim < T_N && g_set.off < T_N && g_set.off <= g_set.dim) g_set.off = (u8)(g_set.dim + 1u); break; + case M_DIMTO: g_set.dimto = (u8)((g_set.dimto + 1u) % DIM2_N); break; + case M_OFF: do g_set.off = (u8)((g_set.off + 1u) % (T_N + 1u)); while (g_set.off < T_N && g_set.dim < T_N && g_set.off <= g_set.dim); break; + case M_RESET: if (g_reset_ask) { g_reset_ask = 0; if (g_sms.cram_dirty) cram_store(); sms_reset(); menu_close(); return; } g_reset_ask = 1; break; + default: g_set.lang = (u8)(en() ? 1u : 2u); break; + } + if (g_items[g_msel] != M_RESET && g_items[g_msel] != M_PAUSE) g_set_dirty = 1; + light(); menu_items(); + } + if (k & BTN_C) { menu_close(); return; } + menu_draw(); +} +static void message(const char *a, const char *b) +{ + hw_px_begin(0, 0, 128, 128); + for (int y = 0; y < 128; y++) { for (int x = 0; x < 128; x++) g_row[x] = BG; text(4, 50, a, INK, g_row, y); text(4, 62, b, INK, g_row, y); hw_px_row(g_row, 128); } + hw_px_end(); +} + +/* ---- keys: the Paradise inputs to the Master System's buttons (map from the Studio) ---- */ +static u32 g_wheel_until[2]; /* wheel up / down held until (ms) */ +static u32 sms_keys(u32 b, u32 now) +{ + u32 in = 0; + int ac = (b & (BTN_A | BTN_C)) == (BTN_A | BTN_C), bc = (b & (BTN_B | BTN_C)) == (BTN_B | BTN_C), ab = (b & (BTN_A | BTN_B)) == (BTN_A | BTN_B); + u32 used = 0; + if (ac && g_cfg.keys[6]) { in |= 1u << 6; used |= BTN_A | BTN_C; } + if (bc && g_cfg.keys[7]) { in |= 1u << 7; used |= BTN_B | BTN_C; } + if (ab && g_cfg.keys[8]) { in |= 1u << 8; used |= BTN_A | BTN_B; } + u32 r = b & ~used; + if (r & BTN_A) in |= 1u; if (r & BTN_B) in |= 2u; if (r & BTN_C) in |= 4u; if (b & BTN_WHEEL) in |= 8u; + if ((s32)(g_wheel_until[0] - now) > 0) in |= 16u; + if ((s32)(g_wheel_until[1] - now) > 0) in |= 32u; + u32 k = 0; + for (int i = 0; i < NIN; i++) if (in & (1u << i)) k |= g_cfg.keys[i]; + if ((s32)(g_pause_until - now) > 0) k |= SMS_PAUSE; + return k; +} + +#ifdef SMS_STATE +/* ---- 1.6.11 test2: the whole machine on leaving (wheel held), read once at the next start ---- */ +#include "../../../emu/src/emu/pstate.h" +#ifdef SESS_FLAG +#define NOSESS ((g_cfg.flags & 0x1000u) != 0u) /* 1.7.3 test7: the Studio's "remember on leaving" off: only the game's own save */ +#else +#define NOSESS 0 +#endif +#define STATE_AT (g_cfg.save_off + 0x9000u) +#define STATE_MAX 0x7000u +static int g_running; +static u32 st_tag(void) { return 0x534D0001u ^ (u32)&g_sms ^ ((u32)sizeof(Sms) << 8) ^ ((u32)sizeof(Z80) << 20) ^ g_cfg.rom_len ^ (u32)sms_line; } +static int st_parts(StPart *pt) +{ + pt[0].p = &g_cpu; pt[0].n = sizeof g_cpu; pt[1].p = &g_sms; pt[1].n = sizeof g_sms; + pt[2].p = g_ram; pt[2].n = sizeof g_ram; pt[3].p = g_vram; pt[3].n = sizeof g_vram; + return 4; +} +static void state_store(void) { StPart pt[4]; int n = st_parts(pt); if (g_running) st_store(STATE_AT, STATE_MAX, st_tag(), pt, n, g_sec); } +static int state_load(void) +{ + if (NOSESS) { st_drop(STATE_AT); return 0; } + StPart pt[4]; int n = st_parts(pt); + const uint8_t *rom = g_sms.rom; uint32_t rl = g_sms.rom_len; uint8_t *cr = g_sms.cram; uint32_t cl = g_sms.cram_len; + int ok = st_load(STATE_AT, STATE_MAX, st_tag(), pt, n); + if (ok) { /* this program's pointers again, the pages and the decoded tiles from the state */ + g_sms.rom = rom; g_sms.rom_len = rl; g_sms.cram = cr; g_sms.cram_len = cl; g_sms.cram_dirty = 0; + g_sms.rp[0] = rom; sms_pages(0); sms_pages(1); sms_pages(2); + for (int i = 48; i < 64; i++) g_sms.rp[i] = g_ram + (i & 7) * 0x400; + for (uint32_t a = 0; a < 0x4000u; a += 4u) tc_row(a); + } + st_drop(STATE_AT); + return ok; +} +#endif + +/* ---- leaving ---- */ +static void leave(void) +{ + psg_quiet(); hw_tone(0); + if (g_set_dirty) set_store(); + REG(0x20000FF8u) = 0; + REG(0x20000FFCu) = 0x4C584D50u; /* "PMXL": back on purpose, the autostart stays off */ +#ifdef SMS_STATE + if (g_running && !NOSESS) { message(en() ? "SAVING" : "SPEICHERN", ""); state_store(); } +#endif + if (g_sms.cram_dirty) cram_store(); +#ifdef PARA_BACK +#ifdef GPLAY + para_points((uint8_t *)g_sec); /* 1.7.2 test14: play time to Tamapoints */ +#endif + para_back_fix(g_sec); +#endif + hw_bl_pwm_off(); + for (u32 t = 0; hw_buttons() && t < 20000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); + XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u; + hw_back_to_paradise(); +} + +__attribute__((used)) volatile u32 g_smsst[4]; /* frames run, frames drawn, frames dropped, last frame in ms (for the tests) */ +extern u32 __bss_start, __bss_end; +void Reset_Handler(void) +{ + __asm__ volatile("cpsid i"); + u32 cnt = REG(0x45000304u), para = para_clock(cnt, 0, 0x1F000u, 0, 0); + if (!para) para = para_mailbox(cnt); +#ifdef PARA_BACK + para_leave_mark(cnt, para); +#endif + __asm__ volatile("" ::: "memory"); + for (u32 *p = &__bss_start; p < &__bss_end; p++) *p = 0; + { extern u32 __data_start, __data_end, __data_load; + const u32 *src = &__data_load; for (u32 *p = &__data_start; p < &__data_end; p++) *p = *src++; } + (void)para; + REG(0xE000ED14u) &= ~(1u << 3); /* UNALIGN_TRP off */ + hw_init(); + hw_tone(0); + XIP_BASE_REG = 0x60000000u | g_cfg.rom_off; /* the ROM in the cached window from 0x10000000 */ + XIP_CTRL_REG = 3u; + __asm__ volatile("dsb\n isb" ::: "memory"); + REG(GPIO2 + 0x04) &= ~3u; g_enc_last = REG(GPIO2) & 3u; + set_load(); + { /* the 512 byte copier header some dumps carry is left out */ + u32 off = (g_cfg.rom_len & 0x3FFFu) == 512u ? 512u : 0u; + g_sms.rom = ROMWIN + off; g_sms.rom_len = g_cfg.rom_len - off; + } + if (g_sms.rom_len < 0x2000u || g_sms.rom_len > 0x100000u) { + message(en() ? "ROM NOT USABLE" : "ROM GEHT NICHT", ""); + for (u32 t = 0; t < 30000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed(); + leave(); + } + g_sms.cram = g_cram; g_sms.cram_len = CRAM_MAX; +#ifdef SMS_GG + if (g_cfg.flags & 4u) { g_sms.gg = 1; OY = 6; OH = 115; } /* flags bit 2: Game Gear */ +#endif + cram_load(); + sms_reset(); +#ifdef SMS_STATE + state_load(); g_running = 1; +#endif + redraw_all(); + SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; SYST_CSR = 7; + __asm__ volatile("cpsie i"); + + u32 last_in = g_ms, wheel_ms = 0, cram_ms = 0, next_ms = g_ms, frac = 0, mk0 = 0; + int skip_run = 0; + int bl = 1, lock = 1, menu_lock = 0; + for (;;) { + hw_wdt_feed(); + u32 now = g_ms; + u32 b = hw_buttons(); + if (lock) { if (b) b = 0; else lock = 0; } + { s32 a = g_enc_acc; + if (a >= 4 || a <= -4) { + __asm__ volatile("cpsid i"); g_enc_acc -= a >= 4 ? 4 : -4; __asm__ volatile("cpsie i"); + int up = (a > 0) ^ ((g_cfg.flags & 2u) != 0); + u32 *u = &g_wheel_until[up ? 0 : 1]; *u = ((s32)(*u - now) > 0 ? *u : now) + 150u; + last_in = now; + if (g_menu) { g_msel = up ? (g_msel + g_nitems - 1) % g_nitems : (g_msel + 1) % g_nitems; menu_draw(); } + } } + if (b) { + last_in = now; + if (!bl || g_dimmed) { + bl = 1; hw_backlight(1); if (g_dimmed) { g_dimmed = 0; light(); } + if (g_menu) menu_draw(); else redraw_all(); + while (hw_buttons()) hw_wdt_feed(); + continue; + } + } + if (b & BTN_WHEEL) { if (!wheel_ms) wheel_ms = now ? now : 1; else if (EXIT_NOW(now - wheel_ms, 2000u)) leave(); } else wheel_ms = 0; + if ((b & (BTN_A | BTN_B | BTN_C)) == (BTN_A | BTN_B | BTN_C) && !g_menu && !menu_lock) { + psg_quiet(); g_menu = 1; menu_lock = 1; g_msel = 1; g_mtop = 0; menu_items(); menu_draw(); mk0 = BTN_A | BTN_B | BTN_C; g_sms.pad = 0; + } + if (!(b & (BTN_A | BTN_B | BTN_C))) menu_lock = 0; + if (g_menu) { + u32 k = b & (BTN_A | BTN_B | BTN_C), nk = k & ~mk0; mk0 = k; if (nk) menu_key(nk); + next_ms = now; + __asm__ volatile("wfi"); + continue; + } + if (!bl) { psg_quiet(); next_ms = now; __asm__ volatile("wfi"); continue; } /* screen off: the game waits */ + g_sms.pad = (u8)sms_keys(b, now); + /* one frame every 16.68 ms (262 lines of 228 cycles at 3.58 MHz); drawn when there is time */ + if ((s32)(now - next_ms) >= 0) { + if ((s32)(now - next_ms) > 100) { g_smsst[2] += (now - next_ms) / 17u; next_ms = now; } + int behind = (s32)(now - next_ms) > 0; + g_draw = skip_run >= 3 || (skip_run >= 1 && !behind); + skip_run = g_draw ? 0 : skip_run + 1; + u32 t0 = g_ms; + sms_frame(g_draw); + if (g_win >= 0) { hw_px_end(); g_win = -1; } + if (g_draw) { g_smsst[1]++; g_force = 0; } + g_smsst[0]++; g_smsst[3] = g_ms - t0; + psg_frame(); + frac += 683u; next_ms += 16u + frac / 1000u; frac %= 1000u; /* 16.68 ms */ + } + if (g_sms.cram_dirty) { if (!cram_ms) cram_ms = now ? now : 1; } + if (cram_ms && now - cram_ms > 3000u && now - last_in > 1000u) { cram_ms = 0; cram_store(); } + if (bl && !g_dimmed && g_set.dim < T_N && now - last_in > T_MS[g_set.dim]) { g_dimmed = 1; light(); } + if (bl && g_set.off < T_N && now - last_in > T_MS[g_set.off]) { bl = 0; hw_backlight(0); if (g_sms.cram_dirty) { cram_ms = 0; cram_store(); } } + if ((s32)(next_ms - g_ms) > 0) __asm__ volatile("wfi"); + } +} + +__attribute__((naked)) static void Default_Handler(void) { __asm__ volatile("1: b 1b\n"); } +__attribute__((naked)) static void Irq_Off(void) { __asm__ volatile("cpsid i\n bx lr\n"); } +__attribute__((section(".vectors"), used)) +const void *const g_vectors[16 + 64] = { (void *)0x18020000u, (void *)Reset_Handler, + [2 ... 10] = (void *)Default_Handler, [11] = (void *)Irq_Off, [12 ... 13] = (void *)Default_Handler, [14] = (void *)Irq_Off, + [15] = (void *)SysTick_Handler, [16 ... 79] = (void *)Irq_Off +}; diff --git a/sms/src/core/gen_z80.py b/sms/src/core/gen_z80.py new file mode 100644 index 0000000..3537c84 --- /dev/null +++ b/sms/src/core/gen_z80.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +# Generates z80_ops.inc (cases of the main opcode switch) and z80_fns.inc (CB, ED, DD/FD) for z80.h. +# Author: mameise +import os +R = ['B', 'C', 'D', 'E', 'H', 'L', None, 'A'] +ALU = ['z_add', 'z_adc', 'z_sub', 'z_sbc', 'z_and', 'z_xor', 'z_or', 'z_cp'] +CC = ['!(F & ZF)', '(F & ZF)', '!(F & CF)', '(F & CF)', '!(F & PF)', '(F & PF)', '!(F & SF)', '(F & SF)'] +RP = ['BC', 'DE', 'HL', 'SP'] +ROT = ['z_rlc', 'z_rrc', 'z_rl', 'z_rr', 'z_sla', 'z_sra', 'z_sll', 'z_srl'] +main = {} +def m(op, code, t): + assert op not in main, hex(op) + main[op] = (code, t) + +m(0x00, '', 4) +for i, rp in enumerate(RP): + b = i << 4 + m(b | 0x01, f'{rp} = z_imm16(z);', 10) + m(b | 0x03, f'{rp}++;', 6) + m(b | 0x0B, f'{rp}--;', 6) + m(b | 0x09, f'HL = z_add16(z, HL, {rp});', 11) +m(0x02, 'WR(BC, A); z->wz.b.l = (uint8_t)(BC + 1); z->wz.b.h = A;', 7) +m(0x12, 'WR(DE, A); z->wz.b.l = (uint8_t)(DE + 1); z->wz.b.h = A;', 7) +m(0x0A, 'A = RD(BC); WZ = (uint16_t)(BC + 1);', 7) +m(0x1A, 'A = RD(DE); WZ = (uint16_t)(DE + 1);', 7) +m(0x22, '{ uint16_t a = z_imm16(z); WR16(a, HL); WZ = (uint16_t)(a + 1); }', 16) +m(0x2A, '{ uint16_t a = z_imm16(z); HL = RD16(a); WZ = (uint16_t)(a + 1); }', 16) +m(0x32, '{ uint16_t a = z_imm16(z); WR(a, A); z->wz.b.l = (uint8_t)(a + 1); z->wz.b.h = A; }', 13) +m(0x3A, '{ uint16_t a = z_imm16(z); A = RD(a); WZ = (uint16_t)(a + 1); }', 13) +for i, r in enumerate(R): + if r is None: + m(0x34, '{ uint8_t v = RD(HL); WR(HL, z_inc(z, v)); }', 11) + m(0x35, '{ uint8_t v = RD(HL); WR(HL, z_dec(z, v)); }', 11) + m(0x36, '{ uint8_t v = IMM8(); WR(HL, v); }', 10) + continue + m(i << 3 | 4, f'{r} = z_inc(z, {r});', 4) + m(i << 3 | 5, f'{r} = z_dec(z, {r});', 4) + m(i << 3 | 6, f'{r} = IMM8();', 7) +m(0x07, 'A = (uint8_t)(A << 1 | A >> 7); F = (uint8_t)((F & (SF | ZF | PF)) | (A & (YF | XF | CF)));', 4) +m(0x0F, 'F = (uint8_t)((F & (SF | ZF | PF)) | (A & CF)); A = (uint8_t)(A >> 1 | A << 7); F |= (uint8_t)(A & (YF | XF));', 4) +m(0x17, '{ uint8_t r = (uint8_t)(A << 1 | (F & CF)); F = (uint8_t)((F & (SF | ZF | PF)) | (A >> 7) | (r & (YF | XF))); A = r; }', 4) +m(0x1F, '{ uint8_t r = (uint8_t)(A >> 1 | F << 7); F = (uint8_t)((F & (SF | ZF | PF)) | (A & CF) | (r & (YF | XF))); A = r; }', 4) +m(0x08, '{ uint16_t x = AF; AF = z->af2; z->af2 = x; }', 4) +m(0x10, '{ int8_t e = (int8_t)IMM8(); if (--B) { PC = (uint16_t)(PC + e); WZ = PC; t = 13; break; } }', 8) +m(0x18, '{ int8_t e = (int8_t)IMM8(); PC = (uint16_t)(PC + e); WZ = PC; }', 12) +for k in range(4): + m(0x20 | k << 3, f'{{ int8_t e = (int8_t)IMM8(); if ({CC[k]}) {{ PC = (uint16_t)(PC + e); WZ = PC; t = 12; break; }} }}', 7) +m(0x27, 'z_daa(z);', 4) +m(0x2F, 'A ^= 0xFF; F = (uint8_t)((F & (SF | ZF | PF | CF)) | HF | NF | (A & (YF | XF)));', 4) +m(0x37, 'F = (uint8_t)((F & (SF | ZF | PF)) | CF | (A & (YF | XF)));', 4) +m(0x3F, 'F = (uint8_t)(((F & (SF | ZF | PF | CF)) | ((F & CF) << 4) | (A & (YF | XF))) ^ CF);', 4) +for d in range(8): + for s in range(8): + op = 0x40 | d << 3 | s + if op == 0x76: + m(op, 'z->halt = 1;', 4); continue + if s == 6: m(op, f'{R[d]} = RD(HL);', 7) + elif d == 6: m(op, f'WR(HL, {R[s]});', 7) + else: m(op, '' if d == s else f'{R[d]} = {R[s]};', 4) +for k in range(8): + for s in range(8): + op = 0x80 | k << 3 | s + if s == 6: m(op, f'{ALU[k]}(z, RD(HL));', 7) + else: m(op, f'{ALU[k]}(z, {R[s]});', 4) + m(0xC6 | k << 3, f'{ALU[k]}(z, IMM8());', 7) + m(0xC7 | k << 3, f'z_push(z, PC); PC = 0x{k * 8:02X}; WZ = PC;', 11) + m(0xC0 | k << 3, f'if ({CC[k]}) {{ PC = z_pop(z); WZ = PC; t = 11; break; }}', 5) + m(0xC2 | k << 3, f'{{ uint16_t a = z_imm16(z); WZ = a; if ({CC[k]}) PC = a; }}', 10) + m(0xC4 | k << 3, f'{{ uint16_t a = z_imm16(z); WZ = a; if ({CC[k]}) {{ z_push(z, PC); PC = a; t = 17; break; }} }}', 10) +for i, rp in enumerate(['BC', 'DE', 'HL', 'AF']): + m(0xC1 | i << 4, f'{rp} = z_pop(z);', 10) + m(0xC5 | i << 4, f'z_push(z, {rp});', 11) +m(0xC3, 'PC = z_imm16(z); WZ = PC;', 10) +m(0xC9, 'PC = z_pop(z); WZ = PC;', 10) +m(0xCD, '{ uint16_t a = z_imm16(z); z_push(z, PC); PC = a; WZ = a; }', 17) +m(0xD3, '{ uint8_t n = IMM8(); Z_OUT((uint16_t)(n | A << 8), A); z->wz.b.l = (uint8_t)(n + 1); z->wz.b.h = A; }', 11) +m(0xDB, '{ uint16_t p = (uint16_t)(IMM8() | A << 8); A = Z_IN(p); WZ = (uint16_t)(p + 1); }', 11) +m(0xD9, '{ uint16_t x = BC; BC = z->bc2; z->bc2 = x; x = DE; DE = z->de2; z->de2 = x; x = HL; HL = z->hl2; z->hl2 = x; }', 4) +m(0xE3, '{ uint16_t v = RD16(SP); WR16(SP, HL); HL = v; WZ = v; }', 19) +m(0xE9, 'PC = HL;', 4) +m(0xEB, '{ uint16_t x = DE; DE = HL; HL = x; }', 4) +m(0xF3, 'z->iff1 = z->iff2 = 0;', 4) +m(0xFB, 'z->iff1 = z->iff2 = 1; z->ei = 1;', 4) +m(0xF9, 'SP = HL;', 6) +m(0xCB, 'op = z_fetch(z); t = z80_cb(z, op); break;', 0) +m(0xED, 'op = z_fetch(z); t = z80_ed(z, op); break;', 0) +m(0xDD, 'op = z_fetch(z); t = z80_xy(z, &z->ix.w, op); if (!t) { z->cyc -= 4; goto again; } break;', 0) +m(0xFD, 'op = z_fetch(z); t = z80_xy(z, &z->iy.w, op); if (!t) { z->cyc -= 4; goto again; } break;', 0) +assert len(main) == 256, len(main) + +out = [] +for op in range(256): + code, t = main[op] + if t: out.append(f'case 0x{op:02X}: t = {t}; {code} break;') + else: out.append(f'case 0x{op:02X}: {code}') +OUTD = os.path.dirname(os.path.abspath(__file__)) +open(os.path.join(OUTD, 'z80_ops.inc'), 'w').write('/* generated by gen_z80.py */\n' + '\n'.join(out) + '\n') + +# ---- CB ---- +f = ['/* generated by gen_z80.py */', 'static int z80_cb(Z80 *z, uint8_t op)', '{', ' switch (op) {'] +for op in range(256): + s = op & 7; r = R[s]; k = (op >> 3) & 7; g = op >> 6 + if g == 0: + if r: f.append(f' case 0x{op:02X}: {r} = {ROT[k]}(z, {r}); return 8;') + else: f.append(f' case 0x{op:02X}: {{ uint8_t v = RD(HL); WR(HL, {ROT[k]}(z, v)); }} return 15;') + elif g == 1: + if r: f.append(f' case 0x{op:02X}: z_bit(z, {k}, {r}); return 8;') + else: f.append(f' case 0x{op:02X}: z_bitm(z, {k}, RD(HL), z->wz.b.h); return 12;') + elif g == 2: + if r: f.append(f' case 0x{op:02X}: {r} &= (uint8_t)~{1 << k}; return 8;') + else: f.append(f' case 0x{op:02X}: {{ uint8_t v = RD(HL); WR(HL, v & (uint8_t)~{1 << k}); }} return 15;') + else: + if r: f.append(f' case 0x{op:02X}: {r} |= {1 << k}; return 8;') + else: f.append(f' case 0x{op:02X}: {{ uint8_t v = RD(HL); WR(HL, v | {1 << k}); }} return 15;') +f += [' }', ' return 8;', '}', ''] + +# ---- ED ---- +f += ['static int z80_ed(Z80 *z, uint8_t op)', '{', ' switch (op) {'] +for i, r in enumerate(R): + op = 0x40 | i << 3 + if r: f.append(f' case 0x{op:02X}: {r} = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[{r}]); WZ = (uint16_t)(BC + 1); return 12;') + else: f.append(f' case 0x{op:02X}: {{ uint8_t v = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[v]); WZ = (uint16_t)(BC + 1); }} return 12;') + f.append(f' case 0x{op | 1:02X}: Z_OUT(BC, {r if r else 0}); WZ = (uint16_t)(BC + 1); return 12;') +for i, rp in enumerate(RP): + b = 0x40 | i << 4 + f.append(f' case 0x{b | 2:02X}: z_sbc16(z, {rp}); return 15;') + f.append(f' case 0x{b | 0xA:02X}: z_adc16(z, {rp}); return 15;') + f.append(f' case 0x{b | 3:02X}: {{ uint16_t a = z_imm16(z); WR16(a, {rp}); WZ = (uint16_t)(a + 1); }} return 20;') + f.append(f' case 0x{b | 0xB:02X}: {{ uint16_t a = z_imm16(z); {rp} = RD16(a); WZ = (uint16_t)(a + 1); }} return 20;') +for op in (0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C): + f.append(f' case 0x{op:02X}: {{ uint8_t v = A; A = 0; z_sub(z, v); }} return 8;') +for op in (0x45, 0x4D, 0x55, 0x5D, 0x65, 0x6D, 0x75, 0x7D): + f.append(f' case 0x{op:02X}: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14;') +for op, im in ((0x46, 0), (0x4E, 0), (0x66, 0), (0x6E, 0), (0x56, 1), (0x76, 1), (0x5E, 2), (0x7E, 2)): + f.append(f' case 0x{op:02X}: z->im = {im}; return 8;') +f.append(' case 0x47: z->i = A; return 9;') +f.append(' case 0x4F: z->r = A; z->r7 = A; return 9;') +f.append(' case 0x57: A = z->i; F = (uint8_t)((F & CF) | zSZ[A] | (z->iff2 ? VF : 0)); return 9;') +f.append(' case 0x5F: A = (uint8_t)((z->r & 0x7F) | (z->r7 & 0x80)); F = (uint8_t)((F & CF) | zSZ[A] | (z->iff2 ? VF : 0)); return 9;') +f.append(' case 0x67: { uint8_t n = RD(HL); WR(HL, (uint8_t)(n >> 4 | A << 4)); A = (uint8_t)((A & 0xF0) | (n & 0x0F)); F = (uint8_t)((F & CF) | zSZP[A]); WZ = (uint16_t)(HL + 1); } return 18;') +f.append(' case 0x6F: { uint8_t n = RD(HL); WR(HL, (uint8_t)(n << 4 | (A & 0x0F))); A = (uint8_t)((A & 0xF0) | (n >> 4)); F = (uint8_t)((F & CF) | zSZP[A]); WZ = (uint16_t)(HL + 1); } return 18;') +f.append(' case 0xA0: z_ldi(z, 1); return 16;') +f.append(' case 0xA8: z_ldi(z, -1); return 16;') +f.append(' case 0xB0: z_ldi(z, 1); if (BC) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16;') +f.append(' case 0xB8: z_ldi(z, -1); if (BC) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16;') +f.append(' case 0xA1: z_cpi(z, 1); return 16;') +f.append(' case 0xA9: z_cpi(z, -1); return 16;') +f.append(' case 0xB1: z_cpi(z, 1); if (BC && !(F & ZF)) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16;') +f.append(' case 0xB9: z_cpi(z, -1); if (BC && !(F & ZF)) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16;') +f.append(' case 0xA2: z_ini(z, 1); return 16;') +f.append(' case 0xAA: z_ini(z, -1); return 16;') +f.append(' case 0xB2: z_ini(z, 1); if (B) { PC -= 2; return 21; } return 16;') +f.append(' case 0xBA: z_ini(z, -1); if (B) { PC -= 2; return 21; } return 16;') +f.append(' case 0xA3: z_outi(z, 1); return 16;') +f.append(' case 0xAB: z_outi(z, -1); return 16;') +f.append(' case 0xB3: z_outi(z, 1); if (B) { PC -= 2; return 21; } return 16;') +f.append(' case 0xBB: z_outi(z, -1); if (B) { PC -= 2; return 21; } return 16;') +f += [' }', ' return 8;', '}', ''] + +# ---- DD / FD ---- +XR = ['B', 'C', 'D', 'E', 'XH', 'XL', None, 'A'] +f += ['#define XY (*xy)', '#define XH (((uint8_t *)xy)[1])', '#define XL (((uint8_t *)xy)[0])', + '#define XA() (WZ = (uint16_t)(XY + (int8_t)IMM8()))', + 'static int z80_xy(Z80 *z, uint16_t *xy, uint8_t op)', '{', ' switch (op) {'] +for i, rp in enumerate(['BC', 'DE', 'XY', 'SP']): + f.append(f' case 0x{i << 4 | 9:02X}: XY = z_add16(z, XY, {rp}); return 15;') +f.append(' case 0x21: XY = z_imm16(z); return 14;') +f.append(' case 0x22: { uint16_t a = z_imm16(z); WR16(a, XY); WZ = (uint16_t)(a + 1); } return 20;') +f.append(' case 0x2A: { uint16_t a = z_imm16(z); XY = RD16(a); WZ = (uint16_t)(a + 1); } return 20;') +f.append(' case 0x23: XY++; return 10;') +f.append(' case 0x2B: XY--; return 10;') +f.append(' case 0x24: XH = z_inc(z, XH); return 8;') +f.append(' case 0x25: XH = z_dec(z, XH); return 8;') +f.append(' case 0x26: XH = IMM8(); return 11;') +f.append(' case 0x2C: XL = z_inc(z, XL); return 8;') +f.append(' case 0x2D: XL = z_dec(z, XL); return 8;') +f.append(' case 0x2E: XL = IMM8(); return 11;') +f.append(' case 0x34: { uint16_t a = XA(); uint8_t v = RD(a); WR(a, z_inc(z, v)); } return 23;') +f.append(' case 0x35: { uint16_t a = XA(); uint8_t v = RD(a); WR(a, z_dec(z, v)); } return 23;') +f.append(' case 0x36: { uint16_t a = XA(); uint8_t v = IMM8(); WR(a, v); } return 19;') +for d in range(8): + for s in range(8): + op = 0x40 | d << 3 | s + if op == 0x76: continue + if s == 6: f.append(f' case 0x{op:02X}: {R[d]} = RD(XA()); return 19;') + elif d == 6: f.append(f' case 0x{op:02X}: WR(XA(), {R[s]}); return 19;') + elif d in (4, 5) or s in (4, 5): + f.append(f' case 0x{op:02X}: {XR[d]} = {XR[s]}; return 8;') +for k in range(8): + for s in (4, 5, 6): + op = 0x80 | k << 3 | s + if s == 6: f.append(f' case 0x{op:02X}: {ALU[k]}(z, RD(XA())); return 19;') + else: f.append(f' case 0x{op:02X}: {ALU[k]}(z, {XR[s]}); return 8;') +f.append(' case 0xE1: XY = z_pop(z); return 14;') +f.append(' case 0xE5: z_push(z, XY); return 15;') +f.append(' case 0xE3: { uint16_t v = RD16(SP); WR16(SP, XY); XY = v; WZ = v; } return 23;') +f.append(' case 0xE9: PC = XY; return 8;') +f.append(' case 0xF9: SP = XY; return 10;') +f.append(''' case 0xCB: { + uint16_t a = XA(); uint8_t c = IMM8(), v = RD(a), g = c >> 6, k = (c >> 3) & 7, r; + if (g == 1) { z_bitm(z, k, v, (uint8_t)(a >> 8)); return 20; } + r = g == 0 ? z_rot(z, k, v) : g == 2 ? (uint8_t)(v & ~(1u << k)) : (uint8_t)(v | 1u << k); + WR(a, r); + switch (c & 7) { case 0: B = r; break; case 1: C = r; break; case 2: D = r; break; case 3: E = r; break; + case 4: H = r; break; case 5: L = r; break; case 7: A = r; break; default: break; } + return 23; }''') +f += [' }', ' return 0;', '}', '#undef XY', '#undef XH', '#undef XL', '#undef XA', ''] +open(os.path.join(OUTD, 'z80_fns.inc'), 'w').write('\n'.join(f) + '\n') diff --git a/sms/src/core/sms.h b/sms/src/core/sms.h new file mode 100644 index 0000000..f3579b0 --- /dev/null +++ b/sms/src/core/sms.h @@ -0,0 +1,310 @@ +/* SMSEmu: the Sega Master System (Z80, VDP mode 4, PSG registers, Sega mapper). Author: mameise. + * Header only, one machine. The includer defines before including: + * SMS_LINE(y, lb) a finished line: y 0..191, lb 256 colour numbers (0..31, see g_sms.pal565) + * and sets g_sms.rom / g_sms.rom_len (and g_sms.cram, cram_len for the cartridge RAM) before sms_reset(). + * The ROM is read in place (on the Paradise: the flash window). */ +#ifndef SMS_H +#define SMS_H +#include + +typedef struct { + const uint8_t *rom; uint32_t rom_len, banks; /* banks of 16 KB (power of two, mask banks - 1) */ + uint8_t *cram; uint32_t cram_len; int cram_dirty; /* cartridge RAM (battery), up to 32 KB */ + const uint8_t *rp[64]; /* read pages of 1 KB */ + uint8_t map[4]; /* FFFC..FFFF */ + uint8_t io_ctrl, pad, pause_in; /* pad: buttons held, active high (SMS_UP...) */ + /* VDP */ + uint8_t reg[16], status, latch, first, code, rbuf, vint, lint, vs_frame; + uint16_t addr; int lcount; int line; + uint8_t cramv[64]; uint16_t pal565[32]; + uint8_t gg, gg_latch; /* Game Gear: 12 bit colours in two bytes, START on port 0 */ + /* PSG */ + uint16_t tone[3]; uint8_t vol[4], noise, psg_latch, psg_on; + uint32_t frames; +} Sms; +#define SMS_UP 1u +#define SMS_DOWN 2u +#define SMS_LEFT 4u +#define SMS_RIGHT 8u +#define SMS_B1 16u +#define SMS_B2 32u +#define SMS_PAUSE 64u + +static Sms g_sms; +static uint8_t g_ram[0x2000] __attribute__((aligned(4))); +static uint8_t g_vram[0x4000] __attribute__((aligned(4))); +static uint32_t g_tc[512 * 8 * 2]; /* tiles decoded: per row 8 colour numbers (two words) */ +static uint32_t g_spread[256]; /* 8 bits to the low bit of 8 nibbles (bit 7 = first dot) */ +static uint8_t g_empty[0x400]; +static inline uint8_t SMS_RD(uint32_t a) { return g_sms.rp[a >> 10][a & 0x3FFu]; } +static inline void sms_wr(uint32_t a, uint8_t v); +static uint8_t sms_in(uint32_t p); +static void sms_out(uint32_t p, uint8_t v); +#define Z_RD(a) SMS_RD(a) +#define Z_WR(a, v) sms_wr((a), (v)) +#define Z_IN(p) sms_in(p) +#define Z_OUT(p, v) sms_out((p), (v)) +#include "z80.h" +static Z80 g_cpu; + +static void sms_pages(int slot) +{ + Sms *s = &g_sms; + if (slot == 2 && (s->map[0] & 8u) && s->cram) { + uint8_t *c = s->cram + ((s->map[0] & 4u) ? 0x4000u : 0u); + for (int p = 0; p < 16; p++) s->rp[32 + p] = c + p * 0x400; + return; + } + uint32_t b = s->map[1 + slot] & (s->banks - 1u), o = b * 0x4000u; + for (int p = slot == 0 ? 1 : 0; p < 16; p++) s->rp[slot * 16 + p] = o + p * 0x400u < s->rom_len ? s->rom + o + p * 0x400u : g_empty; +} +static void sms_mapper(uint32_t r, uint8_t v) +{ + Sms *s = &g_sms; + s->map[r] = v; + if (r == 0) sms_pages(2); else sms_pages((int)r - 1); +} + +static inline void sms_wr(uint32_t a, uint8_t v) +{ + if (a >= 0xC000u) { g_ram[a & 0x1FFFu] = v; if (a >= 0xFFFCu) sms_mapper(a & 3u, v); } + else if (a >= 0x8000u && (g_sms.map[0] & 8u) && g_sms.cram) { + uint32_t o = (a & 0x3FFFu) + ((g_sms.map[0] & 4u) ? 0x4000u : 0u); + if (o < g_sms.cram_len && g_sms.cram[o] != v) { g_sms.cram[o] = v; g_sms.cram_dirty |= 1 << (o >> 12); } + } +} + +/* ---- VDP ---- */ +static void vdp_irq(void) +{ + Sms *s = &g_sms; + g_cpu.irq = (uint8_t)(((s->status & 0x80u) && (s->reg[1] & 0x20u)) || (s->lint && (s->reg[0] & 0x10u))); +} +static void tc_row(uint32_t a) +{ + const uint8_t *v = &g_vram[a & 0x3FFCu]; + uint32_t t = (a & 0x3FFCu) >> 2, b0 = v[0], b1 = v[1], b2 = v[2], b3 = v[3]; + /* first four dots in the first word (byte 0 = first dot), next four in the second */ + uint32_t lo = 0, hi = 0; + uint32_t s0 = g_spread[b0], s1 = g_spread[b1], s2 = g_spread[b2], s3 = g_spread[b3]; + uint32_t n = s0 | s1 << 1 | s2 << 2 | s3 << 3; /* 8 nibbles: nibble k = dot k */ + lo = (n & 0xFu) | ((n >> 4) & 0xFu) << 8 | ((n >> 8) & 0xFu) << 16 | ((n >> 12) & 0xFu) << 24; + hi = ((n >> 16) & 0xFu) | ((n >> 20) & 0xFu) << 8 | ((n >> 24) & 0xFu) << 16 | ((n >> 28) & 0xFu) << 24; + g_tc[t * 2] = lo; g_tc[t * 2 + 1] = hi; +} +static void pal_gg(uint32_t i) /* Game Gear: ----BBBB GGGGRRRR, 4 bits each */ +{ + uint32_t lo = g_sms.cramv[i * 2u], hi = g_sms.cramv[i * 2u + 1u], r = lo & 15u, g = lo >> 4, b = hi & 15u; + g_sms.pal565[i] = (uint16_t)((r << 1 | r >> 3) << 11 | (g << 2 | g >> 2) << 5 | (b << 1 | b >> 3)); +} +static void pal_set(uint32_t i, uint8_t v) +{ + static const uint8_t c5[4] = { 0, 10, 21, 31 }, c6[4] = { 0, 21, 42, 63 }; + g_sms.cramv[i] = v; + g_sms.pal565[i] = (uint16_t)(c5[v & 3u] << 11 | c6[(v >> 2) & 3u] << 5 | c5[(v >> 4) & 3u]); +} +static void vdp_data_w(uint8_t v) +{ + Sms *s = &g_sms; + s->first = 0; + if (s->code == 3) { + if (s->gg) { uint32_t a = s->addr & 63u; if (!(a & 1u)) s->gg_latch = v; else { s->cramv[a - 1u] = s->gg_latch; s->cramv[a] = v; pal_gg(a >> 1); } } + else pal_set(s->addr & 31u, v); + } + else { uint32_t a = s->addr & 0x3FFFu; if (g_vram[a] != v) { g_vram[a] = v; tc_row(a); } } + s->rbuf = v; + s->addr = (uint16_t)((s->addr + 1u) & 0x3FFFu); +} +static uint8_t vdp_data_r(void) +{ + Sms *s = &g_sms; uint8_t r = s->rbuf; + s->first = 0; s->rbuf = g_vram[s->addr & 0x3FFFu]; s->addr = (uint16_t)((s->addr + 1u) & 0x3FFFu); + return r; +} +static void vdp_ctrl_w(uint8_t v) +{ + Sms *s = &g_sms; + if (!s->first) { s->first = 1; s->latch = v; s->addr = (uint16_t)((s->addr & 0x3F00u) | v); return; } + s->first = 0; + s->code = v >> 6; s->addr = (uint16_t)((v & 0x3Fu) << 8 | s->latch); + if (s->code == 0) { s->rbuf = g_vram[s->addr]; s->addr = (uint16_t)((s->addr + 1u) & 0x3FFFu); } + else if (s->code == 2) { s->reg[v & 15u] = s->latch; vdp_irq(); } +} +static uint8_t vdp_status_r(void) +{ + Sms *s = &g_sms; uint8_t r = (uint8_t)(s->status | 0x1Fu); + s->status = 0; s->lint = 0; s->first = 0; vdp_irq(); + return r; +} +static uint8_t vdp_vcount(void) +{ + int l = g_sms.line; + return (uint8_t)(l <= 0xDA ? l : l - 6); +} + +/* ---- PSG (only the registers: the Paradise plays one tone from them) ---- */ +static void psg_w(uint8_t v) +{ + Sms *s = &g_sms; + if (v & 0x80u) { + s->psg_latch = (uint8_t)((v >> 4) & 7u); + uint32_t ch = s->psg_latch >> 1; + if (s->psg_latch & 1u) s->vol[ch] = v & 15u; + else if (ch < 3) s->tone[ch] = (uint16_t)((s->tone[ch] & 0x3F0u) | (v & 15u)); + else s->noise = v & 7u; + } else { + uint32_t ch = s->psg_latch >> 1; + if (s->psg_latch & 1u) s->vol[ch] = v & 15u; + else if (ch < 3) s->tone[ch] = (uint16_t)((s->tone[ch] & 15u) | (v & 0x3Fu) << 4); + else s->noise = v & 7u; + } + s->psg_on = 1; +} + +/* ---- ports ---- */ +static uint8_t sms_in(uint32_t p) +{ + p &= 0xFFu; + if (p < 0x40u) { + if (g_sms.gg && p < 0x08u) { /* Game Gear: START (pressed = 0), export, NTSC; the link port idle */ + static const uint8_t lk[8] = { 0, 0x7F, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF }; + return p ? lk[p] : (uint8_t)(((g_sms.pad & SMS_PAUSE) ? 0 : 0x80u) | 0x40u); + } + return 0xFF; + } + if (p < 0x80u) return (p & 1u) ? (uint8_t)(((228 - g_cpu.cyc) * 171 / 228) & 0xFF) : vdp_vcount(); + if (p < 0xC0u) return (p & 1u) ? vdp_status_r() : vdp_data_r(); + if (!(p & 1u)) { uint32_t k = g_sms.pad; return (uint8_t)~(k & 0x3Fu); } + /* port DD: second pad not there, reset key up; TH lines as set by port 3F (export console) */ + uint8_t c = g_sms.io_ctrl, r = 0x3F; + r |= (c & 0x02u) ? 0x40u : (c & 0x20u) ? 0x40u : 0; + r |= (c & 0x08u) ? 0x80u : (c & 0x80u) ? 0x80u : 0; + return r; +} +static void sms_out(uint32_t p, uint8_t v) +{ + p &= 0xFFu; + if (p < 0x40u) { if (p & 1u) g_sms.io_ctrl = v; return; } + if (p < 0x80u) { psg_w(v); return; } + if (p < 0xC0u) { if (p & 1u) vdp_ctrl_w(v); else vdp_data_w(v); } +} + + +/* ---- one line: background and sprites into 256 colour numbers ---- */ +static uint8_t g_lb[256 + 16] __attribute__((aligned(4))); +static uint8_t g_sm[256 + 16]; +static void render_line(int y) +{ + Sms *s = &g_sms; uint8_t *r = s->reg; + uint8_t back = (uint8_t)(16u + (r[7] & 15u)); + if (!(r[1] & 0x40u)) { for (int x = 0; x < 256; x++) g_lb[x] = back; SMS_LINE(y, g_lb); return; } + /* background: 33 tiles from the column under the first dot, then shifted by the fine scroll */ + static uint32_t bg[66 + 2]; + uint32_t hs = ((r[0] & 0x40u) && y < 16) ? 0 : r[8]; + uint32_t bx0 = (256u - hs) & 255u, col0 = bx0 >> 3, off0 = bx0 & 7u; + uint32_t nt = (uint32_t)(r[2] & 0x0Eu) << 10; + uint32_t vy = (uint32_t)y + s->vs_frame; if (vy >= 224u) vy -= 224u; + for (int k = 0; k < 33; k++) { + uint32_t col = (col0 + (uint32_t)k) & 31u, row = vy; + if ((r[0] & 0x80u) && k - (off0 ? 1 : 0) >= 24) row = (uint32_t)y; + const uint8_t *e = &g_vram[nt + ((row >> 3) * 32u + col) * 2u]; + uint32_t t = e[0] | (uint32_t)(e[1] & 1u) << 8, fl = e[1], ty = row & 7u; + if (fl & 4u) ty = 7u - ty; + uint32_t lo = g_tc[(t * 8u + ty) * 2u], hi = g_tc[(t * 8u + ty) * 2u + 1u]; + if (fl & 2u) { uint32_t x = __builtin_bswap32(hi); hi = __builtin_bswap32(lo); lo = x; } + uint32_t add = ((fl & 8u) ? 0x10101010u : 0u); + if (fl & 0x10u) { /* priority over sprites where the dot is not colour 0 */ + uint32_t ml = lo | lo >> 1 | lo >> 2 | lo >> 3, mh = hi | hi >> 1 | hi >> 2 | hi >> 3; + lo |= (ml & 0x01010101u) << 6; hi |= (mh & 0x01010101u) << 6; + } + bg[k * 2] = lo | add; bg[k * 2 + 1] = hi | add; + } + const uint8_t *src = (const uint8_t *)bg + off0; + uint32_t *d = (uint32_t *)g_lb; + if (!off0) { for (int k = 0; k < 64; k++) d[k] = bg[k]; } + else for (int x = 0; x < 256; x++) g_lb[x] = src[x]; + /* sprites: the first eight on this line, the earlier one wins */ + uint32_t sat = (uint32_t)(r[5] & 0x7Eu) << 7, h = (r[1] & 2u) ? 16u : 8u, zoom = r[1] & 1u, pb = (r[6] & 4u) ? 256u : 0u; + uint32_t hh = h << zoom; + int n = 0, any = 0; + uint8_t idx[8]; + for (int i = 0; i < 64; i++) { + uint32_t sy = g_vram[sat + (uint32_t)i]; + if (sy == 0xD0u) break; + int ly = y - (int)sy - 1; if (ly < -16) ly += 256; + if (ly < 0 || ly >= (int)hh) continue; + if (n == 8) { s->status |= 0x40u; break; } + idx[n++] = (uint8_t)i; + } + for (int j = 0; j < n; j++) { + int i = idx[j]; + uint32_t sy = g_vram[sat + (uint32_t)i]; + int ly = y - (int)sy - 1; if (ly < -16) ly += 256; + ly >>= zoom; + int sx = g_vram[sat + 0x80u + (uint32_t)i * 2u]; if (r[0] & 8u) sx -= 8; + uint32_t t = g_vram[sat + 0x81u + (uint32_t)i * 2u]; if (h == 16u) t &= 0xFEu; + t = (t + pb + (uint32_t)(ly >> 3)) & 511u; + const uint8_t *px = (const uint8_t *)&g_tc[(t * 8u + (uint32_t)(ly & 7)) * 2u]; + if (!any) { for (int x = 0; x < 256; x++) g_sm[x] = 0; any = 1; } + for (int k = 0; k < (8 << zoom); k++) { + int x = sx + k; if (x < 0 || x >= 256) continue; + uint32_t c = px[k >> zoom]; if (!c) continue; + if (g_sm[x]) { s->status |= 0x20u; continue; } + g_sm[x] = 1; + uint8_t b = g_lb[x]; + if ((b & 0x40u) ) continue; + g_lb[x] = (uint8_t)(c | 16u); + } + } + if (r[0] & 0x20u) for (int x = 0; x < 8; x++) g_lb[x] = back; + for (int k = 0; k < 64; k++) d[k] &= 0x1F1F1F1Fu; + SMS_LINE(y, g_lb); +} + +/* ---- the machine ---- */ +static void sms_reset(void) +{ + Sms *s = &g_sms; + const uint8_t *rom = s->rom; uint32_t len = s->rom_len; uint8_t *cr = s->cram; uint32_t cl = s->cram_len; uint8_t gg = s->gg; + uint8_t *p = (uint8_t *)s; for (unsigned i = 0; i < sizeof *s; i++) p[i] = 0; + s->rom = rom; s->rom_len = len; s->cram = cr; s->cram_len = cl; s->gg = gg; + s->banks = 1; while (s->banks * 0x4000u < len) s->banks <<= 1; + for (int i = 0; i < 256; i++) { uint32_t v = 0; for (int k = 0; k < 8; k++) if (i & (0x80 >> k)) v |= 1u << (k * 4); g_spread[i] = v; } + for (unsigned i = 0; i < sizeof g_ram; i++) g_ram[i] = 0; + for (unsigned i = 0; i < sizeof g_vram; i++) g_vram[i] = 0; + for (unsigned i = 0; i < sizeof g_tc / 4; i++) g_tc[i] = 0; + for (unsigned i = 0; i < sizeof g_empty; i++) g_empty[i] = 0xFF; + for (int i = 0; i < 32; i++) pal_set((uint32_t)i, 0); + s->rp[0] = rom; + s->map[0] = 0; s->map[1] = 0; s->map[2] = 1; s->map[3] = 2; + sms_pages(0); sms_pages(1); sms_pages(2); + for (int i = 48; i < 64; i++) s->rp[i] = g_ram + (i & 7) * 0x400; + static const uint8_t r0[11] = { 0x36, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0x00, 0x00, 0x00, 0xFF }; + for (int i = 0; i < 11; i++) s->reg[i] = r0[i]; + s->lcount = 0xFF; + s->io_ctrl = 0xFF; + for (int i = 0; i < 4; i++) s->vol[i] = 15; + z80_tables(); z80_reset(&g_cpu); + g_cpu.sp.w = 0xDFF0; g_cpu.im = 1; +} + +/* one frame (NTSC: 262 lines of 228 cycles); draw: lines go to SMS_LINE */ +static void sms_frame(int draw) +{ + Sms *s = &g_sms; + static uint32_t pause_old; + if ((s->pad & SMS_PAUSE) && !pause_old && !s->gg) g_cpu.nmi = 1; + pause_old = s->pad & SMS_PAUSE; + s->vs_frame = s->reg[9]; + for (int y = 0; y < 262; y++) { + s->line = y; + if (y < 192 && draw) render_line(y); + if (y <= 192) { if (--s->lcount < 0) { s->lcount = s->reg[10]; s->lint = 1; vdp_irq(); } } + else s->lcount = s->reg[10]; + if (y == 193) { s->status |= 0x80u; vdp_irq(); } + z80_run(&g_cpu, 228); + } + s->frames++; +} + +#endif diff --git a/sms/src/core/z80.h b/sms/src/core/z80.h new file mode 100644 index 0000000..3298a98 --- /dev/null +++ b/sms/src/core/z80.h @@ -0,0 +1,210 @@ +/* Z80 interpreter for SMSEmu (Sega Master System on the Tamagotchi Paradise). Author: mameise. + * Header only: the includer defines the memory and port access first: + * Z_RD(a) read a byte (a is 16 bit) + * Z_WR(a, v) write a byte + * Z_IN(p) read a port (p: 16 bit, low byte is the port) + * Z_OUT(p, v) write a port + * Flags kept in F as on the chip (S Z Y H X P/V N C), tables for sign, zero and parity. + * The opcode cases are generated by gen_z80.py into z80_ops.inc. */ +#ifndef SMS_Z80_H +#define SMS_Z80_H +#include + +typedef union { uint16_t w; struct { uint8_t l, h; } b; } ZPair; +typedef struct { + ZPair af, bc, de, hl, ix, iy, sp, wz; + uint16_t pc, af2, bc2, de2, hl2; + uint8_t i, r, r7, im, iff1, iff2, halt, ei; + uint8_t irq; /* the INT line (held by the VDP) */ + uint8_t nmi; /* NMI pending (pause key) */ + int32_t cyc; /* cycles still to run */ +} Z80; + +#define CF 0x01 +#define NF 0x02 +#define PF 0x04 +#define VF 0x04 +#define XF 0x08 +#define HF 0x10 +#define YF 0x20 +#define ZF 0x40 +#define SF 0x80 + +static uint8_t zSZ[256], zSZP[256], zSZBIT[256], zINC[256], zDEC[256]; +static void z80_tables(void) +{ + for (int i = 0; i < 256; i++) { + int p = 0; for (int k = 0; k < 8; k++) p ^= (i >> k) & 1; + zSZ[i] = (uint8_t)((i ? i & SF : ZF) | (i & (YF | XF))); + zSZBIT[i] = (uint8_t)((i ? i & SF : ZF | PF) | (i & (YF | XF))); + zSZP[i] = (uint8_t)(zSZ[i] | (p ? 0 : PF)); + zINC[i] = (uint8_t)(zSZ[i] | (i == 0x80 ? VF : 0) | ((i & 0x0F) == 0 ? HF : 0)); + zDEC[i] = (uint8_t)(zSZ[i] | NF | (i == 0x7F ? VF : 0) | ((i & 0x0F) == 0x0F ? HF : 0)); + } +} + +#define A z->af.b.h +#define F z->af.b.l +#define B z->bc.b.h +#define C z->bc.b.l +#define D z->de.b.h +#define E z->de.b.l +#define H z->hl.b.h +#define L z->hl.b.l +#define AF z->af.w +#define BC z->bc.w +#define DE z->de.w +#define HL z->hl.w +#define SP z->sp.w +#define WZ z->wz.w +#define PC z->pc +#define RD(a) Z_RD((uint16_t)(a)) +#define WR(a, v) Z_WR((uint16_t)(a), (uint8_t)(v)) +#define IMM8() RD(PC++) +#define RD16(a) ((uint16_t)(RD(a) | RD((uint16_t)((a) + 1)) << 8)) +#define WR16(a, v) do { uint16_t a_ = (uint16_t)(a), v_ = (uint16_t)(v); WR(a_, v_ & 0xFF); WR((uint16_t)(a_ + 1), v_ >> 8); } while (0) + +static inline uint16_t z_imm16(Z80 *z) { uint16_t lo = IMM8(); uint16_t hi = IMM8(); return (uint16_t)(lo | hi << 8); } +static inline void z_push(Z80 *z, uint16_t v) { SP -= 2; WR16(SP, v); } +static inline uint16_t z_pop(Z80 *z) { uint16_t v = RD16(SP); SP += 2; return v; } + +static inline void z_add(Z80 *z, uint8_t v) { unsigned a = A, r = a + v; F = (uint8_t)(zSZ[r & 0xFF] | ((r >> 8) & CF) | ((a ^ r ^ v) & HF) | (((v ^ a ^ 0x80) & (v ^ r) & 0x80) >> 5)); A = (uint8_t)r; } +static inline void z_adc(Z80 *z, uint8_t v) { unsigned a = A, r = a + v + (F & CF); F = (uint8_t)(zSZ[r & 0xFF] | ((r >> 8) & CF) | ((a ^ r ^ v) & HF) | (((v ^ a ^ 0x80) & (v ^ r) & 0x80) >> 5)); A = (uint8_t)r; } +static inline void z_sub(Z80 *z, uint8_t v) { unsigned a = A, r = a - v; F = (uint8_t)(zSZ[r & 0xFF] | ((r >> 8) & CF) | NF | ((a ^ r ^ v) & HF) | (((v ^ a) & (a ^ r) & 0x80) >> 5)); A = (uint8_t)r; } +static inline void z_sbc(Z80 *z, uint8_t v) { unsigned a = A, r = a - v - (F & CF); F = (uint8_t)(zSZ[r & 0xFF] | ((r >> 8) & CF) | NF | ((a ^ r ^ v) & HF) | (((v ^ a) & (a ^ r) & 0x80) >> 5)); A = (uint8_t)r; } +static inline void z_cp(Z80 *z, uint8_t v) { unsigned a = A, r = a - v; F = (uint8_t)((zSZ[r & 0xFF] & (SF | ZF)) | (v & (YF | XF)) | ((r >> 8) & CF) | NF | ((a ^ r ^ v) & HF) | (((v ^ a) & (a ^ r) & 0x80) >> 5)); } +static inline void z_and(Z80 *z, uint8_t v) { A &= v; F = (uint8_t)(zSZP[A] | HF); } +static inline void z_or(Z80 *z, uint8_t v) { A |= v; F = zSZP[A]; } +static inline void z_xor(Z80 *z, uint8_t v) { A ^= v; F = zSZP[A]; } +static inline uint8_t z_inc(Z80 *z, uint8_t v) { v++; F = (uint8_t)((F & CF) | zINC[v]); return v; } +static inline uint8_t z_dec(Z80 *z, uint8_t v) { v--; F = (uint8_t)((F & CF) | zDEC[v]); return v; } +static inline uint16_t z_add16(Z80 *z, uint16_t a, uint16_t b) +{ + uint32_t r = (uint32_t)a + b; WZ = (uint16_t)(a + 1); + F = (uint8_t)((F & (SF | ZF | VF)) | (((a ^ r ^ b) >> 8) & HF) | ((r >> 16) & CF) | ((r >> 8) & (YF | XF))); + return (uint16_t)r; +} +static inline void z_adc16(Z80 *z, uint16_t b) +{ + uint32_t a = HL, r = a + b + (F & CF); WZ = (uint16_t)(a + 1); + F = (uint8_t)((((a ^ r ^ b) >> 8) & HF) | ((r >> 16) & CF) | ((r >> 8) & (SF | YF | XF)) | ((r & 0xFFFF) ? 0 : ZF) | (((b ^ a ^ 0x8000) & (b ^ r) & 0x8000) >> 13)); + HL = (uint16_t)r; +} +static inline void z_sbc16(Z80 *z, uint16_t b) +{ + uint32_t a = HL, r = a - b - (F & CF); WZ = (uint16_t)(a + 1); + F = (uint8_t)((((a ^ r ^ b) >> 8) & HF) | NF | ((r >> 16) & CF) | ((r >> 8) & (SF | YF | XF)) | ((r & 0xFFFF) ? 0 : ZF) | (((b ^ a) & (a ^ r) & 0x8000) >> 13)); + HL = (uint16_t)r; +} +static inline uint8_t z_rlc(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v << 1 | v >> 7); F = (uint8_t)(zSZP[r] | (v >> 7)); return r; } +static inline uint8_t z_rrc(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v >> 1 | v << 7); F = (uint8_t)(zSZP[r] | (v & 1)); return r; } +static inline uint8_t z_rl(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v << 1 | (F & CF)); F = (uint8_t)(zSZP[r] | (v >> 7)); return r; } +static inline uint8_t z_rr(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v >> 1 | (F & CF) << 7); F = (uint8_t)(zSZP[r] | (v & 1)); return r; } +static inline uint8_t z_sla(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v << 1); F = (uint8_t)(zSZP[r] | (v >> 7)); return r; } +static inline uint8_t z_sra(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v >> 1 | (v & 0x80)); F = (uint8_t)(zSZP[r] | (v & 1)); return r; } +static inline uint8_t z_sll(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v << 1 | 1); F = (uint8_t)(zSZP[r] | (v >> 7)); return r; } +static inline uint8_t z_srl(Z80 *z, uint8_t v) { uint8_t r = (uint8_t)(v >> 1); F = (uint8_t)(zSZP[r] | (v & 1)); return r; } +static inline void z_bit(Z80 *z, int b, uint8_t v) { F = (uint8_t)((F & CF) | HF | (zSZBIT[v & (1u << b)] & ~(YF | XF)) | (v & (YF | XF))); } +static inline void z_bitm(Z80 *z, int b, uint8_t v, uint8_t hi) { F = (uint8_t)((F & CF) | HF | (zSZBIT[v & (1u << b)] & ~(YF | XF)) | (hi & (YF | XF))); } +static inline uint8_t z_rot(Z80 *z, int k, uint8_t v) +{ + switch (k) { case 0: return z_rlc(z, v); case 1: return z_rrc(z, v); case 2: return z_rl(z, v); case 3: return z_rr(z, v); + case 4: return z_sla(z, v); case 5: return z_sra(z, v); case 6: return z_sll(z, v); default: return z_srl(z, v); } +} +static inline void z_daa(Z80 *z) +{ + uint8_t a = A; + if (F & NF) { if ((F & HF) || (A & 0x0F) > 9) a -= 6; if ((F & CF) || A > 0x99) a -= 0x60; } + else { if ((F & HF) || (A & 0x0F) > 9) a += 6; if ((F & CF) || A > 0x99) a += 0x60; } + F = (uint8_t)((F & (CF | NF)) | (A > 0x99 ? CF : 0) | ((A ^ a) & HF) | zSZP[a]); + A = a; +} +static inline void z_ldi(Z80 *z, int d) +{ + uint8_t v = RD(HL); WR(DE, v); HL += d; DE += d; BC--; + uint8_t n = (uint8_t)(v + A); + F = (uint8_t)((F & (SF | ZF | CF)) | (n & XF) | ((n << 4) & YF) | (BC ? VF : 0)); +} +static inline void z_cpi(Z80 *z, int d) +{ + uint8_t v = RD(HL), r = (uint8_t)(A - v); HL += d; BC--; WZ += d; + F = (uint8_t)((F & CF) | (zSZ[r] & ~(YF | XF)) | ((A ^ v ^ r) & HF) | NF); + if (F & HF) r--; + F |= (uint8_t)((r & XF) | ((r << 4) & YF) | (BC ? VF : 0)); +} +static inline void z_ini(Z80 *z, int d) +{ + uint8_t t = Z_IN(BC); WZ = (uint16_t)(BC + d); B--; WR(HL, t); HL += d; + unsigned t2 = t + (uint8_t)(C + d); + F = (uint8_t)(zSZ[B] | ((t & SF) ? NF : 0) | ((t2 & 0x100) ? HF | CF : 0) | (zSZP[(uint8_t)((t2 & 7) ^ B)] & PF)); +} +static inline void z_outi(Z80 *z, int d) +{ + uint8_t t = RD(HL); B--; WZ = (uint16_t)(BC + d); Z_OUT(BC, t); HL += d; + unsigned t2 = t + L; + F = (uint8_t)(zSZ[B] | ((t & SF) ? NF : 0) | ((t2 & 0x100) ? HF | CF : 0) | (zSZP[(uint8_t)((t2 & 7) ^ B)] & PF)); +} + +static void z80_reset(Z80 *z) +{ + uint8_t *p = (uint8_t *)z; for (unsigned i = 0; i < sizeof *z; i++) p[i] = 0; + AF = 0xFFFF; SP = 0xFFFF; z->ix.w = z->iy.w = 0xFFFF; +} + +/* DD and FD: the ones that use HL, H, L or (HL) take IX / IY. Returns the cycles, or 0: run the opcode plainly + * (4 cycles more). */ +static int z80_xy(Z80 *z, uint16_t *xy, uint8_t op); +static int z80_ed(Z80 *z, uint8_t op); +static int z80_cb(Z80 *z, uint8_t op); + +static inline uint8_t z_fetch(Z80 *z) { z->r++; return IMM8(); } + +/* run until the cycles are used up (z->cyc += n first) */ +static void z80_run(Z80 *z, int32_t n) +{ + z->cyc += n; + while (z->cyc > 0) { + if (z->ei) z->ei = 0; + else if (z->nmi) { + z->nmi = 0; z->halt = 0; z->iff1 = 0; z->r++; + z_push(z, PC); PC = 0x66; WZ = PC; z->cyc -= 11; + } else if (z->irq && z->iff1) { + z->halt = 0; z->iff1 = z->iff2 = 0; z->r++; + z_push(z, PC); + if (z->im == 2) { PC = RD16((uint16_t)(z->i << 8 | 0xFF)); z->cyc -= 19; } + else { PC = 0x38; z->cyc -= 13; } + WZ = PC; + } + if (z->halt) { int32_t k = (z->cyc + 3) >> 2; z->r = (uint8_t)(z->r + k); z->cyc -= k << 2; break; } + uint8_t op = z_fetch(z); + int t; + again: + switch (op) { +#include "z80_ops.inc" + } + z->cyc -= t; + } +} +#include "z80_fns.inc" +#undef A +#undef F +#undef B +#undef C +#undef D +#undef E +#undef H +#undef L +#undef AF +#undef BC +#undef DE +#undef HL +#undef SP +#undef WZ +#undef PC +#undef RD +#undef WR +#undef IMM8 +#undef RD16 +#undef WR16 + +#endif diff --git a/sms/src/core/z80_fns.inc b/sms/src/core/z80_fns.inc new file mode 100644 index 0000000..0fcbdc4 --- /dev/null +++ b/sms/src/core/z80_fns.inc @@ -0,0 +1,457 @@ +/* generated by gen_z80.py */ +static int z80_cb(Z80 *z, uint8_t op) +{ + switch (op) { + case 0x00: B = z_rlc(z, B); return 8; + case 0x01: C = z_rlc(z, C); return 8; + case 0x02: D = z_rlc(z, D); return 8; + case 0x03: E = z_rlc(z, E); return 8; + case 0x04: H = z_rlc(z, H); return 8; + case 0x05: L = z_rlc(z, L); return 8; + case 0x06: { uint8_t v = RD(HL); WR(HL, z_rlc(z, v)); } return 15; + case 0x07: A = z_rlc(z, A); return 8; + case 0x08: B = z_rrc(z, B); return 8; + case 0x09: C = z_rrc(z, C); return 8; + case 0x0A: D = z_rrc(z, D); return 8; + case 0x0B: E = z_rrc(z, E); return 8; + case 0x0C: H = z_rrc(z, H); return 8; + case 0x0D: L = z_rrc(z, L); return 8; + case 0x0E: { uint8_t v = RD(HL); WR(HL, z_rrc(z, v)); } return 15; + case 0x0F: A = z_rrc(z, A); return 8; + case 0x10: B = z_rl(z, B); return 8; + case 0x11: C = z_rl(z, C); return 8; + case 0x12: D = z_rl(z, D); return 8; + case 0x13: E = z_rl(z, E); return 8; + case 0x14: H = z_rl(z, H); return 8; + case 0x15: L = z_rl(z, L); return 8; + case 0x16: { uint8_t v = RD(HL); WR(HL, z_rl(z, v)); } return 15; + case 0x17: A = z_rl(z, A); return 8; + case 0x18: B = z_rr(z, B); return 8; + case 0x19: C = z_rr(z, C); return 8; + case 0x1A: D = z_rr(z, D); return 8; + case 0x1B: E = z_rr(z, E); return 8; + case 0x1C: H = z_rr(z, H); return 8; + case 0x1D: L = z_rr(z, L); return 8; + case 0x1E: { uint8_t v = RD(HL); WR(HL, z_rr(z, v)); } return 15; + case 0x1F: A = z_rr(z, A); return 8; + case 0x20: B = z_sla(z, B); return 8; + case 0x21: C = z_sla(z, C); return 8; + case 0x22: D = z_sla(z, D); return 8; + case 0x23: E = z_sla(z, E); return 8; + case 0x24: H = z_sla(z, H); return 8; + case 0x25: L = z_sla(z, L); return 8; + case 0x26: { uint8_t v = RD(HL); WR(HL, z_sla(z, v)); } return 15; + case 0x27: A = z_sla(z, A); return 8; + case 0x28: B = z_sra(z, B); return 8; + case 0x29: C = z_sra(z, C); return 8; + case 0x2A: D = z_sra(z, D); return 8; + case 0x2B: E = z_sra(z, E); return 8; + case 0x2C: H = z_sra(z, H); return 8; + case 0x2D: L = z_sra(z, L); return 8; + case 0x2E: { uint8_t v = RD(HL); WR(HL, z_sra(z, v)); } return 15; + case 0x2F: A = z_sra(z, A); return 8; + case 0x30: B = z_sll(z, B); return 8; + case 0x31: C = z_sll(z, C); return 8; + case 0x32: D = z_sll(z, D); return 8; + case 0x33: E = z_sll(z, E); return 8; + case 0x34: H = z_sll(z, H); return 8; + case 0x35: L = z_sll(z, L); return 8; + case 0x36: { uint8_t v = RD(HL); WR(HL, z_sll(z, v)); } return 15; + case 0x37: A = z_sll(z, A); return 8; + case 0x38: B = z_srl(z, B); return 8; + case 0x39: C = z_srl(z, C); return 8; + case 0x3A: D = z_srl(z, D); return 8; + case 0x3B: E = z_srl(z, E); return 8; + case 0x3C: H = z_srl(z, H); return 8; + case 0x3D: L = z_srl(z, L); return 8; + case 0x3E: { uint8_t v = RD(HL); WR(HL, z_srl(z, v)); } return 15; + case 0x3F: A = z_srl(z, A); return 8; + case 0x40: z_bit(z, 0, B); return 8; + case 0x41: z_bit(z, 0, C); return 8; + case 0x42: z_bit(z, 0, D); return 8; + case 0x43: z_bit(z, 0, E); return 8; + case 0x44: z_bit(z, 0, H); return 8; + case 0x45: z_bit(z, 0, L); return 8; + case 0x46: z_bitm(z, 0, RD(HL), z->wz.b.h); return 12; + case 0x47: z_bit(z, 0, A); return 8; + case 0x48: z_bit(z, 1, B); return 8; + case 0x49: z_bit(z, 1, C); return 8; + case 0x4A: z_bit(z, 1, D); return 8; + case 0x4B: z_bit(z, 1, E); return 8; + case 0x4C: z_bit(z, 1, H); return 8; + case 0x4D: z_bit(z, 1, L); return 8; + case 0x4E: z_bitm(z, 1, RD(HL), z->wz.b.h); return 12; + case 0x4F: z_bit(z, 1, A); return 8; + case 0x50: z_bit(z, 2, B); return 8; + case 0x51: z_bit(z, 2, C); return 8; + case 0x52: z_bit(z, 2, D); return 8; + case 0x53: z_bit(z, 2, E); return 8; + case 0x54: z_bit(z, 2, H); return 8; + case 0x55: z_bit(z, 2, L); return 8; + case 0x56: z_bitm(z, 2, RD(HL), z->wz.b.h); return 12; + case 0x57: z_bit(z, 2, A); return 8; + case 0x58: z_bit(z, 3, B); return 8; + case 0x59: z_bit(z, 3, C); return 8; + case 0x5A: z_bit(z, 3, D); return 8; + case 0x5B: z_bit(z, 3, E); return 8; + case 0x5C: z_bit(z, 3, H); return 8; + case 0x5D: z_bit(z, 3, L); return 8; + case 0x5E: z_bitm(z, 3, RD(HL), z->wz.b.h); return 12; + case 0x5F: z_bit(z, 3, A); return 8; + case 0x60: z_bit(z, 4, B); return 8; + case 0x61: z_bit(z, 4, C); return 8; + case 0x62: z_bit(z, 4, D); return 8; + case 0x63: z_bit(z, 4, E); return 8; + case 0x64: z_bit(z, 4, H); return 8; + case 0x65: z_bit(z, 4, L); return 8; + case 0x66: z_bitm(z, 4, RD(HL), z->wz.b.h); return 12; + case 0x67: z_bit(z, 4, A); return 8; + case 0x68: z_bit(z, 5, B); return 8; + case 0x69: z_bit(z, 5, C); return 8; + case 0x6A: z_bit(z, 5, D); return 8; + case 0x6B: z_bit(z, 5, E); return 8; + case 0x6C: z_bit(z, 5, H); return 8; + case 0x6D: z_bit(z, 5, L); return 8; + case 0x6E: z_bitm(z, 5, RD(HL), z->wz.b.h); return 12; + case 0x6F: z_bit(z, 5, A); return 8; + case 0x70: z_bit(z, 6, B); return 8; + case 0x71: z_bit(z, 6, C); return 8; + case 0x72: z_bit(z, 6, D); return 8; + case 0x73: z_bit(z, 6, E); return 8; + case 0x74: z_bit(z, 6, H); return 8; + case 0x75: z_bit(z, 6, L); return 8; + case 0x76: z_bitm(z, 6, RD(HL), z->wz.b.h); return 12; + case 0x77: z_bit(z, 6, A); return 8; + case 0x78: z_bit(z, 7, B); return 8; + case 0x79: z_bit(z, 7, C); return 8; + case 0x7A: z_bit(z, 7, D); return 8; + case 0x7B: z_bit(z, 7, E); return 8; + case 0x7C: z_bit(z, 7, H); return 8; + case 0x7D: z_bit(z, 7, L); return 8; + case 0x7E: z_bitm(z, 7, RD(HL), z->wz.b.h); return 12; + case 0x7F: z_bit(z, 7, A); return 8; + case 0x80: B &= (uint8_t)~1; return 8; + case 0x81: C &= (uint8_t)~1; return 8; + case 0x82: D &= (uint8_t)~1; return 8; + case 0x83: E &= (uint8_t)~1; return 8; + case 0x84: H &= (uint8_t)~1; return 8; + case 0x85: L &= (uint8_t)~1; return 8; + case 0x86: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~1); } return 15; + case 0x87: A &= (uint8_t)~1; return 8; + case 0x88: B &= (uint8_t)~2; return 8; + case 0x89: C &= (uint8_t)~2; return 8; + case 0x8A: D &= (uint8_t)~2; return 8; + case 0x8B: E &= (uint8_t)~2; return 8; + case 0x8C: H &= (uint8_t)~2; return 8; + case 0x8D: L &= (uint8_t)~2; return 8; + case 0x8E: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~2); } return 15; + case 0x8F: A &= (uint8_t)~2; return 8; + case 0x90: B &= (uint8_t)~4; return 8; + case 0x91: C &= (uint8_t)~4; return 8; + case 0x92: D &= (uint8_t)~4; return 8; + case 0x93: E &= (uint8_t)~4; return 8; + case 0x94: H &= (uint8_t)~4; return 8; + case 0x95: L &= (uint8_t)~4; return 8; + case 0x96: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~4); } return 15; + case 0x97: A &= (uint8_t)~4; return 8; + case 0x98: B &= (uint8_t)~8; return 8; + case 0x99: C &= (uint8_t)~8; return 8; + case 0x9A: D &= (uint8_t)~8; return 8; + case 0x9B: E &= (uint8_t)~8; return 8; + case 0x9C: H &= (uint8_t)~8; return 8; + case 0x9D: L &= (uint8_t)~8; return 8; + case 0x9E: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~8); } return 15; + case 0x9F: A &= (uint8_t)~8; return 8; + case 0xA0: B &= (uint8_t)~16; return 8; + case 0xA1: C &= (uint8_t)~16; return 8; + case 0xA2: D &= (uint8_t)~16; return 8; + case 0xA3: E &= (uint8_t)~16; return 8; + case 0xA4: H &= (uint8_t)~16; return 8; + case 0xA5: L &= (uint8_t)~16; return 8; + case 0xA6: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~16); } return 15; + case 0xA7: A &= (uint8_t)~16; return 8; + case 0xA8: B &= (uint8_t)~32; return 8; + case 0xA9: C &= (uint8_t)~32; return 8; + case 0xAA: D &= (uint8_t)~32; return 8; + case 0xAB: E &= (uint8_t)~32; return 8; + case 0xAC: H &= (uint8_t)~32; return 8; + case 0xAD: L &= (uint8_t)~32; return 8; + case 0xAE: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~32); } return 15; + case 0xAF: A &= (uint8_t)~32; return 8; + case 0xB0: B &= (uint8_t)~64; return 8; + case 0xB1: C &= (uint8_t)~64; return 8; + case 0xB2: D &= (uint8_t)~64; return 8; + case 0xB3: E &= (uint8_t)~64; return 8; + case 0xB4: H &= (uint8_t)~64; return 8; + case 0xB5: L &= (uint8_t)~64; return 8; + case 0xB6: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~64); } return 15; + case 0xB7: A &= (uint8_t)~64; return 8; + case 0xB8: B &= (uint8_t)~128; return 8; + case 0xB9: C &= (uint8_t)~128; return 8; + case 0xBA: D &= (uint8_t)~128; return 8; + case 0xBB: E &= (uint8_t)~128; return 8; + case 0xBC: H &= (uint8_t)~128; return 8; + case 0xBD: L &= (uint8_t)~128; return 8; + case 0xBE: { uint8_t v = RD(HL); WR(HL, v & (uint8_t)~128); } return 15; + case 0xBF: A &= (uint8_t)~128; return 8; + case 0xC0: B |= 1; return 8; + case 0xC1: C |= 1; return 8; + case 0xC2: D |= 1; return 8; + case 0xC3: E |= 1; return 8; + case 0xC4: H |= 1; return 8; + case 0xC5: L |= 1; return 8; + case 0xC6: { uint8_t v = RD(HL); WR(HL, v | 1); } return 15; + case 0xC7: A |= 1; return 8; + case 0xC8: B |= 2; return 8; + case 0xC9: C |= 2; return 8; + case 0xCA: D |= 2; return 8; + case 0xCB: E |= 2; return 8; + case 0xCC: H |= 2; return 8; + case 0xCD: L |= 2; return 8; + case 0xCE: { uint8_t v = RD(HL); WR(HL, v | 2); } return 15; + case 0xCF: A |= 2; return 8; + case 0xD0: B |= 4; return 8; + case 0xD1: C |= 4; return 8; + case 0xD2: D |= 4; return 8; + case 0xD3: E |= 4; return 8; + case 0xD4: H |= 4; return 8; + case 0xD5: L |= 4; return 8; + case 0xD6: { uint8_t v = RD(HL); WR(HL, v | 4); } return 15; + case 0xD7: A |= 4; return 8; + case 0xD8: B |= 8; return 8; + case 0xD9: C |= 8; return 8; + case 0xDA: D |= 8; return 8; + case 0xDB: E |= 8; return 8; + case 0xDC: H |= 8; return 8; + case 0xDD: L |= 8; return 8; + case 0xDE: { uint8_t v = RD(HL); WR(HL, v | 8); } return 15; + case 0xDF: A |= 8; return 8; + case 0xE0: B |= 16; return 8; + case 0xE1: C |= 16; return 8; + case 0xE2: D |= 16; return 8; + case 0xE3: E |= 16; return 8; + case 0xE4: H |= 16; return 8; + case 0xE5: L |= 16; return 8; + case 0xE6: { uint8_t v = RD(HL); WR(HL, v | 16); } return 15; + case 0xE7: A |= 16; return 8; + case 0xE8: B |= 32; return 8; + case 0xE9: C |= 32; return 8; + case 0xEA: D |= 32; return 8; + case 0xEB: E |= 32; return 8; + case 0xEC: H |= 32; return 8; + case 0xED: L |= 32; return 8; + case 0xEE: { uint8_t v = RD(HL); WR(HL, v | 32); } return 15; + case 0xEF: A |= 32; return 8; + case 0xF0: B |= 64; return 8; + case 0xF1: C |= 64; return 8; + case 0xF2: D |= 64; return 8; + case 0xF3: E |= 64; return 8; + case 0xF4: H |= 64; return 8; + case 0xF5: L |= 64; return 8; + case 0xF6: { uint8_t v = RD(HL); WR(HL, v | 64); } return 15; + case 0xF7: A |= 64; return 8; + case 0xF8: B |= 128; return 8; + case 0xF9: C |= 128; return 8; + case 0xFA: D |= 128; return 8; + case 0xFB: E |= 128; return 8; + case 0xFC: H |= 128; return 8; + case 0xFD: L |= 128; return 8; + case 0xFE: { uint8_t v = RD(HL); WR(HL, v | 128); } return 15; + case 0xFF: A |= 128; return 8; + } + return 8; +} + +static int z80_ed(Z80 *z, uint8_t op) +{ + switch (op) { + case 0x40: B = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[B]); WZ = (uint16_t)(BC + 1); return 12; + case 0x41: Z_OUT(BC, B); WZ = (uint16_t)(BC + 1); return 12; + case 0x48: C = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[C]); WZ = (uint16_t)(BC + 1); return 12; + case 0x49: Z_OUT(BC, C); WZ = (uint16_t)(BC + 1); return 12; + case 0x50: D = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[D]); WZ = (uint16_t)(BC + 1); return 12; + case 0x51: Z_OUT(BC, D); WZ = (uint16_t)(BC + 1); return 12; + case 0x58: E = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[E]); WZ = (uint16_t)(BC + 1); return 12; + case 0x59: Z_OUT(BC, E); WZ = (uint16_t)(BC + 1); return 12; + case 0x60: H = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[H]); WZ = (uint16_t)(BC + 1); return 12; + case 0x61: Z_OUT(BC, H); WZ = (uint16_t)(BC + 1); return 12; + case 0x68: L = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[L]); WZ = (uint16_t)(BC + 1); return 12; + case 0x69: Z_OUT(BC, L); WZ = (uint16_t)(BC + 1); return 12; + case 0x70: { uint8_t v = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[v]); WZ = (uint16_t)(BC + 1); } return 12; + case 0x71: Z_OUT(BC, 0); WZ = (uint16_t)(BC + 1); return 12; + case 0x78: A = Z_IN(BC); F = (uint8_t)((F & CF) | zSZP[A]); WZ = (uint16_t)(BC + 1); return 12; + case 0x79: Z_OUT(BC, A); WZ = (uint16_t)(BC + 1); return 12; + case 0x42: z_sbc16(z, BC); return 15; + case 0x4A: z_adc16(z, BC); return 15; + case 0x43: { uint16_t a = z_imm16(z); WR16(a, BC); WZ = (uint16_t)(a + 1); } return 20; + case 0x4B: { uint16_t a = z_imm16(z); BC = RD16(a); WZ = (uint16_t)(a + 1); } return 20; + case 0x52: z_sbc16(z, DE); return 15; + case 0x5A: z_adc16(z, DE); return 15; + case 0x53: { uint16_t a = z_imm16(z); WR16(a, DE); WZ = (uint16_t)(a + 1); } return 20; + case 0x5B: { uint16_t a = z_imm16(z); DE = RD16(a); WZ = (uint16_t)(a + 1); } return 20; + case 0x62: z_sbc16(z, HL); return 15; + case 0x6A: z_adc16(z, HL); return 15; + case 0x63: { uint16_t a = z_imm16(z); WR16(a, HL); WZ = (uint16_t)(a + 1); } return 20; + case 0x6B: { uint16_t a = z_imm16(z); HL = RD16(a); WZ = (uint16_t)(a + 1); } return 20; + case 0x72: z_sbc16(z, SP); return 15; + case 0x7A: z_adc16(z, SP); return 15; + case 0x73: { uint16_t a = z_imm16(z); WR16(a, SP); WZ = (uint16_t)(a + 1); } return 20; + case 0x7B: { uint16_t a = z_imm16(z); SP = RD16(a); WZ = (uint16_t)(a + 1); } return 20; + case 0x44: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x4C: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x54: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x5C: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x64: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x6C: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x74: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x7C: { uint8_t v = A; A = 0; z_sub(z, v); } return 8; + case 0x45: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x4D: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x55: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x5D: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x65: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x6D: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x75: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x7D: PC = z_pop(z); WZ = PC; z->iff1 = z->iff2; return 14; + case 0x46: z->im = 0; return 8; + case 0x4E: z->im = 0; return 8; + case 0x66: z->im = 0; return 8; + case 0x6E: z->im = 0; return 8; + case 0x56: z->im = 1; return 8; + case 0x76: z->im = 1; return 8; + case 0x5E: z->im = 2; return 8; + case 0x7E: z->im = 2; return 8; + case 0x47: z->i = A; return 9; + case 0x4F: z->r = A; z->r7 = A; return 9; + case 0x57: A = z->i; F = (uint8_t)((F & CF) | zSZ[A] | (z->iff2 ? VF : 0)); return 9; + case 0x5F: A = (uint8_t)((z->r & 0x7F) | (z->r7 & 0x80)); F = (uint8_t)((F & CF) | zSZ[A] | (z->iff2 ? VF : 0)); return 9; + case 0x67: { uint8_t n = RD(HL); WR(HL, (uint8_t)(n >> 4 | A << 4)); A = (uint8_t)((A & 0xF0) | (n & 0x0F)); F = (uint8_t)((F & CF) | zSZP[A]); WZ = (uint16_t)(HL + 1); } return 18; + case 0x6F: { uint8_t n = RD(HL); WR(HL, (uint8_t)(n << 4 | (A & 0x0F))); A = (uint8_t)((A & 0xF0) | (n >> 4)); F = (uint8_t)((F & CF) | zSZP[A]); WZ = (uint16_t)(HL + 1); } return 18; + case 0xA0: z_ldi(z, 1); return 16; + case 0xA8: z_ldi(z, -1); return 16; + case 0xB0: z_ldi(z, 1); if (BC) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16; + case 0xB8: z_ldi(z, -1); if (BC) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16; + case 0xA1: z_cpi(z, 1); return 16; + case 0xA9: z_cpi(z, -1); return 16; + case 0xB1: z_cpi(z, 1); if (BC && !(F & ZF)) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16; + case 0xB9: z_cpi(z, -1); if (BC && !(F & ZF)) { PC -= 2; WZ = (uint16_t)(PC + 1); return 21; } return 16; + case 0xA2: z_ini(z, 1); return 16; + case 0xAA: z_ini(z, -1); return 16; + case 0xB2: z_ini(z, 1); if (B) { PC -= 2; return 21; } return 16; + case 0xBA: z_ini(z, -1); if (B) { PC -= 2; return 21; } return 16; + case 0xA3: z_outi(z, 1); return 16; + case 0xAB: z_outi(z, -1); return 16; + case 0xB3: z_outi(z, 1); if (B) { PC -= 2; return 21; } return 16; + case 0xBB: z_outi(z, -1); if (B) { PC -= 2; return 21; } return 16; + } + return 8; +} + +#define XY (*xy) +#define XH (((uint8_t *)xy)[1]) +#define XL (((uint8_t *)xy)[0]) +#define XA() (WZ = (uint16_t)(XY + (int8_t)IMM8())) +static int z80_xy(Z80 *z, uint16_t *xy, uint8_t op) +{ + switch (op) { + case 0x09: XY = z_add16(z, XY, BC); return 15; + case 0x19: XY = z_add16(z, XY, DE); return 15; + case 0x29: XY = z_add16(z, XY, XY); return 15; + case 0x39: XY = z_add16(z, XY, SP); return 15; + case 0x21: XY = z_imm16(z); return 14; + case 0x22: { uint16_t a = z_imm16(z); WR16(a, XY); WZ = (uint16_t)(a + 1); } return 20; + case 0x2A: { uint16_t a = z_imm16(z); XY = RD16(a); WZ = (uint16_t)(a + 1); } return 20; + case 0x23: XY++; return 10; + case 0x2B: XY--; return 10; + case 0x24: XH = z_inc(z, XH); return 8; + case 0x25: XH = z_dec(z, XH); return 8; + case 0x26: XH = IMM8(); return 11; + case 0x2C: XL = z_inc(z, XL); return 8; + case 0x2D: XL = z_dec(z, XL); return 8; + case 0x2E: XL = IMM8(); return 11; + case 0x34: { uint16_t a = XA(); uint8_t v = RD(a); WR(a, z_inc(z, v)); } return 23; + case 0x35: { uint16_t a = XA(); uint8_t v = RD(a); WR(a, z_dec(z, v)); } return 23; + case 0x36: { uint16_t a = XA(); uint8_t v = IMM8(); WR(a, v); } return 19; + case 0x44: B = XH; return 8; + case 0x45: B = XL; return 8; + case 0x46: B = RD(XA()); return 19; + case 0x4C: C = XH; return 8; + case 0x4D: C = XL; return 8; + case 0x4E: C = RD(XA()); return 19; + case 0x54: D = XH; return 8; + case 0x55: D = XL; return 8; + case 0x56: D = RD(XA()); return 19; + case 0x5C: E = XH; return 8; + case 0x5D: E = XL; return 8; + case 0x5E: E = RD(XA()); return 19; + case 0x60: XH = B; return 8; + case 0x61: XH = C; return 8; + case 0x62: XH = D; return 8; + case 0x63: XH = E; return 8; + case 0x64: XH = XH; return 8; + case 0x65: XH = XL; return 8; + case 0x66: H = RD(XA()); return 19; + case 0x67: XH = A; return 8; + case 0x68: XL = B; return 8; + case 0x69: XL = C; return 8; + case 0x6A: XL = D; return 8; + case 0x6B: XL = E; return 8; + case 0x6C: XL = XH; return 8; + case 0x6D: XL = XL; return 8; + case 0x6E: L = RD(XA()); return 19; + case 0x6F: XL = A; return 8; + case 0x70: WR(XA(), B); return 19; + case 0x71: WR(XA(), C); return 19; + case 0x72: WR(XA(), D); return 19; + case 0x73: WR(XA(), E); return 19; + case 0x74: WR(XA(), H); return 19; + case 0x75: WR(XA(), L); return 19; + case 0x77: WR(XA(), A); return 19; + case 0x7C: A = XH; return 8; + case 0x7D: A = XL; return 8; + case 0x7E: A = RD(XA()); return 19; + case 0x84: z_add(z, XH); return 8; + case 0x85: z_add(z, XL); return 8; + case 0x86: z_add(z, RD(XA())); return 19; + case 0x8C: z_adc(z, XH); return 8; + case 0x8D: z_adc(z, XL); return 8; + case 0x8E: z_adc(z, RD(XA())); return 19; + case 0x94: z_sub(z, XH); return 8; + case 0x95: z_sub(z, XL); return 8; + case 0x96: z_sub(z, RD(XA())); return 19; + case 0x9C: z_sbc(z, XH); return 8; + case 0x9D: z_sbc(z, XL); return 8; + case 0x9E: z_sbc(z, RD(XA())); return 19; + case 0xA4: z_and(z, XH); return 8; + case 0xA5: z_and(z, XL); return 8; + case 0xA6: z_and(z, RD(XA())); return 19; + case 0xAC: z_xor(z, XH); return 8; + case 0xAD: z_xor(z, XL); return 8; + case 0xAE: z_xor(z, RD(XA())); return 19; + case 0xB4: z_or(z, XH); return 8; + case 0xB5: z_or(z, XL); return 8; + case 0xB6: z_or(z, RD(XA())); return 19; + case 0xBC: z_cp(z, XH); return 8; + case 0xBD: z_cp(z, XL); return 8; + case 0xBE: z_cp(z, RD(XA())); return 19; + case 0xE1: XY = z_pop(z); return 14; + case 0xE5: z_push(z, XY); return 15; + case 0xE3: { uint16_t v = RD16(SP); WR16(SP, XY); XY = v; WZ = v; } return 23; + case 0xE9: PC = XY; return 8; + case 0xF9: SP = XY; return 10; + case 0xCB: { + uint16_t a = XA(); uint8_t c = IMM8(), v = RD(a), g = c >> 6, k = (c >> 3) & 7, r; + if (g == 1) { z_bitm(z, k, v, (uint8_t)(a >> 8)); return 20; } + r = g == 0 ? z_rot(z, k, v) : g == 2 ? (uint8_t)(v & ~(1u << k)) : (uint8_t)(v | 1u << k); + WR(a, r); + switch (c & 7) { case 0: B = r; break; case 1: C = r; break; case 2: D = r; break; case 3: E = r; break; + case 4: H = r; break; case 5: L = r; break; case 7: A = r; break; default: break; } + return 23; } + } + return 0; +} +#undef XY +#undef XH +#undef XL +#undef XA + diff --git a/sms/src/core/z80_ops.inc b/sms/src/core/z80_ops.inc new file mode 100644 index 0000000..c685c03 --- /dev/null +++ b/sms/src/core/z80_ops.inc @@ -0,0 +1,257 @@ +/* generated by gen_z80.py */ +case 0x00: t = 4; break; +case 0x01: t = 10; BC = z_imm16(z); break; +case 0x02: t = 7; WR(BC, A); z->wz.b.l = (uint8_t)(BC + 1); z->wz.b.h = A; break; +case 0x03: t = 6; BC++; break; +case 0x04: t = 4; B = z_inc(z, B); break; +case 0x05: t = 4; B = z_dec(z, B); break; +case 0x06: t = 7; B = IMM8(); break; +case 0x07: t = 4; A = (uint8_t)(A << 1 | A >> 7); F = (uint8_t)((F & (SF | ZF | PF)) | (A & (YF | XF | CF))); break; +case 0x08: t = 4; { uint16_t x = AF; AF = z->af2; z->af2 = x; } break; +case 0x09: t = 11; HL = z_add16(z, HL, BC); break; +case 0x0A: t = 7; A = RD(BC); WZ = (uint16_t)(BC + 1); break; +case 0x0B: t = 6; BC--; break; +case 0x0C: t = 4; C = z_inc(z, C); break; +case 0x0D: t = 4; C = z_dec(z, C); break; +case 0x0E: t = 7; C = IMM8(); break; +case 0x0F: t = 4; F = (uint8_t)((F & (SF | ZF | PF)) | (A & CF)); A = (uint8_t)(A >> 1 | A << 7); F |= (uint8_t)(A & (YF | XF)); break; +case 0x10: t = 8; { int8_t e = (int8_t)IMM8(); if (--B) { PC = (uint16_t)(PC + e); WZ = PC; t = 13; break; } } break; +case 0x11: t = 10; DE = z_imm16(z); break; +case 0x12: t = 7; WR(DE, A); z->wz.b.l = (uint8_t)(DE + 1); z->wz.b.h = A; break; +case 0x13: t = 6; DE++; break; +case 0x14: t = 4; D = z_inc(z, D); break; +case 0x15: t = 4; D = z_dec(z, D); break; +case 0x16: t = 7; D = IMM8(); break; +case 0x17: t = 4; { uint8_t r = (uint8_t)(A << 1 | (F & CF)); F = (uint8_t)((F & (SF | ZF | PF)) | (A >> 7) | (r & (YF | XF))); A = r; } break; +case 0x18: t = 12; { int8_t e = (int8_t)IMM8(); PC = (uint16_t)(PC + e); WZ = PC; } break; +case 0x19: t = 11; HL = z_add16(z, HL, DE); break; +case 0x1A: t = 7; A = RD(DE); WZ = (uint16_t)(DE + 1); break; +case 0x1B: t = 6; DE--; break; +case 0x1C: t = 4; E = z_inc(z, E); break; +case 0x1D: t = 4; E = z_dec(z, E); break; +case 0x1E: t = 7; E = IMM8(); break; +case 0x1F: t = 4; { uint8_t r = (uint8_t)(A >> 1 | F << 7); F = (uint8_t)((F & (SF | ZF | PF)) | (A & CF) | (r & (YF | XF))); A = r; } break; +case 0x20: t = 7; { int8_t e = (int8_t)IMM8(); if (!(F & ZF)) { PC = (uint16_t)(PC + e); WZ = PC; t = 12; break; } } break; +case 0x21: t = 10; HL = z_imm16(z); break; +case 0x22: t = 16; { uint16_t a = z_imm16(z); WR16(a, HL); WZ = (uint16_t)(a + 1); } break; +case 0x23: t = 6; HL++; break; +case 0x24: t = 4; H = z_inc(z, H); break; +case 0x25: t = 4; H = z_dec(z, H); break; +case 0x26: t = 7; H = IMM8(); break; +case 0x27: t = 4; z_daa(z); break; +case 0x28: t = 7; { int8_t e = (int8_t)IMM8(); if ((F & ZF)) { PC = (uint16_t)(PC + e); WZ = PC; t = 12; break; } } break; +case 0x29: t = 11; HL = z_add16(z, HL, HL); break; +case 0x2A: t = 16; { uint16_t a = z_imm16(z); HL = RD16(a); WZ = (uint16_t)(a + 1); } break; +case 0x2B: t = 6; HL--; break; +case 0x2C: t = 4; L = z_inc(z, L); break; +case 0x2D: t = 4; L = z_dec(z, L); break; +case 0x2E: t = 7; L = IMM8(); break; +case 0x2F: t = 4; A ^= 0xFF; F = (uint8_t)((F & (SF | ZF | PF | CF)) | HF | NF | (A & (YF | XF))); break; +case 0x30: t = 7; { int8_t e = (int8_t)IMM8(); if (!(F & CF)) { PC = (uint16_t)(PC + e); WZ = PC; t = 12; break; } } break; +case 0x31: t = 10; SP = z_imm16(z); break; +case 0x32: t = 13; { uint16_t a = z_imm16(z); WR(a, A); z->wz.b.l = (uint8_t)(a + 1); z->wz.b.h = A; } break; +case 0x33: t = 6; SP++; break; +case 0x34: t = 11; { uint8_t v = RD(HL); WR(HL, z_inc(z, v)); } break; +case 0x35: t = 11; { uint8_t v = RD(HL); WR(HL, z_dec(z, v)); } break; +case 0x36: t = 10; { uint8_t v = IMM8(); WR(HL, v); } break; +case 0x37: t = 4; F = (uint8_t)((F & (SF | ZF | PF)) | CF | (A & (YF | XF))); break; +case 0x38: t = 7; { int8_t e = (int8_t)IMM8(); if ((F & CF)) { PC = (uint16_t)(PC + e); WZ = PC; t = 12; break; } } break; +case 0x39: t = 11; HL = z_add16(z, HL, SP); break; +case 0x3A: t = 13; { uint16_t a = z_imm16(z); A = RD(a); WZ = (uint16_t)(a + 1); } break; +case 0x3B: t = 6; SP--; break; +case 0x3C: t = 4; A = z_inc(z, A); break; +case 0x3D: t = 4; A = z_dec(z, A); break; +case 0x3E: t = 7; A = IMM8(); break; +case 0x3F: t = 4; F = (uint8_t)(((F & (SF | ZF | PF | CF)) | ((F & CF) << 4) | (A & (YF | XF))) ^ CF); break; +case 0x40: t = 4; break; +case 0x41: t = 4; B = C; break; +case 0x42: t = 4; B = D; break; +case 0x43: t = 4; B = E; break; +case 0x44: t = 4; B = H; break; +case 0x45: t = 4; B = L; break; +case 0x46: t = 7; B = RD(HL); break; +case 0x47: t = 4; B = A; break; +case 0x48: t = 4; C = B; break; +case 0x49: t = 4; break; +case 0x4A: t = 4; C = D; break; +case 0x4B: t = 4; C = E; break; +case 0x4C: t = 4; C = H; break; +case 0x4D: t = 4; C = L; break; +case 0x4E: t = 7; C = RD(HL); break; +case 0x4F: t = 4; C = A; break; +case 0x50: t = 4; D = B; break; +case 0x51: t = 4; D = C; break; +case 0x52: t = 4; break; +case 0x53: t = 4; D = E; break; +case 0x54: t = 4; D = H; break; +case 0x55: t = 4; D = L; break; +case 0x56: t = 7; D = RD(HL); break; +case 0x57: t = 4; D = A; break; +case 0x58: t = 4; E = B; break; +case 0x59: t = 4; E = C; break; +case 0x5A: t = 4; E = D; break; +case 0x5B: t = 4; break; +case 0x5C: t = 4; E = H; break; +case 0x5D: t = 4; E = L; break; +case 0x5E: t = 7; E = RD(HL); break; +case 0x5F: t = 4; E = A; break; +case 0x60: t = 4; H = B; break; +case 0x61: t = 4; H = C; break; +case 0x62: t = 4; H = D; break; +case 0x63: t = 4; H = E; break; +case 0x64: t = 4; break; +case 0x65: t = 4; H = L; break; +case 0x66: t = 7; H = RD(HL); break; +case 0x67: t = 4; H = A; break; +case 0x68: t = 4; L = B; break; +case 0x69: t = 4; L = C; break; +case 0x6A: t = 4; L = D; break; +case 0x6B: t = 4; L = E; break; +case 0x6C: t = 4; L = H; break; +case 0x6D: t = 4; break; +case 0x6E: t = 7; L = RD(HL); break; +case 0x6F: t = 4; L = A; break; +case 0x70: t = 7; WR(HL, B); break; +case 0x71: t = 7; WR(HL, C); break; +case 0x72: t = 7; WR(HL, D); break; +case 0x73: t = 7; WR(HL, E); break; +case 0x74: t = 7; WR(HL, H); break; +case 0x75: t = 7; WR(HL, L); break; +case 0x76: t = 4; z->halt = 1; break; +case 0x77: t = 7; WR(HL, A); break; +case 0x78: t = 4; A = B; break; +case 0x79: t = 4; A = C; break; +case 0x7A: t = 4; A = D; break; +case 0x7B: t = 4; A = E; break; +case 0x7C: t = 4; A = H; break; +case 0x7D: t = 4; A = L; break; +case 0x7E: t = 7; A = RD(HL); break; +case 0x7F: t = 4; break; +case 0x80: t = 4; z_add(z, B); break; +case 0x81: t = 4; z_add(z, C); break; +case 0x82: t = 4; z_add(z, D); break; +case 0x83: t = 4; z_add(z, E); break; +case 0x84: t = 4; z_add(z, H); break; +case 0x85: t = 4; z_add(z, L); break; +case 0x86: t = 7; z_add(z, RD(HL)); break; +case 0x87: t = 4; z_add(z, A); break; +case 0x88: t = 4; z_adc(z, B); break; +case 0x89: t = 4; z_adc(z, C); break; +case 0x8A: t = 4; z_adc(z, D); break; +case 0x8B: t = 4; z_adc(z, E); break; +case 0x8C: t = 4; z_adc(z, H); break; +case 0x8D: t = 4; z_adc(z, L); break; +case 0x8E: t = 7; z_adc(z, RD(HL)); break; +case 0x8F: t = 4; z_adc(z, A); break; +case 0x90: t = 4; z_sub(z, B); break; +case 0x91: t = 4; z_sub(z, C); break; +case 0x92: t = 4; z_sub(z, D); break; +case 0x93: t = 4; z_sub(z, E); break; +case 0x94: t = 4; z_sub(z, H); break; +case 0x95: t = 4; z_sub(z, L); break; +case 0x96: t = 7; z_sub(z, RD(HL)); break; +case 0x97: t = 4; z_sub(z, A); break; +case 0x98: t = 4; z_sbc(z, B); break; +case 0x99: t = 4; z_sbc(z, C); break; +case 0x9A: t = 4; z_sbc(z, D); break; +case 0x9B: t = 4; z_sbc(z, E); break; +case 0x9C: t = 4; z_sbc(z, H); break; +case 0x9D: t = 4; z_sbc(z, L); break; +case 0x9E: t = 7; z_sbc(z, RD(HL)); break; +case 0x9F: t = 4; z_sbc(z, A); break; +case 0xA0: t = 4; z_and(z, B); break; +case 0xA1: t = 4; z_and(z, C); break; +case 0xA2: t = 4; z_and(z, D); break; +case 0xA3: t = 4; z_and(z, E); break; +case 0xA4: t = 4; z_and(z, H); break; +case 0xA5: t = 4; z_and(z, L); break; +case 0xA6: t = 7; z_and(z, RD(HL)); break; +case 0xA7: t = 4; z_and(z, A); break; +case 0xA8: t = 4; z_xor(z, B); break; +case 0xA9: t = 4; z_xor(z, C); break; +case 0xAA: t = 4; z_xor(z, D); break; +case 0xAB: t = 4; z_xor(z, E); break; +case 0xAC: t = 4; z_xor(z, H); break; +case 0xAD: t = 4; z_xor(z, L); break; +case 0xAE: t = 7; z_xor(z, RD(HL)); break; +case 0xAF: t = 4; z_xor(z, A); break; +case 0xB0: t = 4; z_or(z, B); break; +case 0xB1: t = 4; z_or(z, C); break; +case 0xB2: t = 4; z_or(z, D); break; +case 0xB3: t = 4; z_or(z, E); break; +case 0xB4: t = 4; z_or(z, H); break; +case 0xB5: t = 4; z_or(z, L); break; +case 0xB6: t = 7; z_or(z, RD(HL)); break; +case 0xB7: t = 4; z_or(z, A); break; +case 0xB8: t = 4; z_cp(z, B); break; +case 0xB9: t = 4; z_cp(z, C); break; +case 0xBA: t = 4; z_cp(z, D); break; +case 0xBB: t = 4; z_cp(z, E); break; +case 0xBC: t = 4; z_cp(z, H); break; +case 0xBD: t = 4; z_cp(z, L); break; +case 0xBE: t = 7; z_cp(z, RD(HL)); break; +case 0xBF: t = 4; z_cp(z, A); break; +case 0xC0: t = 5; if (!(F & ZF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xC1: t = 10; BC = z_pop(z); break; +case 0xC2: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & ZF)) PC = a; } break; +case 0xC3: t = 10; PC = z_imm16(z); WZ = PC; break; +case 0xC4: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & ZF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xC5: t = 11; z_push(z, BC); break; +case 0xC6: t = 7; z_add(z, IMM8()); break; +case 0xC7: t = 11; z_push(z, PC); PC = 0x00; WZ = PC; break; +case 0xC8: t = 5; if ((F & ZF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xC9: t = 10; PC = z_pop(z); WZ = PC; break; +case 0xCA: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & ZF)) PC = a; } break; +case 0xCB: op = z_fetch(z); t = z80_cb(z, op); break; +case 0xCC: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & ZF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xCD: t = 17; { uint16_t a = z_imm16(z); z_push(z, PC); PC = a; WZ = a; } break; +case 0xCE: t = 7; z_adc(z, IMM8()); break; +case 0xCF: t = 11; z_push(z, PC); PC = 0x08; WZ = PC; break; +case 0xD0: t = 5; if (!(F & CF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xD1: t = 10; DE = z_pop(z); break; +case 0xD2: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & CF)) PC = a; } break; +case 0xD3: t = 11; { uint8_t n = IMM8(); Z_OUT((uint16_t)(n | A << 8), A); z->wz.b.l = (uint8_t)(n + 1); z->wz.b.h = A; } break; +case 0xD4: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & CF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xD5: t = 11; z_push(z, DE); break; +case 0xD6: t = 7; z_sub(z, IMM8()); break; +case 0xD7: t = 11; z_push(z, PC); PC = 0x10; WZ = PC; break; +case 0xD8: t = 5; if ((F & CF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xD9: t = 4; { uint16_t x = BC; BC = z->bc2; z->bc2 = x; x = DE; DE = z->de2; z->de2 = x; x = HL; HL = z->hl2; z->hl2 = x; } break; +case 0xDA: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & CF)) PC = a; } break; +case 0xDB: t = 11; { uint16_t p = (uint16_t)(IMM8() | A << 8); A = Z_IN(p); WZ = (uint16_t)(p + 1); } break; +case 0xDC: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & CF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xDD: op = z_fetch(z); t = z80_xy(z, &z->ix.w, op); if (!t) { z->cyc -= 4; goto again; } break; +case 0xDE: t = 7; z_sbc(z, IMM8()); break; +case 0xDF: t = 11; z_push(z, PC); PC = 0x18; WZ = PC; break; +case 0xE0: t = 5; if (!(F & PF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xE1: t = 10; HL = z_pop(z); break; +case 0xE2: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & PF)) PC = a; } break; +case 0xE3: t = 19; { uint16_t v = RD16(SP); WR16(SP, HL); HL = v; WZ = v; } break; +case 0xE4: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & PF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xE5: t = 11; z_push(z, HL); break; +case 0xE6: t = 7; z_and(z, IMM8()); break; +case 0xE7: t = 11; z_push(z, PC); PC = 0x20; WZ = PC; break; +case 0xE8: t = 5; if ((F & PF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xE9: t = 4; PC = HL; break; +case 0xEA: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & PF)) PC = a; } break; +case 0xEB: t = 4; { uint16_t x = DE; DE = HL; HL = x; } break; +case 0xEC: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & PF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xED: op = z_fetch(z); t = z80_ed(z, op); break; +case 0xEE: t = 7; z_xor(z, IMM8()); break; +case 0xEF: t = 11; z_push(z, PC); PC = 0x28; WZ = PC; break; +case 0xF0: t = 5; if (!(F & SF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xF1: t = 10; AF = z_pop(z); break; +case 0xF2: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & SF)) PC = a; } break; +case 0xF3: t = 4; z->iff1 = z->iff2 = 0; break; +case 0xF4: t = 10; { uint16_t a = z_imm16(z); WZ = a; if (!(F & SF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xF5: t = 11; z_push(z, AF); break; +case 0xF6: t = 7; z_or(z, IMM8()); break; +case 0xF7: t = 11; z_push(z, PC); PC = 0x30; WZ = PC; break; +case 0xF8: t = 5; if ((F & SF)) { PC = z_pop(z); WZ = PC; t = 11; break; } break; +case 0xF9: t = 6; SP = HL; break; +case 0xFA: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & SF)) PC = a; } break; +case 0xFB: t = 4; z->iff1 = z->iff2 = 1; z->ei = 1; break; +case 0xFC: t = 10; { uint16_t a = z_imm16(z); WZ = a; if ((F & SF)) { z_push(z, PC); PC = a; t = 17; break; } } break; +case 0xFD: op = z_fetch(z); t = z80_xy(z, &z->iy.w, op); if (!t) { z->cyc -= 4; goto again; } break; +case 0xFE: t = 7; z_cp(z, IMM8()); break; +case 0xFF: t = 11; z_push(z, PC); PC = 0x38; WZ = PC; break; diff --git a/sms/src/host/host.c b/sms/src/host/host.c new file mode 100644 index 0000000..b5c7bd4 --- /dev/null +++ b/sms/src/host/host.c @@ -0,0 +1,46 @@ +/* SMSEmu on the PC, for tests only: host [KEYS="frame:mask,..."] [SHOTS="frame,..."] + * Writes shot_.ppm (256 x 192) and small_.ppm (128 x 96 as the Paradise shows it). */ +#include +#include +#include +#include +#include +static uint8_t g_img[192][256]; +#define SMS_LINE(y, lb) memcpy(g_img[y], (lb), 256) +#include "../core/sms.h" +static uint8_t rom[4 << 20], cram[0x8000]; +static void ppm(const char *dir, const char *nm, int f) +{ + char p[512]; snprintf(p, sizeof p, "%s/%s_%05d.ppm", dir, nm, f); + FILE *o = fopen(p, "wb"); + if (!strcmp(nm, "shot")) { + fprintf(o, "P6 256 192 255\n"); + for (int y = 0; y < 192; y++) for (int x = 0; x < 256; x++) { uint16_t c = g_sms.pal565[g_img[y][x]]; uint8_t b[3] = { (uint8_t)((c >> 11) << 3), (uint8_t)(((c >> 5) & 63) << 2), (uint8_t)((c & 31) << 3) }; fwrite(b, 1, 3, o); } + } else { + fprintf(o, "P6 128 96 255\n"); + for (int y = 0; y < 96; y++) for (int x = 0; x < 128; x++) { + int r = 0, g = 0, b = 0; + for (int k = 0; k < 4; k++) { uint16_t c = g_sms.pal565[g_img[y * 2 + (k >> 1)][x * 2 + (k & 1)]]; r += c >> 11; g += (c >> 5) & 63; b += c & 31; } + uint8_t q[3] = { (uint8_t)(r * 2), (uint8_t)(g), (uint8_t)(b * 2) }; fwrite(q, 1, 3, o); } + } + fclose(o); +} +int main(int argc, char **argv) +{ + FILE *f = fopen(argv[1], "rb"); size_t n = fread(rom, 1, sizeof rom, f); fclose(f); + int frames = atoi(argv[2]); const char *dir = argv[3]; + if ((n & 0x3FFF) == 512) { memmove(rom, rom + 512, n - 512); n -= 512; } + { size_t L = strlen(argv[1]); g_sms.gg = L > 3 && !strcmp(argv[1] + L - 3, ".gg"); } + g_sms.rom = rom; g_sms.rom_len = (uint32_t)n; g_sms.cram = cram; g_sms.cram_len = sizeof cram; + sms_reset(); + const char *keys = getenv("KEYS"), *shots = getenv("SHOTS"); + clock_t t0 = clock(); + for (int fr = 0; fr < frames; fr++) { + if (keys) { const char *k = keys; while (*k) { int a = atoi(k); const char *c = strchr(k, ':'); if (!c) break; int m = (int)strtol(c + 1, 0, 0); if (a == fr) g_sms.pad = (uint8_t)m; k = strchr(c, ','); if (!k) break; k++; } } + sms_frame(1); + if (shots) { const char *k = shots; while (*k) { if (atoi(k) == fr) { ppm(dir, "shot", fr); ppm(dir, "small", fr); } k = strchr(k, ','); if (!k) break; k++; } } + } + double s = (double)(clock() - t0) / CLOCKS_PER_SEC; + printf("%d frames in %.2f s (%.0f fps), pc %04X\n", frames, s, frames / s, g_cpu.pc); + return 0; +} diff --git a/sms/src/stub/stdlib.h b/sms/src/stub/stdlib.h new file mode 100644 index 0000000..0a10636 --- /dev/null +++ b/sms/src/stub/stdlib.h @@ -0,0 +1,4 @@ +/* freestanding stubs for Peanut-GB on the Paradise */ +#pragma once +#include +void abort(void) __attribute__((noreturn)); diff --git a/sms/src/stub/string.h b/sms/src/stub/string.h new file mode 100644 index 0000000..6678933 --- /dev/null +++ b/sms/src/stub/string.h @@ -0,0 +1,4 @@ +#pragma once +#include +void *memset(void *d, int c, size_t n); +void *memcpy(void *d, const void *s, size_t n); diff --git a/sms/src/stub/time.h b/sms/src/stub/time.h new file mode 100644 index 0000000..1564590 --- /dev/null +++ b/sms/src/stub/time.h @@ -0,0 +1,2 @@ +#pragma once +struct tm { int tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year, tm_wday, tm_yday, tm_isdst; }; diff --git a/sms/test/devsms.py b/sms/test/devsms.py new file mode 100644 index 0000000..25421ba --- /dev/null +++ b/sms/test/devsms.py @@ -0,0 +1,160 @@ +# SMSEmu (sms.bin) in Unicorn, as devt7.py: hardware calls caught, the screen into a picture. +# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms). +# python3 devv3.py [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir] +import sys, struct, subprocess, os +from unicorn import * +from unicorn.arm_const import * +elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3]) +RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each) +out = os.environ.get('OUT', '.') +syms = {} +for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines(): + p = l.split() + if len(p) == 3: syms[p[2]] = int(p[0], 16) +fl = bytearray(open(img, 'rb').read()) +u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS) +u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4) +APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere) +u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000])) +u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000) +u.mem_map(0x10000000, 0x100000) +u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl)) +u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here) +u.mem_write(0x4000B014, struct.pack('= t: m = v + return m +def ret(uc, v=None): + if v is not None: uc.reg_write(UC_ARM_REG_R0, v) + uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1) +def h_begin(uc, *a): + x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3)) + rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc) +US_PX = float(os.environ.get('US_PX', '2.0')) +state['spi'] = 0.0; state['px'] = 0 +def h_row(uc, *a): + p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + state['spi'] += n * US_PX / 1000.0; state['px'] += n + d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n)) + for v in d: + if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v + rect['x'] += 1 + if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1 + ret(uc) +def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc) +def h_btn(uc, *a): ret(uc, keys()) +def h_prog(uc, *a): + ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1) + d = bytes(uc.mem_read(src, 0x1000)); a = ad & 0xFFFFFF + uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc) +def h_erase(uc, *a): + a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF + uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc) +def h_back(uc, *a): state['back'] = 1; uc.emu_stop() +def h_nop(uc, *a): ret(uc) +H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn, + 'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop, + 'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop} +for n, f in H.items(): + a = syms[n] & ~1 + u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a) +import builtins +if hasattr(builtins, '__gbprof'): u.hook_add(UC_HOOK_BLOCK, builtins.__gbprof[0]) +if os.environ.get('CACHESIM'): # test38: the I-cache of the flash window (16 KB, 32-byte lines, WAYS ways, LRU): misses per frame + _ways = int(os.environ.get('WAYS', '4')); _sets = 16384 // 32 // _ways + _cs = [[] for _ in range(_sets)]; state['miss'] = 0; state['acc'] = 0 + def _cr(uc, acc, a, sz, v, ud): + state['acc'] += 1 + ln = (a - 0x10000000) >> 5; s = _cs[ln % _sets] + if ln in s: s.remove(ln); s.append(ln); return + state['miss'] += 1; s.append(ln) + if len(s) > _ways: s.pop(0) + u.hook_add(UC_HOOK_MEM_READ, _cr, begin=0x10000000, end=0x100FFFFF) +def bad(uc, access, addr, size, value, ud): + print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False +u.hook_add(UC_HOOK_MEM_UNMAPPED, bad) +# 1.6.9 test22 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms +state['sh'] = 0; state['shms'] = [0, 0, 0, 0] +def _ahb(uc, acc, a, sz, v, ud): + state['sh'] = v & 7 + if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms']) +u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013) +if os.environ.get('MEMW'): + _mw = int(os.environ['MEMW'], 16) + u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F) +def shot(name): + from PIL import Image + im = Image.new('RGB', (128, 128)) + for y in range(128): + for x in range(128): + v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3)) + im.save(os.path.join(out, name)) +if os.environ.get('PMB'): # test: the Paradise's time in the mailbox (seconds since 1970, local) + _t = int(os.environ['PMB']); _c = int(os.environ.get('RTC0', '5000')) + u.mem_write(0x20000FC0, struct.pack('> state['sh'])); state['shms'][min(state['sh'], 3)] += 1 + except UcError as ex: + print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break + pc = u.reg_read(UC_ARM_REG_PC) + state['ms'] += 1 + v = struct.unpack('= 1.0: + state['spi'] -= 1.0; state['ms'] += 1; v += 1; u.mem_write(gms, struct.pack('= w[0]: + d = 1 if w[1] > 0 else -1; state_enc['ph'] = (state_enc['ph'] + d) % 4; w[0] += 0.004 if (state_enc['ph'] % 4) else 0.02 + if state_enc['ph'] == 0: w[1] -= d + u.mem_write(0x4001A000, struct.pack('= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1 + if 'miss' in state and state['ms'] % 1000 == 0: + _f = struct.unpack(' 4 else 2, b'MASTER SYSTEM') +open(out, 'wb').write(fl) diff --git a/sms/test/zex.c b/sms/test/zex.c new file mode 100644 index 0000000..f414ee3 --- /dev/null +++ b/sms/test/zex.c @@ -0,0 +1,31 @@ +/* zexdoc / zexall on the SMSEmu Z80 (CP/M: BDOS print at 5, end at 0). Test only. */ +#include +#include +#include +static uint8_t mem[65536]; static int done; +struct Z80; +#define Z_RD(a) mem[a] +#define Z_WR(a, v) (mem[a] = (v)) +#define Z_IN(p) 0xFF +static void bdos(void); +#define Z_OUT(p, v) do { if (((p) & 0xFF) == 0) bdos(); else done = 1; } while (0) +#include "../src/core/z80.h" +static Z80 cpu; +static void bdos(void) +{ + Z80 *z = &cpu; + if (z->bc.b.l == 2) putchar(z->de.b.l); + else if (z->bc.b.l == 9) for (uint16_t a = z->de.w; mem[a] != '$'; a++) putchar(mem[a]); + fflush(stdout); +} +int main(int argc, char **argv) +{ + FILE *f = fopen(argv[1], "rb"); size_t n = fread(mem + 0x100, 1, 0xFE00, f); fclose(f); (void)n; + mem[0] = 0xD3; mem[1] = 0x01; /* OUT (1),A: end */ + mem[5] = 0xD3; mem[6] = 0x00; mem[7] = 0xC9; /* OUT (0),A; RET */ + z80_tables(); z80_reset(&cpu); cpu.pc = 0x100; cpu.sp.w = 0xF000; + unsigned long long cyc = 0; + while (!done) { z80_run(&cpu, 100000); cyc += 100000; } + printf("\ncycles %llu\n", cyc); + return 0; +} diff --git a/src/app.js b/src/app.js new file mode 100644 index 0000000..a190859 --- /dev/null +++ b/src/app.js @@ -0,0 +1,4440 @@ +/* Paramix Studio UI. Everything stays in this browser tab: the ROM is read with + * FileReader and the new ROM is offered as a download. Author: mameise */ +(function () { +'use strict'; +const C = window.ParamixCore; +const E = window.ParamixEmu; +const D = window.ParamixDoom; +const F = window.ParamixFeld; +const S6 = window.ParamixSix; +const $ = (id) => document.getElementById(id); + +// ------------------------------------------------------------------ texts +const T = { + de: { + open: 'ROM öffnen', save: 'Neues ROM speichern', + startTitle: 'Mehr aus deinem Tamagotchi Paradise', + startText: 'Paramix Studio baut dein eigenes Paradise-ROM um. Lade dein Paradise-Abbild (16 MB Flash-Dump) oder lies es direkt vom Gerät aus, wähl aus, was dazukommen soll, und schreib das neue ROM zurück.', + featHead: 'Was du damit machen kannst', + g1t: 'Tamagotchi-Emulatoren', g1: 'Farb-Tamas (iD, iD L, Plus Color, P\'s, 4U, 4U+), Tama-Go mit Figuren, Friends, Meets und On, Connection V3, P1, P2, Angel und weitere erste Tamagotchis sowie Digimon V1 und V2. Mehrere zusammen im Menü, jeder mit eigenem Spielstand. Die ROMs bringst du selbst mit.', + g2t: 'DOOM und Wolfenstein 3D', g2: 'DOOM, Wolfenstein 3D und Spear of Destiny auf dem Paradise, mit eigener Tastenbelegung. Die Spieldateien bringst du selbst mit.', + g7t: 'Spielkonsolen', g7: 'Game Boy, Game Boy Color, Master System, Game Gear, Pokémon mini und Arduboy, mit Ton und Spielständen. Deine eigenen Spiele kommen ins Menü.', + g3t: 'Alle Felder', g3: 'Alle sechs Felder in einem ROM, mit Bildern, Spezialfiguren, passendem Planeten und den Lab-Spielen des Felds.', + g4t: 'Menü auf dem Gerät', g4: 'Felder wechseln, Items in die Tasche legen, Tamapoints setzen, Tama wechseln und mehrere Spielstände, direkt am Paradise. Spielzeit in den Spielen gibt Tamapoints.', + g8t: 'Startgerät ohne Paradise', g8: 'Fast die ganzen 16 MB für Emulatoren und Spiele. Jedes Programm kann zuerst starten, die Uhr stellst du im Menü.', + g5t: 'Gerät auslesen und beschreiben', g5: 'Mit einem USB-UART-Dongle das ROM sichern und das neue zurückschreiben. Spielstände bleiben, nur Geändertes wird geschrieben. Ein Schreibschutz hilft, wenn ein Schreiben abbricht.', + g6t: 'Eigene Figuren', g6: 'Jede Figur als Bild-Sheet zum Bearbeiten, auch Digimon von DIM-Karten. Farben und Augen werden automatisch angepasst.', + g9t: 'Spielstände und Besuche', g9: 'Spielstände sichern, einspielen und bearbeiten, Download-Inhalte einfügen. Besuche zwischen zwei Paradise über den Stecker oben, oder mit einem simulierten Besuch über den Dongle.', + dropTitle: 'ROM hierher ziehen oder klicken', + dropText: 'Land, Water, Sky, Jade Forest, Tropical und Glacier werden erkannt.', + f1t: 'Bearbeitung und Sicherung', f1: 'Dateien werden lokal bearbeitet. Beim Auslesen wird eine noch fehlende Edition zuerst privat auf dem Server gesichert, dann auf dem PC gespeichert.', + f2t: 'Nichts Fremdes dabei', f2: 'Paramix Studio enthält kein ROM, keine Firmware und keine WAD. Alles kommt von deinen eigenen Geräten und Dateien.', + f3t: 'Geprüft', f3: 'Prüfsummen werden neu gerechnet, geänderte Bilder vor dem Speichern noch einmal gelesen und jeder geschriebene Sektor auf dem Gerät gegengelesen.', + planTitle: 'Dein neues ROM', planFig: 'Figuren', planEmu: 'Emulator', planEmus: 'Emulatoren', planDoom: 'DOOM', planWolf: 'Wolfenstein 3D', planGb: 'Game Boy', planSms: 'Master System / Game Gear', planPm: 'Pokémon mini', planMenu: 'Menü', planApps: 'Weitere Emulatoren', + stNone: 'nicht dabei', stKeep: 'bleibt', stNew: 'neu', stDel: 'wird entfernt', stChanged: '{n} geändert', stSame: 'unverändert', + segFw: 'Firmware und Figuren', segEmu: 'Emulator', segDoom: 'DOOM', segWolf: 'Wolfenstein 3D', segGb: 'Game Boy', segSms: 'Master System / Game Gear', segPm: 'Pokémon mini', segSlots: 'Spielstände der Felder', segSave: 'Spielstand', segFree: 'frei', segResv: 'reserviert', + ruleBoth: 'Emulator oder DOOM: es passt nur eines von beiden ins ROM. Das Menü passt zu beidem.', + ruleNoRoom: 'In dieser Ausgabe ist kein Platz für Emulator und DOOM (die Figuren-Daten sind grösser). Das Menü geht.', + emuVsDoom: 'Achtung: DOOM ist gewählt oder eingebaut. Mit einer Firmware hier fällt DOOM weg.', + doomVsEmu: 'Achtung: ein Emulator ist gewählt oder eingebaut. Mit einer WAD hier fällt der Emulator weg.', + noRoomApp: 'In dieser Ausgabe ist kein Platz dafür.', a0Menu: 'Diese Ausgabe hat keinen Platz für ein Hauptprogramm bei 0x0A0000: alle Programme kommen ins Menü. Der Stern wählt, was beim Einschalten startet.', a0MenuN: 'Diese Ausgabe hat keinen Platz für ein Hauptprogramm bei 0x0A0000. Tama-Go, Friends, die alten Tamas und das V3 kommen ins Menü (A und C, dafür im Tab Menü Feldwechsel oder Items einschalten). Farb-Tamas und TG18 gehen hier nur im Startgerät.', a0NoMain: '{f}: Farb-Tamas und TG18 gehen bei dieser Ausgabe nur im Startgerät (Tab Menü).', + doomHas: 'In diesem ROM ist DOOM eingebaut.', doomOff: 'DOOM entfernen', doomGone: 'DOOM wird beim Speichern entfernt.', + keysTitle: 'Tasten', kFire: 'Schiessen', kFwd: 'Vorwärts', kBack: 'Zurück', kUse: 'Benutzen', kMod: 'Waffe wechseln: halten + Rad', + kWheel: 'Rad drücken', kRun: 'Laufen mit 2x Vorwärts', kInv: 'Rad andersherum', kFixed: 'Immer gleich: A+C Menü, B+C Karte. Ton an/aus: die Taste von "Waffe wechseln" halten und kurz aufs Rad drücken. Zurück: wie im Tab Menü unter "Zurück aus Programmen".', + kOld: 'Dieses DOOM ist älter und kennt noch keine eigene Tastenbelegung. Mit der WAD neu einbauen.', + help: 'Hilfe', helpTitle: 'So geht\'s', h1t: 'Ablauf', h1: '1. ROM öffnen (Datei vom eigenen Paradise) oder mit "Gerät" direkt auslesen.\n2. In den Tabs wählen, was hinein soll: Figuren, Emulatoren, Game Boy, Master System, Pokémon mini, DOOM, Wolfenstein, Menü.\n3. Speichern oder mit "Gerät" aufs Paradise schreiben. Mit "Spielstände behalten" bleibt der Spielstand auf dem Gerät.', h2t: 'Tasten am Paradise', hk1: 'A und C', hv1: 'auf dem Heimbildschirm: Menü oder Emulator starten', hk2: 'Rad lange (Tab Menü: änderbar)', hv2: 'Stand speichern und zurück ins Paradise', hk3: 'Rad kurz', hv3: 'T7Emu: Einstellungen und Figur', hk4: 'Rad in den ersten 3 s', hv4: 'gespeicherten Stand verwerfen (mit A bestätigen), der nächste Start beginnt frisch ab dem eigenen Spielstand des Tamas', hk5: 'B beim Einschalten', hv5: 'mit Autostart: Paradise oder Menü statt Hauptprogramm', hk6: 'Reset-Knopf', hv6: 'mit Autostart: das Hauptprogramm startet wieder', hk7: 'C beim Einschalten', hv7: 'Flash-App: das Gerät lässt sich mit "Gerät" neu schreiben (Notausgang)', h3t: 'Uhr', h3: 'Mit "Uhr beim Start vom Paradise übernehmen" (Tab Emulator) stellt der Emulator bei jedem Start seine Uhr auf die Zeit des Paradise. Was dazwischen war, wird nicht nachgespielt. Die Uhr also am Paradise stellen.', h4t: 'Wieder reingehen', h4: 'Der Emulator macht genau dort weiter, wo du mit dem Rad rausgegangen bist. Der eigene Spielstand des Tamas bleibt auch dann, wenn der gespeicherte Stand verworfen wird.', h5t: 'Menü und Felder', h5: 'A und C auf dem Heimbildschirm. Rad wählt, B bestätigt, C geht zurück. Beim Feldwechsel wird der Spielstand des alten Felds gepackt und der des neuen zurückgeholt.\n6 Felder: Tropical und Glacier bekommen Land, Water und Sky aus deinem eigenen ROM, Jade Forest bekommt Sky. Im Spiel wechselt das Tama über Planet, Felder. DNA und Bewohner gehören zum jeweiligen Feld.', h8t: 'Startgerät', h8: 'Tab Menü, Startgerät: das Gerät startet ins Menü mit allen Programmen. Ohne Paradise bleibt fast der ganze Speicher für Programme, die Uhr wird im Menü gestellt. Der Stern wählt das Hauptprogramm, mit Autostart startet es beim Einschalten.', h9t: 'Notausgang', h9: 'Bleibt der Bildschirm schwarz oder hängt ein Programm: C halten und Batterien einsetzen (oder Reset-Knopf drücken). Die Flash-App startet, das Gerät lässt sich mit "Gerät" auslesen und neu schreiben. Bricht ein Schreiben ab, startet die Flash-App von selbst.', h6t: 'Spielstände sichern', h7t: 'Spielstand einspielen', h7: '1. ROM mit "Gerät" frisch auslesen (oder das zuletzt gelesene öffnen).\n2. Tab Spielstand: einspielen. Der Spielstand kommt zum passenden Programm.\n3. Mit "Spielstände behalten" aufs Gerät schreiben. Nur dieser Spielstand wird ersetzt, der Paradise-Spielstand und die der anderen Programme bleiben wie auf dem Gerät.\nOhne "Spielstände behalten" kommen alle Spielstände aus der Datei. Programme dazu oder weg besser in einem eigenen Schreiben, vorher alle Spielstände sichern.', h6: 'Tab Spielstand oder Gerät, "Spielstand sichern". Vor einem Wechsel des Emulators sichern, der alte Spielstand geht dabei verloren.', device: 'Gerät', devTitle: 'Gerät über UART', devHint: 'UART-Dongle mit 3,3 V an die drei Kontakte: links RX vom Dongle, Mitte GND, rechts TX vom Dongle. Am Paradise den Download-Bildschirm öffnen (Planet, A, Connect, Download, Download), dann Verbinden. Braucht Chrome oder Edge am Computer.', + devConnect: 'Verbinden', devDump: 'ROM sichern und herunterladen', devWrite: 'Neues ROM aufs Gerät schreiben', devOnly: 'Nur Änderungen schreiben', devKeep: 'Spielstände behalten', devStop: 'Abbrechen', + devNoSerial: 'Dieser Browser kann nicht mit dem Dongle reden. Bitte Chrome oder Edge am Computer verwenden.', devNone: 'Nicht verbunden.', + devOn: 'Verbunden: {ed}, {mb} MB{l}', devLoaded: ', Flash-App geladen', devReady: 'Bereit.', devNeedRom: 'Zum Schreiben zuerst ein ROM öffnen (oder auslesen).', + visTitle: 'Besuch simulieren (Paradise)', visStart: 'Starten', visStop: 'Beenden', + visHint: 'Das Studio spielt ein zweites Paradise. Dongle an die Kontakte, das Paradise läuft normal.\n1. Edition wählen, Starten, Dongle wählen.\n2. Am Paradise: Planet-Menü, VERBINDUNG, PLAYDATE, dann B.\nOben "Verbinden" ist nur fürs ROM, für den Besuch nicht drücken.', + visWait: 'Bereit als {ed}. Am Paradise PLAYDATE wählen und B drücken.', visRun: 'Verbunden, Daten werden getauscht…', visPlay: 'Die beiden spielen…', + visDone: 'Besuch fertig ({ed}). Für den nächsten wieder B am Paradise.', visErr: 'Abgebrochen: {e}. Am Paradise nochmals B.', visBadKey: 'Das Paradise versteht die Daten nicht.', + phload: 'Flash-App laden', phread: 'Auslesen', phcompare: 'Vergleichen', phwrite: 'Schreiben', phcheck: 'Prüfen', phprepare: 'Vorbereiten', + devDumped: 'ROM ausgelesen und als {n} gespeichert. Es ist jetzt im Studio geöffnet.', + devSure: 'Das neue ROM wird jetzt aufs Gerät geschrieben. Gerät während des Schreibens eingeschaltet lassen. Auf eigene Gefahr schreiben?', + devSureFull: 'Ohne "Spielstände behalten" wird auch der Spielstand mit dem aus dem ROM überschrieben. Trotzdem schreiben?', + carryUnknown: 'Das Gerät hat nicht das geladene ROM. Ein Programm zieht um und sein Spielstand auf dem Gerät kann nicht mitgenommen werden. Zuerst das ROM vom Gerät lesen. Trotzdem schreiben?', carryMiss: 'Ein Programm zieht um und sein Spielstand auf dem Gerät kann nicht mitgenommen werden. Vorher im Tab Spielstand sichern. Trotzdem schreiben?', devEmuLost: 'Hauptprogramm auf dem Gerät: {o}. Im neuen ROM: {n}. Der Spielstand von {o} als Hauptprogramm fängt deshalb neu an. Zum Behalten vorher unter "Spielstand" sichern. Trotzdem schreiben?', devEmuNone: 'keinen Emulator', devEmuNew: '{o} mit einer neu gewählten Firmware', + devDone: 'Fertig und geprüft: {w} Sektoren geschrieben{k}. Das Gerät kann neu gestartet werden (Reset oder Batterie).', devKept: ', {k} Sektoren Spielstand behalten', + devSame: 'Nichts zu schreiben, das Gerät hat schon dieses ROM.', devErr: 'Fehler: {e}', devCancelled: 'Abgebrochen.', + fl_timeout: 'keine Antwort vom Gerät ({c} {a})', fl_noAck: 'das Gerät antwortet nicht. Steht es auf dem Download-Bildschirm?', fl_repeats: 'zu viele Wiederholungen beim Laden', + fl_devCancel: 'das Gerät hat das Laden abgebrochen', fl_unexpected: 'unerwartete Antwort: {r}', fl_hello: 'unerwartete Antwort auf HELLO', fl_notReady: 'Flash nicht bereit', + fl_readErr: 'Lesefehler bei {a}', fl_noCrc: 'keine Prüfsumme bei {a}', fl_cancelled: 'abgebrochen', fl_size: 'das Abbild muss genau 16 MB gross sein', + fl_notParadise: 'kein Paradise-Abbild (SONIXDEV fehlt)', fl_cancelledWrite: 'abgebrochen. Gerät eingeschaltet lassen und nochmals schreiben', + fl_notAccepted: 'Sektor {a} nicht angenommen. Gerät eingeschaltet lassen und nochmals schreiben', fl_differs: 'Sektor {a} weicht nach dem Schreiben ab. Gerät eingeschaltet lassen und nochmals schreiben', + fl_checkFail: 'Prüfung bei {a} falsch. Gerät eingeschaltet lassen und nochmals schreiben', fl_rescueBusy: 'der Rettungsbereich (0xFF0000) ist belegt', fl_noRescueRoom: 'Kein Platz für den Schreibschutz (Rettungsstart, oberste 64 KB im Flash). Es wurde nichts geschrieben. Ein Programm im Startgerät entfernen und nochmals schreiben.', fl_rescueMode: 'Das letzte Schreiben wurde unterbrochen. Das Gerät wartet im Flash-Bildschirm: nochmals schreiben.', resOn: 'Schreibschutz aktiv: bricht ein Schreiben ab, startet das Gerät im Flash-Bildschirm.', resModeGo: 'Das letzte Schreiben wurde unterbrochen. Das Gerät ist im Flash-Bildschirm und wartet. "Schreiben fortsetzen" drücken.', resModeRom: 'Das letzte Schreiben wurde unterbrochen. Das Gerät ist im Flash-Bildschirm und wartet. Das ROM nochmals öffnen (oder deinen Abzug) und aufs Gerät schreiben.', resResume: 'Schreiben fortsetzen', resHalf: 'Das letzte Schreiben wurde nicht fertig. "Schreiben fortsetzen" drücken, damit alles wieder zusammenpasst.', resResumed: 'Fertig: {w} Sektoren geschrieben. Paradise aus- und einschalten.', fl_rescueFail: 'der Rettungsstart wurde nicht richtig geschrieben', fl_noRescue: 'kein Rettungsstart: 0xFF0000 ist belegt', resTest: 'Rettungsstart testen', resBack: 'Kopf zurückschreiben', resSure: 'Test: Der Rettungsstart kommt nach 0xFF0000, dann wird der Kopf des Geräts (Sektor 0) gelöscht. Danach Paradise aus- und einschalten. Erscheint der Flash-Bildschirm, hier verbinden und "Kopf zurückschreiben". Erscheint er nicht, ist das Gerät ohne eigenes Flash-Werkzeug nicht mehr startbar. Weiter?', resCleared: 'Kopf gelöscht. Paradise aus- und einschalten. Flash-Bildschirm da? Dann verbinden und "Kopf zurückschreiben".', resBackDone: 'Kopf zurückgeschrieben. Paradise aus- und einschalten: es startet wieder normal.', resNoHdr: 'Kein gemerkter Kopf.', fl_noAnswer: 'keine Antwort. Gerät auf den Download-Bildschirm stellen und nochmals versuchen', fl_noData: 'keine Antwort, vom Adapter kommen gar keine Daten an. Gerät auf den Download-Bildschirm stellen und nochmals versuchen. Kommt weiter nichts: Kabel und Treiber des Adapters prüfen', fl_garbled: 'es kommen Daten an, aber unlesbar ({n} Bytes: {h}). Kabel (TX und RX) und Treiber des Adapters prüfen', plHint: 'Prolific-Adapter (PL2303): Neuere Windows-Treiber sperren ältere und nachgebaute PL2303-Chips. Dann kommen keine Daten durch. Abhilfe: im Geräte-Manager den älteren Prolific-Treiber 3.3.2.x wählen oder einen Adapter mit CH340 oder CP2102 nehmen.', fl_lost: 'das Gerät antwortet vor dem Schreiben nicht mehr. Geschrieben wurde nichts. Paradise aus- und einschalten, Download-Bildschirm, neu verbinden und nochmals schreiben', + fl_appSilent: 'die Flash-App ist gesendet, antwortet aber nicht. Nochmals versuchen', fl_unknownEd: 'Ausgabe des neuen ROMs unbekannt, "Spielstände behalten" abwählen', + fl_otherEd: 'das Gerät ist {d}, das neue ROM ist {r}. Zum Wechseln der Ausgabe "Spielstände behalten" abwählen', + fl_noteNoFit: 'Feld {f} passt nicht ins neue Fach und wird nicht behalten', fl_noteMoved: 'Feld {f} ist ins neue Fach umgezogen', fl_noteSaveMoved: 'Spielstand von {n} mitgenommen', + fl_noteDropped: 'das neue ROM hat kein Feld-Menü, die gespeicherten Felder auf dem Gerät fallen weg', fl_noteEdKept: 'das Gerät ist {d}, das neue ROM ist {r}: gleiche Firmware, Spielstand und Feld vom Gerät bleiben ({d})', fl_noteEmu: 'TamaEmu-Firmware neu gewählt, der Emulator startet frisch. Für ein Update das ROM nur öffnen und speichern', + cleanOn: 'Ohne Paradise (Clean ROM)', cleanClock: 'Uhr beim Start stellen', cleanClockHint: 'Fehlt die Uhr (neue Batterien), fragt das Menü beim Einschalten danach. Ohne: Die Uhr stellst du im Menü unter SETTINGS oder in jedem Emulator selbst.', emuClockOff: 'Geht nur mit "Uhr beim Start stellen" (Tab Menü).', emuSess: 'Spielstand beim Verlassen merken', emuSessHint: 'Beim nächsten Start geht es genau dort weiter. Ohne: Das Spiel startet neu und lädt seinen eigenen Spielstand, wie das echte Gerät.', ruleClean: 'Ohne Paradise: alle Programme kommen ins Menü, fast der ganze Speicher ist für sie da.', cleanHint: 'Kein Paradise mehr auf dem Gerät, nur das Menü mit deinen Programmen. Fast die ganzen 16 MB sind frei.', cleanUse: 'Nach dem Einschalten kommt gleich das Menü. Beim ersten Start stellst du die Uhr, später unter SETTINGS. Zurück aus einem Programm wie gewohnt.', cleanWarn: 'Das Paradise und sein Spielstand gehen beim Schreiben verloren. Mach vorher eine Sicherung.', cleanNoDoom: 'DOOM geht noch nicht ohne Paradise. Bitte DOOM entfernen.', doomOne: 'DOOM geht nur einmal ins Menü.', cleanSure: 'Auf dem Gerät ist das Paradise. Es wird gelöscht, mit seinem Spielstand. Hast du eine Sicherung des Geräts? Weiter?', cleanLoaded: 'ROM ohne Paradise ({ed}) geladen: {n} Programme.', + launchOn: 'Nur Startgerät für Programme', launchHint: 'Vom Paradise bleibt nur die Einrichtung (Sprache, Uhr, Weiter oder Neu). Danach kommt immer das Menü mit deinen Emulatoren und DOOM. Alle Bilder des Spiels fallen weg, das gibt etwa 5 MB mehr Platz.', launchUse: 'Nach dem Einschalten und dem Stellen der Uhr kommt das Menü. Rad wählt, B startet. Zurück aus einem Programm wie gewohnt, dann kommt wieder das Menü.', launchOld: 'Dieses ROM ist ein Startgerät. Für ein normales Paradise das Original-ROM laden.', launchNeed: 'Ein Startgerät braucht mindestens ein Programm (Emulator oder DOOM).', launchSix: 'Startgerät geht nicht mit eingebauten sechs Feldern. Bitte das Original-ROM laden.', planLaunch: 'Startgerät', + tabFeld: 'Menü', feldOn: 'Mehrere Spielstände (mit Feldwahl)', bagOn: 'Items und Tamapoints', tamaOn: 'Tama ändern (Stufe, Pflege, Figur)', gplayOn: 'Spielzeit gibt Tamapoints', gplayHint: 'DOOM, Wolfenstein, Game Boy, Master System, Pokémon mini und Arduboy: 10 Tamapoints pro Minute Spielzeit, beim Zurückkehren ins Paradise.', saveSlot: 'Spielstand {n}', + sixOn: 'Alle 6 Felder', sixPick: 'Land-, Water- oder Sky-ROM wählen', sixHint: 'Holt Land, Water und Sky zu Tropical und Glacier dazu. Die Feldbilder kommen aus deinem eigenen Land-, Water- oder Sky-ROM. Die Lab-Spiele richten sich nach dem Feld, mit dem der Tama im Menü startet.', + sixNeed: 'Für alle 6 Felder fehlt noch ein Land-, Water- oder Sky-ROM.', sixOk: 'Feldbilder aus {n} übernommen.', sixBad: '{n} ist kein Land-, Water- oder Sky-ROM.', sixIn: 'Alle 6 Felder sind eingebaut.', sixOff: 'Beim Speichern kommen Land, Water und Sky wieder raus. Mehrere Spielstände gehen weiterhin.', sixOffJ: 'Beim Speichern kommt Sky wieder raus. Mehrere Spielstände gehen weiterhin.', sixOffField: 'Das Gerät ist gerade auf {f}. Erst im Menü auf {s} wechseln.', sixOffSlots: 'Die im Menü gespeicherten Spielstände werden dabei gelöscht. Weiter?', sixFail: 'Felder nicht eingebaut: {e}', sixNoFw: 'Die Firmware dieses ROMs ist verändert, weitere Felder gehen hier nicht.', planSix: 'Mehr Felder', sixOnJ: 'Sky als 4. Feld', sixHintJ: 'Jade Forest hat die Sky-Bilder schon dabei.', sixInJ: 'Sky ist als 4. Feld eingebaut.', sixOld: 'Alle 6 Felder sind eingebaut, aber in einer älteren Version. Wähl dein Land-, Water- oder Sky-ROM, dann wird beim Speichern alles nachgerüstet.', sixOldJ: 'Sky ist eingebaut und wird beim Speichern auf den neuen Stand gebracht.', sixPlanet: 'Planet passend zum Feld', sixMenu: 'Spielmenü Felder: alle Felder ab Stufe 4', sixPlanetNeed: 'Zum Ändern dieser Einstellung braucht es nochmals dein Land-, Water- oder Sky-ROM.', sixApp: 'DOOM und Emulator passen nicht dazu', + exitKey: 'Zurück aus Programmen', exitHint: 'Wie man aus allen Programmen (Emulatoren und Spiele) zum Paradise oder ins Menü zurückkommt.', exit0: 'Rad lange drücken', exit1: 'Rad und A halten', exit2: 'Rad und C halten', exit3: 'Rad 5 s drücken', feldHint: 'Kleines Menü im ROM: zwischen Spielständen wechseln (neuer Spielstand auf einem Feld nach Wahl), Items in die Tasche legen, Tamapoints setzen, Tama ändern.', + feldUse: 'Öffnen: auf dem Heimbildschirm A und C zusammen halten. Rad wählt, B bestätigt, C zurück.', + feldNo: 'Feldwahl geht mit Land, Water, Sky (untereinander) und Tropical, Glacier (untereinander).', feldMissing: 'In dieser Ausgabe fehlt das Menü.', + feldCur: 'Aktives Feld: {f}.', feldList: 'Wählbar: {s}.', feldStored: 'Gespeichert: {s}.', feldFail: 'Menü nicht eingebaut: {e}', feldUnknown: 'Ausgabe nicht erkannt.', + tabWolf: 'Wolf3D', wolfPick: 'Spieldateien wählen', wolfHint: 'Alle Dateien von Wolfenstein 3D zusammen wählen: Shareware (.WL1), Vollversion (.WL6) oder Spear of Destiny (.SOD). Das Spiel kommt ins Paramix-Menü.', wolfNone: 'Noch keine Spieldateien gewählt.', wolfShare: 'Shareware', wolfFull: 'Vollversion', wolfEps: '{n} Episoden', wolfEp1: '1 Episode', wolfBad: 'Wolfenstein 3D: {e}', wolfNoMain: 'Wolfenstein 3D nur im Menü', wolfTurn: 'Drehen pro Radstufe', wolfFixed: 'Immer gleich: A+C Menü. Zurück (das Spiel wird gespeichert): wie im Tab Menü unter "Zurück aus Programmen".', wolfOne: 'Es gibt nur ein Wolfenstein 3D und ein Spear of Destiny im Menü, das neue ersetzt das alte.', wolfSodN: '21 Level', + tabGb: 'Game Boy / Color', gbNoMain: 'Game Boy nur im Menü', gbPick: 'Spiele wählen (.gb, .gbc)', gbHint: 'Die Spiele kommen ins Paramix-Menü. Am Gerät: A+B+C zusammen öffnet die Einstellungen (dort auch Select und Ton). Rad 2 s halten speichert und führt zurück, beim nächsten Start geht es dort weiter. Zwei Paradise oben zusammengesteckt sind wie mit einem Link-Kabel verbunden, z. B. zum Pokémon tauschen.', gbNone2: 'Noch kein Spiel gewählt.', gbKeysTitle: 'Tasten', gbKeysDef: 'Standard', gbKeysMiss: 'Nicht belegt: {n}', gbNone: '–', gbRight: 'Rechts', gbLeft: 'Links', gbUp: 'Hoch', gbDown: 'Runter', gbInA: 'Taste A', gbInB: 'Taste B', gbInC: 'Taste C', gbInWp: 'Rad drücken', gbInWu: 'Rad hoch', gbInWd: 'Rad runter', gbInAC: 'A + C', gbInBC: 'B + C', gbInAB: 'A + B', gbBad: '{f}: kein Game-Boy-Spiel', gbColor: '{f}: nur für Game Boy Color, das geht nicht', gbNeedRom: 'Zuerst ein ROM öffnen (oder vom Gerät lesen).', t7Old: '{n}: veraltete Version, der Spielstand kann beim Batteriewechsel verloren gehen. Jetzt mit "Spielstände behalten" neu schreiben.', t18Broken: 'Tama Meets ist beschädigt. Tama Meets entfernen und die Firmware neu hinzufügen, dann ohne "Spielstände behalten" schreiben.', t18Clash: 'das Hauptprogramm bräuchte den Platz von Tama Meets. Tama Meets zuerst entfernen.', tabSms: 'Master System / Game Gear', tabPm: 'Pokémon mini', smsNoMain: 'Master System und Game Gear nur im Menü', pmNoMain: 'Pokémon mini nur im Menü', abNoMain: 'Arduboy nur im Menü', planAb: 'Arduboy', segAb: 'Arduboy', tabAb: 'Arduboy', abPick: 'Spiele wählen (.hex, .zip)', abHint: 'Die Spiele kommen ins Paramix-Menü. Am Gerät: A+B+C zusammen öffnet die Einstellungen (dort auch Bildgrösse und Ton). Rad 2 s halten speichert und führt zurück, beim nächsten Start geht es dort weiter.', abBad: '{f}: kein Arduboy-Spiel', abBig: '{f}: zu gross für den Arduboy', smsPick: 'Spiele wählen (.sms, .gg)', smsHint: 'Die Spiele kommen ins Paramix-Menü. Am Gerät: A+B+C zusammen öffnet die Einstellungen (dort auch Pause und Ton). Rad 2 s halten speichert und führt zurück, beim nächsten Start geht es dort weiter.', smsBad: '{f}: kein Master-System- oder Game-Gear-Spiel', smsGG: '{f}: Game-Gear-Spiel, das geht nicht', smsB1: 'Knopf 1', smsB2: 'Knopf 2', smsPause: 'Pause / Start', pmPick: 'Spiele wählen (.min, .zip)', pmHint: 'Die Spiele kommen ins Paramix-Menü. Am Gerät: A+B+C zusammen öffnet die Einstellungen (dort auch Power und Ton). Rad 2 s halten speichert und führt zurück, beim nächsten Start geht es dort weiter.', pmBad: '{f}: kein Pokémon-mini-Spiel', pmBig: '{f}: grösser als 1 MB, das geht nicht', pmBiosPick: 'Eigenes BIOS wählen', pmBiosDel: 'Eigenes BIOS entfernen', pmBiosFree: 'Ohne eigenes BIOS läuft das freie BIOS von PokeMini. Mit dem echten BIOS laufen manche Spiele besser.', pmBiosOwn: 'Eigenes BIOS gewählt, es gilt für alle Pokémon-mini-Spiele.', pmBiosBad: '{f}: kein Pokémon-mini-BIOS', pmA: 'A', pmB: 'B', pmC: 'C', pmPower: 'Power', pmShake: 'Schütteln', + tabFigs: 'Figuren', tabAll: 'Alle Sprites', tabDim: 'Karte', tabEmu: 'Emulator', tabDoom: 'DOOM', + doomPick: 'DOOM.WAD wählen', doomEp: 'Episode', doomMusic: 'Musik', + doomHint: 'Baut DOOM ins ROM. Die WAD bringst du selbst mit, sie bleibt auf deinem Computer.', + doomUse: 'Starten: im Paramix-Menü, mit Paradise auch auf dem Heimbildschirm A und C zusammen halten. Zurück: wie im Tab Menü unter "Zurück aus Programmen".', + doomNone: 'Keine WAD gewählt.', doomOk: 'WAD erkannt ({eps}). DOOM wird beim Speichern eingebaut.', doomEpsHint: 'Ohne Paradise: jede angehakte Episode kommt als eigener Eintrag ins Menü (DOOM E1, DOOM E2 ...), mit eigenem Spielstand.', doomWhole: 'Ganze WAD als ein Eintrag', pwadPick: 'Zusatz-WAD wählen', pwadOff: 'Zusatz-WADs entfernen', doomPwads: 'Dazu: {n}.', pwadNeedD2: '{n} ist für DOOM II: zuerst DOOM2.WAD wählen.', pwadNeedD1: '{n} ist für DOOM oder Ultimate DOOM: zuerst DOOM.WAD wählen.', doomPwadPara: 'Eigene Episoden (wie Sigil) gehen nur ohne Paradise.', doomPwadBig: '{n}: die Karten {m} sind wahrscheinlich zu gross für den Speicher des Paradise. DOOM zeigt dann eine Zeile mit einer 9, Rad 2 s halten führt zurück ins Menü.', doomPwadHint: 'Eigene Episoden (wie Sigil) kommen als eigener Eintrag ins Menü, dafür den Haken setzen. Zusammen mit der ganzen WAD sind sie meist zu gross.', doomD2Clean: 'DOOM II geht nur in ein ROM ohne Paradise.', doomD2Hint: 'DOOM II kommt als ein Eintrag ins Menü. Es braucht fast den ganzen Platz und passt nur ohne Musik.', doomWholeHint: 'Alle Episoden in einem Eintrag "DOOM", die Episode wählt man im Spiel. Braucht viel weniger Platz als einzeln.', + doomBad: 'WAD nicht erkannt: {e}', doomFail: 'DOOM nicht eingebaut: {e}', doomMissing: 'In dieser Ausgabe fehlt das DOOM-Programm.', + doomBoth: 'Emulator und DOOM zusammen passen nicht in ein ROM. Bitte nur eines wählen.', + doomBig: 'Keine Episode dieser WAD passt ins ROM.', doomNoMusic: 'Diese Episode passt nur ohne Musik.', + emuPick: 'Firmware oder ROM wählen', emuOff: 'Emulator entfernen', + emuHint: 'Farb-Tamas (TamaEmu), Tama-Go und Friends (T7Emu), Meets und On (T18Emu), erste Tamagotchis und Digimon (V1Emu), Connection V3 (V3Emu). Das erste ist das Hauptprogramm, jedes weitere kommt ins Menü. Der volle Stern zeigt das Hauptprogramm, ein Klick auf einen leeren Stern macht ein anderes dazu. Die Dateien bringst du selbst mit.', t7Ok: 'V7-ROM erkannt (T7Emu). Es wird beim Speichern eingebaut.', t7OkFr: 'Tamagotchi Friends erkannt (T7Emu, Test). Es wird beim Speichern eingebaut. Figuren gibt es dafür keine.', t7Has: 'In diesem ROM ist T7Emu eingebaut.', t7HasFr: 'In diesem ROM ist T7Emu mit Tamagotchi Friends eingebaut.', t7Use: 'Starten: auf dem Heimbildschirm A und C zusammen halten. Zurück: Rad lange drücken (speichert). Rad kurz: Einstellungen und Figur. Hängt T7Emu: mit A und C starten, loslassen und in den ersten 3 Sekunden das Rad drücken und mit A bestätigen.', t7FigPick: 'Figuren hinzufügen', t7FigNone: 'Noch keine Figuren.', t7FigBad: '{f}: keine Figur.', t7FigFull: 'Kein Platz mehr für {f}.', t7FigMax: 'Kein Platz für weitere Figuren.', t7FigDup: '{f} ist schon dabei.', appPick: 'Weiteren Emulator dazu', appHint: 'Noch ein Tama-Go- oder Friends-ROM (T7Emu). Start über das Menü (A und C), dafür muss im Tab Menü etwas eingeschaltet sein.', appNone: 'Keine weiteren Emulatoren.', appBad: '{f}: kein Tama-Go- oder Friends-ROM.', appBadL: '{f}: weder Tama-Go-, Friends-ROM noch Farb-Tama- oder TG18-Firmware.', appT18One: 'T18Emu geht nur einmal pro ROM.', appHintL: 'Im Startgerät: Tama-Go- oder Friends-ROM, Farb-Tama-Firmware (TamaEmu) oder TG18-Firmware (T18Emu, nur einmal).', ruleLaunch: 'Startgerät: Emulatoren und DOOM passen zusammen, solange Platz frei ist.', appMax: 'Höchstens 12 weitere Emulatoren.', appNeedMenu: 'Weitere Emulatoren starten über das Menü: im Tab Menü Feldwechsel oder Items einschalten.', appFail: 'Weitere Emulatoren: {e}', appSix: 'Sechs Felder gehen nicht zusammen mit weiteren Emulatoren.', t7SaveBtn: 'T7Emu-Spielstand (.bin)', saveFor: 'Programm', saveMain: 'Haupt-Emulator', v1SaveBtn: 'V1Emu-Spielstand (.bin)', saveT18No: 'T18Emu: Spielstand sichern geht hier noch nicht.', saveNoBatt: 'Dieses Spiel hat keinen Spielstand auf dem Modul.', saveNone: 'Noch kein Spielstand.', saveWrongFile: 'Diese Datei passt nicht zu {n}.', saveCartIn: 'Spielstand für {n} übernommen. Jetzt das ROM speichern oder aufs Gerät schreiben. Ein gemerkter Spielzustand wird verworfen.', t7SaveXDone: 'Spielstand für {n} übernommen. Jetzt das ROM speichern oder aufs Gerät schreiben.', t7NoSave: 'Das Tama hat noch keinen Spielstand.', t7SaveInDone: 'T7Emu-Spielstand übernommen. Jetzt das ROM speichern oder aufs Gerät schreiben.', t7SaveNeed: 'T7Emu fehlt im ROM: zuerst im Tab Emulator das Tama-Go-ROM hinzufügen.', saveT18Need: 'T18Emu fehlt im ROM: zuerst im Tab Emulator die TG18-Firmware hinzufügen.', saveEmuAny: 'Emulator-Spielstand (.sav / .bin)', + emuUse: 'Starten: auf dem Heimbildschirm A und C zusammen halten. Zurück: Rad lange drücken (speichert). Hängt TamaEmu: mit A und C starten, loslassen und in den ersten 3 Sekunden das Rad drücken und mit A bestätigen. Dann beginnt er neu ab dem eigenen Spielstand des Tamas.', + emuNone: 'Kein Emulator gewählt.', petT: 'Spielstand ändern', petOpen: 'Paradise-Spielstand öffnen', petRom: 'Spielstand im ROM', petClose: 'Schliessen', petRomDone: 'Im ROM geändert. Jetzt das ROM speichern oder aufs Gerät schreiben (ohne "Spielstände behalten", sonst bleibt der Spielstand des Geräts).', petLevel: 'Stufe', petChar: 'Tama', petCare: 'Satt, glücklich, gesund', petSave: 'Geänderten Spielstand speichern', petKeep: 'unverändert', petKid: 'Kind', petYoung: 'Teen', petAdult: 'Erwachsen', petNow: 'Im Spielstand: Stufe {l}, Tama {c}, Hunger {h}/6, Laune {j}/20{s}.', petSick: ', krank', petOther: 'Der Spielstand ist für eine andere Ausgabe als das geladene ROM.', petNoSet: 'Im Spielstand fehlt der Einstellungsblock.', petDone: '{n} gespeichert. Mit "Spielstand aufs Gerät" übertragen.', petNothing: 'Nichts geändert.', tabSave: 'Spielstand', tabNames: 'Namen', cardNoChars: 'keine Figuren auf dieser Karte', noRoomFrag: 'Passt nicht zusammen: insgesamt wäre genug frei, aber nicht in einem Stück (die WAD von DOOM braucht ein grosses Stück am Stück). Ein Programm entfernen oder DOOM ohne Musik.', noRoomKB: 'Zu wenig Platz: es fehlen etwa {k} KB. Ein Programm entfernen. (Oben bleiben 64 KB für den Schreibschutz frei.)', noRoomAdd: '{n} hat keinen Platz mehr: es fehlen etwa {k} KB. (Oben bleiben 64 KB für den Schreibschutz frei.)', eyeMvT: 'Augen verschieben', mouthMvT: 'Mund verschieben', poseNr: 'Pose {i} von {n}', faceBig: 'Gross', faceSmall: 'Klein', poseOnly: 'Nur diese Pose', poseOnlyHint: 'Die Pfeile verschieben Augen oder Mund nur in der gezeigten Pose. Für eigene Figuren, bei denen einzelne Posen nicht passen.', eyeMvHint: 'Gilt auf dem Feld für Tamas, die nach dem Schreiben schlüpfen oder sich entwickeln. Die kleine Figur rückt halb so weit.', planEyes: 'Augen und Mund', namesHint: 'Namen ändern: Grossbuchstaben, Ziffern, Leerzeichen und . & \' ! ? /. Gilt für alle Sprachen mit lateinischer Schrift auf dem Gerät.', namesFields: 'Felder', namesChars: 'Tamas', namesItems: 'Items', namesFind: 'Suchen', namesUndo: 'Alle zurücksetzen', planNames: 'Namen', planNamesN: '{n} geändert', saveParaOut: 'Paradise-Spielstand (.tamasave)', saveEmuOut: 'TamaEmu-Spielstand (.sav)', saveInfo: 'Exportieren holt die Spielstände aus diesem ROM. Ein Emulator-Spielstand (TamaEmu .sav oder T7Emu .bin) kommt ins ROM, danach das ROM speichern oder aufs Gerät schreiben. Ein Paradise-Spielstand geht direkt aufs Gerät, dafür oben das Gerät verbinden.', saveOutT: 'Exportieren', saveInT: 'Einspielen', saveSecProg: 'Programme', saveSecPara: 'Paradise', saveParaOutB: 'Exportieren (.tamasave)', saveParaInB: 'Aufs Gerät schreiben (.tamasave)', saveProgInfo: 'Exportieren holt den Spielstand des gewählten Programms aus diesem ROM. Einspielen bringt ihn ins ROM, danach das ROM speichern oder aufs Gerät schreiben.', saveParaInfo: 'Exportieren holt den Paradise-Spielstand aus diesem ROM. Aufs Gerät schreiben geht direkt, dafür oben das Gerät verbinden. Platz: welcher Spielstand.', saveSlotL: 'Platz', slotLive: '{n} (aktiv)', slotEmpty: '{n} (leer)', slotNone: 'Auf diesem Platz ist kein Spielstand.', slotField: 'Der Spielstand ist für {a}, der Platz für {b}.', slotDevOther: 'Das Menü auf dem Gerät passt nicht zum geladenen ROM. Zuerst das ROM vom Gerät laden.', slotSure: 'Der Spielstand kommt auf dem Gerät nach {n} und ersetzt den dortigen. Weiter?', slotDone: 'Fertig: {n} auf dem Gerät ersetzt.', saveNoProg: 'Noch kein Programm im ROM. Ein TamaEmu-Spielstand bringt seinen Emulator mit, T7Emu und T18Emu zuerst im Tab Emulator hinzufügen.', saveBtnOut: 'Exportieren ({f})', saveBtnIn: 'Einspielen ({f})', saveEmuInDone: 'TamaEmu-Spielstand übernommen ({d}). Jetzt das ROM speichern oder aufs Gerät schreiben.', saveEmuOther: 'Im ROM ist TamaEmu für {a}, der Spielstand ist für {b}. Trotzdem übernehmen?', saveNoRoom: 'Für TamaEmu ist in diesem ROM kein Platz.', saveEmuBad: 'Das ist kein passender Spielstand für dieses Programm.', saveNoEmu: 'In diesem ROM ist kein Emulator.', saveDone: '{n} gespeichert.', saveNoClock: '{n} gespeichert. Die Uhr ist nicht dabei, in der App eventuell neu stellen.', devSaveRead: 'Spielstand sichern', devSaveWrite: 'Spielstand aufs Gerät', devSaveHint: 'Sichern holt den Paradise-Spielstand mit Uhr und den Spielstand von TamaEmu oder T7Emu. Aufs Gerät geht nur der Paradise-Spielstand.', devSaveSure: 'Der Spielstand wird auf das Gerät ({ed}) geschrieben und ersetzt den jetzigen. Weiter?', devSaveDone: 'Fertig: {w} Seiten geschrieben. {c} Das Gerät kann neu gestartet werden.', devSaveClock: 'Uhr übernommen.', devSaveClockNo: 'Die Uhr bitte am Gerät stellen.', devSaveGot: 'Gesichert: {n}.', fl_saveOtherEd: 'der Spielstand ist von einer anderen Ausgabe ({s}), das Gerät ist {d}', fl_saveFamily: 'der Spielstand passt nicht zu dieser Ausgabe', fl_saveNoSettings: 'im Spielstand fehlt der Einstellungsblock, das ist kein vollständiger Paradise-Spielstand', fl_saveOutside: '{n} Seiten liegen ausserhalb des Spielstands und werden nicht geschrieben', fl_saveIncomplete: 'der Spielstand enthält nicht alle Seiten, fehlende bleiben wie auf dem Gerät', emuUndo: 'Auswahl zurücknehmen', progMain: 'Start mit A und C', progMainL: 'Erster Eintrag im Menü', progMenu: 'Start im Menü', progGone: 'wird entfernt', progUndo: 'Zurücknehmen', progDel: 'Entfernen', progNone: 'Noch kein Emulator. Firmware oder ROM wählen, jedes weitere kommt ins Menü.', appBadMain: '{f}: Farb-Tama- und TG18-Firmware gehen als weiteres Programm nur im Startgerät. Sonst erst den Emulator oben mit × entfernen.', emuInList: 'Im ROM als weitere Programme: {n}. Nicht nochmals wählen.', doomLinkLess: ', mit DOOM {m} MB weniger', emuPack: 'Firmware packen', emuPackHint: 'Spart Platz (bei iD L rund 1 MB), dafür können manche Orte im Spiel langsamer laufen, zum Beispiel das Restaurant.', packNeed: 'Diese Firmware passt hier nur gepackt: in der Zeile von TamaEmu "Firmware packen" einschalten.', packTip: ' Tipp: bei TamaEmu "Firmware packen" einschalten spart Platz.', emuNfc: '4U: NFC-Chip nachbilden', emuNfcHint: 'Das Menü reagiert auf einen Druck. Ohne Haken wie bisher.', emuClock: 'Uhr beim Start vom Paradise übernehmen', emuClockHint: 'Bei jedem Start gilt die Zeit des Paradise. Die Zeit dazwischen wird nicht nachgespielt.', emuAuto: 'Beim Einschalten starten', emuAutoHint: 'Rad lange drücken: zurück ins Paradise, es bleibt dort. Wieder in den Emulator: A und C oder Reset-Knopf.', autoHintL: 'Startet beim Einschalten statt des Menüs. B beim Einschalten halten: Menü.', emuHas: 'In diesem ROM ist ein Emulator eingebaut.', emuBig: 'Diese Firmware ist gross: der Feldwechsel im Menü hat daneben keinen Platz.', emuUp: 'Beim Speichern kommt die neue Emulator-Version hinein. Mit "Spielstände behalten" bleibt der Spielstand.', + emuOk: 'Firmware erkannt ({size}). Sie wird beim Speichern eingebaut.', emuBad: 'Firmware nicht erkannt: {e}', t18Ok: 'TG18-Firmware erkannt (T18Emu, Meets/On). Sie wird beim Speichern eingebaut.', t18Has: 'In diesem ROM ist T18Emu eingebaut.', t18Use: 'Starten: auf dem Heimbildschirm A und C zusammen halten. Zurück: Rad lange drücken (speichert). Hängt T18Emu: mit A und C starten, loslassen, in den ersten 3 Sekunden das Rad drücken und mit A bestätigen. Dann startet die Firmware neu ab ihrem eigenen Spielstand. Experimentell: das Tama läuft noch langsamer als echt.', + emuGone: 'Emulator wird beim Speichern entfernt.', emuMissing: 'In dieser Ausgabe fehlt das Emulator-Programm.', + emuFail: 'Emulator nicht eingebaut: {e}', savedEmu: 'Gespeichert: {name}', + t18Pics: 'Bilder für Erwachsen', t18PicsPick: 'Bilder wählen', t18PicsDel: 'Bilder entfernen', t18PicsOk: '{n} Bilder übernommen.', t18PicsUnknown: '{f}: unbekannter Name', t18PicsHint: 'Am Gerät zeigt Erwachsen dann das Bild der Wahl. PNG-Dateien, Name = Figur (z.B. Mametchi.png, Kuchipatchi.png) oder ihre Nummer (16.png). Der Ordner erwachsen aus dem Android-T18Emu geht auch: alle Dateien samt erwachsen.json wählen. Jede Grösse, wird auf 64x64 verkleinert.', t18Items: 'Items', t18ItemsPick: 'MyMeets-Dateien wählen', t18ItemsNoSave: 'Items gehen, sobald das Spiel einmal gelaufen ist (ROM vom Gerät lesen).', t18ItemsHint: 'Items, Raum und Tamapoints kommen in den Spielstand des Spiels. Beim Schreiben ersetzt das den Spielstand von T18Emu auf dem Gerät, auch mit «Spielstände behalten». Das Tama bleibt, der laufende Stand fängt neu an.', t18ItemsNone: 'Keine Items in den Dateien gefunden.', t18ItemsOther: '{n} ist für {m}, nicht für die Meets/On. Ob es dort geht, ist nicht sicher.', t18ItemsFull: 'kein Platz mehr', mmTitle: 'MixingMeets (Besuch, Heirat)', uartBusy: 'Paramix Studio ist noch mit dem Dongle verbunden. So lange geht die Brücke nicht.', uartFree: 'UART freigeben', uartFreed: 'Dongle freigegeben. Das Paradise neu starten, damit das Spiel wieder läuft.', uartRun: 'Erst warten, bis das Gerät fertig ist.', pairTitle: 'Zwei Paradise verbinden (Besuch, Spiel)', pairHint: 'Beide Paradise oben zusammenstecken, an beiden T18Emu starten. Dann an beiden CONNECTION, TAMAGOTCHI und weiter wie bei zwei Tamas.', pairHintDigi: 'Beide Paradise oben zusammenstecken, an beiden V1Emu mit Digimon starten. Dann den Kampf wählen und starten wie bei zwei echten Digimon.', pairHintPs: 'Beide Paradise oben zusammenstecken, an beiden TamaEmu (P\'s) starten. Dann an beiden Verbindung, たまごっちP\'s, あそぶ. Am einen あそびにいく, am anderen ともだちをよぶ, ふたりで, ein Spiel, dann B.', pairHintIdl: 'Beide Paradise oben zusammenstecken, an beiden TamaEmu (iD L) starten. Dann an beiden die Verbindung im Spiel wählen wie bei zwei echten iD L.', pairHintV3: 'Beide Paradise oben zusammenstecken, an beiden V3Emu starten. Dann an beiden die Verbindung im Spiel wählen wie bei zwei echten V3.', pairHintT7: 'Beide Paradise oben zusammenstecken, an beiden T7Emu (Tama-Go) starten. Dann an beiden Verbindung, TAMA-GO, VISIT oder GAME. Am Gerät, das besuchen geht, B drücken.', mmLink: 'Paramix-Brücke', mmDrag: 'In die Lesezeichenleiste ziehen, dann auf mixing-meets.com anklicken.', mmHint: '1. Den Knopf Paramix-Brücke einmal in die Lesezeichenleiste ziehen (Chrome oder Edge).\n2. Paramix Studio vom Dongle trennen (UART freigeben oder das Studio schliessen). Dongle an die Kontakte wie beim Flashen. Am Tama: CONNECTION, APP, VISIT (zum Zurückholen: A drücken, GO BACK, YES).\n3. Auf mixing-meets.com Connect oder Return öffnen, das Lesezeichen anklicken, dann Select Tamagotchi und den Dongle wählen.\nNach jedem Seitenwechsel das Lesezeichen nochmals anklicken.', t7Gp: 'Gotchi Points', t7GpHint: 'Kommt wie ein eingespielter Spielstand ins ROM: das Tama bleibt, der laufende Stand fängt neu an (am Gerät DOWNLOAD wählen).', t18KeepAsk: 'T18Emu: Items oder Tamapoints geändert. Sein Spielstand auf dem Gerät wird durch den aus dem ROM ersetzt (Stand beim Auslesen), auch mit «Spielstände behalten». Weiter?', t18ItemNo: 'Nr. {n}', t18ItemOk: '{n} liegt jetzt bei {k}.', t18Points: 'Tamapoints', t18A_food: 'Essen', t18A_item: 'Gegenstände', t18A_acc: 'Accessoires', t18A_room: 'Raum', t18RoomBack: 'eigener Raum weg', t18RoomBuiltin: 'eingebauter Raum', dlcPick: 'Download-Inhalte hinzufügen', dlcInfo: 'Belegte Plätze zeigen', progMore: 'Einstellungen und Inhalt', progMakeMain: 'Zum Hauptprogramm machen', progIsMain: 'Hauptprogramm', v1Ok: 'Erstes Tamagotchi oder Digimon erkannt (V1Emu).', v3Ok: 'Tamagotchi Connection V3 erkannt (V3Emu).', v3Use: 'Starten: auf dem Heimbildschirm A und C zusammen halten. Rad kurz: Einstellungen. Zurück: Rad lange drücken.', optVol: 'Lautstärke', optVolN: 'normal', optVolQ: 'leise', optVolL: 'laut', optOff: 'aus', optDim: 'Helligkeit', optScr: 'Bild aus nach', optDev: 'Auch am Gerät: Rad kurz drücken. Dort Geändertes gilt, bis du es hier wieder änderst.', optScrToy: 'wie am Tama', v1Use: 'Starten: auf dem Heimbildschirm A und C zusammen halten. Rad kurz: Einstellungen. Rad drehen: schütteln. Zurück: Rad lange drücken.', progNoMainDoom: 'DOOM ist das Hauptprogramm. Für ein anderes zuerst DOOM entfernen (×).', doomAutoHint: 'Rad 2 s drücken: zurück ins Paradise, es bleibt dort.', progReplaced: '{n} ist jetzt das Hauptprogramm statt {o}.', mainAuto: '{n} ist jetzt der erste Eintrag im Menü, nur so passt alles.', mainNoRoom: 'Als erster Eintrag fehlen etwa {k} KB Platz. Es bleibt wie es war.', appTwice: '{n} ist schon dabei.', progNoMainV1: 'V1Emu startet nur aus dem Menü', progNoMain: 'Geht nur im Startgerät', progMainNow: '{n} ist jetzt das Hauptprogramm. Die Spielstände der getauschten Programme fangen neu an.', dlcLoading: 'Wird gelesen…', dlcNewArea: 'Der Speicher dieses Emulators wird dafür neu eingeteilt. Sein Spielstand fängt nach dem Schreiben neu an.', dlcHint: 'Essen, Kleider, Accessoires, Spiele usw. als .jpg-Download-Dateien oder .zip. Mehrere Dateien auf einmal gehen, bei P\'s einen VDP-Satz immer ganz.', dlcFreeN: '{n} frei', dlcDel: 'entfernen', dlcK0: 'Mahlzeiten', dlcK1: 'Snacks', dlcK2: 'Kleider', dlcK3: 'Accessoires', dlcK4: 'Gegenstände', dlcK5: 'Alltagsdinge', dlcK6: 'Hintergründe', dlcK7: 'Spiele', dlcK8: 'Ausflugsziele', dlcK10: 'VDP-Rezepte', dlcK15: 'Dekorationen', dlcK16: 'Gutscheine', dlcK17: 'Bingo', dlcK18: 'Gashapon', dlcK19: 'Figuren', dlcOk: '{n} liegt jetzt in {k}, Platz {s}.', dlcBad: '{f}: {e}', dlcGone: '{n} entfernt.', + figField: 'Feld:', figAll: 'alle', zipField: 'Feld als ZIP', fieldZipOk: '{f}: {n} Figuren und {s} Bilder als ZIP.', fieldIn: 'Feld aus ZIP übernehmen', fieldInBad: 'Kein Feld-ZIP (field.json fehlt).', fieldInOk: '{src} in {dst} übernommen: {n} Teile.', fieldInEyes: '{k} Figuren bleiben original, ihre Augenbilder sind hier zu gross.', + zipFigs: 'Alle Figuren als ZIP', zipAll: 'Alle Sprites als ZIP', upload: 'Sheets hochladen (PNG oder ZIP)', + numbers: 'Nummern-Test-ROM', + figHint: 'Eine Figur besteht aus Körper, Augen und Mund, je gross und klein. Klick auf eine Figur für ihr Sheet.', + allHint: 'Hintergründe, Menüs, Gegenstände, Schriften.', + moreColors: 'Mehr Farben erlauben (bis 256)', + dimLoad: 'Karte laden', dimHint: 'Abbild einer Figurenkarte (4 MB) oder einer TamaSma-Karte (1 oder 2 MB). Kartenfiguren ersetzen am besten Erwachsene. Baby, Kind und Teen teilen sich die Augen und bleiben original.', + dimPick: 'Kartenfigur', dimTarget: 'ersetzt Figur', dimApply: 'Einsetzen', dimEgg: 'Ei der Karte einsetzen', + dimBaby: 'Baby', dimNone: 'Lade eine Karte, um ihre Figuren zu sehen.', + download: 'Sheet herunterladen', uploadOne: 'Sheet hochladen', reset: 'Original wiederherstellen', close: 'Schliessen', + working: 'Einen Moment …', + dimNr: 'Nr.', stUpd: 'wird aktualisiert', + disclaimer: 'Benutzung auf eigene Gefahr. Das Ändern und Beschreiben des Geräts kann es unbrauchbar machen oder Spielstände löschen. Lies vorher ein Backup aus und nutze das Tool nur, wenn du weisst, was du tust. Es gibt keine Garantie und keine Haftung für Schäden an Geräten oder Daten.', + trademarks: 'Tamagotchi und Digimon sind Marken von BANDAI. DOOM und Wolfenstein sind Marken von id Software (ZeniMax Media). Game Boy und Pokémon mini sind Marken von Nintendo, SEGA und Master System sind Marken von SEGA. Arduboy ist eine Marke von Arduboy Inc. Alle Marken, Spiele und Figuren gehören ihren jeweiligen Inhabern und werden nur genannt, um zu beschreiben, wofür das Tool gedacht ist. Kein offizielles Produkt, keine Verbindung zu diesen Firmen. Das Tool enthält keine Spiele, Firmware oder Spieldaten: du verwendest nur deine eigenen Dateien.', + devWarn: 'Schreiben auf das Gerät geschieht auf eigene Gefahr und ohne Haftung. Vorher ein Backup auslesen und das Gerät während des Schreibens eingeschaltet lassen.', + footer: 'Läuft lokal im Browser. Von mameise.', + edition: 'Edition', sprites: 'Sprites', figures: 'Figuren', changed: 'geändert', space: 'Platz für Figuren', + figure: 'Figur', sprite: 'Sprite', + mSize: 'Zelle {w}×{h}, {n} Bilder, Raster {iw}×{ih}', mColors: '{c}, Palettensätze: {p}', + mDirect: 'Direktfarbe RGB565', mPal: '{n} Farben', mKeep: 'Mehrere Palettensätze (Farbvarianten): beim Hochladen werden die Originalfarben benutzt.', + mSheet: 'Sheet {w}×{h} px. Grösse nicht ändern, sonst passt das Raster nicht mehr.', + mGroupRows: 'Zeilen: Körper (20), Augen (20), Mund (18), Körper klein (24), Augen klein (14), Mund klein (14).', + notRom: 'Das ist kein Paradise-Abbild: {e}', loaded: '{ed} geladen: {s} Sprites, {f} Figuren.', + saved: 'Gespeichert: {name}\n{n} Sprites geändert, noch {kb} KB frei.', nothing: 'Noch nichts geändert.', + tooBig: 'Zu gross für den freien Platz. {e}', + upOk: 'Übernommen: {n}', upSkip: 'Übersprungen: {list}', upNone: 'Keine passenden Dateien gefunden. Erwartet: figur_0237.png oder sprite_0014.png.', sprSix: 'Feldbild der zusätzlichen Felder, nicht änderbar.', + wrongSize: '{f}: {e}', resetOk: 'Original wiederhergestellt.', dimOk: 'Kartenfigur {d} sitzt jetzt in Figur {g}.', eggOk: 'Ei ersetzt.', + numOk: 'Jede Figur zeigt jetzt ihre Nummer. Speichern, aufspielen, aufziehen und notieren, welche Nummer in welcher Stufe kommt.', + notDim: 'Diese Karte kenne ich nicht: {e}', leave: 'Es gibt ungespeicherte Änderungen.', + roleFallback: 'Ersatzfigur', roleBaby: 'Baby', roleAdult: 'erster Erwachsener', + eyeHint: 'Pinker Rahmen = Auge. Es wandert in die Augenebene, damit die Figur blinzelt und die Zelle Augen hat. Falsch? Aufs Auge klicken.', + eyeNone: 'Figur hat keine sichtbaren Augen', dimEyesTooBig: 'Die Augen waren zu detailreich, die Figur bleibt ohne Augenebene.', + roleFallbackText: 'erscheint, wenn das Spiel eine Figur nicht laden kann. Am besten unverändert lassen.', + roleBabyText: 'schlüpft aus dem Ei.', roleAdultText: 'ab hier hat jede Figur eigene Augen.', + mEyes: 'Augen behalten ihre Bytegrösse, sonst schlüpft die Ersatzfigur. Zu detailreiche Augen werden abgelehnt.', + mColorsFig: 'Bleiben alle Farben aus dem Original, färbt das Spiel die Figur weiter je nach Tama um. Neue Farben werden fest (bis 8 Farben plus Umriss).', + }, + en: { + open: 'Open ROM', save: 'Save new ROM', + startTitle: 'Get more out of your Tamagotchi Paradise', + startText: 'Paramix Studio rebuilds your own Paradise ROM. Load your Paradise dump (16 MB flash image) or read it straight from the device, pick what to add, and write the new ROM back.', + featHead: 'What you can do', + g1t: 'Tamagotchi emulators', g1: 'Colour tamas (iD, iD L, Plus Color, P\'s, 4U, 4U+), Tama-Go with figures, Friends, Meets and On, Connection V3, P1, P2, Angel and more first Tamagotchis plus Digimon V1 and V2. Several together in the menu, each with its own save. Bring your own ROMs.', + g2t: 'DOOM and Wolfenstein 3D', g2: 'DOOM, Wolfenstein 3D and Spear of Destiny on the Paradise, with your own key layout. Bring your own game files.', + g7t: 'Game consoles', g7: 'Game Boy, Game Boy Color, Master System, Game Gear, Pokémon mini and Arduboy, with sound and saves. Your own games go into the menu.', + g3t: 'All fields', g3: 'All six fields in one ROM, with pictures, special characters, the matching planet and the field\'s lab games.', + g4t: 'Menu on the device', g4: 'Switch fields, put items in the bag, set Tamapoints, change the Tama and keep several saves, right on the Paradise. Play time in the games earns Tamapoints.', + g8t: 'Start device without the Paradise', g8: 'Almost the whole 16 MB for emulators and games. Any program can start first, the clock is set in the menu.', + g5t: 'Read and write the device', g5: 'Back up the ROM and write the new one with a USB UART dongle. Saves are kept, only changes are written. A write protection helps when writing is cut off.', + g6t: 'Your own characters', g6: 'Every character as an image sheet to edit, Digimon from DIM cards too. Colours and eyes are fitted automatically.', + g9t: 'Saves and visits', g9: 'Back up, restore and edit saves, add download content. Visits between two Paradise through the plug at the top, or a simulated visit over the dongle.', + dropTitle: 'Drop a ROM here or click', + dropText: 'Land, Water, Sky, Jade Forest, Tropical and Glacier are recognised.', + f1t: 'Editing and backups', f1: 'Files are edited locally. Reading a full ROM privately backs up missing editions on the server before downloading to your PC. One per edition; publication requires administrator approval.', + f2t: 'Nothing borrowed inside', f2: 'Paramix Studio contains no ROM, no firmware and no WAD. Everything comes from your own devices and files.', + f3t: 'Checked', f3: 'Checksums are recalculated, changed images are read back before saving and every sector written to the device is verified.', + planTitle: 'Your new ROM', planFig: 'Characters', planEmu: 'Emulator', planEmus: 'Emulators', planDoom: 'DOOM', planWolf: 'Wolfenstein 3D', planGb: 'Game Boy', planSms: 'Master System / Game Gear', planPm: 'Pokémon mini', planMenu: 'Menu', planApps: 'More emulators', + stNone: 'not included', stKeep: 'stays', stNew: 'new', stDel: 'will be removed', stChanged: '{n} changed', stSame: 'unchanged', + segFw: 'Firmware and characters', segEmu: 'Emulator', segDoom: 'DOOM', segWolf: 'Wolfenstein 3D', segGb: 'Game Boy', segSms: 'Master System / Game Gear', segPm: 'Pokémon mini', segSlots: 'Field saves', segSave: 'Save', segFree: 'free', segResv: 'reserved', + ruleBoth: 'Emulator or DOOM: only one of the two fits into the ROM. The menu works with both.', + ruleNoRoom: 'This edition has no room for emulator and DOOM (its character data is larger). The menu works.', + emuVsDoom: 'Note: DOOM is chosen or built in. Choosing a firmware here drops DOOM.', + doomVsEmu: 'Note: an emulator is chosen or built in. Choosing a WAD here drops the emulator.', + noRoomApp: 'This edition has no room for it.', a0Menu: 'This edition has no room for a main program at 0x0A0000: every program goes to the menu. The star chooses what starts when switched on.', a0MenuN: 'This edition has no room for a main program at 0x0A0000. Tama-Go, Friends, the old Tamas and the V3 go to the menu (A and C; switch on field switch or items in the Menu tab). Colour Tamas and TG18 work here in a start device only.', a0NoMain: '{f}: colour Tamas and TG18 work in this edition in a start device only (Menu tab).', + doomHas: 'This ROM contains DOOM.', doomOff: 'Remove DOOM', doomGone: 'DOOM is removed on save.', + keysTitle: 'Buttons', kFire: 'Fire', kFwd: 'Forward', kBack: 'Back', kUse: 'Use', kMod: 'Change weapon: hold + wheel', + kWheel: 'Wheel press', kRun: 'Run with 2x forward', kInv: 'Wheel reversed', kFixed: 'Always the same: A+C menu, B+C map. Sound on/off: hold the "Change weapon" key and press the wheel briefly. Back: as set in the Menu tab under "Back from programs".', + kOld: 'This DOOM is older and has no own button layout yet. Build it in again with the WAD.', + help: 'Help', helpTitle: 'How it works', h1t: 'Steps', h1: '1. Open a ROM (file of your own Paradise) or read it straight from the device with "Device".\n2. Choose in the tabs what goes in: figures, emulators, Game Boy, Master System, Pokémon mini, DOOM, Wolfenstein, menu.\n3. Save, or write it to the Paradise with "Device". With "Keep saves" the save on the device stays.', h2t: 'Buttons on the Paradise', hk1: 'A and C', hv1: 'on the home screen: start the menu or the emulator', hk2: 'Wheel long (tab Menu: can be changed)', hv2: 'save the state and go back to the Paradise', hk3: 'Wheel short', hv3: 'T7Emu: settings and figure', hk4: 'Wheel in the first 3 s', hv4: 'drop the saved state (confirm with A), the next start begins fresh from the Tama\'s own save', hk5: 'B when switching on', hv5: 'with autostart: Paradise or menu instead of the main program', hk6: 'Reset button', hv6: 'with autostart: the main program starts again', hk7: 'C when switching on', hv7: 'flash app: the device can be written again with "Device" (way back)', h3t: 'Clock', h3: 'With "Take the clock from the Paradise at the start" (tab Emulator) the emulator sets its clock to the Paradise\'s time at every start. The time in between is not played through. So set the clock on the Paradise.', h4t: 'Coming back', h4: 'The emulator continues exactly where you left with the wheel. The Tama\'s own save stays even when the saved state is dropped.', h5t: 'Menu and fields', h5: 'A and C on the home screen. The wheel selects, B confirms, C goes back. Switching the field packs the save of the old field and brings back the one of the new field.\n6 fields: Tropical and Glacier get Land, Water and Sky from your own ROM, Jade Forest gets Sky. In the game the Tama moves through Planet, Fields. DNA and residents belong to their field.', h8t: 'Start device', h8: 'Tab Menu, start device: the device starts into the menu with all programs. Without the Paradise almost the whole memory is for programs, the clock is set in the menu. The star picks the main program, with autostart it starts when switching on.', h9t: 'Way back', h9: 'If the screen stays black or a program hangs: hold C and put the batteries in (or press the reset button). The flash app starts, the device can be read and written again with "Device". If a write is cut off, the flash app starts by itself.', h6t: 'Backing up saves', h7t: 'Importing a save', h7: '1. Read the ROM fresh with "Device" (or open the one you read last).\n2. Tab Save: import. The save goes to the program it belongs to.\n3. Write to the device with "Keep saves". Only this save is replaced, the Paradise save and those of the other programs stay as on the device.\nWithout "Keep saves" every save comes from the file. Add or remove programs in a write of its own, back up all saves first.', h6: 'Tab Save, or Device, "Back up save". Back up before changing the emulator, the old save is lost then.', device: 'Device', devTitle: 'Device over UART', devHint: 'UART dongle with 3.3 V on the three contacts: left RX from the dongle, middle GND, right TX from the dongle. Open the download screen on the Paradise (Planet, A, Connect, Download, Download), then Connect. Needs Chrome or Edge on a computer.', + devConnect: 'Connect', devDump: 'Back up ROM, then download', devWrite: 'Write new ROM to the device', devOnly: 'Only write changes', devKeep: 'Keep saves', devStop: 'Cancel', + devNoSerial: 'This browser cannot talk to the dongle. Please use Chrome or Edge on a computer.', devNone: 'Not connected.', + fl_noRescueRoom: 'No room for the write protection (rescue start, top 64 KB of the flash). Nothing was written. Remove a program from the start device and write again.', plHint: 'Prolific adapter (PL2303): newer Windows drivers block older and copied PL2303 chips, then no data gets through. Fix: pick the older Prolific driver 3.3.2.x in the Device Manager, or use an adapter with CH340 or CP2102.', resOn: 'Write protection on: if a write is cut off, the device starts in the flash screen.', resModeGo: 'The last write was cut off. The device is in the flash screen and waits. Press "Continue writing".', resModeRom: 'The last write was cut off. The device is in the flash screen and waits. Open the ROM again (or your backup) and write it to the device.', resResume: 'Continue writing', resHalf: 'The last write did not finish. Press "Continue writing" so everything fits together again.', resResumed: 'Done: {w} sectors written. Switch the Paradise off and on.', resTest: 'Test rescue start', resBack: 'Write header back', resSure: 'Test: the rescue start goes to 0xFF0000, then the device header (sector 0) is cleared. Then switch the Paradise off and on. If the flash screen appears, connect here and "Write header back". If it does not, the device will not start without your own flash tool. Go on?', resCleared: 'Header cleared. Switch the Paradise off and on. Flash screen there? Then connect and "Write header back".', resBackDone: 'Header written back. Switch the Paradise off and on: it starts normally again.', resNoHdr: 'No header kept.', devOn: 'Connected: {ed}, {mb} MB{l}', devLoaded: ', flash app loaded', devReady: 'Ready.', devNeedRom: 'To write, open a ROM first (or read one).', + visTitle: 'Simulate a visit (Paradise)', visStart: 'Start', visStop: 'Stop', + visHint: 'The Studio plays a second Paradise. Dongle on the contacts, the Paradise runs normally.\n1. Choose the edition, Start, choose the dongle.\n2. On the Paradise: planet menu, CONNECTION, PLAYDATE, then B.\n"Connect" above is only for the ROM, do not press it for a visit.', + visWait: 'Ready as {ed}. On the Paradise choose PLAYDATE and press B.', visRun: 'Connected, exchanging data…', visPlay: 'The two are playing…', + visDone: 'Visit done ({ed}). For the next one press B on the Paradise again.', visErr: 'Stopped: {e}. Press B on the Paradise again.', visBadKey: 'The Paradise does not understand the data.', + phload: 'Loading flash app', phread: 'Reading', phcompare: 'Comparing', phwrite: 'Writing', phcheck: 'Checking', phprepare: 'Preparing', + devDumped: 'ROM read and saved as {n}. It is now open in the Studio.', + devSure: 'The new ROM is written to the device now. Keep the device switched on while writing. Write at your own risk?', + devSureFull: 'Without "Keep saves" the save on the device is replaced by the one in the ROM. Write anyway?', + carryUnknown: 'The device does not hold the loaded ROM. A program moves and its save on the device cannot be taken along. Read the ROM from the device first. Write anyway?', carryMiss: 'A program moves and its save on the device cannot be taken along. Back it up in the tab Save first. Write anyway?', devEmuLost: 'Main program on the device: {o}. In the new ROM: {n}. So the save of {o} as the main program starts anew. To keep it, back it up first under "Save". Write anyway?', devEmuNone: 'no emulator', devEmuNew: '{o} with a newly chosen firmware', + devDone: 'Done and checked: {w} sectors written{k}. Restart the device (reset or battery).', devKept: ', {k} save sectors kept', + devSame: 'Nothing to write, the device already has this ROM.', devErr: 'Error: {e}', devCancelled: 'Cancelled.', + cleanOn: 'Without the Paradise (clean ROM)', cleanClock: 'Set the clock at the start', cleanClockHint: 'When the clock is missing (new batteries), the menu asks for it when switched on. Without: set the clock in the menu under SETTINGS or in each emulator itself.', emuClockOff: 'Only with "Set the clock at the start" (tab Menu).', emuSess: 'Remember where you left off', emuSessHint: 'The next start continues right there. Without: the game starts anew and loads its own save, as the real device does.', ruleClean: 'Without the Paradise: all programs go to the menu, almost the whole flash is theirs.', cleanHint: 'No Paradise on the device any more, only the menu with your programs. Almost the whole 16 MB is free.', cleanUse: 'After switching on the menu comes up right away. On the first start you set the clock, later under SETTINGS. Leave a program as usual.', cleanWarn: 'The Paradise and its save are lost when writing. Make a backup first.', cleanNoDoom: 'DOOM does not work without the Paradise yet. Please remove DOOM.', doomOne: 'DOOM goes into the menu only once.', cleanSure: 'The device has the Paradise on it. It is deleted, with its save. Do you have a backup of the device? Go on?', cleanLoaded: 'ROM without the Paradise ({ed}) loaded: {n} programs.', + launchOn: 'Start device for programs only', launchHint: 'Only the setup of the Paradise stays (language, clock, continue or new). After it the menu with your emulators and DOOM always comes up. All pictures of the game go, which gives about 5 MB more room.', launchUse: 'After switching on and setting the clock the menu comes up. Wheel selects, B starts. Leave a program as usual, then the menu comes up again.', launchOld: 'This ROM is a start device. Load the original ROM for a normal Paradise.', launchNeed: 'A start device needs at least one program (emulator or DOOM).', launchSix: 'A start device does not go with six fields built in. Please load the original ROM.', planLaunch: 'Start device', + tabFeld: 'Menu', feldOn: 'Several saves (with field choice)', bagOn: 'Items and Tamapoints', tamaOn: 'Change Tama (level, care, character)', gplayOn: 'Play time earns Tamapoints', gplayHint: 'DOOM, Wolfenstein, Game Boy, Master System, Pokémon mini and Arduboy: 10 Tamapoints per minute of play, when going back to the Paradise.', saveSlot: 'Save {n}', + sixOn: 'All 6 fields', sixPick: 'Choose Land, Water or Sky ROM', sixHint: 'Adds Land, Water and Sky to Tropical and Glacier. The field pictures come from your own Land, Water or Sky ROM. The lab games follow the field the Tama starts with in the menu.', + sixNeed: 'All 6 fields still need a Land, Water or Sky ROM.', sixOk: 'Field pictures taken from {n}.', sixBad: '{n} is not a Land, Water or Sky ROM.', sixIn: 'All 6 fields are built in.', sixOff: 'Saving takes Land, Water and Sky out again. Several saves keep working.', sixOffJ: 'Saving takes Sky out again. Several saves keep working.', sixOffField: 'The device is on {f} now. First switch to {s} in the menu.', sixOffSlots: 'The saves stored in the menu are deleted. Continue?', sixFail: 'Fields not built in: {e}', sixNoFw: 'The firmware of this ROM is changed, more fields do not work here.', planSix: 'More fields', sixOnJ: 'Sky as 4th field', sixHintJ: 'Jade Forest already has the Sky pictures.', sixInJ: 'Sky is built in as the 4th field.', sixOld: 'All 6 fields are built in, but an older version. Choose your Land, Water or Sky ROM and everything is updated when you save.', sixOldJ: 'Sky is built in and is updated when you save.', sixPlanet: 'Planet to match the field', sixMenu: 'Game menu Fields: all fields from level 4', sixPlanetNeed: 'Changing this setting needs your Land, Water or Sky ROM again.', sixApp: 'DOOM and the emulator do not fit with it', + exitKey: 'Back from programs', exitHint: 'How to get from all programs (emulators and games) back to the Paradise or the menu.', exit0: 'Hold the wheel', exit1: 'Hold wheel and A', exit2: 'Hold wheel and C', exit3: 'Hold the wheel 5 s', feldHint: 'Small menu in the ROM: switch between saves (a new save on a field of your choice), put items in the bag, set Tamapoints, change the Tama.', + feldUse: 'Open: hold A and C together on the home screen. Wheel selects, B confirms, C goes back.', + feldNo: 'Field switch works with Land, Water, Sky (among each other) and Tropical, Glacier (among each other).', feldMissing: 'This build does not contain the menu.', + feldCur: 'Active field: {f}.', feldList: 'Selectable: {s}.', feldStored: 'Saved: {s}.', feldFail: 'Menu not built in: {e}', feldUnknown: 'Edition not recognised.', + tabWolf: 'Wolf3D', wolfPick: 'Choose game files', wolfHint: 'Choose all files of Wolfenstein 3D together: shareware (.WL1), full version (.WL6) or Spear of Destiny (.SOD). The game goes into the Paramix menu.', wolfNone: 'No game files chosen yet.', wolfShare: 'Shareware', wolfFull: 'Full version', wolfEps: '{n} episodes', wolfEp1: '1 episode', wolfBad: 'Wolfenstein 3D: {e}', wolfNoMain: 'Wolfenstein 3D only in the menu', wolfTurn: 'Turn per wheel step', wolfFixed: 'Always the same: A+C menu. Back (the game is saved): as set in the Menu tab under "Back from programs".', wolfOne: 'There is only one Wolfenstein 3D and one Spear of Destiny in the menu, the new one replaces the old one.', wolfSodN: '21 floors', + tabGb: 'Game Boy / Color', gbNoMain: 'Game Boy only in the menu', gbPick: 'Choose games (.gb, .gbc)', gbHint: 'The games go into the Paramix menu. On the device: A+B+C together opens the settings (also Select and sound). Hold the wheel for 2 s to save and go back, the next start continues there. Two Paradise plugged together at the top work like a link cable, e.g. to trade Pokémon.', gbNone2: 'No game chosen yet.', gbKeysTitle: 'Keys', gbKeysDef: 'Default', gbKeysMiss: 'Not assigned: {n}', gbNone: '–', gbRight: 'Right', gbLeft: 'Left', gbUp: 'Up', gbDown: 'Down', gbInA: 'Key A', gbInB: 'Key B', gbInC: 'Key C', gbInWp: 'Wheel press', gbInWu: 'Wheel up', gbInWd: 'Wheel down', gbInAC: 'A + C', gbInBC: 'B + C', gbInAB: 'A + B', gbBad: '{f}: not a Game Boy game', gbColor: '{f}: Game Boy Color only, that does not work', gbNeedRom: 'Open a ROM first (or read it from the device).', t7Old: '{n}: old version, the save can be lost when the battery is changed. Write it again now with "Keep saves".', t18Broken: 'Tama Meets is damaged. Remove Tama Meets and add the firmware again, then write without "Keep saves".', t18Clash: 'the main program would need the room of Tama Meets. Remove Tama Meets first.', tabSms: 'Master System / Game Gear', tabPm: 'Pokémon mini', smsNoMain: 'Master System and Game Gear only in the menu', pmNoMain: 'Pokémon mini only in the menu', abNoMain: 'Arduboy only in the menu', planAb: 'Arduboy', segAb: 'Arduboy', tabAb: 'Arduboy', abPick: 'Choose games (.hex, .zip)', abHint: 'The games go into the Paramix menu. On the device: A+B+C together opens the settings (also picture size and sound). Hold the wheel for 2 s to save and go back, the next start continues there.', abBad: '{f}: not an Arduboy game', abBig: '{f}: too big for the Arduboy', smsPick: 'Choose games (.sms, .gg)', smsHint: 'The games go into the Paramix menu. On the device: A+B+C together opens the settings (also Pause and sound). Hold the wheel for 2 s to save and go back, the next start continues there.', smsBad: '{f}: not a Master System or Game Gear game', smsGG: '{f}: Game Gear game, that does not work', smsB1: 'Button 1', smsB2: 'Button 2', smsPause: 'Pause / Start', pmPick: 'Choose games (.min, .zip)', pmHint: 'The games go into the Paramix menu. On the device: A+B+C together opens the settings (also Power and sound). Hold the wheel for 2 s to save and go back, the next start continues there.', pmBad: '{f}: not a Pokémon mini game', pmBig: '{f}: bigger than 1 MB, that does not work', pmBiosPick: 'Choose own BIOS', pmBiosDel: 'Remove own BIOS', pmBiosFree: 'Without an own BIOS the free BIOS of PokeMini runs. Some games run better with the real BIOS.', pmBiosOwn: 'Own BIOS chosen, it is used for all Pokémon mini games.', pmBiosBad: '{f}: not a Pokémon mini BIOS', pmA: 'A', pmB: 'B', pmC: 'C', pmPower: 'Power', pmShake: 'Shake', + tabFigs: 'Characters', tabAll: 'All sprites', tabDim: 'Card', tabEmu: 'Emulator', tabDoom: 'DOOM', + doomPick: 'Choose DOOM.WAD', doomEp: 'Episode', doomMusic: 'Music', + doomHint: 'Builds DOOM into the ROM. Bring your own WAD, it stays on your computer.', + doomUse: 'Start: in the Paramix menu, with the Paradise also by holding A and C together on the home screen. Back: as set in the Menu tab under "Back from programs".', + doomNone: 'No WAD chosen.', doomOk: 'WAD recognised ({eps}). DOOM is built in on save.', doomEpsHint: 'Without the Paradise: each ticked episode goes into the menu as its own entry (DOOM E1, DOOM E2 ...), with its own save.', doomWhole: 'Whole WAD as one entry', pwadPick: 'Choose extra WAD', pwadOff: 'Remove extra WADs', doomPwads: 'With: {n}.', pwadNeedD2: '{n} is for DOOM II: choose DOOM2.WAD first.', pwadNeedD1: '{n} is for DOOM or Ultimate DOOM: choose DOOM.WAD first.', doomPwadPara: 'Own episodes (like Sigil) only go without the Paradise.', doomPwadBig: '{n}: the maps {m} are probably too big for the Paradise\'s memory. DOOM then shows a line with a 9, holding the wheel 2 s goes back to the menu.', doomPwadHint: 'Own episodes (like Sigil) go into the menu as their own entry, tick them for that. Together with the whole WAD they are mostly too big.', doomD2Clean: 'DOOM II only goes into a ROM without the Paradise.', doomD2Hint: 'DOOM II goes into the menu as one entry. It needs almost all the room and only fits without music.', doomWholeHint: 'All episodes in one entry "DOOM", the episode is chosen in the game. Needs much less room than one by one.', + doomBad: 'WAD not recognised: {e}', doomFail: 'DOOM not built in: {e}', doomMissing: 'This build does not contain the DOOM program.', + doomBoth: 'Emulator and DOOM do not fit into one ROM together. Please choose only one.', + doomBig: 'No episode of this WAD fits into the ROM.', doomNoMusic: 'This episode only fits without music.', + emuPick: 'Choose firmware or ROM', emuOff: 'Remove emulator', + emuHint: 'Colour tamas (TamaEmu), Tama-Go and Friends (T7Emu), Meets and On (T18Emu), first Tamagotchis and Digimon (V1Emu), Connection V3 (V3Emu). The first is the main program, every further one goes to the menu. The filled star marks the main program, a click on an empty star makes another one the main program. Bring your own files.', t7Ok: 'V7 ROM recognised (T7Emu). It is built in on save.', t7OkFr: 'Tamagotchi Friends recognised (T7Emu, test). It is built in on save. There are no figures for it.', t7Has: 'This ROM contains T7Emu.', t7HasFr: 'This ROM contains T7Emu with Tamagotchi Friends.', t7Use: 'Start: hold A and C together on the home screen. Back: hold the wheel (saves). Wheel short: settings and figure. If T7Emu hangs: start with A and C, release them and press the wheel within the first 3 seconds and confirm with A.', t7FigPick: 'Add figures', t7FigNone: 'No figures yet.', t7FigBad: '{f}: not a figure.', t7FigFull: 'No room left for {f}.', t7FigMax: 'No room for more figures.', t7FigDup: '{f} is already in.', appPick: 'Add another emulator', appHint: 'One more Tama-Go or Friends ROM (T7Emu). Started from the menu (A and C), so something in the Menu tab must be switched on.', appNone: 'No other emulators.', appBad: '{f}: not a Tama-Go or Friends ROM.', appBadL: '{f}: neither a Tama-Go or Friends ROM nor a colour Tama or TG18 firmware.', appT18One: 'T18Emu goes only once per ROM.', appHintL: 'In a start device: Tama-Go or Friends ROM, colour Tama firmware (TamaEmu) or TG18 firmware (T18Emu, once only).', ruleLaunch: 'Start device: emulators and DOOM fit together as long as there is room.', appMax: 'At most 12 more emulators.', appNeedMenu: 'More emulators start from the menu: switch on the field switch or items in the Menu tab.', appFail: 'More emulators: {e}', appSix: 'Six fields do not go together with more emulators.', t7SaveBtn: 'T7Emu save (.bin)', saveFor: 'Program', saveMain: 'Main emulator', v1SaveBtn: 'V1Emu save (.bin)', saveT18No: 'T18Emu: backing up its save is not possible here yet.', saveNoBatt: 'This game keeps no save on its cartridge.', saveNone: 'No save yet.', saveWrongFile: 'This file does not fit {n}.', saveCartIn: 'Save for {n} taken over. Now save the ROM or write it to the device. A kept game state is dropped.', t7SaveXDone: 'Save for {n} taken over. Now save the ROM or write it to the device.', t7NoSave: 'The Tama has no save yet.', t7SaveInDone: 'T7Emu save taken over. Now save the ROM or write it to the device.', t7SaveNeed: 'T7Emu is missing in the ROM: add the Tama-Go ROM in the Emulator tab first.', saveT18Need: 'T18Emu is missing in the ROM: add the TG18 firmware in the Emulator tab first.', saveEmuAny: 'Emulator save (.sav / .bin)', + emuUse: 'Start: hold A and C together on the home screen. Back: hold the wheel (saves). If TamaEmu hangs: start with A and C, release them and press the wheel within the first 3 seconds and confirm with A. It then starts over from the save the Tama keeps itself.', + emuNone: 'No emulator chosen.', petT: 'Change save', petOpen: 'Open Paradise save', petRom: 'Save in the ROM', petClose: 'Close', petRomDone: 'Changed in the ROM. Now save the ROM or write it to the device (without "Keep saves", otherwise the device keeps its save).', petLevel: 'Level', petChar: 'Tama', petCare: 'Fed, happy, healthy', petSave: 'Save changed save', petKeep: 'unchanged', petKid: 'Kid', petYoung: 'Teen', petAdult: 'Adult', petNow: 'In the save: level {l}, Tama {c}, hunger {h}/6, happiness {j}/20{s}.', petSick: ', sick', petOther: 'The save is for another edition than the loaded ROM.', petNoSet: 'The settings block is missing in the save.', petDone: '{n} saved. Send it with "Save to device".', petNothing: 'Nothing changed.', tabSave: 'Save', tabNames: 'Names', cardNoChars: 'no characters on this card', noRoomFrag: 'Does not fit together: there would be enough room in total, but not in one piece (the DOOM WAD needs one big piece). Remove a program or build DOOM without music.', noRoomKB: 'Not enough room: about {k} KB missing. Remove a program. (The top 64 KB stay free for the write protection.)', noRoomAdd: 'No room left for {n}: about {k} KB missing. (The top 64 KB stay free for the write protection.)', eyeMvT: 'Move the eyes', mouthMvT: 'Move the mouth', poseNr: 'Pose {i} of {n}', faceBig: 'Big', faceSmall: 'Small', poseOnly: 'This pose only', poseOnlyHint: 'The arrows move eyes or mouth only in the pose shown. For your own figures where single poses do not fit.', eyeMvHint: 'Applies on the field to Tamas that hatch or grow after writing. The small figure moves half as far.', planEyes: 'Eyes and mouth', namesHint: 'Change names: capitals, digits, space and . & \' ! ? /. Applies to every language with Latin letters on the device.', namesFields: 'Fields', namesChars: 'Tamas', namesItems: 'Items', namesFind: 'Search', namesUndo: 'Reset all', planNames: 'Names', planNamesN: '{n} changed', saveParaOut: 'Paradise save (.tamasave)', saveEmuOut: 'TamaEmu save (.sav)', saveInfo: 'Export takes the saves out of this ROM. An emulator save (TamaEmu .sav or T7Emu .bin) goes into the ROM, then save the ROM or write it to the device. A Paradise save goes straight to the device, connect it above for that.', saveOutT: 'Export', saveInT: 'Import', saveSecProg: 'Programs', saveSecPara: 'Paradise', saveParaOutB: 'Export (.tamasave)', saveParaInB: 'Write to device (.tamasave)', saveProgInfo: 'Export takes the save of the chosen program out of this ROM. Import puts it into the ROM, then save the ROM or write it to the device.', saveParaInfo: 'Export takes the Paradise save out of this ROM. Write to device goes straight to the device, connect it above for that. Slot: which save.', saveSlotL: 'Slot', slotLive: '{n} (active)', slotEmpty: '{n} (empty)', slotNone: 'There is no save in this slot.', slotField: 'The save is for {a}, the slot for {b}.', slotDevOther: 'The menu on the device does not match the loaded ROM. Load the ROM from the device first.', slotSure: 'The save goes into {n} on the device and replaces the one there. Continue?', slotDone: 'Done: {n} replaced on the device.', saveNoProg: 'No program in this ROM yet. A TamaEmu save brings its emulator along, add T7Emu and T18Emu in the Emulator tab first.', saveBtnOut: 'Export ({f})', saveBtnIn: 'Import ({f})', saveEmuInDone: 'TamaEmu save taken over ({d}). Now save the ROM or write it to the device.', saveEmuOther: 'The ROM has TamaEmu for {a}, the save is for {b}. Take it anyway?', saveNoRoom: 'This ROM has no room for TamaEmu.', saveEmuBad: 'This is not a fitting save for this program.', saveNoEmu: 'This ROM has no emulator.', saveDone: '{n} saved.', saveNoClock: '{n} saved. The clock is not included, set it in the app if needed.', devSaveRead: 'Back up save', devSaveWrite: 'Save to device', devSaveHint: 'Back up takes the Paradise save with the clock and the save of TamaEmu or T7Emu. Only the Paradise save goes to the device.', devSaveSure: 'The save is written to the device ({ed}) and replaces the current one. Continue?', devSaveDone: 'Done: {w} pages written. {c} The device can be restarted.', devSaveClock: 'Clock taken over.', devSaveClockNo: 'Please set the clock on the device.', devSaveGot: 'Backed up: {n}.', fl_saveOtherEd: 'the save is from another edition ({s}), the device is {d}', fl_saveFamily: 'the save does not fit this edition', fl_saveNoSettings: 'the settings block is missing, this is not a complete Paradise save', fl_saveOutside: '{n} pages lie outside the save and are not written', fl_saveIncomplete: 'the save does not hold every page, missing ones stay as on the device', emuUndo: 'Undo choice', progMain: 'Starts with A and C', progMainL: 'First entry of the menu', progMenu: 'Starts from the menu', progGone: 'will be removed', progUndo: 'Undo', progDel: 'Remove', progNone: 'No emulator yet. Choose firmware or ROM, every further one goes to the menu.', appBadMain: '{f}: colour Tama and TG18 firmware go as a further program only in a start device. Otherwise remove the emulator above with × first.', emuInList: 'In the ROM as further programs: {n}. No need to choose them again.', doomLinkLess: ', {m} MB less with DOOM', emuPack: 'Pack the firmware', emuPackHint: 'Saves room (about 1 MB for an iD L), but some places in the game can run slower, for example the restaurant.', packNeed: 'This firmware only fits here packed: switch on "Pack the firmware" in the row of TamaEmu.', packTip: ' Tip: "Pack the firmware" for TamaEmu saves room.', emuNfc: '4U: emulate the NFC chip', emuNfcHint: 'The menu reacts to one press. Unticked it works as before.', emuClock: 'Take the clock from the Paradise at the start', emuClockHint: 'At every start the Paradise\'s time applies. The time in between is not played through.', emuAuto: 'Start when switched on', emuAutoHint: 'Hold the wheel: back to the Paradise, it stays there. Back into the emulator: A and C, or the reset button.', autoHintL: 'Starts at switching on instead of the menu. Hold B while switching on: menu.', emuHas: 'This ROM contains an emulator.', emuBig: 'This firmware is big: the field switch of the menu has no room next to it.', emuUp: 'Saving puts in the new emulator version. With "Keep saves" the save stays.', + emuOk: 'Firmware recognised ({size}). It is built in on save.', emuBad: 'Firmware not recognised: {e}', t18Ok: 'TG18 firmware recognised (T18Emu, Meets/On). It is built in on save.', t18Has: 'This ROM contains T18Emu.', t18Use: 'Start: hold A and C together on the home screen. Back: hold the wheel (saves). If T18Emu hangs: start with A and C, release them, press the wheel within the first 3 seconds and confirm with A. The firmware then starts over from its own save. Experimental: the Tama still runs slower than the real one.', + emuGone: 'The emulator is removed on save.', emuMissing: 'This build does not contain the emulator program.', + emuFail: 'Emulator not built in: {e}', savedEmu: 'Saved: {name}', + t18Pics: 'Pictures for grow up', t18PicsPick: 'Choose pictures', t18PicsDel: 'Remove pictures', t18PicsOk: '{n} pictures taken.', t18PicsUnknown: '{f}: unknown name', t18PicsHint: 'On the device grow up then shows the picture of the choice. PNG files, name = character (e.g. Mametchi.png, Kuchipatchi.png) or its number (16.png). The folder erwachsen of the Android T18Emu works too: choose all files with erwachsen.json. Any size, scaled to 64x64.', t18Items: 'Items', t18ItemsPick: 'Choose MyMeets files', t18ItemsNoSave: 'Items work once the game has run (read the ROM from the device).', t18ItemsHint: 'Items, room and Tamapoints go into the game\'s save. When written it replaces T18Emu\'s save on the device, even with "Keep saves". The Tama stays, the running state starts anew.', t18ItemsNone: 'No items found in the files.', t18ItemsOther: '{n} is for {m}, not for the Meets/On. It may not work there.', t18ItemsFull: 'no room left', mmTitle: 'MixingMeets (visit, marriage)', uartBusy: 'Paramix Studio is still connected to the dongle. The bridge does not work meanwhile.', uartFree: 'Release UART', uartFreed: 'Dongle released. Restart the Paradise so the game runs again.', uartRun: 'Wait until the device is done.', pairTitle: 'Connect two Paradise (visit, game)', pairHint: 'Plug both Paradise together at the top and start T18Emu on both. Then on both CONNECTION, TAMAGOTCHI and on as with two Tamas.', pairHintDigi: 'Plug both Paradise together at the top and start V1Emu with Digimon on both. Then choose and start the battle as with two real Digimon.', pairHintPs: 'Plug both Paradise together at the top and start TamaEmu (P\'s) on both. Then on both connection, たまごっちP\'s, あそぶ. On one あそびにいく, on the other ともだちをよぶ, ふたりで, a game, then B.', pairHintIdl: 'Plug both Paradise together at the top and start TamaEmu (iD L) on both. Then choose the connection in the game on both as with two real iD L.', pairHintV3: 'Plug both Paradise together at the top and start V3Emu on both. Then choose the connection in the game on both as with two real V3.', pairHintT7: 'Plug both Paradise together at the top and start T7Emu (Tama-Go) on both. Then on both connection, TAMA-GO, VISIT or GAME. Press B on the device that goes visiting.', mmLink: 'Paramix bridge', mmDrag: 'Drag it to the bookmarks bar, then click it on mixing-meets.com.', mmHint: '1. Drag the Paramix bridge button to the bookmarks bar once (Chrome or Edge).\n2. Disconnect Paramix Studio from the dongle (Release UART or close the Studio). Dongle on the contacts as for flashing. On the Tama: CONNECTION, APP, VISIT (to bring it back: press A, GO BACK, YES).\n3. On mixing-meets.com open Connect or Return, click the bookmark, then Select Tamagotchi and choose the dongle.\nClick the bookmark again after every page change.', t7Gp: 'Gotchi Points', t7GpHint: 'Goes into the ROM like an imported save: the Tama stays, the running state starts anew (choose DOWNLOAD on the device).', t18KeepAsk: 'T18Emu: items or Tamapoints changed. Its save on the device is replaced by the one in the ROM (as read), even with "Keep saves". Go on?', t18ItemNo: 'No. {n}', t18ItemOk: '{n} is now in {k}.', t18Points: 'Tamapoints', t18A_food: 'Food', t18A_item: 'Items', t18A_acc: 'Accessories', t18A_room: 'Room', t18RoomBack: 'remove own room', t18RoomBuiltin: 'built-in room', dlcPick: 'Add download content', dlcInfo: 'Show used slots', progMore: 'Settings and content', progMakeMain: 'Make it the main program', progIsMain: 'Main program', v1Ok: 'First Tamagotchi or Digimon recognised (V1Emu).', v3Ok: 'Tamagotchi Connection V3 recognised (V3Emu).', v3Use: 'Start: hold A and C together on the home screen. Wheel short: settings. Back: hold the wheel.', optVol: 'Volume', optVolN: 'normal', optVolQ: 'quiet', optVolL: 'loud', optOff: 'off', optDim: 'Brightness', optScr: 'Screen off after', optDev: 'Also on the device: press the wheel briefly. A change made there applies until you change it here again.', optScrToy: 'as on the Tama', v1Use: 'Start: hold A and C together on the home screen. Wheel short: settings. Turn the wheel: shake. Back: hold the wheel.', progNoMainDoom: 'DOOM is the main program. For another one remove DOOM first (×).', doomAutoHint: 'Hold the wheel for 2 s: back to the Paradise, it stays there.', progReplaced: '{n} is now the main program instead of {o}.', mainAuto: '{n} is now the first entry of the menu, only this way everything fits.', mainNoRoom: 'As the first entry about {k} KB of room are missing. It stays as it was.', appTwice: '{n} is already in.', progNoMainV1: 'V1Emu starts from the menu only', progNoMain: 'Only in a start device', progMainNow: '{n} is now the main program. The saves of the swapped programs start anew.', dlcLoading: 'Reading…', dlcNewArea: 'The memory of this emulator is laid out anew for it. Its save starts anew after writing.', dlcHint: 'Food, clothes, accessories, games etc. as .jpg download files or .zip. Several files at once work, on the P\'s always a whole VDP set.', dlcFreeN: '{n} free', dlcDel: 'remove', dlcK0: 'Meals', dlcK1: 'Snacks', dlcK2: 'Clothing', dlcK3: 'Accessories', dlcK4: 'Items', dlcK5: 'Daily items', dlcK6: 'Wallpapers', dlcK7: 'Games', dlcK8: 'Destinations', dlcK10: 'VDP recipes', dlcK15: 'Decorations', dlcK16: 'Coupons', dlcK17: 'Bingo', dlcK18: 'Gashapon', dlcK19: 'Characters', dlcOk: '{n} now sits in {k}, slot {s}.', dlcBad: '{f}: {e}', dlcGone: '{n} removed.', + figField: 'Field:', figAll: 'all', zipField: 'Field as ZIP', fieldZipOk: '{f}: {n} characters and {s} pictures as ZIP.', fieldIn: 'Load field from ZIP', fieldInBad: 'Not a field ZIP (field.json missing).', fieldInOk: '{src} applied to {dst}: {n} parts.', fieldInEyes: '{k} characters stay original, their eye images are too big here.', + zipFigs: 'All characters as ZIP', zipAll: 'All sprites as ZIP', upload: 'Upload sheets (PNG or ZIP)', + numbers: 'Number test ROM', + figHint: 'A character is made of body, eyes and mouth, each large and small. Click a character for its sheet.', + allHint: 'Backgrounds, menus, items, fonts.', + moreColors: 'Allow more colours (up to 256)', + dimLoad: 'Load card', dimHint: 'Dump of a character card (4 MB) or a TamaSma card (1 or 2 MB). Card characters best replace adults. Baby, child and teen share their eyes and stay original.', + dimPick: 'Card character', dimTarget: 'replaces character', dimApply: 'Insert', dimEgg: 'Insert the card’s egg', + dimBaby: 'Baby', dimNone: 'Load a card to see its characters.', + download: 'Download sheet', uploadOne: 'Upload sheet', reset: 'Restore original', close: 'Close', + working: 'One moment …', + dimNr: 'No.', stUpd: 'gets updated', + disclaimer: 'Use at your own risk. Changing and writing the device can make it unusable or erase saves. Read a backup first and only use the tool if you know what you are doing. There is no warranty and no liability for damage to devices or data.', + trademarks: 'Tamagotchi and Digimon are trademarks of BANDAI. DOOM and Wolfenstein are trademarks of id Software (ZeniMax Media). Game Boy and Pokémon mini are trademarks of Nintendo, SEGA and Master System are trademarks of SEGA. Arduboy is a trademark of Arduboy Inc. All trademarks, games and characters belong to their owners and are only named to describe what the tool is for. Not an official product, not affiliated with these companies. The tool contains no games, firmware or game data: you only use your own files.', + devWarn: 'Writing to the device is at your own risk and without liability. Read a backup first and keep the device switched on while writing.', + footer: 'Runs locally in your browser. By mameise.', + edition: 'Edition', sprites: 'Sprites', figures: 'Characters', changed: 'changed', space: 'Room for characters', + figure: 'Character', sprite: 'Sprite', + mSize: 'Cell {w}×{h}, {n} images, grid {iw}×{ih}', mColors: '{c}, palette sets: {p}', + mDirect: 'Direct colour RGB565', mPal: '{n} colours', mKeep: 'Several palette sets (colour variants): uploads use the original colours.', + mSheet: 'Sheet {w}×{h} px. Keep the size, otherwise the grid no longer fits.', + mGroupRows: 'Rows: body (20), eyes (20), mouth (18), small body (24), small eyes (14), small mouth (14).', + notRom: 'This is not a Paradise dump: {e}', loaded: '{ed} loaded: {s} sprites, {f} characters.', + saved: 'Saved: {name}\n{n} sprites changed, {kb} KB still free.', nothing: 'Nothing changed yet.', + tooBig: 'Too big for the free space. {e}', + upOk: 'Applied: {n}', upSkip: 'Skipped: {list}', upNone: 'No matching files. Expected: figur_0237.png or sprite_0014.png.', sprSix: 'Field picture of the extra fields, cannot be changed.', + wrongSize: '{f}: {e}', resetOk: 'Original restored.', dimOk: 'Card character {d} now sits in character {g}.', eggOk: 'Egg replaced.', + numOk: 'Every character now shows its number. Save, flash, raise and note which number shows up at which stage.', + notDim: 'Unknown card: {e}', leave: 'There are unsaved changes.', + roleFallback: 'Fallback', roleBaby: 'Baby', roleAdult: 'first adult', + eyeHint: 'Pink frame = eye. It moves into the eye layer so the character blinks and the cell has eyes. Wrong? Click on the eye.', + eyeNone: 'Character has no visible eyes', dimEyesTooBig: 'The eyes were too detailed, the character keeps no eye layer.', + roleFallbackText: 'appears when the game cannot load a character. Best left unchanged.', + roleBabyText: 'hatches from the egg.', roleAdultText: 'from here on every character has its own eyes.', + mEyes: 'Eyes keep their byte size, otherwise the fallback character hatches. Eyes that are too detailed are rejected.', + mColorsFig: 'If all colours come from the original, the game keeps recolouring the character per tama. New colours become fixed (up to 8 colours plus outline).', + }, +}; +/* ITOSM_KO_BEGIN */ +T.ko = { + "open": "ROM 열기", + "save": "새 ROM 저장", + "startTitle": "다마고치 파라다이스를 더 다양하게", + "startText": "내 파라다이스 ROM으로 원하는 기능을 구성하세요. 16 MB 원본 파일을 열거나 기기에서 직접 읽으세요. 기능을 선택한 뒤 새 ROM을 저장하거나 기기에 기록할 수 있습니다.", + "featHead": "이런 일을 할 수 있어요", + "g1t": "다마고치 에뮬레이터", + "g1": "컬러 다마고치(iD, iD L, Plus Color, P's, 4U, 4U+), 타마고와 피규어, 프렌즈, 미츠·온, 커넥션 V3, P1·P2·엔젤 등의 초기 다마고치와 디지몬 V1·V2를 지원합니다. 여러 프로그램을 넣고 각각 저장할 수 있습니다. ROM은 직접 준비하세요.", + "g2t": "DOOM과 Wolfenstein 3D", + "g2": "파라다이스에서 DOOM, Wolfenstein 3D, Spear of Destiny를 실행하고 버튼을 설정할 수 있습니다. 게임 파일은 직접 준비하세요.", + "g7t": "게임기 에뮬레이터", + "g7": "게임보이·컬러, 마스터 시스템, 게임기어, 포켓몬 미니, Arduboy를 지원합니다. 직접 준비한 게임을 메뉴에 추가하고 소리와 저장 기능을 사용할 수 있습니다.", + "g3t": "지역 확장", + "g3": "지원되는 ROM에 여섯 지역과 배경, 비밀 캐릭터, 지역별 행성 및 연구소 게임을 구성합니다.", + "g4t": "본체 편집 메뉴", + "g4": "본체에서 지역 전환, 아이템 추가, 포인트·다마고치 수정, 여러 저장 슬롯을 사용할 수 있습니다. 게임 플레이 시간으로 포인트를 얻는 기능도 있습니다.", + "g8t": "파라다이스 없는 실행 전용 기기", + "g8": "약 16 MB 전체를 에뮬레이터와 게임에 활용합니다. 시작 프로그램을 지정하고 메뉴에서 시간을 설정합니다.", + "g5t": "기기 읽기·기록", + "g5": "USB-UART 어댑터로 원본을 백업하고 새 ROM을 기록합니다. 저장 데이터를 유지하거나 변경한 부분만 기록할 수 있습니다. 기록 중단에 대비한 복구 시작 기능도 있습니다.", + "g6t": "나만의 캐릭터", + "g6": "캐릭터 이미지를 시트로 내보내 편집합니다. DIM 카드의 디지몬도 가져올 수 있으며 색상과 눈 이미지는 자동으로 맞춥니다.", + "g9t": "저장 관리와 방문", + "g9": "저장 데이터를 백업·복원·편집하고 다운로드 콘텐츠를 추가합니다. 상단 단자로 두 기기를 연결하거나 어댑터로 가상 방문을 실행합니다.", + "dropTitle": "ROM을 여기에 놓거나 클릭하세요", + "dropText": "랜드, 워터, 스카이, 제이드 포레스트, 트로피컬, 글레이셔를 인식합니다.", + "f1t": "내 PC 편집·기종별 백업", + "f1": "파일 열기와 편집은 PC 브라우저에서 처리합니다. 기기에서 읽은 ROM을 보관하고 필요한 기능을 편집할 수 있습니다.", + "f2t": "게임 파일은 직접 준비", + "f2": "도구에는 ROM, 펌웨어, WAD가 포함되지 않습니다. 본인 기기와 파일을 사용하세요.", + "f3t": "변경 내용 검증", + "f3": "체크섬을 다시 계산하고 저장 전 수정 이미지를 확인합니다. 기기에 기록한 각 섹터도 검증합니다.", + "planTitle": "새 ROM 구성", + "planFig": "캐릭터", + "planEmu": "에뮬레이터", + "planEmus": "에뮬레이터", + "planDoom": "DOOM", + "planWolf": "Wolfenstein 3D", + "planGb": "게임보이", + "planSms": "마스터 시스템 / 게임기어", + "planPm": "포켓몬 미니", + "planMenu": "본체 메뉴", + "planApps": "추가 에뮬레이터", + "stNone": "없음", + "stKeep": "유지", + "stNew": "추가", + "stDel": "저장 시 삭제", + "stChanged": "{n}개 변경", + "stSame": "변경 없음", + "segFw": "펌웨어와 캐릭터", + "segEmu": "에뮬레이터", + "segDoom": "DOOM", + "segWolf": "Wolfenstein 3D", + "segGb": "게임보이", + "segSms": "마스터 시스템 / 게임기어", + "segPm": "포켓몬 미니", + "segSlots": "지역별 저장", + "segSave": "저장 데이터", + "segFree": "사용 가능", + "segResv": "예약 영역", + "ruleBoth": "에뮬레이터와 DOOM 중 하나만 넣을 수 있습니다. 본체 메뉴는 둘 다 지원합니다.", + "ruleNoRoom": "이 에디션은 캐릭터 데이터가 커서 에뮬레이터나 DOOM을 넣을 공간이 없습니다. 본체 메뉴는 사용할 수 있습니다.", + "emuVsDoom": "DOOM이 선택되거나 설치되어 있습니다. 여기서 펌웨어를 선택하면 DOOM을 제거합니다.", + "doomVsEmu": "에뮬레이터가 선택되거나 설치되어 있습니다. 여기서 WAD를 선택하면 에뮬레이터를 제거합니다.", + "noRoomApp": "이 에디션에는 필요한 공간이 없습니다.", + "a0Menu": "이 에디션은 0x0A0000에 주 프로그램을 넣을 공간이 없어 모든 프로그램을 메뉴에 넣습니다. 별표로 전원을 켤 때 실행할 프로그램을 선택합니다.", + "a0MenuN": "이 에디션은 0x0A0000에 주 프로그램을 넣을 공간이 없습니다. 타마고·프렌즈·초기 다마고치·V3는 메뉴에서 실행합니다(메뉴 탭에서 지역 전환 또는 아이템을 활성화한 뒤 A+C로 실행). 컬러 다마고치와 TG18은 실행 전용 구성에서만 지원됩니다.", + "a0NoMain": "{f}: 이 에디션의 컬러 다마고치와 TG18은 실행 전용 구성에서만 지원됩니다(메뉴 탭).", + "doomHas": "이 ROM에 DOOM이 들어 있습니다.", + "doomOff": "DOOM 제거", + "doomGone": "저장할 때 DOOM을 제거합니다.", + "keysTitle": "버튼 설정", + "kFire": "발사", + "kFwd": "앞으로", + "kBack": "뒤로", + "kUse": "사용", + "kMod": "무기 변경: 버튼을 누른 채 휠", + "kWheel": "휠 누르기", + "kRun": "앞으로 두 번 눌러 달리기", + "kInv": "휠 방향 반전", + "kFixed": "A+C를 누르면 메뉴가 열립니다. B+C를 누르면 지도가 열립니다. 소리를 켜거나 끄려면 무기 변경 버튼을 누른 채 휠을 짧게 누르세요. 종료 방법은 메뉴 탭의 ‘프로그램에서 돌아오기’ 설정을 따릅니다.", + "kOld": "이 DOOM은 개별 버튼 설정을 지원하지 않는 이전 버전입니다. WAD로 다시 추가하세요.", + "help": "도움말", + "helpTitle": "사용 방법", + "h1t": "진행 순서", + "h1": "1. 내 파라다이스 ROM 파일을 열거나 ‘기기’에서 직접 읽습니다.\n2. 각 탭에서 캐릭터, 에뮬레이터, 게임, 본체 메뉴를 선택합니다.\n3. 파일로 저장하거나 ‘기기’에서 기록합니다. ‘저장 데이터 유지’를 켜면 기기의 저장 데이터를 유지합니다.", + "h2t": "파라다이스 버튼 조작", + "hk1": "A와 C 함께", + "hv1": "홈 화면에서 메뉴 또는 에뮬레이터 실행", + "hk2": "휠 길게 누르기(메뉴 탭에서 변경 가능)", + "hv2": "현재 상태를 저장하고 파라다이스로 돌아가기", + "hk3": "휠 짧게 누르기", + "hv3": "T7Emu의 설정·피규어 선택", + "hk4": "시작 후 3초 안에 휠 누르기", + "hv4": "A로 확인하면 실행 상태를 초기화합니다. 다음 실행 시 게임 자체의 저장 데이터에서 시작합니다.", + "hk5": "전원을 켤 때 B", + "hv5": "자동 시작을 건너뛰고 파라다이스 또는 메뉴 열기", + "hk6": "리셋 버튼", + "hv6": "자동 시작 설정 시 주 프로그램 다시 실행", + "hk7": "전원을 켤 때 C", + "hv7": "기록 프로그램 실행: 웹의 ‘기기’에서 다시 기록 가능", + "h3t": "시계", + "h3": "에뮬레이터 탭의 ‘시작할 때 파라다이스 시간 가져오기’를 켜면 실행할 때마다 기기의 시간으로 맞춥니다. 실행하지 않은 시간 동안의 플레이를 재현하지는 않습니다. 파라다이스 시계를 먼저 맞추세요.", + "h4t": "다시 실행하기", + "h4": "휠로 종료한 시점부터 이어집니다. 실행 상태를 초기화해도 게임 자체의 저장 데이터는 유지됩니다.", + "h5t": "메뉴와 지역", + "h5": "홈 화면에서 A+C를 누릅니다. 휠로 항목을 선택하고 B로 확인하세요. C를 누르면 이전 화면으로 돌아갑니다. 지역을 바꾸면 이전 지역의 저장 데이터를 보관하고 새 지역의 저장을 불러옵니다.\n트로피컬·글레이셔에는 내 ROM에서 랜드·워터·스카이를 추가하고 제이드 포레스트에는 스카이를 추가합니다. 게임에서는 행성 → 지역으로 이동합니다. DNA와 주민은 해당 지역에 속합니다.", + "h8t": "실행 전용 구성", + "h8": "메뉴 탭에서 실행 전용 구성을 선택하면 프로그램 목록으로 시작합니다. 파라다이스를 제거하면 거의 전체 공간을 프로그램에 쓰며 메뉴에서 시계를 맞춥니다. 별표로 주 프로그램을 정하고 자동 시작을 켤 수 있습니다.", + "h9t": "복구 화면으로 돌아가기", + "h9": "화면이 검거나 프로그램이 멈추면 C를 누른 채 배터리를 넣거나 리셋합니다. 기록 프로그램이 시작되면 ‘기기’에서 읽기·기록이 가능합니다. 기록이 중단된 경우에는 복구 시작 기능이 자동으로 기록 화면을 엽니다.", + "h6t": "저장 데이터 백업", + "h7t": "저장 데이터 가져오기", + "h7": "1. ‘기기’에서 최신 ROM을 읽거나 최근 읽은 파일을 엽니다.\n2. 저장 탭에서 데이터를 가져옵니다. 해당 프로그램의 저장에 적용됩니다.\n3. ‘저장 데이터 유지’를 켜고 기록합니다. 가져온 저장만 교체하고 다른 저장은 기기의 것을 유지합니다.\n‘저장 데이터 유지’를 끄면 모든 저장을 파일의 것으로 교체합니다. 프로그램 추가·삭제는 별도 기록으로 진행하고 먼저 모든 저장을 백업하세요.", + "h6": "저장 탭 또는 기기 → ‘저장 데이터 백업’을 사용하세요. 에뮬레이터를 바꾸면 이전 저장을 잃을 수 있으므로 먼저 백업하세요.", + "device": "기기", + "devTitle": "UART 기기 연결", + "devHint": "3.3 V 신호의 USB-UART 어댑터를 사용합니다. 원본 안내의 접점 방향은 왼쪽: 어댑터 RX, 가운데: GND, 오른쪽: 어댑터 TX입니다. 실제 기기 방향과 배선을 확인하세요. 본체의 다마 우주 → A → 통신 → 다운로드 → 다운로드 화면을 연 뒤 연결하세요. PC의 Chrome 또는 Edge가 필요합니다.", + "devConnect": "연결", + "devDump": "ROM 추출·백업 후 다운로드", + "devWrite": "새 ROM을 기기에 기록", + "devOnly": "변경 부분만 기록", + "devKeep": "저장 데이터 유지", + "devStop": "취소", + "devNoSerial": "이 브라우저는 어댑터 연결을 지원하지 않습니다. PC의 Chrome 또는 Edge를 사용하세요.", + "devNone": "연결되지 않았습니다.", + "fl_noRescueRoom": "복구 시작 영역(플래시 마지막 64 KB)에 공간이 없어 기록하지 않았습니다. 실행 전용 구성에서 프로그램을 하나 제거한 뒤 다시 기록하세요.", + "plHint": "PL2303 어댑터: 최신 Windows 드라이버는 구형·호환 칩을 차단할 수 있습니다. 장치 관리자에서 구형 Prolific 3.3.2.x 드라이버를 선택하거나 CH340·CP2102 어댑터를 사용하세요.", + "resOn": "기록 중단 복구 기능 활성화: 중단 시 기기가 기록 화면으로 시작합니다.", + "resModeGo": "이전 기록이 중단되었습니다. 본체의 기록 화면에서 대기 중입니다. ‘기록 이어하기’를 누르세요.", + "resModeRom": "이전 기록이 중단되었습니다. 본체가 기록 화면에서 대기 중입니다. ROM 또는 백업 파일을 다시 열고 기록하세요.", + "resResume": "기록 이어하기", + "resHalf": "이전 기록이 끝나지 않았습니다. ‘기록 이어하기’로 완료하세요.", + "resResumed": "{w}개 섹터 기록 완료. 본체 전원을 껐다 켜세요.", + "resTest": "복구 시작 테스트", + "resBack": "헤더 복원", + "resSure": "테스트: 0xFF0000에 복구 프로그램을 기록한 뒤 기기 헤더(섹터 0)를 지웁니다. 전원을 껐다 켜고 기록 화면이 나오면 연결 후 ‘헤더 복원’을 누르세요. 화면이 나오지 않으면 별도 플래시 도구 없이 부팅할 수 없습니다. 계속할까요?", + "resCleared": "헤더를 지웠습니다. 전원을 껐다 켜세요. 기록 화면이 나오면 연결 후 ‘헤더 복원’을 누르세요.", + "resBackDone": "헤더를 복원했습니다. 전원을 껐다 켜면 정상 시작합니다.", + "resNoHdr": "보관된 헤더가 없습니다.", + "devOn": "연결됨: {ed} · {mb} MB{l}", + "devLoaded": " · 기록 프로그램을 불러왔습니다", + "devReady": "준비되었습니다.", + "devNeedRom": "기록할 ROM을 먼저 열거나 기기에서 읽으세요.", + "visTitle": "가상 방문(파라다이스)", + "visStart": "시작", + "visStop": "중지", + "visHint": "도구가 두 번째 파라다이스 역할을 합니다. 어댑터를 접점에 연결하고 본체는 일반 실행 상태로 두세요.\n1. 에디션 선택 → 시작 → 어댑터 선택.\n2. 본체의 다마 우주 → A → 통신 → 놀기 → B.\n위의 ‘연결’ 버튼은 ROM 작업용이므로 방문할 때는 누르지 마세요.", + "visWait": "{ed} 방문 준비 완료. 본체에서 통신 → 놀기를 선택하고 B를 누르세요.", + "visRun": "연결되었습니다. 데이터를 주고받고 있습니다…", + "visPlay": "두 다마고치가 놀고 있습니다…", + "visDone": "방문 완료({ed}). 다음 방문은 본체에서 B를 다시 누르세요.", + "visErr": "중단됨: {e}. 본체에서 B를 다시 누르세요.", + "visBadKey": "본체가 데이터를 인식하지 못했습니다.", + "phload": "기록 프로그램 로드 중", + "phread": "읽는 중", + "phcompare": "비교 중", + "phwrite": "기록 중", + "phcheck": "검증 중", + "phprepare": "준비 중", + "devDumped": "ROM을 읽어 {n}으로 저장했습니다. 도구에서도 해당 ROM을 열었습니다.", + "devSure": "새 ROM을 기기에 기록합니다. 기록 중 전원을 유지하세요. 변경에 따른 위험을 이해하고 기록할까요?", + "devSureFull": "‘저장 데이터 유지’가 꺼져 있어 기기의 저장을 ROM 파일의 저장으로 교체합니다. 기록할까요?", + "carryUnknown": "기기와 현재 파일의 ROM이 다릅니다. 이동하는 프로그램의 저장을 보존할 수 없습니다. 먼저 기기의 ROM을 읽으세요. 그래도 기록할까요?", + "carryMiss": "이동하는 프로그램의 저장을 보존할 수 없습니다. 저장 탭에서 먼저 백업하세요. 그래도 기록할까요?", + "devEmuLost": "기기의 주 프로그램: {o}. 새 ROM: {n}. {o}의 주 프로그램 저장이 초기화됩니다. 유지하려면 저장 탭에서 먼저 백업하세요. 기록할까요?", + "devEmuNone": "에뮬레이터 없음", + "devEmuNew": "새 펌웨어를 선택한 {o}", + "devDone": "기록·검증 완료: {w}개 섹터 기록{k}. 본체를 리셋하거나 배터리로 재시작하세요.", + "devKept": " · 저장 섹터 {k}개 유지", + "devSame": "기기에 이미 같은 ROM이 있어 기록할 내용이 없습니다.", + "devErr": "오류: {e}", + "devCancelled": "취소했습니다.", + "cleanOn": "파라다이스 제거(클린 ROM)", + "cleanClock": "시작할 때 시계 설정", + "cleanClockHint": "배터리 교체 등으로 시간이 없으면 시작 시 설정합니다. 이 옵션을 끄면 본체 메뉴의 설정 또는 각 에뮬레이터에서 시간을 맞추세요.", + "emuClockOff": "메뉴 탭의 ‘시작할 때 시계 설정’을 켜야 합니다.", + "emuSess": "종료 시 실행 상태 저장", + "emuSessHint": "다음 실행 시 종료한 지점부터 이어집니다. 끄면 실제 기기처럼 새로 시작해 게임 자체의 저장을 불러옵니다.", + "ruleClean": "파라다이스 제거: 모든 프로그램을 메뉴에 넣고 거의 전체 플래시 공간을 활용합니다.", + "cleanHint": "파라다이스 게임을 제거하고 프로그램 메뉴만 남깁니다. 거의 16 MB 전체를 사용할 수 있습니다.", + "cleanUse": "전원을 켜면 메뉴가 바로 나옵니다. 처음에는 시계를 설정하고 이후에는 설정 메뉴에서 변경합니다. 프로그램 종료 방법은 같습니다.", + "cleanWarn": "기록하면 파라다이스와 그 저장 데이터가 삭제됩니다. 먼저 백업하세요.", + "cleanNoDoom": "이 구성에서는 DOOM을 사용할 수 없습니다. DOOM을 제거하세요.", + "doomOne": "DOOM은 메뉴에 한 번만 추가할 수 있습니다.", + "cleanSure": "기기의 파라다이스 게임과 저장 데이터가 삭제됩니다. 기기를 백업했나요? 계속할까요?", + "cleanLoaded": "파라다이스 없는 ROM({ed})을 열었습니다: 프로그램 {n}개.", + "launchOn": "프로그램 실행 전용 구성", + "launchHint": "파라다이스의 초기 설정(언어·시간·이어하기·새 게임)만 남기고 이후에는 프로그램 메뉴로 시작합니다. 게임 이미지를 제거해 약 5 MB를 추가로 확보합니다.", + "launchUse": "전원을 켜고 시간을 맞추면 메뉴가 나옵니다. 휠로 선택하고 B로 실행합니다. 프로그램을 종료하면 메뉴로 돌아옵니다.", + "launchOld": "실행 전용 ROM입니다. 일반 파라다이스로 돌아가려면 원본 ROM을 여세요.", + "launchNeed": "실행 전용 구성에는 에뮬레이터 또는 DOOM 등 프로그램이 하나 이상 필요합니다.", + "launchSix": "여섯 지역 확장이 설치된 ROM은 실행 전용으로 바꿀 수 없습니다. 원본 ROM을 여세요.", + "planLaunch": "실행 전용 구성", + "tabFeld": "본체 메뉴", + "feldOn": "여러 저장 슬롯(지역 선택)", + "bagOn": "아이템과 다마포인트", + "tamaOn": "다마고치 수정(레벨·돌봄·캐릭터)", + "gplayOn": "플레이 시간으로 다마포인트 획득", + "gplayHint": "DOOM, Wolfenstein, 게임보이, 마스터 시스템, 포켓몬 미니, Arduboy를 플레이한 뒤 파라다이스로 돌아오면 1분당 10포인트를 받습니다.", + "saveSlot": "저장 {n}", + "sixOn": "여섯 지역 모두 추가", + "sixPick": "랜드·워터·스카이 ROM 선택", + "sixHint": "트로피컬·글레이셔에 랜드·워터·스카이를 추가합니다. 지역 이미지는 직접 준비한 해당 ROM에서 가져옵니다. 연구소 게임은 메뉴에서 다마고치를 시작한 지역을 따릅니다.", + "sixNeed": "여섯 지역 확장을 위해 랜드·워터·스카이 중 하나의 ROM이 필요합니다.", + "sixOk": "{n}에서 지역 이미지를 가져왔습니다.", + "sixBad": "{n}은 랜드·워터·스카이 ROM이 아닙니다.", + "sixIn": "여섯 지역이 설치되어 있습니다.", + "sixOff": "저장 시 랜드·워터·스카이를 제거합니다. 여러 저장 슬롯은 유지됩니다.", + "sixOffJ": "저장 시 스카이를 제거합니다. 여러 저장 슬롯은 유지됩니다.", + "sixOffField": "현재 기기의 지역은 {f}입니다. 먼저 본체 메뉴에서 {s}로 이동하세요.", + "sixOffSlots": "본체 메뉴에 보관된 저장 데이터가 삭제됩니다. 계속할까요?", + "sixFail": "지역 추가 실패: {e}", + "sixNoFw": "ROM의 펌웨어가 변경되어 지역 확장을 적용할 수 없습니다.", + "planSix": "지역 확장", + "sixOnJ": "스카이를 네 번째 지역으로 추가", + "sixHintJ": "제이드 포레스트에는 스카이 이미지가 이미 들어 있습니다.", + "sixInJ": "스카이가 네 번째 지역으로 설치되어 있습니다.", + "sixOld": "이전 버전의 여섯 지역 확장이 설치되어 있습니다. 랜드·워터·스카이 ROM을 선택하면 저장 시 업데이트합니다.", + "sixOldJ": "스카이가 설치되어 있으며 저장할 때 업데이트합니다.", + "sixPlanet": "지역에 맞는 행성", + "sixMenu": "게임의 지역 메뉴: 레벨 4부터 모든 지역", + "sixPlanetNeed": "이 설정을 바꾸려면 랜드·워터·스카이 ROM이 다시 필요합니다.", + "sixApp": "DOOM·에뮬레이터와 함께 넣을 공간이 없습니다", + "exitKey": "프로그램에서 돌아오기", + "exitHint": "에뮬레이터와 게임에서 파라다이스 또는 본체 메뉴로 돌아오는 조작입니다.", + "exit0": "휠 길게 누르기", + "exit1": "휠과 A 길게 누르기", + "exit2": "휠과 C 길게 누르기", + "exit3": "휠 5초 누르기", + "feldHint": "본체에서 저장 슬롯 전환, 새 지역 시작, 아이템 추가, 포인트 설정, 다마고치 수정을 할 수 있는 메뉴입니다.", + "feldUse": "홈 화면에서 A+C를 길게 누르세요. 휠로 항목을 선택하고 B로 확인하세요. C를 누르면 이전 화면으로 돌아갑니다.", + "feldNo": "지역 전환은 랜드·워터·스카이 사이 또는 트로피컬·글레이셔 사이에서 지원합니다.", + "feldMissing": "이 배포본에는 본체 메뉴가 없습니다.", + "feldCur": "현재 지역: {f}.", + "feldList": "선택 가능: {s}.", + "feldStored": "보관 중: {s}.", + "feldFail": "메뉴 설치 실패: {e}", + "feldUnknown": "에디션을 인식하지 못했습니다.", + "tabWolf": "Wolf3D", + "wolfPick": "게임 파일 선택", + "wolfHint": "Wolfenstein 3D 파일을 모두 함께 선택하세요: 셰어웨어(.WL1), 정식판(.WL6), Spear of Destiny(.SOD). 본체 메뉴에 추가합니다.", + "wolfNone": "선택한 게임 파일이 없습니다.", + "wolfShare": "셰어웨어", + "wolfFull": "정식판", + "wolfEps": "에피소드 {n}개", + "wolfEp1": "에피소드 1개", + "wolfBad": "Wolfenstein 3D: {e}", + "wolfNoMain": "Wolfenstein 3D는 본체 메뉴에서만 실행", + "wolfTurn": "휠 한 칸당 회전", + "wolfFixed": "A+C: 메뉴. 종료·저장은 본체 메뉴 탭의 ‘프로그램에서 돌아오기’ 설정을 따릅니다.", + "wolfOne": "Wolfenstein 3D와 Spear of Destiny는 각각 하나씩만 넣을 수 있습니다. 새 파일을 선택하면 이전 것을 교체합니다.", + "wolfSodN": "21개 층", + "tabGb": "게임보이 / 컬러", + "gbNoMain": "게임보이는 본체 메뉴에서만 실행", + "gbPick": "게임 선택(.gb, .gbc)", + "gbHint": "게임을 본체 메뉴에 추가합니다. A+B+C로 설정(Select·소리 포함)을 열고 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다. 두 파라다이스의 상단 단자를 연결하면 포켓몬 교환 등 통신 케이블 기능을 사용할 수 있습니다.", + "gbNone2": "선택한 게임이 없습니다.", + "gbKeysTitle": "버튼", + "gbKeysDef": "기본값", + "gbKeysMiss": "미지정: {n}", + "gbNone": "–", + "gbRight": "오른쪽", + "gbLeft": "왼쪽", + "gbUp": "위", + "gbDown": "아래", + "gbInA": "A 버튼", + "gbInB": "B 버튼", + "gbInC": "C 버튼", + "gbInWp": "휠 누르기", + "gbInWu": "휠 위로", + "gbInWd": "휠 아래로", + "gbInAC": "A + C", + "gbInBC": "B + C", + "gbInAB": "A + B", + "gbBad": "{f}: 게임보이 게임이 아닙니다", + "gbColor": "{f}: 게임보이 컬러 전용이므로 이 구성에서 지원하지 않습니다", + "gbNeedRom": "먼저 ROM을 열거나 기기에서 읽으세요.", + "t7Old": "{n}: 구버전은 배터리 교체 시 저장이 유실될 수 있습니다. ‘저장 데이터 유지’를 켜고 다시 기록하세요.", + "t18Broken": "Tama Meets가 손상되었습니다. 제거 후 펌웨어를 다시 추가하고 ‘저장 데이터 유지’를 끈 상태로 기록하세요.", + "t18Clash": "주 프로그램과 Tama Meets의 공간이 겹칩니다. Tama Meets를 먼저 제거하세요.", + "tabSms": "마스터 시스템 / 게임기어", + "tabPm": "포켓몬 미니", + "smsNoMain": "마스터 시스템·게임기어는 본체 메뉴에서만 실행", + "pmNoMain": "포켓몬 미니는 본체 메뉴에서만 실행", + "abNoMain": "Arduboy는 본체 메뉴에서만 실행", + "planAb": "Arduboy", + "segAb": "Arduboy", + "tabAb": "Arduboy", + "abPick": "게임 선택(.hex, .zip)", + "abHint": "게임을 본체 메뉴에 추가합니다. A+B+C로 화면 크기·소리 등을 설정합니다. 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다.", + "abBad": "{f}: Arduboy 게임이 아닙니다", + "abBig": "{f}: Arduboy 용량을 초과합니다", + "smsPick": "게임 선택(.sms, .gg)", + "smsHint": "게임을 본체 메뉴에 추가합니다. A+B+C로 일시정지·소리 등을 설정합니다. 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다.", + "smsBad": "{f}: 마스터 시스템·게임기어 게임이 아닙니다", + "smsGG": "{f}: 이 구성에서는 게임기어 게임을 지원하지 않습니다", + "smsB1": "버튼 1", + "smsB2": "버튼 2", + "smsPause": "일시정지 / 시작", + "pmPick": "게임 선택(.min, .zip)", + "pmHint": "게임을 본체 메뉴에 추가합니다. A+B+C로 전원·소리 등을 설정합니다. 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다.", + "pmBad": "{f}: 포켓몬 미니 게임이 아닙니다", + "pmBig": "{f}: 1 MB를 초과해 지원하지 않습니다", + "pmBiosPick": "내 BIOS 선택", + "pmBiosDel": "내 BIOS 제거", + "pmBiosFree": "직접 선택하지 않으면 PokeMini의 자유 BIOS를 사용합니다. 실제 BIOS로 더 잘 실행되는 게임도 있습니다.", + "pmBiosOwn": "선택한 BIOS를 모든 포켓몬 미니 게임에 사용합니다.", + "pmBiosBad": "{f}: 포켓몬 미니 BIOS가 아닙니다", + "pmA": "A", + "pmB": "B", + "pmC": "C", + "pmPower": "전원", + "pmShake": "흔들기", + "tabFigs": "캐릭터", + "tabAll": "전체 이미지", + "tabDim": "카드", + "tabEmu": "에뮬레이터", + "tabDoom": "DOOM", + "doomPick": "DOOM.WAD 선택", + "doomEp": "에피소드", + "doomMusic": "음악", + "doomHint": "직접 준비한 WAD로 ROM에 DOOM을 추가합니다. 파일은 내 PC에서 처리합니다.", + "doomUse": "본체 메뉴에서 실행합니다. 일반 파라다이스에서는 홈 화면에서 A+C로도 실행합니다. 종료는 ‘프로그램에서 돌아오기’ 설정을 따릅니다.", + "doomNone": "선택한 WAD가 없습니다.", + "doomOk": "WAD 인식됨({eps}). 저장할 때 DOOM을 추가합니다.", + "doomEpsHint": "파라다이스 없는 구성에서는 선택한 에피소드를 DOOM E1, E2 등 각각의 메뉴와 저장으로 추가합니다.", + "doomWhole": "전체 WAD를 한 항목으로", + "pwadPick": "추가 WAD 선택", + "pwadOff": "추가 WAD 제거", + "doomPwads": "함께 사용: {n}.", + "pwadNeedD2": "{n}은 DOOM II용입니다. 먼저 DOOM2.WAD를 선택하세요.", + "pwadNeedD1": "{n}은 DOOM·Ultimate DOOM용입니다. 먼저 DOOM.WAD를 선택하세요.", + "doomPwadPara": "Sigil 같은 추가 에피소드는 파라다이스 없는 구성에서만 지원합니다.", + "doomPwadBig": "{n}: {m} 지도는 본체 메모리보다 클 수 있습니다. 실행 중 9가 표시되면 휠을 2초 눌러 메뉴로 돌아가세요.", + "doomPwadHint": "추가 에피소드를 선택하면 개별 메뉴로 추가합니다. 전체 WAD와 함께 넣으면 공간이 부족할 수 있습니다.", + "doomD2Clean": "DOOM II는 파라다이스 없는 ROM에만 추가할 수 있습니다.", + "doomD2Hint": "DOOM II는 메뉴 한 항목으로 추가합니다. 거의 전체 공간을 사용하며 음악을 꺼야 들어갑니다.", + "doomWholeHint": "모든 에피소드를 DOOM 한 항목에 넣고 게임 안에서 선택합니다. 개별 추가보다 공간을 적게 사용합니다.", + "doomBad": "WAD 인식 실패: {e}", + "doomFail": "DOOM 추가 실패: {e}", + "doomMissing": "이 배포본에는 DOOM 프로그램이 없습니다.", + "doomBoth": "에뮬레이터와 DOOM을 함께 넣을 공간이 없습니다. 하나만 선택하세요.", + "doomBig": "이 WAD의 에피소드를 넣을 공간이 없습니다.", + "doomNoMusic": "음악을 꺼야 이 에피소드가 들어갑니다.", + "emuPick": "펌웨어 또는 ROM 선택", + "emuOff": "에뮬레이터 제거", + "emuHint": "컬러 다마고치(TamaEmu), 타마고·프렌즈(T7Emu), 미츠·온(T18Emu), 초기 다마고치·디지몬(V1Emu), 커넥션 V3(V3Emu)를 지원합니다. 첫 파일은 주 프로그램으로 지정합니다. 이후 파일은 본체 메뉴에 추가합니다. 채워진 별표가 주 프로그램이며 빈 별표를 누르면 바뀝니다. 파일은 직접 준비하세요.", + "t7Ok": "V7 ROM 인식됨(T7Emu). 저장할 때 추가합니다.", + "t7OkFr": "다마고치 프렌즈를 불러왔습니다. 저장할 때 추가합니다. 피규어는 지원하지 않습니다.", + "t7Has": "이 ROM에 T7Emu가 들어 있습니다.", + "t7HasFr": "이 ROM에 다마고치 프렌즈 T7Emu가 들어 있습니다.", + "t7Use": "홈 화면에서 A+C를 누르면 실행합니다. 휠을 길게 누르면 저장하고 종료합니다. 짧게 누르면 설정과 피규어 메뉴가 열립니다. 멈췄다면 A+C로 실행하고 버튼을 놓은 뒤 3초 안에 휠을 누르세요. A를 눌러 확인하세요.", + "t7FigPick": "피규어 추가", + "t7FigNone": "추가한 피규어가 없습니다.", + "t7FigBad": "{f}: 피규어 파일이 아닙니다.", + "t7FigFull": "{f}을 넣을 공간이 없습니다.", + "t7FigMax": "피규어를 더 넣을 공간이 없습니다.", + "t7FigDup": "{f}은 이미 들어 있습니다.", + "appPick": "다른 에뮬레이터 추가", + "appHint": "타마고·프렌즈 ROM(T7Emu)을 추가합니다. A+C로 여는 메뉴에서 실행하므로 본체 메뉴 탭의 기능을 하나 이상 켜야 합니다.", + "appNone": "추가 에뮬레이터가 없습니다.", + "appBad": "{f}: 타마고·프렌즈 ROM이 아닙니다.", + "appBadL": "{f}: 타마고·프렌즈 ROM이나 컬러 다마고치·TG18 펌웨어가 아닙니다.", + "appT18One": "T18Emu는 ROM마다 하나만 추가할 수 있습니다.", + "appHintL": "실행 전용 구성: 타마고·프렌즈 ROM, 컬러 다마고치 펌웨어(TamaEmu), TG18 펌웨어(T18Emu는 하나만 추가 가능)를 지원합니다.", + "ruleLaunch": "실행 전용 구성에서는 공간이 있으면 에뮬레이터와 DOOM을 함께 넣을 수 있습니다.", + "appMax": "추가 에뮬레이터는 최대 12개입니다.", + "appNeedMenu": "추가 에뮬레이터를 실행하려면 본체 메뉴 탭에서 지역 전환 또는 아이템을 켜세요.", + "appFail": "추가 에뮬레이터: {e}", + "appSix": "여섯 지역 확장과 추가 에뮬레이터를 함께 사용할 수 없습니다.", + "t7SaveBtn": "T7Emu 저장(.bin)", + "saveFor": "프로그램", + "saveMain": "주 에뮬레이터", + "v1SaveBtn": "V1Emu 저장(.bin)", + "saveT18No": "이 프로그램의 저장 데이터는 백업할 수 없습니다.", + "saveNoBatt": "이 게임은 카트리지에 저장 데이터를 남기지 않습니다.", + "saveNone": "저장 데이터가 없습니다.", + "saveWrongFile": "{n}에 맞는 파일이 아닙니다.", + "saveCartIn": "{n}의 저장을 가져왔습니다. ROM을 저장하거나 기기에 기록하세요. 이전 실행 상태는 초기화됩니다.", + "t7SaveXDone": "{n}의 저장을 가져왔습니다. ROM을 저장하거나 기기에 기록하세요.", + "t7NoSave": "다마고치의 저장 데이터가 없습니다.", + "t7SaveInDone": "T7Emu 저장을 가져왔습니다. ROM을 저장하거나 기기에 기록하세요.", + "t7SaveNeed": "ROM에 T7Emu가 없습니다. 에뮬레이터 탭에서 타마고 ROM을 먼저 추가하세요.", + "saveT18Need": "ROM에 T18Emu가 없습니다. 에뮬레이터 탭에서 TG18 펌웨어를 먼저 추가하세요.", + "saveEmuAny": "에뮬레이터 저장(.sav / .bin)", + "emuUse": "홈 화면에서 A+C로 실행하고 휠을 길게 눌러 저장·종료합니다. TamaEmu가 멈췄다면 A+C로 실행하고 버튼을 놓은 뒤 3초 안에 휠을 누르고 A로 확인하세요. 게임 자체의 저장에서 다시 시작합니다.", + "emuNone": "선택한 에뮬레이터가 없습니다.", + "petT": "저장 데이터 편집", + "petOpen": "파라다이스 저장 열기", + "petRom": "ROM 내부 저장", + "petClose": "닫기", + "petRomDone": "변경 사항을 적용했습니다. 새 ROM을 저장하거나 기기에 기록하세요.", + "petLevel": "레벨", + "petChar": "다마고치", + "petCare": "배부름·행복·건강 회복", + "petSave": "수정한 저장 파일 저장", + "petKeep": "변경 없음", + "petKid": "유아기", + "petYoung": "성장기", + "petAdult": "성체", + "petNow": "저장 상태: 레벨 {l}, 다마고치 {c}, 배부름 {h}/6, 행복 {j}/20{s}.", + "petSick": " · 아픔", + "petOther": "현재 ROM과 다른 에디션의 저장입니다.", + "petNoSet": "저장 데이터에 설정 영역이 없습니다.", + "petDone": "{n} 저장 완료. ‘저장 데이터를 기기에 기록’으로 전송하세요.", + "petNothing": "변경한 내용이 없습니다.", + "tabSave": "저장 관리", + "tabNames": "이름", + "cardNoChars": "이 카드에는 캐릭터가 없습니다", + "noRoomFrag": "전체 여유 공간은 있지만 연속 공간이 부족합니다(DOOM WAD에는 큰 연속 공간이 필요합니다). 프로그램을 제거하거나 DOOM 음악을 끄세요.", + "noRoomKB": "약 {k} KB가 부족합니다. 프로그램을 제거하세요. 마지막 64 KB는 기록 중단 복구용으로 남겨 둡니다.", + "noRoomAdd": "{n}을 넣으려면 약 {k} KB가 더 필요합니다. 마지막 64 KB는 기록 중단 복구용입니다.", + "eyeMvT": "눈 위치 이동", + "mouthMvT": "입 위치 이동", + "poseNr": "자세 {i} / {n}", + "faceBig": "큰 캐릭터", + "faceSmall": "작은 캐릭터", + "poseOnly": "현재 자세만", + "poseOnlyHint": "화살표로 현재 표시된 자세의 눈·입만 이동합니다. 직접 만든 캐릭터의 특정 자세를 맞출 때 사용하세요.", + "eyeMvHint": "기록 후 해당 지역에서 새로 부화하거나 성장한 다마고치에 적용합니다. 작은 캐릭터는 이동량이 절반입니다.", + "planEyes": "눈과 입", + "namesHint": "본체에서 사용할 지역 이름과 다마고치 이름 및 아이템 이름을 수정합니다.", + "namesFields": "지역", + "namesChars": "다마고치", + "namesItems": "아이템", + "namesFind": "검색", + "namesUndo": "모두 초기화", + "planNames": "이름", + "planNamesN": "{n}개 변경", + "saveParaOut": "파라다이스 저장(.tamasave)", + "saveEmuOut": "TamaEmu 저장(.sav)", + "saveInfo": "내보내기는 현재 ROM에서 저장 데이터를 추출합니다. 에뮬레이터 저장은 ROM에 가져온 뒤 파일로 저장하거나 기기에 기록합니다. 파라다이스 저장은 기기로 직접 기록하므로 먼저 연결하세요.", + "saveOutT": "내보내기", + "saveInT": "가져오기", + "saveSecProg": "프로그램", + "saveSecPara": "파라다이스", + "saveParaOutB": "내보내기(.tamasave)", + "saveParaInB": "기기에 기록(.tamasave)", + "saveProgInfo": "선택한 프로그램의 저장을 현재 ROM에서 내보냅니다. 가져온 저장은 ROM 파일을 저장하거나 기기에 기록해야 적용됩니다.", + "saveParaInfo": "현재 ROM에서 파라다이스 저장을 내보냅니다. ‘기기에 기록’은 연결한 기기에 직접 적용합니다. 슬롯으로 대상을 선택하세요.", + "saveSlotL": "슬롯", + "slotLive": "{n}(사용 중)", + "slotEmpty": "{n}(비어 있음)", + "slotNone": "이 슬롯에는 저장 데이터가 없습니다.", + "slotField": "저장은 {a}용이고 슬롯은 {b}용입니다.", + "slotDevOther": "기기의 메뉴가 현재 ROM과 다릅니다. 먼저 기기에서 ROM을 읽으세요.", + "slotSure": "기기의 {n} 슬롯에 기록하며 기존 저장을 교체합니다. 계속할까요?", + "slotDone": "기기의 {n} 슬롯 교체 완료.", + "saveNoProg": "ROM에 프로그램이 없습니다. TamaEmu 저장에는 에뮬레이터가 함께 들어 있습니다. T7Emu·T18Emu는 에뮬레이터 탭에서 먼저 추가하세요.", + "saveBtnOut": "내보내기({f})", + "saveBtnIn": "가져오기({f})", + "saveEmuInDone": "TamaEmu 저장을 가져왔습니다({d}). ROM을 저장하거나 기기에 기록하세요.", + "saveEmuOther": "ROM의 TamaEmu는 {a}용이며 저장 데이터는 {b}용입니다. 그래도 가져올까요?", + "saveNoRoom": "이 ROM에는 TamaEmu를 넣을 공간이 없습니다.", + "saveEmuBad": "이 프로그램에 맞는 저장 파일이 아닙니다.", + "saveNoEmu": "ROM에 에뮬레이터가 없습니다.", + "saveDone": "{n} 저장 완료.", + "saveNoClock": "{n} 저장 완료. 시계는 포함되지 않으므로 필요하면 앱에서 설정하세요.", + "devSaveRead": "저장 데이터 백업", + "devSaveWrite": "저장 데이터를 기기에 기록", + "devSaveHint": "백업에는 파라다이스 저장·시계와 TamaEmu 또는 T7Emu 저장이 포함됩니다. 이 버튼으로는 파라다이스 저장만 기기에 기록합니다.", + "devSaveSure": "기기({ed})의 현재 저장을 선택한 데이터로 교체합니다. 계속할까요?", + "devSaveDone": "{w}개 페이지 기록 완료. {c} 본체를 재시작할 수 있습니다.", + "devSaveClock": "시계를 적용했습니다.", + "devSaveClockNo": "본체에서 시계를 맞추세요.", + "devSaveGot": "백업 완료: {n}.", + "fl_saveOtherEd": "다른 에디션의 저장입니다(파일: {s}, 기기: {d})", + "fl_saveFamily": "이 에디션에 맞는 저장이 아닙니다", + "fl_saveNoSettings": "설정 영역이 없어 완전한 파라다이스 저장이 아닙니다", + "fl_saveOutside": "저장 영역 밖의 {n}개 페이지는 기록하지 않습니다", + "fl_saveIncomplete": "일부 페이지가 없습니다. 누락된 부분은 기기의 데이터를 유지합니다", + "emuUndo": "선택 취소", + "progMain": "A+C로 실행", + "progMainL": "메뉴의 첫 항목", + "progMenu": "메뉴에서 실행", + "progGone": "저장 시 삭제", + "progUndo": "되돌리기", + "progDel": "제거", + "progNone": "펌웨어 또는 ROM을 선택하세요. 이후 추가한 프로그램은 본체 메뉴에 들어갑니다.", + "appBadMain": "{f}: 컬러 다마고치·TG18은 실행 전용 구성에서만 추가 프로그램으로 넣을 수 있습니다. 다른 구성에서는 위 에뮬레이터를 ×로 먼저 제거하세요.", + "emuInList": "ROM의 추가 프로그램: {n}. 다시 선택할 필요가 없습니다.", + "doomLinkLess": " · DOOM과 함께 사용하면 {m} MB 감소", + "emuPack": "펌웨어 압축", + "emuPackHint": "공간을 절약합니다(iD L 약 1 MB). 식당 등 일부 화면은 느려질 수 있습니다.", + "packNeed": "이 펌웨어는 압축해야 들어갑니다. TamaEmu 항목의 ‘펌웨어 압축’을 켜세요.", + "packTip": " 팁: TamaEmu의 ‘펌웨어 압축’으로 공간을 절약할 수 있습니다.", + "emuNfc": "4U: NFC 칩 에뮬레이션", + "emuNfcHint": "메뉴가 버튼 한 번에 반응합니다. 끄면 이전 방식으로 동작합니다.", + "emuClock": "시작할 때 파라다이스 시간 가져오기", + "emuClockHint": "실행할 때마다 파라다이스의 시간으로 맞춥니다. 실행하지 않은 시간의 플레이는 재현하지 않습니다.", + "emuAuto": "전원을 켜면 자동 실행", + "emuAutoHint": "휠을 길게 누르면 파라다이스로 돌아갑니다. A+C 또는 리셋 버튼으로 다시 실행합니다.", + "autoHintL": "전원을 켤 때 메뉴 대신 실행합니다. B를 누른 채 켜면 메뉴가 나옵니다.", + "emuHas": "이 ROM에 에뮬레이터가 들어 있습니다.", + "emuBig": "펌웨어가 커서 지역 전환 기능을 함께 넣을 공간이 없습니다.", + "emuUp": "저장할 때 새 에뮬레이터 버전을 넣습니다. ‘저장 데이터 유지’를 켜면 저장을 유지합니다.", + "emuOk": "펌웨어 인식됨({size}). 저장할 때 추가합니다.", + "emuBad": "펌웨어 인식 실패: {e}", + "t18Ok": "미츠·온용 TG18 펌웨어를 인식했습니다(T18Emu). 저장할 때 추가합니다.", + "t18Has": "이 ROM에 T18Emu가 들어 있습니다.", + "t18Use": "홈 화면에서 A+C로 실행합니다. 휠을 길게 누르면 저장하고 종료합니다. 실행이 멈추면 A+C로 다시 시작한 뒤 3초 안에 휠을 누르세요. A로 확인하면 저장한 게임에서 다시 시작합니다.", + "emuGone": "저장할 때 에뮬레이터를 제거합니다.", + "emuMissing": "이 배포본에는 에뮬레이터 프로그램이 없습니다.", + "emuFail": "에뮬레이터 추가 실패: {e}", + "savedEmu": "저장 완료: {name}", + "t18Pics": "성장 화면 이미지", + "t18PicsPick": "이미지 선택", + "t18PicsDel": "이미지 제거", + "t18PicsOk": "이미지 {n}개 적용.", + "t18PicsUnknown": "{f}: 알 수 없는 이름", + "t18PicsHint": "성장 화면에 표시할 PNG입니다. 파일 이름은 캐릭터 이름(Mametchi.png 등) 또는 번호(16.png)로 지정하세요. Android T18Emu의 erwachsen 폴더도 지원합니다(erwachsen.json 포함 전체 선택). 64×64로 조정합니다.", + "t18Items": "아이템", + "t18ItemsPick": "MyMeets 파일 선택", + "t18ItemsNoSave": "게임을 한 번 실행한 뒤 기기에서 ROM을 읽어야 아이템을 적용할 수 있습니다.", + "t18ItemsHint": "아이템·방·포인트를 게임 저장에 적용합니다. ‘저장 데이터 유지’를 켜도 기기의 T18Emu 저장을 파일의 것으로 교체합니다. 다마고치는 유지하고 실행 상태는 초기화합니다.", + "t18ItemsNone": "파일에 아이템이 없습니다.", + "t18ItemsOther": "{n}은 미츠·온이 아닌 {m}용입니다. 동작하지 않을 수 있습니다.", + "t18ItemsFull": "공간 부족", + "mmTitle": "MixingMeets(방문·결혼)", + "uartBusy": "도구가 어댑터에 연결되어 있어 브리지를 사용할 수 없습니다.", + "uartFree": "UART 연결 해제", + "uartFreed": "어댑터를 해제했습니다. 게임을 실행하려면 본체를 재시작하세요.", + "uartRun": "기기 작업이 끝날 때까지 기다리세요.", + "pairTitle": "파라다이스 두 대 연결(방문·게임)", + "pairHint": "두 기기의 상단 단자를 연결하고 모두 T18Emu를 실행합니다. 양쪽에서 CONNECTION → TAMAGOTCHI를 선택한 뒤 실제 기기처럼 진행하세요.", + "pairHintDigi": "두 기기의 상단 단자를 연결하고 모두 V1Emu의 디지몬을 실행합니다. 실제 디지몬 두 대처럼 배틀을 선택하고 시작하세요.", + "pairHintPs": "두 기기를 상단으로 연결하고 TamaEmu(P's)를 실행합니다. 양쪽에서 연결 → たまごっちP's → あそぶ. 한쪽에서는 あそびにいく를 선택하세요. 다른 쪽에서는 ともだちをよぶ → ふたりで → 게임 → B를 선택하세요.", + "pairHintIdl": "두 기기를 상단으로 연결하고 TamaEmu(iD L)를 실행합니다. 양쪽 게임의 연결 메뉴에서 실제 iD L처럼 진행하세요.", + "pairHintV3": "두 기기를 상단으로 연결하고 V3Emu를 실행합니다. 양쪽 게임의 연결 메뉴에서 실제 V3처럼 진행하세요.", + "pairHintT7": "두 기기를 상단으로 연결하고 T7Emu(타마고)를 실행합니다. 양쪽에서 연결 → TAMA-GO → VISIT 또는 GAME. 방문하는 기기에서 B를 누르세요.", + "mmLink": "Paramix 브리지", + "mmDrag": "북마크 바로 끌어 놓은 뒤 mixing-meets.com에서 클릭하세요.", + "mmHint": "1. Paramix 브리지 버튼을 Chrome·Edge 북마크 바로 끌어 놓습니다.\n2. UART 연결을 해제하거나 도구를 닫습니다. 기록할 때처럼 어댑터를 연결하고 본체에서 CONNECTION → APP → VISIT를 선택합니다. 돌아올 때는 A → GO BACK → YES.\n3. mixing-meets.com의 Connect 또는 Return에서 북마크를 누른 뒤 Select Tamagotchi로 어댑터를 선택합니다.\n페이지를 이동할 때마다 북마크를 다시 누르세요.", + "t7Gp": "고치 포인트", + "t7GpHint": "저장 가져오기처럼 ROM에 적용합니다. 다마고치는 유지하고 실행 상태는 초기화합니다. 본체에서 DOWNLOAD를 선택하세요.", + "t18KeepAsk": "T18Emu 아이템 또는 포인트가 변경되었습니다. ‘저장 데이터 유지’를 켜도 기기의 해당 저장을 ROM을 읽은 시점의 저장으로 교체합니다. 계속할까요?", + "t18ItemNo": "번호 {n}", + "t18ItemOk": "{n}을 {k}에 넣었습니다.", + "t18Points": "다마포인트", + "t18A_food": "음식", + "t18A_item": "아이템", + "t18A_acc": "액세서리", + "t18A_room": "방", + "t18RoomBack": "사용자 방 제거", + "t18RoomBuiltin": "기본 방", + "dlcPick": "다운로드 콘텐츠 추가", + "dlcInfo": "사용 중인 슬롯 보기", + "progMore": "설정과 콘텐츠", + "progMakeMain": "주 프로그램으로 지정", + "progIsMain": "주 프로그램", + "v1Ok": "초기 다마고치 또는 디지몬을 인식했습니다(V1Emu).", + "v3Ok": "다마고치 커넥션 V3를 인식했습니다(V3Emu).", + "v3Use": "홈 화면에서 A+C를 누르면 실행합니다. 휠을 짧게 누르면 설정이 열립니다. 길게 누르면 파라다이스로 돌아갑니다.", + "optVol": "소리 크기", + "optVolN": "보통", + "optVolQ": "작게", + "optVolL": "크게", + "optOff": "끔", + "optDim": "밝기", + "optScr": "화면 자동 꺼짐", + "optDev": "본체에서도 휠을 짧게 눌러 설정할 수 있습니다. 본체 설정은 웹에서 다시 변경하기 전까지 유지됩니다.", + "optScrToy": "원래 기기 설정", + "v1Use": "홈 화면에서 A+C를 누르면 실행합니다. 휠을 짧게 누르면 설정이 열립니다. 휠을 돌리면 흔들고 길게 누르면 파라다이스로 돌아갑니다.", + "progNoMainDoom": "DOOM이 주 프로그램입니다. 바꾸려면 DOOM을 ×로 먼저 제거하세요.", + "doomAutoHint": "휠을 2초 누르면 파라다이스로 돌아가 그대로 유지됩니다.", + "progReplaced": "주 프로그램을 {o}에서 {n}으로 바꿨습니다.", + "mainAuto": "모든 프로그램이 들어가도록 {n}을 메뉴의 첫 항목으로 바꿨습니다.", + "mainNoRoom": "첫 항목으로 바꾸려면 약 {k} KB가 더 필요합니다. 기존 구성을 유지합니다.", + "appTwice": "{n}은 이미 들어 있습니다.", + "progNoMainV1": "V1Emu는 본체 메뉴에서만 실행합니다", + "progNoMain": "실행 전용 구성에서만 가능", + "progMainNow": "{n}이 주 프로그램입니다. 위치가 바뀐 프로그램들의 저장이 초기화됩니다.", + "dlcLoading": "읽는 중…", + "dlcNewArea": "에뮬레이터의 메모리 배치를 다시 구성합니다. 기록 후 해당 저장이 초기화됩니다.", + "dlcHint": "음식·옷·액세서리·게임 등의 .jpg 다운로드 파일 또는 .zip을 선택하세요. 여러 파일을 함께 선택할 수 있습니다. P's의 VDP는 세트 전체를 선택하세요.", + "dlcFreeN": "{n}개 남음", + "dlcDel": "제거", + "dlcK0": "식사", + "dlcK1": "간식", + "dlcK2": "의상", + "dlcK3": "액세서리", + "dlcK4": "아이템", + "dlcK5": "일상용품", + "dlcK6": "배경", + "dlcK7": "게임", + "dlcK8": "방문 장소", + "dlcK10": "VDP 레시피", + "dlcK15": "장식", + "dlcK16": "쿠폰", + "dlcK17": "빙고", + "dlcK18": "가챠", + "dlcK19": "캐릭터", + "dlcOk": "{n}을 {k}의 {s}번 슬롯에 넣었습니다.", + "dlcBad": "{f}: {e}", + "dlcGone": "{n} 제거 완료.", + "figField": "지역:", + "figAll": "전체", + "zipField": "지역을 ZIP으로 내보내기", + "fieldZipOk": "{f}: 캐릭터 {n}개와 이미지 {s}개를 ZIP으로 내보냈습니다.", + "fieldIn": "지역 ZIP 가져오기", + "fieldInBad": "지역 ZIP이 아닙니다(field.json 없음).", + "fieldInOk": "{src} → {dst}: {n}개 부분 적용.", + "fieldInEyes": "눈 이미지가 너무 큰 캐릭터 {k}개는 원본을 유지합니다.", + "zipFigs": "모든 캐릭터 ZIP", + "zipAll": "전체 이미지 ZIP", + "upload": "이미지 시트 가져오기(PNG·ZIP)", + "numbers": "번호 확인용 ROM", + "figHint": "캐릭터는 큰 모습·작은 모습 각각의 몸·눈·입으로 구성됩니다. 캐릭터를 누르면 이미지 시트를 볼 수 있습니다.", + "allHint": "배경, 메뉴, 아이템, 글꼴 이미지입니다.", + "moreColors": "더 많은 색상 허용(최대 256색)", + "dimLoad": "카드 열기", + "dimHint": "캐릭터 카드(4 MB) 또는 TamaSma 카드(1·2 MB) 덤프를 엽니다. 성체 교체에 적합합니다. 아기·유아·성장기는 눈을 공유하므로 원본을 유지합니다.", + "dimPick": "카드 캐릭터", + "dimTarget": "교체할 캐릭터", + "dimApply": "적용", + "dimEgg": "카드의 알 적용", + "dimBaby": "아기", + "dimNone": "카드를 열면 캐릭터가 표시됩니다.", + "download": "이미지 시트 다운로드", + "uploadOne": "이미지 시트 가져오기", + "reset": "원본으로 복원", + "close": "닫기", + "working": "잠시만 기다려 주세요…", + "dimNr": "번호", + "stUpd": "저장 시 업데이트", + "disclaimer": "기기 변경·기록으로 기기가 동작하지 않거나 저장 데이터가 지워질 수 있습니다. 먼저 원본을 백업하고 작업 내용을 이해한 뒤 사용하세요. 도구는 보증 없이 제공되며 기기·데이터 손상에 대한 책임을 지지 않습니다.", + "trademarks": "Tamagotchi·Digimon은 BANDAI의 상표입니다. DOOM·Wolfenstein은 id Software(ZeniMax Media)의 상표입니다. Game Boy·Pokémon mini는 Nintendo의 상표입니다. SEGA·Master System은 SEGA의 상표입니다. Arduboy는 Arduboy Inc.의 상표입니다. 상표·게임·캐릭터는 각 권리자의 소유이며 호환성 설명을 위해 언급합니다. 공식 제품이 아니며 해당 회사와 관련이 없습니다. 도구에 게임·펌웨어·게임 데이터는 포함되지 않습니다. 본인의 파일을 사용하세요.", + "devWarn": "기록 전 원본을 백업하고 기록 중에는 전원을 유지하세요. 기기 기록에 대한 보증은 제공되지 않습니다.", + "footer": "파일 열기와 편집은 브라우저에서 처리합니다. 원작: mameise · 한국어판: ITOSM.", + "edition": "에디션", + "sprites": "이미지", + "figures": "캐릭터", + "changed": "변경됨", + "space": "캐릭터 여유 공간", + "figure": "캐릭터", + "sprite": "이미지", + "mSize": "칸 {w}×{h}, 이미지 {n}개, 격자 {iw}×{ih}", + "mColors": "{c}, 팔레트 세트: {p}", + "mDirect": "직접 색상 RGB565", + "mPal": "{n}색", + "mKeep": "여러 팔레트 세트(색상 변형): 가져오는 이미지에 원본 색상을 사용합니다.", + "mSheet": "시트 {w}×{h}px. 격자가 맞도록 크기를 유지하세요.", + "mGroupRows": "행 순서: 몸(20), 눈(20), 입(18), 작은 몸(24), 작은 눈(14), 작은 입(14).", + "notRom": "파라다이스 덤프가 아닙니다: {e}", + "loaded": "{ed} 열기 완료: 이미지 {s}개, 캐릭터 {f}개.", + "saved": "저장 완료: {name}\n이미지 {n}개를 변경했습니다. 남은 공간은 {kb} KB입니다.", + "nothing": "변경한 내용이 없습니다.", + "tooBig": "여유 공간을 초과합니다. {e}", + "upOk": "적용됨: {n}", + "upSkip": "건너뜀: {list}", + "upNone": "일치하는 파일이 없습니다. figur_0237.png 또는 sprite_0014.png 형식이어야 합니다.", + "sprSix": "추가 지역의 이미지는 수정할 수 없습니다.", + "wrongSize": "{f}: {e}", + "resetOk": "원본으로 복원했습니다.", + "dimOk": "카드 캐릭터 {d}을 캐릭터 {g}에 적용했습니다.", + "eggOk": "알을 교체했습니다.", + "numOk": "캐릭터마다 번호를 표시하도록 바꿨습니다. ROM을 저장·기록한 뒤 성장 단계별로 표시되는 번호를 확인하세요.", + "notDim": "알 수 없는 카드: {e}", + "leave": "저장하지 않은 변경 사항이 있습니다.", + "roleFallback": "대체 캐릭터", + "roleBaby": "아기", + "roleAdult": "첫 성체", + "eyeHint": "분홍 테두리는 눈입니다. 눈 레이어로 옮겨 깜빡임과 눈 표시를 유지합니다. 잘못 잡혔다면 눈을 클릭하세요.", + "eyeNone": "보이는 눈이 없는 캐릭터", + "dimEyesTooBig": "눈 이미지가 너무 복잡해 눈 레이어를 적용하지 않았습니다.", + "roleFallbackText": "캐릭터를 불러오지 못할 때 표시됩니다. 원본 유지를 권장합니다.", + "roleBabyText": "알에서 부화합니다.", + "roleAdultText": "여기부터 각 캐릭터가 고유한 눈을 사용합니다.", + "mEyes": "눈 이미지의 바이트 크기를 유지해야 합니다. 너무 복잡한 눈은 거부하며 크기가 맞지 않으면 대체 캐릭터가 부화할 수 있습니다.", + "mColorsFig": "원본 색상만 사용하면 게임의 개체별 색상 변경을 유지합니다. 새 색상은 고정 색상으로 적용합니다(최대 8색과 외곽선).", + "fl_timeout": "기기 응답 시간 초과({c} {a})", + "fl_noAck": "기기가 응답하지 않습니다. 다운로드 화면인지 확인하세요.", + "fl_repeats": "로드 재시도가 너무 많습니다", + "fl_devCancel": "기기에서 로드를 취소했습니다", + "fl_unexpected": "예상하지 못한 응답: {r}", + "fl_hello": "HELLO에 대한 응답이 올바르지 않습니다", + "fl_notReady": "플래시가 준비되지 않았습니다", + "fl_readErr": "{a} 읽기 오류", + "fl_noCrc": "{a}의 체크섬이 없습니다", + "fl_cancelled": "취소됨", + "fl_size": "ROM 이미지 크기는 정확히 16 MB여야 합니다", + "fl_notParadise": "파라다이스 이미지가 아닙니다(SONIXDEV 없음)", + "fl_cancelledWrite": "기록 취소됨. 본체 전원을 유지하고 다시 기록하세요", + "fl_notAccepted": "섹터 {a}을 받지 못했습니다. 전원을 유지하고 다시 기록하세요", + "fl_differs": "기록 후 섹터 {a}이 일치하지 않습니다. 전원을 유지하고 다시 기록하세요", + "fl_checkFail": "{a} 검증 실패. 전원을 유지하고 다시 기록하세요", + "fl_rescueBusy": "복구 영역(0xFF0000)이 사용 중입니다", + "fl_rescueMode": "이전 기록이 중단되었습니다. 본체의 기록 화면에서 다시 기록하세요.", + "fl_rescueFail": "복구 시작 프로그램 기록이 올바르지 않습니다", + "fl_noRescue": "복구 시작 불가: 0xFF0000이 사용 중입니다", + "fl_noAnswer": "응답이 없습니다. 본체를 다운로드 화면으로 전환하고 다시 시도하세요", + "fl_noData": "어댑터에서 데이터가 전혀 들어오지 않습니다. 다운로드 화면에서 다시 시도하고 케이블·드라이버를 확인하세요", + "fl_garbled": "데이터를 읽을 수 없습니다({n}바이트: {h}). TX·RX 배선과 어댑터 드라이버를 확인하세요", + "fl_lost": "기록 전에 기기 응답이 끊겨 아무것도 기록하지 않았습니다. 전원을 껐다 켜고 다운로드 화면에서 다시 연결하세요", + "fl_appSilent": "기록 프로그램을 전송했지만 응답하지 않습니다. 다시 시도하세요", + "fl_unknownEd": "새 ROM의 에디션을 알 수 없습니다. ‘저장 데이터 유지’를 해제하세요", + "fl_otherEd": "기기는 {d}입니다. 새 ROM은 {r}입니다. 에디션을 바꾸려면 ‘저장 데이터 유지’를 해제하세요", + "fl_noteNoFit": "지역 {f}의 저장이 새 슬롯에 맞지 않아 유지하지 않습니다", + "fl_noteMoved": "지역 {f}의 저장을 새 슬롯으로 옮겼습니다", + "fl_noteSaveMoved": "{n}의 저장을 보존했습니다", + "fl_noteDropped": "새 ROM에 지역 메뉴가 없어 기기에 보관된 지역별 저장이 삭제됩니다", + "fl_noteEdKept": "기기({d})와 새 ROM({r})은 같은 펌웨어를 사용합니다. 기기의 저장 데이터와 지역({d})을 유지합니다", + "fl_noteEmu": "TamaEmu 펌웨어를 새로 선택해 초기 상태로 시작합니다. 업데이트만 하려면 기존 ROM을 열고 저장하세요", + "menuKo": "본체 A+C 메뉴를 한국어로 만들기", + "menuKoHint": "A+C 메뉴의 화면과 다마고치 및 아이템 이름을 한국어로 표시합니다." +}; +T.en.menuKo="Korean A+C device menu"; +T.en.menuKoHint="Experimental Korean device menu: PC preview and build checks only; hardware, save and restore are not yet verified. Back up your ROM and saves before applying. Original game, emulator settings and names read from your ROM remain unchanged."; +T.de.menuKo=T.en.menuKo;T.de.menuKoHint=T.en.menuKoHint; +/* ITOSM_KO_END */ +let lang = 'de'; +try { lang = localStorage.getItem('paramix-lang') || 'ko'; } catch (e) {} +if (!T[lang]) lang = 'en'; +function t(k, vars) { let s = (T[lang][k] ?? T.en[k] ?? k); if (vars) for (const [a, b] of Object.entries(vars)) s = s.split('{' + a + '}').join(b); return s; } +/* Messages of the modules (core, emu, doom, feld) are English; the German page + translates them here. Placeholders ($1, $2) carry numbers and names. */ +const MSG_KO = [ + [/^no ARC2 archive at (\S+)$/, '$1에 ARC2 아카이브가 없습니다'], + [/^unknown bpp (\S+)$/, '알 수 없는 색상 깊이: $1'], + [/^subimage count does not match$/, '부분 이미지 개수가 다릅니다'], + [/^subimage size does not match$/, '부분 이미지 크기가 다릅니다'], + [/^eye image too detailed: (\d+) bytes, at most (\d+) allowed$/, '눈 이미지가 너무 큽니다: $1바이트, 최대 $2바이트'], + [/^not a Paradise flash dump \(SONIXDEV header missing\)$/, '파라다이스 덤프가 아닙니다(SONIXDEV 헤더 없음)'], + [/^unexpected asset archive \((\d+) files\)$/, '예상하지 못한 자료 구성(파일 $1개)'], + [/^too big: assets would end at (\S+), free space ends at (\S+)$/, '데이터가 $1까지 필요하지만 여유 공간은 $2까지입니다'], + [/^checksum wrong at (\S+)$/, '$1 체크섬 오류'], + [/^(?:character )?sheet must be (\S+) px, got (\S+)$/, '시트 크기는 $1px여야 합니다(현재 $2)'], + [/^no sprite package$/, '이미지 패키지가 없습니다'], + [/^not a ZIP file$/, 'ZIP 파일이 아닙니다'], + [/^unsupported ZIP compression in (.+)$/, '$1: 지원하지 않는 ZIP 압축 방식'], + [/^firmware not recognised \(expected a 4 MB or 8 MB image of a colour Tamagotchi\)$/, '컬러 다마고치의 4 MB 또는 8 MB 펌웨어가 필요합니다'], + [/^scene table not found$/, '장면 표를 찾지 못했습니다'], + [/^firmware too big: (\d+) blocks$/, '펌웨어가 너무 큽니다: $1블록'], + [/^no room for the spare pages$/, '여분 페이지를 넣을 공간이 없습니다'], + [/^launcher template does not fit$/, '실행 프로그램 형식이 맞지 않습니다'], + [/^the Paradise image must be 16 MB$/, '파라다이스 이미지 크기는 16 MB여야 합니다'], + [/^home screen not found$/, '홈 화면을 찾지 못했습니다'], + [/^area (\S+) is in use$/, '$1 영역이 사용 중입니다'], + [/^emulator program too big$/, '에뮬레이터 프로그램이 너무 큽니다'], + [/^program too big$/, '프로그램이 너무 큽니다'], + [/^settings block missing in the program$/, '프로그램의 설정 영역이 없습니다'], + [/^no emulator built in$/, '설치된 에뮬레이터가 없습니다'], + [/^no download content in the file$/, '파일에 다운로드 콘텐츠가 없습니다'], + [/^content checksum does not match$/, '콘텐츠 체크섬이 다릅니다'], + [/^this content fits no store of this firmware$/, '이 펌웨어에 맞는 콘텐츠 저장 영역이 없습니다'], + [/^content too big for its store$/, '콘텐츠가 저장 영역보다 큽니다'], + [/^only for the 8 MB firmware$/, '8 MB 펌웨어에서만 지원합니다'], + [/^no matching store$/, '맞는 저장 영역이 없습니다'], + [/^already added$/, '이미 추가했습니다'], + [/^(.+): all slots used, remove one first$/, '$1: 슬롯이 가득 찼습니다. 하나를 먼저 제거하세요'], + [/^no such slot$/, '해당 슬롯이 없습니다'], + [/^not a TG18 firmware \(8 MB\)$/, 'TG18 펌웨어(8 MB)가 아닙니다'], + [/^not enough room: the firmware needs (\d+) blocks of 64 KB, (\d+) are free$/, '64 KB 블록 $1개가 필요하지만 $2개만 비어 있습니다'], + [/^T18Emu program incomplete \(flash part missing\)$/, 'T18Emu 프로그램이 불완전합니다(플래시 부분 없음)'], + [/^the menu is already built in$/, '본체 메뉴가 이미 설치되어 있습니다'], + [/^more fields need a Tropical, Glacier or Jade Forest ROM with the original firmware$/, '지역 확장에는 원본 펌웨어의 트로피컬·글레이셔·제이드 포레스트 ROM이 필요합니다'], + [/^rain pictures too big$/, '비 이미지가 너무 큽니다'], + [/^unexpected Jade Forest data$/, '예상하지 못한 제이드 포레스트 데이터'], + [/^helper page full$/, '보조 페이지가 가득 찼습니다'], + [/^table (\S+) missing$/, '$1 표가 없습니다'], + [/^the second ROM must be a Land, Water or Sky ROM$/, '두 번째 파일은 랜드·워터·스카이 ROM이어야 합니다'], + [/^six fields program missing$/, '여섯 지역 프로그램이 없습니다'], + [/^unexpected map picture$/, '예상하지 못한 지역 이미지'], + [/^unexpected Land picture (\d+)$/, '예상하지 못한 랜드 이미지 $1'], + [/^composite table full$/, '합성 이미지 표가 가득 찼습니다'], + [/^menu program too old for six fields$/, '여섯 지역을 지원하지 않는 구버전 메뉴입니다'], + [/^edition not recognised$/, '에디션을 인식하지 못했습니다'], + [/^nothing chosen$/, '선택한 내용이 없습니다'], + [/^no room for the launcher$/, '실행 프로그램을 넣을 공간이 없습니다'], + [/^no room for the menu next to DOOM$/, 'DOOM과 함께 메뉴를 넣을 공간이 없습니다'], + [/^no room for the saves next to DOOM$/, 'DOOM과 함께 저장 데이터를 넣을 공간이 없습니다'], + [/^menu program too big$/, '본체 메뉴가 허용 용량을 초과합니다'], + [/^the area for the menu is in use$/, '메뉴 영역이 사용 중입니다'], + [/^no room for the saves$/, '저장 데이터를 넣을 공간이 없습니다'], + [/^the area for the saves is in use$/, '저장 영역이 사용 중입니다'], + [/^settings block of the menu missing$/, '메뉴의 설정 영역이 없습니다'], + [/^the stored save of (.+) does not fit here$/, '$1의 저장이 이 영역에 맞지 않습니다'], + [/^not a WAD file$/, 'WAD 파일이 아닙니다'], + [/^no DOOM maps in the WAD \(DOOM 2 is not supported\)$/, 'WAD에 DOOM 지도가 없습니다(이 구성에서는 DOOM 2 미지원)'], + [/^no picture$/, '이미지가 없습니다'], + [/^broken$/, '손상된 데이터입니다'], + [/^WAD conversion failed$/, 'WAD 변환 실패'], + [/^the character data reaches (\S+), DOOM needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. DOOM은 0x830000 이후가 필요합니다'], + [/^DOOM program too big$/, 'DOOM 프로그램이 너무 큽니다'], + [/^WAD too big: (\d+) KB, room (\d+) KB \(try without music\)$/, 'WAD $1 KB, 여유 공간 $2 KB. 음악을 끄고 시도하세요'], + [/^this DOOM has no key layout of its own yet$/, '이 DOOM은 개별 버튼 설정을 지원하지 않습니다'], + [/^fire, forward and back need three different buttons$/, '발사·전진·후진은 서로 다른 버튼이어야 합니다'], + [/^use needs its own button or the wheel$/, '사용은 별도의 버튼 또는 휠이어야 합니다'], + [/^no room for the field saves next to this emulator firmware$/, '이 펌웨어와 함께 지역 저장을 넣을 공간이 없습니다'], + [/^the character data reaches (\S+), the emulator needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. 에뮬레이터는 0x830000 이후가 필요합니다'], + [/^the stored saves do not fit into the room for the fields$/, '보관한 저장이 지역 저장 공간을 초과합니다'], + [/^unexpected planet table in the Land ROM$/, '랜드 ROM의 행성 표가 예상과 다릅니다'], + [/^not a Paradise save \(\.tamasave\)$/, '파라다이스 저장(.tamasave)이 아닙니다'], + [/^unknown save version (\S+)$/, '알 수 없는 저장 버전: $1'], + [/^save is cut off$/, '저장 데이터가 잘렸습니다'], + [/^no room for (.+) \((\d+) KB\)$/, '$1을 넣을 공간이 없습니다($2 KB)'], + [/^no room for (.+)$/, '$1을 넣을 공간이 없습니다'], + [/^only one T18Emu$/, 'T18Emu는 하나만 추가할 수 있습니다'], + [/^T18Emu needs the area at 0x0F0000, the main program uses it: choose T18Emu in the Emulator tab$/, 'T18Emu가 필요한 0x0F0000 영역을 주 프로그램이 사용합니다. 에뮬레이터 탭에서 T18Emu를 선택하세요'], + [/^(.+): only in a start device$/, '$1: 실행 전용 구성에서만 가능합니다'], + [/^too many scenes$/, '장면이 너무 많습니다'] +]; + +const MSG_DE = [ + [/^no ARC2 archive at (\S+)$/, 'kein ARC2-Archiv bei $1'], + [/^unknown bpp (\S+)$/, 'unbekannte Farbtiefe $1'], + [/^subimage count does not match$/, 'Anzahl der Teilbilder passt nicht'], + [/^subimage size does not match$/, 'Grösse der Teilbilder passt nicht'], + [/^eye image too detailed: (\d+) bytes, at most (\d+) allowed$/, 'Augenbild zu detailliert: $1 Byte, höchstens $2 erlaubt'], + [/^not a Paradise flash dump \(SONIXDEV header missing\)$/, 'kein Paradise-Flash-Dump (SONIXDEV-Kopf fehlt)'], + [/^unexpected asset archive \((\d+) files\)$/, 'unerwartetes Archiv ($1 Dateien)'], + [/^too big: assets would end at (\S+), free space ends at (\S+)$/, 'zu gross: die Daten würden bei $1 enden, der freie Platz endet bei $2'], + [/^checksum wrong at (\S+)$/, 'Prüfsumme falsch bei $1'], + [/^sheet must be (\S+) px, got (\S+)$/, 'das Sheet muss $1 px gross sein, ist aber $2'], + [/^character sheet must be (\S+) px, got (\S+)$/, 'das Figuren-Sheet muss $1 px gross sein, ist aber $2'], + [/^no sprite package$/, 'kein Sprite-Paket'], + [/^not a ZIP file$/, 'keine ZIP-Datei'], + [/^unsupported ZIP compression in (.+)$/, 'nicht unterstützte ZIP-Kompression in $1'], + [/^firmware not recognised \(expected a 4 MB or 8 MB image of a colour Tamagotchi\)$/, 'Firmware nicht erkannt (erwartet: 4-MB- oder 8-MB-Abbild eines Farb-Tamas)'], + [/^scene table not found$/, 'Szenentabelle nicht gefunden'], + [/^firmware too big: (\d+) blocks$/, 'Firmware zu gross: $1 Blöcke'], + [/^no room for the spare pages$/, 'kein Platz für die Ersatzseiten'], + [/^launcher template does not fit$/, 'Starter-Vorlage passt nicht'], + [/^the Paradise image must be 16 MB$/, 'das Paradise-Abbild muss 16 MB gross sein'], + [/^home screen not found$/, 'Heimbildschirm nicht gefunden'], + [/^area (\S+) is in use$/, 'Bereich $1 ist belegt'], + [/^emulator program too big$/, 'Emulator-Programm zu gross'], + [/^program too big$/, 'Programm zu gross'], + [/^settings block missing in the program$/, 'Einstellungsblock im Programm fehlt'], + [/^no emulator built in$/, 'kein Emulator eingebaut'], + [/^no download content in the file$/, 'kein Download-Inhalt in der Datei'], + [/^content checksum does not match$/, 'Prüfsumme des Inhalts stimmt nicht'], + [/^this content fits no store of this firmware$/, 'dieser Inhalt passt in kein Fach dieser Firmware'], + [/^content too big for its store$/, 'Inhalt zu gross für sein Fach'], + [/^only for the 8 MB firmware$/, 'nur für 8-MB-Firmware'], + [/^no matching store$/, 'kein passendes Fach'], + [/^already added$/, 'schon drin'], + [/^(.+): all slots used, remove one first$/, (m, a) => storeDe(a) + ': alle Plätze belegt, zuerst einen entfernen'], + [/^no such slot$/, 'kein solcher Platz'], + [/^not a TG18 firmware \(8 MB\)$/, 'keine TG18-Firmware (8 MB)'], + [/^not enough room: the firmware needs (\d+) blocks of 64 KB, (\d+) are free$/, 'zu wenig Platz: die Firmware braucht $1 Blöcke zu 64 KB, frei sind $2'], + [/^T18Emu program incomplete \(flash part missing\)$/, 'T18Emu-Programm unvollständig (Flash-Teil fehlt)'], + [/^the menu is already built in$/, 'das Menü ist schon eingebaut'], + [/^more fields need a Tropical, Glacier or Jade Forest ROM with the original firmware$/, 'mehr Felder gehen nur mit einem Tropical-, Glacier- oder Jade-Forest-ROM mit Original-Firmware'], + [/^rain pictures too big$/, 'Regenbilder zu gross'], [/^area 0xF00000 is in use$/, 'Bereich 0xF00000 ist belegt'], [/^unexpected Jade Forest data$/, 'unerwartete Jade-Forest-Daten'], [/^helper page full$/, 'Hilfsseite voll'], [/^table (\S+) missing$/, 'Tabelle $1 fehlt'], + [/^the second ROM must be a Land, Water or Sky ROM$/, 'das zweite ROM muss ein Land-, Water- oder Sky-ROM sein'], + [/^six fields program missing$/, 'Programm für 6 Felder fehlt'], + [/^unexpected map picture$/, 'unerwartetes Feldbild'], + [/^unexpected Land picture (\d+)$/, 'unerwartetes Land-Bild $1'], + [/^composite table full$/, 'Bildtabelle voll'], + [/^menu program too old for six fields$/, 'Menüprogramm zu alt für 6 Felder'], + [/^edition not recognised$/, 'Ausgabe nicht erkannt'], + [/^nothing chosen$/, 'nichts gewählt'], + [/^no room for the launcher$/, 'kein Platz für den Starter'], + [/^no room for the menu next to DOOM$/, 'neben DOOM ist kein Platz für das Menü'], + [/^no room for the saves next to DOOM$/, 'neben DOOM ist kein Platz für die Spielstände'], + [/^menu program too big$/, 'Menü-Programm zu gross'], + [/^the area for the menu is in use$/, 'der Bereich für das Menü ist belegt'], + [/^no room for the saves$/, 'kein Platz für die Spielstände'], + [/^the area for the saves is in use$/, 'der Bereich für die Spielstände ist belegt'], + [/^settings block of the menu missing$/, 'Einstellungsblock des Menüs fehlt'], + [/^the stored save of (.+) does not fit here$/, 'der gespeicherte Spielstand von $1 passt hier nicht hinein'], + [/^not a WAD file$/, 'keine WAD-Datei'], + [/^no DOOM maps in the WAD \(DOOM 2 is not supported\)$/, 'keine DOOM-Karten in der WAD (DOOM 2 wird nicht unterstützt)'], + [/^no picture$/, 'kein Bild'], + [/^broken$/, 'beschädigt'], + [/^WAD conversion failed$/, 'WAD-Umwandlung fehlgeschlagen'], + [/^the character data reaches (\S+), DOOM needs 0x830000 onwards$/, 'die Figuren-Daten reichen bis $1, DOOM braucht den Platz ab 0x830000'], + [/^DOOM program too big$/, 'DOOM-Programm zu gross'], + [/^WAD too big: (\d+) KB, room (\d+) KB \(try without music\)$/, 'WAD zu gross: $1 KB, Platz $2 KB (ohne Musik versuchen)'], + [/^this DOOM has no key layout of its own yet$/, 'dieses DOOM kennt noch keine eigene Tastenbelegung'], + [/^fire, forward and back need three different buttons$/, 'Schiessen, Vor und Zurück brauchen drei verschiedene Tasten'], + [/^use needs its own button or the wheel$/, 'Benutzen braucht eine eigene Taste oder das Rad'], + [/^no room for the field saves next to this emulator firmware$/, 'neben dieser Emulator-Firmware haben die Spielstände der Felder keinen Platz'], + [/^the character data reaches (\S+), the emulator needs 0x830000 onwards$/, 'die Figuren-Daten reichen bis $1, der Emulator braucht den Platz ab 0x830000'], + [/^the stored saves do not fit into the room for the fields$/, 'die gespeicherten Spielstände passen nicht in den Platz für die Felder'], + [/^script table full$/, 'Skripttabelle voll'], + [/^unexpected Land planet table$/, 'unerwartete Planetentabelle im Land-ROM'], + [/^not a Paradise save \(\.tamasave\)$/, 'kein Paradise-Spielstand (.tamasave)'], + [/^unknown save version (\S+)$/, 'unbekannte Spielstand-Version $1'], + [/^save is cut off$/, 'der Spielstand ist abgeschnitten'], + [/^no room for (.+) \((\d+) KB\)$/, 'kein Platz für $1 ($2 KB)'], + [/^no room for (.+)$/, 'kein Platz für $1'], + [/^only one T18Emu$/, 'T18Emu geht nur einmal'], + [/^T18Emu needs the area at 0x0F0000, the main program uses it: choose T18Emu in the Emulator tab$/, 'T18Emu braucht den Bereich ab 0x0F0000, das Hauptprogramm belegt ihn: T18Emu im Tab Emulator wählen'], + [/^(.+): only in a start device$/, '$1: nur im Startgerät'], + [/^launcher template does not fit$/, 'Starter-Vorlage passt nicht'], + [/^too many scenes$/, 'zu viele Szenen'], +]; +function storeDe(label) { const k = ['Meals', 'Snacks', 'Clothing', 'Accessories', 'Items', 'Daily items', 'Wallpapers', 'Games', 'Destinations', '', 'VDP recipes', '', '', '', '', 'Decorations', 'Coupon', 'Bingo', 'Gashapon', 'Characters'].indexOf(label); return k < 0 ? label : t('dlcK' + k); } +function em(x) { + const s = x && typeof x === 'object' ? (x.message || String(x)) : String(x || ''); + if (lang === 'en') return s; + if (lang === 'ko') { for (const [re, ko] of MSG_KO) if(re.test(s)) return s.replace(re,ko); return s; } + for (const [re, de] of MSG_DE) if (re.test(s)) return s.replace(re, de); + return s; +} +function applyLang() { + document.documentElement.lang = lang; + document.querySelectorAll('[data-t]').forEach(el => { el.textContent = t(el.dataset.t); }); + document.querySelectorAll('[data-lang]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.lang === lang))); + if (state.ctx) { + renderInfo(); renderDim(); renderFieldPick(); renderNames(); renderEmu(); renderDoom(); renderFeld(); renderSave(); + {const chars=C.charTable(state.ctx.files[0]).filter(c=>c.id>1000&&c.id<9000);chars.forEach((c,i)=>state.charNames.set(state.ctx.groups[i+1],C.textGet(state.ctx.rom,c.name,lang)));} + document.querySelectorAll('#gridFigs .tile').forEach((b) => { const g = +b.dataset.idx; b.querySelector('.cap span').textContent = [state.charNames.get(g), groupRole(g)].filter(Boolean).join(' '); }); + if (state.open) openDrawer(state.open.kind, state.open.idx); + } + try { if (!dv.run) devRender(); } catch (e) {} // dv does not exist yet on the first call +} +document.querySelectorAll('[data-lang]').forEach(b => b.onclick = () => { lang = b.dataset.lang; try { localStorage.setItem('paramix-lang', lang); } catch (e) {} applyLang(); }); + +// ------------------------------------------------------------------ state +const featureKeys=['emu','gb','sms','pm','ab','doom','wolf','standalone','cards']; +let siteFeatures=Object.fromEntries(featureKeys.map(k=>[k,false])); +function featureEnabled(key){if(key==='extras')return featureKeys.some(k=>k!=='cards'&&siteFeatures[k]);if(key==='games')return siteFeatures.doom||siteFeatures.wolf;if(key==='consoles')return ['gb','sms','pm','ab'].some(k=>siteFeatures[k]);return siteFeatures[key]===true;} +function applyFeatures(flags={}){siteFeatures=Object.fromEntries(featureKeys.map(k=>[k,flags[k]===true]));for(const k of [...featureKeys,'extras','games','consoles'])document.documentElement.setAttribute('data-feature-'+k,featureEnabled(k)?'on':'off');const active=document.querySelector('.tab[aria-selected="true"][data-feature]');if(active&&!featureEnabled(active.dataset.feature))document.querySelector('[data-tab="figs"]').click();if(state.ctx)renderPlan();} +document.addEventListener('click',e=>{const el=e.target.closest('[data-feature]');if(el&&!featureEnabled(el.dataset.feature)){e.preventDefault();e.stopImmediatePropagation();}},true); +const state = { ctx: null, name: '', changed: new Map(), dim: null, open: null, zoom: 2, decoded: new Map(), eyeOffsets: new Map(), eyeRects: new Map(), eyeLayer: false, fields: [], charNames: new Map() }; +const entry = (i) => state.changed.get(i) || (state.launch && state.launchMap && state.launchMap.get(i)) || state.ctx.entries[i]; +/* 1.7.2 CLEAN_ROM: start device without any Paradise code (Menu tab); the menu starts right away, sets the clock + * itself, and almost the whole flash is for programs */ +const CLEAN_ROM = true; +const menuWanted = () => !!(state.feld || state.bag || state.tama || state.gplay || state.launch); +/* launcher ROM (1.6.8): the small images, computed once per ROM */ +function launchMapGet() { if (!state.launchMap) state.launchMap = C.launcherChanges(state.ctx); return state.launchMap; } +function decode(i) { + const e = entry(i); + let d = state.decoded.get(i); + if (!d || d.src !== e) { d = { src: e, dec: C.spriteDecode(e) }; state.decoded.set(i, d); } + return d.dec; +} + +// ------------------------------------------------------------ helpers +function toast(msg, err) { if (toast.mute) { if (err) toast.mute.err = msg; return; } const el = $('toast'); el.textContent = msg; el.className = 'toast on' + (err ? ' err' : ''); clearTimeout(toast.t); toast.t = setTimeout(() => el.className = 'toast', err ? 9000 : 5000); } +async function busy(fn) { $('busy').classList.add('on'); await new Promise(r => setTimeout(r, 30)); try { return await fn(); } finally { $('busy').classList.remove('on'); } } +function imgToCanvas(img, scale = 1, cv) { + cv = cv || document.createElement('canvas'); cv.width = img.w * scale; cv.height = img.h * scale; + const tmp = document.createElement('canvas'); tmp.width = img.w; tmp.height = img.h; + tmp.getContext('2d').putImageData(new ImageData(img.data, img.w, img.h), 0, 0); + const g = cv.getContext('2d'); g.imageSmoothingEnabled = false; g.clearRect(0, 0, cv.width, cv.height); g.drawImage(tmp, 0, 0, cv.width, cv.height); + return cv; +} +function pngBlob(img) { return new Promise(r => imgToCanvas(img).toBlob(r, 'image/png')); } +async function pngBytes(img) { return new Uint8Array(await (await pngBlob(img)).arrayBuffer()); } +async function decodePng(blob) { + const bmp = await createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' }); + const cv = document.createElement('canvas'); cv.width = bmp.width; cv.height = bmp.height; + const g = cv.getContext('2d', { willReadFrequently: true }); g.drawImage(bmp, 0, 0); + const d = g.getImageData(0, 0, bmp.width, bmp.height); + return { w: d.width, h: d.height, data: d.data }; +} +function download(data, name, type) { + const url = URL.createObjectURL(data instanceof Blob ? data : new Blob([data], { type: type || 'application/octet-stream' })); + const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 4000); +} +async function inflateRaw(bytes) { + const ds = new DecompressionStream('deflate-raw'); + const out = await new Response(new Blob([bytes]).stream().pipeThrough(ds)).arrayBuffer(); + return new Uint8Array(out); +} +const pad4 = (n) => String(n).padStart(4, '0'); +const baseName = () => state.name.replace(/\.[^.]+$/, '').replace(/(_paramix|_emu|_t7|_t18|_doom_E\d|_felder|_fields|_4fields|_6fields|_items|_start|_clean)+$/, ''); + +// ------------------------------------------------------------- loading +async function loadRom(file) { + const buf = new Uint8Array(await file.arrayBuffer()); + let ctx; + // CLEAN_ROM: a ROM without the Paradise (start device of this Studio): only the programs, no pictures or texts + const clean = CLEAN_ROM && F.isClean(buf); + if (clean) { const ed = F.edition(buf); ctx = { rom: buf, entries: [], files: [], groups: [], edition: ed ? (FL.EDITIONS[ed.id] || ed.id) : '?', limit: 0, clean: true }; } + else try { ctx = C.openRom(buf); } catch (e) { toast(t('notRom', { e: em(e) }), true); return; } + state.clean = clean; state.cleanInit = clean; + Object.assign(state, { ctx, name: file.name, changed: new Map(), decoded: new Map(), open: null, eyeOffsets: new Map() }); + // 1.7.3 test21 SPR_ALIGN: own Tama pictures of older versions with an odd length are padded (playdates failed at 90 %) + if (!clean) for (const g of ctx.groups) for (let k = 0; k < 6; k++) { const f = C.spriteAlign(ctx.entries[g + k]); if (f) state.changed.set(g + k, f); } + $('start').hidden = true; $('work').classList.add('on'); $('btnSave').disabled = false; + $('romname').textContent = file.name; + state.pmBios = undefined; state.pmKeys = null; state.abKeys = null; + state.emu = null; state.t7save = null; state.t7saveX = null; state.saveIn = null; state.emuRemove = false; state.doom = null; state.doomKeys = null; state.six = null; state.sixName = ''; state.sixWant = false; state.sixOff = false; state.petDirty = false; state.petChanges=null; state.petOriginalId=null; state.texts = new Map(); state.eyeShift = new Map(); state.mouthShift = new Map(); state.poseAdj = new Map(); state.poseCache = null; face.g = -1; state.dlcT = 'main'; state.figT = 'main'; state.dlcOpen = false; state.mainGuest = null; state.emuPack = (() => { const c = romEmuCfg(buf); return !!(c && c.version >= 5 && c.lzOff); })(); state.t18Main = null; state.t18Dirty = false; state.t18Pics = E.t18PicsRead(buf); state.t18PicsDirty = false; state.itemT = 'main'; state.progOpen = new Set(); state.mainPick = null; state.mainDirty = false; state.roomFree = null; state.paraMainTaken = false; + { const si = S6.sixInfo(buf); state.sixPlanet = si && si.version >= 5 ? si.planet : true; state.sixMenu = si && si.version >= 6 ? si.fieldMenu : true; } + { const l = stubList(buf); const g = E.autoGet(buf, l); state.emuAuto = g === null ? E.autoGetOld(buf, l) : g; } + { const c = E.emuClockGet(buf); state.emuClock = c === null ? true : c; } + { const c = E.emuSessGet(buf); state.emuSess = c === null ? true : c; } // 1.7.3 test7 + { const c = E.emuNfcGet(buf); state.emuNfc = c === null ? true : c; } + state.emuOpt = E.emuOptGet(buf) || { vol: 0, dim: 0, off: 0 }; + if(!clean && lang==='ko')for(const it of F.itemCatalog(buf,'ko'))if(it.name==='GASHAPON'){state.texts.set(it.text,'가샤폰');state.textLanguage='ko';} + $('menuKo').checked = F.koreanMenu(buf) || lang==='ko'; + { const fe = F.embedded(), f = fe && F.feldFind(buf, fe.stub); + state.feld = !!(f && (f.flags & F.F_FIELDS)); state.bag = !!(f && (f.flags & F.F_BAG)); state.tama = !!(f && (f.flags & F.F_TAMA)); state.gplay = !!(f && (f.flags & F.F_GPLAY)); state.saves = true; + state.feldInit = state.feld; state.bagInit = state.bag; state.tamaInit = state.tama; state.gplayInit = state.gplay; state.savesInit = true; + state.launch = !!(f && f.version >= 2 && (f.flags & F.F_LAUNCH)); state.launchInit = state.launch; state.launchMap = null; + state.t18Few = false; state.exitKey = EXIT_KEY ? exitGet(buf) : 0; state.exitKeyInit = state.exitKey; if ($('exitKey')) $('exitKey').value = String(state.exitKey); + state.extras = f ? E.appsRead(buf, F.feldApps(buf, fe.stub).apps).map((x) => sessKeep(x, x.kind === 'tama' ? { kind: 'tama', guest: x.guest, dev: x.dev, clock: x.clock, nfc: x.nfc, opt: x.opt, pack: x.pack } : x.kind === 't18' ? { kind: 't18', fw: x.fw, clock: x.clock, opt: x.opt, keepOff: x.off } : x.kind === 'v1' ? { kind: 'v1', rom: x.rom, clock: x.clock } : x.kind === 'gb' ? { kind: 'gb', rom: x.rom, keys: x.keys, inv: x.inv, save: x.save } : x.kind === 'sms' ? { kind: 'sms', rom: x.rom, title: x.title, gg: x.gg, keys: x.keys, inv: x.inv, save: x.save } : x.kind === 'ab' ? { kind: 'ab', rom: x.rom, title: x.title, keys: x.keys, inv: x.inv, save: x.save } : x.kind === 'pm' ? { kind: 'pm', rom: x.rom, title: x.title, keys: x.keys, inv: x.inv, save: x.save, bios: x.bios } : x.kind === 'wolf' ? { kind: 'wolf', pack: x.pack, keys: x.keys, save: x.save } : x.kind === 'doom' ? { kind: 'doom', mcu: x.mcu, keys: x.keys, keys0: JSON.stringify(x.keys), save: x.save, name: x.name, region: x.region } : { rom: x.rom, figs: x.figs || [], clock: x.clock })) : []; state.extrasDirty = false; + state.extrasUp = f ? extrasOld(buf, F.feldApps(buf, fe.stub).apps) : false; + state.wolfInit = state.extras.some((x) => x.kind === 'wolf'); state.wolfKeysDirty = false; + // test5: a T18Emu in the menu whose blocks were emptied (fault up to test4: main program removed in a start device) + // 1.6.11 test2: a T7Emu that can lose the pet's save (old build): named in red until it is written anew + state.oldT7 = []; if (F.emuType(buf) === 't7' && E.t7Outdated(buf)) state.oldT7.push(mainName(buf) || 'TAMA-GO'); + if (f) for (const x of E.appsRead(buf, F.feldApps(buf, fe.stub).apps)) if (E.extraKind(x) === 't7' && E.t7Outdated(buf, x.off)) state.oldT7.push(x.name); + state.t18Broken = state.extras.some((x) => { if (x.kind !== 't18' || x.keepOff === undefined) return false; const c = E.t18Cfg(buf, x.keepOff); if (!c) return false; + let n = 0; for (const b of c.map) if (b !== 0xFFFF && buf.subarray(b << 16, (b + 1) << 16).every((v) => v === 0xFF)) n++; return n >= 8; }); + state.sig0 = { emu: groupSig('emu'), gb: groupSig('gb'), sms: groupSig('sms'), pm: groupSig('pm'), ab: groupSig('ab') }; // 1.6.10 test4: each tab its own chip // 1.6.8: programs of an older Studio are renewed on save + // 1.6.9 test13: start device with DOOM, the main program out of the menu's list and its autostart + state.cleanClock = true; if (f && clean) try { state.cleanClock = !F.feldApps(buf, fe.stub).noClock; } catch (e) {} // 1.7.3 test7 + if (f && state.launch) { const fa = F.feldApps(buf, fe.stub); + if (fa.v9) { state.emuAuto = !!fa.auto; const k = fa.mainSrc ? E.appsRead(buf, fa.apps).findIndex((x) => x.off === fa.mainSrc - 0x10000000 + 0x11000) : -1; state.mainPick = k >= 0 ? state.extras[k] || null : null; } } + // A menu from an older Studio version is rebuilt on save (e.g. 0.9.5 had no item pictures) + state.feldStale = lang==='ko' && !F.koreanMenu(buf); + if (f) { + if (clean) try { const fa = F.feldApps(buf, fe.stub), re = fe.feldc ? F.cleanApply(buf, { apps: fa.apps, dl: fa.dl, mainSrc: fa.mainSrc, auto: fa.auto, noClock: fa.noClock, spot: F.cleanInfo(buf) }, { feld: fe.feldc, stub: fe.stub }) : buf; state.feldStale = re.some((v, i) => v !== buf[i]); } catch (e) { state.feldStale = lang==='ko' && !F.koreanMenu(buf); } + else try { + const embOld = { stub: fe.stub, oldStub: E.embedded() && E.embedded().stub }; + const fa = F.feldApps(buf, fe.stub), low = fa.apps.length ? Math.min(...fa.apps.map((a) => a.src - 0x10000000 + 0x11000)) : 0; + const dl = f.version >= 7 ? (buf[f.off + 0x334] | buf[f.off + 0x335] << 8 | buf[f.off + 0x336] << 16 | buf[f.off + 0x337] << 24) >>> 0 : 0, dlo = dl ? dl - 0x10000000 + 0x11000 : 0; + const re = F.feldApply(F.feldStrip(buf, embOld, E), { fields: state.feld, bag: state.bag, tama: state.tama, gplay: state.gplay, saves: state.saves, launch: state.launch, apps: fa.apps, name0: fa.name0, appsLow: low, dl, mainSrc: fa.mainSrc, auto: fa.auto, fieldNames: fieldTexts(buf).map((x) => x.name) }, F.feldSlots(buf, fe.stub), { feld: fe.feld, stub: fe.stub }, E); + if (dlo) re.set(buf.subarray(dlo, dlo + 0x10000), dlo); // the flash app stays where it is + state.feldStale = re.length !== buf.length || re.some((v, i) => v !== buf[i]); + } catch (e) { state.feldStale = lang==='ko' && !F.koreanMenu(buf); } + } } + // fields and character names (from the ROM's character table and text table) + state.fields = []; state.charNames = new Map(); + try { + state.fields = C.fieldSets(ctx); + const tt = F.textTabelle(buf), chars = C.charTable(ctx.files[0]).filter((c) => c.id > 1000 && c.id < 9000); + if (tt >= 0 && chars.length + 1 === ctx.groups.length) chars.forEach((c, i) => { const n = C.textGet(buf,c.name,lang); if (n) state.charNames.set(ctx.groups[i + 1], n); }); + } catch (e) { state.fields = []; } + cleanTabs(); + renderInfo(); if (!clean) { renderGrids(); renderNames(); renderDim(); } renderEmu(); renderDoom(); renderFeld(); renderSave(); if (!dv.run) devRender(); + toast(clean ? t('cleanLoaded', { ed: ctx.edition, n: state.extras.length }) : t('loaded', { ed: ctx.edition, s: ctx.entries.length, f: ctx.groups.length })); +} +// ------------------------------------------------------------------ names (1.6.8) +/* Field names: text numbers per field (the field's own one, and 64..66 where LAND/WATER/SKY stand a second time) */ +/* 1.6.8: the extra fields (Land, Water, Sky) are part of the ROM being made: when six fields are switched on in the + * Menu tab, their names can be changed before they are built in */ +const sixActive = () => !!state.ctx && !state.launch && ((!!S6.sixInfo(state.ctx.rom) && !state.sixOff) || !!state.six || !!state.sixWant); +function fieldTexts(rom, six) { + let fn = F.fieldNames(rom).map((s) => s.toUpperCase()); const lws = ['LAND', 'WATER', 'SKY'], out = []; + if (six !== undefined) { + const id = F.feldId(rom); + if (!six) fn = fn.slice(0, 3); + else if (fn.length <= 3) fn = fn.concat(id === 4 ? ['SKY'] : id >= 5 ? lws : []); + } + fn.forEach((nm, i) => { + const k = lws.indexOf(nm), own = i < 3 ? 14 + i : k >= 0 ? 64 + k : -1; + if (own < 0) return; + const idx = [own]; if (i < 3 && k >= 0 && C.textGet(rom, 64 + k, lang) === C.textGet(rom, own, lang)) idx.push(64 + k); + out.push({ idx, name: C.textGet(rom, own, lang) }); + }); + return out; +} +function nameRow(box, label, cur, idx, max) { + const l = document.createElement('label'), sp = document.createElement('span'), inp = document.createElement('input'); + sp.textContent = label; sp.title = label; inp.maxLength = max; + if(state.texts.size && state.textLanguage!==lang){inp.disabled=true;inp.title='수정한 이름을 저장하거나 초기화한 뒤 다른 언어를 편집하세요.';} + const ed = state.texts.get(idx[0]); inp.value = ed !== undefined ? ed : cur; inp.classList.toggle('chg', ed !== undefined); + inp.onchange = () => { + let v; try { v = C.textClean(inp.value, lang); } catch(error){inp.setCustomValidity(error.message);inp.reportValidity();return;} inp.setCustomValidity(''); + state.textLanguage=lang; + for (const i of idx) { if (!v || v === cur) state.texts.delete(i); else state.texts.set(i, v); } + inp.value = v && v !== cur ? v : cur; inp.classList.toggle('chg', !!v && v !== cur); renderPlan(); + }; + l.append(sp, inp); box.appendChild(l); +} +function fieldLabel(name){return lang==='ko'?({LAND:'육지',WATER:'수중',SKY:'하늘',FOREST:'숲',TROPICAL:'트로피컬',GLACIER:'글레이셔'}[String(name).toUpperCase()]||name):name;} +function renderNames() { + if (!state.ctx) return; + if (!state.texts) state.texts = new Map(); + const rom = state.ctx.rom, fb = $('namesFields'), cb = $('namesChars'), ib = $('namesItems'); + fb.innerHTML = ''; cb.innerHTML = ''; ib.innerHTML = ''; + $('namesFind').placeholder = t('namesFind'); + for (const f of fieldTexts(rom, sixActive())) nameRow(fb, f.name, f.name, f.idx, 11); + const seen = new Set(); + try { + for (const c of C.charTable(state.ctx.files[0]).filter((c) => c.id > 1000 && c.id < 9000)) { + if (seen.has(c.name)) continue; const nm = C.textGet(rom, c.name, lang); if (!nm) continue; seen.add(c.name); + nameRow(cb, nm, nm, [c.name], 12); + } + } catch (e) { /* no character table */ } + const q = ($('namesFind').value || '').toUpperCase(); + for (const it of F.itemCatalog(rom, lang)) { + if (seen.has(it.text)) continue; const nm = C.textGet(rom, it.text, lang); if (!nm) continue; seen.add(it.text); + if (q && !nm.includes(q) && !(state.texts.get(it.text) || '').includes(q)) continue; + nameRow(ib, lang==='ko'&&nm==='GASHAPON'?'가샤폰':nm, nm, [it.text], 22); + } +} +$('namesFind').oninput = () => renderNames(); +$('namesUndo').onclick = () => { state.texts = new Map(); renderNames(); renderPlan(); }; +function estimateEnd() { + const ctx = state.ctx; if (ctx.clean) return C.ASSET_BASE; // CLEAN_ROM: no pictures + let pack = 4 * ctx.entries.length; + for (let i = 0; i < ctx.entries.length; i++) { pack += (4 - pack % 4) % 4; pack += entry(i).length; } + const al = (n) => n + ((4 - n % 4) % 4); + return C.ASSET_BASE + 16 + 48 + al(ctx.files[0].length) + al(pack) + al(ctx.files[2].length); +} +function renderInfo() { + const ctx = state.ctx; if (!ctx) return; + if (ctx.clean) { $('info').innerHTML = ''; const s = document.createElement('span'); s.innerHTML = t('edition') + ': '; s.lastChild.textContent = ctx.edition + ' · ' + t('cleanOn'); $('info').appendChild(s); renderPlan(); return; } + const end = estimateEnd(), total = ctx.limit - C.ASSET_BASE, used = end - C.ASSET_BASE, free = ctx.limit - end; + const pct = Math.min(100, used / total * 100); + $('info').innerHTML = ''; + const add = (label, html) => { const s = document.createElement('span'); s.innerHTML = label + ': ' + html + ''; $('info').appendChild(s); }; + add(t('edition'), ctx.edition); add(t('sprites'), ctx.entries.length); add(t('figures'), ctx.groups.length); add(t('changed'), state.changed.size); + const s = document.createElement('span'); + s.innerHTML = t('space') + ': ' + (free / 1024 | 0) + ' KB'; + $('info').appendChild(s); + renderPlan(); +} + +// --------------------------------------------------------------- grids +let observer; +function tile(kind, idx, label) { + const b = document.createElement('button'); b.className = 'tile'; b.dataset.kind = kind; b.dataset.idx = idx; + b.innerHTML = '
#' + idx + '
'; + b.querySelector('.cap span').textContent = label || ''; + b.onclick = () => openDrawer(kind, idx); + observer.observe(b); + return b; +} +function paintTile(b) { + const i = +b.dataset.idx, kind = b.dataset.kind; + let img; + try { const d = decode(i); img = d.subs[0]; } catch (e) { return; } + const box = 96, sc = Math.max(1, Math.min(2, Math.floor(box / Math.max(img.w, img.h)) || 1)); + const cv = imgToCanvas(img, sc); + if (img.w * sc > box || img.h * sc > box) { cv.style.width = '100%'; cv.style.height = 'auto'; } + const st = b.querySelector('.stage'); st.innerHTML = ''; st.appendChild(cv); + const ch = kind === 'fig' ? [0, 1, 2, 3, 4, 5].some(k => state.changed.has(i + k)) : state.changed.has(i); + b.classList.toggle('changed', ch); +} +function renderGrids() { + if (observer) observer.disconnect(); + observer = new IntersectionObserver((es) => es.forEach(e => { if (e.isIntersecting) { paintTile(e.target); observer.unobserve(e.target); } }), { rootMargin: '300px' }); + const ctx = state.ctx, gf = $('gridFigs'), ga = $('gridAll'); gf.innerHTML = ''; ga.innerHTML = ''; + for (const g of ctx.groups) gf.appendChild(tile('fig', g, [state.charNames.get(g), groupRole(g)].filter(Boolean).join(' '))); + renderFieldPick(); + ctx.entries.forEach((e, i) => { const h = C.spriteHeader(e); const tl = tile('spr', i, h.sw * Math.max(1, h.iw) + '×' + h.sh * Math.max(1, h.ih)); if (sixAdded(i)) { tl.classList.add('locked'); tl.title = t('sprSix'); } ga.appendChild(tl); }); +} +function refreshTile(kind, idx) { + document.querySelectorAll('.tile[data-idx="' + idx + '"][data-kind="' + kind + '"]').forEach(paintTile); + if (kind === 'spr') { const g = state.ctx.groups.find(g => idx >= g && idx < g + 6); if (g !== undefined) refreshTile('fig', g); } + else for (let k = 0; k < 6; k++) document.querySelectorAll('.tile[data-idx="' + (idx + k) + '"][data-kind="spr"]').forEach(paintTile); + renderInfo(); +} +/* CLEAN_ROM: without the Paradise its tabs (pictures, names, size, DOOM) have nothing to show */ +const CLEAN_TABS = ['figs', 'all', 'names', 'dim']; +function cleanTabs() { + const off = !!state.clean; + document.querySelectorAll('.tab').forEach((b) => { b.hidden = off && CLEAN_TABS.includes(b.dataset.tab); }); + const sel = document.querySelector('.tab[aria-selected="true"]'); + if (off && sel && sel.hidden) document.querySelector('.tab[data-tab="emu"]').click(); +} +document.querySelectorAll('.tab').forEach(b => b.onclick = () => { + document.querySelectorAll('.tab').forEach(x => x.setAttribute('aria-selected', String(x === b))); + ['figs', 'all', 'names', 'dim', 'emu', 'doom', 'gb', 'sms', 'pm', 'ab', 'wolf', 'feld', 'save'].forEach(k => $('pane-' + k).hidden = k !== b.dataset.tab); +}); + +// Options for a sprite that belongs to a character group (eyes keep their length, +// colours avoid the slots the game recolours). Empty for other sprites. +function partOpts(i) { + const g = state.ctx.groups.find(g => i >= g && i < g + 6); + return g === undefined ? {} : C.partOptions(i - g); +} +function groupRole(g) { + const ctx = state.ctx; + if (g === ctx.groups[0]) return t('roleFallback'); + if (ctx.egg >= 0 && g === ctx.egg + 6) return t('roleBaby'); + if (g === ctx.adult) return t('roleAdult'); + return ''; +} + +// --------------------------------------------------------------- sheets +function sheetOf(kind, idx) { + if (kind === 'fig') return C.groupSheet([0, 1, 2, 3, 4, 5].map(k => decode(idx + k).subs)); + return C.sheetFromSubs(decode(idx).subs); +} +const sheetName = (kind, idx) => (kind === 'fig' ? 'figur_' : 'sprite_') + pad4(idx) + '.png'; +/** Apply an edited sheet. Unchanged parts keep their original bytes. */ +/* 1.6.8: pictures the six fields added (they share their data and are made again when the fields are updated) */ +function sixAdded(i) { const si = S6.sixInfo(state.ctx.rom); return !!si && si.kind === 'gen3' && i >= si.sprites; } +function applySheet(kind, idx, img) { + if (kind === 'spr' && sixAdded(idx)) throw new Error(t('sprSix')); + const opts = { allowMoreColors: $('optColors').checked }; + // encode first, change nothing until every part is accepted (a character is never half replaced) + const plan = []; + const setEntry = (i, subs) => { + const cur = decode(i).subs; + if (subs.length === cur.length && subs.every((s, k) => C.sameImage(s, cur[k]))) return; + const orig = state.ctx.entries[i]; + const od = C.spriteDecode(orig).subs; + if (subs.every((s, k) => C.sameImage(s, od[k]))) { plan.push([i, null]); return; } + plan.push([i, C.spriteEncode(orig, subs, Object.assign({}, opts, partOpts(i)))]); + }; + const commit = () => plan.forEach(([i, e]) => { if (e) state.changed.set(i, e); else state.changed.delete(i); }); + if (kind === 'fig') { C.groupFromSheet(img).forEach((subs, k) => setEntry(idx + k, subs)); commit(); return; } + const d = decode(idx); setEntry(idx, C.subsFromSheet(img, d.subs[0].w, d.subs[0].h, d.subs.length)); commit(); +} +function parseName(name) { + const m = /(figur|figure|sprite)_(\d+)\.png$/i.exec(name.split('/').pop()); + if (!m) return null; + return { kind: /sprite/i.test(m[1]) ? 'spr' : 'fig', idx: +m[2] }; +} +async function uploadFiles(files) { + const items = []; + for (const f of files) { + if (/\.zip$/i.test(f.name)) { + const z = await C.zipRead(new Uint8Array(await f.arrayBuffer()), inflateRaw); + for (const e of z) items.push({ name: e.name, blob: new Blob([e.data], { type: 'image/png' }) }); + } else items.push({ name: f.name, blob: f }); + } + let ok = 0; const skip = []; + for (const it of items) { + const p = parseName(it.name); + if (!p) { if (/\.png$/i.test(it.name)) skip.push(it.name.split('/').pop()); continue; } + if (p.kind === 'fig' && !state.ctx.groups.includes(p.idx)) { skip.push(it.name.split('/').pop()); continue; } + if (p.kind === 'spr' && !(p.idx >= 0 && p.idx < state.ctx.entries.length)) { skip.push(it.name.split('/').pop()); continue; } + try { applySheet(p.kind, p.idx, await decodePng(it.blob)); ok++; refreshTile(p.kind, p.idx); } + catch (e) { skip.push(t('wrongSize', { f: it.name.split('/').pop(), e: em(e) })); } + } + if (!ok && !skip.length) toast(t('upNone'), true); + else toast(t('upOk', { n: ok }) + (skip.length ? '\n' + t('upSkip', { list: skip.slice(0, 6).join(', ') + (skip.length > 6 ? ' …' : '') }) : ''), skip.length > 0 && !ok); + if (state.open) openDrawer(state.open.kind, state.open.idx); +} +/* Fields (worlds): filter the character grid and export everything of one field */ +function renderFieldPick() { + const sel = $('figField'), cur = sel.value; sel.innerHTML = ''; + const o = document.createElement('option'); o.value = ''; o.textContent = t('figAll'); sel.appendChild(o); + state.fields.forEach((f) => { const x = document.createElement('option'); x.value = f.type; x.textContent = fieldLabel(f.name); sel.appendChild(x); }); + sel.value = state.fields.some((f) => String(f.type) === cur) ? cur : ''; + applyFieldPick(); +} +function applyFieldPick() { + const f = state.fields.find((x) => String(x.type) === $('figField').value); + const set = f ? new Set(f.chars.map((c) => c.group)) : null; + {const chars=C.charTable(state.ctx.files[0]).filter(c=>c.id>1000&&c.id<9000);chars.forEach((c,i)=>state.charNames.set(state.ctx.groups[i+1],C.textGet(state.ctx.rom,c.name,lang)));} + document.querySelectorAll('#gridFigs .tile').forEach((b) => { b.hidden = !!set && !set.has(+b.dataset.idx); }); + $('btnZipField').hidden = !f; $('btnFieldIn').hidden = !f; +} +$('figField').onchange = applyFieldPick; +$('btnZipField').onclick = () => busy(async () => { + const f = state.fields.find((x) => String(x.type) === $('figField').value); if (!f) return; + const files = [], lines = ['Paramix Studio: ' + f.name + ' (' + state.ctx.edition + ')', '']; + for (const c of f.chars) { files.push({ name: sheetName('fig', c.group), data: await pngBytes(sheetOf('fig', c.group)) }); lines.push(sheetName('fig', c.group) + ' stage ' + c.stage + ' ' + (state.charNames.get(c.group) || '')); } + const pics = [...f.maps, ...f.overlays, ...f.closeups]; + for (const i of pics) files.push({ name: sheetName('spr', i), data: await pngBytes(sheetOf('spr', i)) }); + if (f.maps.length) lines.push('', 'field map: ' + f.maps.map((i) => sheetName('spr', i)).join(' ')); + if (f.overlays.length) lines.push('map overlays: ' + f.overlays.map((i) => sheetName('spr', i)).join(' ')); + if (f.closeups.length) lines.push('close-up backgrounds: ' + f.closeups.map((i) => sheetName('spr', i)).join(' ')); + files.push({ name: 'contents.txt', data: new TextEncoder().encode(lines.join('\n') + '\n') }); + const meta = { paramix: 'field', edition: state.ctx.edition, type: f.type, name: f.name, chars: f.chars.map((c) => ({ id: c.id, stage: c.stage, group: c.group })), maps: f.maps, overlays: f.overlays, closeups: f.closeups }; + files.push({ name: 'field.json', data: new TextEncoder().encode(JSON.stringify(meta, null, 1)) }); + download(C.zipBuild(files), baseName() + '_' + f.name.toLowerCase() + '.zip', 'application/zip'); + toast(t('fieldZipOk', { f: f.name, n: f.chars.length, s: pics.length })); +}); +/* Load a field ZIP (from this or another ROM) into the selected field: characters in + the same order (child, teens, adults), field map, overlays and close-ups one to one. */ +$('btnFieldIn').onclick = () => $('fileField').click(); +$('fileField').onchange = (e) => { + const file = e.target.files[0]; e.target.value = ''; if (!file) return; + busy(async () => { + const dst = state.fields.find((x) => String(x.type) === $('figField').value); if (!dst) return; + const z = await C.zipRead(new Uint8Array(await file.arrayBuffer()), inflateRaw); + const by = new Map(z.map((x) => [x.name.split('/').pop(), x.data])); + let meta = null; try { meta = JSON.parse(new TextDecoder().decode(by.get('field.json'))); } catch (err) { meta = null; } + if (!meta || meta.paramix !== 'field') { toast(t('fieldInBad'), true); return; } + let n = 0, eyes = 0; const skip = []; + const put = async (kind, srcIdx, dstIdx) => { + const nm = sheetName(kind, srcIdx), data = by.get(nm); if (!data || dstIdx === undefined) return; + try { applySheet(kind, dstIdx, await decodePng(new Blob([data], { type: 'image/png' }))); n++; refreshTile(kind, dstIdx); } + catch (err) { if (/^eye image too detailed/.test(err.message)) eyes++; else skip.push(t('wrongSize', { f: nm, e: em(err) })); } + }; + for (let i = 0; i < meta.chars.length && i < dst.chars.length; i++) await put('fig', meta.chars[i].group, dst.chars[i].group); + for (let i = 0; i < meta.maps.length && i < dst.maps.length; i++) await put('spr', meta.maps[i], dst.maps[i]); + for (let i = 0; i < meta.overlays.length && i < dst.overlays.length; i++) await put('spr', meta.overlays[i], dst.overlays[i]); + for (let i = 0; i < meta.closeups.length && i < dst.closeups.length; i++) await put('spr', meta.closeups[i], dst.closeups[i]); + toast(t('fieldInOk', { src: meta.name + ' (' + meta.edition + ')', dst: dst.name, n }) + (eyes ? '\n' + t('fieldInEyes', { k: eyes }) : '') + (skip.length ? '\n' + t('upSkip', { list: skip.slice(0, 4).join(', ') + (skip.length > 4 ? ' …' : '') }) : ''), skip.length > 0 && !n); + }); +}; +async function zipSheets(kind) { + const list = kind === 'fig' ? state.ctx.groups : state.ctx.entries.map((e, i) => i); + const files = []; + for (const i of list) files.push({ name: sheetName(kind, i), data: await pngBytes(sheetOf(kind, i)) }); + download(C.zipBuild(files), baseName() + (kind === 'fig' ? '_figuren.zip' : '_sprites.zip'), 'application/zip'); +} + +// --------------------------------------------------------------- drawer +function openDrawer(kind, idx) { + state.open = { kind, idx }; + const img = sheetOf(kind, idx); + $('dTitle').textContent = (kind === 'fig' ? t('figure') : t('sprite')) + ' #' + idx; + imgToCanvas(img, state.zoom, $('dCanvas')); + const meta = $('dMeta'); meta.innerHTML = ''; + const li = (s) => { const x = document.createElement('li'); x.textContent = s; meta.appendChild(x); }; + li(t('mSheet', { w: img.w, h: img.h })); + if (kind === 'fig') { li(t('mGroupRows')); li(t('mEyes')); li(t('mColorsFig')); if (groupRole(idx)) li(groupRole(idx) + ': ' + t(idx === state.ctx.groups[0] ? 'roleFallbackText' : idx === state.ctx.adult ? 'roleAdultText' : 'roleBabyText')); } + else { + const h = C.spriteHeader(state.ctx.entries[idx]); + li(t('mSize', { w: h.sw, h: h.sh, n: h.numSprites / (Math.max(1, h.iw) * Math.max(1, h.ih)), iw: Math.max(1, h.iw), ih: Math.max(1, h.ih) })); + li(t('mColors', { c: h.bpp >= 0x10 ? t('mDirect') : t('mPal', { n: 1 << [1, 2, 4, 8][h.bpp] }), p: h.bpp >= 0x10 ? 0 : Math.max(1, h.numPal) })); + if (sixAdded(idx)) li(t('sprSix')); + if (h.numPal > 1) li(t('mKeep')); + } + const ch = kind === 'fig' ? [0, 1, 2, 3, 4, 5].some(k => state.changed.has(idx + k)) : state.changed.has(idx); + $('dReset').disabled = !ch; + $('dEyes').hidden = kind !== 'fig'; if (kind === 'fig') { if (face.g !== idx) $('dPoseOnly').checked = false; eyePreview(idx); } + $('dUp').disabled = kind === 'spr' && sixAdded(idx); + $('drawer').classList.add('open'); $('drawer').setAttribute('aria-hidden', 'false'); $('scrim').classList.add('on'); +} +/* 1.6.8: move a character's eyes and mouth (composite entries of the field). The preview shows every pose of the big + * or the small figure. Arrows move eyes or mouth in all poses (small figure half as far) or, with "this pose only", + * the layers of the pose shown (state.poseAdj: figure -> word positions -> extra offset). */ +const shTxt = (sh) => (sh[0] || sh[1] ? (sh[0] > 0 ? '+' : '') + sh[0] + ' / ' + (sh[1] > 0 ? '+' : '') + sh[1] : ''); +const face = { g: -1, pose: 0, small: false }; +function posesOf(g, small) { + if (!state.poseCache) state.poseCache = new Map(); + const base = small ? g + 3 : g, k = state.ctx.files[0].length + ':' + base; + if (!state.poseCache.has(k)) state.poseCache.set(k, C.facePoses(state.ctx.files[0], base, base + 1, base + 2)); + return state.poseCache.get(k); +} +const poseKey = (l) => l.ox + ':' + l.oy; +function poseAdjGet(g, l) { const m = state.poseAdj && state.poseAdj.get(g), v = l && m && m.get(poseKey(l)); return v ? v.d : [0, 0]; } +function firstPose(ps) { const i = ps.findIndex((p) => p.eye && p.eye.sub === 0 && p.mouth && p.mouth.sub === 0); return i >= 0 ? i : Math.max(0, ps.findIndex((p) => p.eye && p.eye.sub === 0)); } +function eyePreview(g) { + if (face.g !== g) { face.g = g; face.small = false; face.pose = firstPose(posesOf(g, false)); } + const ps = posesOf(g, face.small), only = $('dPoseOnly').checked, cv = $('dEyeCv'), x = cv.getContext('2d'); + const ge = (state.eyeShift && state.eyeShift.get(g)) || [0, 0], gm = (state.mouthShift && state.mouthShift.get(g)) || [0, 0]; + const sc = (v) => (face.small ? [half(v[0]), half(v[1])] : v); + $('dFaceBig').classList.toggle('on', !face.small); $('dFaceSmall').classList.toggle('on', face.small); + $('dFaceHint').textContent = t(only ? 'poseOnlyHint' : 'eyeMvHint'); + x.clearRect(0, 0, 64, 64); + let f; + if (ps.length) { face.pose = Math.min(Math.max(0, face.pose), ps.length - 1); f = ps[face.pose]; } + else { const o = C.eyeFirst(state.ctx.files[0], g, g + 1); if (!o) return; f = { bs: o.bs, eye: { sub: o.es, dx: o.dx, dy: o.dy, ox: -1, oy: -1 }, mouth: null }; } + $('dPoseNr').textContent = ps.length ? t('poseNr', { i: face.pose + 1, n: ps.length }) : ''; + $('dPosePrev').disabled = $('dPoseNext').disabled = ps.length < 2; + $('dPoseOnly').disabled = !ps.length; + $('dMouthRow').hidden = !f.mouth; + const ea = poseAdjGet(g, f.eye), ma = poseAdjGet(g, f.mouth); + $('dEyeVal').textContent = shTxt(only ? ea : ge); $('dMouthVal').textContent = shTxt(only ? ma : gm); + const base = face.small ? g + 3 : g, B = decode(base), b = B.subs[f.bs] || B.subs[0]; + const img = new ImageData(new Uint8ClampedArray(b.data), b.w, b.h); + const put = (part, lay, sh) => { + if (!lay) return; let P; try { P = decode(base + part); } catch (e) { return; } + const e = P.subs[lay.sub] || P.subs[0]; if (!e) return; + const ox = lay.dx + ((b.w - e.w) >> 1) + sh[0], oy = lay.dy + ((b.h - e.h) >> 1) + sh[1]; + for (let y = 0; y < e.h; y++) for (let xx = 0; xx < e.w; xx++) { + const s = (y * e.w + xx) * 4; if (e.data[s + 3] < 128) continue; + const X = xx + ox, Y = y + oy; if (X < 0 || Y < 0 || X >= b.w || Y >= b.h) continue; + const t = (Y * b.w + X) * 4; img.data[t] = e.data[s]; img.data[t + 1] = e.data[s + 1]; img.data[t + 2] = e.data[s + 2]; img.data[t + 3] = 255; + } + }; + const se = sc(ge), sm = sc(gm); + put(1, f.eye, [se[0] + ea[0], se[1] + ea[1]]); put(2, f.mouth, [sm[0] + ma[0], sm[1] + ma[1]]); + cv.width = b.w; cv.height = b.h; x.putImageData(img, 0, 0); + // FACE_SCALE (1.7.2 test15): every sprite at 3x (big 192 px, small 96 px), before the small one was blown up to 192 px + if (FACE_SCALE) { cv.style.width = (b.w * 3) + 'px'; cv.style.height = (b.h * 3) + 'px'; cv.style.margin = ((192 - b.h * 3) >> 1) + 'px ' + ((192 - b.w * 3) >> 1) + 'px'; } +} +const FACE_SCALE = true; +const clamp16 = (v) => Math.max(-16, Math.min(16, v)); +function curLayer(which) { const ps = posesOf(face.g, face.small); const f = ps[face.pose]; return f ? f[which] : null; } +function faceMove(which, dx, dy, reset) { + if (!state.open || state.open.kind !== 'fig') return; + const g = state.open.idx; + if ($('dPoseOnly').checked) { + const l = curLayer(which); if (!l || l.ox < 0) return; + if (!state.poseAdj) state.poseAdj = new Map(); + const m = state.poseAdj.get(g) || new Map(), k = poseKey(l), c = (m.get(k) || { d: [0, 0] }).d, n = reset ? [0, 0] : [clamp16(c[0] + dx), clamp16(c[1] + dy)]; + if (n[0] || n[1]) m.set(k, { ox: l.ox, oy: l.oy, d: n }); else m.delete(k); + if (m.size) state.poseAdj.set(g, m); else state.poseAdj.delete(g); + } else { + const key = which === 'eye' ? 'eyeShift' : 'mouthShift'; + if (!state[key]) state[key] = new Map(); + const c = state[key].get(g) || [0, 0], n = reset ? [0, 0] : [clamp16(c[0] + dx), clamp16(c[1] + dy)]; + if (n[0] || n[1]) state[key].set(g, n); else state[key].delete(g); + } + eyePreview(g); renderPlan(); +} +document.querySelectorAll('[data-eye]').forEach((bt) => bt.onclick = () => { const [dx, dy] = bt.dataset.eye.split(',').map(Number); faceMove('eye', dx, dy); }); +document.querySelectorAll('[data-mouth]').forEach((bt) => bt.onclick = () => { const [dx, dy] = bt.dataset.mouth.split(',').map(Number); faceMove('mouth', dx, dy); }); +$('dEyeReset').onclick = () => faceMove('eye', 0, 0, true); +$('dMouthReset').onclick = () => faceMove('mouth', 0, 0, true); +const poseStep = (k) => { if (!state.open) return; const n = posesOf(face.g, face.small).length; if (n) face.pose = (face.pose + k + n) % n; eyePreview(state.open.idx); }; +$('dPosePrev').onclick = () => poseStep(-1); $('dPoseNext').onclick = () => poseStep(1); +const faceSize = (small) => { if (!state.open) return; face.small = small; face.pose = firstPose(posesOf(face.g, small)); eyePreview(state.open.idx); }; +$('dFaceBig').onclick = () => faceSize(false); $('dFaceSmall').onclick = () => faceSize(true); +$('dPoseOnly').onchange = () => { if (state.open) eyePreview(state.open.idx); }; +function closeDrawer() { state.open = null; $('drawer').classList.remove('open'); $('drawer').setAttribute('aria-hidden', 'true'); $('scrim').classList.remove('on'); } +$('dClose').onclick = closeDrawer; $('scrim').onclick = closeDrawer; +document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeDrawer(); }); +document.querySelectorAll('[data-z]').forEach(b => b.onclick = () => { state.zoom = +b.dataset.z; if (state.open) openDrawer(state.open.kind, state.open.idx); }); +$('dDown').onclick = async () => { const { kind, idx } = state.open; download(await pngBlob(sheetOf(kind, idx)), sheetName(kind, idx)); }; +$('dUp').onclick = () => $('fileOne').click(); +$('fileOne').onchange = async (e) => { + const f = e.target.files[0]; e.target.value = ''; if (!f || !state.open) return; + const { kind, idx } = state.open; + try { await busy(async () => applySheet(kind, idx, await decodePng(f))); refreshTile(kind, idx); openDrawer(kind, idx); toast(t('upOk', { n: 1 })); } + catch (err) { toast(t('wrongSize', { f: f.name, e: em(err) }), true); } +}; +$('dReset').onclick = () => { + const { kind, idx } = state.open; + if (kind === 'fig') for (let k = 0; k < 6; k++) state.changed.delete(idx + k); else state.changed.delete(idx); + refreshTile(kind, idx); openDrawer(kind, idx); toast(t('resetOk')); +}; + +// ------------------------------------------------------------------ card +function eyeRectFor(ch) { + if (!state.eyeRects) state.eyeRects = new Map(); + if (state.eyeRects.has(ch)) return state.eyeRects.get(ch); + const pre = C.dimEyePreset(ch); + const r = pre === undefined ? C.dimGuessEye(ch) : pre; + state.eyeRects.set(ch, r); return r; +} +/** Insert a card character into group g (body, eye layer, blank mouth). */ +function insertDim(ch, g) { + const ctx = state.ctx; + if (!state.eyeLayer) { + // Standard: the card character keeps its own eyes in the body. The game draws the eye + // image of the current character on top (field and cell), so it stays empty. + const parts = C.dimCharParts(ch); + [0, 1, 2, 3, 4, 5].forEach(k => { + const orig = ctx.entries[g + k]; + state.changed.set(g + k, k === 0 || k === 3 ? C.spriteEncode(orig, parts[k], C.partOptions(k)) : C.spriteBlank(orig, C.partOptions(k))); + }); + state.eyeOffsets.delete(g); + return true; + } + const rect = eyeRectFor(ch); + let res = rect ? C.dimCharPartsWithEyes(ch, rect) : null; + const parts = res ? res.parts : C.dimCharParts(ch); + [0, 2, 3, 5].forEach(k => { + const orig = ctx.entries[g + k]; + state.changed.set(g + k, k === 0 || k === 3 ? C.spriteEncode(orig, parts[k], C.partOptions(k)) : C.spriteBlank(orig, C.partOptions(k))); + }); + let eyesOk = !!res; + for (const [k, layer] of [[1, res && res.big], [4, res && res.small]]) { + const orig = ctx.entries[g + k]; let enc = null; + if (layer) for (const v of C.eyeVariants(layer, k === 1)) { try { enc = C.spriteEncode(orig, v, C.partOptions(k)); break; } catch (e) { /* too big, fewer open eyes */ } } + if (!enc) eyesOk = false; + state.changed.set(g + k, enc || C.spriteBlank(orig, C.partOptions(k))); + } + if (!state.eyeOffsets) state.eyeOffsets = new Map(); + if (eyesOk) state.eyeOffsets.set(g, [res.eyeBig, res.eyeSmall]); else state.eyeOffsets.delete(g); + return eyesOk; +} +/** Data pack with the eye layer placed for every inserted character still changed. */ +const half = (v) => Math.sign(v) * Math.round(Math.abs(v) / 2); // symmetric: -1 and 1 both move one pixel +function currentDataPack() { + let dp = state.ctx.files[0]; + if (!state.eyeOffsets) return null; + let any = false; + for (const [g, v] of state.eyeOffsets) { + if (v === 'hide') { + if (!state.changed.has(g)) continue; + dp = C.hideEyes(dp, g, g + 1).dataPack; dp = C.hideEyes(dp, g + 3, g + 4).dataPack; + any = true; continue; + } + const [b, sm] = v; + if (!state.changed.has(g + 1)) continue; + dp = C.setEyeOffset(dp, g, g + 1, 64, 32, b[0], b[1]).dataPack; + dp = C.setEyeOffset(dp, g + 3, g + 4, 32, 16, sm[0], sm[1]).dataPack; + any = true; + } + // 1.6.8: eyes moved in the drawer (small figure: half the way) + for (const [g, [dx, dy]] of state.mouthShift || []) { // mouth: the same way as the eyes + dp = C.shiftEyes(dp, g, g + 2, dx, dy).dataPack; dp = C.shiftEyes(dp, g + 3, g + 5, half(dx), half(dy)).dataPack; + any = true; + } + for (const [, m] of state.poseAdj || []) { if (m.size) { dp = C.layersMove(dp, [...m.values()]); any = true; } } // single poses + for (const [g, [dx, dy]] of state.eyeShift || []) { + dp = C.shiftEyes(dp, g, g + 1, dx, dy).dataPack; dp = C.shiftEyes(dp, g + 3, g + 4, half(dx), half(dy)).dataPack; + any = true; + } + return any ? dp : null; +} +function renderDim() { + const area = $('dimArea'); area.innerHTML = ''; + if (!state.dim) { const p = document.createElement('p'); p.className = 'hint'; p.textContent = t('dimNone'); area.appendChild(p); return; } + const dim = state.dim, ctx = state.ctx; + const bar = document.createElement('div'); bar.className = 'assign'; + const selD = document.createElement('select'); dim.chars.forEach(c => { const o = document.createElement('option'); o.value = c.index; o.textContent = t('dimNr') + ' ' + c.index + (c.baby ? ' (' + t('dimBaby') + ')' : ''); selD.appendChild(o); }); + const selG = document.createElement('select'); ctx.groups.forEach(g => { const o = document.createElement('option'); o.value = g; o.textContent = t('figure') + ' #' + g + (groupRole(g) ? ' (' + groupRole(g) + ')' : ''); selG.appendChild(o); }); if (ctx.groups.includes(ctx.adult)) selG.value = ctx.adult; + const go = document.createElement('button'); go.className = 'btn primary small'; go.textContent = t('dimApply'); + go.onclick = () => busy(async () => { + const ch = dim.chars[+selD.value], g = +selG.value; + const ok = insertDim(ch, g); + refreshTile('fig', g); toast(t('dimOk', { d: ch.index, g }) + (state.eyeLayer && eyeRectFor(ch) && !ok ? '\n' + t('dimEyesTooBig') : '')); + }); + const l1 = document.createElement('span'); l1.textContent = t('dimPick'); + const l2 = document.createElement('span'); l2.textContent = t('dimTarget'); + bar.append(l1, selD, l2, selG, go); + if (dim.eggs.length && ctx.egg >= 0) { + const eg = document.createElement('button'); eg.className = 'btn small'; eg.textContent = t('dimEgg'); + eg.onclick = () => { + const e = C.dimEggSubs(dim.eggs); + state.changed.set(ctx.egg, C.spriteEncode(ctx.entries[ctx.egg], e.small, {})); + state.changed.set(ctx.egg + 3, C.spriteEncode(ctx.entries[ctx.egg + 3], e.big, {})); + refreshTile('spr', ctx.egg); refreshTile('spr', ctx.egg + 3); toast(t('eggOk')); + }; + bar.appendChild(eg); + } + area.appendChild(bar); + // eye editor: the chosen card character large, the eye frame drawn, click to move it + const ed = document.createElement('div'); ed.className = 'eyeed'; + const cv = document.createElement('canvas'); cv.className = 'eyecv'; + const side = document.createElement('div'); + const hint = document.createElement('p'); hint.className = 'hint'; hint.textContent = t('eyeHint'); + const none = document.createElement('label'); none.className = 'check'; + const cb = document.createElement('input'); cb.type = 'checkbox'; none.append(cb, document.createTextNode(' ' + t('eyeNone'))); + side.append(hint, none); ed.append(cv, side); if (state.eyeLayer) area.appendChild(ed); + const S = 5; + const draw = () => { + const ch = dim.chars[+selD.value], im = ch.frames.idle1, r = eyeRectFor(ch); + imgToCanvas(im, S, cv); + const g2 = cv.getContext('2d'); + if (r) { g2.strokeStyle = '#ff2fa0'; g2.lineWidth = 2; g2.strokeRect(r[0] * S - 1, r[1] * S - 1, (r[2] - r[0] + 1) * S + 2, (r[3] - r[1] + 1) * S + 2); } + cb.checked = !r; + }; + cv.onclick = (e) => { + const ch = dim.chars[+selD.value], b = cv.getBoundingClientRect(); + const x = Math.floor((e.clientX - b.left) / b.width * ch.frames.idle1.w), y = Math.floor((e.clientY - b.top) / b.height * ch.frames.idle1.h); + state.eyeRects.set(ch, C.eyeRectAt(ch, x, y)); draw(); + }; + cb.onchange = () => { const ch = dim.chars[+selD.value]; state.eyeRects.set(ch, cb.checked ? null : (C.dimEyePreset(ch) || C.dimGuessEye(ch))); draw(); }; + selD.onchange = () => { state.dimSel = selD.value; draw(); }; + if (state.dimSel === undefined) { const c = dim.chars.find(x => !x.baby); if (c) state.dimSel = String(c.index); } + if (state.dimSel !== undefined) selD.value = state.dimSel; + const grid = document.createElement('div'); grid.className = 'dimgrid'; + dim.chars.forEach(c => { + const b = document.createElement('button'); b.className = 'tile'; + b.innerHTML = '
' + t('dimNr') + ' ' + c.index + '' + (c.baby ? ' ' + t('dimBaby') : '') + '
'; + b.querySelector('.stage').appendChild(imgToCanvas(c.frames.idle1, c.baby ? 3 : 1)); + b.onclick = () => { selD.value = c.index; state.dimSel = selD.value; grid.querySelectorAll('.tile').forEach(x => x.classList.toggle('sel', x === b)); draw(); }; + grid.appendChild(b); + }); + area.appendChild(grid); + draw(); +} +$('btnDim').onclick = () => $('fileDim').click(); +$('fileDim').onchange = async (e) => { + const f = e.target.files[0]; e.target.value = ''; if (!f) return; + try { const raw = new Uint8Array(await f.arrayBuffer()); state.dim = C.smaDetect(raw) ? C.smaLoad(raw) : C.dimLoad(raw); state.dimSel = undefined; renderDim(); if (!state.dim.chars.length) toast(t('notDim', { e: t('cardNoChars') }), true); } + catch (err) { toast(t('notDim', { e: em(err) }), true); } +}; + +// ------------------------------------------------------------ overview +/* 1.6.8: one chip for all emulators, the main one (A and C, or the first entry) in bold */ +function planEmus(emuOn, kind) { + const em = state.emu, xs = state.extras || []; + const oldNm = () => (F.embedded() && F.feldApps(state.ctx.rom, F.embedded().stub).name0) || mainName(state.ctx.rom) || 'EMU'; + const mainNm = em ? emuNm(em) : emuOn ? oldNm() : ''; + const v = []; + if (mainNm) v.push([mainNm, !doomMain()]); // with DOOM as the main program the emulator goes to the menu + if (!em && kind === 2 && state.emuRemove && !state.paraMainTaken) v.push([oldNm() + ' ' + t('stDel'), false]); + xs.filter((x) => !OWN_CHIP.has(x.kind) && x.kind !== 'doom').forEach((x) => v.push([(v.length ? ', ' : '') + E.extraName(x), false])); + if (!v.length) return [t('planEmus'), t('stNone'), 'off']; + const isNew = !!em || xs.some((x) => !OWN_CHIP.has(x.kind) && x.fresh) || (!!state.extrasDirty && groupSig('emu') !== (state.sig0 || {}).emu), upd = emuUpPending() || emuAutoDirty() || !!(state.extrasUp && state.extrasUp.has('emu')), gone = !em && kind === 2 && state.emuRemove; + if (isNew || upd || !gone) v.push([' · ' + (isNew ? t('stNew') : upd ? t('stUpd') : t('stKeep')), false]); + return [t('planEmus'), v, isNew || upd ? 'new' : gone ? 'del' : 'keep']; +} +/* 1.6.10 test2: Wolfenstein 3D with its own chip and its own part of the flash bar */ +function planWolf() { + const xs = (state.extras || []).filter((y) => y.kind === 'wolf'); + if (!xs.length) return [t('planWolf'), state.wolfInit ? t('stDel') : t('stNone'), state.wolfInit ? 'del' : 'off']; + const what = xs.map((x) => { + const inf = E.wolfInfo(x.pack) || { shareware: true, episodes: 1 }; + return inf.sod ? 'Spear of Destiny' : t(inf.shareware ? 'wolfShare' : 'wolfFull') + (inf.episodes > 1 ? ', ' + t('wolfEps', { n: inf.episodes }) : ''); + }).join(' + '); + const fresh = xs.some((x) => x.fresh); + return [t('planWolf'), (fresh ? t('stNew') : state.wolfKeysDirty ? t('stUpd') : t('stKeep')) + ', ' + what, fresh || state.wolfKeysDirty ? 'new' : 'keep']; +} +/* 1.6.10 test4: Game Boy and Master System with their own chip and their own part of the flash bar */ +const OWN_CHIP = new Set(['wolf', 'gb', 'sms', 'pm', 'ab']); +function groupKind(x) { return OWN_CHIP.has(x.kind) ? x.kind : 'emu'; } +function groupSig(g) { + return JSON.stringify((state.extras || []).filter((x) => groupKind(x) === g).map((x) => [E.extraName(x), x.keys || null, !!x.inv, x.clock, x.nfc, x.opt, x.sess !== false])); +} +function planGroup(g, label) { + const xs = (state.extras || []).filter((x) => x.kind === g), sig0 = (state.sig0 || {})[g], was = !!sig0 && sig0 !== '[]'; + if (!xs.length) return [label, was ? t('stDel') : t('stNone'), was ? 'del' : 'off']; + const isNew = xs.some((x) => x.fresh), upd = !isNew && (groupSig(g) !== sig0 || !!(state.extrasUp && state.extrasUp.has(g))); + return [label, xs.map((x) => E.extraName(x)).join(', ') + ' · ' + (isNew ? t('stNew') : upd ? t('stUpd') : t('stKeep')), isNew || upd ? 'new' : 'keep']; +} +const MB = (n) => (n / 1048576).toFixed(n < 1048576 ? 2 : 1).replace(/\.?0+$/, '') + ' MB'; +/* test17: the overview's free room from a quiet trial build (after removing a program, after loading) */ +let roomSoonT = 0, roomSoonRun = false; +function roomSoon() { + clearTimeout(roomSoonT); + roomSoonT = setTimeout(async () => { + if (roomSoonRun || toast.mute || !state.ctx || state.sixOff) return; + const sig = roomSig(); if (state.roomFree && state.roomFree.sig === sig) return; + roomSoonRun = true; + try { const m = await roomTry(); if (!state.roomFree || state.roomFree.sig !== sig) state.roomFree = { sig, kb: -1 }; } finally { roomSoonRun = false; } // 1.7.3 test13: a trial that failed (no programs, no room) says nothing about the room (it showed all as "reserved") + if (roomSig() === sig) renderPlan(); + }, 400); +} +function renderPlan() { + const el = $('plan'); if (!el || !state.ctx) return; + const rom = state.ctx.rom, kind = appInstalled(); + const emuOn = !!state.emu || (kind === 2 && !state.emuRemove && !state.doom), doomOn = !!state.doom || (doomFree() && doomXs().length > 0) || (kind === 1 && !state.emuRemove && (!state.emu || !!state.launch)); + const fe = F.embedded(), menuOld = fe && F.feldFind(rom, fe.stub); + const st = (on, isNew, old, extra) => on ? (isNew ? t('stNew') : t('stKeep')) + (extra ? ', ' + extra : '') : (old ? t('stDel') : t('stNone')); + const chips = [ + [t('planFig'), state.changed.size ? t('stChanged', { n: state.changed.size }) : t('stSame'), state.changed.size ? 'new' : 'keep'], + planEmus(emuOn, kind), + planGroup('gb', t('planGb')), + planGroup('sms', t('planSms')), + planGroup('pm', t('planPm')), + planGroup('ab', t('planAb')), + planWolf(), + [t('planDoom'), st(doomOn, !!state.doom, kind === 1, state.doom ? (DOOM_EPS && doomFree() && state.doom.sel ? doomChip(state.doom) : 'E' + $('doomEp').value) + ($('doomMusic').checked ? ' + ' + t('doomMusic') : '') : ''), state.doom ? 'new' : doomOn ? 'keep' : kind === 1 ? 'del' : 'off'], + ]; + const menuOn = menuWanted(), parts = [state.launch ? t('planLaunch') : '', state.feld ? t('feldOn') : '', state.bag ? t('bagOn') : '', state.tama ? t('tamaOn') : '', state.gplay ? t('gplayOn') : ''].filter(Boolean).join(', '); + const menuSame = state.feld === state.feldInit && state.bag === state.bagInit && state.tama === state.tamaInit && !!state.gplay === !!state.gplayInit && state.saves === state.savesInit && state.launch === state.launchInit; + if (state.clean) chips[0] = [t('planFig'), t('cleanOn'), state.cleanInit ? 'keep' : 'new']; + chips.push([t('planMenu'), menuOn ? parts + (state.feldStale && menuSame ? ' (' + t('stUpd') + ')' : '') : (menuOld ? t('stDel') : t('stNone')), menuOn ? ((menuSame && !state.feldStale) ? 'keep' : 'new') : menuOld ? 'del' : 'off']); + const sixIn = !!S6.sixInfo(rom); + { const n = new Set([...(state.eyeShift || new Map()).keys(), ...(state.mouthShift || new Map()).keys(), ...(state.poseAdj || new Map()).keys()]).size; if (n) chips.push([t('planEyes'), t('planNamesN', { n }), 'new']); } + if (state.texts && state.texts.size) chips.push([t('planNames'), t('planNamesN', { n: state.texts.size }), 'new']); + if (sixIn || state.six || state.sixWant) chips.push([t('planSix'), sixIn ? t('stKeep') : t('stNew'), sixIn ? 'keep' : 'new']); + // Flash: from 0x111000 to the end + const base = state.clean ? 0x10000 : 0x111000, end = 0x1000000, total = end - base, segs = []; + const assets = state.clean ? 0 : estimateEnd() - base + (state.six && !sixIn ? 0xB9000 : 0); if (assets) segs.push(['fw', t('segFw'), assets]); + let doomSize = 0, emuSize = 0; + if (doomFree()) doomSize = doomXs().reduce((n, x) => n + E.extraSize(x), 0); + else if (state.doom) { const f = state.doom.fit[$('doomEp').value]; doomSize = (f ? ($('doomMusic').checked && f.music ? f.sizeM : f.sizeP) : 0) + (0xD48000 - 0xCA0000); } + else if (doomOn) doomSize = (rom[0x830000] | rom[0x830001] << 8 | rom[0x830002] << 16 | rom[0x830003] << 24) + (0xD48000 - 0xCA0000); + if (state.emu) emuSize = state.emu.size || 0; + else if (emuOn) { const c7 = E.t7Cfg(rom), c18 = E.t18Cfg(rom); if (c18) emuSize = c18.map.filter((b) => b !== 0xFFFF).length << 16; else if (c7) emuSize = c7.romLen + c7.figs.reduce((n, f) => n + f.len, 0); else { const o = 0xA0000 + 0x140 + 12; emuSize = rom[o] | rom[o + 1] << 8 | rom[o + 2] << 16 | rom[o + 3] << 24; } } + const gs = { wolf: 0, gb: 0, sms: 0, pm: 0, ab: 0 }; + for (const x of state.extras || []) if (x.kind === 'doom') continue; else if (OWN_CHIP.has(x.kind)) gs[x.kind] += E.extraSize(x); else emuSize += E.extraSize(x); // more emulators: program, save, data + const wolfSize = gs.wolf; + if (doomOn) segs.push(['doom', t('segDoom'), doomSize]); + if (emuOn || (state.extras || []).some((x) => !OWN_CHIP.has(x.kind))) segs.push(['emu', t('segEmu'), emuSize]); + if (gs.gb) segs.push(['gb', t('segGb'), gs.gb]); + if (gs.sms) segs.push(['sms', t('segSms'), gs.sms]); + if (gs.pm) segs.push(['pm', t('segPm'), gs.pm]); + if (gs.ab) segs.push(['ab', t('segAb'), gs.ab]); + if (wolfSize) segs.push(['wolf', t('segWolf'), wolfSize]); + if (state.feld && !doomOn) { const ed = F.edition(rom); segs.push(['slots', t('segSlots'), ed ? ed.profile.names.length * 0x58000 : 0]); } + const save = state.clean ? 0 : (state.launch ? 0xF00000 : end) - 0xD29000; if (save) segs.push(['save', t('segSave'), save]); // start device: the MB behind the save is free for programs + let used = segs.reduce((a, x) => a + x[2], 0); + // test17 ROOM_REAL: in a start device the free part is what the last trial build really left (program parts need + // whole, partly aligned blocks; the write protection block and the flash app count as used); the rest is programs + const rfOk = ROOM_AUTO && state.launch && state.roomFree && state.roomFree.sig === roomSig(), rf = rfOk && state.roomFree.kb >= 0 ? state.roomFree.kb * 1024 : -1; + if (rf >= 0) { const fix = total - used - rf, e = segs.find((x) => x[0] === 'emu'); if (fix > 0) segs.push(['resv', t('segResv'), fix]); else if (e) e[2] = Math.max(0, e[2] + fix); used = total - rf; } // test18: what programs keep empty (spares, saves, gaps) apart + else if (ROOM_AUTO && state.launch && state.ctx && !rfOk) roomSoon(); + segs.push(['free', t('segFree'), Math.max(0, total - used)]); + el.innerHTML = ''; + const h = document.createElement('div'); h.className = 'plan-h'; h.textContent = t('planTitle'); el.appendChild(h); + const row = document.createElement('div'); row.className = 'chips'; + chips.forEach(([l, v, c]) => { + const feature=new Map([[t('planEmus'),'emu'],[t('planGb'),'gb'],[t('planSms'),'sms'],[t('planPm'),'pm'],[t('planAb'),'ab'],[t('planWolf'),'wolf'],[t('planDoom'),'doom']]).get(l);if(feature&&!featureEnabled(feature))return; + const d = document.createElement('span'); d.className = 'chip ' + c; d.innerHTML = ' '; d.firstChild.textContent = l; + if (Array.isArray(v)) for (const [txt, bold] of v) { const e = document.createElement(bold ? 'strong' : 'span'); e.textContent = txt; d.lastChild.appendChild(e); } // 1.6.8: the main emulator in bold + else d.lastChild.textContent = v; + row.appendChild(d); + }); + el.appendChild(row); + const bar = document.createElement('div'); bar.className = 'flash'; + const leg = document.createElement('div'); leg.className = 'legend'; + segs.forEach(([k, l, n]) => { + if (n <= 0) return; + const i = document.createElement('i'); i.className = 'seg ' + k; i.style.width = (n / total * 100).toFixed(2) + '%'; i.title = l + ': ' + MB(n); bar.appendChild(i); + const g = document.createElement('span'); g.innerHTML = ''; g.appendChild(document.createTextNode(l + ' ' + MB(n))); leg.appendChild(g); + }); + el.appendChild(bar); el.appendChild(leg); + if ((state.oldT7 || []).length) { const w = document.createElement('div'); w.className = 'rule warn'; w.textContent = t('t7Old', { n: state.oldT7.join(', ') }); el.appendChild(w); } + if (state.t18Broken && (state.extras || []).some((x) => x.kind === 't18' && x.keepOff !== undefined)) { const w = document.createElement('div'); w.className = 'rule warn'; w.textContent = t('t18Broken'); el.appendChild(w); } + const r = document.createElement('div'); r.className = 'rule'; r.hidden=!featureEnabled('extras'); r.textContent = state.clean ? t('ruleClean') : state.launch ? t('ruleLaunch') : appRoom() ? t('ruleBoth') : t('ruleNoRoom'); el.appendChild(r); +} + +// ------------------------------------------------------------ emulator +function appInstalled() { + try { + const r = state.ctx.rom, fe = F.embedded(); + if (state.ctx.clean) return 0; // CLEAN_ROM: no main program at 0x0A0000, every program is in the menu (DOOM too, test3) + if (fe && F.isLaunch(r, fe.stub)) return F.appKind(r); // 1.6.8: start device, the home screen hooks point to the trampolines + return E.installedOrigs(r, E.sceneTable(r)) ? F.appKind(r) : 0; + } catch (e) { return 0; } +} +function emuInstalled() { return appInstalled() === 2; } +function doomInstalled() { return appInstalled() === 1; } +/* Where the stub can sit: the emulator's own at 0x0B0000, or the menu's (also elsewhere) */ +function stubList(rom) { + const ee = E.embedded(), fe = F.embedded(), l = []; + if (ee) l.push([E.STUB_OFF, ee.stub]); + if (fe) { l.push([E.STUB_OFF, fe.stub]); const f = F.feldFind(rom, fe.stub); if (f && f.stubOff !== E.STUB_OFF) l.push([f.stubOff, fe.stub]); } + return l; +} +function emuAutoDirty() { return (emuInstalled() || (doomInstalled() && !state.launch)) && !state.emu && !state.emuRemove && !state.doom && (!!E.autoGet(state.ctx.rom, stubList(state.ctx.rom)) !== !!state.emuAuto || (emuInstalled() && emuClockDirty())); } +function emuClockDirty() { const sv = E.emuSessGet(state.ctx.rom); if (sv !== null && sv !== (state.emuSess !== false)) return true; const c = E.emuClockGet(state.ctx.rom), n = E.emuNfcGet(state.ctx.rom), o = E.emuOptGet(state.ctx.rom), w = state.emuOpt || {}; return (c !== null && c !== !!state.emuClock) || (n !== null && n !== (state.emuNfc !== false)) || (!!o && (o.vol !== w.vol || o.dim !== w.dim || o.off !== w.off)); } +function emuUpPending() { + const emb = E.embedded(); + if (state.emu || state.emuRemove || state.doom || !emb || !emuInstalled()) return false; + try { + if (F.emuType(state.ctx.rom) === 't7') return !!(E.t7Embedded() && E.t7Upgrade(state.ctx.rom, E.t7Embedded())); + if (F.emuType(state.ctx.rom) === 'v1') return !!(E.v1Embedded() && E.v1Upgrade(state.ctx.rom, E.v1Embedded())); + if (F.emuType(state.ctx.rom) === 't18') return !!(E.t18Embedded() && E.t18Upgrade(state.ctx.rom, E.t18Embedded(), E.embedded() && E.embedded().stub)); + return !!E.emuUpgrade(state.ctx.rom, emb.app); + } catch (e) { return false; } +} +/* Room for emulator and DOOM: both need the area after the characters from 0x830000 and the program space at 0x0A0000 */ +/* 1.6.9 test25: firmware that reaches past 0x0A0000 (Jade Forest wave 2 up to 0x0A1683, GitHub issue; Tropical, Glacier): + * no main program there, but a start device puts every program into the menu (appsPlace, anywhere free) */ +function a0Free() { const r = state.ctx.rom; return !!F.appKind(r) || r.subarray(0xA0000, 0xA1000).every(b => b === 0xFF); } +function appRoom() { return !a0Free() || estimateEnd() <= 0x830000; } // without a main program the trial build decides (roomMissing) +function renderEmu() { + if (!state.ctx) return; + renderGb(); + renderSms(); + renderPm(); + renderAb(); + renderWolf(); + const has = emuInstalled(); + $('btnEmuOff').hidden = true; $('btnEmuUndo').hidden = true; // 1.6.8: in the list of programs (×, ↺) + let s; + if (!E.embedded()) s = t('emuMissing'); + const t7In = has && F.emuType(state.ctx.rom) === 't7', t7 = state.emu ? !!state.emu.t7 : t7In && !state.emuRemove; + const t18In = has && F.emuType(state.ctx.rom) === 't18', t18 = state.emu ? !!state.emu.t18 : t18In && !state.emuRemove; + const t7Fr = state.emu ? !!state.emu.t7 && E.t7Kind(state.emu.rom) === 'friends' : t7In && !!E.t7Cfg(state.ctx.rom) && E.t7Cfg(state.ctx.rom).romLen === 0xC0000; + if (state.emu) s = state.emu.v1 ? t(E.v3Detect(state.emu.rom) ? 'v3Ok' : 'v1Ok') : state.emu.t7 ? t(t7Fr ? 't7OkFr' : 't7Ok') : state.emu.t18 ? t('t18Ok') : t('emuOk', { size: E.DEVICES[state.emu.dev].label }); + else if (state.emuRemove) s = t('emuGone'); + else s = has ? t(t7In ? (t7Fr ? 't7HasFr' : 't7Has') : t18In ? 't18Has' : 'emuHas') + (emuUpPending() ? ' ' + t('emuUp') : '') : (state.extras && state.extras.length ? t('emuInList', { n: state.extras.map((x) => E.extraName(x)).join(', ') }) : t('emuNone')); + const v1 = state.emu ? !!state.emu.v1 : has && F.emuType(state.ctx.rom) === 'v1' && !state.emuRemove; + const v3 = v1 && E.v3Detect(state.emu ? state.emu.rom : E.v1FromRom(state.ctx.rom)); + s += (state.emu || (has && !state.emuRemove) ? '\n' + t(v3 ? 'v3Use' : v1 ? 'v1Use' : t7 ? 't7Use' : t18 ? 't18Use' : 'emuUse') : ''); + const bigIn = has && !state.emu && !state.emuRemove && state.ctx.rom[0xA0148] === 0 && state.ctx.rom[0xA014A] === 0x84; + if ((state.emu && state.emu.big) || bigIn) s += '\n' + t('emuBig'); + const room = appRoom(); + $('btnEmu').disabled = !room; + if (!room) s = t('noRoomApp'); + else if (!a0Free()) s += '\n' + t(state.launch ? 'a0Menu' : 'a0MenuN'); + else if (!state.launch && !state.emu && (state.doom || (doomInstalled() && !state.emuRemove))) s += '\n' + t('emuVsDoom'); + $('emuStat').textContent = s; + renderT7Figs(t7 && room && !t7Fr); + renderApps(); + $('emuAutoRow').hidden = true; $('emuClockRow').hidden = true; // 1.6.8: in the main program's row + { const is4u = state.emu ? (state.emu.dev === '4u' || state.emu.dev === '4u-plain') : (!state.emuRemove && E.emuNfcGet(state.ctx.rom) !== null); $('emuNfcRow').hidden = true; void is4u; $('emuNfc').checked = state.emuNfc !== false; } + $('emuAuto').checked = !!state.emuAuto; + $('emuClock').checked = state.emuClock !== false; + renderPlan(); + $('emuDlc').hidden = true; // 1.6.8: settings, figures and download slots open per program in the list (▾) + $('btnT7Fig').hidden = true; +} +/* T7Emu figures: list with remove buttons */ +function t7State() { + if (state.emu && state.emu.t7) return state.emu; + const cur = E.t7FromRom(state.ctx.rom); if (!cur) return null; + return { t7: true, dev: 't7', rom: cur.rom, figs: cur.figs, size: 0 }; +} +function t7Size(st) { return st.rom.length + st.figs.reduce((n, f) => n + f.data.length, 0); } +/* 1.6.8: download items and figures also for the programs in the menu. Target: 'main' or the index in state.extras */ +const DLC_DEV = ['idl', 'ps', '4u', '4u-plain']; +/* tg: 'main' or the index in state.extras (default: the file dialog's target state.dlcT) */ +function dlcTarget(tg = state.dlcT) { + if (typeof tg === 'number') { const x = (state.extras || [])[tg]; return x && x.kind === 'tama' && DLC_DEV.includes(x.dev) ? { guest: x.guest, dev: x.dev, set: (g) => { x.guest = g; state.extrasDirty = true; } } : null; } + const em = state.emu; + if (em) return !em.t7 && !em.t18 && !em.v1 && DLC_DEV.includes(em.dev) ? { guest: em.guest, dev: em.dev, set: (g) => { em.guest = g; } } : null; + // the installed main TamaEmu: its firmware with the save, read from the ROM; it goes into the work on the first change + const mg = state.mainGuest; + if (mg && !state.emuRemove) return { guest: mg.g, dev: mg.dev, set: (g) => { const pk = E.packMain(g, mg.dev, null, !!state.emuPack); state.emu = { guest: g, dev: mg.dev, size: pk.blob.length, big: pk.big, kept: true }; state.mainGuest = null; } }; + return null; +} +/* test5: Gotchi Points of a Tama-Go (T7Emu): EEPROM 0x030-0x034, 5 bytes BCD lowest digits first, no checksum + * (save.bin: behind the 2 byte page mask). Goes in like an imported save: the running state starts anew. */ +function t7GpSave(tg) { + const rom = state.ctx.rom; + if (tg === 'main') return state.t7save || SV.t7SaveOut(rom); + const x = state.extras[tg]; if (!x || x.kind || x.fresh) return null; + if (state.t7saveX && state.t7saveX.i === tg) return state.t7saveX.save; + const o = romExtras(rom).find((r) => E.extraKind(r) === 't7' && r.rom.length === x.rom.length && r.rom.every((v, k) => v === x.rom[k])); + return o ? SV.t7SaveOut(rom, o.saveOff) : null; +} +function t7GpGet(sv) { + let n = 0; + for (let i = 4; i >= 0; i--) { const v = sv[0x32 + i], hi = v >> 4, lo = v & 15; if (hi > 9 || lo > 9) return -1; n = n * 100 + hi * 10 + lo; } + return n; +} +function t7GpInto(box, tg) { + const sv = t7GpSave(tg); if (!sv || !(sv[0] & 1)) return; // page 0 of the EEPROM must be there + const n = t7GpGet(sv); if (n < 0) return; + const l = document.createElement('label'); l.className = 'check'; const sp = document.createElement('span'); sp.textContent = t('t7Gp') + ' '; + const inp = document.createElement('input'); inp.type = 'number'; inp.min = 0; inp.max = 999999; inp.value = String(n); inp.style.width = '7em'; + inp.onchange = () => { + let v = Math.max(0, Math.min(999999, Math.floor(+inp.value || 0))); + const g = new Uint8Array(sv); + for (let i = 0; i < 5; i++) { const d = v % 100; g[0x32 + i] = ((d / 10 | 0) << 4) | (d % 10); v = Math.floor(v / 100); } + if (tg === 'main') state.t7save = g; else state.t7saveX = { i: tg, save: g }; + renderPlan(); renderEmu(); + }; + l.append(sp, inp); box.appendChild(l); + const w = document.createElement('div'); w.className = 'hint'; w.textContent = t('t7GpHint'); box.appendChild(w); +} +/* 1.6.8 (test47): items of T18Emu (MyMeets files) go straight into its firmware's save; the running state starts anew */ +function t18Target(tg) { + if (typeof tg === 'number') { const x = (state.extras || [])[tg]; return x && x.kind === 't18' ? { fw: x.fw, set: () => { x.items = true; state.extrasDirty = true; } } : null; } + const em = state.emu; + if (em) return em.t18 ? { fw: em.rom, set: () => { em.items = true; } } : null; + if (!emuInstalled() || state.emuRemove || F.emuType(state.ctx.rom) !== 't18') return null; + if (!state.t18Main) state.t18Main = E.t18FromRom(state.ctx.rom); + const fw = state.t18Main; if (!fw) return null; + return { fw, set: () => { state.t18Dirty = true; } }; // written into the installed program on save (E.t18RomWriteGuest) +} +function picCanvas(pic, sc) { + const c = document.createElement('canvas'); c.className = 'itempic'; + if (!pic) { c.width = c.height = 1; return c; } + c.width = pic.w; c.height = pic.h; c.style.width = (pic.w * sc) + 'px'; c.style.height = (pic.h * sc) + 'px'; + c.getContext('2d').putImageData(new ImageData(pic.rgba, pic.w, pic.h), 0, 0); return c; +} +/* test47: pictures for "grow up" (the user's own files: .png, .png or the Android T18Emu set with erwachsen.json) */ +function t18PicsInto(box) { + const h = document.createElement('h4'); h.className = 'subhead'; h.textContent = t('t18Pics'); box.appendChild(h); + const tools = document.createElement('div'); tools.className = 'tools'; + const pick = document.createElement('button'); pick.className = 'btn small'; pick.textContent = t('t18PicsPick'); pick.onclick = () => $('fileT18Pic').click(); + tools.appendChild(pick); + if (state.t18Pics && state.t18Pics.size) { const del = document.createElement('button'); del.className = 'btn small'; del.textContent = t('t18PicsDel'); del.onclick = () => { state.t18Pics = new Map(); state.t18PicsDirty = true; renderEmu(); }; tools.appendChild(del); } + box.appendChild(tools); + if (state.t18Pics && state.t18Pics.size) { + const g = document.createElement('div'); g.className = 'picgrid'; + for (const [id, p] of state.t18Pics) { const f = document.createElement('figure'); const c = picCanvas(E.t18PicRgba(p), 1); const cap = document.createElement('figcaption'); cap.textContent = (E.T18_ADULTS.find((a) => a[0] === id) || [0, '#' + id])[1]; f.append(c, cap); g.appendChild(f); } + box.appendChild(g); + } + const w = document.createElement('div'); w.className = 'hint'; w.textContent = t('t18PicsHint'); box.appendChild(w); +} +async function pngRgba(bytes) { + const bm = await createImageBitmap(new Blob([bytes], { type: 'image/png' })); + const c = document.createElement('canvas'); c.width = bm.width; c.height = bm.height; const x = c.getContext('2d'); x.drawImage(bm, 0, 0); + return { w: bm.width, h: bm.height, rgba: x.getImageData(0, 0, bm.width, bm.height).data }; +} +/* test3: items or Tamapoints changed: with "keep saves" the device would bring back its own T18 save (session, sector + * tables, spare blocks) over the changed one. The whole T18 save comes from the image then (it is the device's state at + * reading plus the change). */ +function t18Fresh(rom, off, fresh) { + const c = E.extraCfg(rom, off); if (!c || c.kind !== 't18') return; + fresh.push([c.saveOff, c.saveOff + 0x24000]); + for (const b of c.spare) if (b !== 0xFFFF) fresh.push([b << 16, (b + 1) << 16]); +} +/* test2: a name the Studio cannot read (Japanese letters) shows as its number */ +function t18Nm(r) { return r.readable !== false || !r.cat ? r.name : t('t18ItemNo', { n: r.cat }); } +/* test6: MixingMeets for T18Emu on the Paradise. The page (mixing-meets.com, Connect and Return) speaks Web Bluetooth + * with "TMGC_meets" (service fff0, fff1 notify, fff2 write). This bookmarklet replaces navigator.bluetooth on that page: + * "Select Tamagotchi" then opens the serial port of the UART dongle on the Paradise's contacts, and T18Emu hands the data + * to the firmware's Bluetooth module, as the Android T18Emu does. Frames: see t18/src/app/main.c (T18_LINK). */ +function pmxBridge() { + if (window.__pmxBridge) { alert('Paramix: bridge already on'); return; } + if (!navigator.serial) { alert('Paramix: this browser has no Web Serial (Chrome or Edge on a computer)'); return; } + window.__pmxBridge = 1; + const bn = document.createElement('div'); + bn.style.cssText = 'position:fixed;left:8px;bottom:8px;z-index:2147483647;background:#1d2b44;color:#fff;padding:8px 12px;border-radius:8px;font:13px/1.3 sans-serif;max-width:320px'; + const st = (m) => { bn.textContent = 'Paramix: ' + m; }; + st('bridge on. Select Tamagotchi, then choose the dongle.'); document.body.appendChild(bn); + const FFF0 = '0000fff0-0000-1000-8000-00805f9b34fb', FFF1 = '0000fff1-0000-1000-8000-00805f9b34fb', FFF2 = '0000fff2-0000-1000-8000-00805f9b34fb'; + let port = null, reader = null, writer = null, hello = 0, ack = null, ping = null, live = false; + const notes = [], gone = []; + let fs = 0, fty = 0, flen = 0, fbuf = [], fsum = 0; + const frame = (ty, d) => { const a = new Uint8Array(4 + d.length); a[0] = 0x5A; a[1] = ty; a[2] = d.length; let s = ty + d.length; for (let i = 0; i < d.length; i++) { a[3 + i] = d[i]; s += d[i]; } a[3 + d.length] = s & 255; return a; }; + const send = (ty, d) => writer.write(frame(ty, d || [])); + const R = { uuid: FFF1, properties: { notify: true, read: false, write: false, writeWithoutResponse: false }, value: null, + addEventListener: (ty, fn) => { if (ty === 'characteristicvaluechanged') notes.push(fn); }, removeEventListener: () => {}, + startNotifications: async () => R, stopNotifications: async () => R }; + const got = (ty, d) => { + if (ty === 0x48) { hello = Date.now(); return; } + if (ty === 0x4B) { const a = ack; ack = null; if (a) a(); return; } + if (ty === 0x4E) { const u = new Uint8Array(d); R.value = new DataView(u.buffer); for (const fn of notes) { try { fn({ target: R }); } catch (e) { console.error(e); } } } + }; + const feed = (b) => { + if (fs === 0) { if (b === 0xA5) fs = 1; return; } + if (fs === 1) { fty = b; fsum = b; fs = 2; return; } + if (fs === 2) { if (b > 64) { fs = 0; return; } flen = b; fsum += b; fbuf = []; fs = flen ? 3 : 4; return; } + if (fs === 3) { fbuf.push(b); fsum += b; if (fbuf.length >= flen) fs = 4; return; } + fs = 0; if ((fsum & 255) === b) got(fty, fbuf); + }; + const down = () => { if (!live) return; live = false; dev.gatt.connected = false; clearInterval(ping); for (const fn of gone) { try { fn({ target: dev }); } catch (e) {} } }; + const readLoop = async () => { try { for (;;) { const { value, done } = await reader.read(); if (done) break; for (const b of value) feed(b); } } catch (e) {} st('dongle closed'); down(); }; + const write = async (data) => { + if (!live) throw new Error('Your Tama disconnected'); + const u = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + for (let o = 0; o < u.length; o += 60) { + const p = new Promise((res, rej) => { ack = res; setTimeout(() => { if (ack === res) { ack = null; rej(new Error('Paradise did not answer')); } }, 15000); }); + await send(0x57, Array.from(u.subarray(o, o + 60))); await p; + } + }; + const T = { uuid: FFF2, properties: { write: true, writeWithoutResponse: false, notify: false, read: false }, + writeValueWithResponse: write, writeValue: write, writeValueWithoutResponse: write }; + const svc = { uuid: FFF0, isPrimary: true, getCharacteristic: async (u) => { u = String(u).toLowerCase(); if (u.indexOf('fff1') >= 0) return R; if (u.indexOf('fff2') >= 0) return T; throw new Error('No characteristic ' + u); } }; + const dev = { id: 'paramix', name: 'TMGC_meets', addEventListener: (ty, fn) => { if (ty === 'gattserverdisconnected') gone.push(fn); }, removeEventListener: () => {} }; + dev.gatt = { device: dev, connected: false, + connect: async () => { await send(0x43, [1]); live = true; dev.gatt.connected = true; clearInterval(ping); ping = setInterval(() => { send(0x50, []).catch(() => {}); }, 1000); st('connected to the Paradise'); return dev.gatt; }, + disconnect: () => { if (writer) send(0x43, [0]).catch(() => {}); down(); }, + getPrimaryService: async (u) => { if (String(u).toLowerCase().indexOf('fff0') < 0) throw new Error('No services matching UUID ' + u); return svc; } }; + const requestDevice = async () => { + if (!port) { + const pp = await navigator.serial.requestPort(); + try { await pp.open({ baudRate: 460800, bufferSize: 4096 }); } + catch (e) { st('the dongle is busy. In Paramix Studio press "UART freigeben" (or close the Studio), then try again.'); alert('Paramix: the dongle is busy.\nParamix Studio still holds it: press "UART freigeben" there or close the Studio, then try again.'); throw e; } + port = pp; + reader = port.readable.getReader(); writer = port.writable.getWriter(); readLoop(); + } + st('looking for T18Emu on the Paradise...'); + const t0 = Date.now(); while (!hello && Date.now() - t0 < 4000) await new Promise((r) => setTimeout(r, 100)); + if (!hello) { st('no answer from the Paradise'); throw new Error('Paradise not found: start T18Emu and check the dongle'); } + st('Paradise found'); return dev; + }; + try { Object.defineProperty(navigator, 'bluetooth', { configurable: true, value: { requestDevice, getAvailability: async () => true } }); } + catch (e) { alert('Paramix: could not take over Bluetooth on this page'); } + window.addEventListener('pagehide', () => { try { if (writer) writer.write(frame(0x43, [0])); } catch (e) {} }); +} +function pmxBridgeHref() { return 'javascript:' + encodeURIComponent('(' + pmxBridge.toString() + ')()'); } +window.pmxBridgeHref = pmxBridgeHref; // for the test +window.pmxTest = { uartWarnInto: (b) => uartWarnInto(b), devFree: () => devFree(), devRender: () => devRender(), dv: () => dv }; +function t18BridgeInto(box) { + const h = document.createElement('h4'); h.className = 'subhead'; h.textContent = t('mmTitle'); box.appendChild(h); + const a = document.createElement('a'); a.className = 'btn small'; a.href = pmxBridgeHref(); a.textContent = t('mmLink'); a.onclick = (e) => { e.preventDefault(); toast(t('mmDrag')); }; + box.appendChild(a); + const w = document.createElement('div'); w.className = 'hint'; w.style.whiteSpace = 'pre-line'; w.textContent = t('mmHint'); box.appendChild(w); + uartWarnInto(box); + pairInto(box, 'pairHint'); +} +/* 1.6.9: visits over the contacts for the other emulators (T7Emu Tama-Go so far) */ +const IR_HINT = { ps: 'pairHintPs', idl: 'pairHintIdl' }; /* TamaEmu with the infrared link (1.6.9) */ +function linkInto(box, hint) { pairInto(box, hint); } +/* test7: the bridge page needs the dongle for themselves. While the Studio holds it, say so and + * offer to let it go. */ +const uartWarns = []; +function uartWarnRender() { + for (const b of uartWarns) { if (!b.isConnected) continue; b.hidden = !dv.io; } +} +function uartWarnInto(box) { + const d = document.createElement('div'); d.className = 'uartwarn'; + const m = document.createElement('span'); m.textContent = t('uartBusy') + ' '; + const k = document.createElement('button'); k.className = 'btn small'; k.textContent = t('uartFree'); k.onclick = () => devFree(); + d.append(m, k); box.appendChild(d); uartWarns.push(d); d.hidden = !dv.io; +} +async function devFree() { + if (dv.run) { toast(t('uartRun')); return; } + try { if (dv.io) await dv.io.close(); } catch (e) {} + dv.io = null; dv.d = null; dv.loaded = false; devRender(t('devNone')); toast(t('uartFreed')); +} +/* 1.6.9: visits between two Paradise: plugged together at the top, the programs talk over the contacts themselves */ +function pairInto(box, hint) { + const h = document.createElement('h4'); h.className = 'subhead'; h.textContent = t('pairTitle'); box.appendChild(h); + const w = document.createElement('div'); w.className = 'hint'; w.style.whiteSpace = 'pre-line'; w.textContent = t(hint); box.appendChild(w); +} +function t18ItemsInto(box, tg) { + const T = t18Target(tg); if (!T) return; + const it = E.t18Items(T.fw); + const h = document.createElement('h4'); h.className = 'subhead'; h.textContent = t('t18Items'); box.appendChild(h); + if (!it.save) { const w = document.createElement('div'); w.className = 'hint'; w.textContent = t('t18ItemsNoSave'); box.appendChild(w); return; } + const tools = document.createElement('div'); tools.className = 'tools'; + const pick = document.createElement('button'); pick.className = 'btn small'; pick.textContent = t('t18ItemsPick'); + pick.onclick = () => { state.itemT = tg; $('fileT18Item').click(); }; + const pl = document.createElement('label'); pl.className = 'check'; const ps = document.createElement('span'); ps.textContent = t('t18Points') + ' '; + const pi = document.createElement('input'); pi.type = 'number'; pi.min = 0; pi.max = 65535; pi.value = String(it.points); pi.style.width = '7em'; + pi.onchange = () => { E.t18Points(T.fw, +pi.value || 0); T.set(); renderEmu(); }; + pl.append(ps, pi); tools.append(pick, pl); box.appendChild(tools); + const grid = document.createElement('div'); grid.className = 'dlcgrid'; + for (const a of it.areas) { + const d = document.createElement('div'); d.className = 'dlcbox'; + const used = a.slots.filter((x) => x.rec); + const hh = document.createElement('h4'); hh.textContent = t('t18A_' + a.key) + ' ' + used.length + '/' + (used.length + a.free); d.appendChild(hh); + for (const x of used) { + const r = document.createElement('div'); r.className = 'dlcrow'; + const n = document.createElement('span'); n.className = 'itemname'; n.append(picCanvas(x.rec.pic, 1), document.createTextNode(' ' + t18Nm(x.rec))); + const sel = document.createElement('select'); [1, 2, 3].forEach((v) => { const o = document.createElement('option'); o.value = String(v); o.textContent = v + '×'; sel.appendChild(o); }); + sel.value = String(x.count); sel.onchange = () => { E.t18ItemCount(T.fw, a.key, x.n, +sel.value); T.set(); renderEmu(); }; + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = t('dlcDel'); + b.onclick = () => { E.t18ItemDel(T.fw, a.key, x.n); T.set(); toast(t('dlcGone', { n: t18Nm(x.rec) })); renderEmu(); }; + const ctl = document.createElement('span'); ctl.className = 'itemctl'; ctl.append(sel, b); r.append(n, ctl); d.appendChild(r); + } + const f = document.createElement('div'); f.className = 'dlcrow free'; f.textContent = t('dlcFreeN', { n: a.free }); d.appendChild(f); + grid.appendChild(d); + } + { const d = document.createElement('div'); d.className = 'dlcbox'; + const hh = document.createElement('h4'); hh.textContent = t('t18A_room'); d.appendChild(hh); + const r = document.createElement('div'); r.className = 'dlcrow'; + if (it.room) { + const n = document.createElement('span'); n.className = 'itemname'; n.append(picCanvas(it.room.pic, 0.5), document.createTextNode(' ' + t18Nm(it.room))); + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = t('t18RoomBack'); + b.onclick = () => { E.t18RoomReset(T.fw); T.set(); renderEmu(); }; + r.append(n, b); + } else r.textContent = t('t18RoomBuiltin'); + d.appendChild(r); grid.appendChild(d); } + box.appendChild(grid); + const w = document.createElement('div'); w.className = 'hint'; w.textContent = t('t18ItemsHint'); box.appendChild(w); +} +function figTarget(tg = state.figT) { + if (typeof tg === 'number') { const x = (state.extras || [])[tg]; if (!x || x.kind || E.t7Kind(x.rom) !== 'go') return null; x.figs = x.figs || []; return x; } + return t7State(); +} +async function mainGuestLoad() { + if (state.mainGuest) return true; + const cfg = romEmuCfg(state.ctx.rom); if (!cfg) return false; + const g = await SV.emuGuestAsync((a, n) => state.ctx.rom.subarray(a, a + n), cfg); + state.mainGuest = { g, dev: cfg.dev }; + return true; +} +function renderT7Figs() { $('btnT7Fig').hidden = true; $('t7Figs').hidden = true; } // 1.6.8: the figures are in the program's row +/* list of the figures of one T7Emu, each with × */ +function figsInto(box, tg) { + const st = figTarget(tg); if (!st) return; + if (!st.figs.length) { const d = document.createElement('span'); d.className = 'hint'; d.textContent = t('t7FigNone'); box.appendChild(d); return; } + const wrap = document.createElement('div'); wrap.className = 'chips'; + st.figs.forEach((f, i) => { + const c = document.createElement('span'); c.className = 'chip keep'; c.textContent = E.t7FigName(f.name) + ' '; + const x = document.createElement('button'); x.className = 'btn small'; x.textContent = '×'; + x.onclick = () => { const s2 = figTarget(tg); s2.figs.splice(i, 1); if (typeof tg === 'number') state.extrasDirty = true; else { s2.size = t7Size(s2); state.emu = s2; emuRemoveClear(); } renderEmu(); }; + c.appendChild(x); wrap.appendChild(c); + }); + box.appendChild(wrap); +} +/* the download content stores of one TamaEmu, each slot with its name */ +function dlcInto(box, tg) { + const g0 = dlcTarget(tg); if (!g0) return; + const grid = document.createElement('div'); grid.className = 'dlcgrid'; + for (const st of E.dlcStores(g0.guest)) { + const used = st.slots.filter(x => x.name).length; + const d = document.createElement('div'); d.className = 'dlcbox'; + const h = document.createElement('h4'); h.textContent = t('dlcK' + st.kind) + ' ' + used + '/' + st.slots.length; d.appendChild(h); + for (const x of st.slots) { + if (!x.name) continue; + const r = document.createElement('div'); r.className = 'dlcrow'; + const n = document.createElement('span'); n.textContent = x.name; + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = t('dlcDel'); + b.onclick = () => { const g = dlcTarget(tg); g.set(E.dlcFree(g.guest, st.kind, x.slot)); toast(t('dlcGone', { n: x.name })); renderEmu(); }; + r.append(n, b); d.appendChild(r); + } + const f = document.createElement('div'); f.className = 'dlcrow free'; f.textContent = t('dlcFreeN', { n: st.slots.length - used }); d.appendChild(f); + grid.appendChild(d); + } + box.appendChild(grid); +} +function selectInto(box, label, items, val, fn) { + const r = document.createElement('div'); r.className = 'tools'; + const l = document.createElement('label'); l.className = 'check'; + const sp = document.createElement('span'); sp.textContent = label + ' '; + const sel = document.createElement('select'); items.forEach((txt, i) => { const o = document.createElement('option'); o.value = String(i); o.textContent = txt; sel.appendChild(o); }); + sel.value = String(val || 0); sel.onchange = () => fn(+sel.value); + l.append(sp, sel); r.appendChild(l); box.appendChild(r); +} +/* 1.6.8: TamaEmu and T18Emu options (set here, the toy has no menu for them) */ +function optInto(box, o, set) { + selectInto(box, t('optVol'), [t('optVolN'), t('optVolQ'), t('optVolL'), t('optOff')], o.vol, (v) => { o.vol = v; set(); }); + { const U = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0]; // 5 % .. 100 % + selectInto(box, t('optDim'), U.map((i) => E.OPT_LV[i] + ' %'), Math.max(0, U.indexOf(o.dim)), (v) => { o.dim = U[v]; set(); }); } + selectInto(box, t('optScr'), [t('optScrToy'), '10 s', '20 s', '30 s', '1 Min', '2 Min', '5 Min', '10 Min'], o.off, (v) => { o.off = v; set(); }); + const h = document.createElement('p'); h.className = 'hint'; h.textContent = t('optDev'); box.appendChild(h); +} +/* 1.7.3 test7: the program's "remember where you left off" taken over from the ROM */ +function sessKeep(x, y) { if (x.sess === false) y.sess = false; return y; } +const SESS_KINDS = new Set(['tama', 't18', 't7', 'v1', 'gb', 'sms', 'pm', 'ab']); +function clockOff() { return !!state.clean && state.cleanClock === false; } +function checkInto(box, label, hint, on, fn, off) { + const r = document.createElement('div'); r.className = 'tools'; + const l = document.createElement('label'); l.className = 'check'; + const c = document.createElement('input'); c.type = 'checkbox'; c.checked = on; c.disabled = !!off; c.onchange = () => fn(c.checked); + const sp = document.createElement('span'); sp.textContent = label; + l.append(c, ' ', sp); r.appendChild(l); + if (hint) { const h = document.createElement('span'); h.className = 'hint'; h.textContent = hint; r.appendChild(h); } + box.appendChild(r); +} +/* All programs in one list (1.6.8). Each row opens with ▾: its settings, figures or download slots. */ +function renderApps() { + const box = $('appsList'); box.innerHTML = ''; + const room = appRoom(); + $('btnApp').disabled = !room || !E.t7Embedded(); + state.progOpen = state.progOpen || new Set(); + const row = (key, name, tag, cls, btns, detail) => { + const r = document.createElement('div'); r.className = 'prow ' + (cls || ''); + const open = !!detail && state.progOpen.has(key); + if (detail) { const tb = document.createElement('button'); tb.className = 'btn small ptog'; tb.textContent = open ? '▴' : '▾'; tb.title = t('progMore'); tb.onclick = () => { if (open) state.progOpen.delete(key); else state.progOpen.add(key); renderEmu(); }; r.appendChild(tb); } + const n = document.createElement('span'); n.className = 'pname'; n.textContent = name; + const g = document.createElement('span'); g.className = 'ptag'; g.textContent = tag; + r.append(n, g); + for (const [txt, fn, title, c, off] of btns) { const b = document.createElement('button'); b.className = 'btn small' + (c ? ' ' + c : ''); b.textContent = txt; if (title) b.title = title; if (fn) b.onclick = fn; if (off) b.disabled = true; r.appendChild(b); } + box.appendChild(r); + if (open) { const d = document.createElement('div'); d.className = 'pdet'; detail(d); box.appendChild(d); } + }; + const has = emuInstalled(), em = state.emu, tagMain = t(state.launch ? 'progMainL' : 'progMain'); + // DOOM at 0x0A0000 is the main program then (in a start device the emulators all go to the menu) + const dm = doomMain(); + const dIn = doomInstalled(), dGone = dIn && !state.doom && (state.emuRemove || (!state.launch && !!state.emu)); + const doomOut = () => { if (state.doom) state.doom = null; else { state.emuRemove = true; if (!state.launch) state.emu = null; } renderEmu(); renderDoom(); }; + const doomBack = () => { state.emuRemove = false; if (!state.launch) state.emu = null; renderEmu(); renderDoom(); }; + // 1.6.9 test13: in the start device DOOM stays at 0x0A0000, but the main program (first in the menu, can start when + // switched on) can be any program of the list (switch FELD_AUTO in the menu) + const lp = !!state.launch && (dm || !!state.clean) && mainV9(); + if (lp && state.mainPick && state.mainPick !== 'emu' && !(state.extras || []).includes(state.mainPick)) state.mainPick = null; + if (lp && state.mainPick === 'emu' && !em) state.mainPick = null; + const pick = (v) => { state.mainPick = v; state.mainDirty = true; renderEmu(); }; + const autoL = (d) => checkInto(d, t('emuAuto'), t('autoHintL'), !!state.emuAuto, (v) => { state.emuAuto = v; state.mainDirty = true; renderEmu(); }); + const star = (on, v) => on ? ['★', null, t('progIsMain'), 'pstar on', true] : ['☆', () => pick(v), t('progMakeMain'), 'pstar']; + const doomIsMain = dm && !(lp && state.mainPick); + if (dm) row('doom', 'DOOM', (doomIsMain ? tagMain : t('progMenu')) + (state.doom ? ' · ' + t('stNew') : ''), doomIsMain ? 'main' : '', [lp ? star(doomIsMain, null) : ['★', null, t('progIsMain'), 'pstar on', true], ['×', doomOut, t('doomOff')]], + state.launch ? (lp && doomIsMain && !state.clean ? autoL : null) : (d) => checkInto(d, t('emuAuto'), t('doomAutoHint'), !!state.emuAuto, (v) => { state.emuAuto = v; renderEmu(); })); + else if (dGone) row('doom', 'DOOM', t('progGone'), 'main gone', [['↺', doomBack, t('progUndo')]]); + const undo = () => { state.emu = null; emuRemoveClear(); state.t7save = null; renderEmu(); renderDoom(); }; + // settings of the main program (they are in the program at 0x0A0000) + const mainSet = (d, dev) => { + if (!dm && !state.clean) checkInto(d, t('emuAuto'), t(state.launch && mainV9() ? 'autoHintL' : 'emuAutoHint'), !!state.emuAuto, (v) => { state.emuAuto = v; if (state.launch) state.mainDirty = true; renderEmu(); }); + else if (lp && state.mainPick === 'emu') autoL(d); + checkInto(d, t('emuClock'), t(clockOff() ? 'emuClockOff' : 'emuClockHint'), !clockOff() && state.emuClock !== false, (v) => { state.emuClock = v; renderEmu(); }, clockOff()); + checkInto(d, t('emuSess'), t('emuSessHint'), state.emuSess !== false, (v) => { state.emuSess = v; renderEmu(); }); + if (dev === '4u' || dev === '4u-plain') checkInto(d, t('emuNfc'), t('emuNfcHint'), state.emuNfc !== false, (v) => { state.emuNfc = v; renderEmu(); }); + // 1.7.3 test20 PACK_OPT: pack the firmware (less room, some places slower); an installed one is read back and built anew + if (E.PACK_OPT && dev && E.DEVICES[dev]) checkInto(d, t('emuPack'), t('emuPackHint'), !!state.emuPack, (v) => { + state.emuPack = v; + if (state.emu && state.emu.guest) { const pk = E.packMain(state.emu.guest, state.emu.dev, null, v); state.emu = Object.assign({}, state.emu, { size: pk.blob.length, big: pk.big }); renderEmu(); return; } + busy(async () => { if (await mainGuestLoad()) { const mg = state.mainGuest, pk = E.packMain(mg.g, mg.dev, null, v); state.emu = { guest: mg.g, dev: mg.dev, size: pk.blob.length, big: pk.big, kept: true }; state.mainGuest = null; } renderEmu(); }); + }); + if (dev !== 't7' && dev !== 'v1' && dev) { state.emuOpt = state.emuOpt || { vol: 0, dim: 0, off: 0 }; optInto(d, state.emuOpt, () => renderEmu()); } + }; + const xRow = (x, i) => { + const b = [], go = !x.kind && E.t7Kind(x.rom) === 'go', big = x.kind === 'tama' && DLC_DEV.includes(x.dev); + if (go) b.push([t('t7FigPick') + (x.figs && x.figs.length ? ' (' + x.figs.length + ')' : ''), () => { state.figT = i; $('fileT7Fig').click(); }]); + if (big) b.push([t('dlcPick'), () => { state.dlcT = i; $('fileDlc').click(); }]); + const xMain = lp && state.mainPick === x; + if (lp) b.push(star(xMain, x)); + else { const ok = !dm && canMain(x); b.push(['☆', ok ? () => busy(() => mainChecked(i)) : null, t(ok ? 'progMakeMain' : x.kind === 'gb' ? 'gbNoMain' : x.kind === 'sms' ? 'smsNoMain' : x.kind === 'pm' ? 'pmNoMain' : x.kind === 'ab' ? 'abNoMain' : x.kind === 'wolf' ? 'wolfNoMain' : dm ? 'progNoMainDoom' : 'progNoMain'), 'pstar', !ok]); } + b.push(['×', () => { if (state.mainPick === x) { state.mainPick = null; state.mainDirty = true; } if (x.fromPara) state.emuRemove = true; if (x.wadSrc) state.doom = null; state.extras.splice(i, 1); state.extrasDirty = true; state.t7saveX = null; state.dlcT = 'main'; state.figT = 'main'; state.progOpen = new Set(); renderEmu(); }, t('progDel')]); + const det = (x.kind === 'wolf' || x.kind === 'doom') && !xMain ? null : (d) => { // 1.7.3 test7: every emulator has "remember where you left off" // test37: the Game Boy has no clock + if (xMain) autoL(d); + if (!(x.kind === 'v1' && !E.v1Clock(x.rom)) && x.kind !== 'gb' && x.kind !== 'sms' && x.kind !== 'pm' && x.kind !== 'ab' && x.kind !== 'wolf' && x.kind !== 'doom') checkInto(d, t('emuClock'), t(clockOff() ? 'emuClockOff' : 'emuClockHint'), !clockOff() && x.clock !== false, (v) => { x.clock = v; state.extrasDirty = true; renderEmu(); }, clockOff()); + if (SESS_KINDS.has(E.extraKind(x))) checkInto(d, t('emuSess'), t('emuSessHint'), x.sess !== false, (v) => { x.sess = v; state.extrasDirty = true; renderEmu(); }); + if (x.kind === 'tama' || x.kind === 't18') { x.opt = x.opt || { vol: 0, dim: 0, off: 0 }; optInto(d, x.opt, () => { state.extrasDirty = true; renderEmu(); }); } + if (x.kind === 'tama' && (x.dev === '4u' || x.dev === '4u-plain')) checkInto(d, t('emuNfc'), t('emuNfcHint'), x.nfc !== false, (v) => { x.nfc = v; state.extrasDirty = true; renderEmu(); }); + if (E.PACK_OPT && x.kind === 'tama') checkInto(d, t('emuPack'), t('emuPackHint'), !!x.pack, (v) => { x.pack = v; state.extrasDirty = true; renderEmu(); }); // 1.7.3 test20 + if (go) { figsInto(d, i); t7GpInto(d, i); linkInto(d, 'pairHintT7'); } + if (big) dlcInto(d, i); + if (x.kind === 'tama' && IR_HINT[x.dev]) linkInto(d, IR_HINT[x.dev]); + if (x.kind === 'v1' && E.v1Name(x.rom).startsWith('DIGIMON')) linkInto(d, 'pairHintDigi'); + if (x.kind === 'v1' && E.v3Detect(x.rom)) linkInto(d, 'pairHintV3'); + if (x.kind === 't18') { t18ItemsInto(d, i); t18BridgeInto(d); } + }; + row('x' + i, E.extraName(x), xMain ? tagMain : t('progMenu'), xMain ? 'main' : '', b, det); + }; + const xFirst = lp && state.mainPick && state.mainPick !== 'emu' ? (state.extras || []).indexOf(state.mainPick) : -1; + if (xFirst >= 0) xRow(state.extras[xFirst], xFirst); + if (em) { + const nm = emuNm(em); + const b = [], go = em.t7 && E.t7Kind(em.rom) === 'go', big = !em.t7 && !em.t18 && !em.v1 && DLC_DEV.includes(em.dev); + if (go) b.push([t('t7FigPick') + (em.figs.length ? ' (' + em.figs.length + ')' : ''), () => { state.figT = 'main'; $('fileT7Fig').click(); }]); + if (big) b.push([t('dlcPick'), () => { state.dlcT = 'main'; $('fileDlc').click(); }]); + const emMain = lp && state.mainPick === 'emu'; + b.push(lp ? star(emMain, 'emu') : dm ? ['☆', null, t('progNoMainDoom'), 'pstar', true] : ['★', null, t('progIsMain'), 'pstar on', true]); + b.push(['×', undo, t('progUndo')]); + row('main', nm, dm ? (emMain ? tagMain : t('progMenu')) + ' · ' + t('stNew') : em.kept ? tagMain : tagMain + ' · ' + t('stNew'), dm && !emMain ? '' : 'main', b, (d) => { mainSet(d, em.dev); if (go) { figsInto(d, 'main'); linkInto(d, 'pairHintT7'); } if (big) dlcInto(d, 'main'); if (!em.t7 && !em.t18 && !em.v1 && IR_HINT[em.dev]) linkInto(d, IR_HINT[em.dev]); if (em.v1 && E.v3Detect(em.rom)) linkInto(d, 'pairHintV3'); if (em.t18) { t18ItemsInto(d, 'main'); t18PicsInto(d); t18BridgeInto(d); } }); + } else if (has && !state.emuRemove) { + const nm = (F.embedded() && F.feldApps(state.ctx.rom, F.embedded().stub).name0) || mainName(state.ctx.rom) || 'EMU'; + const b = [], c7 = F.emuType(state.ctx.rom) === 't7' && E.t7Cfg(state.ctx.rom), go = c7 && c7.romLen !== 0xC0000, cfg = romEmuCfg(state.ctx.rom), big = cfg && DLC_DEV.includes(cfg.dev); + if (go) b.push([t('t7FigPick') + (c7.figs.length ? ' (' + c7.figs.length + ')' : ''), () => { state.figT = 'main'; $('fileT7Fig').click(); }]); + if (big) b.push([t('dlcPick'), () => busy(async () => { if (await mainGuestLoad()) { state.dlcT = 'main'; $('fileDlc').click(); } })]); + b.push(['★', null, t('progIsMain'), 'pstar on', true]); + b.push(['×', () => { state.emu = null; state.emuRemove = true; renderEmu(); }, t('emuOff')]); + row('main', nm, tagMain, 'main', b, (d) => { + mainSet(d, cfg ? cfg.dev : F.emuType(state.ctx.rom)); + if (go) { figsInto(d, 'main'); t7GpInto(d, 'main'); linkInto(d, 'pairHintT7'); } + if (cfg && IR_HINT[cfg.dev]) linkInto(d, IR_HINT[cfg.dev]); + if (F.emuType(state.ctx.rom) === 't18') { t18ItemsInto(d, 'main'); t18PicsInto(d); t18BridgeInto(d); } + if (big) { if (state.mainGuest) dlcInto(d, 'main'); else { const w = document.createElement('div'); w.className = 'hint'; w.textContent = t('dlcLoading'); d.appendChild(w); busy(async () => { await mainGuestLoad(); renderEmu(); }); } } + }); + } else if (has && state.emuRemove && !state.paraMainTaken) { + const nm = (F.embedded() && F.feldApps(state.ctx.rom, F.embedded().stub).name0) || mainName(state.ctx.rom) || 'EMU'; + row('main', nm, t('progGone'), 'main gone', [['↺', undo, t('progUndo')]]); + } + // further programs (started from the menu): each with its own clock setting; 1.7.2 test4: the main one first + (state.extras || []).forEach((x, i) => { if (i !== xFirst) xRow(x, i); }); + if (!box.children.length) { const d = document.createElement('span'); d.className = 'hint'; d.textContent = t('progNone'); box.appendChild(d); } + else if ((state.extras || []).length && !menuWanted()) { const d = document.createElement('span'); d.className = 'hint'; d.textContent = t('appNeedMenu'); box.appendChild(d); } +} +/* 1.6.8: choose which program is the main one (A and C, or the first entry of the start device) */ +/* does a program in the menu come from an older Studio? (vectors and code differ from the program in this one) */ +/* test24 EXIT_KEY: how to go back from a program, for all of them (tab Menu): "EX" << 16 | mode in the last word of + * each program's vector table (IRQ 63, never used); 0 = as before (the word stays the program's own). */ +const EXIT_KEY = true, EXIT_AT = 0x13C, EXIT_MAGIC = 0x5845; +function exitOffs(rom) { + const offs = F.isClean(rom) ? [] : [0xA0000]; try { for (const x of romExtras(rom)) offs.push(x.off); } catch (e) {} + return offs.filter((o) => { const w = rd32(rom, o + EXIT_AT); return (w >>> 16) === EXIT_MAGIC || (w === rd32(rom, o + EXIT_AT - 4) && (w & 1) && w < 0x10000); }); +} +function exitGet(rom) { for (const o of exitOffs(rom)) { const w = rd32(rom, o + EXIT_AT); if ((w >>> 16) === EXIT_MAGIC) return w & 3; } return 0; } +function exitSet(rom, mode) { + let out = rom; + for (const o of exitOffs(rom)) { + const w = mode ? ((EXIT_MAGIC << 16) | mode) >>> 0 : rd32(rom, o + EXIT_AT - 4); + if (rd32(out, o + EXIT_AT) === w) continue; + if (out === rom) out = new Uint8Array(rom); + out[o + EXIT_AT] = w & 255; out[o + EXIT_AT + 1] = (w >>> 8) & 255; out[o + EXIT_AT + 2] = (w >>> 16) & 255; out[o + EXIT_AT + 3] = (w >>> 24) & 255; + } + return out; +} +function extrasOld(rom, apps) { + const up = new Set(); + try { + const progs = { t7: E.t7Embedded(), tama: E.embedded() && E.embedded().app, t18: E.t18Embedded(), v1: E.v1Embedded(), gb: E.gbEmbedded(), sms: E.smsEmbedded(), pm: E.pmEmbedded(), ab: E.abEmbedded() }; // 1.7.3 test5: ArduboyEmu too + for (const x of E.appsRead(rom, apps)) { + const k = E.extraKind(x), img = k === 't18' ? null : k === 'v1' && E.v3Detect(x.rom) ? E.v3Embedded() : k === 'gb' && E.gbIsColor(x.rom) ? E.gbcEmbedded() : progs[k]; if (!img) continue; // 1.7.2: Game Boy Color games against GBCEmu // T18Emu: its image is patched all over; test4: V3Emu against its own program + const at = x.off, same = (a, z) => { for (let i = a; i < z; i++) if (rom[at + i] !== img[i]) return false; return true; }; + if (!same(0, EXIT_AT) || !same(0x800, Math.min(img.length, 0x10000))) up.add(groupKind({ kind: k })); + } + } catch (e) { return false; } + return up.size ? up : false; // 1.7.3 test6: the groups (chips) whose program is older +} +/* 1.6.8: choosing or dropping an emulator does not bring back a DOOM the user took out (emuRemove means "take the + * program at 0x0A0000 out", which is DOOM when DOOM is built in) */ +function emuRemoveClear() { if (!doomInstalled()) state.emuRemove = false; } +/* 1.6.9 test13: the Studio's menu program knows the main program out of its list (version 9) */ +function mainV9() { const fe = F.embedded(); if (!fe) return false; const f = fe.feld; for (let i = 0; i + 8 <= f.length; i += 4) if ((f[i] | f[i + 1] << 8 | f[i + 2] << 16 | f[i + 3] << 24) >>> 0 === 0x444C4546) return (f[i + 4] | f[i + 5] << 8) >= 9; return false; } +function doomMain() { if (doomFree()) return false; return !!state.doom || (doomInstalled() && !state.emuRemove && (!!state.launch || !state.emu)); } +/* 1.7.2 test3 DOOM_FREE: without the Paradise DOOM is a program of the menu like the others: placed anywhere, any program + * can be the main one (star) and start when switched on. The DOOM tab's WAD, or the DOOM of a start device with the + * Paradise, become an entry of the list. */ +const DOOM_FREE = true; +const DOOM_EPS = true; +const DOOM_E4 = true; +const PWAD_ON = true; // 1.7.3 test17: extra WADs (Sigil as its own entry, map packs merged) // 1.7.3 test14: Ultimate DOOM, episode 4 +const DOOM_WHOLE = true; // 1.7.3 test15: without the Paradise the whole WAD as one entry (the DOOM program reaches a WAD over 8 MB) +const DOOM_WHOLE_REGION = 0xA0000; // level data room of the whole WAD (a cache: what does not fit is read from the WAD; 640 KB so that DOOM II fits) +const DOOM_MUSSZ = true; // 1.7.3 test14: the sizes and the room follow the music box +/** Size of one episode as it will be written: with music if ticked and it fits */ +function doomEpSize(f) { return !f ? 0 : DOOM_MUSSZ && $('doomMusic').checked && f.music ? f.sizeM : f.sizeP; } // 1.7.3 test12: without the Paradise several DOOM episodes, each its own menu entry +/* test18: what the DOOM chip of the overview says: the episodes, the own entries of extra WADs (Sigil) and the map packs + * in it (one-humanity) */ +function doomChip(d) { + const sel = d.ok.filter((e) => d.sel.has(e)), base = sel.filter((e) => !'PQ'.includes(e[0])), own = sel.filter((e) => 'PQ'.includes(e[0])).map((e) => (d.titles || {})[e]); + const main = d.d2 ? (DOOM_WHOLE && d.whole ? 'DOOM II' : '') : (DOOM_WHOLE && d.whole ? 'E' + d.eps.join(', E') : base.length ? 'E' + base.join(', E') : ''); + const packs = (d.pwads || []).filter((p) => !p.info.eps.length).map((p) => p.info.title); + return [main && packs.length && (d.whole || base.length) ? main + ' (' + packs.join(', ') + ')' : main].concat(own).filter(Boolean).join(', '); +} +function doomFree() { return DOOM_FREE && !!state.clean; } +function doomXs() { return (state.extras || []).filter((x) => x.kind === 'doom'); } +function doomMcuOf(x) { + const d = x.wadSrc; if (!d) return x.mcu || null; + const f = d.fit[x.ep || $('doomEp').value] || (x.ep !== 'all' && d.fit[d.ok[0]]); if (!f || !f.plain) return null; // 1.7.3 test12: x.ep (several episodes) + return $('doomMusic').checked && f.music ? f.mcuM : f.mcuP; +} +function doomParaX(src) { + const len = rd32(src, D.WAD_OFF); if (!len || len > D.REGION_OFF - D.WAD_OFF - 4) return null; + const keys = D.doomKeysGet(src) || Object.assign({}, D.KEYS_DEFAULT); + return { kind: 'doom', mcu: src.slice(D.WAD_OFF + 4, D.WAD_OFF + 4 + len), keys, keys0: JSON.stringify(keys), save: src.slice(D.SAVE_OFF, D.SAVE_END), fromPara: true }; +} +/* 1.7.2 test4: the main program of a start device with the Paradise (at 0x0A0000) becomes an entry of the list too, so + * there is only one star: it keeps it until another program gets it */ +async function paraMainSync() { + if (!DOOM_FREE) return; + if (!doomFree()) { + if (state.paraMainTaken) { if (state.mainPick && state.mainPick.fromParaMain) state.mainPick = null; state.extras = (state.extras || []).filter((x) => !x.fromParaMain); state.emuRemove = false; state.paraMainTaken = false; } + return; + } + if (state.ctx.clean || state.paraMainTaken || state.emu || state.emuRemove || !emuInstalled()) return; + const x = await installedX(state.ctx.rom); if (!x) return; + Object.assign(x, { fromParaMain: true, clock: state.emuClock !== false, nfc: state.emuNfc !== false, opt: state.emuOpt, sess: state.emuSess !== false }); + state.extras.unshift(x); if (!state.mainPick) state.mainPick = x; + state.emuRemove = true; state.paraMainTaken = true; state.extrasDirty = true; +} +function doomFreeSync() { + if (!DOOM_FREE) return; + if (!doomFree()) { // back to the Paradise: DOOM of the DOOM tab or of the start device as before + const out = (x) => x.fromPara || x.wadSrc; + if (state.mainPick && state.mainPick.kind === 'doom' && out(state.mainPick)) state.mainPick = null; + state.extras = (state.extras || []).filter((x) => !out(x)); return; + } + const old = doomXs(), wasMain = old.includes(state.mainPick); + if (state.doom && DOOM_EPS && state.doom.sel) { // 1.7.3 test12: each chosen episode its own entry in the menu + const d = state.doom, want = (DOOM_WHOLE && d.whole ? ['all'] : d.ok.filter((e) => d.sel.has(e) && !'PQ'.includes(e[0]))).concat(d.ok.filter((e) => 'PQ'.includes(e[0]) && d.sel.has(e))), gone = old.filter((x) => x.wadSrc !== d); + // a new WAD replaces the DOOM of the ROM (as before); a save of the same episode (menu name "DOOM E2") goes along + for (const x of old) if (x.wadSrc !== d || !want.includes(x.ep)) { if (state.mainPick === x) state.mainPick = null; state.extras.splice(state.extras.indexOf(x), 1); state.extrasDirty = true; } + for (const e of want) if (!doomXs().some((x) => x.wadSrc === d && x.ep === e)) { + const x = { kind: 'doom', wadSrc: d, ep: e, size: (DOOM_MUSSZ ? doomEpSize(d.fit[e]) : (d.fit[e] || {}).sizeP) || 0x300000, keys: Object.assign({}, state.doomKeys || D.KEYS_DEFAULT) }; + if (e === 'all') { x.region = DOOM_WHOLE_REGION; if (d.d2) x.d2 = true; } + if ('PQ'.includes(e[0])) x.title = (d.titles || {})[e] || 'DOOM'; + const prev = gone.find((g) => g.name === (e === 'all' ? (d.d2 ? 'DOOM II' : 'DOOM') : 'PQ'.includes(e[0]) ? x.title : 'DOOM E' + e)); if (prev && prev.save) x.save = prev.save; + const i = state.extras.findIndex((y) => y.kind === 'doom' && y.wadSrc === d && y.ep > e && !'PQ'.includes(e[0])); + state.extras.splice(i >= 0 ? i : state.extras.length, 0, x); state.extrasDirty = true; + if (wasMain && !doomXs().includes(state.mainPick)) state.mainPick = x; + } + if (wasMain && !state.mainPick && doomXs().length) state.mainPick = doomXs()[0]; // the star stays with DOOM + } else if (state.doom && !old.some((x) => x.wadSrc === state.doom)) { + const f = state.doom.fit[state.doom.ok[0]] || {}; + const x = { kind: 'doom', wadSrc: state.doom, size: f.sizeP || 0x300000, keys: Object.assign({}, state.doomKeys || D.KEYS_DEFAULT) }; + const i = state.extras.findIndex((y) => y.kind === 'doom'); + state.extras = state.extras.filter((y) => y.kind !== 'doom'); state.extras.splice(i >= 0 ? i : state.extras.length, 0, x); + if (wasMain) state.mainPick = x; + state.extrasDirty = true; + } else if (!state.doom && !state.ctx.clean && doomInstalled() && !state.emuRemove && !old.length) { + const x = doomParaX(state.ctx.rom); + if (x) { state.extras.push(x); if (!state.mainPick) state.mainPick = x; state.extrasDirty = true; } // it was the main program (shown first while it has the star) + } +} +function curMainX() { + const em = state.emu; + if (em) return emuX(em); + return null; +} +function canMain(x) { + if (x.kind === 'gb' || x.kind === 'sms' || x.kind === 'pm' || x.kind === 'ab' || x.kind === 'wolf') return false; // 1.6.9 test36: GBEmu only in the menu (and Wolf3D) + // outside a start device only T7Emu goes to the menu, so the old main program must be a T7Emu (or none) + if (state.launch) return true; + if (!a0Free()) return false; // test25: no main program at 0x0A0000 in this edition + const em = state.emu, ty = em ? (em.v1 ? 'v1' : em.t7 ? 't7' : em.t18 ? 't18' : 'tama') : (emuInstalled() && !state.emuRemove ? F.emuType(state.ctx.rom) : null); + return !ty || ty === 't7' || ty === 'v1'; +} +async function makeMain(i) { + const x = state.extras[i]; if (!x) return; + let old = curMainX(); + if (!old && emuInstalled() && !state.emuRemove) old = await installedX(state.ctx.rom); + let em; + if (x.kind === 't18') { let n = 0; for (let k = 0; k < 128; k++) if (!x.fw.subarray(k << 16, (k + 1) << 16).every((v) => v === 0xFF)) n++; em = { t18: true, dev: 't18', rom: x.fw, size: n << 16 }; } + else if (x.kind === 'tama') { const pk = E.packMain(x.guest, x.dev, null, !!state.emuPack); em = { guest: x.guest, dev: x.dev, size: pk.blob.length, big: pk.big }; } + else if (x.kind === 'v1') em = { v1: true, dev: 'v1', rom: x.rom, size: x.rom.length + 0x2000 }; + else { em = { t7: true, dev: 't7', rom: x.rom, figs: x.figs || [] }; em.size = t7Size(em); } + state.extras.splice(i, 1); + if (old) old.opt = state.emuOpt; + state.emuOpt = x.opt || { vol: 0, dim: 0, off: 0 }; + // outside a start device only T7Emu and V1Emu go to the menu; another main program is replaced + if (old && !state.launch && (old.kind === 'tama' || old.kind === 't18')) { toast(t('progReplaced', { n: E.extraName(x), o: E.extraName(old) })); old = null; } + if (old) state.extras.unshift(old); + state.emu = em; emuRemoveClear(); state.extrasDirty = true; state.t7saveX = null; state.progOpen = new Set(); state.dlcT = 'main'; state.figT = 'main'; state.mainGuest = null; + if (!state.launch) state.doom = null; + if (!x.fresh) toast(t('progMainNow', { n: E.extraName(x) })); + renderDoom(); renderEmu(); +} +/* test17: the star in a start device: only if it still fits, otherwise the old order stays */ +async function mainChecked(i) { + if (!ROOM_AUTO || !state.launch) return makeMain(i); + const snap = { emu: state.emu, extras: state.extras.slice(), emuRemove: state.emuRemove, mainPick: state.mainPick, emuOpt: state.emuOpt, mainGuest: state.mainGuest }; + await makeMain(i); + const m = await roomTry(); + if (m.k || m.err) { Object.assign(state, snap); state.extras = snap.extras.slice(); state.extrasDirty = true; renderDoom(); renderEmu(); toast(m.k ? t('mainNoRoom', { k: m.k }) : t('appFail', { e: m.err }), true); } +} +/* 1.6.8: the main program (state.emu) in the form of a further program, its name; the installed one read from the ROM */ +function emuX(em) { return !em ? null : em.v1 ? { kind: 'v1', rom: em.rom } : em.t18 ? { kind: 't18', fw: em.rom } : em.t7 ? { rom: em.rom, figs: em.figs } : { kind: 'tama', guest: em.guest, dev: em.dev }; } +function emuNm(em) { return em.v1 ? E.v1Name(em.rom) : em.t7 ? E.t7XName(em.rom) : em.t18 ? E.extraName({ kind: 't18' }) : E.tamaName(em.guest, em.dev); } +async function installedX(r0) { + const ty = F.emuType(r0); + if (ty === 't7') { const c7 = E.t7FromRom(r0); return c7 ? { rom: c7.rom, figs: c7.figs } : null; } + if (ty === 't18') { const fw = E.t18FromRom(r0); return fw ? { kind: 't18', fw } : null; } + if (ty === 'v1') { const r = E.v1FromRom(r0); return r ? { kind: 'v1', rom: r } : null; } + const cfg = romEmuCfg(r0); return cfg ? { kind: 'tama', guest: await SV.emuGuestAsync((a, n) => r0.subarray(a, a + n), cfg), dev: cfg.dev } : null; +} +function hasOldSave() { return typeof state.dlcT === 'number' ? !!state.extras[state.dlcT] && !state.extras[state.dlcT].fresh : !!(state.emu && state.emu.kept) || !!state.mainGuest; } +$('btnApp').onclick = () => $('fileApp').click(); +$('fileApp').onchange = async (e) => { + const f = e.target.files[0]; e.target.value = ''; if (!f) return; + await addExtra(new Uint8Array(await f.arrayBuffer()), f.name); +}; +/* 1.6.8: trial build of the ROM as it would be saved now; KB missing for the programs, 0 if they fit */ +let lastRoom = 0, lastFree = -1; +async function roomMissing() { + const m = await roomTry(); return m.k; +} +/* test17 ROOM_AUTO: a trial build that also reports other failures (before: "T18Emu needs 0x0F0000" counted as + * fitting when adding and only came up when writing), and the room really left afterwards */ +const ROOM_AUTO = true; +async function roomTry() { + lastRoom = 0; lastFree = -1; const mute = toast.mute = {}; + let ok = false; + try { ok = !!(await composeRom()); } catch (e) { mute.err = em(e); } finally { toast.mute = null; } + if (ok && lastFree >= 0) state.roomFree = { sig: roomSig(), kb: lastFree }; + return { k: lastRoom, err: !ok && !lastRoom ? (mute.err || '?') : '' }; +} +/* which programs are in, and which one is the main one (the overview's real free room belongs to that) */ +/* 1.7.2 ROOM_FIGS: figures and the firmware data (download content) change the room too, not only the program list */ +const ROOM_FIGS = true, roomIds = new WeakMap(); let roomIdN = 0; +function roomId(a) { if (!a || typeof a !== 'object') return 0; if (!roomIds.has(a)) roomIds.set(a, ++roomIdN); return roomIds.get(a); } +function roomCont(x) { return !x ? '' : [(x.figs || []).reduce((n, f) => n + ((f.data && f.data.length) || f.len || 0), 0) + '/' + (x.figs || []).length, roomId(x.guest), roomId(x.rom), roomId(x.fw)].join(':'); } +function roomSig() { return JSON.stringify([state.emu ? emuNm(state.emu) : '', !!state.emuRemove, !!state.doom, !!state.launch, (state.extras || []).map((x) => E.extraName(x))].concat(DOOM_MUSSZ && state.doom ? [$('doomMusic').checked] : []).concat(ROOM_FIGS ? [roomCont(state.emu), (state.extras || []).map(roomCont)] : [])); } +/* test17: in a start device the first program (at 0x0A0000) changes how much room the others need (TamaEmu and + * T18Emu use the fixed areas there, T18Emu's part at 0x0F0000 is fixed). When the choice does not fit, every other + * program is tried as the first one; the smallest shortfall of all is the one reported, so the message is the same + * whatever order the programs were added in. */ +/* test25 T18_FEW: T18Emu takes 10 spare blocks and a TamaEmu in the menu 576 KB for spare pages when they can; when the + * programs do not fit then (T18Emu with iD L in the menu was 256 KB short), it is tried again with 6 blocks for T18Emu + * and 256 KB for each TamaEmu (as the main TamaEmu has), T18Emu's blocks into the small gaps first (a TamaEmu needs one + * piece), before saying "no room" */ +const T18_FEW = true, T18_FEW_N = 6; +const HI_ORPHAN = true; +function t18Here() { return !!(state.emu && (state.emu.t18 || state.emu.guest)) || (state.extras || []).some((x) => E.extraKind(x) === 't18' || E.extraKind(x) === 'tama') || (emuInstalled() && /t18|tama/.test(F.emuType(state.ctx.rom))); } +async function roomFit() { + const r = await roomFit1(); + if (!T18_FEW || !r.k || state.t18Few || !t18Here()) return r; + state.t18Few = true; + const r2 = await roomFit1(); + if (!r2.k && !r2.err) return r2; + state.t18Few = false; return r; +} +async function roomFit1() { + const m0 = await roomTry(); if (!m0.k && !m0.err) return { k: 0 }; + if (!ROOM_AUTO || !state.launch) return { k: m0.k }; // outside a start device only the room counts (the menu may still be off) + if (doomMain() || state.clean) return m0; + const snap = { emu: state.emu, extras: state.extras.slice(), emuRemove: state.emuRemove, mainPick: state.mainPick, emuOpt: state.emuOpt, mainGuest: state.mainGuest, progOpen: state.progOpen }; + const back = () => { Object.assign(state, snap); state.extras = snap.extras.slice(); state.extrasDirty = true; }; + let best = m0.k || Infinity, err = m0.err; + const names = snap.extras.map((x) => E.extraName(x)); + for (let i = 0; i < snap.extras.length; i++) { + if (!canMain(snap.extras[i])) continue; + back(); toast.mute = {}; try { await makeMain(i); } finally { toast.mute = null; } + const m = await roomTry(); + if (!m.k && !m.err) { toast(t('mainAuto', { n: names[i] })); renderEmu(); return { k: 0 }; } + if (m.k && m.k < best) best = m.k; + } + back(); renderEmu(); + return best < Infinity ? { k: best } : { k: 0, err }; +} +async function addExtra(g, fname, preset) { + let x = preset || null; + if (x) { /* 1.7.3: made by its tab (Arduboy) */ } + else if (E.gbDetect(g)) { if (E.gbColorOnly(g) && !E.gbIsColor(g)) { toast(t('gbColor', { f: fname }), true); return; } x = { kind: 'gb', rom: g, keys: gbKeysNow().slice(), inv: state.gbInv !== false }; } // 1.6.9 test36: GBEmu + else if (E.pmDetect(g)) x = { kind: 'pm', rom: g, title: E.pmTitle(fname), keys: pmKeysNow().slice(), inv: state.pmInv !== false, bios: state.pmBios || null }; // 1.7.3 PokeMiniEmu + else if (E.smsDetect(g, fname)) x = { kind: 'sms', rom: g, title: E.smsTitle(fname), gg: E.smsGameGear(g, fname), keys: smsKeysNow().slice(), inv: state.smsInv !== false }; // 1.6.10 test2: SMSEmu + else if (E.v1Detect(g)) x = { kind: 'v1', rom: g }; // 1.6.8: V1Emu (first Tamagotchis, Digital Monster) + else if (E.t7Detect(g)) x = { rom: g }; + else if (E.t18Detect(g)) x = { kind: 't18', fw: g }; + else { try { const dev = E.emuDetect(g); try { E.packGuest(g, dev); } catch (e1) { E.packGuest(g, dev, { lz: true }); } x = { kind: 'tama', guest: g, dev }; } catch (err) { x = null; } } + if (!x) { + let main = false; try { main = !!E.t18Detect(g) || (E.emuDetect(g) && true); } catch (err) { main = false; } + toast(t(main && !state.launch ? 'appBadMain' : state.launch ? 'appBadL' : 'appBad', { f: fname }), true); return; + } + state.extras = state.extras || []; + if (state.extras.length >= E.APPX_MAX) { toast(t('appMax'), true); return; } + { let m = curMainX(); if (!m && emuInstalled() && !state.emuRemove) { const r0 = state.ctx.rom, ty = F.emuType(r0); if (ty === 't7') { const c7 = E.t7FromRom(r0); if (c7) m = { rom: c7.rom }; } else if (ty === 't18') { const fw = E.t18FromRom(r0); if (fw) m = { kind: 't18', fw }; } else if (ty === 'v1') { const r = E.v1FromRom(r0); if (r) m = { kind: 'v1', rom: r }; } else if (x.kind === 'tama') { await mainGuestLoad(); if (state.mainGuest) m = { kind: 'tama', guest: state.mainGuest.g, dev: state.mainGuest.dev }; } } if ((m && sameFw(x, m)) || state.extras.some((y) => sameFw(x, y))) { toast(t('appTwice', { n: E.extraName(x) }), true); return; } } // 1.6.8: each program once + if (x.kind === 't18' && (state.extras.some((y) => y.kind === 't18') || (state.emu && state.emu.t18) || (!state.emu && F.emuType(state.ctx.rom) === 't18' && !state.emuRemove))) { toast(t('appT18One'), true); return; } + x.fresh = true; state.extras.push(x); state.extrasDirty = true; state.t7saveX = null; + // test25: no room at 0x0A0000 and no start device: a colour Tama or TG18 cannot go anywhere + if (!state.launch && !a0Free() && (x.kind === 'tama' || x.kind === 't18')) { state.extras = state.extras.filter((y) => y !== x); toast(t('a0NoMain', { f: fname }), true); renderEmu(); return; } + // outside a start device a colour Tama or TG18 only runs as the main program (A and C): it becomes the main one + if (!state.launch && (x.kind === 'tama' || x.kind === 't18')) { busy(() => makeMain(state.extras.length - 1)); return; } + // 1.6.8: does it still fit? A trial build right away, not only when writing + const f = await busy(roomFit), k = f.k; + if (k || f.err) { state.extras = state.extras.filter((y) => y !== x); state.extrasDirty = true; renderEmu(); toast(k ? t('noRoomAdd', { n: E.extraName(x), k }) + (E.PACK_OPT && (state.extras || []).some((y) => y.kind === 'tama' && !y.pack) ? t('packTip') : '') : t('appFail', { e: f.err }), true); return; } + renderEmu(); +} +$('btnT7Fig').onclick = () => $('fileT7Fig').click(); +$('fileT7Fig').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; if (!files.length) return; + const st = figTarget(); if (!st) return; + const xi = typeof state.figT === 'number'; + for (const f of files) { + const raw = new Uint8Array(await f.arrayBuffer()); + if (!E.t7FigDetect(raw)) { toast(t('t7FigBad', { f: f.name }), true); continue; } + const d = E.t7FigData(raw); + if (st.figs.length >= 16) { toast(t('t7FigMax'), true); break; } + if (st.figs.some((x) => E.t7FigName(x.name) === E.t7FigName(f.name))) { toast(t('t7FigDup', { f: E.t7FigName(f.name) }), true); continue; } + if (!xi && E.t7Room(st.figs.concat([{ name: f.name, data: d }]), st.rom.length) < 0) { toast(t('t7FigFull', { f: E.t7FigName(f.name) }), true); continue; } + st.figs = st.figs || []; st.figs.push({ name: f.name, data: d }); + } + if (xi) { state.extrasDirty = true; state.t7saveX = null; renderEmu(); return; } + st.size = t7Size(st); state.emu = st; emuRemoveClear(); if (!state.launch) state.doom = null; + renderDoom(); renderEmu(); +}; +/* Download content of the 8 MB guest firmware: one box per store, every slot with its name */ +function renderDlc() { $('dlcList').innerHTML = ''; } // 1.6.8: the slots are in the program's row +const DLC_ZIP = true; +$('btnDlc').onclick = () => $('fileDlc').click(); +$('fileDlc').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; if (!files.length || !dlcTarget()) return; + let nb0 = -1; try { const t0 = dlcTarget(); nb0 = E.packGuest(t0.guest, t0.dev).blocks; } catch (err) { nb0 = -1; } + // DLC_ZIP (1.7.2 test13): .zip files (as the VDPs come) bring their .jpg files; items for another device stay out + const ents = []; + for (const f of files) { + const d = new Uint8Array(await f.arrayBuffer()); + if (DLC_ZIP && f.name.toLowerCase().endsWith('.zip')) { + try { for (const x of await C.zipRead(d, inflateRaw)) { const nm = x.name.split('/').pop(); if (/\.jpe?g$/i.test(nm)) ents.push({ name: nm, data: x.data, zip: true }); } } + catch (err) { toast(t('dlcBad', { f: f.name, e: em(err) }), true); } + } else ents.push({ name: f.name, data: d }); + } + for (const f of ents) { + try { + const tg = dlcTarget(); + const rec = E.dlcRecord(f.data, tg.dev); + if (f.zip && /^t4u_/.test(String.fromCharCode(...rec.subarray(0x34, 0x3B))) && !/^4u/.test(tg.dev)) continue; + const r = E.dlcAdd(tg.guest, rec); + tg.set(r.guest); + toast(t('dlcOk', { n: E.dlcName(rec), k: t('dlcK' + r.store.kind), s: r.slot + 1 })); + } catch (err) { toast(t('dlcBad', { f: f.name, e: em(err) }), true); } + } + // the first item in a still empty store needs a new block: the emulator's layout changes, its save starts anew + try { const t1 = dlcTarget(); const c0 = state.dlcT === 'main' ? romEmuCfg(state.ctx.rom) : null, relay = !!(c0 && c0.version < 5 && E.packMain(t1.guest, t1.dev, null, !!state.emuPack).lzOff !== undefined); // MAIN_LZ: an older main TamaEmu gets the packed layout + if (((nb0 >= 0 && E.packGuest(t1.guest, t1.dev).blocks !== nb0) || relay) && hasOldSave()) toast(t('dlcNewArea'), true); } catch (err) { /* only a hint */ } + renderEmu(); +}; +$('fileT18Item').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; const T = t18Target(state.itemT); if (!files.length || !T) return; + const recs = []; + for (const f of files) { + try { + const b = new Uint8Array(await f.arrayBuffer()); + if (f.name.toLowerCase().endsWith('.zip')) { const z = await C.zipRead(b, inflateRaw); for (const x of z) recs.push(...E.t18iScan(x.data)); } + else recs.push(...E.t18iScan(b)); + } catch (err) { toast(t('dlcBad', { f: f.name, e: em(err) }), true); } + } + if (!recs.length) { toast(t('t18ItemsNone'), true); return; } + let n = 0; + for (const r of recs) { + if (r.model && r.model !== 'tg18') toast(t('t18ItemsOther', { n: t18Nm(r), m: r.model.toUpperCase() }), true); + try { const x = E.t18ItemAdd(T.fw, r, 1); n++; toast(t('t18ItemOk', { n: t18Nm(r), k: t('t18A_' + x.area) })); } + catch (err) { toast(t('dlcBad', { f: t18Nm(r), e: err.message === 'full' ? t('t18ItemsFull') : em(err) }), true); } + } + if (n) T.set(); + renderEmu(); +}; +$('fileT18Pic').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; if (!files.length) return; + const ents = []; + for (const f of files) { + const b = new Uint8Array(await f.arrayBuffer()); + if (f.name.toLowerCase().endsWith('.zip')) { try { for (const x of await C.zipRead(b, inflateRaw)) ents.push({ name: x.name.split('/').pop(), data: x.data }); } catch (err) { toast(t('dlcBad', { f: f.name, e: em(err) }), true); } } + else ents.push({ name: f.name, data: b }); + } + const byImg = new Map(); // the Android set: erwachsen.json names every picture + // English firmwares (Param block at 0xF800D864) take the pictures of the English ones first, the others the Japanese ones + const fw0 = state.emu && state.emu.t18 ? state.emu.rom : null, pa = fw0 ? E.t18Addrs(fw0).param : (state.ctx.rom[0xA0140 + 428] | state.ctx.rom[0xA0140 + 429] << 8 | state.ctx.rom[0xA0140 + 430] << 16 | state.ctx.rom[0xA0140 + 431] << 24) >>> 0; + const EN = new Set(['34525147dbe95eb512760981a07f5c30', '1a7d362f6f31b637e0a3b34ba6b6d110', '190a9d6801ed709f9a090a74f95039af']), wantEn = !pa || pa === 0xF800D864; + const rank = new Map(); + for (const x of ents) if (/\.json$/i.test(x.name)) { try { const j = JSON.parse(new TextDecoder().decode(x.data)); for (const k in j) for (const a of j[k] || []) if (a.img) { byImg.set(a.img, a.id); rank.set(a.img, EN.has(k) === wantEn ? 0 : 1); } } catch (err) { /* not that file */ } } + ents.sort((a, b) => (rank.has(b.name) ? rank.get(b.name) : 0) - (rank.has(a.name) ? rank.get(a.name) : 0)); // the wanted ones last: they win + state.t18Pics = state.t18Pics || new Map(); let n = 0; + for (const x of ents) { + if (!/\.png$/i.test(x.name)) continue; + const id = byImg.has(x.name) ? byImg.get(x.name) : E.t18AdultFind(x.name); + if (id < 0 || !E.T18_ADULTS.some((a) => a[0] === id)) { toast(t('t18PicsUnknown', { f: x.name }), true); continue; } + try { state.t18Pics.set(id, E.t18PicMake(await pngRgba(x.data))); n++; } catch (err) { toast(t('dlcBad', { f: x.name, e: em(err) }), true); } + } + if (n) { state.t18PicsDirty = true; toast(t('t18PicsOk', { n })); } + renderEmu(); +}; +$('btnEmu').onclick = () => $('fileEmu').click(); +$('fileEmu').onchange = async (e) => { + const f = e.target.files[0]; e.target.value = ''; if (!f) return; + const g = new Uint8Array(await f.arrayBuffer()); + // 1.6.8: one button for everything: the first program is the main one (A and C), every further one goes to the menu + if (E.gbDetect(g)) { await addExtra(g, f.name); renderGb(); return; } + if (E.smsDetect(g, f.name)) { await addExtra(g, f.name); renderSms(); return; } // 1.6.10 test2 // 1.6.9 test36: Game Boy games go to the menu + if (state.emu || (emuInstalled() && !state.emuRemove) || (state.extras || []).length || (E.v1Detect(g) && doomMain()) || !a0Free()) { await addExtra(g, f.name); return; } // test25: no room at 0x0A0000: the menu // the first program stays the main one + if (E.v1Detect(g)) { state.emu = { v1: true, dev: 'v1', rom: g, size: g.length + 0x2000 }; extrasDedupe(null); emuRemoveClear(); if (!state.launch) state.doom = null; renderDoom(); } + else if (E.t18Detect(g)) { + let n = 0; for (let i = 0; i < 128; i++) if (!g.subarray(i << 16, (i + 1) << 16).every((v) => v === 0xFF)) n++; + state.emu = { t18: true, dev: 't18', rom: g, size: n << 16 }; extrasDedupe(null); emuRemoveClear(); if (!state.launch) state.doom = null; renderDoom(); + } else if (E.t7Detect(g)) { + const old = state.emu && state.emu.t7 ? state.emu : t7State(); // the figures stay + const st = { t7: true, dev: 't7', rom: g, figs: old && E.t7Kind(g) === 'go' ? old.figs : [] }; + st.size = t7Size(st); state.emu = st; extrasDedupe(null); emuRemoveClear(); if (!state.launch) state.doom = null; renderDoom(); + } else + try { const dev = E.emuDetect(g); const pk = E.packMain(g, dev, null, !!state.emuPack); state.emu = { guest: g, dev, size: pk.blob.length, big: pk.big }; extrasDedupe(null); emuRemoveClear(); if (!state.launch) state.doom = null; renderDoom(); } + catch (err) { toast(t('emuBad', { e: em(err) }), true); } + renderEmu(); +}; +$('emuAuto').onchange = (e) => { state.emuAuto = e.target.checked; renderEmu(); }; +$('emuClock').onchange = (e) => { state.emuClock = e.target.checked; renderEmu(); }; +$('emuNfc').onchange = (e) => { state.emuNfc = e.target.checked; renderEmu(); }; +$('btnEmuOff').onclick = () => { state.emu = null; state.emuRemove = true; renderEmu(); }; +$('btnEmuUndo').onclick = () => { state.emu = null; emuRemoveClear(); state.t7save = null; renderEmu(); renderDoom(); }; + +// ---------------------------------------------------------------- DOOM +function keySel(id, val, wheel) { + const sel = $(id); sel.innerHTML = ''; + [[1, 'A'], [2, 'B'], [4, 'C']].concat(wheel ? [[8, t('kWheel')]] : []).forEach(([v, l]) => { const o = document.createElement('option'); o.value = v; o.textContent = l; sel.appendChild(o); }); + sel.value = String(val); +} +/* 1.6.9 test36: tab Game Boy. The games go into the menu (GBEmu, kind 'gb' in state.extras); one key layout for all. */ +const GB_BTNS = [[0, 'gbNone'], [1, 'A'], [2, 'B'], [8, 'Start'], [4, 'Select'], [16, 'gbRight'], [32, 'gbLeft'], [64, 'gbUp'], [128, 'gbDown']]; +const GB_INS = ['gbInA', 'gbInB', 'gbInC', 'gbInWp', 'gbInWu', 'gbInWd', 'gbInAC', 'gbInBC', 'gbInAB']; +function gbKeysNow() { if (!state.gbKeys) { const x = (state.extras || []).find((y) => y.kind === 'gb' && y.keys && y.keys.length === 9); state.gbKeys = x ? x.keys.slice() : E.GB_KEYS_DEFAULT.slice(); state.gbInv = x ? !!x.inv : true; } return state.gbKeys; } // 1.6.10 test1: wheel reversed by default +function gbKeysApply() { for (const x of state.extras || []) if (x.kind === 'gb') { x.keys = state.gbKeys.slice(); x.inv = !!state.gbInv; } state.extrasDirty = true; renderPlan(); } +function renderGb() { + if (!$('gbList')) return; + const xs = (state.extras || []).map((x, i) => [x, i]).filter(([x]) => x.kind === 'gb'); + const box = $('gbList'); box.innerHTML = ''; + if (!xs.length) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('gbNone2'); box.appendChild(d); } + for (const [x, i] of xs) { + const r = document.createElement('div'); r.className = 'dlcrow'; + const n = document.createElement('span'); n.className = 'itemname'; n.textContent = E.extraName(x) + ' (' + (x.rom.length >> 10) + ' KB)'; + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = '×'; b.title = t('progDel'); + b.onclick = () => { state.extras.splice(i, 1); state.extrasDirty = true; renderEmu(); }; + r.append(n, b); box.appendChild(r); + } + if (xs.length && !menuWanted()) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('appNeedMenu'); box.appendChild(d); } + const k = gbKeysNow(), g = $('gbKeyGrid'); g.innerHTML = ''; + GB_INS.forEach((nm, i) => { + const l = document.createElement('label'); const sp = document.createElement('span'); sp.textContent = t(nm); + const sel = document.createElement('select'); + for (const [v, tn] of GB_BTNS) { const o = document.createElement('option'); o.value = String(v); o.textContent = tn.startsWith('gb') ? t(tn) : tn; sel.appendChild(o); } + sel.value = String(GB_BTNS.some(([v]) => v === k[i]) ? k[i] : 0); + sel.onchange = () => { state.gbKeys[i] = +sel.value; gbKeysApply(); renderGb(); }; + l.append(sp, sel); g.appendChild(l); + }); + $('gbInv').checked = !!state.gbInv; + const used = new Set(k.filter((v) => v)); const miss = [[1, 'A'], [2, 'B'], [8, 'Start']].filter(([v]) => !used.has(v)).map(([, n]) => n); + $('gbKeysStat').textContent = miss.length ? t('gbKeysMiss', { n: miss.join(', ') }) : ''; +} +$('btnGb').onclick = () => { if (!state.ctx) { toast(t('gbNeedRom'), true); return; } $('fileGb').click(); }; +$('fileGb').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; + for (const f of files) { + const g = new Uint8Array(await f.arrayBuffer()); + if (!E.gbDetect(g)) { toast(t('gbBad', { f: f.name }), true); continue; } + await addExtra(g, f.name); + } + renderGb(); +}; +$('gbInv').onchange = () => { gbKeysNow(); state.gbInv = $('gbInv').checked; gbKeysApply(); }; +$('btnGbKeysDef').onclick = () => { state.gbKeys = E.GB_KEYS_DEFAULT.slice(); state.gbInv = true; gbKeysApply(); renderGb(); }; +/* 1.6.10 test2: tab Master System. As the Game Boy: the games go into the menu (SMSEmu, kind 'sms'); one key layout. */ +const SMS_BTNS = [[0, 'gbNone'], [16, 'smsB1'], [32, 'smsB2'], [64, 'smsPause'], [8, 'gbRight'], [4, 'gbLeft'], [1, 'gbUp'], [2, 'gbDown']]; +function smsKeysNow() { if (!state.smsKeys) { const x = (state.extras || []).find((y) => y.kind === 'sms' && y.keys && y.keys.length === 9); state.smsKeys = x ? x.keys.slice() : E.SMS_KEYS_DEFAULT.slice(); state.smsInv = x ? !!x.inv : true; } return state.smsKeys; } +function smsKeysApply() { for (const x of state.extras || []) if (x.kind === 'sms') { x.keys = state.smsKeys.slice(); x.inv = !!state.smsInv; } state.extrasDirty = true; renderPlan(); } +function renderSms() { + if (!$('smsList')) return; + const xs = (state.extras || []).map((x, i) => [x, i]).filter(([x]) => x.kind === 'sms'); + const box = $('smsList'); box.innerHTML = ''; + if (!xs.length) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('gbNone2'); box.appendChild(d); } + for (const [x, i] of xs) { + const r = document.createElement('div'); r.className = 'dlcrow'; + const n = document.createElement('span'); n.className = 'itemname'; n.textContent = E.extraName(x) + ' (' + (x.rom.length >> 10) + ' KB)'; + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = '×'; b.title = t('progDel'); + b.onclick = () => { state.extras.splice(i, 1); state.extrasDirty = true; renderEmu(); }; + r.append(n, b); box.appendChild(r); + } + if (xs.length && !menuWanted()) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('appNeedMenu'); box.appendChild(d); } + const k = smsKeysNow(), g = $('smsKeyGrid'); g.innerHTML = ''; + GB_INS.forEach((nm, i) => { + const l = document.createElement('label'); const sp = document.createElement('span'); sp.textContent = t(nm); + const sel = document.createElement('select'); + for (const [v, tn] of SMS_BTNS) { const o = document.createElement('option'); o.value = String(v); o.textContent = t(tn); sel.appendChild(o); } + sel.value = String(SMS_BTNS.some(([v]) => v === k[i]) ? k[i] : 0); + sel.onchange = () => { state.smsKeys[i] = +sel.value; smsKeysApply(); renderSms(); }; + l.append(sp, sel); g.appendChild(l); + }); + $('smsInv').checked = !!state.smsInv; + const used = new Set(k.filter((v) => v)); const miss = [[16, t('smsB1')], [32, t('smsB2')]].filter(([v]) => !used.has(v)).map(([, n]) => n); + $('smsKeysStat').textContent = miss.length ? t('gbKeysMiss', { n: miss.join(', ') }) : ''; +} +$('btnSms').onclick = () => { if (!state.ctx) { toast(t('gbNeedRom'), true); return; } $('fileSms').click(); }; +$('fileSms').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; + for (const f of files) { + const g = new Uint8Array(await f.arrayBuffer()); + if (!E.smsDetect(g, f.name)) { toast(t('smsBad', { f: f.name }), true); continue; } + await addExtra(g, f.name); + } + renderSms(); +}; +$('smsInv').onchange = () => { smsKeysNow(); state.smsInv = $('smsInv').checked; smsKeysApply(); }; +$('btnSmsKeysDef').onclick = () => { state.smsKeys = E.SMS_KEYS_DEFAULT.slice(); state.smsInv = true; smsKeysApply(); renderSms(); }; +/* 1.7.3: tab Pokemon mini. As the Master System: the games go into the menu (PokeMiniEmu, kind 'pm'); one key layout; + * an own BIOS (optional) for all of them, else PokeMini's free one. Games also in .zip files. */ +const PM_BTNS = [[0, 'gbNone'], [1, 'pmA'], [2, 'pmB'], [4, 'pmC'], [64, 'gbRight'], [32, 'gbLeft'], [8, 'gbUp'], [16, 'gbDown'], [128, 'pmPower'], [256, 'pmShake']]; +function pmKeysNow() { if (!state.pmKeys) { const x = (state.extras || []).find((y) => y.kind === 'pm' && y.keys && y.keys.length === 9); state.pmKeys = x ? x.keys.slice() : E.PM_KEYS_DEFAULT.slice(); state.pmInv = x ? !!x.inv : true; } return state.pmKeys; } +function pmKeysApply() { for (const x of state.extras || []) if (x.kind === 'pm') { x.keys = state.pmKeys.slice(); x.inv = !!state.pmInv; } state.extrasDirty = true; renderPlan(); } +function pmBiosNow() { if (state.pmBios === undefined) { const x = (state.extras || []).find((y) => y.kind === 'pm' && y.bios); state.pmBios = x ? x.bios : null; } return state.pmBios; } +function pmBiosApply() { for (const x of state.extras || []) if (x.kind === 'pm') x.bios = state.pmBios || null; state.extrasDirty = true; renderPlan(); } +function renderPm() { + if (!$('pmList')) return; + const xs = (state.extras || []).map((x, i) => [x, i]).filter(([x]) => x.kind === 'pm'); + const box = $('pmList'); box.innerHTML = ''; + if (!xs.length) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('gbNone2'); box.appendChild(d); } + for (const [x, i] of xs) { + const r = document.createElement('div'); r.className = 'dlcrow'; + const n = document.createElement('span'); n.className = 'itemname'; n.textContent = E.extraName(x) + ' (' + (x.rom.length >> 10) + ' KB)'; + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = '×'; b.title = t('progDel'); + b.onclick = () => { state.extras.splice(i, 1); state.extrasDirty = true; renderEmu(); }; + r.append(n, b); box.appendChild(r); + } + if (xs.length && !menuWanted()) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('appNeedMenu'); box.appendChild(d); } + const bios = pmBiosNow(); $('pmBiosStat').textContent = t(bios ? 'pmBiosOwn' : 'pmBiosFree'); $('btnPmBiosDel').hidden = !bios; + const k = pmKeysNow(), g = $('pmKeyGrid'); g.innerHTML = ''; + GB_INS.forEach((nm, i) => { + const l = document.createElement('label'); const sp = document.createElement('span'); sp.textContent = t(nm); + const sel = document.createElement('select'); + for (const [v, tn] of PM_BTNS) { const o = document.createElement('option'); o.value = String(v); o.textContent = t(tn); sel.appendChild(o); } + sel.value = String(PM_BTNS.some(([v]) => v === k[i]) ? k[i] : 0); + sel.onchange = () => { state.pmKeys[i] = +sel.value; pmKeysApply(); renderPm(); }; + l.append(sp, sel); g.appendChild(l); + }); + $('pmInv').checked = !!state.pmInv; + const used = new Set(k.filter((v) => v)); const miss = [[1, 'A'], [2, 'B'], [4, 'C'], [64, t('gbRight')], [32, t('gbLeft')], [8, t('gbUp')], [16, t('gbDown')]].filter(([v]) => !used.has(v)).map(([, n]) => n); + $('pmKeysStat').textContent = miss.length ? t('gbKeysMiss', { n: miss.join(', ') }) : ''; +} +/* the files of a pick: .min directly, .zip opened (a BIOS among them is taken as the own BIOS) */ +async function pmFiles(files) { + const out = []; + for (const f of files) { + const b = new Uint8Array(await f.arrayBuffer()); + if (/\.zip$/i.test(f.name)) { try { for (const z of await C.zipRead(b, inflateRaw)) { const nm = z.name.split('/').pop(); if (nm) out.push({ name: nm, data: z.data }); } } catch (err) { toast(t('dlcBad', { f: f.name, e: em(err) }), true); } } + else out.push({ name: f.name, data: b }); + } + return out; +} +$('btnPm').onclick = () => { if (!state.ctx) { toast(t('gbNeedRom'), true); return; } $('filePm').click(); }; +$('filePm').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; + for (const f of await pmFiles(files)) { + if (E.pmBiosDetect(f.data)) { state.pmBios = f.data; pmBiosApply(); continue; } + if (E.pmTooBig(f.data)) { toast(t('pmBig', { f: f.name }), true); continue; } + if (!E.pmDetect(f.data)) { toast(t('pmBad', { f: f.name }), true); continue; } + pmBiosNow(); await addExtra(f.data, f.name); + } + renderPm(); +}; +$('btnPmBios').onclick = () => { if (!state.ctx) { toast(t('gbNeedRom'), true); return; } $('filePmBios').click(); }; +$('filePmBios').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; + for (const f of await pmFiles(files)) { if (E.pmBiosDetect(f.data)) { state.pmBios = f.data; pmBiosApply(); renderPm(); return; } } + toast(t('pmBiosBad', { f: files.map((f) => f.name).join(', ') }), true); +}; +$('btnPmBiosDel').onclick = () => { state.pmBios = null; pmBiosApply(); renderPm(); }; +$('pmInv').onchange = () => { pmKeysNow(); state.pmInv = $('pmInv').checked; pmKeysApply(); }; +$('btnPmKeysDef').onclick = () => { state.pmKeys = E.PM_KEYS_DEFAULT.slice(); state.pmInv = true; pmKeysApply(); renderPm(); }; +/* 1.7.3: tab Arduboy. As the Pokemon mini: the games (.hex, also in .zip files) go into the menu (ArduboyEmu, kind + * 'ab'); one key layout for all of them. */ +const AB_BTNS = [[0, 'gbNone'], [16, 'pmA'], [32, 'pmB'], [8, 'gbRight'], [4, 'gbLeft'], [1, 'gbUp'], [2, 'gbDown']]; +function abKeysNow() { if (!state.abKeys) { const x = (state.extras || []).find((y) => y.kind === 'ab' && y.keys && y.keys.length === 9); state.abKeys = x ? x.keys.slice() : E.AB_KEYS_DEFAULT.slice(); state.abInv = x ? !!x.inv : true; } return state.abKeys; } +function abKeysApply() { for (const x of state.extras || []) if (x.kind === 'ab') { x.keys = state.abKeys.slice(); x.inv = !!state.abInv; } state.extrasDirty = true; renderPlan(); } +function renderAb() { + if (!$('abList')) return; + const xs = (state.extras || []).map((x, i) => [x, i]).filter(([x]) => x.kind === 'ab'); + const box = $('abList'); box.innerHTML = ''; + if (!xs.length) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('gbNone2'); box.appendChild(d); } + for (const [x, i] of xs) { + const r = document.createElement('div'); r.className = 'dlcrow'; + const n = document.createElement('span'); n.className = 'itemname'; n.textContent = E.extraName(x) + ' (' + Math.ceil(x.rom.length / 1024) + ' KB)'; + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = '×'; b.title = t('progDel'); + b.onclick = () => { state.extras.splice(i, 1); state.extrasDirty = true; renderEmu(); }; + r.append(n, b); box.appendChild(r); + } + if (xs.length && !menuWanted()) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('appNeedMenu'); box.appendChild(d); } + const k = abKeysNow(), g = $('abKeyGrid'); g.innerHTML = ''; + GB_INS.forEach((nm, i) => { + const l = document.createElement('label'); const sp = document.createElement('span'); sp.textContent = t(nm); + const sel = document.createElement('select'); + for (const [v, tn] of AB_BTNS) { const o = document.createElement('option'); o.value = String(v); o.textContent = t(tn); sel.appendChild(o); } + sel.value = String(AB_BTNS.some(([v]) => v === k[i]) ? k[i] : 0); + sel.onchange = () => { state.abKeys[i] = +sel.value; abKeysApply(); renderAb(); }; + l.append(sp, sel); g.appendChild(l); + }); + $('abInv').checked = !!state.abInv; + const used = new Set(k.filter((v) => v)); const miss = [[16, 'A'], [32, 'B'], [8, t('gbRight')], [4, t('gbLeft')], [1, t('gbUp')], [2, t('gbDown')]].filter(([v]) => !used.has(v)).map(([, n]) => n); + $('abKeysStat').textContent = miss.length ? t('gbKeysMiss', { n: miss.join(', ') }) : ''; +} +$('btnAb').onclick = () => { if (!state.ctx) { toast(t('gbNeedRom'), true); return; } $('fileAb').click(); }; +$('fileAb').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; + for (const f of await pmFiles(files)) { + if (!/\.hex$/i.test(f.name)) continue; + const bin = E.abHex(f.data); + if (!bin) { toast(t(f.data.length > 0x16000 ? 'abBig' : 'abBad', { f: f.name }), true); continue; } + abKeysNow(); + await addExtra(bin, f.name, { kind: 'ab', rom: bin, title: E.abTitle(f.name), keys: state.abKeys.slice(), inv: state.abInv !== false }); + } + renderAb(); +}; +$('abInv').onchange = () => { abKeysNow(); state.abInv = $('abInv').checked; abKeysApply(); }; +$('btnAbKeysDef').onclick = () => { state.abKeys = E.AB_KEYS_DEFAULT.slice(); state.abInv = true; abKeysApply(); renderAb(); }; +/* 1.6.10 test1: tab Wolf3D. The user's game files become one pack (wolf.js) in the browser; Wolf3D goes into the menu + * (kind 'wolf' in state.extras, only one). Keys like DOOM on the Paradise. */ +const W = window.ParamixWolf; +function wolfX() { return (state.extras || []).find((y) => y.kind === 'wolf'); } +function wolfKeysNow() { if (!state.wolfKeys) { const x = wolfX(); state.wolfKeys = Object.assign({}, E.WOLF_KEYS_DEFAULT, (x && x.keys) || {}); } return state.wolfKeys; } +function wolfKeysCheck(k) { return (k.fire === k.fwd || k.fire === k.back || k.fwd === k.back) ? t('wolfBad', { e: 'fire, forward and back need three different buttons' }) : ''; } +function wolfKeysApply() { const xs = (state.extras || []).filter((y) => y.kind === 'wolf'); for (const x of xs) x.keys = Object.assign({}, state.wolfKeys); if (xs.length) { state.extrasDirty = true; state.wolfKeysDirty = true; } renderPlan(); } +function renderWolf() { + if (!$('wolfList')) return; + const box = $('wolfList'); box.innerHTML = ''; + const xs = (state.extras || []).map((x, i) => [x, i]).filter(([x]) => x.kind === 'wolf'); + if (!xs.length) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('wolfNone'); box.appendChild(d); } + for (const [x, i] of xs) { + const inf = E.wolfInfo(x.pack) || { shareware: true, episodes: 1 }; + const r = document.createElement('div'); r.className = 'dlcrow'; + const n = document.createElement('span'); n.className = 'itemname'; + n.textContent = (inf.sod ? 'SPEAR OF DESTINY ' + t('wolfSodN') : 'WOLFENSTEIN 3D ' + t(inf.shareware ? 'wolfShare' : 'wolfFull') + ', ' + (inf.episodes > 1 ? t('wolfEps', { n: inf.episodes }) : t('wolfEp1'))) + ' (' + (x.pack.length >> 10) + ' KB)'; + const b = document.createElement('button'); b.className = 'btn small'; b.textContent = '×'; b.title = t('progDel'); + b.onclick = () => { state.extras.splice(i, 1); state.extrasDirty = true; renderEmu(); }; + r.append(n, b); box.appendChild(r); + } + if (xs.length && !menuWanted()) { const d = document.createElement('div'); d.className = 'hint'; d.textContent = t('appNeedMenu'); box.appendChild(d); } + const k = wolfKeysNow(); + keySel('wkFire', k.fire); keySel('wkFwd', k.fwd); keySel('wkBack', k.back); keySel('wkUse', k.use, true); keySel('wkMod', k.mod); + const ts = $('wkTurn'); ts.innerHTML = ''; + for (const v of [5, 10, 15, 20, 30, 45]) { const o = document.createElement('option'); o.value = String(v); o.textContent = v + '°'; ts.appendChild(o); } + ts.value = String(k.turn); + $('wkRun').checked = !!k.run; $('wkInv').checked = !!k.invert; + $('wolfKeysStat').textContent = wolfKeysCheck(k); +} +[['wkFire', 'fire'], ['wkFwd', 'fwd'], ['wkBack', 'back'], ['wkUse', 'use'], ['wkMod', 'mod'], ['wkTurn', 'turn']].forEach(([id, f]) => { + $(id).onchange = () => { wolfKeysNow()[f] = +$(id).value; wolfKeysApply(); renderWolf(); }; +}); +$('wkRun').onchange = () => { wolfKeysNow().run = $('wkRun').checked; wolfKeysApply(); }; +$('wkInv').onchange = () => { wolfKeysNow().invert = $('wkInv').checked; wolfKeysApply(); }; +$('btnWolfKeysDef').onclick = () => { state.wolfKeys = Object.assign({}, E.WOLF_KEYS_DEFAULT); wolfKeysApply(); renderWolf(); }; +$('btnWolf').onclick = () => { if (!state.ctx) { toast(t('gbNeedRom'), true); return; } $('fileWolf').click(); }; +$('fileWolf').onchange = async (e) => { + const files = [...e.target.files]; e.target.value = ''; + const set = {}; + for (const f of files) set[f.name] = new Uint8Array(await f.arrayBuffer()); + let r; + try { r = W.build(set); } catch (err) { toast(t('wolfBad', { e: err.message }), true); return; } + const old = (state.extras || []).findIndex((y) => y.kind === 'wolf' && E.wolfSod(y.pack) === !!r.sod); // 1.6.11 test2: Wolf3D and SOD side by side + const x = { kind: 'wolf', pack: r.pack, keys: Object.assign({}, wolfKeysNow()), fresh: true }; + state.extras = state.extras || []; + if (old < 0 && state.extras.length >= E.APPX_MAX) { toast(t('appMax'), true); return; } + const prev = old >= 0 ? state.extras[old] : null; + if (old >= 0) { state.extras[old] = x; toast(t('wolfOne')); } else state.extras.push(x); + state.extrasDirty = true; + // does it still fit? a trial build right away (as addExtra) + const f = await busy(roomFit), k = f.k; + if (k || f.err) { if (prev) state.extras[state.extras.indexOf(x)] = prev; else state.extras = state.extras.filter((y) => y !== x); state.extrasDirty = true; renderEmu(); toast(k ? t('noRoomAdd', { n: E.extraName(x), k }) + (E.PACK_OPT && (state.extras || []).some((y) => y.kind === 'tama' && !y.pack) ? t('packTip') : '') : t('appFail', { e: f.err }), true); return; } + renderEmu(); +}; +function renderDoom() { + if (!state.ctx) return; + let s; + const d = state.doom, has = doomFree() ? doomXs().some((x) => !x.wadSrc) : doomInstalled(); + if (!D.embedded()) s = t('doomMissing'); + else if (d && !d.ok.length && !(d.fit.all && d.fit.all.plain)) s = t('doomBig'); + else if (d) s = t('doomOk', { eps: d.d2 ? 'DOOM II' : 'E' + d.eps.join(', E') }) + (PWAD_ON && d.pwads.length ? '\n' + t('doomPwads', { n: d.pwads.map((p) => p.info.title).join(', ') }) + (!doomFree() && d.pwads.some((p) => p.info.eps.length) ? ' ' + t('doomPwadPara') : doomFree() && d.pwads.some((p) => p.info.eps.length) ? ' ' + t('doomPwadHint') : '') + d.pwads.filter((p) => p.info.big && p.info.big.length).map((p) => '\n' + t('doomPwadBig', { n: p.info.title, m: p.info.big.join(', ') })).join('') : '') + '\n' + t('doomUse'); + else if (has && state.emuRemove) s = t('doomGone'); + else if (has) s = t('doomHas') + '\n' + t('doomUse'); + else s = t('doomNone'); + // 1.7.3 test12: without the Paradise a box per episode (each its own menu entry), else the one episode as before + const multi = DOOM_EPS && doomFree() && !!d && (d.ok.length > 1 || d.ok.some((e) => 'PQ'.includes(e[0])) || (DOOM_WHOLE && !!d.fit.all && d.fit.all.plain)), box = $('doomEpsBox'); + if (PWAD_ON) { $('btnPwad').hidden = !d; $('btnPwadOff').hidden = !d || !d.pwads.length; } + $('doomEpLbl').hidden = multi; box.hidden = !multi; box.innerHTML = ''; + if (multi && DOOM_WHOLE && d.fit.all) { // 1.7.3 test15: whole WAD as one entry + const l = document.createElement('label'); l.className = 'check'; const c = document.createElement('input'); c.type = 'checkbox'; c.checked = !!d.whole; c.disabled = !!d.d2; // DOOM II: only whole + c.onchange = () => { d.whole = c.checked; doomFreeSync(); renderEmu(); renderDoom(); }; + l.append(c, ' ' + t('doomWhole') + ' (' + (Math.round(doomEpSize(d.fit.all) / 104857.6) / 10) + ' MB)'); box.appendChild(l); box.appendChild(document.createElement('br')); + } + if (multi) for (const e of d.ok) { if (DOOM_WHOLE && d.whole && !'PQ'.includes(e[0])) continue; + const l = document.createElement('label'); l.className = 'check'; const c = document.createElement('input'); c.type = 'checkbox'; c.checked = d.sel.has(e); + c.onchange = () => { if (c.checked) d.sel.add(e); else d.sel.delete(e); doomFreeSync(); renderEmu(); renderDoom(); }; + const lsv = (d.fit[e] || {}).linkSaved, lnk = lsv >= 0x100000 ? t('doomLinkLess', { m: Math.round(lsv / 104857.6) / 10 }) : ''; // DOOM_LINK + l.append(c, ' ' + ('PQ'.includes(e[0]) ? (d.titles || {})[e] : 'E' + e) + ' (' + (Math.round((DOOM_MUSSZ ? doomEpSize(d.fit[e]) : ((d.fit[e] || {}).sizeP || 0)) / 104857.6) / 10) + ' MB' + lnk + ')'); box.appendChild(l); + } + if (multi) s += '\n' + t(d.d2 ? 'doomD2Hint' : DOOM_WHOLE && d.whole ? 'doomWholeHint' : 'doomEpsHint'); + const sel = $('doomEp'), cur = sel.value; sel.innerHTML = ''; + (d && d.ok.some((e) => !'PQ'.includes(e[0])) ? d.ok.filter((e) => !'PQ'.includes(e[0])) : ['1']).forEach(e => { const o = document.createElement('option'); o.value = e; o.textContent = 'E' + e; sel.appendChild(o); }); + if (cur && [...sel.options].some(o => o.value === cur)) sel.value = cur; + const f = d && d.fit[sel.value]; + const mus = $('doomMusic'); mus.onchange = DOOM_MUSSZ ? () => { // 1.7.3 test14: with or without music changes the size of each entry and the room + for (const x of doomXs()) if (x.wadSrc) { x.size = doomEpSize(x.wadSrc.fit[x.ep || x.wadSrc.ok[0]]) || x.size; x.mcu = null; } + state.extrasDirty = true; renderEmu(); renderDoom(); } : () => renderPlan(); + const fm = DOOM_MUSSZ && multi ? (DOOM_WHOLE && d.whole ? d.fit.all : d.ok.filter((e) => d.sel.has(e)).map((e) => d.fit[e]).find((g) => g && g.music)) : f; // several episodes: music if one of them has room for it + mus.disabled = !fm || !fm.music; if (fm && !fm.music) mus.checked = false; + if (fm && !fm.music) s += '\n' + t('doomNoMusic'); + const room = appRoom(); + $('btnWad').disabled = !room; + $('btnDoomOff').hidden = doomFree() ? !doomXs().length : (!has || state.emuRemove || !!d); + if (!room) s = t('noRoomApp'); + else if (!state.launch && !d && (state.emu || (emuInstalled() && !state.emuRemove))) s += '\n' + t('doomVsEmu'); + $('doomStat').textContent = s; + // Keys: for a new WAD or an installed DOOM + const showKeys = !!d || (has && (doomFree() || !state.emuRemove)); + $('doomKeys').hidden = !showKeys; + if (showKeys) { + if (!state.doomKeys) state.doomKeys = Object.assign({}, (doomFree() ? (doomXs()[0] || {}).keys : has && D.doomKeysGet(state.ctx.rom)) || D.KEYS_DEFAULT); + const k = state.doomKeys, old = !doomFree() && has && !d && !D.doomKeysGet(state.ctx.rom); + keySel('kFire', k.fire); keySel('kFwd', k.fwd); keySel('kBack', k.back); keySel('kUse', k.use, true); keySel('kMod', k.mod); + $('kRun').checked = k.run; $('kInv').checked = k.invert; + ['kFire', 'kFwd', 'kBack', 'kUse', 'kMod', 'kRun', 'kInv'].forEach(id => { $(id).disabled = old; }); + const err = D.doomKeysCheck(k); + $('keysStat').textContent = old ? t('kOld') : (err ? em(err) : t('kFixed')); + $('keysStat').classList.toggle('bad', !!err && !old); + } + renderPlan(); +} +function keysChanged() { + const k = state.doomKeys; if (!k) return; + k.fire = +$('kFire').value; k.fwd = +$('kFwd').value; k.back = +$('kBack').value; k.use = +$('kUse').value; k.mod = +$('kMod').value; + k.run = $('kRun').checked; k.invert = $('kInv').checked; + renderDoom(); +} +['kFire', 'kFwd', 'kBack', 'kUse', 'kMod', 'kRun', 'kInv'].forEach(id => { $(id).onchange = keysChanged; }); +$('btnDoomOff').onclick = () => { + if (doomFree()) { for (const x of doomXs()) { if (state.mainPick === x) { state.mainPick = null; state.mainDirty = true; } if (x.fromPara) state.emuRemove = true; } state.extras = state.extras.filter((x) => x.kind !== 'doom'); state.extrasDirty = true; state.doom = null; renderEmu(); renderDoom(); return; } + state.doom = null; if (!state.launch) state.emu = null; state.emuRemove = true; renderEmu(); renderDoom(); }; +$('doomEp').onchange = () => renderDoom(); +$('btnWad').onclick = () => $('fileWad').click(); +/* 1.7.3 test17: the conversions of a WAD (and its extra WADs) in one place: the base with map packs merged, each episode, + * the whole WAD, and each own episode of an extra WAD (Sigil) as its own entry */ +async function doomCompute(w, pwads, keepSel) { + const emb = D.embedded(); if (!emb) throw new Error(t('doomMissing')); + const mapPw = (pwads || []).filter((p) => !p.info.eps.length), epPw = (pwads || []).filter((p) => p.info.eps.length); + const wm = mapPw.length ? D.wadMerge(w, mapPw.map((p) => ({ data: p.data, slot: false }))) : w; + const eps = D.wadEpisodes(wm).filter(x => x === 'M' || (DOOM_E4 ? x <= '4' : x !== '4')); if (!eps.length) throw new Error(DOOM_E4 ? 'E1 bis E4 fehlen' : 'E1 bis E3 fehlen'); // 1.7.3 test14: E4 (Ultimate DOOM) too + // Does the episode fit in the ROM? With music, otherwise without. + // test15 DOOM_PKREG: without the Paradise an episode may be as big as the biggest free piece (0x111000..0xEFD000) + const big = 0xEFD000 - 0x111000 - 4; + const room = doomFree() ? (PWAD_ON ? big : 0x800000 - 0xA8000 - 0x1000) : D.REGION_OFF - D.WAD_OFF - 4, fit = {}, ok = []; + const d2 = eps[0] === 'M'; // 1.7.3 test15: DOOM II, only as a whole WAD without the Paradise + if (d2 && !doomFree()) throw new Error(t('doomD2Clean')); + const one = async (src, ep, only) => { + const conv = async (m) => { const sub = D.wadSub(src, ep, m, only); return D.convert(sub, D.gbaExtras(sub), emb.wasm); }; + const cm = await conv(true), sm = cm.length, music = sm <= room, cp = music && !doomFree() ? cm : await conv(false), sp = cp.length, plain = sp <= room; // 1.7.3 test13: without the Paradise the version without music too + return { music, plain, sizeM: sm, sizeP: sp, mcuM: DOOM_FREE ? cm : null, mcuP: DOOM_FREE ? cp : null }; // test3: kept for DOOM in the menu + }; + for (const ep of d2 ? [] : eps) { fit[ep] = await one(wm, ep); if (fit[ep].plain) ok.push(ep); } + // 1.7.3 test15: the whole WAD in one piece (without the Paradise; about the size of the WAD instead of the sum of the episodes) + if (DOOM_WHOLE && doomFree() && (eps.length > 1 || d2)) { + const conv = async (m) => { const sub = D.wadSub(wm, eps.join(''), m); return D.convert(sub, D.gbaExtras(sub), emb.wasm); }; + const cm = await conv(true), cp = await conv(false); + fit.all = { music: cm.length <= big, plain: cp.length <= big, sizeM: cm.length, sizeP: cp.length, mcuM: cm, mcuP: cp }; + } + // 1.7.3 test17: an own episode of an extra WAD (Sigil E5, Sigil II E6) in the place of E4, its own entry (only without the Paradise) + const titles = {}; + if (PWAD_ON && doomFree() && !d2) for (let i = 0; i < epPw.length; i++) { + const k = 'P' + i, src = D.wadMerge(wm, [{ data: epPw[i].data, slot: true }]); + fit[k] = await one(src, '4'); titles[k] = epPw[i].info.title; if (fit[k].plain) ok.push(k); + // 1.7.3 test21 DOOM_LINK: shared with DOOM in the same ROM (pictures, sounds), the room needed is that much less + if (E.DOOM_LINK && fit[k].mcuP) { const ref = fit.all && fit.all.mcuP ? fit.all.mcuP : eps.map((e) => fit[e] && fit[e].mcuP).filter(Boolean).sort((a, b) => b.length - a.length)[0]; + if (ref) { let sv = 0; for (const [, l] of E.doomLinks([{ kind: 'doom', mcu: ref }, { kind: 'doom', mcu: fit[k].mcuP }])) sv += l.saved; fit[k].linkSaved = sv; } } + } + // 1.7.3 test17: a DOOM II map pack (one-humanity) also alone, only its maps, as its own entry + if (PWAD_ON && doomFree() && d2) for (let i = 0; i < mapPw.length; i++) { + const k = 'Q' + i, only = new Set(mapPw[i].info.maps.filter((m) => /^MAP\d\d$/.test(m))); + if (!only.size || !only.has('MAP01')) continue; // a new game starts at MAP01 + fit[k] = await one(wm, 'M', only); titles[k] = mapPw[i].info.title; if (fit[k].plain) ok.push(k); + } + const sel = keepSel ? new Set([...keepSel].filter((k) => ok.includes(k))) : new Set(ok.slice(0, 1)); + return { wad: w, wadM: wm, pwads: pwads || [], eps, fit, ok, sel, titles, whole: !!(fit.all && fit.all.plain), d2 }; +} +$('fileWad').onchange = (e) => { + const f = e.target.files[0]; e.target.value = ''; if (!f) return; + busy(async () => { + const w = new Uint8Array(await f.arrayBuffer()); + try { + state.doom = await doomCompute(w, []); if (!state.launch) state.emu = null; if (!doomFree()) state.emuRemove = false; doomFreeSync(); renderEmu(); + } catch (err) { state.doom = null; toast(t('doomBad', { e: em(err) }), true); } + renderDoom(); + }); +}; +// 1.7.3 test17: extra WADs (Sigil, map packs) on top of the chosen WAD +$('btnPwad').onclick = () => $('filePwad').click(); +$('filePwad').onchange = (e) => { + const fs = [...e.target.files]; e.target.value = ''; const d = state.doom; if (!fs.length || !d) return; + busy(async () => { + try { + const add = []; + for (const f of fs) { const data = new Uint8Array(await f.arrayBuffer()); add.push({ name: f.name, data, info: D.pwadInfo(data, f.name) }); } + // test18: an extra WAD only with the game it is made for (Bernd: one-humanity, a DOOM II map, went in with Ultimate DOOM) + for (const a of add) { + const d2maps = a.info.maps.some((m) => /^MAP/.test(m)), d1 = a.info.eps.length || a.info.maps.some((m) => /^E/.test(m)); + if (d.d2 && d1) throw Object.assign(new Error(t('pwadNeedD1', { n: a.info.title })), { plain: true }); + if (!d.d2 && d2maps) throw Object.assign(new Error(t('pwadNeedD2', { n: a.info.title })), { plain: true }); + } + const pw = d.pwads.filter((p) => !add.some((a) => a.name === p.name)).concat(add); + const nd = await doomCompute(d.wad, pw, d.sel); nd.whole = d.whole && !!(nd.fit.all && nd.fit.all.plain); + state.doom = nd; doomFreeSync(); renderEmu(); + } catch (err) { toast(err && err.plain ? err.message : t('doomBad', { e: em(err) }), true); } + renderDoom(); + }); +}; +$('btnPwadOff').onclick = () => { const d = state.doom; if (!d || !d.pwads.length) return; + busy(async () => { try { const nd = await doomCompute(d.wad, [], d.sel); nd.whole = d.whole && !!(nd.fit.all && nd.fit.all.plain); state.doom = nd; doomFreeSync(); renderEmu(); } catch (err) { toast(t('doomBad', { e: em(err) }), true); } renderDoom(); }); }; + +// ------------------------------------------------------------- actions +$('btnOpen').onclick = () => $('fileRom').click(); +$('fileRom').onchange = (e) => { const f = e.target.files[0]; e.target.value = ''; if (f) busy(() => loadRom(f)); }; +const drop = $('drop'); +drop.onclick = () => $('fileRom').click(); +drop.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); $('fileRom').click(); } }; +['dragenter', 'dragover'].forEach(ev => document.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('over'); })); +['dragleave', 'drop'].forEach(ev => document.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('over'); })); +document.addEventListener('drop', (e) => { + const files = [...(e.dataTransfer?.files || [])]; if (!files.length) return; + const rom = files.find(f => f.size === 16777216 || /\.bin$/i.test(f.name) && f.size > 4194304); + if (rom) busy(() => loadRom(rom)); + else if (state.ctx) busy(() => uploadFiles(files)); +}); +$('btnUpload').onclick = $('btnUpload2').onclick = () => $('fileSheets').click(); +$('fileSheets').onchange = (e) => { const fs = [...e.target.files]; e.target.value = ''; if (fs.length) busy(() => uploadFiles(fs)); }; +$('btnZipFigs').onclick = () => busy(() => zipSheets('fig')); +$('btnZipAll').onclick = () => busy(() => zipSheets('spr')); +$('btnNumbers').onclick = () => busy(async () => { + for (const g of state.ctx.groups) { + const big = C.numberImage(String(g), 64, 64, 4), small = C.numberImage(String(g), 32, 32, 2); + [Array(20).fill(big), null, null, Array(24).fill(small), null, null].forEach((subs, k) => { + const i = g + k, orig = state.ctx.entries[i]; + state.changed.set(i, subs ? C.spriteEncode(orig, subs, C.partOptions(k)) : C.spriteBlank(orig, C.partOptions(k))); + }); + refreshTile('fig', g); + } + toast(t('numOk')); +}); +// ------------------------------------------------------------ field select +// installed six fields with the options chosen now? +const sixSame = (si) => !!si && si.planet === (state.sixPlanet !== false) && si.fieldMenu === (state.sixMenu !== false); +const sixPublicModule = {...S6}; +const memberSix = {ready:false, loading:null}; +const sixAllowed = () => !state.ctx || S6.kindOf(state.ctx.rom) !== 'gen3' || memberSix.ready; +function renderSixMembership() { + $('memberSixCard').classList.toggle('locked', !memberSix.ready); + $('sixPreview').inert = !memberSix.ready; + $('sixPreview').toggleAttribute('inert', !memberSix.ready); + $('memberSixShade').hidden = memberSix.ready; + renderDeviceSix(); + if (state.ctx) renderFeld(); +} +function lockSixMembership(message) { + memberSix.ready = false; + Object.assign(S6, sixPublicModule); window.ParamixSix = S6; + $('memberLink').textContent = '로그인'; + $('memberRestore').hidden = true; + $('memberAdmin').hidden = true; + $('memberSixStatus').textContent = message || '로그인 후 이용할 수 있습니다.'; + renderSixMembership(); +} +async function ensureSixMembership() { + if (location.protocol === 'file:') {lockSixMembership('여섯 지역 통합은 온라인 홈페이지에 로그인해서 이용하세요.');return false;} + if (memberSix.loading) return memberSix.loading; + memberSix.loading = (async () => { + try { + const me = await window.TamaArchive.request('/api/member/me'); + if (!me.authenticated) {lockSixMembership(); return false;} + if (!memberSix.ready) { + await new Promise((resolve, reject) => { + const script = document.createElement('script'); script.src = '/api/member/six.js'; + script.onload = () => {Object.assign(S6, window.ParamixSix);window.ParamixSix=S6;script.remove();resolve();}; + script.onerror = () => {script.remove();reject(new Error('회원 전용 확장 코드를 불러오지 못했습니다. 다시 로그인하세요.'));}; + document.head.appendChild(script); + }); + } + memberSix.ready = true; + $('memberLink').textContent = '내 보관함'; + $('memberLink').title = me.username; + $('memberRestore').hidden = false; + $('memberAdmin').hidden = !me.isAdmin; + renderSixMembership();return true; + } catch(e) {lockSixMembership(e.message);return false;} + })(); + try {return await memberSix.loading;} finally {memberSix.loading=null;} +} +function renderDeviceSix() { + const ready = memberSix.ready && !!dv.d && !dv.run; + $('btnSixStart').disabled = !ready; + $('btnSixRead').disabled = !ready; + const current = !!state.ctx && dv.readCtx === state.ctx; + const supported = current && S6.kindOf(state.ctx.rom) === 'gen3'; + $('btnSixWrite').disabled = !ready || !supported || !(state.six || S6.sixInfo(state.ctx.rom)) || !state.sixWant && !S6.sixInfo(state.ctx.rom); + if (memberSix.ready) $('memberSixStatus').textContent = !dv.d ? '기기를 연결한 뒤 이용하세요.' : dv.run ? '기기 작업 중…' : '회원 전용 · 연결된 기기의 여섯 지역 설정'; + if (!ready) { $('deviceSixPanel').hidden = true; $('btnSixStart').setAttribute('aria-expanded','false'); } + $('deviceSixStatus').textContent = !current ? '먼저 위 버튼으로 연결 기기의 ROM을 읽고 백업하세요.' : !supported ? '이 기종은 여섯 지역 확장 대상이 아닙니다. 트로피컬·글레이셔 기기가 필요합니다.' : state.six ? '추가 원본을 선택했습니다. 설정을 확인한 뒤 기기에 기록하세요.' : '아래 여섯 지역 옵션을 켜고 추가 원본을 선택하세요.'; +} +$('btnSixStart').onclick = async () => { + if (!await ensureSixMembership() || !dv.d || dv.run) return; + $('deviceSixPanel').hidden = !$('deviceSixPanel').hidden; + $('btnSixStart').setAttribute('aria-expanded', String(!$('deviceSixPanel').hidden)); + renderDeviceSix(); +}; +$('btnSixRead').onclick = async () => { + if (!memberSix.ready || !dv.d || dv.run) return; + await $('btnDump').onclick(); + if (memberSix.ready && dv.d && dv.readCtx === state.ctx) { + $('deviceSixPanel').hidden = false; $('btnSixStart').setAttribute('aria-expanded','true'); + renderFeld(); renderDeviceSix(); + } +}; +$('btnSixWrite').onclick = () => { if (!$('btnSixWrite').disabled) return $('btnWrite').onclick(); }; +// 1.7.2: DNA per field comes to every ROM with six fields (no Land ROM needed) +const sixDnaUp = (si) => sixAllowed() && !!S6.DNA && !!si && !si.dna && si.version >= 7 && !state.sixOff && S6.sixDnaCan(state.ctx.rom); +function renderFeld() { + if (!state.ctx) return; + if (EXIT_KEY) { const sx = $('exitKey'), v = String(state.exitKey || 0); sx.innerHTML = ''; for (let i = 0; i < 4; i++) { const o = document.createElement('option'); o.value = String(i); o.textContent = t('exit' + i); sx.appendChild(o); } sx.value = v; } + const fe = F.embedded(), rom = state.ctx.rom, ed = F.edition(rom), can = F.canFields(rom); + const box = $('feldOn'), bag = $('bagOn'), tm = $('tamaOn'), la = !!state.launch; + $('launchOn').checked = la; $('launchOn').disabled = !fe || !ed || !!state.ctx.clean || (state.launchInit && C.isLauncher(state.ctx)) || !!S6.sixInfo(rom); $('launchOn').parentNode.title = S6.sixInfo(rom) ? t('launchSix') : ''; + $('cleanRow').hidden = !CLEAN_ROM || !la; $('cleanClockRow').hidden = !state.clean; $('cleanClock').checked = state.cleanClock !== false; $('cleanOn').checked = !!state.clean; $('cleanOn').disabled = !fe || !ed || !!state.ctx.clean || !FL.embedded() || !cleanCan(); + box.checked = !!state.feld && can && !la; box.disabled = !fe || !can || la; + bag.checked = !!state.bag && !la; bag.disabled = !fe || !ed || la; + tm.checked = !!state.tama && !la; tm.disabled = !fe || !ed || la; + { const g = $('gplayOn'), off = la || !!state.clean || !!state.ctx.clean; $('gplayRow').hidden = !F.GPLAY; g.checked = !!state.gplay && !off; g.disabled = !fe || !ed || off; } + let s; + // six fields (Tropical/Glacier): row visible there only + const si = S6.sixInfo(rom), sixIn = !!si, sixOld = !!si && si.version < S6.VERSION, sixCan = !!S6.kindOf(rom), jade = S6.kindOf(rom) === 'jade'; + $('sixRow').hidden = !sixCan || la; + for (const [id, k] of [['sixOnTxt', jade ? 'sixOnJ' : 'sixOn'], ['sixHintTxt', jade ? 'sixHintJ' : 'sixHint']]) { $(id).dataset.t = k; $(id).textContent = t(k); } + $('sixOn').checked = (sixIn && !state.sixOff) || !!state.six || !!state.sixWant; $('sixOn').disabled = !fe || !S6.embedded(); + $('btnSix').hidden = jade || (sixIn && !sixOld && sixSame(si)); + $('sixPlanetRow').hidden = !sixCan || la || !((sixIn && !state.sixOff) || state.six || state.sixWant); + $('sixPlanet').checked = state.sixPlanet !== false; $('sixPlanet').disabled = !fe || !S6.embedded(); + $('sixMenu').checked = state.sixMenu !== false; $('sixMenu').disabled = !fe || !S6.embedded(); + const gen3 = S6.kindOf(rom) === 'gen3'; + const target = $(gen3 ? 'deviceSixControls' : 'sixControlsHome'); + if ($('sixControls').parentNode !== target) target.appendChild($('sixControls')); + const sixLocked = !sixAllowed() || (gen3 && (!dv.d || dv.run || dv.readCtx !== state.ctx)); + $('sixMemberGate').hidden = !sixLocked || la; + $('sixRow').classList.toggle('six-locked', sixLocked); + $('sixPlanetRow').classList.toggle('six-locked', sixLocked); + $('btnSix').disabled = sixLocked; + if (sixLocked) for (const id of ['sixOn','sixPlanet','sixMenu']) $(id).disabled = true; + if (!fe) s = t('feldMissing'); + else if (!ed) s = t('feldUnknown'); + else if (state.clean) s = t('cleanUse') + (state.ctx.clean ? '' : '\n' + t('cleanWarn')); + else if (la) s = t('launchUse') + (state.launchInit && C.isLauncher(state.ctx) ? '\n' + t('launchOld') : ''); + else { + s = t('feldCur', { f: F.fieldNow(rom) }); + if (can) { + s += ' ' + t('feldList', { s: F.fieldNames(rom).slice(0, sixIn && state.sixOff ? 3 : 99).concat(!sixIn && (state.six || (jade && state.sixWant)) ? (jade ? ['Sky'] : ['Land', 'Water', 'Sky']) : []).join(', ') }); + const ff = F.feldFind(rom, fe.stub), sm = ff && ff.version >= 6 && (ff.flags & F.F_SAVES); + const sl = F.feldSlots(rom, fe.stub).map(x => sm ? t('saveSlot', { n: x.index + 1 }) : F.NAMES[x.field]); + if (sl.length) s += ' ' + t('feldStored', { s: sl.join(', ') }); + } else s += '\n' + t('feldNo'); + if (sixCan && sixIn && state.sixOff) s += '\n' + t(jade ? 'sixOffJ' : 'sixOff'); + else if (sixCan) { + if (jade) { if (sixOld) s += '\n' + t('sixOldJ'); else if (sixIn) s += '\n' + t('sixInJ'); else if (!S6.sixCan(rom)) s += '\n' + t('sixNoFw'); } + else if (sixOld && state.six) s += '\n' + t('sixOk', { n: state.sixName }); + else if (sixOld) s += '\n' + t('sixOld'); + else if (sixIn && !sixSame(si) && !state.six) s += '\n' + t('sixPlanetNeed'); + else if (sixIn) s += '\n' + t('sixIn'); + else if (!S6.sixCan(rom)) s += '\n' + t('sixNoFw'); + else if (state.sixWant && !state.six) s += '\n' + t('sixNeed'); + else if (state.six) s += '\n' + t('sixOk', { n: state.sixName }); + } + if (state.feld || state.bag || state.tama) s += '\n' + t('feldUse'); + } + $('feldStat').textContent = s; + renderDeviceSix(); + renderPlan(); +} +$('feldOn').onchange = (e) => { state.feld = e.target.checked; renderFeld(); }; +$('menuKo').onchange = () => { if (!state.ctx) return; state.feldStale = true; renderFeld(); }; +$('exitKey').onchange = (e) => { state.exitKey = +e.target.value; renderPlan(); }; +$('launchOn').onchange = (e) => busy(async () => { + state.launch = e.target.checked; + if (!state.launch) { state.clean = false; await paraMainSync(); doomFreeSync(); cleanTabs(); } + if (state.launch) { launchMapGet(); state.feld = state.bag = state.tama = state.gplay = false; state.sixWant = false; state.six = null; } + renderInfo(); renderFeld(); renderEmu(); renderNames(); +}); +/* CLEAN_ROM: the feld build of this Studio knows the clock sector (menu version 10) */ +function cleanCan() { const fe = F.embedded(); if (!fe || !fe.feldc) return false; const f = fe.feldc; for (let i = 0; i + 8 <= f.length; i += 4) if ((f[i] | f[i + 1] << 8 | f[i + 2] << 16 | f[i + 3] << 24) >>> 0 === 0x444C4546) return (f[i + 4] | f[i + 5] << 8) >= 10; return false; } +$('cleanOn').onchange = (e) => busy(async () => { + state.clean = e.target.checked; + if (state.clean) { state.six = null; state.sixWant = false; } + await paraMainSync(); doomFreeSync(); + state.roomFree = null; cleanTabs(); + renderInfo(); renderFeld(); renderEmu(); renderDoom(); +}); +$('cleanClock').onchange = (e) => { state.cleanClock = e.target.checked; state.mainDirty = true; renderFeld(); renderEmu(); }; // 1.7.3 test7 +$('sixOn').onchange = (e) => { + if (!sixAllowed()) {renderFeld();toast('여섯 지역 통합은 로그인 후 이용하세요.',true);return;} + state.sixOff = !e.target.checked && !!S6.sixInfo(state.ctx.rom); // 1.6.8: take the extra fields out again + state.sixWant = e.target.checked; + if (!e.target.checked) state.six = null; + else { state.feld = true; if (!state.six && S6.sixNeedsSource(state.ctx.rom)) $('fileSix').click(); } + renderFeld(); renderNames(); +}; +$('btnSix').onclick = () => {if (sixAllowed()) $('fileSix').click();}; +$('sixPlanet').onchange = (e) => { if (sixAllowed()) state.sixPlanet = e.target.checked; renderFeld(); }; +$('sixMenu').onchange = (e) => { if (sixAllowed()) state.sixMenu = e.target.checked; renderFeld(); }; +$('fileSix').onchange = async (e) => { + const f = e.target.files[0]; e.target.value = ''; + if (!sixAllowed()) {toast('여섯 지역 통합은 로그인 후 이용하세요.',true);return;} + if (!f) return; + const buf = new Uint8Array(await f.arrayBuffer()); + if (!S6.sixSource(buf)) { toast(t('sixBad', { n: f.name }), true); renderFeld(); return; } + state.six = buf; state.sixName = f.name; state.sixWant = true; state.feld = true; + toast(t('sixOk', { n: f.name })); + renderFeld(); renderNames(); +}; +$('bagOn').onchange = (e) => { state.bag = e.target.checked; renderFeld(); }; +$('tamaOn').onchange = (e) => { state.tama = e.target.checked; renderFeld(); }; +$('gplayOn').onchange = (e) => { state.gplay = e.target.checked; renderFeld(); }; + +/* Build the new ROM from the loaded one and everything chosen in the tabs. + Returns { rom, name, res } or null (the reason is shown). same: nothing chosen. */ +/** test5: the flash of a further T18Emu that stays in place (its blocks, spares, program and save) */ +function keptT18Ranges(xs, rom) { + const r = []; + for (const x of xs) { + if (x.kind !== 't18' || x.keepOff === undefined) continue; + const c = E.t18Cfg(rom, x.keepOff); if (!c) continue; + for (const b of c.map.concat(c.spare)) if (b !== 0xFFFF) r.push([b << 16, (b + 1) << 16]); + r.push([x.keepOff, x.keepOff + 0x10000]); + } + return r; +} +const APPS_CLEAR_FIRST = true; +/* test20 DL_RESCUE: in the start device DOWNLOAD starts the flash app of the write protection (0xFF0000) instead of a + * copy of its own (64 KB less). dlStrip: the copy an earlier write placed stayed in the flash every time (each write + * put a new one elsewhere, 11 copies = 704 KB on one device); copies of it are emptied before placing anew. */ +const DL_SIG = true, DL_RESCUE = true, DL_AT = 0x10000000 + 0xFF0000 - 0x11000; +function dlStrip(rom, fe) { + const fa = F.feldApps(state.ctx.rom, fe.stub), src = state.ctx.rom; + const pats = []; + if (fa.dl && fa.dl !== DL_AT) { const o = fa.dl - 0x10000000 + 0x11000; if (o >= 0x100000 && o + 0x10000 <= 0xFF0000) pats.push(src.subarray(o, o + 0x10000)); } + { const r = src.subarray(0xFF0000, 0x1000000), app = r.subarray(0, 0xE000); if (String.fromCharCode(...r.subarray(0xE000, 0xE008)) === 'SONIXDEV') { const b = new Uint8Array(0x10000); let n = 0xE000; while (n > 0 && app[n - 1] === 0xFF) n--; b.set(app.subarray(0, n)); pats.push(b); } } + // 1.7.2 DL_SIG: copies of older flash app versions differ from both patterns; they all start with the same 64 bytes + const sig = DL_SIG && FL.embedded() ? FL.embedded().subarray(0, 64) : null; + if (!pats.length && !sig) return rom; + let out = rom; + for (let o = 0x100000; o < 0xFF0000; o += 0x10000) { + const blk = out.subarray(o, o + 0x10000); + const hit = pats.some((p) => { for (let i = 0; i < 0x10000; i++) if (blk[i] !== p[i]) return false; return true; }) || (sig && sig.every((v, i) => blk[i] === v)); + if (hit) { if (out === rom) out = new Uint8Array(rom); out.fill(0xFF, o, o + 0x10000); } + } + return out; +} +/* CLEAN_ROM: the programs placed from 0x10000, then the menu, the restart routine and the load table; the device's + * ID page stays (edition), DOWNLOAD starts the flash app of the rescue start */ +async function composeClean() { + const fe = F.embedded(), emb = FL.embedded(), src = state.ctx.rom; + if (!fe || !emb || !cleanCan()) { toast(t('emuMissing'), true); return null; } + // test3 DOOM_FREE: DOOM is a program of the list like the others (no fixed places, any program can be the main one) + await paraMainSync(); doomFreeSync(); + const dxs = doomXs(); + if (dxs.length > 1 && !DOOM_EPS) { toast(t('doomOne'), true); return null; } + const keysDirty = !!state.doomKeys && dxs.some((x) => JSON.stringify(state.doomKeys) !== (x.keys0 || JSON.stringify(x.keys))); + const emuUp = !state.ctx.clean && emuUpPending(); + if (state.ctx.clean && !state.emu && !state.doom && !keysDirty && !state.extrasDirty && !state.mainDirty && !state.extrasUp && !state.feldStale && !state.t7saveX && !state.saveIn && (state.exitKey || 0) === (state.exitKeyInit || 0) && !emuUp) return { rom: src, name: state.name, res: null, same: true }; + let mainX = null; + if (state.emu) mainX = emuX(state.emu); + else if (!state.ctx.clean && emuInstalled() && !state.emuRemove && !state.paraMainTaken) mainX = await installedX(src); + if (mainX) { mainX.clock = state.emuClock !== false; mainX.nfc = state.emuNfc !== false; mainX.opt = state.emuOpt; mainX.sess = state.emuSess !== false; } + extrasDedupe(mainX); + const extrasL = mainX ? [mainX].concat(state.extras || []) : (state.extras || []); + if (!extrasL.length) { toast(t('launchNeed'), true); return null; } + if (!E.t7Embedded()) { toast(t('emuMissing'), true); return null; } + const ed = F.edition(src); if (!ed) { toast(t('feldUnknown'), true); return null; } + const fresh = []; + let rom = F.cleanBase(src), apps = []; + const de = D.embedded(); + for (const x of dxs) { + if (!de || !de.appF) { toast(t('doomMissing'), true); return null; } + if (state.doomKeys) x.keys = Object.assign({}, state.doomKeys); + const err = x.keys && D.doomKeysCheck(x.keys); if (err) { toast(em(err), true); return null; } + if (x.wadSrc) { const m = doomMcuOf(x); if (!m) { toast(t('doomBig'), true); return null; } x.mcu = m; } + } + // a T18Emu that stays where it is keeps its blocks, spares and save (as in the start device with the Paradise) + if (state.ctx.clean) for (const [a, b] of keptT18Ranges(extrasL, src)) rom.set(src.subarray(a, b), a); + const progs = { t7: E.t7Embedded(), tama: E.embedded() && E.embedded().app, t18: E.t18Embedded(), v1: E.v1Embedded(), doom: de && de.appF ? { app: de.appF, xip: de.xipF } : null }; + try { + const r = E.appsPlace(rom, extrasL, progs, { lang, clock: state.emuClock !== false, nfc: state.emuNfc !== false, launch: true, clean: true, noClock: clockOff(), txSpare: T18_FEW && state.t18Few ? 0x40000 : undefined, keep: F.cleanReserved(), dlApp: null }); + rom = r.rom; apps = r.list; lastFree = r.freeKB; state.tamaPacked = !!r.lzUsed; // 1.7.3 test18 TAMA_RAW: packed only for lack of room + const at = (k) => apps[k + (mainX ? 1 : 0)]; + if (state.t7saveX && at(state.t7saveX.i)) rom = SV.t7SaveIn(rom, state.t7saveX.save, at(state.t7saveX.i).off + 0x10000); + const si = state.saveIn, sk = !si ? null : si.key === 'm' ? (mainX ? -1 : null) : si.key; + if (typeof sk === 'number' && (sk === -1 ? apps[0] : at(sk))) { + const a = sk === -1 ? apps[0] : at(sk), cx = E.extraCfg(rom, a.off); + if (si.kind === 'v1' && cx) { rom = new Uint8Array(rom); rom.set(si.data, cx.saveOff); fresh.push([cx.saveOff, cx.saveOff + 0x2000]); } + if (si.kind === 'tama' && cx) fresh.push([cx.saveOff, cx.saveOff + 0x50000], [cx.guestOff, cx.spareEnd]); + } + extrasL.forEach((x, i) => { if (x.carry && apps[i]) { const cx = E.extraCfg(rom, apps[i].off); if (cx && cx.kind === 'tama') fresh.push([cx.saveOff, cx.saveOff + 0x50000], [cx.guestOff, cx.spareEnd]); } }); + for (const x of extrasL) if (x.kind === 't18' && x.items && x.keepOff !== undefined) { const k = extrasL.indexOf(x); if (apps[k]) t18Fresh(rom, apps[k].off, fresh); } + } catch (e) { lastRoom = e && e.room ? e.missing : 0; toast(e && e.room ? t(e.frag ? 'noRoomFrag' : 'noRoomKB', { k: e.missing }) + (e.packHint ? t('packTip') : '') : t('appFail', { e: em(e) }), true); return null; } + // the main program: the one chosen with the star, or the main program of the Paradise taken along + const k = state.mainPick === 'emu' ? (mainX ? 0 : -1) : state.mainPick ? extrasL.indexOf(state.mainPick) : (mainX && !state.ctx.clean ? 0 : -1); + const mainSrc = k >= 0 && apps[k] ? apps[k].src : 0; + try { rom = F.cleanApply(rom, { apps, dl: DL_AT, mainSrc, auto: !!state.emuAuto && !!mainSrc, noClock: state.cleanClock === false }, { feld: fe.feldc, stub: fe.stub }); } + catch (e) { toast(t('feldFail', { e: em(e) }), true); return null; } + { const w = FL.withRescue(rom, emb); if (!w) { toast(t('feldFail', { e: 'rescue' }), true); return null; } rom = w; } + if (EXIT_KEY && (state.exitKey || exitGet(rom))) rom = exitSet(rom, state.exitKey || 0); + return { rom, name: baseName() + (state.doom ? '_doom_E' + $('doomEp').value : '') + '_clean.bin', res: null, fresh }; +} +async function composeRom() { + if (state.ctx && S6.kindOf(state.ctx.rom) === 'gen3') { + const si = S6.sixInfo(state.ctx.rom); + const explicit = !!state.six || !!state.sixWant || !!state.sixOff || (!!si && !sixSame(si)); + if ((explicit || memberSix.ready) && !await ensureSixMembership() && explicit) {toast('여섯 지역 확장 결과를 저장하려면 다시 로그인하세요.',true);return null;} + } + if (CLEAN_ROM && state.clean) return composeClean(); + const keysDirty = !state.doom && doomInstalled() && state.doomKeys && D.doomKeysGet(state.ctx.rom) && JSON.stringify(state.doomKeys) !== JSON.stringify(D.doomKeysGet(state.ctx.rom)); + const si0 = S6.sixInfo(state.ctx.rom), sixUp = (!!si0 && (si0.version < S6.VERSION || !sixSame(si0)) && !S6.sixNeedsSource(state.ctx.rom)) || sixDnaUp(si0); + const emuUp = emuUpPending(); + if (!state.changed.size && !state.t7save && !state.emu && !state.emuRemove && !state.doom && !keysDirty && !emuUp && !emuAutoDirty() && !state.six && !sixUp && !(state.sixWant && !S6.sixInfo(state.ctx.rom)) && state.feld === state.feldInit && state.bag === state.bagInit && state.tama === state.tamaInit && !!state.gplay === !!state.gplayInit && state.saves === state.savesInit && state.launch === state.launchInit && (state.exitKey || 0) === (state.exitKeyInit || 0) && !state.feldStale && !state.extrasDirty && !state.mainDirty && !state.extrasUp && !state.t7saveX && !state.saveIn && !state.sixOff && !state.petDirty && !state.t18Dirty && !state.t18PicsDirty && !(state.texts && state.texts.size) && !(state.eyeShift && state.eyeShift.size) && !(state.mouthShift && state.mouthShift.size) && !(state.poseAdj && state.poseAdj.size)) return { rom: state.ctx.rom, name: state.name, res: null, same: true }; + const fe = F.embedded(); let feldSaved = fe ? F.feldSlots(state.ctx.rom, fe.stub) : []; + // start device with DOOM (1.6.8): DOOM is the program at 0x0A0000, the emulator of the Emulator tab goes along as a further program + const doomL = !!state.launch && (!!state.doom || (doomInstalled() && !state.emuRemove)); + let mainX = null; + if (doomL && state.emu) mainX = emuX(state.emu); + else if (doomL && state.doom && emuInstalled()) mainX = await installedX(state.ctx.rom); + // 1.6.8: an extra that is the same firmware as the main emulator only once (a start device read back shows its + // emulator as a further program; choosing it again in the Emulator tab must not put it in twice) + if (mainX) { mainX.clock = state.emuClock !== false; mainX.nfc = state.emuNfc !== false; mainX.opt = state.emuOpt; mainX.sess = state.emuSess !== false; } + extrasDedupe(mainX); + const extrasL = mainX ? [mainX].concat(state.extras || []) : (state.extras || []); + if (state.emu && state.doom && !doomL) { toast(t('doomBoth'), true); return null; } + if (state.doom && state.doomKeys && D.doomKeysCheck(state.doomKeys)) { toast(em(D.doomKeysCheck(state.doomKeys)), true); return null; } + let rom = state.ctx.rom, res = null; + const fresh = []; // 1.6.8: ranges taken from the image even with "keep saves" (imported saves) + if (state.launch && !FL.embedded()) { toast(t('emuMissing'), true); return null; } + if (state.launch && !(state.emu || state.doom || (state.extras && state.extras.length) || (appInstalled() && !state.emuRemove))) { toast(t('launchNeed'), true); return null; } + const lmap = state.launch ? launchMapGet() : null; + if (state.changed.size || (lmap && lmap.size) || (state.eyeShift && state.eyeShift.size) || (state.mouthShift && state.mouthShift.size) || (state.poseAdj && state.poseAdj.size)) { + const all = lmap ? new Map([...lmap, ...state.changed]) : state.changed; + try { res = C.buildRom(state.ctx, all, currentDataPack()); rom = res.rom; } + catch (e) { toast(t('tooBig', { e: em(e) }), true); return null; } + } + // 1.6.8: names of fields, Tamas and items (text tables) + if (state.texts && state.texts.size) { try { rom = C.textApply(rom, state.texts, state.textLanguage || lang); } catch (e) { toast(t('tooBig', { e: em(e) }), true); return null; } } + if (fe) rom = F.feldStrip(rom, { stub: fe.stub, oldStub: E.embedded() && E.embedded().stub }, E); + // Emulator instead of installed DOOM: remove DOOM completely first (program part, WAD), then install the emulator + // test5: a further T18Emu that stays where it is (start device) has blocks in the area the main program's removal + // empties (0x830000..0xD48000): they are put back; a new main program must not take them + // test6 APPS_CLEAR_FIRST: the further programs of the old ROM go before the main program is built in (they are + // placed again afterwards); before, a new main program (T18Emu needs 91 blocks) only saw the room they left + if (fe && APPS_CLEAR_FIRST) { const old = E.appsRead(state.ctx.rom, F.feldApps(state.ctx.rom, fe.stub).apps); if (old.length) rom = E.appsClear(rom, old.filter((o) => !extrasL.some((x) => x.kind === 't18' && x.keepOff === o.off))); } + // test25 HI_ORPHAN: start device: what removed programs left behind the Paradise's save becomes free (see E.hiFree) + if (HI_ORPHAN && fe && state.launch && APPS_CLEAR_FIRST) { const ff = F.feldFind(rom, fe.stub); rom = E.hiFree(rom, extrasL.filter((x) => x.kind === 't18' && x.keepOff !== undefined).map((x) => x.keepOff), ff ? ff.off : 0); } + const t18Keep = keptT18Ranges(extrasL, rom), t18Back = (r) => { for (const [a, b] of t18Keep) r.set(rom.subarray(a, b), a); return r; }; + const romMain0 = rom; + if (state.emu && doomInstalled() && !doomL) { try { rom = t18Back(E.emuRemove(rom)); } catch (e) { toast(t('emuFail', { e: em(e) }), true); return null; } } + if ((state.emu && !doomL) || state.emuRemove) { + const emb = E.embedded(); + try { + if (state.emu && doomL) { /* goes along as a further program */ } + else if (state.emu && state.emu.v1) { if (!emb || !E.v1Embedded()) throw new Error(t('emuMissing')); rom = E.v1Patch(rom, state.emu.rom, E.v1Embedded(), emb.stub, { lang, clock: state.emuClock !== false }); } + else if (state.emu && state.emu.t7) { if (!emb || !E.t7Embedded()) throw new Error(t('emuMissing')); rom = E.t7Patch(rom, state.emu.rom, state.emu.figs, E.t7Embedded(), emb.stub, { lang }); } + else if (state.emu && state.emu.t18) { if (!emb || !E.t18Embedded()) throw new Error(t('emuMissing')); rom = E.t18Patch(rom, state.emu.rom, E.t18Embedded(), emb.stub, { lang, launch: !!state.launch, spares: T18_FEW && state.t18Few ? T18_FEW_N : undefined, holes: T18_FEW && state.t18Few }).rom; } + else if (state.emu) { if (!emb) throw new Error(t('emuMissing')); rom = E.emuPatch(rom, state.emu.guest, emb.app, emb.stub, { lang, pack: !!state.emuPack }).rom; } + else rom = t18Back(E.emuRemove(rom)); + } catch (e) { toast(e && e.needPack ? t('packNeed') : t('emuFail', { e: em(e) }), true); return null; } + if (t18Keep.some(([a, b]) => rom.subarray(a, b).some((v, i) => v !== romMain0[a + i]))) { toast(t('emuFail', { e: t('t18Clash') }), true); return null; } + } + if (state.t7save && F.emuType(rom) === 't7' && !doomL) rom = SV.t7SaveIn(rom, state.t7save); + if (state.saveIn && state.saveIn.key === 'm' && !doomL) { + if (state.saveIn.kind === 'v1' && F.emuType(rom) === 'v1') { rom = new Uint8Array(rom); rom.set(state.saveIn.data, 0xC0000); fresh.push([0xC0000, 0xC2000]); } + if (state.saveIn.kind === 'tama' && F.emuType(rom) === 'tama') { const g0 = rd32(rom, 0xA0148), se = rd32(rom, 0xA0144) >= 3 ? rd32(rom, 0xA0140 + 152) : g0 + rd32(rom, 0xA014C); fresh.push([0xC0000, 0x110000], [g0, se]); } + } + // newer emulator program: only the program changes, the Tamagotchi's save stays + if (emuUp && F.appKind(rom) === 2) { const ty = F.emuType(rom), u = ty === 'v1' ? E.v1Upgrade(rom, E.v1Embedded()) : ty === 't7' ? E.t7Upgrade(rom, E.t7Embedded()) : ty === 't18' ? E.t18Upgrade(rom, E.t18Embedded(), E.embedded() && E.embedded().stub) : E.emuUpgrade(rom, E.embedded().app); if (u) rom = u; } + if (state.t18Dirty && state.t18Main && !state.emu && !state.emuRemove && F.emuType(rom) === 't18') { try { rom = E.t18RomWriteGuest(rom, state.t18Main); t18Fresh(rom, 0xA0000, fresh); } catch (e) { toast(t('emuFail', { e: em(e) }), true); return null; } } // test47: items + if (F.emuType(rom) === 't18' && state.t18Pics && (state.t18Pics.size || state.t18PicsDirty)) rom = E.t18PicsWrite(rom, state.t18Pics); // test47: grow-up pictures + if (state.doom && !state.doom.ok.length && !(state.doom.fit.all && state.doom.fit.all.plain)) { toast(t('doomBig'), true); return null; } + if (state.doom) { + const emb = D.embedded(), embE = E.embedded(); + try { + if (!emb || !embE) throw new Error(t('doomMissing')); + rom = (await D.doomBuild(rom, state.doom.wadM || state.doom.wad, { episode: $('doomEp').value, music: $('doomMusic').checked, keys: state.doomKeys || D.KEYS_DEFAULT }, { app: emb.app, xip: emb.xip, wasm: emb.wasm, stub: embE.stub }, E)).rom; + } catch (e) { toast(t('doomFail', { e: em(e) }), true); return null; } + } + // Change the keys of an already installed DOOM + if (!state.doom && doomInstalled() && !state.emuRemove && state.doomKeys && D.doomKeysGet(rom)) { + const k = state.doomKeys, err = D.doomKeysCheck(k); + if (err) { toast(em(err), true); return null; } + rom = D.doomKeysSet(rom, k); + } + // 1.6.8: extra fields out again (several saves with the edition's own fields only) + if (state.sixOff && S6.sixInfo(rom)) { + const base = F.fieldNames(S6.sixStrip(state.ctx.rom)), now = F.fieldNow(state.ctx.rom); + if (now && base.length && !base.includes(now)) { toast(t('sixOffField', { f: now, s: base.join(', ') }), true); return null; } + if (feldSaved.length && !confirm(t('sixOffSlots'))) return null; + rom = S6.sixStrip(rom); feldSaved = []; + } + const needSrc = S6.sixNeedsSource(rom); + if (state.sixWant && needSrc && !state.six && !S6.sixInfo(rom)) { toast(t('sixNeed'), true); return null; } + const sixHave = S6.sixInfo(rom); + if (sixHave && needSrc && !state.six && sixHave.version >= S6.VERSION && !sixSame(sixHave)) { toast(t('sixPlanetNeed'), true); return null; } + if ((state.six || (state.sixWant && !needSrc) || (!needSrc && sixHave)) && !(sixHave && sixHave.version >= S6.VERSION && sixSame(sixHave))) { + if (state.doom || doomInstalled() || state.emu) { toast(t('sixFail', { e: t('sixApp') }), true); return null; } + if (state.extras && state.extras.length) { toast(t('appSix'), true); return null; } + try { rom = S6.sixApply(rom, state.six, S6.embedded(), { planet: state.sixPlanet !== false, fieldMenu: state.sixMenu !== false }); } + catch (e) { toast(t('sixFail', { e: em(e) }), true); return null; } + } + if (sixAllowed() && S6.DNA && S6.sixInfo(rom)) rom = S6.sixDna(rom, S6.embedded(), true); + if (sixAllowed() && S6.HUNT && S6.sixInfo(rom)) rom = S6.sixHunt(rom); // 1.7.3 test23: egg hunt per field + if (S6.sixInfo(rom)) rom = S6.sixFix(rom); // the archive may have moved: rain pictures point to 0xF00000 + // more emulators (1.6.0): the old blocks go, the list is placed again from the top of the emulator area + let apps = [], appsLow = 0; + if (fe && !APPS_CLEAR_FIRST) { const old = E.appsRead(state.ctx.rom, F.feldApps(state.ctx.rom, fe.stub).apps); if (old.length) rom = E.appsClear(rom, old.filter((o) => !extrasL.some((x) => x.kind === 't18' && x.keepOff === o.off))); } // test2: an installed T18Emu stays + let dl = 0; + if (extrasL.length || state.launch) { + if (!fe || !menuWanted()) { toast(t('appNeedMenu'), true); return null; } + if (!E.t7Embedded()) { toast(t('emuMissing'), true); return null; } + const progs = { t7: E.t7Embedded(), tama: E.embedded() && E.embedded().app, t18: E.t18Embedded(), v1: E.v1Embedded() }; + let dlRes = false; + if (state.launch) { rom = dlStrip(rom, fe); if (DL_RESCUE && FL.embedded()) { const w = FL.withRescue(rom, FL.embedded()); if (w) { rom = w; dlRes = true; } } } + try { const r = E.appsPlace(rom, extrasL, progs, { lang, clock: state.emuClock !== false, nfc: state.emuNfc !== false, launch: !!state.launch, txSpare: T18_FEW && state.t18Few ? 0x40000 : undefined, keep: F.appKind(rom) === 1 ? [[0x830000, 0xD48000]] : [], dlApp: state.launch && !dlRes ? FL.embedded() : null }); rom = r.rom; apps = r.list; appsLow = r.low; dl = dlRes ? DL_AT : r.dl; lastFree = r.freeKB; + for (const x of extrasL) if (x.kind === 't18' && x.items && x.keepOff !== undefined) t18Fresh(rom, x.keepOff, fresh); // test3 + if (state.t7saveX && apps[state.t7saveX.i + (mainX ? 1 : 0)]) rom = SV.t7SaveIn(rom, state.t7saveX.save, apps[state.t7saveX.i + (mainX ? 1 : 0)].off + 0x10000); + if (state.saveIn && typeof state.saveIn.key === 'number' && apps[state.saveIn.key + (mainX ? 1 : 0)]) { + const at = apps[state.saveIn.key + (mainX ? 1 : 0)].off, cx = E.extraCfg(rom, at); + if (state.saveIn.kind === 'v1' && cx) { rom = new Uint8Array(rom); rom.set(state.saveIn.data, cx.saveOff); fresh.push([cx.saveOff, cx.saveOff + 0x2000]); } + if (state.saveIn.kind === 'tama' && cx) fresh.push([cx.saveOff, cx.saveOff + 0x50000], [cx.guestOff, cx.spareEnd]); // the imported pet: no run state of the device + } + extrasL.forEach((x, i) => { if (!x.carry || !apps[i + (mainX ? 1 : 0)]) return; const cx = E.extraCfg(rom, apps[i + (mainX ? 1 : 0)].off); if (cx && cx.kind === 'tama') fresh.push([cx.saveOff, cx.saveOff + 0x50000], [cx.guestOff, cx.spareEnd]); }); // test26: a save taken along from the device + } + catch (e) { lastRoom = e && e.room ? e.missing : 0; toast(e && e.room ? t(e.frag ? 'noRoomFrag' : 'noRoomKB', { k: e.missing }) + (e.packHint ? t('packTip') : '') : t('appFail', { e: em(e) }), true); return null; } + } + // 1.6.8: always the firmware's name (TAMA-GO, FRIENDS, ID L, 4U+ ...), not the emulator's + // 1.6.9 test13: the chosen main program's place in the list (0 = the program at 0x0A0000) + const mainSrcOf = () => { if (!state.launch || !state.mainPick || !doomL) return 0; const k = state.mainPick === 'emu' ? (mainX ? 0 : -1) : extrasL.indexOf(state.mainPick); return k >= 0 && apps[k] ? apps[k].src : 0; }; + const name0 = F.appKind(rom) === 1 ? 'DOOM' : state.emu && state.emu.guest ? E.tamaName(state.emu.guest, state.emu.dev) : (!state.emu && !state.emuRemove && fe && F.appKind(state.ctx.rom) === F.appKind(rom) && F.feldApps(state.ctx.rom, fe.stub).name0) || mainName(rom); + if (fe && menuWanted()) { + try { rom = F.feldApply(rom, { fields: state.feld, bag: state.bag, tama: state.tama, gplay: state.gplay && !state.clean, saves: state.saves, launch: !!state.launch, apps, name0, appsLow, dl, mainSrc: mainSrcOf(), auto: !!state.emuAuto, fieldNames: fieldTexts(rom).map((x) => x.name) }, feldSaved, { feld: fe.feld, stub: fe.stub }, E); } + catch (e) { toast(t('feldFail', { e: em(e) }), true); return null; } + } + // autostart of the emulator (the stubs above were written with it off), clock switch (1.5.1) + if (F.appKind(rom) === 2) rom = E.emuSessSet(E.emuOptSet(E.emuNfcSet(E.emuClockSet(rom, state.emuClock !== false), state.emuNfc !== false), state.emuOpt), state.emuSess !== false); + if (F.appKind(rom) === 2 || (F.appKind(rom) === 1 && !state.launch)) { // 1.6.8: DOOM as the main program can start right away too + let a = E.autoSet(rom, stubList(rom), !!state.emuAuto); + const fe2 = F.embedded(); + // stub of an older Studio (no switch): put in the current one + if (!a && state.emuAuto && E.embedded() && !(fe2 && F.feldFind(rom, fe2.stub))) { + try { rom = E.installApp(rom, rom.slice(0xA0000, 0xB0000), E.embedded().stub); a = E.autoSet(rom, stubList(rom), true); } catch (e) { a = null; } + } + if (a) rom = a; + } + if (EXIT_KEY && (state.exitKey || exitGet(rom))) rom = exitSet(rom, state.exitKey || 0); + const name = baseName() + (state.changed.size ? '_paramix' : '') + (state.emu ? (state.emu.v1 ? '_v1' : state.emu.t7 ? '_t7' : state.emu.t18 ? '_t18' : '_emu') : '') + (state.doom ? '_doom_E' + $('doomEp').value : '') + (S6.sixInfo(rom) ? (S6.kindOf(rom) === 'jade' ? '_4fields' : '_6fields') : state.feld ? '_fields' : '') + (state.bag ? '_items' : '') + (state.launch ? '_start' : '') + '.bin'; + return { rom, name, res, fresh }; +} +$('btnSave').onclick = () => busy(async () => { + const c = await composeRom(); if (!c) return; + if (c.same) { toast(t('nothing')); return; } + download(c.rom, c.name); + state.saved = state.changed.size; + toast(c.res ? t('saved', { name: c.name, n: state.changed.size, kb: c.res.free / 1024 | 0 }) : t('savedEmu', { name: c.name })); +}); + +// ------------------------------------------------------------- device (UART) +const FL = window.ParamixFlash; +const dv = { io: null, d: null, loaded: false, run: false, cancel: false }; +function devRender(msg) { + $('btnBackupRetry').hidden=!window.TamaArchive.hasPending();$('btnBackupRetry').disabled=!!dv.run; + $('start').hidden = !!state.ctx || !$('device').hidden || !!dv.d || dv.run; + const ser = !!(navigator.serial && FL.embedded()); + $('btnConn').disabled = !ser || dv.run; + $('btnDump').disabled = window.TamaArchive.hasPending() || !dv.d || dv.run; + $('btnWrite').disabled = !dv.d || dv.run || !state.ctx; + $('btnSaveRead').disabled = window.TamaArchive.hasPending() || !dv.d || dv.run; + $('btnSaveWrite').disabled = $('btnParaIn').disabled = !dv.d || dv.run; + $('devOnly').disabled = $('devKeep').disabled = dv.run; + $('btnDevStop').hidden = !dv.run; + $('btnRescueTest').disabled = $('btnRescueBack').disabled = !dv.d || dv.run; + $('devInfo').textContent = dv.d ? t('devOn', { ed: dv.d.info.name, mb: dv.d.info.capacity >> 20, l: dv.loaded ? t('devLoaded') : '' }) : t('devNone'); + if (msg !== undefined) $('devStat').textContent = msg; + else if (!ser) $('devStat').textContent = t('devNoSerial'); + else if (dv.d && !state.ctx && !dv.run) $('devStat').textContent = t('devNeedRom'); + uartWarnRender(); + renderDeviceSix(); + if (state.ctx) renderFeld(); +} +/* Flasher errors and notes carry a code; German has its own texts, English uses the module's */ +function flMsg(x) { return x && x.code && lang !== 'en' && T[lang]['fl_' + x.code] ? t('fl_' + x.code, x.p) : (x.message || x.text || String(x)); } +function devProg(ph, done, total) { + $('devBar').style.width = (total ? Math.min(100, done / total * 100) : 0).toFixed(1) + '%'; + const big = total >= 0x400000, u = big ? 1 << 20 : 1024; + const n = ph === 'write' ? done + ' / ' + total : (done / u | 0) + ' / ' + (total / u | 0) + (big ? ' MB' : ' KB'); + $('devStat').textContent = t('ph' + ph) + ' ' + n; +} +async function devTask(fn) { + dv.run = true; dv.cancel = false; devRender(''); + let msg; + try { await fn(); msg = $('devStat').textContent; } + catch (e) { msg = dv.cancel ? t('devCancelled') : t('devErr', { e: flMsg(e) }); } + dv.run = false; devRender(msg); +} +$('btnDevice').onclick = () => { $('device').hidden = !$('device').hidden; devRender(); }; +$('btnHelp').onclick = () => { $('helpBox').hidden = !$('helpBox').hidden; }; +$('helpClose').onclick = () => { $('helpBox').hidden = true; }; +$('btnDevStop').onclick = () => { dv.cancel = true; }; +/* 1.6.9: simulated playdate partner for the Paradise (src/visit.js). Same link key and serial transport as the + * flash app loader (src/flash.js). */ +const VS = { io: null, v: null }; +const VIS_ED = [['land', 'Land'], ['water', 'Water'], ['sky', 'Sky'], ['jade', 'Jade Forest'], ['tropics', 'Tropics'], ['glacier', 'Glacier']]; +function visKey() { return window.ParamixVisit.parseKey(FL.linkKey); } +function visStat(m) { $('visStat').textContent = m; } +function visEdName() { const e = $('visEd').value; const x = VIS_ED.find((a) => a[0] === e); return x ? x[1] : e; } +function visRender() { + $('btnVis').textContent = t(VS.io ? 'visStop' : 'visStart'); + $('btnVis').disabled = !navigator.serial; +} +{ + const sel = $('visEd'); + for (const [v, n] of VIS_ED) { const o = document.createElement('option'); o.value = v; o.textContent = lang==='ko'?({land:'랜드',water:'워터',sky:'스카이',jade:'제이드 포레스트',tropics:'트로피컬',glacier:'글레이셔'}[v]||n):n; sel.appendChild(o); } + try { const e = localStorage.getItem('pmxVisitEd'); if (e) sel.value = e; } catch (e) {} + if (!sel.value) sel.value = 'water'; + sel.onchange = () => { try { localStorage.setItem('pmxVisitEd', sel.value); } catch (e) {} if (VS.io && (!VS.v || VS.v.state.phase === 'wait' || VS.v.state.phase === 'done' || VS.v.state.phase === 'error')) visArm(); }; + visRender(); +} +function visArm() { + if (VS.v) VS.v.stop(); + const ed = visEdName(); + VS.v = window.ParamixVisit.createVisitor({ + edition: $('visEd').value, key: visKey(), + send: (b) => VS.io.write(b), + log: (e, i) => { + if (e === 'start') visStat(t('visRun')); + else if (e === 'sent') visStat(t('visPlay')); + else if (e === 'done') { visStat(t('visDone', { ed })); setTimeout(() => { if (VS.io) visArm(); visStat(t('visDone', { ed })); }, 500); } + else if (e === 'error') { visStat(i.text === 'key' ? t('visBadKey') : t('visErr', { e: i.text })); if (i.text !== 'key') setTimeout(() => { if (VS.io) visArm(); }, 1000); } + }, + }); + visStat(t('visWait', { ed })); +} +async function visClose() { + const io = VS.io; VS.io = null; + if (VS.v) VS.v.stop(); VS.v = null; + try { if (io) await io.close(); } catch (e) {} + visRender(); +} +$('btnVis').onclick = async () => { + if (VS.io) { await visClose(); visStat(''); return; } + if (!navigator.serial) { visStat(t('devNoSerial')); return; } + if (dv.io) { visStat(t('uartBusy')); return; } + let port; + try { port = await navigator.serial.requestPort(); } catch (e) { return; } + try { VS.io = await FL.serialOpen(port); } catch (e) { visStat(t('visErr', { e: e.message })); return; } + VS.io.onData = (d) => { if (VS.v) VS.v.feed(d); }; + visRender(); visArm(); +}; +const PL_HINT = true; +$('btnConn').onclick = async () => { + if (VS.io) await visClose(); + let port; + try { port = await navigator.serial.requestPort(); } catch (e) { return; } + devTask(async () => { + if (dv.io) { await dv.io.close(); dv.io = null; dv.d = null; } + dv.io = await FL.serialOpen(port); + /* 1.7.3 PL_HINT: a Prolific adapter (USB vendor 0x067B) that gets no readable answer: say what usually helps */ + let r; + try { r = await FL.connect(dv.io, FL.embedded(), {}, devProg); } + catch (e) { + let pl = false; try { pl = PL_HINT && port.getInfo().usbVendorId === 0x067B; } catch (x) {} + if (pl && e && (e.code === 'noData' || e.code === 'noAnswer')) e.message = flMsg(e) + '. ' + t('plHint'), e.code = null; + throw e; + } + dv.d = r.dev; dv.loaded = r.loaded; dv.readCtx = null; + devRender(t('devReady')); + await rescueCheck(); + }); +}; +$('btnBackupRetry').onclick=()=>devTask(async()=>{const img=await window.TamaArchive.retry();if(img.length===0x1000000){await loadRom(new File([img],'paradise-recovered-backup.bin'));dv.readCtx=state.ctx;}}); +$('btnDump').onclick = () => devTask(async () => { + const img = await dv.d.dump(devProg, () => dv.cancel); + const st = new Date().toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-'); + const name = 'paradise-' + dv.d.info.name.toLowerCase().replace(/ /g, '-') + '-' + st + '.bin'; + // Collection is limited to explicit full-ROM extraction; local file opens and saves are never uploaded. + await window.TamaArchive.deliver(img,name,download,msg=>{$('archiveStatus').textContent=msg;}); + await loadRom(new File([img], name)); + dv.readCtx = state.ctx; + devRender(t('devDumped', { n: name })); +}); +if (location.protocol !== 'file:') window.TamaArchive.request('/api/catalog').then(c => { + $('siteTitle').textContent = c.title; $('siteDescription').textContent = c.description; applyFeatures(c.features); +}).catch(() => {}); +ensureSixMembership(); +window.addEventListener('focus', () => {ensureSixMembership();}); +// A user-selected private backup opens locally in the editor; it is not re-uploaded. +if (location.protocol !== 'file:' && new URLSearchParams(location.search).has('backup')) { + window.addEventListener('load', () => busy(async () => { + try { + const {img, item} = await window.TamaArchive.memberFile(new URLSearchParams(location.search).get('backup')); + await loadRom(new File([img], item.label + '.bin')); + } catch (e) { alert(e.message); } + }), {once:true}); +} +/* + * test26 SAVE_CARRY: a TamaEmu or T18Emu that gets another place (main program <-> menu, or another place in the menu) + * takes the device's save along when writing with "Keep saves". The device's layout is the loaded ROM's (checked by + * the programs' settings sectors); only the sectors of its flash that differ on the device are read. The save then goes + * into the new ROM like an imported one. Returns { changed, carried: Set of offsets in the loaded ROM } or null when + * the user stops (the device could not be checked and a save might be lost). + */ +const SAVE_CARRY = true; +async function saveCarry(d, c1) { + const r0 = state.ctx.rom, fe = F.embedded(), out = { changed: false, carried: new Set() }; + const progs = []; + if (emuInstalled() && /tama|t18/.test(F.emuType(r0))) progs.push(0xA0000); + for (const x of romExtras(r0)) if (E.extraKind(x) === 'tama' || E.extraKind(x) === 't18') progs.push(x.off); + if (!progs.length) return out; + // the same place: same program and the same layout there (firmware place, save place, block map); flags may change + const nr = c1.rom, sameAt = (off) => { const m = rd32(r0, off + 0x140), to = m === 0x38584D50 ? 0x140 + 400 : 0x1DC; if (rd32(nr, off + 0x140) !== m) return false; for (let i = 0x148; i < to; i++) if (nr[off + i] !== r0[off + i]) return false; return true; }; + const moved = progs.filter((o) => !sameAt(o)); + if (!moved.length) return out; + let ok = true; + for (const o of [0xA0000].concat(romExtras(r0).map((x) => x.off))) { try { if (await d.crc(o, 0x1000) !== FL.crc32(r0, o, 0x1000)) ok = false; } catch (e) { ok = false; } } + if (!ok) return confirm(t('carryUnknown')) ? out : null; + const base = new Uint8Array(r0); + const pull = async (a, b) => { for (const s of await d.changed(r0, null, () => dv.cancel, a & ~0xFFFF, (b + 0xFFFF) & ~0xFFFF)) { base.set(await d.read(s, 0x1000), s); out.changed = true; } }; + for (const o of moved) { + const m = rd32(r0, o + 0x140); + if (m === 0x43584D50) { // TamaEmu: its firmware with the pet's own writes, spare pages, from the device + const cfg = o === 0xA0000 ? romEmuCfg(r0) : SV.emuCfg(r0.subarray(o, o + 0x1000)); if (!cfg) continue; + const end = cfg.spareEnd || cfg.guestOff + cfg.guestSize; await pull(cfg.guestOff, end); + const g = await SV.emuGuestAsync((a, n) => base.subarray(a, a + n), cfg), me = { kind: 'tama', guest: g, dev: cfg.dev }; + if (state.emu && state.emu.guest && sameFw({ kind: 'tama', guest: state.emu.guest, dev: state.emu.dev }, me)) { const pk = E.packMain(g, cfg.dev, null, !!state.emuPack); state.emu = Object.assign({}, state.emu, { guest: g, size: pk.blob.length, big: pk.big }); out.carried.add(o); } + else if (o === 0xA0000 && state.clean) { const x = (state.extras || []).find((y) => y.fromParaMain && y.kind === 'tama'); if (x) { x.guest = g; x.carry = true; state.extrasDirty = true; out.carried.add(o); } } // CLEAN_ROM: the main program went to the menu + else { const x = (state.extras || []).find((y) => E.extraKind(y) === 'tama' && sameFw(y, me)); if (x) { x.guest = g; x.carry = true; state.extrasDirty = true; out.carried.add(o); } } + } else if (m === 0x38584D50) { // T18Emu: its firmware with its save + const tc = E.t18Cfg(r0, o); if (!tc) continue; + for (const b of tc.map.concat(tc.spare)) if (b !== 0xFFFF && b < 0x100) await pull(b << 16, (b + 1) << 16); + await pull(tc.saveOff, tc.saveOff + 0x24000); + const fw = E.t18FromRom(base, o); if (!fw) continue; + const me = { kind: 't18', fw }; + if (state.emu && state.emu.t18) { state.emu = Object.assign({}, state.emu, { rom: fw }); out.carried.add(o); } + else if (o === 0xA0000 && state.clean) { const x = (state.extras || []).find((y) => y.fromParaMain && y.kind === 't18'); if (x) { x.fw = fw; delete x.keepOff; x.saveImp = true; state.extrasDirty = true; out.carried.add(o); } } + else { const x = (state.extras || []).find((y) => E.extraKind(y) === 't18'); if (x) { x.fw = fw; delete x.keepOff; x.saveImp = true; state.extrasDirty = true; out.carried.add(o); } } + void me; + } + } + if (out.carried.size < moved.length && !confirm(t('carryMiss'))) return null; + return out; +} +$('btnWrite').onclick = async () => { + let c = await busy(composeRom); if (!c) return; + const keep = $('devKeep').checked; + if (!confirm(t('devSure')) || (!keep && !confirm(t('devSureFull')))) return; + // CLEAN_ROM: a device with the Paradise becomes one without: its game and save go (a backup first) + const cleanNew = CLEAN_ROM && F.isClean(c.rom); + if (cleanNew && dv.d) { let dc = false; try { const h = await dv.d.read(0, 0x1000); dc = String.fromCharCode(...h.subarray(0, 8)) === 'SONIXDEV' && (h[8] & 1) === 0; /* our table: not encrypted */ } catch (e) { dc = false; } if (!dc && !confirm(t('cleanSure'))) return; } + // test26: a TamaEmu or T18Emu that moves takes the device's save along + let carried = new Set(); + if (keep && SAVE_CARRY && dv.d) { + let cr = null; try { cr = await busy(() => saveCarry(dv.d, c)); } catch (e) { cr = confirm(t('carryUnknown')) ? { changed: false, carried: new Set() } : null; } + if (!cr) return; + carried = cr.carried; + if (cr.changed && cr.carried.size) { c = await busy(composeRom); if (!c) return; } + } + // an emulator save on the device that the new ROM cannot keep: say so before (1.5.1) + let emuSame = false; + if (keep && !cleanNew) { + const EMU = { 0x43584D50: 'TamaEmu', 0x37584D50: 'T7Emu', 0x38584D50: 'T18Emu', 0x31584D50: 'V1Emu' }; + let dm = 0; + try { const p = await dv.d.read(0xA0000, 0x1000); dm = (p[0x140] | p[0x141] << 8 | p[0x142] << 16 | p[0x143] << 24) >>> 0; } catch (e) { dm = 0; } + const im = (c.rom[0xA0140] | c.rom[0xA0141] << 8 | c.rom[0xA0142] << 16 | c.rom[0xA0143] << 24) >>> 0; + // 1.6.8: the same firmware chosen again (same layout and data as on the device) keeps the save + if (EMU[dm] && dm === im && state.emu) { try { emuSame = await emuSameDev(dv.d, c.rom, dm); } catch (e) { emuSame = false; } } + // 1.6.8: a T7Emu or V1Emu that goes from the main program to the menu takes its save along (keepPlan): no question + let moved = false; + if (EMU[dm] && dm !== im && (dm === 0x37584D50 || dm === 0x31584D50)) { + try { + const p = await dv.d.read(0xA0000, 0x1000), u = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0; + const ro = u(p, 0x148), rl = u(p, 0x14C), dc = await dv.d.crc(ro, rl); + const fe0 = F.embedded(); + if (fe0) for (const x of E.appsRead(c.rom, F.feldApps(c.rom, fe0.stub).apps)) { const cx = E.extraCfg(c.rom, x.off); if (cx && cx.romLen === rl && FL.crc32(c.rom, cx.romOff, cx.romLen) === dc) moved = true; } + } catch (e) { moved = false; } + } + if (carried.has(0xA0000)) moved = true; // test26: its save goes along + if (EMU[dm] && !moved && (dm !== im || (state.emu && !emuSame))) { + const n = EMU[im] ? (dm === im ? t('devEmuNew', { o: EMU[im] }) : EMU[im]) : t('devEmuNone'); + if (!confirm(t('devEmuLost', { o: EMU[dm], n }))) return; + } + } + // test4: items or Tamapoints of T18Emu: its save on the device is replaced by the one in the ROM, "keep saves" or not + if (keep && (state.t18Dirty || (state.extras || []).some((x) => x.kind === 't18' && x.items)) && !confirm(t('t18KeepAsk'))) return; + devTask(async () => { + const fe = F.embedded(); + let plan = keep ? FL.keepPlan(F, E, fe && { stub: fe.stub }, { emuChanged: !!state.emu && !emuSame, t7Save: !!state.t7save, t7SaveX: state.t7saveX ? state.t7saveX.i : -1, t18Imp: !!(state.extras || []).some((x) => x.saveImp), mine: studioSecs(state.ctx.rom, c.rom), fresh: c.fresh || [] }) : null; + if(plan && !cleanNew){ + const names=new Map(); + if(state.texts?.size && (state.textLanguage||lang)==='ko')for(const def of C.charTable(state.ctx.files[0]))if(state.texts.has(def.name))names.set(def.id,C.textGet(c.rom,def.name,'ko')); + if(names.size || state.petChanges)plan=SV.keepEdits(plan,state.ctx.editionId,names,state.petChanges,state.petOriginalId); + } + let img = c.rom; + if (!cleanNew && F.emuType(img) === 't7') { const ck = await dv.d.clockRead(); if (ck && (ck.ctrl & 0x80)) img = E.t7Wall(img, ck.counter, new Date()); } + if (!cleanNew && F.emuType(img) === 't18') { const ck = await dv.d.clockRead(); if (ck && (ck.ctrl & 0x80)) img = E.t18Wall(img, ck.counter, new Date()); } // T18Emu: local time for the first start // T7Emu: local time for the first time setting + let r; + try { r = await dv.d.write(img, { onlyChanged: $('devOnly').checked, keep: plan, rescueApp: FL.embedded(), t18Bases: t18Bases(img, fe), onImage: (x) => stashPut(x) }, devProg, () => dv.cancel); } + catch (e) { if (e && e.code === 'noRescueRoom') alert(t('fl_noRescueRoom')); else if (e && e.code === 'cancelledWrite') await rescueCheck(); throw e; } + await stashDel(); + let m = r.written ? t('devDone', { w: r.written, k: r.kept ? t('devKept', { k: r.kept }) : '' }) : t('devSame'); + if (r.rescue) m += '\n' + t('resOn'); + if (r.notes.length) m += '\n' + r.notes.map(flMsg).join('\n'); + devRender(m); + }); +}; +/* test15: the T18Emu settings blocks in an image (main program and start device), for moving its block at 0xFF0000 */ +function t18Bases(img, fe) { + const out = []; + if (rd32(img, 0xA0140) === 0x38584D50) out.push(0xA0000); + try { if (fe) for (const a of E.appsRead(img, F.feldApps(img, fe.stub).apps)) if (rd32(img, a.off + 0x140) === 0x38584D50) out.push(a.off); } catch (e) {} + return out; +} +/* test15: the image being written, kept in the browser until the write is done (a cut write goes on from there) */ +const STASH_DB = 'pmxStash'; +function stashDb() { return new Promise((ok, no) => { try { const q = indexedDB.open(STASH_DB, 1); q.onupgradeneeded = () => q.result.createObjectStore('img'); q.onsuccess = () => ok(q.result); q.onerror = () => no(q.error); } catch (e) { no(e); } }); } +async function stashOp(mode, fn) { try { const db = await stashDb(); return await new Promise((ok, no) => { const tx = db.transaction('img', mode), st = tx.objectStore('img'), q = fn(st); tx.oncomplete = () => ok(q && q.result); tx.onerror = () => no(tx.error); }); } catch (e) { return null; } } +const stashPut = (img) => stashOp('readwrite', (st) => st.put({ img, time: Date.now() }, 'last')); +const stashGet = () => stashOp('readonly', (st) => st.get('last')); +const stashDel = () => stashOp('readwrite', (st) => st.delete('last')); +/* test15: after connecting: a device without its table is in the rescue start (a write was cut off) */ +async function rescueCheck() { + let h; try { h = await dv.d.read(0, 16); } catch (e) { return; } + dv.rescue = String.fromCharCode(...h.subarray(0, 8)) !== 'SONIXDEV'; + const st = await stashGet(); + dv.stash = st && st.img && st.img.length === 0x1000000 ? st.img : null; + $('rescueResume').hidden = !dv.stash; + // a write that did not finish (cut before the device's table went off): the device starts, but go on anyway + const k = dv.rescue ? (dv.stash ? 'resModeGo' : 'resModeRom') : dv.stash ? 'resHalf' : ''; + if (k) { devRender(t(k)); alert(t(k)); } +} +$('btnResume').onclick = () => devTask(async () => { + if (!dv.stash) return; + const r = await dv.d.write(dv.stash, { onlyChanged: true, keep: null, rescueApp: FL.embedded() }, devProg, () => dv.cancel); + await stashDel(); dv.rescue = false; dv.stash = null; $('rescueResume').hidden = true; + devRender(t('resResumed', { w: r.written })); +}); + +/* 1.6.13 test13: test of the rescue start on the device (only with #rettung in the address, see flash.js) */ +$('rescueBox').hidden = !/rettung|rescue/.test(location.hash); +const RES_KEY = 'pmxRescueHdr'; +$('btnRescueTest').onclick = () => { if (!confirm(t('resSure'))) return; devTask(async () => { + const hdr = await dv.d.rescueTest(FL.embedded(), devProg, () => dv.cancel); + try { localStorage.setItem(RES_KEY, Array.from(hdr, (b) => b.toString(16).padStart(2, '0')).join('')); } catch (e) {} + download(hdr, 'paradise-kopf-' + new Date().toISOString().slice(0, 10) + '.bin'); + devRender(t('resCleared')); +}); }; +$('btnRescueBack').onclick = () => devTask(async () => { + let h = null; try { h = localStorage.getItem(RES_KEY); } catch (e) {} + if (!h || h.length !== 0x2000) { devRender(t('resNoHdr')); return; } + const hdr = new Uint8Array(0x1000); for (let i = 0; i < 0x1000; i++) hdr[i] = parseInt(h.substr(2 * i, 2), 16); + await dv.d.rescueRestore(hdr, devProg, () => dv.cancel); + devRender(t('resBackDone')); +}); + +// ------------------------------------------------------------- save games +const SV = window.ParamixSaves; +const stamp = () => { const d = new Date(), z = (n) => String(n).padStart(2, '0'); return d.getFullYear() + z(d.getMonth() + 1) + z(d.getDate()) + '-' + z(d.getHours()) + z(d.getMinutes()); }; +const edSlug = (id) => (FL.EDITIONS[id] || 'paradise').toLowerCase().replace(/ /g, '-'); +function saveMsg(x) { return t('fl_' + x.code, x.p); } +function mainName(r) { + const ty = F.emuType(r); + if (ty === 't7') return E.t7XName(E.t7FromRom(r).rom); + if (ty === 't18') return E.extraName({ kind: 't18' }); + if (ty === 'v1') { const v = E.v1FromRom(r); return v ? E.v1Name(v) : 'V1'; } + const c = romEmuCfg(r); if (c) return E.extraName({ kind: 'tama', dev: c.dev }); + return ''; +} +/* 1.6.8: an extra that is the same firmware as the main emulator only once */ +function sameFw(a, b) { + // 1.6.8: colour Tamas by their code blocks (the rest of the flash holds the pet's own writes) + if (E.extraKind(a) === 'tama' && E.extraKind(b) === 'tama') { + if (a.dev !== b.dev) return false; + for (const k of [0, 1, 0x40, 0x41]) { const o = k << 16; if (o + 0x10000 > a.guest.length || o + 0x10000 > b.guest.length) continue; for (let i = o; i < o + 0x10000; i++) if (a.guest[i] !== b.guest[i]) return false; } + return true; + } +const ka = E.extraKind(a), kb = E.extraKind(b); if (ka !== kb) return false; const x = ka === 'tama' ? [a.guest, b.guest] : ka === 't18' ? [a.fw, b.fw] : [a.rom, b.rom]; if (!x[0] || !x[1]) return false; const [p0, p1] = x[0].length <= x[1].length ? x : [x[1], x[0]]; for (let i = 0; i < p0.length; i += 4093) if (p0[i] !== p1[i]) return false; for (let i = 0; i < p0.length; i++) if (p0[i] !== p1[i]) return false; for (let i = p0.length; i < p1.length; i++) if (p1[i] !== 0xFF) return false; return true; +} +function extrasDedupe(mainX) { + const mainE = mainX || emuX(state.emu); + if (mainE && state.extras && state.extras.some((x) => sameFw(x, mainE))) { state.extras = state.extras.filter((x) => !sameFw(x, mainE)); state.extrasDirty = true; } + // the same firmware twice in the menu: once is enough (it would share nothing, only take room) + const xs = state.extras || [], keep = xs.filter((x, i) => !xs.slice(0, i).some((y) => sameFw(x, y))); + if (keep.length !== xs.length) { state.extras = keep; state.extrasDirty = true; } +} +/* 1.6.8: does the device hold the same emulator firmware (layout and data) as the image? */ +/* 1.6.8: the sectors the Studio changed against the loaded ROM (download items in an emulator's firmware) */ +const rd32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0; +function studioSecs(a, b) { + const out = new Set(), n = Math.max(a.length, b.length); + for (let s = 0; s < n; s += 0x1000) { + if (s + 0x1000 > a.length || s + 0x1000 > b.length) { out.add(s); continue; } + for (let i = s; i < s + 0x1000; i++) if (a[i] !== b[i]) { out.add(s); break; } + } + return out; +} +async function emuSameDev(d, img, m) { + const p = await d.read(0xA0000, 0x1000), u = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0; + const eq = (a, z) => { for (let i = a; i < z; i++) if (p[i] !== img[0xA0000 + i]) return false; return true; }; + const crcEq = async (a, n) => n > 0 && a + n <= img.length && (await d.crc(a, n)) === FL.crc32(img, a, n); + // TamaEmu: layout and block map, and the code blocks at the reset vector (the guest writes into other blocks + // of its flash, those are kept from the device anyway) + if (m === 0x43584D50) { + if (!eq(0x148, 0x140 + 156)) return false; + const rv = u(img, 0xA0140 + 20) === 0 ? 0 : 0x40, g = u(img, 0xA0148); + for (const b of [rv, rv + 1]) { const k = img[0xA0140 + 24 + b]; if (k !== 0xFF && !(await crcEq(g + k * 0x10000, 0x10000))) return false; } + return true; + } + if (m === 0x37584D50) return eq(0x148, 0x140 + 24 + 16 * 24) && crcEq(u(img, 0xA0148), u(img, 0xA014C)); + if (m === 0x31584D50) return eq(0x148, 0x154) && crcEq(u(img, 0xA0148), u(img, 0xA014C)); // V1Emu: ROM and its place // T7Emu: ROM, figures + if (m === 0x38584D50) { // T18Emu: block map and blocks + if (!eq(0x14C, 0x140 + 400)) return false; + const b0 = img[0xA0150] | img[0xA0151] << 8; // the firmware's first block (code; it writes its save elsewhere) + return b0 === 0xFFFF || crcEq(b0 << 16, 0x10000); + } + return false; +} +function romEmuCfg(rom) { return F.appKind(rom) === 2 && F.emuType(rom) === 'tama' ? SV.emuCfg(rom.subarray(0xA0000, 0xA1000)) : null; } +function romT7(rom) { return F.emuType(rom) === 't7'; } +/* Further T7Emus of the loaded ROM (1.6.0): [{ name, saveOff }] */ +function romExtras(rom) { const fe = F.embedded(); return fe ? E.appsRead(rom, F.feldApps(rom, fe.stub).apps) : []; } +/* Which T7Emu the save buttons are for: -1 the main one, otherwise the further one with this index */ +/* 1.6.8: every program with a save, the main one ('m') and the ones in the menu (index in romExtras) */ +/* 1.6.11 test2: every kind has an export and import: T18Emu the firmware with its save (as the T18Emu app), Game Boy and + * Master System the cartridge RAM (.sav as other emulators), Wolf3D its saved game */ +const SAVE_KINDS = new Set(['tama', 't7', 'v1', 't18', 'gb', 'sms', 'pm', 'ab', 'wolf']); +function saveExt(k) { return k === 'tama' || k === 'gb' || k === 'sms' ? '.sav' : k === 'pm' || k === 'ab' ? '.eep' : '.bin'; } +function savePrograms() { + const rom = state.ctx.rom, out = []; + if (emuInstalled()) { const ty = F.emuType(rom); if (SAVE_KINDS.has(ty)) out.push({ key: 'm', kind: ty, name: mainName(rom) || 'EMU', saveOff: 0xC0000, off: 0xA0000 }); } + romExtras(rom).forEach((x, i) => { const k = E.extraKind(x); if (SAVE_KINDS.has(k)) out.push({ key: i, kind: k, name: x.name, saveOff: x.saveOff, off: x.off }); }); + return out; +} +/* Game Boy: the size of the cartridge RAM from the header (as Peanut-GB; MBC2 512 bytes), at most 32 KB */ +function gbSaveLen(r) { if (!r || r.length < 0x150) return 0; if (r[0x147] === 5 || r[0x147] === 6) return 0x200; return Math.min([0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000][r[0x149]] || 0, 0x8000); } +/* Master System: 32 KB cartridge RAM; 8 KB when the rest was never written */ +function smsSaveLen(sv) { for (let i = 0x3000; i < 0x9000; i++) if (sv[i] !== 0xFF) return 0x8000; return 0x2000; } +/* an extra of state.extras for a program of the loaded ROM (same kind and place in the list of its kind) */ +function extraFor(p) { + const xs = romExtras(state.ctx.rom), x0 = xs[p.key]; if (!x0) return null; + const same = (a, b) => a && b && a.length === b.length && a.every((v, i) => v === b[i]); + if (x0.kind === 'gb' || x0.kind === 'sms' || x0.kind === 'pm' || x0.kind === 'ab') return (state.extras || []).find((y) => y.kind === x0.kind && same(y.rom, x0.rom)) || null; + const k = E.extraKind(x0), nth = xs.slice(0, p.key).filter((y) => E.extraKind(y) === k && (k !== 'wolf' || E.wolfSod(y.pack) === E.wolfSod(x0.pack))).length; + return (state.extras || []).filter((y) => E.extraKind(y) === k && (k !== 'wolf' || E.wolfSod(y.pack) === E.wolfSod(x0.pack)))[nth] || null; +} +function saveFor() { const v = $('saveFor').value; return v === 'm' || v === '' || v === undefined ? -1 : +v; } +function saveProg() { const v = $('saveFor').value; return savePrograms().find((p) => String(p.key) === v) || null; } +function renderSave() { + if (!state.ctx) return; + const ps = savePrograms(), sel = $('saveFor'), cur = sel.value; + sel.innerHTML = ''; + for (const p of ps) { const o = document.createElement('option'); o.value = String(p.key); o.textContent = p.name + (p.key === 'm' ? ' (' + t('progIsMain') + ')' : ''); sel.appendChild(o); } + if ([...sel.options].some((o) => o.value === cur)) sel.value = cur; + $('saveForRow').hidden = !ps.length; + const p = saveProg(), f = !p ? '.sav / .bin' : saveExt(p.kind); + $('btnEmuOut').textContent = t('saveBtnOut', { f }); $('btnEmuIn').textContent = t('saveBtnIn', { f }); + $('btnEmuOut').disabled = !p; $('btnEmuIn').disabled = false; $('btnEmuOut').title = ''; + $('saveStat').textContent = !p ? t('saveNoProg') : t('saveProgInfo'); + let con = false; try { con = !!dv.d && !dv.run; } catch (e) {} + $('btnParaIn').disabled = !con; + // 1.6.8: which save (the menu keeps several) + const ss = paraSlots(), sl = $('paraSlot'), sc = sl.value; + sl.innerHTML = ''; + $('paraSlotRow').hidden = !ss; + if (ss) { + const add = (v, txt) => { const o = document.createElement('option'); o.value = v; o.textContent = txt; sl.appendChild(o); }; + if (ss.live < 0) add('live', t('slotLive', { n: F.fieldNow(state.ctx.rom) })); + for (const x of ss.list) add(x.i === ss.live ? 'live' : String(x.i), x.i === ss.live ? t('slotLive', { n: slotLabel(ss, x.i) }) : x.used ? slotLabel(ss, x.i) : t('slotEmpty', { n: slotLabel(ss, x.i) })); + if ([...sl.options].some((o) => o.value === sc)) sl.value = sc; + } +} +function paraSlots() { const fe = F.embedded(); try { return state.ctx && fe ? F.saveSlots(state.ctx.rom, fe.stub) : null; } catch (e) { return null; } } +function slotLabel(ss, i) { return ss.saves ? t('saveSlot', { n: i + 1 }) : (F.fieldNames(state.ctx.rom)[i] || t('saveSlot', { n: i + 1 })); } +function paraSlotPick() { return $('paraSlotRow').hidden ? 'live' : $('paraSlot').value; } +function t7SaveOutSel() { + const p = saveProg(); if (!p || p.kind !== 't7') return null; + return p.key === 'm' ? SV.t7SaveOut(state.ctx.rom) : SV.t7SaveOut(state.ctx.rom, p.saveOff); +} +$('saveFor').onchange = () => renderSave(); +let g_slotIn = 'live'; +$('btnParaIn').onclick = () => { g_slotIn = paraSlotPick(); $('fileSave').value = ''; $('fileSave').click(); }; +$('btnEmuIn').onclick = () => $('fileEmuSav').click(); +/* test23 SAVE_PICK: a save file goes to the program of its kind, whatever the list shows (with T7Emu in the menu and + * another program chosen the import said "T7Emu has to be in the ROM"), also to an emulator added but not yet saved. + * T18Emu: also the save of the T18Emu app (flash from 0x570000 or 0x5E0000, or its .zip with flash.bin). */ +const SAVE_PICK = true; +const T18_PART = [[0x290000, 0, 0x570000], [0x220000, 0, 0x5E0000], [0x220010, 16, 0x5E0000]]; +async function t18Part(g) { + for (const [n, skip, at] of T18_PART) if (g.length === n) return { data: g.subarray(skip), at }; + if (g.length > 22 && g[0] === 0x50 && g[1] === 0x4B) { + try { const z = await C.zipRead(g, inflateRaw); const fl = z.find((x) => x.name === 'flash.bin' && x.data.length === 0x800000); if (fl) return { data: fl.data.subarray(0x570000), at: 0x570000 }; } catch (err) {} + } + return null; +} +function saveKindOf(g) { + if (SV.t7SaveCheck(g)) return 't7'; + if (E.t18Detect(g)) return 't18'; + if (g.length === 0x400000 || g.length === 0x800000 || g.length === 0x7FF800) { try { return { tama: E.emuDetect(g) }; } catch (err) {} } + return null; +} +function progDev(p) { + const rom = state.ctx.rom; + if (p.key === 'm') { const c = romEmuCfg(rom); return c && c.dev; } + const c = SV.emuCfg(rom.subarray(p.off, p.off + 0x1000)); return c && c.dev; +} +$('fileEmuSav').onchange = async (e) => { + const f = e.target.files[0]; e.target.value = ''; if (!f) return; + let g = new Uint8Array(await f.arrayBuffer()), p = saveProg(); + let part = null; + if (SAVE_PICK) { + let k = saveKindOf(g), dev = null; + if (!k && (part = await t18Part(g))) k = 't18'; + if (k && k.tama) { dev = k.tama; k = 'tama'; } + if (k && !(p && p.kind === k && (k !== 'tama' || progDev(p) === dev))) { + const q = savePrograms().filter((x) => x.kind === k && (k !== 'tama' || progDev(x) === dev)); + if (q.length) { p = q[0]; $('saveFor').value = String(p.key); } + else if (k === 't7' && state.emu && state.emu.t7) p = null; // added, not saved yet: the main program + else if (k === 't18' && state.emu && state.emu.t18) p = { key: 'm', kind: 't18', name: 'T18Emu', pend: true }; + } + if (part && (!p || p.kind !== 't18')) { toast(t('saveT18Need'), true); return; } + } + // 1.6.11 test2: Game Boy, Master System (cartridge RAM), Wolf3D (its saved game), T18Emu (firmware with its save) + if (p && p.kind === 'ab') { // 1.7.3: the Arduboy's EEPROM (1 KB, .eep); the kept game state goes + const x = extraFor(p); if (!x) { toast(t('saveEmuBad'), true); return; } + if (g.length !== 0x400) { toast(t('saveWrongFile', { n: p.name }), true); return; } + const sv = new Uint8Array(E.AB_SAVE).fill(0xFF); if (x.save && x.save.length) sv.set(x.save.subarray(0, 0x1000)); + sv.set(g, 0x1000); x.save = sv; state.extrasDirty = true; renderEmu(); renderPlan(); + $('saveStat').textContent = t('saveCartIn', { n: p.name }); return; + } + if (p && p.kind === 'pm') { // 1.7.3: the EEPROM (8 KB, .eep as PokeMini keeps it); the kept game state goes + const x = extraFor(p); if (!x) { toast(t('saveEmuBad'), true); return; } + if (g.length !== 0x2000) { toast(t('saveWrongFile', { n: p.name }), true); return; } + const sv = new Uint8Array(E.PM_BIOS_AT).fill(0xFF); if (x.save && x.save.length) sv.set(x.save.subarray(0, 0x1000)); + sv.set(g, 0x1000); x.save = sv; state.extrasDirty = true; renderEmu(); renderPlan(); + $('saveStat').textContent = t('saveCartIn', { n: p.name }); return; + } + if (p && (p.kind === 'gb' || p.kind === 'sms' || p.kind === 'wolf')) { + const x = extraFor(p); if (!x) { toast(t('saveEmuBad'), true); return; } + const sv = new Uint8Array(0x10000).fill(0xFF); if (x.save && x.save.length) sv.set(x.save.subarray(0, 0x10000)); + if (p.kind === 'wolf') { + if (g.length !== 0x10000 || (g[0x1000] | g[0x1001] << 8 | g[0x1002] << 16 | g[0x1003] << 24) >>> 0 !== 0x56533357) { toast(t('saveWrongFile', { n: p.name }), true); return; } + sv.set(g.subarray(0x1000), 0x1000); + } else { + const n = p.kind === 'gb' ? gbSaveLen(x.rom) : Math.min(g.length, 0x8000); + if (!n) { toast(t('saveNoBatt'), true); return; } + if (g.length < n || g.length > 0x20000 + 64) { toast(t('saveWrongFile', { n: p.name }), true); return; } + sv.fill(0xFF, 0x1000, 0x10000); sv.set(g.subarray(0, n), 0x1000); // the kept game state (behind the RAM) goes + } + x.save = sv; state.extrasDirty = true; renderEmu(); renderPlan(); + $('saveStat').textContent = t('saveCartIn', { n: p.name }); return; + } + if (p && p.kind === 't18') { + if (SAVE_PICK && part) { // the T18Emu app's save: into the firmware the ROM has (or the one just added) + const x0 = p.key === 'm' ? null : extraFor(p); + const fw0 = p.key === 'm' ? (state.emu && state.emu.t18 ? state.emu.rom : E.t18FromRom(state.ctx.rom)) : x0 && (x0.fw || E.t18FromRom(state.ctx.rom, p.off)); + if (!fw0) { toast(t('saveT18Need'), true); return; } + const fw = new Uint8Array(fw0); fw.set(part.data.subarray(0, 0x800000 - part.at), part.at); g = fw; + } + if (!E.t18Detect(g)) { toast(t('saveWrongFile', { n: p.name }), true); return; } + const undo = { emu: state.emu, rem: state.emuRemove, x: null }; + if (p.key === 'm') { let n = 0; for (let i = 0; i < 128; i++) if (!g.subarray(i << 16, (i + 1) << 16).every((v) => v === 0xFF)) n++; state.emu = { t18: true, dev: 't18', rom: g, size: n << 16 }; emuRemoveClear(); } + else { const x = extraFor(p); if (!x) { toast(t('saveEmuBad'), true); return; } undo.x = [x, x.fw, x.keepOff, x.saveImp]; x.fw = g; delete x.keepOff; x.saveImp = true; state.extrasDirty = true; } + // does it fit? (a saved firmware may use more blocks than the fresh one) a trial build right away + const err = await busy(async () => { toast.mute = {}; try { await composeRom(); } catch (e) { toast.mute.err = toast.mute.err || em(e); } const m = toast.mute.err; toast.mute = null; return m; }); + if (err) { + state.emu = undo.emu; state.emuRemove = undo.rem; + if (undo.x) { const [x, fw, ko, si] = undo.x; x.fw = fw; if (ko !== undefined) x.keepOff = ko; if (!si) delete x.saveImp; } + renderEmu(); toast(err, true); return; + } + renderEmu(); renderPlan(); + $('saveStat').textContent = t('t7SaveXDone', { n: p.name }); return; + } + if (SV.t7SaveCheck(g)) { + if (p && p.kind === 't7' && p.key !== 'm') { state.t7saveX = { i: p.key, save: g }; renderPlan(); $('saveStat').textContent = t('t7SaveXDone', { n: p.name }); return; } + if (!romT7(state.ctx.rom) && !(SAVE_PICK && state.emu && state.emu.t7)) { toast(t('t7SaveNeed'), true); return; } + state.t7save = g; renderPlan(); + $('saveStat').textContent = t('t7SaveInDone'); + return; + } + // V1Emu: session and settings (8 KB, "V1ST" at the start or an empty session) + if (g.length === 0x2000 && p && p.kind === 'v1') { + state.saveIn = { key: p.key, kind: 'v1', data: g }; renderPlan(); + $('saveStat').textContent = t('t7SaveXDone', { n: p.name }); return; + } + let dev, pk; + try { dev = E.emuDetect(g); pk = E.packMain(g, dev); } catch (err) { toast(t('saveEmuBad'), true); return; } + // a colour Tama in the menu: its firmware with the save replaces the one in the ROM + if (p && p.kind === 'tama' && p.key !== 'm') { + const x = (state.extras || [])[p.key]; + if (!x || x.kind !== 'tama' || x.dev !== dev) { toast(t('saveEmuBad'), true); return; } + x.guest = g; state.extrasDirty = true; state.saveIn = { key: p.key, kind: 'tama' }; renderEmu(); + $('saveStat').textContent = t('t7SaveXDone', { n: p.name }); return; + } + if (!appRoom()) { toast(t('saveNoRoom'), true); return; } + const cfg = romEmuCfg(state.ctx.rom), was = state.emu ? state.emu.dev : cfg && cfg.dev; + if (was && was !== dev && !confirm(t('saveEmuOther', { a: E.DEVICES[was].label, b: E.DEVICES[dev].label }))) return; + state.emu = { guest: g, dev, size: pk.blob.length, big: pk.big }; emuRemoveClear(); if (!state.launch) state.doom = null; + state.saveIn = { key: 'm', kind: 'tama' }; + renderDoom(); renderEmu(); + $('saveStat').textContent = t('saveEmuInDone', { d: E.DEVICES[dev].label }); +}; +/* Change a Paradise save (1.6.8): level, character, care. Names come from the loaded ROM. */ +let petSave = null, petName = ''; +$('btnPetOpen').onclick = () => { $('filePet').value = ''; $('filePet').click(); }; +$('filePet').onchange = async (e) => { + const f = e.target.files[0]; if (!f || !state.ctx) return; + let save; try { save = SV.paraDecode(new Uint8Array(await f.arrayBuffer())); } catch (err) { toast(em(err), true); return; } + petOpen(save, f.name, false); +}; +/* 1.6.8: the save of the loaded ROM itself; the change goes back into the ROM */ +$('btnPetRom').onclick = () => { + if (!state.ctx) return; + const ed = state.ctx.editionId; + petOpen({ stamp: 0, counter: 0, alarm: 0, status: 0, regs: [], pages: SV.paraFromImage(state.ctx.rom, ed), edition: ed }, '', true); +}; +$('btnPetClose').onclick = () => { petSave = null; $('petRow').hidden = true; $('petStat').textContent = ''; }; +let petFromRom = false; +function petOpen(save, name, fromRom) { + const ed = save.edition || state.ctx.editionId; + if (SV.family(ed) !== SV.family(state.ctx.editionId)) { toast(t('petOther'), true); return; } + const pet = SV.paraPet(save, ed); + if (!pet) { toast(t('petNoSet'), true); return; } + petSave = save; petSave.edition = ed; petName = name; petFromRom = fromRom; + const lv = $('petLevel'); lv.innerHTML = ''; + for (let i = 0; i <= 10; i++) { const o = document.createElement('option'); o.value = i; o.textContent = i; if (i === pet.level) o.selected = true; lv.appendChild(o); } + const sel = $('petChar'); sel.innerHTML = ''; + const keep = document.createElement('option'); keep.value = ''; keep.textContent = t('petKeep'); sel.appendChild(keep); + const chars = F.characters(state.ctx.rom, lang), fn = F.fieldNames(state.ctx.rom).map(fieldLabel); + let cur = chars.find(c=>c.id===pet.id)?.name || ''; + for (const [st, k] of [[3, 'petKid'], [4, 'petYoung'], [5, 'petAdult']]) { + const g = document.createElement('optgroup'); g.label = t(k); + for (const c of chars.filter((x) => x.stage === st)) { + const o = document.createElement('option'); o.value = c.id + ':' + c.stage; + const nm = c.name.charAt(0) + c.name.slice(1).toLowerCase(); + o.textContent = nm + (c.field >= 0 && fn[c.field] ? ' (' + fn[c.field] + ')' : ''); + if (c.id === pet.id) cur = nm; + g.appendChild(o); + } + sel.appendChild(g); + } + $('petStage').value='';$('petHunger').value=pet.hunger;$('petHappy').value=pet.happy;$('petHealth').value=pet.sick?'keep':'0'; + $('petCare').checked = false; + $('petRow').hidden = false; + $('petStat').textContent = t('petNow', { l: pet.level, c: cur || pet.id, h: pet.hunger, j: pet.happy, s: pet.sick ? t('petSick') : '' }); +} +$('petStage').onchange=()=>{const stage=$('petStage').value;$('petChar').value='';[...$('petChar').options].forEach(o=>{o.hidden=!!stage&&!!o.value&&!o.value.endsWith(':'+stage);});}; +$('btnPetSave').onclick = () => { + if (!petSave) return; + const ed = petSave.edition, pet = SV.paraPet(petSave, ed), ch = {}; + const lv = +$('petLevel').value; if (lv !== pet.level) ch.level = lv; + const v = $('petChar').value; if (v) { const [id, st] = v.split(':').map(Number); if (id !== pet.id || st !== pet.stage) { ch.id = id; ch.stage = st; } } + for(const [key,id]of [['hunger','petHunger'],['happy','petHappy']]){const v=Number($(id).value);if(!$(id).checkValidity()){ $(id).reportValidity();return;}if(v!==pet[key])ch[key]=v;} + if($('petHealth').value==='0' && pet.sick)ch.sick=0; + if(ch.id){const def=C.charTable(state.ctx.files[0]).find(c=>c.id===ch.id);if(def)ch.koreanName=C.textGet(state.ctx.rom,def.name,'ko');} + if ($('petCare').checked) ch.care = true; + if (!Object.keys(ch).length) { toast(t('petNothing')); return; } + if (petFromRom) { + const nw = SV.paraPetSet(petSave, ed, ch), r = new Uint8Array(state.ctx.rom); + for (const [a, d] of nw.pages) if (d.length === 0x1000) r.set(d, a); + if(!state.petChanges)state.petOriginalId=pet.id;state.petChanges={...state.petChanges,...ch}; + state.ctx.rom = r; state.petDirty = true; petSave = nw; petSave.edition = ed; + $('petStat').textContent = t('petRomDone'); renderPlan(); return; + } + const out = SV.paraWrite(SV.paraPetSet(petSave, ed, ch), ed); + const name = petName.replace(/\.tamasave$/i, '') + '-' + stamp() + '.tamasave'; + download(out, name); + $('petStat').textContent = t('petDone', { n: name }); +}; + +$('btnParaOut').onclick = () => busy(async () => { + const ed = state.ctx.editionId, v = paraSlotPick(), rom = state.ctx.rom; + let pages = SV.paraFromImage(rom, ed), tag = ''; + if (v !== 'live') { // 1.6.8: a save the menu keeps in a slot + const ss = paraSlots(), i = +v, sv = ss && await F.slotReadAsync((a, n) => rom.subarray(a, a + n), ss.f, i); + if (!sv) { toast(t('slotNone'), true); return; } + const [a, b] = SV.region(ed), got = F.slotPages(sv); + pages = new Map(); for (let p = a; p < b; p += 0x1000) pages.set(p, got.get(p) || new Uint8Array(0x1000).fill(0xFF)); + tag = '-' + slotLabel(ss, i).toLowerCase().replace(/[^a-z0-9]+/g, ''); + } + const name = edSlug(ed) + tag + '-' + stamp() + '.tamasave'; + download(SV.paraEncode(pages, ed, null), name); + $('saveStat').textContent = t('saveNoClock', { n: name }); +}); +$('btnEmuOut').onclick = () => busy(async () => { + const p = saveProg(); if (!p) { toast(t('saveNoEmu'), true); return; } + const rom = state.ctx.rom, slug = p.name.toLowerCase().replace(/[^a-z0-9]+/g, '-'); + if (p.kind === 't7') { + const sv = t7SaveOutSel(); if (!sv) { toast(t('t7NoSave'), true); return; } + const name = 't7emu-' + slug + '-' + stamp() + '-save.bin'; download(sv, name); + $('saveStat').textContent = t('saveDone', { n: name }); return; + } + if (p.kind === 'v1') { + const sv = rom.slice(p.saveOff, p.saveOff + 0x2000); + if (sv.subarray(0, 0x1000).every((v) => v === 0xFF)) { toast(t('t7NoSave'), true); return; } + const name = 'v1emu-' + slug + '-' + stamp() + '-save.bin'; download(sv, name); + $('saveStat').textContent = t('saveDone', { n: name }); return; + } + if (p.kind === 'tama') { + const cfg = p.key === 'm' ? romEmuCfg(rom) : SV.emuCfg(rom.subarray(p.off, p.off + 0x1000)); if (!cfg) { toast(t('saveNoEmu'), true); return; } + const g = await SV.emuGuestAsync((a, n) => rom.subarray(a, a + n), cfg); + const name = cfg.app + '-' + (p.key === 'm' ? '' : slug + '-') + stamp() + '.sav'; + download(g, name); + $('saveStat').textContent = t('saveDone', { n: name }); return; + } + const slug2 = (k) => k + '-' + slug + '-' + stamp(); + if (p.kind === 't18') { + const fw = p.key === 'm' ? E.t18FromRom(rom) : E.t18FromRom(rom, p.off); if (!fw) { toast(t('saveNone'), true); return; } + const name = 't18emu-' + stamp() + '-save.bin'; download(fw, name); + $('saveStat').textContent = t('saveDone', { n: name }); return; + } + if (p.kind === 'ab') { + const x = romExtras(rom)[p.key], sv = x && x.save; + if (!sv || sv.length < 0x1400) { toast(t('saveNone'), true); return; } + const out = sv.slice(0x1000, 0x1400); if (out.every((v) => v === 0xFF)) { toast(t('saveNone'), true); return; } + const name = slug + '-' + stamp() + '.eep'; download(out, name); + $('saveStat').textContent = t('saveDone', { n: name }); return; + } + if (p.kind === 'pm') { + const x = romExtras(rom)[p.key], sv = x && x.save; + if (!sv || sv.length < 0x3000) { toast(t('saveNone'), true); return; } + const out = sv.slice(0x1000, 0x3000); if (out.every((v) => v === 0xFF)) { toast(t('saveNone'), true); return; } + const name = slug + '-' + stamp() + '.eep'; download(out, name); + $('saveStat').textContent = t('saveDone', { n: name }); return; + } + if (p.kind === 'gb' || p.kind === 'sms' || p.kind === 'wolf') { + const x = romExtras(rom)[p.key], sv = x && x.save; + if (!sv) { toast(t('saveNone'), true); return; } + let out, name; + if (p.kind === 'wolf') { if ((sv[0x1000] | sv[0x1001] << 8 | sv[0x1002] << 16 | sv[0x1003] << 24) >>> 0 !== 0x56533357) { toast(t('saveNone'), true); return; } out = sv.slice(0, 0x10000); name = slug2(E.wolfSod(x.pack) ? 'sod' : 'wolf3d') + '-save.bin'; } + else { + const n = p.kind === 'gb' ? gbSaveLen(x.rom) : smsSaveLen(sv); + if (!n) { toast(t('saveNoBatt'), true); return; } + out = sv.slice(0x1000, 0x1000 + n); + if (out.every((v) => v === 0xFF)) { toast(t('saveNone'), true); return; } + name = slug + '-' + stamp() + '.sav'; + } + download(out, name); + $('saveStat').textContent = t('saveDone', { n: name }); return; + } + toast(t('saveEmuBad'), true); +}); +/* From the device: Paradise save with its clock, and the TamaEmu save if the device has the emulator */ +$('btnSaveRead').onclick = () => devTask(async () => { + const d = dv.d, ed = d.info.edition, [a, b] = SV.region(ed), cancel = () => dv.cancel; + const used = await d.usedSectors(a, b, devProg, cancel); + const pages = new Map(), ff = new Uint8Array(0x1000).fill(0xFF); + for (let p = a; p < b; p += 0x1000) pages.set(p, ff); + let n = 0; + for (const s of used) { if (cancel()) throw new Error('cancelled'); pages.set(s, await d.read(s, 0x1000)); devProg('read', ++n * 0x1000, used.length * 0x1000); } + const clock = await d.clockRead(); + const names = [edSlug(ed) + '-' + stamp() + '.tamasave']; + await window.TamaArchive.deliver(SV.paraEncode(pages,ed,clock && (clock.ctrl & 0x80)?clock:null),names[0],download,msg=>{$('archiveStatus').textContent=msg;},'save'); + if(!siteFeatures.emu){devRender(t('devSaveGot',{n:names.join(' · ')}));return;} + // TamaEmu on the device? + const sec = await d.read(0xA0000, 0x1000); + const kindDoom = (() => { for (let i = 0x140; i < 0x400; i += 4) if ((sec[i] | sec[i + 1] << 8 | sec[i + 2] << 16 | sec[i + 3] << 24) >>> 0 === 0x434D4450) return true; return false; })(); + const cfg = kindDoom ? null : SV.emuCfg(sec); + if ((sec[0x140] | sec[0x141] << 8 | sec[0x142] << 16 | sec[0x143] << 24) >>> 0 === E.T7_MAGIC) { + // T7Emu: the pet's EEPROM (two slots) as save.bin of the T7Emu app + const part = new Uint8Array(SV.T7_EE + 0x4000); + part.set(await d.read(SV.T7_EE, 0x4000), SV.T7_EE); + const sv = SV.t7SaveOut(part); + if (sv) { names.push('t7emu-' + stamp() + '-save.bin'); await window.TamaArchive.deliver(sv,names[names.length-1],download,msg=>{$('archiveStatus').textContent=msg;},'aux'); } + } + // further T7Emus (1.6.0): where the loaded ROM has them, if the device has the same program there + if (state.ctx) for (const x of romExtras(state.ctx.rom)) { + const h = await d.read(x.off, 0x1000); + if ((h[0x140] | h[0x141] << 8 | h[0x142] << 16 | h[0x143] << 24) >>> 0 !== E.T7_MAGIC || (h[0x150] | h[0x151] << 8 | h[0x152] << 16 | h[0x153] << 24) >>> 0 !== x.saveOff) continue; + const part = new Uint8Array(x.saveOff + 0x5000); + part.set(await d.read(x.saveOff + 0x1000, 0x4000), x.saveOff + 0x1000); + const sv = SV.t7SaveOut(part, x.saveOff); + if (sv) { names.push('t7emu-' + x.name.toLowerCase() + '-' + stamp() + '-save.bin'); await window.TamaArchive.deliver(sv,names[names.length-1],download,msg=>{$('archiveStatus').textContent=msg;},'aux'); } + } + if (cfg) { + // read less: if the loaded ROM has the same firmware layout, only the sectors that differ + let base = null; + const rc = state.ctx && romEmuCfg(state.ctx.rom); + if (rc && rc.guestOff === cfg.guestOff && rc.guestSize === cfg.guestSize && rc.kind === cfg.kind && rc.map.every((v, i) => v === cfg.map[i])) { + const end = Math.max(cfg.spareEnd || 0, (cfg.guestOff + cfg.guestSize + 0xFFFF) & ~0xFFFF); + const diff = await d.changed(state.ctx.rom, devProg, cancel, cfg.guestOff & ~0xFFFF, Math.min(end, 0x1000000)); + base = new Uint8Array(state.ctx.rom); + for (const s of diff) base.set(await d.read(s, 0x1000), s); + } + const read = base ? (x, k) => base.subarray(x, x + k) : (x, k) => d.read(x, k); + const g = await SV.emuGuestAsync(read, cfg, base ? null : devProg); + names.push(cfg.app + '-' + stamp() + '.sav'); + await window.TamaArchive.deliver(g,names[names.length-1],download,msg=>{$('archiveStatus').textContent=msg;},'aux'); + } + devRender(t('devSaveGot', { n: names.join(', ') }) + (clock ? '' : ' ' + t('devSaveClockNo'))); +}); +$('btnSaveWrite').onclick = () => { g_slotIn = 'live'; $('fileSave').value = ''; $('fileSave').click(); }; +$('fileSave').onchange = async (e) => { + const f = e.target.files[0]; if (!f || !dv.d) return; + let save; + try { save = SV.paraDecode(new Uint8Array(await f.arrayBuffer())); } catch (err) { toast(em(err), true); return; } + const ed = dv.d.info.edition; + const chk = SV.paraCheck(save, ed); + chk.errors.forEach((x) => { if (x.p) { x.p.s = FL.EDITIONS[x.p.s] || x.p.s; x.p.d = FL.EDITIONS[x.p.d] || x.p.d; } }); + if (chk.errors.length) { devRender(t('devErr', { e: chk.errors.map(saveMsg).join(', ') })); return; } + const warn = chk.warnings.map(saveMsg).join('\n'); + if (g_slotIn !== 'live') { slotWrite(save, chk, +g_slotIn, warn); return; } + if (!confirm(t('devSaveSure', { ed: dv.d.info.name }) + (warn ? '\n\n' + warn : ''))) return; + devTask(async () => { + const d = dv.d, [a, b] = SV.region(ed); + // only pages that differ from the device + const img = new Uint8Array(0x1000000).fill(0xFF); + for (const [p, data] of chk.pages) img.set(data, p); + const diff = await d.changed(img, devProg, () => dv.cancel, a & ~0xFFFF, b); + const map = new Map(); + for (const [p, data] of chk.pages) if (diff.has(p)) map.set(p, data); + const w = map.size ? await d.writeSectors(map, devProg, () => dv.cancel, FL.embedded()) : 0; + const v = SV.paraClock(save); + const cl = v !== null && await d.clockSet(v); + devRender(t('devSaveDone', { w, c: cl ? t('devSaveClock') : t('devSaveClockNo') })); + }); +}; + +/* 1.6.8: a save into a slot of the menu on the device (packed like the menu does it, header page last) */ +function slotWrite(save, chk, i, warn) { + const ss = paraSlots(), rom = state.ctx.rom, ed = dv.d.info.edition; + if (!ss) return; + if (!ss.saves) { + const set = chk.pages.get(0xEFE000), fi = F.fieldOfSettings(rom, set); + if (fi !== i) { devRender(t('devErr', { e: t('slotField', { a: F.fieldNames(rom)[fi] || '?', b: slotLabel(ss, i) }) })); return; } + } + if (!confirm(t('slotSure', { n: slotLabel(ss, i) }) + (warn ? '\n\n' + warn : ''))) return; + devTask(async () => { + const d = dv.d, f = ss.f, [a, b] = SV.region(ed); + const mine = rom.subarray(f.off + 0x140, f.off + 0x140 + 0x180), dev = (await d.read(f.off, 0x1000)).subarray(0x140, 0x140 + 0x180); + for (const o of [0, 8, 12, 16, 364, 368]) if (mine[o] !== dev[o] || mine[o + 1] !== dev[o + 1] || mine[o + 2] !== dev[o + 2] || mine[o + 3] !== dev[o + 3]) throw new Error(t('slotDevOther')); + const heads = []; + for (let j = 0; j < f.nslots; j++) heads.push(new Uint8Array(await d.read(F.slotAddr(f, j), 0x1000))); + const s = F.slotBuild(chk.pages, i, a, b), img = new Uint8Array(0x1000000).fill(0xFF); + const written = F.slotPlace(img, f, i, s, F.poolUsed(f, heads, i)); + const first = new Map([[written[0], new Uint8Array(0x1000).fill(0xFF)]]); + for (const p of written.slice(1)) first.set(p, img.slice(p, p + 0x1000)); + let w = await d.writeSectors(first, devProg, () => dv.cancel, FL.embedded()); + w += await d.writeSectors(new Map([[written[0], img.slice(written[0], written[0] + 0x1000)]]), devProg, () => dv.cancel, FL.embedded()); + devRender(t('slotDone', { n: slotLabel(ss, i) })); + }); +} +window.addEventListener('beforeunload', (e) => { if (window.TamaArchive.hasPending() || (state.ctx && state.changed.size && state.saved !== state.changed.size)) { e.preventDefault(); e.returnValue = t('leave'); } }); + +applyLang(); devRender(); +window.__paramix = state; // for tests +})(); diff --git a/src/archive-client.js b/src/archive-client.js new file mode 100644 index 0000000..b17837a --- /dev/null +++ b/src/archive-client.js @@ -0,0 +1,101 @@ +(function (root) { +'use strict'; +const C = [0, 0x70169E2C, 0x70169E2C, 0x70169E2C, 0x849633DB, 0x96CB83B8, 0x96CB83B8]; +const PAGES = [[0xD29000, [5, 6]], [0xD49000, [1, 2, 3, 4]], [0xEFD000, [1, 2, 3, 4, 5, 6]]]; +const u32 = (b, i) => new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(i, true); +function pageEdition(b, ids) { + if (b.length !== 4096) return 0; + const id = u32(b, 0), tail = u32(b, 0xFF8); + return ids.includes(id) && ((tail + id) >>> 0) === C[id] && u32(b, 0xFFC) === (~tail >>> 0) ? id : 0; +} +function edition(img) { + if (img.length !== 0x1000000) return 0; + for (const [off, ids] of PAGES) { const id = pageEdition(img.subarray(off, off + 4096), ids); if (id) return id; } + return 0; +} +async function deviceEdition(dev) { + for (const [off, ids] of PAGES) { const id = pageEdition(await dev.read(off, 4096), ids); if (id) return id; } + return 0; +} +async function digest(img) { + return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', img)), b => b.toString(16).padStart(2, '0')).join(''); +} +async function verify(img, item) { + if (img.length !== 0x1000000 || img.length !== item.size || String.fromCharCode(...img.subarray(0, 8)) !== 'SONIXDEV' || edition(img) !== item.edition || await digest(img) !== item.sha256) throw new Error('복원 파일 검증에 실패했습니다. 다시 불러오세요.'); + return img; +} +async function request(path, options = {}) { + const r = await fetch(path, {cache: 'no-store', ...options, signal: AbortSignal.timeout(90000)}); + const result = await r.json(); + if (!r.ok) throw new Error(result.error || '서버 요청에 실패했습니다.'); + return result; +} +async function sharedBackup(img, report) { + if (location.protocol === 'file:') return '오프라인 실행: PC에만 저장합니다.'; + try { + report('서버 보유 기종을 확인하고 있습니다…'); + const state = await request('/api/backup-status'); + if (!state.enabled) return '서버 자동 백업이 꺼져 있어 PC에만 저장합니다.'; + const id = edition(img); + if (!id) return '기종을 확인하지 못해 서버에는 보관하지 않았습니다. PC 파일을 보관하세요.'; + if (state.held.includes(id)) return '이미 확보한 기종입니다. 서버 원본은 유지하고 PC에 저장합니다.'; + report('미확보 기종입니다. 서버에 비공개 백업을 먼저 저장하고 있습니다…'); + const result = await request('/api/backups', {method: 'POST', headers: {'Content-Type': 'application/octet-stream', 'X-Backup-Notice': 'shown'}, body: img}); + if (result.status === 'stored') { + if (result.sha256 !== await digest(img)) throw new Error('서버 백업 확인값이 일치하지 않습니다.'); + return result.name + ' 서버 비공개 백업 완료. PC에도 저장합니다.'; + } + return result.status === 'already-held' ? '이미 확보한 기종이므로 PC에만 저장합니다.' : '서버 자동 백업이 꺼져 있어 PC에만 저장합니다.'; + } catch (error) { return '서버 백업 실패: ' + error.message + ' PC 백업은 계속 저장합니다.'; } +} +async function backup(img, report) { + const shared = await sharedBackup(img, report); + if (location.protocol === 'file:') return shared; + try { + const me = await request('/api/member/me'); + if (!me.authenticated) return shared; + report('내 보관함에도 저장하고 있습니다…'); + const result = await request('/api/member/files', {method:'POST', headers:{'Content-Type':'application/octet-stream'}, body:img}); + if (result.sha256 !== await digest(img)) throw new Error('개인 백업 확인값이 일치하지 않습니다.'); + return shared + '\n' + (result.status === 'duplicate' ? '내 보관함에 같은 파일이 이미 있습니다.' : '내 보관함 저장 완료.') + ' PC에도 다운로드합니다.'; + } catch (error) { return shared + '\n개인 보관함 저장 확인 실패: ' + error.message + ' PC 다운로드는 계속합니다.'; } +} +// A failed transfer retains the complete dump in this tab for a user-initiated retry. +let pending=null; +async function deviceBackup(img, report, kind='rom') { + if(location.protocol==='file:')throw Error('서버 우선 백업은 홈페이지에서 사용할 수 있습니다. 관리자 설정에 따라 홈페이지에서 다시 시도하세요.'); + report('백업 방식을 확인하고 있습니다…'); + const policy=await request('/api/backup-status'); + if(policy.mode==='local')return {img,message:kind==='rom'?await backup(img,report):'관리자 설정에 따라 PC에 저장합니다.'}; + report('서버에 비공개로 저장하고 있습니다…'); + const result=await request('/api/device-backups',{method:'POST',headers:{'Content-Type':'application/octet-stream','X-Backup-Kind':kind},body:img}); + const sha=await digest(img); + if(result.sha256!==sha || result.size!==img.length || !/^\/api\/device-backups\/[a-f0-9]{32}$/.test(result.fileUrl))throw Error('서버 백업 확인값이 일치하지 않습니다.'); + report('서버에서 백업을 내려받아 검증하고 있습니다…'); + const response=await fetch(result.fileUrl,{cache:'no-store',signal:AbortSignal.timeout(90000)}); + if(!response.ok)throw Error('서버 백업 다운로드에 실패했습니다. 브라우저의 쿠키 설정을 확인하세요.'); + const saved=new Uint8Array(await response.arrayBuffer()); + if(saved.length!==img.length || await digest(saved)!==sha)throw Error('다운로드한 서버 백업의 검증에 실패했습니다.'); + if(kind==='rom')await backup(saved,report); + return {img:saved,message:'서버 저장과 파일 검증을 완료했습니다. 다운로드할 수 있습니다. 임시 보관 기간은 '+policy.retentionHours+'시간입니다.'}; +} +async function deliver(img,name,download,report,kind='rom') { + pending={img,name,download,report,kind}; + try{const result=await deviceBackup(img,report,kind);download(result.img,name);report(result.message);pending=null;return result.img;} + catch(e){report('서버 백업을 완료하지 못했습니다. '+e.message+' 읽은 데이터는 현재 탭에 유지됩니다. 탭을 닫지 말고 서버 저장 재시도를 눌러 주세요.');throw e;} +} +async function retry(){if(!pending)throw Error('재시도할 백업이 없습니다.');const p=pending;return deliver(p.img,p.name,p.download,p.report,p.kind);} +async function memberFile(id) { + if (!/^[a-f0-9]{32}$/.test(id)) throw new Error('백업 주소가 잘못되었습니다.'); + const me = await request('/api/member/me'); + if (!me.authenticated) throw new Error('내 보관함에 로그인한 뒤 파일을 다시 여세요.'); + const item = me.items.find(x => x.id === id); + if (!item) throw new Error('내 보관함에서 해당 파일을 찾지 못했습니다.'); + const response = await fetch(item.fileUrl, {cache:'no-store', signal:AbortSignal.timeout(90000)}); + if (!response.ok) throw new Error('개인 백업을 불러오지 못했습니다.'); + const img = new Uint8Array(await response.arrayBuffer()); + await verify(img, item); + return {img, item}; +} +root.TamaArchive = {edition, deviceEdition, digest, verify, request, backup, deviceBackup, deliver, retry, hasPending:()=>!!pending, memberFile}; +})(window); diff --git a/src/core.js b/src/core.js new file mode 100644 index 0000000..3f92722 --- /dev/null +++ b/src/core.js @@ -0,0 +1,1299 @@ +/* + * Paramix Studio core: reads and writes the asset archive of Paradise ROM dumps. + * Pure functions on Uint8Array, no DOM. Runs in the browser and in Node (tests). + * + * Format references: github.com/GMMan/tama-para-research (formats/archive.md, + * formats/sprites.md). Everything else measured on the six editions + * (Land, Water, Sky, Jade Forest, Tropical, Glacier). + * + * Author: mameise + */ +(function (root) { +'use strict'; + +const ASSET_BASE = 0x111000; // ARC2 root in flash (all editions) +const ARC2_MAGIC = 0x32435241; // "ARC2" +const EDITIONS = { 1: 'Land', 2: 'Water', 3: 'Sky', 4: 'Jade Forest', 5: 'Tropical', 6: 'Glacier' }; + +// ------------------------------------------------------------------ helpers +const u16 = (b, o) => b[o] | (b[o + 1] << 8); +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +/* 1.7.3 test11: an ID page counts when its footer fits (+0xFF8 = C minus ID, +0xFFC its inverse); Tropical/Glacier + * (0xD29000) first. A Glacier was read as Land: at 0xD49000 it has its own save data (or an ID a Studio up to 1.2.11 + * wrote there) whose first word can be 1..6. Without a fitting footer the first word as before. */ +const ED_C = [0, 0x70169E2C, 0x70169E2C, 0x70169E2C, 0x849633DB, 0x96CB83B8, 0x96CB83B8]; +function edPage(rom, p, check) { + if (p + 0x1000 > rom.length) return 0; + const v = u32(rom, p); if (!(p === 0xD29000 ? v === 5 || v === 6 : p === 0xD49000 ? v >= 1 && v <= 4 : v >= 1 && v <= 6)) return 0; + if (!check) return v; + const k = u32(rom, p + 0xFF8); return ((k + v) >>> 0) === ED_C[v] && u32(rom, p + 0xFFC) === (~k >>> 0) ? v : 0; +} +function editionIdOf(rom) { + for (const p of [0xD29000, 0xD49000, 0xEFD000]) { const v = edPage(rom, p, true); if (v) return v; } // 0xEFD000: clean ROM (1.7.3 test13) + for (const p of [0xD49000, 0xD29000]) { const v = p + 4 <= rom.length ? u32(rom, p) : 0; if (v >= 1 && v <= 6) return v; } + return 0; +} +const s8 = (v) => (v & 0x80 ? v - 256 : v); +function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >> 8) & 255; } +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } +function concat(parts) { + let n = 0; for (const p of parts) n += p.length; + const out = new Uint8Array(n); let o = 0; + for (const p of parts) { out.set(p, o); o += p.length; } + return out; +} +function rgb565ToRgb(v) { return [((v >> 11) & 31) * 255 / 31 | 0, ((v >> 5) & 63) * 255 / 63 | 0, (v & 31) * 255 / 31 | 0]; } +function rgbTo565(r, g, b) { return (((r * 31 + 127) / 255 | 0) << 11) | (((g * 63 + 127) / 255 | 0) << 5) | ((b * 31 + 127) / 255 | 0); } + +// ------------------------------------------------------------------- ARC2 +function arc2Parse(buf, off) { + if (u32(buf, off) !== ARC2_MAGIC) throw new Error('no ARC2 archive at 0x' + off.toString(16)); + const chk = u32(buf, off + 4), length = u32(buf, off + 8), n = u32(buf, off + 12); + const ents = []; + for (let i = 0; i < n; i++) { + const e = off + 16 + 16 * i; + ents.push({ flags: u32(buf, e), offset: u32(buf, e + 4), clen: u32(buf, e + 8), ulen: u32(buf, e + 12) }); + } + return { chk, length, ents }; +} +function arc2Checksum(buf, off, length) { + let s = 0; const end = off + 16 + length; + for (let i = off + 8; i < end; i++) s = (s + buf[i]) >>> 0; + return s; +} +function arc2Files(buf, off) { + return arc2Parse(buf, off).ents.map(e => buf.slice(off + e.offset, off + e.offset + e.ulen)); +} +function arc2Build(files) { + const n = files.length; + let pos = 16 + 16 * n; + const ents = [], body = []; + for (const f of files) { + const pad = (4 - pos % 4) % 4; if (pad) { body.push(new Uint8Array(pad)); pos += pad; } + const aligned = f.length + ((4 - f.length % 4) % 4); + ents.push([0, pos, aligned, f.length]); + body.push(f); if (aligned > f.length) body.push(new Uint8Array(aligned - f.length)); + pos += aligned; + } + const out = new Uint8Array(pos); + w32(out, 0, ARC2_MAGIC); w32(out, 8, pos - 16); w32(out, 12, n); + ents.forEach((e, i) => e.forEach((v, k) => w32(out, 16 + 16 * i + 4 * k, v))); + out.set(concat(body), 16 + 16 * n); + w32(out, 4, arc2Checksum(out, 0, pos - 16)); + return out; +} + +// ------------------------------------------------------------ sprite pack +function packSplit(pack) { + const first = u32(pack, 0), n = first / 4; + const offs = []; for (let i = 0; i < n; i++) offs.push(u32(pack, 4 * i)); + return offs.map((o, i) => pack.slice(o, i + 1 < n ? offs[i + 1] : pack.length)); +} +function packJoin(entries) { + const n = entries.length; let pos = 4 * n; + const offs = [], parts = []; + for (const e of entries) { + const pad = (4 - pos % 4) % 4; if (pad) { parts.push(new Uint8Array(pad)); pos += pad; } + offs.push(pos); parts.push(e); pos += e.length; + } + const head = new Uint8Array(4 * n); offs.forEach((o, i) => w32(head, 4 * i, o)); + return concat([head, ...parts]); +} + +// ----------------------------------------------------------- sprite data +function spriteHeader(e) { + return { + dataLength: u32(e, 0), flags: e[4], bpp: e[5], numSprites: u16(e, 6), sw: e[8], sh: e[9], + ox: s8(e[10]), oy: s8(e[11]), iw: e[12], ih: e[13], palBpp: e[14], numPal: e[15], + transp: u16(e, 16), palOffset: u16(e, 18), pixOffset: u16(e, 20), + }; +} +const F_TRANSP = 0x04, F_RLE_BYTE = 0x20, F_RLE_WORD = 0x40, F_XOR = 0x80; +const BITS = { 0: 1, 1: 2, 2: 4, 3: 8 }; + +function rleDecode(d, word) { + const out = []; let i = 0; + if (!word) { + while (i < d.length) { + const c = d[i++]; if (c === 0) break; + if (c & 0x80) { const n = c & 0x7f; for (let k = 0; k < n; k++) out.push(d[i + k]); i += n; } + else { const v = d[i++]; for (let k = 0; k < c; k++) out.push(v); } + } + } else { + while (i + 4 <= d.length) { + const c = u32(d, i); i += 4; if (c === 0) break; + if (c & 0x80000000) { const n = (c & 0x0fffffff) * 4; for (let k = 0; k < n; k++) out.push(d[i + k]); i += n; } + else { for (let r = 0; r < c; r++) for (let k = 0; k < 4; k++) out.push(d[i + k]); i += 4; } + } + } + return Uint8Array.from(out); +} +function rleEncode(data) { + const out = []; let lit = []; let i = 0; + const flush = () => { while (lit.length) { const c = lit.splice(0, 127); out.push(0x80 | c.length, ...c); } }; + while (i < data.length) { + let j = i; while (j < data.length && data[j] === data[i] && j - i < 127) j++; + const run = j - i; + if (run >= 3) { flush(); out.push(run, data[i]); } else { for (let k = i; k < j; k++) lit.push(data[k]); } + i = j; + } + flush(); out.push(0); + return Uint8Array.from(out); +} + +/** Decode one sprite entry. Returns header, palettes, raw index cells and + * composed subimages as RGBA (palette set `palSet`). */ +function spriteDecode(e, palSet = 0) { + const h = spriteHeader(e); + const n = h.numSprites, w = h.sw, hh = h.sh, npx = w * hh; + const iw = Math.max(1, h.iw), ih = Math.max(1, h.ih); + let cells = [], palettes = null, direct = h.bpp >= 0x10; + if (direct) { + for (let s = 0; s < n; s++) { + const c = new Uint16Array(npx); + for (let k = 0; k < npx; k++) c[k] = u16(e, h.pixOffset + 2 * (s * npx + k)); + cells.push(c); + } + } else { + const bits = BITS[h.bpp]; if (!bits) throw new Error('unknown bpp ' + h.bpp); + const ncol = 1 << bits; + palettes = []; + for (let p = 0; p < Math.max(1, h.numPal); p++) { + const pal = []; for (let k = 0; k < ncol; k++) pal.push(u16(e, h.palOffset + 2 * (p * ncol + k))); + palettes.push(pal); + } + const comp = h.flags & (F_RLE_BYTE | F_RLE_WORD), enc = h.flags & F_XOR; + const bp = h.pixOffset, raws = []; + if (comp) { + for (let s = 0; s < n; s++) { + let off = u32(e, bp + 8 * s); const ln = u32(e, bp + 8 * s + 4); + const unc = off & 0x80000000; off &= 0x7fffffff; + let d = e.slice(bp + off, bp + off + ln); + if (enc) d = d.map(x => x ^ 0x53); + if (!unc) d = rleDecode(d, h.flags & F_RLE_WORD); + raws.push(d); + } + } else { + const sz = Math.ceil(npx * bits / 8); + for (let s = 0; s < n; s++) { let d = e.slice(bp + s * sz, bp + (s + 1) * sz); if (enc) d = d.map(x => x ^ 0x53); raws.push(d); } + } + const mask = ncol - 1; + for (const d of raws) { + const c = new Uint8Array(npx); + for (let k = 0; k < npx; k++) { + const bit = k * bits, byte = (bit >> 3) < d.length ? d[bit >> 3] : 0; + c[k] = (byte >> (bit & 7)) & mask; + } + cells.push(c); + } + } + const nsub = Math.floor(n / (iw * ih)); + const W = w * iw, H = hh * ih, subs = []; + const pal = palettes ? palettes[Math.min(palSet, palettes.length - 1)].map(rgb565ToRgb) : null; + const transp = !!(h.flags & F_TRANSP); + for (let si = 0; si < nsub; si++) { + const px = new Uint8ClampedArray(W * H * 4); + for (let gy = 0; gy < ih; gy++) for (let gx = 0; gx < iw; gx++) { + const c = cells[si * iw * ih + gy * iw + gx]; + for (let k = 0; k < npx; k++) { + const v = c[k], x = gx * w + (k % w), y = gy * hh + ((k / w) | 0), o = (y * W + x) * 4; + if (transp && v === h.transp) { px[o + 3] = 0; continue; } + const rgb = pal ? pal[v] : rgb565ToRgb(v); + px[o] = rgb[0]; px[o + 1] = rgb[1]; px[o + 2] = rgb[2]; px[o + 3] = 255; + } + } + subs.push({ w: W, h: H, data: px }); + } + return { header: h, palettes, cells, subs, width: W, height: H }; +} + +// ------------------------------------------------------------ quantizing +/** Median cut with k-means refinement. pixels: array of [r,g,b]. */ +function quantize(pixels, ncolors) { + const uniq = new Map(); + for (const p of pixels) { const k = (p[0] << 16) | (p[1] << 8) | p[2]; uniq.set(k, (uniq.get(k) || 0) + 1); } + let cols = [...uniq.entries()].map(([k, n]) => [(k >> 16) & 255, (k >> 8) & 255, k & 255, n]); + if (cols.length <= ncolors) return cols.map(c => c.slice(0, 3)); + let boxes = [cols]; + while (boxes.length < ncolors) { + let bi = -1, best = -1, ch = 0; + boxes.forEach((b, i) => { + if (b.length < 2) return; + for (let c = 0; c < 3; c++) { + let lo = 255, hi = 0; for (const p of b) { if (p[c] < lo) lo = p[c]; if (p[c] > hi) hi = p[c]; } + const score = (hi - lo) * Math.log2(1 + b.reduce((s, p) => s + p[3], 0)); + if (score > best) { best = score; bi = i; ch = c; } + } + }); + if (bi < 0) break; + const b = boxes[bi].sort((a, c) => a[ch] - c[ch]); + const total = b.reduce((s, p) => s + p[3], 0); let acc = 0, cut = 1; + for (let i = 0; i < b.length - 1; i++) { acc += b[i][3]; if (acc >= total / 2) { cut = i + 1; break; } } + boxes.splice(bi, 1, b.slice(0, cut), b.slice(cut)); + } + let centers = boxes.map(b => { const t = b.reduce((s, p) => s + p[3], 0); return [0, 1, 2].map(c => b.reduce((s, p) => s + p[c] * p[3], 0) / t); }); + for (let it = 0; it < 20; it++) { // k-means on unique colors, weighted + const sum = centers.map(() => [0, 0, 0, 0]); + for (const p of cols) { + let bi = 0, bd = 1e18; + for (let i = 0; i < centers.length; i++) { const c = centers[i]; const d = (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2 + (p[2] - c[2]) ** 2; if (d < bd) { bd = d; bi = i; } } + const s = sum[bi]; s[0] += p[0] * p[3]; s[1] += p[1] * p[3]; s[2] += p[2] * p[3]; s[3] += p[3]; + } + let moved = 0; + centers = centers.map((c, i) => { const s = sum[i]; if (!s[3]) return c; const n = [s[0] / s[3], s[1] / s[3], s[2] / s[3]]; moved += Math.abs(n[0] - c[0]) + Math.abs(n[1] - c[1]) + Math.abs(n[2] - c[2]); return n; }); + if (moved < 0.5) break; + } + return centers.map(c => c.map(v => Math.round(v))); +} +function nearestIndex(pal, r, g, b, skip) { + let bi = 0, bd = 1e18; + for (let i = 0; i < pal.length; i++) { + if (i === skip) continue; + const c = pal[i]; const d = (r - c[0]) ** 2 + (g - c[1]) ** 2 + (b - c[2]) ** 2; + if (d < bd) { bd = d; bi = i; } + } + return bi; +} + +// -------------------------------------------------------------- encoding +/** + * Re-encode a sprite from RGBA subimages, keeping cell size, grid, count + * and anchor of the original entry. + * opts.keepPalette: map onto the original palettes (forced for sprites + * with more than one palette set: colour variants) + * opts.allowMoreColors: palette sprites may go up to 8 bpp + */ +function spriteEncode(orig, subs, opts = {}) { + const h = spriteHeader(orig); + const n = h.numSprites, w = h.sw, hh = h.sh, npx = w * hh; + const iw = Math.max(1, h.iw), ih = Math.max(1, h.ih); + const W = w * iw, H = hh * ih; + if (subs.length * iw * ih !== n) throw new Error('subimage count does not match'); + for (const s of subs) if (s.w !== W || s.h !== H) throw new Error('subimage size does not match'); + const cellRGBA = (si, gx, gy, k) => { const x = gx * w + (k % w), y = gy * hh + ((k / w) | 0), o = (y * W + x) * 4; return subs[si].data.subarray(o, o + 4); }; + const forEachCell = (fn) => { for (let si = 0; si < subs.length; si++) for (let gy = 0; gy < ih; gy++) for (let gx = 0; gx < iw; gx++) fn(si, gx, gy); }; + + // direct colour: raw RGB565, uncompressed, same layout as original + if (h.bpp >= 0x10) { + const tr = h.transp, hasT = !!(h.flags & F_TRANSP); + const out = new Uint8Array(24 + n * npx * 2); + let s = 0; + forEachCell((si, gx, gy) => { + for (let k = 0; k < npx; k++) { + const p = cellRGBA(si, gx, gy, k); + let v = (hasT && p[3] < 128) ? tr : rgbTo565(p[0], p[1], p[2]); + if (hasT && p[3] >= 128 && v === tr) v ^= 1; // keep visible pixels visible + w16(out, 24 + 2 * (s * npx + k), v); + } + s++; + }); + writeHeader(out, { dataLength: out.length, flags: h.flags & ~(F_RLE_BYTE | F_RLE_WORD | F_XOR), bpp: 0x11, numSprites: n, sw: w, sh: hh, ox: h.ox, oy: h.oy, iw: h.iw, ih: h.ih, palBpp: 0x11, numPal: 0, transp: tr, palOffset: 24, pixOffset: 24 }); + return out; + } + + let keep = opts.keepPalette || h.numPal > 1; + let bpp = h.bpp, palBlock, transpIdx, indexOf; + let anyTransparent = false; + for (const s of subs) for (let i = 3; i < s.data.length; i += 4) if (s.data[i] < 128) { anyTransparent = true; break; } + const origTransp = !!(h.flags & F_TRANSP); + let figureMode = false; + + if (opts.figure && !keep) { + // Character parts: if every colour already exists in the original palette, + // keep it (the game's colour variants keep working). Otherwise use the + // "fixed colour" layout: slots 2-7 are recoloured by the game per tama, + // so they stay unused; near black goes to slot 1 (0x000C in every variant). + const pal0 = spriteDecode(orig).palettes[0].map(rgb565ToRgb); + let fits = true; + outer: for (const s of subs) for (let i = 0; i < s.data.length; i += 4) { + if (s.data[i + 3] < 128) continue; + let ok = false; + for (let k = 1; k < pal0.length; k++) { if (FIG_NOVAR && k >= 2 && k <= 7) continue; const c = pal0[k]; if (Math.abs(c[0] - s.data[i]) <= 8 && Math.abs(c[1] - s.data[i + 1]) <= 8 && Math.abs(c[2] - s.data[i + 2]) <= 8) { ok = true; break; } } + if (!ok) { fits = false; break outer; } + } + if (fits && h.bpp === 2) keep = true; else figureMode = h.bpp === 2; + } + + if (keep) { + const dec = spriteDecode(orig); + const pal0 = dec.palettes[0].map(rgb565ToRgb); + transpIdx = origTransp ? h.transp : -1; + const ncol = 1 << BITS[bpp]; + palBlock = orig.slice(h.palOffset, h.palOffset + 2 * ncol * Math.max(1, h.numPal)); + // FIG_NOVAR: own pictures never land in slots 2-7 (the game recolours them per Tama, on the field too) + const pk = opts.figure && FIG_NOVAR ? pal0.map((c, i) => (i >= 2 && i <= 7 ? [1e6, 1e6, 1e6] : c)) : pal0; + indexOf = (p) => (p[3] < 128 && transpIdx >= 0) ? transpIdx : nearestIndex(pk, p[0], p[1], p[2], transpIdx); + } else if (figureMode) { + const FREE = [8, 9, 10, 11, 12, 13, 14, 15]; + const dark = (r, g, b) => r + g + b < 90; + const opaque = []; + for (const s of subs) for (let i = 0; i < s.data.length; i += 4) if (s.data[i + 3] >= 128 && !dark(s.data[i], s.data[i + 1], s.data[i + 2])) opaque.push([s.data[i], s.data[i + 1], s.data[i + 2]]); + const pal = opaque.length ? quantize(opaque, FREE.length) : []; + transpIdx = 0; + palBlock = new Uint8Array(32); + w16(palBlock, 0, 0x07e0); w16(palBlock, 2, 0x000c); + pal.forEach((c, k) => w16(palBlock, 2 * FREE[k], rgbTo565(c[0], c[1], c[2]))); + const cache = new Map(); + indexOf = (p) => { + if (p[3] < 128) return 0; + if (dark(p[0], p[1], p[2]) || !pal.length) return 1; + const key = (p[0] << 16) | (p[1] << 8) | p[2]; + let v = cache.get(key); + if (v === undefined) { v = FREE[nearestIndex(pal, p[0], p[1], p[2], -1)]; cache.set(key, v); } + return v; + }; + } else { + const useT = origTransp || anyTransparent; + const opaque = []; + for (const s of subs) for (let i = 0; i < s.data.length; i += 4) if (!useT || s.data[i + 3] >= 128) opaque.push([s.data[i], s.data[i + 1], s.data[i + 2]]); + let maxBits = BITS[bpp]; + if (opts.allowMoreColors) maxBits = Math.max(maxBits, 8); + const avail = (1 << maxBits) - (useT ? 1 : 0); + let pal = opaque.length ? quantize(opaque, avail) : [[0, 0, 0]]; + let bits = BITS[bpp]; + while ((1 << bits) - (useT ? 1 : 0) < pal.length && bits < 8) bits *= 2; + bpp = { 1: 0, 2: 1, 4: 2, 8: 3 }[bits]; + const ncol = 1 << bits; + transpIdx = useT ? 0 : -1; + const full = useT ? [[0, 0, 0], ...pal] : pal.slice(); + while (full.length < ncol) full.push([0, 0, 0]); + palBlock = new Uint8Array(2 * ncol); + full.forEach((c, i) => w16(palBlock, 2 * i, rgbTo565(c[0], c[1], c[2]))); + if (useT) w16(palBlock, 0, 0x07e0); // like the originals: slot 0 holds the colour key + const cache = new Map(); + const palIdx = useT ? full.slice(1, pal.length + 1) : full.slice(0, pal.length); + indexOf = (p) => { + if (useT && p[3] < 128) return 0; + const key = (p[0] << 16) | (p[1] << 8) | p[2]; + let v = cache.get(key); + if (v === undefined) { v = nearestIndex(palIdx, p[0], p[1], p[2], -1) + (useT ? 1 : 0); cache.set(key, v); } + return v; + }; + } + + const bits = BITS[bpp]; + const datas = []; + forEachCell((si, gx, gy) => { + const raw = new Uint8Array(Math.ceil(npx * bits / 8)); + for (let k = 0; k < npx; k++) { + const v = indexOf(cellRGBA(si, gx, gy, k)); + const bit = k * bits; raw[bit >> 3] |= v << (bit & 7); + } + datas.push(rleEncode(raw).map(x => x ^ 0x53)); + }); + const palOff = 24, pixOff = palOff + palBlock.length, tblLen = 8 * n; + let pos = pixOff + tblLen; const tbl = [], body = []; + for (const d of datas) { + const pad = (4 - pos % 4) % 4; if (pad) { body.push(new Uint8Array(pad)); pos += pad; } + tbl.push([pos - pixOff, d.length]); body.push(d); pos += d.length; + } + // 1.7.3 test21 SPR_ALIGN: the length a multiple of 4 like every original. The playdate sends the Tama's own pictures + // and sums them up in 32-bit words: an odd length (own pictures) made the other Paradise refuse it at about 90 %. + if (SPR_ALIGN) pos = (pos + 3) & ~3; + const out = new Uint8Array(pos); + const useT = transpIdx >= 0; + writeHeader(out, { dataLength: pos, flags: F_XOR | F_RLE_BYTE | 0x03 | (useT ? F_TRANSP : 0), bpp, numSprites: n, sw: w, sh: hh, ox: h.ox, oy: h.oy, iw: h.iw, ih: h.ih, palBpp: 0x11, numPal: keep ? Math.max(1, h.numPal) : 1, transp: useT ? transpIdx : 0, palOffset: palOff, pixOffset: pixOff }); + out.set(palBlock, palOff); + tbl.forEach((t, i) => { w32(out, pixOff + 8 * i, t[0]); w32(out, pixOff + 8 * i + 4, t[1]); }); + out.set(concat(body), pixOff + tblLen); + if (opts.keepLength) { + // Eye sprites: the game checks their byte length (a different length makes + // a substitute character hatch). Pad with zeros to the original length. + if (out.length > orig.length) throw new Error('eye image too detailed: ' + out.length + ' bytes, at most ' + orig.length + ' allowed'); + const padded = new Uint8Array(orig.length); padded.set(out); w32(padded, 0, orig.length); + return padded; + } + return out; +} +const SPR_ALIGN = true; +/* 1.7.3 test25 FIG_NOVAR: an own picture whose colours all exist in the original palette kept that palette, also for + * colours that sit in slots 2-7. The game recolours those per Tama (colour, field), so the small Tama on the field + * showed fewer colours or a red tint (Glacier: Icy Irukatchi, Ginjirotchi, Yukiraratchi). Those slots are left out. */ +const FIG_NOVAR = true; +/** SPR_ALIGN: a character picture with a length that is not a multiple of 4 (own pictures before 1.7.3 test21), + * padded with zeros; null when it is fine. */ +function spriteAlign(e) { + if (!SPR_ALIGN || !e || e.length < 24) return null; + const n = u32(e, 0); if (!(n & 3) || n < 24 || n > e.length + 3) return null; // the stored entry may already be padded + const out = new Uint8Array((n + 3) & ~3); out.set(e.subarray(0, Math.min(n, out.length))); w32(out, 0, out.length); return out; +} +function writeHeader(b, h) { + w32(b, 0, h.dataLength); b[4] = h.flags; b[5] = h.bpp; w16(b, 6, h.numSprites); b[8] = h.sw; b[9] = h.sh; + b[10] = h.ox & 255; b[11] = h.oy & 255; b[12] = h.iw; b[13] = h.ih; b[14] = h.palBpp; b[15] = h.numPal; + w16(b, 16, h.transp); w16(b, 18, h.palOffset); w16(b, 20, h.pixOffset); w16(b, 22, 0); +} +/** Same format as `orig`, all pixels transparent. */ +function spriteBlank(orig, opts = {}) { + const d = spriteDecode(orig); + const subs = d.subs.map(s => ({ w: s.w, h: s.h, data: new Uint8ClampedArray(s.w * s.h * 4) })); + return spriteEncode(orig, subs, opts); +} +/** Smallest image with the same frame (count, cell size, grid, anchor): 1 bit, all cells share one + * run-length stream. Transparent originals stay transparent, the others become black (launcher ROM, 1.6.8). */ +function spriteTiny(orig) { + const h = spriteHeader(orig), n = h.numSprites, npx = h.sw * h.sh; + const tr = !!(h.flags & F_TRANSP); + const d = rleEncode(new Uint8Array(Math.ceil(npx / 8))).map(x => x ^ 0x53); + const palOff = 24, pixOff = palOff + 4, dataOff = pixOff + 8 * n; + const len = dataOff + d.length, pos = (len + 3) & ~3; + const out = new Uint8Array(pos); + writeHeader(out, { dataLength: pos, flags: F_XOR | F_RLE_BYTE | 0x03 | (tr ? F_TRANSP : 0), bpp: 0, numSprites: n, sw: h.sw, sh: h.sh, ox: h.ox, oy: h.oy, iw: h.iw, ih: h.ih, palBpp: 0x11, numPal: 1, transp: 0, palOffset: palOff, pixOffset: pixOff }); + w16(out, palOff, tr ? 0x07e0 : 0); w16(out, palOff + 2, 0); + for (let i = 0; i < n; i++) { w32(out, pixOff + 8 * i, dataOff - pixOff); w32(out, pixOff + 8 * i + 4, d.length); } + out.set(d, dataOff); + return out; +} +/** Encoding options for part k (0..5) of a character group. */ +function partOptions(k, extra = {}) { return Object.assign({ figure: true, keepLength: k === 1 || k === 4 }, extra); } + +// ------------------------------------------------------- character groups +// One character = 6 consecutive sprites: body, eyes, mouth (large) and the same small. +const GROUP_PARTS = [ + { key: 'body', w: 64, h: 64, n: 20 }, { key: 'eyes', w: 64, h: 32, n: 20 }, { key: 'mouth', w: 64, h: 32, n: 18 }, + { key: 'body_s', w: 32, h: 32, n: 24 }, { key: 'eyes_s', w: 32, h: 16, n: 14 }, { key: 'mouth_s', w: 32, h: 16, n: 14 }, +]; +function findGroups(entries) { + const out = []; + for (let i = 0; i + 5 < entries.length; i++) { + let ok = true; + for (let k = 0; k < 6 && ok; k++) { + const h = spriteHeader(entries[i + k]), p = GROUP_PARTS[k]; + ok = h.sw === p.w && h.sh === p.h && h.numSprites === p.n && h.bpp <= 3; + } + if (ok) out.push(i); + } + return out; +} + +/** Egg: small (32x32, 5 frames) at i, big (64x64, 5 frames) at i+3. -1 if not found. */ +// Baby, child and teen share inherited eye images, adults have their own. Anchor: the eye +// image of the first adult, identical in all six editions. +const ADULT_EYE_CRC = 2777596871; +function eyeSig(e) { + const subs = spriteDecode(e).subs; let n = 0; for (const x of subs) n += x.data.length; + const b = new Uint8Array(n); let o = 0; for (const x of subs) { b.set(x.data, o); o += x.data.length; } + return crc32(b) >>> 0; +} +function findFirstAdult(entries, groups) { + const sigs = groups.map(g => { try { return eyeSig(entries[g + 1]); } catch (e) { return -1; } }); + const i = sigs.indexOf(ADULT_EYE_CRC); + if (i >= 0) return groups[i]; + let last = 0; sigs.forEach((x, k) => { if (k > 0 && sigs.indexOf(x) !== sigs.lastIndexOf(x)) last = k; }); + return groups[Math.min(groups.length - 1, last + 1)]; +} +function findEgg(entries) { + for (let i = 0; i + 3 < entries.length; i++) { + const a = spriteHeader(entries[i]), b = spriteHeader(entries[i + 3]); + if (a.sw === 32 && a.sh === 32 && a.numSprites === 5 && b.sw === 64 && b.sh === 64 && b.numSprites === 5) return i; + } + return -1; +} + +// ------------------------------------------------------- launcher ROM (1.6.8) +/* + * "Start device only": the Paradise keeps its setup (language, clock, birthday, continue or reset, + * planet name), everything else becomes the smallest possible image of the same frame, so the room + * goes to the programs. Kept: every image before the first character set (screens, buttons, frames) + * and the pictures the setup and its intro showed in the Paradise emulator (Land), found by content in + * every edition. + */ +const LAUNCH_KEEP_CRC = [0xe73bd469, 0x287aa401, 0xce0a2a87, 0x1d427953, 0x70c4b300, 0x5ebe8cc7, 0x5fe0481b, 0xb5b75196, + 0x53ff02fb, 0x9e3c2e47, 0x1d2e4d3e, 0x786d7183, 0x7bc20923, 0xc6e5b7b7, 0xf5e876d9, 0x3a8acbb5, 0x615b997e, 0x6c829b75, + 0xc5f0155f, 0xbff645c6, 0x4efa5d79, 0x5112672d, 0x8178c20b, 0xe56b3533, 0x0d47aefd, 0xa81e4c59, 0xfbaeefa0, 0x73b23e63]; +function launcherKeep(ctx) { + const first = ctx.groups.length ? ctx.groups[0] : 0, crcs = new Set(LAUNCH_KEEP_CRC), keep = new Set(); + for (let i = 0; i < first; i++) keep.add(i); + ctx.entries.forEach((e, i) => { if (crcs.has(crc32(e))) keep.add(i); }); + return keep; +} +/** Changed entries for a launcher ROM: Map index -> tiny image (only where it saves room). */ +function launcherChanges(ctx) { + const keep = launcherKeep(ctx), out = new Map(); + ctx.entries.forEach((e, i) => { if (keep.has(i)) return; let t; try { t = spriteTiny(e); } catch (x) { return; } if (t.length < e.length) out.set(i, t); }); + return out; +} +/** Is this ROM already a launcher ROM (most images outside the kept set are tiny)? */ +function isLauncher(ctx) { + const keep = launcherKeep(ctx); let n = 0, tiny = 0; + ctx.entries.forEach((e, i) => { if (keep.has(i)) return; n++; const h = spriteHeader(e); if (h.bpp === 0 && e.length <= 64 + 8 * h.numSprites) tiny++; }); + return n > 0 && tiny * 10 >= n * 9; +} + +// ------------------------------------------------------------------ ROM +function openRom(rom) { + if (rom.length < ASSET_BASE + 16 || String.fromCharCode(...rom.subarray(0, 8)) !== 'SONIXDEV') throw new Error('not a Paradise flash dump (SONIXDEV header missing)'); + const root = arc2Parse(rom, ASSET_BASE); + if (root.ents.length !== 3) throw new Error('unexpected asset archive (' + root.ents.length + ' files)'); + const files = arc2Files(rom, ASSET_BASE); + const entries = packSplit(files[1]); + const end = ASSET_BASE + 16 + root.length; + // free space ends at the first used 4 KB page after the assets (version page / user data) + let limit = (end + 0xfff) & ~0xfff; + const page = (p) => { for (let i = p; i < p + 0x1000 && i < rom.length; i++) if (rom[i] !== 0xff) return false; return true; }; + while (limit < rom.length && page(limit)) limit += 0x1000; + // Edition ID: on its own page (0xD49000, Tropical/Glacier 0xD29000). Previously the first + // used page after the characters, which went wrong with DOOM or save slots next to it. + let editionId = editionIdOf(rom); + if (!editionId) editionId = limit < rom.length ? u32(rom, limit) : 0; + const groups = findGroups(entries); + return { rom, root, files, entries, groups, adult: groups.length ? findFirstAdult(entries, groups) : -1, egg: findEgg(entries), assetEnd: end, limit, editionId, edition: EDITIONS[editionId] || ('Edition ' + editionId) }; +} +/** New ROM with replaced sprite entries. `changed`: Map index -> Uint8Array. */ +function buildRom(ctx, changed, dataPack) { + const entries = ctx.entries.map((e, i) => changed.has(i) ? changed.get(i) : e); + const files = [dataPack || ctx.files[0], packJoin(entries), ctx.files[2]]; + const root = arc2Build(files); + const end = ASSET_BASE + root.length; + if (end > ctx.limit) throw new Error('too big: assets would end at 0x' + end.toString(16) + ', free space ends at 0x' + ctx.limit.toString(16)); + const out = ctx.rom.slice(); + out.set(root, ASSET_BASE); + if (end < ctx.assetEnd) out.fill(0xff, end, ctx.assetEnd); + verifyRom(out, [...changed.keys()]); + return { rom: out, assetEnd: end, free: ctx.limit - end }; +} +function verifyRom(rom, indices) { + const check = (off) => { + const a = arc2Parse(rom, off); + if (arc2Checksum(rom, off, a.length) !== a.chk) throw new Error('checksum wrong at 0x' + off.toString(16)); + for (const e of a.ents) if (u32(rom, off + e.offset) === ARC2_MAGIC) check(off + e.offset); + }; + check(ASSET_BASE); + const entries = packSplit(arc2Files(rom, ASSET_BASE)[1]); + for (const i of indices) spriteDecode(entries[i]); + return true; +} + +// ------------------------------------------------------------- sheets +// Sheet of one sprite: subimages left to right, wrapping, no gaps. +function sheetLayout(w, h, n) { + const cols = Math.max(1, Math.min(n, Math.floor(1280 / w) || 1)); + return { cols, rows: Math.ceil(n / cols), w, h }; +} +function sheetFromSubs(subs) { + const L = sheetLayout(subs[0].w, subs[0].h, subs.length); + const W = L.cols * L.w, H = L.rows * L.h, px = new Uint8ClampedArray(W * H * 4); + subs.forEach((s, i) => blit(px, W, s, (i % L.cols) * L.w, ((i / L.cols) | 0) * L.h)); + return { w: W, h: H, data: px }; +} +function subsFromSheet(img, w, h, n) { + const L = sheetLayout(w, h, n); + if (img.w !== L.cols * w || img.h !== L.rows * h) throw new Error('sheet must be ' + L.cols * w + 'x' + L.rows * h + ' px, got ' + img.w + 'x' + img.h); + const out = []; + for (let i = 0; i < n; i++) out.push(crop(img, (i % L.cols) * w, ((i / L.cols) | 0) * h, w, h)); + return out; +} +// Character sheet: the 6 parts as rows, cells at fixed positions. +const GROUP_SHEET_W = 1280, GROUP_ROWS_Y = [0, 64, 96, 128, 160, 176], GROUP_SHEET_H = 192; +function groupSheet(parts) { // parts: 6 arrays of subimages + const px = new Uint8ClampedArray(GROUP_SHEET_W * GROUP_SHEET_H * 4); + parts.forEach((subs, k) => subs.forEach((s, i) => blit(px, GROUP_SHEET_W, s, i * GROUP_PARTS[k].w, GROUP_ROWS_Y[k]))); + return { w: GROUP_SHEET_W, h: GROUP_SHEET_H, data: px }; +} +function groupFromSheet(img) { + if (img.w !== GROUP_SHEET_W || img.h !== GROUP_SHEET_H) throw new Error('character sheet must be ' + GROUP_SHEET_W + 'x' + GROUP_SHEET_H + ' px, got ' + img.w + 'x' + img.h); + return GROUP_PARTS.map((p, k) => { const a = []; for (let i = 0; i < p.n; i++) a.push(crop(img, i * p.w, GROUP_ROWS_Y[k], p.w, p.h)); return a; }); +} +function blit(dst, DW, s, x0, y0) { + for (let y = 0; y < s.h; y++) dst.set(s.data.subarray(y * s.w * 4, (y + 1) * s.w * 4), ((y0 + y) * DW + x0) * 4); +} +function crop(img, x0, y0, w, h) { + const px = new Uint8ClampedArray(w * h * 4); + for (let y = 0; y < h; y++) px.set(img.data.subarray(((y0 + y) * img.w + x0) * 4, ((y0 + y) * img.w + x0 + w) * 4), y * w * 4); + return { w, h, data: px }; +} +function emptyImage(w, h) { return { w, h, data: new Uint8ClampedArray(w * h * 4) }; } +function sameImage(a, b) { if (a.w !== b.w || a.h !== b.h) return false; for (let i = 0; i < a.data.length; i += 4) { if (a.data[i + 3] < 128 && b.data[i + 3] < 128) continue; for (let k = 0; k < 4; k++) if (Math.abs(a.data[i + k] - b.data[i + k]) > 4) return false; } return true; } + +// --------------------------------------------------------------- character card +const DIM_DIMS = { 3528: [42, 42], 25600: [80, 160], 2560: [32, 40], 2400: [80, 15], 4800: [160, 15], 1536: [32, 24], 7168: [64, 56] }; +const DIM_POSES = ['idle1', 'idle2', 'walk1', 'walk2', 'run1', 'run2', 'train1', 'train2', 'happy', 'sleep', 'attack', 'dodge']; +const DIM_BABY_POSES = ['idle1', 'idle2', 'happy', 'attack', 'sleep']; +function dimLoad(raw) { + const d = raw.map(b => b ^ 0xff); + const b = 0x100000; + if (String.fromCharCode(...d.subarray(b, b + 8)) !== 'GP_SPIFI') throw new Error('no sprite package'); + const n = u32(d, b + 0x48), offs = []; + for (let i = 0; i <= n; i++) offs.push(u32(d, b + 0x4c + 4 * i)); + const sprites = []; + for (let i = 0; i < n; i++) { + const dims = DIM_DIMS[offs[i + 1] - offs[i]]; if (!dims) { sprites.push(null); continue; } + const [w, h] = dims, o = b + offs[i], px = new Uint8ClampedArray(w * h * 4); + for (let k = 0; k < w * h; k++) { + const v = u16(d, o + 2 * k); if (v === 0x07e0) continue; + const c = rgb565ToRgb(v); px.set([c[0], c[1], c[2], 255], 4 * k); + } + sprites.push({ w, h, data: px }); + } + const isSize = (s, w, h) => s && s.w === w && s.h === h; + const chars = []; let i = 0; + while (i < n) { + const s = sprites[i]; + if (isSize(s, 80, 15) || isSize(s, 160, 15)) { + let j = i + 1; const frames = []; + while (j < n && (isSize(sprites[j], 32, 24) || isSize(sprites[j], 64, 56))) frames.push(sprites[j++]); + if (j < n && isSize(sprites[j], 80, 160)) j++; + const baby = frames.length > 0 && frames[0].w === 32; + const poses = baby ? DIM_BABY_POSES : DIM_POSES, f = {}; + frames.forEach((im, k) => { if (poses[k]) f[poses[k]] = im; }); + if (frames.length) chars.push({ index: chars.length, name: s, baby, frames: f }); + i = j; + } else i++; + } + const eggs = sprites.slice(0, 24).filter(s => isSize(s, 32, 40)); + return { chars, eggs }; +} + +// ------------------------------------------------------------ TamaSma cards (1.6.8) +/* + * Character cards of the Tamagotchi Smart (1 or 2 MB). Header at 0x10 "BANDAINTPD...TAMASUMA"; at 0x1000 the list + * of packs (u16 0x3232, u16 count, then 16 bytes each: offset at +8, size at +16, from 0x1000). Pack 0: data (20 + * tables, offsets in u16 units), pack 1: pictures (offsets of image sets, sprites, colours, pixels). + * Image set: first sprite u16, width and height in sprites u8 u8, first colour / 4 u16. Sprite: pixel index u16, + * x and y offset i16 (centre), properties u16 (bits 0-1 bpp 2/4/6/8, 4-5 width 8..64, 6-7 height, 15 four times). + * Pixels MSB first, index * sprite bytes. Colours 15 bit, bit 15 = transparent. + * Characters (table 11, 96 bytes): id, type (1 egg, 2 baby, 3 child, 4 teen, 5 adult, 6 other), frame group at +28. + * Frame groups (table 18): 53 frames of 4 bytes (first layer, count; 0xFFFF = none). Layers (table 15): a mask of + * which u16 follow (bit 0 x, 1 y, 2 sub-image, 4, 5, 8 unknown, 9 type, 10 image id). Image ids with bit 15 are + * on the card (low byte = image set), others are in the toy (accessories): left out. Type 3 body, 1 face. + */ +function smaDetect(raw) { return raw.length >= 0x1100 && String.fromCharCode(...raw.subarray(0x10, 0x1A)) === 'BANDAINTPD' && String.fromCharCode(...raw.subarray(0x20, 0x28)) === 'TAMASUMA'; } +const SMA_POSES = { idle1: 1, idle2: 2, happy: 3, walk1: 22, walk2: 23, run1: 22, run2: 23, train1: 11, train2: 12, sleep: 1, attack: 11, dodge: 7 }; +function smaLoad(raw) { + if (!smaDetect(raw)) throw new Error('no TamaSma card'); + const d = raw, B = 0x1000, s16 = (o) => { const v = u16(d, o); return v > 32767 ? v - 65536 : v; }; + if (u16(d, B) !== 0x3232) throw new Error('no pack list'); + const dp = B + u32(d, B + 8), sp = B + u32(d, B + 24); + const to = []; for (let i = 0; i < 20; i++) to.push(dp + u32(d, dp + 4 * i) * 2); + const tab = (i) => [to[i], to[i + 1] - to[i]]; + // pictures + const [io, so, po, xo] = [0, 4, 8, 12].map((k) => sp + u32(d, sp + k)); + const sprites = []; + for (let o = so; o + 8 <= po; o += 8) { + const pr = u16(d, o + 6), q = pr >> 15, bpp = [2, 4, 6, 8][pr & 3]; + const w = [8, 16, 32, 64][(pr >> 4) & 3] * (q ? 4 : 1), h = [8, 16, 32, 64][(pr >> 6) & 3] * (q ? 4 : 1); + sprites.push({ idx: u16(d, o), ox: s16(o + 2), oy: s16(o + 4), bpp, w, h }); + } + const sets = []; for (let o = io; o + 6 <= so; o += 6) sets.push({ fs: u16(d, o), ws: d[o + 2], hs: d[o + 3], pal: u16(d, o + 4) }); + const colour = (i) => u16(d, po + 2 * i); + const cache = new Map(); + const subimage = (si, sub) => { + const key = si * 4096 + sub; if (cache.has(key)) return cache.get(key); + const st = sets[si]; if (!st) return null; + const s0 = sprites[st.fs]; if (!s0) return null; + const W = st.ws * s0.w, H = st.hs * s0.h, img = emptyImage(W, H), first = st.fs + sub * st.ws * st.hs; + for (let r = 0; r < st.hs; r++) for (let c = 0; c < st.ws; c++) { + const sp1 = sprites[first + r * st.ws + c]; if (!sp1) return null; + const n = sp1.w * sp1.h * sp1.bpp / 8, base = xo + sp1.idx * n; + for (let i = 0; i < sp1.w * sp1.h; i++) { + const bit = i * sp1.bpp; let v = 0; + for (let k = 0; k < sp1.bpp; k++) { const b = bit + k; v = (v << 1) | ((d[base + (b >> 3)] >> (7 - (b & 7))) & 1); } + const col = colour(st.pal * 4 + v); if (col >> 15) continue; + const o = ((r * sp1.h + ((i / sp1.w) | 0)) * W + c * sp1.w + (i % sp1.w)) * 4; + img.data.set([((col >> 10) & 31) << 3, ((col >> 5) & 31) << 3, (col & 31) << 3, 255], o); + } + } + const f = sprites[first], res = { img, ox: f.ox - (s0.w >> 1), oy: f.oy - (s0.h >> 1) }; + cache.set(key, res); return res; + }; + // frames + const [lo, ls] = tab(15), layers = []; + for (let i = 0; i + 2 <= ls;) { + const m = u16(d, lo + i), L = { x: 0, y: 0, sub: 0, type: 0, img: 0 }; + for (const [bit, key] of [[0, 'x'], [1, 'y'], [2, 'sub'], [4, ''], [5, ''], [8, ''], [9, 'type'], [10, 'img']]) { + if (!(m & (1 << bit))) continue; + i += 2; if (key) L[key] = key === 'x' || key === 'y' ? s16(lo + i) : u16(d, lo + i); + } + layers.push(L); i += 2; + } + const [fo, fsz] = tab(18), frames = []; + for (let k = 0; k + 4 <= fsz; k += 4) { const li = u16(d, fo + k), n = u16(d, fo + k + 2); frames.push(li === 0xFFFF ? null : layers.slice(li, li + n)); } + const render = (f) => { + const can = emptyImage(128, 128); + for (const L of f || []) { + if (!(L.img & 0x8000) || (L.type !== 1 && L.type !== 3)) continue; + const si = subimage(L.img & 0xFF, L.sub); if (!si) continue; + const x0 = 64 + L.x + si.ox, y0 = 100 + L.y + si.oy; + for (let y = 0; y < si.img.h; y++) for (let x = 0; x < si.img.w; x++) { + const s = (y * si.img.w + x) * 4; if (!si.img.data[s + 3]) continue; + const X = x0 + x, Y = y0 + y; if (X < 0 || Y < 0 || X >= 128 || Y >= 128) continue; + can.data.set(si.img.data.subarray(s, s + 4), (Y * 128 + X) * 4); + } + } + return can; + }; + // characters + const [co, cs] = tab(11), chars = [], eggs = []; + for (let k = 0; k + 96 <= cs; k += 96) { + const type = u16(d, co + k + 2), grp = u16(d, co + k + 28) & 0xFF, fr = frames.slice(grp * 53, grp * 53 + 53); + if (type < 1 || type > 5 || !fr[1]) continue; + const imgs = {}; for (const [p, i] of Object.entries(SMA_POSES)) imgs[p] = render(fr[i] || fr[1]); + // one box around all poses, so they keep their place to each other + let bb = [128, 128, -1, -1]; + for (const im of Object.values(imgs)) for (let y = 0; y < 128; y++) for (let x = 0; x < 128; x++) if (im.data[(y * 128 + x) * 4 + 3]) { bb[0] = Math.min(bb[0], x); bb[1] = Math.min(bb[1], y); bb[2] = Math.max(bb[2], x); bb[3] = Math.max(bb[3], y); } + if (bb[2] < 0) continue; + const f = {}; for (const p in imgs) f[p] = crop(imgs[p], bb[0], bb[1], bb[2] - bb[0] + 1, bb[3] - bb[1] + 1); + if (type === 1) { eggs.push(place(f.idle1, 32, 40, 1)); continue; } + chars.push({ index: chars.length, name: null, baby: type === 2, stage: type, frames: f }); + } + return { chars, eggs, kind: 'sma' }; +} +const BODY_POSE_MAP = ['idle1', 'idle2', 'walk1', 'happy', 'idle1', 'walk2', 'idle2', 'idle1', 'happy', 'run1', 'run2', 'attack', 'train1', 'dodge', 'sleep', 'sleep', 'train2', 'dodge', 'idle1', 'idle2']; +const SMALL_POSE_MAP = ['idle1', 'idle2', 'walk1', 'idle1', 'idle2', 'happy', 'idle1', 'idle2', 'happy', 'idle1', 'walk1', 'walk2', 'attack', 'train1', 'walk1', 'walk2', 'idle1', 'walk1', 'idle2', 'walk2', 'sleep', 'sleep', 'happy', 'happy']; +const BABY_FALLBACK = { walk1: 'idle1', walk2: 'idle2', run1: 'idle1', run2: 'idle2', train1: 'attack', train2: 'idle2', dodge: 'idle2' }; +function pose(ch, name) { return ch.frames[name] || ch.frames[BABY_FALLBACK[name] || 'idle1'] || ch.frames.idle1; } +/** Scale (nearest up, box down) and place bottom-centred on a W x H canvas. */ +function place(img, W, H, scale, bottom) { + let s = img; + if (scale !== 1) { + const nw = Math.max(1, Math.round(img.w * scale)), nh = Math.max(1, Math.round(img.h * scale)), px = new Uint8ClampedArray(nw * nh * 4); + for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) { + const x0 = Math.floor(x / scale), y0 = Math.floor(y / scale), x1 = Math.max(x0 + 1, Math.floor((x + 1) / scale)), y1 = Math.max(y0 + 1, Math.floor((y + 1) / scale)); + let r = 0, g = 0, b = 0, a = 0, cnt = 0; + for (let yy = y0; yy < Math.min(y1, img.h); yy++) for (let xx = x0; xx < Math.min(x1, img.w); xx++) { + const o = (yy * img.w + xx) * 4; cnt++; const al = img.data[o + 3]; + a += al; r += img.data[o] * al; g += img.data[o + 1] * al; b += img.data[o + 2] * al; + } + const o = (y * nw + x) * 4; + if (cnt && a / cnt >= 110) { px[o] = r / a; px[o + 1] = g / a; px[o + 2] = b / a; px[o + 3] = 255; } + } + s = { w: nw, h: nh, data: px }; + } + if (s.w > W || s.h > H) { const f = Math.min(W / s.w, H / s.h); return place(s, W, H, f, bottom); } + const out = emptyImage(W, H); + blit(out.data, W, s, (W - s.w) >> 1, (bottom === undefined ? H : bottom) - s.h); + return out; +} +/** 6 parts for a character group from a card character. */ +/** Egg frames for the small and big egg sprite from a card (frames 0,1,4,6,7). */ +function dimEggSubs(eggs) { + const pick = [0, 1, 4, 6, 7].map(k => eggs[Math.min(k, eggs.length - 1)]); + return { small: pick.map(e => place(e, 32, 32, 0.625, 28)), big: pick.map(e => place(e, 64, 64, 1.25, 54)) }; +} +function dimCharParts(ch, bigScale, smallScale) { + if (bigScale === undefined) bigScale = ch.baby ? 2 : 1; + if (smallScale === undefined) smallScale = ch.baby ? 1 : 0.5; + const body = BODY_POSE_MAP.map(p => place(pose(ch, p), 64, 64, bigScale)); + const small = SMALL_POSE_MAP.map(p => place(pose(ch, p), 32, 32, smallScale)); + const blank = (k) => Array.from({ length: GROUP_PARTS[k].n }, () => emptyImage(GROUP_PARTS[k].w, GROUP_PARTS[k].h)); + return [body, blank(1), blank(2), small, blank(4), blank(5)]; +} + + +// ------------------------------------------------------------------ eyes +// The game draws the eyes as their own layer over the body, and also into the +// cell (deepest zoom). For a foreign character the eye is moved out of the body +// into that layer, and the layer is placed on the character's eye through the +// composite definitions in the data pack (5 x u16: sprite, flags, x, y, subimage; +// y is the bottom edge, x the centre). Expressions: open eye, closed = a line, +// '- -' (sleep) = empty. Measured in the emulator: hatch, field, zoom, cell. +const EYE_OPEN = new Set([0, 3, 4, 5, 8, 10, 11, 12, 15, 16, 17]), EYE_EMPTY = new Set([7, 19]); +const EYE_OPEN_S = new Set([0, 3, 5, 6, 9, 10, 11, 13]), EYE_EMPTY_S = new Set(); +const EYE_STEPS = [[EYE_OPEN, EYE_OPEN_S], [new Set([0, 3, 8, 12, 15, 16]), new Set([0, 5, 6, 13])], [new Set([0, 12]), new Set([0, 5, 13])], [new Set([0]), new Set([5, 13])]]; +const lum = (d, o) => (d[o] * 3 + d[o + 1] * 6 + d[o + 2]) / 10; +function pix(img, x, y) { const o = (y * img.w + x) * 4; return img.data.subarray(o, o + 4); } +function skinColor(img, r) { + const cnt = new Map(); + for (let y = r[1] - 2; y <= r[3] + 2; y++) for (let x = r[0] - 2; x <= r[2] + 2; x++) { + if (x >= r[0] && x <= r[2] && y >= r[1] && y <= r[3]) continue; + if (x < 0 || y < 0 || x >= img.w || y >= img.h) continue; + const c = pix(img, x, y); if (c[3] < 128 || lum(c, 0) <= 70) continue; + const k = (c[0] << 16) | (c[1] << 8) | c[2]; cnt.set(k, (cnt.get(k) || 0) + 1); + } + let best = 0, bk = 0; for (const [k, n] of cnt) if (n > best) { best = n; bk = k; } + return best ? [(bk >> 16) & 255, (bk >> 8) & 255, bk & 255] : [0, 0, 0]; +} +function cloneImg(img) { return { w: img.w, h: img.h, data: new Uint8ClampedArray(img.data) }; } +function inpaint(dst, src, r) { + const skin = skinColor(src, r); + const ok = (c) => c[3] >= 128 && lum(c, 0) > 70 && Math.abs(c[0] - skin[0]) + Math.abs(c[1] - skin[1]) + Math.abs(c[2] - skin[2]) < 120; + for (let y = r[1]; y <= r[3]; y++) for (let x = r[0]; x <= r[2]; x++) { + if (pix(src, x, y)[3] < 128) continue; + let best = null; + for (let d = 1; d < 12 && !best; d++) for (const [xx, yy] of [[r[0] - d, y], [r[2] + d, y], [x, r[1] - d], [x, r[3] + d]]) { + if (xx < 0 || yy < 0 || xx >= src.w || yy >= src.h) continue; + const c = pix(src, xx, yy); if (ok(c)) { best = c; break; } + } + const o = (y * dst.w + x) * 4; const c = best || [skin[0], skin[1], skin[2], 255]; + dst.data[o] = c[0]; dst.data[o + 1] = c[1]; dst.data[o + 2] = c[2]; dst.data[o + 3] = 255; + } +} +function findTemplate(img, tmpl, ax, ay, radius) { + let best = null; + for (let dy = -radius; dy <= radius; dy++) for (let dx = -radius; dx <= radius; dx++) { + const x0 = ax + dx, y0 = ay + dy; + if (x0 < 0 || y0 < 0 || x0 + tmpl.w > img.w || y0 + tmpl.h > img.h) continue; + let err = 0; + for (let y = 0; y < tmpl.h; y++) for (let x = 0; x < tmpl.w; x++) { + const a = pix(tmpl, x, y), b = pix(img, x0 + x, y0 + y); + if (a[3] < 128 && b[3] < 128) continue; + if ((a[3] < 128) !== (b[3] < 128)) { err++; continue; } + if (Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2]) > 60) err++; + } + if (!best || err < best[2]) best = [x0, y0, err]; + } + return best; +} +function shiftImg(img, dx, dy) { + if (!dx && !dy) return img; + const out = emptyImage(img.w, img.h); + for (let y = 0; y < img.h; y++) for (let x = 0; x < img.w; x++) { + const xx = x + dx, yy = y + dy; if (xx < 0 || yy < 0 || xx >= img.w || yy >= img.h) continue; + out.data.set(pix(img, x, y), (yy * img.w + xx) * 4); + } + return out; +} +/** Remove the eye (rect in the idle1 frame) from every pose, return frames and the eye patches. */ +function dimRemoveEye(ch, r) { + const idle = ch.frames.idle1; + const tmpl = crop(idle, r[0], r[1], r[2] - r[0] + 1, r[3] - r[1] + 1); + const frames = {}; + for (const [name, im] of Object.entries(ch.frames)) { + const hit = findTemplate(im, tmpl, r[0], r[1], 6); + let im2 = im; + if (hit && hit[2] <= tmpl.w * tmpl.h * 0.25) { + im2 = cloneImg(im); + inpaint(im2, im, [hit[0], hit[1], hit[0] + tmpl.w - 1, hit[1] + tmpl.h - 1]); + im2 = shiftImg(im2, r[0] - hit[0], r[1] - hit[1]); + } + frames[name] = im2; + } + const skin = skinColor(idle, r); + const open = emptyImage(idle.w, idle.h), closed = emptyImage(idle.w, idle.h); + for (let y = r[1]; y <= r[3]; y++) for (let x = r[0]; x <= r[2]; x++) { + const c = pix(idle, x, y); + if (c[3] >= 128 && Math.abs(c[0] - skin[0]) + Math.abs(c[1] - skin[1]) + Math.abs(c[2] - skin[2]) > 60) open.data.set(c, (y * idle.w + x) * 4); + } + const mid = ((r[1] + r[3]) >> 1) + 1; + for (let x = r[0] + 1; x < r[2]; x++) if (pix(idle, x, mid)[3] >= 128) closed.data.set([16, 16, 24, 255], (mid * idle.w + x) * 4); + return { ch: Object.assign({}, ch, { frames }), open, closed }; +} +/** Guess the eye: bright pixel next to dark ones in the upper part. Returns a rect or null. */ +function dimGuessEye(ch) { + const im = ch.frames.idle1; let bb = [im.w, im.h, -1, -1]; + for (let y = 0; y < im.h; y++) for (let x = 0; x < im.w; x++) if (pix(im, x, y)[3] >= 128) { bb[0] = Math.min(bb[0], x); bb[1] = Math.min(bb[1], y); bb[2] = Math.max(bb[2], x); bb[3] = Math.max(bb[3], y); } + if (bb[2] < 0) return null; + let best = null; + for (let y = bb[1]; y < bb[1] + (bb[3] - bb[1]) * 0.6; y++) for (let x = bb[0]; x <= bb[2]; x++) { + const c = pix(im, x, y); if (c[3] < 128 || lum(c, 0) < 200) continue; + let dark = 0; + for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) { const xx = x + dx, yy = y + dy; if (xx < 0 || yy < 0 || xx >= im.w || yy >= im.h) continue; const q = pix(im, xx, yy); if (q[3] >= 128 && lum(q, 0) < 60) dark++; } + const score = dark * 2 - (y - bb[1]) * 0.2; + if (dark >= 2 && (!best || score > best[0])) best = [score, x, y]; + } + return best ? eyeRectAt(ch, best[1], best[2]) : null; +} +/** Rect around the eye at (x, y): all non-skin pixels within 5 px. */ +function eyeRectAt(ch, x, y) { + const im = ch.frames.idle1; const r0 = [x - 1, y - 1, x + 1, y + 1]; const skin = skinColor(im, [x - 4, y - 4, x + 4, y + 4]); + let r = [x, y, x, y]; + for (let yy = Math.max(0, y - 5); yy <= Math.min(im.h - 1, y + 5); yy++) for (let xx = Math.max(0, x - 5); xx <= Math.min(im.w - 1, x + 5); xx++) { + const c = pix(im, xx, yy); if (c[3] < 128) continue; + if (Math.abs(c[0] - skin[0]) + Math.abs(c[1] - skin[1]) + Math.abs(c[2] - skin[2]) > 60) { r[0] = Math.min(r[0], xx); r[1] = Math.min(r[1], yy); r[2] = Math.max(r[2], xx); r[3] = Math.max(r[3], yy); } + } + void r0; + return r; +} +/** Character parts with eye layer. Returns {parts, eyeBig:[dx,top], eyeSmall:[dx,top]} or null. */ +function dimCharPartsWithEyes(ch, rect, bigScale, smallScale) { + if (bigScale === undefined) bigScale = ch.baby ? 2 : 1; + if (smallScale === undefined) smallScale = ch.baby ? 1 : 0.5; + const rm = dimRemoveEye(ch, rect); + const mask = emptyImage(ch.frames.idle1.w, ch.frames.idle1.h); + for (let y = rect[1]; y <= rect[3]; y++) for (let x = rect[0]; x <= rect[2]; x++) mask.data.set([255, 255, 255, 255], (y * mask.w + x) * 4); + const one = (W, H, eyeH, scale, poses, n, openSet, emptySet) => { + const m = place(mask, W, H, scale); let bb = [W, H, -1, -1]; + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) if (m.data[(y * W + x) * 4 + 3]) { bb[0] = Math.min(bb[0], x); bb[1] = Math.min(bb[1], y); bb[2] = Math.max(bb[2], x); bb[3] = Math.max(bb[3], y); } + if (bb[2] < 0) return null; + const top = Math.max(0, Math.min(H - eyeH, bb[1] - (eyeH >> 2))); + let dx = ((bb[0] + bb[2] + 1) >> 1) - (W >> 1); + if ((bb[0] - dx) & 1) dx += 1; // even start column packs better (4 bpp) + const body = poses.map(p => place(pose(rm.ch, p), W, H, scale)); + const layer = (patch) => crop(shiftImg(place(patch, W, H, scale), -dx, 0), 0, top, W, eyeH); + const lo = layer(rm.open), lc = layer(rm.closed), em = emptyImage(W, eyeH); + const eyes = Array.from({ length: n }, (_, j) => emptySet.has(j) ? em : (openSet.has(j) ? lo : lc)); + return { body, eyes, lo, lc, em, off: [dx, top] }; + }; + const big = one(64, 64, 32, bigScale, BODY_POSE_MAP, 20, EYE_OPEN, EYE_EMPTY); + const small = one(32, 32, 16, smallScale, SMALL_POSE_MAP, 14, EYE_OPEN_S, EYE_EMPTY_S); + if (!big || !small) return null; + const blank = (k) => Array.from({ length: GROUP_PARTS[k].n }, () => emptyImage(GROUP_PARTS[k].w, GROUP_PARTS[k].h)); + return { parts: [big.body, big.eyes, blank(2), small.body, small.eyes, blank(5)], eyeBig: big.off, eyeSmall: small.off, big, small }; +} +/** Fewer open expressions until the eye sprite fits its original byte length. */ +function eyeVariants(layer, isBig) { + const n = isBig ? 20 : 14, empty = isBig ? EYE_EMPTY : EYE_EMPTY_S; + return EYE_STEPS.map(st => Array.from({ length: n }, (_, j) => empty.has(j) ? layer.em : (st[isBig ? 0 : 1].has(j) ? layer.lo : layer.lc))); +} +const s16v = (v) => (v > 32767 ? v - 65536 : v); +/* 1.6.8 (EYE_V2): the layer table of the data pack read the way the game reads it. A layer is a mask word, then one + * word per set bit (0 x, 1 y, 2 sub-image, 3..8 other, 9 type, 10 picture), the picture comes last. x and y are the + * centre of the picture. Frames (table 18) point into it. The old scan took the word after the picture as the start + * of its fields, which are those of the next layer (eyes moved the mouth). EYE_V2 = false brings the old way back. */ +const EYE_V2 = true; +function paraLayers(dp) { + try { + const u = (o) => dp[o] | (dp[o + 1] << 8), U = (o) => (u(o) | (u(o + 2) << 16)) >>> 0; + const to = []; for (let i = 0; i < 20; i++) to.push(U(4 * i) * 2); + const lo = to[15], le = to[16], fo = to[18], fe = to[19]; + if (!(lo < le && le <= dp.length && fo < fe && fe <= dp.length)) return null; + const layers = []; + for (let i = lo; i + 2 <= le;) { + const m = u(i); if (m & 0xF800) return null; + const L = { m, x: 0, y: 0, sub: 0, type: 0, img: -1, ox: -1, oy: -1 }; + for (let b = 0; b <= 10; b++) { + if (!(m & (1 << b))) continue; i += 2; + if (b === 0) { L.x = s16v(u(i)); L.ox = i; } else if (b === 1) { L.y = s16v(u(i)); L.oy = i; } + else if (b === 2) L.sub = u(i); else if (b === 9) L.type = u(i); else if (b === 10) L.img = u(i); + } + layers.push(L); i += 2; + } + const frames = []; + for (let k = fo; k + 4 <= fe; k += 4) { const li = u(k), n = u(k + 2); if (li !== 0xFFFF && li + n <= layers.length) frames.push(layers.slice(li, li + n)); } + return { layers, frames }; + } catch (e) { return null; } +} +/* body and eye layer of every frame showing both (each eye layer once); null when the table cannot be read */ +function eyePairs(dp, bodyId, eyeId) { + if (!EYE_V2) return null; + const P = paraLayers(dp); if (!P) return null; + const out = [], seen = new Set(); + for (const f of P.frames) { + const b = f.find((l) => l.img === bodyId), e = f.find((l) => l.img === eyeId); + if (!b || !e || seen.has(e) || e.ox < 0 || e.oy < 0) continue; + seen.add(e); out.push({ b, e }); + } + return out; +} +function eyeMove(dataPack, bodyId, eyeId, fn) { + const pr = eyePairs(dataPack, bodyId, eyeId); if (!pr) return null; + const d = dataPack.slice(); + for (const { b, e } of pr) { const [x, y] = fn(b, e); w16(d, e.ox, x & 0xffff); w16(d, e.oy, y & 0xffff); } + return { dataPack: d, count: pr.length }; +} +/** Hide a character's eye layer on the field: move every eye entry far off screen. + * The eye sprite itself stays untouched, so the cell keeps the original eyes with all moods. */ +function hideEyes(dataPack, bodyId, eyeId, far = 2000) { + const v2 = eyeMove(dataPack, bodyId, eyeId, (b) => [b.x + far, b.y - far]); if (v2) return v2; + const d = dataPack.slice(); const n = d.length >> 1; let count = 0; + const w = (i) => d[2 * i] | (d[2 * i + 1] << 8); + for (let i = 0; i < n - 12; i++) { + if (w(i) !== bodyId || w(i + 1) < 1000 || w(i + 1) > 1600 || w(i + 4) > 40) continue; + for (let j = i + 5; j < i + 12; j++) if (w(j) === eyeId && w(j + 1) >= 1000 && w(j + 1) <= 1600) { + const bx = s16v(w(i + 2)), by = s16v(w(i + 3)); + w16(d, 2 * (j + 2), (bx + far) & 0xffff); w16(d, 2 * (j + 3), (by - far) & 0xffff); + count++; break; + } + } + return { dataPack: d, count }; +} +/** Place the eye layer of a character at (dx, top) relative to its body in every composite definition. */ +function setEyeOffset(dataPack, bodyId, eyeId, hBody, hEye, dx, top) { + /* EYE_V2: same width; centres: eye top = body top + top */ + const v2 = eyeMove(dataPack, bodyId, eyeId, (b) => [b.x + dx, b.y - (hBody >> 1) + top + (hEye >> 1)]); if (v2) return v2; + const d = dataPack.slice(); const n = d.length >> 1; let count = 0; + const w = (i) => d[2 * i] | (d[2 * i + 1] << 8); + for (let i = 0; i < n - 12; i++) { + if (w(i) !== bodyId || w(i + 1) < 1000 || w(i + 1) > 1600 || w(i + 4) > 40) continue; + for (let j = i + 5; j < i + 12; j++) if (w(j) === eyeId && w(j + 1) >= 1000 && w(j + 1) <= 1600) { + const bx = s16v(w(i + 2)), by = s16v(w(i + 3)); + w16(d, 2 * (j + 2), (bx + dx) & 0xffff); w16(d, 2 * (j + 3), (by + top - (hBody - hEye)) & 0xffff); + count++; break; + } + } + return { dataPack: d, count }; +} +/* 1.6.8: where a character's eye layer sits relative to its body, as most of its composite entries have it ([x, y] + * of the top left corners, y counted from the top of the body), or null. */ +/* The first composite entry of a character: sub-images of body and eyes and the eye layer's offset (for a preview) */ +function eyeFirst(dataPack, bodyId, eyeId) { + const pr = eyePairs(dataPack, bodyId, eyeId); + if (pr) { /* dx, dy: top left of the eyes inside the body picture (same width; height from the caller) */ + if (!pr.length) return null; + const { b, e } = pr.find((p) => p.e.sub === 0) || pr[0]; + return { bs: b.sub, es: e.sub, dx: e.x - b.x, dy: e.y - b.y, centred: true }; + } + const d = dataPack, n = d.length >> 1, w = (i) => d[2 * i] | (d[2 * i + 1] << 8); + for (let i = 0; i < n - 12; i++) { + if (w(i) !== bodyId || w(i + 1) < 1000 || w(i + 1) > 1600 || w(i + 4) > 40) continue; + for (let j = i + 5; j < i + 12; j++) if (w(j) === eyeId && w(j + 1) >= 1000 && w(j + 1) <= 1600) return { bs: w(i + 4), es: w(j + 4), dx: s16v(w(j + 2)) - s16v(w(i + 2)), dy: s16v(w(j + 3)) - s16v(w(i + 3)) }; + } + return null; +} +/* 1.6.8: one frame of a character for the preview: body sub-image, eyes and mouth (sub-image and centre offset to + * the body). Prefers a frame with the eyes open (sub-image 0). */ +function faceFirst(dataPack, bodyId, eyeId, mouthId) { + const P = EYE_V2 ? paraLayers(dataPack) : null; if (!P) return null; + let best = null; + for (const f of P.frames) { + const b = f.find((l) => l.img === bodyId), e = f.find((l) => l.img === eyeId); if (!b || !e) continue; + const m = f.find((l) => l.img === mouthId), r = { bs: b.sub, eye: { sub: e.sub, dx: e.x - b.x, dy: e.y - b.y }, mouth: m ? { sub: m.sub, dx: m.x - b.x, dy: m.y - b.y } : null }; + if (!best) best = r; + if (e.sub === 0 && m && m.sub === 0) return r; + if (e.sub === 0 && m && !best.mouth) best = r; + } + return best; +} +/* 1.6.8: every pose of a character (frames with body and eyes; each pair of eye and mouth layers once): body + * sub-image, eyes and mouth with sub-image, centre offset to the body and where their x and y words are (to move + * one pose alone). */ +function facePoses(dataPack, bodyId, eyeId, mouthId) { + const P = EYE_V2 ? paraLayers(dataPack) : null; if (!P) return []; + const out = [], seen = new Set(); + const part = (l, b) => (l && l.ox >= 0 && l.oy >= 0 ? { sub: l.sub, dx: l.x - b.x, dy: l.y - b.y, ox: l.ox, oy: l.oy } : null); + for (const f of P.frames) { + const b = f.find((l) => l.img === bodyId), e = f.find((l) => l.img === eyeId); if (!b || !e) continue; + const m = f.find((l) => l.img === mouthId), key = e.ox + ':' + (m ? m.ox : -1); + if (seen.has(key)) continue; seen.add(key); + out.push({ bs: b.sub, eye: part(e, b), mouth: part(m, b) }); + } + return out; +} +/* move single layers: list of { ox, oy, d: [dx, dy] } (word positions from facePoses) */ +function layersMove(dataPack, list) { + const d = dataPack.slice(), r = (o) => s16v(d[o] | (d[o + 1] << 8)); + for (const { ox, oy, d: v } of list) { if (ox < 0 || oy < 0) continue; w16(d, ox, (r(ox) + v[0]) & 0xffff); w16(d, oy, (r(oy) + v[1]) & 0xffff); } + return d; +} +function eyeRelGet(dataPack, bodyId, eyeId, hBody, hEye) { + const pr = eyePairs(dataPack, bodyId, eyeId); + if (pr) { + const seen = new Map(); + for (const { b, e } of pr) { const k = (e.x - b.x) + ',' + (e.y - b.y + ((hBody - hEye) >> 1)); seen.set(k, (seen.get(k) || 0) + 1); } + let best = null, bn = 0; for (const [k, c] of seen) if (c > bn) { bn = c; best = k; } + return best ? best.split(',').map(Number) : null; + } + const d = dataPack, n = d.length >> 1, w = (i) => d[2 * i] | (d[2 * i + 1] << 8), seen = new Map(); + for (let i = 0; i < n - 12; i++) { + if (w(i) !== bodyId || w(i + 1) < 1000 || w(i + 1) > 1600 || w(i + 4) > 40) continue; + for (let j = i + 5; j < i + 12; j++) if (w(j) === eyeId && w(j + 1) >= 1000 && w(j + 1) <= 1600) { + const k = (s16v(w(j + 2)) - s16v(w(i + 2))) + ',' + (s16v(w(j + 3)) - s16v(w(i + 3)) + hBody - hEye); seen.set(k, (seen.get(k) || 0) + 1); break; + } + } + let best = null, bn = 0; for (const [k, c] of seen) if (c > bn) { bn = c; best = k; } + return best ? best.split(',').map(Number) : null; +} +/* 1.6.8: move a character's eye layer by (dx, dy) in every composite entry (the animation stays as it is) */ +function shiftEyes(dataPack, bodyId, eyeId, dx, dy) { + const v2 = eyeMove(dataPack, bodyId, eyeId, (b, e) => [e.x + dx, e.y + dy]); if (v2) return v2; + const d = dataPack.slice(); const n = d.length >> 1; let count = 0; + const w = (i) => d[2 * i] | (d[2 * i + 1] << 8); + for (let i = 0; i < n - 12; i++) { + if (w(i) !== bodyId || w(i + 1) < 1000 || w(i + 1) > 1600 || w(i + 4) > 40) continue; + for (let j = i + 5; j < i + 12; j++) if (w(j) === eyeId && w(j + 1) >= 1000 && w(j + 1) <= 1600) { + w16(d, 2 * (j + 2), (s16v(w(j + 2)) + dx) & 0xffff); w16(d, 2 * (j + 3), (s16v(w(j + 3)) + dy) & 0xffff); + count++; break; + } + } + return { dataPack: d, count }; +} +// Known eye positions (idle frame) for the first supported card, keyed by a pixel checksum of idle1. +const DIM_EYE_PRESETS = { '108888711': [14, 19, 18, 23], '116452384': [28, 8, 33, 13], '581122605': [31, 7, 36, 12], '1245232413': [19, 20, 34, 25], '1336972138': [25, 36, 36, 42], '1500027408': [27, 10, 34, 16], '1848189483': [17, 23, 24, 30], '2311689890': [26, 18, 32, 24], '2355390565': [29, 25, 36, 31], '2531248920': [4, 12, 17, 16], '2626563298': [4, 11, 22, 19], '2954084235': [26, 31, 31, 36], '3228635844': [25, 12, 34, 17], '3828096515': [25, 10, 30, 16], '3939049875': [22, 16, 27, 22] }; +// Characters on that card without visible eyes (null = no eye layer). +Object.assign(DIM_EYE_PRESETS, { '1999209136': null, '26973819': null }); +function dimEyePreset(ch) { const k = String(crc32(ch.frames.idle1.data)); return k in DIM_EYE_PRESETS ? DIM_EYE_PRESETS[k] : undefined; } + +// ------------------------------------------------------------ number test +const DIGITS = ['111101101101111', '010110010010111', '111001111100111', '111001111001111', '101101111001001', '111100111001111', '111100111101111', '111001001001001', '111101111101111', '111101111001111']; +function numberImage(text, w, h, scale) { + const img = emptyImage(w, h); + const set = (x, y, r, g, b) => { if (x < 0 || y < 0 || x >= w || y >= h) return; const o = (y * w + x) * 4; img.data.set([r, g, b, 255], o); }; + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const edge = x === 0 || y === 0 || x === w - 1 || y === h - 1; set(x, y, edge ? 230 : 255, edge ? 30 : 255, edge ? 30 : 255); } + const tw = text.length * 4 * scale - scale, x0 = (w - tw) >> 1, y0 = (h - 5 * scale) >> 1; + [...text].forEach((ch, i) => { const g = DIGITS[+ch]; for (let r = 0; r < 5; r++) for (let c = 0; c < 3; c++) if (g[r * 3 + c] === '1') for (let yy = 0; yy < scale; yy++) for (let xx = 0; xx < scale; xx++) set(x0 + (i * 4 + c) * scale + xx, y0 + r * scale + yy, 0, 0, 0); }); + return img; +} + +// ------------------------------------------------------------------- ZIP +const CRC_TABLE = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })(); +function crc32(d) { let c = 0xffffffff; for (let i = 0; i < d.length; i++) c = CRC_TABLE[(c ^ d[i]) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; } +/** Minimal ZIP writer (stored). files: [{name, data: Uint8Array}] */ +function zipBuild(files) { + const enc = new TextEncoder(), local = [], central = []; let off = 0; + for (const f of files) { + const name = enc.encode(f.name), crc = crc32(f.data); + const lh = new Uint8Array(30 + name.length); + w32(lh, 0, 0x04034b50); w16(lh, 4, 20); w16(lh, 8, 0); w32(lh, 14, crc); w32(lh, 18, f.data.length); w32(lh, 22, f.data.length); w16(lh, 26, name.length); lh.set(name, 30); + const ch = new Uint8Array(46 + name.length); + w32(ch, 0, 0x02014b50); w16(ch, 4, 20); w16(ch, 6, 20); w32(ch, 16, crc); w32(ch, 20, f.data.length); w32(ch, 24, f.data.length); w16(ch, 28, name.length); w32(ch, 42, off); ch.set(name, 46); + local.push(lh, f.data); central.push(ch); off += lh.length + f.data.length; + } + const cd = concat(central), end = new Uint8Array(22); + w32(end, 0, 0x06054b50); w16(end, 8, files.length); w16(end, 10, files.length); w32(end, 12, cd.length); w32(end, 16, off); + return concat([...local, cd, end]); +} +/** ZIP reader. inflateRaw: async (Uint8Array) => Uint8Array for deflated entries. */ +async function zipRead(buf, inflateRaw) { + let eocd = -1; for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) if (u32(buf, i) === 0x06054b50) { eocd = i; break; } + if (eocd < 0) throw new Error('not a ZIP file'); + const n = u16(buf, eocd + 10); let p = u32(buf, eocd + 16); const out = []; const dec = new TextDecoder(); + for (let k = 0; k < n; k++) { + const method = u16(buf, p + 10), csize = u32(buf, p + 20), nlen = u16(buf, p + 28), xlen = u16(buf, p + 30), clen = u16(buf, p + 32), lo = u32(buf, p + 42); + const name = dec.decode(buf.subarray(p + 46, p + 46 + nlen)); + p += 46 + nlen + xlen + clen; + if (name.endsWith('/')) continue; + const start = lo + 30 + u16(buf, lo + 26) + u16(buf, lo + 28), raw = buf.subarray(start, start + csize); + if (method === 0) out.push({ name, data: raw.slice() }); + else if (method === 8) out.push({ name, data: await inflateRaw(raw) }); + else throw new Error('unsupported ZIP compression in ' + name); + } + return out; +} + + +// ------------------------------------------------------------- fields (worlds) +/* + * What belongs to which field. Every edition carries complete sets of characters + * for several field types (1 Land, 2 Water, 3 Sky, 4 Forest, 5 Tropical, 6 Glacier): + * Land/Water/Sky ROMs types 1-3, Jade Forest 1-4, Tropical/Glacier all six. + * Per field: 1 child, 4 teens, 17 adults. Characters come from the character table + * of the data pack (30 byte records: id, ?, name index, stage, line, ..., field at + * word 7); the sprite groups follow the character ids in order (group 0 = fallback). + * Field maps are 7 sprites of 64x64x64 per field (Tropical/Glacier: plus 7 overlay + * sprites of 64x64x32), close-ups are 6 sprites of 64x64x4 per field type. + */ +const FIELD_NAMES = { 1: 'Land', 2: 'Water', 3: 'Sky', 4: 'Forest', 5: 'Tropical', 6: 'Glacier' }; +function charTable(dp) { + const u32 = (o) => (dp[o] | (dp[o + 1] << 8) | (dp[o + 2] << 16) | (dp[o + 3] << 24)) >>> 0; + const u16 = (o) => dp[o] | (dp[o + 1] << 8); + const n = u32(0); + for (let t = 0; t < Math.min(n, 40); t++) { + const a = u32(4 + 4 * t) * 2, b = u32(8 + 4 * t) * 2; + if (b > a && b <= dp.length && (b - a) % 30 === 0 && b - a >= 60 && u16(a) === 0xFFFF && u16(a + 30) === 1000) { + const out = []; + for (let o = a; o < b; o += 30) out.push({ id: u16(o), name: u16(o + 4) + 1, stage: u16(o + 6), line: u16(o + 8), field: u16(o + 14) }); + return out; + } + } + return []; +} +function fieldSets(ctx) { + const chars = charTable(ctx.files[0]).filter((c) => c.id > 1000 && c.id < 9000); + if (chars.length + 1 !== ctx.groups.length) return []; + chars.forEach((c, i) => { c.group = ctx.groups[i + 1]; }); + const types = [...new Set(chars.map((c) => c.field).filter((f) => f >= 1 && f <= 6))].sort((a, b) => a - b); + const kind = (i) => { const h = spriteHeader(ctx.entries[i]); return h.sw === 64 && h.sh === 64 ? Math.max(1, h.iw) * Math.max(1, h.ih) : 0; }; + const maps = [], over = []; + ctx.entries.forEach((e, i) => { const k = kind(i); if (k === 64) maps.push(i); }); + // close-ups: the longest run of 64x64x4 sprites, 6 per field type + let best = [0, 0]; + for (let i = 0; i < ctx.entries.length; i++) { if (kind(i) !== 4) continue; let j = i; while (j + 1 < ctx.entries.length && kind(j + 1) === 4) j++; if (j - i + 1 > best[1] - best[0]) best = [i, j + 1]; i = j; } + const nClose = Math.floor((best[1] - best[0]) / 6); + const nMap = Math.floor(maps.length / 7); + // maps belong to the highest field types present (Tropical/Glacier: Forest, Tropical, Glacier) + const mapTypes = types.slice(Math.max(0, types.length - nMap)); + return types.map((tp) => { + const m = mapTypes.indexOf(tp), maps7 = m >= 0 ? maps.slice(7 * m, 7 * m + 7) : []; + const overlays = []; + if (maps7.length) { const last = maps7[6]; for (let j = last + 1; j < last + 8 && j < ctx.entries.length && kind(j) === 32; j++) overlays.push(j); } + const close = tp <= nClose ? Array.from({ length: 6 }, (_, k) => best[0] + 6 * (tp - 1) + k) : []; + return { type: tp, name: FIELD_NAMES[tp], chars: chars.filter((c) => c.field === tp), maps: maps7, overlays, closeups: close }; + }); +} + + +// ------------------------------------------------------------ texts (1.6.8) +/* + * The third file of the asset archive is an ARC2 with one text table per language (JP, EN, FR, DE, PT, ES, IT and + * two Chinese ones). A table: u16 offsets (in u16 units from the table start; the first one is the number of + * entries), then the strings, u16 glyph codes ending in 0. Names (Tamas, items, fields) are entries of it. A changed + * name goes into every table with Latin letters; the strings are laid out anew, so a name may be longer. + */ +const TXT_ENC = { ' ': 305, '&': 375, "'": 376, '.': 381, '!': 370, '?': 388, '/': 382 }; +for (let i = 0; i < 26; i++) TXT_ENC[String.fromCharCode(65 + i)] = 318 + i; +for (let i = 0; i < 10; i++) TXT_ENC[String(i)] = 306 + i; +const TXT_DEC = {}; for (const k in TXT_ENC) TXT_DEC[TXT_ENC[k]] = k; TXT_DEC[317] = ' '; +/** Clean a name for the Paradise font: capitals, digits, space and . & ' ! ? / ; null if nothing is left. */ +// Native Korean font: KS X 1001 syllables, ROM glyph IDs 481..2830. +const KO_CHARS = "가각간갇갈갉갊감갑값갓갔강갖갗같갚갛개객갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫났낭낮낯낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫달닭닮닯닳담답닷닸당닺닻닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많맏말맑맒맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바박밖밗반받발밝밞밟밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤샥샨샬샴샵샷샹섀섄섈섐섕서석섞섟선섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄업없엇었엉엊엌엎에엑엔엘엠엡엣엥여역엮연열엶엷염엽엾엿였영옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응읒읓읔읕읖읗의읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"; +const KO_ENC = Object.fromEntries([...KO_CHARS].map((c,i)=>[c,481+i])); +function textKoreanTable(x) { const t=x?.tabs[8]; return t && t.n>16 && txtWords(t,1).every(c=>c===61440 || c===305 || c>=481&&c<=2830) ? t : null; } +function textClean(s, language='en') { + if(language==='ko') { + const value=String(s||'').normalize('NFC').toUpperCase().replace(/\s+/g,' ').trim(); + const bad=[...value].filter(c=>!(c in TXT_ENC)&&!(c in KO_ENC)); + if(bad.length)throw Error('본체 글꼴에서 지원하지 않는 문자입니다: '+[...new Set(bad)].join(' ')); + return value||null; + } + return textCleanLatin(s); +} +function textCleanLatin(s) { const t = String(s || '').toUpperCase().split('').filter((c) => c in TXT_ENC).join('').replace(/\s+/g, ' ').trim(); return t || null; } +function textTablesOf(rom) { + const root = arc2Parse(rom, ASSET_BASE), off = ASSET_BASE + root.ents[2].offset; + if (u32(rom, off) !== ARC2_MAGIC) return null; + const tabs = arc2Files(rom, off).map((b) => { + const w = (o) => b[o] | (b[o + 1] << 8), n = w(0), offs = []; + for (let i = 0; i < n; i++) offs.push(w(2 * i)); + return { b, n, offs }; + }); + return { off, tabs }; +} +function txtWords(t, i) { const w = (o) => t.b[o] | (t.b[o + 1] << 8), out = []; for (let o = 2 * t.offs[i]; o + 1 < t.b.length; o += 2) { const c = w(o); if (!c) break; out.push(c); } return out; } +/* Latin table: its words for LAND/WATER/SKY-like entries are capitals or accented letters */ +function txtLatin(t) { if (t.n < 20) return false; const ws = txtWords(t, 1); return ws.length > 2 && ws.every((c) => (c >= 305 && c <= 470) || c === 61440); } +/** English text i (Paradise font), '' if it has other glyphs */ +function textGet(rom, i, language='en') { + const x = textTablesOf(rom); if (!x) return ''; + const t = language==='ko' ? textKoreanTable(x) : x.tabs.find(txtLatin); if (!t || i >= t.n) return ''; + let s = ''; for (const c of txtWords(t, i)) { const ch=TXT_DEC[c] ?? (language==='ko' && c>=481 && c<=2830 ? KO_CHARS[c-481] : undefined); if(ch===undefined)return ''; s+=ch; } return s.trim(); +} +/** ROM with changed texts. edits: Map text index -> name (cleaned). Throws if the archive would not fit. */ +function textApply(rom, edits, language='en') { + if (!edits || !edits.size) return rom; + const x = textTablesOf(rom); if (!x) throw new Error('text tables not found'); + const target=textKoreanTable(x); + if(language==='ko' && !target)throw Error('이 ROM의 한국어 이름 표를 확인할 수 없습니다.'); + const tabs = x.tabs.map((t) => { + if (language==='ko' ? t!==target : !txtLatin(t)) return t.b; + const end = t.b.length >> 1, segs = []; + for (let i = 0; i < t.n; i++) { + const a = t.offs[i], b = i + 1 < t.n ? t.offs[i + 1] : end; + let seg = t.b.subarray(2 * a, 2 * b); + const nm = edits.has(i) ? textClean(edits.get(i), language) : null; + // only an entry that is exactly its string plus the 0 is replaced (the first and the last are not) + if (nm && i > 0 && i + 1 < t.n && b === a + txtWords(t, i).length + 1) { + const ns = new Uint8Array(2 * (nm.length + 1)); [...nm].forEach((c, k) => w16(ns, 2 * k, (TXT_ENC[c] ?? KO_ENC[c]))); seg = ns; + } + segs.push(seg); + } + let pos = t.n; const head = new Uint8Array(2 * t.n); + segs.forEach((sg, i) => { if (pos > 0xFFFF) throw new Error('text table too long'); w16(head, 2 * i, pos); pos += sg.length >> 1; }); + const out = concat([head, ...segs]); + return (t.b.length & 1) ? concat([out, new Uint8Array(1)]) : out; + }); + const files = arc2Files(rom, ASSET_BASE); files[2] = arc2Build(tabs); + const ctx = openRom(rom), root = arc2Build(files), end = ASSET_BASE + root.length; + if (end > ctx.limit) throw new Error('too big: assets would end at 0x' + end.toString(16)); + const out = rom.slice(); out.set(root, ASSET_BASE); + if (end < ctx.assetEnd) out.fill(0xff, end, ctx.assetEnd); + verifyRom(out, []); + if(language==='ko'){ + const names=new Map(charTable(ctx.files[0]).filter(c=>edits.has(c.name)).map(c=>[c.id,textGet(out,c.name,'ko')])); + koreanPetNames(out,ctx.editionId,names); + } + return out; +} + +function koreanPetNames(out,edition,names){ + // Ghost headers cache the actual pet name. Update valid copies using a checksum delta. + for(let a=(edition>=5?0xD2A000:0xD4A000);a<0xEFE000;a+=4096){ + const id=u16(out,a+0x10a),name=names.get(id),size=u32(out,a+0x10c); + if(!name || u32(out,a+8)>255 || size<0x600 || size>0x1B000 || ((u32(out,a)+u32(out,a+4))>>>0)!==0)continue; + let before=0;for(let k=8;k<0x180;k+=4)before=(before+u32(out,a+k))>>>0; + out.fill(0,a+18+8*26,a+18+9*26); + [...name].slice(0,12).forEach((c,i)=>w16(out,a+18+8*26+i*2,TXT_ENC[c]??KO_ENC[c])); + let after=0;for(let k=8;k<0x180;k+=4)after=(after+u32(out,a+k))>>>0; + const sum=(u32(out,a)+after-before)>>>0;w32(out,a,sum);w32(out,a+4,-sum>>>0); + } + return out; +} + +root.ParamixCore = { koreanPetNames, paraLayers, faceFirst, facePoses, layersMove, EYE_V2, smaDetect, smaLoad, eyeFirst, eyeRelGet, shiftEyes, textClean, textGet, textApply, textTablesOf, TXT_ENC, KO_CHARS, KO_ENC, + fieldSets, charTable, FIELD_NAMES, + ASSET_BASE, EDITIONS, GROUP_PARTS, GROUP_SHEET_W, GROUP_SHEET_H, + arc2Parse, arc2Files, arc2Build, arc2Checksum, packSplit, packJoin, spriteHeader, spriteDecode, spriteEncode, spriteBlank, spriteTiny, spriteAlign, partOptions, launcherKeep, launcherChanges, isLauncher, + rleEncode, rleDecode, quantize, findGroups, findEgg, openRom, buildRom, verifyRom, + sheetLayout, sheetFromSubs, subsFromSheet, groupSheet, groupFromSheet, emptyImage, sameImage, crop, + dimLoad, dimCharParts, dimEggSubs, dimCharPartsWithEyes, dimGuessEye, eyeRectAt, eyeVariants, setEyeOffset, hideEyes, dimEyePreset, DIM_EYE_PRESETS, place, numberImage, zipBuild, zipRead, crc32, +}; +if (typeof module !== 'undefined') module.exports = root.ParamixCore; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/src/doom.js b/src/doom.js new file mode 100644 index 0000000..f240c05 --- /dev/null +++ b/src/doom.js @@ -0,0 +1,536 @@ +/* + * Paramix Studio: install DOOM into the Paradise ROM. + * The user supplies the WAD (DOOM.WAD); it never leaves the computer. + * The studio only contains the program (GPL, derived from next-hack nRF52840Doom / GBADoom / PrBoom) + * and the WAD converter (MCUDoomWadUtil, GPL) as WebAssembly. No game graphics, no WAD. + * + * Flow: partial WAD (one episode) -> extra lumps from the same WAD -> converter -> into the ROM. + * Layout in the Paradise flash: + * 0x0A0000 DOOM program (PRAM part, loaded by the stub) + * 0x0B0000 stub and home screen hook (hold A+C), same as the emulator + * 0x0B1000 DOOM program (part in the flash window) + * 0x10E000 settings and save (2 x 4 KB) + * 0x830000 converted WAD (preceded by 4-byte length), 0xCA0000 region for precomputed data + * + * Author: mameise + */ +(function (root) { +'use strict'; + +const CODE_OFF = 0xB1000, SAVE_OFF = 0x10E000, SAVE_END = 0x110000; +const WAD_OFF = 0x830000, REGION_OFF = 0xCA0000, REGION_END = 0xD48000; +const PW = 128, PH = 128; + +const u16 = (b, o) => b[o] | (b[o + 1] << 8); +const s16 = (b, o) => { const v = u16(b, o); return v > 32767 ? v - 65536 : v; }; +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >> 8) & 255; } +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } +const name8 = (b, o) => { let e = o + 8; while (e > o && b[e - 1] === 0) e--; let s = ''; for (let i = o; i < e; i++) s += String.fromCharCode(b[i]); return s; }; +function b64(s) { + if (typeof atob === 'function') { const t = atob(s); const o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; } + return new Uint8Array(Buffer.from(s, 'base64')); +} + +// ------------------------------------------------------------------ WAD +function readWad(d) { + const id = String.fromCharCode(d[0], d[1], d[2], d[3]); + if (id !== 'IWAD' && id !== 'PWAD') throw new Error('not a WAD file'); + const n = u32(d, 4), off = u32(d, 8), L = []; + for (let i = 0; i < n; i++) { + const o = u32(d, off + 16 * i), s = u32(d, off + 16 * i + 4); + L.push([name8(d, off + 16 * i + 8), d.subarray(o, o + s)]); + } + return L; +} +/** Like wadsub.py: header, data in one piece, directory at the end. */ +function writeWad(L, ident) { + let size = 12; for (const [, d] of L) size += d.length; + const out = new Uint8Array(size + 16 * L.length); + out.set([...ident].map(c => c.charCodeAt(0)), 0); w32(out, 4, L.length); w32(out, 8, size); + let p = 12, q = size; + for (const [nm, d] of L) { + out.set(d, p); w32(out, q, p); w32(out, q + 4, d.length); + for (let k = 0; k < 8 && k < nm.length; k++) out[q + 8 + k] = nm.charCodeAt(k) & 255; + p += d.length; q += 16; + } + return out; +} +/** Which episodes does the WAD have? E.g. ['1'] (Shareware), ['1','2','3'] (DOOM), or also '4' (Ultimate). */ +function wadEpisodes(d) { + const eps = new Set(); + let d2 = 0; + for (const [nm] of readWad(d)) { const m = /^E(\d)M\d$/.exec(nm); if (m) eps.add(m[1]); if (/^MAP\d\d$/.test(nm)) d2++; } + if (!eps.size && D2 && d2) return ['M']; // 1.7.3 test15: DOOM II (all maps MAP01..MAP32 as one "episode" M) + if (!eps.size) throw new Error('no DOOM maps in the WAD (DOOM 2 is not supported)'); + return [...eps].sort(); +} + +// ------------------------------------------------------------ partial WAD (wadsub.py) +const MAPL = new Set(['THINGS', 'LINEDEFS', 'SIDEDEFS', 'VERTEXES', 'SEGS', 'SSECTORS', 'NODES', 'SECTORS', 'REJECT', 'BLOCKMAP']); +const ANIMS = [['NUKAGE3', 'NUKAGE1'], ['FWATER4', 'FWATER1'], ['SWATER4', 'SWATER1'], ['LAVA4', 'LAVA1'], ['BLOOD3', 'BLOOD1'], ['RROCK08', 'RROCK05'], ['SLIME04', 'SLIME01'], ['SLIME08', 'SLIME05'], ['SLIME12', 'SLIME09']]; +const TANIMS = [['BLODGR4', 'BLODGR1'], ['SLADRIP3', 'SLADRIP1'], ['BLODRIP4', 'BLODRIP1'], ['FIREWALL', 'FIREWALA'], ['GSTFONT3', 'GSTFONT1'], ['FIRELAVA', 'FIRELAV3'], ['FIREMAG3', 'FIREMAG1'], ['FIREBLU2', 'FIREBLU1'], ['ROCKRED3', 'ROCKRED1'], ['BFALL4', 'BFALL1'], ['SFALL4', 'SFALL1'], ['WFALL4', 'WFALL1'], ['DBRAIN4', 'DBRAIN1']]; +const MON = { 3004: ['POSS'], 9: ['SPOS'], 3001: ['TROO', 'BAL1'], 3002: ['SARG'], 58: ['SARG'], 3003: ['BOSS', 'BAL7'], 3005: ['HEAD', 'BAL2'], 3006: ['SKUL'], 16: ['CYBR'], 7: ['SPID'] }; +const FULL = new Set(['TITLEPIC', 'HELP1', 'HELP2', 'CREDIT', 'VICTORY2', 'PFUB1', 'PFUB2', 'INTERPIC']); +/* 1.7.3 test14 E4: Ultimate DOOM. Its end picture ENDPIC (full screen, only in the WAD with E4) and the flat behind each + * episode's end text are kept. */ +const E4 = true; +if (E4) FULL.add('ENDPIC'); +const END_FLAT = { 1: 'FLOOR4_8', 2: 'SFLR6_1', 3: 'MFLR8_4', 4: 'MFLR8_3' }; +/* 1.7.3 test15 D2: DOOM II (and WADs like it with MAP01..): every map, the three skies, all music, the flats behind the + * texts between maps and the big picture behind the cast at the end */ +const D2 = true; +const D2_FLATS = ['SLIME16', 'RROCK14', 'RROCK07', 'RROCK17', 'RROCK13', 'RROCK19']; +if (D2) { FULL.add('BOSSBACK'); FULL.add('HELP'); } +const upName = (b, o) => name8(b, o).toUpperCase(); + +function readTex(dd) { + const cnt = u32(dd, 0), res = []; + for (let i = 0; i < cnt; i++) { const o = u32(dd, 4 + 4 * i); const pc = u16(dd, o + 20); res.push([upName(dd, o), dd.subarray(o, o + 22 + 10 * pc)]); } + return res; +} +function patchDecode(dd) { + const w = s16(dd, 0), h = s16(dd, 2); + if (w <= 0 || h <= 0) throw new Error('no picture'); + const img = new Uint8Array(w * h); + for (let x = 0; x < w; x++) { + let p = u32(dd, 8 + 4 * x); + while (dd[p] !== 0xFF) { + if (p >= dd.length) throw new Error('broken'); + const top = dd[p], ln = dd[p + 1]; + for (let k = 0; k < ln; k++) { const y = top + k; if (y < h) img[y * w + x] = dd[p + 3 + k]; } + p += ln + 4; + } + } + return { w, h, img }; +} +function fullEncode(img, w, h) { + const colLen = 3 + h + 2, out = new Uint8Array(8 + 4 * w + colLen * w); + w16(out, 0, w); w16(out, 2, h); + for (let x = 0; x < w; x++) { + const o = 8 + 4 * w + colLen * x; w32(out, 8 + 4 * x, o); + out[o] = 0; out[o + 1] = h; out[o + 2] = 0; + for (let y = 0; y < h; y++) out[o + 3 + y] = img[y * w + x]; + out[o + 3 + h] = 0; out[o + 4 + h] = 0xFF; + } + return out; +} +/** Average per target cell, then nearest palette color (same as wadsub.py). */ +function shrink(img, w, h, pal) { + const near = new Map(), res = new Uint8Array(PW * PH); + const nearest = (r, g, b) => { + const key = (r << 16) | (g << 8) | b; let v = near.get(key); + if (v === undefined) { + let best = 1 << 30; v = 0; + for (let i = 0; i < 256; i++) { const dr = pal[3 * i] - r, dg = pal[3 * i + 1] - g, db = pal[3 * i + 2] - b, e = dr * dr + dg * dg + db * db; if (e < best) { best = e; v = i; } } + near.set(key, v); + } + return v; + }; + for (let ty = 0; ty < PH; ty++) { + const y0 = Math.floor(ty * h / PH), y1 = Math.max(y0 + 1, Math.floor((ty + 1) * h / PH)); + for (let tx = 0; tx < PW; tx++) { + const x0 = Math.floor(tx * w / PW), x1 = Math.max(x0 + 1, Math.floor((tx + 1) * w / PW)); + let sr = 0, sg = 0, sb = 0, n = 0; + for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const c = img[y * w + x]; sr += pal[3 * c]; sg += pal[3 * c + 1]; sb += pal[3 * c + 2]; n++; } + res[ty * PW + tx] = nearest(Math.floor((sr + (n >> 1)) / n), Math.floor((sg + (n >> 1)) / n), Math.floor((sb + (n >> 1)) / n)); + } + } + return res; +} + +/** Partial WAD: only episode eps (e.g. '1'), only used textures, flats and monsters, full-screen pictures 128x128. */ +function wadSub(src, eps, music, only) { // only (1.7.3 test17): Set of the map names to keep (a map pack alone) + const L = readWad(src).map(([n, d]) => [n, d]); + let out = []; const usedtex = new Set(), usedflat = new Set(), usedthings = new Set(); + let i = 0; + const musRe = new RegExp('^D_E[' + eps + ']M\\d$'); + while (i < L.length) { + const [nm] = L[i]; + const m = /^E(\d)M(\d)$/.exec(nm) || (D2 && eps === 'M' && /^MAP\d\d$/.test(nm) ? [nm, 'M'] : null); + if (m) { + const keep = eps.includes(m[1]) && (!only || only.has(nm)); + let j = i + 1; while (j < L.length && MAPL.has(L[j][0])) j++; + if (keep) { + for (let k = i; k < j; k++) { + out.push(L[k]); + const [n2, dd] = L[k]; + if (n2 === 'SIDEDEFS') for (let q = 0; q + 30 <= dd.length; q += 30) [4, 12, 20].forEach(o => usedtex.add(upName(dd, q + o))); + if (n2 === 'THINGS') for (let q = 0; q + 10 <= dd.length; q += 10) usedthings.add(u16(dd, q + 6)); + if (n2 === 'SECTORS') for (let q = 0; q + 26 <= dd.length; q += 26) [4, 12].forEach(o => usedflat.add(upName(dd, q + o))); + } + } + i = j; continue; + } + if (nm.startsWith('D_') && music && (musRe.test(nm) || ['D_INTER', 'D_INTRO', 'D_INTROA', 'D_VICTOR'].includes(nm) || (D2 && eps === 'M'))) { out.push(L[i]); i++; continue; } + if (nm.startsWith('DS') || nm.startsWith('D_') || ['ENDOOM', 'GENMIDI', 'DMXGUS'].includes(nm) || /^DEMO\d$/.test(nm)) { i++; continue; } + out.push(L[i]); i++; + } + if (D2 && eps === 'M') { ['SKY1', 'SKY2', 'SKY3'].forEach((t) => usedtex.add(t)); D2_FLATS.forEach((f) => usedflat.add(f)); } + else for (const e of eps) usedtex.add('SKY' + e); + if (E4) for (const e of eps) if (END_FLAT[e]) usedflat.add(END_FLAT[e]); + for (const t of [...usedtex]) { if (t.startsWith('SW1')) usedtex.add('SW2' + t.slice(3)); if (t.startsWith('SW2')) usedtex.add('SW1' + t.slice(3)); } + let names = out.map(x => x[0]); + let fs = names.indexOf('F_START'), fe = names.indexOf('F_END'); + const flats = names.slice(fs + 1, fe); + for (const [a, b] of ANIMS) { + if (flats.includes(a) && flats.includes(b)) { + const rng = flats.slice(flats.indexOf(b), flats.indexOf(a) + 1); + if (rng.some(x => usedflat.has(x))) rng.forEach(x => usedflat.add(x)); + } + } + const need = new Set(), allmon = new Set(); + for (const [t, sp] of Object.entries(MON)) { sp.forEach(x => allmon.add(x)); if (usedthings.has(+t)) sp.forEach(x => need.add(x)); } + const drop = new Set([...allmon].filter(x => !need.has(x))); + const ss = names.indexOf('S_START'), se = names.indexOf('S_END'); + out = out.filter((x, j) => !(ss < j && j < se && drop.has(x[0].slice(0, 4)))); + names = out.map(x => x[0]); fs = names.indexOf('F_START'); fe = names.indexOf('F_END'); + const alltex = []; + for (const k of ['TEXTURE1', 'TEXTURE2']) if (names.includes(k)) readTex(out[names.indexOf(k)][1]).forEach(t => alltex.push(t[0])); + for (const [a, b] of TANIMS) { + if (alltex.includes(a) && alltex.includes(b)) { + const rng = alltex.slice(alltex.indexOf(b), alltex.indexOf(a) + 1); + if (rng.some(x => usedtex.has(x))) rng.forEach(x => usedtex.add(x)); + } + } + for (const k of ['TEXTURE1', 'TEXTURE2']) { + if (!names.includes(k)) continue; + const idx = names.indexOf(k); + const keep = readTex(out[idx][1]).filter((t, j) => (k === 'TEXTURE1' && j === 0) || usedtex.has(t[0])); + let size = 4 + 4 * keep.length; for (const [, raw] of keep) size += raw.length; + const d = new Uint8Array(size); w32(d, 0, keep.length); + let pos = 4 + 4 * keep.length; + keep.forEach(([, raw], j) => { w32(d, 4 + 4 * j, pos); d.set(raw, pos); pos += raw.length; }); + out[idx] = [k, d]; + } + out = out.filter((x, j) => !(fs < j && j < fe && !usedflat.has(x[0]) && !x[0].endsWith('_START') && !x[0].endsWith('_END'))); + const dropfull = new Set(['WIMAP0', 'WIMAP1', 'WIMAP2', 'VICTORY2', 'PFUB1', 'PFUB2']); + if (E4) dropfull.add('ENDPIC'); + for (const e of eps) { dropfull.delete('WIMAP' + (+e - 1)); if (e === '2') dropfull.delete('VICTORY2'); if (e === '4') dropfull.delete('ENDPIC'); if (e === '3') { dropfull.delete('PFUB1'); dropfull.delete('PFUB2'); } } + out = out.filter(x => !dropfull.has(x[0])); + names = out.map(x => x[0]); + const pal = out[names.indexOf('PLAYPAL')][1].subarray(0, 768); + out.forEach((x, k) => { + const nm = x[0]; + if (!(FULL.has(nm) || nm.startsWith('WIMAP') || (nm.startsWith('END') && nm.length === 4))) return; + let p; try { p = patchDecode(x[1]); } catch (e) { return; } + if (p.w !== 320 || p.h !== 200) return; + out[k] = [nm, fullEncode(shrink(p.img, p.w, p.h, pal), PW, PH)]; + }); + return writeWad(out, 'IWAD'); +} + +// ------------------------------------------------- extra WADs (PWAD): Sigil, map packs (1.7.3 test17) +/* PWAD = true: an extra WAD the user brings. Two kinds: + * - maps that replace maps of the base WAD (same names, e.g. MAP01 of a DOOM II map pack) + * - its own episode E5..E9 (Sigil E5, Sigil II E6): the engine knows four episodes, so it goes into the place of E4 + * (maps E4M1..E4M9, its sky as SKY4, its pictures, names, end text and songs; UMAPINFO says which ones). */ +const PWAD = true; +const MARKERS = /^(P|PP|P1|P2|P3|F|FF|F1|F2|F3|S|SS)_(START|END)$/; +const PWAD_DROP = new Set(['DEHACKED', 'MAPINFO', 'UMAPINFO', 'ZMAPINFO', 'EMAPINFO', 'LANGUAGE', 'GAMEINFO', 'EMENUS', 'DD_DEFNS', + 'CHNGLG', 'OPTIONS', 'ANIMATED', 'SWITCHES', 'TITLEPIC', 'HELP1', 'HELP2', 'D_INTER', 'D_INTRO', 'D_INTROA', 'D_VICTOR', 'DEMO1', + 'DEMO2', 'DEMO3', 'DEMO4', 'GENMIDI', 'DMXGUS', 'ENDOOM', 'SNDINFO', 'SNDSEQ', 'MUSINFO', 'DECORATE', 'ZSCRIPT', 'TEXTURES', + 'KEYCONF', 'MENUDEF', 'SBARINFO', 'COLORMAP', 'PLAYPAL']); + +/** UMAPINFO: { E5M1: { levelname, levelpic, music, skytexture, exitpic, endpic, intertext, next, nextsecret, episode } } */ +function umapinfo(txt) { + const out = {}; const re = /map\s+(\w+)\s*\{([^}]*)\}/gi; let m; + while ((m = re.exec(txt))) { + const o = {}, body = m[2].replace(/\/\/[^\n]*/g, ''); + const kv = /(\w+)\s*=\s*((?:"[^"]*"\s*,?\s*)+|[^\n]+)/g; let k; + while ((k = kv.exec(body))) { + const key = k[1].toLowerCase(), strs = [...k[2].matchAll(/"([^"]*)"/g)].map((x) => x[1]); + o[key] = strs.length ? (key === 'intertext' ? strs.join('\n') : strs[0]) : k[2].trim(); + } + out[m[1].toUpperCase()] = o; + } + return out; +} +/** What does the PWAD hold? { eps: ['5'] (own episodes 5..9), maps: names that replace maps, title } */ +function pwadInfo(d, fileName) { + const L = readWad(d), eps = new Set(), maps = []; + for (const [nm] of L) { const m = /^E(\d)M\d$/.exec(nm); if (m) { if (+m[1] >= 5) eps.add(m[1]); else maps.push(nm); } else if (/^MAP\d\d$/.test(nm)) maps.push(nm); } + if (!eps.size && !maps.length) throw new Error('no maps in the extra WAD'); + const ui = L.find((x) => x[0] === 'UMAPINFO'), info = ui ? umapinfo(new TextDecoder('latin1').decode(ui[1])) : {}; + let title = ''; + for (const v of Object.values(info)) if (v.episode) { const q = [...String(v.episode).matchAll(/"([^"]*)"/g)]; title = q[1] ? q[1][1] : ''; } + if (!title && fileName) title = fileName.replace(/\.wad$/i, '').replace(/[_-]?v\d.*$/i, '').replace(/_/g, ' '); + // maps that probably need more RAM than the Paradise has (about 74 KB for a map): lines, sides, sectors, things + const big = []; + L.forEach(([nm], i) => { + if (!/^(E\dM\d|MAP\d\d)$/.test(nm)) return; + const g = (n) => { const y = L.slice(i + 1, i + 12).find((z) => z[0] === n); return y ? y[1].length : 0; }; + if (g('LINEDEFS') / 14 * 6 + g('SIDEDEFS') / 30 + g('SECTORS') / 26 * 44 + g('THINGS') / 10 * 92 > 85000) big.push(nm); + }); + return { eps: [...eps].sort(), maps, big, title: (title || 'EXTRA').toUpperCase().slice(0, 16) }; +} +// MIDI (MThd) -> MUS: the DOOM program plays MUS only. 140 ticks per second, channel 10 of MIDI is 15 of MUS. +const MUS_CTRL = { 0: 1, 1: 2, 7: 3, 10: 4, 11: 5, 91: 6, 93: 7, 64: 8, 67: 9 }, MUS_SYS = { 120: 10, 123: 11, 126: 12, 127: 13, 121: 14 }; +function mid2mus(mid) { + const r32 = (o) => ((mid[o] << 24) | (mid[o + 1] << 16) | (mid[o + 2] << 8) | mid[o + 3]) >>> 0, r16 = (o) => (mid[o] << 8) | mid[o + 1]; + if (String.fromCharCode(mid[0], mid[1], mid[2], mid[3]) !== 'MThd') return null; + const ntr = r16(10), div = r16(12); if (div & 0x8000) return null; + const ev = [], tempos = [[0, 500000]]; let p = 8 + r32(4); + for (let t = 0; t < ntr && p + 8 <= mid.length; t++) { + const len = r32(p + 4); let q = p + 8; const end = q + len; let tick = 0, run = 0; + while (q < end) { + let d = 0, b; do { b = mid[q++]; d = (d << 7) | (b & 127); } while (b & 128); tick += d; + let st = mid[q]; if (st & 128) q++; else st = run; + if (st === 0xFF) { const ty = mid[q++]; let l = 0; do { b = mid[q++]; l = (l << 7) | (b & 127); } while (b & 128); if (ty === 0x51) tempos.push([tick, (mid[q] << 16) | (mid[q + 1] << 8) | mid[q + 2]]); q += l; continue; } + if (st === 0xF0 || st === 0xF7) { let l = 0; do { b = mid[q++]; l = (l << 7) | (b & 127); } while (b & 128); q += l; continue; } + run = st; const hi = st & 0xF0, ch = st & 15, a = mid[q++], c = (hi === 0xC0 || hi === 0xD0) ? 0 : mid[q++]; + ev.push([tick, ev.length, hi, ch, a, c]); + } + p = end; + } + tempos.sort((x, y) => x[0] - y[0]); ev.sort((x, y) => x[0] - y[0] || x[1] - y[1]); + const sec = (tick) => { let s = 0, t0 = 0, us = 500000; for (const [tt, u] of tempos) { if (tt >= tick) break; s += (tt - t0) * us / div / 1e6; t0 = tt; us = u; } return s + (tick - t0) * us / div / 1e6; }; + const chMap = new Map(), vol = new Array(16).fill(-1), out = []; + const musCh = (ch) => { if (ch === 9) return 15; if (!chMap.has(ch)) { if (chMap.size >= 15) return -1; chMap.set(ch, chMap.size); } return chMap.get(ch); }; + let last = -1, tPrev = 0; + const put = (bytes, t) => { + if (last >= 0) { let d = Math.max(0, Math.round((t - tPrev) * 140)); if (d) { out[last] |= 0x80; const v = []; v.unshift(d & 127); d >>= 7; while (d) { v.unshift(0x80 | (d & 127)); d >>= 7; } out.push(...v); tPrev = Math.round(t * 140) / 140; } } + last = out.length; out.push(...bytes); + }; + for (const [tick, , hi, ch, a, c] of ev) { + const m = musCh(ch); if (m < 0) continue; const t = sec(tick); + if (hi === 0x90 && c > 0) { if (vol[m] !== c) { vol[m] = c; put([0x10 | m, 0x80 | a, c], t); } else put([0x10 | m, a], t); } + else if (hi === 0x80 || hi === 0x90) put([0x00 | m, a], t); + else if (hi === 0xE0) put([0x20 | m, c * 2 + (a >> 6) & 255], t); + else if (hi === 0xC0) put([0x40 | m, 0, a], t); + else if (hi === 0xB0) { if (MUS_SYS[a] !== undefined) put([0x30 | m, MUS_SYS[a]], t); else if (MUS_CTRL[a] !== undefined) put([0x40 | m, MUS_CTRL[a], c & 127], t); } + } + put([0x60], ev.length ? sec(ev[ev.length - 1][0]) : 0); + const head = 16, score = out.length, res = new Uint8Array(head + score); + res.set([0x4D, 0x55, 0x53, 0x1A]); w16(res, 4, score); w16(res, 6, head); w16(res, 8, chMap.size); w16(res, 10, 0); w16(res, 12, 0); w16(res, 14, 0); + res.set(out, head); + return score <= 0xFFFF ? res : null; +} +/** Base IWAD + extra WADs. pw: [{ data, slot }]: slot true = its own episode goes into the place of E4. */ +function wadMerge(base, pw) { + let L = readWad(base).map(([n, d]) => [n, d]); + const MAPL2 = new Set(['THINGS', 'LINEDEFS', 'SIDEDEFS', 'VERTEXES', 'SEGS', 'SSECTORS', 'NODES', 'SECTORS', 'REJECT', 'BLOCKMAP', 'BEHAVIOR']); + const isMap = (n) => /^E\dM\d$/.test(n) || /^MAP\d\d$/.test(n); + const set = (name, data) => { const i = L.findIndex((x) => x[0] === name); if (i >= 0) L[i] = [name, data]; else L.push([name, data]); }; + for (const { data, slot } of pw) { + const P = readWad(data).map(([n, d]) => [n, d]), info = pwadInfo(data), e = slot && info.eps[0]; + const ui = P.find((x) => x[0] === 'UMAPINFO'), um = ui ? umapinfo(new TextDecoder('latin1').decode(ui[1])) : {}; + const get = (n) => { const x = P.find((y) => y[0] === n); return x ? x[1] : null; }; + const ren = new Map(); // lumps of the PWAD under a new name (into the place of E4) + if (e) { + const names = [], txt = []; let back = ''; + for (let k = 1; k <= 9; k++) { + const u = um['E' + e + 'M' + k] || {}; + names.push(('E' + e + 'M' + k + ': ' + (u.levelname || '')).toUpperCase()); + const pic = u.levelpic || ('WILV' + (+e - 1) + (k - 1)); if (get(pic)) ren.set(pic, 'WILV3' + (k - 1)); + const mus = get(u.music || ('D_E' + e + 'M' + k)); + if (mus) { const mm = mus[0] === 0x4D && mus[1] === 0x55 && mus[2] === 0x53 ? mus : mid2mus(mus); if (mm) set('D_E4M' + k, mm); } + if (u.exitpic && get(u.exitpic)) ren.set(u.exitpic, 'INTERPIC'); + if (u.endpic && get(u.endpic)) ren.set(u.endpic, 'ENDPIC'); + if (u.intertext) txt.push(u.intertext); + if (k === 9 && u.next) { const m = /M(\d)$/.exec(u.next); if (m) back = m[1]; } + if (k === 1 && u.episode) { const q = /"?(\w+)"?/.exec(u.episode); if (q && get(q[1])) ren.set(q[1], 'M_EPI4'); } + } + if (!um['E' + e + 'M1'] && get('M_EPI' + e)) ren.set('M_EPI' + e, 'M_EPI4'); + const et = txt.length ? txt[txt.length - 1] : (get('E' + e + 'TEXT') ? new TextDecoder('latin1').decode(get('E' + e + 'TEXT')) : ''); + const enc = (s) => Uint8Array.from([...s.replace(/\r/g, '')].map((c) => c.charCodeAt(0) & 255).concat([0])); + set('PDMHU4', enc(names.join('\n'))); + if (et) set('PDMTXT4', enc(et.toUpperCase())); + if (back) set('PDMNXT4', enc(back)); + ren.set('CREDIT', ren.get('CREDIT') || null); // its own title pictures stay out (the base keeps its own) + // the sky: the texture of its maps becomes SKY4 (the engine takes SKY4 for E4) + const sky = (um['E' + e + 'M1'] || {}).skytexture || ('SKY' + e); + for (const tn of ['TEXTURE1', 'TEXTURE2']) { + const td = get(tn); if (!td) continue; + const cnt = u32(td, 0); + for (let i = 0; i < cnt; i++) { + const o = u32(td, 4 + 4 * i), nm = upName(td, o); + const put = (s) => { for (let q = 0; q < 8; q++) td[o + q] = q < s.length ? s.charCodeAt(q) : 0; }; + if (nm === 'SKY4') put('SKY4OLD'); else if (nm === sky) put('SKY4'); + } + } + } + // maps: a map of the PWAD replaces the one of the same name (E5M3 becomes E4M3 in the place of E4) + const outMaps = [], flats = [], sprites = [], rest = []; + let sect = ''; + for (let i = 0; i < P.length; i++) { + const [n, d] = P[i]; + if (MARKERS.test(n)) { sect = n.endsWith('_START') ? n[0] : ''; continue; } + if (isMap(n)) { let j = i + 1; while (j < P.length && MAPL2.has(P[j][0])) j++; const nn = e && n.startsWith('E' + e + 'M') ? 'E4M' + n[3] : n; outMaps.push([nn, P.slice(i + 1, j)]); i = j - 1; continue; } + if (sect === 'F') { flats.push([n, d]); continue; } + if (sect === 'S') { sprites.push([n, d]); continue; } + if (PWAD_DROP.has(n) || /^D_E\dM\d$/.test(n) || /_ZD$/.test(n)) continue; + if (ren.has(n)) { const to = ren.get(n); if (to) rest.push([to, d]); continue; } + if (e && new RegExp('^(WILV' + (+e - 1) + '\\d|M_EPI' + e + '|E' + e + 'TEXT|CREDIT)$').test(n)) continue; + if (e && d.length > 8 && s16(d, 0) === 320 && s16(d, 2) === 200) continue; // its other full pictures (title, end) are not used + rest.push([n, d]); + } + for (const [nm, lumps] of outMaps) { + const i = L.findIndex((x) => x[0] === nm); + if (i >= 0) { let j = i + 1; while (j < L.length && MAPL2.has(L[j][0])) j++; L.splice(i, j - i, [nm, new Uint8Array(0)], ...lumps); } + else { let k = -1; L.forEach((x, q) => { if (isMap(x[0])) k = q; }); let j = k + 1; while (j < L.length && MAPL2.has(L[j][0])) j++; L.splice(j, 0, [nm, new Uint8Array(0)], ...lumps); } + } + const into = (endName, items) => { for (const [n, d] of items) { const i = L.findIndex((x) => x[0] === n); if (i >= 0) L[i] = [n, d]; else { const k = L.findIndex((x) => x[0] === endName); if (k >= 0) L.splice(k, 0, [n, d]); else L.push([n, d]); } } }; + into('F_END', flats); into('S_END', sprites); + for (const [n, d] of rest) set(n, d); + } + return writeWad(L, 'IWAD'); +} + +// ------------------------------------------------- extra lumps (gbaextras.py) +function patchRead(b) { + const w = s16(b, 0), h = s16(b, 2), lo = s16(b, 4), to = s16(b, 6); + const px = []; for (let x = 0; x < w; x++) px.push(new Array(h).fill(null)); + for (let x = 0; x < w; x++) { + let c = u32(b, 8 + 4 * x); + while (b[c] !== 255) { const y0 = b[c], ln = b[c + 1]; for (let t = 0; t < ln; t++) if (y0 + t < h) px[x][y0 + t] = b[c + 3 + t]; c += ln + 4; } + } + return { w, h, lo, to, px }; +} +function patchWrite(w, h, lo, to, px) { + const cols = []; + for (let x = 0; x < w; x++) { + const col = []; let y = 0; + while (y < h) { + if (px[x][y] === null) { y++; continue; } + const y0 = y, run = []; + while (y < h && px[x][y] !== null && run.length < 128) { run.push(px[x][y]); y++; } + col.push(y0, run.length, run[0], ...run, run[run.length - 1]); + } + col.push(255); cols.push(col); + } + let size = 8 + 4 * w; cols.forEach(c => size += c.length); + const out = new Uint8Array(size); w16(out, 0, w); w16(out, 2, h); w16(out, 4, lo); w16(out, 6, to); + let off = 8 + 4 * w; + cols.forEach((c, x) => { w32(out, 8 + 4 * x, off); out.set(c, off); off += c.length; }); + return out; +} +const squeeze = (px, w, nw) => nw === w ? px : Array.from({ length: nw }, (_, x) => px[Math.min(w - 1, Math.floor((x * w + (w >> 1)) / nw))]); +function textPatch(L, txt, scale = 2) { + const glyphs = [...txt].map(ch => ch === ' ' ? null : patchRead(L.get('STCFN' + String(ch.charCodeAt(0)).padStart(3, '0')))); + const H = Math.max(...glyphs.filter(Boolean).map(g => g.h)) * scale, cols = []; + const empty = () => new Array(H).fill(null); + for (const g of glyphs) { + if (!g) { for (let k = 0; k < 4 * scale; k++) cols.push(empty()); continue; } + for (let x = 0; x < g.w; x++) { + const col = empty(); + for (let y = 0; y < g.h; y++) { const v = g.px[x][y]; if (v !== null) for (let sy = 0; sy < scale; sy++) col[(H - g.h * scale) + y * scale + sy] = v; } + for (let k = 0; k < scale; k++) cols.push(col); + } + for (let k = 0; k < scale; k++) cols.push(empty()); + } + return patchWrite(cols.length, H, 0, 0, cols); +} +const SEGS = [[0, 48, 0, 34], [48, 104, 34, 78], [104, 143, 78, 107], [143, 178, 107, 135], [178, 236, 135, 177], [236, 249, 177, 187], [249, 320, 187, 240]]; +function stbarGba(L) { + const B = patchRead(L.get('STBAR')), A = patchRead(L.get('STARMS')); + const bar = B.px, W = B.w; + for (let x = 0; x < A.w; x++) for (let y = 0; y < A.h; y++) if (A.px[x][y] !== null && 104 + x < W) bar[104 + x][y] = A.px[x][y]; + const out = []; for (let x = 0; x < 240; x++) out.push(new Array(32).fill(0)); + for (const [s0, s1, d0, d1] of SEGS) for (let x = d0; x < d1; x++) { + const sx = s0 + Math.floor(((x - d0) * (s1 - s0) + ((s1 - s0) >> 1)) / (d1 - d0)); + for (let y = 0; y < 32; y++) { const v = bar[Math.min(W - 1, sx)][y]; out[x][y] = v !== null && v !== undefined ? v : 0; } + } + const P = patchRead(L.get('STTPRCNT')), pc = squeeze(P.px, P.w, 10); + for (const px0 of [68, 168]) for (let x = 0; x < 10; x++) for (let y = 0; y < P.h; y++) { const v = pc[x][y]; if (v !== null && px0 + x < 240) out[px0 + x][6 + y] = v; } + const r = new Uint8Array(240 * 32); for (let y = 0; y < 32; y++) for (let x = 0; x < 240; x++) r[y * 240 + x] = out[x][y]; + return r; +} +/** Replacement for gbadoom.wad, built only from the user's own WAD. */ +function gbaExtras(wad) { + const L = new Map(readWad(wad)); + const lumps = [['CREDITS', patchWrite(1, 1, 0, 0, [[null]])], ['M_ARUN', textPatch(L, 'ALWAYS RUN')], ['M_GAMMA', textPatch(L, 'GAMMA')]]; + for (let i = 0; i < 10; i++) { const p = patchRead(L.get('STTNUM' + i)); lumps.push(['STGANUM' + i, patchWrite(10, p.h, p.lo, p.to, squeeze(p.px, p.w, 10))]); } + for (let i = 1; i <= 5; i++) lumps.push(['PLAYPAL' + i, L.get('PLAYPAL')]); + lumps.push(['STBARGBA', stbarGba(L)]); + return writeWad(lumps, 'PWAD'); +} + +// --------------------------------------------------------- converter (WASM) +async function convert(sub, extras, wasm) { + const { instance } = await WebAssembly.instantiate(wasm, {}); + const X = instance.exports; + X.reset(); + const pw = X.alloc(sub.length + 8); new Uint8Array(X.memory.buffer).set(sub, pw); + const pg = X.alloc(extras.length + 8); new Uint8Array(X.memory.buffer).set(extras, pg); + const po = X.convert(pw, sub.length, pg, extras.length), n = X.out_len(); + if (!po || !n) throw new Error('WAD conversion failed'); + return new Uint8Array(X.memory.buffer, po, n).slice(); +} + +// ------------------------------------------------------------- into the ROM +/** + * Install DOOM. rom: 16 MB Paradise image, mcu: converted WAD, emb: { app, xip, stub } (embedded), + * E: ParamixEmu (scene table, stub). Returns { rom, free }. + */ +function doomPatch(rom, mcu, emb, E) { + if (rom.length !== 0x1000000) throw new Error('the Paradise image must be 16 MB'); + const assetEnd = 0x111000 + 16 + u32(rom, 0x111000 + 8); + if (assetEnd > WAD_OFF) throw new Error('the character data reaches 0x' + assetEnd.toString(16) + ', DOOM needs 0x830000 onwards'); + if (CODE_OFF + emb.xip.length > SAVE_OFF) throw new Error('DOOM program too big'); + const free = REGION_OFF - WAD_OFF - 4 - mcu.length; + if (free < 0) throw new Error('WAD too big: ' + (mcu.length >> 10) + ' KB, room ' + ((REGION_OFF - WAD_OFF - 4) >> 10) + ' KB (try without music)'); + // Program and stub as for the emulator (shared stub, A+C), but without color Tama firmware + const out = E.installApp(rom, emb.app, emb.stub); + out.fill(0xFF, CODE_OFF, SAVE_END); + out.set(emb.xip, CODE_OFF); + out.fill(0xFF, WAD_OFF, REGION_END); + w32(out, WAD_OFF, mcu.length); + out.set(mcu, WAD_OFF + 4); + return { rom: out, free }; +} +// ------------------------------------------------------------- buttons +/* + * Button mapping in the program's PDMC settings block (from DOOM v0.4.0, version 2): + * button masks A 1, B 2, C 4, wheel press 8. Fixed: A+C menu, B+C map, + * wheel for 2 s returns to the Paradise. + */ +const KEYS_DEFAULT = { fire: 1, fwd: 2, back: 4, use: 8, mod: 4, run: true, invert: true }; +function pdmcAt(rom) { + for (let i = 0xA0000; i < 0xA0400; i += 4) if (u32(rom, i) === 0x434D4450) return i; + return -1; +} +/** Button mapping of a ROM with DOOM, or null (no DOOM, or an old version without mapping). */ +function doomKeysGet(rom) { + const i = pdmcAt(rom); + if (i < 0 || u32(rom, i + 4) < 2) return null; + return { fire: u32(rom, i + 48), fwd: u32(rom, i + 52), back: u32(rom, i + 56), use: u32(rom, i + 60), mod: u32(rom, i + 64), run: !!u32(rom, i + 68), invert: !!u32(rom, i + 44) }; +} +/** Check a mapping: returns an error text or ''. */ +function doomKeysCheck(k) { + if (k.fire === k.fwd || k.fire === k.back || k.fwd === k.back) return 'fire, forward and back need three different buttons'; + if (k.use !== 8 && [k.fire, k.fwd, k.back].includes(k.use)) return 'use needs its own button or the wheel'; + return ''; +} +/** Write a mapping into a ROM with DOOM (new image). */ +function doomKeysSet(rom, k) { + const out = new Uint8Array(rom); + const i = pdmcAt(out); + if (i < 0 || u32(out, i + 4) < 2) throw new Error('this DOOM has no key layout of its own yet'); + const err = doomKeysCheck(k); if (err) throw new Error(err); + w32(out, i + 44, k.invert ? 1 : 0); + w32(out, i + 48, k.fire); w32(out, i + 52, k.fwd); w32(out, i + 56, k.back); w32(out, i + 60, k.use); w32(out, i + 64, k.mod); w32(out, i + 68, k.run ? 1 : 0); + return out; +} + +/** Full path from the user's own WAD to the ROM. */ +async function doomBuild(rom, wad, opts, emb, E) { + const eps = opts.episode || '1'; + const sub = wadSub(wad, eps, opts.music !== false); + const mcu = await convert(sub, gbaExtras(sub), emb.wasm); + const r = doomPatch(rom, mcu, emb, E); + if (opts.keys) r.rom = doomKeysSet(r.rom, opts.keys); + return r; +} + +const DOOM_APP_B64 = '__DOOM_APP_B64__', DOOM_XIP_B64 = '__DOOM_XIP_B64__', DOOM_WASM_B64 = '__DOOM_WASM_B64__'; +const DOOMF_APP_B64 = '__DOOMF_APP_B64__', DOOMF_XIP_B64 = '__DOOMF_XIP_B64__'; // 1.7.2 DOOM_FREE: build with its places from the settings block +function embedded() { + if (DOOM_APP_B64.startsWith('__')) return null; + const fr = !DOOMF_APP_B64.startsWith('__'); + return { app: b64(DOOM_APP_B64), xip: b64(DOOM_XIP_B64), wasm: b64(DOOM_WASM_B64), appF: fr ? b64(DOOMF_APP_B64) : null, xipF: fr ? b64(DOOMF_XIP_B64) : null }; +} + +root.ParamixDoom = { PWAD, pwadInfo, wadMerge, mid2mus, umapinfo, KEYS_DEFAULT, doomKeysGet, doomKeysSet, doomKeysCheck, readWad, writeWad, wadEpisodes, wadSub, gbaExtras, convert, doomPatch, doomBuild, embedded, WAD_OFF, REGION_OFF, REGION_END, CODE_OFF, SAVE_OFF, SAVE_END }; +if (typeof module !== 'undefined') module.exports = root.ParamixDoom; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/src/emu.js b/src/emu.js new file mode 100644 index 0000000..a9fe78f --- /dev/null +++ b/src/emu.js @@ -0,0 +1,2276 @@ +/* + * Paramix Studio: install a color Tama emulator into the Paradise ROM. + * The emulator program (emu.bin, GPL-3.0, core derived from tamaemu) and + * the stub are embedded as Base64 at build time. The user supplies the + * color Tama firmware; it never leaves the computer. + * + * Layout in the Paradise flash: + * 0x0A0000 emulator program (copied to PRAM at startup) + * 0x0B0000 stub and home screen hook (hold A+C) + * 0x0C0000 saved run state (written by the emulator itself) + * 0x940000 color Tama firmware, packed in 64 KB blocks; behind it, up to + * 0xD40000, spare pages for blocks the guest writes (item stores) + * 0x840000 instead, for firmware that does not fit there (P's, 4U+): up to 0xD48000. + * The menu's field saves then have no room. + * + * Author: mameise + */ +(function (root) { +'use strict'; + +const XIP_DEC = 0x11000; +const xip = (off) => 0x10000000 + off - XIP_DEC; +const APP_OFF = 0xA0000, STUB_OFF = 0xB0000, SAVE_OFF = 0xC0000, SAVE_END = 0x110000; +const GUEST_OFF = 0x940000, GUEST_END = 0xD40000; +const BIG_OFF = 0x840000, BIG_END = 0xD48000, SPARE_MIN = 0x4000; // big firmware (1.3.2); 256 KB aligned like 0x940000 +const APP_MAX = 0x10000; +const PMXC = 0x43584D50; +// Placeholders in the prebuilt stub (stub_tpl.bin) +const PH_APP = 0x1234ABCD, PH_AUTO = 0x66666661, PH_ORIG = [0x22222221, 0x33333331, 0x44444441, 0x55555551]; +const HOOK_OFF = [0x40, 0x46, 0x4C, 0x52]; +const DEVICES = { + pc: { kind: 0, size: 0x400000, label: '4 MB', par: 0x3F }, + idl: { kind: 1, size: 0x800000, label: '8 MB', par: 0x00 }, + ps: { kind: 2, size: 0x800000, label: "P's", par: 0x00 }, + '4u': { kind: 3, size: 0x800000, label: '4U+', par: 0x00 }, + '4u-plain': { kind: 4, size: 0x800000, label: '4U', par: 0x00 }, + t7: { kind: 99, size: 0, label: 'T7Emu', par: 0x00 }, // V7 (T7Emu), not packed like the others + t18: { kind: 98, size: 0, label: 'T18Emu', par: 0x00 }, // TG18 (T18Emu), own block map +}; +// 8 MB firmware by its reset vector (file offset 0x400000), as tamaemu's dlc tool tells them apart +const RESET_VEC = { 0x024FDFE6: 'ps', 0x024F6256: '4u', 0x024C680A: '4u-plain' }; +// Blocks with many data accesses first: they sit in the cached 1 MB window +const HOT = { + pc: [0x25, 0x21, 0x04, 0x02, 0x01, 0x03, 0x05, 0x20, 0x22, 0x23, 0x24, 0x26, 0x27, 0x28, 0x29, 0x2a], + idl: [0x0b, 0x0e, 0x0d, 0x19, 0x08, 0x09, 0x16, 0x18, 0x0c, 0x17, 0x4f, 0x50, 0x40, 0x15, 0x4c, 0x4d], // v0.8.17 after measuring (0x08/0x09 added) + // 1.6.13 test10: the blocks P's, 4U+ and 4U read most (measured in the device simulation: menus, status, letter + // and room scenes); before, these took the first blocks in order and their hottest code was read uncached + ps: [0x14, 0x1d, 0x40, 0x1a, 0x1e, 0x53, 0x16, 0x20, 0x1b, 0x15, 0x50, 0x26, 0x51, 0x55, 0x41, 0x52], + '4u': [0x0d, 0x10, 0x40, 0x53, 0x14, 0x23, 0x0e, 0x50, 0x51, 0x0f, 0x4f, 0x41, 0x55, 0x52, 0x4d, 0x19], + '4u-plain': [0x0f, 0x13, 0x4f, 0x40, 0x0d, 0x10, 0x4c, 0x4d, 0x4e, 0x52, 0x41, 0x50, 0x18, 0x51], +}; + +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } +/* 1.7.2: placing into a ROM without the Paradise (appsPlace opts.clean): no pictures, no Paradise save, the whole flash */ +let CLEAN = false; +function assetEnd(b) { return CLEAN ? 0x10000 : 0x111000 + 16 + u32(b, 0x111000 + 8); } +function isFF(b, a, n) { for (let i = a; i < a + n; i++) if (b[i] !== 0xFF) return false; return true; } +function b64(s) { + if (typeof atob === 'function') { const t = atob(s); const o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; } + return new Uint8Array(Buffer.from(s, 'base64')); +} + +// 1.7.4 test2: ID_STRAP_ON: the Tamagotchi iD firmwares (also Lovely Melody) read the debug pin the other way round than the +// Plus Color; flags bit 13 tells TamaEmu to leave the pin on "no debug" +const ID_STRAP_ON = true, ID_STRAP = 0x2000; +function idFirmware(g) { + if (!ID_STRAP_ON || !g || g.length > 0x400000) return false; + const t = [0x54, 0x41, 0x4D, 0x41, 0x47, 0x4F, 0x00]; // "TAMAGO\0", only in the iD firmwares + outer: for (let i = 0; i + t.length <= g.length; i++) { for (let j = 0; j < t.length; j++) if (g[i + j] !== t[j]) continue outer; return true; } + return false; +} +/** Which firmware is this? Returns 'pc' or 'idl', or throws an error. */ +function emuDetect(g) { + if (g.length >= 0x100 && g.length <= 0x400000) { + const v = u32(g, 0); + if (v >= 0xC00000 && v < 0x1000000) return 'pc'; + } + if (g.length > 0x400000 && g.length <= 0x800000) { + const v = u32(g, 0x400000); + if (v >= 0x2000000 && v < 0x2800000) return RESET_VEC[v] || 'idl'; + } + throw new Error('firmware not recognised (expected a 4 MB or 8 MB image of a colour Tamagotchi)'); +} + +/** Paradise scene table: name -> flash offset of the 28-byte entry. */ +function sceneTable(d) { + const names = new Map(); + const pat = [0x50, 0x53, 0x49, 0x44, 0x5F]; // "PSID_" + for (let i = 0; i + 5 < d.length; i++) { + if (d[i] !== 0x50 || d[i + 1] !== 0x53 || d[i + 2] !== 0x49 || d[i + 3] !== 0x44 || d[i + 4] !== 0x5F) continue; + let j = i + 5; while (j < d.length && ((d[j] >= 0x41 && d[j] <= 0x5A) || (d[j] >= 0x30 && d[j] <= 0x39) || d[j] === 0x5F)) j++; + if (d[j] !== 0) continue; + let s = ''; for (let k = i; k < j; k++) s += String.fromCharCode(d[k]); + names.set(xip(i), s); + i = j; + } + void pat; + const ptrs = []; + for (let o = 0; o + 4 <= d.length; o += 4) { const w = u32(d, o); if (names.has(w)) ptrs.push([o, w]); } + if (!ptrs.length) throw new Error('scene table not found'); + let best = [], run = [ptrs[0]]; + for (let k = 1; k < ptrs.length; k++) { + if (ptrs[k][0] - ptrs[k - 1][0] === 28) run.push(ptrs[k]); + else { if (run.length > best.length) best = run; run = [ptrs[k]]; } + } + if (run.length > best.length) best = run; + const base = best[0][0] - 4, tab = {}; + best.forEach(([o, w], i) => { tab[names.get(w)] = base + i * 28; }); + return tab; +} + +/** Pack the firmware into 64 KB blocks. Returns { map, blob, blocks }. */ +/* 1.7.1 GUEST_SPARSE: a TamaEmu in the menu (opts.sparse) keeps the almost empty firmware blocks (at most two 8 KB + * parts with data, never read in the device simulation: menus, games, status, shop) as spare pages instead of whole + * 64 KB blocks. The device reads them over its spare page table as it does since 1.6.6 for written blocks; the hot + * blocks stay as they are, so the speed is the same. iD L 4 blocks (about 250 KB less), P's 7 (up to about 450 KB). */ +const GUEST_SPARSE = true, SPARSE_MAX = 2, SPARSE_PG = 16; +const LZ_GONE = true; // 1.7.3 test21: see guestPagesIn and emu/src/emu/state.c +const SPARSE_SKIP = { idl: [0x5b], '4u': [0x56] }; // read now and then in the simulation (170 s of play): stays a whole block +/* a block that may go into spare pages: not the parameter block, not hot, not read in the simulation, no download item + * store (the Studio writes items there, the device keeps its spare pages) */ +function sparseOk(dev, b) { + const D = DEVICES[dev]; if (!D || b === D.par || (HOT[dev] || []).includes(b) || (SPARSE_SKIP[dev] || []).includes(b)) return false; + return !(DLC_DEV[dev] || []).some((k) => b >= k.base >> 16 && b <= (k.base + k.n * k.size - 1) >> 16); +} +/* GUEST_SPARSE: the firmware parts a TamaEmu in the menu keeps as spare pages, back into its guest (as SV.emuGuestAsync + * reads them; only blocks that can be paged and at most SPARSE_MAX parts, so the pet's own writes elsewhere stay on the + * device as before) */ +function guestPagesIn(rom, c, g) { + if (!GUEST_SPARSE || !c.spareEnd) return; + const lo = (c.guestOff + c.guestSize + 0x1FFF) & ~0x1FFF, hi = c.spareEnd & ~0x1FFF; + if (hi < lo + 0x4000 || hi > rom.length) return; + const data = lo + 0x2000, n = Math.min(64, (hi - data) >> 13); + let x = (0x50584D50 ^ Math.imul(n, 0x9E3779B1)) >>> 0; + const vp = []; for (let i = 0; i < 64; i++) { const v = rom[lo + 16 + 2 * i] | (rom[lo + 17 + 2 * i] << 8); vp.push(v); x = (((x << 5) | (x >>> 27)) ^ v) >>> 0; } + if (u32(rom, lo) !== 0x50584D50 || u32(rom, lo + 4) !== n || u32(rom, lo + 8) !== x) return; + const per = new Map(); + // 1.7.3 test21 LZ_GONE: packed blocks the pet erased read empty, with all their written parts (as on the device) + const gone = new Set(); { const t = rom.subarray(lo, lo + 164), o = 144; let gx = 0x454E4F47; for (let i = 0; i < 4; i++) gx = (gx ^ u32(t, o + 4 * i)) >>> 0; + if (LZ_GONE && c.lzOff && gx === u32(t, o + 16)) for (let b = 0; b < 128; b++) if ((u32(t, o + 4 * (b >> 5)) >>> (b & 31)) & 1) { gone.add(b); if ((b << 16) < g.length) g.fill(0xFF, b << 16, (b + 1) << 16); } } + for (let i = 0; i < n; i++) { const v = vp[i]; if (v === 0xFFFF || (v << 13) >= g.length) continue; const b = v >> 3; if (gone.has(b)) { g.set(rom.subarray(data + (i << 13), data + ((i + 1) << 13)), v << 13); continue; } if (c.map[b] !== 0xFF || !sparseOk(c.dev, b)) continue; if (!per.has(b)) per.set(b, []); per.get(b).push([v, i]); } + for (const [, l] of per) if (l.length <= SPARSE_MAX) for (const [v, i] of l) g.set(rom.subarray(data + (i << 13), data + ((i + 1) << 13)), v << 13); +} +/* 1.7.3 GUEST_LZ: a TamaEmu in the menu keeps its cold firmware blocks packed (LZ4 blocks of 1 KB). Cold: not the + * parameter block, not hot, no download item store and not read in the device simulation (170 s of play: menus, games, + * status, shop, letters). The device unpacks a 1 KB part when the guest reads it (two parts kept in RAM); the hot and + * warm blocks stay as they are, so the speed stays the same. Layout behind the packed blocks: 128 u32 (offset of the + * block's part list from the table, 0 = not packed), per packed block 65 u32 (part k from [k] to [k+1]: same = erased, + * 1024 bytes = stored, else LZ4), then the data. */ +const GUEST_LZ = true, LZ_PART = 0x400; +/* 1.7.4 BIG_LZ: a save that ran for a long time fills more blocks than fit (User: P's and 4U, "firmware too big: 92 + * blocks"). Then the cold blocks are packed, also when "Pack the firmware" is off (packing was only for room before). */ +const BIG_LZ = true; +/** BIG_LZ: does this firmware only fit packed? */ +function tamaNeedsLz(g, dev) { if (!BIG_LZ) return false; try { packGuest(g, dev, { sparse: true }); return false; } catch (e) { try { packGuest(g, dev, { lz: true }); return true; } catch (e2) { return false; } } } +const MAIN_LZ = true; // 1.7.2 test13: also for the main TamaEmu (emuPatch) +const LZ_WARM = { // read in the device simulation (besides HOT): stay whole + idl: [0x00, 0x08, 0x09, 0x0b, 0x0c, 0x0d, 0x0e, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x25, 0x40, 0x41, 0x44, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x5b], + ps: [0x00, 0x0b, 0x14, 0x15, 0x16, 0x1a, 0x1b, 0x1d, 0x1e, 0x20, 0x21, 0x26, 0x2a, 0x40, 0x41, 0x43, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55], + '4u': [0x00, 0x08, 0x0d, 0x0e, 0x0f, 0x10, 0x12, 0x13, 0x14, 0x19, 0x23, 0x26, 0x35, 0x37, 0x38, 0x39, 0x40, 0x41, 0x4d, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x6e], + '4u-plain': [0x00, 0x08, 0x0d, 0x0f, 0x10, 0x12, 0x13, 0x18, 0x39, 0x3b, 0x3c, 0x40, 0x41, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52], + pc: [0x00, 0x02, 0x03, 0x04, 0x21, 0x25, 0x3f], // 1.7.3: 123 s simulation +}; +function lzOk(dev, b) { + const D = DEVICES[dev]; if (!D || !LZ_WARM[dev] || b === D.par || (HOT[dev] || []).includes(b) || LZ_WARM[dev].includes(b)) return false; + return !(DLC_DEV[dev] || []).some((k) => b >= k.base >> 16 && b <= (k.base + k.n * k.size - 1) >> 16); +} +/* LZ4 block (sequences: token, literals, offset, match; the last one only literals), hash chains */ +function lzEnc(src) { + const n = src.length, out = [], head = new Int32Array(4096).fill(-1), prev = new Int32Array(n).fill(-1); + const h4 = (i) => ((src[i] | src[i + 1] << 8 | src[i + 2] << 16 | src[i + 3] << 24) * 2654435761 >>> 20) & 4095; + const put = (v) => { while (v >= 255) { out.push(255); v -= 255; } out.push(v); }; + let i = 0, lit = 0; + const emit = (ml, off) => { + const ll = i - lit, t = out.length; out.push(((ll >= 15 ? 15 : ll) << 4) | (ml ? (ml - 4 >= 15 ? 15 : ml - 4) : 0)); + if (ll >= 15) put(ll - 15); + for (let k = lit; k < i; k++) out.push(src[k]); + if (ml) { out.push(off & 255, off >> 8); if (ml - 4 >= 15) put(ml - 19); } + void t; + }; + const ins = (p) => { if (p + 4 <= n) { const h = h4(p); prev[p] = head[h]; head[h] = p; } }; + while (i + 4 <= n) { + let best = 0, bo = 0; + for (let c = head[h4(i)], d = 0; c >= 0 && d < 256; c = prev[c], d++) { + let l = 0; while (i + l < n && src[c + l] === src[i + l]) l++; + if (l > best) { best = l; bo = i - c; if (i + l === n) break; } + } + if (best >= 4) { emit(best, bo); for (let k = 0; k < best; k++) ins(i + k); i += best; lit = i; } + else { ins(i); i++; } + } + i = n; emit(0, 0); + return new Uint8Array(out); +} +function lzDec(s, n) { + const d = new Uint8Array(n); let ip = 0, op = 0; + for (;;) { + const t = s[ip++]; let l = t >> 4; + if (l === 15) { let x; do { x = s[ip++]; l += x; } while (x === 255); } + while (l-- > 0 && op < n) d[op++] = s[ip++]; + if (op >= n || ip >= s.length) return d; + const o = s[ip] | (s[ip + 1] << 8); ip += 2; let m = (t & 15) + 4; + if ((t & 15) === 15) { let x; do { x = s[ip++]; m += x; } while (x === 255); } + while (m-- > 0 && op < n) { d[op] = d[op - o]; op++; } + } +} +/* the packed blocks as stored behind the firmware blocks (b: list of block numbers) */ +function lzPack(g, blocks) { + const tab = new Uint8Array(512), parts = [], lists = new Map(); + let pos = 512 + blocks.length * 65 * 4; + for (const b of blocks) { + const l = []; + for (let k = 0; k < 64; k++) { + l.push(pos); + const p = g.subarray((b << 16) + k * LZ_PART, (b << 16) + (k + 1) * LZ_PART); + if (p.every((v) => v === 0xFF)) continue; + let c = lzEnc(p); if (c.length >= LZ_PART) c = p; + parts.push(c); pos += c.length; + } + l.push(pos); lists.set(b, l); + } + const out = new Uint8Array(pos); + let lp = 512; + for (const b of blocks) { w32(tab, 4 * b, lp); lists.get(b).forEach((v, k) => w32(out, lp + 4 * k, v)); lp += 65 * 4; } + out.set(tab, 0); + let dp = 512 + blocks.length * 65 * 4; for (const c of parts) { out.set(c, dp); dp += c.length; } + return out; +} +/* back into the guest image g (rd(off, len) reads the flash at the table) */ +function lzUnpack(rd, g) { + const t = rd(0, 512); + for (let b = 0; b < 128 && (b << 16) < g.length; b++) { + const lp = u32(t, 4 * b); if (!lp) continue; + const l = rd(lp, 65 * 4); + for (let k = 0; k < 64; k++) { + const a = u32(l, 4 * k), z = u32(l, 4 * k + 4), at = (b << 16) + k * LZ_PART; + if (z === a) g.fill(0xFF, at, at + LZ_PART); + else if (z - a >= LZ_PART) g.set(rd(a, LZ_PART), at); + else g.set(lzDec(rd(a, z - a), LZ_PART), at); + } + } +} +/* GUEST_LZ: the TamaEmu program knows packed blocks (its settings block says version 5 in the template) */ +function tamaLzCan(app) { if (!app) return false; for (let i = 0; i + 8 <= Math.min(app.length, 0x400); i += 4) if (u32(app, i) === PMXC) return u32(app, i + 4) >= 5; return false; } +function packGuest(fw, dev, opts = {}) { + const D = DEVICES[dev]; + const g = new Uint8Array(D.size); g.fill(0xFF); g.set(fw.subarray(0, Math.min(fw.length, D.size))); + const n = D.size >> 16; + let used = []; + for (let i = 0; i < n; i++) if (i === D.par || !isFF(g, i << 16, 0x10000)) used.push(i); + // 1.6.6: a save of another emulator (P's with download content) can hold more blocks than fit. The sparsest + // blocks then go into spare pages (8 KB parts behind the packed firmware, as the device keeps written empty + // blocks); the device reads them from there. + const parts = (b) => { const r = []; for (let k = 0; k < 8; k++) if (!isFF(g, (b << 16) + (k << 13), 0x2000)) r.push((b << 3) + k); return r; }; + const room = BIG_END - BIG_OFF, PG_RES = 4; + const need = (nb, np) => np ? ((((nb << 16) + 0x1FFF) & ~0x1FFF) + 0x2000 + ((np + PG_RES) << 13)) : (nb << 16) + SPARE_MIN; + let paged = [], lzb = []; + const lzBig = BIG_LZ && GUEST_LZ && opts.lz && !opts.lzOnly && !!LZ_WARM[dev] && need(used.length, 0) > room; + if (need(used.length, 0) > room && !lzBig) { + const cand = used.filter((b) => b !== D.par).map((b) => ({ b, p: parts(b) })).sort((x, y) => x.p.length - y.p.length); + let nb = used.length, np = 0; + for (const c of cand) { + if (need(nb, np) <= room) break; + if (c.p.length >= 8 || np + c.p.length + PG_RES > 64) break; + paged.push(c); nb--; np += c.p.length; + } + if (need(nb, np) > room) throw new Error('firmware too big: ' + used.length + ' blocks'); + used = used.filter((b) => !paged.some((c) => c.b === b)); + } else if (GUEST_LZ && opts.lz && (LZ_WARM[dev] || opts.lzAll)) { + lzb = opts.lzOnly ? used.filter((b) => opts.lzOnly.includes(b)) // MAIN_FEW: only these + : used.filter((b) => opts.lzAll ? b !== DEVICES[dev].par : lzOk(dev, b) || (opts.lzExtra || []).includes(b)); // lzAll, lzExtra: tests only + used = used.filter((b) => !lzb.includes(b)); + } else if (GUEST_SPARSE && opts.sparse) { + let np = 0; + for (const b of used) { + if (!sparseOk(dev, b)) continue; + const p = parts(b); if (p.length > SPARSE_MAX || np + p.length > SPARSE_PG) continue; + paged.push({ b, p }); np += p.length; + } + used = used.filter((b) => !paged.some((c) => c.b === b)); + } + const order = HOT[dev].filter((b) => used.includes(b)).concat(used.filter((b) => !HOT[dev].includes(b))); + const map = new Uint8Array(128); map.fill(0xFF); + const blob = new Uint8Array(order.length << 16); + order.forEach((b, idx) => { map[b] = idx; blob.set(g.subarray(b << 16, (b + 1) << 16), idx << 16); }); + const pages = [].concat(...paged.map((c) => c.p.map((v) => ({ v, data: g.subarray(v << 13, (v + 1) << 13) })))); + if (BIG_OFF + blob.length + SPARE_MIN > BIG_END) throw new Error('firmware too big: ' + order.length + ' blocks'); + if (lzb.length) { // GUEST_LZ: the packed cold blocks behind the others + const z = lzPack(g, lzb), all = new Uint8Array(blob.length + z.length); all.set(blob); all.set(z, blob.length); + if (BIG_OFF + all.length + SPARE_MIN > BIG_END) throw new Error('firmware too big: ' + (order.length + lzb.length) + ' blocks'); + return { map, blob: all, lzOff: blob.length, lzBlocks: lzb.length, blocks: order.length, big: !!opts.lzOnly && GUEST_OFF + all.length + SPARE_MIN > GUEST_END, pages }; + } + return { map, blob, blocks: order.length, big: pages.length > 0 || GUEST_OFF + blob.length + SPARE_MIN > GUEST_END, pages }; +} +/** Spare pages of the guest behind the packed firmware: table (as state.c of the device) and 8 KB parts. */ +function putPages(out, gOff, gEnd, blobLen, pages) { + const lo = (gOff + blobLen + 0x1FFF) & ~0x1FFF, hi = gEnd & ~0x1FFF, data = lo + 0x2000; + const n = Math.min(64, (hi - data) >> 13); + if (pages.length > n) throw new Error('no room for the spare pages'); + const vp = new Array(64).fill(0xFFFF); + pages.forEach((p, i) => { vp[i] = p.v; out.set(p.data, data + (i << 13)); }); + let x = (0x50584D50 ^ Math.imul(n, 0x9E3779B1)) >>> 0; + for (let i = 0; i < 64; i++) x = (((x << 5) | (x >>> 27)) ^ vp[i]) >>> 0; + out.fill(0xFF, lo, lo + 0x1000); + w32(out, lo, 0x50584D50); w32(out, lo + 4, n); w32(out, lo + 8, x); w32(out, lo + 12, 0); + vp.forEach((v, i) => { out[lo + 16 + 2 * i] = v & 255; out[lo + 17 + 2 * i] = v >> 8; }); +} + +/** Is an emulator already installed? Returns the original handlers or null. */ +function installedOrigs(rom, tab) { + const o = tab.PSID_HOME; + const cur = [0, 1, 2, 3].map((k) => u32(rom, o + 12 + 4 * k)); + const lo = xip(STUB_OFF), hi = lo + 0x1000; + if (!cur.some((v) => v >= lo && v < hi)) return null; + return PH_ORIG.map((_, k) => u32(rom, STUB_OFF + 0x94 + 4 * k)); +} + +/** Install the stub with its home screen hook (shared by the emulator and DOOM). */ +function installStub(out, tab, prev, stubTpl) { + const origs = prev || [0, 1, 2, 3].map((k) => u32(out, tab.PSID_HOME + 12 + 4 * k)); + const st = new Uint8Array(stubTpl); + const put = (ph, v) => { let n = 0; for (let i = 0; i + 4 <= st.length; i += 2) if (u32(st, i) === ph) { w32(st, i, v); n++; } if (n !== 1) throw new Error('launcher template does not fit'); }; + put(PH_APP, xip(APP_OFF)); + PH_ORIG.forEach((ph, k) => put(ph, origs[k])); + for (let i = 0; i + 4 <= st.length; i += 2) if (u32(st, i) === PH_AUTO) w32(st, i, 0); // autostart off, see autoSet + out.fill(0xFF, STUB_OFF, STUB_OFF + 0x1000); + out.set(st, STUB_OFF); + HOOK_OFF.forEach((h, k) => w32(out, tab.PSID_HOME + 12 + 4 * k, (xip(STUB_OFF) + h) | 1)); +} +/** Install only the program and stub (for DOOM). Returns a new image. */ +function installApp(rom, app, stubTpl, opts = {}) { + if (rom.length !== 0x1000000) throw new Error('the Paradise image must be 16 MB'); + const out = new Uint8Array(rom); + const tab = sceneTable(out); + if (!tab.PSID_HOME) throw new Error('home screen not found'); + const prev = installedOrigs(out, tab); + if (!prev && !isFF(out, APP_OFF, 0x11000)) throw new Error('area 0x0A0000 is in use'); + if (app.length > APP_MAX) throw new Error('program too big'); + if (!opts.keep) freeT18(out); // opts.keep (1.6.8): the same program again (stub swap), T18Emu keeps its blocks + out.fill(0x00, APP_OFF, APP_OFF + APP_MAX); + out.set(app, APP_OFF); + installStub(out, tab, prev, stubTpl); + return out; +} + +/** + * Install the emulator. rom: 16 MB Paradise image, guest: color Tama + * firmware, app/stub: embedded binaries. Returns a new image. + */ +function emuPatch(rom, guest, app, stubTpl, opts = {}) { + if (rom.length !== 0x1000000) throw new Error('the Paradise image must be 16 MB'); + const dev = opts.device || emuDetect(guest); + const out = new Uint8Array(rom); + const tab = sceneTable(out); + if (!tab.PSID_HOME) throw new Error('home screen not found'); + const prev = installedOrigs(out, tab); + freeT18(out); + // Regions must be free (or already used by us) + // MAIN_LZ (1.7.2 test13): the main TamaEmu packs its cold blocks as well (as in the menu). Before, a P's with a VDP set + // kept only 3 spare pages for its own writes; installing the VDP writes about 35, the rest was lost and the game hung. + const pk = mainPick(guest, dev, app, opts.pack), lzMain = pk.lzOff !== undefined || (MAIN_LZ && tamaLzCan(app) && !pk.raw), { map, blob, blocks, pages } = pk; + const big = pk.big || GUEST_OFF + blob.length + SPARE_MIN > GUEST_END; + const gOff = big ? BIG_OFF : GUEST_OFF, gEnd = big ? BIG_END : GUEST_END; + if (big && assetEnd(out) > 0x830000) throw Object.assign(new Error('the character data reaches 0x' + assetEnd(out).toString(16) + ', the emulator needs 0x830000 onwards'), { needPack: !!pk.raw && MAIN_LZ && tamaLzCan(app) }); + if (!prev) { + if (!isFF(out, APP_OFF, 0x11000)) throw new Error('area 0x0A0000 is in use'); + if (!isFF(out, gOff, gEnd - gOff)) throw new Error('area 0x' + gOff.toString(16) + ' is in use'); + } + if (!isFF(out, SAVE_OFF, SAVE_END - SAVE_OFF) && !prev) throw new Error('area 0x0C0000 is in use'); + // Store the packed guest (an earlier one may sit in the other layout) + if (prev && u32(out, APP_OFF + 0x140) === PMXC) { const o = u32(out, APP_OFF + 0x148); if (o === BIG_OFF) out.fill(0xFF, BIG_OFF, BIG_END); else if (o === GUEST_OFF) out.fill(0xFF, GUEST_OFF, GUEST_END); } + out.fill(0xFF, gOff, gEnd); + out.set(blob, gOff); + if (pages.length) putPages(out, gOff, gEnd, blob.length, pages); + // Program with settings + if (app.length > APP_MAX) throw new Error('emulator program too big'); + const a = new Uint8Array(app); + let ci = -1; for (let i = 0; i + 4 <= a.length; i += 4) if (u32(a, i) === PMXC) { ci = i; break; } + if (ci < 0) throw new Error('settings block missing in the program'); + // version 3: the room behind the packed firmware up to GUEST_END holds the guest's spare pages + // version 4 (1.5.1): flags at +156, bit 1 = clock from the Paradise at every start (on unless opts.clock === false) + const v4 = a.length >= ci + 160 && u32(a, ci + 156) === 0; + w32(a, ci + 4, v4 ? 4 : 3); w32(a, ci + 8, gOff); w32(a, ci + 12, blob.length); w32(a, ci + 16, SAVE_OFF); w32(a, ci + 20, DEVICES[dev].kind); + a.set(map, ci + 24); + w32(a, ci + 152, gEnd); + if (v4) w32(a, ci + 156, (opts.clock === false ? 0 : 2) | ((opts.lang === 'en' || opts.lang === 'ko') ? 1 : 0) | (dev === 'pc' && idFirmware(guest) ? ID_STRAP : 0)); // bit 0 (1.6.6): English texts + if (lzMain && v4) { w32(a, ci + 4, 5); w32(a, ci + 160, pk.lzOff !== undefined ? gOff + pk.lzOff : 0); } // MAIN_LZ: version 5, table of the packed blocks + out.fill(0x00, APP_OFF, APP_OFF + APP_MAX); + out.set(a, APP_OFF); + installStub(out, tab, prev, stubTpl); + // erase the old save (it may belong to a different firmware) + out.fill(0xFF, SAVE_OFF, SAVE_END); + return { rom: out, device: dev, blocks, big }; +} + +/** + * Newer emulator program into a ROM that already has the emulator (v1.2.6). + * Only the program at 0x0A0000 changes: settings (firmware layout) are taken over, + * the packed firmware, the spare pages and the saved session stay. Returns null if + * the program is already the same. + */ +function emuUpgrade(rom, app) { + const ci0 = 0x140; + if (u32(rom, APP_OFF + ci0) !== PMXC) return null; + const a = new Uint8Array(app); + let ci = -1; for (let i = 0; i + 4 <= a.length; i += 4) if (u32(a, i) === PMXC) { ci = i; break; } + if (ci !== ci0) return null; + const ver = u32(rom, APP_OFF + ci + 4); + if (ver < 2) return null; + for (let i = 8; i < 152; i++) a[ci + i] = rom[APP_OFF + ci + i]; + w32(a, ci + 4, 4); + if (ver >= 5) { if (!tamaLzCan(app)) return null; w32(a, ci + 4, 5); w32(a, ci + 160, u32(rom, APP_OFF + ci + 160)); } // MAIN_LZ: the packed layout stays + w32(a, ci + 152, ver >= 3 ? u32(rom, APP_OFF + ci + 152) : GUEST_END); + w32(a, ci + 156, ver >= 4 ? u32(rom, APP_OFF + ci + 156) : 2); // 1.5.1: the clock switch, on for older ROMs + const go = u32(a, ci + 8); + if (!(go === GUEST_OFF && u32(a, ci + 152) <= GUEST_END) && !(go === BIG_OFF && u32(a, ci + 152) <= BIG_END)) return null; + let same = true; + for (let i = 0; i < APP_MAX && same; i++) if ((i < 0x13C || i > 0x13F) && rom[APP_OFF + i] !== (i < a.length ? a[i] : 0)) same = false; // test24: 0x13C the way back (Studio) + if (same) return null; + const out = new Uint8Array(rom); + out.fill(0x00, APP_OFF, APP_OFF + APP_MAX); + out.set(a, APP_OFF); + return out; +} + +/* + * Autostart (v1.2.7): the stub holds a word (0/1, placeholder PH_AUTO in the template). + * stubs = [[offset in the ROM, template], ...]. The ROM's stub must match the template + * everywhere except the placeholder words. + */ +const PH_ALL = [PH_APP, 0x6789EF01, PH_AUTO, ...PH_ORIG]; +function autoAt(rom, stubs) { + for (const [off, tpl] of stubs) { + if (off < 0 || off + tpl.length > rom.length) continue; + let at = -1, ok = true; + const skip = new Set(); + for (let i = 0; i + 4 <= tpl.length; i += 2) { const w = u32(tpl, i); if (PH_ALL.includes(w)) { for (let k = 0; k < 4; k++) skip.add(i + k); if (w === PH_AUTO) at = i; } } + if (at < 0) continue; + for (let i = 0; i < tpl.length && ok; i++) if (!skip.has(i) && rom[off + i] !== tpl[i]) ok = false; + if (ok && u32(rom, off + at) <= 1) return off + at; + } + return -1; +} +// Stubs of 1.2.7 (autostart once per power-on): only read, the Studio puts in the current one +const STUB_127 = ['crYA8IW4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/4UMAu4N/4UMAr4N/4TMAo4N/4TMAl4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACEiIiIxMzMzQURERFFVVVUt6Q9QFEgBaBRKUrEUShNoFEiDQgXQEGAR9ABvAdD/952/DUgQShNoEfTAbw/RGAxO8qFxiEID0EDyAAPO8qFzATMTYJiyWii/9IivAeAAIxNgvegPUGBHAIABQGFmZmb8DwAgQVJQQfgPACBytk/wikNI8kECGmAEItpgT/SAAdpoRCoB0AE5+tENSAAhT/SAMlD4BDtB+AQ7BDr50b/zT4+/82+PB0gAIQFgBkgBaAH04GEFShFDAWC/80+P/ufNqzQSCO0A4AztAOAEAPoF', 'crYBTADwirjNqzQSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/4UMAu4N/4UMAr4N/4TMAo4N/4TMAl4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACEiIiIxMzMzQURERFFVVVUt6Q9QFkgBaBZKUrEWShNoFkiDQgXQEGAR9ABvAdD/952/D0gSShNoEfTAbxPRGAxO8qFxiEID0EDyAAPO8qFzATMTYJiyWigH0wpMACw/9IWvcrYQ4AAjE2C96A9QYEcAgAFAYWZmZvwPACBBUlBB+A8AIAHviWdytk/wikNI8kECGmAEItpgT/SAAdpoRCoB0AE5+tEgRgAhT/SAMlD4BDtB+AQ7BDr50b/zT4+/82+PBkgAIQFgBUgBaAH04GEEShFDAWC/80+P/ucI7QDgDO0A4AQA+gU=']; +// Menu stub of 1.6.0 to 1.6.7 (menu address at 0x148, before the launcher entry of 1.6.8) +const STUB_FELD_167 = 'crYBTADworjNqzQScrYERgTxoEQE9Yg0APCYuAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/4UMAu4N/4UMAr4N/4TMAo4N/4TMAl4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACEiIiIxMzMzQURERFFVVVUt6Q9QH0gBaB9K2rEfSpN4w7n/I5Nwk3ijsR1KE2gdSINCDdAcSINCA9AcSABoHigG0hlIEGAR9ABvA9D/946/FUgQYA9IFkoTaBH0wG8T0RgMTvKhcYhCA9BA8gADzvKhcwEzE2CYslooB9MNTAAsP/R0r3K2F+AAIxNgvegPUGBHAAAAgAFAYWZmZhjtAOD8DwAgUE1YTFBNWFIEAwBF+A8AIAHviWdytk/wikNI8kECGmAEItpgT/SAAdpoRCoB0AE5+tEgRgAhT/SAMlD4BDtB+AQ7BDr50b/zT4+/82+PBkgAIQFgBUgBaAH04GEEShFDAWC/80+P/ucI7QDgDO0A4AQA+gU='; +// Stubs up to 1.7.2 test18 (before the B fallback to the flash app): only read +const STUB_172 = ['crYA8J24AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/4UMAu4N/4UMAr4N/4TMAo4N/4TMAl4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACEiIiIxMzMzQURERFFVVVUt6Q9QHUgBaB1K2rEdSpN4w7n/I5Nwk3ijsRtKE2gbSINCDdAaSINCA9AaSABoHigG0hdIEGAR9ABvA9D/946/E0gQYA1IFEoTaBH0wG8P0RgMTvKhcYhCA9BA8gADzvKhcwEzE2CYsloov/R3rwHgACMTYL3oD1BgRwAAAIABQGFmZmYY7QDg/A8AIFBNWExQTVhSBAMARfgPACBytk/wikNI8kECGmAEItpgT/SAAdpoRCoB0AE5+tENSAAhT/SAMlD4BDtB+AQ7BDr50b/zT4+/82+PB0gAIQFgBkgBaAH04GEFShFDAWC/80+P/ufNqzQSCO0A4AztAOAEAPoF', 'crYBTADwwLjNqzQScrYERgTxoEQE9Yg0APC2uAAAAABytgFMAPCwuAHviWcA8Iy4AAAAAAAAAAAAAAAAAAAAAN/4UMAu4N/4UMAr4N/4TMAo4N/4TMAl4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACEiIiIxMzMzQURERFFVVVUt6Q9QH0gBaB9K2rEfSpN4w7n/I5Nwk3ijsR1KE2gdSINCDdAcSINCA9AcSABoHigG0hlIEGAR9ABvA9D/946/FUgQYA9IFkoTaBH0wG8U0RgMTvKhcYhCA9BA8gADzvKhcwEzE2CYslooCNNf+OxAACw/9HOvcrY04AAjE2C96A9QYEcAgAFAYWZmZhjtAOD8DwAgUE1YTFBNWFIEAwBF+A8AIC3pD1ANSAGIQojSQ5KykUIQ0YGLQPLkcpFCC9NA9jMCkUIH2MGLATkMKQPScrZf+FBBBeC96A9QYEcAAADg72Bytk/wikNI8kECGmAEItpgT/SAAdpoRCoB0AE5+tEgRgAhT/SAMlD4BDtB+AQ7BDr50b/zT4+/82+PBkgAIQFgBUgBaAH04GEEShFDAWC/80+P/ucI7QDgDO0A4AQA+gU=']; +// Stubs of 1.7.2 test19 to 1.7.3 test28 (before BFALL_NOA: A+C at the first home call could start the flash app): only read +const STUB_173 = ['crYBTADwzLjNqzQSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/4UMAu4N/4UMAr4N/4TMAo4N/4TMAl4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACEiIiIxMzMzQURERFFVVVUt6Q9QMEgBaDBKE3gLu/8jE3ATeOuxEfSAbxrRLEoSaCxIgkIV0CxIAGgeKAXTK0iCQgLQKkiCQgvRKkgCaCpLmkIG0QJpKUuaQgLRcrYcRlTgHUgBaCZK2rEmSpN4w7n/I5Nwk3ijsRlKE2gZSINCDdAaSINCA9AXSABoHigG0hZIEGAR9ABvA9D/92e/E0gQYA1IGEoTaBH0wG8P0RgMTvKhcYhCA9BA8gADzvKhcwEzE2CYsloov/RQrwHgACMTYL3oD1BgRwCAAUAZ7QDg/A8AIFBNWEwEAwBFUE1YUlBNWE0A4P9gU09OSQAA/2BhZmZmGO0A4PgPACBytk/wikNI8kECGmAEItpgT/SAAdpoRCoB0AE5+tEgRgAhT/SAMlD4BDtB+AQ7BDr50b/zT4+/82+PBkgAIQFgBUgBaAH04GEEShFDAWC/80+P/ucI7QDgDO0A4AQA+gU=', 'crYBTADw8rjNqzQScrYERgTxoEQE9Yg0APDouAAAAABytgFMAPDiuAHviWcA8L64AAAAAAAAAAAAAAAAAAAAAN/4UMAu4N/4UMAr4N/4TMAo4N/4TMAl4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACEiIiIxMzMzQURERFFVVVUt6Q9QM0gBaDNKE3gLu/8jE3ATeOuxEfSAbxrRL0oSaC9IgkIV0C9IAGgeKAXTLkiCQgLQLUiCQgvRLUgCaC1LmkIG0QJpLEuaQgLRcrYcRnrgIEgBaClK2rEpSpN4w7n/I5Nwk3ijsRxKE2gcSINCDdAdSINCA9AaSABoHigG0hlIEGAR9ABvA9D/92e/FkgQYBBIG0oTaBH0wG8U0RgMTvKhcYhCA9BA8gADzvKhcwEzE2CYslooCNNf+DhBACw/9EyvcrY/4AAjE2C96A9QYEcAAACAAUAZ7QDg/A8AIFBNWEwEAwBFUE1YUlBNWE0A4P9gU09OSQAA/2BhZmZmGO0A4PgPACAt6Q9QDUgBiEKI0kOSspFCENGBi0Dy5HKRQgvTQPYzApFCB9jBiwE5DCkD0nK2X/i0QQXgvegPUGBHAAAA4O9gcrZP8IpDSPJBAhpgBCLaYE/0gAHaaEQqAdABOfrRIEYAIU/0gDJQ+AQ7QfgEOwQ6+dG/80+Pv/NvjwZIACEBYAVIAWgB9OBhBEoRQwFgv/NPj/7nCO0A4AztAOAEAPoF']; +function legacyStubs(stubs) { + const out = []; + for (const [off] of stubs) for (const t of STUB_127.concat([STUB_FELD_167], STUB_172, STUB_173)) out.push([off, b64(t)]); + return out; +} +/** Autostart setting of the ROM: true, false, or null (stub without the switch). */ +function autoGet(rom, stubs) { const a = autoAt(rom, stubs); return a < 0 ? null : u32(rom, a) === 1; } +/** Was the autostart on in a stub of 1.2.7? */ +function autoGetOld(rom, stubs) { const a = autoAt(rom, legacyStubs(stubs)); return a >= 0 && u32(rom, a) === 1; } +/** Set the autostart word. Returns a new image, or null if the stub has no such word. */ +function autoSet(rom, stubs, on) { + const a = autoAt(rom, stubs); + if (a < 0) return null; + const out = new Uint8Array(rom); w32(out, a, on ? 1 : 0); return out; +} + +/** Remove the emulator again (home screen back to the original handlers). */ +function emuRemove(rom) { + const out = new Uint8Array(rom); + const tab = sceneTable(out); + const prev = installedOrigs(out, tab); + if (!prev) throw new Error('no emulator built in'); + const c18 = t18Cfg(rom); + if (c18) for (const b of c18.map.concat(c18.spare)) if (b !== 0xFFFF) out.fill(0xFF, b << 16, (b + 1) << 16); + prev.forEach((v, k) => w32(out, tab.PSID_HOME + 12 + 4 * k, v)); + out.fill(0xFF, APP_OFF, APP_OFF + 0x11000); + out.fill(0xFF, SAVE_OFF, SAVE_END); + out.fill(0xFF, GUEST_OFF, GUEST_END); + if (u32(rom, APP_OFF + 0x140) === PMXC && u32(rom, APP_OFF + 0x148) === BIG_OFF) out.fill(0xFF, BIG_OFF, BIG_END); + // DOOM: program part in the flash window and WAD (only behind the character data) + out.fill(0xFF, STUB_OFF + 0x1000, SAVE_OFF); + const assetEnd = (0x111000 + 16 + u32(out, 0x111000 + 8) + 0xFFF) & ~0xFFF; + out.fill(0xFF, Math.max(0x830000, assetEnd), 0xD48000); + return out; +} + +// ------------------------------------------------------------ download content +/* + * Download content (DLC) for the 8 MB firmware (iD L). Store geometry and routing + * come from tamaemu (tools/dlc.c, GPL-3.0, maragotchi): a record is a TAMAGO + * block, routed by (type [0x4E], category [0x50], flag [0x51]) into a store; + * it goes into the first fully erased slot, existing slots are never overwritten. + */ +const IDL_STORES = [ + { kind: 0, base: 0x590000, size: 0x0800, n: 20, label: 'Meals' }, + { kind: 1, base: 0x5A0000, size: 0x0800, n: 20, label: 'Snacks' }, + { kind: 2, base: 0x600000, size: 0x4000, n: 5, label: 'Clothing' }, + { kind: 3, base: 0x650000, size: 0x2000, n: 10, label: 'Accessories' }, + { kind: 4, base: 0x6A0000, size: 0x2000, n: 10, label: 'Items' }, + { kind: 5, base: 0x740000, size: 0x8000, n: 5, label: 'Daily items' }, + { kind: 6, base: 0x780000, size: 0x2000, n: 10, label: 'Wallpapers' }, + { kind: 7, base: 0x7A0000, size: 0x8000, n: 2, label: 'Games' }, + { kind: 8, base: 0x7B0000, size: 0x8000, n: 2, label: 'Destinations' }, +]; +const IDL_ROUTE = [ + [0x81, 0x02, 0x01, 0], [0x81, 0x0C, 0x02, 1], [0x81, 0x0D, 0x02, 1], [0x81, 0x1F, 0x00, 6], + [0x81, 0x29, 0x00, 5], [0x81, 0x29, 0x02, 5], [0x81, 0x2A, 0x01, 4], [0x81, 0x33, 0x00, 2], + [0x81, 0x34, 0x00, 3], [0x81, 0x35, 0x00, 3], [0x94, 0x47, 0x02, 8], [0x94, 0x5B, 0x01, 7], +]; +// 1.6.6: P's, 4U+ and 4U, stores and routing likewise from tamaemu's tools/dlc.c +const PS_STORES = [ + { kind: 0, base: 0x5A0000, size: 0x0800, n: 20, label: 'Meals' }, + { kind: 1, base: 0x5B0000, size: 0x0800, n: 15, label: 'Snacks' }, + { kind: 2, base: 0x610000, size: 0x4000, n: 5, label: 'Clothing' }, + { kind: 3, base: 0x660000, size: 0x2000, n: 10, label: 'Accessories' }, + { kind: 4, base: 0x6B0000, size: 0x2000, n: 10, label: 'Items' }, + { kind: 6, base: 0x6F0000, size: 0x2000, n: 10, label: 'Wallpapers' }, + { kind: 7, base: 0x710000, size: 0x8000, n: 2, label: 'Games' }, + { kind: 8, base: 0x720000, size: 0x8000, n: 2, label: 'Destinations' }, + { kind: 10, base: 0x750000, size: 0x8000, n: 4, label: 'VDP recipes' }, +]; +const PS_ROUTE = [[0x81, 0x02, 0], [0x81, 0x0D, 1], [0x81, 0x33, 2], [0x81, 0x34, 3], [0x81, 0x35, 3], [0x81, 0x2A, 4], [0x81, 0x1F, 6], [0x81, 0x29, 10], [0x94, 0x47, 8]]; +const FOURU_STORES = [ + { kind: 15, base: 0x5A0000, size: 0x2000, n: 4, label: 'Decorations' }, + { kind: 0, base: 0x5B0000, size: 0x0800, n: 20, label: 'Meals' }, + { kind: 1, base: 0x5C0000, size: 0x0800, n: 20, label: 'Snacks' }, + { kind: 2, base: 0x610000, size: 0x4000, n: 5, label: 'Clothing' }, + { kind: 3, base: 0x660000, size: 0x2000, n: 10, label: 'Accessories' }, + { kind: 4, base: 0x6C0000, size: 0x2000, n: 15, label: 'Items' }, + { kind: 6, base: 0x6F0000, size: 0x2000, n: 10, label: 'Wallpapers' }, + { kind: 7, base: 0x710000, size: 0x8000, n: 2, label: 'Games' }, + { kind: 8, base: 0x720000, size: 0x8000, n: 4, label: 'Destinations' }, + { kind: 16, base: 0x740000, size: 0x2000, n: 1, label: 'Coupon' }, + { kind: 17, base: 0x750000, size: 0x8000, n: 1, label: 'Bingo' }, + { kind: 18, base: 0x760000, size: 0x8000, n: 1, label: 'Gashapon' }, + { kind: 19, base: 0x780000, size: 0x8000, n: 8, label: 'Characters' }, +]; +const FOURU_ROUTE = [ + [0x81, 0x01, 0x01, 0], [0x81, 0x02, 0x01, 0], [0x81, 0x01, 0x02, 1], [0x81, 0x0D, 0x02, 1], [0x81, 0x1F, 0x00, 6], + [0x81, 0x33, 0x00, 2], [0x81, 0x34, 0x00, 3], [0x81, 0x35, 0x00, 3], [0x94, 0x5B, 0x01, 7], [0x94, 0x5B, 0x02, 8], + [0x94, 0x48, 0x03, 19], [0x94, 0x47, 0x02, 8], +]; +const DLC_DEV = { idl: IDL_STORES, ps: PS_STORES, '4u': FOURU_STORES, '4u-plain': FOURU_STORES }; +const dlcDev = (g) => { let d = null; try { d = emuDetect(g); } catch (e) { /* unknown: as before */ } return DLC_DEV[d] ? d : g.length >= 0x7B0000 && !d ? 'idl' : null; }; +const dlcAscii = (r) => { let s = ''; for (let i = 0x34; i < 0x48 && i < r.length && r[i]; i++) s += String.fromCharCode(r[i]); return s; }; +function fouruId(s) { const m = /[0-9]{2,}/.exec(s); return m ? Number(m[0]) : -1; } +// kept for older callers: the game store +const GAME_BASE = 0x7A0000, GAME_SIZE = 0x8000, GAME_SLOTS = 2; +const isTamago = (g, o) => o + 6 <= g.length && g[o] === 0x54 && g[o + 1] === 0x41 && g[o + 2] === 0x4D && g[o + 3] === 0x41 && g[o + 4] === 0x47 && g[o + 5] === 0x4F; +function dlcName(r) { + let s = ''; for (let i = 6; i + 1 < 0x34; i += 2) { const c = (r[i] << 8) | r[i + 1]; if (!c) break; s += String.fromCharCode(c); } + return s.replace(/^DL_[A-Za-z]+_/, '').replace(/\.(jpg|JPG)$/, '').trim(); +} +/** All stores with their slots: [{ kind, label, slots: [{ slot, name|null }] }] (8 MB firmware: iD L, P's, 4U+, 4U). */ +function dlcStores(g) { + const dev = dlcDev(g); if (!dev) return []; + return DLC_DEV[dev].map((k) => ({ kind: k.kind, label: k.label, slots: Array.from({ length: k.n }, (_, i) => { + const o = k.base + i * k.size; + return { slot: i, name: isTamago(g, o) ? dlcName(g.subarray(o, o + 0x34)) : null }; + }) })); +} +/** Game slots (compatibility with the old single-store view). */ +function dlcSlots(g) { + const st = dlcStores(g).find((k) => k.kind === 7); + return st ? st.slots : []; +} +/** Store for a record: { kind, label } or null. dev: 'idl' (default), 'ps', '4u', '4u-plain'. */ +function dlcRoute(r, dev = 'idl') { + const t = r[0x4E], c = r[0x50], f = r[0x51], stores = DLC_DEV[dev] || IDL_STORES; + let kind = -1; + if (dev === 'ps') { + if (t === 0x94 && c === 0x5B) kind = f === 0x01 ? 7 : 8; + else if (t === 0x81 && c === 0x29 && dlcAscii(r).startsWith('idn_rec')) kind = -1; // recipe: store not known + else { const m = PS_ROUTE.find((x) => x[0] === t && x[1] === c); if (m) kind = m[2]; } + } else if (dev === '4u' || dev === '4u-plain') { + const id = fouruId(dlcAscii(r)), m1 = id % 1000; + if (t === 0x81 && c === 0x2A && f === 0x01) kind = id < 0 ? -1 : m1 >= 601 && m1 <= 749 ? 16 : m1 >= 801 && m1 <= 949 ? 15 : 4; + else if (t === 0x81 && c === 0x29 && f === 0x00) kind = id >= 0 && m1 >= 301 && m1 <= 449 ? 17 : id >= 0 && m1 >= 601 && m1 <= 749 ? 18 : -1; + else { const m = FOURU_ROUTE.find((x) => x[0] === t && x[1] === c && x[2] === f); if (m) kind = m[3]; } + } else { + const m = IDL_ROUTE.find((x) => x[0] === t && x[1] === c && x[2] === f); if (m) kind = m[3]; + } + return kind < 0 ? null : stores.find((k) => k.kind === kind) || null; +} +/** Extract and check the TAMAGO record of a download file (.jpg or raw). dev: firmware it goes into. */ +function dlcRecord(d, dev = 'idl') { + let m = -1; + if (isTamago(d, 0)) m = 0; + else { + let e = -1; for (let i = 0; i + 1 < d.length; i++) if (d[i] === 0xFF && d[i + 1] === 0xD9) { e = i + 2; break; } + for (let i = Math.max(0, e); i + 6 <= d.length; i++) if (isTamago(d, i)) { m = i; break; } + } + if (m < 0) throw new Error('no download content in the file'); + const b = d.subarray(m); + const ok = (n) => { if (n < 3) return false; let s = 0; for (let i = 0; i < n - 2; i++) s += b[i]; return (s & 0xFFFF) === ((b[n - 2] << 8) | b[n - 1]); }; + const decl = b.length >= 0x4C ? ((b[0x48] << 24) | (b[0x49] << 16) | (b[0x4A] << 8) | b[0x4B]) >>> 0 : 0; + let len = 0; + if (decl >= 0x60 && decl <= b.length && ok(decl)) len = decl; + else for (let s = 0; s <= 16; s++) { const n = b.length - s; if (n >= Math.max(0x60, decl) && ok(n)) { len = n; break; } } + if (!len) throw new Error('content checksum does not match'); + const r = b.slice(0, len); + const st = dlcRoute(r, dev); + if (!st) throw new Error('this content fits no store of this firmware'); + if (r.length > st.size) throw new Error('content too big for its store'); + return r; +} +function grow(g) { const out = new Uint8Array(Math.max(g.length, 0x800000)); out.fill(0xFF); out.set(g); return out; } +/** Add a record to the first free slot of its store. Returns { guest, store, slot }. */ +function dlcAdd(g, rec) { + const dev = dlcDev(g); if (!dev) throw new Error('only for the 8 MB firmware'); + const st = dlcRoute(rec, dev); if (!st) throw new Error('no matching store'); + const out = grow(g); + for (let i = 0; i < st.n; i++) { const o = st.base + i * st.size; if (isTamago(out, o) && out.subarray(o, o + rec.length).every((v, k) => v === rec[k])) throw new Error('already added'); } + for (let i = 0; i < st.n; i++) { + const o = st.base + i * st.size; + if (isTamago(out, o)) continue; + if (!out.subarray(o, o + st.size).every((v) => v === 0xFF)) continue; + out.set(rec, o); + return { guest: out, store: st, slot: i }; + } + throw new Error(st.label + ': all slots used, remove one first'); +} +/** Empty one slot. Returns the new firmware. */ +function dlcFree(g, kind, slot) { + const dev = dlcDev(g) || 'idl'; + const st = DLC_DEV[dev].find((k) => k.kind === kind); if (!st || slot < 0 || slot >= st.n) throw new Error('no such slot'); + const out = grow(g); const o = st.base + slot * st.size; + out.fill(0xFF, o, o + st.size); + return out; +} +/** Put a game into a given slot (replaces what is there). Returns the new firmware. */ +function dlcPut(g, rec, slot) { + if (g.length < 0x7B0000) throw new Error('only for the 8 MB firmware'); + const out = grow(g); + const o = GAME_BASE + slot * GAME_SIZE; + out.fill(0xFF, o, o + GAME_SIZE); out.set(rec, o); + return out; +} + + +// ------------------------------------------------------------ T7Emu (V7, 6502) +/* + * T7Emu (1.4.0): the V7 core of the T7Emu app (after asterick/tamago, BSD) as a second + * emulator. Same launcher and program place as TamaEmu (only one of them), settings block + * "PMX7" at 0x140 of the program. Layout: the ROM (Tama-Go 640 KB, Friends 768 KB) at 0x940000, the figures right + * behind it (trailing zero bytes cut off, the core reads them as zero anyway), up to + * 0xD40000. Save area at 0x0C0000: session (4 KB), the pet's EEPROM in two slots from 0x0C1000, settings at 0x0C5000. + */ +const T7_MAGIC = 0x37584D50, T7_ROM_SIZE = 0xA0000, T7_FIG_MAX = 16, T7_EE = 0xC1000, T7_EE_END = 0xC6000; // EEPROM slots, then the settings sector +const T7_APP_B64 = '__T7_APP_B64__'; +/* V1Emu (1.6.8): the first Tamagotchis and the Digital Monster (E0C6S46/48, TamaLIB core). Program 64 KB, session 4 KB, ROM. */ +const V1_APP_B64 = '__V1_APP_B64__'; +const V1_MAGIC = 0x31584D50; // "PMX1" +function v1Embedded() { return V1_APP_B64.startsWith('__') ? null : b64(V1_APP_B64); } +/* 1.6.9: V3Emu, the Tamagotchi Connection V3 (Sunplus SPLB32, core from BrickEmuPy by azya52, CC0). It has the settings + * block of V1Emu (same magic and layout), so the Studio handles it as a V1Emu; the program is picked by the ROM. */ +const GB_APP_B64 = '__GB_APP_B64__'; +function gbEmbedded() { return GB_APP_B64.startsWith('__') ? null : b64(GB_APP_B64); } +/* 1.6.9 test36: GBEmu (Game Boy, DMG). Settings block "PMXG" at 0x140: magic, version, ROM, its length, save (4 KB settings, + * then the cartridge RAM up to 32 KB), flags (bit 0 English, bit 1 wheel the other way round), name (16), keys (12 bytes). */ +const GB_MAGIC = 0x47584D50; // "PMXG" +/** keys[i] = Game Boy buttons (1 A, 2 B, 4 SELECT, 8 START, 16 RIGHT, 32 LEFT, 64 UP, 128 DOWN) for the Paradise input i: + * 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B */ +const GB_KEYS_DEFAULT = [32, 2, 16, 1, 64, 128, 8, 0, 0]; // test37: A left, C right; B+C free (run to the right), SELECT in the device's settings +/** A Game Boy ROM: 32 KB to 2 MB, size code at 0x148 matching, header checksum at 0x14D right. Colour-only games are refused. */ +function gbDetect(r) { + if (!r || r.length < 0x8000 || r.length > 0x200000 || (r.length & 0x7FFF)) return false; + if (r[0x148] > 6 || (0x8000 << r[0x148]) !== r.length) return false; + let x = 0; for (let i = 0x134; i <= 0x14C; i++) x = (x - r[i] - 1) & 255; + return x === r[0x14D]; +} +function gbColorOnly(r) { return r[0x143] === 0xC0; } +/* 1.7.2 GBCEmu: games with the colour flag (0x80 or 0xC0) get the Game Boy Color program (gbc/gbc.bin, flags bit 3); its + * save area is 96 KB (the whole Game Boy Color does not fit the 28 KB of a Game Boy state). Over 1 MB (the cached window) + * the game is stored in pages of 1 MB, each bank 0 and 63 switchable banks (flags bit 2). */ +const GBC_ON = true; +const GBC_APP_B64 = '__GBC_APP_B64__'; +function gbcEmbedded() { return GBC_APP_B64.startsWith('__') ? null : b64(GBC_APP_B64); } +const gbIsColor = (r) => GBC_ON && !!(r[0x143] & 0x80); +const gbSaveLen = (color) => (color ? 0x18000 : 0x10000); +const GB_PAGE_BANKS = 63; +function gbPage(rom) { + const n = rom.length / GB_BANK; if (rom.length <= 0x100000 || n !== Math.floor(n)) return null; + const pages = Math.ceil((n - 1) / GB_PAGE_BANKS), out = new Uint8Array(pages * 0x100000).fill(0xFF); + for (let p = 0; p < pages; p++) { + out.set(rom.subarray(0, GB_BANK), p * 0x100000); + for (let k = 0; k < GB_PAGE_BANKS; k++) { const b = 1 + p * GB_PAGE_BANKS + k; if (b >= n) break; out.set(rom.subarray(b * GB_BANK, (b + 1) * GB_BANK), p * 0x100000 + (k + 1) * GB_BANK); } + } + return out; +} +function gbUnpage(st, banks) { + const out = new Uint8Array(banks * GB_BANK); out.set(st.subarray(0, GB_BANK)); + for (let b = 1; b < banks; b++) { const p = Math.floor((b - 1) / GB_PAGE_BANKS), k = (b - 1) % GB_PAGE_BANKS; out.set(st.subarray(p * 0x100000 + (k + 1) * GB_BANK, p * 0x100000 + (k + 2) * GB_BANK), b * GB_BANK); } + return out; +} +/* what goes to the flash: { rom, banks (flags bits 16..31), paged } */ +function gbStore(rom) { + if (gbIsColor(rom) && rom.length > 0x100000) return { rom: gbPage(rom), banks: rom.length / GB_BANK, paged: true }; + const tr = gbTrim(rom); return { rom: tr.rom, banks: tr.banks, paged: false }; +} +function gbTitle(r) { let s = ''; for (let i = 0x134; i < 0x144; i++) { const c = r[i]; if (!c || c > 0x7E) break; if (c >= 0x20) s += String.fromCharCode(c); } return s.trim().toUpperCase() || 'GAME BOY'; } +/* 1.7.1 GB_TRIM: banks at the end of a game that are all the same (Pokémon Red/Blue: 18 banks of zeros, 288 KB) are + * stored once; the program reads every bank behind it from that one (flags bits 16..31: the game's bank count). The + * switchable bank is looked up when the game switches it, not on every read, so the game runs as fast as before. */ +const GB_TRIM = true, GB_BANK = 0x4000; +function gbTrim(rom) { + const n = rom.length / GB_BANK; + if (!GB_TRIM || n < 8 || n !== Math.floor(n) || n > 0xFFFF) return { rom, banks: 0 }; + const same = (i, j) => { for (let k = 0; k < GB_BANK; k++) if (rom[i * GB_BANK + k] !== rom[j * GB_BANK + k]) return false; return true; }; + let l = n - 1; while (l > 1 && same(l - 1, n - 1)) l--; + if (n - 1 - l < 4) return { rom, banks: 0 }; // less than 64 KB: kept whole + return { rom: rom.subarray(0, (l + 1) * GB_BANK), banks: n }; +} +/* the whole game again from a stored one (flags bits 16..31) */ +function gbUntrim(rom, flags) { + const n = flags >>> 16, have = rom.length / GB_BANK; + if (!n || n <= have || have !== Math.floor(have) || !have) return rom; + const out = new Uint8Array(n * GB_BANK); out.set(rom); + const last = rom.subarray(rom.length - GB_BANK); + for (let i = have; i < n; i++) out.set(last, i * GB_BANK); + return out; +} +function gbCfgWrite(a, c, x, romOff, saveOff, flags, tr) { + w32(a, c + 4, 1); w32(a, c + 8, romOff); w32(a, c + 12, tr ? tr.rom.length : x.rom.length); w32(a, c + 16, saveOff); w32(a, c + 20, (flags & (1 | NOSESS)) | (x.inv ? 2 : 0) | (tr && tr.paged ? 4 : 0) | (gbIsColor(x.rom) ? 8 : 0) | (tr && tr.banks ? tr.banks << 16 : 0)); + const nm = gbTitle(x.rom); a.fill(0, c + 24, c + 40); for (let i = 0; i < nm.length && i < 15; i++) a[c + 24 + i] = nm.charCodeAt(i); + const k = (x.keys && x.keys.length === 9) ? x.keys : GB_KEYS_DEFAULT; a.fill(0, c + 40, c + 52); k.forEach((v, i) => { a[c + 40 + i] = v & 255; }); +} +/* 1.6.10 test2 SMSEmu (Sega Master System). Settings block "PMXS" at 0x140, laid out as GBEmu's: magic, version, ROM, its + * length, save (4 KB settings, then the cartridge RAM, 32 KB), flags (bit 0 English, bit 1 wheel the other way round), + * name (16, from the file name), keys (12 bytes). */ +const SMS_APP_B64 = '__SMS_APP_B64__'; +function smsEmbedded() { return SMS_APP_B64.startsWith('__') ? null : b64(SMS_APP_B64); } +const SMS_MAGIC = 0x53584D50; // "PMXS" +/** keys[i] = Master System buttons (1 up, 2 down, 4 left, 8 right, 16 button 1, 32 button 2, 64 pause) for the Paradise + * input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B */ +const SMS_KEYS_DEFAULT = [4, 16, 8, 32, 1, 2, 64, 0, 0]; +/** "TMR SEGA" header at 0x7FF0, 0x3FF0 or 0x1FF0 (a 512 byte copier header in front is allowed) */ +function smsHead(r) { + const o0 = (r.length & 0x3FFF) === 512 ? 512 : 0; + for (const h of [0x7FF0, 0x3FF0, 0x1FF0]) { + const o = o0 + h; if (o + 16 > r.length) continue; + if (String.fromCharCode(...r.subarray(o, o + 8)) === 'TMR SEGA') return { off: o, region: r[o + 15] >> 4 }; + } + return null; +} +/** A Master System or Game Gear ROM: 8 KB to 1 MB; by its header, or (some games have none) by the file name ending + * .sms or .gg */ +function smsDetect(r, name) { + if (!r) return false; + const n = (r.length & 0x3FFF) === 512 ? r.length - 512 : r.length; + if (n < 0x2000 || n > 0x100000 || (n & 0x1FFF)) return false; + const h = smsHead(r); + if (h) return h.region >= 3 && h.region <= 7; // 3 SMS Japan, 4 SMS export, 5..7 Game Gear + return /\.(sms|gg)$/i.test(name || ''); +} +/** 1.6.11 test2: Game Gear (header region 5..7, or a file ending .gg) */ +function smsGameGear(r, name) { const h = smsHead(r); return h ? h.region >= 5 && h.region <= 7 : /\.gg$/i.test(name || ''); } +/** a short name from the file name: without brackets and the ending, upper case, at most 15 letters */ +function smsTitle(fname) { + let s = String(fname || '').replace(/\.[^.]*$/, '').replace(/[([].*$/, '').replace(/[^A-Za-z0-9 !'&.-]/g, ' ').toUpperCase(); + s = s.split(/\s+/).filter((w) => w && !['IN', 'OF', 'THE', 'AND', 'STARRING'].includes(w)).join(' '); + return s.slice(0, 15).trim() || 'MASTER SYSTEM'; +} +function smsCfgWrite(a, c, x, romOff, saveOff, flags) { + w32(a, c + 4, 1); w32(a, c + 8, romOff); w32(a, c + 12, x.rom.length); w32(a, c + 16, saveOff); w32(a, c + 20, (flags & (1 | NOSESS)) | (x.inv ? 2 : 0) | (x.gg ? 4 : 0)); + const nm = x.title || 'MASTER SYSTEM'; a.fill(0, c + 24, c + 40); for (let i = 0; i < nm.length && i < 15; i++) a[c + 24 + i] = nm.charCodeAt(i); + const k = (x.keys && x.keys.length === 9) ? x.keys : SMS_KEYS_DEFAULT; a.fill(0, c + 40, c + 52); k.forEach((v, i) => { a[c + 40 + i] = v & 255; }); +} +/* 1.7.3 PokeMiniEmu (Pokemon mini, core PokeMini by JustBurn, GPL). Settings block "PMXP" at 0x140: magic, version, the + * game, its length, save (64 KB: 4 KB settings, 8 KB EEPROM, the state up to 36 KB, an own BIOS at +0xC000), flags + * (bit 0 English, bit 1 wheel the other way round, bit 2 own BIOS), name (16), keys (12 x u16), place of the BIOS. + * Without an own BIOS the program takes PokeMini's free one. */ +const PM_APP_B64 = '__PM_APP_B64__'; +function pmEmbedded() { return PM_APP_B64.startsWith('__') ? null : b64(PM_APP_B64); } +const PM_MAGIC = 0x50584D50; // "PMXP" +/** keys[i] = Pokemon mini buttons (1 A, 2 B, 4 C, 8 up, 16 down, 32 left, 64 right, 128 power, 256 shake) for the + * Paradise input i: 0 A, 1 B, 2 C, 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B */ +const PM_KEYS_DEFAULT = [32, 2, 64, 1, 8, 16, 4, 0, 256]; +/** a Pokemon mini game (.min): "MN" at 0x2100, up to 1 MB (the cached window of the Paradise) */ +function pmDetect(r) { return !!r && r.length >= 0x2200 && r.length <= 0x100000 && r[0x2100] === 0x4D && r[0x2101] === 0x4E; } +function pmTooBig(r) { return !!r && r.length > 0x100000 && r.length <= 0x200000 && r[0x2100] === 0x4D && r[0x2101] === 0x4E; } +/** the Pokemon mini's BIOS (4 KB, starts with its jump table) */ +function pmBiosDetect(r) { return !!r && r.length === 0x1000 && r[0] === 0x9A && r[1] === 0x00; } +/** a short name from the file name: without brackets, "Pokemon" and the ending, upper case, at most 15 letters */ +function pmTitle(fname) { + let s = String(fname || '').replace(/\.[^.]*$/, '').replace(/[([].*$/, '').replace(/[^A-Za-z0-9 !'&.-]/g, ' ').toUpperCase(); + s = s.split(/\s+/).filter((w) => w && !['POKEMON', 'THE', 'OF'].includes(w)).join(' '); + return s.slice(0, 15).trim() || 'POKEMON MINI'; +} +const PM_SAVE = 0x10000, PM_BIOS_AT = 0xC000; +function pmCfgWrite(a, c, x, romOff, saveOff, flags) { + const own = !!(x.bios && pmBiosDetect(x.bios)); + w32(a, c + 4, 1); w32(a, c + 8, romOff); w32(a, c + 12, x.rom.length); w32(a, c + 16, saveOff); w32(a, c + 20, (flags & (1 | NOSESS)) | (x.inv ? 2 : 0) | (own ? 4 : 0)); + const nm = x.title || 'POKEMON MINI'; a.fill(0, c + 24, c + 40); for (let i = 0; i < nm.length && i < 15; i++) a[c + 24 + i] = nm.charCodeAt(i); + const k = (x.keys && x.keys.length === 9) ? x.keys : PM_KEYS_DEFAULT; a.fill(0, c + 40, c + 64); k.forEach((v, i) => { a[c + 40 + 2 * i] = v & 255; a[c + 41 + 2 * i] = (v >> 8) & 255; }); + w32(a, c + 64, own ? saveOff + PM_BIOS_AT : 0); +} +/* 1.7.3 ArduboyEmu (own ATmega32U4 emulation). Settings block "ABXP" at 0x140: magic, version, the game, its length, + * save, flags (bit 0 English, bit 1 wheel the other way round), name (16), keys (12 bytes). The game lies at the start + * of its own 64 KB block (the base of the cached window), the save (16 KB: 4 KB settings, 4 KB EEPROM (1 KB used), + * 8 KB state) at +0x8000 in the same block; the program has a 64 KB block of its own. */ +const AB_APP_B64 = '__AB_APP_B64__'; +function abEmbedded() { return AB_APP_B64.startsWith('__') ? null : b64(AB_APP_B64); } +const AB_MAGIC = 0x50584241; // "ABXP" +/** keys[i] = Arduboy buttons (1 up, 2 down, 4 left, 8 right, 16 A, 32 B) for the Paradise input i: 0 A, 1 B, 2 C, + * 3 wheel press, 4 wheel up, 5 wheel down, 6 A+C, 7 B+C, 8 A+B */ +const AB_KEYS_DEFAULT = [4, 32, 8, 16, 1, 2, 0, 0, 0]; +const AB_SAVE = 0x4000, AB_SAVE_AT = 0x8000, AB_MAX = 0x8000; +/** an Arduboy game from its .hex (Intel HEX text): the program (up to 32 KB) or null */ +function abHex(data) { + const txt = typeof data === 'string' ? data : new TextDecoder('latin1').decode(data); + if (!/^\s*:[0-9A-Fa-f]{10}/.test(txt)) return null; + const b = new Uint8Array(AB_MAX).fill(0xFF); let top = 0, hi = 0, any = false; + for (const raw of txt.split(/\r?\n/)) { + const l = raw.trim(); if (!l) continue; + if (l[0] !== ':' || l.length < 11) return null; + const n = parseInt(l.slice(1, 3), 16), ad = parseInt(l.slice(3, 7), 16), ty = parseInt(l.slice(7, 9), 16); + if (l.length < 11 + 2 * n) return null; + let sum = 0; for (let i = 1; i < 11 + 2 * n; i += 2) sum += parseInt(l.slice(i, i + 2), 16); + if (sum & 255) return null; + if (ty === 0) { + for (let i = 0; i < n; i++) { const a = hi + ad + i; if (a >= AB_MAX) return null; b[a] = parseInt(l.slice(9 + 2 * i, 11 + 2 * i), 16); top = Math.max(top, a + 1); any = true; } + } else if (ty === 1) break; + else if (ty === 2) hi = parseInt(l.slice(9, 13), 16) << 4; + else if (ty === 4) hi = parseInt(l.slice(9, 13), 16) << 16; + } + if (!any) return null; + return b.slice(0, (top + 1) & ~1); +} +/** a short name from the file name: upper case, at most 15 letters */ +function abTitle(fname) { + const s = String(fname || '').replace(/\.[^.]*$/, '').replace(/[([].*$/, '').replace(/[^A-Za-z0-9 !'&.-]/g, ' ').replace(/\s+/g, ' ').toUpperCase(); + return s.slice(0, 15).trim() || 'ARDUBOY'; +} +function abCfgWrite(a, c, x, romOff, saveOff, flags) { + w32(a, c + 4, 1); w32(a, c + 8, romOff); w32(a, c + 12, x.rom.length); w32(a, c + 16, saveOff); w32(a, c + 20, (flags & (1 | NOSESS)) | (x.inv ? 2 : 0)); + const nm = x.title || 'ARDUBOY'; a.fill(0, c + 24, c + 40); for (let i = 0; i < nm.length && i < 15; i++) a[c + 24 + i] = nm.charCodeAt(i); + const k = (x.keys && x.keys.length === 9) ? x.keys : AB_KEYS_DEFAULT; a.fill(0, c + 40, c + 52); k.forEach((v, i) => { a[c + 40 + i] = v & 255; }); +} +function cfgName(rom, c) { let s = ''; for (let i = 0; i < 15; i++) { const v = rom[c + 24 + i]; if (!v) break; s += String.fromCharCode(v); } return s; } +/* 1.6.10 test1 Wolfenstein 3D (Wolf4SDL, GPL): the data pack (wolf.js, built in the browser from the user's game + * files) first, then the program (128 KB: the PRAM part and the part it copies to RAM itself), then the save (64 KB: + * 4 KB settings, the saved game). Settings block "PMXW" at 0x140: magic, version, pack, its length, save, flags + * (bit 0 English, bit 1 wheel the other way round), name (16), keys fire, forward, back, use, hold key (masks A 1, + * B 2, C 4, wheel press 8), run with forward twice, degrees per wheel step, 0, then the program's own place. */ +const WOLF_APP_B64 = '__WOLF_APP_B64__'; +function wolfEmbedded() { return WOLF_APP_B64.startsWith('__') ? null : b64(WOLF_APP_B64); } +// 1.6.11 test2: Spear of Destiny, the same program built for SOD (wolf/src, SOD=1); its pack has flags bit 1 +const WOLFSOD_APP_B64 = '__WOLFSOD_APP_B64__'; +function wolfSodEmbedded() { return WOLFSOD_APP_B64.startsWith('__') ? null : b64(WOLFSOD_APP_B64); } +function wolfSod(p) { return !!p && p.length > 64 && !!(u32(p, 8) & 2); } +const WOLF_MAGIC = 0x57584D50; // "PMXW" +const WOLF_KEYS_DEFAULT = { fire: 1, fwd: 2, back: 4, use: 8, mod: 4, run: true, invert: true, turn: 15 }; // 1.6.10 test1: wheel reversed by default +function wolfPackOk(p) { return !!p && p.length > 64 && p[0] === 0x57 && p[1] === 0x33 && p[2] === 0x44 && p[3] === 0x50; } +function wolfInfo(p) { return wolfPackOk(p) ? { shareware: !!(u32(p, 8) & 1), sod: !!(u32(p, 8) & 2), episodes: u32(p, 60), maps: u32(p, 28) } : null; } +function wolfCfgWrite(a, c, x, packOff, saveOff, progOff, flags) { + const k = Object.assign({}, WOLF_KEYS_DEFAULT, x.keys || {}); + w32(a, c + 4, 1); w32(a, c + 8, packOff); w32(a, c + 12, x.pack.length); w32(a, c + 16, saveOff); w32(a, c + 20, (flags & 1) | (k.invert ? 2 : 0)); + const nm = wolfSod(x.pack) ? 'SPEAR OF DESTINY' : 'WOLFENSTEIN 3D'; a.fill(0, c + 24, c + 40); for (let i = 0; i < nm.length; i++) a[c + 24 + i] = nm.charCodeAt(i); + a[c + 40] = k.fire; a[c + 41] = k.fwd; a[c + 42] = k.back; a[c + 43] = k.use; a[c + 44] = k.mod; a[c + 45] = k.run ? 1 : 0; a[c + 46] = k.turn; a[c + 47] = 0; + w32(a, c + 48, progOff); +} +function wolfKeysRead(rom, c) { + return { fire: rom[c + 40], fwd: rom[c + 41], back: rom[c + 42], use: rom[c + 43], mod: rom[c + 44], run: !!rom[c + 45], invert: !!(u32(rom, c + 20) & 2), turn: rom[c + 46] || 15 }; +} +const V3_APP_B64 = '__V3_APP_B64__'; +function v3Embedded() { return V3_APP_B64.startsWith('__') ? null : b64(V3_APP_B64); } +/** ROM of the Connection V3: 512 KB, the 6502 vectors (NMI, reset, IRQ) at 0x7FFA in the top half of the address space */ +function v3Detect(r) { + if (!r || r.length !== 0x80000) return false; + const v = (o) => r[o] | (r[o + 1] << 8); + return v(0x7FFA) >= 0xC000 && v(0x7FFC) >= 0xC000 && v(0x7FFE) >= 0xC000; +} +/** the program for this V1Emu ROM: V3Emu for a V3 ROM */ +function v1App(r, app) { return v3Detect(r) ? (app && app.v3) || v3Embedded() : app; } // tests hang v3.bin on the V1 program as .v3 +/** ROM of an E0C6S4x toy: 12 KB or 16 KB of 12-bit words (two bytes each, high byte first, top nibble 0) */ +function v1Detect(r) { + if (v3Detect(r)) return true; + if (!r || (r.length !== 0x3000 && r.length !== 0x4000)) return false; + for (let i = 0; i < r.length; i += 2) if (r[i] > 0x0F) return false; + return true; +} +const V1_NAMES = { 0x1A03E02A: 'TAMA P1', 0xF0A58E57: 'TAMA P2', 0xD1BF093B: 'ANGEL', 0x02E0C792: 'GENJIN', 0x4E0B9922: 'MORINO', + 0x5E1091E3: 'TAMAOTCH', 0x0809B7FA: 'UMINO', 0xDFEA1952: 'YASASHII', 0x58200E73: 'DIGIMON V1', 0x55DF2A89: 'DIGIMON V2', 0xD32D442C: 'DIGIMON V3', + 0xEF932FA1: 'TAMA P1 EN' }; // test31: the English P1 (tama.bin), same program as the Japanese one apart from its texts // 1.6.9 test24: Digimon V3 +/* V1Emu settings block (at 0x140 of its image): ROM, save (session 4 KB, device settings 4 KB), flags, name, icons */ +/* 1.6.8: toys whose LCD sits the other way round (checked on the host with every known ROM: Digimon V1/V2 and Yasashii) */ +/* 1.7.2 test28: these light each menu icon with one segment (V1Emu flag bit 8, core hw.c thw_iconseg) */ +const V1_ICONSEG = ['UMINO', 'GENJIN', 'TAMAOTCH']; +function v1Turned(rom) { const n = v1Name(rom); return n.startsWith('DIGIMON') || n === 'YASASHII'; } +function v1CfgWrite(a, c, rom, romOff, saveOff, flags) { + w32(a, c + 4, 1); w32(a, c + 8, romOff); w32(a, c + 12, rom.length); w32(a, c + 16, saveOff); + w32(a, c + 20, (flags & (3 | NOSESS)) | (v1Clock(rom) ? 8 : 0) | 16 | (v1Turned(rom) ? 32 : 0) | (v1Name(rom).startsWith('DIGIMON') ? 64 : 0) | (v1Name(rom) === 'YASASHII' ? 128 : 0) | (V1_ICONSEG.includes(v1Name(rom)) ? 256 : 0)); // bit 7 (test31): Yasashii, segment n is column n // bit 6: Digimon (clock at RAM 0x1A, 12 h, set with B and C; own icon segments, keys by interrupt, one-shot beeps) // bit 1 clock, bit 3: V1Emu knows the toy's clock, bit 4: bit 1 is meant, bit 5: LCD turned (Digimon) + const nm = v1Name(rom); a.fill(0, c + 24, c + 40); for (let i = 0; i < nm.length && i < 15; i++) a[c + 24 + i] = nm.charCodeAt(i); + // a turned LCD lights place 7 - i for the toy's icon i: the P set goes in reversed then (Yasashii) + v1IconsWrite(a, c, rom); +} +function v1IconsWrite(a, c, rom) { + const nm = v1Name(rom), set = V1_ICONS[nm] || (nm.startsWith('DIGIMON') ? V1_ICONS.DIGIMON : v1Turned(rom) ? V1_ICONS.P.slice().reverse() : V1_ICONS.P); w32(a, c + 40, 1); + set.forEach((rows, i) => rows.forEach((v, r) => { a[c + 44 + i * 32 + r * 2] = v & 255; a[c + 45 + i * 32 + r * 2] = v >> 8; })); +} +/** 1.6.8: V1Emu as the main program (A and C, start when switched on): image at 0x0A0000, ROM at 0x940000, + * session and settings at 0x0C0000. The session stays when the same ROM was in before. */ +function v1Patch(rom, v1rom, app, stubTpl, opts = {}) { + if (!v1Detect(v1rom)) throw new Error('not a V1 ROM'); + app = v1App(v1rom, app); if (!app) throw new Error('V3Emu missing'); + if (assetEnd(rom) > 0x830000) throw new Error('the character data reaches 0x' + assetEnd(rom).toString(16) + ', the emulator needs 0x830000 onwards'); + const old = v1FromRom(rom), same = !!old && old.length === v1rom.length && old.every((v, i) => v === v1rom[i]); + const oldTama = u32(rom, APP_OFF + 0x140) === PMXC, bigOld = oldTama && u32(rom, APP_OFF + 0x148) === BIG_OFF; + const out = installApp(rom, app, stubTpl); + if (bigOld) out.fill(0xFF, BIG_OFF, BIG_END); + out.fill(0xFF, GUEST_OFF, GUEST_END); out.set(v1rom, GUEST_OFF); + const c = APP_OFF + 0x140; + if (u32(out, c) !== V1_MAGIC) throw new Error('settings block missing in the program'); + v1CfgWrite(out, c, v1rom, GUEST_OFF, SAVE_OFF, ((opts.lang === 'en' || opts.lang === 'ko') ? 1 : 0) | (opts.clock === false ? 0 : 2)); + if (!same) out.fill(0xFF, SAVE_OFF, SAVE_OFF + 0x1000); // the settings of the device (second 4 KB) stay + out.fill(0xFF, SAVE_OFF + 0x2000, SAVE_END); + return out; +} +/** The V1 ROM of V1Emu as the main program, or null. */ +function v1FromRom(rom, base = APP_OFF) { + if (u32(rom, base + 0x140) !== V1_MAGIC) return null; + const o = u32(rom, base + 0x148), n = u32(rom, base + 0x14C); + return o + n <= rom.length && (n === 0x3000 || n === 0x4000 || n === 0x80000) ? rom.slice(o, o + n) : null; +} +/** Newer V1Emu program as the main program: the settings block stays. null if nothing to do. */ +function v1Upgrade(rom, app) { + if (u32(rom, APP_OFF + 0x140) !== V1_MAGIC) return null; + app = v1App(v1FromRom(rom), app); if (!app) return null; + const a = new Uint8Array(app); if (u32(a, 0x140) !== V1_MAGIC) return null; + a.set(rom.subarray(APP_OFF + 0x140, APP_OFF + 0x140 + 300), 0x140); + const f = u32(a, 0x140 + 20); if (!(f & 16)) w32(a, 0x140 + 20, f | 2 | 16); + { const r = v1FromRom(rom); if (r && v1Name(r).startsWith('DIGIMON')) w32(a, 0x140 + 20, u32(a, 0x140 + 20) | 32 | 64 | 8); // LCD turned + else if (r && v1Turned(r)) w32(a, 0x140 + 20, u32(a, 0x140 + 20) | 32); + if (r) v1IconsWrite(a, 0x140, r); + if (r && v1Name(r) === 'YASASHII') w32(a, 0x140 + 20, u32(a, 0x140 + 20) | 128); // test31: segment = column + if (r && V1_ICONSEG.includes(v1Name(r))) w32(a, 0x140 + 20, u32(a, 0x140 + 20) | 256); // 1.7.2 test28: one segment per menu icon + if (r) { const nm = v1Name(r); a.fill(0, 0x140 + 24, 0x140 + 40); for (let i = 0; i < nm.length && i < 15; i++) a[0x140 + 24 + i] = nm.charCodeAt(i); if (v1Clock(r)) w32(a, 0x140 + 20, u32(a, 0x140 + 20) | 8); } } // test31: a newly known ROM (tama.bin) gets its name and clock + let same = true; for (let i = 0; i < APP_MAX && same; i++) if ((i < 0x13C || i > 0x13F) && rom[APP_OFF + i] !== (i < a.length ? a[i] : 0)) same = false; // test24: 0x13C the way back (Studio) + if (same) return null; + const out = new Uint8Array(rom); out.fill(0x00, APP_OFF, APP_OFF + APP_MAX); out.set(a, APP_OFF); + return out; +} +/* 1.6.8: the eight LCD icons (16x16, bit 15 left; 0..3 above, 4..7 below), drawn by mameise. The P1/P2 set + * for all toys without their own set. */ +const V1_ICONS = { ANGEL: [[0x0000,0x0000,0x0000,0x1C38,0x2244,0x4182,0x4422,0x500A,0x4202,0x2204,0x1108,0x0910,0x0420,0x0240,0x0180,0x0000],[0x0000,0x0000,0x0038,0x002C,0x0024,0x003C,0x0040,0x0080,0x0100,0x1A00,0x2400,0x4A00,0x5A00,0x4400,0x3800,0x0000],[0x0000,0x0100,0x0820,0x0000,0x2108,0x0280,0x1C70,0x0820,0x2548,0x06C0,0x0440,0x1010,0x0000,0x0440,0x0000,0x0000],[0x0000,0x0000,0x1FF8,0x2404,0x4202,0x5A03,0x5A03,0x5B57,0x5AAA,0x5A02,0x4202,0x2404,0x1FF8,0x0000,0x0000,0x0000],[0x0000,0x0004,0x000C,0x0008,0x01E0,0x0210,0x0788,0x0848,0x1030,0x2F20,0x30C0,0x2640,0x1080,0x0F00,0x0000,0x0000],[0x0000,0x0000,0x0000,0x1C3C,0x1C44,0x1C84,0x0304,0x0304,0x0484,0x0844,0x1024,0x1014,0x100C,0x1FFC,0x0000,0x0000],[0x0000,0x0000,0x0180,0x0420,0x0000,0x1048,0x00C0,0x01C0,0x1248,0x0240,0x0810,0x03C0,0x03C0,0x0180,0x0180,0x0000],[0x0000,0x0000,0x0700,0x0918,0x112E,0x2226,0x242C,0x3870,0x0088,0x0124,0x0F4C,0x1114,0x1AA8,0x0E70,0x0C00,0x0000]], + DIGIMON: [[0x0000,0x07E0,0x1818,0x2084,0x4892,0x8CB1,0xA425,0xB00D,0x500A,0x4402,0x4202,0x2104,0x2004,0x13C8,0x0C30,0x0000],[0x0000,0x1800,0x29C0,0x4660,0x6430,0x1A50,0x1188,0x1148,0x2A38,0x2628,0x2546,0x18E2,0x0494,0x0318,0x0000,0x0000],[0x0800,0x0800,0x1C00,0x1C08,0x1C1C,0x1C08,0x1C08,0x1CFC,0x1C1C,0x1C1C,0x1C1C,0x1C08,0x1C14,0x0824,0x0022,0x0000],[0x0000,0x0000,0x0408,0x0E1C,0x0408,0x0808,0x1CFC,0x1C1C,0x1F9C,0x1C1C,0x1C1C,0x0808,0x1414,0x1224,0x2222,0x0000],[0x0000,0x0000,0x0000,0x0000,0x0300,0x0380,0x07C0,0x0FE0,0x07C0,0x0000,0x1FF0,0x0FE0,0x0000,0x3FF8,0x1FF0,0x0000],[0x0000,0x0240,0x0810,0x03C0,0x25A4,0x0810,0x1008,0x542A,0x1428,0x1668,0x53CA,0x0990,0x0420,0x23C4,0x07E0,0x0000],[0x0000,0x0420,0x0A50,0x1188,0x2104,0x4202,0x2404,0x1808,0x1018,0x2024,0x4042,0x2084,0x1188,0x0A50,0x0420,0x0000],[0x0000,0x0000,0x0100,0x01F0,0x03F8,0x07DC,0x0FFE,0x0FFE,0x007E,0x70FC,0x01F8,0x0BF0,0x1000,0x2000,0x0000,0x0000]], + P: [[0x0000,0x2A0C,0x2A1C,0x2A3C,0x3E3C,0x1C3C,0x083C,0x1C3C,0x1C3C,0x1C0C,0x1C0C,0x1C0C,0x1C0C,0x1C0C,0x0000,0x0000],[0x0000,0x0000,0x0000,0x0240,0x0000,0x13C8,0x0420,0x2814,0x0A50,0x0A50,0x2994,0x0420,0x13C8,0x0000,0x03C0,0x0000],[0x0000,0x3800,0x4400,0x441C,0x443C,0x387C,0x00F8,0x01F0,0x03E0,0x07C0,0x1F80,0x1F00,0x0E00,0x0600,0x0000,0x0000],[0x0000,0x0020,0x0010,0x0128,0x0094,0x014A,0x0220,0x0410,0x0828,0x1840,0x1C80,0x1F00,0x1E00,0x2000,0x0000,0x0000],[0x0000,0x0000,0x0000,0x1C00,0x2200,0x2200,0x5218,0x2224,0x35E4,0x1224,0x1BE4,0x0808,0x0E38,0x03E0,0x0000,0x0000],[0x0000,0x0000,0x07E0,0x1818,0x2244,0x6816,0x6006,0x2204,0x2304,0x310C,0x1008,0x1008,0x0FF0,0x0000,0x0000,0x0000],[0x0000,0x0000,0x0000,0x0F80,0x1FC0,0x3FC2,0x7F85,0x7F25,0x7E55,0x7F15,0x7F89,0x3FC1,0x1FC0,0x0F80,0x0000,0x0000],[0x0000,0x0E00,0x3180,0x2080,0x4A40,0x4040,0x5170,0x2E0C,0x3004,0x0E82,0x02FA,0x0252,0x0104,0x018C,0x0070,0x0000]] }; +/* 1.7.3 test28: menu icons for Genjintchi, Morino and Umino (16x16, made by mameise after the toys' icons). + * Morino lights its icons like the P1 (its picture i is the icon the P1 table gives); Genjintchi and Umino light one + * segment per icon (V1_ICONSEG), in menu order. Switch: V1_ICONS_MORE. */ +const V1_ICONS_MORE = true; +if (V1_ICONS_MORE) Object.assign(V1_ICONS, { + GENJIN: [[0x0000,0x0000,0x2000,0x7800,0x4F80,0x0CFE,0x1214,0x3210,0x2330,0x3F30,0x3F30,0x0030,0x0078,0x0000,0x0000,0x0000],[0x0000,0x0000,0x0000,0x3000,0x3300,0x77F0,0x07F0,0x0FF0,0x1FC6,0x1FDE,0x01CC,0x0008,0x0000,0x0000,0x0000,0x0000],[0x0000,0x0000,0x0000,0x0220,0x3260,0x3840,0x3808,0x7F00,0x27E4,0x00FE,0x2018,0x041C,0x0080,0x0000,0x0000,0x0000],[0x0000,0x0100,0x0300,0x0700,0x07E0,0x07F0,0x01F0,0x0FF0,0x1FC0,0x1F80,0x0FFC,0x03FE,0x7FFE,0x7FFE,0x183C,0x0000],[0x0000,0x0000,0x0200,0x0218,0x0000,0x73C0,0x0462,0x0526,0x0520,0x2560,0x60C8,0x000C,0x0440,0x0440,0x0000,0x0000],[0x0000,0x0000,0x1930,0x3FFC,0x15A8,0x1C38,0x1C38,0x0000,0x6006,0x07E0,0x4FF6,0x0C30,0x07E0,0x0000,0x0000,0x0000],[0x0000,0x0000,0x0098,0x3FE4,0x2180,0x1C3C,0x1400,0x0000,0x4E76,0x0FF8,0x4E7A,0x0C30,0x07E0,0x0000,0x0000,0x0000],[0x0000,0x0000,0x0038,0x0D70,0x0DE0,0x07C0,0x0388,0x19BE,0x3DBE,0x7CE2,0x0CC2,0x06C0,0x0080,0x0000,0x0000,0x0000]], + MORINO: [[0x0000,0x0000,0x0000,0x07E0,0x1818,0x6184,0x4182,0x4002,0x54A6,0x34B4,0x2004,0x33C8,0x1C38,0x0000,0x0000,0x0000],[0x0000,0x0338,0x0370,0x01F0,0x0100,0x1FFC,0x3FCC,0x7F98,0x7FC8,0x7FC8,0x7F90,0x7F90,0x3FF8,0x1FF8,0x0E70,0x0000],[0x0000,0x0000,0x0000,0x03C0,0x0660,0x0C20,0x0820,0x7870,0x0FFC,0x3FC2,0x600C,0x6078,0x3FC0,0x0000,0x0000,0x0000],[0x0000,0x001C,0x0032,0x0062,0x0042,0x1FC4,0x303C,0x6F98,0x7A30,0x6FA0,0x3060,0x3060,0x6060,0x3FC0,0x0000,0x0000],[0x0000,0x0380,0x1CE0,0x781C,0x7F0E,0x41F6,0x4E64,0x4264,0x6644,0x604C,0x6448,0x70D8,0x3EE0,0x03C0,0x0000,0x0000],[0x0000,0x0000,0x01FC,0x07FE,0x0E7C,0x1E78,0x1818,0x3818,0x3E30,0x3E70,0x3FE0,0x7FC0,0x6600,0x0000,0x0000,0x0000],[0x0000,0x0000,0x0400,0x2E00,0x1300,0x2190,0x60D4,0x2192,0x1312,0x2E12,0x0432,0x00E2,0x008C,0x0078,0x0000,0x0000],[0x0000,0x0000,0x0700,0x7400,0x6F00,0x3F82,0x3FDA,0x7F8E,0x7F7E,0x7F7E,0x3F8A,0x3F82,0x0F00,0x0000,0x0000,0x0000]], + UMINO: [[0x0000,0x07E0,0x0FF0,0x1818,0x324C,0x6016,0x6806,0x6606,0x6206,0x63E6,0x67E6,0x33CC,0x1818,0x0FF0,0x07E0,0x0000],[0x0000,0x0000,0x3C00,0x6E00,0x4700,0x651C,0x39B6,0x0FB6,0x0536,0x0512,0x07BE,0x04CC,0x065C,0x03F0,0x0000,0x0000],[0x0000,0x0000,0x0F00,0x31E0,0x233C,0x6636,0x6E42,0x7ACE,0x6BF2,0x6BC2,0x2ED2,0x24C4,0x1EF8,0x03E0,0x0000,0x0000],[0x0000,0x001C,0x0032,0x0062,0x0042,0x1FC4,0x303C,0x6F98,0x7A30,0x6FB0,0x3060,0x3060,0x6060,0x3FC0,0x0000,0x0000],[0x0000,0x1100,0x3FC0,0x2C64,0x6064,0x4332,0x5DA2,0x29C0,0x20E4,0x6060,0x6020,0x2060,0x3180,0x0F00,0x0000,0x0000],[0x0000,0x07C0,0x0C60,0x0FE0,0x0820,0x0FC0,0x0D60,0x1910,0x1110,0x17D0,0x1390,0x1110,0x1830,0x1FF0,0x07C0,0x0000],[0x0000,0x0000,0x0400,0x2E00,0x1300,0x2190,0x60DC,0x2192,0x1112,0x2E12,0x0432,0x00E2,0x0084,0x0078,0x0000,0x0000],[0x0000,0x0000,0x0018,0x0390,0x07C6,0x0F80,0x0F80,0x7F86,0x7FF0,0x3FF0,0x3FE0,0x3380,0x1000,0x0000,0x0000,0x0000]] }); +/* 1.6.8: toys whose clock V1Emu sets (RAM nibble 0x10, see v1/src/app/main.c) */ +const V1_CLOCK = ['TAMA P1', 'TAMA P1 EN', 'TAMA P2', 'ANGEL', 'MORINO', 'DIGIMON V1', 'DIGIMON V2', 'DIGIMON V3', 'TAMA V3']; // 1.6.9: V3Emu (V3_CLOCK) +function v1Clock(r) { return V1_CLOCK.includes(v1Name(r)); } +function v1Name(r) { if (v3Detect(r)) return 'TAMA V3'; let h = 2166136261; for (const x of r) h = Math.imul(h ^ x, 16777619) >>> 0; return V1_NAMES[h] || (r.length === 0x3000 ? 'TAMA 46' : 'TAMA 48'); } +function t7Embedded() { if (T7_APP_B64.startsWith('__')) return null; const a = b64(T7_APP_B64); if (!T7X_APP_B64.startsWith('__')) a.x = b64(T7X_APP_B64); return a; } +/* 1.6.12 test2: second part of T7Emu (t7x.bin, the translator for the JIT) in the save area at +0x8000; the program runs without it */ +const T7X_APP_B64 = '__T7X_APP_B64__', T7X_OFF = 0x8000, T7X_MAX = 0x8000; +function t7XWrite(out, saveOff, app) { + if (!app || !app.x || app.x.length > T7X_MAX) return; + out.fill(0xFF, saveOff + T7X_OFF, saveOff + T7X_OFF + T7X_MAX); out.set(app.x, saveOff + T7X_OFF); +} +function t7XSame(rom, saveOff, app) { if (!app || !app.x) return true; for (let i = 0; i < app.x.length; i++) if (rom[saveOff + T7X_OFF + i] !== app.x[i]) return false; return true; } +/** V7 ROM: Tama-Go (640 KB, reset vector in the static part at 0x3FFC) or Tamagotchi Friends + * (768 KB, 16 KB more in front: reset vector at 0x7FFC, nothing at 0x3FFC). 'go', 'friends' or null. */ +const T7_FRIENDS_SIZE = 0xC0000; +function t7Kind(b) { + if (!b) return null; + const v = (o) => b[o] | (b[o + 1] << 8); + if (b.length === T7_ROM_SIZE && v(0x3FFC) >= 0xC000) return 'go'; + if (b.length === T7_FRIENDS_SIZE && v(0x3FFC) === 0 && v(0x7FFC) >= 0xC000) return 'friends'; + return null; +} +function t7Detect(b) { return !!t7Kind(b); } +/** Figure: "AA 55" at 1 and at 0x11. */ +function t7FigDetect(b) { return !!b && b.length >= 0x40 && b[1] === 0xAA && b[2] === 0x55 && b[0x11] === 0xAA && b[0x12] === 0x55; } +/* Figure data as stored: dumps of the whole chip (the "full" figures, 4 MB) hold the 1 MB of the figure + * four times (the address wraps) and a few bytes of text from the dump tool behind; one copy is enough. + * Then the zeros at the end are cut. */ +function t7FigData(b) { + let n = b.length, p = 1; while (p * 2 <= n) p *= 2; + if (n - p <= 64 && p >= 0x40000) n = p; // dump tool text behind the chip + const same = (h) => { for (let i = 1; i < h; i++) if (b[i] !== b[h + i]) return false; return true; }; + while (n >= 0x80000 && (n & (n - 1)) === 0 && same(n / 2)) n /= 2; + let e = n; while (e > 0 && b[e - 1] === 0) e--; + return b.slice(0, Math.max(e, 0x40)); +} +function t7Trim(b) { return t7FigData(b); } +/** Name for the menu on the device from the file name: "(03)_Tama-Go_Mametchi.bin" -> "Mametchi". */ +function t7FigName(file) { + let n = String(file || '').split(/[\\/]/).pop().replace(/\.[^.]*$/, ''); + n = n.replace(/^\(\d+\)[_ -]*/, '').replace(/^tama[-_ ]?go[_ -]*/i, '').replace(/[_ -]*figure$/i, ' Full').replace(/_/g, ' '); + n = n.replace(/[^\x20-\x7E]/g, '').trim(); + return (n || 'Figur').slice(0, 15); +} +function t7Cfg(rom, base = APP_OFF) { + if (u32(rom, base + 0x140) !== T7_MAGIC) return null; + const c = base + 0x140, n = Math.min(u32(rom, c + 20), T7_FIG_MAX), figs = []; + for (let i = 0; i < n; i++) { + const f = c + 24 + i * 24; let name = ''; + for (let k = 0; k < 16 && rom[f + 8 + k]; k++) name += String.fromCharCode(rom[f + 8 + k]); + figs.push({ off: u32(rom, f), len: u32(rom, f + 4), name }); + } + return { version: u32(rom, c + 4), romOff: u32(rom, c + 8), romLen: u32(rom, c + 12), saveOff: u32(rom, c + 16), figs, flags: u32(rom, c + 24 + T7_FIG_MAX * 24) }; +} +/* 1.6.11 test2: T7Emu builds up to 1.6.8 (and early 1.6.9 tests) could write the pet's save 2 bytes off; their own + * check then failed and after a battery change the game started anew. Known builds by length and FNV-1a over the + * program from 0x800 (the settings block in front differs per install); also a save slot already written off. */ +const T7_SHIFT_BUILDS = [[45856, 0xdfbdc8e8], [48612, 0xc123d5d6], [48612, 0x7880cbf2], [49792, 0xe8560e2d], [49532, 0x71dd1b4a], [51760, 0x91ab1388], [52976, 0xac37ab35], [53056, 0x74031b17], [54440, 0x16007a7e], [57404, 0xc8392ba4], [57984, 0xc27ec6ad], [58244, 0x6c7b9978], [58300, 0x51abf5c5], [58580, 0x53c0e0bd], [59008, 0xad615a75], [59856, 0xd768658e], [59680, 0xa74ff62c]]; +function fnv1a(b, a, e) { let h = 0x811c9dc5; for (let i = a; i < e; i++) h = Math.imul(h ^ b[i], 0x01000193) >>> 0; return h; } +function t7EeShifted(rom, ee) { + for (const at of [ee, ee + 0x2000]) { + if (at + 0x2000 > rom.length || u32(rom, at) !== 0x45453754) continue; + let s = 0x7E7E; for (let i = 0; i < 4096; i++) s = (Math.imul(s, 31) + rom[at + 0x1000 + i]) >>> 0; + if (s === u32(rom, at + 12)) continue; + let s2 = 0x7E7E; for (let i = 2; i < 4096; i++) s2 = (Math.imul(s2, 31) + rom[at + 0x1000 + i]) >>> 0; + if (Math.imul(Math.imul(s2, 31) >>> 0, 31) >>> 0 === u32(rom, at + 12)) return true; + } + return false; +} +/** Is the T7Emu at base one that can lose the pet's save (old build, or a save already written off)? */ +function t7Outdated(rom, base = APP_OFF) { + const c = t7Cfg(rom, base); if (!c) return false; + for (const [len, h] of T7_SHIFT_BUILDS) if (base + len <= rom.length && fnv1a(rom, base + 0x800, base + len) === h) return true; + // a save written off counts only while the program is not the current one (the current one reads and rewrites it) + const cur = t7Embedded(); if (cur && fnv1a(rom, base + 0x800, base + cur.length) === fnv1a(cur, 0x800, cur.length)) return false; + return t7EeShifted(rom, c.saveOff + 0x1000); +} +/** What is installed, as input for t7Patch again (to add or remove figures). */ +function t7FromRom(rom) { + const c = t7Cfg(rom); if (!c) return null; + return { rom: rom.slice(c.romOff, c.romOff + c.romLen), figs: c.figs.map((f) => ({ name: f.name, data: rom.slice(f.off, f.off + f.len) })) }; +} +/** Room the figures may still use (bytes), for the Studio's display. */ +function t7Room(figs, romLen = T7_ROM_SIZE) { let a = GUEST_OFF + romLen; for (const f of figs) a = (a + f.data.length + 0xFFF) & ~0xFFF; return GUEST_END - a; } +/** + * Install T7Emu. rom: 16 MB Paradise image, t7rom: 640 KB V7 ROM, figs: [{name, data}], + * app: t7.bin, stubTpl: launcher. opts.lang 'en' for English texts on the device. Returns a new image. + */ +function t7Patch(rom, t7rom, figs, app, stubTpl, opts = {}) { + if (!t7Detect(t7rom)) throw new Error('not a V7 ROM (Tama-Go 640 KB or Tamagotchi Friends 768 KB)'); + if (t7Kind(t7rom) === 'friends') figs = []; // Friends has no figure port + if (figs.length > T7_FIG_MAX) throw new Error('at most ' + T7_FIG_MAX + ' figures'); + if (assetEnd(rom) > 0x830000) throw new Error('the character data reaches 0x' + assetEnd(rom).toString(16) + ', the emulator needs 0x830000 onwards'); + const oldT7 = t7Cfg(rom), oldTama = u32(rom, APP_OFF + 0x140) === PMXC; + const sameRom = !!oldT7 && oldT7.romLen === t7rom.length && rom.subarray(oldT7.romOff, oldT7.romOff + oldT7.romLen).every((v, i) => v === t7rom[i]); + const bigOld = oldTama && u32(rom, APP_OFF + 0x148) === BIG_OFF; + const out = installApp(rom, app, stubTpl); + if (!installedOrigs(rom, sceneTable(rom)) && !isFF(rom, GUEST_OFF, GUEST_END - GUEST_OFF)) throw new Error('area 0x940000 is in use'); + if (bigOld) out.fill(0xFF, BIG_OFF, BIG_END); + out.fill(0xFF, GUEST_OFF, GUEST_END); + out.set(t7rom, GUEST_OFF); + let at = GUEST_OFF + t7rom.length; + const list = []; + for (const f of figs) { + const d = t7Trim(f.data); + if (at + d.length > GUEST_END) throw new Error('no room for figure ' + f.name); + out.set(d, at); list.push({ off: at, len: d.length, name: t7FigName(f.name) }); + at = (at + d.length + 0xFFF) & ~0xFFF; + } + const c = APP_OFF + 0x140; + if (u32(out, c) !== T7_MAGIC) throw new Error('settings block missing in the program'); + w32(out, c + 4, 1); w32(out, c + 8, GUEST_OFF); w32(out, c + 12, t7rom.length); w32(out, c + 16, SAVE_OFF); w32(out, c + 20, list.length); + out.fill(0, c + 24, c + 24 + T7_FIG_MAX * 24); + list.forEach((f, i) => { const o = c + 24 + i * 24; w32(out, o, f.off); w32(out, o + 4, f.len); for (let k = 0; k < f.name.length; k++) out[o + 8 + k] = f.name.charCodeAt(k); }); + w32(out, c + 24 + T7_FIG_MAX * 24, ((opts.lang === 'en' || opts.lang === 'ko') ? 1 : 0) | (opts.clock === false ? 0 : 2)); + // save area: the pet's EEPROM stays when the same ROM was in before, the session only with the same figures + const sameFigs = sameRom && oldT7.figs.length === list.length && oldT7.figs.every((f, i) => f.len === list[i].len && f.off === list[i].off); + if (!sameRom) out.fill(0xFF, SAVE_OFF, SAVE_END); + else { out.fill(0xFF, T7_EE_END, SAVE_END); if (!sameFigs) out.fill(0xFF, SAVE_OFF, T7_EE); } + t7XWrite(out, SAVE_OFF, app); + return out; +} +/** + * Local time when writing to the device, for the first time setting in the game (T7Emu fills + * it in). counter: the device's seconds counter, date: now. Returns a new image. + */ +function t7Wall(rom, counter, date) { + if (u32(rom, APP_OFF + 0x140) !== T7_MAGIC) return rom; + const out = new Uint8Array(rom), c = APP_OFF + 0x140 + 24 + T7_FIG_MAX * 24 + 4; + w32(out, c, counter >>> 0); + w32(out, c + 4, date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()); + w32(out, c + 8, (date.getFullYear() << 16) | ((date.getMonth() + 1) << 8) | date.getDate()); + return out; +} +/** Newer T7 program into a ROM that already has T7Emu: settings stay. null if nothing to do. */ +function t7Upgrade(rom, app) { + if (u32(rom, APP_OFF + 0x140) !== T7_MAGIC) return null; + const a = new Uint8Array(app); + if (u32(a, 0x140) !== T7_MAGIC) return null; + const n = 24 + T7_FIG_MAX * 24 + 4; + a.set(rom.subarray(APP_OFF + 0x140, APP_OFF + 0x140 + n), 0x140); + let same = true; + for (let i = 0; i < APP_MAX && same; i++) if ((i < 0x13C || i > 0x13F) && rom[APP_OFF + i] !== (i < a.length ? a[i] : 0)) same = false; // test24: 0x13C the way back (Studio) + const so = u32(rom, APP_OFF + 0x150); + if (same && t7XSame(rom, so, app)) return null; + const out = new Uint8Array(rom); + out.fill(0x00, APP_OFF, APP_OFF + APP_MAX); + out.set(a, APP_OFF); + t7XWrite(out, so, app); + return out; +} + +// ------------------------------------------------------------ T18Emu (Meets/On, TG18, ARM7) +/* + * T18Emu (1.5.0): the TG18 core (from T18Emu) with a translator from ARM/Thumb to Cortex-M3 code. + * Same launcher and program place as TamaEmu and T7Emu (only one of them). Settings block "PMX8" + * at 0x140 of the program. Since 1.5.1 the program has two parts: t18.bin (PRAM, copied by the + * launcher from 0x0A0000) and t18x.bin (code run from the flash window, at T18_XIP_OFF). + * The 8 MB firmware is stored in 64 KB blocks in free blocks of the Paradise flash, from the top + * down (from 0xF00000, then from 0xD40000 downwards), so the bottom (from 0x830000) stays free for + * the field saves of the menu. Empty blocks are left out. Behind them up to T18_SPARE_WANT spares + * for the blocks the firmware writes (its save data: 6 blocks after the first start). + * Save area at 0x0C0000: block map, clock note, session (see t18/src/app/t18app.h). + */ +const T18_MAGIC = 0x38584D50, T18_SPARE_MAX = 64, T18_SPARE_MIN = 6, T18_SPARE_WANT = 10, T18_SPARE_GROW = 15, T18_SAVE_LEN = 0x24000; // GROW (test29): spares added in a start device, at most 15 (the sector pool counts to 254) +/* 1.7.2 SPARE_NO_RESCUE: more spares for T18Emu never take the rescue start's block (0xFF0000), also when it is still empty */ +const SPARE_NO_RESCUE = true; +const T18_XIP_OFF = 0xF0000, T18_XIP_MAX = 0x10000, T18_XIP_MAGIC = 0x58383154; +/* Hot window (1.6.6): the device's cached flash window shows 1 MB. With 0xF00000..0xFFFFFF free the + * program moves it there (flag 4) and needs its flash part a second time at T18_XIP_HOT; the blocks + * with the firmware's code (the same in all known TG18 firmwares) and two busy picture blocks go into + * the rest of that MB. */ +const T18_HOT_BASE = 0xF00000, T18_XIP_HOT = 0xFDF000, T18F_HOTWIN = 4; +// 1.6.6 test11 (T18_HOT_V2): the blocks the TG18 firmware reads most (measured over please wait, egg and pet with +// its calls): code 0x12..0x16, 0x1A, 0x00 and the picture data 0x3F, 0x4A, 0x32, 0x40 (pet), 0x18, 0x19, 0x3B (egg). +// The first list had 0x01, 0x1B, 0x17 (hardly read) and 0x5E, 0x63 (empty in the firmware: never placed) instead. +const T18_HOT_V2 = true, T18F_HOT2 = 16; // 8 was the list of test10 +const T18_HOT_GUEST = T18_HOT_V2 ? [0x12, 0x14, 0x15, 0x13, 0x1A, 0x00, 0x16, 0x3F, 0x4A, 0x32, 0x18, 0x19, 0x3B, 0x40] + : [0x12, 0x14, 0x15, 0x13, 0x1A, 0x00, 0x16, 0x18, 0x19, 0x01, 0x1B, 0x17, 0x5E, 0x63]; +const T18_HOT_SLOTS = [0xFF, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0]; +const T18_AREAS = [[0x830000, 0xD40000], [0xF00000, 0x1000000]]; +/* 1.6.13 test13 (RESCUE_RES): the top 64 KB (0xFF0000) stay free for the rescue start (flash.js); an installation that + * already has a block there keeps it (its save belongs to that layout) */ +const RESCUE_RES = true, RESCUE_BLK = 0xFF; +const T18_APP_B64 = '__T18_APP_B64__', T18_XIP_B64 = '__T18_XIP_B64__'; +/** The program: PRAM part, with the flash part as .xip */ +function t18Embedded() { + if (T18_APP_B64.startsWith('__') || T18_XIP_B64.startsWith('__')) return null; + const a = b64(T18_APP_B64); a.xip = b64(T18_XIP_B64); return a; +} +function t18XipOk(app) { return !!app && !!app.xip && app.xip.length >= 8 && app.xip.length <= T18_XIP_MAX && u32(app.xip, 0) === T18_XIP_MAGIC; } +/** TG18 firmware: 8 MB, "SPII" header, entry 0x2000000C. */ +function t18Detect(b) { + return !!b && b.length === 0x800000 && b[0] === 0x53 && b[1] === 0x50 && b[2] === 0x49 && b[3] === 0x49 && u32(b, 4) === 0x2000000C; +} +/** Addresses the core needs (same searches as tg18_init in t18soc.c): idle counter, soft RTC, DMA table. */ +function t18Addrs(fw) { + const n = fw.length >>> 2, w = (i) => u32(fw, i * 4); + const cnt = new Map(); let best = 0, bestc = 0; + for (let i = 0; i + 8 < n; i++) { + const v = w(i); + if (v < 0xF8000000 || v >= 0xF8020000) continue; + let h1 = false, h2 = false; + for (let k = 1; k < 8; k++) { const x = w(i + k); if (x === v + 1) h1 = true; if (x === v + 2) h2 = true; } + if (!h1 || !h2) continue; + if (!cnt.has(v)) { if (cnt.size === 64) continue; cnt.set(v, 0); } + const c = cnt.get(v) + 1; cnt.set(v, c); + if (c > bestc) { bestc = c; best = v; } + } + const idle = bestc >= 40 ? (best - 0x0F) >>> 0 : 0; + let soft = 0; + for (let i = 0; i + 8 <= fw.length && i < 0x20000; i += 4) { + const a1 = u32(fw, i + 4); + if (u32(fw, i) === 0xC0040000 && a1 >= 0xF8008000 && a1 < 0xF8010000 && a1 !== 0xF800128C && (a1 & 3) === 0) { soft = a1; break; } + } + let dma = 0; + for (let i = 0; i + 12 <= fw.length && i < 0x400000; i += 4) { + const a2 = u32(fw, i + 8); + if (u32(fw, i) === 0xD0300000 && u32(fw, i + 4) === 0x3210 && a2 >= 0xF8000000 && a2 < 0xF8020000) { dma = a2; break; } + } + return { idle, soft, dma, param: t18Param(fw) }; +} +/** 1.6.8 (test47): the game's Param block in the SRAM (grow up). The literal pool of DispYobidashiIconInit holds it right + * before the address of its debug text (as the Android T18Emu finds it); checked against its table for all 9 firmwares. */ +function t18Param(fw) { + const pat = [...'DispYobidashiIconInit() pYobi'].map((c) => c.charCodeAt(0)); + let s = -1; + outer: for (let i = 0; i + pat.length <= fw.length; i++) { for (let k = 0; k < pat.length; k++) if (fw[i + k] !== pat[k]) continue outer; s = i; break; } + if (s < 0) return 0; + while (s > 0 && fw[s - 1] !== 0) s--; + const addr = (0x20000000 + s) >>> 0; + for (let p = 4; p + 4 <= fw.length; p += 1) if (u32(fw, p) === addr) { const v = u32(fw, p - 4); return v >= 0xF800C000 && v <= 0xF800F000 ? v : 0; } + return 0; +} +function t18ParamSet(out, c, fw) { const pa = t18Param(fw); w32(out, c + 428, pa); w32(out, c + 432, pa === 0xF800D8B4 ? 1 : 0); } // Sanrio: Flowertchi +function t18Cfg(rom, base = APP_OFF) { + const c = base + 0x140; + if (u32(rom, c) !== T18_MAGIC) return null; + const map = [], spare = [], nspare = Math.min(u32(rom, c + 12), T18_SPARE_MAX); + for (let i = 0; i < 128; i++) map.push(rom[c + 16 + 2 * i] | (rom[c + 17 + 2 * i] << 8)); + for (let i = 0; i < nspare; i++) spare.push(rom[c + 272 + 2 * i] | (rom[c + 273 + 2 * i] << 8)); + return { version: u32(rom, c + 4), saveOff: u32(rom, c + 8), map, spare, flags: u32(rom, c + 400) }; +} +/** An installed T18Emu gives its blocks back (before another emulator or DOOM goes in). */ +function freeT18(out) { + const c = t18Cfg(out); if (!c) return; + for (const b of c.map.concat(c.spare)) if (b !== 0xFFFF) out.fill(0xFF, b << 16, (b + 1) << 16); + if (c.flags & T18F_HOTWIN) out.fill(0xFF, 0xFD0000, 0xFF0000); + out.fill(0xFF, SAVE_OFF, SAVE_END); +} +/** ID page of the edition (0xD49000, Tropical/Glacier 0xD29000): the Paradise's save follows it */ +function idPageOf(rom) { if (CLEAN) return 0xFF0000; const k = u32(rom, 0xD29000), v = u32(rom, 0xD49000); return (k === 5 || k === 6) ? 0xD29000 : v >= 1 && v <= 6 ? 0xD49000 : 0xD29000; } // 1.7.3 test11: Tropical/Glacier first +/** Free 64 KB blocks for the firmware: empty, behind the character data. */ +function t18Free(rom, launch) { + const from = CLEAN ? 0x10000 : Math.max(launch ? 0x200000 : 0x830000, (assetEnd(rom) + 0xFFFF) & ~0xFFFF), list = []; // launcher ROM (1.6.8): all room behind the setup pictures + const areas = CLEAN ? [[from, 0xFF0000]] : launch ? [[from, Math.min(0xD40000, idPageOf(rom))], T18_AREAS[1]] : T18_AREAS; + for (const [a, e] of areas) for (let o = Math.max(a, a < 0xF00000 ? from : a); o < e; o += 0x10000) if (isFF(rom, o, 0x10000)) list.push(o >>> 16); + return list.sort((x, y) => y - x); // from the top down: the bottom stays free for the field saves +} +/** Lowest flash offset T18Emu uses below 0xF00000 (the field saves of the menu end there); 0 = none */ +function t18Low(rom) { + const c = t18Cfg(rom); if (!c) return 0; + const b = c.map.concat(c.spare).filter((x) => x !== 0xFFFF && x < 0xF0); + return b.length ? Math.min(...b) << 16 : 0xD40000; +} +/** + * Install T18Emu. rom: 16 MB Paradise image, fw: 8 MB TG18 firmware, app: t18.bin, stubTpl: launcher. + * opts.lang 'en'. Returns { rom, blocks, spares }. + */ +function t18Patch(rom, fw, app, stubTpl, opts = {}) { + if (!t18Detect(fw)) throw new Error('not a TG18 firmware (8 MB)'); + if (rom.length !== 0x1000000) throw new Error('the Paradise image must be 16 MB'); + // opts.extra (1.6.8): placed as an extra program (appsPlace); the program at 0x0A0000 is someone else's + const old = opts.extra ? null : t18Cfg(rom), oldTama = !opts.extra && u32(rom, APP_OFF + 0x140) === PMXC, oldT7 = !opts.extra && u32(rom, APP_OFF + 0x140) === T7_MAGIC; + const work = new Uint8Array(rom); + // what an earlier emulator used becomes free again + if (old) { for (const b of old.map) if (b !== 0xFFFF) work.fill(0xFF, b << 16, (b + 1) << 16); for (const b of old.spare) work.fill(0xFF, b << 16, (b + 1) << 16); if (old.flags & T18F_HOTWIN) work.fill(0xFF, 0xFD0000, 0xFF0000); } + if (oldTama || oldT7) { work.fill(0xFF, GUEST_OFF, GUEST_END); if (oldTama && u32(rom, APP_OFF + 0x148) === BIG_OFF) work.fill(0xFF, BIG_OFF, BIG_END); } + let used = []; for (let i = 0; i < 128; i++) if (!isFF(fw, i << 16, 0x10000)) used.push(i); + let free = t18Free(work, !!opts.launch); + const resv = RESCUE_RES && !opts.noResv && !(old && old.map.concat(old.spare).includes(RESCUE_BLK)); + if (resv) free = free.filter((b) => b !== RESCUE_BLK); + if (free.length < used.length + T18_SPARE_MIN) throw new Error('not enough room: the firmware needs ' + (used.length + T18_SPARE_MIN) + ' blocks of 64 KB, ' + free.length + ' are free'); + // hot window: the whole MB at 0xF00000 free and still room enough without 0xFD/0xFE + const hot = opts.hotWindow !== false && [...Array(resv ? 15 : 16).keys()].every((i) => free.includes(0xF0 + i)) && free.length - 2 >= used.length + T18_SPARE_MIN; + if (hot) { + const rest = free.filter((b) => b < 0xF0); + free = (resv ? T18_HOT_SLOTS.filter((b) => b !== RESCUE_BLK) : T18_HOT_SLOTS).concat(rest); + used = T18_HOT_GUEST.filter((g) => used.includes(g)).concat(used.filter((g) => !T18_HOT_GUEST.includes(g))); + } + if (opts.holes) { + // test25: the smallest gaps first; the largest free run stays for a TamaEmu in the menu (it needs one piece) + const nh = hot ? (resv ? T18_HOT_SLOTS.filter((b) => b !== RESCUE_BLK) : T18_HOT_SLOTS).length : 0, rest = free.slice(nh), set = new Set(rest); + const run = (b) => { let lo = b, hi = b; while (set.has(lo - 1)) lo--; while (set.has(hi + 1)) hi++; return hi - lo + 1; }; + free = free.slice(0, nh).concat(rest.map((b) => [run(b), b]).sort((x, y) => x[0] - y[0] || y[1] - x[1]).map((x) => x[1])); + } + const out = opts.extra ? new Uint8Array(work) : installApp(work, app, stubTpl); + if (opts.extra) { out.fill(0x00, APP_OFF, APP_OFF + APP_MAX); out.set(app, APP_OFF); } + const map = new Array(128).fill(0xFFFF); + used.forEach((g, k) => { const b = free[k]; map[g] = b; out.set(fw.subarray(g << 16, (g + 1) << 16), b << 16); }); + // spares: up to T18_SPARE_WANT, but 4 blocks (256 KB) stay free for the menu's field saves if possible + const nsp = Math.max(T18_SPARE_MIN, Math.min(opts.spares || T18_SPARE_WANT, free.length - used.length - 4)); // test25: opts.spares (fewer when the rest does not fit) + const spare = free.slice(used.length, used.length + nsp); + const c = APP_OFF + 0x140; + if (u32(out, c) !== T18_MAGIC) throw new Error('settings block missing in the program'); + const ad = t18Addrs(fw); + w32(out, c + 4, 1); w32(out, c + 8, SAVE_OFF); w32(out, c + 12, spare.length); + map.forEach((b, i) => { out[c + 16 + 2 * i] = b & 255; out[c + 17 + 2 * i] = b >> 8; }); + out.fill(0xFF, c + 272, c + 272 + 2 * T18_SPARE_MAX); + spare.forEach((b, i) => { out[c + 272 + 2 * i] = b & 255; out[c + 273 + 2 * i] = b >> 8; }); + w32(out, c + 404, ad.idle); w32(out, c + 408, ad.soft); w32(out, c + 412, ad.dma); w32(out, c + 428, ad.param); w32(out, c + 432, ad.param === 0xF800D8B4 ? 1 : 0); + w32(out, c + 416, 0); w32(out, c + 420, 0); w32(out, c + 424, 0); + // save area: block map, clock note and session belong to this firmware + // (the stored map sector points at the blocks: same places needed, not only the same firmware) + const same = !!old && old.map.every((b, i) => b === map[i]) && old.spare.length === spare.length && old.spare.every((b, i) => b === spare[i]) && used.every((g) => rom.subarray(old.map[g] << 16, (old.map[g] + 1) << 16).every((v, k) => v === fw[(g << 16) + k])); + if (!same) out.fill(0xFF, SAVE_OFF, SAVE_END); + else out.set(rom.subarray(SAVE_OFF, SAVE_OFF + T18_SAVE_LEN), SAVE_OFF); // (installApp cleared it) + w32(out, c + 400, optBits(opts.opt) | ((opts.lang === 'en' || opts.lang === 'ko') ? 1 : 0) | (opts.clock === false ? 0 : 2) | (opts.nosess ? NOSESS : 0) | (hot ? T18F_HOTWIN | (T18_HOT_V2 ? T18F_HOT2 : 0) : 0)); + t18PutXip(out, app); + return { rom: out, blocks: used.length, spares: spare.length, hot }; +} + +/* + * T18Emu items (1.6.8, test47): MyMeets records ("TAMAGO" files, e.g. tg18_as15003_1.txt) into the TG18 save, as the + * Android T18Emu does it (Inhalte.kt, TamaSatz.kt; every number there was measured on the device). The save partition + * starts at guest flash 0x5E0000 (0x220000 bytes). Areas with fixed slot size; a slot shows on the device only with + * its record AND its counter (92 counters of 2 bits from 0x21E053: at most 3 pieces). The active room: record at + * 0x0F0000 and the choice byte 0x21E070 = 0 (8 = built-in room). Tamapoints u16 at 0x21E020. + */ +const T18I_PART = 0x5E0000, T18I_CNT = 0x21E053, T18I_PTS = 0x21E020, T18I_WP = 0x0F0000, T18I_WPLEN = 0x4000, T18I_WPSEL = 0x21E070; +const T18I_AREAS = [ + { key: 'food', base: 0x050000, step: 0x800, n: 22, idx0: 0, arts: ['meal', 'snack'], basic: [0, 1] }, + { key: 'item', base: 0x0A0000, step: 0x2000, n: 24, idx0: 53, arts: ['item'], basic: [0] }, + { key: 'acc', base: 0x060000, step: 0x2000, n: 16, idx0: 37, arts: ['acc'], basic: [] }, +]; +function be16(b, o) { return (b[o] << 8) | b[o + 1]; } +function t18iArt(z) { + switch (z >>> 0) { + case 0x81010101: return 'meal'; case 0x81010102: return 'snack'; + case 0x81042A01: case 0x81042A03: return 'item'; + case 0x81023400: case 0x81023500: return 'acc'; + case 0x81071F00: return 'room'; + } + if ((z >>> 16) === 0x8101) return (z & 0xFF) === 1 ? 'meal' : 'snack'; // derived, not measured (Android T18Emu) + return ''; +} +function t18iPics(b, at) { + if (b.length < at + 2) return null; + const cnt = be16(b, at); if (cnt < 1 || cnt > 32) return null; + const p = at + 2; if (p + 8 > b.length) return null; + const ln = be16(b, p), w = b[p + 2], h = b[p + 3], nf = b[p + 4]; + if (!w || !h || !nf || p + 2 + ln > b.length) return null; + const np = (w * h) >> 1, pd = p + 2 + ln - np, te = p + 8 + 2 * nf; + if (pd < te || pd - te > 4) return null; + const rgba = new Uint8ClampedArray(w * h * 4); + for (let i = 0; i < w * h; i++) { + const by = b[pd + (i >> 1)], n = i & 1 ? by >> 4 : by & 15; + if (n >= nf) continue; + const v = be16(b, p + 8 + 2 * n), bl = (v >> 11) & 31, gr = (v >> 5) & 63, rt = v & 31; // BGR565 + if (n === 0 && bl === 0 && rt === 0 && gr === 63) continue; // pure green: see-through + rgba[i * 4] = rt * 255 / 31; rgba[i * 4 + 1] = gr * 255 / 63; rgba[i * 4 + 2] = bl * 255 / 31; rgba[i * 4 + 3] = 255; + } + return { w, h, rgba }; +} +/** A TAMAGO record: name, kind, catalogue number, price, first picture. null if it is none. */ +function t18iRecord(b) { + if (!b || b.length < 0x100 || String.fromCharCode(...b.subarray(0, 6)) !== 'TAMAGO') return null; + let file = ''; for (let i = 0; i < 20; i++) { const c = b[52 + i]; if (!c) break; if (c >= 32 && c < 127) file += String.fromCharCode(c); } + let name = '', unk = 0; + for (let i = 0; i < 12; i++) { const v = be16(b, 94 + 2 * i); if (!v) break; const n = v & 0xFF; + name += n >= 0xE0 && n <= 0xF9 ? String.fromCharCode(65 + n - 0xE0) : n >= 0xC6 && n <= 0xCF ? String.fromCharCode(48 + n - 0xC6) : n === 0x6C ? ' ' : (unk++, '?'); } + name = name.trim(); + const readable = name.length > 0 && unk * 2 <= name.length; + const z = ((be16(b, 78) << 16) | be16(b, 80)) >>> 0; + let pic = t18iPics(b, 0x200); + if (!pic && b.length > 0x202) pic = t18iPics(b, 0x202 + be16(b, 0x200)); // accessories: a block of its own first + return { bytes: b, file, name: readable ? name : file, readable, art: t18iArt(z), target: z, cat: be16(b, 90), price: be16(b, 118), pic, model: file.split('_')[0].toLowerCase() }; +} +/** All TAMAGO records in a file (several can be in one). */ +function t18iScan(b) { + const out = []; + for (let a = 0; a + 0x60 <= b.length; a++) { + if (b[a] !== 0x54 || b[a + 1] !== 0x41 || b[a + 2] !== 0x4D || b[a + 3] !== 0x41 || b[a + 4] !== 0x47 || b[a + 5] !== 0x4F || b[a + 6] !== 0) continue; + if (b[a + 0x4E] !== 0x81) continue; + const len = (b[a + 0x48] << 24 | b[a + 0x49] << 16 | b[a + 0x4A] << 8 | b[a + 0x4B]) >>> 0; + if (len < 0x60 || len > 0x1F000 || a + len > b.length) continue; + let sum = 0; for (let i = a; i < a + len - 2; i++) sum = (sum + b[i]) & 0xFFFF; + if (sum !== be16(b, a + len - 2)) continue; + const r = t18iRecord(b.slice(a, a + len)); if (r) { out.push(r); a += len - 1; } + } + return out; +} +function t18iCount(fw, idx) { const v = fw[T18I_PART + T18I_CNT + (idx >> 2)]; return (v >> ((idx & 3) * 2)) & 3; } +function t18iSetCount(fw, idx, c) { const o = T18I_PART + T18I_CNT + (idx >> 2), s = (idx & 3) * 2; fw[o] = (fw[o] & ~(3 << s)) | ((Math.max(0, Math.min(3, c)) & 3) << s); } +/** The save exists (the game has run once): the Param block at 0x21E000 is filled */ +function t18iHasSave(fw) { const o = T18I_PART + 0x21E000; for (let i = 0; i < 0x60; i++) if (fw[o + i] !== 0xFF && fw[o + i] !== 0) return true; return false; } +/** Every area with its slots (a slot counts only with record and counter); the room and the Tamapoints. */ +function t18Items(fw) { + const areas = T18I_AREAS.map((A) => { + const slots = []; + for (let n = 0; n < A.n; n++) { + const o = T18I_PART + A.base + n * A.step, cnt = t18iCount(fw, A.idx0 + n); + const rec = fw[o] === 0x54 ? t18iRecord(fw.slice(o, o + A.step)) : null; + const basic = A.basic.includes(n) && rec && rec.cat >= 10000 && rec.cat <= 14999; // the start items: always there + slots.push({ n, rec: rec && cnt > 0 && !basic ? rec : null, count: cnt, basic }); + } + return { key: A.key, slots, free: slots.filter((x) => !x.rec && !x.basic).length }; + }); + const wo = T18I_PART + T18I_WP; + const room = fw[wo] === 0x54 && fw[T18I_PART + T18I_WPSEL] === 0 ? t18iRecord(fw.slice(wo, wo + T18I_WPLEN)) : null; + return { areas, room, points: fw[T18I_PART + T18I_PTS] | (fw[T18I_PART + T18I_PTS + 1] << 8), save: t18iHasSave(fw) }; +} +/** Put a record in: the first free slot of its area (count 1..3), a room becomes the active room. Returns { area, slot } or throws. */ +function t18ItemAdd(fw, rec, count = 1) { + if (!t18iHasSave(fw)) throw new Error('no save yet'); + if (rec.art === 'room') { + if (rec.bytes.length > T18I_WPLEN) throw new Error('record too large'); + const o = T18I_PART + T18I_WP; fw.fill(0xFF, o, o + T18I_WPLEN); fw.set(rec.bytes, o); fw[T18I_PART + T18I_WPSEL] = 0; + return { area: 'room', slot: 0 }; + } + const A = T18I_AREAS.find((x) => x.arts.includes(rec.art)); if (!A) throw new Error('unknown kind'); + if (rec.bytes.length > A.step) throw new Error('record too large'); + const it = t18Items(fw).areas.find((x) => x.key === A.key); + const s = it.slots.find((x) => !x.rec && !x.basic); if (!s) throw new Error('full'); + const o = T18I_PART + A.base + s.n * A.step; fw.fill(0xFF, o, o + A.step); fw.set(rec.bytes, o); t18iSetCount(fw, A.idx0 + s.n, count || 1); + return { area: A.key, slot: s.n }; +} +function t18ItemDel(fw, key, n) { const A = T18I_AREAS.find((x) => x.key === key); const o = T18I_PART + A.base + n * A.step; fw.fill(0xFF, o, o + A.step); t18iSetCount(fw, A.idx0 + n, 0); } +function t18ItemCount(fw, key, n, c) { const A = T18I_AREAS.find((x) => x.key === key); if (fw[T18I_PART + A.base + n * A.step] === 0x54) t18iSetCount(fw, A.idx0 + n, c); } +function t18RoomReset(fw) { const o = T18I_PART + T18I_WP; fw.fill(0xFF, o, o + T18I_WPLEN); fw[T18I_PART + T18I_WPSEL] = 8; } +function t18Points(fw, v) { v = Math.max(0, Math.min(65535, v | 0)); fw[T18I_PART + T18I_PTS] = v & 0xFF; fw[T18I_PART + T18I_PTS + 1] = v >> 8; } + +/** + * 1.6.8 (test47): changed sectors of the guest flash (items) into an installed T18Emu, the way the device keeps them: + * a mapped block (save map "T8MP" or the settings) gets them in place; a sector of an empty block goes to its entry + * of the sector table ("T8SS", T18_SEC_SPARE) or a new pool sector (spare block k >> 4, sector k & 15; spare blocks + * used whole are skipped). The layout stays, only the running state (session) is dropped: the game starts from its + * own save. Throws when there is no room. + */ +function t18RomWriteGuest(rom, fw, base = APP_OFF) { + const c = t18Cfg(rom, base); if (!c) throw new Error('T18Emu not installed'); + const out = new Uint8Array(rom), so = c.saveOff, SROWS = 19, SOFF = so + 4 + 256 + T18_SPARE_MAX; + const old = t18FromRom(rom, base); if (!old) throw new Error('T18Emu not complete'); + let map = c.map, used = new Array(T18_SPARE_MAX).fill(0); + const hasMap = u32(out, so) === 0x504D3854; + if (hasMap) { map = []; for (let i = 0; i < 128; i++) map.push(out[so + 4 + 2 * i] | (out[so + 5 + 2 * i] << 8)); for (let i = 0; i < T18_SPARE_MAX; i++) used[i] = out[so + 4 + 256 + i]; } + const idx = new Uint8Array(128), rows = []; for (let r = 0; r < SROWS; r++) rows.push(new Uint8Array(16)); + if (hasMap && u32(out, SOFF) === 0x53533854) { for (let i = 0; i < 128; i++) idx[i] = out[SOFF + 4 + i] <= SROWS ? out[SOFF + 4 + i] : 0; for (let r = 0; r < SROWS; r++) rows[r].set(out.subarray(SOFF + 132 + 16 * r, SOFF + 148 + 16 * r)); } + const inUse = new Set(); for (let r = 0; r < SROWS; r++) if (idx.includes(r + 1)) for (const k of rows[r]) if (k) inUse.add(k - 1); + let tables = false; + for (let sec = 0; sec < 0x800000; sec += 0x1000) { + let same = true; for (let i = 0; i < 0x1000 && same; i++) if (fw[sec + i] !== old[sec + i]) same = false; + if (same) continue; + const b = sec >> 16, s = (sec >> 12) & 15, data = fw.subarray(sec, sec + 0x1000); + if (map[b] !== 0xFFFF) { out.set(data, (map[b] << 16) | (s << 12)); continue; } + let i = idx[b]; + if (!i) { let r = 0; while (r < SROWS && idx.includes(r + 1)) r++; if (r >= SROWS) throw new Error('no room for more save data'); idx[b] = i = r + 1; rows[r].fill(0); tables = true; } + let k = rows[i - 1][s]; + if (!k) { + let p = -1; for (let q = 0; q < Math.min(c.spare.length * 16, 254); q++) if (!used[q >> 4] && !inUse.has(q)) { p = q; break; } + if (p < 0) throw new Error('no room for more save data'); + inUse.add(p); rows[i - 1][s] = k = p + 1; tables = true; + } + k--; out.set(data, (c.spare[k >> 4] << 16) | ((k & 15) << 12)); + } + if (tables) { + if (!hasMap) { out.fill(0xFF, so, so + 0x1000); w32(out, so, 0x504D3854); map.forEach((v, j) => { out[so + 4 + 2 * j] = v & 255; out[so + 5 + 2 * j] = v >> 8; }); for (let j = 0; j < T18_SPARE_MAX; j++) out[so + 4 + 256 + j] = used[j]; } + w32(out, SOFF, 0x53533854); out.set(idx, SOFF + 4); for (let r = 0; r < SROWS; r++) out.set(rows[r], SOFF + 132 + 16 * r); + } + out.fill(0xFF, so + 0x2000, so + 0x3000); // session header: the game starts from its own save + return out; +} + +/* + * 1.6.8 (test47): pictures for "grow up" on the device, from the user's own files (the Studio has none). One per adult, + * 64x64 with up to 256 colours, at 0x0E4000 behind the T18 save area ("T8PI": magic, count, then per picture: id, + * 3 bytes 0, 256 colours RGB565, 4096 indices). The settings get its place at +436. + */ +const T18_PIC_OFF = 0xE4000, T18_PIC_END = 0xF0000, T18_PIC_SZ = 4 + 512 + 4096; +const T18_ADULTS = [[16, 'Mametchi'], [17, 'Kuchipatchi'], [20, 'Kikitchi'], [25, 'Kuromametchi'], [24, 'Gozarutchi'], [19, 'Lovelitchi'], + [23, 'Nijifuwatchi'], [35, 'Pompomtchi'], [18, 'Memetchi'], [22, 'Watawatatchi'], [21, 'Flowertchi']]; +function t18AdultFind(name) { + const n = name.toLowerCase().replace(/\.[a-z]+$/, '').replace(/[^a-z0-9]/g, ''); + if (/^\d+$/.test(n)) { const id = +n; return T18_ADULTS.some((a) => a[0] === id) ? id : -1; } + for (const [id, nm] of T18_ADULTS) if (n.includes(nm.toLowerCase())) return id; + return -1; +} +/** an image { w, h, rgba } (any size) to 64x64, palette of up to 256 RGB565 colours */ +function t18PicMake(img) { + const px = new Uint16Array(64 * 64); + for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) { + const x0 = Math.floor(x * img.w / 64), x1 = Math.max(x0 + 1, Math.floor((x + 1) * img.w / 64)), y0 = Math.floor(y * img.h / 64), y1 = Math.max(y0 + 1, Math.floor((y + 1) * img.h / 64)); + let r = 0, g = 0, b = 0, n = 0; + for (let yy = y0; yy < y1; yy++) for (let xx = x0; xx < x1; xx++) { const o = (yy * img.w + xx) * 4; r += img.rgba[o]; g += img.rgba[o + 1]; b += img.rgba[o + 2]; n++; } + r /= n; g /= n; b /= n; + px[y * 64 + x] = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); + } + const reduce = [(v) => v, (v) => v & 0xF79E, (v) => v & 0xE71C, (v) => v & 0xC618]; + for (const f of reduce) { + const pal = new Map(); let ok = true; + for (const v of px) { const c = f(v); if (!pal.has(c)) { if (pal.size === 256) { ok = false; break; } pal.set(c, pal.size); } } + if (!ok) continue; + const out = new Uint8Array(T18_PIC_SZ - 4); + for (const [c, i] of pal) { out[2 * i] = c & 255; out[2 * i + 1] = c >> 8; } + for (let i = 0; i < 4096; i++) out[512 + i] = pal.get(f(px[i])); + return out; + } + throw new Error('too many colours'); +} +/** pictures (Map id -> 4608 bytes from t18PicMake) into the ROM of an installed T18Emu (main program) */ +function t18PicsWrite(rom, pics) { + const c = APP_OFF + 0x140; if (u32(rom, c) !== T18_MAGIC) return rom; + const out = new Uint8Array(rom); out.fill(0xFF, T18_PIC_OFF, T18_PIC_END); + const sanrio = (u32(rom, c + 432) & 1) !== 0, ids = T18_ADULTS.map((a) => a[0]).filter((id) => pics.has(id) && id !== (sanrio ? 35 : 21)).slice(0, 10); + if (!ids.length) { w32(out, c + 436, 0); return out; } + w32(out, T18_PIC_OFF, 0x49503854); w32(out, T18_PIC_OFF + 4, ids.length); + ids.forEach((id, k) => { const o = T18_PIC_OFF + 16 + k * T18_PIC_SZ; out.fill(0, o, o + 4); out[o] = id; out.set(pics.get(id), o + 4); }); + w32(out, c + 436, T18_PIC_OFF); + return out; +} +function t18PicsRead(rom) { + const m = new Map(); if (u32(rom, APP_OFF + 0x140) !== T18_MAGIC || u32(rom, T18_PIC_OFF) !== 0x49503854) return m; + const n = Math.min(u32(rom, T18_PIC_OFF + 4), 10); + for (let k = 0; k < n; k++) { const o = T18_PIC_OFF + 16 + k * T18_PIC_SZ; m.set(rom[o], rom.slice(o + 4, o + T18_PIC_SZ)); } + return m; +} +/** for showing: RGBA of a stored picture */ +function t18PicRgba(p) { + const rgba = new Uint8ClampedArray(64 * 64 * 4); + for (let i = 0; i < 4096; i++) { const k = p[512 + i], v = p[2 * k] | (p[2 * k + 1] << 8); rgba[4 * i] = (v >> 11) * 255 / 31; rgba[4 * i + 1] = ((v >> 5) & 63) * 255 / 63; rgba[4 * i + 2] = (v & 31) * 255 / 31; rgba[4 * i + 3] = 255; } + return { w: 64, h: 64, rgba }; +} +/** The flash part of the program at T18_XIP_OFF */ +function t18PutXip(out, app) { + if (!t18XipOk(app)) throw new Error('T18Emu program incomplete (flash part missing)'); + out.fill(0xFF, T18_XIP_OFF, T18_XIP_OFF + T18_XIP_MAX); + out.set(app.xip, T18_XIP_OFF); + if (u32(out, APP_OFF + 0x140) === T18_MAGIC && (u32(out, APP_OFF + 0x140 + 400) & T18F_HOTWIN)) { + out.fill(0xFF, 0xFD0000, 0xFF0000); + out.set(app.xip, T18_XIP_HOT); + } +} +/** Newer T18 program into a ROM that already has T18Emu: settings (block map) stay. null if nothing to do. + * Before 1.5.1 the clock switch did not exist: it is switched on then. */ +function t18Upgrade(rom, app, stubTpl) { + if (u32(rom, APP_OFF + 0x140) !== T18_MAGIC) return null; + // 1.6.6: a ROM without the hot window gets it when there is room. The firmware comes from the ROM as the + // device last saw it (the block map in the save area holds the blocks the firmware wrote), so the pet stays; + // only the running session starts anew. + // test10: a hot window with the first block list gets the new one (same way, the pet stays) + const fl0 = u32(rom, APP_OFF + 0x140 + 400); + if (stubTpl && (!(fl0 & T18F_HOTWIN) || (T18_HOT_V2 && !(fl0 & T18F_HOT2)))) { + const fw = t18FromRom(rom); + if (fw) { + const fl = u32(rom, APP_OFF + 0x140 + 400); + try { const r = t18Patch(rom, fw, app, stubTpl, { lang: fl & 1 ? 'en' : 'de', clock: (fl & 2) !== 0 }); if (r.hot) return r.rom; } catch (e) { /* stays as it is */ } + } + } + const a = new Uint8Array(app); + if (u32(a, 0x140) !== T18_MAGIC) return null; + a.set(rom.subarray(APP_OFF + 0x140, APP_OFF + 0x140 + 428), 0x140); + { const fw = t18FromRom(rom); if (fw) t18ParamSet(a, 0x140, fw); } // test47: the Param block (grow up) + const hotw = (u32(rom, APP_OFF + 0x140 + 400) & T18F_HOTWIN) !== 0; + const xipSame = t18XipOk(app) && rom.subarray(T18_XIP_OFF, T18_XIP_OFF + app.xip.length).every((v, i) => v === app.xip[i]) + && (!hotw || rom.subarray(T18_XIP_HOT, T18_XIP_HOT + app.xip.length).every((v, i) => v === app.xip[i])); + if (!xipSame) a[0x140 + 400] |= 2; + let same = xipSame; + for (let i = 0; i < APP_MAX && same; i++) if ((i < 0x13C || i > 0x13F) && rom[APP_OFF + i] !== (i < a.length ? a[i] : 0)) same = false; // test24: 0x13C the way back (Studio) + if (same) return null; + const out = new Uint8Array(rom); + out.fill(0x00, APP_OFF, APP_OFF + APP_MAX); + out.set(a, APP_OFF); + t18PutXip(out, app); + return out; +} +/** The TG18 firmware as the ROM holds it: the block map of the save area (blocks the firmware wrote) + * or the one of the settings. null if it is not complete. */ +function t18FromRom(rom, base = APP_OFF) { + const c = t18Cfg(rom, base); if (!c) return null; + let map = c.map; + const so = c.saveOff; + if (so + 0x1000 <= rom.length && u32(rom, so) === 0x504D3854) { map = []; for (let i = 0; i < 128; i++) map.push(rom[so + 4 + 2 * i] | (rom[so + 5 + 2 * i] << 8)); } + const fw = new Uint8Array(0x800000).fill(0xFF); + map.forEach((b, g) => { if (b !== 0xFFFF && b < 0x100) fw.set(rom.subarray(b << 16, (b + 1) << 16), g << 16); }); + // test45 (T18_SEC_SPARE): single 4 KB sectors of empty guest blocks from the spare blocks ("T8SS" behind the map) + const o = so + 4 + 256 + T18_SPARE_MAX; + if (map !== c.map && o + 132 + 16 * 19 <= rom.length && u32(rom, o) === 0x53533854) { + for (let g = 0; g < 128; g++) { + const i = rom[o + 4 + g]; if (!i || i > 19 || map[g] !== 0xFFFF) continue; + for (let sct = 0; sct < 16; sct++) { + let k = rom[o + 132 + 16 * (i - 1) + sct]; if (!k) continue; k--; + const b = c.spare[k >> 4]; if (b === undefined || b === 0xFFFF) continue; + const p = (b << 16) | ((k & 15) << 12); fw.set(rom.subarray(p, p + 0x1000), (g << 16) | (sct << 12)); + } + } + } + return t18Detect(fw) ? fw : null; +} +/* + * More programs (1.6.0): besides the program at 0x0A0000 (started by A+C or by the menu) the menu can + * start more programs, each a full 64 KB PRAM image somewhere in the flash (started through the stub + * entry at +0x0C). For now: T7Emu with its own ROM (Tama-Go or Friends), no figures. Placed from the + * top of the emulator area (0xD40000) down, each in its own block: image (64 KB), save (24 KB), ROM. + * The menu lists them (settings block version 5, see feld.js). + */ +const APPX_MAX = 12, T7X_SAVE = 0x6000; // 1.6.8: 12 (menu version 8) +function t7XName(rom) { return t7Kind(rom) === 'friends' ? 'FRIENDS' : 'TAMA-GO'; } +/** Reserved by the program at 0x0A0000 although empty (spares): [from, to) ranges. */ +function appReserved(rom) { + const r = [], m = u32(rom, APP_OFF + 0x140); + if (m === T18_MAGIC) { const c = t18Cfg(rom); for (const b of c.map.concat(c.spare)) if (b !== 0xFFFF) r.push([b << 16, (b + 1) << 16]); if (c.flags & T18F_HOTWIN) r.push([0xFD0000, 0xFF0000]); } + if (m === PMXC && u32(rom, APP_OFF + 0x144) >= 3) { const g = u32(rom, APP_OFF + 0x148); r.push([g, Math.max(g, u32(rom, APP_OFF + 0x140 + 152))]); } + // 1.6.8: the save areas behind the program (empty until used) + if (m === PMXC) r.push([SAVE_OFF, SAVE_END]); + if (m === T7_MAGIC) r.push([SAVE_OFF, SAVE_OFF + 0x6000]); + if (m === V1_MAGIC) r.push([SAVE_OFF, SAVE_OFF + 0x2000]); + if (m === T18_MAGIC) r.push([SAVE_OFF, SAVE_OFF + T18_SAVE_LEN], [T18_XIP_OFF, T18_XIP_OFF + T18_XIP_MAX], [T18_PIC_OFF, T18_PIC_END]); + return r; +} +/* + * 1.6.8: besides T7Emu the extra programs can be TamaEmu (a colour Tama firmware) and T18Emu (one only, its + * flash part has a fixed place at T18_XIP_OFF). An extra is { rom } (T7), { kind: 'tama', guest, dev } or + * { kind: 't18', fw }. Each brings its own 64 KB image (settings block inside) and its own save area: + * T7Emu: image, save (64 KB, 24 KB used), ROM (one piece, as before) + * TamaEmu: packed firmware with room for spare pages (256 KB aligned, it is the base of the cached + * window), then image and run state (320 KB, like 0x0C0000..0x110000) + * T18Emu: firmware blocks anywhere (block map), image, save (T18_SAVE_LEN) + */ +const TX_STATE = 0x50000, TX_SPARE = 0x90000, T18X_SAVE = (T18_SAVE_LEN + 0xFFFF) & ~0xFFFF; +const TX_NAMES = { pc: 'PLUS COLOR', idl: 'ID L', ps: 'PS', '4u': '4U+', '4u-plain': '4U' }; +/* GUEST_SPARSE: the room for spare pages grows by the firmware's own pages (the pool for the guest's writes stays as it + * was, 64 pages at most) */ +function txSpare(pk, txs) { const t = txs || TX_SPARE, np = pk.pages.length; return np ? Math.max(t, Math.min(t + (np << 13), 0x84000)) : t; } +function extraKind(x) { return x.kind || (v1Detect(x.rom) ? 'v1' : 't7'); } +/* DOOM_FREE: room of DOOM in the menu: program with its part and save (64 KB aligned), WAD with the level data behind */ +function doomParts(x, xipLen) { + const page = (n) => (n + 0xFFF) & ~0xFFF, blk = (n) => (n + 0xFFFF) & ~0xFFFF; + const n = x.mcu ? x.mcu.length : (x.size || 0x300000); + return { prog: blk(0x10000 + page(xipLen || 0x3A000) + DOOM_SAVE + (DOOM_CMAP ? 0x3000 : 0)), wad: blk(page(4 + n) + doomRegion(x)) }; +} +/* 1.6.8: iD L versions by their reset vector (all run as iD L): Japanese 1.0, English, 15th anniversary, Princess Spacy */ +const IDL_NAMES = { 0x024CA8FE: 'ID L JP', 0x024CA942: 'ID L JP', 0x024CAA72: 'ID L', 0x024BD18A: 'ID L 15TH', 0x024C14F6: 'ID L SPACY' }; +function tamaName(guest, dev) { + if (dev === 'idl' && guest && guest.length >= 0x400004) { const n = IDL_NAMES[u32(guest, 0x400000)]; if (n) return n; } + if (dev === 'pc' && idFirmware(guest)) return 'ID'; // 1.7.4 test2 + return TX_NAMES[dev] || 'TAMAEMU'; +} +function extraName(x) { const k = extraKind(x); return k === 'doom' ? (x.title ? x.title : x.ep && x.ep !== 'all' ? 'DOOM E' + x.ep : x.d2 ? 'DOOM II' : x.name && /^[A-Z0-9 .'!-]{1,16}$/.test(x.name) ? x.name : 'DOOM') : k === 'tama' ? tamaName(x.guest, x.dev) : k === 't18' ? 'TAMA MEETS' : k === 'v1' ? v1Name(x.rom) : k === 'gb' ? gbTitle(x.rom) : k === 'sms' ? (x.title || 'MASTER SYSTEM') : k === 'pm' ? (x.title || 'POKEMON MINI') : k === 'ab' ? (x.title || 'ARDUBOY') : k === 'wolf' ? (wolfSod(x.pack) ? 'SPEAR OF DESTINY' : 'WOLFENSTEIN 3D') : t7XName(x.rom); } +/** Rough flash use of an extra (for the overview) */ +const SIZE_CACHE = true, sizeCache = new WeakMap(); +function extraSize(x, txs) { + const k = extraKind(x); + if (k === 'tama') { + // 1.7.2 SIZE_CACHE: packing takes up to half a second; the firmware arrays are new ones whenever they change + const ck = (txs || 0) + ':' + x.dev + (x.pack ? ':z' : ''), hit = SIZE_CACHE && sizeCache.get(x.guest); if (hit && hit[ck] !== undefined) return hit[ck]; + // TAMA_RAW (test18): the size as it goes in when there is room (unpacked) + let n = 0; try { const pk = packGuest(x.guest, x.dev, { sparse: true, lz: GUEST_LZ && (PACK_OPT ? !!x.pack || tamaNeedsLz(x.guest, x.dev) : !TAMA_RAW) }); n = ((pk.blob.length + txSpare(pk, txs) + 0xFFFF) & ~0xFFFF) + 0x10000 + TX_STATE; } catch (e) { n = 0; } + if (SIZE_CACHE && x.guest) { const m = hit || {}; m[ck] = n; sizeCache.set(x.guest, m); } + return n; + } + if (k === 'v1') return v3Detect(x.rom) ? 0x92000 : 0x12000 + x.rom.length; + if (k === 'gb') return ((gbStore(x.rom).rom.length + 0xFFFF) & ~0xFFFF) + 0x10000 + gbSaveLen(gbIsColor(x.rom)); + if (k === 'sms') return ((x.rom.length + 0xFFFF) & ~0xFFFF) + 0x20000; + if (k === 'pm') return ((x.rom.length + 0xFFFF) & ~0xFFFF) + 0x10000 + PM_SAVE; + if (k === 'ab') return 0x20000; + if (k === 'wolf') return ((x.pack.length + 0xFFFF) & ~0xFFFF) + 0x30000; + if (k === 'doom') { const p = doomParts(x); return p.prog + p.wad; } + if (k === 't18') { let n = 0; for (let i = 0; i < 128; i++) if (!isFF(x.fw, i << 16, 0x10000)) n++; return (n + T18_SPARE_WANT) * 0x10000 + 0x10000 + T18X_SAVE; } + return 0x20000 + ((x.rom.length + 0xFFFF) & ~0xFFFF) + (x.figs || []).reduce((n, f) => n + ((f.data.length + 0xFFF) & ~0xFFF), 0); +} +/** + * Put the extra programs into rom. app: t7.bin, or { t7, tama, t18 } (the embedded programs). + * opts: lang, clock, launch (launcher ROM: anywhere free behind the setup pictures), keep: more [from, to) + * ranges that must stay free (DOOM's data area). Returns { rom, list: [{ src, name, off }], low }. + */ +/* 1.6.10 test3 APPS_PACK: start device: the biggest programs first, each into the highest gap that fits (before: one + * after the other below the lowest one, gaps above stayed empty); Game Boy and Master System games apart from their + * program. The list keeps its order. */ +const APPS_PACK = true; +/* test13: the rescue block (0xFF0000) is kept free only when everything fits without it */ +/* test15: no longer only when it fits: the block is the write protection, the Studio does not write without it */ +/* 1.7.3 test18 TAMA_RAW, test20 PACK_OPT: a TamaEmu goes in unpacked unless its option "pack" (x.pack) is on (Bernd: iD L + * slow in the restaurant, its pictures sat in packed 1 KB parts that the device unpacks on every read). When the + * programs do not fit, the error says whether packing a TamaEmu could help (e.packHint). */ +const TAMA_RAW = true, PACK_OPT = true, DOOM_TOP = true; +function appsPlace(rom, extras, app, opts = {}) { + CLEAN = !!opts.clean; + try { + try { return appsPlace0(rom, extras, app, opts); } + catch (e) { // 1.7.3 test21 DOOM_TOP: the WADs from the top down, one after the other (the 4 MB rule can split the room) + if (!(DOOM_TOP && e && e.room && opts.clean && !opts.doomTop && extras.filter((x) => extraKind(x) === 'doom').length > 1)) throw e; + try { return appsPlace0(rom, extras, app, Object.assign({}, opts, { doomTop: true })); } catch (e2) { throw e; } + } + } + catch (e) { if (e && e.room && extras.some((x) => extraKind(x) === 'tama' && !x.pack)) e.packHint = true; throw e; } + finally { CLEAN = false; } +} +function appsPlace0(rom, extras, app, opts = {}) { + const apps = app instanceof Uint8Array ? { t7: app } : app; + const out = new Uint8Array(rom), list = [], res = appReserved(out).concat(opts.keep || []); + if (extras.length > APPX_MAX) throw new Error('at most ' + APPX_MAX + ' more programs'); + let top = GUEST_END; + // launcher ROM (1.6.8): anywhere free between the setup pictures and 0xD40000, from the top down + const floor = opts.clean ? 0x10000 : opts.launch ? Math.max(0x200000, (assetEnd(out) + 0xFFFF) & ~0xFFFF) : GUEST_OFF; + const ceil = opts.clean ? 0xFF0000 : opts.launch ? Math.min(GUEST_END, idPageOf(out)) : GUEST_END; // never into the Paradise's save (Tropical/Glacier: from 0xD29000) + if (opts.launch) top = ceil; + const fits = (at, size) => at >= floor && at + size <= ceil && isFF(out, at, size) && !res.some(([a, b]) => a < at + size && b > at); + const find = (size, align) => { let at = ((APPS_PACK && opts.launch ? ceil : top) - size) & ~(align - 1); if (opts.launch || align > 0x10000) while (at >= floor && !fits(at, size)) at -= align; return fits(at, size) ? at : -1; }; + // start device (1.6.8): the Paradise never writes behind its save (0xF00000..0xFFFFFF); without T18Emu (it takes that + // MB itself) programs that fit go there first + const hiOk = !!opts.launch && !opts.clean && !extras.some((x) => extraKind(x) === 't18') && u32(out, APP_OFF + 0x140) !== T18_MAGIC; + const hiEnd = RESCUE_RES && !opts.noResv ? RESCUE_BLK << 16 : 0x1000000; // test13: the rescue start's block stays free + const fitsHi = (at, size) => at >= 0xF00000 && at + size <= hiEnd && isFF(out, at, size) && !res.some(([a, b]) => a < at + size && b > at); + const findHi = (size, align) => { if (!hiOk) return -1; let at = (hiEnd - size) & ~(align - 1); while (at >= 0xF00000 && !fitsHi(at, size)) at -= align; return fitsHi(at, size) ? at : -1; }; + const place = (size, align) => { const h = findHi(size, align); return h >= 0 ? { at: h, hi: true } : { at: find(size, align), hi: false }; }; + // 1.6.8: no room: how much is missing for this program and the ones after it (not just the name of the one that hit it) + const freeKB = () => { let n = 0; for (let a = floor; a + 0x10000 <= ceil; a += 0x10000) if (fits(a, 0x10000)) n++; if (hiOk) for (let a = 0xF00000; a < hiEnd; a += 0x10000) if (fitsHi(a, 0x10000)) n++; return n * 64; }; + const noRoom = (i) => { + let need = opts.dlApp ? 0x10000 : 0; for (let j = 0; j < extras.length; j++) if (left.has(j) && !kept.has(extras[j])) need += extraSize(extras[j], opts.txSpare) - ((typeof dLinks !== 'undefined' && dLinks.get(extras[j])) ? dLinks.get(extras[j]).saved : 0); + const short = Math.ceil((need / 1024 - freeKB()) / 64) * 64, miss = Math.max(64, short); + // 1.7.3 test13: frag: the room adds up, but not in pieces big enough (DOOM episodes need up to 8 MB in one window) + return Object.assign(new Error('no room: about ' + miss + ' KB missing'), { room: true, missing: miss, frag: short <= 0 }); + }; + // test2: an installed T18Emu (keepOff) stays where it is: its save grows while it runs, so placing it anew may no + // longer fit. Its blocks are taken first; the program, its settings and the items are renewed in place below. + const kept = new Set(); + for (const x of extras) { + if (extraKind(x) !== 't18' || x.keepOff === undefined || !t18XipOk(apps.t18)) continue; + const c = t18Cfg(out, x.keepOff); if (!c) continue; + kept.add(x); + for (const b of c.map.concat(c.spare)) if (b !== 0xFFFF) res.push([b << 16, (b + 1) << 16]); + res.push([T18_XIP_OFF, T18_XIP_OFF + T18_XIP_MAX]); if (c.flags & T18F_HOTWIN) res.push([0xFD0000, 0xFF0000]); + res.push([x.keepOff, x.keepOff + 0x10000], [c.saveOff, c.saveOff + T18X_SAVE]); + } + const pack = APPS_PACK && !!opts.launch; + const order = extras.map((x, i) => i); + if (pack) order.sort((a, b) => (kept.has(extras[b]) - kept.has(extras[a])) || (extraSize(extras[b]) - extraSize(extras[a])) || (a - b)); + // DOOM_LINK: linked DOOM entries after the entries they point into + const dLinks = DOOM_LINK && opts.clean ? doomLinks(extras) : new Map(), wadAt = new Map(); + if (dLinks.size) { const late = order.filter((i) => dLinks.has(extras[i])); order.splice(0, order.length, ...order.filter((i) => !dLinks.has(extras[i])), ...late); } + const left = new Set(order); + for (const xi of order) { + const x = extras[xi]; + const k = extraKind(x), name = k === 'wolf' && wolfSod(x.pack) ? 'WOLF3D SPEAR' : extraName(x); // 1.6.11 test2: 12 characters in the menu + // 1.6.8: clock and NFC per program (x.clock / x.nfc), otherwise the common setting + // 1.7.3 test7: opts.noClock (clean ROM, clock not set at the start): no program takes the Paradise's clock; x.sess false: + // no session on leaving (flags bit 12, SESS_FLAG in the programs) + const clk = !opts.noClock && (x.clock !== undefined ? x.clock !== false : opts.clock !== false), nfc = x.nfc !== undefined ? x.nfc !== false : opts.nfc !== false; + const flags = ((opts.lang === 'en' || opts.lang === 'ko') ? 1 : 0) | (clk ? 2 : 0) | (nfc ? 0 : 4) | optBits(x.opt) | (x.sess === false ? NOSESS : 0) | (k === 'tama' && idFirmware(x.guest) ? ID_STRAP : 0); + if (k !== 't7' && k !== 'v1' && k !== 'gb' && k !== 'sms' && k !== 'pm' && k !== 'ab' && k !== 'wolf' && !opts.launch) throw new Error(name + ': only in a start device'); + if (k === 't7') { + if (!t7Detect(x.rom)) throw new Error('not a V7 ROM'); + if (!apps.t7) throw new Error('T7Emu missing'); + // 1.6.8: figures for the further T7Emus as well (behind the ROM, 4 KB aligned) + const figs = t7Kind(x.rom) === 'friends' ? [] : (x.figs || []).slice(0, T7_FIG_MAX).map((f) => ({ d: t7Trim(f.data), name: t7FigName(f.name) })); + let figLen = 0; for (const f of figs) figLen += (f.d.length + 0xFFF) & ~0xFFF; + const size = 0x20000 + ((x.rom.length + 0xFFF) & ~0xFFF) + figLen; + const pl = place((size + 0xFFFF) & ~0xFFFF, 0x10000), at = pl.at; + if (at < 0) throw noRoom(xi); + const a = new Uint8Array(0x10000); a.set(apps.t7); + const c = 0x140; + if (u32(a, c) !== T7_MAGIC) throw new Error('settings block missing in the program'); + w32(a, c + 4, 1); w32(a, c + 8, at + 0x20000); w32(a, c + 12, x.rom.length); w32(a, c + 16, at + 0x10000); w32(a, c + 20, figs.length); + a.fill(0, c + 24, c + 24 + T7_FIG_MAX * 24); + out.set(x.rom, at + 0x20000); + let fo = at + 0x20000 + ((x.rom.length + 0xFFF) & ~0xFFF); + figs.forEach((f, i) => { const o = c + 24 + i * 24; out.set(f.d, fo); w32(a, o, fo); w32(a, o + 4, f.d.length); for (let q = 0; q < f.name.length && q < 15; q++) a[o + 8 + q] = f.name.charCodeAt(q); fo += (f.d.length + 0xFFF) & ~0xFFF; }); + w32(a, c + 24 + T7_FIG_MAX * 24, flags); + out.set(a, at); + t7XWrite(out, at + 0x10000, apps.t7); + list.push({ src: xip(at), name, off: at }); + res.push([at, at + size]); if (!pl.hi) top = Math.min(top, at); + } else if (k === 'gb') { + // 1.6.9 test36 GBEmu: the ROM first (64 KB aligned, the base of the cached window), then program, settings, cartridge RAM + const color = gbIsColor(x.rom), gb = color ? (apps.gbc || gbcEmbedded()) : (apps.gb || gbEmbedded()); if (!gb) throw new Error(color ? 'GBCEmu missing' : 'GBEmu missing'); + const tr = gbStore(x.rom), ra = (tr.rom.length + 0xFFFF) & ~0xFFFF, sl = gbSaveLen(color), size = ra + 0x10000 + sl; + let pl, at, po; + if (pack) { // test3: the game and the program (with its save) each where there is room + pl = place(ra, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); + res.push([at, at + ra]); if (!pl.hi) top = Math.min(top, at); + const p2 = place(0x10000 + sl, 0x10000); po = p2.at; if (po < 0) throw noRoom(xi); + res.push([po, po + 0x10000 + sl]); if (!p2.hi) top = Math.min(top, po); + } else { pl = place(size, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); po = at + ra; } + const a = new Uint8Array(0x10000); a.set(gb); + const c = 0x140; + if (u32(a, c) !== GB_MAGIC) throw new Error('settings block missing in the program'); + gbCfgWrite(a, c, x, at, po + 0x10000, flags, tr); + out.set(tr.rom, at); + out.set(a, po); + if (x.save && x.save.length) { const sv = new Uint8Array(sl).fill(0xFF); sv.set(x.save.subarray(0, sl)); out.set(sv, po + 0x10000); } + else out.fill(0xFF, po + 0x10000, po + 0x10000 + sl); + list.push({ src: xip(po), name, off: po }); + if (!pack) { res.push([at, at + size]); if (!pl.hi) top = Math.min(top, at); } + } else if (k === 'sms') { + // 1.6.10 test2 SMSEmu: as GBEmu (the ROM first, 64 KB aligned, then program, settings, cartridge RAM) + const sm = apps.sms || smsEmbedded(); if (!sm) throw new Error('SMSEmu missing'); + const ra = (x.rom.length + 0xFFFF) & ~0xFFFF, size = ra + 0x20000; + let pl, at, po; + if (pack) { // test3: the game and the program (with its save) each where there is room + pl = place(ra, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); + res.push([at, at + ra]); if (!pl.hi) top = Math.min(top, at); + const p2 = place(0x20000, 0x10000); po = p2.at; if (po < 0) throw noRoom(xi); + res.push([po, po + 0x20000]); if (!p2.hi) top = Math.min(top, po); + } else { pl = place(size, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); po = at + ra; } + const a = new Uint8Array(0x10000); a.set(sm); + const c = 0x140; + if (u32(a, c) !== SMS_MAGIC) throw new Error('settings block missing in the program'); + smsCfgWrite(a, c, x, at, po + 0x10000, flags); + out.set(x.rom, at); + out.set(a, po); + if (x.save && x.save.length) { const sv = new Uint8Array(0x10000).fill(0xFF); sv.set(x.save.subarray(0, 0x10000)); out.set(sv, po + 0x10000); } + else out.fill(0xFF, po + 0x10000, po + 0x20000); + list.push({ src: xip(po), name, off: po }); + if (!pack) { res.push([at, at + size]); if (!pl.hi) top = Math.min(top, at); } + } else if (k === 'pm') { + // 1.7.3 PokeMiniEmu: as SMSEmu (the game first, 64 KB aligned: the base of the cached window; then program and save) + const pm = apps.pm || pmEmbedded(); if (!pm) throw new Error('PokeMiniEmu missing'); + const ra = (x.rom.length + 0xFFFF) & ~0xFFFF, size = ra + 0x10000 + PM_SAVE; + let pl, at, po; + if (pack) { + pl = place(ra, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); + res.push([at, at + ra]); if (!pl.hi) top = Math.min(top, at); + const p2 = place(0x10000 + PM_SAVE, 0x10000); po = p2.at; if (po < 0) throw noRoom(xi); + res.push([po, po + 0x10000 + PM_SAVE]); if (!p2.hi) top = Math.min(top, po); + } else { pl = place(size, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); po = at + ra; } + const a = new Uint8Array(0x10000); a.set(pm); + const c = 0x140; + if (u32(a, c) !== PM_MAGIC) throw new Error('settings block missing in the program'); + pmCfgWrite(a, c, x, at, po + 0x10000, flags); + out.set(x.rom, at); + out.set(a, po); + const sv = new Uint8Array(PM_SAVE).fill(0xFF); + if (x.save && x.save.length) sv.set(x.save.subarray(0, PM_BIOS_AT)); + if (x.bios && pmBiosDetect(x.bios)) sv.set(x.bios, PM_BIOS_AT); + out.set(sv, po + 0x10000); + list.push({ src: xip(po), name, off: po }); + if (!pack) { res.push([at, at + size]); if (!pl.hi) top = Math.min(top, at); } + } else if (k === 'ab') { + // 1.7.3 ArduboyEmu: the game with its save in one 64 KB block (the base of the cached window), the program apart + const ab = apps.ab || abEmbedded(); if (!ab) throw new Error('ArduboyEmu missing'); + if (!x.rom || x.rom.length > AB_MAX) throw new Error(name + ': too big'); + let pl, at, po; + if (pack) { + pl = place(0x10000, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); + res.push([at, at + 0x10000]); if (!pl.hi) top = Math.min(top, at); + const p2 = place(0x10000, 0x10000); po = p2.at; if (po < 0) throw noRoom(xi); + res.push([po, po + 0x10000]); if (!p2.hi) top = Math.min(top, po); + } else { pl = place(0x20000, 0x10000); at = pl.at; if (at < 0) throw noRoom(xi); po = at + 0x10000; } + const a = new Uint8Array(0x10000); a.set(ab); + const c = 0x140; + if (u32(a, c) !== AB_MAGIC) throw new Error('settings block missing in the program'); + abCfgWrite(a, c, x, at, at + AB_SAVE_AT, flags); + out.fill(0xFF, at, at + 0x10000); + out.set(x.rom, at); + out.set(a, po); + const sv = new Uint8Array(AB_SAVE).fill(0xFF); + if (x.save && x.save.length) sv.set(x.save.subarray(0, AB_SAVE)); + out.set(sv, at + AB_SAVE_AT); + list.push({ src: xip(po), name, off: po }); + if (!pack) { res.push([at, at + 0x20000]); if (!pl.hi) top = Math.min(top, at); } + } else if (k === 'doom') { + // 1.7.2 test3 DOOM_FREE: anywhere. The program part runs at XIP 0x100A0000 (the window follows it: code at 0x0A0000 or + // above), the packed flash pointers reach two 4 MB windows (WAD and level data inside 8 MB from a 4 MB boundary) + if (!opts.clean) throw new Error('DOOM goes into the menu only without the Paradise'); + const dm = apps.doom; if (!dm || !dm.app || !dm.xip) throw new Error('DOOM program missing'); + if (!x.mcu) throw new Error('DOOM: WAD not converted'); + const lk = dLinks.get(x), xm = lk ? Object.assign({}, x, { mcu: lk.mcu }) : x; // DOOM_LINK + if (dm.app.length > 0x10000) throw new Error('DOOM program too big'); + const parts = doomParts(xm, dm.xip.length), page = (n) => (n + 0xFFF) & ~0xFFF; + // 1.7.3 test12 (several episodes): the WAD first, at a 4 MB boundary or ending on one where possible (the 8 MB + // window then wastes nothing between two WADs), else top down as before; then the program part anywhere + // test13: the level data (DOOM_REGION) may also lie apart from the WAD, anywhere in the same 8 MB window (the clean + // ROM keeps 0xEFD000..0xF00000: a big episode then fits below it, its level data above it) + const wadOnly = DOOM_PKREG ? page(4 + xm.mcu.length) : (page(4 + xm.mcu.length) + 0xFFFF) & ~0xFFFF; // test15: the WAD on a 4 KB page (DOOM II only just fits) + let w = -1, rg = -1; + const RG = doomRegion(x); + const tryW = (a) => { + if (a < floor || !fits(a, wadOnly)) return false; + const B = a & ~0x3FFFFF; if (!DOOM_PKREG && a + wadOnly > B + 0x800000) return false; + if (fits(a, parts.wad)) { w = a; rg = page(a + 4 + xm.mcu.length); return true; } + // test15 DOOM_PKREG: the level data anywhere (it only has to stay inside the 8 MB from its own 4 MB boundary) + const lo = DOOM_PKREG ? floor : Math.max(B, floor), hi = DOOM_PKREG ? ceil : Math.min(ceil, B + 0x800000); + for (let r = (hi - RG) & ~0xFFF; r >= lo; r -= 0x1000) { + if (r < a + wadOnly && r + RG > a) continue; + if (DOOM_PKREG && r + RG > (r & ~0x3FFFFF) + 0x800000) continue; + if (fits(r, RG)) { w = a; rg = r; return true; } + } + return false; + }; + if (!opts.doomTop) for (let b = 0xC00000; b >= 0 && w < 0; b -= 0x400000) if (!tryW(b)) { const e = (b + 0x400000 - wadOnly) & ~0xFFFF; if (e >= 0) tryW(e); } + for (let a = (ceil - wadOnly) & ~0xFFFF; w < 0 && a >= floor; a -= 0x10000) tryW(a); + if (DOOM_PKREG) for (let a = (ceil - wadOnly) & ~0xFFF; w < 0 && a >= floor; a -= 0x1000) tryW(a); + if (w < 0) throw noRoom(xi); + const wrs = rg === page(w + 4 + xm.mcu.length) ? [[w, w + parts.wad]] : [[w, w + wadOnly], [rg, rg + RG]]; + res.push(...wrs); + let at = -1; for (let a = (ceil - parts.prog) & ~0xFFFF; a >= Math.max(floor, 0x90000); a -= 0x10000) if (fits(a, parts.prog)) { at = a; break; } + if (at < 0) { res.splice(res.length - wrs.length, wrs.length); throw noRoom(xi); } + res.push([at, at + parts.prog]); + const a = new Uint8Array(0x10000); a.set(dm.app); + const c = pdmcAt(a, 0); if (c < 0 || u32(a, c + 4) < 2) throw new Error('settings block missing in DOOM'); + const code = at + 0x10000, save = code + page(dm.xip.length), region = rg, cmo = save + DOOM_SAVE, cmap = DOOM_CMAP && u32(a, c + 4) >= 3 ? doomCmap(x.mcu) : null; + if (cmap) w32(a, c + 76, cmo); + w32(a, c + 8, w + 4); w32(a, c + 12, xm.mcu.length); w32(a, c + 16, region); w32(a, c + 20, RG); w32(a, c + 24, save); w32(a, c + 28, code); + if (x.keys) for (const [kk, o] of Object.entries(DOOM_KEY_AT)) if (x.keys[kk] !== undefined) w32(a, c + o, typeof x.keys[kk] === 'boolean' ? (x.keys[kk] ? 1 : 0) : x.keys[kk]); + out.fill(0xFF, at, at + parts.prog); out.set(a, at); out.set(dm.xip, code); + if (x.save && x.save.length) out.set(x.save.subarray(0, DOOM_SAVE), save); + if (cmap) out.set(cmap, cmo); + for (const [p0, p1] of wrs) out.fill(0xFF, p0, p1); + w32(out, w, xm.mcu.length); out.set(xm.mcu, w + 4); wadAt.set(x, w + 4); + if (lk) { // DOOM_LINK: the shared lumps point into the WADs placed before; c+12 reaches over them when they lie above + let hi = w + 4 + xm.mcu.length; + for (const [d, bx, bp] of lk.refs) { const ba = wadAt.get(bx); if (ba === undefined) throw new Error('DOOM: linked WAD missing'); w32(out, w + 4 + d, (ba + bp - (w + 4)) >>> 0); if (ba > w) hi = Math.max(hi, ba + bx.mcu.length); } + w32(out, at + c + 12, hi - (w + 4)); + } + list.push({ src: xip(at), name, off: at }); + top = Math.min(top, at, w, rg); + } else if (k === 'wolf') { + // 1.6.10 test1 Wolf3D: the pack first (64 KB aligned, the base of the cached window), then the program (128 KB), the save + const sod = wolfSod(x.pack), w = sod ? (apps.wolfsod || wolfSodEmbedded()) : (apps.wolf || wolfEmbedded()); + if (!w) throw new Error((sod ? 'Spear of Destiny' : 'Wolf3D') + ' program missing'); + if (!wolfPackOk(x.pack)) throw new Error('Wolf3D data missing'); + if (w.length > 0x20000) throw new Error('Wolf3D program too big'); + const pa = (x.pack.length + 0xFFFF) & ~0xFFFF, size = pa + 0x30000, pl = place(size, 0x10000), at = pl.at; + if (at < 0) throw noRoom(xi); + const a = new Uint8Array(0x20000).fill(0xFF); a.set(w); + const c = 0x140, po = at + pa; + if (u32(a, c) !== WOLF_MAGIC) throw new Error('settings block missing in the program'); + wolfCfgWrite(a, c, x, at, po + 0x20000, po, flags); + out.fill(0xFF, at, at + pa); out.set(x.pack, at); + out.set(a, po); + if (x.save && x.save.length) { const sv = new Uint8Array(0x10000).fill(0xFF); sv.set(x.save.subarray(0, 0x10000)); out.set(sv, po + 0x20000); } + else out.fill(0xFF, po + 0x20000, po + 0x30000); + list.push({ src: xip(po), name, off: po }); + res.push([at, at + size]); if (!pl.hi) top = Math.min(top, at); + } else if (k === 'v1' && v3Detect(x.rom)) { + // 1.6.9 V3Emu: the ROM first (64 KB aligned, the base of the cached window), then program, session, settings + const v3 = apps.v3 || (apps.v1 && apps.v1.v3) || v3Embedded(); if (!v3) throw new Error('V3Emu missing'); + const size = 0x92000, pl = place(size, 0x10000), at = pl.at; + if (at < 0) throw noRoom(xi); + const a = new Uint8Array(0x10000); a.set(v3); + const c = 0x140, po = at + 0x80000; + if (u32(a, c) !== V1_MAGIC) throw new Error('settings block missing in the program'); + v1CfgWrite(a, c, x.rom, at, po + 0x10000, flags); + for (let i = 0; i < 16; i++) a[c + 24 + i] = i < name.length ? name.charCodeAt(i) : 0; + out.set(x.rom, at); + out.set(a, po); + out.fill(0xFF, po + 0x10000, po + 0x12000); + list.push({ src: xip(po), name, off: po }); + res.push([at, at + size]); if (!pl.hi) top = Math.min(top, at); + } else if (k === 'v1') { + if (!apps.v1) throw new Error('V1Emu missing'); + const size = 0x12000 + ((x.rom.length + 0xFFF) & ~0xFFF); // program, session 4 KB, settings 4 KB, ROM + const pl = place(size, 0x1000), at = pl.at; + if (at < 0) throw noRoom(xi); + const a = new Uint8Array(0x10000); a.set(apps.v1); + const c = 0x140; + if (u32(a, c) !== V1_MAGIC) throw new Error('settings block missing in the program'); + v1CfgWrite(a, c, x.rom, at + 0x12000, at + 0x10000, flags); + for (let i = 0; i < 16; i++) a[c + 24 + i] = i < name.length ? name.charCodeAt(i) : 0; + out.set(a, at); + out.fill(0xFF, at + 0x10000, at + 0x12000); + out.set(x.rom, at + 0x12000); + list.push({ src: xip(at), name, off: at }); + res.push([at, at + size]); if (!pl.hi) top = Math.min(top, at); + } else if (k === 'tama') { + if (!apps.tama) throw new Error('TamaEmu missing'); + const lzCan = GUEST_LZ && tamaLzCan(apps.tama) && (PACK_OPT ? !!x.pack || tamaNeedsLz(x.guest, x.dev) : !opts.tamaRaw); + const memo = SIZE_CACHE && !x.lzAll && !x.lzExtra ? (sizeCache.get(x.guest) || {}) : null, mk = 'pk:' + x.dev + ':' + lzCan; // SIZE_CACHE: trial builds pack only once + const pk = (memo && memo[mk]) || packGuest(x.guest, x.dev, { sparse: true, lz: lzCan, lzAll: !!x.lzAll, lzExtra: x.lzExtra }), { map, blob, pages } = pk; + if (memo && !memo[mk]) { memo[mk] = pk; sizeCache.set(x.guest, memo); } + const gLen = (blob.length + txSpare(pk, opts.txSpare) + 0xFFFF) & ~0xFFFF, size = gLen + 0x10000 + TX_STATE; // test25: opts.txSpare (less room for spare pages when tight, as the main TamaEmu) + const pl = place(size, 0x40000), gOff = pl.at; + if (gOff < 0) throw noRoom(xi); + const gEnd = gOff + gLen, img = gEnd, st = gEnd + 0x10000; + out.set(blob, gOff); + if (pages.length) putPages(out, gOff, gEnd, blob.length, pages); + const a = new Uint8Array(apps.tama.length > 0x10000 ? 0 : 0x10000); a.set(apps.tama); + let ci = -1; for (let i = 0; i + 4 <= a.length; i += 4) if (u32(a, i) === PMXC) { ci = i; break; } + if (ci < 0 || u32(a, ci + 156) !== 0) throw new Error('settings block missing in the program'); + w32(a, ci + 4, 4); w32(a, ci + 8, gOff); w32(a, ci + 12, blob.length); w32(a, ci + 16, st); w32(a, ci + 20, DEVICES[x.dev].kind); + a.set(map, ci + 24); w32(a, ci + 152, gEnd); w32(a, ci + 156, flags); + if (lzCan) { w32(a, ci + 4, 5); w32(a, ci + 160, pk.lzOff !== undefined ? gOff + pk.lzOff : 0); } // GUEST_LZ: version 5, the table of the packed blocks + out.set(a, img); + list.push({ src: xip(img), name, off: img }); + res.push([gOff, gOff + size]); if (!pl.hi) top = Math.min(top, gOff); + } else if (k === 't18' && kept.has(x)) { + const off = x.keepOff, a = new Uint8Array(0x10000); a.set(apps.t18); + if (u32(a, 0x140) !== T18_MAGIC) throw new Error('settings block missing in the program'); + // its block map, spares and save place stay (up to +400); the addresses come from its firmware again (an older + // program had code where +428.. is now: test2 copied that and grow up wrote into nowhere) + a.set(out.subarray(off + 0x140, off + 0x140 + 400), 0x140); + const hot = u32(out, off + 0x140 + 400) & (T18F_HOTWIN | T18F_HOT2), ad = t18Addrs(x.fw); + w32(a, 0x140 + 404, ad.idle); w32(a, 0x140 + 408, ad.soft); w32(a, 0x140 + 412, ad.dma); + w32(a, 0x140 + 416, 0); w32(a, 0x140 + 420, 0); w32(a, 0x140 + 424, 0); + w32(a, 0x140 + 428, ad.param); w32(a, 0x140 + 432, ad.param === 0xF800D8B4 ? 1 : 0); w32(a, 0x140 + 436, 0); + w32(a, 0x140 + 400, hot | optBits(x.opt) | ((opts.lang === 'en' || opts.lang === 'ko') ? 1 : 0) | (clk ? 2 : 0) | (x.sess === false ? NOSESS : 0)); + out.set(a, off); + out.fill(0xFF, T18_XIP_OFF, T18_XIP_OFF + T18_XIP_MAX); out.set(apps.t18.xip, T18_XIP_OFF); + if (hot & T18F_HOTWIN) { out.fill(0xFF, 0xFD0000, 0xFF0000); out.set(apps.t18.xip, T18_XIP_HOT); } + if (x.items) out.set(t18RomWriteGuest(out, x.fw, off)); + list.push({ src: xip(off), name, off }); + } else if (k === 't18') { + if (!t18XipOk(apps.t18)) throw new Error('T18Emu missing'); + if (u32(out, APP_OFF + 0x140) === T18_MAGIC || list.some((l) => u32(out, l.off + 0x140) === T18_MAGIC)) throw new Error('only one T18Emu'); + if (res.some(([a, b]) => a < T18_XIP_OFF + T18_XIP_MAX && b > T18_XIP_OFF) || !isFF(out, T18_XIP_OFF, T18_XIP_MAX)) throw new Error('T18Emu needs the area at 0x0F0000, the main program uses it: choose T18Emu in the Emulator tab'); + // T18Emu's own placement in a scratch copy where everything taken is not empty + const work = new Uint8Array(out); + for (const [a, b] of res) work.fill(0, Math.max(0, a), Math.min(work.length, b)); + const img = find(0x10000 + T18X_SAVE, 0x10000); + if (img < 0) throw noRoom(xi); + work.fill(0, img, img + 0x10000 + T18X_SAVE); + const r = t18Patch(work, x.fw, apps.t18, null, { lang: opts.lang, clock: clk, launch: true, extra: true, opt: x.opt, noResv: opts.noResv, nosess: x.sess === false }); + const w2 = r.rom, c = APP_OFF + 0x140; + const a = w2.slice(APP_OFF, APP_OFF + 0x10000); + w32(a, 0x140 + 8, img + 0x10000); // its own save area + const blocks = []; + for (let i = 0; i < 128; i++) { const b = w2[c + 16 + 2 * i] | (w2[c + 17 + 2 * i] << 8); if (b !== 0xFFFF) blocks.push(b); } + const ns = Math.min(u32(w2, c + 12), T18_SPARE_MAX); + for (let i = 0; i < ns; i++) blocks.push(w2[c + 272 + 2 * i] | (w2[c + 273 + 2 * i] << 8)); + for (const b of blocks) { out.set(w2.subarray(b << 16, (b + 1) << 16), b << 16); res.push([b << 16, (b + 1) << 16]); } + out.set(w2.subarray(T18_XIP_OFF, T18_XIP_OFF + T18_XIP_MAX), T18_XIP_OFF); res.push([T18_XIP_OFF, T18_XIP_OFF + T18_XIP_MAX]); + if (u32(w2, c + 400) & T18F_HOTWIN) { out.set(w2.subarray(0xFD0000, 0xFF0000), 0xFD0000); res.push([0xFD0000, 0xFF0000]); } + out.fill(0xFF, img + 0x10000, img + 0x10000 + T18X_SAVE); + out.set(a, img); + list.push({ src: xip(img), name, off: img }); + res.push([img, img + 0x10000 + T18X_SAVE]); top = Math.min(top, img); + } else throw new Error('unknown program'); + list[list.length - 1].xi = xi; left.delete(xi); + } + list.sort((a, b) => a.xi - b.xi); for (const l of list) delete l.xi; + // start device (1.6.8): the flash app as its own 64 KB image (menu entry DOWNLOAD) + let dl = 0; + if (opts.dlApp) { + if (opts.dlApp.length > 0x10000) throw new Error('flash app too big'); + const pl = place(0x10000, 0x10000), at = pl.at; + if (at < 0) throw noRoom(extras.length); + out.fill(0x00, at, at + 0x10000); out.set(opts.dlApp, at); + dl = xip(at); res.push([at, at + 0x10000]); if (!pl.hi) top = Math.min(top, at); + } + // test29: T18Emu gets more spares where there is room, also an installed one (they are only added behind its + // spares, so its save stays valid). With 6 the firmware's save filled them while growing up and its writes got lost. + if (opts.t18More !== false) for (const l of list) { + const c = l.off + 0x140; if (u32(out, c) !== T18_MAGIC) continue; + const ns = Math.min(u32(out, c + 12), T18_SPARE_MAX); if (ns >= T18_SPARE_GROW) continue; + const taken = (o) => res.some(([a, b]) => o < b && o + 0x10000 > a); + const cand = t18Free(out, !!opts.launch).filter((b) => !taken(b << 16) && !(SPARE_NO_RESCUE && RESCUE_RES && !opts.noResv && b === RESCUE_BLK)); // 1.7.2: never the rescue start's block + const add = Math.min(T18_SPARE_GROW - ns, cand.length - 4); + for (let i = 0; i < add; i++) { const b = cand[i]; out[c + 272 + 2 * (ns + i)] = b & 255; out[c + 273 + 2 * (ns + i)] = b >> 8; res.push([b << 16, (b + 1) << 16]); if (b < 0xF0) top = Math.min(top, b << 16); } + if (add > 0) w32(out, c + 12, ns + add); + } + // test17 ROOM_REAL: the room really left (empty 64 KB blocks a program may use), for the overview + let free = 0; for (let a = floor; a + 0x10000 <= ceil; a += 0x10000) if (fits(a, 0x10000)) free++; + if (opts.launch) for (let a = 0xF00000; a < hiEnd; a += 0x10000) if (fitsHi(a, 0x10000)) free++; + return { rom: out, list, low: top, dl, freeKB: free * 64 }; +} +/** Settings of an extra program at off: { kind, ... } or null */ +/* 1.7.2 test3 DOOM_FREE: DOOM as a program of the menu in a ROM without the Paradise. Its settings block (PDMC) holds + * the places of the WAD, the level data, the save and the program part; nothing is fixed any more. */ +const PDMC = 0x434D4450, DOOM_REGION = 0xA8000, DOOM_SAVE = 0x2000; +/* 1.7.3 test15 DOOM_PKREG: the DOOM program takes its packed-pointer windows from the level data, not from the WAD: the WAD + * may be anywhere and bigger than 8 MB (a whole DOOM.WAD as one entry). That needs more level data room: the lists of + * the whole WAD come first in it (x.region, set by the Studio). */ +const DOOM_PKREG = true; +/* 1.7.3 test17 DOOM_CMAP: a copy of the WAD's COLORMAP (8.5 KB) behind the save in the program part: the DOOM program reads it + * through its cached window instead of keeping it in RAM (that RAM goes to big maps like Sigil and DOOM II MAP29) */ +const DOOM_CMAP = true; +function doomCmap(mcu) { + const n = u32(mcu, 4), dir = u32(mcu, 8); + for (let i = 0; i < n && dir + 16 * i + 16 <= mcu.length; i++) { + let nm = ''; for (let k = 0; k < 8; k++) { const ch = mcu[dir + 16 * i + 8 + k]; if (!ch) break; nm += String.fromCharCode(ch); } + if (nm === 'COLORMAP') { const o = u32(mcu, dir + 16 * i), l = u32(mcu, dir + 16 * i + 4); return l >= 34 * 256 && o + l <= mcu.length ? mcu.subarray(o, o + 34 * 256) : null; } + } + return null; +} +function doomRegion(x) { return DOOM_PKREG && x && x.region ? x.region : DOOM_REGION; } +/* 1.7.3 test21 DOOM_LINK: DOOM entries in the menu share identical lumps (pictures, sounds, textures). A linked entry keeps + * its own directory, but such a lump points into the WAD of another entry (the engine reads a lump at WAD + filepos, any + * address in the flash works). Sigil then needs about its own size instead of its own copy of DOOM. Read back, a linked + * WAD is made whole again (doomUnlink) and linked anew when placed. */ +const DOOM_LINK = true, LINK_MIN = 0x40000; +function doomDir(m) { const n = u32(m, 4), d = u32(m, 8), r = []; for (let i = 0; i < n && d + 16 * i + 16 <= m.length; i++) { let nm = ''; for (let k = 0; k < 8; k++) { const ch = m[d + 16 * i + 8 + k]; if (!ch) break; nm += String.fromCharCode(ch); } r.push({ i, pos: u32(m, d + 16 * i) | 0, size: u32(m, d + 16 * i + 4), nm, at: d + 16 * i }); } return r; } +function lumpKey(m, pos, size) { let h = 0x811C9DC5; for (let k = 0; k < size; k += 7) h = Math.imul(h ^ m[pos + k], 16777619); return size + ':' + (h >>> 0); } +/** Linked WAD of mcu against bases [{ x, mcu }]: { mcu, refs: [[dirAt, base x, base pos]], saved } or null */ +function doomLinkOne(mcu, bases) { + const idx = new Map(); + for (const b of bases) for (const l of doomDir(b.mcu)) if (l.size >= 256 && l.pos >= 0 && l.pos + l.size <= b.mcu.length) { const k = lumpKey(b.mcu, l.pos, l.size); if (!idx.has(k)) idx.set(k, [b, l.pos]); } + const dir = doomDir(mcu), refs = [], keep = []; + let saved = 0; + for (const l of dir) { + let hit = null; + if (l.size >= 256 && l.pos >= 0 && l.pos + l.size <= mcu.length) { const h = idx.get(lumpKey(mcu, l.pos, l.size)); if (h) { const bm = h[0].mcu; let same = true; for (let k = 0; k < l.size && same; k++) same = bm[h[1] + k] === mcu[l.pos + k]; if (same) hit = h; } } + if (hit) { refs.push([l.i, hit[0].x, hit[1]]); saved += l.size; } else keep.push(l); + } + if (saved < LINK_MIN) return null; + let len = 12; const posOf = new Map(); + for (const l of keep) { if (!l.size) continue; len = (len + 3) & ~3; posOf.set(l.i, len); len += l.size; } + len = (len + 3) & ~3; const dirAt = len, out = new Uint8Array(dirAt + 16 * dir.length); + out.set(mcu.subarray(0, 4)); w32(out, 4, dir.length); w32(out, 8, dirAt); + for (const l of dir) { const o = dirAt + 16 * l.i; out.set(mcu.subarray(l.at, l.at + 16), o); if (posOf.has(l.i)) { out.set(mcu.subarray(l.pos, l.pos + l.size), posOf.get(l.i)); w32(out, o, posOf.get(l.i)); } else if (!l.size) w32(out, o, 0); } + return { mcu: out, refs: refs.map(([i, x, p]) => [dirAt + 16 * i, x, p]), saved }; +} +/** DOOM entries of one build: which ones are linked to which (the biggest ones are bases). Map x -> link */ +function doomLinks(extras) { + const ds = extras.filter((x) => extraKind(x) === 'doom' && x.mcu).sort((a, b) => b.mcu.length - a.mcu.length), bases = [], links = new Map(); + for (const x of ds) { const lk = bases.length ? doomLinkOne(x.mcu, bases) : null; if (lk) links.set(x, lk); else bases.push({ x, mcu: x.mcu }); } + return links; +} +/** A linked WAD read back from the ROM, whole again (lumps that point outside it are copied in) */ +function doomUnlink(rom, wad, mcu) { + const dir = doomDir(mcu); if (!dir.some((l) => l.size && (l.pos < 0 || l.pos + l.size > mcu.length))) return mcu; + const parts = []; let len = 12; + for (const l of dir) { if (!l.size) continue; const a = wad + l.pos; const src = l.pos >= 0 && l.pos + l.size <= mcu.length ? mcu.subarray(l.pos, l.pos + l.size) : a >= 0 && a + l.size <= rom.length ? rom.subarray(a, a + l.size) : new Uint8Array(l.size); len = (len + 3) & ~3; parts.push([l, len, src]); len += l.size; } + len = (len + 3) & ~3; const out = new Uint8Array(len + 16 * dir.length); + out.set(mcu.subarray(0, 4)); w32(out, 4, dir.length); w32(out, 8, len); + for (const l of dir) { out.set(mcu.subarray(l.at, l.at + 16), len + 16 * l.i); if (!l.size) w32(out, len + 16 * l.i, 0); } + for (const [l, p, src] of parts) { out.set(src, p); w32(out, len + 16 * l.i, p); } + return out; +} +function pdmcAt(rom, off) { for (let i = 0x140; i < 0x400; i += 4) if (u32(rom, off + i) === PDMC) return off + i; return -1; } +function doomCfg(rom, off) { + if (u32(rom, off + 0x140) !== PMXC) return null; + const c = pdmcAt(rom, off); if (c < 0) return null; + const wad = u32(rom, c + 8); let len = u32(rom, c + 12); + if (DOOM_LINK && wad >= 4 && wad <= rom.length) { const lw = u32(rom, wad - 4); if (lw && lw < len) len = lw; } // DOOM_LINK: c+12 may reach over the linked WADs + if (!len || wad < 4 || wad + len > rom.length) return null; + return { kind: 'doom', cfg: c, romOff: wad - 4, romLen: len + 4, regionOff: u32(rom, c + 16), regionLen: u32(rom, c + 20), saveOff: u32(rom, c + 24), codeOff: u32(rom, c + 28) }; +} +const DOOM_KEY_AT = { invert: 44, fire: 48, fwd: 52, back: 56, use: 60, mod: 64, run: 68 }; +function doomKeysOf(rom, c) { const r = {}; for (const [k, o] of Object.entries(DOOM_KEY_AT)) r[k] = k === 'run' || k === 'invert' ? !!u32(rom, c + o) : u32(rom, c + o); return r; } +function extraCfg(rom, off) { + const m = u32(rom, off + 0x140); + if (m === PMXC) { const d = doomCfg(rom, off); if (d) return d; } + if (m === T7_MAGIC) { const ro = u32(rom, off + 0x148), rl = u32(rom, off + 0x14C); return ro + rl <= rom.length ? { kind: 't7', romOff: ro, romLen: rl, saveOff: u32(rom, off + 0x150) } : null; } + if (m === T18_MAGIC) return Object.assign({ kind: 't18' }, t18Cfg(rom, off)); + if (m === GB_MAGIC) { const ro = u32(rom, off + 0x148), rl = u32(rom, off + 0x14C); return ro + rl <= rom.length ? { kind: 'gb', romOff: ro, romLen: rl, saveOff: u32(rom, off + 0x150) } : null; } + if (m === SMS_MAGIC) { const ro = u32(rom, off + 0x148), rl = u32(rom, off + 0x14C); return ro + rl <= rom.length ? { kind: 'sms', romOff: ro, romLen: rl, saveOff: u32(rom, off + 0x150) } : null; } + if (m === AB_MAGIC) { const ro = u32(rom, off + 0x148), rl = u32(rom, off + 0x14C); return ro + rl <= rom.length ? { kind: 'ab', romOff: ro, romLen: rl, saveOff: u32(rom, off + 0x150) } : null; } + if (m === PM_MAGIC) { const ro = u32(rom, off + 0x148), rl = u32(rom, off + 0x14C); return ro + rl <= rom.length ? { kind: 'pm', romOff: ro, romLen: rl, saveOff: u32(rom, off + 0x150) } : null; } + if (m === WOLF_MAGIC) { const ro = u32(rom, off + 0x148), rl = u32(rom, off + 0x14C); return ro + rl <= rom.length ? { kind: 'wolf', romOff: ro, romLen: rl, saveOff: u32(rom, off + 0x150) } : null; } + if (m === V1_MAGIC) { const ro = u32(rom, off + 0x148), rl = u32(rom, off + 0x14C); return ro + rl <= rom.length ? { kind: 'v1', romOff: ro, romLen: rl, saveOff: u32(rom, off + 0x150) } : null; } + if (m === PMXC && u32(rom, off + 0x144) >= 3) { + const gOff = u32(rom, off + 0x148), gLen = u32(rom, off + 0x14C), saveOff = u32(rom, off + 0x150), kind = u32(rom, off + 0x154); + const dev = Object.keys(DEVICES).find((d) => DEVICES[d].kind === kind); + return dev ? { kind: 'tama', dev, guestOff: gOff, guestSize: gLen, saveOff, map: rom.slice(off + 0x158, off + 0x1D8), spareEnd: u32(rom, off + 0x140 + 152), lzOff: u32(rom, off + 0x144) >= 5 ? u32(rom, off + 0x140 + 160) : 0 } : null; + } + return null; +} +/* test25 HI_ORPHAN: start device: blocks behind the Paradise's save (0xF00000..0xFEFFFF) that no program uses any more + * (left there by an earlier removal; they kept T18Emu from its fast window there) become free again. Used: what the + * program at 0x0A0000 reserves, the programs still listed (keep: their offsets) with all their parts, the menu (menuOff). */ +function hiFree(rom, keep, menuOff) { + const used = new Set(), mark = (a, b) => { for (let o = a & ~0xFFFF; o < b; o += 0x10000) used.add(o >>> 16); }; + for (const [a, b] of appReserved(rom)) mark(a, b); + mark(APP_OFF, APP_OFF + 0x10000); if (menuOff) mark(menuOff, menuOff + 0x10000); + const progs = (keep || []).slice(); if (u32(rom, APP_OFF + 0x140) !== 0xFFFFFFFF) progs.push(APP_OFF); // the program at 0x0A0000 with all its parts too + for (const off of progs) { + const c = extraCfg(rom, off); if (!c) { if (off === APP_OFF && !isFF(rom, APP_OFF + 0x140, 4) && u32(rom, APP_OFF + 0x140) !== T18_MAGIC) return rom; continue; } // unknown: leave everything + mark(off, off + 0x10000); + if (c.kind === 't18') { for (const b of c.map.concat(c.spare)) if (b !== 0xFFFF) used.add(b); mark(c.saveOff, c.saveOff + T18X_SAVE); if (c.flags & T18F_HOTWIN) mark(0xFD0000, 0xFF0000); } + else if (c.kind === 'tama') { mark(c.guestOff, c.spareEnd); mark(off, off + 0x10000 + TX_STATE); } + else if (c.kind === 't7') { mark(c.romOff, c.romOff + c.romLen); mark(c.saveOff, c.saveOff + 0x10000); mark(off, off + 0x20000); const tc = t7Cfg(rom, off); if (tc) for (const f of tc.figs) mark(f.off, f.off + f.len); } + else { mark(c.romOff, c.romOff + c.romLen); mark(c.saveOff, c.saveOff + 0x10000); mark(off, off + 0x20000); } + } + let out = rom; + for (let b = 0xF0; b < RESCUE_BLK; b++) if (!used.has(b) && !isFF(out, b << 16, 0x10000)) { if (out === rom) out = new Uint8Array(rom); out.fill(0xFF, b << 16, (b + 1) << 16); } + return out; +} +/** Free what the extra programs listed (from appsRead) use. */ +function appsClear(rom, old) { + const out = new Uint8Array(rom); + for (const x of old || []) { + const c = extraCfg(out, x.off); if (!c) continue; + if (c.kind === 't7') { let e = x.off + 0x20000 + ((c.romLen + 0xFFFF) & ~0xFFFF); const tc = t7Cfg(out, x.off); if (tc) for (const f of tc.figs) e = Math.max(e, (f.off + f.len + 0xFFF) & ~0xFFF); out.fill(0xFF, x.off, e); } + else if (c.kind === 'v1') { out.fill(0xFF, x.off, x.off + 0x12000); out.fill(0xFF, c.romOff, c.romOff + ((c.romLen + 0xFFF) & ~0xFFF)); } // 1.6.9: V3Emu has its ROM in front + else if (c.kind === 'gb' || c.kind === 'sms') { out.fill(0xFF, c.romOff, c.romOff + ((c.romLen + 0xFFFF) & ~0xFFFF)); out.fill(0xFF, x.off, x.off + 0x10000); out.fill(0xFF, c.saveOff, c.saveOff + (c.kind === 'gb' ? gbSaveLen(!!(u32(out, x.off + 0x140 + 20) & 8)) : 0x10000)); } // test3: may lie apart + else if (c.kind === 'ab') { out.fill(0xFF, c.romOff, c.romOff + 0x10000); out.fill(0xFF, x.off, x.off + 0x10000); } + else if (c.kind === 'pm') { out.fill(0xFF, c.romOff, c.romOff + ((c.romLen + 0xFFFF) & ~0xFFFF)); out.fill(0xFF, x.off, x.off + 0x10000); out.fill(0xFF, c.saveOff, c.saveOff + PM_SAVE); } + else if (c.kind === 'wolf') { out.fill(0xFF, c.romOff, c.saveOff + 0x10000); } + else if (c.kind === 'tama') { out.fill(0xFF, c.guestOff, c.spareEnd); out.fill(0xFF, x.off, x.off + 0x10000 + TX_STATE); } + else if (c.kind === 't18') { + for (const b of c.map.concat(c.spare)) if (b !== 0xFFFF) out.fill(0xFF, b << 16, (b + 1) << 16); + if (c.flags & T18F_HOTWIN) out.fill(0xFF, 0xFD0000, 0xFF0000); + out.fill(0xFF, T18_XIP_OFF, T18_XIP_OFF + T18_XIP_MAX); + out.fill(0xFF, x.off, x.off + 0x10000); if (c.saveOff === x.off + 0x10000) out.fill(0xFF, c.saveOff, c.saveOff + T18X_SAVE); + } + } + return out; +} +/** The extra programs of a ROM, from the menu's list ([{ src, name }]): the sources again, as appsPlace takes them. */ +function appsRead(rom, apps) { + const out = []; + for (const e of apps || []) { + const off = e.src - 0x10000000 + XIP_DEC; + if (off < 0 || off + 0x10000 > rom.length) continue; + const c = extraCfg(rom, off); if (!c) continue; + if (c.kind === 'doom') { out.push({ kind: 'doom', mcu: DOOM_LINK ? doomUnlink(rom, c.romOff + 4, rom.slice(c.romOff + 4, c.romOff + c.romLen)) : rom.slice(c.romOff + 4, c.romOff + c.romLen), keys: doomKeysOf(rom, c.cfg), save: rom.slice(c.saveOff, c.saveOff + DOOM_SAVE), name: e.name, off, saveOff: c.saveOff, region: DOOM_PKREG && c.regionLen > DOOM_REGION && c.regionLen <= 0x400000 ? c.regionLen : undefined }); continue; } + if (c.kind === 't7') { const tc = t7Cfg(rom, off); out.push({ rom: rom.slice(c.romOff, c.romOff + c.romLen), figs: tc ? tc.figs.map((f) => ({ name: f.name, data: rom.slice(f.off, f.off + f.len) })) : [], name: e.name, off, saveOff: c.saveOff, clock: !tc || !!(tc.flags & 2) }); } + else if (c.kind === 'v1') out.push({ kind: 'v1', rom: rom.slice(c.romOff, c.romOff + c.romLen), name: e.name, off, saveOff: c.saveOff, clock: (u32(rom, off + 0x140 + 20) & 16) ? !!(u32(rom, off + 0x140 + 20) & 2) : true }); // bit 4: the clock bit is meant (test26..28 lost it): else on + else if (c.kind === 'gb') { const fl = u32(rom, off + 0x140 + 20), st = rom.slice(c.romOff, c.romOff + c.romLen); + out.push({ kind: 'gb', rom: (fl & 4) ? gbUnpage(st, fl >>> 16) : gbUntrim(st, fl), name: e.name, off, saveOff: c.saveOff, keys: Array.from(rom.subarray(off + 0x140 + 40, off + 0x140 + 49)), inv: !!(fl & 2), save: rom.slice(c.saveOff, c.saveOff + gbSaveLen(!!(fl & 8))) }); } + else if (c.kind === 'sms') out.push({ kind: 'sms', rom: rom.slice(c.romOff, c.romOff + c.romLen), title: cfgName(rom, off + 0x140) || 'MASTER SYSTEM', gg: !!(u32(rom, off + 0x140 + 20) & 4), name: e.name, off, saveOff: c.saveOff, keys: Array.from(rom.subarray(off + 0x140 + 40, off + 0x140 + 49)), inv: !!(u32(rom, off + 0x140 + 20) & 2), save: rom.slice(c.saveOff, c.saveOff + 0x10000) }); + else if (c.kind === 'ab') out.push({ kind: 'ab', rom: rom.slice(c.romOff, c.romOff + c.romLen), title: cfgName(rom, off + 0x140) || 'ARDUBOY', name: e.name, off, saveOff: c.saveOff, keys: Array.from(rom.subarray(off + 0x140 + 40, off + 0x140 + 49)), inv: !!(u32(rom, off + 0x140 + 20) & 2), save: rom.slice(c.saveOff, c.saveOff + AB_SAVE) }); + else if (c.kind === 'pm') { const fl = u32(rom, off + 0x140 + 20), ks = []; for (let q = 0; q < 9; q++) ks.push(rom[off + 0x140 + 40 + 2 * q] | (rom[off + 0x140 + 41 + 2 * q] << 8)); out.push({ kind: 'pm', rom: rom.slice(c.romOff, c.romOff + c.romLen), title: cfgName(rom, off + 0x140) || 'POKEMON MINI', name: e.name, off, saveOff: c.saveOff, keys: ks, inv: !!(fl & 2), save: rom.slice(c.saveOff, c.saveOff + PM_BIOS_AT), bios: (fl & 4) ? rom.slice(c.saveOff + PM_BIOS_AT, c.saveOff + PM_BIOS_AT + 0x1000) : null }); } + else if (c.kind === 'wolf') out.push({ kind: 'wolf', pack: rom.slice(c.romOff, c.romOff + c.romLen), name: e.name, off, saveOff: c.saveOff, keys: wolfKeysRead(rom, off + 0x140), save: rom.slice(c.saveOff, c.saveOff + 0x10000) }); + else if (c.kind === 'tama') { + const g = new Uint8Array(DEVICES[c.dev].size).fill(0xFF); + for (let b = 0; b < (g.length >> 16); b++) { let k = c.map[b]; if (k === 0xFF) continue; if (k === 0xFE) k = b; g.set(rom.subarray(c.guestOff + (k << 16), c.guestOff + (k << 16) + 0x10000), b << 16); } + if (c.lzOff && c.lzOff + 512 <= rom.length) lzUnpack((a, n) => rom.subarray(c.lzOff + a, c.lzOff + a + n), g); // GUEST_LZ + guestPagesIn(rom, c, g); + const fl = u32(rom, off + 0x140 + 156); + out.push({ kind: 'tama', dev: c.dev, guest: g, name: e.name, off, saveOff: c.saveOff, clock: !!(fl & 2), nfc: !(fl & 4), opt: optOf(fl), pack: !!c.lzOff }); // test20 PACK_OPT + } else if (c.kind === 't18') { const fw = t18FromRom(rom, off); if (fw) out.push({ kind: 't18', fw, name: e.name, off, saveOff: c.saveOff, clock: !!(u32(rom, off + 0x140 + 400) & 2), opt: optOf(u32(rom, off + 0x140 + 400)) }); } + } + for (const x of out) { const fo = sessFlagsAt(rom, x.off, extraKind(x)); if (fo) x.sess = !(u32(rom, fo) & NOSESS); } // 1.7.3 test7 + return out; +} +/** Where a program's flags word lies (for NOSESS), 0: none. */ +function sessFlagsAt(rom, off, k) { + const c = off + 0x140; + if (k === 'tama') return c + 156; + if (k === 't18') return c + 400; + if (k === 't7') return c + 24 + T7_FIG_MAX * 24; + if (k === 'v1' || k === 'gb' || k === 'sms' || k === 'pm' || k === 'ab') return c + 20; + return 0; +} +/** Clock switch of all three emulators (1.5.1): at every start the guest clock is set to the Paradise's time, + * nothing is caught up (true), or the old way (false). null: no emulator, or a TamaEmu program too old. */ +function emuClockAt(rom) { + const m = u32(rom, APP_OFF + 0x140); + if (m === T18_MAGIC) return APP_OFF + 0x140 + 400; + if (m === T7_MAGIC) return APP_OFF + 0x140 + 24 + T7_FIG_MAX * 24; + if (m === PMXC && u32(rom, APP_OFF + 0x144) >= 4) return APP_OFF + 0x140 + 156; + return -1; +} +/** 1.7.3 test7: "remember where you left off" of the main program at 0x0A0000 (false: flags bit 12). null: none. */ +function emuSessAt(rom) { const a = emuClockAt(rom); return a >= 0 ? a : u32(rom, APP_OFF + 0x140) === V1_MAGIC ? APP_OFF + 0x140 + 20 : -1; } +function emuSessGet(rom) { const a = emuSessAt(rom); return a < 0 ? null : !(u32(rom, a) & NOSESS); } +function emuSessSet(rom, on) { const a = emuSessAt(rom); if (a < 0 || !(u32(rom, a) & NOSESS) === !!on) return rom; const out = new Uint8Array(rom); w32(out, a, (u32(out, a) & ~NOSESS) | (on ? 0 : NOSESS)); return out; } +/* 1.6.8: TamaEmu and T18Emu: volume (0 normal, 1 quiet, 2 loud, 3 off), brightness (0 100 %, 1 75, 2 50, 3 25 %), + * screen off after (0 like the toy, 1..7 = 10 s, 20 s, 30 s, 1, 2, 5, 10 min) in the flags, bits 16-17, 18-19, 20-22 */ +const OPT_MASK = 0xF7F0000; +const NOSESS = 0x1000; // 1.7.3 test7: flags bit 12 of the programs: no session on leaving, only the game's own save +// 1.6.8 (test45): dim = light step 0..10 (OPT_LV: 100, 5, 10, 20 .. 90 %), bits 24-27 = step + 1; 0 there = the old bits 18-19 +const OPT_LV = [100, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90], OPT_OLD = [0, 8, 6, 3]; +function optBits(o) { return o ? ((o.vol & 3) << 16) | (o.dim ? (((o.dim % 11) + 1) << 24) : 0) | ((o.off & 7) << 20) : 0; } +function optOf(f) { const n = (f >>> 24) & 15; return { vol: (f >> 16) & 3, dim: n && n <= 11 ? n - 1 : OPT_OLD[(f >> 18) & 3], off: (f >> 20) & 7 }; } +function emuOptGet(rom) { const m = u32(rom, APP_OFF + 0x140); if (m !== T18_MAGIC && m !== PMXC) return null; const a = emuClockAt(rom); return a < 0 ? null : optOf(u32(rom, a)); } +function emuOptSet(rom, o) { const m = u32(rom, APP_OFF + 0x140); if (m !== T18_MAGIC && m !== PMXC) return rom; const a = emuClockAt(rom); if (a < 0) return rom; const out = new Uint8Array(rom); w32(out, a, (u32(out, a) & ~OPT_MASK) | optBits(o)); return out; } +function emuClockGet(rom) { const a = emuClockAt(rom); return a < 0 ? null : !!(u32(rom, a) & 2); } +/** 4U/4U+ (1.6.8): NFC chip stand-in on (true, default) or off (flags bit 2). null without a 4U TamaEmu. */ +function emuNfcGet(rom) { if (u32(rom, APP_OFF + 0x140) !== PMXC || u32(rom, APP_OFF + 0x144) < 4) return null; const k = u32(rom, APP_OFF + 0x140 + 20); if (k !== 3 && k !== 4) return null; return !(u32(rom, APP_OFF + 0x140 + 156) & 4); } +function emuNfcSet(rom, on) { + if (emuNfcGet(rom) === null || emuNfcGet(rom) === !!on) return rom; + const out = new Uint8Array(rom), a = APP_OFF + 0x140 + 156; w32(out, a, (u32(out, a) & ~4) | (on ? 0 : 4)); return out; +} +function emuClockSet(rom, on) { + const a = emuClockAt(rom); if (a < 0 || !!(u32(rom, a) & 2) === !!on) return rom; + const out = new Uint8Array(rom); w32(out, a, (u32(out, a) & ~2) | (on ? 2 : 0)); return out; +} +/** Clock switch of T18Emu: at every start the Paradise's time (true) or the game time caught up (false). */ +function t18ClockGet(rom) { return u32(rom, APP_OFF + 0x140) === T18_MAGIC ? !!(u32(rom, APP_OFF + 0x140 + 400) & 2) : null; } +function t18ClockSet(rom, on) { + if (u32(rom, APP_OFF + 0x140) !== T18_MAGIC) return rom; + const out = new Uint8Array(rom), c = APP_OFF + 0x140 + 400; + w32(out, c, (u32(out, c) & ~2) | (on ? 2 : 0)); + return out; +} +/** Local time when writing to the device (first start without a clock note). */ +function t18Wall(rom, counter, date) { + if (u32(rom, APP_OFF + 0x140) !== T18_MAGIC) return rom; + const out = new Uint8Array(rom), c = APP_OFF + 0x140 + 416; + w32(out, c, counter >>> 0); + w32(out, c + 4, date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()); + w32(out, c + 8, (date.getFullYear() << 16) | ((date.getMonth() + 1) << 8) | date.getDate()); + return out; +} + +const EMU_APP_B64 = '__EMU_APP_B64__', EMU_STUB_B64 = '__EMU_STUB_B64__'; +/* MAIN_LZ: packing of the main TamaEmu as emuPatch does it (for room and hints in the Studio) */ +function packMain(g, dev, app, pack) { + let pk; try { pk = mainPick(g, dev, app || (embedded() || {}).app, pack); } catch (e) { pk = packGuest(g, dev, { lz: true }); } + return Object.assign({}, pk, { big: pk.big || GUEST_OFF + pk.blob.length + SPARE_MIN > GUEST_END }); +} +/* 1.7.3 test19 MAIN_RAW, test20: the main TamaEmu goes in unpacked unless "pack" is chosen (as in the menu). Unpacked it + * needs a few spare pages for the firmware's own writes: with fewer than 6 (a P's with its VDP set: 3) the Studio asks + * to pack it (e.needPack) instead of building a device that may hang. */ +/* 1.7.3 test21 MAIN_FEW: 6 spare pages were too few: items and download content need many more (a VDP set about 35). + * Unpacked a P's keeps 19, an iD L 31, a 4U+ 27. Below MAIN_FEW_MIN the Studio now packs only as many of the cold + * blocks as needed (those that pack best first), the rest stays unpacked. */ +const MAIN_RAW = true, MAIN_FEW = true, MAIN_RAW_MIN = MAIN_FEW ? 40 : 6; +function mainSpare(r) { + const big = r.big || GUEST_OFF + r.blob.length + SPARE_MIN > GUEST_END, gEnd = big ? BIG_END : GUEST_END, gOff = big ? BIG_OFF : GUEST_OFF; + const lo = (gOff + r.blob.length + 0x1FFF) & ~0x1FFF; + return Math.min(64, ((gEnd & ~0x1FFF) - (lo + 0x2000)) >> 13) - r.pages.length; +} +function mainPick(g, dev, app, pack) { + const lz = MAIN_LZ && !!app && tamaLzCan(app); + if (lz && pack) return packGuest(g, dev, { lz: true }); + let r; try { r = packGuest(g, dev, {}); } catch (e) { if (BIG_LZ && lz) return packGuest(g, dev, { lz: true }); throw e; } // BIG_LZ: only fits packed + if (lz && mainSpare(r) < MAIN_RAW_MIN) { + if (MAIN_FEW && LZ_WARM[dev]) { + const G = new Uint8Array(DEVICES[dev].size).fill(0xFF); G.set(g.subarray(0, Math.min(g.length, G.length))); + const cand = []; for (let b = 0; b < (G.length >> 16); b++) if (r.map[b] !== 0xFF && lzOk(dev, b)) cand.push({ b, z: lzPack(G, [b]).length }); + cand.sort((x, y) => x.z - y.z || x.b - y.b); + const only = []; + for (const c of cand) { only.push(c.b); const q = packGuest(g, dev, { lz: true, lzOnly: only.slice() }); if (mainSpare(q) >= MAIN_RAW_MIN) return Object.assign(q, { few: only.length }); } + } + throw Object.assign(new Error('unpacked this firmware leaves too few spare pages, pack it'), { needPack: true }); + } + return Object.assign(r, { raw: true }); +} +function embedded() { + if (EMU_APP_B64.startsWith('__')) return null; + return { app: b64(EMU_APP_B64), stub: b64(EMU_STUB_B64) }; +} + +root.ParamixEmu = { PACK_OPT, doomLinks, doomUnlink, DOOM_LINK, packMain, lzEnc, lzDec, lzPack, lzUnpack, tamaLzCan, GUEST_LZ, doomCfg, doomParts, gbTrim, gbUntrim, hiFree, t7Outdated, wolfSod, wolfSodEmbedded, smsEmbedded, smsDetect, smsGameGear, smsTitle, SMS_MAGIC, SMS_KEYS_DEFAULT, abEmbedded, abHex, abTitle, AB_MAGIC, AB_KEYS_DEFAULT, AB_SAVE, AB_MAX, pmEmbedded, pmDetect, pmTooBig, pmBiosDetect, pmTitle, PM_MAGIC, PM_KEYS_DEFAULT, PM_SAVE, PM_BIOS_AT, wolfEmbedded, wolfInfo, wolfPackOk, WOLF_MAGIC, WOLF_KEYS_DEFAULT, gbEmbedded, gbcEmbedded, gbIsColor, gbDetect, gbColorOnly, gbTitle, GB_MAGIC, GB_KEYS_DEFAULT, emuOptGet, emuOptSet, emuSessGet, emuSessSet, v1Embedded, v3Embedded, v3Detect, v1Detect, v1Name, v1Clock, v1Patch, v1FromRom, v1Upgrade, V1_MAGIC, installApp, dlcStores, dlcRoute, dlcAdd, dlcFree, dlcSlots, dlcRecord, dlcPut, dlcName, emuDetect, sceneTable, packGuest, emuPatch, emuUpgrade, emuRemove, t7Embedded, t7Detect, t7Kind, appsPlace, appsRead, appsClear, appReserved, extraKind, extraName, extraSize, extraCfg, t7XName, T7X_SAVE, APPX_MAX, t7FigDetect, t7FigData, t7FigName, t7Cfg, t7FromRom, t7Room, t7Patch, t7Upgrade, t7Wall, T7_MAGIC, t18Embedded, t18Detect, t18FromRom, t18Items, t18ItemAdd, t18ItemDel, t18ItemCount, t18RoomReset, t18Points, t18iScan, t18RomWriteGuest, T18_ADULTS, t18AdultFind, t18PicMake, t18PicsWrite, t18PicsRead, t18PicRgba, t18Addrs, t18Cfg, t18Free, t18Low, t18Patch, t18Upgrade, t18Wall, t18ClockGet, t18ClockSet, emuClockGet, emuClockSet, tamaName, emuNfcGet, emuNfcSet, T18_MAGIC, T18_XIP_OFF, T18_SAVE_LEN, OPT_LV, autoGet, autoGetOld, autoSet, STUB_OFF, installedOrigs, embedded, DEVICES, GUEST_OFF, BIG_OFF }; +if (typeof module !== 'undefined') module.exports = root.ParamixEmu; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/src/errors-ko.js b/src/errors-ko.js new file mode 100644 index 0000000..6794a22 --- /dev/null +++ b/src/errors-ko.js @@ -0,0 +1,86 @@ +const MSG_KO = [ + [/^no ARC2 archive at (\S+)$/, '$1에 ARC2 아카이브가 없습니다'], + [/^unknown bpp (\S+)$/, '알 수 없는 색상 깊이: $1'], + [/^subimage count does not match$/, '부분 이미지 개수가 다릅니다'], + [/^subimage size does not match$/, '부분 이미지 크기가 다릅니다'], + [/^eye image too detailed: (\d+) bytes, at most (\d+) allowed$/, '눈 이미지가 너무 큽니다: $1바이트, 최대 $2바이트'], + [/^not a Paradise flash dump \(SONIXDEV header missing\)$/, '파라다이스 덤프가 아닙니다(SONIXDEV 헤더 없음)'], + [/^unexpected asset archive \((\d+) files\)$/, '예상하지 못한 자료 구성(파일 $1개)'], + [/^too big: assets would end at (\S+), free space ends at (\S+)$/, '데이터가 $1까지 필요하지만 여유 공간은 $2까지입니다'], + [/^checksum wrong at (\S+)$/, '$1 체크섬 오류'], + [/^(?:character )?sheet must be (\S+) px, got (\S+)$/, '시트 크기는 $1px여야 합니다(현재 $2)'], + [/^no sprite package$/, '이미지 패키지가 없습니다'], + [/^not a ZIP file$/, 'ZIP 파일이 아닙니다'], + [/^unsupported ZIP compression in (.+)$/, '$1: 지원하지 않는 ZIP 압축 방식'], + [/^firmware not recognised \(expected a 4 MB or 8 MB image of a colour Tamagotchi\)$/, '컬러 다마고치의 4 MB 또는 8 MB 펌웨어가 필요합니다'], + [/^scene table not found$/, '장면 표를 찾지 못했습니다'], + [/^firmware too big: (\d+) blocks$/, '펌웨어가 너무 큽니다: $1블록'], + [/^no room for the spare pages$/, '여분 페이지를 넣을 공간이 없습니다'], + [/^launcher template does not fit$/, '실행 프로그램 형식이 맞지 않습니다'], + [/^the Paradise image must be 16 MB$/, '파라다이스 이미지 크기는 16 MB여야 합니다'], + [/^home screen not found$/, '홈 화면을 찾지 못했습니다'], + [/^area (\S+) is in use$/, '$1 영역이 사용 중입니다'], + [/^emulator program too big$/, '에뮬레이터 프로그램이 너무 큽니다'], + [/^program too big$/, '프로그램이 너무 큽니다'], + [/^settings block missing in the program$/, '프로그램의 설정 영역이 없습니다'], + [/^no emulator built in$/, '설치된 에뮬레이터가 없습니다'], + [/^no download content in the file$/, '파일에 다운로드 콘텐츠가 없습니다'], + [/^content checksum does not match$/, '콘텐츠 체크섬이 다릅니다'], + [/^this content fits no store of this firmware$/, '이 펌웨어에 맞는 콘텐츠 저장 영역이 없습니다'], + [/^content too big for its store$/, '콘텐츠가 저장 영역보다 큽니다'], + [/^only for the 8 MB firmware$/, '8 MB 펌웨어에서만 지원합니다'], + [/^no matching store$/, '맞는 저장 영역이 없습니다'], + [/^already added$/, '이미 추가했습니다'], + [/^(.+): all slots used, remove one first$/, '$1: 슬롯이 가득 찼습니다. 하나를 먼저 제거하세요'], + [/^no such slot$/, '해당 슬롯이 없습니다'], + [/^not a TG18 firmware \(8 MB\)$/, 'TG18 펌웨어(8 MB)가 아닙니다'], + [/^not enough room: the firmware needs (\d+) blocks of 64 KB, (\d+) are free$/, '64 KB 블록 $1개가 필요하지만 $2개만 비어 있습니다'], + [/^T18Emu program incomplete \(flash part missing\)$/, 'T18Emu 프로그램이 불완전합니다(플래시 부분 없음)'], + [/^the menu is already built in$/, '본체 메뉴가 이미 설치되어 있습니다'], + [/^more fields need a Tropical, Glacier or Jade Forest ROM with the original firmware$/, '지역 확장에는 원본 펌웨어의 트로피컬·글레이셔·제이드 포레스트 ROM이 필요합니다'], + [/^rain pictures too big$/, '비 이미지가 너무 큽니다'], + [/^unexpected Jade Forest data$/, '예상하지 못한 제이드 포레스트 데이터'], + [/^helper page full$/, '보조 페이지가 가득 찼습니다'], + [/^table (\S+) missing$/, '$1 표가 없습니다'], + [/^the second ROM must be a Land, Water or Sky ROM$/, '두 번째 파일은 랜드·워터·스카이 ROM이어야 합니다'], + [/^six fields program missing$/, '여섯 지역 프로그램이 없습니다'], + [/^unexpected map picture$/, '예상하지 못한 지역 이미지'], + [/^unexpected Land picture (\d+)$/, '예상하지 못한 랜드 이미지 $1'], + [/^composite table full$/, '합성 이미지 표가 가득 찼습니다'], + [/^menu program too old for six fields$/, '여섯 지역을 지원하지 않는 구버전 메뉴입니다'], + [/^edition not recognised$/, '에디션을 인식하지 못했습니다'], + [/^nothing chosen$/, '선택한 내용이 없습니다'], + [/^no room for the launcher$/, '실행 프로그램을 넣을 공간이 없습니다'], + [/^no room for the menu next to DOOM$/, 'DOOM과 함께 메뉴를 넣을 공간이 없습니다'], + [/^no room for the saves next to DOOM$/, 'DOOM과 함께 저장 데이터를 넣을 공간이 없습니다'], + [/^menu program too big$/, '본체 메뉴가 허용 용량을 초과합니다'], + [/^the area for the menu is in use$/, '메뉴 영역이 사용 중입니다'], + [/^no room for the saves$/, '저장 데이터를 넣을 공간이 없습니다'], + [/^the area for the saves is in use$/, '저장 영역이 사용 중입니다'], + [/^settings block of the menu missing$/, '메뉴의 설정 영역이 없습니다'], + [/^the stored save of (.+) does not fit here$/, '$1의 저장이 이 영역에 맞지 않습니다'], + [/^not a WAD file$/, 'WAD 파일이 아닙니다'], + [/^no DOOM maps in the WAD \(DOOM 2 is not supported\)$/, 'WAD에 DOOM 지도가 없습니다(이 구성에서는 DOOM 2 미지원)'], + [/^no picture$/, '이미지가 없습니다'], + [/^broken$/, '손상된 데이터입니다'], + [/^WAD conversion failed$/, 'WAD 변환 실패'], + [/^the character data reaches (\S+), DOOM needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. DOOM은 0x830000 이후가 필요합니다'], + [/^DOOM program too big$/, 'DOOM 프로그램이 너무 큽니다'], + [/^WAD too big: (\d+) KB, room (\d+) KB \(try without music\)$/, 'WAD $1 KB, 여유 공간 $2 KB. 음악을 끄고 시도하세요'], + [/^this DOOM has no key layout of its own yet$/, '이 DOOM은 개별 버튼 설정을 지원하지 않습니다'], + [/^fire, forward and back need three different buttons$/, '발사·전진·후진은 서로 다른 버튼이어야 합니다'], + [/^use needs its own button or the wheel$/, '사용은 별도의 버튼 또는 휠이어야 합니다'], + [/^no room for the field saves next to this emulator firmware$/, '이 펌웨어와 함께 지역 저장을 넣을 공간이 없습니다'], + [/^the character data reaches (\S+), the emulator needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. 에뮬레이터는 0x830000 이후가 필요합니다'], + [/^the stored saves do not fit into the room for the fields$/, '보관한 저장이 지역 저장 공간을 초과합니다'], + [/^unexpected planet table in the Land ROM$/, '랜드 ROM의 행성 표가 예상과 다릅니다'], + [/^not a Paradise save \(\.tamasave\)$/, '파라다이스 저장(.tamasave)이 아닙니다'], + [/^unknown save version (\S+)$/, '알 수 없는 저장 버전: $1'], + [/^save is cut off$/, '저장 데이터가 잘렸습니다'], + [/^no room for (.+) \((\d+) KB\)$/, '$1을 넣을 공간이 없습니다($2 KB)'], + [/^no room for (.+)$/, '$1을 넣을 공간이 없습니다'], + [/^only one T18Emu$/, 'T18Emu는 하나만 추가할 수 있습니다'], + [/^T18Emu needs the area at 0x0F0000, the main program uses it: choose T18Emu in the Emulator tab$/, 'T18Emu가 필요한 0x0F0000 영역을 주 프로그램이 사용합니다. 에뮬레이터 탭에서 T18Emu를 선택하세요'], + [/^(.+): only in a start device$/, '$1: 실행 전용 구성에서만 가능합니다'], + [/^too many scenes$/, '장면이 너무 많습니다'] +]; diff --git a/src/feld.js b/src/feld.js new file mode 100644 index 0000000..e1e46fd --- /dev/null +++ b/src/feld.js @@ -0,0 +1,963 @@ +/* + * Paramix Studio: Paramix menu in the ROM (field switch, items, Tamapoints). + * + * A small program in the ROM, launched like the emulator and DOOM through the stub + * (hold A and C on the home screen). It can + * - switch the field (Land/Water/Sky or Tropical/Glacier), each field with + * its own save, which is packed into a slot when switching, + * - put items into the bag and set Tamapoints (as in the TamaParadise app), + * - launch an installed program (DOOM, TamaEmu). + * Anything that depends on the edition lives in the program's settings block and is + * set here (profiles below, measured on the factory images). + * + * Location in flash: + * without DOOM: program and catalog from 0x0B1000, slots behind the character data + * with DOOM: program, catalog and slots in the free end of the DOOM program region + */ +(function (root) { +'use strict'; + +const XIP_DEC = 0x11000; +const xip = (off) => 0x10000000 + off - XIP_DEC; +const APP_OFF = 0xA0000, STUB_OFF = 0xB0000, FELD_OFF = 0xB1000, FELD_END = 0xC0000; +const DOOM_CODE = 0xB1000, DOOM_SAVE = 0x10E000; +const SLOT_BASE = 0x830000, SLOT_SIZE = 0x58000, GUEST_OFF = 0x940000; +const FELD_MAGIC = 0x444C4546, SLOT_MAGIC = 0x544C5346, CAT_MAGIC = 0x54414350, PMXC = 0x43584D50, PDMC = 0x434D4450; +const PH_APP = 0x1234ABCD, PH_FELD = 0x6789EF01, PH_AUTO = 0x66666661, PH_ORIG = [0x22222221, 0x33333331, 0x44444441, 0x55555551]; +const HOOK_OFF = [0x40, 0x46, 0x4C, 0x52]; +const F_FIELDS = 1, F_BAG = 2, F_TAMA = 4, F_SAVES = 8, F_LAUNCH = 16; +/* GPLAY (1.7.2 test14): play time in DOOM, Wolfenstein, Game Boy and Master System earns Tamapoints (the programs read + * this flag from the menu's settings block, see emu/src/emu/gplay.h). Only in a ROM with the Paradise. */ +const F_GPLAY = 64, GPLAY = true; +/* + * Launcher ROM (1.6.8): the handlers of every scene after the setup point to the stub's launch entry + * (+0x20), so the menu comes up instead of the game. The setup scenes below stay. The original handlers + * are kept in the stub page at +0x400 ("PLNC", count, then per scene: table offset, four handlers). + */ +const LAUNCH_ENTRY = 0x20, LREC_OFF = 0x400, LREC_MAGIC = 0x434E4C50; +// Only the game's own scenes (home, care, events, lab, shop, space); the setup and everything not clearly part of the +// game stay (also SETTING_*: the clock after "continue" may use it). Measured in the Paradise emulator (1.6.8): the four +// handlers 8 bytes behind a scene's name belong to the NEXT scene of the table (the setup runs, in this naming, +// OSEWAGAME_03, STARTUP, CORRECTTIME, LANGUAGE, DATETIME, BIRTHDAY, i.e. really STARTUP, INITIAL_LOGO, LANGUAGE, +// DATETIME, BIRTHDAY, PLANETNAME). So scene N is redirected in the entry of the scene before it. +const LAUNCH_SCENE = /^PSID_(HOME|HOME_\w+|OSEWA_\w+|CELL_STATUS|LABOMENU\w*|LBMENU_\w+|INFO_\w+|SHOP_\w+|BOOK_\w+|HELP_\w+|EVENT_\w+|LABOGAME_\w+|OSEWAGAME_\w+|TAMASPACE_\w+)$/; +const isHandler = (v) => v >= 0x10000000 && v < 0x10100000 && (v & 1) === 1; +/* + * Per redirected scene a block of 52 bytes in the trampoline pages (behind the menu program): table offset, the four + * original handlers, then four trampolines "ldr.w r12, ; b.w ". The stub starts the menu only + * once the Paradise has a save, otherwise it jumps to r12 (the original), so a setup after a reset finishes normally. + * The stub page holds at +0x400: "PLNC", count, offset of the trampoline pages. + */ +const LCHECK_ENTRY = 0x2C, TBLK = 52; +function launchScenes(tab) { + const ent = Object.entries(tab).sort((x, y) => x[1] - y[1]), r = []; + for (let i = 1; i < ent.length; i++) if (LAUNCH_SCENE.test(ent[i][0])) r.push(ent[i - 1][1]); + return r; +} +function launchSize(out, tab) { return page(TBLK * launchScenes(tab).filter((o) => [0, 1, 2, 3].every((k) => isHandler(u32(out, o + 12 + 4 * k)))).length); } +/** Thumb-2 b.w from address `from` to `to` (both in the XIP window): two halfwords */ +function bw(from, to) { + const off = to - (from + 4), S = off < 0 ? 1 : 0, imm = off >>> 1; + const imm11 = imm & 0x7FF, imm10 = (imm >>> 11) & 0x3FF, I2 = (imm >>> 21) & 1, I1 = (imm >>> 22) & 1; + const J1 = (~I1 ^ S) & 1, J2 = (~I2 ^ S) & 1; + return [0xF000 | (S << 10) | imm10, 0x9000 | (J1 << 13) | (J2 << 11) | imm11]; +} +function launchRedirect(out, tab, stubOff, tOff) { + const list = launchScenes(tab).filter((o) => [0, 1, 2, 3].every((k) => isHandler(u32(out, o + 12 + 4 * k)))); + if (list.length > 200) throw new Error('too many scenes'); + out.fill(0xFF, tOff, tOff + page(TBLK * list.length)); + list.forEach((o, i) => { + const b = tOff + TBLK * i; + w32(out, b, o); + for (let k = 0; k < 4; k++) { + w32(out, b + 4 + 4 * k, u32(out, o + 12 + 4 * k)); + const t = b + 20 + 8 * k, lit = b + 4 + 4 * k, imm = ((t + 4) & ~3) - lit; // literal behind: ldr.w r12, [pc, #-imm] + w16(out, t, 0xF85F); w16(out, t + 2, 0xC000 | imm); + const [h1, h2] = bw(xip(t + 4), xip(stubOff) + LCHECK_ENTRY); w16(out, t + 4, h1); w16(out, t + 6, h2); + w32(out, o + 12 + 4 * k, xip(t) | 1); + } + }); + const at = stubOff + LREC_OFF; + out.fill(0xFF, at, stubOff + 0x1000); + w32(out, at, LREC_MAGIC); w32(out, at + 4, list.length); w32(out, at + 8, tOff); +} +/** Undo launchRedirect (the record in the stub page and the trampoline pages). */ +function launchRestore(out, stubOff) { + const at = stubOff + LREC_OFF; + if (u32(out, at) !== LREC_MAGIC) return false; + const n = Math.min(u32(out, at + 4), 200), tOff = u32(out, at + 8); + if (tOff < 0x90000 || tOff + TBLK * n > 0x110000) return false; + for (let i = 0; i < n; i++) { const b = tOff + TBLK * i, o = u32(out, b); for (let k = 0; k < 4; k++) w32(out, o + 12 + 4 * k, u32(out, b + 4 + 4 * k)); } + out.fill(0xFF, tOff, tOff + page(TBLK * n)); + out.fill(0xFF, at, at + 12); + return true; +} +/** Is the ROM a launcher ROM (menu with the launch flag)? */ +function isLaunch(rom, tpl) { const f = feldFind(rom, tpl); return !!f && f.version >= 2 && (f.flags & F_LAUNCH) !== 0; } +// Six fields (six.js): helper page at 0x10F000, set byte in the settings block +const SIX_OFF = 0x10F000, SIX_MAGIC = 0x31584953, SIX_FLAG = 0xF04, CODE_END = 0x10F000; +const isSix = (rom) => rom.length > SIX_OFF + 4 && u32(rom, SIX_OFF) === SIX_MAGIC; +/* 1.7.2: lab games per start field (six fields version 7): a fresh field from the menu gets its game family + in the settings byte 0xF05 (0 Tropical/Glacier, 1 Land/Water/Sky, 2 Forest = Jade Forest). Switching the + field in the game leaves the byte alone. */ +const FELD_GAMES = true, SIX_GAMES_FAM = 0xF05; +const sixGames = (rom) => FELD_GAMES && isSix(rom) && u32(rom, SIX_OFF + 4) >= 7 && (u32(rom, SIX_OFF + 32) & 4) === 4; + +const rgb = (r, g, b) => ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); +/* + * Editions. ID page: word 0 = ID, footer u16 h0, u16 h1, C minus ID, + * inverse. Factory settings (0xEFE000/0xEFF000): zeros and these bytes, plus the + * checksum, which the program computes itself. Bag and money as in the app. + */ +const PROFILES = [ + { name: 'gen1', idPage: 0xD49000, edIds: [1, 2, 3], ids: [1, 2, 3], names: ['LAND', 'WATER', 'SKY'], h: [1, 4], c: 0x70169E2C, + cols: [rgb(80, 200, 60), rgb(40, 120, 255), rgb(120, 210, 255)], fieldByte: 439, + common: [[8, 0x11], [16, 0xc0], [17, 0xa8], [168, 1], [576, 0x3f], [577, 0x1f], [1856, 1]], + field: [[[4, 0x0c], [170, 2], [439, 0]], [[4, 4], [170, 1], [439, 1]], [[4, 4], [170, 1], [439, 2]]], + bag: [0xb4, 0x240, 0x740], tama: 0x104, level: 0x7C }, + // Jade Forest: one ID (4), three fields in the save (byte 443): LAND, WATER, FOREST (texts 14 to 16 in the ROM). + // 1.6.9: the block has 4 bytes more from about 0xf8 on (the firmware's offsets from 0x114 are 4 higher than Land's): + // the bag list is at 0x244 and its amounts at 0x744 (count getter LDR [r0,#0x740] from block + 4), the money stays at 0xb4 + { name: 'jade', idPage: 0xD49000, edIds: [4], ids: [0, 0, 0], names: ['LAND', 'WATER', 'FOREST'], h: [2, 0], c: 0x849633DB, + cols: [rgb(80, 200, 60), rgb(40, 120, 255), rgb(60, 190, 110)], fieldByte: 443, + common: [[4, 4], [8, 17], [16, 192], [17, 168], [168, 1], [170, 3], [580, 63], [581, 31], [1860, 1]], + field: [[[443, 0]], [[443, 1]], [[443, 2]]], bag: [0xb4, 0x244, 0x744], tama: 0x108, level: 0x7C }, + // Tropical and Glacier: same firmware, three fields (byte 499): TROPICAL, ICE (Glacier), FOREST + { name: 'gen3', idPage: 0xD29000, edIds: [5, 6], ids: [5, 6, 0], names: ['TROPICAL', 'GLACIER', 'FOREST'], h: [3, 1], c: 0x96CB83B8, + cols: [rgb(255, 150, 60), rgb(150, 220, 255), rgb(60, 190, 110)], fieldByte: 499, + common: [[4, 4], [8, 17], [12, 109], [13, 1], [16, 192], [17, 168], [180, 1], [182, 1], [624, 62], [625, 31], [1904, 1]], + field: [[[499, 0]], [[499, 1]], [[499, 2]]], bag: [0xc0, 0x270, 0x770], tama: 0x114, level: 0x88 }, +]; +const NAMES = { 1: 'Land', 2: 'Water', 3: 'Sky', 4: 'Jade Forest', 5: 'Tropical', 6: 'Glacier' }; +/* Tropical/Glacier with six fields: the second three are slots 0..2 with the set byte 1. */ +function profileOf(rom, p) { + if (!isSix(rom)) return p; + const g = PROFILES[0]; + if (p.name === 'gen3') { + const fam = sixGames(rom) ? [0, 0, 2, 1, 1, 1] : null, field = p.field.concat(p.field.map((f) => f.concat([[SIX_FLAG, 1]]))); + return Object.assign({}, p, { + ids: p.ids.concat(p.ids), names: p.names.concat(g.names), cols: p.cols.concat(g.cols), + field: fam ? field.map((f, i) => f.concat([[SIX_GAMES_FAM, fam[i]]])) : field, six: SIX_FLAG, sixMap: [0, 1, 2, 255, 3, 4, 5, 255], + }); + } + // Jade Forest: Sky is slot 1 (Water) with the set byte + if (p.name === 'jade') return Object.assign({}, p, { + ids: p.ids.concat([0]), names: p.names.concat(['SKY']), cols: p.cols.concat([g.cols[2]]), + field: p.field.concat([[[p.fieldByte, 1], [SIX_FLAG, 1]]]), six: SIX_FLAG, sixMap: [0, 1, 2, 255, 0, 3, 2, 255], + }); + return p; +} +const cap = (s) => s.charAt(0) + s.slice(1).toLowerCase(); + +const u16 = (b, o) => b[o] | (b[o + 1] << 8); +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; } +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } +function isFF(b, a, n) { for (let i = a; i < a + n; i++) if (b[i] !== 0xFF) return false; return true; } +const page = (n) => (n + 0xFFF) & ~0xFFF; +function b64(s) { + if (typeof atob === 'function') { const t = atob(s); const o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; } + return new Uint8Array(Buffer.from(s, 'base64')); +} +function findWord(b, v, from = 0, to = b.length) { for (let i = from; i + 4 <= to; i += 2) if (u32(b, i) === v) return i; return -1; } + +/** Edition of the ROM: { profile, id } or null. */ +function edition(rom) { + // 1.7.3 test11: the ID page with a fitting footer first, Tropical/Glacier before Land (a Glacier was read as Land: + // at 0xD49000 it has save data whose first word can be 1..6); without a footer the first word as before + // 1.7.3 test13: a clean ROM keeps its ID page at CLEAN_ID (top, so 0xD49000 does not split the room for programs) + for (const at of [null, CLEAN_ID]) for (const p of PROFILES.slice().reverse()) { + const a = at || p.idPage; if (a + 0x1000 > rom.length) continue; + const id = u32(rom, a), k = u32(rom, a + 0xFF8); + if (p.edIds.includes(id) && ((k + id) >>> 0) === p.c && u32(rom, a + 0xFFC) === (~k >>> 0)) return { profile: p, id, at: a }; + } + for (const p of PROFILES) { + const id = u32(rom, p.idPage); + if (p.edIds.includes(id)) return { profile: p, id, at: p.idPage }; + } + return null; +} +/** Family of an edition ID (same firmware, only the active field differs): 'gen1' (Land, Water, Sky), 'jade', 'gen3'. */ +function familyOf(id) { const p = PROFILES.find((q) => q.edIds.includes(id)); return p ? p.name : null; } +/** Edition ID (1 Land ... 6 Glacier) or 0. */ +function feldId(rom) { const e = edition(rom); return e ? e.id : 0; } +/** Does this ROM support the field switch? (every recognized edition has three fields) */ +function canFields(rom) { return !!edition(rom); } +/** The fields of this ROM (names). */ +function fieldNames(rom) { const e = edition(rom); return e ? profileOf(rom, e.profile).names.map(cap) : []; } +/** Active field (name), read from the save. */ +function fieldNow(rom) { + const e = edition(rom); if (!e) return ''; + const P = profileOf(rom, e.profile); + let f = rom[0xEFE000 + P.fieldByte]; + if (P.six && f < 4) f = P.sixMap[(rom[0xEFE000 + P.six] === 1 ? 4 : 0) + f]; + return f < P.names.length ? cap(P.names[f]) : NAMES[e.id]; +} + +/** Program in the ROM: 0 none, 1 DOOM, 2 emulator (TamaEmu, T7Emu or T18Emu, see emuType). */ +function appKind(rom) { + if (u32(rom, APP_OFF + 0x140) === 0x37584D50) return 2; // "PMX7": T7Emu + if (u32(rom, APP_OFF + 0x140) === 0x38584D50) return 2; // "PMX8": T18Emu + if (u32(rom, APP_OFF + 0x140) === 0x31584D50) return 2; // "PMX1": V1Emu (1.6.8) + if (u32(rom, APP_OFF + 0x140) !== PMXC) return 0; + for (let i = 0x140; i < 0x400; i += 4) if (u32(rom, APP_OFF + i) === PDMC) return 1; + return 2; +} + +/* + * Where is the stub? Normally at 0x0B0000 (shared with the emulator and DOOM). + * In editions whose firmware code still occupies that spot (Tropical, Glacier), + * right after the code in the first free region below 0x110000. + */ +function freeStubOff(rom) { + if (isFF(rom, STUB_OFF, 0x2000)) return STUB_OFF; + let p = 0x10F000; + while (p > 0x90000 && isFF(rom, p - 0x1000, 0x1000)) p -= 0x1000; + return p; +} +function feldAt(rom, stubOff, ph) { + const v = u32(rom, stubOff + ph); + if (v < 0x10000000 || v >= 0x11000000) return null; + const off = v - 0x10000000 + XIP_DEC; + const c = off + 0x140; + if (off + 0x200 > rom.length || u32(rom, c) !== FELD_MAGIC) return null; + const version = u32(rom, c + 4); + const f = { off, stubOff, version, slotOff: u32(rom, c + 8), slotSize: u32(rom, c + 12), nslots: u32(rom, c + 16), flags: F_FIELDS, catOff: 0, catN: 0 }; + if (version >= 2) { f.flags = u32(rom, c + 36); f.catOff = u32(rom, c + 272); f.catN = u32(rom, c + 276); } + f.slotOff2 = version >= 4 ? u32(rom, c + 364) : 0; f.slotN1 = version >= 4 ? u32(rom, c + 368) : 0; + return f; +} +/** Flash address of slot i (from menu version 4 the slots can lie in two regions). */ +function slotAddr(f, i) { return f.slotOff2 && f.slotN1 && i >= f.slotN1 ? f.slotOff2 + (i - f.slotN1) * f.slotSize : f.slotOff + i * f.slotSize; } +/** Is the menu installed? Returns { off, stubOff, version, slotOff, slotSize, nslots, flags, catOff, catN } or null. */ +function feldFind(rom, tpl) { + const ph0 = findWord(tpl, PH_FELD); + if (ph0 < 0) return null; + // older stubs: menu address at 0xF0 (up to 1.2.6), 0x118 (1.2.7) and 0x148 (1.6.0 to 1.6.7) + for (const ph of [...new Set([ph0, 0xF0, 0x118, 0x148])]) { + const f = feldAt(rom, STUB_OFF, ph); + if (f) return f; + for (let p = 0x90000; p < 0x110000; p += 0x1000) { const g = p !== STUB_OFF && feldAt(rom, p, ph); if (g) return g; } + } + return null; +} + +/** More programs of the menu (version 5): { name0, apps: [{ src, name }] } (empty without). */ +function feldApps(rom, tpl) { + const f = feldFind(rom, tpl), r = { name0: '', apps: [] }; + if (!f || f.version < 5) return r; + const c = f.off + 0x140, str = (o) => { let t = ''; for (let k = 0; k < 12 && rom[o + k]; k++) t += String.fromCharCode(rom[o + k]); return t; }; + r.name0 = str(c + 380); + const n = Math.min(u32(rom, c + 392), f.version >= 8 ? 12 : 6); + for (let i = 0; i < n; i++) { const o = i < 6 ? c + 396 + 16 * i : c + 504 + 16 * (i - 6); r.apps.push({ src: u32(rom, o), name: str(o + 4) }); } + // 1.6.9 test13 (version 9): main program of the start device out of the list, start when switched on + if (f.version >= 9) { r.v9 = true; r.mainSrc = u32(rom, c + 600); r.auto = (u32(rom, c + 604) & 1) === 1; r.noClock = (u32(rom, c + 604) & 2) === 2; } // 1.7.3 test7: clean ROM, clock not asked at the start + if (f.version >= 7) r.dl = u32(rom, c + 500); // test20: the flash app of the start device (DOWNLOAD) + return r; +} +/** Saved slots (raw bytes) of a ROM with the menu, for moving them over. */ +/* + * Saved fields and the shared pool (1.2.12). The header page of field i sits at the start + * of its slot. Older menus put the packed data right after it; from 1.2.12 the header says + * "POOL" (word 5) and lists the pool pages (word 6 = count, u16 list at 2032). The pool is + * every slot page except the header pages, numbered slot by slot. + */ +const POOL_MAGIC = 0x4C4F4F50, DPG_OFF = 2032, DPG_MAX = 1024; +function poolPages(f) { return f.slotSize / 0x1000 - 1; } +function poolAddr(f, k) { const n = poolPages(f); return slotAddr(f, Math.floor(k / n)) + (k % n + 1) * 0x1000; } +/** Read slot i with read(addr, len) (sync, or async with slotReadAsync). { head, field, bytes, stream } or null. */ +function slotParse(f, i, head) { + if (u32(head, 0) !== SLOT_MAGIC) return null; + const field = u32(head, 4), bytes = u32(head, 12); + if (field < 1 || field > 6 || u32(head, 8) > 500) return null; + const pool = u32(head, 20) === POOL_MAGIC, nd = pool ? u32(head, 24) : 0, np = f.nslots * poolPages(f), list = []; + if (pool) { + if (nd > DPG_MAX || bytes > nd * 0x1000) return null; + for (let k = 0; k < nd; k++) { const x = head[DPG_OFF + 2 * k] | (head[DPG_OFF + 2 * k + 1] << 8); if (x >= np) return null; list.push(poolAddr(f, x)); } + } else if (bytes > f.slotSize - 0x1000) return null; + return { head, field, bytes, pool, list, b: slotAddr(f, i) }; +} +function slotFill(p, chunk, k) { p.stream.set(chunk.subarray(0, Math.min(chunk.length, p.bytes - k * 0x1000)), k * 0x1000); } +function slotRead(rom, f, i) { + const p = slotParse(f, i, rom.subarray(slotAddr(f, i), slotAddr(f, i) + 0x1000)); + if (!p) return null; + p.stream = new Uint8Array(p.bytes); + if (p.pool) p.list.forEach((a, k) => slotFill(p, rom.subarray(a, a + 0x1000), k)); + else p.stream.set(rom.subarray(p.b + 0x1000, p.b + 0x1000 + p.bytes)); + return p; +} +async function slotReadAsync(read, f, i) { + const p = slotParse(f, i, new Uint8Array(await read(slotAddr(f, i), 0x1000))); + if (!p) return null; + p.stream = new Uint8Array(p.bytes); + if (p.pool) for (let k = 0; k < p.list.length; k++) slotFill(p, await read(p.list[k], 0x1000), k); + else p.stream.set((await read(p.b + 0x1000, (p.bytes + 0xFFF) & ~0xFFF)).subarray(0, p.bytes)); + return p; +} +/** + * Write a saved field into slot i of image out (pool format). used: Set of pool pages taken + * by fields already placed. Returns the written addresses; throws if the pool is full. + */ +function slotPlace(out, f, i, s, used) { + const n = f.nslots * poolPages(f), nd = Math.ceil(s.bytes / 0x1000), pages = [], own = i * poolPages(f); + for (let r = 0; r < n && pages.length < nd; r++) { const x = (own + r) % n; if (!used.has(x)) { used.add(x); pages.push(x); } } + if (pages.length < nd || nd > DPG_MAX) throw new Error('the stored saves do not fit into the room for the fields'); + const h = new Uint8Array(0x1000).fill(0xFF); + h.set(s.head.subarray(0, DPG_OFF)); + w32(h, 4, i + 1); w32(h, 20, POOL_MAGIC); w32(h, 24, nd); w32(h, 28, 0); + pages.forEach((x, k) => { h[DPG_OFF + 2 * k] = x & 255; h[DPG_OFF + 2 * k + 1] = x >> 8; }); + const b = slotAddr(f, i), written = [b]; + out.set(h, b); + pages.forEach((x, k) => { const a = poolAddr(f, x), pg = new Uint8Array(0x1000).fill(0xFF); + pg.set(s.stream.subarray(k * 0x1000, Math.min(s.bytes, (k + 1) * 0x1000))); out.set(pg, a); written.push(a); }); + return written; +} + +// ---------------------------------------------------------------- one stored save as pages (1.6.8) +/* The menu packs every page with LZSS: flag byte for 8 entries (bit = reference), reference = 2 bytes + * ((distance-1)<<4 | (length-3)), length field 15: one more byte added to 18 (up to 273). Same as feld/main.c. */ +function lzUnpack(inp, n) { + const out = new Uint8Array(0x1000); let i = 0, o = 0; + while (o < 0x1000) { + if (i >= n) throw new Error('stored save damaged'); + const f = inp[i++]; + for (let b = 0; b < 8 && o < 0x1000; b++) { + if (f & (1 << b)) { + if (i + 2 > n) throw new Error('stored save damaged'); + const v = inp[i] | (inp[i + 1] << 8); i += 2; + const off = (v >> 4) + 1; let len = (v & 15) + 3; + if ((v & 15) === 15) { if (i >= n) throw new Error('stored save damaged'); len += inp[i++]; } + if (off > o || o + len > 0x1000) throw new Error('stored save damaged'); + for (let k = 0; k < len; k++, o++) out[o] = out[o - off]; + } else { if (i >= n) throw new Error('stored save damaged'); out[o++] = inp[i++]; } + } + } + if (i !== n) throw new Error('stored save damaged'); + return out; +} +function lzPack(p) { + const out = [], head = new Int32Array(4096).fill(-1), prev = new Int32Array(4096).fill(-1); + const h = (i) => ((p[i] * 1089 + p[i + 1] * 33 + p[i + 2]) & 4095); + let i = 0, fpos = 0, bit = 8; + while (i < 0x1000) { + if (bit === 8) { fpos = out.length; out.push(0); bit = 0; } + let best = 0, boff = 0; + if (i + 3 <= 0x1000) { + let j = head[h(i)], tries = 0; + while (j >= 0 && tries < 48) { + let l = 0; while (l < 273 && i + l < 0x1000 && p[j + l] === p[i + l]) l++; + if (l > best) { best = l; boff = i - j; if (l === 273) break; } + j = prev[j]; tries++; + } + } + const step = best >= 3 ? best : 1; + if (best >= 3) { + const ln = best - 3; out[fpos] |= 1 << bit; + if (ln < 15) { const v = ((boff - 1) << 4) | ln; out.push(v & 255, v >> 8); } + else { const v = ((boff - 1) << 4) | 15; out.push(v & 255, v >> 8, ln - 15); } + } else out.push(p[i]); + bit++; + for (let k = 0; k < step; k++, i++) if (i + 3 <= 0x1000) { const x = h(i); prev[i] = head[x]; head[x] = i; } + } + return Uint8Array.from(out); +} +/** Pages of a stored save (from slotRead/slotReadAsync): Map address -> 4 KB. */ +function slotPages(s) { + const np = u32(s.head, 8), pages = new Map(); let pos = 0, sum = 0; + for (let k = 0; k < s.bytes; k++) sum = (sum + s.stream[k]) >>> 0; + if (np > 500 || sum !== u32(s.head, 16)) throw new Error('stored save damaged'); + for (let k = 0; k < np; k++) { + const pg = u16(s.head, 32 + 4 * k), n = u16(s.head, 34 + 4 * k); + if (pos + n > s.bytes) throw new Error('stored save damaged'); + pages.set(pg * 0x1000, lzUnpack(s.stream.subarray(pos, pos + n), n)); pos += n; + } + return pages; +} +/** A save (Map address -> 4 KB, only pages from..to that are not empty) packed like the menu does, for slotPlace. */ +function slotBuild(pages, i, from, to) { + const head = new Uint8Array(0x1000).fill(0xFF), parts = []; let np = 0, bytes = 0, sum = 0; + for (const a of [...pages.keys()].sort((x, y) => x - y)) { + const d = pages.get(a); + if (a < from || a >= to || d.length !== 0x1000 || d.every((v) => v === 0xFF)) continue; + if (np >= 500) throw new Error('save too big for a slot'); + const c = lzPack(d); parts.push(c); + w16(head, 32 + 4 * np, a >>> 12); w16(head, 34 + 4 * np, c.length); np++; + bytes += c.length; for (const v of c) sum = (sum + v) >>> 0; + } + const stream = new Uint8Array(bytes); let o = 0; for (const c of parts) { stream.set(c, o); o += c.length; } + w32(head, 0, SLOT_MAGIC); w32(head, 4, i + 1); w32(head, 8, np); w32(head, 12, bytes); w32(head, 16, sum); + return { head, field: i + 1, bytes, stream }; +} +/** Pool pages used by the stored saves (heads: slot index -> header page or null), except slot skip. */ +function poolUsed(f, heads, skip) { + const used = new Set(); + heads.forEach((h, j) => { + if (j === skip || !h) return; + const p = slotParse(f, j, h); if (!p) return; + if (p.pool) for (let k = 0; k < u32(h, 24); k++) used.add(h[DPG_OFF + 2 * k] | (h[DPG_OFF + 2 * k + 1] << 8)); + else for (let k = 0; k < Math.ceil(p.bytes / 0x1000); k++) used.add(j * poolPages(f) + k); + }); + return used; +} +/** Field number a settings block (4 KB) stands for, -1 unknown. */ +function fieldOfSettings(rom, p) { + const e = edition(rom); if (!e || !p) return -1; + const P = profileOf(rom, e.profile); + let f = p[P.fieldByte]; + if (P.six && f < 4) f = P.sixMap[(p[P.six] === 1 ? 4 : 0) + f]; + return f < P.names.length ? f : -1; +} +/** + * The save slots of the menu for the Studio (1.6.8): { f, saves (numbered saves or one per field), live (slot of the + * save now in use, it is not stored in a slot), list: [{ i, used }] } or null without slots. + */ +function saveSlots(rom, tpl) { + const f = feldFind(rom, tpl); + if (!f || !(f.flags & F_FIELDS) || f.nslots < 1) return null; + const saves = f.version >= 6 && (f.flags & F_SAVES) !== 0 && f.nslots >= 2, list = []; + for (let i = 0; i < f.nslots; i++) list.push({ i, used: !!slotParse(f, i, rom.subarray(slotAddr(f, i), slotAddr(f, i) + 0x1000)) }); + let live = -1; + if (saves) { + const v = rom[0xEFE000 + 0xF06]; + if (v >= 1 && v <= f.nslots) live = v - 1; else { const fr = list.find((x) => !x.used); live = fr ? fr.i : 0; } + } else live = fieldOfSettings(rom, rom.subarray(0xEFE000, 0xEFF000)); + return { f, saves, live, list }; +} +function feldSlots(rom, tpl) { + const f = feldFind(rom, tpl); + if (!f || !(f.flags & F_FIELDS)) return []; + const out = []; + for (let i = 0; i < f.nslots; i++) { + const s = slotRead(rom, f, i); + if (!s) continue; + // Slot ID: from menu version 3 the field number + 1, before that (v0.9.4/v0.9.5) the edition ID + out.push(Object.assign(s, { index: f.version >= 3 ? s.field - 1 : i })); + } + return out; +} + +// ---------------------------------------------------------------- catalog +/* + * Items from the user's own image, as in the TamaParadise app (Bilder.kt): + * picture table found by its shape, item table (46-byte records), English + * text table found by its marker words. Name = text number in the record plus one. + */ +const SATZ = 46, CH_A = 318; +const SONDER = { 305: ' ', 317: ' ', 375: '&', 376: "'", 381: '.', 370: '!', 388: '?', 382: '/' }; +for (let i = 0; i < 10; i++) SONDER[306 + i] = String(i); // 1.6.8: digits (names changed in the Studio) +const WORTE = ['FOOD', 'SNACKS', 'OUTSIDE TOY', 'LAB LOG', 'MILK']; +/* + * The image table of the ROM. Only searched inside the asset archive (from 0x111000 to + * its end): programs built in by the Studio (DOOM, TamaEmu) contain tables that look + * alike, and DOOM sits before the archive's image table. + */ +function bildTabelle(d) { + const end = Math.min(d.length, assetEnd(d)); + for (let o = 0x111000; o + 4 < end; o += 4) { + const e0 = u32(d, o); + if (e0 < 0x1000 || e0 > 0x8000 || e0 % 4) continue; + let prev = e0, ok = true; + for (let i = 1; i < 60; i++) { const w = u32(d, o + 4 * i); if (w <= prev || w > 0x1000000) { ok = false; break; } prev = w; } + if (!ok) continue; + const k = o + e0; + if (k + 24 >= d.length) continue; + const g = u32(d, k), p = u32(d, k + 20); + if (p > 24 && p < g && g >= 1 && g <= 0x20000 && p % 8 === 0 && d[k + 8] > 0 && d[k + 9] > 0) return o; + } + return -1; +} +function itemTabelle(d, nb) { + let best = -1, bn = 0; + for (let o = 0; o + SATZ < d.length; o += 2) { + const k0 = u16(d, o); + if (k0 < 5001 || k0 > 9999) continue; + const seen = new Set(); let n = 0; + while (n < 400 && o + n * SATZ + 5 < d.length) { + const k = u16(d, o + n * SATZ), b = u16(d, o + n * SATZ + 4); + if (k < 5001 || k > 9999 || b >= nb || seen.has(k)) break; + seen.add(k); n++; + } + if (n > bn) { bn = n; best = o; } + if (n > 8) o += n * SATZ - 2; + } + return [best, bn]; +} +function zeichenkette(d, t, n) { + const ab = u16(d, t + 2 * n); + if (ab <= 0 || ab > 0x8000) return ''; + let o = t + 2 * ab, s = ''; + while (s.length < 40) { + const c = u16(d, o); + if (c === 0) break; + if (c >= CH_A && c < CH_A + 26) s += String.fromCharCode(65 + c - CH_A); + else if (SONDER[c] !== undefined) s += SONDER[c]; + else return ''; + o += 2; + } + return s.trim(); +} +function wort3(d, t, n) { + const ab = u16(d, t + 2 * n); + if (ab <= 0 || ab > 0x8000) return false; + for (let k = 0; k < 3; k++) { const c = u16(d, t + 2 * ab + 2 * k); if (c < CH_A || c >= CH_A + 26) return false; } + return true; +} +function textTabelle(d) { + let best = -1, bp = 0; + for (let o = 0; o < d.length - 8; o += 2) { + const n = u16(d, o); + if (n < 100 || n > 4000 || !(u16(d, o + 2) > n && u16(d, o + 4) > u16(d, o + 2) && u16(d, o + 6) > u16(d, o + 4)) || !wort3(d, o, 1)) continue; + let prev = n, ok = true; + for (let i = 1; i < Math.min(n, 200); i++) { const w = u16(d, o + 2 * i); if (w < prev || w > 0x8000) { ok = false; break; } prev = w; } + if (!ok) continue; + let p = 0; for (let k = 1; k < 120; k++) if (WORTE.includes(zeichenkette(d, o, k))) p++; + if (p > bp) { bp = p; best = o; } + } + return bp >= 2 ? best : -1; +} +/* + * Byte sum of an item picture entry, as the menu computes it after copying the entry + * to RAM (header, sub-image table, palette, pixel data of all sub-images). 0 = unknown. + */ +function picSum(d, P, pic) { const i = picInfo(d, P, pic); return i ? i.sum : 0; } +/* Where the picture entry lies in flash, its length, byte sum and first word (or null). */ +function picInfo(d, P, pic) { + const n = u32(d, P) / 4; if (pic >= n) return null; + const e = P + u32(d, P + 4 * pic); if (e & 3) return null; + const flags = d[e + 4], bpp = d[e + 5], sw = d[e + 8], sh = d[e + 9]; + if (bpp > 3 || !sw || !sh) return null; + const iw = d[e + 12] || 1, ih = d[e + 13] || 1, cnt = iw * ih, bits = 1 << bpp, mask = (1 << bits) - 1; + const need = (sw * sh * bits + 7) >> 3, po = u16(d, e + 18), px = u16(d, e + 20); + let end = px + 8 * cnt; + for (let c = 0; c < cnt; c++) { + let x; + if (flags & 0x60) { const w = u32(d, e + px + 8 * c), off = w & 0x7FFFFFFF, ln = u32(d, e + px + 8 * c + 4); x = px + off + ((w & 0x80000000) ? need : ln); } + else x = px + (c + 1) * need; + if (x > end) end = x; + } + end = Math.max(end, po + 2 * (mask + 1)); + if (end > 12288 || e + end > d.length) return null; + let sum = 0; for (let i = 0; i < end; i++) sum += d[e + i]; + return { addr: e, len: end, sum: (sum & 0xFFFF) || 1, head: u32(d, e) }; +} +/** Catalog: [{ id, fixed, pic, sum, name }] ascending, only groups 5 to 8. */ +function itemCatalog(d, language='en') { + const bt = bildTabelle(d); + if (bt < 0) return []; + const [it, n] = itemTabelle(d, u32(d, bt) / 4); + if (it < 0 || n < 100) return []; + const tt = textTabelle(d); + const out = []; + for (let i = 0; i < n; i++) { + const o = it + i * SATZ, id = u16(d, o); + if (id < 5001 || id > 8999) continue; + const pic = u16(d, o + 4); + const pi = picInfo(d, bt, pic); + out.push({ id, fixed: u16(d, o + 24) === 0xFFFF, pic, sum: pi ? pi.sum : 0, at: pi, text: u16(d, o + 2) + 1, name: language==='ko' ? globalThis.ParamixCore.textGet(d,u16(d,o+2)+1,'ko') : tt >= 0 ? zeichenkette(d, tt, u16(d, o + 2) + 1) : '' }); + } + out.sort((a, b) => a.id - b.id); + out.pack = bt; + return out; +} +/* + * Characters for the TAMA menu (1.6.8): kid, young and adult of the character table with their + * English names. fixed 2, stage, field = index + 1 in the menu's field list (P.names), 0 = none. + */ +const FIELD_DEFAULT = new Set(['LAND', 'WATER', 'SKY', 'FOREST', 'TROPICAL', 'ICE', 'GLACIER']); +/** Text numbers of the field names (1.6.8): the three fields at 14..16, the further ones of six fields at 64..66 */ +const FIELD_TEXT = [14, 15, 16, 64, 65, 66]; +const TYPE_NAMES = { 1: 'LAND', 2: 'WATER', 3: 'SKY', 4: 'FOREST', 5: 'TROPICAL', 6: 'GLACIER' }; +function charCatalog(d, P, language='en', pictures=false) { + const C = typeof ParamixCore !== 'undefined' ? ParamixCore : (typeof require !== 'undefined' ? require('./core.js') : null); + if (!C) return []; + let ctx; try { ctx = C.openRom(d); } catch (e) { return []; } + const tt = textTabelle(d), out = []; + const all=C.charTable(ctx.files[0]).filter(c=>c.id>1000&&c.id<9000); + for (const c of C.charTable(ctx.files[0])) { + if (c.id < 1001 || c.id > 4999 || c.stage < 2 || c.stage > 5) continue; + const nm = (language==='ko' ? C.textGet(d,c.name,'ko') : tt >= 0 ? zeichenkette(d,tt,c.name) : '') || ('NO. ' + c.id); + const fi = P.names.indexOf(TYPE_NAMES[c.field]); + out.push({ id: c.id, fixed: 2, pic: 0, sum: (c.stage & 255) | ((fi + 1) << 8), at: null, nativeName:C.textGet(d,c.name,'ko'), thumbnail:language==='ko'&&pictures?portrait(C,ctx,ctx.groups[all.findIndex(v=>v.id===c.id)+1]):null, name: nm.replace(/\s+/g, ' ') }); + } + return out; +} +/** Characters the TAMA menu offers (for the Studio's save editor too): [{ id, stage, field, name }] */ +function characters(d, language='en') { + const e = edition(d); if (!e) return []; + const P = profileOf(d, e.profile); + return charCatalog(d, P, language).map((c) => ({ id: c.id, stage: c.sum & 255, field: (c.sum >> 8) - 1, name: c.name })); +} +/* + * Catalog: 8 byte header, 28 bytes per entry, then "PEXT" and 12 bytes per entry: + * flash address of the picture entry, its length, byte sum, first word. The menu + * reads the picture straight from there (no lookup in the ROM's image table). + */ +const EXT_MAGIC = 0x54584550; +function portrait(C,ctx,g){ + if(g===undefined)return null; + try{const pose=C.faceFirst(ctx.files[0],g,g+1,g+2);if(!pose)return null; + const body=C.spriteDecode(ctx.entries[g]).subs[pose.bs];const img={w:body.w,h:body.h,data:new Uint8ClampedArray(body.data)}; + for(const [j,v]of [[1,pose.eye],[2,pose.mouth]]){if(!v)continue;const part=C.spriteDecode(ctx.entries[g+j]).subs[v.sub];const x=(body.w-part.w)/2+v.dx,y=(body.h-part.h)/2+v.dy;for(let py=0;py=img.w||yy>=img.h)continue;const k=(py*part.w+px)*4;if(part.data[k+3])img.data.set(part.data.subarray(k,k+4),(yy*img.w+xx)*4);}} + const out=new Uint8Array(32*32*2);for(let y=0;y<32;y++)for(let x=0;x<32;x++){const i=(Math.floor(y*img.h/32)*img.w+Math.floor(x*img.w/32))*4;const c=img.data[i+3]?((img.data[i]>>3)<<11)|((img.data[i+1]>>2)<<5)|(img.data[i+2]>>3):0xF81F;w16(out,(y*32+x)*2,c);}return out; + }catch(e){return null;} +} +function catalogBlob(cat, korean=false) { + const x = 8 + 28 * cat.length; + const font=korean ? globalThis.ParamixKoreanMenu.font() : new Uint8Array(0); + const encoded=cat.map(c=>korean?globalThis.ParamixKoreanMenu.encode(c.name||('항목 '+c.id),60):c.name.slice(0,20)); + const base=x+4+12*cat.length+font.length, tails=korean?26*cat.length+4*cat.length+cat.reduce((n,c)=>n+(c.thumbnail?.length||0),0)+encoded.reduce((n,c)=>n+c.length+1,0):0; + const b = new Uint8Array(base+tails); + const nameOffsets=[]; + if(korean){let pos=base+30*cat.length;cat.forEach((c,i)=>{ + [...(c.nativeName||c.name)].slice(0,12).forEach((ch,j)=>w16(b,base+i*26+j*2,globalThis.ParamixCore.TXT_ENC[ch]??globalThis.ParamixCore.KO_ENC[ch]??0)); + if(c.thumbnail){w32(b,base+26*cat.length+i*4,pos);b.set(c.thumbnail,pos);pos+=c.thumbnail.length;} + });encoded.forEach(n=>{nameOffsets.push(pos);for(const c of n)b[pos++]=c.charCodeAt(0);b[pos++]=0;});} + if(korean)b.set(font,x+4+12*cat.length); + w32(b, x, EXT_MAGIC); + cat.forEach((c, i) => { const o = x + 4 + 12 * i; if (c.at) { w32(b, o, c.at.addr); w16(b, o + 4, c.at.len); w16(b, o + 6, c.at.sum); w32(b, o + 8, c.at.head); } }); + w32(b, 0, CAT_MAGIC); w32(b, 4, cat.length); + cat.forEach((c, i) => { + const o = 8 + 28 * i, nm = encoded[i]; + w16(b, o, c.id); b[o + 2] = c.fixed === 2 ? 2 : c.fixed ? 1 : 0; b[o + 3] = nm.length; w16(b, o + 4, c.pic); w16(b, o + 6, c.sum || 0); + if(korean){b[o+3]=255;w32(b,o+8,nameOffsets[i]);} + else for (let k = 0; k < nm.length; k++) b[o + 8 + k] = nm.charCodeAt(k); + }); + return b; +} + +// ---------------------------------------------------------------- install and remove +function doomCodeEnd(rom) { + let e = DOOM_SAVE; + while (e > DOOM_CODE && rom[e - 1] === 0xFF) e--; + return page(e); +} +function assetEnd(rom) { return 0x111000 + 16 + u32(rom, 0x111000 + 8); } + +/** Remove the menu (program, catalog, slots, stub). Call feldSlots() first if the saves should be kept. */ +function feldStrip(rom, emb, E) { + const out = new Uint8Array(rom); + const f = feldFind(out, emb.stub); + if (!f) return out; + const tab = E.sceneTable(out); + launchRestore(out, f.stubOff); // start device: scene handlers back, trampolines gone (before the menu area is erased) + const prev = f.stubOff === STUB_OFF ? E.installedOrigs(out, tab) : [0, 1, 2, 3].map((k) => u32(out, f.stubOff + 0x94 + 4 * k)); + // The Korean catalog is separate from executable code and from save slots. + if(f.catOff>=0x111000 && f.catN<2000 && u32(out,f.catOff)===CAT_MAGIC){ + const font=f.catOff+12+40*f.catN, count=u32(out,font+4); + if(u32(out,font)===0x31464f4b && count<=4096){ + let end=font+8+13*count; + if(f.catN){ + const last=f.catOff+8+28*(f.catN-1), ptr=f.catOff+u32(out,last+8); + if(out[last+3]!==255 || ptrout.length)throw Error('한글 이름 자료의 위치가 올바르지 않습니다.'); + end=ptr;while(end= 2 ? 0x8000 : 0x4000); + if (f.catOff > f.off && u32(rom, f.catOff) === CAT_MAGIC) { + let ce = f.catOff + 8 + (f.version >= 3 ? 28 : 24) * f.catN; + if (u32(rom, ce) === EXT_MAGIC) ce += 4 + 12 * f.catN; + end = Math.max(end, page(ce)); + } + if (f.slotOff > f.off && f.slotOff < end) end = f.slotOff; + end = Math.min(end, f.stubOff === STUB_OFF && f.off < FELD_END ? FELD_END : (isSix(out) ? CODE_END : 0x110000)); + out.fill(0xFF, f.off, end); + // Slots: never erase into the character data + if (f.nslots && f.slotSize) { + if (f.slotOff2 && f.slotN1) { + for (let i = 0; i < f.nslots; i++) { const b = slotAddr(f, i); if (b >= page(assetEnd(out)) || b < 0x111000) out.fill(0xFF, b, b + f.slotSize); } + } else { + const from = f.slotOff < 0x800000 ? f.slotOff : Math.max(f.slotOff, page(assetEnd(out))); + out.fill(0xFF, from, f.slotOff + f.nslots * f.slotSize); + } + } + // the flash app of the start device (version 7) + if (f.version >= 7) { const d = u32(out, f.off + 0x140 + 500); if (d >= 0x10000000 && d < 0x11000000) { const o = d - 0x10000000 + XIP_DEC; if (o >= 0x111000 && o + 0x10000 <= out.length) out.fill(0xFF, o, o + 0x10000); } } + if (prev) { + if (f.stubOff === STUB_OFF && appKind(out) && emb.oldStub) return E.installApp(out, out.slice(APP_OFF, APP_OFF + 0x10000), emb.oldStub, { keep: true }); // 1.6.8: before, this freed the blocks of T18Emu + prev.forEach((v, k) => w32(out, tab.PSID_HOME + 12 + 4 * k, v)); + out.fill(0xFF, f.stubOff, f.stubOff + 0x1000); + } + return out; +} + +/** + * Install the menu into an image without a menu (after emulator/DOOM). + * opts: { fields, bag }, saved: feldSlots() of the source ROM, + * emb: { feld, stub } (embedded), E: ParamixEmu. Returns a new image. + */ +function feldApply(rom, opts, saved, emb, E) { + if (rom.length !== 0x1000000) throw new Error('the Paradise image must be 16 MB'); + const out = new Uint8Array(rom); + if (feldFind(out, emb.stub)) throw new Error('the menu is already built in'); + const ed = edition(out); + if (!ed) throw new Error('edition not recognised'); + const P = profileOf(out, ed.profile); + const v6 = u32(emb.feld, findWord(emb.feld, FELD_MAGIC) + 4) >= 6; + const launch = !!opts.launch; + const gplay = GPLAY && !!opts.gplay && !launch && !opts.clean; const fields = !!opts.fields && !launch, bag = !!opts.bag && !launch, tama = !!opts.tama && v6 && !launch, saves = fields && v6 && opts.saves !== false; + if (!fields && !bag && !tama && !gplay && !launch) throw new Error('nothing chosen'); + if (launch && (u32(emb.stub, LAUNCH_ENTRY) !== 0x4C01B672 || (u32(emb.stub, LCHECK_ENTRY) & 0xF800) !== 0xF000)) throw new Error('launcher template does not fit'); // cpsid i; ldr r4, feld_src / b.w lcheck + const tab = E.sceneTable(out); + if (!tab.PSID_HOME) throw new Error('home screen not found'); + const prev = E.installedOrigs(out, tab); + const kind = appKind(out); + const stubOff = prev || kind ? STUB_OFF : freeStubOff(out); + if (!prev && !isFF(out, stubOff, 0x1000)) throw new Error('no room for the launcher'); + const korean=containsKoMark(emb.feld); + const catList = bag ? itemCatalog(out,korean?'ko':'en') : []; + if (tama) { const pack = catList.pack; catList.push(...charCatalog(out, P,korean?'ko':'en',korean)); catList.sort((a, b) => a.id - b.id); catList.pack = pack; } + const cat = bag || tama || korean ? catalogBlob(catList,korean) : new Uint8Array(0); + const fsz = page(emb.feld.length), catalogSize=page(cat.length), csz=korean?0:catalogSize; + let separateCat=0; + if(korean){ + const ceiling=Math.min(P.idPage-0x1000,opts.appsLow||P.idPage-0x1000); + const floor=page(assetEnd(out)); + for(let a=(ceiling-catalogSize)&~0xFFF;a>=floor;a-=4096)if(isFF(out,a,catalogSize)){separateCat=a;break;} + if(!separateCat)throw Error('한글 이름과 그림을 넣을 공간이 부족합니다.'); + } + const doom = kind === 1; + let prog = doom ? doomCodeEnd(out) : stubOff + 0x1000; + // DOOM with T18Emu as a further program (start device, 1.6.8): its flash part at 0x0F0000 lies in DOOM's free end + const tsz = launch ? launchSize(out, E.sceneTable(out)) : 0; // start device: trampoline pages behind the menu + if (doom) while (prog + fsz + csz + tsz <= DOOM_SAVE && !isFF(out, prog, fsz + csz + tsz)) prog += 0x1000; + const tOff = page(prog + fsz + csz); + const catOff = cat.length ? (separateCat || prog + fsz) : 0; + + const nslots = fields ? P.ids.length : 0; + let slotOff = 0, slotSize = 0, slotOff2 = 0, slotN1 = 0; + if (doom) { + if (prog + fsz + csz + tsz > DOOM_SAVE) throw new Error('no room for the menu next to DOOM'); + if (fields) { + slotOff = prog + fsz + csz; + slotSize = Math.floor((DOOM_SAVE - slotOff) / nslots / 0x1000) * 0x1000; + if (slotSize < 0x8000) throw new Error('no room for the saves next to DOOM'); + } + } else { + if (prog + fsz + csz + tsz > (stubOff === STUB_OFF ? FELD_END : CODE_END)) throw new Error('menu program too big'); + if (!isFF(out, prog, fsz + csz + tsz)) throw new Error('the area for the menu is in use'); + if (fields && P.six) { + // six fields: slots behind the menu (up to the helper page) and behind the character data + const a1 = page(prog + fsz + csz), r1 = CODE_END - a1, a2 = page(assetEnd(out)), r2 = (separateCat || P.idPage - 0x1000) - a2; + for (let s = SLOT_SIZE; s >= 0x10000; s -= 0x1000) { + const n1 = Math.max(0, Math.floor(r1 / s)), n2 = Math.max(0, Math.floor(r2 / s)); + if (n1 + n2 >= nslots) { slotSize = s; slotN1 = Math.min(n1, nslots); slotOff = slotN1 ? a1 : a2; slotOff2 = slotN1 && slotN1 < nslots ? a2 : 0; if (!slotN1) slotN1 = 0; break; } + } + if (!slotSize) throw new Error('no room for the saves'); + } else if (fields) { + slotOff = Math.max(SLOT_BASE, page(assetEnd(out))); + // the emulator's firmware starts at 0x940000, a big one (P's, 4U+) already at 0x840000 (1.3.2) + // T18Emu (1.5.1) puts its firmware from the top down: the saves get the room below its lowest block + const T18 = 0x38584D50, t18low = u32(out, 0xA0140) === T18 && E && E.t18Low ? E.t18Low(out) : 0; + const limit0 = kind === 2 ? (u32(out, 0xA0140) === PMXC ? Math.min(u32(out, 0xA0148), GUEST_OFF) : t18low ? Math.min(t18low, P.idPage - 0x1000) : GUEST_OFF) : P.idPage - 0x1000; + const limit = Math.min(limit0, opts.appsLow || limit0, separateCat || limit0); + if (limit - slotOff < nslots * 0x10000) throw new Error('no room for the field saves next to this emulator firmware'); + // all the room up to the emulator or the device's save area (1.2.11; before at most 0x58000 each) + slotSize = Math.floor((limit - slotOff) / nslots / 0x1000) * 0x1000; + if (slotSize < 0x10000) throw new Error('no room for the saves'); + } + } + const fs = { slotOff, slotSize, slotOff2, slotN1 }; + if (fields) for (let i = 0; i < nslots; i++) if (!isFF(out, slotAddr(fs, i), slotSize)) throw new Error('the area for the saves is in use'); + // Program with settings + const f = new Uint8Array(emb.feld); + const ci = findWord(f, FELD_MAGIC); + if (ci < 0 || u32(f, ci + 4) < 3) throw new Error('settings block of the menu missing'); + w32(f, ci + 8, slotOff); w32(f, ci + 12, slotSize); w32(f, ci + 16, nslots); + w32(f, ci + 20, P.idPage + 0x1000); w32(f, ci + 24, P.six ? 0xF00000 : 0x1000000); // six fields: rain pictures from 0xF00000 + w32(f, ci + 28, P.idPage); // ID page (1.2.2 to 1.2.11 lost this line: Tropical/Glacier wrote the ID to 0xD49000) + w32(f, ci + 32, stubOff); w32(f, ci + 36, (fields ? F_FIELDS : 0) | (bag ? F_BAG : 0) | (tama ? F_TAMA : 0) | (saves ? F_SAVES : 0) | (launch ? F_LAUNCH : 0) | (gplay ? F_GPLAY : 0)); + w32(f, ci + 40, P.c); w16(f, ci + 44, P.h[0]); w16(f, ci + 46, P.h[1]); + // 1.6.8: a field renamed in the Studio (text table) shows its new name in the menu too + const shownName = (i) => { const x = (opts.fieldNames || [])[i]; const native=korean?globalThis.ParamixCore.textGet(out,FIELD_TEXT[i],'ko'):'';const name=(x && !FIELD_DEFAULT.has(x) ? x : native || P.names[i]) || ''; return korean ? globalThis.ParamixKoreanMenu.encode(name,10) : name.slice(0,11); }; + w32(f, ci + 48, P.ids.length); + for (let i = 0; i < 4; i++) { + w32(f, ci + 52 + 4 * i, P.ids[i] || 0); + const nm = shownName(i); + for (let k = 0; k < 12; k++) f[ci + 68 + 12 * i + k] = k < nm.length ? nm.charCodeAt(k) : 0; + w32(f, ci + 116 + 4 * i, P.cols[i] || 0xFFFF); + } + for (let k = 0; k < 16; k++) { const p = P.common[k]; w16(f, ci + 132 + 4 * k, p ? p[0] : 0); f[ci + 134 + 4 * k] = p ? p[1] : 0; f[ci + 135 + 4 * k] = 0; } + for (let i = 0; i < 4; i++) for (let k = 0; k < 4; k++) { + const p = (P.field[i] || [])[k], o = ci + 196 + 16 * i + 4 * k; + w16(f, o, p ? p[0] : 0); f[o + 2] = p ? p[1] : 0; f[o + 3] = 0; + } + w32(f, ci + 260, P.bag[0]); w32(f, ci + 264, P.bag[1]); w32(f, ci + 268, P.bag[2]); + w32(f, ci + 272, catOff); w32(f, ci + 276, cat.length ? u32(cat, 4) : 0); + w32(f, ci + 280, P.fieldByte); w32(f, ci + 284, bag && catList.pack > 0 ? catList.pack : 0); + if (P.six) { + if (u32(f, ci + 4) < 4) throw new Error('menu program too old for six fields'); + w32(f, ci + 288, P.six); + for (let i = 4; i < 6; i++) { + w32(f, ci + 292 + 4 * (i - 4), P.ids[i] || 0); + const nm = shownName(i); + for (let k = 0; k < 12; k++) f[ci + 300 + 12 * (i - 4) + k] = k < nm.length ? nm.charCodeAt(k) : 0; + w32(f, ci + 324 + 4 * (i - 4), P.cols[i] || 0xFFFF); + for (let k = 0; k < 4; k++) { const p = (P.field[i] || [])[k], o = ci + 332 + 16 * (i - 4) + 4 * k; w16(f, o, p ? p[0] : 0); f[o + 2] = p ? p[1] : 0; f[o + 3] = 0; } + } + w32(f, ci + 364, slotOff2); w32(f, ci + 368, slotOff2 ? slotN1 : 0); + P.sixMap.forEach((v, k) => { f[ci + 372 + k] = v; }); + } + // more programs (1.6.0, version 5): name of the stub's program and the list the menu can start + if (u32(f, ci + 4) >= 5) { + const nm = (opts.name0 || '').slice(0, 12); + for (let k = 0; k < 12; k++) f[ci + 380 + k] = k < nm.length ? nm.charCodeAt(k) : 0; + const max = u32(f, ci + 4) >= 8 ? 12 : 6, apps = (opts.apps || []).slice(0, max); // 1.6.8 (version 8): 12 + if ((opts.apps || []).length > max) throw new Error('at most ' + max + ' more programs'); + w32(f, ci + 392, apps.length); + for (let i = 0; i < max; i++) { + const a = apps[i], o = i < 6 ? ci + 396 + 16 * i : ci + 504 + 16 * (i - 6); + w32(f, o, a ? a.src : 0); + for (let k = 0; k < 12; k++) f[o + 4 + k] = a && k < a.name.length ? a.name.charCodeAt(k) : 0; + } + } else if (opts.apps && opts.apps.length) throw new Error('menu program too old for more programs'); + // TAMA menu (1.6.8, version 6): where the pet and the planet level lie in the settings block + if (u32(f, ci + 4) >= 6) { w32(f, ci + 492, tama ? P.tama : 0); w32(f, ci + 496, tama ? P.level : 0); } + // DOWNLOAD in the start device (1.6.8, version 7): the flash app placed by appsPlace + if (u32(f, ci + 4) >= 7) w32(f, ci + 500, launch && opts.dl ? opts.dl : 0); + else if (launch && opts.dl) throw new Error('menu program too old for the start device'); + // 1.6.9 test13 (version 9): the main program of the start device (one of the list, shown first) and its autostart + if (u32(f, ci + 4) >= 9) { w32(f, ci + 600, launch && opts.mainSrc ? opts.mainSrc : 0); w32(f, ci + 604, launch && opts.auto ? 1 : 0); } + out.set(f, prog); + if (cat.length) out.set(cat, catOff); + // carry over saved slots (the active field lives in the save itself) + if (fields) { const used = new Set(), g = Object.assign({ nslots }, fs); + for (const s of saved || []) { + const i = s.index; + if (i < 0 || i >= nslots) continue; + try { slotPlace(out, g, i, s, used); } catch (e) { throw new Error('the stored save of ' + cap(P.names[i]) + ' does not fit here'); } + } } + // Stub + const origs = prev || [0, 1, 2, 3].map((k) => u32(out, tab.PSID_HOME + 12 + 4 * k)); + const st = new Uint8Array(emb.stub); + const put = (ph, v) => { let n = 0; for (let i = 0; i + 4 <= st.length; i += 2) if (u32(st, i) === ph) { w32(st, i, v); n++; } if (n !== 1) throw new Error('launcher template does not fit'); }; + put(PH_APP, kind ? xip(APP_OFF) : 0); + put(PH_FELD, xip(prog)); + PH_ORIG.forEach((ph, k) => put(ph, origs[k])); + { const ia = findWord(st, PH_AUTO); if (ia >= 0) w32(st, ia, 0); } // autostart off, the Studio sets it at the end + out.fill(0xFF, stubOff, stubOff + 0x1000); + out.set(st, stubOff); + HOOK_OFF.forEach((h, k) => w32(out, tab.PSID_HOME + 12 + 4 * k, (xip(stubOff) + h) | 1)); + if (launch) launchRedirect(out, tab, stubOff, tOff); + return out; +} + +/* + * 1.7.2 CLEAN_ROM: a ROM without the Paradise. The boot ROM of the chip starts our menu straight away: an unencrypted + * load table at 0 (a copy of the device's own with LOAD_CFG bit 0 off, as the rescue start at 0xFFE000, confirmed on + * the device) loads the menu (0x0B1000, as in every Paramix ROM) into the PRAM; the menu sets up clock, pins and + * display itself. Programs go back through the routine at flash 0x110568 (the firmware's restart, the programs call + * it at 0x100FF568 with the window at 0x60011000): here it starts the menu through the stub. The menu keeps the clock + * in its own sector (0x0C0000). Kept from the device: only the ID page (its edition and identity, so the Studio and + * the flasher know the device). Everything else of the 16 MB is free for programs, besides the rescue start. + */ +const CLEAN_ID = 0xEFD000; // 1.7.3 test13: the ID page of a clean ROM (below the kept Paradise settings pages) +const CLEAN_ROM = true, F_CLEAN = 32, CLOCK_SEC = 0xC0000, CLEAN_SHIM = 0x110568, CLEAN_LO = 0x10000, CLEAN_HI = 0xFF0000; +/** Areas a clean ROM keeps for itself (programs must not go there). */ +function cleanReserved() { + return [[0, CLEAN_LO], [STUB_OFF, CLOCK_SEC + 0x1000], [CLEAN_SHIM & ~0xFFF, (CLEAN_SHIM & ~0xFFF) + 0x1000], [CLEAN_ID, 0xF00000], [CLEAN_HI, 0x1000000]]; +} +function crc32z(b, a, n) { + let c = 0xFFFFFFFF; + for (let i = a; i < a + n; i++) { c ^= b[i]; for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xEDB88320 & -(c & 1)); } + return (c ^ 0xFFFFFFFF) >>> 0; +} +/** Is this a ROM without the Paradise (made by cleanApply)? */ +function isClean(rom) { return !!cleanInfo(rom); } +/** Menu place and clock sector of a clean ROM: { feld, clock } or null. */ +function cleanInfo(rom) { + if (!rom || rom.length !== 0x1000000 || String.fromCharCode(...rom.subarray(0, 8)) !== 'SONIXDEV') return null; + const a = u32(rom, 0x10) - 0x60000000; + if (a !== FELD_OFF) return null; + const ci = findWord(rom.subarray(a, a + 0x10000), FELD_MAGIC); + if (ci < 0 || !(u32(rom, a + ci + 36) & F_CLEAN)) return null; + return { feld: a, clock: u32(rom, a + ci + 4) >= 10 ? u32(rom, a + ci + 608) : CLOCK_SEC }; +} +/** Empty 16 MB with the device's ID page (from its own ROM src); the rest comes from appsPlace and cleanApply. */ +function cleanBase(src) { + const ed = edition(src); + if (!ed) throw new Error('edition not recognised'); + const out = new Uint8Array(0x1000000).fill(0xFF); + out.set(src.subarray(ed.at, ed.at + 0x1000), CLEAN_ID); // 1.7.3 test13: at the top (was its own place 0xD49000/0xD29000) + out.set(src.subarray(0, 0x1000), 0); // the load table, made ours in cleanApply + return out; +} +/** Menu, stub, restart routine and load table into a clean ROM (programs already placed). opts: apps, dl, mainSrc, auto; + * spot: { feld, clock } (the usual places when left out). */ +function cleanApply(rom, opts, emb) { + const out = new Uint8Array(rom); + const sp = opts.spot || { feld: FELD_OFF, clock: CLOCK_SEC }, FO = sp.feld; + if (String.fromCharCode(...out.subarray(0, 8)) !== 'SONIXDEV') throw new Error('load table missing'); + const ed = edition(out); if (!ed) throw new Error('edition not recognised'); + const f = new Uint8Array(emb.feld), ci = findWord(f, FELD_MAGIC); + if (ci < 0 || u32(f, ci + 4) < 10) throw new Error('menu program too old for a ROM without the Paradise'); + if (f.length > 0xE000) throw new Error('menu program too big'); + // settings: no fields, items or Tama; the programs, DOWNLOAD, the clock sector + for (let k = 8; k < 36; k += 4) w32(f, ci + k, 0); + w32(f, ci + 28, CLEAN_ID); w32(f, ci + 32, STUB_OFF); w32(f, ci + 36, F_LAUNCH | F_CLEAN); + w32(f, ci + 48, 0); w32(f, ci + 272, 0); w32(f, ci + 276, 0); w32(f, ci + 288, 0); w32(f, ci + 284, 0); + { const nm = (opts.app && opts.name0 || '').slice(0, 12); for (let k = 0; k < 12; k++) f[ci + 380 + k] = k < nm.length ? nm.charCodeAt(k) : 0; } + const max = 12, apps = (opts.apps || []).slice(0, max); + if ((opts.apps || []).length > max) throw new Error('at most ' + max + ' more programs'); + w32(f, ci + 392, apps.length); + for (let i = 0; i < max; i++) { + const a = apps[i], o = i < 6 ? ci + 396 + 16 * i : ci + 504 + 16 * (i - 6); + w32(f, o, a ? a.src : 0); + for (let k = 0; k < 12; k++) f[o + 4 + k] = a && k < a.name.length ? a.name.charCodeAt(k) : 0; + } + w32(f, ci + 492, 0); w32(f, ci + 496, 0); + w32(f, ci + 500, opts.dl || 0); + w32(f, ci + 600, opts.mainSrc || 0); w32(f, ci + 604, (opts.auto ? 1 : 0) | (opts.noClock ? 2 : 0)); + w32(f, ci + 608, sp.clock); + const size = page(f.length); + out.fill(0xFF, FO, FO + size); out.set(f, FO); + // stub: only its start entry is used (no home screen hooks) + const st = new Uint8Array(emb.stub); + const put = (ph, v) => { let n = 0; for (let i = 0; i + 4 <= st.length; i += 2) if (u32(st, i) === ph) { w32(st, i, v); n++; } if (n !== 1) throw new Error('launcher template does not fit'); }; + put(PH_APP, opts.app || 0); put(PH_FELD, xip(FO)); PH_ORIG.forEach((ph) => put(ph, 0)); + { const ia = findWord(st, PH_AUTO); if (ia >= 0) w32(st, ia, 0); } + if (u32(st, 0x0C) !== 0x4604B672) throw new Error('launcher template does not fit'); // cpsid i; mov r4, r0 (start_src) + out.fill(0xFF, STUB_OFF, STUB_OFF + 0x1000); out.set(st, STUB_OFF); + // the restart routine the programs call: ldr r0, [menu]; ldr r1, [start_src]; bx r1 + const r = CLEAN_SHIM; + out.fill(0xFF, r & ~0xFFF, (r & ~0xFFF) + 0x1000); + w16(out, r, 0x4801); w16(out, r + 2, 0x4902); w16(out, r + 4, 0x4708); w16(out, r + 6, 0xBF00); + w32(out, r + 8, xip(FO)); w32(out, r + 12, (xip(STUB_OFF) + 0x0C) | 1); + // the load table: the menu, not encrypted + const t = out.subarray(0, 0x1000); + w32(t, 0x08, u32(t, 0x08) & ~1); + w32(t, 0x10, 0x60000000 + FO); + w32(t, 0x14, size); + w32(t, 0x24, crc32z(out, FO, size)); + t.fill(0, 0x80, 0x84); + return out; +} + +const FELD_B64 = '__FELD_B64__', FELD_STUB_B64 = '__FELD_STUB_B64__', FELDC_B64 = '__FELDC_B64__'; +const FELD_KO_B64 = '__FELD_KO_B64__', FELDC_KO_B64 = '__FELDC_KO_B64__'; +function containsKoMark(b){const m='ITOSM_KO_MENU_V1';return b.some((_,i)=>i+m.lengthb[i+j]===c.charCodeAt(0)));} +function koreanMenu(rom) { + if (FELD_STUB_B64.startsWith('__')) return false; + const f = feldFind(rom, b64(FELD_STUB_B64)); + if (!f) return false; + const mark = 'ITOSM_KO_MENU_V1', end = Math.min(rom.length, f.off + (isClean(rom) ? 0xE000 : 0x8000)); + for (let i=f.off; i+mark.length { const o = new Uint8Array(LV_A.length + LV_B.length); let s = 0x2C1B3C6D; + for (let i = 0; i < o.length; i++) { s = (Math.imul(s, 1103515245) + 12345) & 0x7fffffff; o[i] = (i & 1 ? LV_B : LV_A)[i >> 1] ^ ((s >>> 16) & 255); } + return o; })(); +const LINK_KEY = String.fromCharCode(...LV.subarray(0, 32)), PDLO_TOKEN = String.fromCharCode(...LV.subarray(32, 40)); +const PDLO_XOR = (LV[40] | LV[41] << 8 | LV[42] << 16 | LV[43] << 24) >>> 0; +const IMAGE_SIZE = 0x10000, CHUNK = 0x1000; +const EDITIONS = { 1: 'Land', 2: 'Water', 3: 'Sky', 4: 'Jade Forest', 5: 'Tropical', 6: 'Glacier' }; + +// ------------------------------------------------------------------ messages +// English texts; every error and note carries .code and .p so the page can show +// its own translation (keys "fl_" in app.js). +const MSG = { + timeout: 'no answer from the device ({c} {a})', + noAck: 'the device does not answer. Is it on the download screen?', + repeats: 'too many repeats while loading', + devCancel: 'the device cancelled loading', + unexpected: 'unexpected answer: {r}', + hello: 'unexpected HELLO answer', + notReady: 'flash not ready', + readErr: 'read error at {a}', + noCrc: 'no checksum at {a}', + cancelled: 'cancelled', + size: 'the image must be exactly 16 MB', + notParadise: 'not a Paradise image (SONIXDEV missing)', + cancelledWrite: 'cancelled. Keep the device switched on and write again', + notAccepted: 'sector {a} not accepted. Keep the device switched on and write again', + differs: 'sector {a} differs after writing. Keep the device switched on and write again', + checkFail: 'check failed at {a}. Keep the device switched on and write again', + rescueBusy: 'the rescue area (0xFF0000) is in use', + rescueFail: 'the rescue start was not written correctly', + noRescue: 'no rescue start: 0xFF0000 is in use', + noRescueRoom: 'no room for the write protection (rescue start, top 64 KB of the flash). Nothing was written. Remove a program from the start device and write again', + rescueMode: 'the last write was cut off. The device waits in the flash screen: write again', + noAnswer: 'no answer. Put the device on the download screen and try again', + noData: 'no answer, no data comes in from the adapter. Put the device on the download screen and try again. Still nothing: check the cable and the adapter driver', + garbled: 'data comes in, but it is not readable ({n} bytes: {h}). Check the cable (TX and RX) and the adapter driver', + lost: 'the device stopped answering before writing. Nothing was written. Switch the Paradise off and on, put it on the download screen, connect again and write again', + appSilent: 'the flash app was sent but does not answer. Try again', + unknownEd: 'unknown edition in the new ROM, untick "keep saves"', + otherEd: 'the device is {d}, the new ROM is {r}. Untick "keep saves" to switch the edition', + noteNoFit: 'field {f} does not fit into the new slot and is not kept', + noteMoved: 'field {f} moved to the new slot', + noteDropped: 'the new ROM has no field menu, stored fields on the device are dropped', + noteEdKept: 'the device is {d}, the new ROM is {r}: same firmware, the device keeps its save and its field ({d})', + noteSaveMoved: 'save of {n} taken along', + noteEmu: 'TamaEmu firmware chosen again, the emulator starts fresh. For an update just open the ROM and save it', +}; +function fill(m, p) { if (p) for (const k of Object.keys(p)) m = m.split('{' + k + '}').join(p[k]); return m; } +function fe(code, p) { const e = new Error(fill(MSG[code], p)); e.code = code; e.p = p; return e; } +function note(code, p) { return { code, p, text: fill(MSG[code], p) }; } +const hex = (v) => '0x' + v.toString(16); + +// ------------------------------------------------------------------ helpers +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } +const ascii = (s) => Uint8Array.from(s, (c) => c.charCodeAt(0)); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +function b64(s) { + if (typeof atob === 'function') { const t = atob(s); const o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; } + return new Uint8Array(Buffer.from(s, 'base64')); +} + +const CRC_TAB = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })(); +function crc32(d, a = 0, n = d.length - a) { let c = 0xFFFFFFFF; for (let i = a; i < a + n; i++) c = (c >>> 8) ^ CRC_TAB[(c ^ d[i]) & 255]; return (c ^ 0xFFFFFFFF) >>> 0; } +function crc16(d) { let c = 0; for (const b of d) { c ^= b; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xA001 : c >>> 1; } return c; } +async function sha256(d) { return new Uint8Array(await root.crypto.subtle.digest('SHA-256', d)); } + +function cobsEncode(d) { + const o = new Uint8Array(d.length + Math.ceil(d.length / 254) + 3); + let n = 1, ci = 1, code = 1; o[0] = 0; // leading delimiter + o[n++] = 0; + for (const b of d) { + if (b !== 0) { o[n++] = b; code++; if (code === 255) { o[ci] = code; ci = n; o[n++] = 0; code = 1; } } + else { o[ci] = code; ci = n; o[n++] = 0; code = 1; } + } + o[ci] = code; o[n++] = 0; + return o.subarray(0, n); +} +function cobsDecode(f, len) { + const o = new Uint8Array(len); let n = 0, i = 0; + while (i < len) { + const code = f[i++]; if (code === 0) continue; + for (let k = 1; k < code && i < len; k++) o[n++] = f[i++]; + if (code !== 255 && i < len) o[n++] = 0; + } + return o.subarray(0, n); +} + +// ------------------------------------------------------------------ link +/** One serial line: PAU1 frames and text lines are parsed from the same bytes. */ +class Link { + constructor(io, opts = {}) { + this.io = io; this.scale = opts.timeScale || 1; + this.session = (Math.random() * 0x7FFFFFFF | 0) + 1; this.seq = 0; + this.asm = new Uint8Array(0x10000); this.an = 0; + this.line = []; this.lines = []; this.frames = []; this.wake = null; + io.onData = (d) => this.feed(d); + } + feed(d) { + for (let i = 0; i < d.length; i++) { + const b = d[i]; + if (b === 0) { if (this.an) { const f = this.parse(cobsDecode(this.asm, this.an)); if (f) this.frames.push(f); } this.an = 0; } + else if (this.an < this.asm.length) this.asm[this.an++] = b; else this.an = 0; + if (b === 10) { const s = String.fromCharCode(...this.line).trim(); this.line = []; if (s) this.lines.push(s); } + else if (b !== 13) { if (this.line.length < 200 && b >= 32 && b < 127) this.line.push(b); else if (this.line.length >= 200 || b < 32 || b >= 127) this.line = []; } + } + if (this.wake) { const w = this.wake; this.wake = null; w(); } + } + parse(d) { + if (d.length < 28 || d[0] !== 0x50 || d[1] !== 0x41 || d[2] !== 0x55 || d[3] !== 0x31) return null; + const plen = d[20] | (d[21] << 8); + if (d.length < 28 + plen || u32(d, 24 + plen) !== crc32(d, 0, 24 + plen)) return null; + return { type: d[6], seq: u32(d, 12), off: u32(d, 16), status: d[22] | (d[23] << 8), payload: d.slice(24, 24 + plen) }; + } + async until(test, ms, what) { + const end = Date.now() + ms * this.scale; + for (;;) { + const r = test(); if (r) return r; + const left = end - Date.now(); if (left <= 0) throw new TimeoutError(what); + await new Promise((res) => { const t = setTimeout(() => { this.wake = null; res(); }, Math.min(left, 500)); this.wake = () => { clearTimeout(t); res(); }; }); + } + } + clear() { this.lines = []; this.frames = []; this.line = []; this.an = 0; } + async writeLine(s) { await this.io.write(ascii(s + '\r\n')); } + waitLine(ms) { return this.until(() => this.lines.shift(), ms, { c: 'line', a: '' }); } + frame(type, seq, off, payload) { + const d = new Uint8Array(28 + payload.length); + d.set([0x50, 0x41, 0x55, 0x31, 1, 1, type, 0]); + w32(d, 8, this.session); w32(d, 12, seq); w32(d, 16, off); + d[20] = payload.length & 255; d[21] = payload.length >> 8; + d.set(payload, 24); w32(d, 24 + payload.length, crc32(d, 0, 24 + payload.length)); + return cobsEncode(d); + } + /** Send one PAU1 request and wait for the matching reply. */ + async request(type, off, payload = new Uint8Array(0), ms = 6000) { + const seq = ++this.seq; + await this.io.write(this.frame(type, seq, off >>> 0, payload)); + return this.until(() => { + while (this.frames.length) { const f = this.frames.shift(); if (f.type === type && f.seq === seq && f.off === off >>> 0) return f; } + return null; + }, ms, { c: type, a: hex(off >>> 0) }); + } +} +class TimeoutError extends Error { constructor(what) { super(fill(MSG.timeout, what)); this.code = 'timeout'; this.p = what; } } + +// ------------------------------------------------------------------ app loading +/** Make a PDLO file from a raw image (up to 64 KB, runs from PRAM 0). */ +function buildPdlo(img) { + const head = new Uint8Array(16); head.set(ascii('PDLO')); w32(head, 4, IMAGE_SIZE / 4); head.set(ascii(PDLO_TOKEN), 8); + const body = new Uint8Array(IMAGE_SIZE); body.set(img.subarray(0, IMAGE_SIZE)); + const f = new Uint8Array(16 + IMAGE_SIZE); f.set(head); f.set(body, 16); + for (let i = 0; i < f.length; i += 4) w32(f, i, u32(f, i) ^ PDLO_XOR); + return f; +} +let keystream = null; +async function chunk(idx, payload) { + const nonce = new Uint8Array([1, 0, 0, 0]); + if (!keystream) { const s = new Uint8Array(4 + 32); s.set(nonce); s.set(ascii(LINK_KEY), 4); keystream = await sha256(s); } + const body = new Uint8Array(12 + payload.length); + body.set(ascii('TCP'), 4); body[7] = 3; body[8] = idx & 255; body[9] = 255 - (idx & 255); + const c = crc16(payload); body[10] = c & 255; body[11] = c >> 8; + body.set(payload, 12); + const k = keystream.slice(); + for (let i = 0; i < body.length; i++) { const j = i % 32; body[i] ^= k[j]; k[j] = (k[j] * 2 + 1) & 255; } + const out = new Uint8Array(4 + body.length); out.set(nonce); out.set(body, 4); + return out; +} +/** Is the device on the download screen? */ +/* 1.7.2 PROBE_RETRY: some adapters (PL2303) lose or garble the first bytes after opening, and the hello frame before + * has no line end: the line is ended first, three tries, any line before the answer is skipped */ +const PROBE_RETRY = true; +async function probe(link) { + if (!PROBE_RETRY) { link.clear(); await link.writeLine('ECHO REQ'); try { return (await link.waitLine(2000)).startsWith('ECHO REP'); } catch (e) { return false; } } + for (let t = 0; t < 3; t++) { + await link.io.write(ascii('\r\n')); await sleep(150 * link.scale); link.clear(); + await link.writeLine('ECHO REQ'); + const end = Date.now() + 2000 * link.scale; + for (;;) { + const left = end - Date.now(); if (left <= 0) break; + let l = ''; try { l = await link.waitLine(left / link.scale); } catch (e) { break; } + if (l.indexOf('ECHO REP') >= 0) return true; + } + } + return false; +} +/** Load an image into the device (download screen) and start it. */ +async function loadApp(link, img, progress) { + const file = buildPdlo(img); + link.clear(); await link.writeLine('PKT ' + file.length); + const a = await link.waitLine(4000).catch(() => ''); + if (!a.startsWith('ACK')) throw fe('noAck'); + let idx = 0, guard = 0; + while (idx * CHUNK < file.length) { + if (++guard > 200) throw fe('repeats'); + const off = idx * CHUNK, n = Math.min(CHUNK, file.length - off); + await link.io.write(await chunk(idx, file.subarray(off, off + n))); + const r = await link.waitLine(6000); + if (r.startsWith('ACK')) { idx++; if (progress) progress(Math.min(idx * CHUNK, file.length), file.length); } + else if (r.startsWith('ENQ')) { const e = parseInt(r.slice(3), 10); if (!isNaN(e)) idx = e; } + else if (r.startsWith('NAK')) { /* same chunk again */ } + else if (r.startsWith('CAN')) throw fe('devCancel'); + else throw fe('unexpected', { r }); + } +} + +// ------------------------------------------------------------------ rescue start +/* + * 1.6.13 test13 (PARA_RESCUE): a second load table at 0xFFE000 starts our flash app from 0xFF0000 (not encrypted, + * CRC-32 of 0xE000 bytes) when the device's own table or firmware does not check out. A device whose own table or firmware is broken (write cut off) then shows the flash screen and + * can be written again from the Studio, without the download screen. + * RESCUE_FIRST: before writing, the device's own table is cleared once the rescue start is in place, so the device + * comes up in the flash app whenever the write is cut off; the table is written back last. Only after the test + * on the device (rescueTest) showed that the ROM takes the second table. + */ +const PARA_RESCUE = true, RESCUE_FIRST = true, SECTOR_RETRY = true; // SECTOR_RETRY: test16, see putSector // test15: RESCUE_FIRST on (test13 on the device: the ROM took the second table) +const RESCUE_OFF = 0xFF0000, RESCUE_TAB = 0xFFE000, RESCUE_CODE = 0xE000; +/* test23 BAT_PIC: the Paradise's "battery empty" picture in the last sector of the rescue block (0xFFF000), for the + * emulators to show before they switch off on empty batteries: "BAT1", byte count, 16 colours (RGB565), then one byte + * per run (colour << 4 | length - 1), 128 x 128 row by row. The sprite's number differs by edition. */ +const BAT_PIC = true, BATPIC_OFF = 0xFFF000, BATPIC_IDX = { 'Land': 53, 'Water': 53, 'Sky': 53, 'Jade Forest': 54, 'Tropical': 56, 'Glacier': 56 }; +function batPic(img) { + const C = root.ParamixCore || (typeof require !== 'undefined' ? require('./core.js') : null); + if (!BAT_PIC || !C) return null; + try { + const ctx = C.openRom(img), i = BATPIC_IDX[ctx.edition]; + if (i === undefined || !ctx.entries[i]) return null; + const s = C.spriteDecode(ctx.entries[i]).subs[0]; + if (s.w !== 128 || s.h !== 128) return null; + const pal = [], px = new Uint8Array(128 * 128); + for (let k = 0; k < px.length; k++) { + const d = s.data, c = d[4 * k + 3] ? ((((d[4 * k] * 31 + 127) / 255) | 0) << 11) | ((((d[4 * k + 1] * 63 + 127) / 255) | 0) << 5) | (((d[4 * k + 2] * 31 + 127) / 255) | 0) : 0xFFFF; + let j = pal.indexOf(c); if (j < 0) { if (pal.length >= 16) return null; j = pal.push(c) - 1; } + px[k] = j; + } + const out = new Uint8Array(SECTOR).fill(0xFF); let n = 0; + for (let k = 0; k < px.length; ) { + let r = 1; while (r < 16 && k + r < px.length && px[k + r] === px[k]) r++; + if (40 + n >= SECTOR) return null; + out[40 + n++] = (px[k] << 4) | (r - 1); k += r; + } + w32(out, 0, 0x31544142); w32(out, 4, n); + for (let j = 0; j < 16; j++) { const c = pal[j] || 0; out[8 + 2 * j] = c & 255; out[9 + 2 * j] = c >> 8; } + return out; + } catch (e) { return null; } +} +/* 1.7.2: a ROM without the Paradise has no picture of its own: the same sector with our text instead (white on black, + * "BATTERY EMPTY, SHUTTING DOWN", own 5 x 7 letters at twice the size) */ +const BAT_FONT = { A: '01110100011000111111100011000110001', B: '11110100011000111110100011000111110', D: '11110100011000110001100011000111110', + E: '11111100001000011110100001000011111', G: '01110100011000010111100011000101111', H: '10001100011000111111100011000110001', + I: '01110001000010000100001000010001110', M: '10001110111010110101100011000110001', N: '10001110011010110011100011000110001', + O: '01110100011000110001100011000101110', P: '11110100011000111110100001000010000', R: '11110100011000111110101001001010001', + S: '01111100001000001110000010000111110', T: '11111001000010000100001000010000100', U: '10001100011000110001100011000101110', + W: '10001100011000110101101011010101010', Y: '10001100010101000100001000010000100' }; +function batText() { + const px = new Uint8Array(128 * 128), lines = ['BATTERY', 'EMPTY', 'SHUTTING', 'DOWN']; + lines.forEach((ln, li) => { + const w = ln.length * 12 - 2, x0 = (128 - w) >> 1, y0 = 22 + li * 22; + for (let c = 0; c < ln.length; c++) { + const g = BAT_FONT[ln[c]]; if (!g) continue; + for (let y = 0; y < 7; y++) for (let x = 0; x < 5; x++) if (g[y * 5 + x] === '1') + for (let dy = 0; dy < 2; dy++) for (let dx = 0; dx < 2; dx++) px[(y0 + 2 * y + dy) * 128 + x0 + c * 12 + 2 * x + dx] = li < 2 ? 1 : 2; + } + }); + const out = new Uint8Array(SECTOR).fill(0xFF); let n = 0; + for (let k = 0; k < px.length; ) { + let r = 1; while (r < 16 && k + r < px.length && px[k + r] === px[k]) r++; + out[40 + n++] = (px[k] << 4) | (r - 1); k += r; + } + w32(out, 0, 0x31544142); w32(out, 4, n); + const pal = [0x0000, 0xFFFF, 0xA514]; + for (let j = 0; j < 16; j++) { const c = pal[j] || 0; out[8 + 2 * j] = c & 255; out[9 + 2 * j] = c >> 8; } + return out; +} +function rescueBlock(app, hdr, pic) { + if (!app || app.length > RESCUE_CODE || !hdr || hdr.length < SECTOR || String.fromCharCode(...hdr.subarray(0, 8)) !== 'SONIXDEV') return null; + const b = new Uint8Array(BLOCK64).fill(0xFF); + b.set(app, 0); + if (pic && pic.length === SECTOR) b.set(pic, BATPIC_OFF - RESCUE_OFF); // test23: not part of the start (CRC_CHK_SUM covers the code only) + const t = new Uint8Array(hdr.subarray(0, SECTOR)); + w32(t, 0x08, u32(t, 0x08) & ~1); // LOAD_CFG: not encrypted (CRC check stays on) + w32(t, 0x10, 0x60000000 + RESCUE_OFF); // ADDR_USERCODE + w32(t, 0x14, RESCUE_CODE); // SIZE_USERCODE + w32(t, 0x24, crc32(b, 0, RESCUE_CODE)); // CRC_CHK_SUM + t.fill(0, 0x80, 0x84); // encrypter mark off + b.set(t, RESCUE_TAB - RESCUE_OFF); + return b; +} +const allFF = (d, a, n) => { for (let i = a; i < a + n; i++) if (d[i] !== 0xFF) return false; return true; }; +/* test18 RESCUE_OLD: a rescue start of an earlier Studio (other flash app) is ours too and is renewed. Before, an image + * read from such a device counted 0xFF0000 as taken and the Studio refused to write at all ("no room"). */ +const RESCUE_OLD = true; +function isRescue(d, base = 0) { + const t = base + RESCUE_TAB - RESCUE_OFF; + return String.fromCharCode(...d.subarray(t, t + 8)) === 'SONIXDEV' && u32(d, t + 0x10) === 0x60000000 + RESCUE_OFF && u32(d, t + 0x14) === RESCUE_CODE; +} +/** The image with the rescue start, or null when 0xFF0000 holds something else. */ +/* CLEAN_ROM: a ROM without the Paradise has no battery picture of its own, it shows a short text */ +function batFor(img) { + const F = root.ParamixFeld || (typeof require !== 'undefined' ? require('./feld.js') : null); + return F && F.isClean && F.isClean(img) ? batText() : batPic(img); +} +function withRescue(img, app) { + const F = root.ParamixFeld || (typeof require !== 'undefined' ? require('./feld.js') : null); + const rb = rescueBlock(app, img.subarray(0, SECTOR), batFor(img)); + if (!rb) return null; + let same = true; for (let i = 0; i < BLOCK64; i++) if (img[RESCUE_OFF + i] !== rb[i]) { same = false; break; } + if (same) return img; + if (!allFF(img, RESCUE_OFF, BLOCK64) && !(RESCUE_OLD && isRescue(img, RESCUE_OFF))) return null; + const out = new Uint8Array(img); out.set(rb, RESCUE_OFF); return out; +} + +/* + * test15: T18Emu installed before test13 with its hot window has a firmware block at 0xFF0000. That block's guest + * moves into the hot slot of the least used one (0xF0 up), that one's guest into T18Emu's last spare (which must be + * unused), and the spare list gets one shorter: 0xFF0000 is free, the save stays. Only guest blocks the game never + * wrote (stored map = settings map) move; the stored map ("T8MP" in its save area) is patched after the save was + * taken from the device. moves: [{ c, so, ns, list: [{ g, from, to }] }] + */ +const T18M = 0x38584D50, T8MP = 0x504D3854, T8SS = 0x53533854, T8_SOFF = 4 + 256 + 64; +const rd16 = (b, o) => b[o] | (b[o + 1] << 8); +const wr16 = (b, o, v) => { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; }; +function t18Relocate(image, bases) { + const moves = []; + for (const base of bases || []) { + const c = base + 0x140; if (u32(image, c) !== T18M) continue; + const ns = Math.min(u32(image, c + 12), 64), so = u32(image, c + 8); + const mapIdx = (b) => { for (let i = 0; i < 128; i++) if (rd16(image, c + 16 + 2 * i) === b) return i; return -1; }; + let sp0 = false; for (let i = 0; i < ns; i++) if (rd16(image, c + 272 + 2 * i) === 0xFF) sp0 = true; + const top = mapIdx(0xFF); + if (top < 0 && !sp0) continue; + if (sp0 || ns < 2) return null; + const S = rd16(image, c + 272 + 2 * (ns - 1)), list = []; + let L = -1, gl = -1; + if (image[c + 400] & 4) for (let b = 0xF0; b <= 0xFC; b++) { const g = mapIdx(b); if (g >= 0) { L = b; gl = g; break; } } + const mv = (from, to, g) => { image.copyWithin(to << 16, from << 16, (from + 1) << 16); wr16(image, c + 16 + 2 * g, to); list.push({ g, from, to }); }; + if (L >= 0) { mv(L, S, gl); mv(0xFF, L, top); } else mv(0xFF, S, top); + image.fill(0xFF, 0xFF0000, 0x1000000); + w32(image, c + 12, ns - 1); wr16(image, c + 272 + 2 * (ns - 1), 0xFFFF); + moves.push({ c, so, ns, S, list }); + } + return moves; +} +/* the device's settings block (d at dc) as it reads after the moves of the T18Emu at c (for comparing) */ +function t18Moved(d, dc, moves, c) { + const m = moves && moves.find((x) => x.c === c); if (!m) return { d, dc }; + const t = new Uint8Array(d.subarray(dc, dc + 0x200)); + for (const { g, from, to } of m.list) if (rd16(t, 16 + 2 * g) === from) wr16(t, 16 + 2 * g, to); + if (u32(t, 12) === m.ns && rd16(t, 272 + 2 * (m.ns - 1)) === m.S) { w32(t, 12, m.ns - 1); wr16(t, 272 + 2 * (m.ns - 1), 0xFFFF); } + return { d: t, dc: 0 }; +} +/* after the save was taken over: the moved guests must be unwritten and the last spare unused; patch the stored map */ +function t18MovesFinish(image, moves) { + const secs = new Set(); + for (const m of moves) { + const t8 = u32(image, m.so) === T8MP; + if (t8) { + if (image[m.so + 4 + 256 + m.ns - 1]) return null; // the spare is in use + if (u32(image, m.so + T8_SOFF) === T8SS) for (let r = 0; r < 19; r++) for (let j = 0; j < 16; j++) { const v = image[m.so + T8_SOFF + 132 + 16 * r + j]; if (v && ((v - 1) >> 4) === m.ns - 1) return null; } + for (const { g, from, to } of m.list) { const v = rd16(image, m.so + 4 + 2 * g); if (v !== from && v !== to) return null; } // the game wrote that block (to: moved before) + for (const { g, to } of m.list) wr16(image, m.so + 4 + 2 * g, to); + secs.add(m.so); + } + secs.add(m.c & ~0xFFF); + for (const { to } of m.list) for (let s = to << 16; s < (to + 1) << 16; s += SECTOR) secs.add(s); + } + for (let s = 0xFF0000; s < 0x1000000; s += SECTOR) secs.add(s); + return secs; +} + +// ------------------------------------------------------------------ device +class Paradise { + constructor(link) { this.link = link; this.info = null; } + get block() { const b = this.info.maxBlock; return b === 1024 || b === 2048 || b === 4096 ? b : 1024; } + async hello(ms = 6000) { + const r = await this.link.request(HELLO, 0, undefined, ms); + const p = r.payload; if (p.length !== 44) throw fe('hello'); + this.info = { edition: p[8], wave: p[9], maxBlock: p[10] | (p[11] << 8), jedec: u32(p, 24), capacity: u32(p, 32), flashError: u32(p, 36) }; + // The flash app always reports 1 (Land). The real edition is the ID page in the flash + // (0xD49000, Tropical/Glacier 0xD29000), read like the Studio reads a ROM (1.3.0). + try { + // 1.7.3 test11: Tropical/Glacier first, with the page's footer (C minus ID, inverse): a Glacier was taken for Land + // (its save data at 0xD49000 can begin with 1..6) + const C = [0, 0x70169E2C, 0x70169E2C, 0x70169E2C, 0x849633DB, 0x96CB83B8, 0x96CB83B8]; + const ok = async (p, ids) => { const a = await this.read(p, 4), v = u32(a, 0); if (!ids.includes(v)) return 0; + const f = await this.read(p + 0xFF8, 8), k = u32(f, 0); return ((k + v) >>> 0) === C[v] && u32(f, 4) === (~k >>> 0) ? v : -v; }; + const g = await ok(0xD29000, [5, 6]), l = g > 0 ? 0 : await ok(0xD49000, [1, 2, 3, 4]); + const c = g > 0 || l > 0 ? 0 : await ok(0xEFD000, [1, 2, 3, 4, 5, 6]); // 1.7.3 test13: a clean ROM's ID page + const v = g > 0 ? g : l > 0 ? l : c > 0 ? c : l < 0 ? -l : g < 0 ? -g : 0; + if (v) this.info.edition = v; + } catch (e) { if (!(e instanceof TimeoutError)) throw e; } + this.info.name = EDITIONS[this.info.edition] || 'Edition ' + this.info.edition; + return this.info; + } + ready() { if (!this.info || this.info.capacity !== FLASH_SIZE || this.info.flashError) throw fe('notReady'); } + async read(off, len) { + const out = new Uint8Array(len), blk = this.block; + for (let o = 0; o < len; o += blk) { + let r = null; + for (let t = 0; t < 5 && !r; t++) { + try { const x = await this.link.request(READ, off + o, u32le(blk)); if (x.payload.length === blk && !x.status) r = x; } + catch (e) { if (!(e instanceof TimeoutError)) throw e; } + } + if (!r) throw fe('readErr', { a: hex(off + o) }); + out.set(r.payload.subarray(0, Math.min(blk, len - o)), o); + } + return out; + } + async crc(off, len) { + for (let t = 0; t < 4; t++) { + try { const c = await this.link.request(CRC, off, u32le(len), 15000); if (c.payload.length === 4 && !c.status) return u32(c.payload, 0); } + catch (e) { if (!(e instanceof TimeoutError)) throw e; } + } + throw fe('noCrc', { a: hex(off) }); + } + /** Seconds counter of the Paradise (1.3.0 flash app). null if the app is older. */ + async clockRead() { + try { const r = await this.link.request(CLOCK_READ, 0, undefined, 2500); if (r.payload.length === 8) return { counter: u32(r.payload, 0), ctrl: u32(r.payload, 4) }; } + catch (e) { if (!(e instanceof TimeoutError)) throw e; } + return null; + } + /** Set the seconds counter. Returns true if the device took it. */ + async clockSet(v) { + try { const r = await this.link.request(CLOCK_SET, 0, u32le(v >>> 0), 2500); return r.payload.length === 4 && !r.status && u32(r.payload, 0) - v < 5; } + catch (e) { if (!(e instanceof TimeoutError)) throw e; } + return false; + } + /** Which 4 KB sectors in [from, to) are not empty (0xFF)? Uses the CRC, reads nothing. */ + async usedSectors(from, to, progress, cancel) { + const ff = new Uint8Array(BLOCK64).fill(0xFF), cB = crc32(ff, 0, BLOCK64), cS = crc32(ff, 0, SECTOR), out = []; + for (let off = from & ~(BLOCK64 - 1); off < to; off += BLOCK64) { + if (cancel && cancel()) throw fe('cancelled'); + if (await this.crc(off, BLOCK64) !== cB) for (let s = off; s < off + BLOCK64; s += SECTOR) if (s >= from && s < to && await this.crc(s, SECTOR) !== cS) out.push(s); + if (progress) progress('compare', off + BLOCK64 - from, to - from); + } + return out; + } + /** Writer state; asked again a few times, then a ping (1.5.6: a lost answer here broke the write). */ + async writeState() { + for (let t = 0; t < 3; t++) { + try { return await this.link.request(WRITE_STATE, 0, undefined, 6000); } + catch (e) { if (!(e instanceof TimeoutError)) throw e; } + try { await this.link.request(HELLO, 0, undefined, 3000); } catch (e) { if (!(e instanceof TimeoutError)) throw e; } + } + throw fe('lost'); + } + /** Write single 4 KB sectors (Map address -> data), checked one by one. */ + async writeSectors(map, progress, cancel, guard) { + this.ready(); + let jobs = [...map.keys()].sort((a, b) => a - b).map((s) => [s, map.get(s)]), extra = 0; + // test15: with the rescue start on the device, its own table is off while the pages are written, back last + if (guard && PARA_RESCUE && RESCUE_FIRST && !map.has(0)) { + const hdr = await this.read(0, SECTOR), rb = rescueBlock(guard, hdr, BAT_PIC ? new Uint8Array(await this.read(BATPIC_OFF, SECTOR)) : null); // test23: the picture there as it is + if (rb && await this.crc(RESCUE_OFF, BLOCK64) === crc32(rb)) { jobs = [[0, new Uint8Array(SECTOR).fill(0xFF)]].concat(jobs, [[0, hdr]]); extra = 2; } + } + const st = await this.writeState(); + if (!(st.payload.length >= 16 && u32(st.payload, 12))) await this.link.request(WRITE_TEST, 0, undefined, 15000); + await this.link.request(WRITE_BEGIN, 0, new Uint8Array(36), 15000); + const blk = this.block; + let n = 0; + for (let q = 0; q < jobs.length; q++) { + if (cancel && cancel()) { // the table always comes back + if (!extra || n === jobs.length - 1) throw fe('cancelledWrite'); + if (n) { jobs = jobs.slice(0, n).concat([jobs[jobs.length - 1]]); cancel = null; } + else throw fe('cancelledWrite'); + } + const [s, d] = jobs[q]; + await this.putSector(s, d); + n++; if (progress) progress('write', n, jobs.length); + } + await this.link.request(WRITE_FINISH, 0, undefined, 15000); + return n - extra; + } + /** The steps that move T18Emu's block from 0xFF0000 on the device (see write), as [address, 4 KB] in order. */ + async t18Pre(image, moves) { + const out = []; + for (const m of moves) { + const cs = m.c & ~(SECTOR - 1), co = m.c - cs, dc = new Uint8Array(await this.read(cs, SECTOR)); + if (u32(dc, co) !== T18M || u32(dc, co + 12) !== m.ns || rd16(dc, co + 272 + 2 * (m.ns - 1)) !== m.S) continue; // another T18Emu on the device + if (!m.list.every(({ g, from }) => rd16(dc, co + 16 + 2 * g) === from)) continue; + const dt = new Uint8Array(await this.read(m.so, SECTOR)), t8 = u32(dt, 0) === T8MP; + const blk = (b) => { for (let a = b << 16; a < (b + 1) << 16; a += SECTOR) out.push([a, image.slice(a, a + SECTOR)]); }; + // with a stored map that map is what T18Emu follows: only it changes here, the settings block (in the sector with + // the program's start) comes later with the rest, after the rescue start is in place and the table is off + const step = (k) => { + const { g, to } = m.list[k]; + blk(to); + if (t8) { wr16(dt, 4 + 2 * g, to); out.push([m.so, dt.slice()]); return; } + if (k === 0) { w32(dc, co + 12, m.ns - 1); wr16(dc, co + 272 + 2 * (m.ns - 1), 0xFFFF); } + wr16(dc, co + 16 + 2 * g, to); out.push([cs, dc.slice()]); + }; + for (let k = 0; k < m.list.length; k++) step(k); + } + return out; + } + /** + * One 4 KB sector: data packets, then the commit with the sector's CRC-32; the device erases, programs, reads back + * and compares. test16 (SECTOR_RETRY): a lost answer is asked again (both steps can be repeated without harm), and a + * flash app that checks the buffer first (status 2: the buffer does not match, nothing written) gets the sector again. + */ + async putSector(s, d) { + const blk = this.block, want = crc32(d, 0, SECTOR); + const ask = async (type, off, pl, ms) => { + for (let t = 0; ; t++) { + try { return await this.link.request(type, off, pl, ms); } + catch (e) { if (!(SECTOR_RETRY && e instanceof TimeoutError && t < 2)) throw e; } + } + }; + for (let t = 0; t < (SECTOR_RETRY ? 3 : 1); t++) { + for (let o = 0; o < SECTOR; o += blk) await ask(WRITE_DATA, s + o, d.subarray(o, o + blk), SECTOR_RETRY ? 5000 : 15000); + const c = await ask(WRITE_COMMIT, s, u32le(want), 15000); + if (c.payload.length !== 8) throw fe('notAccepted', { a: hex(s) }); + const st = u32(c.payload, 4); + if (st === 2 && SECTOR_RETRY) continue; // the device's buffer did not match: send again + if (st || u32(c.payload, 0) !== want) throw fe('differs', { a: hex(s) }); + return; + } + throw fe('differs', { a: hex(s) }); + } + /** Rescue start in place on the device? 'ok', 'free' (0xFF0000 empty) or 'busy'. */ + async rescueState(block) { + if (await this.crc(RESCUE_OFF, BLOCK64) === crc32(block)) return 'ok'; + if (RESCUE_OLD && isRescue(new Uint8Array(await this.read(RESCUE_TAB, SECTOR)), RESCUE_OFF - RESCUE_TAB)) return 'free'; // an older one: renewed + return (await this.usedSectors(RESCUE_OFF, FLASH_SIZE)).length ? 'busy' : 'free'; + } + async rescueInstall(block, progress, cancel) { + const m = new Map(); for (let s = 0; s < BLOCK64; s += SECTOR) m.set(RESCUE_OFF + s, block.subarray(s, s + SECTOR)); + await this.writeSectors(m, progress, cancel); + if (await this.crc(RESCUE_OFF, BLOCK64) !== crc32(block)) throw fe('rescueFail'); + } + /** + * Test on the device (1.6.13 test13): rescue start in place, then the device's own table (sector 0) cleared. + * Returns the cleared sector 0, to be written back with rescueRestore after the restart. + */ + async rescueTest(app, progress, cancel) { + this.ready(); + const hdr = await this.read(0, SECTOR), block = rescueBlock(app, hdr); + if (!block) throw fe('notParadise'); + const st = await this.rescueState(block); + if (st === 'busy') throw fe('rescueBusy'); + if (st === 'free') await this.rescueInstall(block, progress, cancel); + await this.writeSectors(new Map([[0, new Uint8Array(SECTOR).fill(0xFF)]]), progress, cancel); + return hdr; + } + async rescueRestore(hdr, progress, cancel) { + this.ready(); + if (String.fromCharCode(...hdr.subarray(0, 8)) !== 'SONIXDEV') throw fe('notParadise'); + await this.writeSectors(new Map([[0, hdr.subarray(0, SECTOR)]]), progress, cancel); + if (await this.crc(0, SECTOR) !== crc32(hdr, 0, SECTOR)) throw fe('checkFail', { a: hex(0) }); + } + /** Whole flash (16 MB). */ + async dump(progress, cancel) { + this.ready(); + const img = new Uint8Array(FLASH_SIZE); + for (let off = 0; off < FLASH_SIZE; off += BLOCK64) { + if (cancel && cancel()) throw fe('cancelled'); + img.set(await this.read(off, BLOCK64), off); + if (progress) progress('read', off + BLOCK64, FLASH_SIZE); + } + return img; + } + /** Sectors (4 KB offsets) where the device differs from img, in [from, to). */ + async changed(img, progress, cancel, from = 0, to = FLASH_SIZE) { + const out = new Set(); + for (let off = from; off < to; off += BLOCK64) { + if (cancel && cancel()) throw fe('cancelled'); + if (await this.crc(off, BLOCK64) !== crc32(img, off, BLOCK64)) { + for (let s = off; s < off + BLOCK64; s += SECTOR) if (await this.crc(s, SECTOR) !== crc32(img, s, SECTOR)) out.add(s); + } + if (progress) progress('compare', off + BLOCK64 - from, to - from); + } + return out; + } + /** + * Write img. opts: { onlyChanged, keep (function from keepPlan or null) }. + * Returns { written, kept, notes, image } (image = what the device holds now). + */ + async write(img, opts, progress, cancel) { + if (img.length !== FLASH_SIZE) throw fe('size'); + if (String.fromCharCode(...img.subarray(0, 8)) !== 'SONIXDEV') throw fe('notParadise'); + this.ready(); + let image = img, notes = [], kept = 0, changed = null, rescue = false, moves = null; + if (PARA_RESCUE && opts.rescueApp) { // test13: the rescue start goes along (first), when 0xFF0000 is free + let r = withRescue(image, opts.rescueApp); + if (!r) { // test15: an old T18Emu layout gives 0xFF0000 up + const w = new Uint8Array(image); moves = t18Relocate(w, opts.t18Bases); + if (moves && moves.length) r = withRescue(w, opts.rescueApp); + if (!r) moves = null; + } + if (r) { image = r; rescue = true; } + else if (opts.rescueNeeded !== false) throw fe('noRescueRoom'); + else notes.push(note('noRescue')); + } + if (opts.onlyChanged || opts.keep || rescue) changed = await this.changed(image, progress, cancel); + if (opts.keep) { + const k = await opts.keep(this, image, changed, moves); + image = k.image; notes = k.notes; kept = k.kept; + for (const s of k.protectedSectors) changed.delete(s); + } + if (moves) { + if (image === img) image = new Uint8Array(image); + const secs = t18MovesFinish(image, moves); + if (!secs) throw fe('noRescueRoom'); + for (const x of secs) if (await this.crc(x, SECTOR) !== crc32(image, x, SECTOR)) changed.add(x); else changed.delete(x); + } + if (rescue) { // the save ranges of "keep saves" reach to the end of the flash: the rescue start wins there + const rb = rescueBlock(opts.rescueApp, image.subarray(0, SECTOR), batFor(image)); + if (image === img) image = new Uint8Array(image); + image.set(rb, RESCUE_OFF); + for (let s = RESCUE_OFF; s < FLASH_SIZE; s += SECTOR) if (await this.crc(s, SECTOR) !== crc32(image, s, SECTOR)) changed.add(s); else changed.delete(s); + } + if (opts.onImage) await opts.onImage(image); // test15: what is written, for going on after a cut + const st = await this.writeState(); + if (!(st.payload.length >= 16 && u32(st.payload, 12))) { if (progress) progress('prepare', 0, 1); await this.link.request(WRITE_TEST, 0, undefined, 15000); } + let order = sectorOrder(); + if (rescue) order = order.filter((s) => s >= RESCUE_OFF).concat(order.filter((s) => s < RESCUE_OFF)); + if (opts.onlyChanged) { + order = order.filter((s) => changed.has(s)); + if (!order.length) { await this.link.request(WRITE_FINISH, 0, undefined, 15000); return { written: 0, kept, notes, image, rescue }; } + } else if (changed) order = order.filter((s) => s >= 0x11000 || s === 0 || changed.has(s)); // test15: the firmware at 0x1000 only when it differs + // RESCUE_FIRST: the device's table off while the rest is written (the ROM starts the rescue then), back at the end + const clear0 = (opts.rescueFirst !== undefined ? opts.rescueFirst : RESCUE_FIRST) && rescue && order.some((s) => s && s < RESCUE_OFF); + if (clear0 && order[order.length - 1] !== 0) order.push(0); + // test15: a moved T18Emu block goes to its new place before the rescue start overwrites 0xFF0000, in steps that + // each leave the device's T18Emu whole (cut anywhere: it still finds every block): new copy, settings, stored map + const pre = moves ? await this.t18Pre(image, moves) : []; + const preDone = new Set(); { const last = new Map(); for (const [a, d] of pre) last.set(a, d); for (const [a, d] of last) if (crc32(d) === crc32(image, a, SECTOR)) preDone.add(a); } + order = order.filter((s) => !preDone.has(s)); + const nRes = order.filter((s) => s >= RESCUE_OFF).length; + const begin = new Uint8Array(36); begin.set(await sha256(image)); w32(begin, 32, crc32(image)); + const pos = await this.link.request(WRITE_BEGIN, 0, begin, 15000); + let start = !opts.onlyChanged && pos.payload.length >= 4 ? u32(pos.payload, 0) : 0; + if (start >= order.length) start = 0; + const blk = this.block; + let written = 0; + for (const [a, d] of pre) { + if (cancel && cancel()) throw fe('cancelledWrite'); + await this.putSector(a, d); + written++; + } + for (let i = start; i < order.length; i++) { + if (cancel && cancel()) throw fe('cancelledWrite'); + const s = order[i]; + if (clear0 && i === Math.max(start, nRes)) { + if (await this.crc(RESCUE_OFF, BLOCK64) !== crc32(image, RESCUE_OFF, BLOCK64)) throw fe('rescueFail'); + const ff = new Uint8Array(SECTOR).fill(0xFF); + await this.putSector(0, ff); + } + await this.putSector(s, image.subarray(s, s + SECTOR)); + written++; + if (progress) progress('write', i + 1 - start, order.length - start); + } + for (let off = 0; off < FLASH_SIZE; off += BLOCK64) { + if (await this.crc(off, BLOCK64) !== crc32(image, off, BLOCK64)) throw fe('checkFail', { a: hex(off) }); + if (progress) progress('check', off + BLOCK64, FLASH_SIZE); + } + await this.link.request(WRITE_FINISH, 0, undefined, 15000); + return { written, kept, notes, image, rescue }; + } +} +const u32le = (v) => { const b = new Uint8Array(4); w32(b, 0, v); return b; }; +function sectorOrder() { + const l = []; + for (let s = FIRST_USER; s < FLASH_SIZE; s += SECTOR) l.push(s); + for (let s = SECTOR; s < FIRST_USER; s += SECTOR) l.push(s); + l.push(0); + return l; +} + +/** Open the device: talk to the flash app, or load it first from the download screen. */ +async function connect(io, appImage, opts = {}, status) { + const link = new Link(io, opts), dev = new Paradise(link); + try { await dev.hello(2500); return { dev, loaded: false }; } + catch (e) { if (!(e instanceof TimeoutError)) throw e; } + if (!(await probe(link))) { + /* 1.7.3 CONN_DIAG: say whether anything came in at all (driver or cable) or only unreadable bytes */ + if (CONN_DIAG && io.rx !== undefined) throw fe(io.rx === 0 ? 'noData' : 'garbled', { n: io.rx, h: io.rxHead }); + throw fe('noAnswer'); + } + if (status) status('load', 0, 1); + await loadApp(link, appImage, (d, t) => status && status('load', d, t)); + await sleep(1200 * (opts.timeScale || 1)); + link.clear(); + for (let t = 0; t < 4; t++) { + try { await dev.hello(4000); return { dev, loaded: true }; } + catch (e) { if (!(e instanceof TimeoutError)) throw e; } + } + throw fe('appSilent'); +} + +// ------------------------------------------------------------------ keep saves +/* + * Which sectors of the new image hold game progress, and is the device's copy + * of them still valid for the new image? Ranges (taken from the device): + * - Paradise save data: from the page after the edition ID page to the end of + * the flash (same edition only, otherwise keeping makes no sense), + * - field slots of the Paramix menu, when the device has the same slot layout + * (a different layout: the stored fields are copied into the new slots), + * - TamaEmu: run state and the guest firmware (holds the guest's own save), + * when the device runs the same guest with the same packing and the guest + * was not changed in the Studio, + * - DOOM: its save sectors, when the device runs DOOM too. + * F and E are the feld.js and emu.js modules, menu = { stub } of the menu (or + * null); opts.emuChanged = guest replaced in the Studio. + */ +/* T18Emu's settings on the device (d at dc) and in the new image (n at nc) describe the same save: same save place, + * block map and spares, where the new one may have more spares behind (test29: spares added keep the save). */ +function t18SameGrown(d, dc, n, nc) { + const eq = (a, len) => { for (let i = 0; i < len; i++) if (d[dc + a + i] !== n[nc + a + i]) return false; return true; }; + const nd = u32(d, dc + 12), nn = u32(n, nc + 12); + if (nd > 64 || nn > 64 || nn < nd) return false; + return eq(8, 4) && eq(16, 256) && eq(272, 2 * nd) && (nn === nd ? eq(272, 128) : true); +} +function keepPlan(F, E, menu, opts = {}) { + return async (dev, img, changed, moves) => { + const ed = F.edition(img); + if (!ed) throw fe('unknownEd'); + // 1.6.6: Land/Water/Sky and Tropical/Glacier are the same firmware; the edition ID page only follows the + // active field. Within such a family the device's ID page and save stay (so the device keeps its field). + const fam = (id) => (F.familyOf ? F.familyOf(id) : null); + const sameFam = dev.info.edition !== ed.id && fam(dev.info.edition) && fam(dev.info.edition) === fam(ed.id); + if (dev.info.edition !== ed.id && !sameFam) throw fe('otherEd', { d: dev.info.name, r: EDITIONS[ed.id] || ed.id }); + const image = new Uint8Array(img), notes = []; + if (sameFam) notes.push(note('noteEdKept', { d: dev.info.name, r: EDITIONS[ed.id] || ed.id })); + // the device's program area (stub, menu, apps), only the sectors that differ + const view = new Uint8Array(img); + for (const s of changed) if (s === 0 || (s >= 0x90000 && s < 0x110000)) view.set(await dev.read(s, SECTOR), s); + // CLEAN_ROM: without the Paradise there is no save of it and no main program at 0x0A0000 (any program may sit + // there); the menu's clock stays when the device is clean too + const clean = !!(F.isClean && F.isClean(img)), dclean = !!(F.isClean && F.isClean(view)), mainOk = !clean && !dclean; + // six fields keep pictures from 0xF00000; a start device (1.6.8) may have programs there (the Paradise never writes there) + const launchImg = !!(menu && F.isLaunch && F.isLaunch(img, menu.stub)); + const ranges = mainOk ? [[ed.profile.idPage + (sameFam ? 0 : SECTOR), (F.isSix && F.isSix(img)) || launchImg ? 0xF00000 : FLASH_SIZE]] : []; + if (clean && dclean) { const ci = F.cleanInfo(img), cd = F.cleanInfo(view); if (ci && cd && ci.clock === cd.clock) ranges.push([ci.clock, ci.clock + SECTOR]); } + // field slots + const fi = menu && F.feldFind(img, menu.stub), fd = menu && F.feldFind(view, menu.stub); + if (fd && (fd.flags & 1)) { + const at = (f, i) => (F.slotAddr ? F.slotAddr(f, i) : f.slotOff + i * f.slotSize); + if (fi && (fi.flags & 1) && fi.slotOff === fd.slotOff && fi.slotSize === fd.slotSize && fi.nslots === fd.nslots && (fi.slotOff2 || 0) === (fd.slotOff2 || 0) && (fi.slotN1 || 0) === (fd.slotN1 || 0)) { + for (let i = 0; i < fd.nslots; i++) ranges.push([at(fd, i), at(fd, i) + fd.slotSize]); + } + else if (fi && (fi.flags & 1) && F.slotReadAsync) { + // other layout: copy every stored field into the new slots (shared pool, 1.2.12) + const slots = []; + for (let i = 0; i < fd.nslots; i++) { + const s = await F.slotReadAsync((a, n) => dev.read(a, n), fd, i); + if (!s) continue; + const idx = fd.version >= 3 ? s.field - 1 : i; + if (idx < 0 || idx >= fi.nslots) { notes.push(note('noteNoFit', { f: s.field })); continue; } + slots.push([idx, s]); + } + // the device's saves replace whatever the new image carries in the slots + for (let i = 0; i < fi.nslots; i++) image.fill(0xFF, at(fi, i), at(fi, i) + fi.slotSize); + const used = new Set(); + for (const [idx, s] of slots) { + try { F.slotPlace(image, fi, idx, s, used); notes.push(note('noteMoved', { f: s.field })); } + catch (e) { notes.push(note('noteNoFit', { f: s.field })); } + } + for (let i = 0; i < fi.nslots; i++) for (let a = at(fi, i); a < at(fi, i) + fi.slotSize; a += SECTOR) if (crc32(image, a, SECTOR) !== crc32(img, a, SECTOR)) changed.add(a); + } else notes.push(note('noteDropped')); + } + const guestR = []; // 1.6.8: TamaEmu firmware areas; sectors the Studio changed there (download items) come from the image + const mine = opts.mine || null; + const mineIn = (a, b) => { if (!mine) return false; for (let x = a & ~(SECTOR - 1); x < b; x += SECTOR) if (mine.has(x)) return true; return false; }; + // TamaEmu: settings block at 0x0A0140 (guest size and block map decide the layout) + const kind = mainOk ? F.appKind(img) : 0, dkind = mainOk ? F.appKind(view) : 0; + const T7 = 0x37584D50, t7i = mainOk && u32(img, 0xA0140) === T7, t7d = mainOk && u32(view, 0xA0140) === T7; + const T18 = 0x38584D50, t18i = mainOk && u32(img, 0xA0140) === T18, t18d = !dclean && u32(view, 0xA0140) === T18, PMXC_ = 0x43584D50, t18keepX = []; + if (t7i && t7d) { + // T7Emu (1.4.0): the pet's EEPROM stays as long as the V7 ROM is the same, the session also needs the same figures + const ro = u32(img, 0xA0148), rl = u32(img, 0xA014C); + let sameRom = ro === u32(view, 0xA0148) && rl === u32(view, 0xA014C); + for (let a = ro & ~0xFFF; sameRom && a < ro + rl; a += SECTOR) if (changed.has(a)) sameRom = false; + if (sameRom && opts.t7Save) ranges.push([0xC5000, 0xC6000]); // an imported save.bin replaces the pet, the settings stay + else if (sameRom) { + ranges.push([0xC1000, 0xC6000]); // EEPROM slots and the settings + if (view.subarray(0xA0148, 0xA0140 + 24 + 16 * 24).every((v, i) => v === img[0xA0148 + i])) ranges.push([0xC0000, 0xC1000]); + } else notes.push(note('noteEmu')); + } else if (mainOk && u32(img, 0xA0140) === 0x31584D50 && u32(view, 0xA0140) === 0x31584D50) { + // V1Emu as the main program (1.6.8): session and settings stay with the same ROM at the same place + const ro = u32(img, 0xA0148), rl = u32(img, 0xA014C), so = u32(img, 0xA0150); + let same = [0x148, 0x14C, 0x150].every((k) => u32(view, 0xA0000 + k) === u32(img, 0xA0000 + k)); + for (let x = ro & ~0xFFF; same && x < ro + rl; x += SECTOR) if (changed.has(x)) same = false; + if (same) ranges.push([so, so + 0x2000]); else { ranges.push([so + 0x1000, so + 0x2000]); notes.push(note('noteEmu')); } + } else if (kind === 2 && dkind === 2 && !t7i && !t7d && !t18i && !t18d && u32(img, 0xA0140) !== 0x31584D50 && u32(view, 0xA0140) !== 0x31584D50) { + // same firmware layout (offset, size, save area, device, block map); the program version may differ + const same = view.subarray(0xA0148, 0xA0140 + 24 + 128).every((v, i) => v === img[0xA0148 + i]); + if (same && !opts.emuChanged) { + const gOff = u32(img, 0xA0148), gLen = u32(img, 0xA014C); + // with the packed firmware also the spare pages behind it (item stores, since v0.9.2) + const end = u32(img, 0xA0144) >= 3 ? Math.min(u32(img, 0xA0140 + 152), 0xD48000) : gOff + gLen; + ranges.push([0xC0000, 0x110000], [gOff, Math.max((gOff + gLen + 0xFFF) & ~0xFFF, end)]); + guestR.push([gOff, Math.max((gOff + gLen + 0xFFF) & ~0xFFF, end)]); + } else notes.push(note('noteEmu')); + } + if (kind === 1 && dkind === 1) ranges.push([0x10E000, 0x110000]); + // more programs of the menu (1.6.0): a save stays when the device has the same program at the same + // place with the same ROM + const xT18 = []; // T18Emu as a further program (start device, 1.6.8): its blocks, like the main one's below + if (menu && F.feldApps) { + const ai = F.feldApps(img, menu.stub).apps, ad = F.feldApps(view, menu.stub).apps; + for (const [ix, a] of ai.entries()) { + const off = a.src - 0x10000000 + 0x11000; + const mag = u32(img, off + 0x140); + if (mag === T18) { + const c = off + 0x140, ns = Math.min(u32(img, c + 12), 64), bl = []; + for (let i = 0; i < 128; i++) { const b = img[c + 16 + 2 * i] | (img[c + 17 + 2 * i] << 8); if (b !== 0xFFFF) bl.push(b); } + const nMap = bl.length; + for (let i = 0; i < ns; i++) bl.push(img[c + 272 + 2 * i] | (img[c + 273 + 2 * i] << 8)); + if (img[c + 400] & 4) bl.push(0xFD, 0xFE); + xT18.push(...bl); + if (!ad.some((d) => d.src === a.src)) continue; + const dv = changed.has(off) ? await dev.read(off, SECTOR) : img.subarray(off, off + SECTOR); + const fwMine = !!opts.t18Imp && bl.slice(0, nMap).some((b) => b < 0x100 && mineIn(b << 16, (b + 1) << 16)); // 1.6.11 test2: an imported firmware with its save + const mvd = t18Moved(dv, 0x140, moves, c); + if (u32(dv, 0x140) === T18 && t18SameGrown(mvd.d, mvd.dc, img, c) && !opts.emuChanged && !fwMine) { + const so = u32(img, c + 8); ranges.push([so, so + 0x24000]); + for (let i = 0; i < ns; i++) { const b = img[c + 272 + 2 * i] | (img[c + 273 + 2 * i] << 8); t18keepX.push([b << 16, (b + 1) << 16]); } + } else notes.push(note('noteEmu')); + continue; + } + if (!ad.some((d) => d.src === a.src)) continue; + const dv = changed.has(off) ? await dev.read(off, SECTOR) : img.subarray(off, off + SECTOR); + { const di = E && E.doomCfg ? E.doomCfg(img, off) : null; // DOOM_FREE (1.7.2 test3): DOOM in the menu, its save and level data stay with the same WAD at the same place + if (di) { + const pi = di.cfg - off, same = u32(dv, 0x140) === PMXC_ && u32(dv, pi) === 0x434D4450 && [8, 12, 16, 20, 24, 28].every((k) => u32(dv, pi + k) === u32(img, di.cfg + k)); + let sameW = same; for (let x = di.romOff & ~0xFFF; sameW && x < di.romOff + di.romLen; x += SECTOR) if (changed.has(x)) sameW = false; + if (sameW) ranges.push([di.saveOff, di.saveOff + 0x2000], [di.regionOff, di.regionOff + di.regionLen]); else if (same) notes.push(note('noteEmu')); + continue; + } } + if (mag === PMXC_ && u32(img, off + 0x144) >= 3) { + // TamaEmu as a further program: run state and spare pages stay with the same firmware layout + const same = u32(dv, 0x140) === PMXC_ && dv.subarray(0x148, 0x140 + 156).every((v, i) => v === img[off + 0x148 + i]); // the flags (+156: clock, NFC) may change + const gOff = u32(img, off + 0x148), gLen = u32(img, off + 0x14C), so = u32(img, off + 0x150), se = u32(img, off + 0x140 + 152); + let sameFw = same; + if (mine && same) { + // 1.6.8: the same firmware when its code blocks (reset vector) are untouched by the Studio; the rest of + // its flash (its own writes) stays from the device, except what the Studio changed (download items) + const rv = u32(img, off + 0x140 + 20) === 0 ? 0 : 0x40; + for (const b of [rv, rv + 1]) { const k = img[off + 0x140 + 24 + b]; if (k === 0xFF) continue; const kk = k === 0xFE ? b : k; for (let x = gOff + (kk << 16); sameFw && x < gOff + ((kk + 1) << 16); x += SECTOR) if (mine.has(x) && changed.has(x)) sameFw = false; } + if (sameFw) { ranges.push([gOff, gOff + gLen]); guestR.push([gOff, gOff + gLen]); } + } else for (let x = gOff; sameFw && x < gOff + gLen; x += SECTOR) if (changed.has(x)) sameFw = false; + if (sameFw) ranges.push([so, so + 0x50000], [(gOff + gLen + 0xFFF) & ~0xFFF, se]); else notes.push(note('noteEmu')); + continue; + } + if (mag === 0x47584D50 || mag === 0x53584D50) { // GBEmu (1.6.9 test36), SMSEmu (1.6.10 test2): settings and cartridge RAM stay with the same game at the same place + const sameG = [0x140, 0x148, 0x14C, 0x150].every((k) => u32(dv, k) === u32(img, off + k)); + const ro = u32(img, off + 0x148), rl = u32(img, off + 0x14C), so = u32(img, off + 0x150); + let sameRom = sameG; for (let x = ro & ~0xFFF; sameRom && x < ro + rl; x += SECTOR) if (changed.has(x)) sameRom = false; + const sl = mag === 0x47584D50 && (u32(img, off + 0x140 + 20) & 8) ? 0x18000 : 0x10000; // 1.7.2: GBCEmu keeps 96 KB + if (sameRom && !mineIn(so, so + sl)) ranges.push([so, so + sl]); else if (!sameRom) notes.push(note('noteEmu')); // 1.6.11 test2: with the state behind the cartridge RAM; an imported save (changed by the Studio) wins + continue; + } + if (mag === 0x50584241) { // ArduboyEmu (1.7.3): settings, EEPROM and state stay with the same game at the same place + const sameP = [0x140, 0x148, 0x14C, 0x150].every((k) => u32(dv, k) === u32(img, off + k)); + const ro = u32(img, off + 0x148), rl = u32(img, off + 0x14C), so = u32(img, off + 0x150); + let sameRom = sameP; for (let x = ro & ~0xFFF; sameRom && x < ro + rl; x += SECTOR) if (changed.has(x)) sameRom = false; + if (sameRom && !mineIn(so, so + 0x4000)) ranges.push([so, so + 0x4000]); else if (!sameRom) notes.push(note('noteEmu')); + continue; + } + if (mag === 0x50584D50) { // PokeMiniEmu (1.7.3): settings, EEPROM and state stay with the same game at the same place (not the BIOS behind them) + const sameP = [0x140, 0x148, 0x14C, 0x150].every((k) => u32(dv, k) === u32(img, off + k)); + const ro = u32(img, off + 0x148), rl = u32(img, off + 0x14C), so = u32(img, off + 0x150); + let sameRom = sameP; for (let x = ro & ~0xFFF; sameRom && x < ro + rl; x += SECTOR) if (changed.has(x)) sameRom = false; + if (sameRom && !mineIn(so, so + 0xC000)) ranges.push([so, so + 0xC000]); else if (!sameRom) notes.push(note('noteEmu')); + continue; + } + if (mag === 0x57584D50) { // Wolf3D (1.6.10 test1): settings and the saved game stay with the same pack at the same place + const sameW = [0x140, 0x148, 0x14C, 0x150].every((k) => u32(dv, k) === u32(img, off + k)); + const ro = u32(img, off + 0x148), rl = u32(img, off + 0x14C), so = u32(img, off + 0x150); + let samePack = sameW; for (let x = ro & ~0xFFF; samePack && x < ro + rl; x += SECTOR) if (changed.has(x)) samePack = false; + if (samePack && !mineIn(so, so + 0x10000)) ranges.push([so, so + 0x10000]); else if (!samePack) notes.push(note('noteEmu')); + continue; + } + if (mag === 0x31584D50) { // V1Emu (1.6.8): the session stays with the same ROM at the same place + const sameV = [0x140, 0x148, 0x14C, 0x150].every((k) => u32(dv, k) === u32(img, off + k)); + const ro = u32(img, off + 0x148), rl = u32(img, off + 0x14C), so = u32(img, off + 0x150); + let sameRom = sameV; for (let x = ro & ~0xFFF; sameRom && x < ro + rl; x += SECTOR) if (changed.has(x)) sameRom = false; + if (sameRom) ranges.push([so, so + 0x2000]); else { ranges.push([so + 0x1000, so + 0x2000]); notes.push(note('noteEmu')); } // session, settings + continue; + } + const same = [0x140, 0x148, 0x14C, 0x150].every((k) => u32(dv, k) === u32(img, off + k)) && u32(img, off + 0x140) === T7; + if (!same) continue; + const ro = u32(img, off + 0x148), rl = u32(img, off + 0x14C), so = u32(img, off + 0x150); + let sameRom = true; + for (let x = ro & ~0xFFF; sameRom && x < ro + rl; x += SECTOR) if (changed.has(x)) sameRom = false; + if (sameRom && opts.t7SaveX === ix) ranges.push([so + 0x5000, so + 0x6000]); // an imported save.bin replaces the pet, the settings stay + else if (sameRom) ranges.push([so, so + 0x6000]); else notes.push(note('noteEmu')); + } + } + // T18Emu (1.5.0): firmware blocks come from the image (they may lie in areas that are kept + // otherwise); its save (map, clock note, session at 0x0C0000 and the spare blocks the firmware + // wrote) stays when the block map is the same + const t18blocks = xT18.slice(), t18keep = t18keepX; + if (t18i) { + const c = 0xA0140, ns = Math.min(u32(img, c + 12), 64); + for (let i = 0; i < 128; i++) { const b = img[c + 16 + 2 * i] | (img[c + 17 + 2 * i] << 8); if (b !== 0xFFFF) t18blocks.push(b); } + // spares must be empty unless the save that uses them is kept (they may lie in the Paradise save range) + for (let i = 0; i < ns; i++) t18blocks.push(img[c + 272 + 2 * i] | (img[c + 273 + 2 * i] << 8)); + if (img[c + 400] & 4) t18blocks.push(0xFD, 0xFE); // hot window (1.6.6): second copy of the flash part + const mvd = t18Moved(view, c, moves, c), same = t18d && t18SameGrown(mvd.d, mvd.dc, img, c); + if (same && !opts.emuChanged) { + ranges.push([0xC0000, 0xC0000 + 0x24000]); // map, clock note, session (the program's flash part at 0x0F0000 comes from the image) + for (let i = 0; i < ns; i++) { const b = img[c + 272 + 2 * i] | (img[c + 273 + 2 * i] << 8); t18keep.push([b << 16, (b + 1) << 16]); } + } else if (t18d) notes.push(note('noteEmu')); + } + // T18Emu leaves the device or gets other blocks (1.5.6): its old firmware blocks and spares are no + // save of the Paradise; they take what the new image has there (mostly empty) instead of being kept + const t18old = []; + if (t18d && !t18keep.length) { + const c = 0xA0140, ns = Math.min(u32(view, c + 12), 64); + for (let i = 0; i < 128; i++) { const b = view[c + 16 + 2 * i] | (view[c + 17 + 2 * i] << 8); if (b !== 0xFFFF && b < 0x100) t18old.push(b); } + for (let i = 0; i < ns; i++) { const b = view[c + 272 + 2 * i] | (view[c + 273 + 2 * i] << 8); if (b < 0x100) t18old.push(b); } + if (view[c + 400] & 4) t18old.push(0xFD, 0xFE); + } + // 1.6.8: saves that moved (main program <-> menu, other place in the menu): T7Emu and V1Emu by their ROM. + // The device's save of the same ROM is copied to the program's new save area. + if (menu && F.feldApps && opts.moveSaves !== false) { + const T7M = 0x37584D50, V1M = 0x31584D50; + const progs = async (b, rd, apps) => { + const out = [], one = async (base, cfgOf) => { + const c = await cfgOf(base); const m = u32(c, 0x140); + if (m !== T7M && m !== V1M) return; + const isMain = base === 0xA0000, so = u32(c, 0x150); + out.push({ kind: m, romOff: u32(c, 0x148), romLen: u32(c, 0x14C), saveOff: so, saveLen: m === V1M ? 0x2000 : (isMain ? 0x6000 : 0x6000), base }); + }; + if (b === img ? !clean : !dclean) await one(0xA0000, async (o) => rd(o, SECTOR)); + for (const a of apps) await one(a.src - 0x10000000 + 0x11000, async (o) => rd(o, SECTOR)); + return out; + }; + const imgRd = async (o, n) => img.subarray(o, o + n); + const devRd = async (o, n) => (changed.has(o) ? dev.read(o, n) : img.subarray(o, o + n)); + try { + const ip = await progs(img, imgRd, F.feldApps(img, menu.stub).apps), dp = await progs(view, devRd, F.feldApps(view, menu.stub).apps); + const covered = (a) => ranges.some(([x, y]) => a >= x && a < y); + for (const p of ip) { + if (covered(p.saveOff)) continue; + const want = crc32(img, p.romOff, p.romLen); + for (const d of dp) { + if (d.kind !== p.kind || d.romLen !== p.romLen || (d.base === p.base && d.saveOff === p.saveOff)) continue; + const dc = dev.crc ? await dev.crc(d.romOff, d.romLen) : crc32(await dev.read(d.romOff, d.romLen), 0, d.romLen); + if (dc !== want) continue; + const len = Math.min(p.saveLen, d.saveLen), data = await dev.read(d.saveOff, len); + image.set(data, p.saveOff); + for (let s = p.saveOff; s < p.saveOff + len; s += SECTOR) changed.add(s); + notes.push(note('noteSaveMoved', { n: p.kind === V1M ? 'V1Emu' : 'T7Emu' })); + break; + } + } + } catch (e) { /* only an extra; the normal plan stands */ } + } + // take the device's copy of every protected sector that differs + const prot = new Set(); + for (const [a, b] of ranges) for (let s = a & ~0xFFF; s < b; s += SECTOR) prot.add(s); + for (const b of t18blocks.concat(t18old)) for (let s = b << 16; s < (b + 1) << 16; s += SECTOR) prot.delete(s); + for (const [a, b] of t18keep) for (let s = a; s < b; s += SECTOR) prot.add(s); + if (mine) for (const [a, b] of guestR) for (let s = a & ~0xFFF; s < b; s += SECTOR) if (mine.has(s)) prot.delete(s); + for (const [a, b] of opts.fresh || []) for (let s = a & ~0xFFF; s < b; s += SECTOR) prot.delete(s); // 1.6.8: imported saves + let kept = 0; + for (const s of prot) if (changed.has(s)) { image.set(await dev.read(s, SECTOR), s); kept++; } + const protectedSectors = [...prot].filter((s) => changed.has(s)); + return { image, notes, kept, protectedSectors }; + }; +} + +const FLASH_APP_B64 = '__FLASH_APP_B64__'; +function embedded() { return FLASH_APP_B64.startsWith('__') ? null : b64(FLASH_APP_B64); } + +const CONN_DIAG = true; +function rxCount(io, v) { + for (let i = 0; i < v.length && io.rxHead.length < 48; i++) io.rxHead += (io.rxHead ? ' ' : '') + v[i].toString(16).padStart(2, '0'); + io.rx += v.length; +} +/** Web Serial transport (Chrome, Edge). */ +async function serialOpen(port) { + await port.open({ baudRate: BAUD, bufferSize: 1 << 16 }); + const writer = port.writable.getWriter(); + const io = { onData: null, closed: false, rx: 0, rxHead: '' }; + let reader = null, stop = false; + (async () => { + // a buffer overrun, framing or parity error ends the reader but not the port: take a new one (1.5.6) + while (!stop && port.readable) { + reader = port.readable.getReader(); + try { for (;;) { const { value, done } = await reader.read(); if (done) break; if (value) rxCount(io, value); if (value && io.onData) io.onData(value); } } + catch (e) { io.errors = (io.errors || 0) + 1; } + try { reader.releaseLock(); } catch (e) {} + if (stop) break; + } + io.closed = true; + })(); + io.write = (d) => writer.write(d); + io.close = async () => { stop = true; try { await reader.cancel(); } catch (e) {} try { reader.releaseLock(); } catch (e) {} try { writer.releaseLock(); } catch (e) {} try { await port.close(); } catch (e) {} }; + return io; +} + +root.ParamixFlash = { linkKey: LINK_KEY, rescueBlock, withRescue, batPic, batText, batFor, t18Relocate, RESCUE_OFF, PARA_RESCUE, connect, keepPlan, Link, Paradise, serialOpen, embedded, buildPdlo, crc32, sectorOrder, EDITIONS, FLASH_SIZE, BAUD, TimeoutError }; +if (typeof module !== 'undefined') module.exports = root.ParamixFlash; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000..ab47a9e --- /dev/null +++ b/src/index.html @@ -0,0 +1,757 @@ + + + + + +다마고치 펌웨어 편집·한국어 메뉴 | 다마고치 연구소 + + + + + + + +
+
Paramix Studio
+ + + + 로그인 + + + + + +
+ +
+
+ + + + + + + + + + + + + + + + + +
+ + + +
+

+

+
+ + +
+
+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+ + + + + + + + + + + + + +
+
+
+ + + + + + + +
+
+
+ + + + + + + + + + + + +
+
+ +
+ +
+
+ + + + + + + + + + + + + + + diff --git a/src/ko.tsv b/src/ko.tsv new file mode 100644 index 0000000..19ff482 --- /dev/null +++ b/src/ko.tsv @@ -0,0 +1,705 @@ +open ROM 열기 +save 새 ROM 저장 +startTitle 다마고치 파라다이스를 더 다양하게 +startText 내 파라다이스 ROM으로 원하는 기능을 구성하세요. 16 MB 원본 파일을 열거나 기기에서 직접 읽은 뒤, 기능을 선택하고 새 ROM을 기기에 기록할 수 있습니다. +featHead 이런 일을 할 수 있어요 +g1t 다마고치 에뮬레이터 +g1 컬러 다마고치(iD, iD L, Plus Color, P's, 4U, 4U+), 타마고와 피규어, 프렌즈, 미츠·온, 커넥션 V3, P1·P2·엔젤 등의 초기 다마고치와 디지몬 V1·V2를 지원합니다. 여러 프로그램을 넣고 각각 저장할 수 있습니다. ROM은 직접 준비하세요. +g2t DOOM과 Wolfenstein 3D +g2 파라다이스에서 DOOM, Wolfenstein 3D, Spear of Destiny를 실행하고 버튼을 설정할 수 있습니다. 게임 파일은 직접 준비하세요. +g7t 게임기 에뮬레이터 +g7 게임보이·컬러, 마스터 시스템, 게임기어, 포켓몬 미니, Arduboy를 지원합니다. 직접 준비한 게임을 메뉴에 추가하고 소리와 저장 기능을 사용할 수 있습니다. +g3t 지역 확장 +g3 지원되는 ROM에 여섯 지역과 배경, 비밀 캐릭터, 지역별 행성 및 연구소 게임을 구성합니다. +g4t 본체 편집 메뉴 +g4 본체에서 지역 전환, 아이템 추가, 포인트·다마고치 수정, 여러 저장 슬롯을 사용할 수 있습니다. 게임 플레이 시간으로 포인트를 얻는 기능도 있습니다. +g8t 파라다이스 없는 실행 전용 기기 +g8 약 16 MB 전체를 에뮬레이터와 게임에 활용합니다. 시작 프로그램을 지정하고 메뉴에서 시간을 설정합니다. +g5t 기기 읽기·기록 +g5 USB-UART 어댑터로 원본을 백업하고 새 ROM을 기록합니다. 저장 유지와 변경 부분만 기록하기를 지원하며, 기록 중단에 대비한 복구 시작 기능이 있습니다. +g6t 나만의 캐릭터 +g6 캐릭터 이미지를 시트로 내보내 편집합니다. DIM 카드의 디지몬도 가져올 수 있으며 색상과 눈 이미지는 자동으로 맞춥니다. +g9t 저장 관리와 방문 +g9 저장 데이터를 백업·복원·편집하고 다운로드 콘텐츠를 추가합니다. 상단 단자로 두 기기를 연결하거나 어댑터로 가상 방문을 실행합니다. +dropTitle ROM을 여기에 놓거나 클릭하세요 +dropText 랜드, 워터, 스카이, 제이드 포레스트, 트로피컬, 글레이셔를 인식합니다. +f1t 내 PC 편집·기종별 백업 +f1 파일 편집은 내 PC에서 처리합니다. 본체 ROM 추출 시 서버에 없는 기종만 비공개 백업 후 PC에 다운로드합니다. 기종당 1개이며 관리자 승인 후에만 공개됩니다. +f2t 게임 파일은 직접 준비 +f2 도구에는 ROM, 펌웨어, WAD가 포함되지 않습니다. 본인 기기와 파일을 사용하세요. +f3t 변경 내용 검증 +f3 체크섬을 다시 계산하고 저장 전 수정 이미지를 확인합니다. 기기에 기록한 각 섹터도 검증합니다. +planTitle 새 ROM 구성 +planFig 캐릭터 +planEmu 에뮬레이터 +planEmus 에뮬레이터 +planDoom DOOM +planWolf Wolfenstein 3D +planGb 게임보이 +planSms 마스터 시스템 / 게임기어 +planPm 포켓몬 미니 +planMenu 본체 메뉴 +planApps 추가 에뮬레이터 +stNone 없음 +stKeep 유지 +stNew 추가 +stDel 저장 시 삭제 +stChanged {n}개 변경 +stSame 변경 없음 +segFw 펌웨어와 캐릭터 +segEmu 에뮬레이터 +segDoom DOOM +segWolf Wolfenstein 3D +segGb 게임보이 +segSms 마스터 시스템 / 게임기어 +segPm 포켓몬 미니 +segSlots 지역별 저장 +segSave 저장 데이터 +segFree 사용 가능 +segResv 예약 영역 +ruleBoth 에뮬레이터와 DOOM 중 하나만 넣을 수 있습니다. 본체 메뉴는 둘 다 지원합니다. +ruleNoRoom 이 에디션은 캐릭터 데이터가 커서 에뮬레이터나 DOOM을 넣을 공간이 없습니다. 본체 메뉴는 사용할 수 있습니다. +emuVsDoom DOOM이 선택되거나 설치되어 있습니다. 여기서 펌웨어를 선택하면 DOOM을 제거합니다. +doomVsEmu 에뮬레이터가 선택되거나 설치되어 있습니다. 여기서 WAD를 선택하면 에뮬레이터를 제거합니다. +noRoomApp 이 에디션에는 필요한 공간이 없습니다. +a0Menu 이 에디션은 0x0A0000에 주 프로그램을 넣을 공간이 없어 모든 프로그램을 메뉴에 넣습니다. 별표로 전원을 켤 때 실행할 프로그램을 선택합니다. +a0MenuN 이 에디션은 0x0A0000에 주 프로그램을 넣을 공간이 없습니다. 타마고·프렌즈·초기 다마고치·V3는 메뉴에서 실행합니다(A+C, 메뉴 탭에서 지역 전환 또는 아이템 활성화). 컬러 다마고치와 TG18은 실행 전용 구성에서만 지원됩니다. +a0NoMain {f}: 이 에디션의 컬러 다마고치와 TG18은 실행 전용 구성에서만 지원됩니다(메뉴 탭). +doomHas 이 ROM에 DOOM이 들어 있습니다. +doomOff DOOM 제거 +doomGone 저장할 때 DOOM을 제거합니다. +keysTitle 버튼 설정 +kFire 발사 +kFwd 앞으로 +kBack 뒤로 +kUse 사용 +kMod 무기 변경: 버튼을 누른 채 휠 +kWheel 휠 누르기 +kRun 앞으로 두 번 눌러 달리기 +kInv 휠 방향 반전 +kFixed 고정 조작: A+C 메뉴, B+C 지도. 소리 전환: 무기 변경 버튼을 누른 채 휠을 짧게 누릅니다. 종료는 메뉴 탭의 ‘프로그램에서 돌아오기’ 설정을 따릅니다. +kOld 이 DOOM은 개별 버튼 설정을 지원하지 않는 이전 버전입니다. WAD로 다시 추가하세요. +help 도움말 +helpTitle 사용 방법 +h1t 진행 순서 +h1 1. 내 파라다이스 ROM 파일을 열거나 ‘기기’에서 직접 읽습니다.\n2. 각 탭에서 캐릭터, 에뮬레이터, 게임, 본체 메뉴를 선택합니다.\n3. 파일로 저장하거나 ‘기기’에서 기록합니다. ‘저장 데이터 유지’를 켜면 기기의 저장 데이터를 유지합니다. +h2t 파라다이스 버튼 조작 +hk1 A와 C 함께 +hv1 홈 화면에서 메뉴 또는 에뮬레이터 실행 +hk2 휠 길게 누르기(메뉴 탭에서 변경 가능) +hv2 현재 상태를 저장하고 파라다이스로 돌아가기 +hk3 휠 짧게 누르기 +hv3 T7Emu의 설정·피규어 선택 +hk4 시작 후 3초 안에 휠 누르기 +hv4 A로 확인하면 실행 상태를 버리고, 다음 실행 시 게임 자체의 저장 데이터에서 시작 +hk5 전원을 켤 때 B +hv5 자동 시작을 건너뛰고 파라다이스 또는 메뉴 열기 +hk6 리셋 버튼 +hv6 자동 시작 설정 시 주 프로그램 다시 실행 +hk7 전원을 켤 때 C +hv7 기록 프로그램 실행: 웹의 ‘기기’에서 다시 기록 가능 +h3t 시계 +h3 에뮬레이터 탭의 ‘시작할 때 파라다이스 시간 가져오기’를 켜면 실행할 때마다 기기의 시간으로 맞춥니다. 실행하지 않은 시간 동안의 플레이를 재현하지는 않습니다. 파라다이스 시계를 먼저 맞추세요. +h4t 다시 실행하기 +h4 휠로 종료한 시점부터 이어집니다. 실행 상태를 초기화해도 게임 자체의 저장 데이터는 유지됩니다. +h5t 메뉴와 지역 +h5 홈 화면에서 A+C를 누릅니다. 휠로 선택, B로 확인, C로 돌아갑니다. 지역을 바꾸면 이전 지역의 저장 데이터를 보관하고 새 지역의 저장을 불러옵니다.\n트로피컬·글레이셔에는 내 ROM에서 랜드·워터·스카이를 추가하고, 제이드 포레스트에는 스카이를 추가합니다. 게임에서는 행성 → 지역으로 이동합니다. DNA와 주민은 해당 지역에 속합니다. +h8t 실행 전용 구성 +h8 메뉴 탭에서 실행 전용 구성을 선택하면 프로그램 목록으로 시작합니다. 파라다이스를 제거하면 거의 전체 공간을 프로그램에 쓰며 메뉴에서 시계를 맞춥니다. 별표로 주 프로그램을 정하고 자동 시작을 켤 수 있습니다. +h9t 복구 화면으로 돌아가기 +h9 화면이 검거나 프로그램이 멈추면 C를 누른 채 배터리를 넣거나 리셋합니다. 기록 프로그램이 시작되면 ‘기기’에서 읽기·기록이 가능합니다. 기록이 중단된 경우에는 복구 시작 기능이 자동으로 기록 화면을 엽니다. +h6t 저장 데이터 백업 +h7t 저장 데이터 가져오기 +h7 1. ‘기기’에서 최신 ROM을 읽거나 최근 읽은 파일을 엽니다.\n2. 저장 탭에서 데이터를 가져옵니다. 해당 프로그램의 저장에 적용됩니다.\n3. ‘저장 데이터 유지’를 켜고 기록합니다. 가져온 저장만 교체하고 다른 저장은 기기의 것을 유지합니다.\n‘저장 데이터 유지’를 끄면 모든 저장을 파일의 것으로 교체합니다. 프로그램 추가·삭제는 별도 기록으로 진행하고 먼저 모든 저장을 백업하세요. +h6 저장 탭 또는 기기 → ‘저장 데이터 백업’을 사용하세요. 에뮬레이터를 바꾸면 이전 저장을 잃을 수 있으므로 먼저 백업하세요. +device 기기 +devTitle UART 기기 연결 +devHint 3.3 V 신호의 USB-UART 어댑터를 사용합니다. 원본 안내의 접점 방향은 왼쪽: 어댑터 RX, 가운데: GND, 오른쪽: 어댑터 TX입니다. 실제 기기 방향과 배선을 확인하세요. 본체의 행성 → A → 연결 → 다운로드 → 다운로드 화면을 연 뒤 연결하세요. PC의 Chrome 또는 Edge가 필요합니다. +devConnect 연결 +devDump ROM 추출·백업 후 다운로드 +devWrite 새 ROM을 기기에 기록 +devOnly 변경 부분만 기록 +devKeep 저장 데이터 유지 +devStop 취소 +devNoSerial 이 브라우저는 어댑터 연결을 지원하지 않습니다. PC의 Chrome 또는 Edge를 사용하세요. +devNone 연결되지 않았습니다. +fl_noRescueRoom 복구 시작 영역(플래시 마지막 64 KB)에 공간이 없어 기록하지 않았습니다. 실행 전용 구성에서 프로그램을 하나 제거한 뒤 다시 기록하세요. +plHint PL2303 어댑터: 최신 Windows 드라이버는 구형·호환 칩을 차단할 수 있습니다. 장치 관리자에서 구형 Prolific 3.3.2.x 드라이버를 선택하거나 CH340·CP2102 어댑터를 사용하세요. +resOn 기록 중단 복구 기능 활성화: 중단 시 기기가 기록 화면으로 시작합니다. +resModeGo 이전 기록이 중단되었습니다. 본체의 기록 화면에서 대기 중입니다. ‘기록 이어하기’를 누르세요. +resModeRom 이전 기록이 중단되었습니다. 본체가 기록 화면에서 대기 중입니다. ROM 또는 백업 파일을 다시 열고 기록하세요. +resResume 기록 이어하기 +resHalf 이전 기록이 끝나지 않았습니다. ‘기록 이어하기’로 완료하세요. +resResumed {w}개 섹터 기록 완료. 본체 전원을 껐다 켜세요. +resTest 복구 시작 테스트 +resBack 헤더 복원 +resSure 테스트: 0xFF0000에 복구 프로그램을 기록한 뒤 기기 헤더(섹터 0)를 지웁니다. 전원을 껐다 켜고 기록 화면이 나오면 연결 후 ‘헤더 복원’을 누르세요. 화면이 나오지 않으면 별도 플래시 도구 없이 부팅할 수 없습니다. 계속할까요? +resCleared 헤더를 지웠습니다. 전원을 껐다 켜세요. 기록 화면이 나오면 연결 후 ‘헤더 복원’을 누르세요. +resBackDone 헤더를 복원했습니다. 전원을 껐다 켜면 정상 시작합니다. +resNoHdr 보관된 헤더가 없습니다. +devOn 연결됨: {ed}, {mb} MB{l} +devLoaded , 기록 프로그램 로드됨 +devReady 준비되었습니다. +devNeedRom 기록할 ROM을 먼저 열거나 기기에서 읽으세요. +visTitle 가상 방문(파라다이스) +visStart 시작 +visStop 중지 +visHint 도구가 두 번째 파라다이스 역할을 합니다. 어댑터를 접점에 연결하고 본체는 일반 실행 상태로 두세요.\n1. 에디션 선택 → 시작 → 어댑터 선택.\n2. 본체의 행성 메뉴 → 연결 → 플레이데이트 → B.\n위의 ‘연결’ 버튼은 ROM 작업용이므로 방문할 때는 누르지 마세요. +visWait {ed} 방문 준비 완료. 본체에서 플레이데이트를 선택하고 B를 누르세요. +visRun 연결됨, 데이터 교환 중… +visPlay 두 다마고치가 놀고 있습니다… +visDone 방문 완료({ed}). 다음 방문은 본체에서 B를 다시 누르세요. +visErr 중단됨: {e}. 본체에서 B를 다시 누르세요. +visBadKey 본체가 데이터를 인식하지 못했습니다. +phload 기록 프로그램 로드 중 +phread 읽는 중 +phcompare 비교 중 +phwrite 기록 중 +phcheck 검증 중 +phprepare 준비 중 +devDumped ROM을 읽어 {n}으로 저장했습니다. 도구에서도 해당 ROM을 열었습니다. +devSure 새 ROM을 기기에 기록합니다. 기록 중 전원을 유지하세요. 변경에 따른 위험을 이해하고 기록할까요? +devSureFull ‘저장 데이터 유지’가 꺼져 있어 기기의 저장을 ROM 파일의 저장으로 교체합니다. 기록할까요? +carryUnknown 기기와 현재 파일의 ROM이 다릅니다. 이동하는 프로그램의 저장을 보존할 수 없습니다. 먼저 기기의 ROM을 읽으세요. 그래도 기록할까요? +carryMiss 이동하는 프로그램의 저장을 보존할 수 없습니다. 저장 탭에서 먼저 백업하세요. 그래도 기록할까요? +devEmuLost 기기의 주 프로그램: {o}. 새 ROM: {n}. {o}의 주 프로그램 저장이 초기화됩니다. 유지하려면 저장 탭에서 먼저 백업하세요. 기록할까요? +devEmuNone 에뮬레이터 없음 +devEmuNew 새 펌웨어를 선택한 {o} +devDone 기록·검증 완료: {w}개 섹터 기록{k}. 본체를 리셋하거나 배터리로 재시작하세요. +devKept , 저장 섹터 {k}개 유지 +devSame 기기에 이미 같은 ROM이 있어 기록할 내용이 없습니다. +devErr 오류: {e} +devCancelled 취소했습니다. +cleanOn 파라다이스 제거(클린 ROM) +cleanClock 시작할 때 시계 설정 +cleanClockHint 배터리 교체 등으로 시간이 없으면 시작 시 설정합니다. 이 옵션을 끄면 본체 메뉴의 설정 또는 각 에뮬레이터에서 시간을 맞추세요. +emuClockOff 메뉴 탭의 ‘시작할 때 시계 설정’을 켜야 합니다. +emuSess 종료 시 실행 상태 저장 +emuSessHint 다음 실행 시 종료한 지점부터 이어집니다. 끄면 실제 기기처럼 새로 시작해 게임 자체의 저장을 불러옵니다. +ruleClean 파라다이스 제거: 모든 프로그램을 메뉴에 넣고 거의 전체 플래시 공간을 활용합니다. +cleanHint 파라다이스 게임을 제거하고 프로그램 메뉴만 남깁니다. 거의 16 MB 전체를 사용할 수 있습니다. +cleanUse 전원을 켜면 메뉴가 바로 나옵니다. 처음에는 시계를 설정하고 이후에는 설정 메뉴에서 변경합니다. 프로그램 종료 방법은 같습니다. +cleanWarn 기록하면 파라다이스와 그 저장 데이터가 삭제됩니다. 먼저 백업하세요. +cleanNoDoom 이 구성에서는 DOOM을 사용할 수 없습니다. DOOM을 제거하세요. +doomOne DOOM은 메뉴에 한 번만 추가할 수 있습니다. +cleanSure 기기의 파라다이스 게임과 저장 데이터가 삭제됩니다. 기기를 백업했나요? 계속할까요? +cleanLoaded 파라다이스 없는 ROM({ed})을 열었습니다: 프로그램 {n}개. +launchOn 프로그램 실행 전용 구성 +launchHint 파라다이스의 초기 설정(언어·시간·이어하기·새 게임)만 남기고 이후에는 프로그램 메뉴로 시작합니다. 게임 이미지를 제거해 약 5 MB를 추가로 확보합니다. +launchUse 전원을 켜고 시간을 맞추면 메뉴가 나옵니다. 휠로 선택하고 B로 실행합니다. 프로그램을 종료하면 메뉴로 돌아옵니다. +launchOld 실행 전용 ROM입니다. 일반 파라다이스로 돌아가려면 원본 ROM을 여세요. +launchNeed 실행 전용 구성에는 에뮬레이터 또는 DOOM 등 프로그램이 하나 이상 필요합니다. +launchSix 여섯 지역 확장이 설치된 ROM은 실행 전용으로 바꿀 수 없습니다. 원본 ROM을 여세요. +planLaunch 실행 전용 구성 +tabFeld 본체 메뉴 +feldOn 여러 저장 슬롯(지역 선택) +bagOn 아이템과 다마포인트 +tamaOn 다마고치 수정(레벨·돌봄·캐릭터) +gplayOn 플레이 시간으로 다마포인트 획득 +gplayHint DOOM, Wolfenstein, 게임보이, 마스터 시스템, 포켓몬 미니, Arduboy를 플레이한 뒤 파라다이스로 돌아오면 1분당 10포인트를 받습니다. +saveSlot 저장 {n} +sixOn 여섯 지역 모두 추가 +sixPick 랜드·워터·스카이 ROM 선택 +sixHint 트로피컬·글레이셔에 랜드·워터·스카이를 추가합니다. 지역 이미지는 직접 준비한 해당 ROM에서 가져옵니다. 연구소 게임은 메뉴에서 다마고치를 시작한 지역을 따릅니다. +sixNeed 여섯 지역 확장을 위해 랜드·워터·스카이 중 하나의 ROM이 필요합니다. +sixOk {n}에서 지역 이미지를 가져왔습니다. +sixBad {n}은 랜드·워터·스카이 ROM이 아닙니다. +sixIn 여섯 지역이 설치되어 있습니다. +sixOff 저장 시 랜드·워터·스카이를 제거합니다. 여러 저장 슬롯은 유지됩니다. +sixOffJ 저장 시 스카이를 제거합니다. 여러 저장 슬롯은 유지됩니다. +sixOffField 현재 기기의 지역은 {f}입니다. 먼저 본체 메뉴에서 {s}로 이동하세요. +sixOffSlots 본체 메뉴에 보관된 저장 데이터가 삭제됩니다. 계속할까요? +sixFail 지역 추가 실패: {e} +sixNoFw ROM의 펌웨어가 변경되어 지역 확장을 적용할 수 없습니다. +planSix 지역 확장 +sixOnJ 스카이를 네 번째 지역으로 추가 +sixHintJ 제이드 포레스트에는 스카이 이미지가 이미 들어 있습니다. +sixInJ 스카이가 네 번째 지역으로 설치되어 있습니다. +sixOld 이전 버전의 여섯 지역 확장이 설치되어 있습니다. 랜드·워터·스카이 ROM을 선택하면 저장 시 업데이트합니다. +sixOldJ 스카이가 설치되어 있으며 저장할 때 업데이트합니다. +sixPlanet 지역에 맞는 행성 +sixMenu 게임의 지역 메뉴: 레벨 4부터 모든 지역 +sixPlanetNeed 이 설정을 바꾸려면 랜드·워터·스카이 ROM이 다시 필요합니다. +sixApp DOOM·에뮬레이터와 함께 넣을 공간이 없습니다 +exitKey 프로그램에서 돌아오기 +exitHint 에뮬레이터와 게임에서 파라다이스 또는 본체 메뉴로 돌아오는 조작입니다. +exit0 휠 길게 누르기 +exit1 휠과 A 길게 누르기 +exit2 휠과 C 길게 누르기 +exit3 휠 5초 누르기 +feldHint 본체에서 저장 슬롯 전환, 새 지역 시작, 아이템 추가, 포인트 설정, 다마고치 수정을 할 수 있는 메뉴입니다. +feldUse 홈 화면에서 A+C를 길게 누르세요. 휠로 선택, B로 확인, C로 돌아갑니다. +feldNo 지역 전환은 랜드·워터·스카이끼리, 트로피컬·글레이셔끼리 지원합니다. +feldMissing 이 배포본에는 본체 메뉴가 없습니다. +feldCur 현재 지역: {f}. +feldList 선택 가능: {s}. +feldStored 보관 중: {s}. +feldFail 메뉴 설치 실패: {e} +feldUnknown 에디션을 인식하지 못했습니다. +tabWolf Wolf3D +wolfPick 게임 파일 선택 +wolfHint Wolfenstein 3D 파일을 모두 함께 선택하세요: 셰어웨어(.WL1), 정식판(.WL6), Spear of Destiny(.SOD). 본체 메뉴에 추가합니다. +wolfNone 선택한 게임 파일이 없습니다. +wolfShare 셰어웨어 +wolfFull 정식판 +wolfEps 에피소드 {n}개 +wolfEp1 에피소드 1개 +wolfBad Wolfenstein 3D: {e} +wolfNoMain Wolfenstein 3D는 본체 메뉴에서만 실행 +wolfTurn 휠 한 칸당 회전 +wolfFixed A+C: 메뉴. 종료·저장은 본체 메뉴 탭의 ‘프로그램에서 돌아오기’ 설정을 따릅니다. +wolfOne Wolfenstein 3D와 Spear of Destiny는 각각 하나씩만 넣을 수 있습니다. 새 파일을 선택하면 이전 것을 교체합니다. +wolfSodN 21개 층 +tabGb 게임보이 / 컬러 +gbNoMain 게임보이는 본체 메뉴에서만 실행 +gbPick 게임 선택(.gb, .gbc) +gbHint 게임을 본체 메뉴에 추가합니다. A+B+C로 설정(Select·소리 포함)을 열고 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다. 두 파라다이스의 상단 단자를 연결하면 포켓몬 교환 등 통신 케이블 기능을 사용할 수 있습니다. +gbNone2 선택한 게임이 없습니다. +gbKeysTitle 버튼 +gbKeysDef 기본값 +gbKeysMiss 미지정: {n} +gbNone – +gbRight 오른쪽 +gbLeft 왼쪽 +gbUp 위 +gbDown 아래 +gbInA A 버튼 +gbInB B 버튼 +gbInC C 버튼 +gbInWp 휠 누르기 +gbInWu 휠 위로 +gbInWd 휠 아래로 +gbInAC A + C +gbInBC B + C +gbInAB A + B +gbBad {f}: 게임보이 게임이 아닙니다 +gbColor {f}: 게임보이 컬러 전용이므로 이 구성에서 지원하지 않습니다 +gbNeedRom 먼저 ROM을 열거나 기기에서 읽으세요. +t7Old {n}: 구버전은 배터리 교체 시 저장이 유실될 수 있습니다. ‘저장 데이터 유지’를 켜고 다시 기록하세요. +t18Broken Tama Meets가 손상되었습니다. 제거 후 펌웨어를 다시 추가하고 ‘저장 데이터 유지’를 끈 상태로 기록하세요. +t18Clash 주 프로그램과 Tama Meets의 공간이 겹칩니다. Tama Meets를 먼저 제거하세요. +tabSms 마스터 시스템 / 게임기어 +tabPm 포켓몬 미니 +smsNoMain 마스터 시스템·게임기어는 본체 메뉴에서만 실행 +pmNoMain 포켓몬 미니는 본체 메뉴에서만 실행 +abNoMain Arduboy는 본체 메뉴에서만 실행 +planAb Arduboy +segAb Arduboy +tabAb Arduboy +abPick 게임 선택(.hex, .zip) +abHint 게임을 본체 메뉴에 추가합니다. A+B+C로 화면 크기·소리 등을 설정하고, 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다. +abBad {f}: Arduboy 게임이 아닙니다 +abBig {f}: Arduboy 용량을 초과합니다 +smsPick 게임 선택(.sms, .gg) +smsHint 게임을 본체 메뉴에 추가합니다. A+B+C로 일시정지·소리 등을 설정하고, 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다. +smsBad {f}: 마스터 시스템·게임기어 게임이 아닙니다 +smsGG {f}: 이 구성에서는 게임기어 게임을 지원하지 않습니다 +smsB1 버튼 1 +smsB2 버튼 2 +smsPause 일시정지 / 시작 +pmPick 게임 선택(.min, .zip) +pmHint 게임을 본체 메뉴에 추가합니다. A+B+C로 전원·소리 등을 설정하고, 휠을 2초 누르면 저장 후 종료합니다. 다음 실행 시 이어집니다. +pmBad {f}: 포켓몬 미니 게임이 아닙니다 +pmBig {f}: 1 MB를 초과해 지원하지 않습니다 +pmBiosPick 내 BIOS 선택 +pmBiosDel 내 BIOS 제거 +pmBiosFree 직접 선택하지 않으면 PokeMini의 자유 BIOS를 사용합니다. 실제 BIOS로 더 잘 실행되는 게임도 있습니다. +pmBiosOwn 선택한 BIOS를 모든 포켓몬 미니 게임에 사용합니다. +pmBiosBad {f}: 포켓몬 미니 BIOS가 아닙니다 +pmA A +pmB B +pmC C +pmPower 전원 +pmShake 흔들기 +tabFigs 캐릭터 +tabAll 전체 이미지 +tabDim 카드 +tabEmu 에뮬레이터 +tabDoom DOOM +doomPick DOOM.WAD 선택 +doomEp 에피소드 +doomMusic 음악 +doomHint 직접 준비한 WAD로 ROM에 DOOM을 추가합니다. 파일은 내 PC에서 처리합니다. +doomUse 본체 메뉴에서 실행합니다. 일반 파라다이스에서는 홈 화면에서 A+C로도 실행합니다. 종료는 ‘프로그램에서 돌아오기’ 설정을 따릅니다. +doomNone 선택한 WAD가 없습니다. +doomOk WAD 인식됨({eps}). 저장할 때 DOOM을 추가합니다. +doomEpsHint 파라다이스 없는 구성에서는 선택한 에피소드를 DOOM E1, E2 등 각각의 메뉴와 저장으로 추가합니다. +doomWhole 전체 WAD를 한 항목으로 +pwadPick 추가 WAD 선택 +pwadOff 추가 WAD 제거 +doomPwads 함께 사용: {n}. +pwadNeedD2 {n}은 DOOM II용입니다. 먼저 DOOM2.WAD를 선택하세요. +pwadNeedD1 {n}은 DOOM·Ultimate DOOM용입니다. 먼저 DOOM.WAD를 선택하세요. +doomPwadPara Sigil 같은 추가 에피소드는 파라다이스 없는 구성에서만 지원합니다. +doomPwadBig {n}: {m} 지도는 본체 메모리보다 클 수 있습니다. 실행 중 9가 표시되면 휠을 2초 눌러 메뉴로 돌아가세요. +doomPwadHint 추가 에피소드를 선택하면 개별 메뉴로 추가합니다. 전체 WAD와 함께 넣으면 공간이 부족할 수 있습니다. +doomD2Clean DOOM II는 파라다이스 없는 ROM에만 추가할 수 있습니다. +doomD2Hint DOOM II는 메뉴 한 항목으로 추가합니다. 거의 전체 공간을 사용하며 음악을 꺼야 들어갑니다. +doomWholeHint 모든 에피소드를 DOOM 한 항목에 넣고 게임 안에서 선택합니다. 개별 추가보다 공간을 적게 사용합니다. +doomBad WAD 인식 실패: {e} +doomFail DOOM 추가 실패: {e} +doomMissing 이 배포본에는 DOOM 프로그램이 없습니다. +doomBoth 에뮬레이터와 DOOM을 함께 넣을 공간이 없습니다. 하나만 선택하세요. +doomBig 이 WAD의 에피소드를 넣을 공간이 없습니다. +doomNoMusic 음악을 꺼야 이 에피소드가 들어갑니다. +emuPick 펌웨어 또는 ROM 선택 +emuOff 에뮬레이터 제거 +emuHint 컬러 다마고치(TamaEmu), 타마고·프렌즈(T7Emu), 미츠·온(T18Emu), 초기 다마고치·디지몬(V1Emu), 커넥션 V3(V3Emu)를 지원합니다. 첫 파일은 주 프로그램, 이후 파일은 본체 메뉴에 추가합니다. 채워진 별표가 주 프로그램이며 빈 별표를 누르면 바뀝니다. 파일은 직접 준비하세요. +t7Ok V7 ROM 인식됨(T7Emu). 저장할 때 추가합니다. +t7OkFr 다마고치 프렌즈를 불러왔습니다. 저장할 때 추가합니다. 피규어는 지원하지 않습니다. +t7Has 이 ROM에 T7Emu가 들어 있습니다. +t7HasFr 이 ROM에 다마고치 프렌즈 T7Emu가 들어 있습니다. +t7Use 홈 화면에서 A+C로 실행합니다. 휠 길게: 저장·종료, 짧게: 설정·피규어. 멈췄다면 A+C로 실행하고 버튼을 놓은 뒤 3초 안에 휠을 누르고 A로 확인하세요. +t7FigPick 피규어 추가 +t7FigNone 추가한 피규어가 없습니다. +t7FigBad {f}: 피규어 파일이 아닙니다. +t7FigFull {f}을 넣을 공간이 없습니다. +t7FigMax 피규어를 더 넣을 공간이 없습니다. +t7FigDup {f}은 이미 들어 있습니다. +appPick 다른 에뮬레이터 추가 +appHint 타마고·프렌즈 ROM(T7Emu)을 추가합니다. A+C로 여는 메뉴에서 실행하므로 본체 메뉴 탭의 기능을 하나 이상 켜야 합니다. +appNone 추가 에뮬레이터가 없습니다. +appBad {f}: 타마고·프렌즈 ROM이 아닙니다. +appBadL {f}: 타마고·프렌즈 ROM이나 컬러 다마고치·TG18 펌웨어가 아닙니다. +appT18One T18Emu는 ROM마다 하나만 추가할 수 있습니다. +appHintL 실행 전용 구성: 타마고·프렌즈 ROM, 컬러 다마고치 펌웨어(TamaEmu), TG18 펌웨어(T18Emu, 하나만)를 지원합니다. +ruleLaunch 실행 전용 구성에서는 공간이 있으면 에뮬레이터와 DOOM을 함께 넣을 수 있습니다. +appMax 추가 에뮬레이터는 최대 12개입니다. +appNeedMenu 추가 에뮬레이터를 실행하려면 본체 메뉴 탭에서 지역 전환 또는 아이템을 켜세요. +appFail 추가 에뮬레이터: {e} +appSix 여섯 지역 확장과 추가 에뮬레이터를 함께 사용할 수 없습니다. +t7SaveBtn T7Emu 저장(.bin) +saveFor 프로그램 +saveMain 주 에뮬레이터 +v1SaveBtn V1Emu 저장(.bin) +saveT18No 이 프로그램의 저장 데이터는 백업할 수 없습니다. +saveNoBatt 이 게임은 카트리지에 저장 데이터를 남기지 않습니다. +saveNone 저장 데이터가 없습니다. +saveWrongFile {n}에 맞는 파일이 아닙니다. +saveCartIn {n}의 저장을 가져왔습니다. ROM을 저장하거나 기기에 기록하세요. 이전 실행 상태는 초기화됩니다. +t7SaveXDone {n}의 저장을 가져왔습니다. ROM을 저장하거나 기기에 기록하세요. +t7NoSave 다마고치의 저장 데이터가 없습니다. +t7SaveInDone T7Emu 저장을 가져왔습니다. ROM을 저장하거나 기기에 기록하세요. +t7SaveNeed ROM에 T7Emu가 없습니다. 에뮬레이터 탭에서 타마고 ROM을 먼저 추가하세요. +saveT18Need ROM에 T18Emu가 없습니다. 에뮬레이터 탭에서 TG18 펌웨어를 먼저 추가하세요. +saveEmuAny 에뮬레이터 저장(.sav / .bin) +emuUse 홈 화면에서 A+C로 실행하고 휠을 길게 눌러 저장·종료합니다. TamaEmu가 멈췄다면 A+C로 실행하고 버튼을 놓은 뒤 3초 안에 휠을 누르고 A로 확인하세요. 게임 자체의 저장에서 다시 시작합니다. +emuNone 선택한 에뮬레이터가 없습니다. +petT 저장 데이터 편집 +petOpen 파라다이스 저장 열기 +petRom ROM 내부 저장 +petClose 닫기 +petRomDone 변경 사항을 적용했습니다. 새 ROM을 저장하거나 기기에 기록하세요. +petLevel 레벨 +petChar 다마고치 +petCare 배부름·행복·건강 회복 +petSave 수정한 저장 파일 저장 +petKeep 변경 없음 +petKid 유아기 +petYoung 성장기 +petAdult 성체 +petNow 저장 상태: 레벨 {l}, 다마고치 {c}, 배부름 {h}/6, 행복 {j}/20{s}. +petSick , 아픔 +petOther 현재 ROM과 다른 에디션의 저장입니다. +petNoSet 저장 데이터에 설정 영역이 없습니다. +petDone {n} 저장 완료. ‘저장 데이터를 기기에 기록’으로 전송하세요. +petNothing 변경한 내용이 없습니다. +tabSave 저장 관리 +tabNames 이름 +cardNoChars 이 카드에는 캐릭터가 없습니다 +noRoomFrag 전체 여유 공간은 있지만 연속 공간이 부족합니다(DOOM WAD에는 큰 연속 공간이 필요합니다). 프로그램을 제거하거나 DOOM 음악을 끄세요. +noRoomKB 약 {k} KB가 부족합니다. 프로그램을 제거하세요. 마지막 64 KB는 기록 중단 복구용으로 남겨 둡니다. +noRoomAdd {n}을 넣으려면 약 {k} KB가 더 필요합니다. 마지막 64 KB는 기록 중단 복구용입니다. +eyeMvT 눈 위치 이동 +mouthMvT 입 위치 이동 +poseNr 자세 {i} / {n} +faceBig 큰 캐릭터 +faceSmall 작은 캐릭터 +poseOnly 현재 자세만 +poseOnlyHint 화살표로 현재 표시된 자세의 눈·입만 이동합니다. 직접 만든 캐릭터의 특정 자세를 맞출 때 사용하세요. +eyeMvHint 기록 후 해당 지역에서 새로 부화하거나 성장한 다마고치에 적용합니다. 작은 캐릭터는 이동량이 절반입니다. +planEyes 눈과 입 +namesHint 본체에서 사용할 지역 이름과 다마고치 이름 및 아이템 이름을 수정합니다. +namesFields 지역 +namesChars 다마고치 +namesItems 아이템 +namesFind 검색 +namesUndo 모두 초기화 +planNames 이름 +planNamesN {n}개 변경 +saveParaOut 파라다이스 저장(.tamasave) +saveEmuOut TamaEmu 저장(.sav) +saveInfo 내보내기는 현재 ROM에서 저장 데이터를 추출합니다. 에뮬레이터 저장은 ROM에 가져온 뒤 파일로 저장하거나 기기에 기록합니다. 파라다이스 저장은 기기로 직접 기록하므로 먼저 연결하세요. +saveOutT 내보내기 +saveInT 가져오기 +saveSecProg 프로그램 +saveSecPara 파라다이스 +saveParaOutB 내보내기(.tamasave) +saveParaInB 기기에 기록(.tamasave) +saveProgInfo 선택한 프로그램의 저장을 현재 ROM에서 내보냅니다. 가져온 저장은 ROM 파일을 저장하거나 기기에 기록해야 적용됩니다. +saveParaInfo 현재 ROM에서 파라다이스 저장을 내보냅니다. ‘기기에 기록’은 연결한 기기에 직접 적용합니다. 슬롯으로 대상을 선택하세요. +saveSlotL 슬롯 +slotLive {n}(사용 중) +slotEmpty {n}(비어 있음) +slotNone 이 슬롯에는 저장 데이터가 없습니다. +slotField 저장은 {a}용이고 슬롯은 {b}용입니다. +slotDevOther 기기의 메뉴가 현재 ROM과 다릅니다. 먼저 기기에서 ROM을 읽으세요. +slotSure 기기의 {n} 슬롯에 기록하며 기존 저장을 교체합니다. 계속할까요? +slotDone 기기의 {n} 슬롯 교체 완료. +saveNoProg ROM에 프로그램이 없습니다. TamaEmu 저장에는 에뮬레이터가 함께 들어 있습니다. T7Emu·T18Emu는 에뮬레이터 탭에서 먼저 추가하세요. +saveBtnOut 내보내기({f}) +saveBtnIn 가져오기({f}) +saveEmuInDone TamaEmu 저장을 가져왔습니다({d}). ROM을 저장하거나 기기에 기록하세요. +saveEmuOther ROM의 TamaEmu는 {a}용, 저장은 {b}용입니다. 그래도 가져올까요? +saveNoRoom 이 ROM에는 TamaEmu를 넣을 공간이 없습니다. +saveEmuBad 이 프로그램에 맞는 저장 파일이 아닙니다. +saveNoEmu ROM에 에뮬레이터가 없습니다. +saveDone {n} 저장 완료. +saveNoClock {n} 저장 완료. 시계는 포함되지 않으므로 필요하면 앱에서 설정하세요. +devSaveRead 저장 데이터 백업 +devSaveWrite 저장 데이터를 기기에 기록 +devSaveHint 백업에는 파라다이스 저장·시계와 TamaEmu 또는 T7Emu 저장이 포함됩니다. 이 버튼으로는 파라다이스 저장만 기기에 기록합니다. +devSaveSure 기기({ed})의 현재 저장을 선택한 데이터로 교체합니다. 계속할까요? +devSaveDone {w}개 페이지 기록 완료. {c} 본체를 재시작할 수 있습니다. +devSaveClock 시계를 적용했습니다. +devSaveClockNo 본체에서 시계를 맞추세요. +devSaveGot 백업 완료: {n}. +fl_saveOtherEd 다른 에디션의 저장입니다(파일: {s}, 기기: {d}) +fl_saveFamily 이 에디션에 맞는 저장이 아닙니다 +fl_saveNoSettings 설정 영역이 없어 완전한 파라다이스 저장이 아닙니다 +fl_saveOutside 저장 영역 밖의 {n}개 페이지는 기록하지 않습니다 +fl_saveIncomplete 일부 페이지가 없습니다. 누락된 부분은 기기의 데이터를 유지합니다 +emuUndo 선택 취소 +progMain A+C로 실행 +progMainL 메뉴의 첫 항목 +progMenu 메뉴에서 실행 +progGone 저장 시 삭제 +progUndo 되돌리기 +progDel 제거 +progNone 펌웨어 또는 ROM을 선택하세요. 이후 추가한 프로그램은 본체 메뉴에 들어갑니다. +appBadMain {f}: 컬러 다마고치·TG18은 실행 전용 구성에서만 추가 프로그램으로 넣을 수 있습니다. 다른 구성에서는 위 에뮬레이터를 ×로 먼저 제거하세요. +emuInList ROM의 추가 프로그램: {n}. 다시 선택할 필요가 없습니다. +doomLinkLess , DOOM과 함께 사용하면 {m} MB 감소 +emuPack 펌웨어 압축 +emuPackHint 공간을 절약합니다(iD L 약 1 MB). 식당 등 일부 화면은 느려질 수 있습니다. +packNeed 이 펌웨어는 압축해야 들어갑니다. TamaEmu 항목의 ‘펌웨어 압축’을 켜세요. +packTip 팁: TamaEmu의 ‘펌웨어 압축’으로 공간을 절약할 수 있습니다. +emuNfc 4U: NFC 칩 에뮬레이션 +emuNfcHint 메뉴가 버튼 한 번에 반응합니다. 끄면 이전 방식으로 동작합니다. +emuClock 시작할 때 파라다이스 시간 가져오기 +emuClockHint 실행할 때마다 파라다이스의 시간으로 맞춥니다. 실행하지 않은 시간의 플레이는 재현하지 않습니다. +emuAuto 전원을 켜면 자동 실행 +emuAutoHint 휠을 길게 누르면 파라다이스로 돌아갑니다. A+C 또는 리셋 버튼으로 다시 실행합니다. +autoHintL 전원을 켤 때 메뉴 대신 실행합니다. B를 누른 채 켜면 메뉴가 나옵니다. +emuHas 이 ROM에 에뮬레이터가 들어 있습니다. +emuBig 펌웨어가 커서 지역 전환 기능을 함께 넣을 공간이 없습니다. +emuUp 저장할 때 새 에뮬레이터 버전을 넣습니다. ‘저장 데이터 유지’를 켜면 저장을 유지합니다. +emuOk 펌웨어 인식됨({size}). 저장할 때 추가합니다. +emuBad 펌웨어 인식 실패: {e} +t18Ok TG18 펌웨어 인식됨(T18Emu, 미츠·온). 저장할 때 추가합니다. +t18Has 이 ROM에 T18Emu가 들어 있습니다. +t18Use 홈 화면에서 A+C로 실행합니다. 휠을 길게 누르면 저장하고 종료합니다. 실행이 멈추면 A+C로 다시 시작한 뒤 3초 안에 휠을 누르세요. A로 확인하면 저장한 게임에서 다시 시작합니다. +emuGone 저장할 때 에뮬레이터를 제거합니다. +emuMissing 이 배포본에는 에뮬레이터 프로그램이 없습니다. +emuFail 에뮬레이터 추가 실패: {e} +savedEmu 저장 완료: {name} +t18Pics 성장 화면 이미지 +t18PicsPick 이미지 선택 +t18PicsDel 이미지 제거 +t18PicsOk 이미지 {n}개 적용. +t18PicsUnknown {f}: 알 수 없는 이름 +t18PicsHint 성장 화면에 표시할 PNG입니다. 파일 이름은 캐릭터 이름(Mametchi.png 등) 또는 번호(16.png)로 지정하세요. Android T18Emu의 erwachsen 폴더도 지원합니다(erwachsen.json 포함 전체 선택). 64×64로 조정합니다. +t18Items 아이템 +t18ItemsPick MyMeets 파일 선택 +t18ItemsNoSave 게임을 한 번 실행한 뒤 기기에서 ROM을 읽어야 아이템을 적용할 수 있습니다. +t18ItemsHint 아이템·방·포인트를 게임 저장에 적용합니다. ‘저장 데이터 유지’를 켜도 기기의 T18Emu 저장을 파일의 것으로 교체합니다. 다마고치는 유지하고 실행 상태는 초기화합니다. +t18ItemsNone 파일에 아이템이 없습니다. +t18ItemsOther {n}은 미츠·온이 아닌 {m}용입니다. 동작하지 않을 수 있습니다. +t18ItemsFull 공간 부족 +mmTitle MixingMeets(방문·결혼) +uartBusy 도구가 어댑터에 연결되어 있어 브리지를 사용할 수 없습니다. +uartFree UART 연결 해제 +uartFreed 어댑터를 해제했습니다. 게임을 실행하려면 본체를 재시작하세요. +uartRun 기기 작업이 끝날 때까지 기다리세요. +pairTitle 파라다이스 두 대 연결(방문·게임) +pairHint 두 기기의 상단 단자를 연결하고 모두 T18Emu를 실행합니다. 양쪽에서 CONNECTION → TAMAGOTCHI를 선택한 뒤 실제 기기처럼 진행하세요. +pairHintDigi 두 기기의 상단 단자를 연결하고 모두 V1Emu의 디지몬을 실행합니다. 실제 디지몬 두 대처럼 배틀을 선택하고 시작하세요. +pairHintPs 두 기기를 상단으로 연결하고 TamaEmu(P's)를 실행합니다. 양쪽에서 연결 → たまごっちP's → あそぶ. 한쪽은 あそびにいく, 다른 쪽은 ともだちをよぶ → ふたりで → 게임 → B를 선택하세요. +pairHintIdl 두 기기를 상단으로 연결하고 TamaEmu(iD L)를 실행합니다. 양쪽 게임의 연결 메뉴에서 실제 iD L처럼 진행하세요. +pairHintV3 두 기기를 상단으로 연결하고 V3Emu를 실행합니다. 양쪽 게임의 연결 메뉴에서 실제 V3처럼 진행하세요. +pairHintT7 두 기기를 상단으로 연결하고 T7Emu(타마고)를 실행합니다. 양쪽에서 연결 → TAMA-GO → VISIT 또는 GAME. 방문하는 기기에서 B를 누르세요. +mmLink Paramix 브리지 +mmDrag 북마크 바로 끌어 놓은 뒤 mixing-meets.com에서 클릭하세요. +mmHint 1. Paramix 브리지 버튼을 Chrome·Edge 북마크 바로 끌어 놓습니다.\n2. UART 연결을 해제하거나 도구를 닫습니다. 기록할 때처럼 어댑터를 연결하고 본체에서 CONNECTION → APP → VISIT를 선택합니다. 돌아올 때는 A → GO BACK → YES.\n3. mixing-meets.com의 Connect 또는 Return에서 북마크를 누른 뒤 Select Tamagotchi로 어댑터를 선택합니다.\n페이지를 이동할 때마다 북마크를 다시 누르세요. +t7Gp 고치 포인트 +t7GpHint 저장 가져오기처럼 ROM에 적용합니다. 다마고치는 유지하고 실행 상태는 초기화합니다. 본체에서 DOWNLOAD를 선택하세요. +t18KeepAsk T18Emu 아이템 또는 포인트가 변경되었습니다. ‘저장 데이터 유지’를 켜도 기기의 해당 저장을 ROM을 읽은 시점의 저장으로 교체합니다. 계속할까요? +t18ItemNo 번호 {n} +t18ItemOk {n}을 {k}에 넣었습니다. +t18Points 다마포인트 +t18A_food 음식 +t18A_item 아이템 +t18A_acc 액세서리 +t18A_room 방 +t18RoomBack 사용자 방 제거 +t18RoomBuiltin 기본 방 +dlcPick 다운로드 콘텐츠 추가 +dlcInfo 사용 중인 슬롯 보기 +progMore 설정과 콘텐츠 +progMakeMain 주 프로그램으로 지정 +progIsMain 주 프로그램 +v1Ok 초기 다마고치 또는 디지몬을 인식했습니다(V1Emu). +v3Ok 다마고치 커넥션 V3를 인식했습니다(V3Emu). +v3Use 홈 화면에서 A+C로 실행합니다. 휠 짧게: 설정, 길게: 돌아가기. +optVol 소리 크기 +optVolN 보통 +optVolQ 작게 +optVolL 크게 +optOff 끔 +optDim 밝기 +optScr 화면 자동 꺼짐 +optDev 본체에서도 휠을 짧게 눌러 설정할 수 있습니다. 본체 설정은 웹에서 다시 변경하기 전까지 유지됩니다. +optScrToy 원래 기기 설정 +v1Use 홈 화면에서 A+C로 실행합니다. 휠 짧게: 설정, 돌리기: 흔들기, 길게: 돌아가기. +progNoMainDoom DOOM이 주 프로그램입니다. 바꾸려면 DOOM을 ×로 먼저 제거하세요. +doomAutoHint 휠을 2초 누르면 파라다이스로 돌아가 그대로 유지됩니다. +progReplaced 주 프로그램을 {o}에서 {n}으로 바꿨습니다. +mainAuto 모든 프로그램이 들어가도록 {n}을 메뉴의 첫 항목으로 바꿨습니다. +mainNoRoom 첫 항목으로 바꾸려면 약 {k} KB가 더 필요합니다. 기존 구성을 유지합니다. +appTwice {n}은 이미 들어 있습니다. +progNoMainV1 V1Emu는 본체 메뉴에서만 실행합니다 +progNoMain 실행 전용 구성에서만 가능 +progMainNow {n}이 주 프로그램입니다. 위치가 바뀐 프로그램들의 저장이 초기화됩니다. +dlcLoading 읽는 중… +dlcNewArea 에뮬레이터의 메모리 배치를 다시 구성합니다. 기록 후 해당 저장이 초기화됩니다. +dlcHint 음식·옷·액세서리·게임 등의 .jpg 다운로드 파일 또는 .zip을 선택하세요. 여러 파일을 함께 선택할 수 있습니다. P's의 VDP는 세트 전체를 선택하세요. +dlcFreeN {n}개 남음 +dlcDel 제거 +dlcK0 식사 +dlcK1 간식 +dlcK2 의상 +dlcK3 액세서리 +dlcK4 아이템 +dlcK5 일상용품 +dlcK6 배경 +dlcK7 게임 +dlcK8 방문 장소 +dlcK10 VDP 레시피 +dlcK15 장식 +dlcK16 쿠폰 +dlcK17 빙고 +dlcK18 가챠 +dlcK19 캐릭터 +dlcOk {n}을 {k}의 {s}번 슬롯에 넣었습니다. +dlcBad {f}: {e} +dlcGone {n} 제거 완료. +figField 지역: +figAll 전체 +zipField 지역을 ZIP으로 내보내기 +fieldZipOk {f}: 캐릭터 {n}개와 이미지 {s}개를 ZIP으로 내보냈습니다. +fieldIn 지역 ZIP 가져오기 +fieldInBad 지역 ZIP이 아닙니다(field.json 없음). +fieldInOk {src} → {dst}: {n}개 부분 적용. +fieldInEyes 눈 이미지가 너무 큰 캐릭터 {k}개는 원본을 유지합니다. +zipFigs 모든 캐릭터 ZIP +zipAll 전체 이미지 ZIP +upload 이미지 시트 가져오기(PNG·ZIP) +numbers 번호 확인용 ROM +figHint 캐릭터는 큰 모습·작은 모습 각각의 몸·눈·입으로 구성됩니다. 캐릭터를 누르면 이미지 시트를 볼 수 있습니다. +allHint 배경, 메뉴, 아이템, 글꼴 이미지입니다. +moreColors 더 많은 색상 허용(최대 256색) +dimLoad 카드 열기 +dimHint 캐릭터 카드(4 MB) 또는 TamaSma 카드(1·2 MB) 덤프를 엽니다. 성체 교체에 적합합니다. 아기·유아·성장기는 눈을 공유하므로 원본을 유지합니다. +dimPick 카드 캐릭터 +dimTarget 교체할 캐릭터 +dimApply 적용 +dimEgg 카드의 알 적용 +dimBaby 아기 +dimNone 카드를 열면 캐릭터가 표시됩니다. +download 이미지 시트 다운로드 +uploadOne 이미지 시트 가져오기 +reset 원본으로 복원 +close 닫기 +working 잠시만 기다려 주세요… +dimNr 번호 +stUpd 저장 시 업데이트 +disclaimer 기기 변경·기록으로 기기가 동작하지 않거나 저장 데이터가 지워질 수 있습니다. 먼저 원본을 백업하고 작업 내용을 이해한 뒤 사용하세요. 도구는 보증 없이 제공되며 기기·데이터 손상에 대한 책임을 지지 않습니다. +trademarks Tamagotchi·Digimon은 BANDAI, DOOM·Wolfenstein은 id Software(ZeniMax Media), Game Boy·Pokémon mini는 Nintendo, SEGA·Master System은 SEGA, Arduboy는 Arduboy Inc.의 상표입니다. 상표·게임·캐릭터는 각 권리자의 소유이며 호환성 설명을 위해 언급합니다. 공식 제품이 아니며 해당 회사와 관련이 없습니다. 도구에 게임·펌웨어·게임 데이터는 포함되지 않습니다. 본인의 파일을 사용하세요. +devWarn 기록 전 원본을 백업하고 기록 중에는 전원을 유지하세요. 기기 기록에 대한 보증은 제공되지 않습니다. +footer 모든 파일 처리는 브라우저에서 실행됩니다. 원작: mameise · 한국어판: ITOSM. +edition 에디션 +sprites 이미지 +figures 캐릭터 +changed 변경됨 +space 캐릭터 여유 공간 +figure 캐릭터 +sprite 이미지 +mSize 칸 {w}×{h}, 이미지 {n}개, 격자 {iw}×{ih} +mColors {c}, 팔레트 세트: {p} +mDirect 직접 색상 RGB565 +mPal {n}색 +mKeep 여러 팔레트 세트(색상 변형): 가져오는 이미지에 원본 색상을 사용합니다. +mSheet 시트 {w}×{h}px. 격자가 맞도록 크기를 유지하세요. +mGroupRows 행 순서: 몸(20), 눈(20), 입(18), 작은 몸(24), 작은 눈(14), 작은 입(14). +notRom 파라다이스 덤프가 아닙니다: {e} +loaded {ed} 열기 완료: 이미지 {s}개, 캐릭터 {f}개. +saved 저장 완료: {name}\n이미지 {n}개 변경, 여유 공간 {kb} KB. +nothing 변경한 내용이 없습니다. +tooBig 여유 공간을 초과합니다. {e} +upOk 적용됨: {n} +upSkip 건너뜀: {list} +upNone 일치하는 파일이 없습니다. figur_0237.png 또는 sprite_0014.png 형식이어야 합니다. +sprSix 추가 지역의 이미지는 수정할 수 없습니다. +wrongSize {f}: {e} +resetOk 원본으로 복원했습니다. +dimOk 카드 캐릭터 {d}을 캐릭터 {g}에 적용했습니다. +eggOk 알을 교체했습니다. +numOk 캐릭터마다 번호를 표시하도록 바꿨습니다. ROM을 저장·기록한 뒤 성장 단계별로 표시되는 번호를 확인하세요. +notDim 알 수 없는 카드: {e} +leave 저장하지 않은 변경 사항이 있습니다. +roleFallback 대체 캐릭터 +roleBaby 아기 +roleAdult 첫 성체 +eyeHint 분홍 테두리는 눈입니다. 눈 레이어로 옮겨 깜빡임과 눈 표시를 유지합니다. 잘못 잡혔다면 눈을 클릭하세요. +eyeNone 보이는 눈이 없는 캐릭터 +dimEyesTooBig 눈 이미지가 너무 복잡해 눈 레이어를 적용하지 않았습니다. +roleFallbackText 캐릭터를 불러오지 못할 때 표시됩니다. 원본 유지를 권장합니다. +roleBabyText 알에서 부화합니다. +roleAdultText 여기부터 각 캐릭터가 고유한 눈을 사용합니다. +mEyes 눈 이미지의 바이트 크기를 유지해야 합니다. 너무 복잡한 눈은 거부하며 크기가 맞지 않으면 대체 캐릭터가 부화할 수 있습니다. +mColorsFig 원본 색상만 사용하면 게임의 개체별 색상 변경을 유지합니다. 새 색상은 고정 색상으로 적용합니다(최대 8색과 외곽선). +fl_timeout 기기 응답 시간 초과({c} {a}) +fl_noAck 기기가 응답하지 않습니다. 다운로드 화면인지 확인하세요. +fl_repeats 로드 재시도가 너무 많습니다 +fl_devCancel 기기에서 로드를 취소했습니다 +fl_unexpected 예상하지 못한 응답: {r} +fl_hello HELLO에 대한 응답이 올바르지 않습니다 +fl_notReady 플래시가 준비되지 않았습니다 +fl_readErr {a} 읽기 오류 +fl_noCrc {a}의 체크섬이 없습니다 +fl_cancelled 취소됨 +fl_size ROM 이미지 크기는 정확히 16 MB여야 합니다 +fl_notParadise 파라다이스 이미지가 아닙니다(SONIXDEV 없음) +fl_cancelledWrite 기록 취소됨. 본체 전원을 유지하고 다시 기록하세요 +fl_notAccepted 섹터 {a}을 받지 못했습니다. 전원을 유지하고 다시 기록하세요 +fl_differs 기록 후 섹터 {a}이 일치하지 않습니다. 전원을 유지하고 다시 기록하세요 +fl_checkFail {a} 검증 실패. 전원을 유지하고 다시 기록하세요 +fl_rescueBusy 복구 영역(0xFF0000)이 사용 중입니다 +fl_rescueMode 이전 기록이 중단되었습니다. 본체의 기록 화면에서 다시 기록하세요. +fl_rescueFail 복구 시작 프로그램 기록이 올바르지 않습니다 +fl_noRescue 복구 시작 불가: 0xFF0000이 사용 중입니다 +fl_noAnswer 응답이 없습니다. 본체를 다운로드 화면으로 전환하고 다시 시도하세요 +fl_noData 어댑터에서 데이터가 전혀 들어오지 않습니다. 다운로드 화면에서 다시 시도하고 케이블·드라이버를 확인하세요 +fl_garbled 데이터를 읽을 수 없습니다({n}바이트: {h}). TX·RX 배선과 어댑터 드라이버를 확인하세요 +fl_lost 기록 전에 기기 응답이 끊겨 아무것도 기록하지 않았습니다. 전원을 껐다 켜고 다운로드 화면에서 다시 연결하세요 +fl_appSilent 기록 프로그램을 전송했지만 응답하지 않습니다. 다시 시도하세요 +fl_unknownEd 새 ROM의 에디션을 알 수 없습니다. ‘저장 데이터 유지’를 해제하세요 +fl_otherEd 기기는 {d}, 새 ROM은 {r}입니다. 에디션을 바꾸려면 ‘저장 데이터 유지’를 해제하세요 +fl_noteNoFit 지역 {f}의 저장이 새 슬롯에 맞지 않아 유지하지 않습니다 +fl_noteMoved 지역 {f}의 저장을 새 슬롯으로 옮겼습니다 +fl_noteSaveMoved {n}의 저장을 보존했습니다 +fl_noteDropped 새 ROM에 지역 메뉴가 없어 기기에 보관된 지역별 저장이 삭제됩니다 +fl_noteEdKept 기기 {d}, 새 ROM {r}: 같은 펌웨어이므로 기기의 저장과 지역({d})을 유지합니다 +fl_noteEmu TamaEmu 펌웨어를 새로 선택해 초기 상태로 시작합니다. 업데이트만 하려면 기존 ROM을 열고 저장하세요 +menuKo 본체 A+C 메뉴를 한국어로 만들기 +menuKoHint A+C 메뉴의 화면과 다마고치 및 아이템 이름을 한국어로 표시합니다. diff --git a/src/menu-font-ko.js b/src/menu-font-ko.js new file mode 100644 index 0000000..3719219 --- /dev/null +++ b/src/menu-font-ko.js @@ -0,0 +1,8 @@ +// Generated Galmuri9 native Korean font. See third-party/Galmuri-OFL.txt. +(function(root){ +const fixed="·가간감값강개거건게경계고과관그글금기까꺼끄끔난남뉴는니다단대데도돌동되됨됩뒤드득때랜램량러레력로록료류름리릭마메면목미방배벨변보복본봄부분불비사삭상새서선설성세셔소손수숫스습시식실아않알았어업없었에역열예오옵완요용운워원유으을음의이인읽임입있자작잠장재저적전정제조존중지짐집참체초추취치카캐컬코크타택터템통트패편포품프플픔피하한할함합행현형화확환회후휠", native="가각간갇갈갉갊감갑값갓갔강갖갗같갚갛개객갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫났낭낮낯낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫달닭닮닯닳담답닷닸당닺닻닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많맏말맑맒맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바박밖밗반받발밝밞밟밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤샥샨샬샴샵샷샹섀섄섈섐섕서석섞섟선섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄업없엇었엉엊엌엎에엑엔엘엠엡엣엥여역엮연열엶엷염엽엾엿였영옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응읒읓읔읕읖읗의읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝", data="S09GMd8JAAAAAAAAAEAAAAAAAAAA+QJAkCQRhEITBAEAAPkCQJhE4QBEAQB/AAD5AkCYROEAB/EEfwAA+QJhE4QAFIchVHiAAPkCQJhE4QAD4QQ+AAD6gqCoKhOEoisKAoAA+QJAkDwRBEITBAEAAPkCQPBE4QBEAQB/AADyhKEoehKIoisKAoAA+QPAkFzhAAPhBD4AAPKEoehKEouiKwoCgAB/AEAQBAkCQIP+AAAA+QJAkCQpiEIT9AEAAPkCQpiE/QBEAQB/AAB/AEAQBAEAQAP+AAAAfwBAE/4AH8HxgH8AAH8AQBAE/4AH8QR/AAD5AkCQJBEEQhMEAQAA+RJEkSRJkkSSRAEAAPkSRJE8SRJEkkQBAAB3BEEQRBEEQAP+AAAAdwRBEAD/gAfxBH8AAIEgSBoE/QBEAQB/AACBIEgaBP0AB/EEfwAAQBAEAfwAP+IgiCIAAEAQB/AA/4AEAQB/AACBIEgSBIEgSBPkAQAA+SBIEgSBoEgT5AEAAPkgSBoE+QBEAQB/AAD6oKgqCoOgqCvqAoAA+qCoKjqCoKgr6gKAAH8QBAEAfwIAg/4AAAB/EAfwIP+fwfGAfwAAfxAH8CD/gAPhBD4AAPkgSBIE+QhCE/QBAAD5IE+QhP0AB/EEfwAA+SBPkIT9EEfxBH8AAPkgSBPkAT9CEIQhAAB/EAQBAH8AAAP+AAAAfxAH8AD/gAfwBAEAAPqoqiqKo6iqK+oCgAD6gq+6CvqApAEAf4AA+oKvugr6gAf5An+AAPkCb5IG+QAD4QQ+AAD5AkCT5IcgSBPkAQAA8oShK8qOoKgrygKAAPkDz5Ic+QAH8AQBAAB/AEfxAH8CAIP+AAAAfwfGAfwIP+AB/AEAAH8AR/EAfwiCI/4AAAB/AEfxAH8AD/iIIgAAfwfGAfz/gAfxBH8AAPkCQJPkgSBIE+QBAAD5Ak+SBPkAB/AEAQAA+SJIkiSJokiT5AEAAPqiqKo6iqKoq+oCgAD5I8iSPPkARAEAfwAAfxBH8CD/gAfwBAEAAPkiSJIkiSJIk+QBAACJPkiaJPkAA+EEPgAAiqKoq+qLoqir6gKAAIq/qKvqAB/h+YB/gACJP8iSPPkARAEAfwAAQR/EEQR/AgCD/gAAAEEfxBH8CD/gAfwBAABBH8QR/Ag/4AEAfwAAQR/EEfwIP+fxBH8AAEEfxBH8AD/ggCAIAABBH8QR/AA/4IEAfwAAQR/EE/4IH8HxgH8AAIkiSJPkiSJIk+QBAAAhCEIQhFGUSJIkAQAAIQhCGUSJAAfwBAEAACEIQhlEiQAD4QQ+AAAiiKIoilOUqKoqAoAAIQhCEJxRFEiSJAEAACEIQnFEiQBEAQB/AAAhCcUSJAAfwfGAfwAAIQhCcUSJAAPhBD4AACKIoii6UpSoqioCgAAhCEJwhFEVyJIkAQAACAIBQIhBAgCD/gAAAAgFBjAg/4AEAQB/AAAIBQIhBAA/4IAgCAAACAUGMAD/ggCAUGMAAAgCAUCIQQAAA/4AAAAIBQYwAP+QR/EEfwAAIQhCEIRRFEiSJAEAACEIQhFEiQAH8AQBAAAhCEUSJAAfwfGAfwAAcSJIkiSJokiRxAEAAHEiSJokcQCE+RRyAABxImiRxAAfwfGAfwAAcSJImiRxAAIhVIiAAHEiSJI8iSJIkcQBAABxI8iRxAAQR/EEfwAAcSPIkcQAFIchVHiAAHEiSPIkcQACIVSIgAByoqiqOoqiqKnKAoAAcSPIkjxxAAfwBAEAAHEjyJHcAR/B8YB/AAByoqjqKoqjqKnKAoAAPhBEEQQ+AgCD/gAAAD4QQ+Ag/5BH8QR/AABxIkcYhP0ARAEAfwAAPhBEEQQ+CIIj/gAAAD4QQ+CI/4AD4QQ+AAA+EEPgAP+CBIEAfwAAcSJIkcQBP0IQnCEAAHEiRxP0JwhEAQB/AAA+EEQQ+AA/4iCIIgAAPhBEEQQ+AAAD/gAAAD4QQ+P+AB/B8YB/AAA+EEPgAP+AB/EEfwAAcSJIkiRxAEAT9AEAAHEiSJIkiSJIkcQBAABxIkiSJHEARAEAfwAAcSJIkcQAHcMRBHEAAHEiSJIkcQAH8QR/AABxIkiRxAAQR/EEfwAAcSJIkiRxAAIhVIiAAPkIQhCEUZRIkiQBAAD5CEIZRIkAB/AEAQAA+QhCGUSJAAfxBH8AAPkIQhlEiQAD4QQ+AAD6iKIoilOUqKoqAoAA+QhCEJxRFEiSJAEAAPkIQnFEiQAH8AQBAAD5CEJxRIkARAEAfwAA+QhCcUSJAAPhBD4AAPqIoii6UpSoqioCgAB/AgFAiEECAIP+AAAAfwUGMCD/gAQBAH8AAH8FBjAA/4ID4QQ+AAD5CEIQhFEUSJIkAQAA+QhCEUSJAAfxBH8AAPkIRRIkABBH8QR/AAAhPkIZRIkAB/EEfwAAcoCvqIoulKUqKgKAABwAB/AgFBrAg/4AAAAIH8CAUGMAD/ggCAAAIT5FEiQBP0IQhCEAAHEAT5CEIRRFEiQBAAD5AkCT5BGEQhMEAQAA+oKgq+oThKIrCgKAAPkCT/BE4R/B8YB/AAB/AEAR/AECQIP+AAAAfwBAEfwBAEAD/gAAAPkgSBPkgaBIE+QBAAD6oK+6CvqAB/gCAIAA+SBIE9yBIEgT5AEAAPKgr2oK8oAH+QJ/gAB/H4QB/Ag/4+EEPgAAfxAH8QB/AAAD/gAAAPqUpSlKU5SlK+oCgAD5FcURXPkARAEAfwAAfwiCIIh/AgCD/gAAAH8Ih/AA/4IH8QR/AAB/CIIgiH8AAAP+AAAAfwiH8/4AH8HxgH8AAH8Ih/AA/4AH8QR/AAD9EkSRJEkSRJP0AQAAcQBP0ARxokiRxAEAACE/RxokcQBEAQB/AAAhP0caJHEfwfGAfwAAIT9HGiRxAAfxBH8AACE/RxokcRBH8QR/AAAivqc6KnKAA/ECPwAAIT7HEixxAEQBAH8AACE+xxIscQAD4QQ+AAAhP0ARxImcQhP0AQAAIT9EmMQhP0AB/AEAACE/RJjEIT9AAQB/AAAhP0ARxIkcQhP0AQAACD/j4QQ+AA/4IAgAACE/RJP0IB/B8YB/AAD5AkCQJBGEQhMEAQAA+QJAmEThAAfwBAEAAPkCQJhE4QBEAQB/AAD5AkCYROEAB/EAfwAA+QJhE4QAH8HxgH8AAPkCYROEAB3DEQRxAAD5AmEThAAdw1EUdwAA+QJAmEThAAfxBH8AAPkCYROEABBH8QR/AAD5AmEThAAUhyFUeIAA+QJAmEThAECAUGMAAPkCQJhE4QACIVSIgAD5AkCYROEAA+EEPgAA+QJAmEThAAfwUGMAAPkCQJhE4QIH8FBjAAD5AmEThAAfx+EAfwAA+QJAmEThAAfwiH8AAPkCQJhE4QIH8IgcAAD6gqCoKhOEoisKAoAA+oKguErigAf4AgCAAPqCoLhK4oCkAQB/gAD6guErigAf4fmAf4AA+oKguErigAf5An+AAPqC4SuKABAn+QJ/gAD6gqC4SuKAoIBQYwAA+oKguErigAIhVIiAAPqCoLhK4oAD8QI/AAD5AkCYJBEEYhMEAQAA+QJgkEbhAAfwBAEAAPkCYJBG4QBEAQB/AAD5AmEThgEfwfGAfwAA+QJgkEbhAECAUGMAAPkCYJBG4QAD4QQ+AAD6gqC4KhKE4isKAoAA+oLgqE7igKQBAH+AAPqC4SuOAp/h+YB/gAD5AkCQPBEEQhMEAQAA+QJA8EThAAfwBAEAAPkCQPBE4QBEAQB/AAD5AkDwROEAB/EAfwAA+QPBE4QAH8HxgH8AAPkDwROEAB3DURR3AAD5AkDwROEAB/EEfwAA+QPBE4QAEEfxBH8AAPkCQPBE4QBAgFBjAAD5AkDwROEAAiFUiIAA+QJA8EThAAPhBD4AAPkCQPBE4QAH8FBjAAD5A8EThAAfx+EAfwAA+QJA8EThAAfwiH8AAPkCQPBE4QIH8IgcAADyhKEoehKIoisKAoAA8oSh6IrCgKQBAH+AAPKEoeiKwp/h+YB/gADyhKHoisKAB/kCf4AA8oSh6IrCkCf5An+AAPKEoeiKwoCggFBjAADyhKHoisKAAiFUiIAA8oSh6IrCgAPxAj8AAPkCQPAkEQXCEwQBAAD5A8CQXOEAB/AEAQAA+QPAkFzhAAfwJAkAAPkDwJBc4QBEAQB/AAD5A8CQXOEAB/EAfwAA+QPBE5wBH8HxgH8AAPkDwJBc4QAH8QR/AAD5A8ETnAEQR/EEfwAA+QPAkFzhAECAUGMAAPkDwJBc4QACIVSIgAD5A8CQXOEAA+EEPgAA+QPBE5wBH8fhAH8AAPKEoehKEouiKwoCgADyh6EousKApAEAf4AA8oehKLrCn+H5gH+AAPKHoSi6wpAn+QJ/gADyh6EousKAoIBQYwAAfwBAEAQJAkCD/gAAAH8AQJAg/4AH8AQBAAB/AECQIP+ABAEAfwAAfwBAkCD/gAfxAH8AAH8AQJP+AB/B8YB/AAB/AECT/gAdw1EUdwAAfwBAk/4AHIMhFHiAAH8AQJP+AByD+RRyAAB/AECQIP+AB/EEfwAAfwBAkCD/kEfxBH8AAH8AQJAg/4AAgFBjAAB/AECQIP+AA+EEPgAAfwBAkCD/gAfwUGMAAPkCQJAkKYhCE/QBAAD5AkKYhP0AB/AEAQAA+QJCmIT9AEQBAH8AAPkCQpv0AB/B8YB/AAD5AkKb9AAdw1EUdwAA+QJCmIT9AAfxBH8AAPkCQpiE/RBH8QR/AAD5AkKYhP0AQIBQYwAA+QJCmIT9AAPhBD4AAPqCoKgqK4iiK+oCgAD6gqK4ivqApAEAf4AA+oLiq/oAH+H5gH+AAPqCoriK+pAn+QJ/gAD6gqK4ivqAAiFUiIAA+oKiuIr6gAPxAj8AAPkCQJAkKQhCE/QBAAD5AkKQhP0AB/AEAQAA+QJCkIT9AEQBAH8AAPkCQpP0AB/B8YB/AAD5AkKQhP0AB/EEfwAA+QJCkIT9EEfxBH8AAPkCQpCE/QBAgFBjAAD5AkKQhP0AA+EEPgAAfwBAEAQlCUJD/gAAAH8AQlCQ/4AEAQB/AAB/AEJT/gAfwfGAfwAAfwBCUJD/kEfxBH8AAH8AQlCQ/4AAgFBjAAB/AEAQBP+CAIAgCAAAfwBAEAT/ggfwBAEAAH8AQBAE/4IEgQB/AAB/AEAQBP+CB/EAfwAAfwBAE/4IH8HxgH8AAH8AQBP+CB3DEQRxAAB/AEAT/ggdw1EUdwAAfwBAE/4IHIP5FHIAAH8AQBAE/4IH8QR/AAB/AEAT/ggQR/EEfwAAfwBAE/4IAACAUGMAAH8AQBAE/4ID4QQ+AAB/AEAT/ggAB/BQYwAA+QJAkCT9CEJwhCEAAPkCQJP0JwhH8AQBAAD5AkCT9CcIRAEAfwAA+QJP0JwhH8HxgH8AAPkCQJP0JwhCIVSIgAD5AkCT9CcIQ+EEPgAA8oShKEr6iKLoiiKAAPKEoSvqLoiggFBjAAD5AkCQJP0IQhCEIQAA+QJAk/QhCAfwBAEAAPkCQJP0IQhEAQB/AAD5AkCT9CAfwfGAfwAA+QJAk/QhCAfxBH8AAPkCQJP0IRBH8QR/AAD5AkCT9CEIQIBQYwAAfwBAEAT/iIIgiCIAAH8AQBAE/4SFIQB/AAB/AEAT/iIfwfGAfwAAfwBAEAQBAEAD/gAAAH8AQBAE/4AH8AQBAAB/AEAQBP+ABAEAfwAAfwBAEAT/gAfxAH8AAH8AQBP+AB/B8YB/AAB/AEAT/gAdwxEEcQAAfwBAEAT/gAfxBH8AAH8AQBP+ABBH8QR/AAB/AEAQBP+AAIBQYwAAfwBAEAT/gAPhBD4AAPkCQJAkCQJAE/QBAAD5AkCQJBEEQhMEAQAA+QJAkEThAAfwBAEAAPkCQJBE4QBEAQB/AAD5AkCQROEAB/EAfwAA+QJBE4QAH8HxgH8AAPkCQROEAB3DURR3AAD5AkCQROEAB/EEfwAA+QJBE4QAEEfxBH8AAPkCQJBE4QBAgFBjAAD5AkCQROEAA+EEPgAA+QJAkEThAAfwUGMAAPkCQJBE4QAH8Ih/AAD5EkSRJEmSRJJEAQAA+RJEmSSRAAfwBAEAAPkSRJkkkQAH8CQJAAD5EkSZJJEARAEAfwAA+RJkkkQAH8HxgH8AAPkSZJJEAB3DURR3AAD5EkSZJJEAB/EEfwAA+RJkkkQAEEfxBH8AAPkSRJkkkQBAgFBjAAD5EkSZJJEAAiFUiIAA+RJEmSSRAAPhBD4AAPkSZJJEAB/H4QB/AAD6kqSpKkuSpKpKAoAA+pKkuSqSgAf4AgCAAPqSpLkqkoCkAQB/gAD6kuSqSgAf4fmAf4AA+pKkuSqSgAf5An+AAPqS5KpKABAn+QJ/gAD6kqS5KpKAoIBQYwAA+pKkuSqSgAIhVIiAAPqSpLkqkoAD8QI/AAD5EkSZJEkSZJJEAQAA+RJkkSaRAAfwBAEAAPkSZJJGAR/B8YB/AAD5EkSRPEkSRJJEAQAA+RJE8SSRAAfwBAEAAPkSRPEkkQAH8CQJAAD5EkTxJJEARAEAfwAA+RPEkkQAH8HxgH8AAPkSRPEkkQAH8QR/AAD5E8SSRAAQR/EEfwAA+RJE8SSRAECAUGMAAPkSRPEkkQACIVSIgAD5EkTxJJEAA+EEPgAA+pKkqTpKkqSqSgKAAPqSpOkqkoAH+AIAgAD6kqTpKpKApAEAf4AA+pKk6SqSgAf5An+AAPqSpOkqkoCggFBjAAD6kqTpKpKAA/ECPwAA+RJE8SRJE8SSRAEAAPkTxJE8kQBEAQB/AAD5E8SSXAEfwfGAfwAA+RPEkTyRAECAUGMAAPkTxJE8kQACIVSIgAD5E8SSXAEfx+EAfwAA+pKk6SpKk6SqSgKAAHcEQRBEEQIAg/4AAAB3BEGQIP+AB/AEAQAAdwRBkCD/gAQBAH8AAHcEQZAg/4CE+RRyAAB3BECD/gAfwfGAfwAAdwRBkCD/gAfxBH8AAHcEQZAg/5BH8QR/AAB3BEGQIP+AAIBQYwAAdwRBkCD/gAPhBD4AAHcEQZAg/4AH8FBjAAB3BEGQIP+CB/BQYwAA/QlCUJQlhEET9AEAAP0JQlhE/QAH8AQBAAD9CWET9AAfwfGAfwAA/QlCWET9AAIhVIiAAP0JQlhE/QAD4QQ+AAD6kqSpKkuIoivqAoAA+pKkuIr6gAf4AgCAAPqSpLiK+oAD8QI/AAD9CUJQlCUEQRP0AQAA/QlCUET9AEQBAH8AAP0JQRP0AB/B8YB/AAD9CUJQRP0AB/EEfwAA/QlCUET9EEfxBH8AAP0JQlBE/QAD4QQ+AAB3BEEQRBEJAkP+AAAAdwRBEET/ggCAIAgAAHcEQRAA/4IH8AQBAAB3BEEQAP+CBIEAfwAAdwRBE/4IH8HxgH8AAHcEQRP+CByD+RRyAAB3BEEQAP+CB/EEfwAAdwRBE/4IEEfxBH8AAHcEQRP+CAAAgFBjAAB3BEEQAP+CA+EEPgAAdwRBE/4IAAfwUGMAAP0JQlCUAT9CEJwhAAD9CU/QnCEfwfGAfwAA/QlCU/QnCEIhVIiAAP0JQlP0JwhD4QQ+AAD6kqSpKvqIouiKIoAA+pKkq+ouiKf4AgCAAPqSpKvqLoikAQB/gAD6kq+ouiKf4fmAf4AA+pKkq+ouiKf5An+AAPqSpKvqLpCn+QJ/gAD6kqSr6i6AoiFUiIAA/QlCUJQBP0EQRBEAAP0JQlP8EQREAQB/AAD9CUJT/BAfwfGAfwAA/QlCU/wRBAfxBH8AAP0JQlP8EBRH8QR/AAB3BEEQRP+IgiCIIgAAdwRBEEQRBEAD/gAAAHcEQRAA/4AH8AQBAAB3BEEQAP+ABAEAfwAAdwRBE/4AEIT5FHIAAHcEQRP+AB/B8YB/AAB3BEET/gAdw1EUdwAAdwRBE/4AHIP5FHIAAHcEQRAA/4AH8QR/AAB3BEET/gAQR/EEfwAAdwRBEAD/gACAUGMAAHcEQRAA/4AD4QQ+AAB3BEET/gAfx+EAfwAA+RJEkSRJEkSSRAEAAPkSRJEkkQAH8AQBAAD5EkSRJJEARAEAfwAA+RJEkkQAH8HxgH8AAPkSRJEkkQAH8QR/AAD5EkSSRAAQR/EEfwAA+RJEkSSRAECAUGMAAPkSRJEkkQAD4QQ+AACBIEgSBIGgSBP0AQAAgSBIGgT9AAfwBAEAAIEgSBoE/QAH8CQJAACBIEgaBP0ARAEAfwAAgSBIGgT9AAfxAH8AAIEgaBP0AB/B8YB/AACBIGgT9AAdwxEEcQAAgSBoE/QAHcNRFHcAAIEgSBoE/QAH8QR/AACBIGgT9AAQR/EEfwAAgSBIGgT9AECAUGMAAIEgSBoE/QACIVSIgACBIEgaBP0AA+EEPgAAgSBIGgT9AAfwUGMAAIEgSBoE/QIH8FBjAACBIGgT9AAfx+EAfwAAgSBIGgT9AgfwiBwAAIKgqCoKg6CoK+oCgACCoKg6CvqAB/gCAIAAgqCoOgr6gKQBAH+AAIKg6CvqAB/h+YB/gACCoKg6CvqAB/kCf4AAgqDoK+oAECf5An+AAIKgqDoK+oCggFBjAACCoKg6CvqAAiFUiIAAgqCoOgr6gAPxAj8AAIEgSBoEgSBoE/QBAACBIGgSBv0AB/AEAQAAgSBoEgb9AEQBAH8AAIEgaBP2AR/B8YB/AACBIGgSBv0AB/EEfwAAgSBoEgb9AAPhBD4AAIEgSBI8gSBIE+QBAACBIEhyBPkAB/AEAQAAgSBIcgT5AAcgVBiAAIEgSHIE+QBEAQB/AACBIcgT5AAfwfGAfwAAgSHIE+QAHcNRFHcAAIEhyBPkAB1DcRR3AACBIEhyBPkAB/EEfwAAgSHIE+QAEEfxBH8AAIEgSHIE+QBAgFBjAACBIEhyBPkAAiFUiIAAgSBIcgT5AAPhBD4AAIEhyBPkAQIH8IgcAACCoKgqOoKgqCvqAoAAgqCo6gr6gAf4AgCAAIKgqOoK+oCkAQB/gACCo6gr6gAf4fmAf4AAgqCo6gr6gAf5An+AAIKjqCvqABAn+QJ/gACCoKjqCvqAAIBQYwAAgqCo6gr6gAIhVIiAAIKgqOoK+oAD8QI/AACBIEjyBI8gSBPkAQAAgSHIEhzxAAfwBAEAAIEhyBIc8QBEAQB/AACBIcgT3AEfwfGAfwAAgSHIEhzxAAfxBH8AAIEhyBPcARBH8QR/AACBIcgSHPEAAiFUiIAAgSHIEhzxAAPhBD4AAIEhyBPcAR/AEfwBAACCoKjqCo6gqCvqAoAAgqOoKjrygKQBAH+AAEAQBAEAfwIAg/4AAABAEAfwIP+AB/AEAQAAQBAH8CD/gAQBAH8AAEAfwIP+AB/B8YB/AABAH8CD/gAdw1EUdwAAQBAH8CD/gAfxBH8AAEAQB/Ag/5BH8QR/AABAEAfwIP+AAIBQYwAAQBAH8CD/gAPhBD4AAEAQB/Ag/4AH8Ih/AABAEAfwIP+CB/CIHAAAgSBIEgT5iEIT9AEAAIEgT5iE/QBEAQB/AACBPmIT9AAfwfGAfwAAgSBPmIT9AAIhVIiAAIEgSBIE+QhCE/QBAACBIE+QhP0ARAEAfwAAgT5CE/QAH8HxgH8AAIEgT5CE/QAH8QR/AACBIE+QhP0QR/EEfwAAgSBPkIT9AECAUGMAAEAQBAEAfwiCI/4AAABAEAfwiP+AB/AEAQAAQBAH8Ij/gAQBAH8AAEAfwiP+AB/B8YB/AABAEAfwiP+QR/EEfwAAQBAH8Ij/gACAUGMAAEAQB/CI/4AD4QQ+AABAEAQB/AA/4IAgCAAAQBAH8AD/ggfwBAEAAEAQB/AA/4IEgQB/AABAEAfwAP+CB/EAfwAAQB/AA/4IH8HxgH8AAEAQB/AA/4IH8QR/AABAEAfwAP+SR/EEfwAAQBAH8AD/ggCAUGMAAEAQB/AA/4ID4QQ+AACBIEgT5AE/QhCcIQAAgT5AE/QnCEIhVIiAAIKgqCvqAr6iKLoigACBIEgT5AE/QhCEIQAAgSBPkAT9CEYBAH8AAIE+QBP0IB/B8YB/AACBIE+QBP0IB/EEfwAAgT5AE/QgEEfxBH8AAEAQBAH8AD/iIIgiAABAEAfwAP+Ih/AEAQAAQB/AA/4iH8HxgH8AAEAQB/AA/4iH8QR/AABAH8AD/iIQR/EEfwAAQBAH8AD/iIPhBD4AAEAQBAEAfwAAA/4AAABAEAfwAP+AB/AEAQAAQBAH8AD/gAQBAH8AAEAfwAP+AB/B8YB/AABAH8AD/gAdwxEEcQAAQB/AA/4AHcNRFHcAAEAQB/AA/4AH8QR/AABAEAfwAP+QR/EEfwAAQBAH8AD/gACAUGMAAEAQB/AA/4AD4QQ+AABAEAfwAP+AB/BQYwAAQBAH8AD/gAfwiH8AAIEgSBIE+QBAE/QBAACBIE+QBP0ARAEAfwAAgT5AE/QAH8HxgH8AAIEgSBIEgSBIE+QBAACBIEgSBPkAB/AEAQAAgSBIEgT5AEQBAH8AAIEgSBPkAB/B8YB/AACBIEgT5AAdw1EUdwAAgSBIEgT5AAfxBH8AAIEgSBPkABBH8QR/AACBIEgSBPkAQIBQYwAAgSBIEgT5AAPhBD4AAIEgSBIE+QAH8Ih/AAD5IEgSBIGgSBPkAQAA+SBIGgT5AAfwBAEAAPkgSBoE+QAH8CQJAAD5IEgaBPkARAEAfwAA+SBIGgT5AAfxAH8AAPkgaBPkAB/B8YB/AAD5IGgT5AAdwxEEcQAA+SBoE+QAHcNRFHcAAPkgaBPkAB1DcRR3AAD5IGgT5AAcg/kUcgAA+SBIGgT5AAfxBH8AAPkgaBPkABBH8QR/AAD5IEgaBPkAQIBQYwAA+SBIGgT5AAIhVIiAAPkgSBoE+QAD4QQ+AAD5IEgaBPkAB/BQYwAA+SBIG+QBAgfwUGMAAPkgSBvkAQIH8IgcAAD6oKgqCoOgqCvqAoAA+qCoOgr6gAf4AgCAAPqgqDoK+oCkAQB/gAD6oOgr6gAf4fmAf4AA+qCoOgr6gAf5An+AAPqg6CvqABAn+QJ/gAD6oKg6CvqAoIBQYwAA+qCoOgr6gAIhVIiAAPqgqDoK+oAD8QI/AAD5IEgaBIEgaBPkAQAA+SBIEjyBIEgT5AEAAPkgSHIE+QAH8AQBAAD5IEhyBPkAB/AkCQAA+SBIcgT5AEQBAH8AAPkgSHIE+QAH8QB/AAD5IcgT5AAfwfGAfwAA+SHIE+QAHcNRFHcAAPkhyBPkAB1DcRR3AAD5IEhyBPkAB/EEfwAA+SHIE+QAEEfxBH8AAPkgSHIE+QBAgFBjAAD5IEhyBPkAA+EEPgAA+SBIc+QBAgfwUGMAAPkgSHIE+QAH8Ih/AAD6oKgqOoKgqCvqAoAA+qCo6gr6gAf4AgCAAPqgqOoK+oCkAQB/gADyo6grygAf4fmAf4AA+qCo6gr6gAf5An+AAPqgqOoK+pAn+QJ/gAD6oKjqCvqAAIBQYwAA+qCo6gr6gAIhVIiAAPqgqOoK+oAD8QI/AAD5IEhyBIEhyBPkAQAA8SHIEhzxAEQBAH8AAPEhyBPcAR/B8YB/AADxIcgSHPEAAiFUiIAA8SHIEhzxAAPhBD4AAPKgqOoKgqOoK8oCgADyo6gqOvKApAEAf4AAfxAEAQB/AgCD/gAAAH8QB/Ag/4AH8AQBAAB/EAfwIP+ABAEAfwAAfxAH8CD/gAfxAH8AAH8QB/Ag/5/B8YB/AAB/EAfwIP+dw1EUdwAAfxAH8CD/nAMhFHiAAH8QB/Ag/4AH8QR/AAB/EAfwIP+QR/EEfwAAfxAH8CD/gACAUGMAAH8QB/Ag/4AD4QQ+AAB/EAfwIP+CB/BQYwAAfxAH8CD/kAfxAH8AAPkgSBIE+YhCE/QBAAD5IEgb5CE/QAEAfwAA+SBPmIT9H8HxgH8AAPqgqCoK+4iiK+oCgAD6oK+4ivqAAiFUiIAA+SBIEgT5CEIT9AEAAPkgSBPkIT9AAQB/AAD5IE+QhP0fwfGAfwAA+SBPkIT9AAfxBH8AAPkgT5CE/RBH8QR/AAD5IE+QhP0AQIBQYwAAfxAEAQB/CIIj/gAAAH8QBAH8AD/ggCAIAAB/EAfwAP+CB/AEAQAAfxAH8AD/ggSBAH8AAH8QB/P+CB/B8YB/AAB/EAfwAP+CB/EEfwAAfxAH8AD/kkfxBH8AAH8QB/AA/4IAgFBjAAB/EAfwAP+CA+EEPgAA+SBIE+QBP0IQnCEAAHkQR5P0JwhCIVSIgAD6oKgr6gK+oii6IoAAepCnq+ouiKPxAj8AAPkgSBPkAT9CEIQhAAD5IE+QBP0IRgEAfwAAeRBHk/QgH8HxgH8AAPkgT5P0IBBH8QR/AAD5IE+QBP0IQIBQYwAA+SBPkAT9CAPhBD4AAH8QBAH8AD/iIIgiAAB/EAfwAP+EhSEAfwAAfxAH8/4iH8HxgH8AAH8QB/AA/4iH8QR/AAB/EAfwAP+Ig+EEPgAAfxAEAQB/AAAD/gAAAH8QB/AA/4AH8AQBAAB/EAfwAP+ABAEAfwAAfxAH8AD/gAfxAH8AAH8QB/P+AB/B8YB/AAB/EAfz/gAdw1EUdwAAfxAH8AD/gAfxBH8AAH8QB/AA/5BH8QR/AAB/EAfwAP+AAIBQYwAAfxAH8AD/gAPhBD4AAPkgSBIE+QBAE/QBAAD5IEgSBIEgSBPkAQAA+SBIEgT5AAfwBAEAAPkgSBIE+QBEAQB/AAD5IEgSBPkAB/EAfwAA+SBIE+QAH8HxgH8AAPkgSBIE+QAH8QR/AAD5IEgT5AAQR/EEfwAA+SBIEgT5AECAUGMAAPkgSBIE+QACIVSIgAD5IEgSBPkAA+EEPgAA+SBIEgT5AAfwUGMAAP0kSRJEkaRJE/QBAAD9JEkaRP0AB/AEAQAA/SRJGkT9AEQBAH8AAP0kaRP0AB/B8YB/AAD9JEkaRP0AB/EEfwAA/SRpE/QAEEfxBH8AAP0kSRpE/QBAgFBjAAD9JEkaRP0AAiFUiIAA/SRJGkT9AAPhBD4AAP0kSRpE/QIH8IgcAAD6qKoqiqOoqivqAoAA+qiqOor6gAf4AgCAAPqoqjqK+oCkAQB/gAD6qOor6gAf4fmAf4AA+qiqOor6gAf5An+AAPqo6ivqABAn+QJ/gAD6qKo6ivqAoIBQYwAA+qiqOor6gAIhVIiAAPqoqjqK+oAD8QI/AAD9JEkSXJEkSRP0AQAA/SRJckT9AAfwBAEAAP0kSXJE/QBEAQB/AAD5KcoT5AAfwfGAfwAA+SnKE+QAHcNRFHcAAPkpyhPkAB1DcRR3AAD9JElyRP0AB/EEfwAA+SnKE+QAEEfxBH8AAP0kSXJE/QBAgFBjAAD9JElyRP0AAiFUiIAA/SRJckT9AAPhBD4AAP0kSXJE/QIH8IgcAAD6qKoquqKoqivqAoAA+qiq6or6gAf4AgCAAPqoquqK+oCkAQB/gAD6qaor6gAf4fmAf4AA+qiq6or6gAf5An+AAPqpqivqABAn+QJ/gAD6qKrqivqAoIBQYwAA+qiq6or6gAIhVIiAAPqoquqK+oAD8QI/AAD9JElyRJElyRP0AQAA+SnKEpz5AAIhVIiAAH8SBIEgfwIAg/4AAAB/EgfwIP+AB/AEAQAAfxIH8CD/gAQBAH8AAH8SB/Ag/5/B8YB/AAB/EgfwIP+AA+EEPgAA/SRJEkT9hEET9AEAAP0kT9hE/R/B8YB/AAD6qKoqivuIoivqAoAA/SRJEkT9BEET9AEAAP0kT9BE/QBEAQB/AAB/EgSB/AA/4IAgCAAAfxIH8AD/ggfwBAEAAH8SB/AA/4IEgQB/AAB/Egfz/ggfwfGAfwAAfxIH8/4IHIP5FHIAAH8SB/AA/4IH8QR/AAB/EgfwAP+CA+EEPgAA+qiqK+oCvqIouiKAAP0kSRP0AT9BEEQRAAD9JE/QBP0ERQEAfwAA/SRP0/wQH8HxgH8AAP0kT9AE/QQH8QR/AAD9JE/QBP0UR/EEfwAA/SRP0AT9BAPhBD4AAH8SBIEgfwAAA/4AAAB/EgfwAP+AB/AEAQAAfxIH8AD/gAQBAH8AAH8SB/AA/4AH8QB/AAB/Egfz/gAfwfGAfwAAfxIH8AD/gAfxBH8AAH8SB/AA/5BH8QR/AAB/EgfwAP+AAIBQYwAA/SRJEkT9AEAT9AEAAP0kT9AE/QBEAQB/AAD9JE/QBP0fwfGAfwAA/SRP0AT9AAfxBH8AAP0kT9AE/RBH8QR/AAD9JEkSRJEkSRP0AQAA/SRJEkT9AEQBAH8AAP0kSRP0AB/B8YB/AAD9JEkSRP0AB/EEfwAA/SRJE/QAEEfxBH8AAP0kSRJE/QBAgFBjAAD9JEkSRP0AA+EEPgAA+QJAk+SBoEgT5AEAAPkCT5oE+QAH8AQBAAD5Ak+aBPkARAEAfwAA+QJPmgT5H8HxgH8AAPkCT5oE+QAH8QR/AAD5Ak+aBPkQR/EEfwAA+QJPmgT5AECAUGMAAPkCT5oE+QACIVSIgAD5Ak+aBPkAA+EEPgAA+QJPmgT5AAfwUGMAAPkCT5oE+QAH8Ih/AAD5Ak+aBPkCB/CIHAAA+oKgq+qDoKgr6gKAAPqCr7oK+oAH+AIAgAD6gq+6CvqApAEAf4AA+oKvugr6n+H5gH+AAPqCr7oK+oAH+QJ/gAD6gq+6CvqQJ/kCf4AA+oKvugr6gKCAUGMAAPqCr7oK+oACIVSIgAD6gq+6CvqAA/ECPwAA+QJAm+SBIGgT5AEAAPkCb5IG+QAH8AQBAAD5Am+SBvkARAEAfwAA+QJvkgb5AECAUGMAAPkCb5IG+QAD4QQ+AAD5AkCT5IcgSBPkAQAA+QJPsgT5AAfwBAEAAPkCT7IE+QBEAQB/AAD5Ak+yBPkfwfGAfwAA+QJPsgT5AAfxBH8AAPkCT7IE+RBH8QR/AAD5Ak+yBPkAQIBQYwAA+QJPsgT5AAIhVIiAAPkCT7IE+QAD4QQ+AAD5Ak+yBPkCB/CIHAAA8oShK8qOoKgrygKAAPKEr2oK8oAH+AIAgADyhK9qCvKApAEAf4AA8oSvagryn+H5gH+AAPKEr2oK8oAH+QJ/gADyhK9qCvKQJ/kCf4AA8oSvagrygKCAUGMAAPKEr2oK8oAD8QI/AAD5AkDz5IEhyBPkAQAA+QPPkhz5AAfwBAEAAPkDz5Ic+QBEAQB/AAD5A8+SHPkfwfGAfwAA+QPPkhz5AAfxBH8AAPkDz5Ic+RBH8QR/AAD5A8+SHPkAQIBQYwAA+QPPkhz5AAIhVIiAAPkDz5Ic+QAD4QQ+AADyhKHryoKjqCvKAoAA8oevKjrygKQBAH+AAPKHryo68pAn+QJ/gADyh68qOvKAoIBQYwAAfwBH8QB/AgCD/gAAAH8HxgH8CD/gAfwBAAB/B8YB/Ag/4AEAfwAAfwfGAfwIP+HxgH8AAH8HxgH8CD/n8QR/AAB/B8YB/Ag/5BH8fwAAfwfGAfwIP+CAUGMAAH8HxgH8CD/j4QQ+AAD5Ak+SBPmIQhP0AQAA+Q5MG+QhP0ABAH8AAPkOTBvkIT9D4QQ+AAD6jqw76iK+oiFUiIAA+QJPkgT5CEIT9AEAAPkOTBPkIT9AAQB/AAD5DkwT5CE/wfGAfwAA+Q5ME+QhP0fxBH8AAPkOTBPkIT9EEfx/AAD5DkwT5CE/QIBQYwAA+Q5ME+QhP0PhBD4AAH8AR/EAfwiCI/4AAAB/B8YB/CI/4AEAfwAAfwfGAfwiP+HxgH8AAH8HxgH8Ij/kEfx/AAB/B8YB/CI/4IBQYwAAfwfGAfwiP+PhBD4AAH8AR/EAfwAP+CAIAAB/B8YB/AA/4IH8AQAAfwfGAfwAP+CBAH8AAH8HxgP+CB/B8YB/AAB/B8YB/P+CB/EEfwAAfwfGAfz/kkfxBH8AAH8HxgH8/4IAgFBjAAB/B8YB/P+CA+EEPgAA+Q5ME+QBP0IQnCEAAPkOTBP0JwhCIVSIgAD6jqwr6gK+oii6IoAA+Q5ME+QBP0IQhCEAAPkOTBPkAT9CAfwBAAD5DkwT5AE/QhEAfwAAeQZGE/QgH8HxgH8AAHkGRhHk/QgH8QR/AAB5BkYR5P0IQoBQYwAAeQZGEeT9CAPhBD4AAH8AR/EAfwAP+IgiAAB/B8YB/AA/4iH8AQAAfwfGAfwAP+EhAH8AAH8HxgP+Ih/B8YB/AAB/B8YB/P+Ih/EEfwAAfwfGAfz/iIQR/H8AAH8HxgH8/4iAgFBjAAB/B8YB/P+Ig+EEPgAAfwBH8QB/AAAD/gAAAH8HxgH8AD/gAfwBAAB/B8YB/AA/4AEAfwAAfwfGA/4AH8HxgH8AAH8HxgH8/4AH8QR/AAB/B8YB/P+QR/EEfwAAfwfGAfwAP+CAUGMAAH8HxgH8/4AD4QQ+AAB/B8YB/P+AB/BQYwAAfwfGA/4AH8fhAH8AAH8HxgH8/4AH8Ih/AAD5AkCT5IEgSBPkAQAA+QJPkgT5AAfwBAEAAPkCT5IE+QBEAQB/AAD5Ak+SBPkfwfGAfwAA+QJPkgT5AAfxBH8AAPkCT5IE+RBH8QR/AAD5Ak+SBPkAQIBQYwAA+QJPkgT5AAPhBD4AAPkiSJIkiaJIk+QBAAD5IkiaJPkAB/AEAQAA+SJImiT5AEQBAH8AAPkiSJok+QCE+RRyAAD5IkiaJPkAB/EAfwAA+SJok+QAH8HxgH8AAPkiaJPkAB3DEQRxAAD5ImiT5AAdw1EUdwAA+SJImiT5AAfxBH8AAPkiaJPkABBH8QR/AAD5IkiaJPkAQIBQYwAA+SJImiT5AAPhBD4AAPkiSJok+QAH8FBjAAD5ImiT5AAfx+EAfwAA+SJImiT5AgfwiBwAAPqiqKoqi6Koq+oCgAD6oqi6KvqAB/gCAIAA+qKouir6gKQBAH+AAPqi6KvqAB/h+YB/gAD6oqi6KvqAB/kCf4AA+qKouir6kCf5An+AAPqiqLoq+oCggFBjAAD6oqi6KvqAAiFUiIAA+qKouir6gAPxAj8AAPqiqLoq+oAH+EhhgAD5IkiaJIkiaJPkAQAA+SJokib5AAfwBAEAAPkiaJPmAR/B8YB/AAD5ImiSJvkAA+EEPgAA+SJIkjyJIkiT5AEAAPkiSPIk+QAH8AQBAAD5IkjyJPkARAEAfwAA+SPIk+QAH8HxgH8AAPkjyJPkAB3DURR3AAD5IkjyJPkAB/EEfwAA+SPIk+QAEEfxBH8AAPkiSPIk+QBAgFBjAAD5IkjyJPkAA+EEPgAA+SJI8iT5AAfwUGMAAPkiSPIk+QIH8IgcAAD6oqiqOoqiqKvqAoAA+qKo6ir6gAf4AgCAAPqiqOoq+oCkAQB/gAD6o6ir6gAf4fmAf4AA+qKo6ir6gAf5An+AAPqjqKvqABAn+QJ/gAD6oqjqKvqAoIBQYwAA+qKo6ir6gAIhVIiAAPqiqOoq+oAD8QI/AAD5IkjyJIkjyJPkAQAA+SPIkjz5AAfwBAEAAPkjyJI8+QBEAQB/AAD5I8iT/AEfwfGAfwAA+SPIkjz5AECAUGMAAPkjyJI8+QACIVSIgAD5I8iSPPkAA+EEPgAA+SPIkjz5AgfwUGMAAPqiqOoqiqOoq+oCgAB/EEQRBH8CAIP+AAAAfxBH8CD/gAfwBAEAAH8QR/Ag/4AHIFQYgAB/EEfwIP+ABAEAfwAAfxBH8CD/n8HxgH8AAH8QR/Ag/53DURR3AAB/EEfwIP+AB/EEfwAAfxBH8CD/kEfxBH8AAH8QR/Ag/4AAgFBjAAB/EEfwIP+AA+EEPgAA+SJIkiT5iEIT9AEAAPkiT5iE/QBEAQB/AAD5Ik+YhP0AAiFUiIAA+SJPmIT9AAPhBD4AAPkiSJIk+QhCE/QBAAD5Ik+QhP0ARAEAfwAA+SJPkIT9H8HxgH8AAPkiT5CE/RBH8QR/AAD5Ik+QhP0AQIBQYwAA+SJPkIT9AAPhBD4AAH8QRBEEfwiCI/4AAAB/EEfwiP+ABAEAfwAAfxBH8Ij/n8HxgH8AAH8QR/CI/5BH8QR/AAB/EEfwiP+AAIBQYwAAfxBEEfwAP+CAIAgAAH8QR/AA/4IH8AQBAAB/EEfwAP+CB/AkCQAAfxBH8AD/ggSBAH8AAH8QR/AA/4IH8QB/AAB/EEfz/ggfwfGAfwAAfxBH8/4IHcMRBHEAAH8QR/P+CB3DURR3AAB/EEfwAP+CB/EEfwAAfxBH8AD/kkfxBH8AAH8QR/AA/4IAgFBjAAB/EEfwAP+CA+EEPgAAfxBH8/4IH8fhAH8AAH8QR/P+CAIH8IgcAAD5IkiT5AE/QhCcIQAA+SJPkAT9CcYRAH8AAHkSR5P0Ix/B8YB/AAB5EkeT9CcQR/EEfwAAeRJHk/QnCECAUGMAAPqiqKvqAr6iKLoigAD5IkiT5AE/QhCEIQAA+SJPkAT9CEYBAH8AAHkSR5P0IB/B8YB/AAB/EEQR/AA/4iCIIgAAfxBH8AD/hIUhAH8AAH8QR/P+Ih/B8YB/AAB/EEfwAP+Ih/EEfwAAfxBH8AD/iICAUGMAAH8QRBEEfwAAA/4AAAB/EEfwAP+ABAEAfwAAfxBH8/4AH8HxgH8AAH8QR/AA/4AH8QR/AAB/EEfwAP+AAIBQYwAA+SJIkiSJIkiT5AEAAPkiSJIk+QAH8AQBAAD5IkiSJPkARAEAfwAA+SJIkiT5AAfxAH8AAPkiSJPkAB/B8YB/AAD5IkiT5AAdw1EUdwAA+SJIkiT5AAfxBH8AAPkiSJPkABBH8QR/AAD5IkiSJPkAQIBQYwAA+SJIkiT5AAIhVIiAAPkiSJIk+QAD4QQ+AAD5IkiSJPkCB/BQYwAA+SJIk+QAH8fhAH8AAIkiSJPkiaJIk+QBAACJPkiaJPkAB/AEAQAAiT5ImiT5AAfwJAkAAIk+SJok+QAHIFQYgACJPkiaJPkARAEAfwAAiT5ImiT5AAfxAH8AAIk+aJPkAB/B8YB/AACJPmiT5AAdwxEEcQAAiT5ok+QAHcNRFHcAAIk+aJPkAB1DcRR3AACJPkiaJPkAB/EEfwAAiT5ok+QAEEfxBH8AAIk+SJok+QBAgFBjAACJPkiaJPkAA+EEPgAAiT5ok+QAH8fhAH8AAIqiqKvqi6Koq+oCgACKvqi6KvqAB/gCAIAAir6ouir6gKQBAH+AAIq+6KvqAB/h+YB/gACKvqi6KvqAB/kCf4AAir7oq+oAECf5An+AAIq+qLoq+oCggFBjAACKvqi6KvqAAiFUiIAAir6ouir6gAPxAj8AAIq+6KvqAB/n8QB/gACJIkib5IkiaJPkAQAAiT5okib5AAfwBAEAAIk+aJIm+QBEAQB/AACJPmiT5gEQR/EEfwAAiSJIk/yJIkiT5AEAAIk+SPIk+QAH8AQBAACJPkjyJPkARAEAfwAAiT5I8iT5AAfxAH8AAIk/yJPkAB/B8YB/AACJP8iT5AAdw1EUdwAAiT5I8iT5AAfxBH8AAIk/yJPkABBH8QR/AACJPkjyJPkAQIBQYwAAiT5I8iT5AAPhBD4AAIk+SPIk+QAH8FBjAACKoqir+oqiqKvqAoAAir6o6ir6gAf4AgCAAIq+qOoq+oCkAQB/gACKvqjqKvqAB/kAf4AAir+oq+oAH+H5gH+AAIq+qOoq+oAH+QJ/gACKv6ir6gAQJ/kCf4AAir6o6ir6gKCAUGMAAIq+qOoq+oACIVSIgACKvqjqKvqAA/ECPwAAiSJI8+SJI8iT5AEAAIk/yJI8+QAH8AQBAACJP8iSPPkARAEAfwAAiT/Ik/wBH8HxgH8AAIk/yJI8+RBH8QR/AACJP8iSPPkAQIBQYwAAiT/Ikjz5AAIhVIiAAIk/yJI8+QAD4QQ+AACJP8iT/AEfx+EAfwAAiqKo6+qKo6ir6gKAAIq/qKo6+oCkAQB/gABBH8QRBH8CAIP+AAAAQR/EEfwIP+AB/AEAAEEfxBH8CD/gAfwJAABBH8QR/Ag/4AEAfwAAQR/EEfwIP+HxgH8AAEEfxBH8CD/n8QR/AABBH8QR/Ag/5BH8fwAAQR/EEfwIP+CAUGMAAEEfxBH8CD/j4QQ+AACJPkiSJPmIQhP0AQAAiT5Im+QhP0ABAH8AAIk+SJvkIT9CIVSIgACKvqiqKvuIoivqAoAAir6ou+oivqIhVIiAAIk+SJIk+QhCE/QBAACJPkiT5CE/QAH8AQAAiT5Ik+QhP0ABAH8AAIk+SJPkIT/B8YB/AACJPkiT5CE/R/EEfwAAiT5Ik+QhP0QR/H8AAEEfxBEEfwiCI/4AAABBH8QR/CI/4AEAfwAAQR/EEfwAP+CAIAgAAEEfxBH8AD/ggfwBAABBH8QR/AA/4IEAfwAAQR/EEfz/ggfxAH8AAEEfxBP+CB/B8YB/AABBH8QT/ggdwxEEcQAAQR/EE/4IHcNRFHcAAEEfxBH8/4IH8QR/AABBH8QR/P+SR/EEfwAAQR/EEfz/ggCAUGMAAEEfxBH8/4ID4QQ+AABBH8QT/ggfx+EAfwAAQR/EEfz/ggfwiH8AAIk+SJPkAT9CEJwhAABJHkST9CMfwfGAfwAASR5Ek/QnCEIhVIiAAIq+qKvqAr6iKLoigACJPkiT5AE/QhCEIQAASR5EkeT9CAfwBAEAAEkeRJHk/QhGAQB/AABJHkST9CAfwfGAfwAASR5EkeT9CAPhBD4AAEEfxBH8AD/iIIgiAABBH8QR/AA/4SEAfwAAQR/EE/4iH8HxgH8AAEEfxBH8/4iH8QR/AABBH8QR/P+IgIBQYwAAQR/EEfz/iIPhBD4AAEEfxBEEfwAAA/4AAABBH8QR/AA/4AH8AQAAQR/EEfwAP+ABAH8AAEEfxBP+AB/B8YB/AABBH8QR/P+AB/EEfwAAQR/EEfz/kEfxBH8AAEEfxBH8AD/ggFBjAACJIkiT5IkiSJPkAQAAiT5IkiT5AAfwBAEAAIk+SJIk+QBEAQB/AACJPkiT5AAfwfGAfwAAiT5Ik+QAHcNRFHcAAIk+SJIk+QAH8QR/AACJPkiT5AAQR/EEfwAAiT5IkiT5AECAUGMAAIk+SJIk+QAD4QQ+AACJPkiSJPkAB/BQYwAAiT5IkiT5AgfwUGMAAKkqSpPkqapKk+QBAACpPkqapPkAB/AEAQAAqT5KmqT5AEQBAH8AAKk+apPkAB/B8YB/AACpPmqT5AAdw1EUdwAAqT5KmqT5AAfxBH8AAKk+apPkABBH8QR/AACpPkqapPkAQIBQYwAAqT5KmqT5AAIhVIiAAKk+Spqk+QAD4QQ+AACpPkqapPkCB/CIHAAAqqqqq+qrqqqr6gKAAKq+qrqq+oAH+AIAgACqvqq6qvqApAEAf4AAqr7qq+oAH+H5gH+AAKq+qrqq+oAH+QJ/gACqvuqr6gAQJ/kCf4AAqr6quqr6gKCAUGMAAKq+qrqq+oACIVSIgACqvqq6qvqAA/ECPwAAqSpKm+SpKmqT5AEAAKk+apKm+QAH8AQBAACpPmqSpvkAB/EEfwAAqSpKk/ypKkqT5AEAAKk+SvKk+QAH8AQBAACpPkrypPkARAEAfwAAqT5K8qT5AAfxAH8AAKk/ypPkAB/B8YB/AACpPkrypPkAB/EEfwAAqT5K8qT5AECAUGMAAKk+SvKk+QACIVSIgACpPkrypPkAA+EEPgAAqqqqq/qqqqqr6gKAAKq+quqq+oAD8QI/AACpKkrz5KkrypPkAQAAqT/Kkrz5AAfwBAEAAKk/ypK8+QAH8QR/AACpP8qSvPkQR/EEfwAAqT/Kkrz5AECAUGMAAKk/ypK8+QACIVSIgACpP8qSvPkAA+EEPgAAVR3FUVR3AgCD/gAAAFUdxVHcCD/gAfwBAABVHcVR3Ag/4AEAfwAAVR3HcCD/n8HxgH8AAFUdx3Ag/4AH8QR/AABVHcdwIP+QR/EEfwAAVR3HcCD/gAPhBD4AAKk+SpKk+QhCE/QBAABVHcVRVHcIgiP+AAAAVR3HcIj/gAPhBD4AAFUdxVHcAD/ggCAIAABVHcVR3AA/4IH8AQAAVR3FUdwAP+CBAH8AAFUdxVP+CB/B8YB/AABVHcdwAP+CB/EEfwAAVR3HcAD/ggCAUGMAAFUdx3AA/4ID4QQ+AABVHcVR3AA/4iCIIgAAVR3HcAD/iIPhBD4AAFUdxVFUdwAAA/4AAABVHcVR3AA/4AEAfwAAVR3FU/4AH8HxgH8AAFUdx3AA/4AH8QR/AABVHcdwAP+QR/EEfwAAqSpKk+SpKkqT5AEAAKk+SpKk+QAH8AQBAACpPkqSpPkARAEAfwAAqT5Kk+QAH8HxgH8AAKk+SpKk+QAH8QR/AACpPkqT5AAQR/EEfwAAqT5KkqT5AECAUGMAAKk+SpKk+QAD4QQ+AAAhCEIQhFGUSJIkAQAAIQhCGUSJAAfwBAEAACEIQhlEiQAHIFQYgAAhCEIZRIkARAEAfwAAIQhCGUSJAAfxAH8AACEIZRIkAB/B8YB/AAAhCGUSJAAdwxEEcQAAIQhlEiQAHcNRFHcAACEIQhlEiQAH8QR/AAAhCGUSJAAQR/EEfwAAIQhCGUSJAECAUGMAACEIQhlEiQACIVSIgAAhCEIZRIkAA+EEPgAAIQhlEiQAH8fhAH8AACKIoiiKU5SoqioCgAAiiKI5SoqAB/gCAIAAIoiiOUqKgKQBAH+AACKI5SoqAB/h+YB/gAAiiKI5SoqAB/kCf4AAIojlKioAECf5An+AACKIojlKioCggFBjAAAiiKI5SoqAAiFUiIAAIoiiOUqKgAPxAj8AACEIQhiEURRokiQBAAAhCGIRRokAB/AEAQAAIQhiEUaJAEQBAH8AACEIZRImAR/B8YB/AAAhCGIRRokAB/EEfwAAIQhlEiYBEEfxBH8AACEIYhFGiQBAgFBjAAAhCGIRRokAA+EEPgAAIoiiOIpSlOiqKgKAACKI4ilOioCkAQB/gAAiiOUqLgKf4fmAf4AAIojiKU6KgAf5An+AACKI4ilOioAD8QI/AAAhCEIQnFEUSJIkAQAAIQhCcUSJAAfwBAEAACEIQnFEiQAH8CQJAAAhCEJxRIkAByBUGIAAIQhCcUSJAEQBAH8AACEIQnFEiQAH8QB/AAAhCcUSJAAfwfGAfwAAIQnFEiQAHcNRFHcAACEJxRIkAB1DcRR3AAAhCEJxRIkAB/EEfwAAIQnFEiQAEEfxBH8AACEIQnFEiQBAgFBjAAAhCEJxRIkAAiFUiIAAIQhCcUSJAAPhBD4AACEIQnFEiQAH8Ih/AAAiiKIoulKUqKoqAoAAIoii6UqKgAf4AgCAACKIoulKioCkAQB/gAAii6UqKgAf4fmAf4AAIoii6UqKgAf5An+AACKLpSoqABAn+QJ/gAAiiKLpSoqAoIBQYwAAIoii6UqKgAIhVIiAACKIoulKioAD8QI/AAAhCEJwhFEVyJIkAQAAIQnCEVyJAAfwBAEAACEJwhFciQBEAQB/AAAhCcIRXIkfwfGAfwAAIQnCEVyJAAfxBH8AACEJwhFciRBH8QR/AAAhCcIRXIkAQIBQYwAAIQnCEVyJAAIhVIiAACEJwhFciQAD4QQ+AAAiiKJoilKVqKoqAoAAIomiKVqKgKQBAH+AACKJoilaip/h+YB/gAAiiaIpWoqAA/ECPwAACAIBQIhBAgCD/gAAAAgFBjAg/4AH8AQBAAAIBQYwIP+AB/AkCQAACAUGMCD/gAQBAH8AAAgFBjAg/5/B8YB/AAAIBQYwIP+dw1EUdwAACAUGMCD/gAfxBH8AAAgFBjAg/5BH8QR/AAAIBQYwIP+AAIBQYwAACAUGMCD/gAPhBD4AAAgFBjAg/5/H4QB/AAAhCEIRRImIQhP0AQAAIRRImIT9AAfwBAEAACEUSJiE/QBEAQB/AAAhFEiYhP0fwfGAfwAAIRRImIT9AAPhBD4AACKIoilKi4iiK+oCgAAilKi4ivqApAEAf4AAIpSouIr6n+H5gH+AACKUqLiK+oAH+QJ/gAAilKi4ivqAoIBQYwAAIpSouIr6gAIhVIiAACEIQhFEiQhCE/QBAAAhFEiQhP0ARAEAfwAAIRRIkIT9H8HxgH8AACEUSJCE/QAH8QR/AAAhFEiQhP0QR/EEfwAAIRRIkIT9AECAUGMAAAgCAUCIQQiCI/4AAAAIBQYwiP+AB/AEAQAACAUGMIj/gAQBAH8AAAgFBjCI/5/B8YB/AAAIBQYwiP+AB/EEfwAACAUGMIj/kEfxBH8AAAgFBjCI/4AAgFBjAAAIBQYwiP+AA+EEPgAACAUCIQQAP+CAIAgAAAgFBjAA/4IH8AQBAAAIBQYwAP+CBIEAfwAACAUGMAD/ggfxAH8AAAgFBjP+CB/B8YB/AAAIBQYwAP+CB/EEfwAACAUGMAD/kkfxBH8AAAgFBjAA/4IAgFBjAAAIBQYwAP+CA+EEPgAACAUGM/4IAgfwUGMAAAgFBjP+CB/H4QB/AAAIBQYwAP+CB/CIfwAAIQhFEiQBP0IQnCEAACEUSJP0JwhCIVSIgAAiiKUqKgK+oii6IoAAIpSoq+ouiKf4AgCAACKUqKvqLoikAQB/gAAilKir6iaf4fmAf4AAIpSoq+ouiKf5An+AACKUqKvqLoij8QI/AAAhCEUSJAE/QhCEIQAAIRRIkAT9CAfwBAEAACEUSJAE/QhGAQB/AAAhFEiT9CAfwfGAfwAAIRRIkAT9CAfxBH8AACEUSJP0IBBH8QR/AAAhFEiQBP0IQoBQYwAAIRRIkAT9CAPhBD4AAAgFAiEEAD/iIIgiAAAIBQYwAP+Ih/AEAQAACAUGM/4iH8HxgH8AAAgFBjAA/4iH8QR/AAAIBQYwAP+IgIBQYwAACAUGMAD/iIPhBD4AAAgCAUCIQQAAA/4AAAAIBQYwAP+AB/AEAQAACAUGMAD/gAQBAH8AAAgFBjP+AB/B8YB/AAAIBQYz/gAdwxEEcQAACAUGMAD/gAfxBH8AAAgFBjAA/5BH8QR/AAAIBQYwAP+AAIBQYwAACAUGMAD/gAPhBD4AACEIQhCEURRIkiQBAAAhCEIRRIkAB/AEAQAAIQhCEUSJAEQBAH8AACEIQhFEiQAH8QB/AAAhCEUSJAAfwfGAfwAAIQhFEiQAHIP5FHIAACEIQhFEiQAH8QR/AAAhCEUSJAAQR/EEfwAAIQhCEUSJAECAUGMAACEIQhFEiQAD4QQ+AAAhCEIRRIkAB/CIfwAAURRFEUSpqkqSpAEAAFEURRqkqQAH8AQBAABRFEUapKkAByBUGIAAURRFGqSpAEQBAH8AAFEUapKkAB/B8YB/AABRFEUapKkAB/EEfwAAURRqkqQAEEfxBH8AAFEURRqkqQACIVSIgABRFEUapKkAA+EEPgAAURRKmqQBAgfwiBwAAFKUpSlKq6qqqqoCgABSlKU6qqqAB/gCAIAAUpSlOqqqgKQBAH+AAFKU6qqqAB/h+YB/gABSlKU6qqqAB/kCf4AAUpTqqqoAECf5An+AAFKUpTqqqoACIVSIgABSlKU6qqqAA/ECPwAAURRlEqapAAPhBD4AAFEURRFcqSpKkqQBAABRFEVypKkAB/AEAQAAURRFcqSpAEQBAH8AAFEVypKkAB/B8YB/AABRFcqSpAAdw1EUdwAAURRFcqSpAAfxBH8AAFEVypKkABBH8QR/AABRFEVypKkAAiFUiIAAURRFcqSpAAPhBD4AAFKUpSlaqqqqqqoCgABSlKVqqqqApAEAf4AAUpWqqqoAH+H5gH+AAFKVpSq6qoCkAQB/gAAiCIVSIgACAIP+AAAAIhVICCD/gAfwBAEAACIVSAgg/4AEAQB/AAAiFUgIIP+AB/EAfwAAIhVICCD/n8HxgH8AACIVSAgg/53DURR3AAAiFUgIIP+AB/EEfwAAIhVICCD/kEfxBH8AACIVSAgg/4AD4QQ+AABRFEUSpKmAQhP0AQAAURRKmiQhP0AB/AEAAFEUSpokIT9AAQB/AABRFEqYhP0AAiFUiIAAUpSlKqqrgKIr6gKAAFKUqriK+oACIVSIgABRFEUSpKkAQhP0AQAAURRKkiQhP0ABAH8AAFEUSpCE/R/B8YB/AABRFEqQhP0AB/EEfwAAURRKkIT9EEfxBH8AACIIhVIiAAiCI/4AAAAiCIVSIgA/4IAgCAAAIhVIiAD/ggfwBAEAACIVSIgA/4IEgQB/AAAiFUiL/ggfwfGAfwAAIhVIiAD/ggfxBH8AACIVSIgA/5JH8QR/AAAiFUiIAP+CA+EEPgAAURRKkqQBP0IQnCEAAFEUSpP0JwhCIVSIgABSlKqqqgK+oii6IoAAURRKkqQBP0IQhCEAAFEUSpAE/QhGAQB/AAAiFUiIAP+Ig+EEPgAAIgiFUiIAAAAD/gAAACIVSIgA/4AH8AQBAAAiFUiIAP+ABAEAfwAAIhVIi/4AH8HxgH8AACIVSIv+AB3DURR3AAAiFUiL/gAcg/kUcgAAIhVIiAD/gAfxBH8AACIVSIgA/5BH8QR/AABRFEUSpKkAQBP0AQAAURRKkAT9AEQBAH8AAFEUSpAE/R/B8YB/AABRFEqQBP0AB/EEfwAAURRFEUSpKkqSpAEAAFEURRKkqQAH8AQBAABRFEUSpKkARAEAfwAAURRKkqQAH8HxgH8AAFEURRKkqQAH8QR/AABRFEqSpAAQR/EEfwAAURRFEqSpAECAUGMAAFEURRKkqQAD4QQ+AABxIkiSJImiSJHEAQAAcSJImiRxAAfwBAEAAHEiSJokcQBEAQB/AABxIkiaJHEABPkUeIAAcSJImiRxAIT5FHIAAHEiaJHEAB/B8YB/AABxImiRxAAdwxEEcQAAcSJokcQAHcNRFHcAAHEiaJHEAByD+RRyAABxIkiaJHEAB/EEfwAAcSJokcQAEEfxBH8AAHEiSJokcQBAgFBjAABxIkiaJHEAAiFUiIAAcSJImiRxAAPhBD4AAHEiaJHEAB/H4QB/AABxIkiaJHEAB/CIfwAAcqKoqiqLoqipygKAAHKiqLoqcoAH+AIAgAByoqi6KnKApAEAf4AAcqLoqcoAH+H5gH+AAHKiqLoqcoAH+QJ/gAByouipygAQJ/kCf4AAcqKouipygKCAUGMAAHKiqLoqcoACIVSIgAByoqi6KnKAA/ECPwAAcSJImiSJImiRxAEAAHEiaJImcQAH8AQBAABxImiSJnEARAEAfwAAcSJokcYBH8HxgH8AAHEiaJHGAR1DcRR3AABxImiSJnEAB/EEfwAAcSJokcYBEEfxBH8AAHEiaJImcQBAgFBjAABxImiSJnEAA+EEPgAAcSJokcYBH8fhAH8AAHEiaJImcQIH8IgcAAByoqi6Koqi6KnKAoAAcqLoqi5ygKQBAH+AAHKi6KnOAp/h+YB/gAByouipzgKQJ/kCf4AAcSJIkjyJIkiRxAEAAHEiSPIkcQAH8AQBAABxIkjyJHEARAEAfwAAcSJI8iRxAAT5FHiAAHEiSPIkcQAH8QB/AABxI8iRxAAfwfGAfwAAcSPIkcQAHcMRBHEAAHEjyJHEAB3DURR3AABxIkjyJHEAB/EEfwAAcSPIkcQAEEfxBH8AAHEjyJHEABSHIVR4gABxIkjyJHEAQIBQYwAAcSJI8iRxAAIhVIiAAHEiSPIkcQAD4QQ+AABxIkjyJHEAB/BQYwAAcSPIkcQAH8AR/AEAAHEiSPIkcQAH8Ih/AAByoqiqOoqiqKnKAoAAcqKo6ipygAf4AgCAAHKiqOoqcoCkAQB/gAByo6ipygAf4fmAf4AAcqKo6ipygAf5An+AAHKjqKnKABAn+QJ/gAByoqjqKnKAoIBQYwAAcqKo6ipygAPxAj8AAHEiSPIkiSPIkcQBAABxI8iSPHEAB/AEAQAAcSPIkjxxAAfwJAkAAHEjyJI8cQBEAQB/AABxI8iR3AEfwfGAfwAAcSPIkdwBHcNRFHcAAHEjyJHcAR1DcRR3AABxI8iSPHEAB/EEfwAAcSPIkjxxEEfxBH8AAHEjyJI8cRSHIVR4gABxI8iSPHEAQIBQYwAAcSPIkjxxAAIhVIiAAHEjyJI8cQAD4QQ+AABxI8iR3AEfx+EAfwAAcSPIkjxxAAfwiH8AAHEjyJI8cQIH8IgcAAByoqjqKoqjqKnKAoAAcqOoqjpygKQBAH+AAHKjqKnaAp/h+YB/gAByo6iqOnKAB/kCf4AAcqOoqjpykCf5An+AAHKjqKo6coCggFBjAAByo6iqOnKAAiFUiIAAPhBEEQQ+AgCD/gAAAD4QQ+Ag/4AH8AQBAAA+EEPgIP+ABAEAfwAAPhBD4CD/n8HxgH8AAD4QQ+Ag/53DEQRxAAA+EEPgIP+dw1EUdwAAPhBD4CD/nAMhFHiAAD4QQ+Ag/5yD+RRyAAA+EEPgIP+AB/EEfwAAPhBD4CD/kEfxBH8AAD4QQ+Ag/4AAgFBjAAA+EEPgIP+AA+EEPgAAPhBD4CD/ggfwUGMAAHEiSJIkcYhCE/QBAABxIkcYhP0AB/AEAQAAcSJHGIT9AEQBAH8AAHEiRxiE/R/B8YB/AABxIkcYhP0AB/EEfwAAcSJHGIT9EEfxBH8AAHEiRxiE/QBAgFBjAABxIkcYhP0AAiFUiIAAcSJHGIT9AAPhBD4AAHKiqKoqc4iiK+oCgAByoqc4ivqAB/gCAIAAcqKnOIr6gKQBAH+AAHKipziK+oAH+QJ/gAByoqc4ivqAoIBQYwAAcqKnOIr6gAPxAj8AAHEiSJIkcQhCE/QBAABxIkcQhP0AB/AEAQAAcSJHEIT9AEQBAH8AAHEiRxCE/R/B8YB/AABxIkcQhP0AB/EEfwAAcSJHEIT9EEfxBH8AAHEiRxCE/QBAgFBjAABxIkcQhP0AA+EEPgAAPhBEEQQ+CIIj/gAAAD4QQ+CI/4AH8AQBAAA+EEPgiP+ABAEAfwAAPhBD4Ij/n8HxgH8AAD4QQ+CI/4AH8QR/AAA+EEPgiP+QR/EEfwAAPhBD4Ij/gACAUGMAAD4QQ+CI/4AD4QQ+AAA+EEQQ+AA/4IAgCAAAPhBD4AD/ggfwBAEAAD4QQ+AA/4IEgQB/AAA+EEPj/ggfwfGAfwAAPhBD4/4IHcMRBHEAAD4QQ+P+CB3DURR3AAA+EEPgAP+CB/EEfwAAPhBD4AD/kkfxBH8AAD4QQ+AA/4IAgFBjAAA+EEPgAP+CA+EEPgAAcSJIkcQBP0IQnCEAAHEiRxP0JwhH8AQBAABxIkcT9CcIRAEAfwAAcSJHE/QjH8HxgH8AAHEiRxP0JwhH8QR/AABxIkcT9CcQR/EEfwAAcSJHE/QnCEIhVIiAAHEiRxP0JwhD4QQ+AAByoqipygK+oii6IoAAcqKnK+ouiKf4AgCAAHKipygK+oumKQB/gAByoqcr6iaf4fmAf4AAcqKnK+ouiKf5An+AAHKipyvqLpCn+QJ/gAByoqcr6i6Io/ECPwAAcSJIkcQBP0IQhCEAAHEiRxAE/QgH8AQBAABxIkcQBP0IRgEAfwAAcSJHE/QgH8HxgH8AAHEiRxAE/QgH8QR/AABxIkcT9CAQR/EEfwAAcSJHEAT9CEKAUGMAAHEiRxAE/QgD4QQ+AAA+EEQQ+AA/4iCIIgAAPhBD4AD/iIfwBAEAAD4QQ+AA/4SFIQB/AAA+EEPj/iIfwfGAfwAAPhBD4AD/iIfxBH8AAD4QQ+P+IhBH8QR/AAA+EEPgAP+IgIBQYwAAPhBD4AD/iIPhBD4AAD4QQ+P+IgIH8HBjAAA+EEQRBD4AAAP+AAAAPhBD4AD/gAfwBAEAAD4QQ+AA/4AEAQB/AAA+EEPj/gAfwfGAfwAAPhBD4/4AH+NRFH+AAD4QQ+AA/4AH8QR/AAA+EEPgAP+QR/EEfwAAPhBD4AD/gACAUGMAAD4QQ+AA/4AD4QQ+AAA+EEPgAP+AB/BQYwAAPhBD4AD/ggfwUGMAAD4QQ+P+AB/AEfwBAAA+EEPj/gAfx+EAfwAAPhBD4AD/gAfwiH8AAD4QQ+P+AAIH8IgcAABxIkiSJHEAQBP0AQAAcSJHEAT9AEQBAH8AAHEiRxP0AB/B8YB/AABxIkcQBP0AB/EEfwAAcSJHEAT9AECAUGMAAHEiSJIkiSJIkcQBAABxIkiSJHEAB/AEAQAAcSJIkiRxAEQBAH8AAHEiSJHEAB/B8YB/AABxIkiRxAAdwxEEcQAAcSJIkcQAHcNRFHcAAHEiSJHEAByD+RRyAABxIkiSJHEAB/EEfwAAcSJIkcQAEEfxBH8AAHEiSJIkcQBAgFBjAABxIkiSJHEAAiFUiIAAcSJIkiRxAAPhBD4AAHEiSJIkcQAH8FBjAABxIkiSJHEAB/CIfwAA+QhCEIRRlEiSJAEAAPkIQhlEiQAH8AQBAAD5CEIZRIkARAEAfwAA+QhCGUSJAIT5FHIAAPkIQhlEiQAH8QB/AAD5CGUSJAAfwfGAfwAA+QhlEiQAHcNRFHcAAPkIQhlEiQAH8QR/AAD5CGUSJAAQR/EEfwAA+QhCGUSJAECAUGMAAPkIQhlEiQACIVSIgAD5CEIZRIkAA+EEPgAA+QhCGUSJAAfwUGMAAPqIoiiKU5SoqioCgAD6iKI5SoqAB/gCAIAA+oiiOUqKgKQBAH+AAPqI5SoqAB/h+YB/gAD6iKI5SoqAB/kCf4AA+ojlKioAECf5An+AAPqIojlKioCggFBjAAD6iKI5SoqAAiFUiIAA+oiiOUqKgAPxAj8AAPkIQhiEURRokiQBAAD5CGIRRokAB/AEAQAA+QhiEUaJAEQBAH8AAPkIYhFGiQCE+RRyAAD5CGUSJgEfwfGAfwAA+QhiEUaJAAfxBH8AAPkIYhFGiQAD4QQ+AAD6iKI4ilKU6KoqAoAA+ojiKU6KgKQBAH+AAPqI5SouAp/h+YB/gAD5CEIQnFEUSJIkAQAA+QhCcUSJAAfwBAEAAPkIQnFEiQBEAQB/AAD5CcUSJAAfwfGAfwAA+QnFEiQAHcNRFHcAAPkIQnFEiQAH8QR/AAD5CcUSJAAQR/EEfwAA+QhCcUSJAECAUGMAAPkIQnFEiQAD4QQ+AAD5CEJxRIkAB/BQYwAA+oiiKLpSlKiqKgKAAPqIomlKioAH+AIAgAD6iKJpSoqApAEAf4AA+omlKioAH+H5gH+AAPqIomlKioAH+QJ/gAD6iaUqKgAQJ/kCf4AA+oiiaUqKgKCAUGMAAPqIomlKioAD8QI/AAD5CEJwhFEVyJIkAQAA+QnCEVyJAEQBAH8AAPkJwhFciR/B8YB/AAD5CcIRXIkAB/EEfwAA+QnCEVyJEEfxBH8AAPkJwhFciQACIVSIgAD5CcIRXIkAA+EEPgAA+oiiaIpSlaiqKgKAAH8CAUCIQQIAg/4AAAB/BQYwIP+AB/AEAQAAfwUGMCD/gAQBAH8AAH8FBjAg/5/B8YB/AAB/BQYwIP+dw1EUdwAAfwUGMCD/gAfxBH8AAH8FBjAg/5BH8QR/AAB/BQYwIP+AAIBQYwAAfwUGMCD/gAPhBD4AAH8FBjAg/4AH8FBjAAB/BQYwIP+CB/BQYwAAfwUGMCD/ggfwiBwAAPkIQhFEiYhCE/QBAAD5FEiYhP0AB/AEAQAA+RRImIT9H8HxgH8AAPkUSJiE/RBH8QR/AAD5FEiYhP0AQIBQYwAA+RRImIT9AAPhBD4AAPqIoilKi4iiK/oCgAD6lKi4ivqAAiFUiIAA+pSouIr6gAPxAj8AAPkIQhFEiQhCE/QBAAD5FEiQhP0ARAEAfwAA+RRIkIT9H8HxgH8AAPkUSJCE/QAH8QR/AAD5FEiQhP0QR/EEfwAA+RRIkIT9AECAUGMAAPkUSJCE/QAD4QQ+AAB/AgFAiEEIgiP+AAAAfwUGMIj/gAfwBAEAAH8FBjCI/4AEAQB/AAB/BQYwiP+AA+EEPgAAfwIBQYwAP+CAIAgAAH8FBjAA/4IH8AQBAAB/BQYwAP+CBIEAfwAAfwUGM/4IH8HxgH8AAH8FBjP+CB3DEQRxAAB/BQYz/ggdw1EUdwAAfwUGMAD/ggfxBH8AAH8FBjAA/5JH8QR/AAB/BQYwAP+CAIBQYwAAfwUGMAD/ggPhBD4AAPkIRRIkAT9CEJwhAAD5FEiT9CcIQiFUiIAA+oilKioCvqIouiKAAPkIRRIkAT9CEIQhAAD5FEiQBP0IB/AEAQAA+RRIkAT9CEYBAH8AAPkUSJP0IB/B8YB/AAD5FEiQBP0IB/EEfwAA+RRIk/QgEEfxBH8AAPkUSJAE/QhCgFBjAAB/AgFBjAA/4iCIIgAAfwUGMAD/hIUhAH8AAH8FBjP+Ih/B8YB/AAB/BQYwAP+Ih/EEfwAAfwIBQIhBAAAD/gAAAH8FBjAA/4AH8AQBAAB/BQYwAP+ABAEAfwAAfwUGM/4AH8HxgH8AAH8FBjAA/4AH8QR/AAB/BQYwAP+QR/EEfwAAfwUGMAD/gACAUGMAAH8FBjAA/4AD4QQ+AAD5CEIQhFEUSJIkAQAA+QhCEUSJAAfwBAEAAPkIQhFEiQBEAQB/AAD5CEIRRIkAB/EAfwAA+QhFEiQAH8HxgH8AAPkIRRIkAB3DURR3AAD5CEIRRIkAB/EEfwAA+QhFEiQAEEfxBH8AAPkIQhFEiQBAgFBjAAD5CEIRRIkAA+EEPgAA+QhCEUSJAAfwUGMAAPkIRRIkAB/H4QB/AAD5CEIRRIkAB/CIfwAA+RRFEURRqkqSpAEAAPkURRqkqQAH8AQBAAD5FEUapKkARAEAfwAA+RRFGqSpAIT5FHIAAPkUapKkAB/B8YB/AAD5FGqSpAAdQ3EUdwAA+RRFGqSpAAfxBH8AAPkUapKkABBH8QR/AAD5FEUapKkAQIBQYwAA+RRFGqSpAAIhVIiAAPkURRqkqQAD4QQ+AAD6lKUpSlOqqqqqAoAA+pSlOqqqgAf4AgCAAPqUpTqqqoCkAQB/gAD6lOUqqgAf4fmAf4AA+pSlOqqqgAf5An+AAPqU6qqqABAn+QJ/gAD6lKU6qqqAoIBQYwAA+pSlOqqqgAIhVIiAAPqUpTqqqoAD8QI/AAD5FEUZRKkqapKkAQAA+RRlEqapAEQBAH8AAPkUZRKmqQAD4QQ+AAD5FEURXFEqSpKkAQAA+RRFcqSpAAfwBAEAAPkURXKkqQBEAQB/AAD5FcqSpAAfwfGAfwAA+RRFcqSpAAfxBH8AAPkVypKkABBH8QR/AAD5FEVypKkAQIBQYwAA+RRFcqSpAAIhVIiAAPkURXKkqQAD4QQ+AAD6lKUpWlKqqqqqAoAA+pSlaqqqgAPxAj8AAPkURXFEUSvKkqQBAAD5FcUSvKkAAiFUiIAA/4iCIVSAggCD/gAAAHcIhVAg/4AH8AQBAAB3CIVQIP+ABAEAfwAAdwiFUCD/n8HxgH8AAHcIhVAg/4AH8QR/AAB3CIVQIP+QR/EEfwAAdwiFUCD/gACAUGMAAHcIhVAg/4AD4QQ+AAB3CIVQIP+CB/BQYwAA+RRFEqSpgEIT9AEAAPkUSpiE/QAH8AQBAAD5FEqYhP0fwfGAfwAA+RRKmIT9AAIhVIiAAPqUpSqqq4CiK+oCgAD6lKq4ivqAAiFUiIAA+RRFEqSpAEIT9AEAAPkUSpCE/QBEAQB/AAD5FEqQhP0fwfGAfwAA+RRKkIT9AAfxBH8AAPkUSpCE/RBH8QR/AAB3CIVQiP+AA+EEPgAA/4iFUiIAP+CAIAgAAHcIhVAA/4IH8AQBAAB3CIVQAP+CBIEAfwAAdwiFU/4IH8HxgH8AAHcIhVAA/4IH8QR/AAB3CIVQAP+SR/EEfwAAdwiFUAD/ggPhBD4AAPkUSpKkAT9CEJwhAAD5FEqT9CcIQiFUiIAA+RRKk/QnCEPhBD4AAPkUSpKkAT9CEIQhAAD/iIVSIgA/4iCIIgAA/4iCIVSIgAAD/gAAAHcIhVAA/4AH8QR/AAB3CIVQAP+AAIBQYwAAdwiFUAD/gAPhBD4AAPkURRFEUSpKkqQBAAD5FEUSpKkAB/AEAQAA+RRFEqSpAEQBAH8AAPkUSpKkAB/B8YB/AAD5FEUSpKkAB/EEfwAA+RRKkqQAEEfxBH8AAPkURRKkqQAD4QQ+AAD5FEUSpKkAB/BQYwAA+RRKkqQBAgfwiBwAAHEAT5CEIZRFEiQBAAAhPkIZRIkAB/AEAQAAIT5CGUSJAEQBAH8AACE+QhlEiQCE+RRyAAAhPkIZRIkfwfGAfwAAIT5CGUSJAAfxBH8AACE+QhlEiRBH8QR/AAAhPkIZRIkAQIBQYwAAIT5CGUSJAAIhVIiAACE+QhlEiQAD4QQ+AAAhPkIZRIkAB/BQYwAAcoCvqIojlKUqKgKAACK+ojlKioAH+AIAgAAivqI5SoqApAEAf4AAIr6iOUqKn+H5gH+AACK+ojlKioAH+QJ/gAAivqI5SoqQJ/kCf4AAIr6iOUqKgKCAUGMAACK+ojlKioACIVSIgAAivqI5SoqAA/ECPwAAcQBPmIQhFGUSJAEAACE+YhFGiQBEAQB/AAAhPmIRRokAhPkUcgAAIT5iEUaJH8HxgH8AACE+YhFGiQAH8QR/AAAhPmIRRokAA+EEPgAAcQBPkIQnFEUSJAEAACE+QnFEiQAH8AQBAAAhPkJxRIkARAEAfwAAIT5CcUSJH8HxgH8AACE+QnFEiQAH8QR/AAAhPkJxRIkQR/EEfwAAIT5CcUSJAECAUGMAACE+QnFEiQACIVSIgAAhPkJxRIkAA+EEPgAAcoCvqIoulKUqKgKAACK+omlKioAH+AIAgAAivqJpSoqApAEAf4AAIr6iaUqKn+H5gH+AACK+omlKioAH+QJ/gAAivqJpSoqQJ/kCf4AAIr6iaUqKgKCAUGMAACK+omlKioAD8QI/AABxAE+QnCEVxRIkAQAAIT7CEUyJAEQBAH8AACE+whFMiQACIVSIgABygK+omiKVpSoqAoAAIr2iKVqKgKQBAH+AACK9oilaioAD8QI/AAAcAAfwIBQawIP+AAAACB/BQYwIP+AB/AEAAAgfwUGMCD/gAQB/AAAIH8FBjAg/4fGAfwAACB/BQYwIP+fxBH8AAAgfwUGMCD/kEfx/AAAIH8FBjAg/4IBQYwAACB/BQYwIP+PhBD4AACE+QhFEiYhCE/QBAAAhPkUaJCE/QAEAfwAAIT5FGiQhP8HxgH8AACE+RRokIT9D4QQ+AAAhPkIRRIkIQhP0AQAAIT5FEiQhP0ABAH8AACE+RRIkIT/B8YB/AAAhPkUSJCE/R/EEfwAAIT5FEiQhP0QR/H8AACE+RRIkIT9AgFBjAAAhPkUSJCE/Q+EEPgAAHAAH8CAUGMIj/gAAAAgfwUGMIj/n8QR/AAAIH8CAUGMAD/ggCAAACB/BQYwAP+CB/AEAAAgfwUGMAD/ggQB/AAAIH8Nj/ggfwfGAfwAACB/BQYz/ggfxBH8AAAgfwUGM/5JH8QR/AAAIH8FBjP+CAIBQYwAACB/BQYz/ggPhBD4AACE+RRIkAT9CEJwhAAAhPkUSJP0JwiFUiIAAIr6lKioCvqIouiKAACK+pSoq+oumKQB/gAAhPkUSJAE/QhCEIQAAIT5FEiT9CEYBAH8AACE+TZP0IB/B8YB/AAAhPkUSJP0IB/EEfwAAIT5Nk/QgEEfxBH8AACE+RRIk/QhCgFBjAAAhPkUSJP0IA+EEPgAACB/AgFBjAA/4iCIAAAgfwUGMAD/hIQB/AAAIH8Nj/iIfwfGAfwAACB/BQYz/iIfxBH8AAAgfwUGM/4iD4QQ+AAAcAAfwIBQYwAP+AAAACB/BQYwAP+AB/AEAAAgfwUGMAD/gAQB/AAAIH8FBjP+fwfGAfwAACB/BQYz/gAfxBH8AAAgfwUGM/5BH8QR/AAAIH8FBjP+AAIBQYwAACB/BQYz/gAPhBD4AAHEAT5CEIRRFEiQBAAAhPkIRRIkAB/AEAQAAIT5CEUSJAEQBAH8AACE+QhFEiQAH8QB/AAAhPkIRRIkfwfGAfwAAIT5CEUSJHcMRBHEAACE+QhFEiQAH8QR/AAAhPkIRRIkQR/EEfwAAIT5CEUSJAECAUGMAACE+QhFEiQAD4QQ+AAD5AkCT5BGEQhMEAQAA+QJPmEThAAfwBAEAAPkCT5hE4QBEAQB/AAD5Ak+YROEfwfGAfwAA+QJPmEThAAfxBH8AAPkCT5hE4RBH8QR/AAD5Ak+YROEAQIBQYwAA+QJPmEThAAPhBD4AAPqCoKvqE4SiKwoCgAD6gq+4SuKAB/gCAIAA+oKvuErigKQBAH+AAPqCr7hK4p/h+YB/gAD6gq+4SuKAB/kCf4AA+oKvuErikCf5An+AAPqCr7hK4oCggFBjAAD6gq+4SuKAAiFUiIAA+oKvuErigAPxAj8AAPkCQJvkEQRiEwQBAAD5Am+QRuEAB/AEAQAA+QJvkEbhAAPhBD4AAPkCQJP8EQRCEwQBAAD5Ak/wROEAB/AEAQAA+QJP8EThAEQBAH8AAPkCT/BE4QAH8QB/AAD5Ak/wROEfwfGAfwAA+QJP8EThAAfxBH8AAPkCT/BE4RBH8QR/AAD5Ak/wROEAQIBQYwAA+QJP8EThAAIhVIiAAPkCT/BE4QAD4QQ+AAD6gqCr+hKEoisKAoAA+oKv6ErigAf4AgCAAPqCr+hK4oCkAQB/gAD6gq/oSuKf4fmAf4AA+oKv6ErigAf5An+AAPqCr+hK4pAn+QJ/gAD6gq/oSuKAoIBQYwAA+oKv6ErigAPxAj8AAPkCQPPkEQXCEwQBAAD5A8+QXOEARAEAfwAA+QPPkFzhH8HxgH8AAPkDz5Bc4QAH8QR/AAD5A8+QXOEQR/EEfwAA+QPPkFzhAECAUGMAAPkDz5Bc4QACIVSIgAD5A8+QXOEAA+EEPgAA+oKg6+oShaIrCgKAAH8AQBH8AQJAg/4AAAB/AEfwJP+AB/AEAQAAfwBH8CT/gAQBAH8AAH8AR/Ak/5/B8YB/AAB/AEfwJP+AB/EEfwAAfwBH8CT/kEfxBH8AAH8AR/Ak/4AAgFBjAAB/AEfwJP+AA+EEPgAA+QJAk+QJikIT9AEAAPkCT5ik/QAH8AQBAAD5Ak+YpP0ARAEAfwAA+QJPmKT9H8HxgH8AAPkCT5ik/QAH8QR/AAD5Ak+YpP0AA+EEPgAA+oKgq+oLiqIr6gKAAPqCr7iq/oAD8QI/AAD5AkCT5AkKQhP0AQAA+R5Ck/QAH8HxgH8AAH8AQBH8AQlCQ/4AAAB/AEfwBAE/4IAgCAAAfwBH8AT/ggfwBAEAAH8AR/AE/4IEgQB/AAB/D8AT/ggfwfGAfwAAfwBH8AT/ggfxBH8AAH8AR/AE/5JH8QR/AAB/AEfwBP+CAIBQYwAAfwBH8AT/ggPhBD4AAPkCT5Ak/QhCcIQhAAD5Ak+QJP0JxhEAfwAA+R5Ak/QjH8HxgH8AAPkeQJP0JwhD4QQ+AADyhK8oSvqIouiKIoAA8pyhK+ouiKPxAj8AAPkCT5AkCT9CEIQhAAD5Ak+QJP0IB/AEAQAA+QJPkCT9CEYBAH8AAPkeQJP0IB/B8YB/AAD5Ak+QJP0IB/EEfwAA+R5Ak/QgEEfxBH8AAPkCT5Ak/QhCgFBjAAD5Ak+QJP0IA+EEPgAAfwBH8AQBP+IgiCIAAH8AR/AE/4SFIQB/AAB/D8AT/iIfwfGAfwAAfwBH8AT/iIfxBH8AAH8AQBH8AQBAA/4AAAB/AEfwBP+AB/AEAQAAfwBH8AT/gAQBAH8AAH8AR/AE/5/B8YB/AAB/AEfwBP+AB/EEfwAAfwBH8AT/kEfxBH8AAH8AR/AE/4AD4QQ+AAD5AkCT5BEEQhMEAQAA+QJPkEThAAfwBAEAAPkCT5BE4QBEAQB/AAD5Ak+QROEfwfGAfwAA+QJPkEThAAfxBH8AAPkCT5BE4RBH8QR/AAD5Ak+QROEAQIBQYwAA+QJPkEThAAPhBD4AAPkgSBPkgaBIE+QBAAD5IE+aBPkAB/AEAQAA+SBPmgT5AEQBAH8AAPkgT5oE+R/B8YB/AAD5IE+aBPkdwxEEcQAA+SBPmgT5AAfxBH8AAPkgT5oE+RBH8QR/AAD5IE+aBPkAQIBQYwAA+SBPmgT5AAIhVIiAAPkgT5oE+QAD4QQ+AAD6oKgr6oOgqCvqAoAA+qCvugr6gAf4AgCAAPqgr7oK+oCkAQB/gAD6oK+6Cvqf4fmAf4AA+qCvugr6gAf5An+AAPqgr7oK+pAn+QJ/gAD6oK+6CvqAoIBQYwAA+qCvugr6gAIhVIiAAPqgr7oK+oAD8QI/AAD5IEgb5IEgaBPkAQAA+SBvkgb5AAPhBD4AAPkgSBPcgSBIE+QBAAD5IE9yBPkAB/AEAQAA+SBPcgT5AEQBAH8AAPkgT3IE+R/B8YB/AAD5IE9yBPkdw1EUdwAA+SBPcgT5AAfxBH8AAPkgT3IE+RBH8QR/AAD5IE9yBPkAQIBQYwAA+SBPcgT5AAIhVIiAAPkgT3IE+QAD4QQ+AADyoKgr2oKgqCvKAoAA8qCvagrygAf4AgCAAPKgr2oK8oCkAQB/gADyoK9qCvKf4fmAf4AA8qCvagrygAf5An+AAPKgr2oK8pAn+QJ/gADyoK9qCvKAoIBQYwAA8qCvagrygAPxAj8AAPkgSHPkgSHIE+QBAAD5Ic8SHPkARAEAfwAA+SHPEhz5AAIhVIiAAPKgqOvKgqOoK8oCgADyoa8qGvKApAEAf4AAfxAH8QB/AgCD/gAAAH8fhAH8CD/gAfwBAAB/H4QB/Ag/4AEAfwAAfx+EAfwIP+HxgH8AAH8fhAH8CD/n8QR/AAB/H4QB/Ag/5BH8fwAAfx+EAfwIP+CAUGMAAH8fhAH8CD/j4QQ+AAB/H4QB/Ag/5/CIfwAA+SBPkgT5iEIT9AEAAPk8SBvkIT9AAQB/AAD6oK+qCvuIoivqAoAA+SBPkgT5CEIT9AEAAPk8SBPkIT9AAQB/AAD5PEgT5CE/QIBQYwAA+TxIE+QhP0PhBD4AAH8QB/EAfwiCI/4AAAB/EAfxAH8AD/ggCAAAfx+EAfwAP+CB/AEAAH8fhAH8AD/ggQB/AAB/H4QD/ggfwfGAfwAAfx+EAfz/ggfxBH8AAH8fhAH8/5JH8QR/AAB/H4QB/P+CAIBQYwAAfx+EAfz/ggPhBD4AAPkgT5IE+QBP0JwhAAB5HEQT9CcIQiFUiIAA+qCvqgr6gK+ouiKAAPkgT5IE+QBP0IQhAAB5HEQR5P0IB/AEAQAAeRxEEeT9CEYBAH8AAHkcRBP0IB/B8YB/AAB5HEQR5P0IB/EEfwAAeRxEE/QgEEfxBH8AAHkcRBHk/QgD4QQ+AAB/EAfxAH8AD/iIIgAAfx+EAfwAP+EhAH8AAH8fhAP+Ih/B8YB/AAB/H4QB/P+Ih/EEfwAAfx+EAfz/iIPhBD4AAH8QB/EAfwAAA/4AAAB/H4QB/AA/4AH8AQAAfx+EAfwAP+ABAH8AAH8fhAH8/4AH8QB/AAB/H4QD/gAfwfGAfwAAfx+EA/4AHcNRFHcAAH8fhAH8/4AH8QR/AAB/H4QB/P+QR/EEfwAAfx+EAfz/gACAUGMAAPkgT5IE+QBAE/QBAAD5PEgT5AE/QAEAfwAAeRxEE/QAH8HxgH8AAHkcRBHk/QAH8QR/AAB5HEQR5P0QR/EEfwAA+SBIE+SBIEgT5AEAAPkgT5IE+QAH8AQBAAD5IE+SBPkARAEAfwAA+SBPkgT5H8HxgH8AAPkgT5IE+QAH8QR/AAD5IE+SBPkQR/EEfwAA+SBPkgT5AECAUGMAAPkgT5IE+QAD4QQ+AAD9EkSRJEmSRJP0AQAA/RJEmST9AAfwBAEAAP0SRJkk/QAH8CQJAAD9EkSZJP0ARAEAfwAA/RJkk/QAH8HxgH8AAP0SZJP0AB3DURR3AAD9EkSZJP0AB/EEfwAA/RJkk/QAEEfxBH8AAP0SRJkk/QBAgFBjAAD9EkSZJP0AAiFUiIAA/RJEmST9AAPhBD4AAP0SZJP0AB/H4QB/AAD6lKUpSlOUpSvqAoAA+pSlOUr6gAf4AgCAAPqUpTlK+oCkAQB/gAD6lOUr6gAf4fmAf4AA+pSlOUr6gAf5An+AAPqU5SvqABAn+QJ/gAD6lKU5SvqAoIBQYwAA+pSlOUr6gAIhVIiAAPqUpTlK+oAD8QI/AAD9EkSZJEkSZJP0AQAA/RJkkSb9AAfwBAEAAP0SRJE8SRJEk/QBAAD5FEVxRPkAB/AEAQAA+RRFcUT5AEQBAH8AAPkVxRPkAB/B8YB/AAD5FEVxRPkAB/EEfwAA+RRFcUT5EEfxBH8AAPkURXFE+QBAgFBjAAD5FEVxRPkAAiFUiIAA+RRFcUT5AAPhBD4AAPqUpSlaUpSlK+oCgAD6lKVpSvqAB/gCAIAA+pSlaUr6gKQBAH+AAPqVpSvqAB/h+YB/gAD6lKVpSvqAB/kCf4AA+pWlK+oAECf5An+AAPqUpWlK+oCggFBjAAD6lKVpSvqAA/ECPwAA/RJE8SRJE8ST9AEAAPkVxRFc+QBEAQB/AAD5FcURXPkfwfGAfwAA+RXFEVz5AAfxBH8AAPkVxRFc+RBH8QR/AAD5FcURXPkAAiFUiIAA+RXFEVz5AAPhBD4AAPqUpWlKUpWlK+oCgAD6laUpWvqf4fmAf4AA+pWlKVr6kCf5An+AAPqVpSla+oCggFBjAAB/CIIgiH8CAIP+AAAAfwiH8CD/gAfwBAEAAH8Ih/Ag/4AEAQB/AAB/CIfwIP+fwfGAfwAAfwiH8CD/gAfxBH8AAH8Ih/Ag/5BH8QR/AAB/CIfwIP+AAIBQYwAAfwiH8CD/gAPhBD4AAP0SRJEk/YhCE/QBAAD9Ek/YhP0AA+EEPgAA/RJEkST9CEIT9AEAAP0ST9CE/QBEAQB/AAB/CIIgiH8IgiP+AAAAfwiH8Ij/gAQBAH8AAH8Ih/CI/5/B8YB/AAB/CIfwiP+QR/EEfwAAfwiH8Ij/gACAUGMAAH8IgiH8AD/ggCAIAAB/CIfwAP+CB/AEAQAAfwiH8AD/ggSBAH8AAH8Ih/AA/4IH8QB/AAB/CIfz/ggfwfGAfwAAfwiH8/4IHcNRFHcAAH8Ih/AA/4IH8QR/AAB/CIfwAP+SR/EEfwAAfwiH8AD/ggCAUGMAAH8Ih/AA/4ID4QQ+AAD9EkST9AE/QhCcIQAA+RRPk/QnCEPhBD4AAP0SRJP0AT9CEIQhAAD9Ek/QBP0IRgEAfwAA+RRPk/QgH8HxgH8AAP0ST9AE/QgH8QR/AAD9Ek/QBP0IQoBQYwAAfwiCIfwAP+IgiCIAAH8Ih/AA/4SFIQB/AAB/CIfz/iIfwfGAfwAAfwiH8AD/iIfxBH8AAH8Ih/AA/4iAgFBjAAB/CIfwAP+Ig+EEPgAAfwiCIIh/AAAD/gAAAH8Ih/AA/4AEAQB/AAB/CIfz/gAfwfGAfwAAfwiH8AD/gAfxBH8AAH8Ih/AA/5BH8QR/AAB/CIfwAP+AAIBQYwAA/RJEkSRJEkST9AEAAP0SRJEk/QAH8AQBAAD9EkSRJP0ARAEAfwAA/RJEk/QAH8HxgH8AAP0SRJEk/QAH8QR/AAD9EkST9AAQR/EEfwAA/RJEkST9AECAUGMAAP0SRJEk/QAD4QQ+AABxAE/QBHGiSJHEAQAAIT9HGiRxAAfwBAEAACE/RxokcQBEAQB/AAAhP0caJHEfwfGAfwAAIT9HGiRxHcNhEHcAACE/RxokcQAH8QR/AAAhP0caJHEQR/EEfwAAIT9HGiRxAECAUGMAACE/RxokcQAD4QQ+AABygK+oCnOiqKnKAoAAIr6nOipygAf4AgCAACK+pzoqcoCkAQB/gAAivqc6KnKf4fmAf4AAIr6nOipygAf5An+AACK+pzoqcpAn+QJ/gAAivqc6KnKAoIBQYwAAIr6nOipygAIhVIiAACK+pzoqcoAD8QI/AABxAE/YBHEiaJHEAQAAIT9nEiZxAAPhBD4AAHEAT9AEdyJIkcQBAAAhPkdyJHEAB/AEAQAAIT5HciRxAEQBAH8AACE+R3IkcR/B8YB/AAAhPkdyJHEdw1EUdwAAIT5HciRxAAfxBH8AACE+R3IkcRBH8QR/AAAhPkdyJHEAQIBQYwAAIT5HciRxAAPhBD4AAHKAr6gKdqKoqcoCgAAivqdqKnKAB/gCAIAAIr6naipygKQBAH+AACK+p2oqcp/h+YB/gAAivqdqKnKAB/kCf4AAIr6naipykCf5An+AACK+p2oqcoCggFBjAAAivqdqKnKAA/ECPwAAcQBPkBxxI8iRxAEAACE+xxIscQAH8AQBAAAhPscSLHEARAEAfwAAIT7HEixxH8HxgH8AACE+xxIscQAH8QR/AAAhPscSLHEQR/EEfwAAIT7HEixxAECAUGMAACE+xxIscQACIVSIgAAhPscSLHEAA+EEPgAAcoCvqBpyo6ipygKAACK+p2oqdoCkAQB/gAAivqdqKnaf4fmAf4AAIr6naip2kKf5An+AAAg/4AD4QQ+Ag/4AAAAIP+QQ+Ag/4AH8AQAACD/kEPgIP+ABAH8AAAg/5BD4CD/h8YB/AAAIP+QQ+Ag/42EQdwAACD/kEPgIP+fxBH8AAAg/5BD4CD/kEfx/AAAIP+QQ+Ag/4IBQYwAACD/kEPgIP+PhBD4AAAg/5BD4CD/n4QB/AAAhP0ARxImcQhP0AQAAIT9EmMQhP0AB/AEAACE/RJjEIT9AAQB/AAAhP0SYxCE/wfGAfwAAIT9EmMQhP0CAUGMAACE/RJjEIT9D4QQ+AAAivqApyoucoivqAoAAIr+kuMoiv6AB/gCAACK/pKjOIr+gKQB/gAAiv6S4yiK/oIBQYwAAIr+kuMoiv6PxAj8AACE/QBHEiRxCE/QBAAAhP0SQxCE/QAH8AQAAIT9EkMQhP0ABAH8AACE/RJDEIT/B8YB/AAAhP0SQxCE/RBH8fwAAIT9EkMQhP0CAUGMAACE/RJDEIT9D4QQ+AAAIP+AA+EEPgiP+AAAACD/kEPgiP+ABAH8AAAg/5BD4Ij/h8YB/AAAIP+QQ+CI/5BH8fwAACD/kEPgiP+CAUGMAAAg/4+EEPgAP+CAIAAAIP+QQ+P+CB/AEAQAACD/kEPj/ggSBAH8AAAg/5BP+CB/B8YB/AAAIP+QT/ggdw2EQdwAACD/kEPj/ggfxBH8AAAg/5BD4/4IAgFBjAAAIP+QQ+P+CA+EEPgAAIT9HEiRxAE/QnCEAACE/RJDE/QnGEQB/AAAhP0ST9CMfwfGAfwAAIT9EkMT9CMfxBH8AACE/RJDE/QjD4QQ+AAAivqcqKnKAr6i6IoAAIr6lK+ouiKf4AgCAACK/pKjK+oumKQB/gAAivqUr6iaf4fmAf4AAIr6lK+ouiKPxAj8AACE/RxIkcQBP0IQhAAAhP0SQxP0IB/AEAQAAIT9EkMT9CEYBAH8AACE/RJP0IB/B8YB/AAAhP0SQxP0IB/EEfwAAIT9Ek/QhEEfxBH8AACE/RJDE/QhCgFBjAAAhP0SQxP0IA+EEPgAACD/j4QQ+AA/4iCIAAAg/5BD4/4iH8AQBAAAIP+QQ+P+EhSEAfwAACD/kE/4iH8HxgH8AAAg/5BD4/4iH8QR/AAAIP+QQ+P+IgIBQYwAACD/kEPj/iIPhBD4AAAg/4AD4QQ+AA/4AAAAIP+QQ+P+AB/AEAQAACD/kEPj/gAQBAH8AAAg/5BD4/4CE+RRyAAAIP+QQ+P+AB/EAfwAACD/kEPj/n8HxgH8AAAg/5BD4/53DEQRxAAAIP+QQ+P+AB/EEfwAACD/kEPj/kEfxBH8AAAg/5BD4/4AAgFBjAAAIP+QQ+P+AA+EEPgAACD/kEPj/n8fhAH8AACE/QBHEiRxAE/QBAAAhP0SQxP0ARAEAfwAAIT9EkMT9H8HxgH8AACE/RJDE/QAH8QR/AAAhP0SQxP0QR/EEfwAAIT9EkMT9AAPhBD4AAHEAT9AEcSJIkcQBAAAhP0cSJHEAB/AEAQAAIT9HEiRxAEQBAH8AACE/RxIkcR/B8YB/AAAhP0cSJHEAB/EEfwAAIT9HEiRxEEfxBH8AACE/RxIkcQBAgFBjAAAhP0cSJHEAA+EEPgAA"; +function encode(s,max=255){let out='';for(const c of s){let v=c;if(c.charCodeAt(0)>127){let n=fixed.indexOf(c);if(n<0){let k=native.indexOf(c);if(k<0)throw Error('본체 메뉴에서 지원하지 않는 문자: '+c);n=fixed.length+k;}v=String.fromCharCode(128+(n>>7),128+(n&127));}if(out.length+v.length>max)break;out+=v;}return out;} +function font(){return typeof Buffer!=='undefined'?new Uint8Array(Buffer.from(data,'base64')):Uint8Array.from(atob(data),c=>c.charCodeAt(0));} +root.ParamixKoreanMenu={encode,font,fixed,native}; +if(typeof module!=='undefined')module.exports=root.ParamixKoreanMenu; +})(typeof window!=='undefined'?window:globalThis); diff --git a/src/restore.html b/src/restore.html new file mode 100644 index 0000000..13317dd --- /dev/null +++ b/src/restore.html @@ -0,0 +1,22 @@ + + +기종별 원본 복원 · 다마고치 연구소 + + +
+

TAMAGOTCHI PARADISE · RECOVERY

기종별 백업으로 복원

+

관리자가 공개한 파일을 확인하고 백업 당시의 상태로 돌아갑니다.

+

기종별 복원은 로그인 후 이용할 수 있습니다. 회원가입·로그인

+ diff --git a/src/restore.js b/src/restore.js new file mode 100644 index 0000000..9fd5a72 --- /dev/null +++ b/src/restore.js @@ -0,0 +1,109 @@ +'use strict'; +const $ = id => document.getElementById(id), A = window.TamaArchive, FL = window.ParamixFlash; +let items = [], selected = null, image = null, io = null, dev = null, deviceId = 0, running = false, authenticated = false; +function status(message) { $('status').textContent = message; } +function render() { + $('restoreContent').hidden = !authenticated; $('restoreLogin').hidden = authenticated; + $('catalog').disabled = running || !items.length; + $('prepare').disabled = running || !selected; + $('download').disabled = running || !image; + $('connect').disabled = running || !!io || !navigator.serial; + $('disconnect').disabled = running || !io; + $('backup').disabled = running || !dev || A.hasPending(); + $('retryBackup').hidden=!A.hasPending();$('retryBackup').disabled=running; + $('ack').disabled = running; + $('restore').disabled = running || !image || !dev || !deviceId || deviceId !== selected?.edition || !$('ack').checked; +} +async function task(fn) { + if (running || !authenticated) return; + running = true; render(); + try { await fn(); } catch (e) { status('작업 실패: ' + e.message); } + finally { running = false; render(); } +} +function progress(phase, done, total) { + $('progress').value = total ? done / total * 100 : 0; + status(({load: '연결 프로그램 불러오기', read: '본체 읽기', compare: '파일 비교', write: '본체 기록', check: '기록 검증', prepare: '준비'}[phase] || '처리') + ' ' + Math.round(total ? done / total * 100 : 0) + '%'); +} +function save(img, name) { + const url = URL.createObjectURL(new Blob([img], {type: 'application/octet-stream'})); + const a = document.createElement('a'); a.href = url; a.download = name; a.click(); + setTimeout(() => URL.revokeObjectURL(url), 30000); +} +function choose() { + selected = items.find(x => (x.id || x.sha256) === $('catalog').value) || null; + image = null; $('ack').checked = false; $('fileStatus').textContent = ''; + $('details').textContent = selected ? selected.name + ' · 16 MB · ' + (selected.sourceDate || selected.createdAt) + '\nSHA-256: ' + selected.sha256 : ''; + render(); +} +$('catalog').onchange = choose; +$('ack').onchange = render; +$('prepare').onclick = () => task(async () => { + image = null; $('fileStatus').textContent = '복원 파일을 불러와 확인하고 있습니다…'; + const response = await fetch(selected.fileUrl || '/api/file/' + selected.sha256, {cache: 'no-store', signal: AbortSignal.timeout(90000)}); + if (!response.ok) { $('fileStatus').textContent = '파일 불러오기 실패'; throw new Error('공개된 파일을 불러올 수 없습니다.'); } + image = await A.verify(new Uint8Array(await response.arrayBuffer()), selected); + $('fileStatus').textContent = '파일 확인을 마쳤습니다. 본체를 연결하고 복원을 진행하세요.'; +}); +$('download').onclick = () => { if (authenticated && image && !running) save(image, 'paradise-' + selected.slug + '-restore-' + selected.sha256.slice(0, 12) + '.bin'); }; +$('connect').onclick = async () => { + if (!authenticated || running || io || !navigator.serial) return; + // Keep requestPort in the user's click event for the browser permission chooser. + let port; + try { port = await navigator.serial.requestPort(); } catch (e) { status('기기 선택을 취소했습니다.'); return; } + await task(async () => { + try { + io = await FL.serialOpen(port); + const result = await FL.connect(io, FL.embedded(), {}, progress); + dev = result.dev; + deviceId = await A.deviceEdition(dev); + if (dev.info.capacity !== 0x1000000) throw new Error('지원하지 않는 본체 용량입니다.'); + $('deviceStatus').textContent = deviceId ? '연결됨: ' + FL.EDITIONS[deviceId] : '연결됐지만 기종을 확인할 수 없습니다. 복원 기록은 차단됩니다.'; + status('선택한 파일과 본체 기종이 같아야 복원할 수 있습니다.'); + } catch (e) { + if (io) await io.close().catch(() => {}); + io = null; dev = null; deviceId = 0; throw e; + } + }); +}; +$('disconnect').onclick = () => task(async () => { if (io) await io.close(); io = null; dev = null; deviceId = 0; $('deviceStatus').textContent = '연결 해제됨'; }); +$('backup').onclick = () => task(async () => { + const current = await dev.dump(progress); + const name='paradise-' + (FL.EDITIONS[A.edition(current)] || 'unknown').toLowerCase().replace(/ /g, '-') + '-' + new Date().toISOString().replace(/[:.]/g, '-') + '.bin'; + await A.deliver(current,name,save,status); +}); +$('retryBackup').onclick=()=>task(()=>A.retry()); +$('restore').onclick = async () => { + if (!authenticated || running || !image || !dev || !deviceId || deviceId !== selected?.edition || !$('ack').checked) return; + if (!confirm(selected.label + '으로 복원합니다.\n현재 저장 데이터와 추가 메뉴가 교체됩니다.\n전원과 케이블을 유지하세요. 계속할까요?')) return; + await task(async () => { + await A.verify(image, selected); + if (await A.deviceEdition(dev) !== selected.edition) throw new Error('본체 기종이 선택한 백업과 다릅니다.'); + // Exact image restoration: no composition, save merging or rescue-code insertion. + // The upstream writer verifies each committed sector and all 64 KB blocks. + const result = await dev.write(image, {onlyChanged: true, keep: null}, progress); + status('복원 기록·검증 완료 (' + result.written + '개 구역). 연결을 해제하고 본체 전원을 껐다 켜세요.'); + $('ack').checked = false; + }); +}; +window.addEventListener('beforeunload', event => { if (running || A.hasPending()) { event.preventDefault(); event.returnValue = ''; } }); +if (!navigator.serial) $('deviceStatus').textContent = '본체 연결은 PC의 Chrome 또는 Edge에서 지원합니다. 파일 다운로드는 가능합니다.'; +render(); +async function refreshRestoreMembership() { + if (running) return; + try { + const me = await A.request('/api/member/me'); + authenticated = !!me.authenticated; + render(); + if (!authenticated) { items=[]; selected=null; image=null; $('ack').checked=false; return; } + const result = await A.request('/api/catalog'); + items = result.items.concat(me.authenticated ? me.items.filter(x => x.edition).map(x => ({...x, label:'내 보관함 · '+x.label})) : []); + $('catalog').replaceChildren(); + for (const item of items) { const opt = document.createElement('option'); opt.value = item.id || item.sha256; opt.textContent = item.label; $('catalog').appendChild(opt); } + const requested = new URLSearchParams(location.search).get('backup'); + if (requested && items.some(x => x.id === requested)) $('catalog').value = requested; + if (!items.length) { const opt = document.createElement('option'); opt.textContent = '공개된 백업이 없습니다.'; $('catalog').appendChild(opt); } + choose(); + } catch(e) { authenticated=false; render(); status(e.message); } +} +refreshRestoreMembership(); +window.addEventListener('focus', refreshRestoreMembership); diff --git a/src/saves.js b/src/saves.js new file mode 100644 index 0000000..1b372c3 --- /dev/null +++ b/src/saves.js @@ -0,0 +1,334 @@ +/* + * Paramix Studio: save games in and out of the Paradise. + * + * Paradise: the game keeps its progress in the flash after the edition ID page + * (0xD4A000, Tropical/Glacier 0xD2A000) up to 0xF00000. Exported as a + * .tamasave (format 3 of the TamaParadise app): every page of that region, + * the seconds counter of the device and an armed wake alarm, so the app + * continues instead of starting like a fresh battery. Behind the pages a + * Paramix trailer ("PMXE", edition, region) that the app ignores and the + * Studio uses to refuse a save of another edition. + * + * TamaEmu: the guest's own save is its flash. Exported as the raw image the + * TamaEmu app uses (.sav, 4 MB or 8 MB; named after the app's device: plus-color, idl, ps, 4u): packed blocks plus the spare pages + * the emulator wrote. Importing a .sav works like choosing a firmware. + * + * Author: mameise + */ +(function (root) { +'use strict'; + +const PAGE = 0x1000; +const MAGIC = 'TAMASAVE', VERSION = 3, TRAILER = 0x45584D50; // "PMXE" +const SET_A = 0xEFE000, SET_B = 0xEFF000, REGION_END = 0xF00000; +const u16 = (b, o) => b[o] | (b[o + 1] << 8); +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } + +/** Edition 5/6 (Tropical, Glacier) keep their ID page lower. */ +function idPage(edition) { return edition === 5 || edition === 6 ? 0xD29000 : 0xD49000; } +function region(edition) { return [idPage(edition) + PAGE, REGION_END]; } +function family(edition) { return edition === 5 || edition === 6 ? 'gen3' : edition === 4 ? 'jade' : 'gen1'; } + +/* Settings block: CRC-16/ARC over bytes 4..4095 at 0, its inverse at 2. */ +function crc16arc(d, from, to) { + let c = 0; + for (let i = from; i < to; i++) { c ^= d[i]; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xA001 : c >>> 1; } + return c; +} +function settingsOk(p) { const c = crc16arc(p, 4, PAGE); return u16(p, 0) === c && u16(p, 2) === (~c & 0xFFFF); } + +// ---------------------------------------------------------------- Paradise +/** Pages of the save region from a 16 MB image (all of them, empty ones too). */ +function paraFromImage(img, edition) { + const [a, b] = region(edition), pages = new Map(); + for (let p = a; p < b; p += PAGE) pages.set(p, img.slice(p, p + PAGE)); + return pages; +} +/** + * .tamasave from pages (Map address -> 4 KB). clock: { counter, ctrl } of the device or null. + */ +function paraEncode(pages, edition, clock, now = Math.floor(Date.now() / 1000)) { + const counter = clock ? clock.counter >>> 0 : 0; + const alarm = counter ? counter - 1 : 0, status = counter ? 0x100 : 0; // armed, as the app does when it puts the console away + // the always powered system registers as the app stores them (clock and PLL as the firmware sets them) + const regs = counter ? [[0x000, 0xC051], [0x004, 0xA55A0000], [0x00C, 4], [0x010, 0], [0x018, 0x21], [0x020, 0x42], [0x050, 0], + [0x100, 0x157EB7], [0x108, 0], [0x10C, 0x1FFFFD], [0x110, 0], [0x200, clock.ctrl & 0x80 ? clock.ctrl >>> 0 : 0xE0], [0x204, 0], + [0x210, 0], [0x214, 0], [0x218, 0], [0x230, alarm], [0x234, status], [0x300, 0x10]] : []; + const list = [...pages.keys()].sort((x, y) => x - y); + const size = 36 + 8 * regs.length + 4 + list.reduce((n, a) => n + 8 + pages.get(a).length, 0) + 16; + const out = new Uint8Array(size); + for (let i = 0; i < 8; i++) out[i] = MAGIC.charCodeAt(i); + w32(out, 8, VERSION); + w32(out, 12, counter ? now : 0); w32(out, 16, 0); // u64 time stamp (seconds since 1970) + w32(out, 20, counter); w32(out, 24, alarm); w32(out, 28, status); w32(out, 32, regs.length); + let o = 36; + for (const [k, v] of regs) { w32(out, o, k); w32(out, o + 4, v); o += 8; } + w32(out, o, list.length); o += 4; + for (const a of list) { const d = pages.get(a); w32(out, o, a / PAGE); w32(out, o + 4, d.length); out.set(d, o + 8); o += 8 + d.length; } + w32(out, o, TRAILER); w32(out, o + 4, edition); w32(out, o + 8, region(edition)[0]); w32(out, o + 12, region(edition)[1]); + return out; +} +/** Write a decoded save back as it was (time stamp, clock, registers kept). */ +function paraWrite(save, edition) { + const regs = save.regs || [], list = [...save.pages.keys()].sort((x, y) => x - y); + const size = 36 + 8 * regs.length + 4 + list.reduce((n, a) => n + 8 + save.pages.get(a).length, 0) + 16; + const out = new Uint8Array(size); + for (let i = 0; i < 8; i++) out[i] = MAGIC.charCodeAt(i); + w32(out, 8, VERSION); + w32(out, 12, save.stamp % 4294967296); w32(out, 16, Math.floor(save.stamp / 4294967296)); + w32(out, 20, save.counter); w32(out, 24, save.alarm); w32(out, 28, save.status); w32(out, 32, regs.length); + let o = 36; + for (const [k, v] of regs) { w32(out, o, k); w32(out, o + 4, v); o += 8; } + w32(out, o, list.length); o += 4; + for (const a of list) { const d = save.pages.get(a); w32(out, o, a / PAGE); w32(out, o + 4, d.length); out.set(d, o + 8); o += 8 + d.length; } + const ed = edition || save.edition; + w32(out, o, TRAILER); w32(out, o + 4, ed); w32(out, o + 8, region(ed)[0]); w32(out, o + 12, region(ed)[1]); + return out; +} +/** Read a .tamasave (format 3). Throws on anything else. */ +function paraDecode(b) { + if (b.length < 40 || String.fromCharCode(...b.subarray(0, 8)) !== MAGIC) throw new Error('not a Paradise save (.tamasave)'); + if (u32(b, 8) !== VERSION) throw new Error('unknown save version ' + u32(b, 8)); + const stamp = u32(b, 12) + u32(b, 16) * 4294967296, counter = u32(b, 20), alarm = u32(b, 24), status = u32(b, 28); + const nr = u32(b, 32); let o = 36; + const regs = []; + for (let i = 0; i < nr; i++) { if (o + 8 > b.length) throw new Error('save is cut off'); regs.push([u32(b, o), u32(b, o + 4)]); o += 8; } + if (o + 4 > b.length) throw new Error('save is cut off'); + const np = u32(b, o); o += 4; + const pages = new Map(); + for (let i = 0; i < np; i++) { + if (o + 8 > b.length) throw new Error('save is cut off'); + const a = u32(b, o) * PAGE, n = u32(b, o + 4); o += 8; + if (o + n > b.length) throw new Error('save is cut off'); + pages.set(a, b.slice(o, o + n)); o += n; + } + let edition = 0; + if (o + 16 <= b.length && u32(b, o) === TRAILER) edition = u32(b, o + 4); + return { stamp, counter, alarm, status, regs, pages, edition }; +} +/** + * Can this save go onto a device of this edition? Returns { errors, warnings, pages (only the + * save region, full 4 KB), complete }. + */ +function paraCheck(save, edition) { + const errors = [], warnings = [], [a, b] = region(edition), pages = new Map(); + if (save.edition && save.edition !== edition) errors.push({ code: 'saveOtherEd', p: { s: save.edition, d: edition } }); + let outside = 0; + for (const [p, d] of save.pages) { + if (p < a || p >= b || d.length !== PAGE) { outside++; continue; } + pages.set(p, d); + } + if (outside) warnings.push({ code: 'saveOutside', p: { n: outside } }); + const sa = pages.get(SET_A), sb = pages.get(SET_B); + const set = sa && settingsOk(sa) ? sa : sb && settingsOk(sb) ? sb : null; + if (!set) errors.push({ code: 'saveNoSettings' }); + else if ((u16(set, 12) === 0x016D) !== (family(edition) === 'gen3')) errors.push({ code: 'saveFamily' }); + let complete = true; + for (let p = a; p < b; p += PAGE) if (!pages.has(p)) { complete = false; break; } + if (!complete) warnings.push({ code: 'saveIncomplete' }); + return { errors, warnings, pages, complete }; +} +/** Seconds counter to set on the device: the saved one plus the time since. */ +function paraClock(save, now = Math.floor(Date.now() / 1000)) { + if (!save.counter || !save.stamp) return null; + return (save.counter + Math.max(0, now - save.stamp)) >>> 0; +} + +// ---------------------------------------------------------------- change a Paradise save (1.6.8) +// The pet in the settings block: +4/+6 character, +0x10 sickness, +0x18 bits 2..4 stage, +0x1C hunger 0..6, +// +0x1D happiness 0..20. Planet level: low nibble = level, high nibble = level already celebrated. +const PET = { gen1: { tama: 0x104, level: 0x7C }, jade: { tama: 0x108, level: 0x7C }, gen3: { tama: 0x114, level: 0x88 } }; +function paraSettings(save) { for (const a of [SET_A, SET_B]) { const p = save.pages.get(a); if (p && p.length === PAGE && settingsOk(p)) return p; } return null; } +/** What the save says about the pet: { level, id, stage, hunger, happy, sick } or null. */ +function paraPet(save, edition) { + const p = paraSettings(save), o = PET[family(edition)]; if (!p || !o) return null; + const t = o.tama; + return { level: p[o.level] & 15, id: u16(p, t + 4), stage: (p[t + 0x18] >> 2) & 7, hunger: p[t + 0x1C], happy: p[t + 0x1D], sick: p[t + 0x10] }; +} +/** + * Changed copy of the save. ch: { level, id, stage, care } (each optional). A new character goes + * into the settings block and into the pet's own file (pages with the old character in the header). + */ +const TAMA_ANY = true; +function paraPetSet(save, edition, ch) { + const p0 = paraSettings(save), o = PET[family(edition)]; + if (!p0 || !o) throw new Error('the save has no settings block'); + const t = o.tama, p = p0.slice(), pages = new Map(save.pages); + const old = u16(p, t + 4); + if (ch.level !== undefined) { const v = Math.max(0, Math.min(10, ch.level | 0)), now = p[o.level] & 15; p[o.level] = v > now ? (p[o.level] & 0xF0) | v : (v << 4) | v; } + if (ch.id) { + p[t + 4] = ch.id & 255; p[t + 5] = ch.id >> 8; p[t + 6] = ch.id & 255; p[t + 7] = ch.id >> 8; + if (ch.stage) p[t + 0x18] = (p[t + 0x18] & ~0x1C) | ((ch.stage & 7) << 2); + let found = 0; + if (old && old !== ch.id) for (const [a, d] of save.pages) { + if (a === SET_A || a === SET_B || d.length !== PAGE) continue; + // 1.7.2 TAMA_ANY: a bred Tama's file was not found (GitHub): small number at +8, character at +0x0C or +0x0E + if (TAMA_ANY ? (u32(d, 8) === 0 || u32(d, 8) > 255 || (u16(d, 14) !== old && u16(d, 12) !== old)) : (u32(d, 8) !== 1 || u16(d, 14) !== old)) continue; + const n = d.slice(); found++; + if (!TAMA_ANY || u16(n, 14) === old) { n[14] = ch.id & 255; n[15] = ch.id >> 8; } + if (u16(n, 12) === old) { n[12] = ch.id & 255; n[13] = ch.id >> 8; } + if (u16(n, 0x10A) === old) { n[0x10A] = ch.id & 255; n[0x10B] = ch.id >> 8; } + if(((u32(d,0)+u32(d,4))>>>0)===0){ + const names=ch.koreanName; + if(names){const C=globalThis.ParamixCore; n.fill(0,18+8*26,18+9*26);[...names].slice(0,12).forEach((c,i)=>{const v=C.TXT_ENC[c]??C.KO_ENC[c];n[18+8*26+i*2]=v&255;n[19+8*26+i*2]=v>>8;});} + if(ch.stage){n[0xFC]=ch.stage;n[0xFD]=0;} + let delta=0;for(let i=8;i<0x180;i+=4)delta=(delta+u32(n,i)-u32(d,i))>>>0; + const sum=(u32(d,0)+delta)>>>0;w32(n,0,sum);w32(n,4,-sum>>>0); + } + pages.set(a, n); + } + if (TAMA_ANY && old && old !== ch.id && !found) throw new Error('the Tama\'s own file is not in the save, the Tama would not change'); + } + for(const [key,off,max]of [['hunger',0x1C,6],['happy',0x1D,20],['sick',0x10,1]]){ + if(ch[key]!==undefined){if(!Number.isInteger(ch[key])||ch[key]<0||ch[key]>max)throw Error('저장 데이터 값의 범위를 확인하세요.');p[t+off]=ch[key];} + } + if (ch.care) { p[t + 0x1C] = 6; p[t + 0x1D] = 20; p[t + 0x10] = 0; } + const c = crc16arc(p, 4, PAGE); p[0] = c & 255; p[1] = c >> 8; p[2] = ~c & 255; p[3] = (~c >> 8) & 255; + pages.set(SET_A, p); pages.set(SET_B, p.slice()); + return Object.assign({}, save, { pages }); +} + +// ---------------------------------------------------------------- TamaEmu +const APP_CFG = 0xA0140, PMXC = 0x43584D50, PG_MAGIC = 0x50584D50, PG_MAX = 64; +const KINDS = { 0: { dev: 'pc', size: 0x400000, app: 'plus-color' }, 1: { dev: 'idl', size: 0x800000, app: 'idl' }, + 2: { dev: 'ps', size: 0x800000, app: 'ps' }, 3: { dev: '4u', size: 0x800000, app: '4u' }, 4: { dev: '4u-plain', size: 0x800000, app: '4u-plain' } }; +/** Settings block of the emulator in an image (or the 4 KB sector at 0xA0000). */ +function emuCfg(sec, base = 0xA0000) { + const c = APP_CFG - base; + if (u32(sec, c) !== PMXC) return null; + const v = u32(sec, c + 4), kind = u32(sec, c + 20); + if (!KINDS[kind]) return null; + return { version: v, guestOff: u32(sec, c + 8), guestSize: u32(sec, c + 12), saveOff: u32(sec, c + 16), kind, map: sec.slice(c + 24, c + 152), spareEnd: v >= 3 ? u32(sec, c + 152) : 0, lzOff: v >= 5 ? u32(sec, c + 160) : 0, ...KINDS[kind] }; +} +/** + * Guest flash (the .sav of the TamaEmu app) from the packed firmware and the spare pages. + * read(addr, len) gives bytes of the Paradise flash (sync or async). + */ +function lzDec(s, n) { // LZ4 block (as emu.js) + const d = new Uint8Array(n).fill(0xFF); let ip = 0, op = 0; + for (;;) { + const t = s[ip++]; let l = t >> 4; + if (l === 15) { let x; do { x = s[ip++]; l += x; } while (x === 255); } + while (l-- > 0 && op < n) d[op++] = s[ip++]; + if (op >= n || ip >= s.length) return d; + const o = s[ip] | (s[ip + 1] << 8); ip += 2; let m = (t & 15) + 4; + if ((t & 15) === 15) { let x; do { x = s[ip++]; m += x; } while (x === 255); } + while (m-- > 0 && op < n) { d[op] = d[op - o]; op++; } + } +} +/* 1.7.3 test21 LZ_GONE: TamaEmu notes behind its page table which packed blocks the pet erased (four words, then + * their xor with 0x454E4F47). Those blocks read empty, apart from the parts in spare pages (written after this). */ +function lzGoneApply(t, o, g, size) { + if (t.length < o + 20) return; + let x = 0x454E4F47; for (let i = 0; i < 4; i++) x = (x ^ u32(t, o + 4 * i)) >>> 0; + if (x !== u32(t, o + 16)) return; + for (let b = 0; b < 128 && (b << 16) < size; b++) if ((u32(t, o + 4 * (b >> 5)) >>> (b & 31)) & 1) g.fill(0xFF, b << 16, (b + 1) << 16); +} +async function emuGuestAsync(read, cfg, progress) { + const out = new Uint8Array(cfg.size).fill(0xFF), nb = cfg.size >> 16; + let done = 0; const todo = [...cfg.map.subarray(0, nb)].filter((k) => k !== 0xFF).length; + for (let b = 0; b < nb; b++) { + let k = cfg.map[b]; + if (k === 0xFF) continue; + if (k === 0xFE) k = b; + out.set(new Uint8Array(await read(cfg.guestOff + (k << 16), 0x10000)), b << 16); + if (progress) progress('read', ++done, todo); + } + // 1.7.3 GUEST_LZ: the packed cold blocks (LZ4 parts of 1 KB, see emu.js lzPack) + if (cfg.lzOff) { + const t = new Uint8Array(await read(cfg.lzOff, 512)); + for (let b = 0; b < nb; b++) { + const lp = u32(t, 4 * b); if (!lp || cfg.map[b] !== 0xFF) continue; + const l = new Uint8Array(await read(cfg.lzOff + lp, 65 * 4)), a0 = u32(l, 0), z0 = u32(l, 256); + const raw = z0 > a0 ? new Uint8Array(await read(cfg.lzOff + a0, z0 - a0)) : new Uint8Array(0); + for (let k = 0; k < 64; k++) { + const a = u32(l, 4 * k) - a0, z = u32(l, 4 * k + 4) - a0, at = (b << 16) + k * 0x400; + if (z === a) continue; + out.set(z - a >= 0x400 ? raw.subarray(a, a + 0x400) : lzDec(raw.subarray(a, z), 0x400), at); + } + } + } + // spare pages (8 KB parts the guest wrote into blocks that are empty in the firmware) + if (cfg.spareEnd) { + const lo = (cfg.guestOff + cfg.guestSize + 0x1FFF) & ~0x1FFF, hi = cfg.spareEnd & ~0x1FFF; + if (hi >= lo + 0x4000) { + const data = lo + 0x2000; let n = (hi - data) >> 13; if (n > PG_MAX) n = PG_MAX; + const t = new Uint8Array(await read(lo, 16 + 2 * PG_MAX + 20)); + let x = (PG_MAGIC ^ Math.imul(n, 0x9E3779B1)) >>> 0; + for (let i = 0; i < PG_MAX; i++) x = (((x << 5) | (x >>> 27)) ^ u16(t, 16 + 2 * i)) >>> 0; + if (u32(t, 0) === PG_MAGIC && u32(t, 4) === n && u32(t, 8) === x) { + lzGoneApply(t, 16 + 2 * PG_MAX, out, cfg.size); // 1.7.3 test21 LZ_GONE: packed blocks the pet erased + for (let i = 0; i < n; i++) { + const v = u16(t, 16 + 2 * i); + if (v === 0xFFFF || (v << 13) >= cfg.size) continue; + if (cfg.map[(v << 13) >> 16] !== 0xFF) continue; // only blocks that are empty in the firmware + out.set(new Uint8Array(await read(data + (i << 13), 0x2000)), v << 13); + } + } + } + } + return out; +} + +// ---------------------------------------------------------------- T7Emu +/* + * The pet's EEPROM (4 KB) in the ROM: two slots of 8 KB from 0x0C1000 (header sector: + * "T7EE", sequence, page mask, checksum; then the pages). The T7Emu app keeps it as + * save.bin: page mask (2 bytes) and the 16 pages, 4098 bytes. Same content, so it can go back and forth. + */ +const T7_EE = 0xC1000, T7_EE_MAGIC = 0x45453754, T7_SAVE_LEN = 4098; +function t7Sum(b, o) { let s = 0x7E7E; for (let i = 0; i < 4096; i++) s = (Math.imul(s, 31) + b[o + i]) >>> 0; return s; } +// test27: up to test26 the T7Emu could write its pages 2 bytes off (the flash DMA takes words, its buffer lay at ...2): +// 2 other bytes first, the pages without their last 2. The header sum is over the right pages, so such a slot is found. +function t7Sum2(b, o) { let s = 0x7E7E; for (let i = 2; i < 4096; i++) s = (Math.imul(s, 31) + b[o + i]) >>> 0; return Math.imul(Math.imul(s, 31) >>> 0, 31) >>> 0; } +function t7Slot(img, at) { + if (u32(img, at) !== T7_EE_MAGIC) return null; + const sum = u32(img, at + 12), sh = sum === t7Sum(img, at + 0x1000) ? 0 : sum === t7Sum2(img, at + 0x1000) ? 2 : -1; + if (sh < 0) return null; + return { seq: u32(img, at + 4), have: u32(img, at + 8) & 0xFFFF, at, sh }; +} +function t7Newest(img, ee = T7_EE) { const a = t7Slot(img, ee), b = t7Slot(img, ee + 0x2000); if (a && b) return ((a.seq - b.seq) | 0) > 0 ? a : b; return a || b; } +/** save.bin of the T7Emu app from a 16 MB image (null: the pet has no save yet). base: save area of + * the T7Emu (0x0C0000, a further one from 1.6.0 its own). */ +function t7SaveOut(img, base = 0xC0000) { + const s = t7Newest(img, base + 0x1000); if (!s) return null; + const out = new Uint8Array(T7_SAVE_LEN); out[0] = s.have & 255; out[1] = s.have >> 8; + out.set(img.subarray(s.at + 0x1000 + s.sh, s.at + 0x2000), 2); // shifted slot: the last 2 bytes stay 0 + return out; +} +function t7SaveCheck(b) { return b && b.length === T7_SAVE_LEN; } +/** save.bin into the image: into the older slot, as the device does. Returns a new image. */ +function t7SaveIn(img, save, base = 0xC0000) { + if (!t7SaveCheck(save)) throw new Error('not a T7Emu save (save.bin, 4098 bytes)'); + const ee = base + 0x1000, out = new Uint8Array(img), cur = t7Newest(img, ee); + const at = cur && cur.at === ee ? ee + 0x2000 : ee; + out.fill(0xFF, at, at + 0x2000); + out.set(save.subarray(2), at + 0x1000); + w32(out, at, T7_EE_MAGIC); w32(out, at + 4, cur ? (cur.seq + 1) >>> 0 : 1); w32(out, at + 8, save[0] | (save[1] << 8)); w32(out, at + 12, t7Sum(out, at + 0x1000)); + out.fill(0xFF, base, base + 0x1000); // the running session belongs to the old pet + return out; +} + +/** Merge explicit edits into the writer's freshly preserved device save. */ +function keepEdits(base, edition, names, changes, expectedId) { + return async function(dev, image, changed, moves) { + const result=await base(dev,image,changed,moves), before=result.image, out=before.slice(); + if(changes && Object.keys(changes).length){ + const save={pages:paraFromImage(out,edition),edition}; + const pet=paraPet(save,edition); + if(!pet || (expectedId && pet.id!==expectedId))throw Error('본체의 다마고치가 편집을 시작했을 때와 다릅니다. 본체를 다시 읽고 수정하세요.'); + const next=paraPetSet(save,edition,changes); + for(const [a,d]of next.pages)if(d.length===4096)out.set(d,a); + } + if(names && names.size)globalThis.ParamixCore.koreanPetNames(out,edition,names); + const updated=new Set(); + for(let a=0;a!updated.has(a))}; + }; +} +root.ParamixSaves = { keepEdits, paraPet, paraPetSet, paraWrite, t7SaveOut, t7SaveIn, t7SaveCheck, T7_EE, idPage, region, family, settingsOk, crc16arc, paraFromImage, paraEncode, paraDecode, paraCheck, paraClock, emuCfg, emuGuestAsync, lzGoneApply, KINDS }; +if (typeof module !== 'undefined') module.exports = root.ParamixSaves; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/src/six.js b/src/six.js new file mode 100644 index 0000000..4f245e4 --- /dev/null +++ b/src/six.js @@ -0,0 +1,1049 @@ +/* + * Paramix Studio: six fields on Tropical/Glacier. + * + * The Tropical/Glacier firmware has three field slots (Tropical, Glacier, Forest; + * byte 499 of the settings block). It already holds the characters of all six + * fields, only the field pictures of Land, Water and Sky are missing. This module + * - copies those pictures from the user's own Land, Water or Sky ROM into the + * archive (8 bit maps, colours reduced to 128 per field, identical tiles shared), + * - patches four places of the firmware so that a flag byte in the settings block + * (offset 0xF04) switches the three slots to Land, Water, Sky: backgrounds, + * child, teen and adult characters, + * - writes the helper code and its tables to flash 0x10F000 (source in six/src). + * The menu (feld.js) then offers six fields; a field of the second three is + * slot 0..2 plus the flag. Nothing of a Land ROM is shipped: everything comes from + * the ROM the user opens. + * + * Author: mameise + */ +(function (root) { +'use strict'; +const C = root.ParamixCore || (typeof require !== 'undefined' ? require('./core.js') : null); + +const SIX_OFF = 0x10F000, SIX_XIP = 0x100FE000, SIX_MAGIC = 0x31584953; +const FLAG_OFF = 0xF04; // set byte in the settings block +const XIP = (off) => 0x10000000 + off - 0x11000; +const SIX_VERSION = 7; +/* DNA per field (1.7.2, switch): the DNA history and the per slot values of the firmware follow the six + * fields. An add-on of the version 7 page (code from 0xC00), so a ROM with six fields gets it without the + * Land ROM. Option bit 3 in the header. */ +/* 1.7.4 SIX_FOOD (switch): food per field. Land, Water, Sky food counted for the young stage (the + * firmware took the Land, Water, Sky characters for its own fields). Part of the DNA part. */ +const SIX_FOOD = true; +const SIX_DNA = true, P_DNA = 0xC00, P_DNA_FN = 0xC40, DNA_CHILD = 7, DNA_FSET = 9, DNA_END = 0x1000; +// page layout (six/src/six.s) +const P_FM = 0x800, P_FM_FN = 0x830, P_PMAP = 0x1B0, P_BG = 0x1C0, P_CHILD = 0x1CC, P_FN = 0x1E0, T_BG = 0x200, T_CHILD = 0x340, T_CHILD_O = 0x348, T_SITES = 0x380, T_MORE = 0x500; +const FN_TAB = [0, 1, 5], FN_BG = 2, FN_CHILD = 3, FN_PMAP = 4; +// Region B (0xF00000, unused by the firmware): cells of the rain pictures (Tropical/Glacier). Header +// "SIXB", count, per picture: sprite id and 64 offsets into the data (0xFFFFFFFF = cell in the archive). +const B_OFF = 0xF00000, B_END = 0xFF0000, B_MAGIC = 0x42584953; // 1.6.13 test13: 0xFF0000 stays free for the rescue start (was 0x1000000) +// Tropical maps reduced to 128 colours to make room (look the same) +const TROP_MAPS = [[1118, 7], [1132, 7], [1146, 7]]; +const K_COLORS = 128; +/* + * The firmwares. bg: function that returns the background composites of a field (replaced by a + * jump), child: code that picks the child from a list in the code, sites: movw/movt pairs that + * load a per field table (offset in the firmware window, register, table, name of the + * alternative table). Offsets are relative to flash 0x11000. + */ +const KINDS = { + gen3: { id: 0, idPage: 0xD29000, ids: [5, 6], flag: 0x18000BE8 + 0xF00, slots: [0, 1, 2], + bg: { at: 0xAEAC, orig: '81b08df8', table: 0x10092E06, mode: 0 }, + child: { at: 0xFD62, orig: '40f61500adf8', back: 0xFD7C, sp: 0xC4, list: [2091, 2113, 2069] }, + sites: [ + [0xFED2, 1, 0x10091314, 'teen'], [0xFFBC, 1, 0x1009132C, 'adult'], + [0x3FBBC, 1, 0x100A012C, 'speed'], [0x3FDD2, 1, 0x100A012C, 'speed'], [0x3FEA0, 1, 0x100A012C, 'speed'], + [0x432AE, 1, 0x10095790, 'egg'], [0x4366C, 0, 0x10095790, 'egg'], [0x435C0, 1, 0x10093382, 'eggPic'], + [0x4307C, 1, 0x10095778, 'wagon'], + [0x560B6, 1, 0x1009472C, 'scene'], [0x56316, 1, 0x1009472C, 'scene'], [0x56624, 1, 0x1009472C, 'scene'], + [0x7FEA4, 0, 0x1009472C, 'scene'], [0x7FED2, 0, 0x1009472C, 'scene'], + // special adult per field: two halfwords per movw/movt (Tropical/Glacier: 4112, 4134, 4090) + [0x10060, 0, 0x0FFA0FFA, 'spec2'], [0x1006A, 0, 0x10261010, 'spec1'], + ], + // planet: calls of the edition-to-row function, the field byte, row per field slot, and the + // two planet stage tables (3 rows of 11 stages, and the same rows loaded one by one) + planet: { calls: [0x7C7A, 0x7C98, 0x7CB4, 0x575FA], fn: 0x1002B314, field: 0x18000BE8 + 0x1EF, rows: [0, 1, 2], + sites: [[0x7CC4, 2, 0x100A1020, 'plTab'], [0x57636, 1, 0x10094786, 'pl0'], [0x5768E, 1, 0x100947B2, 'pl1'], + [0x576E6, 1, 0x1009479C, 'pl2'], [0x5773E, 1, 0x10094786, 'pl0']] }, + // the game's field menu: menu object pointer, field byte, planet level, list builder call, + // preview loader calls, reads of the list (compare with the field, switch the field), + // immediates that move the index and count (old, new), offsets list/index/count/flag, entries + fm: { obj: 0x1801417C, field: 0x18000BE8 + 0x1EF, level: 0x18000BE8 + 0x84, build: [0x265E2, 0x100167D8], + prev: [0x100856D4, 0x414EC, 0x41818, 0x41B38], cmp: [0x41690, 0x41782, 0x4183A, 0x418EA], set: 0x416B8, read: '90f94c00', + imm: [[0x265EA, 0x50, 0x48], [0x41496, 0x4F, 0x53], [0x41618, 0x4F, 0x53]], off: [0x4C, 0x48, 0x53, 0x68], ent: [0, 1, 2, 0x80, 0x81, 0x82] }, + // DNA per field (1.7.2, helper page DNA part): settings block, offsets of the DNA count and the + // field byte, stash and marker (RAM offsets, free in the settings block), byte with one bit per + // slot, regions kept per slot (offset, length), DNA picture per field (Tropical, Glacier, Forest, + // Land, Water, Sky), and the firmware places: [XIP, original bytes, how, helper number or bytes] + dna: { base: 0x18000BE8, cnt: 0x131, field: 0x1EF, stash: 0xF0C, mark: 0xF0B, bits: 133, mask: 7, slots: 7, + regions: [[256, 6], [350, 6], [422, 72], [500, 12]], icons: [1184, 1185, 1180, 1165, 1166, 1167], + sites: [[0x10081C68, '80b590b0', 'bw', 0], [0x10081CEC, '80b590b0', 'bw', 1], [0x1000AE44, '81b08df8', 'bw', 2], + [0x1003BFB2, '0328', 'hex', '0628'], [0x1008211C, 'fff7a4fd', 'bl', 3], [0x10082124, '0228', 'hex', '0528'], + [0x10013BBE, '90f8ef01', 'bl', 4], [0x10072676, '90f8ef01', 'bl', 4], [0x10013C78, '91f8ef01', 'bl', 5], + [0x10013C3E, '91f9ef11', 'bl', 6], [0x10013F42, '91f9ef11', 'bl', 6], [0x10068B54, '28f018f981790ca830f81100', 'bl', 8]], + // food per field: history offset, first food kind per field 0..5, check of the kind, young stage branch + food: { hist: 0x13E, kinds: [12, 15, 9, 0, 3, 6], sites: [[0x1001027E, '0df055fd', 'bl', 10], [0x10081D70, '80b596b0', 'bw', 11]] } } }, + jade: { id: 1, idPage: 0xD49000, ids: [4], flag: 0x18000BA0 + 0xF00, slots: [1], + bg: { at: 0x966C, orig: '81b08df8', table: 0x1007F98C, mode: 1 }, + child: { at: 0xE1DA, orig: '40f61500adf8', back: 0xE1F4, sp: 0xBC, list: [2002, 2003, 2069] }, + sites: [ + [0xE3F2, 1, 0x1007DFC4, 'teen'], [0xE536, 1, 0x1007DFDC, 'adult'], + [0x3AA58, 1, 0x1008BCE8, 'speed'], [0x3AC6E, 1, 0x1008BCE8, 'speed'], [0x3AD3C, 1, 0x1008BCE8, 'speed'], + [0x3DE22, 1, 0x100820E8, 'egg'], [0x3DBF4, 1, 0x100820D0, 'wagon'], + [0x4F1FE, 1, 0x10081198, 'scene'], [0x4F45E, 1, 0x10081198, 'scene'], [0x4F76C, 1, 0x10081198, 'scene'], + [0x7164C, 0, 0x10081198, 'scene'], [0x7167A, 0, 0x10081198, 'scene'], + [0xE5E2, 0, 0x0FE30FE2, 'spec1'], + ], + planet: { calls: [0x670A, 0x6728, 0x6744, 0x50742], fn: 0x10026E10, field: 0x18000BA0 + 0x1B7, rows: [0xFF, 1, 0xFF], + sites: [[0x6754, 2, 0x1008CBD0, 'plTab'], [0x5077E, 1, 0x100811DA, 'pl0'], [0x507D6, 1, 0x10081206, 'pl1'], + [0x5082E, 1, 0x100811F0, 'pl2'], [0x50886, 1, 0x100811DA, 'pl0']] }, + fm: { obj: 0x180140B8, field: 0x18000BA0 + 0x1B7, level: 0x18000BA0 + 0x78, build: [0x2262C, 0x10014954], + prev: [0x1007564C, 0x3C2E0, 0x3C5C2], cmp: [0x3C470, 0x3C53E, 0x3C5EA, 0x3C69A], set: 0x3C498, read: '90f94a00', + imm: [[0x22634, 0x4E, 0x48], [0x3C29E, 0x4D, 0x4F], [0x3C3F8, 0x4D, 0x4F]], off: [0x4A, 0x48, 0x4F, 0x64], ent: [0, 1, 2, 0x81] }, + // food per field without the DNA part (option bit 64): settings block, field byte, switched slots, history, + // first food kind per field (Land, Water, Forest, -, Sky in the Water slot, -), check and young stage branch + food: { ram: 0x18000BA0, field: 0x1B7, slots: 2, hist: 0x132, kinds: [0, 3, 9, 0, 6, 0], sites: [[0x1000E7F6, '0cf035f9', 'bl', 10], [0x10072750, '80b590b0', 'bw', 11]] } }, +}; +/* 1.7.3 test23 SIX_HUNT: the egg hunt gives 8 entries per field (picture, item, found bit; two groups of 4, one picked at + * random). It was left on the slot's own row, so Sky in the Forest slot gave Jade Forest ingredients. The rows of Land, + * Water and Sky as in their firmware (items and found bits), the pictures from this ROM's item table. Jade Forest: Sky in + * the Water slot keeps the Water slot's found bits. Option bit 4 in the header. */ +const SIX_HUNT = true; +const HUNT_ROWS = [ + [[5003, 0], [5004, 1], [5007, 4], [5008, 5], [5005, 2], [5006, 3], [5007, 4], [5008, 5]], // Land + [[5009, 6], [5010, 7], [5013, 10], [5014, 11], [5011, 8], [5012, 9], [5013, 10], [5014, 11]], // Water + [[5015, 12], [5016, 13], [5017, 14], [5018, 15], [5019, 16], [5020, 17], [5017, 14], [5018, 15]], // Sky +]; +const HUNT_SITES = { gen3: [[0x4336E, 1, 0x100A0600, 'hunt'], [0x433AC, 0, 0x100A0600, 'hunt']], + jade: [[0x3DEE2, 1, 0x1008C1BC, 'hunt'], [0x3DF20, 0, 0x1008C1BC, 'hunt']] }; +/* 1.7.3 test24 SIX_COOK: the kitchen's recipe table (12 pairs dish, ingredient; 4 per field, all three fields of the + * firmware) also follows the set byte: Land, Water and Sky recipes as in their firmware (Jade Forest: Sky in place of + * Water). Option bit 5 in the header. */ +const SIX_COOK = true; +const COOK_ROWS = [[5021, 5004, 5022, 5005, 5023, 5006, 5024, 5008], [5025, 5009, 5026, 5010, 5027, 5012, 5028, 5014], [5029, 5016, 5030, 5018, 5031, 5019, 5032, 5020]]; +const COOK_SITES = { gen3: [0x30A72, 0x4B930, 0x4B9A0, 0x4BAB4, 0x4BB7A, 0x6F202].map((o) => [o, 0, 0x10091FBC, 'cook']), + jade: [0x2C426, 0x45B94, 0x45C04, 0x45D18, 0x45DDE, 0x635CA].map((o) => [o, 0, 0x1007EB5C, 'cook']) }; +const T_COOK = 0x740; // 24 halfwords up to the egg hunt table +/* the add-on tables of six fields: name, sites, place in the helper page, option bit, table for this ROM */ +const EXTRAS = [ + { name: 'hunt', on: () => SIX_HUNT, sites: HUNT_SITES, at: 0x770, bit: 16, + tab: (rom, kind) => kind === 'jade' ? rows(rom, HUNT_SITES.jade[0][2], 24, 3, { 1: huntRow(rom, 2, 6) }) : [0, 1, 2].flatMap((r) => huntRow(rom, r)) }, + { name: 'cook', on: () => SIX_COOK, sites: COOK_SITES, at: T_COOK, bit: 32, + tab: (rom, kind) => kind === 'jade' ? rows(rom, COOK_SITES.jade[0][2], 8, 3, { 1: COOK_ROWS[2] }) : [].concat(...COOK_ROWS) }, +]; +/** SIX_HUNT, SIX_COOK for a ROM that has six fields already (no Land ROM needed): table, site entries, jumps */ +function sixHunt(rom) { + let out = rom; + for (const X of EXTRAS) out = extraAdd(out, X); + return out; +} +function extraAdd(rom, X) { + const info = sixInfo(rom); + if (!X.on() || !info || info.version < 7 || (u32(rom, SIX_OFF + 32) & X.bit) || !extraCan(rom, info.kind, X)) return rom; + const K = KINDS[info.kind], f = (o) => 0x11000 + o, out = new Uint8Array(rom), P = SIX_OFF, S = X.sites[info.kind], tab = X.tab(rom, info.kind); + for (let i = P + X.at; i < P + X.at + 2 * tab.length; i++) if (out[i] !== 0xFF && out[i] !== 0) return rom; // free (the program leaves its tables empty) + let n = 0; while (u32(out, P + T_SITES + 12 * n) !== 0) { n++; if (12 * (n + S.length + 1) > T_MORE - T_SITES) return rom; } + tab.forEach((x, i) => w16(out, P + X.at + 2 * i, x)); + const fn = (k) => u32(out, P + P_FN + 4 * k) & ~1; + S.forEach(([o, r, t], i) => { + const e = P + T_SITES + 12 * (n + i); w32(out, e, (XIP(f(o)) + 4) | 1); w32(out, e + 4, t); w32(out, e + 8, SIX_XIP + X.at); + const b = new Uint8Array(8); b.set(branch(XIP(f(o)), fn(FN_TAB[r]), true)); w16(b, 4, 0xBF00); w16(b, 6, 0xBF00); out.set(b, f(o)); + }); + w32(out, P + T_SITES + 12 * (n + S.length), 0); + w32(out, P + 32, u32(out, P + 32) | X.bit); + return out; +} +function extraCan(rom, kind, X) { const f = (o) => 0x11000 + o; return X.sites[kind].every(([o, r, t]) => hex(rom, f(o), 8) === hex(movPairBytes(r, t), 0, 8)); } +function huntCan(rom, kind) { return extraCan(rom, kind, EXTRAS[0]); } +function huntRow(rom, r, bitBase) { + const Fd = root.ParamixFeld || (typeof require !== 'undefined' ? require('./feld.js') : null); + const cat = Fd ? Fd.itemCatalog(rom) : [], pic = new Map(cat.map((x) => [x.id, x.pic])); + const out = []; + for (const [id, bit] of HUNT_ROWS[r]) { if (!pic.has(id)) throw new Error('item ' + id + ' missing'); out.push(pic.get(id), id, bitBase === undefined ? bit : bitBase + (bit % 6)); } + return out; +} +// v1 and v2 (1.2.0, 1.2.1) of Tropical/Glacier jumped from these places too +const OLD_PATCH = [[0x20ED2, '41f21431c1f20901'], [0x20FBC, '41f22c31c1f20901']]; +// Land firmware: background table, adult table and a few code places (to recognise it) +const LAND_BG = 0x1007BAA8, LAND_ADULT = 0x10079AA4, LAND_SPEED = 0x10086918, LAND_PLANET = 0x100877EC; +// planet stages of Sky (Land, Water, Sky ROMs: third row of LAND_PLANET) +const SKY_PLANET = [2, 5, 5, 5, 8, 8, 9, 9, 9, 9, 10]; +const LAND_BG_AT = 0x11000 + 0x158F8, LAND_ADULT_AT = 0x11000 + 0xE2D0; +const LAND_FP = [[0x11000 + 0x38AA6, '46f61811c1f20801'], [0x11000 + 0x4D316, '01f65301']]; +/* + * Land, Water, Sky scripts per table column (Land numbers, + field): found through Jade Forest, + * whose tables have the same layout as Tropical's and whose scripts match Land's one to one. + * scene: 5 columns, wagon: 2 columns (the other two stay), egg: field eggs. + */ +const LAND_SCENE = [0x853, 1558, 1564, 1561, 1567], LAND_WAGON = [1464, 1467], LAND_EGG = 180; +// Jade Forest keeps the Sky pictures and scripts itself: Sky values in Jade's own numbers +const JADE_SKY = { bg: [773, 774, 775, 775, 776, 777, 777, 778, 779, 779, 780, 781, 781, 780, 781, 781], + speed: [1371, 1372, 1373], egg: [183], scene: [2273, 1670, 1676, 1673, 1679], wagon: [1576, 1579, 1580, 1581], + teen: [3013, 3014, 3015, 3016], child: [2002, 2004, 2069], + adult: [4050, 4051, 4052, 4053, 4060, 4059, 4058, 4061, 4054, 4055, 4056, 4057, 4062, 4063, 4064, 4065] }; +// Script ids of op 15 (probably sounds) that moved between the editions (Land -> Tropical) +const OP15 = { 24: 26, 25: 27, 26: 28, 27: 29, 28: 30, 29: 31, 30: 32, 31: 33, 32: 34, 33: 35, 34: 37, 35: 38, 36: 39, 37: 40, 38: 41, 39: 42, 40: 43, 41: 44, 42: 45, 43: 46, 44: 47, 45: 48 }; + +const u16 = (b, o) => b[o] | (b[o + 1] << 8); +const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; } +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } +const hex = (b, o, n) => Array.from(b.subarray(o, o + n), (x) => x.toString(16).padStart(2, '0')).join(''); +function b64(s) { + if (typeof atob === 'function') { const t = atob(s); const o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; } + return new Uint8Array(Buffer.from(s, 'base64')); +} +function concat(parts) { let n = 0; for (const p of parts) n += p.length; const o = new Uint8Array(n); let k = 0; for (const p of parts) { o.set(p, k); k += p.length; } return o; } + +// ------------------------------------------------------------ Thumb-2 +function movwDec(b, o) { + const h1 = u16(b, o), h2 = u16(b, o + 2); + if ((h1 & 0xFBF0) !== 0xF240 && (h1 & 0xFBF0) !== 0xF2C0) return -1; + return ((h1 & 15) << 12) | (((h1 >> 10) & 1) << 11) | (((h2 >> 12) & 7) << 8) | (h2 & 255); +} +function movEnc(rd, imm, top) { + const o = new Uint8Array(4); + w16(o, 0, (top ? 0xF2C0 : 0xF240) | (((imm >> 11) & 1) << 10) | ((imm >> 12) & 15)); + w16(o, 2, (((imm >> 8) & 7) << 12) | (rd << 8) | (imm & 255)); + return o; +} +function movPair(b, o) { const lo = movwDec(b, o), hi = movwDec(b, o + 4); return lo < 0 || hi < 0 ? -1 : ((hi << 16) | lo) >>> 0; } +function branch(src, dst, link) { + const off = dst - (src + 4); + const S = (off >>> 24) & 1, I1 = (off >>> 23) & 1, I2 = (off >>> 22) & 1; + const h1 = 0xF000 | (S << 10) | ((off >>> 12) & 0x3FF); + const h2 = (link ? 0xD000 : 0x9000) | (((~I1 ^ S) & 1) << 13) | (((~I2 ^ S) & 1) << 11) | ((off >>> 1) & 0x7FF); + const o = new Uint8Array(4); w16(o, 0, h1); w16(o, 2, h2); return o; +} + +// ------------------------------------------------------------ data pack +// Header: u32 word offsets (in 16 bit units) of 22 tables, then the end. +function dpSplit(d) { + const n = u32(d, 0) * 2 / 4 - 1, offs = []; + for (let i = 0; i <= n; i++) offs.push(u32(d, 4 * i) * 2); + const t = []; for (let i = 0; i < n; i++) t.push(d.slice(offs[i], offs[i + 1])); + return t; +} +function dpJoin(tables) { + const n = tables.length, hdr = 4 * (n + 1), h = new Uint8Array(hdr); + let pos = hdr; + tables.forEach((t, i) => { w32(h, 4 * i, pos / 2); pos += t.length; }); + w32(h, 4 * n, pos / 2); + return concat([h, ...tables]); +} +const words = (t) => { const a = []; for (let i = 0; i + 1 < t.length; i += 2) a.push(u16(t, i)); return a; }; +const toBytes = (a) => { const b = new Uint8Array(2 * a.length); a.forEach((v, i) => w16(b, 2 * i, v)); return b; }; +// composites: table 4 = start of each (16 bit units into table 5) +function comp(tabs, i) { const ix = words(tabs[4]), d = words(tabs[5]); return d.slice(ix[i], i + 1 < ix.length ? ix[i + 1] : d.length); } + +// ------------------------------------------------------------ maps +function rgb(v) { return [((v >> 11) & 31) * 255 / 31, ((v >> 5) & 63) * 255 / 63, (v & 31) * 255 / 31]; } +function to565(c) { return (Math.round(c[0] * 31 / 255) << 11) | (Math.round(c[1] * 63 / 255) << 5) | Math.round(c[2] * 31 / 255); } +function mapCells(e) { + const h = C.spriteHeader(e); + if (h.bpp !== 3 || !(h.flags & 0x20) || h.numSprites !== 64) throw new Error('unexpected map picture'); + const cells = []; + for (let s = 0; s < h.numSprites; s++) { + let off = u32(e, h.pixOffset + 8 * s); const ln = u32(e, h.pixOffset + 8 * s + 4); const unc = off & 0x80000000; off &= 0x7fffffff; + let d = e.slice(h.pixOffset + off, h.pixOffset + off + ln); + if (h.flags & 0x80) d = d.map((x) => x ^ 0x53); + if (!unc) d = C.rleDecode(d, false); + cells.push(d); + } + const pal = []; for (let k = 0; k < 256; k++) pal.push(rgb(u16(e, h.palOffset + 2 * k))); + return { h, cells, pal }; +} +/* Reduce the colours of a group of 8 bit maps that share their pixel indices (seasons + * of one field): k-means over the indices, each picture keeps its own colours per cluster. */ +function reduce(group, K) { + const cnt = new Float64Array(256); + for (const s of group) for (const c of s.cells) for (const v of c) cnt[v]++; + const used = []; for (let k = 0; k < 256; k++) if (cnt[k]) used.push(k); + const X = used.map((k) => group.flatMap((s) => s.pal[k])), w = used.map((k) => cnt[k]), D = X[0].length; + const d2 = (a, b) => { let s = 0; for (let i = 0; i < D; i++) s += (a[i] - b[i]) ** 2; return s; }; + let cent; + if (used.length <= K) cent = X.map((x) => x.slice()); + else { + cent = [X[w.indexOf(Math.max(...w))].slice()]; + while (cent.length < K) { + let best = -1, bi = 0; + for (let i = 0; i < X.length; i++) { let d = 1e18; for (const c of cent) { const e = d2(X[i], c); if (e < d) d = e; } d *= Math.sqrt(w[i]); if (d > best) { best = d; bi = i; } } + cent.push(X[bi].slice()); + } + } + const map = new Array(X.length).fill(0); + for (let it = 0; it < 20; it++) { + for (let i = 0; i < X.length; i++) { let d = 1e18, b = 0; cent.forEach((c, k) => { const e = d2(X[i], c); if (e < d) { d = e; b = k; } }); map[i] = b; } + const s = cent.map(() => ({ v: new Array(D).fill(0), w: 0 })); + for (let i = 0; i < X.length; i++) { const t = s[map[i]]; for (let j = 0; j < D; j++) t.v[j] += X[i][j] * w[i]; t.w += w[i]; } + cent = s.map((t, k) => (t.w ? t.v.map((x) => x / t.w) : cent[k])); + } + const remap = new Uint8Array(256); used.forEach((k, i) => { remap[k] = map[i]; }); + return { remap, pals: group.map((_, g) => cent.map((c) => to565(c.slice(3 * g, 3 * g + 3)))) }; +} +const HEAD = 24 + 512 + 8 * 64; // header, palette, cell table of one 8x8 map +/* Pack entries for a group: all headers first, then the cell data, shared between the + * pictures where it is the same (offsets always point forward). */ +function packGroup(group, K, ext) { + const { remap, pals } = reduce(group, K); + ext = ext || []; + const enc = group.map((s) => s.cells.map((c) => C.rleEncode(c.map((v) => remap[v])).map((x) => x ^ 0x53))); + // in the pack: every cell a picture inside the pack uses; outside (region B): cells only rain pictures use + const place = (into, list, r) => { const key = r.join(','); if (into.seen.has(key)) return into.seen.get(key); + const pad = (4 - into.pos % 4) % 4; if (pad) { list.push(new Uint8Array(pad)); into.pos += pad; } + const t = [into.pos, r.length]; into.seen.set(key, t); list.push(r); into.pos += r.length; return t; }; + const A = { seen: new Map(), pos: 0 }, Bx = { seen: new Map(), pos: 0 }, dA = [], dB = []; + group.forEach((_, j) => { if (!ext[j]) enc[j].forEach((r) => place(A, dA, r)); }); + const tables = group.map((_, j) => enc[j].map((r) => { + const key = r.join(','); + if (A.seen.has(key)) return { a: A.seen.get(key) }; + return { b: place(Bx, dB, r) }; + })); + const n = group.length, blob = concat(dA), out = [], outside = []; + group.forEach((s, j) => { + const e = new Uint8Array(HEAD + (j === n - 1 ? blob.length : 0)); + e.set(s.h.raw.subarray(0, 24)); + w32(e, 0, HEAD * (n - j) + blob.length); e[4] = 0xA3; e[5] = 3; e[15] = 1; w16(e, 18, 24); w16(e, 20, 536); + pals[j].forEach((v, k) => w16(e, 24 + 2 * k, v)); + const rel = []; + tables[j].forEach((t, k) => { + if (t.a) { w32(e, 536 + 8 * k, HEAD * (n - j) - 536 + t.a[0]); w32(e, 536 + 8 * k + 4, t.a[1]); rel.push(-1); } + else { w32(e, 536 + 8 * k, 0); w32(e, 536 + 8 * k + 4, t.b[1]); rel.push(t.b[0]); } + }); + if (j === n - 1) e.set(blob, HEAD); + out.push(e); outside.push(rel.some((x) => x >= 0) ? rel : null); + }); + return Object.assign(out, { outside, bdata: concat(dB) }); +} +/* One map on its own, colours reduced (for the Tropical maps). */ +function reduceOne(e, K) { + const m = mapCells(e); m.h.raw = e; + return packGroup([m], K)[0]; +} + +// ------------------------------------------------------------ scripts (animations) +// Table 13 = start of each script (16 bit, in 4 byte units) in table 14. A script: one word, +// then commands: low byte = command, high byte = which parameters follow (one bit each). +// Command 16 starts another script (first parameter), command 1 shows a sprite, command 15 +// refers to a numbered entry that moved between the editions (OP15). +function scripts(tabs) { + const ix = words(tabs[13]), w = words(tabs[14]); + return { ix, w, get: (a) => w.slice(2 * ix[a], a + 1 < ix.length ? 2 * ix[a + 1] : w.length) }; +} +function parseScript(s) { + const ops = []; let i = 1; + while (i < s.length) { + const op = s[i]; + if (op === 0xFCBD && i === s.length - 1) { i++; break; } + let n = 0; for (let m = op >> 8; m; m >>= 1) n += m & 1; + ops.push({ op: op & 255, mask: op >> 8, p: s.slice(i + 1, i + 1 + n) }); i += 1 + n; + } + return ops; +} +/** Copies scripts (with the scripts and sprites they use) from one archive into another. */ +function importer(src, dst, entries) { + const S = scripts(src.tabs), D = scripts(dst.tabs); + const anims = new Map(), sprites = new Map(), have = new Map(), made = []; + dst.entries.forEach((e, i) => { const k = e.length + ':' + C.crc32(e); if (!have.has(k)) have.set(k, i); }); + const sprite = (i) => { + if (sprites.has(i)) return sprites.get(i); + const e = src.entries[i], k = e.length + ':' + C.crc32(e); + let id = have.get(k); + if (id === undefined) { id = entries.length; entries.push(e); have.set(k, id); } + sprites.set(i, id); return id; + }; + const anim = (a) => { + if (anims.has(a)) return anims.get(a); + const id = D.ix.length + made.length; anims.set(a, id); made.push(null); + const s = S.get(a), out = [s[0]]; + for (const o of parseScript(s)) { + const p = o.p.slice(); + if (o.mask & 0x80 && p.length) { + if (o.op === 16) p[0] = anim(p[0]); + else if (o.op === 1) p[0] = sprite(p[0]); + else if (o.op === 15 && OP15[p[0]]) p[0] = OP15[p[0]]; + } + out.push(o.op | (o.mask << 8), ...p); + } + if (out.length & 1) out.push(0xFCBD); + made[id - D.ix.length] = out; + return id; + }; + const done = () => { + const ix = D.ix.slice(), w = D.w.slice(); + for (const out of made) { if (w.length / 2 > 0xFFFF) throw new Error('script table full'); ix.push(w.length / 2); w.push(...out); } + dst.tabs[13] = toBytes(ix); dst.tabs[14] = toBytes(w); + }; + return { anim, sprite, done }; +} + +// ------------------------------------------------------------ lab games per start field (1.7.2, version 7) +/* + * Land, Water and Sky have other lab games than Tropical and Glacier (Matching Meals, Catching Poop and + * Cleaning Dust in place of Fish Matching, Fruit Gathering and Curling); Jade Forest has Matching Meals and + * Catching Poop next to Cloudy Coin. The game code is the same in all firmwares, only the numbers of the + * pictures differ. With the family byte (0xF05, written by the Paramix menu when it starts a field) the + * firmware places below take the Land numbers (translated into this ROM, missing pictures are copied from the + * user's Land, Water or Sky ROM). Sites: XIP address, kind (w: movw/mov.w, a: addw/add.w with rn), rd, rn, + * original value, resource (c composite, s script, p picture), Land number, families (1 Land, 2 Jade, 3 both). + * Tables (movw/movt pairs): XIP address of the pair, register, table name, families, flags (1: in every scene, + * for the PLAY list of the care menu, which runs in the home scene). + */ +const SIX_GAMES = true; +const G_SCENES = [44, 45, 46, 47, 48, 49, 50, 51, 92, 95, 96, 97]; // lab card list (44, 45..51 back from game k), result, games +const G_SEQ = [[0, 1, 2, 3, 6, 5], [0, 1, 2, 3, 4, 5]]; +const G_NAV = [[0x1002FFE4, 1], [0x1003003A, 2]]; // ldrh.w r1,[r2,#126] -> six_cnext / six_cprev +const G_NAV_ORIG = 'b2f87e10'; +const G_SITES = [ + ['0x10050b1e','w','r0',"",1225,'c',997,3], + ['0x10050b46','w','r1',"",2626,'s',1967,3], + ['0x10070760','w','r2',"",1227,'c',999,3], + ['0x10070778','w','r0',"",1228,'c',1001,3], + ['0x1007079a','w','r0',"",1232,'c',1005,3], + ['0x100707ba','w','r0',"",1236,'c',1009,3], + ['0x10071054','w','r0',"",1253,'c',1026,3], + ['0x1007107a','w','r1',"",2645,'s',2001,3], + ['0x10071092','w','r0',"",1250,'c',1023,3], + ['0x100710b8','w','r1',"",2636,'s',1985,3], + ['0x100710d0','w','r0',"",1251,'c',1024,3], + ['0x100710f6','w','r1',"",2643,'s',1993,3], + ['0x10071110','w','r0',"",1252,'c',1025,3], + ['0x10071136','w','r1',"",2644,'s',1997,3], + ['0x100711fc','w','r2',"",1227,'c',999,3], + ['0x1007122a','w','r0',"",1228,'c',1001,3], + ['0x1007124c','w','r0',"",1232,'c',1005,3], + ['0x1007126c','w','r0',"",1236,'c',1009,3], + ['0x100713aa','a','r2','r2',1231,'c',1004,3], + ['0x100713e8','a','r2','r2',1231,'c',1004,3], + ['0x10071418','a','r1','r1',2167,'p',1387,3], + ['0x10069ef4','a','r1','r1',1231,'c',1004,3], + ['0x10069f32','a','r1','r1',1231,'c',1004,3], + ['0x10069f68','a','r1','r1',2167,'p',1387,3], + ['0x10051e6e','w','r0',"",1285,'c',1060,3], + ['0x10051e94','w','r1',"",2662,'s',2025,3], + ['0x10051eac','w','r0',"",1286,'c',1061,3], + ['0x10051ed2','w','r1',"",2667,'s',2027,3], + ['0x10051eea','w','r0',"",1287,'c',1062,3], + ['0x10051f10','w','r1',"",2669,'s',2030,3], + ['0x10051f2a','w','r0',"",1288,'c',1063,3], + ['0x10051f50','w','r1',"",2671,'s',2033,3], + ['0x100843a8','w','r2',"",1256,'c',1029,3], + ['0x100843c4','w','r2',"",1257,'c',1030,3], + ['0x10084368','w','r2',"",1262,'c',1035,3], + ['0x10084304','w','r2',"",1271,'c',1044,3], + ['0x1007d08a','w','r2',"",1263,'c',1036,3], + ['0x1007d152','w','r2',"",1262,'c',1035,3], + ['0x1008f4f4','w','r0',"",1275,'c',1048,3], + ['0x1006aa1a','w','r0',"",1271,'c',1044,3], + ['0x1006aa34','a','r0','r0',1271,'c',1044,3], + ['0x100842ca','w','r2',"",1279,'c',1054,3], + ['0x1008f768','w','r0',"",1265,'c',1038,3], + ['0x10021758','w','r2',"",1291,'c',1066,1], + ['0x1002176e','w','r2',"",1298,'c',1072,1], + ['0x1005219e','w','r1',"",2675,'s',2034,1], + ['0x1005236a','w','r0',"",1294,'c',1069,1], + ['0x100528f8','w','r0',"",1294,'c',1069,1], + ['0x1006fc84','a','r1','r1',1301,'c',1075,1], + ['0x1005fd98','w','r0',"",1296,'c',1071,1], + ['0x1005fda4','w','r0',"",1298,'c',1072,1], + ['0x100788e8','w','r0',"",1296,'c',1071,1], + ['0x100788f4','w','r0',"",1298,'c',1072,1], + ['0x10051696','w','r0',"",1254,'c',1027,3], + ['0x1005184c','w','r0',"",1284,'c',1059,3], +]; +const G_TABS = [ + ['0x100410a4','r3','play',1,1], + ['0x10041200','r0','play',1,1], + ['0x1005168a','r0','intro03',3], + ['0x10051840','r0','intro03',3], + ['0x10083938','r1','avatar',3], + ['0x1007d0a6','r0','avatar2',3], + ['0x1007d16e','r0','avatar2',3], + ['0x1008f782','r0','avatar2',3], + ['0x100301de','r1','cardPic',3], + ['0x100303d8','r1','cardPic',3], + ['0x100304aa','r1','cardPic',3], + ['0x100306a6','r1','cardPic',3], + ['0x100478c4','r1','cardPic',3], + ['0x10047b8c','r1','cardPic',3], + ['0x100301fc','r0','cardName',3], + ['0x100303f6','r0','cardName',3], + ['0x100304c8','r0','cardName',3], + ['0x100306c4','r0','cardName',3], + ['0x100478e2','r0','cardName',3], + ['0x10047baa','r0','cardName',3], + ['0x1008f89c','r0','bg03',3], + ['0x1008f8d0','r0','bg03',3], + ['0x1008f906','r0','bg03',3], + ['0x1008f934','r0','bg03',3], + ['0x1008f96a','r0','bg03',3], + ['0x1008f9ee','r0','bg03',3], + ['0x1008fa24','r0','bg03',3], + ['0x1008fa52','r0','bg03',3], + ['0x1008fa88','r0','bg03',3], + ['0x1008fafa','r0','bg03',3], + ['0x100300b0','r0','cardLevel',3], + ['0x10047e1e','r0','cardLevel',3], +]; +const G_TABLES = { + avatar: { addr: 0x100A008A, n: 23, w: 2, f1: [[0,'s',1984],[1,'c',1022],[2,'s',1981],[3,'c',1019],[4,'s',1982],[5,'c',1020],[6,'s',1983],[7,'c',1021],[20,'c',1038],[21,'c',1039],[22,'c',1040]], f2: [[0,'s',1984],[1,'c',1022],[2,'s',1981],[3,'c',1019],[4,'s',1982],[5,'c',1020],[6,'s',1983],[7,'c',1021],[20,'c',1038],[21,'c',1039],[22,'c',1040]] }, + avatar2: { addr: 0x100A00B2, n: 3, w: 2, f1: [[0,'c',1038],[1,'c',1039],[2,'c',1040]], f2: [[0,'c',1038],[1,'c',1039],[2,'c',1040]] }, + cardPic: { addr: 0x10093544, n: 7, w: 4, f1: [[0,'p',1335],[1,'p',1336],[2,'p',1337],[3,'p',1338],[6,'p',1339],[5,'p',1340]], f2: [[0,'p',1335],[1,'p',1336],[2,'p',1337],[3,'p',1338],[5,'p',1340]] }, + cardName: { addr: 0x10093560, n: 8, w: 2, f1: [[0,'=',803],[1,'=',804],[2,'=',805],[3,'=',806],[6,'=',807],[5,'=',808]], f2: [[0,'=',803],[1,'=',804],[2,'=',805],[3,'=',806],[5,'=',808]] }, + cardLevel: { addr: 0x10093976, n: 7, w: 2, f1: [[0,'=',1],[1,'=',4],[2,'=',4],[3,'=',4],[6,'=',1],[5,'=',1]], f2: [[0,'=',1],[1,'=',4],[2,'=',4],[3,'=',4],[5,'=',1]] }, + intro03: { addr: 0x10094368, n: 2, w: 2, f1: [[0,'s',2005],[1,'s',2015]], f2: [[0,'s',2005],[1,'s',2015]] }, + bg03: { addr: 0x10091CC4, n: 5, w: 2, f1: [[0,'p',1402],[1,'p',1402],[2,'p',1402],[3,'p',1402],[4,'p',1402]], f2: [[0,'p',1402],[1,'p',1402],[2,'p',1402],[3,'p',1402],[4,'p',1402]] }, + play: { addr: 0x10094140, n: 24, w: 2, f1: [[0,'=',809],[2,'=',101],[12,'=',811],[14,'=',103],[18,'=',812],[20,'=',104]] }, +}; +const P_GM = 0x980, P_GM_FN = 0x9B0; + +/* movw / mov.w / addw / add.w with an immediate: kind w or a, rd, rn, value */ +function immDec(b, o) { + const h1 = u16(b, o), h2 = u16(b, o + 2), i12 = (((h1 >> 10) & 1) << 11) | (((h2 >> 12) & 7) << 8) | (h2 & 255), rd = (h2 >> 8) & 15, rn = h1 & 15; + if (h2 & 0x8000) return null; + const expand = (v) => { const x = v & 255; if ((v >> 10) === 0) return [x, (x << 16) | x, ((x << 24) | (x << 8)) >>> 0, (x * 0x01010101) >>> 0][(v >> 8) & 3]; + const u = 0x80 | (v & 0x7F), r = v >> 7; return ((u >>> r) | (u << (32 - r))) >>> 0; }; + if ((h1 & 0xFBF0) === 0xF240) return { kind: 'w', rd, imm: ((h1 & 15) << 12) | i12 }; + if ((h1 & 0xFBFF) === 0xF04F) return { kind: 'w', rd, imm: expand(i12) }; + if ((h1 & 0xFBF0) === 0xF200) return { kind: 'a', rd, rn, imm: i12 }; + if ((h1 & 0xFBF0) === 0xF100) return { kind: 'a', rd, rn, imm: expand(i12) }; + return null; +} +/** Finds Land resources in this ROM (same content) or copies them over. */ +function translator(L, tt, entries) { + const lix = words(L.tabs[4]), lcw = words(L.tabs[5]), lsx = words(L.tabs[13]), lsw = words(L.tabs[14]); + const tix = words(tt[4]), tcw = words(tt[5]), tsx = words(tt[13]), tsw = words(tt[14]); + const n0 = { c: tix.length, s: tsx.length }; + const lComp = (i) => lcw.slice(lix[i], i + 1 < lix.length ? lix[i + 1] : lcw.length); + const tComp = (i) => tcw.slice(tix[i], i + 1 < tix.length ? tix[i + 1] : tcw.length); + const lScr = (a) => lsw.slice(2 * lsx[a], a + 1 < lsx.length ? 2 * lsx[a + 1] : lsw.length); + const tScr = (a) => tsw.slice(2 * tsx[a], a + 1 < tsx.length ? 2 * tsx[a + 1] : tsw.length); + const key = (e) => e.length + ':' + C.crc32(e); + const tSpr = new Map(); entries.forEach((e, i) => { const k = key(e); if (!tSpr.has(k)) tSpr.set(k, i); }); + const tScrM = new Map(); for (let a = 0; a < n0.s; a++) { const k = tScr(a).join(','); if (!tScrM.has(k)) tScrM.set(k, a); } + const tCompM = new Map(); for (let i = 0; i < n0.c; i++) { const k = tComp(i).join(','); if (!tCompM.has(k)) tCompM.set(k, i); } + const shape = (s) => parseScript(s).map((o) => o.op + ':' + o.mask).join(','); + const fSpr = new Map(), fScr = new Map(), fComp = new Map(); + const findSprite = (i) => { if (!fSpr.has(i)) { const j = i < L.entries.length ? tSpr.get(key(L.entries[i])) : undefined; fSpr.set(i, j === undefined ? null : j); } return fSpr.get(i); }; + const mapScript = (s, sub, spr) => { + const out = [s[0]]; + for (const o of parseScript(s)) { + const p = o.p.slice(); + if (o.mask & 0x80 && p.length) { + if (o.op === 16) { const r = sub(p[0]); if (r === null) return null; p[0] = r; } + else if (o.op === 1) { const r = spr(p[0]); if (r === null) return null; p[0] = r; } + } + out.push(o.op | (o.mask << 8), ...p); + } + if (out.length & 1) out.push(0xFCBD); + return out; + }; + const findScript = (a, d = 0) => { + if (fScr.has(a)) return fScr.get(a); + fScr.set(a, null); + if (a >= lsx.length || d > 12) return null; + const out = mapScript(lScr(a), (x) => findScript(x, d + 1), findSprite); + const r = out && tScrM.has(out.join(',')) ? tScrM.get(out.join(',')) : null; + fScr.set(a, r); return r; + }; + const findComp = (i) => { + if (fComp.has(i)) return fComp.get(i); + let r = null; + if (i < lix.length) { + const w = lComp(i).slice(), t = w[0] >> 12; let ok = true; + if (t === 1 && w.length > 3) { const x = findSprite(w[3]); if (x === null) ok = false; else w[3] = x; } + else if (t === 5 && w.length > 3) { const x = findScript(w[3]); if (x === null) ok = false; else w[3] = x; } + if (ok && tCompM.has(w.join(','))) r = tCompM.get(w.join(',')); + } + fComp.set(i, r); return r; + }; + // the same block of Land numbers sits elsewhere in this ROM: offset of the nearest neighbour found + const near = (find, id) => { for (let d = 1; d < 40; d++) for (const k of [id - d, id + d]) { if (k < 0) continue; const r = find(k); if (r !== null) return r - k; } return null; }; + const looseScript = (a) => { + const r = findScript(a); if (r !== null) return r; + const off = near(findScript, a); + return off !== null && a + off >= 0 && a + off < n0.s && a < lsx.length && shape(tScr(a + off)) === shape(lScr(a)) ? a + off : null; + }; + const looseComp = (i) => { + const r = findComp(i); if (r !== null) return r; + const off = near(findComp, i); if (off === null || i + off >= n0.c || i >= lix.length) return null; + const w = lComp(i), g = tComp(i + off); + if (g.length !== w.length || g[0] !== w[0] || g[1] !== w[1] || g[2] !== w[2]) return null; + if ((w[0] >> 12) === 5 && shape(tScr(g[3])) !== shape(lScr(w[3]))) return null; + return i + off; + }; + const gSpr = new Map(), gScr = new Map(), gComp = new Map(); + const sprite = (i) => { + if (gSpr.has(i)) return gSpr.get(i); + let j = findSprite(i); if (j === null) { j = entries.length; entries.push(L.entries[i]); tSpr.set(key(L.entries[i]), j); } + gSpr.set(i, j); return j; + }; + const script = (a) => { + if (gScr.has(a)) return gScr.get(a); + let j = looseScript(a); if (j !== null) { gScr.set(a, j); return j; } + j = tsx.length; gScr.set(a, j); tsx.push(tsw.length / 2); tsw.push(0, 0); + const out = [lScr(a)[0]]; + for (const o of parseScript(lScr(a))) { + const p = o.p.slice(); + if (o.mask & 0x80 && p.length) { if (o.op === 16) p[0] = script(p[0]); else if (o.op === 1) p[0] = sprite(p[0]); else if (o.op === 15 && OP15[p[0]]) p[0] = OP15[p[0]]; } + out.push(o.op | (o.mask << 8), ...p); + } + if (out.length & 1) out.push(0xFCBD); + // the placeholder was the last script so far: put the real one there (scripts after it are appended later) + pend.push([j, out]); + return j; + }; + const pend = []; + const comp = (i) => { + if (gComp.has(i)) return gComp.get(i); + let j = looseComp(i); if (j !== null) { gComp.set(i, j); return j; } + const w = lComp(i).slice(), t = w[0] >> 12; + if (t === 1 && w.length > 3) w[3] = sprite(w[3]); else if (t === 5 && w.length > 3) w[3] = script(w[3]); + j = tix.length; tix.push(tcw.length); tcw.push(...w); if (tcw.length & 1) tcw.push(0); + gComp.set(i, j); return j; + }; + const res = (kind, v) => (kind === 'c' ? comp(v) : kind === 's' ? script(v) : sprite(v)); + const done = () => { + // scripts: rebuild the added ones in order (their sizes were not known when the numbers were given) + if (pend.length) { + pend.sort((a, b) => a[0] - b[0]); + const ix = tsx.slice(0, pend[0][0]), w = tsw.slice(0, 2 * tsx[pend[0][0]]); + for (const [j, out] of pend) { if (ix.length !== j) throw new Error('script order'); ix.push(w.length / 2); w.push(...out); } + if (w.length / 2 > 0xFFFF) throw new Error('script table full'); + tt[13] = toBytes(ix); tt[14] = toBytes(w); + } + if (tcw.length > 0xFFFF) throw new Error('composite table full'); + tt[4] = toBytes(tix); tt[5] = toBytes(tcw); + }; + return { res, done, findSprite }; +} +/* Site list and tables of the games (region B, after the rain cells). Returns the bytes; page gets the + addresses. base: flash offset where the bytes go. */ +function gamesBuild(rom, X, base) { + const f = (x) => x - 0x10000000 + 0x11000, rd16 = (a) => u16(rom, f(a)), rd32 = (a) => u32(rom, f(a)); + const REG = (r) => (r === 'ip' ? 12 : +String(r).slice(1)); + const MAP = (off) => 0x60000000 + off; // flash, as the firmware reads its archive + const parts = [], tabAt = {}; let pos = 0; + const put = (b) => { const at = pos; parts.push(b); pos += b.length; const pad = (4 - pos % 4) % 4; if (pad) { parts.push(new Uint8Array(pad)); pos += pad; } return at; }; + // tables: copy of the original with the family values + for (const [name, T] of Object.entries(G_TABLES)) { + for (let fam = 1; fam <= 2; fam++) { + const sub = T['f' + fam]; if (!sub) continue; + const b = new Uint8Array(T.n * T.w); + for (let i = 0; i < T.n; i++) { const v = T.w === 4 ? rd32(T.addr + 4 * i) : rd16(T.addr + 2 * i); if (T.w === 4) w32(b, 4 * i, v); else w16(b, 2 * i, v); } + for (const [i, kind, lv] of sub) { const v = kind === '=' ? lv : X.res(kind, lv); if (T.w === 4) w32(b, 4 * i, v); else w16(b, 2 * i, v); } + tabAt[name + fam] = MAP(base + put(b)); + } + } + const ent = []; + const site = (xip, rd, rn, vals, flags = 0) => { const b = new Uint8Array(20); w32(b, 0, (xip + 4) | 1); vals.forEach((v, k) => w32(b, 4 + 4 * k, v)); b[16] = rd; b[17] = rn; b[18] = flags; ent.push(b); }; + const patches = []; + for (const [a, kind, rd, rn, gv, res, lv, fams] of G_SITES) { + const xip = parseInt(a, 16), d = immDec(rom, f(xip)); + // the place must still hold the original instruction with the original value + if (!d || d.kind !== kind || d.imm !== gv || d.rd !== REG(rd) || (kind === 'a' && d.rn !== REG(rn))) throw new Error('game place changed ' + a); + const nv = X.res(res, lv); + site(xip, REG(rd), kind === 'a' ? REG(rn) : 0xFF, [gv, fams & 1 ? nv : gv, fams & 2 ? nv : gv]); + patches.push([xip, 4]); + } + for (const [a, rd, name, fams, flags = 0] of G_TABS) { + const xip = parseInt(a, 16), t = movPair(rom, f(xip)); + if (t !== G_TABLES[name].addr) throw new Error('game table place changed ' + a); + site(xip, REG(rd), 0xFF, [t, fams & 1 && tabAt[name + 1] ? tabAt[name + 1] : t, fams & 2 && tabAt[name + 2] ? tabAt[name + 2] : t], flags); + patches.push([xip, 8]); + } + ent.push(new Uint8Array(4)); + const listAt = put(concat(ent)); + // original bytes of every place (for taking the games out again): count, then XIP address, length, 8 bytes + const rest = new Uint8Array(4 + 16 * (patches.length + G_NAV.length)); let n = 0; + for (const [xip, len] of patches.concat(G_NAV.map(([x]) => [x, 4]))) { const o = 4 + 16 * n++; w32(rest, o, xip); w32(rest, o + 4, len); rest.set(rom.subarray(f(xip), f(xip) + len), o + 8); } + w32(rest, 0, n); + const restAt = put(rest); + return { bytes: concat(parts), patches, list: MAP(base + listAt), rest: base + restAt }; +} + +// ------------------------------------------------------------ install +function kindOf(rom) { + if (rom.length !== 0x1000000) return null; + const a = u32(rom, 0xD29000), b = u32(rom, 0xD49000); + if (a === 5 || a === 6) return 'gen3'; + if (b === 4) return 'jade'; + return null; +} +function sixInfo(rom) { + if (rom.length < SIX_OFF + 0x400 || u32(rom, SIX_OFF) !== SIX_MAGIC) return null; + const version = u32(rom, SIX_OFF + 4); + return { version, kind: version >= 3 && u32(rom, SIX_OFF + 28) === 1 ? 'jade' : 'gen3', flagOff: u32(rom, SIX_OFF + 12), + sprites: u32(rom, SIX_OFF + 16), comps: u32(rom, SIX_OFF + 20), anims: version >= 2 ? u32(rom, SIX_OFF + 24) : 0, + planet: version >= 5 && (u32(rom, SIX_OFF + 32) & 1) === 1, fieldMenu: version >= 6 && (u32(rom, SIX_OFF + 32) & 2) === 2, + games: version >= 7 && (u32(rom, SIX_OFF + 32) & 4) === 4, dna: version >= 7 && (u32(rom, SIX_OFF + 32) & 8) === 8, hunt: version >= 7 && (u32(rom, SIX_OFF + 32) & 16) === 16, food: version >= 7 && (u32(rom, SIX_OFF + 32) & 64) === 64, gamesRest: version >= 7 ? u32(rom, SIX_OFF + 36) : 0 }; +} +const movPairBytes = (r, t) => concat([movEnc(r, t & 0xFFFF), movEnc(r, t >>> 16, true)]); +/** Can this ROM get more fields? (Tropical/Glacier: Land, Water, Sky; Jade Forest: Sky) */ +function sixCan(rom) { + const k = kindOf(rom); if (!k) return false; + if (sixInfo(rom)) return true; + const K = KINDS[k], f = (o) => 0x11000 + o; + return hex(rom, f(K.bg.at), 4) === K.bg.orig && hex(rom, f(K.child.at), 6) === K.child.orig && + K.sites.concat(K.planet.sites).every(([o, r, t]) => hex(rom, f(o), 8) === hex(movPairBytes(r, t), 0, 8)) && + K.planet.calls.every((o) => hex(rom, f(o), 4) === hex(branch(XIP(f(o)), K.planet.fn, true), 0, 4)); +} +/** Is this a Land, Water or Sky ROM that can give its fields? */ +function sixSource(land) { + if (!land || land.length !== 0x1000000) return false; + const id = u32(land, 0xD49000); + if (id < 1 || id > 3) return false; + return movPair(land, LAND_BG_AT) === LAND_BG && movPair(land, LAND_ADULT_AT) === LAND_ADULT && LAND_FP.every(([o, h]) => hex(land, o, h.length / 2) === h); +} +/** Does this ROM need a Land, Water or Sky ROM for its extra fields? (Jade Forest does not) */ +function sixNeedsSource(rom) { return kindOf(rom) === 'gen3'; } +/** Takes the extra fields out again (firmware places, helper page, added pictures and scripts). */ +function sixStrip(rom) { + const info = sixInfo(rom); + if (!info) return rom; + const out = new Uint8Array(rom), K = KINDS[info.kind], f = (o) => 0x11000 + o; + const put = (o, h) => { for (let k = 0; k < h.length / 2; k++) out[o + k] = parseInt(h.substr(2 * k, 2), 16); }; + if (info.dna) dnaStrip(out, K, info); + if (info.food && K.food) foodStrip(out, K); + put(f(K.bg.at), K.bg.orig); put(f(K.child.at), K.child.orig); + if (info.kind === 'gen3') for (const [o, h] of OLD_PATCH) put(o, h); + for (const [o, r, t] of K.sites.concat(K.planet.sites, ...EXTRAS.map((X) => X.sites[info.kind]))) out.set(movPairBytes(r, t), f(o)); + for (const o of K.planet.calls) out.set(branch(XIP(f(o)), K.planet.fn, true), f(o)); + if (info.fieldMenu) fmStrip(out, K); + if (info.games && info.gamesRest >= B_OFF && info.gamesRest < B_END) { + const r = info.gamesRest, n = u32(out, r); + for (let k = 0; k < n && k < 4096; k++) { const o = r + 4 + 16 * k, xip = u32(out, o), len = u32(out, o + 4); out.set(out.slice(o + 8, o + 8 + len), xip - 0x10000000 + 0x11000); } + } + out.fill(0xFF, SIX_OFF, SIX_OFF + 0x1000); + if (u32(out, B_OFF) === B_MAGIC) out.fill(0xFF, B_OFF, 0x1000000); + if (info.kind === 'jade') return out; + const T = C.openRom(out), tabs = dpSplit(T.files[0]); + const ix = words(tabs[4]), cw = words(tabs[5]); + tabs[4] = toBytes(ix.slice(0, info.comps)); tabs[5] = toBytes(cw.slice(0, ix[info.comps])); + if (info.version >= 2) { const S = scripts(tabs); tabs[13] = toBytes(S.ix.slice(0, info.anims)); tabs[14] = toBytes(S.w.slice(0, 2 * S.ix[info.anims])); } + return C.buildRom({ rom: out, entries: T.entries.slice(0, info.sprites), files: [null, null, T.files[2]], limit: T.limit, assetEnd: T.assetEnd }, new Map(), dpJoin(tabs)).rom; +} +/* The game's field menu: are the places as the original firmware has them? */ +function fmCan(rom, K) { + const F = K.fm, f = (o) => 0x11000 + o; + if (!F) return false; + if (hex(rom, f(F.build[0]), 4) !== hex(branch(0x10000000 + F.build[0], F.build[1], true), 0, 4)) return false; + if (!F.prev.slice(1).every((o) => hex(rom, f(o), 4) === hex(branch(0x10000000 + o, F.prev[0], true), 0, 4))) return false; + if (!F.cmp.concat([F.set]).every((o) => hex(rom, f(o), 4) === F.read)) return false; + return F.imm.every(([o, old]) => rom[f(o) + 2] === old); +} +function fmStrip(out, K) { + const F = K.fm, f = (o) => 0x11000 + o, rd = (o) => { for (let k = 0; k < 4; k++) out[f(o) + k] = parseInt(F.read.substr(2 * k, 2), 16); }; + out.set(branch(0x10000000 + F.build[0], F.build[1], true), f(F.build[0])); + for (const o of F.prev.slice(1)) out.set(branch(0x10000000 + o, F.prev[0], true), f(o)); + F.cmp.concat([F.set]).forEach(rd); + for (const [o, old] of F.imm) out[f(o) + 2] = old; +} +function fmInstall(out, page, K) { + const F = K.fm, f = (o) => 0x11000 + o, fn = (k) => u32(page, P_FM_FN + 4 * k) & ~1; + w32(page, P_FM, F.obj); w32(page, P_FM + 4, F.field); w32(page, P_FM + 8, F.level); + w32(page, P_FM + 12, F.build[1] | 1); w32(page, P_FM + 16, F.prev[0] | 1); + F.off.forEach((v, i) => { page[P_FM + 0x14 + i] = v; }); + page[P_FM + 0x18] = F.ent.length; page.fill(0, P_FM + 0x19, P_FM + 0x1C); + page.fill(0, P_FM + 0x1C, P_FM + 0x24); F.ent.forEach((v, i) => { page[P_FM + 0x1C + i] = v; }); + out.set(branch(0x10000000 + F.build[0], fn(0), true), f(F.build[0])); + for (const o of F.cmp) out.set(branch(0x10000000 + o, fn(1), true), f(o)); + out.set(branch(0x10000000 + F.set, fn(2), true), f(F.set)); + for (const o of F.prev.slice(1)) out.set(branch(0x10000000 + o, fn(3), true), f(o)); + for (const [o, , nu] of F.imm) out[f(o) + 2] = nu; +} +/* Helper page and firmware jumps. alt: alternative tables by name (rows like the original). */ +function install(out, kind, blob, alt, counts, planet, fieldMenu, games) { + const K = KINDS[kind], f = (o) => 0x11000 + o, sites = (planet ? K.sites.concat(K.planet.sites) : K.sites).concat(...EXTRAS.filter((X) => alt[X.name]).map((X) => X.sites[kind])); + const page = new Uint8Array(0x1000).fill(0xFF); page.set(blob.subarray(0, Math.min(blob.length, P_DNA))); + w32(page, 8, K.flag); w32(page, 12, FLAG_OFF); + w32(page, 16, counts[0]); w32(page, 20, counts[1]); w32(page, 24, counts[2]); w32(page, 28, K.id); w32(page, 32, (planet ? 1 : 0) | (fieldMenu ? 2 : 0) | (games ? 4 : 0) | EXTRAS.reduce((m, X) => m | (alt[X.name] ? X.bit : 0), 0)); w32(page, 36, games ? games.rest : 0); + // background table and child list + alt.bg.forEach((v, i) => w16(page, T_BG + 2 * i, v)); + w32(page, P_BG, K.bg.table); w32(page, P_BG + 4, SIX_XIP + T_BG); w32(page, P_BG + 8, K.bg.mode); + K.child.list.forEach((v, i) => w16(page, T_CHILD_O + 2 * i, v)); alt.child.forEach((v, i) => w16(page, T_CHILD + 2 * i, v)); + w32(page, P_CHILD, SIX_XIP + T_CHILD_O); w32(page, P_CHILD + 4, SIX_XIP + T_CHILD); w32(page, P_CHILD + 8, K.child.sp); + // other tables, then the site list + let pos = T_MORE; const at = {}; + for (const name of new Set(sites.map((x) => x[3]))) { + const v = alt[name]; if (v === undefined) throw new Error('table ' + name + ' missing'); + { const X = EXTRAS.find((y) => y.name === name); if (X) { at[name] = X.at; v.forEach((x, i) => w16(page, X.at + 2 * i, x)); continue; } } // add-on tables: fixed places (also for the add-on path) + if (typeof v === 'number') { at[name] = v - SIX_XIP; continue; } // a value instead of a table + at[name] = pos; v.forEach((x, i) => w16(page, pos + 2 * i, x)); pos += (2 * v.length + 3) & ~3; + } + if (pos > Math.min(0x800, ...EXTRAS.filter((X) => alt[X.name]).map((X) => X.at))) throw new Error('helper page full'); + if (12 * (sites.length + 1) > T_MORE - T_SITES) throw new Error('helper page full'); + sites.forEach(([o, , t, name], i) => { const e = T_SITES + 12 * i; w32(page, e, (XIP(f(o)) + 4) | 1); w32(page, e + 4, t); w32(page, e + 8, SIX_XIP + at[name]); }); + w32(page, T_SITES + 12 * sites.length, 0); + // planet: original function, field byte, row per field slot + w32(page, P_PMAP, K.planet.fn | 1); w32(page, P_PMAP + 4, K.planet.field); + K.planet.rows.forEach((v, i) => { page[P_PMAP + 8 + i] = v; }); + if (fieldMenu) fmInstall(out, page, K); + out.set(page, SIX_OFF); + // firmware: background function -> b.w, child -> bl + b, sites -> bl + 2 nop + const fn = (k) => u32(page, P_FN + 4 * k) & ~1; + out.set(branch(XIP(f(K.bg.at)), fn(FN_BG), false), f(K.bg.at)); + { const src = XIP(f(K.child.at)), b = new Uint8Array(6); b.set(branch(src, fn(FN_CHILD), true)); + w16(b, 4, 0xE000 | (((XIP(f(K.child.back)) - (src + 8)) >> 1) & 0x7FF)); out.set(b, f(K.child.at)); } + for (const [o, r] of sites) { const b = new Uint8Array(8); b.set(branch(XIP(f(o)), fn(FN_TAB[r]), true)); w16(b, 4, 0xBF00); w16(b, 6, 0xBF00); out.set(b, f(o)); } + if (planet) for (const o of K.planet.calls) out.set(branch(XIP(f(o)), fn(FN_PMAP), true), f(o)); + if (games) gamesInstall(out, page, K, games); + out.set(page, SIX_OFF); + return out; +} +function gamesInstall(out, page, K, games) { + const g = (k) => u32(page, P_GM_FN + 4 * k) & ~1, fo = (x) => x - 0x10000000 + 0x11000; + w32(page, P_GM, games.list); w32(page, P_GM + 4, K.flag + 1); w32(page, P_GM + 8, 0x18001CB4); + page.fill(0, P_GM + 0x0C, P_GM + 0x18); G_SCENES.forEach((v, i) => { page[P_GM + 0x0C + i] = v; }); + page.fill(0xFF, P_GM + 0x18, P_GM + 0x28); G_SEQ.forEach((q, fam) => q.forEach((v, i) => { page[P_GM + 0x18 + 8 * fam + i] = v; })); + for (const [xip, len] of games.patches) { + const b = new Uint8Array(len); b.set(branch(xip, g(0), true)); if (len === 8) { w16(b, 4, 0xBF00); w16(b, 6, 0xBF00); } + out.set(b, fo(xip)); + } + for (const [xip, k] of G_NAV) { if (hex(out, fo(xip), 4) !== G_NAV_ORIG) throw new Error('game place changed ' + xip.toString(16)); out.set(branch(xip, g(k), true), fo(xip)); } +} +/* DNA per field: can this ROM (with six fields of version 7 or new) get it? */ +function dnaCan(rom, K) { + const D = K && K.dna, fo = (x) => x - 0x10000000 + 0x11000; + if (!SIX_DNA || !D) return false; + return dnaSites(D).every(([x, h]) => hex(rom, fo(x), h.length / 2) === h); +} +/* the firmware places of the DNA part (with the food places when on) */ +function dnaSites(D) { return SIX_FOOD && D.food ? D.sites.concat(D.food.sites) : D.sites; } +/* An old DNA part without the food places: put the DNA part in again (the saved values stay). + * Jade Forest (no DNA part): the food part alone. */ +function sixFood(rom, blob) { + const info = sixInfo(rom), K = info && KINDS[info.kind], fo = (x) => x - 0x10000000 + 0x11000; + if (!SIX_FOOD || !info || info.version < 7 || !K || !blob || blob.length <= P_DNA_FN + 4 * 11 || u32(blob, P_DNA_FN + 4 * 11) === 0) return rom; + const F = K.dna ? K.dna.food : K.food; + if (!F || !F.sites.every(([x, h]) => hex(rom, fo(x), h.length / 2) === h)) return rom; + const out = new Uint8Array(rom); + if (K.dna) { if (!info.dna) return rom; dnaStrip(out, K, info); dnaInstall(out, K, blob, info.fieldMenu); } + else if (!info.dna) foodInstall(out, K, blob); + return out; +} +/* Food part alone (Jade Forest): the code of the DNA part, only the values the food code reads. */ +function foodInstall(out, K, blob) { + const F = K.food, page = out.subarray(SIX_OFF, SIX_OFF + 0x1000); + page.fill(0xFF, P_DNA, DNA_END); page.set(blob.subarray(P_DNA), P_DNA); page.fill(0, P_DNA, P_DNA + 0x40); + w32(page, P_DNA, F.ram); w16(page, P_DNA + 6, F.field); page[P_DNA + 15] = F.slots; + w16(page, P_DNA + 0x34, F.hist); F.kinds.forEach((v, i) => { page[P_DNA + 0x36 + i] = v; }); + w32(page, 32, u32(page, 32) | 64); + sitesPut(out, F.sites, (k) => u32(page, P_DNA_FN + 4 * k) & ~1); +} +function foodStrip(out, K) { + const F = K.food, page = out.subarray(SIX_OFF, SIX_OFF + 0x1000); + for (const [x, h] of F.sites) for (let k = 0; k < h.length / 2; k++) out[x - 0x10000000 + 0x11000 + k] = parseInt(h.substr(2 * k, 2), 16); + w32(page, 32, u32(page, 32) & ~64); page.fill(0xFF, P_DNA, DNA_END); +} +function sitesPut(out, sites, fn) { + for (const [x, h, how, a] of sites) { + const n = h.length / 2, b = new Uint8Array(n); + if (how === 'hex') { for (let k = 0; k < n; k++) b[k] = parseInt(a.substr(2 * k, 2), 16); } + else { b.set(branch(x, fn(a), how === 'bl')); for (let k = 4; k < n; k += 2) w16(b, k, 0xBF00); } + out.set(b, x - 0x10000000 + 0x11000); + } +} +/* Puts the DNA part in (page at SIX_OFF of out, its code from blob) and patches the firmware. */ +function dnaInstall(out, K, blob, fieldMenu) { + const D = K.dna, fo = (x) => x - 0x10000000 + 0x11000; + if (!blob || blob.length <= P_DNA_FN) throw new Error('six fields program missing'); + const page = out.subarray(SIX_OFF, SIX_OFF + 0x1000); + page.fill(0xFF, P_DNA, DNA_END); page.set(blob.subarray(P_DNA), P_DNA); + w32(page, P_DNA, D.base); w16(page, P_DNA + 4, D.cnt); w16(page, P_DNA + 6, D.field); w16(page, P_DNA + 8, D.stash); w16(page, P_DNA + 10, D.mark); + w16(page, P_DNA + 12, D.bits); page[P_DNA + 14] = D.mask; page[P_DNA + 15] = D.slots; + page.fill(0, P_DNA + 0x10, P_DNA + 0x28); D.regions.forEach(([o, n], i) => { w16(page, P_DNA + 0x10 + 4 * i, o); w16(page, P_DNA + 0x12 + 4 * i, n); }); + D.icons.forEach((v, i) => w16(page, P_DNA + 0x28 + 2 * i, v)); + if (SIX_FOOD && D.food) { w16(page, P_DNA + 0x34, D.food.hist); D.food.kinds.forEach((v, i) => { page[P_DNA + 0x36 + i] = v; }); } + w32(page, 32, u32(page, 32) | 8); + const fn = (k) => u32(page, P_DNA_FN + 4 * k) & ~1; + sitesPut(out, dnaSites(D), fn); + out.set(branch(XIP(0x11000 + K.child.at), fn(DNA_CHILD), true), 0x11000 + K.child.at); + if (fieldMenu) out.set(branch(0x10000000 + K.fm.set, fn(DNA_FSET), true), 0x11000 + K.fm.set); +} +/* Takes the DNA part out again (the firmware places as before, the six fields stay). */ +function dnaStrip(out, K, info) { + const D = K.dna, fo = (x) => x - 0x10000000 + 0x11000, page = out.subarray(SIX_OFF, SIX_OFF + 0x1000); + if (!D) return; + for (const [x, h] of D.food ? D.sites.concat(D.food.sites) : D.sites) for (let k = 0; k < h.length / 2; k++) out[fo(x) + k] = parseInt(h.substr(2 * k, 2), 16); + const fn = (k) => u32(page, P_FN + 4 * k) & ~1; + out.set(branch(XIP(0x11000 + K.child.at), fn(FN_CHILD), true), 0x11000 + K.child.at); + if (info.fieldMenu) out.set(branch(0x10000000 + K.fm.set, u32(page, P_FM_FN + 8) & ~1, true), 0x11000 + K.fm.set); + w32(page, 32, u32(page, 32) & ~8); page.fill(0xFF, P_DNA, DNA_END); +} +/** + * DNA per field on or off for a ROM that has six fields already (no Land ROM needed). Returns the ROM + * unchanged when there is nothing to do or the ROM cannot take it. + */ +function sixDna(rom, blob, on) { + const info = sixInfo(rom); + if (info && info.version >= 7 && on && (info.dna || !KINDS[info.kind].dna)) return sixFood(rom, blob); + if (info && info.food && !on) { const o = new Uint8Array(rom); foodStrip(o, KINDS[info.kind]); return o; } + if (!info || info.version < 7 || !!info.dna === !!on) return rom; + const K = KINDS[info.kind], out = new Uint8Array(rom); + if (!on) { dnaStrip(out, K, info); return out; } + if (!SIX_DNA || !K.dna || !blob || u32(blob, P_DNA_FN) === 0 || !dnaCan(rom, K)) return rom; + dnaInstall(out, K, blob, info.fieldMenu); + return out; +} +/** Can this ROM get DNA per field? */ +function sixDnaCan(rom) { const i = sixInfo(rom), k = i ? i.kind : kindOf(rom); return SIX_DNA && !!k && !!KINDS[k].dna; } +/* rows of an original table with some rows replaced: table at XIP address, per row n values */ +function rows(rom, addr, n, nrows, repl) { + const o = addr - 0x10000000 + 0x11000, v = []; + for (let r = 0; r < nrows; r++) for (let i = 0; i < n; i++) v.push(repl[r] ? repl[r][i] : u16(rom, o + 2 * (n * r + i))); + return v; +} +/** + * More fields: returns a new image. rom: Tropical/Glacier or Jade Forest image without the menu + * (call feldStrip first). land: the user's Land, Water or Sky image (only for Tropical/Glacier). + * blob: six.bin. + */ +function sixApply(rom, land, blob, opts = {}) { + const planet = opts.planet !== false; + const have = sixInfo(rom); + let fieldMenu = opts.fieldMenu !== false; + const wantGames = SIX_GAMES && opts.games !== false && kindOf(rom) === 'gen3'; + const wantDna = SIX_DNA && opts.dna !== false && !!(KINDS[have ? have.kind : kindOf(rom)] || {}).dna; + const wantFood = SIX_FOOD && opts.dna !== false; + + if (have && have.version >= SIX_VERSION && have.planet === planet && have.fieldMenu === fieldMenu && have.games === wantGames) { let r = sixDna(rom, blob, wantDna); if (wantFood) r = sixFood(r, blob); return sixHunt(r); } + if (have) rom = sixStrip(rom); + const kind = kindOf(rom); + if (kind && fieldMenu && !fmCan(rom, KINDS[kind])) fieldMenu = false; + if (!kind || !sixCan(rom)) throw new Error('more fields need a Tropical, Glacier or Jade Forest ROM with the original firmware'); + if (!blob || blob.length > 0x1000 || u32(blob, 0) !== SIX_MAGIC || u32(blob, 4) !== SIX_VERSION) throw new Error('six fields program missing'); + const dnaOk = wantDna && dnaCan(rom, KINDS[kind]); + for (let i = SIX_OFF; i < SIX_OFF + 0x1000; i++) if (rom[i] !== 0xFF) throw new Error('area 0x10F000 is in use'); + if (kind === 'jade') { + const T = C.openRom(rom), ix = words(dpSplit(T.files[0])[4]); + if (ix.length <= 781 || comp(dpSplit(T.files[0]), 773)[0] !== 0x1007) throw new Error('unexpected Jade Forest data'); + const J = JADE_SKY, alt = { + bg: rows(rom, KINDS.jade.bg.table, 16, 3, { 1: J.bg }), child: J.child, + teen: rows(rom, 0x1007DFC4, 4, 3, { 1: J.teen }), adult: rows(rom, 0x1007DFDC, 16, 3, { 1: J.adult }), + speed: rows(rom, 0x1008BCE8, 3, 3, { 1: J.speed }), egg: rows(rom, 0x100820E8, 1, 3, { 1: J.egg }), + wagon: rows(rom, 0x100820D0, 4, 3, { 1: J.wagon }), scene: rows(rom, 0x10081198, 5, 3, { 1: J.scene }), + spec1: 0x0FE40FE2 }; // Land 4066, Sky 4068 (Yayacorntchi) in the Water slot + // planet: Sky stages in the Water row (the field slot of Sky) + alt.plTab = rows(rom, 0x1008CBD0, 11, 3, { 1: SKY_PLANET }); + alt.pl0 = rows(rom, 0x100811DA, 11, 1, {}); alt.pl1 = SKY_PLANET; alt.pl2 = rows(rom, 0x100811F0, 11, 1, {}); + for (const X of EXTRAS) if (X.on() && opts[X.name] !== false && extraCan(rom, 'jade', X)) alt[X.name] = X.tab(rom, 'jade'); + const outJ = install(new Uint8Array(rom), 'jade', blob, alt, [0, 0, 0], planet, fieldMenu); + if (dnaOk) dnaInstall(outJ, KINDS.jade, blob, fieldMenu); + else if (wantFood) return sixFood(outJ, blob); + return outJ; + } + if (!sixSource(land)) throw new Error('the second ROM must be a Land, Water or Sky ROM'); + const trop = rom; + const T = C.openRom(trop), L = C.openRom(land); + const tt = dpSplit(T.files[0]), lt = dpSplit(L.files[0]); + const lw = (off) => u16(land, off), lfw = (x) => 0x11000 + x - 0x10000000; + // Land backgrounds: 3 fields x 10 composites (5 times of day x clear/rain), base before them + const lbg = []; for (let i = 0; i < 30; i++) lbg.push(lw(lfw(LAND_BG) + 2 * i)); + const adult = []; for (let i = 0; i < 48; i++) adult.push(lw(lfw(LAND_ADULT) + 2 * i)); + const entries = T.entries.slice(); + const nspr0 = entries.length, ix = words(tt[4]), cw = words(tt[5]), ncomp0 = ix.length, nanim0 = words(tt[13]).length; + const compNew = new Map(), sprNew = new Map(); + const fields = [0, 1, 2].map((fi) => { + const row = lbg.slice(10 * fi, 10 * fi + 10), base = row[0] - 1; + const clear = [base, row[0], row[2], row[4], row[6], row[8]], rain = [row[1], row[3], row[5], row[7], row[9]]; + const sprs = [], ext = []; + for (const c of clear.concat(rain)) { + const w = comp(lt, c); + if (w[0] !== 0x1007 || w.length < 4) throw new Error('unexpected Land picture ' + c); + if (!sprs.includes(w[3])) { sprs.push(w[3]); ext.push(!clear.includes(c)); } + } + return { row, base, sprs, ext }; + }); + const bList = [], bData = []; let bPos = 0; + for (const fd of fields) { + const group = fd.sprs.map((i) => { const m = mapCells(L.entries[i]); m.h.raw = L.entries[i]; return m; }); + const packed = packGroup(group, K_COLORS, fd.ext); + fd.sprs.forEach((i, j) => { + sprNew.set(i, entries.length); + if (packed.outside[j]) bList.push({ id: entries.length, rel: packed.outside[j].map((x) => (x < 0 ? -1 : x + bPos)) }); + entries.push(packed[j]); + }); + bData.push(packed.bdata); bPos += packed.bdata.length; const pad = (4 - bPos % 4) % 4; if (pad) { bData.push(new Uint8Array(pad)); bPos += pad; } + } + const bHead = 8 + bList.length * 260; + if (B_OFF + bHead + bPos > B_END) throw new Error('rain pictures too big'); + const addComp = (c) => { + if (compNew.has(c)) return compNew.get(c); + const w = comp(lt, c).slice(); w[3] = sprNew.get(w[3]); + const id = ix.length; ix.push(cw.length); cw.push(...w); if (cw.length & 1) cw.push(0); + compNew.set(c, id); return id; + }; + const tBg = []; + for (const fd of fields) { + const half = [addComp(fd.base)]; + for (let s = 0; s < 5; s++) { const c = addComp(fd.row[2 * s]), r = addComp(fd.row[2 * s + 1]); half.push(c, r, r); } + tBg.push(...half, ...half); + } + if (cw.length > 0xFFFF) throw new Error('composite table full'); + tt[4] = toBytes(ix); tt[5] = toBytes(cw); + // scenes: travel backgrounds, field eggs, scene animations, wagon + const imp = importer({ tabs: lt, entries: L.entries }, { tabs: tt, entries: T.entries }, entries); + const speed = []; for (let i = 0; i < 9; i++) speed.push(imp.anim(lw(lfw(LAND_SPEED) + 2 * i))); + const firstPic = (a, d = 0) => { + for (const o of parseScript(scripts(lt).get(a))) { + if (o.mask & 0x80 && o.p.length && o.op === 1) return o.p[0]; + if (o.mask & 0x80 && o.p.length && o.op === 16 && d < 4) { const r = firstPic(o.p[0], d + 1); if (r >= 0) return r; } + } + return -1; + }; + const egg = [0, 1, 2].map((fi) => imp.anim(LAND_EGG + fi)); + const eggPic = [0, 1, 2].map((fi) => { const p = firstPic(LAND_EGG + fi); if (p < 0) throw new Error('unexpected Land picture ' + (LAND_EGG + fi)); return imp.sprite(p); }); + const scene = [], wagon = [], tw = rows(trop, 0x10095778, 4, 3, {}); + for (let fi = 0; fi < 3; fi++) { + for (const c of LAND_SCENE) scene.push(imp.anim(c + fi)); + wagon.push(imp.anim(LAND_WAGON[0] + fi), imp.anim(LAND_WAGON[1] + fi), tw[4 * fi + 2], tw[4 * fi + 3]); + } + imp.done(); + // lab games per start field: Land pictures go in with the rest, the site list after the rain cells + let games = null; + const gBase = (B_OFF + bHead + bPos + 0xFFF) & ~0xFFF; + if (SIX_GAMES && opts.games !== false) { + const X = translator({ tabs: lt, entries: L.entries }, tt, entries); + games = gamesBuild(trop, X, gBase); + X.done(); + if (gBase + games.bytes.length > B_END) throw new Error('rain pictures too big'); + } + for (const [a, n] of TROP_MAPS) for (let i = a; i < a + n; i++) entries[i] = reduceOne(entries[i], K_COLORS); + const out = C.buildRom({ rom: trop, entries, files: [null, null, T.files[2]], limit: T.limit, assetEnd: T.assetEnd }, new Map(), dpJoin(tt)).rom; + const alt = { bg: tBg, child: [2002, 2003, 2004], teen: Array.from({ length: 12 }, (_, i) => 3005 + i), adult, speed, egg, eggPic, scene, wagon, + spec1: 0x0FE30FE2, spec2: 0x0FE40FE4 }; // specials Chodracotchi 4066, Mermarintchi 4067, Yayacorntchi 4068 + // planet stages of Land, Water, Sky (from the Land ROM, the same in all three) + alt.plTab = []; for (let i = 0; i < 33; i++) alt.plTab.push(lw(lfw(LAND_PLANET) + 2 * i)); + if (alt.plTab[0] !== 2 || alt.plTab[11] !== 2 || alt.plTab[22] !== 2) throw new Error('unexpected Land planet table'); + alt.pl0 = alt.plTab.slice(0, 11); alt.pl1 = alt.plTab.slice(11, 22); alt.pl2 = alt.plTab.slice(22, 33); + for (const X of EXTRAS) if (X.on() && opts[X.name] !== false && extraCan(trop, 'gen3', X)) alt[X.name] = X.tab(trop, 'gen3'); + install(out, 'gen3', blob, alt, [nspr0, ncomp0, nanim0], planet, fieldMenu, games); + if (dnaOk) dnaInstall(out, KINDS.gen3, blob, fieldMenu); + // region B: rain cells + for (let i = B_OFF; i < B_END; i++) if (trop[i] !== 0xFF) throw new Error('area 0xF00000 is in use'); + const bh = new Uint8Array(bHead); w32(bh, 0, B_MAGIC); w32(bh, 4, bList.length); + bList.forEach((x, k) => { const o = 8 + k * 260; w32(bh, o, x.id); x.rel.forEach((r, t) => w32(bh, o + 4 + 4 * t, r < 0 ? 0xFFFFFFFF : r)); }); + out.set(bh, B_OFF); out.set(concat(bData), B_OFF + bHead); + if (games) out.set(games.bytes, gBase); + return sixFix(out); +} +/** Points the rain pictures at their cells in region B again (call after every archive rebuild). */ +function sixFix(rom) { + if (!sixInfo(rom) || u32(rom, B_OFF) !== B_MAGIC) return rom; + const out = new Uint8Array(rom), n = u32(out, B_OFF + 4), data = B_OFF + 8 + n * 260; + const pack = 0x111000 + u32(out, 0x111000 + 16 + 16 + 4); + for (let k = 0; k < n; k++) { + const o = B_OFF + 8 + k * 260, id = u32(out, o), h = pack + u32(out, pack + 4 * id), pix = h + u16(out, h + 20); + for (let t = 0; t < 64; t++) { const r = u32(out, o + 4 + 4 * t); if (r !== 0xFFFFFFFF) w32(out, pix + 8 * t, data + r - pix); } + } + w32(out, 0x111004, C.arc2Checksum(out, 0x111000, u32(out, 0x111008))); // archive checksum + return out; +} + +const SIX_B64 = '__SIX_B64__'; +function embedded() { return SIX_B64.startsWith('__') ? null : b64(SIX_B64); } + +root.ParamixSix = { VERSION: SIX_VERSION, DNA: SIX_DNA, HUNT: SIX_HUNT, sixHunt, sixDna, sixDnaCan, sixApply, sixStrip, sixFix, sixCan, sixSource, sixInfo, sixNeedsSource, kindOf, embedded, FLAG_OFF, SIX_OFF, packGroup, reduceOne, mapCells }; +if (typeof module !== 'undefined') module.exports = root.ParamixSix; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/src/visit.js b/src/visit.js new file mode 100644 index 0000000..96adab3 --- /dev/null +++ b/src/visit.js @@ -0,0 +1,213 @@ +/* + * Paramix Studio 1.6.9: simulated playdate partner for the Tamagotchi Paradise. + * + * The Paradise talks on its contacts (UART, 460800 8-N-1) with the "TCP" protocol described by GMMan + * (tama-para-research, protocols/tcp.md and playdate.md). The Studio plays the other device: the player + * starts a playdate on the Paradise and presses B there, so the Paradise is the initiator and we answer. + * + * Flow as recipient (measured with two emulated consoles): + * < PKT 2 session ID (type bit 4), 2 random bytes + * < PKT 131092 ghost package + planet screenshot + playdate data (0x20014 bytes) + * > PKT 131092 our answer: their own package with the chosen edition (rom_type) and our own IDs + * < PKT 2 friendship level + * ECHO REQ / ECHO REP while the animation runs + * < PKT 4 play result (u16 result, bit 0 of the next u16: breeding possible) + * with breeding: we answer "BREED 0" and "SYNC 1" (we never breed) + * + * No game data is in here: the visitor is a copy of the player's own Tama, only the edition and the IDs + * are ours. The chunks use the same link key as the flash app loader (src/flash.js). Transport free: + * send(bytes) out, feed(bytes) in, so the same code runs in the test. + */ +(function (root) { + 'use strict'; + const ED = { land: 1, water: 2, sky: 3, jade: 4, tropics: 5, glacier: 6 }; + const PD = 0x20000; // playdate data in the phase 1 packet + const enc = (s) => new TextEncoder().encode(s); + + function crc16(d) { + let c = 0; + for (let i = 0; i < d.length; i++) { c ^= d[i]; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xA001 : c >>> 1; } + return c; + } + async function sha256(u) { + const c = (root.crypto && root.crypto.subtle) ? root.crypto : (typeof require === 'function' ? require('crypto').webcrypto : null); + return new Uint8Array(await c.subtle.digest('SHA-256', u)); + } + async function keystream(nonce, key) { + const m = new Uint8Array(4 + key.length); m.set(nonce, 0); m.set(key, 4); + return sha256(m); + } + /* encrypt and decrypt are the same: XOR with the keystream, each key byte becomes 2k+1 after use */ + async function crypt(nonce, key, data) { + const k = await keystream(nonce, key), out = new Uint8Array(data.length); + for (let i = 0; i < data.length; i++) { const j = i & 31; out[i] = data[i] ^ k[j]; k[j] = (k[j] * 2 + 1) & 255; } + return out; + } + function rnd4() { + const n = new Uint8Array(4); + if (root.crypto && root.crypto.getRandomValues) root.crypto.getRandomValues(n); + else for (let i = 0; i < 4; i++) n[i] = Math.random() * 256 | 0; + return n; + } + const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0; + const w16 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >> 8 & 255; }; + const w32 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >> 8 & 255; b[o + 2] = v >> 16 & 255; b[o + 3] = v >>> 24; }; + + /* the link key: 32 characters, as text or as the bytes of the key file */ + function parseKey(x) { + let s = typeof x === 'string' ? x : new TextDecoder('latin1').decode(x); + s = s.trim(); + if (!/^[\x21-\x7e]{16,64}$/.test(s)) return null; + return enc(s); + } + + /* + * opts: { edition: 'water' | 1..6, key: Uint8Array, send: async (Uint8Array) => {}, log: (event, info) => {} } + * Returns { feed(Uint8Array), stop(), state }. + * log events: 'start', 'packet' {kind}, 'sent', 'result' {result, breed}, 'done', 'error' {text} + */ + function createVisitor(opts) { + const ed = typeof opts.edition === 'number' ? opts.edition : ED[String(opts.edition).toLowerCase()]; + if (!ed) throw new Error('unknown edition'); + const key = opts.key, log = opts.log || (() => {}); + const st = { phase: 'wait', sid: 0, got: 0, stopped: false, result: null }; + let buf = new Uint8Array(0); + let need = 0; // > 0: a chunk of this size is expected + let rx = null; // packet coming in + let tx = null; // packet going out + let echo = null, queue = Promise.resolve(); + const out = (s) => opts.send(typeof s === 'string' ? enc(s) : s); + const line = (s) => out(s + '\r\n'); + + function idle(on) { + clearInterval(echo); echo = null; + // the other device pings every 3 to 4 s while nothing is sent; we do the same so it sees us + if (on && !st.stopped) echo = setInterval(() => { if (!tx && !rx && !need) line('ECHO REQ').catch(() => {}); }, 3000); + } + async function sendPacket(data, type) { + tx = { data, type, idx: 0, n: Math.ceil(data.length / 0x1000), tries: 0, done: null }; + const p = new Promise((res, rej) => { tx.done = res; tx.fail = rej; }); + await line('PKT ' + data.length); + tx.timer = setTimeout(retryPkt, 2000); + return p; + } + function retryPkt() { + if (!tx || st.stopped) return; + if (++tx.tries >= 3) { const f = tx.fail; tx = null; line('CAN').catch(() => {}); f(new Error('no ACK')); return; } + line('PKT ' + tx.data.length).catch(() => {}); tx.timer = setTimeout(retryPkt, 2000); + } + async function sendChunk() { + const i = tx.idx, d = tx.data.subarray(i * 0x1000, Math.min(tx.data.length, (i + 1) * 0x1000)); + const p = new Uint8Array(12 + d.length); + w32(p, 0, st.sid); p[4] = 0x54; p[5] = 0x43; p[6] = 0x50; p[7] = tx.type; p[8] = i; p[9] = 255 - i; w16(p, 10, crc16(d)); p.set(d, 12); + const n = rnd4(), c = await crypt(n, key, p), all = new Uint8Array(4 + c.length); + all.set(n, 0); all.set(c, 4); + clearTimeout(tx.timer); tx.timer = setTimeout(() => { if (tx && ++tx.tries < 3) sendChunk().catch(() => {}); else if (tx) { const f = tx.fail; tx = null; f(new Error('no ACK for a chunk')); } }, 5000); + await out(all); + } + function onAck() { + if (!tx) return; + tx.tries = 0; + if (tx.started) tx.idx++; + tx.started = true; + if (tx.idx >= tx.n) { clearTimeout(tx.timer); const d = tx.done; tx = null; d(); return; } + sendChunk().catch((e) => fail(e)); + } + + function answer(their) { + if (their.length < PD + 0x14) return null; + const a = their.slice(); + w16(a, PD, 0); // force_send_away: never + w16(a, PD + 2, ed); // rom_type: the chosen edition + w32(a, PD + 4, 0x504D5800 | ed); // device UID of the simulated device ("PMX" + edition) + w32(a, PD + 8, (u32(their, PD + 8) ^ 0x5A5A0000 ^ ed) >>> 0); // character UID: theirs, changed + return a; + } + async function packet(d, type) { + st.got++; + if (type & 0x10) { log('packet', { kind: 'session' }); return; } + if (d.length === 0x20014) { + log('packet', { kind: 'data', ed: u32(d, PD) >>> 16 }); + st.phase = 'send'; + const a = answer(d); + await new Promise((r) => setTimeout(r, 150)); // the other device also waits a moment before it answers + await sendPacket(a, type & 15); + st.phase = 'play'; log('sent', {}); idle(true); + return; + } + if (d.length === 2) { log('packet', { kind: 'friendship', level: d[0] | d[1] << 8 }); return; } + if (d.length === 4) { + const result = d[0] | d[1] << 8, breed = !!(d[2] & 1); + st.result = result; log('result', { result, breed }); + if (breed) { await line('BREED 0'); await line('SYNC 1'); return; } + finish(); + return; + } + log('packet', { kind: 'other', n: d.length }); + } + function finish() { if (st.phase === 'done') return; st.phase = 'done'; idle(false); log('done', { result: st.result }); } + function fail(e) { if (st.stopped) return; idle(false); st.phase = 'error'; log('error', { text: e && e.message || String(e) }); } + + async function chunk(c) { + const n = c.subarray(0, 4), p = await crypt(n, key, c.subarray(4)); + const sid = u32(p, 0), type = p[7], idx = p[8], crc = p[10] | p[11] << 8, d = p.subarray(12); + const ok = p[4] === 0x54 && p[5] === 0x43 && p[6] === 0x50 && p[9] === 255 - idx && crc16(d) === crc && (!st.sid || (type & 0x10) || sid === st.sid); + if (!ok) { need = c.length; await line('NAK'); if (!st.badKey && p[4] !== 0x54) { st.badKey = true; log('error', { text: 'key' }); } return; } + if (idx !== rx.idx) { need = c.length; await line('ENQ ' + rx.idx); return; } + if (type & 0x10) st.sid = sid; + rx.data.set(d, rx.off); rx.off += d.length; rx.idx++; + const left = rx.n - rx.off; + need = left > 0 ? 16 + Math.min(0x1000, left) : 0; + await line('ACK'); + if (!left) { const r = rx; rx = null; packet(r.data, type).catch(fail); } + } + async function command(s) { + const w = s.trim().split(/\s+/); + if (!w[0]) return; + if (w[0] === 'PKT') { + const n = +w[1]; + if (!(n > 0 && n <= 0x100000)) return; + if (st.phase === 'wait' && !st.started) { st.started = true; log('start', {}); } + rx = { n, off: 0, idx: 0, data: new Uint8Array(n) }; + need = 16 + Math.min(0x1000, n); + await line('ACK'); + return; + } + if (w[0] === 'ACK') { onAck(); return; } + if (w[0] === 'NAK') { if (tx && tx.started) sendChunk().catch(fail); return; } + if (w[0] === 'ENQ') { if (tx) { tx.idx = +w[1] || 0; tx.started = true; sendChunk().catch(fail); } return; } + if (w[0] === 'CAN') { if (tx) { const f = tx.fail; tx = null; f(new Error('cancelled by the Paradise')); } else if (st.phase !== 'done') fail(new Error('cancelled by the Paradise')); return; } + if (w[0] === 'ECHO') { if (w[1] === 'REQ') await line('ECHO REP'); return; } + if (w[0] === 'SYNC') return; // we sent ours with BREED 0 + } + async function pump() { + for (;;) { + if (need) { + if (buf.length < need) return; + const c = buf.slice(0, need); buf = buf.slice(need); need = 0; + await chunk(c); + continue; + } + let j = -1; + for (let i = 0; i + 1 < buf.length; i++) if (buf[i] === 13 && buf[i + 1] === 10) { j = i; break; } + if (j < 0) { if (buf.length > 256) buf = buf.slice(buf.length - 64); return; } + const s = new TextDecoder('latin1').decode(buf.subarray(0, j)); buf = buf.slice(j + 2); + await command(s); + } + } + return { + state: st, + feed(bytes) { + if (st.stopped) return queue; + const b = new Uint8Array(buf.length + bytes.length); b.set(buf, 0); b.set(bytes, buf.length); buf = b; + queue = queue.then(pump).catch(fail); + return queue; + }, + stop() { st.stopped = true; idle(false); if (tx) clearTimeout(tx.timer); tx = null; rx = null; }, + }; + } + + const api = { ED, createVisitor, parseKey, crypt, crc16 }; + if (typeof module === 'object' && module.exports) module.exports = api; + else root.ParamixVisit = api; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/src/wolf.js b/src/wolf.js new file mode 100644 index 0000000..0fb5b4d --- /dev/null +++ b/src/wolf.js @@ -0,0 +1,182 @@ +/* + * Paramix Studio: Wolfenstein 3D for the Paradise, the data pack. + * The user brings the game files (shareware .WL1 or full version .WL6); they never leave the computer. + * The Studio only reads them in the browser and puts what the program needs into one pack for the flash. + * + * Pack "W3DP" (little endian, offsets from the start of the pack): + * 0 'W3DP' 4 version (1) 8 flags (bit 0 shareware) 12 total length + * 16 pages: count, first sprite, table offset (table: offset u32, length u32; walls 64x64 by columns, sprites as in VSWAP) + * 28 maps: count, RLEW tag, table offset (table: offset u32 or 0; map header 38 bytes as in GAMEMAPS, plane starts + * relative to the pack, planes Carmack + RLEW packed as in GAMEMAPS) + * 40 sounds: count, table offset (PC speaker sounds: offset u32, length u32; data = u32 length, u16 priority, bytes) + * 48 pics: count, table offset (table: offset u32, width u16, height u16; 8-bit, rows from the top) + * 56 reserved 60 episodes + * Pics: the range L_COLONPIC .. GETPSYCHEDPIC of the game (91 pics, same order in all versions; TITLEPIC is pic 43). + * Spear of Destiny (.SOD, flags bit 1): the same 91 places taken from its own chunks (title from its two halves), then + * its faces GODMODEFACE1..3, BJWAITING1..2, BJOUCH (pics 91..96). One episode of 21 floors. + * + * Author: mameise + */ +(function (root) { +'use strict'; + +const u16 = (b, o) => b[o] | (b[o + 1] << 8); +const s32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)); +const u32 = (b, o) => s32(b, o) >>> 0; +const u24 = (b, o) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16); +function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >> 8) & 255; } +function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; } + +const NUMSOUNDS = 87; // audiowl6.h LASTSOUND (shareware and full version) +const NUMSOUNDS_SOD = 81; // audiosod.h +// Spear of Destiny 1.4 (170 chunks): its chunk for each of the 91 places (gfxv_sod.h); TITLE (43) = TITLE1 above TITLE2 +// the game palette of SOD (sodpal.inc of Wolf4SDL, 6-bit RGB): its title has a palette of its own (TITLEPALETTE, chunk +// 153), the program shows every pic with the game palette, so the title is taken to the nearest colours +const SOD_PAL_B64 = 'AAAAAAAqACoAACoqKgAAKgAqKhUAKioqFRUVFRU/FT8VFT8/PxUVPxU/Pz8VPz8/Ozs7Nzc3NDQ0MDAwLS0tKioqJiYmIyMjHx8fHBwcGRkZFRUVEhISDg4OCwsLCAgIPwAAOwAAOAAANQAAMgAALwAALAAAKQAAJgAAIgAAHwAAHAAAGQAAFgAAEwAAEAAAPzY2Py4uPycnPx8fPxcXPxAQPwgIPwAAPyoXPyYQPyIIPx4AORsAMxgALRUAJxMAPz82Pz8uPz8nPz8fPz4XPz0QPz0IPz0AOTYAMzEALSsAJycAISEAHBsAFhUAEBAAND8XMT8QLT8IKD8AJDkAIDMAHS0AGCcANj82Lz8uJz8nID8fGD8XED8QCD8IAD8AAD8AADsAADgAADUAATIAAS8AASwAASkAASYAASIAAR8AARwAARkAARYAARMAARAANj8/Lj8/Jz8/Hz8+Fz8/ED8/CD8/AD8/ADk5ADMzAC0tACcnACEhABwcABYWABAQFy8/ECw/CCo/ACc/ACM5AB8zABstABcnNjY/Li8/Jyc/HyA/Fxg/EBA/CAk/AAE/AAA/AAA7AAA4AAA1AAAyAAAvAAAsAAApAAAmAAAiAAAfAAAcAAAZAAAWAAATAAAQCgoKPzgNPzUJPzMGPzACPy0AAA4AAAoAJgA5IAAzHQAtGAAnFAAhEQAcDQAWCgAQPzY/Py4/Pyc/Px8/Pxc/PxA/Pwg/PwA/OAA5MgAzLQAtJwAnIQAhGwAcFgAWEAAQPzo3Pzg0PzYxPzUvPzMsPzEpPy8nPy4kPywgPykcPycYPCUXOiMWNyIVNCAUMh8TLx4SLRwRKhoQKBkPJxgOJBcNIhYMIBQLHRMKGxIJFxAIFQ8HEg4GEAwGDgsFCggDGAAZABkZABgYAAAHAAALDAkEEgASFAAUAAANBwcHExMTFxcXEBAQDAwMDQ0NNj09Ljo6Jzc3HTIyEjAwCC0tCCwsACkpACYmACMjACEhAB8fAB4eAB0dABwcABsbJgAi'; +function b64(s) { if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(s, 'base64')); const t = atob(s), o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; } +function toGamePal(px, pal) { + const gp = b64(SOD_PAL_B64), map = new Uint8Array(256); + for (let c = 0; c < 256; c++) { + let best = 0, bd = 1e9; + for (let j = 0; j < 256; j++) { const dr = pal[3 * c] - gp[3 * j], dg = pal[3 * c + 1] - gp[3 * j + 1], db = pal[3 * c + 2] - gp[3 * j + 2], d = 3 * dr * dr + 4 * dg * dg + 2 * db * db; if (d < bd) { bd = d; best = j; } } + map[c] = best; + } + return px.map((v) => map[v]); +} +function sodChunk(k) { + if (k <= 41) return 37 + k; // L_COLONPIC .. L_BJWINSPIC + if (k >= 47 && k <= 87) return 54 + k; // KNIFEPIC .. GOTGATLINGPIC + if (k >= 91) return 51 + k; // GODMODEFACE1PIC .. BJOUCHPIC + return { 42: 90, 43: 79, 44: 91, 45: 92, 46: 29, 88: 142, 89: 148, 90: 149 }[k]; +} +const PIC_FIRST = { 150: 44, 157: 56 }; // chunk of L_COLONPIC by number of chunks (Activision/GT 1.4, Apogee 1.4) +const PIC_COUNT = 91; // L_COLONPIC .. GETPSYCHEDPIC +// used by the program: STATUSBAR (42, its colour), TITLE (43), weapons, keys, digits, faces, PAUSED, GETPSYCHED (47..90) +const PIC_USED = (k) => k === 42 || k === 43 || k >= 47; + +const NEED = ['VSWAP', 'MAPHEAD', 'GAMEMAPS', 'AUDIOHED', 'AUDIOT', 'VGAHEAD', 'VGADICT', 'VGAGRAPH']; + +/** files: { 'VSWAP.WL1': Uint8Array, ... } (any case). Returns { ext, files } of one complete set or throws. */ +function pickSet(files) { + const by = {}; + for (const n of Object.keys(files)) { + const m = /^([A-Za-z]+)\.(WL1|WL6|SOD)$/i.exec(n.replace(/^.*[\\/]/, '')); + if (m) (by[m[2].toUpperCase()] = by[m[2].toUpperCase()] || {})[m[1].toUpperCase()] = files[n]; + } + for (const ext of ['WL6', 'SOD', 'WL1']) { + const s = by[ext]; if (!s) continue; + const miss = NEED.filter((k) => !s[k]); + if (!miss.length) return { ext, files: s }; + } + const have = Object.keys(by); + if (!have.length) throw new Error('no Wolfenstein 3D files (.WL1, .WL6 or .SOD)'); + const ext = have.includes('WL6') ? 'WL6' : have.includes('SOD') ? 'SOD' : 'WL1'; + throw new Error('missing: ' + NEED.filter((k) => !by[ext][k]).map((k) => k + '.' + ext).join(', ')); +} + +function huffExpand(src, so, len, nodes) { + const out = new Uint8Array(len); let o = 0, n = 254, i = so, val = src[i++], mask = 1; + while (o < len) { + const v = (val & mask) ? nodes[2 * n + 1] : nodes[2 * n]; + if (mask === 0x80) { val = src[i++]; mask = 1; } else mask <<= 1; + if (v < 256) { out[o++] = v; n = 254; } else n = v - 256; + } + return out; +} + +function readGraph(head, dict, graph) { + const nchunks = Math.floor(head.length / 3); + const nodes = new Uint16Array(255 * 2); for (let i = 0; i < 510; i++) nodes[i] = u16(dict, 2 * i); + const pos = (c) => { const v = u24(head, 3 * c); return v === 0xFFFFFF ? -1 : v; }; + const chunk = (c, explicit) => { + const p = pos(c); if (p < 0) return null; + let q = c + 1; while (q < nchunks && pos(q) < 0) q++; + const len = explicit !== undefined ? explicit : s32(graph, p); + return huffExpand(graph, explicit !== undefined ? p : p + 4, len, nodes); + }; + return { nchunks, chunk }; +} + +function deplane(d, w, h) { + const out = new Uint8Array(w * h), pw = w >> 2; let s = 0; + for (let p = 0; p < 4; p++) for (let y = 0; y < h; y++) for (let x = 0; x < pw; x++) out[y * w + (x << 2) + p] = d[s++]; + return out; +} + +/** Build the pack. files: complete set (see pickSet). */ +function build(files) { + const { ext, files: f } = pickSet(files); + const sod = ext === 'SOD', nsnd = sod ? NUMSOUNDS_SOD : NUMSOUNDS; + const parts = []; let size = 64; + const add = (b) => { const o = size; parts.push([o, b]); size += b.length; size = (size + 3) & ~3; return o; }; + const hdr = new Uint8Array(64); + // pages (walls and sprites, no digitized sounds) + const vs = f.VSWAP, nch = u16(vs, 0), spr = u16(vs, 2), snd = u16(vs, 4); + // walls are 64 x 64 (4096 bytes); modified games (MacenWolf: 128 x 128) do not run with this program + for (let i = 0; i < spr; i++) { const len = u16(vs, 6 + 4 * nch + 2 * i); if (len && len !== 4096) throw new Error('VSWAP.' + ext + ': walls not 64 x 64 (a modified game?), version 1.4 needed'); } + const npages = snd, ptab = new Uint8Array(npages * 8); + for (let i = 0; i < npages; i++) { + const off = u32(vs, 6 + 4 * i), len = u16(vs, 6 + 4 * nch + 2 * i); + if (!off || !len || off + len > vs.length) continue; + w32(ptab, 8 * i, add(vs.subarray(off, off + len))); w32(ptab, 8 * i + 4, len); + } + w32(hdr, 16, npages); w32(hdr, 20, spr); w32(hdr, 24, add(ptab)); + // maps + const mh = f.MAPHEAD, gm = f.GAMEMAPS, tag = u16(mh, 0); + let nmaps = 0; const moff = []; + for (let i = 0; 2 + 4 * i + 4 <= mh.length && i < 100; i++) { const o = s32(mh, 2 + 4 * i); moff.push(o > 0 && o + 38 <= gm.length ? o : 0); if (moff[i]) nmaps = i + 1; } + const mtab = new Uint8Array(nmaps * 4); + for (let i = 0; i < nmaps; i++) { + const o = moff[i]; if (!o) continue; + const h = new Uint8Array(gm.subarray(o, o + 38)); + const at = add(h); + for (let p = 0; p < 3; p++) { + const ps = s32(gm, o + 4 * p), pl = u16(gm, o + 12 + 2 * p); + w32(h, 4 * p, ps > 0 && pl ? add(gm.subarray(ps, ps + pl)) : 0); + } + w32(mtab, 4 * i, at); + } + w32(hdr, 28, nmaps); w32(hdr, 32, tag); w32(hdr, 36, add(mtab)); + // PC speaker sounds + const ah = f.AUDIOHED, at = f.AUDIOT, stab = new Uint8Array(nsnd * 8); + for (let i = 0; i < nsnd && 4 * i + 8 <= ah.length; i++) { + const a = u32(ah, 4 * i), b = u32(ah, 4 * i + 4); + if (b > a && b <= at.length) { w32(stab, 8 * i, add(at.subarray(a, b))); w32(stab, 8 * i + 4, b - a); } + } + w32(hdr, 40, nsnd); w32(hdr, 44, add(stab)); + // pictures + const g = readGraph(f.VGAHEAD, f.VGADICT, f.VGAGRAPH); + const first = sod ? (g.nchunks === 170 ? 0 : undefined) : PIC_FIRST[g.nchunks]; + if (first === undefined) throw new Error('unknown version of VGAHEAD (' + g.nchunks + ' chunks)'); + const st = g.chunk(0); // STRUCTPIC: width, height of every pic from chunk 3 + const pics = []; for (let k = 0; k < PIC_COUNT + (sod ? 6 : 0); k++) pics.push(sod ? sodChunk(k) : first + k); // TITLEPIC is pic 43 + const pic = (c) => { + const w = s16v(st, 4 * (c - 3)), h = s16v(st, 4 * (c - 3) + 2), d = g.chunk(c); + if (!d || w <= 0 || h <= 0 || (w & 3) || d.length < w * h) return null; + return { w, h, px: deplane(d, w, h) }; + }; + const xtab = new Uint8Array(pics.length * 8); + pics.forEach((c, k) => { + if (!PIC_USED(k)) return; // pictures the program never shows stay out (flash) + let p = pic(c); + if (p && sod && k === 43) { // the title of SOD comes in two halves + const q = pic(c + 1); + if (q && q.w === p.w) { const px = new Uint8Array(p.w * (p.h + q.h)); px.set(p.px); px.set(q.px, p.w * p.h); p = { w: p.w, h: p.h + q.h, px }; } + const tp = g.chunk(153); // TITLEPALETTE + if (tp && tp.length >= 768) p.px = toGamePal(p.px, tp); + } + if (!p) return; + w32(xtab, 8 * k, add(p.px)); w16(xtab, 8 * k + 4, p.w); w16(xtab, 8 * k + 6, p.h); + }); + w32(hdr, 48, pics.length); w32(hdr, 52, add(xtab)); + const episodes = sod ? 1 : Math.max(1, Math.floor(nmaps / 10)); + w32(hdr, 60, episodes); + hdr.set([0x57, 0x33, 0x44, 0x50]); w32(hdr, 4, 1); w32(hdr, 8, (ext === 'WL1' ? 1 : 0) | (sod ? 2 : 0)); w32(hdr, 12, size); + const out = new Uint8Array(size); out.set(hdr); + for (const [o, b] of parts) out.set(b, o); + return { pack: out, ext, maps: nmaps, episodes, sod }; +} +function s16v(b, o) { const v = u16(b, o); return v > 32767 ? v - 65536 : v; } +root.ParamixWolf = { pickSet, build, readGraph, NEED }; +if (typeof module !== 'undefined') module.exports = root.ParamixWolf; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/t18/README.md b/t18/README.md new file mode 100644 index 0000000..bb2c8a4 --- /dev/null +++ b/t18/README.md @@ -0,0 +1,224 @@ +# T18Emu for the Tamagotchi Paradise + +An emulator for the Tamagotchi Meets and On (TG18 firmware, ARM7TDMI with the +GPEL3101A peripherals) that runs on the Paradise (Cortex-M3, 96 MHz). The +Studio builds it into the ROM together with the user's own 8 MB firmware. No +firmware is part of this repository. + +- `t18.bin` and `t18x.bin`: the program. The TamaEmu launcher copies `t18.bin` + (64 KB at most) to PRAM and starts it; `t18x.bin` is the code that is not hot, + run from the flash window (flash 0x0F0000). Its settings block ("PMX8") is at + 0x140 and is filled in by the Studio (`src/emu.js`, `t18Patch`). Flag bit 1: + set the clock to the Paradise's time at every start. Flag bit 12 (1.7.3 test7, `SESS_FLAG`): no session; only + the firmware's own save is written, an old session is dropped and the firmware boots as on the toy. +- `src/core`: the core from the T18Emu app by mameise, slimmed down for the + Paradise: + - `t18cpu.c`: ARM7TDMI interpreter. Guest SRAM (0xF8000000) is the Paradise + SRAM, the firmware is reached through a map of 64 KB blocks. Idle rounds: + a round of a loop that changes nothing (same registers, SRAM as before, only + reads of registers that hold still until the next event) is watched once, + then the further rounds up to the next event are skipped. The result is the + same as without skipping, instruction by instruction. + - `t18jit.c`: translator from ARM and Thumb code to Thumb-2 for the + Cortex-M3. A block only runs when the cycle budget covers it, so interrupts + come at the same instruction as in the interpreter; SRAM accesses are + direct, the rest goes to the SoC. `t2enc.h` encodes the instructions. + - `t18soc.c`: the SoC (timers, interrupts, RTC, SPI flash, DMA, LCD, tone). +- `src/app`: the Paradise side (`main.c`): screen, keys, tone, flash writes of + the firmware (two 4 KB sectors held in RAM; empty blocks the firmware writes + get 4 KB sectors from the spare blocks, `T18_SEC_SPARE`), session, clock note. +- `host/ref.c`: the core on the PC as the reference (script commands wait, + press, hash, shot, sram, flash, armprof, acnt). +- `test`: `m3main.c` with `m3run.py` runs the core with the translator in + Unicorn on a Cortex-M3 with the memory of the Paradise (PRAM 64 KB, RAM at + 0x20000000 only 4 KB, writes into the PRAM only from the flash window) and compares with the reference (hash lines) and counts + host instructions per emulated second. `devt18.py` runs the whole `t18.bin` on + a simulated Paradise (screen pictures, keys, speed per second). + +## Memory on the Paradise + +The RAM at 0x20000000 has only 4 KB (mirrored 16 times), and they belong to the +Paradise firmware: nothing of T18Emu is there (1.5.0 put its data there, which +is why it hung on the device). Writing the PRAM while the CPU fetches code from +it corrupts instructions (known from TamaEmu), so the PRAM is only written by +`t18_pram_w16`, which writes whole words (1.6.2: a halfword write on the device +fills the other half of the word with the halfword written last) and runs from the SRAM (in `.data`, like the copy loop of +TamaEmu) with interrupts off. Without `T18_PRAM_WR_SRAM` it runs from the flash +window (1.5.1 to 1.5.3; E1 at the start on the device). + +| Where | What | +| --- | --- | +| PRAM 0x00000000 (64 KB) | hot code; from `__jc_start` on (over the start code) the translated code | +| flash window 0x100DF000 (flash 0x0F0000) | the rest of the code (`.xip`), first word "T18X" and the build number | +| SRAM 0x18000000..0x18020000 | guest SRAM 0xF8000000 1:1, except for the hole | +| SRAM 0x1800E600..0x18014400 (the hole) | stack (2 KB, bottom), data, tables, pages for the guest's bytes in the hole | + +The guest SRAM is the Paradise SRAM itself (host = guest + 0x20000000). All five +TG18 firmwares only zero 0xF800E600..0xF8014400 at the start and use a few +hundred bytes of it later (both stacks lie above it), so that range holds +T18Emu's own data. The guest's bytes there live in pages of 512 bytes, made on +the first non-zero write (8 pages; out of pages: red screen with code E2). +The translated code checks every SRAM access for the hole (two compares); the +stack pointer is used directly only above it (checked before each block that +uses it). + +Errors show a red screen: E1 fault (two columns: PC LR, CFSR fault address, start +stage 1 to 8 and the firmware's PC, r0 r1, r2 r3, r12 xPSR, SP EXC_RETURN, HFSR and +the number of translated blocks with bit 31 set when the translator is off), E6 +self test of PRAM code failed (the two results, expected 5A and A5), E2 out of +pages for the hole, E3 stack overflow, E4 the flash part is missing or from +another build, E5 state too big. The wheel goes back to the Paradise. + +Holding B while T18Emu starts switches the translator off (interpreter only, +about 60 % speed, for tests on the device). + +## Layout in the Paradise flash + +| Offset | What | +| --- | --- | +| 0x0A0000 | program (copied to PRAM on start) | +| 0x0C0000 | block map as it is now ("T8MP": spares in use; at +0x144 "T8SS": the sector table of `T18_SEC_SPARE`) | +| 0x0C1000 | clock note ("T8NT": seconds counter and game time when leaving) | +| 0x0C2000 | session ("T8SS": CPU and SoC state, then the 128 KB SRAM) | +| 0x0F0000 | the code part of the program (`t18x.bin`, up to 64 KB) | +| free 64 KB blocks, from 0xF00000 and from 0xD40000 downwards | the firmware's used blocks, then up to 10 spares; the bottom stays for the field saves | + +## Build + +``` +sh src/app/build.sh # arm-none-eabi-gcc; writes t18.bin and t18x.bin +KEEPELF=1 sh src/app/build.sh # keeps src/app/t18.elf for devt18.py +``` + +## Speed switches (1.6.8) + +build.sh sets them (REL). Each one keeps the results bit for bit as the reference (checked without T18_OVERSHOOT): +- T18_IO_FAST: the device registers the firmware polls most (timer control, buttons, interrupt vector and mask) are + read straight from the translator's slow path, without io_rd in the flash window. +- T18_SPCHK_MOD: only blocks that move sp check it at their start (push, pop, add/sub sp; add/mov sp, rX is left + to the interpreter). +- T18_TIERUP: SysTick notes the interrupted pc in the code buffer; a block hit three times while it uses the shared + check routine is translated again with the checks inline. +- T18_IDLE_CAP, T18_IDLE_DISARM, T18_IDLE_PASS: idle tries away from the known idle pc stop after 256 steps; the + known idle pc is given up after 32 failed tries in a row; once tried in a run it no longer stops the translated code. +- T18_XRET: a conditional return from an exception (ldmcc ..., {..., pc}^) no longer splits the interrupt handler. + +- T18_CLOCK_AFTER: when the firmware sets its battery clock (first setup), the Paradise's time is applied again + 500 ms later. +- T18_RADIO: the Bluetooth module of the Meets/On (SPI 0xC0080000, chip select GPIO 0xC0000064 bit 12) answers + like the real one without a phone (register 0x0A boot/patch/running, register 0x08 bytes waiting, setup + answers, module memory reads, HCI Command Complete). Without it the camera (item box, Special) stayed at READY? + and took no key. About 300 bytes in the SoC struct, outside the saved state. + +- T18_TONE_Q: the tone in real time. Tone changes are queued with the game time and played on the Paradise's + clock 300 ms after the first of a sequence; below 100 % a melody keeps its tempo (late by more than 200 ms: + timing starts anew). +- T18_IDLE_MEMO: the last skippable idle round at the known idle pc is kept with every value it read (memory and + registers that hold still); the same start and the same values now skip it without stepping (living room: + ~900 rounds a second were single-stepped). The guest flash counts as one value (t18_flash_gen). +- T18_IDLE_BACKOFF=13: tries away from the idle pc back off up to 2000 << 13 master ticks after failing. +- T18_JH_PROBE=16: the block table searches 16 slots (with 8, busy keys pushed each other out before they got hot + and were interpreted every time). +- T18_JT_MUL: multiplicative hash for the indirect jump cache (the old one put 4 of the 10 busiest return + addresses of the egg scene into one set). +- 1.6.8-test3 T18_GROW2: grow up with the clock at x60 only for the game minute before a step (age set just before it), + the step and its animation in real time, 18 s for it before the next jump (test4, was 25 s); the game kept awake (tg18_set_keep_awake, + as Android). x60 all along was too much for the Paradise (slow animation) and let the game's minutes run (hunger, + illness). The Param address is only used inside the guest SRAM (PA_OK). On the PC: GROW2=1 with the script command + grow (T18_GROW_TEST): Bernd's Tama baby to Pompomtchi in 72 s, hunger 6, mood 30, never asleep. +- 1.6.9 test14 T18_SUM_FNV: the row check of present() (rotate by 5, xor per pixel pair) repeats its rotations every + 32 pairs (64 pixels), folded to 16 bits for T18_LINK every 16 pairs: equal changes 32 pixels apart cancel, a row of + one colour always gives the same value. Rows that changed stayed old on the panel (AM/PM on the clock, frames in the + stats). Now FNV-1a per pixel pair (multiply). PC model (host/ref.c, FNV=1, STALE=1 prints rows that differ from the + buffer at the end of each pseq): clock page with A, old 1 to 2 rows, new 0. T18_ROW_RR: one row per picture (by + the time) goes out anyway. T18_PRES_FIRST: the row sums at 0x20000D00 are set to 0x5A5A at the start. + T18_WAKE_ASYNC (with WAKE_ASYNC in hw.c): the panel comes on in steps from the main loop (SLPOUT, 125 ms, DISPON, + 20 ms, light, then a whole picture) instead of 145 ms of waiting in hw_backlight. In standby the firmware switches + the screen on for about 2 s with each call reminder (PC: every 60 s). +- 1.6.9 test11 and test12 (T18_PRESENT_GATE, presents at each transfer or gated) were worse on the device (slide from + the top, parts missing, old picture left): taken out again in test13, main.c and build.sh are as in test10 + (T18_PRESENT_IDLE + T18_PRESENT_STABLE). The panel model in host/ref.c (-DT18_PANEL_MODEL -DT18_PRES_PARA, + POLICY=old|xfer, GATE=1) stays for later work. The code of test12 is in its handover. +- 1.6.8-test7 T18_LINK infrared: CONNECTION, TAMAGOTCHI between two Paradise. As the Android LinkManager the IR byte + stream goes 1:1 to the other device: ur_tx hands each byte to tg18_link_ir_out (sent as 'I' frames of up to 36 + bytes, flushed every loop), ur_feed takes them from tg18_link_ir_in at line rate when tg18_link_ir_avail. The parser + takes 5A (PC) and A5 (another Paradise) as start, so two Paradise plugged together at the top talk directly; the Studio does not take part. Link block at 0x20000E00 now checked to stay below 0x20000F00 (test6 was 276 bytes and wrote + into the spare rows). Checked on the PC: host/pair.py runs two ref cores in lockstep (linkrun): playdate, both + connect, the guest appears in the host's room, TOGETHER AGAIN, guest home with PLAYED WITH .... +- 1.6.8-test6 T18_LINK: Bluetooth visits and marriages (mixing-meets.com) over the UART on the contacts (UART1 0x4000B000, + IRQ 37, 460800 8N1 as the flash program). Core: tg18_ble_connect / tg18_ble_from_phone (22 len data into the module's + queue, 64 bytes kept for the module's own answers), tg18_link_out (data for the phone, given by the platform), register + 0x0A bit 0x0004 once connected and set up (as Android radio.c). Device: frames 5A type len data sum ('C' connect, 'W' + write, 'P' alive) and A5 .. ('H' hello every second, 'N' notification, 'K' write taken); ring buffer and state at + 0x20000E00 (the row sums are 16 bit with T18_LINK). PC side: the bookmarklet in src/app.js (pmxBridge) replaces + navigator.bluetooth on the page with Web Serial. Checked on the PC: host/ref.c "blereplay " (as + tools/ble/mmphone.py of the Android T18Emu) with Bernd's capture of a visit and marriage: same answers as the real + device (F0 0C 70 A1, F0 0D 04 01), the Tama comes home with an egg, the baby hatches. Navigation on the PC: CONNECTION, + APP, VISIT; back: A until GO BACK? YES, B. Note: a Tama with a call or flag +0x16 bit 7 set does not open CONNECTION. +- 1.6.8-test4 T18_DAY_FIX: the firmware counts the days itself (soft clock +0x2C, days since 2007-12-31, one up when the + hour goes from 23 to 0) and a new start loads them from its save (CONTINUE): time right, date of leaving. The note + (T18_NOTE_SEC) keeps the game's day and the clock's day at leaving (gday, rday; 0xFFFFFFFF in older notes); during the + first 5 minutes, when the game shows that day again, it gets the days since added once (not 23:55 to 0:05). A resumed + session needs nothing (tg18_set_time moves the day counter itself). +- 1.6.8-test3 T18_WAKE_START: 0.6 s after the start a sleeping game (screen dark) gets one short C, as the Android + T18Emu does when it becomes visible. Before, the screen stayed black until a key. +- 1.6.8-test1 T18_GROW (with ASK_EXTRA in ask.c): grow up from the settings (Param block address and the Sanrio flag + from the Studio in the settings at +428/+432, pictures at +436). Items: the Studio writes changed sectors of the + guest flash into the installed program in place (`t18RomWriteGuest` in src/emu.js: mapped blocks, sector table, + new pool sectors) and drops the session. +- test45 T18_SEC_SPARE: spares by the 4 KB sector for empty guest blocks (tables in the Paradise RAM, saved as "T8SS" in + the map sector). With 6 spare blocks the old way lost the 7th block the firmware writes (photo, diary). +- test44: RM_N (48) and W_LOG (32, was 64) can be set with -D; TQ_N 32. With 64 the build no longer fit the hole. + Code that runs before the flash window is set up (Reset_Handler up to hw_init) must stay in the PRAM; + build.sh checks it. +M3 (Minstr per guest second, plus uncached flash reads at 96 each): egg 121.7 -> 98.7, call 84.5 -> 80.5, +living room 75.8 -> 55.6. Exact as before (suite 20 of 20, without T18_OVERSHOOT). + +## Tests + +``` +gcc -O2 -o ref host/ref.c src/core/t18soc.c src/core/t18cpu.c -lz +./ref fw_tg18.bin script.txt +gcc -O2 -DT18_HOLE_LO=0xE600u -DT18_HOLE_HI=0x14400u -o refh host/ref.c src/core/t18soc.c src/core/t18cpu.c -lz # the hole on the PC +sh test/build_m3.sh /tmp/m3.elf -DT18_JIT -DT18_JC_LINKED -DT18_PRAM_WR -DJH_BITS=8 -DJT_BITS=8 -DJ_HOT=8 +python3 test/m3run.py /tmp/m3.elf fw_tg18.bin script.txt # same hash lines as ./ref +python3 test/devt18.py src/app/t18.elf paradise_with_t18.bin 30000 # PARA="2026-10-15 18:42:07": a Paradise clock in the SRAM +``` + +## Power save while the game sleeps (T18_PW, T18_LOOP_XIP, T18_WHEEL_RAW, 1.6.13 test1) + +Measured on the PC (ref): without a key the TG18 firmware switches itself off after about 3 minutes (screen dark) and +then only waits for its RTC alarm (once a minute, on for about 100 ms) or a key; the core runs no instructions then +(off_run). The program still ran its loop every ms at 96 MHz (or the eco clock). + +- T18_PW: game off, screen dark, no key, tone, link or grow-up: the chip from its internal 12 MHz RC, PLL and crystal + off; deep sleep once caught up, the RTC (1 s) or a key wakes it, the ms tick continues from the RTC (as T7Emu). + The game's time passes in steps of 8 ms with tg18_run_us_off (nothing runs while it is off; when the alarm or a key + switches it on, the platform goes back to 96 MHz first). Not dropped while off; screen dark: up to 5 s behind before + time is dropped (250 ms with the screen on). +- T18_LOOP_XIP: the main loop, present, tq_pump, lk_poll and the font of ask.c run from the flash window: the code + buffer in the PRAM starts at 0x83E4 instead of 0x9154 (+3.4 KB). +- T18_WHEEL_RAW: the wheel's long press is timed with a tick count that is never set ahead (deep sleep). + +Device simulation (devt18.py now models clock source and deep sleep), 330 s from the start without a key: game off +from 194 s, then asleep 98 % of the time, awake at 12 MHz 1 %, at 96 MHz for the minute alarms. M3 test bed with the +device's buffer (babyh, 210 s guest, buffer from 0x826C): 63.6 -> 60.2 Minstr per guest second (-5 %), half the +buffer flushes (900 instead of 1817). + +## Known addresses in the translator (T18_KNOWN, T18_SPEC, 1.6.13 test2) + +M3 profile of the busy scenes: a third of the host time went into the slow path of memory accesses. The firmware +polls 0xD0000064 (SPI busy, always 0) before every register write and moves the bytes of the SPI flash through the +SPI registers 0xC0150000..0C (status, send, answer), six device accesses per byte, each through j_slow. + +- T18_KNOWN: per block, registers with a value known while translating (MOV/MVN immediate, ADD/SUB immediate of a + known register or the pc, literal loads; Thumb: MOV/ADD/SUB #imm8, LDR pc, ADR, MOV high). A load or store at a known + address in the SRAM (not the hole, aligned) is done directly; 0xD0000064 is loaded as 0; the SPI registers go + straight to the SPI model (loads inline from the model's words, stores through j_sfw -> tg18_sf_fast). +- T18_SPEC: the same for these device registers when the base register was set before the block (the SPI loops): + the value it has when the block is translated is checked at run time (cmp/bne), otherwise the usual way. The glue + that translates from inside the code buffer (j_chain, the lookup of j_ind) writes r0..r7 into arm7_t first. +- The same accesses in the same order with the same cycles: M3 hash lines identical to the build without them. + +M3 test bed (without T18_OVERSHOOT, hash lines compared): SPI phase (making the save) 173 -> 137 Minstr per guest +second (-21 %), the scene after it 107 -> 95 (-12 %), egg 27 -> 25 (-8 %). diff --git a/t18/host/ref.c b/t18/host/ref.c new file mode 100644 index 0000000..c2b3e56 --- /dev/null +++ b/t18/host/ref.c @@ -0,0 +1,429 @@ +/* PC run of the T18 core with the Paradise memory map (reference for the JIT and the device). + * ref