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.

Doom: vanilla's screen melt, its random numbers and tics as in Chocolate Doom

Mason36384e0c84efaa7
diff --git a/games/doom/src/doom/d_main.c b/games/doom/src/doom/d_main.c
index 7b354e2e..fa831c23 100644
--- a/games/doom/src/doom/d_main.c
+++ b/games/doom/src/doom/d_main.c
@@ -468,6 +468,28 @@ boolean D_GrabMouseCallback(void)
//
void D_RunFrame()
{
+#if NUMWORKS
+ // vanilla's wipe: the melt, a tic or more at a time (nw/nw_back.inc)
+ int nowtime;
+ int tics;
+ static int wipestart;
+ static boolean wipe;
+ extern int nw_melt(int tics);
+
+ if (wipe)
+ {
+ do
+ {
+ nowtime = I_GetTime ();
+ tics = nowtime - wipestart;
+ I_Sleep(1);
+ } while (tics <= 0);
+
+ wipestart = nowtime;
+ wipe = !nw_melt(tics);
+ return;
+ }
+#endif
#if !DOOM_TINY
int nowtime;
int tics;
@@ -514,6 +536,9 @@ void D_RunFrame()
// normal update
I_FinishUpdate (); // page flip or blit buffer
}
+#elif NUMWORKS
+ if ((wipe = D_Display ()))
+ wipestart = I_GetTime () - 1;
#else
do {
D_Display();
diff --git a/games/doom/src/doom/g_game.c b/games/doom/src/doom/g_game.c
index c29d7ea5..1aef361f 100644
--- a/games/doom/src/doom/g_game.c
+++ b/games/doom/src/doom/g_game.c
@@ -980,7 +980,7 @@ void G_Ticker (void)
// do things to change the game state
while (gameaction != ga_nothing)
{
-#if DOOM_TINY
+#if DOOM_TINY && !NUMWORKS
if (gameaction == ga_loadlevel || gameaction == ga_newgame || gameaction == ga_completed || gameaction == ga_worlddone) {
// we prefer (real doom seems to, chocolate doesn't, but i think it looks better without the menu wiping at least)
// to remove menu/status before wipe, so insert an extra frame so it can be drawn as an (non framebuffer) overlay instead
@@ -1158,7 +1158,7 @@ void G_Ticker (void)
{
case GS_LEVEL:
P_Ticker ();
-#if DOOM_TINY
+#if DOOM_TINY && !NUMWORKS
if (!pre_wipe_state)
#endif
ST_Ticker ();
diff --git a/games/doom/src/doom/r_things.c b/games/doom/src/doom/r_things.c
index 7a062427..0fc39fa6 100644
--- a/games/doom/src/doom/r_things.c
+++ b/games/doom/src/doom/r_things.c
@@ -1312,6 +1312,9 @@ static void nw_draw_vis_sprite(vissprite_t *vis, int x1, int x2) {
nw_masked_flush();
}
+// the columns of each masked seg drawn in the band
+static uint64_t nw_masked_done[NW_DRAWSEG_MAX];
+
// vanilla's R_RenderMaskedSegRange
static void nw_masked_seg_range(nw_drawseg_t *ds, int x1, int x2) {
if (x1 > x2) return;
@@ -1335,8 +1338,12 @@ static void nw_masked_seg_range(nw_drawseg_t *ds, int x1, int x2) {
framedrawable_t *fd = lookup_masked_texture(m->texture);
int width_mask = whd_textures[m->texture].width - 1;
if (fixedcolormap) dc_colormap_index = fixedcolormap;
+ uint64_t *done = &nw_masked_done[ds - nw_drawsegs];
for (dc_x = x1; dc_x <= x2; dc_x++, spryscale += step) {
- if (cols[dc_x] == SHRT_MAX) continue;
+ // (each column once in the band: the frame may be drawn again, in a melt, so the columns are kept)
+ uint64_t bit = (uint64_t) 1 << (dc_x - nw_band_x0);
+ if (*done & bit) continue;
+ *done |= bit;
if (!fixedcolormap) {
unsigned index = spryscale >> LIGHTSCALESHIFT;
if (index >= MAXLIGHTSCALE) index = MAXLIGHTSCALE - 1;
@@ -1345,7 +1352,6 @@ static void nw_masked_seg_range(nw_drawseg_t *ds, int x1, int x2) {
sprtopscreen = centeryfrac - FixedMul(dc_texturemid, spryscale);
dc_iscale = 0xffffffffu / (unsigned) spryscale;
nw_draw_masked_column(R_GetMaskedColumn(fd, cols[dc_x] & width_mask));
- cols[dc_x] = SHRT_MAX;
}
nw_masked_flush();
}
@@ -1488,6 +1494,7 @@ int nw_fuzz_prepass(int fuzzpos) {
// the band's sprites, masked walls and weapon (nw_band_x0 to nw_band_x1): vanilla's R_DrawMasked
void nw_draw_masked(void) {
+ memset(nw_masked_done, 0, nw_drawseg_count * sizeof nw_masked_done[0]);
for (int k = 0; k < nw_vissprite_count; k++) {
vissprite_t *spr = &nw_vissprites[nw_vis_order[k]];
if (spr->x2 < nw_band_x0 || spr->x1 >= nw_band_x1) continue;
diff --git a/games/doom/src/nw/i_video.c b/games/doom/src/nw/i_video.c
index bb58de90..2311620d 100644
--- a/games/doom/src/nw/i_video.c
+++ b/games/doom/src/nw/i_video.c
@@ -218,6 +218,32 @@ void nw_band_begin(uint8_t *band, int x0, int x1) {
uint8_t host_doom_screen[SCREENWIDTH * SCREENHEIGHT]; /* (tests: the frame in Doom's own pixels) */
#endif
+/* the melt (nw/nw_back.inc): the band's columns of the screen moved down, the new rows above them */
+extern int16_t nw_melt_from[SCREENWIDTH / 2], nw_melt_to[SCREENWIDTH / 2];
+extern int nw_melting;
+static void nw_melt_band(int x0, int x1) {
+ uint16_t col[8 * PLAT_H], doom[SCREENHEIGHT];
+ for (int x = x0; x < x1; x += 8) {
+ int moved = 0;
+ for (int c = 0; c < 8; c += 2) moved |= nw_melt_to[(x + c) / 2] > nw_melt_from[(x + c) / 2];
+ if (!moved) continue;
+ plat_pull(x, 0, 8, PLAT_H, col);
+ for (int c = 0; c < 8; c++) {
+ int from = nw_melt_from[(x + c) / 2], to = nw_melt_to[(x + c) / 2];
+ if (to <= from) continue;
+ /* the screen's rows as Doom's (screen row 6k + j is Doom's 5k + j, the sixth the fifth again) */
+ for (int d = 0; d < SCREENHEIGHT; d++) doom[d] = col[(d / 5 * 6 + d % 5) * 8 + c];
+ for (int d = SCREENHEIGHT - 1; d >= to; d--) doom[d] = doom[d - to + from];
+ for (int d = from; d < to; d++) doom[d] = palette[nw_band[d * NW_BAND_W + x + c - x0]];
+ for (int l = 0; l < PLAT_H; l++) {
+ int j = l % 6;
+ col[l * 8 + c] = doom[l / 6 * 5 + (j < 5 ? j : 4)];
+ }
+ }
+ plat_push(x, 0, 8, PLAT_H, col);
+ }
+}
+
void nw_band_end(int x0, int x1) {
int w = x1 - x0;
#ifdef HOST
@@ -229,6 +255,10 @@ void nw_band_end(int x0, int x1) {
nw_band_ms += (made - nw_band_ms) / 4;
if (nw_sync_period && !nw_sync_off) nw_sync_band(j);
uint32_t t = plat_millis();
+ if (nw_melting) {
+ nw_melt_band(x0, x1);
+ return;
+ }
uint16_t lines[NW_BAND_W * 24];
for (int y = 0; y < SCREENHEIGHT; y += 20) {
const uint8_t *src = nw_band + y * NW_BAND_W;
diff --git a/games/doom/src/nw/nw_back.inc b/games/doom/src/nw/nw_back.inc
index eb4a361c..8a309eb4 100644
--- a/games/doom/src/nw/nw_back.inc
+++ b/games/doom/src/nw/nw_back.inc
@@ -480,8 +480,93 @@ static void nw_draw_band(uint8_t *band, int x0, int x1, bool view, int help, boo
nw_band_end(x0, x1);
}
+// the frame's bands, in the order the panel refreshes them
+static bool nw_frame_view, nw_frame_strips;
+static int nw_frame_help;
+
+static void nw_draw_frame() {
+ bool view = nw_frame_view, strips = nw_frame_strips;
+ int help = nw_frame_help;
+ nw_frame_begin();
+ uint8_t __aligned(8) band[NW_BAND_W * SCREENHEIGHT];
+ const int bands = SCREENWIDTH / NW_BAND_W;
+ if (nw_scan_right_to_left) {
+ // (a frame drawn band by band has its visplanes in each band's pass: the spans' starts in the bands
+ // on the left are not known, and are taken where the band starts)
+ bool edges = view && !automapactive && !strips;
+ if (edges) nw_plane_edges(band);
+ for (int k = bands - 1; k >= 0; k--) {
+ if (edges && k) {
+ memcpy(nw_carry_plane, nw_edge_plane[k - 1], sizeof nw_carry_plane);
+ memcpy(nw_carry_start, nw_edge_start[k - 1], sizeof nw_carry_start);
+ } else {
+ memset(nw_carry_plane, -1, sizeof nw_carry_plane);
+ }
+ nw_draw_band(band, k * NW_BAND_W, (k + 1) * NW_BAND_W, view, help, strips);
+ }
+ } else {
+ memset(nw_carry_plane, -1, sizeof nw_carry_plane);
+ for (int k = 0; k < bands; k++) nw_draw_band(band, k * NW_BAND_W, (k + 1) * NW_BAND_W, view, help, strips);
+ }
+ nw_band_x0 = 0;
+ nw_band_x1 = SCREENWIDTH;
+ nw_frame_end();
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// vanilla's screen melt (f_wipe.c) from the screen shown to the new one: the panel keeps the old screen, each
+// of its columns (two pixels wide) slides down, and the new screen's rows show above it; the new screen is the
+// frame drawn when it started, drawn again from its records each time (nw/i_video.c moves the columns)
+
+extern "C" {
+int16_t nw_melt_from[SCREENWIDTH / 2], nw_melt_to[SCREENWIDTH / 2];
+int nw_melting;
+int M_Random(void);
+}
+static int16_t nw_melt_y[SCREENWIDTH / 2];
+static bool nw_melt_going;
+
+// a tic or more of it; true when it is done
+extern "C" int nw_melt(int tics) {
+ const int height = SCREENHEIGHT;
+ if (!nw_melt_going) {
+ // wipe_initMelt: the columns' starting places (for all 320 of them, though half are used)
+ nw_melt_going = true;
+ int y = -(M_Random() % 16);
+ nw_melt_y[0] = (int16_t) y;
+ for (int i = 1; i < SCREENWIDTH; i++) {
+ int r = (M_Random() % 3) - 1;
+ y += r;
+ if (y > 0) y = 0;
+ else if (y == -16) y = -15;
+ if (i < SCREENWIDTH / 2) nw_melt_y[i] = (int16_t) y;
+ }
+ }
+ // wipe_doMelt
+ bool done = true;
+ for (int i = 0; i < SCREENWIDTH / 2; i++) nw_melt_from[i] = nw_melt_y[i] > 0 ? nw_melt_y[i] : 0;
+ while (tics--) {
+ for (int i = 0; i < SCREENWIDTH / 2; i++) {
+ if (nw_melt_y[i] < 0) {
+ nw_melt_y[i]++;
+ done = false;
+ } else if (nw_melt_y[i] < height) {
+ int dy = nw_melt_y[i] < 16 ? nw_melt_y[i] + 1 : 8;
+ if (nw_melt_y[i] + dy >= height) dy = height - nw_melt_y[i];
+ nw_melt_y[i] = (int16_t) (nw_melt_y[i] + dy);
+ done = false;
+ }
+ }
+ }
+ for (int i = 0; i < SCREENWIDTH / 2; i++) nw_melt_to[i] = nw_melt_y[i] > 0 ? nw_melt_y[i] : 0;
+ nw_melting = 1;
+ nw_draw_frame();
+ nw_melting = 0;
+ if (done) nw_melt_going = false;
+ return done;
+}
+
void pd_end_frame(int wipe_start) {
- (void) wipe_start;
int help = inhelpscreens;
bool view = gamestate == GS_LEVEL && !help;
#if HOST
@@ -519,43 +604,23 @@ void pd_end_frame(int wipe_start) {
nw_patches[0].header.max = count_of(nw_patches) - 1;
V_BeginPatchList(nw_patches);
if (!help) {
- if (gamestate == GS_LEVEL) ST_Drawer(false, !pre_wipe_state);
+ if (gamestate == GS_LEVEL) ST_Drawer(false, true);
else if (gamestate == GS_INTERMISSION) WI_Drawer();
} else if (gamestate == GS_LEVEL) {
ST_doPaletteStuff();
}
ST_FpsDrawer(-1);
- if (!pre_wipe_state && gamestate == GS_LEVEL && gametic && !inhelpscreens) HU_Drawer();
+ if (gamestate == GS_LEVEL && gametic && !inhelpscreens) HU_Drawer();
if (paused) {
int y = automapactive ? 4 : viewwindowy + 4;
V_DrawPatchDirect(viewwindowx + (scaledviewwidth - 68) / 2, y, VPATCH_HANDLE(VPATCH_NAME(M_PAUSE)));
}
M_Drawer();
- if (pre_wipe_state == PRE_WIPE_EXTRA_FRAME_NEEDED) pre_wipe_state = PRE_WIPE_EXTRA_FRAME_DONE;
- nw_frame_begin();
- uint8_t __aligned(8) band[NW_BAND_W * SCREENHEIGHT];
- const int bands = SCREENWIDTH / NW_BAND_W;
- if (nw_scan_right_to_left) {
- // (a frame drawn band by band has its visplanes in each band's pass: the spans' starts in the bands
- // on the left are not known, and are taken where the band starts)
- bool edges = view && !automapactive && !strips;
- if (edges) nw_plane_edges(band);
- for (int k = bands - 1; k >= 0; k--) {
- if (edges && k) {
- memcpy(nw_carry_plane, nw_edge_plane[k - 1], sizeof nw_carry_plane);
- memcpy(nw_carry_start, nw_edge_start[k - 1], sizeof nw_carry_start);
- } else {
- memset(nw_carry_plane, -1, sizeof nw_carry_plane);
- }
- nw_draw_band(band, k * NW_BAND_W, (k + 1) * NW_BAND_W, view, help, strips);
- }
- } else {
- memset(nw_carry_plane, -1, sizeof nw_carry_plane);
- for (int k = 0; k < bands; k++) nw_draw_band(band, k * NW_BAND_W, (k + 1) * NW_BAND_W, view, help, strips);
- }
+ nw_frame_view = view;
+ nw_frame_strips = strips;
+ nw_frame_help = help;
fuzzpos = (int8_t) fuzz_end;
- nw_band_x0 = 0;
- nw_band_x1 = SCREENWIDTH;
- nw_frame_end();
+ // (a wipe: the old screen stays, and melts into this one, nw_melt)
+ if (!wipe_start) nw_draw_frame();
}
diff --git a/games/doom/src/nw/plat.h b/games/doom/src/nw/plat.h
index 07864f93..9b34338e 100644
--- a/games/doom/src/nw/plat.h
+++ b/games/doom/src/nw/plat.h
@@ -20,6 +20,8 @@ void plat_push(int x, int y, int w, int h, const uint16_t *px);
void plat_fill(int x, int y, int w, int h, uint16_t c);
/* waits for the display's next refresh to start (false if it cannot tell) */
bool plat_vblank(void);
+/* what the display shows, back */
+void plat_pull(int x, int y, int w, int h, uint16_t *px);
bool plat_save(const char *name, const void *data, uint32_t len);
const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */
/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its
diff --git a/games/doom/src/nw/plat_eadk.c b/games/doom/src/nw/plat_eadk.c
index c78c66e3..ad18e2fd 100644
--- a/games/doom/src/nw/plat_eadk.c
+++ b/games/doom/src/nw/plat_eadk.c
@@ -15,6 +15,9 @@ void plat_push(int x, int y, int w, int h, const uint16_t *px) {
eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
}
bool plat_vblank(void) { return eadk_display_wait_for_vblank(); }
+void plat_pull(int x, int y, int w, int h, uint16_t *px) {
+ eadk_display_pull_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
void plat_fill(int x, int y, int w, int h, uint16_t c) {
if (w > 0 && h > 0) eadk_display_push_rect_uniform((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, c);
}
diff --git a/games/doom/src/nw/plat_host.c b/games/doom/src/nw/plat_host.c
index 609a9edd..be583779 100644
--- a/games/doom/src/nw/plat_host.c
+++ b/games/doom/src/nw/plat_host.c
@@ -27,6 +27,11 @@ void plat_push(int x, int y, int w, int h, const uint16_t *px) {
if ((unsigned)(x + c) < PLAT_W && (unsigned)(y + r) < PLAT_H) host_fb[(y + r) * PLAT_W + x + c] = px[r * w + c];
}
bool plat_vblank(void) { return false; }
+void plat_pull(int x, int y, int w, int h, uint16_t *px) {
+ for (int r = 0; r < h; r++)
+ for (int c = 0; c < w; c++)
+ px[r * w + c] = (unsigned)(x + c) < PLAT_W && (unsigned)(y + r) < PLAT_H ? host_fb[(y + r) * PLAT_W + x + c] : 0;
+}
void plat_fill(int x, int y, int w, int h, uint16_t c) {
for (int r = 0; r < h; r++)
for (int k = 0; k < w; k++)
diff --git a/games/doom/tests/check.py b/games/doom/tests/check.py
index 3af87281..565bf5b5 100644
--- a/games/doom/tests/check.py
+++ b/games/doom/tests/check.py
@@ -51,14 +51,15 @@ def check(cond, what):
# the title, the credits and the three demos, which must play exactly as in Chocolate Doom 3.1.0 (vanilla Doom
-# 1.9): where each ends, the player there and both random number generators are Chocolate Doom's, tic for tic
+# 1.9): where each ends, the player there and both random number generators are Chocolate Doom's, tic for tic (the
+# screen melts take theirs from the second one, M_Random, as they do there)
CHOCOLATE = [
"leveltime=5026 map=E1M5 x=87385351 y=84364146 z=5767168 angle=2514731840 health=0 armor=36 kills=61 items=7 "
- "secrets=1 ammo=103,0,0,0 weapon=1 prnd=181 rnd=108",
+ "secrets=1 ammo=103,0,0,0 weapon=1 prnd=181 rnd=172",
"leveltime=3836 map=E1M3 x=-9362093 y=-84944896 z=3145728 angle=2688383391 health=0 armor=0 kills=41 items=14 "
- "secrets=0 ammo=140,34,0,0 weapon=2 prnd=75 rnd=152",
+ "secrets=0 ammo=140,34,0,0 weapon=2 prnd=75 rnd=216",
"leveltime=2134 map=E1M7 x=-91417116 y=-164628508 z=7340032 angle=2593932736 health=0 armor=68 kills=20 items=9 "
- "secrets=0 ammo=70,14,0,0 weapon=2 prnd=207 rnd=107",
+ "secrets=0 ammo=70,14,0,0 weapon=2 prnd=207 rnd=171",
]
e = run(["--ms", "340000"], what="the demos")
if e:
diff --git a/games/doom/tests/play.c b/games/doom/tests/play.c
index 5b04e94f..5563e0b7 100644
--- a/games/doom/tests/play.c
+++ b/games/doom/tests/play.c
@@ -102,6 +102,10 @@ void host_demo_end(void) {
gametic, leveltime, gameepisode, gamemap, mo ? mo->xy.x : 0, mo ? mo->xy.y : 0, mo ? mo->z : 0,
mo ? (unsigned)mobj_full(mo)->angle : 0u, p->health, p->armorpoints, p->killcount, p->itemcount,
p->secretcount, p->ammo[0], p->ammo[1], p->ammo[2], p->ammo[3], (int)p->readyweapon, prndindex, rndindex);
+ int mapped = 0;
+ line_t *li = lines;
+ for (int i = 0; i < (int)numlines; i++, li += line_next_step(li)) mapped += line_is_mapped(li) != 0;
+ printf("MAPPED %d of %d\n", mapped, (int)numlines);
fflush(stdout);
}
diff --git a/games/doom/tools/panel.py b/games/doom/tools/panel.py
new file mode 100644
index 00000000..480f40eb
--- /dev/null
+++ b/games/doom/tools/panel.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""panel.py NWA [--model n0120|n0110] [--hz 40] [--dir ltr|rtl] [--from MS] [--ms MS] [--keys SPEC] [--out DIR]:
+Doom in the emulator (tools/emu.py) with the calculator's display panel as it refreshes itself: every 1/hz s, after
+its blanking time, it goes over its memory a column at a time (left to right, or right to left), and
+eadk_display_wait_for_vblank waits for the blanking time. Each refresh's picture is compared with the frames the app
+sent: a refresh that shows parts of two frames is torn (its picture is saved in DIR, the first few).
+
+Time is the calculator's: the emulator runs 216 million instructions a second, which is the N0110's clock; on the N0120
+(550 MHz) everything the app does takes 216/550 of the time. Sending pixels takes 40 ns each."""
+import argparse
+import os
+import struct
+import sys
+
+import numpy as np
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "tools"))
+import emu # noqa: E402
+
+ap = argparse.ArgumentParser()
+ap.add_argument("nwa")
+ap.add_argument("--model", default="n0120", choices=["n0120", "n0110"])
+ap.add_argument("--hz", type=float, default=40.0)
+ap.add_argument("--dir", default="ltr", choices=["ltr", "rtl"])
+ap.add_argument("--vblank", default="end", choices=["start", "end"], help="when the wait for vblank returns")
+ap.add_argument("--from", dest="t0", type=int, default=2000, help="real ms: refreshes before are not counted")
+ap.add_argument("--ms", type=int, default=12000, help="real ms to run")
+ap.add_argument("--keys", default="")
+ap.add_argument("--out", default="")
+ap.add_argument("--ns-per-pixel", type=float, default=40.0)
+a = ap.parse_args()
+
+emu.configure(model=a.model, ram_length=133652)
+K = 550 / 216 if a.model == "n0120" else 1.0 # emulator ms for one real ms
+T = 1000.0 / a.hz # the refresh period, real ms
+V = T * 24 / 344 # its blanking time (24 lines of porch for 320)
+DT = (T - V) / 320 # the time to refresh one column
+
+
+class Panel(emu.Calculator):
+ def __init__(self, nwa):
+ super().__init__(nwa)
+ self.mem = np.zeros((240, 320), np.uint16)
+ self.ref = 0 # the refresh being done
+ self.col = 0 # the columns of it done
+ self.comp = np.zeros((240, 320), np.uint16)
+ self.frames = [] # the last whole frames sent
+ self.last_frame_count = None
+ self.refreshes = self.torn = 0
+ self.torn_pixels = []
+ self.saved = 0
+ self.frame_times = []
+
+ def real(self):
+ return self.now_ms / K
+
+ def scan_until(self, t):
+ """the panel's refreshes up to real time t"""
+ while True:
+ start = self.ref * T + V
+ n = int((t - start) / DT) + 1 if t >= start else 0
+ n = min(n, 320)
+ if n > self.col:
+ cols = slice(self.col, n) if a.dir == "ltr" else slice(320 - n, 320 - self.col)
+ self.comp[:, cols] = self.mem[:, cols]
+ self.col = n
+ if self.col < 320:
+ return
+ self.judge()
+ self.ref += 1
+ self.col = 0
+
+ def judge(self):
+ if self.ref * T < a.t0 or not self.frames:
+ return
+ self.refreshes += 1
+ best = min(int(np.count_nonzero(self.comp != f)) for f in self.frames + [self.mem])
+ if best:
+ self.torn += 1
+ self.torn_pixels.append(best)
+ if a.out and self.saved < 6:
+ from PIL import Image
+ c = self.comp.astype(np.uint32)
+ rgb = np.stack([((c >> 11) & 31) * 255 // 31, ((c >> 5) & 63) * 255 // 63, (c & 31) * 255 // 31], -1)
+ Image.fromarray(rgb.astype(np.uint8), "RGB").save(f"{a.out}/torn_{int(self.ref * T):06d}.png")
+ self.saved += 1
+
+ def frame_count(self):
+ return struct.unpack("<I", bytes(self.uc.mem_read(self.symbols["perf_frames"], 4)))[0]
+
+ def _intr(self, uc, intno, data):
+ if intno != 2:
+ return super()._intr(uc, intno, data)
+ pc = self.reg(emu.UC_ARM_REG_PC)
+ n = struct.unpack("<H", uc.mem_read(pc - 2, 2))[0] & 0xFF
+ r0, r1 = self.reg(emu.UC_ARM_REG_R0), self.reg(emu.UC_ARM_REG_R1)
+ if n == 19: # push: the frame before it, if one ended
+ fc = self.frame_count()
+ if fc != self.last_frame_count:
+ if self.last_frame_count is not None:
+ self.frames = (self.frames + [self.mem.copy()])[-3:]
+ self.frame_times.append(self.real())
+ self.last_frame_count = fc
+ x, y, w, h = r0 & 0xFFFF, r0 >> 16, r1 & 0xFFFF, r1 >> 16
+ t = self.real()
+ self.scan_until(t)
+ px = np.frombuffer(bytes(uc.mem_read(self.reg(emu.UC_ARM_REG_R2), w * h * 2)), "<u2").reshape(h, w)
+ self.mem[y:y + h, x:x + w] = px
+ self.now_ms += w * h * a.ns_per_pixel / 1e6 * K
+ self.scan_until(self.real())
+ return super()._intr(uc, intno, data)
+ if n == 21: # wait for vblank
+ t = self.real()
+ k = int(t // T) + 1
+ when = k * T + (V if a.vblank == "end" else 0)
+ if a.vblank == "end" and t < (k - 1) * T + V:
+ when = (k - 1) * T + V
+ self.scan_until(when)
+ self.now_ms = when * K
+ uc.reg_write(emu.UC_ARM_REG_R0, 1)
+ return
+ if n == 48: # millis
+ ms = int(self.real())
+ uc.reg_write(emu.UC_ARM_REG_R0, ms & 0xFFFFFFFF)
+ uc.reg_write(emu.UC_ARM_REG_R1, ms >> 32)
+ return
+ if n in (49, 50): # msleep, usleep
+ d = r0 if n == 49 else r0 / 1000
+ self.now_ms += d * K
+ self.slept_ms += d * K
+ self.scan_until(self.real())
+ return
+ return super()._intr(uc, intno, data)
+
+ def go(self, until_real_ms):
+ chunk = emu.CPU_HZ // 10000 # a tenth of an emulator millisecond
+ while not self.exited and self.real() < until_real_ms:
+ self.uc.emu_start(self.pc, 0xFFFFFFFF, count=chunk)
+ self.pc = self.reg(emu.UC_ARM_REG_PC) | 1
+ self.insns += chunk
+ self.now_ms += 0.1
+ self.scan_until(self.real())
+
+
+c = Panel(a.nwa)
+c.keys = [(int(s * K), int(e * K), k) for s, e, k in emu.parse_keys(a.keys)] if a.keys else []
+if a.out:
+ os.makedirs(a.out, exist_ok=True)
+c.go(a.ms)
+ft = [t for t in c.frame_times if t >= a.t0]
+fps = (len(ft) - 1) / ((ft[-1] - ft[0]) / 1000) if len(ft) > 1 else 0
+print(f"{a.model} {a.hz:g} Hz {a.dir}: {c.refreshes} refreshes, {c.torn} torn"
+ + (f" (pixels: median {sorted(c.torn_pixels)[len(c.torn_pixels) // 2]}, most {max(c.torn_pixels)})"
+ if c.torn else "") + f", {fps:.1f} frames a second")