| 1 | #!/usr/bin/env python3 |
| 2 | """t1181: sender/receiver flight latency and smoothness with two real browser clients. |
| 3 | |
| 4 | Usage: t1181-flights-playwright.py [ROOT] [TAG] |
| 5 | ROOT defaults to /workspace/meteors (its build/ is served by php -S). |
| 6 | Desktop (1280x800) is the sender; mobile (390x844, touch, DPR 3) is the receiver. |
| 7 | Writes /workspace/meteors-shots/t1181-<TAG>-*.png and prints JSON metrics. |
| 8 | """ |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import json |
| 12 | import os |
| 13 | import socket |
| 14 | import subprocess |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import time |
| 18 | from pathlib import Path |
| 19 | |
| 20 | from playwright.sync_api import sync_playwright |
| 21 | |
| 22 | ROOT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/workspace/meteors") |
| 23 | TAG = sys.argv[2] if len(sys.argv) > 2 else "after" |
| 24 | SHOTS = Path("/workspace/meteors-shots") |
| 25 | SHOTS.mkdir(parents=True, exist_ok=True) |
| 26 | PHP = os.environ.get("PHP", "/home/box/.local/bin/php") |
| 27 | CHROME = "/usr/bin/google-chrome" |
| 28 | ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"] |
| 29 | FAILURES = [] |
| 30 | URL = None |
| 31 | |
| 32 | # Records, per frame, every flight element's on-screen centre, plus the |
| 33 | # Date.now() when each of my shots left the field (cull). |
| 34 | PROBE = """() => { |
| 35 | if (window.__probe) return; |
| 36 | const P = window.__probe = { culls: {}, tracks: {}, frames: 0 }; |
| 37 | const orig = GameCore.prototype.consumeOutgoingShots; |
| 38 | GameCore.prototype.consumeOutgoingShots = function () { |
| 39 | const shots = orig.call(this); |
| 40 | if (this === app.core) for (const s of shots) P.culls[String(s.id)] = Date.now(); |
| 41 | return shots; |
| 42 | }; |
| 43 | let ids = new WeakMap(); let next = 1; |
| 44 | function f() { |
| 45 | P.frames++; |
| 46 | const now = Date.now(); |
| 47 | for (const el of document.querySelectorAll('#flights .flight, #flights-back .flight')) { |
| 48 | if (!ids.has(el)) ids.set(el, 'el' + (next++)); |
| 49 | const k = ids.get(el); |
| 50 | const r = el.getBoundingClientRect(); |
| 51 | if (!r.width) continue; |
| 52 | (P.tracks[k] = P.tracks[k] || []).push([now, r.left + r.width / 2, r.top + r.height / 2]); |
| 53 | } |
| 54 | requestAnimationFrame(f); |
| 55 | } |
| 56 | requestAnimationFrame(f); |
| 57 | }""" |
| 58 | |
| 59 | SHOOT = """(n) => { |
| 60 | const out = []; |
| 61 | for (let i = 0; i < n; i++) { |
| 62 | const b = app.core.createBlock(2 + 2 * i, 13.0, i % 5, 'flying'); |
| 63 | b.vy = 6; |
| 64 | out.push(b.id); |
| 65 | } |
| 66 | return out; |
| 67 | }""" |
| 68 | |
| 69 | |
| 70 | def check(cond, msg): |
| 71 | print(("OK " if cond else "FAIL") + " " + msg) |
| 72 | if not cond: |
| 73 | FAILURES.append(msg) |
| 74 | return cond |
| 75 | |
| 76 | |
| 77 | def free_port(): |
| 78 | s = socket.socket(); s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]; s.close(); return port |
| 79 | |
| 80 | |
| 81 | def start_php(port, data): |
| 82 | env = os.environ.copy(); env["METEORS_DATA_DIR"] = str(data) |
| 83 | log = open(f"/tmp/t1181-php-{TAG}.log", "w") |
| 84 | proc = subprocess.Popen([PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")], |
| 85 | cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log) |
| 86 | time.sleep(0.5) |
| 87 | return proc |
| 88 | |
| 89 | |
| 90 | def login(page, n): |
| 91 | page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded") |
| 92 | page.wait_for_timeout(300) |
| 93 | page.goto(f"{URL}index.html?online=1", wait_until="domcontentloaded") |
| 94 | page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000) |
| 95 | page.locator("#online-panel").wait_for(state="visible", timeout=8000) |
| 96 | |
| 97 | |
| 98 | def analyse(tracks, t_ref): |
| 99 | """First appearance (ms after t_ref), max per-frame jump (px) and path length per flight.""" |
| 100 | out = [] |
| 101 | for k, pts in tracks.items(): |
| 102 | if len(pts) < 2: |
| 103 | continue |
| 104 | first = pts[0][0] - t_ref |
| 105 | jumps = [] |
| 106 | for a, b in zip(pts, pts[1:]): |
| 107 | dt = max(1, b[0] - a[0]) |
| 108 | d = ((b[1] - a[1]) ** 2 + (b[2] - a[2]) ** 2) ** 0.5 |
| 109 | jumps.append(d / (dt / 16.7)) # px per 60 Hz frame |
| 110 | out.append({"id": k, "first_ms": first, "frames": len(pts), "start": [round(pts[0][1]), round(pts[0][2])], |
| 111 | "max_jump_px": round(max(jumps), 1), "median_jump_px": round(sorted(jumps)[len(jumps) // 2], 1), |
| 112 | "max_kink_px": round(max([abs(y - x) for x, y in zip(jumps, jumps[1:])] or [0]), 1), |
| 113 | "dur_ms": pts[-1][0] - pts[0][0]}) |
| 114 | return sorted(out, key=lambda r: r["first_ms"]) |
| 115 | |
| 116 | |
| 117 | def main(): |
| 118 | global URL |
| 119 | port = free_port(); URL = f"http://127.0.0.1:{port}/" |
| 120 | proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1181-"))) |
| 121 | metrics = {} |
| 122 | try: |
| 123 | with sync_playwright() as p: |
| 124 | b = p.chromium.launch(executable_path=CHROME, args=ARGS, headless=True) |
| 125 | c1 = b.new_context(viewport={"width": 1280, "height": 800}) |
| 126 | c2 = b.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=3) |
| 127 | p1, p2 = c1.new_page(), c2.new_page() |
| 128 | errs = [] |
| 129 | for pg, tag in ((p1, "desktop"), (p2, "mobile")): |
| 130 | pg.on("pageerror", lambda e, tag=tag: errs.append(f"{tag}: {e}")) |
| 131 | login(p1, 1); login(p2, 2) |
| 132 | p1.locator("#btn-create").click() |
| 133 | p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000) |
| 134 | code = p1.locator("#lobby-code").inner_text().strip() |
| 135 | p2.locator("#join-code").fill(code); p2.locator("#btn-join").click() |
| 136 | p2.locator("#online-lobby").wait_for(state="visible", timeout=8000) |
| 137 | p1.locator("#btn-ready").click(); p2.locator("#btn-ready").click() |
| 138 | start = p1.locator("#btn-start") |
| 139 | for _ in range(20): |
| 140 | if start.is_visible() and start.is_enabled(): |
| 141 | break |
| 142 | p1.wait_for_timeout(400) |
| 143 | start.click() |
| 144 | for pg in (p1, p2): |
| 145 | pg.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000) |
| 146 | p1.wait_for_timeout(1500) |
| 147 | for pg in (p1, p2): |
| 148 | pg.evaluate(PROBE) |
| 149 | # Several rounds so the poll phase varies. |
| 150 | rounds = [] |
| 151 | for rnd in range(4): |
| 152 | for pg in (p1, p2): |
| 153 | pg.evaluate("() => { window.__probe.tracks = {}; window.__probe.culls = {}; }") |
| 154 | p1.wait_for_timeout(137 * rnd) |
| 155 | t_shot = p1.evaluate("() => Date.now()") |
| 156 | p1.evaluate(SHOOT, 3) |
| 157 | if rnd == 0: |
| 158 | p1.wait_for_timeout(120); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-120ms.png")) |
| 159 | p1.wait_for_timeout(330); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-450ms.png")) |
| 160 | p2.wait_for_timeout(500); p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-receiver.png")) |
| 161 | p1.wait_for_timeout(3200) |
| 162 | s = p1.evaluate("() => window.__probe") |
| 163 | r = p2.evaluate("() => window.__probe") |
| 164 | cull = min(s["culls"].values()) if s["culls"] else t_shot |
| 165 | rounds.append({"sender": analyse(s["tracks"], cull), "receiver": analyse(r["tracks"], cull)}) |
| 166 | metrics["rounds"] = rounds |
| 167 | # t1182: falling blocks on the receiver's mini of the sender. |
| 168 | p2.evaluate("""() => { |
| 169 | const R = window.__mini = { rows: [] }; |
| 170 | const orig = Online._drawMini; |
| 171 | Online._drawMini = function (canvas, snapshot, planet, shownY) { |
| 172 | if (snapshot && snapshot.blocks) { |
| 173 | for (const b of snapshot.blocks) if (b.color === 3 && b.col === 7) { |
| 174 | const y = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y; |
| 175 | R.rows.push([performance.now(), b.id, y, b.state]); |
| 176 | } |
| 177 | } |
| 178 | return orig.apply(this, arguments); |
| 179 | }; |
| 180 | }""") |
| 181 | p1.evaluate("""() => { |
| 182 | const b = app.core.createBlock(7, 12.6, 3, 'falling'); |
| 183 | b.vy = -app.planet.fallSpeed; |
| 184 | }""") |
| 185 | p2.wait_for_timeout(1400) |
| 186 | p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-mini-falling.png")) |
| 187 | p2.wait_for_timeout(2600) |
| 188 | rows = p2.evaluate("() => window.__mini.rows") |
| 189 | fall_speed = p1.evaluate("() => app.planet.fallSpeed") |
| 190 | steps = [] |
| 191 | falling = [r for r in rows if r[3] == 'falling'] |
| 192 | for a_, b_ in zip(falling, falling[1:]): |
| 193 | if a_[1] == b_[1]: |
| 194 | steps.append(round(a_[2] - b_[2], 4)) |
| 195 | # Only judge motion until the block reaches its resting spot |
| 196 | # (prediction stops on top of the stack, it never locks). |
| 197 | last = max([i for i, s in enumerate(steps) if abs(s) > 1e-6] or [0]) |
| 198 | steps = steps[:last + 1] |
| 199 | moving = [s for s in steps if abs(s) > 1e-6] |
| 200 | metrics["mini"] = { |
| 201 | "frames_falling": len(falling), |
| 202 | "frames_moving": len(moving), |
| 203 | "share_moving": round(len(moving) / max(1, len(steps)), 3), |
| 204 | "max_step_cells": max([abs(s) for s in steps] or [0]), |
| 205 | "fall_speed": fall_speed, |
| 206 | # A jump: > 0.5 cell in one frame AND far faster than the |
| 207 | # real fall (long frames from renderer stalls are not jumps). |
| 208 | "jumps_over_half_cell": sum(1 for a_, b_ in zip(falling, falling[1:]) |
| 209 | if a_[1] == b_[1] and abs(a_[2] - b_[2]) > 0.5 |
| 210 | and abs(a_[2] - b_[2]) / max(1e-3, (b_[0] - a_[0]) / 1000) > 2.5 * fall_speed), |
| 211 | "upward_steps": sum(1 for s in steps if s < -1e-6), |
| 212 | "landed_seen": any(r[3] != 'falling' for r in rows), |
| 213 | "big_steps": [[round(a_[0]-falling[0][0]), round(b_[0]-a_[0]), round(a_[2],3), round(b_[2],3)] for a_, b_ in zip(falling, falling[1:]) if a_[1]==b_[1] and abs(a_[2]-b_[2])>0.3], |
| 214 | "series": [[round(r[0]-falling[0][0]), round(r[2],3)] for r in falling][::6] if falling else [], |
| 215 | } |
| 216 | metrics["errors"] = errs |
| 217 | b.close() |
| 218 | finally: |
| 219 | proc.terminate() |
| 220 | # Summaries |
| 221 | # Own outgoing shots leave the top of the sender's main field; flights |
| 222 | # that start low on the screen are incoming garbage from the opponent. |
| 223 | sf = [f for r in metrics["rounds"] for f in r["sender"] if f["start"][1] < 400] |
| 224 | rf = [f for r in metrics["rounds"] for f in r["receiver"]] |
| 225 | summ = { |
| 226 | "tag": TAG, |
| 227 | "sender_flights": len(sf), |
| 228 | "sender_first_ms": [f["first_ms"] for f in sf], |
| 229 | "sender_max_jump_px": max([f["max_jump_px"] for f in sf] or [0]), |
| 230 | "receiver_flights": len(rf), |
| 231 | "receiver_first_ms": [f["first_ms"] for f in rf], |
| 232 | "receiver_max_jump_px": max([f["max_jump_px"] for f in rf] or [0]), |
| 233 | "receiver_starts": [f["start"] for f in rf][:6], |
| 234 | "sender_max_kink_px": max([f["max_kink_px"] for f in sf] or [0]), |
| 235 | "receiver_max_kink_px": max([f["max_kink_px"] for f in rf] or [0]), |
| 236 | "sender_first_ms_median": sorted(f["first_ms"] for f in sf if f["first_ms"] >= 0)[len(sf) // 2] if sf else None, |
| 237 | "receiver_first_ms_median": sorted(f["first_ms"] for f in rf if f["first_ms"] >= 0)[len(rf) // 2] if rf else None, |
| 238 | "errors": metrics["errors"], |
| 239 | "mini": metrics.get("mini"), |
| 240 | } |
| 241 | print(json.dumps(summ, indent=1)) |
| 242 | Path(f"/workspace/meteors-shots/t1181-{TAG}-metrics.json").write_text(json.dumps({"summary": summ, **metrics}, indent=1)) |
| 243 | return summ |
| 244 | |
| 245 | |
| 246 | if __name__ == "__main__": |
| 247 | s = main() |
| 248 | if TAG == "after": |
| 249 | check(s["sender_flights"] >= 12, f"sender drew a flight for every shot ({s['sender_flights']})") |
| 250 | check(max(s["sender_first_ms"] or [9999]) <= 120, f"sender flight starts within ~1-2 frames of the cull (max {max(s['sender_first_ms'] or [0])} ms)") |
| 251 | check(s["receiver_flights"] >= 12, f"receiver drew the opponent's flights ({s['receiver_flights']})") |
| 252 | check(not s["errors"], f"no page errors {s['errors'][:2]}") |
| 253 | m = s["mini"] or {} |
| 254 | check(m.get("share_moving", 0) > 0.8, f"mini: falling block moves on most frames ({m.get('share_moving')})") |
| 255 | check(m.get("jumps_over_half_cell", 99) == 0, f"mini: no jumps > 0.5 cell ({m.get('jumps_over_half_cell')})") |
| 256 | check(m.get("upward_steps", 99) == 0, f"mini: never moves up ({m.get('upward_steps')})") |
| 257 | sys.exit(1 if FAILURES else 0) |
projects-timfalken-com meteors