BlueGit

projects-timfalken-com meteors

t1183: Playwright flame sampling and frame strip

timfa Grok Bot · pushed by timfa

Authored 2026-11-14 · 3 days ago

Hash
a06352dacc4ec608161210c3d530935e00a2ad04
Parent
bb3f80d0
1 file changed +131 −0
test/t1183-flame-playwright.py added +131 −0
@@ -0,0 +1,131 @@
1 #!/usr/bin/env python3
2 """t1183: rocket flame jitter — sample the flame per frame and save a frame strip.
3
4 Usage: python3 test/t1183-flame-playwright.py URL TAG
5 Starts a logged-out solo game, freezes the game core (rendering keeps
6 running), places one gray rocket block with a flame and records the
7 flame's frame / flip / rotation / size and its top-centre anchor every
8 animation frame, plus a strip of close-up screenshots.
9 """
10 import json, sys, statistics
11 from pathlib import Path
12 from playwright.sync_api import sync_playwright
13 from PIL import Image, ImageDraw
14
15 URL = sys.argv[1] if len(sys.argv) > 1 else "https://projects.timfalken.com/meteors/"
16 TAG = sys.argv[2] if len(sys.argv) > 2 else "live"
17 SHOTS = Path("/workspace/meteors-shots")
18 fails = []
19
20 def check(c, m):
21 print(("OK " if c else "FAIL ") + m)
22 if not c: fails.append(m)
23
24 with sync_playwright() as pw:
25 br = pw.chromium.launch(args=["--use-gl=angle", "--use-angle=swiftshader"])
26 ctx = br.new_context(viewport={"width": 1280, "height": 800})
27 page = ctx.new_page()
28 errors = []
29 page.on("pageerror", lambda e: errors.append(str(e)))
30 page.goto(URL + ("" if URL.endswith("/") else "/") + "index.html?t1183=" + TAG, wait_until="networkidle")
31 has = page.evaluate("() => typeof FlameFx !== 'undefined'")
32 check(has, "FlameFx present in the served game.js")
33 page.locator("#btn-play").click()
34 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
35 page.wait_for_timeout(200)
36 page.locator("#btn-planet-go").click()
37 page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)
38 page.wait_for_timeout(400)
39 info = page.evaluate("""() => {
40 app.core.tick = function () {};
41 for (const b of app.core.blocks.slice()) { b.y = -50; }
42 const b = app.core.createBlock(4, 7, GameCore.COLOR_GRAY, 'still');
43 b.flame = true; b.vy = 0;
44 window.__fb = b;
45 const R = window.__flame = { rows: [] };
46 const loop = () => {
47 const f = app.flames[b.id];
48 if (f) {
49 const p = { x: f.transform.position.x, y: f.transform.position.y, w: f.transform.size.x,
50 h: f.transform.size.y, rotation: f.transform.rotation, mirrorX: f.renderer.mirrorX };
51 const top = FlameFx.topCentreOf(p);
52 R.rows.push([performance.now(), f.renderer.subImage, !!f.renderer.mirrorX, +f.transform.rotation.toFixed(3),
53 +f.transform.size.x.toFixed(2), +f.transform.size.y.toFixed(2), +top.x.toFixed(3), +top.y.toFixed(3)]);
54 }
55 requestAnimationFrame(loop);
56 };
57 requestAnimationFrame(loop);
58 const cv = app.scene.canvas;
59 const c = cv.getBoundingClientRect();
60 return { tile: app.tile, col: b.col, fieldH: app.fieldH, canvas: [c.left, c.top, c.width, c.height],
61 cw: cv.width, reduced: FlameFx.reducedMotion(), fps: FlameFx.FPS,
62 vars: [FlameFx.SCALE_VAR, FlameFx.WIDTH_VAR, FlameFx.HEIGHT_VAR, FlameFx.ROT_VAR_DEG] };
63 }""")
64 page.wait_for_timeout(500)
65 # Close-up strip around the rocket.
66 t = info["tile"]; cl, ct, cwid, ch = info["canvas"]; k = cwid / info["cw"]
67 cx = cl + (info["col"] * t + t / 2) * k
68 topy = ct + (info["fieldH"] - 7 * t - t * 0.5) * k
69 clip = {"x": cx - 2.0 * t * k, "y": topy - 0.4 * t * k, "width": 4.0 * t * k, "height": 3.6 * t * k}
70 frames = []
71 for i in range(12):
72 p = SHOTS / f"t1183-{TAG}-frame-{i:02d}.png"
73 page.screenshot(path=str(p), clip=clip)
74 frames.append(p)
75 page.wait_for_timeout(45)
76 page.wait_for_timeout(1500)
77 rows = page.evaluate("() => window.__flame.rows")
78 page.screenshot(path=str(SHOTS / f"t1183-{TAG}-full.png"))
79 ctx.close()
80 # Reduced-motion context: old rate, no flip / scale / rotation.
81 ctx2 = br.new_context(viewport={"width": 1280, "height": 800}, reduced_motion="reduce")
82 p2 = ctx2.new_page()
83 p2.goto(URL + ("" if URL.endswith("/") else "/") + "index.html", wait_until="networkidle")
84 red = p2.evaluate("""() => { const s = FlameFx.create(4, Math.random, FlameFx.reducedMotion()); const r = [];
85 for (let i = 0; i < 40; i++) { FlameFx.advance(s, 0.05, Math.random, FlameFx.reducedMotion()); r.push([s.flip, s.rot, s.scale * s.w * s.h]); }
86 return { reduced: FlameFx.reducedMotion(), anyJitter: r.some(x => x[0] || x[1] !== 0 || x[2] !== 1) }; }""")
87 ctx2.close()
88 br.close()
89
90 # Strip image.
91 ims = [Image.open(p) for p in frames]
92 w, h = ims[0].size
93 strip = Image.new("RGB", (w * len(ims), h + 18), (12, 12, 24))
94 d = ImageDraw.Draw(strip)
95 for i, im in enumerate(ims):
96 strip.paste(im, (i * w, 18))
97 d.text((i * w + 4, 3), f"#{i + 1}", fill=(220, 220, 220))
98 strip_path = SHOTS / f"t1183-{TAG}-strip.png"
99 strip.save(strip_path)
100
101 # Analysis over the sampled frames (only frames where the pose changed = ticks).
102 ticks = [b for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6]]
103 dur = (rows[-1][0] - rows[0][0]) / 1000 if len(rows) > 1 else 1
104 tick_rate = len(ticks) / dur
105 frame_changes = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] != b[1])
106 same_frame_ticks = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] == b[1])
107 anchor_x = [r[6] for r in rows]; anchor_y = [r[7] for r in rows]
108 rots = [r[3] for r in rows]; flips = [r[2] for r in rows]
109 ws = [r[4] for r in rows]; hs = [r[5] for r in rows]
110 summary = {
111 "url": URL, "fps_constant": info["fps"], "variation": dict(zip(["scale", "width", "height", "rotation_deg"], info["vars"])),
112 "reduced_motion_in_main_ctx": info["reduced"], "samples": len(rows), "seconds": round(dur, 2),
113 "measured_tick_rate_hz": round(tick_rate, 1), "frames_used": sorted(set(r[1] for r in rows)),
114 "ticks_with_same_frame": same_frame_ticks, "flip_share": round(sum(flips) / len(flips), 2),
115 "rotation_range": [min(rots), max(rots)], "width_range": [min(ws), max(ws)], "height_range": [min(hs), max(hs)],
116 "anchor_spread_px": [round(max(anchor_x) - min(anchor_x), 3), round(max(anchor_y) - min(anchor_y), 3)],
117 "reduced_motion_ctx": red, "errors": errors, "strip": str(strip_path),
118 }
119 (SHOTS / f"t1183-{TAG}-metrics.json").write_text(json.dumps({"summary": summary, "rows": rows}, indent=1))
120 print(json.dumps(summary, indent=1))
121 check(len(rows) > 60, f"sampled {len(rows)} frames")
122 check(15 <= tick_rate <= 30, f"tick rate ~25 Hz (measured {tick_rate:.1f}; capped by the headless frame rate)")
123 check(set(summary["frames_used"]) == {0, 1, 2, 3}, "all 4 sprite frames used")
124 check(same_frame_ticks == 0, "every tick switches to a different frame")
125 check(0.3 <= summary["flip_share"] <= 0.7, f"flips about half the time ({summary['flip_share']})")
126 check(max(abs(min(rots)), abs(max(rots))) <= 2.5 + 1e-6 and max(rots) - min(rots) > 2, "rotation within ±2.5° and varies")
127 check(summary["anchor_spread_px"][0] < 0.01 and summary["anchor_spread_px"][1] < 0.01, f"top-centre anchor fixed {summary['anchor_spread_px']}")
128 check(red["reduced"] and not red["anyJitter"], "reduced motion: no flip/scale/rotation")
129 check(not errors, f"no page errors {errors[:2]}")
130 print("ALL OK" if not fails else f"{len(fails)} FAIL")
131 sys.exit(1 if fails else 0)
@@ -0,0 +1,131 @@
1#!/usr/bin/env python3
2"""t1183: rocket flame jitter — sample the flame per frame and save a frame strip.
3
4Usage: python3 test/t1183-flame-playwright.py URL TAG
5Starts a logged-out solo game, freezes the game core (rendering keeps
6running), places one gray rocket block with a flame and records the
7flame's frame / flip / rotation / size and its top-centre anchor every
8animation frame, plus a strip of close-up screenshots.
9"""
10import json, sys, statistics
11from pathlib import Path
12from playwright.sync_api import sync_playwright
13from PIL import Image, ImageDraw
14
15URL = sys.argv[1] if len(sys.argv) > 1 else "https://projects.timfalken.com/meteors/"
16TAG = sys.argv[2] if len(sys.argv) > 2 else "live"
17SHOTS = Path("/workspace/meteors-shots")
18fails = []
19
20def check(c, m):
21 print(("OK " if c else "FAIL ") + m)
22 if not c: fails.append(m)
23
24with sync_playwright() as pw:
25 br = pw.chromium.launch(args=["--use-gl=angle", "--use-angle=swiftshader"])
26 ctx = br.new_context(viewport={"width": 1280, "height": 800})
27 page = ctx.new_page()
28 errors = []
29 page.on("pageerror", lambda e: errors.append(str(e)))
30 page.goto(URL + ("" if URL.endswith("/") else "/") + "index.html?t1183=" + TAG, wait_until="networkidle")
31 has = page.evaluate("() => typeof FlameFx !== 'undefined'")
32 check(has, "FlameFx present in the served game.js")
33 page.locator("#btn-play").click()
34 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
35 page.wait_for_timeout(200)
36 page.locator("#btn-planet-go").click()
37 page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)
38 page.wait_for_timeout(400)
39 info = page.evaluate("""() => {
40 app.core.tick = function () {};
41 for (const b of app.core.blocks.slice()) { b.y = -50; }
42 const b = app.core.createBlock(4, 7, GameCore.COLOR_GRAY, 'still');
43 b.flame = true; b.vy = 0;
44 window.__fb = b;
45 const R = window.__flame = { rows: [] };
46 const loop = () => {
47 const f = app.flames[b.id];
48 if (f) {
49 const p = { x: f.transform.position.x, y: f.transform.position.y, w: f.transform.size.x,
50 h: f.transform.size.y, rotation: f.transform.rotation, mirrorX: f.renderer.mirrorX };
51 const top = FlameFx.topCentreOf(p);
52 R.rows.push([performance.now(), f.renderer.subImage, !!f.renderer.mirrorX, +f.transform.rotation.toFixed(3),
53 +f.transform.size.x.toFixed(2), +f.transform.size.y.toFixed(2), +top.x.toFixed(3), +top.y.toFixed(3)]);
54 }
55 requestAnimationFrame(loop);
56 };
57 requestAnimationFrame(loop);
58 const cv = app.scene.canvas;
59 const c = cv.getBoundingClientRect();
60 return { tile: app.tile, col: b.col, fieldH: app.fieldH, canvas: [c.left, c.top, c.width, c.height],
61 cw: cv.width, reduced: FlameFx.reducedMotion(), fps: FlameFx.FPS,
62 vars: [FlameFx.SCALE_VAR, FlameFx.WIDTH_VAR, FlameFx.HEIGHT_VAR, FlameFx.ROT_VAR_DEG] };
63 }""")
64 page.wait_for_timeout(500)
65 # Close-up strip around the rocket.
66 t = info["tile"]; cl, ct, cwid, ch = info["canvas"]; k = cwid / info["cw"]
67 cx = cl + (info["col"] * t + t / 2) * k
68 topy = ct + (info["fieldH"] - 7 * t - t * 0.5) * k
69 clip = {"x": cx - 2.0 * t * k, "y": topy - 0.4 * t * k, "width": 4.0 * t * k, "height": 3.6 * t * k}
70 frames = []
71 for i in range(12):
72 p = SHOTS / f"t1183-{TAG}-frame-{i:02d}.png"
73 page.screenshot(path=str(p), clip=clip)
74 frames.append(p)
75 page.wait_for_timeout(45)
76 page.wait_for_timeout(1500)
77 rows = page.evaluate("() => window.__flame.rows")
78 page.screenshot(path=str(SHOTS / f"t1183-{TAG}-full.png"))
79 ctx.close()
80 # Reduced-motion context: old rate, no flip / scale / rotation.
81 ctx2 = br.new_context(viewport={"width": 1280, "height": 800}, reduced_motion="reduce")
82 p2 = ctx2.new_page()
83 p2.goto(URL + ("" if URL.endswith("/") else "/") + "index.html", wait_until="networkidle")
84 red = p2.evaluate("""() => { const s = FlameFx.create(4, Math.random, FlameFx.reducedMotion()); const r = [];
85 for (let i = 0; i < 40; i++) { FlameFx.advance(s, 0.05, Math.random, FlameFx.reducedMotion()); r.push([s.flip, s.rot, s.scale * s.w * s.h]); }
86 return { reduced: FlameFx.reducedMotion(), anyJitter: r.some(x => x[0] || x[1] !== 0 || x[2] !== 1) }; }""")
87 ctx2.close()
88 br.close()
89
90# Strip image.
91ims = [Image.open(p) for p in frames]
92w, h = ims[0].size
93strip = Image.new("RGB", (w * len(ims), h + 18), (12, 12, 24))
94d = ImageDraw.Draw(strip)
95for i, im in enumerate(ims):
96 strip.paste(im, (i * w, 18))
97 d.text((i * w + 4, 3), f"#{i + 1}", fill=(220, 220, 220))
98strip_path = SHOTS / f"t1183-{TAG}-strip.png"
99strip.save(strip_path)
100
101# Analysis over the sampled frames (only frames where the pose changed = ticks).
102ticks = [b for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6]]
103dur = (rows[-1][0] - rows[0][0]) / 1000 if len(rows) > 1 else 1
104tick_rate = len(ticks) / dur
105frame_changes = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] != b[1])
106same_frame_ticks = sum(1 for a, b in zip(rows, rows[1:]) if a[1:6] != b[1:6] and a[1] == b[1])
107anchor_x = [r[6] for r in rows]; anchor_y = [r[7] for r in rows]
108rots = [r[3] for r in rows]; flips = [r[2] for r in rows]
109ws = [r[4] for r in rows]; hs = [r[5] for r in rows]
110summary = {
111 "url": URL, "fps_constant": info["fps"], "variation": dict(zip(["scale", "width", "height", "rotation_deg"], info["vars"])),
112 "reduced_motion_in_main_ctx": info["reduced"], "samples": len(rows), "seconds": round(dur, 2),
113 "measured_tick_rate_hz": round(tick_rate, 1), "frames_used": sorted(set(r[1] for r in rows)),
114 "ticks_with_same_frame": same_frame_ticks, "flip_share": round(sum(flips) / len(flips), 2),
115 "rotation_range": [min(rots), max(rots)], "width_range": [min(ws), max(ws)], "height_range": [min(hs), max(hs)],
116 "anchor_spread_px": [round(max(anchor_x) - min(anchor_x), 3), round(max(anchor_y) - min(anchor_y), 3)],
117 "reduced_motion_ctx": red, "errors": errors, "strip": str(strip_path),
118}
119(SHOTS / f"t1183-{TAG}-metrics.json").write_text(json.dumps({"summary": summary, "rows": rows}, indent=1))
120print(json.dumps(summary, indent=1))
121check(len(rows) > 60, f"sampled {len(rows)} frames")
122check(15 <= tick_rate <= 30, f"tick rate ~25 Hz (measured {tick_rate:.1f}; capped by the headless frame rate)")
123check(set(summary["frames_used"]) == {0, 1, 2, 3}, "all 4 sprite frames used")
124check(same_frame_ticks == 0, "every tick switches to a different frame")
125check(0.3 <= summary["flip_share"] <= 0.7, f"flips about half the time ({summary['flip_share']})")
126check(max(abs(min(rots)), abs(max(rots))) <= 2.5 + 1e-6 and max(rots) - min(rots) > 2, "rotation within ±2.5° and varies")
127check(summary["anchor_spread_px"][0] < 0.01 and summary["anchor_spread_px"][1] < 0.01, f"top-centre anchor fixed {summary['anchor_spread_px']}")
128check(red["reduced"] and not red["anyJitter"], "reduced motion: no flip/scale/rotation")
129check(not errors, f"no page errors {errors[:2]}")
130print("ALL OK" if not fails else f"{len(fails)} FAIL")
131sys.exit(1 if fails else 0)