Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Retro-Go: Master System and Game Gear
Mason3634a77b4528ddc
diff --git a/README.md b/README.mdindex 4caac319..313a2416 100644--- a/README.md+++ b/README.md@@ -87,15 +87,15 @@ These are too big to fit next to NumPlay, so each one is its own app. Install it</tr></table>-## Your own Game Boy and NES games+## Your own Game Boy, NES and Sega games<table><tr>- <td align="center" width="33%"><a href="games/retrogo/README.md"><img src="docs/media/thumb_retrogo.png" width="200" alt="Retro-Go"><br><b>Retro-Go</b></a><br><sub>Game Boy, Game Boy Color and NES games, with Retro-Go's menus and save slots</sub></td>+ <td align="center" width="33%"><a href="games/retrogo/README.md"><img src="docs/media/thumb_retrogo.png" width="200" alt="Retro-Go"><br><b>Retro-Go</b></a><br><sub>Game Boy, Game Boy Color, NES, Master System and Game Gear games, with Retro-Go's menus and save slots</sub></td></tr></table>-Retro-Go plays the Game Boy, Game Boy Color and NES games you choose: games you own, or free ones like homebrew games. It isn't in NumPlay.nwa: you get it, with your games inside, from NumPlay's customizer website.+Retro-Go plays the Game Boy, Game Boy Color, NES, Master System and Game Gear games you choose: games you own, or free ones like homebrew games. It isn't in NumPlay.nwa: you get it, with your games inside, from NumPlay's customizer website.## How to install@@ -186,7 +186,7 @@ Filmed on my own calculator, no emulator.- [x] The Powder Toy (NumPowder)- [x] Block Blast- [x] Undertale: the whole Underground, from the Ruins to New Home and the neutral ending-- [x] [Retro-Go](https://github.com/ducalex/retro-go) for Game Boy, Game Boy Color and NES: upload your own ROMs on the website and get a .nwa app that plays them+- [x] [Retro-Go](https://github.com/ducalex/retro-go) for Game Boy, Game Boy Color, NES, Master System and Game Gear: upload your own ROMs on the website and get a .nwa app that plays them- [ ] The Binding of Isaac- [ ] Plants vs. Zombies- [ ] Doom@@ -222,7 +222,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks- **Buckshot Roulette** by Mike Klubnika inspired NumPlay's Buckshot Roulette, whose scenes are rendered from the game through the Open Buckshot Roulette project (1503Dev). Fonts: Fake Receipt by Ray Larabie and Dot Matrix by Dionaea.- The **Doodle Champion Island Games** (2021) inspired Champion Island, which uses the doodle's own pictures, maps and texts from the [Google-Doodle-Champion-Island](https://github.com/potherca-blog/Google-Doodle-Champion-Island) archive by potherca-blog, and the **PixelMplus** font by Itou Hiroki ([license](LICENSES/PixelMplus.txt)).- **[Portal Returns](https://www.cemetech.net/downloads/files/1313/x1313)** by MateoConLechuga for the TI-84 Plus CE, with sprites by CKH4 and Portal Prelude chambers ported by Unicorn from BuilderBoy's original.-- **[Retro-Go](https://github.com/ducalex/retro-go)** by ducalex inspired NumPlay's Retro-Go, whose launcher, menus and frame skipping are written again for NumPlay with no code copied from it. Its emulators are **[gnuboy](https://github.com/rofl0r/gnuboy)** by Laguna and Gilgamesh (GNU GPL v2 or later) for the Game Boy and **nofrendo** by Matthew Conte (GNU LGPL v2, used under the GPL) for the NES. Its tests use Blargg's test ROMs, Matt Currie's dmg-acid2 and cgb-acid2 and kevtris's nestest. Not affiliated with them.+- **[Retro-Go](https://github.com/ducalex/retro-go)** by ducalex inspired NumPlay's Retro-Go, whose launcher, menus and frame skipping are written again for NumPlay with no code copied from it. Its emulators are **[gnuboy](https://github.com/rofl0r/gnuboy)** by Laguna and Gilgamesh (GNU GPL v2 or later) for the Game Boy and **nofrendo** by Matthew Conte (GNU LGPL v2, used under the GPL) for the NES; the Master System and Game Gear are NumPlay's own, around **[superzazu's z80](https://github.com/superzazu/z80)** by Nicolas Allemand (MIT License). Its tests use Blargg's test ROMs, Matt Currie's dmg-acid2 and cgb-acid2, kevtris's nestest and Frank Cringle's zexdoc and zexall. Not affiliated with them.- The **Nunito** and **Rammetto One** fonts, under the SIL Open Font License ([LICENSES](LICENSES)).- The **Fusion Pixel** font by TakWolf (with glyphs from **Ark Pixel**), under the SIL Open Font License ([license](LICENSES/OFL-1.1-Fusion-Pixel.txt)), for the Chinese letters.- **[Upsilon](https://github.com/UpsilonNumworks/Upsilon)**, the custom software NumPlay-Upsilon.nwa runs on.@@ -235,7 +235,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorksNumPlay is licensed under the [GNU General Public License v3.0](LICENSE). Copyright (c) 2026 Mason Chen. Code and fonts from others keep their own licenses: the `UNLICENSE` files in the games' folders and the [LICENSES](LICENSES) folder. The names, artwork and music of the games NumPlay is inspired by belong to their makers and are not covered by it.-<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Hungry Studio (Block Blast!), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale), Florian van Strien (The Final Earth 2), The Powder Toy's developers (The Powder Toy), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Chrome Dino, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper), ducalex (Retro-Go), Nintendo (Game Boy, NES). Tetris is a trademark of The Tetris Company, Chrome of Google LLC, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco, Connect Four of Hasbro, and Game Boy, Game Boy Color and NES of Nintendo.</sub>+<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Hungry Studio (Block Blast!), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale), Florian van Strien (The Final Earth 2), The Powder Toy's developers (The Powder Toy), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Chrome Dino, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper), ducalex (Retro-Go), Nintendo (Game Boy, NES), Sega (Master System, Game Gear). Tetris is a trademark of The Tetris Company, Chrome of Google LLC, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco, Connect Four of Hasbro, Game Boy, Game Boy Color and NES of Nintendo, and Master System and Game Gear of Sega.</sub>## Gallerydiff --git a/docs/play.md b/docs/play.mdindex 628a3b76..efff5bf8 100644--- a/docs/play.md+++ b/docs/play.md@@ -476,12 +476,12 @@ Google's brick breaker: seven bricks across in blue, red, yellow and green, wall| Key | What it does || --- | --- || **Arrows** | Choose a system, then a game. In a game: the D-pad |-| **OK** | Open it. In a game: **A** |-| **Back** | Back to the systems. In a game: **B** |-| **shift** / **EXE** | In a game: **Select** / **Start** |+| **OK** | Open it. In a game: **A** (**2** on Sega's pads) |+| **Back** | Back to the systems. In a game: **B** (**1**) |+| **shift** / **EXE** | In a game: **Select** / **Start** (the Master System's **Pause**) || **Backspace** | Retro-Go's menu: save, load, reset, options || **Home** | Save and quit |-Game Boy, Game Boy Color and NES games you pick on NumPlay's customizer website. Open a game for New game, or Resume game from one of its 4 save slots. In a game, Backspace opens Retro-Go's menu: Save & Continue, Save & Quit, Load game, Reset and Options, where the picture can be 1x, Fit or Full screen. The cartridges' own saves are kept as well.+Game Boy, Game Boy Color, NES, Master System and Game Gear games you pick on NumPlay's customizer website. Open a game for New game, or Resume game from one of its 4 save slots. In a game, Backspace opens Retro-Go's menu: Save & Continue, Save & Quit, Load game, Reset and Options, where the picture can be 1x, Fit or Full screen. The cartridges' own saves are kept as well.<br clear="right">diff --git a/games/games.json b/games/games.jsonindex 11f2fc0c..e21e5d36 100644--- a/games/games.json+++ b/games/games.json@@ -381,7 +381,7 @@{"id": "retrogo","title": "Retro-Go",- "tagline": "Game Boy and NES games",+ "tagline": "Game Boy, NES and Sega games","credit": "Based on Retro-Go by ducalex","top": "0xE84B39","bottom": "0x1E1430",@@ -403,7 +403,9 @@"systems": [1,2,- 3+ 3,+ 4,+ 5]}]diff --git a/games/retrogo/Makefile b/games/retrogo/Makefileindex 09c86b32..4c444fb5 100644--- a/games/retrogo/Makefile+++ b/games/retrogo/Makefile@@ -1,4 +1,4 @@-# Retro-Go: Game Boy, Game Boy Color and NES games on the calculator.+# Retro-Go: Game Boy, Game Boy Color, NES, Master System and Game Gear games on the calculator.# make build output/retrogo.nwa (RetroGo.nwa), its ROM table from ROMS (none: empty)# make ROMS="a.gb b.nes" the same with those games in it, to try them (or ROMS_LIST=file:# one a line, for names with spaces)@@ -20,9 +20,10 @@ ROMS ?=GB_SRC = $(addprefix src/gb/,cpu.c hw.c mem.c lcdc.c rtc.c lcd.c gb.c)NES_SRC = $(addprefix src/nes/,nes6502.c nes_ppu.c nes_mmc.c mmclist.c nes_apu.c nes.c) \$(sort $(wildcard src/nes/mappers/*.c))-CORE_SRC = $(GB_SRC) $(NES_SRC)+SMS_SRC = src/sms/z80.c src/sms/sms.c+CORE_SRC = $(GB_SRC) $(NES_SRC) $(SMS_SRC)APP_SRC = src/main.c src/romtable.c src/pack.c-CORE_H = $(wildcard src/*.h src/gb/*.h src/nes/*.h)+CORE_H = $(wildcard src/*.h src/gb/*.h src/nes/*.h src/sms/*.h)HEADERS = $(CORE_H) ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h \../../launcher/src/gfx.h ../../launcher/src/np.h ../../launcher/src/font.h@@ -116,8 +117,12 @@ $(BUILD_DIR)/host/romtable: tests/host_romtable.c src/romtable.c src/romtable.h$(BUILD_DIR)/host/pack: tests/host_pack.c src/pack.c src/pack.h@mkdir -p $(BUILD_DIR)/host$(Q) $(HOST_CC) $(HOST_CFLAGS) tests/host_pack.c src/pack.c -o $@-test: $(BUILD_DIR)/host/core $(BUILD_DIR)/host/romtable $(BUILD_DIR)/host/pack+# (the Z80 at full speed: zexall runs 46.7 billion clocks)+$(BUILD_DIR)/host/z80: tests/host_z80.c src/sms/z80.c src/sms/z80.h+ @mkdir -p $(BUILD_DIR)/host+ $(Q) $(HOST_CC) -std=gnu11 -O2 -Wall -Wextra tests/host_z80.c src/sms/z80.c -o $@+test: $(BUILD_DIR)/host/core $(BUILD_DIR)/host/romtable $(BUILD_DIR)/host/pack $(BUILD_DIR)/host/z80$(Q) $(BUILD_DIR)/host/pack$(Q) $(PY) tests/test_romtable.py $(BUILD_DIR)/host/romtable- $(Q) $(PY) tests/test_cores.py $(BUILD_DIR)/host/core $(TEST_ROMS)+ $(Q) $(PY) tests/test_cores.py $(BUILD_DIR)/host/core $(TEST_ROMS) $(BUILD_DIR)/host/z80$(Q) NWLINK="$(NWLINK)" $(PY) tests/test_app.pydiff --git a/games/retrogo/README.md b/games/retrogo/README.mdindex ffb22fe8..815b75ba 100644--- a/games/retrogo/README.md+++ b/games/retrogo/README.md@@ -1,6 +1,6 @@# Retro-Go-Play your own Game Boy, Game Boy Color and NES games on the NumWorks calculator. Retro-Go is the launcher and emulators of handhelds like the ODROID-GO, whose screen is the calculator's size; this is its look and its menus, made for the keypad.+Play your own Game Boy, Game Boy Color, NES, Master System and Game Gear games on the NumWorks calculator. Retro-Go is the launcher and emulators of handhelds like the ODROID-GO, whose screen is the calculator's size; this is its look and its menus, made for the keypad.<img src="docs/shot.png" width="320" alt="Retro-Go's list of NES games, with Thwaite chosen">@@ -9,6 +9,7 @@ You pick the games on NumPlay's customizer website: it puts them inside your Num- **Retro-Go's launcher:** a tab for each system with its own colours, the game list, and for each game Resume game, New game, Delete save and Properties.- **Game Boy and Game Boy Color** with gnuboy, the emulator Retro-Go started from: the cartridges with MBC1, MBC2, MBC3 (with its clock), MBC5, HuC1 and HuC3 bank controllers, up to 32 KB of cartridge RAM.- **NES** with nofrendo, Retro-Go's NES emulator at its start: 34 mappers, among them NROM, MMC1, UNROM, CNROM, MMC3, MMC5, AxROM, MMC2, Namco 163 and the Konami VRC chips.+- **Master System and Game Gear** with a machine written for NumPlay around superzazu's Z80: Sega's, Codemasters' and the Korean mappers, the cartridges' RAM, the 224-line pictures, the European games that need 50 Hz, and the Game Gear games made for the Master System's mode.- **Full speed** on every calculator: as Retro-Go does, a frame is drawn, then at least one is skipped, more when the calculator can't keep up, so the game always runs at its own speed.- **Retro-Go's menu** in a game: Save & Continue, Save & Quit, Load game, Reset, Options, Controls, About and Quit.- **4 save slots** for each game, and the cartridges' own battery saves, kept a few seconds after the game writes them. Home saves and quits.@@ -23,6 +24,10 @@ You pick the games on NumPlay's customizer website: it puts them inside your Num<td align="center"><img src="docs/menu.png" width="320" alt="Retro-Go's menu over the game"><br><sub>Retro-Go's menu</sub></td><td align="center"><img src="docs/options.png" width="320" alt="Retro-Go's options: scaling, speed and the emulator's options"><br><sub>Options</sub></td></tr>+ <tr>+ <td align="center"><img src="docs/sms.png" width="320" alt="Raposa do Sol, a Master System homebrew game, in Fit"><br><sub>Raposa do Sol, a Master System homebrew game</sub></td>+ <td align="center"><img src="docs/gg.png" width="320" alt="Waternet, a Game Gear homebrew game, at 1x with the keys on the side"><br><sub>Waternet on the Game Gear, at 1x</sub></td>+ </tr></table>## Controls@@ -30,22 +35,22 @@ You pick the games on NumPlay's customizer website: it puts them inside your Num| Key | In the launcher | In a game || --- | --- | --- || Arrows | Choose a system, then a game | The D-pad |-| OK | Open the system, then the game | A |-| Back | Back to the systems | B |+| OK | Open the system, then the game | A (Sega: 2) |+| Back | Back to the systems | B (Sega: 1) || shift | | Select |-| EXE | Like OK | Start |+| EXE | Like OK | Start (Master System: Pause) || Backspace | Options, Controls, About | Retro-Go's menu || Home | Quit | Save and quit |-In 1x on the Game Boy, the keys are written on the side of the screen. The first time you play, Retro-Go shows them, and Controls in its menu shows them again.+In 1x on the Game Boy and the Game Gear, the keys are written on the side of the screen. The first time you play, Retro-Go shows them, and Controls in its menu shows them again.## Good to know- No sound: the calculator has no speaker.-- The calculator has about 42 KB for every app's saves. A Game Boy or NES state takes 2 to 10 KB, a Game Boy Color one up to 30 KB, so keep the slots you need and delete the others in the launcher (Delete save).+- The calculator has about 42 KB for every app's saves. A Game Boy or NES state takes 2 to 10 KB, a Master System or Game Gear one 3 to 15 KB, a Game Boy Color one up to 30 KB, so keep the slots you need and delete the others in the launcher (Delete save).- The calculator has no clock for apps: a Game Boy game's clock runs while you play, and you can set it in Options, RTC config.- Cartridges with more than 32 KB of RAM (a few Game Boy Color games) and NES mappers nofrendo doesn't have say so instead of starting.-- Master System and Game Gear, which Retro-Go also plays, are not here yet: the emulator Retro-Go uses for them has a Z80 core that may not be shared freely.+- The SG-1000's games, and the light gun and 3-D glasses games of the Master System, don't play.## Credits@@ -53,9 +58,10 @@ In 1x on the Game Boy, the keys are written on the side of the screen. The first- **[gnuboy](https://github.com/rofl0r/gnuboy)** by Laguna and Gilgamesh and gnuboy's contributors (GPL-2.0-or-later, [COPYING](src/gb/COPYING)), from rofl0r's tree, emulates the Game Boy. Its picture is drawn by new code here: gnuboy's keeps 256 KB of decoded tiles, more than the calculator has.- **nofrendo** by Matthew Conte and nofrendo's contributors (version 2 of the GNU Library GPL, [COPYING.LGPL](src/nes/COPYING.LGPL), used under the GPL as its section 3 allows) emulates the NES. Its 2.0 release is the one used here.-- The tests run [Blargg's test ROMs](https://github.com/retrio/gb-test-roms), [dmg-acid2 and cgb-acid2](https://github.com/mattcurrie) by Matt Currie and [nestest](https://github.com/christopherpow/nes-test-roms) by kevtris, which aren't in NumPlay. The pictures show [Thwaite](https://github.com/pinobatch/thwaite-nes), [Concentration Room](https://github.com/pinobatch/croom-nes), [Libbet and the Magic Floor](https://github.com/pinobatch/libbet) and the [240p Test Suite](https://github.com/pinobatch/240p-test-mini) by Damian Yerrick and others, and [µCity](https://github.com/AntonioND/ucity) by Antonio Niño Díaz, all free homebrew games.-- Game Boy, Game Boy Color and NES are trademarks of Nintendo. Not affiliated with Nintendo.+- **[z80](https://github.com/superzazu/z80)** by Nicolas Allemand (superzazu) (MIT License, [LICENSE.z80](src/sms/LICENSE.z80)) is the Master System's and Game Gear's processor, changed to run faster on the calculator. The rest of those machines is NumPlay's, written from Charles MacDonald's notes on their hardware and SMS Power's pages. Retro-Go's own Master System emulator, SMS Plus, can't be used: its Z80 may not be shared freely. The short list of games that need something of their own is [SMS Plus GX](https://github.com/libretro/smsplus-gx)'s (GPL-2.0-or-later).+- The tests run [Blargg's test ROMs](https://github.com/retrio/gb-test-roms), [dmg-acid2 and cgb-acid2](https://github.com/mattcurrie) by Matt Currie, [nestest](https://github.com/christopherpow/nes-test-roms) by kevtris, Frank Cringle's zexdoc and zexall, as [superzazu's z80](https://github.com/superzazu/z80) has them and in [Maxim's Master System port](https://github.com/maxim-zhao/zexall-sms), which aren't in NumPlay. The pictures show [Thwaite](https://github.com/pinobatch/thwaite-nes), [Concentration Room](https://github.com/pinobatch/croom-nes), [Libbet and the Magic Floor](https://github.com/pinobatch/libbet) and the [240p Test Suite](https://github.com/pinobatch/240p-test-mini) by Damian Yerrick and others, [µCity](https://github.com/AntonioND/ucity) by Antonio Niño Díaz, [Raposa do Sol](https://github.com/jflores82/raposadosol) by tibonev, [Waternet](https://github.com/joyrider3774/waternet) by Willems Davy and [Tunnel](https://github.com/liamhays/tunnel) by Liam Hays, all free homebrew games.+- Game Boy, Game Boy Color and NES are trademarks of Nintendo, Master System and Game Gear of Sega. Not affiliated with Nintendo or Sega.Made by Mason Chen as part of NumPlay. It comes from the customizer website with your games in it, inside [NumPlay](https://github.com/Mason363/NumPlay) or on its own.-Build: `make ROMS="game.gb game.nes"` makes `output/retrogo.nwa` with those games in it, and `make test` checks the emulators and the saves on your computer (see `tests/`).+Build: `make ROMS="game.gb game.nes game.sms"` makes `output/retrogo.nwa` with those games in it, and `make test` checks the emulators and the saves on your computer (see `tests/`).diff --git a/games/retrogo/docs/gg.png b/games/retrogo/docs/gg.pngnew file mode 100644index 00000000..709a5b5fBinary files /dev/null and b/games/retrogo/docs/gg.png differdiff --git a/games/retrogo/docs/sms.png b/games/retrogo/docs/sms.pngnew file mode 100644index 00000000..c9ba0b25Binary files /dev/null and b/games/retrogo/docs/sms.png differdiff --git a/games/retrogo/docs/welcome.png b/games/retrogo/docs/welcome.pngindex 8c35a8c3..d8d87bf4 100644Binary files a/games/retrogo/docs/welcome.png and b/games/retrogo/docs/welcome.png differdiff --git a/games/retrogo/lang/fr.txt b/games/retrogo/lang/fr.txtindex f5d0e604..996273b5 100644--- a/games/retrogo/lang/fr.txt+++ b/games/retrogo/lang/fr.txt@@ -74,8 +74,8 @@ Can't start the game Impossible de lancer le jeuWelcome to Retro-Go! Bienvenue dans Retro-Go !Add games on NumPlay's Ajoute des jeux sur le sitecustomizer website: de personnalisation de NumPlay :-Game Boy, Game Boy Color des jeux Game Boy, Game Boy Color-and NES games. et NES.+Game Boy, Game Boy Color, NES, des jeux Game Boy, Game Boy Color, NES,+Master System and Game Gear. Master System et Game Gear.Home: quit Accueil : quitterLeft/Right: system OK: games Home: quit Gauche/Droite : console OK : jeux Accueil : quitterOK: play Back: systems Left/Right: system OK : jouer Retour : consoles Gauche/Droite : console@@ -85,7 +85,6 @@ System ConsoleSize TailleClose FermerFile properties Propriétés-Retro-Go on the calculator plays Game Boy, Game Boy Color and NES games. Retro-Go sur la calculatrice joue aux jeux Game Boy, Game Boy Color et NES.Resume game ReprendreNew game Nouvelle partieDelete save Effacer une sauvegarde@@ -93,3 +92,9 @@ Properties PropriétésResume ReprendreDelete save? Effacer la sauvegarde ?Delete sram file? Effacer la sauvegarde de la cartouche ?+# a Sega pad's buttons and the Master System's+A, 2 A, 2+B, 1 B, 1+Start, Pause Start, Pause+Pause Pause+z80 by superzazu z80 de superzazudiff --git a/games/retrogo/lang/zh.txt b/games/retrogo/lang/zh.txtindex d7833b2f..3dc50ed2 100644--- a/games/retrogo/lang/zh.txt+++ b/games/retrogo/lang/zh.txt@@ -74,8 +74,8 @@ Can't start the game 无法启动游戏Welcome to Retro-Go! 欢迎使用 Retro-Go!Add games on NumPlay's 请在 NumPlay 的customizer website: 定制网站上添加-Game Boy, Game Boy Color Game Boy、Game Boy Color-and NES games. 和 NES 游戏。+Game Boy, Game Boy Color, NES, Game Boy、Game Boy Color、NES、+Master System and Game Gear. Master System 和 Game Gear 游戏。Home: quit 主页:退出Left/Right: system OK: games Home: quit 左/右:主机 OK:游戏 主页:退出OK: play Back: systems Left/Right: system OK:开始 返回:主机 左/右:切换主机@@ -85,7 +85,6 @@ System 主机Size 大小Close 关闭File properties 文件属性-Retro-Go on the calculator plays Game Boy, Game Boy Color and NES games. 计算器上的 Retro-Go 可以玩 Game Boy、Game Boy Color 和 NES 游戏。Resume game 继续游戏New game 新游戏Delete save 删除存档@@ -93,3 +92,9 @@ Properties 属性Resume 继续Delete save? 删除存档?Delete sram file? 删除卡带存档?+# a Sega pad's buttons and the Master System's+A, 2 A, 2+B, 1 B, 1+Start, Pause Start, 暂停+Pause 暂停+z80 by superzazu superzazu 的 z80diff --git a/games/retrogo/src/main.c b/games/retrogo/src/main.cindex f526a00c..cb32b916 100644--- a/games/retrogo/src/main.c+++ b/games/retrogo/src/main.c@@ -1,4 +1,4 @@-/* Retro-Go: Game Boy, Game Boy Color and NES games on the calculator.+/* Retro-Go: Game Boy, Game Boy Color, NES, Master System and Game Gear games on the calculator.** Retro-Go (ducalex) is a launcher and a set of emulators for ESP32 handhelds whose 320 x 240* screen is the calculator's. This is its look and its ways, made again for the keypad: the@@ -6,8 +6,9 @@* Reset, Options...), its scaling (1x, Fit, Full), its frame skipping (a frame drawn, then at* least one skipped, more when the calculator can't keep up), save states in 4 slots and the* cartridges' battery saves. The emulators are gnuboy (Game Boy, Game Boy Color) and nofrendo- * (NES), the ones Retro-Go started from; Retro-Go's own code is GPL-2.0 only, so none of it is- * here (see README.md).+ * (NES), the ones Retro-Go started from, and for the Master System and Game Gear a machine+ * written for NumPlay around superzazu's Z80 (sms/); Retro-Go's own code is GPL-2.0 only, so+ * none of it is here (see README.md).** The games come in a table in flash, np_roms (tools/romtable.py, or the customizer website),* read in place. Inside NumPlay the app draws with the launcher's strips and fonts and saves@@ -21,6 +22,7 @@#include "pack.h"#include "gb/gb.h"#include "nes/nes_core.h"+#include "sms/sms.h"#if NP_MODULE /* (np_file_read, np_file_write, np_storage_delete: NumPlay's, launcher/src/np.h) */#define np_app_begin()@@ -121,15 +123,11 @@ static int nroms;/* Retro-Go's tabs, in its order */static const uint8_t tab_order[] = {RG_SYS_NES, RG_SYS_GB, RG_SYS_GBC, RG_SYS_SMS, RG_SYS_GG};static uint8_t tabs[5], ntabs;-static const char *const sys_name[RG_SYS_COUNT] = {- "Retro-Go", "Nintendo Gameboy", "Nintendo Gameboy Color", "Nintendo Entertainment System", "Sega Master System",- "Sega Game Gear"};static const char *const sys_short[RG_SYS_COUNT] = {"", "GB", "GBC", "NES", "SMS", "GG"};/* the tab's banner: the maker, then the system, as Retro-Go's banners show them */static const char *const sys_maker[RG_SYS_COUNT] = {"", "Nintendo", "Nintendo", "Nintendo", "SEGA", "SEGA"};static const char *const sys_model[RG_SYS_COUNT] = {"Retro-Go", "Game Boy", "Game Boy Color", "Entertainment System","Master System", "Game Gear"};-static bool sys_supported(int s) { return s == RG_SYS_GB || s == RG_SYS_GBC || s == RG_SYS_NES; }static int tab_first(int sys) {for (int i = 0; i < nroms; i++)@@ -264,14 +262,15 @@ void rg_line(int y, const uint16_t *px) {/* the picture's place for the game running (Retro-Go's update_viewport_scaling) */static int sys_now;static void set_view(void) {- int sw = 160, sh = 144, cx = 0, cy = 0;+ int sx = 0, sy = 0, sw = 160, sh = 144;if (sys_now == RG_SYS_NES) {- sw = NES_WIDTH, sh = NES_HEIGHT;- cy = cfg.overscan ? 8 : 0;- cx = cfg.crop_sides ? 8 : 0;+ sy = cfg.overscan ? 8 : 0;+ sx = cfg.crop_sides ? 8 : 0;+ sw = NES_WIDTH - 2 * sx, sh = NES_HEIGHT - 2 * sy;+ } else if (sys_now == RG_SYS_SMS || sys_now == RG_SYS_GG) {+ sms_view(&sx, &sy, &sw, &sh); /* (the Game Gear's screen, or the taller pictures of some games) */}- view.src_x = cx, view.src_y = cy, view.src_w = sw - 2 * cx, view.src_h = sh - 2 * cy;- sw = view.src_w, sh = view.src_h;+ view.src_x = sx, view.src_y = sy, view.src_w = sw, view.src_h = sh;int w = sw, h = sh;if (cfg.scaling == SCALE_FULL) {w = SCREEN_W, h = SCREEN_H;@@ -693,18 +692,35 @@ static int session_slot = -1; /* the slot this game was loaded from or sastatic int frameskip = 1, skip; /* Retro-Go's frame skipping */static uint32_t autosave_at; /* when the battery save is due, 0 none */-static bool is_gb(void) { return sys_now == RG_SYS_GB || sys_now == RG_SYS_GBC; }+/* the three emulators: gnuboy, nofrendo, and the Master System's (for the Game Gear too) */+enum { CORE_GB, CORE_NES, CORE_SMS };+static int core;+static bool is_gb(void) { return core == CORE_GB; }-static int core_chunks(rg_chunk_t *c) { return is_gb() ? gb_state_chunks(c) : nes_state_chunks(c); }+static int core_chunks(rg_chunk_t *c) {+ return core == CORE_GB ? gb_state_chunks(c) : core == CORE_NES ? nes_state_chunks(c) : sms_state_chunks(c);+}-static uint8_t *core_sram(uint32_t *size) { return is_gb() ? gb_sram(size) : nes_sram(size); }-static bool core_sram_dirty(void) { return is_gb() ? gb_sram_dirty() : nes_sram_dirty(); }+/* the battery RAM, NULL if none (a Sega cartridge's only once the game has turned it on) */+static uint8_t *core_sram(uint32_t *size) {+ if (core == CORE_SMS) return sms_sram(size);+ return core == CORE_GB ? gb_sram(size) : nes_sram(size);+}+static bool core_sram_dirty(void) {+ return core == CORE_GB ? gb_sram_dirty() : core == CORE_NES ? nes_sram_dirty() : sms_sram_dirty();+}+static void core_sram_saved(void) {+ if (core == CORE_GB) gb_sram_saved();+ else if (core == CORE_NES) nes_sram_saved();+ else sms_sram_saved();+}static void core_redraw(void) {redraw_all = true;pend_n = 0;- if (is_gb()) gb_redraw();- else nes_redraw();+ if (core == CORE_GB) gb_redraw();+ else if (core == CORE_NES) nes_redraw();+ else sms_redraw();flush();redraw_all = false;}@@ -712,17 +728,14 @@ static void core_redraw(void) {static bool sram_save(void) {uint32_t size = 0;uint8_t *ram = core_sram(&size);- if (!ram) return true;+ if (!ram || (core == CORE_SMS && !sms_sram_used())) return true;char name[20];save_name(name, game, -1);rg_chunk_t parts[2] = {{ram, size}, {NULL, 0}};int n = 1;if (is_gb() && gb_has_rtc()) parts[n].at = gb_rtc_state(&parts[n].size), n++;bool ok = !size && n == 1 ? true : save_parts(name, SAVE_MAGIC_SRAM, game_crc, parts, n);- if (ok) {- if (is_gb()) gb_sram_saved();- else nes_sram_saved();- }+ if (ok) core_sram_saved();autosave_at = 0;return ok;}@@ -736,13 +749,11 @@ static void sram_load(void) {rg_chunk_t parts[2] = {{ram, size}, {NULL, 0}};int n = 1;if (is_gb() && gb_has_rtc()) parts[n].at = gb_rtc_state(&parts[n].size), n++;- if (load_parts(name, SAVE_MAGIC_SRAM, game_crc, parts, n) < 0) memset(ram, 0xFF, size);- if (is_gb()) {- if (gb_has_rtc()) gb_rtc_loaded();- gb_sram_saved();- } else {- nes_sram_saved();- }+ int r = load_parts(name, SAVE_MAGIC_SRAM, game_crc, parts, n);+ if (r < 0) memset(ram, 0xFF, size);+ if (is_gb() && gb_has_rtc()) gb_rtc_loaded();+ if (core == CORE_SMS && r > 0) sms_sram_loaded();+ core_sram_saved();}static uint32_t slot_seq(const rg_rom_t *r, int slot) {@@ -784,8 +795,9 @@ static bool state_load(int slot) {save_name(name, game, slot);int r = load_parts(name, SAVE_MAGIC_STATE, game_crc, parts, n);if (r > 0) {- if (is_gb()) gb_state_loaded();- else nes_state_loaded();+ if (core == CORE_GB) gb_state_loaded();+ else if (core == CORE_NES) nes_state_loaded();+ else sms_state_loaded();last_slot = session_slot = slot, skip = 0;return true;}@@ -797,15 +809,33 @@ static bool state_load(int slot) {}static void core_reset(bool hard) {- if (is_gb()) gb_reset(hard);- else nes_reset_machine(hard);+ if (core == CORE_GB) gb_reset(hard);+ else if (core == CORE_NES) nes_reset_machine(hard);+ else sms_reset(hard);skip = 0;}static void apply_settings(void) {- if (is_gb()) gb_set_palette(cfg.gb_palette);- else nes_set_palette(cfg.nes_palette), nes_set_sprite_limit(cfg.sprite_limit);+ if (core == CORE_GB) gb_set_palette(cfg.gb_palette);+ else if (core == CORE_NES) nes_set_palette(cfg.nes_palette), nes_set_sprite_limit(cfg.sprite_limit);+}++/* The pad's buttons as the system running names them (a Sega pad's are 1 and 2; the Master+ System's pause button is on the console), NULL for none; with no game, every system's. */+static const char *button_name(int k) {+ static const char *const names[] = {T("D-pad"), "A", "B", T("Select"), T("Start")};+ bool sega = sys_now == RG_SYS_SMS || sys_now == RG_SYS_GG;+ if (!game) {+ bool any = false;+ for (int i = 0; i < ntabs; i++) any |= tabs[i] == RG_SYS_SMS || tabs[i] == RG_SYS_GG;+ static const char *const both[] = {NULL, T("A, 2"), T("B, 1"), NULL, T("Start, Pause")};+ return any && both[k] ? both[k] : names[k];+ }+ if (!sega) return names[k];+ static const char *const sms[] = {T("D-pad"), "2", "1", NULL, T("Pause")};+ return k == 4 && sys_now == RG_SYS_GG ? T("Start") : sms[k];}+static const char *const button_keys[] = {T("arrows"), T("OK"), T("Back"), T("shift"), T("EXE")};/* the game's picture again, with what is around it */static void borders_scene(void *ctx) {@@ -813,10 +843,13 @@ static void borders_scene(void *ctx) {gfx_fill(0, gfx_y0, SCREEN_W, gfx_y1 - gfx_y0, BLACK);if (view.x < 72) return;/* (room on the sides: the keys) */- static const char *const keys[][2] = {{T("arrows"), T("D-pad")}, {T("OK"), "A"}, {T("Back"), "B"},- {T("shift"), T("Select")}, {T("EXE"), T("Start")},- {T("Backspace"), T("menu")}, {T("Home"), T("quit")}};- for (int i = 0; i < 7; i++) {+ const char *keys[7][2];+ int n = 0;+ for (int k = 0; k < 5; k++)+ if (button_name(k)) keys[n][0] = button_keys[k], keys[n][1] = button_name(k), n++;+ keys[n][0] = T("Backspace"), keys[n++][1] = T("menu");+ keys[n][0] = T("Home"), keys[n++][1] = T("quit");+ for (int i = 0; i < n; i++) {int y = view.y + 10 + i * 20;gfx_text_right(&np_font_small, view.x - 6, y, keys[i][0], HEX(0x9AA0A6), 256);gfx_text_right(&np_font_small, view.x - 6, y + 9, keys[i][1], WHITE, 256);@@ -953,11 +986,14 @@ static int emulator_options_cb(item_t *it, int ev) {OPTION(T("SRAM autosave"), autosave_cb, 0)};if (!gb_has_rtc()) items[1].flags = IT_DISABLED;r = dialog_run(it->label, items, 3, 0);- } else {+ } else if (core == CORE_NES) {item_t items[] = {OPTION(T("Palette"), nes_palette_cb, 0), OPTION(T("Overscan"), overscan_cb, 0),OPTION(T("Crop sides"), crop_cb, 0), OPTION(T("Sprite limit"), sprite_limit_cb, 0),OPTION(T("SRAM autosave"), autosave_cb, 0)};r = dialog_run(it->label, items, 5, 0);+ } else {+ item_t items[] = {OPTION(T("SRAM autosave"), autosave_cb, 0)};+ r = dialog_run(it->label, items, 1, 0);}return r == DLG_HOME ? CB_SELECT : CB_NONE;}@@ -970,23 +1006,25 @@ static int options_menu(void) {}static int controls(void) {- item_t items[] = {- {0, T("D-pad"), "", IT_MESSAGE, 1, NULL, 0}, {0, "A", "", IT_MESSAGE, 1, NULL, 0},- {0, "B", "", IT_MESSAGE, 1, NULL, 0}, {0, T("Select"), "", IT_MESSAGE, 1, NULL, 0},- {0, T("Start"), "", IT_MESSAGE, 1, NULL, 0}, {0, T("Menu"), "", IT_MESSAGE, 1, NULL, 0},- {0, T("Quit"), "", IT_MESSAGE, 1, NULL, 0}, ITEM(1, T("OK"))};+ item_t items[8];static const char *const keys[] = {T("arrows"), "OK", T("Back"), T("shift"), "EXE", T("Backspace"),T("Home (saves)")};- for (int i = 0; i < 7; i++) strcpy(items[i].value, keys[i]);+ for (int i = 0; i < 7; i++) {+ const char *label = i < 5 ? button_name(i) : i == 5 ? T("Menu") : T("Quit");+ items[i] = (item_t){0, label ? label : "", "", label ? IT_MESSAGE : IT_HIDDEN, 1, NULL, 0};+ strcpy(items[i].value, keys[i]);+ }+ items[7] = (item_t)ITEM(1, T("OK"));return dialog_run(T("Controls"), items, 8, 7);}static int about(void) {item_t items[] = {{0, T("Retro-Go"), "ducalex", IT_MESSAGE, 1, NULL, 0}, {0, "Game Boy", "gnuboy", IT_MESSAGE, 1, NULL, 0},- {0, "NES", "nofrendo", IT_MESSAGE, 1, NULL, 0}, {0, T("Port"), "NumPlay", IT_MESSAGE, 1, NULL, 0},- MESSAGE(T("Not affiliated with Retro-Go")), ITEM(1, T("OK"))};- return dialog_run(T("About Retro-Go"), items, 6, 5);+ {0, "NES", "nofrendo", IT_MESSAGE, 1, NULL, 0}, {0, "SMS, GG", T("z80 by superzazu"), IT_MESSAGE, 1, NULL, 0},+ {0, T("Port"), "NumPlay", IT_MESSAGE, 1, NULL, 0}, MESSAGE(T("Not affiliated with Retro-Go")),+ ITEM(1, T("OK"))};+ return dialog_run(T("About Retro-Go"), items, 7, 6);}/* Retro-Go's save slots: 0 to 3; the slot, DLG_BACK or DLG_HOME */@@ -1084,9 +1122,12 @@ uint32_t perf_frames, perf_drawn;static int play(const rg_rom_t *r, int slot) {sys_now = r->system;+ core = sys_now == RG_SYS_NES ? CORE_NES : sys_now == RG_SYS_SMS || sys_now == RG_SYS_GG ? CORE_SMS : CORE_GB;game = r;game_crc = rom_crc(r);- int err = is_gb() ? gb_load(r->data, r->size) : nes_load(r->data, r->size);+ int err = core == CORE_GB ? gb_load(r->data, r->size)+ : core == CORE_NES ? nes_load(r->data, r->size)+ : sms_load(r->data, r->size, game_crc, sys_now == RG_SYS_GG);if (err != RG_OK) {game = NULL;const char *why = err == RG_ERR_MAPPER ? T("This cartridge type isn't supported.")@@ -1111,9 +1152,9 @@ static int play(const rg_rom_t *r, int slot) {game_screen();wait_release();- const bool gb = is_gb();- /* a frame: the Game Boy's 70224 clocks at 4.194304 MHz, the NES's 29780.5 at 1.789773 MHz */- const uint32_t frame_us = gb ? 16742 : 16639;+ /* a frame: the Game Boy's 70224 clocks at 4.194304 MHz, the NES's 29780.5 at 1.789773 MHz, the+ Master System's 59736 at 3.579545 MHz (or 50 a second) */+ const uint32_t frame_us = core == CORE_GB ? 16742 : core == CORE_NES ? 16639 : sms_frame_us();uint32_t next_us = millis() * 1000u, second = millis(), frames = 0, busy = 0;int result = GAME_ON;frameskip = NP_MAX(1, cfg.speed * 3 / 2), skip = 0, autosave_at = 0;@@ -1146,9 +1187,15 @@ static int play(const rg_rom_t *r, int slot) {uint32_t t0 = millis();bool draw = skip == 0;- if (gb) gb_set_pad(pad), gb_run_frame(draw);- else nes_set_pad(pad), nes_run_frame(draw);+ if (core == CORE_GB) gb_set_pad(pad), gb_run_frame(draw);+ else if (core == CORE_NES) nes_set_pad(pad), nes_run_frame(draw);+ else sms_set_pad(pad), sms_run_frame(draw);if (draw) flush(), redraw_all = false, perf_drawn++;+ if (core == CORE_SMS) { /* (a game that changes the picture's height) */+ int x, y, w, h;+ sms_view(&x, &y, &w, &h);+ if (y != view.src_y || h != view.src_h) set_view(), game_screen();+ }perf_frames++, frames++;uint32_t elapsed = millis() - t0;busy += elapsed;@@ -1195,7 +1242,7 @@ static void picker_scene(void *ctx) {if (!ntabs) { /* (no games: Retro-Go's welcome, and where they come from) */header(0, 0);static const char *const lines[] = {T("Welcome to Retro-Go!"), "", T("Add games on NumPlay's"),- T("customizer website:"), T("Game Boy, Game Boy Color"), T("and NES games."),+ T("customizer website:"), T("Game Boy, Game Boy Color, NES,"), T("Master System and Game Gear."),"", T("Home: quit")};for (int i = 0; i < 8; i++) gfx_text(&np_font_body, 8, 80 + 18 * i, lines[i], i ? 0xAD55 : WHITE, 256);return;@@ -1249,9 +1296,6 @@ static int properties(const rg_rom_t *r) {/* Retro-Go's menu for a game: Resume game, New game, Delete save, Properties */static int file_menu(const rg_rom_t *r) {- if (!sys_supported(r->system)) {- return alert(sys_name[r->system], T("Retro-Go on the calculator plays Game Boy, Game Boy Color and NES games."));- }message_box(NULL, T("Reading..."));bool has_save = false, has_sram = false;for (int i = 0; i < 4; i++) has_save |= state_exists(r, i);diff --git a/games/retrogo/src/sms/LICENSE.z80 b/games/retrogo/src/sms/LICENSE.z80new file mode 100644index 00000000..e593d415--- /dev/null+++ b/games/retrogo/src/sms/LICENSE.z80@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2019 Nicolas Allemand++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.diff --git a/games/retrogo/src/sms/sms.c b/games/retrogo/src/sms/sms.cnew file mode 100644index 00000000..9e4288b9--- /dev/null+++ b/games/retrogo/src/sms/sms.c@@ -0,0 +1,501 @@+/* The Sega Master System and Game Gear around superzazu's Z80: the cartridge's mappers (Sega's,+ * Codemasters', the Korean one), the work RAM, the pads, the Game Gear's ports and the video chip+ * (mode 4: the tiles, their scrolling and priorities, the sprites, the line and frame+ * interrupts, the counters), drawn a line at a time. Written for NumPlay from the hardware's+ * public descriptions (Charles MacDonald's notes on the VDP and the Master System, SMS Power's+ * pages); no sound, the calculator has no speaker. The short list of games that need something+ * of their own (their CRC32s) is SMS Plus GX's (GNU GPL v2 or later). The old TMS9918 modes of+ * the SG-1000 are not drawn. */+#include <string.h>+#include "sms.h"+#include "z80.h"++#define LINE_CLOCKS 228 /* the Z80's clocks a line (3.58 MHz) */++enum { MAP_SEGA, MAP_CODIES, MAP_KOREA };+enum { DB_CODIES = 1, DB_PAL = 2, DB_GGMS = 4, DB_KOREA = 8 };++/* the games that need something of their own (from SMS Plus GX's list): Codemasters' or the+ Korean mapper, 50 Hz (European games made for it), Master System mode on the Game Gear */+static const struct { uint32_t crc; uint8_t flags; } special[] = {+ {0x29822980, DB_CODIES | DB_PAL}, {0x6CAA625B, DB_CODIES}, {0xEA5C3A6F, DB_CODIES},+ {0x152F0DCC, DB_CODIES}, {0x5E53C7F7, DB_CODIES}, {0x8813514B, DB_CODIES | DB_PAL},+ {0xAA140C9C, DB_CODIES | DB_GGMS}, {0xB9664AE1, DB_CODIES | DB_PAL}, {0xC888222B, DB_CODIES | DB_GGMS},+ {0x76C5BDFB, DB_CODIES | DB_GGMS}, {0xD9A7F170, DB_CODIES}, {0xA577CE46, DB_CODIES | DB_PAL},+ {0xF7C524F6, DB_CODIES | DB_PAL}, {0xDBE8895C, DB_CODIES | DB_PAL}, {0xC1756BEE, DB_CODIES | DB_PAL},+ {0x89B79E77, DB_KOREA}, {0x18FB98A3, DB_KOREA}, {0x97D03541, DB_KOREA}, {0x67C2F0FF, DB_KOREA},+ {0x72420F38, DB_PAL}, {0x2D48C1D3, DB_PAL}, {0x1CBB7BF1, DB_PAL}, {0x1B10A951, DB_PAL},+ {0xC0E25D62, DB_PAL}, {0xC9DBF936, DB_PAL}, {0xA109A6FE, DB_PAL}, {0x4FF0CEC7, DB_PAL},+ {0x0047B615, DB_PAL}, {0xF42E145C, DB_PAL}, {0x9F951756, DB_PAL}, {0x1575581D, DB_PAL},+ {0x96B3F29E, DB_PAL}, {0x5B3B922C, DB_PAL}, {0xD6F2BFCA, DB_PAL}, {0xCA1D3752, DB_PAL},+ {0x85CFC9C9, DB_PAL}, {0x38434560, DB_PAL}, {0xDA2A68C6, DB_PAL}, {0x205CAAE8, DB_PAL},+ {0xA67F2A5C, DB_PAL},+ {0x59840FD6, DB_GGMS}, {0x9942B69B, DB_GGMS}, {0x5877B10D, DB_GGMS}, {0x9C76FB3A, DB_GGMS},+ {0x7BB81E3D, DB_GGMS}, {0x44FBE8F6, DB_GGMS}, {0x18086B70, DB_GGMS}, {0xDA8E95A9, DB_GGMS},+ {0xCB42BD33, DB_GGMS}, {0x1D93246E, DB_GGMS}, {0xA2F9C7AF, DB_GGMS}, {0xF037EC00, DB_GGMS},+ {0xE5F789B9, DB_GGMS}, {0x311D2863, DB_GGMS}, {0x45F058D6, DB_GGMS}, {0x56201996, DB_GGMS},+ {0x10DBBEF4, DB_GGMS}, {0xBD1CC7DF, DB_GGMS},+};++/* what a save state keeps of the machine besides the Z80 and the memories (bytes only, any value+ read back is made sound by sms_state_loaded) */+typedef struct {+ uint8_t reg[16]; /* the video chip's registers */+ uint8_t cram[64]; /* its colours: 32 bytes on the Master System, 32 words on the Game Gear */+ uint8_t status; /* frame interrupt, sprite overflow, sprite collision */+ uint8_t pending; /* the control port's first byte was written */+ uint8_t latch, code, buffer, cram_latch;+ uint16_t addr;+ uint8_t vint, hint; /* the frame and line interrupts, pending */+ int16_t counter; /* the line counter */+ uint16_t line; /* the line running */+ uint8_t vscroll; /* the vertical scroll, as the frame took it */+ uint8_t mapper[4]; /* Sega's at $FFFC-$FFFF; Codemasters' and the Korean slots in 1 to 3 */+ uint8_t io3f; /* the pads' lines (port $3F) */+ uint8_t sram_on; /* the game turned its cartridge RAM on */+ uint8_t pause; /* the pause button, held */+ uint8_t pad_[3];+} state_t;++/* a line's registers as it was drawn (sms_redraw draws the frame again from them) */+typedef struct { uint8_t r0, r1, r2, r5, r6, r7, hs, vs; } line_regs_t;++static z80 cpu;+static state_t st;+static uint8_t *ram, *vram, *sram, *sram_slot;+static uint32_t *expand; /* a byte of a tile's plane -> its 8 pixels, a bit in each nibble */+static line_regs_t *snap;+static int snap_lines;+static const uint8_t *rom;+static uint32_t rom_size, banks;+static uint8_t mapper_kind;+static bool gg, gg_vdp, pal, sram_dirty;+static uint8_t pad_bits;+static bool start_button;+static uint32_t line_start, line_end;+static uint16_t pal565[32];+static uint8_t lb[256 + 16]; /* a line: colour index (0-31), 0x40 the tile over the sprites, 0x20 a sprite */+static uint16_t px[256];+static const uint8_t open_bus[0x400] = {[0 ... 0x3FF] = 0xFF};+const uint8_t *z80_rmap[64];++/* ------------------------------------------------------------ memory */+static const uint8_t *rom_page(uint32_t bank, int k) {+ uint32_t at = (bank % banks) * 0x4000 + (uint32_t)k * 0x400;+ return at + 0x400 <= rom_size ? rom + at : open_bus;+}++static void map_update(void) {+ sram_slot = NULL;+ if (mapper_kind == MAP_SEGA) {+ z80_rmap[0] = rom_page(0, 0); /* (the first 1 KB never moves) */+ for (int k = 1; k < 16; k++) z80_rmap[k] = rom_page(st.mapper[1], k);+ for (int k = 0; k < 16; k++) z80_rmap[16 + k] = rom_page(st.mapper[2], k);+ if (st.mapper[0] & 0x08) sram_slot = sram + (st.mapper[0] & 0x04 ? 0x4000 : 0);+ for (int k = 0; k < 16; k++) z80_rmap[32 + k] = sram_slot ? sram_slot + k * 0x400 : rom_page(st.mapper[3], k);+ } else {+ for (int k = 0; k < 16; k++) {+ z80_rmap[k] = rom_page(mapper_kind == MAP_CODIES ? st.mapper[1] : 0, k);+ z80_rmap[16 + k] = rom_page(mapper_kind == MAP_CODIES ? st.mapper[2] : 1, k);+ z80_rmap[32 + k] = rom_page(st.mapper[3], k);+ }+ }+ for (int k = 0; k < 16; k++) z80_rmap[48 + k] = ram + (k & 7) * 0x400;+}++void z80_bus_write(uint16_t a, uint8_t v) {+ if (a >= 0xC000) {+ ram[a & 0x1FFF] = v;+ if (a >= 0xFFFC && mapper_kind == MAP_SEGA) {+ st.mapper[a & 3] = v;+ if ((a & 3) == 0 && (v & 0x08)) st.sram_on = 1;+ map_update();+ }+ } else if (a >= 0x8000 && sram_slot) {+ sram_slot[a & 0x3FFF] = v;+ sram_dirty = true;+ } else if (mapper_kind == MAP_CODIES && (a & 0x3FFF) == 0) {+ st.mapper[1 + (a >> 14)] = v;+ map_update();+ } else if (mapper_kind == MAP_KOREA && a == 0xA000) {+ st.mapper[3] = v;+ map_update();+ }+}++/* ------------------------------------------------------------ the video chip */+static int height_of(uint8_t r0, uint8_t r1) {+ if ((r0 & 0x06) == 0x06) { /* (mode 4 with M2: the taller pictures) */+ if (r1 & 0x10) return 224;+ if (r1 & 0x08) return 240;+ }+ return 192;+}+static int height(void) { return height_of(st.reg[0], st.reg[1]); }++static void irq_update(void) {+ cpu.irq_line = (st.vint && (st.reg[1] & 0x20)) || (st.hint && (st.reg[0] & 0x10));+}++static void palette_update(int i) {+ int r, g, b;+ if (gg_vdp) {+ unsigned c = st.cram[2 * i] | st.cram[2 * i + 1] << 8;+ r = c & 15, g = (c >> 4) & 15, b = (c >> 8) & 15;+ pal565[i] = (uint16_t)((r * 31 + 7) / 15 << 11 | (g * 63 + 7) / 15 << 5 | (b * 31 + 7) / 15);+ } else {+ unsigned c = st.cram[i];+ r = c & 3, g = (c >> 2) & 3, b = (c >> 4) & 3;+ pal565[i] = (uint16_t)((r * 31 + 1) / 3 << 11 | (g * 63 + 1) / 3 << 5 | (b * 31 + 1) / 3);+ }+}++static uint8_t vdp_status(void) {+ uint8_t v = st.status | 0x1F;+ st.status = 0, st.pending = 0, st.vint = 0, st.hint = 0;+ irq_update();+ return v;+}++static uint8_t vdp_read(void) {+ uint8_t v = st.buffer;+ st.pending = 0;+ st.buffer = vram[st.addr & 0x3FFF];+ st.addr = (st.addr + 1) & 0x3FFF;+ return v;+}++static void vdp_write(uint8_t v) {+ st.pending = 0;+ if (st.code == 3) {+ if (!gg_vdp) {+ st.cram[st.addr & 0x1F] = v;+ palette_update(st.addr & 0x1F);+ } else if (st.addr & 1) { /* (the Game Gear: a word, its first byte kept until the second) */+ st.cram[st.addr & 0x3E] = st.cram_latch;+ st.cram[(st.addr & 0x3E) | 1] = v;+ palette_update((st.addr >> 1) & 0x1F);+ } else {+ st.cram_latch = v;+ }+ } else {+ vram[st.addr & 0x3FFF] = v;+ }+ st.buffer = v;+ st.addr = (st.addr + 1) & 0x3FFF;+}++static void vdp_control(uint8_t v) {+ if (!st.pending) {+ st.latch = v;+ st.addr = (st.addr & 0x3F00) | v;+ st.pending = 1;+ return;+ }+ st.pending = 0;+ st.code = v >> 6;+ st.addr = (uint16_t)((v << 8 | st.latch) & 0x3FFF);+ if (st.code == 0) {+ st.buffer = vram[st.addr];+ st.addr = (st.addr + 1) & 0x3FFF;+ } else if (st.code == 2) {+ st.reg[v & 0x0F] = st.latch;+ irq_update();+ }+}++/* the counters the game can read: the line (with the jumps it makes in the blank) and the+ pixel, from the clocks run in the line */+static uint8_t vcounter(void) {+ int l = st.line, h = height();+ if (!pal) return (uint8_t)(l <= (h == 192 ? 0xDA : 0xEA) ? l : l - 6);+ if (h == 192) return (uint8_t)(l <= 0xF2 ? l : l - 57);+ return (uint8_t)(l <= 0x102 ? l : l - 57);+}+static uint8_t hcounter(void) {+ uint32_t c = cpu.cyc - line_start;+ if (c >= LINE_CLOCKS) c = LINE_CLOCKS - 1;+ uint32_t h = c * 3 / 4;+ return (uint8_t)(h > 0x93 ? h + 0x55 : h);+}++/* ------------------------------------------------------------ the ports */+static uint8_t pad_dc(void) { return (uint8_t)~pad_bits; }++/* the pads' TH lines: set as outputs, they read what was written (a machine from outside Japan) */+static uint8_t pad_dd(void) {+ uint8_t v = 0xFF;+ if (!(st.io3f & 0x02)) v = (uint8_t)((v & ~0x40) | (st.io3f & 0x20) << 1);+ if (!(st.io3f & 0x08)) v = (uint8_t)((v & ~0x80) | (st.io3f & 0x80));+ return v;+}++uint8_t z80_bus_in(uint8_t port) {+ if (gg && port < 7) { /* the Game Gear's: Start, outside Japan, 60 Hz; the link port, idle */+ static const uint8_t idle[7] = {0, 0x7F, 0xFF, 0x00, 0xFF, 0x00, 0xFF};+ return port ? idle[port] : (uint8_t)(0x40 | (start_button ? 0 : 0x80));+ }+ switch (port & 0xC1) {+ case 0x00: case 0x01: return 0xFF;+ case 0x40: return vcounter();+ case 0x41: return hcounter();+ case 0x80: return vdp_read();+ case 0x81: return vdp_status();+ case 0xC0: return pad_dc();+ default: return pad_dd();+ }+}++void z80_bus_out(uint8_t port, uint8_t v) {+ if (gg && port < 7) return; /* (the link port and the stereo sound) */+ switch (port & 0xC1) {+ case 0x01: st.io3f = v; break;+ case 0x80: vdp_write(v); break;+ case 0x81: vdp_control(v); break;+ default: break; /* (the memory control without a BIOS, the sound chip) */+ }+}++/* ------------------------------------------------------------ drawing a line */+static inline uint32_t tile_row(const uint8_t *p) {+ return expand[p[0]] | expand[p[1]] << 1 | expand[p[2]] << 2 | expand[p[3]] << 3;+}++static void background(int line, const line_regs_t *r) {+ int h = height_of(r->r0, r->r1);+ unsigned nt = h == 192 ? (r->r2 & 0x0E) << 10 : ((r->r2 & 0x0C) << 10) | 0x0700;+ int fine = r->hs & 7, coarse = r->hs >> 3;+ int vrow = line + r->vs;+ vrow = h == 192 ? vrow % 224 : vrow & 255;+ /* 33 tiles from 8 pixels left of the screen, the first ones half out with the fine scroll; the+ last 8 columns don't scroll down if the game said so */+ for (int k = 0; k <= 32; k++) {+ int v = k >= 25 && (r->r0 & 0x80) ? line : vrow;+ unsigned a = (nt + (unsigned)(v >> 3) * 64 + (unsigned)((k - 1 - coarse) & 31) * 2) & 0x3FFE;+ unsigned e = vram[a] | vram[a + 1] << 8;+ int y = v & 7;+ if (e & 0x400) y ^= 7;+ uint32_t row = tile_row(vram + ((e & 0x1FF) << 5 | (unsigned)y << 2));+ uint8_t pal = e & 0x800 ? 16 : 0, prio = e & 0x1000 ? 0x40 : 0;+ uint8_t *o = lb + fine + 8 * k;+ if (e & 0x200)+ for (int i = 7; i >= 0; i--, row >>= 4) o[i] = (uint8_t)(pal | (row & 15) | (row & 15 ? prio : 0));+ else+ for (int i = 0; i < 8; i++, row >>= 4) o[i] = (uint8_t)(pal | (row & 15) | (row & 15 ? prio : 0));+ }+}++/* the sprites on the line (8 at most: more set the overflow flag), over the tiles but under the+ tiles in front; two sprites' pixels on each other set the collision flag */+static void sprites(int line, const line_regs_t *r) {+ const uint8_t *sat = vram + ((r->r5 << 7) & 0x3F00);+ int h = height_of(r->r0, r->r1), size = r->r1 & 2 ? 16 : 8, zoom = r->r1 & 1, span = size << zoom;+ int base = (r->r6 & 4) << 6, shift = r->r0 & 8 ? 8 : 0, count = 0;+ for (int i = 0; i < 64; i++) {+ int y = sat[i];+ if (y == 0xD0 && h == 192) break;+ if (++y > 240) y -= 256;+ int row = line - y;+ if (row < 0 || row >= span) continue;+ if (++count > 8) {+ st.status |= 0x40;+ break;+ }+ int x = sat[0x80 + 2 * i] - shift, t = sat[0x81 + 2 * i];+ if (size == 16) t &= 0xFE;+ row >>= zoom;+ t = ((base | t) + (row >> 3)) & 0x1FF;+ uint32_t bits = tile_row(vram + (t << 5 | (row & 7) << 2));+ for (int j = 0; bits; j++, bits >>= 4) {+ int c = bits & 15;+ if (!c) continue;+ for (int s = 0; s <= zoom; s++) {+ int xx = x + (j << zoom) + s;+ if (xx >= 256) break;+ uint8_t *d = lb + 8 + xx;+ if (*d & 0x20) st.status |= 0x20;+ else *d = *d & 0x40 ? *d | 0x20 : (uint8_t)(0x30 | c);+ }+ }+ }+}++/* the picture shown (the Game Gear's screen: 160 x 144 in the middle) */+void sms_view(int *x, int *y, int *w, int *h) {+ int lines = height();+ if (gg_vdp) *x = 48, *y = (lines - 144) / 2, *w = 160, *h = 144;+ else *x = 0, *y = 0, *w = 256, *h = lines;+}++static void draw_line(int line, const line_regs_t *r, bool draw) {+ bool on = (r->r1 & 0x40) && (r->r0 & 0x04);+ int vx, vy, vw, vh;+ sms_view(&vx, &vy, &vw, &vh);+ if (!draw || line < vy || line >= vy + vh) { /* (not seen: only the flags the game can read) */+ if (!on) return;+ memset(lb + 8, 0, 256);+ sprites(line, r);+ return;+ }+ uint8_t backdrop = (uint8_t)(16 | (r->r7 & 15));+ if (!on) {+ memset(lb + 8, backdrop, 256);+ } else {+ background(line, r);+ sprites(line, r);+ if (r->r0 & 0x20) memset(lb + 8, backdrop, 8); /* (the left column hidden) */+ }+ for (int x = vx; x < vx + vw; x++) px[x] = pal565[lb[8 + x] & 31];+ rg_line(line, px);+}++static void snap_line(int line) {+ line_regs_t *r = &snap[line];+ *r = (line_regs_t){st.reg[0], st.reg[1], st.reg[2], st.reg[5], st.reg[6], st.reg[7],+ (uint8_t)((st.reg[0] & 0x40) && line < 16 ? 0 : st.reg[8]), st.vscroll};+}++/* ------------------------------------------------------------ the machine */+static int lines_per_frame(void) { return pal ? 313 : 262; }++static void run_line(bool draw) {+ int line = st.line, h = height();+ if (line == 0) st.vscroll = st.reg[9];+ if (line < h) {+ snap_line(line);+ draw_line(line, &snap[line], draw);+ }+ /* the line counter, on the picture's lines and the one after; reloaded below */+ if (line <= h) {+ if (--st.counter < 0) st.counter = st.reg[10], st.hint = 1;+ } else {+ st.counter = st.reg[10];+ }+ if (line == h) st.vint = 1, st.status |= 0x80;+ irq_update();+ line_start = line_end;+ line_end += LINE_CLOCKS;+ z80_run(&cpu, line_end);+}++/* A frame: from the blank to the picture's last line, so that what the game changes in the blank+ is in the frame's picture (and sms_redraw draws the same again). */+void sms_run_frame(bool draw) {+ int lpf = lines_per_frame();+ for (int n = 0; n < 2 * lpf; n++) {+ run_line(draw);+ if (++st.line >= lpf) st.line = 0;+ if (st.line == height()) break;+ }+ snap_lines = height();+ cpu.cyc -= line_end, line_end = 0; /* (the clocks from 0 again, with what the last instruction ran over) */+}++void sms_redraw(void) {+ uint8_t status = st.status;+ for (int line = 0; line < snap_lines; line++) draw_line(line, &snap[line], true);+ st.status = status;+}++void sms_set_pad(int p) {+ pad_bits = (uint8_t)((p & RG_PAD_UP ? 0x01 : 0) | (p & RG_PAD_DOWN ? 0x02 : 0) | (p & RG_PAD_LEFT ? 0x04 : 0) |+ (p & RG_PAD_RIGHT ? 0x08 : 0) | (p & RG_PAD_B ? 0x10 : 0) | (p & RG_PAD_A ? 0x20 : 0));+ bool start = p & RG_PAD_START;+ if (gg_vdp) {+ start_button = start;+ } else { /* the Master System's pause button (or the Game Gear's Start in its mode): an NMI */+ if (start && !st.pause) z80_gen_nmi(&cpu);+ st.pause = start;+ }+}++uint32_t sms_frame_us(void) { return pal ? 20120 : 16688; } /* (313 or 262 lines of 228 clocks) */+bool sms_is_gg(void) { return gg; }++void sms_reset(bool hard) {+ if (hard) {+ memset(ram, 0, 0x2000);+ memset(vram, 0, 0x4000);+ memset(&st, 0, sizeof st);+ /* the video chip as the BIOS leaves it */+ static const uint8_t regs[11] = {0x36, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0x00, 0x00, 0x00, 0xFF};+ memcpy(st.reg, regs, sizeof regs);+ st.counter = 0xFF;+ for (int i = 0; i < 32; i++) palette_update(i);+ memset(snap, 0, 240 * sizeof *snap);+ snap_lines = 0;+ }+ st.mapper[0] = 0, st.mapper[1] = 0, st.mapper[2] = 1;+ st.mapper[3] = mapper_kind == MAP_SEGA ? 2 : 0;+ st.line = 0, st.pause = 0;+ map_update();+ z80_init(&cpu);+ cpu.sp = 0xDFF0; /* (where the BIOS leaves it; a few games count on it) */+ line_start = line_end = 0;+ irq_update();+}++int sms_load(const uint8_t *data, uint32_t size, uint32_t crc, bool is_gg) {+ if ((size & 0x3FFF) == 512 && size > 512) data += 512, size -= 512; /* (a copier's header) */+ if (size < 0x400) return RG_ERR_ROM;+ rg_alloc_reset();+ ram = rg_alloc(0x2000), vram = rg_alloc(0x4000), sram = rg_alloc(0x8000);+ expand = rg_alloc(256 * sizeof *expand), snap = rg_alloc(240 * sizeof *snap);+ if (!ram || !vram || !sram || !expand || !snap) return RG_ERR_MEMORY;+ for (int b = 0; b < 256; b++) {+ uint32_t v = 0;+ for (int i = 0; i < 8; i++)+ if (b & (0x80 >> i)) v |= 1u << (4 * i);+ expand[b] = v;+ }+ rom = data, rom_size = size, banks = (size + 0x3FFF) >> 14;+ uint8_t flags = 0;+ for (unsigned i = 0; i < sizeof special / sizeof special[0]; i++)+ if (special[i].crc == crc) flags = special[i].flags;+ /* Codemasters' games say so: a checksum at $7FE6 and its complement after it */+ if (size > 0x8000) {+ unsigned sum = data[0x7FE6] | data[0x7FE7] << 8, inv = data[0x7FE8] | data[0x7FE9] << 8;+ if (sum && sum + inv == 0x10000) flags |= DB_CODIES;+ }+ mapper_kind = flags & DB_CODIES ? MAP_CODIES : flags & DB_KOREA ? MAP_KOREA : MAP_SEGA;+ pal = flags & DB_PAL;+ gg = is_gg, gg_vdp = is_gg && !(flags & DB_GGMS);+ pad_bits = 0, start_button = false, sram_dirty = false;+ sms_reset(true);+ return RG_OK;+}++/* ------------------------------------------------------------ saves */+uint8_t *sms_sram(uint32_t *size) {+ *size = 0x8000;+ return sram;+}+bool sms_sram_used(void) { return st.sram_on; }+bool sms_sram_dirty(void) { return sram_dirty; }+void sms_sram_saved(void) { sram_dirty = false; }+void sms_sram_loaded(void) { st.sram_on = 1, sram_dirty = false; }++int sms_state_chunks(rg_chunk_t *out) {+ out[0] = (rg_chunk_t){&cpu, sizeof cpu};+ out[1] = (rg_chunk_t){&st, sizeof st};+ out[2] = (rg_chunk_t){ram, 0x2000};+ out[3] = (rg_chunk_t){vram, 0x4000};+ out[4] = (rg_chunk_t){sram, 0x8000};+ return 5;+}++void sms_state_loaded(void) {+ z80_fix(&cpu);+ if (cpu.cyc > 64) cpu.cyc = 0;+ line_start = line_end = 0;+ if (st.line >= lines_per_frame()) st.line = 0;+ st.addr &= 0x3FFF, st.code &= 3, st.pending &= 1, st.vint &= 1, st.hint &= 1;+ st.sram_on &= 1, st.pause &= 1;+ if (st.counter < -1 || st.counter > 255) st.counter = st.reg[10];+ map_update();+ for (int i = 0; i < 32; i++) palette_update(i);+ irq_update();+ /* (the picture under the menus: this state's registers on every line) */+ snap_lines = height();+ for (int line = 0; line < snap_lines; line++) snap_line(line);+}diff --git a/games/retrogo/src/sms/sms.h b/games/retrogo/src/sms/sms.hnew file mode 100644index 00000000..e589ee27--- /dev/null+++ b/games/retrogo/src/sms/sms.h@@ -0,0 +1,36 @@+/* The Sega Master System and Game Gear (sms.c and superzazu's Z80), as Retro-Go's screens drive+ * them. */+#ifndef SMS_H+#define SMS_H+#include "../rg.h"++#define SMS_WIDTH 256+#define SMS_HEIGHT 240 /* (the tallest picture; most games show 192 lines) */++/* Loads a ROM read in place, a Game Gear's (gg) or a Master System's; crc is its CRC32, for the+ few games that need something of their own (the mapper, 50 Hz, Master System mode on the Game+ Gear). RG_OK or an RG_ERR_ code. */+int sms_load(const uint8_t *data, uint32_t size, uint32_t crc, bool gg);+void sms_reset(bool hard);+void sms_run_frame(bool draw);+void sms_set_pad(int rg_pad);+/* the picture shown: its first line and column and its size (the Game Gear's screen is a part of+ its video chip's) */+void sms_view(int *x, int *y, int *w, int *h);+/* a frame's length in microseconds: 60 frames a second, 50 for the European games that need it */+uint32_t sms_frame_us(void);+bool sms_is_gg(void);+/* the last frame drawn, line by line through rg_line again (under the menus) */+void sms_redraw(void);++/* the cartridge's RAM (32 KB), and whether the game has turned it on (only then is it saved) */+uint8_t *sms_sram(uint32_t *size);+bool sms_sram_used(void);+bool sms_sram_dirty(void);+void sms_sram_saved(void);+/* it was read back from a save: the game had it on */+void sms_sram_loaded(void);++int sms_state_chunks(rg_chunk_t *out);+void sms_state_loaded(void);+#endifdiff --git a/games/retrogo/src/sms/z80.c b/games/retrogo/src/sms/z80.cnew file mode 100644index 00000000..e426ce8d--- /dev/null+++ b/games/retrogo/src/sms/z80.c@@ -0,0 +1,1725 @@+/* superzazu's z80 (https://github.com/superzazu/z80), a Z80 emulator that passes zexdoc and+ * zexall, as the Master System's and Game Gear's processor.+ *+ * MIT License+ *+ * Copyright (c) 2019 Nicolas Allemand+ *+ * 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.+ *+ * Changed for NumPlay's Retro-Go (these changes are under the GNU GPL version 3 or later, like+ * NumPlay): memory read through z80_rmap's 1 KB pages and written, like the ports, through the+ * machine's functions (no function pointers); a byte for each flag instead of bit fields and+ * the carries and parity worked out at once (a calculator is slow at bit fields); the INT line+ * as a level the machine holds, taken before an instruction (EI holds it off for one); z80_run+ * for a stretch of clocks, skipping straight to its end while halted; nothing printed; OTDR's+ * repeat clocks; z80_fix for save states. */+#include "z80.h"++// MARK: timings+static const uint8_t cyc_00[256] = {4, 10, 7, 6, 4, 4, 7, 4, 4, 11, 7, 6, 4, 4,+ 7, 4, 8, 10, 7, 6, 4, 4, 7, 4, 12, 11, 7, 6, 4, 4, 7, 4, 7, 10, 16, 6, 4, 4,+ 7, 4, 7, 11, 16, 6, 4, 4, 7, 4, 7, 10, 13, 6, 11, 11, 10, 4, 7, 11, 13, 6,+ 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4,+ 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4,+ 7, 4, 7, 7, 7, 7, 7, 7, 4, 7, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7,+ 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4,+ 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4, 4, 4, 4, 4, 4, 7, 4, 4,+ 4, 4, 4, 4, 4, 7, 4, 5, 10, 10, 10, 10, 11, 7, 11, 5, 10, 10, 0, 10, 17, 7,+ 11, 5, 10, 10, 11, 10, 11, 7, 11, 5, 4, 10, 11, 10, 0, 7, 11, 5, 10, 10, 19,+ 10, 11, 7, 11, 5, 4, 10, 4, 10, 0, 7, 11, 5, 10, 10, 4, 10, 11, 7, 11, 5, 6,+ 10, 4, 10, 0, 7, 11};++static const uint8_t cyc_ed[256] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 12,+ 12, 15, 20, 8, 14, 8, 9, 12, 12, 15, 20, 8, 14, 8, 9, 12, 12, 15, 20, 8, 14,+ 8, 9, 12, 12, 15, 20, 8, 14, 8, 9, 12, 12, 15, 20, 8, 14, 8, 18, 12, 12, 15,+ 20, 8, 14, 8, 18, 12, 12, 15, 20, 8, 14, 8, 8, 12, 12, 15, 20, 8, 14, 8, 8,+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,+ 8, 8, 8, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8,+ 16, 16, 16, 16, 8, 8, 8, 8, 16, 16, 16, 16, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,+ 8, 8, 8, 8, 8, 8, 8};++static const uint8_t cyc_ddfd[256] = {4, 4, 4, 4, 4, 4, 4, 4, 4, 15, 4, 4, 4, 4,+ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 15, 4, 4, 4, 4, 4, 4, 4, 14, 20, 10, 8, 8,+ 11, 4, 4, 15, 20, 10, 8, 8, 11, 4, 4, 4, 4, 4, 23, 23, 19, 4, 4, 15, 4, 4,+ 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8,+ 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8, 8, 8, 8,+ 8, 19, 8, 19, 19, 19, 19, 19, 19, 4, 19, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4,+ 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4,+ 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4,+ 4, 8, 8, 19, 4, 4, 4, 4, 4, 8, 8, 19, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0,+ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 14, 4, 23, 4,+ 15, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 10, 4, 4, 4, 4,+ 4, 4};++// MARK: helpers++// get bit "n" of number "val"+#define GET_BIT(n, val) (((val) >> (n)) & 1)++static inline uint8_t rb(z80* const z, uint16_t addr) {+ (void)z;+ return z80_rmap[addr >> 10][addr & 0x3FF];+}++static inline void wb(z80* const z, uint16_t addr, uint8_t val) {+ (void)z;+ z80_bus_write(addr, val);+}++static inline uint16_t rw(z80* const z, uint16_t addr) {+ return (rb(z, addr + 1) << 8) | rb(z, addr);+}++static inline void ww(z80* const z, uint16_t addr, uint16_t val) {+ wb(z, addr, val & 0xFF);+ wb(z, addr + 1, val >> 8);+}++static inline void pushw(z80* const z, uint16_t val) {+ z->sp -= 2;+ ww(z, z->sp, val);+}++static inline uint16_t popw(z80* const z) {+ z->sp += 2;+ return rw(z, z->sp - 2);+}++static inline uint8_t nextb(z80* const z) {+ return rb(z, z->pc++);+}++static inline uint16_t nextw(z80* const z) {+ z->pc += 2;+ return rw(z, z->pc - 2);+}++static inline uint16_t get_bc(z80* const z) {+ return (z->b << 8) | z->c;+}++static inline uint16_t get_de(z80* const z) {+ return (z->d << 8) | z->e;+}++static inline uint16_t get_hl(z80* const z) {+ return (z->h << 8) | z->l;+}++static inline void set_bc(z80* const z, uint16_t val) {+ z->b = val >> 8;+ z->c = val & 0xFF;+}++static inline void set_de(z80* const z, uint16_t val) {+ z->d = val >> 8;+ z->e = val & 0xFF;+}++static inline void set_hl(z80* const z, uint16_t val) {+ z->h = val >> 8;+ z->l = val & 0xFF;+}++static inline uint8_t get_f(z80* const z) {+ uint8_t val = 0;+ val |= z->cf << 0;+ val |= z->nf << 1;+ val |= z->pf << 2;+ val |= z->xf << 3;+ val |= z->hf << 4;+ val |= z->yf << 5;+ val |= z->zf << 6;+ val |= z->sf << 7;+ return val;+}++static inline void set_f(z80* const z, uint8_t val) {+ z->cf = (val >> 0) & 1;+ z->nf = (val >> 1) & 1;+ z->pf = (val >> 2) & 1;+ z->xf = (val >> 3) & 1;+ z->hf = (val >> 4) & 1;+ z->yf = (val >> 5) & 1;+ z->zf = (val >> 6) & 1;+ z->sf = (val >> 7) & 1;+}++// increments R, keeping the highest byte intact+static inline void inc_r(z80* const z) {+ z->r = (z->r & 0x80) | ((z->r + 1) & 0x7f);+}++// returns the parity of byte: 0 if number of 1 bits in `val` is odd, else 1+static inline bool parity(uint8_t val) {+ val ^= val >> 4;+ return !((0x6996 >> (val & 15)) & 1);+}++static void exec_opcode(z80* const z, uint8_t opcode);+static void exec_opcode_cb(z80* const z, uint8_t opcode);+static void exec_opcode_dcb(+ z80* const z, const uint8_t opcode, const uint16_t addr);+static void exec_opcode_ed(z80* const z, uint8_t opcode);+static void exec_opcode_ddfd(z80* const z, uint8_t opcode, uint16_t* const iz);++// MARK: opcodes+// jumps to an address+static inline void jump(z80* const z, uint16_t addr) {+ z->pc = addr;+ z->mem_ptr = addr;+}++// jumps to next word in memory if condition is true+static inline void cond_jump(z80* const z, bool condition) {+ const uint16_t addr = nextw(z);+ if (condition) {+ jump(z, addr);+ }+ z->mem_ptr = addr;+}++// calls to next word in memory+static inline void call(z80* const z, uint16_t addr) {+ pushw(z, z->pc);+ z->pc = addr;+ z->mem_ptr = addr;+}++// calls to next word in memory if condition is true+static inline void cond_call(z80* const z, bool condition) {+ const uint16_t addr = nextw(z);+ if (condition) {+ call(z, addr);+ z->cyc += 7;+ }+ z->mem_ptr = addr;+}++// returns from subroutine+static inline void ret(z80* const z) {+ z->pc = popw(z);+ z->mem_ptr = z->pc;+}++// returns from subroutine if condition is true+static inline void cond_ret(z80* const z, bool condition) {+ if (condition) {+ ret(z);+ z->cyc += 6;+ }+}++static inline void jr(z80* const z, int8_t displacement) {+ z->pc += displacement;+ z->mem_ptr = z->pc;+}++static inline void cond_jr(z80* const z, bool condition) {+ const int8_t b = nextb(z);+ if (condition) {+ jr(z, b);+ z->cyc += 5;+ }+}++// ADD Byte: adds two bytes together+static inline uint8_t addb(z80* const z, uint8_t a, uint8_t b, bool cy) {+ const unsigned sum = a + b + cy, carries = sum ^ a ^ b;+ const uint8_t result = sum;+ z->sf = result >> 7;+ z->zf = result == 0;+ z->hf = (carries >> 4) & 1;+ z->pf = ((carries >> 7) ^ (carries >> 8)) & 1;+ z->cf = (carries >> 8) & 1;+ z->nf = 0;+ z->xf = GET_BIT(3, result);+ z->yf = GET_BIT(5, result);+ return result;+}++// SUBstract Byte: substracts two bytes (with optional carry)+static inline uint8_t subb(z80* const z, uint8_t a, uint8_t b, bool cy) {+ uint8_t val = addb(z, a, ~b, !cy);+ z->cf = !z->cf;+ z->hf = !z->hf;+ z->nf = 1;+ return val;+}++// ADD Word: adds two words together+static inline uint16_t addw(z80* const z, uint16_t a, uint16_t b, bool cy) {+ uint8_t lsb = addb(z, a, b, cy);+ uint8_t msb = addb(z, a >> 8, b >> 8, z->cf);++ uint16_t result = (msb << 8) | lsb;+ z->zf = result == 0;+ z->mem_ptr = a + 1;+ return result;+}++// SUBstract Word: substracts two words (with optional carry)+static inline uint16_t subw(z80* const z, uint16_t a, uint16_t b, bool cy) {+ uint8_t lsb = subb(z, a, b, cy);+ uint8_t msb = subb(z, a >> 8, b >> 8, z->cf);++ uint16_t result = (msb << 8) | lsb;+ z->zf = result == 0;+ z->mem_ptr = a + 1;+ return result;+}++// adds a word to HL+static inline void addhl(z80* const z, uint16_t val) {+ bool sf = z->sf;+ bool zf = z->zf;+ bool pf = z->pf;+ uint16_t result = addw(z, get_hl(z), val, 0);+ set_hl(z, result);+ z->sf = sf;+ z->zf = zf;+ z->pf = pf;+}++// adds a word to IX or IY+static inline void addiz(z80* const z, uint16_t* reg, uint16_t val) {+ bool sf = z->sf;+ bool zf = z->zf;+ bool pf = z->pf;+ uint16_t result = addw(z, *reg, val, 0);+ *reg = result;+ z->sf = sf;+ z->zf = zf;+ z->pf = pf;+}++// adds a word (+ carry) to HL+static inline void adchl(z80* const z, uint16_t val) {+ uint16_t result = addw(z, get_hl(z), val, z->cf);+ z->sf = result >> 15;+ z->zf = result == 0;+ set_hl(z, result);+}++// substracts a word (+ carry) to HL+static inline void sbchl(z80* const z, uint16_t val) {+ const uint16_t result = subw(z, get_hl(z), val, z->cf);+ z->sf = result >> 15;+ z->zf = result == 0;+ set_hl(z, result);+}++// increments a byte value+static inline uint8_t inc(z80* const z, uint8_t a) {+ bool cf = z->cf;+ uint8_t result = addb(z, a, 1, 0);+ z->cf = cf;+ return result;+}++// decrements a byte value+static inline uint8_t dec(z80* const z, uint8_t a) {+ bool cf = z->cf;+ uint8_t result = subb(z, a, 1, 0);+ z->cf = cf;+ return result;+}++// MARK: bitwise++// executes a logic "and" between register A and a byte, then stores the+// result in register A+static inline void land(z80* const z, uint8_t val) {+ const uint8_t result = z->a & val;+ z->sf = result >> 7;+ z->zf = result == 0;+ z->hf = 1;+ z->pf = parity(result);+ z->nf = 0;+ z->cf = 0;+ z->xf = GET_BIT(3, result);+ z->yf = GET_BIT(5, result);+ z->a = result;+}++// executes a logic "xor" between register A and a byte, then stores the+// result in register A+static inline void lxor(z80* const z, const uint8_t val) {+ const uint8_t result = z->a ^ val;+ z->sf = result >> 7;+ z->zf = result == 0;+ z->hf = 0;+ z->pf = parity(result);+ z->nf = 0;+ z->cf = 0;+ z->xf = GET_BIT(3, result);+ z->yf = GET_BIT(5, result);+ z->a = result;+}++// executes a logic "or" between register A and a byte, then stores the+// result in register A+static inline void lor(z80* const z, const uint8_t val) {+ const uint8_t result = z->a | val;+ z->sf = result >> 7;+ z->zf = result == 0;+ z->hf = 0;+ z->pf = parity(result);+ z->nf = 0;+ z->cf = 0;+ z->xf = GET_BIT(3, result);+ z->yf = GET_BIT(5, result);+ z->a = result;+}++// compares a value with register A+static inline void cp(z80* const z, const uint8_t val) {+ subb(z, z->a, val, 0);++ // the only difference between cp and sub is that+ // the xf/yf are taken from the value to be substracted,+ // not the result+ z->yf = GET_BIT(5, val);+ z->xf = GET_BIT(3, val);+}++// 0xCB opcodes+// rotate left with carry+static inline uint8_t cb_rlc(z80* const z, uint8_t val) {+ const bool old = val >> 7;+ val = (val << 1) | old;+ z->sf = val >> 7;+ z->zf = val == 0;+ z->pf = parity(val);+ z->nf = 0;+ z->hf = 0;+ z->cf = old;+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// rotate right with carry+static inline uint8_t cb_rrc(z80* const z, uint8_t val) {+ const bool old = val & 1;+ val = (val >> 1) | (old << 7);+ z->sf = val >> 7;+ z->zf = val == 0;+ z->nf = 0;+ z->hf = 0;+ z->cf = old;+ z->pf = parity(val);+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// rotate left (simple)+static inline uint8_t cb_rl(z80* const z, uint8_t val) {+ const bool cf = z->cf;+ z->cf = val >> 7;+ val = (val << 1) | cf;+ z->sf = val >> 7;+ z->zf = val == 0;+ z->nf = 0;+ z->hf = 0;+ z->pf = parity(val);+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// rotate right (simple)+static inline uint8_t cb_rr(z80* const z, uint8_t val) {+ const bool c = z->cf;+ z->cf = val & 1;+ val = (val >> 1) | (c << 7);+ z->sf = val >> 7;+ z->zf = val == 0;+ z->nf = 0;+ z->hf = 0;+ z->pf = parity(val);+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// shift left preserving sign+static inline uint8_t cb_sla(z80* const z, uint8_t val) {+ z->cf = val >> 7;+ val <<= 1;+ z->sf = val >> 7;+ z->zf = val == 0;+ z->nf = 0;+ z->hf = 0;+ z->pf = parity(val);+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// SLL (exactly like SLA, but sets the first bit to 1)+static inline uint8_t cb_sll(z80* const z, uint8_t val) {+ z->cf = val >> 7;+ val <<= 1;+ val |= 1;+ z->sf = val >> 7;+ z->zf = val == 0;+ z->nf = 0;+ z->hf = 0;+ z->pf = parity(val);+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// shift right preserving sign+static inline uint8_t cb_sra(z80* const z, uint8_t val) {+ z->cf = val & 1;+ val = (val >> 1) | (val & 0x80); // 0b10000000+ z->sf = val >> 7;+ z->zf = val == 0;+ z->nf = 0;+ z->hf = 0;+ z->pf = parity(val);+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// shift register right+static inline uint8_t cb_srl(z80* const z, uint8_t val) {+ z->cf = val & 1;+ val >>= 1;+ z->sf = val >> 7;+ z->zf = val == 0;+ z->nf = 0;+ z->hf = 0;+ z->pf = parity(val);+ z->xf = GET_BIT(3, val);+ z->yf = GET_BIT(5, val);+ return val;+}++// tests bit "n" from a byte+static inline uint8_t cb_bit(z80* const z, uint8_t val, uint8_t n) {+ const uint8_t result = val & (1 << n);+ z->sf = result >> 7;+ z->zf = result == 0;+ z->yf = GET_BIT(5, val);+ z->hf = 1;+ z->xf = GET_BIT(3, val);+ z->pf = z->zf;+ z->nf = 0;+ return result;+}++static inline void ldi(z80* const z) {+ const uint16_t de = get_de(z);+ const uint16_t hl = get_hl(z);+ const uint8_t val = rb(z, hl);++ wb(z, de, val);++ set_hl(z, get_hl(z) + 1);+ set_de(z, get_de(z) + 1);+ set_bc(z, get_bc(z) - 1);++ // see https://wikiti.brandonw.net/index.php?title=Z80_Instruction_Set+ // for the calculation of xf/yf on LDI+ const uint8_t result = val + z->a;+ z->xf = GET_BIT(3, result);+ z->yf = GET_BIT(1, result);++ z->nf = 0;+ z->hf = 0;+ z->pf = get_bc(z) > 0;+}++static inline void ldd(z80* const z) {+ ldi(z);+ // same as ldi but HL and DE are decremented instead of incremented+ set_hl(z, get_hl(z) - 2);+ set_de(z, get_de(z) - 2);+}++static inline void cpi(z80* const z) {+ bool cf = z->cf;+ const uint8_t result = subb(z, z->a, rb(z, get_hl(z)), 0);+ set_hl(z, get_hl(z) + 1);+ set_bc(z, get_bc(z) - 1);+ z->xf = GET_BIT(3, result - z->hf);+ z->yf = GET_BIT(1, result - z->hf);+ z->pf = get_bc(z) != 0;+ z->cf = cf;+ z->mem_ptr += 1;+}++static inline void cpd(z80* const z) {+ cpi(z);+ // same as cpi but HL is decremented instead of incremented+ set_hl(z, get_hl(z) - 2);+ z->mem_ptr -= 2;+}++static void in_r_c(z80* const z, uint8_t* r) {+ *r = z80_bus_in(z->c);+ z->zf = *r == 0;+ z->sf = *r >> 7;+ z->pf = parity(*r);+ z->nf = 0;+ z->hf = 0;+}++static void ini(z80* const z) {+ uint8_t val = z80_bus_in(z->c);+ wb(z, get_hl(z), val);+ set_hl(z, get_hl(z) + 1);+ z->b -= 1;+ z->zf = z->b == 0;+ z->nf = 1;+ z->mem_ptr = get_bc(z) + 1;+}++static void ind(z80* const z) {+ ini(z);+ set_hl(z, get_hl(z) - 2);+ z->mem_ptr = get_bc(z) - 2;+}++static void outi(z80* const z) {+ z80_bus_out(z->c, rb(z, get_hl(z)));+ set_hl(z, get_hl(z) + 1);+ z->b -= 1;+ z->zf = z->b == 0;+ z->nf = 1;+ z->mem_ptr = get_bc(z) + 1;+}++static void outd(z80* const z) {+ outi(z);+ set_hl(z, get_hl(z) - 2);+ z->mem_ptr = get_bc(z) - 2;+}++static void daa(z80* const z) {+ // "When this instruction is executed, the A register is BCD corrected+ // using the contents of the flags. The exact process is the following:+ // if the least significant four bits of A contain a non-BCD digit+ // (i. e. it is greater than 9) or the H flag is set, then $06 is+ // added to the register. Then the four most significant bits are+ // checked. If this more significant digit also happens to be greater+ // than 9 or the C flag is set, then $60 is added."+ // > http://z80-heaven.wikidot.com/instructions-set:daa+ uint8_t correction = 0;++ if ((z->a & 0x0F) > 0x09 || z->hf) {+ correction += 0x06;+ }++ if (z->a > 0x99 || z->cf) {+ correction += 0x60;+ z->cf = 1;+ }++ const bool substraction = z->nf;+ if (substraction) {+ z->hf = z->hf && (z->a & 0x0F) < 0x06;+ z->a -= correction;+ } else {+ z->hf = (z->a & 0x0F) > 0x09;+ z->a += correction;+ }++ z->sf = z->a >> 7;+ z->zf = z->a == 0;+ z->pf = parity(z->a);+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+}++static inline uint16_t displace(+ z80* const z, uint16_t base_addr, int8_t displacement) {+ const uint16_t addr = base_addr + displacement;+ z->mem_ptr = addr;+ return addr;+}++// the INT line taken: in mode 2 through the table at I (the bus floats at+// 0xFF), in modes 0 and 1 to 0x38 (in mode 0, the 0xFF on the bus is RST 38h)+static void take_int(z80* const z) {+ z->halted = 0;+ z->iff1 = 0;+ z->iff2 = 0;+ inc_r(z);+ if (z->interrupt_mode == 2) {+ z->cyc += 19;+ call(z, rw(z, (z->i << 8) | 0xFF));+ } else {+ z->cyc += 13;+ call(z, 0x38);+ }+}++static void take_nmi(z80* const z) {+ z->nmi_pending = 0;+ z->halted = 0;+ z->iff1 = 0;+ inc_r(z);+ z->cyc += 11;+ call(z, 0x66);+}++// MARK: interface+// the Z80 as it comes out of a reset+void z80_init(z80* const z) {+ *z = (z80){0};+ z->sp = 0xFFFF;+ // af and sp are set to 0xFFFF after reset,+ // and the other values are undefined (z80-documented)+ z->a = 0xFF;+ z->sf = z->zf = z->yf = z->hf = z->xf = z->pf = z->nf = z->cf = 1;+ z->ix = z->iy = 0xFFFF;+}++void z80_run(z80* const z, uint32_t until) {+ while ((int32_t)(z->cyc - until) < 0) {+ // (interrupts between instructions, never right after EI)+ if (z->nmi_pending) {+ take_nmi(z);+ } else if (z->irq_line && z->iff1 && !z->ei_shadow) {+ take_int(z);+ }+ z->ei_shadow = 0;+ if (z->halted) {+ // NOPs to the end: nothing wakes it before, the machine moves its lines+ // only between runs+ const uint32_t n = (until - z->cyc + 3) / 4;+ z->cyc += n * 4;+ z->r = (z->r & 0x80) | ((z->r + n) & 0x7f);+ return;+ }+ exec_opcode(z, nextb(z));+ }+}++// an NMI to take (the Master System's pause button)+void z80_gen_nmi(z80* const z) {+ z->nmi_pending = 1;+}++void z80_fix(z80* const z) {+ uint8_t* const bits[] = {&z->sf, &z->zf, &z->yf, &z->hf, &z->xf, &z->pf,+ &z->nf, &z->cf, &z->ei_shadow, &z->iff1, &z->iff2, &z->halted,+ &z->irq_line, &z->nmi_pending};+ for (unsigned k = 0; k < sizeof bits / sizeof bits[0]; k++) {+ *bits[k] &= 1;+ }+ if (z->interrupt_mode > 2) {+ z->interrupt_mode = 1;+ }+}++// executes a non-prefixed opcode+void exec_opcode(z80* const z, uint8_t opcode) {+ z->cyc += cyc_00[opcode];+ inc_r(z);++ switch (opcode) {+ case 0x7F: z->a = z->a; break; // ld a,a+ case 0x78: z->a = z->b; break; // ld a,b+ case 0x79: z->a = z->c; break; // ld a,c+ case 0x7A: z->a = z->d; break; // ld a,d+ case 0x7B: z->a = z->e; break; // ld a,e+ case 0x7C: z->a = z->h; break; // ld a,h+ case 0x7D: z->a = z->l; break; // ld a,l++ case 0x47: z->b = z->a; break; // ld b,a+ case 0x40: z->b = z->b; break; // ld b,b+ case 0x41: z->b = z->c; break; // ld b,c+ case 0x42: z->b = z->d; break; // ld b,d+ case 0x43: z->b = z->e; break; // ld b,e+ case 0x44: z->b = z->h; break; // ld b,h+ case 0x45: z->b = z->l; break; // ld b,l++ case 0x4F: z->c = z->a; break; // ld c,a+ case 0x48: z->c = z->b; break; // ld c,b+ case 0x49: z->c = z->c; break; // ld c,c+ case 0x4A: z->c = z->d; break; // ld c,d+ case 0x4B: z->c = z->e; break; // ld c,e+ case 0x4C: z->c = z->h; break; // ld c,h+ case 0x4D: z->c = z->l; break; // ld c,l++ case 0x57: z->d = z->a; break; // ld d,a+ case 0x50: z->d = z->b; break; // ld d,b+ case 0x51: z->d = z->c; break; // ld d,c+ case 0x52: z->d = z->d; break; // ld d,d+ case 0x53: z->d = z->e; break; // ld d,e+ case 0x54: z->d = z->h; break; // ld d,h+ case 0x55: z->d = z->l; break; // ld d,l++ case 0x5F: z->e = z->a; break; // ld e,a+ case 0x58: z->e = z->b; break; // ld e,b+ case 0x59: z->e = z->c; break; // ld e,c+ case 0x5A: z->e = z->d; break; // ld e,d+ case 0x5B: z->e = z->e; break; // ld e,e+ case 0x5C: z->e = z->h; break; // ld e,h+ case 0x5D: z->e = z->l; break; // ld e,l++ case 0x67: z->h = z->a; break; // ld h,a+ case 0x60: z->h = z->b; break; // ld h,b+ case 0x61: z->h = z->c; break; // ld h,c+ case 0x62: z->h = z->d; break; // ld h,d+ case 0x63: z->h = z->e; break; // ld h,e+ case 0x64: z->h = z->h; break; // ld h,h+ case 0x65: z->h = z->l; break; // ld h,l++ case 0x6F: z->l = z->a; break; // ld l,a+ case 0x68: z->l = z->b; break; // ld l,b+ case 0x69: z->l = z->c; break; // ld l,c+ case 0x6A: z->l = z->d; break; // ld l,d+ case 0x6B: z->l = z->e; break; // ld l,e+ case 0x6C: z->l = z->h; break; // ld l,h+ case 0x6D: z->l = z->l; break; // ld l,l++ case 0x7E: z->a = rb(z, get_hl(z)); break; // ld a,(hl)+ case 0x46: z->b = rb(z, get_hl(z)); break; // ld b,(hl)+ case 0x4E: z->c = rb(z, get_hl(z)); break; // ld c,(hl)+ case 0x56: z->d = rb(z, get_hl(z)); break; // ld d,(hl)+ case 0x5E: z->e = rb(z, get_hl(z)); break; // ld e,(hl)+ case 0x66: z->h = rb(z, get_hl(z)); break; // ld h,(hl)+ case 0x6E: z->l = rb(z, get_hl(z)); break; // ld l,(hl)++ case 0x77: wb(z, get_hl(z), z->a); break; // ld (hl),a+ case 0x70: wb(z, get_hl(z), z->b); break; // ld (hl),b+ case 0x71: wb(z, get_hl(z), z->c); break; // ld (hl),c+ case 0x72: wb(z, get_hl(z), z->d); break; // ld (hl),d+ case 0x73: wb(z, get_hl(z), z->e); break; // ld (hl),e+ case 0x74: wb(z, get_hl(z), z->h); break; // ld (hl),h+ case 0x75: wb(z, get_hl(z), z->l); break; // ld (hl),l++ case 0x3E: z->a = nextb(z); break; // ld a,*+ case 0x06: z->b = nextb(z); break; // ld b,*+ case 0x0E: z->c = nextb(z); break; // ld c,*+ case 0x16: z->d = nextb(z); break; // ld d,*+ case 0x1E: z->e = nextb(z); break; // ld e,*+ case 0x26: z->h = nextb(z); break; // ld h,*+ case 0x2E: z->l = nextb(z); break; // ld l,*+ case 0x36: wb(z, get_hl(z), nextb(z)); break; // ld (hl),*++ case 0x0A:+ z->a = rb(z, get_bc(z));+ z->mem_ptr = get_bc(z) + 1;+ break; // ld a,(bc)+ case 0x1A:+ z->a = rb(z, get_de(z));+ z->mem_ptr = get_de(z) + 1;+ break; // ld a,(de)+ case 0x3A: {+ const uint16_t addr = nextw(z);+ z->a = rb(z, addr);+ z->mem_ptr = addr + 1;+ } break; // ld a,(**)++ case 0x02:+ wb(z, get_bc(z), z->a);+ z->mem_ptr = (z->a << 8) | ((get_bc(z) + 1) & 0xFF);+ break; // ld (bc),a++ case 0x12:+ wb(z, get_de(z), z->a);+ z->mem_ptr = (z->a << 8) | ((get_de(z) + 1) & 0xFF);+ break; // ld (de),a++ case 0x32: {+ const uint16_t addr = nextw(z);+ wb(z, addr, z->a);+ z->mem_ptr = (z->a << 8) | ((addr + 1) & 0xFF);+ } break; // ld (**),a++ case 0x01: set_bc(z, nextw(z)); break; // ld bc,**+ case 0x11: set_de(z, nextw(z)); break; // ld de,**+ case 0x21: set_hl(z, nextw(z)); break; // ld hl,**+ case 0x31: z->sp = nextw(z); break; // ld sp,**++ case 0x2A: {+ const uint16_t addr = nextw(z);+ set_hl(z, rw(z, addr));+ z->mem_ptr = addr + 1;+ } break; // ld hl,(**)++ case 0x22: {+ const uint16_t addr = nextw(z);+ ww(z, addr, get_hl(z));+ z->mem_ptr = addr + 1;+ } break; // ld (**),hl++ case 0xF9: z->sp = get_hl(z); break; // ld sp,hl++ case 0xEB: {+ const uint16_t de = get_de(z);+ set_de(z, get_hl(z));+ set_hl(z, de);+ } break; // ex de,hl++ case 0xE3: {+ const uint16_t val = rw(z, z->sp);+ ww(z, z->sp, get_hl(z));+ set_hl(z, val);+ z->mem_ptr = val;+ } break; // ex (sp),hl++ case 0x87: z->a = addb(z, z->a, z->a, 0); break; // add a,a+ case 0x80: z->a = addb(z, z->a, z->b, 0); break; // add a,b+ case 0x81: z->a = addb(z, z->a, z->c, 0); break; // add a,c+ case 0x82: z->a = addb(z, z->a, z->d, 0); break; // add a,d+ case 0x83: z->a = addb(z, z->a, z->e, 0); break; // add a,e+ case 0x84: z->a = addb(z, z->a, z->h, 0); break; // add a,h+ case 0x85: z->a = addb(z, z->a, z->l, 0); break; // add a,l+ case 0x86: z->a = addb(z, z->a, rb(z, get_hl(z)), 0); break; // add a,(hl)+ case 0xC6: z->a = addb(z, z->a, nextb(z), 0); break; // add a,*++ case 0x8F: z->a = addb(z, z->a, z->a, z->cf); break; // adc a,a+ case 0x88: z->a = addb(z, z->a, z->b, z->cf); break; // adc a,b+ case 0x89: z->a = addb(z, z->a, z->c, z->cf); break; // adc a,c+ case 0x8A: z->a = addb(z, z->a, z->d, z->cf); break; // adc a,d+ case 0x8B: z->a = addb(z, z->a, z->e, z->cf); break; // adc a,e+ case 0x8C: z->a = addb(z, z->a, z->h, z->cf); break; // adc a,h+ case 0x8D: z->a = addb(z, z->a, z->l, z->cf); break; // adc a,l+ case 0x8E: z->a = addb(z, z->a, rb(z, get_hl(z)), z->cf); break; // adc a,(hl)+ case 0xCE: z->a = addb(z, z->a, nextb(z), z->cf); break; // adc a,*++ case 0x97: z->a = subb(z, z->a, z->a, 0); break; // sub a,a+ case 0x90: z->a = subb(z, z->a, z->b, 0); break; // sub a,b+ case 0x91: z->a = subb(z, z->a, z->c, 0); break; // sub a,c+ case 0x92: z->a = subb(z, z->a, z->d, 0); break; // sub a,d+ case 0x93: z->a = subb(z, z->a, z->e, 0); break; // sub a,e+ case 0x94: z->a = subb(z, z->a, z->h, 0); break; // sub a,h+ case 0x95: z->a = subb(z, z->a, z->l, 0); break; // sub a,l+ case 0x96: z->a = subb(z, z->a, rb(z, get_hl(z)), 0); break; // sub a,(hl)+ case 0xD6: z->a = subb(z, z->a, nextb(z), 0); break; // sub a,*++ case 0x9F: z->a = subb(z, z->a, z->a, z->cf); break; // sbc a,a+ case 0x98: z->a = subb(z, z->a, z->b, z->cf); break; // sbc a,b+ case 0x99: z->a = subb(z, z->a, z->c, z->cf); break; // sbc a,c+ case 0x9A: z->a = subb(z, z->a, z->d, z->cf); break; // sbc a,d+ case 0x9B: z->a = subb(z, z->a, z->e, z->cf); break; // sbc a,e+ case 0x9C: z->a = subb(z, z->a, z->h, z->cf); break; // sbc a,h+ case 0x9D: z->a = subb(z, z->a, z->l, z->cf); break; // sbc a,l+ case 0x9E: z->a = subb(z, z->a, rb(z, get_hl(z)), z->cf); break; // sbc a,(hl)+ case 0xDE: z->a = subb(z, z->a, nextb(z), z->cf); break; // sbc a,*++ case 0x09: addhl(z, get_bc(z)); break; // add hl,bc+ case 0x19: addhl(z, get_de(z)); break; // add hl,de+ case 0x29: addhl(z, get_hl(z)); break; // add hl,hl+ case 0x39: addhl(z, z->sp); break; // add hl,sp++ case 0xF3:+ z->iff1 = 0;+ z->iff2 = 0;+ break; // di+ case 0xFB:+ z->iff1 = 1;+ z->iff2 = 1;+ z->ei_shadow = 1;+ break; // ei+ case 0x00: break; // nop+ case 0x76: z->halted = 1; break; // halt++ case 0x3C: z->a = inc(z, z->a); break; // inc a+ case 0x04: z->b = inc(z, z->b); break; // inc b+ case 0x0C: z->c = inc(z, z->c); break; // inc c+ case 0x14: z->d = inc(z, z->d); break; // inc d+ case 0x1C: z->e = inc(z, z->e); break; // inc e+ case 0x24: z->h = inc(z, z->h); break; // inc h+ case 0x2C: z->l = inc(z, z->l); break; // inc l+ case 0x34: {+ uint8_t result = inc(z, rb(z, get_hl(z)));+ wb(z, get_hl(z), result);+ } break; // inc (hl)++ case 0x3D: z->a = dec(z, z->a); break; // dec a+ case 0x05: z->b = dec(z, z->b); break; // dec b+ case 0x0D: z->c = dec(z, z->c); break; // dec c+ case 0x15: z->d = dec(z, z->d); break; // dec d+ case 0x1D: z->e = dec(z, z->e); break; // dec e+ case 0x25: z->h = dec(z, z->h); break; // dec h+ case 0x2D: z->l = dec(z, z->l); break; // dec l+ case 0x35: {+ uint8_t result = dec(z, rb(z, get_hl(z)));+ wb(z, get_hl(z), result);+ } break; // dec (hl)++ case 0x03: set_bc(z, get_bc(z) + 1); break; // inc bc+ case 0x13: set_de(z, get_de(z) + 1); break; // inc de+ case 0x23: set_hl(z, get_hl(z) + 1); break; // inc hl+ case 0x33: z->sp = z->sp + 1; break; // inc sp++ case 0x0B: set_bc(z, get_bc(z) - 1); break; // dec bc+ case 0x1B: set_de(z, get_de(z) - 1); break; // dec de+ case 0x2B: set_hl(z, get_hl(z) - 1); break; // dec hl+ case 0x3B: z->sp = z->sp - 1; break; // dec sp++ case 0x27: daa(z); break; // daa++ case 0x2F:+ z->a = ~z->a;+ z->nf = 1;+ z->hf = 1;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ break; // cpl++ case 0x37:+ z->cf = 1;+ z->nf = 0;+ z->hf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ break; // scf++ case 0x3F:+ z->hf = z->cf;+ z->cf = !z->cf;+ z->nf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ break; // ccf++ case 0x07: {+ z->cf = z->a >> 7;+ z->a = (z->a << 1) | z->cf;+ z->nf = 0;+ z->hf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ } break; // rlca (rotate left)++ case 0x0F: {+ z->cf = z->a & 1;+ z->a = (z->a >> 1) | (z->cf << 7);+ z->nf = 0;+ z->hf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ } break; // rrca (rotate right)++ case 0x17: {+ const bool cy = z->cf;+ z->cf = z->a >> 7;+ z->a = (z->a << 1) | cy;+ z->nf = 0;+ z->hf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ } break; // rla++ case 0x1F: {+ const bool cy = z->cf;+ z->cf = z->a & 1;+ z->a = (z->a >> 1) | (cy << 7);+ z->nf = 0;+ z->hf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ } break; // rra++ case 0xA7: land(z, z->a); break; // and a+ case 0xA0: land(z, z->b); break; // and b+ case 0xA1: land(z, z->c); break; // and c+ case 0xA2: land(z, z->d); break; // and d+ case 0xA3: land(z, z->e); break; // and e+ case 0xA4: land(z, z->h); break; // and h+ case 0xA5: land(z, z->l); break; // and l+ case 0xA6: land(z, rb(z, get_hl(z))); break; // and (hl)+ case 0xE6: land(z, nextb(z)); break; // and *++ case 0xAF: lxor(z, z->a); break; // xor a+ case 0xA8: lxor(z, z->b); break; // xor b+ case 0xA9: lxor(z, z->c); break; // xor c+ case 0xAA: lxor(z, z->d); break; // xor d+ case 0xAB: lxor(z, z->e); break; // xor e+ case 0xAC: lxor(z, z->h); break; // xor h+ case 0xAD: lxor(z, z->l); break; // xor l+ case 0xAE: lxor(z, rb(z, get_hl(z))); break; // xor (hl)+ case 0xEE: lxor(z, nextb(z)); break; // xor *++ case 0xB7: lor(z, z->a); break; // or a+ case 0xB0: lor(z, z->b); break; // or b+ case 0xB1: lor(z, z->c); break; // or c+ case 0xB2: lor(z, z->d); break; // or d+ case 0xB3: lor(z, z->e); break; // or e+ case 0xB4: lor(z, z->h); break; // or h+ case 0xB5: lor(z, z->l); break; // or l+ case 0xB6: lor(z, rb(z, get_hl(z))); break; // or (hl)+ case 0xF6: lor(z, nextb(z)); break; // or *++ case 0xBF: cp(z, z->a); break; // cp a+ case 0xB8: cp(z, z->b); break; // cp b+ case 0xB9: cp(z, z->c); break; // cp c+ case 0xBA: cp(z, z->d); break; // cp d+ case 0xBB: cp(z, z->e); break; // cp e+ case 0xBC: cp(z, z->h); break; // cp h+ case 0xBD: cp(z, z->l); break; // cp l+ case 0xBE: cp(z, rb(z, get_hl(z))); break; // cp (hl)+ case 0xFE: cp(z, nextb(z)); break; // cp *++ case 0xC3: jump(z, nextw(z)); break; // jm **+ case 0xC2: cond_jump(z, z->zf == 0); break; // jp nz, **+ case 0xCA: cond_jump(z, z->zf == 1); break; // jp z, **+ case 0xD2: cond_jump(z, z->cf == 0); break; // jp nc, **+ case 0xDA: cond_jump(z, z->cf == 1); break; // jp c, **+ case 0xE2: cond_jump(z, z->pf == 0); break; // jp po, **+ case 0xEA: cond_jump(z, z->pf == 1); break; // jp pe, **+ case 0xF2: cond_jump(z, z->sf == 0); break; // jp p, **+ case 0xFA: cond_jump(z, z->sf == 1); break; // jp m, **++ case 0x10: cond_jr(z, --z->b != 0); break; // djnz *+ case 0x18: z->pc += (int8_t) nextb(z); break; // jr *+ case 0x20: cond_jr(z, z->zf == 0); break; // jr nz, *+ case 0x28: cond_jr(z, z->zf == 1); break; // jr z, *+ case 0x30: cond_jr(z, z->cf == 0); break; // jr nc, *+ case 0x38: cond_jr(z, z->cf == 1); break; // jr c, *++ case 0xE9: z->pc = get_hl(z); break; // jp (hl)+ case 0xCD: call(z, nextw(z)); break; // call++ case 0xC4: cond_call(z, z->zf == 0); break; // cnz+ case 0xCC: cond_call(z, z->zf == 1); break; // cz+ case 0xD4: cond_call(z, z->cf == 0); break; // cnc+ case 0xDC: cond_call(z, z->cf == 1); break; // cc+ case 0xE4: cond_call(z, z->pf == 0); break; // cpo+ case 0xEC: cond_call(z, z->pf == 1); break; // cpe+ case 0xF4: cond_call(z, z->sf == 0); break; // cp+ case 0xFC: cond_call(z, z->sf == 1); break; // cm++ case 0xC9: ret(z); break; // ret+ case 0xC0: cond_ret(z, z->zf == 0); break; // ret nz+ case 0xC8: cond_ret(z, z->zf == 1); break; // ret z+ case 0xD0: cond_ret(z, z->cf == 0); break; // ret nc+ case 0xD8: cond_ret(z, z->cf == 1); break; // ret c+ case 0xE0: cond_ret(z, z->pf == 0); break; // ret po+ case 0xE8: cond_ret(z, z->pf == 1); break; // ret pe+ case 0xF0: cond_ret(z, z->sf == 0); break; // ret p+ case 0xF8: cond_ret(z, z->sf == 1); break; // ret m++ case 0xC7: call(z, 0x00); break; // rst 0+ case 0xCF: call(z, 0x08); break; // rst 1+ case 0xD7: call(z, 0x10); break; // rst 2+ case 0xDF: call(z, 0x18); break; // rst 3+ case 0xE7: call(z, 0x20); break; // rst 4+ case 0xEF: call(z, 0x28); break; // rst 5+ case 0xF7: call(z, 0x30); break; // rst 6+ case 0xFF: call(z, 0x38); break; // rst 7++ case 0xC5: pushw(z, get_bc(z)); break; // push bc+ case 0xD5: pushw(z, get_de(z)); break; // push de+ case 0xE5: pushw(z, get_hl(z)); break; // push hl+ case 0xF5: pushw(z, (z->a << 8) | get_f(z)); break; // push af++ case 0xC1: set_bc(z, popw(z)); break; // pop bc+ case 0xD1: set_de(z, popw(z)); break; // pop de+ case 0xE1: set_hl(z, popw(z)); break; // pop hl+ case 0xF1: {+ uint16_t val = popw(z);+ z->a = val >> 8;+ set_f(z, val & 0xFF);+ } break; // pop af++ case 0xDB: {+ const uint8_t port = nextb(z);+ const uint8_t a = z->a;+ z->a = z80_bus_in(port);+ z->mem_ptr = (a << 8) | (z->a + 1);+ } break; // in a,(n)++ case 0xD3: {+ const uint8_t port = nextb(z);+ z80_bus_out(port, z->a);+ z->mem_ptr = (port + 1) | (z->a << 8);+ } break; // out (n), a++ case 0x08: {+ uint8_t a = z->a;+ uint8_t f = get_f(z);++ z->a = z->a_;+ set_f(z, z->f_);++ z->a_ = a;+ z->f_ = f;+ } break; // ex af,af'+ case 0xD9: {+ uint8_t b = z->b, c = z->c, d = z->d, e = z->e, h = z->h, l = z->l;++ z->b = z->b_;+ z->c = z->c_;+ z->d = z->d_;+ z->e = z->e_;+ z->h = z->h_;+ z->l = z->l_;++ z->b_ = b;+ z->c_ = c;+ z->d_ = d;+ z->e_ = e;+ z->h_ = h;+ z->l_ = l;+ } break; // exx++ case 0xCB: exec_opcode_cb(z, nextb(z)); break;+ case 0xED: exec_opcode_ed(z, nextb(z)); break;+ case 0xDD: exec_opcode_ddfd(z, nextb(z), &z->ix); break;+ case 0xFD: exec_opcode_ddfd(z, nextb(z), &z->iy); break;++ }+}++// executes a DD/FD opcode (IZ = IX or IY)+void exec_opcode_ddfd(z80* const z, uint8_t opcode, uint16_t* const iz) {+ z->cyc += cyc_ddfd[opcode];+ inc_r(z);++#define IZD displace(z, *iz, nextb(z))+#define IZH (*iz >> 8)+#define IZL (*iz & 0xFF)++ switch (opcode) {+ case 0xE1: *iz = popw(z); break; // pop iz+ case 0xE5: pushw(z, *iz); break; // push iz++ case 0xE9: jump(z, *iz); break; // jp iz++ case 0x09: addiz(z, iz, get_bc(z)); break; // add iz,bc+ case 0x19: addiz(z, iz, get_de(z)); break; // add iz,de+ case 0x29: addiz(z, iz, *iz); break; // add iz,iz+ case 0x39: addiz(z, iz, z->sp); break; // add iz,sp++ case 0x84: z->a = addb(z, z->a, IZH, 0); break; // add a,izh+ case 0x85: z->a = addb(z, z->a, *iz & 0xFF, 0); break; // add a,izl+ case 0x8C: z->a = addb(z, z->a, IZH, z->cf); break; // adc a,izh+ case 0x8D: z->a = addb(z, z->a, *iz & 0xFF, z->cf); break; // adc a,izl++ case 0x86: z->a = addb(z, z->a, rb(z, IZD), 0); break; // add a,(iz+*)+ case 0x8E: z->a = addb(z, z->a, rb(z, IZD), z->cf); break; // adc a,(iz+*)+ case 0x96: z->a = subb(z, z->a, rb(z, IZD), 0); break; // sub (iz+*)+ case 0x9E: z->a = subb(z, z->a, rb(z, IZD), z->cf); break; // sbc (iz+*)++ case 0x94: z->a = subb(z, z->a, IZH, 0); break; // sub izh+ case 0x95: z->a = subb(z, z->a, *iz & 0xFF, 0); break; // sub izl+ case 0x9C: z->a = subb(z, z->a, IZH, z->cf); break; // sbc izh+ case 0x9D: z->a = subb(z, z->a, *iz & 0xFF, z->cf); break; // sbc izl++ case 0xA6: land(z, rb(z, IZD)); break; // and (iz+*)+ case 0xA4: land(z, IZH); break; // and izh+ case 0xA5: land(z, *iz & 0xFF); break; // and izl++ case 0xAE: lxor(z, rb(z, IZD)); break; // xor (iz+*)+ case 0xAC: lxor(z, IZH); break; // xor izh+ case 0xAD: lxor(z, *iz & 0xFF); break; // xor izl++ case 0xB6: lor(z, rb(z, IZD)); break; // or (iz+*)+ case 0xB4: lor(z, IZH); break; // or izh+ case 0xB5: lor(z, *iz & 0xFF); break; // or izl++ case 0xBE: cp(z, rb(z, IZD)); break; // cp (iz+*)+ case 0xBC: cp(z, IZH); break; // cp izh+ case 0xBD: cp(z, *iz & 0xFF); break; // cp izl++ case 0x23: *iz += 1; break; // inc iz+ case 0x2B: *iz -= 1; break; // dec iz++ case 0x34: {+ uint16_t addr = IZD;+ wb(z, addr, inc(z, rb(z, addr)));+ } break; // inc (iz+*)++ case 0x35: {+ uint16_t addr = IZD;+ wb(z, addr, dec(z, rb(z, addr)));+ } break; // dec (iz+*)++ case 0x24: *iz = IZL | ((inc(z, IZH)) << 8); break; // inc izh+ case 0x25: *iz = IZL | ((dec(z, IZH)) << 8); break; // dec izh+ case 0x2C: *iz = (IZH << 8) | inc(z, IZL); break; // inc izl+ case 0x2D: *iz = (IZH << 8) | dec(z, IZL); break; // dec izl++ case 0x2A: *iz = rw(z, nextw(z)); break; // ld iz,(**)+ case 0x22: ww(z, nextw(z), *iz); break; // ld (**),iz+ case 0x21: *iz = nextw(z); break; // ld iz,**++ case 0x36: {+ uint16_t addr = IZD;+ wb(z, addr, nextb(z));+ } break; // ld (iz+*),*++ case 0x70: wb(z, IZD, z->b); break; // ld (iz+*),b+ case 0x71: wb(z, IZD, z->c); break; // ld (iz+*),c+ case 0x72: wb(z, IZD, z->d); break; // ld (iz+*),d+ case 0x73: wb(z, IZD, z->e); break; // ld (iz+*),e+ case 0x74: wb(z, IZD, z->h); break; // ld (iz+*),h+ case 0x75: wb(z, IZD, z->l); break; // ld (iz+*),l+ case 0x77: wb(z, IZD, z->a); break; // ld (iz+*),a++ case 0x46: z->b = rb(z, IZD); break; // ld b,(iz+*)+ case 0x4E: z->c = rb(z, IZD); break; // ld c,(iz+*)+ case 0x56: z->d = rb(z, IZD); break; // ld d,(iz+*)+ case 0x5E: z->e = rb(z, IZD); break; // ld e,(iz+*)+ case 0x66: z->h = rb(z, IZD); break; // ld h,(iz+*)+ case 0x6E: z->l = rb(z, IZD); break; // ld l,(iz+*)+ case 0x7E: z->a = rb(z, IZD); break; // ld a,(iz+*)++ case 0x44: z->b = IZH; break; // ld b,izh+ case 0x4C: z->c = IZH; break; // ld c,izh+ case 0x54: z->d = IZH; break; // ld d,izh+ case 0x5C: z->e = IZH; break; // ld e,izh+ case 0x7C: z->a = IZH; break; // ld a,izh++ case 0x45: z->b = IZL; break; // ld b,izl+ case 0x4D: z->c = IZL; break; // ld c,izl+ case 0x55: z->d = IZL; break; // ld d,izl+ case 0x5D: z->e = IZL; break; // ld e,izl+ case 0x7D: z->a = IZL; break; // ld a,izl++ case 0x60: *iz = IZL | (z->b << 8); break; // ld izh,b+ case 0x61: *iz = IZL | (z->c << 8); break; // ld izh,c+ case 0x62: *iz = IZL | (z->d << 8); break; // ld izh,d+ case 0x63: *iz = IZL | (z->e << 8); break; // ld izh,e+ case 0x64: break; // ld izh,izh+ case 0x65: *iz = (IZL << 8) | IZL; break; // ld izh,izl+ case 0x67: *iz = IZL | (z->a << 8); break; // ld izh,a+ case 0x26: *iz = IZL | (nextb(z) << 8); break; // ld izh,*++ case 0x68: *iz = (IZH << 8) | z->b; break; // ld izl,b+ case 0x69: *iz = (IZH << 8) | z->c; break; // ld izl,c+ case 0x6A: *iz = (IZH << 8) | z->d; break; // ld izl,d+ case 0x6B: *iz = (IZH << 8) | z->e; break; // ld izl,e+ case 0x6C: *iz = (IZH << 8) | IZH; break; // ld izl,izh+ case 0x6D: break; // ld izl,izl+ case 0x6F: *iz = (IZH << 8) | z->a; break; // ld izl,a+ case 0x2E: *iz = (IZH << 8) | nextb(z); break; // ld izl,*++ case 0xF9: z->sp = *iz; break; // ld sp,iz++ case 0xE3: {+ const uint16_t val = rw(z, z->sp);+ ww(z, z->sp, *iz);+ *iz = val;+ z->mem_ptr = val;+ } break; // ex (sp),iz++ case 0xCB: {+ uint16_t addr = IZD;+ uint8_t op = nextb(z);+ exec_opcode_dcb(z, op, addr);+ } break;++ default: {+ // any other FD/DD opcode behaves as a non-prefixed opcode:+ exec_opcode(z, opcode);+ // R should not be incremented twice:+ z->r = (z->r & 0x80) | ((z->r - 1) & 0x7f);+ } break;+ }++#undef IZD+#undef IZH+#undef IZL+}++// executes a CB opcode+void exec_opcode_cb(z80* const z, uint8_t opcode) {+ z->cyc += 8;+ inc_r(z);++ // decoding instructions from http://z80.info/decoding.htm#cb+ uint8_t x_ = (opcode >> 6) & 3; // 0b11+ uint8_t y_ = (opcode >> 3) & 7; // 0b111+ uint8_t z_ = opcode & 7; // 0b111++ uint8_t hl = 0;+ uint8_t* reg = 0;+ switch (z_) {+ case 0: reg = &z->b; break;+ case 1: reg = &z->c; break;+ case 2: reg = &z->d; break;+ case 3: reg = &z->e; break;+ case 4: reg = &z->h; break;+ case 5: reg = &z->l; break;+ case 6:+ hl = rb(z, get_hl(z));+ reg = &hl;+ break;+ case 7: reg = &z->a; break;+ }++ switch (x_) {+ case 0: {+ switch (y_) {+ case 0: *reg = cb_rlc(z, *reg); break;+ case 1: *reg = cb_rrc(z, *reg); break;+ case 2: *reg = cb_rl(z, *reg); break;+ case 3: *reg = cb_rr(z, *reg); break;+ case 4: *reg = cb_sla(z, *reg); break;+ case 5: *reg = cb_sra(z, *reg); break;+ case 6: *reg = cb_sll(z, *reg); break;+ case 7: *reg = cb_srl(z, *reg); break;+ }+ } break; // rot[y] r[z]+ case 1: { // BIT y, r[z]+ cb_bit(z, *reg, y_);++ // in bit (hl), x/y flags are handled differently:+ if (z_ == 6) {+ z->yf = GET_BIT(5, z->mem_ptr >> 8);+ z->xf = GET_BIT(3, z->mem_ptr >> 8);+ z->cyc += 4;+ }+ } break;+ case 2: *reg &= ~(1 << y_); break; // RES y, r[z]+ case 3: *reg |= 1 << y_; break; // SET y, r[z]+ }++ if ((x_ == 0 || x_ == 2 || x_ == 3) && z_ == 6) {+ z->cyc += 7;+ }++ if (reg == &hl) {+ wb(z, get_hl(z), hl);+ }+}++// executes a displaced CB opcode (DDCB or FDCB)+void exec_opcode_dcb(z80* const z, uint8_t opcode, uint16_t addr) {+ uint8_t val = rb(z, addr);+ uint8_t result = 0;++ // decoding instructions from http://z80.info/decoding.htm#ddcb+ uint8_t x_ = (opcode >> 6) & 3; // 0b11+ uint8_t y_ = (opcode >> 3) & 7; // 0b111+ uint8_t z_ = opcode & 7; // 0b111++ switch (x_) {+ case 0: {+ // rot[y] (iz+d)+ switch (y_) {+ case 0: result = cb_rlc(z, val); break;+ case 1: result = cb_rrc(z, val); break;+ case 2: result = cb_rl(z, val); break;+ case 3: result = cb_rr(z, val); break;+ case 4: result = cb_sla(z, val); break;+ case 5: result = cb_sra(z, val); break;+ case 6: result = cb_sll(z, val); break;+ case 7: result = cb_srl(z, val); break;+ }+ } break;+ case 1: {+ result = cb_bit(z, val, y_);+ z->yf = GET_BIT(5, addr >> 8);+ z->xf = GET_BIT(3, addr >> 8);+ } break; // bit y,(iz+d)+ case 2: result = val & ~(1 << y_); break; // res y, (iz+d)+ case 3: result = val | (1 << y_); break; // set y, (iz+d)++ }++ // ld r[z], rot[y] (iz+d)+ // ld r[z], res y,(iz+d)+ // ld r[z], set y,(iz+d)+ if (x_ != 1 && z_ != 6) {+ switch (z_) {+ case 0: z->b = result; break;+ case 1: z->c = result; break;+ case 2: z->d = result; break;+ case 3: z->e = result; break;+ case 4: z->h = result; break;+ case 5: z->l = result; break;+ case 6: wb(z, get_hl(z), result); break;+ case 7: z->a = result; break;+ }+ }++ if (x_ == 1) {+ // bit instructions take 20 cycles, others take 23+ z->cyc += 20;+ } else {+ wb(z, addr, result);+ z->cyc += 23;+ }+}++// executes a ED opcode+void exec_opcode_ed(z80* const z, uint8_t opcode) {+ z->cyc += cyc_ed[opcode];+ inc_r(z);+ switch (opcode) {+ case 0x47: z->i = z->a; break; // ld i,a+ case 0x4F: z->r = z->a; break; // ld r,a++ case 0x57:+ z->a = z->i;+ z->sf = z->a >> 7;+ z->zf = z->a == 0;+ z->hf = 0;+ z->nf = 0;+ z->pf = z->iff2;+ break; // ld a,i++ case 0x5F:+ z->a = z->r;+ z->sf = z->a >> 7;+ z->zf = z->a == 0;+ z->hf = 0;+ z->nf = 0;+ z->pf = z->iff2;+ break; // ld a,r++ case 0x45:+ case 0x55:+ case 0x5D:+ case 0x65:+ case 0x6D:+ case 0x75:+ case 0x7D:+ z->iff1 = z->iff2;+ ret(z);+ break; // retn+ case 0x4D: ret(z); break; // reti++ case 0xA0: ldi(z); break; // ldi+ case 0xB0: {+ ldi(z);++ if (get_bc(z) != 0) {+ z->pc -= 2;+ z->cyc += 5;+ z->mem_ptr = z->pc + 1;+ }+ } break; // ldir++ case 0xA8: ldd(z); break; // ldd+ case 0xB8: {+ ldd(z);++ if (get_bc(z) != 0) {+ z->pc -= 2;+ z->cyc += 5;+ z->mem_ptr = z->pc + 1;+ }+ } break; // lddr++ case 0xA1: cpi(z); break; // cpi+ case 0xA9: cpd(z); break; // cpd+ case 0xB1: {+ cpi(z);+ if (get_bc(z) != 0 && !z->zf) {+ z->pc -= 2;+ z->cyc += 5;+ z->mem_ptr = z->pc + 1;+ } else {+ z->mem_ptr += 1;+ }+ } break; // cpir+ case 0xB9: {+ cpd(z);+ if (get_bc(z) != 0 && !z->zf) {+ z->pc -= 2;+ z->cyc += 5;+ } else {+ z->mem_ptr += 1;+ }+ } break; // cpdr++ case 0x40: in_r_c(z, &z->b); break; // in b, (c)+ case 0x48: in_r_c(z, &z->c); break; // in c, (c)+ case 0x50: in_r_c(z, &z->d); break; // in d, (c)+ case 0x58: in_r_c(z, &z->e); break; // in e, (c)+ case 0x60: in_r_c(z, &z->h); break; // in h, (c)+ case 0x68: in_r_c(z, &z->l); break; // in l, (c)+ case 0x70: {+ uint8_t val;+ in_r_c(z, &val);+ } break; // in (c)+ case 0x78:+ in_r_c(z, &z->a);+ z->mem_ptr = get_bc(z) + 1;+ break; // in a, (c)++ case 0xA2: ini(z); break; // ini+ case 0xB2:+ ini(z);+ if (z->b > 0) {+ z->pc -= 2;+ z->cyc += 5;+ }+ break; // inir+ case 0xAA: ind(z); break; // ind+ case 0xBA:+ ind(z);+ if (z->b > 0) {+ z->pc -= 2;+ z->cyc += 5;+ }+ break; // indr++ case 0x41: z80_bus_out(z->c, z->b); break; // out (c), b+ case 0x49: z80_bus_out(z->c, z->c); break; // out (c), c+ case 0x51: z80_bus_out(z->c, z->d); break; // out (c), d+ case 0x59: z80_bus_out(z->c, z->e); break; // out (c), e+ case 0x61: z80_bus_out(z->c, z->h); break; // out (c), h+ case 0x69: z80_bus_out(z->c, z->l); break; // out (c), l+ case 0x71: z80_bus_out(z->c, 0); break; // out (c), 0+ case 0x79:+ z80_bus_out(z->c, z->a);+ z->mem_ptr = get_bc(z) + 1;+ break; // out (c), a++ case 0xA3: outi(z); break; // outi+ case 0xB3: {+ outi(z);+ if (z->b > 0) {+ z->pc -= 2;+ z->cyc += 5;+ }+ } break; // otir+ case 0xAB: outd(z); break; // outd+ case 0xBB: {+ outd(z);+ if (z->b > 0) {+ z->pc -= 2;+ z->cyc += 5;+ }+ } break; // otdr++ case 0x42: sbchl(z, get_bc(z)); break; // sbc hl,bc+ case 0x52: sbchl(z, get_de(z)); break; // sbc hl,de+ case 0x62: sbchl(z, get_hl(z)); break; // sbc hl,hl+ case 0x72: sbchl(z, z->sp); break; // sbc hl,sp++ case 0x4A: adchl(z, get_bc(z)); break; // adc hl,bc+ case 0x5A: adchl(z, get_de(z)); break; // adc hl,de+ case 0x6A: adchl(z, get_hl(z)); break; // adc hl,hl+ case 0x7A: adchl(z, z->sp); break; // adc hl,sp++ case 0x43: {+ const uint16_t addr = nextw(z);+ ww(z, addr, get_bc(z));+ z->mem_ptr = addr + 1;+ } break; // ld (**), bc++ case 0x53: {+ const uint16_t addr = nextw(z);+ ww(z, addr, get_de(z));+ z->mem_ptr = addr + 1;+ } break; // ld (**), de++ case 0x63: {+ const uint16_t addr = nextw(z);+ ww(z, addr, get_hl(z));+ z->mem_ptr = addr + 1;+ } break; // ld (**), hl++ case 0x73: {+ const uint16_t addr = nextw(z);+ ww(z, addr, z->sp);+ z->mem_ptr = addr + 1;+ } break; // ld (**),sp++ case 0x4B: {+ const uint16_t addr = nextw(z);+ set_bc(z, rw(z, addr));+ z->mem_ptr = addr + 1;+ } break; // ld bc, (**)++ case 0x5B: {+ const uint16_t addr = nextw(z);+ set_de(z, rw(z, addr));+ z->mem_ptr = addr + 1;+ } break; // ld de, (**)++ case 0x6B: {+ const uint16_t addr = nextw(z);+ set_hl(z, rw(z, addr));+ z->mem_ptr = addr + 1;+ } break; // ld hl, (**)++ case 0x7B: {+ const uint16_t addr = nextw(z);+ z->sp = rw(z, addr);+ z->mem_ptr = addr + 1;+ } break; // ld sp,(**)++ case 0x44:+ case 0x54:+ case 0x64:+ case 0x74:+ case 0x4C:+ case 0x5C:+ case 0x6C:+ case 0x7C: z->a = subb(z, 0, z->a, 0); break; // neg++ case 0x46:+ case 0x66: z->interrupt_mode = 0; break; // im 0+ case 0x56:+ case 0x76: z->interrupt_mode = 1; break; // im 1+ case 0x5E:+ case 0x7E: z->interrupt_mode = 2; break; // im 2++ case 0x67: {+ uint8_t a = z->a;+ uint8_t val = rb(z, get_hl(z));+ z->a = (a & 0xF0) | (val & 0xF);+ wb(z, get_hl(z), (val >> 4) | (a << 4));++ z->nf = 0;+ z->hf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ z->zf = z->a == 0;+ z->sf = z->a >> 7;+ z->pf = parity(z->a);+ z->mem_ptr = get_hl(z) + 1;+ } break; // rrd++ case 0x6F: {+ uint8_t a = z->a;+ uint8_t val = rb(z, get_hl(z));+ z->a = (a & 0xF0) | (val >> 4);+ wb(z, get_hl(z), (val << 4) | (a & 0xF));++ z->nf = 0;+ z->hf = 0;+ z->xf = GET_BIT(3, z->a);+ z->yf = GET_BIT(5, z->a);+ z->zf = z->a == 0;+ z->sf = z->a >> 7;+ z->pf = parity(z->a);+ z->mem_ptr = get_hl(z) + 1;+ } break; // rld++ default: break; // (the other ED opcodes do nothing)+ }+}++#undef GET_BITdiff --git a/games/retrogo/src/sms/z80.h b/games/retrogo/src/sms/z80.hnew file mode 100644index 00000000..1803ced6--- /dev/null+++ b/games/retrogo/src/sms/z80.h@@ -0,0 +1,48 @@+/* The Z80 of the Master System and the Game Gear: superzazu's z80 (MIT License, see z80.c and+ * LICENSE.z80), changed to run inside the machine (sms.c): memory read through 1 KB pages, the+ * interrupt line held by the video chip, and whole stretches of clocks at a time. */+#ifndef Z80_Z80_H_+#define Z80_Z80_H_++#include <stdbool.h>+#include <stdint.h>++/* (only bytes: a save state is this as it is) */+typedef struct z80 {+ uint32_t cyc; // cycle count (t-states)++ uint16_t pc, sp, ix, iy; // special purpose registers+ uint16_t mem_ptr; // "wz" register+ uint8_t a, b, c, d, e, h, l; // main registers+ uint8_t a_, b_, c_, d_, e_, h_, l_, f_; // alternate registers+ uint8_t i, r; // interrupt vector, memory refresh++ // flags: sign, zero, yf, half-carry, xf, parity/overflow, negative, carry+ // (a byte each, 0 or 1)+ uint8_t sf, zf, yf, hf, xf, pf, nf, cf;++ uint8_t ei_shadow; // the instruction after EI: no interrupt before it+ uint8_t interrupt_mode;+ uint8_t iff1, iff2;+ uint8_t halted;+ uint8_t irq_line; // the INT line, held low by the machine while it wants an interrupt+ uint8_t nmi_pending;+ uint8_t pad_[3];+} z80;++/* The machine around the Z80 (sms.c, or a test's): 64 pages of 1 KB to read from, and the+ rest through functions. */+extern const uint8_t *z80_rmap[64];+void z80_bus_write(uint16_t addr, uint8_t val);+uint8_t z80_bus_in(uint8_t port);+void z80_bus_out(uint8_t port, uint8_t val);++void z80_init(z80* const z);+/* runs instructions until the cycle count reaches `until` (a little past it, the last one+ finished) */+void z80_run(z80* const z, uint32_t until);+void z80_gen_nmi(z80* const z);+/* a state read back: whatever it held, values the Z80 can have */+void z80_fix(z80* const z);++#endif // Z80_Z80_H_diff --git a/games/retrogo/tests/host_core.c b/games/retrogo/tests/host_core.cindex 1f24a224..494daba2 100644--- a/games/retrogo/tests/host_core.c+++ b/games/retrogo/tests/host_core.c@@ -1,7 +1,7 @@/* Retro-Go's emulators on a computer: runs a ROM for some frames, with random keys if asked,* and writes the last frame as a PPM picture.- * host_core ROM FRAMES OUT.ppm [SEED] (SEED: random pad presses; 0 for none)- * The system comes from the file's extension (.gb .gbc .nes). */+ * host_core ROM FRAMES OUT.ppm [SEED] [SCRIPT] (SEED: random pad presses; 0 for none)+ * The system comes from the file's extension (.gb .gbc .nes .sms .gg). */#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -9,12 +9,15 @@#include "../src/rg.h"#include "../src/gb/gb.h"#include "../src/nes/nes_core.h"+#include "../src/sms/sms.h"static uint8_t heap[RG_HEAP_SIZE] __attribute__((aligned(8)));static uint32_t used;bool rg_drawing = true;static uint16_t frame[256 * 240];-static int width = 160, lines_seen;+static int lines_seen;+/* the three emulators behind the same few calls */+static enum { GB, NES, SMS } kind;void *rg_alloc(uint32_t size) {size = (size + 7) & ~7u;@@ -31,39 +34,60 @@ void rg_line(int y, const uint16_t *px) {fprintf(stderr, "line %d out of the picture\n", y);abort();}- memcpy(frame + y * 256, px, (size_t)width * 2);+ memcpy(frame + y * 256, px, (size_t)(kind == GB ? 160 : 256) * 2);lines_seen++;}-/* the ROM, read only as the calculator's flash is: a write into it stops the test */+/* the ROM, read only as the calculator's flash is: a write into it stops the test (and a read+ past its end too: the page after it isn't there) */static uint8_t *load(const char *path, uint32_t *size) {FILE *f = fopen(path, "rb");if (!f) return NULL;fseek(f, 0, SEEK_END);long n = ftell(f);fseek(f, 0, SEEK_SET);- size_t pages = ((size_t)n + 4095) / 4096 * 4096;+ size_t pages = ((size_t)n + 4095) / 4096 * 4096 + 4096;uint8_t *d = mmap(NULL, pages, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);if (d == MAP_FAILED || fread(d, 1, (size_t)n, f) != (size_t)n) return NULL;fclose(f);- mprotect(d, pages, PROT_READ);+ mprotect(d, pages - 4096, PROT_READ);+ mprotect(d + pages - 4096, 4096, PROT_NONE);*size = (uint32_t)n;return d;}+static uint32_t crc32(const uint8_t *p, uint32_t n) {+ uint32_t c = 0xFFFFFFFF;+ for (uint32_t i = 0; i < n; i++) {+ c ^= p[i];+ for (int k = 0; k < 8; k++) c = c >> 1 ^ (0xEDB88320 & -(c & 1));+ }+ return ~c;+}++static void set_pad(int p) { kind == NES ? nes_set_pad(p) : kind == SMS ? sms_set_pad(p) : gb_set_pad(p); }+static void run_frame(void) { kind == NES ? nes_run_frame(true) : kind == SMS ? sms_run_frame(true) : gb_run_frame(true); }+static int chunks(rg_chunk_t *c) { return kind == NES ? nes_state_chunks(c) : kind == SMS ? sms_state_chunks(c) : gb_state_chunks(c); }+static void loaded(void) { kind == NES ? nes_state_loaded() : kind == SMS ? sms_state_loaded() : gb_state_loaded(); }+static void redraw(void) { kind == NES ? nes_redraw() : kind == SMS ? sms_redraw() : gb_redraw(); }+static void view(int *x, int *y, int *w, int *h) {+ if (kind == SMS) sms_view(x, y, w, h);+ else *x = 0, *y = 0, *w = kind == NES ? 256 : 160, *h = kind == NES ? 240 : 144;+}+int main(int argc, char **argv) {- if (argc < 4) return fprintf(stderr, "usage: host_core ROM FRAMES OUT.ppm [SEED]\n"), 2;+ if (argc < 4) return fprintf(stderr, "usage: host_core ROM FRAMES OUT.ppm [SEED] [SCRIPT]\n"), 2;uint32_t size;uint8_t *rom = load(argv[1], &size);if (!rom) return fprintf(stderr, "can't read %s\n", argv[1]), 1;int frames = atoi(argv[2]);unsigned seed = argc > 4 ? (unsigned)atoi(argv[4]) : 0;const char *ext = strrchr(argv[1], '.');- bool nes = ext && !strcmp(ext, ".nes");- int r = nes ? nes_load(rom, size) : gb_load(rom, size);+ kind = ext && !strcmp(ext, ".nes") ? NES : ext && (!strcmp(ext, ".sms") || !strcmp(ext, ".gg")) ? SMS : GB;+ int r = kind == NES ? nes_load(rom, size)+ : kind == SMS ? sms_load(rom, size, crc32(rom, size), !strcmp(ext, ".gg"))+ : gb_load(rom, size);if (r != RG_OK) return fprintf(stderr, "load failed: %d\n", r), 1;- int h = nes ? 240 : 144;- width = nes ? 256 : 160;int pad = 0;const char *script = argc > 5 ? argv[5] : ""; /* "FRAME=PAD,FRAME=PAD...": the pad from then on */for (int i = 0; i < frames; i++) {@@ -78,65 +102,61 @@ int main(int argc, char **argv) {const char *comma = strchr(eq, ',');script = comma ? comma + 1 : "";}- if (nes) nes_set_pad(pad), nes_run_frame(true);- else gb_set_pad(pad), gb_run_frame(true);+ set_pad(pad), run_frame();}+ int vx, vy, vw, vh;+ view(&vx, &vy, &vw, &vh);/* STATE=1: a save state taken now, 120 more frames, the state put back, the same 120 frames:the same picture at the end (the state holds the whole machine); then states of randombytes, which must not crash it. REDRAW=1: the last frame drawn again is the same picture. */if (getenv("STATE")) {rg_chunk_t parts[RG_MAX_CHUNKS];- int n = nes ? nes_state_chunks(parts) : gb_state_chunks(parts);+ int n = chunks(parts);static uint8_t copy[RG_HEAP_SIZE + 65536];uint32_t at = 0;for (int i = 0; i < n; i++) memcpy(copy + at, parts[i].at, parts[i].size), at += parts[i].size;static uint16_t first[256 * 240];for (int pass = 0; pass < 2; pass++) {if (pass) {- n = nes ? nes_state_chunks(parts) : gb_state_chunks(parts);+ n = chunks(parts);at = 0;for (int i = 0; i < n; i++) memcpy(parts[i].at, copy + at, parts[i].size), at += parts[i].size;- if (nes) nes_state_loaded();- else gb_state_loaded();+ loaded();}for (int i = 0; i < 120; i++) {int p = (i / 10) % 3 ? 0 : RG_PAD_RIGHT | (i & 16 ? RG_PAD_A : 0);- if (nes) nes_set_pad(p), nes_run_frame(true);- else gb_set_pad(p), gb_run_frame(true);+ set_pad(p), run_frame();}if (!pass) memcpy(first, frame, sizeof first);}printf("state %s\n", memcmp(first, frame, sizeof first) ? "differs" : "same");for (int k = 0; k < 30; k++) {- n = nes ? nes_state_chunks(parts) : gb_state_chunks(parts);+ n = chunks(parts);for (int i = 0; i < n; i++)for (uint32_t j = 0; j < parts[i].size; j++)if (k < 10 || (j * 7 + (unsigned)k) % 13 == 0) {seed = seed * 1103515245u + 12345u + (unsigned)k;((uint8_t *)parts[i].at)[j] = (uint8_t)(seed >> 16);}- if (nes) nes_state_loaded();- else gb_state_loaded();- for (int i = 0; i < 30; i++) {- if (nes) nes_set_pad(i & 0xFF), nes_run_frame(true);- else gb_set_pad(i & 0xFF), gb_run_frame(true);- }+ loaded();+ for (int i = 0; i < 30; i++) set_pad(i & 0xFF), run_frame();}printf("random states: no crash\n");+ view(&vx, &vy, &vw, &vh);}if (getenv("REDRAW")) {static uint16_t last[256 * 240];memcpy(last, frame, sizeof last);- if (nes) nes_redraw();- else gb_redraw();+ redraw();int differ = 0;- for (int i = 0; i < 256 * h; i++) differ += last[i] != frame[i];+ for (int y = vy; y < vy + vh; y++)+ for (int x = vx; x < vx + vw; x++) differ += last[y * 256 + x] != frame[y * 256 + x];printf("redraw: %d pixels differ\n", differ);}FILE *o = fopen(argv[3], "wb");- fprintf(o, "P6\n%d %d\n255\n", width, h);- for (int y = 0; y < h; y++)- for (int x = 0; x < width; x++) {+ fprintf(o, "P6\n%d %d\n255\n", vw, vh);+ for (int y = vy; y < vy + vh; y++)+ for (int x = vx; x < vx + vw; x++) {uint16_t c = frame[y * 256 + x];fputc((c >> 11) << 3 | (c >> 13), o);fputc(((c >> 5) & 63) << 2 | ((c >> 9) & 3), o);diff --git a/games/retrogo/tests/host_z80.c b/games/retrogo/tests/host_z80.cnew file mode 100644index 00000000..9393caae--- /dev/null+++ b/games/retrogo/tests/host_z80.c@@ -0,0 +1,59 @@+/* The Master System's Z80 (src/sms/z80.c) on a computer, running the CP/M Z80 instruction+ * exercisers as superzazu's z80 tests do: prelim.com, zexdoc.cim, zexall.cim (Frank Cringle's,+ * freely distributable; not in NumPlay). It prints what they print, then the clocks they took,+ * which must be the original z80's to the clock.+ * host_z80 FILE EXPECTED_CYCLES */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "../src/sms/z80.h"++static uint8_t memory[0x10000];+const uint8_t *z80_rmap[64];+static z80 cpu;+static int finished;+static uint32_t end_cyc;++void z80_bus_write(uint16_t addr, uint8_t val) { memory[addr] = val; }++/* "in a,(0)" at 0x0005: CP/M's BDOS, C = 2 a letter in E, 9 a text at DE up to '$' */+uint8_t z80_bus_in(uint8_t port) {+ (void)port;+ if (cpu.c == 2) putchar(cpu.e);+ else if (cpu.c == 9)+ for (uint16_t a = (uint16_t)(cpu.d << 8 | cpu.e); memory[a] != '$'; a++) putchar(memory[a]);+ fflush(stdout);+ return 0xFF;+}++/* "out (0),a" at 0x0000: the end (the clocks as they are with it; then halted, so the run stops) */+void z80_bus_out(uint8_t port, uint8_t val) {+ (void)port, (void)val;+ finished = 1;+ end_cyc = cpu.cyc;+ cpu.halted = 1;+}++int main(int argc, char **argv) {+ if (argc < 3) return fprintf(stderr, "usage: host_z80 FILE EXPECTED_CYCLES\n"), 2;+ FILE *f = fopen(argv[1], "rb");+ if (!f) return fprintf(stderr, "can't read %s\n", argv[1]), 1;+ size_t n = fread(memory + 0x100, 1, sizeof memory - 0x100, f);+ fclose(f);+ if (!n) return 1;+ for (int i = 0; i < 64; i++) z80_rmap[i] = memory + i * 0x400;+ memory[0x0000] = 0xD3, memory[0x0001] = 0x00; /* out (0),a */+ memory[0x0005] = 0xDB, memory[0x0006] = 0x00, memory[0x0007] = 0xC9; /* in a,(0); ret */+ z80_init(&cpu);+ cpu.pc = 0x100;+ /* (superzazu's tests start from these, not from a reset's) */+ cpu.sp = 0xFFFF, cpu.ix = cpu.iy = 0, cpu.a = 0xFF;+ unsigned long long total = 0, expected = strtoull(argv[2], NULL, 10);+ while (!finished) {+ uint32_t before = cpu.cyc;+ z80_run(&cpu, before + 1000000);+ total += (uint32_t)((finished ? end_cyc : cpu.cyc) - before);+ }+ printf("\n%llu cycles (expected %llu)\n", total, expected);+ return total == expected ? 0 : 1;+}diff --git a/games/retrogo/tests/test_app.py b/games/retrogo/tests/test_app.pyindex ca6a9f5b..3a0ae7e7 100644--- a/games/retrogo/tests/test_app.py+++ b/games/retrogo/tests/test_app.py@@ -1,12 +1,12 @@#!/usr/bin/env python3-"""Retro-Go in tools/emu.py, with two small games this test makes: a Game Boy cartridge with battery-RAM and an NES one with battery RAM, each counting its frames in that RAM. For each: a new game,+"""Retro-Go in tools/emu.py, with three small games this test makes: a Game Boy cartridge with battery+RAM, an NES one and a Master System one, each counting its frames in that RAM. For each: a new game,Home (the battery save and a state are written), then Resume from the state and On/Off: the countgoes on from where it was. All along: what tests/test_games.py checks (Home and On/Off quit, theRAM handed back clean, no write to flash, so nothing written into a cartridge read in place, nounaligned multi-word read of the file system, the firmware's RAM untouched, the stack).-usage: test_app.py [--keep DIR] (builds output/test/retrogo-full.nwa with ROMS set to the two games)"""+usage: test_app.py [--keep DIR] (builds output/test/retrogo-full.nwa with ROMS set to the three games)"""import argparseimport osimport struct@@ -51,6 +51,22 @@ def nes_rom():return b"NES\x1a" + bytes([1, 1, 0x02, 0]) + bytes(8) + bytes(prg) + bytes(0x2000)+def sms_rom():+ """Sega's mapper with its cartridge RAM on: a 16-bit count at $8000, one more each frame (the+ line counter going past $C0)."""+ rom = bytearray(0x8000)+ code = [0xF3, 0x31, 0xF0, 0xDF, # di; ld sp,$DFF0+ 0x3E, 0x08, 0x32, 0xFC, 0xFF, # ld a,$08; ld ($FFFC),a: the RAM at $8000+ 0x21, 0x00, 0x80, # loop: ld hl,$8000+ 0x34, 0x20, 0x02, 0x23, 0x34, # inc (hl); jr nz,+2; inc hl; inc (hl)+ 0xDB, 0x7E, 0xFE, 0xC0, 0x20, 0xFA, # wait for line $C0+ 0xDB, 0x7E, 0xFE, 0xC1, 0x20, 0xFA, # then $C1+ 0x18, 0xEA] # jr loop+ rom[:len(code)] = bytes(code)+ rom[0x7FF0:0x7FF8] = b"TMR SEGA"+ return bytes(rom)++def unpack(data, size):"""games/retrogo/src/pack.c's format"""out, i = bytearray(), 0@@ -124,9 +140,10 @@ def main():a = ap.parse_args()out = os.path.join(game, "output", "test")os.makedirs(out, exist_ok=True)- roms = [os.path.join(out, "Counter.gb"), os.path.join(out, "Counter.nes")]+ roms = [os.path.join(out, "Counter.gb"), os.path.join(out, "Counter.nes"), os.path.join(out, "Counter.sms")]open(roms[0], "wb").write(gb_rom())open(roms[1], "wb").write(nes_rom())+ open(roms[2], "wb").write(sms_rom())nwa = os.path.join(out, "retrogo-full.nwa")if os.path.exists(os.path.join(game, "output", "retrogo-full.nwa")):os.remove(os.path.join(game, "output", "retrogo-full.nwa"))@@ -139,19 +156,21 @@ def main():if os.path.exists(storage):os.remove(storage)stack = 0- for sys_tab, label in ((1, "Game Boy"), (0, "NES")): # (the tabs: NES, then Game Boy)- right = "300-400:right," if sys_tab else ""- back = "300-400:back,600-700:left," if label == "NES" else "" # (from the Game Boy list to the NES tab)+ # (the tabs: NES, Game Boy, Master System; the launcher starts on the NES tab, then where it was left)+ games = (("Game Boy", 1, "300-400:right,"), # NES tab -> Game Boy+ ("NES", 3, "300-400:back,600-700:left,"), # Game Boy list -> NES tab+ ("Master System", 4, "300-400:back,600-700:right,800-850:right,")) # NES list -> Master System+ for k, (label, system, to_tab) in enumerate(games):# a new game (the controls the first time), then Home- first = f"{back}{right}900-1000:ok,1500-1600:ok,2100-2200:ok" + (",2700-2800:ok" if sys_tab else "")+ first = f"{to_tab}900-1000:ok,1500-1600:ok,2100-2200:ok" + (",2700-2800:ok" if not k else "")recs, s = session(nwa, storage, first, 6000, "home", problems, f"{label}, new game")stack = max(stack, s)srm = [n for n in recs if n.startswith("rg_") and n.endswith(".srm")]st = [n for n in recs if n.startswith("rg_") and n.endswith(".st0")]- if len(srm) != 2 - sys_tab or len(st) != 2 - sys_tab:+ if len(srm) != k + 1 or len(st) != k + 1:problems.append(f"{label}: saves after Home: {sorted(recs)}")continue- name = [n for n in srm if recs[n][5] == (1 if sys_tab else 3)][0] # (its system byte)+ name = [n for n in srm if recs[n][5] == system][0] # (its system byte)count1 = battery(recs, name)# Resume (the file menu's first choice), the slot last used, then On/Offrecs, s = session(nwa, storage, "900-1000:ok,1500-1600:ok,2100-2200:ok", 5000, "onoff", problems,diff --git a/games/retrogo/tests/test_cores.py b/games/retrogo/tests/test_cores.pyindex 1c1f033b..37fc6dfd 100644--- a/games/retrogo/tests/test_cores.py+++ b/games/retrogo/tests/test_cores.py@@ -3,11 +3,13 @@behaviour sanitizers, the ROM read only like the calculator's flash):- test ROMs give the pictures they should (Blargg's cpu_instrs and instr_timing, dmg-acid2 and- cgb-acid2, nestest), when they are in the test ROM folder;+ cgb-acid2, nestest, zexdoc for the Master System), when they are in the test ROM folder, and the+ Master System's Z80 runs the CP/M instruction exercisers (prelim; zexdoc and zexall with ZEX=1)+ to the clock;- every ROM there plays a few hundred runs of random keys without a crash;- broken ROMs (random bytes, headers made up, files cut short) never crash either.-usage: test_cores.py HOST_CORE [TEST_ROM_FOLDER]+usage: test_cores.py HOST_CORE [TEST_ROM_FOLDER] [HOST_Z80]Only freely distributable test ROMs and homebrew go in the folder (see games/retrogo/README.md)."""import hashlibimport os@@ -19,6 +21,7 @@ import tempfilecore = sys.argv[1]folder = sys.argv[2] if len(sys.argv) > 2 else ""+z80 = sys.argv[3] if len(sys.argv) > 3 else ""tmp = tempfile.mkdtemp()failures = []@@ -29,7 +32,11 @@ EXPECTED = {"dmg-acid2.gb": (120, "", "1b496ea223ab"),"cgb-acid2.gbc": (120, "", "3e99d1d0cb67"),"nestests/nes-test-roms-master/other/nestest.nes": (400, "30=8,35=0", "9c699fb5f8ff"),+ "sega/zexall/x/zexdoc.sms": (3000, "", "e20e5a6fb45d"),}+# the CP/M exercisers and the clocks superzazu's z80 takes for them+ZEX = [("z80/prelim.com", 8721), ("z80/zexdoc.cim", 46734978649), ("z80/zexall.cim", 46734978649)]+SYSTEMS = (".gb", ".gbc", ".nes", ".sms", ".gg")def run(rom, frames, seed=0, script=""):@@ -67,12 +74,28 @@ if folder and os.path.isdir(folder):print("ok ", rel)for root, _, files in os.walk(folder):for f in sorted(files):- if f.lower().endswith((".gb", ".gbc", ".nes")):+ if f.lower().endswith(SYSTEMS):roms.append(os.path.join(root, f))+# ---- the Z80 instruction exercisers+if z80 and folder:+ for rel, clocks in ZEX[:1] + (ZEX[1:] if os.environ.get("ZEX") else []):+ path = os.path.join(folder, rel)+ if not os.path.exists(path):+ print("skip", rel)+ continue+ r = subprocess.run([z80, path, str(clocks)], capture_output=True, text=True, timeout=1200)+ if r.returncode != 0 or "ERROR" in r.stdout:+ failures.append(f"{rel}: {r.stdout.strip()[-600:]}")+ print("FAIL", rel, r.stdout.strip()[-600:])+ else:+ print("ok ", rel, r.stdout.strip().splitlines()[-1])+# ---- save states: the machine goes on the same after its state is put back, and random states# don't crash it-for rel in ("libbet.gb", "ucity_compat.gbc", "cgb-acid2.gbc", "thwaite.nes", "croom.nes", "240pee.nes"):+for rel in ("libbet.gb", "ucity_compat.gbc", "cgb-acid2.gbc", "thwaite.nes", "croom.nes", "240pee.nes",+ "sega/raposa/x/raposadosol_v20.sms", "sega/waternet/sms/waternet.sms", "sega/waternet/gg/waternet.gg",+ "sega/tunnel/tunnel.gg"):path = os.path.join(folder, rel) if folder else ""if not os.path.exists(path):continue@@ -102,8 +125,8 @@ def write(name, data):broken = []-for k in range(120):- kind = k % 6+for k in range(160):+ kind = k % 8if kind == 0: # random bytes, a GB header's sizedata = bytes(rng.getrandbits(8) for _ in range(rng.choice([0x8000, 0x10000, 0x20000])))broken.append(write(f"rand{k}.gb", data))@@ -124,8 +147,15 @@ for k in range(120):head = b"NES\x1a" + bytes([prg, chr_, rng.getrandbits(8) & 0xF4, 0]) + bytes(8)body = bytes(rng.getrandbits(8) for _ in range(rng.randint(0, prg * 0x4000 + chr_ * 0x2000)))broken.append(write(f"cut{k}.nes", head + body))- else: # random bytes as an NES file+ elif kind == 5: # random bytes as an NES filebroken.append(write(f"rand{k}.nes", bytes(rng.getrandbits(8) for _ in range(rng.randint(0, 0x30000)))))+ elif kind == 6: # random bytes as a Master System or Game Gear game, any size, a Codemasters header maybe+ data = bytearray(rng.getrandbits(8) for _ in range(rng.choice([0x400, 0x2000, 0x8000, 0xC000, 0x20000, 0x40200])))+ if len(data) > 0x8000 and k % 2:+ data[0x7FE6:0x7FEA] = bytes([0x34, 0x12, 0xCC, 0xED])+ broken.append(write(f"rand{k}." + rng.choice(["sms", "gg"]), bytes(data)))+ else: # a Master System file cut short+ broken.append(write(f"short{k}.sms", bytes(rng.getrandbits(8) for _ in range(rng.randint(0, 0x5000)))))for path in broken:r, _ = run(path, rng.randint(20, 120), rng.randint(1, 1 << 30))check(os.path.basename(path), r, allow_load_error=True)diff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txtindex 45284d96..d48e04fb 100644--- a/launcher/lang/fr.txt+++ b/launcher/lang/fr.txt@@ -98,7 +98,7 @@ Clear the field, flag the mines Déblaie le terrain, pose les drapeauxBlock Breaker Casse-briquesBreak every brick Casse toutes les briquesBackgrounds, clocks, timers Fonds, horloges, minuteurs-Game Boy and NES games Jeux Game Boy et NES+Game Boy, NES and Sega games Jeux Game Boy, NES et Sega# (names that stay as they are)NumDash NumDashNumBlocks NumBlocksdiff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txtindex 62479fc5..c1067280 100644--- a/launcher/lang/zh.txt+++ b/launcher/lang/zh.txt@@ -97,7 +97,7 @@ Clear the field, flag the mines 清理雷区,标出地雷Block Breaker 打砖块Break every brick 打碎每一块砖Backgrounds, clocks, timers 背景、时钟、计时器-Game Boy and NES games Game Boy 和 NES 游戏+Game Boy, NES and Sega games Game Boy、NES 和 Sega 游戏# (names that stay as they are)NumDash NumDashNumBlocks NumBlocks