From 74790e210280bf608f08d37331678d9bcb0aa850 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 07:34:37 -0700 Subject: [PATCH] fix: grid3d's pygbag page starts in 3D and keeps the 2D view safe, for 0.5.1 The browser page now starts in 3D, as a desktop Grid3DView game does, and the problems found in a game's run of the 0.5.0 template are fixed. - 3D by default: the relay's scripts and engine are loaded at once, alongside pygbag. The starting view is taken from ?view=2d / ?view=3d in the address (not remembered), else the player's last choice on the button (localStorage, every access in try/catch; a stored 2D wins), else the game's default: the button's data-default-view, "3d" unless the game builds with templatePath(defaultView="2d"). - The 2D canvas is hidden only once the game has sent the 3D view something to draw, and the relay canvas stays invisible (and lets presses through) until then, so pygbag's loading and tap-to-start screens stay usable while 3D loads. - If 3D can't start (no WebGL 2, a file missing, too big, the engine failed), 2D stays, the button reads "3D unavailable" and a note under it says why in plain words (Strata's failure codes are translated). Strata's own loading/failure overlay is hidden; it covered the 2D game. - The relay's three scripts (about 58 KB) are no longer in the page's markup; they are injected, in order, when 3D is wanted, so a page starting in 2D fetches nothing of the 3D view. Graphik3D.wanted() (wants3D()) turns true only once they are in. - The page is kept from scrolling (overflow: hidden on html and body), so a phone's browser can no longer widen it to fit pygbag's 50000-pixel measuring element and push the 2D/3D button off screen; the relay canvas is sized 100% rather than 100vw. - pygbag's two viewport tags, the second of which replaced the first's width=device-width, are merged into one. - Graphik3D.area() and grid3d.web.buttonArea() give the button's (x, y, width, height) in CSS pixels, so a game's HUD can keep its text out from under it. Template content checks and tests for templatePath(defaultView), buttonArea() and parseArea() are added; the version is 0.5.1 and the README's browser section describes the above. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- README.md | 8 +- .../python/preponderous/graphik/_version.py | 2 +- .../graphik/grid3d/templates/pygbag.tmpl | 207 +++++++++++++++--- .../python/preponderous/graphik/grid3d/web.py | 75 ++++++- .../graphik/grid3d/test_grid3d_web.py | 148 ++++++++++++- 5 files changed, 388 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index a491fb4..5987f08 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This library assists developers with graphics programming. graphik is released as git tags, not on PyPI. Install a release from its tag's archive (no `git` needed): ```bash -pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.0.zip" +pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.1.zip" ``` In a `requirements.txt`, use the same line without the quotes. See [RELEASING.md](RELEASING.md) for how releases are cut. @@ -95,7 +95,7 @@ and runs on Linux and Windows desktops, and in the browser under pygbag (see [In the browser](#in-the-browser)): ```bash -pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.0.zip" +pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.1.zip" ``` ```python @@ -140,7 +140,9 @@ Under [pygbag](https://pypi.org/project/pygbag/) (`sys.platform == "emscripten"` - `view.ready` turns true once the page has loaded the 3D view; `view.failure()` says why it couldn't. `open()` raises `Unavailable` on a page without the relay. - `view.pollEvents()` returns Strata-style events (keys with desktop Strata's scancodes, mouse, wheel, resize, and `FINGER_*` for touch), and `grid3d.web.toPygameEvents(events, pygame)` turns them into pygame events, so a game's 2D input code runs unchanged. It converts desktop Strata events too. -- The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and scripts and a **3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone. Nothing of the 3D view is downloaded until the player presses the button; the 2D canvas stays on screen while it loads and whenever it can't (too big, no WebGL 2), and the button then says so. `grid3d.web.wants3D()` tells the game the button is on, and `set3D(False, reason)` turns it off. +- The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and a **2D/3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone. +- Since 0.5.1 the page starts in **3D**, as a desktop `Grid3DView` game does: the relay's scripts and engine load at once, alongside pygbag, and the 2D canvas stays on screen until the 3D view is drawing the game. If 3D can't start (no WebGL 2, a file missing, too big, the engine failed), the 2D view stays, the button reads *3D unavailable* and a note under it says why in plain words. Which view a page starts in: `?view=2d` or `?view=3d` in the address (for testing and sharing; not remembered), else the player's last choice on the button (kept in `localStorage`; a stored 2D wins over the default), else the game's default, which `templatePath(defaultView="2d")` makes 2D. A page that starts in 2D downloads nothing of the 3D view (not even the relay's three small scripts) until the button is pressed. `grid3d.web.wants3D()` tells the game 3D is on and the relay's scripts are in, so `Grid3DWebView.open()` can begin, and `set3D(False, reason)` turns it off. +- The button sits in the page's top right corner. `grid3d.web.buttonArea()` gives its `(x, y, width, height)` in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (`None` outside a browser). The page never scrolls (`overflow: hidden`), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag sets `width=device-width` (pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game. In a game's `browser.yml`, where graphik is installed into `src/` for pygbag: diff --git a/src/main/python/preponderous/graphik/_version.py b/src/main/python/preponderous/graphik/_version.py index 3d18726..dd9b22c 100644 --- a/src/main/python/preponderous/graphik/_version.py +++ b/src/main/python/preponderous/graphik/_version.py @@ -1 +1 @@ -__version__ = "0.5.0" +__version__ = "0.5.1" diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl index c718106..9569582 100644 --- a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -181,8 +181,7 @@ function show_infobox() { {{cookiecutter.title}} - - + @@ -430,33 +429,87 @@ frameborder="1" - - - - - - + diff --git a/src/main/python/preponderous/graphik/grid3d/web.py b/src/main/python/preponderous/graphik/grid3d/web.py index 5376280..a74fd19 100644 --- a/src/main/python/preponderous/graphik/grid3d/web.py +++ b/src/main/python/preponderous/graphik/grid3d/web.py @@ -29,9 +29,13 @@ `pygbag --template ...`, then copy the relay's prebuilt files from Strata's release next to the built page with relay.py (`python -m preponderous.graphik.grid3d.relay --strata --dest -build/web`). Nothing of -the 3D view is downloaded until the player asks for it, and the game keeps -its 2D canvas whenever the 3D view can't load. +build/web`). The page starts in 3D, loading the relay alongside pygbag, +unless the game built it with templatePath(defaultView="2d"), the address +says ?view=2d, or the player last chose 2D on the button (remembered). The +game keeps its 2D canvas, and the page says why, whenever the 3D view can't +start; a page starting in 2D fetches nothing of the 3D view until the +button is pressed. The button sits in the page's top right corner; +buttonArea() says where, so a game's HUD can stay out from under it. Pure Python (struct, base64, json); pygbag's `platform` only in a browser. """ @@ -41,6 +45,7 @@ import os import struct import sys +import tempfile import time from types import SimpleNamespace @@ -99,10 +104,32 @@ TEMPLATE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates", "pygbag.tmpl") -def templatePath(): - """The pygbag page template with the relay's canvas, scripts and the 3D - toggle (`pygbag --template ...`).""" - return TEMPLATE +DEFAULT_VIEW_ATTRIBUTE = 'data-default-view="3d"' +VIEWS = ("2d", "3d") + + +def templatePath(defaultView="3d"): + """The pygbag page template with the relay's canvas and the 2D/3D + button (`pygbag --template ...`). The page starts in + `defaultView` ("3d", the default, or "2d") unless the address asks + for a view (?view=2d or ?view=3d) or the player chose one on the + button before (kept in the browser's localStorage). For "2d" a copy + of the template saying so is written to the temporary folder and its + path returned.""" + view = str(defaultView).lower() + if view not in VIEWS: + raise ValueError("defaultView is '2d' or '3d', not %r" % (defaultView,)) + if view == "3d": + return TEMPLATE + with open(TEMPLATE, encoding="utf-8") as handle: + page = handle.read() + if page.count(DEFAULT_VIEW_ATTRIBUTE) != 1: + raise RuntimeError("graphik's page template has no single default view to change") + page = page.replace(DEFAULT_VIEW_ATTRIBUTE, 'data-default-view="%s"' % view) + path = os.path.join(tempfile.gettempdir(), "graphik-pygbag-%s.tmpl" % view) + with open(path, "w", encoding="utf-8") as handle: + handle.write(page) + return path # -- the wire format (Strata's web/kit/grid-relay/WIRE.md, format 1.0) @@ -281,7 +308,10 @@ def __init__(self, relay=None): if relay is None: relay = pageObject("StrataGridRelay") if relay is None: - raise Unavailable("this page has no 3D view (grid-relay.js isn't loaded)") + raise Unavailable( + "this page has no 3D view (grid-relay.js isn't loaded; on graphik's " + "template it loads once the 3D toggle is on, when wants3D() turns true)" + ) self.js = relay def request(self, options): @@ -353,11 +383,38 @@ def pageObject(name): def wants3D(): """True while the page's 3D toggle (the template's window.Graphik3D) is - on. False outside a browser or on a page without the toggle.""" + on and the relay's scripts, fetched only once it is pressed, have + loaded, so Grid3DWebView.open() can begin. False outside a browser or + on a page without the toggle.""" toggle = pageObject("Graphik3D") return bool(toggle is not None and int(toggle.wanted())) +def parseArea(text): + """(x, y, width, height) from the template's "x,y,width,height", or + None for "" or anything else.""" + try: + area = tuple(int(float(part)) for part in str(text).split(",")) + except ValueError: + return None + return area if len(area) == 4 and area[2] > 0 and area[3] > 0 else None + + +def buttonArea(): + """Where the page's 2D/3D button sits, as (x, y, width, height) in CSS + pixels from the top left of the page (the units of Grid3DWebView's + labels and panels), for keeping HUD text out from under it; None + outside a browser, on a page without the button, or while it is + hidden. The template keeps it in the top right corner.""" + toggle = pageObject("Graphik3D") + if toggle is None: + return None + try: + return parseArea(toggle.area()) + except Exception: # an older template, without area() + return None + + def set3D(on, reason=""): """Turns the page's 3D toggle on or off (off with a `reason` marks it unavailable, e.g. after Unavailable). Does nothing outside a browser.""" diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py index f90a808..255d879 100644 --- a/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py @@ -390,6 +390,51 @@ def set(self, value, reason): def test_outside_a_browser_there_is_no_toggle(): assert web.wants3D() is False web.set3D(True) # does nothing + assert web.buttonArea() is None + + +def test_the_buttons_area_is_read_from_the_page(monkeypatch): + class Toggle: + shown = "326,8,56,36" + + def area(self): + return self.shown + + toggle = Toggle() + monkeypatch.setattr(sys, "platform", "emscripten") + fake = types.ModuleType("platform") + fake.window = types.SimpleNamespace(Graphik3D=toggle) + monkeypatch.setitem(sys.modules, "platform", fake) + assert web.buttonArea() == (326, 8, 56, 36) + toggle.shown = "" # hidden + assert web.buttonArea() is None + + +def test_a_template_without_area_has_no_button_area(monkeypatch): + class OldToggle: + def area(self): + raise AttributeError("area") + + monkeypatch.setattr(sys, "platform", "emscripten") + fake = types.ModuleType("platform") + fake.window = types.SimpleNamespace(Graphik3D=OldToggle()) + monkeypatch.setitem(sys.modules, "platform", fake) + assert web.buttonArea() is None + + +@pytest.mark.parametrize( + "text, area", + [ + ("326,8,56,36", (326, 8, 56, 36)), + ("326.4,8.6,56,36", (326, 8, 56, 36)), + ("", None), + ("1,2,3", None), + ("1,2,0,4", None), + ("a,b,c,d", None), + ], +) +def test_parse_area(text, area): + assert web.parseArea(text) == area # -- pygame events @@ -452,16 +497,109 @@ def test_desktop_strata_events_convert_too(): # -- the page template -def test_the_template_is_package_data_with_the_relay_and_a_3d_toggle(): +def templatePage(): with open(web.templatePath(), encoding="utf-8") as handle: - page = handle.read() + return handle.read() + + +def graphikBlock(page): + """The template's own part, after pygbag's default page.""" + return page[page.index("graphik grid3d:"):] + + +def test_the_template_is_package_data_with_the_relay_and_a_3d_toggle(): + page = templatePage() assert page.startswith("' % script in page assert 'id="graphik3d"' in page and "window.Graphik3D" in page # 3D loads only when asked for, and 2D comes back when it can't - assert page.index("relay.request(") > page.index("function set(") + assert page.index("StrataGridRelay.request(") > page.index("function start(") assert 'state.indexOf("failed:") === 0' in page and "show2d(true)" in page # pygbag's own canvas is still there, and its python block intact assert 'id="canvas"' in page and "asyncio.run( custom_site() )" in page + + +def test_the_relays_scripts_are_fetched_only_when_3d_is_wanted(): + page = templatePage() + block = graphikBlock(page) + # no script tag fetches them with the page (a page starting in 2D + # fetches nothing of the 3D view) + for script in ("strata-loader.js", "strata-kit.js", "grid-relay.js"): + assert '