BlueGit

projects-timfalken-com meteors

Files

meteors / test / minis-flights-playwright.py

minis-flights-playwright.py

minis-flights-playwright.py 16.1 KiB Download Raw
1#!/usr/bin/env python3
2"""Layout and flight-arc visuals for t1125 (wide / narrow / mobile)."""
3from __future__ import annotations
4
5import socket
6import subprocess
7import sys
8import time
9from pathlib import Path
10
11from playwright.sync_api import sync_playwright
12
13ROOT = Path("/workspace/meteors")
14OUT = Path("/workspace/meteors-shots")
15OUT.mkdir(parents=True, exist_ok=True)
16CHROME = "/usr/bin/google-chrome"
17CHROME_ARGS = [
18 "--use-gl=angle",
19 "--use-angle=swiftshader",
20 "--no-sandbox",
21 "--disable-dev-shm-usage",
22 "--disable-gpu-sandbox",
23]
24FAILURES = []
25
26
27def free_port():
28 s = socket.socket()
29 s.bind(("127.0.0.1", 0))
30 port = s.getsockname()[1]
31 s.close()
32 return port
33
34
35def check(cond, msg):
36 if not cond:
37 FAILURES.append(msg)
38 print("FAIL", msg)
39 else:
40 print("OK ", msg)
41 return cond
42
43
44def shot(page, name):
45 path = OUT / name
46 page.screenshot(path=str(path), full_page=False)
47 print(f"wrote {path} ({path.stat().st_size} bytes)")
48 return path
49
50
51def start_http(port):
52 proc = subprocess.Popen(
53 ["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1",
54 "--directory", str(ROOT / "build")],
55 stdout=subprocess.DEVNULL,
56 stderr=subprocess.DEVNULL,
57 )
58 time.sleep(0.35)
59 if proc.poll() is not None:
60 raise RuntimeError("http.server failed to start")
61 return proc
62
63
64def open_offline(page, url, round_n=1):
65 page.goto(url, wait_until="domcontentloaded", timeout=15000)
66 page.wait_for_timeout(400)
67 page.locator("#btn-offline").click()
68 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
69 page.locator("#btn-planet-go").click()
70 page.wait_for_function(
71 "() => app && app.mode === 'playing' && app.offline && app.battle && app.core",
72 timeout=10000,
73 )
74 if round_n != 1:
75 page.evaluate(
76 """(round) => {
77 teardownPlay();
78 startPlay({ planet: app.planet, offline: true, round: round });
79 }""",
80 round_n,
81 )
82 page.wait_for_function(
83 "() => app && app.mode === 'playing' && app.battle && app.miniLayout",
84 timeout=8000,
85 )
86 page.wait_for_timeout(250)
87
88
89LAYOUT_INFO = """() => {
90 const plan = app.miniLayout || {};
91 const fieldEl = app.scene && app.scene.canvas;
92 const fr = fieldEl ? fieldEl.getBoundingClientRect() : null;
93 const minis = [...document.querySelectorAll('#minis .mini')].map((el) => {
94 const r = el.getBoundingClientRect();
95 const c = el.querySelector('canvas');
96 const cr = c ? c.getBoundingClientRect() : r;
97 return {
98 id: el.getAttribute('data-player'),
99 left: r.left, right: r.right, top: r.top, bottom: r.bottom,
100 cx: cr.left + cr.width / 2,
101 cy: cr.top + cr.height / 2
102 };
103 });
104 return {
105 mode: plan.mode,
106 sidesClass: document.getElementById('minis').classList.contains('sides'),
107 n: plan.n,
108 field: fr ? { left: fr.left, right: fr.right, top: fr.top, bottom: fr.bottom,
109 x: app.fieldX, y: app.fieldY, w: app.fieldW, h: app.fieldH } : null,
110 positions: plan.positions || [],
111 minis,
112 tile: app.tile,
113 vw: window.innerWidth,
114 vh: window.innerHeight
115 };
116}"""
117
118
119
120INJECT_FLIGHTS = """(age) => {
121 if (age == null) age = 0.55;
122 const plan = app.miniLayout;
123 const field = app.scene.canvas.getBoundingClientRect();
124 function anchor(id, inner) {
125 const el = document.querySelector('#minis .mini[data-player="' + id + '"] canvas');
126 if (!el) return { x: 80, y: 80 };
127 const r = el.getBoundingClientRect();
128 if (plan && plan.mode === 'sides') {
129 const mid = field.left + field.width / 2;
130 const left = (r.left + r.width / 2) < mid;
131 if (inner) return { x: left ? r.right : r.left, y: r.top + r.height / 2 };
132 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
133 }
134 return { x: r.left + r.width / 2, y: inner ? r.bottom : r.top };
135 }
136 const bots = (app.battle.bots || []).map(b => b.id);
137 const a = bots[0] || 'bot-1';
138 const b = bots[1] || bots[0] || 'bot-2';
139 const landCol = 3;
140 const pStart = {
141 x: field.left + ((4 + 0.5) / 10) * field.width,
142 y: field.top + 4
143 };
144 if (typeof Online.clearFlights === 'function') Online.clearFlights();
145 const flights = [
146 { id: 'vis-p2e', client_id: 'vis-p2e', from_id: 'player', target_id: a, miss: false, color: 0, flight_duration: 1.2, age: age, land_col: landCol },
147 { id: 'vis-e2p', client_id: 'vis-e2p', from_id: a, target_id: 'player', miss: false, color: 1, flight_duration: 1.2, age: age, land_col: landCol },
148 { id: 'vis-e2e', client_id: 'vis-e2e', from_id: a, target_id: b, miss: false, color: 2, flight_duration: 1.2, age: age, land_col: 7 },
149 { id: 'vis-emiss', client_id: 'vis-emiss', from_id: b, target_id: null, miss: true, color: 3, flight_duration: 1.2, age: Math.min(age, 0.45) }
150 ];
151 const aOut = anchor(a, true);
152 const bOut = anchor(b, true);
153 const locals = {
154 'vis-p2e': { from_id: 'player', color: 0, startX: pStart.x, startY: pStart.y, col: 4, land_col: landCol },
155 'vis-e2p': { from_id: a, color: 1, startX: aOut.x, startY: aOut.y, land_col: landCol },
156 'vis-e2e': { from_id: a, color: 2, startX: aOut.x, startY: aOut.y, land_col: 7 },
157 'vis-emiss': { from_id: b, color: 3, startX: bOut.x, startY: bOut.y }
158 };
159 Online.spawnFlights(flights, locals);
160 Online.tickFlights();
161 const front = [...document.querySelectorAll('#flights .flight')].map(el => ({
162 src: el.getAttribute('src') || el.src,
163 transform: el.style.transform,
164 parent: 'front'
165 }));
166 const back = [...document.querySelectorAll('#flights-back .flight')].map(el => ({
167 src: el.getAttribute('src') || el.src,
168 transform: el.style.transform,
169 parent: 'back'
170 }));
171 const kinds = (Online._flights || []).map(f => {
172 const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));
173 const u = Online.easeInOutCubic(raw);
174 let pt;
175 if (f.waypoints && f.waypoints.length > 2)
176 { pt = Online.pointOnPath(f.waypoints, u); }
177 else if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')
178 { pt = Online.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45); }
179 else
180 { pt = Online.arcPoint(f.start, f.end, u, f.height || 80); }
181 const samples = [];
182 if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')
183 {
184 for (let i = 0; i <= 16; i++)
185 {
186 const su = i / 16;
187 let sp;
188 if (f.waypoints && f.waypoints.length > 2)
189 { sp = Online.pointOnPath(f.waypoints, su); }
190 else
191 { sp = Online.aroundFieldPoint(f.start, f.end, su, f.field, (f.height || 80) * 0.45); }
192 samples.push({
193 u: su, x: sp.x, y: sp.y,
194 inside: Online.pointInFieldInterior(sp.x, sp.y, f.field)
195 });
196 }
197 }
198 return {
199 kind: f.kind, miss: f.miss,
200 startScale: f.startScale, endScale: f.endScale,
201 parent: (f.el && f.el.parentElement && f.el.parentElement.id) || '',
202 src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',
203 color: f.color,
204 landCol: f.landCol,
205 end: f.end,
206 pos: pt,
207 samples: samples,
208 insideNow: f.field ? Online.pointInFieldInterior(pt.x, pt.y, f.field) : false
209 };
210 });
211 const expectedEndX = field.left + ((landCol + 0.5) / 10) * field.width;
212 return {
213 front: front.length,
214 back: back.length,
215 kinds,
216 expectedEndX,
217 field: { left: field.left, right: field.right, top: field.top, bottom: field.bottom },
218 pad: field.top,
219 hudH: app.hudH,
220 mode: plan.mode
221 };
222}"""
223
224
225def assert_sides(info, tag, expect_rows=False):
226 check(info["mode"] == "sides", f"{tag}: mode is sides (got {info['mode']})")
227 check(info["sidesClass"], f"{tag}: #minis has .sides")
228 field = info["field"]
229 minis = info["minis"]
230 check(len(minis) >= 1, f"{tag}: at least one mini ({len(minis)})")
231 if field:
232 # t1129: room above the field for around-the-top arcs
233 gap = field["top"] - 50 # HUD is ~56–80; require a clear pad
234 check(field["top"] >= (info.get("hud") or 70) + 80
235 or field["y"] >= 70 + 80,
236 f"{tag}: wide layout has top padding (field.top={field['top']:.1f}, y={field.get('y')})")
237 if not field or not minis:
238 return
239 for i, m in enumerate(minis):
240 if i % 2 == 0:
241 check(m["right"] <= field["left"] + 2,
242 f"{tag}: mini {i} ({m['id']}) is on the left of the field "
243 f"(right={m['right']:.1f} field.left={field['left']:.1f})")
244 else:
245 check(m["left"] >= field["right"] - 2,
246 f"{tag}: mini {i} ({m['id']}) is on the right of the field "
247 f"(left={m['left']:.1f} field.right={field['right']:.1f})")
248 check(m["bottom"] <= field["bottom"] + 8,
249 f"{tag}: mini {i} does not hang below the field")
250 check(m["top"] >= 50,
251 f"{tag}: mini {i} stays under the HUD (top={m['top']:.1f})")
252 if expect_rows and len(minis) >= 3:
253 check(minis[2]["bottom"] <= minis[0]["top"] + 4,
254 f"{tag}: third mini is stacked above the first "
255 f"(b={minis[2]['bottom']:.1f} vs top={minis[0]['top']:.1f})")
256
257
258def assert_top(info, tag):
259 check(info["mode"] == "top", f"{tag}: mode is top (got {info['mode']})")
260 check(not info["sidesClass"], f"{tag}: #minis is not .sides")
261 field = info["field"]
262 minis = info["minis"]
263 check(len(minis) >= 1, f"{tag}: at least one mini")
264 if not field or not minis:
265 return
266 for i, m in enumerate(minis):
267 check(m["bottom"] <= field["top"] + 12,
268 f"{tag}: mini {i} sits above the field "
269 f"(bottom={m['bottom']:.1f} field.top={field['top']:.1f})")
270
271
272def assert_flights(info, tag, expect_behind=True, expect_around=True):
273 check(info["front"] >= 3, f"{tag}: front flights present ({info['front']})")
274 kinds = {k["kind"]: k for k in info["kinds"]}
275 check("player-to-enemy" in kinds, f"{tag}: player-to-enemy")
276 check("enemy-to-player" in kinds, f"{tag}: enemy-to-player")
277 check("enemy-miss" in kinds, f"{tag}: enemy-miss")
278 if "player-to-enemy" in kinds:
279 k = kinds["player-to-enemy"]
280 check(k["startScale"] > k["endScale"],
281 f"{tag}: player-to-enemy shrinks ({k['startScale']:.2f}→{k['endScale']:.2f})")
282 check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
283 f"{tag}: player-to-enemy is grey (src={k.get('src')} color={k.get('color')})")
284 if "enemy-to-player" in kinds:
285 k = kinds["enemy-to-player"]
286 check(k["endScale"] > k["startScale"],
287 f"{tag}: enemy-to-player grows ({k['startScale']:.2f}→{k['endScale']:.2f})")
288 check(k.get("landCol") == 3,
289 f"{tag}: enemy-to-player landCol is 3 (got {k.get('landCol')})")
290 if k.get("end") and info.get("expectedEndX"):
291 check(abs(k["end"]["x"] - info["expectedEndX"]) < 3,
292 f"{tag}: arc ends at column 3 "
293 f"(end.x={k['end']['x']:.1f} expected={info['expectedEndX']:.1f})")
294 check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
295 f"{tag}: enemy-to-player is grey (src={k.get('src')} color={k.get('color')})")
296 if expect_around and k.get("samples"):
297 inside = [s for s in k["samples"] if s.get("inside")]
298 check(len(inside) == 0,
299 f"{tag}: enemy-to-player path stays outside the field "
300 f"({len(inside)} interior samples {inside[:3]})")
301 check(not k.get("insideNow"),
302 f"{tag}: enemy-to-player mid-arc is not over the field interior")
303 if "player-to-enemy" in kinds and expect_around:
304 k = kinds["player-to-enemy"]
305 inside = [s for s in (k.get("samples") or []) if s.get("inside")]
306 check(len(inside) == 0,
307 f"{tag}: player-to-enemy path stays outside the field "
308 f"({len(inside)} interior samples {inside[:3]})")
309 if "enemy-to-enemy" in kinds:
310 k = kinds["enemy-to-enemy"]
311 check(abs(k["startScale"] - k["endScale"]) < 0.05,
312 f"{tag}: enemy-to-enemy stays small ({k['startScale']:.2f})")
313 check(k["parent"] == "flights-back",
314 f"{tag}: enemy-to-enemy is in #flights-back (got {k['parent']})")
315 if expect_behind:
316 check(info["back"] >= 1, f"{tag}: at least one behind-field flight")
317 check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
318 f"{tag}: enemy-to-enemy is grey (src={k.get('src')} color={k.get('color')})")
319 if "enemy-miss" in kinds:
320 k = kinds["enemy-miss"]
321 check(k["startScale"] < 0.7,
322 f"{tag}: enemy-miss starts small ({k['startScale']:.2f})")
323 check(k["parent"] == "flights",
324 f"{tag}: enemy-miss is in #flights (got {k['parent']})")
325 # Misses keep the sender colour (not forced grey).
326 check(k.get("color") != -1,
327 f"{tag}: enemy-miss keeps the sender colour (color={k.get('color')})")
328
329
330def run_viewport(browser, url, name, width, height, is_mobile, round_n, expect_mode):
331 context = browser.new_context(
332 viewport={"width": width, "height": height},
333 device_scale_factor=1,
334 is_mobile=is_mobile,
335 has_touch=is_mobile,
336 )
337 page = context.new_page()
338 open_offline(page, url, round_n=round_n)
339 page.wait_for_timeout(300)
340 info = page.evaluate(LAYOUT_INFO)
341 print(f"--- {name} layout:", {k: info[k] for k in ('mode', 'n', 'tile', 'vw', 'vh', 'sidesClass')},
342 "fieldY", info.get("field") and info["field"].get("y"),
343 "field.top", info.get("field") and info["field"].get("top"))
344 if expect_mode == "sides":
345 assert_sides(info, name, expect_rows=(round_n >= 12))
346 else:
347 assert_top(info, name)
348 shot(page, f"t1126-{name}-layout.png")
349
350 # Mid-arc (age 0.55 of 1.2 s) — main verification frame
351 flights = page.evaluate(INJECT_FLIGHTS, 0.55)
352 print(f"--- {name} flights:", {k: flights[k] for k in ('front', 'back', 'expectedEndX', 'hudH', 'mode') if k in flights})
353 for knd in flights["kinds"]:
354 print(f" {knd['kind']}: color={knd.get('color')} landCol={knd.get('landCol')} "
355 f"src={knd.get('src')} insideNow={knd.get('insideNow')} "
356 f"end={knd.get('end')} pos={knd.get('pos')}")
357 assert_flights(flights, name)
358 shot(page, f"t1126-{name}-midarc.png")
359
360 # Extra mid-path frames on the wide 2-bot view so the around-route is visible
361 if name == "desktop-wide":
362 for age, label in ((0.25, "early"), (0.85, "late")):
363 page.evaluate(INJECT_FLIGHTS, age)
364 shot(page, f"t1126-{name}-midarc-{label}.png")
365 context.close()
366
367
368def main():
369 port = free_port()
370 http = start_http(port)
371 url = f"http://127.0.0.1:{port}/"
372 try:
373 with sync_playwright() as p:
374 browser = p.chromium.launch(
375 executable_path=CHROME,
376 args=CHROME_ARGS,
377 headless=True,
378 )
379 run_viewport(browser, url, "desktop-wide", 1280, 900, False, 2, "sides")
380 run_viewport(browser, url, "desktop-wide-many", 1400, 900, False, 25, "sides")
381 run_viewport(browser, url, "desktop-narrow", 720, 800, False, 2, "top")
382 run_viewport(browser, url, "mobile", 393, 851, True, 2, "top")
383 browser.close()
384 finally:
385 http.terminate()
386 try:
387 http.wait(timeout=3)
388 except subprocess.TimeoutExpired:
389 http.kill()
390
391 if FAILURES:
392 print(f"\n{len(FAILURES)} failure(s):")
393 for f in FAILURES:
394 print(" -", f)
395 return 1
396 print("\nall minis/flights checks passed")
397 return 0
398
399
400if __name__ == "__main__":
401 sys.exit(main())