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 2: six nights and the Custom Night, on its own

Mason363aac17aa88691
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 5b09ef53..0bd62e22 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -100,6 +100,7 @@ jobs:
make -C games/rider host test
make -C games/snowrider host test
make -C games/templerun host test
+ make -C games/fnaf2 host test
diff --git a/Makefile b/Makefile
index 14cccffc..938c1229 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 finalearth2 flappybird flappydunk fnaf 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 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_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
+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
# 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
@@ -333,6 +333,7 @@ APP_mahjong = $(B)/games/mahjong/mahjong.nwa:Mahjong.nwa
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
# the big games' modules are made from these (the kit)
$(foreach g,$(XL_GAMES),$(eval MOD_$(g) = $$(word 1,$$(subst :, ,$$(APP_$(g))))))
@@ -377,6 +378,7 @@ apps: | $(B)
$(MAKE) -C games/rider build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/rider
$(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
cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
cp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))
cp $(word 1,$(subst :, ,$(APP_crossyroad))) $(B)/apps/$(word 2,$(subst :, ,$(APP_crossyroad)))
@@ -419,6 +421,7 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_rider))) $(B)/apps/$(word 2,$(subst :, ,$(APP_rider)))
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)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
STD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))
@@ -502,5 +505,6 @@ clean:
-$(MAKE) -C games/rider clean
-$(MAKE) -C games/snowrider clean
-$(MAKE) -C games/templerun clean
+ -$(MAKE) -C games/fnaf2 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 d5df077e..52d7a2d3 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 32 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.
+ Plus 33 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.
</p>
<p align="center">
@@ -149,9 +149,10 @@ These are too big to fit next to NumPlay, so each one is its own app. Install it
<tr>
<td align="center"><a href="games/snowrider/README.md"><img src="docs/media/thumb_snowrider.png" width="200" alt="Snow Rider 3D"><br><b>Snow Rider 3D</b></a><br><sub>The endless sled run: its slope, 11 sleds and gifts to buy them</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/SnowRider3D.nwa">Download</a></td>
<td align="center"><a href="games/templerun/README.md"><img src="docs/media/thumb_templerun.png" width="200" alt="Temple Run"><br><b>Temple Run</b></a><br><sub>Run from the temple: turn, jump, slide and lean</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/TempleRun.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="games/fnaf2/README.md"><img src="docs/media/thumb_fnaf2.png" width="200" alt="Five Nights at Freddy's 2"><br><b>Five Nights at Freddy's 2</b></a><br><sub>The new pizzeria: six nights, the mask, the music box and the Custom Night</sub><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddys2.nwa">Download</a></td>
</tr>
<tr>
+ <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>
<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>
@@ -306,6 +307,7 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
- [x] Meowdoku
- [x] Rider
- [x] Temple Run
+- [x] Five Nights at Freddy's 2
- [ ] Full Minecraft 1.18.2 as a standalone app
- [ ] Among Us, against bots
- [ ] Cat Ninja
@@ -328,7 +330,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, Mega Drive, SG-1000 and ColecoVision
-- [ ] Five Nights at Freddy's 2, 3, 4 and FNAF World
+- [ ] Five Nights at Freddy's 3, 4 and FNAF World
- [ ] Brawl Stars, against bots
- [ ] Papers, Please, with the story and Endless
- [ ] Mario Kart
@@ -388,6 +390,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
- **Snow Rider 3D** inspired NumPlay's Snow Rider 3D, which makes its slope, sleds, gifts and camera the way the game does, with its models, colours, numbers and logo read from its Unity project ([q8j-dev/snow-rider-3d](https://github.com/q8j-dev/snow-rider-3d)). **[dennisimoo](https://github.com/dennisimoo)** brought it to NumPlay. Not affiliated with its makers.
- **Temple Run** by Imangi Studios inspired NumPlay's Temple Run, which follows the game's rules and numbers (its path, piece for piece, and its pacing, speeds, coins, power-ups, upgrades and objectives) and uses its own models (Guy Dangerous, the demon monkeys, the path, the coins and the scenery, with fewer triangles), all read from its Android package (version 1.0.8), and the **Lilita One** font (SIL Open Font License, [license](LICENSES/OFL-1.1-LilitaOne.txt)). Not affiliated with Imangi Studios.
- **[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, as the fan port [fnaf-2_html5](https://github.com/VocalNutria9174/fnaf-2_html5) (VocalNutria9174) keeps them, 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.
- **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.
@@ -416,7 +419,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), SEGA (Sonic the Hedgehog, Master System, Game Gear), 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), 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). 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 and Game Gear 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), SEGA (Sonic the Hedgehog, Master System, Game Gear), 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), 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). 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 and Game Gear 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
@@ -524,5 +527,6 @@ NumPlay is licensed under the [GNU General Public License v3.0](LICENSE). Copyri
<tr>
<td align="center"><img src="docs/media/gallery/snowrider.gif" alt="Snow Rider 3D: sledding through the snowmen and stumps"><br><a href="games/snowrider/README.md"><b>Snow Rider 3D</b></a></td>
<td align="center"><img src="docs/media/gallery/templerun.gif" alt="Temple Run: a run along the temple path, a corner, a gap jumped, coins"><br><a href="games/templerun/README.md"><b>Temple Run</b></a></td>
+ <td align="center"><img src="docs/media/gallery/fnaf2.gif" alt="Five Nights at Freddy's 2: the music box wound on CAM 11, a light down the hallway, the mask on as someone comes in"><br><a href="games/fnaf2/README.md"><b>Five Nights at Freddy's 2</b></a></td>
</tr>
</table>
diff --git a/_config.yml b/_config.yml
index 797613e8..5e0f9006 100644
--- a/_config.yml
+++ b/_config.yml
@@ -1,5 +1,5 @@
title: NumPlay
-description: "29 games for the NumWorks calculator in one app: NumDash, Crossy Road, NumBlocks, NumDrive, Balatro, Buckshot Roulette, Block Blast, Suika Game, Portal Returns, Tetris, Chrome Dino, Chess, Space Invaders, Sudoku and more. And Doom, Sonic, Plants vs. Zombies, Cookie Clicker, Mahjong, Meowdoku, Rider, Snow Rider 3D, Temple Run and more on their own. Free and open source, with a kit to make your own NumWorks games in C."
+description: "29 games for the NumWorks calculator in one app: NumDash, Crossy Road, NumBlocks, NumDrive, Balatro, Buckshot Roulette, Block Blast, Suika Game, Portal Returns, Tetris, Chrome Dino, Chess, Space Invaders, Sudoku and more. And Doom, Sonic, Plants vs. Zombies, Cookie Clicker, Mahjong, Meowdoku, Rider, Snow Rider 3D, Temple Run, Five Nights at Freddy's 2 and more on their own. Free and open source, with a kit to make your own NumWorks games in C."
url: https://mason363.github.io
baseurl: /NumPlay
theme: jekyll-theme-cayman
diff --git a/customize/app.js b/customize/app.js
index 01909dcf..cef3d381 100644
--- a/customize/app.js
+++ b/customize/app.js
@@ -398,7 +398,7 @@
// An app's .nwa becomes a game of NumPlay the way a big game's does (apps.js). It may only leave undefined what
// the calculator's installer gives an app (tools/kit.py's check) and what the launcher gives a big game (KIT_API)
const LOOSE = /^(eadk_|_heap_end$|_data_section_|_bss_section_|np_keyboard_scan$|np_event_get$|np_display_draw_string$|np_sbrk$|numplay_launcher$|__sf$|_printf_float$)/;
- const MAX_GAMES = 64; // (launcher/src/np.h's NP_MAX_GAMES: games, Retro-Go and apps)
+ const MAX_GAMES = 96; // (launcher/src/np.h's NP_MAX_GAMES: games, Retro-Go and apps)
const entries = () => ordered().length + (rg && st.roms.length ? 1 : 0) + st.apps.length;
const ascii = (t) => (t || '').replace(/[^\x20-\x7e]/g, '').trim().slice(0, 24);
const allocBytes = (obj) => npApps.readElf(obj).secs.reduce((n, x) => n + (x.flags & 2 && x.type !== 8 ? align4(x.size) : 0), 0);
diff --git a/docs/play.md b/docs/play.md
index a998c6fb..50e052af 100644
--- a/docs/play.md
+++ b/docs/play.md
@@ -736,6 +736,25 @@ Temple Run comes as its own app, `TempleRun.nwa`. Run from the temple and don't
<br clear="right">
+## Five Nights at Freddy's 2
+
+<img src="../games/fnaf2/docs/shot.png" width="320" align="right" alt="Five Nights at Freddy's 2: the office, the hallway ahead and a vent on each side">
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** (or 4 / 6) | Look left and right |
+| **5** or **Up**, held | The flashlight, down the hallway |
+| **7** / **9** (or 1 / 3), held | The left / right vent light |
+| **2** or **Down** | The Freddy mask on and off |
+| **OK** or **EXE** | The monitor up and down |
+| **0** to **9**, **Left / Right** | On the monitor: a camera (1 again: CAM 11, then 12) |
+| **Up**, held | On the monitor: the camera's light; on CAM 11, wind the music box |
+| **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.
+
+<br clear="right">
+
## Portal Returns
<img src="media/portal.gif" width="320" align="right" alt="Portal Returns: falling through a portal and flying across a test chamber">
diff --git a/games/fnaf2/.gitignore b/games/fnaf2/.gitignore
new file mode 100644
index 00000000..2bb66cc0
--- /dev/null
+++ b/games/fnaf2/.gitignore
@@ -0,0 +1,3 @@
+output/
+build/
+ref/
diff --git a/games/fnaf2/Makefile b/games/fnaf2/Makefile
new file mode 100644
index 00000000..b7b6beaa
--- /dev/null
+++ b/games/fnaf2/Makefile
@@ -0,0 +1,89 @@
+# Five Nights at Freddy's 2 on the NumWorks calculator.
+# make output/fnaf2.nwa
+# make check link it like the calculator does (output/fnaf2.bin)
+# make host build/play: the game on a computer, for tests and screenshots
+# make test the game played on a computer (tests/rules.c and tests/check.py, with the sanitizers)
+# make data src/data.bin and src/data.h from the pictures tools/fetch.py gathers
+# (REF=its folder, Python + Pillow + NumPy); make stand-ins: the stand-in pictures
+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
+REF ?=
+
+# 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 stand-ins
+build: $(BUILD_DIR)/fnaf2.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/fnaf2.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/fnaf2.bin
+ @echo "BIN $(BUILD_DIR)/fnaf2.bin: $$(wc -c < $(BUILD_DIR)/fnaf2.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)/fnaf2.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/play.c plays it with scripted keys and saves screenshots
+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/play build/pictures build/rules
+build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c src/data.S -lm -o $@
+ @echo "HOST $@"
+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
+ python3 tests/check.py build/play build/pictures
+
+data:
+ @test -n "$(REF)" || { echo "make data REF=<the folder tools/fetch.py filled>"; exit 1; }
+ python3 -I tools/pack.py $(REF)
+stand-ins:
+ python3 -I tools/pack.py
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/fnaf2/README.md b/games/fnaf2/README.md
new file mode 100644
index 00000000..91a7ab73
--- /dev/null
+++ b/games/fnaf2/README.md
@@ -0,0 +1,86 @@
+> **Five Nights at Freddy's 2 is a [NumPlay](../../README.md) game that comes on its own.** It is too big to sit next to NumPlay. Get `FiveNightsAtFreddys2.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 2 icon">
+</p>
+
+<h1 align="center">Five Nights at Freddy's 2</h1>
+
+<p align="center">
+ <b>Survive the night shift at the new Freddy Fazbear's Pizza, on the NumWorks calculator.</b><br>
+ Nights 1 to 6 and the Custom Night, with the mask, the music box and the flashlight.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/FiveNightsAtFreddys2.nwa"><b>Download FiveNightsAtFreddys2.nwa</b></a>
+ &nbsp;·&nbsp; <a href="#controls">Controls</a>
+</p>
+
+<p align="center">
+ <img src="../../docs/media/gallery/fnaf2.gif" width="320" alt="Five Nights at Freddy's 2: the music box wound on CAM 11, a light down the hallway, the mask on as someone comes in">
+</p>
+
+## Highlights
+
+* **The whole game:** nights 1 to 5, the 6th once the 5th is beaten, then the Custom Night with its ten animatronics and its ten modes, from 20/20/20/20 to Golden Freddy. The paycheck, the overtime check and the pink slip, and the stars on the title screen.
+* **The office as you know it:** no doors, a hallway in front and a vent on each side. Look left and right, light the hallway with the flashlight and the vents with their lights, and put on the Freddy mask.
+* **The twelve cameras,** the four party rooms and the two vents dark but for the camera's light, and the music box on CAM 11 to wind.
+* **Everyone, as the game moves them:** the Toys, the Withereds, Mangle, Balloon Boy, the Puppet and Golden Freddy, with the AI levels each night sets at its hours and the game's caps. A movement opportunity every 5 seconds, each on its own path through the building to the hallway or a vent.
+* **The mask, the light and the box:** whoever waits in the hallway or a vent comes in while the monitor is up, and is in the office when it comes down: the mask at once, or they get you. Mangle stays on the ceiling, Balloon Boy takes your lights, Withered Foxy only leaves for the flashlight, and the Puppet comes for anyone who lets the music box run down.
+* **What the game makes you hear, written down:** the vents banging, Balloon Boy's voice, Mangle's radio static, the music box's tune.
+* **Saved like in the game:** the night you reached, your stars and your last Custom Night. Home keeps the night as it is, and the next start puts you back in it, paused. Your saves are also copied into `fnaf2_saves.py`, so installing the app again doesn't erase them.
+
+<p align="center">
+ <img src="docs/shot.png" width="390" alt="The office">
+</p>
+
+## How to play
+
+New Game shows the newspaper and, the first time, which key does what. Then it is 12 AM and your shift starts. You have to last until 6 AM: an hour is a little over a minute.
+
+Keep the music box on CAM 11 wound, or the Puppet comes, and nothing stops it. The others come down the hallway or through the vents: light them, and when someone is there, put the mask on and wait for them to leave. Someone in the office when the monitor comes down? The mask, right away. Flash the hallway now and then: Withered Foxy waits there, and the mask doesn't fool him. The flashlight's battery doesn't come back during the night.
+
+Back pauses: from there you can go on, read how to play again, or quit the night.
+
+## Controls
+
+| Key | What it does |
+| --- | --- |
+| ← → or 4 6 | Look left and right |
+| 5 or ↑, held | The flashlight, down the hallway |
+| 7 or 1, held | The left vent light |
+| 9 or 3, held | The right vent light |
+| 2 or ↓ | The Freddy mask on and off |
+| OK or EXE | The monitor up and down (↓ also puts it down) |
+| 0 to 9 | On the monitor: that camera (0 is CAM 10); 1 again for CAM 11, then 12 |
+| ← → | On the monitor: the previous and next camera |
+| ↑, held | On the monitor: the camera's light; on CAM 11, wind the music box |
+| Back | Pause |
+| Home | Keep the night and quit |
+
+The vent keys turn you to that side first if you're looking the other way. On the title and the Custom Night, the arrows choose and OK starts.
+
+## Good to know
+
+* **One app at a time:** Five Nights at Freddy's 2 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 vents banging when someone crawls in or out, Balloon Boy's voice, Mangle's radio static, the music box's tune when the Puppet is out. The music box's warning sign is the game's.
+* **No calls:** each of the game's calls runs a minute or two. The night's card gives a short tip instead.
+* **Left out:** the minigames after a death and between nights, Shadow Freddy, Shadow Bonnie, the Endo, JJ and the prizes the Custom Night puts on the desk. None of them are part of surviving a night.
+* **A few numbers are the port's own,** where nobody has read them out of the game yet: the music box winds full in about 6 seconds, you get a second to put the mask on, a fooled visitor stays 4 seconds, Mangle in the office attacks 1 time in 3 the monitor comes down, and Withered Foxy leaves after 5 flashes.
+* **The pictures are the game's,** at 240 pixels high: the office turns a little further, as the screen is 4:3.
+
+## Credits
+
+Inspired by Five Nights at Freddy's 2 by Scott Cawthon, not affiliated with him.
+
+* The pictures come from the game, as VocalNutria9174's fan port [fnaf-2_html5](https://github.com/VocalNutria9174/fnaf-2_html5) keeps them. `tools/fetch.py` gets it, `tools/pack.py` makes them into `src/data.bin`.
+* How the animatronics move, their AI levels, the music box, the flashlight and Withered Foxy follow what the game's players read out of its events, as the [Technical FNaF Wiki](https://technicalfnaf.fandom.com) and the [Five Nights at Freddy's Wiki](https://freddy-fazbears-pizza.fandom.com) write them down.
+* The words are drawn in the DejaVu fonts ([license](../../LICENSES/DejaVu.txt)), and the paychecks with them.
+
+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/fnaf2/docs/shot.png b/games/fnaf2/docs/shot.png
new file mode 100644
index 00000000..82f9cfb1
Binary files /dev/null and b/games/fnaf2/docs/shot.png differ
diff --git a/games/fnaf2/src/data.S b/games/fnaf2/src/data.S
new file mode 100644
index 00000000..af1c26cc
--- /dev/null
+++ b/games/fnaf2/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 _fnaf2_data
+_fnaf2_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.fnaf2_data,"a"
+ .balign 4
+ .global fnaf2_data
+fnaf2_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/fnaf2/src/data.bin b/games/fnaf2/src/data.bin
new file mode 100644
index 00000000..c08d163e
Binary files /dev/null and b/games/fnaf2/src/data.bin differ
diff --git a/games/fnaf2/src/data.h b/games/fnaf2/src/data.h
new file mode 100644
index 00000000..e76bc91e
--- /dev/null
+++ b/games/fnaf2/src/data.h
@@ -0,0 +1,183 @@
+/* Made by tools/pack.py: what is in data.bin. */
+#ifndef FNAF2_DATA_H
+#define FNAF2_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 SEC_MAP 7
+#define PIC_OFFICE 0
+#define PIC_HALL_LIT 1
+#define PIC_HALL_TFFAR 2
+#define PIC_HALL_TF 3
+#define PIC_HALL_TC 4
+#define PIC_HALL_MANGLE 5
+#define PIC_HALL_WF 6
+#define PIC_HALL_WB 7
+#define PIC_HALL_FOXY 8
+#define PIC_HALL_GF 9
+#define PIC_LVENT_LIT 10
+#define PIC_LVENT_TC 11
+#define PIC_LVENT_BB 12
+#define PIC_RVENT_LIT 13
+#define PIC_RVENT_TB 14
+#define PIC_RVENT_MANGLE 15
+#define PIC_OCC_TF 16
+#define PIC_OCC_TB 17
+#define PIC_OCC_TC 18
+#define PIC_OCC_WF 19
+#define PIC_OCC_WB 20
+#define PIC_OCC_WC 21
+#define PIC_OCC_GF 22
+#define PIC_OFFICE_MANGLE 23
+#define PIC_OFFICE_BB 24
+#define PIC_CAM01_DARK 25
+#define PIC_CAM01_LIT 26
+#define PIC_CAM01_TC 27
+#define PIC_CAM01_WB 28
+#define PIC_CAM01_MANGLE 29
+#define PIC_CAM01_PUPPET 30
+#define PIC_CAM02_DARK 31
+#define PIC_CAM02_LIT 32
+#define PIC_CAM02_TB 33
+#define PIC_CAM02_WC 34
+#define PIC_CAM02_MANGLE 35
+#define PIC_CAM02_PUPPET 36
+#define PIC_CAM03_DARK 37
+#define PIC_CAM03_LIT 38
+#define PIC_CAM03_TB 39
+#define PIC_CAM03_WF 40
+#define PIC_CAM03_PUPPET 41
+#define PIC_CAM04_DARK 42
+#define PIC_CAM04_LIT 43
+#define PIC_CAM04_TB 44
+#define PIC_CAM04_WC 45
+#define PIC_CAM04_PUPPET 46
+#define PIC_CAM05_DARK 47
+#define PIC_CAM05_LIT 48
+#define PIC_CAM05_TC 49
+#define PIC_CAM05_BB 50
+#define PIC_CAM05_WB 51
+#define PIC_CAM06_DARK 52
+#define PIC_CAM06_LIT 53
+#define PIC_CAM06_TB 54
+#define PIC_CAM06_WC 55
+#define PIC_CAM06_MANGLE 56
+#define PIC_CAM07_EMPTY 57
+#define PIC_CAM07_TC 58
+#define PIC_CAM07_MANGLE 59
+#define PIC_CAM07_WF 60
+#define PIC_CAM07_WB 61
+#define PIC_CAM07_PUPPET 62
+#define PIC_CAM08_S0 63
+#define PIC_CAM08_S1 64
+#define PIC_CAM08_S2 65
+#define PIC_CAM08_S3 66
+#define PIC_CAM08_S4 67
+#define PIC_CAM08_S5 68
+#define PIC_CAM08_S6 69
+#define PIC_CAM08_S7 70
+#define PIC_CAM08_FOXY 71
+#define PIC_CAM09_S0 72
+#define PIC_CAM09_S1 73
+#define PIC_CAM09_S2 74
+#define PIC_CAM09_S3 75
+#define PIC_CAM09_S4 76
+#define PIC_CAM09_S5 77
+#define PIC_CAM09_S6 78
+#define PIC_CAM09_S7 79
+#define PIC_CAM10_EMPTY 80
+#define PIC_CAM10_TF 81
+#define PIC_CAM10_BB 82
+#define PIC_CAM10_MANGLE 83
+#define PIC_CAM11_P0 84
+#define PIC_CAM11_P1 85
+#define PIC_CAM11_P2 86
+#define PIC_CAM11_P3 87
+#define PIC_CAM11_EMPTY 88
+#define PIC_CAM11_MANGLE 89
+#define PIC_CAM12_MANGLE 90
+#define PIC_CAM12_EMPTY 91
+#define PIC_SCARE_TF0 92
+#define PIC_SCARE_TF1 93
+#define PIC_SCARE_TF2 94
+#define PIC_SCARE_TB0 95
+#define PIC_SCARE_TB1 96
+#define PIC_SCARE_TB2 97
+#define PIC_SCARE_TC0 98
+#define PIC_SCARE_TC1 99
+#define PIC_SCARE_TC2 100
+#define PIC_SCARE_MANGLE0 101
+#define PIC_SCARE_MANGLE1 102
+#define PIC_SCARE_MANGLE2 103
+#define PIC_SCARE_WF0 104
+#define PIC_SCARE_WF1 105
+#define PIC_SCARE_WF2 106
+#define PIC_SCARE_WB0 107
+#define PIC_SCARE_WB1 108
+#define PIC_SCARE_WB2 109
+#define PIC_SCARE_WC0 110
+#define PIC_SCARE_WC1 111
+#define PIC_SCARE_WC2 112
+#define PIC_SCARE_FOXY0 113
+#define PIC_SCARE_FOXY1 114
+#define PIC_SCARE_FOXY2 115
+#define PIC_SCARE_GF0 116
+#define PIC_SCARE_GF1 117
+#define PIC_SCARE_GF2 118
+#define PIC_SCARE_PUPPET0 119
+#define PIC_SCARE_PUPPET1 120
+#define PIC_SCARE_PUPPET2 121
+#define PIC_TITLE 122
+#define PIC_NEWSPAPER 123
+#define PIC_PAYCHECK 124
+#define PIC_OVERTIME 125
+#define PIC_PINKSLIP 126
+#define PIC_GAMEOVER 127
+#define PIC_FACE0 128
+#define PIC_FACE1 129
+#define PIC_FACE2 130
+#define PIC_FACE3 131
+#define PIC_FACE4 132
+#define PIC_FACE5 133
+#define PIC_FACE6 134
+#define PIC_FACE7 135
+#define PIC_FACE8 136
+#define PIC_FACE9 137
+#define PIC_COUNT 138
+#define FONT_HUD 0
+#define FONT_BIG 1
+#define FONT_TEXT 2
+#define FONT_CLOCK 3
+#define FONT_HUGE 4
+#define SCARE_TF_N 3
+#define SCARE_TB_N 3
+#define SCARE_TC_N 3
+#define SCARE_MANGLE_N 3
+#define SCARE_WF_N 3
+#define SCARE_WB_N 3
+#define SCARE_WC_N 3
+#define SCARE_FOXY_N 3
+#define SCARE_GF_N 3
+#define SCARE_PUPPET_N 3
+#define IMG_TITLE 0
+#define IMG_STAR 1
+#define HALL_X 176
+#define HALL_Y 32
+#define LVENT_X 0
+#define LVENT_Y 112
+#define RVENT_X 404
+#define RVENT_Y 112
+#define OCC_X 160
+#define OCC_Y 48
+#define MANGLE_X 192
+#define MANGLE_Y 0
+#define BBO_X 16
+#define BBO_Y 96
+#define STAND_INS 1
+
+#endif
diff --git a/games/fnaf2/src/game.c b/games/fnaf2/src/game.c
new file mode 100644
index 00000000..75bd4bcc
--- /dev/null
+++ b/games/fnaf2/src/game.c
@@ -0,0 +1,432 @@
+/* The scenes around the nights: the title, the newspaper, how to play, the night's card, 6 AM, the paychecks
+ * and the pink slip, the game over and the custom night; keys and saves. */
+#include <string.h>
+#include "game.h"
+#include "gfx.h"
+#include "res.h"
+
+Game g;
+static uint32_t seed = 0x2C1B3C6Du;
+
+uint32_t rnd(void) {
+ seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;
+ return seed;
+}
+
+static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }
+
+void caption(const char *s) {
+ for (int i = 0; i < 4; i++)
+ if (g.cap[i] == s && g.cap_t[i] > 1.2f) { /* (the same again: it stays up) */
+ g.cap_t[i] = 3;
+ return;
+ }
+ memmove(g.cap, g.cap + 1, 3 * sizeof g.cap[0]);
+ memmove(g.cap_t, g.cap_t + 1, 3 * sizeof g.cap_t[0]);
+ 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) {
+ g.n.night = (uint8_t)night;
+ memset(g.cap, 0, sizeof g.cap);
+ go(SC_INTRO);
+}
+
+void game_init(void) {
+ seed ^= plat_millis() * 2654435761u;
+ if (!seed) seed = 0x2C1B3C6Du;
+ g.running = true;
+ g.held = 0xFFFFFFFFu; /* (the key that opened the app is not a press) */
+ save_restore_copy();
+ save_load();
+ if (save_resume_load()) { /* Home left a night: back in it, paused */
+ go(SC_NIGHT);
+ g.paused = 1;
+ } else
+ go(SC_TITLE);
+}
+
+/* ------------------------------------------------------------------ the title */
+enum { M_NEW, M_CONTINUE, M_SIXTH, M_CUSTOM };
+
+static int title_light = 24;
+static float light_t;
+
+static void title_step(void) {
+ light_t += DT;
+ if (light_t >= 0.3f) light_t = 0, title_light = 22 + (int)(rnd() % 14);
+ g.menu_n = (uint8_t)(2 + (g.stars & 1) + ((g.stars >> 1) & 1));
+ if (g.menu >= g.menu_n) g.menu = 0;
+ if (pressed(K_UP | K_DIGIT(8))) g.menu = (uint8_t)((g.menu + g.menu_n - 1) % g.menu_n);
+ if (pressed(K_DOWN | K_DIGIT(2))) g.menu = (uint8_t)((g.menu + 1) % g.menu_n);
+ if (pressed(K_BACK)) g.running = false;
+ if (!pressed(K_OK)) return;
+ switch (g.menu) {
+ case M_NEW:
+ g.reached = 1;
+ save_progress();
+ g.n.night = 1;
+ go(SC_NEWS);
+ break;
+ case M_CONTINUE: start_night(g.reached); break;
+ case M_SIXTH: start_night(6); break;
+ case M_CUSTOM: go(SC_CUSTOM); break;
+ }
+}
+
+static void title_draw(void) {
+ pic_draw(PIC_TITLE, 0, 0);
+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, title_light);
+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 7, rnd());
+ int sy = (int)(g.t / 20 * (SCREEN_H + 10)) % (SCREEN_H + 10) - 10;
+ gfx_blend(0, sy, SCREEN_W, 10, WHITE, 3);
+ gfx_img(IMG_TITLE, 20, 16, WHITE);
+ for (int i = 0; i < 4; i++)
+ if (g.stars >> i & 1) gfx_img(IMG_STAR, 20 + 27 * i, 128, WHITE);
+ static const char *const items[] = {"New Game", "Continue", "6th Night", "Custom Night"};
+ int y0 = g.stars ? 158 : 148;
+ for (int i = 0; i < g.menu_n; i++) {
+ int y = y0 + 18 * i;
+ gfx_text(FONT_BIG, 44, y, items[i], WHITE);
+ if (g.menu == i) gfx_text(FONT_BIG, 20, y, ">>", WHITE);
+ }
+ if (g.menu == M_CONTINUE) {
+ char s[] = "Night 0";
+ s[6] = (char)('0' + g.reached);
+ gfx_text(FONT_HUD, 44, y0 + 18 * g.menu_n + 4, s, WHITE);
+ }
+}
+
+/* ------------------------------------------------------------------ the newspaper, how to play, the card */
+static int fade_in_out(float t, float in, float hold, float out) { /* 0 black to 32 */
+ float a = t < in ? t / in : t < hold ? 1 : t < hold + out ? 1 - (t - hold) / out : 0;
+ return (int)(a * 32);
+}
+
+static void news_draw(void) {
+ pic_draw(PIC_NEWSPAPER, 0, 0);
+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, fade_in_out(g.t, 1.5f, 8, 1.5f));
+}
+
+static void news_step(void) {
+ if (pressed(K_OK) && g.t > 1.5f && g.t < 8) g.t = 8;
+ if (g.t >= 9.5f) {
+ if (!g.keys_seen) {
+ go(SC_KEYS);
+ g.after_keys = 0;
+ } else
+ start_night(1);
+ }
+}
+
+static void keys_draw(void) {
+ static const char *const rows[][2] = {
+ {"In the office", NULL},
+ {"4 6, < >", "look left and right"},
+ {"5, up", "the flashlight, down the hall"},
+ {"7 1 9 3", "the left and right vent lights"},
+ {"2, down", "the Freddy mask on and off"},
+ {"OK", "the monitor up and down"},
+ {"On the monitor", NULL},
+ {"0 to 9, < >", "a camera (1 again: 11, 12)"},
+ {"up", "the light; on CAM 11: wind"},
+ {"Back", "pause"},
+ };
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ gfx_text_c(FONT_BIG, 160, 6, "How to survive", WHITE);
+ int y = 30;
+ for (unsigned i = 0; i < sizeof rows / sizeof rows[0]; i++) {
+ if (!rows[i][1]) {
+ gfx_text(FONT_HUD, 12, y + 2, rows[i][0], RGB(0x8FD18F));
+ y += 17;
+ continue;
+ }
+ gfx_text(FONT_HUD, 20, y, rows[i][0], WHITE);
+ gfx_text(FONT_TEXT, 112, y, rows[i][1], RGB(0xC8C8C8));
+ y += 15;
+ }
+ gfx_text_c(FONT_TEXT, 160, 190, "Keep the music box wound. Mask whoever gets in,", RGB(0xC8C8C8));
+ gfx_text_c(FONT_TEXT, 160, 203, "flash Foxy in the hall. Last until 6 AM.", RGB(0xC8C8C8));
+ if ((int)(g.t * 2) & 1) gfx_text_c(FONT_HUD, 160, 224, "OK", WHITE);
+}
+
+static void keys_step(void) {
+ if (!pressed(K_OK | K_BACK) || g.t < 0.4f) return;
+ if (!g.keys_seen) {
+ g.keys_seen = 1;
+ save_progress();
+ }
+ if (g.after_keys) {
+ g.scene = SC_NIGHT;
+ g.paused = 1;
+ } else
+ start_night(g.n.night ? g.n.night : 1);
+}
+
+static const char *const nth[] = {"", "1st Night", "2nd Night", "3rd Night", "4th Night", "5th Night", "6th Night",
+ "7th Night"};
+/* a word for each night, in place of the calls (they run a minute or two each) */
+static const char *const hint[] = {"",
+ "Wind the music box on CAM 11. Mask whoever gets in.",
+ "Light the vents. The flashlight's battery won't come back.",
+ "The old ones wake up. The mask won't fool Foxy: flash him.",
+ "Balloon Boy takes your lights if he gets in.",
+ "Everyone is restless tonight.",
+ "One more night.",
+ "Custom Night."};
+
+static void intro_draw(void) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ gfx_text_c(FONT_HUGE, 160, 84, "12:00 AM", WHITE);
+ gfx_text_c(FONT_BIG, 160, 116, nth[g.n.night], WHITE);
+ gfx_text_c(FONT_TEXT, 160, 150, hint[g.n.night], RGB(0x9A9A9A));
+ if (g.t < 0.15f) gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 20, rnd());
+ if (g.t > 2.2f) gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, (int)((3.2f - g.t) * 32));
+}
+
+static void intro_step(void) {
+ if (pressed(K_OK) && g.t > 0.5f && g.t < 2.2f) g.t = 2.2f;
+ if (g.t < 3.2f) return;
+ night_begin(g.n.night);
+ go(SC_NIGHT);
+}
+
+/* ------------------------------------------------------------------ the night, paused */
+static void night_scene_step(void) {
+ if (g.paused) {
+ if (g.confirm) {
+ if (pressed(K_LEFT | K_RIGHT | K_UP | K_DOWN | K_DIGIT(4) | K_DIGIT(6))) g.pause_item ^= 1;
+ if (pressed(K_BACK)) g.confirm = 0, g.pause_item = 2;
+ if (pressed(K_OK)) {
+ if (g.pause_item) go(SC_TITLE), g.paused = 0;
+ g.confirm = 0, g.pause_item = 2;
+ }
+ return;
+ }
+ if (pressed(K_UP | K_DIGIT(8))) g.pause_item = (uint8_t)((g.pause_item + 2) % 3);
+ if (pressed(K_DOWN | K_DIGIT(2))) g.pause_item = (uint8_t)((g.pause_item + 1) % 3);
+ if (pressed(K_BACK)) g.paused = 0;
+ if (pressed(K_OK)) {
+ if (g.pause_item == 0) g.paused = 0;
+ else if (g.pause_item == 1) go(SC_KEYS), g.after_keys = 1;
+ else g.confirm = 1, g.pause_item = 0;
+ }
+ return;
+ }
+ if (pressed(K_BACK)) {
+ g.paused = 1;
+ g.pause_item = 0;
+ return;
+ }
+ night_step();
+}
+
+static void pause_draw(void) {
+ view_night();
+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, 9);
+ if (g.confirm) {
+ gfx_text_c(FONT_BIG, 160, 84, "Quit this night?", WHITE);
+ gfx_text_c(FONT_TEXT, 160, 106, "It starts over next time.", RGB(0xB0B0B0));
+ gfx_text(FONT_BIG, 104, 132, "No", WHITE);
+ gfx_text(FONT_BIG, 190, 132, "Yes", WHITE);
+ gfx_text(FONT_BIG, g.pause_item ? 168 : 82, 132, ">>", WHITE);
+ return;
+ }
+ gfx_text_c(FONT_HUGE, 160, 62, "Paused", WHITE);
+ static const char *const items[] = {"Resume", "How to play", "Quit night"};
+ for (int i = 0; i < 3; i++) {
+ gfx_text(FONT_BIG, 112, 104 + 20 * i, items[i], WHITE);
+ if (g.pause_item == i) gfx_text(FONT_BIG, 88, 104 + 20 * i, ">>", WHITE);
+ }
+}
+
+/* ------------------------------------------------------------------ the custom night's modes */
+static const struct {
+ const char *name;
+ int8_t ai[10]; /* CUSTOM_ORDER: W.Freddy, W.Bonnie, W.Chica, W.Foxy, BB, T.Freddy, T.Bonnie, T.Chica, Mangle, G.Freddy */
+} MODES[] = {
+ {"Custom", {0}},
+ {"20/20/20/20", {20, 20, 20, 20, 0, 0, 0, 0, 0, 0}},
+ {"New & Shiny", {0, 0, 0, 0, 10, 10, 10, 10, 10, 0}},
+ {"Double Trouble", {0, 20, 0, 5, 0, 0, 20, 0, 0, 0}},
+ {"Night of Misfits", {0, 0, 0, 0, 20, 0, 0, 0, 20, 10}},
+ {"Foxy Foxy", {0, 0, 0, 20, 0, 0, 0, 0, 20, 0}},
+ {"Ladies Night", {0, 0, 20, 0, 0, 0, 0, 20, 20, 0}},
+ {"Freddy's Circus", {20, 0, 0, 10, 10, 20, 0, 0, 0, 10}},
+ {"Cupcake Challenge", {5, 5, 5, 5, 5, 5, 5, 5, 5, 5}},
+ {"Fazbear Fever", {10, 10, 10, 10, 10, 10, 10, 10, 10, 10}},
+ {"Golden Freddy", {20, 20, 20, 20, 20, 20, 20, 20, 20, 20}},
+};
+#define NMODES (int)(sizeof MODES / sizeof MODES[0])
+
+static bool custom_is(int mode) { return !memcmp(g.custom, MODES[mode].ai, sizeof g.custom); }
+
+/* ------------------------------------------------------------------ 6 AM, the paychecks */
+static void six_begin(void) {
+ int n = g.n.night;
+ if (n < 5 && g.reached < n + 1) g.reached = (uint8_t)(n + 1);
+ if (n == 5) g.stars |= 1;
+ if (n == 6) g.stars |= 2;
+ if (n == 7 && custom_is(1)) g.stars |= 4;
+ if (n == 7 && custom_is(10)) g.stars |= 8;
+ save_progress();
+ caption("*chimes*");
+}
+
+static void six_draw(void) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ float r = g.t < 1 ? 0 : g.t > 6 ? 1 : (g.t - 1) / 5;
+ int cy = 104, dh = 30, off = (int)(r * dh);
+ if (gfx_y0 + BAND_H > cy - 2 && gfx_y0 < cy + dh) {
+ gfx_text(FONT_HUGE, 118, cy - off, "5", WHITE);
+ gfx_text(FONT_HUGE, 118, cy + dh - off, "6", WHITE);
+ gfx_fill(110, cy - dh, 30, dh, BLACK); /* (only the window between shows) */
+ gfx_fill(110, cy + dh, 30, dh, BLACK);
+ }
+ gfx_text(FONT_HUGE, 148, cy, "AM", WHITE);
+ gfx_text_c(FONT_TEXT, 160, 170, g.t > 6.2f ? "*children cheering*" : "*chimes*", RGB(0xA0A0A0));
+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, fade_in_out(g.t, 1, 10.5f, 1));
+}
+
+static void six_step(void) {
+ if (g.t < DT * 1.5f) six_begin();
+ if (pressed(K_OK) && g.t > 6.5f && g.t < 10.5f) g.t = 10.5f;
+ if (g.t < 11.5f) return;
+ int n = g.n.night;
+ if (n < 5) start_night(n + 1);
+ else {
+ g.paper = (uint8_t)(n - 5);
+ go(SC_PAPER);
+ }
+}
+
+static void paper_draw(void) {
+ static const int pics[3] = {PIC_PAYCHECK, PIC_OVERTIME, PIC_PINKSLIP};
+ pic_draw(pics[g.paper], 0, 0);
+ gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, fade_in_out(g.t, 2, 15, 2));
+}
+
+static void paper_step(void) {
+ if (pressed(K_OK) && g.t > 2 && g.t < 15) g.t = 15;
+ if (g.t >= 17) go(g.paper == 1 ? SC_CUSTOM : SC_TITLE);
+}
+
+/* ------------------------------------------------------------------ the end of a night */
+static void over_draw(void) {
+ if (g.t < 2) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 30, rnd());
+ return;
+ }
+ pic_draw(PIC_GAMEOVER, 0, 0);
+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, g.t < 2.5f ? 26 : 6, rnd());
+ gfx_text_r(FONT_HUGE, 306, 200, "Game Over", WHITE);
+}
+
+static void over_step(void) {
+ if ((pressed(K_OK) && g.t > 2.5f) || g.t > 12) go(SC_TITLE);
+}
+
+/* ------------------------------------------------------------------ the custom night */
+static const char *const short_names[10] = {"W.Freddy", "W.Bonnie", "W.Chica", "W.Foxy", "BB",
+ "T.Freddy", "T.Bonnie", "T.Chica", "Mangle", "G.Freddy"};
+
+static void custom_draw(void) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ gfx_text_c(FONT_BIG, 160, 4, "Customize Night", WHITE);
+ for (int i = 0; i < 10; i++) {
+ int x = 8 + 62 * (i % 5), y = 28 + 92 * (i / 5);
+ pic_draw(PIC_FACE0 + i, x + 3, y);
+ gfx_frame_rect(x + 1, y - 2, 52, 52, g.custom_sel == i ? WHITE : RGB(0x404040));
+ gfx_text_c(FONT_TEXT, x + 27, y + 52, short_names[i], RGB(0xC8C8C8));
+ char s[3] = {(char)('0' + g.custom[i] / 10), (char)('0' + g.custom[i] % 10), 0};
+ gfx_text_c(FONT_BIG, x + 27, y + 67, g.custom[i] >= 10 ? s : s + 1, WHITE);
+ if (g.custom_sel == i) {
+ gfx_text(FONT_HUD, x + 4, y + 70, "<", WHITE);
+ gfx_text(FONT_HUD, x + 44, y + 70, ">", WHITE);
+ }
+ }
+ int sel = g.custom_sel == 10;
+ gfx_text(FONT_TEXT, 10, 214, "Mode:", RGB(0x909090));
+ gfx_text(FONT_HUD, 48, 213, MODES[g.custom_mode].name, sel ? WHITE : RGB(0xB0B0B0));
+ if (sel) gfx_frame_rect(44, 210, 150, 17, WHITE);
+ gfx_text(FONT_TEXT, 10, 228, "< > pick up down: level OK: ready", RGB(0x707070));
+ gfx_text_r(FONT_BIG, 312, 208, "Ready", (int)(g.t * 2) & 1 ? WHITE : RGB(0xC0C0C0));
+}
+
+static void custom_step(void) {
+ if (pressed(K_LEFT | K_DIGIT(4))) g.custom_sel = (uint8_t)((g.custom_sel + 10) % 11);
+ if (pressed(K_RIGHT | K_DIGIT(6))) g.custom_sel = (uint8_t)((g.custom_sel + 1) % 11);
+ int d = 0;
+ uint32_t up = K_UP | K_DIGIT(8), down = K_DOWN | K_DIGIT(2);
+ if (pressed(up)) d = 1, g.repeat = 0.35f;
+ else if (pressed(down)) d = -1, g.repeat = 0.35f;
+ else if (g.held & (up | down) && g.custom_sel < 10) { /* held: faster */
+ g.repeat -= DT;
+ if (g.repeat <= 0) g.repeat = 0.06f, d = g.held & up ? 1 : -1;
+ }
+ if (d && g.custom_sel == 10) { /* a mode: its levels */
+ g.custom_mode = (uint8_t)((g.custom_mode + NMODES + d) % NMODES);
+ if (g.custom_mode == 0) g.custom_mode = (uint8_t)(d > 0 ? 1 : NMODES - 1);
+ memcpy(g.custom, MODES[g.custom_mode].ai, sizeof g.custom);
+ } else if (d) {
+ int8_t *v = &g.custom[g.custom_sel];
+ *v = (int8_t)(*v + d < 0 ? 0 : *v + d > 20 ? 20 : *v + d);
+ g.custom_mode = 0;
+ for (int m = 1; m < NMODES; m++)
+ if (custom_is(m)) g.custom_mode = (uint8_t)m;
+ }
+ if (pressed(K_BACK)) {
+ save_progress();
+ go(SC_TITLE);
+ }
+ if (pressed(K_OK)) {
+ save_progress();
+ start_night(7);
+ }
+}
+
+/* ------------------------------------------------------------------ steps and drawing */
+void game_step(uint32_t keys) {
+ g.pressed = keys & ~g.held;
+ g.held = keys;
+ for (int i = 0; i < 4; i++)
+ if (g.cap_t[i] > 0) g.cap_t[i] -= DT;
+ if (g.blip > 0) g.blip -= DT;
+ if (keys & K_HOME) { /* Home (or On/Off): a night is kept as it is */
+ if (g.scene == SC_NIGHT) save_resume();
+ g.running = false;
+ return;
+ }
+ g.t += DT;
+ switch (g.scene) {
+ case SC_TITLE: title_step(); break;
+ case SC_NEWS: news_step(); break;
+ case SC_KEYS: keys_step(); break;
+ case SC_INTRO: intro_step(); break;
+ case SC_NIGHT: night_scene_step(); break;
+ case SC_SCARE:
+ g.scare_t += DT;
+ if (g.scare_t > 1.1f) go(SC_OVER);
+ break;
+ case SC_SIX: six_step(); break;
+ case SC_PAPER: paper_step(); break;
+ case SC_OVER: over_step(); break;
+ case SC_CUSTOM: custom_step(); break;
+ }
+}
+
+void game_draw(void) {
+ static void (*const draws[])(void) = {
+ [SC_TITLE] = title_draw, [SC_NEWS] = news_draw, [SC_KEYS] = keys_draw, [SC_INTRO] = intro_draw,
+ [SC_NIGHT] = view_night, [SC_SCARE] = view_scare, [SC_SIX] = six_draw, [SC_PAPER] = paper_draw,
+ [SC_OVER] = over_draw, [SC_CUSTOM] = custom_draw};
+ gfx_frame(g.scene == SC_NIGHT && g.paused ? pause_draw : draws[g.scene]);
+}
diff --git a/games/fnaf2/src/game.h b/games/fnaf2/src/game.h
new file mode 100644
index 00000000..0024a1cd
--- /dev/null
+++ b/games/fnaf2/src/game.h
@@ -0,0 +1,142 @@
+/* Five Nights at Freddy's 2: the game's state and its parts.
+ *
+ * game.c: the scenes (title, newspaper, how to play, the night's card, 6 AM, the paychecks, game over, the
+ * custom night), keys and saves. night.c: a night (time, the music box, the flashlight, the mask, the vents,
+ * the cameras and every animatronic) as the game plays it, 60 steps a second. view.c: drawing the office, the
+ * cameras and what is around them. */
+#ifndef FNAF2_GAME_H
+#define FNAF2_GAME_H
+#include <stdbool.h>
+#include <stdint.h>
+
+#define DT (1.0f / 60) /* a step */
+#define HOUR 68.0f /* seconds of an hour */
+#define OFFICE_PAN 180 /* how far the office view turns (the office is 500 wide, the screen 320) */
+#define BOX_FULL 2000 /* the music box, wound up */
+
+/* where everyone can be: the 12 cameras (CAM 01 to 12), then the places the cameras don't show */
+enum {
+ L_PR1, L_PR2, L_PR3, L_PR4, L_LVENT, L_RVENT, L_MAIN, L_PARTS, L_STAGE, L_GAME, L_PRIZE, L_KIDS,
+ L_UNSEEN, /* Balloon Boy between the Game Area and the vent */
+ L_HALL_FAR, /* the office hallway, far (Toy Freddy) */
+ L_HALL, /* the office hallway */
+ L_LSPOT, /* the left vent's blind spot */
+ L_RSPOT, /* the right vent's blind spot */
+ L_OFFICE,
+ L_COUNT
+};
+#define CAM_COUNT 12
+
+/* the animatronics: the ones that walk a path, then Withered Foxy, Golden Freddy and the Puppet */
+enum { TF, TB, TC, MANGLE, BB, WF, WB, WC, WALKERS, FOXY = WALKERS, GF, PUPPET, BOTS };
+
+/* the office's visitor (one at a time): how far along */
+enum { OCC_NONE, OCC_IN, OCC_SHOWN, OCC_MASKED, OCC_LEAVING, OCC_DOOMED };
+/* Golden Freddy */
+enum { GF_NONE, GF_HALL, GF_COMING, GF_SHOWN, GF_FADING };
+
+/* scenes */
+enum { SC_TITLE, SC_NEWS, SC_KEYS, SC_INTRO, SC_NIGHT, SC_SCARE, SC_SIX, SC_PAPER, SC_OVER, SC_CUSTOM };
+
+/* 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; /* 1 to 7 (7: the custom night) */
+ uint8_t hour; /* 0 (12 AM) to 6 */
+ int8_t ai[BOTS]; /* 0 to 20 (the caps apply when moving) */
+ uint8_t step[WALKERS]; /* how far along its path each walker is */
+ uint8_t ready[WALKERS];/* at its last place, it comes in the next time the monitor is up */
+ uint8_t pending[BOTS]; /* a move won while stunned: made when the stun ends */
+ uint16_t stun[BOTS]; /* frames it can't move (the camera's light) */
+ uint8_t occ, occ_state;/* the office's visitor and how far along (OCC_*) */
+ uint8_t mangle_in, bb_in;
+ uint8_t foxy_hall, foxy_got, foxy_flashes, foxy_off;
+ uint8_t gf; /* GF_* */
+ uint8_t puppet; /* 0 in the box, 1 partly out, 2 mostly out, 3 out, 4 gone from CAM 11 */
+ uint8_t puppet_at; /* gone: where (an L_*) */
+ uint8_t monitor; /* up, or going up */
+ uint8_t mask; /* on, or going on */
+ uint8_t cam; /* the camera picked */
+ uint8_t hall_light, vent_light, cam_light, winding; /* held: the lights (vent: 1 + side), the box */
+ int8_t want; /* a vent light pressed while looking away: turning there first (-1 none) */
+ uint8_t warned; /* the music box's warning, given */
+ uint8_t hall_was; /* the hallway light, the step before */
+ uint8_t pad[2];
+ float t; /* seconds since 12 AM */
+ float hour_t;
+ float box; /* the music box: 0 to BOX_FULL */
+ float battery; /* frames of light used */
+ float move_t[BOTS]; /* until the next movement opportunity */
+ float occ_t; /* the visitor's timer */
+ float force_t; /* a doomed visitor pulls the monitor down or the mask off */
+ float blackout; /* seconds of the office's lights out */
+ float flicker; /* seconds of the office's lights flickering */
+ float foxy_d; /* Withered Foxy's D */
+ float foxy_hold; /* the hallway light held on him */
+ float foxy_ten; /* until the next 10 s mark */
+ float foxy_dim; /* until the next half second (the light down the hall in Parts/Service) */
+ float gf_t, gf_lit;
+ float pan, pan_v; /* the office view's left edge */
+ float flip; /* the monitor: 0 down to 1 up */
+ float mask_anim; /* the mask: 0 off to 1 on */
+ float glitch; /* seconds of static on the camera watched */
+ float laugh_t; /* Balloon Boy in the office */
+} Night;
+
+typedef struct {
+ int scene;
+ float t; /* seconds in the scene */
+ uint32_t held, pressed;
+ bool running;
+ /* the save: the night reached (1 to 5), the stars, whether the keys were shown */
+ uint8_t reached, stars, keys_seen;
+ uint8_t menu, menu_n;
+ uint8_t paused, confirm, pause_item;
+ uint8_t custom_sel, custom_mode, paper;
+ uint8_t scare, after_keys;
+ int8_t custom[10]; /* the custom night's levels (CUSTOM_ORDER) */
+ float scare_t;
+ float blip; /* the cameras' white flicker when switched */
+ 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;
+
+extern Game g;
+/* the custom night's ten, in the order of its screen: W.Freddy, W.Bonnie, W.Chica, W.Foxy, BB, T.Freddy,
+ * T.Bonnie, T.Chica, Mangle, G.Freddy */
+extern const uint8_t CUSTOM_ORDER[10];
+extern const char *const BOT_NAMES[BOTS];
+
+/* game.c */
+void game_init(void);
+void game_step(uint32_t keys);
+void game_draw(void);
+uint32_t rnd(void);
+void start_night(int night);
+void caption(const char *s);
+
+/* night.c */
+void night_begin(int night);
+void night_step(void);
+int bot_at(int who); /* where an animatronic is (an L_*), or -1 off the map */
+int ai_level(int who); /* its AI level, capped as the game caps it */
+int battery_bars(void); /* the flashlight: 0 to 4 */
+bool lights_work(void); /* the flashlight and the vent lights (Balloon Boy takes them) */
+int battery_frames(int night);
+float box_drain(int night, int hour);
+bool box_warning(void);
+void apply_hour(int night, int hour);
+
+/* 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/fnaf2/src/gfx.c b/games/fnaf2/src/gfx.c
new file mode 100644
index 00000000..3a516a68
--- /dev/null
+++ b/games/fnaf2/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/fnaf2/src/gfx.h b/games/fnaf2/src/gfx.h
new file mode 100644
index 00000000..54f9e18c
--- /dev/null
+++ b/games/fnaf2/src/gfx.h
@@ -0,0 +1,53 @@
+/* Five Nights at Freddy's 2: 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 FNAF2_GFX_H
+#define FNAF2_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/fnaf2/src/icon.png b/games/fnaf2/src/icon.png
new file mode 100644
index 00000000..72a2f788
Binary files /dev/null and b/games/fnaf2/src/icon.png differ
diff --git a/games/fnaf2/src/main.c b/games/fnaf2/src/main.c
new file mode 100644
index 00000000..6caca85a
--- /dev/null
+++ b/games/fnaf2/src/main.c
@@ -0,0 +1,46 @@
+/* Five Nights at Freddy's 2 for the NumWorks calculator.
+ *
+ * Inspired by Five Nights at Freddy's 2 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 2";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+extern const uint8_t fnaf2_data[];
+const uint8_t *fnaf2_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();
+ fnaf2_bin = fnaf2_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/fnaf2/src/night.c b/games/fnaf2/src/night.c
new file mode 100644
index 00000000..e0babc71
--- /dev/null
+++ b/games/fnaf2/src/night.c
@@ -0,0 +1,531 @@
+/* A night of Five Nights at Freddy's 2, 60 steps a second, as the game plays it.
+ *
+ * The AI levels are set at given hours (they don't rise each hour as in the first game), and the game caps them
+ * at 15 (Withered Foxy 17, Golden Freddy 10). Every 5 seconds each animatronic has a movement opportunity: a
+ * number from 1 to 20, and it moves one place along its path if its level is that number or more. From the
+ * last place before the office (the hallway, a vent or a vent's blind spot) it comes in the next time the
+ * monitor is up, unless the Freddy mask is on at its next opportunity: then it goes back. Once in, it shows
+ * when the monitor comes down: the mask at once and it leaves, or it gets you the next time the monitor comes
+ * down or the mask comes off. Mangle stays on the ceiling, Balloon Boy takes the lights. Withered Foxy waits in
+ * the hallway for the flashlight, Golden Freddy appears, and the Puppet comes for anyone who lets the music box
+ * run down. The numbers are in the game's events, as the players who read them wrote them down: see the
+ * README's Credits. */
+#include <string.h>
+#include "game.h"
+#include "plat.h"
+
+#define N g.n
+#define STUN 400 /* frames a camera's light holds an animatronic (6.66 s) */
+#define WINDOW 1.0f /* seconds to put the mask on, once a visitor shows */
+#define MASKED_STAY 4.0f /* a visitor sent off by the mask stays this long first */
+#define WIND_RATE (BOX_FULL / 6.0f)
+
+const uint8_t CUSTOM_ORDER[10] = {WF, WB, WC, FOXY, BB, TF, TB, TC, MANGLE, GF};
+const char *const BOT_NAMES[BOTS] = {"Toy Freddy", "Toy Bonnie", "Toy Chica", "Mangle", "Balloon Boy",
+ "Withered Freddy", "Withered Bonnie", "Withered Chica", "Withered Foxy",
+ "Golden Freddy", "The Puppet"};
+
+/* the walkers' paths to the office, and where each goes back to when sent away */
+static const uint8_t PATH[WALKERS][10] = {
+ [TF] = {L_STAGE, L_GAME, L_HALL_FAR, L_HALL},
+ [TB] = {L_STAGE, L_PR3, L_PR4, L_PR2, L_RVENT, L_RSPOT},
+ [TC] = {L_STAGE, L_MAIN, L_HALL, L_PR1, L_LVENT, L_LSPOT},
+ [MANGLE] = {L_KIDS, L_PRIZE, L_GAME, L_MAIN, L_HALL, L_PR1, L_PR2, L_RVENT, L_RSPOT},
+ [BB] = {L_GAME, L_UNSEEN, L_LVENT, L_LSPOT},
+ [WF] = {L_PARTS, L_MAIN, L_PR3, L_HALL},
+ [WB] = {L_PARTS, L_MAIN, L_HALL, L_PR1, L_LVENT},
+ [WC] = {L_PARTS, L_PR4, L_PR2, L_RVENT},
+};
+static const uint8_t PATH_LEN[WALKERS] = {4, 6, 6, 9, 4, 4, 5, 4};
+static const uint8_t BACK_TO[WALKERS] = {0, 1, 1, 3, 0, 1, 1, 1};
+/* who comes in first when several are waiting */
+static const uint8_t ENTRY_ORDER[WALKERS] = {WF, WB, WC, TF, TB, TC, MANGLE, BB};
+
+/* The AI levels at the hours the game sets them: the night, the hour, then Toy Freddy, Toy Bonnie, Toy Chica,
+ * Mangle, Balloon Boy, Withered Freddy, Bonnie, Chica, Foxy, Golden Freddy and the Puppet (-1: as it was; Foxy
+ * -2: not there at all) */
+static const int8_t AI_TABLE[][2 + BOTS] = {
+ {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 1},
+ {1, 1, 0, 2, 2, 0, 0, 0, 0, 0, -1, -1, -1},
+ {1, 2, 2, 3, 2, 0, 0, 0, 0, 0, -1, -1, -1},
+ {2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5},
+ {2, 1, 2, 3, 3, 3, 3, 0, 0, 0, 1, -1, -1},
+ {3, 0, 0, 0, 0, 0, 1, 0, 1, 1, 2, 0, 8},
+ {3, 1, 0, 1, 1, 0, 2, 2, 2, 2, 3, -1, -1},
+ {4, 0, 0, 0, 0, 5, 3, 0, 1, 0, 7, 0, 9},
+ {4, 2, 0, 1, 0, 5, 3, 3, 4, 4, 7, -1, -1},
+ {5, 0, 5, 2, 2, 1, 5, 2, 2, 2, 5, 0, 10},
+ {5, 1, 1, 2, 2, 10, 5, 5, 5, 5, 7, -1, -1},
+ {6, 0, 0, 0, 0, 3, 5, 5, 5, 5, 10, 0, 15},
+ {6, 2, 5, 5, 5, 10, 9, 10, 10, 10, 15, 3, -1},
+};
+/* Golden Freddy's chance, at 12 AM, to be there at level 1: nights 2 to 6 (1 in this) */
+static const uint16_t GOLDEN_ODDS[7] = {0, 0, 1000, 1000, 100, 100, 10};
+
+static bool pressed(uint32_t k) { return (g.pressed & k) != 0; }
+static bool held(uint32_t k) { return (g.held & k) != 0; }
+static bool monitor_up(void) { return N.flip >= 1; }
+static bool mask_on(void) { return N.mask && N.mask_anim >= 1; }
+static int roll(void) { return 1 + (int)(rnd() % 20); }
+
+int ai_level(int who) {
+ int a = N.ai[who], cap = who == FOXY ? 17 : who == GF ? 10 : 15;
+ return a < 0 ? a : a > cap ? cap : a;
+}
+
+void apply_hour(int night, int hour) {
+ for (unsigned r = 0; r < sizeof AI_TABLE / sizeof AI_TABLE[0]; r++)
+ if (AI_TABLE[r][0] == night && AI_TABLE[r][1] == hour)
+ for (int k = 0; k < BOTS; k++)
+ if (AI_TABLE[r][2 + k] != -1) N.ai[k] = AI_TABLE[r][2 + k] == -2 ? -1 : AI_TABLE[r][2 + k];
+}
+
+int battery_frames(int night) {
+ static const int16_t frames[8] = {0, 7000, 6000, 5000, 4000, 3000, 3000, 3000};
+ return frames[night < 1 ? 1 : night > 7 ? 7 : night];
+}
+
+int battery_bars(void) {
+ float left = battery_frames(N.night) - N.battery, fifth = battery_frames(N.night) / 5.0f;
+ if (left <= 0) return 0;
+ int b = (int)(left / fifth + 0.9999f) - 1;
+ return b < 0 ? 0 : b > 4 ? 4 : b;
+}
+
+/* the music box's drain a second: 20 times the night, none on the first night before 2 AM, the custom night as
+ * the 6th */
+float box_drain(int night, int hour) {
+ if (night == 1) return hour < 2 ? 0 : 40;
+ return 20.0f * (night > 6 ? 6 : night);
+}
+
+bool box_warning(void) { return N.box <= BOX_FULL / 5 && N.puppet < 3; }
+
+bool lights_work(void) { return !N.bb_in && N.blackout <= 0; }
+static bool battery_left(void) { return N.battery < battery_frames(N.night); }
+
+int bot_at(int who) {
+ if (who < WALKERS) {
+ if ((who == MANGLE && N.mangle_in) || (who == BB && N.bb_in)) return L_OFFICE;
+ if (N.occ == who && N.occ_state != OCC_NONE) return L_OFFICE;
+ return PATH[who][N.step[who]];
+ }
+ if (who == FOXY) return N.foxy_hall ? L_HALL : L_PARTS;
+ if (who == PUPPET) return N.puppet < 4 ? L_PRIZE : N.puppet_at;
+ return N.gf == GF_HALL ? L_HALL : N.gf == GF_SHOWN || N.gf == GF_FADING ? L_OFFICE : -1;
+}
+
+void night_begin(int night) {
+ memset(&N, 0, sizeof N);
+ N.night = (uint8_t)night;
+ if (night <= 6) {
+ apply_hour(night, 0);
+ if (GOLDEN_ODDS[night] && rnd() % GOLDEN_ODDS[night] == 0) N.ai[GF] = 1;
+ } else {
+ for (int k = 0; k < 10; k++) N.ai[CUSTOM_ORDER[k]] = g.custom[k];
+ N.ai[PUPPET] = 15;
+ }
+ N.box = BOX_FULL;
+ N.pan = OFFICE_PAN / 2;
+ N.want = -1;
+ N.cam = L_STAGE;
+ N.occ = 0xFF;
+ for (int k = 0; k < BOTS; k++) N.move_t[k] = 5;
+ N.move_t[PUPPET] = 1;
+ N.foxy_ten = 10;
+}
+
+/* ------------------------------------------------------------------ the end of a night */
+static void scare(int who) {
+ g.scene = SC_SCARE;
+ g.scare = (uint8_t)who;
+ g.scare_t = 0;
+ N.monitor = 0;
+ N.flip = 0;
+ N.mask = 0;
+ N.mask_anim = 0;
+}
+
+static void six_am(void) {
+ g.scene = SC_SIX;
+ g.t = 0;
+}
+
+/* ------------------------------------------------------------------ the walkers */
+static const char *vent_side(int loc) {
+ return loc == L_LVENT || loc == L_LSPOT ? "left" : loc == L_RVENT || loc == L_RSPOT ? "right" : NULL;
+}
+
+static void send_back(int who) {
+ int from = PATH[who][N.step[who]];
+ N.step[who] = BACK_TO[who];
+ N.ready[who] = 0;
+ N.pending[who] = 0;
+ if (vent_side(from)) caption(from == L_LSPOT || from == L_LVENT ? "*clattering: the left vent empties*"
+ : "*clattering: the right vent empties*");
+ if (N.flip >= 1 && N.cam == PATH[who][N.step[who]]) N.glitch = 1;
+}
+
+static void moved(int who, int from, int to) {
+ if (N.flip >= 1 && (N.cam == from || N.cam == to)) N.glitch = 1; /* the feed breaks up */
+ if (to == L_LVENT || to == L_LSPOT) caption("*banging in the left vent*");
+ if (to == L_RVENT || to == L_RSPOT) caption("*banging in the right vent*");
+ if (who == BB) {
+ static const char *const says[3] = {"*a child's voice: \"Hello?\"*", "*a child's voice: \"Hi!\"*",
+ "*a child laughs*"};
+ caption(says[rnd() % 3]);
+ }
+}
+
+static void advance(int who) {
+ int len = PATH_LEN[who];
+ if (N.step[who] == len - 1) { /* at the last place: in, at the next monitor, unless the mask is on */
+ if (mask_on()) send_back(who);
+ else N.ready[who] = 1;
+ return;
+ }
+ int from = PATH[who][N.step[who]];
+ N.step[who]++;
+ moved(who, from, PATH[who][N.step[who]]);
+}
+
+static bool in_office(int who) {
+ return (who == MANGLE && N.mangle_in) || (who == BB && N.bb_in) || (N.occ == who && N.occ_state != OCC_NONE);
+}
+
+static void walkers(void) {
+ for (int who = 0; who < WALKERS; who++) {
+ if (N.stun[who] > 0 && --N.stun[who] == 0 && N.pending[who]) {
+ N.pending[who] = 0;
+ if (!in_office(who)) advance(who);
+ }
+ N.move_t[who] -= DT;
+ if (N.move_t[who] > 0) continue;
+ N.move_t[who] += 5;
+ int a = ai_level(who);
+ if (a <= 0 || in_office(who) || roll() > a) continue;
+ /* the Withereds stay in Parts/Service while its camera is watched */
+ if (who >= WF && N.step[who] == 0 && monitor_up() && N.cam == L_PARTS) continue;
+ if (N.stun[who]) N.pending[who] = 1;
+ else advance(who);
+ }
+}
+
+/* the monitor up: whoever is waiting comes in */
+static void entries(void) {
+ if (!monitor_up()) return;
+ for (int i = 0; i < WALKERS; i++) {
+ int who = ENTRY_ORDER[i];
+ if (!N.ready[who]) continue;
+ if (who == MANGLE) {
+ N.mangle_in = 1, N.ready[who] = 0;
+ caption("*radio static, overhead*");
+ } else if (who == BB) {
+ N.bb_in = 1, N.ready[who] = 0;
+ caption("*a child laughs, in the office*");
+ } else if (N.occ_state == OCC_NONE && N.gf == GF_NONE) {
+ N.occ = (uint8_t)who, N.occ_state = OCC_IN, N.ready[who] = 0;
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ the office's visitor */
+static void doomed(void) {
+ N.occ_state = OCC_DOOMED;
+ N.blackout = 1;
+ N.force_t = 2 + (float)(rnd() % 400) / 100;
+}
+
+static void visitor(void) {
+ switch (N.occ_state) {
+ case OCC_SHOWN:
+ N.occ_t += DT;
+ N.flicker = 0.2f;
+ if (N.mask) N.occ_state = OCC_MASKED, N.occ_t = 0;
+ else if (N.occ_t >= WINDOW) doomed();
+ break;
+ case OCC_MASKED:
+ N.occ_t += DT;
+ N.flicker = 0.2f;
+ if (!N.mask) scare(N.occ);
+ else if (N.occ_t >= MASKED_STAY) N.occ_state = OCC_LEAVING, N.blackout = 1;
+ break;
+ case OCC_LEAVING:
+ if (N.blackout <= 0) {
+ int who = N.occ;
+ N.occ_state = OCC_NONE, N.occ = 0xFF;
+ send_back(who);
+ }
+ break;
+ case OCC_DOOMED:
+ if (monitor_up() || N.mask) { /* left alone, it pulls the monitor down or the mask off */
+ N.force_t -= DT;
+ if (N.force_t <= 0) {
+ if (N.mask) scare(N.occ);
+ else N.monitor = 0;
+ }
+ }
+ break;
+ }
+}
+
+/* ------------------------------------------------------------------ Withered Foxy */
+static void foxy(bool flash_on, bool flash_new) {
+ if (N.ai[FOXY] < 0) return;
+ bool threats = N.occ_state != OCC_NONE || N.gf != GF_NONE;
+ for (int k = 0; k < WALKERS; k++) threats |= N.ready[k] != 0;
+ if (N.blackout <= 0) N.foxy_d += DT * (mask_on() && !threats ? 2 : 1);
+ if (flash_on) {
+ if (N.foxy_hall) {
+ if (N.foxy_got) {
+ scare(FOXY);
+ return;
+ }
+ N.foxy_d = 0;
+ if (flash_new) N.foxy_flashes++;
+ N.foxy_hold += DT;
+ if (N.foxy_hold >= 1) N.foxy_hold -= 1, N.foxy_flashes++;
+ if (N.foxy_flashes >= 5) N.foxy_off = 1;
+ }
+ } else
+ N.foxy_hold = 0;
+ /* every half second: the light down the hall while he is in Parts/Service takes 1 off D */
+ N.foxy_dim += DT;
+ if (N.foxy_dim >= 0.5f) {
+ N.foxy_dim -= 0.5f;
+ if (flash_on && !N.foxy_hall) N.foxy_d = N.foxy_d > 1 ? N.foxy_d - 1 : 0;
+ }
+ N.move_t[FOXY] -= DT;
+ if (N.move_t[FOXY] <= 0) {
+ N.move_t[FOXY] += 5;
+ if (!N.foxy_off && 21 + (int)(rnd() % 5) - (int)N.foxy_d < ai_level(FOXY)) {
+ if (!N.foxy_hall) {
+ N.foxy_hall = 1, N.foxy_flashes = 0, N.foxy_hold = 0;
+ if (monitor_up() && N.cam == L_PARTS) N.glitch = 1;
+ } else
+ N.foxy_got = 1;
+ }
+ }
+ N.foxy_ten -= DT;
+ if (N.foxy_ten <= 0) {
+ N.foxy_ten += 10;
+ if (N.foxy_got && N.blackout <= 0) scare(FOXY);
+ }
+}
+
+/* ------------------------------------------------------------------ the music box and the Puppet */
+static void puppet(bool wind) {
+ N.winding = wind;
+ if (wind) N.box = N.box + WIND_RATE * DT > BOX_FULL ? BOX_FULL : N.box + WIND_RATE * DT;
+ else {
+ N.box -= box_drain(N.night, N.hour) * DT;
+ if (N.box < 0) N.box = 0;
+ }
+ if (!N.warned && box_warning()) N.warned = 1;
+ if (N.box > BOX_FULL / 5) N.warned = 0;
+ if (N.puppet < 3 && N.box >= BOX_FULL) N.puppet = 0;
+ if (N.stun[PUPPET] > 0) N.stun[PUPPET]--;
+ N.move_t[PUPPET] -= DT;
+ if (N.move_t[PUPPET] > 0) return;
+ N.move_t[PUPPET] += 1;
+ int a = ai_level(PUPPET);
+ if (N.puppet < 3 && N.box > 0) return; /* wound in time: he stays */
+ if (N.stun[PUPPET] || (int)(rnd() % 20) > a) return;
+ if (N.puppet < 4) {
+ if (++N.puppet == 4) {
+ N.puppet_at = L_MAIN;
+ caption("*a jack-in-the-box tune starts*");
+ if (monitor_up() && (N.cam == L_PRIZE || N.cam == L_MAIN)) N.glitch = 1;
+ }
+ return;
+ }
+ /* on his way: the Main Hall, a party room, Party Room 2, the hallway, the office */
+ int from = N.puppet_at, to;
+ static const uint8_t rooms[3] = {L_PR3, L_PR1, L_PR4};
+ switch (from) {
+ case L_MAIN: to = rooms[rnd() % 3]; break;
+ case L_PR1: case L_PR3: case L_PR4: to = L_PR2; break;
+ case L_PR2: to = L_UNSEEN; break;
+ default: to = L_OFFICE; break;
+ }
+ N.puppet_at = (uint8_t)to;
+ if (monitor_up() && (N.cam == from || N.cam == to)) N.glitch = 1;
+ if (to == L_OFFICE) scare(PUPPET);
+}
+
+/* ------------------------------------------------------------------ Golden Freddy */
+static void golden(bool flash_on) {
+ switch (N.gf) {
+ case GF_NONE:
+ N.move_t[GF] -= DT;
+ if (N.move_t[GF] > 0) break;
+ N.move_t[GF] += 5;
+ if (ai_level(GF) <= 0 || N.occ_state != OCC_NONE || N.blackout > 0 || roll() > ai_level(GF)) break;
+ if (N.flip <= 0) N.gf = GF_HALL, N.gf_t = N.gf_lit = 0;
+ else if (rnd() % 100 < 60) N.gf = GF_COMING;
+ break;
+ case GF_HALL:
+ N.gf_t += DT;
+ if (flash_on) N.gf_lit += DT;
+ if (N.gf_lit >= 0.5f) scare(GF);
+ else if (N.gf_t >= 10) N.gf = GF_NONE;
+ break;
+ case GF_SHOWN:
+ N.gf_t += DT;
+ N.flicker = 0.2f;
+ if (N.mask) N.gf = GF_FADING, N.gf_t = 0;
+ else if (N.gf_t >= WINDOW) scare(GF);
+ break;
+ case GF_FADING:
+ N.gf_t += DT;
+ if (N.gf_t >= 1.5f) N.gf = GF_NONE;
+ break;
+ }
+}
+
+/* ------------------------------------------------------------------ the monitor and the mask */
+static void monitor_moves(void) {
+ bool was_up = N.flip >= 1, was_down = N.flip <= 0;
+ N.flip += (N.monitor ? 1 : -1) * DT / 0.25f;
+ N.flip = N.flip < 0 ? 0 : N.flip > 1 ? 1 : N.flip;
+ if (!was_up && N.flip >= 1) { /* up */
+ g.blip = 0.12f;
+ if (N.foxy_off) N.foxy_hall = N.foxy_off = N.foxy_got = 0, N.foxy_d = 0, N.foxy_flashes = 0;
+ if (N.gf == GF_HALL) N.gf = GF_NONE;
+ }
+ if (!was_down && N.flip <= 0) { /* down: who is in the office shows */
+ N.glitch = 0;
+ if (N.occ_state == OCC_IN) N.occ_state = OCC_SHOWN, N.occ_t = 0;
+ else if (N.occ_state == OCC_DOOMED) {
+ scare(N.occ);
+ return;
+ }
+ if (N.gf == GF_COMING) N.gf = GF_SHOWN, N.gf_t = 0;
+ if (N.mangle_in && rnd() % 3 == 0) scare(MANGLE);
+ }
+}
+
+static void mask_moves(void) {
+ N.mask_anim += (N.mask ? 1 : -1) * DT / 0.25f;
+ N.mask_anim = N.mask_anim < 0 ? 0 : N.mask_anim > 1 ? 1 : N.mask_anim;
+}
+
+/* ------------------------------------------------------------------ keys */
+static bool side_in_view(int side) { return side == 0 ? N.pan <= 30 : N.pan >= OFFICE_PAN - 30; }
+
+/* returns the lights held this step: bit 0 the hallway, bit 1 the left vent, bit 2 the right vent, bit 3 the
+ * camera's light, bit 4 winding */
+static int keys(void) {
+ int lights = 0;
+ bool office = N.flip <= 0 && !N.monitor;
+ if (office) {
+ if (pressed(K_DOWN | K_DIGIT(2)) && (N.mask_anim <= 0 || N.mask_anim >= 1)) N.mask ^= 1;
+ if (pressed(K_OK) && !N.mask && N.mask_anim <= 0) {
+ N.monitor = 1;
+ N.want = -1;
+ return 0;
+ }
+ float target = 0;
+ if (held(K_LEFT | K_DIGIT(4))) target = -380, N.want = -1;
+ else if (held(K_RIGHT | K_DIGIT(6))) target = 380, N.want = -1;
+ if (!N.mask && N.mask_anim <= 0) {
+ if (held(K_UP | K_DIGIT(5))) lights |= 1;
+ for (int side = 0; side < 2; side++) {
+ uint32_t k = side ? K_DIGIT(9) | K_DIGIT(3) : K_DIGIT(7) | K_DIGIT(1);
+ if (pressed(k)) N.want = (int8_t)side;
+ if (held(k)) {
+ if (side_in_view(side)) lights |= 2 << side, N.want = -1;
+ else if (N.want == side) target = side ? 720 : -720;
+ }
+ }
+ }
+ float dv = target - N.pan_v, step = 4200 * DT;
+ N.pan_v += dv > step ? step : dv < -step ? -step : dv;
+ N.pan += N.pan_v * DT;
+ if (N.pan < 0) N.pan = 0, N.pan_v = 0;
+ if (N.pan > OFFICE_PAN) N.pan = OFFICE_PAN, N.pan_v = 0;
+ return lights;
+ }
+ if (N.flip < 1) return 0;
+ if (pressed(K_OK | K_DOWN)) {
+ N.monitor = 0;
+ return 0;
+ }
+ int to = -1;
+ if (pressed(K_LEFT)) to = (N.cam + CAM_COUNT - 1) % CAM_COUNT;
+ if (pressed(K_RIGHT)) to = (N.cam + 1) % CAM_COUNT;
+ for (int d = 2; d <= 9; d++)
+ if (pressed(K_DIGIT(d))) to = d - 1;
+ if (pressed(K_DIGIT(0))) to = L_GAME;
+ if (pressed(K_DIGIT(1))) to = N.cam == L_PR1 ? L_PRIZE : N.cam == L_PRIZE ? L_KIDS : L_PR1;
+ if (to >= 0 && to != N.cam) {
+ N.cam = (uint8_t)to;
+ N.glitch = 0;
+ g.blip = 0.12f;
+ }
+ if (held(K_UP)) lights |= N.cam == L_PRIZE ? 16 : 8;
+ return lights;
+}
+
+/* ------------------------------------------------------------------ time */
+static void time_passes(void) {
+ N.t += DT;
+ N.hour_t += DT;
+ if (N.hour_t < HOUR) return;
+ N.hour_t -= HOUR;
+ N.hour++;
+ if (N.night <= 6) apply_hour(N.night, N.hour);
+ if (N.hour >= 6) six_am();
+}
+
+static void sounds(void) {
+ N.laugh_t += DT;
+ if (N.laugh_t < 4) return;
+ N.laugh_t -= 4;
+ if (N.bb_in) caption("*Balloon Boy laughs*");
+ int m = bot_at(MANGLE);
+ if (m == L_HALL || m == L_RVENT || m == L_RSPOT || m == L_PR1 || m == L_PR2 || m == L_OFFICE)
+ caption(m == L_OFFICE ? "*radio static, overhead*" : "*radio static, close by*");
+}
+
+void night_step(void) {
+ time_passes();
+ if (g.scene != SC_NIGHT) return;
+ int lights = keys();
+ monitor_moves();
+ if (g.scene != SC_NIGHT) return;
+ mask_moves();
+ if (N.blackout > 0) N.blackout -= DT;
+ if (N.flicker > 0) N.flicker -= DT;
+ if (N.glitch > 0) N.glitch -= DT;
+ /* the lights: the flashlight (the hallway, the camera's) uses the battery, the vent lights don't */
+ bool can = lights_work(), batt = battery_left();
+ N.hall_light = (lights & 1) && can && batt;
+ N.vent_light = (lights & 2) && can ? 1 : (lights & 4) && can ? 2 : 0;
+ N.cam_light = (lights & 8) && batt && N.blackout <= 0;
+ if (N.hall_light || N.cam_light) N.battery += 1;
+ bool flash_new = N.hall_light && !N.hall_was;
+ N.hall_was = N.hall_light;
+ if (N.cam_light) { /* the camera's light holds who it falls on */
+ for (int who = 0; who < WALKERS; who++) {
+ int at = bot_at(who);
+ if (at != N.cam || who == BB) continue;
+ if (who >= WF && at == L_PARTS) continue;
+ if (who <= TC && at == L_STAGE) continue;
+ if (who == MANGLE && at == L_PRIZE) continue;
+ N.stun[who] = STUN;
+ }
+ if (N.puppet >= 4 && N.puppet_at == N.cam) N.stun[PUPPET] = STUN;
+ }
+ puppet((lights & 16) != 0);
+ if (g.scene != SC_NIGHT) return;
+ walkers();
+ entries();
+ visitor();
+ if (g.scene != SC_NIGHT) return;
+ foxy(N.hall_light, flash_new);
+ if (g.scene != SC_NIGHT) return;
+ golden(N.hall_light);
+ if (g.scene != SC_NIGHT) return;
+ sounds();
+}
diff --git a/games/fnaf2/src/pic.c b/games/fnaf2/src/pic.c
new file mode 100644
index 00000000..474ffc9d
--- /dev/null
+++ b/games/fnaf2/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 != fnaf2_bin) {
+ for (int k = 0; k < 4; k++) h[k] = huff_tab(k);
+ loaded = fnaf2_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/fnaf2/src/plat.h b/games/fnaf2/src/plat.h
new file mode 100644
index 00000000..59cfe754
--- /dev/null
+++ b/games/fnaf2/src/plat.h
@@ -0,0 +1,41 @@
+/* Five Nights at Freddy's 2: 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 FNAF2_PLAT_H
+#define FNAF2_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, EXE */
+ 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_ANY = 1 << 18
+};
+#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/fnaf2/src/plat_eadk.c b/games/fnaf2/src/plat_eadk.c
new file mode 100644
index 00000000..d94b80d6
--- /dev/null
+++ b/games/fnaf2/src/plat_eadk.c
@@ -0,0 +1,43 @@
+/* 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) | KEY(eadk_key_exe))) r |= K_OK;
+ 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/fnaf2/src/plat_host.c b/games/fnaf2/src/plat_host.c
new file mode 100644
index 00000000..f3f5a8c5
--- /dev/null
+++ b/games/fnaf2/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/fnaf2/src/res.h b/games/fnaf2/src/res.h
new file mode 100644
index 00000000..c9d9b88f
--- /dev/null
+++ b/games/fnaf2/src/res.h
@@ -0,0 +1,15 @@
+/* Five Nights at Freddy's 2: data.bin (tools/pack.py), read where it lies in flash. */
+#ifndef FNAF2_RES_H
+#define FNAF2_RES_H
+#include <stdint.h>
+#include "data.h"
+
+extern const uint8_t *fnaf2_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 fnaf2_bin + rd32(fnaf2_bin + 8 + 4 * s); }
+#endif
diff --git a/games/fnaf2/src/save.c b/games/fnaf2/src/save.c
new file mode 100644
index 00000000..76fae6ad
--- /dev/null
+++ b/games/fnaf2/src/save.c
@@ -0,0 +1,183 @@
+/* Saves: the progress (fnaf2.sav: the night reached, the stars, the custom night), the night as it was when Home quit
+ * (fnaf2res.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 "fnaf2.sav"
+#define RESUME_NAME "fnaf2res.sav"
+#define COPY_NAME "fnaf2_saves.py"
+#define MAGIC 0x32464E46u /* "FNF2" */
+#define VERSION 1
+
+typedef struct {
+ uint32_t magic;
+ uint8_t version, reached, stars, keys_seen;
+ int8_t custom[10]; /* the custom night's last levels */
+ uint8_t custom_mode, 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 2 keeps a copy of your nights\n"
+ "# and stars here, so that reinstalling it doesn't erase\n"
+ "# them. If you delete this file, the game writes it again.\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.reached = g.reached, p.stars = g.stars, p.keys_seen = g.keys_seen;
+ memcpy(p.custom, g.custom, sizeof p.custom);
+ p.custom_mode = g.custom_mode;
+ 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.reached = 1;
+ if (!d || len != sizeof(Progress)) return;
+ Progress p;
+ memcpy(&p, d, sizeof p);
+ if (p.magic != MAGIC || p.version != VERSION) return;
+ g.reached = p.reached >= 1 && p.reached <= 5 ? p.reached : 1;
+ g.stars = p.stars & 15;
+ g.keys_seen = p.keys_seen ? 1 : 0;
+ for (int k = 0; k < 10; k++) g.custom[k] = p.custom[k] >= 0 && p.custom[k] <= 20 ? p.custom[k] : 0;
+ g.custom_mode = p.custom_mode <= 10 ? p.custom_mode : 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) {
+ static const uint8_t len[WALKERS] = {4, 6, 6, 9, 4, 4, 5, 4};
+ if (n->night < 1 || n->night > 7 || n->hour > 5 || n->cam >= CAM_COUNT) return false;
+ for (int k = 0; k < WALKERS; k++)
+ if (n->step[k] >= len[k] || n->ready[k] > 1) return false;
+ for (int k = 0; k < BOTS; k++)
+ if (n->ai[k] < -1 || n->ai[k] > 20 || !(n->move_t[k] >= -1 && n->move_t[k] <= 6)) return false;
+ if (n->occ_state > OCC_DOOMED || (n->occ_state != OCC_NONE && n->occ >= WALKERS) || n->gf > GF_FADING) return false;
+ if (n->puppet > 4 || (n->puppet == 4 && n->puppet_at >= L_COUNT) || n->vent_light > 2) return false;
+ if (!(n->box >= 0 && n->box <= BOX_FULL) || !(n->battery >= 0 && n->battery <= 8000)) return false;
+ if (!(n->pan >= 0 && n->pan <= OFFICE_PAN) || !(n->flip >= 0 && n->flip <= 1) || !(n->mask_anim >= 0 && n->mask_anim <= 1))
+ return false;
+ if (!(n->t >= 0 && n->t < 7 * HOUR) || !(n->hour_t >= 0 && n->hour_t <= HOUR)) 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/fnaf2/src/view.c b/games/fnaf2/src/view.c
new file mode 100644
index 00000000..460b29c9
--- /dev/null
+++ b/games/fnaf2/src/view.c
@@ -0,0 +1,360 @@
+/* Drawing a night: the office (turning, the hallway and the vents in the light, who is in the room, the mask),
+ * the monitor and its cameras (the feeds, their static and light, the map, the music box), and around them the
+ * clock, the flashlight's battery, the music box's warning and the captions of what can be heard. */
+#include <stddef.h>
+#include "game.h"
+#include "gfx.h"
+#include "res.h"
+
+#define N g.n
+#define GREY RGB(0xB8B8B8)
+
+/* chosen once a frame (the bands of a frame must agree) */
+static struct {
+ bool flick_off; /* the lights flickering: this frame dark */
+ int noise;
+ uint32_t seed;
+ int shake;
+} f;
+
+static void prepare(void) {
+ f.flick_off = N.flicker > 0 && rnd() % 3 == 0;
+ f.noise = 4 + (int)(rnd() % 4) + (rnd() % 16 == 0 ? 6 : 0);
+ f.seed = rnd();
+ f.shake = (int)(rnd() % 9) - 4;
+}
+
+/* ------------------------------------------------------------------ helpers */
+static void number(int font, int x, int y, int v, uint16_t c) {
+ char s[4];
+ int n = 0;
+ if (v >= 100) s[n++] = (char)('0' + v / 100);
+ if (v >= 10) s[n++] = (char)('0' + v / 10 % 10);
+ s[n++] = (char)('0' + v % 10);
+ s[n] = 0;
+ gfx_text(font, x, y, s, c);
+}
+
+/* a filled disc, clipped to the band */
+static void disc(int cx, int cy, int r, uint16_t c) {
+ for (int dy = -r; dy <= r; dy++) {
+ int y = cy + dy;
+ if (y < gfx_y0 || y >= gfx_y0 + BAND_H) continue;
+ int w = 0;
+ while ((w + 1) * (w + 1) + dy * dy <= r * r) w++;
+ gfx_fill(cx - w, y, 2 * w + 1, 1, c);
+ }
+}
+
+/* the music box's warning: a triangle with "!" (orange, then red and blinking) */
+static void warning_sign(int x, int y) {
+ if (!box_warning()) return;
+ bool red = N.box <= BOX_FULL / 20;
+ if (red && ((int)(g.t * 4) & 1)) return;
+ uint16_t c = red ? RGB(0xE02020) : RGB(0xF09020);
+ for (int r = 0; r < 18; r++) gfx_fill(x + 10 - r * 10 / 18, y + r, 1 + 2 * (r * 10 / 18), 1, c);
+ gfx_fill(x + 9, y + 5, 3, 7, BLACK);
+ gfx_fill(x + 9, y + 14, 3, 2, BLACK);
+}
+
+/* ------------------------------------------------------------------ around the view */
+static void clock_and_night(void) {
+ char h[3] = {'1', '2', 0}; /* 12 AM, then 1 to 5 */
+ if (N.hour) h[0] = (char)('0' + N.hour), h[1] = 0;
+ int x = 312 - gfx_text_w(FONT_BIG, " AM") - gfx_text_w(FONT_CLOCK, h);
+ x += gfx_text(FONT_CLOCK, x, 4, h, WHITE);
+ gfx_text(FONT_BIG, x, 8, " AM", WHITE);
+ int nx = 312 - gfx_text_w(FONT_HUD, "Night 0");
+ nx += gfx_text(FONT_HUD, nx, 30, "Night ", WHITE);
+ number(FONT_HUD, nx, 30, N.night, WHITE);
+}
+
+static void battery_hud(void) {
+ bool ok = lights_work() || N.flip >= 1;
+ uint16_t c = ok ? WHITE : RGB(0x707070);
+ gfx_frame_rect(8, 8, 44, 16, c);
+ gfx_fill(52, 12, 3, 8, c);
+ int bars = battery_bars();
+ for (int i = 0; i < bars; i++) gfx_fill(11 + 10 * i, 11, 8, 10, ok ? RGB(0x9CD94A) : RGB(0x5A5A5A));
+ gfx_text(FONT_TEXT, 60, 10, "Flashlight", c);
+}
+
+void view_captions(void) {
+ int y = g.scene == SC_NIGHT && g.n.flip >= 1 ? 182 : 196;
+ for (int i = 3; i >= 0; i--) {
+ if (!g.cap[i] || g.cap_t[i] <= 0) continue;
+ int a = g.cap_t[i] > 0.5f ? 32 : (int)(g.cap_t[i] * 64);
+ gfx_text(FONT_TEXT, 9, y + 1, g.cap[i], BLACK);
+ gfx_text(FONT_TEXT, 8, y, g.cap[i], gfx_mix(RGB(0xD8E8FF), BLACK, a));
+ y -= 13;
+ }
+}
+
+/* the bars at the bottom: the mask on the left, the monitor on the right, with their keys */
+static void bottom_bars(bool cams) {
+ if (!cams) {
+ gfx_blend(8, 226, 116, 12, RGB(0xC02020), 12);
+ gfx_frame_rect(8, 226, 116, 12, RGB(0xE06060));
+ gfx_text_c(FONT_TEXT, 66, 226, "2 or down: mask", WHITE);
+ }
+ gfx_blend(196, 226, 116, 12, WHITE, 6);
+ gfx_frame_rect(196, 226, 116, 12, gfx_mix(WHITE, BLACK, 14));
+ gfx_text_c(FONT_TEXT, 254, 226, cams ? "OK: put it down" : "OK: monitor", WHITE);
+}
+
+/* the first night, and the first seconds of every other: what the other keys do */
+static void key_line(bool cams) {
+ if (N.night > 1 && N.t > 15) return;
+ if (cams) {
+ gfx_blend(8, 198, 152, 27, BLACK, 20);
+ gfx_text(FONT_TEXT, 12, 199, "0-9 camera, 1 again: 11 12", RGB(0xE0E0B0));
+ gfx_text(FONT_TEXT, 12, 211, "hold up: light, wind on 11", RGB(0xE0E0B0));
+ return;
+ }
+ gfx_blend(0, 210, SCREEN_W, 14, BLACK, 20);
+ gfx_text_c(FONT_TEXT, 160, 211, "4 6 look 5 or up: hall light 7 9: vent lights", RGB(0xE0E0B0));
+}
+
+/* ------------------------------------------------------------------ the office */
+static int hall_picture(void) {
+ if (N.gf == GF_HALL) return PIC_HALL_GF;
+ if (N.foxy_hall) return PIC_HALL_FOXY;
+ static const struct { uint8_t who, pic; } in_hall[] = {
+ {WF, PIC_HALL_WF}, {TF, PIC_HALL_TF}, {WB, PIC_HALL_WB}, {TC, PIC_HALL_TC}, {MANGLE, PIC_HALL_MANGLE}};
+ for (unsigned i = 0; i < sizeof in_hall / sizeof in_hall[0]; i++)
+ if (bot_at(in_hall[i].who) == L_HALL) return in_hall[i].pic;
+ if (bot_at(TF) == L_HALL_FAR) return PIC_HALL_TFFAR;
+ return PIC_HALL_LIT;
+}
+
+static int vent_picture(int side) {
+ if (side == 0) return bot_at(TC) == L_LSPOT ? PIC_LVENT_TC : bot_at(BB) == L_LSPOT ? PIC_LVENT_BB : PIC_LVENT_LIT;
+ return bot_at(TB) == L_RSPOT ? PIC_RVENT_TB : bot_at(MANGLE) == L_RSPOT ? PIC_RVENT_MANGLE : PIC_RVENT_LIT;
+}
+
+static int visitor_picture(void) {
+ if (N.gf == GF_SHOWN || N.gf == GF_FADING) return PIC_OCC_GF;
+ if (N.occ_state != OCC_SHOWN && N.occ_state != OCC_MASKED) return -1;
+ static const uint8_t pics[WALKERS] = {[TF] = PIC_OCC_TF, [TB] = PIC_OCC_TB, [TC] = PIC_OCC_TC,
+ [WF] = PIC_OCC_WF, [WB] = PIC_OCC_WB, [WC] = PIC_OCC_WC};
+ return N.occ < WALKERS ? pics[N.occ] : -1;
+}
+
+/* the Freddy mask: dark but for its eyes, coming down from the top */
+static void mask_view(void) {
+ int bottom = (int)(N.mask_anim * SCREEN_H);
+ int y0 = gfx_y0, y1 = gfx_y0 + BAND_H < bottom ? gfx_y0 + BAND_H : bottom;
+ int top = bottom - SCREEN_H; /* the mask's top row */
+ for (int y = y0; y < y1; y++) {
+ int my = y - top; /* in the mask */
+ /* the eyes: two ellipses */
+ int spans[2][2], n = 0;
+ for (int e = 0; e < 2; e++) {
+ int cx = e ? 214 : 106, cy = 104, rx = 50, ry = 34, dy = my - cy;
+ if (dy * dy >= ry * ry) continue;
+ int w = (int)(rx * __builtin_sqrtf(1.0f - (float)(dy * dy) / (float)(ry * ry)));
+ spans[n][0] = cx - w, spans[n][1] = cx + w, n++;
+ }
+ int x = 0;
+ for (int k = 0; k <= n; k++) {
+ int end = k < n ? spans[k][0] : SCREEN_W;
+ if (end > x) {
+ gfx_dim(x, y, end - x, 1, 3);
+ gfx_blend(x, y, end - x, 1, RGB(0x2A1608), 10);
+ }
+ if (k < n) {
+ gfx_dim(spans[k][0], y, spans[k][1] - spans[k][0], 1, 22);
+ x = spans[k][1];
+ }
+ }
+ }
+}
+
+static void office(void) {
+ int px = (int)N.pan;
+ if (N.blackout > 0) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ return;
+ }
+ pic_part(PIC_OFFICE, 0, 0, px, 0, SCREEN_W, SCREEN_H);
+ if (N.hall_light) pic_draw(hall_picture(), HALL_X - px, HALL_Y);
+ if (N.vent_light == 1) pic_draw(vent_picture(0), LVENT_X - px, LVENT_Y);
+ if (N.vent_light == 2) pic_draw(vent_picture(1), RVENT_X - px, RVENT_Y);
+ if (N.mangle_in) pic_draw(PIC_OFFICE_MANGLE, MANGLE_X - px, MANGLE_Y);
+ if (N.bb_in) pic_draw(PIC_OFFICE_BB, BBO_X - px, BBO_Y);
+ int v = visitor_picture();
+ if (v >= 0) {
+ pic_draw(v, OCC_X - px, OCC_Y);
+ if (N.gf == GF_FADING) gfx_dim(OCC_X - px, gfx_y0, pic_w(v), BAND_H, 32 - (int)(N.gf_t / 1.5f * 32));
+ }
+ if (f.flick_off) gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, 6);
+}
+
+/* ------------------------------------------------------------------ the cameras */
+static const char *const cam_names[CAM_COUNT] = {
+ "Party Room 1", "Party Room 2", "Party Room 3", "Party Room 4", "Left Air Vent", "Right Air Vent", "Main Hall",
+ "Parts/Service", "Show Stage", "Game Area", "Prize Corner", "Kid's Cove"};
+
+static bool at(int who, int loc) { return bot_at(who) == loc; }
+static bool puppet_at(int loc) { return N.puppet >= 4 && N.puppet_at == loc; }
+
+/* the feed: the dark rooms (the party rooms, the vents) show nothing but in the light */
+static int cam_picture(bool lit) {
+ switch (N.cam) {
+ case L_PR1:
+ if (!lit) return PIC_CAM01_DARK;
+ return puppet_at(L_PR1) ? PIC_CAM01_PUPPET : at(WB, L_PR1) ? PIC_CAM01_WB : at(TC, L_PR1) ? PIC_CAM01_TC
+ : at(MANGLE, L_PR1) ? PIC_CAM01_MANGLE : PIC_CAM01_LIT;
+ case L_PR2:
+ if (!lit) return PIC_CAM02_DARK;
+ return puppet_at(L_PR2) ? PIC_CAM02_PUPPET : at(WC, L_PR2) ? PIC_CAM02_WC : at(TB, L_PR2) ? PIC_CAM02_TB
+ : at(MANGLE, L_PR2) ? PIC_CAM02_MANGLE : PIC_CAM02_LIT;
+ case L_PR3:
+ if (!lit) return PIC_CAM03_DARK;
+ return puppet_at(L_PR3) ? PIC_CAM03_PUPPET : at(WF, L_PR3) ? PIC_CAM03_WF : at(TB, L_PR3) ? PIC_CAM03_TB
+ : PIC_CAM03_LIT;
+ case L_PR4:
+ if (!lit) return PIC_CAM04_DARK;
+ return puppet_at(L_PR4) ? PIC_CAM04_PUPPET : at(WC, L_PR4) ? PIC_CAM04_WC : at(TB, L_PR4) ? PIC_CAM04_TB
+ : PIC_CAM04_LIT;
+ case L_LVENT:
+ if (!lit) return PIC_CAM05_DARK;
+ return at(WB, L_LVENT) ? PIC_CAM05_WB : at(TC, L_LVENT) ? PIC_CAM05_TC : at(BB, L_LVENT) ? PIC_CAM05_BB
+ : PIC_CAM05_LIT;
+ case L_RVENT:
+ if (!lit) return PIC_CAM06_DARK;
+ return at(WC, L_RVENT) ? PIC_CAM06_WC : at(TB, L_RVENT) ? PIC_CAM06_TB : at(MANGLE, L_RVENT) ? PIC_CAM06_MANGLE
+ : PIC_CAM06_LIT;
+ case L_MAIN:
+ return puppet_at(L_MAIN) ? PIC_CAM07_PUPPET : at(WF, L_MAIN) ? PIC_CAM07_WF : at(WB, L_MAIN) ? PIC_CAM07_WB
+ : at(TC, L_MAIN) ? PIC_CAM07_TC : at(MANGLE, L_MAIN) ? PIC_CAM07_MANGLE : PIC_CAM07_EMPTY;
+ case L_PARTS: {
+ int m = at(WF, L_PARTS) | at(WB, L_PARTS) << 1 | at(WC, L_PARTS) << 2;
+ if (!m && N.ai[FOXY] >= 0 && !N.foxy_hall) return PIC_CAM08_FOXY;
+ return PIC_CAM08_S0 + m;
+ }
+ case L_STAGE: return PIC_CAM09_S0 + (at(TF, L_STAGE) | at(TB, L_STAGE) << 1 | at(TC, L_STAGE) << 2);
+ case L_GAME:
+ return at(TF, L_GAME) ? PIC_CAM10_TF : at(BB, L_GAME) ? PIC_CAM10_BB : at(MANGLE, L_GAME) ? PIC_CAM10_MANGLE
+ : PIC_CAM10_EMPTY;
+ case L_PRIZE:
+ if (N.puppet < 4) return N.puppet == 0 && at(MANGLE, L_PRIZE) ? PIC_CAM11_MANGLE : PIC_CAM11_P0 + N.puppet;
+ return at(MANGLE, L_PRIZE) ? PIC_CAM11_MANGLE : PIC_CAM11_EMPTY;
+ default: return at(MANGLE, L_KIDS) ? PIC_CAM12_MANGLE : PIC_CAM12_EMPTY;
+ }
+}
+
+static void tiny_label(int x, int y, int cam, uint16_t c) {
+ char s[3] = {(char)('0' + (cam + 1) / 10), (char)('0' + (cam + 1) % 10), 0};
+ gfx_text_c(FONT_TEXT, x, y, s, c);
+}
+
+static void camera_map(void) {
+ const uint8_t *m = section(SEC_MAP);
+ int mw = (int)rd16(m), mh = (int)rd16(m + 2), stride = (mw + 7) >> 3;
+ int mx = SCREEN_W - mw - 6, my = 216 - mh;
+ for (int r = 0; r < mh; r++) {
+ int y = my + r;
+ if (y < gfx_y0 || y >= gfx_y0 + BAND_H) continue;
+ const uint8_t *row = m + 4 + r * stride;
+ uint16_t *d = gfx_band + (y - gfx_y0) * SCREEN_W + mx;
+ for (int c = 0; c < mw; c++)
+ if (row[c >> 3] >> (c & 7) & 1) d[c] = WHITE;
+ }
+ const uint8_t *centres = m + 4 + mh * stride;
+ bool blink = !((int)(g.t * 3) & 1);
+ for (int k = 0; k < CAM_COUNT; k++) {
+ int cx = mx + (int)rd16(centres + 4 * k), cy = my + (int)rd16(centres + 4 * k + 2);
+ bool sel = k == N.cam;
+ gfx_fill(cx - 9, cy - 6, 19, 13, sel && blink ? RGB(0x8BC34A) : RGB(0x3A3A3A));
+ gfx_frame_rect(cx - 9, cy - 6, 19, 13, RGB(0xD0D0D0));
+ tiny_label(cx + 1, cy - 6, k, WHITE);
+ if (k == L_PRIZE) warning_sign(cx + 11, cy - 9);
+ }
+ gfx_text(FONT_HUD, 12, 34, cam_names[N.cam], WHITE);
+ char s[] = "CAM 00";
+ s[4] = (char)('0' + (N.cam + 1) / 10), s[5] = (char)('0' + (N.cam + 1) % 10);
+ gfx_text(FONT_HUD, 12, 48, s, RGB(0xC0C0C0));
+}
+
+/* CAM 11: the music box's button and how wound it is (20 marks round a circle) */
+static void music_box(void) {
+ int cx = 70, cy = 106;
+ gfx_blend(14, 76, 112, 58, BLACK, 18);
+ gfx_frame_rect(14, 76, 112, 58, N.winding ? WHITE : GREY);
+ gfx_text_c(FONT_HUD, 70, 118, N.winding ? "winding..." : "hold up: wind", WHITE);
+ int marks = (int)(N.box * 20 / BOX_FULL + 0.999f);
+ static const int8_t ring[20][2] = {{0, -13}, {4, -12}, {8, -11}, {11, -8}, {12, -4}, {13, 0}, {12, 4}, {11, 8},
+ {8, 11}, {4, 12}, {0, 13}, {-4, 12}, {-8, 11}, {-11, 8}, {-12, 4}, {-13, 0},
+ {-12, -4}, {-11, -8}, {-8, -11}, {-4, -12}};
+ for (int i = 0; i < 20; i++)
+ gfx_fill(cx + ring[i][0] - 1, cy - 10 + ring[i][1] - 1, 3, 3, i < marks ? WHITE : RGB(0x404040));
+}
+
+static void cameras(void) {
+ bool lit = N.cam_light;
+ if (N.glitch > 0) {
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, 18, f.seed);
+ } else {
+ pic_draw(cam_picture(lit), 0, 0);
+ bool dark_room = N.cam <= L_RVENT;
+ if (lit && !dark_room) gfx_dim(0, gfx_y0, SCREEN_W, BAND_H, 46);
+ gfx_static(0, gfx_y0, SCREEN_W, BAND_H, f.noise + (N.cam == N.puppet_at && N.puppet >= 4 ? 8 : 0), f.seed);
+ }
+ if (g.blip > 0) gfx_blend(0, gfx_y0, SCREEN_W, BAND_H, WHITE, (int)(g.blip * 120));
+ gfx_frame_rect(5, 5, 310, 230, gfx_mix(WHITE, BLACK, 20));
+ if ((int)(g.t * 1.5f) & 1) disc(64, 53, 4, RGB(0xE02020));
+ camera_map();
+ if (N.cam == L_PRIZE) music_box();
+}
+
+/* the monitor coming up, or going down */
+static void tablet(void) {
+ int top = (int)((1 - N.flip) * SCREEN_H);
+ gfx_fill(6, top, SCREEN_W - 12, SCREEN_H - top, RGB(0x1C1F22));
+ gfx_frame_rect(6, top, SCREEN_W - 12, SCREEN_H - top + 2, RGB(0x50565C));
+ gfx_fill(20, top + 12, SCREEN_W - 40, SCREEN_H - top - 12, RGB(0x0A0C0D));
+}
+
+/* ------------------------------------------------------------------ the night */
+static void night_draw(void) {
+ bool cams = N.flip >= 1;
+ if (cams) cameras();
+ else {
+ office();
+ if (N.mask_anim > 0) mask_view();
+ if (N.flip > 0) tablet();
+ }
+ if (N.blackout <= 0 || cams) {
+ clock_and_night();
+ battery_hud();
+ if (!cams) warning_sign(286, 202);
+ key_line(cams);
+ if (N.mask_anim <= 0 || cams) bottom_bars(cams);
+ }
+ view_captions();
+}
+
+void view_night(void) {
+ if (gfx_y0 == 0) prepare();
+ night_draw();
+}
+
+/* ------------------------------------------------------------------ jumpscares */
+void view_scare(void) {
+ static const uint8_t first[BOTS] = {[TF] = PIC_SCARE_TF0, [TB] = PIC_SCARE_TB0, [TC] = PIC_SCARE_TC0,
+ [MANGLE] = PIC_SCARE_MANGLE0, [WF] = PIC_SCARE_WF0, [WB] = PIC_SCARE_WB0,
+ [WC] = PIC_SCARE_WC0, [FOXY] = PIC_SCARE_FOXY0, [GF] = PIC_SCARE_GF0,
+ [PUPPET] = PIC_SCARE_PUPPET0};
+ static const uint8_t count[BOTS] = {[TF] = SCARE_TF_N, [TB] = SCARE_TB_N, [TC] = SCARE_TC_N,
+ [MANGLE] = SCARE_MANGLE_N, [WF] = SCARE_WF_N, [WB] = SCARE_WB_N,
+ [WC] = SCARE_WC_N, [FOXY] = SCARE_FOXY_N, [GF] = SCARE_GF_N,
+ [PUPPET] = SCARE_PUPPET_N};
+ if (gfx_y0 == 0) prepare();
+ int w = g.scare < BOTS && count[g.scare] ? g.scare : TF;
+ int k = (int)(g.scare_t * 24) % count[w];
+ int dx = g.scare_t > 0.08f ? f.shake : 0;
+ gfx_fill(0, gfx_y0, SCREEN_W, BAND_H, BLACK);
+ pic_draw(first[w] + k, dx, 0);
+}
diff --git a/games/fnaf2/tests/check.py b/games/fnaf2/tests/check.py
new file mode 100644
index 00000000..43742d7f
--- /dev/null
+++ b/games/fnaf2/tests/check.py
@@ -0,0 +1,242 @@
+#!/usr/bin/env python3
+"""Checks of Five Nights at Freddy's 2 on a computer (make test): the host build, with AddressSanitizer and
+UBSan, through every picture, the menus, whole nights played by tests/play.c's own player, the paychecks, the
+custom night, pausing, Home, damaged and lost saves, and a few hundred sessions of random keys.
+
+ python3 tests/check.py build/play build/pictures [--quick]
+
+--quick plays fewer nights and fuzz sessions."""
+import concurrent.futures
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+PLAY = sys.argv[1] if len(sys.argv) > 1 else "build/play"
+PICTURES = sys.argv[2] if len(sys.argv) > 2 else "build/pictures"
+QUICK = "--quick" in sys.argv
+ENV = dict(os.environ, ASAN_OPTIONS="detect_leaks=0", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1")
+failures = []
+SC_TITLE, SC_NEWS, SC_KEYS, SC_INTRO, SC_NIGHT, SC_SCARE, SC_SIX, SC_PAPER, SC_OVER, SC_CUSTOM = range(10)
+TF, TB, TC, MANGLE, BB, WF, WB, WC, FOXY, GF, PUPPET = range(11)
+NIGHT = 60 * 6 * 68 + 400 # a night's steps, its card and a bit
+
+
+def run(args, frames, saves=None, what=""):
+ """Plays; returns the end state (a dict) and the events (6 AM, jumpscares) on the way"""
+ own = saves is None
+ if own:
+ saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+ shots = tempfile.mkdtemp(prefix="fnaf2_shots_")
+ p = subprocess.run([PLAY, "--saves", saves, "--out", shots, "--frames", str(frames)] + args, capture_output=True,
+ text=True, env=ENV, timeout=1800)
+ shutil.rmtree(shots, ignore_errors=True)
+ if own:
+ shutil.rmtree(saves, ignore_errors=True)
+ if p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr:
+ failures.append(f"{what or args}: crashed or a sanitizer error\n{p.stderr[-2000:]}")
+ return None, []
+ m = re.search(r"END (.*)", p.stdout)
+ if not m:
+ failures.append(f"{what}: no end state\n{p.stdout[-500:]}")
+ return None, []
+ words = m.group(1).split()
+ s = {}
+ for k, v in zip(words[::2], words[1::2]):
+ s[k] = [int(x) for x in v.split(",")] if "," in v else float(v) if "." in v else int(v)
+ events = [dict(zip(e.split()[1::2], e.split()[2::2]), kind=e.split()[0])
+ for e in re.findall(r"EVENT (.*)", p.stdout)]
+ return s, events
+
+
+def check(cond, msg):
+ if not cond:
+ failures.append(msg)
+
+
+def record(saves, name):
+ p = os.path.join(saves, name)
+ return open(p, "rb").read() if os.path.exists(p) else None
+
+
+def scared_by(ev, who):
+ return any(e["kind"] == "scare" and int(e["who"]) == who for e in ev)
+
+
+# every picture decodes
+d = tempfile.mkdtemp(prefix="fnaf2_pics_")
+p = subprocess.run([PICTURES, d], capture_output=True, text=True, env=ENV, timeout=600)
+check(p.returncode == 0 and "runtime error" not in p.stderr, f"pictures: {p.stderr[-1500:]}")
+check(len(os.listdir(d)) >= 138, f"pictures: only {len(os.listdir(d))} drawn")
+shutil.rmtree(d, ignore_errors=True)
+
+# the title, New Game, the newspaper (skipped), how to play, the first night's card, then the office
+saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+s, _ = run(["--keys", "60:ok,200:ok,700:ok"], 1400, saves, "a new game")
+if s:
+ check(s["scene"] == SC_NIGHT and s["night"] == 1 and s["keys_seen"] == 1, f"a new game: {s}")
+ check(record(saves, "fnaf2.sav") is not None and record(saves, "fnaf2_saves.py") is not None,
+ "a new game: no save, or no copy of it")
+# Back pauses; Quit night asks, and Yes goes back to the title
+s, _ = run(["--night", "1", "--keys", "400:back,430:down,450:down,470:ok,500:right,520:ok"], 600, saves, "quitting")
+if s:
+ check(s["scene"] == SC_TITLE, f"quitting a night: {s}")
+# ... No goes back to the pause menu, Back to the night
+s, _ = run(["--night", "1", "--keys", "400:back,430:down,450:down,470:ok,520:ok,560:back"], 620, saves, "not quitting")
+if s:
+ check(s["scene"] == SC_NIGHT and s["paused"] == 0, f"not quitting: {s}")
+shutil.rmtree(saves, ignore_errors=True)
+
+
+# whole nights, played by the test's player: the first one always, the next ones with one of three tries
+def night(n, seed):
+ saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+ s, ev = run(["--night", str(n), "--bot", "--seed", str(seed)], NIGHT + 900, saves, f"night {n}")
+ shutil.rmtree(saves, ignore_errors=True)
+ six = [e for e in ev if e["kind"] == "six"]
+ return s, six and int(six[0]["night"]) == n, ev
+
+
+with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as pool:
+ jobs = {(n, seed): pool.submit(night, n, seed) for n in ([1, 2] if QUICK else [1, 2, 3]) for seed in (1, 2, 3)}
+ for n in sorted({k[0] for k in jobs}):
+ results = [jobs[(n, seed)].result() for seed in (1, 2, 3)]
+ won = [r for r in results if r[1]]
+ if n == 1:
+ check(len(won) == 3, f"night 1 not survived: {[r[2] for r in results]}")
+ else:
+ check(won, f"night {n} never survived: {[r[2] for r in results]}")
+ for s, ok, ev in won:
+ check(s["reached"] == n + 1 and s["night"] == n + 1, f"night {n}: the next night not reached: {s}")
+
+# the fifth night's 6 AM: a star and the paycheck, then the title; the sixth's: the overtime, the custom night
+s, ev = run(["--night", "5", "--hour", "5", "--ai", "0,0,0,0,0,0,0,0,0,0,0", "--bot"], 68 * 60 + 2400, None,
+ "night 5's end")
+if s:
+ check(any(e["kind"] == "six" for e in ev) and s["stars"] & 1 and s["scene"] == SC_TITLE, f"night 5's end: {s} {ev}")
+s, ev = run(["--night", "6", "--hour", "5", "--ai", "0,0,0,0,0,0,0,0,0,0,0", "--bot"], 68 * 60 + 2400, None,
+ "night 6's end")
+if s:
+ check(any(e["kind"] == "six" for e in ev) and s["stars"] & 2 and s["scene"] == SC_CUSTOM, f"night 6's end: {s} {ev}")
+
+# the music box left alone: the Puppet comes, through the mask
+s, ev = run(["--night", "4", "--ai", "0,0,0,0,0,0,0,0,-1,0,9", "--box", "0", "--keys", "300:2"], 60 * 60, None,
+ "the Puppet")
+if s:
+ check(scared_by(ev, PUPPET), f"the Puppet: {s} {ev}")
+
+# Toy Bonnie waiting in the vent comes in with the monitor; down without the mask, up and down again: caught
+s, ev = run(["--night", "1", "--step", "1:5", "--ready", "1", "--keys", "300:ok,400:ok,600:ok,700:ok"], 900, None,
+ "Toy Bonnie")
+if s:
+ check(scared_by(ev, TB), f"Toy Bonnie: {s} {ev}")
+# ... with the mask at once: he leaves
+s, ev = run(["--night", "1", "--step", "1:5", "--ready", "1", "--keys", "300:ok,400:ok,422:2,1000:2"], 1100, None,
+ "Toy Bonnie masked")
+if s:
+ check(not ev and s["occ_state"] == 0 and s["steps"][TB] == 1, f"Toy Bonnie masked: {s} {ev}")
+
+# Balloon Boy gets in: no lights, but no jumpscare
+s, ev = run(["--night", "2", "--ai", "0,0,0,0,0,0,0,0,-1,0,0", "--step", "4:3", "--ready", "4",
+ "--keys", "300:ok,400:ok,500-600:5"], 1400, None, "Balloon Boy")
+if s:
+ check(not ev and s["bb_in"] == 1, f"Balloon Boy: {s} {ev}")
+
+# Withered Foxy in the hallway, never flashed: he gets you; flashed, he goes back
+s, ev = run(["--night", "4", "--ai", "0,0,0,0,0,0,0,0,17,0,0", "--foxy-hall"], 60 * 40, None, "Foxy")
+if s:
+ check(scared_by(ev, FOXY), f"Foxy: {s} {ev}")
+flashes = ",".join(f"{300 + 20 * k}-{306 + 20 * k}:5" for k in range(6))
+s, ev = run(["--night", "4", "--ai", "0,0,0,0,0,0,0,0,7,0,0", "--foxy-hall", "--keys", flashes + ",500:ok,600:ok"],
+ 700, None, "Foxy flashed")
+if s:
+ check(not ev and s["foxy_hall"] == 0, f"Foxy flashed: {s} {ev}")
+
+# the custom night: the 20/20/20/20 mode starts night 7 with its levels
+s, _ = run(["--stars", "3", "--keys", "100:down,120:down,140:down,160:ok,200:left,240:up,300:ok"], 600, None,
+ "custom night 20")
+if s:
+ check(s["scene"] == SC_NIGHT and s["night"] == 7 and s["ai"][WF:FOXY + 1] == [20, 20, 20, 20] and s["ai"][PUPPET] == 15,
+ f"custom night 20/20/20/20: {s}")
+
+# Home keeps the night: the next start is back in it, paused, at the same moment; installing apps keeps only the
+# scripts, and it comes back from the copy
+saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+s, _ = run(["--night", "1", "--keys", "300:2,1500:home"], 1600, saves, "Home")
+if s and record(saves, "fnaf2res.sav") is None:
+ check(False, f"Home: no kept night ({s})")
+elif s:
+ check(s["running"] == 0, f"Home: {s}")
+ os.remove(os.path.join(saves, "fnaf2res.sav"))
+ s2, _ = run([], 30, saves, "back after Home")
+ if s2:
+ check(s2["scene"] == SC_NIGHT and s2["paused"] == 1 and s2["night"] == 1 and abs(s2["t"] - s["t"]) < 0.5
+ and s2["mask"] == 1, f"back after Home, from the copy: {s2} (left at {s})")
+ check(record(saves, "fnaf2res.sav") is None, "the kept night is read once")
+shutil.rmtree(saves, ignore_errors=True)
+
+# the progress: lost (comes back from the copy), and damaged (starts over, never crashes)
+saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+s, _ = run(["--night", "1", "--hour", "5", "--ai", "0,0,0,0,0,0,0,0,-1,0,0", "--bot"], 68 * 60 + 1400, saves,
+ "night 1 won")
+if s and record(saves, "fnaf2.sav"):
+ os.remove(os.path.join(saves, "fnaf2.sav"))
+ s2, _ = run([], 30, saves, "after a reinstall")
+ check(record(saves, "fnaf2.sav") is not None and s2 and s2["reached"] == 2,
+ f"after a reinstall: fnaf2.sav not restored from fnaf2_saves.py ({s2})")
+shutil.rmtree(saves, ignore_errors=True)
+good = None
+saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+run(["--keys", "60:ok"], 100, saves, "a save")
+good = record(saves, "fnaf2.sav")
+shutil.rmtree(saves, ignore_errors=True)
+damaged = {"empty": b"", "short": good[:7], "long": good + b"\0", "magic": b"XXXX" + good[4:],
+ "version": good[:4] + b"\x63" + good[5:], "garbage": bytes(range(len(good))),
+ "levels": good[:8] + bytes([200] * 10) + good[18:]}
+for name, data in damaged.items():
+ saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+ open(os.path.join(saves, "fnaf2.sav"), "wb").write(data)
+ s, _ = run(["--keys", "60:down,80:ok"], 400, saves, f"a damaged save ({name})")
+ if s:
+ check(1 <= s["reached"] <= 5 and s["scene"] in (SC_TITLE, SC_INTRO, SC_NIGHT, SC_CUSTOM),
+ f"a damaged save ({name}): {s}")
+ shutil.rmtree(saves, ignore_errors=True)
+# a damaged kept night: thrown away, the title
+saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+run(["--night", "3", "--keys", "500:home"], 600, saves, "a kept night")
+night_bytes = record(saves, "fnaf2res.sav")
+shutil.rmtree(saves, ignore_errors=True)
+if night_bytes:
+ for name, data in {"short": night_bytes[:40], "garbage": bytes((i * 37) & 255 for i in range(len(night_bytes))),
+ "places": night_bytes[:20] + bytes([99] * 30) + night_bytes[50:]}.items():
+ saves = tempfile.mkdtemp(prefix="fnaf2_check_")
+ open(os.path.join(saves, "fnaf2res.sav"), "wb").write(data)
+ s, _ = run([], 60, saves, f"a damaged kept night ({name})")
+ if s:
+ check(s["scene"] == SC_TITLE and record(saves, "fnaf2res.sav") is None,
+ f"a damaged kept night ({name}): {s}")
+ shutil.rmtree(saves, ignore_errors=True)
+
+
+# random keys: a few hundred sessions from the title and from each night, never a crash or a sanitizer error
+def fuzz(k):
+ args = ["--fuzz", "--seed", str(k)]
+ if k % 3:
+ args += ["--night", str(1 + k % 7), "--stars", "15"]
+ s, _ = run(args, 2400, None, f"random keys {k}")
+ return s is not None
+
+
+with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as pool:
+ n = 60 if QUICK else 300
+ ok = sum(pool.map(fuzz, range(n)))
+check(ok == n, f"random keys: {n - ok} of {n} sessions failed")
+
+if failures:
+ print(f"{len(failures)} failures:")
+ for f in failures:
+ print("-", f)
+ sys.exit(1)
+print("all checks passed")
diff --git a/games/fnaf2/tests/pics.c b/games/fnaf2/tests/pics.c
new file mode 100644
index 00000000..e4db1524
--- /dev/null
+++ b/games/fnaf2/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 fnaf2_data[];
+const uint8_t *fnaf2_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);
+ fnaf2_bin = fnaf2_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/fnaf2/tests/play.c b/games/fnaf2/tests/play.c
new file mode 100644
index 00000000..a8c14d66
--- /dev/null
+++ b/games/fnaf2/tests/play.c
@@ -0,0 +1,244 @@
+/* Plays Five Nights at Freddy's 2 on a computer, with scripted keys (or a player of its own), and saves frames.
+ *
+ * play [--frames N] [--keys "10-40:left,50:ok,..."] [--shots 30,60|all|every:N] [--out DIR] [--saves DIR]
+ * [--night N] [--ai A,B,...] [--hour H] [--box B] [--step WHO:STEP] [--ready WHO] [--foxy-hall]
+ * [--custom A,...] [--stars S] [--seed S] [--bot] [--fuzz]
+ *
+ * Keys: left right up down ok back home del 0 to 9. "a-b:key" holds the key from frame (step) a to b, "a:key" for
+ * one step. --night starts that night (its card first); --ai (the eleven: Toy Freddy, Toy Bonnie, Toy Chica,
+ * Mangle, Balloon Boy, Withered Freddy, Bonnie, Chica, Foxy, Golden Freddy, the Puppet; -1 keeps one), --hour,
+ * --box (the music box), --step (an animatronic's place on its path), --ready and --foxy-hall then set the night;
+ * --custom the custom night's ten levels, --stars the stars won. --bot plays the night itself (it knows where
+ * everyone is). --fuzz presses random keys (never Home). Frames are steps (60 a second); the screen is drawn every
+ * second step. Screenshots are DIR/shot_<frame>.ppm. At the end it prints the state: "END scene ... night ...". */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include "../src/game.h"
+#include "../src/gfx.h"
+#include "../src/res.h"
+
+extern uint32_t host_keys, host_time;
+void host_shot(const char *path);
+void host_save_dir(const char *d);
+extern const uint8_t fnaf2_data[];
+const uint8_t *fnaf2_bin;
+
+typedef struct { int a, b; uint32_t k; } Hold;
+static Hold holds[4096];
+static int nholds;
+
+static uint32_t key_of(const char *s) {
+ static const struct { const char *n; uint32_t k; } names[] = {
+ {"left", K_LEFT}, {"right", K_RIGHT}, {"up", K_UP}, {"down", K_DOWN}, {"ok", K_OK}, {"back", K_BACK},
+ {"home", K_HOME}, {"del", K_DEL}};
+ for (unsigned i = 0; i < sizeof names / sizeof names[0]; i++)
+ if (!strcmp(s, names[i].n)) return names[i].k;
+ if (s[0] >= '0' && s[0] <= '9' && !s[1]) return K_DIGIT(s[0] - '0');
+ fprintf(stderr, "unknown key %s\n", s);
+ exit(2);
+}
+
+static void parse_keys(char *s) {
+ for (char *t = strtok(s, ","); t; t = strtok(NULL, ",")) {
+ char *colon = strchr(t, ':');
+ if (!colon || nholds >= 4096) continue;
+ *colon = 0;
+ int a = atoi(t), b = a;
+ char *dash = strchr(t, '-');
+ if (dash) b = atoi(dash + 1);
+ holds[nholds++] = (Hold){a, b, key_of(colon + 1)};
+ }
+}
+
+/* ------------------------------------------------------------------ a player */
+static bool at_last(int who) {
+ int at = bot_at(who);
+ return at == L_LSPOT || at == L_RSPOT || (at == L_HALL && (who == TF || who == WF)) ||
+ (who == WB && at == L_LVENT) || (who == WC && at == L_RVENT);
+}
+
+static uint32_t bot(int f) {
+ Night *n = &g.n;
+ static int flash_until, next_flash, winding;
+ if (g.scene != SC_NIGHT || g.paused) return 0;
+ bool up = n->flip >= 1, down = n->flip <= 0 && !n->monitor;
+ bool showing = n->occ_state == OCC_SHOWN || n->gf == GF_SHOWN;
+ bool staying = n->occ_state == OCC_MASKED || n->occ_state == OCC_LEAVING || n->gf == GF_FADING;
+ /* someone waiting at a vent or the hallway: the mask, unless the music box needs winding */
+ bool threat = false;
+ for (int k = 0; k < WALKERS; k++)
+ if (at_last(k) && !(k == MANGLE && n->mangle_in) && !(k == BB && n->bb_in)) threat = true;
+ bool need_wind = n->box < 900 || (winding && n->box < BOX_FULL - 20);
+ static int up_since, flashed_after;
+ if (n->monitor) {
+ if (!up) return 0;
+ if (!up_since) up_since = f;
+ flashed_after = 0;
+ /* never more than 3.5 s up: Foxy may have come to the hallway */
+ if (n->cam != L_PRIZE && f - up_since < 210) return (f & 1) ? 0 : K_DIGIT(1);
+ if (n->box < BOX_FULL - 20 && f - up_since < 210) {
+ winding = 1;
+ return K_UP;
+ }
+ winding = n->box < BOX_FULL - 20;
+ return (f & 1) ? 0 : K_OK;
+ }
+ up_since = 0;
+ if (!down) return 0;
+ if (showing && !n->mask) return K_DOWN;
+ if (staying) return 0;
+ if (n->mask) {
+ if (threat && n->box > 400 && !(n->foxy_hall && !n->foxy_off)) return 0;
+ return (f & 1) ? 0 : K_DOWN; /* off */
+ }
+ if (n->mask_anim > 0) return 0;
+ /* the hallway: a short flash every 2 s, quick ones while Foxy is there until he's off (never at Golden
+ Freddy's head) */
+ if (!flashed_after && n->gf != GF_HALL) next_flash = f, flashed_after = 1; /* a look down the hall */
+ if (n->ai[FOXY] >= 0 && n->gf != GF_HALL && n->battery < battery_frames(n->night) - 30) {
+ if (f < flash_until) return K_DIGIT(5);
+ if (f >= next_flash) {
+ bool foxy_there = n->foxy_hall && !n->foxy_off;
+ flash_until = f + 8;
+ next_flash = f + (foxy_there ? 20 : 120);
+ return K_DIGIT(5);
+ }
+ }
+ if (threat && n->box > 400 && n->occ_state == OCC_NONE) return (f & 1) ? 0 : K_DOWN;
+ if (need_wind || n->foxy_off) return (f & 1) ? 0 : K_OK;
+ return 0;
+}
+
+/* random keys: mostly the ones a night uses, now and then Back, never Home */
+static uint32_t fuzz(void) {
+ static uint32_t keep;
+ static int left;
+ if (left-- > 0) return keep;
+ static const uint32_t keys[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_BACK, K_DEL, K_DIGIT(0), K_DIGIT(1),
+ K_DIGIT(2), K_DIGIT(3), K_DIGIT(4), K_DIGIT(5), K_DIGIT(6), K_DIGIT(7),
+ K_DIGIT(8), K_DIGIT(9), 0, 0, 0};
+ uint32_t r = rnd();
+ keep = keys[r % 20];
+ if (keep == K_BACK && (r >> 8) % 4) keep = K_OK;
+ left = (int)((r >> 12) % 40);
+ return keep;
+}
+
+static int parse_list(const char *s, int *v, int n) {
+ int k = 0;
+ while (*s && k < n) {
+ v[k++] = atoi(s);
+ while (*s && *s != ',') s++;
+ if (*s) s++;
+ }
+ return k;
+}
+
+int main(int argc, char **argv) {
+ int frames = 600, night = 0, hour = -1, ai[BOTS], custom[10], ncustom = 0, stars = -1, box = -1, ready = -1;
+ int step_who = -1, step_at = 0;
+ bool use_bot = false, use_fuzz = false, all = false, foxy_hall = false, trace = false;
+ int every = 0;
+ for (int k = 0; k < BOTS; k++) ai[k] = -100;
+ const char *out = "build/shots", *saves = "build/host-saves";
+ static int shots[4096];
+ int nshots = 0;
+ for (int i = 1; i < argc; i++) {
+ const char *a = argv[i];
+ if (!strcmp(a, "--frames")) frames = atoi(argv[++i]);
+ else if (!strcmp(a, "--keys")) parse_keys(argv[++i]);
+ else if (!strcmp(a, "--shots")) {
+ char *s = argv[++i];
+ if (!strcmp(s, "all")) all = true;
+ else if (!strncmp(s, "every:", 6)) every = atoi(s + 6);
+ else
+ for (char *t = strtok(s, ","); t && nshots < 4096; t = strtok(NULL, ",")) shots[nshots++] = atoi(t);
+ } else if (!strcmp(a, "--out")) out = argv[++i];
+ else if (!strcmp(a, "--saves")) saves = argv[++i];
+ else if (!strcmp(a, "--night")) night = atoi(argv[++i]);
+ else if (!strcmp(a, "--hour")) hour = atoi(argv[++i]);
+ else if (!strcmp(a, "--box")) box = atoi(argv[++i]);
+ else if (!strcmp(a, "--ready")) ready = atoi(argv[++i]);
+ else if (!strcmp(a, "--foxy-hall")) foxy_hall = true;
+ else if (!strcmp(a, "--ai")) {
+ int v[BOTS], n = parse_list(argv[++i], v, BOTS);
+ for (int k = 0; k < n; k++)
+ if (v[k] != -1) ai[k] = v[k];
+ } else if (!strcmp(a, "--custom")) ncustom = parse_list(argv[++i], custom, 10);
+ else if (!strcmp(a, "--step")) sscanf(argv[++i], "%d:%d", &step_who, &step_at);
+ else if (!strcmp(a, "--seed")) {
+ unsigned s = (unsigned)atoi(argv[++i]);
+ for (unsigned k = 0; k < s % 1000; k++) rnd();
+ } else if (!strcmp(a, "--bot")) use_bot = true;
+ else if (!strcmp(a, "--fuzz")) use_fuzz = true;
+ else if (!strcmp(a, "--trace")) trace = true;
+ else if (!strcmp(a, "--stars")) stars = atoi(argv[++i]);
+ else {
+ fprintf(stderr, "unknown argument %s\n", a);
+ return 2;
+ }
+ }
+ mkdir(out, 0755);
+ mkdir(saves, 0755);
+ host_save_dir(saves);
+ static uint16_t band[SCREEN_W * BAND_H];
+ gfx_set_band_memory(band);
+ fnaf2_bin = fnaf2_data;
+ host_time = 1000;
+ game_init();
+ if (stars >= 0) g.stars = (uint8_t)stars;
+ for (int k = 0; k < ncustom; k++) g.custom[k] = (int8_t)custom[k];
+ if (night) start_night(night);
+ bool set = false;
+ int f;
+ for (f = 0; f < frames && g.running; f++) {
+ if (!set && g.scene == SC_NIGHT && !g.paused) { /* the night as asked */
+ set = true;
+ for (int k = 0; k < BOTS; k++)
+ if (ai[k] != -100) g.n.ai[k] = (int8_t)ai[k];
+ if (hour >= 0) g.n.hour = (uint8_t)hour, g.n.t = hour * HOUR + 1;
+ if (box >= 0) g.n.box = (float)box;
+ if (step_who >= 0 && step_who < WALKERS) g.n.step[step_who] = (uint8_t)step_at;
+ if (ready >= 0 && ready < WALKERS) g.n.ready[ready] = 1;
+ if (foxy_hall) g.n.foxy_hall = 1;
+ }
+ uint32_t k = 0;
+ for (int i = 0; i < nholds; i++)
+ if (f >= holds[i].a && f <= holds[i].b) k |= holds[i].k;
+ if (use_bot && !k) k = bot(f);
+ if (use_fuzz && !k) k = fuzz();
+ host_keys = k;
+ int was = g.scene;
+ game_step(k);
+ if (trace && g.scene == SC_NIGHT && f % 30 == 0)
+ printf("T %.1f foxy %d d %.1f got %d off %d fl %d | mask %d mon %d flip %.2f box %d occ %d/%d threat-ready %d%d%d%d%d%d%d%d cam %d batt %d hl %d bb %d\n",
+ g.n.t, g.n.foxy_hall, g.n.foxy_d, g.n.foxy_got, g.n.foxy_off, g.n.foxy_flashes, g.n.mask, g.n.monitor,
+ g.n.flip, (int)g.n.box, g.n.occ == 0xFF ? -1 : g.n.occ, g.n.occ_state, g.n.ready[0], g.n.ready[1],
+ g.n.ready[2], g.n.ready[3], g.n.ready[4], g.n.ready[5], g.n.ready[6], g.n.ready[7], g.n.cam, (int)g.n.battery, g.n.hall_light, g.n.bb_in);
+ if (g.scene != was && (g.scene == SC_SIX || g.scene == SC_SCARE))
+ printf("EVENT %s night %d hour %d box %d t %.1f who %d\n", g.scene == SC_SIX ? "six" : "scare", g.n.night,
+ g.n.hour, (int)g.n.box, g.n.t, g.scare);
+ host_time += (f % 3 == 2) ? 17 : 16;
+ bool shot = all || (every && f % every == 0);
+ for (int i = 0; i < nshots; i++) shot |= shots[i] == f;
+ if (g.running && (shot || !(f & 1))) {
+ game_draw();
+ if (shot) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/shot_%05d.ppm", out, f);
+ host_shot(p);
+ }
+ }
+ }
+ printf("END scene %d night %d hour %d box %d t %.1f frames %d running %d paused %d reached %d stars %d "
+ "steps %d,%d,%d,%d,%d,%d,%d,%d occ %d occ_state %d mangle_in %d bb_in %d foxy_hall %d gf %d puppet %d "
+ "battery %d mask %d monitor %d cam %d keys_seen %d ai %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d scare %d\n",
+ g.scene, g.n.night, g.n.hour, (int)g.n.box, g.n.t, f, g.running, g.paused, g.reached, g.stars, g.n.step[0],
+ g.n.step[1], g.n.step[2], g.n.step[3], g.n.step[4], g.n.step[5], g.n.step[6], g.n.step[7],
+ g.n.occ == 0xFF ? -1 : g.n.occ, g.n.occ_state, g.n.mangle_in, g.n.bb_in, g.n.foxy_hall, g.n.gf, g.n.puppet,
+ (int)g.n.battery, g.n.mask, g.n.monitor, g.n.cam, g.keys_seen, g.n.ai[0], g.n.ai[1], g.n.ai[2], g.n.ai[3],
+ g.n.ai[4], g.n.ai[5], g.n.ai[6], g.n.ai[7], g.n.ai[8], g.n.ai[9], g.n.ai[10], g.scare);
+ return 0;
+}
diff --git a/games/fnaf2/tests/rules.c b/games/fnaf2/tests/rules.c
new file mode 100644
index 00000000..2d327f9e
--- /dev/null
+++ b/games/fnaf2/tests/rules.c
@@ -0,0 +1,421 @@
+/* The rules of a night against the numbers the port follows (the game's, as its players read them out of its
+ * events): the AI levels by night and hour and their caps, the music box's drain and winding, the flashlight's
+ * battery, Withered Foxy's formula, the paths, the mask, a visitor in the office, Balloon Boy, Mangle, Golden
+ * Freddy, the Puppet and the camera's light. Built with the sanitizers; prints each failure. */
+#include <stdio.h>
+#include <string.h>
+#include "../src/game.h"
+#include "../src/gfx.h"
+#include "../src/res.h"
+
+extern const uint8_t fnaf2_data[];
+const uint8_t *fnaf2_bin;
+static int failures, checks;
+#define STUN_FRAMES 400
+
+#define CHECK(c, ...) \
+ do { \
+ checks++; \
+ if (!(c)) { \
+ failures++; \
+ printf("FAIL %s:%d: ", __FILE__, __LINE__); \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ } \
+ } while (0)
+
+/* a night as it starts, everyone at 0 unless set */
+static void begin(int night) {
+ memset(&g, 0, sizeof g);
+ g.running = true;
+ night_begin(night);
+ g.scene = SC_NIGHT;
+ g.n.night = (uint8_t)night;
+}
+static void quiet(void) {
+ for (int k = 0; k < BOTS; k++) g.n.ai[k] = 0;
+ g.n.ai[FOXY] = -1;
+}
+static void step(uint32_t keys) { game_step(keys); }
+static void steps(int n, uint32_t keys) {
+ for (int i = 0; i < n && g.scene == SC_NIGHT; i++) step(keys);
+}
+static void tap(uint32_t k) {
+ step(k);
+ step(0);
+}
+static void monitor(bool up) {
+ if ((g.n.flip >= 1) != up) tap(K_OK);
+ steps(20, 0);
+}
+
+static void ai_table(void) {
+ /* night, hour: Toy Freddy, Toy Bonnie, Toy Chica, Mangle, BB, W.Freddy, W.Bonnie, W.Chica, W.Foxy, Puppet */
+ static const int8_t want[][12] = {
+ {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1}, {1, 1, 0, 2, 2, 0, 0, 0, 0, 0, -1, 1}, {1, 2, 2, 3, 2, 0, 0, 0, 0, 0, -1, 1},
+ {2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5}, {2, 1, 2, 3, 3, 3, 3, 0, 0, 0, 1, 5}, {3, 0, 0, 0, 0, 0, 1, 0, 1, 1, 2, 8},
+ {3, 1, 0, 1, 1, 0, 2, 2, 2, 2, 3, 8}, {4, 0, 0, 0, 0, 5, 3, 0, 1, 0, 7, 9}, {4, 2, 0, 1, 0, 5, 3, 3, 4, 4, 7, 9},
+ {5, 0, 5, 2, 2, 1, 5, 2, 2, 2, 5, 10}, {5, 1, 1, 2, 2, 10, 5, 5, 5, 5, 7, 10}, {6, 0, 0, 0, 0, 3, 5, 5, 5, 5, 10, 15},
+ {6, 2, 5, 5, 5, 10, 9, 10, 10, 10, 15, 15}};
+ static const uint8_t order[10] = {TF, TB, TC, MANGLE, BB, WF, WB, WC, FOXY, PUPPET};
+ for (unsigned r = 0; r < sizeof want / sizeof want[0]; r++) {
+ begin(want[r][0]);
+ for (int h = 1; h <= want[r][1]; h++) apply_hour(want[r][0], h);
+ for (int k = 0; k < 10; k++)
+ CHECK(g.n.ai[order[k]] == want[r][2 + k], "night %d %d AM: %s is %d, not %d", want[r][0], want[r][1],
+ BOT_NAMES[order[k]], g.n.ai[order[k]], want[r][2 + k]);
+ }
+ begin(6);
+ apply_hour(6, 2);
+ CHECK(g.n.ai[GF] == 3, "night 6, 2 AM: Golden Freddy at 3");
+ /* the caps: 20 plays as 15, Foxy 17, Golden Freddy 10 */
+ begin(7);
+ for (int k = 0; k < BOTS; k++) g.n.ai[k] = 20;
+ CHECK(ai_level(TB) == 15 && ai_level(FOXY) == 17 && ai_level(GF) == 10 && ai_level(PUPPET) == 15, "the caps");
+ /* the custom night: its ten from the screen, the Puppet at 15 */
+ memset(&g, 0, sizeof g);
+ for (int k = 0; k < 10; k++) g.custom[k] = (int8_t)(k + 1);
+ night_begin(7);
+ for (int k = 0; k < 10; k++) CHECK(g.n.ai[CUSTOM_ORDER[k]] == k + 1, "custom night: %s", BOT_NAMES[CUSTOM_ORDER[k]]);
+ CHECK(g.n.ai[PUPPET] == 15, "custom night: the Puppet at 15");
+ /* the hours: 68 seconds each, the levels change at the hour, 6 AM ends it */
+ begin(1);
+ quiet();
+ g.n.ai[PUPPET] = 1;
+ g.n.box = BOX_FULL;
+ steps(68 * 60 + 2, 0);
+ CHECK(g.n.hour == 1 && g.n.ai[TB] == 2 && g.n.ai[TC] == 2, "1 AM after 68 s: hour %d, Toy Bonnie %d", g.n.hour,
+ g.n.ai[TB]);
+}
+
+static void music_box(void) {
+ for (int night = 2; night <= 7; night++) {
+ begin(night);
+ quiet();
+ steps(600, 0);
+ float want = BOX_FULL - 10 * 20.0f * (night > 6 ? 6 : night);
+ CHECK(g.n.box > want - 2 && g.n.box < want + 2, "night %d: the box at %.1f after 10 s, not %.0f", night, g.n.box,
+ want);
+ }
+ begin(1);
+ quiet();
+ steps(600, 0);
+ CHECK(g.n.box == BOX_FULL, "night 1: the box holds until 2 AM");
+ CHECK(box_drain(1, 2) == 40, "night 1 from 2 AM: 40 a second");
+ /* winding on CAM 11: from empty to full in about 6 s, and it doesn't drain while wound */
+ begin(3);
+ quiet();
+ g.n.box = 0;
+ monitor(true);
+ tap(K_DIGIT(1));
+ tap(K_DIGIT(1));
+ CHECK(g.n.cam == L_PRIZE, "1 twice: CAM 11 (cam %d)", g.n.cam);
+ steps(5 * 60, K_UP);
+ CHECK(g.n.box > 1600 && g.n.box < BOX_FULL, "5 s of winding: %.0f", g.n.box);
+ steps(70, K_UP);
+ CHECK(g.n.box == BOX_FULL, "6 s of winding: full");
+ /* the warning: a fifth or less left */
+ g.n.box = 401;
+ CHECK(!box_warning(), "no warning above a fifth");
+ g.n.box = 399;
+ CHECK(box_warning(), "the warning under a fifth");
+}
+
+static void flashlight(void) {
+ int frames[8] = {0, 7000, 6000, 5000, 4000, 3000, 3000, 3000};
+ for (int night = 1; night <= 7; night++) CHECK(battery_frames(night) == frames[night], "night %d's battery", night);
+ begin(1);
+ quiet();
+ CHECK(battery_bars() == 4, "4 bars at first");
+ g.n.battery = 1400;
+ CHECK(battery_bars() == 3, "a fifth used: 3 bars (%d)", battery_bars());
+ g.n.battery = 5601;
+ CHECK(battery_bars() == 0, "past four fifths: no bar shown (%d)", battery_bars());
+ /* the hallway light uses it a frame at a time, until it's empty */
+ g.n.battery = 0;
+ steps(100, K_DIGIT(5));
+ CHECK(g.n.battery == 100 && g.n.hall_light, "100 frames of light: %.0f", g.n.battery);
+ g.n.battery = 7000;
+ steps(10, K_DIGIT(5));
+ CHECK(!g.n.hall_light && g.n.battery == 7000, "an empty battery: no light");
+ /* the vent lights are free */
+ g.n.battery = 0;
+ g.n.pan = 0;
+ steps(60, K_DIGIT(7));
+ CHECK(g.n.vent_light == 1 && g.n.battery == 0, "the left vent light, free");
+ /* pressed while looking right: turns left first */
+ steps(2, 0);
+ g.n.pan = OFFICE_PAN;
+ steps(90, K_DIGIT(7));
+ CHECK(g.n.vent_light == 1 && g.n.pan <= 30, "the vent light turns the view first (pan %.0f)", g.n.pan);
+}
+
+static void foxy(void) {
+ /* night 1: not there */
+ begin(1);
+ CHECK(g.n.ai[FOXY] < 0, "night 1: no Withered Foxy");
+ /* 21 + random(0..4) - D < AI: at AI 17 he never moves while D is 0, and always once D passes 9 */
+ begin(4);
+ quiet();
+ g.n.ai[FOXY] = 17;
+ for (int i = 0; i < 40 * 60; i++) {
+ g.n.foxy_d = 0;
+ step(0);
+ }
+ CHECK(!g.n.foxy_hall, "D 0: Foxy stays in Parts/Service");
+ g.n.foxy_d = 10;
+ steps(5 * 60 + 2, 0);
+ CHECK(g.n.foxy_hall, "D 10: Foxy in the hallway");
+ /* left alone in the hallway: he gets you */
+ steps(30 * 60, 0);
+ CHECK(g.scene == SC_SCARE && g.scare == FOXY, "Foxy unflashed: the jumpscare (scene %d)", g.scene);
+ /* the light: D back to 0; five flashes and he leaves at the next monitor */
+ begin(4);
+ quiet();
+ g.n.ai[FOXY] = 17;
+ g.n.foxy_hall = 1;
+ g.n.foxy_d = 8;
+ for (int k = 0; k < 5; k++) {
+ steps(6, K_DIGIT(5));
+ steps(6, 0);
+ }
+ CHECK(g.n.foxy_off && g.n.foxy_d < 1, "five flashes: Foxy off (flashes %d)", g.n.foxy_flashes);
+ monitor(true);
+ CHECK(!g.n.foxy_hall, "the monitor up: Foxy back in Parts/Service");
+ /* a flash once he has you: the jumpscare */
+ begin(4);
+ quiet();
+ g.n.ai[FOXY] = 17;
+ g.n.foxy_hall = 1;
+ g.n.foxy_got = 1;
+ g.n.foxy_ten = 9;
+ steps(3, K_DIGIT(5));
+ CHECK(g.scene == SC_SCARE && g.scare == FOXY, "a flash at Foxy who has you");
+ /* the mask on, no one about: D twice as fast */
+ begin(4);
+ quiet();
+ g.n.ai[FOXY] = 0;
+ tap(K_DOWN);
+ steps(30, 0);
+ float d0 = g.n.foxy_d;
+ steps(120, 0);
+ CHECK(g.n.foxy_d - d0 > 3.9f && g.n.foxy_d - d0 < 4.1f, "the mask: D +2 a second (%.2f)", g.n.foxy_d - d0);
+}
+
+/* steps until who moves (at most 30 s: at 20, capped at 15, 3 opportunities in 4 succeed); where it is then */
+static int next_place(int who) {
+ int was = bot_at(who), ready = who < WALKERS ? g.n.ready[who] : 0;
+ for (int i = 0; i < 30 * 60 && g.scene == SC_NIGHT; i++) {
+ step(0);
+ if (bot_at(who) != was || (who < WALKERS && g.n.ready[who] != ready)) break;
+ }
+ return bot_at(who);
+}
+
+static void paths(void) {
+ /* Toy Bonnie: Party Room 3, 4, 2, the right vent, its blind spot, then waiting to come in */
+ begin(1);
+ quiet();
+ g.n.ai[TB] = 20;
+ static const int8_t at[] = {L_PR3, L_PR4, L_PR2, L_RVENT, L_RSPOT};
+ for (int k = 0; k < 5; k++) {
+ int now = next_place(TB);
+ CHECK(now == at[k], "Toy Bonnie's move %d: %d, not %d", k + 1, now, at[k]);
+ }
+ next_place(TB);
+ CHECK(g.n.ready[TB], "Toy Bonnie waits in the blind spot");
+ /* the mask at his next won opportunity: back to Party Room 3 */
+ tap(K_DOWN);
+ next_place(TB);
+ CHECK(bot_at(TB) == L_PR3 && !g.n.ready[TB], "the mask sends Toy Bonnie back (%d)", bot_at(TB));
+ /* the others' first steps */
+ static const struct { uint8_t who; int8_t at[3]; } first[] = {
+ {TF, {L_GAME, L_HALL_FAR, L_HALL}}, {TC, {L_MAIN, L_HALL, L_PR1}}, {MANGLE, {L_PRIZE, L_GAME, L_MAIN}},
+ {BB, {L_UNSEEN, L_LVENT, L_LSPOT}}, {WF, {L_MAIN, L_PR3, L_HALL}}, {WB, {L_MAIN, L_HALL, L_PR1}},
+ {WC, {L_PR4, L_PR2, L_RVENT}}};
+ for (unsigned i = 0; i < sizeof first / sizeof first[0]; i++) {
+ begin(3);
+ quiet();
+ g.n.ai[first[i].who] = 20;
+ for (int k = 0; k < 3; k++) {
+ int now = next_place(first[i].who);
+ CHECK(now == first[i].at[k], "%s's move %d: %d", BOT_NAMES[first[i].who], k + 1, now);
+ }
+ }
+ /* a move a 5 s opportunity, no sooner */
+ begin(3);
+ quiet();
+ g.n.ai[WC] = 20;
+ int moves = 0, was = bot_at(WC);
+ for (int i = 0; i < 15 * 60 - 2; i++) {
+ step(0);
+ if (bot_at(WC) != was) moves++, was = bot_at(WC);
+ }
+ CHECK(moves <= 2, "two opportunities in 15 s (%d moves)", moves);
+ /* AI 0: no one moves */
+ begin(1);
+ quiet();
+ steps(60 * 60, 0);
+ for (int k = 0; k < WALKERS; k++) CHECK(g.n.step[k] == 0, "%s moved at 0", BOT_NAMES[k]);
+ /* the Withereds stay in Parts/Service while its camera is watched */
+ begin(3);
+ quiet();
+ g.n.ai[WB] = 20;
+ monitor(true);
+ tap(K_DIGIT(8));
+ steps(30 * 60, 0);
+ CHECK(bot_at(WB) == L_PARTS, "Withered Bonnie held in Parts/Service by its camera");
+}
+
+static void visitor(void) {
+ /* Withered Chica comes in with the monitor up, shows when it comes down: no mask in time, she gets you the
+ next time it comes down */
+ begin(3);
+ quiet();
+ g.n.step[WC] = 3;
+ g.n.ready[WC] = 1;
+ monitor(true);
+ CHECK(g.n.occ == WC && g.n.occ_state == OCC_IN, "in with the monitor up");
+ monitor(false);
+ CHECK(g.n.occ_state == OCC_SHOWN, "she shows (%d)", g.n.occ_state);
+ steps(60, 0);
+ CHECK(g.n.occ_state == OCC_DOOMED, "no mask within the second: doomed (%d)", g.n.occ_state);
+ CHECK(g.scene == SC_NIGHT, "not yet");
+ monitor(true);
+ steps(20, 0);
+ if (g.scene == SC_NIGHT) monitor(false);
+ CHECK(g.scene == SC_SCARE && g.scare == WC, "the monitor up and down: Withered Chica's jumpscare");
+ /* the mask within the second: she stays, the lights go out, she's back in Party Room 4 */
+ begin(3);
+ quiet();
+ g.n.step[WC] = 3;
+ g.n.ready[WC] = 1;
+ monitor(true);
+ tap(K_OK);
+ steps(16, 0);
+ tap(K_DOWN);
+ CHECK(g.n.occ_state == OCC_MASKED, "masked in time (%d)", g.n.occ_state);
+ steps(6 * 60, 0);
+ CHECK(g.n.occ_state == OCC_NONE && bot_at(WC) == L_PR4 && g.scene == SC_NIGHT, "she left (%d, at %d)",
+ g.n.occ_state, bot_at(WC));
+ /* the mask off too soon */
+ begin(3);
+ quiet();
+ g.n.step[WC] = 3;
+ g.n.ready[WC] = 1;
+ monitor(true);
+ tap(K_OK);
+ steps(16, 0);
+ tap(K_DOWN);
+ steps(60, 0);
+ tap(K_DOWN);
+ CHECK(g.scene == SC_SCARE && g.scare == WC, "the mask off too soon");
+ /* doomed, the mask on: pulled off after a while */
+ begin(3);
+ quiet();
+ g.n.step[WF] = 3;
+ g.n.ready[WF] = 1;
+ monitor(true);
+ monitor(false);
+ steps(70, 0);
+ tap(K_DOWN);
+ steps(8 * 60, 0);
+ CHECK(g.scene == SC_SCARE && g.scare == WF, "doomed with the mask on: it comes off");
+}
+
+static void others(void) {
+ /* Balloon Boy in the office: no flashlight, no vent lights, no jumpscare */
+ begin(2);
+ quiet();
+ g.n.step[BB] = 3;
+ g.n.ready[BB] = 1;
+ monitor(true);
+ monitor(false);
+ CHECK(g.n.bb_in && !lights_work(), "Balloon Boy in: the lights don't work");
+ steps(30, K_DIGIT(5));
+ CHECK(!g.n.hall_light, "no hallway light with Balloon Boy in");
+ steps(60 * 30, 0);
+ CHECK(g.scene == SC_NIGHT, "Balloon Boy doesn't attack");
+ /* Mangle in the office: the mask does nothing; sooner or later the monitor coming down ends it */
+ begin(2);
+ quiet();
+ g.n.step[MANGLE] = 8;
+ g.n.ready[MANGLE] = 1;
+ monitor(true);
+ CHECK(g.n.mangle_in, "Mangle in");
+ for (int i = 0; i < 40 && g.scene == SC_NIGHT; i++) {
+ monitor(false);
+ if (g.scene == SC_NIGHT) monitor(true);
+ }
+ CHECK(g.scene == SC_SCARE && g.scare == MANGLE, "Mangle attacks, the monitor going up and down");
+ /* Golden Freddy's head in the hallway: lit half a second, the jumpscare */
+ begin(6);
+ quiet();
+ g.n.gf = GF_HALL;
+ steps(40, K_DIGIT(5));
+ CHECK(g.scene == SC_SCARE && g.scare == GF, "Golden Freddy in the light");
+ /* ... in the office: the mask in time and he fades */
+ begin(6);
+ quiet();
+ g.n.gf = GF_COMING;
+ monitor(true);
+ tap(K_OK);
+ steps(16, 0);
+ tap(K_DOWN);
+ steps(120, 0);
+ CHECK(g.scene == SC_NIGHT && g.n.gf == GF_NONE, "Golden Freddy masked: gone (%d)", g.n.gf);
+ /* the Puppet: the box run down, he comes out and gets you, mask or not */
+ begin(7);
+ quiet();
+ g.n.ai[PUPPET] = 15;
+ g.n.box = 0;
+ tap(K_DOWN);
+ steps(60 * 60, 0);
+ CHECK(g.scene == SC_SCARE && g.scare == PUPPET, "the Puppet, through the mask (%d %d)", g.n.puppet, g.n.puppet_at);
+ /* wound before he is out: he stays */
+ begin(7);
+ quiet();
+ g.n.ai[PUPPET] = 19;
+ g.n.box = 0;
+ while (g.n.puppet < 1) step(0);
+ g.n.box = 500;
+ steps(3 * 60, 0);
+ CHECK(g.n.puppet == 1 && g.scene == SC_NIGHT, "wound in time: the Puppet stays (%d)", g.n.puppet);
+ /* the camera's light holds Toy Bonnie 6.66 s */
+ begin(1);
+ quiet();
+ g.n.ai[TB] = 20;
+ g.n.step[TB] = 1;
+ monitor(true);
+ tap(K_DIGIT(3));
+ steps(2, K_UP);
+ CHECK(g.n.stun[TB] >= 398, "the light holds Toy Bonnie (%d)", g.n.stun[TB]);
+ g.n.battery = -100000; /* (light enough for the test) */
+ steps(30 * 60, K_UP);
+ CHECK(bot_at(TB) == L_PR3 && g.n.pending[TB], "held: his move waits");
+ steps(30, 0);
+ steps(STUN_FRAMES - 30, 0);
+ CHECK(bot_at(TB) == L_PR4, "6.66 s after the light, he moves (%d)", bot_at(TB));
+ /* ... but not the Toys on the Show Stage */
+ begin(1);
+ quiet();
+ monitor(true);
+ tap(K_DIGIT(9));
+ steps(2, K_UP);
+ CHECK(g.n.stun[TB] == 0, "the Show Stage: no hold");
+}
+
+int main(void) {
+ static uint16_t band[SCREEN_W * BAND_H];
+ gfx_set_band_memory(band);
+ fnaf2_bin = fnaf2_data;
+ ai_table();
+ music_box();
+ flashlight();
+ foxy();
+ paths();
+ visitor();
+ others();
+ printf("%d of %d rules checks passed\n", checks - failures, checks);
+ return failures ? 1 : 0;
+}
diff --git a/games/fnaf2/tools/codec.py b/games/fnaf2/tools/codec.py
new file mode 100644
index 00000000..cd60b260
--- /dev/null
+++ b/games/fnaf2/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/fnaf2/tools/fetch.py b/games/fnaf2/tools/fetch.py
new file mode 100644
index 00000000..c63e7adf
--- /dev/null
+++ b/games/fnaf2/tools/fetch.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""Five Nights at Freddy's 2: gathers the public material tools/pack.py turns into src/data.bin.
+
+ python3 tools/fetch.py REF (then fill in REF/map.txt, then: make data REF=REF)
+
+The game's own pictures, as a fan web port keeps them in its repository, at the commit used:
+VocalNutria9174's fnaf-2_html5 (github.com/VocalNutria9174/fnaf-2_html5), the game's Clickteam HTML5 build,
+whose pictures are numbered files in resources/. It is cloned with git into REF/html5.
+
+Then REF/map.txt is written (if it isn't there): a line for each picture pack.py needs, "NAME ?" and what it
+shows. Put the file each comes from in place of the "?" (from REF, html5/resources/0018.png say); a jumpscare
+gets a line for each of its frames, in order."""
+import os
+import subprocess
+import sys
+
+SOURCES = [
+ ("html5", "https://github.com/VocalNutria9174/fnaf-2_html5", "9dce599551feb34bd5c2aca199b7a9dfde70f866"),
+]
+EXTRA = [("TITLE_TEXT", "the title's words, white on transparent"), ("STAR", "the title's star"),
+ ("ICON", "a face for the app's icon (it is cut square)")]
+
+
+def main():
+ if len(sys.argv) != 2:
+ raise SystemExit(__doc__)
+ ref = sys.argv[1]
+ os.makedirs(ref, exist_ok=True)
+ for name, url, commit in SOURCES:
+ d = os.path.join(ref, name)
+ if not os.path.isdir(os.path.join(d, ".git")):
+ subprocess.run(["git", "clone", "--quiet", url, d], check=True)
+ subprocess.run(["git", "-C", d, "checkout", "--quiet", commit], check=True)
+ print(f"{name}: {commit[:10]}")
+ path = os.path.join(ref, "map.txt")
+ if os.path.exists(path):
+ return
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from pack import PICTURES # noqa: E402 (the list of pictures, nothing else of it runs)
+ with open(path, "w") as f:
+ f.write("# NAME file (from this folder). A jumpscare: a line a frame, in order.\n")
+ for name, kind, what in PICTURES:
+ if kind == "face" or not kind.startswith("patch"):
+ f.write(f"{name} ? # {what}\n")
+ else:
+ f.write(f"{name} ? # {what} (the whole office: pack.py cuts the part)\n")
+ for name, what in EXTRA:
+ f.write(f"{name} ? # {what}\n")
+ print(f"wrote {path}: fill it in, then make data REF={ref}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/fnaf2/tools/pack.py b/games/fnaf2/tools/pack.py
new file mode 100644
index 00000000..bfbfaeb0
--- /dev/null
+++ b/games/fnaf2/tools/pack.py
@@ -0,0 +1,733 @@
+#!/usr/bin/env python3
+"""Five Nights at Freddy's 2: its pictures and fonts -> src/data.bin + src/data.h.
+
+ python3 -I tools/pack.py REF the game's pictures (REF: the folder tools/fetch.py filled, with its
+ map.txt filled in; Python + Pillow + NumPy)
+ python3 -I tools/pack.py stand-in pictures: the rooms as plain shapes, everyone as a name plate,
+ to build and test the game before the pictures are gathered
+
+REF/map.txt names the picture each of the game's states comes from, a line each: "NAME path" (the path from
+REF). PICTURES below lists the names and what each shows. The office's states (the hallway and the vents lit,
+who is in the room) are whole office pictures (1600 x 768): pack.py cuts the part that changes. A jumpscare's
+frames are lines of the same name, in order. TITLE_TEXT and STAR are white on transparent; ICON is the face for
+the app's icon.
+
+data.bin: "FNF2", 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)
+- MAP: the camera map: its width and height (u16), its walls (1 bit a pixel), where the 12 buttons are
+
+The office is the game's 1600 x 768 at 240 high (500 x 240): the calculator shows 320 of it and turns. The
+cameras are its 1024 x 768 at 320 x 240."""
+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 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, "..", "..", "..")
+SECTIONS = ["HUFF", "QUANT", "PICS", "TABLE", "BANK", "FONTS", "IMGS", "MAP"]
+QUALITY = {"scene": 80, "scare": 70, "paper": 84, "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 = 500, 240 # the office on the calculator
+CW, CH = 320, 240 # a camera
+# the parts of the office that change, drawn over it (x, y, w, h in the 500 x 240 office)
+PATCHES = {
+ "HALL": (176, 32, 144, 128), # the hallway, in the flashlight
+ "LVENT": (0, 112, 96, 80), # the left vent's blind spot, in its light
+ "RVENT": (404, 112, 96, 80), # the right one
+ "OCC": (160, 48, 176, 192), # whoever stands in front of the desk
+ "MANGLE": (192, 0, 128, 64), # Mangle on the ceiling
+ "BBO": (16, 96, 144, 144), # Balloon Boy in the office
+}
+WHO = {"TF": "Toy Freddy", "TB": "Toy Bonnie", "TC": "Toy Chica", "MANGLE": "Mangle", "BB": "Balloon Boy",
+ "WF": "Withered Freddy", "WB": "Withered Bonnie", "WC": "Withered Chica", "FOXY": "Withered Foxy",
+ "GF": "Golden Freddy", "PUPPET": "The Puppet", "TFFAR": "Toy Freddy"}
+# the stand-ins' colours (a stripe on each name plate)
+COLOUR = {"TF": (150, 95, 50), "TB": (70, 120, 220), "TC": (235, 205, 60), "MANGLE": (235, 230, 235),
+ "BB": (220, 60, 50), "WF": (110, 70, 40), "WB": (100, 80, 170), "WC": (220, 150, 40),
+ "FOXY": (170, 60, 40), "GF": (225, 185, 60), "PUPPET": (240, 240, 240), "TFFAR": (150, 95, 50)}
+
+# Every picture, in order (the code knows them by name): what it is, how big, and what it shows.
+# office: the whole office; patch P: the part P of an office picture; cam: a camera; scare: a jumpscare's
+# frames; screen: a menu picture; face: a custom night tile
+PICTURES = [("OFFICE", "office", "the office, the lights out down the hall and in the vents")]
+PICTURES += [(f"HALL_{s}", "patch HALL", f"the hallway in the flashlight: {d}") for s, d in (
+ ("LIT", "no one"), ("TFFAR", "Toy Freddy far down"), ("TF", "Toy Freddy close"), ("TC", "Toy Chica"),
+ ("MANGLE", "Mangle"), ("WF", "Withered Freddy"), ("WB", "Withered Bonnie"), ("FOXY", "Withered Foxy"),
+ ("GF", "Golden Freddy's head"))]
+PICTURES += [(f"LVENT_{s}", "patch LVENT", f"the left vent lit: {d}") for s, d in (
+ ("LIT", "no one"), ("TC", "Toy Chica"), ("BB", "Balloon Boy"))]
+PICTURES += [(f"RVENT_{s}", "patch RVENT", f"the right vent lit: {d}") for s, d in (
+ ("LIT", "no one"), ("TB", "Toy Bonnie"), ("MANGLE", "Mangle"))]
+PICTURES += [(f"OCC_{s}", "patch OCC", f"{WHO[s]} in the office, in front of the desk")
+ for s in ("TF", "TB", "TC", "WF", "WB", "WC", "GF")]
+PICTURES += [("OFFICE_MANGLE", "patch MANGLE", "Mangle on the office's ceiling"),
+ ("OFFICE_BB", "patch BBO", "Balloon Boy standing in the office")]
+CAMS = [
+ ("01", "Party Room 1", ["DARK", "LIT", "TC", "WB", "MANGLE", "PUPPET"]),
+ ("02", "Party Room 2", ["DARK", "LIT", "TB", "WC", "MANGLE", "PUPPET"]),
+ ("03", "Party Room 3", ["DARK", "LIT", "TB", "WF", "PUPPET"]),
+ ("04", "Party Room 4", ["DARK", "LIT", "TB", "WC", "PUPPET"]),
+ ("05", "Left Air Vent", ["DARK", "LIT", "TC", "BB", "WB"]),
+ ("06", "Right Air Vent", ["DARK", "LIT", "TB", "WC", "MANGLE"]),
+ ("07", "Main Hall", ["EMPTY", "TC", "MANGLE", "WF", "WB", "PUPPET"]),
+ ("08", "Parts/Service", [f"S{m}" for m in range(8)] + ["FOXY"]),
+ ("09", "Show Stage", [f"S{m}" for m in range(8)]),
+ ("10", "Game Area", ["EMPTY", "TF", "BB", "MANGLE"]),
+ ("11", "Prize Corner", ["P0", "P1", "P2", "P3", "EMPTY", "MANGLE"]),
+ ("12", "Kid's Cove", ["MANGLE", "EMPTY"]),
+]
+for num, room, states in CAMS:
+ for s in states:
+ PICTURES.append((f"CAM{num}_{s}", "cam", f"CAM {num}, {room}: {s}"))
+SCARES = ["TF", "TB", "TC", "MANGLE", "WF", "WB", "WC", "FOXY", "GF", "PUPPET"]
+PICTURES += [(f"SCARE_{s}", "scare", f"{WHO[s]}'s jumpscare, its frames in order") for s in SCARES]
+PICTURES += [("TITLE", "screen", "the title's background"), ("NEWSPAPER", "screen", "the newspaper before night 1"),
+ ("PAYCHECK", "screen", "the paycheck after night 5"), ("OVERTIME", "screen", "the check after night 6"),
+ ("PINKSLIP", "screen", "the pink slip after the custom night"),
+ ("GAMEOVER", "screen", "the game over")]
+FACES = ["WF", "WB", "WC", "FOXY", "BB", "TF", "TB", "TC", "MANGLE", "GF"]
+PICTURES += [(f"FACE{i}", "face", f"{WHO[s]}'s face on the custom night") for i, s in enumerate(FACES)]
+# Parts/Service's S<m> and the Show Stage's: who is there, a bit each (1 the Freddy, 2 the Bonnie, 4 the Chica)
+
+REF = None
+MAP = {}
+
+
+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, serif=False):
+ name = "DejaVu" + ("SansMono" if mono else "Serif" if serif 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)
+
+
+# ------------------------------------------------------------------ the camera map
+# where the cameras' buttons are, on a plan of the building (the office at the bottom): its rooms as boxes
+MAP_W, MAP_H = 148, 104
+MAP_ROOMS = [(2, 2, 32, 22), (36, 2, 104, 22), (108, 2, 146, 22), (2, 24, 32, 46), (36, 24, 104, 46),
+ (108, 24, 146, 46), (2, 48, 30, 68), (30, 48, 56, 68), (2, 70, 30, 102), (30, 70, 56, 102),
+ (58, 70, 84, 102), (110, 70, 146, 102)]
+MAP_BUTTONS = {"01": (16, 86), "02": (43, 86), "03": (16, 58), "04": (43, 58), "05": (71, 86), "06": (128, 86),
+ "07": (70, 35), "08": (17, 35), "09": (70, 12), "10": (127, 35), "11": (127, 12), "12": (17, 12)}
+
+
+def camera_map():
+ im = Image.new("L", (MAP_W, MAP_H))
+ d = ImageDraw.Draw(im)
+ for box in MAP_ROOMS:
+ d.rectangle(box, outline=255)
+ d.rectangle((86, 84, 108, 102), fill=0, outline=255) # the office
+ d.text((97, 93), "YOU", font=font(7, bold=True), fill=255, anchor="mm")
+ bits = np.asarray(im) > 128
+ stride = (MAP_W + 7) // 8
+ out = struct.pack("<HH", MAP_W, MAP_H)
+ for r in range(MAP_H):
+ row = bytearray(stride)
+ for c in range(MAP_W):
+ if bits[r, c]:
+ row[c >> 3] |= 1 << (c & 7)
+ out += row
+ for k in sorted(MAP_BUTTONS):
+ out += struct.pack("<HH", *MAP_BUTTONS[k])
+ return out
+
+
+# ------------------------------------------------------------------ the stand-in pictures
+RNG = np.random.default_rng(2)
+
+
+def grain(a, s=4.0):
+ return a # (the stand-ins stay flat: they take little room)
+
+
+def plate(d, cx, cy, who, scale=1.0, text=None):
+ """a name plate where someone stands: a dark card, the colour stripe, the name"""
+ name = (text or WHO[who]).upper()
+ f = font(max(8, int(11 * scale)), bold=True)
+ w = int(f.getlength(name)) + int(16 * scale)
+ h = int(30 * scale)
+ x0, y0 = int(cx - w / 2), int(cy - h / 2)
+ d.rounded_rectangle((x0, y0, x0 + w, y0 + h), radius=int(5 * scale), fill=(24, 24, 28), outline=(200, 200, 200))
+ d.rectangle((x0 + 3, y0 + 3, x0 + w - 3, y0 + int(8 * scale)), fill=COLOUR[who])
+ d.text((cx, y0 + int(19 * scale)), name, font=f, fill=(240, 240, 240), anchor="mm")
+
+
+def stand_in_office():
+ im = Image.new("RGB", (OW, OH), (30, 26, 24))
+ d = ImageDraw.Draw(im)
+ d.rectangle((0, 170, OW, OH), fill=(42, 36, 32)) # the floor
+ d.polygon([(176, 32), (320, 32), (300, 150), (196, 150)], fill=(8, 8, 10)) # the hallway
+ d.rectangle((168, 26, 328, 34), fill=(50, 44, 40))
+ for x0 in (8, 412): # the vents
+ d.rectangle((x0, 120, x0 + 80, 184), fill=(10, 10, 12), outline=(70, 70, 74))
+ for k in range(1, 4):
+ d.line((x0, 120 + 16 * k, x0 + 80, 120 + 16 * k), fill=(40, 40, 44))
+ d.rectangle((150, 176, 350, 240), fill=(58, 50, 44)) # the desk
+ d.rectangle((222, 150, 278, 180), fill=(20, 22, 24), outline=(80, 80, 80))
+ return grain(arr(im))
+
+
+def stand_in_patch(office, part, who=None, lit=True, pos=None, scale=1.0, text=None):
+ x, y, w, h = PATCHES[part]
+ im = Image.fromarray(np.clip(office, 0, 255).astype(np.uint8))
+ d = ImageDraw.Draw(im)
+ if lit and part == "HALL":
+ d.polygon([(176, 32), (320, 32), (300, 150), (196, 150)], fill=(84, 78, 68))
+ d.polygon([(220, 60), (276, 60), (270, 120), (226, 120)], fill=(40, 38, 34))
+ if lit and part in ("LVENT", "RVENT"):
+ x0 = 8 if part == "LVENT" else 412
+ d.rectangle((x0, 120, x0 + 80, 184), fill=(70, 66, 58), outline=(120, 120, 120))
+ if who:
+ cx, cy = pos or (x + w / 2, y + h / 2)
+ plate(d, cx, cy, who, scale, text)
+ return arr(im)[y:y + h, x:x + w]
+
+
+def stand_in_room(num, room, lit, who=(), extra=None):
+ im = Image.new("RGB", (CW, CH), (36, 34, 40) if lit else (6, 6, 8))
+ d = ImageDraw.Draw(im)
+ wall, floor = ((70, 64, 72), (52, 46, 44)) if lit else ((12, 12, 14), (9, 9, 10))
+ d.rectangle((0, 0, CW, 150), fill=wall)
+ d.polygon([(0, 240), (320, 240), (260, 150), (60, 150)], fill=floor)
+ if "Vent" in room:
+ d.rectangle((0, 0, CW, CH), fill=(14, 14, 16) if not lit else (60, 58, 56))
+ d.polygon([(40, 30), (280, 30), (230, 200), (90, 200)], fill=(4, 4, 6) if not lit else (34, 32, 30))
+ d.text((CW - 14, 30), room.upper(), font=font(9), fill=(90, 90, 90) if lit else (30, 30, 30), anchor="rm")
+ n = len(who)
+ for i, w in enumerate(who):
+ plate(d, CW / 2 + (i - (n - 1) / 2) * 96, 84, w, 0.9 if n > 1 else 1.1)
+ if extra:
+ d.text((CW / 2, 112), extra, font=font(11), fill=(220, 220, 220), anchor="mm")
+ return grain(arr(im), 5)
+
+
+def stand_in_cams():
+ for num, room, states in CAMS:
+ base = None
+ for s in states:
+ name = f"CAM{num}_{s}"
+ if s == "DARK":
+ pic(name, stand_in_room(num, room, False))
+ continue
+ if num in ("08", "09") and s.startswith("S"):
+ m = int(s[1:])
+ trio = ["WF", "WB", "WC"] if num == "08" else ["TF", "TB", "TC"]
+ who = [trio[k] for k in range(3) if m >> k & 1]
+ elif s in ("LIT", "EMPTY"):
+ who = []
+ elif s.startswith("P") and num == "11":
+ who = ["PUPPET"]
+ else:
+ who = [s]
+ extra = None
+ if num == "11" and s.startswith("P"):
+ extra = ["in the box", "partly out", "mostly out", "out of the box"][int(s[1:])]
+ if num == "11" and s == "MANGLE":
+ extra = "the music box shut"
+ a = stand_in_room(num, room, True, who, extra)
+ p = pic(name, a, base=base)
+ base = base or p
+
+
+def stand_in_scares():
+ for who in SCARES:
+ first = prev = None
+ for k in range(3):
+ im = Image.new("RGB", (CW, CH), (60 + 40 * k, 8, 8))
+ d = ImageDraw.Draw(im)
+ plate(d, CW / 2, CH / 2, who, 2.2 + 0.5 * k)
+ p = pic(f"SCARE_{who}{k}", grain(arr(im), 10), "scare", base=first, refs=[prev] if prev else [])
+ first, prev = first or p, p
+ define(f"SCARE_{who}_N", 3)
+
+
+def paper(color):
+ im = Image.new("RGB", (CW, CH), (12, 12, 12))
+ d = ImageDraw.Draw(im)
+ d.rectangle((22, 30, 297, 210), fill=color)
+ return im
+
+
+def text(d, xy, s, size, bold=False, serif=False, fill=(30, 30, 30), anchor="la"):
+ d.text(xy, s, font=font(size, bold, serif=serif), fill=fill, anchor=anchor)
+
+
+def cheque(amount, words, memo):
+ im = paper((222, 228, 214))
+ d = ImageDraw.Draw(im)
+ d.rectangle((26, 34, 293, 206), outline=(120, 140, 120))
+ text(d, (34, 42), "Fazbear Entertainment, Inc.", 11, bold=True, serif=True)
+ text(d, (34, 56), "Freddy Fazbear's Pizza", 9, serif=True, fill=(70, 70, 70))
+ text(d, (286, 42), "No. 1987", 9, fill=(90, 90, 90), anchor="ra")
+ text(d, (34, 88), "PAY TO THE", 8, fill=(80, 80, 80))
+ text(d, (34, 98), "ORDER OF", 8, fill=(80, 80, 80))
+ text(d, (92, 92), "Jeremy Fitzgerald", 13, serif=True, fill=(20, 30, 90))
+ d.line((90, 110, 220, 110), fill=(80, 80, 80))
+ d.rectangle((228, 86, 290, 106), outline=(80, 80, 80))
+ text(d, (286, 96), amount, 13, bold=True, fill=(20, 30, 90), anchor="rm")
+ text(d, (34, 124), words, 10, serif=True, fill=(20, 30, 90))
+ d.line((34, 138, 286, 138), fill=(80, 80, 80))
+ text(d, (34, 172), "MEMO", 8, fill=(80, 80, 80))
+ text(d, (64, 168), memo, 11, serif=True, fill=(20, 30, 90))
+ d.line((62, 184, 150, 184), fill=(80, 80, 80))
+ d.line((180, 184, 286, 184), fill=(80, 80, 80))
+ text(d, (233, 188), "Fazbear Entertainment", 7, fill=(80, 80, 80), anchor="ma")
+ return im
+
+
+def pink_slip():
+ im = paper((236, 178, 190))
+ d = ImageDraw.Draw(im)
+ text(d, (160, 40), "NOTICE OF TERMINATION", 13, bold=True, serif=True, anchor="ma")
+ text(d, (160, 58), "Freddy Fazbear's Pizza", 9, serif=True, fill=(80, 40, 50), anchor="ma")
+ d.line((34, 74, 286, 74), fill=(120, 60, 70))
+ rows = [("Employee:", "Fritz Smith"), ("Position:", "Night security"), ("Reason:", "Tampering with the"),
+ ("", "animatronics, odor.")]
+ y = 88
+ for k, v in rows:
+ text(d, (36, y), k, 10, bold=True, fill=(60, 20, 30))
+ text(d, (110, y), v, 11, serif=True, fill=(30, 20, 20))
+ y += 18
+ text(d, (160, 186), "Please return your uniform.", 9, serif=True, fill=(80, 40, 50), anchor="ma")
+ return im
+
+
+def newspaper():
+ im = paper((214, 210, 196))
+ d = ImageDraw.Draw(im)
+ text(d, (160, 38), "HELP WANTED", 20, bold=True, serif=True, anchor="ma")
+ d.line((34, 64, 286, 64), fill=(60, 60, 60), width=2)
+ lines = ["Freddy Fazbear's Pizza, open again", "with all new characters, needs a", "night security guard.",
+ "", "Watch the cameras from 12 to 6 AM.", "Keep an eye on the place.", "", "$100.50 a week."]
+ for i, s in enumerate(lines):
+ text(d, (160, 74 + 15 * i), s, 11, serif=True, fill=(30, 30, 30), anchor="ma")
+ return im
+
+
+def stand_in_screens():
+ title = Image.new("RGB", (CW, CH), (10, 8, 8))
+ d = ImageDraw.Draw(title)
+ for k in range(40):
+ d.line((0, 6 * k, CW, 6 * k), fill=(16, 12, 12))
+ pic("TITLE", grain(arr(title), 6), "face")
+ pic("NEWSPAPER", arr(newspaper()), "paper")
+ pic("PAYCHECK", arr(cheque("$100.50", "One hundred and 50/100 dollars", "One week's work")), "paper")
+ pic("OVERTIME", arr(cheque("$20.10", "Twenty and 10/100 dollars", "Overtime")), "paper")
+ pic("PINKSLIP", arr(pink_slip()), "paper")
+ over = stand_in_room("08", "Parts/Service", True, ["WF", "WB", "WC"]) * 0.6
+ pic("GAMEOVER", over, "scene")
+
+
+def stand_in_faces():
+ for i, who in enumerate(FACES):
+ im = Image.new("RGB", (48, 48), (20, 20, 24))
+ d = ImageDraw.Draw(im)
+ d.rectangle((2, 2, 45, 12), fill=COLOUR[who])
+ initials = "".join(w[0] for w in WHO[who].replace("The ", "").split())
+ d.text((24, 30), initials, font=font(16, bold=True), fill=(235, 235, 235), anchor="mm")
+ pic(f"FACE{i}", arr(im), "face")
+
+
+def stand_in_title_text():
+ im = Image.new("L", (190, 112))
+ d = ImageDraw.Draw(im)
+ f = font(22, bold=True, serif=True)
+ for i, s in enumerate(["Five", "Nights", "at Freddy's"]):
+ d.text((0, 26 * i), s, font=f, fill=255)
+ d.text((150, 52), "2", font=font(46, bold=True, serif=True), fill=255)
+ img("TITLE", np.asarray(im).astype(np.float64))
+
+
+def star_img(alpha=None):
+ if alpha is None:
+ im = Image.new("L", (22 * 4, 21 * 4))
+ pts = []
+ for k in range(10):
+ r = 42 if k % 2 == 0 else 17
+ a = np.pi / 2 + k * np.pi / 5
+ pts.append((44 + r * np.cos(a), 46 - r * np.sin(a)))
+ ImageDraw.Draw(im).polygon(pts, fill=255)
+ alpha = np.asarray(im.resize((22, 21), Image.LANCZOS)).astype(np.float64)
+ img("STAR", alpha)
+
+
+def stand_in_icon():
+ sys.path.insert(0, os.path.join(ROOT, "tools"))
+ from make_icon import corner_mask
+ im = Image.new("RGB", (55, 56), (18, 10, 10))
+ d = ImageDraw.Draw(im)
+ d.text((27, 22), "FNaF", font=font(15, bold=True, serif=True), fill=(230, 230, 230), anchor="mm")
+ d.text((27, 42), "2", font=font(18, bold=True, serif=True), fill=(220, 40, 40), anchor="mm")
+ im.putalpha(corner_mask(55, 56))
+ im.save(os.path.join(HERE, "..", "src", "icon.png"), optimize=True)
+
+
+def stand_ins():
+ office = stand_in_office()
+ o = pic("OFFICE", office)
+ who_pos = {"TFFAR": ((248, 100), 0.6, None)}
+ for name, kind, _ in PICTURES:
+ if not kind.startswith("patch"):
+ continue
+ part = kind.split()[1]
+ state = name.split("_", 1)[1] if part != "MANGLE" and part != "BBO" else None
+ who = None if state in (None, "LIT") else state
+ if part == "MANGLE":
+ who = "MANGLE"
+ if part == "BBO":
+ who = "BB"
+ pos, scale, txt = who_pos.get(who, (None, 1.0, None))
+ a = stand_in_patch(office, part, who, True, pos, scale, txt)
+ if part in ("MANGLE", "BBO", "OCC"):
+ a = stand_in_patch(office, part, who, False, pos, 0.85 if part == "BBO" else scale, txt)
+ pic(name, a)
+ del o
+ stand_in_cams()
+ stand_in_scares()
+ stand_in_screens()
+ stand_in_faces()
+ stand_in_title_text()
+ star_img()
+ stand_in_icon()
+
+
+# ------------------------------------------------------------------ the game's own pictures (REF/map.txt)
+def ref_files(name):
+ return [os.path.join(REF, p) for p in MAP.get(name, [])]
+
+
+def ref_image(name, i=0):
+ files = ref_files(name)
+ if not files:
+ raise SystemExit(f"pack: map.txt has no picture for {name}")
+ return Image.open(files[i])
+
+
+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]
+
+
+def from_ref():
+ office = cover(ref_image("OFFICE"), OW, OH)
+ pic("OFFICE", office)
+ bases = {}
+ for name, kind, _ in PICTURES:
+ if kind.startswith("patch"):
+ x, y, w, h = PATCHES[kind.split()[1]]
+ a = cover(ref_image(name), OW, OH)[y:y + h, x:x + w]
+ part = kind.split()[1]
+ p = pic(name, a, base=bases.get(part))
+ if part in ("HALL", "LVENT", "RVENT") and part not in bases:
+ bases[part] = p
+ elif kind == "cam":
+ num, state = name[3:5], name[6:]
+ a = cover(ref_image(name), CW, CH)
+ first = bases.get(num)
+ p = pic(name, a, base=first if state not in ("DARK",) else None)
+ if state != "DARK" and not first:
+ bases[num] = p
+ for who in SCARES:
+ files = ref_files(f"SCARE_{who}")
+ first = prev = None
+ for k in range(len(files)):
+ p = pic(f"SCARE_{who}{k}", cover(Image.open(files[k]), CW, CH), "scare", base=first,
+ refs=[prev] if prev else [])
+ first, prev = first or p, p
+ define(f"SCARE_{who}_N", len(files))
+ for name, kind, _ in PICTURES:
+ if kind == "screen":
+ pic(name, cover(ref_image(name), CW, CH), "paper" if name in ("NEWSPAPER", "PAYCHECK", "OVERTIME",
+ "PINKSLIP") else "face")
+ elif kind == "face":
+ pic(name, cover(ref_image(name), 48, 48), "face")
+ t = ref_image("TITLE_TEXT").convert("RGBA")
+ t = t.resize((190, int(t.height * 190 / t.width)), Image.LANCZOS)
+ a = np.asarray(t).astype(np.float64)
+ img("TITLE", a[..., 3] * a[..., :3].mean(axis=2) / 255)
+ s = np.asarray(ref_image("STAR").convert("RGBA").resize((22, 21), Image.LANCZOS)).astype(np.float64)
+ star_img(s[..., 3] * s[..., :3].mean(axis=2) / 255)
+ sys.path.insert(0, os.path.join(ROOT, "tools"))
+ from make_icon import corner_mask
+ icon = Image.fromarray(cover(ref_image("ICON"), 55, 56).astype(np.uint8))
+ icon.putalpha(corner_mask(55, 56))
+ icon.save(os.path.join(HERE, "..", "src", "icon.png"), optimize=True)
+
+
+def read_map():
+ path = os.path.join(REF, "map.txt")
+ for line in open(path):
+ line = line.split("#", 1)[0].strip()
+ if not line:
+ continue
+ name, file = line.split(None, 1)
+ if file != "?":
+ MAP.setdefault(name, []).append(file)
+
+
+def main():
+ global REF
+ if len(sys.argv) > 2:
+ raise SystemExit(__doc__)
+ if len(sys.argv) == 2:
+ REF = sys.argv[1]
+ read_map()
+ from_ref()
+ else:
+ stand_ins()
+ names = [p.name for p in PICS]
+ for n, k, _ in PICTURES: # (the same pictures either way, for the code)
+ assert k == "scare" or n in names, n
+ for part, (x, y, w, h) in PATCHES.items():
+ define(f"{part}_X", x)
+ define(f"{part}_Y", y)
+ 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(), camera_map()]
+ head = b"FNF2" + 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 FNAF2_DATA_H", "#define FNAF2_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 += [f"#define STAND_INS {0 if REF else 1}"]
+ h += ["", "#endif", ""]
+ open(OUT_H, "w").write("\n".join(h))
+ print(f"data.bin: {len(out)} bytes" + ("" if REF else " (stand-in pictures)"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/games.json b/games/games.json
index 06b8c556..9da39b55 100644
--- a/games/games.json
+++ b/games/games.json
@@ -1360,5 +1360,27 @@
"repo": "https://github.com/Mason363/NumPlay/tree/main/games/templerun",
"default": false,
"xl": true
+ },
+ {
+ "id": "fnaf2",
+ "rank": 33,
+ "title": "Five Nights at Freddy's 2",
+ "tagline": "Survive the new pizzeria",
+ "credit": "Based on the game by Scott Cawthon",
+ "top": "0x3A2C46",
+ "bottom": "0x0A0610",
+ "accent": "0xE04A3A",
+ "colors": 16,
+ "records": [
+ "fnaf2.sav",
+ "fnaf2res.sav",
+ "fnaf2_saves.py"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/fnaf2",
+ "default": false,
+ "xl": true
}
]
diff --git a/launcher/src/np.h b/launcher/src/np.h
index e1cce70c..886601a7 100644
--- a/launcher/src/np.h
+++ b/launcher/src/np.h
@@ -68,7 +68,7 @@ typedef struct {
} np_game_t;
/* every game of games.json, the kit's too, can be in one NumPlay (tools/gen_games.py checks it) */
-#define NP_MAX_GAMES 64
+#define NP_MAX_GAMES 96
#if NP_SIMULATOR
extern const np_game_t np_games[];
extern const int np_game_count;
diff --git a/tests/test_games.py b/tests/test_games.py
index 86afe1fc..f805e647 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -300,6 +300,10 @@ GAMES = {
# time, from the copy, straight from the title into another run, quit with On/Off
"templerun": ("TempleRun.nwa", "templerun.sav", presses((1500, "ok"), (2200, "ok")), 9000,
presses((1500, "ok")), 4000),
+ # Continue: the first night's card, then the office; Home keeps the night, and the next start is back in it,
+ # paused: Back, and the night goes on
+ "fnaf2": ("FiveNightsAtFreddys2.nwa", "fnaf2res.sav", presses((1500, "down"), (1800, "ok")), 9000,
+ presses((1500, "back")), 5000),
# a level, its message, then play; then back to the level select
"portal": ("PortalReturns.nwa", "portal.sav",
presses((1500, "ok"), (2500, "ok"), (3500, "ok")) + every(4000, 7000, 400, "right", 300), 8000,
@@ -369,7 +373,8 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p
"fnf": "fnf_saves.py", "turborush": "turborush_saves.py",
"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"}
+ "rider": "rider_saves.py", "snowrider": "snowrider_saves.py", "templerun": "templerun_saves.py",
+ "fnaf2": "fnaf2_saves.py"}
def paperclips_ok(v):
@@ -614,6 +619,9 @@ CHECKS = {
"templerun": (lambda v: v[:4] == b"TNR1" and struct.unpack_from("<2I", v, 4) == (1, 48)
and struct.unpack_from("<I", v, 24)[0] == 1 and struct.unpack_from("<I", v, 16)[0] > 0,
lambda v: v[:4] == b"TNR1" and struct.unpack_from("<I", v, 24)[0] == 2),
+ # 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),
"breakout": (lambda v: len(v) == 12 and v[:2] == b"B\2" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 10,
lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off
# Air Hockey and the easy computer chosen; then the normal computer and Tanks, the tallies of the six games kept
diff --git a/tools/release.py b/tools/release.py
index b516b9ba..13f6501f 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -60,6 +60,7 @@ ALONE = {
"rider": ("Rider", "Ketchapp's neon motorbike game: the endless run, 48 levels and 55 bikes, one button to ride and flip"),
"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"),
}
VARIANTS = [
("NumPlay-Invisible.nwa", "The same app, hidden: a blank icon with no name"),