Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
PolyGT 3D: three circuits, rivals that race, the endless road and saves that keep
Mason3639266ec4c9a5f
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 5fea0f85..89f11a09 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -90,6 +90,7 @@ jobs:make -C games/uno host testmake -C games/fnf host test BUILD_DIR=../../build/data/games/fnfmake -C games/turborush host test BUILD_DIR=../../build/data/games/turborush+ make -C games/polygt3d host test BUILD_DIR=../../build/data/games/polygt3ddiff --git a/Makefile b/Makefileindex fe75eb4e..3706d816 100644--- a/Makefile+++ b/Makefile@@ -18,7 +18,7 @@ PY ?= python3CARGO ?= cargoB = build/data# Conventional games honor a configurable output directory; special layouts are kept local.-GAMES_REDIRECT = 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 minesweeper monkeymart numblocks numpowder numvisuals pacman portal pvz snake sokoban solitaire sonic stickmanhook subway sudoku suika tombofthemask towerblock turborush twoplayer undertale uno uttt+GAMES_REDIRECT = 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 minesweeper monkeymart numblocks numpowder numvisuals pacman polygt3d portal pvz snake sokoban solitaire sonic stickmanhook subway sudoku suika tombofthemask towerblock turborush twoplayer undertale uno utttGAMES_OUT = dinorunGAME_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+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 PolyGT3D# 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@@ -47,7 +47,7 @@ XL_APP_SPACE = 6291456# the spaces the customizer website offers (kit.json "spaces"; tools/kit.py links a NumPlay at each)SPACES = std:$(APP_START):$(APP_END) e26:$(APP_START_26):$(APP_END) xl:$(APP_START):$(XL_END) xl26:$(APP_START_26):$(XL_END)# big games that must install on their own without Enlarged Extra Apps: make check holds them to APP_SPACE-APP_SPACE_APPS = HillClimbRacing FridayNightFunkin TurboRush+APP_SPACE_APPS = HillClimbRacing FridayNightFunkin TurboRush PolyGT3D# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has# the games that fit it (NumPlay draws their text there: see launcher/src/compat.c)UPSILON_RAM = 107674@@ -324,6 +324,7 @@ APP_tombofthemask = $(B)/games/tombofthemask/tombofthemask.nwa:TombOfTheMask.nwaAPP_uno = $(B)/games/uno/uno.nwa:UNO.nwaAPP_fnf = $(B)/games/fnf/fnf.nwa:FridayNightFunkin.nwaAPP_turborush = $(B)/games/turborush/turborush.nwa:TurboRush.nwa+APP_polygt3d = $(B)/games/polygt3d/polygt3d.nwa:PolyGT3D.nwa# the big games' modules are made from these (the kit)$(foreach g,$(XL_GAMES),$(eval MOD_$(g) = $$(word 1,$$(subst :, ,$$(APP_$(g))))))@@ -360,6 +361,7 @@ apps: | $(B)$(MAKE) -C games/uno build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/uno$(MAKE) -C games/fnf build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnf$(MAKE) -C games/turborush build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/turborush+ $(MAKE) -C games/polygt3d build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/polygt3dcd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quietcp $(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)))@@ -394,6 +396,7 @@ apps: | $(B)cp $(word 1,$(subst :, ,$(APP_uno))) $(B)/apps/$(word 2,$(subst :, ,$(APP_uno)))cp $(word 1,$(subst :, ,$(APP_fnf))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnf)))cp $(word 1,$(subst :, ,$(APP_turborush))) $(B)/apps/$(word 2,$(subst :, ,$(APP_turborush)))+ cp $(word 1,$(subst :, ,$(APP_polygt3d))) $(B)/apps/$(word 2,$(subst :, ,$(APP_polygt3d)))arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwaSTD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))@@ -468,5 +471,6 @@ clean:-$(MAKE) -C games/uno clean-$(MAKE) -C games/fnf clean-$(MAKE) -C games/turborush clean+ -$(MAKE) -C games/polygt3d clean-cd games/tetris/tetris && $(CARGO) clean-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)diff --git a/docs/media/gallery/polygt3d.gif b/docs/media/gallery/polygt3d.gifnew file mode 100644index 00000000..f103f799Binary files /dev/null and b/docs/media/gallery/polygt3d.gif differdiff --git a/docs/media/thumb_polygt3d.png b/docs/media/thumb_polygt3d.pngnew file mode 100644index 00000000..4d1c91bfBinary files /dev/null and b/docs/media/thumb_polygt3d.png differdiff --git a/games/games.json b/games/games.jsonindex cadce010..452cd1a5 100644--- a/games/games.json+++ b/games/games.json@@ -677,7 +677,7 @@},{"id": "championisland",- "rank": 21,+ "rank": 22,"title": "Champion Island","tagline": "Seven sports, one island","credit": "Based on Google's Champion Island Games",@@ -699,7 +699,7 @@},{"id": "finalearth2",- "rank": 22,+ "rank": 23,"title": "The Final Earth 2","tagline": "Build a city in space","credit": "Based on the game by Florian van Strien",@@ -923,7 +923,7 @@},{"id": "cookieclicker",- "rank": 24,+ "rank": 25,"title": "Cookie Clicker","tagline": "Bake billions of cookies","credit": "Based on Cookie Clicker by Orteil",@@ -944,7 +944,7 @@},{"id": "leveldevil",- "rank": 23,+ "rank": 24,"title": "Level Devil","tagline": "Run to the door","credit": "Based on Level Devil by Unept",@@ -1151,5 +1151,26 @@"repo": "https://github.com/Mason363/NumPlay/tree/main/games/turborush","default": false,"xl": true+ },+ {+ "id": "polygt3d",+ "rank": 21,+ "title": "PolyGT 3D",+ "tagline": "3D racing on three circuits",+ "credit": "A game by Boris-TH",+ "top": "0x231955",+ "bottom": "0xEB6E50",+ "accent": "0x00C3EB",+ "colors": 16,+ "records": [+ "polygt3d.sav",+ "polygt3d_saves.py"+ ],+ "shots": [+ "docs/shot.png"+ ],+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/polygt3d",+ "default": false,+ "xl": true}]diff --git a/games/polygt3d/.gitignore b/games/polygt3d/.gitignorenew file mode 100644index 00000000..342d9dda--- /dev/null+++ b/games/polygt3d/.gitignore@@ -0,0 +1,2 @@+output/+build/diff --git a/games/polygt3d/Makefile b/games/polygt3d/Makefileindex e38e4a74..2ce2d278 100644--- a/games/polygt3d/Makefile+++ b/games/polygt3d/Makefile@@ -1,35 +1,46 @@-# PolyGT 3D — PlayStation 1 style retro 3D racing simulator-# make build output/polygt3d.nwa-# make check link the app like the calculator does (output/polygt3d.bin)-# make test run self-verification unit and physics tests+# PolyGT 3D on the NumWorks calculator.+# make output/polygt3d.nwa+# make check link it like the calculator does (output/polygt3d.bin), within the RAM and the app space+# make host build/play: the game on a computer, for tests and pictures+# make test the roads, laps, physics, crashes, the rivals finishing every circuit at every level, a race+# driven to the finish, the endless road, saves (kept, damaged, storage full), random keys and the+# same race to the same hash on every computer (with the sanitizers)Q ?= @CC = arm-none-eabi-gccNWLINK ?= npx --yes -- [email protected]BUILD_DIR = output-SRC = src/main.c+L = ../../launcher/src-CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)-CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant-CFLAGS += -DPLATFORM_DEVICE=1+SRC = src/main.c src/track.c src/race.c src/save.c src/render.c src/draw.c src/plat_eadk.c \+ $(L)/gfx.c $(L)/font_data.c $(L)/xfont.c+HEADERS = $(wildcard src/*.h) $(L)/gfx.h $(L)/font.h $(L)/np.h ../common/epsilon_app.h ../common/epsilon_files.h++CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1 -I$(L) -Isrc+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant -ffp-contract=off+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+CFLAGS += -ffunction-sections -fdata-sectionsLDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specsLDFLAGS += -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 test clean+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones), and the+# calculator's app space is 2031616 bytes+RAM = 133652+APP_SPACE = 2031616+.PHONY: build check clean host testbuild: $(BUILD_DIR)/polygt3d.nwacheck: $(BUILD_DIR)/polygt3d.nwa- $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/polygt3d.bin- @echo "BIN $(BUILD_DIR)/polygt3d.bin: $$(wc -c < $(BUILD_DIR)/polygt3d.bin) bytes"--test:- $(Q) gcc -O2 -Wall -Wextra tests/verify_sim.c -o $(BUILD_DIR)/verify_sim- $(Q) ./$(BUILD_DIR)/verify_sim+ $(Q) $(NWLINK) nwa-bin --ram-length $(RAM) $< $(BUILD_DIR)/polygt3d.bin+ $(Q) n=$$(wc -c < $(BUILD_DIR)/polygt3d.bin); [ $$n -le $(APP_SPACE) ] || \+ { echo "polygt3d.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }; \+ echo "BIN $(BUILD_DIR)/polygt3d.bin: $$n bytes, RAM within $(RAM) bytes"-$(BUILD_DIR)/polygt3d.nwa: $(SRC) $(BUILD_DIR)/icon.o | $(BUILD_DIR)+$(BUILD_DIR)/polygt3d.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o@echo "LD $@"- $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@- $(Q) arm-none-eabi-strip --strip-debug $@+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -lm -o $@+ $(Q) arm-none-eabi-strip --strip-unneeded $@$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)@echo "ICON $<"@@ -38,5 +49,17 @@ $(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)$(BUILD_DIR):$(Q) mkdir -p $@+# on a computer: tests/play.c drives races and the whole app, and saves pictures+HOST_SRC = tests/play.c src/track.c src/race.c src/save.c src/render.c src/draw.c $(L)/gfx.c $(L)/font_data.c \+ $(L)/xfont.c+HOST_FLAGS = -std=gnu11 -O2 -g -Wall -Wextra -Wno-unused-parameter -ffp-contract=off -Isrc -I$(L) -DHOST+host: build/play+build/play: $(HOST_SRC) src/main.c $(wildcard src/*.h)+ $(Q) mkdir -p build+ $(Q) cc $(HOST_FLAGS) -fsanitize=address,undefined -fno-sanitize-recover=undefined $(HOST_SRC) -lm -o $@+ @echo "HOST $@"+test: build/play+ build/play test build+clean:- $(Q) rm -rf $(BUILD_DIR)+ $(Q) rm -rf $(BUILD_DIR) builddiff --git a/games/polygt3d/README.md b/games/polygt3d/README.mdindex a1e034b3..b1b906a9 100644--- a/games/polygt3d/README.md+++ b/games/polygt3d/README.md@@ -1,43 +1,89 @@-# PolyGT 3D+> **PolyGT 3D is a [NumPlay](../../README.md) game that comes on its own.** It is too big to fit next to NumPlay on the calculator. Get `PolyGT3D.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).-A low-poly retro 3D racing simulator for the NumWorks graphing calculator, built with a custom tile-strip software rasterizer and true 3D world physics.+<p align="center">+ <img src="src/icon.png" width="84" alt="PolyGT 3D icon">+</p>-+<h1 align="center">PolyGT 3D</h1>++<p align="center">+ <b>A low-poly 3D racer for the NumWorks calculator.</b><br>+ Three circuits, seven rivals and a road that never ends.+</p>++<p align="center">+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/PolyGT3D.nwa"><b>Download PolyGT3D.nwa</b></a>+ · <a href="#controls">Controls</a>+</p>++<p align="center">+ <img src="../../docs/media/gallery/polygt3d.gif" width="640" alt="PolyGT 3D: the start at Ridge Valley GT, chasing the rivals into the first bends">+</p>## Highlights-- **Custom 3D Engine in ~52 KB Binary**:- - 6-strip (`320x40`) tile Z-buffer renderer using only 51.2 KB of RAM for full `320x240` 16-bit depth-buffered output.- - Sub-pixel PS1 integer vertex snapping/jitter and perspective-correct affine textures.- - Analytic scanline span rasterizer hitting 2,600+ FPS on PC simulator and 60 FPS on Cortex-M7.-- **True 3D Physics & Simcade Handling**:- - Full Euclidean 3D world coordinates `(wx, wy, wz, yaw)`.- - Body roll/pitch suspension, progressive steering rack, tire smoke, and exhaust flame sparks.- - Automatic & 6-speed Manual transmission (`Alpha` / `+` / `-`), E-brake power drifting (`Shift` / `Backspace`).- - Nitro Boost (`Ans` / `EXE` / `x,n,t`) and 3D spinning crystal boost orbs.-- **Game Modes & Content**:- - **Circuits**: Ridge Valley GT (Sunset), Neo-Tokyo Wangan (Midnight Expressway), Mt. Akagi Touge (Dusk Mountain Pass).- - **Procedural Infinity Mode**: Endless streaming highway with dynamic terrain biomes, elevation changes, and zero bot traffic.- - **Cars**: RX-79 Apex GT, NSX-R Proto, Evo-IV Rally, Black Stallion, Brown Mustang.- - **Rivals**: 3D AI rivals with corner braking, overtaking, and drafting slipstream.- - **Best Lap Ghost**: 3D transparent stipple ghost car recording your fastest run.+* **Three circuits:** Ridge Valley GT at sunset, Neo-Tokyo Wangan at midnight and Mt. Akagi Touge at dusk, each with its own bends, hills and roadside.+* **Up to seven rivals** who brake for the bends, keep to their own lines, pass slower cars and grab nitro orbs, at three levels: Easy, Normal and Hard.+* **The endless road:** a road that goes on through five landscapes. Reach each zone before the clock runs out.+* **Three cars and two horses:** the Apex GT, Proto R and Rally IV, the Black Stallion and the Brown Mustang, each with its own top speed, pick-up and grip.+* **Nitro and the slipstream:** orbs on the road fill your nitro, and driving close behind a car pulls you along.+* **A ghost of your best lap** on each circuit, to race yourself.+* **Your way:** 1 to 9 laps, no rivals up to seven, automatic or manual gears, three views.+* **Saved as you go:** Home saves and quits, even in the middle of a race, and Continue picks it up. Your progress is also copied into `polygt3d_saves.py`, so installing the app again doesn't erase it.++<table>+ <tr>+ <td align="center"><img src="docs/shot.png" width="390" alt="The start at Ridge Valley GT"><br><sub>Ridge Valley GT: seven rivals ahead</sub></td>+ <td align="center"><img src="docs/wangan.png" width="390" alt="Neo-Tokyo Wangan at midnight"><br><sub>Neo-Tokyo Wangan at midnight</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/akagi.png" width="390" alt="Mt. Akagi Touge at dusk"><br><sub>Mt. Akagi Touge, its hairpins and climbs</sub></td>+ <td align="center"><img src="docs/endless.png" width="390" alt="The endless road"><br><sub>The endless road, with a nitro orb</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/horse.png" width="390" alt="The Brown Mustang on the title screen"><br><sub>The Brown Mustang, one of the two horses</sub></td>+ <td align="center"><img src="docs/setup.png" width="390" alt="Choosing a race"><br><sub>Choosing a race</sub></td>+ </tr>+</table>++## How to play++You start at the back of the grid. Hold **Up** to accelerate, steer with **Left** and **Right**, and finish the laps ahead of as many rivals as you can. The map at the top right shows where everyone is.++Your car goes where it points. A bend you don't steer through carries you to its outside, and the faster you go, the less the tyres can turn you: brake before the tight bends (yellow arrows mark the sharpest). Brake while steering hard to slide round a hairpin, a tighter line for less braking. The grass slows you down, and so do the barriers.++**OK** burns nitro for more speed, and only the blue orbs on the road fill it up again. Driving close behind a car pulls you along. Each circuit keeps a ghost of your best lap, so you can race yourself.++On the endless road there are no rivals: reach each new zone before the time runs out. Every zone adds time, a little less each time.## Controls-Designed to match the physical ergonomics of the NumWorks keyboard:+| Key | What it does |+| --- | --- |+| Up | Accelerate |+| Down | Brake (while steering hard: slide) |+| Left and Right | Steer |+| OK or EXE | Nitro |+| + and - | Change gear, with the manual gearbox |+| Back | Pause (Resume, Restart race, How to play, Quit game) |+| Home | Save and quit |++In the menus, the arrows choose, **OK** picks and **Back** goes back. 8, 4, 6, 2 and 5 work as the arrows and OK.++## Good to know-| Action | NumWorks Key | PC Key |-| :--- | :--- | :--- |-| **Steer** | `◀ Left` / `▶ Right` (or `4` / `6`) | `A` / `D` or `◀` / `▶` |-| **Accelerate** | `OK` / `▲ Up` / `EXE` / `×` | `W` / `▲` / `Enter` |-| **Brake / Reverse** | `Back` (`⮌`) / `▼ Down` / `÷` | `S` / `▼` / `Backspace` |-| **E-Brake Drift** | `shift` (Left Thumb) or `clear ⌫` (Right Thumb) | `Left Shift` |-| **Nitro Boost** | `Ans` / `x,n,t` / `0` / `.` / `EXE` | `Space` / `X` / `Left Ctrl` |-| **Shift Up / Down (MT)** | `+` / `-` (or `(` / `)`) | `E` / `Q` or `+` / `-` |-| **AT / MT Toggle** | `alpha` | `M` / `Tab` |-| **Change Camera** | `toolbox` or `var` | `C` / `V` / `P` |-| **Return to Garage** | `Home` | `Esc` |+* **On its own:** PolyGT 3D is too big to fit next to NumPlay. Installing it from the NumWorks website swaps out NumPlay and the other apps, and installing NumPlay again swaps it back out. Your progress in each one is kept.+* **Quit game** in the pause menu asks first, and can take you back to the main menu instead. The race is kept either way.+* The ghosts are kept until you quit the game.+* There is no music or sound: the calculator has no speaker.## Credits-- Developed by Boris-TH+PolyGT 3D by **Boris-TH**, made for NumPlay.++* The cars, the horses and the scenery were made for the game by Boris-TH.+* The text uses NumPlay's **Nunito** font (SIL Open Font License).++## License++The game's code and pictures are licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. Nunito keeps the SIL Open Font License (`LICENSES/OFL-1.1-Nunito.txt`).diff --git a/games/polygt3d/docs/akagi.png b/games/polygt3d/docs/akagi.pngnew file mode 100644index 00000000..2aed76d7Binary files /dev/null and b/games/polygt3d/docs/akagi.png differdiff --git a/games/polygt3d/docs/endless.png b/games/polygt3d/docs/endless.pngnew file mode 100644index 00000000..c3a5dcf2Binary files /dev/null and b/games/polygt3d/docs/endless.png differdiff --git a/games/polygt3d/docs/horse.png b/games/polygt3d/docs/horse.pngnew file mode 100644index 00000000..388886f1Binary files /dev/null and b/games/polygt3d/docs/horse.png differdiff --git a/games/polygt3d/docs/preview.png b/games/polygt3d/docs/preview.pngdeleted file mode 100644index 5d4f74a4..00000000Binary files a/games/polygt3d/docs/preview.png and /dev/null differdiff --git a/games/polygt3d/docs/setup.png b/games/polygt3d/docs/setup.pngnew file mode 100644index 00000000..fc5d8b2aBinary files /dev/null and b/games/polygt3d/docs/setup.png differdiff --git a/games/polygt3d/docs/shot.png b/games/polygt3d/docs/shot.pngnew file mode 100644index 00000000..d0cf5487Binary files /dev/null and b/games/polygt3d/docs/shot.png differdiff --git a/games/polygt3d/docs/sunset.png b/games/polygt3d/docs/sunset.pngdeleted file mode 100644index 140f3a73..00000000Binary files a/games/polygt3d/docs/sunset.png and /dev/null differdiff --git a/games/polygt3d/docs/wangan.png b/games/polygt3d/docs/wangan.pngnew file mode 100644index 00000000..8df28085Binary files /dev/null and b/games/polygt3d/docs/wangan.png differdiff --git a/games/polygt3d/src/draw.c b/games/polygt3d/src/draw.cnew file mode 100644index 00000000..d117c47d--- /dev/null+++ b/games/polygt3d/src/draw.c@@ -0,0 +1,605 @@+/* PolyGT 3D's screens: the title over a car on a turntable, the race screen, how to play and the records; the race's+ * dials; the pause, results and questions over the race. Each has a line of plain keys at the bottom. */+#include <string.h>+#include "../../../launcher/src/gfx.h"+#include "draw.h"++#define WHITE 0xFFFF+#define INK HEX(0x0E0B24)+#define PANEL HEX(0x1C1745)+#define LINE HEX(0x3B3478)+#define CYAN HEX(0x00C3EB)+#define SUN HEX(0xEB6E50)+#define GOLD HEX(0xFFD052)+#define MUTED HEX(0xB2ADD6)+#define DIM HEX(0x6A6496)+#define RED HEX(0xFF5A4E)+#define STRIP 24++/* the launcher's drawing (gfx.c) sends strips here when asked; this game sends its own */+void plat_push(int x, int y, int w, int h, const uint16_t *px);+void np_push(int x, int y, int w, int h, const color_t *px) { plat_push(x, y, w, h, px); }+static color_t strip[SCREEN_W * STRIP];++const char *const pg_driver[PG_CARS] = {"You", "Aiko", "Bruno", "Dara", "Emil", "Farah", "Goro", "Hana"};+static const char *const MODES[2] = {"Circuit race", "Endless road"};+static const char *const LEVELS[3] = {"Easy", "Normal", "Hard"};+static const char *const VIEW_NAMES[VIEWS] = {"Behind", "Far behind", "Bumper"};++static const pg_file *F;+static const pg_track *T;+static const pg_race *R;+static const pg_ui *U;++/* ------------------------------------------------------------------ text */+static char *cat(char *p, const char *s) {+ while (*s) *p++ = *s++;+ *p = 0;+ return p;+}+static char *num(char *p, uint32_t v) {+ char t[12];+ int n = 0;+ do t[n++] = (char)('0' + v % 10); while ((v /= 10) && n < 11);+ while (n) *p++ = t[--n];+ *p = 0;+ return p;+}+static char *clock_of(char *p, uint32_t ms) {+ p = num(p, ms / 60000);+ *p++ = ':', *p++ = (char)('0' + ms / 10000 % 6), *p++ = (char)('0' + ms / 1000 % 10), *p++ = '.';+ *p++ = (char)('0' + ms / 100 % 10), *p++ = (char)('0' + ms / 10 % 10), *p = 0;+ return p;+}+static char *ordinal(char *p, int n) {+ p = num(p, (uint32_t)n);+ return cat(p, n == 1 ? "st" : n == 2 ? "nd" : n == 3 ? "rd" : "th");+}+static char *km(char *p, uint32_t m) {+ p = num(p, m / 1000);+ *p++ = '.', *p++ = (char)('0' + m / 100 % 10);+ return cat(p, " km");+}++static void text(const np_font_t *f, int x, int y, const char *s, color_t c) { gfx_text(f, x, y, s, c, 256); }+static void center(const np_font_t *f, int x, int y, const char *s, color_t c) { gfx_text_center(f, x, y, s, c, 256); }+static void right(const np_font_t *f, int x, int y, const char *s, color_t c) { gfx_text_right(f, x, y, s, c, 256); }++/* ------------------------------------------------------------------ pieces */+/* a line of keys: "Up Down=choose|OK=open", each key in cyan, what it does after it */+static void key_line(int y, const char *s) {+ char buf[48];+ int w = 0;+ for (int pass = 0; pass < 2; pass++) {+ int x = 160 - w / 2;+ w = 0;+ const char *q = s;+ while (*q) {+ int k = 0;+ while (q[k] && q[k] != '=' && q[k] != '|' && k < (int)sizeof buf - 1) k++;+ memcpy(buf, q, (size_t)k), buf[k] = 0;+ bool key = q[k] == '=';+ int tw = gfx_text_width(&np_font_small, buf);+ if (pass) text(&np_font_small, x + w, y, buf, key ? CYAN : MUTED);+ w += tw + (key ? 4 : 0);+ q += k;+ if (*q == '=') q++;+ else if (*q == '|') q++, w += 11;+ }+ }+}++static void keys(const char *s) {+ gfx_fill(0, 222, 320, 18, INK);+ gfx_fill(0, 222, 320, 1, LINE);+ key_line(235, s);+}++static void page(const char *title) {+ gfx_vgrad(0, 0, 320, 222, 0x120E30, 0x2A1F55);+ text(&np_font_title, 14, 30, title, WHITE);+}++/* a button: the chosen one bright and framed */+static void button(int x, int y, int w, const char *s, bool on) {+ if (on) {+ gfx_rrect(x - 2, y - 2, w + 4, 30, 8, WHITE, 256);+ gfx_rrect(x, y, w, 26, 6, CYAN, 256);+ } else {+ gfx_rrect(x, y, w, 26, 6, PANEL, 235);+ gfx_rrect_outline(x, y, w, 26, 6, 1, LINE, 256);+ }+ center(&np_font_body, x + w / 2, y + 18, s, on ? INK : WHITE);+}++static void dim(void) { gfx_fill_alpha(0, 0, 320, 240, HEX(0x05040F), 150); }++/* when the calculator's storage is full, say so above the keys */+static void not_saved(void) {+ if (!U->save_failed) return;+ gfx_rrect(40, 202, 240, 17, 5, HEX(0x5A1E1A), 240);+ center(&np_font_small, 160, 214, "Storage full: progress not saved", WHITE);+}++static void bar(int x, int y, int w, int h, int v, int max, color_t c) {+ gfx_rrect(x, y, w, h, h / 2, HEX(0x2A2456), 256);+ int f = v * w / max;+ if (f > 0) gfx_rrect(x, y, f < h ? h : f, h, h / 2, c, 256);+}++/* "POLYGT 3D", twice the title font, slanted, with a shadow */+static void logo(int x0, int y) {+ const np_font_t *f = &np_font_title;+ const char *s = "POLYGT 3D";+ for (int pass = 0; pass < 2; pass++) {+ int x = x0 + (pass ? 0 : 2), base = y + (pass ? 0 : 2);+ for (const char *q = s; *q; q++) {+ const np_glyph_t *g = &f->glyphs[(uint8_t)*q - f->first];+ const uint8_t *m = f->data + g->offset;+ color_t c = pass ? (q >= s + 7 ? SUN : WHITE) : HEX(0x0A0820);+ for (int gy = 0; gy < g->h; gy++) {+ int yy = base + (g->y + gy) * 2;+ if (yy + 2 <= gfx_y0 || yy >= gfx_y1) continue;+ for (int gx = 0; gx < g->w; gx++) {+ int k = gy * g->w + gx, cov = (m[k / 2] >> ((k & 1) * 4)) & 15;+ int lean = (g->h - gy) / 3;+ if (cov) gfx_fill_alpha(x + (g->x + gx) * 2 + lean, yy, 2, 2, c, cov * 17);+ }+ }+ x += g->advance * 2;+ }+ }+}++/* a circuit's outline: a soft edge, a light line, the start line */+static int16_t map_x[64], map_y[64];+static int map_of = -1;+static void map_setup(const pg_track *t, int w, int h) {+ int key = t->id * 1000 + w * 10 + h;+ if (map_of == key) return;+ pg_map(t, 64, map_x, map_y, w, h);+ map_of = key;+}+static void outline(int x, int y) {+ for (int pass = 0; pass < 2; pass++)+ for (int i = 0; i < 64; i++) {+ int j = (i + 1) % 64, x0 = x + map_x[i], y0 = y + map_y[i], x1 = x + map_x[j], y1 = y + map_y[j];+ int n = NP_MAX(NP_MAX(x1 - x0, x0 - x1), NP_MAX(y1 - y0, y0 - y1));+ for (int k = 0; k <= n; k++) {+ int px = x0 + (n ? (x1 - x0) * k / n : 0), py = y0 + (n ? (y1 - y0) * k / n : 0);+ if (pass) gfx_fill(px, py, 1, 1, HEX(0xE6E4F2));+ else gfx_fill(px - 1, py - 1, 3, 3, HEX(0x6E68A0));+ }+ }+ gfx_fill(x + map_x[0] - 1, y + map_y[0] - 3, 3, 6, WHITE);+}+/* where a distance is on the outline */+static void map_at(int32_t s, int *px, int *py) {+ int32_t L = T->length, m = s % L;+ if (m < 0) m += L;+ int64_t f = (int64_t)m * 64 / L;+ int i = (int)f, j = (i + 1) % 64;+ int32_t frac = (int32_t)((int64_t)m * 64 % L * 256 / L);+ *px = map_x[i] + (map_x[j] - map_x[i]) * frac / 256;+ *py = map_y[i] + (map_y[j] - map_y[i]) * frac / 256;+}++/* ------------------------------------------------------------------ the race's dials */+static void hud(void) {+ const pg_race *r = R;+ char s[40], *p;+ bool endless = r->mode == MODE_ENDLESS;+ gfx_rrect(6, 6, 98, 40, 6, INK, 215);+ if (endless) {+ text(&np_font_small, 14, 19, "TIME", MUTED);+ text(&np_font_small, 62, 19, "ZONE", MUTED);+ uint32_t left = (uint32_t)r->time_left;+ num(s, (left + 999) / 1000);+ text(&np_font_title, 14, 40, s, left < 10000 && ((U->clock / 250) & 1) ? RED : WHITE);+ num(s, (uint32_t)r->zone + 1);+ text(&np_font_body, 62, 40, s, WHITE);+ } else {+ text(&np_font_small, 14, 19, "POS", MUTED);+ text(&np_font_small, 62, 19, "LAP", MUTED);+ num(s, (uint32_t)pg_rank(r, 0));+ int w = gfx_text(&np_font_title, 14, 40, s, WHITE, 256);+ p = cat(s, "/");+ num(p, (uint32_t)r->rivals + 1);+ text(&np_font_body, 14 + w + 1, 40, s, MUTED);+ p = num(s, r->lap);+ p = cat(p, "/");+ num(p, r->laps);+ text(&np_font_body, 62, 40, s, WHITE);+ }+ /* the clock, or the distance */+ gfx_rrect(112, 6, 96, 40, 6, INK, 215);+ if (endless) {+ km(s, (uint32_t)(r->car[0].s / FX));+ center(&np_font_body, 160, 23, s, WHITE);+ if (F->p.best_m) {+ p = cat(s, "Best ");+ km(p, F->p.best_m);+ center(&np_font_small, 160, 38, s, MUTED);+ } else {+ center(&np_font_small, 160, 38, pg_zone_name[(pg_zone_at(T, r->car[0].s) - 3) % 5], MUTED);+ }+ } else {+ clock_of(s, r->time_ms);+ center(&np_font_body, 160, 23, s, WHITE);+ uint32_t best = r->best_lap_ms;+ if (best) {+ clock_of(cat(s, "Best lap "), best);+ center(&np_font_small, 160, 38, s, MUTED);+ } else {+ center(&np_font_small, 160, 38, pg_circuit_name[r->track], MUTED);+ }+ }+ /* the map */+ if (!endless) {+ map_setup(T, 70, 50);+ gfx_rrect(232, 6, 82, 62, 6, INK, 200);+ outline(238, 12);+ int sx, sy;+ for (int i = r->rivals; i >= 1; i--) {+ map_at(r->car[i].s, &sx, &sy);+ gfx_circle(238 + sx, 12 + sy, 2, rd_rgb(rd_paint[r->car[i].paint & 7]), 256);+ }+ map_at(r->car[0].s, &sx, &sy);+ gfx_circle(238 + sx, 12 + sy, 4, WHITE, 256);+ gfx_circle(238 + sx, 12 + sy, 3, SUN, 256);+ }+ /* speed | gear | nitro, then the keys */+ const pg_car *c = &r->car[0];+ gfx_fill_alpha(0, 202, 320, 25, INK, 230);+ gfx_fill(0, 202, 320, 1, LINE);+ gfx_fill(0, 227, 320, 13, HEX(0x08061A));+ gfx_fill(92, 207, 1, 16, LINE), gfx_fill(140, 207, 1, 16, LINE);+ num(s, (uint32_t)pg_kmh(c->v));+ right(&np_font_title, 56, 224, s, c->boost ? CYAN : WHITE);+ text(&np_font_small, 60, 224, "km/h", MUTED);+ text(&np_font_small, 99, 213, "GEAR", MUTED);+ s[0] = (char)('0' + c->gear), s[1] = 0;+ bool red = pg_rpm(r) > pg_vehicles[c->model].redline - 350;+ text(&np_font_body, 100, 225, s, red && r->manual ? RED : r->manual ? GOLD : WHITE);+ text(&np_font_small, 113, 225, r->manual ? "MT" : "AT", DIM);+ const char *nl = r->flash ? "NITRO +" : r->slipstream > 10 ? "SLIPSTREAM" : c->drift ? "SLIDE" : "NITRO";+ text(&np_font_small, 146, 213, nl, r->flash || r->slipstream > 10 ? GOLD : c->drift ? SUN : MUTED);+ bar(146, 216, 166, 7, c->nitro, 1000, c->boost ? HEX(0xA8F2FF) : CYAN);+ key_line(237, r->manual ? "Up=gas|Down=brake|OK=nitro|+ -=gears|Back=pause" : "Up=gas|Down=brake|OK=nitro|Back=pause");+ /* the start, a lap, the finish */+ if (r->phase == PH_GRID || (U->hold && U->screen == V_RACE)) {+ int n = r->phase == PH_GRID ? (r->countdown + PG_HZ - 1) / PG_HZ : U->hold;+ gfx_rrect(100, 58, 120, 48, 8, INK, 225);+ if (n > 3) {+ center(&np_font_body, 160, 78, endless ? "Endless road" : pg_circuit_name[r->track], WHITE);+ center(&np_font_small, 160, 96, "Get ready", MUTED);+ } else {+ s[0] = (char)('0' + n), s[1] = 0;+ center(&np_font_title, 160, 90, s, GOLD);+ }+ } else if (r->phase == PH_RACE && r->time_ms < 1000 && !r->banner_t) {+ gfx_rrect(110, 58, 100, 48, 8, INK, 225);+ center(&np_font_title, 160, 90, "GO!", GOLD);+ } else if (r->phase == PH_DONE) {+ gfx_rrect(90, 58, 140, 54, 8, INK, 225);+ if (r->end == END_FINISH) {+ center(&np_font_title, 160, 86, "Finish!", GOLD);+ ordinal(s, r->car[0].place);+ center(&np_font_body, 160, 105, s, WHITE);+ } else {+ center(&np_font_title, 160, 86, "Time up", RED);+ if (endless) km(s, (uint32_t)(r->car[0].s / FX)), center(&np_font_body, 160, 105, s, WHITE);+ }+ } else if (r->banner_t) {+ const char *big = "";+ char t[24];+ t[0] = 0;+ color_t col = GOLD;+ if (r->banner == BANNER_LAP || r->banner == BANNER_FINAL) {+ if (r->banner == BANNER_FINAL) big = "Final lap";+ else p = cat(s, "Lap "), num(p, r->banner_arg), big = s;+ char *e = clock_of(t, r->last_lap_ms);+ if (r->banner_arg >= 3 && r->last_lap_ms == r->best_lap_ms) cat(e, " best");+ } else if (r->banner == BANNER_ZONE) {+ p = cat(s, "Zone "), num(p, (uint32_t)r->banner_arg + 1), big = s;+ uint32_t b = (uint32_t)pg_zone_bonus(r->banner_arg);+ p = cat(t, "+");+ p = num(p, b / 1000);+ if (b % 1000) *p++ = '.', *p++ = (char)('0' + b / 100 % 10), *p = 0;+ cat(p, " s");+ } else if (r->banner == BANNER_WRONG) {+ big = "Wrong way", col = RED;+ cat(t, "Turn round");+ }+ if (big[0]) {+ gfx_rrect(90, 58, 140, t[0] ? 54 : 40, 8, INK, 225);+ center(&np_font_title, 160, 86, big, col);+ if (t[0]) center(&np_font_body, 160, 105, t, WHITE);+ }+ }+}++/* ------------------------------------------------------------------ screens */+static void title(void) {+ for (int y = 0; y < 84; y += 4) gfx_fill_alpha(0, y, 320, 4, HEX(0x05040F), 160 - y * 160 / 84);+ logo(16, 46);+ text(&np_font_small, 18, 66, "by Boris-TH, made for NumPlay", WHITE);+ static const char *const NAMES[4] = {"Continue", "Play", "Records", "How to play"};+ int n = U->menu_n, y0 = 92;+ for (int i = 0; i < n; i++) {+ int item = U->menu[i];+ const char *s = NAMES[item];+ if (item == MENU_CONTINUE) s = F->race.mode == MODE_ENDLESS ? "Continue drive" : "Continue race";+ button(16, y0 + i * 31, 136, s, U->sel == i);+ }+ /* the car on the turntable (or, when the storage is full, that) */+ const pg_vehicle *v = &pg_vehicles[F->p.vehicle];+ if (U->save_failed) {+ gfx_rrect(164, 186, 150, 30, 6, HEX(0x5A1E1A), 240);+ center(&np_font_small, 239, 199, "Storage full:", WHITE);+ center(&np_font_small, 239, 211, "progress not saved", WHITE);+ } else {+ gfx_rrect(164, 186, 150, 30, 6, INK, 200);+ center(&np_font_body, 239, 200, v->name, WHITE);+ center(&np_font_small, 239, 212, v->kind, MUTED);+ }+ keys("Up Down=choose|OK=open|Back=quit");+}++static void stat_row(int y, const char *name, int v, int max) {+ text(&np_font_small, 212, y, name, MUTED);+ bar(212, y + 4, 90, 6, v < 0 ? 0 : v, max, CYAN);+}++static void setup(void) {+ page("RACE");+ const pg_profile *p = &F->p;+ static const char *const NAMES[SET_ROWS] = {"Mode", "Circuit", "Car", "Laps", "Rivals", "Level", "Gearbox", "View", ""};+ bool endless = p->mode == MODE_ENDLESS;+ char s[24];+ for (int i = 0; i < SET_START; i++) {+ int y = 38 + i * 19;+ bool on = U->sel == i;+ bool off = endless && (i == SET_TRACK || i == SET_LAPS || i == SET_RIVALS || i == SET_LEVEL);+ if (on) gfx_rrect(8, y - 1, 194, 19, 5, WHITE, 256);+ gfx_rrect(10, y, 190, 17, 4, on ? CYAN : PANEL, 256);+ color_t c = on ? INK : off ? DIM : WHITE;+ text(&np_font_small, 18, y + 13, NAMES[i], c);+ const char *v = "";+ switch (i) {+ case SET_MODE: v = MODES[p->mode]; break;+ case SET_TRACK: v = endless ? "-" : pg_circuit_name[p->track]; break;+ case SET_CAR: v = pg_vehicles[p->vehicle].name; break;+ case SET_LAPS:+ if (endless) v = "-";+ else num(s, p->laps), v = s;+ break;+ case SET_RIVALS:+ if (endless) v = "-";+ else if (!p->rivals) v = "None";+ else num(s, p->rivals), v = s;+ break;+ case SET_LEVEL: v = endless ? "-" : LEVELS[p->level]; break;+ case SET_GEARS: v = p->manual ? "Manual" : "Automatic"; break;+ case SET_VIEW: v = VIEW_NAMES[p->view]; break;+ }+ right(&np_font_small, off ? 192 : 180, y + 13, v, c);+ if (!off) text(&np_font_small, 184, y + 13, ">", on ? INK : DIM);+ }+ /* the right: the car when choosing it, else the circuit or the road */+ gfx_rrect(206, 38, 104, 150, 6, PANEL, 256);+ if (U->sel == SET_CAR) {+ const pg_vehicle *v = &pg_vehicles[p->vehicle];+ center(&np_font_small, 258, 54, v->name, WHITE);+ stat_row(74, "Top speed", v->top / 8 - 60, 25);+ stat_row(98, "Pick-up", v->accel / 8 - 30, 18);+ stat_row(122, "Grip", v->grip - 110, 50);+ stat_row(146, "On grass", 160 - v->offroad, 100);+ num(s, (uint32_t)(v->top / 8) * 36 / 10);+ cat(s + strlen(s), " km/h");+ center(&np_font_small, 258, 178, s, GOLD);+ } else if (endless) {+ center(&np_font_small, 258, 56, "Endless road", WHITE);+ static const char *const L[6] = {"Reach each zone", "before the time", "runs out.", "Every zone adds", "time; the road", "never ends."};+ for (int i = 0; i < 6; i++) center(&np_font_small, 258, 80 + i * 15, L[i], MUTED);+ if (p->best_m) {+ km(cat(s, "Best "), p->best_m);+ center(&np_font_small, 258, 178, s, GOLD);+ }+ } else {+ center(&np_font_small, 258, 54, "Circuit", MUTED);+ map_setup(T, 84, 66);+ outline(216, 62);+ center(&np_font_small, 258, 146, pg_circuit_name[p->track], WHITE);+ center(&np_font_small, 258, 160, pg_circuit_note[p->track], MUTED);+ if (p->best_ms[p->track]) {+ clock_of(cat(s, "Best "), p->best_ms[p->track]);+ center(&np_font_small, 258, 178, s, GOLD);+ }+ }+ button(10, 192, 300, endless ? "Start the drive" : "Start race", U->sel == SET_START);+ keys(U->sel == SET_START ? "OK=start|Up Down=choose|Back=menu" : "Left Right=change|Up Down=choose|Back=menu");+}++static void confirm_box(const char *q, const char *note, int n, const char *const *labels) {+ dim();+ int h = 70 + n * 32;+ gfx_rrect(40, 120 - h / 2, 240, h, 8, INK, 256);+ gfx_rrect_outline(40, 120 - h / 2, 240, h, 8, 1, LINE, 256);+ center(&np_font_body, 160, 120 - h / 2 + 28, q, WHITE);+ if (note) center(&np_font_small, 160, 120 - h / 2 + 46, note, MUTED);+ for (int i = 0; i < n; i++) button(60, 120 - h / 2 + 58 + i * 32, 200, labels[i], U->sel == i);+}++static void help_page(int k, bool guide) {+ page(guide ? "BEFORE YOU RACE" : "HOW TO PLAY");+ static const char *const TITLES[PG_HELP_PAGES] = {"Keys", "Racing", "Endless road"};+ center(&np_font_body, 160, 56, TITLES[k], GOLD);+ if (k == 0) {+ static const char *const K[7][2] = {{"Up", "Accelerate"}, {"Down", "Brake"}, {"Left Right", "Steer"},+ {"OK or EXE", "Nitro"}, {"+ and -", "Gears, if manual"},+ {"Back", "Pause"}, {"Home", "Save and quit"}};+ for (int i = 0; i < 7; i++) {+ int y = 66 + i * 20;+ gfx_rrect(40, y, 240, 18, 4, PANEL, 256);+ text(&np_font_small, 50, y + 13, K[i][0], CYAN);+ text(&np_font_small, 140, y + 13, K[i][1], WHITE);+ }+ } else {+ static const char *const L[2][7] = {+ {"Finish the laps ahead of the rivals.", "Brake before tight bends, or you", "run wide. Brake while steering hard",+ "to slide round a hairpin. Orbs on the", "road fill your nitro; driving close", "behind a car pulls you along.",+ "Your best lap comes back as a ghost."},+ {"Reach the next zone before the", "clock runs out: each one adds time,", "a little less each time.",+ "There are no rivals, just you,", "the orbs and the road, which goes", "on and changes scenery.", ""}};+ for (int i = 0; i < 7; i++) center(&np_font_small, 160, 82 + i * 19, L[k - 1][i], WHITE);+ }+ for (int i = 0; i < PG_HELP_PAGES; i++) gfx_circle(148 + i * 12, 212, 3, i == k ? CYAN : DIM, 256);+ keys(guide ? "OK=start|Left Right=page|Back=return" : "Left Right=page|Back=return");+}++static void records(void) {+ page("RECORDS");+ text(&np_font_small, 172, 50, "Race", MUTED);+ text(&np_font_small, 246, 50, "Lap", MUTED);+ char s[32];+ for (int i = 0; i < PG_CIRCUITS; i++) {+ int y = 56 + i * 24;+ gfx_rrect(10, y, 300, 21, 5, PANEL, 256);+ text(&np_font_small, 18, y + 15, pg_circuit_name[i], WHITE);+ if (F->p.best_ms[i]) clock_of(s, F->p.best_ms[i]);+ else cat(s, "-");+ text(&np_font_small, 172, y + 15, s, F->p.best_ms[i] ? GOLD : DIM);+ if (F->p.best_lap_ms[i]) clock_of(s, F->p.best_lap_ms[i]);+ else cat(s, "-");+ text(&np_font_small, 246, y + 15, s, F->p.best_lap_ms[i] ? GOLD : DIM);+ }+ int y = 56 + 3 * 24;+ gfx_rrect(10, y, 300, 21, 5, PANEL, 256);+ text(&np_font_small, 18, y + 15, "Endless road", WHITE);+ if (F->p.best_m) {+ char *q = km(s, F->p.best_m);+ q = cat(q, ", zone ");+ num(q, F->p.best_zone);+ } else {+ cat(s, "-");+ }+ text(&np_font_small, 172, y + 15, s, F->p.best_m ? GOLD : DIM);+ char t[64], *q = cat(t, "Races ");+ q = num(q, F->p.races);+ q = cat(q, " Wins ");+ num(q, F->p.wins);+ center(&np_font_small, 160, 196, t, MUTED);+ keys("Back=menu");+}++static void result(void) {+ dim();+ const pg_race *r = R;+ char s[48];+ bool endless = r->mode == MODE_ENDLESS;+ int h = endless ? 176 : 196, y0 = (222 - h) / 2;+ gfx_rrect(30, y0, 260, h, 8, INK, 256);+ gfx_rrect_outline(30, y0, 260, h, 8, 1, LINE, 256);+ int y = y0 + 30;+ if (endless) {+ km(s, (uint32_t)(r->car[0].s / FX));+ center(&np_font_title, 160, y, s, GOLD);+ char *q = cat(s, "Zone ");+ num(q, (uint32_t)r->zone + 1);+ center(&np_font_body, 160, y + 22, s, WHITE);+ if (U->new_far && !U->save_failed) center(&np_font_small, 160, y + 40, "Your furthest yet!", GOLD);+ else if (F->p.best_m) km(cat(s, "Best "), F->p.best_m), center(&np_font_small, 160, y + 40, s, MUTED);+ } else if (r->end == END_TIME) {+ center(&np_font_title, 160, y, "Time up", RED);+ center(&np_font_small, 160, y + 16, pg_circuit_name[r->track], MUTED);+ } else {+ char *q = ordinal(s, U->result_rank);+ cat(q, U->result_rank == 1 ? " place!" : " place");+ center(&np_font_title, 160, y, s, U->result_rank == 1 ? GOLD : WHITE);+ center(&np_font_small, 160, y + 16, pg_circuit_name[r->track], MUTED);+ clock_of(cat(s, "Time "), r->car[0].finish_ms);+ center(&np_font_body, 160, y + 36, s, WHITE);+ if (r->best_lap_ms) {+ clock_of(cat(s, "Best lap "), r->best_lap_ms);+ center(&np_font_small, 160, y + 52, s, WHITE);+ }+ if ((U->new_best || U->new_lap) && !U->save_failed)+ center(&np_font_small, 160, y + 68, U->new_best ? "New circuit record!" : "New lap record!", GOLD);+ }+ int by = y0 + h - 70;+ button(50, by, 220, endless ? "Drive again" : "Race again", U->sel == 0);+ button(50, by + 31, 220, "Main menu", U->sel == 1);+ if (U->save_failed) not_saved();+ keys("Up Down=choose|OK=select");+}++static void race_screen(void) {+ hud();+ if (U->screen == V_PAUSE) {+ static const char *const L[PAUSE_ROWS] = {"Resume", "Restart race", "How to play", "Quit game"};+ dim();+ gfx_rrect(60, 30, 200, 172, 8, INK, 256);+ gfx_rrect_outline(60, 30, 200, 172, 8, 1, LINE, 256);+ center(&np_font_title, 160, 60, "PAUSED", WHITE);+ for (int i = 0; i < PAUSE_ROWS; i++) {+ const char *s = i == PAUSE_RESTART && R->mode == MODE_ENDLESS ? "Restart drive" : L[i];+ button(80, 74 + i * 31, 160, s, U->sel == i);+ }+ keys("Up Down=choose|OK=select|Back=resume");+ } else if (U->screen == V_LEAVE) {+ static const char *const L[3] = {"Keep racing", "Main menu", "Quit PolyGT 3D"};+ confirm_box(R->mode == MODE_ENDLESS ? "Leave the drive?" : "Leave the race?", "It's kept: Continue picks it up.", 3, L);+ keys("Up Down=choose|OK=select|Back=pause");+ } else if (U->screen == V_RESULT) {+ result();+ }+}++static void scene(void) {+ switch (U->screen) {+ case V_SETUP: setup(); break;+ case V_NEWRUN: {+ setup();+ static const char *const L[2] = {"Keep it", "Start new"};+ confirm_box("Start something new?", F->race.mode == MODE_ENDLESS ? "The drive you left will end." : "The race you left will end.", 2, L);+ keys("Up Down=choose|OK=select|Back=return");+ break;+ }+ case V_GUIDE: help_page(U->page, true); break;+ case V_HELP: help_page(U->page, false); break;+ case V_RECORDS: records(); break;+ case V_TITLE:+ case V_QUIT:+ rd_draw();+ title();+ if (U->screen == V_QUIT) {+ static const char *const L[2] = {"Stay", "Quit"};+ confirm_box("Quit PolyGT 3D?", NULL, 2, L);+ keys("Up Down=choose|OK=select|Back=return");+ }+ break;+ default:+ rd_draw();+ race_screen();+ break;+ }+}++void pg_render(const pg_file *f, const pg_track *t, const pg_race *prev, const pg_race *race, int alpha,+ const pg_ui *ui, const rd_ghost *g) {+ F = f, T = t, R = race, U = ui;+ int s = ui->screen;+ if (s == V_RACE || s == V_PAUSE || s == V_LEAVE || s == V_RESULT)+ rd_race(t, prev, race, alpha, f->p.view, g, ui->clock);+ else if (s == V_TITLE || s == V_QUIT)+ rd_showroom(f->p.vehicle, (int32_t)(ui->clock * 12), f->p.track, ui->clock);+ color_t *old = gfx_buf;+ gfx_buf = strip;+ for (int y = 0; y < SCREEN_H; y += STRIP) {+ gfx_y0 = y, gfx_y1 = y + STRIP;+ scene();+ plat_push(0, y, SCREEN_W, STRIP, strip);+ }+ gfx_buf = old;+}diff --git a/games/polygt3d/src/draw.h b/games/polygt3d/src/draw.hnew file mode 100644index 00000000..c3ad60d4--- /dev/null+++ b/games/polygt3d/src/draw.h@@ -0,0 +1,27 @@+/* The screens (draw.c): menus, the race's dials, results. */+#ifndef PG_DRAW_H+#define PG_DRAW_H+#include "game.h"+#include "render.h"+#include "save.h"++enum { V_TITLE, V_SETUP, V_NEWRUN, V_GUIDE, V_HELP, V_RECORDS, V_RACE, V_PAUSE, V_LEAVE, V_RESULT, V_QUIT, V_SCREENS };+enum { SET_MODE, SET_TRACK, SET_CAR, SET_LAPS, SET_RIVALS, SET_LEVEL, SET_GEARS, SET_VIEW, SET_START, SET_ROWS };+enum { PAUSE_RESUME, PAUSE_RESTART, PAUSE_HELP, PAUSE_QUIT, PAUSE_ROWS };+enum { MENU_CONTINUE, MENU_PLAY, MENU_RECORDS, MENU_HELP };+#define PG_HELP_PAGES 3++typedef struct {+ uint8_t screen, sel, page, under; /* under: where Back goes from how to play */+ uint8_t menu[4], menu_n; /* the title's buttons */+ uint8_t hold; /* a race going on again: 3, 2, 1 */+ uint8_t result_rank, new_best, new_lap, new_far;+ uint32_t clock; /* ms, for what moves on the menus */+ bool save_failed;+} pg_ui;++extern const char *const pg_driver[PG_CARS];+/* the whole screen; race: the race shown (the one going, or the last one) */+void pg_render(const pg_file *f, const pg_track *t, const pg_race *prev, const pg_race *race, int alpha,+ const pg_ui *ui, const rd_ghost *g);+#endifdiff --git a/games/polygt3d/src/game.h b/games/polygt3d/src/game.hnew file mode 100644index 00000000..f0b70f42--- /dev/null+++ b/games/polygt3d/src/game.h@@ -0,0 +1,146 @@+/* PolyGT 3D's rules: the roads (track.c) and the race (race.c), in whole numbers only, so that a race comes out the+ * same on the calculator and on every computer. The picture (render.c) is drawn from them with floats.+ *+ * Distances are in 1/256 metre (FX), speeds in 1/256 metre a second, angles in 1/65536 of a turn; the race moves on+ * in steps of 20 ms. A car is placed along the road (s, from the start line) and across it (x, + to the right), and+ * points at `ang` from the road's direction; the road turns right where its heading grows. */+#ifndef PG_GAME_H+#define PG_GAME_H+#include <stdbool.h>+#include <stdint.h>++#define FX 256+#define PG_TICK 20 /* ms per step */+#define PG_HZ 50+#define PG_CARS 8 /* you and up to seven rivals */+#define PG_CIRCUITS 3+#define PG_VEHICLES 5+#define PG_MAXN 288 /* segments in a circuit, at most */+#define PG_RING 128 /* the endless road: the segments kept around you (a power of two) */+#define PG_SEG (6 * FX) /* the endless road's segments; circuits come close to it */+#define PG_ROAD (8 * FX) /* half the road */+#define PG_KERB (6 * FX / 5)+#define PG_WALL (25 * FX / 2) /* the barriers, either side */+#define PG_HL (22 * FX / 10) /* half a car's length... */+#define PG_HW (115 * FX / 100) /* ...and half its width */+#define PG_ZONE 70 /* the endless road changes scenery every 70 segments (420 m) */+#define PG_ORBS 24 /* nitro orbs on a circuit, at most */+#define PG_MAX_LAPS 9+#define PG_GHOST 480 /* samples of a lap, every 200 ms: 96 seconds */+#define ANG_TURN 65536++enum { MODE_RACE, MODE_ENDLESS };+enum { LEVEL_EASY, LEVEL_NORMAL, LEVEL_HARD };+enum { VIEW_CHASE, VIEW_FAR, VIEW_BUMPER, VIEWS };+enum { PH_GRID, PH_RACE, PH_DONE };+enum { END_NONE, END_FINISH, END_TIME };+enum { IN_GAS = 1, IN_BRAKE = 2, IN_LEFT = 4, IN_RIGHT = 8, IN_NITRO = 16 };+enum { BANNER_NONE, BANNER_LAP, BANNER_FINAL, BANNER_ZONE, BANNER_WRONG };+/* what stands at a segment */+enum { PROP_NONE, PROP_TREE, PROP_ARCH, PROP_GANTRY, PROP_CHEVRON };++/* ------------------------------------------------------------------ fixed-point helpers (track.c) */+int32_t pg_sin(int32_t a); /* 32767 = 1 */+int32_t pg_cos(int32_t a);+int32_t pg_atan2(int32_t y, int32_t x); /* the angle of (x, y), x along 0 */+uint32_t pg_isqrt(uint64_t v);+uint32_t pg_rng(uint32_t *s); /* xorshift32; s must not be 0 */++/* ------------------------------------------------------------------ the roads (track.c) */+typedef struct {+ uint32_t rng;+ int32_t head; /* heading of the segment being laid */+ int32_t turn, turn_to; /* its bend, and the bend it eases into (1/16 angle unit a segment) */+ int32_t slope, slope_to; /* climb a segment (FX) */+ int16_t turn_hold, slope_hold;+ uint8_t zone, spare;+ int32_t count; /* segments laid */+ int32_t x, y, z; /* the end of the road so far */+ int32_t prev_head; /* the heading of the segment before */+} pg_gen;++typedef struct {+ uint8_t endless, id; /* id: the circuit, or the scenery the endless road starts in */+ uint16_t n; /* circuit: segments in a lap */+ int32_t seg; /* a segment's length */+ int32_t length; /* circuit: a lap, n * seg */+ int32_t px[PG_MAXN], py[PG_MAXN], pz[PG_MAXN]; /* where each segment starts (its node) */+ uint16_t nh[PG_MAXN]; /* the road's heading at the node */+ int16_t cv[PG_MAXN]; /* how much it turns over the segment */+ uint8_t limit[PG_MAXN]; /* the fastest a car with grip 1 takes the segment's bend (m/s) */+ uint8_t prop[PG_MAXN]; /* PROP_..., + 8 on the left */+ uint8_t zone[PG_MAXN]; /* the scenery (endless: changes along the road) */+ int8_t orb[PG_MAXN]; /* a nitro orb at the segment's middle: its x in 1/8 metre, or -128 */+ int8_t orb_id[PG_MAXN]; /* circuit: the orb's number, for its cooldown */+ uint8_t orbs; /* circuit: orbs on a lap */+ int32_t first, last; /* endless: the segments kept, by number from the start */+ pg_gen gen;+} pg_track;++extern const char *const pg_circuit_name[PG_CIRCUITS];+extern const char *const pg_circuit_note[PG_CIRCUITS];+extern const char *const pg_zone_name[5];+void pg_build(pg_track *t, int id); /* a circuit */+void pg_endless(pg_track *t, uint32_t seed); /* the endless road, from its start */+void pg_extend(pg_track *t, int32_t upto); /* the endless road laid on to segment `upto` (and kept from+ there back), or nothing for a circuit */+int pg_slot(const pg_track *t, int32_t k); /* the arrays' index of segment k (any lap) */+int32_t pg_seg_of(const pg_track *t, int32_t s); /* the segment number under s (negative too) */+int32_t pg_heading_at(const pg_track *t, int32_t s);+int32_t pg_height_at(const pg_track *t, int32_t s);+void pg_world(const pg_track *t, int32_t s, int32_t x, int32_t *wx, int32_t *wy, int32_t *wz);+int32_t pg_wrap(const pg_track *t, int32_t ds); /* a circuit gap brought within half a lap either way */+int pg_zone_at(const pg_track *t, int32_t s);+int pg_map(const pg_track *t, int n, int16_t *xs, int16_t *ys, int w, int h); /* the outline, fit in w x h */++/* ------------------------------------------------------------------ cars (race.c) */+typedef struct {+ const char *name, *kind;+ uint16_t top; /* top speed, 1/8 m/s */+ uint16_t accel; /* 1/8 m/s^2 */+ uint8_t grip, drift; /* 1/128 */+ uint8_t offroad; /* grass drag, 1/128 */+ uint8_t horse;+ uint16_t redline;+ uint8_t body[3], accent[3];+} pg_vehicle;+extern const pg_vehicle pg_vehicles[PG_VEHICLES];++typedef struct {+ int32_t s, x, v; /* along (unwound: laps add up), across, speed */+ int32_t lane; /* a rival: the x it heads for */+ int16_t ang; /* where it heads, from the road's direction */+ int16_t slip; /* the body turned from where it heads (a slide) */+ int16_t steer; /* -1024..1024 */+ uint16_t nitro; /* 0..1000 */+ uint32_t finish_ms; /* at the line (0: not yet) */+ uint16_t think, aim; /* a rival: steps to its next look ahead, the speed it aims for (FX / 8) */+ uint8_t gear, boost, drift, model, paint, place, bump;+ uint8_t driven; /* by the game: the rivals, and you after the line */+} pg_car;++typedef struct {+ uint8_t mode, track, vehicle, laps, rivals, level, manual, phase;+ uint8_t end, lap, finished, banner, banner_arg, zone, wrong, flash; /* flash: an orb just taken */+ uint16_t countdown, done, banner_t, slipstream;+ uint32_t ticks, time_ms, lap_at, best_lap_ms, last_lap_ms, seed;+ int32_t time_left; /* endless: ms left */+ int32_t last_orb; /* endless: the last orb taken (its segment) */+ uint16_t orb_wait[PG_ORBS]; /* circuit: steps before an orb is back */+ pg_car car[PG_CARS]; /* 0 is you */+} pg_race;++typedef struct {+ uint8_t mode, track, vehicle, laps, rivals, level, manual;+} pg_setup;++void pg_new(pg_race *r, pg_track *t, const pg_setup *s, uint32_t seed);+void pg_step(pg_race *r, pg_track *t, unsigned input, int shift);+bool pg_valid(const pg_race *r, const pg_track *t);+int pg_rank(const pg_race *r, int car); /* 1.. : by finish, then by distance */+int pg_kmh(int32_t v);+int pg_rpm(const pg_race *r);+int32_t pg_lap_s(const pg_race *r, const pg_track *t); /* where you are in the lap (or on the endless road) */+int32_t pg_zone_bonus(int zone); /* ms a zone of the endless road gives */+uint32_t pg_sum(const void *data, uint32_t n);+#endifdiff --git a/games/polygt3d/src/main.c b/games/polygt3d/src/main.cindex 8d6da8b2..85862ceb 100644--- a/games/polygt3d/src/main.c+++ b/games/polygt3d/src/main.c@@ -1,3096 +1,422 @@-#include <eadk.h>-#include <stdbool.h>-#include <stddef.h>-#include <stdint.h>--const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "PolyGT 3D";-const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;--// ============================================================================-// FAST MATH, TRIGONOMETRY & PRNG-// ============================================================================-#define PI_F 3.14159265f-#define TAU_F 6.28318530f--static inline float clampf(float v, float lo, float hi) {- return v < lo ? lo : (v > hi ? hi : v);-}-static inline int clampi(int v, int lo, int hi) {- return v < lo ? lo : (v > hi ? hi : v);-}-static inline float fabsf_fast(float x) { return x < 0.0f ? -x : x; }-static inline float wrap_angle(float x) {- while (x > PI_F) x -= TAU_F;- while (x < -PI_F) x += TAU_F;- return x;-}--static float sinf_fast(float x) {- x = wrap_angle(x);- const float B = 4.0f / PI_F;- const float C = -4.0f / (PI_F * PI_F);- float y = B * x + C * x * fabsf_fast(x);- const float P = 0.225f;- return P * (y * fabsf_fast(y) - y) + y;-}--static float cosf_fast(float x) { return sinf_fast(x + 1.57079632f); }--static float sqrtf_fast(float x) {- if (x <= 0.0f) return 0.0f;-#if defined(__ARM_FP) && PLATFORM_DEVICE- float res;- __asm__("vsqrt.f32 %0, %1" : "=t"(res) : "t"(x));- return res;-#else- union {- float f;- uint32_t i;- } u = {x};- u.i = 0x5f3759df - (u.i >> 1);- float y = u.f;- y = y * (1.5f - 0.5f * x * y * y);- y = y * (1.5f - 0.5f * x * y * y);- return x * y;+/* PolyGT 3D, a low-poly 3D racer for the NumWorks calculator, by Boris-TH, made for NumPlay: three circuits against+ * up to seven rivals, the endless road against the clock, three cars and two horses, nitro orbs, the slipstream and a+ * ghost of your best lap. The rules are in race.c and track.c, the picture in render.c, the screens+ * in draw.c and the save in save.c.+ *+ * Keys: Up accelerates, Down brakes, Left and Right steer, OK (or EXE) burns nitro, + and - change gear with the+ * manual gearbox, Back pauses; Home saves and quits, from anywhere. */+#include <string.h>+#include "draw.h"+#include "game.h"+#include "plat.h"+#include "render.h"+#include "save.h"++static pg_file sv; /* what's kept: your choices and records, the race going on */+static pg_track track; /* the road built (the race's, or the circuit on the race screen) */+static pg_race prev;+static pg_ui ui;+static uint32_t now, saved_at, hold_at;+static int32_t accum;+static int pending_shift;+static int built = -1; /* which road is in `track`: a circuit, or 100: the endless road of seed... */+static uint32_t built_seed; /* ...built_seed */+static uint32_t frame_gap; /* the least ms between frames (the tests draw fewer) */+/* frames drawn, the slowest (ms) and those over 33 ms: read by tools/emu.py */+#ifndef HOST+__attribute__((used, externally_visible))#endif-}--static uint32_t rng_state = 0xCAFEBABEu;-static uint32_t rand_u32(void) {- rng_state ^= rng_state << 13;- rng_state ^= rng_state >> 17;- rng_state ^= rng_state << 5;- return rng_state;-}-static float rand_range(float lo, float hi) {- float t = (float)(rand_u32() & 0xFFFF) * (1.0f / 65535.0f);- return lo + (hi - lo) * t;-}--// ============================================================================-// 3D GRAPHICS ENGINE: TILE-STRIP Z-BUFFER + AFFINE TEXTURES-// ============================================================================-#define SCREEN_W 320-#define SCREEN_H 240-#define STRIP_H 40-#define NUM_STRIPS (SCREEN_H / STRIP_H)-#define MAX_SCREEN_TRIS 720-#define NEAR_Z 1.6f-#define FAR_Z 195.0f--static eadk_color_t fb_strip[SCREEN_W * STRIP_H];-static uint16_t zb_strip[SCREEN_W * STRIP_H];----enum TexType {- TEX_FLAT = 0,- TEX_ASPHALT = 1,- TEX_KERB = 2,- TEX_FINISH = 3,- TEX_GRASS = 4,- TEX_WALL = 5,- TEX_GHOST = 6-};+uint32_t perf_frames, perf_max, perf_slow;+/* ------------------------------------------------------------------ the ghost of your best lap on each circuit+ (kept until you quit): where you were every 200 ms */typedef struct {- float x, y, z;- float u, v;-} Vec3UV;-+ uint16_t s; /* in the lap, 1/8 metre */+ int8_t x, a; /* across, 1/8 metre; heading from the road, 1/256 turn */+} ghost_pt;typedef struct {- int16_t x0, y0, x1, y1, x2, y2;- uint16_t z0, z1, z2;- int16_t u0, v0, u1, v1, u2, v2;- uint8_t r, g, b;- uint8_t tex_id;- int16_t min_y, max_y;-} ScreenTri;--static ScreenTri screen_tris[MAX_SCREEN_TRIS];-static int num_screen_tris = 0;--static int ps1_jitter_shift = 1;--static inline eadk_color_t rgb565(int r, int g, int b) {- return (eadk_color_t)(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3));-}--// Camera state-static float cam_x = 0.0f, cam_y = 2.8f, cam_z = 0.0f;-static float cam_yaw = 0.0f, cam_pitch = -0.08f, cam_roll = 0.0f;-static float cam_cos_yaw, cam_sin_yaw;-static float cam_cos_pitch, cam_sin_pitch;-static float cam_cos_roll, cam_sin_roll;-static float fov_scale = 205.0f;--static uint8_t fog_r = 180, fog_g = 110, fog_b = 140;--static void update_camera_trig(void) {- cam_cos_yaw = cosf_fast(cam_yaw);- cam_sin_yaw = sinf_fast(cam_yaw);- cam_cos_pitch = cosf_fast(cam_pitch);- cam_sin_pitch = sinf_fast(cam_pitch);- cam_cos_roll = cosf_fast(cam_roll);- cam_sin_roll = sinf_fast(cam_roll);-}--static Vec3UV world_to_cam(Vec3UV w) {- float dx = w.x - cam_x;- float dy = w.y - cam_y;- float dz = w.z - cam_z;-- float x1 = dx * cam_cos_yaw - dz * cam_sin_yaw;- float z1 = dx * cam_sin_yaw + dz * cam_cos_yaw;- float y1 = dy;-- float y2 = y1 * cam_cos_pitch - z1 * cam_sin_pitch;- float z2 = y1 * cam_sin_pitch + z1 * cam_cos_pitch;- float x2 = x1;-- float x3 = x2 * cam_cos_roll - y2 * cam_sin_roll;- float y3 = x2 * cam_sin_roll + y2 * cam_cos_roll;-- Vec3UV out = {x3, y3, z2, w.u, w.v};- return out;-}--static void push_projected_tri(Vec3UV c0, Vec3UV c1, Vec3UV c2,- uint8_t r, uint8_t g, uint8_t b, uint8_t tex_id,- bool double_sided) {- if (num_screen_tris >= MAX_SCREEN_TRIS) return;- if (c0.z > FAR_Z && c1.z > FAR_Z && c2.z > FAR_Z) return;-- float inv0 = fov_scale / c0.z;- float inv1 = fov_scale / c1.z;- float inv2 = fov_scale / c2.z;-- int sx0 = (int)(SCREEN_W * 0.5f + c0.x * inv0);- int sy0 = (int)(SCREEN_H * 0.48f - c0.y * inv0);- int sx1 = (int)(SCREEN_W * 0.5f + c1.x * inv1);- int sy1 = (int)(SCREEN_H * 0.48f - c1.y * inv1);- int sx2 = (int)(SCREEN_W * 0.5f + c2.x * inv2);- int sy2 = (int)(SCREEN_H * 0.48f - c2.y * inv2);-- if (ps1_jitter_shift > 0) {- sx0 = (sx0 >> ps1_jitter_shift) << ps1_jitter_shift;- sy0 = (sy0 >> ps1_jitter_shift) << ps1_jitter_shift;- sx1 = (sx1 >> ps1_jitter_shift) << ps1_jitter_shift;- sy1 = (sy1 >> ps1_jitter_shift) << ps1_jitter_shift;- sx2 = (sx2 >> ps1_jitter_shift) << ps1_jitter_shift;- sy2 = (sy2 >> ps1_jitter_shift) << ps1_jitter_shift;- }-- int cross = (sx1 - sx0) * (sy2 - sy0) - (sy1 - sy0) * (sx2 - sx0);- if (!double_sided && cross <= 0) return;- if (cross < 0) {- int tx = sx1; sx1 = sx2; sx2 = tx;- int ty = sy1; sy1 = sy2; sy2 = ty;- Vec3UV tc = c1; c1 = c2; c2 = tc;- }-- int min_x = sx0 < sx1 ? (sx0 < sx2 ? sx0 : sx2) : (sx1 < sx2 ? sx1 : sx2);- int max_x = sx0 > sx1 ? (sx0 > sx2 ? sx0 : sx2) : (sx1 > sx2 ? sx1 : sx2);- int min_y = sy0 < sy1 ? (sy0 < sy2 ? sy0 : sy2) : (sy1 < sy2 ? sy1 : sy2);- int max_y = sy0 > sy1 ? (sy0 > sy2 ? sy0 : sy2) : (sy1 > sy2 ? sy1 : sy2);-- if (max_x < 0 || min_x >= SCREEN_W || max_y < 0 || min_y >= SCREEN_H) return;- if (min_y == max_y || min_x == max_x) return;-- float avg_z = (c0.z + c1.z + c2.z) * 0.3333f;- if (avg_z > 55.0f) {- float fog_t = clampf((avg_z - 55.0f) * (1.0f / (FAR_Z - 55.0f)), 0.0f, 0.88f);- r = (uint8_t)(r + (fog_r - r) * fog_t);- g = (uint8_t)(g + (fog_g - g) * fog_t);- b = (uint8_t)(b + (fog_b - b) * fog_t);+ uint16_t n;+ uint8_t model, on;+ uint32_t ms;+ ghost_pt p[PG_GHOST];+} ghost;+static ghost best_ghost[PG_CIRCUITS], rec;+static bool rec_ok; /* the lap being recorded was driven from its start */+static rd_ghost ghost_now;++static void save(void) {+ ui.save_failed = !save_write(&sv);+ saved_at = now;+}++/* the road for a race, built again when it isn't the one in `track` */+static void show_race(const pg_race *r) {+ if (r->mode == MODE_ENDLESS) {+ if (built != 100 || built_seed != r->seed || !track.endless) {+ pg_endless(&track, r->seed);+ built = 100, built_seed = r->seed;+ }+ pg_extend(&track, pg_seg_of(&track, r->car[0].s) + 48);+ } else if (built != r->track || track.endless) {+ pg_build(&track, r->track);+ built = r->track;+ }+}+static void show_circuit(int id) {+ if (built != id || track.endless) pg_build(&track, id), built = id;+}++static pg_setup setup_of(void) {+ pg_setup s;+ s.mode = sv.p.mode, s.track = sv.p.track, s.vehicle = sv.p.vehicle, s.laps = sv.p.laps, s.rivals = sv.p.rivals;+ s.level = sv.p.level, s.manual = sv.p.manual;+ return s;+}++static void title_menu(void) {+ int n = 0;+ if (sv.has_race) ui.menu[n++] = MENU_CONTINUE;+ ui.menu[n++] = MENU_PLAY, ui.menu[n++] = MENU_RECORDS, ui.menu[n++] = MENU_HELP;+ ui.menu_n = (uint8_t)n;+}+static void to_title(void) {+ ui.screen = V_TITLE, ui.sel = 0;+ title_menu();+}++/* ------------------------------------------------------------------ races */+/* the race screen's choices set to the race just driven (to drive it again) */+static void use_race_settings(void) {+ pg_race *r = &sv.race;+ sv.p.mode = r->mode, sv.p.vehicle = r->vehicle, sv.p.manual = r->manual;+ if (r->mode == MODE_RACE) sv.p.track = r->track, sv.p.laps = r->laps, sv.p.rivals = r->rivals, sv.p.level = r->level;+}++static void race_begin(void) {+ pg_setup s = setup_of();+ pg_new(&sv.race, &track, &s, (plat_random() ^ now) | 1);+ built = s.mode == MODE_ENDLESS ? 100 : s.track, built_seed = sv.race.seed;+ prev = sv.race;+ sv.has_race = 1;+ ui.screen = V_RACE, ui.sel = 0, ui.hold = 0;+ accum = 0, pending_shift = 0;+ rec.n = 0, rec_ok = true;+ save();+}++static void start_or_guide(void) {+ if (!sv.p.guide) {+ ui.screen = V_GUIDE, ui.page = 0;+ return;}-- ScreenTri *t = &screen_tris[num_screen_tris++];- t->x0 = (int16_t)clampi(sx0, -512, 832);- t->y0 = (int16_t)clampi(sy0, -512, 752);- t->x1 = (int16_t)clampi(sx1, -512, 832);- t->y1 = (int16_t)clampi(sy1, -512, 752);- t->x2 = (int16_t)clampi(sx2, -512, 832);- t->y2 = (int16_t)clampi(sy2, -512, 752);-- t->z0 = (uint16_t)clampf(c0.z * 320.0f, 1.0f, 65534.0f);- t->z1 = (uint16_t)clampf(c1.z * 320.0f, 1.0f, 65534.0f);- t->z2 = (uint16_t)clampf(c2.z * 320.0f, 1.0f, 65534.0f);-- t->u0 = (int16_t)(c0.u * 256.0f);- t->v0 = (int16_t)(c0.v * 256.0f);- t->u1 = (int16_t)(c1.u * 256.0f);- t->v1 = (int16_t)(c1.v * 256.0f);- t->u2 = (int16_t)(c2.u * 256.0f);- t->v2 = (int16_t)(c2.v * 256.0f);-- t->r = r;- t->g = g;- t->b = b;- t->tex_id = tex_id;- t->min_y = (int16_t)clampi(min_y, 0, SCREEN_H - 1);- t->max_y = (int16_t)clampi(max_y, 0, SCREEN_H - 1);+ race_begin();}-static inline Vec3UV lerp_v3(Vec3UV a, Vec3UV b, float t) {- Vec3UV o = {- a.x + (b.x - a.x) * t,- a.y + (b.y - a.y) * t,- a.z + (b.z - a.z) * t,- a.u + (b.u - a.u) * t,- a.v + (b.v - a.v) * t,- };- return o;+static void resume_saved(void) {+ show_race(&sv.race);+ prev = sv.race;+ ui.screen = V_RACE, ui.hold = 3, accum = 0, pending_shift = 0;+ hold_at = now + 500;+ rec.n = 0, rec_ok = false;}-static void submit_world_tri(Vec3UV v0, Vec3UV v1, Vec3UV v2,- uint8_t r, uint8_t g, uint8_t b,- uint8_t tex_id, bool double_sided) {- Vec3UV c0 = world_to_cam(v0);- Vec3UV c1 = world_to_cam(v1);- Vec3UV c2 = world_to_cam(v2);-- Vec3UV in_pts[3];- Vec3UV out_pts[3];- int in_n = 0, out_n = 0;-- if (c0.z >= NEAR_Z) in_pts[in_n++] = c0; else out_pts[out_n++] = c0;- if (c1.z >= NEAR_Z) in_pts[in_n++] = c1; else out_pts[out_n++] = c1;- if (c2.z >= NEAR_Z) in_pts[in_n++] = c2; else out_pts[out_n++] = c2;-- if (in_n == 0) return;- if (in_n == 3) {- push_projected_tri(c0, c1, c2, r, g, b, tex_id, double_sided);- } else if (in_n == 1) {- float t0 = (NEAR_Z - in_pts[0].z) / (out_pts[0].z - in_pts[0].z);- float t1 = (NEAR_Z - in_pts[0].z) / (out_pts[1].z - in_pts[0].z);- Vec3UV p1 = lerp_v3(in_pts[0], out_pts[0], t0);- Vec3UV p2 = lerp_v3(in_pts[0], out_pts[1], t1);- push_projected_tri(in_pts[0], p1, p2, r, g, b, tex_id, double_sided);- } else if (in_n == 2) {- float t0 = (NEAR_Z - in_pts[0].z) / (out_pts[0].z - in_pts[0].z);- float t1 = (NEAR_Z - in_pts[1].z) / (out_pts[0].z - in_pts[1].z);- Vec3UV p0 = lerp_v3(in_pts[0], out_pts[0], t0);- Vec3UV p1 = lerp_v3(in_pts[1], out_pts[0], t1);- push_projected_tri(in_pts[0], in_pts[1], p0, r, g, b, tex_id, double_sided);- push_projected_tri(in_pts[1], p1, p0, r, g, b, tex_id, double_sided);+static void finish_race(void) {+ pg_race *r = &sv.race;+ pg_profile *p = &sv.p;+ ui.new_best = ui.new_lap = ui.new_far = 0;+ if (r->mode == MODE_ENDLESS) {+ uint32_t m = (uint32_t)(r->car[0].s / FX);+ if (m > PG_MAX_M) m = PG_MAX_M;+ if (p->runs < 999999) p->runs++;+ if (m > p->best_m) p->best_m = m, p->best_zone = (uint16_t)(r->zone + 1), ui.new_far = 1;+ } else {+ int rank = r->car[0].place ? r->car[0].place : pg_rank(r, 0);+ ui.result_rank = (uint8_t)rank;+ if (p->races < 999999) p->races++;+ if (rank == 1 && r->rivals) p->wins++;+ int id = r->track;+ uint32_t t = r->car[0].finish_ms;+ if (t && t <= PG_MAX_TIME && (!p->best_ms[id] || t < p->best_ms[id])) p->best_ms[id] = t, ui.new_best = 1;+ if (r->best_lap_ms && r->best_lap_ms <= PG_MAX_TIME && (!p->best_lap_ms[id] || r->best_lap_ms < p->best_lap_ms[id]))+ p->best_lap_ms[id] = r->best_lap_ms, ui.new_lap = 1;+ /* (a best race holds a lap at least as good) */+ if (p->best_ms[id] && (!p->best_lap_ms[id] || p->best_lap_ms[id] > p->best_ms[id])) p->best_lap_ms[id] = p->best_ms[id];+ }+ sv.has_race = 0;+ ui.screen = V_RESULT, ui.sel = 0;+ save();+}++/* the ghost: a sample every 200 ms of the lap; at the end of a lap, kept if it's the best on this circuit */+static void ghost_after_step(int lap_before) {+ pg_race *r = &sv.race;+ if (r->mode != MODE_RACE) return;+ ghost *g = &best_ghost[r->track];+ bool lap_done = r->lap != lap_before || (r->phase == PH_DONE && r->end == END_FINISH && r->car[0].driven && rec.n &&+ r->last_lap_ms && r->time_ms - r->lap_at == r->last_lap_ms);+ if (lap_done) {+ if (rec_ok && rec.n > 10 && r->last_lap_ms && (!g->on || r->last_lap_ms < g->ms)) {+ memcpy(g->p, rec.p, sizeof(ghost_pt) * rec.n);+ g->n = rec.n, g->ms = r->last_lap_ms, g->model = r->vehicle, g->on = 1;+ }+ rec.n = 0, rec_ok = r->phase == PH_RACE;+ }+ if (r->phase != PH_RACE || r->car[0].driven) return;+ uint32_t t = r->time_ms - r->lap_at;+ if (t % 200 || t / 200 != rec.n) {+ if (t / 200 > rec.n) rec_ok = false;+ return;}-}--static void submit_world_quad(Vec3UV v0, Vec3UV v1, Vec3UV v2, Vec3UV v3,- uint8_t r, uint8_t g, uint8_t b,- uint8_t tex_id, bool double_sided) {- submit_world_tri(v0, v1, v2, r, g, b, tex_id, double_sided);- submit_world_tri(v0, v2, v3, r, g, b, tex_id, double_sided);-}--static inline void sample_ps1_texture(uint8_t tex_id, int u8, int v8,- int sx, int sy,- uint8_t base_r, uint8_t base_g, uint8_t base_b,- int *out_r, int *out_g, int *out_b, bool *discard) {- *discard = false;- int r = base_r, g = base_g, b = base_b;- int u = (u8 >> 2) & 63;- int v = (v8 >> 2) & 63;-- switch (tex_id) {- case TEX_ASPHALT: {- int grain = (((u * 17) ^ (v * 31)) & 7) - 4;- r += grain * 2;- g += grain * 2;- b += grain * 2;- if (u <= 2 || u >= 61) {- r = 225; g = 225; b = 230;- } else if (u >= 30 && u <= 33 && (v & 32)) {- r = 235; g = 205; b = 70;- }+ if (rec.n >= PG_GHOST) {+ rec_ok = false;+ return;+ }+ const pg_car *c = &r->car[0];+ ghost_pt *q = &rec.p[rec.n++];+ q->s = (uint16_t)(pg_lap_s(r, &track) / 32);+ q->x = (int8_t)(c->x / 32);+ q->a = (int8_t)((c->ang + c->slip) / 256);+}++static void ghost_pose(int alpha) {+ ghost_now.on = false;+ pg_race *r = &sv.race;+ if (r->mode != MODE_RACE || r->phase != PH_RACE || track.endless) return;+ const ghost *g = &best_ghost[r->track];+ if (!g->on) return;+ uint32_t t = r->time_ms - r->lap_at + (uint32_t)(alpha * PG_TICK / 256);+ uint32_t i = t / 200, f = t % 200;+ if (i + 1 >= g->n) return;+ const ghost_pt *a = &g->p[i], *b = &g->p[i + 1];+ int32_t L = track.length, sa = a->s * 32, sb = b->s * 32;+ if (sb - sa < -L / 2) sb += L;+ if (sb - sa > L / 2) sb -= L;+ ghost_now.s = sa + (sb - sa) * (int32_t)f / 200;+ ghost_now.x = (a->x * 32) + (b->x - a->x) * 32 * (int32_t)f / 200;+ ghost_now.ang = a->a * 256 + (int32_t)(int8_t)(b->a - a->a) * 256 * (int32_t)f / 200;+ ghost_now.model = g->model;+ ghost_now.on = true;+}++/* ------------------------------------------------------------------ keys, screen by screen */+static bool row_off(int row) {+ return sv.p.mode == MODE_ENDLESS && (row == SET_TRACK || row == SET_LAPS || row == SET_RIVALS || row == SET_LEVEL);+}++static void set_change(int row, int d) {+ pg_profile *p = &sv.p;+ switch (row) {+ case SET_MODE: p->mode ^= 1; break;+ case SET_TRACK: p->track = (uint8_t)((p->track + PG_CIRCUITS + d) % PG_CIRCUITS); break;+ case SET_CAR: p->vehicle = (uint8_t)((p->vehicle + PG_VEHICLES + d) % PG_VEHICLES); break;+ case SET_LAPS: p->laps = (uint8_t)((p->laps - 1 + PG_MAX_LAPS + d) % PG_MAX_LAPS + 1); break;+ case SET_RIVALS: p->rivals = (uint8_t)((p->rivals + PG_CARS + d) % PG_CARS); break;+ case SET_LEVEL: p->level = (uint8_t)((p->level + 3 + d) % 3); break;+ case SET_GEARS: p->manual ^= 1; break;+ case SET_VIEW: p->view = (uint8_t)((p->view + VIEWS + d) % VIEWS); break;+ }+}++static bool keys_menu(uint32_t hit) {+ int n;+ switch (ui.screen) {+ case V_TITLE:+ n = ui.menu_n;+ if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + n - 1) % n);+ if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % n);+ if (hit & PK_BACK) ui.screen = V_QUIT, ui.sel = 0;+ else if (hit & PK_OK) switch (ui.menu[ui.sel % n]) {+ case MENU_CONTINUE: resume_saved(); break;+ case MENU_PLAY: ui.screen = V_SETUP, ui.sel = SET_START; break;+ case MENU_RECORDS: ui.screen = V_RECORDS; break;+ default: ui.screen = V_HELP, ui.page = 0, ui.under = V_TITLE; break;+ }break;- }- case TEX_KERB: {- int stripe = (v >> 4) & 1;- int bevel = (u < 8 || u > 55) ? -25 : 0;- if (stripe) {- r = base_r + bevel;- g = base_g + bevel;- b = base_b + bevel;- } else {- r = 240 + bevel;- g = 240 + bevel;- b = 245 + bevel;+ case V_QUIT:+ if (hit & (PK_UP | PK_DOWN)) ui.sel ^= 1;+ if (hit & PK_BACK) ui.screen = V_TITLE, ui.sel = 0;+ else if (hit & PK_OK) {+ if (ui.sel) return true;+ ui.screen = V_TITLE, ui.sel = 0;}break;- }- case TEX_FINISH: {- int chk = ((u >> 3) ^ (v >> 3)) & 1;- if (chk) {- r = 245; g = 245; b = 245;- } else {- r = 25; g = 25; b = 30;- }+ case V_SETUP: {+ int d = (hit & PK_DOWN) ? 1 : (hit & PK_UP) ? -1 : 0;+ if (d) {+ do ui.sel = (uint8_t)((ui.sel + SET_ROWS + d) % SET_ROWS);+ while (row_off(ui.sel));+ }+ int dx = (hit & PK_RIGHT) ? 1 : (hit & PK_LEFT) ? -1 : 0;+ if (dx && ui.sel < SET_START) set_change(ui.sel, dx);+ if (hit & PK_BACK) {+ save();+ to_title();+ ui.sel = (uint8_t)(ui.menu_n - 3);+ } else if (hit & PK_OK) {+ if (ui.sel < SET_START) set_change(ui.sel, 1);+ else if (sv.has_race) ui.screen = V_NEWRUN, ui.sel = 0;+ else start_or_guide();+ }+ if (ui.screen == V_SETUP && sv.p.mode == MODE_RACE) show_circuit(sv.p.track);break;}- case TEX_GRASS: {- int chk = ((u >> 4) ^ (v >> 4)) & 1;- int noise = (((u * 13) ^ (v * 29)) & 7) - 3;- if (chk) {- r += 10 + noise; g += 16 + noise; b += 8 + noise;- } else {- r += noise; g += noise; b += noise;- }+ case V_NEWRUN:+ if (hit & (PK_UP | PK_DOWN)) ui.sel ^= 1;+ if ((hit & PK_BACK) || ((hit & PK_OK) && !ui.sel)) ui.screen = V_SETUP, ui.sel = SET_START;+ else if (hit & PK_OK) sv.has_race = 0, start_or_guide();break;- }- case TEX_WALL: {- if (v < 14 && (((u + v) >> 3) & 1)) {- r = 240; g = 180; b = 30;- } else if ((v & 15) == 0 || (u & 31) == 0) {- r -= 22; g -= 22; b -= 22;- }+ case V_GUIDE:+ if ((hit & PK_RIGHT) && ui.page + 1 < PG_HELP_PAGES) ui.page++;+ if ((hit & PK_LEFT) && ui.page) ui.page--;+ if (hit & PK_BACK) ui.screen = V_SETUP, ui.sel = SET_START;+ else if (hit & PK_OK) sv.p.guide = 1, race_begin();break;- }- case TEX_GHOST: {- if ((sx ^ sy) & 1) {- *discard = true;- return;+ case V_HELP:+ if ((hit & PK_RIGHT) && ui.page + 1 < PG_HELP_PAGES) ui.page++;+ if ((hit & PK_LEFT) && ui.page) ui.page--;+ if (hit & (PK_BACK | PK_OK)) {+ if (ui.under == V_PAUSE) ui.screen = V_PAUSE, ui.sel = PAUSE_HELP;+ else to_title(), ui.sel = (uint8_t)(ui.menu_n - 1);}break;- }- default:+ case V_RECORDS:+ if (hit & (PK_BACK | PK_OK)) to_title(), ui.sel = (uint8_t)(ui.menu_n - 2);break;- }-- *out_r = clampi(r, 0, 255);- *out_g = clampi(g, 0, 255);- *out_b = clampi(b, 0, 255);-}--static void rasterize_tri_strip(const ScreenTri *t, int strip_y0) {- int strip_y1 = strip_y0 + STRIP_H - 1;- if (t->max_y < strip_y0 || t->min_y > strip_y1) return;-- int y_start = t->min_y > strip_y0 ? t->min_y : strip_y0;- int y_end = t->max_y < strip_y1 ? t->max_y : strip_y1;-- int x0 = t->x0, y0 = t->y0;- int x1 = t->x1, y1 = t->y1;- int x2 = t->x2, y2 = t->y2;-- int min_x = x0 < x1 ? (x0 < x2 ? x0 : x2) : (x1 < x2 ? x1 : x2);- int max_x = x0 > x1 ? (x0 > x2 ? x0 : x2) : (x1 > x2 ? x1 : x2);- min_x = clampi(min_x, 0, SCREEN_W - 1);- max_x = clampi(max_x, 0, SCREEN_W - 1);-- int area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);- if (area <= 0) return;-- int32_t inv_area = (1 << 20) / area;-- int A01 = y0 - y1, B01 = x1 - x0;- int A12 = y1 - y2, B12 = x2 - x1;- int A20 = y2 - y0, B20 = x0 - x2;-- int w0_row = (min_x - x1) * A12 + (y_start - y1) * B12;- int w1_row = (min_x - x2) * A20 + (y_start - y2) * B20;- int w2_row = (min_x - x0) * A01 + (y_start - y0) * B01;-- int dz1 = (int)t->z1 - (int)t->z0;- int dz2 = (int)t->z2 - (int)t->z0;-- if (t->tex_id == TEX_FLAT) {- eadk_color_t flat_col = rgb565(t->r, t->g, t->b);- for (int y = y_start; y <= y_end; y++) {- int rx0 = min_x, rx1 = max_x;- if (A12 == 0) {- if (w0_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- } else if (A12 > 0) {- if (w0_row < 0) {- int val = min_x + (-w0_row + A12 - 1) / A12;- if (val > rx0) rx0 = val;- }- } else {- if (w0_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- int val = min_x + w0_row / (-A12);- if (val < rx1) rx1 = val;- }-- if (A20 == 0) {- if (w1_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- } else if (A20 > 0) {- if (w1_row < 0) {- int val = min_x + (-w1_row + A20 - 1) / A20;- if (val > rx0) rx0 = val;- }- } else {- if (w1_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- int val = min_x + w1_row / (-A20);- if (val < rx1) rx1 = val;- }-- if (A01 == 0) {- if (w2_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- } else if (A01 > 0) {- if (w2_row < 0) {- int val = min_x + (-w2_row + A01 - 1) / A01;- if (val > rx0) rx0 = val;- }- } else {- if (w2_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- int val = min_x + w2_row / (-A01);- if (val < rx1) rx1 = val;- }-- if (rx0 <= rx1) {- int w1 = w1_row + (rx0 - min_x) * A20;- int w2 = w2_row + (rx0 - min_x) * A01;- int row_offset = (y - strip_y0) * SCREEN_W;- for (int x = rx0; x <= rx1; x++) {- int b1 = (w1 * inv_area) >> 12;- int b2 = (w2 * inv_area) >> 12;- uint16_t z = (uint16_t)((int)t->z0 + ((dz1 * b1 + dz2 * b2) >> 8));- int idx = row_offset + x;- if (z < zb_strip[idx]) {- zb_strip[idx] = z;- fb_strip[idx] = flat_col;- }- w1 += A20;- w2 += A01;- }- }-- w0_row += B12;- w1_row += B20;- w2_row += B01;- }- } else {- int du1 = (int)t->u1 - (int)t->u0;- int du2 = (int)t->u2 - (int)t->u0;- int dv1 = (int)t->v1 - (int)t->v0;- int dv2 = (int)t->v2 - (int)t->v0;-- for (int y = y_start; y <= y_end; y++) {- int rx0 = min_x, rx1 = max_x;- if (A12 == 0) {- if (w0_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- } else if (A12 > 0) {- if (w0_row < 0) {- int val = min_x + (-w0_row + A12 - 1) / A12;- if (val > rx0) rx0 = val;+ case V_PAUSE:+ if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + PAUSE_ROWS - 1) % PAUSE_ROWS);+ if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % PAUSE_ROWS);+ if (hit & PK_BACK) ui.screen = V_RACE;+ else if (hit & PK_OK) switch (ui.sel) {+ case PAUSE_RESUME: ui.screen = V_RACE; break;+ case PAUSE_RESTART: use_race_settings(), race_begin(); break;+ case PAUSE_HELP: ui.screen = V_HELP, ui.page = 0, ui.under = V_PAUSE; break;+ default: ui.screen = V_LEAVE, ui.sel = 0; break;}- } else {- if (w0_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- int val = min_x + w0_row / (-A12);- if (val < rx1) rx1 = val;+ break;+ case V_LEAVE:+ if (hit & PK_UP) ui.sel = (uint8_t)((ui.sel + 2) % 3);+ if (hit & PK_DOWN) ui.sel = (uint8_t)((ui.sel + 1) % 3);+ if (hit & PK_BACK) ui.screen = V_PAUSE, ui.sel = PAUSE_QUIT;+ else if (hit & PK_OK) {+ if (ui.sel == 0) ui.screen = V_RACE;+ else if (ui.sel == 1) save(), to_title();+ else return true;}-- if (A20 == 0) {- if (w1_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- } else if (A20 > 0) {- if (w1_row < 0) {- int val = min_x + (-w1_row + A20 - 1) / A20;- if (val > rx0) rx0 = val;+ break;+ case V_RESULT:+ if (hit & (PK_UP | PK_DOWN)) ui.sel ^= 1;+ if (hit & PK_OK) {+ if (ui.sel == 0) {+ use_race_settings(), race_begin();+ } else {+ to_title();}- } else {- if (w1_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- int val = min_x + w1_row / (-A20);- if (val < rx1) rx1 = val;}-- if (A01 == 0) {- if (w2_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- } else if (A01 > 0) {- if (w2_row < 0) {- int val = min_x + (-w2_row + A01 - 1) / A01;- if (val > rx0) rx0 = val;- }+ break;+ }+ return false;+}++/* ------------------------------------------------------------------ the loop */+static unsigned race_input(uint32_t keys) {+ unsigned in = 0;+ if (keys & PK_UP) in |= IN_GAS;+ if (keys & PK_DOWN) in |= IN_BRAKE;+ if (keys & PK_LEFT) in |= IN_LEFT;+ if (keys & PK_RIGHT) in |= IN_RIGHT;+ if (keys & PK_OK) in |= IN_NITRO;+ return in;+}++static bool race_over(const pg_race *r) {+ return r->phase == PH_DONE && r->done >= (r->mode == MODE_ENDLESS ? 2 * PG_HZ + PG_HZ / 2 : 3 * PG_HZ);+}++int main(void) {+ plat_begin();+ memset(&ui, 0, sizeof ui);+ now = plat_millis();+ save_load(&sv);+ if (sv.has_race) show_race(&sv.race);+ to_title();+ uint32_t stale = plat_keys(), prev_keys = stale, rep_at = 0, last = now, frame_at = 0, spin0 = now;+ uint8_t shown = 0xFF;+ bool dirty = true;+ uint32_t min_frame = frame_gap ? frame_gap : plat_slow() ? 33 : 20;+ for (;;) {+ now = plat_millis();+ uint32_t dt = now - last;+ if (dt > 100) dt = 100;+ last = now;+ uint32_t keys = plat_keys();+ stale &= keys; /* keys still held from the screen before don't count */+ uint32_t live = keys & ~stale, hit = live & ~prev_keys;+ if (ui.screen != V_RACE) { /* in menus, a held arrow repeats */+ uint32_t arrows = live & (PK_UP | PK_DOWN | PK_LEFT | PK_RIGHT);+ if (hit & arrows) rep_at = now + 350;+ else if (arrows && (int32_t)(now - rep_at) >= 0) hit |= arrows, rep_at = now + 110;+ }+ prev_keys = live;+ if (keys & PK_HOME) break; /* Home (or On/Off): saved below, then out */+ if (hit && ui.screen != V_RACE) dirty = true; /* (a race is drawn at its own pace) */+ bool quit = false;+ if (ui.screen == V_RACE) {+ if (hit & PK_BACK) {+ ui.screen = V_PAUSE, ui.sel = PAUSE_RESUME;+ save();+ } else if (ui.hold) {+ if ((int32_t)(now - hold_at) >= 0) ui.hold--, hold_at = now + 500, dirty = true;+ prev = sv.race;} else {- if (w2_row < 0) { w0_row += B12; w1_row += B20; w2_row += B01; continue; }- int val = min_x + w2_row / (-A01);- if (val < rx1) rx1 = val;- }-- if (rx0 <= rx1) {- int w1 = w1_row + (rx0 - min_x) * A20;- int w2 = w2_row + (rx0 - min_x) * A01;- int row_offset = (y - strip_y0) * SCREEN_W;- for (int x = rx0; x <= rx1; x++) {- int b1 = (w1 * inv_area) >> 12;- int b2 = (w2 * inv_area) >> 12;- uint16_t z = (uint16_t)((int)t->z0 + ((dz1 * b1 + dz2 * b2) >> 8));- int idx = row_offset + x;- if (z < zb_strip[idx]) {- int u8 = (int)t->u0 + ((du1 * b1 + du2 * b2) >> 8);- int v8 = (int)t->v0 + ((dv1 * b1 + dv2 * b2) >> 8);- int cr, cg, cb;- bool discard = false;- sample_ps1_texture(t->tex_id, u8, v8, x, y, t->r, t->g, t->b, &cr, &cg, &cb, &discard);- if (!discard) {- zb_strip[idx] = z;- fb_strip[idx] = rgb565(cr, cg, cb);- }+ if (hit & PK_GEAR_UP) pending_shift = 1;+ if (hit & PK_GEAR_DOWN) pending_shift = -1;+ accum += (int32_t)dt;+ unsigned in = race_input(live);+ while (accum >= PG_TICK) {+ prev = sv.race;+ int lap = sv.race.lap;+ pg_step(&sv.race, &track, in, pending_shift);+ pending_shift = 0;+ accum -= PG_TICK;+ ghost_after_step(lap);+ if (race_over(&sv.race)) {+ finish_race();+ break;}- w1 += A20;- w2 += A01;}+ if (ui.screen == V_RACE && (int32_t)(now - saved_at) >= 30000) save();}-- w0_row += B12;- w1_row += B20;- w2_row += B01;- }- }-}--// ============================================================================-// KNOT-FREE CLOSED-LOOP POLAR SPLINE TRACK GENERATOR-// ============================================================================-#define TRACK_N 180-#define ROAD_HALF_W 10.0f--typedef struct {- float x, y, z;- float tx, tz; // Forward unit tangent- float nx, nz; // Right unit normal- float seg_len; // Exact Euclidean distance to next node- float cum_dist; // Cumulative distance from start line- float curv; // Signed angle change at this node- uint8_t prop_type; // 0=none, 1=tree/lamp, 2=arch, 3=gantry, 4=chevron_sign- uint8_t biome_id; // 0..4 terrain biome index (morphs continuously in Infinity Mode!)- int8_t prop_side;- int8_t orb_slot; // 0=none, 1=active orb, >1=respawn cooldown ticks- float orb_offset; // Lateral road offset of the boost orb (-6.5m .. +6.5m)-} TrackNode;--typedef struct {- const char *name;- const char *subtitle;- uint8_t sky_top_r, sky_top_g, sky_top_b;- uint8_t sky_bot_r, sky_bot_g, sky_bot_b;- uint8_t ground_r, ground_g, ground_b;- uint8_t road_r, road_g, road_b;- uint8_t kerb_r, kerb_g, kerb_b;- float grip_mult;-} TrackTheme;--static const TrackTheme themes[3] = {- {- "RIDGE VALLEY GT",- "Sunset High-Speed Circuit",- 35, 25, 85,- 235, 110, 80,- 35, 85, 42,- 62, 64, 72,- 220, 35, 35,- 1.00f- },- {- "NEO-TOKYO WANGAN",- "Midnight Bay Expressway",- 10, 12, 32,- 55, 25, 85,- 22, 24, 34,- 46, 50, 62,- 0, 195, 235,- 1.04f- },- {- "MT. AKAGI TOUGE",- "Dusk Mountain Drift Pass",- 45, 35, 60,- 165, 130, 145,- 48, 62, 42,- 58, 56, 60,- 230, 165, 20,- 0.92f- }-};--#define NUM_INF_BIOMES 5-#define INF_BIOME_SEGS 45-#define INF_SEG_LEN 9.5f--static const TrackTheme infinity_biomes[NUM_INF_BIOMES] = {- {- "ZONE: ALPINE VALLEY",- "Rolling Forest Highway",- 25, 60, 140,- 130, 190, 245,- 34, 98, 44,- 62, 65, 72,- 225, 40, 40,- 1.00f- },- {- "ZONE: SUNSET CANYON",- "Red-Gold Desert Dunes",- 55, 20, 75,- 245, 115, 50,- 180, 98, 46,- 74, 62, 56,- 240, 185, 25,- 0.98f- },- {- "ZONE: NEON WANGAN",- "Midnight Cyber Expressway",- 10, 12, 34,- 70, 25, 105,- 20, 26, 42,- 44, 48, 60,- 0, 215, 255,- 1.04f- },- {- "ZONE: GLACIER PASS",- "Icy Alpine Mountain Peaks",- 38, 82, 150,- 185, 225, 250,- 198, 215, 232,- 68, 76, 92,- 35, 115, 240,- 0.93f- },- {- "ZONE: VOLCANIC ASH",- "Molten Dusk Caldera",- 36, 16, 38,- 215, 65, 35,- 44, 36, 38,- 48, 44, 46,- 255, 95, 15,- 0.96f- }-};--static TrackNode track_nodes[TRACK_N];-static float track_total_length = 1200.0f;-static int current_track_id = 0;-static uint32_t current_track_seed = 101;-static float map_cx = 0.0f, map_cz = 0.0f, map_scale = 0.14f;--// Streaming Endless Procedural Highway state for Infinity Mode-static uint32_t inf_gen_count = 0;-static int inf_head_seg = 0;-static float inf_yaw = 0.0f;-static float inf_curv = 0.0f;-static float inf_target_curv = 0.0f;-static int inf_curve_hold = 0;-static float inf_pitch_slope = 0.0f;-static float inf_target_slope = 0.0f;-static int inf_slope_hold = 0;-static uint8_t inf_current_biome = 0;--// Generates one new procedural road segment at the horizon frontier in Infinity Mode!-// Continuously varies road curvature, elevation hills/valleys, props, and terrain biomes.-static void append_infinity_segment(void) {- int cur_idx = inf_head_seg;- int next_idx = (cur_idx + 1) % TRACK_N;- TrackNode *cn = &track_nodes[cur_idx];- TrackNode *nn = &track_nodes[next_idx];-- // Switch to a new distinct terrain biome every INF_BIOME_SEGS segments (~425m)!- if (inf_gen_count > 0 && (inf_gen_count % INF_BIOME_SEGS) == 0) {- uint8_t step = 1 + (uint8_t)(rand_u32() % (NUM_INF_BIOMES - 1));- inf_current_biome = (inf_current_biome + step) % NUM_INF_BIOMES;- }- cn->biome_id = inf_current_biome;-- // Update procedural horizontal curvature (sweeping corners, S-bends, hairpins, and straights)- if (inf_curve_hold <= 0) {- uint32_t r = rand_u32() & 7;- if (r < 2) {- inf_target_curv = 0.0f; // High-speed straightaway- inf_curve_hold = 10 + (int)(rand_u32() % 14);- } else {- // Biome-specific corner sharpness, strictly bounded so road never folds or inverts!- float max_c = (inf_current_biome == 3 || inf_current_biome == 4) ? 0.046f : 0.038f;- float mag = rand_range(0.016f, max_c);- inf_target_curv = ((rand_u32() & 1) ? mag : -mag);- inf_curve_hold = 12 + (int)(rand_u32() % 18);- }- }- inf_curve_hold--;- inf_curv += (inf_target_curv - inf_curv) * 0.18f;- inf_curv = clampf(inf_curv, -0.046f, 0.046f);-- // Update procedural vertical terrain elevation (hills, canyon dips, mountain climbs!)- if (inf_slope_hold <= 0) {- // Glacier Pass & Volcanic Ash have steeper mountain climbs/descents; Neon Wangan is flatter- float max_sl = (inf_current_biome == 3) ? 0.95f- : ((inf_current_biome == 4 || inf_current_biome == 1) ? 0.78f- : ((inf_current_biome == 2) ? 0.28f : 0.55f));- inf_target_slope = rand_range(-max_sl, max_sl);- inf_slope_hold = 10 + (int)(rand_u32() % 16);- }- inf_slope_hold--;- inf_pitch_slope += (inf_target_slope - inf_pitch_slope) * 0.16f;-- // Advance heading and compute unit tangent & right normal- inf_yaw = wrap_angle(inf_yaw + inf_curv);- float tx = sinf_fast(inf_yaw);- float tz = cosf_fast(inf_yaw);- cn->tx = tx;- cn->tz = tz;- cn->nx = tz;- cn->nz = -tx;- cn->seg_len = INF_SEG_LEN;- cn->curv = inf_curv;-- // Place next frontier vertex in 3D space- nn->x = cn->x + tx * INF_SEG_LEN;- nn->y = cn->y + inf_pitch_slope;- nn->z = cn->z + tz * INF_SEG_LEN;- nn->cum_dist = cn->cum_dist + INF_SEG_LEN;- nn->tx = tx;- nn->tz = tz;- nn->nx = tz;- nn->nz = -tx;- nn->seg_len = INF_SEG_LEN;- nn->curv = inf_curv;- nn->biome_id = inf_current_biome;- nn->prop_type = 0;- nn->orb_slot = 0;-- // Roadside props tailored to the terrain & biome transitions- cn->prop_type = 0;- cn->prop_side = (inf_gen_count & 1) ? 1 : -1;- if ((inf_gen_count % INF_BIOME_SEGS) == 0 && inf_gen_count > 0) {- cn->prop_type = 2; // Biome Transition Gate Arch!- } else if (inf_current_biome == 2 && (inf_gen_count % 3) == 0) {- cn->prop_type = 3; // Cyber Highway Overhead Light Gantry Pillars- } else if (fabsf_fast(cn->curv) > 0.028f && (inf_gen_count % 2) == 0) {- cn->prop_type = 4; // Turn Chevron Sign on outside of curve- cn->prop_side = (cn->curv > 0.0f) ? -1 : 1;- } else if ((inf_gen_count % 3) == 0) {- cn->prop_type = 1; // Biome Tree / Desert Pillar / Snow Pine / Streetlamp- }-- // Spawn glowing 3D Boost Orbs along the endless road (every 12 segments)- if (inf_gen_count >= 6 && (inf_gen_count % 12) == 6) {- cn->orb_slot = 1;- if (fabsf_fast(cn->curv) > 0.022f) {- cn->orb_offset = (cn->curv > 0.0f) ? 4.0f : -4.0f;} else {- cn->orb_offset = rand_range(-5.0f, 5.0f);- }- } else {- cn->orb_slot = 0;- cn->orb_offset = 0.0f;- }-- inf_head_seg = next_idx;- inf_gen_count++;-}--static void update_infinity_minimap_bounds(int center_seg) {- float min_x = 1e9f, max_x = -1e9f, min_z = 1e9f, max_z = -1e9f;- for (int s = -8; s <= 36; s++) {- int idx = (center_seg + s + TRACK_N) % TRACK_N;- float x = track_nodes[idx].x;- float z = track_nodes[idx].z;- if (x < min_x) min_x = x;- if (x > max_x) max_x = x;- if (z < min_z) min_z = z;- if (z > max_z) max_z = z;- }- map_cx = (min_x + max_x) * 0.5f;- map_cz = (min_z + max_z) * 0.5f;- float span = (max_x - min_x) > (max_z - min_z) ? (max_x - min_x) : (max_z - min_z);- map_scale = (span > 1.0f) ? (42.0f / span) : 0.14f;-}--static void init_infinity_road(uint32_t seed) {- rng_state = seed ^ 0xA5A5F00Du;- for (int k = 0; k < 4; k++) rand_u32();-- inf_gen_count = 0;- inf_head_seg = 0;- inf_yaw = 0.0f;- inf_curv = 0.0f;- inf_target_curv = 0.0f;- inf_curve_hold = 8;- inf_pitch_slope = 0.0f;- inf_target_slope = 0.0f;- inf_slope_hold = 6;- inf_current_biome = (uint8_t)(current_track_id % NUM_INF_BIOMES);-- track_nodes[0].x = 0.0f;- track_nodes[0].y = 0.0f;- track_nodes[0].z = 0.0f;- track_nodes[0].cum_dist = 0.0f;- track_nodes[0].biome_id = inf_current_biome;-- // Pre-generate 60 segments ahead so the horizon is completely filled- for (int i = 0; i < 60; i++) {- append_infinity_segment();- }- update_infinity_minimap_bounds(2);-}--// Generates a 100% non-self-intersecting closed loop in polar coordinates,-// then smooths and resamples it so there are ZERO knots or upside-down flips!-static void build_track_seeded(int track_id, uint32_t seed) {- current_track_id = track_id;- current_track_seed = seed;- rng_state = seed ^ 0x9E3779B9u ^ ((uint32_t)track_id * 0x45D9F3Bu);- for (int k = 0; k < 5; k++) rand_u32();-- const TrackTheme *th = &themes[track_id];- fog_r = th->sky_bot_r;- fog_g = th->sky_bot_g;- fog_b = th->sky_bot_b;-- // Randomized Fourier harmonics for radius R(theta): strictly positive (R > 110m)- // so the loop can NEVER cross itself or pinch into a knot!- float base_r = 185.0f;- float a2 = rand_range(-38.0f, 38.0f);- float p2 = rand_range(0.0f, TAU_F);- float a3 = rand_range(-28.0f, 28.0f);- float p3 = rand_range(0.0f, TAU_F);- float a4 = rand_range(-16.0f, 16.0f);- float p4 = rand_range(0.0f, TAU_F);- float aspect_x = rand_range(0.82f, 1.22f);- float aspect_z = rand_range(0.82f, 1.22f);-- float h_amp1 = rand_range(3.5f, 6.5f);- float h_amp2 = rand_range(2.0f, 4.5f);- float h_phase = rand_range(0.0f, TAU_F);-- for (int i = 0; i < TRACK_N; i++) {- float theta = (float)i / (float)TRACK_N * TAU_F;- float r = base_r +- a2 * cosf_fast(2.0f * theta + p2) +- a3 * sinf_fast(3.0f * theta + p3) +- a4 * cosf_fast(4.0f * theta + p4);- // Flatten section around theta == 0 into a clean start/finish straightaway- track_nodes[i].x = -r * cosf_fast(theta) * aspect_x;- track_nodes[i].z = r * sinf_fast(theta) * aspect_z;- track_nodes[i].y = h_amp1 * sinf_fast(theta + h_phase) + h_amp2 * cosf_fast(2.0f * theta);- }-- // Smooth the closed polygon (4-pass Laplacian filter) to guarantee large minimum turn radius- // so inner kerbs and grass shoulders NEVER overlap or invert!- for (int pass = 0; pass < 4; pass++) {- float prev_x = track_nodes[TRACK_N - 1].x;- float prev_y = track_nodes[TRACK_N - 1].y;- float prev_z = track_nodes[TRACK_N - 1].z;- float first_x = track_nodes[0].x;- float first_y = track_nodes[0].y;- float first_z = track_nodes[0].z;- for (int i = 0; i < TRACK_N; i++) {- int nxt = (i + 1) % TRACK_N;- float nx_x = (nxt == 0) ? first_x : track_nodes[nxt].x;- float nx_y = (nxt == 0) ? first_y : track_nodes[nxt].y;- float nx_z = (nxt == 0) ? first_z : track_nodes[nxt].z;- float cur_x = track_nodes[i].x;- float cur_y = track_nodes[i].y;- float cur_z = track_nodes[i].z;- track_nodes[i].x = 0.25f * prev_x + 0.50f * cur_x + 0.25f * nx_x;- track_nodes[i].y = 0.25f * prev_y + 0.50f * cur_y + 0.25f * nx_y;- track_nodes[i].z = 0.25f * prev_z + 0.50f * cur_z + 0.25f * nx_z;- prev_x = cur_x;- prev_y = cur_y;- prev_z = cur_z;- }- }-- // Shift origin so node 0 is at (0, 0, 0) and compute mini-map bounds- float ox = track_nodes[0].x, oy = track_nodes[0].y, oz = track_nodes[0].z;- float min_x = 1e9f, max_x = -1e9f, min_z = 1e9f, max_z = -1e9f;- for (int i = 0; i < TRACK_N; i++) {- track_nodes[i].x -= ox;- track_nodes[i].y -= oy;- track_nodes[i].z -= oz;- if (track_nodes[i].x < min_x) min_x = track_nodes[i].x;- if (track_nodes[i].x > max_x) max_x = track_nodes[i].x;- if (track_nodes[i].z < min_z) min_z = track_nodes[i].z;- if (track_nodes[i].z > max_z) max_z = track_nodes[i].z;- }- map_cx = (min_x + max_x) * 0.5f;- map_cz = (min_z + max_z) * 0.5f;- float span = (max_x - min_x) > (max_z - min_z) ? (max_x - min_x) : (max_z - min_z);- map_scale = (span > 1.0f) ? (42.0f / span) : 0.14f;-- // Compute exact tangents, normals, segment lengths, cumulative distances, and props- float cum = 0.0f;- int gantry_start = 50 + (int)(rand_u32() % 65);- for (int i = 0; i < TRACK_N; i++) {- int next = (i + 1) % TRACK_N;- float dx = track_nodes[next].x - track_nodes[i].x;- float dz = track_nodes[next].z - track_nodes[i].z;- float len = sqrtf_fast(dx * dx + dz * dz);- if (len < 0.1f) len = 0.1f;-- track_nodes[i].tx = dx / len;- track_nodes[i].tz = dz / len;- track_nodes[i].nx = track_nodes[i].tz;- track_nodes[i].nz = -track_nodes[i].tx;- track_nodes[i].seg_len = len;- track_nodes[i].cum_dist = cum;- track_nodes[i].biome_id = (uint8_t)track_id;- cum += len;- }- track_total_length = cum;-- for (int i = 0; i < TRACK_N; i++) {- int next = (i + 1) % TRACK_N;- track_nodes[i].curv = track_nodes[next].tx * track_nodes[i].tz -- track_nodes[next].tz * track_nodes[i].tx;- track_nodes[i].prop_type = 0;- track_nodes[i].prop_side = (i & 1) ? 1 : -1;-- if (i == 0 || i == TRACK_N / 3 || i == (2 * TRACK_N) / 3) {- track_nodes[i].prop_type = 2; // Start/Finish or Sector Arch- } else if (i >= gantry_start && i <= gantry_start + 12 && (i % 2 == 0)) {- track_nodes[i].prop_type = 3; // Overhead Highway Light Gantry Pillars (no solid roof slab!)- } else if (fabsf_fast(track_nodes[i].curv) > 0.045f && (i % 2 == 0)) {- track_nodes[i].prop_type = 4; // Turn Chevron Sign on outside of curve- track_nodes[i].prop_side = (track_nodes[i].curv > 0.0f) ? -1 : 1;- } else if ((i % 4) == 0) {- track_nodes[i].prop_type = 1; // Tree or Streetlamp- }-- // Spawn rarer glowing 3D Boost Orbs on the road (every 15 segments)- if (i >= 8 && (i % 15) == 8) {- track_nodes[i].orb_slot = 1; // Boost Orb- if (fabsf_fast(track_nodes[i].curv) > 0.025f) {- track_nodes[i].orb_offset = (track_nodes[i].curv > 0.0f) ? 4.2f : -4.2f;- } else {- track_nodes[i].orb_offset = rand_range(-5.0f, 5.0f);- }+ quit = keys_menu(hit);+ }+ if (quit) break;+ if (ui.screen != shown) {+ stale = keys, prev_keys = 0; /* a new screen starts with all keys up */+ if (ui.screen != V_RACE) accum = 0;+ if (ui.screen == V_SETUP && sv.p.mode == MODE_RACE) show_circuit(sv.p.track);+ if (ui.screen == V_RACE || ui.screen == V_PAUSE || ui.screen == V_RESULT) show_race(&sv.race);+ shown = ui.screen;+ dirty = true;+ }+ bool moving = ui.screen == V_RACE || ui.screen == V_TITLE || ui.screen == V_QUIT;+ if (dirty || (moving && now - frame_at >= min_frame)) {+ uint32_t t0 = plat_millis();+ ui.clock = now - spin0;+ int alpha = accum >= PG_TICK ? 256 : accum * 256 / PG_TICK;+ if (ui.screen != V_RACE || ui.hold) alpha = 256;+ ghost_pose(alpha);+ plat_vblank();+ pg_render(&sv, &track, &prev, &sv.race, alpha, &ui, &ghost_now);+ uint32_t spent = plat_millis() - t0;+ perf_frames++;+ if (spent > perf_max) perf_max = spent;+ if (spent > 33) perf_slow++;+ frame_at = now;+ dirty = false;} else {- track_nodes[i].orb_slot = 0;- track_nodes[i].orb_offset = 0.0f;- }- }-}--// ============================================================================-// CAR SPECS & LOW-POLY 3D CAR MESH RENDERER-// ============================================================================-typedef struct {- const char *name;- const char *drivetrain;- uint8_t body_r, body_g, body_b;- uint8_t accent_r, accent_g, accent_b;- float max_speed;- float accel_force;- float grip_lat;- float drift_ease;- int redline_rpm;-} CarSpec;--#define NUM_CARS 5--static const CarSpec car_specs[NUM_CARS] = {- {- "RX-79 APEX GT",- "RWD / TWIN-TURBO",- 225, 32, 42,- 245, 190, 40,- 79.0f, 38.0f, 1.00f, 1.15f, 8500- },- {- "NSX-R PROTO",- "MR / NA VTEC",- 240, 240, 245,- 220, 30, 35,- 82.0f, 36.5f, 1.16f, 0.90f, 9000- },- {- "EVO-IV RALLY",- "AWD / TURBO",- 35, 105, 230,- 245, 205, 45,- 76.5f, 43.0f, 1.10f, 1.05f, 7800- },- {- "BLACK STALLION",- "4-HOOF / GALLOP",- 24, 24, 32,- 255, 45, 35,- 84.5f, 44.0f, 1.18f, 1.08f, 9200- },- {- "BROWN MUSTANG",- "4-HOOF / GALLOP",- 148, 84, 42,- 225, 175, 55,- 82.5f, 42.5f, 1.20f, 1.05f, 8800- }-};--static const uint8_t npc_colors[8][3] = {- {245, 195, 25},- { 30, 205, 95},- {175, 55, 235},- {245, 110, 25},- { 50, 195, 240},- {215, 215, 225},- {235, 45, 135},- { 40, 85, 220}-};--typedef struct {- float x, y, z;- float cos_y, sin_y;- float roll, pitch;- float steer_angle;-} CarPose;--static Vec3UV car_local_to_world(const CarPose *p, float lx, float ly, float lz, float u, float v) {- float rx = lx - ly * p->roll;- float ry = ly + lx * p->roll + lz * p->pitch;- float rz = lz - ly * p->pitch;-- float wx = p->x + rx * p->cos_y + rz * p->sin_y;- float wy = p->y + ry;- float wz = p->z - rx * p->sin_y + rz * p->cos_y;-- Vec3UV out = {wx, wy, wz, u, v};- return out;-}--static uint32_t frame_counter;-static float player_speed;--static void draw_3d_horse(const CarPose *pose, bool is_brown, bool braking, bool shift_flame, bool is_ghost) {- uint8_t tex = is_ghost ? TEX_GHOST : TEX_FLAT;-- // Coat colors: Obsidian Black Stallion vs Classic Warm Chestnut/Bay Brown Mustang- uint8_t c_top_r = is_ghost ? 70 : (is_brown ? 168 : 38);- uint8_t c_top_g = is_ghost ? 220 : (is_brown ? 98 : 38);- uint8_t c_top_b = is_ghost ? 250 : (is_brown ? 50 : 48);-- uint8_t c_side_r = is_ghost ? 55 : (is_brown ? 140 : 24);- uint8_t c_side_g = is_ghost ? 185 : (is_brown ? 78 : 24);- uint8_t c_side_b = is_ghost ? 225 : (is_brown ? 38 : 32);-- uint8_t c_dark_r = is_ghost ? 40 : (is_brown ? 96 : 14);- uint8_t c_dark_g = is_ghost ? 140 : (is_brown ? 52 : 14);- uint8_t c_dark_b = is_ghost ? 180 : (is_brown ? 24 : 20);-- // Dark espresso/black mane & tail for both horses- uint8_t c_mane_r = is_ghost ? 90 : (is_brown ? 36 : 10);- uint8_t c_mane_g = is_ghost ? 240 : (is_brown ? 22 : 10);- uint8_t c_mane_b = is_ghost ? 255 : (is_brown ? 14 : 14);-- // Gallop animation phase- float phase = (float)frame_counter * 0.42f + (pose->x + pose->z) * 0.18f;- float bob = 0.06f * fabsf_fast(sinf_fast(phase));- float head_turn = clampf(pose->steer_angle * 0.45f, -0.45f, 0.45f);-- if (!is_ghost) {- Vec3UV s0 = car_local_to_world(pose, -0.60f, 0.04f, -1.85f, 0, 0);- Vec3UV s1 = car_local_to_world(pose, 0.60f, 0.04f, -1.85f, 1, 0);- Vec3UV s2 = car_local_to_world(pose, 0.60f, 0.04f, 1.85f, 1, 1);- Vec3UV s3 = car_local_to_world(pose, -0.60f, 0.04f, 1.85f, 0, 1);- submit_world_quad(s0, s1, s2, s3, 14, 14, 20, TEX_FLAT, true);- }-- // Sleek, narrow equine torso (Barrel, Haunches & Chest)- float by0 = 0.86f + bob;- float by1 = 1.44f + bob;- Vec3UV r_bl = car_local_to_world(pose, -0.42f, by0, -1.38f, 0, 0);- Vec3UV r_br = car_local_to_world(pose, 0.42f, by0, -1.38f, 1, 0);- Vec3UV r_tl = car_local_to_world(pose, -0.38f, by1, -1.28f, 0, 1);- Vec3UV r_tr = car_local_to_world(pose, 0.38f, by1, -1.28f, 1, 1);-- Vec3UV m_bl = car_local_to_world(pose, -0.46f, by0 - 0.04f, 0.05f, 0, 0);- Vec3UV m_br = car_local_to_world(pose, 0.46f, by0 - 0.04f, 0.05f, 1, 0);- Vec3UV m_tl = car_local_to_world(pose, -0.40f, by1 + 0.02f, 0.08f, 0, 1);- Vec3UV m_tr = car_local_to_world(pose, 0.40f, by1 + 0.02f, 0.08f, 1, 1);-- Vec3UV f_bl = car_local_to_world(pose, -0.42f, by0, 1.25f, 0, 0);- Vec3UV f_br = car_local_to_world(pose, 0.42f, by0, 1.25f, 1, 0);- Vec3UV f_tl = car_local_to_world(pose, -0.36f, by1 + 0.08f, 1.18f, 0, 1);- Vec3UV f_tr = car_local_to_world(pose, 0.36f, by1 + 0.08f, 1.18f, 1, 1);-- // Back, flanks, chest, and rump- submit_world_quad(r_bl, r_br, r_tr, r_tl, c_dark_r, c_dark_g, c_dark_b, tex, true);- submit_world_quad(r_tl, r_tr, m_tr, m_tl, c_top_r, c_top_g, c_top_b, tex, true);- submit_world_quad(m_tl, m_tr, f_tr, f_tl, c_top_r, c_top_g, c_top_b, tex, true);- submit_world_quad(f_tl, f_tr, f_br, f_bl, c_side_r, c_side_g, c_side_b, tex, true);-- submit_world_quad(r_bl, m_bl, m_tl, r_tl, c_side_r, c_side_g, c_side_b, tex, true);- submit_world_quad(m_bl, f_bl, f_tl, m_tl, c_side_r, c_side_g, c_side_b, tex, true);- submit_world_quad(m_br, r_br, r_tr, m_tr, c_side_r, c_side_g, c_side_b, tex, true);- submit_world_quad(f_br, m_br, m_tr, f_tr, c_side_r, c_side_g, c_side_b, tex, true);-- // Saddle on the horse's back- if (!is_ghost) {- uint8_t sr = is_brown ? 75 : 185;- uint8_t sg = is_brown ? 42 : 28;- uint8_t sb = is_brown ? 20 : 35;- Vec3UV sd_rl = car_local_to_world(pose, -0.42f, by1 + 0.04f, -0.48f, 0, 0);- Vec3UV sd_rr = car_local_to_world(pose, 0.42f, by1 + 0.04f, -0.48f, 1, 0);- Vec3UV sd_fl = car_local_to_world(pose, -0.42f, by1 + 0.05f, 0.42f, 0, 1);- Vec3UV sd_fr = car_local_to_world(pose, 0.42f, by1 + 0.05f, 0.42f, 1, 1);- submit_world_quad(sd_rl, sd_rr, sd_fr, sd_fl, sr, sg, sb, TEX_FLAT, true);- }-- // Arched Neck & Head (steers with player input!)- float nx_top = head_turn * 0.32f;- Vec3UV n_bl = car_local_to_world(pose, -0.22f, by1 - 0.06f, 0.88f, 0, 0);- Vec3UV n_br = car_local_to_world(pose, 0.22f, by1 - 0.06f, 0.88f, 1, 0);- Vec3UV n_fl = car_local_to_world(pose, -0.20f, by1 - 0.18f, 1.34f, 0, 0);- Vec3UV n_fr = car_local_to_world(pose, 0.20f, by1 - 0.18f, 1.34f, 1, 0);-- Vec3UV h_bl = car_local_to_world(pose, nx_top - 0.18f, by1 + 0.76f, 1.38f, 0, 1);- Vec3UV h_br = car_local_to_world(pose, nx_top + 0.18f, by1 + 0.76f, 1.38f, 1, 1);- Vec3UV h_fl = car_local_to_world(pose, nx_top - 0.16f, by1 + 0.52f, 1.72f, 0, 1);- Vec3UV h_fr = car_local_to_world(pose, nx_top + 0.16f, by1 + 0.52f, 1.72f, 1, 1);-- submit_world_quad(n_bl, n_br, h_br, h_bl, c_top_r, c_top_g, c_top_b, tex, true);- submit_world_quad(n_fl, n_bl, h_bl, h_fl, c_side_r, c_side_g, c_side_b, tex, true);- submit_world_quad(n_br, n_fr, h_fr, h_br, c_side_r, c_side_g, c_side_b, tex, true);- submit_world_quad(n_fl, n_fr, h_fr, h_fl, c_dark_r, c_dark_g, c_dark_b, tex, true);-- // Flowing Mane Ridge along the neck- Vec3UV mn_b = car_local_to_world(pose, 0.0f, by1 + 0.06f, 0.65f, 0, 0);- Vec3UV mn_m = car_local_to_world(pose, nx_top * 0.5f, by1 + 0.52f, 0.95f, 1, 0);- Vec3UV mn_t = car_local_to_world(pose, nx_top, by1 + 0.86f, 1.35f, 0, 1);- submit_world_tri(mn_b, mn_m, mn_t, c_mane_r, c_mane_g, c_mane_b, tex, true);-- // Sculpted Snout / Muzzle- float sx_tip = head_turn * 0.52f;- Vec3UV sn_tl = car_local_to_world(pose, sx_tip - 0.12f, by1 + 0.45f, 2.18f, 0, 0);- Vec3UV sn_tr = car_local_to_world(pose, sx_tip + 0.12f, by1 + 0.45f, 2.18f, 1, 0);- Vec3UV sn_bl = car_local_to_world(pose, sx_tip - 0.11f, by1 + 0.25f, 2.10f, 0, 1);- Vec3UV sn_br = car_local_to_world(pose, sx_tip + 0.11f, by1 + 0.25f, 2.10f, 1, 1);-- // White blaze on forehead/snout for the Brown Mustang!- uint8_t st_r = (is_brown && !is_ghost) ? 235 : c_top_r;- uint8_t st_g = (is_brown && !is_ghost) ? 230 : c_top_g;- uint8_t st_b = (is_brown && !is_ghost) ? 220 : c_top_b;- submit_world_quad(h_bl, h_br, sn_tr, sn_tl, st_r, st_g, st_b, tex, true);- submit_world_quad(h_fl, h_bl, sn_tl, sn_bl, c_side_r, c_side_g, c_side_b, tex, true);- submit_world_quad(h_br, h_fr, sn_br, sn_tr, c_side_r, c_side_g, c_side_b, tex, true);- submit_world_quad(sn_tl, sn_tr, sn_br, sn_bl, c_dark_r, c_dark_g, c_dark_b, tex, true);-- // Pointed Ears & Eyes- Vec3UV el0 = car_local_to_world(pose, nx_top - 0.18f, by1 + 0.74f, 1.40f, 0, 0);- Vec3UV el1 = car_local_to_world(pose, nx_top - 0.08f, by1 + 0.74f, 1.46f, 1, 0);- Vec3UV el2 = car_local_to_world(pose, nx_top - 0.14f, by1 + 1.02f, 1.36f, 0, 1);- submit_world_tri(el0, el1, el2, c_side_r, c_side_g, c_side_b, tex, true);-- Vec3UV er0 = car_local_to_world(pose, nx_top + 0.08f, by1 + 0.74f, 1.46f, 0, 0);- Vec3UV er1 = car_local_to_world(pose, nx_top + 0.18f, by1 + 0.74f, 1.40f, 1, 0);- Vec3UV er2 = car_local_to_world(pose, nx_top + 0.14f, by1 + 1.02f, 1.36f, 0, 1);- submit_world_tri(er0, er1, er2, c_side_r, c_side_g, c_side_b, tex, true);-- if (!is_ghost) {- uint8_t ey_r = is_brown ? 245 : 255;- uint8_t ey_g = is_brown ? 195 : 40;- uint8_t ey_b = is_brown ? 60 : 30;- Vec3UV eyl0 = car_local_to_world(pose, nx_top - 0.19f, by1 + 0.64f, 1.58f, 0, 0);- Vec3UV eyl1 = car_local_to_world(pose, nx_top - 0.19f, by1 + 0.70f, 1.72f, 1, 0);- Vec3UV eyl2 = car_local_to_world(pose, nx_top - 0.17f, by1 + 0.59f, 1.74f, 0, 1);- submit_world_tri(eyl0, eyl1, eyl2, ey_r, ey_g, ey_b, TEX_FLAT, true);-- Vec3UV eyr0 = car_local_to_world(pose, nx_top + 0.19f, by1 + 0.64f, 1.58f, 0, 0);- Vec3UV eyr1 = car_local_to_world(pose, nx_top + 0.19f, by1 + 0.70f, 1.72f, 1, 0);- Vec3UV eyr2 = car_local_to_world(pose, nx_top + 0.17f, by1 + 0.59f, 1.74f, 0, 1);- submit_world_tri(eyr0, eyr1, eyr2, ey_r, ey_g, ey_b, TEX_FLAT, true);- }-- // Flowing Tail (billows dynamically in the wind!)- float tail_sway = sinf_fast(phase * 1.3f) * 0.20f - head_turn * 0.25f;- float tail_lift = shift_flame ? 0.32f : 0.0f;- Vec3UV t_top_l = car_local_to_world(pose, -0.14f, by1 - 0.06f, -1.34f, 0, 0);- Vec3UV t_top_r = car_local_to_world(pose, 0.14f, by1 - 0.06f, -1.34f, 1, 0);- Vec3UV t_mid_l = car_local_to_world(pose, tail_sway - 0.22f, 0.85f + tail_lift, -1.85f, 0, 1);- Vec3UV t_mid_r = car_local_to_world(pose, tail_sway + 0.22f, 0.85f + tail_lift, -1.85f, 1, 1);- Vec3UV t_tip = car_local_to_world(pose, tail_sway * 1.3f, 0.32f + tail_lift, -2.20f, 0, 1);- submit_world_quad(t_top_l, t_top_r, t_mid_r, t_mid_l, c_mane_r, c_mane_g, c_mane_b, tex, true);- submit_world_tri(t_mid_l, t_mid_r, t_tip, c_mane_r, c_mane_g, c_mane_b, tex, true);-- // 4 Animated Galloping Slender Legs + Hooves- const float lx[4] = {-0.32f, 0.32f, -0.30f, 0.30f};- const float lz[4] = {-1.10f, -1.10f, 1.02f, 1.02f};- const float l_phase[4] = {0.0f, 2.7f, 1.4f, 4.1f};-- for (int l = 0; l < 4; l++) {- float p_ang = phase + l_phase[l];- float swing = sinf_fast(p_ang) * 0.52f;- float lift = clampf(cosf_fast(p_ang) * 0.28f, 0.0f, 0.30f);-- float top_x = lx[l];- float top_z = lz[l];- float bot_z = lz[l] + swing;- float bot_y = 0.04f + lift;-- Vec3UV l_tl = car_local_to_world(pose, top_x - 0.09f, by0 + 0.08f, top_z - 0.10f, 0, 0);- Vec3UV l_tr = car_local_to_world(pose, top_x + 0.09f, by0 + 0.08f, top_z + 0.10f, 1, 0);- Vec3UV l_br = car_local_to_world(pose, top_x + 0.07f, bot_y, bot_z + 0.08f, 1, 1);- Vec3UV l_bl = car_local_to_world(pose, top_x - 0.07f, bot_y, bot_z - 0.08f, 0, 1);- submit_world_quad(l_tl, l_tr, l_br, l_bl, c_dark_r, c_dark_g, c_dark_b, tex, true);-- // Side thickness of leg + hoof- Vec3UV ls_t0 = car_local_to_world(pose, top_x, by0 + 0.08f, top_z - 0.12f, 0, 0);- Vec3UV ls_t1 = car_local_to_world(pose, top_x, by0 + 0.08f, top_z + 0.12f, 1, 0);- Vec3UV ls_b1 = car_local_to_world(pose, top_x, bot_y, bot_z + 0.10f, 1, 1);- Vec3UV ls_b0 = car_local_to_world(pose, top_x, bot_y, bot_z - 0.10f, 0, 1);- submit_world_quad(ls_t0, ls_t1, ls_b1, ls_b0, c_side_r, c_side_g, c_side_b, tex, true);-- if (!is_ghost) {- uint8_t hr = braking ? 255 : (shift_flame ? 40 : (is_brown ? 225 : 195));- uint8_t hg = braking ? 55 : (shift_flame ? 235 : (is_brown ? 215 : 165));- uint8_t hb = braking ? 35 : (shift_flame ? 255 : (is_brown ? 195 : 90));- Vec3UV hf0 = car_local_to_world(pose, top_x - 0.10f, bot_y, bot_z - 0.11f, 0, 0);- Vec3UV hf1 = car_local_to_world(pose, top_x + 0.10f, bot_y, bot_z - 0.11f, 1, 0);- Vec3UV hf2 = car_local_to_world(pose, top_x + 0.10f, bot_y + 0.16f, bot_z + 0.11f, 1, 1);- Vec3UV hf3 = car_local_to_world(pose, top_x - 0.10f, bot_y + 0.16f, bot_z + 0.11f, 0, 1);- submit_world_quad(hf0, hf1, hf2, hf3, hr, hg, hb, TEX_FLAT, true);- }- }-}--static void draw_3d_car_colored(const CarPose *pose, int car_id,- uint8_t br, uint8_t bg, uint8_t bb,- bool braking, bool shift_flame, bool is_ghost) {- int cid = car_id % NUM_CARS;- if (cid == 3 || cid == 4) {- draw_3d_horse(pose, cid == 4, braking, shift_flame, is_ghost);- return;- }- const CarSpec *cs = &car_specs[cid];- uint8_t tex = is_ghost ? TEX_GHOST : TEX_FLAT;-- if (is_ghost) {- br = 70; bg = 220; bb = 250;- }-- uint8_t dr = (br * 3) >> 2;- uint8_t dg = (bg * 3) >> 2;- uint8_t db = (bb * 3) >> 2;-- uint8_t sr = (br * 5) >> 3;- uint8_t sg = (bg * 5) >> 3;- uint8_t sb = (bb * 5) >> 3;-- if (!is_ghost) {- Vec3UV s0 = car_local_to_world(pose, -1.28f, 0.04f, -2.35f, 0, 0);- Vec3UV s1 = car_local_to_world(pose, 1.28f, 0.04f, -2.35f, 1, 0);- Vec3UV s2 = car_local_to_world(pose, 1.28f, 0.04f, 2.35f, 1, 1);- Vec3UV s3 = car_local_to_world(pose, -1.28f, 0.04f, 2.35f, 0, 1);- submit_world_quad(s0, s1, s2, s3, 18, 18, 24, TEX_FLAT, true);- }-- Vec3UV r_bot_l = car_local_to_world(pose, -1.15f, 0.28f, -2.20f, 0, 0);- Vec3UV r_bot_r = car_local_to_world(pose, 1.15f, 0.28f, -2.20f, 1, 0);- Vec3UV r_top_l = car_local_to_world(pose, -1.08f, 0.82f, -2.12f, 0, 1);- Vec3UV r_top_r = car_local_to_world(pose, 1.08f, 0.82f, -2.12f, 1, 1);-- Vec3UV m_bot_l = car_local_to_world(pose, -1.20f, 0.24f, 0.20f, 0, 0);- Vec3UV m_bot_r = car_local_to_world(pose, 1.20f, 0.24f, 0.20f, 1, 0);- Vec3UV m_top_l = car_local_to_world(pose, -1.12f, 0.80f, 0.55f, 0, 1);- Vec3UV m_top_r = car_local_to_world(pose, 1.12f, 0.80f, 0.55f, 1, 1);-- Vec3UV f_bot_l = car_local_to_world(pose, -1.10f, 0.24f, 2.25f, 0, 0);- Vec3UV f_bot_r = car_local_to_world(pose, 1.10f, 0.24f, 2.25f, 1, 0);- Vec3UV f_top_l = car_local_to_world(pose, -1.02f, 0.64f, 2.15f, 0, 1);- Vec3UV f_top_r = car_local_to_world(pose, 1.02f, 0.64f, 2.15f, 1, 1);-- Vec3UV d_rear_l = car_local_to_world(pose, -1.04f, 0.84f, -1.30f, 0, 0);- Vec3UV d_rear_r = car_local_to_world(pose, 1.04f, 0.84f, -1.30f, 1, 0);-- float roof_h = ((car_id % NUM_CARS) == 1) ? 1.18f : (((car_id % NUM_CARS) == 2) ? 1.32f : 1.24f);- Vec3UV c_rear_l = car_local_to_world(pose, -0.82f, roof_h, -0.95f, 0, 0);- Vec3UV c_rear_r = car_local_to_world(pose, 0.82f, roof_h, -0.95f, 1, 0);- Vec3UV c_frnt_l = car_local_to_world(pose, -0.78f, roof_h - 0.04f, 0.15f, 0, 1);- Vec3UV c_frnt_r = car_local_to_world(pose, 0.78f, roof_h - 0.04f, 0.15f, 1, 1);-- submit_world_quad(r_bot_l, r_bot_r, r_top_r, r_top_l, dr, dg, db, tex, true);- submit_world_quad(r_top_l, r_top_r, d_rear_r, d_rear_l, br, bg, bb, tex, true);-- uint8_t gr = is_ghost ? 60 : 32;- uint8_t gg = is_ghost ? 180 : 48;- uint8_t gb = is_ghost ? 220 : 75;- submit_world_quad(d_rear_l, d_rear_r, c_rear_r, c_rear_l, gr, gg, gb, tex, true);-- uint8_t rfr = ((car_id % NUM_CARS) == 1 && !is_ghost) ? 30 : br;- uint8_t rfg = ((car_id % NUM_CARS) == 1 && !is_ghost) ? 32 : bg;- uint8_t rfb = ((car_id % NUM_CARS) == 1 && !is_ghost) ? 40 : bb;- submit_world_quad(c_rear_l, c_rear_r, c_frnt_r, c_frnt_l, rfr, rfg, rfb, tex, true);-- submit_world_quad(c_frnt_l, c_frnt_r, m_top_r, m_top_l, gr + 10, gg + 15, gb + 20, tex, true);- submit_world_quad(m_top_l, m_top_r, f_top_r, f_top_l, br, bg, bb, tex, true);- submit_world_quad(f_top_l, f_top_r, f_bot_r, f_bot_l, dr, dg, db, tex, true);-- submit_world_quad(r_bot_l, m_bot_l, m_top_l, r_top_l, sr, sg, sb, tex, true);- submit_world_quad(m_bot_l, f_bot_l, f_top_l, m_top_l, sr, sg, sb, tex, true);- submit_world_quad(d_rear_l, m_top_l, c_frnt_l, c_rear_l, gr, gg, gb, tex, true);-- submit_world_quad(m_bot_r, r_bot_r, r_top_r, m_top_r, sr, sg, sb, tex, true);- submit_world_quad(f_bot_r, m_bot_r, m_top_r, f_top_r, sr, sg, sb, tex, true);- submit_world_quad(m_top_r, d_rear_r, c_rear_r, c_frnt_r, gr, gg, gb, tex, true);-- Vec3UV w_l0 = car_local_to_world(pose, -1.14f, 1.08f, -2.08f, 0, 0);- Vec3UV w_r0 = car_local_to_world(pose, 1.14f, 1.08f, -2.08f, 1, 0);- Vec3UV w_r1 = car_local_to_world(pose, 1.14f, 1.02f, -1.78f, 1, 1);- Vec3UV w_l1 = car_local_to_world(pose, -1.14f, 1.02f, -1.78f, 0, 1);- submit_world_quad(w_l0, w_r0, w_r1, w_l1, is_ghost ? 90 : 35, is_ghost ? 230 : 35, is_ghost ? 255 : 42, tex, true);-- if (!is_ghost) {- uint8_t tl_r = braking ? 255 : 185;- uint8_t tl_g = braking ? 55 : 15;- uint8_t tl_b = braking ? 40 : 20;-- Vec3UV tl_l0 = car_local_to_world(pose, -1.02f, 0.56f, -2.23f, 0, 0);- Vec3UV tl_l1 = car_local_to_world(pose, -0.42f, 0.56f, -2.23f, 1, 0);- Vec3UV tl_l2 = car_local_to_world(pose, -0.42f, 0.74f, -2.18f, 1, 1);- Vec3UV tl_l3 = car_local_to_world(pose, -1.02f, 0.74f, -2.18f, 0, 1);- submit_world_quad(tl_l0, tl_l1, tl_l2, tl_l3, tl_r, tl_g, tl_b, TEX_FLAT, true);-- Vec3UV tl_r0 = car_local_to_world(pose, 0.42f, 0.56f, -2.23f, 0, 0);- Vec3UV tl_r1 = car_local_to_world(pose, 1.02f, 0.56f, -2.23f, 1, 0);- Vec3UV tl_r2 = car_local_to_world(pose, 1.02f, 0.74f, -2.18f, 1, 1);- Vec3UV tl_r3 = car_local_to_world(pose, 0.42f, 0.74f, -2.18f, 0, 1);- submit_world_quad(tl_r0, tl_r1, tl_r2, tl_r3, tl_r, tl_g, tl_b, TEX_FLAT, true);-- Vec3UV pl0 = car_local_to_world(pose, -0.24f, 0.36f, -2.23f, 0, 0);- Vec3UV pl1 = car_local_to_world(pose, 0.24f, 0.36f, -2.23f, 1, 0);- Vec3UV pl2 = car_local_to_world(pose, 0.24f, 0.54f, -2.21f, 1, 1);- Vec3UV pl3 = car_local_to_world(pose, -0.24f, 0.54f, -2.21f, 0, 1);- submit_world_quad(pl0, pl1, pl2, pl3, cs->accent_r, cs->accent_g, cs->accent_b, TEX_FLAT, true);-- if (shift_flame) {- Vec3UV ex0 = car_local_to_world(pose, -0.68f, 0.28f, -2.24f, 0, 0);- Vec3UV ex1 = car_local_to_world(pose, -0.44f, 0.28f, -2.24f, 1, 0);- Vec3UV ex2 = car_local_to_world(pose, -0.56f, 0.34f, -2.95f, 0, 1);- submit_world_tri(ex0, ex1, ex2, 255, 195, 40, TEX_FLAT, true);- }-- const float wx[4] = {-1.18f, 1.18f, -1.16f, 1.16f};- const float wz[4] = {-1.38f, -1.38f, 1.38f, 1.38f};- for (int w = 0; w < 4; w++) {- float x_in = wx[w] > 0 ? wx[w] - 0.22f : wx[w] + 0.22f;- float x_out = wx[w];- Vec3UV w0 = car_local_to_world(pose, x_in, 0.05f, wz[w] - 0.36f, 0, 0);- Vec3UV w1 = car_local_to_world(pose, x_out, 0.05f, wz[w] - 0.36f, 1, 0);- Vec3UV w2 = car_local_to_world(pose, x_out, 0.58f, wz[w] - 0.36f, 1, 1);- Vec3UV w3 = car_local_to_world(pose, x_in, 0.58f, wz[w] - 0.36f, 0, 1);- submit_world_quad(w0, w1, w2, w3, 24, 24, 28, TEX_FLAT, true);-- Vec3UV s0 = car_local_to_world(pose, x_out, 0.08f, wz[w] - 0.34f, 0, 0);- Vec3UV s1 = car_local_to_world(pose, x_out, 0.08f, wz[w] + 0.34f, 1, 0);- Vec3UV s2 = car_local_to_world(pose, x_out, 0.56f, wz[w] + 0.34f, 1, 1);- Vec3UV s3 = car_local_to_world(pose, x_out, 0.56f, wz[w] - 0.34f, 0, 1);- submit_world_quad(s0, s1, s2, s3, cs->accent_r >> 1, cs->accent_g >> 1, cs->accent_b >> 1, TEX_FLAT, true);- }- }-}--static void draw_3d_car(const CarPose *pose, int car_id, bool braking, bool shift_flame, bool is_ghost) {- const CarSpec *cs = &car_specs[car_id % NUM_CARS];- draw_3d_car_colored(pose, car_id, cs->body_r, cs->body_g, cs->body_b, braking, shift_flame, is_ghost);-}--// ============================================================================-// TRUE 3D WORLD-SPACE CAR PHYSICS (ZERO AUTO-STEER / ZERO STATIC PULL!)-// ============================================================================-#define GHOST_SAMPLES 600-#define MAX_NPCS 7--typedef struct {- int16_t wx_dm;- int16_t wy_dm;- int16_t wz_dm;- int16_t yaw_mrad;- uint8_t seg_idx;-} GhostFrame;--typedef struct {- int seg_idx;- float seg_frac;- int lap;- float total_dist;- float offset;- float target_offset;- float speed;- float max_speed;- float wx, wy, wz;- float sin_y, cos_y;- float boost_fuel;- uint8_t car_model;- uint8_t color_idx;- bool braking;- bool boosting;-} NpcCar;--static GhostFrame best_ghost[GHOST_SAMPLES];-static GhostFrame curr_ghost[GHOST_SAMPLES];-static bool has_best_ghost[3] = {false, false, false};-static uint32_t best_lap_ms[3] = {0, 0, 0};-static uint32_t best_sector_ms[3][3] = {{0}};--static bool infinity_mode = false;-static int race_total_laps = 3;-static int race_npc_count = 5;-static int saved_race_laps = 3;-static int saved_npc_count = 5;-static NpcCar npcs[MAX_NPCS];-static int player_position = 1;-static int final_finish_position = 1;-static bool race_finished = false;-static uint32_t total_race_ms = 0;-static uint32_t race_start_ms = 0;-static bool slipstreaming = false;-static float player_boost_fuel = 30.0f;-static bool player_boosting = false;-static int orb_pickup_flash = 0;--// Player TRUE 3D World-Space state-static int selected_car_id = 0;-static float player_wx = 0.0f, player_wy = 0.0f, player_wz = 0.0f;-static float player_cos_yaw = 1.0f, player_sin_yaw = 0.0f;-static int player_seg = 0;-static int player_laps_done = 0;-static float player_offset = 0.0f;-static float player_dist = 0.0f;-static float player_total_dist = 0.0f;-static float player_speed = 0.0f;-static float player_drift = 0.0f;-static float player_steer = 0.0f;-static float player_yaw_rate = 0.0f;-static float body_roll = 0.0f;-static float body_pitch = 0.0f;--static int current_gear = 1;-static bool manual_trans = false;-static int engine_rpm = 1200;-static int shift_flame_timer = 0;-static int cam_mode = 0;--static int current_lap = 1;-static int current_sector = 0;-static uint32_t lap_start_ms = 0;-static uint32_t last_lap_ms = 0;-static int32_t split_delta_ms = 0;-static int split_popup_timer = 0;-static uint32_t frame_counter = 0;--static const float gear_ratios[6] = {3.45f, 2.35f, 1.72f, 1.34f, 1.08f, 0.88f};-static const float gear_top_spd[6] = {22.0f, 35.0f, 48.0f, 60.0f, 71.0f, 84.0f};--static void update_npc_world_pos(NpcCar *ai) {- const TrackNode *n0 = &track_nodes[ai->seg_idx];- const TrackNode *n1 = &track_nodes[(ai->seg_idx + 1) % TRACK_N];- float bx = n0->x + (n1->x - n0->x) * ai->seg_frac;- float by = n0->y + (n1->y - n0->y) * ai->seg_frac;- float bz = n0->z + (n1->z - n0->z) * ai->seg_frac;- ai->wx = bx + n0->nx * ai->offset;- ai->wy = by;- ai->wz = bz + n0->nz * ai->offset;- ai->sin_y = n0->tx;- ai->cos_y = n0->tz;-}--static void reset_race_state(uint32_t now_ms) {- if (infinity_mode) {- race_npc_count = 0;- init_infinity_road(current_track_seed);- player_seg = 2;- } else {- if (inf_gen_count > 0) {- build_track_seeded(current_track_id, current_track_seed);- inf_gen_count = 0;- }- player_seg = 1;- }- player_laps_done = 0;- player_offset = (race_npc_count > 0) ? -3.0f : 0.0f;- const TrackNode *n = &track_nodes[player_seg];- player_wx = n->x + n->nx * player_offset;- player_wy = n->y;- player_wz = n->z + n->nz * player_offset;- // Point player car straight along the starting grid tangent- player_sin_yaw = n->tx;- player_cos_yaw = n->tz;-- player_dist = n->cum_dist;- player_total_dist = 0.0f;- player_speed = 0.0f;- player_drift = 0.0f;- player_steer = 0.0f;- player_yaw_rate = 0.0f;- cam_sin_yaw = player_sin_yaw;- cam_cos_yaw = player_cos_yaw;- body_roll = 0.0f;- body_pitch = 0.0f;- current_gear = 1;- engine_rpm = 1200;- shift_flame_timer = 0;- current_lap = 1;- current_sector = 0;- lap_start_ms = now_ms;- race_start_ms = now_ms;- last_lap_ms = 0;- total_race_ms = 0;- split_delta_ms = 0;- split_popup_timer = 0;- race_finished = false;- slipstreaming = false;- player_boost_fuel = infinity_mode ? 100.0f : 30.0f;- player_boosting = false;- orb_pickup_flash = 0;-- for (int i = 0; i < TRACK_N; i++) {- if (track_nodes[i].orb_slot > 1) track_nodes[i].orb_slot = 1;- }-- for (int i = 0; i < race_npc_count; i++) {- npcs[i].seg_idx = 3 + i * 2;- npcs[i].seg_frac = 0.0f;- npcs[i].lap = 0;- npcs[i].offset = (i & 1) ? 3.0f : -3.0f;- npcs[i].target_offset = npcs[i].offset;- npcs[i].speed = 0.0f;- npcs[i].max_speed = 60.0f + (float)i * 2.4f;- npcs[i].boost_fuel = 25.0f;- npcs[i].car_model = (uint8_t)((i + 1) % 3);- npcs[i].color_idx = (uint8_t)(i % 8);- npcs[i].braking = false;- npcs[i].boosting = false;- npcs[i].total_dist = track_nodes[npcs[i].seg_idx].cum_dist;- update_npc_world_pos(&npcs[i]);- }- player_position = race_npc_count + 1;- final_finish_position = player_position;-}--static void step_npcs_and_collisions(float dt) {- slipstreaming = false;-- // Tick Boost Orb respawn timers- if ((frame_counter & 3) == 0) {- for (int i = 0; i < TRACK_N; i++) {- if (track_nodes[i].orb_slot > 1) {- track_nodes[i].orb_slot--;- }- }- }-- for (int i = 0; i < race_npc_count; i++) {- NpcCar *ai = &npcs[i];- int s0 = ai->seg_idx;- int s_look = (s0 + 4) % TRACK_N;- float curv_ahead = track_nodes[s_look].curv;- float corner_sev = fabsf_fast(track_nodes[s0].curv) + fabsf_fast(curv_ahead) * 1.4f;-- // Check if this NPC is the current race leader (1st place)- bool ai_is_leader = (ai->total_dist > player_total_dist);- for (int j = 0; j < race_npc_count && ai_is_leader; j++) {- if (j != i && npcs[j].total_dist > ai->total_dist) ai_is_leader = false;- }-- // NPC Boost activation: fire nitro on straights when fuel >= 32%, or sustain until depleted!- if (!ai->boosting) {- if (ai->boost_fuel >= 32.0f && corner_sev < 0.045f && ai->speed > 38.0f) {- ai->boosting = true;- }- } else {- if (ai->boost_fuel <= 0.0f || corner_sev > 0.085f) {- ai->boosting = false;- }- }-- float boost_top_bonus = 0.0f;- float boost_accel_bonus = 0.0f;- if (ai->boosting && ai->boost_fuel > 0.0f) {- // Leader burns boost 1.75x faster too!- float burn_rate = ai_is_leader ? 44.0f : 25.0f;- ai->boost_fuel = clampf(ai->boost_fuel - burn_rate * dt, 0.0f, 100.0f);- boost_top_bonus = 10.5f;- boost_accel_bonus = 22.0f;- }-- float target_spd = (ai->max_speed + boost_top_bonus) *- clampf(1.06f - corner_sev * 2.8f, 0.50f, 1.0f);-- ai->braking = (!ai->boosting && ai->speed > target_spd + 3.5f);- if (ai->braking) {- ai->speed -= 35.0f * dt;- } else if (ai->speed < target_spd) {- ai->speed += (28.0f + boost_accel_bonus) * dt;- }-- float gap = ai->total_dist - player_total_dist;- if (gap > 150.0f) ai->speed *= (1.0f - 0.12f * dt);- else if (gap < -120.0f) ai->speed += 8.0f * dt;- ai->speed = clampf(ai->speed, 12.0f, ai->max_speed + boost_top_bonus + 4.0f);-- // Balanced AI Steering & Partial Boost Orb Seeking:- // Bots check 1..5 segments ahead for an active Boost Orb (~50% chance if within 5.2m laterally).- bool seeking_orb = false;- if (ai->boost_fuel < 85.0f) {- for (int look = 1; look <= 5; look++) {- int so = (s0 + look) % TRACK_N;- if (track_nodes[so].orb_slot == 1) {- float orb_off = track_nodes[so].orb_offset;- float lat_diff = fabsf_fast(orb_off - ai->offset);- int decision_hash = (so * 7 + i * 13 + ai->lap * 5) & 7;- if (lat_diff < 5.2f && decision_hash < 4) {- ai->target_offset = ai->offset * 0.25f + orb_off * 0.75f;- seeking_orb = true;- }- break;- }- }- }-- if (!seeking_orb) {- if (fabsf_fast(curv_ahead) > 0.03f) {- ai->target_offset = (curv_ahead > 0.0f) ? 4.5f : -4.5f;- } else if (((frame_counter + i * 19) & 63) == 0) {- ai->target_offset = rand_range(-5.0f, 5.0f);- }- }-- ai->offset += clampf((ai->target_offset - ai->offset) * 1.9f, -6.2f, 6.2f) * dt;- ai->offset = clampf(ai->offset, -(ROAD_HALF_W - 1.5f), ROAD_HALF_W - 1.5f);-- float move_d = ai->speed * dt;- while (move_d > 0.0f) {- float seg_l = track_nodes[ai->seg_idx].seg_len;- float rem = (1.0f - ai->seg_frac) * seg_l;- if (move_d < rem) {- ai->seg_frac += move_d / seg_l;- move_d = 0.0f;- } else {- move_d -= rem;- ai->seg_frac = 0.0f;- ai->seg_idx++;- if (ai->seg_idx >= TRACK_N) {- ai->seg_idx = 0;- ai->lap++;- }- // Check if NPC collected a Boost Orb on the segment it just entered- if (track_nodes[ai->seg_idx].orb_slot == 1 &&- fabsf_fast(ai->offset - track_nodes[ai->seg_idx].orb_offset) < 2.5f) {- track_nodes[ai->seg_idx].orb_slot = 55; // Longer respawn cooldown (rarer!)- ai->boost_fuel = clampf(ai->boost_fuel + (ai_is_leader ? 18.0f : 30.0f), 0.0f, 100.0f);- }- }- }- ai->total_dist = (float)ai->lap * track_total_length +- track_nodes[ai->seg_idx].cum_dist +- ai->seg_frac * track_nodes[ai->seg_idx].seg_len;- update_npc_world_pos(ai);-- // True 3D World-Space Collision & Slipstream Check with Player!- float dx = ai->wx - player_wx;- float dz = ai->wz - player_wz;- float dist_sq = dx * dx + dz * dz;-- // Project relative vector onto player's forward & right axes- float rel_fwd = dx * player_sin_yaw + dz * player_cos_yaw;- float rel_right = dx * player_cos_yaw - dz * player_sin_yaw;-- if (rel_fwd > 4.5f && rel_fwd < 22.0f && fabsf_fast(rel_right) < 1.9f && player_speed > 30.0f) {- slipstreaming = true;- }-- if (dist_sq < 14.5f && fabsf_fast(rel_fwd) < 4.2f && fabsf_fast(rel_right) < 2.2f) {- if (fabsf_fast(rel_fwd) > fabsf_fast(rel_right) * 1.4f) {- if (rel_fwd > 0.0f && player_speed > ai->speed) {- float avg = (player_speed + ai->speed) * 0.5f;- player_speed = avg * 0.90f;- ai->speed = avg * 1.08f;- player_wx -= player_sin_yaw * 0.4f;- player_wz -= player_cos_yaw * 0.4f;- body_pitch = -0.06f;- }- } else {- float push = (rel_right >= 0.0f) ? -0.55f : 0.55f;- player_wx += player_cos_yaw * push;- player_wz -= player_sin_yaw * push;- ai->offset -= push;- body_roll = push * 0.22f;- }- }- }-- int pos = 1;- for (int i = 0; i < race_npc_count; i++) {- if (npcs[i].total_dist > player_total_dist) pos++;- }- player_position = pos;-}--static void step_physics(float dt, bool key_L, bool key_R, bool key_gas,- bool key_brake, bool key_ebrake, bool key_boost,- bool shift_up_pressed, bool shift_dn_pressed,- uint32_t now_ms) {- if (race_finished) return;- const CarSpec *cs = &car_specs[selected_car_id];- const TrackTheme *th = infinity_mode- ? &infinity_biomes[track_nodes[player_seg].biome_id % NUM_INF_BIOMES]- : &themes[current_track_id];-- // 1. Direct Player Steering Input (fast & snappy response)- if (key_L) {- player_steer = clampf(player_steer - 5.5f * dt, -1.0f, 1.0f);- } else if (key_R) {- player_steer = clampf(player_steer + 5.5f * dt, -1.0f, 1.0f);- } else {- player_steer *= 0.72f;- if (fabsf_fast(player_steer) < 0.02f) player_steer = 0.0f;- }-- // 2. Gearbox, RPM & Position-Scaled Boost Burn Simulation- // If you are in 1st place in front of everyone, boost burns 1.85x faster so you can't hoard & runaway!- player_boosting = (key_boost && player_boost_fuel > 0.5f);- if (player_boosting) {- float burn_rate = (player_position == 1 && race_npc_count > 0) ? 45.0f : 24.0f;- player_boost_fuel = clampf(player_boost_fuel - burn_rate * dt, 0.0f, 100.0f);- shift_flame_timer = 2;- }- if (orb_pickup_flash > 0) orb_pickup_flash--;-- float boost_top_bonus = player_boosting ? 13.5f : 0.0f;- float gear_max = gear_top_spd[current_gear - 1] * ((cs->max_speed + boost_top_bonus) / 80.0f);- float rpm_norm = player_speed / gear_max;- engine_rpm = 1250 + (int)(rpm_norm * (cs->redline_rpm - 1250));-- if (!manual_trans) {- if (engine_rpm > cs->redline_rpm - 250 && current_gear < 6) {- current_gear++;- shift_flame_timer = 5;- } else if (engine_rpm < 3600 && current_gear > 1 && player_speed < gear_top_spd[current_gear - 2] * 0.85f) {- current_gear--;- }- } else {- if (shift_up_pressed && current_gear < 6) {- current_gear++;- shift_flame_timer = 6;- }- if (shift_dn_pressed && current_gear > 1) {- current_gear--;- shift_flame_timer = 5;- }- }-- if (engine_rpm > cs->redline_rpm + 200) {- engine_rpm = cs->redline_rpm - 150;- shift_flame_timer = 3;- }- if (shift_flame_timer > 0) shift_flame_timer--;-- // 3. Longitudinal Forces- float torque_curve = 0.72f + 0.35f * sinf_fast(clampf(rpm_norm, 0.1f, 1.05f) * 2.4f);- float gear_pull = gear_ratios[current_gear - 1] * 0.48f;- float accel = 0.0f;-- if ((key_gas || player_boosting) && player_speed < gear_max * 1.05f) {- accel += cs->accel_force * torque_curve * clampf(gear_pull, 0.52f, 1.35f);- if (slipstreaming) accel += 10.5f;- if (player_boosting) accel += 32.0f;- }- if (key_brake) accel -= 62.0f;- if (key_ebrake) accel -= 28.0f;-- float drag = 0.0065f * player_speed * player_speed + 2.1f;- float drift_scrub = fabsf_fast(player_drift) * player_speed * 0.30f;-- float abs_off = fabsf_fast(player_offset);- bool on_kerb = (abs_off > ROAD_HALF_W - 1.1f && abs_off < ROAD_HALF_W + 1.2f);- bool off_road = (abs_off >= ROAD_HALF_W + 1.2f);- if (off_road) {- drag += player_speed * (selected_car_id == 2 ? 0.55f : 1.10f) + 8.0f;- }-- player_speed += (accel - drag - drift_scrub) * dt;- player_speed = clampf(player_speed, 0.0f,- cs->max_speed + boost_top_bonus + (slipstreaming ? 5.0f : 0.0f));-- // 4. Rotate Player World Heading ONLY by Player Steering (ZERO phantom auto-steer!)- float grip = cs->grip_lat * th->grip_mult * (off_road ? 0.72f : 1.0f);- float steer_auth = clampf(player_speed / 12.0f, 0.0f, 1.0f);- player_yaw_rate = player_steer * 1.38f * grip * steer_auth;- float d_yaw = player_yaw_rate * dt;-- if (key_ebrake && player_speed > 18.0f) {- player_drift += player_steer * 2.6f * cs->drift_ease * dt;- } else if (fabsf_fast(player_steer) > 0.7f && player_speed > 50.0f && key_gas) {- player_drift += player_steer * 0.85f * cs->drift_ease * dt;- } else {- player_drift *= (1.0f - clampf(4.5f * grip * dt, 0.0f, 0.9f));- }- if (fabsf_fast(player_drift) < 0.005f) player_drift = 0.0f;- player_drift = clampf(player_drift, -0.65f, 0.65f);-- // Rotate unit heading vector (player_sin_yaw, player_cos_yaw) by d_yaw- if (d_yaw != 0.0f) {- float c = cosf_fast(d_yaw), s = sinf_fast(d_yaw);- float ns = player_sin_yaw * c + player_cos_yaw * s;- float nc = player_cos_yaw * c - player_sin_yaw * s;- float inv_l = 1.0f / sqrtf_fast(ns * ns + nc * nc);- player_sin_yaw = ns * inv_l;- player_cos_yaw = nc * inv_l;- }-- // Advance car in 3D World Space along its true world heading!- player_wx += player_sin_yaw * player_speed * dt;- player_wz += player_cos_yaw * player_speed * dt;-- // 5. Locate closest track segment to (player_wx, player_wz) to get road height, offset, and lap progress- int best_s = player_seg;- float best_d2 = 1e18f;- for (int ds = -6; ds <= 10; ds++) {- int s = (player_seg + ds + TRACK_N) % TRACK_N;- float dx = player_wx - track_nodes[s].x;- float dz = player_wz - track_nodes[s].z;- float d2 = dx * dx + dz * dz;- if (d2 < best_d2) {- best_d2 = d2;- best_s = s;- }- }-- int prev_seg = player_seg;- player_seg = best_s;-- // In Infinity Mode, continuously generate new procedural road & changing biomes ahead of the horizon!- if (infinity_mode) {- while (((inf_head_seg - player_seg + TRACK_N) % TRACK_N) < 48) {- append_infinity_segment();- }- if (fabsf_fast(player_wx) > 2000.0f || fabsf_fast(player_wz) > 2000.0f) {- float sx = player_wx, sz = player_wz;- for (int i = 0; i < TRACK_N; i++) {- track_nodes[i].x -= sx;- track_nodes[i].z -= sz;- }- player_wx = 0.0f;- player_wz = 0.0f;- cam_x -= sx;- cam_z -= sz;- }- if (player_seg != prev_seg) {- update_infinity_minimap_bounds(player_seg);- }- }-- const TrackNode *n0 = &track_nodes[player_seg];- const TrackNode *n1 = &track_nodes[(player_seg + 1) % TRACK_N];-- float rel_x = player_wx - n0->x;- float rel_z = player_wz - n0->z;- float along = rel_x * n0->tx + rel_z * n0->tz;- float seg_frac = clampf(along / n0->seg_len, 0.0f, 1.0f);- player_offset = rel_x * n0->nx + rel_z * n0->nz;- player_wy = n0->y + (n1->y - n0->y) * seg_frac;-- // Player Boost Orb Pickup Check (check current and next segment in 3D world space!)- for (int os = 0; os <= 1; os++) {- int check_s = (player_seg + os) % TRACK_N;- if (track_nodes[check_s].orb_slot == 1) {- const TrackNode *on = &track_nodes[check_s];- float ox = on->x + on->nx * on->orb_offset;- float oz = on->z + on->nz * on->orb_offset;- float odx = player_wx - ox;- float odz = player_wz - oz;- if (odx * odx + odz * odz < 7.8f) {- track_nodes[check_s].orb_slot = infinity_mode ? 24 : 55;- // Leader in 1st place (with bots) gets +18% vs +30%; Infinity mode gets +35%- float gain = infinity_mode ? 35.0f : ((player_position == 1 && race_npc_count > 0) ? 18.0f : 30.0f);- player_boost_fuel = clampf(player_boost_fuel + gain, 0.0f, 100.0f);- orb_pickup_flash = 14;- }- }- }-- // Outer guardrail wall collision: keeps car inside track corridor without auto-steering on road!- const float max_wall = ROAD_HALF_W + 3.2f;- if (player_offset > max_wall) {- player_offset = max_wall;- player_wx = n0->x + n0->tx * along + n0->nx * player_offset;- player_wz = n0->z + n0->tz * along + n0->nz * player_offset;- player_speed -= player_speed * 1.5f * dt;- float dot_out = player_sin_yaw * n0->nx + player_cos_yaw * n0->nz;- if (dot_out > 0.0f) {- player_sin_yaw = n0->tx;- player_cos_yaw = n0->tz;- }- } else if (player_offset < -max_wall) {- player_offset = -max_wall;- player_wx = n0->x + n0->tx * along + n0->nx * player_offset;- player_wz = n0->z + n0->tz * along + n0->nz * player_offset;- player_speed -= player_speed * 1.5f * dt;- float dot_out = player_sin_yaw * n0->nx + player_cos_yaw * n0->nz;- if (dot_out < 0.0f) {- player_sin_yaw = n0->tx;- player_cos_yaw = n0->tz;- }- }-- // Dynamic 3D suspension body roll & pitch- float target_roll = clampf(-player_steer * (player_speed / 75.0f) * 0.15f - player_drift * 0.14f, -0.20f, 0.20f);- float target_pitch = clampf((accel - drag) * 0.0018f, -0.08f, 0.08f);- if ((on_kerb || off_road) && player_speed > 10.0f) {- target_roll += ((frame_counter & 1) ? 0.04f : -0.04f);- }- body_roll += (target_roll - body_roll) * 0.18f;- body_pitch += (target_pitch - body_pitch) * 0.25f;-- if (infinity_mode) {- player_dist = n0->cum_dist + seg_frac * n0->seg_len;- player_total_dist = player_dist;- int stage_num = 1 + (int)(player_total_dist / (INF_BIOME_SEGS * INF_SEG_LEN));- if (stage_num > current_lap) {- current_lap = stage_num;- player_laps_done = current_lap - 1;- uint32_t elapsed_ms = now_ms - lap_start_ms;- last_lap_ms = elapsed_ms;- lap_start_ms = now_ms;- if (last_lap_ms > 2000 &&- (best_lap_ms[current_track_id] == 0 || last_lap_ms < best_lap_ms[current_track_id])) {- split_delta_ms = (best_lap_ms[current_track_id] > 0)- ? ((int32_t)last_lap_ms - (int32_t)best_lap_ms[current_track_id])- : -1;- best_lap_ms[current_track_id] = last_lap_ms;- split_popup_timer = 75;- }- }- } else {- // Update Lap & Sector Timing (with exact player_laps_done tracking so finish rank is 100% accurate!)- if (prev_seg > TRACK_N - 15 && player_seg < 15) {- // Crossed Start/Finish line forward!- player_laps_done++;- uint32_t elapsed_ms = now_ms - lap_start_ms;- last_lap_ms = elapsed_ms;- lap_start_ms = now_ms;- current_sector = 0;-- if (last_lap_ms > 3000 &&- (best_lap_ms[current_track_id] == 0 || last_lap_ms < best_lap_ms[current_track_id])) {- split_delta_ms = (best_lap_ms[current_track_id] > 0)- ? ((int32_t)last_lap_ms - (int32_t)best_lap_ms[current_track_id])- : -1;- best_lap_ms[current_track_id] = last_lap_ms;- has_best_ghost[current_track_id] = true;- for (int i = 0; i < GHOST_SAMPLES; i++) {- best_ghost[i] = curr_ghost[i];- }- split_popup_timer = 95;- }-- if (race_total_laps > 0 && player_laps_done >= race_total_laps) {- race_finished = true;- total_race_ms = now_ms - race_start_ms;- } else {- current_lap = player_laps_done + 1;- }- } else if (prev_seg < 15 && player_seg > TRACK_N - 15) {- if (player_laps_done > 0) player_laps_done--;- }-- player_dist = n0->cum_dist + seg_frac * n0->seg_len;- // Use player_laps_done (not current_lap - 1!) so crossing the finish line increments total_dist!- player_total_dist = (float)player_laps_done * track_total_length + player_dist;- }-- step_npcs_and_collisions(dt);- if (race_finished) {- final_finish_position = player_position;- }-- if (!infinity_mode) {- uint32_t elapsed_ms = now_ms - lap_start_ms;- int ghost_slot = clampi((int)(elapsed_ms / 100), 0, GHOST_SAMPLES - 1);- curr_ghost[ghost_slot].wx_dm = (int16_t)(player_wx * 10.0f);- curr_ghost[ghost_slot].wy_dm = (int16_t)(player_wy * 10.0f);- curr_ghost[ghost_slot].wz_dm = (int16_t)(player_wz * 10.0f);- curr_ghost[ghost_slot].yaw_mrad = (int16_t)(player_sin_yaw * 1000.0f);- curr_ghost[ghost_slot].seg_idx = (uint8_t)player_seg;-- int new_sec = (player_seg * 3) / TRACK_N;- if (new_sec > current_sector && new_sec < 3) {- current_sector = new_sec;- if (best_sector_ms[current_track_id][current_sector] > 0) {- split_delta_ms = (int32_t)elapsed_ms - (int32_t)best_sector_ms[current_track_id][current_sector];- split_popup_timer = 75;- }- if (best_sector_ms[current_track_id][current_sector] == 0 ||- elapsed_ms < best_sector_ms[current_track_id][current_sector]) {- best_sector_ms[current_track_id][current_sector] = elapsed_ms;- }- }- }- if (split_popup_timer > 0) split_popup_timer--;-}--// ============================================================================-// BUILD 3D SCENE (CAMERA LOCKED TO PLAYER HEADING, NOT TRACK TANGENT!)-// ============================================================================-static TrackTheme active_sky_theme;--static void update_active_sky_theme(void) {- if (!infinity_mode) {- active_sky_theme = themes[current_track_id];- } else {- uint8_t b0 = track_nodes[player_seg].biome_id % NUM_INF_BIOMES;- uint8_t b1 = track_nodes[(player_seg + 14) % TRACK_N].biome_id % NUM_INF_BIOMES;- const TrackTheme *t0 = &infinity_biomes[b0];- const TrackTheme *t1 = &infinity_biomes[b1];- int b1_count = 0;- if (b0 != b1) {- for (int s = 1; s <= 14; s++) {- if ((track_nodes[(player_seg + s) % TRACK_N].biome_id % NUM_INF_BIOMES) == b1) b1_count++;- }- }- float w = (float)b1_count * (1.0f / 14.0f);- active_sky_theme.name = t0->name;- active_sky_theme.subtitle = t0->subtitle;- active_sky_theme.sky_top_r = (uint8_t)(t0->sky_top_r + (t1->sky_top_r - t0->sky_top_r) * w);- active_sky_theme.sky_top_g = (uint8_t)(t0->sky_top_g + (t1->sky_top_g - t0->sky_top_g) * w);- active_sky_theme.sky_top_b = (uint8_t)(t0->sky_top_b + (t1->sky_top_b - t0->sky_top_b) * w);- active_sky_theme.sky_bot_r = (uint8_t)(t0->sky_bot_r + (t1->sky_bot_r - t0->sky_bot_r) * w);- active_sky_theme.sky_bot_g = (uint8_t)(t0->sky_bot_g + (t1->sky_bot_g - t0->sky_bot_g) * w);- active_sky_theme.sky_bot_b = (uint8_t)(t0->sky_bot_b + (t1->sky_bot_b - t0->sky_bot_b) * w);- active_sky_theme.ground_r = (uint8_t)(t0->ground_r + (t1->ground_r - t0->ground_r) * w);- active_sky_theme.ground_g = (uint8_t)(t0->ground_g + (t1->ground_g - t0->ground_g) * w);- active_sky_theme.ground_b = (uint8_t)(t0->ground_b + (t1->ground_b - t0->ground_b) * w);- active_sky_theme.road_r = t0->road_r;- active_sky_theme.road_g = t0->road_g;- active_sky_theme.road_b = t0->road_b;- active_sky_theme.kerb_r = t0->kerb_r;- active_sky_theme.kerb_g = t0->kerb_g;- active_sky_theme.kerb_b = t0->kerb_b;- active_sky_theme.grip_mult = t0->grip_mult;- }- fog_r = active_sky_theme.sky_bot_r;- fog_g = active_sky_theme.sky_bot_g;- fog_b = active_sky_theme.sky_bot_b;-}--static void build_race_scene(bool braking, bool ebraking, uint32_t now_ms) {- num_screen_tris = 0;- update_active_sky_theme();-- // Camera sits directly behind the player car along the player's TRUE world heading!- // Zero track-tangent camera rotation!- bool is_horse = (selected_car_id == 3 || selected_car_id == 4);- float cam_dist = (cam_mode == 0) ? (is_horse ? 6.6f : 6.8f) : ((cam_mode == 1) ? 9.5f : -0.6f);- float cam_h = (cam_mode == 0) ? (is_horse ? 2.50f : 2.40f) : ((cam_mode == 1) ? 3.35f : 1.55f);-- cam_sin_yaw = player_sin_yaw;- cam_cos_yaw = player_cos_yaw;- cam_x = player_wx - player_sin_yaw * cam_dist;- cam_y = player_wy + cam_h;- cam_z = player_wz - player_cos_yaw * cam_dist;-- const TrackNode *pn0 = &track_nodes[player_seg];- const TrackNode *pn2 = &track_nodes[(player_seg + 2) % TRACK_N];- float slope = (pn2->y - pn0->y) * (1.0f / (pn0->seg_len * 2.0f));- cam_pitch = -0.11f + clampf(slope * 0.35f, -0.08f, 0.08f);- cam_roll = -body_roll * 0.35f;- cam_cos_pitch = cosf_fast(cam_pitch);- cam_sin_pitch = sinf_fast(cam_pitch);- cam_cos_roll = cosf_fast(cam_roll);- cam_sin_roll = sinf_fast(cam_roll);-- // Render 22 segments ahead and 2 behind- const int DRAW_SEGS = 22;- for (int s = DRAW_SEGS; s >= -2; s--) {- int i0 = (player_seg + s + TRACK_N) % TRACK_N;- int i1 = (i0 + 1) % TRACK_N;- const TrackNode *n0 = &track_nodes[i0];- const TrackNode *n1 = &track_nodes[i1];- uint8_t b_id = n0->biome_id % NUM_INF_BIOMES;- const TrackTheme *th = infinity_mode ? &infinity_biomes[b_id] : &themes[current_track_id];-- float u_v0 = (float)(i0 & 1);- float u_v1 = u_v0 + 1.0f;-- Vec3UV r0_l = {n0->x - n0->nx * ROAD_HALF_W, n0->y, n0->z - n0->nz * ROAD_HALF_W, 0.0f, u_v0};- Vec3UV r0_m = {n0->x, n0->y, n0->z, 0.5f, u_v0};- Vec3UV r0_r = {n0->x + n0->nx * ROAD_HALF_W, n0->y, n0->z + n0->nz * ROAD_HALF_W, 1.0f, u_v0};-- Vec3UV r1_l = {n1->x - n1->nx * ROAD_HALF_W, n1->y, n1->z - n1->nz * ROAD_HALF_W, 0.0f, u_v1};- Vec3UV r1_m = {n1->x, n1->y, n1->z, 0.5f, u_v1};- Vec3UV r1_r = {n1->x + n1->nx * ROAD_HALF_W, n1->y, n1->z + n1->nz * ROAD_HALF_W, 1.0f, u_v1};-- uint8_t road_tex = (!infinity_mode && i0 == 0) ? TEX_FINISH : TEX_ASPHALT;- uint8_t shade = (i0 & 1) ? 0 : 6;- submit_world_quad(r0_l, r0_m, r1_m, r1_l,- th->road_r + shade, th->road_g + shade, th->road_b + shade, road_tex, true);- submit_world_quad(r0_m, r0_r, r1_r, r1_m,- th->road_r + shade, th->road_g + shade, th->road_b + shade, road_tex, true);-- float kw = 1.40f;- Vec3UV k0_ll = {n0->x - n0->nx * (ROAD_HALF_W + kw), n0->y + 0.12f, n0->z - n0->nz * (ROAD_HALF_W + kw), 0.0f, u_v0};- Vec3UV k1_ll = {n1->x - n1->nx * (ROAD_HALF_W + kw), n1->y + 0.12f, n1->z - n1->nz * (ROAD_HALF_W + kw), 0.0f, u_v1};- submit_world_quad(k0_ll, r0_l, r1_l, k1_ll, th->kerb_r, th->kerb_g, th->kerb_b, TEX_KERB, true);-- Vec3UV k0_rr = {n0->x + n0->nx * (ROAD_HALF_W + kw), n0->y + 0.12f, n0->z + n0->nz * (ROAD_HALF_W + kw), 0.0f, u_v0};- Vec3UV k1_rr = {n1->x + n1->nx * (ROAD_HALF_W + kw), n1->y + 0.12f, n1->z + n0->nz * (ROAD_HALF_W + kw), 0.0f, u_v1};- submit_world_quad(r0_r, k0_rr, k1_rr, r1_r, th->kerb_r, th->kerb_g, th->kerb_b, TEX_KERB, true);-- // Compact terrain shoulder verge (grass / desert sand / cyber grid / snow / volcanic ash!)- if (s < 14) {- float gw = ROAD_HALF_W + 6.5f;- Vec3UV g0_l = {n0->x - n0->nx * gw, n0->y - 0.05f, n0->z - n0->nz * gw, 0.0f, u_v0};- Vec3UV g1_l = {n1->x - n1->nx * gw, n1->y - 0.05f, n1->z - n1->nz * gw, 0.0f, u_v1};- submit_world_quad(g0_l, k0_ll, k1_ll, g1_l, th->ground_r, th->ground_g, th->ground_b, TEX_GRASS, true);-- Vec3UV g0_r = {n0->x + n0->nx * gw, n0->y - 0.05f, n0->z + n0->nz * gw, 0.0f, u_v0};- Vec3UV g1_r = {n1->x + n1->nx * gw, n1->y - 0.05f, n1->z + n1->nz * gw, 0.0f, u_v1};- submit_world_quad(k0_rr, g0_r, g1_r, k1_rr, th->ground_r, th->ground_g, th->ground_b, TEX_GRASS, true);- }-- if (s < 0) continue;-- // Render 3D Floating Boost Orb (slot == 1) on road!- if (n0->orb_slot == 1 && s < 20) {- float ox = n0->x + n0->nx * n0->orb_offset;- float oz = n0->z + n0->nz * n0->orb_offset;- float bob = 1.25f + 0.25f * sinf_fast((float)frame_counter * 0.22f + (float)i0);- float oy = n0->y + bob;- float ang = (float)frame_counter * 0.16f + (float)i0;- float rx = cosf_fast(ang) * 1.15f;- float rz = sinf_fast(ang) * 1.15f;-- Vec3UV o_top = {ox, oy + 1.10f, oz, 0, 0};- Vec3UV o_bot = {ox, oy - 0.85f, oz, 0, 1};- Vec3UV o_l = {ox - rx, oy + 0.10f, oz - rz, 0, 0};- Vec3UV o_r = {ox + rx, oy + 0.10f, oz + rz, 1, 0};- Vec3UV o_f = {ox - rz, oy + 0.10f, oz + rx, 0, 1};- Vec3UV o_b = {ox + rz, oy + 0.10f, oz - rx, 1, 1};-- // Glowing ground pad under the orb- Vec3UV p0 = {ox - n0->nx * 1.1f, n0->y + 0.05f, oz - n0->nz * 1.1f, 0, 0};- Vec3UV p1 = {ox + n0->nx * 1.1f, n0->y + 0.05f, oz + n0->nz * 1.1f, 1, 0};- Vec3UV p2 = {ox + n0->tx * 1.4f, n0->y + 0.05f, oz + n0->tz * 1.4f, 0, 1};- submit_world_tri(p0, p1, p2, 0, 195, 255, TEX_FLAT, true);-- // Cyan/Gold Nitro Boost Orb- submit_world_tri(o_top, o_l, o_f, 60, 255, 255, TEX_FLAT, true);- submit_world_tri(o_top, o_f, o_r, 0, 210, 255, TEX_FLAT, true);- submit_world_tri(o_bot, o_f, o_l, 20, 150, 245, TEX_FLAT, true);- submit_world_tri(o_bot, o_r, o_f, 255, 230, 80, TEX_FLAT, true);- submit_world_tri(o_top, o_r, o_b, 80, 255, 220, TEX_FLAT, true);- submit_world_tri(o_top, o_b, o_l, 0, 185, 255, TEX_FLAT, true);- }-- // Roadside Props & Arches (no floating tunnel ceiling slabs!)- if (n0->prop_type == 2 || n0->prop_type == 3) {- float aw = ROAD_HALF_W + 2.4f;- float ah = (n0->prop_type == 2) ? 6.8f : 5.8f;- Vec3UV p_l0 = {n0->x - n0->nx * aw, n0->y, n0->z - n0->nz * aw, 0, 0};- Vec3UV p_l1 = {n0->x - n0->nx * (aw - 0.9f), n0->y, n0->z - n0->nz * (aw - 0.9f), 1, 0};- Vec3UV p_l2 = {n0->x - n0->nx * (aw - 0.7f), n0->y + ah, n0->z - n0->nz * (aw - 0.7f), 1, 1};- submit_world_tri(p_l0, p_l1, p_l2, 200, 200, 215, TEX_FLAT, true);-- Vec3UV p_r0 = {n0->x + n0->nx * (aw - 0.9f), n0->y, n0->z + n0->nz * (aw - 0.9f), 0, 0};- Vec3UV p_r1 = {n0->x + n0->nx * aw, n0->y, n0->z + n0->nz * aw, 1, 0};- Vec3UV p_r2 = {n0->x + n0->nx * (aw - 0.7f), n0->y + ah, n0->z + n0->nz * (aw - 0.7f), 1, 1};- submit_world_tri(p_r0, p_r1, p_r2, 200, 200, 215, TEX_FLAT, true);-- if (n0->prop_type == 2) {- Vec3UV b0 = {n0->x - n0->nx * aw, n0->y + ah - 1.3f, n0->z - n0->nz * aw, 0, 0};- Vec3UV b1 = {n0->x + n0->nx * aw, n0->y + ah - 1.3f, n0->z + n0->nz * aw, 1, 0};- Vec3UV b2 = {n0->x + n0->nx * aw, n0->y + ah, n0->z + n0->nz * aw, 1, 1};- Vec3UV b3 = {n0->x - n0->nx * aw, n0->y + ah, n0->z - n0->nz * aw, 0, 1};- uint8_t ban_r = (!infinity_mode && i0 == 0) ? 235 : th->kerb_r;- uint8_t ban_g = (!infinity_mode && i0 == 0) ? 45 : th->kerb_g;- uint8_t ban_b = (!infinity_mode && i0 == 0) ? 45 : th->kerb_b;- submit_world_quad(b0, b1, b2, b3, ban_r, ban_g, ban_b,- (!infinity_mode && i0 == 0) ? TEX_FINISH : TEX_FLAT, true);- }- } else if (n0->prop_type == 1 && s < 16) {- float side = (float)n0->prop_side * (ROAD_HALF_W + 4.8f);- float tx = n0->x + n0->nx * side;- float ty = n0->y;- float tz = n0->z + n0->nz * side;- bool is_cyber_lamp = infinity_mode ? (b_id == 2) : (current_track_id == 1);- if (is_cyber_lamp) {- Vec3UV l0 = {tx - n0->nx * 0.25f, ty, tz - n0->nz * 0.25f, 0, 0};- Vec3UV l1 = {tx + n0->nx * 0.25f, ty, tz + n0->nz * 0.25f, 1, 0};- Vec3UV l2 = {tx, ty + 6.5f, tz, 0, 1};- submit_world_tri(l0, l1, l2, 90, 220, 255, TEX_FLAT, true);- } else {- Vec3UV t0 = {tx - n0->nx * 2.2f, ty + 0.6f, tz - n0->nz * 2.2f, 0, 0};- Vec3UV t1 = {tx + n0->nx * 2.2f, ty + 0.6f, tz + n0->nz * 2.2f, 1, 0};- Vec3UV t2 = {tx, ty + 6.8f, tz, 0, 1};- uint8_t pr = 24, pg = 95, pb = 44;- if (infinity_mode) {- if (b_id == 1) { pr = 205; pg = 120; pb = 52; } // Desert sandstone spire- else if (b_id == 3) { pr = 185; pg = 220; pb = 245; } // Snow-covered glacier pine- else if (b_id == 4) { pr = 235; pg = 85; pb = 28; } // Volcanic crystal obelisk- }- submit_world_tri(t0, t1, t2, pr, pg, pb, TEX_FLAT, true);- }- } else if (n0->prop_type == 4 && s < 16) {- float side = (float)n0->prop_side * (ROAD_HALF_W + 2.5f);- float sx = n0->x + n0->nx * side;- float sy = n0->y;- float sz = n0->z + n0->nz * side;- Vec3UV c0 = {sx - n0->nx * 1.2f, sy + 0.4f, sz - n0->nz * 1.2f, 0, 0};- Vec3UV c1 = {sx + n0->nx * 1.2f, sy + 0.4f, sz + n0->nz * 1.2f, 1, 0};- Vec3UV c2 = {sx + n0->nx * 1.2f, sy + 2.2f, sz + n0->nz * 1.2f, 1, 1};- Vec3UV c3 = {sx - n0->nx * 1.2f, sy + 2.2f, sz - n0->nz * 1.2f, 0, 1};- submit_world_quad(c0, c1, c2, c3, 240, 185, 20, TEX_WALL, true);- }- }-- // Render 3D AI NPC Rival Cars (with exhaust flame when NPC is boosting!)- for (int i = 0; i < race_npc_count; i++) {- const NpcCar *ai = &npcs[i];- int seg_diff = (ai->seg_idx - player_seg + TRACK_N) % TRACK_N;- if (seg_diff < 22 || seg_diff > TRACK_N - 4) {- CarPose apose = {- ai->wx,- ai->wy,- ai->wz,- ai->cos_y,- ai->sin_y,- 0.0f,- 0.0f,- 0.0f- };- const uint8_t *col = npc_colors[ai->color_idx & 7];- draw_3d_car_colored(&apose, ai->car_model, col[0], col[1], col[2], ai->braking, ai->boosting, false);- }- }-- // Render Best Lap 3D Ghost Car (Circuit mode only)- if (!infinity_mode && has_best_ghost[current_track_id]) {- uint32_t elapsed_ms = now_ms - lap_start_ms;- int g_slot = clampi((int)(elapsed_ms / 100), 0, GHOST_SAMPLES - 1);- const GhostFrame *gf = &best_ghost[g_slot];- int seg_diff = ((int)gf->seg_idx - player_seg + TRACK_N) % TRACK_N;- if (seg_diff < 22 || seg_diff > TRACK_N - 4) {- const TrackNode *gn = &track_nodes[gf->seg_idx % TRACK_N];- CarPose gpose = {- (float)gf->wx_dm * 0.1f,- (float)gf->wy_dm * 0.1f,- (float)gf->wz_dm * 0.1f,- gn->tz,- gn->tx,- 0.0f, 0.0f, 0.0f- };- draw_3d_car(&gpose, selected_car_id, false, false, true);- }- }-- // Render Player 3D Car (with drift visual rotation & twin cyan nitro flames!)- if (cam_mode != 2) {- float slip_ang = player_drift * 0.65f;- float cd = cosf_fast(slip_ang);- float sd = sinf_fast(slip_ang);- float vis_sin = player_sin_yaw * cd + player_cos_yaw * sd;- float vis_cos = player_cos_yaw * cd - player_sin_yaw * sd;- CarPose ppose = {- player_wx,- player_wy,- player_wz,- vis_cos,- vis_sin,- body_roll,- body_pitch,- player_steer- };- draw_3d_car(&ppose, selected_car_id, braking, shift_flame_timer > 0 || player_boosting, false);-- if (player_boosting) {- float f_len = (frame_counter & 1) ? -3.45f : -3.10f;- Vec3UV nf0 = car_local_to_world(&ppose, -0.76f, 0.30f, -2.24f, 0, 0);- Vec3UV nf1 = car_local_to_world(&ppose, -0.36f, 0.30f, -2.24f, 1, 0);- Vec3UV nf2 = car_local_to_world(&ppose, -0.56f, 0.36f, f_len, 0, 1);- submit_world_tri(nf0, nf1, nf2, 40, 240, 255, TEX_FLAT, true);-- Vec3UV nr0 = car_local_to_world(&ppose, 0.36f, 0.30f, -2.24f, 0, 0);- Vec3UV nr1 = car_local_to_world(&ppose, 0.76f, 0.30f, -2.24f, 1, 0);- Vec3UV nr2 = car_local_to_world(&ppose, 0.56f, 0.36f, f_len, 0, 1);- submit_world_tri(nr0, nr1, nr2, 40, 240, 255, TEX_FLAT, true);- }-- if ((fabsf_fast(player_drift) > 0.16f || ebraking) && player_speed > 15.0f) {- float jit = ((frame_counter & 1) ? 0.25f : -0.25f);- Vec3UV sm0 = car_local_to_world(&ppose, -1.25f + jit, 0.10f, -2.1f, 0, 0);- Vec3UV sm1 = car_local_to_world(&ppose, -0.65f + jit, 0.10f, -2.6f, 1, 0);- Vec3UV sm2 = car_local_to_world(&ppose, -0.95f, 0.75f, -2.5f, 0, 1);- submit_world_tri(sm0, sm1, sm2, 215, 215, 225, TEX_GHOST, true);-- Vec3UV sr0 = car_local_to_world(&ppose, 0.65f + jit, 0.10f, -2.6f, 0, 0);- Vec3UV sr1 = car_local_to_world(&ppose, 1.25f + jit, 0.10f, -2.1f, 1, 0);- Vec3UV sr2 = car_local_to_world(&ppose, 0.95f, 0.75f, -2.5f, 0, 1);- submit_world_tri(sr0, sr1, sr2, 215, 215, 225, TEX_GHOST, true);- }- }-}--// ============================================================================-// 2D PIXEL FONT, HUD, MINI-MAP & 2-STEP MENU OVERLAYS-// ============================================================================-static inline void strip_put_px(int strip_y0, int x, int y, eadk_color_t c) {- if (x >= 0 && x < SCREEN_W && y >= strip_y0 && y < strip_y0 + STRIP_H) {- fb_strip[(y - strip_y0) * SCREEN_W + x] = c;- }-}--static void strip_fill_rect(int strip_y0, int x, int y, int w, int h, eadk_color_t c) {- int y0 = y > strip_y0 ? y : strip_y0;- int y1 = (y + h - 1) < (strip_y0 + STRIP_H - 1) ? (y + h - 1) : (strip_y0 + STRIP_H - 1);- if (y0 > y1) return;- int x0 = clampi(x, 0, SCREEN_W - 1);- int x1 = clampi(x + w - 1, 0, SCREEN_W - 1);- for (int py = y0; py <= y1; py++) {- eadk_color_t *row = &fb_strip[(py - strip_y0) * SCREEN_W];- for (int px = x0; px <= x1; px++) row[px] = c;- }-}--static const uint16_t font3x5[45] = {- 0x7B6F, // 0- 0x2492, // 1- 0x73E7, // 2- 0x73CF, // 3- 0x5BC9, // 4- 0x79CF, // 5- 0x79EF, // 6- 0x7249, // 7- 0x7BEF, // 8- 0x7BCF, // 9- 0x0000, // space (10)- 0x0410, // : (11)- 0x0002, // . (12)- 0x01C0, // - (13)- 0x05D0, // + (14)- 0x2524, // / (15)- // A..Z (16..41)- 0x7BED, 0x6BAE, 0x7927, 0x6B6E, 0x79E7, 0x79E4, 0x796F, 0x5BED,- 0x7497, 0x126F, 0x5BAD, 0x4927, 0x5FED, 0x6B6D, 0x7B6F, 0x7BE4,- 0x7B7A, 0x6BAD, 0x79CF, 0x7492, 0x5B6F, 0x5B6A, 0x5BFD, 0x5AAD,- 0x5A92, 0x72A7,- 0x1511, // < (42)- 0x4544, // > (43)- 0x0000-};--static int char_to_glyph(char c) {- if (c >= '0' && c <= '9') return c - '0';- if (c >= 'A' && c <= 'Z') return 16 + (c - 'A');- if (c >= 'a' && c <= 'z') return 16 + (c - 'a');- if (c == ':') return 11;- if (c == '.') return 12;- if (c == '-') return 13;- if (c == '+') return 14;- if (c == '/') return 15;- if (c == '<') return 42;- if (c == '>') return 43;- return 10;-}--static void strip_draw_text(int strip_y0, int x, int y, const char *str, int scale, eadk_color_t col) {- if (y + 5 * scale < strip_y0 || y >= strip_y0 + STRIP_H) return;- int cx = x;- while (*str) {- int g = char_to_glyph(*str++);- uint16_t bits = font3x5[g];- if (bits) {- for (int r = 0; r < 5; r++) {- for (int c = 0; c < 3; c++) {- if ((bits >> (14 - (r * 3 + c))) & 1) {- strip_fill_rect(strip_y0, cx + c * scale, y + r * scale, scale, scale, col);- }- }- }- }- cx += 4 * scale;- }-}--static void format_time_ms(uint32_t ms, char *buf) {- uint32_t mins = ms / 60000;- uint32_t secs = (ms / 1000) % 60;- uint32_t hund = (ms / 10) % 100;- buf[0] = '0' + (mins % 10);- buf[1] = ':';- buf[2] = '0' + (secs / 10);- buf[3] = '0' + (secs % 10);- buf[4] = '.';- buf[5] = '0' + (hund / 10);- buf[6] = '0' + (hund % 10);- buf[7] = '\0';-}--static void format_int3(int val, char *buf) {- if (val < 0) val = 0;- buf[0] = (val >= 100) ? ('0' + (val / 100) % 10) : ' ';- buf[1] = (val >= 10) ? ('0' + (val / 10) % 10) : ' ';- buf[2] = '0' + (val % 10);- buf[3] = '\0';-}--static void fill_background_strip(int strip_y0) {- const TrackTheme *th = &active_sky_theme;- int horizon_y = (int)(SCREEN_H * 0.48f - cam_sin_pitch * fov_scale);- horizon_y = clampi(horizon_y, 20, SCREEN_H - 20);-- // Fast reset 16-bit depth buffer to 0xFFFF (32-bit word fills)- uint32_t *zrow32 = (uint32_t *)zb_strip;- for (int i = 0; i < (SCREEN_W * STRIP_H) / 2; i++) {- zrow32[i] = 0xFFFFFFFFu;- }-- for (int sy = 0; sy < STRIP_H; sy++) {- int y = strip_y0 + sy;- eadk_color_t *row = &fb_strip[sy * SCREEN_W];-- if (y < horizon_y) {- float t = clampf((float)y / (float)(horizon_y > 0 ? horizon_y : 1), 0.0f, 1.0f);- int r = (int)(th->sky_top_r + (th->sky_bot_r - th->sky_top_r) * t);- int g = (int)(th->sky_top_g + (th->sky_bot_g - th->sky_top_g) * t);- int b = (int)(th->sky_top_b + (th->sky_bot_b - th->sky_top_b) * t);-- eadk_color_t sky_col = rgb565(r, g, b);- eadk_color_t mtn_col = rgb565(th->sky_top_r + 18, th->sky_top_g + 16, th->sky_top_b + 28);-- int m_scroll = (int)(cam_sin_yaw * 95.0f);- for (int x = 0; x < SCREEN_W; x++) {- int mx = (x + m_scroll) & 255;- int m_h = ((mx & 31) < 16 ? (mx & 15) : (15 - (mx & 15))) + (((mx >> 5) * 7) & 11);- row[x] = (y >= horizon_y - m_h) ? mtn_col : sky_col;- }- } else {- float t = clampf((float)(y - horizon_y) / (float)(SCREEN_H - horizon_y), 0.0f, 1.0f);- int r = (int)(fog_r + (th->ground_r - fog_r) * t);- int g = (int)(fog_g + (th->ground_g - fog_g) * t);- int b = (int)(fog_b + (th->ground_b - fog_b) * t);- eadk_color_t gnd_col = rgb565(r, g, b);- for (int x = 0; x < SCREEN_W; x++) {- row[x] = gnd_col;- }- }- }-}--static void draw_minimap_strip(int strip_y0, int center_x, int center_y, bool show_cars) {- if (strip_y0 > center_y + 30 || strip_y0 + STRIP_H < center_y - 30) return;-- if (infinity_mode && show_cars) {- for (int s = -6; s <= 34; s++) {- int i = (player_seg + s + TRACK_N) % TRACK_N;- int mx = center_x + (int)((track_nodes[i].x - map_cx) * map_scale);- int my = center_y - (int)((track_nodes[i].z - map_cz) * map_scale);- strip_fill_rect(strip_y0, mx, my, 2, 2, (s > 0) ? 0x07FF : 0xAD55);- }- } else {- for (int i = 0; i < TRACK_N; i++) {- int mx = center_x + (int)((track_nodes[i].x - map_cx) * map_scale);- int my = center_y - (int)((track_nodes[i].z - map_cz) * map_scale);- strip_fill_rect(strip_y0, mx, my, 2, 2, (i == 0) ? 0xFFE0 : 0xAD55);- }- }- if (!show_cars) return;-- for (int i = 0; i < race_npc_count; i++) {- int nx = center_x + (int)((npcs[i].wx - map_cx) * map_scale);- int ny = center_y - (int)((npcs[i].wz - map_cz) * map_scale);- strip_fill_rect(strip_y0, nx - 1, ny - 1, 3, 3, 0x07E0);- }-- int px = center_x + (int)((player_wx - map_cx) * map_scale);- int py = center_y - (int)((player_wz - map_cz) * map_scale);- strip_fill_rect(strip_y0, px - 2, py - 2, 4, 4, 0xF800);-}--static void draw_hud_strip(int strip_y0, uint32_t now_ms) {- const CarSpec *cs = &car_specs[selected_car_id];- int disp_pos = race_finished ? final_finish_position : player_position;-- if (strip_y0 == 0) {- strip_fill_rect(strip_y0, 0, 0, SCREEN_W, 20, 0x1082);- if (infinity_mode) {- strip_draw_text(strip_y0, 5, 5, "INF", 2, 0xFFE0);- char lap_str[8];- int l_idx = 0;- lap_str[l_idx++] = 'Z';- if (current_lap >= 10) lap_str[l_idx++] = '0' + ((current_lap / 10) % 10);- lap_str[l_idx++] = '0' + (current_lap % 10);- lap_str[l_idx] = '\0';- strip_draw_text(strip_y0, 35, 5, lap_str, 2, 0xFFFF);-- strip_draw_text(strip_y0, 76, 5, "KM", 2, 0x07E0);- int km_tenths = (int)(player_total_dist * 0.01f);- int km_whole = km_tenths / 10;- int km_frac = km_tenths % 10;- char km_str[8];- int k_idx = 0;- if (km_whole >= 10) km_str[k_idx++] = '0' + ((km_whole / 10) % 10);- km_str[k_idx++] = '0' + (km_whole % 10);- km_str[k_idx++] = '.';- km_str[k_idx++] = '0' + km_frac;- km_str[k_idx] = '\0';- strip_draw_text(strip_y0, 98, 5, km_str, 2, 0xFFFF);- } else {- strip_draw_text(strip_y0, 5, 5, "LAP", 2, 0xFFE0);- char lap_str[8];- int l_idx = 0;- if (current_lap >= 10) lap_str[l_idx++] = '0' + (current_lap / 10);- lap_str[l_idx++] = '0' + (current_lap % 10);- lap_str[l_idx++] = '/';- if (race_total_laps >= 10) lap_str[l_idx++] = '0' + (race_total_laps / 10);- lap_str[l_idx++] = '0' + (race_total_laps % 10);- lap_str[l_idx] = '\0';- strip_draw_text(strip_y0, 33, 5, lap_str, 2, 0xFFFF);-- strip_draw_text(strip_y0, 82, 5, "POS", 2, 0x07E0);- char pos_str[6] = {- '0' + (disp_pos % 10),- '/',- '0' + ((race_npc_count + 1) % 10),- '\0'- };- strip_draw_text(strip_y0, 110, 5, pos_str, 2, 0xFFFF);- }-- char tbuf[12];- format_time_ms(now_ms - lap_start_ms, tbuf);- strip_draw_text(strip_y0, 144, 5, tbuf, 2, 0x07FF);-- strip_draw_text(strip_y0, 212, 5, "BEST", 2, 0xFBE0);- if (best_lap_ms[current_track_id] > 0) {- format_time_ms(best_lap_ms[current_track_id], tbuf);- } else {- const char *dash = "-:--.--";- for (int i = 0; i < 8; i++) tbuf[i] = dash[i];- }- strip_draw_text(strip_y0, 248, 5, tbuf, 2, 0xFBE0);-- if (split_popup_timer > 0) {- strip_fill_rect(strip_y0, 108, 22, 104, 15, 0x0841);- bool faster = (split_delta_ms <= 0);- uint32_t abs_d = faster ? (uint32_t)(-split_delta_ms) : (uint32_t)split_delta_ms;- char dbuf[12];- dbuf[0] = faster ? '-' : '+';- dbuf[1] = '0' + ((abs_d / 1000) % 10);- dbuf[2] = '.';- dbuf[3] = '0' + ((abs_d / 100) % 10);- dbuf[4] = '0' + ((abs_d / 10) % 10);- dbuf[5] = 'S';- dbuf[6] = '\0';- strip_draw_text(strip_y0, 132, 25, dbuf, 2, faster ? 0x07E0 : 0xF800);- }- }-- draw_minimap_strip(strip_y0, 288, 52, true);-- if (race_finished && strip_y0 >= 40 && strip_y0 <= 120) {- strip_fill_rect(strip_y0, 44, 62, 232, 74, 0x0841);- strip_fill_rect(strip_y0, 44, 62, 232, 3, 0xFFE0);- strip_draw_text(strip_y0, 74, 70, "FINISH! POSITION:", 2, 0xFFE0);- char p_str[4] = {'0' + disp_pos, '\0'};- strip_draw_text(strip_y0, 222, 68, p_str, 3, (disp_pos == 1) ? 0x07E0 : 0xFFFF);-- char rt_buf[12];- format_time_ms(total_race_ms, rt_buf);- strip_draw_text(strip_y0, 74, 94, "RACE TIME:", 2, 0x07FF);- strip_draw_text(strip_y0, 166, 94, rt_buf, 2, 0xFFFF);- strip_draw_text(strip_y0, 62, 116, "OK: NEW TRACK HOME: MENU", 1, 0xAD55);- }-- if (strip_y0 == 200) {- strip_fill_rect(strip_y0, 0, 204, SCREEN_W, 36, 0x0841);- strip_fill_rect(strip_y0, 0, 204, SCREEN_W, 2, player_boosting ? 0x07FF : 0xAD55);-- strip_draw_text(strip_y0, 8, 208, "RPM", 1, 0xAD55);- if (orb_pickup_flash > 0) {- strip_draw_text(strip_y0, 30, 208, "+ORB BOOST!", 1, 0xFFE0);- } else if (player_boosting) {- strip_draw_text(strip_y0, 30, 208,- (!infinity_mode && disp_pos == 1 && race_npc_count > 0) ? "NITRO (1ST 2X BURN)" : "NITRO ACTIVE!",- 1, 0x07FF);- } else if (slipstreaming) {- strip_draw_text(strip_y0, 30, 208, "SLIPSTREAM!", 1, 0x07E0);- } else if (infinity_mode) {- uint8_t b_id = track_nodes[player_seg].biome_id % NUM_INF_BIOMES;- strip_draw_text(strip_y0, 30, 208, infinity_biomes[b_id].name, 1, 0x07E0);- }-- int bars = (engine_rpm * 20) / cs->redline_rpm;- bars = clampi(bars, 1, 20);- for (int b = 0; b < 20; b++) {- eadk_color_t bcol = (b >= 17) ? 0xF800 : ((b >= 13) ? 0xFFE0 : 0x07FF);- if (b >= bars) bcol = 0x2104;- int bh = 5 + (b >> 2);- strip_fill_rect(strip_y0, 8 + b * 6, 226 - bh, 4, bh, bcol);- }-- // NITRO / BOOST ORB FUEL BAR- strip_draw_text(strip_y0, 8, 230, "BST", 1, player_boosting ? 0xFFE0 : 0x07FF);- strip_fill_rect(strip_y0, 26, 230, 102, 6, 0x2104);- int boost_w = clampi((int)player_boost_fuel, 0, 100);- if (boost_w > 0) {- eadk_color_t ncol = player_boosting ? ((frame_counter & 1) ? 0xFFFF : 0xFFE0)- : ((orb_pickup_flash > 0) ? 0xFFE0 : 0x07FF);- strip_fill_rect(strip_y0, 27, 231, boost_w, 4, ncol);- }-- strip_fill_rect(strip_y0, 156, 209, 26, 27, 0x2104);- char g_str[2] = {'0' + current_gear, '\0'};- eadk_color_t g_col = (engine_rpm > cs->redline_rpm - 350) ? 0xF800 : 0xFFE0;- strip_draw_text(strip_y0, 163, 213, g_str, 4, g_col);- strip_draw_text(strip_y0, 186, 212, manual_trans ? "MT" : "AT", 2, 0x07E0);-- if (fabsf_fast(player_drift) > 0.16f) {- strip_draw_text(strip_y0, 186, 226, "DRIFT", 1, 0xF81F);- }-- int kmh = (int)(player_speed * 3.6f);- char spd_str[4];- format_int3(kmh, spd_str);- strip_draw_text(strip_y0, 234, 212, spd_str, 4, player_boosting ? 0x07FF : 0xFFFF);- strip_draw_text(strip_y0, 286, 224, "KMH", 2, 0xAD55);- }-}---static uint16_t strip_tri_list[NUM_STRIPS][MAX_SCREEN_TRIS];-static uint16_t strip_tri_count[NUM_STRIPS];--static inline void bin_screen_tris_to_strips(void) {- for (int s = 0; s < NUM_STRIPS; s++) strip_tri_count[s] = 0;- for (int i = 0; i < num_screen_tris; i++) {- int s_min = screen_tris[i].min_y / STRIP_H;- int s_max = screen_tris[i].max_y / STRIP_H;- if (s_min < 0) s_min = 0;- if (s_max >= NUM_STRIPS) s_max = NUM_STRIPS - 1;- for (int s = s_min; s <= s_max; s++) {- strip_tri_list[s][strip_tri_count[s]++] = (uint16_t)i;- }- }-}--static void render_full_frame(bool braking, bool ebraking, uint32_t now_ms) {- build_race_scene(braking, ebraking, now_ms);- bin_screen_tris_to_strips();-- for (int s = 0; s < NUM_STRIPS; s++) {- int strip_y0 = s * STRIP_H;- fill_background_strip(strip_y0);-- int count = strip_tri_count[s];- const uint16_t *list = strip_tri_list[s];- for (int t = 0; t < count; t++) {- rasterize_tri_strip(&screen_tris[list[t]], strip_y0);- }-- draw_hud_strip(strip_y0, now_ms);-- eadk_rect_t rect = {0, (uint16_t)strip_y0, SCREEN_W, STRIP_H};- eadk_display_push_rect(rect, fb_strip);- }-}--// ============================================================================-// 2-STEP MENU SYSTEM (GARAGE -> RACE SETUP -> RACE)-// ============================================================================-enum GameScreen {- SCREEN_GARAGE = 0,- SCREEN_RACE_SETUP = 1,- SCREEN_RACING = 2,- SCREEN_CONTROLS = 3-};--static int setup_cursor = 0;-static int controls_return_screen = SCREEN_GARAGE;--static void render_menu_frame(float spin_angle, int screen_state) {- num_screen_tris = 0;- const TrackTheme *th = &themes[current_track_id];- const CarSpec *cs = &car_specs[selected_car_id];- active_sky_theme = *th;- fog_r = th->sky_bot_r;- fog_g = th->sky_bot_g;- fog_b = th->sky_bot_b;-- cam_x = 0.0f;- cam_y = (selected_car_id >= 3) ? 2.25f : 2.15f;- cam_z = (selected_car_id >= 3) ? -5.5f : -5.6f;- cam_yaw = 0.0f;- cam_pitch = -0.14f;- cam_roll = 0.0f;- update_camera_trig();-- for (int i = 0; i < 12; i++) {- float a0 = (float)i * (TAU_F / 12.0f) + spin_angle * 0.5f;- float a1 = (float)(i + 1) * (TAU_F / 12.0f) + spin_angle * 0.5f;- Vec3UV v0 = {0.0f, -0.02f, 0.0f, 0.5f, 0.5f};- Vec3UV v1 = {cosf_fast(a0) * 3.5f, -0.02f, sinf_fast(a0) * 3.5f, 0.0f, 0.0f};- Vec3UV v2 = {cosf_fast(a1) * 3.5f, -0.02f, sinf_fast(a1) * 3.5f, 1.0f, 1.0f};- uint8_t c = (i & 1) ? 45 : 70;- submit_world_tri(v0, v1, v2, c, c + 5, c + 18, TEX_FLAT, true);- }-- CarPose pose = {0.0f, 0.0f, 0.0f, cosf_fast(spin_angle), sinf_fast(spin_angle), 0.0f, 0.0f, 0.25f};- draw_3d_car(&pose, selected_car_id, true, false, false);- bin_screen_tris_to_strips();-- for (int s = 0; s < NUM_STRIPS; s++) {- int strip_y0 = s * STRIP_H;- fill_background_strip(strip_y0);- int count = strip_tri_count[s];- const uint16_t *list = strip_tri_list[s];- for (int t = 0; t < count; t++) {- rasterize_tri_strip(&screen_tris[list[t]], strip_y0);- }-- if (screen_state == SCREEN_GARAGE) {- if (strip_y0 == 0) {- strip_fill_rect(0, 0, 0, SCREEN_W, 38, 0x0841);- strip_draw_text(0, 12, 6, "POLYGT 3D", 3, 0xFFE0);- strip_draw_text(0, 140, 10, "PS1 RACING SIMULATOR", 2, 0x07FF);- strip_draw_text(0, 12, 26, "UP/DN: THEME L/R: CAR TOOLBOX: CONTROLS", 1, 0xAD55);- }- if (strip_y0 == 40) {- strip_fill_rect(40, 10, 44, 300, 26, 0x1082);- strip_draw_text(40, 16, 48, "THEME:", 2, 0xFFE0);- strip_draw_text(40, 72, 48, th->name, 2, 0xFFFF);- strip_draw_text(40, 72, 60, th->subtitle, 1, 0xAD55);- }- if (strip_y0 == 160) {- strip_fill_rect(160, 10, 176, 300, 22, 0x1082);- strip_draw_text(160, 16, 182, "CAR:", 2, 0x07E0);- strip_draw_text(160, 56, 182, cs->name, 2, 0xFFFF);- strip_draw_text(160, 200, 184, cs->drivetrain, 1, 0x07FF);- }- if (strip_y0 == 200) {- strip_fill_rect(200, 0, 202, SCREEN_W, 38, 0x0841);- strip_draw_text(200, 12, 210, "OK / EXE: RACE SETUP", 2, 0x07E0);- strip_draw_text(200, 12, 226, "TOOLBOX / C: VIEW FULL CONTROLS LIST", 1, 0xFFE0);- }- } else if (screen_state == SCREEN_CONTROLS) {- if (strip_y0 == 0) {- strip_fill_rect(0, 0, 0, SCREEN_W, 36, 0x0841);- strip_draw_text(0, 12, 8, "CONTROLS LIST", 3, 0xFFE0);- strip_draw_text(0, 188, 12, "NUMWORKS / PC", 2, 0x07FF);- strip_draw_text(0, 12, 26, "DRIVER MANUAL AND KEYBINDINGS", 1, 0xAD55);- }-- if (strip_y0 >= 40 && strip_y0 <= 160) {- strip_fill_rect(strip_y0, 8, 42, 304, 154, 0x0841);- strip_fill_rect(strip_y0, 12, 46, 296, 14, 0x2104);- strip_draw_text(strip_y0, 16, 50, "ACTION", 1, 0xFFE0);- strip_draw_text(strip_y0, 126, 50, "NUMWORKS KEY", 1, 0x07E0);- strip_draw_text(strip_y0, 232, 50, "PC KEY", 1, 0x07FF);-- const char *act[9] = {- "ACCELERATE / GAS",- "BRAKE / REVERSE",- "STEER LEFT/RIGHT",- "E-BRAKE DRIFT",- "NITRO BOOST",- "AT / MT GEARBOX",- "SHIFT UP / DOWN",- "CAMERA VIEW",- "GARAGE / PAUSE"- };- const char *nw_k[9] = {- "OK / UP / EXE / *",- "BACK / DOWN / /",- "LEFT / RIGHT / 4 6",- "SHIFT / CLEAR",- "XNT / ANS / 0 / .",- "ALPHA",- "+ / - OR ( )",- "TOOLBOX / VAR",- "HOME"- };- const char *pc_k[9] = {- "W / UP / ENTER",- "S / DN / BKSP",- "A / D / ARROWS",- "SHIFT",- "SPACE / X / B",- "M / TAB",- "E / Q OR + -",- "C / V / P",- "ESCAPE"- };-- for (int r = 0; r < 9; r++) {- int ry = 64 + r * 14;- if (r & 1) {- strip_fill_rect(strip_y0, 12, ry - 2, 296, 13, 0x1082);- }- strip_draw_text(strip_y0, 16, ry, act[r], 1, 0xFFFF);- strip_draw_text(strip_y0, 126, ry, nw_k[r], 1, 0x07E0);- strip_draw_text(strip_y0, 232, ry, pc_k[r], 1, 0x07FF);- }- }-- if (strip_y0 == 200) {- strip_fill_rect(200, 0, 202, SCREEN_W, 38, 0x0841);- strip_draw_text(200, 16, 212, "PRESS OK OR BACK TO RETURN", 2, 0x07E0);- strip_draw_text(200, 16, 228, "HOME / ESC DURING RACE RETURNS TO GARAGE", 1, 0xAD55);- }- } else {- if (strip_y0 == 0) {- strip_fill_rect(0, 0, 0, SCREEN_W, 36, 0x0841);- strip_draw_text(0, 12, 8, "RACE SETUP", 3, 0x07E0);- strip_draw_text(0, 152, 12, "NEW PROCEDURAL TRACK", 2, 0xFFE0);- strip_draw_text(0, 12, 26, "UP/DN: SELECT L/R: CHANGE TOOLBOX: CONTROLS", 1, 0xAD55);- }-- if (strip_y0 >= 40 && strip_y0 <= 160) {- strip_fill_rect(strip_y0, 12, 46, 210, 138, 0x0841);- strip_fill_rect(strip_y0, 228, 46, 80, 138, 0x0841);-- // Row 0: MODE (< RACE > or < INFINITY >)- eadk_color_t c0 = (setup_cursor == 0) ? 0xFFE0 : 0xFFFF;- if (setup_cursor == 0) strip_fill_rect(strip_y0, 16, 52, 202, 22, 0x2104);- strip_draw_text(strip_y0, 22, 58, "MODE:", 2, c0);- strip_draw_text(strip_y0, 96, 58,- infinity_mode ? "< INFINITY >" : "< RACE >",- 2, infinity_mode ? 0xF81F : 0x07E0);-- // Row 1: LAPS- eadk_color_t c1 = (setup_cursor == 1) ? 0xFFE0 : 0xFFFF;- if (setup_cursor == 1) strip_fill_rect(strip_y0, 16, 82, 202, 22, 0x2104);- strip_draw_text(strip_y0, 22, 88, "LAPS:", 2, c1);- if (infinity_mode) {- strip_draw_text(strip_y0, 96, 88, "INFINITE", 2, 0x07FF);- } else {- char l_str[8];- l_str[0] = '<';- l_str[1] = ' ';- if (race_total_laps >= 10) {- l_str[2] = '1'; l_str[3] = '0'; l_str[4] = ' '; l_str[5] = '>'; l_str[6] = '\0';- } else {- l_str[2] = '0' + race_total_laps; l_str[3] = ' '; l_str[4] = '>'; l_str[5] = '\0';- }- strip_draw_text(strip_y0, 132, 88, l_str, 2, 0x07FF);- }-- // Row 2: NPC CARS- eadk_color_t c2 = (setup_cursor == 2) ? 0xFFE0 : 0xFFFF;- if (setup_cursor == 2) strip_fill_rect(strip_y0, 16, 112, 202, 22, 0x2104);- strip_draw_text(strip_y0, 22, 118, "NPC CARS:", 2, c2);- if (infinity_mode) {- strip_draw_text(strip_y0, 116, 118, "NO BOTS", 2, 0xAD55);- } else {- char n_str[8] = {'<', ' ', (char)('0' + race_npc_count), ' ', '>', '\0'};- strip_draw_text(strip_y0, 132, 118, n_str, 2, 0x07E0);- }-- // Row 3: COURSE SEED- eadk_color_t c3 = (setup_cursor == 3) ? 0xFFE0 : 0xFFFF;- if (setup_cursor == 3) strip_fill_rect(strip_y0, 16, 142, 202, 22, 0x2104);- strip_draw_text(strip_y0, 22, 148, "COURSE:", 2, c3);- char s_str[10] = {'<', ' ', 'N', 'E', 'W', ' ', (char)('0' + (current_track_seed % 10)), ' ', '>', '\0'};- strip_draw_text(strip_y0, 116, 148, s_str, 2, 0xFBE0);-- strip_draw_text(strip_y0, 242, 54, "COURSE MAP", 1, 0xFFE0);- draw_minimap_strip(strip_y0, 268, 116, false);- }-- if (strip_y0 == 200) {- strip_fill_rect(200, 0, 202, SCREEN_W, 38, 0x0841);- strip_draw_text(200, 16, 212,- infinity_mode ? "OK/ENTER: START INFINITY DRIVE!" : "PRESS OK / ENTER TO START THE RACE!",- 2, 0x07E0);- strip_draw_text(200, 16, 228, "BACK: GARAGE TOOLBOX / C: CONTROLS LIST", 1, 0xAD55);- }- }-- eadk_rect_t rect = {0, (uint16_t)strip_y0, SCREEN_W, STRIP_H};- eadk_display_push_rect(rect, fb_strip);- }-}--static void toggle_infinity_mode(void) {- if (!infinity_mode) {- saved_race_laps = (race_total_laps > 0) ? race_total_laps : 3;- saved_npc_count = race_npc_count;- infinity_mode = true;- race_npc_count = 0;- } else {- infinity_mode = false;- race_total_laps = (saved_race_laps > 0) ? saved_race_laps : 3;- race_npc_count = saved_npc_count;- }-}--int main(int argc, char *argv[]) {- (void)argc;- (void)argv;-- uint32_t boot_ms = (uint32_t)eadk_timing_millis();- build_track_seeded(0, 101 + boot_ms);-- int screen_state = SCREEN_GARAGE;- float menu_spin = 2.6f;-- uint64_t prev_kb = 0;- uint32_t last_ms = boot_ms;- reset_race_state(last_ms);-- while (true) {- eadk_keyboard_state_t kb = eadk_keyboard_scan();- uint64_t just_pressed = kb & (~prev_kb);- prev_kb = kb;-- uint32_t now_ms = (uint32_t)eadk_timing_millis();- uint32_t dt_ms = now_ms - last_ms;- if (dt_ms < 25) {- eadk_timing_msleep(25 - dt_ms);- now_ms = (uint32_t)eadk_timing_millis();- dt_ms = now_ms - last_ms;- }- last_ms = now_ms;- float dt = clampf((float)dt_ms * 0.001f, 0.01f, 0.08f);- frame_counter++;-- if (screen_state == SCREEN_GARAGE) {- if (eadk_keyboard_key_down(just_pressed, eadk_key_home)) {- break;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_toolbox) ||- eadk_keyboard_key_down(just_pressed, eadk_key_var)) {- controls_return_screen = SCREEN_GARAGE;- screen_state = SCREEN_CONTROLS;- continue;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_left)) {- selected_car_id = (selected_car_id + NUM_CARS - 1) % NUM_CARS;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_right)) {- selected_car_id = (selected_car_id + 1) % NUM_CARS;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_up)) {- current_track_id = (current_track_id + 2) % 3;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_down)) {- current_track_id = (current_track_id + 1) % 3;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_ok) ||- eadk_keyboard_key_down(just_pressed, eadk_key_exe)) {- build_track_seeded(current_track_id, now_ms ^ (frame_counter * 2654435761u));- setup_cursor = 0;- screen_state = SCREEN_RACE_SETUP;- }- menu_spin += 1.1f * dt;- render_menu_frame(menu_spin, SCREEN_GARAGE);- } else if (screen_state == SCREEN_CONTROLS) {- if (eadk_keyboard_key_down(just_pressed, eadk_key_back) ||- eadk_keyboard_key_down(just_pressed, eadk_key_home) ||- eadk_keyboard_key_down(just_pressed, eadk_key_ok) ||- eadk_keyboard_key_down(just_pressed, eadk_key_exe) ||- eadk_keyboard_key_down(just_pressed, eadk_key_toolbox) ||- eadk_keyboard_key_down(just_pressed, eadk_key_var)) {- screen_state = controls_return_screen;- continue;- }- menu_spin += 1.1f * dt;- render_menu_frame(menu_spin, SCREEN_CONTROLS);- } else if (screen_state == SCREEN_RACE_SETUP) {- if (eadk_keyboard_key_down(just_pressed, eadk_key_back) ||- eadk_keyboard_key_down(just_pressed, eadk_key_home)) {- screen_state = SCREEN_GARAGE;- continue;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_toolbox) ||- eadk_keyboard_key_down(just_pressed, eadk_key_var)) {- controls_return_screen = SCREEN_RACE_SETUP;- screen_state = SCREEN_CONTROLS;- continue;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_up)) {- setup_cursor = (setup_cursor + 3) % 4;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_down)) {- setup_cursor = (setup_cursor + 1) % 4;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_left)) {- if (setup_cursor == 0) {- toggle_infinity_mode();- } else if (setup_cursor == 1) {- if (!infinity_mode) {- if (race_total_laps > 1) race_total_laps--;- else toggle_infinity_mode();- }- } else if (setup_cursor == 2 && !infinity_mode && race_npc_count > 0) {- race_npc_count--;- } else if (setup_cursor == 3) {- build_track_seeded(current_track_id, current_track_seed + 17 + now_ms);- }- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_right)) {- if (setup_cursor == 0) {- toggle_infinity_mode();- } else if (setup_cursor == 1) {- if (infinity_mode) {- toggle_infinity_mode();- race_total_laps = 1;- } else if (race_total_laps < 10) {- race_total_laps++;- }- } else if (setup_cursor == 2 && !infinity_mode && race_npc_count < MAX_NPCS) {- race_npc_count++;- } else if (setup_cursor == 3) {- build_track_seeded(current_track_id, current_track_seed + 31 + now_ms);- }- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_ok) ||- eadk_keyboard_key_down(just_pressed, eadk_key_exe)) {- reset_race_state(now_ms);- screen_state = SCREEN_RACING;- }- menu_spin += 1.1f * dt;- render_menu_frame(menu_spin, SCREEN_RACE_SETUP);- } else {- if (eadk_keyboard_key_down(just_pressed, eadk_key_home)) {- screen_state = SCREEN_GARAGE;- continue;- }- if (race_finished &&- (eadk_keyboard_key_down(just_pressed, eadk_key_ok) ||- eadk_keyboard_key_down(just_pressed, eadk_key_exe))) {- build_track_seeded(current_track_id, now_ms ^ (frame_counter * 1664525u));- reset_race_state(now_ms);- continue;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_alpha)) {- manual_trans = !manual_trans;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_toolbox)) {- cam_mode = (cam_mode + 1) % 3;- }- if (eadk_keyboard_key_down(just_pressed, eadk_key_var)) {- cam_mode = (cam_mode + 1) % 3;- }-- bool key_L = eadk_keyboard_key_down(kb, eadk_key_left) ||- eadk_keyboard_key_down(kb, eadk_key_four);- bool key_R = eadk_keyboard_key_down(kb, eadk_key_right) ||- eadk_keyboard_key_down(kb, eadk_key_six);- bool key_gas = eadk_keyboard_key_down(kb, eadk_key_ok) ||- eadk_keyboard_key_down(kb, eadk_key_up) ||- eadk_keyboard_key_down(kb, eadk_key_exe) ||- eadk_keyboard_key_down(kb, eadk_key_multiplication);- bool key_brake = eadk_keyboard_key_down(kb, eadk_key_back) ||- eadk_keyboard_key_down(kb, eadk_key_down) ||- eadk_keyboard_key_down(kb, eadk_key_division);- bool key_ebrake = eadk_keyboard_key_down(kb, eadk_key_shift) ||- eadk_keyboard_key_down(kb, eadk_key_backspace);- bool key_boost = eadk_keyboard_key_down(kb, eadk_key_xnt) ||- eadk_keyboard_key_down(kb, eadk_key_ans) ||- eadk_keyboard_key_down(kb, eadk_key_zero) ||- eadk_keyboard_key_down(kb, eadk_key_dot) ||- eadk_keyboard_key_down(kb, eadk_key_exp);-- bool shift_up = eadk_keyboard_key_down(just_pressed, eadk_key_plus) ||- eadk_keyboard_key_down(just_pressed, eadk_key_right_parenthesis);- bool shift_dn = eadk_keyboard_key_down(just_pressed, eadk_key_minus) ||- eadk_keyboard_key_down(just_pressed, eadk_key_left_parenthesis);-- step_physics(dt, key_L, key_R, key_gas, key_brake, key_ebrake, key_boost,- shift_up, shift_dn, now_ms);- render_full_frame(key_brake, key_ebrake, now_ms);+ plat_sleep(moving ? 2 : 10);}}- return 0;+ save();+ return plat_end();}diff --git a/games/polygt3d/src/plat.h b/games/polygt3d/src/plat.hnew file mode 100644index 00000000..bbdbcad3--- /dev/null+++ b/games/polygt3d/src/plat.h@@ -0,0 +1,23 @@+/* What the game needs from the calculator (plat_eadk.c), or from a computer for the tests. */+#ifndef PG_PLAT_H+#define PG_PLAT_H+#include <stdbool.h>+#include <stdint.h>++/* (PK_: NumPlay's np.h has K_ keys of its own) */+enum {+ PK_OK = 1, PK_UP = 2, PK_DOWN = 4, PK_LEFT = 8, PK_RIGHT = 16, PK_BACK = 32, PK_HOME = 64, PK_GEAR_UP = 128,+ PK_GEAR_DOWN = 256+};+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);+void plat_vblank(void);+bool plat_save(const char *name, const void *data, uint32_t len);+const uint8_t *plat_load(const char *name, uint32_t *len);+uint32_t plat_random(void);+bool plat_slow(void); /* an N0110 or N0115 */+void plat_begin(void);+int plat_end(void);+#endifdiff --git a/games/polygt3d/src/plat_eadk.c b/games/polygt3d/src/plat_eadk.cnew file mode 100644index 00000000..d3e890c6--- /dev/null+++ b/games/polygt3d/src/plat_eadk.c@@ -0,0 +1,37 @@+/* The calculator: keys, time, the screen and files (EADK, and NumPlay's careful file helpers). */+#include <eadk.h>+#include "../../common/epsilon_app.h"+#include "../../common/epsilon_files.h"+#include "plat.h"++const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "PolyGT 3D";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;++#define KEY(k) ((uint64_t)1 << (k))++uint32_t plat_keys(void) {+ uint64_t k = eadk_keyboard_scan();+ uint32_t r = 0;+ if (k & (KEY(eadk_key_ok) | KEY(eadk_key_exe) | KEY(eadk_key_five))) r |= PK_OK;+ if (k & (KEY(eadk_key_up) | KEY(eadk_key_eight))) r |= PK_UP;+ if (k & (KEY(eadk_key_down) | KEY(eadk_key_two))) r |= PK_DOWN;+ if (k & (KEY(eadk_key_left) | KEY(eadk_key_four))) r |= PK_LEFT;+ if (k & (KEY(eadk_key_right) | KEY(eadk_key_six))) r |= PK_RIGHT;+ if (k & (KEY(eadk_key_back) | KEY(eadk_key_backspace))) r |= PK_BACK;+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= PK_HOME;+ if (k & KEY(eadk_key_plus)) r |= PK_GEAR_UP;+ if (k & KEY(eadk_key_minus)) r |= PK_GEAR_DOWN;+ 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}, (const eadk_color_t *)px);+}+void plat_vblank(void) { eadk_display_wait_for_vblank(); }+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); }+uint32_t plat_random(void) { return eadk_random(); }+bool plat_slow(void) { return epsilon_slow_model(); }+void plat_begin(void) { np_app_begin(); }+int plat_end(void) { return np_app_end(); }diff --git a/games/polygt3d/src/race.c b/games/polygt3d/src/race.cnew file mode 100644index 00000000..1f36faa1--- /dev/null+++ b/games/polygt3d/src/race.c@@ -0,0 +1,588 @@+/* The race: your car and the rivals' on the road, a step of 20 ms at a time. Whole numbers only (game.h).+ *+ * Your car goes where it points; steering turns it as far as its tyres hold (24 m/s^2 sideways at grip 1, less on+ * the grass and on the touge), and a bend you don't steer through carries you to its outside. Braking while you+ * steer hard at speed slides the car: a tighter line for less braking. The engine pulls through six gears, nitro+ * adds a push and top speed, and driving close behind a car pulls you along. The rivals keep to their lines, brake+ * for the bends at three levels, pass slower cars and take orbs. Cars never go through each other or the barriers.+ */+#include <string.h>+#include "game.h"++const pg_vehicle pg_vehicles[PG_VEHICLES] = {+ /* name, kind, top speed and pull (1/8), grip, slide, grass (1/128), horse, redline, body, accent */+ {"Apex GT", "Rear drive, twin turbo", 81 * 8, 88, 128, 147, 128, 0, 8500, {225, 32, 42}, {245, 190, 40}},+ {"Proto R", "Mid engine, sharp grip", 79 * 8, 82, 146, 115, 128, 0, 9000, {240, 240, 245}, {220, 30, 35}},+ {"Rally IV", "Four-wheel drive", 76 * 8, 96, 138, 134, 64, 0, 7800, {35, 105, 230}, {245, 205, 45}},+ {"Black Stallion", "A horse: quick off the mark", 72 * 8, 104, 153, 138, 80, 1, 9200, {24, 24, 32}, {255, 45, 35}},+ {"Brown Mustang", "A horse: sure-footed", 70 * 8, 100, 157, 134, 72, 1, 8800, {148, 84, 42}, {225, 175, 55}},+};++/* grip of the road in each scenery (1/128): the three circuits, then the endless road's five */+static const uint8_t ZONE_GRIP[8] = {128, 133, 118, 128, 125, 133, 119, 123};+static const uint16_t TORQUE[18] = {206, 206, 211, 223, 235, 245, 255, 262, 268, 272, 274, 274, 272, 268, 262, 254,+ 245, 236};+static const uint16_t PULL[6] = {346, 289, 211, 165, 133, 133};+static const uint8_t GEAR_TOP[6] = {22, 35, 48, 60, 71, 84}; /* each gear's top, in 80ths of the car's */++#define MS(x) ((int32_t)((x) * FX)) /* metres (a second, a second squared) */+#define A_LAT MS(24)+#define BRAKE MS(28)+#define DRIFT_BRAKE MS(12)+#define AI_BRAKE MS(20)+#define NITRO_A MS(7)+#define NITRO_TOP MS(13.5)+#define DRAFT_A MS(2.5)+#define DRAFT_TOP MS(5)+#define DRAG0 MS(2.1)+#define TURN_MAX 14394 /* 1.38 radians a second, at most */+#define RAD 10430 /* angle units in a radian */+#define COUNTDOWN (3 * PG_HZ + PG_HZ / 2)+#define ORB_WAIT 275 /* steps before an orb comes back (5.5 s) */+#define GRID_GAP MS(8)++static int32_t clampi(int32_t v, int32_t lo, int32_t hi) { return v < lo ? lo : v > hi ? hi : v; }+static int32_t absi(int32_t v) { return v < 0 ? -v : v; }++uint32_t pg_sum(const void *data, uint32_t n) {+ const uint8_t *p = data;+ uint32_t h = 2166136261u;+ for (uint32_t i = 0; i < n; i++) h = (h ^ p[i]) * 16777619u;+ return h;+}++int pg_kmh(int32_t v) { return (int)((int64_t)v * 36 / (10 * FX)); }++static int32_t top_of(const pg_car *c) { return (int32_t)pg_vehicles[c->model].top * FX / 8; }+static int32_t gear_max(const pg_car *c, int g) { return top_of(c) * GEAR_TOP[g - 1] / 80; }++int pg_rpm(const pg_race *r) {+ const pg_car *c = &r->car[0];+ int red = pg_vehicles[c->model].redline;+ int32_t norm = (int32_t)((int64_t)c->v * 256 / gear_max(c, c->gear));+ int rpm = 1250 + (int)((int64_t)norm * (red - 1250) / 256);+ return rpm > red + 200 ? red + 200 : rpm;+}++/* the engine's push in the car's gear (FX/s^2), skill: 256 = all of it */+static int32_t engine(const pg_car *c, int skill) {+ int32_t gm = gear_max(c, c->gear);+ if (c->v >= gm + gm / 20) return 0; /* on the limiter */+ int32_t norm = (int32_t)((int64_t)c->v * 16 / gm);+ norm = clampi(norm, 0, 17);+ int64_t a = (int64_t)pg_vehicles[c->model].accel * FX / 8;+ return (int32_t)(a * TORQUE[norm] / 256 * PULL[c->gear - 1] / 256 * skill / 256);+}++/* air and rolling: none of the engine's push is left at the car's top speed in top gear */+static int32_t drag(const pg_car *c) {+ int32_t top = top_of(c);+ int64_t a = (int64_t)pg_vehicles[c->model].accel * FX / 8;+ int32_t at_top = (int32_t)(a * 250 / 256 * PULL[5] / 256);+ return DRAG0 + (int32_t)((int64_t)(at_top - DRAG0) * c->v / top * c->v / top);+}++static int32_t grip_of(const pg_race *r, const pg_track *t, const pg_car *c) {+ int32_t g = (int32_t)pg_vehicles[c->model].grip * ZONE_GRIP[pg_zone_at(t, c->s)] / 128;+ if (absi(c->x) > PG_ROAD + PG_KERB) g = g * 92 / 128;+ (void)r;+ return g; /* 1/128 */+}++static void shift_auto(pg_car *c) {+ int red = pg_vehicles[c->model].redline;+ int32_t norm = (int32_t)((int64_t)c->v * 256 / gear_max(c, c->gear));+ int rpm = 1250 + (int)((int64_t)norm * (red - 1250) / 256);+ if (rpm > red - 250 && c->gear < 6) c->gear++;+ else if (c->gear > 1 && rpm < 3600 && c->v < gear_max(c, c->gear - 1) * 4 / 5) c->gear--;+}++/* the leader burns nitro faster, so nobody hoards it out in front */+static bool leading(const pg_race *r, int i) {+ if (r->mode == MODE_ENDLESS || r->rivals == 0) return false;+ for (int j = 0; j <= r->rivals; j++)+ if (j != i && !r->car[j].finish_ms && r->car[j].s > r->car[i].s) return false;+ return true;+}++/* a car close in front, in line: you're in its slipstream */+static bool drafting(const pg_race *r, const pg_track *t, int i) {+ const pg_car *c = &r->car[i];+ if (c->v < MS(30)) return false;+ for (int j = 0; j <= r->rivals; j++) {+ if (j == i) continue;+ int32_t ds = pg_wrap(t, r->car[j].s - c->s);+ if (ds > MS(4.5) && ds < MS(22) && absi(r->car[j].x - c->x) < MS(1.9)) return true;+ }+ return false;+}++/* where a car goes in a step: along the road (more of it on the inside of a bend), across it, and how the bend+ turns it */+static void move(pg_track *t, pg_car *c) {+ int32_t k = pg_seg_of(t, c->s);+ int32_t cv = t->cv[pg_slot(t, k)];+ int32_t step = c->v / PG_HZ;+ int32_t kx = (int32_t)((int64_t)cv * c->x * 6283 / (1000LL * t->seg));+ int32_t den = clampi(65536 - kx, 40000, 90000);+ int32_t ds = (int32_t)((int64_t)step * pg_cos(c->ang) / 32767 * 65536 / den);+ int32_t dx = (int32_t)((int64_t)step * pg_sin(c->ang) / 32767);+ c->s += ds;+ c->x += dx;+ c->ang = (int16_t)(c->ang - (int32_t)((int64_t)cv * ds / t->seg));+}++static void barriers(pg_race *r, pg_track *t, pg_car *c) {+ int32_t lim = PG_WALL - PG_HW;+ if (absi(c->x) > lim) {+ bool right = c->x > 0;+ c->x = right ? lim : -lim;+ int32_t a = c->ang;+ if ((right && a > 0) || (!right && a < 0)) {+ /* into it: the speed across is lost, a little more besides, and the car turns along it (the way it was+ going: forwards, or backwards) */+ c->v = (int32_t)((int64_t)c->v * absi(pg_cos(a)) / 32767 * 15 / 16);+ bool back = a > 16384 || a < -16384;+ int32_t rel = back ? a - (a > 0 ? 32768 : -32768) : a;+ c->ang = (int16_t)(back ? rel / 4 + (a > 0 ? 32768 : -32768) : rel / 4);+ c->bump = 12;+ }+ c->v -= c->v / 160; /* scraping along */+ c->drift = 0;+ }+ /* the endless road behind you isn't kept: it's a wall too */+ if (t->endless) {+ int32_t back = (t->first + 6) * t->seg;+ if (c->s < back) c->s = back, c->v = 0;+ }+ (void)r;+}++/* ------------------------------------------------------------------ your car */+static void drive(pg_race *r, pg_track *t, unsigned in, int shift) {+ pg_car *c = &r->car[0];+ const pg_vehicle *veh = &pg_vehicles[c->model];+ bool racing = r->phase == PH_RACE;+ if (!racing) in = r->phase == PH_GRID ? in & (IN_LEFT | IN_RIGHT) : 0;+ /* the wheel turns in quickly and comes back by itself */+ if ((in & IN_LEFT) && !(in & IN_RIGHT)) c->steer = (int16_t)clampi(c->steer - (c->steer > 0 ? 200 : 92), -1024, 1024);+ else if ((in & IN_RIGHT) && !(in & IN_LEFT)) c->steer = (int16_t)clampi(c->steer + (c->steer < 0 ? 200 : 92), -1024, 1024);+ else c->steer = (int16_t)(absi(c->steer) < 24 ? 0 : c->steer * 7 / 8);+ if (r->phase == PH_GRID) return;+ /* gears */+ if (r->manual) {+ if (shift > 0 && c->gear < 6) c->gear++;+ if (shift < 0 && c->gear > 1) c->gear--;+ } else {+ shift_auto(c);+ }+ /* nitro */+ bool lead = leading(r, 0);+ c->boost = (in & IN_NITRO) && c->nitro > 5;+ int burn = lead ? 9 : 5;+ if (c->boost) c->nitro = (uint16_t)(c->nitro > burn ? c->nitro - burn : 0);+ bool draft = drafting(r, t, 0);+ r->slipstream = draft ? (uint16_t)(r->slipstream + 1) : 0;+ /* a slide: braking while steering hard at speed */+ int32_t v = c->v;+ if ((in & IN_BRAKE) && absi(c->steer) >= 512 && v >= MS(22)) c->drift = 1;+ if (!(in & IN_BRAKE) || v < MS(15)) c->drift = 0;+ /* along */+ int32_t a = 0;+ if ((in & IN_GAS) || c->boost) {+ int32_t e = engine(c, 256);+ a += c->drift ? e / 2 : e;+ if (draft) a += DRAFT_A;+ if (c->boost) a += NITRO_A;+ }+ if (in & IN_BRAKE) a -= c->drift ? DRIFT_BRAKE : BRAKE;+ a -= drag(c);+ bool grass = absi(c->x) > PG_ROAD + PG_KERB;+ if (grass) a -= (int32_t)((MS(6) + (int64_t)v * v * 12 / 1000 / FX) * veh->offroad / 128);+ if (c->drift) a -= v / 25; /* the slide scrubs speed off */+ v += a / PG_HZ;+ int32_t top = top_of(c) + (c->boost ? NITRO_TOP : 0) + (draft ? DRAFT_TOP : 0);+ if (v > top) v = v - (v - top) / 8 > top ? v - (v - top) / 8 : top;+ if (v < 0) v = 0;+ c->v = v;+ /* turning: as far as the tyres hold */+ int32_t grip = grip_of(r, t, c);+ int32_t lat = A_LAT * grip / 128;+ int32_t hold = v > MS(1) ? (int32_t)((int64_t)lat * RAD / v) : TURN_MAX; /* units a second */+ int32_t lock = hold + hold / 6 < TURN_MAX ? hold + hold / 6 : TURN_MAX;+ int32_t auth = v >= MS(12) ? 256 : v * 256 / MS(12);+ int32_t want = (int32_t)((int64_t)c->steer * lock / 1024 * auth / 256);+ int32_t can = c->drift ? hold * 13 / 10 : hold;+ int32_t turn = clampi(want, -can, can);+ if (want != turn) c->v -= c->v / 400; /* asking more than the tyres give: they scrub */+ c->ang = (int16_t)(c->ang + turn / PG_HZ);+ /* the body in a slide: turned into the bend, by how much the car slides */+ int32_t slip_to = c->drift ? (int32_t)((int64_t)c->steer * 4700 / 1024 * veh->drift / 128) : 0;+ c->slip = (int16_t)(c->slip + (slip_to - c->slip) / 6);+ move(t, c);+ barriers(r, t, c);+ if (c->bump) c->bump--;+}++/* ------------------------------------------------------------------ the rivals */+static const int16_t LEVEL_CORNER[3] = {214, 234, 254}; /* how close to the limit they take bends (1/256) */+static const int16_t LEVEL_PULL[3] = {226, 242, 256};++static void rival(pg_race *r, pg_track *t, int i) {+ pg_car *c = &r->car[i];+ int lv = r->level <= LEVEL_HARD ? r->level : LEVEL_NORMAL;+ int skill_c = LEVEL_CORNER[lv] - (i == 0 ? 0 : (i - 1) * 3), skill_e = LEVEL_PULL[lv] - (i == 0 ? 0 : (i - 1) * 2);+ bool racing = r->phase == PH_RACE || (r->phase == PH_DONE && r->mode == MODE_RACE);+ int32_t top = top_of(c);+ /* a little help or a little holding back, away from you (not on Hard) */+ if (i && lv != LEVEL_HARD && r->car[0].finish_ms == 0) {+ int32_t gap = r->car[i].s - r->car[0].s;+ if (gap > MS(150)) top = top * 246 / 256, skill_e = skill_e * 240 / 256;+ else if (gap < -MS(120)) top = top * 262 / 256, skill_c += 6;+ }+ if (c->finish_ms) skill_c -= 16, top = top * 7 / 8; /* a lap of honour */+ int32_t k0 = pg_seg_of(t, c->s);+ /* every few steps: the speed for what comes (the slowest bend ahead, braking from here) and the line */+ if (c->think == 0) {+ c->think = 4;+ int32_t grip = grip_of(r, t, c);+ int64_t aim2 = (int64_t)(top + (c->boost ? NITRO_TOP : 0)) * (top + (c->boost ? NITRO_TOP : 0));+ for (int k = 0; k < 24; k++) {+ int sl = pg_slot(t, k0 + k);+ int64_t vl = (int64_t)t->limit[sl] * FX;+ vl = vl * pg_isqrt((uint64_t)grip * 128) / 128 * skill_c / 256; /* (speed grows with the root of grip) */+ int64_t d = (int64_t)(k0 + k) * t->seg - c->s;+ if (d < 0) d = 0;+ int64_t v2 = vl * vl + 2 * (int64_t)AI_BRAKE * d;+ if (v2 < aim2) aim2 = v2;+ }+ c->aim = (uint16_t)(pg_isqrt((uint64_t)aim2) / 8 > 65535 ? 65535 : pg_isqrt((uint64_t)aim2) / 8);+ /* the line: out before a bend, in at its middle, with each rival a little to its own side */+ int32_t near = 0, far = 0;+ for (int k = 0; k < 4; k++) near += t->cv[pg_slot(t, k0 + k)];+ for (int k = 4; k < 13; k++) far += t->cv[pg_slot(t, k0 + k)];+ int32_t line = near * 3 - far; /* angle units */+ int32_t want = (int32_t)((int64_t)line * MS(6) / 3000) + ((i * 37) % 7 - 3) * MS(0.6);+ /* a slower car ahead in the way: go round it, on the side with room; none: follow it */+ int blocker = -1;+ int32_t best = MS(18);+ for (int j = 0; j <= r->rivals; j++) {+ if (j == i) continue;+ int32_t ds = pg_wrap(t, r->car[j].s - c->s);+ if (ds > 0 && ds < best && absi(r->car[j].x - c->x) < MS(2.8) && r->car[j].v < c->v + MS(1)) best = ds, blocker = j;+ }+ if (blocker >= 0) {+ int32_t bx = r->car[blocker].x;+ int32_t lft = bx - MS(3.4), rgt = bx + MS(3.4);+ bool lok = lft > -(PG_ROAD - MS(1.2)), rok = rgt < PG_ROAD - MS(1.2);+ for (int j = 0; j <= r->rivals; j++) {+ if (j == i || j == blocker) continue;+ int32_t ds = pg_wrap(t, r->car[j].s - c->s);+ if (ds < -MS(6) || ds > MS(24)) continue;+ if (absi(r->car[j].x - lft) < MS(2.6)) lok = false;+ if (absi(r->car[j].x - rgt) < MS(2.6)) rok = false;+ }+ if (lok && (!rok || absi(lft - c->x) <= absi(rgt - c->x))) want = lft;+ else if (rok) want = rgt;+ else if (c->aim > (r->car[blocker].v + MS(0.5)) / 8) c->aim = (uint16_t)((r->car[blocker].v + MS(0.5)) / 8);+ }+ /* an orb close to the line, when nitro runs low */+ if (c->nitro < 850 && r->mode == MODE_RACE) {+ for (int k = 1; k <= 5; k++) {+ int sl = pg_slot(t, k0 + k);+ if (t->orb[sl] == -128) continue;+ int id = t->orb_id[sl];+ if (id >= 0 && r->orb_wait[id]) break;+ int32_t ox = t->orb[sl] * FX / 8;+ if (absi(ox - c->x) < MS(5.2) && ((k0 + k) * 7 + i * 13) % 8 < 4 && blocker < 0) want = ox;+ break;+ }+ }+ c->lane = clampi(want, -(PG_ROAD - MS(1.4)), PG_ROAD - MS(1.4));+ }+ c->think--;+ /* nitro on the straights */+ int32_t aim = (int32_t)c->aim * 8;+ if (!racing) aim = 0;+ if (!c->boost) {+ if (racing && c->nitro >= 320 && aim >= top && c->v > MS(38)) c->boost = 1;+ } else if (c->nitro <= 5 || aim < top || !racing) {+ c->boost = 0;+ }+ if (c->boost) {+ int burn = leading(r, i) ? 9 : 5;+ c->nitro = (uint16_t)(c->nitro > burn ? c->nitro - burn : 0);+ }+ /* gas or brakes */+ if (c->gear < 1 || c->gear > 6) c->gear = 1;+ shift_auto(c);+ int32_t a = -drag(c);+ if (c->v > aim + MS(1)) a -= AI_BRAKE;+ else if (c->v < aim) {+ a += engine(c, skill_e);+ if (c->boost) a += NITRO_A;+ if (drafting(r, t, i)) a += DRAFT_A;+ }+ int32_t v = c->v + a / PG_HZ;+ int32_t cap = top + (c->boost ? NITRO_TOP : 0) + MS(3);+ if (absi(c->x) > PG_ROAD + PG_KERB) cap = cap * 3 / 4;+ c->v = clampi(v, 0, cap);+ /* across, towards the line, and pointing where it goes */+ int32_t dx = c->lane - c->x, vx_max = MS(5) / PG_HZ;+ int32_t vx = clampi(dx / 6, -vx_max, vx_max);+ if (c->v < MS(3)) vx = 0;+ int32_t head = c->v > MS(1) ? pg_atan2(vx * PG_HZ, c->v) : 0;+ c->ang = (int16_t)(head > 32767 ? head - 65536 : head);+ c->steer = (int16_t)clampi(c->ang * 8, -1024, 1024);+ /* along the road, as the road goes */+ int32_t keep = c->ang;+ move(t, c);+ c->ang = (int16_t)keep;+ c->slip = 0, c->drift = 0;+ barriers(r, t, c);+ if (c->bump) c->bump--;+}++/* ------------------------------------------------------------------ cars touching */+static void touch(pg_race *r, pg_track *t) {+ int n = r->mode == MODE_ENDLESS ? 1 : r->rivals + 1;+ for (int pass = 0; pass < 3; pass++)+ for (int a = 0; a < n; a++)+ for (int b = a + 1; b < n; b++) {+ pg_car *A = &r->car[a], *B = &r->car[b];+ int32_t ds = pg_wrap(t, B->s - A->s), dx = B->x - A->x;+ int32_t ps = 2 * PG_HL - absi(ds), px = 2 * PG_HW - absi(dx);+ if (ps <= 0 || px <= 0) continue;+ if ((int64_t)ps * PG_HW < (int64_t)px * PG_HL) {+ /* nose to tail: the car behind stops at the other's bumper and gives it a push */+ pg_car *back = ds > 0 ? A : B, *front = ds > 0 ? B : A;+ back->s -= ps * 3 / 4 + 1, front->s += ps - ps * 3 / 4;+ if (back->v > front->v) {+ int32_t d = back->v - front->v;+ back->v = front->v - d / 8 > 0 ? front->v - d / 8 : 0, front->v += d / 3;+ }+ back->bump = front->bump = 10;+ } else {+ /* side by side: pushed apart, both straightened */+ pg_car *left = dx > 0 ? A : B, *right = dx > 0 ? B : A;+ int32_t lw = -(PG_WALL - PG_HW), rw = PG_WALL - PG_HW;+ int32_t half = px / 2 + 1;+ int32_t lx = left->x - half, rx = right->x + (px - px / 2 + 1);+ if (lx < lw) rx += lw - lx, lx = lw; /* against a barrier: the other takes all of it */+ if (rx > rw) lx -= rx - rw, rx = rw;+ if (lx < lw) lx = lw;+ left->x = lx, right->x = rx;+ if (left->ang > 0) left->ang = (int16_t)(left->ang / 2);+ if (right->ang < 0) right->ang = (int16_t)(right->ang / 2);+ left->v -= left->v / 64, right->v -= right->v / 64;+ left->bump = right->bump = 10;+ left->drift = right->drift = 0;+ }+ }+}++/* ------------------------------------------------------------------ orbs */+static void orbs(pg_race *r, pg_track *t, int i, int32_t s0) {+ pg_car *c = &r->car[i];+ int32_t k0 = pg_seg_of(t, s0), k1 = pg_seg_of(t, c->s);+ for (int32_t k = k0; k <= k1 && k <= k0 + 2; k++) {+ int sl = pg_slot(t, k);+ if (t->orb[sl] == -128) continue;+ int32_t mid = k * t->seg + t->seg / 2;+ if (!(s0 < mid && c->s >= mid)) continue;+ if (absi(t->orb[sl] * FX / 8 - c->x) >= MS(2.6)) continue;+ int gain;+ if (r->mode == MODE_ENDLESS) {+ if (k <= r->last_orb) continue;+ r->last_orb = k, gain = 350;+ } else {+ int id = t->orb_id[sl];+ if (id < 0 || r->orb_wait[id]) continue;+ r->orb_wait[id] = ORB_WAIT;+ gain = leading(r, i) ? 180 : 300;+ }+ c->nitro = (uint16_t)(c->nitro + gain > 1000 ? 1000 : c->nitro + gain);+ if (i == 0) r->flash = 25;+ }+}++/* ------------------------------------------------------------------ the race */+static void banner(pg_race *r, int b, int arg) { r->banner = (uint8_t)b, r->banner_arg = (uint8_t)arg, r->banner_t = 2 * PG_HZ; }++void pg_new(pg_race *r, pg_track *t, const pg_setup *s, uint32_t seed) {+ memset(r, 0, sizeof *r);+ r->mode = s->mode <= MODE_ENDLESS ? s->mode : MODE_RACE;+ r->track = s->track < PG_CIRCUITS ? s->track : 0;+ r->vehicle = s->vehicle < PG_VEHICLES ? s->vehicle : 0;+ r->laps = s->laps >= 1 && s->laps <= PG_MAX_LAPS ? s->laps : 3;+ r->rivals = r->mode == MODE_ENDLESS ? 0 : s->rivals <= PG_CARS - 1 ? s->rivals : 5;+ r->level = s->level <= LEVEL_HARD ? s->level : LEVEL_NORMAL;+ r->manual = s->manual ? 1 : 0;+ r->seed = seed ? seed : 1;+ r->phase = PH_GRID, r->countdown = COUNTDOWN, r->lap = 1;+ if (r->mode == MODE_ENDLESS) pg_endless(t, r->seed);+ else pg_build(t, r->track);+ uint32_t rng = r->seed;+ int n = r->rivals + 1;+ for (int i = 0; i < n; i++) {+ pg_car *c = &r->car[i];+ /* the grid: two by two behind the line, you at the back */+ int slot = i == 0 ? n - 1 : i - 1;+ c->s = -(MS(10) + (slot / 2) * GRID_GAP + (slot & 1) * GRID_GAP / 2);+ c->x = r->mode == MODE_ENDLESS ? 0 : (slot & 1) ? MS(3.2) : -MS(3.2);+ c->lane = c->x, c->gear = 1, c->nitro = 300;+ c->model = i == 0 ? r->vehicle : (uint8_t)((i + pg_rng(&rng) % 3) % 3);+ c->paint = (uint8_t)(i == 0 ? 0 : (i + 2) % 8);+ c->driven = i != 0, c->think = (uint16_t)(i % 4);+ }+ if (r->mode == MODE_ENDLESS) {+ r->car[0].s = MS(30), r->car[0].nitro = 1000;+ r->time_left = 30000, r->last_orb = -1;+ }+}++/* time a zone of the endless road gives: 8 s, a quarter of a second less each zone, 3 s at least */+int32_t pg_zone_bonus(int zone) {+ int32_t b = 8000 - 250 * (zone - 1);+ return b < 3000 ? 3000 : b;+}++void pg_step(pg_race *r, pg_track *t, unsigned input, int shift) {+ r->ticks++;+ if (r->mode == MODE_ENDLESS) pg_extend(t, pg_seg_of(t, r->car[0].s) + 48);+ if (r->phase == PH_GRID) {+ drive(r, t, input, 0); /* (the wheel turns; the car stays) */+ if (r->countdown) r->countdown--;+ if (!r->countdown) r->phase = PH_RACE;+ return;+ }+ if ((r->phase == PH_RACE || (r->phase == PH_DONE && r->mode == MODE_RACE)) && r->time_ms < 99u * 60000u) r->time_ms += PG_TICK;+ if (r->flash) r->flash--;+ int n = r->rivals + 1;+ int32_t before[PG_CARS];+ for (int i = 0; i < n; i++) before[i] = r->car[i].s;+ if (r->car[0].driven) rival(r, t, 0);+ else drive(r, t, input, shift);+ for (int i = 1; i < n; i++) rival(r, t, i);+ touch(r, t);+ for (int i = 0; i < n; i++) orbs(r, t, i, before[i]);+ for (int k = 0; k < PG_ORBS; k++)+ if (r->orb_wait[k]) r->orb_wait[k]--;+ if (r->banner_t && !--r->banner_t) r->banner = BANNER_NONE;+ pg_car *me = &r->car[0];+ /* wrong way: pointing back down the road and moving */+ bool back = me->ang > 18000 || me->ang < -18000;+ r->wrong = (uint8_t)(back && me->v > MS(4) && r->phase == PH_RACE ? (r->wrong < 255 ? r->wrong + 1 : 255) : 0);+ if (r->mode == MODE_ENDLESS) {+ int zone = (int)(pg_seg_of(t, me->s) / PG_ZONE);+ if (zone > r->zone && r->phase == PH_RACE) {+ r->zone = (uint8_t)(zone < 255 ? zone : 255);+ r->time_left += pg_zone_bonus(zone);+ banner(r, BANNER_ZONE, zone);+ }+ if (r->phase == PH_RACE) {+ r->time_left -= PG_TICK;+ if (r->time_left <= 0) r->time_left = 0, r->phase = PH_DONE, r->end = END_TIME, me->drift = 0;+ } else {+ r->done = (uint16_t)(r->done < 65535 ? r->done + 1 : 65535);+ me->v -= me->v / 20 + MS(0.2); /* out of time: the car rolls to a stop */+ if (me->v < 0) me->v = 0;+ }+ return;+ }+ /* laps, the finish */+ for (int i = 0; i < n; i++) {+ pg_car *c = &r->car[i];+ int32_t L = t->length;+ if (c->s < -L) c->s += L; /* (a whole lap backwards: the same place) */+ if (c->finish_ms) {+ if (c->s >= (int32_t)(r->laps + 1) * L) c->s -= L;+ continue;+ }+ if (c->s >= (int32_t)r->laps * L) {+ c->finish_ms = r->time_ms ? r->time_ms : 1;+ c->place = (uint8_t)++r->finished;+ if (i == 0) {+ r->phase = PH_DONE, r->end = END_FINISH, c->driven = 1, c->drift = 0, c->boost = 0;+ uint32_t lap = r->time_ms - r->lap_at;+ r->last_lap_ms = lap;+ if (!r->best_lap_ms || lap < r->best_lap_ms) r->best_lap_ms = lap;+ }+ } else if (i == 0) {+ int lap = c->s < 0 ? 1 : (int)(c->s / L) + 1;+ if (lap > r->lap) {+ uint32_t ms = r->time_ms - r->lap_at;+ r->lap_at = r->time_ms, r->last_lap_ms = ms;+ bool best = !r->best_lap_ms || ms < r->best_lap_ms;+ if (best) r->best_lap_ms = ms;+ r->lap = (uint8_t)lap;+ banner(r, lap == r->laps ? BANNER_FINAL : BANNER_LAP, lap);+ }+ }+ }+ /* (99 minutes and still not over the line: out of time) */+ if (r->phase == PH_RACE && r->time_ms >= 99u * 60000u - PG_TICK) r->phase = PH_DONE, r->end = END_TIME, me->driven = 1;+ if (r->phase == PH_DONE) r->done = (uint16_t)(r->done < 65535 ? r->done + 1 : 65535);+ if (r->wrong > PG_HZ && r->banner != BANNER_WRONG) banner(r, BANNER_WRONG, 0);+}++int pg_rank(const pg_race *r, int car) {+ const pg_car *c = &r->car[car];+ if (c->place) return c->place;+ int rank = 1 + r->finished;+ for (int j = 0; j <= r->rivals; j++)+ if (j != car && !r->car[j].place && (r->car[j].s > c->s || (r->car[j].s == c->s && j < car))) rank++;+ return rank;+}++int32_t pg_lap_s(const pg_race *r, const pg_track *t) {+ int32_t s = r->car[0].s;+ if (t->endless) return s;+ int32_t L = t->length, m = s % L;+ return m < 0 ? m + L : m;+}++/* everything in range: what the game makes, and what a damaged save might hold */+bool pg_valid(const pg_race *r, const pg_track *t) {+ if (r->mode > MODE_ENDLESS || r->track >= PG_CIRCUITS || r->vehicle >= PG_VEHICLES) return false;+ if (r->laps < 1 || r->laps > PG_MAX_LAPS || r->rivals > PG_CARS - 1 || r->level > LEVEL_HARD) return false;+ if (r->manual > 1 || r->phase > PH_DONE || r->end > END_TIME || r->flash > 25) return false;+ if (r->mode == MODE_ENDLESS && r->rivals) return false;+ if (r->lap < 1 || r->lap > r->laps || r->finished > r->rivals + 1 || r->banner > BANNER_WRONG) return false;+ if (r->countdown > COUNTDOWN || (r->phase == PH_GRID) != (r->countdown > 0 && r->time_ms == 0)) return false;+ if (r->phase != PH_DONE && (r->end || r->done)) return false;+ if (r->phase == PH_DONE && !r->end) return false;+ if (r->banner_t > 2 * PG_HZ || r->lap_at > r->time_ms || r->best_lap_ms > r->time_ms || r->last_lap_ms > r->time_ms)+ return false;+ if (r->time_ms > 99 * 60000u || r->seed == 0) return false;+ for (int k = 0; k < PG_ORBS; k++)+ if (r->orb_wait[k] > ORB_WAIT) return false;+ if (r->mode == MODE_ENDLESS) {+ if (r->time_left < 0 || r->time_left > 30 * 60000 || r->last_orb < -1) return false;+ if (r->phase == PH_DONE && r->end != END_TIME) return false;+ } else if (r->end == END_TIME && r->car[0].finish_ms) {+ return false;+ } else if (r->time_left || r->last_orb || r->zone) {+ return false;+ }+ int32_t L = t && !t->endless ? t->length : MS(1800);+ int32_t lo = r->mode == MODE_ENDLESS ? 0 : -L - MS(100);+ int32_t hi = r->mode == MODE_ENDLESS ? MS(2000000) : (int32_t)(r->laps + 2) * L;+ for (int i = 0; i < PG_CARS; i++) {+ const pg_car *c = &r->car[i];+ if (i > r->rivals) {+ const uint8_t *b = (const uint8_t *)c;+ for (unsigned k = 0; k < sizeof *c; k++)+ if (b[k]) return false;+ continue;+ }+ if (c->s < lo || c->s > hi || c->x < -(PG_WALL - PG_HW) || c->x > PG_WALL - PG_HW) return false;+ if (c->lane < -PG_ROAD || c->lane > PG_ROAD || c->v < 0 || c->v > MS(130)) return false;+ if (c->steer < -1024 || c->steer > 1024 || c->nitro > 1000 || c->gear < 1 || c->gear > 6) return false;+ if (c->boost > 1 || c->drift > 1 || c->model >= PG_VEHICLES || c->paint > 7 || c->bump > 12 || c->driven > 1) return false;+ if (c->place > r->rivals + 1 || (c->place != 0) != (c->finish_ms != 0) || c->finish_ms > r->time_ms + 1) return false;+ if (c->think > 4 || (i == 0 && c->model != r->vehicle)) return false;+ if (i > 0 ? !c->driven : c->driven != (c->finish_ms || (r->mode == MODE_RACE && r->end == END_TIME) ? 1 : 0)) return false;+ }+ return true;+}diff --git a/games/polygt3d/src/render.c b/games/polygt3d/src/render.cnew file mode 100644index 00000000..3e2eb384--- /dev/null+++ b/games/polygt3d/src/render.c@@ -0,0 +1,886 @@+/* PolyGT 3D's picture: low-poly, flat-shaded triangles seen from behind your car.+ *+ * A frame is set up once (rd_race, rd_showroom): the road's segments ahead, the roadside, the orbs and the cars are+ * turned into the camera's space, cut at the near plane, projected, and kept as screen triangles with their depth+ * (1/z, which is flat across the screen). rd_draw then fills a strip of rows at a time: the sky, the hills and the+ * ground, then every triangle crossing the strip, nearest wins. Edges are walked in floats with a fill rule, so+ * neighbouring triangles never leave a gap or overlap. */+#include <string.h>+#include "../../../launcher/src/gfx.h"+#include "render.h"++#define CX 160.0f+#define CY 115.0f+#define FOCAL 205.0f+#define NEAR 1.0f+#define FAR 215.0f+#define FOG0 55.0f+#define MAX_TRIS 1400+#define DRAW_SEGS 34 /* segments ahead */+#define DETAIL_SEGS 14 /* ...with lines and stripes */+#define GUARD 1000.0f /* screen triangles are cut to this far outside the screen */++typedef struct { float x, y, z; } v3;++typedef struct {+ int16_t x[3], y[3]; /* 1/16 pixel, top to bottom */+ uint16_t w[3]; /* NEAR/z, 65535 = at the near plane */+ uint16_t c;+ uint8_t stip, pad;+ int16_t y0, y1; /* the rows it covers */+} tri;++static tri tris[MAX_TRIS];+static int ntris;+int rd_dropped, rd_tris;++/* the camera */+static int32_t cam_x, cam_y, cam_z; /* where it is (FX) */+static float cy_c, cy_s, cp_c, cp_s, cr_c, cr_s;+static int32_t cam_yaw;+static int horizon;+/* the background */+static uint8_t sky_top[3], sky_bot[3], fog[3], ground[3], hill[3];+static uint8_t hills[SCREEN_W];++/* ------------------------------------------------------------------ colours */+typedef struct {+ uint8_t sky_top[3], sky_bot[3], ground[3], road[3], kerb[3], tree[3], wall[3];+ uint8_t lamps;+} theme;+static const theme THEMES[8] = {+ {{35, 25, 85}, {235, 110, 80}, {35, 85, 42}, {62, 64, 72}, {220, 35, 35}, {24, 95, 44}, {214, 214, 222}, 0},+ {{10, 12, 32}, {55, 25, 85}, {22, 24, 34}, {46, 50, 62}, {0, 195, 235}, {90, 220, 255}, {104, 110, 128}, 1},+ {{45, 35, 60}, {165, 130, 145}, {48, 62, 42}, {58, 56, 60}, {230, 165, 20}, {30, 72, 44}, {190, 190, 196}, 0},+ {{25, 60, 140}, {130, 190, 245}, {34, 98, 44}, {62, 65, 72}, {225, 40, 40}, {24, 95, 44}, {214, 214, 222}, 0},+ {{55, 20, 75}, {245, 115, 50}, {180, 98, 46}, {74, 62, 56}, {240, 185, 25}, {205, 120, 52}, {196, 170, 140}, 0},+ {{10, 12, 34}, {70, 25, 105}, {20, 26, 42}, {44, 48, 60}, {0, 215, 255}, {90, 220, 255}, {96, 104, 126}, 1},+ {{38, 82, 150}, {185, 225, 250}, {198, 215, 232}, {68, 76, 92}, {35, 115, 240}, {185, 220, 245}, {150, 160, 176}, 0},+ {{36, 16, 38}, {215, 65, 35}, {44, 36, 38}, {48, 44, 46}, {255, 95, 15}, {235, 85, 28}, {120, 110, 112}, 0},+};+const uint8_t rd_paint[8][3] = {{245, 195, 25}, {30, 205, 95}, {175, 55, 235}, {245, 110, 25},+ {50, 195, 240}, {215, 215, 225}, {235, 45, 135}, {40, 85, 220}};++uint16_t rd_rgb(const uint8_t c[3]) { return (uint16_t)((c[0] & 0xF8) << 8 | (c[1] & 0xFC) << 3 | c[2] >> 3); }+static uint8_t cl8(int v) { return (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v); }+static void mix3(uint8_t *o, const uint8_t *a, const uint8_t *b, int t256) {+ for (int i = 0; i < 3; i++) o[i] = (uint8_t)(a[i] + (b[i] - a[i]) * t256 / 256);+}++/* ------------------------------------------------------------------ small float maths */+static float fsinu(int32_t a) { return (float)pg_sin(a) * (1.0f / 32767.0f); }+static float fcosu(int32_t a) { return (float)pg_cos(a) * (1.0f / 32767.0f); }+static int iceil(float f) {+ int i = (int)f;+ return (float)i < f ? i + 1 : i;+}+static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }++/* a point of the world (FX), in the camera's space */+static v3 to_cam_f(float dx, float dy, float dz) {+ float x1 = dx * cy_c - dz * cy_s, z1 = dx * cy_s + dz * cy_c;+ float y2 = dy * cp_c - z1 * cp_s, z2 = dy * cp_s + z1 * cp_c;+ v3 o = {x1 * cr_c - y2 * cr_s, x1 * cr_s + y2 * cr_c, z2};+ return o;+}+static v3 to_cam(int32_t wx, int32_t wy, int32_t wz) {+ return to_cam_f((float)(wx - cam_x) * (1.0f / FX), (float)(wy - cam_y) * (1.0f / FX), (float)(wz - cam_z) * (1.0f / FX));+}++/* ------------------------------------------------------------------ triangles */+typedef struct { float x, y, w; } sv;++static void store(const sv *a, const sv *b, const sv *c, uint16_t col, uint8_t stip) {+ if (ntris >= MAX_TRIS) {+ rd_dropped = 1;+ return;+ }+ const sv *p[3] = {a, b, c};+ /* top to bottom */+ for (int i = 0; i < 2; i++)+ for (int j = 0; j < 2 - i; j++)+ if (p[j]->y > p[j + 1]->y) {+ const sv *t = p[j];+ p[j] = p[j + 1], p[j + 1] = t;+ }+ int y0 = iceil(p[0]->y - 0.5f), y1 = iceil(p[2]->y - 0.5f);+ if (y0 < 0) y0 = 0;+ if (y1 > SCREEN_H) y1 = SCREEN_H;+ if (y1 <= y0) return;+ float xmin = p[0]->x, xmax = p[0]->x;+ for (int i = 1; i < 3; i++) {+ if (p[i]->x < xmin) xmin = p[i]->x;+ if (p[i]->x > xmax) xmax = p[i]->x;+ }+ if (xmax < 0 || xmin > SCREEN_W) return;+ tri *t = &tris[ntris++];+ for (int i = 0; i < 3; i++) {+ t->x[i] = (int16_t)(p[i]->x * 16.0f);+ t->y[i] = (int16_t)(p[i]->y * 16.0f);+ t->w[i] = (uint16_t)(clampf(p[i]->w, 0.0f, 1.0f) * 65535.0f);+ }+ t->c = col, t->stip = stip, t->y0 = (int16_t)y0, t->y1 = (int16_t)y1;+}++/* a convex polygon on the screen, cut to the guard band when it reaches far outside */+static void screen_poly(sv *v, int n, uint16_t col, uint8_t stip) {+ bool far_out = false;+ for (int i = 0; i < n; i++)+ if (v[i].x < -GUARD || v[i].x > SCREEN_W + GUARD || v[i].y < -GUARD || v[i].y > SCREEN_H + GUARD) far_out = true;+ if (far_out) {+ static const float LIM[4] = {-GUARD, SCREEN_W + GUARD, -GUARD, SCREEN_H + GUARD};+ sv buf[2][12];+ int m = n;+ memcpy(buf[0], v, sizeof(sv) * (size_t)n);+ int cur = 0;+ for (int e = 0; e < 4 && m; e++) {+ sv *in = buf[cur], *out = buf[cur ^ 1];+ int k = 0;+ for (int i = 0; i < m; i++) {+ sv *A = &in[i], *B = &in[(i + 1) % m];+ float a = e < 2 ? A->x : A->y, b = e < 2 ? B->x : B->y;+ bool ain = (e & 1) ? a <= LIM[e] : a >= LIM[e], bin = (e & 1) ? b <= LIM[e] : b >= LIM[e];+ if (ain) out[k++] = *A;+ if (ain != bin && k < 12) {+ float t = (LIM[e] - a) / (b - a);+ sv q = {A->x + (B->x - A->x) * t, A->y + (B->y - A->y) * t, A->w + (B->w - A->w) * t};+ out[k++] = q;+ }+ }+ m = k, cur ^= 1;+ }+ for (int i = 1; i + 1 < m; i++) store(&buf[cur][0], &buf[cur][i], &buf[cur][i + 1], col, stip);+ return;+ }+ for (int i = 1; i + 1 < n; i++) store(&v[0], &v[i], &v[i + 1], col, stip);+}++/* a polygon in the camera's space (3 or 4 corners, convex), cut at the near plane, fogged, projected */+static void poly(const v3 *p, int n, const uint8_t *rgb, uint8_t stip) {+ v3 c[6];+ int m = 0;+ bool any_far = true;+ for (int i = 0; i < n; i++) {+ const v3 *A = &p[i], *B = &p[(i + 1) % n];+ bool ain = A->z >= NEAR, bin = B->z >= NEAR;+ if (A->z < FAR) any_far = false;+ if (ain) c[m++] = *A;+ if (ain != bin) {+ float t = (NEAR - A->z) / (B->z - A->z);+ v3 q = {A->x + (B->x - A->x) * t, A->y + (B->y - A->y) * t, NEAR};+ c[m++] = q;+ }+ }+ if (m < 3 || any_far) return;+ /* fog towards the horizon's colour */+ float zs = 0;+ for (int i = 0; i < n; i++) zs += p[i].z;+ zs /= (float)n;+ uint8_t col[3] = {rgb[0], rgb[1], rgb[2]};+ if (zs > FOG0) {+ int t = (int)(clampf((zs - FOG0) * (1.0f / (FAR - FOG0)), 0.0f, 0.9f) * 256.0f);+ mix3(col, rgb, fog, t);+ }+ sv s[6];+ for (int i = 0; i < m; i++) {+ float inv = 1.0f / c[i].z;+ s[i].x = CX + c[i].x * FOCAL * inv;+ s[i].y = CY - c[i].y * FOCAL * inv;+ s[i].w = NEAR * inv;+ }+ screen_poly(s, m, rd_rgb(col), stip);+}++static void quad(v3 a, v3 b, v3 c, v3 d, const uint8_t *rgb) {+ v3 p[4] = {a, b, c, d};+ poly(p, 4, rgb, 0);+}+static void tri3(v3 a, v3 b, v3 c, const uint8_t *rgb, uint8_t stip) {+ v3 p[3] = {a, b, c};+ poly(p, 3, rgb, stip);+}++/* a face of a solid object: only when it faces the camera (seen from outside its centre o) */+static bool facing(const v3 *p, int n, v3 o) {+ v3 u = {p[1].x - p[0].x, p[1].y - p[0].y, p[1].z - p[0].z}, v = {p[n - 1].x - p[0].x, p[n - 1].y - p[0].y, p[n - 1].z - p[0].z};+ v3 nn = {u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x};+ float fx = 0, fy = 0, fz = 0;+ for (int i = 0; i < n; i++) fx += p[i].x, fy += p[i].y, fz += p[i].z;+ fx /= (float)n, fy /= (float)n, fz /= (float)n;+ float out = nn.x * (fx - o.x) + nn.y * (fy - o.y) + nn.z * (fz - o.z);+ float view = nn.x * fx + nn.y * fy + nn.z * fz;+ return out * view < 0;+}++/* ------------------------------------------------------------------ objects: a frame of axes in the camera's space */+typedef struct {+ v3 o, r, u, f; /* origin, right, up, forward */+} frame;++static v3 at(const frame *F, float x, float y, float z) {+ v3 p = {F->o.x + F->r.x * x + F->u.x * y + F->f.x * z, F->o.y + F->r.y * x + F->u.y * y + F->f.y * z,+ F->o.z + F->r.z * x + F->u.z * y + F->f.z * z};+ return p;+}++/* an object standing at a world point, pointing at heading h (angle units); roll and pitch in radians */+static frame frame_at(int32_t wx, int32_t wy, int32_t wz, int32_t h, float roll, float pitch) {+ frame F;+ F.o = to_cam(wx, wy, wz);+ float s = fsinu(h), c = fcosu(h);+ v3 zero = to_cam_f(0, 0, 0);+ v3 R = to_cam_f(c, 0, -s), U = to_cam_f(0, 1, 0), Fw = to_cam_f(s, 0, c);+ R.x -= zero.x, R.y -= zero.y, R.z -= zero.z;+ U.x -= zero.x, U.y -= zero.y, U.z -= zero.z;+ Fw.x -= zero.x, Fw.y -= zero.y, Fw.z -= zero.z;+ /* small tilts: the body leans in a bend and pitches under braking */+ F.r = (v3){R.x + U.x * roll, R.y + U.y * roll, R.z + U.z * roll};+ F.u = (v3){U.x - R.x * roll + Fw.x * pitch, U.y - R.y * roll + Fw.y * pitch, U.z - R.z * roll + Fw.z * pitch};+ F.f = (v3){Fw.x - U.x * pitch, Fw.y - U.y * pitch, Fw.z - U.z * pitch};+ return F;+}++static void lquad(const frame *F, const float *a, const float *b, const float *c, const float *d, const uint8_t *rgb,+ bool solid, v3 centre) {+ v3 p[4] = {at(F, a[0], a[1], a[2]), at(F, b[0], b[1], b[2]), at(F, c[0], c[1], c[2]), at(F, d[0], d[1], d[2])};+ if (solid && !facing(p, 4, centre)) return;+ poly(p, 4, rgb, 0);+}++/* ------------------------------------------------------------------ cars */+static const float CAR_V[18][3] = {+ {-1.15f, 0.28f, -2.20f}, {1.15f, 0.28f, -2.20f}, {-1.08f, 0.82f, -2.12f}, {1.08f, 0.82f, -2.12f},+ {-1.20f, 0.24f, 0.20f}, {1.20f, 0.24f, 0.20f}, {-1.12f, 0.80f, 0.55f}, {1.12f, 0.80f, 0.55f},+ {-1.10f, 0.24f, 2.25f}, {1.10f, 0.24f, 2.25f}, {-1.02f, 0.64f, 2.15f}, {1.02f, 0.64f, 2.15f},+ {-1.04f, 0.84f, -1.30f}, {1.04f, 0.84f, -1.30f}, {-0.82f, 1.24f, -0.95f}, {0.82f, 1.24f, -0.95f},+ {-0.78f, 1.20f, 0.15f}, {0.78f, 1.20f, 0.15f}};+/* the body's faces: corners, and which colour (0 body, 1 side, 2 dark, 3 glass, 4 roof) */+static const uint8_t CAR_F[15][5] = {+ {0, 1, 3, 2, 2}, {2, 3, 13, 12, 0}, {12, 13, 15, 14, 3}, {14, 15, 17, 16, 4}, {16, 17, 7, 6, 3}, {6, 7, 11, 10, 0},+ {10, 11, 9, 8, 2}, {0, 4, 6, 2, 1}, {4, 8, 10, 6, 1}, {12, 6, 16, 14, 3}, {5, 1, 3, 7, 1}, {9, 5, 7, 11, 1},+ {7, 13, 15, 17, 3}, {2, 6, 12, 2, 1}, {3, 13, 7, 3, 1}};++typedef struct {+ int32_t wx, wy, wz, head;+ float roll, pitch, steer;+ int model;+ const uint8_t *paint;+ bool brake, flame, boost, smoke, ghost, near;+} car_pose;++static void horse(const frame *F, const car_pose *P, uint32_t clock);++static void car(const car_pose *P, uint32_t clock) {+ frame F = frame_at(P->wx, P->wy, P->wz, P->head, P->roll, P->pitch);+ if (F.o.z < -6.0f || F.o.z > FAR) return;+ if (F.o.z > 0 && (F.o.x > F.o.z * 1.2f + 6 || F.o.x < -F.o.z * 1.2f - 6)) return; /* out to the side */+ if (pg_vehicles[P->model].horse) {+ horse(&F, P, clock);+ return;+ }+ static const uint8_t GHOST[3] = {70, 220, 250};+ uint8_t b[3];+ for (int i = 0; i < 3; i++) b[i] = P->ghost ? GHOST[i] : P->paint[i];+ uint8_t col[5][3];+ for (int i = 0; i < 3; i++) {+ col[0][i] = b[i];+ col[1][i] = (uint8_t)(b[i] * 5 / 8);+ col[2][i] = (uint8_t)(b[i] * 3 / 4);+ col[3][i] = P->ghost ? (uint8_t)(b[i] * 3 / 4) : (uint8_t)(i == 0 ? 32 : i == 1 ? 48 : 75);+ col[4][i] = P->model == 1 && !P->ghost ? (uint8_t)(i == 2 ? 40 : 30) : b[i];+ }+ v3 centre = at(&F, 0, 0.6f, 0);+ float roof = P->model == 1 ? 1.18f : P->model == 2 ? 1.32f : 1.24f;+ v3 V[18];+ for (int i = 0; i < 18; i++) V[i] = at(&F, CAR_V[i][0], i >= 14 ? (i >= 16 ? roof - 0.04f : roof) : CAR_V[i][1], CAR_V[i][2]);+ bool far_away = F.o.z > 70.0f;+ uint8_t stip = P->ghost ? 1 : 0;+ if (!P->ghost) { /* the shadow */+ static const uint8_t SH[3] = {14, 14, 20};+ v3 s[4] = {at(&F, -1.25f, 0.04f, -2.3f), at(&F, 1.25f, 0.04f, -2.3f), at(&F, 1.25f, 0.04f, 2.3f), at(&F, -1.25f, 0.04f, 2.3f)};+ poly(s, 4, SH, 0);+ }+ for (int k = 0; k < 15; k++) {+ const uint8_t *f = CAR_F[k];+ if (far_away && (k == 9 || k >= 12)) continue;+ v3 p[4] = {V[f[0]], V[f[1]], V[f[2]], V[f[3]]};+ int n = f[3] == f[0] ? 3 : 4;+ if (!facing(p, n, centre)) continue;+ poly(p, n, col[f[4]], stip);+ }+ if (far_away) return;+ /* the wing, the lights, the plate, the wheels */+ static const uint8_t WING[3] = {35, 35, 42}, TYRE[3] = {24, 24, 28};+ float wl0[3] = {-1.14f, 1.08f, -2.08f}, wr0[3] = {1.14f, 1.08f, -2.08f}, wr1[3] = {1.14f, 1.02f, -1.78f},+ wl1[3] = {-1.14f, 1.02f, -1.78f};+ if (!P->ghost) lquad(&F, wl0, wr0, wr1, wl1, WING, false, centre);+ if (P->ghost) return;+ const pg_vehicle *veh = &pg_vehicles[P->model];+ uint8_t tl[3] = {(uint8_t)(P->brake ? 255 : 185), (uint8_t)(P->brake ? 55 : 15), (uint8_t)(P->brake ? 40 : 20)};+ float a0[3] = {-1.02f, 0.56f, -2.23f}, a1[3] = {-0.42f, 0.56f, -2.23f}, a2[3] = {-0.42f, 0.74f, -2.18f}, a3[3] = {-1.02f, 0.74f, -2.18f};+ lquad(&F, a0, a1, a2, a3, tl, true, centre);+ float b0[3] = {0.42f, 0.56f, -2.23f}, b1[3] = {1.02f, 0.56f, -2.23f}, b2[3] = {1.02f, 0.74f, -2.18f}, b3[3] = {0.42f, 0.74f, -2.18f};+ lquad(&F, b0, b1, b2, b3, tl, true, centre);+ float p0[3] = {-0.24f, 0.36f, -2.23f}, p1[3] = {0.24f, 0.36f, -2.23f}, p2[3] = {0.24f, 0.54f, -2.21f}, p3[3] = {-0.24f, 0.54f, -2.21f};+ lquad(&F, p0, p1, p2, p3, veh->accent, true, centre);+ static const float WX[4] = {-1.18f, 1.18f, -1.16f, 1.16f}, WZ[4] = {-1.38f, -1.38f, 1.38f, 1.38f};+ uint8_t hub[3] = {(uint8_t)(veh->accent[0] / 2), (uint8_t)(veh->accent[1] / 2), (uint8_t)(veh->accent[2] / 2)};+ for (int w = 0; w < 4; w++) {+ float xin = WX[w] > 0 ? WX[w] - 0.22f : WX[w] + 0.22f, xo = WX[w];+ float q0[3] = {xin, 0.05f, WZ[w] - 0.36f}, q1[3] = {xo, 0.05f, WZ[w] - 0.36f}, q2[3] = {xo, 0.58f, WZ[w] - 0.36f},+ q3[3] = {xin, 0.58f, WZ[w] - 0.36f};+ lquad(&F, q0, q1, q2, q3, TYRE, false, centre);+ float s0[3] = {xo, 0.08f, WZ[w] - 0.34f}, s1[3] = {xo, 0.08f, WZ[w] + 0.34f}, s2[3] = {xo, 0.56f, WZ[w] + 0.34f},+ s3[3] = {xo, 0.56f, WZ[w] - 0.34f};+ lquad(&F, s0, s1, s2, s3, hub, true, centre);+ }+ if (P->boost || P->flame) { /* nitro (blue) or a shift (orange), out of the exhausts */+ static const uint8_t FLAME[2][3] = {{255, 195, 40}, {40, 240, 255}};+ float len = P->boost ? ((clock / 40) & 1 ? -3.45f : -3.1f) : -2.9f;+ for (int side = -1; side <= 1; side += 2) {+ tri3(at(&F, side * 0.76f, 0.30f, -2.24f), at(&F, side * 0.36f, 0.30f, -2.24f), at(&F, side * 0.56f, 0.36f, len),+ FLAME[P->boost ? 1 : 0], 0);+ }+ }+ if (P->smoke) {+ static const uint8_t SMOKE[3] = {215, 215, 225};+ float j = (clock / 40) & 1 ? 0.25f : -0.25f;+ for (int side = -1; side <= 1; side += 2)+ tri3(at(&F, side * 1.25f + j, 0.10f, -2.1f), at(&F, side * 0.65f + j, 0.10f, -2.6f), at(&F, side * 0.95f, 0.75f, -2.5f),+ SMOKE, 1);+ }+}++/* Boris-TH's horses: a galloping body, head turned with the steering */+static void hq(const frame *F, float ax, float ay, float az, float bx, float by, float bz, float cx, float cy, float cz,+ float dx, float dy, float dz, const uint8_t *rgb, uint8_t stip) {+ v3 p[4] = {at(F, ax, ay, az), at(F, bx, by, bz), at(F, cx, cy, cz), at(F, dx, dy, dz)};+ poly(p, 4, rgb, stip);+}+static void ht(const frame *F, float ax, float ay, float az, float bx, float by, float bz, float cx, float cy, float cz,+ const uint8_t *rgb, uint8_t stip) {+ tri3(at(F, ax, ay, az), at(F, bx, by, bz), at(F, cx, cy, cz), rgb, stip);+}++static float fabsf_(float x) { return x < 0 ? -x : x; }+static float fsin(float x) { /* x in radians */+ int32_t a = (int32_t)(x * 10430.378f);+ return fsinu(a);+}++static void horse(const frame *F, const car_pose *P, uint32_t clock) {+ bool brown = P->model == 4, g = P->ghost;+ uint8_t stip = g ? 1 : 0;+ /* top, side, dark, mane: the ghost, the brown mustang, the black stallion */+ static const uint8_t COAT[3][4][3] = {{{70, 220, 250}, {55, 185, 225}, {40, 140, 180}, {90, 240, 255}},+ {{168, 98, 50}, {140, 78, 38}, {96, 52, 24}, {36, 22, 14}},+ {{38, 38, 48}, {24, 24, 32}, {14, 14, 20}, {10, 10, 14}}};+ int coat = g ? 0 : brown ? 1 : 2;+ const uint8_t *top = COAT[coat][0], *side = COAT[coat][1], *dark = COAT[coat][2], *mane = COAT[coat][3];+ float speed = P->near ? 1.0f : 0.8f;+ float phase = (float)clock * 0.0168f * speed;+ float bob = 0.06f * fabsf_(fsin(phase));+ float turn = clampf(P->steer * 0.45f, -0.45f, 0.45f);+ if (!g) {+ static const uint8_t SH[3] = {14, 14, 20};+ hq(F, -0.6f, 0.04f, -1.85f, 0.6f, 0.04f, -1.85f, 0.6f, 0.04f, 1.85f, -0.6f, 0.04f, 1.85f, SH, 0);+ }+ float y0 = 0.86f + bob, y1 = 1.44f + bob;+ /* the body */+ hq(F, -0.42f, y0, -1.38f, 0.42f, y0, -1.38f, 0.38f, y1, -1.28f, -0.38f, y1, -1.28f, dark, stip);+ hq(F, -0.38f, y1, -1.28f, 0.38f, y1, -1.28f, 0.40f, y1 + 0.02f, 0.08f, -0.40f, y1 + 0.02f, 0.08f, top, stip);+ hq(F, -0.40f, y1 + 0.02f, 0.08f, 0.40f, y1 + 0.02f, 0.08f, 0.36f, y1 + 0.08f, 1.18f, -0.36f, y1 + 0.08f, 1.18f, top, stip);+ hq(F, -0.36f, y1 + 0.08f, 1.18f, 0.36f, y1 + 0.08f, 1.18f, 0.42f, y0, 1.25f, -0.42f, y0, 1.25f, side, stip);+ hq(F, -0.42f, y0, -1.38f, -0.46f, y0 - 0.04f, 0.05f, -0.40f, y1 + 0.02f, 0.08f, -0.38f, y1, -1.28f, side, stip);+ hq(F, -0.46f, y0 - 0.04f, 0.05f, -0.42f, y0, 1.25f, -0.36f, y1 + 0.08f, 1.18f, -0.40f, y1 + 0.02f, 0.08f, side, stip);+ hq(F, 0.46f, y0 - 0.04f, 0.05f, 0.42f, y0, -1.38f, 0.38f, y1, -1.28f, 0.40f, y1 + 0.02f, 0.08f, side, stip);+ hq(F, 0.42f, y0, 1.25f, 0.46f, y0 - 0.04f, 0.05f, 0.40f, y1 + 0.02f, 0.08f, 0.36f, y1 + 0.08f, 1.18f, side, stip);+ if (!g) { /* the saddle */+ uint8_t sd[3] = {(uint8_t)(brown ? 75 : 185), (uint8_t)(brown ? 42 : 28), (uint8_t)(brown ? 20 : 35)};+ hq(F, -0.42f, y1 + 0.04f, -0.48f, 0.42f, y1 + 0.04f, -0.48f, 0.42f, y1 + 0.05f, 0.42f, -0.42f, y1 + 0.05f, 0.42f, sd, 0);+ }+ /* the neck and head */+ float nt = turn * 0.32f;+ hq(F, -0.22f, y1 - 0.06f, 0.88f, 0.22f, y1 - 0.06f, 0.88f, nt + 0.18f, y1 + 0.76f, 1.38f, nt - 0.18f, y1 + 0.76f, 1.38f, top, stip);+ hq(F, -0.20f, y1 - 0.18f, 1.34f, -0.22f, y1 - 0.06f, 0.88f, nt - 0.18f, y1 + 0.76f, 1.38f, nt - 0.16f, y1 + 0.52f, 1.72f, side, stip);+ hq(F, 0.22f, y1 - 0.06f, 0.88f, 0.20f, y1 - 0.18f, 1.34f, nt + 0.16f, y1 + 0.52f, 1.72f, nt + 0.18f, y1 + 0.76f, 1.38f, side, stip);+ hq(F, -0.20f, y1 - 0.18f, 1.34f, 0.20f, y1 - 0.18f, 1.34f, nt + 0.16f, y1 + 0.52f, 1.72f, nt - 0.16f, y1 + 0.52f, 1.72f, dark, stip);+ ht(F, 0.0f, y1 + 0.06f, 0.65f, nt * 0.5f, y1 + 0.52f, 0.95f, nt, y1 + 0.86f, 1.35f, mane, stip);+ float sx = turn * 0.52f;+ static const uint8_t WHITE_BLAZE[3] = {235, 230, 220};+ uint8_t blaze[3];+ for (int i = 0; i < 3; i++) blaze[i] = brown && !g ? WHITE_BLAZE[i] : top[i];+ hq(F, nt - 0.18f, y1 + 0.76f, 1.38f, nt + 0.18f, y1 + 0.76f, 1.38f, sx + 0.12f, y1 + 0.45f, 2.18f, sx - 0.12f, y1 + 0.45f, 2.18f, blaze, stip);+ hq(F, nt - 0.16f, y1 + 0.52f, 1.72f, nt - 0.18f, y1 + 0.76f, 1.38f, sx - 0.12f, y1 + 0.45f, 2.18f, sx - 0.11f, y1 + 0.25f, 2.10f, side, stip);+ hq(F, nt + 0.18f, y1 + 0.76f, 1.38f, nt + 0.16f, y1 + 0.52f, 1.72f, sx + 0.11f, y1 + 0.25f, 2.10f, sx + 0.12f, y1 + 0.45f, 2.18f, side, stip);+ hq(F, sx - 0.12f, y1 + 0.45f, 2.18f, sx + 0.12f, y1 + 0.45f, 2.18f, sx + 0.11f, y1 + 0.25f, 2.10f, sx - 0.11f, y1 + 0.25f, 2.10f, dark, stip);+ ht(F, nt - 0.18f, y1 + 0.74f, 1.40f, nt - 0.08f, y1 + 0.74f, 1.46f, nt - 0.14f, y1 + 1.02f, 1.36f, side, stip);+ ht(F, nt + 0.08f, y1 + 0.74f, 1.46f, nt + 0.18f, y1 + 0.74f, 1.40f, nt + 0.14f, y1 + 1.02f, 1.36f, side, stip);+ /* the tail */+ float sway = fsin(phase * 1.3f) * 0.20f - turn * 0.25f, lift = P->boost ? 0.32f : 0.0f;+ hq(F, -0.14f, y1 - 0.06f, -1.34f, 0.14f, y1 - 0.06f, -1.34f, sway + 0.22f, 0.85f + lift, -1.85f, sway - 0.22f, 0.85f + lift, -1.85f, mane, stip);+ ht(F, sway - 0.22f, 0.85f + lift, -1.85f, sway + 0.22f, 0.85f + lift, -1.85f, sway * 1.3f, 0.32f + lift, -2.20f, mane, stip);+ /* four legs at a gallop */+ static const float LX[4] = {-0.32f, 0.32f, -0.30f, 0.30f}, LZ[4] = {-1.10f, -1.10f, 1.02f, 1.02f}, LP[4] = {0.0f, 2.7f, 1.4f, 4.1f};+ for (int l = 0; l < 4; l++) {+ float a = phase + LP[l];+ float swing = fsin(a) * 0.52f, up = clampf(fsin(a + 1.5708f) * 0.28f, 0.0f, 0.30f);+ float tx = LX[l], tz = LZ[l], bz = LZ[l] + swing, by = 0.04f + up;+ hq(F, tx - 0.09f, y0 + 0.08f, tz - 0.10f, tx + 0.09f, y0 + 0.08f, tz + 0.10f, tx + 0.07f, by, bz + 0.08f, tx - 0.07f, by, bz - 0.08f, dark, stip);+ hq(F, tx, y0 + 0.08f, tz - 0.12f, tx, y0 + 0.08f, tz + 0.12f, tx, by, bz + 0.10f, tx, by, bz - 0.10f, side, stip);+ if (!g) {+ uint8_t hf[3] = {(uint8_t)(P->brake ? 255 : P->boost ? 40 : brown ? 225 : 195),+ (uint8_t)(P->brake ? 55 : P->boost ? 235 : brown ? 215 : 165),+ (uint8_t)(P->brake ? 35 : P->boost ? 255 : brown ? 195 : 90)};+ hq(F, tx - 0.10f, by, bz - 0.11f, tx + 0.10f, by, bz - 0.11f, tx + 0.10f, by + 0.16f, bz + 0.11f, tx - 0.10f, by + 0.16f, bz + 0.11f, hf, 0);+ }+ }+}++/* ------------------------------------------------------------------ the road */+enum { O_OUTL, O_WALLL, O_VERGEL, O_KERBL, O_LINEL, O_CL, O_CR, O_LINER, O_KERBR, O_VERGER, O_WALLR, O_OUTR, O_TOPL, O_TOPR, O_N };+static const float OFF[12] = {-38.5f, -12.5f, -9.2f, -8.0f, -7.7f, -0.15f, 0.15f, 7.7f, 8.0f, 9.2f, 12.5f, 38.5f};+static v3 node_pts[DRAW_SEGS + 4][O_N];++static void node_points(const pg_track *t, int32_t k, v3 *out) {+ int i = pg_slot(t, k);+ float nx = fcosu(t->nh[i]), nz = -fsinu(t->nh[i]);+ float bx = (float)(t->px[i] - cam_x) * (1.0f / FX), by = (float)(t->py[i] - cam_y) * (1.0f / FX),+ bz = (float)(t->pz[i] - cam_z) * (1.0f / FX);+ for (int o = 0; o < 12; o++) out[o] = to_cam_f(bx + nx * OFF[o], by, bz + nz * OFF[o]);+ out[O_TOPL] = to_cam_f(bx + nx * OFF[O_WALLL], by + 0.9f, bz + nz * OFF[O_WALLL]);+ out[O_TOPR] = to_cam_f(bx + nx * OFF[O_WALLR], by + 0.9f, bz + nz * OFF[O_WALLR]);+}++static void shade3(uint8_t *o, const uint8_t *c, int d) {+ for (int i = 0; i < 3; i++) o[i] = cl8(c[i] + d);+}++static void road_segment(const pg_track *t, int32_t k, const v3 *A, const v3 *B, int dist) {+ const theme *th = &THEMES[t->zone[pg_slot(t, k)] & 7];+ bool odd = k & 1;+ uint8_t road[3], kerb[3], white[3] = {225, 225, 230}, verge[3], out[3], wall[3];+ shade3(road, th->road, odd ? 0 : 6);+ shade3(verge, th->ground, odd ? 0 : 10);+ shade3(out, th->ground, odd ? -6 : -2);+ for (int i = 0; i < 3; i++) kerb[i] = odd ? white[i] : th->kerb[i];+ shade3(wall, th->wall, odd ? 0 : -24);+ bool detail = dist < DETAIL_SEGS;+ /* the start line: a band of squares */+ if (!t->endless && pg_slot(t, k) == 0) {+ static const uint8_t CHECK[2][3] = {{245, 245, 245}, {25, 25, 30}};+ for (int c = 0; c < 8; c++) {+ float f0 = (float)c / 8, f1 = (float)(c + 1) / 8;+ for (int row = 0; row < 2; row++) {+ float g0 = row * 0.5f, g1 = g0 + 0.5f;+ v3 la = {A[O_KERBL].x + (A[O_KERBR].x - A[O_KERBL].x) * f0, A[O_KERBL].y + (A[O_KERBR].y - A[O_KERBL].y) * f0, A[O_KERBL].z + (A[O_KERBR].z - A[O_KERBL].z) * f0};+ v3 lb = {A[O_KERBL].x + (A[O_KERBR].x - A[O_KERBL].x) * f1, A[O_KERBL].y + (A[O_KERBR].y - A[O_KERBL].y) * f1, A[O_KERBL].z + (A[O_KERBR].z - A[O_KERBL].z) * f1};+ v3 ma = {B[O_KERBL].x + (B[O_KERBR].x - B[O_KERBL].x) * f0, B[O_KERBL].y + (B[O_KERBR].y - B[O_KERBL].y) * f0, B[O_KERBL].z + (B[O_KERBR].z - B[O_KERBL].z) * f0};+ v3 mb = {B[O_KERBL].x + (B[O_KERBR].x - B[O_KERBL].x) * f1, B[O_KERBL].y + (B[O_KERBR].y - B[O_KERBL].y) * f1, B[O_KERBL].z + (B[O_KERBR].z - B[O_KERBL].z) * f1};+ v3 p0 = {la.x + (ma.x - la.x) * g0 * 0.4f, la.y + (ma.y - la.y) * g0 * 0.4f, la.z + (ma.z - la.z) * g0 * 0.4f};+ v3 p1 = {lb.x + (mb.x - lb.x) * g0 * 0.4f, lb.y + (mb.y - lb.y) * g0 * 0.4f, lb.z + (mb.z - lb.z) * g0 * 0.4f};+ v3 p2 = {lb.x + (mb.x - lb.x) * g1 * 0.4f, lb.y + (mb.y - lb.y) * g1 * 0.4f, lb.z + (mb.z - lb.z) * g1 * 0.4f};+ v3 p3 = {la.x + (ma.x - la.x) * g1 * 0.4f, la.y + (ma.y - la.y) * g1 * 0.4f, la.z + (ma.z - la.z) * g1 * 0.4f};+ quad(p0, p1, p2, p3, CHECK[(c + row) & 1]);+ }+ /* the rest of the segment: road */+ }+ v3 m0 = {A[O_KERBL].x + (B[O_KERBL].x - A[O_KERBL].x) * 0.4f, A[O_KERBL].y + (B[O_KERBL].y - A[O_KERBL].y) * 0.4f, A[O_KERBL].z + (B[O_KERBL].z - A[O_KERBL].z) * 0.4f};+ v3 m1 = {A[O_KERBR].x + (B[O_KERBR].x - A[O_KERBR].x) * 0.4f, A[O_KERBR].y + (B[O_KERBR].y - A[O_KERBR].y) * 0.4f, A[O_KERBR].z + (B[O_KERBR].z - A[O_KERBR].z) * 0.4f};+ quad(m0, m1, B[O_KERBR], B[O_KERBL], road);+ } else if (detail) {+ quad(A[O_KERBL], A[O_LINEL], B[O_LINEL], B[O_KERBL], white);+ quad(A[O_LINER], A[O_KERBR], B[O_KERBR], B[O_LINER], white);+ if (!odd) {+ static const uint8_t YEL[3] = {235, 205, 70};+ quad(A[O_LINEL], A[O_CL], B[O_CL], B[O_LINEL], road);+ quad(A[O_CL], A[O_CR], B[O_CR], B[O_CL], YEL);+ quad(A[O_CR], A[O_LINER], B[O_LINER], B[O_CR], road);+ } else {+ quad(A[O_LINEL], A[O_LINER], B[O_LINER], B[O_LINEL], road);+ }+ } else {+ quad(A[O_KERBL], A[O_KERBR], B[O_KERBR], B[O_KERBL], road);+ }+ quad(A[O_VERGEL], A[O_KERBL], B[O_KERBL], B[O_VERGEL], kerb);+ quad(A[O_KERBR], A[O_VERGER], B[O_VERGER], B[O_KERBR], kerb);+ quad(A[O_WALLL], A[O_VERGEL], B[O_VERGEL], B[O_WALLL], verge);+ quad(A[O_VERGER], A[O_WALLR], B[O_WALLR], B[O_VERGER], verge);+ if (dist < 26) {+ quad(A[O_OUTL], A[O_WALLL], B[O_WALLL], B[O_OUTL], out);+ quad(A[O_WALLR], A[O_OUTR], B[O_OUTR], B[O_WALLR], out);+ }+ if (dist < 24) { /* the barriers: their side facing the road */+ quad(A[O_WALLL], B[O_WALLL], B[O_TOPL], A[O_TOPL], wall);+ quad(B[O_WALLR], A[O_WALLR], A[O_TOPR], B[O_TOPR], wall);+ }+}++/* what stands at a segment */+static void prop(const pg_track *t, int32_t k, int dist, uint32_t clock) {+ int i = pg_slot(t, k);+ int p = t->prop[i] & 7, left = t->prop[i] & 8;+ const theme *th = &THEMES[t->zone[i] & 7];+ float nx = fcosu(t->nh[i]), nz = -fsinu(t->nh[i]), fx = fsinu(t->nh[i]), fz = fcosu(t->nh[i]);+ float bx = (float)(t->px[i] - cam_x) * (1.0f / FX), by = (float)(t->py[i] - cam_y) * (1.0f / FX),+ bz = (float)(t->pz[i] - cam_z) * (1.0f / FX);+ (void)clock;+ if (p == PROP_ARCH || p == PROP_GANTRY) {+ float aw = 13.2f, ah = p == PROP_ARCH ? 7.0f : 6.2f;+ static const uint8_t PIL[3] = {200, 200, 215}, PIL2[3] = {150, 150, 165};+ for (int s = -1; s <= 1; s += 2) {+ float px = bx + nx * aw * (float)s, pz = bz + nz * aw * (float)s;+ float w = 0.45f;+ v3 a = to_cam_f(px - fx * w, by, pz - fz * w), b = to_cam_f(px + fx * w, by, pz + fz * w);+ v3 c = to_cam_f(px + fx * w, by + ah, pz + fz * w), d = to_cam_f(px - fx * w, by + ah, pz - fz * w);+ quad(a, b, c, d, PIL);+ v3 e = to_cam_f(px - nx * w * (float)s - fx * w, by, pz - nz * w * (float)s - fz * w),+ f = to_cam_f(px - nx * w * (float)s - fx * w, by + ah, pz - nz * w * (float)s - fz * w);+ quad(a, e, f, d, PIL2);+ }+ if (p == PROP_ARCH) {+ bool start = !t->endless && i == 0;+ float y0 = by + ah - 1.4f, y1 = by + ah;+ int parts = start ? 8 : 1;+ static const uint8_t CHECK[2][3] = {{245, 245, 245}, {25, 25, 30}};+ for (int c = 0; c < parts; c++) {+ float s0 = -aw + 2 * aw * (float)c / (float)parts, s1 = -aw + 2 * aw * (float)(c + 1) / (float)parts;+ v3 a = to_cam_f(bx + nx * s0, y0, bz + nz * s0), b = to_cam_f(bx + nx * s1, y0, bz + nz * s1);+ v3 cc = to_cam_f(bx + nx * s1, y1, bz + nz * s1), d = to_cam_f(bx + nx * s0, y1, bz + nz * s0);+ if (start) quad(a, b, cc, d, CHECK[c & 1]);+ else quad(a, b, cc, d, th->kerb);+ }+ } else {+ static const uint8_t BEAM[3] = {70, 74, 90}, LIGHT[3] = {255, 240, 190};+ float y0 = by + ah - 0.5f, y1 = by + ah;+ v3 a = to_cam_f(bx - nx * aw, y0, bz - nz * aw), b = to_cam_f(bx + nx * aw, y0, bz + nz * aw);+ v3 c = to_cam_f(bx + nx * aw, y1, bz + nz * aw), d = to_cam_f(bx - nx * aw, y1, bz - nz * aw);+ quad(a, b, c, d, BEAM);+ if (dist < 20)+ for (int l = -1; l <= 1; l++) {+ float c0 = (float)l * 5.0f - 0.9f, c1 = c0 + 1.8f, ly = y0 - 0.02f;+ v3 p0 = to_cam_f(bx + nx * c0, ly, bz + nz * c0), p1 = to_cam_f(bx + nx * c1, ly, bz + nz * c1);+ v3 p2 = to_cam_f(bx + nx * c1 + fx * 0.6f, ly, bz + nz * c1 + fz * 0.6f), p3 = to_cam_f(bx + nx * c0 + fx * 0.6f, ly, bz + nz * c0 + fz * 0.6f);+ quad(p0, p1, p2, p3, LIGHT);+ }+ }+ return;+ }+ float side = left ? -1.0f : 1.0f;+ if (p == PROP_TREE) {+ if (dist > 26) return;+ float d = side * (12.5f + 3.6f);+ float tx = bx + nx * d, tz = bz + nz * d;+ if (th->lamps) {+ static const uint8_t POLE[3] = {70, 80, 100};+ float w = 0.16f;+ v3 a = to_cam_f(tx - fx * w, by, tz - fz * w), b = to_cam_f(tx + fx * w, by, tz + fz * w);+ v3 c = to_cam_f(tx + fx * w, by + 7.0f, tz + fz * w), dd = to_cam_f(tx - fx * w, by + 7.0f, tz - fz * w);+ quad(a, b, c, dd, POLE);+ v3 e = to_cam_f(tx - nx * w, by, tz - nz * w), f = to_cam_f(tx + nx * w, by, tz + nz * w);+ v3 g = to_cam_f(tx + nx * w, by + 7.0f, tz + nz * w), h = to_cam_f(tx - nx * w, by + 7.0f, tz - nz * w);+ quad(e, f, g, h, POLE);+ /* the lamp, leaning over the road */+ float hx = tx - nx * side * 2.2f, hz = tz - nz * side * 2.2f;+ v3 l0 = to_cam_f(tx, by + 7.0f, tz), l1 = to_cam_f(hx, by + 7.2f, hz);+ v3 l2 = to_cam_f(hx + fx * 0.5f, by + 7.0f, hz + fz * 0.5f);+ tri3(l0, l1, l2, POLE, 0);+ v3 q0 = to_cam_f(hx - fx * 0.5f, by + 6.95f, hz - fz * 0.5f), q1 = to_cam_f(hx + fx * 0.5f, by + 6.95f, hz + fz * 0.5f);+ v3 q2 = to_cam_f(hx + fx * 0.5f + nx * 0.6f, by + 6.95f, hz + fz * 0.5f + nz * 0.6f), q3 = to_cam_f(hx - fx * 0.5f + nx * 0.6f, by + 6.95f, hz - fz * 0.5f + nz * 0.6f);+ quad(q0, q1, q2, q3, th->tree);+ return;+ }+ /* a cone of five sides on a short trunk, lit from the left */+ static const uint8_t TRUNK[3] = {70, 48, 30};+ float r = 2.1f, h = 6.8f;+ v3 apex = to_cam_f(tx, by + h, tz);+ v3 base[5];+ for (int s = 0; s < 5; s++) {+ int32_t a = s * 13107 + (int32_t)(k * 977);+ base[s] = to_cam_f(tx + fsinu(a) * r, by + 0.7f, tz + fcosu(a) * r);+ }+ v3 cen = to_cam_f(tx, by + 2.5f, tz);+ for (int s = 0; s < 5; s++) {+ v3 p[3] = {base[s], base[(s + 1) % 5], apex};+ if (!facing(p, 3, cen)) continue;+ int32_t a = s * 13107 + 6553 + (int32_t)(k * 977) - (int32_t)t->nh[i];+ uint8_t c[3];+ shade3(c, th->tree, (int)(fsinu(a) * 22.0f));+ poly(p, 3, c, 0);+ }+ float w = 0.25f;+ v3 a = to_cam_f(tx - fx * w, by, tz - fz * w), b = to_cam_f(tx + fx * w, by, tz + fz * w);+ v3 c = to_cam_f(tx + fx * w, by + 0.8f, tz + fz * w), dd = to_cam_f(tx - fx * w, by + 0.8f, tz - fz * w);+ quad(a, b, c, dd, TRUNK);+ return;+ }+ if (p == PROP_CHEVRON) {+ if (dist > 22) return;+ float d = side * 13.0f;+ float sx = bx + nx * d, sz = bz + nz * d;+ static const uint8_t YEL[3] = {240, 185, 20}, BLK[3] = {25, 25, 30}, POST[3] = {90, 90, 100};+ v3 a = to_cam_f(sx - nx * 1.3f, by + 0.6f, sz - nz * 1.3f), b = to_cam_f(sx + nx * 1.3f, by + 0.6f, sz + nz * 1.3f);+ v3 c = to_cam_f(sx + nx * 1.3f, by + 2.2f, sz + nz * 1.3f), dd = to_cam_f(sx - nx * 1.3f, by + 2.2f, sz - nz * 1.3f);+ quad(a, b, c, dd, YEL);+ v3 p0 = to_cam_f(sx - nx * 0.15f, by, sz - nz * 0.15f), p1 = to_cam_f(sx + nx * 0.15f, by, sz + nz * 0.15f);+ v3 p2 = to_cam_f(sx + nx * 0.15f, by + 0.6f, sz + nz * 0.15f), p3 = to_cam_f(sx - nx * 0.15f, by + 0.6f, sz - nz * 0.15f);+ quad(p0, p1, p2, p3, POST);+ /* the arrow points into the bend (away from the side it stands on) */+ float dir = -side, e = -0.05f;+ for (int c2 = -1; c2 <= 1; c2 += 2) {+ float o = (float)c2 * 0.55f;+ v3 t0 = to_cam_f(sx + nx * (o - dir * 0.35f) + fx * e, by + 0.8f, sz + nz * (o - dir * 0.35f) + fz * e);+ v3 t1 = to_cam_f(sx + nx * (o + dir * 0.35f) + fx * e, by + 1.4f, sz + nz * (o + dir * 0.35f) + fz * e);+ v3 t2 = to_cam_f(sx + nx * (o - dir * 0.35f) + fx * e, by + 2.0f, sz + nz * (o - dir * 0.35f) + fz * e);+ tri3(t0, t1, t2, BLK, 0);+ }+ }+}++static void orb(const pg_track *t, int32_t k, uint32_t clock) {+ int i = pg_slot(t, k);+ int32_t s = k * t->seg + t->seg / 2, wx, wy, wz;+ pg_world(t, s, t->orb[i] * FX / 8, &wx, &wy, &wz);+ float ox = (float)(wx - cam_x) * (1.0f / FX), oz = (float)(wz - cam_z) * (1.0f / FX), gy = (float)(wy - cam_y) * (1.0f / FX);+ float oy = gy + 1.25f + 0.25f * fsinu((int32_t)(clock * 6) + k * 3000);+ int32_t ang = (int32_t)(clock * 16) + k * 5000;+ float rx = fcosu(ang) * 1.1f, rz = fsinu(ang) * 1.1f;+ v3 top = to_cam_f(ox, oy + 1.05f, oz), bot = to_cam_f(ox, oy - 0.85f, oz);+ v3 l = to_cam_f(ox - rx, oy + 0.1f, oz - rz), r = to_cam_f(ox + rx, oy + 0.1f, oz + rz);+ v3 f = to_cam_f(ox - rz, oy + 0.1f, oz + rx), b = to_cam_f(ox + rz, oy + 0.1f, oz - rx);+ static const uint8_t C0[3] = {60, 255, 255}, C1[3] = {0, 210, 255}, C2[3] = {20, 150, 245}, C3[3] = {255, 230, 80},+ PAD[3] = {0, 150, 210};+ v3 centre = to_cam_f(ox, oy, oz);+ v3 faces[8][3] = {{top, l, f}, {top, f, r}, {top, r, b}, {top, b, l}, {bot, f, l}, {bot, r, f}, {bot, b, r}, {bot, l, b}};+ const uint8_t *cols[8] = {C0, C1, C0, C1, C2, C3, C2, C3};+ for (int q = 0; q < 8; q++)+ if (facing(faces[q], 3, centre)) poly(faces[q], 3, cols[q], 0);+ float nx = fcosu(t->nh[i]), nz = -fsinu(t->nh[i]), fx = fsinu(t->nh[i]), fz = fcosu(t->nh[i]);+ v3 p0 = to_cam_f(ox - nx * 1.1f, gy + 0.05f, oz - nz * 1.1f), p1 = to_cam_f(ox + fx * 1.4f, gy + 0.05f, oz + fz * 1.4f);+ v3 p2 = to_cam_f(ox + nx * 1.1f, gy + 0.05f, oz + nz * 1.1f), p3 = to_cam_f(ox - fx * 1.4f, gy + 0.05f, oz - fz * 1.4f);+ quad(p0, p1, p2, p3, PAD);+}++/* ------------------------------------------------------------------ the background */+static void sky_for(int zone_a, int zone_b, int t256) {+ const theme *a = &THEMES[zone_a & 7], *b = &THEMES[zone_b & 7];+ mix3(sky_top, a->sky_top, b->sky_top, t256);+ mix3(sky_bot, a->sky_bot, b->sky_bot, t256);+ mix3(ground, a->ground, b->ground, t256);+ memcpy(fog, sky_bot, 3);+ for (int i = 0; i < 3; i++) hill[i] = (uint8_t)((sky_top[i] * 3 + sky_bot[i]) / 5);+}++static void setup_camera(int32_t x, int32_t y, int32_t z, int32_t yaw, float pitch, float roll) {+ cam_x = x, cam_y = y, cam_z = z, cam_yaw = yaw;+ cy_c = fcosu(yaw), cy_s = fsinu(yaw);+ float p2 = pitch * pitch, r2 = roll * roll;+ cp_c = 1 - p2 / 2 + p2 * p2 / 24, cp_s = pitch - pitch * p2 / 6;+ cr_c = 1 - r2 / 2, cr_s = roll - roll * r2 / 6;+ horizon = (int)(CY + FOCAL * cp_s / cp_c);+ /* the hills on the horizon turn with the camera: 1024 pixels a turn; three ranges laid over each other */+ int scroll = (int)(((uint32_t)yaw & 0xFFFF) >> 6);+ for (int x2 = 0; x2 < SCREEN_W; x2++) {+ int m = (x2 + scroll) & 1023;+ int a = (m % 128) - 64, b = ((m + 40) % 52) - 26, c = ((m + 11) % 20) - 10;+ int h = 26 - (a < 0 ? -a : a) * 14 / 64 - (b < 0 ? -b : b) * 7 / 26 - (c < 0 ? -c : c) * 3 / 10;+ hills[x2] = (uint8_t)(h < 1 ? 1 : h);+ }+ ntris = 0, rd_dropped = 0;+}++/* ------------------------------------------------------------------ frames */+static int32_t lerp(int32_t a, int32_t b, int alpha) { return a + (int32_t)((int64_t)(b - a) * alpha / 256); }++void rd_race(const pg_track *t, const pg_race *a, const pg_race *b, int alpha, int view, const rd_ghost *g,+ uint32_t clock) {+ const pg_car *ca = &a->car[0], *cb = &b->car[0];+ int32_t s = lerp(ca->s, cb->s, alpha), x = lerp(ca->x, cb->x, alpha);+ int32_t ang = ca->ang + (int32_t)((int64_t)(int16_t)(cb->ang - ca->ang) * alpha / 256);+ int32_t head = pg_heading_at(t, s) + ang;+ int32_t wx, wy, wz;+ pg_world(t, s, x, &wx, &wy, &wz);+ /* behind the car, a little above, looking where it goes */+ float dist = view == VIEW_FAR ? 9.5f : view == VIEW_BUMPER ? -0.6f : 6.8f;+ float high = view == VIEW_FAR ? 3.35f : view == VIEW_BUMPER ? 1.55f : 2.4f;+ bool horse_ = pg_vehicles[cb->model].horse;+ if (horse_ && view == VIEW_CHASE) dist = 6.6f, high = 2.5f;+ if (horse_ && view == VIEW_BUMPER) high = 2.6f, dist = -0.2f;+ int32_t sh = pg_sin(head), ch = pg_cos(head);+ int32_t cx = wx - (int32_t)(dist * (float)sh * (FX / 32767.0f)), cz = wz - (int32_t)(dist * (float)ch * (FX / 32767.0f));+ int32_t ground_y = wy;+ int32_t slope = pg_height_at(t, s + 12 * FX) - pg_height_at(t, s);+ float pitch = -0.11f + clampf((float)slope / (12.0f * FX) * 0.35f, -0.08f, 0.08f);+ float roll = -(float)cb->steer / 1024.0f * clampf((float)cb->v / (75.0f * FX), 0, 1) * 0.15f * 0.35f;+ setup_camera(cx, ground_y + (int32_t)(high * FX), cz, head, pitch, roll);+ /* the sky: the scenery here, blending into the one ahead */+ int32_t k0 = pg_seg_of(t, s);+ int za = t->zone[pg_slot(t, k0)], zb = t->zone[pg_slot(t, k0 + 14)], blend = 0;+ if (za != zb)+ for (int k = 1; k <= 14; k++) blend += t->zone[pg_slot(t, k0 + k)] == zb ? 18 : 0;+ sky_for(za, zb, blend > 256 ? 256 : blend);+ /* the road, from far to near (the depth buffer sorts it out, but the far pieces go first if room runs out) */+ int32_t kc = pg_seg_of(t, s - (int32_t)(dist > 0 ? dist * FX : 0)) - 1;+ int32_t kend = k0 + DRAW_SEGS;+ if (t->endless && kend > t->last) kend = t->last;+ if (t->endless && kc < t->first) kc = t->first;+ int nn = (int)(kend - kc + 1);+ if (nn > DRAW_SEGS + 4) nn = DRAW_SEGS + 4;+ for (int j = 0; j < nn; j++) node_points(t, kc + j, node_pts[j]);+ for (int j = nn - 2; j >= 0; j--) road_segment(t, kc + j, node_pts[j], node_pts[j + 1], (int)(kc + j - k0));+ for (int j = nn - 2; j >= 0; j--) {+ int32_t k = kc + j;+ int i = pg_slot(t, k);+ if (t->prop[i] & 7) prop(t, k, (int)(k - k0), clock);+ if (t->orb[i] != -128 && k - k0 < 28 && k >= k0 - 1) {+ bool here = t->endless ? k > b->last_orb : t->orb_id[i] >= 0 && !b->orb_wait[t->orb_id[i]];+ if (here) orb(t, k, clock);+ }+ }+ /* the rivals */+ for (int i = 1; i <= b->rivals; i++) {+ const pg_car *pa = &a->car[i], *pb = &b->car[i];+ int32_t rs = lerp(pa->s, pb->s, alpha);+ if (!t->endless) rs = s + pg_wrap(t, rs - s);+ if (rs < s - 30 * FX || rs > s + (DRAW_SEGS - 2) * t->seg) continue;+ car_pose P;+ memset(&P, 0, sizeof P);+ pg_world(t, rs, lerp(pa->x, pb->x, alpha), &P.wx, &P.wy, &P.wz);+ P.head = pg_heading_at(t, rs) + pb->ang;+ P.model = pb->model, P.paint = rd_paint[pb->paint & 7];+ P.brake = pb->v < pa->v - FX / 4, P.boost = pb->boost;+ car(&P, clock + (uint32_t)i * 97);+ }+ /* the ghost of your best lap */+ if (g && g->on) {+ int32_t gs = s + pg_wrap(t, g->s - pg_lap_s(b, t));+ if (gs > s - 20 * FX && gs < s + (DRAW_SEGS - 2) * t->seg) {+ car_pose P;+ memset(&P, 0, sizeof P);+ pg_world(t, gs, g->x, &P.wx, &P.wy, &P.wz);+ P.head = pg_heading_at(t, gs) + g->ang, P.model = g->model, P.ghost = true, P.near = true;+ P.paint = pg_vehicles[g->model].body;+ car(&P, clock);+ }+ }+ /* your car */+ if (view != VIEW_BUMPER) {+ car_pose P;+ memset(&P, 0, sizeof P);+ P.wx = wx, P.wy = wy, P.wz = wz;+ int32_t slip = ca->slip + (int32_t)((int64_t)(cb->slip - ca->slip) * alpha / 256);+ P.head = head + slip;+ P.model = cb->model, P.paint = pg_vehicles[cb->model].body;+ float spd = clampf((float)cb->v / (75.0f * FX), 0, 1);+ P.roll = clampf(-(float)cb->steer / 1024.0f * spd * 0.15f - (float)slip * (0.14f / 4700.0f), -0.2f, 0.2f);+ if (cb->bump || (cb->x > PG_ROAD || cb->x < -PG_ROAD)) P.roll += (clock / 40) & 1 ? 0.03f : -0.03f;+ P.pitch = cb->v < ca->v - FX / 6 ? -0.05f : cb->v > ca->v + FX / 8 ? 0.03f : 0.0f;+ P.steer = (float)cb->steer / 1024.0f;+ P.brake = cb->v < ca->v - FX / 6 || cb->drift;+ P.boost = cb->boost, P.flame = b->manual && pg_rpm(b) > pg_vehicles[cb->model].redline - 300;+ P.smoke = (cb->drift || cb->bump) && cb->v > 15 * FX;+ P.near = true;+ car(&P, clock);+ }+}++void rd_showroom(int vehicle, int32_t angle, int zone, uint32_t clock) {+ /* the car on the right of the screen: the camera to its left */+ setup_camera(-(int32_t)(2.3f * FX), (int32_t)(2.2f * FX), -(int32_t)(7.0f * FX), 0, -0.15f, 0);+ sky_for(zone, zone, 0);+ float ox = 2.3f, oy = -2.2f, oz = 7.0f; /* the turntable's middle, from the camera */+ for (int i = 0; i < 16; i++) {+ int32_t a0 = i * 65536 / 16 + angle / 2, a1 = (i + 1) * 65536 / 16 + angle / 2;+ v3 c = to_cam_f(ox, oy, oz), p = to_cam_f(ox + fcosu(a0) * 3.4f, oy, oz + fsinu(a0) * 3.4f),+ q = to_cam_f(ox + fcosu(a1) * 3.4f, oy, oz + fsinu(a1) * 3.4f);+ uint8_t col[3] = {(uint8_t)((i & 1) ? 40 : 58), (uint8_t)((i & 1) ? 36 : 52), (uint8_t)((i & 1) ? 70 : 92)};+ tri3(c, p, q, col, 0);+ }+ car_pose P;+ memset(&P, 0, sizeof P);+ P.head = angle, P.model = vehicle, P.paint = pg_vehicles[vehicle].body, P.brake = true, P.near = true, P.steer = 0.25f;+ car(&P, clock);+}++/* ------------------------------------------------------------------ drawing a strip */+static uint16_t zbuf[SCREEN_W * 24];+static const uint8_t BAYER[4][4] = {{0, 8, 2, 10}, {12, 4, 14, 6}, {3, 11, 1, 9}, {15, 7, 13, 5}};++static void row_fill(uint16_t *row, int y, const uint8_t *c) {+ uint16_t pat[4];+ for (int i = 0; i < 4; i++) {+ int d = BAYER[y & 3][i];+ int r = c[0] + (d >> 1), g = c[1] + (d >> 2), b = c[2] + (d >> 1);+ pat[i] = (uint16_t)((r > 255 ? 31 : r >> 3) << 11 | (g > 255 ? 63 : g >> 2) << 5 | (b > 255 ? 31 : b >> 3));+ }+ for (int x = 0; x < SCREEN_W; x += 4) row[x] = pat[0], row[x + 1] = pat[1], row[x + 2] = pat[2], row[x + 3] = pat[3];+}++static void raster(const tri *t, int ys, int ye) {+ float x0 = t->x[0] * (1.0f / 16), y0 = t->y[0] * (1.0f / 16), x1 = t->x[1] * (1.0f / 16), y1 = t->y[1] * (1.0f / 16),+ x2 = t->x[2] * (1.0f / 16), y2 = t->y[2] * (1.0f / 16);+ float w0 = t->w[0] * (1.0f / 65535), w1 = t->w[1] * (1.0f / 65535), w2 = t->w[2] * (1.0f / 65535);+ float dx1 = x1 - x0, dy1 = y1 - y0, dx2 = x2 - x0, dy2 = y2 - y0;+ float det = dx1 * dy2 - dx2 * dy1;+ if (det > -0.01f && det < 0.01f) return;+ float B = ((w1 - w0) * dy2 - (w2 - w0) * dy1) / det, C = (dx1 * (w2 - w0) - dx2 * (w1 - w0)) / det;+ float s02 = (x2 - x0) / (y2 - y0);+ float s01 = y1 > y0 ? (x1 - x0) / (y1 - y0) : 0, s12 = y2 > y1 ? (x2 - x1) / (y2 - y1) : 0;+ int ra = t->y0 > ys ? t->y0 : ys, rb = t->y1 < ye ? t->y1 : ye;+ uint16_t col = t->c;+ for (int r = ra; r < rb; r++) {+ float yc = (float)r + 0.5f;+ float xl = x0 + (yc - y0) * s02;+ float xs = yc < y1 ? x0 + (yc - y0) * s01 : x1 + (yc - y1) * s12;+ float xa = xl < xs ? xl : xs, xb = xl < xs ? xs : xl;+ xa = clampf(xa, -1.0f, SCREEN_W + 1.0f), xb = clampf(xb, -1.0f, SCREEN_W + 1.0f);+ int pa = iceil(xa - 0.5f), pb = iceil(xb - 0.5f);+ if (pa < 0) pa = 0;+ if (pb > SCREEN_W) pb = SCREEN_W;+ if (pb <= pa) continue;+ float wa = w0 + B * ((float)pa + 0.5f - x0) + C * (yc - y0);+ float wb = w0 + B * ((float)pb - 0.5f - x0) + C * (yc - y0);+ int32_t qa = (int32_t)(clampf(wa, 0, 1) * 1073741824.0f), qb = (int32_t)(clampf(wb, 0, 1) * 1073741824.0f);+ int n = pb - pa;+ int32_t dq = n > 1 ? (qb - qa) / (n - 1) : 0;+ uint16_t *z = zbuf + (r - gfx_y0) * SCREEN_W, *p = gfx_buf + (r - gfx_y0) * SCREEN_W;+ if (t->stip) {+ for (int x = pa; x < pb; x++, qa += dq) {+ if ((x + r) & 1) continue;+ uint16_t q = (uint16_t)(qa >> 14 > 65535 ? 65535 : qa >> 14);+ if (q > z[x]) z[x] = q, p[x] = col;+ }+ } else {+ for (int x = pa; x < pb; x++, qa += dq) {+ uint16_t q = (uint16_t)(qa >> 14 > 65535 ? 65535 : qa >> 14);+ if (q > z[x]) z[x] = q, p[x] = col;+ }+ }+ }+}++void rd_draw(void) {+ int ys = gfx_y0, ye = gfx_y1;+ rd_tris = ntris;+ for (int y = ys; y < ye; y++) {+ uint16_t *row = gfx_buf + (y - ys) * SCREEN_W;+ memset(zbuf + (y - ys) * SCREEN_W, 0, SCREEN_W * 2);+ uint8_t c[3];+ if (y < horizon) {+ int t = horizon > 0 ? y * 256 / horizon : 256;+ mix3(c, sky_top, sky_bot, t > 256 ? 256 : t);+ row_fill(row, y, c);+ uint16_t hc = rd_rgb(hill);+ int up = horizon - y;+ if (up <= 26)+ for (int x = 0; x < SCREEN_W; x++)+ if (hills[x] >= up) row[x] = hc;+ } else {+ int t = SCREEN_H > horizon ? (y - horizon) * 256 / (SCREEN_H - horizon) : 256;+ mix3(c, fog, ground, t > 256 ? 256 : t);+ row_fill(row, y, c);+ }+ }+ for (int i = 0; i < ntris; i++)+ if (tris[i].y1 > ys && tris[i].y0 < ye) raster(&tris[i], ys, ye);+}diff --git a/games/polygt3d/src/render.h b/games/polygt3d/src/render.hnew file mode 100644index 00000000..6ba52d8a--- /dev/null+++ b/games/polygt3d/src/render.h@@ -0,0 +1,25 @@+/* The 3D picture (render.c): the road, the roadside and the cars, flat-shaded triangles drawn with a depth buffer+ * a strip of the screen at a time. */+#ifndef PG_RENDER_H+#define PG_RENDER_H+#include "game.h"++typedef struct {+ bool on;+ int32_t s, x; /* where the ghost is */+ int32_t ang; /* where it points, from the road */+ uint8_t model;+} rd_ghost;++/* a frame of the race, between the step before (a) and the last one (b), alpha/256 of the way */+void rd_race(const pg_track *t, const pg_race *a, const pg_race *b, int alpha, int view, const rd_ghost *g,+ uint32_t clock_ms);+/* a car on a turntable, for the menus; zone: the scenery behind it */+void rd_showroom(int vehicle, int32_t angle, int zone, uint32_t clock_ms);+/* draws what was set up into the strip gfx_y0..gfx_y1 of gfx_buf */+void rd_draw(void);+/* whether the last frame ran out of room for triangles, and how many it had */+extern int rd_dropped, rd_tris;+uint16_t rd_rgb(const uint8_t c[3]);+extern const uint8_t rd_paint[8][3]; /* the rivals' paints */+#endifdiff --git a/games/polygt3d/src/save.c b/games/polygt3d/src/save.cnew file mode 100644index 00000000..9310b28c--- /dev/null+++ b/games/polygt3d/src/save.c@@ -0,0 +1,126 @@+/* The save (save.h): checked field by field; anything damaged, cut short or from elsewhere is not read: the copy in+ * the Python script is tried, then a fresh start. */+#include <stddef.h>+#include <string.h>+#include "plat.h"+#include "save.h"++void pg_fresh(pg_profile *p) {+ memset(p, 0, sizeof *p);+ p->laps = 3, p->rivals = 5, p->level = LEVEL_NORMAL;+}++static bool profile_ok(const pg_profile *p) {+ if (p->races > 999999 || p->wins > p->races || p->runs > 999999) return false;+ for (int i = 0; i < PG_CIRCUITS; i++) {+ if (p->best_ms[i] > PG_MAX_TIME || p->best_lap_ms[i] > PG_MAX_TIME) return false;+ if (p->best_ms[i] && (!p->best_lap_ms[i] || p->best_lap_ms[i] > p->best_ms[i])) return false;+ }+ if (p->best_m > PG_MAX_M || p->best_zone > 9999 || (p->best_zone && !p->best_m)) return false;+ return p->mode <= MODE_ENDLESS && p->track < PG_CIRCUITS && p->vehicle < PG_VEHICLES && p->laps >= 1 &&+ p->laps <= PG_MAX_LAPS && p->rivals <= PG_CARS - 1 && p->level <= LEVEL_HARD && p->manual <= 1 &&+ p->view < VIEWS && p->guide <= 1 && !p->spare[0] && !p->spare[1] && !p->spare[2];+}++bool pg_file_ok(const pg_file *f) {+ if (f->magic != PG_MAGIC || f->version != PG_VERSION || f->size != sizeof *f) return false;+ if (f->sum != pg_sum(f, offsetof(pg_file, sum))) return false;+ if (f->spare[0] || f->spare[1] || f->spare[2] || f->has_race > 1 || !profile_ok(&f->p)) return false;+ if (!f->has_race) {+ const uint8_t *b = (const uint8_t *)&f->race;+ for (unsigned i = 0; i < sizeof f->race; i++)+ if (b[i]) return false;+ return true;+ }+ return pg_valid(&f->race, NULL);+}++static const char head[] = "# PolyGT 3D keeps a copy of your progress here,\n"+ "# so that installing it again doesn't erase it.\n";+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+static uint8_t copy[1 + sizeof head + 2 + sizeof PG_SAVE_NAME + 1 + (sizeof(pg_file) + 2) / 3 * 4 + 2];++/* the copy: the file in base 64, in a comment line of a script */+static bool copy_write(const pg_file *f) {+ const uint8_t *bytes = (const uint8_t *)f;+ uint32_t len = sizeof *f, nl = sizeof PG_SAVE_NAME - 1;+ uint8_t *p = copy;+ *p++ = 0; /* (a script's first byte: not imported) */+ memcpy(p, head, sizeof head - 1), p += sizeof head - 1;+ *p++ = '#', *p++ = '>';+ memcpy(p, PG_SAVE_NAME, nl), p += nl;+ *p++ = ':';+ for (uint32_t i = 0; i < len; i += 3, p += 4) {+ uint32_t left = len - i;+ uint32_t v = (uint32_t)bytes[i] << 16 | (left > 1 ? (uint32_t)bytes[i + 1] << 8 : 0) | (left > 2 ? bytes[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';+ return plat_save(PG_COPY_NAME, copy, (uint32_t)(p - copy));+}++static int b64v(uint8_t c) {+ for (int i = 0; i < 64; i++)+ if ((uint8_t)b64[i] == c) return i;+ return -1;+}++static bool copy_read(pg_file *f) {+ uint32_t n, nl = sizeof PG_SAVE_NAME - 1;+ const uint8_t *c = plat_load(PG_COPY_NAME, &n);+ if (!c) return false;+ for (uint32_t i = 0; i + nl + 3 <= n; i++) {+ if (c[i] != '#' || c[i + 1] != '>' || memcmp(c + i + 2, PG_SAVE_NAME, nl) || c[i + 2 + nl] != ':') continue;+ const uint8_t *l = c + i + 3 + nl;+ uint32_t m = 0;+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;+ if (m != (sizeof *f + 2) / 3 * 4) return false;+ uint8_t *bytes = (uint8_t *)f;+ uint32_t o = 0;+ for (uint32_t k = 0; k < m; k += 4) {+ int v0 = b64v(l[k]), v1 = b64v(l[k + 1]), v2 = l[k + 2] == '=' ? 0 : b64v(l[k + 2]),+ v3 = l[k + 3] == '=' ? 0 : b64v(l[k + 3]);+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) return false;+ uint32_t w = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);+ if (o < sizeof *f) bytes[o++] = (uint8_t)(w >> 16);+ if (o < sizeof *f) bytes[o++] = (uint8_t)(w >> 8);+ if (o < sizeof *f) bytes[o++] = (uint8_t)w;+ }+ return true;+ }+ return false;+}++bool save_load(pg_file *f) {+ uint32_t n;+ const uint8_t *d = plat_load(PG_SAVE_NAME, &n);+ bool ok = false;+ if (d && n == sizeof *f) {+ memcpy(f, d, sizeof *f);+ ok = pg_file_ok(f);+ }+ if (!ok && copy_read(f) && pg_file_ok(f)) {+ ok = true;+ plat_save(PG_SAVE_NAME, f, sizeof *f); /* back where it belongs */+ }+ if (!ok) {+ memset(f, 0, sizeof *f);+ pg_fresh(&f->p);+ }+ return ok;+}++static pg_file out; /* (static: the stack stays small) */+bool save_write(const pg_file *f) {+ out = *f;+ out.magic = PG_MAGIC, out.version = PG_VERSION, out.size = sizeof out;+ memset(out.spare, 0, sizeof out.spare);+ if (!out.has_race) memset(&out.race, 0, sizeof out.race); /* (a race over is not kept) */+ out.sum = pg_sum(&out, offsetof(pg_file, sum));+ bool ok = plat_save(PG_SAVE_NAME, &out, sizeof out);+ copy_write(&out);+ return ok;+}diff --git a/games/polygt3d/src/save.h b/games/polygt3d/src/save.hnew file mode 100644index 00000000..e3e1b41c--- /dev/null+++ b/games/polygt3d/src/save.h@@ -0,0 +1,38 @@+/* What PolyGT 3D keeps, in polygt3d.sav: your choices on the race screen, your records and the race you left. A copy+ * goes into a Python script, polygt3d_saves.py (installing apps from the NumWorks website keeps only scripts, so the+ * save comes back from it). One format: a magic, a version, the size and a checksum; anything else is not read, and+ * the game starts afresh. */+#ifndef PG_SAVE_H+#define PG_SAVE_H+#include "game.h"++#define PG_SAVE_NAME "polygt3d.sav"+#define PG_COPY_NAME "polygt3d_saves.py"+#define PG_MAGIC 0x31544750u /* "PGT1" */+#define PG_VERSION 1+#define PG_MAX_TIME (99u * 60000u)+#define PG_MAX_M 2000000u /* (2000 km) */++typedef struct {+ uint32_t races, wins, runs; /* races finished, won; endless runs */+ uint32_t best_ms[PG_CIRCUITS], best_lap_ms[PG_CIRCUITS];+ uint32_t best_m; /* the endless road: the furthest (metres)... */+ uint16_t best_zone; /* ...and zones */+ uint8_t mode, track, vehicle, laps, rivals, level, manual, view, guide, spare[3];+} pg_profile;++typedef struct {+ uint32_t magic;+ uint16_t version, size;+ pg_profile p;+ uint8_t has_race, spare[3];+ pg_race race;+ uint32_t sum; /* FNV-1a of everything before it */+} pg_file;+_Static_assert(sizeof(pg_file) == 496, "polygt3d.sav: 496 bytes");++void pg_fresh(pg_profile *p);+bool pg_file_ok(const pg_file *f);+bool save_load(pg_file *f); /* the save, its copy, or a fresh start (false) */+bool save_write(const pg_file *f); /* with the magic, size and sum */+#endifdiff --git a/games/polygt3d/src/track.c b/games/polygt3d/src/track.cnew file mode 100644index 00000000..75d703b3--- /dev/null+++ b/games/polygt3d/src/track.c@@ -0,0 +1,363 @@+/* The roads: three circuits, each a loop of pieces (so many segments, a bend, a climb) made into segments with+ * eased bends and hills and closed exactly; and the endless road, laid segment by segment ahead of you from a+ * seed, its bends, hills and scenery changing as it goes. Whole numbers only (game.h). */+#include "game.h"++/* ------------------------------------------------------------------ fixed point */+static const int16_t SIN[257] = {+ 0, 201, 402, 603, 804, 1005, 1206, 1407, 1608, 1809, 2009, 2210, 2410, 2611, 2811, 3012,+ 3212, 3412, 3612, 3811, 4011, 4210, 4410, 4609, 4808, 5007, 5205, 5404, 5602, 5800, 5998, 6195,+ 6393, 6590, 6786, 6983, 7179, 7375, 7571, 7767, 7962, 8157, 8351, 8545, 8739, 8933, 9126, 9319,+ 9512, 9704, 9896, 10087, 10278, 10469, 10659, 10849, 11039, 11228, 11417, 11605, 11793, 11980, 12167, 12353,+ 12539, 12725, 12910, 13094, 13279, 13462, 13645, 13828, 14010, 14191, 14372, 14553, 14732, 14912, 15090, 15269,+ 15446, 15623, 15800, 15976, 16151, 16325, 16499, 16673, 16846, 17018, 17189, 17360, 17530, 17700, 17869, 18037,+ 18204, 18371, 18537, 18703, 18868, 19032, 19195, 19357, 19519, 19680, 19841, 20000, 20159, 20317, 20475, 20631,+ 20787, 20942, 21096, 21250, 21403, 21554, 21705, 21856, 22005, 22154, 22301, 22448, 22594, 22739, 22884, 23027,+ 23170, 23311, 23452, 23592, 23731, 23870, 24007, 24143, 24279, 24413, 24547, 24680, 24811, 24942, 25072, 25201,+ 25329, 25456, 25582, 25708, 25832, 25955, 26077, 26198, 26319, 26438, 26556, 26674, 26790, 26905, 27019, 27133,+ 27245, 27356, 27466, 27575, 27683, 27790, 27896, 28001, 28105, 28208, 28310, 28411, 28510, 28609, 28706, 28803,+ 28898, 28992, 29085, 29177, 29268, 29358, 29447, 29534, 29621, 29706, 29791, 29874, 29956, 30037, 30117, 30195,+ 30273, 30349, 30424, 30498, 30571, 30643, 30714, 30783, 30852, 30919, 30985, 31050, 31113, 31176, 31237, 31297,+ 31356, 31414, 31470, 31526, 31580, 31633, 31685, 31736, 31785, 31833, 31880, 31926, 31971, 32014, 32057, 32098,+ 32137, 32176, 32213, 32250, 32285, 32318, 32351, 32382, 32412, 32441, 32469, 32495, 32521, 32545, 32567, 32589,+ 32609, 32628, 32646, 32663, 32678, 32692, 32705, 32717, 32728, 32737, 32745, 32752, 32757, 32761, 32765, 32766,+ 32767};++int32_t pg_sin(int32_t a) {+ uint32_t u = (uint32_t)a & 0xFFFF;+ uint32_t q = u >> 14, i = (u >> 6) & 255;+ int32_t f = (int32_t)(u & 63), v;+ if (q & 1) v = SIN[256 - i] + (SIN[255 - i] - SIN[256 - i]) * f / 64;+ else v = SIN[i] + (SIN[i + 1] - SIN[i]) * f / 64;+ return q & 2 ? -v : v;+}+int32_t pg_cos(int32_t a) { return pg_sin(a + 16384); }++/* CORDIC: the angle of (x, y) in 1/65536 of a turn, 0 along x, growing towards y */+static const int32_t ATAN16[16] = {131072, 77376, 40884, 20753, 10417, 5213, 2607, 1304, 652, 326, 163, 81, 41, 20,+ 10, 5};+int32_t pg_atan2(int32_t y, int32_t x) {+ if (!x && !y) return 0;+ int64_t X = x, Y = y;+ int32_t a = 0;+ if (X < 0) X = -X, Y = -Y, a = 32768 * 16;+ while (X > (1 << 28) || Y > (1 << 28) || Y < -(1 << 28)) X /= 2, Y /= 2;+ X *= 4, Y *= 4;+ for (int i = 0; i < 16; i++) {+ int64_t nx;+ if (Y > 0) nx = X + (Y >> i), Y = Y - (X >> i), X = nx, a += ATAN16[i];+ else nx = X - (Y >> i), Y = Y + (X >> i), X = nx, a -= ATAN16[i];+ }+ return ((a + 8) >> 4) & 0xFFFF;+}++uint32_t pg_isqrt(uint64_t v) {+ uint64_t r = 0, b = (uint64_t)1 << 62;+ while (b > v) b >>= 2;+ while (b) {+ if (v >= r + b) v -= r + b, r = (r >> 1) + b;+ else r >>= 1;+ b >>= 2;+ }+ return (uint32_t)r;+}++uint32_t pg_rng(uint32_t *s) {+ uint32_t x = *s;+ x ^= x << 13, x ^= x >> 17, x ^= x << 5;+ return *s = x;+}++static int32_t wrap16(int32_t a) { return (int16_t)(uint16_t)(a & 0xFFFF); }++/* ------------------------------------------------------------------ circuits */+typedef struct {+ uint8_t len; /* segments */+ int16_t turn; /* degrees over the piece, + right */+ int8_t climb; /* metres */+} piece;++#define P(...) {__VA_ARGS__}+static const piece RIDGE[] = {+ P(24, 0, 0), P(18, 65, 2), P(8, 0, 3), P(9, -38, 2), P(9, 48, 0), P(14, 0, -4), P(22, 105, -3), P(38, 0, 0),+ P(9, -35, 2), P(6, 0, 2), P(11, 95, 0), P(12, 0, -4), P(14, 55, -3), P(10, 0, 0), P(9, -30, 2), P(12, 0, 0),+ P(13, 95, 0), P(10, 0, 0)};+static const piece WANGAN[] = {+ P(36, 0, 0), P(8, 10, 3), P(16, 0, 4), P(14, 95, 2), P(34, 0, 0), P(12, 85, -2), P(28, 0, -4), P(6, -18, 0),+ P(6, 18, 0), P(3, 0, 0), P(11, 50, 2), P(12, 0, 4), P(9, -25, 2), P(12, 0, 0), P(18, 130, -3), P(7, 0, -3),+ P(6, 15, -2), P(9, 0, 0)};+static const piece AKAGI[] = {+ P(14, 0, 0), P(10, 80, 4), P(6, 0, 5), P(8, -165, 4), P(10, 0, 7), P(8, 170, 5), P(10, 0, 6), P(9, -55, 3),+ P(9, 65, 2), P(8, 0, 0), P(9, -150, -2), P(10, 0, -6), P(8, 160, -5), P(12, 0, -8), P(12, 110, -6), P(9, -45, -4),+ P(43, 0, -3), P(11, 140, 0), P(7, 0, 0), P(9, -70, 0), P(24, 0, 0), P(13, 120, 0), P(8, 0, 0)};+#undef P++typedef struct {+ const piece *p;+ uint8_t n;+ uint8_t trees; /* a tree (or lamp) every so many segments */+ uint8_t gantry0, gantry1; /* lit gantries over the road from..to (segments) */+} circuit;+#define C(a, ...) {a, sizeof a / sizeof a[0], __VA_ARGS__}+static const circuit CIRCUITS[PG_CIRCUITS] = {C(RIDGE, 4, 56, 74), C(WANGAN, 3, 24, 120), C(AKAGI, 3, 0, 0)};+#undef C+const char *const pg_circuit_name[PG_CIRCUITS] = {"Ridge Valley GT", "Neo-Tokyo Wangan", "Mt. Akagi Touge"};+const char *const pg_circuit_note[PG_CIRCUITS] = {"Flowing bends", "Long straights", "Hairpins and climbs"};+const char *const pg_zone_name[5] = {"Alpine Valley", "Sunset Canyon", "Neon Wangan", "Glacier Pass", "Volcanic Ash"};++/* the fastest a car of grip 1 takes a bend: 24 m/s^2 sideways */+static uint8_t corner_limit(int32_t seg, int32_t turn) {+ if (turn < 0) turn = -turn;+ if (turn < 4) return 255;+ /* R = seg / (turn * 2pi / 65536); v = sqrt(24 R) */+ int64_t r_fx = (int64_t)seg * 65536 * 1000 / ((int64_t)turn * 6283);+ uint32_t v = pg_isqrt((uint64_t)(24 * r_fx / FX));+ return v > 255 ? 255 : (uint8_t)v;+}++static void finish_nodes(pg_track *t, int n) {+ /* headings from the positions: each segment's, then each node's halfway between its two segments */+ static uint16_t hs[PG_MAXN];+ for (int k = 0; k < n; k++) {+ int j = (k + 1) % n;+ hs[k] = (uint16_t)pg_atan2(t->px[j] - t->px[k], t->pz[j] - t->pz[k]);+ }+ for (int k = 0; k < n; k++) {+ int32_t a = hs[(k + n - 1) % n], b = hs[k];+ t->nh[k] = (uint16_t)(a + wrap16(b - a) / 2);+ }+ for (int k = 0; k < n; k++) t->cv[k] = (int16_t)wrap16(t->nh[(k + 1) % n] - t->nh[k]);+ for (int k = 0; k < n; k++) {+ int32_t c = (t->cv[(k + n - 1) % n] + 2 * t->cv[k] + t->cv[(k + 1) % n]) / 4;+ t->limit[k] = corner_limit(t->seg, c);+ }+}++void pg_build(pg_track *t, int id) {+ if (id < 0 || id >= PG_CIRCUITS) id = 0;+ const circuit *c = &CIRCUITS[id];+ static int32_t turn[PG_MAXN], climb[PG_MAXN], tmp[PG_MAXN];+ int n = 0;+ for (int i = 0; i < c->n; i++)+ for (int k = 0; k < c->p[i].len && n < PG_MAXN; k++, n++) {+ /* the piece's bend over its segments, in 1/16 angle unit; its climb in FX */+ turn[n] = (int32_t)c->p[i].turn * 65536 * 16 / 360 / c->p[i].len;+ climb[n] = (int32_t)c->p[i].climb * FX / c->p[i].len;+ }+ /* bends and hills ease in and out */+ for (int pass = 0; pass < 4; pass++) {+ for (int k = 0; k < n; k++) tmp[k] = (turn[(k + n - 1) % n] + 2 * turn[k] + turn[(k + 1) % n]) / 4;+ for (int k = 0; k < n; k++) turn[k] = tmp[k];+ for (int k = 0; k < n; k++) tmp[k] = (climb[(k + n - 1) % n] + 2 * climb[k] + climb[(k + 1) % n]) / 4;+ for (int k = 0; k < n; k++) climb[k] = tmp[k];+ }+ /* exactly one turn round, and back to the height it started at */+ int64_t st = 0, sc = 0;+ for (int k = 0; k < n; k++) st += turn[k], sc += climb[k];+ int32_t dt = (int32_t)(65536 * 16 - st), dc = (int32_t)-sc;+ int32_t rt = dt - dt / n * n, rc = dc - dc / n * n; /* (what's left, spread one by one) */+ for (int k = 0; k < n; k++) {+ turn[k] += dt / n + (k < rt ? 1 : 0) - (k < -rt ? 1 : 0);+ climb[k] += dc / n + (k < rc ? 1 : 0) - (k < -rc ? 1 : 0);+ }+ /* laid out, each segment along its middle heading */+ int32_t seg = PG_SEG;+ int64_t x = 0, y = 0, z = 0, h = 0;+ for (int k = 0; k < n; k++) {+ t->px[k] = (int32_t)x, t->py[k] = (int32_t)y, t->pz[k] = (int32_t)z;+ int32_t mid = (int32_t)((h + turn[k] / 2) / 16);+ x += (int64_t)seg * pg_sin(mid) / 32767;+ z += (int64_t)seg * pg_cos(mid) / 32767;+ y += climb[k];+ h += turn[k];+ }+ /* what's left of a closed loop, spread along it */+ for (int k = 0; k < n; k++) {+ t->px[k] -= (int32_t)(x * k / n);+ t->py[k] -= (int32_t)(y * k / n);+ t->pz[k] -= (int32_t)(z * k / n);+ }+ t->endless = 0, t->id = (uint8_t)id, t->n = (uint16_t)n, t->seg = seg, t->length = seg * n;+ t->first = 0, t->last = n - 1;+ finish_nodes(t, n);+ /* the roadside and the orbs */+ int orbs = 0;+ for (int k = 0; k < n; k++) {+ int32_t cv = t->cv[k];+ int side = (k & 1) ? 0 : 8;+ uint8_t p = PROP_NONE;+ if (k == 0 || k == n / 3 || k == 2 * n / 3) p = PROP_ARCH;+ else if (k >= c->gantry0 && k < c->gantry1 && k % 4 == 0) p = PROP_GANTRY;+ else if ((cv > 700 || cv < -700) && k % 2 == 0) p = PROP_CHEVRON, side = cv > 0 ? 8 : 0; /* on the outside */+ else if (k % c->trees == 0) p = PROP_TREE;+ t->prop[k] = (uint8_t)(p | (p ? side : 0));+ t->zone[k] = (uint8_t)id;+ t->orb[k] = -128, t->orb_id[k] = -1;+ if (k >= 8 && k % 15 == 8 && orbs < PG_ORBS) {+ int32_t x8;+ if (cv > 400) x8 = 34; /* towards the inside of the bend */+ else if (cv < -400) x8 = -34;+ else x8 = (int32_t)((uint32_t)(k * 2654435761u) >> 26) - 32; /* -32..31: up to 4 m off the middle */+ t->orb[k] = (int8_t)x8, t->orb_id[k] = (int8_t)orbs++;+ }+ }+ t->orbs = (uint8_t)orbs;+}++/* ------------------------------------------------------------------ the endless road */+#define R_MASK (PG_RING - 1)++/* lay one more segment from the end of the road */+static void lay(pg_track *t) {+ pg_gen *g = &t->gen;+ int32_t k = g->count;+ if (k > 0 && k % PG_ZONE == 0) g->zone = (uint8_t)((g->zone + 1 + pg_rng(&g->rng) % 4) % 5);+ /* bends: straights, sweepers and S-bends, sharper in the mountains */+ if (g->turn_hold <= 0) {+ uint32_t r = pg_rng(&g->rng) & 7;+ if (r < 2) {+ g->turn_to = 0, g->turn_hold = (int16_t)(10 + pg_rng(&g->rng) % 14);+ } else {+ /* (1/16 angle unit a segment: sweepers from a 600 m bend down to 105 m, 70 m in the mountains) */+ int32_t hi = (g->zone == 3 || g->zone == 4) ? 14000 : 9300;+ int32_t mag = 1700 + (int32_t)(pg_rng(&g->rng) % (uint32_t)(hi - 1700));+ g->turn_to = (pg_rng(&g->rng) & 1) ? mag : -mag;+ g->turn_hold = (int16_t)(12 + pg_rng(&g->rng) % 18);+ }+ }+ g->turn_hold--;+ g->turn += (g->turn_to - g->turn) * 46 / 256;+ /* hills: steeper in the mountains, flat on the expressway */+ if (g->slope_hold <= 0) {+ int32_t max = g->zone == 3 ? 150 : g->zone == 4 || g->zone == 1 ? 120 : g->zone == 2 ? 45 : 90; /* FX a seg */+ g->slope_to = (int32_t)(pg_rng(&g->rng) % (uint32_t)(2 * max + 1)) - max;+ g->slope_hold = (int16_t)(10 + pg_rng(&g->rng) % 16);+ }+ g->slope_hold--;+ g->slope += (g->slope_to - g->slope) * 41 / 256;+ /* keep the road within a few hundred metres up or down */+ if (g->y > 60 * FX && g->slope > 0) g->slope -= 8;+ if (g->y < -60 * FX && g->slope < 0) g->slope += 8;++ int s = k & R_MASK;+ int32_t head = g->head + g->turn / 32; /* the segment's middle heading */+ t->px[s] = g->x, t->py[s] = g->y, t->pz[s] = g->z;+ t->zone[s] = (uint8_t)(3 + g->zone);+ /* the node's heading: halfway between the segment before and this one */+ int32_t hs = head;+ if (k == 0) g->prev_head = hs;+ t->nh[s] = (uint16_t)(g->prev_head + wrap16(hs - g->prev_head) / 2);+ if (k > 0) {+ int p = (k - 1) & R_MASK;+ t->cv[p] = (int16_t)wrap16(t->nh[s] - t->nh[p]);+ t->limit[p] = corner_limit(t->seg, t->cv[p]);+ }+ g->prev_head = hs;+ g->x += (int32_t)((int64_t)t->seg * pg_sin(hs) / 32767);+ g->z += (int32_t)((int64_t)t->seg * pg_cos(hs) / 32767);+ g->y += g->slope;+ g->head += g->turn / 16;+ /* the roadside: a gate at each new scenery, gantries on the expressway, chevrons on the outside of bends */+ int32_t bend = g->turn / 16;+ uint8_t p = PROP_NONE;+ int side = (k & 1) ? 0 : 8;+ if (k > 0 && k % PG_ZONE == 0) p = PROP_ARCH;+ else if (g->zone == 2 && k % 4 == 0) p = PROP_GANTRY;+ else if ((bend > 450 || bend < -450) && k % 2 == 0) p = PROP_CHEVRON, side = bend > 0 ? 8 : 0;+ else if (k % 3 == 0) p = PROP_TREE;+ t->prop[s] = (uint8_t)(p | (p ? side : 0));+ t->orb[s] = -128, t->orb_id[s] = -1;+ if (k >= 6 && k % 12 == 6) {+ int32_t x8 = bend > 250 ? 32 : bend < -250 ? -32 : (int32_t)(pg_rng(&g->rng) % 65) - 32;+ t->orb[s] = (int8_t)x8;+ }+ g->count = k + 1;+ t->last = k - 1; /* (the last segment whose bend is known) */+ t->first = k + 1 - PG_RING;+ if (t->first < 0) t->first = 0;+}++void pg_endless(pg_track *t, uint32_t seed) {+ t->endless = 1, t->n = 0, t->seg = PG_SEG, t->length = 0, t->orbs = 0;+ pg_gen *g = &t->gen;+ g->rng = seed ? seed : 0x9E3779B9u;+ for (int i = 0; i < 4; i++) pg_rng(&g->rng);+ g->zone = (uint8_t)(pg_rng(&g->rng) % 5);+ t->id = g->zone;+ g->head = 0, g->turn = 0, g->turn_to = 0, g->turn_hold = 14, g->slope = 0, g->slope_to = 0, g->slope_hold = 10;+ g->count = 0, g->x = g->y = g->z = 0, g->prev_head = 0, g->spare = 0;+ t->first = 0, t->last = -1;+ pg_extend(t, 60);+}++void pg_extend(pg_track *t, int32_t upto) {+ if (!t->endless) return;+ while (t->last < upto) lay(t);+}++int pg_slot(const pg_track *t, int32_t k) {+ if (t->endless) return (int)(k & R_MASK);+ int32_t n = t->n, m = k % n;+ return (int)(m < 0 ? m + n : m);+}++int32_t pg_seg_of(const pg_track *t, int32_t s) {+ int32_t q = s / t->seg;+ if (s < 0 && q * t->seg != s) q--;+ return q;+}++int32_t pg_heading_at(const pg_track *t, int32_t s) {+ int32_t k = pg_seg_of(t, s), f = s - k * t->seg;+ int i = pg_slot(t, k);+ return (int32_t)t->nh[i] + (int32_t)((int64_t)t->cv[i] * f / t->seg);+}++int32_t pg_height_at(const pg_track *t, int32_t s) {+ int32_t k = pg_seg_of(t, s), f = s - k * t->seg;+ int i = pg_slot(t, k), j = pg_slot(t, k + 1);+ return t->py[i] + (int32_t)((int64_t)(t->py[j] - t->py[i]) * f / t->seg);+}++void pg_world(const pg_track *t, int32_t s, int32_t x, int32_t *wx, int32_t *wy, int32_t *wz) {+ int32_t k = pg_seg_of(t, s), f = s - k * t->seg;+ int i = pg_slot(t, k), j = pg_slot(t, k + 1);+ int32_t h = (int32_t)t->nh[i] + (int32_t)((int64_t)t->cv[i] * f / t->seg);+ *wx = t->px[i] + (int32_t)((int64_t)(t->px[j] - t->px[i]) * f / t->seg) + (int32_t)((int64_t)x * pg_cos(h) / 32767);+ *wz = t->pz[i] + (int32_t)((int64_t)(t->pz[j] - t->pz[i]) * f / t->seg) - (int32_t)((int64_t)x * pg_sin(h) / 32767);+ *wy = t->py[i] + (int32_t)((int64_t)(t->py[j] - t->py[i]) * f / t->seg);+}++int32_t pg_wrap(const pg_track *t, int32_t ds) {+ if (t->endless) return ds;+ int32_t L = t->length;+ ds %= L;+ if (ds >= L / 2) ds -= L;+ if (ds < -L / 2) ds += L;+ return ds;+}++int pg_zone_at(const pg_track *t, int32_t s) { return t->zone[pg_slot(t, pg_seg_of(t, s))]; }++/* the outline of a circuit, fit in w x h (y down, north up) */+int pg_map(const pg_track *t, int n, int16_t *xs, int16_t *ys, int w, int h) {+ int32_t x0 = t->px[0], x1 = x0, z0 = t->pz[0], z1 = z0;+ int nn = t->endless ? PG_RING : t->n;+ int32_t base = t->endless ? t->first : 0;+ for (int k = 0; k < nn; k++) {+ int i = pg_slot(t, base + k);+ if (t->px[i] < x0) x0 = t->px[i];+ if (t->px[i] > x1) x1 = t->px[i];+ if (t->pz[i] < z0) z0 = t->pz[i];+ if (t->pz[i] > z1) z1 = t->pz[i];+ }+ int32_t sx = x1 - x0 + 1, sz = z1 - z0 + 1;+ int32_t scale_n = w * sz > h * sx ? h : w, scale_d = w * sz > h * sx ? sz : sx; /* the tighter fit */+ int32_t ox = (w - (int32_t)((int64_t)sx * scale_n / scale_d)) / 2, oy = (h - (int32_t)((int64_t)sz * scale_n / scale_d)) / 2;+ for (int i = 0; i < n; i++) {+ int k = pg_slot(t, base + (int32_t)((int64_t)i * nn / n));+ xs[i] = (int16_t)(ox + (int64_t)(t->px[k] - x0) * scale_n / scale_d);+ ys[i] = (int16_t)(h - 1 - oy - (int64_t)(t->pz[k] - z0) * scale_n / scale_d);+ }+ return n;+}diff --git a/games/polygt3d/tests/play.c b/games/polygt3d/tests/play.cnew file mode 100644index 00000000..eb89fe08--- /dev/null+++ b/games/polygt3d/tests/play.c@@ -0,0 +1,1056 @@+/* PolyGT 3D on a computer, for tests and pictures (make host, make test).+ *+ * play test DIR the roads, laps, physics, crashes, the rivals finishing every circuit at every level, a+ * driver finishing races, the endless road, the whole app through its keys, saves written and+ * read back, damaged saves, a full storage, a few hundred sessions of random keys, and the same+ * race twice, to the same hash on every computer+ * play shots DIR pictures of the screens (DIR/<name>.ppm)+ * play docs DIR the README's pictures (DIR/<name>.ppm)+ * play film DIR MS T [VIEW CAR STEP] MS milliseconds of a race on circuit T, a driver at the wheel, a frame every+ * STEP ms (DIR/<frame>_<ms>.raw, for tools/record.py --frames)+ */+#define main pg_app_main+#include "../src/main.c"+#undef main+#include <stddef.h>+#include <stdio.h>+#include <stdlib.h>++/* ---------------------------------------------------------------- the calculator, on a computer */+static uint16_t fb[240][320];+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ for (int j = 0; j < h; j++)+ if (y + j < 240)+ for (int i = 0; i < w; i++) fb[y + j][x + i] = px[j * w + i];+}+void *np_alloc(uint32_t n) { (void)n; return 0; }+static double clock_ms;+static uint32_t (*script)(uint32_t frame);+static uint32_t frame_no, quit_at;+static void (*watch)(void);+uint32_t plat_keys(void) {+ clock_ms += 5;+ frame_no++;+ if (watch) watch();+ if (frame_no >= quit_at) return PK_HOME;+ return script ? script(frame_no) : 0;+}+uint32_t plat_millis(void) { return (uint32_t)clock_ms; }+void plat_sleep(uint32_t ms) { clock_ms += ms; }+void plat_vblank(void) {}+static uint32_t rnd_state = 1;+uint32_t plat_random(void) { return pg_rng(&rnd_state); }+bool plat_slow(void) { return false; }+void plat_begin(void) {}+int plat_end(void) { return 0; }++static struct { char name[32]; uint8_t data[4096]; uint32_t len; bool on; } files[4];+static bool storage_full;+bool plat_save(const char *name, const void *data, uint32_t len) {+ if (storage_full) return false;+ int k = -1;+ for (int i = 0; i < 4; i++)+ if (files[i].on && !strcmp(files[i].name, name)) k = i;+ for (int i = 0; i < 4 && k < 0; i++)+ if (!files[i].on) k = i;+ if (k < 0 || len > sizeof files[k].data) return false;+ strcpy(files[k].name, name), memcpy(files[k].data, data, len), files[k].len = len, files[k].on = true;+ return true;+}+const uint8_t *plat_load(const char *name, uint32_t *len) {+ for (int i = 0; i < 4; i++)+ if (files[i].on && !strcmp(files[i].name, name)) return *len = files[i].len, files[i].data;+ return 0;+}+static void forget(const char *name) {+ for (int i = 0; i < 4; i++)+ if (files[i].on && !strcmp(files[i].name, name)) files[i].on = false;+}+static uint8_t *file_data(const char *name, uint32_t *len) {+ for (int i = 0; i < 4; i++)+ if (files[i].on && !strcmp(files[i].name, name)) return *len = files[i].len, files[i].data;+ return 0;+}++static void shot(const char *dir, const char *name) {+ char path[512];+ snprintf(path, sizeof path, "%s/%s.ppm", dir, name);+ FILE *f = fopen(path, "wb");+ if (!f) exit(2);+ fprintf(f, "P6 320 240 255\n");+ for (int y = 0; y < 240; y++)+ for (int x = 0; x < 320; x++) {+ uint16_t c = fb[y][x];+ fputc((c >> 11) * 255 / 31, f), fputc((c >> 5 & 63) * 255 / 63, f), fputc((c & 31) * 255 / 31, f);+ }+ fclose(f);+}++static int fails;+static const char *const LEVELS[3] = {"Easy", "Normal", "Hard"};+#define RACE_HASH 0x8932C86Au /* (made on a Mac with clang; Linux with GCC must agree) */+#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)++/* ---------------------------------------------------------------- a driver */+/* it drives as a good player would: the rivals' line (out, in, out), steering for the bend ahead with taps of the+ keys, braking for the slowest bend coming up with the tyres it has, round slower cars, nitro on the straights;+ skill 0..100 (how much of the grip it dares) */+static int bot_skill = 100;+static int32_t bot_line;+static unsigned bot(const pg_race *r, const pg_track *t) {+ const pg_car *c = &r->car[0];+ int32_t v = c->v, k0 = pg_seg_of(t, c->s);+ int32_t grip = (int32_t)pg_vehicles[c->model].grip * (t->zone[pg_slot(t, k0)] == 2 ? 118 : 128) / 128;+ if (abs(c->x) > PG_ROAD + PG_KERB) grip = grip * 92 / 128;+ int64_t aim2 = (int64_t)200 * FX * 200 * FX;+ for (int k = 0; k < 30; k++) {+ int sl = pg_slot(t, k0 + k);+ int64_t vl = (int64_t)t->limit[sl] * FX;+ vl = vl * pg_isqrt((uint64_t)grip * 128) / 128 * (84 + bot_skill * 18 / 100) / 100;+ int64_t d = (int64_t)(k0 + k) * t->seg - c->s - 4 * FX;+ if (d < 0) d = 0;+ int64_t v2 = vl * vl + 2LL * 24 * FX * d;+ if (v2 < aim2) aim2 = v2;+ }+ int32_t aim = (int32_t)pg_isqrt((uint64_t)aim2);+ /* the line: out before a bend, in at its middle */+ int32_t near = 0, far = 0;+ for (int k = 0; k < 4; k++) near += t->cv[pg_slot(t, k0 + k)];+ for (int k = 4; k < 13; k++) far += t->cv[pg_slot(t, k0 + k)];+ int32_t line = (int32_t)((int64_t)(near * 3 - far) * 6 * FX / 3000);+ /* a slower car close ahead in the way: go round it */+ for (int j = 1; j <= r->rivals; j++) {+ int32_t ds = pg_wrap(t, r->car[j].s - c->s);+ if (ds > 0 && ds < 25 * FX && abs(r->car[j].x - c->x) < 3 * FX && r->car[j].v < v + FX)+ bot_line = r->car[j].x > 0 ? r->car[j].x - 4 * FX : r->car[j].x + 4 * FX;+ }+ bot_line -= bot_line / 32;+ int32_t target = line + bot_line;+ if (target > 6 * FX) target = 6 * FX;+ if (target < -6 * FX) target = -6 * FX;+ unsigned in = 0;+ if (v > aim + FX / 2) in |= IN_BRAKE;+ else in |= IN_GAS;+ /* steering: what the bend needs at this speed, plus a heading back towards the line */+ int32_t cv = t->cv[pg_slot(t, k0)];+ int32_t want_ang = (target - c->x) / 16;+ if (want_ang > 2500) want_ang = 2500;+ if (want_ang < -2500) want_ang = -2500;+ int64_t road = (int64_t)cv * v / t->seg; /* angle units a second */+ int64_t turn = road + (int64_t)(want_ang - c->ang) * 4; /* ...and the correction, over a quarter second */+ int32_t lat = 24 * FX * grip / 128;+ int32_t hold = v > FX ? (int32_t)((int64_t)lat * 10430 / v) : 14394;+ int32_t lock = hold + hold / 6 < 14394 ? hold + hold / 6 : 14394;+ int32_t auth = v >= 12 * FX ? 256 : v * 256 / (12 * FX);+ int32_t full = (int32_t)((int64_t)lock * auth / 256);+ int32_t steer = full > 0 ? (int32_t)(turn * 1024 / full) : 0;+ if (steer > 1024) steer = 1024;+ if (steer < -1024) steer = -1024;+ if (c->steer < steer - 60) in |= IN_RIGHT;+ else if (c->steer > steer + 60) in |= IN_LEFT;+ if (!(in & IN_BRAKE) && aim > v + 20 * FX && c->nitro > 300 && abs(c->ang) < 1500) in |= IN_NITRO;+ return in;+}++static uint32_t hash_race(const pg_race *r, uint32_t h) { return h ^ pg_sum(r, sizeof *r) * 16777619u; }++/* ---------------------------------------------------------------- the roads */+static pg_track TT;+static pg_setup plain(int mode, int id, int vehicle, int rivals, int level) {+ pg_setup s;+ memset(&s, 0, sizeof s);+ s.mode = (uint8_t)mode, s.track = (uint8_t)id, s.vehicle = (uint8_t)vehicle, s.laps = 3, s.rivals = (uint8_t)rivals;+ s.level = (uint8_t)level;+ return s;+}++static int64_t dist2(const pg_track *t, int a, int b) {+ int64_t dx = (t->px[a] - t->px[b]) / FX, dz = (t->pz[a] - t->pz[b]) / FX;+ return dx * dx + dz * dz;+}++static void roads(void) {+ for (int id = 0; id < PG_CIRCUITS; id++) {+ pg_build(&TT, id);+ int n = TT.n;+ CHECK(n > 200 && n <= PG_MAXN && TT.length == n * TT.seg, "%s: %d segments", pg_circuit_name[id], n);+ int64_t turn = 0;+ int jerk = 0, steep = 0, close = 0, gaps = 0;+ for (int k = 0; k < n; k++) {+ turn += TT.cv[k];+ if (abs(TT.cv[(k + 1) % n] - TT.cv[k]) > 1200) jerk++;+ if (abs(TT.py[(k + 1) % n] - TT.py[k]) > FX * 9 / 10) steep++; /* no more than 15% */+ int64_t d2 = dist2(&TT, k, (k + 1) % n);+ if (d2 < 5 * 5 || d2 > 7 * 7) gaps++;+ for (int j = k + 8; j < n && j < k + n - 8; j++)+ if (dist2(&TT, k, j) < 32 * 32) close++;+ }+ CHECK(turn == ANG_TURN, "%s: turns %lld, not one turn round", pg_circuit_name[id], (long long)turn);+ CHECK(!jerk && !steep && !gaps, "%s: %d sudden bends, %d steep, %d uneven segments", pg_circuit_name[id], jerk, steep, gaps);+ CHECK(!close, "%s: the road comes within 32 m of itself %d times", pg_circuit_name[id], close);+ int lo = 255;+ for (int k = 0; k < n; k++)+ if (TT.limit[k] < lo) lo = TT.limit[k];+ CHECK(lo >= 15 && TT.orbs >= 10, "%s: tightest bend %d m/s, %d orbs", pg_circuit_name[id], lo, TT.orbs);+ printf(" %-17s %3d segments, %.2f km, tightest bend %d km/h, %d orbs\n", pg_circuit_name[id], n, n * TT.seg / 256000.0,+ lo * 36 / 10, TT.orbs);+ }+ /* the endless road: laid on and on, always joined up, never too steep, within its heights */+ pg_endless(&TT, 777);+ int bad = 0, zones[5] = {0};+ int32_t ylo = 0, yhi = 0;+ for (int32_t k = 0; k < 20000; k += 7) {+ pg_extend(&TT, k + 48);+ for (int32_t j = k; j < k + 40; j++) {+ int a = pg_slot(&TT, j), b = pg_slot(&TT, j + 1);+ int64_t d2 = dist2(&TT, a, b);+ if (d2 < 5 * 5 || d2 > 7 * 7) bad++;+ if (abs(TT.py[b] - TT.py[a]) > FX * 3 / 4) bad++;+ if (TT.py[a] < ylo) ylo = TT.py[a];+ if (TT.py[a] > yhi) yhi = TT.py[a];+ if (TT.zone[a] < 3 || TT.zone[a] > 7) bad++;+ else zones[TT.zone[a] - 3]++;+ }+ }+ CHECK(!bad && ylo > -100 * FX && yhi < 100 * FX, "the endless road: %d bad joins, heights %d..%d m", bad, ylo / FX, yhi / FX);+ CHECK(zones[0] && zones[1] && zones[2] && zones[3] && zones[4], "the endless road: every scenery");+ printf(" the endless road: 120 km laid, heights %d..%d m\n", ylo / FX, yhi / FX);+}++/* a whole race driven by the bot; returns the steps it took (0: not finished in 11 minutes) */+static int drive_race(pg_race *r, const pg_setup *s, uint32_t seed, int skill, uint32_t *hash) {+ pg_new(r, &TT, s, seed);+ bot_skill = skill, bot_line = 0;+ int steps = 0;+ while (r->phase != PH_DONE && steps < 11 * 60 * PG_HZ) {+ pg_step(r, &TT, bot(r, &TT), 0);+ steps++;+ if (hash) *hash = hash_race(r, *hash);+ if (!pg_valid(r, &TT)) {+ CHECK(0, "race not valid at step %d on %s", steps, pg_circuit_name[s->track]);+ break;+ }+ }+ return r->end == END_FINISH ? steps : 0;+}++static void laps(void) {+ pg_race r;+ pg_setup s = plain(MODE_RACE, 0, 0, 0, LEVEL_NORMAL);+ pg_new(&r, &TT, &s, 5);+ CHECK(r.phase == PH_GRID && r.lap == 1 && r.car[0].s < 0, "the start: on the grid, behind the line, lap 1");+ int steps = 0, laps_seen = 1;+ while (r.phase == PH_GRID) pg_step(&r, &TT, IN_GAS, 0), steps++;+ CHECK(steps == 3 * PG_HZ + PG_HZ / 2 && r.car[0].v == 0, "the countdown took %d steps, the car held", steps);+ bot_line = 0;+ while (r.phase == PH_RACE && steps < 20000) {+ int before = r.lap;+ int32_t s0 = r.car[0].s;+ pg_step(&r, &TT, bot(&r, &TT), 0);+ steps++;+ if (r.lap != before) {+ CHECK(r.lap == before + 1, "lap %d to %d", before, r.lap);+ CHECK(s0 < before * TT.length && r.car[0].s >= before * TT.length, "the lap changed off the line");+ CHECK(r.banner == (r.lap == 3 ? BANNER_FINAL : BANNER_LAP), "the lap's banner");+ CHECK(r.last_lap_ms > 15000 && r.lap_at == r.time_ms, "the lap's time (%u)", r.last_lap_ms);+ laps_seen++;+ }+ }+ CHECK(laps_seen == 3 && r.end == END_FINISH && r.car[0].place == 1, "three laps, then the finish (%d laps, end %d)",+ laps_seen, r.end);+ CHECK(r.car[0].s >= 3 * TT.length && r.car[0].finish_ms == r.time_ms, "finished at the line");+ CHECK(r.best_lap_ms > 15000 && r.best_lap_ms * 3 <= r.time_ms + 6000, "a best lap (%u ms of %u)", r.best_lap_ms, r.time_ms);+ /* standing still, or going backwards over the line, counts no lap */+ pg_new(&r, &TT, &s, 5);+ for (int i = 0; i < 2000; i++) pg_step(&r, &TT, IN_BRAKE, 0);+ CHECK(r.lap == 1 && r.car[0].v == 0, "standing still: still lap 1");+ pg_new(&r, &TT, &s, 5);+ r.phase = PH_RACE, r.countdown = 0;+ r.car[0].s = 20 * FX, r.car[0].ang = 32767, r.car[0].v = 20 * FX; /* pointing back down the road */+ int wrong = 0;+ for (int i = 0; i < 1500; i++) {+ pg_step(&r, &TT, IN_GAS, 0);+ if (r.banner == BANNER_WRONG) wrong = 1;+ }+ CHECK(r.lap == 1 && r.car[0].s < -100 * FX && wrong, "backwards: lap %d, at %d m, told %d", r.lap, r.car[0].s / FX, wrong);+}++static void physics(void) {+ pg_race r;+ /* flat out on Neo-Tokyo Wangan's long straight: the car's top speed, no more; nitro adds to it */+ for (int v = 0; v < PG_VEHICLES; v++) {+ pg_setup s = plain(MODE_RACE, 1, v, 0, LEVEL_NORMAL);+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0;+ int32_t top = (int32_t)pg_vehicles[v].top * FX / 8, most = 0;+ int t100 = 0;+ for (int i = 0; i < 40 * PG_HZ; i++) {+ r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0; /* (kept on the straight) */+ pg_step(&r, &TT, IN_GAS, 0);+ if (r.car[0].v > most) most = r.car[0].v;+ if (!t100 && pg_kmh(r.car[0].v) >= 100) t100 = i;+ }+ CHECK(most <= top + FX / 4 && most > top - 3 * FX, "%s: top %d km/h, its own %d", pg_vehicles[v].name, pg_kmh(most), pg_kmh(top));+ r.car[0].nitro = 1000;+ for (int i = 0; i < 3 * PG_HZ; i++) {+ r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0;+ pg_step(&r, &TT, IN_GAS | IN_NITRO, 0);+ }+ CHECK(r.car[0].v > top + 5 * FX, "%s: nitro adds speed", pg_vehicles[v].name);+ printf(" %-15s top %d km/h, 0-100 km/h in %.1f s\n", pg_vehicles[v].name, pg_kmh(most), t100 / 50.0);+ }+ /* the manual gearbox: first gear stops at its limiter, + takes the next */+ {+ pg_setup m = plain(MODE_RACE, 1, 0, 0, LEVEL_NORMAL);+ m.manual = 1;+ pg_new(&r, &TT, &m, 3);+ r.phase = PH_RACE, r.countdown = 0;+ for (int i = 0; i < 10 * PG_HZ; i++) {+ r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0;+ pg_step(&r, &TT, IN_GAS, 0);+ }+ int32_t first = r.car[0].v;+ CHECK(r.car[0].gear == 1 && pg_kmh(first) < 90, "manual: still in first (%d) at %d km/h", r.car[0].gear, pg_kmh(first));+ pg_step(&r, &TT, IN_GAS, 1);+ for (int i = 0; i < 3 * PG_HZ; i++) {+ r.car[0].s = 10 * FX, r.car[0].x = 0, r.car[0].ang = 0;+ pg_step(&r, &TT, IN_GAS, 0);+ }+ CHECK(r.car[0].gear == 2 && r.car[0].v > first + 5 * FX, "manual: second gear goes on (%d km/h)", pg_kmh(r.car[0].v));+ pg_step(&r, &TT, IN_GAS, -1), pg_step(&r, &TT, IN_GAS, -1);+ CHECK(r.car[0].gear == 1, "manual: - goes back down, not below first");+ }+ /* braking from 200 km/h: under 60 m */+ pg_setup s = plain(MODE_RACE, 1, 0, 0, LEVEL_NORMAL);+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 200 * FX * 10 / 36;+ int32_t s0 = r.car[0].s;+ while (r.car[0].v > 0) pg_step(&r, &TT, IN_BRAKE, 0);+ CHECK(r.car[0].s - s0 < 60 * FX && r.car[0].s - s0 > 30 * FX, "braking from 200 km/h: %d m", (r.car[0].s - s0) / FX);+ /* a bend not steered through carries you to its outside; steering keeps you on the road */+ pg_build(&TT, 2);+ int32_t kb = 0;+ for (int k = 0; k < TT.n; k++)+ if (TT.cv[k] > TT.cv[kb]) kb = k;+ s = plain(MODE_RACE, 2, 0, 0, LEVEL_NORMAL);+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0, r.car[0].s = (kb - 4) * TT.seg, r.car[0].v = 15 * FX;+ for (int i = 0; i < 60; i++) pg_step(&r, &TT, IN_GAS, 0);+ CHECK(r.car[0].x < -2 * FX, "a right bend, unsteered: out to the left (%d)", r.car[0].x / FX);+ /* the tyres hold so much: full lock at speed turns no faster than the grip allows */+ pg_build(&TT, 1);+ s = plain(MODE_RACE, 1, 0, 0, LEVEL_NORMAL);+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 60 * FX;+ int32_t worst = 0;+ for (int i = 0; i < 30; i++) {+ int16_t a0 = r.car[0].ang;+ int32_t cv = TT.cv[pg_slot(&TT, pg_seg_of(&TT, r.car[0].s))];+ int32_t ds0 = r.car[0].s;+ pg_step(&r, &TT, IN_RIGHT, 0);+ int32_t turned = (int16_t)(r.car[0].ang - a0) + (int32_t)((int64_t)cv * (r.car[0].s - ds0) / TT.seg);+ int32_t lat = (int32_t)((int64_t)turned * PG_HZ * r.car[0].v / 10430); /* v * turn rate: FX/s^2 */+ if (lat > worst) worst = lat;+ }+ int32_t hold = 24 * FX * pg_vehicles[0].grip / 128 * 133 / 128;+ CHECK(worst <= hold + FX / 2 && worst > hold * 3 / 4, "sideways at full lock: %d m/s^2, the tyres %d", worst / FX, hold / FX);+ /* braking hard while steering hard slides the car: a tighter turn, less braking */+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 40 * FX, r.car[0].steer = 1024;+ pg_race q = r;+ for (int i = 0; i < 25; i++) pg_step(&r, &TT, IN_BRAKE | IN_RIGHT, 0), pg_step(&q, &TT, IN_RIGHT, 0);+ CHECK(r.car[0].drift && r.car[0].slip > 1000 && r.car[0].ang > q.car[0].ang, "a slide: %d, body %d, heading %d vs %d",+ r.car[0].drift, r.car[0].slip, r.car[0].ang, q.car[0].ang);+ /* the grass is slow */+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0;+ for (int i = 0; i < 30 * PG_HZ; i++) {+ r.car[0].s = 10 * FX, r.car[0].x = 11 * FX, r.car[0].ang = 0;+ pg_step(&r, &TT, IN_GAS, 0);+ }+ CHECK(pg_kmh(r.car[0].v) < 160, "on the grass: %d km/h", pg_kmh(r.car[0].v));+ /* the barriers: never through, and hitting one costs speed */+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0, r.car[0].s = 10 * FX, r.car[0].v = 50 * FX, r.car[0].ang = 6000;+ int32_t far_x = 0, v0 = r.car[0].v;+ for (int i = 0; i < 100; i++) {+ pg_step(&r, &TT, IN_GAS, 0);+ if (r.car[0].x > far_x) far_x = r.car[0].x;+ }+ CHECK(far_x <= PG_WALL - PG_HW && r.car[0].v < v0, "into the barrier: %d cm in, %d km/h", (far_x - (PG_WALL - PG_HW)) * 100 / FX,+ pg_kmh(r.car[0].v));+}++static int inside_count(const pg_race *r, const pg_track *t) {+ int n = 0;+ for (int a = 0; a <= r->rivals; a++)+ for (int b = a + 1; b <= r->rivals; b++) {+ int32_t ds = pg_wrap(t, r->car[b].s - r->car[a].s), dx = r->car[b].x - r->car[a].x;+ if (abs(ds) < 2 * PG_HL - FX / 4 && abs(dx) < 2 * PG_HW - FX / 4) n++;+ }+ return n;+}++static void crashes(void) {+ pg_race r;+ /* random keys among a full field: never a car inside another, everything in range */+ uint32_t lcg = 77;+ int inside = 0, bad = 0;+ for (int id = 0; id < PG_CIRCUITS; id++) {+ pg_setup s = plain(MODE_RACE, id, id, 7, LEVEL_HARD);+ pg_new(&r, &TT, &s, (uint32_t)id + 1);+ for (int i = 0; i < 9000 && r.phase != PH_DONE; i++) {+ lcg = lcg * 1103515245u + 12345u;+ unsigned in = (lcg >> 16) & 31;+ pg_step(&r, &TT, in | IN_GAS, 0);+ inside += inside_count(&r, &TT);+ if (!pg_valid(&r, &TT)) bad++;+ }+ }+ CHECK(!inside && !bad, "cars inside each other %d times, %d bad steps", inside, bad);+ /* ramming the car in front: you stop at its bumper, it takes the push */+ pg_setup s = plain(MODE_RACE, 1, 0, 1, LEVEL_EASY);+ pg_new(&r, &TT, &s, 3);+ r.phase = PH_RACE, r.countdown = 0;+ r.car[0].s = 100 * FX, r.car[0].x = 0, r.car[0].v = 60 * FX;+ r.car[1].s = 112 * FX, r.car[1].x = 0, r.car[1].lane = 0, r.car[1].v = 20 * FX;+ bool through = false;+ int32_t v1 = r.car[1].v;+ for (int i = 0; i < 30; i++) {+ r.car[1].lane = 0, r.car[1].think = 2;+ pg_step(&r, &TT, IN_GAS, 0);+ if (r.car[0].s > r.car[1].s && abs(r.car[0].x - r.car[1].x) < 2 * PG_HW) through = true;+ }+ CHECK(!through && r.car[1].v > v1, "drove through the car in front (%d), it was pushed (%d)", through, r.car[1].v > v1);+}++static void rivals(void) {+ uint32_t h = 0;+ for (int id = 0; id < PG_CIRCUITS; id++) {+ uint32_t mean[3] = {0};+ for (int level = 0; level < 3; level++) {+ pg_race r;+ pg_setup s = plain(MODE_RACE, id, 0, 7, level);+ pg_new(&r, &TT, &s, (uint32_t)(id * 3 + level + 1));+ /* you stay on the grid: the rivals race on their own */+ int steps = 0, inside = 0;+ while (r.finished < 7 && steps < 11 * 60 * PG_HZ) {+ pg_step(&r, &TT, 0, 0), steps++;+ h = hash_race(&r, h);+ inside += inside_count(&r, &TT);+ }+ CHECK(r.finished == 7 && !inside, "%s, %s: %d of 7 rivals finished, %d overlaps", pg_circuit_name[id], LEVELS[level],+ r.finished, inside);+ uint32_t first = 0, last = 0;+ for (int i = 1; i < PG_CARS; i++) {+ mean[level] += r.car[i].finish_ms / 7;+ if (r.car[i].place == 1) first = r.car[i].finish_ms;+ if (r.car[i].place == 7) last = r.car[i].finish_ms;+ }+ printf(" %-17s %-6s rivals %u:%04.1f to %u:%04.1f\n", pg_circuit_name[id], LEVELS[level], first / 60000,+ first % 60000 / 1000.0, last / 60000, last % 60000 / 1000.0);+ CHECK(last - first < 30000, "%s %s: the field spread over %u ms", pg_circuit_name[id], LEVELS[level], last - first);+ }+ CHECK(mean[0] > mean[1] && mean[1] > mean[2], "%s: Easy %u, Normal %u, Hard %u ms", pg_circuit_name[id], mean[0], mean[1], mean[2]);+ }+ printf(" rivals' hash %08x\n", h);+}++/* the driver against the field, every circuit and level */+static void racing(void) {+ int wins[3] = {0}, finishes = 0, places[3] = {0};+ for (int level = 0; level < 3; level++)+ for (int id = 0; id < PG_CIRCUITS; id++) {+ pg_race r;+ pg_setup s = plain(MODE_RACE, id, 0, 7, level);+ int steps = drive_race(&r, &s, (uint32_t)(100 + id + level * 7), 100, NULL);+ CHECK(steps > 0, "%s %s: the driver didn't finish", pg_circuit_name[id], LEVELS[level]);+ if (steps) finishes++;+ if (r.car[0].place == 1) wins[level]++;+ places[level] += r.car[0].place;+ printf(" %-17s %-6s %u:%04.1f, %d%s, best lap %u:%04.1f\n", pg_circuit_name[id], LEVELS[level], r.time_ms / 60000,+ r.time_ms % 60000 / 1000.0, r.car[0].place, r.car[0].place == 1 ? "st" : r.car[0].place == 2 ? "nd" : r.car[0].place == 3 ? "rd" : "th",+ r.best_lap_ms / 60000, r.best_lap_ms % 60000 / 1000.0);+ }+ printf(" the driver won %d easy, %d normal, %d hard races of 3 each\n", wins[0], wins[1], wins[2]);+ CHECK(finishes == 9, "%d of 9 races finished", finishes);+ CHECK(places[0] <= places[1] && places[1] <= places[2], "harder levels should be harder (%d %d %d)", places[0], places[1], places[2]);+}++/* the endless road: zones add time, the clock runs out, orbs fill nitro */+static void endless(void) {+ pg_race r;+ pg_setup s = plain(MODE_ENDLESS, 0, 0, 0, LEVEL_NORMAL);+ for (int run = 0; run < 3; run++) {+ pg_new(&r, &TT, &s, 400 + (uint32_t)run);+ CHECK(r.rivals == 0 && r.time_left == 30000, "the endless road: alone, 30 s");+ bot_skill = 100 - run * 20, bot_line = 0;+ int steps = 0, orbs = 0, bad = 0;+ uint16_t n0 = r.car[0].nitro;+ while (r.phase != PH_DONE && steps < 30 * 60 * PG_HZ) {+ pg_step(&r, &TT, bot(&r, &TT), 0), steps++;+ if (r.car[0].nitro > n0) orbs++;+ n0 = r.car[0].nitro;+ if (!pg_valid(&r, &TT)) bad++;+ }+ CHECK(r.phase == PH_DONE && r.end == END_TIME && !bad, "the endless road ends when time runs out (%d bad)", bad);+ CHECK(r.zone >= 4 && orbs > 3, "the endless road: zone %d, %d orbs", r.zone + 1, orbs);+ printf(" endless, skill %d: %.1f km, zone %d, %.0f s, %d orbs\n", bot_skill, r.car[0].s / 256000.0, r.zone + 1,+ r.ticks / 50.0, orbs);+ }+}++/* the same race twice, to the same hash on every computer */+static void same_twice(void) {+ uint32_t h1 = 0, h2 = 0;+ pg_race a, b;+ pg_setup s = plain(MODE_RACE, 2, 1, 7, LEVEL_NORMAL);+ drive_race(&a, &s, 2026, 100, &h1);+ drive_race(&b, &s, 2026, 100, &h2);+ printf(" a race's hash %08X\n", h1);+ CHECK(h1 == h2 && h1 == RACE_HASH, "the same race twice, and as on every computer: %08X", h1);+}++/* ---------------------------------------------------------------- saves */+static void saves(void) {+ memset(files, 0, sizeof files);+ pg_file a, b;+ memset(&a, 0, sizeof a);+ pg_fresh(&a.p);+ a.p.races = 9, a.p.wins = 4, a.p.runs = 3, a.p.best_ms[1] = 160000, a.p.best_lap_ms[1] = 51000, a.p.best_lap_ms[2] = 47000;+ a.p.best_m = 12345, a.p.best_zone = 21, a.p.mode = MODE_RACE, a.p.track = 2, a.p.vehicle = 4, a.p.laps = 5;+ a.p.rivals = 6, a.p.level = LEVEL_HARD, a.p.manual = 1, a.p.view = VIEW_FAR, a.p.guide = 1;+ pg_setup s = plain(MODE_RACE, 2, 4, 6, LEVEL_HARD);+ pg_new(&a.race, &TT, &s, 4);+ bot_line = 0;+ for (int i = 0; i < 2500; i++) pg_step(&a.race, &TT, bot(&a.race, &TT), 0);+ a.has_race = 1;+ CHECK(save_write(&a), "saved");+ CHECK(save_load(&b) && !memcmp(&a.p, &b.p, sizeof a.p) && b.has_race && !memcmp(&a.race, &b.race, sizeof a.race),+ "read back as written");+ /* the copy in the script brings it back when the save is gone */+ forget(PG_SAVE_NAME);+ CHECK(save_load(&b) && b.p.races == 9 && b.has_race, "back from polygt3d_saves.py");+ CHECK(plat_load(PG_SAVE_NAME, &(uint32_t){0}) != NULL, "and put back in polygt3d.sav");+ /* every byte damaged in turn: never read (with the copy gone, a fresh start) */+ uint32_t n;+ uint8_t good[sizeof(pg_file)];+ memcpy(good, file_data(PG_SAVE_NAME, &n), sizeof good);+ forget(PG_COPY_NAME);+ int bad = 0;+ for (uint32_t i = 0; i < sizeof good; i++) {+ uint8_t *d = file_data(PG_SAVE_NAME, &n);+ memcpy(d, good, sizeof good);+ d[i] ^= (uint8_t)(1 + i % 255);+ if (save_load(&b) || b.p.races || b.has_race || b.p.laps != 3) bad++;+ }+ CHECK(!bad, "%d damaged saves read", bad);+ /* cut short, empty, another version: a fresh start */+ for (int k = 0; k < 4; k++)+ if (files[k].on && !strcmp(files[k].name, PG_SAVE_NAME)) memcpy(files[k].data, good, sizeof good), files[k].len = sizeof good - 1;+ CHECK(!save_load(&b) && b.p.rivals == 5, "a short save: fresh");+ for (int k = 0; k < 4; k++)+ if (files[k].on && !strcmp(files[k].name, PG_SAVE_NAME)) files[k].len = 0;+ CHECK(!save_load(&b), "an empty save: fresh");+ pg_file v = a;+ v.magic = PG_MAGIC, v.size = sizeof v, v.version = 2;+ v.sum = pg_sum(&v, offsetof(pg_file, sum));+ plat_save(PG_SAVE_NAME, &v, sizeof v);+ CHECK(!save_load(&b), "another version: fresh");+ /* a checksum that fits over values that don't: not read either; whatever is read races and draws safely */+ uint32_t lcg = 5;+ int read = 0;+ for (int k = 0; k < 400; k++) {+ pg_file x;+ memcpy(&x, good, sizeof x);+ uint8_t *p = (uint8_t *)&x;+ for (int j = 0; j < 3; j++) {+ lcg = lcg * 1103515245u + 12345u;+ uint32_t at = 8 + (lcg >> 8) % (offsetof(pg_file, sum) - 8);+ p[at] = (uint8_t)(lcg >> 24);+ }+ x.sum = pg_sum(&x, offsetof(pg_file, sum));+ plat_save(PG_SAVE_NAME, &x, sizeof x);+ if (save_load(&b)) {+ read++;+ if (b.has_race) {+ show_race(&b.race), built = -1;+ int went_bad = 0;+ for (int i = 0; i < 300; i++) {+ pg_step(&b.race, &track, (unsigned)i & 31, 0);+ if (!pg_valid(&b.race, NULL)) went_bad++;+ }+ CHECK(!went_bad, "an accepted race went bad");+ }+ }+ }+ printf(" saves: %d of 400 changed saves with a fitting checksum were still in range\n", read);+ /* odd but possible races (cars on top of each other, flat out, stopped, wide): read, then raced and drawn */+ int odd = 0, odd_bad = 0;+ for (int k = 0; k < 200; k++) {+ pg_file x;+ memcpy(&x, good, sizeof x);+ for (int i = 0; i <= x.race.rivals; i++) {+ pg_car *c = &x.race.car[i];+ lcg = lcg * 1103515245u + 12345u;+ c->s = (int32_t)(lcg >> 9) % (3 * 1600 * FX);+ lcg = lcg * 1103515245u + 12345u;+ c->x = ((int32_t)(lcg >> 8) % (2 * (PG_WALL - PG_HW))) - (PG_WALL - PG_HW);+ c->lane = ((int32_t)(lcg >> 20) % 3 - 1) * 4 * FX;+ lcg = lcg * 1103515245u + 12345u;+ c->v = (int32_t)(lcg >> 8) % (100 * FX);+ c->ang = (int16_t)(lcg >> 3);+ }+ x.race.car[1].s = x.race.car[2].s, x.race.car[1].x = x.race.car[2].x; /* two cars in one place */+ x.sum = pg_sum(&x, offsetof(pg_file, sum));+ plat_save(PG_SAVE_NAME, &x, sizeof x);+ if (!save_load(&b) || !b.has_race) continue;+ odd++;+ sv = b, built = -1;+ show_race(&sv.race);+ for (int i = 0; i < 400; i++) {+ pg_step(&sv.race, &track, bot(&sv.race, &track), 0);+ if (!pg_valid(&sv.race, &track)) odd_bad++;+ }+ prev = sv.race, ui.screen = V_RACE;+ pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);+ }+ CHECK(odd > 150 && !odd_bad, "odd races: %d read, %d steps gone bad", odd, odd_bad);+ /* storage full: the save fails, the game goes on */+ memset(files, 0, sizeof files);+ storage_full = true;+ CHECK(!save_write(&a), "a full storage fails the save");+ storage_full = false;+ memset(files, 0, sizeof files);+}++/* ---------------------------------------------------------------- the whole app, with keys */+static int bad_frames;+static void check_state(void) {+ if (ui.screen >= V_SCREENS) bad_frames++;+ if (sv.has_race && !pg_valid(&sv.race, NULL)) bad_frames++;+ if (sv.p.wins > sv.p.races || sv.p.laps < 1 || sv.p.laps > PG_MAX_LAPS || sv.p.vehicle >= PG_VEHICLES) bad_frames++;+ if (rd_dropped) bad_frames++;+}++static uint32_t (*menu_keys)(uint32_t f);+static uint32_t drive_keys(uint32_t f) {+ if (ui.screen == V_RACE && !ui.hold && sv.race.phase != PH_DONE) {+ unsigned in = bot(&sv.race, &track);+ uint32_t k = 0;+ if (in & IN_GAS) k |= PK_UP;+ if (in & IN_BRAKE) k |= PK_DOWN;+ if (in & IN_LEFT) k |= PK_LEFT;+ if (in & IN_RIGHT) k |= PK_RIGHT;+ if (in & IN_NITRO) k |= PK_OK;+ return k;+ }+ return menu_keys ? menu_keys(f) : 0;+}++/* a race: Play, Start race, the guide, three laps driven, then the results' Main menu */+static int race_phase;+static uint32_t race_menu(uint32_t f) {+ if (f % 4) return 0;+ switch (ui.screen) {+ case V_TITLE:+ if (race_phase) return 0;+ return ui.menu[ui.sel] == MENU_PLAY ? PK_OK : PK_DOWN;+ case V_SETUP: return ui.sel == SET_START ? PK_OK : PK_DOWN;+ case V_GUIDE: return PK_OK;+ case V_RESULT: race_phase = 1; return ui.sel == 1 ? PK_OK : PK_DOWN;+ default: return 0;+ }+}+static bool saw_ghost;+static void watch_race(void) {+ check_state();+ if (ghost_now.on) saw_ghost = true;+ if (race_phase == 1 && ui.screen == V_TITLE) quit_at = frame_no + 2, race_phase = 2;+}+static void race_app(void) {+ memset(files, 0, sizeof files);+ memset(best_ghost, 0, sizeof best_ghost);+ frame_gap = 60;+ race_phase = 0, saw_ghost = false;+ script = drive_keys, menu_keys = race_menu, watch = watch_race;+ frame_no = 0, quit_at = 4000000, bad_frames = 0;+ bot_line = 0;+ pg_app_main();+ script = 0, menu_keys = 0, watch = 0;+ pg_file f;+ CHECK(save_load(&f), "the race saved");+ CHECK(f.p.races == 1 && !f.has_race && f.p.guide == 1 && f.p.best_ms[0] && f.p.best_lap_ms[0], "a race finished and its records kept (races %u)",+ f.p.races);+ CHECK(race_phase == 2 && saw_ghost, "back to the menu (%d), the ghost seen (%d)", race_phase, saw_ghost);+ CHECK(!bad_frames, "%d bad frames", bad_frames);+ printf(" a race through the keys: %u:%04.1f, %s, %u frames\n", f.p.best_ms[0] / 60000, f.p.best_ms[0] % 60000 / 1000.0,+ f.p.wins ? "won" : "not won", frame_no);+}++/* the endless road: chosen on the race screen, a minute of driving, pause, Quit game to the menu (kept), Continue,+ then Home: it's saved */+static int en_step;+static uint32_t en_menu(uint32_t f) {+ if (f % 4) return 0;+ switch (ui.screen) {+ case V_TITLE:+ if (en_step >= 2) return ui.menu[ui.sel] == MENU_CONTINUE ? PK_OK : PK_UP;+ return ui.menu[ui.sel] == MENU_PLAY ? PK_OK : PK_DOWN;+ case V_SETUP:+ if (sv.p.mode != MODE_ENDLESS) return ui.sel == SET_MODE ? PK_RIGHT : PK_UP;+ return ui.sel == SET_START ? PK_OK : PK_UP;+ case V_GUIDE: return PK_OK;+ case V_PAUSE: return ui.sel == PAUSE_QUIT ? PK_OK : PK_DOWN;+ case V_LEAVE: return ui.sel == 1 ? PK_OK : PK_DOWN;+ default: return 0;+ }+}+static uint32_t en_keys(uint32_t f) {+ if (ui.screen == V_RACE && en_step == 0 && sv.race.car[0].s > 1500 * FX) en_step = 1;+ if (ui.screen == V_RACE && en_step == 1) return f % 8 < 4 ? PK_BACK : 0;+ if (ui.screen == V_TITLE && en_step == 1) en_step = 2;+ if (ui.screen == V_RACE && en_step == 2 && !ui.hold) en_step = 3, quit_at = frame_no + 600;+ return drive_keys(f);+}+static void endless_app(void) {+ memset(files, 0, sizeof files);+ frame_gap = 60;+ en_step = 0;+ script = en_keys, menu_keys = en_menu, watch = check_state;+ frame_no = 0, quit_at = 400000, bad_frames = 0;+ bot_line = 0;+ pg_app_main();+ script = 0, menu_keys = 0, watch = 0;+ pg_file f;+ CHECK(en_step == 3, "the endless steps (%d)", en_step);+ CHECK(save_load(&f) && f.has_race && f.race.mode == MODE_ENDLESS && f.race.car[0].s > 1500 * FX,+ "the drive kept on Home (%d)", f.has_race);+ CHECK(!bad_frames, "%d bad frames", bad_frames);+ printf(" the endless road through the keys: %.1f km, kept on Home\n", f.race.car[0].s / 256000.0);+}++static uint32_t lcg_keys;+static uint32_t rnd(void) { return lcg_keys = lcg_keys * 1103515245u + 12345u, lcg_keys >> 8; }+static uint32_t held_keys, held_until;+static uint32_t random_keys(uint32_t f) {+ if (f >= held_until) {+ static const uint32_t pick[] = {PK_OK, PK_OK, PK_OK, PK_LEFT, PK_RIGHT, PK_UP, PK_UP, PK_UP, PK_DOWN, PK_BACK,+ PK_GEAR_UP, PK_GEAR_DOWN, PK_UP | PK_OK, PK_UP | PK_LEFT, PK_DOWN | PK_RIGHT, 0, 0};+ held_keys = pick[rnd() % (sizeof pick / sizeof pick[0])];+ held_until = f + 2 + rnd() % 40;+ }+ return held_keys;+}++static void fuzz(void) {+ memset(files, 0, sizeof files);+ frame_gap = 90;+ int sessions = 0, kept = 0;+ for (int s = 0; s < 300; s++) {+ lcg_keys = (uint32_t)s * 2654435761u + 1;+ if (s % 40 == 0) memset(files, 0, sizeof files);+ storage_full = s % 37 == 36;+ script = random_keys, watch = check_state;+ frame_no = 0, quit_at = 2000 + rnd() % 6000, held_until = 0, bad_frames = 0;+ pg_app_main();+ sessions++;+ storage_full = false;+ pg_file f;+ if (save_load(&f)) kept += f.has_race;+ CHECK(!bad_frames, "session %d: %d bad frames", s, bad_frames);+ }+ script = 0, watch = 0;+ printf(" keys: %d sessions of random keys, quit with Home each time (%d left a race going)\n", sessions, kept);+}++static void test(const char *dir) {+ (void)dir;+ printf("the roads\n");+ roads();+ printf("laps\n");+ laps();+ printf("physics\n");+ physics();+ printf("crashes\n");+ crashes();+ printf("rivals\n");+ rivals();+ printf("racing\n");+ racing();+ printf("the endless road\n");+ endless();+ printf("the same race\n");+ same_twice();+ printf("saves\n");+ saves();+ printf("the app\n");+ race_app();+ endless_app();+ fuzz();+ printf(fails ? "%d FAILED\n" : "all good\n", fails);+}++/* ---------------------------------------------------------------- pictures */+static void picture(const char *dir, const char *name) {+ pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);+ shot(dir, name);+}++static void race_at(int id, int vehicle, int rivals, float metres, int view) {+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ sv.p.track = (uint8_t)id, sv.p.vehicle = (uint8_t)vehicle, sv.p.rivals = (uint8_t)rivals, sv.p.view = (uint8_t)view;+ sv.p.guide = 1;+ race_begin();+ bot_line = 0;+ while (sv.race.car[0].s < (int32_t)(metres * FX) && sv.race.phase != PH_DONE) {+ prev = sv.race;+ pg_step(&sv.race, &track, bot(&sv.race, &track), 0);+ }+ prev = sv.race;+ ui.screen = V_RACE;+}++static void endless_at(float metres, uint32_t seed) {+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ sv.p.mode = MODE_ENDLESS, sv.p.guide = 1;+ rnd_state = seed;+ race_begin();+ bot_line = 0;+ while (sv.race.car[0].s < (int32_t)(metres * FX) && sv.race.phase != PH_DONE) {+ prev = sv.race;+ pg_step(&sv.race, &track, bot(&sv.race, &track), 0);+ }+ prev = sv.race;+ ui.screen = V_RACE;+}++static void shots(const char *dir) {+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ now = 1000;+ to_title();+ ui.clock = 2600;+ picture(dir, "title");+ ui.screen = V_SETUP, ui.sel = SET_START;+ show_circuit(0);+ picture(dir, "setup");+ ui.sel = SET_CAR;+ picture(dir, "setup_car");+ ui.screen = V_RECORDS;+ picture(dir, "records");+ for (int k = 0; k < PG_HELP_PAGES; k++) {+ ui.screen = V_HELP, ui.page = (uint8_t)k;+ char n[16];+ snprintf(n, sizeof n, "help%d", k);+ picture(dir, n);+ }+ race_at(0, 0, 7, -1, VIEW_CHASE);+ picture(dir, "grid");+ static const float AT[3] = {420, 600, 500};+ for (int id = 0; id < PG_CIRCUITS; id++) {+ race_at(id, id, 7, AT[id], VIEW_CHASE);+ char n[16];+ snprintf(n, sizeof n, "track%d", id);+ picture(dir, n);+ }+ race_at(2, 3, 5, 700, VIEW_CHASE);+ picture(dir, "horse");+ race_at(1, 1, 5, 900, VIEW_FAR);+ picture(dir, "far");+ race_at(0, 2, 5, 300, VIEW_BUMPER);+ picture(dir, "bumper");+ ui.screen = V_PAUSE, ui.sel = 0;+ picture(dir, "pause");+ ui.screen = V_LEAVE, ui.sel = 1;+ picture(dir, "leave");+ for (int z = 0; z < 5; z++) {+ endless_at(400 + 430 * z, 7 + z);+ char n[16];+ snprintf(n, sizeof n, "endless%d", z);+ picture(dir, n);+ }+ /* a race to the end, then its results */+ race_at(0, 1, 5, 99999, VIEW_CHASE);+ while (!race_over(&sv.race)) prev = sv.race, pg_step(&sv.race, &track, 0, 0);+ prev = sv.race;+ finish_race();+ picture(dir, "result");+ /* the endless road, out of time, then its results */+ endless_at(1e6f, 3);+ while (!race_over(&sv.race)) prev = sv.race, pg_step(&sv.race, &track, 0, 0);+ ui.screen = V_RACE;+ prev = sv.race;+ picture(dir, "timeup");+ finish_race();+ picture(dir, "result_endless");+ /* the horses, close */+ for (int v = 3; v < 5; v++) {+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ sv.p.vehicle = (uint8_t)v;+ to_title();+ ui.clock = 1800 + v * 900;+ char n[16];+ snprintf(n, sizeof n, "title_v%d", v);+ picture(dir, n);+ }+ race_at(1, 4, 3, 300, VIEW_CHASE);+ picture(dir, "mustang");+ /* the title with a race kept, the questions */+ sv.has_race = 1;+ to_title();+ ui.clock = 900;+ picture(dir, "title_continue");+ ui.screen = V_QUIT, ui.sel = 0;+ picture(dir, "quit");+ ui.screen = V_NEWRUN, ui.sel = 0;+ picture(dir, "newrun");+ ui.screen = V_GUIDE, ui.page = 0;+ picture(dir, "guide");+ sv.p.best_ms[0] = 101230, sv.p.best_lap_ms[0] = 32870, sv.p.best_ms[2] = 152110, sv.p.best_lap_ms[2] = 49010;+ sv.p.best_m = 9420, sv.p.best_zone = 23, sv.p.races = 12, sv.p.wins = 5;+ ui.screen = V_RECORDS;+ picture(dir, "records_full");+ ui.screen = V_TITLE, ui.sel = 0, ui.save_failed = true;+ picture(dir, "title_full");+ ui.save_failed = false;+}++/* the README's pictures: a race on each circuit, taken when the most rivals are close ahead (the race is run once to+ find that moment, then again to it) */+static void doc_race(const char *dir, const char *name, int id, int vehicle, int view, int after_ms) {+ int best_t = -1, best_n = 0;+ for (int pass = 0; pass < 2; pass++) {+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ sv.p.track = (uint8_t)id, sv.p.vehicle = (uint8_t)vehicle, sv.p.view = (uint8_t)view, sv.p.rivals = 7, sv.p.guide = 1;+ now = 0, rnd_state = 1;+ race_begin();+ ui.screen = V_RACE;+ bot_line = 0, bot_skill = 100;+ for (int t = 0; t < 3 * 60000 && sv.race.phase != PH_DONE; t += PG_TICK) {+ prev = sv.race;+ int lap = sv.race.lap;+ pg_step(&sv.race, &track, bot(&sv.race, &track), 0);+ ghost_after_step(lap);+ if (pass == 1) {+ if (t == best_t) break;+ continue;+ }+ if (t < after_ms || sv.race.banner_t || abs(sv.race.car[0].x) > PG_ROAD - FX || abs(sv.race.car[0].ang) > 1500) continue;+ int close = 0;+ for (int i = 1; i <= sv.race.rivals; i++) {+ int32_t ds = pg_wrap(&track, sv.race.car[i].s - sv.race.car[0].s);+ if (ds > 9 * FX && ds < 70 * FX) close += ds < 35 * FX ? 2 : 1;+ }+ if (close > best_n) best_n = close, best_t = t;+ }+ }+ prev = sv.race;+ ui.clock = sv.race.time_ms;+ ghost_pose(256);+ picture(dir, name);+}++static void docs(const char *dir) {+ doc_race(dir, "shot", 0, 0, VIEW_CHASE, 6000);+ doc_race(dir, "wangan", 1, 1, VIEW_CHASE, 6000);+ doc_race(dir, "akagi", 2, 2, VIEW_CHASE, 9000);+ endless_at(2700, 21);+ picture(dir, "endless");+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ now = 0;+ to_title();+ ui.clock = 2300;+ picture(dir, "title");+ sv.p.vehicle = 4;+ ui.clock = 4300;+ picture(dir, "horse");+ sv.p.vehicle = 0;+ sv.p.best_ms[0] = 101230;+ ui.screen = V_SETUP, ui.sel = SET_START;+ show_circuit(0);+ picture(dir, "setup");+}++/* raw frames of a race, the driver at the wheel, every `step` ms (for tools/record.py --frames) */+static void film(const char *dir, int ms, int id, int view, int vehicle, int step) {+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ sv.p.track = (uint8_t)id, sv.p.view = (uint8_t)view, sv.p.vehicle = (uint8_t)vehicle, sv.p.rivals = 7, sv.p.guide = 1;+ sv.p.level = LEVEL_NORMAL;+ now = 0;+ race_begin();+ ui.screen = V_RACE;+ bot_line = 0, bot_skill = 100;+ int frame = 0;+ for (int t = 0; t < ms; t += PG_TICK) {+ prev = sv.race;+ int lap = sv.race.lap;+ pg_step(&sv.race, &track, bot(&sv.race, &track), 0);+ ghost_after_step(lap);+ if (t % step) continue;+ ui.clock = (uint32_t)t;+ ghost_pose(256);+ pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);+ char path[512];+ snprintf(path, sizeof path, "%s/%06d_%06d.raw", dir, frame++, t);+ FILE *f = fopen(path, "wb");+ if (!f) exit(2);+ fwrite(fb, 2, 320 * 240, f);+ fclose(f);+ }+}++/* the busiest frames of whole races: triangles, for every circuit and view */+static void busy(void) {+ for (int view = 0; view < VIEWS; view++)+ for (int id = 0; id < PG_CIRCUITS; id++) {+ memset(&sv, 0, sizeof sv);+ pg_fresh(&sv.p);+ sv.p.track = (uint8_t)id, sv.p.rivals = 7, sv.p.view = (uint8_t)view, sv.p.guide = 1;+ race_begin();+ bot_line = 0;+ int most = 0, at = 0, drops = 0;+ ui.screen = V_RACE;+ for (int i = 0; i < 6000 && sv.race.phase != PH_DONE; i++) {+ prev = sv.race;+ pg_step(&sv.race, &track, bot(&sv.race, &track), 0);+ if (i % 3) continue;+ pg_render(&sv, &track, &prev, &sv.race, 256, &ui, &ghost_now);+ if (rd_tris > most) most = rd_tris, at = i;+ drops += rd_dropped;+ }+ printf("view %d %-17s most %d triangles at step %d, %d frames out of room\n", view, pg_circuit_name[id], most, at, drops);+ }+}++int main(int argc, char **argv) {+ if (argc >= 3 && !strcmp(argv[1], "docs")) {+ docs(argv[2]);+ return 0;+ }+ if (argc >= 5 && !strcmp(argv[1], "film")) {+ film(argv[2], atoi(argv[3]), atoi(argv[4]), argc > 5 ? atoi(argv[5]) : 0, argc > 6 ? atoi(argv[6]) : 0,+ argc > 7 ? atoi(argv[7]) : 60);+ return 0;+ }+ if (argc >= 2 && !strcmp(argv[1], "busy")) {+ busy();+ return 0;+ }+ if (argc >= 3 && !strcmp(argv[1], "test")) {+ test(argv[2]);+ return fails ? 1 : 0;+ }+ if (argc >= 3 && !strcmp(argv[1], "shots")) {+ shots(argv[2]);+ return 0;+ }+ fprintf(stderr, "usage: play test DIR | shots DIR | docs DIR | film DIR MS CIRCUIT\n");+ return 2;+}diff --git a/games/polygt3d/tests/verify_sim.c b/games/polygt3d/tests/verify_sim.cdeleted file mode 100644index c54542b9..00000000--- a/games/polygt3d/tests/verify_sim.c+++ /dev/null@@ -1,179 +0,0 @@-#include <assert.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#define PLATFORM_DEVICE 1-#define main app_entry_main-#include "../src/main.c"-#undef main--static eadk_color_t full_screen[SCREEN_W * SCREEN_H];-static uint32_t mock_millis = 0;-static eadk_keyboard_state_t mock_kb = 0;--void eadk_display_push_rect(eadk_rect_t rect, const eadk_color_t *pixels) {- for (int y = 0; y < rect.height; y++) {- int sy = rect.y + y;- if (sy >= 0 && sy < SCREEN_H) {- for (int x = 0; x < rect.width; x++) {- int sx = rect.x + x;- if (sx >= 0 && sx < SCREEN_W) {- full_screen[sy * SCREEN_W + sx] = pixels[y * rect.width + x];- }- }- }- }-}--eadk_keyboard_state_t eadk_keyboard_scan(void) { return mock_kb; }-uint64_t eadk_timing_millis(void) { return mock_millis; }-void eadk_timing_msleep(uint32_t ms) { mock_millis += ms; }--static void save_ppm(const char *path) {- FILE *f = fopen(path, "wb");- assert(f != NULL);- 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 = full_screen[i];- uint8_t r = ((c >> 11) & 0x1F) << 3;- uint8_t g = ((c >> 5) & 0x3F) << 2;- uint8_t b = (c & 0x1F) << 3;- fputc(r, f);- fputc(g, f);- fputc(b, f);- }- fclose(f);-}--int main(void) {- // 1. Stress-test 50 random track seeds: verify ZERO knots, ZERO upside-down/bowtie quads!- const float gw = ROAD_HALF_W + 6.5f;- for (uint32_t seed = 1; seed <= 50; seed++) {- build_track_seeded(seed % 3, seed * 7919u);- for (int i = 0; i < TRACK_N; i++) {- int next = (i + 1) % TRACK_N;- const TrackNode *n0 = &track_nodes[i];- const TrackNode *n1 = &track_nodes[next];-- // Tangent dot product must be > 0.90 (smooth turns, never folds back)- float dot_t = n0->tx * n1->tx + n0->tz * n1->tz;- assert(dot_t > 0.90f && "Track segment angle too sharp / knotted!");-- // Verify left and right outer grass edges advance forward along tangent (no bowtie inversion)- float gl_dx = (n1->x - n1->nx * gw) - (n0->x - n0->nx * gw);- float gl_dz = (n1->z - n1->nz * gw) - (n0->z - n0->nz * gw);- float gr_dx = (n1->x + n1->nx * gw) - (n0->x + n0->nx * gw);- float gr_dz = (n1->z + n1->nz * gw) - (n0->z + n0->nz * gw);- assert((gl_dx * n0->tx + gl_dz * n0->tz) > 0.5f && "Left shoulder quad inverted!");- assert((gr_dx * n0->tx + gr_dz * n0->tz) > 0.5f && "Right shoulder quad inverted!");- }- }-- // 2. Verify Smooth Steering Dynamics & ZERO static phantom drift:- build_track_seeded(0, 2026);- race_npc_count = 0;- reset_race_state(0);- float start_sin = player_sin_yaw;- float start_cos = player_cos_yaw;- for (int step = 0; step < 25; step++) {- mock_millis += 33;- step_physics(0.033f, false, false, true, false, false, false, false, false, mock_millis);- if (fabsf_fast(player_offset) < ROAD_HALF_W) {- assert(fabsf_fast(player_sin_yaw - start_sin) < 1e-5f && "Phantom static steering detected!");- assert(fabsf_fast(player_cos_yaw - start_cos) < 1e-5f && "Phantom static steering detected!");- }- }- // Verify progressive steering ramp and smooth return (no instant on/off snap)- step_physics(0.033f, false, true, true, false, false, false, false, false, mock_millis);- assert(player_steer > 0.05f && player_steer < 0.25f && "Steering must build progressively on press!");- float prev_steer = player_steer;- step_physics(0.033f, false, false, true, false, false, false, false, false, mock_millis);- assert(player_steer < prev_steer && player_steer >= 0.0f && "Steering must smoothly decay toward center!");-- // 3. Verify Winner Finish Position Bug Fix: when player crosses finish line ahead of all NPCs, position == 1!- race_npc_count = 5;- race_total_laps = 1;- reset_race_state(1000);- // Place player at segment TRACK_N - 2 about to cross the finish line ahead of NPCs (lap 0)- player_seg = TRACK_N - 2;- player_wx = track_nodes[player_seg].x;- player_wz = track_nodes[player_seg].z;- player_sin_yaw = track_nodes[player_seg].tx;- player_cos_yaw = track_nodes[player_seg].tz;- player_speed = 75.0f;- for (int step = 0; step < 15 && !race_finished; step++) {- mock_millis += 33;- step_physics(0.033f, false, false, true, false, false, false, false, false, mock_millis);- }- assert(race_finished && "Player should have finished 1-lap race!");- assert(final_finish_position == 1 && player_position == 1 && "Winner finish position must be 1st!");-- // 4. Verify Infinity Driving Mode: zero bots, full nitro, streaming endless procedural road & biome transitions!- toggle_infinity_mode();- assert(infinity_mode && race_npc_count == 0 && "Infinity mode must disable bots!");- reset_race_state(2000);- assert(player_boost_fuel == 100.0f && "Infinity mode starts with 100% nitro!");- uint32_t initial_gen = inf_gen_count;- uint8_t start_biome = track_nodes[player_seg].biome_id;- bool saw_new_biome = false;- bool saw_elev_change = false;- float start_y = track_nodes[player_seg].y;- // Simulate driving forward along the streaming road across 120 segments (>2 biomes)- for (int step = 0; step < 120; step++) {- int next_seg = (player_seg + 1) % TRACK_N;- // Check that consecutive streamed road segments never fold or invert- float dx = track_nodes[next_seg].x - track_nodes[player_seg].x;- float dz = track_nodes[next_seg].z - track_nodes[player_seg].z;- float dot = dx * track_nodes[player_seg].tx + dz * track_nodes[player_seg].tz;- assert(dot > 5.0f && "Streamed infinity road segment must advance forward without folding!");- player_wx = track_nodes[next_seg].x;- player_wz = track_nodes[next_seg].z;- player_sin_yaw = track_nodes[next_seg].tx;- player_cos_yaw = track_nodes[next_seg].tz;- player_speed = 75.0f;- mock_millis += 33;- step_physics(0.033f, false, false, true, false, false, false, false, false, mock_millis);- if (track_nodes[player_seg].biome_id != start_biome) saw_new_biome = true;- if (fabsf_fast(track_nodes[player_seg].y - start_y) > 2.5f) saw_elev_change = true;- }- assert(inf_gen_count > initial_gen + 100 && "Infinity mode must continuously stream new segments ahead!");- assert(saw_new_biome && "Infinity mode must transition across terrain biomes!");- assert(saw_elev_change && "Infinity mode must generate changing hills and valleys!");- assert(!race_finished && current_lap >= 2 && "Infinity mode must never trigger race_finished and must advance zones!");- render_full_frame(false, false, mock_millis);- toggle_infinity_mode();-- // 5. Render Race Setup & Active Race with Boost Orbs & NPCs- race_total_laps = 3;- race_npc_count = 5;- render_menu_frame(2.85f, SCREEN_RACE_SETUP);- save_ppm("preview_setup.ppm");-- // Verify Black Stallion (car_id 3) and Brown Mustang (car_id 4) render cleanly- selected_car_id = 3;- render_menu_frame(2.40f, SCREEN_GARAGE);- assert(num_screen_tris > 40);-- selected_car_id = 4;- render_menu_frame(2.40f, SCREEN_GARAGE);- assert(num_screen_tris > 40);- save_ppm("preview_horse_garage.ppm");-- render_menu_frame(2.40f, SCREEN_CONTROLS);- save_ppm("preview_controls.ppm");-- reset_race_state(mock_millis);- for (int step = 0; step < 12; step++) {- mock_millis += 33;- frame_counter++;- step_physics(0.033f, false, false, true, false, false, step > 5, false, false, mock_millis);- }- render_full_frame(false, false, mock_millis);- assert(num_screen_tris > 250 && num_screen_tris < MAX_SCREEN_TRIS);- save_ppm("preview_race_npcs.ppm");-- printf("[PASS] Black Stallion & Brown Mustang, Infinity Mode, Steering & Orbs verified! Tris: %d\n",- num_screen_tris);- return 0;-}diff --git a/tests/test_games.py b/tests/test_games.pyindex e2a44a1c..a0c9e1a7 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -258,6 +258,10 @@ GAMES = {# from the copy, Continue: the race again (after a 3, 2, 1), quit with On/Off"turborush": ("TurboRush.nwa", "turborush.sav", presses((1500, "ok"), (2200, "ok"), (2900, "ok"), (9500, "back"))+ [(3500, 9000, K["up"])], 11000, presses((1500, "ok")) + [(3500, 6500, K["up"])], 7500),+ # the title's Play, Start race, the first-run guide's OK, then the race: flat out, Back to pause, Home. Next time,+ # from the copy, Continue: the race again (after a 3, 2, 1), quit with On/Off+ "polygt3d": ("PolyGT3D.nwa", "polygt3d.sav", presses((1500, "ok"), (2200, "ok"), (2900, "ok"), (9500, "back"))+ + [(3500, 9000, K["up"])], 11000, presses((1500, "ok")) + [(3500, 6500, K["up"])], 7500),# 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,@@ -324,7 +328,7 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p"jetpackjoyride": "jetpackjoyride_saves.py", "stickmanhook": "stickmanhook_saves.py","donkeykong": "donkeykong_saves.py", "dune": "dune_saves.py", "monkeymart": "monkeymart_saves.py","tombofthemask": "tombofthemask_saves.py", "uno": "uno_saves.py",- "fnf": "fnf_saves.py", "turborush": "turborush_saves.py"}+ "fnf": "fnf_saves.py", "turborush": "turborush_saves.py", "polygt3d": "polygt3d_saves.py"}def dk_frames(v):@@ -483,6 +487,12 @@ CHECKS = {and struct.unpack_from("<I", v, 164)[0] >= 1000,lambda v: len(v) == 492 and v[:4] == b"TRU1" and v[114] == 1 and v[127] == 1and struct.unpack_from("<I", v, 164)[0] >= 4000),+ # "PGT1", version 1, its size (496): the guide read (58), a race kept (64) and going (phase at 75), its clock (96)+ # running; after the reinstall, from the copy, the same race goes on+ "polygt3d": (lambda v: len(v) == 496 and v[:4] == b"PGT1" and v[4] == 1 and v[58] == 1 and v[64] == 1 and v[75] == 1+ and struct.unpack_from("<I", v, 96)[0] >= 1000,+ lambda v: len(v) == 496 and v[:4] == b"PGT1" and v[64] == 1 and v[75] == 1+ and struct.unpack_from("<I", v, 96)[0] >= 5000),"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 keptdiff --git a/tools/release.py b/tools/release.pyindex 270195d9..cd20be9c 100644--- a/tools/release.py+++ b/tools/release.py@@ -51,6 +51,7 @@ ALONE = {"uno": ("UNO", "the card game against one to three bots, with the official rules and scoring to 500"),"fnf": ("Friday Night Funkin'", "the Tutorial, Weeks 1 to 7, Weekend 1 and LE SSERAFIM, in story mode and freeplay"),"turborush": ("Turbo Rush", "an arcade racer by Bobydeluxe: six circuits, a Grand Prix, single races and Free Ride"),+ "polygt3d": ("PolyGT 3D", "a low-poly 3D racer by Boris-TH: three circuits against seven rivals, and the endless road"),}VARIANTS = [("NumPlay-Invisible.nwa", "The same app, hidden: a blank icon with no name"),