Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Fix crashes and lost saves, README and release workflow

Mason363ee85c9d5e1d2
diff --git a/.github/release.md b/.github/release.md
new file mode 100644
index 00000000..8d51db7f
--- /dev/null
+++ b/.github/release.md
@@ -0,0 +1,10 @@
+**New to NumPlay?** Download `NumPlay.nwa`, then add it on [my.numworks.com/apps](https://my.numworks.com/apps) with your calculator plugged in. [How to install](https://github.com/Mason363/NumPlay/blob/main/docs/install.md) · [How to play](https://github.com/Mason363/NumPlay/blob/main/docs/play.md)
+
+| File | |
+| --- | --- |
+| **NumPlay.nwa** | Every game in one app |
+| NumDash.nwa | Jump to the beat |
+| CrossyRoad.nwa | Hop, dodge, survive |
+| NumDrive.nwa | Drive, flip, finish |
+| Tetris.nwa | Stack and clear lines |
+| NumChess.nwa | Bots, puzzles, 2 players |
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 00000000..3f752196
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,64 @@
+name: Build
+
+# Builds NumPlay.nwa and every game on its own. Pushing a tag like v1.2.0
+# publishes them as a GitHub release.
+
+on:
+ push:
+ branches: [main]
+ tags: ["v*"]
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: write
+
+jobs:
+ build:
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: ARM toolchain
+ run: |
+ v=15.2.1-1.1
+ curl -sSL "https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/releases/download/v$v/xpack-arm-none-eabi-gcc-$v-linux-x64.tar.gz" | tar -xz -C "$RUNNER_TEMP"
+ echo "$RUNNER_TEMP/xpack-arm-none-eabi-gcc-$v/bin" >> "$GITHUB_PATH"
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+
+ - name: Tools
+ run: |
+ sudo apt-get update -q && sudo apt-get install -yq pngquant
+ pip install pillow zopfli pyelftools unicorn==2.1.4
+ npm install -g [email protected]
+ rustup target add thumbv7em-none-eabihf
+
+ - name: Build
+ run: make -j4 nwa apps check NWLINK=nwlink
+
+ - name: Test
+ run: |
+ python3 tests/test_games.py build/apps
+ python3 tests/test_uninstall.py build/NumPlay.nwa --game numdrive
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: nwa
+ path: |
+ build/NumPlay.nwa
+ build/apps/*.nwa
+
+ - name: Release
+ if: startsWith(github.ref, 'refs/tags/v')
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ gh release create "$GITHUB_REF_NAME" build/NumPlay.nwa build/apps/*.nwa \
+ --title "NumPlay $GITHUB_REF_NAME" --notes-file .github/release.md
diff --git a/LICENSES/OFL-1.1-Nunito.txt b/LICENSES/OFL-1.1-Nunito.txt
new file mode 100644
index 00000000..c8210f08
--- /dev/null
+++ b/LICENSES/OFL-1.1-Nunito.txt
@@ -0,0 +1,93 @@
+Copyright 2014 The Nunito Project Authors (https://github.com/googlefonts/nunito)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/LICENSES/OFL-1.1-RammettoOne.txt b/LICENSES/OFL-1.1-RammettoOne.txt
new file mode 100644
index 00000000..035fdde7
--- /dev/null
+++ b/LICENSES/OFL-1.1-RammettoOne.txt
@@ -0,0 +1,93 @@
+Copyright 2011 The Rammetto Project Authors (https://github.com/googlefonts/RammettoFont), with Reserved Font Name Rammetto.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/Makefile b/Makefile
index 2f35f12a..e3815718 100644
--- a/Makefile
+++ b/Makefile
@@ -64,7 +64,9 @@ $(B)/modules/%.o: FORCE | $(B)
@if [ "$*" != tetris ]; then $(MAKE) --no-print-directory -C games/$* module NWLINK="$(NWLINK)"; \
else $(MAKE) --no-print-directory $(MOD_tetris); fi
$(ARM_LD) -r -d -T tools/module.ld $(MOD_$*) -o $(B)/modules/$*.1.o
- $(ARM_OBJCOPY) --keep-global-symbol=$(or $(ENTRY_$*),$(ENTRY)) $(B)/modules/$*.1.o $(B)/modules/$*.2.o
+ $(ARM_OBJCOPY) --keep-global-symbol=$(or $(ENTRY_$*),$(ENTRY)) \
+ --redefine-sym eadk_keyboard_scan=np_keyboard_scan --redefine-sym eadk_event_get=np_event_get \
+ $(B)/modules/$*.1.o $(B)/modules/$*.2.o
$(PY) tools/npmodule.py $(B)/modules/$*.2.o $@ --game $* --index $(INDEX_$*) \
--entry $(or $(ENTRY_$*),$(ENTRY)) --json $(B)/modules/$*.json
@@ -125,7 +127,7 @@ apps: | $(B)
# ------------------------------------------------------------------ simulator
SIM_numdash = games/numdash/build/sim-module.o
SIM_crossyroad = games/crossyroad/output/sim-module.o
-SIM_numdrive = games/numdrive/output/npsim/sim-module.o
+SIM_numdrive = games/numdrive/output/sim-module.o
SIM_chess = games/chess/output/sim-module.o
SIM_tetris = $(B)/sim/tetris.o
SIM_CFLAGS = -std=gnu11 -O2 -fPIC -DNP_SIMULATOR=1 $(EADK_SIM_CFLAGS) -Ilauncher/src -Wall -Wno-unused-parameter
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..13bb5879
--- /dev/null
+++ b/README.md
@@ -0,0 +1,63 @@
+<p align="center">
+ <img src="docs/media/icon.png" width="96" alt="NumPlay icon">
+</p>
+
+<h1 align="center">NumPlay</h1>
+
+<p align="center">
+ <b>Every game for your NumWorks calculator, in one app.</b><br>
+ NumDash, Crossy Road, NumDrive, Tetris and Chess.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay.nwa"><img src="https://img.shields.io/badge/Download-NumPlay.nwa-7B43FF?style=for-the-badge&logo=github" alt="Download NumPlay.nwa"></a>
+</p>
+
+<p align="center">
+ <a href="docs/install.md"><b>How to install</b></a> &nbsp;·&nbsp; <a href="docs/play.md"><b>How to play</b></a>
+</p>
+
+<p align="center">
+ Open to game requests! Email me at <a href="mailto:[email protected]">[email protected]</a>.
+</p>
+
+<p align="center">
+ <img src="docs/media/launcher.gif" width="640" alt="The NumPlay launcher on a NumWorks calculator, scrolling through its games">
+</p>
+
+## Games
+
+| | Game | Download |
+| :---: | --- | --- |
+| <img src="docs/media/thumb_numdash.png" width="120" alt="NumDash"> | **NumDash**<br>Jump to the beat | [NumDash.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumDash.nwa) |
+| <img src="docs/media/thumb_crossyroad.png" width="120" alt="Crossy Road"> | **Crossy Road**<br>Hop, dodge, survive | [CrossyRoad.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/CrossyRoad.nwa) |
+| <img src="docs/media/thumb_numdrive.png" width="120" alt="NumDrive"> | **NumDrive**<br>Drive, flip, finish | [NumDrive.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumDrive.nwa) |
+| <img src="docs/media/thumb_tetris.png" width="120" alt="Tetris"> | **Tetris**<br>Stack and clear lines | [Tetris.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/Tetris.nwa) |
+| <img src="docs/media/thumb_chess.png" width="120" alt="Chess"> | **Chess**<br>Bots, puzzles, 2 players | [NumChess.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumChess.nwa) |
+
+All of them are in `NumPlay.nwa`. Each one also installs on its own.
+
+## Gameplay
+
+<table>
+ <tr>
+ <td><img src="docs/media/numdash.gif" alt="NumDash gameplay"></td>
+ <td><img src="docs/media/crossyroad.gif" alt="Crossy Road gameplay"></td>
+ </tr>
+ <tr>
+ <td><img src="docs/media/numdrive.gif" alt="NumDrive gameplay"></td>
+ <td><img src="docs/media/tetris.gif" alt="Tetris gameplay"></td>
+ </tr>
+ <tr>
+ <td><img src="docs/media/chess.gif" alt="Chess against a bot"></td>
+ <td><img src="docs/media/uninstall.gif" alt="Uninstalling a game from NumPlay's settings to free up space"></td>
+ </tr>
+</table>
+
+## Acknowledgements
+
+- **[Tatone26](https://github.com/Tatone26/Numworks-games/tree/main/apps/tetris)** made Tetris and released it into the public domain.
+- **[gd3ds](https://github.com/AleFunky/gd3ds)** by AleFunky and friends, whose research into Geometry Dash made NumDash possible.
+- The **Nunito** and **Rammetto One** fonts, under the SIL Open Font License ([LICENSES](LICENSES)).
+
+<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road) or the makers of Drive Mad. Tetris is a trademark of The Tetris Company.</sub>
diff --git a/_config.yml b/_config.yml
new file mode 100644
index 00000000..b0620de1
--- /dev/null
+++ b/_config.yml
@@ -0,0 +1,4 @@
+title: NumPlay
+description: "Games for the NumWorks calculator: NumDash, Crossy Road, NumDrive, Tetris and Chess, in one app."
+theme: jekyll-theme-cayman
+exclude: [games, launcher, tools, tests, build, LICENSES, Makefile, .github]
diff --git a/docs/install.md b/docs/install.md
new file mode 100644
index 00000000..8eb2e797
--- /dev/null
+++ b/docs/install.md
@@ -0,0 +1,20 @@
+# How to install NumPlay
+
+You need your NumWorks calculator, its USB cable, and a computer with **Chrome** or **Edge**.
+
+1. **Download** [NumPlay.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay.nwa).
+2. **Plug** your calculator into the computer.
+3. **Open** [my.numworks.com/apps](https://my.numworks.com/apps), add `NumPlay.nwa` and follow the steps.
+4. **Play**: press the Home key and open **NumPlay**, at the end of the list of apps.
+
+<p align="center"><img src="media/home.png" width="480" alt="NumPlay's game carousel"></p>
+
+## Good to know
+
+- **Other apps.** The website installs every app you add in one go. If you also use other apps, add them in the same step as NumPlay.
+- **One game only?** Every game is also available on its own, from the [latest release](https://github.com/Mason363/NumPlay/releases/latest): `NumDash.nwa`, `CrossyRoad.nwa`, `NumDrive.nwa`, `Tetris.nwa` and `NumChess.nwa`. Install them the same way.
+- **Space.** NumPlay takes about 550 KB, less than installing the five games one by one. To free space, open the **Settings** card in NumPlay and uninstall the games you don't play.
+- **Your progress** is saved on the calculator, in the same files whether you play a game in NumPlay or on its own.
+- Made for the **NumWorks N0120**. Keep your calculator's software up to date on [my.numworks.com](https://my.numworks.com).
+
+Next: [how to play](play.md).
diff --git a/docs/media/chess.gif b/docs/media/chess.gif
new file mode 100644
index 00000000..bc0070c9
Binary files /dev/null and b/docs/media/chess.gif differ
diff --git a/docs/media/crossyroad.gif b/docs/media/crossyroad.gif
new file mode 100644
index 00000000..ede59430
Binary files /dev/null and b/docs/media/crossyroad.gif differ
diff --git a/docs/media/home.png b/docs/media/home.png
new file mode 100644
index 00000000..7042634e
Binary files /dev/null and b/docs/media/home.png differ
diff --git a/docs/media/icon.png b/docs/media/icon.png
new file mode 100644
index 00000000..fbd50449
Binary files /dev/null and b/docs/media/icon.png differ
diff --git a/docs/media/launcher.gif b/docs/media/launcher.gif
new file mode 100644
index 00000000..367f6f72
Binary files /dev/null and b/docs/media/launcher.gif differ
diff --git a/docs/media/numdash.gif b/docs/media/numdash.gif
new file mode 100644
index 00000000..d8e4136e
Binary files /dev/null and b/docs/media/numdash.gif differ
diff --git a/docs/media/numdrive.gif b/docs/media/numdrive.gif
new file mode 100644
index 00000000..ca01788c
Binary files /dev/null and b/docs/media/numdrive.gif differ
diff --git a/docs/media/social.png b/docs/media/social.png
new file mode 100644
index 00000000..abff317d
Binary files /dev/null and b/docs/media/social.png differ
diff --git a/docs/media/tetris.gif b/docs/media/tetris.gif
new file mode 100644
index 00000000..2cfff40f
Binary files /dev/null and b/docs/media/tetris.gif differ
diff --git a/docs/media/thumb_chess.png b/docs/media/thumb_chess.png
new file mode 100644
index 00000000..aa7f6375
Binary files /dev/null and b/docs/media/thumb_chess.png differ
diff --git a/docs/media/thumb_crossyroad.png b/docs/media/thumb_crossyroad.png
new file mode 100644
index 00000000..1c8d5f3d
Binary files /dev/null and b/docs/media/thumb_crossyroad.png differ
diff --git a/docs/media/thumb_numdash.png b/docs/media/thumb_numdash.png
new file mode 100644
index 00000000..13760ad2
Binary files /dev/null and b/docs/media/thumb_numdash.png differ
diff --git a/docs/media/thumb_numdrive.png b/docs/media/thumb_numdrive.png
new file mode 100644
index 00000000..71f73670
Binary files /dev/null and b/docs/media/thumb_numdrive.png differ
diff --git a/docs/media/thumb_tetris.png b/docs/media/thumb_tetris.png
new file mode 100644
index 00000000..2fa1822b
Binary files /dev/null and b/docs/media/thumb_tetris.png differ
diff --git a/docs/media/uninstall.gif b/docs/media/uninstall.gif
new file mode 100644
index 00000000..2df85407
Binary files /dev/null and b/docs/media/uninstall.gif differ
diff --git a/docs/play.md b/docs/play.md
new file mode 100644
index 00000000..3abfd8e4
--- /dev/null
+++ b/docs/play.md
@@ -0,0 +1,86 @@
+# How to play
+
+## NumPlay
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** (or 4 / 6) | Pick a game |
+| **OK** or **EXE** (or 5) | Play |
+| **Back** | Leave a game's main menu to come back here. On the carousel, quit NumPlay |
+| **Home** | Quit, from anywhere |
+
+The last card, **Settings**, uninstalls the games you don't play, to free up space.
+
+## NumDash
+
+<img src="media/numdash.gif" width="320" align="right" alt="NumDash gameplay: Stereo Madness">
+
+| Key | What it does |
+| --- | --- |
+| **OK**, **EXE** or **Up** | Jump. Hold to keep jumping, or to fly the ship up |
+| **Back** | Pause, or go back in menus |
+| **0** | Place a checkpoint (practice mode) |
+| **⌫** | Remove your last checkpoint |
+
+The **?** button on the main menu shows every key, including the level editor's.
+
+<br clear="right">
+
+## Crossy Road
+
+<img src="media/crossyroad.gif" width="320" align="right" alt="Crossy Road gameplay">
+
+| Key | What it does |
+| --- | --- |
+| **Up**, **OK** or **EXE** | Hop forward |
+| **Left / Right / Down** | Hop sideways or back |
+| **Back** | Pause |
+
+Keep moving, or the eagle gets you.
+
+<br clear="right">
+
+## NumDrive
+
+<img src="media/numdrive.gif" width="320" align="right" alt="NumDrive gameplay">
+
+| Key | What it does |
+| --- | --- |
+| **Right** | Drive forward |
+| **Left** | Brake and reverse |
+| **OK** or **Back** | Pause |
+| **Back** on a card | Level list (Back again to leave) |
+
+Don't floor it the whole way: too much gas flips the car.
+
+<br clear="right">
+
+## Tetris
+
+<img src="media/tetris.gif" width="320" align="right" alt="Tetris gameplay">
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** (or 4 / 6) | Move |
+| **Down** (or 2) | Soft drop |
+| **Up** (or 8) | Hard drop |
+| **OK / Back** | Rotate |
+| **⌫** | Hold the piece |
+| **Shift** | Pause |
+
+<br clear="right">
+
+## Chess
+
+<img src="media/chess.gif" width="320" align="right" alt="Chess against a bot">
+
+| Key | What it does |
+| --- | --- |
+| **Arrows** | Move the cursor |
+| **OK** or **EXE** | Pick a piece, then its move |
+| **Back** | Deselect, pause menu, or back |
+| **⌫** | Undo |
+
+12 bots from 150 to 2100 Elo, endless puzzles, and a two-player clock.
+
+<br clear="right">
diff --git a/games/chess/src/main.c b/games/chess/src/main.c
index 55d4c783..51afde58 100644
--- a/games/chess/src/main.c
+++ b/games/chess/src/main.c
@@ -1,5 +1,7 @@
#include <eadk.h>
#include <string.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/jump.h"
#include "chess.h"
#include "sprites.h"
@@ -262,9 +264,13 @@ static int prating = 800, pstreak, pdelta, spin_mode, spin_y, spin;
/* -------------------------------------------------------------- Input */
+/* Home and On/Off leave the app from anywhere: main() set this jump. */
+static np_jump_t leave;
+
static int key(int ms) {
int32_t t = ms;
int e = eadk_event_get(&t);
+ if (e == 6 || e == 8) np_jump(leave); /* Home, On/Off */
return e == K_EXE ? K_OK : e;
}
@@ -884,10 +890,12 @@ static int puzzle_menu(int *i) {
}
int main(void) {
+ np_app_begin();
+ if (np_save_jump(leave)) return np_app_end();
ch_init();
int m = 0, pk = 0;
for (;;) {
- if (main_menu(&m) < 0) return 0;
+ if (main_menu(&m) < 0) return np_app_end();
if (m == 0 && bot_select()) game(M_BOT);
if (m == 1 && puzzle_menu(&pk) >= 0) puzzles(pk);
if (m == 2 && time_select()) game(M_2P);
diff --git a/games/common/epsilon_app.h b/games/common/epsilon_app.h
new file mode 100644
index 00000000..497d0a2d
--- /dev/null
+++ b/games/common/epsilon_app.h
@@ -0,0 +1,102 @@
+/* Staying safe as an external app on the NumWorks calculator (Epsilon).
+ *
+ * Home. Epsilon normally leaves an app the moment Home is pressed, then
+ * reuses the app's RAM for its own memory pools. Whether a pool has to be
+ * rebuilt is decided by a flag stored in that same RAM, so an app that used
+ * it can leave the flag set over a broken pool: the calculator crashes soon
+ * after, resets, and loses its files (saves included). np_app_begin() asks
+ * Epsilon to hold Home back while the app runs, so the app sees Home as a key
+ * and quits by itself, and np_app_end() clears the app's RAM before handing it
+ * back. Both do nothing when the game runs inside the NumPlay launcher, which
+ * does the same for all its games.
+ *
+ * Files. The file system is found through the userland header of the
+ * software that runs this app: at the start of the userland of either
+ * firmware slot, 64 KiB later on models with an extra data sector. Only
+ * addresses in external flash are probed, which exist on every model.
+ *
+ * Include it in one file per app. */
+#ifndef EPSILON_APP_H
+#define EPSILON_APP_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+typedef struct {
+ uint32_t magic;
+ char version[8];
+ uint32_t storage_ram, storage_size;
+ uint32_t apps_flash_start, apps_flash_end;
+ uint32_t apps_ram_start, apps_ram_end;
+ uint32_t name_flash_start, name_flash_end;
+ uint32_t footer;
+} epsilon_userland_t;
+
+#if PLATFORM_DEVICE && !defined(HOST)
+
+/* The header of the software running this app, or NULL. */
+__attribute__((unused)) static const epsilon_userland_t *epsilon_userland(void) {
+ static const uint32_t where[] = {0x90010000u, 0x90020000u, 0x90410000u, 0x90420000u};
+ uint32_t self = (uint32_t)(uintptr_t)&epsilon_userland;
+ const epsilon_userland_t *found = NULL;
+ for (unsigned i = 0; i < sizeof where / sizeof where[0]; i++) {
+ const volatile epsilon_userland_t *h = (const volatile epsilon_userland_t *)(uintptr_t)where[i];
+ if (h->magic != 0xDEC0EDFEu || h->footer != 0xDEC0EDFEu) continue;
+ if (self < h->apps_flash_start || self >= h->apps_flash_end) continue;
+ if (found) return NULL; /* ambiguous: better not guess */
+ found = (const epsilon_userland_t *)h;
+ }
+ return found;
+}
+
+/* The record area of Epsilon's file system (after its magic word), or NULL. */
+__attribute__((unused)) static uint8_t *epsilon_storage(uint32_t *size) {
+ const epsilon_userland_t *h = epsilon_userland();
+ if (!h) return NULL;
+ uint32_t ram = h->storage_ram, n = h->storage_size;
+ bool in_ram = (ram >= 0x20000000u && ram + n + 8 <= 0x20040000u) || (ram >= 0x24000000u && ram + n + 8 <= 0x24040000u);
+ if (!in_ram || (ram & 3) || n < 1024 || n > 0x10000) return NULL;
+ const volatile uint8_t *fs = (const volatile uint8_t *)(uintptr_t)ram;
+ uint32_t head = fs[0] | fs[1] << 8 | fs[2] << 16 | (uint32_t)fs[3] << 24;
+ const volatile uint8_t *f = fs + 4 + n;
+ uint32_t foot = f[0] | f[1] << 8 | f[2] << 16 | (uint32_t)f[3] << 24;
+ if (head != 0xEE0BDDBAu || foot != 0xEE0BDDBAu) return NULL;
+ *size = n;
+ return (uint8_t *)(uintptr_t)ram + 4;
+}
+
+/* Bounds of this app's RAM, from the installer's linker script. */
+extern char _data_section_start_ram[], _heap_end[];
+/* Defined by the NumPlay launcher only. */
+extern const uint8_t numplay_launcher[] __attribute__((weak));
+static bool epsilon_home_held;
+
+/* Epsilon's circuit breaker: while locked, Home cannot interrupt the app
+ * (system calls 10 and 13, unchanged since 2021). */
+__attribute__((unused)) static void np_app_begin(void) {
+ if (numplay_launcher || !epsilon_userland()) return;
+ __asm__ volatile("svc 10" ::: "r0", "r1", "r2", "r3", "r12", "memory");
+ epsilon_home_held = true;
+}
+
+/* Call as `return np_app_end();` from main: nothing in RAM is used after. */
+__attribute__((unused, noinline)) static int np_app_end(void) {
+ if (numplay_launcher) return 0;
+ bool unlock = epsilon_home_held;
+ for (volatile uint32_t *p = (volatile uint32_t *)(void *)_data_section_start_ram; p < (volatile uint32_t *)(void *)_heap_end; p++)
+ *p = 0;
+ /* a Home press held back so far may take effect now: the RAM is clean */
+ if (unlock) __asm__ volatile("svc 13" ::: "r0", "r1", "r2", "r3", "r12", "memory");
+ return 0;
+}
+
+#else /* simulator, host tools */
+__attribute__((unused)) static uint8_t *epsilon_storage(uint32_t *size) {
+ (void)size;
+ return NULL;
+}
+static inline void np_app_begin(void) {}
+static inline int np_app_end(void) { return 0; }
+#endif
+
+#endif
diff --git a/games/common/epsilon_files.h b/games/common/epsilon_files.h
new file mode 100644
index 00000000..2ee4cfaf
--- /dev/null
+++ b/games/common/epsilon_files.h
@@ -0,0 +1,177 @@
+/* Small files in Epsilon's file system, done carefully.
+ *
+ * Records are packed in a buffer: a 16-bit size, the name ("base.ext" and a
+ * zero), then the content; a zero size ends the list. These helpers:
+ * - rewrite a record of the same size in place, so nothing moves;
+ * - always keep the list terminated when adding a record at the end;
+ * - when a record has to be removed from the middle, slide the others down
+ * (like Epsilon does) and clear Epsilon's cache of the last record it looked
+ * up, which would otherwise point into moved data. The cache (a name
+ * checksum and a pointer, after the buffer) is only cleared once found and
+ * verified; if it cannot be, only the last record can be removed.
+ *
+ * Needs epsilon_app.h. Include in one file. */
+#ifndef EPSILON_FILES_H
+#define EPSILON_FILES_H
+#include "epsilon_app.h"
+
+typedef struct {
+ uint8_t *buf;
+ uint32_t size;
+} ef_fs_t;
+
+static uint16_t ef_rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
+static void ef_wr16(uint8_t *p, uint32_t v) {
+ p[0] = (uint8_t)v;
+ p[1] = (uint8_t)(v >> 8);
+}
+static uint32_t ef_strlen(const char *s) {
+ uint32_t n = 0;
+ while (s[n]) n++;
+ return n;
+}
+
+static bool ef_open(ef_fs_t *fs) {
+ fs->buf = epsilon_storage(&fs->size);
+ return fs->buf != NULL;
+}
+
+/* Offset of the terminating zero size, or -1 if the list looks corrupt. */
+static int ef_end(const ef_fs_t *fs) {
+ uint32_t p = 0;
+ while (p + 2 <= fs->size) {
+ uint16_t n = ef_rd16(fs->buf + p);
+ if (!n) return (int)p;
+ if (n < 4 || p + n > fs->size) return -1;
+ p += n;
+ }
+ return -1;
+}
+
+/* Offset of the record named `name`, or -1. */
+static int ef_find(const ef_fs_t *fs, const char *name, int end) {
+ uint32_t len = ef_strlen(name) + 1;
+ for (uint32_t p = 0; (int)p < end; p += ef_rd16(fs->buf + p)) {
+ uint16_t n = ef_rd16(fs->buf + p);
+ if (n < 2 + len) continue;
+ uint32_t i = 0;
+ while (i < len && fs->buf[p + 2 + i] == (uint8_t)name[i]) i++;
+ if (i == len) return (int)p;
+ }
+ return -1;
+}
+
+#if PLATFORM_DEVICE && !defined(HOST)
+static uint32_t ef_crc_bytes(const void *data, uint32_t len) {
+ if (!len) return 0;
+ register uint32_t r0 __asm__("r0") = (uint32_t)(uintptr_t)data;
+ register uint32_t r1 __asm__("r1") = len;
+ __asm__ volatile("svc 15" : "+r"(r0), "+r"(r1) : : "r2", "r3", "r12", "memory");
+ return r0;
+}
+static uint32_t ef_crc_words(const uint32_t *data, uint32_t words) {
+ register uint32_t r0 __asm__("r0") = (uint32_t)(uintptr_t)data;
+ register uint32_t r1 __asm__("r1") = words;
+ __asm__ volatile("svc 16" : "+r"(r0), "+r"(r1) : : "r2", "r3", "r12", "memory");
+ return r0;
+}
+/* Epsilon's Record checksum: a CRC of the CRCs of the base name and extension. */
+static uint32_t ef_name_crc(const char *full) {
+ const char *dot = full;
+ while (*dot && *dot != '.') dot++;
+ if (!*dot) return 0;
+ uint32_t parts[2] = {ef_crc_bytes(full, (uint32_t)(dot - full)), ef_crc_bytes(dot + 1, ef_strlen(dot + 1))};
+ return ef_crc_words(parts, 2);
+}
+/* The (accessible size, cached checksum, cached pointer) triple after the
+ * buffer's end magic: exactly one candidate must pass every check. */
+static uint32_t *ef_cache(const ef_fs_t *fs, int end) {
+ uint32_t *after = (uint32_t *)(void *)(fs->buf + fs->size + 4), *found = NULL;
+ uint32_t base = (uint32_t)(uintptr_t)fs->buf;
+ for (int i = 1; i < 96; i++) {
+ uint32_t *w = after + i;
+ uint32_t accessible = w[0], crc = w[1], ptr = w[2];
+ if (accessible > fs->size || (int)accessible < end + 2 || accessible < fs->size / 2) continue;
+ if (!ptr) {
+ if (crc) continue;
+ } else {
+ if (ptr < base || ptr >= base + (uint32_t)end) continue;
+ uint32_t p = 0;
+ while ((int)p < end && p != ptr - base) p += ef_rd16(fs->buf + p);
+ if (p != ptr - base) continue;
+ if (!crc || crc != ef_name_crc((const char *)(uintptr_t)(ptr + 2))) continue;
+ }
+ if (found) return NULL;
+ found = w;
+ }
+ return found;
+}
+#else
+static uint32_t *ef_cache(const ef_fs_t *fs, int end) {
+ (void)fs, (void)end;
+ return NULL;
+}
+#endif
+
+/* Removes a record; true if it is gone (or was never there). */
+__attribute__((unused)) static bool ef_remove(const char *name) {
+ ef_fs_t fs;
+ if (!ef_open(&fs)) return false;
+ int end = ef_end(&fs);
+ if (end < 0) return false;
+ int at = ef_find(&fs, name, end);
+ if (at < 0) return true;
+ uint16_t size = ef_rd16(fs.buf + at);
+ if (at + size == end) { /* the last one: nothing moves */
+ ef_wr16(fs.buf + at, 0);
+ return true;
+ }
+ uint32_t *cache = ef_cache(&fs, end);
+ if (!cache) return false;
+ uint8_t *d = fs.buf + at;
+ const uint8_t *s = d + size;
+ for (int n = end + 2 - (at + size); n > 0; n--) *d++ = *s++;
+ for (int n = size; n > 0; n--) *d++ = 0;
+ cache[1] = cache[2] = 0;
+ return true;
+}
+
+/* Writes a record (creating it at the end if needed). */
+__attribute__((unused)) static bool ef_write(const char *name, const void *content, uint32_t len) {
+ ef_fs_t fs;
+ if (!ef_open(&fs)) return false;
+ int end = ef_end(&fs);
+ if (end < 0) return false;
+ uint32_t nlen = ef_strlen(name) + 1, total = 2 + nlen + len;
+ if (total > 0xFFFF) return false;
+ int at = ef_find(&fs, name, end);
+ if (at >= 0 && ef_rd16(fs.buf + at) != total) {
+ if (!ef_remove(name)) return false;
+ end = ef_end(&fs);
+ at = -1;
+ }
+ if (at < 0) {
+ if ((uint32_t)end + total + 2 > fs.size) return false;
+ at = end;
+ ef_wr16(fs.buf + at + total, 0); /* keep the list terminated */
+ for (uint32_t i = 0; i < nlen; i++) fs.buf[at + 2 + i] = (uint8_t)name[i];
+ ef_wr16(fs.buf + at, total);
+ }
+ const uint8_t *c = (const uint8_t *)content;
+ for (uint32_t i = 0; i < len; i++) fs.buf[at + 2 + nlen + i] = c ? c[i] : 0;
+ return true;
+}
+
+/* The content of a record (unaligned!) and its length, or NULL. */
+__attribute__((unused)) static const uint8_t *ef_read(const char *name, uint32_t *len) {
+ ef_fs_t fs;
+ if (!ef_open(&fs)) return NULL;
+ int end = ef_end(&fs);
+ if (end < 0) return NULL;
+ int at = ef_find(&fs, name, end);
+ if (at < 0) return NULL;
+ uint32_t nlen = ef_strlen(name) + 1;
+ *len = ef_rd16(fs.buf + at) - 2 - nlen;
+ return fs.buf + at + 2 + nlen;
+}
+#endif
diff --git a/games/common/jump.h b/games/common/jump.h
new file mode 100644
index 00000000..370cc036
--- /dev/null
+++ b/games/common/jump.h
@@ -0,0 +1,33 @@
+/* A minimal setjmp/longjmp for the calculator: newlib's pulls in the C++
+ * unwinder, and the Rust builds link no C library. Saves the callee-saved
+ * core registers, the stack pointer, the return address and s16-s31.
+ * On other platforms, the C library's. */
+#ifndef NP_JUMP_H
+#define NP_JUMP_H
+#include <stdint.h>
+
+#if PLATFORM_DEVICE && !defined(HOST) && defined(__arm__)
+typedef uint32_t np_jump_t[26];
+__attribute__((naked, returns_twice, noinline, unused)) static int np_save_jump(__attribute__((unused)) np_jump_t j) {
+ __asm__ volatile(
+ "mov r12, sp\n"
+ "stmia r0!, {r4-r11, r12, lr}\n"
+ "vstmia r0!, {s16-s31}\n"
+ "movs r0, #0\n"
+ "bx lr\n");
+}
+__attribute__((naked, noreturn, noinline, unused)) static void np_jump(__attribute__((unused)) np_jump_t j) {
+ __asm__ volatile(
+ "ldmia r0!, {r4-r11, r12, lr}\n"
+ "mov sp, r12\n"
+ "vldmia r0!, {s16-s31}\n"
+ "movs r0, #1\n"
+ "bx lr\n");
+}
+#else
+#include <setjmp.h>
+typedef jmp_buf np_jump_t;
+#define np_save_jump(j) setjmp(j)
+#define np_jump(j) longjmp(j, 1)
+#endif
+#endif
diff --git a/games/crossyroad/src/crossy.c b/games/crossyroad/src/crossy.c
index aa9d4ada..de552753 100644
--- a/games/crossyroad/src/crossy.c
+++ b/games/crossyroad/src/crossy.c
@@ -150,7 +150,6 @@ struct Rom {
uint16_t font[22][10];
uint16_t hand_ol[14], hand_in[14];
char save_name[15];
- uint32_t slots[2];
char s_crossy[7], s_road[5], s_new_top[8];
};
@@ -453,7 +452,6 @@ static const struct Rom rom_init = {
.hand_in = {0x000, 0x040, 0x040, 0x040, 0x04A, 0x04A, 0x62A, 0x73E,
0x7FE, 0x3FE, 0x3FC, 0x1FC, 0x000, 0x000},
.save_name = "crossyroad.sav",
- .slots = {0x90010000u, 0x90410000u}, // userland headers of the two firmware slots
.s_crossy = "CROSSY",
.s_road = "ROAD",
.s_new_top = "NEW TOP",
@@ -476,7 +474,6 @@ static const struct Rom rom_init = {
#define hand_ol G.rom.hand_ol
#define hand_in G.rom.hand_in
#define save_name G.rom.save_name
-#define slots G.rom.slots
#define str_crossy G.rom.s_crossy
#define str_road G.rom.s_road
#define str_new_top G.rom.s_new_top
@@ -1740,6 +1737,9 @@ static void render(void) {
// ---------------------------------------------------------------------------
// Persistence
+// (after the global register variable: this header defines functions)
+#include "../../common/epsilon_app.h"
+
// The calculator keeps its files in RAM; the userland header of the running
// firmware slot tells where. Top score and coins go in a tiny record named
// "crossyroad.sav", written only after the whole file system checks out.
@@ -1776,21 +1776,13 @@ static void fs_locate(void) {
}
#else
static void fs_locate(void) {
- uint32_t me; // any address inside this app: this code's own
- __asm__("mov %0, pc" : "=r"(me));
- for (int i = 0; i < 2; i++) {
- const volatile uint32_t *h = (const volatile uint32_t *)slots[i];
- if (h[0] != 0xDEC0EDFEu || me < h[5] || me >= h[6]) continue;
- uint32_t a = h[3], n = h[4];
- if ((a & 3) || a < 0x20000000u || a > 0x24080000u || n < 4096 || n > 0x20000 || (n & 3)) continue;
- const volatile uint32_t *st = (const volatile uint32_t *)a;
- if (st[0] != FS_MAGIC || st[1 + n / 4] != FS_MAGIC) continue;
- fs_buf = (uint8_t *)(a + 4);
- fs_size = n;
- uint8_t *f;
- if (!fs_walk(&f)) fs_buf = 0;
- return;
- }
+ // the userland header can be at four places (two firmware slots, with or
+ // without an extra data sector): N0120s use the second one
+ uint32_t n = 0;
+ fs_buf = epsilon_storage(&n);
+ fs_size = n;
+ uint8_t *f;
+ if (fs_buf && !fs_walk(&f)) fs_buf = 0;
}
#endif
@@ -1934,6 +1926,7 @@ int main(int argc, char *argv[]) {
#else
memcpy(&G.rom, &rom_init, sizeof(rom_init));
#endif
+ np_app_begin();
init_palette();
build_models();
load_save();
@@ -1945,6 +1938,7 @@ int main(int argc, char *argv[]) {
uint64_t k = eadk_keyboard_scan(), pr = k & ~prevk;
prevk = k;
#define PRESSED(key) ((pr >> (key)) & 1)
+ if (PRESSED(eadk_key_home) || PRESSED(eadk_key_on_off)) break;
int dir = -1;
if (PRESSED(eadk_key_up) || PRESSED(eadk_key_ok) || PRESSED(eadk_key_exe)) dir = 0;
else if (PRESSED(eadk_key_right)) dir = 1;
@@ -2006,5 +2000,5 @@ int main(int argc, char *argv[]) {
#if PLATFORM_DEVICE && !defined(HOST)
g9 = caller_r9;
#endif
- return 0;
+ return np_app_end();
}
diff --git a/games/games.json b/games/games.json
index 96f96add..3515c884 100644
--- a/games/games.json
+++ b/games/games.json
@@ -2,61 +2,94 @@
{
"id": "numdash",
"title": "NumDash",
- "tagline": "Geometry Dash, with the real levels",
+ "tagline": "Jump to the beat",
"credit": null,
"top": "0x3D6BFF",
"bottom": "0x14124F",
"accent": "0x35C759",
- "records": ["numdash.nds", "numdash.ndd", "numdash1.ndl", "numdash2.ndl", "numdash3.ndl"],
- "shots": ["docs/screenshots/menu.png", "docs/screenshots/gameplay.png", "docs/screenshots/level-complete.png"],
+ "records": [
+ "numdash.nds",
+ "numdash.ndd",
+ "numdash1.ndl",
+ "numdash2.ndl",
+ "numdash3.ndl"
+ ],
+ "shots": [
+ "docs/screenshots/menu.png",
+ "docs/screenshots/gameplay.png",
+ "docs/screenshots/level-complete.png"
+ ],
"repo": "https://github.com/Mason363/NumDash"
},
{
"id": "crossyroad",
"title": "Crossy Road",
- "tagline": "Hop across roads, rivers and rails",
+ "tagline": "Hop, dodge, survive",
"credit": null,
"top": "0x45B649",
"bottom": "0x10421C",
"accent": "0xFF8A1F",
- "records": ["crossyroad.sav"],
- "shots": ["screenshots/title.png", "screenshots/river.png", "screenshots/train.png"],
+ "records": [
+ "crossyroad.sav"
+ ],
+ "shots": [
+ "screenshots/title.png",
+ "screenshots/river.png",
+ "screenshots/train.png"
+ ],
"repo": "https://github.com/Mason363/CrossyWorks"
},
{
"id": "numdrive",
"title": "NumDrive",
- "tagline": "157 levels of Drive Mad style physics",
+ "tagline": "Drive, flip, finish",
"credit": null,
"top": "0x35A8F0",
"bottom": "0x123A63",
"accent": "0xFFB020",
- "records": ["drivemad.sav"],
- "shots": ["docs/shot1.png", "docs/shot2.png", "docs/shot3.png"],
+ "records": [
+ "drivemad.sav"
+ ],
+ "shots": [
+ "docs/shot1.png",
+ "docs/shot2.png",
+ "docs/shot3.png"
+ ],
"repo": "https://github.com/Mason363/NumDrive"
},
{
"id": "tetris",
"title": "Tetris",
- "tagline": "The classic, full screen. By Tatone26",
+ "tagline": "Stack and clear lines",
"credit": "Tatone26",
"top": "0x8A4DFF",
"bottom": "0x1E0B45",
"accent": "0xFF4FA3",
- "records": ["tetris.sav", "tetris.set"],
- "shots": ["docs/shot1.png", "docs/shot2.png", "docs/shot3.png"],
+ "records": [
+ "tetris.sav",
+ "tetris.set"
+ ],
+ "shots": [
+ "docs/shot1.png",
+ "docs/shot2.png",
+ "docs/shot3.png"
+ ],
"repo": "https://github.com/Tatone26/Numworks-games/tree/main/apps/tetris"
},
{
"id": "chess",
"title": "Chess",
- "tagline": "12 bots, endless puzzles, 2 players",
+ "tagline": "Bots, puzzles, 2 players",
"credit": null,
"top": "0x7FA650",
"bottom": "0x22211E",
"accent": "0x81B64C",
"records": [],
- "shots": ["docs/italian.png", "docs/bots.png", "docs/puzzle-mate1.png"],
+ "shots": [
+ "docs/italian.png",
+ "docs/bots.png",
+ "docs/puzzle-mate1.png"
+ ],
"repo": "https://github.com/Mason363/NumChess"
}
]
diff --git a/games/numdash/src/main.c b/games/numdash/src/main.c
index 03f97742..6d30b12a 100644
--- a/games/numdash/src/main.c
+++ b/games/numdash/src/main.c
@@ -11,6 +11,9 @@ int main(int argc, char **argv) {
(void)argc;
(void)argv;
if (!platform_init()) return 1;
+#if PLATFORM_DEVICE
+ platform_begin();
+#endif
app_init();
uint32_t prev = platform_millis(), acc = 0, fps_start = prev, frames = 0, pending = 0, render_ms = 30;
while (app.running) {
@@ -53,5 +56,9 @@ int main(int argc, char **argv) {
#endif
}
platform_close();
+#if PLATFORM_DEVICE
+ return platform_end();
+#else
return 0;
+#endif
}
diff --git a/games/numdash/src/platform.h b/games/numdash/src/platform.h
index 51d30fbe..dac2b2ec 100644
--- a/games/numdash/src/platform.h
+++ b/games/numdash/src/platform.h
@@ -11,6 +11,10 @@ enum { K_LEFT = 1, K_RIGHT = 2, K_UP = 4, K_DOWN = 8, K_OK = 16, K_EXE = 32,
bool platform_init(void);
void platform_close(void);
+/* On the calculator: hold Home back while the app runs, and clear its RAM
+ * when it ends (games/common/epsilon_app.h). */
+bool platform_begin(void);
+int platform_end(void);
/* Keys held now, plus keys pressed and released since the previous call. */
uint32_t platform_keys(void);
uint32_t platform_millis(void);
diff --git a/games/numdash/src/platform_eadk.c b/games/numdash/src/platform_eadk.c
index 75f8d9f7..8b94b3e7 100644
--- a/games/numdash/src/platform_eadk.c
+++ b/games/numdash/src/platform_eadk.c
@@ -1,6 +1,13 @@
#include "platform.h"
#include <eadk.h>
#include <string.h>
+#include "../../common/epsilon_app.h"
+
+bool platform_begin(void) {
+ np_app_begin();
+ return true;
+}
+int platform_end(void) { return np_app_end(); }
bool platform_init(void) { return true; }
void platform_close(void) {}
@@ -57,51 +64,12 @@ void platform_strip(int y, int h, const uint16_t *pixels) {
}
void platform_frame_end(void) { capture_keys(); }
-/* Only Epsilon's documented record buffer is used. A SlotInfo pointer is
- * available after a USB transfer but can be zero after a cold boot, so a
- * unique validated storage from either firmware slot is accepted too. */
-static uint8_t *storage_at(uint32_t address, size_t *size) {
-#if PLATFORM_DEVICE
- /* The optional extra-data sector shifts the userland header by 64 KiB. */
- if (address != 0x90010000 && address != 0x90020000 && address != 0x90410000 && address != 0x90420000) return NULL;
- const uint32_t *header = (const uint32_t *)(uintptr_t)address;
- if (header[0] != 0xDEC0EDFE || header[11] != 0xDEC0EDFE) return NULL;
- uint32_t ram = header[3], length = header[4];
- if (length < 1024 || length > 65536 || ram < 0x24000010 || ram > 0x24040000 - length - 8 || ram % 4) return NULL;
- const uint32_t *magic = (const uint32_t *)(uintptr_t)ram;
- if (*magic != 0xEE0BDDBA) return NULL;
- uint32_t footer;
- memcpy(&footer, (const uint8_t *)magic + 4 + length, 4);
- if (footer != 0xEE0BDDBA) return NULL;
- *size = length;
- return (uint8_t *)(uintptr_t)(ram + 4);
-#else
- (void)address; (void)size;
- return NULL;
-#endif
-}
+/* Epsilon's record buffer, found through the userland header of the
+ * software running this app (see games/common/epsilon_app.h). */
uint8_t *platform_storage(size_t *size) {
-#if !PLATFORM_DEVICE
- (void)size;
- return NULL;
-#endif
- const volatile uint32_t *slot = (const volatile uint32_t *)0x24000000;
- if (slot[0] == 0xEFEEDBBA && slot[3] == 0xEFEEDBBA) {
- uint8_t *a = storage_at(slot[2], size);
- if (a) return a;
- }
- static const uint32_t headers[] = {0x90010000, 0x90020000, 0x90410000, 0x90420000};
- uint8_t *match = NULL;
- size_t matched = 0;
- for (unsigned i = 0; i < 4; i++) {
- size_t bytes = 0;
- uint8_t *a = storage_at(headers[i], &bytes);
- if (!a) continue;
- if (match && (match != a || matched != bytes)) return NULL;
- match = a;
- matched = bytes;
- }
- if (match) *size = matched;
- return match;
+ uint32_t n = 0;
+ uint8_t *a = epsilon_storage(&n);
+ if (a) *size = n;
+ return a;
}
void platform_storage_commit(void) {}
diff --git a/games/numdrive/Makefile b/games/numdrive/Makefile
index 76033460..944670af 100644
--- a/games/numdrive/Makefile
+++ b/games/numdrive/Makefile
@@ -64,8 +64,8 @@ output/device/module.o: $(addprefix output/device/,$(SOURCES:.c=.o)) output/devi
@echo "LD $@"
$(Q) arm-none-eabi-gcc $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $^ -o $@
-sim-module: output/npsim/sim-module.o
-output/npsim/sim-module.o: $(addprefix src/,$(SOURCES)) src/pack.bin src/*.h
+sim-module: output/sim-module.o
+output/sim-module.o: $(addprefix src/,$(SOURCES)) src/pack.bin src/*.h
@mkdir -p output/npsim
$(Q) cd src && xxd -i -n pack_bin pack.bin > ../output/npsim/pack_bin.c
$(Q) for f in $(SOURCES); do cc -std=gnu11 -O2 -fPIC -fsingle-precision-constant -Wno-unused-function \
diff --git a/games/numdrive/host/platform_host.c b/games/numdrive/host/platform_host.c
index 82c8a58e..0579da7c 100644
--- a/games/numdrive/host/platform_host.c
+++ b/games/numdrive/host/platform_host.c
@@ -259,3 +259,6 @@ static void s_checkpoint(void) {
sr->done[s_id] = 0;
}
#endif
+
+void plat_begin(void) {}
+int plat_end(int code) { return code; }
diff --git a/games/numdrive/src/main.c b/games/numdrive/src/main.c
index 8be0b28a..bf81825d 100644
--- a/games/numdrive/src/main.c
+++ b/games/numdrive/src/main.c
@@ -107,7 +107,8 @@ int main(int argc, char **argv) {
#ifdef ARMTEST
environ = argv + 1; /* semihosting has no environment: pass KEY=VALUE arguments */
#endif
- if (!world_init()) return 1;
+ plat_begin();
+ if (!world_init()) return plat_end(1);
save_load();
int lvl = progress.last < nlevels ? progress.last : 0;
#ifdef HOST
@@ -116,7 +117,7 @@ int main(int argc, char **argv) {
if (!start_level(lvl)) {
plat_fill(0, 0, SCREEN_W, SCREEN_H, 0xF800);
plat_sleep(2000);
- return 1;
+ return plat_end(1);
}
int state = ST_PLAY, kind = CARD_PAUSE, anim = 0, sel = 1, lsel = 0, lscroll = 0;
bool dirty = true;
@@ -127,7 +128,7 @@ int main(int argc, char **argv) {
uint64_t k = plat_keys();
uint64_t hit = k & ~prev;
prev = k;
- if (k & KEY(K_HOME)) break;
+ if (k & (KEY(K_HOME) | KEY(K_ONOFF))) break;
/* frame pacing: fixed 60 Hz simulation, catching up when rendering is slow */
int steps = 1;
#ifndef HOST
@@ -240,5 +241,5 @@ int main(int argc, char **argv) {
}
plat_frame_done();
}
- return 0;
+ return plat_end(0);
}
diff --git a/games/numdrive/src/platform.h b/games/numdrive/src/platform.h
index 0bdde46d..f6e0f953 100644
--- a/games/numdrive/src/platform.h
+++ b/games/numdrive/src/platform.h
@@ -8,7 +8,7 @@
/* key bits follow eadk_key_t */
enum {
- K_LEFT = 0, K_UP = 1, K_DOWN = 2, K_RIGHT = 3, K_OK = 4, K_BACK = 5, K_HOME = 6,
+ K_LEFT = 0, K_UP = 1, K_DOWN = 2, K_RIGHT = 3, K_OK = 4, K_BACK = 5, K_HOME = 6, K_ONOFF = 8,
K_SHIFT = 12, K_ALPHA = 13, K_BACKSPACE = 17, K_FOUR = 36, K_SIX = 38, K_ONE = 42,
K_TWO = 43, K_THREE = 44, K_PLUS = 45, K_MINUS = 46, K_ZERO = 48, K_EXE = 52
};
@@ -23,5 +23,9 @@ void plat_vblank(void);
void plat_sleep(int ms);
uint32_t plat_random(void);
void plat_frame_done(void); /* host harness hook (captures frames) */
+/* On the calculator: hold Home back while the game runs, clear its RAM when
+ * it ends (games/common/epsilon_app.h). plat_end returns `code`. */
+void plat_begin(void);
+int plat_end(int code);
#endif
diff --git a/games/numdrive/src/platform_eadk.c b/games/numdrive/src/platform_eadk.c
index a11c230f..315315ff 100644
--- a/games/numdrive/src/platform_eadk.c
+++ b/games/numdrive/src/platform_eadk.c
@@ -1,5 +1,12 @@
#include <eadk.h>
#include "platform.h"
+#include "../../common/epsilon_app.h"
+
+void plat_begin(void) { np_app_begin(); }
+int plat_end(int code) {
+ np_app_end();
+ return code;
+}
void plat_push(int x, int y, int w, int h, const uint16_t *px) {
eadk_rect_t r = {(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h};
diff --git a/games/numdrive/src/save.c b/games/numdrive/src/save.c
index 7501d578..46dc8a30 100644
--- a/games/numdrive/src/save.c
+++ b/games/numdrive/src/save.c
@@ -34,31 +34,21 @@ void save_store(void) {
}
#else
+#include "../../common/epsilon_app.h"
+
static const char rec_name[] = "drivemad.sav";
#define SAVE_MAGIC 0x444Du
-#define USERLAND_MAGIC 0xDEC0EDFEu
-#define STORAGE_MAGIC 0xEE0BDDBAu
static uint8_t *storage_buf;
static uint32_t storage_size;
+/* The userland header can be at four places (two firmware slots, with or
+ * without an extra data sector): N0120s use the second one. */
static bool find_storage(void) {
- static const uint32_t cand[] = {0x90010000u, 0x90410000u};
- for (int i = 0; i < 2; i++) {
- const uint32_t *h = (const uint32_t *)cand[i];
- if (h[0] != USERLAND_MAGIC || h[11] != USERLAND_MAGIC) continue;
- uint32_t addr = h[3], size = h[4];
- if (addr < 0x20000000u || addr >= 0x24080000u || size < 1024 || size > 0x20000) continue;
- const uint32_t *fs = (const uint32_t *)addr;
- if (fs[0] != STORAGE_MAGIC) continue;
- uint32_t foot;
- memcpy(&foot, (const uint8_t *)addr + 4 + size, 4);
- if (foot != STORAGE_MAGIC) continue;
- storage_buf = (uint8_t *)addr + 4;
- storage_size = size;
- return true;
- }
- return false;
+ uint32_t n = 0;
+ storage_buf = epsilon_storage(&n);
+ storage_size = n;
+ return storage_buf != 0;
}
static inline uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
diff --git a/games/tetris/docs/shot1.png b/games/tetris/docs/shot1.png
index d39497f4..15786f12 100644
Binary files a/games/tetris/docs/shot1.png and b/games/tetris/docs/shot1.png differ
diff --git a/games/tetris/docs/shot2.png b/games/tetris/docs/shot2.png
index 4ea9ed3f..9ccce5fe 100644
Binary files a/games/tetris/docs/shot2.png and b/games/tetris/docs/shot2.png differ
diff --git a/games/tetris/docs/shot3.png b/games/tetris/docs/shot3.png
index dfa35d3b..ca77ac01 100644
Binary files a/games/tetris/docs/shot3.png and b/games/tetris/docs/shot3.png differ
diff --git a/games/tetris/numworks_utils/build.rs b/games/tetris/numworks_utils/build.rs
index 66c7a9c4..bc4b027d 100644
--- a/games/tetris/numworks_utils/build.rs
+++ b/games/tetris/numworks_utils/build.rs
@@ -1,39 +1,32 @@
use std::process::Command;
fn main() {
- // The C storage helpers read the calculator's memory directly: they are only
- // built for the calculator. Other targets (the simulator build of NumPlay)
- // provide the same functions.
+ // The C helpers (files, app lifetime) read the calculator's memory directly:
+ // they are only built for the calculator. Other targets (the simulator
+ // build of NumPlay) provide the same functions.
+ println!("cargo::rerun-if-changed=src/storage/storage.c");
+ println!("cargo::rerun-if-changed=../../common/epsilon_app.h");
+ println!("cargo::rerun-if-changed=../../common/epsilon_files.h");
+ println!("cargo::rerun-if-env-changed=NWLINK");
if !std::env::var("TARGET").unwrap_or_default().starts_with("thumb") {
return;
}
- // Exécuter la commande pour récupérer les CFLAGS
+ // compiler flags for the calculator, from nwlink ($NWLINK, or nwlink in the path)
+ let nwlink = std::env::var("NWLINK").unwrap_or_else(|_| "nwlink".to_string());
let output = Command::new("sh")
.arg("-c")
- .arg("nwlink eadk-cflags-device") // Remplacez $(NWLINK) par la commande appropriée
+ .arg(format!("{nwlink} eadk-cflags-device"))
.output()
- .expect("Échec lors de l'exécution de la commande NWLINK");
-
- if !output.status.success() {
- panic!(
- "La commande nwlink a échoué avec le statut : {}",
- output.status
- );
- }
- // Convertir la sortie en chaîne de caractères
- let cflags = String::from_utf8(output.stdout)
- .expect("Impossible de convertir la sortie de NWLINK en String");
+ .expect("could not run nwlink");
+ assert!(output.status.success(), "nwlink failed: {}", output.status);
+ let cflags = String::from_utf8(output.stdout).expect("nwlink output");
let mut build = cc::Build::new();
for flag in cflags.split_whitespace() {
build.flag(flag.trim_matches('"'));
}
build
.file("src/storage/storage.c")
- .file("src/storage/mystring.c")
- // .flag("-Os")
+ .flag("-Os")
.compiler("arm-none-eabi-gcc")
.compile("storage");
-
- println!("cargo::rerun-if-changed=src/storage/mystring.c");
- println!("cargo::rerun-if-changed=src/storage/storage.c");
}
diff --git a/games/tetris/numworks_utils/src/app.rs b/games/tetris/numworks_utils/src/app.rs
new file mode 100644
index 00000000..f5eb1f51
--- /dev/null
+++ b/games/tetris/numworks_utils/src/app.rs
@@ -0,0 +1,20 @@
+//! How a game starts and ends on the calculator.
+//!
+//! `run` starts the game with Home held back by Epsilon and cleans up when
+//! it ends; `leave` ends it from anywhere (Home, On/Off, or after a panic).
+//! Both are in C (src/storage/storage.c), which can jump out of the game.
+
+extern "C" {
+ fn np_app_run(game: extern "C" fn()) -> i32;
+ fn np_app_leave();
+}
+
+/// Runs `game` (an `extern "C" fn()`), returns when it ends or is left.
+pub fn run(game: extern "C" fn()) -> i32 {
+ unsafe { np_app_run(game) }
+}
+
+/// Ends the game now and returns from `run`.
+pub fn leave() {
+ unsafe { np_app_leave() }
+}
diff --git a/games/tetris/numworks_utils/src/eadk.rs b/games/tetris/numworks_utils/src/eadk.rs
index 4a231a56..d1569b6d 100644
--- a/games/tetris/numworks_utils/src/eadk.rs
+++ b/games/tetris/numworks_utils/src/eadk.rs
@@ -246,6 +246,10 @@ pub mod keyboard {
#[must_use]
pub fn scan() -> State {
let raw = unsafe { eadk_keyboard_scan() };
+ // Home and On/Off leave the app from anywhere (see crate::app)
+ if raw >> super::key::HOME & 1 != 0 || raw >> 8 & 1 != 0 {
+ crate::app::leave();
+ }
let mut state = raw;
for (pad, arrow) in [
(super::key::EIGHT, super::key::UP),
@@ -366,5 +370,11 @@ fn panic(info: &PanicInfo<'_>) -> ! {
Color::WHITE,
);
+ // leave cleanly after a key press, instead of freezing the calculator
+ crate::utils::wait_for_no_keydown();
+ while !keyboard::scan().any_down() {
+ timing::msleep(20);
+ }
+ crate::app::leave();
loop {}
}
diff --git a/games/tetris/numworks_utils/src/lib.rs b/games/tetris/numworks_utils/src/lib.rs
index 2e03ca7f..04bcb9bf 100644
--- a/games/tetris/numworks_utils/src/lib.rs
+++ b/games/tetris/numworks_utils/src/lib.rs
@@ -1,6 +1,7 @@
#![no_std]
#![no_main]
+pub mod app;
pub mod eadk;
pub mod graphical;
pub mod menu;
diff --git a/games/tetris/numworks_utils/src/storage.rs b/games/tetris/numworks_utils/src/storage.rs
index 871481bf..c8736371 100644
--- a/games/tetris/numworks_utils/src/storage.rs
+++ b/games/tetris/numworks_utils/src/storage.rs
@@ -1,5 +1,5 @@
use heapless::Vec;
-use low_level_storage::{extapp_fileErase, extapp_fileExists, extapp_fileRead, extapp_fileWrite};
+use low_level_storage::{extapp_fileExists, extapp_fileRead, extapp_fileWrite};
pub mod save;
@@ -7,23 +7,12 @@ pub const MAX_STORAGE_VALUES: usize = 32;
// const MAX_FILE_SIZE: usize = MAX_VALUES * 4; // which represents 64 values (each represented by a u32)
pub mod low_level_storage {
- #[link(name = "storage")]
+ // games/tetris/numworks_utils/src/storage/storage.c (on the calculator)
extern "C" {
- #[allow(dead_code)]
- fn reverse32(value: u32) -> u32;
- #[allow(dead_code)]
- fn strcmp(s1: *const u8, s2: *const u8);
pub fn extapp_fileExists(filename: *const u8) -> bool;
pub fn extapp_fileRead(filename: *const u8, len: *mut u32) -> *const u8;
pub fn extapp_fileWrite(filename: *const u8, content: *const u8, len: u32) -> bool;
pub fn extapp_fileErase(filename: *const u8) -> bool;
- pub fn extapp_size() -> u32;
- pub fn extapp_address() -> u32;
- pub fn extapp_used() -> u32;
- pub fn extapp_nextFree() -> *mut u32;
- pub fn extapp_isValid(address: *mut u32) -> bool;
- pub fn extapp_calculatorModel() -> u8;
- pub fn extapp_userlandAddress() -> *mut u32;
}
}
@@ -102,8 +91,8 @@ pub fn write_data(filename: &str, pos: Option<u32>, value: u32) -> usize {
res = values.len() - 1;
}
let name = record_name(filename);
- unsafe { extapp_fileErase(name.as_ptr()) };
- // A full storage only means the settings are not remembered.
+ // rewritten in place when the size is unchanged; a full storage only
+ // means the settings are not remembered
let _ = unsafe {
extapp_fileWrite(
name.as_ptr(),
diff --git a/games/tetris/numworks_utils/src/storage/mystring.c b/games/tetris/numworks_utils/src/storage/mystring.c
deleted file mode 100644
index 1100b5f0..00000000
--- a/games/tetris/numworks_utils/src/storage/mystring.c
+++ /dev/null
@@ -1,77 +0,0 @@
-#include "mystring.h"
-
-// I couldn't make the libc work with Rust and all... so I just remade those 4 functions that storage.c uses. It is definitely not a good solution, and I may look at it again later.
-
-// from github.com/numworks/epsilon/liba/
-int strcmp(const char *s1, const char *s2)
-{
- while (*s1 != '\0' && *s1 == *s2)
- {
- s1++;
- s2++;
- }
- return (*(unsigned char *)s1) - (*(unsigned char *)s2);
-}
-
-// from github.com/numworks/epsilon/liba/
-void *mymemcpy(void *__restrict__ dest, const void *__restrict__ src, size_t n)
-{
- char *destination = (char *)dest;
- char *source = (char *)src;
-
- while (n--)
- {
- *destination = *source;
- destination++;
- source++;
- }
-
- return dest;
-}
-
-// from github.com/numworks/epsilon/liba/
-void *mymemmove(void *dest, const void *src, size_t n)
-{
- char *destination = (char *)dest;
- char *source = (char *)src;
-
- if (source < destination && destination < source + n)
- {
- /* Copy backwards to avoid overwrites */
- source += n;
- destination += n;
- while (n--)
- {
- *--destination = *--source;
- }
- }
- else
- {
- while (n--)
- {
- *destination++ = *source++;
- }
- }
-
- return dest;
-}
-
-// from github.com/numworks/epsilon/liba/
-void *mymemset(void *s, int c, size_t n)
-{
- char *destination = (char *)s;
- while (n--)
- {
- *destination++ = (unsigned char)c;
- }
- return s;
-}
-
-// from github.com/numworks/epsilon/liba/
-unsigned int strlen(const char *s)
-{
- const char *str = s;
- while (*str)
- str++;
- return str - s;
-}
\ No newline at end of file
diff --git a/games/tetris/numworks_utils/src/storage/mystring.h b/games/tetris/numworks_utils/src/storage/mystring.h
deleted file mode 100644
index cee96c83..00000000
--- a/games/tetris/numworks_utils/src/storage/mystring.h
+++ /dev/null
@@ -1,15 +0,0 @@
-#ifndef MYSTRING_H
-#define MYSTRING_H
-
-#include <stddef.h>
-
-#define CPY_DIR_LOWER_TO_HIGHER 0
-#define CPY_DIR_HIGHER_TO_LOWER 1
-
-int strcmp(const char *s1, const char *s2);
-void *mymemcpy(void *__restrict__ dest, const void *__restrict__ src, size_t n);
-void *mymemmove(void *dest, const void *src, size_t n);
-void *mymemset(void *s, int c, size_t n);
-unsigned int strlen(const char *s);
-
-#endif
\ No newline at end of file
diff --git a/games/tetris/numworks_utils/src/storage/save.rs b/games/tetris/numworks_utils/src/storage/save.rs
index 1d10a9e1..016b2c54 100644
--- a/games/tetris/numworks_utils/src/storage/save.rs
+++ b/games/tetris/numworks_utils/src/storage/save.rs
@@ -69,7 +69,7 @@ pub fn load_save<T: GameSave>(app: &str, slot: Option<u8>) -> Option<T> {
let word_count = (len as usize / 4).min(MAX_STORAGE_VALUES);
for i in 0..word_count {
- let val: u32 = unsafe { data_ptr.add(i * 4).cast::<u32>().read() };
+ let val: u32 = unsafe { data_ptr.add(i * 4).cast::<u32>().read_unaligned() };
words.push(val).ok()?;
}
@@ -80,10 +80,7 @@ pub fn write_save<T: GameSave>(app: &str, slot: Option<u8>, state: &T) -> bool {
let filename = get_save_filename(app, slot);
let words = state.to_words();
- if unsafe { extapp_fileExists(filename.as_ptr()) } {
- unsafe { extapp_fileErase(filename.as_ptr()) };
- }
-
+ // replaced in place when it has the same size
unsafe {
extapp_fileWrite(
filename.as_ptr(),
diff --git a/games/tetris/numworks_utils/src/storage/storage.c b/games/tetris/numworks_utils/src/storage/storage.c
index f74c7bf0..3d5abf11 100644
--- a/games/tetris/numworks_utils/src/storage/storage.c
+++ b/games/tetris/numworks_utils/src/storage/storage.c
@@ -1,305 +1,47 @@
-// https://framagit.org/Yaya.Cout/numworks-extapp-storage (thanks !)
-// copyright (c) 2021-2022 Numworks
-// Not the most optimised thing but pretty clean and working. Allows writing a lot of differents files to the storage.
-// In storage.rs, I made a wrapper to call those functions easily in a concrete environment : storing game data and options.
-
-#include <stdbool.h>
+/* Files and app lifetime for the Rust games, on the calculator.
+ *
+ * The file functions wrap games/common/epsilon_files.h, which finds Epsilon's
+ * file system through the userland header of the running software, keeps the
+ * record list terminated and clears Epsilon's record cache when records move.
+ * (They replace the earlier helpers, which could write through a null header
+ * address after a cold boot and could corrupt the records that follow an
+ * erased one.)
+ *
+ * np_app_run() runs the game with Home held back by Epsilon, so that leaving
+ * cleans up first (see games/common/epsilon_app.h); np_app_leave() leaves
+ * from anywhere, for Home or a panic. */
#include "storage.h"
-#include <stdint.h>
-#include "mystring.h"
-
-// Taken from https://codereview.stackexchange.com/questions/151049/endianness-conversion-in-c/151070#151070
-// I could convert the endianness manually, but it's less readable.
-uint32_t reverse32(uint32_t value)
-{
- return (((value & 0x000000FF) << 24) |
- ((value & 0x0000FF00) << 8) |
- ((value & 0x00FF0000) >> 8) |
- ((value & 0xFF000000) >> 24));
-}
-
-bool extapp_fileExists(const char *filename)
-{
- uint32_t storageAddress = extapp_address();
- char *offset = (char *)storageAddress;
- const char *endAddress = (char *)extapp_size() + storageAddress;
-
- if (!extapp_isValid((const uint32_t *)offset))
- {
- // Storage is invalid
- return false;
- }
-
- offset += 4;
- int currentRecord = 0;
-
- while (offset < endAddress)
- {
- uint16_t size = *(uint16_t *)offset;
- if (size == 0)
- {
- break;
- }
- char *name = offset + 2;
-
- if (strcmp(name, filename) == 0)
- {
- // File was found
- return true;
- }
-
- offset += size;
- currentRecord++;
- }
-
- return false;
-}
-
-char *extapp_fileRead(const char *filename, size_t *len)
-{
- uint32_t storageAddress = extapp_address();
- char *offset = (char *)storageAddress;
- const char *endAddress = (char *)extapp_size() + storageAddress;
-
- if (!extapp_isValid((const uint32_t *)offset))
- {
- // Storage is invalid
- return NULL;
- }
-
- offset += 4;
-
- while (offset < endAddress)
- {
- uint16_t size = *(uint16_t *)offset;
- if (size == 0)
- {
- break;
- }
- char *name = offset + 2;
-
- if (strcmp(name, filename) == 0)
- {
- // filename + \0
- uint16_t nameSize = strlen(name) + 1;
- // Size contains size + filename + real content. Here, we only want the
- // content
- *len = size - 2 - nameSize;
- // offset + size + filename
- return offset + 2 + nameSize;
- }
-
- offset += size;
- }
-
- // File not found
- return NULL;
-}
-
-bool extapp_fileWrite(const char *filename, const char *content, size_t len)
-{
- // Check if we have enough free space
- const uint32_t *recordStartPointer = extapp_nextFree();
- // Start Address + size + filename + \0 + content
- const uint32_t *recordEndPointer = (uint32_t *)((char *)recordStartPointer + 2 + strlen(filename) + 1 + len);
- const uint32_t *storageEndPointer = (uint32_t *)(extapp_address() + extapp_size());
-
- // In case where we have overflown storage, we return an error
- if (storageEndPointer <= recordEndPointer)
- {
- return false;
- }
-
- char *writableRecordStartPointer = (char *)extapp_nextFree();
-
- // We have enough storage, so we can write the data
- // Write size :
- // size + filename + \0 + content
- const uint16_t totalSize = 2 + strlen(filename) + 1 + len;
-
- *(uint16_t *)writableRecordStartPointer = totalSize;
-
- // Write filename:
- mymemcpy(writableRecordStartPointer + 2, filename, strlen(filename) + 1); // COUPABLE DU CRASH !!!! ouuuiiiin (mon avis : résoudre ce problème = résoudre le problème de erase aussi)
-
- // Write content:
- mymemcpy(writableRecordStartPointer + 2 + strlen(filename) + 1, content, len);
-
- // The record is now written, so we can return
- return true;
-}
-
-bool extapp_fileErase(const char *filename)
-{
- uint32_t storageAddress = extapp_address();
- char *offset = (char *)storageAddress;
- const char *endAddress = (char *)extapp_size() + storageAddress;
-
- if (!extapp_isValid((const uint32_t *)offset))
- {
- // Storage is invalid
- return false;
- }
-
- offset += 4;
-
- // Locate the record address
- char *recordAddress = NULL;
- uint16_t file_size;
- while (offset < endAddress)
- {
- uint16_t size = *(uint16_t *)offset;
- if (size == 0)
- {
- file_size = 0;
- break;
- }
- char *name = offset + 2;
-
- if (strcmp(name, filename) == 0)
- {
- recordAddress = offset;
- file_size = size;
- break;
- }
-
- offset += size;
- }
+#include "../../../../common/epsilon_files.h"
+#include "../../../../common/jump.h"
- // File not found
- if (recordAddress == NULL)
- {
- return false;
- }
-
- // Move the rest of the data
- // Why not len + 2 ?
- mymemmove(offset, offset + file_size, (char *)extapp_nextFree() - offset);
-
- // Overwrite the rest of the storage with zeroes
- // the + 1 in len + 1 is for the uint16_t used for file size
- mymemset(offset + *(uint16_t *)offset + 1, 0, file_size + 1);
-
- return true;
+bool extapp_fileExists(const char *filename) {
+ uint32_t len;
+ return ef_read(filename, &len) != NULL;
}
-uint32_t extapp_address()
-{
- return *(uint32_t *)((*extapp_userlandAddress()) + 0xC);
+const char *extapp_fileRead(const char *filename, uint32_t *len) {
+ return (const char *)ef_read(filename, len);
}
-uint32_t extapp_size()
-{
- return *(uint32_t *)((*extapp_userlandAddress()) + 0x10);
+bool extapp_fileWrite(const char *filename, const char *content, uint32_t len) {
+ return ef_write(filename, content, len);
}
-uint32_t *extapp_nextFree()
-{
- uint32_t storageAddress = extapp_address();
- char *offset = (char *)storageAddress;
- const char *endAddress = (char *)extapp_size() + storageAddress;
-
- if (!extapp_isValid((const uint32_t *)offset))
- {
- // Storage is invalid
- return NULL;
- }
+bool extapp_fileErase(const char *filename) { return ef_remove(filename); }
- offset += 4;
+static np_jump_t leave;
+static bool running;
- while (offset < endAddress)
- {
- uint16_t size = *(uint16_t *)offset;
- if (size == 0)
- {
- // Here, we are at the place where new records should start
- return (uint32_t *)offset;
- }
-
- offset += size;
- }
-
- // If we exited the loop, it mean that we have gone out of the storage
- return NULL;
- // return (uint32_t *)storageAddress + extapp_size();
+int np_app_run(void (*game)(void)) {
+ np_app_begin();
+ if (!np_save_jump(leave)) {
+ running = true;
+ game();
+ }
+ running = false;
+ return np_app_end();
}
-uint32_t extapp_used()
-{
- return (uint32_t)extapp_nextFree() - extapp_address();
+void np_app_leave(void) {
+ if (running) np_jump(leave);
}
-
-bool extapp_isValid(const uint32_t *address)
-{
- return *address == reverse32(0xBADD0BEE);
-}
-
-uint8_t extapp_calculatorModel()
-{
- // To guess the storage size without reading forbidden addresses, we try to
- // get the storage address from the userland header
-
- uint32_t *userlandMagicSlotAN0110 = *(uint32_t **)0x90010000;
- uint32_t *userlandMagicSlotBN0110 = *(uint32_t **)0x90410000;
- uint32_t *userlandMagicSlotAN0120 = *(uint32_t **)0x90020000;
- uint32_t *userlandMagicSlotBN0120 = *(uint32_t **)0x90420000;
-
- // On N0110, RAM start is at 0x20000000 and end is 0x20040000
- // On N0120, RAM start is at 0x20040000
- bool userlandMagicSlotAN0110IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotAN0110;
- bool userlandMagicSlotBN0110IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotBN0110;
- // TODO: Check the end address on N0120 (should be working, but good to check anyway)
- bool userlandMagicSlotAN0120IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotAN0120;
- bool userlandMagicSlotBN0120IsValid = reverse32(0xfeedc0de) == (uint32_t)userlandMagicSlotBN0120;
-
- int N0110Counter = userlandMagicSlotAN0110IsValid + userlandMagicSlotBN0110IsValid;
- int N0120Counter = userlandMagicSlotAN0120IsValid + userlandMagicSlotBN0120IsValid;
-
- // At least one slot indicate N0110 and none N0120
- if ((N0110Counter > 0) && (N0120Counter == 0))
- {
- return 1;
- }
-
- // At least one slot indicate N0120 and none N0110
- if ((N0120Counter > 0) && (N0110Counter == 0))
- {
- return 2;
- }
-
- // In case where both matched, choose the one with most matches (for example,
- // if slot data made a false positive (should not happen unless someone flash
- // the wrong firmware on a calculator))
- if (N0110Counter > N0120Counter)
- {
- return 1;
- }
- if (N0120Counter > N0110Counter)
- {
- return 2;
- }
-
- // The remaining cases is equality (no match or as much matches). In both
- // cases, we cannot know
- return 0;
-}
-
-uint32_t *extapp_userlandAddress()
-{
- // Get the model
- const uint8_t model = extapp_calculatorModel();
-
- if (model == 1)
- {
- return (uint32_t *)0x20000008;
- }
- if (model == 2)
- {
- return (uint32_t *)0x24000008;
- }
-
- // We don't know for other cases, so we suppose (arbitrary) that it's an
- // N0110/N0115 because N0120 is not the latest model and is much less used
- // than N0110/N0115
- return (uint32_t *)0x24000008;
-}
\ No newline at end of file
diff --git a/games/tetris/numworks_utils/src/storage/storage.h b/games/tetris/numworks_utils/src/storage/storage.h
index 149328e4..9131549a 100644
--- a/games/tetris/numworks_utils/src/storage/storage.h
+++ b/games/tetris/numworks_utils/src/storage/storage.h
@@ -1,25 +1,15 @@
-// code from https://framagit.org/Yaya.Cout/numworks-extapp-storage (thanks !)
-// copyright (c) 2021-2022 Numworks
-
#ifndef STORAGE_H
#define STORAGE_H
-#include <stdint.h>
-#include <stddef.h>
#include <stdbool.h>
+#include <stdint.h>
-uint32_t reverse32(uint32_t value);
bool extapp_fileExists(const char *filename);
-char *extapp_fileRead(const char *filename, size_t *len);
-bool extapp_fileWrite(const char *filename, const char *content, size_t len);
+const char *extapp_fileRead(const char *filename, uint32_t *len);
+bool extapp_fileWrite(const char *filename, const char *content, uint32_t len);
bool extapp_fileErase(const char *filename);
-uint32_t extapp_size();
-uint32_t extapp_address();
-uint32_t extapp_used();
-uint32_t *extapp_nextFree();
-bool extapp_isValid(const uint32_t *address);
-// Return the calculator model : 0 is unknown, 1 is N0110/N0115, 2 is N0120
-uint8_t extapp_calculatorModel();
-uint32_t *extapp_userlandAddress();
+
+int np_app_run(void (*game)(void));
+void np_app_leave(void);
#endif
diff --git a/games/tetris/tetris/src/lib.rs b/games/tetris/tetris/src/lib.rs
index 98095042..4c731e5c 100644
--- a/games/tetris/tetris/src/lib.rs
+++ b/games/tetris/tetris/src/lib.rs
@@ -16,11 +16,14 @@ use ui_tetris::draw_tetrimino;
pub use game_tetris::start;
+extern "C" fn play() {
+ game_tetris::start();
+}
+
/// Entry point when Tetris runs inside the NumPlay launcher.
#[no_mangle]
pub extern "C" fn np_tetris_main() -> i32 {
- game_tetris::start();
- 0
+ numworks_utils::app::run(play)
}
pub fn thumbnail(_: Point) {
diff --git a/games/tetris/tetris/src/main.rs b/games/tetris/tetris/src/main.rs
index 7499e9b2..6497941b 100644
--- a/games/tetris/tetris/src/main.rs
+++ b/games/tetris/tetris/src/main.rs
@@ -19,7 +19,11 @@ pub static EADK_APP_API_LEVEL: u32 = 0;
#[link_section = ".rodata.eadk_app_icon"]
pub static EADK_APP_ICON: [u8; 3030] = *include_bytes!("../target/icon.nwi");
-#[no_mangle]
-pub fn main() {
+extern "C" fn play() {
game_tetris::start();
}
+
+#[no_mangle]
+pub fn main() -> i32 {
+ numworks_utils::app::run(play)
+}
diff --git a/launcher/assets/icon.png b/launcher/assets/icon.png
index 83dc929a..429969bd 100644
Binary files a/launcher/assets/icon.png and b/launcher/assets/icon.png differ
diff --git a/launcher/sim/sim.c b/launcher/sim/sim.c
index 925260ea..5aa8fa26 100644
--- a/launcher/sim/sim.c
+++ b/launcher/sim/sim.c
@@ -201,3 +201,19 @@ bool extapp_fileErase(const char *name) {
/* Rust's prebuilt core for the host references an unwinding personality;
* NumPlay's Rust code aborts on panic and never unwinds. */
void rust_eh_personality(void) {}
+
+/* Tetris's app lifetime (storage.c provides it on the calculator). */
+#include <setjmp.h>
+static jmp_buf rust_leave;
+static bool rust_running;
+int np_app_run(void (*game)(void)) {
+ if (!setjmp(rust_leave)) {
+ rust_running = true;
+ game();
+ }
+ rust_running = false;
+ return 0;
+}
+void np_app_leave(void) {
+ if (rust_running) longjmp(rust_leave, 1);
+}
diff --git a/launcher/src/home.c b/launcher/src/home.c
index 0a675d49..28fbf522 100644
--- a/launcher/src/home.c
+++ b/launcher/src/home.c
@@ -38,7 +38,7 @@ static uint32_t item_color(int game, int which) {
}
static const char *item_title(int game) { return game < 0 ? "Settings" : np_games[game].title; }
-static const char *item_tagline(int game) { return game < 0 ? "Uninstall games to free up space" : np_games[game].tagline; }
+static const char *item_tagline(int game) { return game < 0 ? "Uninstall games" : np_games[game].tagline; }
static float absf(float v) { return v < 0 ? -v : v; }
diff --git a/launcher/src/main.c b/launcher/src/main.c
index cea22eb1..2992a107 100644
--- a/launcher/src/main.c
+++ b/launcher/src/main.c
@@ -1,12 +1,34 @@
/* NumPlay: one app for all the games. */
+#include <eadk.h>
#include "np.h"
+#include "sys.h"
#if PLATFORM_DEVICE && !NP_SIMULATOR
const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "NumPlay";
const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+/* Tells the games (games/common/epsilon_app.h) that the launcher takes care
+ * of Home and of the RAM. */
+const uint8_t numplay_launcher[1] = {1};
+
+/* The games read the keyboard through these (the build renames their calls),
+ * so NumPlay knows when a game ended because of Home or On/Off. */
+static bool home_pressed;
+eadk_keyboard_state_t np_keyboard_scan(void) {
+ eadk_keyboard_state_t s = eadk_keyboard_scan();
+ if (s & ((1ull << eadk_key_home) | (1ull << eadk_key_on_off))) home_pressed = true;
+ return s;
+}
+eadk_event_t np_event_get(int32_t *timeout) {
+ eadk_event_t e = eadk_event_get(timeout);
+ if (e == 6 || e == 8) home_pressed = true; /* Home, On/Off */
+ return e;
+}
+#else
+static bool home_pressed;
#endif
int main(void) {
+ np_session_begin();
np_finish_pending_uninstalls();
int selected = np_game_count ? 0 : -1;
bool returning = false;
@@ -18,10 +40,12 @@ int main(void) {
np_settings();
continue;
}
+ home_pressed = false;
np_game_run(r);
+ /* Home in a game goes all the way home, like everywhere on the calculator */
+ if (home_pressed) break;
np_wait_release();
returning = true;
}
- np_wait_release();
- return 0;
+ return np_session_end();
}
diff --git a/launcher/src/storage.c b/launcher/src/storage.c
index 6d89f396..41516e3e 100644
--- a/launcher/src/storage.c
+++ b/launcher/src/storage.c
@@ -1,141 +1,11 @@
-/* Deleting a game's save files from Epsilon's file system.
- *
- * The file system is a FileSystem object in RAM: a magic word, the record
- * buffer, the magic word again, then private members. Records are packed:
- * a 16-bit size, the NUL-terminated name, the content; a zero size ends the
- * list. Removing a record slides the following ones down, exactly like
- * Epsilon's own destroyRecord. Epsilon also caches the position of the last
- * record it looked up (a name checksum and a pointer, stored after the
- * buffer); that cache is located and verified, then cleared, so Epsilon does
- * not use a stale position. If it cannot be verified, only a record that is
- * last in the list (nothing moves) is removed. */
-#include <string.h>
+/* Deleting a game's save files from Epsilon's file system, with the careful
+ * record handling shared with the games (games/common/epsilon_files.h). */
#include "np.h"
-#include "sys.h"
+#include "../../games/common/epsilon_files.h"
-#if PLATFORM_DEVICE && !NP_SIMULATOR
-#define FS_MAGIC 0xEE0BDDBAu
+bool np_storage_delete(const char *name) { return ef_remove(name); }
-typedef struct {
- uint8_t *buf;
- uint32_t size;
- uint32_t *after; /* first word after the footer */
-} fs_t;
-
-static bool open_fs(fs_t *fs) {
- const np_userland_t *h = np_userland();
- if (!h) return false;
- uint32_t ram = h->storage_ram, size = h->storage_size;
- if (ram < 0x24000000 || ram % 4 || size < 1024 || size > 0x10000 || ram + size + 8 > 0x24040000) return false;
- uint32_t *magic = (uint32_t *)ram;
- uint32_t footer;
- memcpy(&footer, (uint8_t *)ram + 4 + size, 4);
- if (*magic != FS_MAGIC || footer != FS_MAGIC) return false;
- fs->buf = (uint8_t *)ram + 4;
- fs->size = size;
- fs->after = (uint32_t *)(ram + 4 + size + 4);
- return true;
-}
-
-static uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
-
-/* End of the records (offset of the terminating zero size), or -1 if corrupt. */
-static int records_end(const fs_t *fs) {
- uint32_t p = 0;
- while (p + 2 <= fs->size) {
- uint16_t n = rd16(fs->buf + p);
- if (!n) return (int)p;
- if (n < 4 || p + n > fs->size) return -1;
- p += n;
- }
- return -1;
-}
-
-static int find(const fs_t *fs, const char *name, uint16_t *size) {
- uint32_t p = 0;
- size_t len = strlen(name) + 1;
- while (p + 2 <= fs->size) {
- uint16_t n = rd16(fs->buf + p);
- if (n < 4 || p + n > fs->size) return -1;
- if (n >= 2 + len && !memcmp(fs->buf + p + 2, name, len)) {
- *size = n;
- return (int)p;
- }
- p += n;
- }
- return -1;
-}
-
-static bool is_record_start(const fs_t *fs, uint32_t off, int end) {
- uint32_t p = 0;
- while ((int)p < end) {
- if (p == off) return true;
- p += rd16(fs->buf + p);
- }
- return false;
-}
-
-/* Epsilon's Record checksum: CRC of the CRCs of the base name and extension. */
-static uint32_t name_crc(const char *full) {
- const char *dot = strchr(full, '.');
- if (!dot) return 0;
- uint32_t parts[2] = {np_crc32_bytes(full, (uint32_t)(dot - full)), np_crc32_bytes(dot + 1, (uint32_t)strlen(dot + 1))};
- return np_crc32_words(parts, 2);
-}
-
-/* Finds Epsilon's (accessible size, cached record checksum, cached pointer)
- * triple after the buffer. Exactly one candidate must pass every check. */
-static uint32_t *find_cache(const fs_t *fs, int end) {
- uint32_t *found = 0;
- for (int i = 1; i < 96; i++) {
- uint32_t *w = fs->after + i;
- uint32_t accessible = w[0], crc = w[1], ptr = w[2];
- if (accessible > fs->size || (int)accessible < end + 2 || accessible < fs->size / 2) continue;
- if (ptr == 0) {
- if (crc != 0) continue;
- } else {
- uint32_t base = (uint32_t)(uintptr_t)fs->buf;
- if (ptr < base || ptr >= base + (uint32_t)end || !is_record_start(fs, ptr - base, end)) continue;
- if (crc == 0 || crc != name_crc((const char *)(uintptr_t)(ptr + 2))) continue;
- }
- if (found) return 0;
- found = w;
- }
- return found;
-}
-
-bool np_storage_delete(const char *name) {
- fs_t fs;
- if (!open_fs(&fs)) return false;
- int end = records_end(&fs);
- if (end < 0) return false;
- uint16_t size;
- int at = find(&fs, name, &size);
- if (at < 0) return true;
- uint32_t *cache = find_cache(&fs, end);
- bool last = at + size == end;
- if (!cache && !last) return false;
- /* slide what follows (and the terminating zero) down */
- memmove(fs.buf + at, fs.buf + at + size, (size_t)(end + 2 - (at + size)));
- memset(fs.buf + end + 2 - size, 0, size);
- if (cache) cache[1] = cache[2] = 0;
- return true;
-}
-
-uint32_t np_storage_record_size(const char *name) {
- fs_t fs;
- uint16_t size;
- if (!open_fs(&fs) || find(&fs, name, &size) < 0) return 0;
- return size;
-}
-
-#else
-bool np_storage_delete(const char *name) {
- (void)name;
- return true;
-}
uint32_t np_storage_record_size(const char *name) {
- (void)name;
- return 0;
+ uint32_t len = 0;
+ return ef_read(name, &len) ? len : 0;
}
-#endif
diff --git a/launcher/src/sys.c b/launcher/src/sys.c
index c090cf72..92447371 100644
--- a/launcher/src/sys.c
+++ b/launcher/src/sys.c
@@ -2,7 +2,6 @@
#if PLATFORM_DEVICE && !NP_SIMULATOR
#define USERLAND_MAGIC 0xDEC0EDFEu
-#define SLOT_MAGIC 0xEFEEDBBAu
/* System calls, numbered as in Epsilon's svcall.h (stable since 2022). The
* kernel returns the result in r0 and may clobber r1-r3. */
@@ -40,11 +39,8 @@ const np_userland_t *np_userland(void) {
static bool done;
if (done) return cached;
done = true;
- const volatile uint32_t *slot = (const volatile uint32_t *)0x24000000;
- if (slot[0] == SLOT_MAGIC && slot[3] == SLOT_MAGIC && valid_header(slot[2])) {
- cached = (const np_userland_t *)slot[2];
- return cached;
- }
+ /* Only external flash is probed: it exists on every model (RAM addresses
+ * differ between models, and reading a missing one faults). */
static const uint32_t candidates[] = {0x90010000, 0x90020000, 0x90410000, 0x90420000};
for (unsigned i = 0; i < 4; i++)
if (valid_header(candidates[i])) {
@@ -57,6 +53,25 @@ const np_userland_t *np_userland(void) {
return cached;
}
+/* The whole session runs with Home held back (Epsilon's circuit breaker),
+ * and ends with the app's RAM cleared: see games/common/epsilon_app.h. */
+extern char _data_section_start_ram[], _heap_end[];
+static bool session_locked;
+
+void np_session_begin(void) {
+ if (!np_userland()) return;
+ SVC2(10, 0, 0);
+ session_locked = true;
+}
+
+int np_session_end(void) {
+ bool unlock = session_locked;
+ for (volatile uint32_t *p = (volatile uint32_t *)(void *)_data_section_start_ram; p < (volatile uint32_t *)(void *)_heap_end; p++)
+ *p = 0;
+ if (unlock) SVC2(13, 0, 0);
+ return 0;
+}
+
uint32_t np_crc32_bytes(const void *data, uint32_t len) { return len ? SVC2(15, data, len) : 0; }
uint32_t np_crc32_words(const uint32_t *data, uint32_t words) { return SVC2(16, data, words); }
int np_battery_level(void) { return (int)(SVC2(4, 0, 0) & 0xFF); }
@@ -89,6 +104,8 @@ bool np_flash_write(void *dst, const void *src, uint32_t len) {
}
void np_interrupts_lock(void) {}
void np_interrupts_unlock(void) {}
+void np_session_begin(void) {}
+int np_session_end(void) { return 0; }
#endif
int np_software_major(void) {
diff --git a/launcher/src/sys.h b/launcher/src/sys.h
index 9ef160ac..044a10a5 100644
--- a/launcher/src/sys.h
+++ b/launcher/src/sys.h
@@ -29,5 +29,9 @@ bool np_flash_erase_sector(int sector);
* breaker), so a critical section runs to its end. */
void np_interrupts_lock(void);
void np_interrupts_unlock(void);
+/* Holds Home back for the whole session; the end clears the app's RAM and
+ * must be followed by `return` from main. */
+void np_session_begin(void);
+int np_session_end(void);
bool np_flash_write(void *dst, const void *src, uint32_t len);
#endif
diff --git a/tests/test_games.py b/tests/test_games.py
new file mode 100644
index 00000000..9b478a35
--- /dev/null
+++ b/tests/test_games.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python3
+"""Plays each game's calculator build in the ARM emulator, twice, and checks
+what used to crash calculators or lose saves:
+
+- the app quits on Home by itself (Epsilon holds Home back while it runs) and
+ hands back its RAM cleared, so Epsilon's memory pools come back safely;
+- no unaligned multi-word access (a fault on the Cortex-M7), no write to flash
+ or to the firmware's RAM outside the file system;
+- the file system stays valid: the game's save is there, the other files are
+ untouched, and a file added after the save does not stop the game from
+ updating it on the second run.
+
+Usage: test_games.py build/apps [--game NAME] [--out DIR]
+"""
+import argparse
+import json
+import os
+import struct
+import sys
+import tempfile
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools"))
+import emu # noqa: E402
+
+K = emu.KEYS
+
+
+def presses(*items):
+ """(time, key[, duration]) -> key ranges."""
+ out = []
+ for it in items:
+ t, k = it[0], it[1]
+ d = it[2] if len(it) > 2 else 90
+ out.append((t, t + d, K[k]))
+ return out
+
+
+def every(t0, t1, step, key, d=80):
+ return [(t, t + d, K[key]) for t in range(t0, t1, step)]
+
+
+# name: (nwa, save record, first run keys, home time, second run keys, home time)
+GAMES = {
+ "crossyroad": ("CrossyRoad.nwa", "crossyroad.sav",
+ every(1500, 9000, 350, "up"), 12000, every(1500, 4000, 400, "up"), 6000),
+ "chess": ("NumChess.nwa", None, presses((1500, "ok"), (2500, "ok")), 4000, [], 2500),
+ "numdash": ("NumDash.nwa", "numdash.nds", presses((2500, "ok"), (4000, "ok"), (5500, "ok")), 9000,
+ presses((2500, "ok")), 5000),
+ # pause, level list, next level, play: that saves the level to start from
+ "numdrive": ("NumDrive.nwa", "drivemad.sav", presses((1500, "ok"), (2000, "back"), (2500, "right"), (3000, "ok")),
+ 5000, presses((1500, "ok"), (2000, "back"), (2500, "left"), (3000, "ok")), 5000),
+ "tetris": ("Tetris.nwa", "tetris.sav", presses((1200, "ok")) + every(2500, 7000, 500, "up"), 8000,
+ presses((1200, "ok"), (2500, "ok")), 5000),
+}
+
+
+# saves already on the calculator, and what each session must leave in them
+SEEDS = {
+ # the first level done and last played
+ "numdrive": b"MD" + bytes([1] + [0] * 24) + b"\0\0\0",
+}
+CHECKS = {
+ "numdrive": (lambda v: v[27] == 1, lambda v: v[27] == 0), # last played level
+}
+
+
+def records(buf):
+ out, p = [], 0
+ while p + 2 <= len(buf):
+ n, = struct.unpack_from("<H", buf, p)
+ if n == 0:
+ return out
+ if n < 4 or p + n > len(buf):
+ raise ValueError(f"corrupt record at {p}")
+ name = buf[p + 2:buf.index(b"\0", p + 2)].decode("latin1")
+ out.append((name, bytes(buf[p + 3 + len(name):p + n])))
+ p += n
+ raise ValueError("no end of the record list")
+
+
+def through_launcher(index, keys, home):
+ """The same session, started from NumPlay's carousel (game `index`)."""
+ lead = [(1200 + 300 * i, 1290 + 300 * i, K["right"]) for i in range(index)]
+ ok = 1500 + 300 * index
+ lead.append((ok, ok + 90, K["ok"]))
+ shift = ok + 800
+ return lead + [(a + shift, b + shift, k) for a, b, k in keys], home + shift
+
+
+def run_once(nwa, storage, keys, home, out, tag):
+ c = emu.Calculator(nwa, storage_file=storage)
+ c.enable_checks(reads=True)
+ c.keys = keys + [(home, home + 400, K["home"])]
+ c.pending_shots = [(home - 100, os.path.join(out, f"{tag}.png"))]
+ c.run(home + 3000)
+ problems = []
+ if not c.exited:
+ problems.append("did not quit on Home")
+ if c.violations:
+ problems += sorted(set(c.violations))[:8]
+ if not c.app_ram_clean():
+ problems.append("RAM not cleared on exit")
+ if c.max_locks != 1 or c.locks != 0:
+ problems.append(f"Home lock not held and released once (max {c.max_locks}, now {c.locks})")
+ changed = c.firmware_ram_changes()
+ if changed:
+ problems.append(f"{len(changed)} words of the firmware's RAM changed, first at {changed[0]:#x}")
+ stack = c.stack_used()
+ if stack > 30 * 1024:
+ problems.append(f"stack use {stack} bytes, close to the 32 KB limit")
+ return c, problems, stack
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("apps")
+ ap.add_argument("--game")
+ ap.add_argument("--out", default="build/test_games")
+ ap.add_argument("--numplay", help="play the games inside this NumPlay.nwa instead")
+ a = ap.parse_args()
+ order = [g["id"] for g in json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "games",
+ "games.json")))]
+ os.makedirs(a.out, exist_ok=True)
+ failed = False
+ for name, (nwa, save, keys1, home1, keys2, home2) in GAMES.items():
+ if a.game and a.game != name:
+ continue
+ path = os.path.join(a.apps, nwa)
+ if a.numplay: # Home in a game quits NumPlay altogether
+ path = a.numplay
+ keys1, home1 = through_launcher(order.index(name), keys1, home1)
+ keys2, home2 = through_launcher(order.index(name), keys2, home2)
+ with tempfile.TemporaryDirectory() as d:
+ storage = os.path.join(d, "storage.bin")
+ # the calculator already has a script
+ pre = [("pi.py", b"\x01print(3.14159)\n")]
+ if name in SEEDS:
+ pre.append((save, SEEDS[name]))
+ buf = bytearray(emu.STORAGE_SIZE)
+ p = 0
+ for rn, content in pre:
+ size = 2 + len(rn) + 1 + len(content)
+ struct.pack_into("<H", buf, p, size)
+ buf[p + 2:p + size] = rn.encode() + b"\0" + content
+ p += size
+ open(storage, "wb").write(buf)
+ c, problems, stack = run_once(path, storage, keys1, home1, a.out, f"{name}_1")
+ recs = dict(records(open(storage, "rb").read()))
+ if recs.get("pi.py") != pre[0][1]:
+ problems.append("pi.py changed")
+ if save and save not in recs:
+ problems.append(f"{save} not written")
+ elif name in CHECKS and not CHECKS[name][0](recs[save]):
+ problems.append(f"{save} not updated")
+ # a script added after the save, then a second session
+ buf = bytearray(open(storage, "rb").read())
+ lst = records(buf)
+ p = sum(2 + len(n) + 1 + len(v) for n, v in lst)
+ late = b"\x01print('later')\n"
+ size = 2 + len("late.py") + 1 + len(late)
+ struct.pack_into("<H", buf, p, size)
+ buf[p + 2:p + size] = b"late.py\0" + late
+ struct.pack_into("<H", buf, p + size, 0)
+ open(storage, "wb").write(buf)
+ c2, problems2, stack2 = run_once(path, storage, keys2, home2, a.out, f"{name}_2")
+ problems += [f"second run: {x}" for x in problems2]
+ try:
+ recs2 = dict(records(open(storage, "rb").read()))
+ if recs2.get("pi.py") != pre[0][1] or recs2.get("late.py") != late:
+ problems.append("second run: other files changed")
+ if save and save not in recs2:
+ problems.append(f"second run: {save} lost")
+ elif name in CHECKS and not CHECKS[name][1](recs2[save]):
+ problems.append(f"second run: {save} not updated")
+ except ValueError as e:
+ problems.append(f"second run: file system corrupt ({e})")
+ status = "ok" if not problems else "FAIL"
+ failed |= bool(problems)
+ print(f"{name:11s} {status} stack {max(stack, stack2)} bytes, files {sorted(recs)}", flush=True)
+ for x in problems:
+ print(" ", x)
+ sys.exit(1 if failed else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_uninstall.py b/tests/test_uninstall.py
index 17f79506..e7bc3ed5 100644
--- a/tests/test_uninstall.py
+++ b/tests/test_uninstall.py
@@ -12,6 +12,7 @@ what happened to the flash and to the calculator's files.
Usage: test_uninstall.py build/NumPlay.nwa [--out DIR]
"""
import argparse
+import json
import os
import struct
import sys
@@ -38,7 +39,9 @@ def main():
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
c = emu.Calculator(a.nwa)
- games = [n[3:-6] for n in c.symbols if n.startswith("np_") and n.endswith("_begin")]
+ manifest = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "games", "games.json")
+ manifest = json.load(open(manifest))
+ games = [g["id"] for g in manifest]
order = sorted(games, key=lambda g: c.symbols[f"np_{g}_begin"])
target = a.game
if target not in order:
@@ -46,10 +49,13 @@ def main():
begin, end = c.symbols[f"np_{target}_begin"], c.symbols[f"np_{target}_end"]
flash_before = bytes(c.uc.mem_read(emu.FLASH, emu.FLASH_SIZE))
- save = {"crossyroad": "crossyroad.sav", "numdrive": "drivemad.sav", "numdash": "numdash.nds",
- "tetris": "tetris.sav", "chess": None}[target]
+ # the game's own files go with it; a script and another game's save stay
+ own = next(g["records"] for g in manifest if g["id"] == target)
+ save = own[0] if own else None
+ other = ("crossyroad.sav", bytes(range(24))) if target == "tetris" else ("tetris.set", struct.pack("<3I", 1, 1, 1234))
records = [("pi.py", b"\x01print(3.14)\n"), (save or "none.sav", bytes(range(40))),
- ("script.py", b"\x01import math\nprint(math.e)\n"), ("tetris.set", struct.pack("<3I", 1, 1, 1234))]
+ ("script.py", b"\x01import math\nprint(math.e)\n"), other]
+ records[3:3] = [(n, bytes(range(12))) for n in own[1:2]]
c.set_records(records, cached="script.py")
# Home: the settings card is last. Settings: the games are listed in order.
@@ -145,19 +151,23 @@ def main():
b, e = c.symbols[f"np_{g}_begin"], c.symbols[f"np_{g}_end"]
if struct.unpack_from("<I", flash, off(b))[0] != 0x3147504E or struct.unpack_from("<I", flash, off(e) - 4)[0] != 0x444E4550:
fail(f"{g} lost its marks")
- if c.locks != 0 or c.max_locks != 1:
+ # the session holds Home back, and the uninstall once more inside it
+ if c.locks != 0 or c.max_locks != 2:
fail(f"Home interrupt lock not balanced (depth {c.locks}, max {c.max_locks})")
+ if not c.app_ram_clean():
+ fail("NumPlay did not clear its RAM when quitting")
erased = sum(1 for op in c.flash_log if op[0] == "erase")
print(f"flash: {target} block {begin:#x}-{end:#x} ({(end - begin) / 1024:.1f} KB) wiped, "
f"{erased} sectors erased, nothing else changed")
# ---- files
names = [n for n, _ in c.records()]
- if save and save in names:
- fail(f"{save} is still there")
+ for name in own:
+ if name in names:
+ fail(f"{name} is still there")
buf = c.storage_bytes()
for name, content in records:
- if name == save:
+ if name in own:
continue
if name not in names:
fail(f"{name} disappeared")
diff --git a/tools/emu.py b/tools/emu.py
index 7ddbd50d..dd662f57 100644
--- a/tools/emu.py
+++ b/tools/emu.py
@@ -25,7 +25,8 @@ import sys
import tempfile
from elftools.elf.elffile import ELFFile
-from unicorn import UC_ARCH_ARM, UC_HOOK_CODE, UC_HOOK_INTR, UC_HOOK_MEM_INVALID, UC_MODE_MCLASS, UC_MODE_THUMB, Uc, UcError
+from unicorn import (UC_ARCH_ARM, UC_HOOK_CODE, UC_HOOK_INTR, UC_HOOK_MEM_INVALID, UC_HOOK_MEM_READ, UC_HOOK_MEM_WRITE,
+ UC_MODE_MCLASS, UC_MODE_THUMB, Uc, UcError)
from unicorn.arm_const import (UC_ARM_REG_LR, UC_ARM_REG_PC, UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2,
UC_ARM_REG_R3, UC_ARM_REG_SP)
@@ -217,6 +218,69 @@ class Calculator:
uc.reg_write(UC_ARM_REG_LR, EXIT_HOOK | 1)
self.pc = self.entry | 1
+ # ------------------------------------------------------------ checks
+ def enable_checks(self, reads=True):
+ """Watch for what would crash or corrupt a real calculator: unaligned
+ multi-word loads (LDRD, LDM, VLDR... fault on the Cortex-M7), writes to
+ flash outside the flash system calls, changes to the firmware's RAM
+ other than its file system, and the deepest stack use.
+ (Unicorn mis-runs some code with write hooks on RAM, so RAM writes are
+ checked by comparing snapshots, and the stack is painted.)"""
+ self.violations = []
+ if reads: # loads from the file system: records sit at any byte offset
+ self.uc.hook_add(UC_HOOK_MEM_READ, self._check, begin=STORAGE, end=STORAGE + STORAGE_SIZE + 8)
+ self.uc.hook_add(UC_HOOK_MEM_WRITE, self._flash_write, begin=FLASH, end=FLASH + FLASH_SIZE - 1)
+ self.uc.mem_write(EXT_RAM_END, b"\xa5" * (STACK_TOP - EXT_RAM_END))
+ self.ram_before = bytes(self.uc.mem_read(SRAM, SRAM_SIZE))
+
+ def _flash_write(self, uc, access, addr, size, value, data):
+ self.violations.append(f"write to flash at {addr:#x} (pc {uc.reg_read(UC_ARM_REG_PC):#x})")
+
+ def stack_used(self):
+ stack = bytes(self.uc.mem_read(EXT_RAM_END, STACK_TOP - EXT_RAM_END))
+ i = 0
+ while i < len(stack) and stack[i] == 0xA5:
+ i += 1
+ return len(stack) - i
+
+ def firmware_ram_changes(self):
+ """Offsets of firmware RAM that changed, outside the file system."""
+ now = bytes(self.uc.mem_read(SRAM, SRAM_SIZE))
+ allowed = [(EXT_RAM_START, STACK_TOP), (STORAGE + 4, STORAGE + 4 + STORAGE_SIZE),
+ (self.fs_private + 4 + 128 + 4, self.fs_private + 4 + 128 + 12)]
+ changed = []
+ for i in range(0, SRAM_SIZE, 4):
+ if now[i:i + 4] != self.ram_before[i:i + 4]:
+ a = SRAM + i
+ if not any(lo <= a < hi for lo, hi in allowed):
+ changed.append(a)
+ return changed
+
+ def _needs_alignment(self, pc):
+ hw1, = struct.unpack("<H", self.uc.mem_read(pc, 2))
+ if hw1 >> 11 in (0x18, 0x19): # 16-bit LDM/STM
+ return "LDM/STM"
+ if hw1 < 0xE800:
+ return None
+ hw2, = struct.unpack("<H", self.uc.mem_read(pc + 2, 2))
+ if hw1 & 0xFE40 == 0xE800:
+ return "LDM/STM"
+ if hw1 & 0xFE40 == 0xE840:
+ return "LDRD/STRD/LDREX"
+ if hw1 & 0xFE00 == 0xEC00 and (hw2 >> 9) & 7 == 5:
+ return "VLDR/VSTR/VLDM/VSTM"
+ return None
+
+ def _check(self, uc, access, addr, size, value, data):
+ if addr & 3:
+ pc = uc.reg_read(UC_ARM_REG_PC)
+ kind = self._needs_alignment(pc)
+ if kind:
+ self.violations.append(f"unaligned {kind} at {addr:#x} (pc {pc:#x})")
+
+ def app_ram_clean(self):
+ return not any(self.uc.mem_read(EXT_RAM_START, EXT_RAM_LEN))
+
# ------------------------------------------------------------ helpers
def reg(self, r):
return self.uc.reg_read(r)
@@ -453,6 +517,7 @@ def main():
ap.add_argument("--flash-start", type=lambda s: int(s, 0), default=EXT_FLASH_START)
ap.add_argument("--nwlink", default="nwlink")
ap.add_argument("--records", action="store_true", help="list storage records at the end")
+ ap.add_argument("--frames", help="save raw RGB565 frames here (for tools/record.py --frames)")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
c = Calculator(a.nwa, a.flash_start, a.storage, a.nwlink)
@@ -462,11 +527,20 @@ def main():
frames = []
g0, g1 = (int(x) for x in a.gif.split("-")) if a.gif else (None, None)
+ count = [0]
+
def grab(calc):
if g0 is not None and g0 <= calc.now_ms <= g1:
frames.append(calc.frame_image())
-
- c.run(a.ms, grab if a.gif else None, 1000 / a.fps if a.gif else None)
+ if a.frames:
+ name = f"{count[0]:06d}_{int(calc.now_ms):06d}.raw"
+ open(os.path.join(a.frames, name), "wb").write(bytes(calc.screen))
+ count[0] += 1
+
+ if a.frames:
+ os.makedirs(a.frames, exist_ok=True)
+ recording = a.gif or a.frames
+ c.run(a.ms, grab if recording else None, 1000 / a.fps if recording else None)
if frames:
frames[0].save(os.path.join(a.out, "anim.gif"), save_all=True, append_images=frames[1:],
duration=int(1000 / a.fps), loop=0)
diff --git a/tools/make_icon.py b/tools/make_icon.py
index 5a8402d3..fdaa64fb 100644
--- a/tools/make_icon.py
+++ b/tools/make_icon.py
@@ -9,7 +9,9 @@ S = 8
def icon(w=55, h=56):
- W, H = w * S, h * S
+ """Drawn for 55x56 and scaled for other sizes."""
+ S = 8 * w / 55
+ W, H = int(w * 8), int(h * 8)
# diagonal gradient
top, bottom = (255, 94, 98), (123, 67, 255)
grad = Image.new("RGB", (W, H))
@@ -24,8 +26,8 @@ def icon(w=55, h=56):
out.paste(grad, (0, 0), mask)
d = ImageDraw.Draw(out)
# soft shadow, then the pad
- cx, cy = W / 2, H / 2 + 2 * S
- pw, ph = 40 * S, 24 * S
+ cx, cy = W / 2, H / 2
+ pw, ph = 42 * S, 26 * S
def pad(dx, dy, fill):
d.rounded_rectangle([cx - pw / 2 + dx, cy - ph / 2 + dy, cx + pw / 2 + dx, cy + ph / 2 + dy], radius=ph / 2,
@@ -42,9 +44,6 @@ def icon(w=55, h=56):
for bx, by, col in ((cx + 8 * S, cy + 2.5 * S, (255, 94, 98, 255)), (cx + 13 * S, cy - 2.5 * S, ink)):
r = 3 * S
d.ellipse([bx - r, by - r, bx + r, by + r], fill=col)
- # a little sparkle above: this is a launcher of many games
- for i, (sx, sy, r) in enumerate(((cx - 12 * S, 12 * S, 2.2 * S), (cx, 9 * S, 3 * S), (cx + 12 * S, 12 * S, 2.2 * S))):
- d.ellipse([sx - r, sy - r, sx + r, sy + r], fill=(255, 255, 255, 230 if i == 1 else 170))
return out.resize((w, h), Image.LANCZOS)
diff --git a/tools/media/social.py b/tools/media/social.py
new file mode 100644
index 00000000..edba9599
--- /dev/null
+++ b/tools/media/social.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python3
+"""Renders docs/media/social.png, the 1280x640 picture shown when the
+repository is shared (upload it in the repository's settings)."""
+import json
+import os
+import sys
+
+from PIL import Image, ImageDraw, ImageFilter, ImageFont
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
+sys.path.insert(0, os.path.join(ROOT, "tools"))
+import fontgen # noqa: E402
+import make_icon # noqa: E402
+
+W, H = 1280, 640
+bg = Image.new("RGB", (W, H))
+px = bg.load()
+a, b = (40, 22, 110), (12, 10, 40)
+for y in range(H):
+ for x in range(W):
+ t = (x * 0.4 + y * 0.6) / (W * 0.4 + H * 0.6)
+ px[x, y] = tuple(int(p + (q - p) * t) for p, q in zip(a, b))
+img = bg.convert("RGBA")
+games = {g["id"]: g for g in json.load(open(os.path.join(ROOT, "games", "games.json")))}
+shots = [("numdash", 1), ("crossyroad", 1), ("numdrive", 0), ("tetris", 1)]
+cw, ch = 290, 218
+for k, (gid, i) in enumerate(shots):
+ x, y = 650 + (k % 2) * (cw + 24), 90 + (k // 2) * (ch + 24)
+ im = Image.open(os.path.join(ROOT, "games", gid, games[gid]["shots"][i])).convert("RGB").resize((cw, ch), Image.LANCZOS)
+ sh = Image.new("RGBA", (cw + 60, ch + 60), (0, 0, 0, 0))
+ ImageDraw.Draw(sh).rounded_rectangle([30, 36, cw + 30, ch + 36], radius=18, fill=(0, 0, 0, 160))
+ img.alpha_composite(sh.filter(ImageFilter.GaussianBlur(12)), (x - 30, y - 30))
+ card = Image.new("RGBA", (cw + 10, ch + 10), (0, 0, 0, 0))
+ ImageDraw.Draw(card).rounded_rectangle([0, 0, cw + 9, ch + 9], radius=18, fill=(255, 255, 255, 255))
+ m = Image.new("L", (cw, ch), 0)
+ ImageDraw.Draw(m).rounded_rectangle([0, 0, cw - 1, ch - 1], radius=13, fill=255)
+ card.paste(im, (5, 5), m)
+ img.alpha_composite(card, (x - 5, y - 5))
+img.alpha_composite(make_icon.icon(150, 153).convert("RGBA"), (70, 100))
+font = fontgen.font_file()
+f1 = ImageFont.truetype(font, 100)
+f1.set_variation_by_axes([900])
+f2 = ImageFont.truetype(font, 36)
+f2.set_variation_by_axes([700])
+d = ImageDraw.Draw(img)
+d.text((64, 282), "NumPlay", font=f1, fill=(255, 255, 255))
+d.multiline_text((72, 410), "Every game for your\nNumWorks calculator,\nin one app.", font=f2, fill=(220, 215, 255),
+ spacing=8)
+img.convert("RGB").save(os.path.join(ROOT, "docs", "media", "social.png"), optimize=True)
diff --git a/tools/record.py b/tools/record.py
index 7236500a..b247160c 100644
--- a/tools/record.py
+++ b/tools/record.py
@@ -13,6 +13,7 @@ Usage:
import argparse
import glob
import os
+import shutil
import subprocess
import tempfile
@@ -30,27 +31,59 @@ def load_frames(d):
return frames
+def global_palette(images, colors=255):
+ """One palette for the whole animation (from pngquant when available), so
+ unchanged pixels stay identical from frame to frame and compress well."""
+ step = max(1, -(-len(images) // 64)) # spread over the whole animation
+ sample = images[::step]
+ w, h = sample[0].size
+ sw, sh = w // 4, h // 4
+ sheet = Image.new("RGB", (sw * 8, sh * ((len(sample) + 7) // 8)))
+ for i, im in enumerate(sample):
+ sheet.paste(im.resize((sw, sh), Image.BOX), ((i % 8) * sw, (i // 8) * sh))
+ q = None
+ if shutil.which("pngquant"):
+ with tempfile.TemporaryDirectory() as d:
+ src, dst = os.path.join(d, "s.png"), os.path.join(d, "q.png")
+ sheet.save(src)
+ subprocess.run(["pngquant", "--nofs", "--force", "--output", dst, str(colors), src], check=True)
+ q = Image.open(dst)
+ q.load()
+ if q is None or q.mode != "P":
+ q = sheet.quantize(colors=colors, method=Image.Quantize.MEDIANCUT)
+ return q
+
+
def save_gif(frames, path, scale, fps):
ims = [im.resize((320 * scale, 240 * scale), Image.NEAREST) if scale != 1 else im for _, im in frames]
+ pal = global_palette(ims)
+ ims = [im.quantize(palette=pal, dither=Image.Dither.NONE) for im in ims]
# keep the timing of the recording
durations = []
for i, (t, _) in enumerate(frames):
nxt = frames[i + 1][0] if i + 1 < len(frames) else t + 1000 // fps
durations.append(max(20, nxt - t))
- tmp = path + ".tmp.gif"
- ims[0].save(tmp, save_all=True, append_images=ims[1:], duration=durations, loop=0, optimize=False, disposal=1)
- try:
- subprocess.run(["gifsicle", "-O3", "--lossy=30", "--colors", "256", tmp, "-o", path], check=True)
- os.remove(tmp)
- except (FileNotFoundError, subprocess.CalledProcessError):
- os.replace(tmp, path)
+ if not shutil.which("gifsicle"):
+ ims[0].save(path, save_all=True, append_images=ims[1:], duration=durations, loop=0)
+ return
+ # gifsicle assembles the frames: it picks a transparent colour that no
+ # frame uses when it stores only what changed
+ with tempfile.TemporaryDirectory() as d:
+ args = ["gifsicle", "-O3", "--loopcount=0"]
+ for i, (im, ms) in enumerate(zip(ims, durations)):
+ f = os.path.join(d, f"{i:05d}.gif")
+ im.save(f)
+ args += ["-d", str(max(2, round(ms / 10))), f]
+ args += ["-o", path]
+ subprocess.run(args, check=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--simulator", default=os.environ.get("EPSILON"))
ap.add_argument("--nwb", default="build/NumPlay.nwb")
- ap.add_argument("--keys", required=True)
+ ap.add_argument("--keys", help="scripted keys for the simulator")
+ ap.add_argument("--frames", help="use raw frames already recorded (tools/emu.py, tools/media) instead")
ap.add_argument("--end", type=int, default=0)
ap.add_argument("--fps", type=int, default=30)
ap.add_argument("--out", required=True)
@@ -60,6 +93,14 @@ def main():
ap.add_argument("--keep", help="also save every frame as PNG in this directory")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
+ if a.frames:
+ frames = load_frames(a.frames)
+ else:
+ frames = record(a)
+ finish(a, frames)
+
+
+def record(a):
with tempfile.TemporaryDirectory() as d:
state = os.path.join(d, "events.nws")
open(state, "wb").write(b"\x04")
@@ -70,7 +111,10 @@ def main():
subprocess.run([a.simulator, "--headless", "--headless-state-file", "--load-state-file", state,
"--take-screenshot", os.path.join(d, "last.png"), "--nwb", os.path.abspath(a.nwb)],
env=env, check=False, timeout=600)
- frames = load_frames(d)
+ return load_frames(d)
+
+
+def finish(a, frames):
if not frames:
raise SystemExit("record: no frames (is the simulator path right?)")
print(f"record: {len(frames)} frames over {frames[-1][0] / 1000:.1f} s")