Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
TI-84 CE: faster screen, OK on 2nd, builds checked for room
Mason363ac7daee51e13
diff --git a/platform/port.mk b/platform/port.mkindex dc1ef1d5..153fb43d 100644--- a/platform/port.mk+++ b/platform/port.mk@@ -31,14 +31,21 @@ CEDEV ?= $(HOME)/Documents/Assets/toolchains/CEdevCE_NAME = $(shell echo '$(PORT_ID)' | tr a-z A-Z | tr -cd 'A-Z0-9' | cut -c1-8)CE_DIR = $(PORT_OUT)/$(PORT_ID)CE_ALL = $(abspath $(PORT_SRC) $(NP_PLATFORM)/ti84ce/np_ce.c $(PORT_COMMON))+# the game's flags with their folders made absolute (the build runs in CE_DIR); PORT_DEPS: files the sources include+# that the game's Makefile makes (levels...)+CE_FLAGS = $(foreach f,$(PORT_FLAGS),$(if $(filter -I%,$(f)),-I$(abspath $(patsubst -I%,%,$(f))),$(f))) $(PORT_CE_FLAGS)+# a shift past an int's 24 bits stops the build; a frame that big on the 4 KB stack is worth a look+CE_WARN = -Wall -Werror=shift-count-overflow -Werror=shift-overflow -Wshift-sign-overflow -Wframe-larger-than=1024port: $(CE_DIR)/bin/$(CE_NAME).8xp-$(CE_DIR)/bin/$(CE_NAME).8xp: $(PORT_SRC) $(wildcard $(NP_PLATFORM)/include/*.h) $(NP_PLATFORM)/ti84ce/np_ce.c+$(CE_DIR)/bin/$(CE_NAME).8xp: $(PORT_SRC) $(PORT_DEPS) $(wildcard $(NP_PLATFORM)/include/*.h) $(NP_PLATFORM)/ti84ce/np_ce.c \+ $(NP_PLATFORM)/ti84ce/check.py@rm -rf $(CE_DIR)/src && mkdir -p $(CE_DIR)/src@n=0; for f in $(CE_ALL); do n=$$((n+1)); echo "#include \"$$f\"" > $(CE_DIR)/src/f$$n.c; done- @printf 'NAME = %s\nDESCRIPTION = "%s"\nCOMPRESSED = YES\nARCHIVED = YES\nCFLAGS = -Wall -Oz -Werror=shift-count-overflow -Wno-unused-command-line-argument %s\ninclude $$(shell cedev-config --makefile)\n' \- '$(CE_NAME)' '$(PORT_NAME)' '-DNP_PORT=1 -DNP_APP_ID="\"$(PORT_ID)\"" -DNP_APP_NAME="\"$(PORT_NAME)\"" -I$(abspath $(NP_PLATFORM)/include) $(PORT_CE_FLAGS)' \+ @printf 'NAME = %s\nDESCRIPTION = "%s"\nCOMPRESSED = YES\nARCHIVED = YES\nCFLAGS = %s -Oz -Wno-unused-command-line-argument %s\ninclude $$(shell cedev-config --makefile)\n' \+ '$(CE_NAME)' '$(PORT_NAME)' '$(CE_WARN)' '-DNP_PORT=1 -DNP_APP_ID="\"$(PORT_ID)\"" -DNP_APP_NAME="\"$(PORT_NAME)\"" -I$(abspath $(NP_PLATFORM)/include) $(CE_FLAGS)' \> $(CE_DIR)/makefile$(Q) PATH="$(CEDEV)/bin:$$PATH" $(MAKE) -C $(CE_DIR) --no-print-directory TARGET=$(CE_NAME).8xp+ $(Q) python3 $(NP_PLATFORM)/ti84ce/check.py $(CE_DIR) || { rm -f $@; exit 1; }@echo "CE $@"else ifeq ($(TARGET),nspire)# Ndless's SDK (NDLESS_SDK: its ndless-sdk folder, with its toolchain built in toolchain/install)diff --git a/platform/ti84ce/README.md b/platform/ti84ce/README.mdindex 93033cf3..de7aada3 100644--- a/platform/ti84ce/README.md+++ b/platform/ti84ce/README.md@@ -1,18 +1,18 @@# NumPlay on the TI-84 Plus CE-The TI-84 Plus CE, TI-84 Plus CE Python and TI-83 Premium CE, with the [CE C toolchain](https://ce-programming.github.io/toolchain/).+The TI-84 Plus CE, TI-84 Plus CE Python and TI-83 Premium CE, with the [CE C toolchain](https://ce-programming.github.io/toolchain/) (v15).```make port TARGET=ti84ce (in a game's folder): build/ti84ce/<game>/bin/<GAME>.8xp```-`CEDEV` points to the toolchain (default `~/Documents/Assets/toolchains/CEdev`).+`CEDEV` points to the toolchain (default `~/Documents/Assets/toolchains/CEdev`). On the calculator the games need the CE C libraries (`clibs.8xg`), and on OS 5.5 or later [arTIfiCE](https://yvantt.github.io/arTIfiCE/) to start them.| Key | NumWorks key || --- | --- || Arrows | Arrows |-| enter | OK |-| 2nd | EXE |+| 2nd | OK |+| enter | EXE || clear | Back || mode, on | Home (save and quit) || del | ⌫ |@@ -21,8 +21,21 @@ make port TARGET=ti84ce (in a game's folder): build/ti84ce/<game>/bin/<GA| math | toolbox || vars | var || x,T,θ,n | x,n,t |+| (−) | ans || 0 to 9, + − × ÷ . , ( ) ^ x² ln log sin cos tan | the same |+2nd is OK because it sits by the arrows, as OK does on a NumWorks, and enter is EXE at the bottom right. An arrow or del held down repeats in the menus.+Saves: the appvar `NP` + the game's id (6 letters), archived when the game ends.-The CE is slow (48 MHz) and has 154 KB of RAM: the classics and the light 2D games run on it.+## Room++A CE program runs from RAM, unpacked: about 150 KB for the program as stored and unpacked, 60 KB for its static data, a stack of 4 KB, and an `int` of 24 bits. Each build prints what the game takes and stops when it's too much (`check.py`). In a game's folder,++```+python3 ../../platform/ti84ce/check.py --ints build/ti84ce/<game>+```++lists what loses bits only with a 24-bit `int`: conversions, shifts, and the casts to `int` to look at.++The CE is slow (48 MHz, and `float` is done in software): the classics and the light 2D games run on it.diff --git a/platform/ti84ce/check.py b/platform/ti84ce/check.pynew file mode 100644index 00000000..1ef1e80c--- /dev/null+++ b/platform/ti84ce/check.py@@ -0,0 +1,183 @@+#!/usr/bin/env python3+"""A game's TI-84 CE build, checked (platform/ti84ce/README.md). Run by `make port TARGET=ti84ce` on its folder:++ python3 platform/ti84ce/check.py build/ti84ce/<game>++prints the .8xp's size, the RAM it takes (the program, its static data) and how deep its stack goes, and fails when+one of them is past the calculator's room. Also, in a game's folder:++ python3 ../../platform/ti84ce/check.py --ints build/ti84ce/<game>++lists what loses bits only with the CE's 24-bit int: the sources compiled for the CE and for a 32-bit calculator,+their implicit conversions compared, then again with the casts to int taken out (each one to look at)."""+import glob+import os+import re+import shlex+import shutil+import subprocess+import sys++STATIC_ROOM = 0xD13FD8 - 0xD052C6 # BSSHEAP_HIGH - BSSHEAP_LOW: static data and malloc's heap+STACK_ROOM = 4096 # 0xD1987E up to 0xD1A87E+RAM_ROOM = 150000 # a calculator's free RAM at best: the program as stored, then unpacked+VAR_ROOM = 65500 # a variable's bytes+++def sections(map_text):+ sec = {}+ for name, size in re.findall(r"^\.(\w+)\s+0x[0-9a-f]+\s+0x([0-9a-f]+)", map_text, re.M):+ sec[name] = int(size, 16)+ return sec+++def stack(asm):+ """The deepest call chain from main: each function's frame (__frameset's size, its return address and ix),+ the arguments it pushes before a call; a call through a pointer may reach any function whose address is+ taken. Functions that call themselves count once (their depth is the game's to bound)."""+ funcs, cur, taken = {}, None, set()+ for line in asm.split("\n"):+ m = re.match(r"^(_[\w.$]+):", line)+ if m:+ cur = m.group(1)+ funcs[cur] = dict(frame=None, calls={}, pushes=0, maxpush=0, indirect=False, n=0, pending=0)+ continue+ if cur is None:+ continue+ f, t = funcs[cur], line.strip()+ if not t or t.startswith(";"):+ continue+ if t.startswith("."):+ if t.startswith((".d24", ".long")):+ taken.update(re.findall(r"(_[A-Za-z]\w*)", t))+ continue+ f["n"] += 1+ m = re.match(r"ld\s+hl,\s*(-?\d+)$", t)+ if f["frame"] is None and f["n"] <= 2 and m:+ f["pending"] = int(m.group(1))+ continue+ if f["frame"] is None:+ f["frame"] = 6 if t == "call\t__frameset0" else 6 - f["pending"] if t == "call\t__frameset" else 3+ if t.startswith("call\t__frameset"):+ continue+ if t.startswith("push"):+ f["pushes"] += 1+ f["maxpush"] = max(f["maxpush"], f["pushes"])+ elif t.startswith("pop"):+ f["pushes"] = max(0, f["pushes"] - 1)+ m = re.match(r"(?:call|jp)\s+(?:[a-z]+,\s*)?(_[\w.$]+)$", t)+ if m and not m.group(1).startswith("_.L"):+ if m.group(1).startswith("__indcall"):+ f["indirect"] = True+ f["calls"][m.group(1)] = max(f["calls"].get(m.group(1), 0), 3 * f["pushes"])+ taken.update(re.findall(r"^(?:ld|push)\s+\w+,\s*(_[A-Za-z]\w*)$", t))+ for f in funcs.values():+ f["frame"] = f["frame"] or 3+ taken &= set(funcs)+ memo, path, loops = {}, [], set()++ def depth(fn):+ if fn in memo:+ return memo[fn]+ if fn in path:+ loops.add(fn)+ return 0, []+ f = funcs.get(fn)+ if f is None: # a routine of the C library+ return 40, [fn]+ path.append(fn)+ calls = dict(f["calls"])+ if f["indirect"]:+ for t in taken:+ calls.setdefault(t, 3 * f["maxpush"])+ best = max(((p + depth(c)[0], depth(c)[1]) for c, p in calls.items()), default=(3 * f["maxpush"], []))+ path.pop()+ memo[fn] = (f["frame"] + best[0], [fn] + best[1])+ return memo[fn]++ if "_main" not in funcs:+ return 0, [], set()+ d, chain = depth("_main")+ return d, chain, {l for l in loops if l != "_main"}+++def check(ce_dir):+ maps, progs = glob.glob(os.path.join(ce_dir, "bin", "*.map")), glob.glob(os.path.join(ce_dir, "bin", "*.8xp"))+ if not maps or not progs:+ sys.exit(f"{ce_dir}: no .8xp built")+ sec = sections(open(maps[0]).read())+ prog = sum(sec.get(k, 0) for k in ("header", "init", "text", "rodata", "init_array", "fini_array", "data"))+ stored, bss = os.path.getsize(progs[0]), sec.get("bss", 0)+ lto = os.path.join(ce_dir, "obj", "lto.s")+ deep, chain, loops = stack(open(lto).read()) if os.path.exists(lto) else (0, [], set())+ name = os.path.basename(progs[0])+ print(f"CE {name}: {stored} bytes; RAM: the program {prog}, its static data {bss} of {STATIC_ROOM}, "+ f"a stack of {deep} of {STACK_ROOM}" + (f" (and more: {', '.join(sorted(l[1:] for l in loops))} call "+ f"themselves)" if loops else ""))+ bad = []+ if stored > VAR_ROOM:+ bad.append(f"{name} is past a variable's {VAR_ROOM} bytes")+ if stored + prog > RAM_ROOM:+ bad.append(f"stored and unpacked, it takes {stored + prog} bytes of the calculator's {RAM_ROOM}")+ if deep > STACK_ROOM - 512:+ bad.append(f"its stack may reach {deep} bytes: " + " > ".join(c.lstrip("_") for c in chain[:12]))+ for b in bad:+ print("CE too big for a TI-84 CE: " + b)+ return not bad+++def ints(ce_dir):+ """Implicit conversions that drop bits on the CE only, then the casts to int to look at."""+ mk = open(os.path.join(ce_dir, "makefile")).read()+ flags = [f for f in shlex.split(re.search(r"^CFLAGS = (.*)$", mk, re.M).group(1)) if f.startswith(("-D", "-I"))]+ srcs = [re.search(r'#include "(.*)"', open(f).read()).group(1) for f in sorted(glob.glob(os.path.join(ce_dir, "src", "*.c")))]+ srcs = [s for s in srcs if "/platform/" not in s and "/launcher/src/font_data.c" not in s]+ cedev = os.environ.get("CEDEV", os.path.expanduser("~/Documents/Assets/toolchains/CEdev"))+ ez80 = [os.path.join(cedev, "bin", "ez80-clang"), "-fsyntax-only", "-nostdinc", "-isystem", cedev + "/include",+ "-D__TICE__=1", "-std=gnu11"]+ gcc = shutil.which("arm-none-eabi-gcc")+ if not gcc:+ sys.exit("--ints needs arm-none-eabi-gcc on PATH (its C library's headers)")+ arm = ["clang", "--target=armv7em-none-eabi", "-fsyntax-only", "-std=gnu11", "-isystem",+ os.path.join(os.path.dirname(gcc), "..", "arm-none-eabi", "include")]+ warn = ["-Wimplicit-int-conversion", "-Wshorten-64-to-32", "-Wshift-sign-overflow", "-Wshift-count-overflow",+ "-Wshift-overflow", "-Wconstant-conversion", "-Wtautological-constant-out-of-range-compare", "-Wformat",+ "-Winteger-overflow", "-Wno-unused", "-ferror-limit=0"]++ def warnings(cmd, path):+ r = subprocess.run(cmd + flags + warn + [path], capture_output=True, text=True)+ return {(os.path.realpath(m[0]), int(m[1]), int(m[2]), m[4]): m[3] for m in+ re.findall(r"^(.*?):(\d+):(\d+): warning: (.*?) \[(-W[\w-]+)", r.stderr, re.M)}++ cast = re.compile(r"\((?:int|unsigned|unsigned int|signed|short|unsigned short)\)")+ for path in srcs:+ lines = open(path).read().split("\n")+ ce, a32 = warnings(ez80, path), warnings(arm, path)+ for (f, line, col, flag), msg in sorted(ce.items()):+ if (f, line, col, flag) not in a32:+ txt = open(f, errors="replace").read().split("\n")[line - 1].strip()+ print(f"{os.path.relpath(f)}:{line}:{col}: {msg} [{flag}]\n {txt[:150]}")+ # the casts: taken out (same columns), the CE's warnings where a 32- or 64-bit value becomes an int+ tmp = path + ".ce-ints.c"+ open(tmp, "w").write(cast.sub(lambda m: " " * len(m.group(0)), "\n".join(lines)))+ try:+ got = warnings(ez80, tmp)+ finally:+ os.remove(tmp)+ for (f, line, col, flag), msg in sorted(got.items()):+ m = re.search(r"precision: '[^']*'(?: \(aka '([^']*)'\))? to '([^']*)'", msg)+ if f.endswith(".ce-ints.c") and m and "long" in (m.group(1) or msg) and m.group(2) in ("int", "unsigned int") \+ and cast.search(lines[line - 1]):+ print(f"{os.path.relpath(path)}:{line}:{col}: a cast to int of a {m.group(1)} (look at its range)\n"+ f" {lines[line - 1].strip()[:150]}")+++if __name__ == "__main__":+ a = sys.argv[1:]+ if a and a[0] == "--ints":+ ints(a[1])+ elif len(a) == 1:+ sys.exit(0 if check(a[0]) else 1)+ else:+ print(__doc__)+ sys.exit(1)diff --git a/platform/ti84ce/np_ce.c b/platform/ti84ce/np_ce.cindex b61ede4c..daa2e192 100644--- a/platform/ti84ce/np_ce.c+++ b/platform/ti84ce/np_ce.c@@ -2,6 +2,9 @@* is the LCD's memory in the software's own 16-bit mode, the keys come from the keypad (platform/ti84ce/README.md),* the files are one appvar per game, archived when the game ends.*+ * A game draws straight into the LCD's memory, a rectangle at a time, as on a NumWorks: nothing is copied but what+ * it sends. Time is the 32768 Hz clock (timer 1).+ ** Build defines: NP_APP_ID (the game's id). The appvar is "NP" and the id's first 6 letters. */#include <eadk.h>#include <fileioc.h>@@ -21,31 +24,53 @@static uint16_t *const lcd = (uint16_t *)lcd_Ram;+/* the part of r on the screen: its width and height (0: none) */+static unsigned clip(eadk_rect_t r, unsigned *h) {+ if (r.x >= LCD_WIDTH || r.y >= LCD_HEIGHT) return *h = 0;+ *h = r.y + r.height > LCD_HEIGHT ? LCD_HEIGHT - r.y : r.height;+ return r.x + r.width > LCD_WIDTH ? LCD_WIDTH - r.x : r.width;+}+void eadk_display_push_rect(eadk_rect_t r, const eadk_color_t *px) {- if (r.x >= LCD_WIDTH || r.y >= LCD_HEIGHT) return;- unsigned w = r.x + r.width > LCD_WIDTH ? LCD_WIDTH - r.x : r.width;- for (unsigned y = 0; y < r.height && r.y + y < LCD_HEIGHT; y++)- memcpy(&lcd[(r.y + y) * LCD_WIDTH + r.x], px + y * r.width, w * 2);+ unsigned h, w = clip(r, &h);+ uint16_t *row = lcd + r.y * LCD_WIDTH + r.x;+ if (w == LCD_WIDTH && r.width == LCD_WIDTH) w *= h, h = 1; /* rows of the screen's width: one copy */+ for (; w && h; h--, row += LCD_WIDTH, px += r.width) memcpy(row, px, w * 2);}void eadk_display_push_rect_uniform(eadk_rect_t r, eadk_color_t c) {- for (unsigned y = r.y; y < (unsigned)r.y + r.height && y < LCD_HEIGHT; y++)- for (unsigned x = r.x; x < (unsigned)r.x + r.width && x < LCD_WIDTH; x++) lcd[y * LCD_WIDTH + x] = c;+ unsigned h, w = clip(r, &h);+ uint16_t *row = lcd + r.y * LCD_WIDTH + r.x;+ if (!w || !h) return;+ if ((c >> 8) == (c & 0xFF)) { /* black, white...: both bytes alike */+ for (; h; h--, row += LCD_WIDTH) memset(row, c & 0xFF, w * 2);+ return;+ }+ for (unsigned i = 0; i < w; i++) row[i] = c; /* the first row, then copies of it */+ for (uint16_t *p = row + LCD_WIDTH; --h; p += LCD_WIDTH) memcpy(p, row, w * 2);}void eadk_display_pull_rect(eadk_rect_t r, eadk_color_t *px) {- for (unsigned y = 0; y < r.height; y++)- for (unsigned x = 0; x < r.width; x++)- px[y * r.width + x] = r.x + x < LCD_WIDTH && r.y + y < LCD_HEIGHT ? lcd[(r.y + y) * LCD_WIDTH + r.x + x] : 0;+ unsigned h, w = clip(r, &h);+ const uint16_t *row = lcd + r.y * LCD_WIDTH + r.x;+ for (unsigned y = 0; y < r.height; y++, px += r.width)+ if (y < h) {+ memcpy(px, row + y * LCD_WIDTH, w * 2);+ memset(px + w, 0, (r.width - w) * 2);+ } else {+ memset(px, 0, r.width * 2);+ }}+/* the LCD shows its memory as it is drawn (as the NumWorks's does): no wait, every frame counts on the CE */bool eadk_display_wait_for_vblank(void) { return true; }-/* the NumWorks keys on the CE keypad: (group, bit) for each */+/* the NumWorks keys on the CE keypad: (group, bit) for each. 2nd is OK, next to the arrows like the NumWorks's,+ * and enter is EXE, at the bottom right like it */#define K(g, b, k) {g, b, k}static const struct {uint8_t group, bit;eadk_key_t key;} KEYS[] = {K(7, kb_Left, eadk_key_left), K(7, kb_Right, eadk_key_right), K(7, kb_Up, eadk_key_up), K(7, kb_Down, eadk_key_down),- K(6, kb_Enter, eadk_key_ok), K(1, kb_2nd, eadk_key_exe), K(6, kb_Clear, eadk_key_back), K(1, kb_Mode, eadk_key_home),+ K(1, kb_2nd, eadk_key_ok), K(6, kb_Enter, eadk_key_exe), K(6, kb_Clear, eadk_key_back), K(1, kb_Mode, eadk_key_home),K(1, kb_Del, eadk_key_backspace), K(2, kb_Alpha, eadk_key_alpha), K(1, kb_Yequ, eadk_key_shift),K(2, kb_Math, eadk_key_toolbox), K(5, kb_Vars, eadk_key_var), K(3, kb_GraphVar, eadk_key_xnt),K(3, kb_0, eadk_key_zero), K(3, kb_1, eadk_key_one), K(4, kb_2, eadk_key_two), K(5, kb_3, eadk_key_three),@@ -55,7 +80,7 @@ static const struct {K(3, kb_Comma, eadk_key_comma), K(4, kb_LParen, eadk_key_left_parenthesis),K(5, kb_RParen, eadk_key_right_parenthesis), K(6, kb_Power, eadk_key_power), K(2, kb_Square, eadk_key_square),K(2, kb_Ln, eadk_key_ln), K(2, kb_Log, eadk_key_log), K(3, kb_Sin, eadk_key_sine), K(4, kb_Cos, eadk_key_cosine),- K(5, kb_Tan, eadk_key_tangent),+ K(5, kb_Tan, eadk_key_tangent), K(5, kb_Chs, eadk_key_ans), /* (ans is 2nd (-) on the CE) */};eadk_keyboard_state_t eadk_keyboard_scan(void) {@@ -63,31 +88,59 @@ eadk_keyboard_state_t eadk_keyboard_scan(void) {eadk_keyboard_state_t s = 0;for (unsigned i = 0; i < sizeof KEYS / sizeof KEYS[0]; i++)if (kb_Data[KEYS[i].group] & KEYS[i].bit) s |= (eadk_keyboard_state_t)1 << KEYS[i].key;- if (kb_On) s |= (eadk_keyboard_state_t)1 << eadk_key_home, kb_ClearOnLatch();+ if (kb_On) s |= (eadk_keyboard_state_t)1 << eadk_key_home | (eadk_keyboard_state_t)1 << eadk_key_on_off, kb_ClearOnLatch();return s;}+/* key presses as events: each key pressed once, in turn; an arrow or ⌫ held repeats, as on the NumWorks */+#define REPEATS ((eadk_keyboard_state_t)0xF | (eadk_keyboard_state_t)1 << eadk_key_backspace)eadk_event_t eadk_event_get(int32_t *timeout) {- static eadk_keyboard_state_t before = ~(eadk_keyboard_state_t)0;- uint64_t until = eadk_timing_millis() + (uint64_t)(timeout && *timeout > 0 ? *timeout : 0);- do {- eadk_keyboard_state_t now = eadk_keyboard_scan(), hit = now & ~before;- before = now;- for (unsigned k = 0; k < 64; k++)- if (hit >> k & 1) return (eadk_event_t)k;- } while (eadk_timing_millis() < until);+ static eadk_keyboard_state_t before = ~(eadk_keyboard_state_t)0, pending;+ static uint64_t repeat_at;+ static int held = -1;+ uint64_t t0 = eadk_timing_millis(), t = t0, until = t0 + (uint64_t)(timeout && *timeout > 0 ? *timeout : 0);+ for (;;) {+ eadk_keyboard_state_t now = eadk_keyboard_scan();+ pending |= now & ~before, before = now;+ if (held >= 0 && !(now >> held & 1)) held = -1;+ int k = -1;+ if (pending) {+ for (k = 0; !(pending >> k & 1); k++) {}+ pending &= pending - 1;+ held = REPEATS >> k & 1 ? k : -1, repeat_at = t + 300;+ } else if (held >= 0 && t >= repeat_at) {+ k = held, repeat_at = t + 70;+ }+ if (k >= 0) { /* what is left of the wait */+ if (timeout && *timeout > 0) *timeout = t - t0 >= (uint64_t)*timeout ? 0 : *timeout - (int32_t)(t - t0);+ return (eadk_event_t)k;+ }+ if (t >= until) break;+ t = eadk_timing_millis();+ }if (timeout) *timeout = 0;return eadk_event_none;}-/* time: the 32768 Hz clock */-static clock_t t0;-uint64_t eadk_timing_millis(void) { return (uint64_t)(clock() - t0) * 1000 / CLOCKS_PER_SEC; }+/* time: timer 1, 32768 ticks a second, counted in milliseconds on 64 bits (its 32 bits go round in 36 hours) */+static uint32_t ticks0, frac;+static uint64_t ms;+uint64_t eadk_timing_millis(void) {+ uint32_t t = (uint32_t)clock(), d = t - ticks0;+ ticks0 = t;+ frac += (d & 0x7FFF) * 1000; /* (thousandths of a tick: less than 32768 of them a millisecond) */+ ms += (uint64_t)(d >> 15) * 1000 + (frac >> 15);+ frac &= 0x7FFF;+ return ms;+}void eadk_timing_msleep(uint32_t ms) {- while (ms > 60000) msleep(60000), ms -= 60000;- msleep((uint16_t)ms);+ for (; ms >= 60000; ms -= 60000) ticksleep(60 * CLOCKS_PER_SEC);+ ticksleep((ms * 4096 + 124) / 125); /* ms * 32768 / 1000, rounded up */+}+void eadk_timing_usleep(uint32_t us) {+ for (; us >= 1000000; us -= 1000000) ticksleep(CLOCKS_PER_SEC);+ ticksleep((us * 4096 + 124999) / 125000); /* us * 32768 / 1000000, rounded up */}-void eadk_timing_usleep(uint32_t us) { eadk_timing_msleep((us + 999) / 1000); }uint32_t eadk_random(void) { return (uint32_t)random() << 16 ^ (uint32_t)random(); }void eadk_backlight_set_brightness(uint8_t b) { lcd_BacklightLevel = (uint8_t)(255 - b); }uint8_t eadk_backlight_brightness(void) { return (uint8_t)(255 - lcd_BacklightLevel); }@@ -130,9 +183,11 @@ uint8_t *np_storage(uint32_t *size) {return storage;}static void keep(bool archive) {+ uint32_t n = storage_end();+ if (n > STORAGE_SIZE - 2) return; /* (a broken list: the last good file stays) */uint8_t h = ti_Open(var_name(), "w");if (!h) return;- ti_Write(storage, 1, storage_end() + 2, h);+ ti_Write(storage, 1, (size_t)n + 2, h);if (archive) ti_SetArchiveStatus(true, h);ti_Close(h);}@@ -141,12 +196,14 @@ void np_storage_changed(void) { keep(false); }bool np_slow(void) { return true; }const char *np_target(void) { return "ti84ce"; }void np_begin(void) {- t0 = clock();+ ticks0 = (uint32_t)clock();srandom(rtc_Time());kb_DisableOnLatch();}int np_end(void) {if (loaded) keep(true);+ /* a key still down (enter on a Quit button) would act on the home screen: let go first, 2 seconds at most */+ for (uint64_t t = eadk_timing_millis(); eadk_keyboard_scan() && eadk_timing_millis() - t < 2000;) {}os_ClrHomeFull();return 0;}