forked from rosebudai/OpenRCT2-Web
ralph: story-6 Playwright screenshot skill for OpenRCT2 web
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
5d42bbc51f
commit
0b7ae76261
2 files changed
+215
-117
No files matched your search
@@ -1,133 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Take a screenshot of the OpenRCT2 web game using Playwright.
|
||||
"""Take a screenshot of OpenRCT2 running in headless Chromium.
|
||||
|
||||
Starts a local COOP/COEP server, launches headless Chromium, waits for
|
||||
the game canvas to appear and loading to finish, then captures a screenshot.
|
||||
Starts a local COOP/COEP-enabled HTTP server, launches Playwright
|
||||
Chromium, waits for the game canvas to become visible, captures a
|
||||
screenshot and writes it to *--output*.
|
||||
|
||||
Usage::
|
||||
|
||||
Usage:
|
||||
python3 screenshot_game.py --serve-dir build/www --output screenshot.png
|
||||
python3 screenshot_game.py --serve-dir build/www --output screenshot.png --port 9000 --wait-seconds 15
|
||||
python3 screenshot_game.py --serve-dir build/www --output shot.png --port 9000 --wait-seconds 15
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Embedded COOP/COEP server (mirrors serve-emscripten.py pattern)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class COOPCOEPHandler(SimpleHTTPRequestHandler):
|
||||
"""HTTP handler that adds Cross-Origin Isolation headers."""
|
||||
"""HTTP handler that injects SharedArrayBuffer-enabling headers."""
|
||||
|
||||
def end_headers(self):
|
||||
def end_headers(self) -> None:
|
||||
self.send_header("Cross-Origin-Opener-Policy", "same-origin")
|
||||
self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
|
||||
self.send_header("Cross-Origin-Resource-Policy", "cross-origin")
|
||||
super().end_headers()
|
||||
|
||||
def log_message(self, format, *args):
|
||||
"""Suppress request logging to keep output clean."""
|
||||
# Suppress per-request log lines during automated runs.
|
||||
def log_message(self, format: str, *args: object) -> None: # noqa: A002
|
||||
pass
|
||||
|
||||
|
||||
def start_server(directory, host="127.0.0.1", port=8000):
|
||||
"""Start a COOP/COEP HTTP server in a background thread.
|
||||
def start_server(
|
||||
directory: str,
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 0,
|
||||
) -> tuple[ThreadingHTTPServer, int]:
|
||||
"""Start a COOP/COEP HTTP server in a daemon thread.
|
||||
|
||||
Returns (server, thread) so the caller can shut it down.
|
||||
Parameters
|
||||
----------
|
||||
directory:
|
||||
Filesystem path to serve.
|
||||
host:
|
||||
Bind address.
|
||||
port:
|
||||
Bind port. Use ``0`` to let the OS pick a free port.
|
||||
|
||||
Returns
|
||||
-------
|
||||
(server, actual_port)
|
||||
The running server instance and the port it actually bound to.
|
||||
"""
|
||||
handler = partial(COOPCOEPHandler, directory=directory)
|
||||
server = ThreadingHTTPServer((host, port), handler)
|
||||
actual_port = server.server_address[1]
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
return server, thread
|
||||
return server, actual_port
|
||||
|
||||
|
||||
def take_screenshot(port=8000, output_path="screenshot.png", wait_seconds=10):
|
||||
"""Launch headless Chromium and screenshot the OpenRCT2 game.
|
||||
def stop_server(server: ThreadingHTTPServer) -> None:
|
||||
"""Shut down a running server."""
|
||||
server.shutdown()
|
||||
|
||||
Requires playwright to be installed with Chromium browser.
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Validation helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def validate_serve_dir(serve_dir: str) -> Optional[str]:
|
||||
"""Return an error string if *serve_dir* is not usable, else ``None``."""
|
||||
p = Path(serve_dir)
|
||||
if not p.is_dir():
|
||||
return f"--serve-dir does not exist or is not a directory: {serve_dir}"
|
||||
if not (p / "index.html").is_file():
|
||||
return f"--serve-dir does not contain index.html: {serve_dir}"
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Screenshot logic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def take_screenshot(
|
||||
serve_dir: str,
|
||||
output: str,
|
||||
port: int = 0,
|
||||
wait_seconds: int = 10,
|
||||
) -> None:
|
||||
"""Launch the game in headless Chromium and save a screenshot.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
serve_dir:
|
||||
Directory containing the built wasm output (must have index.html).
|
||||
output:
|
||||
Filesystem path for the PNG screenshot.
|
||||
port:
|
||||
Port for the embedded HTTP server (0 = auto).
|
||||
wait_seconds:
|
||||
Max seconds to wait for the game canvas to become visible and
|
||||
for the loading element to be removed.
|
||||
"""
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=["--enable-features=SharedArrayBuffer"],
|
||||
)
|
||||
page = browser.new_page(viewport={"width": 1280, "height": 720})
|
||||
|
||||
url = f"http://127.0.0.1:{port}/index.html"
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
|
||||
# Wait for the canvas to become visible
|
||||
page.wait_for_selector(
|
||||
"canvas#canvas",
|
||||
state="visible",
|
||||
timeout=wait_seconds * 1000,
|
||||
)
|
||||
|
||||
# Wait for loading to finish — #loadingWebassembly is removed when done
|
||||
try:
|
||||
page.wait_for_selector(
|
||||
"#loadingWebassembly",
|
||||
state="detached",
|
||||
timeout=wait_seconds * 1000,
|
||||
)
|
||||
except Exception:
|
||||
# If the element never existed or was already gone, that's fine
|
||||
pass
|
||||
|
||||
# Give the game a moment to render a frame
|
||||
time.sleep(2)
|
||||
|
||||
page.screenshot(path=output_path, full_page=False)
|
||||
print(f"Screenshot saved to {output_path}")
|
||||
|
||||
browser.close()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Take a screenshot of the OpenRCT2 web game"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--serve-dir", required=True,
|
||||
help="Directory containing the built wasm output (index.html etc.)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", required=True,
|
||||
help="Output path for the screenshot PNG"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port", type=int, default=8000,
|
||||
help="Port for the local server (default: 8000)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--wait-seconds", type=int, default=10,
|
||||
help="Max seconds to wait for game to load (default: 10)"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
# Validate serve dir exists
|
||||
if not os.path.isdir(args.serve_dir):
|
||||
print(f"ERROR: serve directory does not exist: {args.serve_dir}")
|
||||
error = validate_serve_dir(serve_dir)
|
||||
if error:
|
||||
print(f"Error: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Start server
|
||||
server, thread = start_server(args.serve_dir, port=args.port)
|
||||
print(f"Server started on http://127.0.0.1:{args.port}")
|
||||
|
||||
server: Optional[ThreadingHTTPServer] = None
|
||||
try:
|
||||
take_screenshot(
|
||||
port=args.port,
|
||||
output_path=args.output,
|
||||
wait_seconds=args.wait_seconds,
|
||||
)
|
||||
server, actual_port = start_server(serve_dir, port=port)
|
||||
url = f"http://127.0.0.1:{actual_port}/index.html"
|
||||
print(f"Serving {serve_dir} at {url}")
|
||||
|
||||
with sync_playwright() as pw:
|
||||
browser = pw.chromium.launch(
|
||||
headless=True,
|
||||
args=["--enable-features=SharedArrayBuffer"],
|
||||
)
|
||||
page = browser.new_page(viewport={"width": 1280, "height": 720})
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
|
||||
# Wait for canvas to appear and become visible.
|
||||
# In the game flow, canvas#canvas starts with display:none and
|
||||
# gets display="" once loading completes.
|
||||
page.wait_for_selector(
|
||||
"canvas#canvas",
|
||||
state="visible",
|
||||
timeout=wait_seconds * 1000,
|
||||
)
|
||||
|
||||
# Wait for #loadingWebassembly to be removed from the DOM.
|
||||
try:
|
||||
page.wait_for_selector(
|
||||
"#loadingWebassembly",
|
||||
state="detached",
|
||||
timeout=wait_seconds * 1000,
|
||||
)
|
||||
except Exception:
|
||||
# Element may already have been removed; that's fine.
|
||||
pass
|
||||
|
||||
# Give the game a moment to render after loading completes.
|
||||
time.sleep(2)
|
||||
|
||||
page.screenshot(path=output, full_page=False)
|
||||
print(f"Screenshot saved to {output}")
|
||||
|
||||
browser.close()
|
||||
finally:
|
||||
server.shutdown()
|
||||
print("Server stopped.")
|
||||
if server is not None:
|
||||
stop_server(server)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Take a screenshot of OpenRCT2 running in headless Chromium.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--serve-dir",
|
||||
required=True,
|
||||
help="Directory containing the built wasm output (must contain index.html).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
required=True,
|
||||
help="Output path for the PNG screenshot.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port",
|
||||
type=int,
|
||||
default=8000,
|
||||
help="Port for the embedded HTTP server (default: 8000).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--wait-seconds",
|
||||
type=int,
|
||||
default=10,
|
||||
help="Seconds to wait for the game to load (default: 10).",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
args = parse_args(argv)
|
||||
|
||||
error = validate_serve_dir(args.serve_dir)
|
||||
if error:
|
||||
print(f"Error: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
take_screenshot(
|
||||
serve_dir=args.serve_dir,
|
||||
output=args.output,
|
||||
port=args.port,
|
||||
wait_seconds=args.wait_seconds,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,53 +1,63 @@
|
||||
"""Tests for screenshot_game.py (server and error handling only).
|
||||
"""Tests for screenshot_game.py -- server and validation helpers only.
|
||||
|
||||
Does NOT test the full Playwright flow — that requires a wasm build.
|
||||
Does NOT test the full Playwright flow (that requires a real wasm build).
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from screenshot_game import start_server
|
||||
from screenshot_game import start_server, stop_server, validate_serve_dir
|
||||
|
||||
|
||||
def test_server_starts_and_stops():
|
||||
"""Verify the COOP/COEP server can start, serve, and stop cleanly."""
|
||||
"""Start the COOP/COEP server on a temp dir, make an HTTP request,
|
||||
verify COOP/COEP headers are present, then stop the server."""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
# Create a minimal index.html to serve
|
||||
with open(os.path.join(d, "index.html"), "w") as f:
|
||||
f.write("<html><body>test</body></html>")
|
||||
f.write("<html><body>hello</body></html>")
|
||||
|
||||
server, thread = start_server(d, host="127.0.0.1", port=18765)
|
||||
# Port 0 = OS picks a free port, avoiding conflicts
|
||||
server, port = start_server(d, host="127.0.0.1", port=0)
|
||||
try:
|
||||
# Give server a moment to start
|
||||
time.sleep(0.2)
|
||||
|
||||
# Fetch the page
|
||||
resp = urllib.request.urlopen("http://127.0.0.1:18765/index.html")
|
||||
resp = urllib.request.urlopen(f"http://127.0.0.1:{port}/index.html")
|
||||
body = resp.read().decode()
|
||||
assert "test" in body
|
||||
assert "hello" in body
|
||||
|
||||
# Verify COOP/COEP headers
|
||||
# Verify required cross-origin isolation headers
|
||||
coop = resp.headers.get("Cross-Origin-Opener-Policy")
|
||||
coep = resp.headers.get("Cross-Origin-Embedder-Policy")
|
||||
assert coop == "same-origin"
|
||||
assert coep == "require-corp"
|
||||
corp = resp.headers.get("Cross-Origin-Resource-Policy")
|
||||
assert coop == "same-origin", f"Expected same-origin, got {coop}"
|
||||
assert coep == "require-corp", f"Expected require-corp, got {coep}"
|
||||
assert corp == "cross-origin", f"Expected cross-origin, got {corp}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
stop_server(server)
|
||||
|
||||
|
||||
def test_missing_serve_dir():
|
||||
"""Verify graceful error when serve directory doesn't exist."""
|
||||
import subprocess
|
||||
result = subprocess.run(
|
||||
[sys.executable, os.path.join(os.path.dirname(__file__), "screenshot_game.py"),
|
||||
"--serve-dir", "/nonexistent/path/abc123",
|
||||
"--output", "/tmp/test.png"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
assert result.returncode == 1
|
||||
assert "does not exist" in result.stderr or "does not exist" in result.stdout
|
||||
"""validate_serve_dir returns an error when the directory doesn't exist."""
|
||||
error = validate_serve_dir("/nonexistent/path/abc123")
|
||||
assert error is not None
|
||||
assert "does not exist" in error
|
||||
|
||||
|
||||
def test_missing_index_html():
|
||||
"""validate_serve_dir returns an error when index.html is absent."""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
error = validate_serve_dir(d)
|
||||
assert error is not None
|
||||
assert "index.html" in error
|
||||
|
||||
|
||||
def test_valid_serve_dir():
|
||||
"""validate_serve_dir returns None for a valid directory."""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
with open(os.path.join(d, "index.html"), "w") as f:
|
||||
f.write("<html></html>")
|
||||
error = validate_serve_dir(d)
|
||||
assert error is None
|
||||
Reference in new issue
Block a user