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.

Core Ball: drop the separate build tooling and paperwork

Mason363450f6413471f
diff --git a/.github/workflows/coreball.yml b/.github/workflows/coreball.yml
deleted file mode 100644
index 280ad8c7..00000000
--- a/.github/workflows/coreball.yml
+++ /dev/null
@@ -1,56 +0,0 @@
-name: Core Ball
-
-on:
- pull_request:
- paths:
- - 'games/coreball/**'
- - 'games/common/**'
- - 'tools/emu.py'
- - 'Makefile'
- - '.github/workflows/coreball.yml'
- push:
- branches: [main]
- paths:
- - 'games/coreball/**'
- - 'games/common/**'
- - '.github/workflows/coreball.yml'
- workflow_dispatch:
-
-permissions:
- contents: read
-
-jobs:
- game:
- runs-on: ubuntu-24.04
- steps:
- - uses: actions/checkout@v4
- - name: ARM toolchain
- run: |
- v=15.2.1-1.1
- curl -fsSL "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: |
- npm install -g [email protected]
- pip install pillow numpy pyelftools unicorn==2.1.4
- - name: Build and test Core Ball
- run: |
- make build/apps/CoreBall.nwa NWLINK=nwlink
- make -C games/coreball check test NWLINK=nwlink
- - name: Compare with the pinned original
- run: |
- mkdir -p build/coreball-reference/js
- curl -fsSL "https://raw.githubusercontent.com/Gr4ys0n/Gr4ys0n.github.io/29006b0f11904704c390b457f7055c9fa1e53484/public/assets/games/core-ball/js/index.js" -o build/coreball-reference/js/index.js
- make -C games/coreball fidelity HOST_CC=cc
- - name: ARM profiles, saves and safe exit
- run: python3 games/coreball/tests/test_arm.py --nwlink nwlink
- - uses: actions/upload-artifact@v4
- with:
- name: CoreBall
- path: build/apps/CoreBall.nwa
diff --git a/Makefile b/Makefile
index 30f3155a..64268ea0 100644
--- a/Makefile
+++ b/Makefile
@@ -199,7 +199,6 @@ APP_buckshot = games/buckshot/output/buckshot.nwa:BuckshotRoulette.nwa
APP_portal = games/portal/output/portal.nwa:PortalReturns.nwa
APP_chess = games/chess/output/chess.nwa:NumChess.nwa
APP_tetris = games/tetris/tetris/target/thumbv7em-none-eabihf/release/tetris:Tetris.nwa
-APP_coreball = games/coreball/output/coreball.nwa:CoreBall.nwa
# Tetris on its own, without building every game (tools/build.py --game tetris)
tetris-app: | $(B)
cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
@@ -277,17 +276,6 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_jetpackjoyride))) $(B)/apps/$(word 2,$(subst :, ,$(APP_jetpackjoyride)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
-# Core Ball is published as its own app.
-.PHONY: check-coreball
-apps: $(B)/apps/CoreBall.nwa
-$(B)/apps/CoreBall.nwa: FORCE | $(B)
- $(MAKE) --no-print-directory -C games/coreball build NWLINK="$(NWLINK)"
- mkdir -p $(B)/apps
- cp games/coreball/output/coreball.nwa $@
-check: check-coreball
-check-coreball: $(B)/apps/CoreBall.nwa
- $(NWLINK) nwa-bin $< $(B)/apps/CoreBall.bin --ram-length $(UPSILON_RAM)
-
STD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))
apps: $(STD_APPS)
$(STD_APPS): $(B)/apps/%.nwa: FORCE | $(B)
@@ -330,7 +318,6 @@ emu: $(B)/NumPlay.nwa
clean:
rm -rf $(B)
-$(MAKE) -C games/numdash clean
- -$(MAKE) -C games/coreball clean
-$(MAKE) -C games/crossyroad clean
-$(MAKE) -C games/numdrive clean
-$(MAKE) -C games/balatro clean
diff --git a/README.md b/README.md
index 952739d7..f1555bee 100644
--- a/README.md
+++ b/README.md
@@ -258,8 +258,6 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
## Credits
-- **[Bobydeluxe](https://github.com/Bobydeluxe)** made the **[Core Ball](games/coreball/README.md)** NumWorks adaptation: 60 original levels with an English interface. It installs on its own as **CoreBall.nwa**, available from the releases once included. Based on the supplied Core Ball reference; original code and lettering are credited in the game README. Not affiliated with its original creators.
-
NumPlay is a fan project, made out of love for these games and for the NumWorks calculator. If you enjoy a game here, go play the original and support the people who made it. NumWorks also has a great community of people making games by hand: try [Numcraft](https://github.com/yannis300307/NumcraftRust), [Celeste Classic](https://github.com/BenchatonDev/Celeste-Numworks), [Tatone26's All the Apps](https://github.com/Tatone26/Numworks-games), the apps on [Nwagyu](https://nwagyu.org/guide/) and [yannis300307's list](https://gist.github.com/yannis300307/9123136f90877107ec0d49ba96b303e5).
- **[Tatone26](https://github.com/Tatone26/Numworks-games)**'s **All the Apps** inspired NumPlay's list of classics. Flappy Bird, Pac-Man, Snake, Connect Four, Solitaire and 2048 are written in C for NumPlay and keep its options, with no code copied from it. Tetris is Tatone26's own, which they released into the public domain, adapted for NumPlay.
diff --git a/games/coreball/VALIDATION.md b/games/coreball/VALIDATION.md
deleted file mode 100644
index 5ca95318..00000000
--- a/games/coreball/VALIDATION.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Validation — Core Ball
-
-Validated on 21 October 2026 with GCC 15.2.1 (ARM), GCC 16.2 (host), nwlink 1.0.0 and NumPlay's Unicorn-based ARM emulator. The reference is pinned in `assets/provenance.json`.
-
-| Check | Result |
-| --- | --- |
-| Original campaign | All 60 levels completed by a timing-only solver, 36,964 simulated frames; at most four attempts per level |
-| Actual original JavaScript | 66,000 motion samples; worst angular error 0.00632 degrees |
-| Rotation soak | 4,320,000 frames across the twelve used motion behaviours; bounded finite angles |
-| Save data | Round-trip, null/truncated data rejection, every-byte corruption rejection, final 60/60 progress |
-| Actual ARM app | N0110, N0115, N0120 Epsilon memory profiles and the smaller Upsilon profile pass |
-| Pause | Game state remains byte-for-byte unchanged until resume |
-| Exit | Back/Home/Power handling, held launch keys, execution lock release, clean app RAM and unchanged firmware RAM |
-| Filesystem | Existing files retained; checked save reload; full storage supports continued play and exit |
-| Ending | Last level unlocks 60/60, saves it and replays level 60; no level 61 |
-| Rendering | All 60 level layouts and the dense victory scatter render safely; maximum observed ARM render time 7 ms |
-| Release packing | Installed release/debug bytes are identical at the 107,674-byte RAM budget |
-
-Text is now rasterized at its real 13/22/32-pixel sizes with four-bit antialias coverage. Menus, help, counters and the antialiased title/GO masks were inspected at the native 320 × 240 size. No heading is enlarged from a small bitmap. Physics and the existing save format are unchanged.
-
-Release: **35,692 bytes**; installed image: **30,653 bytes**; static app RAM (`.data` + `.bss`): **5,557 bytes**; deepest measured stack: **388 bytes**. No heap is used. The icon is kept in flash and is not counted as static RAM.
-
-SHA-256: `43c1b6d9be3c1d554193d9465cb5c1faa60406498092830b17cb7b371ab359f4`.
-
-Machine-readable results are retained in [docs/validation.json](docs/validation.json). Screenshots in `docs/` come from the tested host renderer or actual ARM app. ARM timings are emulator measurements, not hardware benchmarks; physical LCD transfer and firmware timing can differ. N0115 testing uses its memory budget with the emulator's compatible N0110 processor profile. Hardware playtesting remains the final check for perceived input and display smoothness.
-
-The published artifact is built against the upstream common safety helpers at `979c19e828fee928d2d9b2843f8a2f6f2fea500e`.
diff --git a/games/coreball/build.py b/games/coreball/build.py
deleted file mode 100644
index a41f93a2..00000000
--- a/games/coreball/build.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/env python3
-"""Build a standalone Core Ball .nwa, without changing the NumPlay launcher.
-
-python build.py --arm-bin /path/to/arm/bin --nwlink /path/to/nwlink
-NWLINK may also name the nwlink JavaScript entry point (run with Node).
-"""
-import argparse
-import hashlib
-import struct
-import json
-import os
-from pathlib import Path
-import re
-import shlex
-import shutil
-import subprocess
-import sys
-
-ROOT = Path(__file__).resolve().parent
-REPO = ROOT.parents[1]
-OUT = ROOT/'output'
-
-def run(args):
- args = [str(x) for x in args]
- subprocess.run(args, cwd=ROOT, check=True)
-
-def main():
- ap = argparse.ArgumentParser(description=__doc__)
- ap.add_argument('--arm-bin', default=os.environ.get('ARM_BIN',''))
- ap.add_argument('--nwlink', default=os.environ.get('NWLINK','nwlink'))
- a = ap.parse_args()
- OUT.mkdir(exist_ok=True)
- arm = lambda name: str(Path(a.arm_bin)/('arm-none-eabi-'+name)) if a.arm_bin else 'arm-none-eabi-'+name
- if Path(a.nwlink).is_file():
- nw = [a.nwlink] if a.nwlink.endswith(('.exe','.cmd')) else ['node',a.nwlink]
- else:
- nw = ([v.replace('"','') for v in re.findall(r'(?:[^\s"]|"[^"]*")+',a.nwlink)]
- if os.name=='nt' else shlex.split(a.nwlink))
- flags = subprocess.check_output(nw+['eadk-cflags-device'],cwd=ROOT,text=True).strip()
- # nwlink quotes the include directory. Preserve backslashes inside Windows paths.
- target = ([v.replace('"','') for v in re.findall(r'(?:[^\s"]|"[^"]*")+',flags)]
- if os.name=='nt' else shlex.split(flags))
- opts = ['-std=c11',*target,'-Os','-Wall','-Wextra','-Werror','-ffunction-sections',
- '-fdata-sections','-fstack-usage','-fno-tree-loop-distribute-patterns',
- '-flto','-fno-fat-lto-objects','-fvisibility=internal']
- run([sys.executable,'tools/assets.py'])
- objects = []
- for name in ('main','game','save','render','assets'):
- obj = OUT/(name+'.o')
- run([arm('gcc'),*opts,'-c','src/'+name+'.c','-o',obj]);objects.append(obj)
- packer = ROOT/'tools/compact_nwa.py'
- run([*nw,'png-icon-o','src/icon.png',OUT/'icon.o'])
- run([sys.executable,packer,'icon',OUT/'icon.o',OUT/'icon-compact.o','--objcopy',arm('objcopy')])
- run([arm('gcc'),*opts,'-nostartfiles','--specs=nano.specs',
- '-Wl,--relocatable,--gc-sections,-e,main','-flinker-output=nolto-rel',
- '-Wl,-u,eadk_app_name,-u,eadk_app_icon,-u,eadk_api_level',
- *objects,OUT/'icon-compact.o','-lm','-o',OUT/'standalone.o'])
- run([sys.executable,packer,'app',OUT/'standalone.o',OUT/'coreball-debug.nwa','--ld',arm('ld')])
- run([sys.executable,packer,'release',OUT/'coreball-debug.nwa',OUT/'coreball.nwa','--objcopy',arm('objcopy')])
- for name in ('coreball','coreball-debug'):
- run([*nw,'nwa-bin',OUT/(name+'.nwa'),OUT/(name+'.bin'),'--ram-length','107674'])
- installed = (OUT/'coreball.bin').read_bytes()
- assert installed == (OUT/'coreball-debug.bin').read_bytes(), 'Release changes installed bytes'
- apps = REPO/'build/apps';apps.mkdir(parents=True,exist_ok=True)
- shutil.copyfile(OUT/'coreball.nwa',apps/'CoreBall.nwa')
- elf=(OUT/('coreball-debug.nwa')).read_bytes()
- shoff=struct.unpack_from('<I',elf,32)[0];shsize,shcount=struct.unpack_from('<HH',elf,46)
- names_index=struct.unpack_from('<H',elf,50)[0]
- names_header=struct.unpack_from('<10I',elf,shoff+names_index*shsize)
- names=elf[names_header[4]:names_header[4]+names_header[5]]
- static_ram=0
- for i in range(shcount):
- header=struct.unpack_from('<10I',elf,shoff+i*shsize)
- name=names[header[0]:].split(b'\0',1)[0]
- if name in (b'.data',b'.bss'):static_ram+=header[5]
- report = dict(static_ram_bytes=static_ram, sha256=hashlib.sha256((OUT/'coreball.nwa').read_bytes()).hexdigest(), nwa_bytes=(OUT/'coreball.nwa').stat().st_size, installed_bytes=len(installed),
- release_installed_matches_debug=True, artifact=str(apps/'CoreBall.nwa'))
- (OUT/'build-report.json').write_text(json.dumps(report,indent=2)+'\n')
- print(json.dumps(report,indent=2))
-
-if __name__=='__main__':
- main()
diff --git a/games/coreball/tests/test_arm.py b/games/coreball/tests/test_arm.py
deleted file mode 100644
index a29c0cf5..00000000
--- a/games/coreball/tests/test_arm.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/env python3
-"""Actual ARM .nwa tests: three calculator profiles, physics, save/reload and safe exit.
-Requires the repository emulator's dependencies (Unicorn, pyelftools, Pillow).
-"""
-import argparse
-import io
-import json
-import os
-from pathlib import Path
-import re
-import shlex
-import struct
-import tempfile
-import types
-
-ROOT = Path(__file__).resolve().parents[1]
-REPO = ROOT.parents[1]
-emu_path = REPO/'tools/emu.py'
-emu = types.ModuleType('arcade_emu');emu.__file__=str(emu_path);emu.io=io
-source = emu_path.read_text().replace('ELFFile(open(elf, "rb"))','ELFFile(io.BytesIO(open(elf, "rb").read()))')
-source = source.replace('cmd = [nwlink, "nwa-elf",','cmd = nwlink + ["nwa-elf",')
-source = source.replace('chunk = CPU_HZ // 1000','chunk = CPU_HZ // 10000')
-source = source.replace('self.now_ms += 1\n','self.now_ms += 0.1\n')
-source = source.replace(' next_frame = self.now_ms if frame_ms else None',
- ' self.checkpoint = until_ms\n next_frame = self.now_ms if frame_ms else None')
-source = source.replace(' self.slept_ms += r0\n',
- ' self.slept_ms += r0\n if self.now_ms >= self.checkpoint: uc.emu_stop()\n')
-exec(compile(source,str(emu_path),'exec'),emu.__dict__)
-
-def presses(*items):
- return [(t,t+d,emu.KEYS[k]) for t,k,d in items]
-
-def storage(path,items):
- data=bytearray(emu.STORAGE_SIZE);offset=0
- for name,value in items:
- record=name.encode()+b'\0'+value;size=2+len(record)
- struct.pack_into('<H',data,offset,size);data[offset+2:offset+size]=record;offset+=size
- assert offset+2<=len(data)
- path.write_bytes(data)
-
-def records(data):
- result={};offset=0
- while offset+2<=len(data):
- n=struct.unpack_from('<H',data,offset)[0]
- if not n:break
- assert n>=3 and offset+n<=len(data)
- name,value=data[offset+2:offset+n].split(b'\0',1);result[name.decode()]=value;offset+=n
- return result
-
-def check_exit(c,upsilon=False):
- assert c.exited,'App did not exit'
- assert not c.violations,sorted(set(c.violations))
- assert not c.firmware_ram_changes(),'Firmware RAM changed'
- assert c.app_ram_clean(),'App RAM not cleared'
- assert c.locks==0 and c.max_locks==(0 if upsilon else 1)
- assert c.stack_used()<4096,c.stack_used()
-
-def uint(c,name):
- return struct.unpack('<I',bytes(c.uc.mem_read(c.symbols[name],4)))[0]
-
-def main():
- ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--nwlink',default='nwlink');a=ap.parse_args()
- nw=['node',a.nwlink] if Path(a.nwlink).is_file() and not a.nwlink.endswith(('.exe','.cmd')) else shlex.split(a.nwlink)
- slug=ROOT.name;dune=slug=='dune';out=ROOT/'output/arm';out.mkdir(parents=True,exist_ok=True);tempfile.tempdir=str(out)
- host=json.loads((ROOT/'output/host-report.json').read_text());size=host['game_bytes'];stats_size=host['stats_bytes']
- nwa=str(ROOT/f'output/{slug}-debug.nwa');report=[];sentinel=b'print(42)\n';save_size=40 if dune else 24
- profiles=[('n0120','n0120','epsilon',153676),('n0110','n0110','epsilon',148928),('n0115','n0110','epsilon',133652),('upsilon','n0110','upsilon',107674)]
- for profile,model,system,ram in profiles:
- emu.configure(model,system,ram);st=out/(profile+'.bin');storage(st,[('keep.py',sentinel)])
- c=emu.Calculator(nwa,storage_file=str(st),nwlink=nw);c.enable_checks()
- c.keys=presses((300,'ok',80),(500,'ok',180),(850,'back',80),(1750,'back',80),(2400,'home',180))
- c.run(250);c.save_png(str(out/(profile+'-title.png')))
- c.run(1200);assert uint(c,'current_view')==2,('Pause menu did not open',uint(c,'current_view'))
- c.save_png(str(out/(profile+'-pause.png')));before=bytes(c.uc.mem_read(c.symbols['game'],size));c.run(1600)
- assert bytes(c.uc.mem_read(c.symbols['game'],size))==before,'Pause advanced physics'
- c.run(2100);c.save_png(str(out/(profile+'-play.png')))
- frames=uint(c,'perf_frames');slowest=uint(c,'perf_max');slow=uint(c,'perf_slow')
- c.run(3000);check_exit(c,system=='upsilon');r=records(st.read_bytes())
- assert r['keep.py']==sentinel and len(r[slug+'.sav'])==save_size
- expected=r[slug+'.sav'][4:4+(26 if dune else 16)]
- d=emu.Calculator(nwa,storage_file=str(st),nwlink=nw);d.enable_checks();d.keys=presses((400,'onoff',150));d.run(250)
- assert bytes(d.uc.mem_read(d.symbols['stats'],len(expected)))==expected,'Saved progress was not restored'
- d.run(900);check_exit(d,system=='upsilon');assert records(st.read_bytes())['keep.py']==sentinel
- report.append(dict(profile=profile,pause_save_reload_exit='pass',stack_bytes=max(c.stack_used(),d.stack_used()),frames=frames,slowest_draw_ms=slowest,frames_over_33ms=slow));print(profile,report[-1],flush=True)
- emu.configure();c=emu.Calculator(nwa,nwlink=nw);c.enable_checks();c.keys=presses((200,'ok',60));c.run(400)
- for i in range(26 if dune else 60):
- fixture=(ROOT/('output/stress.bin' if dune else f'output/fixture{i}.bin')).read_bytes();assert len(fixture)==size
- c.uc.mem_write(c.symbols['game'],fixture)
- if dune:c.uc.mem_write(c.symbols['stats'],struct.pack('<IIIIIIBBxx',100,50000,(1<<26)-1,127,1,1234,i,i%7))
- c.run(c.now_ms+75);assert not c.violations,sorted(set(c.violations))
- if i in (0,3,6,12,25,49,59):c.save_png(str(out/f'scene{i}.png'))
- if not dune:
- c.uc.mem_write(c.symbols['game'],(ROOT/'output/stress.bin').read_bytes());c.run(c.now_ms+180);assert not c.violations
- report.append(dict(scenes='26 balls and all 7 landscapes' if dune else '60 original levels',slowest_draw_ms=uint(c,'perf_max'),stack_bytes=c.stack_used()))
- c.keys=presses((c.now_ms+100,'home',180));c.run(c.now_ms+700);check_exit(c)
- # Last level completes at 60/60 and replays level 60 rather than creating 61.
- c=emu.Calculator(nwa,nwlink=nw);c.enable_checks();c.keys=presses((200,'ok',60));c.run(400)
- fixture=bytearray((ROOT/'output/fixture59.bin').read_bytes());fixture[host['remaining_offset']]=0
- c.uc.mem_write(c.symbols['game'],bytes(fixture));c.keys=[];c.run(c.now_ms+1400)
- assert uint(c,'current_view')==3 and struct.unpack('<II',bytes(c.uc.mem_read(c.symbols['stats'],8)))==(59,60)
- c.save_png(str(out/'complete.png'));now=c.now_ms;c.keys=presses((now+100,'ok',80),(now+500,'home',180));c.run(now+350)
- assert bytes(c.uc.mem_read(c.symbols['game']+host['level_offset'],1))==bytes([59]);c.run(now+1000);check_exit(c)
- report.append(dict(ending='60/60 saved, last level replayed without level 61'))
- st=out/'full.bin';payload=b'x'*(emu.STORAGE_SIZE-2-2-len('keep.py')-1);storage(st,[('keep.py',payload)])
- c=emu.Calculator(nwa,storage_file=str(st),nwlink=nw);c.enable_checks();c.keys=presses((400,'home',180),(1100,'1',80),(1600,'home',100),(2200,'back',80))
- c.run(900);assert not c.exited and uint(c,'current_view')==6;c.save_png(str(out/'storage-full.png'));c.run(1400);assert not c.exited;c.run(2800);check_exit(c)
- assert records(st.read_bytes())=={'keep.py':payload};report.append(dict(full_storage='continue and exit preserve other files'))
- c=emu.Calculator(nwa,nwlink=nw);c.enable_checks();c.keys=presses((0,'ok',600),(850,'home',180));c.run(700);assert uint(c,'current_view')==0;c.run(1500);check_exit(c)
- (out/'report.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
-if __name__=='__main__':main()
diff --git a/games/coreball/tools/compact_nwa.py b/games/coreball/tools/compact_nwa.py
deleted file mode 100644
index f320bb54..00000000
--- a/games/coreball/tools/compact_nwa.py
+++ /dev/null
@@ -1,228 +0,0 @@
-#!/usr/bin/env python3
-"""Lossless standalone NWA packing. Python standard library + ARM binutils.
-
-Keep the standard ELF/NWI formats: no runtime decoder, extra RAM, or archive.
-"""
-import argparse
-from bisect import bisect_left, insort
-import json
-from pathlib import Path
-import subprocess
-import tempfile
-
-ICON_BYTES = 55 * 56 * 2
-
-
-def decode_lz4(data, expected_size):
- """Decode a raw LZ4 block, with an exact output bound for launcher icons."""
- out = bytearray()
- pos = 0
-
- def length(value):
- nonlocal pos
- if value == 15:
- while True:
- if pos >= len(data):
- raise ValueError('Truncated LZ4 length')
- extra = data[pos]
- pos += 1
- value += extra
- if extra != 255:
- break
- return value
-
- while pos < len(data):
- token = data[pos]
- pos += 1
- size = length(token >> 4)
- if pos + size > len(data) or len(out) + size > expected_size:
- raise ValueError('Invalid LZ4 literal run')
- out += data[pos:pos + size]
- pos += size
- if pos == len(data):
- break
- if pos + 2 > len(data):
- raise ValueError('Truncated LZ4 offset')
- distance = data[pos] | data[pos + 1] << 8
- pos += 2
- size = length(token & 15) + 4
- if not distance or distance > len(out) or len(out) + size > expected_size:
- raise ValueError('Invalid LZ4 match')
- for _ in range(size):
- out.append(out[-distance])
- if len(out) != expected_size:
- raise ValueError('Unexpected decoded icon size')
- return bytes(out)
-
-
-def _extension_cost(value, threshold):
- return 0 if value < threshold else 1 + (value - threshold) // 255
-
-
-def compress_lz4(data):
- """Find a minimum-size raw LZ4 parse for a small (<= 65535 byte) image.
-
- A suffix array finds the longest legal previous match. Dynamic programming
- chooses literal/match lengths, including extension-byte costs. The final
- five bytes are literals; the last match starts at least twelve bytes from
- the end, as required by standard LZ4 block decoders.
- """
- n = len(data)
- if n > 65535:
- raise ValueError('Only small build-time assets are supported')
- if not n:
- return b'\0'
- suffixes = sorted(range(n), key=lambda i: data[i:])
- rank = [0] * n
- for r, pos in enumerate(suffixes):
- rank[pos] = r
- seen = []
- matches = [(0, 0)] * n
- for i in range(n - 11):
- r = rank[i]
- at = bisect_left(seen, r)
- best, distance = 0, 0
- # Among earlier suffixes, a lexicographic neighbour has the longest
- # common prefix. Overlapping matches are legal in LZ4.
- for q in seen[max(0, at - 1):at + 1]:
- j = suffixes[q]
- lo, hi = 0, n - i - 5
- while lo < hi:
- mid = (lo + hi + 1) // 2
- if data[i:i + mid] == data[j:j + mid]:
- lo = mid
- else:
- hi = mid - 1
- if lo > best:
- best, distance = lo, i - j
- matches[i] = best, distance
- insort(seen, r)
-
- dp = [0] * (n + 1)
- plan = [None] * n
- match_cost = [0] * n
- match_length = [0] * n
- starts = []
- for i in range(n - 1, -1, -1):
- best = n - i + 1 + _extension_cost(n - i, 15)
- longest, _ = matches[i]
- if longest >= 4:
- cost, size = min((2 + _extension_cost(size, 19) + dp[i + size], size)
- for size in range(4, longest + 1))
- match_cost[i], match_length[i] = cost, size
- starts.append(i)
- for j in reversed(starts):
- literal = j - i
- if literal + 3 >= best:
- break
- cost = 1 + literal + _extension_cost(literal, 15) + match_cost[j]
- if cost < best:
- best = cost
- plan[i] = j, match_length[j], matches[j][1]
- dp[i] = best
-
- out = bytearray()
-
- def emit_length(value):
- while value >= 255:
- out.append(255)
- value -= 255
- out.append(value)
-
- anchor = 0
- while anchor < n:
- entry = plan[anchor]
- if entry is None:
- literal = n - anchor
- out.append(min(literal, 15) << 4)
- if literal >= 15:
- emit_length(literal - 15)
- out += data[anchor:]
- break
- j, size, distance = entry
- literal = j - anchor
- out.append(min(literal, 15) << 4 | min(size - 4, 15))
- if literal >= 15:
- emit_length(literal - 15)
- out += data[anchor:j]
- out += bytes((distance & 255, distance >> 8))
- if size >= 19:
- emit_length(size - 19)
- anchor = j + size
- if len(out) != dp[0] or decode_lz4(out, n) != data:
- raise ValueError('Lossless compression verification failed')
- return bytes(out)
-
-
-def compact_icon(source, output, objcopy):
- output.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.TemporaryDirectory(dir=output.parent) as folder:
- folder = Path(folder)
- original, packed, obj = folder/'original.nwi', folder/'packed.nwi', folder/'icon.o'
- section = '.rodata.eadk_app_icon'
- subprocess.run([objcopy, '--dump-section=' + section + '=' + str(original),
- str(source), str(obj)], check=True)
- before = original.read_bytes()
- pixels = decode_lz4(before, ICON_BYTES)
- after = compress_lz4(pixels)
- if len(after) > len(before):
- after = before
- packed.write_bytes(after)
- subprocess.run([objcopy, '--update-section=' + section + '=' + str(packed),
- str(obj), str(output)], check=True)
- # Verify the bytes actually stored in the resulting ELF, too.
- subprocess.run([objcopy, '--dump-section=' + section + '=' + str(packed),
- str(output), str(folder/'verify.o')], check=True)
- if decode_lz4(packed.read_bytes(), ICON_BYTES) != pixels:
- raise ValueError('Packed icon pixels changed')
- return dict(source_icon_bytes=len(before), icon_bytes=len(after), decoded_icon_bytes=ICON_BYTES)
-
-
-def compact_app(source, output, linker):
- output.parent.mkdir(parents=True, exist_ok=True)
- script = Path(__file__).with_name('standalone.ld')
- with tempfile.TemporaryDirectory(dir=output.parent) as folder:
- packed = Path(folder)/'packed.nwa'
- subprocess.run([linker, '--relocatable', '--script', str(script), str(source),
- '-o', str(packed)], check=True)
- output.write_bytes(packed.read_bytes())
-
-
-def compact_release(source, output, objcopy):
- """Remove unused ARM mapping symbols from the transport ELF only.
-
- GNU objcopy preserves $t/$d symbols specially even when unused. Rename
- them in a temporary release copy, then let objcopy decide which symbols
- relocations still need. Keep the debug ELF intact for ARM disassembly.
- Python builders compare release/debug bytes on all supported profiles;
- Make's check target compares them on the smallest RAM profile.
- """
- output.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.TemporaryDirectory(dir=output.parent) as folder:
- folder = Path(folder)
- stripped, renamed = folder/'stripped.nwa', folder/'renamed.nwa'
- subprocess.run([objcopy, '--strip-unneeded', str(source), str(stripped)], check=True)
- subprocess.run([objcopy, '--redefine-sym=$t=unused_thumb_marker',
- '--redefine-sym=$d=unused_data_marker', str(stripped),
- str(renamed)], check=True)
- subprocess.run([objcopy, '--strip-unneeded', str(renamed), str(output)], check=True)
-
-
-def main():
- ap = argparse.ArgumentParser(description=__doc__)
- ap.add_argument('kind', choices=('icon', 'app', 'release'))
- ap.add_argument('source', type=Path)
- ap.add_argument('output', type=Path)
- ap.add_argument('--objcopy', default='arm-none-eabi-objcopy')
- ap.add_argument('--ld', default='arm-none-eabi-ld')
- args = ap.parse_args()
- if args.kind == 'icon':
- print(json.dumps(compact_icon(args.source, args.output, args.objcopy)))
- elif args.kind == 'release':
- compact_release(args.source, args.output, args.objcopy)
- else:
- compact_app(args.source, args.output, args.ld)
-
-
-if __name__ == '__main__':
- main()
diff --git a/tools/release.py b/tools/release.py
index ffa4b289..0eb318d1 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -23,7 +23,6 @@ REPO = "https://github.com/Mason363/NumPlay"
EXTRAS = set()
# games too big to fit next to NumPlay on the calculator: only on their own, in a section of their own
ALONE = {
- "coreball": ("Core Ball", "60 original levels with an English interface, adapted by Bobydeluxe; installed separately"),
"celeste": ("Celeste", "the whole climb up Celeste Mountain"),
"hollowknight": ("Hollow Knight", "from King's Pass to Hornet in Greenpath"),
"undertale": ("Undertale", "the whole Underground, to the barrier and the neutral ending"),