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
Moto X3M: the bike racing game, all 50 levels
Mason3637240ca9459a4
diff --git a/LICENSES/BSD-2-Clause-Nape.txt b/LICENSES/BSD-2-Clause-Nape.txtnew file mode 100644index 00000000..6e6c7f11--- /dev/null+++ b/LICENSES/BSD-2-Clause-Nape.txt@@ -0,0 +1,26 @@+Copyright (c) 2012, Luca Deltodesco+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++The views and conclusions contained in the software and documentation are those+of the authors and should not be interpreted as representing official policies,+either expressed or implied, of the Nape Project.diff --git a/Makefile b/Makefileindex 182dc678..77040b85 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 = angrybirds badtime balatro blockblast breakout buckshot catninja celeste championisland chess clashroyale connectfour cookieclicker coreball deltarune dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnaf3 fnaf4 fnafworld fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride kingdomrush leveldevil mahjong meowdoku minesweeper monkeymart mrbullet numblocks numpico numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock twoplayer undertale uno uttt+GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot catninja celeste championisland chess clashroyale connectfour cookieclicker coreball deltarune dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnaf3 fnaf4 fnafworld fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride kingdomrush leveldevil mahjong meowdoku minesweeper monkeymart motox3m mrbullet numblocks numpico numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock 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 AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 FiveNightsAtFreddys3 FiveNightsAtFreddys4 Famidash ClashRoyale UniversalPaperclips-French CatNinja KingdomRush Deltarune FiveNightsAtFreddysWorld MrBullet NumPico+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 AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 FiveNightsAtFreddys3 FiveNightsAtFreddys4 Famidash ClashRoyale UniversalPaperclips-French CatNinja KingdomRush Deltarune FiveNightsAtFreddysWorld MrBullet NumPico MotoX3M# 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 AngryBirds PolyTrack UniversalPaperclips UniversalPaperclips-French BadTimeSimulator Mahjong SnowRider3D TempleRun Famidash CatNinja MrBullet NumPico+APP_SPACE_APPS = HillClimbRacing FridayNightFunkin AngryBirds PolyTrack UniversalPaperclips UniversalPaperclips-French BadTimeSimulator Mahjong SnowRider3D TempleRun Famidash CatNinja MrBullet NumPico MotoX3M# 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@@ -343,6 +343,7 @@ APP_kingdomrush = $(B)/games/kingdomrush/kingdomrush.nwa:KingdomRush.nwaAPP_mrbullet = $(B)/games/mrbullet/mrbullet.nwa:MrBullet.nwaAPP_numpico = $(B)/games/numpico/numpico.nwa:NumPico.nwaAPP_deltarune = $(B)/games/deltarune/deltarune.nwa:Deltarune.nwa+APP_motox3m = $(B)/games/motox3m/motox3m.nwa:MotoX3M.nwa# the big games' modules are made from these (the kit)$(foreach g,$(XL_GAMES),$(eval MOD_$(g) = $$(word 1,$$(subst :, ,$$(APP_$(g))))))# (NumPico's leaves its table of carts to NumPlay Studio, which links the carts dropped on it in its block)@@ -399,6 +400,7 @@ apps: | $(B)$(MAKE) -C games/mrbullet build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/mrbullet$(MAKE) -C games/numpico build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/numpico$(MAKE) -C games/deltarune build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/deltarune+ $(MAKE) -C games/motox3m build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/motox3mcd 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)))@@ -452,6 +454,7 @@ apps: | $(B)cp $(word 1,$(subst :, ,$(APP_mrbullet))) $(B)/apps/$(word 2,$(subst :, ,$(APP_mrbullet)))cp $(word 1,$(subst :, ,$(APP_numpico))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numpico)))cp $(word 1,$(subst :, ,$(APP_deltarune))) $(B)/apps/$(word 2,$(subst :, ,$(APP_deltarune)))+ cp $(word 1,$(subst :, ,$(APP_motox3m))) $(B)/apps/$(word 2,$(subst :, ,$(APP_motox3m)))arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwaSTD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))@@ -545,5 +548,6 @@ clean:-$(MAKE) -C games/mrbullet clean-$(MAKE) -C games/numpico clean-$(MAKE) -C games/deltarune clean+ -$(MAKE) -C games/motox3m clean-cd games/tetris/tetris && $(CARGO) clean-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)diff --git a/README.md b/README.mdindex dae76e17..a31167f4 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@<p align="center"><b>29 free games for your NumWorks calculator, in one app.</b><br>- Plus 41 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.+ Plus 42 big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.</p><p align="center">@@ -75,94 +75,95 @@ The games with a blue ring are all in one app, **NumPlay.nwa**. The others are b<tr><td align="center" width="33%"><a href="games/crossyroad/README.md"><img src="docs/media/readme/thumb_crossyroad.png" width="240" alt="Crossy Road"><br><b>Crossy Road</b></a></td><td align="center" width="33%"><a href="games/rider/README.md"><img src="docs/media/readme/thumb_rider.png" width="240" alt="Rider"><br><b>Rider</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Rider.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/numdrive/README.md"><img src="docs/media/readme/thumb_numdrive.png" width="240" alt="NumDrive"><br><b>NumDrive</b></a></td>+ <td align="center" width="33%"><a href="games/motox3m/README.md"><img src="docs/media/readme/thumb_motox3m.png" width="240" alt="Moto X3M"><br><b>Moto X3M</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/MotoX3M.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/numdrive/README.md"><img src="docs/media/readme/thumb_numdrive.png" width="240" alt="NumDrive"><br><b>NumDrive</b></a></td><td align="center" width="33%"><a href="games/leveldevil/README.md"><img src="docs/media/readme/thumb_leveldevil.png" width="240" alt="Level Devil"><br><b>Level Devil</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/LevelDevil.nwa">Download</a></td><td align="center" width="33%"><a href="games/hillclimb/README.md"><img src="docs/media/readme/thumb_hillclimb.png" width="240" alt="Hill Climb Racing"><br><b>Hill Climb Racing</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/HillClimbRacing.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/pvz/README.md"><img src="docs/media/readme/thumb_pvz.png" width="240" alt="Plants vs. Zombies"><br><b>Plants vs. Zombies</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/PlantsVsZombies.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/pvz/README.md"><img src="docs/media/readme/thumb_pvz.png" width="240" alt="Plants vs. Zombies"><br><b>Plants vs. Zombies</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/PlantsVsZombies.nwa">Download</a></td><td align="center" width="33%"><a href="games/famidash/README.md"><img src="docs/media/readme/thumb_famidash.png" width="240" alt="Famidash"><br><b>Famidash</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Famidash.nwa">Download</a></td><td align="center" width="33%"><a href="games/doom/README.md"><img src="docs/media/readme/thumb_doom.png" width="240" alt="Doom"><br><b>Doom</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Doom.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/isaac/README.md"><img src="docs/media/readme/thumb_isaac.png" width="240" alt="The Binding of Isaac"><br><b>The Binding of Isaac</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/BindingOfIsaac.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/isaac/README.md"><img src="docs/media/readme/thumb_isaac.png" width="240" alt="The Binding of Isaac"><br><b>The Binding of Isaac</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/BindingOfIsaac.nwa">Download</a></td><td align="center" width="33%"><a href="games/cookieclicker/README.md"><img src="docs/media/readme/thumb_cookieclicker.png" width="240" alt="Cookie Clicker"><br><b>Cookie Clicker</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/CookieClicker.nwa">Download</a></td><td align="center" width="33%"><a href="games/jetpackjoyride/README.md"><img src="docs/media/readme/thumb_jetpackjoyride.png" width="240" alt="Jetpack Joyride"><br><b>Jetpack Joyride</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/JetpackJoyride.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/angrybirds/README.md"><img src="docs/media/readme/thumb_angrybirds.png" width="240" alt="Angry Birds"><br><b>Angry Birds</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/AngryBirds.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/angrybirds/README.md"><img src="docs/media/readme/thumb_angrybirds.png" width="240" alt="Angry Birds"><br><b>Angry Birds</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/AngryBirds.nwa">Download</a></td><td align="center" width="33%"><a href="games/fnf/README.md"><img src="docs/media/readme/thumb_fnf.png" width="240" alt="Friday Night Funkin'"><br><b>Friday Night Funkin'</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FridayNightFunkin.nwa">Download</a></td><td align="center" width="33%"><a href="games/kingdomrush/README.md"><img src="docs/media/readme/thumb_kingdomrush.png" width="240" alt="Kingdom Rush"><br><b>Kingdom Rush</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/KingdomRush.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/mrbullet/README.md"><img src="docs/media/readme/thumb_mrbullet.png" width="240" alt="Mr Bullet"><br><b>Mr Bullet</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/MrBullet.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/mrbullet/README.md"><img src="docs/media/readme/thumb_mrbullet.png" width="240" alt="Mr Bullet"><br><b>Mr Bullet</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/MrBullet.nwa">Download</a></td><td align="center" width="33%"><a href="games/sonic/README.md"><img src="docs/media/readme/thumb_sonic.png" width="240" alt="Sonic the Hedgehog"><br><b>Sonic the Hedgehog</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/SonicTheHedgehog.nwa">Download</a></td><td align="center" width="33%"><a href="games/portal/README.md"><img src="docs/media/readme/thumb_portal.png" width="240" alt="Portal Returns"><br><b>Portal Returns</b></a></td>- <td align="center" width="33%"><a href="games/stickmanhook/README.md"><img src="docs/media/readme/thumb_stickmanhook.png" width="240" alt="Stickman Hook"><br><b>Stickman Hook</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/StickmanHook.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/stickmanhook/README.md"><img src="docs/media/readme/thumb_stickmanhook.png" width="240" alt="Stickman Hook"><br><b>Stickman Hook</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/StickmanHook.nwa">Download</a></td><td align="center" width="33%"><a href="games/blockblast/README.md"><img src="docs/media/readme/thumb_blockblast.png" width="240" alt="Block Blast"><br><b>Block Blast</b></a></td><td align="center" width="33%"><a href="games/suika/README.md"><img src="docs/media/readme/thumb_suika.png" width="240" alt="Suika Game"><br><b>Suika Game</b></a></td>- <td align="center" width="33%"><a href="games/tombofthemask/README.md"><img src="docs/media/readme/thumb_tombofthemask.png" width="240" alt="Tomb of the Mask"><br><b>Tomb of the Mask</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/TombOfTheMask.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/tombofthemask/README.md"><img src="docs/media/readme/thumb_tombofthemask.png" width="240" alt="Tomb of the Mask"><br><b>Tomb of the Mask</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/TombOfTheMask.nwa">Download</a></td><td align="center" width="33%"><a href="games/monkeymart/README.md"><img src="docs/media/readme/thumb_monkeymart.png" width="240" alt="Monkey Mart"><br><b>Monkey Mart</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/MonkeyMart.nwa">Download</a></td><td align="center" width="33%"><a href="games/badtime/README.md"><img src="docs/media/readme/thumb_badtime.png" width="240" alt="Bad Time Simulator"><br><b>Bad Time Simulator</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/BadTimeSimulator.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/catninja/README.md"><img src="docs/media/readme/thumb_catninja.png" width="240" alt="Cat Ninja"><br><b>Cat Ninja</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/CatNinja.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/catninja/README.md"><img src="docs/media/readme/thumb_catninja.png" width="240" alt="Cat Ninja"><br><b>Cat Ninja</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/CatNinja.nwa">Download</a></td><td align="center" width="33%"><a href="games/championisland/README.md"><img src="docs/media/readme/thumb_championisland.png" width="240" alt="Champion Island"><br><b>Champion Island</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/ChampionIsland.nwa">Download</a></td><td align="center" width="33%"><a href="games/numpowder/README.md"><img src="docs/media/readme/thumb_numpowder.png" width="240" alt="NumPowder"><br><b>NumPowder</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumPowder.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/finalearth2/README.md"><img src="docs/media/readme/thumb_finalearth2.png" width="240" alt="The Final Earth 2"><br><b>The Final Earth 2</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FinalEarth2.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/finalearth2/README.md"><img src="docs/media/readme/thumb_finalearth2.png" width="240" alt="The Final Earth 2"><br><b>The Final Earth 2</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FinalEarth2.nwa">Download</a></td><td align="center" width="33%"><a href="games/paperclips/README.md"><img src="docs/media/readme/thumb_paperclips.png" width="240" alt="Universal Paperclips"><br><b>Universal Paperclips</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/UniversalPaperclips.nwa">Download</a></td><td align="center" width="33%"><a href="games/dune/README.md"><img src="docs/media/readme/thumb_dune.png" width="240" alt="Dune"><br><b>Dune</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Dune.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/flappybird/README.md"><img src="docs/media/readme/thumb_flappybird.png" width="240" alt="Flappy Bird"><br><b>Flappy Bird</b></a></td></tr><tr>+ <td align="center" width="33%"><a href="games/flappybird/README.md"><img src="docs/media/readme/thumb_flappybird.png" width="240" alt="Flappy Bird"><br><b>Flappy Bird</b></a></td><td align="center" width="33%"><a href="games/doodlejump/README.md"><img src="docs/media/readme/thumb_doodlejump.png" width="240" alt="Doodle Jump"><br><b>Doodle Jump</b></a></td><td align="center" width="33%"><a href="games/dinorun/README.md"><img src="docs/media/readme/thumb_dinorun.png" width="240" alt="Chrome Dino"><br><b>Chrome Dino</b></a></td>- <td align="center" width="33%"><a href="games/tetris/README.md"><img src="docs/media/readme/thumb_tetris.png" width="240" alt="Tetris"><br><b>Tetris</b></a></td></tr><tr>+ <td align="center" width="33%"><a href="games/tetris/README.md"><img src="docs/media/readme/thumb_tetris.png" width="240" alt="Tetris"><br><b>Tetris</b></a></td><td align="center" width="33%"><a href="games/pacman/README.md"><img src="docs/media/readme/thumb_pacman.png" width="240" alt="Pac-Man"><br><b>Pac-Man</b></a></td><td align="center" width="33%"><a href="games/donkeykong/README.md"><img src="docs/media/readme/thumb_donkeykong.png" width="240" alt="Donkey Kong"><br><b>Donkey Kong</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/DonkeyKong.nwa">Download</a></td>- <td align="center" width="33%"><a href="games/flappydunk/README.md"><img src="docs/media/readme/thumb_flappydunk.png" width="240" alt="Flappy Dunk"><br><b>Flappy Dunk</b></a></td></tr><tr>+ <td align="center" width="33%"><a href="games/flappydunk/README.md"><img src="docs/media/readme/thumb_flappydunk.png" width="240" alt="Flappy Dunk"><br><b>Flappy Dunk</b></a></td><td align="center" width="33%"><a href="games/towerblock/README.md"><img src="docs/media/readme/thumb_towerblock.png" width="240" alt="Tower Blocks"><br><b>Tower Blocks</b></a></td><td align="center" width="33%"><a href="games/coreball/README.md"><img src="docs/media/readme/thumb_coreball.png" width="240" alt="Core Ball"><br><b>Core Ball</b></a></td>- <td align="center" width="33%"><a href="games/uno/README.md"><img src="docs/media/readme/thumb_uno.png" width="240" alt="UNO"><br><b>UNO</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/UNO.nwa">Download</a></td></tr><tr>+ <td align="center" width="33%"><a href="games/uno/README.md"><img src="docs/media/readme/thumb_uno.png" width="240" alt="UNO"><br><b>UNO</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/UNO.nwa">Download</a></td><td align="center" width="33%"><a href="games/twoplayer/README.md"><img src="docs/media/readme/thumb_twoplayer.png" width="240" alt="2 Players"><br><b>2 Players</b></a></td><td align="center" width="33%"><a href="games/chess/README.md"><img src="docs/media/readme/thumb_chess.png" width="240" alt="Chess"><br><b>Chess</b></a></td>- <td align="center" width="33%"><a href="games/invaders/README.md"><img src="docs/media/readme/thumb_invaders.png" width="240" alt="Space Invaders"><br><b>Space Invaders</b></a></td></tr><tr>+ <td align="center" width="33%"><a href="games/invaders/README.md"><img src="docs/media/readme/thumb_invaders.png" width="240" alt="Space Invaders"><br><b>Space Invaders</b></a></td><td align="center" width="33%"><a href="games/breakout/README.md"><img src="docs/media/readme/thumb_breakout.png" width="240" alt="Block Breaker"><br><b>Block Breaker</b></a></td><td align="center" width="33%"><a href="games/snake/README.md"><img src="docs/media/readme/thumb_snake.png" width="240" alt="Snake"><br><b>Snake</b></a></td>- <td align="center" width="33%"><a href="games/connectfour/README.md"><img src="docs/media/readme/thumb_connectfour.png" width="240" alt="Connect Four"><br><b>Connect Four</b></a></td></tr><tr>+ <td align="center" width="33%"><a href="games/connectfour/README.md"><img src="docs/media/readme/thumb_connectfour.png" width="240" alt="Connect Four"><br><b>Connect Four</b></a></td><td align="center" width="33%"><a href="games/mahjong/README.md"><img src="docs/media/readme/thumb_mahjong.png" width="240" alt="Mahjong"><br><b>Mahjong</b></a><br><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Mahjong.nwa">Download</a></td><td align="center" width="33%"><a href="games/g2048/README.md"><img src="docs/media/readme/thumb_g2048.png" width="240" alt="2048"><br><b>2048</b></a></td>- <td align="center" width="33%"><a href="games/solitaire/README.md"><img src="docs/media/readme/thumb_solitaire.png" width="240" alt="Solitaire"><br><b>Solitaire</b></a></td></tr><tr>+ <td align="center" width="33%"><a href="games/solitaire/README.md"><img src="docs/media/readme/thumb_solitaire.png" width="240" alt="Solitaire"><br><b>Solitaire</b></a></td><td align="center" width="33%"><a href="games/minesweeper/README.md"><img src="docs/media/readme/thumb_minesweeper.png" width="240" alt="Minesweeper"><br><b>Minesweeper</b></a></td><td align="center" width="33%"><a href="games/uttt/README.md"><img src="docs/media/readme/thumb_uttt.png" width="240" alt="Ultimate Tic-Tac-Toe"><br><b>Ultimate Tic-Tac-Toe</b></a></td>- <td align="center" width="33%"><a href="games/sudoku/README.md"><img src="docs/media/readme/thumb_sudoku.png" width="240" alt="Sudoku"><br><b>Sudoku</b></a></td></tr><tr>+ <td align="center" width="33%"><a href="games/sudoku/README.md"><img src="docs/media/readme/thumb_sudoku.png" width="240" alt="Sudoku"><br><b>Sudoku</b></a></td><td align="center" width="33%"><a href="games/sokoban/README.md"><img src="docs/media/readme/thumb_sokoban.png" width="240" alt="Sokoban"><br><b>Sokoban</b></a></td><td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-64"><b>Super Mario 64</b></a></td>- <td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-Bros"><b>Super Mario Bros.</b></a></td></tr><tr>+ <td align="center"><a href="https://github.com/Mason363/NumWorks-Super-Mario-Bros"><b>Super Mario Bros.</b></a></td><td align="center"><a href="#roadmap"><b>More on the way</b></a></td></tr></table>@@ -330,10 +331,10 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an- [x] Crossy Road: the characters and the prize machine- [x] Famidash: its newest and fullest version, HUGE, with 173 levels- [x] ColecoVision games in Retro-Go+- [x] Five Nights at Freddy's 3</details>-- [x] Five Nights at Freddy's 3- [x] Five Nights at Freddy's 4- [x] Clash Royale, against bots- [x] Cat Ninja@@ -343,6 +344,7 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an- [x] FNAF World- [x] Mr. Bullet- [x] A PICO-8 emulator, NumPico: add your own .p8 games on the website+- [x] Moto X3M- [ ] Full Minecraft 1.18.2 as a standalone app- [ ] Among Us, against bots- [ ] Into the Breach@@ -431,6 +433,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks- **Deltarune** by Toby Fox inspired NumPlay's Deltarune, which uses the pictures, fonts, rooms and texts of Chapter 1's own files. Not affiliated with Toby Fox.- **FNAF World** by Scott Cawthon inspired NumPlay's FNAF World, which uses the game's own pictures and map and runs its battles as the game's own events do, all read from its Windows release. Not affiliated with Scott Cawthon.- **Mr Bullet - Spy Puzzles** by Lion Studios and 1Button inspired NumPlay's Mr Bullet, which plays the game's Classic, Grenades, Hostages and Friendly Fire levels with its own pictures, read from its Android release, and follows its rules and numbers. Its physics is **Box2D 2.3.1** by Erin Catto (zlib license, [license](LICENSES/Zlib-Box2D.txt)), the engine the game runs on. Not affiliated with Lion Studios.+- **Moto X3M** by Madpuffers inspired NumPlay's Moto X3M, which plays the game's 50 levels with its own pictures and its **Impact** and **CF Crack and Bold** fonts, read from its web release, and follows its rules and numbers. Its physics is **[Nape](https://github.com/deltaluca/nape)** by Luca Deltodesco (BSD license, [license](LICENSES/BSD-2-Clause-Nape.txt)), the engine the game runs on, ported to C. Not affiliated with Madpuffers.- **PICO-8** by Lexaloffle inspired NumPlay's NumPico, which runs PICO-8 carts with **[femto8](https://github.com/benbaker76/femto8)** by Ben Baker (MIT license, [license](LICENSES/MIT-femto8.txt)) and its Lua, z8lua by Sam Hocevar (WTFPL) on Lua 5.2 (MIT license), and unpacks .p8.png carts with Lexaloffle's own algorithms (MIT and zlib licenses). Its pictures show [Combo Pool](https://www.lexaloffle.com/bbs/?pid=combopool-0) by NuSan (CC4-BY-NC-SA), which isn't in NumPlay. Not affiliated with Lexaloffle.- **Pong** by Atari (1972) inspired NumPlay's 2 Players, with air hockey, tanks in a maze in the spirit of Tank Trouble and the light cycles of Tron. All four are written in C for NumPlay and drawn from shapes, with no code or art from them.- **[Cookie Clicker](https://orteil.dashnet.org/cookieclicker/)** by Orteil and Opti (DashNet) inspired NumPlay's Cookie Clicker, which uses the game's own pictures, texts and numbers (version 2.058, from its public mirror [ozh/cookieclicker](https://github.com/ozh/cookieclicker)) and the **Merriweather**, **Kavoon** and **Noto Sans** fonts (SIL Open Font License: [Merriweather](LICENSES/OFL-1.1-Merriweather.txt), [Kavoon](LICENSES/OFL-1.1-Kavoon.txt), [Noto Sans](LICENSES/OFL-1.1-NotoSans.txt)). Not affiliated with Orteil or DashNet.@@ -468,7 +471,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorksNumPlay is licensed under the [GNU General Public License v3.0](LICENSE). Copyright (c) 2026 Mason Chen. Code and fonts from others keep their own licenses: the `UNLICENSE` files in the games' folders and the [LICENSES](LICENSES) folder. The names, artwork and music of the games NumPlay is inspired by belong to their makers and are not covered by it.-<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Hungry Studio (Block Blast!), Aladdin X (Suika Game), Voodoo (Flappy Dunk), Lima Sky (Doodle Jump), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale, Deltarune), jcw87 (Bad Time Simulator), Imangi Studios (Temple Run), id Software (Doom), Edmund McMillen, Florian Himsl or Nicalis (The Binding of Isaac), PopCap Games or Electronic Arts (Plants vs. Zombies), Scott Cawthon (Five Nights at Freddy's, Five Nights at Freddy's 2, Five Nights at Freddy's 3, Five Nights at Freddy's 4, FNAF World), SEGA (Sonic the Hedgehog, Master System, Game Gear, SG-1000), SYBO or Kiloo (Subway Surfers), Fingersoft (Hill Climb Racing), Unept (Level Devil), Halfbrick (Jetpack Joyride), Madbox (Stickman Hook), Nintendo (Donkey Kong, Game Boy, NES), Team Lava (Dune!), Inlogic Software (Dune Rider), TinyDobbins (Monkey Mart), Playgendary (Tomb of the Mask), Mattel (UNO), the Funkin' Crew (Friday Night Funkin'), Rovio Entertainment (Angry Birds), Kodub (PolyTrack), Frank Lantz or Everybody House Games (Universal Paperclips), the makers of Snow Rider 3D, Ketchapp (Rider), TFDSoft (Famidash), Brodie Lockard or Activision (Shanghai), Atari (Pong), Disney (Tron), Orteil or DashNet (Cookie Clicker), Taito or Midway (Space Invaders), Thinking Rabbit or Falcon (Sokoban), Oakever Games (Meowdoku), Florian van Strien (The Final Earth 2), The Powder Toy's developers (The Powder Toy), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Chrome Dino, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper), ducalex (Retro-Go), Coleco (ColecoVision), Supercell (Clash Royale), Richman Stewart or TrackMill (Cat Ninja), Ironhide Game Studio or Armor Games (Kingdom Rush), Lion Studios (Mr Bullet), Lexaloffle (PICO-8). Tetris is a trademark of The Tetris Company, Chrome of Google LLC, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco, Connect Four of Hasbro, DOOM of ZeniMax Media, Sonic the Hedgehog, Master System, Game Gear and SG-1000 of SEGA, Space Invaders of Taito, UNO of Mattel, Angry Birds of Rovio Entertainment, Clash Royale of Supercell, and Donkey Kong, Game Boy, Game Boy Color and NES of Nintendo.</sub>+<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Hungry Studio (Block Blast!), Aladdin X (Suika Game), Voodoo (Flappy Dunk), Lima Sky (Doodle Jump), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Toby Fox (Undertale, Deltarune), jcw87 (Bad Time Simulator), Imangi Studios (Temple Run), id Software (Doom), Edmund McMillen, Florian Himsl or Nicalis (The Binding of Isaac), PopCap Games or Electronic Arts (Plants vs. Zombies), Scott Cawthon (Five Nights at Freddy's, Five Nights at Freddy's 2, Five Nights at Freddy's 3, Five Nights at Freddy's 4, FNAF World), SEGA (Sonic the Hedgehog, Master System, Game Gear, SG-1000), SYBO or Kiloo (Subway Surfers), Fingersoft (Hill Climb Racing), Unept (Level Devil), Halfbrick (Jetpack Joyride), Madbox (Stickman Hook), Nintendo (Donkey Kong, Game Boy, NES), Team Lava (Dune!), Inlogic Software (Dune Rider), TinyDobbins (Monkey Mart), Playgendary (Tomb of the Mask), Mattel (UNO), the Funkin' Crew (Friday Night Funkin'), Rovio Entertainment (Angry Birds), Kodub (PolyTrack), Frank Lantz or Everybody House Games (Universal Paperclips), the makers of Snow Rider 3D, Ketchapp (Rider), TFDSoft (Famidash), Brodie Lockard or Activision (Shanghai), Atari (Pong), Disney (Tron), Orteil or DashNet (Cookie Clicker), Taito or Midway (Space Invaders), Thinking Rabbit or Falcon (Sokoban), Oakever Games (Meowdoku), Florian van Strien (The Final Earth 2), The Powder Toy's developers (The Powder Toy), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Chrome Dino, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper), ducalex (Retro-Go), Coleco (ColecoVision), Supercell (Clash Royale), Richman Stewart or TrackMill (Cat Ninja), Ironhide Game Studio or Armor Games (Kingdom Rush), Lion Studios (Mr Bullet), Lexaloffle (PICO-8), Madpuffers (Moto X3M). Tetris is a trademark of The Tetris Company, Chrome of Google LLC, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco, Connect Four of Hasbro, DOOM of ZeniMax Media, Sonic the Hedgehog, Master System, Game Gear and SG-1000 of SEGA, Space Invaders of Taito, UNO of Mattel, Angry Birds of Rovio Entertainment, Clash Royale of Supercell, and Donkey Kong, Game Boy, Game Boy Color and NES of Nintendo.</sub>## Gallery@@ -593,4 +596,7 @@ NumPlay is licensed under the [GNU General Public License v3.0](LICENSE). Copyri<td align="center"><img src="docs/media/gallery/mrbullet.gif" alt="Mr Bullet: the first three levels, the third cleared with one bullet off the stairs"><br><a href="games/mrbullet/README.md"><b>Mr Bullet</b></a></td><td align="center"><img src="docs/media/gallery/numpico.gif" alt="NumPico: Combo Pool's balls roll and bounce on a tiled table"><br><a href="games/numpico/README.md"><b>NumPico</b></a></td></tr>+ <tr>+ <td align="center"><img src="docs/media/gallery/motox3m.gif" alt="Moto X3M: level 2 on the beach, a back flip over the pit and its half second off the clock"><br><a href="games/motox3m/README.md"><b>Moto X3M</b></a></td>+ </tr></table>diff --git a/_config.yml b/_config.ymlindex 06e4636b..bc7f2d1f 100644--- a/_config.yml+++ b/_config.yml@@ -1,5 +1,5 @@title: NumPlay-description: "29 games for the NumWorks calculator in one app: NumDash, Crossy Road, NumBlocks, NumDrive, Balatro, Buckshot Roulette, Block Blast, Suika Game, Portal Returns, Tetris, Chrome Dino, Chess, Space Invaders, Sudoku and more. And Doom, Sonic, Plants vs. Zombies, Cookie Clicker, Mahjong, Meowdoku, Rider, Snow Rider 3D, Temple Run, Five Nights at Freddy's 2, Famidash, Clash Royale, Cat Ninja, Kingdom Rush, Deltarune, FNAF World, Mr Bullet and more on their own. Free and open source, with a kit to make your own NumWorks games in C."+description: "29 games for the NumWorks calculator in one app: NumDash, Crossy Road, NumBlocks, NumDrive, Balatro, Buckshot Roulette, Block Blast, Suika Game, Portal Returns, Tetris, Chrome Dino, Chess, Space Invaders, Sudoku and more. And Doom, Sonic, Plants vs. Zombies, Cookie Clicker, Mahjong, Meowdoku, Rider, Snow Rider 3D, Temple Run, Five Nights at Freddy's 2, Famidash, Clash Royale, Cat Ninja, Kingdom Rush, Deltarune, FNAF World, Mr Bullet, Moto X3M and more on their own. Free and open source, with a kit to make your own NumWorks games in C."url: https://mason363.github.iobaseurl: /NumPlaytheme: jekyll-theme-caymandiff --git a/docs/media/gallery/motox3m.gif b/docs/media/gallery/motox3m.gifnew file mode 100644index 00000000..751bf771Binary files /dev/null and b/docs/media/gallery/motox3m.gif differdiff --git a/docs/media/readme/thumb_motox3m.png b/docs/media/readme/thumb_motox3m.pngnew file mode 100644index 00000000..7f81b1ceBinary files /dev/null and b/docs/media/readme/thumb_motox3m.png differdiff --git a/docs/media/thumb_motox3m.png b/docs/media/thumb_motox3m.pngnew file mode 100644index 00000000..6dda0d68Binary files /dev/null and b/docs/media/thumb_motox3m.png differdiff --git a/docs/play.md b/docs/play.mdindex 5acad2fb..9d35cc88 100644--- a/docs/play.md+++ b/docs/play.md@@ -864,6 +864,23 @@ Shoot every spy in the level. Bullets bounce off walls, so aim at a wall to reac<br clear="right">+## Moto X3M++<img src="../games/motox3m/docs/shot.png" width="320" align="right" alt="Moto X3M">++| Key | What it does |+| --- | --- |+| **Up** | Gas |+| **Down** | Brake |+| **Left** and **Right** | Lean (flip in the air) |+| **OK** | Go on after a crash |+| **Back** | Pause (Resume, Restart, Levels, Quit game) |+| **Home** | Save and quit |++Ride to the finish as fast as you can. Lean to land on your wheels, and keep leaning in the air to flip: each flip takes half a second off your time. If your head hits the ground, or you touch spikes, a saw or water, you crash and go on from the last checkpoint. Beat a level's times for up to three stars. Stars open new bikes in the bike shop.++<br clear="right">+## NumPico<img src="../games/numpico/docs/shot.png" width="320" align="right" alt="NumPico playing Combo Pool">diff --git a/games/games.json b/games/games.jsonindex 44c1ea57..92cb90c0 100644--- a/games/games.json+++ b/games/games.json@@ -1592,5 +1592,26 @@"default": false,"xl": true,"carts": true+ },+ {+ "id": "motox3m",+ "rank": 44,+ "title": "Moto X3M",+ "tagline": "Flip the bike, beat the clock",+ "credit": "Based on Moto X3M by Madpuffers",+ "top": "0xF0B040",+ "bottom": "0x10304A",+ "accent": "0x2A9AD8",+ "colors": 16,+ "records": [+ "motox3m.sav",+ "motox3m_saves.py"+ ],+ "shots": [+ "docs/shot.png"+ ],+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/motox3m",+ "default": false,+ "xl": true}]diff --git a/games/motox3m/.gitignore b/games/motox3m/.gitignorenew file mode 100644index 00000000..342d9dda--- /dev/null+++ b/games/motox3m/.gitignore@@ -0,0 +1,2 @@+output/+build/diff --git a/games/motox3m/Makefile b/games/motox3m/Makefilenew file mode 100644index 00000000..009965db--- /dev/null+++ b/games/motox3m/Makefile@@ -0,0 +1,84 @@+# Moto X3M on the NumWorks calculator (C; the physics are Nape's, ported: src/nape.c).+# make output/motox3m.nwa+# make check link it like the calculator does (output/motox3m.bin)+# make host build/play: the game on a computer, for tests and screenshots+# make test the game played on a computer (tests/check.py, with the sanitizers)+# make data src/data.bin, src/data.h and src/bike_data.h from the game's web build+# (REF=its folder, Python + Pillow + NumPy)+Q ?= @+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>+TOOLCHAIN ?=+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)+CC = $(BIN)arm-none-eabi-gcc+NWLINK ?= npx --yes -- [email protected]+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded+SIZE = $(BIN)arm-none-eabi-size+BUILD_DIR = output+REF ?=++# the physics and the drawing run every frame at -O2; the rest is small at -Os+HOT = src/nape.c src/gfx.c src/view.c+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h++CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DEPSILON_XL=1 -DDATA_BIN='"src/data.bin"'+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel++.PHONY: build check clean host test data+build: $(BUILD_DIR)/motox3m.nwa++# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones); installed on its+# own, the app must fit the calculator's space for apps (0x90200000 to 0x903F0000 in its flash)+RAM_LENGTH = 133652+APP_SPACE = 2031616+check: $(BUILD_DIR)/motox3m.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length $(RAM_LENGTH) $< $(BUILD_DIR)/motox3m.bin+ @n=$$(wc -c < $(BUILD_DIR)/motox3m.bin); \+ echo "BIN $(BUILD_DIR)/motox3m.bin: $$n bytes, $$(( $(APP_SPACE) - n )) to spare of the app space"; \+ [ $$n -le $(APP_SPACE) ] || { echo "motox3m.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }++$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@++$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@++$(BUILD_DIR)/motox3m.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@+ $(Q) $(STRIP) $@+ $(Q) $(SIZE) $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@++# on a computer: tests/play.c plays it with scripted keys and saves screenshots+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c))+host: build/play+build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS)+ $(Q) mkdir -p $(dir $@)+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c src/data.S -lm -o $@+ @echo "HOST $@"++test: build/play+ python3 tests/check.py build/play++data:+ @test -n "$(REF)" || { echo "make data REF=<the game's web build>"; exit 1; }+ python3 -I tools/pack.py $(REF)++clean:+ $(Q) rm -rf $(BUILD_DIR) builddiff --git a/games/motox3m/README.md b/games/motox3m/README.mdnew file mode 100644index 00000000..17441e1e--- /dev/null+++ b/games/motox3m/README.md@@ -0,0 +1,82 @@+> **Moto X3M is a [NumPlay](../../README.md) game that comes on its own.** It is too big to fit next to NumPlay on the calculator. Get `MotoX3M.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).++<p align="center">+ <img src="src/icon.png" width="84" alt="Moto X3M icon">+</p>++<h1 align="center">Moto X3M</h1>++<p align="center">+ <b>Race your bike through 50 levels of loops, jumps and traps, on the NumWorks calculator.</b><br>+ Flip in the air, beat the clock, earn stars and new bikes.+</p>++<p align="center">+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/MotoX3M.nwa"><b>Download MotoX3M.nwa</b></a>+ · <a href="#controls">Controls</a>+</p>++<p align="center">+ <img src="../../docs/media/gallery/motox3m.gif" width="640" alt="Moto X3M: level 2 on the beach, a back flip over the pit and its half second off the clock">+</p>++## Highlights++* **The game's own 50 levels:** read from Moto X3M's web release, with every loop, ramp, saw, spike, barrel and TNT where the original puts them.+* **The real physics:** Nape, the engine the original runs on, ported to C and set up as the original sets it up: the same gravity, steps, bike, springs and rider. The rider goes limp when you crash.+* **Everything in the levels:** TNT that blows up, glass that breaks, planks that fall, gates and switches, moving platforms, geysers, boosts and water.+* **Flips:** each one takes half a second off your time.+* **Stars and bikes:** beat each level's three times for stars. Stars open the six bikes of the bike shop.+* **The game's look:** its three worlds, its bikes, rider, menus, level map and fonts.+* **Saves:** every level's stars and best time. Home saves and quits. Your progress is also copied into `motox3m_saves.py`, so installing the app again doesn't erase it.++<table>+ <tr>+ <td align="center"><img src="docs/shot.png" width="390" alt="A back flip over a pit on the beach"><br><sub>Flip for half a second off</sub></td>+ <td align="center"><img src="docs/l22.png" width="390" alt="The bike in a loop between two big wheels"><br><sub>Loops</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/l9.png" width="390" alt="TNT blowing rocks into the air"><br><sub>TNT</sub></td>+ <td align="center"><img src="docs/l30.png" width="390" alt="The bike under a sawblade at sunset"><br><sub>Saws</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/map.png" width="390" alt="The level map"><br><sub>The level map</sub></td>+ <td align="center"><img src="docs/finish.png" width="390" alt="Level 3 complete with one star"><br><sub>Stars by time</sub></td>+ </tr>+</table>++## How to play++Ride to the finish as fast as you can. Up is the gas and Down the brake. Left and Right lean the bike: lean to land on your wheels, and keep leaning in the air to flip. Each flip takes half a second off your time. If your head hits the ground, or you touch spikes, a saw or water, you crash: press OK to go on from the last checkpoint.++Beat a level's times for one, two or three stars. Finishing a level opens the next one. Stars open new bikes in the bike shop: 10, 20, 30, 40 and 50 stars.++## Controls++| Key | What it does |+| --- | --- |+| Up | Gas |+| Down | Brake |+| Left and Right | Lean (flip in the air) |+| OK | Go on after a crash |+| Back | Pause (Resume, Restart, Levels, Quit game) |+| Home | Save and quit |++## Good to know++* **On its own:** Moto X3M 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.+* **What's in:** the 50 levels of the web version 1.2.4. There is no music or sound (the calculator has no speaker).+* **Far off the screen:** to save the calculator's memory, loose planks and barrels far from the screen hold still until you come near.++## Credits++Inspired by Moto X3M by Madpuffers, not affiliated with them. Go play the original.++* The levels, the bikes, the rider, the worlds, the menus and the **Impact** and **CF Crack and Bold** fonts come from the game's web release, read by [tools/pack.py](tools/pack.py) into `src/data.bin`. Its rules and numbers follow the game's own code.+* The physics is [Nape](https://github.com/deltaluca/nape) by Luca Deltodesco (BSD 2-clause license, see [LICENSES/BSD-2-Clause-Nape.txt](../../LICENSES/BSD-2-Clause-Nape.txt)), ported to C in [src/nape.c](src/nape.c).++Made by Mason Chen as part of NumPlay.++## License++The game's code is licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. The physics keeps Nape's BSD license. The game's pictures, fonts and levels keep their own terms (see Credits). Moto X3M is a trademark of Madpuffers.diff --git a/games/motox3m/docs/finish.png b/games/motox3m/docs/finish.pngnew file mode 100644index 00000000..997af5e9Binary files /dev/null and b/games/motox3m/docs/finish.png differdiff --git a/games/motox3m/docs/l14.png b/games/motox3m/docs/l14.pngnew file mode 100644index 00000000..810dedc7Binary files /dev/null and b/games/motox3m/docs/l14.png differdiff --git a/games/motox3m/docs/l2.png b/games/motox3m/docs/l2.pngnew file mode 100644index 00000000..909518adBinary files /dev/null and b/games/motox3m/docs/l2.png differdiff --git a/games/motox3m/docs/l22.png b/games/motox3m/docs/l22.pngnew file mode 100644index 00000000..135f6706Binary files /dev/null and b/games/motox3m/docs/l22.png differdiff --git a/games/motox3m/docs/l30.png b/games/motox3m/docs/l30.pngnew file mode 100644index 00000000..e35457c9Binary files /dev/null and b/games/motox3m/docs/l30.png differdiff --git a/games/motox3m/docs/l5.png b/games/motox3m/docs/l5.pngnew file mode 100644index 00000000..01a799c5Binary files /dev/null and b/games/motox3m/docs/l5.png differdiff --git a/games/motox3m/docs/l9.png b/games/motox3m/docs/l9.pngnew file mode 100644index 00000000..bdef4932Binary files /dev/null and b/games/motox3m/docs/l9.png differdiff --git a/games/motox3m/docs/lean.png b/games/motox3m/docs/lean.pngnew file mode 100644index 00000000..dfa1d34fBinary files /dev/null and b/games/motox3m/docs/lean.png differdiff --git a/games/motox3m/docs/map.png b/games/motox3m/docs/map.pngnew file mode 100644index 00000000..cb8af31fBinary files /dev/null and b/games/motox3m/docs/map.png differdiff --git a/games/motox3m/docs/pause.png b/games/motox3m/docs/pause.pngnew file mode 100644index 00000000..27a592b7Binary files /dev/null and b/games/motox3m/docs/pause.png differdiff --git a/games/motox3m/docs/shop.png b/games/motox3m/docs/shop.pngnew file mode 100644index 00000000..913087bbBinary files /dev/null and b/games/motox3m/docs/shop.png differdiff --git a/games/motox3m/docs/shot.png b/games/motox3m/docs/shot.pngnew file mode 100644index 00000000..6baa00d2Binary files /dev/null and b/games/motox3m/docs/shot.png differdiff --git a/games/motox3m/docs/title.png b/games/motox3m/docs/title.pngnew file mode 100644index 00000000..f31bb062Binary files /dev/null and b/games/motox3m/docs/title.png differdiff --git a/games/motox3m/src/bike.c b/games/motox3m/src/bike.cnew file mode 100644index 00000000..d81514bf--- /dev/null+++ b/games/motox3m/src/bike.c@@ -0,0 +1,702 @@+/* Moto X3M: the bike and its rider (see bike.h). Numbers from the game's levels/1.json and levels/bike.json. */+#include <math.h>+#include <string.h>+#include "bike.h"+#include "bike_data.h"+#include "fx.h"+#include "level.h"+#include "plat.h"++Bike bike;++#define TO_RAD 0.017453292519943295f+#define PI 3.14159265358979f+#define LONG_FLY_TIME 0.1f+#define DAMPING_DELTA 0.99f+#define MIN_AC_BR_TIME 1.0f+#define MAX_VEL_TIME 2.0f+#define FRAME_END_DELAY 0.1f+#define WHEEL_END_DELAY 0.25f+#define START_SPIN_FRICTION 0.01f+#define START_SPIN_DELAY 1.0f+#define SMOKE_TIME 0.2f++extern Body *np_world(void);+static int nmats_base;+static float max_ang_vel, accel_torque, delta_torque, tilt_torque, max_tilt_speed, wheel_radius;++/* the shapes' materials go after the level's in sp.mats */+static uint8_t add_mat(float el, float dyn, float stat, float density, float rolling) {+ Material *m = &sp.mats[nmats_base++];+ m->elasticity = el, m->dyn = dyn, m->stat = stat, m->density = density, m->rolling = rolling;+ return (uint8_t)(nmats_base - 1);+}++static void box(float *loc, float w, float h, float ox, float oy) {+ float v[8] = {-w / 2 + ox, -h / 2 + oy, w / 2 + ox, -h / 2 + oy, w / 2 + ox, h / 2 + oy, -w / 2 + ox, h / 2 + oy};+ memcpy(loc, v, sizeof v);+}++/* a polygon's area, centre and inertia per unit mass about the origin (Polygon.__validate_area_inertia) */+static void poly_props(Shape *s) {+ const V2 *v = (const V2 *)(const void *)s->loc;+ int n = s->n;+ float area = 0, s1 = 0, s2 = 0, cx = 0, cy = 0;+ for (int i = 0; i < n; i++) {+ V2 u = v[(i + n - 1) % n], p = v[i], w = v[(i + 1) % n];+ float a = u.x * p.y - u.y * p.x, b = p.x * p.x + p.y * p.y + p.x * u.x + p.y * u.y + u.x * u.x + u.y * u.y;+ s1 += a * b, s2 += a;+ area += p.x * (w.y - u.y);+ float cf = p.x * w.y - p.y * w.x;+ cx += (p.x + w.x) * cf, cy += (p.y + w.y) * cf;+ }+ s->inertia = s1 / (6 * s2);+ s->lcom = v2(cx / (3 * area), cy / (3 * area));+ s->area = area * 0.5f;+}++static void poly_shape(Shape *s, float *loc, float *glob, int n, uint8_t mat, uint8_t filter) {+ s->type = SH_POLY, s->n = (uint8_t)n, s->loc = loc, s->glob = glob, s->mat = mat, s->filter = filter;+ /* Nape keeps polygons with a positive area */+ float a = 0;+ for (int i = 0; i < n; i++) {+ int j = (i + 1) % n, k = (i + n - 1) % n;+ a += loc[2 * i] * (loc[2 * j + 1] - loc[2 * k + 1]);+ }+ if (a < 0)+ for (int i = 0; i < n / 2; i++) {+ float tx = loc[2 * i], ty = loc[2 * i + 1];+ loc[2 * i] = loc[2 * (n - 1 - i)], loc[2 * i + 1] = loc[2 * (n - 1 - i) + 1];+ loc[2 * (n - 1 - i)] = tx, loc[2 * (n - 1 - i) + 1] = ty;+ }+ poly_props(s);+}++/* Body.align: the origin moves to the centre of mass */+static void align(Body *b) {+ np_body_mass(b);+ V2 c = b->lcom;+ for (int i = 0; i < b->nshapes; i++) {+ Shape *s = &b->shapes[i];+ if (s->type == SH_POLY) {+ float *l = (float *)(uintptr_t)s->loc;+ for (int k = 0; k < s->n; k++) l[2 * k] -= c.x, l[2 * k + 1] -= c.y;+ poly_props(s);+ } else s->lcom = v2(s->lcom.x - c.x, s->lcom.y - c.y);+ }+ b->pos = np_local_to_world(b, c);+ np_body_mass(b);+}++static Con *con(Con *c, int type, Body *b1, Body *b2) {+ memset(c, 0, sizeof *c);+ c->type = (uint8_t)type, c->b1 = b1, c->b2 = b2;+ c->flags = CF_ACTIVE | CF_STIFF;+ c->frequency = 10, c->damping = 1, c->ratio = 1;+ c->sb = -1;+ np_register_con(c);+ return c;+}++static void con_on(Con *c, bool on) {+ if (on) c->flags |= CF_ACTIVE;+ else c->flags &= (uint8_t)~CF_ACTIVE;+}++/* DriverPartObject.createJoints / DriverObject.connectArm, connectLeg */+static void joints(PartJoint *j, Body *b, Body *parent, V2 at, float r, float freq, float damp, bool to_frame) {+ j->has = true;+ /* pivot(body, parent) for parts; pivot(frame, part) for the arm and leg */+ Body *b1 = to_frame ? parent : b, *b2 = to_frame ? b : parent;+ Con *p = con(&j->pivot, C_PIVOT, b1, b2);+ p->a1 = np_world_to_local(b1, at), p->a2 = np_world_to_local(b2, at);+ float u = b2->rot - b1->rot;+ j->base = u, j->delta = r;+ if (r > 0) {+ Con *s = con(&j->soft, C_ANGLE, b1, b2);+ s->jmin = s->jmax = u;+ s->flags &= (uint8_t)~CF_STIFF;+ s->frequency = freq, s->damping = damp;+ Con *t = con(&j->stiff, C_ANGLE, b1, b2);+ t->jmin = u - r, t->jmax = u + r;+ }+}++static void joint_connect(PartJoint *j, bool on) {+ if (!j->has) return;+ con_on(&j->pivot, on);+ con_on(&j->soft, on);+ if (on) j->stiff.jmin = j->base - j->delta, j->stiff.jmax = j->base + j->delta;+ con_on(&j->stiff, on);+ np_con_clear(&j->pivot), np_con_clear(&j->soft), np_con_clear(&j->stiff);+}++static void joint_move(PartJoint *j, float t, float e) {+ j->stiff.jmin = j->base - j->delta + t * e, j->stiff.jmax = j->base + j->delta + t * e;+ j->soft.jmin = j->soft.jmax = j->base + t * e;+}++static void joint_relax(PartJoint *j) {+ if (!j->has) return;+ con_on(&j->soft, false);+ j->stiff.jmin = j->base - 5 * j->delta, j->stiff.jmax = j->base + 5 * j->delta;+}++static const PartGeo *part_geo(int p) {+ switch (p >= P_HIP2 ? p - 4 : p) {+ case P_HEAD: return &GEO_DRIVER_HEAD;+ case P_CORPSE: return &GEO_DRIVER_CORPSE;+ case P_HIP: return &GEO_DRIVER_HIP;+ case P_SHIN: return &GEO_DRIVER_SHIN;+ case P_ARM: return &GEO_DRIVER_ARM;+ default: return &GEO_DRIVER_FOREARM;+ }+}++static float start_x, start_y;++static Body *all_bodies[4 + NPARTS];++void bike_build(float x, float y, int skin) {+ Bike *k = &bike;+ memset(k, 0, sizeof *k);+ k->skin = skin;+ nmats_base = lv.h->nmats;+ Body *world = np_world();+ (void)world;+ /* the frame: a box (mass) and the bike's outline (what touches things) */+ Body *f = &k->frame;+ f->type = B_DYNAMIC, f->pos = v2(x, y), f->cb = CB_BODY;+ np_body_set_rot(f, 0);+ f->shapes = k->frame_shapes, f->nshapes = 2;+ box(k->frame_loc[0], CAR_bodyW, CAR_bodyH, 0, 0);+ poly_shape(&k->frame_shapes[0], k->frame_loc[0], k->frame_glob[0], 4, add_mat(0, 0, 0, CAR_bodyDensity, 0.001f),+ FL_NOTHING);+ for (int i = 0; i < 4; i++) k->frame_loc[1][2 * i] = GEO_POINTS[i].x, k->frame_loc[1][2 * i + 1] = GEO_POINTS[i].y;+ poly_shape(&k->frame_shapes[1], k->frame_loc[1], k->frame_glob[1], 4, add_mat(0, 1, 2, 0.001f, 0.001f), FL_WHEEL);+ align(f);+ np_register(f);+ /* the wheels: on a line joint (the fork) and a spring */+ for (int w = 0; w < 2; w++) {+ bool back = w == 0;+ float fr = back ? CAR_wheelBackFriction : CAR_wheelFrontFriction, de = back ? CAR_wheelBackDensity : CAR_wheelFrontDensity;+ float r = back ? CAR_wheelBackR : CAR_wheelFrontR;+ float dx = back ? -CAR_wheelBackDx : CAR_wheelFrontDx;+ float ay = back ? CAR_axisBackY : CAR_axisFrontY, alen = back ? CAR_axisBackLen : CAR_axisFrontLen;+ float dy = back ? CAR_damperBackY : CAR_damperFrontY, dlen = back ? CAR_damperBackLen : CAR_damperFrontLen;+ float freq = back ? CAR_damperBackFreq : CAR_damperFrontFreq, damp = back ? CAR_damperBackDamp : CAR_damperFrontDamp;+ float ang = back ? CAR_axisBackAngle : CAR_axisFrontAngle;+ Body *b = &k->wheel[w];+ b->type = B_DYNAMIC, b->cb = CB_WHEEL;+ b->pos = v2(f->pos.x + dx, f->pos.y + dlen);+ np_body_set_rot(b, 0);+ b->shapes = &k->wheel_shape[w], b->nshapes = 1;+ Shape *s = &k->wheel_shape[w];+ s->type = SH_CIRCLE, s->radius = r, s->area = PI * r * r, s->inertia = r * r * 0.5f, s->filter = FL_WHEEL;+ k->mat_wheel[w] = add_mat(0, fr, fr, de, 0.001f);+ s->mat = k->mat_wheel[w];+ np_register(b);+ Con *l = con(&k->line[w], C_LINE, f, b);+ l->a1 = v2(dx, ay), l->a2 = v2(0, 0), l->nlocal = v2(cosf(ang), sinf(ang)), l->jmin = 0, l->jmax = alen;+ Con *d = con(&k->dist[w], C_DIST, f, b);+ d->a1 = v2(dx, dy), d->a2 = v2(0, 0), d->jmin = dlen, d->jmax = 2 * dlen;+ d->frequency = freq, d->damping = damp;+ d->flags = CF_ACTIVE | CF_IGNORE;+ if (!back) {+ Con *bj = con(&k->brake_joint, C_ANGLE, f, b);+ bj->jmin = bj->jmax = 0;+ bj->flags = 0; /* inactive, soft */+ bj->damping = 100;+ }+ }+ /* back wheel's braking material: a tenth of its friction */+ {+ Material *m = &sp.mats[k->mat_wheel[0]];+ k->mat_brake = add_mat(m->elasticity, 0.1f * m->stat, 0.1f * m->stat, m->density, m->rolling);+ }+ /* the rider's body: a box welded to the frame, its weight shifting as he leans */+ Body *dv = &k->driver;+ dv->type = B_DYNAMIC;+ np_body_set_rot(dv, 0);+ dv->shapes = &k->driver_shape, dv->nshapes = 1;+ box(k->driver_loc, CAR_driverW, CAR_driverH, 0, 0);+ poly_shape(&k->driver_shape, k->driver_loc, k->driver_glob, 4, add_mat(0, 0, 0, CAR_driverDensity, 0.001f),+ FL_NOTHING);+ np_register(dv);+ Con *wd = con(&k->weld, C_WELD, f, dv);+ wd->a1 = v2(0, CAR_driverDy), wd->a2 = v2(0, 0);+ wd->flags |= CF_IGNORE;+ /* the rider's parts, at the frame's start position */+ uint8_t pmat = add_mat(0, 1, 2, 1, 0.001f);+ float fx = f->pos.x, fy = f->pos.y;+ for (int p = 0; p < NPARTS; p++) {+ const PartGeo *g = part_geo(p);+ Body *b = &k->part[p];+ b->type = B_DYNAMIC, b->cb = p == P_HEAD ? CB_DRIVER : CB_PART;+ b->pos = v2(g->x + fx, g->y + fy);+ np_body_set_rot(b, g->r);+ b->shapes = &k->part_shape[p], b->nshapes = 1;+ box(k->part_loc[p], g->w, g->h, 0, 0);+ poly_shape(&k->part_shape[p], k->part_loc[p], k->part_glob[p], 4, pmat, FL_PART);+ np_register(b);+ }+ float r10 = 10 * TO_RAD;+ V2 o = v2(fx, fy);+#define AT(J) v2(o.x + (J).x, o.y + (J).y)+ joints(&k->pj[P_SHIN], &k->part[P_SHIN], &k->part[P_HIP], AT(GEO_HIP_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_SHIN2], &k->part[P_SHIN2], &k->part[P_HIP2], AT(GEO_HIP_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_HIP], &k->part[P_HIP], &k->part[P_CORPSE], AT(GEO_CORPSE_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_HIP2], &k->part[P_HIP2], &k->part[P_CORPSE], AT(GEO_CORPSE_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_FOREARM], &k->part[P_FOREARM], &k->part[P_ARM], AT(GEO_FOREARM_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_FOREARM2], &k->part[P_FOREARM2], &k->part[P_ARM2], AT(GEO_FOREARM_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_ARM], &k->part[P_ARM], &k->part[P_CORPSE], AT(GEO_ARM_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_ARM2], &k->part[P_ARM2], &k->part[P_CORPSE], AT(GEO_ARM_JOINT), r10, 10, 1, false);+ joints(&k->pj[P_HEAD], &k->part[P_HEAD], &k->part[P_CORPSE], AT(GEO_HEAD_JOINT), r10, 10, 1, false);+ joints(&k->arm, &k->part[P_FOREARM], f, AT(GEO_STEER_JOINT), r10, 50, 50, true);+ joints(&k->leg, &k->part[P_SHIN], f, AT(GEO_SHIN_JOINT), r10, 50, 100, true);+#undef AT+ /* CarObject.setParams */+ wheel_radius = CAR_wheelBackR;+ max_ang_vel = 2 * (CAR_maxSpeed / (2 * PI * wheel_radius)) * PI;+ accel_torque = CAR_torque;+ delta_torque = CAR_maxTorque > CAR_torque ? CAR_maxTorque - CAR_torque : 0;+ tilt_torque = CAR_flipTorque;+ max_tilt_speed = CAR_maxFlipSpeed;+ k->review_x = start_x = f->pos.x, k->review_y = start_y = f->pos.y;+ all_bodies[0] = f, all_bodies[1] = &k->wheel[0], all_bodies[2] = &k->wheel[1], all_bodies[3] = dv;+ for (int p = 0; p < NPARTS; p++) all_bodies[4 + p] = &k->part[p];+ for (int i = 0; i < 4 + NPARTS; i++) all_bodies[i]->user = 0, all_bodies[i]->flags |= BF_KEEP;+ k->safe_id = -1;+}++bool bike_owns(const Body *b) {+ for (int i = 0; i < 4 + NPARTS; i++)+ if (all_bodies[i] == b) return true;+ return false;+}++int bike_body_slot(const Body *b) {+ for (int i = 0; i < 4 + NPARTS; i++)+ if (all_bodies[i] == b) return i == 3 ? -1 : i; /* (the welded body has no effector) */+ return -1;+}++static void stop(Body *b) {+ b->torque = 0, b->vel = v2(0, 0), b->angvel = 0;+ b->flags &= (uint8_t)~(BF_NOMOVE | BF_NOROT);+ np_body_mass(b);+}++static void mirror_parts(bool on) {+ for (int p = P_HIP2; p < NPARTS; p++) {+ Body *m = &bike.part[p], *s = &bike.part[p - 4];+ if (on) {+ stop(m);+ m->pos = s->pos;+ np_body_set_rot(m, s->rot);+ np_body_add(m);+ np_body_moved(m);+ } else np_body_remove(m);+ joint_connect(&bike.pj[p], on);+ }+}++static void connect_driver(bool on) {+ joint_connect(&bike.arm, on);+ joint_connect(&bike.leg, on);+}++static void driver_move(float t, float e) {+ /* the rider's weight: his box's centre goes driverDx forwards or back */+ float *l = bike.driver_loc;+ box(l, CAR_driverW, CAR_driverH, CAR_driverDx * t, 0);+ poly_props(&bike.driver_shape);+ np_body_mass(&bike.driver);+ joint_move(&bike.pj[P_SHIN], e, 30 * TO_RAD);+ joint_move(&bike.pj[P_HIP], e, -45 * TO_RAD);+ joint_move(&bike.pj[P_ARM], e, -45 * TO_RAD);+ float s = 15 * e * TO_RAD;+ joint_move(&bike.leg, 1, s);+}++static void wheel_brake(int w, bool on) {+ Shape *s = &bike.wheel_shape[w];+ if (w != 0) return;+ if (on && !bike.braked) {+ s->mat = bike.mat_brake;+ np_drop_shape(s);+ } else if (!on && bike.braked) {+ s->mat = bike.mat_wheel[0];+ np_drop_shape(s);+ }+ bike.braked = on;+}++/* CarObject.review: back to the review point, standing */+void bike_review(void) {+ Bike *k = &bike;+ Body *f = &k->frame;+ for (int w = 0; w < 2; w++) {+ con_on(&k->line[w], false), con_on(&k->dist[w], false);+ }+ connect_driver(false);+ /* driver.connect(false): the weld and every part's joints */+ con_on(&k->weld, false);+ for (int p = 0; p < NPARTS; p++) joint_connect(&k->pj[p], false);+ stop(f), stop(&k->wheel[0]), stop(&k->wheel[1]);+ stop(&k->driver);+ for (int p = 0; p < NPARTS; p++) stop(&k->part[p]);+ /* frame.review */+ f->pos = v2(k->review_x, k->review_y);+ np_body_set_rot(f, 0);+ k->start_fly = k->max_fly = k->min_fly = k->rotation = 0;+ float wdy = fmaxf(CAR_axisBackY + CAR_axisBackLen + CAR_wheelBackR, CAR_axisFrontY + CAR_axisFrontLen + CAR_wheelFrontR);+ k->wheel[0].pos = np_local_to_world(f, v2(-CAR_wheelBackDx, wdy));+ k->wheel[1].pos = np_local_to_world(f, v2(CAR_wheelFrontDx, wdy));+ /* driver.review: lean 0, his parts at their places around the frame */+ driver_move(0, 0);+ k->driver.pos = v2(f->pos.x, f->pos.y + CAR_driverDy);+ np_body_set_rot(&k->driver, 0);+ for (int p = 0; p < NPARTS; p++) {+ const PartGeo *g = part_geo(p);+ k->part[p].pos = v2(f->pos.x + g->x, f->pos.y + g->y);+ np_body_set_rot(&k->part[p], g->r);+ }+ k->spiked = false;+ for (int w = 0; w < 2; w++) {+ con_on(&k->line[w], true), con_on(&k->dist[w], true);+ np_con_clear(&k->line[w]), np_con_clear(&k->dist[w]);+ }+ connect_driver(true);+ con_on(&k->weld, true);+ np_con_clear(&k->weld);+ for (int p = 0; p < P_HIP2; p++) joint_connect(&k->pj[p], true);+ mirror_parts(false);+ for (int i = 0; i < 4 + NPARTS; i++) {+ if (i >= 4 + P_HIP2) continue;+ np_body_add(all_bodies[i]);+ np_body_moved(all_bodies[i]);+ }+ k->dead = false, k->drive = true, k->exploded = false;+ con_on(&k->brake_joint, false);+ k->boost_left = 0, k->boosting = false;+ k->accel_brake_timer = k->max_vel_timer = 0;+}++/* CarObject.restart + frame and wheels back at the start (hard restart) */+void bike_restart(void) {+ Bike *k = &bike;+ k->safe_id = -1;+ k->finished = false;+ /* the frame's start: the level's start plus its centre of mass (it was aligned) */+ k->review_x = start_x, k->review_y = start_y;+ bike_review();+ for (int w = 0; w < 2; w++) {+ sp.mats[k->mat_wheel[w]].dyn = sp.mats[k->mat_wheel[w]].stat = w ? CAR_wheelFrontFriction : CAR_wheelBackFriction;+ k->spin_delay[w] = 0;+ k->wheel_ground[w] = false, k->wheel_end_delay[w] = 0, k->wheel_fly[w] = 0;+ }+ k->frame_ground = false, k->frame_end_delay = 0;+ k->fly_time = k->fall_time = 0;+ k->braked = false;+ k->wheel_shape[0].mat = k->mat_wheel[0];+ for (int i = 0; i < NPARTS + 4; i++) k->eff_vx[i] = k->eff_vy[i] = 0;+}++/* ---- each tick ---- */++/* userData.isGround: shapers, pathers, the ground and planks (the packer flags them) */+static bool ground_body(const Arb *a, const Body *me, V2 *p, float *nang) {+ const Body *o = a->b1 == me ? a->b2 : a->b1;+ uint16_t s = a->b1 == me ? a->s2 : a->s1;+ bool g = s & 0x8000 ? o->pad != 0 : sp.sbodies[sp.sshapes[s].body].pad != 0;+ if (!g) return false;+ if (p) {+ const Contact *c = &a->c[a->c1 >= 0 ? a->c1 : 0];+ *p = v2(c->r1x + a->b1->pos.x, c->r1y + a->b1->pos.y);+ float ang = atan2f(a->n.y, a->n.x);+ if (a->b1 == me) ang += PI;+ *nang = ang;+ }+ return true;+}++static bool touching_ground(const Body *b, V2 *p, float *nang) {+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ const Arb *a = &sp.arbs[i];+ if (!a->used || a->type != A_COL || !a->active || a->up_stamp != sp.stamp) continue;+ if (a->b1 != b && a->b2 != b) continue;+ if (ground_body(a, b, p, nang)) return true;+ }+ return false;+}++static void effector(Body *b, int slot, float dt) {+ float ex = bike.eff_vx[slot], ey = bike.eff_vy[slot];+ if (ex != 0 || ey != 0) {+ b->vel.x += 2 * dt * (ex - b->vel.x);+ b->vel.y += 2 * dt * (ey - b->vel.y);+ bike.eff_vx[slot] = bike.eff_vy[slot] = 0;+ np_wake(b);+ }+}++static void wheels_update(float dt) {+ Bike *k = &bike;+ for (int w = 0; w < 2; w++) {+ Body *b = &k->wheel[w];+ if (k->spin_delay[w] > 0) {+ k->spin_delay[w] -= dt;+ float fr = w ? CAR_wheelFrontFriction : CAR_wheelBackFriction;+ Material *m = &sp.mats[k->mat_wheel[w]];+ if (k->spin_delay[w] <= 0) m->stat = m->dyn = fr;+ else if (k->spin_delay[w] < 0.5f * START_SPIN_DELAY)+ m->stat = m->dyn = START_SPIN_FRICTION + (fr - START_SPIN_FRICTION) *+ (0.5f * START_SPIN_DELAY - k->spin_delay[w]) / (0.5f * START_SPIN_DELAY);+ }+ V2 p;+ float ang;+ bool e = touching_ground(b, &p, &ang);+ if (e && k->skin != 4) {+ float h = hypotf(b->vel.x, b->vel.y), l = b->angvel * k->wheel_shape[w].radius;+ if (fabsf(l) - fabsf(h) > 250) for (int q = 0; q < 3; q++) fx_ground(p.x, p.y, ang, l > 0);+ }+ if (e) k->wheel_end_delay[w] = 0, k->wheel_ground[w] = true, k->wheel_fly[w] = 0;+ else if (k->wheel_ground[w] && k->wheel_end_delay[w] == 0) k->wheel_end_delay[w] = WHEEL_END_DELAY;+ if (k->wheel_ground[w]) {+ if (k->wheel_end_delay[w] > 0) {+ k->wheel_end_delay[w] -= dt;+ if (k->wheel_end_delay[w] <= 0) k->wheel_ground[w] = false;+ }+ } else k->wheel_fly[w] += dt;+ effector(b, 1 + w, dt);+ }+}++static void frame_update(float dt) {+ Bike *k = &bike;+ bool e = touching_ground(&k->frame, 0, 0);+ if (e) k->frame_end_delay = 0, k->frame_ground = true;+ else if (k->frame_ground && k->frame_end_delay == 0) k->frame_end_delay = FRAME_END_DELAY;+ if (k->frame_ground && k->frame_end_delay > 0) {+ k->frame_end_delay -= dt;+ if (k->frame_end_delay <= 0) k->frame_ground = false;+ }+ effector(&k->frame, 0, dt);+}++static void process_land(void) {+ Bike *k = &bike;+ if (k->finished) return;+ if (!k->dead && (k->wheel_ground[0] || k->wheel_ground[1])) {+ float t = k->start_fly - k->min_fly;+ int i = (int)(t / (2 * PI));+ t -= 2 * i * PI;+ if (t >= PI) i++;+ int back = i;+ t = k->max_fly - k->start_fly;+ i = (int)(t / (2 * PI));+ t -= 2 * i * PI;+ if (t >= PI) i++;+ int front = i;+ if (back > 0) game_flip(back);+ if (front > 0) game_flip(front);+ }+ k->start_fly = k->max_fly = k->min_fly = k->rotation;+}++static void apply_drive(float t) {+ Bike *k = &bike;+ bool s = k->accell, n = k->brake;+ float o = accel_torque, a = max_ang_vel;+ if (delta_torque > 0 && s) {+ float r = k->speed / wheel_radius;+ if (r < a) {+ float p = 0.5f + 2.5f * r / a, h = (1 / (p * p) - 1.0f / 9) / (4 - 1.0f / 9);+ o = accel_torque + h * delta_torque;+ }+ }+ if (s && n) k->accel_brake_timer += t;+ else {+ if (k->accel_brake_timer > MIN_AC_BR_TIME) k->max_vel_timer = MAX_VEL_TIME;+ k->accel_brake_timer = 0;+ }+ Body *fw = &k->wheel[1], *bw = &k->wheel[0];+ if (n) {+ if (fabsf(fw->angvel) < 1) {+ k->brake_joint.jmin = k->brake_joint.jmax = fw->rot - k->frame.rot;+ if (!(k->brake_joint.flags & CF_ACTIVE)) np_con_clear(&k->brake_joint);+ k->brake_joint.flags |= CF_ACTIVE;+ }+ fw->angvel *= 0.25f;+ wheel_brake(0, true);+ if (!s) bw->angvel = 0;+ } else {+ k->brake_joint.flags &= (uint8_t)~CF_ACTIVE;+ wheel_brake(0, false);+ }+ if (s) {+ if (k->max_vel_timer > 0) {+ if (bw->angvel < 1.2f * a) bw->angvel += 1.5f * t * o * bw->iinertia;+ k->max_vel_timer -= t;+ } else {+ if (bw->angvel < 0) bw->angvel *= 0.5f;+ if (bw->angvel < a) bw->angvel += t * o * bw->iinertia;+ }+ np_wake(bw);+ } else k->max_vel_timer = 0;+}++static void apply_tilt(float e) {+ Bike *k = &bike;+ k->tilt = (int)e;+ Body *f = &k->frame;+ f->torque = e * tilt_torque;+ np_wake(f);+ float s = f->angvel;+ if (s < 0 && s < -max_tilt_speed) f->angvel = -max_tilt_speed;+ else if (s > 0 && s > max_tilt_speed) f->angvel = max_tilt_speed;+ float n = e;+ if (n == 0) {+ if (k->frame_ground || k->wheel_ground[0] || k->wheel_ground[1]) {+ if (k->accell) n = -1;+ } else {+ float vy = f->vel.y;+ if (vy < -20) n = 1;+ else if (vy > 20) n = -1;+ }+ }+ driver_move(e, n);+}++/* the bike's centre of mass (Compound.COM) */+static V2 bike_com(void) {+ float m = 0, x = 0, y = 0;+ for (int i = 0; i < 4 + NPARTS; i++) {+ Body *b = all_bodies[i];+ if (!(b->flags & BF_SPACE)) continue;+ V2 c = np_local_to_world(b, b->lcom);+ x += c.x * b->mass, y += c.y * b->mass, m += b->mass;+ }+ return m ? v2(x / m, y / m) : bike.frame.pos;+}++void bike_update(float dt, uint32_t keys) {+ Bike *k = &bike;+ Body *f = &k->frame;+ /* wheels, frame and parts update before the car (their order in MaxGameCore) */+ wheels_update(dt);+ frame_update(dt);+ for (int p = 0; p < NPARTS; p++) effector(&k->part[p], 4 + p, dt);+ if (k->dead) k->x = k->part[P_HEAD].pos.x, k->y = k->part[P_HEAD].pos.y;+ else k->x = f->pos.x, k->y = f->pos.y;+ k->rotation = f->rot;+ float prev = k->speed;+ k->speed = hypotf(f->vel.x, f->vel.y);+ bool ground = k->frame_ground || k->wheel_ground[0] || k->wheel_ground[1];+ if (ground) {+ if (k->fly_time > LONG_FLY_TIME) {+ process_land();+ if (prev > 500) fx_landing();+ }+ k->fly_time = 0, k->fall_time = 0;+ } else {+ if (k->fly_time == 0) k->max_fly = k->min_fly = k->start_fly = k->rotation;+ if (k->rotation > k->max_fly) k->max_fly = k->rotation;+ else if (k->rotation < k->min_fly) k->min_fly = k->rotation;+ k->fly_time += dt;+ if (f->vel.y > 0) k->fall_time += dt;+ else k->fall_time = 0;+ }+ if (k->drive) {+ k->accell = !k->finished && (keys & K_UP);+ k->brake = !k->finished && (keys & K_DOWN);+ apply_drive(dt);+ if (k->finished) apply_tilt(0);+ else apply_tilt((keys & K_RIGHT ? 1 : 0) - (keys & K_LEFT ? 1 : 0));+ if (k->skin != 4) {+ k->smoke_timer -= k->accell ? 2 * dt : dt;+ if (k->smoke_timer <= 0) {+ k->smoke_timer += SMOKE_TIME;+ V2 a = np_local_to_world(f, v2(-43, -16));+ float h = 0.1f * PI;+ if (k->accell) {+ fx_smoke(a.x, a.y, k->rotation - 0.5f * h + fx_rand() * h);+ fx_smoke(a.x, a.y, k->rotation - 0.1f * PI + 0.5f * h + fx_rand() * h);+ fx_smoke(a.x, a.y, k->rotation + 0.1f * PI + 0.5f * h + fx_rand() * h);+ } else fx_smoke(a.x, a.y, k->rotation - 0.5f * h + fx_rand() * h);+ }+ }+ if (k->skin == 5) fx_fire(k->part[P_HEAD].pos.x, k->part[P_HEAD].pos.y);+ } else if (k->finished) {+ k->wheel[0].angvel *= 0.8f, k->wheel[1].angvel *= 0.8f;+ }+ /* the boost */+ if (k->boost_left > 0) {+ V2 c = bike_com();+ float r = f->rot;+ np_apply_impulse(f, v2(dt * k->boost_force * cosf(r), dt * k->boost_force * sinf(r)), c);+ if (!ground) f->angvel *= 0.8f;+ k->boost_left -= dt;+ k->boosting = k->boost_left > 0;+ }+}++/* BikeObject.processDriverGround */+void bike_driver_ground(void) {+ Bike *k = &bike;+ if (k->dead) return;+ k->drive = false, k->dead = true;+ connect_driver(false);+ for (int p = 0; p < NPARTS; p++) joint_relax(&k->pj[p]);+ mirror_parts(true);+ apply_tilt(0);+ game_died();+}++void bike_explode(void) {+ Bike *k = &bike;+ if (k->exploded) return;+ k->exploded = true;+ Body *f = &k->frame;+ for (int w = 0; w < 2; w++) {+ Body *b = &k->wheel[w];+ float dx = b->pos.x - f->pos.x, dy = b->pos.y - f->pos.y, l = hypotf(dx, dy);+ if (l > 0) dx /= l, dy /= l;+ con_on(&k->line[w], false), con_on(&k->dist[w], false);+ b->vel.x += 500 * dx, b->vel.y += 500 * dy;+ np_wake(b);+ }+ f->vel.y -= 100;+ np_wake(f);+ fx_explosion(f->pos.x, f->pos.y, 0);+ fx_shake();+}++void bike_spikes(Body *part) {+ bike.spiked = true;+ if (part) {+ stop(part);+ part->flags |= BF_NOMOVE | BF_NOROT;+ np_body_mass(part);+ }+}++void bike_finish(void) {+ Bike *k = &bike;+ if (k->finished) return;+ k->drive = false, k->finished = true;+ apply_tilt(0);+ game_finished();+}++void bike_add_boost(float time, float force) {+ Bike *k = &bike;+ if (k->dead) return;+ if (k->boost_left <= 0) k->boost_force = force, k->boost_left = time;+ else {+ if (force > k->boost_force) k->boost_force = force;+ k->boost_left += time;+ }+ k->boosting = true;+}diff --git a/games/motox3m/src/bike.h b/games/motox3m/src/bike.hnew file mode 100644index 00000000..40e2be63--- /dev/null+++ b/games/motox3m/src/bike.h@@ -0,0 +1,63 @@+/* Moto X3M: the bike and its rider (motox3m4.js: CarBuilder, CarObject, BikeObject, FrameObject, WheelObject,+ * DriverObject, DriverPartObject, BoostEffector, BodyEffector). */+#ifndef MX_BIKE_H+#define MX_BIKE_H+#include <stdbool.h>+#include "nape.h"++/* the rider's parts: head, corpse, hip, shin, arm, forearm, then the other hip, shin, arm and forearm */+enum { P_HEAD, P_CORPSE, P_HIP, P_SHIN, P_ARM, P_FOREARM, P_HIP2, P_SHIN2, P_ARM2, P_FOREARM2, NPARTS };++typedef struct {+ Con pivot, soft, stiff; /* to its parent part (or the frame) */+ float base, delta;+ bool has;+} PartJoint;++typedef struct {+ Body frame, wheel[2], driver, part[NPARTS];+ Shape frame_shapes[2], wheel_shape[2], driver_shape, part_shape[NPARTS];+ float frame_loc[2][8], driver_loc[8], part_loc[NPARTS][8];+ float frame_glob[2][20], driver_glob[20], part_glob[NPARTS][20];+ Con line[2], dist[2], brake_joint, weld;+ PartJoint pj[NPARTS]; /* each part to its parent */+ PartJoint arm, leg; /* forearm and shin to the frame */+ uint8_t mat_wheel[2], mat_brake; /* material slots */+ int skin;+ /* state */+ bool dead, finished, drive, accell, brake, exploded, braked, spiked, boosting;+ int tilt;+ float speed, x, y, rotation;+ float fly_time, fall_time, start_fly, min_fly, max_fly;+ float accel_brake_timer, max_vel_timer;+ bool frame_ground, wheel_ground[2];+ float frame_end_delay, wheel_end_delay[2], wheel_fly[2], spin_delay[2];+ float review_x, review_y;+ int safe_id;+ float smoke_timer;+ float boost_left, boost_force;+ float eff_vx[NPARTS + 4], eff_vy[NPARTS + 4]; /* geysers: frame, wheels, driver body, parts */+ V2 wheel_contact[2];+ float wheel_normal[2];+ bool wheel_contacted[2];+} Bike;++extern Bike bike;++void bike_build(float x, float y, int skin);+void bike_review(void); /* to the last safe point (or the start) */+void bike_restart(void); /* to the start */+/* a game tick: keys K_UP gas, K_DOWN brake, K_LEFT / K_RIGHT lean */+void bike_update(float dt, uint32_t keys);+void bike_driver_ground(void); /* processDriverGround */+void bike_explode(void);+void bike_spikes(Body *part);+void bike_finish(void);+void bike_add_boost(float time, float force);+bool bike_owns(const Body *b);+int bike_body_slot(const Body *b); /* geyser effect slot, or -1 */+/* flips landed: the game takes 0.5 s off the time for each */+extern void game_flip(int n);+extern void game_died(void);+extern void game_finished(void);+#endifdiff --git a/games/motox3m/src/bike_data.h b/games/motox3m/src/bike_data.hnew file mode 100644index 00000000..3e2e9e6c--- /dev/null+++ b/games/motox3m/src/bike_data.h@@ -0,0 +1,76 @@+/* Moto X3M: the bike, from the game's levels/1.json and levels/bike.json (made by tools/pack.py) */+#ifndef MX_BIKE_DATA_H+#define MX_BIKE_DATA_H+#define CAR_axisBackAngle 1.57079633f+#define CAR_axisBackLen 14.0f+#define CAR_axisBackY 13.0f+#define CAR_axisFrontAngle 1.09955743f+#define CAR_axisFrontLen 14.0f+#define CAR_axisFrontY 13.0f+#define CAR_baseHealth 2700.0f+#define CAR_bodyDensity 1.0f+#define CAR_bodyH 24.0f+#define CAR_bodyMassType 1.0f+#define CAR_bodyW 96.0f+#define CAR_boostCount 3.0f+#define CAR_boostForce 0.0f+#define CAR_boostValue 0.0f+#define CAR_damperBackDamp 0.0f+#define CAR_damperBackFreq 5.0f+#define CAR_damperBackLen 12.0f+#define CAR_damperBackY 12.0f+#define CAR_damperFrontDamp 0.0f+#define CAR_damperFrontFreq 5.0f+#define CAR_damperFrontLen 12.0f+#define CAR_damperFrontY 12.0f+#define CAR_driverDensity 1.0f+#define CAR_driverDx 45.0f+#define CAR_driverDy -16.0f+#define CAR_driverH 32.0f+#define CAR_driverW 32.0f+#define CAR_engineCount 3.0f+#define CAR_flipTorque 200000.0f+#define CAR_handlingCount 3.0f+#define CAR_handlingPct 0.0f+#define CAR_health 0.0f+#define CAR_healthCount 3.0f+#define CAR_healthValue 900.0f+#define CAR_maxFlipSpeed 0.2f+#define CAR_maxSpeed 700.0f+#define CAR_maxSpeedPct 2.0f+#define CAR_maxTorque 600000.0f+#define CAR_skinId 1.0f+#define CAR_torque 400000.0f+#define CAR_torquePct 5.0f+#define CAR_wd 0.0f+#define CAR_weapon 0.0f+#define CAR_wheelBackDensity 1.0f+#define CAR_wheelBackDx 34.0f+#define CAR_wheelBackFriction 6.0f+#define CAR_wheelBackR 19.0f+#define CAR_wheelFrictionPct 0.0f+#define CAR_wheelFrontDensity 3.0f+#define CAR_wheelFrontDx 45.0f+#define CAR_wheelFrontFriction 5.0f+#define CAR_wheelFrontR 19.0f+#define CAR_wheelRadiusValue 0.0f+#define CAR_wheels 0.0f+#define CAR_wheelsCount 3.0f+typedef struct { float x, y, w, h, r; } PartGeo;+static const PartGeo GEO_DRIVER_HEAD = {-1.8f, -59.5f, 25.2f, 23.1f, 0.26179486f};+static const PartGeo GEO_DRIVER_CORPSE = {-8.35f, -33.75f, 14.1f, 30.2f, 0.274591616f};+static const PartGeo GEO_DRIVER_ARM = {-4.25f, -39.4f, 16.1f, 10.1f, 0.78539044f};+static const PartGeo GEO_DRIVER_FOREARM = {8.8f, -33.35f, 19.1f, 6.0f, 0.192002197f};+static const PartGeo GEO_DRIVER_HIP = {-7.4f, -18.5f, 13.1f, 9.1f, 0.523596645f};+static const PartGeo GEO_DRIVER_SHIN = {-1.8f, -2.7f, 9.1f, 31.2f, 0.0523811828f};+static const V2 GEO_HIP_JOINT = {-3.0f, -15.0f};+static const V2 GEO_CORPSE_JOINT = {-11.0f, -23.2f};+static const V2 GEO_FOREARM_JOINT = {0.85f, -35.15f};+static const V2 GEO_ARM_JOINT = {-7.75f, -43.65f};+static const V2 GEO_HEAD_JOINT = {-5.6f, -48.5f};+static const V2 GEO_STEER_JOINT = {16.05f, -30.5f};+static const V2 GEO_SHIN_JOINT = {-1.0f, 10.0f};+static const V2 GEO_SUSPEND_BACK = {-6.0f, 12.0f};+#define GEO_SUSPEND_BACK_W 28.1f+static const V2 GEO_POINTS[4] = {{-12, 6}, {-40, -17}, {23, -28}, {15, 8}};+#endifdiff --git a/games/motox3m/src/data.S b/games/motox3m/src/data.Snew file mode 100644index 00000000..0ebb90dc--- /dev/null+++ b/games/motox3m/src/data.S@@ -0,0 +1,19 @@+/* data.bin (tools/pack.py) in the app's read-only data */+#ifdef __APPLE__+ .const_data+ .p2align 2+ .globl _mx_data+_mx_data:+ .incbin DATA_BIN+ .p2align 2+#else+ .section .rodata.mx_data,"a"+ .balign 4+ .global mx_data+mx_data:+ .incbin DATA_BIN+ .balign 4+#endif+#ifdef __ELF__+ .section .note.GNU-stack,"",%progbits+#endifdiff --git a/games/motox3m/src/data.bin b/games/motox3m/src/data.binnew file mode 100644index 00000000..16fed76dBinary files /dev/null and b/games/motox3m/src/data.bin differdiff --git a/games/motox3m/src/data.h b/games/motox3m/src/data.hnew file mode 100644index 00000000..d493cc81--- /dev/null+++ b/games/motox3m/src/data.h@@ -0,0 +1,47 @@+/* Moto X3M: what's in data.bin (made by tools/pack.py) */+#ifndef MX_DATA_H+#define MX_DATA_H+#define N_PICS 283+#define N_FONTS 4+#define N_LEVELS 50+#define PIC_UI_0LOGO 265+#define PIC_UI_0POPUP_BG 268+#define PIC_UI_ARROW_BTN 270+#define PIC_UI_ARROWS 279+#define PIC_UI_EXIT_BTN 262+#define PIC_UI_IMPROVED_BG 264+#define PIC_UI_LOGO 281+#define PIC_UI_MAP 273+#define PIC_UI_MAPBG 282+#define PIC_UI_NEXT_BTN 261+#define PIC_UI_ORANGE_BTN 258+#define PIC_UI_ORANGE_BTN_BIG 259+#define PIC_UI_ORANGE_BTN_BIG_GREEN 260+#define PIC_UI_PAUSE_BG 267+#define PIC_UI_PLAY_BTN 271+#define PIC_UI_RESTART_BTN 263+#define PIC_UI_SELECT_LEVEL 269+#define PIC_UI_SHOP_BTN 272+#define PIC_UI_STAR0 255+#define PIC_UI_STAR1 256+#define PIC_UI_TIMER_BG 254+#define PIC_UI_TOP_BG 266+#define PIC_UI_W_STAR 257+#define PIC_ROCKET 237+#define PIC_CAREXPLODE 0+#define PIC_SMOKE_PART_ANIM 27+#define PIC_GROUND_PART_ANIM 42+#define PIC_GLASSCRASHED0_0 68+#define PIC_GEYSERBASE 102+#define PIC_GEYSER_ANIM 131+#define PIC_PARTICLE_BOOST 137+static const uint16_t PIC_BG[3][3] = {{167, 168, 169}, {170, 65535, 65535}, {171, 65535, 172}};+/* per bike: frame, frame exploded, wheel, head, corpse, arm, forearm, hip, shin, suspend back, front */+static const uint16_t PIC_BIKE[6][11] = {{173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183}, {184, 185, 175, 186, 187, 188, 189, 190, 191, 192, 193}, {194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204}, {205, 206, 196, 207, 208, 209, 210, 211, 212, 213, 214}, {215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225}, {226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236}};+enum { FONT_SMALL, FONT_MID, FONT_BIG, FONT_HUGE };+static const int16_t MAP_PTS[50][2] = {{71, 378}, {162, 339}, {82, 266}, {162, 206}, {115, 94}, {200, 77}, {246, 206}, {263, 370}, {359, 378}, {350, 270}, {413, 198}, {332, 97}, {410, 65}, {480, 260}, {432, 380}, {516, 371}, {554, 191}, {488, 97}, {562, 88}, {613, 266}, {589, 357}, {677, 377}, {675, 197}, {647, 111}, {706, 76}, {744, 206}, {744, 356}, {831, 249}, {797, 111}, {862, 76}, {877, 186}, {895, 266}, {840, 370}, {939, 370}, {978, 213}, {953, 94}, {1053, 88}, {1033, 276}, {1033, 377}, {1117, 257}, {1130, 121}, {1199, 77}, {1189, 213}, {1153, 377}, {1252, 371}, {1283, 265}, {1283, 65}, {1351, 107}, {1368, 260}, {1334, 359}};+/* bikes as the menus show them (bike11: the pause screen's, then bike1-6): picture, x, y, angle */+typedef struct { uint16_t pic; int16_t x, y, deg; } BikePart;+static const BikePart BIKE_LAYOUT[7][11] = {{{175, -76, 11, 16}, {175, 76, 54, 16}, {182, -17, 17, -174}, {173, 1, -2, 16}, {177, -2, -94, 101}, {180, -36, -96, 145}, {181, -69, -97, 118}, {178, 16, -81, 60}, {179, 38, -63, 26}, {176, 40, -113, 47}, {183, 81, 54, 79}}, {{175, -70, 34, 0}, {175, 88, 34, 0}, {182, -12, 24, 170}, {173, 0, 0, 0}, {183, 92, 32, 63}, {177, -17, -68, 16}, {176, -4, -119, 15}, {179, 18, -67, 11}, {178, -8, -79, 45}, {181, -4, -5, 3}, {180, -15, -37, 30}}, {{175, -62, 40, 0}, {175, 100, 40, 0}, {192, -12, 24, 170}, {193, 92, 32, 63}, {184, 0, 0, 0}, {187, -17, -68, 16}, {186, -4, -119, 15}, {189, 18, -67, 11}, {188, -8, -79, 45}, {191, -4, -5, 3}, {190, -15, -37, 30}}, {{196, -68, 34, 0}, {196, 92, 32, 0}, {194, 0, 0, 0}, {204, 92, 32, 63}, {203, -12, 24, 170}, {198, -17, -68, 16}, {197, -4, -119, 15}, {200, 18, -67, 11}, {199, -8, -79, 45}, {202, -4, -5, 3}, {201, -15, -37, 30}}, {{175, -68, 34, 0}, {175, 94, 34, 0}, {205, 0, 0, 0}, {214, 92, 32, 63}, {213, -12, 24, 170}, {208, -17, -68, 16}, {207, -4, -119, 15}, {210, 18, -67, 11}, {209, -8, -79, 45}, {212, -4, -5, 3}, {211, -15, -37, 30}}, {{217, -68, 34, 0}, {217, 94, 34, 0}, {215, 0, 0, 0}, {225, 92, 32, 63}, {224, -12, 24, 170}, {219, -17, -68, 16}, {218, -4, -119, 15}, {221, 18, -67, 11}, {220, -8, -79, 45}, {223, -4, -5, 3}, {222, -15, -37, 30}}, {{228, -68, 34, 0}, {228, 94, 34, 0}, {236, 92, 32, 63}, {235, -12, 24, 170}, {226, 0, 0, 0}, {233, -15, -37, 30}, {230, -17, -68, 16}, {229, -4, -119, 15}, {232, 18, -67, 11}, {231, -8, -79, 45}, {234, -4, -5, 3}}};+#define PIC_FIRE 243+#endifdiff --git a/games/motox3m/src/fx.c b/games/motox3m/src/fx.cnew file mode 100644index 00000000..860bf30d--- /dev/null+++ b/games/motox3m/src/fx.c@@ -0,0 +1,265 @@+/* Moto X3M: the camera and the effects (see fx.h). */+#include <math.h>+#include <string.h>+#include "bike.h"+#include "fx.h"+#include "gfx.h"+#include "level.h"++Cam cam;++#define VIEW_H 480.0f /* the game's view: 720 x 480; the calculator shows its middle 640 x 480 */+#define VIEW_W 640.0f+#define CAR_DX 150.0f++static uint32_t seed = 12345;+float fx_rand(void) {+ seed = seed * 1664525u + 1013904223u;+ return (seed >> 8) * (1.0f / 16777216.0f);+}++static float prev_x, prev_y;++void cam_reset(float x, float y) {+ cam.frame_h = VIEW_H;+ cam.scale = 0.5f;+ cam.path = -1;+ cam.tweening = false;+ cam.shake = 0;+ prev_x = x + CAR_DX, prev_y = y - 100;+ cam.px = prev_x, cam.py = prev_y;+}++static float frame_h_by_speed(float t) {+ float e = VIEW_H;+ if (t > 500) {+ if (t > 3000) t = 3000;+ e += (t - 500) / 2500 * VIEW_H;+ }+ float d = e - cam.frame_h;+ if (d < -2) e = cam.frame_h - 2;+ else if (d > 8) e = cam.frame_h + 8;+ cam.frame_h = e;+ return e;+}++/* RaceCamera.focusOnCar */+void cam_update(float x, float y, float speed, bool frozen) {+ int path;+ float o = level_cam_y(x, y, &path);+ float h = frame_h_by_speed(speed), r, l, c;+ bool tw = false;+ if (cam.path >= 0 && path >= 0 && path != cam.path) tw = true;+ if (path >= 0 || cam.path < 0) cam.path = path >= 0 ? path : cam.path;+ if (isnan(o)) {+ r = VIEW_H / h;+ l = x + CAR_DX / r, c = y - 100;+ } else {+ float d = o - y + 200;+ if (d > h) h = d;+ r = VIEW_H / h;+ c = o - 0.5f * h, l = x + CAR_DX / r;+ }+ if (tw) cam.tweening = true;+ if (cam.tweening) prev_x += 0.4f * (l - prev_x), prev_y += 0.4f * (c - prev_y);+ else prev_x = l, prev_y = c;+ cam.x = prev_x - 0.5f * VIEW_W / r, cam.y = prev_y - 0.5f * VIEW_H / r;+ cam.w = VIEW_W / r, cam.h = VIEW_H / r;+ if (!frozen) {+ cam.px = prev_x, cam.py = prev_y;+ cam.scale = r * (SCREEN_H / VIEW_H);+ }+}++bool fx_in_camera(float x, float y, float m) {+ return x > cam.x - m && x < cam.x + cam.w + m && y > cam.y - m && y < cam.y + cam.h + m;+}++void fx_shake(void) { cam.shake = 0.6f; }+float fx_shake_x(void) {+ if (cam.shake <= 0) return 0;+ float t = 0.6f - cam.shake, k = fmodf(t, 0.2f) / 0.1f;+ return 7.5f * (k < 1 ? k : 2 - k);+}+float fx_shake_y(void) { return fx_shake_x(); }++/* ---- particles ---- */++enum { PT_SMOKE, PT_DUST, PT_FIRE, PT_GLASS };+typedef struct {+ float x, y, vx, vy, t, rot, va, scale;+ uint8_t kind, frame, alive, pic;+} Part;++#define NPART 96+static Part parts[NPART];+static int next_part;++typedef struct {+ float x, y, t;+ struct Obj *hide;+ bool alive;+} Boom;+static Boom booms[4];++static Part *new_part(int kind) {+ for (int k = 0; k < NPART; k++) {+ Part *p = &parts[(next_part + k) % NPART];+ if (!p->alive) {+ next_part = (next_part + k + 1) % NPART;+ memset(p, 0, sizeof *p);+ p->kind = (uint8_t)kind, p->alive = 1, p->scale = 1;+ return p;+ }+ }+ Part *p = &parts[next_part];+ next_part = (next_part + 1) % NPART;+ memset(p, 0, sizeof *p);+ p->kind = (uint8_t)kind, p->alive = 1, p->scale = 1;+ return p;+}++void fx_smoke(float x, float y, float a) {+ Part *p = new_part(PT_SMOKE);+ p->x = x, p->y = y, p->vx = -50 * cosf(a), p->vy = -50 * sinf(a);+}++void fx_ground(float x, float y, float s, bool fwd) {+ Part *p = new_part(PT_DUST);+ float a = 128 + 64 * fx_rand(), r = fx_rand() * 0.1f * 3.14159265f, h = 2 * 3.14159265f * fx_rand();+ r = fwd ? s - r : s + r;+ p->x = x + 8 * cosf(h), p->y = y + 8 * cosf(h);+ p->vx = a * cosf(r), p->vy = a * sinf(r);+}++void fx_fire(float x, float y) {+ Part *p = new_part(PT_FIRE);+ p->x = x - 5 + 10 * fx_rand(), p->y = y - 5 + 10 * fx_rand();+ p->rot = 3.14159265f * fx_rand(), p->scale = 1.3f;+}++void fx_glass(struct Obj *o) {+ static const float pts[2][12] = {{-47, -6, -35, 2, 13, 2, 48, 2, 47, -4, 4, -4},+ {-23, -6, -17, 2, 7, 2, 25, 2, 24, -4, 3, -4}};+ const ObjRec *r = o->r;+ bool big = level_param(o, 3) == 1;+ float scale = level_param(o, 3), hh = 0.5f * level_param(o, 2);+ if (!fx_in_camera(r->x, r->y, 256)) return;+ float cx = o->x->gx, cy = o->x->gy + 2 * hh;+ float c = cosf(r->rot), s = sinf(r->rot);+ for (int k = 0; k < 6; k++) {+ Part *p = new_part(PT_GLASS);+ float lx = pts[big ? 0 : 1][2 * k], ly = pts[big ? 0 : 1][2 * k + 1];+ p->x = r->x + lx * c - ly * s, p->y = r->y + lx * s + ly * c;+ p->rot = r->rot, p->scale = scale, p->pic = (uint8_t)k;+ /* a small push away from where it was hit (an impulse of 5 on a 4 px circle) */+ float dx = p->x + 0.5f * fx_rand() - cx, dy = p->y - cy, l = hypotf(dx, dy);+ if (l > 0) p->vx = dx / l * 5 / 0.0503f, p->vy = dy / l * 5 / 0.0503f;+ p->va = 0;+ }+}++void fx_landing(void) {}++void fx_explosion(float x, float y, struct Obj *hide) {+ for (int i = 0; i < 4; i++)+ if (!booms[i].alive) {+ booms[i] = (Boom){x, y, 0, hide, true};+ return;+ }+}++void fx_clear(void) {+ memset(parts, 0, sizeof parts);+ memset(booms, 0, sizeof booms);+ cam.shake = 0;+}++void fx_update(float dt) {+ if (cam.shake > 0) cam.shake -= dt;+ for (int i = 0; i < NPART; i++) {+ Part *p = &parts[i];+ if (!p->alive) continue;+ p->t += dt;+ switch (p->kind) {+ case PT_SMOKE:+ p->x += p->vx * dt, p->y += p->vy * dt, p->vy -= 500 * dt;+ if (p->t >= 15 / 30.0f) p->alive = 0;+ break;+ case PT_DUST:+ p->x += p->vx * dt, p->y += p->vy * dt, p->vy += 500 * dt;+ if (p->t >= 26 / 30.0f) p->alive = 0;+ break;+ case PT_FIRE:+ p->vy -= 350 * dt, p->y += p->vy * dt;+ p->scale -= 10 * dt;+ p->rot += 3.14159265f / 180;+ if (p->t >= 11 / 20.0f || p->scale <= 0) p->alive = 0;+ break;+ case PT_GLASS:+ p->vx *= 1 - dt * 0.015f, p->vy = p->vy * (1 - dt * 0.015f) + 500 * dt;+ p->x += p->vx * dt, p->y += p->vy * dt;+ if (p->t >= 5) p->alive = 0;+ break;+ }+ }+ for (int i = 0; i < 4; i++) {+ Boom *b = &booms[i];+ if (!b->alive) continue;+ b->t += dt;+ if (b->t >= 27 / 30.0f) {+ b->alive = false;+ if (b->hide) b->hide->hidden = 1;+ }+ }+}++/* ---- drawing ---- */++static inline float scr_x(float x) { return (x - cam.px) * cam.scale + SCREEN_W / 2 + cam.shx; }+static inline float scr_y(float y) { return (y - cam.py) * cam.scale + SCREEN_H / 2 + cam.shy; }++void fx_draw_back(void) {+ float k = cam.scale / 0.5f;+ for (int i = 0; i < NPART; i++) {+ Part *p = &parts[i];+ if (!p->alive || p->kind == PT_GLASS || p->kind == PT_FIRE) continue;+ float y = scr_y(p->y);+ if (!gfx_rows(y - 10, y + 10)) continue;+ int frame = (int)(p->t * 30);+ int base = p->kind == PT_SMOKE ? PIC_SMOKE_PART_ANIM : PIC_GROUND_PART_ANIM;+ int n = p->kind == PT_SMOKE ? 15 : 26;+ if (frame >= n) frame = n - 1;+ gfx_pic(base + frame, scr_x(p->x), y, k, k, 0, 256);+ }+}++/* the flaming rider's fire: behind everything in the objects' layer */+void fx_draw_fire(void) {+ float k = cam.scale / 0.5f;+ for (int i = 0; i < NPART; i++) {+ Part *p = &parts[i];+ if (!p->alive || p->kind != PT_FIRE) continue;+ int frame = (int)(p->t * 20);+ if (frame > 10) frame = 10;+ gfx_pic(PIC_FIRE + frame, scr_x(p->x), scr_y(p->y), k * p->scale, k * p->scale, p->rot, 256);+ }+}++void fx_draw_front(void) {+ float k = cam.scale / 0.5f;+ for (int i = 0; i < NPART; i++) {+ Part *p = &parts[i];+ if (!p->alive) continue;+ if (p->kind == PT_GLASS) {+ gfx_pic(PIC_GLASSCRASHED0_0 + p->pic, scr_x(p->x), scr_y(p->y), k * p->scale, k * p->scale, p->rot, 256);+ }+ }+ for (int i = 0; i < 4; i++) {+ Boom *b = &booms[i];+ if (!b->alive) continue;+ int frame = (int)(b->t * 30);+ if (frame > 26) frame = 26;+ gfx_pic(PIC_CAREXPLODE + frame, scr_x(b->x), scr_y(b->y), 2 * k, 2 * k, 0, 256);+ }+}diff --git a/games/motox3m/src/fx.h b/games/motox3m/src/fx.hnew file mode 100644index 00000000..9afb3ad4--- /dev/null+++ b/games/motox3m/src/fx.h@@ -0,0 +1,39 @@+/* Moto X3M: the camera and the effects: explosions, exhaust smoke, the wheels' dust, the flaming rider's fire,+ * broken glass (motox3m4.js: RaceCamera, CarExplodeObject, SmokePartClip, GroundPartClip, FirePartClip,+ * GlassBlockPart). */+#ifndef MX_FX_H+#define MX_FX_H+#include <stdbool.h>++typedef struct {+ float x, y, w, h; /* RaceCamera.x, y, w, h: the world rectangle in view */+ float px, py, scale; /* the point at the screen's centre, screen pixels a world pixel */+ float frame_h;+ float shake; /* seconds of shaking left */+ float shx, shy; /* this frame's shake offset (screen pixels) */+ int path;+ bool tweening;+} Cam;+extern Cam cam;++void cam_reset(float x, float y);+void cam_update(float x, float y, float speed, bool frozen);+bool fx_in_camera(float x, float y, float margin);+void fx_shake(void);+float fx_shake_x(void), fx_shake_y(void);++struct Obj;+void fx_explosion(float x, float y, struct Obj *hide_when_done);+void fx_smoke(float x, float y, float angle);+void fx_ground(float x, float y, float angle, bool fwd);+void fx_fire(float x, float y);+void fx_glass(struct Obj *glass);+void fx_landing(void);+void fx_update(float dt);+void fx_clear(void);+float fx_rand(void);+/* drawn by view.c */+void fx_draw_fire(void); /* the flaming rider's fire, behind the objects */+void fx_draw_back(void); /* smoke and dust, over the bike */+void fx_draw_front(void); /* explosions, fire, glass */+#endifdiff --git a/games/motox3m/src/game.c b/games/motox3m/src/game.cnew file mode 100644index 00000000..fa46b7df--- /dev/null+++ b/games/motox3m/src/game.c@@ -0,0 +1,385 @@+/* Moto X3M: the game's screens and rules around a run (see game.h). */+#include <math.h>+#include <stddef.h>+#include <string.h>+#include "bike.h"+#include "fx.h"+#include "game.h"+#include "gfx.h"+#include "level.h"+#include "plat.h"+#include "view.h"++Game g;+Save save;++#define DT (1.0f / 30)+static const int PRICES[NSKINS] = {0, 10, 20, 30, 40, 50};++void level_start(void);+void ui_draw(void);++/* ---- saves: "MX3S", a version, then the levels' stars and best times, the bike ---- */++#define SAVE_NAME "motox3m.sav"+#define SAVE_MAGIC 0x5333584Du+#define SAVE_VERSION 1++typedef struct {+ uint32_t magic;+ uint16_t version, size;+ Save s;+} SaveFile;+/* (tests/check.py and NumPlay's tests/test_games.py read these) */+_Static_assert(sizeof(SaveFile) == 264 && offsetof(SaveFile, s.best) == 60 && offsetof(SaveFile, s.skin) == 260,+ "the save's layout");++static void save_defaults(void) {+ memset(&save, 0, sizeof save);+ for (int i = 0; i < NLEVELS; i++) save.stars[i] = 0xFF;+ save.stars[0] = 0;+ save.skin = 1;+ save.owned = 1;+}++/* a copy in a Python script, "#>motox3m.sav:base64": installing apps from the NumWorks website keeps only Python+ * scripts, so the save comes back from it when the file itself is gone (the way NumPlay and its big games keep theirs) */+#define COPY_NAME "motox3m_saves.py"+static const char copy_head[] = "# Moto X3M's saves: keep this file\n";+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+#define COPY_BYTES (1 + sizeof copy_head - 1 + 2 + sizeof SAVE_NAME - 1 + 1 + (sizeof(SaveFile) + 2) / 3 * 4 + 2)++static bool copy_write(const SaveFile *f) {+ uint8_t o[COPY_BYTES], *p = o;+ const uint8_t *d = (const uint8_t *)f;+ uint32_t len = sizeof *f;+ *p++ = 0; /* (the script's status byte: not imported) */+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;+ *p++ = '#', *p++ = '>';+ memcpy(p, SAVE_NAME, sizeof SAVE_NAME - 1), p += sizeof SAVE_NAME - 1;+ *p++ = ':';+ for (uint32_t i = 0; i < len; i += 3, p += 4) {+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's+ * launcher/src/storage.c) */+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);+ p[0] = (uint8_t)b64[v >> 18 & 63];+ p[1] = (uint8_t)b64[v >> 12 & 63];+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';+ }+ *p++ = '\n';+ *p++ = 0;+ return plat_save(COPY_NAME, o, (uint32_t)(p - o));+}++static int b64_value(uint8_t c) {+ for (int i = 0; i < 64; i++)+ if ((uint8_t)b64[i] == c) return i;+ return -1;+}++/* the save from the copy; false if there is none or it is broken */+static bool copy_read(SaveFile *f) {+ uint32_t n, nl = sizeof SAVE_NAME - 1;+ const uint8_t *c = plat_load(COPY_NAME, &n), *l = NULL;+ if (!c) return false;+ for (uint32_t i = 0; i + nl + 3 <= n && !l; i++)+ if (c[i] == '#' && c[i + 1] == '>' && !memcmp(c + i + 2, SAVE_NAME, nl) && c[i + 2 + nl] == ':') l = c + i + 3 + nl;+ if (!l) return false;+ uint32_t len = 0;+ while (l + len < c + n && l[len] != '\n' && l[len]) len++;+ if (len != (sizeof *f + 2) / 3 * 4) return false;+ uint8_t *out = (uint8_t *)f;+ uint32_t o = 0;+ for (uint32_t i = 0; i < len; i += 4) {+ int v0 = b64_value(l[i]), v1 = b64_value(l[i + 1]);+ int v2 = l[i + 2] == '=' ? 0 : b64_value(l[i + 2]), v3 = l[i + 3] == '=' ? 0 : b64_value(l[i + 3]);+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) return false;+ uint32_t w = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);+ if (o < sizeof *f) out[o++] = (uint8_t)(w >> 16);+ if (o < sizeof *f) out[o++] = (uint8_t)(w >> 8);+ if (o < sizeof *f) out[o++] = (uint8_t)w;+ }+ return true;+}++void save_read(void) {+ save_defaults();+ uint32_t len;+ const uint8_t *d = plat_load(SAVE_NAME, &len);+ SaveFile f;+ if (d && len >= sizeof f) memcpy(&f, d, sizeof f);+ else if (d || !copy_read(&f)) return;+ if (f.magic != SAVE_MAGIC || f.version != SAVE_VERSION || f.size != sizeof(Save)) return;+ if (f.s.skin < 1 || f.s.skin > NSKINS) return;+ for (int i = 0; i < NLEVELS; i++)+ if (f.s.stars[i] != 0xFF && f.s.stars[i] > 3) return;+ save = f.s;+ save.owned |= 1;+ if (save.stars[0] == 0xFF) save.stars[0] = 0;+}++bool save_write(void) {+ SaveFile f = {SAVE_MAGIC, SAVE_VERSION, sizeof(Save), save};+ bool ok = plat_save(SAVE_NAME, &f, sizeof f);+ return copy_write(&f) && ok;+}++int total_stars(void) {+ int t = 0;+ for (int i = 0; i < NLEVELS; i++)+ if (save.stars[i] != 0xFF) t += save.stars[i];+ return t;+}++const int *shop_prices(void) { return PRICES; }++/* ---- a run ---- */++static void hard_restart(void) {+ g.help = g.level == 0;+ bike_restart();+ level_restart();+ bike_review();+ g.started = false;+ g.timer = 0;+ g.flip_t = 99;+ g.dead_t = 0;+ cam_reset(bike.frame.pos.x, bike.frame.pos.y);+ view_reset();+}++static void start_level(int n) {+ g.level = n;+ if (!level_load(n)) {+ g.state = S_MAP;+ return;+ }+ bike_build(lv.h->startx, lv.h->starty, save.skin);+ level_start();+ hard_restart();+ /* the camera starts on the bike (RaceCamera.hardFocusOnCar) */+ for (int i = 0; i < 20; i++) cam_update(bike.frame.pos.x, bike.frame.pos.y, 0, false);+ g.state = S_PLAY;+}++void game_start_level(int n) { start_level(n); }++void game_flip(int n) {+ g.timer -= 0.5f * n;+ g.flip_n = n;+ g.flip_t = 0;+}++void game_died(void) { g.dead_t = 0; }++/* postRace */+void game_finished(void) {+ int n = g.level;+ float t = g.timer;+ int stars = 0;+ for (int i = 0; i < 3; i++)+ if (t <= lv.h->prize[i]) stars++;+ bool improved;+ if (save.stars[n] == 0xFF || save.best[n] == 0) {+ save.stars[n] = (uint8_t)stars;+ save.best[n] = t;+ improved = true;+ } else {+ if (stars > save.stars[n]) save.stars[n] = (uint8_t)stars;+ improved = t < save.best[n];+ if (improved) save.best[n] = t;+ }+ if (n + 1 < NLEVELS && save.stars[n + 1] == 0xFF) save.stars[n + 1] = 0;+ g.stars = stars, g.improved = improved, g.result = t;+ g.finish_t = 0;+ g.state = S_FINISH;+ g.sel = 1;+ save_write();+}++static void world_tick(uint32_t keys) {+ /* MaxGameCore.updateIternal: the timer, before the world moves */+ if (g.started) {+ if (!bike.dead) g.timer += DT;+ } else if (bike.accell || bike.tilt != 0) {+ g.started = true;+ g.help = false;+ }+ /* the world far from the view keeps still (memory for contacts is short on the calculator) */+ np_window(cam.x - 900, cam.x + cam.w + 900);+ for (int k = 0; k < 2; k++) {+ np_step(DT / 2);+ level_events();+ }+ level_update(DT);+ bike_update(DT, g.state == S_PLAY ? keys : 0);+ fx_update(DT);+ cam_update(bike.x, bike.y, bike.speed, bike.finished);+ if (bike.dead) g.dead_t += DT;+ g.flip_t += DT;+ g.finish_t += DT;+ view_ticks++;+}++static void respawn(void) {+ if (bike.safe_id >= 0) {+ bike_review();+ level_review();+ bike_review();+ } else hard_restart();+}++/* ---- input ---- */++static inline bool pressed(uint32_t k) { return (g.keys & k) && !(g.prev & k); }++static void play_input(void) {+ if (pressed(K_BACK)) {+ g.state = S_PAUSE;+ g.sel = 0;+ g.confirm = false;+ return;+ }+ if (bike.dead && !bike.finished && pressed(K_OK)) respawn();+}++static void pause_input(void) {+ if (g.confirm) {+ if (pressed(K_LEFT) || pressed(K_RIGHT) || pressed(K_UP) || pressed(K_DOWN)) g.sel ^= 1;+ if (pressed(K_BACK)) g.confirm = false, g.sel = 3;+ else if (pressed(K_OK)) {+ if (g.sel == 0) {+ save_write();+ g.running = false;+ } else g.confirm = false, g.sel = 3;+ }+ return;+ }+ if (pressed(K_UP)) g.sel = (g.sel + 3) % 4;+ if (pressed(K_DOWN)) g.sel = (g.sel + 1) % 4;+ if (pressed(K_BACK)) g.state = S_PLAY;+ else if (pressed(K_OK)) {+ switch (g.sel) {+ case 0: g.state = S_PLAY; break;+ case 1: hard_restart(); g.state = S_PLAY; break;+ case 2: g.state = S_MAP; g.map_sel = g.level; break;+ case 3: g.confirm = true, g.sel = 1; break;+ }+ }+}++static int last_open(void) {+ int l = 0;+ for (int i = 0; i < NLEVELS; i++)+ if (save.stars[i] != 0xFF) l = i;+ return l;+}++static void finish_input(void) {+ if (g.finish_t < 0.3f) return;+ if (pressed(K_LEFT)) g.sel = (g.sel + 2) % 3;+ if (pressed(K_RIGHT)) g.sel = (g.sel + 1) % 3;+ int next = g.level + 1 < NLEVELS ? g.level + 1 : g.level;+ if (pressed(K_BACK)) {+ g.state = S_MAP, g.map_sel = next;+ return;+ }+ if (pressed(K_OK)) {+ if (g.sel == 0) g.state = S_MAP, g.map_sel = next;+ else if (g.sel == 1) {+ if (g.level + 1 >= NLEVELS) g.state = S_MAP, g.map_sel = g.level;+ else start_level(g.level + 1);+ } else {+ g.prev_state = S_MAP;+ g.map_sel = next;+ g.state = S_SHOP, g.shop_sel = save.skin - 1;+ }+ }+}++static void map_input(void) {+ int n = g.map_sel;+ if (pressed(K_RIGHT) || pressed(K_DOWN)) n++;+ if (pressed(K_LEFT) || pressed(K_UP)) n--;+ if (n < 0) n = 0;+ if (n > last_open()) n = last_open();+ g.map_sel = n;+ if (pressed(K_BACK)) g.state = S_TITLE, g.sel = 0;+ else if (pressed(K_OK)) start_level(g.map_sel);+}++static void shop_input(void) {+ if (pressed(K_LEFT) && g.shop_sel > 0) g.shop_sel--;+ if (pressed(K_RIGHT) && g.shop_sel < NSKINS - 1) g.shop_sel++;+ if (pressed(K_BACK)) g.state = g.prev_state, g.sel = 1;+ else if (pressed(K_OK)) {+ int k = g.shop_sel;+ if (save.owned & (1 << k)) save.skin = (uint8_t)(k + 1);+ else if (total_stars() >= PRICES[k]) {+ save.owned |= (uint8_t)(1 << k);+ save.skin = (uint8_t)(k + 1);+ }+ save_write();+ }+}++static void title_input(void) {+ if (pressed(K_UP)) g.sel = (g.sel + 2) % 3;+ if (pressed(K_DOWN)) g.sel = (g.sel + 1) % 3;+ if (pressed(K_BACK)) g.running = false;+ else if (pressed(K_OK)) {+ if (g.sel == 0) {+ g.state = S_MAP;+ g.map_sel = last_open();+ } else if (g.sel == 1) {+ g.prev_state = S_TITLE;+ g.state = S_SHOP;+ g.shop_sel = save.skin - 1;+ } else g.state = S_HELP;+ }+}++void game_init(void) {+ memset(&g, 0, sizeof g);+ save_read();+ g.running = true;+ g.state = S_TITLE;+ g.prev = ~0u; /* keys held at the start do nothing */+#ifdef START_LEVEL+ start_level(START_LEVEL - 1); /* (speed tests) */+#endif+}++void game_tick(uint32_t keys) {+ g.keys = keys;+ if (keys & K_HOME) {+ save_write();+ g.running = false;+ return;+ }+ switch (g.state) {+ case S_TITLE: title_input(); break;+ case S_MAP: map_input(); break;+ case S_SHOP: shop_input(); break;+ case S_PLAY:+ play_input();+ if (g.state == S_PLAY) world_tick(keys);+ break;+ case S_PAUSE: pause_input(); break;+ case S_HELP:+ if (pressed(K_BACK) || pressed(K_OK)) g.state = S_TITLE, g.sel = 2;+ break;+ case S_FINISH:+ world_tick(0);+ finish_input();+ break;+ }+ if (g.state != S_PLAY && g.state != S_FINISH) view_ticks++;+ g.prev = keys;+}++void game_draw(void) {+ if (g.state == S_PLAY || g.state == S_PAUSE || g.state == S_FINISH) view_prepare();+ gfx_frame(ui_draw);+}diff --git a/games/motox3m/src/game.h b/games/motox3m/src/game.hnew file mode 100644index 00000000..a0d403ab--- /dev/null+++ b/games/motox3m/src/game.h@@ -0,0 +1,53 @@+/* Moto X3M: the game's screens and rules around a run (GameplayState, ChooseZone, Garage, Menu, Inventory). */+#ifndef MX_GAME_H+#define MX_GAME_H+#include <stdbool.h>+#include <stdint.h>++#define NLEVELS 50+#define NSKINS 6++enum { S_TITLE, S_MAP, S_SHOP, S_PLAY, S_PAUSE, S_FINISH, S_HELP };++typedef struct {+ uint8_t stars[NLEVELS]; /* 0xFF: locked */+ float best[NLEVELS]; /* seconds, 0: none */+ uint8_t skin; /* 1-6 */+ uint8_t owned; /* bit k: skin k+1 */+ uint8_t seen_help;+} Save;++typedef struct {+ int state, prev_state;+ int level; /* 0-based */+ int sel; /* the menu's choice */+ int map_sel;+ float map_x; /* the map's scroll */+ int shop_sel;+ bool started; /* the timer runs (MaxGameCore.drive) */+ float timer;+ float flip_t; /* the flip message's age */+ int flip_n;+ bool help; /* "Use arrows to move" */+ float dead_t;+ /* the last finish */+ int stars;+ bool improved;+ float result;+ float finish_t;+ bool confirm; /* the quit question */+ uint32_t keys, prev;+ bool running;+} Game;++extern Game g;+extern Save save;++void game_init(void);+void game_start_level(int n); /* past the menus (tests) */+void game_tick(uint32_t keys); /* 30 a second */+void game_draw(void);+bool save_write(void);+void save_read(void);+int total_stars(void);+#endifdiff --git a/games/motox3m/src/gfx.c b/games/motox3m/src/gfx.cnew file mode 100644index 00000000..1dc33b38--- /dev/null+++ b/games/motox3m/src/gfx.c@@ -0,0 +1,320 @@+/* Moto X3M: drawing (see gfx.h). */+#include <math.h>+#include <string.h>+#include "gfx.h"++uint16_t *gfx_band;+int gfx_y0;++void gfx_init(uint16_t *band) { gfx_band = band; }++void gfx_frame(void (*draw)(void)) {+ for (int y = 0; y < SCREEN_H; y += BAND) {+ gfx_y0 = y;+ draw();+ plat_push(0, y, SCREEN_W, BAND, gfx_band);+ }+}++static inline uint16_t blend(uint16_t d, uint16_t s, int a) {+ /* a: 0-256 */+ uint32_t dd = (d | ((uint32_t)d << 16)) & 0x07E0F81F, ss = (s | ((uint32_t)s << 16)) & 0x07E0F81F;+ uint32_t r = (dd + (((ss - dd) * (uint32_t)(a >> 3)) >> 5)) & 0x07E0F81F;+ return (uint16_t)(r | (r >> 16));+}++/* A polygon's edges that reach the band, for its even-odd spans: edges wholly right of the screen are left out+ * (they cannot change what is on it), edges wholly left of it only count for the parity. */+#define MAX_EDGES 160+#define MAX_LEFT 96+typedef struct {+ int ne, nl;+ float e[4 * MAX_EDGES];+ float l[2 * MAX_LEFT];+} Edges;++static void band_edges(const float *xy, int n, Edges *E) {+ E->ne = E->nl = 0;+ float b0 = (float)gfx_y0, b1 = (float)(gfx_y0 + BAND);+ for (int i = 0, j = n - 1; i < n; j = i++) {+ float yi = xy[2 * i + 1], yj = xy[2 * j + 1];+ float lo = yi < yj ? yi : yj, hi = yi < yj ? yj : yi;+ if (hi < b0 || lo > b1 || yi == yj) continue;+ float xi = xy[2 * i], xj = xy[2 * j];+ if (xi >= SCREEN_W && xj >= SCREEN_W) continue;+ if (xi < 0 && xj < 0) {+ if (E->nl < MAX_LEFT) E->l[2 * E->nl] = yj, E->l[2 * E->nl + 1] = yi, E->nl++;+ continue;+ }+ if (E->ne >= MAX_EDGES) continue;+ float *e = E->e + 4 * E->ne++;+ e[0] = xj, e[1] = yj, e[2] = xi, e[3] = yi;+ }+}++/* the row's spans (pairs of x), clamped to the screen */+static int spans(const Edges *E, float yc, int16_t *out) {+ float xs[48];+ int k = 0;+ bool inside = false;+ for (int i = 0; i < E->nl; i++)+ if ((E->l[2 * i] > yc) != (E->l[2 * i + 1] > yc)) inside = !inside;+ for (int i = 0; i < E->ne; i++) {+ const float *e = E->e + 4 * i;+ if ((e[3] > yc) != (e[1] > yc)) {+ float x = e[0] + (yc - e[1]) * (e[2] - e[0]) / (e[3] - e[1]);+ if (x < 0) inside = !inside;+ else if (k < 48) xs[k++] = x;+ }+ }+ for (int a = 1; a < k; a++) {+ float v = xs[a];+ int b = a - 1;+ while (b >= 0 && xs[b] > v) xs[b + 1] = xs[b], b--;+ xs[b + 1] = v;+ }+ int ns = 0;+ float start = 0;+ for (int i = 0; i < k; i++) {+ if (inside) {+ int xa = (int)ceilf(start - 0.5f), xb = (int)ceilf(xs[i] - 0.5f);+ if (xa < 0) xa = 0;+ if (xb > SCREEN_W) xb = SCREEN_W;+ if (xa < xb) out[2 * ns] = (int16_t)xa, out[2 * ns + 1] = (int16_t)xb, ns++;+ } else start = xs[i];+ inside = !inside;+ }+ if (inside) {+ int xa = (int)ceilf(start - 0.5f);+ if (xa < 0) xa = 0;+ if (xa < SCREEN_W) out[2 * ns] = (int16_t)xa, out[2 * ns + 1] = SCREEN_W, ns++;+ }+ return ns;+}+++void gfx_poly_pic(const float *xy, int n, const Pic *p, const Map *m, bool wrap, int alpha) {+ Edges E;+ int16_t sp[48];+ band_edges(xy, n, &E);+ if (!E.ne && !E.nl) return;+ const uint16_t *pal = pic_pal(p);+ const uint8_t *al = pic_alpha(p), *px = pic_px(p);+ bool four = p->flags & IMG_4BIT, opaque = (p->flags & IMG_OPAQUE) && alpha >= 256;+ int w = p->w, h = p->h, stride = pic_stride(p);+ int32_t du = (int32_t)(m->ux * 65536), dv = (int32_t)(m->vx * 65536);+ for (int r = 0; r < BAND; r++) {+ int y = gfx_y0 + r;+ float yc = y + 0.5f;+ int k = spans(&E, yc, sp);+ uint16_t *row = gfx_band + r * SCREEN_W;+ for (int s = 0; s < k; s++) {+ int xa = sp[2 * s], xb = sp[2 * s + 1];+ float fx = xa + 0.5f;+ int32_t u = (int32_t)((m->ux * fx + m->uy * yc + m->u0) * 65536);+ int32_t v = (int32_t)((m->vx * fx + m->vy * yc + m->v0) * 65536);+ if (wrap) {+ unsigned wm = (unsigned)w - 1, hm = (unsigned)h - 1;+ if (four) {+ for (int x = xa; x < xb; x++, u += du, v += dv) {+ unsigned tx = (unsigned)(u >> 16) & wm, ty = (unsigned)(v >> 16) & hm;+ uint8_t b = px[ty * (unsigned)stride + (tx >> 1)];+ unsigned c = tx & 1 ? b & 15 : b >> 4;+ if (opaque) row[x] = pal[c];+ else if (al[c]) row[x] = al[c] == 255 && alpha >= 256 ? pal[c] : blend(row[x], pal[c], al[c] * alpha >> 8);+ }+ } else {+ for (int x = xa; x < xb; x++, u += du, v += dv) {+ unsigned tx = (unsigned)(u >> 16) & wm, ty = (unsigned)(v >> 16) & hm;+ unsigned c = px[ty * (unsigned)stride + tx];+ if (opaque) row[x] = pal[c];+ else if (al[c]) row[x] = al[c] == 255 && alpha >= 256 ? pal[c] : blend(row[x], pal[c], al[c] * alpha >> 8);+ }+ }+ } else {+ for (int x = xa; x < xb; x++, u += du, v += dv) {+ int tx = u >> 16, ty = v >> 16;+ if ((unsigned)tx >= (unsigned)w || (unsigned)ty >= (unsigned)h) continue;+ unsigned c;+ if (four) {+ uint8_t b = px[ty * stride + (tx >> 1)];+ c = tx & 1 ? b & 15 : b >> 4;+ } else c = px[ty * stride + tx];+ if (!al[c]) continue;+ row[x] = al[c] == 255 && alpha >= 256 ? pal[c] : blend(row[x], pal[c], al[c] * alpha >> 8);+ }+ }+ }+ }+}++void gfx_poly_color(const float *xy, int n, uint16_t c, int alpha) {+ Edges E;+ int16_t sp[48];+ band_edges(xy, n, &E);+ for (int r = 0; r < BAND && (E.ne || E.nl); r++) {+ float yc = gfx_y0 + r + 0.5f;+ int k = spans(&E, yc, sp);+ uint16_t *row = gfx_band + r * SCREEN_W;+ for (int s = 0; s < k; s++) {+ int xa = sp[2 * s], xb = sp[2 * s + 1];+ if (alpha >= 256)+ for (int x = xa; x < xb; x++) row[x] = c;+ else+ for (int x = xa; x < xb; x++) row[x] = blend(row[x], c, alpha);+ }+ }+}++void gfx_pic(int id, float x, float y, float sx, float sy, float angle, int alpha) {+ const Pic *p = pic(id);+ if (!p || sx == 0 || sy == 0) return;+ float c = cosf(angle), s = sinf(angle);+ float corners[8];+ float lx[4] = {0, (float)p->w, (float)p->w, 0}, ly[4] = {0, 0, (float)p->h, (float)p->h};+ float miny = 1e9f, maxy = -1e9f;+ for (int i = 0; i < 4; i++) {+ float dx = (lx[i] - p->px) * sx, dy = (ly[i] - p->py) * sy;+ corners[2 * i] = x + dx * c - dy * s;+ corners[2 * i + 1] = y + dx * s + dy * c;+ if (corners[2 * i + 1] < miny) miny = corners[2 * i + 1];+ if (corners[2 * i + 1] > maxy) maxy = corners[2 * i + 1];+ }+ if (!gfx_rows(miny, maxy)) return;+ /* screen to picture: undo the turn, then the scale */+ Map m;+ m.ux = c / sx, m.uy = s / sx, m.u0 = p->px - (x * c + y * s) / sx;+ m.vx = -s / sy, m.vy = c / sy, m.v0 = p->py - (-x * s + y * c) / sy;+ gfx_poly_pic(corners, 4, p, &m, false, alpha);+}++void gfx_pic_at(int id, float x, float y, float scale, int alpha) {+ const Pic *p = pic(id);+ if (!p) return;+ if (!gfx_rows(y, y + p->h * scale)) return;+ if (scale == 1 && x == (int)x && y == (int)y) {+ /* straight copy */+ const uint16_t *pal = pic_pal(p);+ const uint8_t *al = pic_alpha(p), *px = pic_px(p);+ int ix = (int)x, iy = (int)y;+ int r0 = gfx_y0 > iy ? gfx_y0 - iy : 0, r1 = p->h;+ if (iy + r1 > gfx_y0 + BAND) r1 = gfx_y0 + BAND - iy;+ int c0 = ix < 0 ? -ix : 0, c1 = p->w;+ if (ix + c1 > SCREEN_W) c1 = SCREEN_W - ix;+ bool opaque = (p->flags & IMG_OPAQUE) && alpha >= 256;+ if (opaque) {+ /* a straight copy of opaque rows (the backgrounds) */+ for (int r = r0; r < r1; r++) {+ uint16_t *row = gfx_band + (iy + r - gfx_y0) * SCREEN_W + ix;+ if (p->flags & IMG_4BIT) {+ const uint8_t *src = px + r * ((p->w + 1) >> 1);+ int cx = c0;+ if (cx & 1) row[cx] = pal[src[cx >> 1] & 15], cx++;+ for (; cx + 1 < c1; cx += 2) {+ uint8_t b = src[cx >> 1];+ row[cx] = pal[b >> 4], row[cx + 1] = pal[b & 15];+ }+ if (cx < c1) row[cx] = pal[src[cx >> 1] >> 4];+ } else {+ const uint8_t *src = px + r * p->w;+ for (int cx = c0; cx < c1; cx++) row[cx] = pal[src[cx]];+ }+ }+ return;+ }+ for (int r = r0; r < r1; r++) {+ uint16_t *row = gfx_band + (iy + r - gfx_y0) * SCREEN_W + ix;+ for (int cx = c0; cx < c1; cx++) {+ unsigned c = pic_at(p, px, cx, r);+ if (opaque) row[cx] = pal[c];+ else if (al[c]) row[cx] = al[c] == 255 && alpha >= 256 ? pal[c] : blend(row[cx], pal[c], al[c] * alpha >> 8);+ }+ }+ return;+ }+ float corners[8] = {x, y, x + p->w * scale, y, x + p->w * scale, y + p->h * scale, x, y + p->h * scale};+ Map m = {1 / scale, 0, -x / scale, 0, 1 / scale, -y / scale};+ gfx_poly_pic(corners, 4, p, &m, false, alpha);+}++void gfx_fill(int x, int y, int w, int h, uint16_t c, int alpha) {+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND ? y + h : gfx_y0 + BAND;+ if (x < 0) w += x, x = 0;+ if (x + w > SCREEN_W) w = SCREEN_W - x;+ if (w <= 0) return;+ for (int yy = y0; yy < y1; yy++) {+ uint16_t *row = gfx_band + (yy - gfx_y0) * SCREEN_W + x;+ if (alpha >= 256)+ for (int i = 0; i < w; i++) row[i] = c;+ else+ for (int i = 0; i < w; i++) row[i] = blend(row[i], c, alpha);+ }+}++void gfx_line(float x0, float y0, float x1, float y1, float w, uint16_t c, int alpha) {+ float dx = x1 - x0, dy = y1 - y0, l = sqrtf(dx * dx + dy * dy);+ if (l <= 0) return;+ float nx = -dy / l * w / 2, ny = dx / l * w / 2;+ float q[8] = {x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny};+ float lo = fminf(fminf(q[1], q[3]), fminf(q[5], q[7])), hi = fmaxf(fmaxf(q[1], q[3]), fmaxf(q[5], q[7]));+ if (!gfx_rows(lo, hi)) return;+ gfx_poly_color(q, 4, c, alpha);+}++/* ---- text ---- */++static void glyph(const Font *f, const Glyph *g, int x, int y, uint16_t color, int alpha) {+ const uint8_t *bits = font_bits(f) + g->off;+ int gx = x + g->x, gy = y + g->y;+ for (int r = 0; r < g->h; r++) {+ int yy = gy + r;+ if (yy < gfx_y0 || yy >= gfx_y0 + BAND) continue;+ uint16_t *row = gfx_band + (yy - gfx_y0) * SCREEN_W;+ for (int c = 0; c < g->w; c++) {+ int xx = gx + c;+ if ((unsigned)xx >= SCREEN_W) continue;+ int i = r * g->w + c;+ int v = i & 1 ? bits[i >> 1] & 15 : bits[i >> 1] >> 4;+ if (!v) continue;+ int a = (v * 17 + 1) * alpha >> 8;+ row[xx] = a >= 255 ? color : blend(row[xx], color, a);+ }+ }+}++int gfx_text_width(int fid, const char *s) {+ const Font *f = font(fid);+ const Glyph *gs = font_glyphs(f);+ int w = 0;+ for (; *s; s++) {+ unsigned ch = (uint8_t)*s;+ if (ch < f->first || ch >= f->first + f->count) continue;+ w += gs[ch - f->first].adv;+ }+ return w;+}++int gfx_text(int fid, float fx, float fy, const char *s, uint16_t color, uint16_t outline, int thick, int align) {+ const Font *f = font(fid);+ const Glyph *gs = font_glyphs(f);+ int w = gfx_text_width(fid, s);+ int x = (int)(fx + 0.5f) - (align == 1 ? w / 2 : align == 2 ? w : 0), y = (int)(fy + 0.5f);+ if (y + thick + 8 < gfx_y0 || y - f->ascent - thick > gfx_y0 + BAND) return w;+ for (int pass = thick ? 0 : 1; pass < 2; pass++) {+ int px = x;+ for (const char *p = s; *p; p++) {+ unsigned ch = (uint8_t)*p;+ if (ch < f->first || ch >= f->first + f->count) continue;+ const Glyph *g = &gs[ch - f->first];+ if (g->w) {+ if (pass == 0) {+ for (int oy = -thick; oy <= thick; oy++)+ for (int ox = -thick; ox <= thick; ox++)+ if ((ox || oy) && ox * ox + oy * oy <= thick * thick + 1) glyph(f, g, px + ox, y + oy, outline, 256);+ } else glyph(f, g, px, y, color, 256);+ }+ px += g->adv;+ }+ }+ return w;+}diff --git a/games/motox3m/src/gfx.h b/games/motox3m/src/gfx.hnew file mode 100644index 00000000..0a13117a--- /dev/null+++ b/games/motox3m/src/gfx.h@@ -0,0 +1,41 @@+/* Moto X3M: drawing. The calculator has no frame buffer for the whole screen, so a frame is drawn a band of rows+ * at a time: the scene is walked once per band and each primitive fills only the band's rows. */+#ifndef MX_GFX_H+#define MX_GFX_H+#include <stdbool.h>+#include <stdint.h>+#include "plat.h"+#include "res.h"++#define BAND 12++static inline uint16_t rgb565(uint32_t rgb) {+ return (uint16_t)(((rgb >> 8) & 0xF800) | ((rgb >> 5) & 0x07E0) | ((rgb >> 3) & 0x001F));+}++extern uint16_t *gfx_band;+extern int gfx_y0; /* the band's first row */++void gfx_init(uint16_t *band);+/* draws a frame: calls draw() once for each band, then pushes it */+void gfx_frame(void (*draw)(void));+static inline bool gfx_rows(float y0, float y1) { return y1 >= gfx_y0 && y0 < gfx_y0 + BAND; }++/* an affine map from the screen to a picture's pixels: u = ux*x + uy*y + u0, v = vx*x + vy*y + v0 */+typedef struct {+ float ux, uy, u0, vx, vy, v0;+} Map;++/* a polygon (screen points, even-odd) filled with a picture: wrapped (tiles) or clipped to it */+void gfx_poly_pic(const float *xy, int n, const Pic *p, const Map *m, bool wrap, int alpha);+void gfx_poly_color(const float *xy, int n, uint16_t c, int alpha);+/* a picture turned and scaled around its pivot, the pivot at (x, y); alpha 0-256 */+void gfx_pic(int id, float x, float y, float sx, float sy, float angle, int alpha);+/* a picture upright at its top-left (no pivot), scaled */+void gfx_pic_at(int id, float x, float y, float scale, int alpha);+void gfx_fill(int x, int y, int w, int h, uint16_t c, int alpha);+void gfx_line(float x0, float y0, float x1, float y1, float w, uint16_t c, int alpha);+/* text: y is the baseline; align 0 left, 1 centre, 2 right; outline 0 none; its width */+int gfx_text(int font, float x, float y, const char *s, uint16_t color, uint16_t outline, int thick, int align);+int gfx_text_width(int font, const char *s);+#endifdiff --git a/games/motox3m/src/icon.png b/games/motox3m/src/icon.pngnew file mode 100644index 00000000..0b9c9c33Binary files /dev/null and b/games/motox3m/src/icon.png differdiff --git a/games/motox3m/src/level.c b/games/motox3m/src/level.cnew file mode 100644index 00000000..73b844e8--- /dev/null+++ b/games/motox3m/src/level.c@@ -0,0 +1,853 @@+/* Moto X3M: a level in play (see level.h). */+#include <math.h>+#include <string.h>+#include "bike.h"+#include "fx.h"+#include "level.h"++Level lv;++static uint8_t arena[ARENA_SIZE] __attribute__((aligned(8)));+int arena_used, arena_peak;++void *arena_alloc(int size) {+ size = (size + (int)sizeof(void *) - 1) & ~((int)sizeof(void *) - 1);+ if (arena_used + size > ARENA_SIZE) return 0;+ void *p = arena + arena_used;+ arena_used += size;+ if (arena_used > arena_peak) arena_peak = arena_used;+ memset(p, 0, (size_t)size);+ return p;+}++#define MAX_MATS 40+static Material mats[MAX_MATS];+/* Filters (InteractionFilter(collisionGroup, collisionMask, sensorGroup, sensorMask)), as tools/levels.py */+static const Filter filters[] = {+ {1, -1, 1, -1}, {0, 0, 0, 0}, {0, 0, 1, 4369}, {1, 4369, 1, -1},+ {4096, 272, 17, 4369}, {4096, 272, 1, -1}, {17, 4369, 1, 4369}, {256, 4096, 1, 4369},+};+static SBody *sbodies;++float level_param(const Obj *o, int k) { return lv.params[o->r->params + k]; }++static Con *new_con(int type, Body *b1, Body *b2) {+ Con *c = arena_alloc(sizeof(Con));+ if (!c) return 0;+ c->type = (uint8_t)type;+ c->b1 = b1, c->b2 = b2;+ c->flags = CF_ACTIVE | CF_STIFF;+ c->frequency = 10, c->damping = 1, c->ratio = 1;+ c->sb = -1;+ np_register_con(c);+ return c;+}++extern Body *np_world(void);++static void body_reset(Body *b, const DBodyRec *r) {+ b->pos = v2(r->x, r->y);+ np_body_set_rot(b, r->rot);+ b->vel = v2(0, 0);+ b->angvel = 0, b->torque = 0;+}++/* the level's bodies, objects and constraints into the space */+bool level_load(int n) {+ const LevelHdr *h = level(n);+ memset(&lv, 0, sizeof lv);+ lv.h = h, lv.n = n;+ arena_used = 0;+ np_reset();+ sp.gravity = v2(0, h->gravity);+ /* materials: the level's, then room for the bike's */+ memcpy(mats, lvl_at(h, L_MATS), sizeof(Material) * h->nmats);+ sp.mats = mats;+ sp.filters = filters;+ sp.sshapes = lvl_at(h, L_SSHAPES);+ sp.nsshapes = h->nsshapes;+ sp.sverts = lvl_at(h, L_SVERTS);+ sp.buckets = lvl_at(h, L_BUCKETS);+ sp.bucket_list = lvl_at(h, L_BLIST);+ sp.nbuckets = h->nbuckets;+ sp.bucket_x0 = (int)h->bucket_x0;+ sbodies = arena_alloc(sizeof(SBody) * (h->nsbodies + 1));+ const SBodyRec *sr = lvl_at(h, L_SBODIES);+ for (int i = 0; i < h->nsbodies; i++) {+ sbodies[i].cb = sr[i].cb, sbodies[i].flags = BF_SPACE, sbodies[i].pad = sr[i].pad;+ sbodies[i].viscosity = sr[i].viscosity, sbodies[i].density = sr[i].density;+ }+ sp.sbodies = sbodies, sp.nsbodies = h->nsbodies;+ /* pointer tables: the level's bodies and shapes, then the bike's */+ int njoints = 0;+ const ObjRec *orr0 = lvl_at(h, L_OBJS);+ for (int i = 0; i < h->nobj; i++) njoints += orr0[i].type == O_PIVOT ? 1 : orr0[i].type == O_MOTOR ? 2 : 0;+ int maxb = h->ndbodies + 16, maxs = h->ndshapes + 16, maxc = njoints + 40; /* (the bike: 15 bodies, 39 joints) */+ sp.bodies = arena_alloc(sizeof(Body *) * maxb);+ sp.shapes = arena_alloc(sizeof(Shape *) * maxs);+ sp.cons = arena_alloc(sizeof(Con *) * maxc);+ if (!sp.bodies || !sp.shapes || !sp.cons || !sbodies) return false;+ /* dynamic and kinematic bodies */+ lv.ndbodies = h->ndbodies;+ lv.dbodies = arena_alloc(sizeof(Body) * (h->ndbodies ? h->ndbodies : 1));+ const DBodyRec *dr = lvl_at(h, L_DBODIES);+ const DShapeRec *ds = lvl_at(h, L_DSHAPES);+ const float *dd = lvl_at(h, L_DDATA);+ if (!lv.dbodies) return false;+ for (int i = 0; i < h->ndbodies; i++) {+ Body *b = &lv.dbodies[i];+ const DBodyRec *r = &dr[i];+ b->type = r->type == 2 ? B_KINEMATIC : B_DYNAMIC;+ b->cb = r->cb;+ b->flags = r->flags & BF_NOROT;+ b->pad = (r->flags & 0x10) != 0; /* ground */+ body_reset(b, r);+ b->nshapes = r->nshapes;+ b->shapes = arena_alloc(sizeof(Shape) * r->nshapes);+ if (!b->shapes) return false;+ for (int k = 0; k < r->nshapes; k++) {+ const DShapeRec *q = &ds[r->first_shape + k];+ Shape *s = &b->shapes[k];+ s->type = q->type ? SH_POLY : SH_CIRCLE;+ s->n = q->n, s->filter = q->filter, s->flags = q->flags, s->mat = q->mat;+ s->radius = q->radius, s->lcom = v2(q->cx, q->cy), s->area = q->area, s->inertia = q->inertia;+ if (q->type) {+ s->loc = dd + q->off;+ s->glob = arena_alloc((int)sizeof(float) * 5 * q->n);+ if (!s->glob) return false;+ }+ }+ np_register(b);+ b->user = 0;+ np_body_add(b);+ }+ /* objects */+ lv.nobj = h->nobj;+ lv.objs = arena_alloc(sizeof(Obj) * (h->nobj ? h->nobj : 1));+ if (!lv.objs) return false;+ lv.params = lvl_at(h, L_PARAMS);+ lv.aux = lvl_at(h, L_AUX);+ lv.draws = lvl_at(h, L_DRAWS);+ lv.dpts = lvl_at(h, L_DPTS);+ const ObjRec *orr = lvl_at(h, L_OBJS);+ Body *world = np_world();+ for (int i = 0; i < h->nobj; i++) {+ Obj *o = &lv.objs[i];+ const ObjRec *r = &orr[i];+ o->r = r;+ o->body = r->body >= 0 ? &lv.dbodies[r->body] : 0;+ o->body2 = r->body2 >= 0 ? &lv.dbodies[r->body2] : 0;+ o->sbody = r->type == O_PIVOT || r->type == O_MOTOR ? -1 : r->sbody;+ if (o->body && !o->body->user) o->body->user = o;+ if (r->type == O_PIVOT || r->type == O_MOTOR || r->type == O_MOVER || r->type == O_GLASS) {+ o->x = arena_alloc(sizeof(ObjExt));+ if (!o->x) return false;+ }+ if (r->type == O_MOVER) {+ o->x->mv = arena_alloc(sizeof(Mover));+ if (!o->x->mv) return false;+ }+ switch (r->type) {+ case O_PIVOT: {+ /* the pivot holds body (c) to body2 (u) or the world, at the object's point */+ Body *c = o->body, *u = o->body2 ? o->body2 : world;+ V2 p = v2(r->x, r->y);+ Con *k = new_con(C_PIVOT, c, u);+ if (!k) return false;+ k->a1 = np_world_to_local(c, p), k->a2 = np_world_to_local(u, p);+ k->flags |= CF_IGNORE;+ k->sb = (int16_t)(o->body2 ? -1 : r->sbody);+ o->x->con[0] = k;+ break;+ }+ case O_MOTOR: {+ /* pivot(f, s) and motor(f, s): s = body turns, f = body2 or the world */+ Body *s = o->body, *f = o->body2 ? o->body2 : world;+ V2 p = v2(r->x, r->y);+ Con *k = new_con(C_PIVOT, f, s);+ Con *m = new_con(C_MOTOR, f, s);+ if (!k || !m) return false;+ k->a1 = np_world_to_local(f, p), k->a2 = np_world_to_local(s, p);+ k->flags |= CF_IGNORE;+ k->sb = m->sb = (int16_t)(o->body2 ? -1 : r->sbody);+ m->rate = level_param(o, 0);+ m->flags &= (uint8_t)~CF_ACTIVE;+ o->x->con[0] = k, o->x->con[1] = m;+ o->x->gx = r->x, o->x->gy = r->y;+ break;+ }+ default: break;+ }+ }+ return true;+}++/* MaxGameCore.add: an object answers activate() when it has an id */+static bool activatable(const Obj *o) {+ switch (o->r->type) {+ case O_SHAPER: case O_DYN: case O_REMOVED: case O_TNT: case O_MOTOR: case O_MOVER: case O_PIVOT: case O_DECOR:+ case O_GEYSER: case O_WATER:+ return true;+ default:+ return false;+ }+}++static void body_space(Body *b, bool in) {+ if (!b) return;+ if (in) np_body_add(b);+ else np_body_remove(b);+}++static void body_cons(Body *b, bool on, bool pivots_only) {+ for (int i = 0; i < sp.ncons; i++) {+ Con *c = sp.cons[i];+ if ((c->b1 == b || c->b2 == b) && (!pivots_only || c->type == C_PIVOT)) {+ if (on) c->flags |= CF_ACTIVE;+ else c->flags &= (uint8_t)~CF_ACTIVE;+ np_con_clear(c);+ }+ }+}++static bool body_has_cons(const Body *b) {+ for (int i = 0; i < sp.ncons; i++)+ if (sp.cons[i]->b1 == b || sp.cons[i]->b2 == b) return true;+ return false;+}++static void stop_reset(Obj *o) {+ if (!o->body) return;+ const DBodyRec *r = (const DBodyRec *)lvl_at(lv.h, L_DBODIES) + o->r->body;+ body_reset(o->body, r);+ if (o->body->flags & BF_SPACE) np_body_moved(o->body);+}++/* ---- movers ---- */++static V2 mv_point(const Obj *o, int i) { return v2(lv.aux[2 * (o->r->aux + i)], lv.aux[2 * (o->r->aux + i) + 1]); }++static V2 mv_next(const Obj *o) {+ int n = o->r->naux;+ if (o->x->mv->pdir > 0) return o->x->mv->pid >= n - 1 ? mv_point(o, 0) : mv_point(o, o->x->mv->pid + 1);+ return o->x->mv->pid <= 0 ? mv_point(o, n - 1) : mv_point(o, o->x->mv->pid - 1);+}++static void mv_vel(Obj *o) {+ Body *b = o->body;+ V2 e = mv_next(o);+ float dx = e.x - b->pos.x, dy = e.y - b->pos.y, a = atan2f(dy, dx);+ o->x->mv->vx = cosf(a) * o->x->mv->speed, o->x->mv->vy = sinf(a) * o->x->mv->speed;+ o->x->mv->ttp_total = o->x->mv->ttp = sqrtf(dx * dx + dy * dy) / o->x->mv->speed;+}++static void mv_accel_vel(Obj *o) {+ Body *b = o->body;+ int n = o->r->naux;+ float e = 0;+ if (o->x->mv->pdir > 0) {+ for (int i = 1; i <= o->x->mv->pid; i++) {+ V2 p = mv_point(o, i - 1), q = mv_point(o, i);+ e += hypotf(q.x - p.x, q.y - p.y);+ }+ V2 p = mv_point(o, o->x->mv->pid);+ e += hypotf(b->pos.x - p.x, b->pos.y - p.y);+ } else {+ for (int i = n - 2; i >= o->x->mv->pid; i--) {+ V2 p = mv_point(o, i + 1), q = mv_point(o, i);+ e += hypotf(q.x - p.x, q.y - p.y);+ }+ V2 p = mv_point(o, o->x->mv->pid);+ e += hypotf(b->pos.x - p.x, b->pos.y - p.y);+ e = o->x->mv->total - e;+ }+ float base = level_param(o, 0), ad = level_param(o, 1);+ if (e < ad) o->x->mv->speed = o->x->mv->min_speed + e / ad * (base - o->x->mv->min_speed);+ else if (e > o->x->mv->total - ad) o->x->mv->speed = o->x->mv->min_speed + (o->x->mv->total - e) / ad * (base - o->x->mv->min_speed);+ else o->x->mv->speed = base;+ V2 nx = mv_next(o);+ float dx = nx.x - b->pos.x, dy = nx.y - b->pos.y, a = atan2f(dy, dx);+ o->x->mv->vx = cosf(a) * o->x->mv->speed, o->x->mv->vy = sinf(a) * o->x->mv->speed;+ o->x->mv->ttp_total = o->x->mv->ttp = sqrtf(dx * dx + dy * dy) / o->x->mv->speed;+}++static void mv_check_dir(Obj *o) {+ if (o->x->mv->dir * o->x->mv->prev_dir < 0) {+ o->x->mv->pdir = (int8_t)-o->x->mv->pdir;+ o->x->mv->vx = -o->x->mv->vx, o->x->mv->vy = -o->x->mv->vy;+ o->x->mv->ttp = o->x->mv->ttp_total - o->x->mv->ttp;+ }+ o->x->mv->prev_dir = o->x->mv->dir;+}++static void mv_restart(Obj *o) {+ Body *b = o->body;+ const ObjRec *r = o->r;+ int fl = r->flags;+ o->x->mv->start_time = level_param(o, 2);+ o->x->mv->active = (fl & 2) != 0;+ o->x->mv->ang_speed = 0;+ o->x->mv->dir = o->x->mv->active ? 1 : 0;+ o->x->mv->prev_dir = 1;+ o->x->mv->pid = 0, o->x->mv->pdir = 1;+ o->x->mv->speed = level_param(o, 0);+ b->type = B_KINEMATIC;+ b->flags |= BF_NOROT;+ np_body_mass(b);+ np_body_set_rot(b, o->x->mv->base_rot);+ if (!(b->flags & BF_SPACE)) np_body_add(b);+ float t = 0, pos = level_param(o, 5);+ bool found = false;+ for (int i = 1; i < r->naux; i++) {+ V2 p = mv_point(o, i - 1), q = mv_point(o, i);+ float len = hypotf(q.x - p.x, q.y - p.y);+ t += len;+ if (!found && t >= pos) {+ o->x->mv->pid = (int16_t)(i - 1);+ float k = 1 - (t - pos) / len;+ b->pos = v2(p.x + k * (q.x - p.x), p.y + k * (q.y - p.y));+ mv_vel(o);+ found = true;+ }+ }+ b->vel = v2(0, 0), b->angvel = 0;+ np_body_moved(b);+}++static void mv_init(Obj *o) {+ const ObjRec *r = o->r;+ o->x->mv->base_rot = o->body->rot;+ float base = level_param(o, 0), ad = level_param(o, 1);+ if (ad > 0) {+ o->x->mv->min_speed = 0.05f * base;+ o->x->mv->accel = (base * base - o->x->mv->min_speed * o->x->mv->min_speed) / (2 * ad);+ }+ float t = 0;+ for (int i = 1; i < r->naux; i++) {+ V2 p = mv_point(o, i - 1), q = mv_point(o, i);+ t += hypotf(q.x - p.x, q.y - p.y);+ }+ o->x->mv->total = t;+ mv_restart(o);+}++static void mv_switch_on(Obj *o, int t) {+ int fl = o->r->flags;+ if (o->x->mv->active && (fl & 12)) return;+ o->x->mv->dir = (int8_t)(o->x->mv->dir + t);+ o->x->mv->active = o->x->mv->dir != 0;+ if (o->x->mv->active) mv_check_dir(o);+ else o->body->vel = v2(0, 0);+}++static void mv_switch_off(Obj *o, int t) {+ int fl = o->r->flags;+ if (fl & 12) {+ if (o->x->mv->dir != 0) return;+ o->x->mv->dir = (int8_t)(o->x->mv->dir + t);+ } else o->x->mv->dir = (int8_t)(o->x->mv->dir - t);+ o->x->mv->active = o->x->mv->dir != 0;+ if (o->x->mv->active) mv_check_dir(o);+ else o->body->vel = v2(0, 0);+}++static void mv_update(Obj *o, float dt) {+ Body *b = o->body;+ const ObjRec *r = o->r;+ int n = r->naux, fl = r->flags;+ float side_wait = level_param(o, 3), side_angle = level_param(o, 4), ad = level_param(o, 1);+ if (!o->x->mv->active) {+ b->vel = v2(0, 0);+ return;+ }+ if (o->x->mv->start_time > 0) {+ b->vel = v2(0, 0);+ o->x->mv->start_time -= dt;+ if (o->x->mv->start_time <= 0) {+ if (side_angle != 0 && o->x->mv->ang_speed != 0) {+ o->x->mv->ang_speed = 0;+ np_body_set_rot(b, o->x->mv->side_target);+ }+ } else if (side_angle != 0 && o->x->mv->ang_speed != 0) np_body_set_rot(b, b->rot + o->x->mv->ang_speed * dt);+ return;+ }+ if (o->x->mv->ttp > 0) {+ if (ad > 0) mv_accel_vel(o);+ } else {+ o->x->mv->pid = (int16_t)(o->x->mv->pid + o->x->mv->pdir);+ if (o->x->mv->pid == 0 || o->x->mv->pid == n - 1) {+ if (side_wait > 0) {+ o->x->mv->start_time = side_wait;+ if (side_angle != 0) {+ if (o->x->mv->pid == 0) o->x->mv->side_target = o->x->mv->base_rot, o->x->mv->ang_speed = -side_angle / side_wait;+ else o->x->mv->side_target = o->x->mv->base_rot + side_angle, o->x->mv->ang_speed = side_angle / side_wait;+ }+ }+ if (!(fl & 1)) o->x->mv->pdir = (int8_t)-o->x->mv->pdir;+ if (fl & 4) {+ o->x->mv->active = 0, o->x->mv->dir = 0;+ b->pos = mv_point(o, o->x->mv->pid);+ }+ } else if (o->x->mv->pid < 0 || o->x->mv->pid > n - 1) o->x->mv->pid = (int16_t)(o->x->mv->pdir > 0 ? 0 : n - 1);+ if (ad > 0) mv_accel_vel(o);+ else mv_vel(o);+ if (fl & 8) o->x->mv->active = 0;+ }+ b->vel = o->x->mv->active ? v2(o->x->mv->vx, o->x->mv->vy) : v2(0, 0);+ o->x->mv->ttp -= dt;+}++/* ---- activation ---- */++static void tnt_explode(Obj *o) {+ const ObjRec *r = o->r;+ if (o->body) np_body_remove(o->body);+ float imp = level_param(o, 0), count = level_param(o, 1), radius = level_param(o, 2);+ if (imp > 0 && count > 0) {+ float ang = 6.2831853f / count;+ for (int k = 0; k < (int)count; k++) {+ float a = k * ang;+ V2 d = v2(cosf(a), sinf(a));+ Body *b;+ int sb;+ float dist;+ if (np_raycast(v2(r->x, r->y), d, radius, &b, &sb, &dist) && b && b->type == B_DYNAMIC) {+ float m = imp * (radius - dist) / radius;+ np_apply_impulse(b, v2(m * d.x, m * d.y), v2(r->x + d.x * dist, r->y + d.y * dist));+ }+ }+ }+ o->active = 1;+ if (fx_in_camera(r->x, r->y, 256)) {+ fx_explosion(r->x, r->y, o);+ fx_shake();+ } else o->hidden = 1;+}++static void obj_activate(Obj *o, bool t) {+ const ObjRec *r = o->r;+ switch (r->type) {+ case O_SHAPER: {+ bool remove = !(r->flags & 1);+ if (remove) {+ o->hidden = 1;+ if (o->body) {+ body_cons(o->body, false, true);+ np_body_remove(o->body);+ }+ if (o->sbody >= 0) {+ sbodies[o->sbody].flags &= (uint8_t)~BF_SPACE;+ np_drop_static(o->sbody);+ }+ } else {+ if (o->body && !body_has_cons(o->body)) body_space(o->body, t);+ if (o->sbody >= 0) {+ if (t) sbodies[o->sbody].flags |= BF_SPACE;+ else {+ sbodies[o->sbody].flags &= (uint8_t)~BF_SPACE;+ np_drop_static(o->sbody);+ }+ }+ o->hidden = !t;+ }+ break;+ }+ case O_REMOVED:+ if (o->active) break;+ /* fall through */+ case O_DYN:+ if (t) {+ np_body_add(o->body);+ body_cons(o->body, true, false);+ } else {+ for (int i = 0; i < sp.ncons; i++) {+ Con *c = sp.cons[i];+ if (c->b1 == o->body || c->b2 == o->body) c->flags = (uint8_t)((c->flags & ~CF_ACTIVE) | 0x80);+ }+ np_body_remove(o->body);+ }+ break;+ case O_TNT:+ if (!o->active && t) tnt_explode(o);+ break;+ case O_MOTOR:+ if (!o->active && o->x->con[1]) {+ o->body->flags &= (uint8_t)~BF_NOROT;+ np_body_mass(o->body);+ np_wake(o->body);+ if (t) o->x->con[1]->flags |= CF_ACTIVE;+ else o->x->con[1]->flags &= (uint8_t)~CF_ACTIVE;+ o->t1 = level_param(o, 1);+ o->active = 1;+ }+ break;+ case O_MOVER:+ if (t) mv_switch_on(o, 1);+ else mv_switch_off(o, 1);+ break;+ case O_PIVOT:+ if (!o->active && o->x->con[0]) {+ o->x->con[0]->flags &= (uint8_t)~CF_ACTIVE;+ if (o->body) np_wake(o->body);+ if (o->body2) np_wake(o->body2);+ o->active = 1;+ }+ break;+ case O_DECOR:+ o->hidden = t;+ break;+ case O_GEYSER:+ case O_WATER:+ o->active = t;+ break;+ default: break;+ }+}++void level_activate(int id, bool on) {+ for (int i = 0; i < lv.nobj; i++) {+ Obj *o = &lv.objs[i];+ if (o->r->id == id && activatable(o)) obj_activate(o, on);+ }+}++/* ---- restart ---- */++static void obj_restart(Obj *o) {+ const ObjRec *r = o->r;+ switch (r->type) {+ case O_SHAPER:+ if (!(r->flags & 1)) {+ o->hidden = 0;+ if (o->body) {+ np_body_add(o->body);+ body_cons(o->body, true, true);+ }+ if (o->sbody >= 0) sbodies[o->sbody].flags |= BF_SPACE;+ } else if (r->id >= 0) obj_activate(o, false);+ if (o->body && o->body->type != B_STATIC) stop_reset(o);+ break;+ case O_PLANK:+ if (o->body) stop_reset(o);+ break;+ case O_REMOVED:+ o->t2 = 1, o->active = 0, o->alpha = 1, o->hidden = 0;+ np_body_add(o->body);+ /* fall through */+ case O_DYN:+ stop_reset(o);+ if (r->flags & 1) obj_activate(o, false);+ break;+ case O_TNT:+ if (o->body) {+ stop_reset(o);+ np_body_add(o->body);+ }+ o->active = 0, o->hidden = 0;+ break;+ case O_TOGGLE:+ o->active = 0, o->sens = 0;+ sbodies[o->sbody].flags |= BF_SPACE;+ break;+ case O_SAFE:+ o->active = 0, o->t1 = 0;+ break;+ case O_MOTOR:+ if (o->x->con[0]) {+ np_con_clear(o->x->con[0]), np_con_clear(o->x->con[1]);+ o->x->con[1]->flags &= (uint8_t)~CF_ACTIVE;+ o->body->flags |= BF_NOROT;+ o->body->angvel = 0;+ np_body_mass(o->body);+ }+ o->active = 0, o->t2 = 0;+ break;+ case O_MOVER:+ mv_restart(o);+ break;+ case O_PIVOT:+ if (o->x->con[0]) {+ np_con_clear(o->x->con[0]);+ if (!(o->x->con[0]->flags & 0x80)) o->x->con[0]->flags |= CF_ACTIVE;+ }+ o->active = 0;+ break;+ case O_GEYSER:+ if (r->id >= 0) o->active = 0;+ else o->active = 1;+ break;+ case O_BOOST:+ o->active = 0, o->hidden = 0;+ sbodies[o->sbody].flags |= BF_SPACE;+ break;+ case O_GLASS:+ o->t1 = 0, o->active = 0, o->hidden = 0, o->alpha = 1;+ sbodies[o->sbody].flags |= BF_SPACE;+ break;+ default: break;+ }+}++static bool obj_reviewed(const Obj *o) {+ switch (o->r->type) {+ case O_SHAPER: case O_PLANK: case O_DYN: case O_REMOVED: case O_TNT: case O_TOGGLE: case O_MOTOR: case O_MOVER:+ case O_PIVOT: case O_GEYSER: case O_BOOST: case O_GLASS:+ return true;+ default:+ return false;+ }+}++void level_restart(void) {+ for (int i = 0; i < lv.nobj; i++) {+ Obj *o = &lv.objs[i];+ if (o->r->type == O_MOVER && !o->x->mv->total) mv_init(o);+ obj_restart(o);+ }+ fx_clear();+}++void level_review(void) {+ for (int i = 0; i < lv.nobj; i++) {+ Obj *o = &lv.objs[i];+ if (!obj_reviewed(o)) continue;+ if (o->r->type == O_SHAPER && (o->r->flags & 2) && o->body && o->body->type == B_KINEMATIC) continue;+ obj_restart(o);+ }+}++/* the first time: MaxGameCore.initialDeactivate (objects not active at the start) */+void level_start(void);+void level_start(void) {+ for (int i = 0; i < lv.nobj; i++) {+ Obj *o = &lv.objs[i];+ if (o->r->type == O_MOVER) mv_init(o);+ if (o->r->type == O_REMOVED) o->t2 = 1, o->alpha = 1;+ if ((o->r->type == O_DYN || o->r->type == O_REMOVED) && (o->r->flags & 1)) obj_activate(o, false);+ if (o->r->type == O_GEYSER) o->active = o->r->id < 0;+ }+}++/* ---- each game tick ---- */++void level_update(float dt) {+ for (int i = 0; i < lv.nobj; i++) {+ Obj *o = &lv.objs[i];+ switch (o->r->type) {+ case O_REMOVED:+ if (o->active) {+ if (o->t1 > 0) {+ o->t1 -= dt;+ if (o->t1 <= 0) {+ np_body_remove(o->body);+ o->hidden = 1;+ } else if (o->t1 < 0.5f) o->alpha = o->t1 / 0.5f;+ }+ } else if (o->t2 > 0) o->t2 -= dt;+ else if (o->body->flags & BF_SPACE) {+ float v = hypotf(o->body->vel.x, o->body->vel.y);+ if (v > 100) o->active = 1, o->t1 = 1;+ }+ break;+ case O_MOTOR:+ if (o->x->con[1] && o->active && o->t1 > 0) {+ o->x->grot += dt * o->x->con[1]->rate;+ o->t1 -= dt;+ if (o->t1 <= 0) {+ o->x->con[1]->flags &= (uint8_t)~CF_ACTIVE;+ o->body->angvel = 0;+ o->body->flags |= BF_NOROT;+ np_body_mass(o->body);+ }+ }+ if (o->x->con[0] && o->body2) {+ V2 p = np_local_to_world(o->body, o->x->con[0]->a2);+ o->x->gx = p.x, o->x->gy = p.y;+ }+ break;+ case O_MOVER:+ mv_update(o, dt);+ break;+ case O_PIVOT:+ if (o->x->con[0] && o->body2) {+ V2 p = np_local_to_world(o->body2, o->x->con[0]->a2);+ o->x->gx = p.x, o->x->gy = p.y;+ } else o->x->gx = o->r->x, o->x->gy = o->r->y;+ break;+ case O_SAFE:+ if (o->active && o->t1 < 1) o->t1 += dt;+ break;+ case O_GLASS:+ if (o->t1 > 0) {+ o->t1 -= dt;+ if (o->t1 <= 0) {+ sbodies[o->sbody].flags &= (uint8_t)~BF_SPACE;+ np_drop_static(o->sbody);+ o->hidden = 1;+ fx_glass(o);+ }+ }+ break;+ default: break;+ }+ }+}++/* ---- the space's events (MaxPhysics listeners) ---- */++static Obj *obj_of_static(int sb, int type) {+ for (int i = 0; i < lv.nobj; i++)+ if (lv.objs[i].sbody == sb && (type < 0 || lv.objs[i].r->type == type)) return &lv.objs[i];+ return 0;+}++static void toggle_sens(Obj *o, bool begin, bool dead) {+ const ObjRec *r = o->r;+ bool off = r->flags & 1;+ if (!begin) {+ if (--o->sens <= 0) level_activate(r->id, false);+ return;+ }+ if (!dead) {+ if (r->id >= 0) {+ level_activate(r->id, true);+ if (!off) {+ sbodies[o->sbody].flags &= (uint8_t)~BF_SPACE;+ np_drop_static(o->sbody);+ }+ o->sens++;+ }+ if (r->id2 >= 0) {+ level_activate(r->id2, false);+ if (!off) {+ sbodies[o->sbody].flags &= (uint8_t)~BF_SPACE;+ np_drop_static(o->sbody);+ }+ }+ }+ o->active = 1;+}++static void handle(const Event *e, Body *b, int sb, Body *ob, int osb) {+ /* b: the bike's (or a level object's) body; ob/osb: the other side */+ uint16_t cb = b ? b->cb : 0;+ uint16_t ocb = ob ? ob->cb : osb >= 0 ? sbodies[osb].cb : 0;+ (void)sb;+ bool car = cb & (CB_WHEEL | CB_BODY), driver = cb & CB_DRIVER, part = cb & CB_PART;+ if (e->type == A_SENSOR) {+ if (!e->begin) {+ if (car && (ocb & CB_TOGGLE_OFF) && osb >= 0) {+ Obj *o = obj_of_static(osb, O_TOGGLE);+ if (o) toggle_sens(o, false, false);+ }+ return;+ }+ if (car && (ocb & CB_TOGGLE) && osb >= 0) {+ Obj *o = obj_of_static(osb, O_TOGGLE);+ if (o && (sbodies[osb].flags & BF_SPACE)) toggle_sens(o, true, bike.dead);+ }+ if ((car || part) && (ocb & CB_BOOST) && osb >= 0) {+ Obj *o = obj_of_static(osb, O_BOOST);+ if (o && !o->active) {+ o->active = 1, o->hidden = 1;+ sbodies[osb].flags &= (uint8_t)~BF_SPACE;+ np_drop_static(osb);+ bike_add_boost(level_param(o, 0), level_param(o, 1));+ }+ }+ if ((driver || part) && (ocb & CB_FINISH)) bike_finish();+ if ((driver || part) && (ocb & CB_SAFE) && osb >= 0 && !bike.dead) {+ Obj *o = obj_of_static(osb, O_SAFE);+ if (o) {+ bike.review_x = o->r->x, bike.review_y = o->r->y, bike.safe_id = o->r->id;+ if (!o->active) o->active = 1, o->t1 = 0;+ }+ }+ return;+ }+ if (e->type == A_FLUID) {+ if (e->begin && (driver || part) && (ocb & CB_WATER)) {+ bike_driver_ground();+ bike_explode();+ }+ return;+ }+ if (!e->begin) return;+ if ((car || driver || part) && (ocb & CB_GLASS) && osb >= 0) {+ Obj *o = obj_of_static(osb, O_GLASS);+ if (o && !o->active) {+ o->active = 1;+ o->x->gx = e->px, o->x->gy = e->py;+ o->t1 = level_param(o, 0);+ if (o->t1 <= 0) o->t1 = 0.0001f;+ }+ }+ if (driver && (ocb & CB_GROUND)) {+ bike_driver_ground();+ bike_explode();+ }+ if (car && (ocb & (CB_SPIKES | CB_SAW))) {+ bike_driver_ground();+ bike_explode();+ }+ if ((driver || part) && (ocb & CB_SPIKES)) {+ bike_driver_ground();+ bike_spikes(b);+ }+ if ((driver || part) && (ocb & CB_SAW)) {+ bike_spikes(0);+ bike_driver_ground();+ bike_explode();+ }+}++void level_events(void) {+ for (int i = 0; i < sp.nevents; i++) {+ const Event *e = &sp.events[i];+ if (e->b1 && bike_owns(e->b1)) handle(e, e->b1, e->sb1, e->b2, e->sb2);+ if (e->b2 && bike_owns(e->b2)) handle(e, e->b2, e->sb2, e->b1, e->sb1);+ }+ sp.nevents = 0;+ /* geysers push while touching (ONGOING) */+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ const Arb *a = &sp.arbs[i];+ if (!a->used || a->type != A_SENSOR || a->up_stamp != sp.stamp) continue;+ int sb1 = a->s1 & 0x8000 ? -1 : sp.sshapes[a->s1].body, sb2 = a->s2 & 0x8000 ? -1 : sp.sshapes[a->s2].body;+ int gs = -1;+ Body *b = 0;+ if (sb2 >= 0 && (sbodies[sb2].cb & CB_GEYSER) && sb1 < 0) gs = sb2, b = a->b1;+ else if (sb1 >= 0 && (sbodies[sb1].cb & CB_GEYSER) && sb2 < 0) gs = sb1, b = a->b2;+ if (gs < 0 || !b) continue;+ int slot = bike_body_slot(b);+ if (slot < 0) continue;+ Obj *o = obj_of_static(gs, O_GEYSER);+ if (!o) continue;+ bike.eff_vx[slot] = level_param(o, 0), bike.eff_vy[slot] = level_param(o, 1);+ }+}++/* ---- camera paths (CameraPathes.getPathPointXY) ---- */++float level_cam_y(float x, float y, int *path) {+ const uint8_t *p = lvl_at(lv.h, L_CAMS);+ float best = NAN;+ int bi = -1;+ for (int k = 0; k < lv.h->ncams; k++) {+ const CamRec *c = (const CamRec *)(const void *)(p + 8 * k);+ const int16_t *q = lv.dpts + 2 * c->pts;+ float minx = q[0], maxx = q[2 * (c->n - 1)];+ if (x < minx || x > maxx) continue;+ for (int i = 1; i < c->n; i++) {+ float ax = q[2 * i], ay = q[2 * i + 1] + c->dy;+ if (ax >= x) {+ float rx = q[2 * i - 2], ry = q[2 * i - 1] + c->dy;+ float h = x - rx, ang = atan2f(ay - ry, ax - rx);+ float yy = ry + h * tanf(ang);+ if (!(yy < y) && (isnan(best) || yy < best)) best = yy, bi = k;+ break;+ }+ }+ }+ *path = bi;+ return best;+}diff --git a/games/motox3m/src/level.h b/games/motox3m/src/level.hnew file mode 100644index 00000000..58646af5--- /dev/null+++ b/games/motox3m/src/level.h@@ -0,0 +1,79 @@+/* Moto X3M: a level in play: its bodies in the physics, its objects and what they do (motox3m4.js: RaceBuilder,+ * ShaperObject, ToggleObject, MoverPatherObject, MotorObject, PivotObject, TntObject, RemovedBodyObjects, ...). */+#ifndef MX_LEVEL_H+#define MX_LEVEL_H+#include <stdbool.h>+#include "nape.h"+#include "res.h"++/* the game's callback types (tools/levels.py CB), and a flag for what counts as ground */+enum {+ CB_GROUND = 1, CB_SPIKES = 2, CB_SAW = 4, CB_FINISH = 8, CB_SAFE = 16, CB_TOGGLE = 32, CB_TOGGLE_OFF = 64,+ CB_GLASS = 128, CB_WATER = 256, CB_BOOST = 512, CB_GEYSER = 1024, CB_WHEEL = 2048, CB_BODY = 4096, CB_DRIVER = 8192,+ CB_PART = 16384+};+/* filters (tools/levels.py FILTERS) */+enum { FL_DEFAULT, FL_NOTHING, FL_SENSOR, FL_EARTH, FL_WHEEL, FL_PART, FL_GROUND, FL_PLAYER };++typedef struct {+ int8_t dir, prev_dir, pdir;+ uint8_t active;+ int16_t pid;+ float speed, ttp, ttp_total, vx, vy, start_time, ang_speed, side_target, min_speed, accel, total, base_rot;+} Mover;++/* what only joints, movers and glass need */+typedef struct {+ Con *con[2]; /* pivot, motor */+ Mover *mv;+ float gx, gy, grot; /* a picture's place (motor, pivot), where glass was hit */+} ObjExt;++typedef struct Obj {+ const ObjRec *r;+ Body *body, *body2;+ ObjExt *x;+ int16_t sbody;+ uint8_t active, hidden, sens, pad;+ float t1, t2, alpha; /* timers (each kind its own use) */+} Obj;++typedef struct {+ const LevelHdr *h;+ int n; /* 0-based */+ Obj *objs;+ int nobj;+ Body *dbodies; /* the level's dynamic and kinematic bodies */+ int ndbodies;+ const float *params, *aux;+ const DrawRec *draws;+ const int16_t *dpts;+ float wave; /* water's surface (it stays still in the game: its objects are never active) */+} Level;++extern Level lv;++#ifdef HOST+#define ARENA_SIZE 100000 /* (pointers are twice as big on a computer) */+#else+#define ARENA_SIZE 70000+#endif+bool level_load(int n);+/* hard restart: every object as at the start */+void level_restart(void);+/* back to the last safe point: every object that can is reset (MaxGameCore.restartFromSafePoint) */+void level_review(void);+void level_update(float dt);+/* MaxGameCore.activate */+void level_activate(int id, bool on);+/* after each physics step: the space's begin and end events */+void level_events(void);+float level_param(const Obj *o, int k);+static inline const float *obj_params(const Obj *o) { return lv.params + o->r->params; }+/* the camera paths: the lowest path point under x not above y, or NAN */+float level_cam_y(float x, float y, int *path);++/* memory for a level's bodies, shapes and constraints, and the bike's (bump allocated, reset each load) */+void *arena_alloc(int size);+extern int arena_used, arena_peak;+#endifdiff --git a/games/motox3m/src/main.c b/games/motox3m/src/main.cnew file mode 100644index 00000000..fbf939be--- /dev/null+++ b/games/motox3m/src/main.c@@ -0,0 +1,51 @@+/* Moto X3M for the NumWorks calculator.+ *+ * Inspired by Moto X3M by Madpuffers, not affiliated with them.+ * Made by Mason Chen as part of NumPlay. */+#include "game.h"+#include "gfx.h"+#include "plat.h"+#include "view.h"++#ifndef HOST+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Moto X3M";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;++uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */+uint32_t perf_max __attribute__((used));++int main(void) {+ /* the band drawn into lives on main's stack, leaving the app's RAM to the physics */+ uint16_t band[SCREEN_W * BAND];+ uint32_t visbuf[VIEW_VIS_BYTES / 4];+ float scrbuf[VIEW_SCR_FLOATS];+ gfx_init(band);+ view_init(visbuf, scrbuf);+ plat_begin();+ game_init();+ /* the game's ticks at 30 a second (GameplayState.DESIRED_FRAME_TIME), at most 3 a drawing (MAX_FRAME_TIME) */+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 100 a tick */+ while (g.running) {+ int n = 0;+ uint32_t now = plat_millis() * 3;+ while ((int32_t)(now - next) >= 0 && n < 3 && g.running) {+ game_tick(plat_keys());+ next += 100;+ n++;+ }+ if (!g.running) break;+ if ((int32_t)(now - next) > 300) next = now; /* far behind: do not rush */+ if (n) {+ uint32_t t0 = plat_millis();+ game_draw();+ uint32_t dt = plat_millis() - t0;+ if (dt > perf_max && perf_frames > 30) perf_max = dt;+ perf_frames++;+ } else {+ plat_sleep(1);+ }+ }+ save_write();+ return plat_end();+}+#endifdiff --git a/games/motox3m/src/nape.c b/games/motox3m/src/nape.cnew file mode 100644index 00000000..b7f35a90--- /dev/null+++ b/games/motox3m/src/nape.c@@ -0,0 +1,2104 @@+/* Moto X3M: the physics, ported from Nape 2's cx sources (zpp_nape/space/Space.cx, dynamics/Arbiter.cx,+ * geom/Collide.cx, the constraints, phys/Body.cx, shape/Polygon.cx) as the game sets it up: Space.step with 10+ * velocity and 10 position iterations, world drag 0.015, Nape's Config values. See nape.h. */+#include <math.h>+#include <string.h>+#include "nape.h"++Space sp;++#define EPS 1e-8f+#define FMAX 3.4e38f+#define SLOP 0.2f+#define EXPIRE 6+#define STATIC_FRICTION_THRESHOLD 2.0f+#define ELASTIC_THRESHOLD 20.0f+#define SLEEP_DELAY 60+#define LIN_SLEEP 0.2f+#define ANG_SLEEP 0.4f+#define BIAS_DYN 0.3f+#define BIAS_STATIC 0.6f+#define LIN_SLOP 0.1f+#define ANG_SLOP 1e-3f+#define ILL_COND 2e8f+#define DRAG 0.015f+#define TAU 6.28318530718f+#define VEL_ITER 10+#define POS_ITER 10++static Body world; /* every static body: at the origin, never turned */+static int16_t htab[256];+static int16_t hnext[NP_MAX_ARBS];++static inline float cross(float ax, float ay, float bx, float by) { return ax * by - ay * bx; }++static void delta_rot(Body *b, float dr) {+ b->rot += dr;+ if (dr * dr > 0.0001f) {+ b->axis.x = sinf(b->rot), b->axis.y = cosf(b->rot);+ } else {+ float d2 = dr * dr, p = 1 - 0.5f * d2, m = 1 - d2 * d2 / 8;+ float nx = (p * b->axis.x + dr * b->axis.y) * m;+ b->axis.y = (p * b->axis.y - dr * b->axis.x) * m;+ b->axis.x = nx;+ }+}++void np_body_set_rot(Body *b, float r) {+ b->rot = r;+ b->axis.x = sinf(r), b->axis.y = cosf(r);+}++void np_body_mass(Body *b) {+ float m = 0, in = 0, cx = 0, cy = 0;+ for (int i = 0; i < b->nshapes; i++) {+ Shape *s = &b->shapes[i];+ float sm = s->area * sp.mats[s->mat].density / 1000;+ m += sm;+ in += s->inertia * sm;+ cx += s->lcom.x * sm, cy += s->lcom.y * sm;+ }+ b->lcom = m ? v2(cx / m, cy / m) : v2(0, 0);+ bool dyn = b->type == B_DYNAMIC;+ b->mass = m;+ b->imass = dyn && !(b->flags & BF_NOMOVE) && m > 0 ? 1 / m : 0;+ b->iinertia = dyn && !(b->flags & BF_NOROT) && in > 0 ? 1 / in : 0;+}++void np_reset(void) {+ memset(&sp, 0, sizeof sp);+ memset(&world, 0, sizeof world);+ world.axis = v2(0, 1);+ world.type = B_STATIC;+ world.flags = BF_SPACE;+ for (int i = 0; i < NP_MAX_ARBS; i++) sp.arbs[i].next = (int16_t)(i + 1 < NP_MAX_ARBS ? i + 1 : -1);+ sp.free_arb = 0;+ for (int i = 0; i < 256; i++) htab[i] = -1;+}++/* ---- shapes as the narrow phase sees them ---- */++#define SV_MAX 48++typedef struct {+ uint16_t id;+ uint8_t type, n, flags, filter;+ const Material *mat;+ Body *body;+ int sbody; /* static body, or -1 */+ float radius;+ V2 wcom, lcom;+ const V2 *gv, *gn;+ const float *gp;+ float minx, miny, maxx, maxy;+ V2 vb[SV_MAX], nb[SV_MAX]; /* a static shape's, decoded */+ float pb[SV_MAX];+} SV;++static const float UNIT[4] = {0.25f, 0.5f, 1, 2};++static void edges(const V2 *v, int n, V2 *nrm, float *proj) {+ for (int i = 0; i < n; i++) {+ V2 u = v[i], w = v[i + 1 < n ? i + 1 : 0];+ float dx = u.x - w.x, dy = u.y - w.y, l = sqrtf(dx * dx + dy * dy);+ if (l > 0) dx /= l, dy /= l;+ nrm[i] = v2(-dy, dx);+ proj[i] = -dy * u.x + dx * u.y;+ }+}++static void sview(uint16_t id, SV *v) {+ v->id = id;+ if (id & 0x8000) {+ Shape *s = sp.shapes[id & 0x7FFF];+ v->type = s->type, v->n = s->n, v->flags = s->flags, v->filter = s->filter;+ v->mat = &sp.mats[s->mat], v->body = s->body, v->sbody = -1;+ v->radius = s->radius, v->wcom = s->wcom, v->lcom = s->lcom;+ v->gv = (const V2 *)(const void *)s->glob, v->gn = (const V2 *)(const void *)(s->glob + 2 * s->n);+ v->gp = s->glob + 4 * s->n;+ v->minx = s->minx, v->miny = s->miny, v->maxx = s->maxx, v->maxy = s->maxy;+ } else {+ const SShape *s = &sp.sshapes[id];+ const int16_t *q = sp.sverts + 2 * s->voff;+ float k = UNIT[(s->flags >> 4) & 3];+ v->type = SH_POLY, v->n = s->n, v->flags = s->flags & 15, v->filter = s->filter;+ v->mat = &sp.mats[s->mat], v->body = &world, v->sbody = s->body;+ v->radius = 0;+ for (int i = 0; i < s->n; i++) v->vb[i] = v2(s->x0 + q[2 * i] * k, s->y0 + q[2 * i + 1] * k);+ edges(v->vb, s->n, v->nb, v->pb);+ v->gv = v->vb, v->gn = v->nb, v->gp = v->pb;+ v->minx = s->x0, v->miny = s->y0, v->maxx = s->x0 + s->w, v->maxy = s->y0 + s->h;+ }+}++/* a face's normal and projection in its body's own coordinates (for the position iterations) */+static void local_face(const SV *p, int e, V2 *ln, float *lp) {+ const Body *b = p->body;+ V2 g = p->gn[e];+ *ln = v2(g.x * b->axis.y + g.y * b->axis.x, g.y * b->axis.y - g.x * b->axis.x);+ *lp = p->gp[e] - (g.x * b->pos.x + g.y * b->pos.y);+}++static void shape_world(Shape *s) {+ Body *b = s->body;+ s->wcom = np_local_to_world(b, s->lcom);+ if (s->type == SH_CIRCLE) {+ s->minx = s->wcom.x - s->radius, s->maxx = s->wcom.x + s->radius;+ s->miny = s->wcom.y - s->radius, s->maxy = s->wcom.y + s->radius;+ return;+ }+ float mnx = FMAX, mny = FMAX, mxx = -FMAX, mxy = -FMAX;+ const V2 *lv = (const V2 *)(const void *)s->loc;+ V2 *gv = (V2 *)(void *)s->glob;+ for (int i = 0; i < s->n; i++) {+ V2 g = np_local_to_world(b, lv[i]);+ gv[i] = g;+ if (g.x < mnx) mnx = g.x;+ if (g.x > mxx) mxx = g.x;+ if (g.y < mny) mny = g.y;+ if (g.y > mxy) mxy = g.y;+ }+ edges(gv, s->n, (V2 *)(void *)(s->glob + 2 * s->n), s->glob + 4 * s->n);+ s->minx = mnx, s->miny = mny, s->maxx = mxx, s->maxy = mxy;+}++static void body_world(Body *b) {+ b->minx = b->miny = FMAX, b->maxx = b->maxy = -FMAX;+ for (int i = 0; i < b->nshapes; i++) {+ Shape *s = &b->shapes[i];+ shape_world(s);+ if (s->minx < b->minx) b->minx = s->minx;+ if (s->miny < b->miny) b->miny = s->miny;+ if (s->maxx > b->maxx) b->maxx = s->maxx;+ if (s->maxy > b->maxy) b->maxy = s->maxy;+ }+}++/* ---- arbiters ---- */++static inline unsigned hkey(uint16_t a, uint16_t b) {+ if (a > b) { uint16_t t = a; a = b; b = t; }+ return ((unsigned)a * 31u + b * 7u) & 255u;+}++static Arb *arb_find(uint16_t a, uint16_t b) {+ for (int i = htab[hkey(a, b)]; i >= 0; i = hnext[i]) {+ Arb *r = &sp.arbs[i];+ if ((r->s1 == a && r->s2 == b) || (r->s1 == b && r->s2 == a)) return r;+ }+ return 0;+}++static void arb_free(Arb *r);+static Body *shape_body(uint16_t id);++/* all slots in use: a contact of the bike's takes a level object's (the least useful one) */+static bool arb_evict(void) {+ int best = -1, score = -1;+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ Arb *r = &sp.arbs[i];+ if (!r->used || r->present || (r->b1->flags & BF_KEEP) || (r->b2->flags & BF_KEEP)) continue;+ int sc = r->up_stamp != sp.stamp ? 3 : r->type == A_SENSOR ? 2 : r->b1->type != B_DYNAMIC || r->b2->type != B_DYNAMIC ? 0 : 1;+ if (sc > score) score = sc, best = i;+ if (sc == 3) break;+ }+ if (best < 0) return false;+ arb_free(&sp.arbs[best]);+ return true;+}++static Arb *arb_new(uint16_t a, uint16_t b) {+ if (sp.free_arb < 0) {+ sp.overflow = true;+ Body *ba = shape_body(a), *bb = shape_body(b);+ if (!((ba->flags | bb->flags) & BF_KEEP) || !arb_evict()) return 0;+ }+ int i = sp.free_arb;+ Arb *r = &sp.arbs[i];+ sp.free_arb = r->next;+ memset(r, 0, sizeof *r);+ r->used = 1;+ r->s1 = a, r->s2 = b;+ r->c1 = r->c2 = -1;+ unsigned h = hkey(a, b);+ hnext[i] = htab[h];+ htab[h] = (int16_t)i;+ return r;+}++static void arb_free(Arb *r) {+ int i = (int)(r - sp.arbs);+ unsigned h = hkey(r->s1, r->s2);+ int16_t *p = &htab[h];+ while (*p >= 0 && *p != i) p = &hnext[*p];+ if (*p == i) *p = hnext[i];+ r->used = 0;+ r->next = sp.free_arb;+ sp.free_arb = (int16_t)i;+}++static int sbody_of(uint16_t id) { return id & 0x8000 ? -1 : sp.sshapes[id].body; }+static Body *shape_body(uint16_t id) { return id & 0x8000 ? sp.shapes[id & 0x7FFF]->body : &world; }+static const Material *shape_mat(uint16_t id) {+ return &sp.mats[id & 0x8000 ? sp.shapes[id & 0x7FFF]->mat : sp.sshapes[id].mat];+}++static void push_event(bool begin, const Arb *a) {+ if (sp.nevents >= NP_MAX_EVENTS) return;+ Event *e = &sp.events[sp.nevents++];+ e->begin = begin, e->type = a->type;+ e->sb1 = sbody_of(a->s1), e->sb2 = sbody_of(a->s2);+ e->b1 = e->sb1 < 0 ? a->b1 : 0;+ e->b2 = e->sb2 < 0 ? a->b2 : 0;+ e->px = e->py = 0;+ if (a->type == A_COL && a->nc) {+ const Contact *c = &a->c[a->c1 >= 0 ? a->c1 : 0];+ e->px = c->r1x + a->b1->pos.x, e->py = c->r1y + a->b1->pos.y;+ }+}++/* the same two bodies (static ones by their own index) */+static bool same_pair(const Arb *a, const Arb *b) {+ int a1 = sbody_of(a->s1), a2 = sbody_of(a->s2), b1 = sbody_of(b->s1), b2 = sbody_of(b->s2);+ const void *pa1 = a1 < 0 ? (const void *)a->b1 : 0, *pa2 = a2 < 0 ? (const void *)a->b2 : 0;+ const void *pb1 = b1 < 0 ? (const void *)b->b1 : 0, *pb2 = b2 < 0 ? (const void *)b->b2 : 0;+ return (pa1 == pb1 && a1 == b1 && pa2 == pb2 && a2 == b2) || (pa1 == pb2 && a1 == b2 && pa2 == pb1 && a2 == b1);+}++static bool pair_present(const Arb *a) {+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ const Arb *o = &sp.arbs[i];+ if (o != a && o->used && o->present && o->type == a->type && same_pair(o, a)) return true;+ }+ return false;+}++static void arb_retire(Arb *a, bool events) {+ if (a->present) {+ a->present = 0;+ if (events && !pair_present(a)) push_event(false, a);+ }+ arb_free(a);+}++void np_drop_body(Body *b) {+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ Arb *a = &sp.arbs[i];+ if (a->used && (a->b1 == b || a->b2 == b)) arb_retire(a, true);+ }+}++void np_drop_static(int sb) {+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ Arb *a = &sp.arbs[i];+ if (a->used && (sbody_of(a->s1) == sb || sbody_of(a->s2) == sb)) arb_retire(a, true);+ }+}++Body *np_world(void) { return &world; }++void np_drop_shape(Shape *s) {+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ Arb *a = &sp.arbs[i];+ if (!a->used) continue;+ uint16_t id1 = a->s1, id2 = a->s2;+ if (((id1 & 0x8000) && sp.shapes[id1 & 0x7FFF] == s) || ((id2 & 0x8000) && sp.shapes[id2 & 0x7FFF] == s))+ arb_retire(a, true);+ }+}++static Contact *inject(Arb *a, float px, float py, float nx, float ny, float dist, int hash, bool posonly) {+ Contact *c = 0;+ for (int i = 0; i < a->nc; i++)+ if (a->c[i].hash == hash) { c = &a->c[i]; break; }+ if (!c) {+ if (a->nc >= 2) return &a->c[0];+ c = &a->c[a->nc++];+ memset(c, 0, sizeof *c);+ c->hash = (uint8_t)hash;+ c->fresh = 1;+ a->jr = 0;+ } else c->fresh = 0;+ c->r1x = px - a->b1->pos.x, c->r1y = py - a->b1->pos.y;+ c->r2x = px - a->b2->pos.x, c->r2y = py - a->b2->pos.y;+ a->n = v2(nx, ny);+ c->dist = dist;+ c->stamp = sp.stamp;+ c->posonly = posonly;+ return c;+}++static Contact *circle_query(Arb *a, V2 p1, V2 p2, float r1, float r2, bool rev, int hash) {+ float min = r1 + r2, px = p2.x - p1.x, py = p2.y - p1.y, d2 = px * px + py * py;+ if (d2 > min * min) return 0;+ if (d2 < EPS * EPS) return inject(a, p1.x, p1.y, 1, 0, -min, hash, false);+ float inv = 1 / sqrtf(d2), dist = inv < EPS ? FMAX : 1 / inv, df = 0.5f + (r1 - 0.5f * min) * inv;+ if (rev) return inject(a, p1.x + px * df, p1.y + py * df, -px * inv, -py * inv, dist - min, hash, false);+ return inject(a, p1.x + px * df, p1.y + py * df, px * inv, py * inv, dist - min, hash, false);+}++static inline V2 revrot(V2 a, V2 axis) { return v2(a.x * axis.y + a.y * axis.x, a.y * axis.y - a.x * axis.x); }++static bool circle2circle(const SV *c1, const SV *c2, Arb *a, bool rev) {+ Contact *c = circle_query(a, c1->wcom, c2->wcom, c1->radius, c2->radius, rev, 0);+ if (!c) return false;+ if (rev) c->lr1x = c2->lcom.x, c->lr1y = c2->lcom.y, c->lr2x = c1->lcom.x, c->lr2y = c1->lcom.y;+ else c->lr1x = c1->lcom.x, c->lr1y = c1->lcom.y, c->lr2x = c2->lcom.x, c->lr2y = c2->lcom.y;+ a->radius = c1->radius + c2->radius;+ a->ptype = PT_CIRCLE;+ return true;+}++static bool circle2poly(const SV *c, const SV *p, Arb *a, bool rev) {+ float max = -FMAX;+ int a0 = -1;+ for (int i = 0; i < p->n; i++) {+ float d = p->gn[i].x * c->wcom.x + p->gn[i].y * c->wcom.y - p->gp[i] - c->radius;+ if (d > 0) return false;+ if (d > max) max = d, a0 = i;+ }+ V2 v0 = p->gv[a0], v1 = p->gv[a0 + 1 < p->n ? a0 + 1 : 0], g = p->gn[a0];+ float dt = cross(g.x, g.y, c->wcom.x, c->wcom.y);+ for (int k = 0; k < 2; k++) {+ V2 vv = k ? v1 : v0;+ bool hit = k ? dt >= cross(g.x, g.y, v1.x, v1.y) : dt <= cross(g.x, g.y, v0.x, v0.y);+ if (!hit) continue;+ Contact *co = circle_query(a, c->wcom, vv, c->radius, 0, rev, 0);+ if (co) {+ a->ptype = PT_CIRCLE;+ V2 l = revrot(v2(vv.x - p->body->pos.x, vv.y - p->body->pos.y), p->body->axis);+ if (rev) co->lr1x = l.x, co->lr1y = l.y, co->lr2x = c->lcom.x, co->lr2y = c->lcom.y;+ else co->lr2x = l.x, co->lr2y = l.y, co->lr1x = c->lcom.x, co->lr1y = c->lcom.y;+ a->radius = c->radius;+ }+ return co != 0;+ }+ float k = c->radius + max * 0.5f;+ float px = c->wcom.x - g.x * k, py = c->wcom.y - g.y * k;+ Contact *co = rev ? inject(a, px, py, g.x, g.y, max, 0, false) : inject(a, px, py, -g.x, -g.y, max, 0, false);+ a->ptype = rev ? PT_FACE1 : PT_FACE2;+ local_face(p, a0, &a->lnorm, &a->lproj);+ a->rev = !rev;+ a->radius = c->radius;+ co->lr1x = c->lcom.x, co->lr1y = c->lcom.y;+ return true;+}++static bool poly2poly(const SV *p1, const SV *p2, Arb *a, bool rev) {+ float max = -FMAX;+ int maxi = -1, ax1 = -1, ax2 = -1;+ for (int pass = 0; pass < 2; pass++) {+ const SV *pa = pass ? p2 : p1, *pb = pass ? p1 : p2;+ for (int e = 0; e < pa->n; e++) {+ float min = FMAX, gx = pa->gn[e].x, gy = pa->gn[e].y, gp = pa->gp[e];+ for (int i = 0; i < pb->n; i++) {+ float k = gx * pb->gv[i].x + gy * pb->gv[i].y;+ if (k < min) min = k;+ if (min - gp <= max) break;+ }+ min -= gp;+ if (min >= 0) return false;+ if (min > max) {+ max = min;+ if (pass) ax2 = e; else ax1 = e;+ maxi = pass + 1;+ }+ }+ }+ const SV *q1, *q2;+ int ax;+ float scale;+ if (maxi == 1) q1 = p1, q2 = p2, ax = ax1, scale = 1;+ else q1 = p2, q2 = p1, ax = ax2, scale = -1;+ V2 g = q1->gn[ax];+ float gproj = q1->gp[ax];+ int n1 = q1->n;+ V2 g0 = q1->gv[ax], g1 = q1->gv[ax + 1 < n1 ? ax + 1 : 0];+ float tp0 = cross(g.x, g.y, g0.x, g0.y), tp1 = cross(g.x, g.y, g1.x, g1.y);+ int ay = 0;+ float min = FMAX;+ for (int e = 0; e < q2->n; e++) {+ float k = g.x * q2->gn[e].x + g.y * q2->gn[e].y;+ if (k < min) min = k, ay = e;+ }+ V2 c0 = q2->gv[ay], c1 = q2->gv[ay + 1 < q2->n ? ay + 1 : 0];+ float dvx = c1.x - c0.x, dvy = c1.y - c0.y;+ float d0 = cross(c0.x, c0.y, g.x, g.y), d1 = cross(c1.x, c1.y, g.x, g.y), den = 1 / (d1 - d0);+ float t = (-tp1 - d0) * den;+ if (t > EPS) c0.x += dvx * t, c0.y += dvy * t;+ t = (-tp0 - d1) * den;+ if (t < -EPS) c1.x += dvx * t, c1.y += dvy * t;+ float nx = g.x * scale, ny = g.y * scale;+ local_face(q1, ax, &a->lnorm, &a->lproj);+ a->radius = 0;+ a->rev = rev != (scale == -1);+ a->ptype = a->rev ? PT_FACE2 : PT_FACE1;+ float c0d = c0.x * g.x + c0.y * g.y - gproj, c1d = c1.x * g.x + c1.y * g.y - gproj;+ if (c0d > 0 && c1d > 0) return false;+ if (rev) nx = -nx, ny = -ny;+ Body *qb = q2->body;+ Contact *con = inject(a, c0.x - g.x * c0d * 0.5f, c0.y - g.y * c0d * 0.5f, nx, ny, c0d, a->rev ? 1 : 0, c0d > 0);+ V2 l = revrot(v2(c0.x - qb->pos.x, c0.y - qb->pos.y), qb->axis);+ con->lr1x = l.x, con->lr1y = l.y;+ con = inject(a, c1.x - g.x * c1d * 0.5f, c1.y - g.y * c1d * 0.5f, nx, ny, c1d, a->rev ? 0 : 1, c1d > 0);+ l = revrot(v2(c1.x - qb->pos.x, c1.y - qb->pos.y), qb->axis);+ con->lr1x = l.x, con->lr1y = l.y;+ return true;+}++static bool test_circle_poly(const SV *c, const SV *p) {+ float max = -FMAX;+ int a0 = -1;+ for (int i = 0; i < p->n; i++) {+ float d = p->gn[i].x * c->wcom.x + p->gn[i].y * c->wcom.y - p->gp[i] - c->radius;+ if (d > 0) return false;+ if (d > max) max = d, a0 = i;+ }+ V2 v0 = p->gv[a0], v1 = p->gv[a0 + 1 < p->n ? a0 + 1 : 0], g = p->gn[a0];+ float dt = cross(g.x, g.y, c->wcom.x, c->wcom.y);+ V2 v;+ if (dt <= cross(g.x, g.y, v0.x, v0.y)) v = v0;+ else if (dt >= cross(g.x, g.y, v1.x, v1.y)) v = v1;+ else return true;+ float dx = v.x - c->wcom.x, dy = v.y - c->wcom.y;+ return dx * dx + dy * dy <= c->radius * c->radius;+}++static bool test_collide(const SV *s1, const SV *s2) {+ if (s1->type == SH_CIRCLE && s2->type == SH_CIRCLE) {+ float dx = s2->wcom.x - s1->wcom.x, dy = s2->wcom.y - s1->wcom.y, r = s1->radius + s2->radius;+ return dx * dx + dy * dy <= r * r;+ }+ if (s1->type == SH_CIRCLE) return test_circle_poly(s1, s2);+ if (s2->type == SH_CIRCLE) return test_circle_poly(s2, s1);+ for (int pass = 0; pass < 2; pass++) {+ const SV *pa = pass ? s2 : s1, *pb = pass ? s1 : s2;+ for (int e = 0; e < pa->n; e++) {+ float min = FMAX;+ for (int i = 0; i < pb->n; i++) {+ float k = pa->gn[e].x * pb->gv[i].x + pa->gn[e].y * pb->gv[i].y;+ if (k < min) min = k;+ }+ if (min - pa->gp[e] > 0) return false;+ }+ }+ return true;+}++/* a constraint with ignore set between the two bodies (a static one by its index: sb) */+static bool ignored(const Body *b1, const Body *b2, int sb) {+ for (int i = 0; i < sp.ncons; i++) {+ const Con *c = sp.cons[i];+ if (!(c->flags & CF_IGNORE)) continue;+ if ((c->b1 == b1 && c->b2 == b2) || (c->b1 == b2 && c->b2 == b1)) {+ if (b1 != &world && b2 != &world) return true;+ if (c->sb == sb) return true;+ }+ }+ return false;+}++/* Space.interactionType: 2 sensor, 1 collision, -1 none */+static int itype(const SV *s1, const SV *s2) {+ const Body *b1 = s1->body, *b2 = s2->body;+ if (ignored(b1, b2, s1->sbody >= 0 ? s1->sbody : s2->sbody)) return -1;+ const Filter *f1 = &sp.filters[s1->filter], *f2 = &sp.filters[s2->filter];+ if ((s1->flags & SF_SENSOR) || (s2->flags & SF_SENSOR)) {+ if ((f1->sgroup & f2->smask) && (f2->sgroup & f1->smask)) return 2;+ }+ /* fluids: every filter flows (fluidGroup 1, fluidMask -1) */+ if (((s1->flags & SF_FLUID) || (s2->flags & SF_FLUID)) &&+ !(b1->imass == 0 && b2->imass == 0 && b1->iinertia == 0 && b2->iinertia == 0))+ return 0;+ if ((f1->cgroup & f2->cmask) && (f2->cgroup & f1->cmask) &&+ !(b1->imass == 0 && b2->imass == 0 && b1->iinertia == 0 && b2->iinertia == 0))+ return 1;+ return -1;+}++/* ---- fluids (water): the overlap's area and centre, by clipping (the game's water is static and convex) ---- */++static float soft_gamma(float freq, float damping, float dt, float *gamma, float *biascoef);++static int clip_poly(const V2 *in, int n, V2 nrm, float proj, V2 *out) {+ int m = 0;+ for (int i = 0; i < n; i++) {+ V2 a = in[i], b = in[(i + 1) % n];+ float da = nrm.x * a.x + nrm.y * a.y - proj, db = nrm.x * b.x + nrm.y * b.y - proj;+ if (da <= 0) out[m++] = a;+ if ((da < 0) != (db < 0) && da != db) {+ float t = da / (da - db);+ out[m++] = v2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);+ }+ }+ return m;+}++static bool flow_collide(const SV *s1, const SV *s2, Arb *a) {+ const SV *fl = s1->flags & SF_FLUID ? s1 : s2, *o = fl == s1 ? s2 : s1;+ if (fl->type != SH_POLY) return false;+ V2 buf[2][SV_MAX + 24];+ int n;+ if (o->type == SH_CIRCLE) {+ n = 16;+ for (int i = 0; i < n; i++) {+ float t = i * (TAU / 16);+ buf[0][i] = v2(o->wcom.x + o->radius * cosf(t), o->wcom.y + o->radius * sinf(t));+ }+ } else {+ n = o->n;+ for (int i = 0; i < n; i++) buf[0][i] = o->gv[i];+ }+ int cur = 0;+ for (int e = 0; e < fl->n && n > 0; e++) {+ n = clip_poly(buf[cur], n, fl->gn[e], fl->gp[e], buf[cur ^ 1]);+ cur ^= 1;+ if (n > SV_MAX + 16) n = SV_MAX + 16;+ }+ if (n < 3) return false;+ float area = 0, cx = 0, cy = 0;+ const V2 *p = buf[cur];+ for (int i = 0; i < n; i++) {+ V2 u = p[i], w = p[(i + 1) % n];+ float c = u.x * w.y - w.x * u.y;+ area += c;+ cx += (u.x + w.x) * c, cy += (u.y + w.y) * c;+ }+ if (area == 0) return false;+ cx /= 3 * area, cy /= 3 * area;+ area = fabsf(area) * 0.5f;+ if (area < 1e-4f) return false;+ a->f.overlap = area, a->f.cx = cx, a->f.cy = cy;+ return true;+}++/* Polygon.__validate_angDrag and Circle.__validate_angDrag */+static float ang_drag(const SV *v) {+ float dyn = v->mat->dyn;+ if (v->type == SH_CIRCLE) {+ float lc = v->lcom.x * v->lcom.x + v->lcom.y * v->lcom.y, r2 = v->radius * v->radius, skin = dyn * 2.5f;+ return ((lc + 2 * r2) * skin + 0.5f * 100 * 1.5f * lc) / (2 * (lc + 0.5f * r2));+ }+ const Shape *sh = (v->id & 0x8000) ? sp.shapes[v->id & 0x7FFF] : 0;+ float inertia = sh ? sh->inertia : 1;+ float acc = 0, perim = 0;+ const Body *b = v->body;+ for (int i = 0; i < v->n; i++) {+ /* in the body's own coordinates */+ V2 gu = v->gv[i], gw = v->gv[(i + 1) % v->n];+ V2 u = np_world_to_local(b, gu), w = np_world_to_local(b, gw);+ V2 ln;+ float lp;+ local_face(v, i, &ln, &lp);+ float dx = w.x - u.x, dy = w.y - u.y, len = sqrtf(dx * dx + dy * dy);+ perim += len;+ acc += len * 2.5f * dyn * lp * lp;+ float den = cross(ln.x, ln.y, dx, dy);+ float t = den != 0 ? -cross(ln.x, ln.y, u.x, u.y) / den : 2;+ if (t > 0) {+ float ta = t > 1 ? 1 : t, ccx = u.x + dx * ta, ccy = u.y + dy * ta;+ float da = cross(u.x, u.y, ln.x, ln.y), db = cross(ccx, ccy, ln.x, ln.y);+ if (db != da) acc += (db * db * db - da * da * da) / (3 * (db - da)) * ta * len * 100;+ }+ if (t < 1) {+ float tb = t < 0 ? 0 : t, ccx = u.x + dx * tb, ccy = u.y + dy * tb;+ float da = cross(ccx, ccy, ln.x, ln.y), db = cross(w.x, w.y, ln.x, ln.y);+ if (db != da) acc += (db * db * db - da * da * da) / (3 * (db - da)) * 0.5f * (1 - tb) * len * 100;+ }+ }+ return perim > 0 ? acc / (inertia * perim) : 0;+}++static float shape_area(const SV *v) {+ if (v->type == SH_CIRCLE) return 3.14159265f * v->radius * v->radius;+ const Shape *sh = (v->id & 0x8000) ? sp.shapes[v->id & 0x7FFF] : 0;+ if (sh) return sh->area;+ float a = 0;+ for (int i = 0; i < v->n; i++) {+ V2 u = v->gv[i], w = v->gv[(i + 1) % v->n];+ a += u.x * w.y - w.x * u.y;+ }+ return fabsf(a) * 0.5f;+}++static float lin_drag(const SV *other, float f, V2 n) {+ if (other->type == SH_CIRCLE) return -f * other->radius * 0.5f / (2 * other->radius * 3.14159265f);+ float bord = 0, acc = 0;+ for (int i = 0; i < other->n; i++) {+ V2 u = other->gv[i], w = other->gv[(i + 1) % other->n];+ float len = hypotf(w.x - u.x, w.y - u.y);+ bord += len;+ float fact = f * len * (other->gn[i].x * n.x + other->gn[i].y * n.y);+ if (fact > 0) fact *= -0.5f;+ acc -= fact * 0.5f * 0.5f;+ }+ return bord > 0 ? acc / bord : 0;+}++static void fluid_prestep(Arb *a, float dt) {+ Body *b1 = a->b1, *b2 = a->b2;+ SV s1, s2;+ sview(a->s1, &s1), sview(a->s2, &s2);+ a->f.r1x = a->f.cx - b1->pos.x, a->f.r1y = a->f.cy - b1->pos.y;+ a->f.r2x = a->f.cx - b2->pos.x, a->f.r2y = a->f.cy - b2->pos.y;+ bool f1 = s1.flags & SF_FLUID, f2 = s2.flags & SF_FLUID;+ const SBody *w1 = f1 ? &sp.sbodies[s1.sbody] : 0, *w2 = f2 ? &sp.sbodies[s2.sbody] : 0;+ float bx = 0, by = 0, g = 1;+ (void)g;+ if (f1) {+ float m = a->f.overlap * w1->density / 1000;+ bx -= sp.gravity.x * m, by -= sp.gravity.y * m;+ } else if (f2) {+ float m = a->f.overlap * w2->density / 1000;+ bx += sp.gravity.x * m, by += sp.gravity.y * m;+ }+ bx *= dt, by *= dt;+ if (b1->type == B_DYNAMIC) {+ b1->vel.x -= bx * b1->imass, b1->vel.y -= by * b1->imass;+ b1->angvel -= cross(a->f.r1x, a->f.r1y, bx, by) * b1->iinertia;+ }+ if (b2->type == B_DYNAMIC) {+ b2->vel.x += bx * b2->imass, b2->vel.y += by * b2->imass;+ b2->angvel += cross(a->f.r2x, a->f.r2y, bx, by) * b2->iinertia;+ }+ float v1 = f1 ? w1->viscosity : 0, v2v = f2 ? w2->viscosity : 0;+ if (v1 == 0 && v2v == 0) {+ a->f.nodrag = 1;+ a->f.dampx = a->f.dampy = a->f.adamp = 0;+ return;+ }+ a->f.nodrag = 0;+ float tv = 0, bc;+ if (f1) tv += v1 * ang_drag(&s2) * a->f.overlap / shape_area(&s2);+ if (f2) tv += v2v * ang_drag(&s1) * a->f.overlap / shape_area(&s1);+ if (tv != 0) {+ float is = b1->iinertia + b2->iinertia;+ a->f.wmass = is != 0 ? 1 / is : 0;+ tv *= 0.0004f;+ a->f.wmass *= soft_gamma(tv, 1, dt, &a->f.agamma, &bc);+ } else a->f.wmass = 0, a->f.agamma = 0;+ float vx = (b2->vel.x - a->f.r2y * b2->angvel) - (b1->vel.x - a->f.r1y * b2->angvel);+ float vy = (b2->vel.y + a->f.r2x * b2->angvel) - (b1->vel.y + a->f.r1x * b1->angvel);+ float l = vx * vx + vy * vy;+ if (l >= EPS * EPS) {+ l = 1 / sqrtf(l);+ a->f.nx = vx * l, a->f.ny = vy * l;+ }+ V2 n = v2(a->f.nx, a->f.ny);+ tv = 0;+ if (f1) tv += lin_drag(&s2, -v1 * a->f.overlap / shape_area(&s2), n);+ if (f2) tv += lin_drag(&s1, -v2v * a->f.overlap / shape_area(&s1), n);+ if (tv != 0) {+ float K[3], m = b1->imass + b2->imass;+ K[0] = m, K[1] = 0, K[2] = m;+ if (b1->iinertia != 0) {+ float X = a->f.r1x * b1->iinertia, Y = a->f.r1y * b1->iinertia;+ K[0] += Y * a->f.r1y, K[1] += -Y * a->f.r1x, K[2] += X * a->f.r1x;+ }+ if (b2->iinertia != 0) {+ float X = a->f.r2x * b2->iinertia, Y = a->f.r2y * b2->iinertia;+ K[0] += Y * a->f.r2y, K[1] += -Y * a->f.r2x, K[2] += X * a->f.r2x;+ }+ float det = K[0] * K[2] - K[1] * K[1];+ if (det != 0) {+ det = 1 / det;+ float t = K[2] * det;+ K[2] = K[0] * det, K[0] = t, K[1] *= -det;+ }+ float ig = soft_gamma(tv, 1, dt, &a->f.lgamma, &bc);+ a->f.vmass[0] = K[0] * ig, a->f.vmass[1] = K[1] * ig, a->f.vmass[2] = K[2] * ig;+ } else a->f.vmass[0] = a->f.vmass[1] = a->f.vmass[2] = 0, a->f.lgamma = 0;+}++static void fluid_warm(Arb *a) {+ Body *b1 = a->b1, *b2 = a->b2;+ float dx = a->f.dampx, dy = a->f.dampy;+ b1->vel.x -= dx * b1->imass, b1->vel.y -= dy * b1->imass;+ b2->vel.x += dx * b2->imass, b2->vel.y += dy * b2->imass;+ b1->angvel -= b1->iinertia * cross(a->f.r1x, a->f.r1y, dx, dy);+ b2->angvel += b2->iinertia * cross(a->f.r2x, a->f.r2y, dx, dy);+ b1->angvel -= a->f.adamp * b1->iinertia;+ b2->angvel += a->f.adamp * b2->iinertia;+}++static void fluid_vel(Arb *a) {+ if (a->f.nodrag) return;+ Body *b1 = a->b1, *b2 = a->b2;+ float w1 = b1->angvel, w2 = b2->angvel;+ float jx = (b1->vel.x - a->f.r1y * w1) - (b2->vel.x - a->f.r2y * w2);+ float jy = (b1->vel.y + a->f.r1x * w1) - (b2->vel.y + a->f.r2x * w2);+ float t = a->f.vmass[0] * jx + a->f.vmass[1] * jy;+ jy = a->f.vmass[1] * jx + a->f.vmass[2] * jy, jx = t;+ jx -= a->f.dampx * a->f.lgamma, jy -= a->f.dampy * a->f.lgamma;+ a->f.dampx += jx, a->f.dampy += jy;+ b1->vel.x -= jx * b1->imass, b1->vel.y -= jy * b1->imass;+ b2->vel.x += jx * b2->imass, b2->vel.y += jy * b2->imass;+ b1->angvel -= b1->iinertia * cross(a->f.r1x, a->f.r1y, jx, jy);+ b2->angvel += b2->iinertia * cross(a->f.r2x, a->f.r2y, jx, jy);+ float jd = (w1 - w2) * a->f.wmass - a->f.adamp * a->f.agamma;+ a->f.adamp += jd;+ b1->angvel -= jd * b1->iinertia;+ b2->angvel += jd * b2->iinertia;+}++static void wake_body(Body *b);++static void narrow(uint16_t id1, uint16_t id2, bool stat) {+ SV v1, v2_;+ sview(id1, &v1), sview(id2, &v2_);+ if (v1.maxx < v2_.minx || v2_.maxx < v1.minx || v1.maxy < v2_.miny || v2_.maxy < v1.miny) return;+ int it = itype(&v1, &v2_);+ if (it < 0) return;+ const SV *sa, *sb;+ if (v1.type > v2_.type) sa = &v2_, sb = &v1;+ else if (v1.type == v2_.type) {+ if (v1.id < v2_.id) sa = &v1, sb = &v2_;+ else sa = &v2_, sb = &v1;+ } else sa = &v1, sb = &v2_;+ bool rev = sa == &v2_;+ Arb *a = arb_find(id1, id2);+ int type = it == 2 ? A_SENSOR : it == 0 ? A_FLUID : A_COL;+ if (a && a->type != type) {+ arb_retire(a, true);+ a = 0;+ }+ bool first = !a;+ if (!first && a->stamp == sp.stamp) return;+ if (first) {+ a = arb_new(id1, id2);+ if (!a) return;+ a->type = (uint8_t)type;+ a->b1 = v1.body, a->b2 = v2_.body;+ } else if (type == A_COL) rev = sa->id != a->s1;+ a->stamp = sp.stamp;+ a->stat = stat;+ bool hit;+ if (type == A_SENSOR) hit = test_collide(sa, sb);+ else if (type == A_FLUID) hit = flow_collide(&v1, &v2_, a);+ else if (sb->type == SH_POLY) hit = sa->type == SH_POLY ? poly2poly(sa, sb, a, rev) : circle2poly(sa, sb, a, rev);+ else hit = circle2circle(sa, sb, a, rev);+ if (!hit) {+ if (first) arb_free(a);+ return;+ }+ a->fresh = first ? 1 : a->up_stamp < sp.stamp - 1;+ a->up_stamp = a->stamp;+ if (type != A_SENSOR) {+ if (a->b1->flags & BF_FROZEN) a->b1->flags &= (uint8_t)~BF_FROZEN;+ if (a->b2->flags & BF_FROZEN) a->b2->flags &= (uint8_t)~BF_FROZEN;+ if (a->b1->type == B_DYNAMIC && (a->b1->flags & BF_SLEEP)) wake_body(a->b1);+ if (a->b2->type == B_DYNAMIC && (a->b2->flags & BF_SLEEP)) wake_body(a->b2);+ }+}++/* ---- sleeping ---- */++static int16_t dsf_find(int i) {+ while (sp.bodies[i]->dsf != i) {+ int p = sp.bodies[i]->dsf;+ sp.bodies[i]->dsf = sp.bodies[p]->dsf;+ i = p;+ }+ return (int16_t)i;+}+static void dsf_union(int a, int b) {+ a = dsf_find(a), b = dsf_find(b);+ if (a != b) sp.bodies[b]->dsf = (int16_t)a;+}++static int body_index(const Body *b) { return b->idx; }++static void wake_body(Body *b) {+ /* the whole island wakes: everything joined to it by a constraint or touching it */+ static Body *queue[64];+ if (!(b->flags & BF_SLEEP)) return;+ int head = 0, tail = 0;+ b->flags &= (uint8_t)~BF_SLEEP;+ b->waket = sp.stamp;+ queue[tail++] = b;+ while (head < tail) {+ Body *w = queue[head++];+ for (int pass = 0; pass < 2; pass++) {+ int n = pass ? sp.ncons : NP_MAX_ARBS;+ for (int i = 0; i < n; i++) {+ Body *o;+ if (pass) {+ Con *c = sp.cons[i];+ if (!(c->flags & CF_ACTIVE)) continue;+ o = c->b1 == w ? c->b2 : c->b2 == w ? c->b1 : 0;+ } else {+ Arb *a = &sp.arbs[i];+ if (!a->used || a->type != A_COL) continue;+ o = a->b1 == w ? a->b2 : a->b2 == w ? a->b1 : 0;+ }+ if (!o || o->type != B_DYNAMIC || !(o->flags & BF_SLEEP)) continue;+ o->flags &= (uint8_t)~BF_SLEEP;+ o->waket = sp.stamp;+ if (tail < 64) queue[tail++] = o;+ }+ }+ if (head == tail) break;+ }+}++void np_wake(Body *b) {+ if (b->type == B_DYNAMIC) {+ if (b->flags & BF_SLEEP) wake_body(b);+ b->waket = sp.stamp;+ }+}++static bool at_rest(Body *b, float dt) {+ float lin = LIN_SLEEP * LIN_SLEEP;+ bool can = true;+ /* (Nape also checks how far it moved in the step; the velocities are enough here) */+ (void)dt;+ if (b->vel.x * b->vel.x + b->vel.y * b->vel.y > lin) can = false;+ else {+ float wx = b->maxx - b->minx, wy = b->maxy - b->miny, idl = wx * wx + wy * wy, ang = ANG_SLEEP * ANG_SLEEP;+ if (4 * b->angvel * b->angvel * idl > ang) can = false;+ }+ if (!can) b->waket = sp.stamp;+ return b->waket + SLEEP_DELAY < sp.stamp;+}++static void forests(float dt) {+ int n = sp.nbodies;+ for (int i = 0; i < n; i++) sp.bodies[i]->dsf = (int16_t)i;+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ Arb *a = &sp.arbs[i];+ if (!a->used || a->type != A_COL || a->up_stamp != sp.stamp) continue;+ if (a->b1->type == B_DYNAMIC && a->b2->type == B_DYNAMIC) dsf_union(body_index(a->b1), body_index(a->b2));+ }+ for (int i = 0; i < sp.ncons; i++) {+ Con *c = sp.cons[i];+ if (!(c->flags & CF_ACTIVE)) continue;+ if (!(c->b1->flags & BF_SPACE) || !(c->b2->flags & BF_SPACE)) continue;+ if (c->b1->type == B_DYNAMIC && c->b2->type == B_DYNAMIC) dsf_union(body_index(c->b1), body_index(c->b2));+ }+ /* an island sleeps when every body in it has rested long enough */+ static uint8_t awake[256];+ int m = n < 256 ? n : 256;+ memset(awake, 0, (size_t)m);+ for (int i = 0; i < m; i++) {+ Body *b = sp.bodies[i];+ if (b->type != B_DYNAMIC || !(b->flags & BF_SPACE) || (b->flags & BF_STILL)) continue;+ if (!at_rest(b, dt)) awake[dsf_find(i)] = 1;+ }+ for (int i = 0; i < m; i++) {+ Body *b = sp.bodies[i];+ if (b->type != B_DYNAMIC || !(b->flags & BF_SPACE) || (b->flags & BF_STILL)) continue;+ if (!awake[dsf_find(i)]) {+ b->flags |= BF_SLEEP;+ b->vel = v2(0, 0), b->angvel = 0;+ }+ }+}++/* ---- the step ---- */++static float pre_dt_space;++static bool arb_prestep(Arb *a, float dt) {+ /* two bodies at rest keep no contacts (Nape keeps them sleeping; here they are made again on waking) */+ bool r1 = a->b1->type != B_DYNAMIC || (a->b1->flags & BF_STILL), r2 = a->b2->type != B_DYNAMIC || (a->b2->flags & BF_STILL);+ if (r1 && r2 && a->type != A_SENSOR && !(a->b1->type == B_KINEMATIC || a->b2->type == B_KINEMATIC)) {+ arb_free(a);+ return false;+ }+ bool begcb = a->fresh, endcb = a->up_stamp == sp.stamp - 1;+ if (begcb) {+ if (!a->present) {+ if (!pair_present(a)) push_event(true, a);+ a->present = 1;+ }+ } else if (endcb && a->present) {+ a->present = 0;+ if (!pair_present(a)) push_event(false, a);+ }+ a->fresh = 0;+ if (a->up_stamp + (a->type == A_COL ? EXPIRE : 0) < sp.stamp) {+ arb_retire(a, true);+ return false;+ }+ a->active = a->up_stamp == sp.stamp;+ if (a->type == A_FLUID) {+ if (a->active) fluid_prestep(a, dt);+ return a->active;+ }+ if (a->type != A_COL) return a->active;+ Body *b1 = a->b1, *b2 = a->b2;+ /* materials, from the shapes */+ {+ const Material *m1 = shape_mat(a->s1), *m2 = shape_mat(a->s2);+ float r = (m1->elasticity + m2->elasticity) / 2;+ a->rest = r < 0 ? 0 : r > 1 ? 1 : r;+ a->dyn = sqrtf(m1->dyn * m2->dyn);+ a->stat_f = sqrtf(m1->stat * m2->stat);+ a->rfric = sqrtf(m1->rolling * m2->rolling);+ }+ if (!a->active) {+ /* cleanupContacts */+ int k = 0;+ for (int i = 0; i < a->nc; i++)+ if (a->c[i].stamp + EXPIRE >= sp.stamp) a->c[k++] = a->c[i];+ a->nc = (uint8_t)k;+ for (int i = 0; i < a->nc; i++) a->c[i].active = 0;+ return false;+ }+ float dtratio = 1; /* the game steps at a fixed 1/60 s */+ (void)dt;+ float ms = b1->imass + b2->imass;+ bool stat = b1->type != B_DYNAMIC || b2->type != B_DYNAMIC;+ a->biascoef = stat ? BIAS_STATIC : BIAS_DYN;+ int k = 0;+ for (int i = 0; i < a->nc; i++)+ if (a->c[i].stamp + EXPIRE >= sp.stamp) a->c[k++] = a->c[i];+ a->nc = (uint8_t)k;+ int c1 = -1, c2 = -1;+ bool fst = true;+ a->hc2 = 0;+ float nx = a->n.x, ny = a->n.y;+ for (int i = 0; i < a->nc; i++) {+ Contact *c = &a->c[i];+ c->active = c->stamp == sp.stamp;+ if (!c->active) continue;+ if (fst) fst = false, c1 = i;+ else a->hc2 = 1, c2 = i;+ float d2 = c->r2x * nx + c->r2y * ny, d1 = c->r1x * nx + c->r1y * ny;+ float kt = ms + b2->iinertia * d2 * d2 + b1->iinertia * d1 * d1;+ c->tmass = kt < EPS * EPS ? 0 : 1 / kt;+ float x2 = cross(c->r2x, c->r2y, nx, ny), x1 = cross(c->r1x, c->r1y, nx, ny);+ float nt = ms + b2->iinertia * x2 * x2 + b1->iinertia * x1 * x1;+ c->nmass = nt < EPS * EPS ? 0 : 1 / nt;+ float vrx = (b2->vel.x - c->r2y * b2->angvel) - (b1->vel.x - c->r1y * b1->angvel);+ float vry = (b2->vel.y + c->r2x * b2->angvel) - (b1->vel.y + c->r1x * b1->angvel);+ float vdot = nx * vrx + ny * vry;+ c->bounce = vdot * a->rest;+ if (c->bounce > -ELASTIC_THRESHOLD) c->bounce = 0;+ vdot = cross(nx, ny, vrx, vry);+ c->friction = vdot * vdot > STATIC_FRICTION_THRESHOLD * STATIC_FRICTION_THRESHOLD ? a->dyn : a->stat_f;+ c->jn *= dtratio, c->jt *= dtratio;+ }+ if (a->hc2) {+ a->hpc2 = 1;+ if (a->c[c1].posonly) {+ int t = c1; c1 = c2; c2 = t;+ a->hc2 = 0;+ } else if (a->c[c2].posonly) a->hc2 = 0;+ if (a->c[c1].posonly) fst = true;+ } else a->hpc2 = 0;+ a->jr *= dtratio;+ a->c1 = (int8_t)c1, a->c2 = (int8_t)c2;+ if (!fst) {+ Contact *c = &a->c[c1];+ a->rn1a = cross(c->r1x, c->r1y, nx, ny), a->rt1a = c->r1x * nx + c->r1y * ny;+ a->rn1b = cross(c->r2x, c->r2y, nx, ny), a->rt1b = c->r2x * nx + c->r2y * ny;+ }+ if (a->hc2) {+ Contact *c = &a->c[c2];+ a->rn2a = cross(c->r1x, c->r1y, nx, ny), a->rt2a = c->r1x * nx + c->r1y * ny;+ a->rn2b = cross(c->r2x, c->r2y, nx, ny), a->rt2b = c->r2x * nx + c->r2y * ny;+ float i1 = b1->iinertia, i2 = b2->iinertia;+ float ka = ms + i1 * a->rn1a * a->rn1a + i2 * a->rn1b * a->rn1b;+ float kb = ms + i1 * a->rn1a * a->rn2a + i2 * a->rn1b * a->rn2b;+ float kc = ms + i1 * a->rn2a * a->rn2a + i2 * a->rn2b * a->rn2b;+ float norm = ka * ka + 2 * kb * kb + kc * kc, det = ka * kc - kb * kb;+ if (norm < ILL_COND * det) {+ a->kk[0] = ka, a->kk[1] = kb, a->kk[2] = kc;+ det = 1 / det;+ a->km[0] = kc * det, a->km[1] = -kb * det, a->km[2] = ka * det;+ } else {+ a->hc2 = 0;+ if (a->c[c2].dist < a->c[c1].dist) { a->c1 = (int8_t)c2; a->c2 = (int8_t)c1; c1 = a->c1; }+ a->c[a->c2].active = 0;+ if (!fst) {+ Contact *c = &a->c[c1];+ a->rn1a = cross(c->r1x, c->r1y, nx, ny), a->rt1a = c->r1x * nx + c->r1y * ny;+ a->rn1b = cross(c->r2x, c->r2y, nx, ny), a->rt1b = c->r2x * nx + c->r2y * ny;+ }+ }+ }+ float rm = b1->iinertia + b2->iinertia;+ a->rmass = rm != 0 ? 1 / rm : 0;+ a->active = !fst;+ return a->active;+}++static inline void app_imp(Arb *a, const Contact *c, float jn, float jt) {+ Body *b1 = a->b1, *b2 = a->b2;+ float nx = a->n.x, ny = a->n.y;+ float jx = nx * jn - ny * jt, jy = ny * jn + nx * jt;+ b1->vel.x -= jx * b1->imass, b1->vel.y -= jy * b1->imass;+ b1->angvel -= b1->iinertia * cross(c->r1x, c->r1y, jx, jy);+ b2->vel.x += jx * b2->imass, b2->vel.y += jy * b2->imass;+ b2->angvel += b2->iinertia * cross(c->r2x, c->r2y, jx, jy);+}++static void arb_warm(Arb *a) {+ app_imp(a, &a->c[a->c1], a->c[a->c1].jn, a->c[a->c1].jt);+ if (a->hc2) app_imp(a, &a->c[a->c2], a->c[a->c2].jn, a->c[a->c2].jt);+ a->b2->angvel += a->jr * a->b2->iinertia;+ a->b1->angvel -= a->jr * a->b1->iinertia;+}++static void arb_vel(Arb *a) {+ Body *b1 = a->b1, *b2 = a->b2;+ float nx = a->n.x, ny = a->n.y, j, jmax, jold, cj;+ Contact *c1 = &a->c[a->c1], *c2 = a->hc2 ? &a->c[a->c2] : 0;+#define REL(c, vx, vy) \+ float vx = b2->vel.x - (c)->r2y * b2->angvel - (b1->vel.x - (c)->r1y * b1->angvel); \+ float vy = b2->vel.y + (c)->r2x * b2->angvel - (b1->vel.y + (c)->r1x * b1->angvel)+#define FRICTION(c, v1x, v1y, rta, rtb) \+ j = cross(nx, ny, v1x, v1y) * (c)->tmass; \+ jmax = (c)->friction * (c)->jn; jold = (c)->jt; \+ cj = jold - j; if (cj > jmax) cj = jmax; else if (cj < -jmax) cj = -jmax; \+ j = cj - jold; (c)->jt = cj; \+ { float jx = -ny * j, jy = nx * j; \+ b2->vel.x += jx * b2->imass; b2->vel.y += jy * b2->imass; \+ b1->vel.x -= jx * b1->imass; b1->vel.y -= jy * b1->imass; \+ b2->angvel += (rtb) * j * b2->iinertia; b1->angvel -= (rta) * j * b1->iinertia; }+ {+ REL(c1, v1x, v1y);+ FRICTION(c1, v1x, v1y, a->rt1a, a->rt1b);+ }+ if (c2) {+ {+ REL(c2, v2x, v2y);+ FRICTION(c2, v2x, v2y, a->rt2a, a->rt2b);+ }+ REL(c1, v1x, v1y);+ REL(c2, v2x, v2y);+ float ax = c1->jn, ay = c2->jn;+ float jnx = v1x * nx + v1y * ny + c1->bounce - (a->kk[0] * ax + a->kk[1] * ay);+ float jny = v2x * nx + v2y * ny + c2->bounce - (a->kk[1] * ax + a->kk[2] * ay);+ float xx = -(a->km[0] * jnx + a->km[1] * jny), xy = -(a->km[1] * jnx + a->km[2] * jny);+ if (xx >= 0 && xy >= 0) {+ jnx = xx - ax, jny = xy - ay;+ c1->jn = xx, c2->jn = xy;+ } else {+ xx = -c1->nmass * jnx;+ if (xx >= 0 && (a->kk[1] * xx + jny) >= 0) {+ jnx = xx - ax, jny = -ay;+ c1->jn = xx, c2->jn = 0;+ } else {+ xy = -c2->nmass * jny;+ if (xy >= 0 && (a->kk[1] * xy + jnx) >= 0) {+ jnx = -ax, jny = xy - ay;+ c1->jn = 0, c2->jn = xy;+ } else if (jnx >= 0 && jny >= 0) {+ jnx = -ax, jny = -ay;+ c1->jn = c2->jn = 0;+ } else jnx = jny = 0;+ }+ }+ j = jnx + jny;+ float jx = nx * j, jy = ny * j;+ b2->vel.x += jx * b2->imass, b2->vel.y += jy * b2->imass;+ b1->vel.x -= jx * b1->imass, b1->vel.y -= jy * b1->imass;+ b2->angvel += (a->rn1b * jnx + a->rn2b * jny) * b2->iinertia;+ b1->angvel -= (a->rn1a * jnx + a->rn2a * jny) * b1->iinertia;+ } else {+ if (a->radius != 0) {+ float dw = b2->angvel - b1->angvel;+ j = dw * a->rmass;+ jmax = a->rfric * c1->jn;+ jold = a->jr;+ a->jr -= j;+ if (a->jr > jmax) a->jr = jmax; else if (a->jr < -jmax) a->jr = -jmax;+ j = a->jr - jold;+ b2->angvel += j * b2->iinertia;+ b1->angvel -= j * b1->iinertia;+ }+ REL(c1, v1x, v1y);+ j = (c1->bounce + nx * v1x + ny * v1y) * c1->nmass;+ jold = c1->jn;+ cj = jold - j;+ if (cj < 0) cj = 0;+ j = cj - jold;+ c1->jn = cj;+ float jx = nx * j, jy = ny * j;+ b2->vel.x += jx * b2->imass, b2->vel.y += jy * b2->imass;+ b1->vel.x -= jx * b1->imass, b1->vel.y -= jy * b1->imass;+ b2->angvel += a->rn1b * j * b2->iinertia;+ b1->angvel -= a->rn1a * j * b1->iinertia;+ }+#undef REL+#undef FRICTION+}++static inline V2 rot_axis(float lx, float ly, V2 axis) { return v2(lx * axis.y - ly * axis.x, lx * axis.x + ly * axis.y); }++static void arb_pos(Arb *a) {+ Body *b1 = a->b1, *b2 = a->b2;+ float bc = a->biascoef;+ if (a->ptype == PT_CIRCLE) {+ Contact *c = &a->c[a->c1];+ V2 r2 = rot_axis(c->lr2x, c->lr2y, b2->axis);+ r2.x += b2->pos.x, r2.y += b2->pos.y;+ V2 r1 = rot_axis(c->lr1x, c->lr1y, b1->axis);+ r1.x += b1->pos.x, r1.y += b1->pos.y;+ float dx = r2.x - r1.x, dy = r2.y - r1.y, dl = sqrtf(dx * dx + dy * dy);+ float r = a->radius - SLOP, err = dl - r;+ if (dx * a->n.x + dy * a->n.y < 0) {+ dx = -dx, dy = -dy;+ err -= a->radius;+ }+ if (err < 0) {+ if (dl < EPS) {+ if (b1->imass != 0) b1->pos.x += EPS * 10;+ else b2->pos.x += EPS * 10;+ } else {+ dx /= dl, dy /= dl;+ float px = 0.5f * (r1.x + r2.x), py = 0.5f * (r1.y + r2.y), pen = dl - r;+ float q1x = px - b1->pos.x, q1y = py - b1->pos.y, q2x = px - b2->pos.x, q2y = py - b2->pos.y;+ float rn1 = cross(q1x, q1y, dx, dy), rn2 = cross(q2x, q2y, dx, dy);+ float K = b2->imass + rn2 * rn2 * b2->iinertia + b1->imass + rn1 * rn1 * b1->iinertia;+ if (K != 0) {+ float jn = -bc * pen / K, jx = dx * jn, jy = dy * jn;+ b1->pos.x -= jx * b1->imass, b1->pos.y -= jy * b1->imass;+ delta_rot(b1, -rn1 * b1->iinertia * jn);+ b2->pos.x += jx * b2->imass, b2->pos.y += jy * b2->imass;+ delta_rot(b2, rn2 * b2->iinertia * jn);+ }+ }+ }+ return;+ }+ V2 g;+ float gproj;+ V2 clip1, clip2 = {0, 0};+ Contact *c1 = &a->c[a->c1], *c2 = a->hpc2 && a->c2 >= 0 ? &a->c[a->c2] : 0;+ if (a->ptype == PT_FACE1) {+ g = rot_axis(a->lnorm.x, a->lnorm.y, b1->axis);+ gproj = a->lproj + g.x * b1->pos.x + g.y * b1->pos.y;+ clip1 = rot_axis(c1->lr1x, c1->lr1y, b2->axis);+ clip1.x += b2->pos.x, clip1.y += b2->pos.y;+ if (c2) {+ clip2 = rot_axis(c2->lr1x, c2->lr1y, b2->axis);+ clip2.x += b2->pos.x, clip2.y += b2->pos.y;+ }+ } else {+ g = rot_axis(a->lnorm.x, a->lnorm.y, b2->axis);+ gproj = a->lproj + g.x * b2->pos.x + g.y * b2->pos.y;+ clip1 = rot_axis(c1->lr1x, c1->lr1y, b1->axis);+ clip1.x += b1->pos.x, clip1.y += b1->pos.y;+ if (c2) {+ clip2 = rot_axis(c2->lr1x, c2->lr1y, b1->axis);+ clip2.x += b1->pos.x, clip2.y += b1->pos.y;+ }+ }+ float err1 = clip1.x * g.x + clip1.y * g.y - gproj - a->radius + SLOP, err2 = 0;+ if (c2) err2 = clip2.x * g.x + clip2.y * g.y - gproj - a->radius + SLOP;+ if (!(err1 < 0 || err2 < 0)) return;+ if (a->rev) g.x = -g.x, g.y = -g.y;+ float c1r1x = clip1.x - b1->pos.x, c1r1y = clip1.y - b1->pos.y;+ float c1r2x = clip1.x - b2->pos.x, c1r2y = clip1.y - b2->pos.y;+ if (c2) {+ float c2r1x = clip2.x - b1->pos.x, c2r1y = clip2.y - b1->pos.y;+ float c2r2x = clip2.x - b2->pos.x, c2r2y = clip2.y - b2->pos.y;+ float rn1a = cross(c1r1x, c1r1y, g.x, g.y), rn1b = cross(c1r2x, c1r2y, g.x, g.y);+ float rn2a = cross(c2r1x, c2r1y, g.x, g.y), rn2b = cross(c2r2x, c2r2y, g.x, g.y);+ float ms = b1->imass + b2->imass, i1 = b1->iinertia, i2 = b2->iinertia;+ float ka = ms + i1 * rn1a * rn1a + i2 * rn1b * rn1b;+ float kb = ms + i1 * rn1a * rn2a + i2 * rn1b * rn2b;+ float kc = ms + i1 * rn2a * rn2a + i2 * rn2b * rn2b;+ float bx = err1 * bc, by = err2 * bc, xx, xy;+ /* mat2_solve(kMass, -b) */+ {+ float det = ka * kc - kb * kb, vx = -bx, vy = -by;+ if (det != det) xx = xy = 0;+ else if (det == 0) {+ xx = ka != 0 ? vx / ka : 0;+ xy = kc != 0 ? vy / kc : 0;+ } else {+ det = 1 / det;+ xx = det * (kc * vx - kb * vy);+ xy = det * (ka * vy - kb * vx);+ }+ }+ bool ok = xx >= 0 && xy >= 0;+ if (!ok) {+ xx = -bx / ka, xy = 0;+ ok = xx >= 0 && kb * xx + by >= 0;+ }+ if (!ok) {+ xx = 0, xy = -by / kc;+ ok = xy >= 0 && kb * xy + bx >= 0;+ }+ if (ok) {+ float s = xx + xy;+ b1->pos.x -= g.x * s * b1->imass, b1->pos.y -= g.y * s * b1->imass;+ delta_rot(b1, -b1->iinertia * (rn1a * xx + rn2a * xy));+ b2->pos.x += g.x * s * b2->imass, b2->pos.y += g.y * s * b2->imass;+ delta_rot(b2, b2->iinertia * (rn1b * xx + rn2b * xy));+ }+ } else {+ float rn1 = cross(c1r1x, c1r1y, g.x, g.y), rn2 = cross(c1r2x, c1r2y, g.x, g.y);+ float K = b2->imass + rn2 * rn2 * b2->iinertia + b1->imass + rn1 * rn1 * b1->iinertia;+ if (K != 0) {+ float jn = -bc * err1 / K, jx = g.x * jn, jy = g.y * jn;+ b1->pos.x -= jx * b1->imass, b1->pos.y -= jy * b1->imass;+ delta_rot(b1, -rn1 * b1->iinertia * jn);+ b2->pos.x += jx * b2->imass, b2->pos.y += jy * b2->imass;+ delta_rot(b2, rn2 * b2->iinertia * jn);+ }+ }+}++/* ---- constraints ---- */++static float soft_gamma(float freq, float damping, float dt, float *gamma, float *biascoef) {+ float omega = TAU * freq;+ float g = 1 / (dt * omega * (2 * damping + omega * dt)), ig = 1 / (1 + g);+ *biascoef = dt * omega * omega * g;+ *gamma = g * ig;+ return ig;+}++static int mat2_invert(float *m) {+ float det = m[0] * m[2] - m[1] * m[1];+ if (det != det) { m[0] = m[1] = m[2] = 0; return 3; }+ if (det == 0) {+ int flag = 0;+ if (m[0] != 0) m[0] = 1 / m[0]; else { m[0] = 0; flag |= 1; }+ if (m[2] != 0) m[2] = 1 / m[2]; else { m[2] = 0; flag |= 2; }+ m[1] = 0;+ return flag;+ }+ det = 1 / det;+ float t = m[2] * det;+ m[2] = m[0] * det;+ m[0] = t;+ m[1] *= -det;+ return 0;+}++static void mat2_solve(const float *m, float *vx, float *vy) {+ float det = m[0] * m[2] - m[1] * m[1];+ if (det != det) { *vx = *vy = 0; return; }+ if (det == 0) {+ *vx = m[0] != 0 ? *vx / m[0] : 0;+ *vy = m[2] != 0 ? *vy / m[2] : 0;+ return;+ }+ det = 1 / det;+ float t = det * (m[2] * *vx - m[1] * *vy);+ *vy = det * (m[0] * *vy - m[1] * *vx);+ *vx = t;+}++/* 3x3 symmetric: a b c / b d e / c e f stored a,b,d,c,e,f as Nape's mat3_set(m,A,B,D,C,E,F) */+static int mat3_invert(float *m) {+ float a = m[0], b = m[1], d = m[2], c = m[3], e = m[4], f = m[5];+ float det = a * (d * f - e * e) + b * (c * e - b * f) + c * (b * e - c * d);+ if (det != det) { for (int i = 0; i < 6; i++) m[i] = 0; return 7; }+ if (det == 0) {+ int flag = 0;+ if (a != 0) m[0] = 1 / a; else { m[0] = 0; flag |= 1; }+ if (d != 0) m[2] = 1 / d; else { m[2] = 0; flag |= 2; }+ if (f != 0) m[5] = 1 / f; else { m[5] = 0; flag |= 4; }+ m[1] = m[3] = m[4] = 0;+ return flag;+ }+ det = 1 / det;+ float A = det * (d * f - e * e);+ float B = det * (e * c - b * f), D = det * (a * f - c * c);+ float C = det * (b * e - c * d), E = det * (b * c - a * e), F = det * (a * d - b * b);+ m[0] = A, m[1] = B, m[2] = D, m[3] = C, m[4] = E, m[5] = F;+ return 0;+}++static void mat3_xform(const float *m, float *v) {+ float X = m[0] * v[0] + m[1] * v[1] + m[3] * v[2];+ float Y = m[1] * v[0] + m[2] * v[1] + m[4] * v[2];+ v[2] = m[3] * v[0] + m[4] * v[1] + m[5] * v[2];+ v[0] = X, v[1] = Y;+}++static void mat3_solve(const float *m, float *v) {+ float a = m[0], b = m[1], d = m[2], c = m[3], e = m[4], f = m[5];+ float det = a * (d * f - e * e) + b * (c * e - b * f) + c * (b * e - c * d);+ if (det != det) { v[0] = v[1] = v[2] = 0; return; }+ if (det == 0) {+ v[0] = a != 0 ? v[0] / a : 0;+ v[1] = d != 0 ? v[1] / d : 0;+ v[2] = f != 0 ? v[2] / f : 0;+ return;+ }+ det = 1 / det;+ float B = e * c - b * f, C = b * e - c * d, E = b * c - a * e;+ float X = det * (v[0] * (d * f - e * e) + v[1] * B + v[2] * C);+ float Y = det * (v[0] * B + v[1] * (a * f - c * c) + v[2] * E);+ v[2] = det * (v[0] * C + v[1] * E + v[2] * (a * d - b * b));+ v[0] = X, v[1] = Y;+}++static void clamp2(float *x, float *y, float m) {+ float ls = *x * *x + *y * *y;+ if (ls > m * m) {+ float k = m / sqrtf(ls);+ *x *= k, *y *= k;+ }+}++static inline V2 anchor(const Body *b, V2 l) { return rot_axis(l.x, l.y, b->axis); }++/* PivotJoint, WeldJoint (2D part) helpers */+static void pivot_keff(const Body *b1, const Body *b2, V2 r1, V2 r2, float *k) {+ float m = b1->imass + b2->imass;+ k[0] = m, k[1] = 0, k[2] = m;+ if (b1->iinertia != 0) {+ float X = r1.x * b1->iinertia, Y = r1.y * b1->iinertia;+ k[0] += Y * r1.y, k[1] += -Y * r1.x, k[2] += X * r1.x;+ }+ if (b2->iinertia != 0) {+ float X = r2.x * b2->iinertia, Y = r2.y * b2->iinertia;+ k[0] += Y * r2.y, k[1] += -Y * r2.x, k[2] += X * r2.x;+ }+}++static void pivot_imp(Body *b1, Body *b2, V2 r1, V2 r2, float jx, float jy, bool bias) {+ if (bias) {+ b1->pos.x -= jx * b1->imass, b1->pos.y -= jy * b1->imass;+ b2->pos.x += jx * b2->imass, b2->pos.y += jy * b2->imass;+ delta_rot(b1, -cross(r1.x, r1.y, jx, jy) * b1->iinertia);+ delta_rot(b2, cross(r2.x, r2.y, jx, jy) * b2->iinertia);+ } else {+ b1->vel.x -= jx * b1->imass, b1->vel.y -= jy * b1->imass;+ b2->vel.x += jx * b2->imass, b2->vel.y += jy * b2->imass;+ b1->angvel -= cross(r1.x, r1.y, jx, jy) * b1->iinertia;+ b2->angvel += cross(r2.x, r2.y, jx, jy) * b2->iinertia;+ }+}++static void weld_keff(const Body *b1, const Body *b2, V2 r1, V2 r2, float *k) {+ float m = b1->imass + b2->imass;+ k[0] = m, k[1] = 0, k[2] = m, k[3] = 0, k[4] = 0, k[5] = 0;+ const Body *bs[2] = {b1, b2};+ V2 rs[2] = {r1, r2};+ for (int i = 0; i < 2; i++) {+ const Body *b = bs[i];+ if (b->iinertia == 0) continue;+ float X = rs[i].x * b->iinertia, Y = rs[i].y * b->iinertia;+ k[0] += Y * rs[i].y, k[1] += -Y * rs[i].x, k[2] += X * rs[i].x;+ k[3] += -Y, k[4] += X, k[5] += b->iinertia;+ }+}++static void weld_imp(Body *b1, Body *b2, V2 r1, V2 r2, const float *j, bool bias) {+ float c1 = cross(r1.x, r1.y, j[0], j[1]) + j[2], c2 = cross(r2.x, r2.y, j[0], j[1]) + j[2];+ if (bias) {+ b1->pos.x -= j[0] * b1->imass, b1->pos.y -= j[1] * b1->imass;+ b2->pos.x += j[0] * b2->imass, b2->pos.y += j[1] * b2->imass;+ delta_rot(b1, -c1 * b1->iinertia);+ delta_rot(b2, c2 * b2->iinertia);+ } else {+ b1->vel.x -= j[0] * b1->imass, b1->vel.y -= j[1] * b1->imass;+ b2->vel.x += j[0] * b2->imass, b2->vel.y += j[1] * b2->imass;+ b1->angvel -= c1 * b1->iinertia;+ b2->angvel += c2 * b2->iinertia;+ }+}++/* DistanceJoint Cerr: C, and n */+static float dist_cerr(Con *c, V2 r1, V2 r2, V2 *n, bool *slack) {+ Body *b1 = c->b1, *b2 = c->b2;+ float nx = b2->pos.x + r2.x - (b1->pos.x + r1.x), ny = b2->pos.y + r2.y - (b1->pos.y + r1.y);+ float C = nx * nx + ny * ny;+ if (C < EPS) { *n = v2(0, 0); *slack = true; return 0; }+ C = sqrtf(C);+ nx /= C, ny /= C;+ if (c->flags & CF_EQUAL) { C -= c->jmax; *slack = false; }+ else if (C < c->jmin) { C = c->jmin - C; nx = -nx, ny = -ny; *slack = false; }+ else if (C > c->jmax) { C -= c->jmax; *slack = false; }+ else { nx = ny = 0; C = 0; *slack = true; }+ *n = v2(nx, ny);+ return C;+}++static void dist_imp(Body *b1, Body *b2, V2 n, float cx1, float cx2, float j, bool bias) {+ if (bias) {+ b1->pos.x -= n.x * b1->imass * j, b1->pos.y -= n.y * b1->imass * j;+ b2->pos.x += n.x * b2->imass * j, b2->pos.y += n.y * b2->imass * j;+ delta_rot(b1, -cx1 * b1->iinertia * j);+ delta_rot(b2, cx2 * b2->iinertia * j);+ } else {+ b1->vel.x -= n.x * b1->imass * j, b1->vel.y -= n.y * b1->imass * j;+ b2->vel.x += n.x * b2->imass * j, b2->vel.y += n.y * b2->imass * j;+ b1->angvel -= cx1 * b1->iinertia * j;+ b2->angvel += cx2 * b2->iinertia * j;+ }+}++/* AngleJoint Cerr */+static float angle_cerr(Con *c, float *scale, bool *slack) {+ float C = c->ratio * c->b2->rot - c->b1->rot;+ if (c->flags & CF_EQUAL) { C -= c->jmax; *slack = false; *scale = 1; }+ else if (C < c->jmin) { C = c->jmin - C; *scale = -1; *slack = false; }+ else if (C > c->jmax) { C -= c->jmax; *scale = 1; *slack = false; }+ else { *scale = 0; C = 0; *slack = true; }+ return C;+}++static void angle_imp(Con *c, float scale, float j, bool bias) {+ Body *b1 = c->b1, *b2 = c->b2;+ if (bias) {+ delta_rot(b1, -scale * j * b1->iinertia);+ delta_rot(b2, c->ratio * scale * j * b2->iinertia);+ } else {+ b1->angvel -= scale * b1->iinertia * j;+ b2->angvel += c->ratio * scale * b2->iinertia * j;+ }+}++/* LineJoint */+static void line_cerr(Con *c, V2 r1, V2 r2, V2 n, V2 *d, float *Cx, float *Cy, float *scale) {+ Body *b1 = c->b1, *b2 = c->b2;+ d->x = b2->pos.x + r2.x - b1->pos.x - r1.x;+ d->y = b2->pos.y + r2.y - b1->pos.y - r1.y;+ *Cx = cross(n.x, n.y, d->x, d->y);+ *Cy = n.x * d->x + n.y * d->y;+ if (c->flags & CF_EQUAL) { *Cy -= c->jmin; *scale = 1; }+ else if (*Cy > c->jmax) { *Cy -= c->jmax; *scale = 1; }+ else if (*Cy < c->jmin) { *Cy = c->jmin - *Cy; *scale = -1; }+ else { *Cy = 0; *scale = 0; }+}++static void line_keff(Con *c, V2 r1, V2 r2, V2 n, V2 d, float scale, float *k, float *dot1, float *cx1, float *dot2,+ float *cx2) {+ Body *b1 = c->b1, *b2 = c->b2;+ float drx = d.x + r1.x, dry = d.y + r1.y;+ *dot1 = n.x * drx + n.y * dry, *cx1 = cross(n.x, n.y, drx, dry);+ *dot2 = n.x * r2.x + n.y * r2.y, *cx2 = cross(n.x, n.y, r2.x, r2.y);+ k[0] = b1->imass + b2->imass + *dot1 * *dot1 * b1->iinertia + *dot2 * *dot2 * b2->iinertia;+ k[1] = -scale * (*dot1 * *cx1 * b1->iinertia + *dot2 * *cx2 * b2->iinertia);+ k[2] = scale * scale * (b1->imass + b2->imass + *cx1 * *cx1 * b1->iinertia + *cx2 * *cx2 * b2->iinertia);+}++static void line_imp(Body *b1, Body *b2, V2 n, float scale, float dot1, float cx1, float dot2, float cx2, float jx,+ float jy, bool bias) {+ float Jx = scale * n.x * jy - n.y * jx, Jy = n.x * jx + scale * n.y * jy;+ float w1 = (scale * cx1 * jy - dot1 * jx) * b1->iinertia, w2 = (dot2 * jx - scale * cx2 * jy) * b2->iinertia;+ if (bias) {+ b1->pos.x -= Jx * b1->imass, b1->pos.y -= Jy * b1->imass;+ b2->pos.x += Jx * b2->imass, b2->pos.y += Jy * b2->imass;+ delta_rot(b1, w1);+ delta_rot(b2, w2);+ } else {+ b1->vel.x -= Jx * b1->imass, b1->vel.y -= Jy * b1->imass;+ b2->vel.x += Jx * b2->imass, b2->vel.y += Jy * b2->imass;+ b1->angvel += w1;+ b2->angvel += w2;+ }+}++static bool con_live(const Con *c) {+ return (c->flags & CF_ACTIVE) && (c->b1->flags & BF_SPACE) && (c->b2->flags & BF_SPACE) &&+ !((c->b1->flags & BF_STILL || c->b1->type != B_DYNAMIC) && (c->b2->flags & BF_STILL || c->b2->type != B_DYNAMIC)) &&+ !(c->b1->flags & BF_FROZEN) && !(c->b2->flags & BF_FROZEN);+}++void np_con_clear(Con *c) {+ c->jacc[0] = c->jacc[1] = c->jacc[2] = 0;+ c->pre_dt = -1;+ c->flags &= (uint8_t)~CF_SLACK;+}++static void con_prestep(Con *c, float dt) {+ Body *b1 = c->b1, *b2 = c->b2;+ if (c->pre_dt == -1) c->pre_dt = dt;+ float dtratio = dt / c->pre_dt;+ c->pre_dt = dt;+ bool stiff = c->flags & CF_STIFF;+ float biascoef;+ switch (c->type) {+ case C_PIVOT: {+ c->a1rel = anchor(b1, c->a1), c->a2rel = anchor(b2, c->a2);+ pivot_keff(b1, b2, c->a1rel, c->a2rel, c->k);+ int flag = mat2_invert(c->k);+ if (flag & 1) c->jacc[0] = 0;+ if (flag & 2) c->jacc[1] = 0;+ if (!stiff) {+ float ig = soft_gamma(c->frequency, c->damping, dt, &c->gamma, &biascoef);+ c->k[0] *= ig, c->k[1] *= ig, c->k[2] *= ig;+ c->bias[0] = -biascoef * (b2->pos.x + c->a2rel.x - (b1->pos.x + c->a1rel.x));+ c->bias[1] = -biascoef * (b2->pos.y + c->a2rel.y - (b1->pos.y + c->a1rel.y));+ } else c->bias[0] = c->bias[1] = 0, c->gamma = 0;+ c->jacc[0] *= dtratio, c->jacc[1] *= dtratio;+ break;+ }+ case C_WELD: {+ c->a1rel = anchor(b1, c->a1), c->a2rel = anchor(b2, c->a2);+ weld_keff(b1, b2, c->a1rel, c->a2rel, c->k);+ int flag = mat3_invert(c->k);+ if (flag & 1) c->jacc[0] = 0;+ if (flag & 2) c->jacc[1] = 0;+ if (flag & 4) c->jacc[2] = 0;+ if (!stiff) {+ float ig = soft_gamma(c->frequency, c->damping, dt, &c->gamma, &biascoef);+ for (int i = 0; i < 6; i++) c->k[i] *= ig;+ c->bias[0] = -biascoef * (b2->pos.x + c->a2rel.x - (b1->pos.x + c->a1rel.x));+ c->bias[1] = -biascoef * (b2->pos.y + c->a2rel.y - (b1->pos.y + c->a1rel.y));+ c->bias[2] = -biascoef * (b2->rot - b1->rot - c->phase);+ } else c->bias[0] = c->bias[1] = c->bias[2] = 0, c->gamma = 0;+ for (int i = 0; i < 3; i++) c->jacc[i] *= dtratio;+ break;+ }+ case C_DIST: {+ if (c->jmin == c->jmax) c->flags |= CF_EQUAL; else c->flags &= (uint8_t)~CF_EQUAL;+ c->a1rel = anchor(b1, c->a1), c->a2rel = anchor(b2, c->a2);+ bool slack;+ float C = dist_cerr(c, c->a1rel, c->a2rel, &c->n, &slack);+ if (slack) c->flags |= CF_SLACK; else c->flags &= (uint8_t)~CF_SLACK;+ if (!slack) {+ c->cx1 = cross(c->a1rel.x, c->a1rel.y, c->n.x, c->n.y);+ c->cx2 = cross(c->a2rel.x, c->a2rel.y, c->n.x, c->n.y);+ float k = b1->imass + b2->imass + c->cx1 * c->cx1 * b1->iinertia + c->cx2 * c->cx2 * b2->iinertia;+ if (k != 0) k = 1 / k; else c->jacc[0] = 0;+ if (!stiff) {+ k *= soft_gamma(c->frequency, c->damping, dt, &c->gamma, &biascoef);+ c->bias[0] = -C * biascoef;+ } else c->bias[0] = 0, c->gamma = 0;+ c->k[0] = k;+ c->jacc[0] *= dtratio;+ }+ break;+ }+ case C_LINE: {+ if (c->jmin == c->jmax) c->flags |= CF_EQUAL; else c->flags &= (uint8_t)~CF_EQUAL;+ c->a1rel = anchor(b1, c->a1), c->nrel = anchor(b1, c->nlocal), c->a2rel = anchor(b2, c->a2);+ V2 d;+ float Cx, Cy;+ line_cerr(c, c->a1rel, c->a2rel, c->nrel, &d, &Cx, &Cy, &c->scale);+ line_keff(c, c->a1rel, c->a2rel, c->nrel, d, c->scale, c->k, &c->dot1, &c->cx1, &c->dot2, &c->cx2);+ int flag = mat2_invert(c->k);+ if (flag & 1) c->jacc[0] = 0;+ if (flag & 2) c->jacc[1] = 0;+ if (!stiff) {+ float ig = soft_gamma(c->frequency, c->damping, dt, &c->gamma, &biascoef);+ c->k[0] *= ig, c->k[1] *= ig, c->k[2] *= ig;+ c->bias[0] = -Cx * biascoef, c->bias[1] = -Cy * biascoef;+ } else c->gamma = 0, c->bias[0] = c->bias[1] = 0;+ c->jacc[0] *= dtratio, c->jacc[1] *= dtratio;+ break;+ }+ case C_ANGLE: {+ if (c->jmin == c->jmax) c->flags |= CF_EQUAL; else c->flags &= (uint8_t)~CF_EQUAL;+ bool slack;+ float C = angle_cerr(c, &c->scale, &slack);+ if (slack) c->flags |= CF_SLACK; else c->flags &= (uint8_t)~CF_SLACK;+ if (!slack) {+ float k = b1->iinertia + c->ratio * c->ratio * b2->iinertia;+ if (k != 0) k = 1 / k; else c->jacc[0] = 0;+ if (!stiff) {+ k *= soft_gamma(c->frequency, c->damping, dt, &c->gamma, &biascoef);+ c->bias[0] = -C * biascoef;+ } else c->bias[0] = 0, c->gamma = 0;+ c->k[0] = k;+ c->jacc[0] *= dtratio;+ }+ break;+ }+ case C_MOTOR:+ c->k[0] = 1 / (b1->iinertia + c->ratio * c->ratio * b2->iinertia);+ c->jacc[0] *= dtratio;+ break;+ }+}++static void con_warm(Con *c) {+ Body *b1 = c->b1, *b2 = c->b2;+ switch (c->type) {+ case C_PIVOT: pivot_imp(b1, b2, c->a1rel, c->a2rel, c->jacc[0], c->jacc[1], false); break;+ case C_WELD: weld_imp(b1, b2, c->a1rel, c->a2rel, c->jacc, false); break;+ case C_DIST:+ if (!(c->flags & CF_SLACK)) dist_imp(b1, b2, c->n, c->cx1, c->cx2, c->jacc[0], false);+ break;+ case C_LINE:+ line_imp(b1, b2, c->nrel, c->scale, c->dot1, c->cx1, c->dot2, c->cx2, c->jacc[0], c->jacc[1], false);+ break;+ case C_ANGLE:+ if (!(c->flags & CF_SLACK)) angle_imp(c, c->scale, c->jacc[0], false);+ break;+ case C_MOTOR:+ b1->angvel -= b1->iinertia * c->jacc[0];+ b2->angvel += c->ratio * b2->iinertia * c->jacc[0];+ break;+ }+}++static void con_vel(Con *c) {+ Body *b1 = c->b1, *b2 = c->b2;+ switch (c->type) {+ case C_PIVOT: {+ V2 r1 = c->a1rel, r2 = c->a2rel;+ float Ex = (b2->vel.x - r2.y * b2->angvel) - (b1->vel.x - r1.y * b1->angvel);+ float Ey = (b2->vel.y + r2.x * b2->angvel) - (b1->vel.y + r1.x * b1->angvel);+ float jx = c->bias[0] - Ex, jy = c->bias[1] - Ey;+ float t = c->k[0] * jx + c->k[1] * jy;+ jy = c->k[1] * jx + c->k[2] * jy, jx = t;+ jx -= c->jacc[0] * c->gamma, jy -= c->jacc[1] * c->gamma;+ float ox = c->jacc[0], oy = c->jacc[1];+ c->jacc[0] += jx, c->jacc[1] += jy;+ jx = c->jacc[0] - ox, jy = c->jacc[1] - oy;+ pivot_imp(b1, b2, r1, r2, jx, jy, false);+ break;+ }+ case C_WELD: {+ V2 r1 = c->a1rel, r2 = c->a2rel;+ float E[3];+ E[0] = (b2->vel.x - r2.y * b2->angvel) - (b1->vel.x - r1.y * b1->angvel);+ E[1] = (b2->vel.y + r2.x * b2->angvel) - (b1->vel.y + r1.x * b1->angvel);+ E[2] = b2->angvel - b1->angvel;+ float J[3] = {c->bias[0] - E[0], c->bias[1] - E[1], c->bias[2] - E[2]};+ mat3_xform(c->k, J);+ for (int i = 0; i < 3; i++) J[i] -= c->jacc[i] * c->gamma;+ for (int i = 0; i < 3; i++) {+ float o = c->jacc[i];+ c->jacc[i] += J[i];+ J[i] = c->jacc[i] - o;+ }+ weld_imp(b1, b2, r1, r2, J, false);+ break;+ }+ case C_DIST: {+ if (c->flags & CF_SLACK) break;+ float E = c->n.x * (b2->vel.x - b1->vel.x) + c->n.y * (b2->vel.y - b1->vel.y) + b2->angvel * c->cx2 - b1->angvel * c->cx1;+ float j = c->k[0] * (c->bias[0] - E) - c->jacc[0] * c->gamma;+ float o = c->jacc[0];+ c->jacc[0] += j;+ if (!(c->flags & CF_EQUAL) && c->jacc[0] > 0) c->jacc[0] = 0;+ j = c->jacc[0] - o;+ dist_imp(b1, b2, c->n, c->cx1, c->cx2, j, false);+ break;+ }+ case C_LINE: {+ V2 n = c->nrel;+ float dvx = b2->vel.x - b1->vel.x, dvy = b2->vel.y - b1->vel.y;+ float Ex = cross(n.x, n.y, dvx, dvy) + b2->angvel * c->dot2 - b1->angvel * c->dot1;+ float Ey = c->scale * (n.x * dvx + n.y * dvy - b2->angvel * c->cx2 + b1->angvel * c->cx1);+ float jx = c->bias[0] - Ex, jy = c->bias[1] - Ey;+ float t = c->k[0] * jx + c->k[1] * jy;+ jy = c->k[1] * jx + c->k[2] * jy, jx = t;+ jx -= c->jacc[0] * c->gamma, jy -= c->jacc[1] * c->gamma;+ float ox = c->jacc[0], oy = c->jacc[1];+ c->jacc[0] += jx, c->jacc[1] += jy;+ if (c->jacc[1] > 0) c->jacc[1] = 0;+ jx = c->jacc[0] - ox, jy = c->jacc[1] - oy;+ line_imp(b1, b2, n, c->scale, c->dot1, c->cx1, c->dot2, c->cx2, jx, jy, false);+ break;+ }+ case C_ANGLE: {+ if (c->flags & CF_SLACK) break;+ float E = c->scale * (c->ratio * b2->angvel - b1->angvel);+ float j = c->k[0] * (c->bias[0] - E) - c->jacc[0] * c->gamma;+ float o = c->jacc[0];+ c->jacc[0] += j;+ if (!(c->flags & CF_EQUAL) && c->jacc[0] > 0) c->jacc[0] = 0;+ j = c->jacc[0] - o;+ angle_imp(c, c->scale, j, false);+ break;+ }+ case C_MOTOR: {+ float E = c->ratio * b2->angvel - b1->angvel - c->rate;+ float j = -c->k[0] * E;+ c->jacc[0] += j;+ b1->angvel -= b1->iinertia * j;+ b2->angvel += c->ratio * b2->iinertia * j;+ break;+ }+ }+}++static void con_pos(Con *c) {+ Body *b1 = c->b1, *b2 = c->b2;+ switch (c->type) {+ case C_PIVOT: {+ V2 r1 = anchor(b1, c->a1), r2 = anchor(b2, c->a2);+ float Ex = b2->pos.x + r2.x - (b1->pos.x + r1.x), Ey = b2->pos.y + r2.y - (b1->pos.y + r1.y);+ if (Ex * Ex + Ey * Ey < LIN_SLOP * LIN_SLOP) return;+ Ex *= 0.5f, Ey *= 0.5f;+ if (Ex * Ex + Ey * Ey > 6) {+ float k = b1->imass + b2->imass;+ if (k > EPS) {+ k = 0.75f / k;+ float jx = -Ex * k, jy = -Ey * k;+ clamp2(&jx, &jy, 20);+ b1->pos.x -= jx * b1->imass, b1->pos.y -= jy * b1->imass;+ b2->pos.x += jx * b2->imass, b2->pos.y += jy * b2->imass;+ Ex = 0.5f * (b2->pos.x + r2.x - (b1->pos.x + r1.x)), Ey = 0.5f * (b2->pos.y + r2.y - (b1->pos.y + r1.y));+ }+ }+ float K[3];+ pivot_keff(b1, b2, r1, r2, K);+ float jx = -Ex, jy = -Ey;+ clamp2(&jx, &jy, 6);+ mat2_solve(K, &jx, &jy);+ pivot_imp(b1, b2, r1, r2, jx, jy, true);+ break;+ }+ case C_WELD: {+ V2 r1 = anchor(b1, c->a1), r2 = anchor(b2, c->a2);+ float E[3] = {b2->pos.x + r2.x - (b1->pos.x + r1.x), b2->pos.y + r2.y - (b1->pos.y + r1.y), b2->rot - b1->rot - c->phase};+ bool cont = true;+ if (E[0] * E[0] + E[1] * E[1] < LIN_SLOP * LIN_SLOP) { cont = false; E[0] = E[1] = 0; }+ if (E[2] * E[2] < ANG_SLOP * ANG_SLOP) {+ if (!cont) return;+ E[2] = 0;+ }+ E[0] *= 0.5f, E[1] *= 0.5f, E[2] *= 0.5f;+ if (E[0] * E[0] + E[1] * E[1] > 6) {+ float k = b1->imass + b2->imass;+ if (k > EPS) {+ k = 0.75f / k;+ float jx = -E[0] * k, jy = -E[1] * k;+ clamp2(&jx, &jy, 20);+ b1->pos.x -= jx * b1->imass, b1->pos.y -= jy * b1->imass;+ b2->pos.x += jx * b2->imass, b2->pos.y += jy * b2->imass;+ E[0] = 0.5f * (b2->pos.x + r2.x - (b1->pos.x + r1.x));+ E[1] = 0.5f * (b2->pos.y + r2.y - (b1->pos.y + r1.y));+ E[2] = 0.5f * (b2->rot - b1->rot - c->phase);+ }+ }+ float K[6];+ weld_keff(b1, b2, r1, r2, K);+ float J[3] = {-E[0], -E[1], -E[2]};+ clamp2(&J[0], &J[1], 6);+ J[2] = J[2] > 0.25f ? 0.25f : J[2] < -0.25f ? -0.25f : J[2];+ mat3_solve(K, J);+ weld_imp(b1, b2, r1, r2, J, true);+ break;+ }+ case C_DIST: {+ V2 r1 = anchor(b1, c->a1), r2 = anchor(b2, c->a2), n;+ bool slack;+ float E = dist_cerr(c, r1, r2, &n, &slack);+ if (slack) return;+ if (E * E < LIN_SLOP * LIN_SLOP) return;+ E *= 0.5f;+ bool equal = c->flags & CF_EQUAL;+ if (E * E > 6) {+ float k = b1->imass + b2->imass;+ if (k > EPS) {+ k = 0.75f / k;+ float j = -E * k;+ if (equal || j < 0) {+ b1->pos.x -= n.x * j * b1->imass, b1->pos.y -= n.y * j * b1->imass;+ b2->pos.x += n.x * j * b2->imass, b2->pos.y += n.y * j * b2->imass;+ E = 0.5f * dist_cerr(c, r1, r2, &n, &slack);+ }+ }+ }+ float cx1 = cross(r1.x, r1.y, n.x, n.y), cx2 = cross(r2.x, r2.y, n.x, n.y);+ float k = b1->imass + b2->imass + cx1 * cx1 * b1->iinertia + cx2 * cx2 * b2->iinertia;+ if (k != 0) k = 1 / k;+ float j = -E * k;+ if (equal || j < 0) dist_imp(b1, b2, n, cx1, cx2, j, true);+ break;+ }+ case C_LINE: {+ V2 n = anchor(b1, c->nlocal), r1 = anchor(b1, c->a1), r2 = anchor(b2, c->a2), d;+ float Ex, Ey, scale;+ line_cerr(c, r1, r2, n, &d, &Ex, &Ey, &scale);+ if (Ex * Ex + Ey * Ey < LIN_SLOP * LIN_SLOP) return;+ Ex *= 0.5f, Ey *= 0.5f;+ if (Ex * Ex + Ey * Ey > 6) {+ float k = b1->imass + b2->imass;+ if (k > EPS) {+ k = 0.8f / k;+ /* (as Nape writes it) */+ float jx = k * (n.y * Ex - scale * n.x * Ey), jy = k * (n.x * Ex * scale - n.y * Ex);+ b1->pos.x -= jx * b1->imass, b1->pos.y -= jy * b1->imass;+ b2->pos.x += jx * b2->imass, b2->pos.y += jy * b2->imass;+ line_cerr(c, r1, r2, n, &d, &Ex, &Ey, &scale);+ Ex *= 0.5f, Ey *= 0.5f;+ }+ }+ float K[3], dot1, cx1, dot2, cx2;+ line_keff(c, r1, r2, n, d, scale, K, &dot1, &cx1, &dot2, &cx2);+ float jx = -Ex, jy = -Ey;+ mat2_solve(K, &jx, &jy);+ if (jy > 0) jy = 0;+ line_imp(b1, b2, n, scale, dot1, cx1, dot2, cx2, jx, jy, true);+ break;+ }+ case C_ANGLE: {+ float scale;+ bool slack;+ float E = angle_cerr(c, &scale, &slack);+ if (slack) return;+ E *= 0.5f;+ float j = -E * c->k[0];+ if ((c->flags & CF_EQUAL) || j < 0) angle_imp(c, scale, j, true);+ break;+ }+ default: break;+ }+}++static Arb *col_list[NP_MAX_ARBS], *fl_list[16];++void np_step(float dt) {+ sp.stamp++;+ pre_dt_space = dt;+ /* validation: the world shapes of moving bodies */+ for (int i = 0; i < sp.nbodies; i++) {+ Body *b = sp.bodies[i];+ if ((b->flags & BF_SPACE) && !(b->flags & BF_STILL)) body_world(b);+ }+ /* broad and narrow phases */+ for (int i = 0; i < sp.nbodies; i++) {+ Body *a = sp.bodies[i];+ if (!(a->flags & BF_SPACE) || (a->flags & BF_STILL)) continue;+ bool kin = a->type == B_KINEMATIC;+ if (kin && a->vel.x == 0 && a->vel.y == 0 && a->angvel == 0) continue;+ for (int si = 0; si < a->nshapes; si++) {+ Shape *s = &a->shapes[si];+ uint16_t id = s->id;+ /* against the level: static shapes sit in the 256 px columns they span */+ if (!kin) {+ int c0 = (int)((s->minx - sp.bucket_x0) / 256), c1 = (int)((s->maxx - sp.bucket_x0) / 256);+ if (c0 < 0) c0 = 0;+ if (c1 >= sp.nbuckets) c1 = sp.nbuckets - 1;+ for (int c = c0; c <= c1 + 1; c++) {+ int col = c > c1 ? sp.nbuckets : c; /* then the wide shapes */+ int first = sp.buckets[2 * col], count = sp.buckets[2 * col + 1];+ for (int k = 0; k < count; k++) {+ uint16_t sid = sp.bucket_list[first + k];+ const SShape *ss = &sp.sshapes[sid];+ if (ss->x0 + ss->w < s->minx || ss->x0 > s->maxx || ss->y0 + ss->h < s->miny || ss->y0 > s->maxy) continue;+ if (!(sp.sbodies[ss->body].flags & BF_SPACE)) continue;+ /* a shape spanning columns is met once, in the first column both share */+ if (col < sp.nbuckets && c > c0 && (int)((ss->x0 - sp.bucket_x0) / 256) < c) continue;+ narrow(id, sid, true);+ }+ }+ }+ /* against the other bodies (two moving ones once) */+ for (int j = 0; j < sp.nbodies; j++) {+ Body *b = sp.bodies[j];+ if (b == a || !(b->flags & BF_SPACE)) continue;+ if (kin && b->type != B_DYNAMIC) continue;+ bool bmoving = (b->flags & BF_FROZEN) ? false+ : b->type == B_DYNAMIC ? !(b->flags & BF_SLEEP) : (b->vel.x != 0 || b->vel.y != 0 || b->angvel != 0);+ if (bmoving && j < i) continue;+ if (b->maxx < s->minx || b->minx > s->maxx || b->maxy < s->miny || b->miny > s->maxy) continue;+ for (int sj = 0; sj < b->nshapes; sj++) {+ Shape *t = &b->shapes[sj];+ if (t->maxx < s->minx || t->minx > s->maxx || t->maxy < s->miny || t->miny > s->maxy) continue;+ narrow(id, t->id, b->type != B_DYNAMIC || a->type != B_DYNAMIC);+ }+ }+ }+ }+ /* prestep */+ for (int i = 0; i < sp.ncons; i++) {+ Con *c = sp.cons[i];+ if (con_live(c)) con_prestep(c, dt);+ }+ int ncol = 0, nfl = 0;+ for (int pass = 0; pass < 2; pass++)+ for (int i = 0; i < NP_MAX_ARBS; i++) {+ Arb *a = &sp.arbs[i];+ if (!a->used || a->stat != pass) continue;+ if (arb_prestep(a, dt)) {+ if (a->type == A_COL) col_list[ncol++] = a;+ else if (a->type == A_FLUID && nfl < 16) fl_list[nfl++] = a;+ }+ }+ /* updateVel */+ float lin = 1 - dt * DRAG, ang = 1 - dt * DRAG;+ for (int i = 0; i < sp.nbodies; i++) {+ Body *b = sp.bodies[i];+ if (!(b->flags & BF_SPACE) || (b->flags & BF_STILL) || b->type != B_DYNAMIC) continue;+ if (b->imass != 0) {+ float t = dt * b->imass;+ b->vel.x = lin * b->vel.x + (sp.gravity.x * b->mass) * t;+ b->vel.y = lin * b->vel.y + (sp.gravity.y * b->mass) * t;+ }+ if (b->iinertia != 0) {+ V2 wc = rot_axis(b->lcom.x, b->lcom.y, b->axis);+ float torque = b->torque + cross(wc.x, wc.y, sp.gravity.x, sp.gravity.y) * b->mass;+ b->angvel = ang * b->angvel + torque * dt * b->iinertia;+ }+ }+ /* warm start and velocity iterations */+ for (int i = 0; i < nfl; i++) fluid_warm(fl_list[i]);+ for (int i = 0; i < ncol; i++) arb_warm(col_list[i]);+ for (int i = 0; i < sp.ncons; i++) {+ Con *c = sp.cons[i];+ if (con_live(c)) con_warm(c);+ }+ for (int it = 0; it < VEL_ITER; it++) {+ for (int i = 0; i < nfl; i++) fluid_vel(fl_list[i]);+ for (int i = 0; i < sp.ncons; i++) {+ Con *c = sp.cons[i];+ if (con_live(c)) con_vel(c);+ }+ for (int i = 0; i < ncol; i++) arb_vel(col_list[i]);+ }+ /* positions */+ float maxvel = TAU / dt;+ for (int i = 0; i < sp.nbodies; i++) {+ Body *b = sp.bodies[i];+ if (!(b->flags & BF_SPACE) || (b->flags & BF_STILL) || b->type == B_STATIC) continue;+ b->pos.x += b->vel.x * dt, b->pos.y += b->vel.y * dt;+ if (b->angvel != 0) delta_rot(b, fmodf(b->angvel, maxvel) * dt);+ }+ for (int it = 0; it < POS_ITER; it++) {+ for (int i = 0; i < sp.ncons; i++) {+ Con *c = sp.cons[i];+ if (c->type != C_MOTOR && (c->flags & CF_STIFF) && con_live(c)) con_pos(c);+ }+ for (int i = 0; i < ncol; i++) arb_pos(col_list[i]);+ }+ forests(dt);+}++void np_body_add(Body *b) {+ if (b->flags & BF_SPACE) return;+ b->flags |= BF_SPACE;+ b->flags &= (uint8_t)~BF_SLEEP;+ b->waket = sp.stamp;+ body_world(b);+}++void np_body_remove(Body *b) {+ if (!(b->flags & BF_SPACE)) return;+ np_drop_body(b);+ b->flags &= (uint8_t)~(BF_SPACE | BF_SLEEP);+}++void np_apply_impulse(Body *b, V2 j, V2 at) {+ b->vel.x += j.x * b->imass, b->vel.y += j.y * b->imass;+ b->angvel += cross(at.x - b->pos.x, at.y - b->pos.y, j.x, j.y) * b->iinertia;+ np_wake(b);+}++/* ---- queries ---- */++static bool ray_poly(V2 o, V2 d, float maxd, const V2 *gv, const V2 *gn, const float *gp, int n, float *t) {+ float tmin = 0, tmax = maxd;+ for (int i = 0; i < n; i++) {+ float den = gn[i].x * d.x + gn[i].y * d.y, num = gp[i] - (gn[i].x * o.x + gn[i].y * o.y);+ if (den == 0) {+ if (num < 0) return false;+ } else {+ float tt = num / den;+ if (den < 0) { if (tt > tmin) tmin = tt; }+ else if (tt < tmax) tmax = tt;+ if (tmin > tmax) return false;+ }+ }+ (void)gv;+ *t = tmin;+ return true;+}++bool np_raycast(V2 o, V2 d, float maxd, Body **body, int *sbody, float *dist) {+ float best = maxd;+ bool hit = false;+ *body = 0, *sbody = -1;+ for (int i = 0; i < sp.nsshapes; i++) {+ const SShape *s = &sp.sshapes[i];+ if (!(sp.sbodies[s->body].flags & BF_SPACE) || (s->flags & SF_SENSOR)) continue;+ float x0 = o.x < o.x + d.x * best ? o.x : o.x + d.x * best, x1 = o.x < o.x + d.x * best ? o.x + d.x * best : o.x;+ if (s->x0 + s->w < x0 || s->x0 > x1) continue;+ SV v;+ sview((uint16_t)i, &v);+ float t;+ if (ray_poly(o, d, best, v.gv, v.gn, v.gp, v.n, &t) && t <= best) best = t, hit = true, *body = 0, *sbody = s->body;+ }+ for (int i = 0; i < sp.nbodies; i++) {+ Body *b = sp.bodies[i];+ if (!(b->flags & BF_SPACE)) continue;+ for (int k = 0; k < b->nshapes; k++) {+ Shape *s = &b->shapes[k];+ if (s->flags & SF_SENSOR) continue;+ float t;+ if (s->type == SH_CIRCLE) {+ float ox = o.x - s->wcom.x, oy = o.y - s->wcom.y, bq = ox * d.x + oy * d.y, c = ox * ox + oy * oy - s->radius * s->radius;+ float disc = bq * bq - c;+ if (disc < 0) continue;+ t = -bq - sqrtf(disc);+ if (t < 0) t = 0;+ if (t > best) continue;+ } else if (!ray_poly(o, d, best, (const V2 *)(const void *)s->glob, (const V2 *)(const void *)(s->glob + 2 * s->n),+ s->glob + 4 * s->n, s->n, &t) || t > best) continue;+ best = t, hit = true, *body = b, *sbody = -1;+ }+ }+ *dist = best;+ return hit;+}++int np_bodies_under(V2 p, Body **out, int max, int *sbody) {+ int n = 0;+ *sbody = -1;+ for (int i = 0; i < sp.nbodies && n < max; i++) {+ Body *b = sp.bodies[i];+ if (!(b->flags & BF_SPACE)) continue;+ body_world(b);+ for (int k = 0; k < b->nshapes; k++) {+ Shape *s = &b->shapes[k];+ bool in;+ if (s->type == SH_CIRCLE) {+ float dx = p.x - s->wcom.x, dy = p.y - s->wcom.y;+ in = dx * dx + dy * dy < s->radius * s->radius;+ } else {+ in = true;+ const float *gn = s->glob + 2 * s->n, *gp = s->glob + 4 * s->n;+ for (int e = 0; e < s->n && in; e++) in = gn[2 * e] * p.x + gn[2 * e + 1] * p.y <= gp[e];+ }+ if (in) { out[n++] = b; break; }+ }+ }+ for (int i = 0; i < sp.nsshapes; i++) {+ const SShape *s = &sp.sshapes[i];+ if (!(sp.sbodies[s->body].flags & BF_SPACE)) continue;+ if (p.x < s->x0 || p.x > s->x0 + s->w || p.y < s->y0 || p.y > s->y0 + s->h) continue;+ SV v;+ sview((uint16_t)i, &v);+ bool in = true;+ for (int e = 0; e < v.n && in; e++) in = v.gn[e].x * p.x + v.gn[e].y * p.y <= v.gp[e];+ if (in) { *sbody = s->body; break; }+ }+ return n;+}+++void np_body_moved(Body *b) {+ body_world(b);+ np_wake(b);+}++void np_register(Body *b) {+ b->idx = (int16_t)sp.nbodies;+ sp.bodies[sp.nbodies++] = b;+ for (int i = 0; i < b->nshapes; i++) {+ Shape *s = &b->shapes[i];+ s->body = b;+ s->id = (uint16_t)(0x8000 | sp.nshapes);+ sp.shapes[sp.nshapes++] = s;+ }+ np_body_mass(b);+}++void np_register_con(Con *c) {+ sp.cons[sp.ncons++] = c;+ c->pre_dt = -1;+}++void np_window(float x0, float x1) {+ for (int i = 0; i < sp.nbodies; i++) {+ Body *b = sp.bodies[i];+ if (!(b->flags & BF_SPACE) || (b->flags & BF_KEEP)) continue;+ bool out = b->maxx < x0 || b->minx > x1;+ if (out) b->flags |= BF_FROZEN;+ else if (b->flags & BF_FROZEN) {+ b->flags &= (uint8_t)~BF_FROZEN;+ b->waket = sp.stamp;+ }+ }+}diff --git a/games/motox3m/src/nape.h b/games/motox3m/src/nape.hnew file mode 100644index 00000000..acf47f0b--- /dev/null+++ b/games/motox3m/src/nape.h@@ -0,0 +1,205 @@+/* Moto X3M: the physics. A port to C of the parts of Nape 2 (Luca Deltodesco, BSD 2-clause, LICENSES/Nape.txt)+ * the game uses: bodies of circles and convex polygons, Nape's contact solver (two-contact block solver, position+ * iterations), its sleeping islands, sensors with begin and end events, and six constraints (pivot, weld,+ * distance, line, angle, motor) with Nape's soft-constraint maths. Floats instead of doubles; no continuous+ * collisions or fluids (the levels have no water).+ *+ * Static shapes live in the level data (world coordinates, their bodies at the origin); dynamic and kinematic+ * bodies own RAM shapes in body coordinates whose world copies are refreshed each step. */+#ifndef MX_NAPE_H+#define MX_NAPE_H+#include <stdbool.h>+#include <stdint.h>++typedef struct { float x, y; } V2;++enum { B_STATIC, B_DYNAMIC, B_KINEMATIC };+/* BF_FROZEN: out of the game's window (far from the camera): kept still until it comes back in view;+ * BF_KEEP: its contacts are always made, taking the slot of another's when all are in use (the bike) */+enum { BF_SPACE = 1, BF_NOMOVE = 2, BF_NOROT = 4, BF_SLEEP = 8, BF_FROZEN = 16, BF_KEEP = 32 };+#define BF_STILL (BF_SLEEP | BF_FROZEN)+enum { SH_CIRCLE, SH_POLY };+enum { SF_SENSOR = 1, SF_FLUID = 2 };++typedef struct {+ float elasticity, dyn, stat, density, rolling;+} Material;++typedef struct {+ int32_t cgroup, cmask, sgroup, smask;+} Filter;++struct Body;++/* a shape of a dynamic or kinematic body, in the body's own coordinates */+typedef struct Shape {+ struct Body *body;+ const float *loc; /* polygon: local vertices (2n floats) */+ float *glob; /* world vertices (2n), edge normals (2n, outwards), projections (n), refreshed each step */+ float minx, miny, maxx, maxy;+ V2 lcom, wcom; /* centre of mass (a circle's centre), local and world */+ float radius, area, inertia; /* inertia per unit mass about the body's origin */+ uint16_t id; /* 0x8000 | its index in sp.shapes */+ uint8_t type, n, flags, filter, mat, pad; /* mat: index in sp.mats */+} Shape;++typedef struct Body {+ V2 pos, vel, axis; /* axis = (sin rot, cos rot) */+ float rot, angvel, torque;+ float mass, imass, iinertia;+ V2 lcom;+ float minx, miny, maxx, maxy;+ Shape *shapes;+ void *user;+ int32_t waket;+ uint16_t cb; /* the game's callback types */+ int16_t dsf, idx; /* islands; its index in sp.bodies */+ uint8_t nshapes, type, flags, pad;+} Body;++/* static shapes, in the level data: their box's corner and size, their vertices as int16 pairs from the corner+ * (in quarter pixels, or half, whole or two pixels for big ones: unit in flags' bits 4-5) */+typedef struct {+ float x0, y0;+ int16_t w, h;+ uint16_t voff;+ uint8_t n, filter, mat, flags;+ uint16_t body;+} SShape;++typedef struct {+ uint16_t cb;+ uint8_t flags, pad; /* BF_SPACE */+ float viscosity, density; /* a fluid's (water) */+} SBody;++enum { C_PIVOT, C_WELD, C_DIST, C_LINE, C_ANGLE, C_MOTOR };+enum { CF_ACTIVE = 1, CF_STIFF = 2, CF_IGNORE = 4, CF_SLACK = 8, CF_EQUAL = 16 };++typedef struct Con {+ Body *b1, *b2;+ int16_t sb; /* the static body standing in for the world, or -1 (for CF_IGNORE) */+ uint8_t type, flags;+ float frequency, damping;+ V2 a1, a2, a1rel, a2rel; /* anchors (local, rotated) */+ V2 nlocal, nrel; /* line joint's direction */+ float jmin, jmax, ratio, rate, phase;+ float k[6], jacc[3], bias[3]; /* effective mass (2x2 or 3x3 symmetric), accumulated impulse, bias */+ float gamma, pre_dt, scale, cx1, cx2, dot1, dot2;+ V2 n;+ void *user;+} Con;++typedef struct {+ float r1x, r1y, r2x, r2y, lr1x, lr1y, lr2x, lr2y;+ float dist, jn, jt, nmass, tmass, bounce, friction;+ int32_t stamp;+ uint8_t hash, fresh, active, posonly;+} Contact;++enum { A_COL, A_SENSOR, A_FLUID };+enum { PT_CIRCLE, PT_FACE1, PT_FACE2 };++typedef struct Arb {+ Body *b1, *b2;+ uint16_t s1, s2; /* shape ids: static ones < 0x8000, dynamic ones | 0x8000 */+ uint8_t type, ptype, rev, nc;+ uint8_t fresh, active, present, hc2, hpc2, stat, used, pad;+ int32_t stamp, up_stamp;+ V2 n, lnorm;+ float lproj, radius, biascoef;+ float dyn, stat_f, rest, rfric;+ float jr, rmass;+ float rn1a, rn1b, rn2a, rn2b, rt1a, rt1b, rt2a, rt2b;+ float km[3], kk[3];+ union {+ Contact c[2];+ struct { /* a fluid arbiter (FluidArbiter) */+ float overlap, cx, cy, r1x, r1y, r2x, r2y, wmass, adamp, agamma, vmass[3], dampx, dampy, lgamma, nx, ny;+ uint8_t nodrag;+ } f;+ };+ int8_t c1, c2; /* the active contacts */+ int16_t next; /* free list */+} Arb;++#ifndef NP_MAX_ARBS+#define NP_MAX_ARBS 128+#endif+#define NP_MAX_EVENTS 48++typedef struct {+ uint8_t begin, type; /* begin or end, A_COL, A_SENSOR or A_FLUID */+ Body *b1, *b2; /* null: the static body sb1 / sb2 */+ int sb1, sb2; /* static bodies (-1 if dynamic) */+ float px, py; /* a collision's first contact */+} Event;++typedef struct {+ V2 gravity;+ int32_t stamp;+ /* the level's static shapes */+ const SShape *sshapes;+ int nsshapes;+ const int16_t *sverts;+ SBody *sbodies;+ int nsbodies;+ const uint16_t *buckets; /* per 256 px column: first index into bucket_list, count; then the wide shapes' */+ const uint16_t *bucket_list;+ int nbuckets, bucket_x0;+ /* dynamic and kinematic bodies */+ Body **bodies;+ int nbodies;+ Shape **shapes; /* all RAM shapes, by id */+ int nshapes;+ Con **cons;+ int ncons;+ Material *mats; /* every shape's material, by index */+ const Filter *filters;+ Arb arbs[NP_MAX_ARBS];+ int16_t free_arb;+ Event events[NP_MAX_EVENTS];+ int nevents;+ bool overflow;+} Space;++extern Space sp;++void np_reset(void);+/* a body's mass and inertia from its shapes (after changing them) */+void np_body_mass(Body *b);+void np_body_set_rot(Body *b, float r);+void np_step(float dt);+/* forget a body's or a shape's contacts (taken out of the space, or its material changed) */+void np_drop_body(Body *b);+void np_drop_shape(Shape *s);+void np_con_clear(Con *c);+void np_body_add(Body *b);+/* a static body taken out of the space: its contacts go */+void np_drop_static(int sb);+Body *np_world(void);+void np_body_remove(Body *b);+void np_wake(Body *b);+/* bodies wholly outside [x0, x1] freeze, the others thaw (BF_FROZEN) */+void np_window(float x0, float x1);+/* a body moved or turned by hand: its shapes follow, and it wakes */+void np_body_moved(Body *b);+/* registers a body (and its shapes) with the space; it enters the space with np_body_add */+void np_register(Body *b);+void np_register_con(Con *c);++static inline V2 v2(float x, float y) { V2 r = {x, y}; return r; }+static inline V2 np_local_to_world(const Body *b, V2 p) {+ return v2(b->pos.x + p.x * b->axis.y - p.y * b->axis.x, b->pos.y + p.x * b->axis.x + p.y * b->axis.y);+}+static inline V2 np_world_to_local(const Body *b, V2 p) {+ float dx = p.x - b->pos.x, dy = p.y - b->pos.y;+ return v2(dx * b->axis.y + dy * b->axis.x, dy * b->axis.y - dx * b->axis.x);+}+void np_apply_impulse(Body *b, V2 j, V2 at);+/* the first shape a ray meets (dir unit length, up to maxd): its body (or null and *sbody a static body) and its+ * distance; false if none */+bool np_raycast(V2 from, V2 dir, float maxd, Body **body, int *sbody, float *dist);+/* the bodies with a shape under a point: dynamic ones in out[], and the first static body in *sbody */+int np_bodies_under(V2 p, Body **out, int max, int *sbody);+#endifdiff --git a/games/motox3m/src/plat.h b/games/motox3m/src/plat.hnew file mode 100644index 00000000..bde9b79d--- /dev/null+++ b/games/motox3m/src/plat.h@@ -0,0 +1,40 @@+/* Moto X3M: the platform (the calculator, or a computer for tests).+ *+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.+ * plat_host.c: a frame buffer that tests save as images, scripted keys and+ * simulated time (tests/play.c). */+#ifndef MX_PLAT_H+#define MX_PLAT_H+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#define SCREEN_W 320+#define SCREEN_H 240++/* keys held now, as bits */+enum {+ K_LEFT = 1 << 0, /* Left, 4: lean back */+ K_RIGHT = 1 << 1, /* Right, 6: lean forwards */+ K_UP = 1 << 2, /* Up, 8: gas */+ K_DOWN = 1 << 3, /* Down, 2: brake */+ K_OK = 1 << 4, /* OK, EXE, 5: choose, go on after a crash */+ K_BACK = 1 << 5, /* Back: pause, back a screen */+ K_HOME = 1 << 6, /* Home, On/Off: save and quit */+ K_ANY = 1 << 7+};+uint32_t plat_keys(void);+uint32_t plat_millis(void);+void plat_sleep(uint32_t ms);+void plat_push(int x, int y, int w, int h, const uint16_t *px);+bool plat_save(const char *name, const void *data, uint32_t len);+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */+/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its bytes,+ * plat_reserved says they are written; NULL if there is no room */+uint8_t *plat_reserve(const char *name, uint32_t len);+void plat_reserved(const char *name, uint32_t len);+bool plat_remove(const char *name);+void plat_begin(void);+int plat_end(void);+bool plat_slow(void); /* an N0110 or N0115 (216 MHz, the N0120 has 550) */+#endifdiff --git a/games/motox3m/src/plat_eadk.c b/games/motox3m/src/plat_eadk.cnew file mode 100644index 00000000..c0c5e6aa--- /dev/null+++ b/games/motox3m/src/plat_eadk.c@@ -0,0 +1,38 @@+/* The calculator: EADK display, keyboard, time and files. */+#include <eadk.h>+#include "../../common/epsilon_app.h"+#include "../../common/epsilon_files.h"+#include "plat.h"++#define KEY(k) ((uint64_t)1 << (k))++uint32_t plat_keys(void) {+ uint64_t k = eadk_keyboard_scan();+ uint32_t r = 0;+ if (k & (KEY(eadk_key_left) | KEY(eadk_key_four))) r |= K_LEFT;+ if (k & (KEY(eadk_key_right) | KEY(eadk_key_six))) r |= K_RIGHT;+ if (k & (KEY(eadk_key_up) | KEY(eadk_key_eight))) r |= K_UP;+ if (k & (KEY(eadk_key_down) | KEY(eadk_key_two))) r |= K_DOWN;+ if (k & (KEY(eadk_key_ok) | KEY(eadk_key_exe) | KEY(eadk_key_five))) r |= K_OK;+ if (k & KEY(eadk_key_back)) r |= K_BACK;+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;+ if (k) r |= K_ANY;+ return r;+}++uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);+}+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }+uint8_t *plat_reserve(const char *name, uint32_t len) {+ uint32_t n;+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */+}+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }+bool plat_remove(const char *name) { return ef_remove(name); }+void plat_begin(void) { np_app_begin(); }+int plat_end(void) { return np_app_end(); }+bool plat_slow(void) { return epsilon_slow_model(); }diff --git a/games/motox3m/src/plat_host.c b/games/motox3m/src/plat_host.cnew file mode 100644index 00000000..91a01972--- /dev/null+++ b/games/motox3m/src/plat_host.c@@ -0,0 +1,70 @@+/* A computer: the screen goes to a frame buffer that tests save as images,+ * keys come from a script, time is simulated. */+#include <stdio.h>+#include <stdlib.h>+#include "plat.h"++uint16_t host_fb[SCREEN_W * SCREEN_H];+uint32_t host_time; /* ms */+uint32_t host_keys;++uint32_t plat_keys(void) { return host_keys; }+uint32_t plat_millis(void) { return host_time; }+void plat_sleep(uint32_t ms) { host_time += ms; }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ for (int r = 0; r < h; r++)+ for (int c = 0; c < w; c++)+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];+}++static char save_dir[256] = "build/host-saves";+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }+bool plat_save(const char *name, const void *data, uint32_t len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "wb");+ if (!f) return false;+ bool ok = fwrite(data, 1, len, f) == len;+ fclose(f);+ return ok;+}+/* (each file read gets its own buffer: callers may hold two at once) */+static uint8_t loaded[4][1 << 16];+static int next_load;+const uint8_t *plat_load(const char *name, uint32_t *len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "rb");+ if (!f) return NULL;+ uint8_t *b = loaded[next_load++ & 3];+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);+ fclose(f);+ return b;+}+static uint8_t reserved[1 << 16];+uint8_t *plat_reserve(const char *name, uint32_t len) {+ (void)name;+ return len <= sizeof reserved ? reserved : NULL;+}+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }+bool plat_remove(const char *name) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ return remove(p) == 0;+}+void plat_begin(void) {}+int plat_end(void) { return 0; }+bool plat_slow(void) { return false; }++/* writes the screen as a PPM image */+void host_shot(const char *path) {+ FILE *f = fopen(path, "wb");+ if (!f) return;+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {+ uint16_t c = host_fb[i];+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};+ fwrite(rgb, 1, 3, f);+ }+ fclose(f);+}diff --git a/games/motox3m/src/res.c b/games/motox3m/src/res.cnew file mode 100644index 00000000..9c0a5e85--- /dev/null+++ b/games/motox3m/src/res.c@@ -0,0 +1,17 @@+/* Moto X3M: the pictures, fonts and levels in data.bin: "MX3D", their counts, then where each one starts. */+#include "res.h"++static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }++const Pic *pic(int id) {+ if (id < 0 || id >= N_PICS) return 0;+ return (const Pic *)(const void *)(mx_data + rd32(mx_data + 16 + 4 * id));+}++const Font *font(int id) {+ return (const Font *)(const void *)(mx_data + rd32(mx_data + 16 + 4 * (N_PICS + id)));+}++const LevelHdr *level(int n) {+ return (const LevelHdr *)(const void *)(mx_data + rd32(mx_data + 16 + 4 * (N_PICS + N_FONTS + n)));+}diff --git a/games/motox3m/src/res.h b/games/motox3m/src/res.hnew file mode 100644index 00000000..8bb904a7--- /dev/null+++ b/games/motox3m/src/res.h@@ -0,0 +1,108 @@+/* Moto X3M: the pictures, fonts and levels in data.bin (tools/pack.py). */+#ifndef MX_RES_H+#define MX_RES_H+#include <stdint.h>+#include "data.h"+#include "nape.h"++extern const uint8_t mx_data[];++/* a picture: its colours (RGB565, then alpha 0-255), then a byte a pixel, or two (IMG_4BIT, high bits first) */+typedef struct {+ uint16_t w, h;+ float px, py; /* its pivot */+ uint16_t ncolors;+ uint8_t flags, pad;+} Pic;+enum { IMG_TILE = 1, IMG_OPAQUE = 2, IMG_4BIT = 4 };++const Pic *pic(int id);+static inline const uint16_t *pic_pal(const Pic *p) { return (const uint16_t *)(const void *)(p + 1); }+static inline const uint8_t *pic_alpha(const Pic *p) { return (const uint8_t *)(pic_pal(p) + p->ncolors); }+static inline const uint8_t *pic_px(const Pic *p) {+ uintptr_t a = (uintptr_t)(pic_alpha(p) + p->ncolors);+ return (const uint8_t *)((a + 3) & ~(uintptr_t)3);+}+static inline int pic_stride(const Pic *p) { return p->flags & IMG_4BIT ? (p->w + 1) >> 1 : p->w; }+static inline unsigned pic_at(const Pic *p, const uint8_t *px, int x, int y) {+ if (p->flags & IMG_4BIT) {+ uint8_t b = px[y * ((p->w + 1) >> 1) + (x >> 1)];+ return x & 1 ? b & 15 : b >> 4;+ }+ return px[y * p->w + x];+}++typedef struct {+ uint8_t w, h;+ int8_t x, y; /* from the pen; y from the baseline */+ uint8_t adv, pad0;+ uint16_t pad1;+ uint32_t off; /* 4-bit coverage, two pixels a byte */+} Glyph;+typedef struct {+ uint8_t first, count, height, ascent;+} Font;+const Font *font(int id);+static inline const Glyph *font_glyphs(const Font *f) { return (const Glyph *)(const void *)(f + 1); }+static inline const uint8_t *font_bits(const Font *f) { return (const uint8_t *)(font_glyphs(f) + f->count); }++/* ---- levels ---- */++typedef struct {+ uint8_t theme, nmats, pad0, pad1;+ uint16_t nobj, nsshapes, nsbodies, ndbodies, ndshapes, nbuckets, ndraws, ncams, naux, pad2;+ float gravity, prize[3], startx, starty, finishx, bucket_x0;+ uint32_t off[15]; /* mats, sshapes, sverts, sbodies, buckets, blist, dbodies, dshapes, ddata, objs, aux, draws,+ dpts, params, cams */+} LevelHdr;+enum { L_MATS, L_SSHAPES, L_SVERTS, L_SBODIES, L_BUCKETS, L_BLIST, L_DBODIES, L_DSHAPES, L_DDATA, L_OBJS, L_AUX,+ L_DRAWS, L_DPTS, L_PARAMS, L_CAMS };++typedef struct {+ uint16_t cb;+ uint8_t flags, pad;+ float viscosity, density;+} SBodyRec;++typedef struct {+ float x, y, rot;+ uint16_t first_shape;+ uint8_t nshapes, type; /* 1 dynamic, 2 kinematic */+ uint16_t cb;+ uint8_t flags, pad; /* BF_NOROT */+} DBodyRec;++typedef struct {+ uint8_t type, n, filter, flags, mat, pad[3]; /* type 0 circle, 1 polygon */+ float radius, cx, cy, area, inertia;+ uint32_t off; /* local vertices in ddata */+} DShapeRec;++enum { O_GROUND, O_SHAPER, O_PLANK, O_DYN, O_REMOVED, O_TNT, O_SPIKES, O_TOGGLE, O_SAFE, O_FINISH, O_MOVER, O_MOTOR,+ O_PIVOT, O_DECOR, O_WATER, O_GEYSER, O_BOOST, O_GLASS };++typedef struct {+ uint8_t type, flags;+ int16_t id, id2, body, sbody, body2;+ uint16_t img, naux, aux, params;+ float x, y, rot;+} ObjRec;++enum { D_POLY, D_STRIP, D_SPRITE, D_WATER };+enum { C_SHAPES, C_LAND, C_OBJ, C_FRONT };+typedef struct {+ uint8_t kind, cont, flags, back;+ int16_t owner; /* the object whose body carries it, or -1 */+ uint16_t n, img, pts, params;+ int16_t minx, miny, maxx, maxy;+ uint16_t pad;+} DrawRec;++typedef struct {+ uint16_t pts, n;+ float dy;+} CamRec;++const LevelHdr *level(int n); /* 0-based */+static inline const void *lvl_at(const LevelHdr *l, int part) { return (const uint8_t *)l + l->off[part]; }+#endifdiff --git a/games/motox3m/src/ui.c b/games/motox3m/src/ui.cnew file mode 100644index 00000000..a7b69351--- /dev/null+++ b/games/motox3m/src/ui.c@@ -0,0 +1,263 @@+/* Moto X3M: the HUD and the menus, drawn a band at a time (GameplayState's popups, ChooseZone, Garage, Menu). */+#include <math.h>+#include <stdio.h>+#include <string.h>+#include "bike.h"+#include "data.h"+#include "fx.h"+#include "game.h"+#include "gfx.h"+#include "level.h"+#include "view.h"++#define ORANGE 0xFC60 /* #FF8F00 */+#define WHITE 0xFFFF+#define BLACK 0x0000+#define GREY 0xDEDA /* #DDD9D7 */++const int *shop_prices(void);++static void fmt_time(char *s, float t, bool pad2) {+ int w = (int)ceilf(100 * t);+ if (w < 0) w = 0;+ int p = w / 100;+ w -= 100 * p;+ if (pad2) snprintf(s, 16, "%02d.%02d", p, w);+ else snprintf(s, 16, "%d.%02d", p, w);+}++/* text in the game's titles' look: an outline, then the letters */+static void title(int font, float x, float y, const char *s, uint16_t c, int align) {+ gfx_text(font, x, y, s, c, WHITE, 2, align);+ gfx_text(font, x, y, s, c, BLACK, 1, align);+}++static void bike_pose(int layout, float cx, float cy, float scale) {+ for (int i = 0; i < 11; i++) {+ const BikePart *p = &BIKE_LAYOUT[layout][i];+ gfx_pic(p->pic, cx + p->x * 0.25f * scale, cy + p->y * 0.25f * scale, scale, scale, p->deg * 0.0174533f, 256);+ }+}++static void button(int pic_id, int icon, float x, float y, bool sel) {+ float k = sel ? 0.84f + 0.04f * sinf(view_ticks * 0.3f) : 0.8f;+ gfx_pic(pic_id, x, y, k, k, 0, sel ? 256 : 200);+ if (icon >= 0) gfx_pic(icon, x, y - 3 * k, k, k, 0, 256);+ if (sel) {+ const Pic *p = pic(pic_id);+ float w = p->w * k, h = p->h * k;+ gfx_fill((int)(x - w / 3), (int)(y + h / 2 - 4), (int)(w * 2 / 3), 2, ORANGE, 256);+ }+}++/* ---- in a run ---- */++static void hud(void) {+ char s[24];+ gfx_pic(PIC_UI_TIMER_BG, 160, 12, 1, 1, 0, 256);+ fmt_time(s, g.timer, true);+ gfx_text(FONT_SMALL, 159, 17, s, GREY, BLACK, 0, 0);+ snprintf(s, sizeof s, "#%d", g.level + 1);+ gfx_text(FONT_SMALL, 6, 15, s, GREY, BLACK, 1, 0);+ if (g.flip_t < 1.1f && !bike.finished) {+ char a[16], b[16];+ if (g.flip_n > 1) snprintf(a, sizeof a, "FLIP %dX", g.flip_n);+ else snprintf(a, sizeof a, "FLIP");+ float d = 0.5f * g.flip_n;+ if (d == (int)d) snprintf(b, sizeof b, "-%d sec", (int)d);+ else snprintf(b, sizeof b, "-%d.5 sec", (int)d);+ title(FONT_BIG, 160, 50, a, ORANGE, 1);+ gfx_text(FONT_MID, 160, 66, b, ORANGE, BLACK, 1, 1);+ }+ if (g.help) {+ gfx_fill(70, 200, 180, 26, BLACK, 180);+ gfx_pic(PIC_UI_ARROWS + (int)(view_ticks / 15 % 2), 76, 199, 0.85f, 0.85f, 0, 256);+ gfx_text(FONT_SMALL, 128, 218, "Use arrows to move", WHITE, BLACK, 0, 0);+ } else if (bike.dead && !bike.finished && g.dead_t > 0.3f) {+ gfx_fill(70, 200, 180, 22, BLACK, 180);+ gfx_text(FONT_SMALL, 160, 215, "Press OK to continue", WHITE, BLACK, 0, 1);+ }+}++static void popup_back(void) {+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK, 110);+ gfx_pic(PIC_UI_0POPUP_BG, 160, 124, 0.95f, 1.05f, 0, 256);+}++static void pause_menu(void) {+ popup_back();+ title(FONT_BIG, 160, 46, g.confirm ? "QUIT GAME?" : "GAME PAUSED", WHITE, 1);+ if (g.confirm) {+ bike_pose(0, 160, 120, 0.8f);+ const char *opts[2] = {"YES", "NO"};+ for (int i = 0; i < 2; i++) {+ bool sel = g.sel == i;+ float x = i ? 205 : 115;+ title(FONT_MID, x, 196, opts[i], sel ? ORANGE : WHITE, 1);+ if (sel) gfx_fill((int)x - 18, 200, 36, 2, ORANGE, 256);+ }+ return;+ }+ bike_pose(0, 110, 128, 0.8f);+ static const char *items[4] = {"RESUME", "RESTART", "LEVELS", "QUIT GAME"};+ for (int i = 0; i < 4; i++) {+ bool sel = g.sel == i;+ float y = 92 + i * 26;+ title(FONT_MID, 205, y, items[i], sel ? ORANGE : WHITE, 1);+ if (sel) gfx_fill(170, (int)y + 4, 70, 2, ORANGE, 256);+ }+}++static void star(float x, float y, float sc, float ang, bool on, float age) {+ gfx_pic(PIC_UI_STAR0, x, y, sc, sc, ang, 256);+ if (on && age >= 0) {+ /* comes down from three times its size */+ float t = age / 0.4f, k = t >= 1 ? sc : sc * (3 - 2 * t);+ gfx_pic(PIC_UI_STAR1, x, y, k, k, ang, t >= 1 ? 256 : (int)(256 * t));+ }+}++static void finish_menu(void) {+ char s[40], t[16];+ popup_back();+ snprintf(s, sizeof s, g.level + 1 < 10 ? "LEVEL 0%d COMPLETE" : "LEVEL %d COMPLETE", g.level + 1);+ title(FONT_BIG, 160, 30, s, ORANGE, 1);+ /* stars: the times for one, two and three */+ float a = g.finish_t - 0.2f;+ float times[3] = {lv.h->prize[2], lv.h->prize[1], lv.h->prize[0]};+ float xs[3] = {94, 160, 226}, ys[3] = {82, 76, 82}, ang[3] = {-0.1745f, 0, 0.1745f}, sc[3] = {0.8f, 0.9f, 0.8f};+ float ages[3] = {a, a - 0.4f, a - 1.1f};+ for (int i = 0; i < 3; i++) {+ star(xs[i], ys[i], sc[i], ang[i], g.stars > i, ages[i]);+ snprintf(t, sizeof t, "%d sec.", (int)times[i]);+ gfx_text(FONT_SMALL, xs[i], ys[i] + 40 - (i == 1 ? 4 : 0), t, GREY, BLACK, 1, 1);+ }+ fmt_time(t, g.result, false);+ snprintf(s, sizeof s, "Your time: %s sec.", t);+ gfx_text(FONT_SMALL, 160, 143, s, GREY, BLACK, 1, 1);+ if (g.improved) {+ gfx_pic(PIC_UI_IMPROVED_BG, 266, 150, 0.8f, 0.8f, 0.4363f, 256);+ gfx_text(FONT_SMALL, 264, 147, "NEW BEST", WHITE, BLACK, 1, 1);+ gfx_text(FONT_SMALL, 268, 158, "TIME", WHITE, BLACK, 1, 1);+ }+ button(PIC_UI_ORANGE_BTN, PIC_UI_EXIT_BTN, 44, 214, g.sel == 0);+ button(PIC_UI_ORANGE_BTN, PIC_UI_NEXT_BTN, 276, 214, g.sel == 1);+ {+ bool sel = g.sel == 2;+ float k = sel ? 0.92f + 0.03f * sinf(view_ticks * 0.3f) : 0.9f;+ gfx_pic(PIC_UI_ORANGE_BTN_BIG, 160, 196, k, k, 0, sel ? 256 : 200);+ title(FONT_MID, 160, 200, "CHANGE BIKE", WHITE, 1);+ if (sel) gfx_fill(108, 216, 104, 2, ORANGE, 256);+ }+}++/* ---- menus ---- */++static void title_screen(void) {+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK, 256);+ gfx_pic(PIC_UI_0POPUP_BG, 230, 60, 0.6f, 0.7f, 0, 256);+ gfx_pic(PIC_UI_0POPUP_BG, 230, 190, 0.6f, 0.7f, 0, 256);+ gfx_pic(PIC_UI_LOGO, 92, 70, 1, 1, 0, 256);+ bike_pose(0, 92, 190, 0.9f);+ static const char *items[3] = {"PLAY", "BIKE SHOP", "HOW TO PLAY"};+ for (int i = 0; i < 3; i++) {+ bool sel = g.sel == i;+ float y = i == 0 ? 112 : i == 1 ? 160 : 196;+ title(i ? FONT_BIG : FONT_HUGE, 232, y, items[i], sel ? ORANGE : WHITE, 1);+ if (sel) gfx_fill(176, (int)y + 6, 112, 3, ORANGE, 256);+ }+ char s[16];+ snprintf(s, sizeof s, "%d", total_stars());+ gfx_pic(PIC_UI_W_STAR, 298, 18, 1, 1, 0, 256);+ gfx_text(FONT_MID, 284, 24, s, WHITE, BLACK, 1, 2);+}++static void map_screen(void) {+ const Pic *bg = pic(PIC_UI_MAPBG);+ /* keep the chosen level in view */+ float want = MAP_PTS[g.map_sel][0] * 0.5f - 160;+ float maxx = bg->w - SCREEN_W;+ if (want < 0) want = 0;+ if (want > maxx) want = maxx;+ if (gfx_y0 == 0) {+ g.map_x += (want - g.map_x) * 0.3f;+ if (fabsf(want - g.map_x) < 0.5f) g.map_x = want;+ }+ gfx_pic_at(PIC_UI_MAPBG, -floorf(g.map_x), 0, 1, 256);+ for (int i = 0; i < NLEVELS; i++) {+ float x = MAP_PTS[i][0] * 0.5f - floorf(g.map_x), y = MAP_PTS[i][1] * 0.5f;+ if (x < -30 || x > SCREEN_W + 30) continue;+ bool open = save.stars[i] != 0xFF, sel = i == g.map_sel;+ float k = sel ? 1.05f + 0.05f * sinf(view_ticks * 0.25f) : 1;+ gfx_pic(PIC_UI_MAP, x, y, k, k, 0, 256);+ gfx_pic(PIC_UI_MAP + (open ? save.stars[i] + 2 : 1), x, y, k, k, 0, 256);+ if (open) {+ char s[4];+ snprintf(s, sizeof s, "%02d", i + 1);+ gfx_text(FONT_MID, x, y + 2, s, sel ? ORANGE : WHITE, BLACK, 1, 1);+ }+ }+ /* the top bar: stars; the bottom: the keys */+ gfx_pic(PIC_UI_TOP_BG, 0, 0, 1, 1, 0, 256);+ char s[16];+ snprintf(s, sizeof s, "%d", total_stars());+ gfx_pic(PIC_UI_W_STAR, 18, 16, 0.8f, 0.8f, 0, 256);+ gfx_text(FONT_MID, 34, 22, s, WHITE, BLACK, 1, 0);+ gfx_fill(0, 222, SCREEN_W, 18, BLACK, 170);+ gfx_text(FONT_SMALL, 160, 235, "Arrows choose OK ride Back menu", WHITE, BLACK, 0, 1);+}++static void shop_screen(void) {+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK, 256);+ gfx_pic(PIC_UI_0POPUP_BG, 160, 120, 0.95f, 1.1f, 0, 256);+ title(FONT_HUGE, 160, 40, "BIKE SHOP", ORANGE, 1);+ char s[24];+ snprintf(s, sizeof s, "%d", total_stars());+ gfx_pic(PIC_UI_W_STAR, 300, 18, 1, 1, 0, 256);+ gfx_text(FONT_MID, 286, 24, s, WHITE, BLACK, 1, 2);+ int k = g.shop_sel;+ bike_pose(k + 1, 160, 120, 1.2f);+ if (k > 0) gfx_pic(PIC_UI_ARROW_BTN, 22, 120, -1, 1, 0, 256);+ if (k < NSKINS - 1) gfx_pic(PIC_UI_ARROW_BTN, 298, 120, 1, 1, 0, 256);+ bool owned = save.owned & (1 << k), equipped = save.skin == k + 1;+ gfx_pic(equipped ? PIC_UI_ORANGE_BTN_BIG_GREEN : PIC_UI_ORANGE_BTN_BIG, 160, 214, 0.45f, 0.45f, 0, 256);+ title(FONT_MID, 160, 219, equipped ? "EQUIPPED" : "EQUIP IT", WHITE, 1);+ if (!owned) {+ int price = shop_prices()[k];+ if (price) {+ snprintf(s, sizeof s, "PRICE: %d", price);+ int w = gfx_text(FONT_MID, 152, 188, s, total_stars() >= price ? WHITE : GREY, BLACK, 1, 1);+ gfx_pic(PIC_UI_W_STAR, 152 + w / 2 + 12, 182, 0.7f, 0.7f, 0, 256);+ } else title(FONT_MID, 160, 188, "FREE", WHITE, 1);+ }+}++static void help_screen(void) {+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BLACK, 256);+ gfx_pic(PIC_UI_0POPUP_BG, 160, 124, 0.95f, 1.1f, 0, 256);+ title(FONT_BIG, 160, 34, "HOW TO PLAY", ORANGE, 1);+ static const char *keys[] = {"Up", "Down", "Left, Right", "Back", "OK"};+ static const char *what[] = {"gas", "brake", "lean, flip in the air", "pause", "go on after a crash"};+ for (int i = 0; i < 5; i++) {+ gfx_text(FONT_SMALL, 150, 66 + i * 17, keys[i], ORANGE, BLACK, 1, 2);+ gfx_text(FONT_SMALL, 162, 66 + i * 17, what[i], WHITE, BLACK, 1, 0);+ }+ gfx_text(FONT_SMALL, 160, 168, "Each flip takes half a second off your time.", WHITE, BLACK, 1, 1);+ gfx_text(FONT_SMALL, 160, 184, "Beat a level's times for stars.", WHITE, BLACK, 1, 1);+ gfx_text(FONT_SMALL, 160, 198, "More stars open new bikes.", WHITE, BLACK, 1, 1);+}++void ui_draw(void) {+ switch (g.state) {+ case S_TITLE: title_screen(); break;+ case S_HELP: help_screen(); break;+ case S_MAP: map_screen(); break;+ case S_SHOP: shop_screen(); break;+ default:+ view_draw_world();+ if (g.state == S_PLAY) hud();+ else if (g.state == S_PAUSE) pause_menu();+ else if (g.state == S_FINISH) finish_menu();+ break;+ }+}diff --git a/games/motox3m/src/view.c b/games/motox3m/src/view.cnew file mode 100644index 00000000..bed4e25d--- /dev/null+++ b/games/motox3m/src/view.c@@ -0,0 +1,365 @@+/* Moto X3M: the level and the bike on the screen (MaxGameView: background, landscape, objects, front). */+#include <math.h>+#include <string.h>+#include "bike.h"+#include "bike_data.h"+#include "fx.h"+#include "gfx.h"+#include "level.h"+#include "view.h"++#define TEX_SCALE 0.5f /* pictures are kept at half the game's size */+#define MAXPTS 300++static float *scr; /* 2 * (MAXPTS + 4) floats, on main's stack */+static float bg_dx;+uint32_t view_ticks;++/* the drawings in view this frame, with their transform */+typedef struct {+ uint16_t d;+ int16_t y0, y1;+ float ox, oy, c, s; /* local to world */+} Vis;+static Vis *vis; /* VIEW_MAXVIS of them, on main's stack */+static int nvis;+#define MAXVIS VIEW_MAXVIS+_Static_assert(sizeof(Vis) * VIEW_MAXVIS <= VIEW_VIS_BYTES, "the drawings in view need more room");++void view_init(void *visbuf, float *scrbuf) {+ vis = visbuf;+ scr = scrbuf;+}++static inline float sx(float x) { return (x - cam.px) * cam.scale + SCREEN_W / 2 + cam.shx; }+static inline float sy(float y) { return (y - cam.py) * cam.scale + SCREEN_H / 2 + cam.shy; }++void view_reset(void) { bg_dx = 0; }++static const Obj *owner_of(const DrawRec *d) { return d->owner >= 0 ? &lv.objs[d->owner] : 0; }++/* where an owned drawing is: its object's body, or the object's place */+static void pose(const DrawRec *d, float *ox, float *oy, float *c, float *s) {+ const Obj *o = owner_of(d);+ if (!o || (d->kind == D_SPRITE && !o->body)) {+ *ox = *oy = 0, *c = 1, *s = 0;+ return;+ }+ if (o->body) {+ *ox = o->body->pos.x, *oy = o->body->pos.y, *c = o->body->axis.y, *s = o->body->axis.x;+ } else if (d->kind == D_SPRITE) {+ *ox = *oy = 0, *c = 1, *s = 0;+ } else {+ *ox = o->r->x, *oy = o->r->y, *c = cosf(o->r->rot), *s = sinf(o->r->rot);+ }+}++static bool hidden(const DrawRec *d) {+ const Obj *o = owner_of(d);+ if (!o) return false;+ if (o->hidden) return true;+ if (o->body && !(o->body->flags & BF_SPACE) && o->r->type != O_SHAPER && o->r->type != O_PLANK) return true;+ return false;+}++void view_prepare(void) {+ cam.shx = fx_shake_x(), cam.shy = fx_shake_y();+ nvis = 0;+ const DrawRec *ds = lv.draws;+ for (int i = 0; i < lv.h->ndraws && nvis < MAXVIS; i++) {+ const DrawRec *d = &ds[i];+ if (hidden(d)) continue;+ float ox, oy, c, s;+ pose(d, &ox, &oy, &c, &s);+ float x0, y0, x1, y1;+ if (d->kind == D_SPRITE) {+ const float *p = lv.params + d->params;+ const Pic *pc = pic(d->img);+ float r = (pc ? (float)(pc->w > pc->h ? pc->w : pc->h) : 16) / TEX_SCALE * fmaxf(fabsf(p[3]), fabsf(p[4]));+ float px = p[0], py = p[1];+ x0 = ox + px * c - py * s, y0 = oy + px * s + py * c;+ x1 = x0 + r, y1 = y0 + r, x0 -= r, y0 -= r;+ } else {+ float cx = 0.5f * (d->minx + d->maxx), cy = 0.5f * (d->miny + d->maxy);+ float r = 0.5f * hypotf((float)(d->maxx - d->minx), (float)(d->maxy - d->miny)) + 64;+ float wx = ox + cx * c - cy * s, wy = oy + cx * s + cy * c;+ x0 = wx - r, x1 = wx + r, y0 = wy - r, y1 = wy + r;+ }+ if (x1 < cam.x - 16 || x0 > cam.x + cam.w + 16 || y1 < cam.y - 16 || y0 > cam.y + cam.h + 16) continue;+ float ya = sy(y0), yb = sy(y1);+ if (yb < 0 || ya > SCREEN_H) continue;+ Vis *v = &vis[nvis++];+ v->d = (uint16_t)i, v->y0 = (int16_t)fmaxf(-1000, ya), v->y1 = (int16_t)fminf(1000, yb);+ v->ox = ox, v->oy = oy, v->c = c, v->s = s;+ }+}++/* ---- background ---- */++void view_bg_scroll(float target_x) {+ (void)target_x;+}++static void draw_bg(void) {+ int t = lv.h->theme;+ gfx_pic_at(PIC_BG[t][0], 0, 0, 1, 256);+ for (int k = 1; k < 3; k++) {+ int id = PIC_BG[t][k];+ if (id == 0xFFFF) continue;+ const Pic *p = pic(id);+ float part = k == 1 ? -0.2f : -0.4f, y = k == 1 ? 125 : 135;+ if (!gfx_rows(y, y + p->h)) continue;+ float e = bike.x + bg_dx;+ float n = fmodf(-e * part, (float)p->w);+ float x0 = -n;+ for (int i = 0; i < 6; i++) gfx_pic_at(id, floorf(x0 + i * (p->w - 1)), y, 1, 256);+ }+}++/* ---- the level's drawings ---- */++static int to_screen(const Vis *v, const DrawRec *d) {+ const int16_t *q = lv.dpts + 2 * d->pts;+ int n = d->n > MAXPTS ? MAXPTS : d->n;+ for (int i = 0; i < n; i++) {+ float lx = q[2 * i], ly = q[2 * i + 1];+ float wx = v->ox + lx * v->c - ly * v->s, wy = v->oy + lx * v->s + ly * v->c;+ scr[2 * i] = sx(wx), scr[2 * i + 1] = sy(wy);+ }+ return n;+}++/* screen to the drawing's own coordinates, then to its picture: (local - origin) * k */+static Map local_map(const Vis *v, float ox, float oy, float k) {+ /* screen -> world: w = (s - centre) / scale + cam */+ float is = 1 / cam.scale;+ float cx = SCREEN_W / 2 + cam.shx, cy = SCREEN_H / 2 + cam.shy;+ /* world -> local: rotate by -angle about (ox, oy) of the pose */+ Map m;+ float c = v->c, s = v->s;+ /* lx = (wx - px) * c + (wy - py) * s ; ly = -(wx - px) * s + (wy - py) * c */+ float ax = -cx * is + cam.px - v->ox, ay = -cy * is + cam.py - v->oy;+ m.ux = is * c * k, m.uy = is * s * k, m.u0 = (ax * c + ay * s - ox) * k;+ m.vx = -is * s * k, m.vy = is * c * k, m.v0 = (-ax * s + ay * c - oy) * k;+ return m;+}++static void draw_poly(const Vis *v, const DrawRec *d) {+ int n = to_screen(v, d);+ const Pic *p = pic(d->img);+ if (!p) return;+ const float *pr = lv.params + d->params;+ Map m = local_map(v, pr[0], pr[1], TEX_SCALE);+ gfx_poly_pic(scr, n, p, &m, true, 256);+}++/* a strip: the picture repeated along the line, its height across it (Drawing.drawBitmapPath2; ropes the same) */+static void draw_strip(const Vis *v, const DrawRec *d) {+ const Pic *p = pic(d->img);+ if (!p) return;+ const int16_t *q = lv.dpts + 2 * d->pts;+ float tw = p->w / TEX_SCALE, th = p->h / TEX_SCALE;+ bool rope = lv.params[d->params] != 0;+ float along = 0;+ float margin = th * cam.scale;+ float b0 = gfx_y0 - margin, b1 = gfx_y0 + BAND + margin;+ for (int i = 0; i + 1 < d->n; i++) {+ float ax = q[2 * i], ay = q[2 * i + 1], bx = q[2 * i + 2], by = q[2 * i + 3];+ float dx = bx - ax, dy = by - ay, len = sqrtf(dx * dx + dy * dy);+ if (len <= 0) continue;+ {+ /* only the segments that reach this band's rows and the screen */+ float y0 = sy(v->oy + ax * v->s + ay * v->c), y1 = sy(v->oy + bx * v->s + by * v->c);+ float x0 = sx(v->ox + ax * v->c - ay * v->s), x1 = sx(v->ox + bx * v->c - by * v->s);+ if ((y0 < b0 && y1 < b0) || (y0 > b1 && y1 > b1) || (x0 < -margin && x1 < -margin) ||+ (x0 > SCREEN_W + margin && x1 > SCREEN_W + margin)) {+ along += len;+ continue;+ }+ }+ float ux = dx / len, uy = dy / len, nx = -uy * th / 2, ny = ux * th / 2;+ /* pieces of the picture's width */+ float t = 0;+ while (t < len - 0.01f) {+ float step = rope ? len - t : fminf(tw, len - t);+ float x0 = ax + ux * t, y0 = ay + uy * t, x1 = x0 + ux * step, y1 = y0 + uy * step;+ float wq[8] = {x0 - nx, y0 - ny, x1 - nx, y1 - ny, x1 + nx, y1 + ny, x0 + nx, y0 + ny};+ float lo = 1e9f, hi = -1e9f;+ for (int k = 0; k < 4; k++) {+ float lx = wq[2 * k], ly = wq[2 * k + 1];+ float wx = v->ox + lx * v->c - ly * v->s, wy = v->oy + lx * v->s + ly * v->c;+ scr[2 * k] = sx(wx), scr[2 * k + 1] = sy(wy);+ if (scr[2 * k + 1] < lo) lo = scr[2 * k + 1];+ if (scr[2 * k + 1] > hi) hi = scr[2 * k + 1];+ }+ if (gfx_rows(lo, hi)) {+ /* the piece's own axes: u along (from x0), v across (from the top edge) */+ Vis pv = *v;+ float c = v->c * ux - v->s * uy, s = v->s * ux + v->c * uy;+ float tx = x0 - nx, ty = y0 - ny;+ pv.ox = v->ox + tx * v->c - ty * v->s, pv.oy = v->oy + tx * v->s + ty * v->c;+ pv.c = c, pv.s = s;+ float k = rope ? TEX_SCALE : TEX_SCALE * (step < tw ? tw / step : 1);+ Map m = local_map(&pv, rope ? -fmodf(along + t, tw) : 0, 0, TEX_SCALE);+ if (!rope && step < tw) m.ux *= k / TEX_SCALE, m.uy *= k / TEX_SCALE, m.u0 *= k / TEX_SCALE;+ gfx_poly_pic(scr, 4, p, &m, true, 256);+ }+ t += step;+ }+ along += len;+ }+}++static int anim_frame(const DrawRec *d, int frames) {+ const Obj *o = owner_of(d);+ if (frames <= 1) return 0;+ if (d->flags & 1) return (int)(view_ticks % (uint32_t)frames); /* Dec12: always */+ if (o && o->r->type == O_SAFE) {+ if (!o->active) return 0;+ int f = (int)(o->t1 * 30);+ return f < frames ? f : frames - 1;+ }+ return (int)(view_ticks % (uint32_t)frames);+}++static void draw_sprite(const Vis *v, const DrawRec *d) {+ const float *p = lv.params + d->params;+ const Obj *o = owner_of(d);+ float wx = v->ox + p[0] * v->c - p[1] * v->s, wy = v->oy + p[0] * v->s + p[1] * v->c;+ float ang = atan2f(v->s, v->c) + p[2];+ int frame = anim_frame(d, (int)p[5]);+ int alpha = 256;+ if (o && o->r->type == O_REMOVED) alpha = (int)(o->alpha * 256);+ float k = cam.scale / TEX_SCALE;+ gfx_pic(d->img + frame, sx(wx), sy(wy), k * p[3], k * p[4], ang, alpha);+}++static void draw_water(const Vis *v, const DrawRec *d) {+ /* WaterShape: blue at 40 %, its top edge waving by 4 px every 16 px, a light line on it */+ const int16_t *q = lv.dpts + 2 * d->pts;+ int n = 0;+ float x0 = q[0], y0 = q[1], wdx = q[2] - q[0];+ int c = (int)(wdx / 16);+ if (c < 1) c = 1;+ float u = wdx / c;+ float tmp[2 * (MAXPTS + 40)];+ tmp[2 * n] = x0, tmp[2 * n + 1] = y0, n++;+ for (int i = 0; i < c && n < MAXPTS + 30; i++) {+ float dd = (i + 1) * u;+ tmp[2 * n] = x0 + dd, tmp[2 * n + 1] = y0 + 4 * sinf(0.05f * (lv.wave + dd)), n++;+ }+ int top = n;+ for (int i = 2; i < d->n && n < MAXPTS + 38; i++) tmp[2 * n] = q[2 * i], tmp[2 * n + 1] = q[2 * i + 1], n++;+ for (int i = 0; i < n; i++) {+ float lx = tmp[2 * i], ly = tmp[2 * i + 1];+ float wx = v->ox + lx * v->c - ly * v->s, wy = v->oy + lx * v->s + ly * v->c;+ tmp[2 * i] = sx(wx), tmp[2 * i + 1] = sy(wy);+ }+ gfx_poly_color(tmp, n, rgb565(0x0087FF), 102);+ float w = 2 * cam.scale;+ for (int i = 0; i + 1 < top; i++)+ gfx_line(tmp[2 * i], tmp[2 * i + 1], tmp[2 * i + 2], tmp[2 * i + 3], w < 1 ? 1 : w, rgb565(0xBFE1FF), 256);+}++static void draw_items(int cont) {+ for (int i = 0; i < nvis; i++) {+ const Vis *v = &vis[i];+ const DrawRec *d = &lv.draws[v->d];+ if (d->cont != cont) continue;+ if (v->y1 < gfx_y0 || v->y0 > gfx_y0 + BAND) continue;+ switch (d->kind) {+ case D_POLY: draw_poly(v, d); break;+ case D_STRIP: draw_strip(v, d); break;+ case D_SPRITE: draw_sprite(v, d); break;+ case D_WATER: draw_water(v, d); break;+ }+ }+}++/* motors and pivots (their pictures sit at their joints), geysers */+static void draw_joints(void) {+ float k = cam.scale / TEX_SCALE;+ for (int i = 0; i < lv.nobj; i++) {+ const Obj *o = &lv.objs[i];+ int t = o->r->type;+ if ((t == O_MOTOR || t == O_PIVOT) && o->r->img != 0xFFFF) {+ float x = t == O_PIVOT && !o->body2 ? o->r->x : o->x->gx, y = t == O_PIVOT && !o->body2 ? o->r->y : o->x->gy;+ if (t == O_MOTOR && !o->body2) x = o->r->x, y = o->r->y;+ if (!fx_in_camera(x, y, 64)) continue;+ gfx_pic(o->r->img, sx(x), sy(y), k, k, t == O_MOTOR ? fmodf(o->x->grot, 6.2831853f) : 0, 256);+ } else if (t == O_GEYSER && o->active) {+ const float *p = obj_params(o);+ float w = p[2], c = cosf(o->r->rot), s = sinf(o->r->rot);+ float bx = o->r->x - 0.5f * w * c, by = o->r->y - 0.5f * w * s;+ if (!fx_in_camera(o->r->x, o->r->y, w)) continue;+ gfx_pic(PIC_GEYSERBASE, sx(bx), sy(by), k, k, o->r->rot, 256);+ int f = (int)(view_ticks % 6);+ gfx_pic(PIC_GEYSER_ANIM + f, sx(bx), sy(by), k, k, o->r->rot, 256);+ /* the air: streaks along it */+ for (int j = 0; j < 12; j++) {+ float a = fmodf(view_ticks * (p[5] / 30) / w + j * 0.0833f, 1.0f);+ float off = ((j * 37) % 11 / 10.0f - 0.5f) * p[3] * 0.8f;+ float px = bx + c * a * w - s * off, py = by + s * a * w + c * off;+ gfx_pic(PIC_PARTICLE_BOOST, sx(px), sy(py), k, k, o->r->rot, (int)(256 * (1 - a)));+ }+ }+ }+}++/* ---- the bike ---- */++static void part_pic(int slot, const Body *b) {+ float k = cam.scale / TEX_SCALE;+ gfx_pic(PIC_BIKE[bike.skin - 1][slot], sx(b->pos.x), sy(b->pos.y), k, k, b->rot, 256);+}++static void draw_bike(void) {+ Bike *bk = &bike;+ const Body *f = &bk->frame;+ float k = cam.scale / TEX_SCALE;+ int sk = bk->skin;+ /* wheels, suspensions, the frame */+ part_pic(2, &bk->wheel[0]);+ part_pic(2, &bk->wheel[1]);+ if (!bk->exploded) {+ V2 u = np_local_to_world(f, GEO_SUSPEND_BACK);+ float dx = bk->wheel[0].pos.x - u.x, dy = bk->wheel[0].pos.y - u.y;+ gfx_pic(PIC_BIKE[sk - 1][9], sx(u.x), sy(u.y), k * hypotf(dx, dy) / GEO_SUSPEND_BACK_W, k, atan2f(dy, dx), 256);+ }+ bool front_first = sk == 3 || sk == 6 || sk == 2;+ if (front_first && !bk->exploded)+ gfx_pic(PIC_BIKE[sk - 1][10], sx(bk->wheel[1].pos.x), sy(bk->wheel[1].pos.y), k, k, CAR_axisFrontAngle + f->rot, 256);+ if (bk->boosting) {+ V2 r = np_local_to_world(f, v2(-20, -10));+ gfx_pic(PIC_ROCKET + (int)(view_ticks % 6), sx(r.x), sy(r.y), k, k, f->rot, 256);+ }+ gfx_pic(PIC_BIKE[sk - 1][bk->exploded ? 1 : 0], sx(f->pos.x), sy(f->pos.y), k, k, f->rot, 256);+ if (!front_first && !bk->exploded)+ gfx_pic(PIC_BIKE[sk - 1][10], sx(bk->wheel[1].pos.x), sy(bk->wheel[1].pos.y), k, k, CAR_axisFrontAngle + f->rot, 256);+ /* the rider: the far limbs (after a crash), then his parts in the skin's order */+ static const int slot[NPARTS] = {3, 4, 7, 8, 5, 6, 7, 8, 5, 6};+ if (bk->part[P_HIP2].flags & BF_SPACE) {+ static const int far[4] = {P_ARM2, P_FOREARM2, P_HIP2, P_SHIN2};+ for (int i = 0; i < 4; i++) part_pic(slot[far[i]], &bk->part[far[i]]);+ }+ static const int ord6[6] = {P_HIP, P_CORPSE, P_HEAD, P_SHIN, P_ARM, P_FOREARM};+ static const int ord2[6] = {P_CORPSE, P_HEAD, P_HIP, P_SHIN, P_ARM, P_FOREARM};+ static const int ord[6] = {P_HEAD, P_CORPSE, P_HIP, P_SHIN, P_ARM, P_FOREARM};+ const int *o = sk == 6 ? ord6 : sk == 2 ? ord2 : ord;+ for (int i = 0; i < 6; i++) part_pic(slot[o[i]], &bk->part[o[i]]);+}++static void draw_scene(void) {+ draw_bg();+ draw_items(C_SHAPES);+ draw_items(C_LAND);+ fx_draw_fire();+ draw_items(C_OBJ);+ draw_joints();+ draw_bike();+ fx_draw_back();+ draw_items(C_FRONT);+ fx_draw_front();+}++void view_draw_world(void) { draw_scene(); }diff --git a/games/motox3m/src/view.h b/games/motox3m/src/view.hnew file mode 100644index 00000000..60500dc1--- /dev/null+++ b/games/motox3m/src/view.h@@ -0,0 +1,17 @@+/* Moto X3M: the level and the bike on the screen. */+#ifndef MX_VIEW_H+#define MX_VIEW_H+#include <stdint.h>++extern uint32_t view_ticks; /* game ticks, for animations */+/* the drawings in view (24 bytes each) and screen points, given room on main's stack */+#define VIEW_MAXVIS 300+#define VIEW_VIS_BYTES (24 * VIEW_MAXVIS)+#define VIEW_SCR_FLOATS (2 * 304)+void view_init(void *visbuf, float *scrbuf);+void view_reset(void);+/* once a frame, before drawing: which drawings are in view */+void view_prepare(void);+/* once a band */+void view_draw_world(void);+#endifdiff --git a/games/motox3m/tests/check.py b/games/motox3m/tests/check.pynew file mode 100644index 00000000..4dee2718--- /dev/null+++ b/games/motox3m/tests/check.py@@ -0,0 +1,72 @@+#!/usr/bin/env python3+"""Moto X3M's checks on a computer (make test): every level loads and runs (the sanitizers on), a level is+finished and its stars and time are kept, a saved game comes back (from its copy too), and random keys never crash it.++ python3 tests/check.py build/play"""+import os+import re+import shutil+import subprocess+import sys++PLAY = sys.argv[1] if len(sys.argv) > 1 else "build/play"+TMP = "build/check"+failed = []+++def run(args, saves):+ os.makedirs(saves, exist_ok=True)+ p = subprocess.run([PLAY, "--saves", saves] + args, capture_output=True, text=True, timeout=600)+ out = p.stdout + p.stderr+ if p.returncode != 0 or "runtime error" in out or "Sanitizer" in out:+ failed.append(" ".join(args) + "\n" + out[-2000:])+ return None+ m = re.search(r"END state (\d+) level (\d+) timer ([-\d.]+) dead (\d) finished (\d) x ([-\d.]+) y ([-\d.]+) "+ r"arena (\d+) overflow (\d)", out)+ return m+++def check(cond, what):+ if not cond:+ failed.append(what)+++shutil.rmtree(TMP, ignore_errors=True)+# every level: built, played 15 s with the gas held, nothing out of room, nothing through the floor+for n in range(1, 51):+ m = run(["--level", str(n), "--gas", "--frames", "450"], "%s/l%d" % (TMP, n))+ if m:+ check(int(m.group(9)) == 0, "level %d: contacts ran out" % n)+ check(float(m.group(7)) < 5000, "level %d: fell through the world (y %s)" % (n, m.group(7)))+ check(int(m.group(1)) in (3, 5), "level %d: did not start" % n)+# a finished level: stars and best time kept, the next level open (level 3, by the test driver)+m = run(["--level", "3", "--auto", "--frames", "1500"], TMP + "/fin")+check(m is not None and m.group(5) == "1", "level 3 not finished by the test driver")+save = os.path.join(TMP, "fin", "motox3m.sav")+check(os.path.exists(save), "no save after a finish")+if os.path.exists(save):+ d = open(save, "rb").read()+ check(d[:4] == b"MX3S", "the save's magic")+ stars = d[8:58]+ check(stars[0] == 0 and 1 <= stars[2] <= 3 and stars[3] == 0 and stars[4] == 0xFF,+ "stars kept: level 1 open, 3 starred, 4 opened, 5 locked (%s)" % list(stars[:6]))+# after a reinstall only the copy in motox3m_saves.py is left: the save comes back from it+if os.path.exists(save):+ os.makedirs(TMP + "/copy", exist_ok=True)+ shutil.copy(os.path.join(TMP, "fin", "motox3m_saves.py"), TMP + "/copy")+ run(["--frames", "20", "--keys", "10:home"], TMP + "/copy")+ back = os.path.join(TMP, "copy", "motox3m.sav")+ check(os.path.exists(back) and open(back, "rb").read() == d, "the save does not come back from its copy")+# a broken save resets cleanly+os.makedirs(TMP + "/bad", exist_ok=True)+open(TMP + "/bad/motox3m.sav", "wb").write(b"MX3S\x01\x00\xff\xff" + bytes(range(256)) * 2)+m = run(["--frames", "120", "--keys", "10:ok,30:ok,40-110:up"], TMP + "/bad")+check(m is not None and m.group(1) == "3", "a broken save stops the game")+# random keys through menus and runs+for seed in range(1, 41):+ run(["--fuzz", str(seed), "--frames", "6000"], "%s/fuzz%d" % (TMP, seed))++if failed:+ print("FAILED:\n" + "\n".join(failed))+ sys.exit(1)+print("all checks passed")diff --git a/games/motox3m/tests/phystest.c b/games/motox3m/tests/phystest.cnew file mode 100644index 00000000..08552d6b--- /dev/null+++ b/games/motox3m/tests/phystest.c@@ -0,0 +1,85 @@+/* Moto X3M: the physics on its own (a floor, falling boxes and wheels, a pendulum). */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include "nape.h"++static Material mats[1] = {{0, 1, 2, 1, 0.001f}};+static const Filter filters[1] = {{1, -1, 1, -1}};+static SShape sshapes[1];+static SBody sbodies[1];+static uint16_t buckets[2 * 64], blist[64];++static Body bodies[32];+static Shape shapes[32];+static float loc[32][20], glob[32][20];+static Body *bptr[32];+static Shape *sptr[32];+static Con *cptr[8];++static void box_shape(Shape *s, int i, float w, float h) {+ V2 v[4] = {{-w / 2, -h / 2}, {w / 2, -h / 2}, {w / 2, h / 2}, {-w / 2, h / 2}};+ for (int k = 0; k < 4; k++) {+ V2 u = v[k], n = v[(k + 1) & 3];+ float dx = u.x - n.x, dy = u.y - n.y, l = sqrtf(dx * dx + dy * dy);+ dx /= l, dy /= l;+ loc[i][2 * k] = u.x, loc[i][2 * k + 1] = u.y;+ loc[i][8 + 2 * k] = -dy, loc[i][8 + 2 * k + 1] = dx;+ loc[i][16 + k] = -dy * u.x + dx * u.y;+ }+ s->type = SH_POLY, s->n = 4, s->loc = loc[i], s->glob = glob[i];+ s->area = w * h;+ s->inertia = (w * w + h * h) / 12;+ s->mat = 0;+}++int main(void) {+ np_reset();+ sp.gravity = v2(0, 500);+ /* floor from x -1000 to 1000 at y 0..100: 4 verts, 4 normals, 4 projections */+ V2 fv[4] = {{-1000, 0}, {1000, 0}, {1000, 100}, {-1000, 100}};+ static float sd2[20];+ for (int k = 0; k < 4; k++) {+ V2 u = fv[k], n = fv[(k + 1) & 3];+ float dx = u.x - n.x, dy = u.y - n.y, l = sqrtf(dx * dx + dy * dy);+ dx /= l, dy /= l;+ sd2[2 * k] = u.x, sd2[2 * k + 1] = u.y;+ sd2[8 + 2 * k] = -dy, sd2[8 + 2 * k + 1] = dx;+ sd2[16 + k] = -dy * u.x + dx * u.y;+ }+ sshapes[0] = (SShape){-1000, 0, 1000, 100, 0, 4, 0, 0, 0, 0, 0};+ sbodies[0].flags = BF_SPACE;+ sp.sshapes = sshapes, sp.nsshapes = 1, sp.sdata = sd2, sp.sbodies = sbodies, sp.nsbodies = 1;+ for (int c = 0; c < 8; c++) buckets[2 * c] = 0, buckets[2 * c + 1] = 1;+ blist[0] = 0;+ sp.buckets = buckets, sp.bucket_list = blist, sp.nbuckets = 8, sp.bucket_x0 = -1024;+ sp.bodies = bptr, sp.shapes = sptr, sp.cons = cptr, sp.mats = mats, sp.filters = filters;+ /* a stack of 5 boxes */+ for (int i = 0; i < 5; i++) {+ Body *b = &bodies[i];+ b->type = B_DYNAMIC;+ b->pos = v2(0, -20 - 41 * i);+ np_body_set_rot(b, 0);+ b->shapes = &shapes[i], b->nshapes = 1;+ box_shape(&shapes[i], i, 40, 40);+ np_register(b);+ np_body_add(b);+ }+ /* a wheel */+ Body *w = &bodies[5];+ w->type = B_DYNAMIC, w->pos = v2(200, -300);+ np_body_set_rot(w, 0);+ w->shapes = &shapes[5], w->nshapes = 1;+ Shape *ws = &shapes[5];+ ws->type = SH_CIRCLE, ws->radius = 19, ws->area = 3.14159f * 19 * 19, ws->inertia = 19 * 19 / 2.0f, ws->mat = 0;+ np_register(w);+ np_body_add(w);+ w->angvel = 10;+ for (int t = 0; t < 600; t++) {+ np_step(1 / 60.0f);+ if (t % 60 == 59)+ printf("t=%3d top box y=%.2f rot=%.4f sleep=%d wheel x=%.1f y=%.2f w=%.2f arbs ovf=%d\n", t + 1, bodies[4].pos.y,+ bodies[4].rot, (bodies[4].flags & BF_SLEEP) != 0, w->pos.x, w->pos.y, w->angvel, sp.overflow);+ }+ return 0;+}diff --git a/games/motox3m/tests/play.c b/games/motox3m/tests/play.cnew file mode 100644index 00000000..19445f2e--- /dev/null+++ b/games/motox3m/tests/play.c@@ -0,0 +1,167 @@+/* Plays Moto X3M on a computer, with scripted keys, and saves frames.+ *+ * play [--level N] [--frames N] [--keys "10-40:right,50:ok,..."] [--shots 30,60|every:N] [--out DIR]+ * [--saves DIR] [--gas] [--auto] [--stunt H] [--fuzz SEED] [--draw] [--trace N]+ *+ * Keys: left right up down ok back home. "a-b:key" holds the key from frame a to b, "a:key" for one frame (a frame+ * is a game tick, 1/30 s). --level starts that level (1-50) past the menus; --gas holds the gas from the start.+ * Screenshots are DIR/shot_<frame>.ppm. --fuzz presses random keys through menus and runs. --trace N prints the+ * bike every N ticks. --auto drives (the gas, and leaning to keep the bike level); --stunt H also back flips when+ * the ground is more than H below a jump. At the end: END state S level L timer T dead D finished F x X y Y. */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include "../src/bike.h"+#include "../src/game.h"+#include "../src/gfx.h"+#include "../src/level.h"+#include "../src/view.h"++extern uint32_t host_keys, host_time;+void host_shot(const char *path);+void host_save_dir(const char *d);++typedef struct { int a, b; uint32_t k; } Hold;+static Hold holds[4096];+static int nholds;+static int shots[4096], nshots, every;++static uint32_t key_of(const char *s) {+ static const char *const names[] = {"left", "right", "up", "down", "ok", "back", "home"};+ static const uint32_t bits[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_BACK, K_HOME};+ for (int i = 0; i < 7; i++)+ if (!strcmp(s, names[i])) return bits[i];+ fprintf(stderr, "unknown key %s\n", s);+ exit(2);+}++static void parse_keys(const char *spec) {+ static char buf[65536];+ snprintf(buf, sizeof buf, "%s", spec);+ for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) {+ int a, b;+ char k[16];+ if (sscanf(tok, "%d-%d:%15s", &a, &b, k) == 3) holds[nholds++] = (Hold){a, b, key_of(k)};+ else if (sscanf(tok, "%d:%15s", &a, k) == 2) holds[nholds++] = (Hold){a, a, key_of(k)};+ }+}++static uint32_t rng = 1;+static uint32_t rnd(void) {+ rng ^= rng << 13, rng ^= rng >> 17, rng ^= rng << 5;+ return rng;+}++static int arbs_used(void) {+ int n = 0;+ for (int i = 0; i < NP_MAX_ARBS; i++) n += sp.arbs[i].used;+ return n;+}+static int asleep(void) {+ int n = 0;+ for (int i = 0; i < sp.nbodies; i++) n += (sp.bodies[i]->flags & BF_SLEEP) != 0;+ return n;+}++int main(int argc, char **argv) {+ int frames = 300, level = 0, trace = 0, air_t = 0;+ float stunt = 0, flip_from = NAN, flip_seen = 0;+ bool gas = false, fuzz = false, draw = false, autop = false;+ const char *out = "build/shots";+ for (int i = 1; i < argc; i++) {+ if (!strcmp(argv[i], "--frames")) frames = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--level")) level = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--keys")) parse_keys(argv[++i]);+ else if (!strcmp(argv[i], "--out")) out = argv[++i];+ else if (!strcmp(argv[i], "--saves")) host_save_dir(argv[++i]);+ else if (!strcmp(argv[i], "--gas")) gas = true;+ else if (!strcmp(argv[i], "--auto")) autop = true;+ else if (!strcmp(argv[i], "--stunt")) autop = true, stunt = (float)atof(argv[++i]);+ else if (!strcmp(argv[i], "--draw")) draw = true;+ else if (!strcmp(argv[i], "--trace")) trace = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--fuzz")) fuzz = true, rng = (uint32_t)atoi(argv[++i]) * 2654435761u + 1;+ else if (!strcmp(argv[i], "--shots")) {+ const char *s = argv[++i];+ if (!strncmp(s, "every:", 6)) every = atoi(s + 6);+ else+ for (const char *p = s; *p;) {+ shots[nshots++] = atoi(p);+ p = strchr(p, ',');+ if (!p) break;+ p++;+ }+ }+ }+ mkdir(out, 0755);+ static uint16_t band[SCREEN_W * BAND];+ static uint32_t visbuf[VIEW_VIS_BYTES / 4];+ static float scrbuf[VIEW_SCR_FLOATS];+ gfx_init(band);+ view_init(visbuf, scrbuf);+ game_init();+ if (level) game_start_level(level - 1);+ uint32_t fk = 0;+ static int state_hist[8];+ for (int f = 0; f < frames && g.running; f++) {+ uint32_t k = 0;+ for (int i = 0; i < nholds; i++)+ if (f >= holds[i].a && f <= holds[i].b) k |= holds[i].k;+ if (gas) k |= K_UP;+ if (autop && g.state == S_PLAY) {+ /* gas, and lean to keep the bike level; after a crash, go on */+ float r = fmodf(bike.frame.rot, 6.2831853f);+ if (r > 3.14159f) r -= 6.2831853f;+ if (r < -3.14159f) r += 6.2831853f;+ k |= K_UP;+ if (r < -0.35f) k |= K_RIGHT;+ else if (r > 0.35f) k |= K_LEFT;+ if (bike.dead && g.dead_t > 0.5f && f % 2) k = K_OK;+ }+ if (stunt && g.state == S_PLAY && !bike.dead) {+ /* in a long jump (the ground far below), a back flip, then level again for the landing */+ bool air = !bike.wheel_ground[0] && !bike.wheel_ground[1] && !bike.frame_ground;+ air_t = air ? air_t + 1 : 0;+ if (air_t == 4) {+ Body *b;+ int sb;+ float d;+ /* (from below the bike, which the ray would hit) */+ flip_from = np_raycast((V2){bike.frame.pos.x, bike.frame.pos.y + 70}, (V2){0, 1}, 4000, &b, &sb, &d) && d + 70 > stunt+ ? bike.frame.rot : NAN;+ }+ if (air_t >= 4 && !isnan(flip_from) && bike.frame.rot > flip_from - 6.2831853f + 0.9f) k = K_UP | K_LEFT;+ }+ if (g.flip_t < flip_seen) printf("FLIP %d at %d\n", g.flip_n, f);+ flip_seen = g.flip_t;+ if (autop && g.state == S_FINISH && f % 30 == 0) k = 0;+ if (fuzz) {+ if (rnd() % 8 == 0) fk = rnd() & (K_LEFT | K_RIGHT | K_UP | K_DOWN | K_OK | (rnd() % 16 == 0 ? K_BACK : 0));+ k = fk;+ if (g.state == S_TITLE || (g.state == S_PAUSE && g.confirm)) k &= ~(uint32_t)K_BACK; /* (stay in the game) */+ if (g.state == S_PAUSE && (g.confirm || g.sel == 3)) k &= ~(uint32_t)K_OK;+ }+ host_keys = k;+ state_hist[g.state]++;+ game_tick(k);+ host_time += 33;+ bool shot = every ? f % every == 0 : false;+ for (int i = 0; i < nshots; i++) shot |= shots[i] == f;+ if (shot || draw) game_draw();+ if (shot) {+ char p[512];+ snprintf(p, sizeof p, "%s/shot_%04d.ppm", out, f);+ host_shot(p);+ }+ if (trace && f % trace == 0 && (g.state == S_PLAY || g.state == S_FINISH))+ printf("t%4d x %8.1f y %7.1f rot %6.2f v %6.1f wheel %6.2f ground %d%d%d timer %5.2f dead %d arbs %d sleep %d\n", f,+ bike.frame.pos.x, bike.frame.pos.y, bike.frame.rot, bike.speed, bike.wheel[0].angvel, bike.wheel_ground[0],+ bike.wheel_ground[1], bike.frame_ground, g.timer, bike.dead, arbs_used(), asleep());+ }+ if (fuzz) printf("STATES title %d map %d shop %d play %d pause %d finish %d\n", state_hist[0], state_hist[1], state_hist[2],+ state_hist[3], state_hist[4], state_hist[5]);+ printf("END state %d level %d timer %.2f dead %d finished %d x %.1f y %.1f arena %d overflow %d\n", g.state,+ g.level + 1, g.timer, bike.dead, bike.finished, bike.frame.pos.x, bike.frame.pos.y, arena_peak, sp.overflow);+ return 0;+}diff --git a/games/motox3m/tools/bike_anchors.json b/games/motox3m/tools/bike_anchors.jsonnew file mode 100644index 00000000..2b847074--- /dev/null+++ b/games/motox3m/tools/bike_anchors.json@@ -0,0 +1,13 @@+{"FRAMES_ANCHORX": [0.48, 0.465, 0.45, 0.51, 0.52, 0.38],+ "FRAMES_ANCHORY": [0.65, 0.606, 0.62, 0.69, 0.65, 0.5],+ "SUSPEND_BACK_ANCHORX": [0.05, 0.027, 0.05, 0.03, 0, -0.125],+ "SUSPEND_BACK_ANCHORY": [0.5, 0.47, 0.5, 0.5, 0.5, 0.56],+ "SUSPEND_FRONT_ANCHORX": [0.8, 0.769, 0.8, 0.85, 0.95, 0.83],+ "SUSPEND_FRONT_ANCHORY": [0.2, 0.5, 0.5, 0.36, 0.5, 0.625],+ "ARCHORS_X": {"driver_head": [0.5, 0.44, 0.5, 0.44, 0.6, 0.45], "driver_corpse": [0.5, 0.52, 0.5, 0.53, 0.56, 0.47],+ "driver_arm": [0.5, 0.55, 0.5, 0.44, 0.45, 0.44], "driver_forearm": [0.5, 0.54, 0.5, 0.5, 0.35, 0.47],+ "driver_hip": [0.5, 0.52, 0.5, 0.5, 0.59, 0.6], "driver_shin": [0.5, 0.33, 0.5, 0.37, 0.43, 0.38]},+ "ARCHORS_Y": {"driver_head": [0.5, 0.44, 0.5, 0.5, 0.38, 0.43], "driver_corpse": [0.5, 0.51, 0.5, 0.5, 0.61, 0.5],+ "driver_arm": [0.5, 0.57, 0.5, 0.45, 0.54, 0.37], "driver_forearm": [0.5, 0.44, 0.5, 0.5, 0.5, 0.43],+ "driver_hip": [0.5, 0.5, 0.5, 0.45, 0.53, 0.55], "driver_shin": [0.5, 0.48, 0.5, 0.5, 0.45, 0.5]},+ "WHEELS": ["Wheel_1_0", "Wheel_1_0", "Wheel_3_0", "Wheel_3_0", "Wheel_5_0", "Wheel_6_0"]}diff --git a/games/motox3m/tools/geom.py b/games/motox3m/tools/geom.pynew file mode 100644index 00000000..bb0a7e7f--- /dev/null+++ b/games/motox3m/tools/geom.py@@ -0,0 +1,207 @@+"""Moto X3M packer: Nape's polygon rules (winding, edges, area, inertia, centre of mass) and a convex+decomposition for the concave shapes the levels draw."""+import math++EPS = 1e-8+++def js_round(v):+ """JavaScript's Math.round (halves go up)."""+ return math.floor(v + 0.5)+++def cross(ax, ay, bx, by):+ return ax * by - ay * bx+++def nape_area2(vs):+ """twice Nape's signed area (Polygon.__validate_area_inertia)"""+ n = len(vs)+ a = 0.0+ for i in range(n):+ u, v, w = vs[i - 1], vs[i], vs[(i + 1) % n]+ a += v[0] * (w[1] - u[1])+ return a+++def clean(vs):+ """drops repeated and collinear vertices (Polygon.splice_collinear)"""+ out = []+ for p in vs:+ if not out or (p[0] - out[-1][0]) ** 2 + (p[1] - out[-1][1]) ** 2 >= EPS * EPS:+ out.append((float(p[0]), float(p[1])))+ while len(out) > 1 and (out[0][0] - out[-1][0]) ** 2 + (out[0][1] - out[-1][1]) ** 2 < EPS * EPS:+ out.pop()+ changed = True+ while changed and len(out) > 3:+ changed = False+ for i in range(len(out)):+ u, v, w = out[i - 1], out[i], out[(i + 1) % len(out)]+ c = cross(v[0] - u[0], v[1] - u[1], w[0] - v[0], w[1] - v[1])+ if c * c < EPS * EPS:+ out.pop(i)+ changed = True+ break+ return out+++def nape_poly(vs):+ """a polygon as Nape keeps it: vertices with positive area, outward edge normals and projections, area,+ inertia per unit mass about the origin, centre of mass"""+ vs = clean(vs)+ if nape_area2(vs) < 0:+ vs = vs[::-1]+ n = len(vs)+ norms, projs = [], []+ for i in range(n):+ u, v = vs[i], vs[(i + 1) % n]+ dx, dy = u[0] - v[0], u[1] - v[1]+ l = math.hypot(dx, dy)+ dx, dy = dx / l, dy / l+ nx, ny = -dy, dx+ norms.append((nx, ny))+ projs.append(nx * u[0] + ny * u[1])+ s1 = s2 = 0.0+ for i in range(n):+ u, v = vs[i - 1], vs[i]+ a = cross(u[0], u[1], v[0], v[1])+ b = v[0] * v[0] + v[1] * v[1] + v[0] * u[0] + v[1] * u[1] + u[0] * u[0] + u[1] * u[1]+ s1 += a * b+ s2 += a+ area2 = nape_area2(vs)+ area = area2 / 2+ inertia = s1 / (6 * s2) if s2 else 0.0+ cx = cy = 0.0+ for i in range(n):+ v, w = vs[i], vs[(i + 1) % n]+ cf = cross(v[0], v[1], w[0], w[1])+ cx += (v[0] + w[0]) * cf+ cy += (v[1] + w[1]) * cf+ k = 1 / (3 * area2)+ return {"v": vs, "n": norms, "p": projs, "area": area, "inertia": inertia, "com": (cx * k, cy * k)}+++def is_convex(vs):+ vs = clean(vs)+ n = len(vs)+ if n < 3:+ return False+ sign = 0+ for i in range(n):+ u, v, w = vs[i - 1], vs[i], vs[(i + 1) % n]+ c = cross(v[0] - u[0], v[1] - u[1], w[0] - v[0], w[1] - v[1])+ if abs(c) < 1e-9:+ continue+ s = 1 if c > 0 else -1+ if sign == 0:+ sign = s+ elif s != sign:+ return False+ return True+++def _area(vs):+ a = 0.0+ for i in range(len(vs)):+ x0, y0 = vs[i - 1]+ x1, y1 = vs[i]+ a += x0 * y1 - x1 * y0+ return a / 2+++def _in_tri(p, a, b, c):+ d1 = cross(b[0] - a[0], b[1] - a[1], p[0] - a[0], p[1] - a[1])+ d2 = cross(c[0] - b[0], c[1] - b[1], p[0] - b[0], p[1] - b[1])+ d3 = cross(a[0] - c[0], a[1] - c[1], p[0] - c[0], p[1] - c[1])+ return d1 >= -1e-9 and d2 >= -1e-9 and d3 >= -1e-9+++def triangulate(vs):+ """ear clipping; returns triangles as index triples (counterclockwise in maths axes)"""+ vs = clean(vs)+ idx = list(range(len(vs)))+ if _area(vs) < 0:+ idx.reverse()+ tris = []+ guard = 0+ while len(idx) > 3 and guard < 10000:+ guard += 1+ n = len(idx)+ found = False+ for k in range(n):+ i0, i1, i2 = idx[k - 1], idx[k], idx[(k + 1) % n]+ a, b, c = vs[i0], vs[i1], vs[i2]+ if cross(b[0] - a[0], b[1] - a[1], c[0] - b[0], c[1] - b[1]) <= 1e-12:+ continue+ if any(_in_tri(vs[j], a, b, c) for j in idx if j not in (i0, i1, i2)):+ continue+ tris.append((i0, i1, i2))+ idx.pop(k)+ found = True+ break+ if not found:+ # not simple: cut the flattest corner anyway+ k = 0+ tris.append((idx[k - 1], idx[k], idx[(k + 1) % len(idx)]))+ idx.pop(k)+ if len(idx) == 3:+ tris.append(tuple(idx))+ return vs, tris+++def convex_decompose(vs):+ """convex pieces: triangles merged across diagonals while they stay convex (Hertel-Mehlhorn)"""+ vs, tris = triangulate(vs)+ polys = [list(t) for t in tris]+ merged = True+ while merged:+ merged = False+ for i in range(len(polys)):+ for j in range(i + 1, len(polys)):+ a, b = polys[i], polys[j]+ # a shared edge: a has (p, q), b has (q, p)+ for ia in range(len(a)):+ p, q = a[ia], a[(ia + 1) % len(a)]+ for ib in range(len(b)):+ if b[ib] == q and b[(ib + 1) % len(b)] == p:+ # build merged ring: a from q around to p, then b from p around to q+ ring = []+ k = (ia + 1) % len(a)+ for _ in range(len(a)):+ ring.append(a[k])+ k = (k + 1) % len(a)+ # ring starts at q, ends at p; continue in b after p (skipping p) up to before q+ k = (ib + 2) % len(b)+ while b[k] != q:+ ring.append(b[k])+ k = (k + 1) % len(b)+ pts = [vs[t] for t in ring]+ if len(set(ring)) == len(ring) and is_convex(pts):+ polys[i] = ring+ polys.pop(j)+ merged = True+ break+ if merged:+ break+ if merged:+ break+ if merged:+ break+ return [[vs[t] for t in p] for p in polys]+++def convex_pieces(vs):+ vs = clean(vs)+ if len(vs) < 3:+ return []+ if is_convex(vs):+ return [vs]+ return [p for p in convex_decompose(vs) if len(clean(p)) >= 3 and abs(_area(p)) > 1e-6]+++def contains(poly, p):+ """a point in a convex polygon given by nape_poly"""+ for (nx, ny), pr in zip(poly["n"], poly["p"]):+ if nx * p[0] + ny * p[1] > pr:+ return False+ return Truediff --git a/games/motox3m/tools/levels.py b/games/motox3m/tools/levels.pynew file mode 100644index 00000000..d1034dcc--- /dev/null+++ b/games/motox3m/tools/levels.py@@ -0,0 +1,772 @@+"""Moto X3M packer: the levels. Builds each level's bodies, objects and drawings the way the game's RaceBuilder+does (motox3m4.js: GroundObject, ShaperObject, PlankObject, NapeUtil, PhysicUtil, ...), so the calculator only+has to read them."""+import json+import math+import os++from geom import js_round, nape_poly, convex_pieces, is_convex, clean, contains++TO_RAD = math.pi / 180++# the game's callback types (bits)+CB = dict(GROUND=1, SPIKES=2, SAW=4, FINISH=8, SAFE=16, TOGGLE=32, TOGGLE_OFF=64, GLASS=128, WATER=256, BOOST=512,+ GEYSER=1024, WHEEL=2048, BODY=4096, DRIVER=8192, PART=16384)+# InteractionFilter(collisionGroup, collisionMask, sensorGroup, sensorMask), as Filters+FILTERS = [+ ("DEFAULT", 1, -1, 1, -1),+ ("NOTHING", 0, 0, 0, 0),+ ("SENSOR", 0, 0, 1, 4369),+ ("WITH_EARTH_ONLY", 1, 4369, 1, -1),+ ("WHEEL", 4096, 272, 17, 4369),+ ("DRIVER_PART", 4096, 272, 1, -1),+ ("GROUND", 17, 4369, 1, 4369),+ ("PLAYER_ONLY", 256, 4096, 1, 4369),+]+F = {f[0]: i for i, f in enumerate(FILTERS)}+F["TOGGLE"] = F["SENSOR"]+F["WATER"] = F["SENSOR"]+F["BODY_COLLIDER"] = F["WHEEL"]+# Material(elasticity, dynamicFriction, staticFriction, density, rollingFriction)+MAT_DEFAULT = (0.0, 1.0, 2.0, 1.0, 0.001)++# object kinds (the C side's O_*)+O = dict(GROUND=0, SHAPER=1, PLANK=2, DYN=3, REMOVED=4, TNT=5, SPIKES=6, TOGGLE=7, SAFE=8, FINISH=9, MOVER=10,+ MOTOR=11, PIVOT=12, DECOR=13, WATER=14, GEYSER=15, BOOST=16, GLASS=17)+# drawing containers, back to front (MaxGameView): shapes, landscape, objects, front+C_SHAPES, C_LAND, C_OBJ, C_FRONT = 0, 1, 2, 3+# drawing kinds+D_POLY, D_STRIP, D_SPRITE, D_WATER = 0, 1, 2, 3++BG = [["Bg0_0", "Bg1_0", "Bg2_0"], ["Bg0_1", None, None], ["Bg0_2", None, "Bg2_2"]]+ROAD_LINE = ["line", "RoadLine0_1", "RoadLine1_4", "RoadLine0_3", "RoadLine0_4", "Plank0", "RoadLine0_0", "RoadLine0_7",+ "RoadLine0_8", "line_ivy", "UnLine0", "UnLine1", "LineChain", "CandyGround", "RoadLine0_Bg"]+PILLAR_LINE = ["RoadPillar0_0", "RoadPillar0_1", "RoadPillar0_2"]+DECORS_ALL = ["Dec1", "Dec2", "Dec3", "Dec4", "Dec5", "Dec6", "Dec7", "Dec8", "Dec9", "Dec10", "Dec11", "Dec12", "Dec13",+ "Dec14", "Dec15", "Dec16", "Dec17", "Dec18", "Dec19", "Dec29", "Sign1", "Sign2", "Sign15", "Sign21",+ "SignPillar", "PillarTop0_0", "PillarTop0_1", "PillarTop0_2", "PillarBot0_0", "PillarBot0_1",+ "PillarBot0_2"]+DECORS = [DECORS_ALL, DECORS_ALL, DECORS_ALL[12:16] + DECORS_ALL[19:]]+++def load(path):+ with open(path, encoding="utf-8-sig") as f:+ return json.load(f)+++def jsmod(a, b):+ return math.fmod(a, b)+++def rot(p, a):+ c, s = math.cos(a), math.sin(a)+ return (p[0] * c - p[1] * s, p[0] * s + p[1] * c)+++def normalize_vertices(params):+ """Util.normalizeVertices: rounded vertices turned about the object's origin, in world coordinates"""+ x, y, r = params["x"], params["y"], TO_RAD * params["rotation"]+ out = []+ for v in params["vertices"]:+ d, p = js_round(v["x"]), js_round(v["y"])+ if d == 0 and p == 0:+ out.append({"x": x, "y": y})+ else:+ f = math.atan2(p, d) + r+ l = math.hypot(d, p)+ out.append({"x": x + math.cos(f) * l, "y": y + math.sin(f) * l})+ q = dict(params)+ q["vertices"] = out+ q["x"] = q["y"] = 0+ q["rotation"] = 0+ return q+++class Body:+ def __init__(self, kind, x, y, cb=0):+ self.kind = kind # "static", "dynamic", "kinematic"+ self.x, self.y, self.rot = float(x), float(y), 0.0+ self.shapes = [] # dicts: type poly/circle, v (local) or r + c, filter, mat, sensor, fluid+ self.cb = cb+ self.space = True+ self.norot = False+ self.fluid = None # (viscosity, density)+ self.index = -1+ self.ground = False # userData.isGround: the bike's wheels and frame count it as ground++ def poly(self, verts, mat, flt, sensor=False):+ for piece in convex_pieces(verts):+ self.shapes.append({"type": "poly", "v": piece, "mat": mat, "filter": flt, "sensor": sensor})++ def circle(self, r, mat, flt, sensor=False, c=(0.0, 0.0)):+ self.shapes.append({"type": "circle", "r": r, "c": c, "mat": mat, "filter": flt, "sensor": sensor})++ def mass_com(self):+ m = cx = cy = 0.0+ for s in self.shapes:+ if s["type"] == "poly":+ p = nape_poly(s["v"])+ a, c = p["area"], p["com"]+ else:+ a, c = math.pi * s["r"] ** 2, s["c"]+ d = a * s["mat"][3]+ m += d+ cx += c[0] * d+ cy += c[1] * d+ return m, ((cx / m, cy / m) if m else (0.0, 0.0))++ def align(self):+ """Body.align: the origin moves to the centre of mass"""+ m, (cx, cy) = self.mass_com()+ if not m:+ return+ for s in self.shapes:+ if s["type"] == "poly":+ s["v"] = [(v[0] - cx, v[1] - cy) for v in s["v"]]+ else:+ s["c"] = (s["c"][0] - cx, s["c"][1] - cy)+ w = rot((cx, cy), self.rot)+ self.x += w[0]+ self.y += w[1]++ def rotate(self, cx, cy, a):+ """Body.rotate(centre, angle)"""+ d = rot((self.x - cx, self.y - cy), a)+ self.x, self.y = cx + d[0], cy + d[1]+ self.rot += a++ def to_world(self, p):+ q = rot(p, self.rot)+ return (self.x + q[0], self.y + q[1])++ def world_shapes(self):+ out = []+ for s in self.shapes:+ if s["type"] == "poly":+ out.append(nape_poly([self.to_world(v) for v in s["v"]]))+ else:+ c = self.to_world(s["c"])+ out.append({"circle": True, "c": c, "r": s["r"]})+ return out++ def contains(self, pt):+ for s in self.world_shapes():+ if s.get("circle"):+ if (pt[0] - s["c"][0]) ** 2 + (pt[1] - s["c"][1]) ** 2 < s["r"] ** 2:+ return True+ elif contains(s, pt):+ return True+ return False+++def num(v, default=0.0):+ """a parameter as JavaScript would use it in arithmetic (some are strings)"""+ if v is None or v == "":+ return default+ try:+ return float(v)+ except (TypeError, ValueError):+ return default+++def mat_with(density=None, base=MAT_DEFAULT):+ m = list(base)+ if density is not None:+ m[3] = num(density, 1.0)+ return tuple(m)+++class Level:+ def __init__(self, n, data, objects, warn):+ self.n = n+ self.data = data+ self.settings = data["settings"]+ self.theme = self.settings["theme"] % 3+ self.objects_json = objects+ self.warn = warn+ self.bodies = []+ self.objs = []+ self.draws = []+ self.cams = []+ self.start = (360.0, 240.0)+ self.finish_x = 0.0+ self.images = set()+ self.prizes = [float(x) for x in self.settings["prizes"].split(",")]+ for li, layer in enumerate(data["layers"]):+ for o in layer or []:+ self.parse(o, li)++ # ---- helpers ----+ def body(self, kind, x, y, cb=0):+ b = Body(kind, x, y, cb)+ b.index = len(self.bodies)+ self.bodies.append(b)+ return b++ def obj(self, kind, **kw):+ o = {"kind": O[kind], "flags": 0, "id": -1, "id2": -1, "body": None, "body2": None, "x": 0.0, "y": 0.0,+ "rot": 0.0, "p": [0.0] * 8, "aux": [], "img": None, "cname": ""}+ o.update(kw)+ o["index"] = len(self.objs)+ self.objs.append(o)+ return o++ def draw(self, kind, cont, owner, img, pts=None, p=None, flags=0, back=False):+ if img is not None:+ self.images.add(img)+ d = {"kind": kind, "cont": cont, "owner": owner, "img": img, "pts": pts or [], "p": p or [0.0] * 6,+ "flags": flags, "back": back, "order": len(self.draws)}+ self.draws.append(d)+ return d++ def rect_body(self, kind, flt, sensor, w, h, x, y, rot_rad, cb, mat=MAT_DEFAULT):+ b = self.body(kind, x, y, cb)+ b.rot = rot_rad+ b.poly([(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)], mat, flt, sensor)+ return b++ def poly_body(self, params, mat, flt, kind):+ """NapeUtil.createPolyBody"""+ b = self.body(kind, params["x"], params["y"])+ b.poly([(v["x"], v["y"]) for v in params["vertices"]], mat, flt)+ return b++ def pather_body(self, params, mat, flt, thick):+ """NapeUtil.createPatherBody: a quad per segment, joints mitred"""+ b = self.body("static" if params.get("isStatic") else "dynamic", params["x"], params["y"])+ p = params["vertices"]+ y = len(p)+ s = thick+ a = [[0, 0], [0, 0], [0, 0], [0, 0]]+ for f in range(y - 1):+ lx, ly = p[f + 1]["x"] - p[f]["x"], p[f + 1]["y"] - p[f]["y"]+ if f == 0:+ g = math.atan2(ly, lx) + 0.5 * math.pi+ a[0] = [p[f]["x"] - 0.5 * s * math.cos(g), p[f]["y"] - 0.5 * s * math.sin(g)]+ a[1] = [p[f]["x"] + 0.5 * s * math.cos(g), p[f]["y"] + 0.5 * s * math.sin(g)]+ else:+ a[0] = list(a[3])+ a[1] = list(a[2])+ if f == y - 2:+ g = math.atan2(ly, lx) + 0.5 * math.pi+ a[3] = [p[f + 1]["x"] - 0.5 * s * math.cos(g), p[f + 1]["y"] - 0.5 * s * math.sin(g)]+ a[2] = [p[f + 1]["x"] + 0.5 * s * math.cos(g), p[f + 1]["y"] + 0.5 * s * math.sin(g)]+ else:+ ll = math.hypot(lx, ly)+ lx, ly = -lx / ll, -ly / ll+ ux, uy = p[f + 2]["x"] - p[f + 1]["x"], p[f + 2]["y"] - p[f + 1]["y"]+ ul = math.hypot(ux, uy)+ ux, uy = ux / ul, uy / ul+ g = math.atan2(ly + uy, lx + ux)+ a[3] = [p[f + 1]["x"] - 0.5 * s * math.cos(g), p[f + 1]["y"] - 0.5 * s * math.sin(g)]+ a[2] = [p[f + 1]["x"] + 0.5 * s * math.cos(g), p[f + 1]["y"] + 0.5 * s * math.sin(g)]+ q = [tuple(v) for v in a]+ if not is_convex(q):+ q = [q[0], q[1], q[3], q[2]]+ for piece in convex_pieces(q):+ b.shapes.append({"type": "poly", "v": piece, "mat": mat, "filter": flt, "sensor": False})+ b.align()+ return b++ def ground_body(self, params):+ """PhysicUtil.createGroundBody: convex runs of the ground line, thick downwards"""+ x, y = params["x"], params["y"]+ n = params["vertices"]+ u = float("nan")+ d = float("nan")+ thick = params.get("thick") if params.get("thick") is not None else 128+ f = params.get("direction", 0) * TO_RAD+ directed = params.get("directed")+ b = self.body("static", x, y, CB["GROUND"])++ def add(run, ua, la):+ pts = []+ for k, g in enumerate(run):+ if k == 0:+ ang = f if directed else ua+ pts.append((g["x"] + math.cos(ang) * thick, g["y"] + math.sin(ang) * thick))+ pts.append((g["x"], g["y"]))+ if k == len(run) - 1:+ ang = f if directed else la+ pts.append((g["x"] + math.cos(ang) * thick, g["y"] + math.sin(ang) * thick))+ if is_convex(pts):+ b.shapes.append({"type": "poly", "v": clean(pts), "mat": MAT_DEFAULT, "filter": F["GROUND"],+ "sensor": False})+ else:+ for piece in convex_pieces(pts):+ b.shapes.append({"type": "poly", "v": piece, "mat": MAT_DEFAULT, "filter": F["GROUND"],+ "sensor": False})++ v = [n[0]]+ xang = 0.0+ for k in range(1, len(n)):+ bb = n[k]+ w = v[-1]+ if len(v) == 1:+ v.append(bb)+ xang = math.atan2(bb["y"] - w["y"], bb["x"] - w["x"])+ if math.isnan(u):+ u = xang + 0.5 * math.pi+ else:+ c = math.atan2(bb["y"] - w["y"], bb["x"] - w["x"])+ da = c - xang+ if da > math.pi:+ da -= 2 * math.pi+ elif da < -math.pi:+ da += 2 * math.pi+ if da < 0:+ if not directed:+ tx, ty = math.cos(xang) - math.cos(c), math.sin(xang) - math.sin(c)+ d = math.atan2(ty, tx)+ add(v, u, d)+ u = d+ v = [w, bb]+ else:+ v.append(bb)+ xang = c+ add(v, u, xang + 0.5 * math.pi)+ b.ground = True+ if not b.shapes:+ self.bodies.pop()+ return None+ return b++ def under(self, pt):+ return [b for b in self.bodies if b.space and b.contains(pt)]++ def sprite(self, cont, owner, img, x, y, rot_rad, sx=1.0, sy=1.0, frames=1, back=False, flags=0):+ return self.draw(D_SPRITE, cont, owner, img, p=[x, y, rot_rad, sx, sy, frames], back=back, flags=flags)++ def strip(self, cont, owner, img, pts, rope, back=False):+ if len(pts) < 2:+ return+ self.draw(D_STRIP, cont, owner, "strip:" + img, pts=pts, p=[1.0 if rope else 0.0, 0, 0, 0, 0, 0], back=back)++ # ---- objects ----+ def parse(self, o, li):+ cname = o["className"].split("::")[-1]+ p = o["params"]+ th = self.theme+ if cname == "PlayerWP":+ self.start = (p["x"], p["y"])+ return+ if "GroundPather" in cname:+ self.ground(p, cname)+ elif "LandscapeShaper" in cname or "FinishShaper" in cname:+ self.shaper(p, "Finish" in cname)+ elif "WaterShaper" in cname:+ self.water(p)+ elif "GeyserE" in cname:+ self.geyser(p)+ elif "MoverPather" in cname:+ self.mover(p)+ elif "DynamicPather" in cname or "PillarPather" in cname:+ self.pather(p, "PillarPather" in cname)+ elif cname.startswith("Glass"):+ self.glass(p, cname)+ elif cname.startswith("Dec") or cname.startswith("Sign") or cname.startswith("Pillar"):+ self.decor(p, cname, li)+ elif cname in ("BarrelE", "Plank0"):+ self.dyn(p, cname, "DYN")+ elif cname == "ToggleE":+ b = self.rect_body("static", F["TOGGLE"], True, p["width"], p["height"], p["x"], p["y"],+ TO_RAD * p["rotation"], CB["TOGGLE"] | (CB["TOGGLE_OFF"] if p.get("off") else 0))+ self.obj("TOGGLE", id=p.get("id", -1), id2=p.get("id_off", -1) if p.get("id_off") else -1, body=b,+ flags=1 if p.get("off") else 0, p=[float(p.get("sndId", -1) if p.get("sndId") is not None else -1),+ 0, 0, 0, 0, 0, 0, 0])+ elif cname == "BoostE":+ b = self.body("static", p["x"], p["y"], CB["BOOST"])+ b.circle(32, MAT_DEFAULT, F["SENSOR"], True)+ ob = self.obj("BOOST", body=b, x=p["x"], y=p["y"], p=[p["time"], p["force"], 0, 0, 0, 0, 0, 0])+ self.sprite(C_OBJ, ob, "boost_anim", p["x"], p["y"], 0, frames=10)+ elif cname == "SafePointE":+ b = self.rect_body("static", F["SENSOR"], True, p["width"], p["height"], p["x"], p["y"],+ TO_RAD * p["rotation"], CB["SAFE"])+ ob = self.obj("SAFE", body=b, x=p["x"], y=p["y"], id=p.get("id", -1))+ self.sprite(C_OBJ, ob, "SafePointAnim", p["x"], p["y"], TO_RAD * p["rotation"], frames=2)+ elif cname == "MotorJointE":+ self.motor(p)+ elif cname == "PivotJointE":+ self.pivot(p)+ elif cname == "SpikesE":+ d = self.objects_json["SpikesE"]+ b = self.rect_body("static", F["GROUND"], False, d["w"], d["h"], p["x"], p["y"], TO_RAD * p["rotation"],+ CB["SPIKES"])+ ob = self.obj("SPIKES", body=b)+ self.sprite(C_OBJ, ob, "SpikesE", p["x"], p["y"], TO_RAD * p["rotation"])+ elif cname.startswith("Removed"):+ self.dyn(p, cname, "REMOVED")+ elif cname.startswith("Tnt"):+ self.tnt(p, cname)+ elif cname == "FinishZone":+ b = self.rect_body("static", F["SENSOR"], True, p["width"], p["height"], p["x"], p["y"],+ TO_RAD * p["rotation"], CB["FINISH"])+ ob = self.obj("FINISH", body=b)+ w, h = p["width"], p["height"]+ pts = [(p["x"] - w / 2, p["y"] - h / 2), (p["x"] + w / 2, p["y"] - h / 2), (p["x"] + w / 2, p["y"] + h / 2),+ (p["x"] - w / 2, p["y"] + h / 2)]+ self.draw(D_POLY, C_LAND, None, "finish", pts=pts, p=[p["x"] - w / 2, p["y"] - h / 2, 0, 0, 0, 0])+ self.finish_x = p["x"]+ elif cname in ("EggE", "OvalTemplate"):+ pass+ else:+ self.warn("level %d: %s left out" % (self.n, cname))++ def ground(self, p, cname):+ th = self.theme+ if p.get("rotation", 0) != 0:+ p = normalize_vertices(p)+ line_id = p.get("lineId", 0)+ cont = C_LAND+ if line_id == 3 and th == 0:+ cont = C_FRONT+ elif line_id == 3 and th == 1:+ cont = C_OBJ+ if p.get("physic") is True:+ self.ground_body(p)+ vs = p["vertices"]+ x0, y0 = vs[0]["x"], vs[0]["y"]+ m = [(v["x"] - x0, v["y"] - y0) for v in vs]+ vmax = 0.0+ for q in m:+ if q[1] > vmax:+ vmax = q[1]+ ox, oy = p["x"] + x0, p["y"] + y0+ if p.get("shape") is True or p.get("line") is True:+ if p.get("shape") is True:+ tex = "finish" if line_id == 100 else "tile%d" % th+ gx = min(q[0] for q in m)+ gy = min(q[1] for q in m)+ poly = [(m[0][0], vmax + 480)] + list(m) + [(m[-1][0], vmax + 480)]+ pts = [(ox + q[0], oy + q[1]) for q in poly]+ self.draw(D_POLY, cont, None, tex, pts=pts, p=[gx, gy, 0, 0, 0, 0])+ if p.get("line") is True:+ key, rope = None, False+ if line_id == 0:+ key, rope = "line%d" % th, True+ elif line_id == 1:+ key, rope = ("line_top_%d" % th, True) if th > 0 else ("line_wood_g", False)+ elif line_id == 2:+ key = None # "line_bg" is not in the atlas+ elif line_id == 3:+ key = "line_metal_g"+ if key:+ self.strip(cont, None, key, [(ox + q[0], oy + q[1]) for q in m], rope)+ if p.get("camera") is True:+ off = num(p.get("cameraOffsetY", 0))+ self.cams.append(([(ox + q[0], oy + q[1]) for q in m], off))++ def shaper(self, e, finish):+ th = self.theme+ layer = e.get("layer", 0)+ cont = C_SHAPES if finish or layer == 1 else C_LAND+ n_, y_ = e["x"], e["y"]+ body = None+ ob = self.obj("SHAPER", x=n_, y=y_)+ if not finish:+ ob["id"] = e.get("id", -1) if e.get("id") is not None else -1+ safe = e.get("safeId", -1)+ if safe is not None and safe <= -10:+ ob["flags"] |= 2 # skipRevive+ if e.get("rem") is False:+ ob["flags"] |= 1 # appears when toggled instead of going away+ is_static = finish or e.get("isStatic")+ if finish or e.get("physic") is True:+ if finish:+ mat = MAT_DEFAULT+ elif num(e.get("density", 1)) == 1:+ mat = MAT_DEFAULT+ else:+ mat = mat_with(e["density"])+ if finish:+ flt = F["SENSOR"]+ elif e.get("plr") is True:+ flt = F["PLAYER_ONLY"]+ elif e.get("ignore") is True:+ flt = F["NOTHING"]+ else:+ flt = F["GROUND"]+ body = self.poly_body(e, mat, flt, "static" if is_static else "dynamic")+ body.cb = CB["GROUND"]+ body.ground = True+ if finish:+ for s in body.shapes:+ s["sensor"] = True+ body.cb |= CB["FINISH"]+ else:+ if layer == 3:+ body.cb |= CB["SAW"]+ if layer == 9:+ body.cb |= CB["SPIKES"]+ body.align()+ ob["body"] = body+ bx, by = (n_ - body.x, y_ - body.y) if body else (0.0, 0.0)+ if finish or e.get("graphic") is True:+ tex = "tile_stone" if th == 1 else "RoadTile0_1"+ if finish:+ tex = "finish"+ elif layer == 1:+ tex = "tile_bg%d" % th+ elif layer == 2:+ tex = "tile%d" % th+ elif layer == 3:+ tex = "tile_saw"+ elif layer == 4:+ tex = "tile_rivet"+ elif layer == 5:+ tex = "tile_rivet_bg"+ elif layer == 6:+ tex = "tile_stone"+ line = None+ if not finish:+ if layer == 0:+ if th == 1:+ line, tex = "line_stone_shape", "tile_stone"+ else:+ line = "RoadLine0_4"+ elif layer == 1:+ line = "RoadLine0_Bg%d" % th+ elif layer == 2:+ if e.get("line") is True:+ line = "line_top1"+ elif layer == 3:+ line = "UnLine0"+ elif layer == 4:+ line = "line_rivet"+ elif layer == 6:+ line = "line_stone_shape"+ d = e["vertices"]+ local = [(v["x"] + bx, v["y"] + by) for v in d]+ mx = min(q[0] for q in local)+ my = min(q[1] for q in local)+ owner = ob+ # the texture's origin, in the drawing's own coordinates+ self.draw(D_POLY, cont, owner, tex, pts=local, p=[mx - jsmod(bx, 256), my - jsmod(by, 256), 0, 0, 0, 0])+ if line:+ outline = list(local)+ if abs(d[0]["x"] - d[-1]["x"]) > 4 or abs(d[0]["y"] - d[-1]["y"]) > 4:+ mid = (0.5 * (d[0]["x"] + d[-1]["x"]) + bx, 0.5 * (d[0]["y"] + d[-1]["y"]) + by)+ outline = [mid] + outline + [mid]+ self.strip(cont, owner, line, outline, "Bg" in line)+ if body:+ if e.get("rotation", 0) != 0:+ body.rotate(n_, y_, TO_RAD * e["rotation"])+ ob["x"], ob["y"], ob["rot"] = body.x, body.y, body.rot+ else:+ ob["x"], ob["y"], ob["rot"] = n_, y_, TO_RAD * e.get("rotation", 0)+ if body and e.get("isWheel"):+ ob["flags"] |= 4+ body.is_wheel = True++ def pather(self, e, pillar):+ if e.get("rotation", 0) != 0:+ e = normalize_vertices(e)+ t = e.get("type", 0)+ ob = self.obj("PLANK", x=e["x"], y=e["y"])+ body = None+ w = P = 0.0+ if e.get("physic"):+ c = e.get("shapeH")+ if t in (4, 5, 6):+ c = 20+ flt = F["NOTHING"] if t in (3, 7) else F["GROUND"]+ body = self.pather_body(e, mat_with(e.get("density", 1)), flt, c)+ body.cb = CB["SPIKES"] if t in (4, 5, 6) else CB["GROUND"]+ body.ground = True+ w, P = e["x"] - body.x, e["y"] - body.y+ ob["body"] = body+ ob["x"], ob["y"] = body.x, body.y+ if pillar or e.get("graphic"):+ if pillar:+ key = PILLAR_LINE[t] if t < len(PILLAR_LINE) else None+ elif t in (4, 5, 6):+ key = ROAD_LINE[9]+ else:+ key = ROAD_LINE[t + 5] if t + 5 < len(ROAD_LINE) else None+ if key == "line":+ key = None+ if key:+ pts = [(v["x"] + w, v["y"] + P) for v in e["vertices"]]+ if not body:+ pts = [(q[0] + e["x"], q[1] + e["y"]) for q in pts]+ self.strip(C_LAND, ob if body else None, key, pts, False)++ def decor(self, p, cname, li):+ th = self.theme+ e = cname+ dup = e.find("_dup")+ if dup >= 0:+ e = e[:dup]+ if e not in DECORS[th]:+ return+ cont = C_LAND if li <= 1 else C_FRONT+ back = False+ if th in (0, 2):+ cont, back = C_LAND, True+ if cname.startswith("Dec") and int(cname[3:].split("_")[0]) <= 7:+ cont, back = C_FRONT, False+ if e.startswith("Sign") and e != "SignPillar":+ cont, back = C_LAND, False+ ob = None+ if p.get("id") is not None and p.get("id", -1) >= 0:+ ob = self.obj("DECOR", id=p["id"])+ sx = p.get("scaleX", 1) if p.get("scaleX") is not None else 1+ sy = p.get("scaleY", 1) if p.get("scaleY") is not None else 1+ frames = 22 if e == "Dec12" else 1+ self.sprite(cont, ob, e, p["x"], p["y"], TO_RAD * p.get("rotation", 0), sx, sy, frames, back,+ flags=1 if e == "Dec12" else 0)++ def dyn(self, p, cname, kind):+ d = self.objects_json[cname]+ if d["shape"] == "circ":+ b = self.body("dynamic", p["x"], p["y"])+ b.rot = TO_RAD * p["rotation"]+ b.circle(0.5 * d["w"], MAT_DEFAULT, F["GROUND"])+ else:+ b = self.rect_body("dynamic", F["GROUND"], False, d["w"], d["h"], p["x"], p["y"], TO_RAD * p["rotation"],+ 0)+ if cname.startswith("Plank"):+ b.ground = True+ ob = self.obj(kind, body=b, x=b.x, y=b.y, rot=b.rot, id=p.get("id", -1) if p.get("id") is not None else -1)+ if p.get("active") is False:+ ob["flags"] |= 1+ self.sprite(C_OBJ, ob, cname, 0, 0, 0)++ def tnt(self, p, cname):+ d = self.objects_json[cname]+ b = None+ if p.get("physic"):+ b = self.rect_body("dynamic", F["WITH_EARTH_ONLY"], False, d["w"], d["h"], p["x"], p["y"],+ TO_RAD * p["rotation"], 0)+ ob = self.obj("TNT", body=b, x=p["x"], y=p["y"], rot=TO_RAD * p["rotation"],+ id=p.get("id", -1) if p.get("id") is not None else -1,+ p=[float(p.get("impulse", 0) or 0), float(p.get("count", 0) or 0), float(p.get("radius", 0) or 0),+ 0, 0, 0, 0, 0])+ if b:+ self.sprite(C_OBJ, ob, cname, 0, 0, 0)+ else:+ self.sprite(C_OBJ, ob, cname, p["x"], p["y"], TO_RAD * p["rotation"])++ def glass(self, p, cname):+ d = self.objects_json[cname]+ b = self.rect_body("static", F["GROUND"], False, d["w"], d["h"], p["x"], p["y"], TO_RAD * p["rotation"],+ CB["GLASS"] | CB["GROUND"])+ ob = self.obj("GLASS", body=b, x=p["x"], y=p["y"], rot=TO_RAD * p["rotation"],+ p=[float(p.get("ttl", 0) or 0), d["w"], d["h"], 1.0 if cname == "GlassCrashed0" else 0.5, 0, 0,+ 0, 0], cname=cname)+ self.sprite(C_OBJ, ob, cname, p["x"], p["y"], TO_RAD * p["rotation"])+ for k in range(6):+ self.images.add("GlassCrashed0_%d" % k)++ def water(self, p):+ b = self.poly_body(p, MAT_DEFAULT, F["WATER"], "static")+ b.cb = CB["WATER"] | (CB["SAW"] if p.get("layer") == 3 else 0)+ b.fluid = (num(p.get("viscosity"), 1.0), num(p.get("density"), 1.0))+ b.align()+ n_, y_ = p["x"], p["y"]+ bx, by = n_ - b.x, y_ - b.y+ if p.get("rotation", 0) != 0:+ b.rotate(n_, y_, TO_RAD * p["rotation"])+ ob = self.obj("WATER", body=b, x=b.x, y=b.y, rot=b.rot)+ pts = [(v["x"] + bx, v["y"] + by) for v in p["vertices"]]+ if self.theme == 0:+ self.draw(D_WATER, C_SHAPES, ob, None, pts=pts, p=[1, 0, 0, 0, 0, 0])+ self.draw(D_WATER, C_LAND, ob, None, pts=pts)++ def geyser(self, p):+ b = self.rect_body("static", F["SENSOR"], True, p["width"], p["height"], p["x"], p["y"],+ TO_RAD * p["rotation"], CB["GEYSER"])+ r = b.rot+ ob = self.obj("GEYSER", body=b, x=p["x"], y=p["y"], rot=r, id=p.get("id", -1),+ p=[p["speed"] * math.cos(r), p["speed"] * math.sin(r), p["width"], p["height"],+ float(p.get("rate", 1) if p.get("rate") is not None else 1), p["speed"], 0, 0])+ self.images.add("GeyserBase")+ self.images.add("geyser_anim")+ self.images.add("particle_boost")++ def mover(self, p):+ ob = self.obj("MOVER", id=p.get("id", -1), x=p["x"], y=p["y"])+ if p.get("body"):+ b = self.body("kinematic", 0, 0)+ b.circle(16, MAT_DEFAULT, F["NOTHING"])+ else:+ cands = [b for b in self.under((p["x"], p["y"])) if b.kind == "dynamic"]+ if not cands:+ self.warn("level %d: a mover with nothing to move" % self.n)+ self.objs.pop()+ return+ if len(cands) > 1:+ self.warn("level %d: a mover over %d bodies" % (self.n, len(cands)))+ b = cands[-1]+ b.kind = "kinematic"+ ob["body"] = b+ b.norot = True+ pts = [(p["x"] + v["x"], p["y"] + v["y"]) for v in p["vertices"]]+ ob["aux"] = pts+ accel = p.get("accelDist") or 0+ fl = 0+ if p.get("cycle") == 1:+ fl |= 1+ if p.get("active") == 1:+ fl |= 2+ if p.get("stopOnEnd") is True:+ fl |= 4+ if p.get("stopOnPoint") is True:+ fl |= 8+ ob["flags"] = fl+ ob["p"] = [float(p["speed"]), float(accel), float(p.get("startTime", 0) or 0),+ float(p.get("sideWait", 0) or 0), float((p.get("sideAngle", 0) or 0) * TO_RAD),+ float(p.get("position", 0) or 0), 0, 0]++ def motor(self, p):+ pt = (p["x"], p["y"])+ under = self.under(pt)+ s = None+ for b in reversed(under):+ if b.kind == "dynamic":+ s = b+ break+ if not s:+ self.warn("level %d: a motor over nothing" % self.n)+ return+ f = None+ for b in reversed(under):+ if b is s or (b.cb & CB["TOGGLE"]):+ continue+ f = b+ break+ ob = self.obj("MOTOR", id=p.get("id", -1), x=p["x"], y=p["y"])+ if f is not None and getattr(f, "is_wheel", False):+ f, s = s, f+ s.norot = True+ ob["body"] = s # body2: the one that turns+ ob["body2"] = f # body1: the other, or the world (a static body: its collisions with s are ignored)+ ob["p"] = [p.get("rate", 0) * TO_RAD, float(p.get("time", 0) or 0), 0, 0, 0, 0, 0, 0]+ g = p.get("graphic") or 0+ if g > 0:+ ob["img"] = "Motor%d" % (g - 1)+ self.images.add(ob["img"])++ def pivot(self, p):+ pt = (p["x"], p["y"])+ under = list(reversed(self.under(pt)))+ c = u = None+ for b in under:+ if b.kind == "dynamic":+ if c is None:+ c = b+ elif u is None:+ u = b+ break+ elif u is None:+ u = b+ if c is None:+ return+ if u is not None and u.kind == "static":+ u = None # the world+ ob = self.obj("PIVOT", id=p.get("id", -1), x=p["x"], y=p["y"], body=c, body2=u)+ g = p.get("graphic") or 0+ if g > 0:+ ob["img"] = "Pivot%d" % (g - 1)+ self.images.add(ob["img"])+diff --git a/games/motox3m/tools/pack.py b/games/motox3m/tools/pack.pynew file mode 100644index 00000000..493193d4--- /dev/null+++ b/games/motox3m/tools/pack.py@@ -0,0 +1,698 @@+#!/usr/bin/env python3+"""Packs Moto X3M's src/data.bin, src/data.h and src/bike_data.h from the game's HTML5 build (REF), read only:++ python3 -I tools/pack.py REF++REF holds the build's files as the web serves them: assets/levels/map1..50.json, objects.json, bike.json, 1.json;+assets/atlases/x1/theme, cars_game and garage (.png and .json); assets/images/x1/0bg_garage.png;+assets/fonts/Impact/impact.woff. Python 3 with Pillow."""+import json+import math+import os+import struct+import sys++import numpy as np+from PIL import Image, ImageDraw, ImageFont++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from geom import nape_poly # noqa: E402+from levels import (CB, C_FRONT, C_LAND, C_OBJ, C_SHAPES, FILTERS, Level, load, BG) # noqa: E402++HERE = os.path.dirname(os.path.abspath(__file__))+SRC = os.path.join(HERE, "..", "src")+NLEVELS = 50++warnings = []+++def warn(s):+ warnings.append(s)+++class Atlas:+ def __init__(self, ref, name):+ base = os.path.join(ref, "assets", "atlases", "x1", name)+ self.img = Image.open(base + ".png").convert("RGBA")+ d = load(base + ".json")+ fr = d["frames"]+ self.frames = fr if isinstance(fr, dict) else {f["filename"]: f for f in fr}++ def has(self, name):+ return name in self.frames++ def get(self, name):+ """a frame as its full source picture (trimmed borders back) and its size"""+ f = self.frames[name]+ r = f["frame"]+ if f.get("rotated"):+ raise ValueError("rotated frame " + name)+ crop = self.img.crop((r["x"], r["y"], r["x"] + r["w"], r["y"] + r["h"]))+ ss = f.get("sourceSize", {"w": r["w"], "h": r["h"]})+ sp = f.get("spriteSourceSize", {"x": 0, "y": 0})+ full = Image.new("RGBA", (ss["w"], ss["h"]), (0, 0, 0, 0))+ full.paste(crop, (sp["x"], sp["y"]))+ return full+++# ---- pictures ----++class Pics:+ def __init__(self):+ self.list = [] # (name, bytes)+ self.ids = {}++ def add(self, name, im, pivot, scale, tile=False, colors=255):+ """im: RGBA source; pivot in source pixels; stored scaled, cropped to its visible box unless a tile"""+ if name in self.ids:+ return self.ids[name]+ w, h = im.size+ sw, sh = max(1, round(w * scale)), max(1, round(h * scale))+ if tile:+ sw, sh = 1 << max(0, round(math.log2(sw))), 1 << max(0, round(math.log2(sh)))+ im = premul_resize(im, (sw, sh))+ px, py = pivot[0] * sw / w, pivot[1] * sh / h+ ox = oy = 0+ if not tile:+ bbox = im.getchannel("A").point(lambda a: 255 if a > 8 else 0).getbbox()+ if bbox is None:+ bbox = (0, 0, 1, 1)+ im = im.crop(bbox)+ ox, oy = bbox[0], bbox[1]+ data = encode(im, px - ox, py - oy, tile, colors)+ self.ids[name] = len(self.list)+ self.list.append((name, data))+ return self.ids[name]++ def blobs(self):+ """each picture's bytes once: repeated frames share them"""+ seen = {}+ out = []+ for name, data in self.list:+ out.append(seen.setdefault(data, len(seen)))+ uniq = sorted(seen, key=seen.get)+ return out, uniq+++def premul_resize(im, size):+ if im.size == size:+ return im+ a = np.asarray(im, dtype=np.float32) / 255+ pm = a.copy()+ pm[..., :3] *= pm[..., 3:4]+ r = np.stack([np.asarray(Image.fromarray((pm[..., k] * 255).astype(np.uint8), "L").resize(size, Image.LANCZOS),+ dtype=np.float32) / 255 for k in range(4)], axis=-1)+ al = r[..., 3:4]+ rgb = np.where(al > 0, np.clip(r[..., :3] / np.maximum(al, 1e-6), 0, 1), 0)+ out = np.concatenate([rgb, al], axis=-1)+ return Image.fromarray((out * 255 + 0.5).astype(np.uint8), "RGBA")+++def rgb565(r, g, b):+ return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)+++def encode(im, px, py, tile, colors):+ """w, h, pivot, colours (RGB565 + alpha), then a byte a pixel"""+ w, h = im.size+ # alpha in 5 steps so the drawing can skip, write or blend quickly+ arr = np.asarray(im).copy()+ al = arr[..., 3].astype(np.int32)+ al = np.where(al < 24, 0, np.where(al > 232, 255, np.minimum(255, (al + 32) // 64 * 64)))+ arr[..., 3] = al+ arr[al == 0, :3] = 0+ q = Image.fromarray(arr, "RGBA")+ if colors <= 16:+ pal_img = q.convert("RGB").quantize(colors=colors, method=Image.Quantize.MEDIANCUT,+ dither=Image.Dither.FLOYDSTEINBERG)+ if q.getchannel("A").getextrema()[0] < 255:+ pal_img = q.quantize(colors=colors, method=Image.Quantize.FASTOCTREE, dither=Image.Dither.FLOYDSTEINBERG)+ else:+ pal_img = q.quantize(colors=colors, method=Image.Quantize.FASTOCTREE, dither=Image.Dither.NONE)+ pal = pal_img.getpalette(rawmode="RGBA")+ n = len(pal) // 4+ idx = pal_img.tobytes()+ used = max(idx) + 1 if idx else 1+ n = min(n, used)+ opaque = all(pal[4 * i + 3] == 255 for i in range(n) if i in set(idx))+ flags = (1 if tile else 0) | (2 if opaque else 0)+ if n <= 16:+ flags |= 4 # two pixels a byte, the left one in the high bits+ rows = []+ for y in range(h):+ row = idx[y * w:(y + 1) * w] + (b"\0" if w & 1 else b"")+ rows.append(bytes((row[i] << 4) | row[i + 1] for i in range(0, len(row), 2)))+ idx = b"".join(rows)+ out = struct.pack("<HHffHBB", w, h, px, py, n, flags, 0)+ out += b"".join(struct.pack("<H", rgb565(pal[4 * i], pal[4 * i + 1], pal[4 * i + 2])) for i in range(n))+ out += bytes(min(255, pal[4 * i + 3]) for i in range(n))+ out += b"\0" * (-len(out) % 4)+ out += idx+ out += b"\0" * (-len(out) % 4)+ return out+++def anchor_pivot(im, ax, ay):+ return (ax * im.size[0], ay * im.size[1])+++# ---- fonts ----++def make_font(path, size, first=32, last=126):+ f = ImageFont.truetype(path, size)+ asc, desc = f.getmetrics()+ glyphs = []+ bits = b""+ for c in range(first, last + 1):+ ch = chr(c)+ bb = f.getbbox(ch)+ adv = round(f.getlength(ch))+ if bb[2] <= bb[0] or bb[3] <= bb[1]:+ glyphs.append((0, 0, 0, 0, adv, len(bits)))+ continue+ w, h = bb[2] - bb[0], bb[3] - bb[1]+ im = Image.new("L", (w, h), 0)+ ImageDraw.Draw(im).text((-bb[0], -bb[1]), ch, font=f, fill=255)+ data = bytes(v * 15 // 255 for v in im.tobytes())+ packed = bytes((data[i] << 4) | (data[i + 1] if i + 1 < len(data) else 0) for i in range(0, len(data), 2))+ glyphs.append((w, h, bb[0], bb[1] - asc, adv, len(bits)))+ bits += packed+ out = struct.pack("<BBBB", first, last - first + 1, asc + desc, asc)+ for g in glyphs:+ out += struct.pack("<BBbbBBHI", g[0], g[1], g[2], g[3], g[4], 0, 0, g[5])+ out += bits+ out += b"\0" * (-len(out) % 4)+ return out+++# ---- levels ----++class Pool:+ """a level's numbers, each list stored once (repeats share it)"""++ def __init__(self, fmt):+ self.fmt = fmt+ self.items = []+ self.seen = {}++ def add(self, vals):+ key = tuple(vals)+ if key in self.seen:+ return self.seen[key]+ off = len(self.items)+ self.items += list(vals)+ self.seen[key] = off+ return off++ def data(self):+ return struct.pack("<%d%s" % (len(self.items), self.fmt), *self.items)+++def i16(v):+ v = int(round(v))+ assert -32768 <= v <= 32767, v+ return v+++def pack_level(L, pics, theme_pic):+ mats = []++ def mat_index(m):+ m = tuple(float(x) for x in m)+ if m not in mats:+ mats.append(m)+ return mats.index(m)++ statics = [b for b in L.bodies if b.kind == "static"]+ dyns = [b for b in L.bodies if b.kind != "static"]+ sidx = {id(b): i for i, b in enumerate(statics)}+ didx = {id(b): i for i, b in enumerate(dyns)}++ # static shapes in world coordinates: their box, and their vertices in quarter pixels from its corner+ sshapes = []+ sverts = Pool("h")+ for bi, b in enumerate(statics):+ for s in b.shapes:+ if s["type"] != "poly":+ c = b.to_world(s["c"])+ verts = [(c[0] + s["r"] * math.cos(k * math.pi / 6), c[1] + s["r"] * math.sin(k * math.pi / 6))+ for k in range(12)]+ else:+ verts = [b.to_world(v) for v in s["v"]]+ p = nape_poly(verts)+ xs = [v[0] for v in p["v"]]+ ys = [v[1] for v in p["v"]]+ x0, y0 = math.floor(min(xs)), math.floor(min(ys))+ span = max(max(xs) - x0, max(ys) - y0)+ unit = 0+ while span * (4 >> unit if unit < 3 else 0.5) > 32000:+ unit += 1+ k = [4, 2, 1, 0.5][unit]+ q = []+ for v in p["v"]:+ q += [i16((v[0] - x0) * k), i16((v[1] - y0) * k)]+ flags = (1 if s["sensor"] else 0) | (2 if b.fluid else 0) | (unit << 4)+ off = sverts.add(q)+ assert off % 2 == 0 and off // 2 < 65536 and len(p["v"]) <= 48, (off, len(p["v"]))+ sshapes.append(struct.pack("<ffhhHBBBBH", x0, y0, i16(math.ceil(max(xs)) - x0 + 1),+ i16(math.ceil(max(ys)) - y0 + 1), off // 2, len(p["v"]), s["filter"],+ mat_index(s["mat"]), flags, bi))+ sbodies = []+ for b in statics:+ vis, den = b.fluid if b.fluid else (0.0, 0.0)+ sbodies.append(struct.pack("<HBBff", b.cb, 1, 1 if b.ground else 0, vis, den))++ # buckets: 256 px columns of the static shapes+ boxes = []+ for rec in sshapes:+ x0, y0, w, h = struct.unpack_from("<ffhh", rec)+ boxes.append((x0, x0 + w))+ if boxes:+ bx0 = math.floor(min(b0 for b0, _ in boxes) / 256) * 256 - 256+ bx1 = max(b1 for _, b1 in boxes) + 256+ else:+ bx0, bx1 = -256, 256+ nb = int((bx1 - bx0) // 256) + 1+ cols = [[] for _ in range(nb)]+ wide = []+ for i, (b0, b1) in enumerate(boxes):+ if b1 - b0 > 1536:+ wide.append(i) # checked every time+ continue+ for c in range(int((b0 - bx0) // 256), int((b1 - bx0) // 256) + 1):+ cols[c].append(i)+ buckets, blist = [], []+ for c in cols:+ buckets += [len(blist), len(c)]+ blist += c+ buckets += [len(blist), len(wide)]+ blist += wide+ assert len(blist) < 65536++ # dynamic and kinematic bodies, shapes in body coordinates (repeated shapes share their numbers)+ dbodies, dshapes = [], []+ ddata = Pool("f")+ for b in dyns:+ first = len(dshapes)+ for s in b.shapes:+ if s["type"] == "poly":+ p = nape_poly(s["v"])+ vals = []+ for v in p["v"]:+ vals += [v[0], v[1]]+ vals = [struct.unpack("<f", struct.pack("<f", v))[0] for v in vals]+ dshapes.append(struct.pack("<BBBBB3xfffffI", 1, len(p["v"]), s["filter"],+ 1 if s["sensor"] else 0, mat_index(s["mat"]), 0.0, p["com"][0], p["com"][1],+ p["area"], p["inertia"], ddata.add(vals)))+ else:+ r, c = s["r"], s["c"]+ dshapes.append(struct.pack("<BBBBB3xfffffI", 0, 0, s["filter"], 1 if s["sensor"] else 0,+ mat_index(s["mat"]), r, c[0], c[1], math.pi * r * r,+ r * r * 0.5 + c[0] ** 2 + c[1] ** 2, 0))+ flags = (4 if b.norot else 0) | (0x10 if b.ground else 0)+ dbodies.append(struct.pack("<fffHBBHBB", b.x, b.y, b.rot, first, len(b.shapes),+ 1 if b.kind == "dynamic" else 2, b.cb, flags, 0))++ params = Pool("f")+ # objects+ objs, aux = [], []+ for o in L.objs:+ b = o["body"]+ bi = di = -1+ if b is not None:+ if b.kind == "static":+ bi = sidx[id(b)]+ else:+ di = didx[id(b)]+ b2 = o["body2"]+ d2 = -1+ if b2 is not None and b2.kind != "static":+ d2 = didx[id(b2)]+ elif b2 is not None and bi < 0:+ bi = sidx[id(b2)] # a joint to a static body: its index (the joint ignores their collisions)+ img = theme_pic(o["img"]) if o["img"] else 0xFFFF+ a = len(aux) // 2+ for q in o["aux"]:+ aux += [q[0], q[1]]+ p = (list(o["p"]) + [0.0] * 8)[:8]+ po = params.add([float(v) for v in p]) if any(p) else 0+ objs.append(struct.pack("<BBhhhhhHHHH3f", o["kind"], o["flags"], int(o["id"] if o["id"] is not None else -1),+ int(o["id2"] if o["id2"] is not None else -1), di, bi, d2, img, len(o["aux"]), a, po,+ o["x"], o["y"], o["rot"]))++ # drawings, back to front: the containers in order, landscape's back items first (in reverse)+ def key(d):+ if d["cont"] == C_LAND and d["back"]:+ return (d["cont"], 0, -d["order"])+ return (d["cont"], 1, d["order"])++ draws = []+ dpts = Pool("h")+ for d in sorted(L.draws, key=key):+ img = theme_pic(d["img"]) if d["img"] else 0xFFFF+ if d["img"] and img == 0xFFFF:+ continue+ pts = d["pts"]+ flat = []+ for q in pts:+ flat += [i16(q[0]), i16(q[1])]+ off = dpts.add(flat) // 2 if flat else 0+ if d["kind"] == 0 and len(flat) > 8:+ dpts.seen.setdefault(tuple(flat[2:-2]), off * 2 + 2)+ if pts:+ xs = [q[0] for q in pts]+ ys = [q[1] for q in pts]+ bnd = (math.floor(min(xs)), math.floor(min(ys)), math.ceil(max(xs)), math.ceil(max(ys)))+ else:+ bnd = (0, 0, 0, 0)+ owner = d["owner"]["index"] if d["owner"] is not None else -1+ if d["kind"] == 2:+ pv = d["p"][:6] # sprite: x, y, angle, scale x, y, frames+ elif d["kind"] == 0:+ pv = d["p"][:2] # polygon: its texture's origin+ else:+ pv = d["p"][:1] # strip: rope; water: background+ po = params.add([float(v) for v in pv])+ draws.append(struct.pack("<BBBBhHHHH4h2x", d["kind"], d["cont"], d["flags"], 1 if d["back"] else 0, owner,+ len(pts), img, off, po, *[i16(v) for v in bnd]))++ cams = b""+ for c, dy in L.cams:+ flat = []+ for q in c:+ flat += [i16(q[0]), i16(q[1])]+ off = dpts.add(flat)+ cams += struct.pack("<HHf", off // 2, len(c), float(dy))++ parts = [("mats", b"".join(struct.pack("<5f", *m) for m in mats)),+ ("sshapes", b"".join(sshapes)),+ ("sverts", sverts.data()),+ ("sbodies", b"".join(sbodies)),+ ("buckets", struct.pack("<%dH" % len(buckets), *buckets)),+ ("blist", struct.pack("<%dH" % len(blist), *blist)),+ ("dbodies", b"".join(dbodies)),+ ("dshapes", b"".join(dshapes)),+ ("ddata", ddata.data()),+ ("objs", b"".join(objs)),+ ("aux", struct.pack("<%df" % len(aux), *aux)),+ ("draws", b"".join(draws)),+ ("dpts", dpts.data()),+ ("params", params.data()),+ ("cams", cams)]+ hdr_size = 4 + 2 * 10 + 4 * 8 + 4 * 15+ blob = b""+ offs = []+ sizes = {}+ for name, data in parts:+ blob += b"\0" * (-(hdr_size + len(blob)) % 4)+ offs.append(hdr_size + len(blob))+ blob += data+ sizes[name] = len(data)+ hdr = struct.pack("<BBBB", L.theme, len(mats), 0, 0)+ hdr += struct.pack("<10H", len(L.objs), len(sshapes), len(statics), len(dyns), len(dshapes), nb, len(draws),+ len(L.cams), len(aux) // 2, 0)+ hdr += struct.pack("<8f", 500.0 if not L.settings.get("gravityY") else float(L.settings["gravityY"]),+ *L.prizes[:3], L.start[0], L.start[1], L.finish_x, float(bx0))+ hdr += struct.pack("<15I", *offs)+ assert len(hdr) == hdr_size+ sizes["dverts"] = len(ddata.items) // 2+ return hdr + blob, sizes+++def main():+ if len(sys.argv) < 2:+ print(__doc__)+ sys.exit(1)+ ref = sys.argv[1]+ lv = os.path.join(ref, "assets", "levels")+ objects = load(os.path.join(lv, "objects.json"))+ theme = Atlas(ref, "theme")+ cars = Atlas(ref, "cars_game")+ garage = Atlas(ref, "garage")+ pics = Pics()++ # the levels first, to know which pictures they use+ levels = [Level(n, load(os.path.join(lv, "map%d.json" % n)), objects, warn) for n in range(1, NLEVELS + 1)]+ used = set()+ for L in levels:+ used |= L.images++ WORLD = 0.5+ ANCHOR = {"Dec12": (0.5, 0.7)}+ TILES = {"tile0", "tile1", "tile2", "tile_bg0", "tile_bg1", "tile_stone", "tile_saw", "tile_rivet",+ "tile_rivet_bg", "RoadTile0_1", "finish"}+ STRIPS = {"line0", "line1", "line2", "line_top_1", "line_top_2", "line_wood_g", "line_metal_g", "line_stone_shape",+ "RoadLine0_4", "RoadLine0_Bg0", "RoadLine0_Bg1", "line_top1", "UnLine0", "UnLine1", "line_rivet",+ "Plank0_line", "RoadLine0_7", "RoadLine0_8", "line_ivy", "LineChain", "RoadPillar0_0", "RoadPillar0_1",+ "RoadPillar0_2"}+ frames_of = {"Dec12": 22, "SafePointAnim": 2, "boost_anim": 10, "geyser_anim": 6}++ def theme_pic(name):+ if name in pics.ids:+ return pics.ids[name]+ if name.startswith("strip:"):+ src = name[6:]+ if not theme.has(src + "0000"):+ warn("no picture " + src)+ return 0xFFFF+ im = theme.get(src + "0000")+ return pics.add(name, im, (0, im.size[1] / 2), WORLD, tile=True)+ nframes = frames_of.get(name, 1)+ first = None+ for k in range(nframes):+ fname = "%s%04d" % (name, k)+ if not theme.has(fname):+ if k == 0:+ warn("no picture " + name)+ return 0xFFFF+ break+ im = theme.get(fname)+ if name in TILES:+ i = pics.add(name if k == 0 else "%s_%d" % (name, k), im, (0, 0), WORLD, tile=True, colors=16)+ elif name in STRIPS:+ i = pics.add(name if k == 0 else "%s_%d" % (name, k), im, (0, im.size[1] / 2), WORLD, tile=True)+ else:+ ax, ay = ANCHOR.get(name, (0.5, 0.5))+ i = pics.add(name if k == 0 else "%s_%d" % (name, k), im, anchor_pivot(im, ax, ay), WORLD)+ if first is None:+ first = i+ return first++ # pictures every level may use+ for n in ["CarExplode", "smoke_part_anim", "ground_part_anim"] + ["GlassCrashed0_%d" % k for k in range(6)]:+ frames_of.setdefault("CarExplode", 27)+ frames_of.setdefault("smoke_part_anim", 15)+ frames_of.setdefault("ground_part_anim", 26)+ theme_pic(n)+ for n in sorted(used):+ theme_pic(n)+ # strips: their pictures repeat along the line; Plank0 is also a sprite, so its strip gets its own name+ # backgrounds, at the screen's scale (the game draws them twice their size on a 720 x 480 screen)+ bg_ids = []+ for t in range(3):+ row = []+ for k in range(3):+ nm = BG[t][k]+ if nm:+ im = theme.get(nm + "0000")+ row.append(pics.add(nm, im, (0, 0), 1.0, colors=16))+ else:+ row.append(0xFFFF)+ bg_ids.append(row)++ # the bikes (cars atlas, world scale)+ from levels import TO_RAD # noqa: F401+ ASSETS = load(os.path.join(HERE, "bike_anchors.json"))+ bike_ids = []+ for skin in range(1, 7):+ k = skin - 1+ ids = []+ im = cars.get("bike_%d_base0000" % skin)+ ids.append(pics.add("bike_%d_base" % skin, im, anchor_pivot(im, ASSETS["FRAMES_ANCHORX"][k],+ ASSETS["FRAMES_ANCHORY"][k]), WORLD))+ im = cars.get("Car%dFrameExploded0000" % skin)+ ids.append(pics.add("Car%dFrameExploded" % skin, im, anchor_pivot(im, ASSETS["FRAMES_ANCHORX"][k],+ ASSETS["FRAMES_ANCHORY"][k]), WORLD))+ wname = ASSETS["WHEELS"][k]+ im = cars.get(wname + "0000")+ ids.append(pics.add(wname, im, anchor_pivot(im, 0.5, 0.5), WORLD))+ for part in ["driver_head", "driver_corpse", "driver_arm", "driver_forearm", "driver_hip", "driver_shin"]:+ im = cars.get("%s%d0000" % (part, skin))+ ids.append(pics.add("%s%d" % (part, skin), im, anchor_pivot(im, ASSETS["ARCHORS_X"][part][k],+ ASSETS["ARCHORS_Y"][part][k]), WORLD))+ im = cars.get("suspend_back%d0000" % skin)+ ids.append(pics.add("suspend_back%d" % skin, im, anchor_pivot(im, ASSETS["SUSPEND_BACK_ANCHORX"][k],+ ASSETS["SUSPEND_BACK_ANCHORY"][k]), WORLD))+ im = cars.get("suspend_front%d0000" % skin)+ ids.append(pics.add("suspend_front%d" % skin, im, anchor_pivot(im, ASSETS["SUSPEND_FRONT_ANCHORX"][k],+ ASSETS["SUSPEND_FRONT_ANCHORY"][k]), WORLD))+ bike_ids.append(ids)+ rocket = None+ for k in range(6):+ im = cars.get("RocketAnim%04d" % k)+ i = pics.add("RocketAnim_%d" % k, im, anchor_pivot(im, 1.0, 0.5), WORLD)+ rocket = i if rocket is None else rocket++ # the bikes as the menus show them+ def part_pic(g):+ for skin in range(1, 7):+ k = skin - 1+ for slot, nm in enumerate(["bike_%d_base" % skin, "Car%dFrameExploded" % skin, ASSETS["WHEELS"][k]]):+ if g == nm:+ return bike_ids[k][slot]+ if g.startswith("Wheel_"):+ return bike_ids[0][2] if g == "Wheel_1_0" else pics.ids.get(g, bike_ids[0][2])+ for slot, part in enumerate(["driver_head", "driver_corpse", "driver_arm", "driver_forearm", "driver_hip",+ "driver_shin", "suspend_back", "suspend_front"]):+ if g == "%s%d" % (part, skin):+ return bike_ids[k][3 + slot]+ raise KeyError(g)+ layouts = []+ b11 = objects["bike11"]+ lay = []+ for key in ["Wheel0", "Wheel1", "suspend_back", "base", "driver_corpse", "driver_hip", "driver_shin", "driver_arm",+ "driver_forearm", "driver_head", "suspend_front"]:+ q = b11[key]+ lay.append((part_pic(q["g"]), round(q["x"] * 2), round(q["y"] * 2), round(q["r"])))+ layouts.append(lay)+ for skin in range(1, 7):+ lay = []+ for q in objects["bike%d" % skin]:+ lay.append((part_pic(q["g"]), round(q["x"] * 2), round(q["y"] * 2), round(q["r"])))+ while len(lay) < 11:+ lay.append(lay[-1])+ layouts.append(lay[:11])+ fire = None+ for k in range(11):+ im = theme.get("hell_rider_head%04d" % k)+ i = pics.add("hell_rider_head_%d" % k, im, anchor_pivot(im, .5, .5), WORLD)+ fire = i if fire is None else fire++ # the menus (garage atlas, half size)+ UI = 0.5+ ui = {}+ for nm, ax, ay in [("timer_bg", .5, .5), ("star0", .5, .5), ("star1", .5, .5), ("w_star", .5, .5),+ ("orange_btn", .5, .5), ("orange_btn_big", .5, .5), ("orange_btn_big_green", .5, .5),+ ("next_btn", .5, .5), ("exit_btn", .5, .5), ("restart_btn", 0, 0), ("improved_bg", .5, .5),+ ("0logo", .5, .5), ("top_bg", 0, 0), ("pause_bg", 0, 0), ("0popup_bg", .5, .5),+ ("select_level", .5, .5), ("arrow_btn", .5, .5), ("play_btn", .5, .5), ("shop_btn", .5, .5)]:+ im = garage.get(nm + "0000")+ ui[nm] = pics.add("ui_" + nm, im, anchor_pivot(im, ax, ay), UI, colors=16 if nm == "0popup_bg" else 255)+ for k in range(6):+ im = garage.get("LeveMapItemLocked%04d" % k)+ i = pics.add("ui_map%d" % k, im, anchor_pivot(im, .5, .5), UI)+ if k == 0:+ ui["map"] = i+ for k in range(2):+ im = garage.get("arrow_keys%04d" % k)+ i = pics.add("ui_arrows%d" % k, im, anchor_pivot(im, 0, 0), UI)+ if k == 0:+ ui["arrows"] = i+ im = garage.get("0logo0000").rotate(-90, expand=True)+ ui["logo"] = pics.add("ui_logo", im, anchor_pivot(im, .5, .5), UI)+ im = Image.open(os.path.join(ref, "assets", "images", "x1", "0bg_garage.png")).convert("RGBA")+ ui["mapbg"] = pics.add("ui_mapbg", im, (0, 0), UI, colors=16)++ # fonts: the game's Impact and CF Crack and Bold, at half their sizes+ impact = os.path.join(ref, "assets", "fonts", "Impact", "impact.woff")+ crack = os.path.join(ref, "assets", "fonts", "CfCrackBold", "cfcrackandbold.woff")+ fonts = [make_font(impact, 11), make_font(crack, 15), make_font(crack, 20), make_font(crack, 36)]++ # levels+ lblobs = []+ stats = []+ for L in levels:+ blob, st = pack_level(L, pics, theme_pic)+ lblobs.append(blob)+ stats.append(st)++ # data.bin: "MX3D", counts, offsets, then everything+ nimg, nfont, nlev = len(pics.list), len(fonts), len(lblobs)+ head = struct.pack("<4sIII", b"MX3D", nimg, nfont, nlev)+ table_size = 4 * (nimg + nfont + nlev)+ pos = len(head) + table_size+ offs = []+ body = b""+ which, uniq = pics.blobs()+ uoff = []+ for data in uniq:+ uoff.append(pos + len(body))+ body += data+ for k in which:+ offs.append(uoff[k])+ for data in fonts:+ offs.append(pos + len(body))+ body += data+ for data in lblobs:+ body += b"\0" * (-(pos + len(body)) % 4)+ offs.append(pos + len(body))+ body += data+ out = head + struct.pack("<%dI" % len(offs), *offs) + body+ with open(os.path.join(SRC, "data.bin"), "wb") as f:+ f.write(out)++ # data.h+ with open(os.path.join(SRC, "data.h"), "w") as f:+ f.write("/* Moto X3M: what's in data.bin (made by tools/pack.py) */\n#ifndef MX_DATA_H\n#define MX_DATA_H\n")+ f.write("#define N_PICS %d\n#define N_FONTS %d\n#define N_LEVELS %d\n" % (nimg, nfont, nlev))+ for nm in sorted(ui):+ f.write("#define PIC_UI_%s %d\n" % (nm.upper(), ui[nm]))+ f.write("#define PIC_ROCKET %d\n" % rocket)+ for nm in ["CarExplode", "smoke_part_anim", "ground_part_anim", "GlassCrashed0_0", "GeyserBase",+ "geyser_anim", "particle_boost"]:+ if nm in pics.ids:+ f.write("#define PIC_%s %d\n" % (nm.upper(), pics.ids[nm]))+ f.write("static const uint16_t PIC_BG[3][3] = {%s};\n" %+ ", ".join("{%s}" % ", ".join(str(v) for v in r) for r in bg_ids))+ f.write("/* per bike: frame, frame exploded, wheel, head, corpse, arm, forearm, hip, shin, suspend back, front */\n")+ f.write("static const uint16_t PIC_BIKE[6][11] = {%s};\n" %+ ", ".join("{%s}" % ", ".join(str(v) for v in r) for r in bike_ids))+ f.write("enum { FONT_SMALL, FONT_MID, FONT_BIG, FONT_HUGE };\n")+ f.write("static const int16_t MAP_PTS[50][2] = {%s};\n" % ", ".join(+ "{%d, %d}" % (objects["point%d" % k]["x"], objects["point%d" % k]["y"]) for k in range(50)))+ f.write("/* bikes as the menus show them (bike11: the pause screen's, then bike1-6): picture, x, y, angle */\n")+ f.write("typedef struct { uint16_t pic; int16_t x, y, deg; } BikePart;\n")+ f.write("static const BikePart BIKE_LAYOUT[7][11] = {%s};\n" % ", ".join(+ "{%s}" % ", ".join("{%d, %d, %d, %d}" % q for q in lay) for lay in layouts))+ f.write("#define PIC_FIRE %d\n" % fire)+ f.write("#endif\n")+ # bike_data.h: the bike's numbers (levels/1.json) and its rider's parts and joints (levels/bike.json)+ car = load(os.path.join(lv, "1.json"))+ geo = load(os.path.join(lv, "bike.json"))+ def fl(v):+ t = "%.9g" % float(v)+ return (t if ("." in t or "e" in t) else t + ".0") + "f"++ with open(os.path.join(SRC, "bike_data.h"), "w") as f:+ f.write("/* Moto X3M: the bike, from the game's levels/1.json and levels/bike.json (made by tools/pack.py) */\n")+ f.write("#ifndef MX_BIKE_DATA_H\n#define MX_BIKE_DATA_H\n")+ for k in sorted(car):+ f.write("#define CAR_%s %s\n" % (k, fl(car[k])))+ f.write("typedef struct { float x, y, w, h, r; } PartGeo;\n")+ for k in ["driver_head", "driver_corpse", "driver_arm", "driver_forearm", "driver_hip", "driver_shin"]:+ g = geo[k]+ f.write("static const PartGeo GEO_%s = {%s, %s, %s, %s, %s};\n" % (+ k.upper(), fl(g["x"]), fl(g["y"]), fl(g["w"]), fl(g["h"]), fl(g["r"])))+ for k in ["hip_joint", "corpse_joint", "forearm_joint", "arm_joint", "head_joint", "steer_joint", "shin_joint",+ "suspend_back"]:+ g = geo[k]+ f.write("static const V2 GEO_%s = {%s, %s};\n" % (k.upper(), fl(g["x"]), fl(g["y"])))+ f.write("#define GEO_SUSPEND_BACK_W %s\n" % fl(geo["suspend_back_w"]))+ pts = geo["points"]+ f.write("static const V2 GEO_POINTS[%d] = {%s};\n" % (len(pts), ", ".join(+ "{%d, %d}" % (int(q["x"]), int(q["y"])) for q in pts)))+ f.write("#endif\n")+ tot = sum(len(d) for d in uniq)+ print("data.bin: %d bytes (pictures %d in %d, fonts %d, levels %d)" % (+ len(out), tot, nimg, sum(len(d) for d in fonts), sum(len(b) for b in lblobs)))+ tot = {}+ for st in stats:+ for k, v in st.items():+ tot[k] = tot.get(k, 0) + v+ print("levels:", tot)+ for w in sorted(set(warnings)):+ print("note:", w)+++if __name__ == "__main__":+ main()diff --git a/tests/ci.py b/tests/ci.pyindex 202944ab..1e86db0c 100644--- a/tests/ci.py+++ b/tests/ci.py@@ -24,7 +24,7 @@ HOST = ["numblocks", "numdrive", "championisland", "undertale", "doom", "isaac","hillclimb", "leveldevil", "cookieclicker", "jetpackjoyride", "donkeykong", "dune", "monkeymart","tombofthemask", "invaders", "sudoku", "uttt", "sokoban", "twoplayer", "flappydunk", "towerblock", "suika","doodlejump", "stickmanhook", "coreball", "uno", "fnf", "angrybirds", "polytrack", "paperclips", "badtime",- "mahjong", "rider", "snowrider", "templerun", "fnaf2", "famidash", "catninja"]+ "mahjong", "rider", "snowrider", "templerun", "fnaf2", "famidash", "catninja", "motox3m"]HOST_ARGS = {"fnf": " BUILD_DIR=../../build/data/games/fnf"}# seconds on CI (v1.24.3's run); the emulator's 71 apps took 2450 in all, the Python tests about 380WEIGHT = {"numblocks": 89, "numdrive": 20, "championisland": 69, "undertale": 445, "doom": 54, "isaac": 380,@@ -33,7 +33,7 @@ WEIGHT = {"numblocks": 89, "numdrive": 20, "championisland": 69, "undertale": 44"invaders": 7, "sudoku": 3, "uttt": 2, "sokoban": 2, "twoplayer": 114, "flappydunk": 2, "towerblock": 2,"suika": 112, "doodlejump": 5, "stickmanhook": 103, "coreball": 26, "uno": 36, "fnf": 80, "angrybirds": 627,"polytrack": 116, "paperclips": 164, "badtime": 59, "mahjong": 25, "rider": 137, "snowrider": 30,- "templerun": 384, "fnaf2": 654, "famidash": 7, "catninja": 60}+ "templerun": 384, "fnaf2": 654, "famidash": 7, "catninja": 60, "motox3m": 10}EMULATOR = 2450PYTHON = 380diff --git a/tests/test_games.py b/tests/test_games.pyindex f9915d4a..c59efaa1 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -325,6 +325,10 @@ GAMES = {presses((1500, "ok"), (2200, "ok"), (3000, "ok"), (4000, "ok"), (8000, "back"))+ [(5000, 7000, K["ok"])], 9000,presses((1500, "ok"), (2500, "ok")) + [(3500, 5500, K["ok"])], 6500),+ # Play, the first level, the gas held a while; Home saves. Next time, from the copy, the map, then On/Off+ "motox3m": ("MotoX3M.nwa", "motox3m.sav",+ presses((1500, "ok"), (2200, "ok"), (3000, "up", 4000)), 9000,+ presses((1500, "ok")), 3500),# 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,@@ -424,7 +428,7 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p"clashroyale": "clashroyale_saves.py","catninja": "catninja_saves.py","kingdomrush": "kingdomrush_saves.py",- "mrbullet": "mrbullet_saves.py"}+ "mrbullet": "mrbullet_saves.py", "motox3m": "motox3m_saves.py"}def paperclips_ok(v):@@ -723,6 +727,8 @@ CHECKS = {# "MRB1", version 1, its size (1216): the first level's three stars (8), cleared (604), how to play read (1208);# after the reinstall, from the copy, the same"mrbullet": (lambda v: len(v) == 1216 and v[:4] == b"MRB1" and v[8] == 3 and v[604] == 1 and v[1208] == 1,) * 2,+ # "MX3S", version 1, its size (264): the first level open (8), the second locked, the first bike (260)+ "motox3m": (lambda v: len(v) == 264 and v[:4] == b"MX3S" and v[8] <= 3 and v[9] == 0xFF and v[260] == 1,) * 2,"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 a9409bd0..3b83299c 100644--- a/tools/release.py+++ b/tools/release.py@@ -69,6 +69,7 @@ ALONE = {"catninja": ("Cat Ninja", "Richman Stewart's Flash platformer: its 30 levels of wall jumps and traps, the boss and the crystals"),"kingdomrush": ("Kingdom Rush", "Ironhide's 2011 tower defense: its 12 stages with Heroic and Iron challenges, every tower, spell and boss"),"mrbullet": ("Mr Bullet", "Lion Studios' spy puzzles: 596 levels of Classic, Grenades, Hostages and Friendly Fire, read from the game's own files"),+ "motox3m": ("Moto X3M", "Madpuffers' stunt bike racing: all 50 levels, the flips, the stars and the six bikes, on the game's own physics"),"numpico": ("NumPico", "PICO-8 carts on the calculator: add your own .p8 and .p8.png carts in NumPlay Studio"),}VARIANTS = [