Skip to content

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.

Five Nights at Freddy's 3

Mason363d0c9779b509d
diff --git a/Makefile b/Makefile
index 432d36db..58c629e0 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,7 @@ PY ?= python3
CARGO ?= cargo
B = build/data
# Conventional games honor a configurable output directory; special layouts are kept local.
-GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil mahjong meowdoku minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock turborush twoplayer undertale uno uttt
+GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnaf3 fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil mahjong meowdoku minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock turborush twoplayer undertale uno uttt
GAMES_OUT = dinorun
GAME_REDIRECT_ARG = $(if $(filter $(1),$(GAMES_OUT)),OUT=../../$(B)/games/$(1),BUILD_DIR=../../$(B)/games/$(1))
# the RAM the oldest calculator software that runs apps gives them (23.2: 148928 bytes; 25.2 gives 153676).
@@ -29,7 +29,7 @@ RAM_LIMIT = 148928
# custom builds of Epsilon 25.2's source give apps less: 133652 bytes; every game fits there too, in NumPlay and on
# its own (their big buffers are on the stack, 32 KB apart from that RAM, or in the RAM the software has left)
CUSTOM_RAM = 133652
-BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 Famidash UniversalPaperclips-French
+BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 FiveNightsAtFreddys3 Famidash UniversalPaperclips-French
# the calculator's space for installed apps: from the end of its software (64 KiB aligned) to 64 KiB before the
# end of its 4 MiB slot of flash, 0x903F0000. The software's size sets the start: 0x90200000 is the latest a
# NumPlay counts on (1.94 MB, APP_SPACE); Epsilon 26.4 on an N0120 ends at 0x90180000 (2.44 MB, the
@@ -334,6 +334,7 @@ APP_rider = $(B)/games/rider/rider.nwa:Rider.nwa
APP_snowrider = $(B)/games/snowrider/snowrider.nwa:SnowRider3D.nwa
APP_templerun = $(B)/games/templerun/templerun.nwa:TempleRun.nwa
APP_fnaf2 = $(B)/games/fnaf2/fnaf2.nwa:FiveNightsAtFreddys2.nwa
+APP_fnaf3 = $(B)/games/fnaf3/fnaf3.nwa:FiveNightsAtFreddys3.nwa
APP_famidash = $(B)/games/famidash/famidash.nwa:Famidash.nwa
# the big games' modules are made from these (the kit)
$(foreach g,$(XL_GAMES),$(eval MOD_$(g) = $$(word 1,$$(subst :, ,$$(APP_$(g))))))
@@ -380,6 +381,7 @@ apps: | $(B)
$(MAKE) -C games/snowrider build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/snowrider
$(MAKE) -C games/templerun build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/templerun
$(MAKE) -C games/fnaf2 build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnaf2
+ $(MAKE) -C games/fnaf3 build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnaf3
$(MAKE) -C games/famidash build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/famidash
cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
cp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))
@@ -425,6 +427,7 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_snowrider))) $(B)/apps/$(word 2,$(subst :, ,$(APP_snowrider)))
cp $(word 1,$(subst :, ,$(APP_templerun))) $(B)/apps/$(word 2,$(subst :, ,$(APP_templerun)))
cp $(word 1,$(subst :, ,$(APP_fnaf2))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnaf2)))
+ cp $(word 1,$(subst :, ,$(APP_fnaf3))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnaf3)))
cp $(word 1,$(subst :, ,$(APP_famidash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_famidash)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
@@ -510,6 +513,7 @@ clean:
-$(MAKE) -C games/snowrider clean
-$(MAKE) -C games/templerun clean
-$(MAKE) -C games/fnaf2 clean
+ -$(MAKE) -C games/fnaf3 clean
-$(MAKE) -C games/famidash clean
-cd games/tetris/tetris && $(CARGO) clean
-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)
diff --git a/README.md b/README.md
index dc6c5cb5..9a916e67 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
<p align="center">
<b>29 free games for your NumWorks calculator, in one app.</b><br>
- Plus 34 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.
+ Plus 35 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.
</p>
<p align="center">
@@ -153,10 +153,11 @@ These are too big to fit next to NumPlay, so each one is its own app. Install it
</tr>
<tr>
<td align="center"><a href="games/famidash/README.md"><img src="docs/media/thumb_famidash.png" width="200" alt="Famidash"><br><b>Famidash</b></a><br><sub>Geometry Dash for the NES: 173 levels, every mode, practice mode</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Famidash.nwa">Download</a></td>
+ <td align="center"><a href="games/fnaf3/README.md"><img src="docs/media/thumb_fnaf3.png" width="200" alt="Five Nights at Freddy's 3"><br><b>Five Nights at Freddy's 3</b></a><br><sub>Fazbear's Fright: Springtrap, the phantoms, the lure and the vents</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddys3.nwa">Download</a></td>
<td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-64"><b>Super Mario 64</b></a><br><sub>In a repository of its own: NumWorks-Super-Mario-64</sub></td>
- <td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-Bros"><b>Super Mario Bros.</b></a><br><sub>All 32 stages, in a repository of its own: NumWorks-Super-Mario-Bros</sub></td>
</tr>
<tr>
+ <td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-Bros"><b>Super Mario Bros.</b></a><br><sub>All 32 stages, in a repository of its own: NumWorks-Super-Mario-Bros</sub></td>
<td align="center"><a href="#roadmap"><b>More on the way</b></a><br><sub>Minecraft 1.18.2 and more: see the roadmap</sub></td>
</tr>
</table>
@@ -319,6 +320,7 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
- [x] Crossy Road: the characters and the prize machine
- [x] Famidash: its newest and fullest version, HUGE, with 173 levels
- [x] ColecoVision games in Retro-Go
+- [x] Five Nights at Freddy's 3
- [ ] Full Minecraft 1.18.2 as a standalone app
- [ ] Among Us, against bots
- [ ] Cat Ninja
@@ -340,7 +342,7 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
- [ ] Castle Crashers
- [ ] Hotline Miami
- [ ] More of Retro-Go: Game & Watch, SNES and Mega Drive
-- [ ] Five Nights at Freddy's 3, 4 and FNAF World
+- [ ] Five Nights at Freddy's 4 and FNAF World
- [ ] Brawl Stars, against bots
- [ ] Papers, Please, with the story and Endless
- [ ] Mario Kart
@@ -404,6 +406,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
- **[Famidash](https://github.com/tfdsoft/famidash)** by TFDSoft, Geometry Dash made for the NES, inspired NumPlay's Famidash, which turns the game's own code into C and plays the 173 levels of its HUGE version with its graphics, menu screens, icons and numbers (MIT License, [license](LICENSES/MIT-Famidash.txt)). Famidash is made by Zephyrside (UserSniper), kandowontu, Ficus mcHousePlant, dajinkosa, ElAngel378, SeaGlowingPro, KawaiiDawn and the rest of its team. Its levels are named after songs by ForeverBound, DJVI, Step, Waterflame, Dj-Nate and OcularNebula, which are not in the app. Not affiliated with TFDSoft or RobTop Games.
- **[Level Devil](https://store.steampowered.com/app/3242750/)** by Unept: NumPlay's Level Devil is written in C with no code from the game, but its 80 rooms (their tiles, traps and timing) are the game's own, taken from its web build by games/leveldevil/tools/fetch.py, and its runner is drawn from the game's sprites.
- **Five Nights at Freddy's 2** by Scott Cawthon inspired NumPlay's Five Nights at Freddy's 2, which uses the game's own pictures, from its Clickteam HTML5 build as the fan port [fnaf-2_html5](https://github.com/VocalNutria9174/fnaf-2_html5) (VocalNutria9174) keeps it, two of them from fredtheking's [FNaF2-RaylibCs](https://github.com/fredtheking/FNaF2-RaylibCs), and the DejaVu fonts ([license](LICENSES/DejaVu.txt)). Its AI levels, paths, music box, flashlight and Withered Foxy follow what the game's players read out of its events, written down on the [Technical FNaF Wiki](https://technicalfnaf.fandom.com) and the [Five Nights at Freddy's Wiki](https://freddy-fazbears-pizza.fandom.com). Not affiliated with Scott Cawthon.
+- **Five Nights at Freddy's 3** by Scott Cawthon inspired NumPlay's Five Nights at Freddy's 3, which uses the game's own pictures and runs its nights as the game's own events do, both read from its Android package. Not affiliated with Scott Cawthon.
- **Pong** by Atari (1972) inspired NumPlay's 2 Players, with air hockey, tanks in a maze in the spirit of Tank Trouble and the light cycles of Tron. All four are written in C for NumPlay and drawn from shapes, with no code or art from them.
- **[Cookie Clicker](https://orteil.dashnet.org/cookieclicker/)** by Orteil and Opti (DashNet) inspired NumPlay's Cookie Clicker, which uses the game's own pictures, texts and numbers (version 2.058, from its public mirror [ozh/cookieclicker](https://github.com/ozh/cookieclicker)) and the **Merriweather**, **Kavoon** and **Noto Sans** fonts (SIL Open Font License: [Merriweather](LICENSES/OFL-1.1-Merriweather.txt), [Kavoon](LICENSES/OFL-1.1-Kavoon.txt), [Noto Sans](LICENSES/OFL-1.1-NotoSans.txt)). Not affiliated with Orteil or DashNet.
@@ -432,7 +435,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
NumPlay 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!), Aladdin X (Suika Game), Voodoo (Flappy Dunk), Lima Sky (Doodle Jump), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale), jcw87 (Bad Time Simulator), Imangi Studios (Temple Run), id Software (Doom), Edmund McMillen, Florian Himsl or Nicalis (The Binding of Isaac), PopCap Games or Electronic Arts (Plants vs. Zombies), Scott Cawthon (Five Nights at Freddy's, Five Nights at Freddy's 2), SEGA (Sonic the Hedgehog, Master System, Game Gear, SG-1000), SYBO or Kiloo (Subway Surfers), Fingersoft (Hill Climb Racing), Unept (Level Devil), Halfbrick (Jetpack Joyride), Madbox (Stickman Hook), Nintendo (Donkey Kong, Game Boy, NES), Team Lava (Dune!), Inlogic Software (Dune Rider), TinyDobbins (Monkey Mart), Playgendary (Tomb of the Mask), Mattel (UNO), the Funkin' Crew (Friday Night Funkin'), W Production (Turbo Rush), Rovio Entertainment (Angry Birds), Kodub (PolyTrack), Frank Lantz or Everybody House Games (Universal Paperclips), the makers of Snow Rider 3D, Ketchapp (Rider), TFDSoft (Famidash), Brodie Lockard or Activision (Shanghai), Atari (Pong), Disney (Tron), Orteil or DashNet (Cookie Clicker), Taito or Midway (Space Invaders), Thinking Rabbit or Falcon (Sokoban), Oakever Games (Meowdoku), 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), Coleco (ColecoVision). 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, DOOM of ZeniMax Media, Sonic the Hedgehog, Master System, Game Gear and SG-1000 of SEGA, Space Invaders of Taito, UNO of Mattel, Angry Birds of Rovio Entertainment, and Donkey Kong, 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!), Aladdin X (Suika Game), Voodoo (Flappy Dunk), Lima Sky (Doodle Jump), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale), jcw87 (Bad Time Simulator), Imangi Studios (Temple Run), id Software (Doom), Edmund McMillen, Florian Himsl or Nicalis (The Binding of Isaac), PopCap Games or Electronic Arts (Plants vs. Zombies), Scott Cawthon (Five Nights at Freddy's, Five Nights at Freddy's 2, Five Nights at Freddy's 3), SEGA (Sonic the Hedgehog, Master System, Game Gear, SG-1000), SYBO or Kiloo (Subway Surfers), Fingersoft (Hill Climb Racing), Unept (Level Devil), Halfbrick (Jetpack Joyride), Madbox (Stickman Hook), Nintendo (Donkey Kong, Game Boy, NES), Team Lava (Dune!), Inlogic Software (Dune Rider), TinyDobbins (Monkey Mart), Playgendary (Tomb of the Mask), Mattel (UNO), the Funkin' Crew (Friday Night Funkin'), W Production (Turbo Rush), Rovio Entertainment (Angry Birds), Kodub (PolyTrack), Frank Lantz or Everybody House Games (Universal Paperclips), the makers of Snow Rider 3D, Ketchapp (Rider), TFDSoft (Famidash), Brodie Lockard or Activision (Shanghai), Atari (Pong), Disney (Tron), Orteil or DashNet (Cookie Clicker), Taito or Midway (Space Invaders), Thinking Rabbit or Falcon (Sokoban), Oakever Games (Meowdoku), 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), Coleco (ColecoVision). 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, DOOM of ZeniMax Media, Sonic the Hedgehog, Master System, Game Gear and SG-1000 of SEGA, Space Invaders of Taito, UNO of Mattel, Angry Birds of Rovio Entertainment, and Donkey Kong, Game Boy, Game Boy Color and NES of Nintendo.</sub>
## Gallery
diff --git a/docs/media/thumb_fnaf3.png b/docs/media/thumb_fnaf3.png
new file mode 100644
index 00000000..c5784b13
Binary files /dev/null and b/docs/media/thumb_fnaf3.png differ
diff --git a/docs/play.md b/docs/play.md
index 28b57710..734d39a9 100644
--- a/docs/play.md
+++ b/docs/play.md
@@ -754,6 +754,24 @@ Temple Run comes as its own app, `TempleRun.nwa`. Run from the temple and don't
| **Back** | Pause (Resume, How to play, Quit night) |
Five Nights at Freddy's 2 comes as its own app, `FiveNightsAtFreddys2.nwa`. Last from 12 to 6 AM. Your office has no doors: a hallway in front and a vent on each side. Keep the music box on CAM 11 wound or the Puppet comes, and nothing stops it. When someone stands in the hallway or a vent, put the mask on; if one is in the office when the monitor comes down, the mask at once. The mask doesn't fool Withered Foxy: flash the hallway at him. Balloon Boy takes your lights, and the flashlight's battery doesn't come back. Night 5 opens the 6th, and the 6th the Custom Night, with its ten modes.
+## Five Nights at Freddy's 3
+
+<img src="../games/fnaf3/docs/shot.png" width="320" align="right" alt="Five Nights at Freddy's 3: Springtrap at the office's window">
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** (or 4 / 6) | Look left and right |
+| **OK**, **EXE** or **Up** | The monitor up |
+| **Down** | The maintenance panel up |
+| **Arrows**, **0** to **9** | On the monitor: a camera |
+| **OK** | On the monitor: play the audio (the vent map: seal the vent) |
+| **Backspace** | On the monitor: the camera map or the vent map |
+| **EXE** | The monitor down, the panel's Exit |
+| **Back** | Pause (Resume, Quit game) |
+
+Five Nights at Freddy's 3 comes as its own app, `FiveNightsAtFreddys3.nwa`. Last from 12 to 6 AM at Fazbear's Fright. Springtrap comes room by room: play the audio on a camera next to his and he follows it, and seal the vent he crawls into. Reboot the audio, the cameras and the ventilation on the maintenance panel when they fail; with the ventilation down the dark comes in waves and he comes closer. Look away from a phantom on a camera before it jumps out. Night 5 opens the 6th.
+
+<br clear="right">
## Famidash
<img src="../games/famidash/docs/shot.png" width="320" align="right" alt="Famidash">
diff --git a/games/fnaf3/.gitignore b/games/fnaf3/.gitignore
new file mode 100644
index 00000000..edd4c316
--- /dev/null
+++ b/games/fnaf3/.gitignore
@@ -0,0 +1,4 @@
+output/
+build/
+ref/
+__pycache__/
diff --git a/games/fnaf3/Makefile b/games/fnaf3/Makefile
new file mode 100644
index 00000000..5ed807f2
--- /dev/null
+++ b/games/fnaf3/Makefile
@@ -0,0 +1,81 @@
+# Five Nights at Freddy's 3 on the NumWorks calculator.
+# make output/fnaf3.nwa
+# make check link it like the calculator does (output/fnaf3.bin)
+# make host build/rules and build/pictures: the game on a computer, for tests and screenshots
+# make test the game played on a computer (tests/rules.c, with the sanitizers)
+# make data src/data.bin and src/data.h from the game's application.ccn (CCN=its path; Python + Pillow + NumPy)
+
+Q ?= @
+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>
+TOOLCHAIN ?=
+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
+CC = $(BIN)arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
+SIZE = $(BIN)arm-none-eabi-size
+BUILD_DIR = output
+CCN ?=
+
+# the pictures are decoded and drawn every frame at -O2; the rest is small at -Os
+HOT = src/pic.c src/gfx.c
+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))
+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DEPSILON_XL=1 -DDATA_BIN='"src/data.bin"'
+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean host test data
+build: $(BUILD_DIR)/fnaf3.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/fnaf3.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/fnaf3.bin
+ @echo "BIN $(BUILD_DIR)/fnaf3.bin: $$(wc -c < $(BUILD_DIR)/fnaf3.bin) bytes"
+
+$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)
+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@
+
+$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(@D)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+
+$(BUILD_DIR)/fnaf3.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
+ $(Q) $(STRIP) $@
+ $(Q) $(SIZE) $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+# on a computer: tests/rules.c checks the rules, plays nights and random keys; tests/pics.c draws every picture
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'
+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined
+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c))
+host: build/pictures build/rules
+build/pictures: src/pic.c src/gfx.c src/plat_host.c tests/pics.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) src/pic.c src/gfx.c src/plat_host.c tests/pics.c src/data.S -lm -o $@
+
+build/rules: $(HOST_SRC) tests/rules.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/rules.c src/data.S -lm -o $@
+
+test: host
+ ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 build/rules
+
+data:
+ python3 -I tools/pack.py $(CCN)
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/fnaf3/README.md b/games/fnaf3/README.md
new file mode 100644
index 00000000..63b94977
--- /dev/null
+++ b/games/fnaf3/README.md
@@ -0,0 +1,82 @@
+> **Five Nights at Freddy's 3 is a [NumPlay](../../README.md) game that comes on its own.** It is too big to sit next to NumPlay. Get `FiveNightsAtFreddys3.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+<p align="center">
+ <img src="src/icon.png" width="84" alt="Five Nights at Freddy's 3 icon">
+</p>
+
+<h1 align="center">Five Nights at Freddy's 3</h1>
+
+<p align="center">
+ <b>Survive the night shift at Fazbear's Fright, on the NumWorks calculator.</b><br>
+ Nights 1 to 5 and the 6th night, with Springtrap, the phantoms, the audio lure, the vents and the maintenance panel.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddys3.nwa"><b>Download FiveNightsAtFreddys3.nwa</b></a>
+ &nbsp;·&nbsp; <a href="#controls">Controls</a>
+</p>
+
+## Highlights
+
+* **The game's own night:** Springtrap, the phantoms and the three systems run as the game's own events run them, read out of its Android package: his rooms and his moves, when he waits for you to look at a screen, the lure that fails 1 time in 7, the wear on each system and the reboot times.
+* **Springtrap** walks the attraction's ten cameras and its five vents. He looks in through the window, runs past it, hides by the door and peeks around it. Lure him away with BB's laugh, and seal the vent he's in.
+* **The maintenance panel:** the audio, the cameras and the ventilation wear out. Reboot one or all. With the ventilation down the office flashes red, the cameras show him where he isn't, and the dark comes in waves.
+* **The phantoms:** BB, Mangle, Chica, Phantom Freddy, the Puppet and Foxy, when and where the game brings them, each once a night.
+* **Nights 1 to 5, then the 6th:** the 6th night and the Extras open once the game is beaten, a star for each ending.
+* **Saved like in the game:** the night you reached and your stars. Home keeps the night as it is, and the next start puts you back in it, paused. Your saves are also copied into `fnaf3_saves.py`, so installing the app again doesn't erase them.
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/shot.png" width="390" alt="Springtrap at the office's window at 3 AM"><br><sub>Springtrap at the window</sub></td>
+ <td align="center"><img src="docs/monitor.png" width="390" alt="CAM 07 on the monitor, the map over it"><br><sub>The cameras</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/vents.png" width="390" alt="The vent cameras, CAM 12 sealed"><br><sub>The vents</sub></td>
+ <td align="center"><img src="docs/panel.png" width="390" alt="The maintenance panel, two systems in error"><br><sub>The maintenance panel</sub></td>
+ </tr>
+</table>
+
+## How to play
+
+New Game starts the first night. Last from 12 to 6 AM: an hour is half a minute on the first night, a minute after that.
+
+Springtrap comes closer room by room. Find him on the cameras, then play the audio on a camera next to his: he follows the sound. On the vent map, seal the vent he crawls into, and he turns back. Watch the maintenance panel: when a system errors, reboot it. Looking away from every screen too long wears the ventilation down.
+
+The phantoms don't kill you, but their scare brings the ventilation down and Springtrap closer. Look away from a phantom on a camera before it jumps out.
+
+## Controls
+
+| Key | What it does |
+| --- | --- |
+| ← → or 4 6 | Look left and right |
+| OK, EXE or ↑ | The monitor up (looking right first) |
+| ↓ | The maintenance panel up (looking left first) |
+| Arrows or 0 to 9 | On the monitor: a camera (0 is CAM 10; 1 to 5 on the vent map are CAM 11 to 15) |
+| OK | On the monitor: play the audio, or seal the vent on the vent map |
+| Backspace | On the monitor: the camera map or the vent map |
+| EXE | The monitor down, the panel's Exit |
+| ↑ ↓, OK | On the panel: a system, reboot it |
+| Back | Pause |
+| Home | Keep the night and quit |
+
+## Good to know
+
+* **One app at a time:** Five Nights at Freddy's 3 can't share the calculator's room for apps with NumPlay. Install it on its own; your saves in each one are kept.
+* **No sound:** the calculator has no speaker. What you would hear is written at the bottom left: the footsteps, the vents, BB's laugh, the alarm. Springtrap's hum, louder the closer he is, is the two bars at the top left.
+* **Left out:** the phone calls and the 8-bit minigames between nights, with the good ending they lead to. The cheats in Extras open with the good ending, so they stay shut.
+* **The pictures are the game's,** at half size: the screen shows 640 of its 800 pixels around where the game looks.
+
+## Credits
+
+Inspired by Five Nights at Freddy's 3 by Scott Cawthon, not affiliated with him.
+
+* The pictures and the rules come from the game's Android package (its Clickteam application): `tools/ccn.py` reads its pictures and objects, and `tools/pack.py` places them as the game places them and makes them into `src/data.bin`. The night follows the game's own events, read out of the same file.
+* The words are drawn in the DejaVu fonts ([license](../../LICENSES/DejaVu.txt)).
+
+Made by Mason Chen as part of NumPlay.
+
+## License
+
+The game's code is licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. The game's pictures keep their own terms (see Credits).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink), `make test` on a computer.
diff --git a/games/fnaf3/docs/bb.png b/games/fnaf3/docs/bb.png
new file mode 100644
index 00000000..4bb6bf5b
Binary files /dev/null and b/games/fnaf3/docs/bb.png differ
diff --git a/games/fnaf3/docs/monitor.png b/games/fnaf3/docs/monitor.png
new file mode 100644
index 00000000..8f363ea2
Binary files /dev/null and b/games/fnaf3/docs/monitor.png differ
diff --git a/games/fnaf3/docs/panel.png b/games/fnaf3/docs/panel.png
new file mode 100644
index 00000000..738016a4
Binary files /dev/null and b/games/fnaf3/docs/panel.png differ
diff --git a/games/fnaf3/docs/shot.png b/games/fnaf3/docs/shot.png
new file mode 100644
index 00000000..10248705
Binary files /dev/null and b/games/fnaf3/docs/shot.png differ
diff --git a/games/fnaf3/docs/vents.png b/games/fnaf3/docs/vents.png
new file mode 100644
index 00000000..811d7801
Binary files /dev/null and b/games/fnaf3/docs/vents.png differ
diff --git a/games/fnaf3/src/data.S b/games/fnaf3/src/data.S
new file mode 100644
index 00000000..778bbe6e
--- /dev/null
+++ b/games/fnaf3/src/data.S
@@ -0,0 +1,19 @@
+/* data.bin (tools/pack.py) in the app's read-only data */
+#ifdef __APPLE__
+ .const_data
+ .p2align 2
+ .globl _fnaf3_data
+_fnaf3_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.fnaf3_data,"a"
+ .balign 4
+ .global fnaf3_data
+fnaf3_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/fnaf3/src/data.bin b/games/fnaf3/src/data.bin
new file mode 100644
index 00000000..e5134ccf
Binary files /dev/null and b/games/fnaf3/src/data.bin differ
diff --git a/games/fnaf3/src/data.h b/games/fnaf3/src/data.h
new file mode 100644
index 00000000..6a965fa1
--- /dev/null
+++ b/games/fnaf3/src/data.h
@@ -0,0 +1,379 @@
+/* Made by tools/pack.py: what is in data.bin. */
+#ifndef FNAF3_DATA_H
+#define FNAF3_DATA_H
+
+#define SEC_HUFF 0
+#define SEC_QUANT 1
+#define SEC_PICS 2
+#define SEC_TABLE 3
+#define SEC_BANK 4
+#define SEC_FONTS 5
+#define SEC_IMGS 6
+#define PIC_OFFICE 0
+#define PIC_OFFICE_RED 1
+#define PIC_WIN_SPRING 2
+#define PIC_WIN_RUN0 3
+#define PIC_WIN_RUN1 4
+#define PIC_WIN_RUN2 5
+#define PIC_WIN_RUN3 6
+#define PIC_WIN_RUN4 7
+#define PIC_WIN_RUN5 8
+#define PIC_WIN_RUN6 9
+#define PIC_WIN_RUN7 10
+#define PIC_WIN_FREDDY0 11
+#define PIC_WIN_FREDDY1 12
+#define PIC_WIN_FREDDY2 13
+#define PIC_WIN_FREDDY3 14
+#define PIC_WIN_FREDDY4 15
+#define PIC_WIN_FREDDY5 16
+#define PIC_WIN_FREDDY6 17
+#define PIC_WIN_FREDDY7 18
+#define PIC_WIN_FREDDY8 19
+#define PIC_WIN_FREDDY9 20
+#define PIC_WIN_FREDDY10 21
+#define PIC_WIN_FREDDY11 22
+#define PIC_WIN_FREDDY12 23
+#define PIC_WIN_FREDDY13 24
+#define PIC_WIN_FREDDY14 25
+#define PIC_WIN_FREDDY15 26
+#define PIC_WIN_FREDDY16 27
+#define PIC_WIN_FREDDY17 28
+#define PIC_WIN_FREDDY18 29
+#define PIC_WIN_FREDDY19 30
+#define PIC_WIN_FREDDY20 31
+#define PIC_WIN_FREDDY21 32
+#define PIC_WIN_FREDDY22 33
+#define PIC_WIN_FREDDY23 34
+#define PIC_WIN_FREDDY24 35
+#define PIC_WIN_FREDDY25 36
+#define PIC_WIN_FREDDY26 37
+#define PIC_WIN_FREDDY27 38
+#define PIC_WIN_FREDDY28 39
+#define PIC_WIN_FREDDY29 40
+#define PIC_WIN_FREDDY30 41
+#define PIC_WIN_FREDDY31 42
+#define PIC_WIN_FREDDY32 43
+#define PIC_WIN_FREDDY33 44
+#define PIC_WIN_FREDDY34 45
+#define PIC_WIN_FREDDY35 46
+#define PIC_WIN_FREDDY36 47
+#define PIC_WIN_FREDDY37 48
+#define PIC_WIN_FREDDY38 49
+#define PIC_WIN_FREDDY39 50
+#define PIC_WIN_FREDDY40 51
+#define PIC_WIN_FREDDY41 52
+#define PIC_WIN_FREDDY42 53
+#define PIC_WIN_FREDDY43 54
+#define PIC_WIN_FREDDY44 55
+#define PIC_WIN_FREDDY45 56
+#define PIC_WIN_FREDDY46 57
+#define PIC_WIN_FREDDY47 58
+#define PIC_WIN_FREDDY48 59
+#define PIC_WIN_FREDDY49 60
+#define PIC_WIN_FREDDY50 61
+#define PIC_WIN_FREDDY51 62
+#define PIC_WIN_FREDDY52 63
+#define PIC_WIN_FREDDY53 64
+#define PIC_WIN_FREDDY54 65
+#define PIC_WIN_FREDDY55 66
+#define PIC_WIN_FREDDY56 67
+#define PIC_WIN_FREDDY57 68
+#define PIC_WIN_FREDDY58 69
+#define PIC_WIN_FREDDY59 70
+#define PIC_WIN_FREDDY60 71
+#define PIC_WIN_FREDDY61 72
+#define PIC_WIN_FREDDY62 73
+#define PIC_WIN_FREDDY63 74
+#define PIC_WIN_FREDDY64 75
+#define PIC_WIN_FREDDY65 76
+#define PIC_WIN_FREDDY66 77
+#define PIC_WIN_FREDDY67 78
+#define PIC_WIN_FREDDY68 79
+#define PIC_WIN_FREDDY69 80
+#define PIC_WIN_FREDDY70 81
+#define PIC_WIN_FREDDY71 82
+#define PIC_WIN_FREDDY72 83
+#define PIC_WIN_FREDDY73 84
+#define PIC_WIN_FREDDY74 85
+#define PIC_WIN_FREDDY75 86
+#define PIC_WIN_FREDDY76 87
+#define PIC_WIN_FREDDY77 88
+#define PIC_WIN_FREDDY78 89
+#define PIC_WIN_FREDDY79 90
+#define PIC_WIN_FREDDY80 91
+#define PIC_WIN_FREDDY81 92
+#define PIC_WIN_FREDDY82 93
+#define PIC_WIN_FREDDY83 94
+#define PIC_WIN_FREDDY84 95
+#define PIC_WIN_FREDDY85 96
+#define PIC_WIN_FREDDY86 97
+#define PIC_WIN_FLUNGE0 98
+#define PIC_WIN_FLUNGE1 99
+#define PIC_WIN_FLUNGE2 100
+#define PIC_WIN_FLUNGE3 101
+#define PIC_WIN_FLUNGE4 102
+#define PIC_WIN_FLUNGE5 103
+#define PIC_WIN_FLUNGE6 104
+#define PIC_WIN_FLUNGE7 105
+#define PIC_WIN_FLUNGE8 106
+#define PIC_WIN_FLUNGE9 107
+#define PIC_WIN_FLUNGE10 108
+#define PIC_WIN_MANGLE0 109
+#define PIC_WIN_MANGLE1 110
+#define PIC_WIN_MANGLE2 111
+#define PIC_WIN_MANGLE3 112
+#define PIC_WIN_MANGLE4 113
+#define PIC_WIN_MANGLE5 114
+#define PIC_WIN_MANGLE6 115
+#define PIC_WIN_MANGLE7 116
+#define PIC_WIN_MANGLE8 117
+#define PIC_WIN_MANGLE9 118
+#define PIC_WIN_MANGLE10 119
+#define PIC_DOOR_HEAD 120
+#define PIC_DOOR_HIDE0 121
+#define PIC_DOOR_HIDE1 122
+#define PIC_DOOR_HIDE2 123
+#define PIC_DOOR_HIDE3 124
+#define PIC_DOOR_HIDE4 125
+#define PIC_DOOR_HIDE5 126
+#define PIC_DOOR_HIDE6 127
+#define PIC_DOOR_HIDE7 128
+#define PIC_BB0 129
+#define PIC_BB1 130
+#define PIC_BB2 131
+#define PIC_BB3 132
+#define PIC_BB4 133
+#define PIC_BB5 134
+#define PIC_BB6 135
+#define PIC_CHICA0 136
+#define PIC_CHICA1 137
+#define PIC_CHICA2 138
+#define PIC_CHICA3 139
+#define PIC_CHICA4 140
+#define PIC_CHICA5 141
+#define PIC_CHICA6 142
+#define PIC_FOXY0 143
+#define PIC_FOXY1 144
+#define PIC_FOXY2 145
+#define PIC_FOXY3 146
+#define PIC_FOXY4 147
+#define PIC_FOXY5 148
+#define PIC_FOXY6 149
+#define PIC_FOXY7 150
+#define PIC_JUMPL0 151
+#define PIC_JUMPL1 152
+#define PIC_JUMPL2 153
+#define PIC_JUMPL3 154
+#define PIC_JUMPL4 155
+#define PIC_JUMPL5 156
+#define PIC_JUMPL6 157
+#define PIC_JUMPL7 158
+#define PIC_JUMPL8 159
+#define PIC_JUMPL9 160
+#define PIC_JUMPL10 161
+#define PIC_JUMPR0 162
+#define PIC_JUMPR1 163
+#define PIC_JUMPR2 164
+#define PIC_JUMPR3 165
+#define PIC_JUMPR4 166
+#define PIC_JUMPR5 167
+#define PIC_JUMPR6 168
+#define PIC_JUMPR7 169
+#define PIC_JUMPR8 170
+#define PIC_JUMPR9 171
+#define PIC_JUMPR10 172
+#define PIC_FSCARE0 173
+#define PIC_FSCARE1 174
+#define PIC_FSCARE2 175
+#define PIC_FSCARE3 176
+#define PIC_FSCARE4 177
+#define PIC_FEED12_0 178
+#define PIC_FEED12_1 179
+#define PIC_FEED13_0 180
+#define PIC_FEED14_0 181
+#define PIC_FEED14_1 182
+#define PIC_FEED15_0 183
+#define PIC_FEED16_0 184
+#define PIC_FEED17_0 185
+#define PIC_FEED21_0 186
+#define PIC_FEED21_1 187
+#define PIC_FEED23_0 188
+#define PIC_FEED24_0 189
+#define PIC_FEED25_0 190
+#define PIC_FEED26_0 191
+#define PIC_FEED26_1 192
+#define PIC_FEED27_0 193
+#define PIC_FEED27_1 194
+#define PIC_FEED28_0 195
+#define PIC_FEED29_0 196
+#define PIC_FEED30_0 197
+#define PIC_FEED31_0 198
+#define PIC_FEED32_0 199
+#define PIC_FEED33_0 200
+#define PIC_FEED34_0 201
+#define PIC_FEED35_0 202
+#define PIC_FEED35_1 203
+#define PIC_FEED43_0 204
+#define PIC_FEED43_1 205
+#define PIC_FEED45_0 206
+#define PIC_FEED46_0 207
+#define PIC_FEED47_0 208
+#define PIC_FEED48_0 209
+#define PIC_FEED49_0 210
+#define PIC_FEED50_0 211
+#define PIC_FEED51_0 212
+#define PIC_FEED52_0 213
+#define PIC_FEED53_0 214
+#define PIC_FEED54_0 215
+#define PIC_FEED55_0 216
+#define PIC_FEED56_0 217
+#define PIC_FEED57_0 218
+#define PIC_BBPEEK 219
+#define PIC_GAMEOVER 220
+#define PIC_BADEND 221
+#define PIC_GOODEND 222
+#define PIC_THEEND 223
+#define PIC_TITLE 224
+#define PIC_TITLE12 225
+#define PIC_TITLE13 226
+#define PIC_TITLE14 227
+#define PIC_TITLE15 228
+#define PIC_PANEL 229
+#define PIC_COUNT 230
+#define FONT_HUD 0
+#define FONT_BIG 1
+#define FONT_TEXT 2
+#define FONT_CLOCK 3
+#define FONT_HUGE 4
+#define RUN_N 8
+#define FREDDY_X0 995
+#define FREDDY_N 87
+#define FLUNGE_N 11
+#define HIDE_N 8
+#define BB_N 7
+#define CHICA_N 7
+#define FOXY_N 8
+#define WIN_X 240
+#define WIN_Y 16
+#define WIN_W 272
+#define WIN_H 128
+#define DOOR_X 0
+#define DOOR_Y 32
+#define DOOR_W 144
+#define DOOR_H 176
+#define BB_X 352
+#define BB_Y 48
+#define BB_W 176
+#define BB_H 192
+#define CHICA_X 64
+#define CHICA_Y 16
+#define CHICA_W 288
+#define CHICA_H 224
+#define FOXY_X 160
+#define FOXY_Y 0
+#define FOXY_W 128
+#define FOXY_H 240
+#define JUMP_N 11
+#define FSCARE_N 5
+#define FEED12_N 2
+#define FEED13_N 1
+#define FEED14_N 2
+#define FEED15_N 1
+#define FEED16_N 1
+#define FEED17_N 1
+#define FEED21_N 2
+#define FEED23_N 1
+#define FEED24_N 1
+#define FEED25_N 1
+#define FEED26_N 2
+#define FEED27_N 2
+#define FEED28_N 1
+#define FEED29_N 1
+#define FEED30_N 1
+#define FEED31_N 1
+#define FEED32_N 1
+#define FEED33_N 1
+#define FEED34_N 1
+#define FEED35_N 2
+#define FEED43_N 2
+#define FEED45_N 1
+#define FEED46_N 1
+#define FEED47_N 1
+#define FEED48_N 1
+#define FEED49_N 1
+#define FEED50_N 1
+#define FEED51_N 1
+#define FEED52_N 1
+#define FEED53_N 1
+#define FEED54_N 1
+#define FEED55_N 1
+#define FEED56_N 1
+#define FEED57_N 1
+#define IMG_STAR 0
+#define IMG_MAP 1
+#define IMG_VENTMAP 2
+#define MAP_X 152
+#define MAP_Y 86
+#define BTN01_X 183
+#define BTN01_Y 203
+#define BTN02_X 263
+#define BTN02_Y 193
+#define BTN03_X 293
+#define BTN03_Y 177
+#define BTN04_X 293
+#define BTN04_Y 153
+#define BTN05_X 232
+#define BTN05_Y 159
+#define BTN06_X 181
+#define BTN06_Y 162
+#define BTN07_X 181
+#define BTN07_Y 137
+#define BTN08_X 220
+#define BTN08_Y 129
+#define BTN09_X 244
+#define BTN09_Y 113
+#define BTN10_X 284
+#define BTN10_Y 127
+#define BTN11_X 182
+#define BTN11_Y 103
+#define BTN12_X 205
+#define BTN12_Y 147
+#define BTN13_X 237
+#define BTN13_Y 169
+#define BTN14_X 268
+#define BTN14_Y 139
+#define BTN15_X 277
+#define BTN15_Y 191
+#define SEAL11_X 173
+#define SEAL11_Y 125
+#define SEAL12_X 184
+#define SEAL12_Y 151
+#define SEAL13_X 218
+#define SEAL13_Y 174
+#define SEAL14_X 287
+#define SEAL14_Y 163
+#define SEAL15_X 259
+#define SEAL15_Y 200
+#define IMG_P_AUDIO 3
+#define IMG_P_CAMERA 4
+#define IMG_P_VENT 5
+#define IMG_P_ALL 6
+#define IMG_P_EXIT 7
+#define IMG_P_CURSOR 8
+#define IMG_P_ERROR 9
+#define IMG_P_DOTS0 10
+#define IMG_P_DOTS1 11
+#define IMG_P_DOTS2 12
+#define IMG_P_DOTS3 13
+#define IMG_P_DOTS4 14
+#define DOTS_N 5
+#define IMG_M_AUDIO 15
+#define IMG_M_VIDEO 16
+#define IMG_M_VENT 17
+#define IMG_PHEAD0 18
+#define IMG_PHEAD1 19
+#define IMG_PHEAD2 20
+#define IMG_PHEAD3 21
+#define IMG_PHEAD4 22
+
+#endif
diff --git a/games/fnaf3/src/game.c b/games/fnaf3/src/game.c
new file mode 100644
index 00000000..79cd6af1
--- /dev/null
+++ b/games/fnaf3/src/game.c
@@ -0,0 +1,268 @@
+/* Five Nights at Freddy's 3: the scenes around the nights, the keys and the saves.
+ *
+ * As the game: the title (New Game, Continue, the 6th night and Extras once the game is beaten, a star for each
+ * ending), the night's card, the night, 5 AM turning 6 AM, the static and game over when Springtrap gets you, and
+ * the endings after the 5th and the 6th night. */
+#include <stdio.h>
+#include <string.h>
+#include "game.h"
+#include "gfx.h"
+#include "data.h"
+#include "plat.h"
+
+Game g;
+
+static uint32_t seed = 0x3F3A2B1u;
+uint32_t rnd(void) {
+ seed = seed * 1664525u + 1013904223u;
+ return seed >> 8;
+}
+uint32_t rnd_n(uint32_t n) { return n ? rnd() % n : 0; }
+
+static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }
+#define GREY_TEXT RGB(0x9A9A9A)
+#define GREEN_TEXT RGB(0x4CD964)
+static void game_band(void);
+
+void caption(const char *s) {
+ for (int i = 0; i < 3; i++) g.cap[i] = g.cap[i + 1], g.cap_t[i] = g.cap_t[i + 1];
+ g.cap[3] = s, g.cap_t[3] = 3;
+}
+
+static void go(int scene) { g.scene = scene, g.t = 0, g.menu = 0; }
+
+void start_night(int night) {
+ night_begin(night);
+ memset(g.cap, 0, sizeof g.cap);
+ go(SC_DAY);
+}
+
+void game_init(void) {
+ memset(&g, 0, sizeof g);
+ g.running = true;
+ seed ^= plat_millis() * 2654435761u;
+ save_restore_copy();
+ save_load();
+ if (save_resume_load()) g.scene = SC_NIGHT, g.paused = 1;
+}
+
+/* ------------------------------------------------------------ the title */
+enum { M_NEW, M_CONTINUE, M_SIXTH, M_EXTRAS };
+static int title_items(uint8_t *items) {
+ int n = 0;
+ items[n++] = M_NEW, items[n++] = M_CONTINUE;
+ if (g.beatgame) items[n++] = M_SIXTH, items[n++] = M_EXTRAS;
+ return n;
+}
+
+static void title_step(void) {
+ uint8_t items[4];
+ int n = title_items(items);
+ if (pressed(K_UP | K_DIGIT(8))) g.menu = (uint8_t)((g.menu + n - 1) % n);
+ if (pressed(K_DOWN | K_DIGIT(2))) g.menu = (uint8_t)((g.menu + 1) % n);
+ if (pressed(K_BACK)) g.running = false;
+ if (!pressed(K_OK | K_EXE)) return;
+ switch (items[g.menu]) {
+ case M_NEW: g.level = 1, save_progress(), start_night(1); break;
+ case M_CONTINUE: start_night(g.level > 5 ? 5 : g.level); break;
+ case M_SIXTH: start_night(6); break;
+ case M_EXTRAS: go(SC_EXTRAS); break;
+ }
+}
+
+static void title_draw(void) {
+ int r = (int)(g.t * 60) % 240;
+ int pic = r < 4 ? PIC_TITLE12 : r < 7 ? PIC_TITLE13 : r == 100 ? PIC_TITLE14 : PIC_TITLE;
+ pic_draw(pic, 0, 0);
+ gfx_static(0, 0, SCREEN_W, SCREEN_H, 4 + (int)rnd_n(4), (uint32_t)(g.t * 60));
+ gfx_text_s(FONT_BIG, 14, 14, "Five", WHITE);
+ gfx_text_s(FONT_BIG, 14, 32, "Nights", WHITE);
+ gfx_text_s(FONT_BIG, 14, 50, "at", WHITE);
+ gfx_text_s(FONT_BIG, 14, 68, "Freddy's", WHITE);
+ gfx_text_s(FONT_HUGE, 120, 50, "3", WHITE);
+ uint8_t items[4];
+ int n = title_items(items);
+ static const char *const names[4] = {"New Game", "Continue", "6th Night", "Extras"};
+ for (int i = 0; i < n; i++) {
+ int y = 120 + 22 * i;
+ if (i == g.menu) gfx_text_s(FONT_TEXT, 14, y, ">>", WHITE);
+ gfx_text_s(FONT_TEXT, 34, y, names[items[i]], WHITE);
+ if (items[i] == M_CONTINUE) {
+ char t[12];
+ snprintf(t, sizeof t, "Night %d", g.level > 5 ? 5 : g.level);
+ gfx_text_s(FONT_HUD, 112, y + 1, t, GREY_TEXT);
+ }
+ }
+ int stars = g.beatgame + g.beat6 + g.goodend;
+ for (int i = 0; i < stars; i++) gfx_img(IMG_STAR, 14 + 26 * i, 96, WHITE);
+ gfx_text(FONT_HUD, 8, SCREEN_H - 14, "Up Down choose OK start Back quit", WHITE);
+}
+
+/* ------------------------------------------------------------ extras */
+static void extras_step(void) {
+ bool cheats = g.goodend && g.beat6;
+ int n = cheats ? 5 : 1;
+ if (pressed(K_UP | K_DIGIT(8))) g.extras_sel = (uint8_t)((g.extras_sel + n - 1) % n);
+ if (pressed(K_DOWN | K_DIGIT(2))) g.extras_sel = (uint8_t)((g.extras_sel + 1) % n);
+ if (pressed(K_BACK)) go(SC_TITLE);
+ if (pressed(K_OK | K_EXE)) {
+ if (g.extras_sel == n - 1) go(SC_TITLE);
+ else g.cheats ^= (uint8_t)(1 << g.extras_sel), save_progress();
+ }
+}
+
+static void extras_draw(void) {
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ gfx_text_s(FONT_BIG, 14, 12, "Extras", WHITE);
+ bool cheats = g.goodend && g.beat6;
+ static const char *const names[4] = {"Fast Nights", "Radar", "Aggressive", "No Errors"};
+ int n = 0;
+ if (cheats)
+ for (; n < 4; n++) {
+ int y = 50 + 22 * n;
+ if (n == g.extras_sel) gfx_text(FONT_TEXT, 14, y, ">>", WHITE);
+ gfx_text(FONT_TEXT, 34, y, names[n], WHITE);
+ gfx_text(FONT_TEXT, 160, y, g.cheats >> n & 1 ? "ON" : "OFF", g.cheats >> n & 1 ? GREEN_TEXT : GREY_TEXT);
+ }
+ else
+ gfx_text(FONT_TEXT, 14, 50, "The cheats open after the 6th night and the good ending.", GREY_TEXT);
+ int y = 50 + 22 * (cheats ? 4 : 2);
+ if (g.extras_sel == n) gfx_text(FONT_TEXT, 14, y, ">>", WHITE);
+ gfx_text(FONT_TEXT, 34, y, "Exit", WHITE);
+ gfx_text(FONT_HUD, 8, SCREEN_H - 14, "Up Down choose OK pick Back title", WHITE);
+}
+
+/* ------------------------------------------------------------ the night and around it */
+static void captions_draw(void) {
+ int y = SCREEN_H - 30;
+ for (int i = 3; i >= 0; i--) {
+ if (!g.cap[i] || g.cap_t[i] <= 0) continue;
+ gfx_text_s(FONT_TEXT, 8, y, g.cap[i], WHITE);
+ y -= 13;
+ }
+}
+
+static const char *key_line(void) {
+ if (g.n.viewing >= 2) return g.n.vents_map ? "Arrows cams OK seal Del map EXE down" : "Arrows cams OK audio Del map EXE down";
+ if (g.n.panel >= 2) return g.n.rebooting ? "Rebooting..." : "Up Down choose OK reboot EXE exit";
+ return "Left Right look OK monitor Down panel";
+}
+
+static void pause_step(void) {
+ if (g.confirm) {
+ if (pressed(K_OK | K_EXE)) save_resume(), g.n.night = 0, go(SC_TITLE), g.paused = 0, g.confirm = 0;
+ if (pressed(K_BACK)) g.confirm = 0;
+ return;
+ }
+ if (pressed(K_UP | K_DOWN | K_DIGIT(8) | K_DIGIT(2))) g.pause_item ^= 1;
+ if (pressed(K_BACK)) g.paused = 0;
+ if (pressed(K_OK | K_EXE)) {
+ if (g.pause_item == 0) g.paused = 0;
+ else g.confirm = 1;
+ }
+}
+
+static void pause_draw(void) {
+ gfx_dim(0, 60, SCREEN_W, 120, 22);
+ if (g.confirm) {
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 90, "Quit the night?", WHITE);
+ gfx_text_c(FONT_HUD, SCREEN_W / 2, 120, "OK quit Back stay", WHITE);
+ return;
+ }
+ gfx_text_c(FONT_BIG, SCREEN_W / 2, 74, "Paused", WHITE);
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 110, g.pause_item == 0 ? "> Resume <" : "Resume", WHITE);
+ gfx_text_c(FONT_TEXT, SCREEN_W / 2, 134, g.pause_item == 1 ? "> Quit game <" : "Quit game", WHITE);
+}
+
+static void six_done(void) {
+ int night = g.n.night;
+ if (night == 5) g.beatgame = 1;
+ if (night == 6) g.beat6 = 1;
+ if (night < 5) g.level = (uint8_t)(night + 1);
+ save_progress();
+ if (night >= 5) g.ending = night == 6 ? 2 : 1, go(SC_END);
+ else start_night(night + 1);
+}
+
+void game_step(uint32_t keys) {
+ g.pressed = keys & ~g.held;
+ g.held = keys;
+ if (keys & K_HOME) {
+ if (g.scene == SC_NIGHT && !g.n.got_you) save_resume();
+ g.running = false;
+ return;
+ }
+ for (int i = 0; i < 4; i++)
+ if (g.cap_t[i] > 0) g.cap_t[i] -= 1.0f / 60;
+ switch (g.scene) {
+ case SC_TITLE: title_step(); break;
+ case SC_EXTRAS: extras_step(); break;
+ case SC_DAY:
+ if (g.t > 160 / 60.0f) go(SC_NIGHT);
+ break;
+ case SC_NIGHT:
+ if (g.paused) {
+ pause_step();
+ break;
+ }
+ if (pressed(K_BACK)) {
+ g.paused = 1, g.pause_item = 0;
+ break;
+ }
+ night_step();
+ break;
+ case SC_STATIC:
+ if (g.t > 5) go(SC_OVER);
+ break;
+ case SC_OVER:
+ if (g.t > 5 || (g.t > 0.5f && pressed(K_OK | K_EXE | K_BACK))) go(SC_TITLE);
+ break;
+ case SC_SIX:
+ if (g.t > 400 / 60.0f || (g.t > 2 && pressed(K_OK | K_EXE))) six_done();
+ break;
+ case SC_END:
+ if (g.t > 20 || (g.t > 3 && pressed(K_OK | K_EXE | K_BACK))) go(SC_TITLE);
+ break;
+ }
+ g.t += 1.0f / 60;
+}
+
+void game_draw(void) { gfx_frame(game_band); }
+
+/* (gfx_frame calls this for each band) */
+static void game_band(void) {
+ switch (g.scene) {
+ case SC_TITLE: title_draw(); break;
+ case SC_EXTRAS: extras_draw(); break;
+ case SC_DAY: {
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ gfx_text_c(FONT_CLOCK, SCREEN_W / 2, 90, "12:00 AM", WHITE);
+ char t[12];
+ snprintf(t, sizeof t, "Night %d", g.n.night);
+ gfx_text_c(FONT_BIG, SCREEN_W / 2, 126, t, WHITE);
+ break;
+ }
+ case SC_NIGHT:
+ view_night();
+ captions_draw();
+ if (g.n.frame < 600 || g.n.viewing >= 2 || g.n.panel >= 2) {
+ gfx_dim(0, SCREEN_H - 14, SCREEN_W, 14, 20);
+ gfx_text(FONT_HUD, 6, SCREEN_H - 13, key_line(), WHITE);
+ }
+ if (g.paused) pause_draw();
+ break;
+ case SC_STATIC: gfx_static(0, 0, SCREEN_W, SCREEN_H, 32, (uint32_t)(g.t * 60)); break;
+ case SC_OVER: pic_draw(PIC_GAMEOVER, 0, 0); break;
+ case SC_SIX: {
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ float t = g.t * 60; /* (the 5 rolls up for 100 frames, the 6 comes up for 100) */
+ int h = t < 100 ? 5 : 6, dy = t < 100 ? -(int)(t * 30 / 100) : t < 200 ? 30 - (int)((t - 100) * 30 / 100) : 0;
+ char s[8];
+ snprintf(s, sizeof s, "%d", h);
+ gfx_text_r(FONT_HUGE, 150, 100 + dy, s, WHITE);
+ gfx_text(FONT_HUGE, 156, 100, "AM", WHITE);
+ break;
+ }
+ case SC_END: pic_draw(g.ending == 2 ? PIC_THEEND : PIC_BADEND, 0, 0); break;
+ }
+}
diff --git a/games/fnaf3/src/game.h b/games/fnaf3/src/game.h
new file mode 100644
index 00000000..3483e795
--- /dev/null
+++ b/games/fnaf3/src/game.h
@@ -0,0 +1,169 @@
+/* Five Nights at Freddy's 3: the game's state and its parts.
+ *
+ * game.c: the scenes (title, extras, the night's card, 6 AM, the static and game over, the endings), keys and saves.
+ * night.c: a night as the game's own events run it (Springtrap, the audio lure, the vents, the three systems and
+ * their errors, the phantoms), 60 steps a second, in the events' order. view.c: drawing the office, the monitor
+ * and the maintenance panel. The game's names for its counters are kept in the comments. */
+#ifndef FNAF3_GAME_H
+#define FNAF3_GAME_H
+#include <stdbool.h>
+#include <stdint.h>
+
+#define XMIN 392 /* the view's centre, in the game's 1200-wide office ("scroll" X: 392..812 in steps of 20) */
+#define XMAX 812
+
+/* where Springtrap can be ("dhfgh" overlapping a marker): CAM 01 to 10 (1..10), the vents CAM 11 to 15
+ (11..15), then the office's approach ("attack stage 1" to 4) and the two lunges ("GOT YOU", "GOT YOU 2") */
+enum { L_NONE, L_CAM1, L_CAM10 = 10, L_VENT11, L_VENT15 = 15, L_ST1, L_ST2, L_ST3, L_ST4, L_GOT, L_GOT2, L_OFF };
+
+/* the scares that end a phantom's sighting with a white flash (the "white flash" animation each uses) */
+enum { PH_NONE, PH_BB, PH_FREDDY, PH_CHICA, PH_FOXY };
+
+/* scenes */
+enum { SC_TITLE, SC_EXTRAS, SC_DAY, SC_NIGHT, SC_STATIC, SC_OVER, SC_SIX, SC_END };
+
+/* A night, all of it: kept as it is when Home quits (save.c), so the next start goes on from there. */
+typedef struct {
+ uint8_t night; /* "night number": 1 to 6 */
+ uint8_t ai; /* "AI" */
+ uint8_t tlimit; /* "time limit": the phantoms' stare limit, in frames */
+ uint8_t hour; /* "hour": 0 (12 AM) to 6 */
+ /* Springtrap */
+ uint8_t loc; /* L_* */
+ uint8_t moves; /* "move counter" */
+ uint8_t turns; /* "total turns" */
+ uint8_t action; /* "action selected" (0: none) */
+ uint8_t aggressive; /* "aggresive?" */
+ uint8_t latch; /* "dhfgh" s17: stage 1's move to stage 2 waits for a screen */
+ uint8_t pic_random; /* "pic random" */
+ uint8_t lure_to; /* "dhfgh" s11: the camera a lure pulls him to (0 none) */
+ uint8_t ran_past, hid; /* (ONCE a night: "run past", "hide") */
+ uint8_t window, head; /* "inwindow" and "head" shown */
+ uint8_t got_you; /* "got you": 0, 1 (the door lunge), 2 (from the right) */
+ uint8_t force_move, target; /* "force move", "target location" */
+ uint8_t walk_was; /* "action selected" > 1 the step before (the walk cue's edge) */
+ int16_t lure_t; /* "dhfgh" s12: frames until the lure's move */
+ /* the view, the monitor, the panel */
+ int16_t x; /* "scroll" X */
+ int8_t want; /* a screen asked for while looking away: 1 the monitor, 2 the panel, 0 none */
+ uint8_t viewing; /* "viewing": 0 down, 1 going up, 2 up */
+ uint8_t mon_s0; /* "flip it out" s0: 5 ready, 2..4 up */
+ uint8_t mon_anim; /* frames into the flip animation (out or in) */
+ uint8_t mon_down; /* the flip-in animation playing */
+ uint8_t panel; /* "screen two flipper" s0: 0 down, 1 rising, 2..3 up */
+ uint8_t panel_anim, panel_dropping;
+ uint8_t cursor; /* the panel's item: 1 audio, 2 camera, 3 ventilation, 4 reboot all, 5 exit */
+ uint8_t rebooting; /* "rebooting": 0, or the item */
+ uint8_t reboot_p; /* "cursor" s1 */
+ uint8_t cam; /* "C": the last camera (1..10) */
+ uint8_t vent; /* "D": the last vent camera (11..15) */
+ uint8_t vents_map; /* "toggle button" s0: the vent map shown */
+ uint8_t toggle_cd; /* "toggle button" s1 */
+ uint8_t closed; /* "what vent is closed" (0 none) */
+ uint8_t sealing; /* "going to seal" (0 none) */
+ int16_t seal_t; /* "seal vent button" s19 */
+ uint8_t play; /* "play counter": 1..7 (7: the lure is ready) */
+ uint8_t sdfg; /* frames left of the lure's sound wave on the map (0 none) */
+ uint8_t lure_cam; /* where it is */
+ /* the systems: 0 OK down to -10 (an error) */
+ int8_t audio, camera, vent_h;
+ uint8_t cam_wear; /* "camera text" s5: seconds of monitor up */
+ uint8_t idle; /* "ventilation text" s6: seconds with no screen up */
+ uint16_t vent_err; /* "ventilation text" s1: frames in error */
+ int16_t halluc_t; /* "ventilation text" s2 */
+ uint8_t red; /* "foreground" s0 */
+ int16_t alarm; /* "foreground" s3 */
+ uint8_t red_on; /* the office red this tick */
+ uint16_t halluc; /* cams 01..10 showing him (bit n-1) */
+ uint8_t hallucinating;
+ int16_t black; /* "blackout" s1: 0..255+ */
+ uint8_t black_up; /* "blackout" s0: 1 fading back */
+ int16_t black2; /* "blackout 2" (the Puppet) */
+ int16_t static_s4; /* "smallstatic" s4 */
+ int16_t static_s5; /* "smallstatic" s5 */
+ uint8_t static_s1;
+ uint8_t trail_n; /* the "trail"s: up to 3, their places and ages */
+ uint8_t trail_at[3], trail_age[3];
+ uint8_t nearby; /* "nearby" s0: 0, 1, 2 */
+ /* the phantoms */
+ uint8_t bb, mangle, puppet, chica, freddy; /* "BB", "mangle", "puppet", "chica", "golden freddy" */
+ uint8_t forced; /* the forced appearances done (bits: BB, Mangle, Marionette, Chica, Golden Freddy) */
+ uint8_t bb_pending, bb_shown;
+ int16_t bb_stare; /* "BBpeek" s3 */
+ int16_t mangle_stare; /* "mangle 2" s0 */
+ int16_t mangle_win; /* frames into Mangle's rise in the window (0 none) */
+ int16_t puppet_stare; /* "phantom head" s2 */
+ int16_t head_t; /* "phantom head" s1 */
+ int16_t head_x; /* the head's place (screen) */
+ uint8_t head_anim, head_out;
+ int16_t chica_stare; /* "chica 2" s0 (never reset) */
+ uint8_t chica_in; /* shown in the office */
+ uint8_t freddy_pending; /* "BBpeek" s1 */
+ uint8_t fwalk; /* walking */
+ int16_t fwalk_t; /* frames into his walk */
+ int16_t fwalk_stare; /* "fwalk" s0 */
+ uint8_t flunge; /* frames into his lunge + 1 (0 none) */
+ uint8_t fscare_ready; /* "BBpeek" s2 */
+ uint8_t foxy; /* "foxy" s0 = 1: shown */
+ uint8_t foxy_done;
+ uint8_t scare; /* the phantom scare playing (PH_*) */
+ int16_t scare_t; /* frames into it */
+ uint8_t cooldown; /* "scare cooldown" */
+ uint8_t frozen; /* "frozen" */
+ uint8_t frozen_was;
+ int16_t flash; /* frames of the white flash left */
+ int16_t breath; /* "scroll" s15 */
+ int16_t death_t; /* frames into Springtrap's lunge (0 none) */
+ uint8_t pad[2];
+ uint32_t frame; /* steps since the night began */
+} Night;
+
+typedef struct {
+ int scene;
+ float t; /* seconds in the scene */
+ uint32_t held, pressed;
+ bool running;
+ /* the save (Ini "freddy3"): the night reached, the stars, the extras */
+ uint8_t level, beatgame, beat6, goodend, keys_seen;
+ uint8_t cheats; /* bits: fast nights, radar, aggressive, no errors */
+ uint8_t menu, menu_n;
+ uint8_t paused, confirm, pause_item;
+ uint8_t after_keys, extras_sel, ending;
+ float repeat; /* a held key repeats */
+ const char *cap[4]; /* what is heard, as captions (the newest last) */
+ float cap_t[4];
+ Night n;
+} Game;
+
+enum { CH_FAST = 1, CH_RADAR = 2, CH_AGGRESSIVE = 4, CH_NOERRORS = 8 };
+
+extern Game g;
+
+/* game.c */
+void game_init(void);
+void game_step(uint32_t keys);
+void game_draw(void);
+uint32_t rnd(void);
+uint32_t rnd_n(uint32_t n); /* Random(n): 0..n-1 */
+void start_night(int night);
+void caption(const char *s);
+
+/* night.c */
+void night_begin(int night);
+void night_step(void);
+int feed_anim(int cam); /* the camera feed's animation for a camera (fnaf3_spec 7.5) */
+int screen_up(void); /* "viewing a screen" */
+int spring_cam(void); /* "mon in": 1..15, 0 elsewhere */
+
+/* view.c */
+void view_night(void);
+void view_scare(void);
+void view_captions(void);
+
+/* save.c */
+void save_restore_copy(void);
+void save_progress(void);
+void save_load(void);
+void save_resume(void); /* the night as it is (Home) */
+bool save_resume_load(void);
+#endif
diff --git a/games/fnaf3/src/gfx.c b/games/fnaf3/src/gfx.c
new file mode 100644
index 00000000..3a516a68
--- /dev/null
+++ b/games/fnaf3/src/gfx.c
@@ -0,0 +1,167 @@
+/* Drawing (gfx.h): a band of 16 rows at a time, then pushed to the screen. */
+#include "gfx.h"
+#include "res.h"
+
+uint16_t *gfx_band;
+int gfx_y0;
+
+void gfx_set_band_memory(uint16_t *m) { gfx_band = m; }
+
+void gfx_frame(void (*draw)(void)) {
+ for (gfx_y0 = 0; gfx_y0 < SCREEN_H; gfx_y0 += BAND_H) {
+ draw();
+ plat_push(0, gfx_y0, SCREEN_W, BAND_H, gfx_band);
+ }
+ gfx_y0 = 0;
+}
+
+uint16_t gfx_mix(uint16_t f, uint16_t b, int a) {
+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;
+ return (uint16_t)(y | y >> 16);
+}
+
+/* the rectangle's part in this band: rows r0 to r1 of the band, columns x0 to x1 */
+static bool clip(int x, int y, int w, int h, int *x0, int *x1, int *r0, int *r1) {
+ *x0 = x > 0 ? x : 0, *x1 = x + w < SCREEN_W ? x + w : SCREEN_W;
+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;
+ *r0 = y0 - gfx_y0, *r1 = y1 - gfx_y0;
+ return *x0 < *x1 && *r0 < *r1;
+}
+
+void gfx_fill(int x, int y, int w, int h, uint16_t c) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) *p = c;
+}
+
+void gfx_blend(int x, int y, int w, int h, uint16_t c, int a) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++)
+ *p = gfx_mix(c, *p, a);
+}
+
+void gfx_frame_rect(int x, int y, int w, int h, uint16_t c) {
+ gfx_fill(x, y, w, 1, c);
+ gfx_fill(x, y + h - 1, w, 1, c);
+ gfx_fill(x, y, 1, h, c);
+ gfx_fill(x + w - 1, y, 1, h, c);
+}
+
+/* static: grey noise, spread out for gfx_mix (made once) */
+static uint32_t noise[2048];
+
+void gfx_static(int x, int y, int w, int h, int a, uint32_t seed) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1) || a <= 0) return;
+ if (!noise[0]) {
+ uint32_t s = 0x2545F491u;
+ for (int i = 0; i < 2048; i++) {
+ s ^= s << 13, s ^= s >> 17, s ^= s << 5;
+ uint32_t g = (s >> 24) * 3 / 4;
+ uint32_t c = (g & 0xF8) << 8 | (g & 0xFC) << 3 | g >> 3;
+ noise[i] = ((c | c << 16) & 0x07E0F81F) | 1u << 31; /* (the top bit: made) */
+ }
+ }
+ for (int r = r0; r < r1; r++) {
+ uint32_t s = seed ^ (uint32_t)(gfx_y0 + r) * 0x9E3779B1u;
+ s ^= s >> 15, s *= 0x2C1B3C6Du, s ^= s >> 12;
+ /* a line now and then is brighter, as the game's static has */
+ uint32_t la = (s & 31) == 0 ? (uint32_t)a + 6 : (uint32_t)a;
+ if (la > 32) la = 32;
+ const uint32_t *nz = noise + (s >> 16 & 1023);
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) {
+ uint32_t n = *nz++ & 0x07E0F81F, b = (*p | (uint32_t)*p << 16) & 0x07E0F81F;
+ b = (b + ((n - b) * la >> 5)) & 0x07E0F81F;
+ *p = (uint16_t)(b | b >> 16);
+ }
+ }
+}
+
+void gfx_dim(int x, int y, int w, int h, int a) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) {
+ if (a <= 32) {
+ *p = gfx_mix(*p, BLACK, a);
+ } else { /* brighter: each channel times a / 32, up to 2 */
+ uint32_t v = *p, R = (v >> 11) * (uint32_t)a >> 5, G = (v >> 5 & 63) * (uint32_t)a >> 5, B = (v & 31) * (uint32_t)a >> 5;
+ *p = (uint16_t)((R > 31 ? 31 : R) << 11 | (G > 63 ? 63 : G) << 5 | (B > 31 ? 31 : B));
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ text */
+static const uint8_t *font_at(int font) {
+ const uint8_t *s = section(SEC_FONTS);
+ return s + rd32(s + 4 + 4 * font);
+}
+
+int gfx_line_h(int font) { return font_at(font)[0]; }
+
+/* 4-bit alpha rows (the first pixel in the low half of a byte) in colour c */
+static void alpha_rows(const uint8_t *rows, int w, int h, int x, int y, uint16_t c) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ int stride = (w + 1) >> 1;
+ for (int r = r0; r < r1; r++) {
+ const uint8_t *src = rows + (gfx_y0 + r - y) * stride;
+ uint16_t *d = gfx_band + r * SCREEN_W;
+ for (int px = x0; px < x1; px++) {
+ int i = px - x, a = src[i >> 1] >> ((i & 1) * 4) & 15;
+ if (a) d[px] = a == 15 ? c : gfx_mix(c, d[px], a * 2 + (a >> 3));
+ }
+ }
+}
+
+int gfx_text_n(int font, int x, int y, const char *s, int n, uint16_t c) {
+ const uint8_t *f = font_at(font);
+ int x0 = x;
+ bool here = y < gfx_y0 + BAND_H && y + f[0] > gfx_y0;
+ for (; *s && n-- > 0; s++) {
+ int ch = (uint8_t)*s;
+ if (ch < 32 || ch > 126) ch = '?';
+ const uint8_t *g = f + 4 + 12 * (ch - 32);
+ if (here && g[1]) alpha_rows(f + rd32(g + 8), g[1], g[2], x + (int8_t)g[3], y + (int8_t)g[4], c);
+ x += g[0];
+ }
+ return x - x0;
+}
+
+int gfx_text(int font, int x, int y, const char *s, uint16_t c) { return gfx_text_n(font, x, y, s, 1 << 30, c); }
+
+int gfx_text_wn(int font, const char *s, int n) {
+ const uint8_t *f = font_at(font);
+ int w = 0;
+ for (; *s && n-- > 0; s++) {
+ int ch = (uint8_t)*s;
+ if (ch < 32 || ch > 126) ch = '?';
+ w += f[4 + 12 * (ch - 32)];
+ }
+ return w;
+}
+int gfx_text_w(int font, const char *s) { return gfx_text_wn(font, s, 1 << 30); }
+
+void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c) { gfx_text(font, cx - gfx_text_w(font, s) / 2, y, s, c); }
+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c) { gfx_text(font, rx - gfx_text_w(font, s), y, s, c); }
+void gfx_text_s(int font, int x, int y, const char *s, uint16_t c) {
+ gfx_text(font, x + 1, y + 1, s, BLACK);
+ gfx_text(font, x, y, s, c);
+}
+
+/* ------------------------------------------------------------------ small pictures */
+static const uint8_t *img_at(int id) {
+ const uint8_t *s = section(SEC_IMGS);
+ return s + rd32(s + 4 + 4 * id);
+}
+int gfx_img_w(int id) { return (int)rd16(img_at(id)); }
+int gfx_img_h(int id) { return (int)rd16(img_at(id) + 2); }
+
+void gfx_img(int id, int x, int y, uint16_t c) {
+ const uint8_t *p = img_at(id);
+ alpha_rows(p + 8, (int)rd16(p), (int)rd16(p + 2), x, y, c);
+}
diff --git a/games/fnaf3/src/gfx.h b/games/fnaf3/src/gfx.h
new file mode 100644
index 00000000..7748354c
--- /dev/null
+++ b/games/fnaf3/src/gfx.h
@@ -0,0 +1,53 @@
+/* Five Nights at Freddy's 3: drawing, a band of 16 rows at a time.
+ *
+ * The screen is drawn in 15 bands of 320 x 16 pixels (one row of the pictures' 16 x 16 squares): for each
+ * band the scene's whole drawing function runs, everything clipped to the band, then the band is pushed.
+ * So the game needs no frame buffer (it would not fit in the RAM apps get), and a picture's squares are
+ * decoded once each, as the band they fall in is drawn. */
+#ifndef FNAF3_GFX_H
+#define FNAF3_GFX_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "plat.h"
+
+#define BAND_H 16
+#define RGB(c) (uint16_t)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+#define BLACK 0x0000
+
+extern uint16_t *gfx_band; /* SCREEN_W x BAND_H */
+extern int gfx_y0; /* the band's top row */
+void gfx_set_band_memory(uint16_t *m);
+/* draws the frame: draw() once for each band */
+void gfx_frame(void (*draw)(void));
+
+uint16_t gfx_mix(uint16_t f, uint16_t b, int a); /* f over b, a from 0 (b) to 32 (f) */
+void gfx_fill(int x, int y, int w, int h, uint16_t c);
+void gfx_blend(int x, int y, int w, int h, uint16_t c, int a);
+void gfx_frame_rect(int x, int y, int w, int h, uint16_t c);
+/* video noise over a rectangle: a of 32 of the way to grey static; seed changes it each frame */
+void gfx_static(int x, int y, int w, int h, int a, uint32_t seed);
+/* the rectangle a of 32 of the way to black, or brighter (a > 32 up to 64) */
+void gfx_dim(int x, int y, int w, int h, int a);
+
+/* text in data.bin's fonts (FONT_*); returns the width */
+int gfx_text(int font, int x, int y, const char *s, uint16_t c);
+int gfx_text_w(int font, const char *s);
+int gfx_text_n(int font, int x, int y, const char *s, int n, uint16_t c); /* the first n letters */
+int gfx_text_wn(int font, const char *s, int n);
+int gfx_line_h(int font);
+void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c); /* centred on cx */
+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c); /* ending at rx */
+/* with a 1-pixel dark shadow, for words over pictures */
+void gfx_text_s(int font, int x, int y, const char *s, uint16_t c);
+/* data.bin's small pictures (IMG_*): white (or grey) with alpha, in colour c */
+void gfx_img(int id, int x, int y, uint16_t c);
+int gfx_img_w(int id);
+int gfx_img_h(int id);
+
+/* pictures (pic.c): the whole of one at (x, y), or the part (sx, sy, w, h) of it */
+void pic_draw(int id, int x, int y);
+void pic_part(int id, int x, int y, int sx, int sy, int w, int h);
+int pic_w(int id); /* (in squares of 16 pixels, times 16) */
+int pic_h(int id);
+#endif
diff --git a/games/fnaf3/src/icon.png b/games/fnaf3/src/icon.png
new file mode 100644
index 00000000..08908334
Binary files /dev/null and b/games/fnaf3/src/icon.png differ
diff --git a/games/fnaf3/src/main.c b/games/fnaf3/src/main.c
new file mode 100644
index 00000000..38242450
--- /dev/null
+++ b/games/fnaf3/src/main.c
@@ -0,0 +1,46 @@
+/* Five Nights at Freddy's 3 for the NumWorks calculator.
+ *
+ * Inspired by Five Nights at Freddy's 3 by Scott Cawthon, not affiliated with him.
+ * Made by Mason Chen as part of NumPlay. */
+#include "game.h"
+#include "gfx.h"
+#include "plat.h"
+#include "res.h"
+
+#ifndef HOST
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "FNAF 3";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+extern const uint8_t fnaf3_data[];
+const uint8_t *fnaf3_bin;
+
+uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */
+uint32_t perf_updates __attribute__((used));
+
+int main(void) {
+ uint16_t band[SCREEN_W * BAND_H]; /* (here: on the stack, out of the RAM apps get) */
+ gfx_set_band_memory(band);
+ plat_begin();
+ fnaf3_bin = fnaf3_data;
+ game_init();
+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 50 a step, 60 steps a second */
+ while (g.running) {
+ /* the game's steps: drawn when caught up (at most 4 steps for a drawing) */
+ int n = 0;
+ uint32_t now = plat_millis() * 3;
+ while ((int32_t)(now - next) >= 0 && n < 4 && g.running) {
+ game_step(plat_keys());
+ perf_updates++;
+ next += 50;
+ n++;
+ }
+ if (!g.running) break;
+ if ((int32_t)(now - next) > 600) next = now; /* far behind: do not rush */
+ if (n) {
+ game_draw();
+ perf_frames++;
+ } else
+ plat_sleep(1);
+ }
+ return plat_end();
+}
+#endif
diff --git a/games/fnaf3/src/night.c b/games/fnaf3/src/night.c
new file mode 100644
index 00000000..5c16f609
--- /dev/null
+++ b/games/fnaf3/src/night.c
@@ -0,0 +1,574 @@
+/* Five Nights at Freddy's 3: a night, as the game's own events run it (gamesrc spec fnaf3_spec.md, from the
+ * Android build's Clickteam events), 60 steps a second. Within a step things happen in the events' order, so each
+ * reads what the ones before it just changed. The comments name the game's own counters and objects. */
+#include <string.h>
+#include "game.h"
+#include "data.h"
+#include "plat.h"
+
+#define N g.n
+static bool held(uint32_t k) { return (g.held & k) != 0; }
+static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }
+static int clampi(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; }
+
+/* Clickteam's "every N ms": its clock started with the night, so the ones with the same period fire together */
+static bool every(int ms) {
+ uint32_t t1 = N.frame * 50 / 3, t0 = (N.frame - 1) * 50 / 3;
+ return t1 / (uint32_t)ms != t0 / (uint32_t)ms;
+}
+
+int screen_up(void) { return N.viewing >= 2 || N.panel >= 2; }
+int spring_cam(void) { return N.loc >= L_CAM1 && N.loc <= L_VENT15 ? N.loc : 0; }
+static int you_in(void) { return N.vents_map ? N.vent : N.cam; }
+static bool err(int8_t h) { return h <= -10; }
+
+/* ------------------------------------------------------------ moving him */
+static void go(int loc) { N.loc = (uint8_t)loc, N.turns = 0, N.action = 0; }
+
+static void quiet_vent(void) { caption("A quiet sound in the vents"); }
+static void loud_vent(void) { caption("A loud bang in the vents"); }
+
+/* the room graph (fnaf3_spec 2.4): a move for the action chosen, if this place has one now */
+static void room_graph(void) {
+ int a = N.action;
+ if (a < 2) return;
+ bool up = screen_up();
+ switch (N.loc) {
+ case 10: if (a <= 3) go(9); else go(14), quiet_vent(); break;
+ case 9: if (a == 2) go(10); else if (a == 3) go(8); else go(11), quiet_vent(); break;
+ case 8: if (a == 2) go(9); else if (a == 3) go(7); else go(5); break;
+ case 7: if (a == 2) go(8); else if (a == 3) go(6); else go(12), quiet_vent(); break;
+ case 6: if (a == 2) go(7); else go(5); break;
+ case 5:
+ if (a == 2) go(6);
+ else if (a == 3) go(2);
+ else if (!N.pic_random) go(4);
+ else go(13), quiet_vent();
+ break;
+ case 2:
+ if (a == 2) go(5);
+ else if (a == 3) go(4);
+ else if (!N.pic_random) go(L_ST1);
+ else go(15), quiet_vent();
+ break;
+ case 4: if (a == 2) go(2); else go(3); break;
+ case 3: if (a == 2) go(4); else go(L_ST1); break;
+ case L_ST1: if (a >= 3) N.turns = 0, N.action = 0, N.latch = 1; break;
+ case L_ST2: if (a >= 3) go(L_ST3); break;
+ case L_ST3: if (up) go(a == 2 ? 1 : L_ST4); break;
+ case 1: if (up) go(a == 2 ? L_ST3 : L_ST4); break;
+ case L_ST4: /* the attack: from the door if the panel is up, from the right if the monitor is */
+ if (N.panel >= 2) go(L_GOT);
+ else if (N.viewing >= 2) go(L_GOT2);
+ break;
+ }
+}
+
+/* the vents (fnaf3_spec 2.4): out the way he came if it's sealed, else on to the office */
+static void vent_moves(void) {
+ static const uint8_t back[5] = {9, 7, 5, 10, 2}, on[5] = {L_ST3, L_ST3, L_ST1, L_GOT2, L_GOT2};
+ if (N.loc < L_VENT11 || N.loc > L_VENT15 || N.action < 2) return;
+ int i = N.loc - L_VENT11;
+ if (N.closed == N.loc) go(back[i]), quiet_vent();
+ else go(on[i]), loud_vent();
+}
+
+/* a step at the blackout's darkest (fnaf3_spec 2.7): he comes one place closer */
+static void blackout_peak(void) {
+ bool moved = true;
+ if (N.loc == L_ST1) go(L_ST2);
+ else if (N.loc == L_ST2) go(L_ST3);
+ else if (N.loc == L_ST3 || N.loc == 1) go(L_ST4);
+ else if (N.loc == L_ST4) go(L_GOT);
+ else if (N.loc == L_GOT2 && !screen_up() && !N.got_you) N.got_you = 2, N.x = XMAX;
+ else moved = false;
+ if (moved) N.black = 249, N.black_up = 1;
+ if (N.head_out && N.head_t <= 0) N.head_out = 0; /* (the Puppet's head, sliding off, gone at a peak) */
+}
+
+/* ------------------------------------------------------------ the screens */
+static void monitor_down(void) {
+ if (N.viewing == 0 && !N.mon_down) return;
+ N.viewing = 0, N.mon_s0 = 0, N.mon_down = 1, N.mon_anim = 0;
+ N.sealing = 0, N.sdfg = 0; /* (lowering it cancels the sealing) */
+}
+static void panel_down(void) {
+ if (N.panel && !N.panel_dropping) N.panel_dropping = 1, N.panel_anim = 0;
+}
+
+static void select_cam(int id) {
+ if (id >= L_VENT11) N.vent = (uint8_t)id;
+ else N.cam = (uint8_t)id;
+ N.static_s4 = 250, N.bb_shown = 0, N.bb_stare = 0;
+}
+
+/* the map's buttons, for the arrows: the nearest one that way */
+static const int16_t BTN[16][2] = {{0, 0},
+ {BTN01_X, BTN01_Y}, {BTN02_X, BTN02_Y}, {BTN03_X, BTN03_Y}, {BTN04_X, BTN04_Y}, {BTN05_X, BTN05_Y},
+ {BTN06_X, BTN06_Y}, {BTN07_X, BTN07_Y}, {BTN08_X, BTN08_Y}, {BTN09_X, BTN09_Y}, {BTN10_X, BTN10_Y},
+ {BTN11_X, BTN11_Y}, {BTN12_X, BTN12_Y}, {BTN13_X, BTN13_Y}, {BTN14_X, BTN14_Y}, {BTN15_X, BTN15_Y}};
+static int nearest(int from, int dx, int dy) {
+ int lo = N.vents_map ? 11 : 1, hi = N.vents_map ? 15 : 10, best = from, bd = 1 << 30;
+ for (int i = lo; i <= hi; i++) {
+ int ex = BTN[i][0] - BTN[from][0], ey = BTN[i][1] - BTN[from][1];
+ int along = ex * dx + ey * dy, side = ex * dy - ey * dx;
+ if (i == from || along <= 0) continue;
+ int d = along * along + 3 * side * side;
+ if (d < bd) bd = d, best = i;
+ }
+ return best;
+}
+
+/* the lure's adjacency (fnaf3_spec 3): a lure at camera c pulls him from these places */
+static bool lure_pulls(int c, int loc) {
+ static const uint8_t from[11][4] = {{0}, {L_ST4}, {L_ST1, 3, 4, 5}, {2, 4}, {2, 3}, {2, 6, 7, 8}, {5, 7}, {6, 8},
+ {7, 5, 9}, {8, 10}, {9}};
+ for (int i = 0; i < 4; i++)
+ if (from[c][i] && from[c][i] == loc) return true;
+ return false;
+}
+
+static void play_audio(void) {
+ /* [214]: the monitor up, no audio error, the counter full, the camera map */
+ if (N.viewing < 2 || err(N.audio) || N.play < 7 || N.vents_map) return;
+ N.play = 1; /* (0, held at its minimum 1) */
+ N.audio = (int8_t)clampi(N.audio - N.ai, -10, 0);
+ N.sdfg = 133, N.lure_cam = N.cam;
+ caption("BB laughs on the camera");
+ if (rnd_n(7) + 1 == 1) return; /* [220-221]: one time in 7 he doesn't come */
+ if (lure_pulls(N.cam, N.loc) && !N.lure_to) N.lure_to = N.cam, N.lure_t = (int16_t)rnd_n(100), N.static_s4 = 200;
+}
+
+static void input(void) {
+ bool locked = N.got_you || N.frozen;
+ /* the view: 20 px a step while looking around [7-12] */
+ if (!locked && N.viewing == 0 && !N.mon_down && N.panel == 0) {
+ int dir = held(K_LEFT | K_DIGIT(4)) ? -1 : held(K_RIGHT | K_DIGIT(6)) ? 1 : 0;
+ if (dir) N.want = 0;
+ if (pressed(K_OK | K_EXE | K_UP | K_DIGIT(8))) N.want = 1;
+ if (pressed(K_DOWN | K_DIGIT(2))) N.want = 2;
+ if (N.want == 1 && N.x < 800) dir = 1;
+ if (N.want == 2 && N.x > 400) dir = -1;
+ if (dir < 0 && N.x > 400) N.x = (int16_t)(N.x - 20);
+ if (dir > 0 && N.x < 800) N.x = (int16_t)(N.x + 20);
+ /* the monitor's button at the right end [14], the panel's at the left [32] */
+ if (N.want == 1 && N.x >= 800 && N.mon_s0 == 5 && !N.black2)
+ N.viewing = 1, N.mon_anim = 0, N.want = 0;
+ if (N.want == 2 && N.x <= 400 && !N.black2) N.panel = 1, N.panel_anim = 0, N.want = 0;
+ return;
+ }
+ if (N.viewing >= 2 && N.mon_s0 == 4) {
+ if (pressed(K_EXE)) {
+ monitor_down();
+ return;
+ }
+ if (pressed(K_DEL) && !N.toggle_cd) { /* Map Toggle [373-424] */
+ N.vents_map ^= 1, N.toggle_cd = 20, N.sdfg = 0, N.sealing = 0;
+ N.static_s4 = 250, N.bb_shown = 0, N.bb_stare = 0;
+ }
+ int now = you_in(), to = 0;
+ if (pressed(K_LEFT)) to = nearest(now, -1, 0);
+ if (pressed(K_RIGHT)) to = nearest(now, 1, 0);
+ if (pressed(K_UP)) to = nearest(now, 0, -1);
+ if (pressed(K_DOWN)) to = nearest(now, 0, 1);
+ for (int d = 0; d <= 9; d++)
+ if (pressed(K_DIGIT(d))) {
+ int id = d == 0 ? 10 : d;
+ to = N.vents_map ? (id <= 5 ? 10 + id : 0) : id;
+ }
+ if (to && to != now && !(N.vents_map && N.sealing)) select_cam(to);
+ if (pressed(K_OK)) {
+ if (!N.vents_map) play_audio();
+ else N.sealing = N.vent, N.seal_t = (int16_t)(50 + rnd_n(50)); /* (the double click on a vent camera) */
+ }
+ return;
+ }
+ if (N.panel == 3 && !N.panel_dropping) {
+ if (!N.rebooting) {
+ if (pressed(K_UP | K_DIGIT(8))) N.cursor = (uint8_t)(N.cursor == 1 ? 5 : N.cursor - 1);
+ if (pressed(K_DOWN | K_DIGIT(2))) N.cursor = (uint8_t)(N.cursor == 5 ? 1 : N.cursor + 1);
+ if (pressed(K_OK)) {
+ if (N.cursor == 5) panel_down();
+ else N.rebooting = N.cursor, N.reboot_p = 0;
+ }
+ if (pressed(K_EXE)) panel_down();
+ }
+ }
+}
+
+/* the monitor's and the panel's animations (flip out 6 pictures, flip in 4, the panel up 5 and down 4, at 50) */
+static void screens(void) {
+ if (N.viewing == 1 && ++N.mon_anim >= 12) N.viewing = 2, N.mon_s0 = 4, N.mon_anim = 0;
+ if (N.mon_down && ++N.mon_anim >= 8) N.mon_down = 0, N.mon_s0 = 5, N.mon_anim = 0;
+ if (N.panel == 1 && ++N.panel_anim >= 10) N.panel = 3, N.panel_anim = 0;
+ if (N.panel_dropping && ++N.panel_anim >= 8) N.panel = 0, N.panel_dropping = 0, N.panel_anim = 0;
+ if (N.toggle_cd) N.toggle_cd--;
+}
+
+/* ------------------------------------------------------------ the camera feed (fnaf3_spec 7.5) */
+int feed_anim(int c) {
+ static const uint8_t empty[16] = {0, 17, 14, 15, 16, 21, 12, 13, 23, 24, 25, 45, 46, 47, 48, 49};
+ static const uint8_t him[16] = {0, 30, 43, 28, 29, 27, 26, 31, 32, 33, 34, 50, 51, 52, 53, 54};
+ bool here = spring_cam() == c, h = c <= 10 && (N.halluc >> (c - 1) & 1);
+ int a = empty[c];
+ if (c == 2 && here) a = N.pic_random ? 43 : 35;
+ else if (c == 2 && h) a = 43;
+ else if (here || h) a = him[c];
+ if (c == 4 && N.mangle == 2) a = 55;
+ if (c == 8 && N.puppet == 2) a = 56;
+ if (c == 7 && N.chica == 2) a = 57;
+ return a;
+}
+
+/* ------------------------------------------------------------ a night */
+void night_begin(int night) {
+ memset(&N, 0, sizeof N);
+ N.night = (uint8_t)night;
+ N.x = 512, N.mon_s0 = 5, N.cursor = 1;
+ N.cam = 2, N.vent = 11, N.play = 1;
+ N.pic_random = (uint8_t)rnd_n(2);
+ static const uint8_t start[5] = {10, 9, 8, 7, 6};
+ N.loc = night == 1 ? L_OFF : start[rnd_n(5)];
+ if (night == 1) { /* [612]: the systems start a little worn */
+ N.audio = (int8_t)(-3 - (int)rnd_n(4));
+ N.camera = (int8_t)(-3 - (int)rnd_n(4));
+ N.vent_h = (int8_t)(-2 - (int)rnd_n(4));
+ }
+ /* [537-539]: the phantoms that can come this night */
+ N.bb = N.mangle = night >= 2, N.freddy = N.chica = night >= 3, N.puppet = night >= 4;
+}
+
+static void white_flash(void) { /* [547-550] */
+ N.vent_h = -10, N.vent_err = 2000, N.black_up = 1, N.black = 255;
+ N.flash = 51, N.breath = 500, N.scare = PH_NONE, N.scare_t = 0;
+}
+
+static void start_scare(int who) {
+ N.scare = (uint8_t)who, N.scare_t = 0, N.frozen = 1, N.cooldown = 10;
+ monitor_down(), panel_down();
+}
+
+static void phantoms(void) {
+ bool noon = N.hour == 0;
+ int cam = you_in();
+ bool mon = N.viewing >= 2;
+ /* forced appearances: once, and only while that phantom is still to come [630-634] */
+ if (!noon) {
+ if (!N.bb) N.forced |= 1;
+ if (N.mangle != 1) N.forced |= 2;
+ if (N.puppet != 1) N.forced |= 4;
+ if (N.chica != 1) N.forced |= 8;
+ if (N.freddy != 1) N.forced |= 16;
+ }
+ /* BB [511-512, 521-529, 552-553] */
+ if (every(20000) && N.bb == 1 && N.viewing <= 1 && rnd_n(10) + 1 <= N.ai && !noon) N.bb_pending = 1;
+ if (!(N.forced & 1) && N.bb == 1 && N.viewing <= 1 && N.hour == 3) N.bb_pending = 1, N.forced |= 1;
+ if (N.bb_pending && mon && (cam == 1 || cam == 7 || cam == 9 || cam == 10)) N.bb_pending = 0, N.bb_shown = 1;
+ if (!mon) N.bb_shown = 0, N.bb_stare = 0;
+ if (N.bb_shown && ++N.bb_stare > N.tlimit) {
+ N.bb_shown = 0, N.bb = 0;
+ monitor_down();
+ start_scare(PH_BB);
+ caption("BB screams");
+ }
+ /* Mangle [513-514, 557, 560-568] */
+ if (every(20000) && cam != 4 && N.mangle == 1 && rnd_n(7) + 1 <= N.ai && !noon) N.mangle = 2;
+ if (!(N.forced & 2) && N.mangle == 1 && N.hour == 5 && cam != 4 && mon) N.mangle = 2, N.forced |= 2;
+ if (N.mangle == 2 && mon && cam == 4) N.mangle_stare++;
+ if (!mon) {
+ N.mangle_stare = 0;
+ if (N.mangle == 2) N.mangle = 1;
+ }
+ if (N.mangle == 2 && N.mangle_stare >= N.tlimit) {
+ N.mangle = 0, N.mangle_win = 1;
+ monitor_down();
+ N.audio = -10;
+ caption("Mangle's radio garbles");
+ }
+ if (N.mangle_win) { /* up 100 px at 5 (160 frames), half a second, down at 50 (16 frames) */
+ if (++N.mangle_win > 160 + 30 + 16) N.mangle_win = 0, N.breath = 500;
+ else if (N.mangle_win % 60 == 0) caption("Mangle's radio garbles");
+ }
+ /* the Puppet [515-516, 558, 563, 569, 571-584] */
+ if (every(20000) && cam != 8 && N.puppet == 1 && rnd_n(10) + 1 <= N.ai && !noon) N.puppet = 2;
+ if (!(N.forced & 4) && N.puppet == 1 && N.hour == 5 && cam != 8) N.puppet = 2, N.forced |= 4;
+ if (N.puppet == 2 && mon && cam == 8) N.puppet_stare++;
+ if (!mon) {
+ N.puppet_stare = 0;
+ if (N.puppet == 2) N.puppet = 1;
+ }
+ if (N.puppet == 2 && N.puppet_stare >= N.tlimit && !N.cooldown) {
+ N.puppet = 0, N.head_t = 500, N.head_out = 1, N.head_x = 160;
+ monitor_down(), panel_down();
+ caption("A mask moves over you");
+ }
+ if (N.head_t > 0) {
+ N.head_t--, N.black2 = 100;
+ if (N.black > 210) N.head_x += N.head_x < 160 ? (160 - N.head_x < 13 ? 160 - N.head_x : 13) : 0;
+ if (every(250)) N.head_anim = (uint8_t)rnd_n(3);
+ } else if (N.head_out) {
+ N.head_x = (int16_t)(N.head_x - 8);
+ if (N.head_x <= -230) N.head_out = 0;
+ }
+ if (!N.head_t && N.black2 > 0) N.black2--;
+ /* Chica [517-518, 559, 570, 585-590, 592] */
+ if (every(20000) && N.chica == 1 && cam != 7 && rnd_n(10) + 1 <= N.ai && !noon) N.chica = 2;
+ if (!(N.forced & 8) && N.chica == 1 && N.hour == 5 && cam != 7) N.chica = 2, N.forced |= 8;
+ if (N.chica == 2 && mon && cam == 7) N.chica_stare++;
+ if (!mon && N.chica == 2) N.chica = 1;
+ if (N.chica == 1 && N.chica_stare >= N.tlimit && !N.cooldown && !N.chica_in) N.chica_in = 1, N.chica = 3;
+ if (N.chica_in == 1) {
+ if (N.x > 512) N.x = (int16_t)(N.x - 30 < 512 ? 512 : N.x - 30);
+ if (N.x < 600) N.chica_in = 2, start_scare(PH_CHICA), caption("Chica screams");
+ }
+ /* Phantom Freddy [519-520, 541-546, 551, 530, 554, 556] */
+ if (every(60000) && N.freddy == 1 && rnd_n(12) + 1 <= N.ai && !noon) N.freddy_pending = 1;
+ if (!(N.forced & 16) && N.freddy == 1 && N.hour == 4) N.freddy_pending = 1, N.forced |= 16;
+ if (N.freddy_pending && !N.fwalk && !N.flunge && N.freddy == 1 && every(1000) && rnd_n(2)) N.fwalk = 1, N.fwalk_t = 0;
+ if (N.fwalk) {
+ if (++N.fwalk_t >= 1955) N.fwalk = 0, N.freddy_pending = 0; /* (733 px at 3/8 px a frame: past, safe) */
+ if (screen_up()) N.fwalk_stare = 0;
+ else N.fwalk_stare++;
+ if (N.fwalk && N.fwalk_stare >= 3 * N.tlimit && !N.cooldown) N.flunge = 1;
+ }
+ if (N.flunge && ++N.flunge > 28) N.flunge = 0, N.fwalk = 0, N.fscare_ready = 1;
+ if (N.fscare_ready && every(1000) && rnd_n(2) && !N.cooldown) {
+ N.fscare_ready = 0, N.freddy_pending = 0;
+ start_scare(PH_FREDDY);
+ caption("Phantom Freddy screams");
+ }
+}
+
+static void foxy_step(void) { /* [709-713, 588, 602, 606] */
+ static const uint16_t chance[7] = {0, 0, 1000, 100, 50, 10, 10};
+ if (N.night >= 2 && N.panel == 1 && N.panel_anim == 1 && N.frame > 600) N.foxy = rnd_n(chance[N.night]) == 0;
+ if (N.foxy && !N.foxy_done && N.x < 568 && !N.cooldown && !screen_up() && N.panel == 0) {
+ N.foxy_done = 1, N.foxy = 0;
+ start_scare(PH_FOXY);
+ caption("Foxy screams");
+ }
+}
+
+/* the phantoms' scares, played: their pictures, then the white flash */
+static void scare_step(void) {
+ if (!N.scare) return;
+ int len = N.scare == PH_BB ? 30 + 17 : N.scare == PH_CHICA ? 20 : N.scare == PH_FOXY ? 23 : 17;
+ if (++N.scare_t >= len) {
+ if (N.scare == PH_CHICA) N.chica = 0, N.chica_in = 0;
+ if (N.scare == PH_FREDDY) N.freddy = 0;
+ white_flash();
+ N.frozen = 0;
+ }
+}
+
+static void ventilation(void) {
+ if (err(N.vent_h)) N.vent_err++;
+ else N.vent_err = 0;
+ int ai = N.ai;
+ bool was = N.hallucinating;
+ if (N.vent_err > 1000 - 100 * ai) N.halluc_t = (int16_t)(200 + rnd_n(200));
+ if (N.halluc_t > 0) {
+ N.red = 50, N.hallucinating = 1;
+ if (every(250)) {
+ N.red_on ^= 1;
+ if (N.red_on && N.alarm > 0) caption("The ventilation alarm");
+ }
+ N.halluc_t = (int16_t)(N.halluc_t - 2);
+ } else {
+ N.hallucinating = 0;
+ if (N.red) N.red--;
+ else N.red_on = 0;
+ }
+ if (N.halluc_t > 0 && N.alarm == 0 && !was) N.alarm = 400;
+ if (N.alarm > 0) N.alarm--;
+ if (N.hallucinating) {
+ N.halluc = 0;
+ for (int c = 0; c < 10; c++)
+ if (rnd_n(3) == 1) N.halluc |= (uint16_t)(1 << c);
+ } else {
+ N.halluc = 0;
+ }
+ if (N.hallucinating != was) N.static_s4 = (int16_t)(was ? 200 + rnd_n(100) : 200);
+ /* the blackout [344-353] */
+ bool dark = N.vent_err > 2000 - 200 * ai;
+ if (dark) {
+ if (!N.black_up) {
+ if (++N.black > 255) N.black_up = 1;
+ } else if (--N.black <= 100) N.black_up = 0;
+ }
+ if (N.black2 > 0) {
+ if (!N.black_up) {
+ if ((N.black += 5) > 255) N.black_up = 1;
+ } else if ((N.black -= 5) <= 150) N.black_up = 0;
+ }
+ if (!dark && !N.black2 && N.black > 0) N.black_up = 0, N.black--;
+ if (N.black > 250) blackout_peak();
+}
+
+static void wear(void) {
+ int ai = N.ai;
+ if (N.viewing >= 2 && every(1000) && ++N.cam_wear >= 12) N.cam_wear = 0, N.camera = (int8_t)clampi(N.camera - ai, -10, 0);
+ static const uint8_t vent_s[8] = {0, 0, 12, 10, 9, 8, 0, 0};
+ if (ai < 8 && vent_s[ai] && every(vent_s[ai] * 1000)) N.vent_h = (int8_t)clampi(N.vent_h - 1, -10, 0);
+ if (every(1000)) {
+ if (screen_up()) N.idle = 0;
+ else if (N.idle < 255) N.idle++;
+ if (N.idle > 10 && N.night != 1) N.vent_h = (int8_t)clampi(N.vent_h - 1, -10, 0);
+ }
+ if (screen_up()) N.idle = 0;
+ if (g.cheats & CH_NOERRORS) N.audio = N.camera = N.vent_h = 0;
+}
+
+static void reboot(void) {
+ if (!N.rebooting) return;
+ if (every(N.rebooting == 4 ? 2000 : 1000)) N.reboot_p = (uint8_t)(N.reboot_p + 1 + rnd_n(2));
+ if (N.reboot_p >= 10) {
+ if (N.rebooting == 1 || N.rebooting == 4) N.audio = 0;
+ if (N.rebooting == 2 || N.rebooting == 4) N.camera = 0;
+ if (N.rebooting == 3 || N.rebooting == 4) N.vent_h = 0;
+ if (N.rebooting == 4) N.cam_wear = 0;
+ N.rebooting = 0, N.reboot_p = 0;
+ }
+}
+
+static void statics(void) {
+ if (every(500)) N.static_s1 = (uint8_t)(rnd_n(2) * 5);
+ if (every(360) && rnd_n(5) == 0) N.static_s4 = 100;
+ if (every(1000) && rnd_n(10) == 0) N.static_s4 = 200;
+ if (N.static_s5 > 0) {
+ N.static_s5--;
+ if (you_in() == spring_cam()) N.static_s4 = 200;
+ for (int i = 0; i < N.trail_n; i++)
+ if (N.trail_at[i] == you_in()) N.static_s4 = 250;
+ }
+ N.static_s4 = (int16_t)(N.static_s4 > 10 ? N.static_s4 - 12 : N.static_s4 - 2);
+ if (N.static_s4 < 0) N.static_s4 = 0;
+ /* the trail [182-184]: where he was, for a second or two */
+ if (every(3000) && N.trail_n < 3 && spring_cam()) N.trail_at[N.trail_n] = (uint8_t)spring_cam(), N.trail_age[N.trail_n++] = 0;
+ if (every(1000)) {
+ for (int i = 0; i < N.trail_n;) {
+ if (++N.trail_age[i] >= 2) {
+ N.trail_n--;
+ N.trail_at[i] = N.trail_at[N.trail_n], N.trail_age[i] = N.trail_age[N.trail_n];
+ } else {
+ i++;
+ }
+ }
+ }
+}
+
+static void office_visuals(void) {
+ if (N.loc == L_ST1 && screen_up()) N.window = 1;
+ if (N.loc != L_ST1) N.window = 0;
+ if (N.loc == L_ST2 && !N.ran_past) N.ran_past = 1;
+ else if (N.ran_past && N.ran_past < 255 && ++N.ran_past > 31) N.ran_past = 255;
+ if (N.loc == L_ST3 && N.panel_dropping && !N.hid) N.hid = 1;
+ else if (N.hid && N.hid < 255 && ++N.hid > 27) N.hid = 255;
+ if (N.loc == L_ST4 && screen_up()) N.head = 1;
+ if (N.loc != L_ST4) N.head = 0;
+ if (N.latch && screen_up()) N.latch = 0, go(L_ST2); /* [190] */
+}
+
+static void nearby(void) {
+ int l = N.loc, v = 0;
+ if (l == 1 || l == 2 || (l >= L_ST1 && l <= L_GOT2)) v = 2;
+ else if (l == 3 || l == 4 || l == 5 || l == 13) v = 1;
+ if ((N.fwalk || N.chica_in) && v < 1) v = 1;
+ N.nearby = (uint8_t)v;
+}
+
+static void attack(void) {
+ if (N.loc == L_GOT && !N.got_you) N.got_you = 1;
+ if (N.loc == L_GOT2 && !N.got_you) {
+ if (N.panel >= 2) go(L_GOT);
+ else if (N.viewing >= 2 && every(1000) && rnd_n(2)) N.got_you = 2;
+ }
+ if (!N.got_you) return;
+ if (N.got_you == 2) monitor_down();
+ panel_down();
+ N.bb_shown = 0, N.chica_in = 0, N.fwalk = 0, N.foxy = 0, N.head_t = 0, N.head_out = 0, N.mangle_win = 0;
+ if (N.got_you == 1 && N.x > 512) N.x = (int16_t)(N.x - 20 < 512 ? 512 : N.x - 20);
+ if (++N.death_t == 1) caption("Springtrap screams");
+ if (N.death_t >= 37 + 4) { /* the lunge (11 pictures at 30), then 5 frames: the static */
+ g.scene = SC_STATIC, g.t = 0;
+ }
+}
+
+void night_step(void) {
+ N.frame++;
+ input();
+ screens();
+ /* Springtrap's move [135-140] */
+ if (N.night > 1) {
+ if (every(15000)) {
+ N.aggressive = 0;
+ if (rnd_n(5) < N.ai) N.aggressive = 1; /* [505-506] */
+ }
+ if (every(1000)) {
+ N.moves = (uint8_t)(N.moves + ((g.cheats & CH_AGGRESSIVE) ? 2 : 1));
+ if ((int)N.moves > (10 - N.ai - N.aggressive) + (int)rnd_n(15) - N.turns) {
+ N.moves = 0;
+ N.action = (uint8_t)(rnd_n(3 + N.aggressive) + 1);
+ if (N.action == 1) N.action = 0, N.turns++;
+ }
+ }
+ /* the walk cue [141]: on the step the action turns > 1 */
+ bool walk = N.action > 1;
+ if (walk && !N.walk_was && !N.window && !N.head)
+ N.static_s5 = (int16_t)(50 + rnd_n(100)), N.static_s4 = (int16_t)(N.static_s4 + 100), caption("Footsteps");
+ N.walk_was = walk;
+ room_graph();
+ office_visuals();
+ /* the lure's move [245-255] */
+ if (N.lure_to && --N.lure_t <= 0) {
+ N.loc = N.lure_to, N.lure_to = 0, N.static_s5 = (int16_t)(50 + rnd_n(100)), N.moves = 0;
+ }
+ }
+ if (N.sdfg) N.sdfg--;
+ if (every(1500) && N.play < 7) N.play++;
+ reboot();
+ wear();
+ ventilation();
+ vent_moves();
+ /* sealing [436-439] */
+ if (N.sealing && !N.vents_map) N.sealing = 0;
+ if (N.sealing && --N.seal_t <= 0) N.closed = N.sealing, N.sealing = 0;
+ /* the hours [485-491] */
+ int len = (N.night == 1 ? 30000 : 60000) / ((g.cheats & CH_FAST) ? 2 : 1);
+ if (every(len)) N.hour++;
+ if (N.hour >= 6) {
+ g.scene = SC_SIX, g.t = 0;
+ return;
+ }
+ static const uint8_t AI[7] = {0, 0, 2, 3, 4, 5, 7}, TL[7] = {0, 100, 50, 40, 30, 20, 20};
+ N.ai = AI[N.night > 6 ? 6 : N.night], N.tlimit = TL[N.night > 6 ? 6 : N.night];
+ attack();
+ if (g.scene != SC_NIGHT) return;
+ phantoms();
+ foxy_step();
+ scare_step();
+ if (every(1000) && N.cooldown) N.cooldown--;
+ if (N.flash > 0) N.flash--;
+ if (N.breath > 0 && every(30)) N.breath--;
+ /* the forced move after a phantom (nights 3 on) [719-726, 753-755] */
+ if (N.frozen && !N.frozen_was && N.night >= 3) N.force_move = 1, N.target = (uint8_t)(rnd_n(3) + 1);
+ N.frozen_was = N.frozen;
+ if (N.force_move == 1) {
+ if (N.loc >= 6 && N.loc <= 10) N.force_move = 2;
+ else if (N.loc == 5) N.loc = 2, N.force_move = 0;
+ else if (N.loc == 2) N.loc = L_ST1, N.force_move = 0;
+ }
+ if (N.force_move == 2) {
+ N.loc = N.target == 1 ? 5 : N.target == 2 ? 10 : 4;
+ if (N.target != 1) N.moves = 0;
+ N.force_move = 0;
+ }
+ /* pic random [330]: rolled again every 10 s while you look elsewhere */
+ if (every(10000) && you_in() != spring_cam()) N.pic_random = (uint8_t)rnd_n(2);
+ /* aggressive [288, 595-596, 730, 735, 743] */
+ if (err(N.vent_h) || N.frozen || N.breath > 0 || N.idle > 10 || N.hour >= 3) N.aggressive = 1;
+ if (N.hour == 0) N.aggressive = 0;
+ statics();
+ nearby();
+ if (N.night == 1) N.loc = L_OFF;
+}
diff --git a/games/fnaf3/src/pic.c b/games/fnaf3/src/pic.c
new file mode 100644
index 00000000..1e2a0521
--- /dev/null
+++ b/games/fnaf3/src/pic.c
@@ -0,0 +1,264 @@
+/* The pictures (tools/codec.py): 16 x 16 squares coded as JPEG codes them, decoded as the bands are drawn.
+ *
+ * A square: four 8 x 8 blocks of Y, one of Cb and one of Cr (at half resolution), each a Huffman-coded
+ * list of quantized cosine coefficients. The inverse transform is libjpeg's "ifast" one (the AAN algorithm,
+ * its scales folded into the quantization tables by tools/pack.py), with a shortcut for the many blocks
+ * that are one flat colour in these dark rooms. Colours are dithered on the way to 16 bits, or the dark
+ * gradients would band. */
+#include "gfx.h"
+#include "res.h"
+
+typedef struct {
+ const uint16_t *lut; /* 9 bits ahead: length << 8 | symbol, 0 when the code is longer */
+ const int32_t *maxcode; /* JPEG's, by length (1 to 17) */
+ const int32_t *valoff;
+ const uint8_t *vals;
+} Huff;
+
+static const uint8_t zigzag[64 + 16] = {
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,
+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 /* (a corrupt run lands here) */
+};
+
+static Huff huff_tab(int k) {
+ const uint8_t *p = section(SEC_HUFF) + 1424 * k;
+ return (Huff){(const uint16_t *)(const void *)p, (const int32_t *)(const void *)(p + 1024),
+ (const int32_t *)(const void *)(p + 1096), p + 1168};
+}
+
+/* ------------------------------------------------------------------ bits */
+typedef struct {
+ const uint8_t *p;
+ uint32_t buf; /* the next bits, from the top */
+ int n;
+} Bits;
+
+static inline void fill(Bits *b) {
+ while (b->n <= 24) {
+ b->buf |= (uint32_t)*b->p++ << (24 - b->n);
+ b->n += 8;
+ }
+}
+static inline uint32_t take(Bits *b, int k) {
+ uint32_t v = b->buf >> (32 - k);
+ b->buf <<= k;
+ b->n -= k;
+ return v;
+}
+static inline int decode(Bits *b, const Huff *h) {
+ fill(b);
+ uint32_t e = h->lut[b->buf >> 23];
+ if (e) {
+ b->buf <<= e >> 8;
+ b->n -= (int)(e >> 8);
+ return (int)(e & 0xFF);
+ }
+ for (int l = 10; l <= 16; l++) {
+ int32_t code = (int32_t)(b->buf >> (32 - l));
+ if (code <= h->maxcode[l]) {
+ b->buf <<= l;
+ b->n -= l;
+ return h->vals[(code + h->valoff[l]) & 0xFF];
+ }
+ }
+ b->buf <<= 16; /* (corrupt: give up on this block) */
+ b->n -= 16;
+ return 0;
+}
+/* JPEG's extension of s bits to a signed value */
+static inline int value(Bits *b, int s) {
+ if (!s) return 0;
+ fill(b);
+ int v = (int)take(b, s);
+ return v < 1 << (s - 1) ? v - (1 << s) + 1 : v;
+}
+
+/* ------------------------------------------------------------------ one block */
+#define CONST_BITS 8
+#define MUL(v, c) (((v) * (c)) >> CONST_BITS)
+#define FIX_1_082392200 277
+#define FIX_1_414213562 362
+#define FIX_1_847759065 473
+#define FIX_2_613125930 669
+
+static inline uint8_t clamp8(int v) { return (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v); }
+
+/* decodes a block into out (8 x 8 bytes, stride 8); *pred: the DC before it */
+static void block(Bits *b, const Huff *dc, const Huff *ac, int *pred, const uint16_t *q, uint8_t *out) {
+ int32_t c[64];
+ uint64_t cols = 0; /* which coefficients are not 0, a bit each */
+ int s = decode(b, dc);
+ *pred += value(b, s);
+ int dcv = *pred * q[0];
+ for (int k = 1; k < 64;) {
+ int rs = decode(b, ac), r = rs >> 4;
+ s = rs & 15;
+ if (!s) {
+ if (r != 15) break;
+ k += 16;
+ continue;
+ }
+ k += r;
+ if (k > 63) break;
+ int z = zigzag[k++];
+ cols |= (uint64_t)1 << z;
+ c[z] = value(b, s) * q[z];
+ }
+ if (!cols) { /* one colour */
+ uint8_t v = clamp8(((dcv + 16) >> 5) + 128);
+ uint32_t w = v * 0x01010101u;
+ for (int i = 0; i < 16; i++) ((uint32_t *)(void *)out)[i] = w;
+ return;
+ }
+ c[0] = dcv;
+ int32_t ws[64];
+ for (int x = 0; x < 8; x++) { /* columns */
+ int32_t *in = c + x, *o = ws + x;
+#define IN(k) ((cols >> (x + 8 * (k)) & 1) ? in[8 * (k)] : 0)
+ if (!(cols >> 8 & (0x01010101010101ull << x))) {
+ int32_t d = x ? IN(0) : dcv;
+ for (int k = 0; k < 8; k++) o[8 * k] = d;
+ continue;
+ }
+ int32_t t0 = x ? IN(0) : dcv, t1 = IN(2), t2 = IN(4), t3 = IN(6);
+ int32_t t10 = t0 + t2, t11 = t0 - t2, t13 = t1 + t3, t12 = MUL(t1 - t3, FIX_1_414213562) - t13;
+ t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;
+ int32_t t4 = IN(1), t5 = IN(3), t6 = IN(5), t7 = IN(7);
+#undef IN
+ int32_t z13 = t6 + t5, z10 = t6 - t5, z11 = t4 + t7, z12 = t4 - t7;
+ t7 = z11 + z13;
+ t11 = MUL(z11 - z13, FIX_1_414213562);
+ int32_t z5 = MUL(z10 + z12, FIX_1_847759065);
+ t10 = MUL(z12, FIX_1_082392200) - z5;
+ t12 = MUL(z10, -FIX_2_613125930) + z5;
+ t6 = t12 - t7, t5 = t11 - t6, t4 = t10 + t5;
+ o[0] = t0 + t7, o[56] = t0 - t7, o[8] = t1 + t6, o[48] = t1 - t6;
+ o[16] = t2 + t5, o[40] = t2 - t5, o[32] = t3 + t4, o[24] = t3 - t4;
+ }
+ for (int y = 0; y < 8; y++) { /* rows: +128 and rounding folded into the first */
+ int32_t *w = ws + 8 * y;
+ uint8_t *o = out + 8 * y;
+ int32_t w0 = w[0] + (128 << 5) + 16;
+ int32_t t10 = w0 + w[4], t11 = w0 - w[4], t13 = w[2] + w[6], t12 = MUL(w[2] - w[6], FIX_1_414213562) - t13;
+ int32_t t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;
+ int32_t z13 = w[5] + w[3], z10 = w[5] - w[3], z11 = w[1] + w[7], z12 = w[1] - w[7];
+ int32_t t7 = z11 + z13, t11b = MUL(z11 - z13, FIX_1_414213562), z5 = MUL(z10 + z12, FIX_1_847759065);
+ int32_t t10b = MUL(z12, FIX_1_082392200) - z5, t12b = MUL(z10, -FIX_2_613125930) + z5;
+ int32_t t6 = t12b - t7, t5 = t11b - t6, t4 = t10b + t5;
+ o[0] = clamp8((t0 + t7) >> 5), o[7] = clamp8((t0 - t7) >> 5);
+ o[1] = clamp8((t1 + t6) >> 5), o[6] = clamp8((t1 - t6) >> 5);
+ o[2] = clamp8((t2 + t5) >> 5), o[5] = clamp8((t2 - t5) >> 5);
+ o[4] = clamp8((t3 + t4) >> 5), o[3] = clamp8((t3 - t4) >> 5);
+ }
+}
+
+/* ------------------------------------------------------------------ one square */
+#if defined(__ARM_FEATURE_SAT)
+#include <arm_acle.h>
+#define SAT8(v) __usat(v, 8)
+#else
+#define SAT8(v) ((v) < 0 ? 0 : (v) > 255 ? 255 : (v))
+#endif
+/* a 4 x 4 ordered dither: what is added to red and blue (0 to 7) and green (0 to 3) before they lose bits */
+static const uint8_t dither_rb[4][4] = {{0, 4, 1, 5}, {6, 2, 7, 3}, {1, 5, 0, 4}, {7, 3, 6, 2}};
+static const uint8_t dither_g[4][4] = {{0, 2, 0, 2}, {3, 1, 3, 1}, {0, 2, 0, 2}, {3, 1, 3, 1}};
+
+/* decodes the square at data into dst (16 x 16, rows stride apart) */
+static void square(const uint8_t *data, int qset, uint16_t *dst, int stride) {
+ static Huff h[4];
+ static const uint8_t *loaded;
+ if (loaded != fnaf3_bin) {
+ for (int k = 0; k < 4; k++) h[k] = huff_tab(k);
+ loaded = fnaf3_bin;
+ }
+ const uint16_t *qy = (const uint16_t *)(const void *)(section(SEC_QUANT) + 256 * qset), *qc = qy + 64;
+ uint8_t y[4][64] __attribute__((aligned(4))), cb[64] __attribute__((aligned(4))), cr[64] __attribute__((aligned(4)));
+ Bits b = {data, 0, 0};
+ int pred = 0;
+ for (int k = 0; k < 4; k++) block(&b, &h[0], &h[1], &pred, qy, y[k]);
+ pred = 0;
+ block(&b, &h[2], &h[3], &pred, qc, cb);
+ pred = 0;
+ block(&b, &h[2], &h[3], &pred, qc, cr);
+ for (int rp = 0; rp < 8; rp++) { /* two rows at a time, sharing their colours */
+ int dr[8], dg[8], db[8];
+ for (int c = 0; c < 8; c++) {
+ int u = cb[rp * 8 + c] - 128, v = cr[rp * 8 + c] - 128;
+ dr[c] = (91881 * v + 32768) >> 16;
+ dg[c] = (-22554 * u - 46802 * v + 32768) >> 16;
+ db[c] = (116130 * u + 32768) >> 16;
+ }
+ for (int r = 2 * rp; r < 2 * rp + 2; r++) {
+ const uint8_t *yl = y[(r >> 3) * 2] + (r & 7) * 8, *drb = dither_rb[r & 3], *dgg = dither_g[r & 3];
+ uint16_t *o = dst + r * stride;
+ for (int c = 0; c < 16; c++) {
+ if (c == 8) yl = y[(r >> 3) * 2 + 1] + (r & 7) * 8;
+ int l = yl[c & 7], k = c >> 1;
+ int R = SAT8(l + dr[k] + drb[c & 3]), G = SAT8(l + dg[k] + dgg[c & 3]), B = SAT8(l + db[k] + drb[(c + 2) & 3]);
+ o[c] = (uint16_t)((R & 0xF8) << 8 | (G & 0xFC) << 3 | B >> 3);
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ pictures */
+typedef struct {
+ int mw, mh, q;
+ const uint8_t *table, *base_table; /* base_table: the picture whose squares it shares, or NULL */
+ int count; /* its own squares then */
+} Info;
+
+static Info info(int id) {
+ const uint8_t *p = section(SEC_PICS) + 12 * id, *t = section(SEC_TABLE);
+ Info i = {p[0], p[1], p[2], t + rd32(p + 8), NULL, (int)rd16(p + 6)};
+ uint32_t base = rd16(p + 4);
+ if (base != 0xFFFF) i.base_table = t + rd32(section(SEC_PICS) + 12 * base + 8);
+ return i;
+}
+
+static uint32_t square_at(const Info *i, int k) {
+ if (!i->base_table) return rd24(i->table + 3 * k);
+ int lo = 0, hi = i->count - 1;
+ while (lo <= hi) {
+ int mid = (lo + hi) >> 1, mk = (int)rd16(i->table + 5 * mid);
+ if (mk == k) return rd24(i->table + 5 * mid + 2);
+ if (mk < k) lo = mid + 1;
+ else hi = mid - 1;
+ }
+ return rd24(i->base_table + 3 * k);
+}
+
+int pic_w(int id) { return 16 * section(SEC_PICS)[12 * id]; }
+int pic_h(int id) { return 16 * section(SEC_PICS)[12 * id + 1]; }
+
+void pic_part(int id, int x, int y, int sx, int sy, int w, int h) {
+ Info in = info(id);
+ /* clip to the screen, the band and the picture */
+ int x0 = x > 0 ? x : 0, x1 = x + w < SCREEN_W ? x + w : SCREEN_W;
+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;
+ if (x0 >= x1 || y0 >= y1) return;
+ const uint8_t *bank = section(SEC_BANK);
+ uint16_t px[256];
+ /* in the picture: rows y0 - y + sy to y1 - y + sy, columns likewise */
+ int pr0 = y0 - y + sy, pr1 = y1 - y + sy, pc0 = x0 - x + sx, pc1 = x1 - x + sx;
+ for (int my = pr0 >> 4; my <= (pr1 - 1) >> 4 && my < in.mh; my++)
+ for (int mx = pc0 >> 4; mx <= (pc1 - 1) >> 4 && mx < in.mw; mx++) {
+ const uint8_t *data = bank + square_at(&in, my * in.mw + mx);
+ int r0 = my * 16 > pr0 ? my * 16 : pr0, r1 = my * 16 + 16 < pr1 ? my * 16 + 16 : pr1;
+ int c0 = mx * 16 > pc0 ? mx * 16 : pc0, c1 = mx * 16 + 16 < pc1 ? mx * 16 + 16 : pc1;
+ if (r1 - r0 == 16 && c1 - c0 == 16) { /* all of it shows: straight into the band */
+ square(data, in.q, gfx_band + (r0 - sy + y - gfx_y0) * SCREEN_W + (c0 - sx + x), SCREEN_W);
+ continue;
+ }
+ square(data, in.q, px, 16);
+ for (int r = r0; r < r1; r++) {
+ uint16_t *d = gfx_band + (r - sy + y - gfx_y0) * SCREEN_W + (c0 - sx + x);
+ const uint16_t *s = px + (r - my * 16) * 16 + (c0 - mx * 16);
+ for (int c = c0; c < c1; c++) *d++ = *s++;
+ }
+ }
+}
+
+void pic_draw(int id, int x, int y) { pic_part(id, x, y, 0, 0, pic_w(id), pic_h(id)); }
diff --git a/games/fnaf3/src/plat.h b/games/fnaf3/src/plat.h
new file mode 100644
index 00000000..89059cc2
--- /dev/null
+++ b/games/fnaf3/src/plat.h
@@ -0,0 +1,42 @@
+/* Five Nights at Freddy's 3: the platform (the calculator, or a computer for tests).
+ *
+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.
+ * plat_host.c: a frame buffer that tests save as images, scripted keys and
+ * simulated time (tests/play.c). */
+#ifndef FNAF3_PLAT_H
+#define FNAF3_PLAT_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define SCREEN_W 320
+#define SCREEN_H 240
+
+/* keys held now, as bits */
+enum {
+ K_LEFT = 1 << 0, K_RIGHT = 1 << 1, K_UP = 1 << 2, K_DOWN = 1 << 3,
+ K_OK = 1 << 4, /* OK */
+ K_BACK = 1 << 5, /* Back: pause */
+ K_HOME = 1 << 6, /* Home, On/Off: keep the moment and quit */
+ K_DEL = 1 << 7, /* backspace: mute the call */
+ K_0 = 1 << 8, /* the digits: K_0 << n */
+ K_EXE = 1 << 18, /* EXE: the monitor down, the panel's exit */
+ K_ANY = 1 << 19
+};
+#define K_DIGIT(n) (K_0 << (n))
+uint32_t plat_keys(void);
+uint32_t plat_millis(void);
+void plat_sleep(uint32_t ms);
+void plat_push(int x, int y, int w, int h, const uint16_t *px);
+bool plat_save(const char *name, const void *data, uint32_t len);
+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */
+/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its
+ * bytes, plat_reserved says they are written; NULL if there is no room */
+uint8_t *plat_reserve(const char *name, uint32_t len);
+void plat_reserved(const char *name, uint32_t len);
+bool plat_remove(const char *name);
+void plat_begin(void);
+int plat_end(void);
+/* an N0110 or N0115 (216 MHz, the N0120 has 550) */
+bool plat_slow(void);
+#endif
diff --git a/games/fnaf3/src/plat_eadk.c b/games/fnaf3/src/plat_eadk.c
new file mode 100644
index 00000000..52991778
--- /dev/null
+++ b/games/fnaf3/src/plat_eadk.c
@@ -0,0 +1,44 @@
+/* The calculator: EADK display, keyboard, time and files. */
+#include <eadk.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#include "plat.h"
+
+#define KEY(k) ((uint64_t)1 << (k))
+
+uint32_t plat_keys(void) {
+ static const uint8_t digits[10] = {eadk_key_zero, eadk_key_one, eadk_key_two, eadk_key_three, eadk_key_four,
+ eadk_key_five, eadk_key_six, eadk_key_seven, eadk_key_eight, eadk_key_nine};
+ uint64_t k = eadk_keyboard_scan();
+ uint32_t r = 0;
+ if (k & KEY(eadk_key_left)) r |= K_LEFT;
+ if (k & KEY(eadk_key_right)) r |= K_RIGHT;
+ if (k & KEY(eadk_key_up)) r |= K_UP;
+ if (k & KEY(eadk_key_down)) r |= K_DOWN;
+ if (k & KEY(eadk_key_ok)) r |= K_OK;
+ if (k & KEY(eadk_key_exe)) r |= K_EXE;
+ if (k & KEY(eadk_key_back)) r |= K_BACK;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;
+ if (k & KEY(eadk_key_backspace)) r |= K_DEL;
+ for (int i = 0; i < 10; i++)
+ if (k & KEY(digits[i])) r |= K_DIGIT(i);
+ if (k) r |= K_ANY;
+ return r;
+}
+
+uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }
+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ uint32_t n;
+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */
+}
+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }
+bool plat_remove(const char *name) { return ef_remove(name); }
+void plat_begin(void) { np_app_begin(); }
+int plat_end(void) { return np_app_end(); }
+bool plat_slow(void) { return epsilon_slow_model(); }
diff --git a/games/fnaf3/src/plat_host.c b/games/fnaf3/src/plat_host.c
new file mode 100644
index 00000000..f3f5a8c5
--- /dev/null
+++ b/games/fnaf3/src/plat_host.c
@@ -0,0 +1,71 @@
+/* A computer: the screen goes to a frame buffer that tests save as images,
+ * keys come from a script, time is simulated. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "plat.h"
+
+uint16_t host_fb[SCREEN_W * SCREEN_H];
+uint32_t host_time; /* ms */
+uint32_t host_keys;
+
+uint32_t plat_keys(void) { return host_keys; }
+uint32_t plat_millis(void) { return host_time; }
+void plat_sleep(uint32_t ms) { host_time += ms; }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ for (int r = 0; r < h; r++)
+ for (int c = 0; c < w; c++)
+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];
+}
+
+static char save_dir[256] = "build/host-saves";
+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }
+bool plat_save(const char *name, const void *data, uint32_t len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "wb");
+ if (!f) return false;
+ bool ok = fwrite(data, 1, len, f) == len;
+ fclose(f);
+ return ok;
+}
+/* (each file read gets its own buffer: callers may hold two at once) */
+static uint8_t loaded[4][1 << 16];
+static int next_load;
+const uint8_t *plat_load(const char *name, uint32_t *len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "rb");
+ if (!f) return NULL;
+ uint8_t *b = loaded[next_load++ & 3];
+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);
+ fclose(f);
+ return b;
+}
+static uint8_t reserved[1 << 16];
+bool host_storage_full; /* tests: no room for any file */
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ (void)name;
+ return len <= sizeof reserved && !host_storage_full ? reserved : NULL;
+}
+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }
+bool plat_remove(const char *name) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ return remove(p) == 0;
+}
+void plat_begin(void) {}
+int plat_end(void) { return 0; }
+bool plat_slow(void) { return false; }
+
+/* writes the screen as a PPM image */
+void host_shot(const char *path) {
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);
+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {
+ uint16_t c = host_fb[i];
+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, f);
+ }
+ fclose(f);
+}
diff --git a/games/fnaf3/src/res.h b/games/fnaf3/src/res.h
new file mode 100644
index 00000000..d9af32e1
--- /dev/null
+++ b/games/fnaf3/src/res.h
@@ -0,0 +1,15 @@
+/* Five Nights at Freddy's 3: data.bin (tools/pack.py), read where it lies in flash. */
+#ifndef FNAF3_RES_H
+#define FNAF3_RES_H
+#include <stdint.h>
+#include "data.h"
+
+extern const uint8_t *fnaf3_bin;
+
+/* (byte by byte: the data is not always aligned) */
+static inline uint32_t rd16(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8); }
+static inline int32_t rds16(const uint8_t *p) { return (int16_t)(p[0] | p[1] << 8); }
+static inline uint32_t rd24(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16); }
+static inline uint32_t rd32(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24); }
+static inline const uint8_t *section(int s) { return fnaf3_bin + rd32(fnaf3_bin + 8 + 4 * s); }
+#endif
diff --git a/games/fnaf3/src/save.c b/games/fnaf3/src/save.c
new file mode 100644
index 00000000..aee4b803
--- /dev/null
+++ b/games/fnaf3/src/save.c
@@ -0,0 +1,169 @@
+/* Saves: the progress (fnaf3.sav: the night reached, the stars, the custom night), the night as it was when Home quit
+ * (fnaf3res.sav, read once on the next start), and a copy of both in a Python script: installing apps from the
+ * NumWorks website keeps only Python scripts, so the saves come back from it when the files themselves are
+ * gone. Each is a comment line "#>name:base64" (the way NumPlay and its big games keep theirs). */
+#include <string.h>
+#include "game.h"
+#include "plat.h"
+
+#define SAVE_NAME "fnaf3.sav"
+#define RESUME_NAME "fnaf3res.sav"
+#define COPY_NAME "fnaf3_saves.py"
+#define MAGIC 0x33464E46u /* "FNF3" */
+#define VERSION 1
+
+typedef struct { /* the game's Ini keys: level, beatgame, beat6, goodend, and the extras' cheats */
+ uint32_t magic;
+ uint8_t version, level, beatgame, beat6;
+ uint8_t goodend, cheats, keys_seen, pad;
+} Progress;
+
+typedef struct {
+ uint32_t magic;
+ uint32_t size;
+ Night n;
+} Resume;
+
+static const char *const kept[] = {SAVE_NAME, RESUME_NAME};
+#define NKEPT (int)(sizeof kept / sizeof kept[0])
+static const char copy_head[] = "# Five Nights at Freddy's 3's saves: keep this file\n";
+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static void copy_write(void) {
+ uint32_t total = 1 + (sizeof copy_head - 1) + 1, len;
+ int n = 0;
+ for (int k = 0; k < NKEPT; k++)
+ if (plat_load(kept[k], &len) && len) total += 2 + (uint32_t)strlen(kept[k]) + 1 + (len + 2) / 3 * 4 + 1, n++;
+ plat_remove(COPY_NAME);
+ if (!n) return;
+ uint8_t *o = plat_reserve(COPY_NAME, total), *p = o;
+ if (!o) return;
+ *p++ = 0; /* (the script's status byte: not imported) */
+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;
+ for (int k = 0; k < NKEPT; k++) {
+ const uint8_t *d = plat_load(kept[k], &len);
+ if (!d || !len) continue;
+ uint32_t nl = (uint32_t)strlen(kept[k]);
+ *p++ = '#', *p++ = '>';
+ memcpy(p, kept[k], nl), p += nl;
+ *p++ = ':';
+ for (uint32_t i = 0; i < len; i += 3, p += 4) {
+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's
+ * launcher/src/storage.c) */
+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);
+ p[0] = (uint8_t)b64[v >> 18 & 63];
+ p[1] = (uint8_t)b64[v >> 12 & 63];
+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';
+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';
+ }
+ *p++ = '\n';
+ }
+ *p++ = 0;
+ plat_reserved(COPY_NAME, (uint32_t)(p - o));
+}
+
+static int b64_value(uint8_t c) {
+ for (int i = 0; i < 64; i++)
+ if ((uint8_t)b64[i] == c) return i;
+ return -1;
+}
+
+static const uint8_t *copy_line(int k, uint32_t *len) {
+ uint32_t n, nl = (uint32_t)strlen(kept[k]);
+ const uint8_t *c = plat_load(COPY_NAME, &n);
+ if (!c) return NULL;
+ for (uint32_t i = 0; i + nl + 3 <= n; i++)
+ if (c[i] == '#' && c[i + 1] == '>' && !memcmp(c + i + 2, kept[k], nl) && c[i + 2 + nl] == ':') {
+ const uint8_t *l = c + i + 3 + nl;
+ uint32_t m = 0;
+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;
+ *len = m;
+ return l;
+ }
+ return NULL;
+}
+
+void save_restore_copy(void) {
+ for (int k = 0; k < NKEPT; k++) {
+ uint32_t have, len;
+ if (plat_load(kept[k], &have)) continue;
+ const uint8_t *l = copy_line(k, &len);
+ if (!l || !len || len % 4) continue;
+ uint32_t size = len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=');
+ uint8_t *out = plat_reserve(kept[k], size);
+ if (!out) continue;
+ l = copy_line(k, &len);
+ bool ok = l != NULL && len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=') == size;
+ uint32_t o = 0;
+ for (uint32_t i = 0; ok && i < len; i += 4) {
+ int v0 = l[i] == '=' ? 0 : b64_value(l[i]), v1 = l[i + 1] == '=' ? 0 : b64_value(l[i + 1]);
+ int v2 = l[i + 2] == '=' ? 0 : b64_value(l[i + 2]), v3 = l[i + 3] == '=' ? 0 : b64_value(l[i + 3]);
+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) ok = false;
+ uint32_t wd = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);
+ if (o < size) out[o++] = (uint8_t)(wd >> 16);
+ if (o < size) out[o++] = (uint8_t)(wd >> 8);
+ if (o < size) out[o++] = (uint8_t)wd;
+ }
+ if (ok && o == size) plat_reserved(kept[k], size);
+ else plat_remove(kept[k]);
+ }
+}
+
+void save_progress(void) {
+ Progress p;
+ memset(&p, 0, sizeof p);
+ p.magic = MAGIC, p.version = VERSION;
+ p.level = g.level, p.beatgame = g.beatgame, p.beat6 = g.beat6, p.goodend = g.goodend;
+ p.cheats = g.cheats, p.keys_seen = g.keys_seen;
+ plat_save(SAVE_NAME, &p, sizeof p);
+ copy_write();
+}
+
+void save_load(void) {
+ uint32_t len;
+ const uint8_t *d = plat_load(SAVE_NAME, &len);
+ g.level = 1;
+ if (!d || len != sizeof(Progress)) return;
+ Progress p;
+ memcpy(&p, d, sizeof p);
+ if (p.magic != MAGIC || p.version != VERSION) return;
+ g.level = p.level >= 1 && p.level <= 7 ? p.level : 1;
+ g.beatgame = p.beatgame & 1, g.beat6 = p.beat6 & 1, g.goodend = p.goodend & 1;
+ g.cheats = p.cheats & 15, g.keys_seen = p.keys_seen ? 1 : 0;
+}
+
+void save_resume(void) {
+ Resume r;
+ memset(&r, 0, sizeof r);
+ r.magic = MAGIC, r.size = sizeof(Night), r.n = g.n;
+ plat_save(RESUME_NAME, &r, sizeof r);
+ copy_write();
+}
+
+/* a kept night that can be played on: every place, state and number in its range */
+static bool night_valid(const Night *n) { /* (a resume file that doesn't hold together is dropped) */
+ if (n->night < 1 || n->night > 6 || n->hour > 5 || n->loc > L_OFF) return false;
+ if (n->cam < 1 || n->cam > 10 || n->vent < 11 || n->vent > 15 || n->closed > 15 || n->sealing > 15) return false;
+ if (n->x < XMIN || n->x > XMAX + 700 || n->viewing > 2 || n->panel > 3 || n->cursor < 1 || n->cursor > 5) return false;
+ if (n->rebooting > 4 || n->play < 1 || n->play > 7 || n->trail_n > 3 || n->scare > PH_FOXY || n->got_you > 2) return false;
+ if (n->audio < -10 || n->audio > 0 || n->camera < -10 || n->camera > 0 || n->vent_h < -10 || n->vent_h > 0) return false;
+ return true;
+}
+
+bool save_resume_load(void) {
+ uint32_t len;
+ const uint8_t *d = plat_load(RESUME_NAME, &len);
+ if (!d) return false;
+ bool ok = false;
+ if (len == sizeof(Resume)) {
+ Resume r;
+ memcpy(&r, d, sizeof r);
+ if (r.magic == MAGIC && r.size == sizeof(Night) && night_valid(&r.n)) {
+ g.n = r.n;
+ ok = true;
+ }
+ }
+ plat_remove(RESUME_NAME);
+ copy_write();
+ return ok;
+}
diff --git a/games/fnaf3/src/view.c b/games/fnaf3/src/view.c
new file mode 100644
index 00000000..fd01550f
--- /dev/null
+++ b/games/fnaf3/src/view.c
@@ -0,0 +1,181 @@
+/* Five Nights at Freddy's 3: drawing the night. The office is the game's at half size (600 x 240) and the
+ * calculator shows 320 of it around the game's view; what changes in it (the window, the left door, the phantoms
+ * standing in it) are patches tools/pack.py made from the game's pictures. The monitor is the camera feed with the
+ * map over it, the maintenance panel its own picture with the menu's words. */
+#include <stdio.h>
+#include "game.h"
+#include "gfx.h"
+#include "data.h"
+
+#define N g.n
+#define GREY RGB(0xB0B0B0)
+#define GREEN RGB(0x4CD964)
+#define RED RGB(0xE03030)
+#define BLUE RGB(0x4A90E2)
+
+static int pan; /* the office's left edge on the screen */
+
+/* a picture placed in the office at (ox, oy), as much of it as is on the screen */
+static void office_part(int id, int ox, int oy, int w, int h) {
+ int x = ox - pan, sx = 0;
+ if (x < 0) sx = -x, w += x, x = 0;
+ if (x + w > SCREEN_W) w = SCREEN_W - x;
+ if (w > 0) pic_part(id, x, oy, sx, 0, w, h);
+}
+
+static int seq(int t, int len, int n) { /* frame t of len, as one of n pictures */
+ int k = t * n / (len > 0 ? len : 1);
+ return k < 0 ? 0 : k >= n ? n - 1 : k;
+}
+
+static void office(void) {
+ int xc = N.got_you == 2 ? XMAX : N.x;
+ pan = (xc - 320) / 2;
+ if (N.frozen) pan += (int)rnd_n(7) - 3; /* (the view shakes during a scare) */
+ pan = pan < 0 ? 0 : pan > 600 - SCREEN_W ? 600 - SCREEN_W : pan;
+ pic_part(N.red_on ? PIC_OFFICE_RED : PIC_OFFICE, 0, 0, pan, 0, SCREEN_W, SCREEN_H);
+ /* the window */
+ int win = -1;
+ if (N.window) win = PIC_WIN_SPRING;
+ else if (N.ran_past && N.ran_past < 255) win = PIC_WIN_RUN0 + seq(N.ran_past - 1, 31, RUN_N);
+ else if (N.mangle_win) {
+ int t = N.mangle_win, i = t < 160 ? t * 10 / 160 : t < 190 ? 10 : 10 - (t - 190) * 10 / 16;
+ win = PIC_WIN_MANGLE0 + (i < 0 ? 0 : i);
+ } else if (N.flunge) win = PIC_WIN_FLUNGE0 + seq(N.flunge - 1, 28, FLUNGE_N);
+ else if (N.fwalk) {
+ int x = 1011 - N.fwalk_t * 3 / 8, i = (FREDDY_X0 - x) / 8;
+ if (i >= 0 && i < FREDDY_N) win = PIC_WIN_FREDDY0 + i;
+ }
+ if (win >= 0) office_part(win, WIN_X, WIN_Y, WIN_W, WIN_H);
+ /* the left door */
+ if (N.head) office_part(PIC_DOOR_HEAD, DOOR_X, DOOR_Y, DOOR_W, DOOR_H);
+ else if (N.hid && N.hid < 255) office_part(PIC_DOOR_HIDE0 + seq(N.hid - 1, 27, HIDE_N), DOOR_X, DOOR_Y, DOOR_W, DOOR_H);
+ /* the phantoms in the office */
+ if (N.scare == PH_BB)
+ office_part(PIC_BB0 + (N.scare_t < 30 ? (N.scare_t / 15) % 2 : 2 + seq(N.scare_t - 30, 17, BB_N - 2)), BB_X, BB_Y, BB_W, BB_H);
+ if (N.chica_in == 1) office_part(PIC_CHICA0, CHICA_X, CHICA_Y, CHICA_W, CHICA_H);
+ if (N.scare == PH_CHICA) office_part(PIC_CHICA0 + 1 + seq(N.scare_t, 20, CHICA_N - 1), CHICA_X, CHICA_Y, CHICA_W, CHICA_H);
+ if (N.foxy && N.scare != PH_FOXY) office_part(PIC_FOXY0, FOXY_X, FOXY_Y, FOXY_W, FOXY_H);
+ if (N.scare == PH_FOXY) office_part(PIC_FOXY0 + 1 + seq(N.scare_t, 23, FOXY_N - 1), FOXY_X, FOXY_Y, FOXY_W, FOXY_H);
+}
+
+/* ------------------------------------------------------------ the monitor */
+static const int16_t BX[16] = {0, BTN01_X, BTN02_X, BTN03_X, BTN04_X, BTN05_X, BTN06_X, BTN07_X, BTN08_X, BTN09_X,
+ BTN10_X, BTN11_X, BTN12_X, BTN13_X, BTN14_X, BTN15_X};
+static const int16_t BY[16] = {0, BTN01_Y, BTN02_Y, BTN03_Y, BTN04_Y, BTN05_Y, BTN06_Y, BTN07_Y, BTN08_Y, BTN09_Y,
+ BTN10_Y, BTN11_Y, BTN12_Y, BTN13_Y, BTN14_Y, BTN15_Y};
+static const int16_t SX[5] = {SEAL11_X, SEAL12_X, SEAL13_X, SEAL14_X, SEAL15_X};
+static const int16_t SY[5] = {SEAL11_Y, SEAL12_Y, SEAL13_Y, SEAL14_Y, SEAL15_Y};
+
+static int feed_pic(int a, int k) {
+ switch (a) {
+#define F(n) case n: return PIC_FEED##n##_0 + k % FEED##n##_N;
+ F(12) F(13) F(14) F(15) F(16) F(17) F(21) F(23) F(24) F(25) F(26) F(27) F(28) F(29) F(30) F(31) F(32) F(33)
+ F(34) F(35) F(43) F(45) F(46) F(47) F(48) F(49) F(50) F(51) F(52) F(53) F(54) F(55) F(56) F(57)
+#undef F
+ }
+ return PIC_FEED17_0;
+}
+
+static void monitor(void) {
+ int c = N.vents_map ? N.vent : N.cam;
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ bool video = N.camera > -10;
+ if (video) {
+ if (N.bb_shown) pic_draw(PIC_BBPEEK, 8, 0);
+ else pic_draw(feed_pic(feed_anim(c), (int)(N.frame / 8)), 8, 0);
+ }
+ int s0 = (int)rnd_n(30) + N.static_s1 + N.static_s4 + 30, op = s0 - 45;
+ op = op < 0 ? 0 : op > 255 ? 255 : op;
+ gfx_static(8, 0, 304, 240, video ? op * 32 / 255 : 24, N.frame);
+ gfx_img(N.vents_map ? IMG_VENTMAP : IMG_MAP, MAP_X, MAP_Y, N.vents_map ? BLUE : GREY);
+ int lo = N.vents_map ? 11 : 1, hi = N.vents_map ? 15 : 10;
+ for (int i = lo; i <= hi; i++) {
+ int x = BX[i] - 11, y = BY[i] - 7;
+ gfx_fill(x, y, 22, 15, i == c ? GREEN : RGB(0x505050));
+ gfx_frame_rect(x, y, 22, 15, WHITE);
+ char t[4];
+ snprintf(t, sizeof t, "%02d", i);
+ gfx_text_c(FONT_HUD, BX[i], y + 1, t, WHITE);
+ }
+ if (N.vents_map)
+ for (int i = 0; i < 5; i++) gfx_fill(SX[i] - 6, SY[i] - 4, 12, 8, N.closed == 11 + i ? RED : GREEN);
+ if ((g.cheats & CH_RADAR) && spring_cam()) {
+ int s = spring_cam();
+ if ((s >= 11) == (bool)N.vents_map) gfx_fill(BX[s] - 3, BY[s] - 3, 6, 6, RED);
+ }
+ if (N.sdfg && !N.vents_map) { /* the lure's sound wave */
+ int r = 4 + (133 - N.sdfg) % 20;
+ gfx_frame_rect(BX[N.lure_cam] - r, BY[N.lure_cam] - r / 2, 2 * r, r, WHITE);
+ }
+ char cam[8];
+ snprintf(cam, sizeof cam, "CAM %02d", c);
+ gfx_text_s(FONT_BIG, 14, 6, cam, WHITE);
+ int y = 30;
+ if (N.audio <= -10) gfx_img(IMG_M_AUDIO, 14, y, RED), y += gfx_img_h(IMG_M_AUDIO) + 2;
+ if (!video) gfx_img(IMG_M_VIDEO, 14, y, RED), y += gfx_img_h(IMG_M_VIDEO) + 2;
+ if (N.vent_h <= -10) gfx_img(IMG_M_VENT, 14, y, RED);
+ if (N.sealing) gfx_text_s(FONT_HUD, MAP_X, MAP_Y - 14, "SEALING...", WHITE);
+ if (!N.vents_map && N.play < 7) {
+ char p[4];
+ snprintf(p, sizeof p, "%d", N.play);
+ gfx_text_s(FONT_BIG, MAP_X, MAP_Y - 20, p, WHITE);
+ }
+}
+
+static void panel(void) {
+ int y0 = 0;
+ if (N.panel == 1) y0 = SCREEN_H - N.panel_anim * SCREEN_H / 10;
+ if (N.panel_dropping) y0 = N.panel_anim * SCREEN_H / 8;
+ if (y0 > 0) office();
+ if (y0 >= SCREEN_H) return;
+ pic_part(PIC_PANEL, 0, y0, 0, 0, SCREEN_W, SCREEN_H - y0);
+ static const uint8_t item_y[5] = {66, 96, 123, 176, 201};
+ static const uint8_t ids[5] = {IMG_P_AUDIO, IMG_P_CAMERA, IMG_P_VENT, IMG_P_ALL, IMG_P_EXIT};
+ for (int i = 0; i < 5; i++) {
+ int y = y0 + item_y[i];
+ gfx_img(ids[i], 40, y, WHITE);
+ bool bad = (i == 0 && N.audio <= -10) || (i == 1 && N.camera <= -10) || (i == 2 && N.vent_h <= -10);
+ if (bad && N.rebooting != i + 1) gfx_img(IMG_P_ERROR, 210, y, RED);
+ if (N.rebooting == i + 1) gfx_img(IMG_P_DOTS0 + (int)(N.frame / 12) % DOTS_N, 210, y, WHITE);
+ if (N.cursor == i + 1) gfx_img(IMG_P_CURSOR, 4, y, WHITE);
+ }
+}
+
+/* the hour, the night, how close he is (the game's hum, shown) */
+static void hud(void) {
+ char t[12];
+ if (N.hour == 0) snprintf(t, sizeof t, "12 AM");
+ else snprintf(t, sizeof t, "%d AM", N.hour);
+ gfx_text_r(FONT_CLOCK, SCREEN_W - 6, 2, t, WHITE);
+ snprintf(t, sizeof t, "Night %d", N.night);
+ gfx_text_r(FONT_TEXT, SCREEN_W - 6, 30, t, WHITE);
+ for (int i = 0; i < 2; i++)
+ gfx_fill(6 + 7 * i, 18 - 6 * i, 5, 6 + 6 * i, i < N.nearby ? (N.nearby == 2 ? RED : RGB(0xE0A030)) : RGB(0x303030));
+}
+
+void view_night(void) {
+ if (N.got_you && N.death_t > 0) {
+ int k = seq(N.death_t, 37, JUMP_N);
+ pic_draw((N.got_you == 1 ? PIC_JUMPL0 : PIC_JUMPR0) + k, 0, 0);
+ return;
+ }
+ if (N.scare == PH_FREDDY) {
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ pic_draw(PIC_FSCARE0 + seq(N.scare_t, 17, FSCARE_N), 0, 0);
+ return;
+ }
+ if (N.viewing >= 2) monitor();
+ else if (N.viewing == 1) gfx_static(0, 0, SCREEN_W, SCREEN_H, 28, N.frame);
+ else if (N.panel) panel();
+ else office();
+ if (N.head_t > 0 || N.head_out) {
+ int id = N.head_t > 0 ? IMG_PHEAD1 + N.head_anim : IMG_PHEAD0;
+ gfx_img(id, N.head_x - gfx_img_w(id) / 2, SCREEN_H - gfx_img_h(id), RGB(0xE8E8E8));
+ }
+ if (N.black > 0) gfx_dim(0, 0, SCREEN_W, SCREEN_H, (N.black > 255 ? 255 : N.black) * 32 / 255);
+ if (N.flash > 0) gfx_blend(0, 0, SCREEN_W, SCREEN_H, WHITE, N.flash * 32 / 51);
+ if (N.viewing < 2 && !N.panel) hud();
+}
+
+void view_scare(void) { view_night(); }
diff --git a/games/fnaf3/tests/pics.c b/games/fnaf3/tests/pics.c
new file mode 100644
index 00000000..79c8a23f
--- /dev/null
+++ b/games/fnaf3/tests/pics.c
@@ -0,0 +1,30 @@
+/* Draws every picture of data.bin on a computer (build/pics/<id>.ppm), to check the codec:
+ * tests/check.py compares them with what tools/pack.py was given. */
+#include <stdio.h>
+#include "../src/gfx.h"
+#include "../src/res.h"
+
+extern const uint8_t fnaf3_data[];
+const uint8_t *fnaf3_bin;
+void host_shot(const char *path);
+
+static int cur, offx;
+static void draw(void) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ pic_draw(cur, -offx, 0);
+}
+
+int main(int argc, char **argv) {
+ static uint16_t band[SCREEN_W * BAND_H];
+ gfx_set_band_memory(band);
+ fnaf3_bin = fnaf3_data;
+ const char *dir = argc > 1 ? argv[1] : "build/pics";
+ for (cur = 0; cur < PIC_COUNT; cur++)
+ for (offx = 0; offx < pic_w(cur); offx += SCREEN_W) {
+ gfx_frame(draw);
+ char path[256];
+ snprintf(path, sizeof path, "%s/%d_%d.ppm", dir, cur, offx);
+ host_shot(path);
+ }
+ return 0;
+}
diff --git a/games/fnaf3/tests/rules.c b/games/fnaf3/tests/rules.c
new file mode 100644
index 00000000..07214fca
--- /dev/null
+++ b/games/fnaf3/tests/rules.c
@@ -0,0 +1,257 @@
+/* Five Nights at Freddy's 3 on a computer (make test, with the sanitizers): the night's rules against the game's
+ * events (gamesrc spec fnaf3_spec.md), whole nights played by a bot that watches, lures, seals and reboots, random
+ * keys on every night, and the saves. Prints what failed; exits 1 if anything did. Screenshots: build/rules shots
+ * DIR. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../src/game.h"
+#include "../src/gfx.h"
+#include "../src/plat.h"
+
+extern const uint8_t fnaf3_data[];
+const uint8_t *fnaf3_bin;
+extern uint32_t host_keys;
+void host_shot(const char *path);
+void host_save_dir(const char *d);
+static int fails, checks;
+#define CHECK(c, ...) (checks++, (c) ? 0 : (fails++, printf("FAIL %d: ", __LINE__), printf(__VA_ARGS__), printf("\n")))
+#define N g.n
+
+static void step(uint32_t keys) { game_step(keys); }
+static void steps(int n, uint32_t keys) {
+ for (int i = 0; i < n; i++) step(keys);
+}
+static void tap(uint32_t k) { step(k), step(0); }
+
+static void night(int n) {
+ start_night(n);
+ while (g.scene == SC_DAY) step(0);
+}
+
+static void rules(void) {
+ /* night 1: no Springtrap, no errors however long you look away */
+ night(1);
+ steps(60 * 100, 0);
+ CHECK(N.loc == L_OFF && spring_cam() == 0, "night 1: Springtrap off the map (%d)", N.loc);
+ CHECK(N.vent_h > -10 && N.audio > -10 && N.camera > -10, "night 1: no error");
+ CHECK(N.ai == 0 && N.tlimit == 100, "night 1: AI 0, time limit 100");
+ /* night 1 lasts 3 minutes: 6 AM at 180 s */
+ night(1);
+ steps(60 * 179, 0);
+ CHECK(g.scene == SC_NIGHT && N.hour == 5, "night 1: 5 AM at 179 s (hour %d)", N.hour);
+ steps(70, 0);
+ CHECK(g.scene == SC_SIX, "night 1: 6 AM after 3 minutes (scene %d)", g.scene);
+ /* nights 2 on: he starts in CAM 06 to 10 */
+ for (int s = 0; s < 40; s++) {
+ night(2);
+ CHECK(N.loc >= 6 && N.loc <= 10, "night 2: starts at 06..10 (%d)", N.loc);
+ }
+ /* AI by night (events 492-497) */
+ static const uint8_t ai[7] = {0, 0, 2, 3, 4, 5, 7};
+ for (int n = 1; n <= 6; n++) {
+ night(n);
+ step(0);
+ CHECK(N.ai == ai[n], "night %d: AI %d (%d)", n, ai[n], N.ai);
+ }
+ /* the lure: CAM 06 pulls him from 05 or 07, the counter refills in 9 s */
+ night(3);
+ steps(60 * 10, 0);
+ N.loc = 5, N.lure_to = 0, N.action = 0;
+ tap(K_OK); /* (the view pans right, then the monitor comes up) */
+ while (N.viewing < 2) step(0);
+ tap(K_DIGIT(6));
+ CHECK(N.cam == 6, "the monitor: 6 picks CAM 06 (%d)", N.cam);
+ int pulled = 0, tries = 0;
+ for (int k = 0; k < 140; k++) {
+ N.loc = 5, N.lure_to = 0, N.play = 7, N.action = 0, N.audio = 0;
+ tap(K_OK);
+ tries++;
+ pulled += N.lure_to == 6;
+ }
+ CHECK(pulled > tries * 70 / 100 && pulled < tries * 95 / 100, "the lure works 6 times in 7 (%d of %d)", pulled, tries);
+ N.loc = 9, N.lure_to = 0, N.play = 7;
+ tap(K_OK);
+ CHECK(N.lure_to == 0, "a lure on CAM 06 doesn't reach CAM 09");
+ CHECK(N.play == 1, "the lure's counter starts again");
+ steps(9 * 60 + 2, 0);
+ CHECK(N.play == 7, "the lure is ready again after 9 s (%d)", N.play);
+ /* audio: AI per play, an error at -10 */
+ night(2);
+ step(0);
+ N.x = 800;
+ tap(K_OK);
+ while (N.viewing < 2) step(0);
+ int plays = 0;
+ while (N.audio > -10 && plays < 20) N.play = 7, tap(K_OK), plays++;
+ CHECK(plays == 5, "night 2: 5 lures before the audio error (%d)", plays);
+ /* sealing: a vent camera on the vent map; he goes back out of a sealed vent */
+ tap(K_DEL);
+ CHECK(N.vents_map, "backspace shows the vent map");
+ tap(K_DIGIT(3));
+ CHECK(N.vent == 13, "3 on the vent map is CAM 13 (%d)", N.vent);
+ tap(K_OK);
+ CHECK(N.sealing == 13, "OK seals CAM 13");
+ steps(110, 0);
+ CHECK(N.closed == 13 && !N.sealing, "CAM 13 sealed in under 1.7 s (%d)", N.closed);
+ N.loc = 13, N.action = 2;
+ step(0);
+ CHECK(N.loc == 5, "out of the sealed CAM 13: back to CAM 05 (%d)", N.loc);
+ N.closed = 0, N.loc = 13, N.action = 2;
+ step(0);
+ CHECK(N.loc == L_ST1, "out of an open CAM 13: the window (%d)", N.loc);
+ /* the panel: reboot all takes 10 to 20 s and clears the three */
+ night(4);
+ step(0);
+ N.audio = N.camera = N.vent_h = -10;
+ tap(K_DOWN);
+ steps(40, 0);
+ CHECK(N.panel == 3, "Down brings the panel up (%d)", N.panel);
+ tap(K_DOWN), tap(K_DOWN), tap(K_DOWN);
+ CHECK(N.cursor == 4, "the cursor on reboot all (%d)", N.cursor);
+ tap(K_OK);
+ int t = 0;
+ while (N.rebooting && t < 60 * 30) step(0), t++;
+ CHECK(t >= 60 * 9 && t <= 60 * 21, "reboot all: %d frames", t);
+ CHECK(N.audio == 0 && N.camera == 0 && N.vent_h == 0, "reboot all clears the three");
+ /* ventilation error: the blackout moves him on at its peak */
+ night(5);
+ step(0);
+ N.loc = L_ST1, N.vent_h = -10;
+ int moved = 0;
+ for (int k = 0; k < 60 * 30 && !moved; k++) step(0), moved = N.loc != L_ST1;
+ CHECK(moved, "a ventilation error's blackout brings him from the window");
+ /* at the door with a screen up: he gets you */
+ night(5);
+ step(0);
+ N.loc = L_ST4, N.action = 2;
+ N.x = 400;
+ tap(K_DOWN);
+ steps(60, 0);
+ CHECK(g.scene == SC_STATIC || N.got_you, "at the door, the panel up: the lunge");
+ steps(60, 0);
+ CHECK(g.scene == SC_STATIC || g.scene == SC_OVER, "then the static (%d)", g.scene);
+}
+
+/* a bot: watches him, lures him away, keeps the systems up */
+static uint32_t bot_keys(void) {
+ static int t;
+ t++;
+ if (g.scene != SC_NIGHT || N.got_you) return t & 1 ? K_OK : 0;
+ if (N.panel >= 2) {
+ if (N.rebooting) return 0;
+ if (N.audio > -10 && N.camera > -10 && N.vent_h > -10) return t & 1 ? K_EXE : 0;
+ if (N.cursor != 4) return t & 1 ? K_DOWN : 0;
+ return t & 1 ? K_OK : 0;
+ }
+ if (N.viewing >= 2) {
+ if (N.vent_h <= -10 || N.camera <= -10 || (N.audio <= -10 && N.loc <= 5)) return t & 1 ? K_EXE : 0;
+ if (N.bb_shown || N.mangle == 2 || N.puppet == 2 || N.chica == 2) return (t & 1) ? K_DIGIT(5) : 0;
+ int s = spring_cam(), c = N.cam;
+ static const uint8_t away[16] = {0, 0, 5, 2, 3, 6, 7, 8, 9, 10, 9, 0, 0, 0, 0, 0};
+ if (s && s <= 10 && away[s] && c != away[s]) return t & 1 ? K_DIGIT(away[s] % 10) : 0;
+ if (s && s <= 10 && away[s] && N.play == 7) return t & 1 ? K_OK : 0;
+ return 0;
+ }
+ if (N.vent_h <= -10 || N.camera <= -10 || N.audio <= -10) return t & 1 ? K_DOWN : 0;
+ return t & 1 ? K_OK : 0;
+}
+
+static void bot_nights(void) {
+ int won = 0, lost = 0;
+ for (int n = 1; n <= 6; n++)
+ for (int s = 0; s < 3; s++) {
+ night(n);
+ int t = 0;
+ while (g.scene == SC_NIGHT && t < 60 * 60 * 7) step(bot_keys()), t++;
+ if (g.scene == SC_SIX) won++;
+ else lost++;
+ }
+ printf("bot: %d nights won, %d lost\n", won, lost);
+ CHECK(won >= 3, "the bot wins some nights (%d)", won);
+}
+
+static void fuzz(int sessions) {
+ uint32_t r = 7;
+ for (int s = 0; s < sessions; s++) {
+ night(1 + s % 6);
+ for (int f = 0; f < 60 * 120 && g.scene == SC_NIGHT; f++) {
+ r = r * 1103515245u + 12345u;
+ static const uint32_t keys[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_EXE, K_DEL, K_DIGIT(1), K_DIGIT(5),
+ K_DIGIT(0), K_DIGIT(3), 0};
+ uint32_t k = keys[(r >> 16) % 12];
+ if (k == 0 || (r >> 8) % 3) step(0);
+ else step(k);
+ }
+ }
+}
+
+static void saves(void) {
+ night(3);
+ steps(60 * 30, 0);
+ Night keep = g.n;
+ save_resume();
+ memset(&g.n, 0, sizeof g.n);
+ CHECK(save_resume_load() && g.n.night == 3 && g.n.frame == keep.frame && g.n.loc == keep.loc, "the night kept by Home comes back");
+ CHECK(!save_resume_load(), "and only once");
+ g.level = 4, g.beatgame = 1, g.beat6 = 0, g.goodend = 0;
+ save_progress();
+ g.level = 1, g.beatgame = 0;
+ save_load();
+ CHECK(g.level == 4 && g.beatgame == 1, "the progress comes back");
+}
+
+static void shot(const char *dir, const char *name) {
+ char p[256];
+ game_draw();
+ snprintf(p, sizeof p, "%s/%s.ppm", dir, name);
+ host_shot(p);
+}
+
+static void draw_all(const char *dir) {
+ night(5);
+ steps(60, 0);
+ N.loc = L_ST1, N.window = 1, N.x = 760, N.hour = 3;
+ shot(dir, "shot");
+ night(5);
+ steps(60, 0);
+ N.x = 640, N.scare = PH_BB, N.scare_t = 36, N.hour = 2;
+ shot(dir, "bb");
+ night(5);
+ steps(60, 0);
+ N.x = 800, N.cam = 7, N.hour = 4;
+ tap(K_OK);
+ steps(30, 0);
+ N.loc = 7;
+ step(0);
+ shot(dir, "monitor");
+ tap(K_DEL);
+ steps(2, 0);
+ N.closed = 12;
+ step(0);
+ shot(dir, "vents");
+ night(5);
+ steps(60, 0);
+ N.vent_h = -10, N.camera = -10;
+ tap(K_DOWN);
+ steps(60, 0);
+ shot(dir, "panel");
+}
+
+int main(int argc, char **argv) {
+ static uint16_t band[SCREEN_W * BAND_H];
+ gfx_set_band_memory(band);
+ fnaf3_bin = fnaf3_data;
+ host_save_dir("build");
+ game_init();
+ if (argc > 2 && !strcmp(argv[1], "shots")) {
+ draw_all(argv[2]);
+ return 0;
+ }
+ rules();
+ bot_nights();
+ fuzz(60);
+ saves();
+ printf("%d checks, %d failed\n", checks, fails);
+ return fails != 0;
+}
diff --git a/games/fnaf3/tools/ccn.py b/games/fnaf3/tools/ccn.py
new file mode 100644
index 00000000..c0bf7340
--- /dev/null
+++ b/games/fnaf3/tools/ccn.py
@@ -0,0 +1,121 @@
+"""Five Nights at Freddy's 3's application.ccn (Clickteam Fusion, from the game's Android package): its pictures, its
+objects with their animations, and its frames with the objects in them. Read only; tools/pack.py uses it.
+
+The file is chunks (u16 id, u16 flags, u32 size, the data). The ones read here:
+- 0x6666, the pictures: u16 count, u16 the highest number, then each: u16 its number, u32 format (0: RGBA, 3: RGB with
+ rows padded), u16 width, u16 height, 4 x i16 hot spot and action point, u32 size, zlib data.
+- 0x2229, the objects: u32 count, then each a run of chunks: 0x4444 (u16 its number, i16 kind: 1 backdrop, 2 active,
+ 3 string, 7 counter), 0x4445 (its name, UTF-16), 0x4446 (its properties: an active's animations from the offset
+ at byte 6: u16 count, u16 offsets, each animation 32 directions, a direction's u16 picture count at 6 and the
+ pictures from 8).
+- 0x3333, the frames: chunks of their own, 0x3335 the name, 0x3338 the objects placed (u32 count, then 20 bytes
+ each: u16, u16 the object, i32 x, i32 y, 4 x i16)."""
+import struct
+import zlib
+
+from PIL import Image
+
+
+def chunks(b, p=0):
+ out = []
+ while p + 8 <= len(b):
+ cid, _, size = struct.unpack_from("<HHI", b, p)
+ out.append((cid, b[p + 8:p + 8 + size]))
+ p += 8 + size
+ if cid == 0x7F7F:
+ break
+ return out
+
+
+class App:
+ def __init__(self, path):
+ d = open(path, "rb").read()
+ assert d[:4] == b"PAMU", "not a Clickteam application"
+ top = chunks(d, 16)
+ self.pics = {}
+ bank = next(c for i, c in top if i == 0x6666)
+ q = 4
+ while q < len(bank):
+ h, fmt, w, hh, hx, hy, _, _, size = struct.unpack_from("<HIHHhhhhI", bank, q)
+ self.pics[h] = (fmt, w, hh, q + 22, size, hx, hy)
+ q += 22 + size
+ self.bank = bank
+ self.objects, self.by_name = {}, {}
+ b = next(c for i, c in top if i == 0x2229)
+ q = 4
+ for _ in range(struct.unpack_from("<I", b, 0)[0]):
+ head = name = props = None
+ while True:
+ sid, _, size = struct.unpack_from("<HHI", b, q)
+ body = b[q + 8:q + 8 + size]
+ q += 8 + size
+ if sid == 0x4444:
+ head = struct.unpack_from("<Hh", body, 0)
+ elif sid == 0x4445:
+ name = body.decode("utf-16-le").split("\0")[0]
+ elif sid == 0x4446:
+ props = body
+ elif sid == 0x7F7F:
+ break
+ anims = self._anims(props) if head[1] == 2 and props else {}
+ self.objects[head[0]] = (head[1], name, anims)
+ self.frames = {}
+ for i, c in top:
+ if i != 0x3333:
+ continue
+ sub = dict(chunks(c))
+ name = sub[0x3335].decode("utf-16-le").split("\0")[0]
+ placed = []
+ x = sub.get(0x3338, b"\0\0\0\0")
+ for k in range(struct.unpack_from("<I", x, 0)[0]):
+ _, obj, px, py = struct.unpack_from("<HHii", x, 4 + 20 * k)
+ placed.append((obj, px, py))
+ self.frames[name] = placed
+
+ @staticmethod
+ def _anims(p):
+ at = struct.unpack_from("<H", p, 6)[0]
+ if not at:
+ return {}
+ out = {}
+ count = struct.unpack_from("<H", p, at + 2)[0]
+ for a, off in enumerate(struct.unpack_from(f"<{count}H", p, at + 4)):
+ if not off:
+ continue
+ dirs = struct.unpack_from("<32H", p, at + off)
+ if dirs[0]:
+ q = at + off + dirs[0]
+ n = struct.unpack_from("<H", p, q + 6)[0]
+ out[a] = list(struct.unpack_from(f"<{n}H", p, q + 8))
+ return out
+
+ def picture(self, h):
+ """a picture by its number, RGBA"""
+ fmt, w, hh, at, size = self.pics[h][:5]
+ raw = zlib.decompress(self.bank[at:at + size])
+ if fmt == 0:
+ return Image.frombytes("RGBA", (w, hh), raw[:w * hh * 4])
+ pitch = len(raw) // hh
+ return Image.frombytes("RGB", (w, hh), b"".join(raw[y * pitch:y * pitch + w * 3] for y in range(hh))).convert("RGBA")
+
+ def hotspot(self, h):
+ """a picture's hot spot: where an object placed at (x, y) has it"""
+ return self.pics[h][5:7]
+
+ def obj(self, name, frame=None):
+ """an object's number by its name (the one placed in that frame when several share it)"""
+ hits = [h for h, o in self.objects.items() if o[1] == name]
+ if frame is not None:
+ placed = {o for o, _, _ in self.frames[frame]}
+ hits = [h for h in hits if h in placed]
+ assert len(hits) == 1, (name, frame, hits)
+ return hits[0]
+
+ def anim(self, name, a=0, frame=None):
+ """an object's animation: its pictures' numbers"""
+ return self.objects[self.obj(name, frame)][2][a]
+
+ def placed(self, name, frame):
+ """where an object is placed in a frame (its first place)"""
+ o = self.obj(name, frame)
+ return next((x, y) for h, x, y in self.frames[frame] if h == o)
diff --git a/games/fnaf3/tools/codec.py b/games/fnaf3/tools/codec.py
new file mode 100644
index 00000000..cd60b260
--- /dev/null
+++ b/games/fnaf3/tools/codec.py
@@ -0,0 +1,249 @@
+"""Five Nights at Freddy's: the pictures' codec (src/pic.c decodes it).
+
+The game's pictures are dark, grainy renders: what keeps them small is what JPEG does, so this is JPEG's
+baseline coding without its file format. A picture is a grid of 16 x 16 squares (MCUs): YCbCr, the colours at
+half resolution (4:2:0), each 8 x 8 block cosine-transformed, quantized and Huffman-coded (JPEG's run/size
+symbols and tables, one set for the whole game). Every square stands alone, starting on a byte, with no DC
+prediction from the one before it (only between the four Y blocks of a square), so the game decodes only the
+squares on screen, and pictures share squares: a camera with Bonnie in it is the empty camera's squares but
+where he stands, the frames of a jumpscare share what doesn't move, and squares that come out the same anywhere
+are stored once."""
+import heapq
+
+import numpy as np
+
+ZIGZAG = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,
+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63]
+STD_LUMA = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99]
+STD_CHROMA = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99] + [99] * 32
+# libjpeg's "ifast" IDCT folds these scales into the quantization table (src/pic.c)
+AANSCALES = [16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 22725, 31521, 29692, 26722, 22725, 17855, 12299,
+ 6270, 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, 19266, 26722, 25172, 22654, 19266, 15137,
+ 10426, 5315, 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 12873, 17855, 16819, 15137, 12873,
+ 10114, 6967, 3552, 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, 4520, 6270, 5906, 5315, 4520,
+ 3552, 2446, 1247]
+LUT_BITS = 9
+
+
+def qtable(base, quality):
+ s = 5000 / quality if quality < 50 else 200 - 2 * quality
+ return np.array([min(255, max(1, int((b * s + 50) // 100))) for b in base], dtype=np.float64)
+
+
+def dct_matrix():
+ c = np.zeros((8, 8))
+ for k in range(8):
+ for n in range(8):
+ c[k, n] = (np.sqrt(1 / 8) if k == 0 else np.sqrt(2 / 8)) * np.cos((2 * n + 1) * k * np.pi / 16)
+ return c
+
+
+DCT = dct_matrix()
+
+
+def ycbcr(rgb):
+ """an H x W x 3 picture (0-255) -> Y (H x W), Cb and Cr (H/2 x W/2), all level-shifted (-128)"""
+ r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
+ y = 0.299 * r + 0.587 * g + 0.114 * b - 128
+ cb = -0.168736 * r - 0.331264 * g + 0.5 * b
+ cr = 0.5 * r - 0.418688 * g - 0.081312 * b
+ h, w = y.shape
+ cb = cb.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))
+ cr = cr.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))
+ return y, cb, cr
+
+
+def blocks_of(plane):
+ """an H x W plane -> (H/8, W/8, 8, 8) of its DCT coefficients"""
+ h, w = plane.shape
+ b = plane.reshape(h // 8, 8, w // 8, 8).transpose(0, 2, 1, 3)
+ return np.einsum("ij,abjk,lk->abil", DCT, b, DCT)
+
+
+def quantize(coef, q, deadzone):
+ """coefficients (..., 8, 8) / a natural-order table, rounded toward 0 a little (deadzone) on the AC ones"""
+ x = coef / q.reshape(8, 8)
+ r = np.sign(x) * np.floor(np.abs(x) + 0.5 - deadzone)
+ r[..., 0, 0] = np.round(x[..., 0, 0])
+ return np.maximum(r, 0 * r - 2047).clip(-2047, 2047).astype(np.int32)
+
+
+def size_of(v):
+ v = abs(int(v))
+ n = 0
+ while v:
+ n += 1
+ v >>= 1
+ return n
+
+
+def bits_of(v, n):
+ return v if v >= 0 else v + (1 << n) - 1
+
+
+def block_symbols(zz, pred):
+ """one block's coefficients in zigzag order -> [(table: 0 DC 1 AC, symbol, extra bits value, extra bits count)]"""
+ out = []
+ d = int(zz[0]) - pred
+ s = size_of(d)
+ out.append((0, s, bits_of(d, s), s))
+ run = 0
+ last = 63
+ while last > 0 and zz[last] == 0:
+ last -= 1
+ for k in range(1, last + 1):
+ v = int(zz[k])
+ if v == 0:
+ run += 1
+ continue
+ while run > 15:
+ out.append((1, 0xF0, 0, 0))
+ run -= 16
+ s = size_of(v)
+ out.append((1, run << 4 | s, bits_of(v, s), s))
+ run = 0
+ if last < 63:
+ out.append((1, 0x00, 0, 0))
+ return out
+
+
+def mcu_symbols(yq, cbq, crq):
+ """the quantized blocks of one square: 4 Y (8 x 8 each, natural order), Cb, Cr -> [(component class, ...)]"""
+ syms = []
+ pred = 0
+ for b in yq:
+ zz = b.reshape(64)[ZIGZAG]
+ syms += [(0,) + s for s in block_symbols(zz, pred)]
+ pred = int(zz[0])
+ for b in (cbq, crq):
+ zz = b.reshape(64)[ZIGZAG]
+ syms += [(1,) + s for s in block_symbols(zz, 0)]
+ return syms
+
+
+def huffman_lengths(freq):
+ """symbol -> frequency, to code lengths of at most 16 bits (JPEG's Annex K.2 and K.3)"""
+ # a symbol of its own takes the all-ones code, which JPEG never uses (the padding is ones)
+ f = {s: float(c) for s, c in freq.items() if c > 0}
+ f[256] = 0.5
+ syms = list(f)
+ heap = [(f[s], i, [s]) for i, s in enumerate(syms)]
+ heapq.heapify(heap)
+ length = {s: 0 for s in syms}
+ n = len(syms)
+ while len(heap) > 1:
+ f1, _, a = heapq.heappop(heap)
+ f2, _, b = heapq.heappop(heap)
+ for s in a + b:
+ length[s] += 1
+ n += 1
+ heapq.heappush(heap, (f1 + f2, n, a + b))
+ bits = [0] * 64
+ for s in syms:
+ bits[length[s]] += 1
+ i = 63
+ while i > 16:
+ while bits[i] > 0:
+ j = i - 2
+ while bits[j] == 0:
+ j -= 1
+ bits[i] -= 2
+ bits[i - 1] += 1
+ bits[j + 1] += 2
+ bits[j] -= 1
+ i -= 1
+ while bits[i] == 0:
+ i -= 1
+ bits[i] -= 1 # (the reserved code goes)
+ order = sorted(syms, key=lambda s: (length[s], s == 256, s))[:-1]
+ out = {}
+ k = 0
+ for ln in range(1, 17):
+ for _ in range(bits[ln]):
+ out[order[k]] = ln
+ k += 1
+ return out
+
+
+def canonical(lengths):
+ """symbol -> length to (symbol -> (code, length), BITS[1..16], HUFFVAL)"""
+ order = sorted(lengths, key=lambda s: (lengths[s], s))
+ bits = [0] * 17
+ for s in order:
+ bits[lengths[s]] += 1
+ codes = {}
+ code = 0
+ k = 0
+ for ln in range(1, 17):
+ for _ in range(bits[ln]):
+ codes[order[k]] = (code, ln)
+ code += 1
+ k += 1
+ code <<= 1
+ return codes, bits[1:], order
+
+
+def decode_tables(bits, vals):
+ """BITS and HUFFVAL -> the decoder's tables: a LUT_BITS lookup (length << 8 | symbol, 0 when longer), then
+ for the slow way JPEG's maxcode (17 int32, -1 when none) and valoffset (17 int32), then HUFFVAL (256 bytes)"""
+ lut = [0] * (1 << LUT_BITS)
+ maxcode = [-1] * 18
+ valoff = [0] * 18
+ code = 0
+ k = 0
+ for ln in range(1, 17):
+ n = bits[ln - 1]
+ if n:
+ valoff[ln] = k - code
+ for _ in range(n):
+ if ln <= LUT_BITS:
+ base = code << (LUT_BITS - ln)
+ for j in range(1 << (LUT_BITS - ln)):
+ lut[base + j] = ln << 8 | vals[k]
+ code += 1
+ k += 1
+ maxcode[ln] = code - 1
+ code <<= 1
+ maxcode[17] = 0x7FFFFFFF
+ out = b"".join(v.to_bytes(2, "little") for v in lut)
+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in maxcode)
+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in valoff)
+ out += bytes(vals) + bytes(256 - len(vals))
+ return out
+
+
+class BitWriter:
+ def __init__(self):
+ self.out = bytearray()
+ self.acc = 0
+ self.n = 0
+
+ def put(self, v, n):
+ if n == 0:
+ return
+ self.acc = self.acc << n | (v & ((1 << n) - 1))
+ self.n += n
+ while self.n >= 8:
+ self.n -= 8
+ self.out.append(self.acc >> self.n & 0xFF)
+ self.acc &= (1 << self.n) - 1
+
+ def flush(self):
+ """pads with ones (like JPEG) to a byte"""
+ if self.n:
+ self.put((1 << (8 - self.n)) - 1, 8 - self.n)
+ return bytes(self.out)
+
+
+def encode_mcu(syms, tables):
+ """a square's symbols -> its bytes; tables[component class][0 DC, 1 AC][symbol] = (code, length)"""
+ w = BitWriter()
+ for comp, tab, sym, val, n in syms:
+ code, ln = tables[comp][tab][sym]
+ w.put(code, ln)
+ w.put(val, n)
+ return w.flush()
diff --git a/games/fnaf3/tools/pack.py b/games/fnaf3/tools/pack.py
new file mode 100644
index 00000000..560d0543
--- /dev/null
+++ b/games/fnaf3/tools/pack.py
@@ -0,0 +1,533 @@
+#!/usr/bin/env python3
+"""Five Nights at Freddy's 3: its pictures and fonts -> src/data.bin + src/data.h.
+
+ python3 -I tools/pack.py [CCN] CCN: the game's application.ccn, from its Android package (res/raw); by
+ default ~/Documents/Assets/gamesrc/fnaf3/dl/application.ccn
+
+Every picture is the game's own, read from the application by tools/ccn.py, its objects placed where the game
+places them (an object's place is its picture's hot spot), at half size: the 1200 x 480 office is 600 x 240 here,
+and the calculator shows 320 of it. What is seen through the office's window (Springtrap, Phantom Freddy walking,
+Mangle) and the phantoms standing in the office are drawn into parts of the office (patches), as the game shows them.
+The cameras are its 507 x 399 at 304 x 240.
+
+data.bin: "FNF3", the number of sections, their offsets, then the sections (SEC_* in data.h):
+- HUFF: the four Huffman tables (Y DC, Y AC, colour DC, colour AC), 1424 bytes each (tools/codec.py)
+- QUANT: for each quality, the Y and colour tables (64 u16 each, natural order, scaled for the IDCT)
+- PICS: 12 bytes a picture (PIC_*): its width and height in 16 x 16 squares, its quality, 0, the picture it
+ shares squares with (u16, 0xFFFF none), how many squares it has of its own then (u16) and where its table
+ starts (u32)
+- TABLE: a whole picture's squares (3 bytes each: where in BANK), or a picture sharing another's: the squares
+ that differ (u16 the square's index, then 3 bytes)
+- BANK: the squares, each from a byte boundary
+- FONTS: for each font (FONT_*) its line height, baseline and 95 glyphs (32 to 126): advance, width, height,
+ x and y from the top of the line (s8), 0, the offset of its 4-bit alpha rows (u32, from the section)
+- IMGS: small pictures with alpha (IMG_*): width, height (u16), then 4-bit alpha (or 4-bit grey and alpha)"""
+import os
+import struct
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+import ccn # noqa: E402
+import codec as C # noqa: E402
+
+OUT_BIN = os.path.join(HERE, "..", "src", "data.bin")
+OUT_H = os.path.join(HERE, "..", "src", "data.h")
+ROOT = os.path.join(HERE, "..", "..", "..")
+CCN = os.path.expanduser("~/Documents/Assets/gamesrc/fnaf3/dl/application.ccn")
+SECTIONS = ["HUFF", "QUANT", "PICS", "TABLE", "BANK", "FONTS", "IMGS"]
+QUALITY = {"scene": 80, "scare": 70, "face": 76}
+FONT_DIRS = [os.environ.get("FONTS", ""), "/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/TTF",
+ "/usr/local/share/fonts", "/Library/Fonts", os.path.expanduser("~/Library/Fonts"),
+ os.path.expanduser("~/Documents/Assets/gamesrc/fonts/dejavu")]
+OW, OH = 600, 240 # the office here (the game's 1200 x 480 at half size)
+CW, CH = 304, 240 # a camera
+F = "Frame 1" # the night
+
+
+def find_font(name):
+ for d in FONT_DIRS:
+ p = os.path.join(d, name) if d else ""
+ if p and os.path.exists(p):
+ return p
+ raise SystemExit(f"pack: {name} not found (the DejaVu fonts; FONTS=<their folder>)")
+
+
+def font(size, bold=False, mono=False):
+ name = "DejaVu" + ("SansMono" if mono else "Sans") + ("-Bold" if bold else "") + ".ttf"
+ return ImageFont.truetype(find_font(name), size)
+
+
+def pad16(a):
+ h, w = a.shape[:2]
+ H, W = -(-h // 16) * 16, -(-w // 16) * 16
+ return np.pad(a, ((0, H - h), (0, W - w), (0, 0)), mode="edge")
+
+
+def arr(im):
+ return np.asarray(im.convert("RGB")).astype(np.float64)
+
+
+# ------------------------------------------------------------------ pictures
+class Pic:
+ def __init__(self, name, a, quality, base=None, refs=()):
+ self.name, self.q, self.base = name, quality, base
+ self.w, self.h = a.shape[1], a.shape[0]
+ self.a = pad16(a)
+ self.refs = [r for r in ([base] if base else []) + list(refs) if r]
+ self.mw, self.mh = self.a.shape[1] // 16, self.a.shape[0] // 16
+
+
+PICS = []
+BY_NAME = {}
+
+
+def pic(name, a, quality="scene", base=None, refs=()):
+ p = Pic(name, np.clip(a, 0, 255), quality, base, refs)
+ PICS.append(p)
+ BY_NAME[name] = p
+ return p
+
+
+def same_square(a, b, strict):
+ d = np.abs(a - b)
+ return d.max() <= (6 if strict else 14) and d.mean() <= (1.2 if strict else 3.0)
+
+
+def encode_all():
+ qt = {k: (C.qtable(C.STD_LUMA, v), C.qtable(C.STD_CHROMA, v)) for k, v in QUALITY.items()}
+ qnames = list(QUALITY)
+ for p in PICS:
+ y, cb, cr = C.ycbcr(p.a)
+ ql, qc = qt[p.q]
+ yq = C.quantize(C.blocks_of(y), ql, 0.18)
+ cbq = C.quantize(C.blocks_of(cb), qc, 0.22)
+ crq = C.quantize(C.blocks_of(cr), qc, 0.22)
+ p.sq = []
+ for my in range(p.mh):
+ for mx in range(p.mw):
+ src = None
+ tile = p.a[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16]
+ for r in p.refs:
+ if mx < r.mw and my < r.mh and r.q == p.q:
+ if same_square(tile, r.a[my * 16:my * 16 + 16, mx * 16:mx * 16 + 16], r is not p.base):
+ src = r.sq[my * r.mw + mx]
+ break
+ if src is None:
+ blocks = [yq[2 * my + i, 2 * mx + j] for i in (0, 1) for j in (0, 1)]
+ src = ("own", tuple(C.mcu_symbols(blocks, cbq[my, mx], crq[my, mx])))
+ p.sq.append(src)
+ freq = [[{}, {}], [{}, {}]]
+ seen = set()
+ for p in PICS:
+ for s in p.sq:
+ if id(s) in seen:
+ continue
+ seen.add(id(s))
+ for comp, tab, sym, _, _ in s[1]:
+ f = freq[comp][tab]
+ f[sym] = f.get(sym, 0) + 1
+ tables, huff = [[None, None], [None, None]], b""
+ for comp in (0, 1):
+ for tab in (0, 1):
+ codes, bits, vals = C.canonical(C.huffman_lengths(freq[comp][tab]))
+ tables[comp][tab] = codes
+ huff += C.decode_tables(bits, vals)
+ bank, where, by_id = bytearray(), {}, {}
+ for p in PICS:
+ p.off = []
+ for s in p.sq:
+ if id(s) not in by_id:
+ data = C.encode_mcu(s[1], tables)
+ if data not in where:
+ where[data] = len(bank)
+ bank += data
+ by_id[id(s)] = where[data]
+ p.off.append(by_id[id(s)])
+ bank += bytes(8)
+ assert len(bank) < 1 << 24
+ quant = b""
+ for k in qnames:
+ for t in qt[k]:
+ quant += b"".join(struct.pack("<H", (int(t[i]) * C.AANSCALES[i] + 2048) >> 12) for i in range(64))
+ pics, table = b"", bytearray()
+ for p in PICS:
+ diff = []
+ if p.base:
+ b = p.base
+ assert (b.mw, b.mh) == (p.mw, p.mh) and not b.base
+ diff = [k for k in range(len(p.off)) if p.off[k] != b.off[k]]
+ if p.base and 5 * len(diff) < 3 * len(p.off):
+ pics += struct.pack("<BBBBHHI", p.mw, p.mh, qnames.index(p.q), 0, PICS.index(b), len(diff), len(table))
+ for k in diff:
+ table += struct.pack("<H", k) + p.off[k].to_bytes(3, "little")
+ else:
+ pics += struct.pack("<BBBBHHI", p.mw, p.mh, qnames.index(p.q), 0, 0xFFFF, 0, len(table))
+ for o in p.off:
+ table += o.to_bytes(3, "little")
+ print(f"pictures: {len(PICS)}, squares {len(bank)} bytes, tables {len(table)} bytes")
+ return huff, quant, pics, bytes(table), bytes(bank)
+
+
+# ------------------------------------------------------------------ fonts and small pictures
+def nibbles(alpha):
+ h, w = alpha.shape
+ out = bytearray()
+ for r in range(h):
+ row = list(alpha[r]) + [0]
+ for c in range(0, w, 2):
+ out.append(int(row[c]) | int(row[c + 1]) << 4)
+ return bytes(out)
+
+
+def to4(a):
+ return np.clip(np.round(np.asarray(a, dtype=np.float64) / 255 * 15), 0, 15).astype(np.uint8)
+
+
+def ttf_font(f, line=None):
+ asc, desc = f.getmetrics()
+ line = line or asc + desc
+ glyphs = []
+ for c in range(32, 127):
+ ch = chr(c)
+ adv = int(round(f.getlength(ch)))
+ box = f.getbbox(ch)
+ if box[2] <= box[0] or ch == " ":
+ glyphs.append((adv, 0, 0, 0, 0, b""))
+ continue
+ im = Image.new("L", (box[2] - box[0], box[3] - box[1]))
+ ImageDraw.Draw(im).text((-box[0], -box[1]), ch, font=f, fill=255)
+ glyphs.append((adv, im.width, im.height, box[0], box[1], nibbles(to4(np.asarray(im)))))
+ return line, asc, glyphs
+
+
+def pack_fonts(fonts):
+ blobs = []
+ for line, asc, glyphs in fonts:
+ b = struct.pack("<BBBB", line, asc, 32, 95)
+ rows, offs = b"", []
+ for adv, w, h, x, y, r in glyphs:
+ offs.append(len(rows))
+ rows += r
+ g0 = len(b) + 12 * 95
+ for (adv, w, h, x, y, r), o in zip(glyphs, offs):
+ b += struct.pack("<BBBbbBHI", adv, w, h, x, y, 0, 0, g0 + o)
+ blobs.append(b + rows)
+ out = struct.pack("<I", len(fonts))
+ p = 4 + 4 * len(fonts)
+ for b in blobs:
+ out += struct.pack("<I", p)
+ p += len(b)
+ return out + b"".join(blobs)
+
+
+DEFINES = []
+
+
+def define(name, value):
+ DEFINES.append((name, value))
+
+
+IMGS = []
+
+
+def img(name, alpha):
+ a = to4(alpha)
+ h, w = a.shape
+ define(f"IMG_{name}", len(IMGS))
+ IMGS.append(struct.pack("<HHBBH", w, h, 0, 0, 0) + nibbles(a))
+
+
+def pack_imgs():
+ out = struct.pack("<I", len(IMGS))
+ p = 4 + 4 * len(IMGS)
+ for d in IMGS:
+ out += struct.pack("<I", p)
+ p += len(d) + (-len(d) % 4)
+ return out + b"".join(d + bytes(-len(d) % 4) for d in IMGS)
+
+
+
+
+def cover(im, w, h):
+ """im resized to fill w x h, its middle kept"""
+ s = max(w / im.width, h / im.height)
+ r = im.convert("RGB").resize((max(w, round(im.width * s)), max(h, round(im.height * s))), Image.LANCZOS)
+ x, y = (r.width - w) // 2, (r.height - h) // 2
+ return arr(r)[y:y + h, x:x + w]
+
+
+
+
+# ------------------------------------------------------------------ the game's objects, placed
+APP = None
+
+
+def sprite(name, anim=0, k=0, frame=F):
+ """an object's picture: (RGBA image, its hot spot)"""
+ h = APP.anim(name, anim, frame)[k]
+ return APP.picture(h), APP.hotspot(h)
+
+
+def frames_of(name, anim=0, frame=F):
+ return len(APP.anim(name, anim, frame))
+
+
+def put(canvas, name, x, y, anim=0, k=0, frame=F):
+ """the object's picture onto canvas (an RGBA image in office coordinates) with its hot spot at (x, y)"""
+ im, (hx, hy) = sprite(name, anim, k, frame)
+ layer = Image.new("RGBA", canvas.size)
+ layer.paste(im, (x - hx, y - hy))
+ canvas.alpha_composite(layer)
+
+
+def office(behind=(), front=(), red=False):
+ """the 1200 x 480 office as the game shows it: what is behind its window, the office, what stands in it"""
+ c = Image.new("RGBA", (1200, 480), (0, 0, 0, 255))
+ c.alpha_composite(APP.picture(1173)) # (the night's Backdrop: the hall behind the window)
+ for args in behind:
+ put(c, *args)
+ put(c, "foreground", 0, 0, 12 if red else 0)
+ for args in front:
+ put(c, *args)
+ return c
+
+
+def half(im):
+ return arr(im.convert("RGB").resize((im.width // 2, im.height // 2), Image.LANCZOS))
+
+
+def box16(x0, y0, x1, y1):
+ """a rectangle of the half-size office, out to whole 16 x 16 squares"""
+ x0, y0 = max(0, x0 // 2 // 16 * 16), max(0, y0 // 2 // 16 * 16)
+ x1, y1 = min(OW, -(-(x1 // 2) // 16) * 16), min(OH, -(-(y1 // 2) // 16) * 16)
+ return x0, y0, x1 - x0, y1 - y0
+
+
+PATCH = {}
+
+
+def patch(name, part, a, base=None):
+ x, y, w, h = PATCH[part]
+ return pic(name, a[y:y + h, x:x + w], base=base)
+
+
+def office_pictures():
+ o = pic("OFFICE", half(office()))
+ pic("OFFICE_RED", half(office(red=True)), base=o)
+ # the window: what is behind the glass (the game's window is x 505..1000, y 76..257)
+ PATCH["WIN"] = box16(500, 60, 1010, 270)
+ base = patch("WIN_SPRING", "WIN", half(office(behind=[("inwindow", 896, 234)])))
+ # Springtrap running past the window (stage 2): 269 px left at path speed 70 (31 frames), 8 pictures
+ n = frames_of("run past")
+ for k in range(n):
+ x = 1031 - 269 * k // (n - 1) # (created at the window, inwindow +135)
+ patch(f"WIN_RUN{k}", "WIN", half(office(behind=[("run past", x, 432, 0, k)])), base=base)
+ define("RUN_N", n)
+ # Phantom Freddy walking left behind the window from (1011, 90), 733 px, 8 pictures a cycle; a patch every
+ # 8 px where he can be seen
+ steps = []
+ for x in range(1011, 1011 - 734, -8):
+ im, (hx, hy) = sprite("fwalk", 0, 0)
+ if x - hx + im.width < 505 or x - hx > 1000:
+ continue
+ steps.append(x)
+ for i, x in enumerate(steps):
+ k = (1011 - x) // 8 % frames_of("fwalk")
+ patch(f"WIN_FREDDY{i}", "WIN", half(office(behind=[("fwalk", x, 90, 0, k)])), base=base)
+ define("FREDDY_X0", steps[0])
+ define("FREDDY_N", len(steps))
+ # his lunge where he stands (anim 12, 11 pictures), for every place he can be seen: drawn from the nearest
+ for k in range(frames_of("fwalk", 12)):
+ patch(f"WIN_FLUNGE{k}", "WIN", half(office(behind=[("fwalk", 900, 90, 12, k)])), base=base)
+ define("FLUNGE_N", frames_of("fwalk", 12))
+ # Mangle in the window, rising 100 px from (694, 326): a patch every 10 px
+ for i in range(11):
+ patch(f"WIN_MANGLE{i}", "WIN", half(office(behind=[("mangle 2", 694, 326 - 10 * i)])), base=base)
+ # standing in the office: Springtrap at the left door (head), hiding there, BB, Chica, Foxy
+ PATCH["DOOR"] = box16(0, 80, 260, 410)
+ d = patch("DOOR_HEAD", "DOOR", half(office(front=[("head", 78, 236)])))
+ for k in range(frames_of("hide")):
+ patch(f"DOOR_HIDE{k}", "DOOR", half(office(front=[("hide", 58, 231, 0, k)])), base=d)
+ define("HIDE_N", frames_of("hide"))
+ PATCH["BB"] = box16(730, 110, 1040, 480)
+ first = None
+ seq = [(0, k) for k in range(frames_of("BB scare"))] + [(12, k) for k in range(frames_of("BB scare", 12))]
+ for i, (an, k) in enumerate(seq):
+ p = patch(f"BB{i}", "BB", half(office(front=[("BB scare", 590, 77, an, k)])), base=first)
+ first = first or p
+ define("BB_N", len(seq))
+ PATCH["CHICA"] = box16(150, 60, 700, 480)
+ first = None
+ seq = [(0, 0)] + [(12, k) for k in range(frames_of("chica 2", 12))]
+ for i, (an, k) in enumerate(seq):
+ p = patch(f"CHICA{i}", "CHICA", half(office(front=[("chica 2", 40, 18, an, k)])), base=first)
+ first = first or p
+ define("CHICA_N", len(seq))
+ PATCH["FOXY"] = box16(350, 20, 560, 480)
+ first = None
+ seq = [(0, 0)] + [(12, k) for k in range(frames_of("foxy", 12))]
+ for i, (an, k) in enumerate(seq):
+ p = patch(f"FOXY{i}", "FOXY", half(office(front=[("foxy", 455, 471, an, k)])), base=first)
+ first = first or p
+ define("FOXY_N", len(seq))
+ for part, (x, y, w, h) in PATCH.items():
+ define(f"{part}_X", x), define(f"{part}_Y", y), define(f"{part}_W", w), define(f"{part}_H", h)
+
+
+def view(im, xc):
+ """the screen when the game's view is centred on office x xc: 640 of its 800 (the calculator's 320)"""
+ a = half(im)
+ x = max(0, min(OW - 320, (xc - 320) // 2))
+ return a[:, x:x + 320]
+
+
+def scare_pictures():
+ # Springtrap's lunge: at 00 anchor 2 (-4, -77) from the door (the view pushed to x 512), (542, -80) from the
+ # right (the view where the monitor was, 812)
+ for side, (dx, dy, xc) in (("L", (-4, -77, 512)), ("R", (542, -80, 812))):
+ first = prev = None
+ for k in range(frames_of("jumpscare")):
+ p = pic(f"JUMP{side}{k}", view(office(front=[("jumpscare", dx, dy, 0, k)]), xc), "scare", base=first,
+ refs=[prev] if prev else [])
+ first, prev = first or p, p
+ define("JUMP_N", frames_of("jumpscare"))
+ # Phantom Freddy's scare, on the screen (00 anchor: the screen's corner), over the dark office
+ first = prev = None
+ for k in range(frames_of("fscare")):
+ c = Image.new("RGBA", (800, 480), (0, 0, 0, 255))
+ put(c, "fscare", 0, 0, 0, k)
+ a = half(c)[:, 40:360]
+ p = pic(f"FSCARE{k}", a, "scare", base=first, refs=[prev] if prev else [])
+ first, prev = first or p, p
+ define("FSCARE_N", frames_of("fscare"))
+
+
+# the camera feed's animations the night shows (fnaf3_spec 7.5): rooms empty, with Springtrap, the vents,
+# Mangle, the Puppet and Chica
+FEEDS = [12, 13, 14, 15, 16, 17, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 43] + list(range(45, 58))
+
+
+def camera_pictures():
+ for an in FEEDS:
+ for k in range(len(APP.anim("camera screen", an, F))):
+ pic(f"FEED{an}_{k}", cover(sprite("camera screen", an, k)[0], CW, CH))
+ define(f"FEED{an}_N", len(APP.anim("camera screen", an, F)))
+ pic("BBPEEK", cover(sprite("BBpeek")[0], CW, CH), "scare")
+
+
+def alpha_of(im, scale):
+ """an RGBA picture's brightness times alpha, scaled, for IMGS"""
+ im = im.resize((max(1, round(im.width * scale)), max(1, round(im.height * scale))), Image.LANCZOS)
+ a = np.asarray(im).astype(np.float64)
+ return a[..., 3] * a[..., :3].max(axis=2) / 255
+
+
+MAP_SCALE = 0.37
+MAP_X, MAP_Y = 152, 86 # the map's corner on the monitor
+
+
+def map_imgs():
+ for an, nm in ((0, "MAP"), (12, "VENTMAP")):
+ img(nm, alpha_of(sprite("map", an)[0], MAP_SCALE))
+ define("MAP_X", MAP_X), define("MAP_Y", MAP_Y)
+ # the buttons: centres on the map (the game's office coordinates less the map's corner (779, 82))
+ for n in [f"{i:02d}" for i in range(1, 11)] + [f"cam {i}" for i in range(11, 16)]:
+ x, y = APP.placed(n, F)
+ nm = n.replace("cam ", "")
+ define(f"BTN{nm}_X", MAP_X + round((x - 779) * MAP_SCALE))
+ define(f"BTN{nm}_Y", MAP_Y + round((y - 82) * MAP_SCALE))
+ for i in range(11, 16):
+ x, y = APP.placed(f"vent {i}", F)
+ define(f"SEAL{i}_X", MAP_X + round((x - 779) * MAP_SCALE))
+ define(f"SEAL{i}_Y", MAP_Y + round((y - 82) * MAP_SCALE))
+
+
+def panel_imgs():
+ s = 320 / 560
+ for nm, obj in (("P_AUDIO", "audio text"), ("P_CAMERA", "camera text"), ("P_VENT", "ventilation text"),
+ ("P_ALL", "reboot all text"), ("P_EXIT", "exit text"), ("P_CURSOR", "cursor")):
+ img(nm, alpha_of(sprite(obj)[0], s))
+ img("P_ERROR", alpha_of(sprite("audio error")[0], s))
+ for k in range(frames_of("progress bar")):
+ img(f"P_DOTS{k}", alpha_of(sprite("progress bar", 0, k)[0], s))
+ define("DOTS_N", frames_of("progress bar"))
+ for nm, obj in (("M_AUDIO", "audio message"), ("M_VIDEO", "video message"), ("M_VENT", "ventilation error 2")):
+ img(nm, alpha_of(sprite(obj)[0], 0.5))
+ pic("PANEL", cover(sprite("screen2")[0], 320, 240), "face")
+
+
+def head_imgs():
+ """the Puppet's head, in front of everything (grey)"""
+ seq = [(0, 0)] + [(12, k) for k in range(3)] + [(13, 0)]
+ for i, (an, k) in enumerate(seq):
+ img(f"PHEAD{i}", alpha_of(sprite("phantom head", an, k)[0], 0.5))
+
+
+def screens():
+ pic("GAMEOVER", cover(APP.picture(1062), 320, 240), "face")
+ pic("BADEND", cover(APP.picture(1091), 320, 240), "face")
+ pic("GOODEND", cover(APP.picture(1093), 320, 240), "face")
+ pic("THEEND", cover(APP.picture(1095), 320, 240), "face")
+ t = APP.anim("Active 2", 0, "title")
+ pic("TITLE", cover(APP.picture(t[0]), 320, 240), "face")
+ for an in (12, 13, 14, 15):
+ pic(f"TITLE{an}", cover(APP.picture(APP.anim("Active 2", an, "title")[0]), 320, 240), "face")
+ img("STAR", alpha_of(APP.picture(840), 0.5))
+
+
+def icon():
+ sys.path.insert(0, os.path.join(ROOT, "tools"))
+ from make_icon import corner_mask
+ im = APP.picture(APP.anim("Active 2", 0, "title")[0]).convert("RGB")
+ s = min(im.width, im.height)
+ face = im.crop(((im.width - s) // 2, 0, (im.width + s) // 2, s)).resize((55, 56), Image.LANCZOS)
+ face.putalpha(corner_mask(55, 56))
+ face.save(os.path.join(HERE, "..", "src", "icon.png"), optimize=True)
+
+
+def main():
+ global APP
+ APP = ccn.App(sys.argv[1] if len(sys.argv) > 1 else CCN)
+ office_pictures()
+ scare_pictures()
+ camera_pictures()
+ screens()
+ map_imgs()
+ panel_imgs()
+ head_imgs()
+ icon()
+ huff, quant, pics, table, bank = encode_all()
+ fonts = [
+ ttf_font(font(11, bold=True, mono=True)), # FONT_HUD
+ ttf_font(font(17, mono=True)), # FONT_BIG
+ ttf_font(font(11)), # FONT_TEXT
+ ttf_font(font(24, bold=True)), # FONT_CLOCK
+ ttf_font(font(24, mono=True)), # FONT_HUGE
+ ]
+ sections = [huff, quant, pics, table, bank, pack_fonts(fonts), pack_imgs()]
+ head = b"FNF3" + struct.pack("<I", len(sections))
+ offs, p = [], len(head) + 4 * len(sections)
+ for s in sections:
+ offs.append(p)
+ p += len(s) + (-len(s) % 4)
+ out = head + b"".join(struct.pack("<I", o) for o in offs)
+ for s in sections:
+ out += s + bytes(-len(s) % 4)
+ open(OUT_BIN, "wb").write(out)
+ h = ["/* Made by tools/pack.py: what is in data.bin. */", "#ifndef FNAF3_DATA_H", "#define FNAF3_DATA_H", ""]
+ h += [f"#define SEC_{n} {i}" for i, n in enumerate(SECTIONS)]
+ h += [f"#define PIC_{p.name} {i}" for i, p in enumerate(PICS)]
+ h += [f"#define PIC_COUNT {len(PICS)}"]
+ h += [f"#define FONT_{n} {i}" for i, n in enumerate(["HUD", "BIG", "TEXT", "CLOCK", "HUGE"])]
+ h += [f"#define {n} {v}" for n, v in DEFINES]
+ h += ["", "#endif", ""]
+ open(OUT_H, "w").write("\n".join(h))
+ print(f"data.bin: {len(out)} bytes")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/games.json b/games/games.json
index 22818a12..d0f00eca 100644
--- a/games/games.json
+++ b/games/games.json
@@ -1385,6 +1385,28 @@
"default": false,
"xl": true
},
+ {
+ "id": "fnaf3",
+ "rank": 35,
+ "title": "Five Nights at Freddy's 3",
+ "tagline": "Survive Fazbear's Fright",
+ "credit": "Based on the game by Scott Cawthon",
+ "top": "0x2E3A22",
+ "bottom": "0x080C06",
+ "accent": "0x8FBF4A",
+ "colors": 16,
+ "records": [
+ "fnaf3.sav",
+ "fnaf3res.sav",
+ "fnaf3_saves.py"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/fnaf3",
+ "default": false,
+ "xl": true
+ },
{
"id": "famidash",
"rank": 34,
diff --git a/tests/test_games.py b/tests/test_games.py
index cf88db12..2b10e089 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -304,6 +304,8 @@ GAMES = {
# paused: Back, and the night goes on
"fnaf2": ("FiveNightsAtFreddys2.nwa", "fnaf2res.sav", presses((1500, "down"), (1800, "ok")), 9000,
presses((1500, "back")), 5000),
+ # New Game: the first night's card, then the office; Home keeps the night, the next start is back in it, paused
+ "fnaf3": ("FiveNightsAtFreddys3.nwa", "fnaf3res.sav", presses((1500, "ok")), 9000, presses((1500, "back")), 5000),
# how to play (the first time: two pages), Play, Stereo Madness, OK held to jump, Back to pause; Home keeps the
# guide read and the time played. Next time, from the copy, Play straight away, quit with On/Off
"famidash": ("Famidash.nwa", "famidash.sav",
@@ -380,7 +382,7 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p
"angrybirds": "angrybirds_saves.py", "polytrack": "polytrack_saves.py", "paperclips": "paperclips_saves.py",
"badtime": "badtime_saves.py", "mahjong": "mahjong_saves.py",
"rider": "rider_saves.py", "snowrider": "snowrider_saves.py", "templerun": "templerun_saves.py",
- "fnaf2": "fnaf2_saves.py", "famidash": "famidash_saves.py"}
+ "fnaf2": "fnaf2_saves.py", "fnaf3": "fnaf3_saves.py", "famidash": "famidash_saves.py"}
def paperclips_ok(v):
@@ -638,6 +640,9 @@ CHECKS = {
# the night kept ("FNF2", its seconds at 96); after the reinstall, from the copy, it goes on
"fnaf2": (lambda v: v[:4] == b"FNF2" and struct.unpack_from("<f", v, 96)[0] > 2,
lambda v: v[:4] == b"FNF2" and struct.unpack_from("<f", v, 96)[0] > 6.5),
+ # the night kept ("FNF3", its steps at 148); after the reinstall, from the copy, it goes on
+ "fnaf3": (lambda v: v[:4] == b"FNF3" and struct.unpack_from("<I", v, 148)[0] > 120,
+ lambda v: v[:4] == b"FNF3" and struct.unpack_from("<I", v, 148)[0] > 300),
# "FMD1", version 1: how to play read (flags at 5), time played (564); after the reinstall, from the copy, more
"famidash": (lambda v: famidash_ok(v) and v[5] & 1 and struct.unpack_from("<I", v, 2100)[0] >= 7000,
lambda v: famidash_ok(v) and v[5] & 1 and struct.unpack_from("<I", v, 2100)[0] >= 12000),
diff --git a/tools/release.py b/tools/release.py
index 45b49743..5470378b 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -61,6 +61,7 @@ ALONE = {
"snowrider": ("Snow Rider 3D", "the endless sled run: its slope, sleds, gifts and crashes, read from the game's own Unity project"),
"templerun": ("Temple Run", "the endless run from the temple: turn, jump, slide and lean, with the game's rules and numbers"),
"fnaf2": ("Five Nights at Freddy's 2", "the new pizzeria's six nights and the Custom Night: the mask, the music box, the flashlight"),
+ "fnaf3": ("Five Nights at Freddy's 3", "Fazbear's Fright's six nights with Springtrap and the phantoms: the lure, the vents, the maintenance panel"),
"famidash": ("Famidash", "TFDSoft's Geometry Dash for the NES, made for the calculator: the 173 levels of Famidash HUGE, every mode, practice mode"),
}
VARIANTS = [