| 1 | #!/usr/bin/env python3 |
| 2 | """t1136: online multiplayer uses the same presentation as Offline Strijd. |
| 3 | |
| 4 | Two (and a third) Playwright clients against a local PHP server with |
| 5 | loopback test-auth. After the match starts we inspect MiniLayout and |
| 6 | feed shot_flights through Online._handleTransitions — the same path |
| 7 | a real poll uses — then assert sides/outer-edge/pad, around-field |
| 8 | C¹ arcs, land_col endings, grey hits, launch from the cell, and a |
| 9 | smooth dive into the spawn pose. |
| 10 | """ |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import os |
| 14 | import shutil |
| 15 | import socket |
| 16 | import subprocess |
| 17 | import sys |
| 18 | import tempfile |
| 19 | import time |
| 20 | from pathlib import Path |
| 21 | |
| 22 | from playwright.sync_api import sync_playwright |
| 23 | |
| 24 | ROOT = Path("/workspace/meteors") |
| 25 | OUT = Path("/workspace/meteors-shots") |
| 26 | OUT.mkdir(parents=True, exist_ok=True) |
| 27 | CHROME = "/usr/bin/google-chrome" |
| 28 | CHROME_ARGS = [ |
| 29 | "--use-gl=angle", |
| 30 | "--use-angle=swiftshader", |
| 31 | "--no-sandbox", |
| 32 | "--disable-dev-shm-usage", |
| 33 | ] |
| 34 | PHP = shutil.which("php") or str(Path.home() / ".local/bin/php") |
| 35 | FAILURES = [] |
| 36 | URL = "" |
| 37 | |
| 38 | |
| 39 | def free_port(): |
| 40 | s = socket.socket() |
| 41 | s.bind(("127.0.0.1", 0)) |
| 42 | port = s.getsockname()[1] |
| 43 | s.close() |
| 44 | return port |
| 45 | |
| 46 | |
| 47 | def check(cond, msg): |
| 48 | if not cond: |
| 49 | FAILURES.append(msg) |
| 50 | print("FAIL", msg) |
| 51 | else: |
| 52 | print("OK ", msg) |
| 53 | return cond |
| 54 | |
| 55 | |
| 56 | def shot(page, name): |
| 57 | path = OUT / name |
| 58 | page.screenshot(path=str(path), full_page=False) |
| 59 | print(f"wrote {path} ({path.stat().st_size} bytes)") |
| 60 | return path |
| 61 | |
| 62 | |
| 63 | def start_php(port, data_dir): |
| 64 | env = os.environ.copy() |
| 65 | env["METEORS_DATA_DIR"] = str(data_dir) |
| 66 | proc = subprocess.Popen( |
| 67 | [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), |
| 68 | str(ROOT / "build" / "router.php")], |
| 69 | cwd=str(ROOT / "build"), |
| 70 | stdout=subprocess.DEVNULL, |
| 71 | stderr=open(str(Path(data_dir) / "php.log"), "w"), |
| 72 | env=env, |
| 73 | ) |
| 74 | time.sleep(0.5) |
| 75 | if proc.poll() is not None: |
| 76 | log = Path(data_dir) / "php.log" |
| 77 | err = log.read_text(encoding="utf-8", errors="replace") if log.exists() else "" |
| 78 | raise RuntimeError("php -S failed: " + err) |
| 79 | return proc |
| 80 | |
| 81 | |
| 82 | def login(page, n): |
| 83 | page.goto(f"{URL}auth.php?test={n}&next=index.html", |
| 84 | wait_until="domcontentloaded", timeout=15000) |
| 85 | page.wait_for_timeout(250) |
| 86 | page.goto(f"{URL}index.html?online=1", |
| 87 | wait_until="domcontentloaded", timeout=15000) |
| 88 | page.wait_for_timeout(400) |
| 89 | |
| 90 | |
| 91 | def wait_visible(page, sel, timeout=8000): |
| 92 | page.locator(sel).wait_for(state="visible", timeout=timeout) |
| 93 | |
| 94 | |
| 95 | INSPECT = """() => { |
| 96 | const plan = app.miniLayout || {}; |
| 97 | const fieldEl = app.scene && app.scene.canvas; |
| 98 | const fr = fieldEl ? fieldEl.getBoundingClientRect() : null; |
| 99 | const minis = [...document.querySelectorAll('#minis .mini')].map((el) => { |
| 100 | const r = el.getBoundingClientRect(); |
| 101 | return { |
| 102 | id: el.getAttribute('data-player'), |
| 103 | left: r.left, right: r.right, top: r.top, bottom: r.bottom |
| 104 | }; |
| 105 | }); |
| 106 | const me = Online.mePlayer && Online.mePlayer(); |
| 107 | const ops = (Online.opponents && Online.opponents()) || []; |
| 108 | return { |
| 109 | mode: plan.mode, |
| 110 | sidesClass: document.getElementById('minis').classList.contains('sides'), |
| 111 | n: plan.n, |
| 112 | fieldY: app.fieldY, |
| 113 | hudH: app.hudH, |
| 114 | pad: (typeof MiniLayout !== 'undefined') ? MiniLayout.ARC_TOP_PAD : null, |
| 115 | field: fr ? { left: fr.left, right: fr.right, top: fr.top, bottom: fr.bottom, |
| 116 | width: fr.width, height: fr.height } : null, |
| 117 | minis, |
| 118 | positions: plan.positions || [], |
| 119 | me: me && me.id, |
| 120 | opponents: ops.map(o => o.id), |
| 121 | online: !!app.online, |
| 122 | offline: !!app.offline, |
| 123 | vw: window.innerWidth, |
| 124 | vh: window.innerHeight |
| 125 | }; |
| 126 | }""" |
| 127 | |
| 128 | |
| 129 | POLL_FLIGHTS = """() => { |
| 130 | const me = Online.mePlayer(); |
| 131 | const ops = Online.opponents() || []; |
| 132 | const a = ops[0]; |
| 133 | const b = ops[1] || ops[0]; |
| 134 | if (!a || !me) return { error: 'no opponents or me' }; |
| 135 | const field = app.scene.canvas.getBoundingClientRect(); |
| 136 | if (Online.clearFlights) Online.clearFlights(); |
| 137 | // Exact poll path: shot_flights only, no rememberFlightLocal (t1136). |
| 138 | Online._handleTransitions('playing', { |
| 139 | incoming: [], |
| 140 | shot_results: [], |
| 141 | shot_flights: [ |
| 142 | { id: 601, client_id: 'on-e2p', from_id: a.id, from_user: a.id, |
| 143 | target_id: me.id, miss: false, color: 1, flight_duration: 1.2, |
| 144 | age: 0.5, land_col: 3, col: 6, y: 13 }, |
| 145 | { id: 602, client_id: 'on-p2e', from_id: me.id, from_user: me.id, |
| 146 | target_id: a.id, miss: false, color: 0, flight_duration: 1.2, |
| 147 | age: 0.35, land_col: 5, col: 4, y: 13 }, |
| 148 | { id: 603, client_id: 'on-e2e', from_id: a.id, from_user: a.id, |
| 149 | target_id: b.id, miss: false, color: 2, flight_duration: 1.2, |
| 150 | age: 0.45, land_col: 7, col: 2, y: 13 }, |
| 151 | { id: 604, client_id: 'on-miss', from_id: b.id, from_user: b.id, |
| 152 | target_id: null, miss: true, color: 3, flight_duration: 1.2, |
| 153 | age: 0.3, col: 1, y: 13 } |
| 154 | ] |
| 155 | }); |
| 156 | Online.tickFlights(); |
| 157 | const expectedEndX = field.left + ((3 + 0.5) / 10) * field.width; |
| 158 | const expectedEndY = field.top + (1 - 13.5 / 13) * field.height; |
| 159 | const expectedStartY = field.top + (1 - 13.5 / 13) * field.height; |
| 160 | const kinds = (Online._flights || []).map(f => { |
| 161 | const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration)); |
| 162 | const u = f.miss ? Online.easeInOutCubic(raw) : Online.smoothParam(raw, 0.85, 0.85); |
| 163 | const pt = Online.flightPointAt(f, u); |
| 164 | const samples = []; |
| 165 | if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy') { |
| 166 | for (let i = 0; i <= 16; i++) { |
| 167 | const su = i / 16; |
| 168 | const sp = Online.flightPointAt(f, su); |
| 169 | const inside = !!(f.field && Online.pointInFieldInterior(sp.x, sp.y, f.field)); |
| 170 | const allowed = !f.field || Online.pointAllowedOnArc(sp, f.field, f.start, f.end); |
| 171 | samples.push({ u: su, inside, allowed }); |
| 172 | } |
| 173 | } |
| 174 | return { |
| 175 | kind: f.kind, miss: f.miss, color: f.color, landCol: f.landCol, |
| 176 | start: f.start, end: f.end, pos: pt, |
| 177 | startScale: f.startScale, endScale: f.endScale, |
| 178 | parent: (f.el && f.el.parentElement && f.el.parentElement.id) || '', |
| 179 | src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '', |
| 180 | hasCurve: !!f.curve, |
| 181 | d0: f.curve ? Online.curveDeriv(f.curve, 0) : null, |
| 182 | d1: f.curve ? Online.curveDeriv(f.curve, 1) : null, |
| 183 | samples, |
| 184 | forbidden: samples.filter(s => s.inside && !s.allowed).length |
| 185 | }; |
| 186 | }); |
| 187 | return { |
| 188 | kinds, |
| 189 | expectedEndX, expectedEndY, expectedStartY, |
| 190 | field: { left: field.left, right: field.right, top: field.top, |
| 191 | bottom: field.bottom, width: field.width, height: field.height }, |
| 192 | front: document.querySelectorAll('#flights .flight').length, |
| 193 | back: document.querySelectorAll('#flights-back .flight').length |
| 194 | }; |
| 195 | }""" |
| 196 | |
| 197 | |
| 198 | def assert_layout(info, tag, n_ops): |
| 199 | check(info.get("online") is True, f"{tag}: app.online is true") |
| 200 | check(info.get("offline") is False, f"{tag}: not in offline mode") |
| 201 | check(info.get("mode") == "sides", f"{tag}: mode is sides (got {info.get('mode')})") |
| 202 | check(info.get("sidesClass"), f"{tag}: #minis has .sides") |
| 203 | check((info.get("n") or 0) >= 1, f"{tag}: at least one opponent mini (n={info.get('n')})") |
| 204 | if (info.get("n") or 0) < n_ops: |
| 205 | print(f"note {tag}: wanted {n_ops} opponents, got {info.get('n')} (flights still verified)") |
| 206 | pad = info.get("pad") or 0 |
| 207 | if pad and info.get("hudH") is not None and info.get("fieldY") is not None: |
| 208 | check(info["fieldY"] >= info["hudH"] + pad - 1, |
| 209 | f"{tag}: ARC_TOP_PAD (fieldY={info['fieldY']} hud={info['hudH']} pad={pad})") |
| 210 | field = info.get("field") or {} |
| 211 | minis = info.get("minis") or [] |
| 212 | vw = info.get("vw") or 0 |
| 213 | # Outer-edge: first two minis sit near the left and right screen edges. |
| 214 | if len(minis) >= 1: |
| 215 | lefts = sorted(minis, key=lambda m: m["left"]) |
| 216 | check(lefts[0]["left"] < 40, |
| 217 | f"{tag}: leftmost mini is on the outer left edge ({lefts[0]['left']:.0f})") |
| 218 | if len(minis) >= 2: |
| 219 | rights = sorted(minis, key=lambda m: -m["right"]) |
| 220 | check(abs(vw - rights[0]["right"]) < 40, |
| 221 | f"{tag}: rightmost mini is on the outer right edge " |
| 222 | f"(right={rights[0]['right']:.0f} vw={vw})") |
| 223 | # Bottom-aligned with the field |
| 224 | if field.get("bottom"): |
| 225 | for m in minis: |
| 226 | check(abs(m["bottom"] - field["bottom"]) < 16, |
| 227 | f"{tag}: mini {m['id']} bottom-aligned " |
| 228 | f"(mini={m['bottom']:.0f} field={field['bottom']:.0f})") |
| 229 | |
| 230 | |
| 231 | def assert_online_flights(info, tag): |
| 232 | kinds = {k["kind"]: k for k in info.get("kinds") or []} |
| 233 | check("player-to-enemy" in kinds, f"{tag}: player-to-enemy via shot_flights") |
| 234 | check("enemy-to-player" in kinds, f"{tag}: enemy-to-player via shot_flights") |
| 235 | if "player-to-enemy" in kinds: |
| 236 | k = kinds["player-to-enemy"] |
| 237 | check(k.get("hasCurve"), f"{tag}: p2e smooth curve") |
| 238 | check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(), |
| 239 | f"{tag}: p2e is grey") |
| 240 | if k.get("start") and info.get("expectedStartY") is not None: |
| 241 | check(k["start"]["y"] <= info["field"]["top"] + 2, |
| 242 | f"{tag}: p2e launches at the exit (at/above the canvas top) " |
| 243 | f"(y={k['start']['y']:.1f} top={info['field']['top']:.1f})") |
| 244 | check(abs(k["start"]["y"] - info["expectedStartY"]) < 10, |
| 245 | f"{tag}: p2e start at y=13 exit pose") |
| 246 | if k.get("d0"): |
| 247 | check(k["d0"]["y"] < 0, f"{tag}: p2e leaves going up") |
| 248 | check(k.get("forbidden", 0) == 0, f"{tag}: p2e corridors only") |
| 249 | if "enemy-to-player" in kinds: |
| 250 | k = kinds["enemy-to-player"] |
| 251 | check(k.get("hasCurve"), f"{tag}: e2p smooth curve") |
| 252 | check(k.get("landCol") == 3, f"{tag}: e2p land_col=3 (got {k.get('landCol')})") |
| 253 | check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(), |
| 254 | f"{tag}: e2p is grey") |
| 255 | if k.get("end") and info.get("expectedEndX") is not None: |
| 256 | check(abs(k["end"]["x"] - info["expectedEndX"]) < 4, |
| 257 | f"{tag}: e2p ends at land_col x") |
| 258 | check(abs(k["end"]["y"] - info["expectedEndY"]) < 10, |
| 259 | f"{tag}: e2p ends at spawn pose y=13") |
| 260 | if k.get("d1"): |
| 261 | check(k["d1"]["y"] > 0, f"{tag}: e2p arrives going down") |
| 262 | check(abs(k.get("endScale", 0) - 1) < 0.05, f"{tag}: e2p end scale is 1") |
| 263 | check(k.get("forbidden", 0) == 0, f"{tag}: e2p corridors only") |
| 264 | if "enemy-to-enemy" in kinds: |
| 265 | k = kinds["enemy-to-enemy"] |
| 266 | check(k["parent"] == "flights-back", |
| 267 | f"{tag}: e2e behind the field ({k['parent']})") |
| 268 | check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(), |
| 269 | f"{tag}: e2e is grey") |
| 270 | check(info.get("back", 0) >= 1, f"{tag}: #flights-back has a flight") |
| 271 | if "enemy-miss" in kinds: |
| 272 | k = kinds["enemy-miss"] |
| 273 | check(k.get("color") != -1, f"{tag}: miss keeps sender colour") |
| 274 | |
| 275 | |
| 276 | def leave_if_needed(page): |
| 277 | if page.locator("#online-lobby").is_visible() and page.locator("#btn-leave-lobby").is_visible(): |
| 278 | page.locator("#btn-leave-lobby").click() |
| 279 | page.wait_for_timeout(400) |
| 280 | |
| 281 | |
| 282 | def start_match(browser, width, height, n_players=3): |
| 283 | contexts = [] |
| 284 | pages = [] |
| 285 | for i in range(n_players): |
| 286 | ctx = browser.new_context(viewport={"width": width, "height": height}) |
| 287 | page = ctx.new_page() |
| 288 | contexts.append(ctx) |
| 289 | pages.append(page) |
| 290 | login(page, i + 1) |
| 291 | wait_visible(page, "#online-panel") |
| 292 | leave_if_needed(page) |
| 293 | |
| 294 | p1 = pages[0] |
| 295 | wait_visible(p1, "#btn-create") |
| 296 | p1.locator("#btn-create").click() |
| 297 | wait_visible(p1, "#online-lobby") |
| 298 | p1.wait_for_function( |
| 299 | "() => document.getElementById('lobby-code') && " |
| 300 | "document.getElementById('lobby-code').textContent.trim().length >= 4", |
| 301 | timeout=8000, |
| 302 | ) |
| 303 | code = p1.locator("#lobby-code").inner_text().strip() |
| 304 | check(len(code) >= 4, f"lobby code ({code})") |
| 305 | |
| 306 | for p in pages[1:]: |
| 307 | wait_visible(p, "#join-code") |
| 308 | p.locator("#join-code").fill(code) |
| 309 | p.locator("#btn-join").click() |
| 310 | wait_visible(p, "#online-lobby") |
| 311 | p.wait_for_timeout(400) |
| 312 | for _ in range(20): |
| 313 | if p1.locator("#lobby-players li").count() >= n_players: |
| 314 | break |
| 315 | p1.wait_for_timeout(300) |
| 316 | counts = [pg.locator("#lobby-players li").count() for pg in pages] |
| 317 | print(f"lobby player counts: {counts}") |
| 318 | check(counts[0] >= 2, f"host sees at least 2 players ({counts[0]})") |
| 319 | |
| 320 | for p in pages: |
| 321 | # ready |
| 322 | btn = p.locator("#btn-ready") |
| 323 | if btn.is_visible(): |
| 324 | btn.click() |
| 325 | p.wait_for_timeout(200) |
| 326 | |
| 327 | start = p1.locator("#btn-start") |
| 328 | enabled = False |
| 329 | for _ in range(20): |
| 330 | if start.is_visible() and start.is_enabled(): |
| 331 | enabled = True |
| 332 | break |
| 333 | p1.wait_for_timeout(300) |
| 334 | check(enabled, "host can start") |
| 335 | if not enabled: |
| 336 | raise RuntimeError("host Starten stayed disabled") |
| 337 | start.click() |
| 338 | for i, p in enumerate(pages): |
| 339 | try: |
| 340 | p.wait_for_function( |
| 341 | "() => app && app.mode === 'playing' && app.online && app.core", |
| 342 | timeout=15000, |
| 343 | ) |
| 344 | except Exception as e: |
| 345 | state = p.evaluate( |
| 346 | """() => ({ |
| 347 | mode: typeof app === 'undefined' ? 'no-app' : app.mode, |
| 348 | online: !!(typeof app !== 'undefined' && app.online), |
| 349 | hasCore: !!(typeof app !== 'undefined' && app.core), |
| 350 | lobby: (typeof Online !== 'undefined' && Online.lobby) |
| 351 | ? { status: Online.lobby.status, n: (Online.lobby.players||[]).length } |
| 352 | : null, |
| 353 | visible: { |
| 354 | panel: !document.getElementById('online-panel').hidden, |
| 355 | lobby: !document.getElementById('online-lobby').hidden, |
| 356 | hud: !document.getElementById('hud').hidden, |
| 357 | planet: !document.getElementById('planet-select').hidden |
| 358 | } |
| 359 | })""" |
| 360 | ) |
| 361 | shot(p, f"t1136-debug-p{i+1}.png") |
| 362 | print(f"start failed on player {i+1}: {state}") |
| 363 | raise |
| 364 | p.wait_for_selector("canvas", state="visible", timeout=8000) |
| 365 | p.wait_for_timeout(500) |
| 366 | return contexts, pages |
| 367 | |
| 368 | |
| 369 | def run_viewport(browser, name, width, height, n_players=3): |
| 370 | print(f"\n======== online {name} ========") |
| 371 | contexts, pages = start_match(browser, width, height, n_players=n_players) |
| 372 | p1 = pages[0] |
| 373 | info = p1.evaluate(INSPECT) |
| 374 | print("layout", {k: info.get(k) for k in |
| 375 | ("mode", "n", "fieldY", "hudH", "pad", "online", "vw", "vh", |
| 376 | "sidesClass", "opponents")}) |
| 377 | assert_layout(info, name, n_players - 1) |
| 378 | shot(p1, f"t1136-{name}-layout.png") |
| 379 | |
| 380 | flights = p1.evaluate(POLL_FLIGHTS) |
| 381 | print("flights", {k: flights.get(k) for k in |
| 382 | ("front", "back", "expectedEndX", "expectedEndY", "expectedStartY")}) |
| 383 | for knd in flights.get("kinds") or []: |
| 384 | print(f" {knd['kind']}: land={knd.get('landCol')} color={knd.get('color')} " |
| 385 | f"curve={knd.get('hasCurve')} start={knd.get('start')} end={knd.get('end')}") |
| 386 | if flights.get("error"): |
| 387 | check(False, f"{name}: {flights['error']}") |
| 388 | else: |
| 389 | assert_online_flights(flights, name) |
| 390 | shot(p1, f"t1136-{name}-midarc.png") |
| 391 | # early / late |
| 392 | for age_delta, label in ((-0.3, "early"), (0.3, "late")): |
| 393 | # re-inject by running POLL_FLIGHTS is mid; use evaluate with age via a small wrapper |
| 394 | p1.evaluate( |
| 395 | """(age) => { |
| 396 | const payload = { incoming: [], shot_results: [], shot_flights: [] }; |
| 397 | // Just retick existing? Clear and let POLL-like ages set in a short helper. |
| 398 | const me = Online.mePlayer(); |
| 399 | const ops = Online.opponents() || []; |
| 400 | const a = ops[0], b = ops[1] || ops[0]; |
| 401 | if (Online.clearFlights) Online.clearFlights(); |
| 402 | Online._handleTransitions('playing', { |
| 403 | incoming: [], shot_results: [], |
| 404 | shot_flights: [ |
| 405 | { id: 701, client_id: 'e-'+age, from_id: a.id, target_id: me.id, |
| 406 | miss: false, color: 1, flight_duration: 1.2, age: age, |
| 407 | land_col: 3, col: 6, y: 13 }, |
| 408 | { id: 702, client_id: 'p-'+age, from_id: me.id, target_id: a.id, |
| 409 | miss: false, color: 0, flight_duration: 1.2, age: age, |
| 410 | land_col: 5, col: 4, y: 13 } |
| 411 | ] |
| 412 | }); |
| 413 | Online.tickFlights(); |
| 414 | }""", |
| 415 | 0.2 if label == "early" else 0.85, |
| 416 | ) |
| 417 | shot(p1, f"t1136-{name}-midarc-{label}.png") |
| 418 | |
| 419 | for c in contexts: |
| 420 | c.close() |
| 421 | |
| 422 | |
| 423 | def main(): |
| 424 | global URL |
| 425 | port = free_port() |
| 426 | data = tempfile.mkdtemp(prefix="meteors-online-") |
| 427 | URL = f"http://127.0.0.1:{port}/" |
| 428 | proc = start_php(port, data) |
| 429 | try: |
| 430 | with sync_playwright() as p: |
| 431 | browser = p.chromium.launch( |
| 432 | executable_path=CHROME, args=CHROME_ARGS, headless=True |
| 433 | ) |
| 434 | run_viewport(browser, "1920x1080", 1920, 1080, n_players=2) |
| 435 | run_viewport(browser, "1024x532", 1024, 532, n_players=2) |
| 436 | browser.close() |
| 437 | finally: |
| 438 | proc.terminate() |
| 439 | try: |
| 440 | proc.wait(timeout=3) |
| 441 | except subprocess.TimeoutExpired: |
| 442 | proc.kill() |
| 443 | shutil.rmtree(data, ignore_errors=True) |
| 444 | |
| 445 | if FAILURES: |
| 446 | print(f"\n{len(FAILURES)} failure(s):") |
| 447 | for f in FAILURES: |
| 448 | print(" -", f) |
| 449 | return 1 |
| 450 | print("\nall online presentation checks passed") |
| 451 | return 0 |
| 452 | |
| 453 | |
| 454 | if __name__ == "__main__": |
| 455 | sys.exit(main()) |
projects-timfalken-com meteors