From cddcb62d752b4214c95ec293cb08ca290d4a8d3e Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 19 Nov 2026 22:23:52 -0700 Subject: [PATCH 1/3] feat: grid3d helpers games shared, and a browser backend, for 0.5.0 The helpers three games had each hand-built for their 3D views are moved into grid3d, and a browser backend is added so a grid3d game can draw 3D under pygbag later. The 0.4.0 API is kept working. - Picking (pick.py): projectToScreen, pickCell, pickPoint, screenRay and cellScreenPosition, plus view.pickCell(x, y) on both views. - Text (text.py): measureText for Strata's 8x8 font (exactly one pixel size per character, checked against strata.h and the overlay's layout), wrapText and centredLabel beside fitText. - Screen buttons and a Graphik stand-in (ui.py): Button (panel, centred label, drawButton's edges and hover lift), hoverColor and ScreenRecorder for running 2D screens under a 3D view. - GridBoard options: per-cell tiles (Tile colour and raise), mergeTiles for big boards, a Viewport window, a hover highlight slab (scene(highlight=...)), and public bridgePairs/bridgeShape. - PieceStyle.extras is documented as returning shapes relative to the piece. - grid3d/web.py: Grid3DWebView drawn by Strata's grid relay (wire format 1.0 encoder and reader), Grid3DView.open() picking it under emscripten, toPygameEvents (FINGER* included) and a pygbag page template, shipped as package data, with a 3D toggle that loads the relay only on request and keeps the 2D canvas when it can't load. - Version 0.5.0 and the README's 3D section. 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 | 30 +- pyproject.toml | 4 + .../python/preponderous/graphik/_version.py | 2 +- .../preponderous/graphik/grid3d/__init__.py | 40 +- .../preponderous/graphik/grid3d/board.py | 275 ++++++-- .../preponderous/graphik/grid3d/pick.py | 103 +++ .../graphik/grid3d/templates/pygbag.tmpl | 509 +++++++++++++++ .../preponderous/graphik/grid3d/text.py | 53 ++ .../python/preponderous/graphik/grid3d/ui.py | 213 ++++++ .../preponderous/graphik/grid3d/view.py | 45 +- .../python/preponderous/graphik/grid3d/web.py | 607 ++++++++++++++++++ .../graphik/grid3d/test_grid3d_helpers.py | 319 +++++++++ .../graphik/grid3d/test_grid3d_web.py | 467 ++++++++++++++ 13 files changed, 2604 insertions(+), 63 deletions(-) create mode 100644 src/main/python/preponderous/graphik/grid3d/pick.py create mode 100644 src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl create mode 100644 src/main/python/preponderous/graphik/grid3d/text.py create mode 100644 src/main/python/preponderous/graphik/grid3d/ui.py create mode 100644 src/main/python/preponderous/graphik/grid3d/web.py create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py diff --git a/README.md b/README.md index 8d3dbde..b6e892d 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.4.0.zip" +pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.0.zip" ``` In a `requirements.txt`, use the same line without the quotes. See [RELEASING.md](RELEASING.md) for how releases are cut. @@ -91,10 +91,11 @@ An alpha component in a fill color (`(r, g, b, a)`) does not make `drawRectangle pieces standing on cells that slide smoothly between cells from one game tick to the next. A game describes its board once and reports what is on each cell every tick; the look lives in a `Theme`. It needs the optional Strata binding -and runs on Linux and Windows desktops: +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.4.0.zip" +pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.0.zip" ``` ```python @@ -119,10 +120,31 @@ else: - `Grid3DView.open(..., headless=True)` renders off-screen for tests and screenshots (`savePng`); `reducedMotion=True` makes pieces jump instead of slide. - `Unavailable` says in plain words why 3D can't run (no binding, no library for the system, no window); the game should fall back to its 2D view. - Everything except `Grid3DView.open` is plain Python, so scene code can be unit-tested without a GPU. Importing `grid3d` loads neither Strata nor pygame. +- `PieceStyle.extras(piece, x, z, baseY)` returns shapes placed relative to the piece: x and z measured from the given `(x, z)`, so moving the piece moves them all the same way. The browser backend sends them as offsets from the piece and relies on this. + +### Helpers for a game's 3D view + +So that games stop hand-building the same pieces: + +- **Picking.** `view.pickCell(x, y)` (or `pickCell(camera, board, x, y, width, height)`) gives the `(column, row)` under a pointer, or `None`; the whole cell counts, gaps between tiles included. `projectToScreen(camera, point, width, height)` and `cellScreenPosition(camera, board, column, row, width, height, y)` go the other way, for aiming a tap at a piece or putting a note beside a tile. They use the same look-at and perspective the view asks Strata for. +- **Text.** Strata's built-in font is an 8 x 8 bitmap font in which every character is exactly `pixelSize` wide. `measureText(text, pixelSize)`, `fitText(text, width, pixelSize)` (cut with `...`), `wrapText(text, maxWidth, pixelSize)` (greedy word wrap) and `centredLabel(text, x, y, pixelSize, color, rise=0.5)` build on that. +- **Screen buttons.** `Button(x, y, width, height, text, color, textColor, pixelSize, function)` draws a panel and a centred label (`button.draw(pointer)`), hit-tests with `drawButton`'s edges (`contains`, `click`), and lifts under the pointer as `drawButton` does (`hoverColor`). Colours are 0-255, as for `drawButton`; `padding` widens a button whose label doesn't fit. +- **2D screens under a 3D view.** `ScreenRecorder` stands in for `Graphik`: a game's 2D screens draw into it as usual (`drawText`, `drawRectangle`, `drawButton`), the 3D view shows what they drew, and `recorder.click(pos)` runs the 2D button's own function. +- **Bigger boards.** `GridBoard(columns, rows, theme, tiles=..., mergeTiles=True, viewport=...)`: `tiles` maps a cell to its own `Tile(color, raised)`; `mergeTiles` draws each row's neighbouring tiles that look the same as one box (a 64 x 64 board of one colour is 64 boxes, not 4096); `viewport=Viewport.around(column, row, reach)` draws only a window of the board, framed and fitted as if it were the whole board, with pieces and picking still in whole-board cells. +- **Hover.** `board.scene(..., highlight=(column, row))` lays a thin slab in `Theme.highlight` on the tile under the pointer. +- **Chains.** `board.bridgePairs(pieces)` names the joined pieces and `board.bridgeShape(a, b, aAt, bAt)` draws one bridge. + +### In the browser + +Under [pygbag](https://pypi.org/project/pygbag/) (`sys.platform == "emscripten"`), `Grid3DView.open()` returns a `grid3d.web.Grid3DWebView`: the same calls, drawn by Strata's grid relay, a small Strata web-kit scene in the page (Strata's `web/kit/grid-relay`, whose `WIRE.md` specifies the messages). Python sends the board, each tick's pieces, the HUD and the camera as small versioned binary messages; the page slides the pieces between ticks itself, so nothing is sent per display frame. A game that builds whole `Scene`s can keep calling `drawScene()` every frame; only what changed is sent. + +- `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. Put the relay's build from Strata's web kit (`grid-relay-scene.js`, `grid-relay-scene.wasm`, `strata-loader.js`, `strata-kit.js`, `grid-relay.js`) next to the built page. 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. ## Dependencies - pygame -- optional: `strata-engine` 0.7.0 for the 3D grid view (the `strata` extra) +- optional: `strata-engine` 0.8.0 for the 3D grid view on the desktop (the `strata` extra) Python 3.9 or newer is required (`requires-python` in [pyproject.toml](pyproject.toml)). The test suite is run against 3.9 through 3.13; see [`.github/workflows/test.yml`](.github/workflows/test.yml) for why 3.13 is the ceiling. diff --git a/pyproject.toml b/pyproject.toml index 42db9c7..a470411 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,10 @@ package-dir = { "" = "src/main/python" } [tool.setuptools.packages.find] where = ["src/main/python"] +# grid3d's pygbag page template (grid3d.web.templatePath()) +[tool.setuptools.package-data] +"preponderous.graphik.grid3d" = ["templates/*.tmpl"] + [tool.setuptools.dynamic] version = { attr = "preponderous.graphik._version.__version__" } diff --git a/src/main/python/preponderous/graphik/_version.py b/src/main/python/preponderous/graphik/_version.py index 6a9beea..3d18726 100644 --- a/src/main/python/preponderous/graphik/_version.py +++ b/src/main/python/preponderous/graphik/_version.py @@ -1 +1 @@ -__version__ = "0.4.0" +__version__ = "0.5.0" diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py index e472a09..bb7fc73 100644 --- a/src/main/python/preponderous/graphik/grid3d/__init__.py +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -4,13 +4,31 @@ each cell every tick (Piece), and a Grid3DView draws it, sliding pieces between cells. The scene description (scene.py, board.py, animate.py) is pure Python and needs no GPU; only Grid3DView.open() loads Strata, through the -optional `graphik[strata]` extra. Desktop Linux and Windows only for now. +optional `graphik[strata]` extra, on desktop Linux and Windows. In a browser +(pygbag) Grid3DView.open() returns web.Grid3DWebView, drawn by Strata's grid +relay in the page. + +Helpers shared by the 3D views of grid games: picking (pick.py: the cell +under a pointer, where a point lands on screen), text in Strata's font +(text.py: measure, fit, wrap, centre), screen buttons and a Graphik +stand-in for running 2D screens under a 3D view (ui.py). Importing this package imports neither Strata nor pygame. """ from .animate import Animator, interpolatePosition -from .board import BED_TOP, GridBoard, Piece, PieceStyle, Theme, cellCenter, fitCamera +from .board import ( + BED_TOP, + GridBoard, + Piece, + PieceStyle, + Theme, + Tile, + Viewport, + cellCenter, + fitCamera, +) +from .pick import cellScreenPosition, pickCell, pickPoint, projectToScreen, screenRay from .scene import ( CAPSULE, CLEAR_COLOR, @@ -33,14 +51,30 @@ rgba, shade, ) +from .text import centredLabel, measureText, wrapText +from .ui import ( + Button, + RecordedButton, + RecordedDisplay, + RecordedRect, + RecordedText, + ScreenRecorder, + drawButtons, + hoverColor, +) from .view import STRATA_VERSION, Grid3DView, Unavailable __all__ = [ "Animator", "interpolatePosition", - "BED_TOP", "GridBoard", "Piece", "PieceStyle", "Theme", "cellCenter", "fitCamera", + "BED_TOP", "GridBoard", "Piece", "PieceStyle", "Theme", "Tile", "Viewport", + "cellCenter", "fitCamera", + "cellScreenPosition", "pickCell", "pickPoint", "projectToScreen", "screenRay", "CAPSULE", "CLEAR_COLOR", "CUBE", "CYLINDER", "DIM_TEXT_COLOR", "MAX_POINT_LIGHTS", "MAX_SHADOWED_POINT_LIGHTS", "SPHERE", "TEXT_COLOR", "Camera", "Label", "Light", "Panel", "Scene", "SceneLimitError", "Shape", "fitText", "rgb255", "rgba", "shade", + "centredLabel", "measureText", "wrapText", + "Button", "RecordedButton", "RecordedDisplay", "RecordedRect", "RecordedText", + "ScreenRecorder", "drawButtons", "hoverColor", "STRATA_VERSION", "Grid3DView", "Unavailable", ] diff --git a/src/main/python/preponderous/graphik/grid3d/board.py b/src/main/python/preponderous/graphik/grid3d/board.py index 736d703..fb1aa19 100644 --- a/src/main/python/preponderous/graphik/grid3d/board.py +++ b/src/main/python/preponderous/graphik/grid3d/board.py @@ -4,8 +4,15 @@ everything looks (tile colours, frame, one PieceStyle per kind of piece). GridBoard turns the two into scene shapes and lights, and fits a camera. Pure Python: no Strata, no pygame. + +Options for bigger or busier boards: `tiles` gives cells their own colour +(and a raise above the bed), `mergeTiles` draws a row's neighbouring tiles +of one look as one box (a 64 x 64 board of grass is 64 boxes, not 4096), +and `viewport` draws only a window of the board (a close-up around one +cell). `scene(highlight=...)` lights the tile under the pointer. """ +import math from dataclasses import dataclass, field from typing import Callable, Dict, Hashable, List, Optional, Tuple @@ -32,10 +39,17 @@ class PieceStyle: piece's main shape, standing on the board with its base `lift` above the tiles. `glow` adds a point light above it: (radius, intensity). `tones` (odd, even) shades chained pieces alternately by link, so a long body - reads as segments. `extras` - draws decorations (eyes, a crown): called with (piece, x, z, baseY), it - returns more Shapes, positioned from the piece's current (possibly - interpolated) world position. + reads as segments. + + `extras` draws decorations (eyes, a crown): called with + (piece, x, z, baseY), it returns more Shapes. Their positions are + relative to the piece: x and z measured from the given (x, z), which is + the piece's current (possibly interpolated) world position, and y from + `baseY` (or absolute). Moving (x, z) by some amount must move every shape + it returns by the same amount, and nothing else about them may depend on + where the piece stands. The browser backend (web.py) relies on this: it + draws a piece's shapes once, sends them as offsets from the piece, and + the page slides them along with it. """ kind: int = CUBE @@ -93,6 +107,9 @@ class Theme: bridgeAcross: float = 0.6 bridgeHeight: float = 0.8 bridgeShade: float = 0.85 + # The slab GridBoard.scene(highlight=cell) lays on the tile under the + # pointer (the 3D form of a 2D button's hover lift). + highlight: Tuple[float, float, float] = (1.0, 0.86, 0.35) def style(self, name): try: @@ -104,6 +121,37 @@ def style(self, name): ) +@dataclass(frozen=True) +class Tile: + """One cell's own tile (GridBoard's `tiles`): a 0-1 (r, g, b) colour, and + how far its top stands above the bed (water and grass a little proud of + bare soil). Its bottom stays where every tile's is.""" + + color: Tuple[float, float, float] + raised: float = 0.0 + + +@dataclass(frozen=True) +class Viewport: + """A window of a board: `columns` x `rows` cells from (column, row), its + top-left cell. It may reach past the board's edges; cells off the board + are left empty.""" + + column: int + row: int + columns: int + rows: int + + def contains(self, column, row): + return (self.column <= column < self.column + self.columns + and self.row <= row < self.row + self.rows) + + @classmethod + def around(cls, column, row, reach): + """The (2 * reach + 1)-cell square centred on (column, row).""" + return cls(column - reach, row - reach, 2 * reach + 1, 2 * reach + 1) + + def cellCenter(column, row, columns, rows): """World (x, z) of the middle of cell (column, row).""" return (column - (columns - 1) / 2.0, row - (rows - 1) / 2.0) @@ -125,66 +173,166 @@ def fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0): class GridBoard: - """A columns x rows board drawn with a Theme.""" + """A columns x rows board drawn with a Theme. + + `tiles` maps (column, row) to a Tile (or a 0-1 colour) for cells whose + tile isn't the theme's checker; the others keep it. `mergeTiles` draws + each run of neighbouring tiles in a row that look the same (colour and + raise, after any tint) as one stretched box, so a big board costs a + shape per run, not per cell. `viewport` (a Viewport) draws only that + window of the board: the window is centred on the origin, framed and + fitted by the camera as if it were the whole board, pieces outside it + aren't drawn, and cells past the board's edge stay empty. Pieces and + picking still use the whole board's (column, row). + """ - def __init__(self, columns, rows, theme=None): + def __init__(self, columns, rows, theme=None, tiles=None, mergeTiles=False, + viewport=None): if columns < 1 or rows < 1: raise ValueError("a board needs at least one column and one row") + if viewport is not None and (viewport.columns < 1 or viewport.rows < 1): + raise ValueError("a viewport needs at least one column and one row") self.columns = columns self.rows = rows self.theme = theme or Theme() + self.tiles = tiles + self.mergeTiles = mergeTiles + self.viewport = viewport + + # -- what is on show + + def shownSize(self): + """(columns, rows) of what is drawn: the viewport's, or the board's.""" + if self.viewport is None: + return self.columns, self.rows + return self.viewport.columns, self.viewport.rows + + def shownOrigin(self): + """The board cell drawn at the top-left of what is on show.""" + if self.viewport is None: + return 0, 0 + return self.viewport.column, self.viewport.row + + def visible(self, column, row): + """True for a board cell that is drawn (on the board and in view).""" + return self.contains(column, row) and ( + self.viewport is None or self.viewport.contains(column, row) + ) def cellCenter(self, column, row): - return cellCenter(column, row, self.columns, self.rows) + if self.viewport is None: + return cellCenter(column, row, self.columns, self.rows) + v = self.viewport + return cellCenter(column - v.column, row - v.row, v.columns, v.rows) def contains(self, column, row): return 0 <= column < self.columns and 0 <= row < self.rows def camera(self, aspect=1.0): - return fitCamera(self.columns, self.rows, aspect) + columns, rows = self.shownSize() + return fitCamera(columns, rows, aspect) + + def cellAt(self, x, z): + """The visible board cell under world point (x, z), or None.""" + columns, rows = self.shownSize() + originColumn, originRow = self.shownOrigin() + column = int(math.floor(x + columns / 2.0)) + originColumn + row = int(math.floor(z + rows / 2.0)) + originRow + return (column, row) if self.visible(column, row) else None # -- the static part + def tileAt(self, column, row): + """The Tile drawn on a visible cell (before any tint).""" + t = self.theme + own = None if self.tiles is None else self.tiles.get((column, row)) + if own is not None: + return own if isinstance(own, Tile) else Tile(tuple(own)) + if t.alternate is not None and (column + row) % 2: + return Tile(t.alternate) + return Tile(t.tile) + + def tileRaise(self, column, row): + """How far the tile on a visible cell stands above the bed.""" + own = None if self.tiles is None else self.tiles.get((column, row)) + return own.raised if isinstance(own, Tile) else 0.0 + def boardShapes(self, tint=None, tintAmount=0.55): - """Tiles (checkered when the theme has an alternate colour) and a - frame. `tint` blends every tile towards a colour (a red flash on a - collision).""" + """Tiles (checkered when the theme has an alternate colour, or the + board's own `tiles`) and a frame. `tint` blends every tile towards a + colour (a red flash on a collision).""" t = self.theme shapes = [] edge = 1.0 - t.tileGap - for row in range(self.rows): - for column in range(self.columns): - cx, cz = self.cellCenter(column, row) - color = t.tile - if t.alternate is not None and (column + row) % 2: - color = t.alternate + columns, rows = self.shownSize() + originColumn, originRow = self.shownOrigin() + for shownRow in range(rows): + row = originRow + shownRow + run = None # [first column, last column, color, raised] + for shownColumn in range(columns): + column = originColumn + shownColumn + if not self.contains(column, row): + if run is not None: + shapes.append(self._tileShape(run, row, edge)) + run = None + continue + tile = self.tileAt(column, row) + color = tile.color if tint is not None: color = tuple( (1 - tintAmount) * c + tintAmount * k for c, k in zip(color, tint) ) - shapes.append( - Shape( - CUBE, - (cx, BED_TOP - t.tileHeight / 2, cz), - (edge, t.tileHeight, edge), - rgba(color), - ) - ) + if (self.mergeTiles and run is not None + and run[2] == color and run[3] == tile.raised): + run[1] = column + continue + if run is not None: + shapes.append(self._tileShape(run, row, edge)) + run = [column, column, color, tile.raised] + if run is not None: + shapes.append(self._tileShape(run, row, edge)) if t.frame is not None: - halfW, halfD = self.columns / 2.0, self.rows / 2.0 + halfW, halfD = columns / 2.0, rows / 2.0 rim, height = t.frameWidth, t.tileHeight + 0.12 yMid = BED_TOP - t.tileHeight + height / 2 frame = rgba(t.frame) - wide = self.columns + 2 * rim + wide = columns + 2 * rim shapes += [ Shape(CUBE, (0.0, yMid, -halfD - rim / 2), (wide, height, rim), frame), Shape(CUBE, (0.0, yMid, halfD + rim / 2), (wide, height, rim), frame), - Shape(CUBE, (-halfW - rim / 2, yMid, 0.0), (rim, height, self.rows), frame), - Shape(CUBE, (halfW + rim / 2, yMid, 0.0), (rim, height, self.rows), frame), + Shape(CUBE, (-halfW - rim / 2, yMid, 0.0), (rim, height, rows), frame), + Shape(CUBE, (halfW + rim / 2, yMid, 0.0), (rim, height, rows), frame), ] return shapes + def _tileShape(self, run, row, edge): + first, last, color, raised = run + t = self.theme + firstX, z = self.cellCenter(first, row) + if first == last: + x, width = firstX, edge + else: + lastX, _ = self.cellCenter(last, row) + x, width = (firstX + lastX) / 2.0, last - first + 1 - t.tileGap + if raised: + height = t.tileHeight + raised + y = BED_TOP - t.tileHeight + height / 2 + else: + height, y = t.tileHeight, BED_TOP - t.tileHeight / 2 + return Shape(CUBE, (x, y, z), (width, height, edge), rgba(color)) + + def highlightShapes(self, cell, color=None): + """A thin slab on a visible cell's tile, in the theme's highlight + colour (or `color`): the tile under the pointer. None for no cell.""" + if cell is None or not self.visible(*cell): + return [] + x, z = self.cellCenter(*cell) + edge = 1.0 - self.theme.tileGap + top = BED_TOP + self.tileRaise(*cell) + color = self.theme.highlight if color is None else color + return [Shape(CUBE, (x, top + 0.005, z), (edge, 0.01, edge), rgba(color))] + # -- the dynamic part def checkPieces(self, pieces): @@ -205,7 +353,10 @@ def checkPieces(self, pieces): def pieceShapes(self, pieces, positions=None): """Shapes and lights for `pieces`. `positions` maps a piece id to its world (x, z) for this frame (from an Animator); pieces without one - stand in the middle of their cell.""" + stand in the middle of their cell. With a viewport, pieces outside + it are left out.""" + if self.viewport is not None: + pieces = [p for p in pieces if self.viewport.contains(p.column, p.row)] shapes, lights = [], [] where = {} for piece in pieces: @@ -235,48 +386,66 @@ def pieceShapes(self, pieces, positions=None): ) if style.extras is not None: shapes.extend(style.extras(piece, x, z, baseY) or []) - shapes.extend(self._bridges(pieces, where)) + for a, b in self.bridgePairs(pieces): + shapes.append(self.bridgeShape(a, b, where[a.id], where[b.id])) return shapes, lights - def _bridges(self, pieces, where): - t = self.theme + def bridgePairs(self, pieces): + """(a, b) for every pair of pieces joined by a bridge: the same chain, + consecutive links (a's link + 1 == b's) and orthogonal neighbours on + their cells. Chains come in the order their first piece does, each + pair in link order: the order pieceShapes draws the bridges in.""" chains = {} for piece in pieces: if piece.chain is not None: chains.setdefault(piece.chain, []).append(piece) - shapes = [] + pairs = [] for members in chains.values(): - members.sort(key=lambda p: p.link) + members = sorted(members, key=lambda p: p.link) for a, b in zip(members, members[1:]): if b.link != a.link + 1: continue # only orthogonal neighbours (on their target cells) are joined if abs(a.column - b.column) + abs(a.row - b.row) != 1: continue - (ax, az), (bx, bz) = where[a.id], where[b.id] - style = t.style(b.style) - scale = (a.scale + b.scale) / 2 - across = t.bridgeAcross * scale - height = style.height * t.bridgeHeight * (0.75 + 0.25 * scale) - color = b.color if b.color is not None else style.color - shapes.append( - Shape( - SPHERE, - ((ax + bx) / 2, BED_TOP + style.lift + height / 2, (az + bz) / 2), - (max(across, abs(ax - bx)), height, max(across, abs(az - bz))), - rgba(shade(color, t.bridgeShade)), - ) - ) - return shapes + pairs.append((a, b)) + return pairs + + def bridgeShape(self, a, b, aAt, bAt): + """The bridge between joined pieces a and b drawn at world (x, z) + `aAt` and `bAt`: in the middle, stretched to reach both (and never + thinner across than the theme's bridgeAcross).""" + t = self.theme + (ax, az), (bx, bz) = aAt, bAt + style = t.style(b.style) + scale = (a.scale + b.scale) / 2 + across = t.bridgeAcross * scale + height = style.height * t.bridgeHeight * (0.75 + 0.25 * scale) + color = b.color if b.color is not None else style.color + return Shape( + SPHERE, + ((ax + bx) / 2, BED_TOP + style.lift + height / 2, (az + bz) / 2), + (max(across, abs(ax - bx)), height, max(across, abs(az - bz))), + rgba(shade(color, t.bridgeShade)), + ) + + def _bridges(self, pieces, where): + # kept for code written against 0.4.0; bridgePairs and bridgeShape + # are the public form + return [self.bridgeShape(a, b, where[a.id], where[b.id]) + for a, b in self.bridgePairs(pieces)] # -- everything def scene(self, pieces=(), positions=None, labels=(), panels=(), lights=(), - aspect=1.0, tint=None, clearColor=None): - """A complete Scene, checked against the engine limits.""" + aspect=1.0, tint=None, clearColor=None, highlight=None, + highlightColor=None): + """A complete Scene, checked against the engine limits. `highlight` + is a (column, row) whose tile gets the hover slab, drawn last.""" pieceShapes, pieceLights = self.pieceShapes(pieces, positions) scene = Scene(camera=self.camera(aspect)) - scene.shapes = self.boardShapes(tint) + pieceShapes + scene.shapes = (self.boardShapes(tint) + pieceShapes + + self.highlightShapes(highlight, highlightColor)) scene.lights = list(lights) + pieceLights scene.labels = list(labels) scene.panels = list(panels) diff --git a/src/main/python/preponderous/graphik/grid3d/pick.py b/src/main/python/preponderous/graphik/grid3d/pick.py new file mode 100644 index 0000000..b4a1402 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/pick.py @@ -0,0 +1,103 @@ +"""Screen <-> world: where a world point lands in the window, and which cell +is under a pointer. + +The same right-handed look-at and OpenGL perspective a Grid3DView asks +Strata for (up is +y, Camera.fovDegrees vertical), so a press lands on the +tile the player sees, on the desktop and in the browser alike. Pure Python: +no Strata, no pygame. +""" + +import math + +from .board import BED_TOP + + +def _sub(a, b): + return (a[0] - b[0], a[1] - b[1], a[2] - b[2]) + + +def _dot(a, b): + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + + +def _cross(a, b): + return ( + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ) + + +def _unit(a): + length = math.sqrt(_dot(a, a)) + return (a[0] / length, a[1] / length, a[2] / length) + + +def cameraBasis(camera): + """(forward, right, up) unit vectors of a Camera.""" + forward = _unit(_sub(camera.target, camera.eye)) + right = _unit(_cross(forward, (0.0, 1.0, 0.0))) + return forward, right, _cross(right, forward) + + +def projectToScreen(camera, point, width, height): + """Where world point (x, y, z) lands in a width x height window, in + pixels from the top-left, or None when it is behind the camera.""" + forward, right, up = cameraBasis(camera) + offset = _sub(point, camera.eye) + depth = _dot(offset, forward) + if depth <= 0: + return None + focal = 1.0 / math.tan(math.radians(camera.fovDegrees) / 2.0) + aspect = width / float(height) + ndcX = focal / aspect * _dot(offset, right) / depth + ndcY = focal * _dot(offset, up) / depth + return ((ndcX + 1.0) / 2.0 * width, (1.0 - ndcY) / 2.0 * height) + + +def screenRay(camera, x, y, width, height): + """The direction (not normalised) from the camera's eye through window + pixel (x, y).""" + forward, right, up = cameraBasis(camera) + focal = 1.0 / math.tan(math.radians(camera.fovDegrees) / 2.0) + aspect = width / float(height) + ndcX = x / float(width) * 2.0 - 1.0 + ndcY = 1.0 - y / float(height) * 2.0 + return tuple( + forward[i] + right[i] * ndcX * aspect / focal + up[i] * ndcY / focal + for i in range(3) + ) + + +def pickPoint(camera, x, y, width, height, planeY=BED_TOP): + """World (x, z) where the ray through window pixel (x, y) meets the + horizontal plane at height `planeY` (the tiles' top), or None when the + pixel looks above the horizon.""" + direction = screenRay(camera, x, y, width, height) + if direction[1] >= 0: + return None + t = (planeY - camera.eye[1]) / direction[1] + if t <= 0: + return None # the plane is behind the camera + return (camera.eye[0] + direction[0] * t, camera.eye[2] + direction[2] * t) + + +def pickCell(camera, board, x, y, width, height): + """The (column, row) of the board cell under window pixel (x, y), or + None (off the board, out of its viewport, or above the horizon). The + whole cell counts, gaps between tiles included, so no press between two + tiles is lost. The 3D form of a 2D grid's pixel-to-cell division.""" + if x is None or y is None: + return None + point = pickPoint(camera, x, y, width, height) + if point is None: + return None + return board.cellAt(*point) + + +def cellScreenPosition(camera, board, column, row, width, height, y=BED_TOP): + """Where the middle of cell (column, row), `y` above the bed, lands in + the window (pixels from the top-left), or None behind the camera: for + aiming a tap at a piece, or putting a note beside a tile.""" + cx, cz = board.cellCenter(column, row) + return projectToScreen(camera, (cx, y, cz), width, height) diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl new file mode 100644 index 0000000..502659e --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -0,0 +1,509 @@ + + + {{cookiecutter.title}} + + + + + + + + + + + + + + + + + + + + +
+ +
Downloading...
+
+ +
+
+ + + + + + + +
Loading, please wait ...
+ +
+ +
+ + + + + +
+ + + + +
+
+
+ + + + + + + + + + + + + diff --git a/src/main/python/preponderous/graphik/grid3d/text.py b/src/main/python/preponderous/graphik/grid3d/text.py new file mode 100644 index 0000000..14ba333 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/text.py @@ -0,0 +1,53 @@ +"""Screen text in Strata's built-in font: measuring, cutting, wrapping and +centring it. + +Strata draws screen text in an 8 x 8 bitmap font scaled to a Label's +`pixelSize`: every character is a square cell exactly pixelSize wide and +tall (strata.h, StrataText), so a line of n characters is n * pixelSize +pixels wide. A character outside printable ASCII shows as one '?', still one +cell, and a newline starts the next line pixelSize lower. Pure Python. +""" + +from .scene import TEXT_COLOR, Label, fitText + +__all__ = ["measureText", "fitText", "wrapText", "centredLabel"] + + +def measureText(text, pixelSize): + """How wide `text` is drawn at `pixelSize`, in pixels: its longest line's + characters times pixelSize.""" + return max(len(line) for line in str(text).split("\n")) * pixelSize + + +def wrapText(text, maxWidth, pixelSize): + """Word-wrap `text` (a string, or a list of lines) to lines no wider + than `maxWidth` pixels at `pixelSize`. Words are split on single spaces + and packed greedily; an empty line stays an empty line, and a word too + wide for any line is left whole on a line of its own rather than cut or + dropped. Newlines in a string start new lines. Returns the lines.""" + lines = text.split("\n") if isinstance(text, str) else list(text) + wrapped = [] + for line in lines: + if not line: + wrapped.append(line) + continue + current = "" + for word in line.split(" "): + candidate = word if not current else current + " " + word + if current and measureText(candidate, pixelSize) > maxWidth: + wrapped.append(current) + current = word + else: + current = candidate + wrapped.append(current) + return wrapped + + +def centredLabel(text, x, y, pixelSize, color=TEXT_COLOR, rise=0.5): + """A Label centred across x, as graphik's 2D drawText centres its text. + `rise` places it vertically: its top is `rise * pixelSize` above y, so + 0.5 centres its cells on y, 0.45 centres the ink of most glyphs on y + (capitals fill the top seven of the font's eight rows), and 0 puts its + top at y.""" + return Label(text, x - measureText(text, pixelSize) / 2.0, y - pixelSize * rise, + pixelSize, color) diff --git a/src/main/python/preponderous/graphik/grid3d/ui.py b/src/main/python/preponderous/graphik/grid3d/ui.py new file mode 100644 index 0000000..a34d6c6 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ui.py @@ -0,0 +1,213 @@ +"""Menus over a 3D view that look and behave like graphik's 2D ones. + +Button is a screen button for a 3D window: a panel with a centred label, a +hit test with the same edges as Graphik.drawButton's, and the same hover +lift. ScreenRecorder stands in for Graphik so a game's own 2D screens can +run unchanged under a 3D view: they draw into it as usual, and the 3D view +shows what they drew (as Buttons, Labels and Panels) and sends a click to +the 2D button's own function. Pure Python: no pygame, no Strata. + +Colours here are 0-255 (r, g, b), as the 2D screens give them to Graphik. +""" + +from dataclasses import dataclass +from typing import Callable, Optional, Tuple + +from .scene import Panel, rgb255, rgba +from .text import centredLabel, measureText + +Color255 = Tuple[int, int, int] + + +def hoverColor(color): + """Graphik.drawButton's hover lift for a 0-255 (r, g, b[, a]) colour: + light colours (an average r/g/b of 128 or more) darken by 25, the rest + lighten by 35, each channel clamped to 0-255. Returns (r, g, b).""" + shift = -25 if sum(color[:3]) / 3.0 >= 128 else 35 + return tuple(max(0, min(255, c + shift)) for c in color[:3]) + + +def contains(x, y, width, height, position): + """True when `position` (x, y) is on the box, with Graphik.drawButton's + edges: left and top in, right and bottom out, so buttons laid edge to + edge share no pixel. None is never on it.""" + if position is None: + return False + px, py = position + return x <= px < x + width and y <= py < y + height + + +@dataclass +class Button: + """A screen button for a 3D window, in window pixels. + + `color` and `textColor` are 0-255, as Graphik.drawButton takes them; + `pixelSize` is the label's Strata pixel size. The panel is drawn at + `alpha`. With `padding`, a label too wide for the box widens it about its + centre to the label's width plus `padding` a side (Strata's font is + wider than most pygame fonts). `rise` places the label vertically (see + centredLabel). `function` is what a click runs (click()). + """ + + x: float + y: float + width: float + height: float + text: str + color: Color255 = (200, 200, 200) + textColor: Color255 = (0, 0, 0) + pixelSize: float = 16 + function: Optional[Callable] = None + alpha: float = 1.0 + padding: Optional[float] = None + rise: float = 0.5 + + def rect(self): + """(x, y, width, height) as drawn and hit.""" + if self.padding is None: + return self.x, self.y, self.width, self.height + needed = measureText(self.text, self.pixelSize) + 2 * self.padding + if needed <= self.width: + return self.x, self.y, self.width, self.height + centre = self.x + self.width / 2.0 + return centre - needed / 2.0, self.y, needed, self.height + + def contains(self, position): + x, y, width, height = self.rect() + return contains(x, y, width, height, position) + + def draw(self, pointer=None): + """(Panel, Label) for this frame; the panel takes the hover lift while + `pointer` is over the button.""" + x, y, width, height = self.rect() + box = hoverColor(self.color) if contains(x, y, width, height, pointer) else self.color + panel = Panel(x, y, width, height, rgba(rgb255(box), self.alpha)) + label = centredLabel(self.text, x + width / 2.0, y + height / 2.0, self.pixelSize, + rgba(rgb255(self.textColor)), rise=self.rise) + return panel, label + + def click(self, position): + """Runs `function` when `position` is on the button; True if it was.""" + if self.function is None or not self.contains(position): + return False + self.function() + return True + + +def drawButtons(buttons, pointer=None): + """Labels and panels for several Buttons: ([Label], [Panel]).""" + labels, panels = [], [] + for button in buttons: + panel, label = button.draw(pointer) + panels.append(panel) + labels.append(label) + return labels, panels + + +# -- standing in for Graphik + + +@dataclass +class RecordedText: + """A drawText call: text centred on (x, y); size is a pygame font size.""" + + text: str + x: float + y: float + size: float + color: Color255 + + +@dataclass +class RecordedRect: + """A drawRectangle call.""" + + x: float + y: float + width: float + height: float + color: Color255 + + +@dataclass +class RecordedButton: + """A drawButton call, with the function the 2D screen gave it.""" + + x: float + y: float + width: float + height: float + color: Color255 + textColor: Color255 + textSize: float + text: str + function: Callable + + def contains(self, position): + # exactly the drawn box, as drawButton counts it + return contains(self.x, self.y, self.width, self.height, position) + + +class RecordedDisplay: + """The parts of a pygame Surface that screens ask Graphik's display for.""" + + def __init__(self, width, height): + self.width, self.height = width, height + + def get_size(self): + return (self.width, self.height) + + def get_width(self): + return self.width + + def get_height(self): + return self.height + + def fill(self, color): + pass + + +class ScreenRecorder: + """Stands in for Graphik: keeps, in order, what a screen draws (drawText, + drawRectangle, drawButton) instead of painting it. `items` is one frame's + worth; reset() starts the next.""" + + def __init__(self, width=800, height=600): + self.gameDisplay = RecordedDisplay(width, height) + self.items = [] + + def resize(self, width, height): + self.gameDisplay.width, self.gameDisplay.height = width, height + + def getGameDisplay(self): + return self.gameDisplay + + def reset(self): + self.items = [] + + def drawText(self, text, xpos, ypos, size, color): + self.items.append(RecordedText(str(text), xpos, ypos, size, tuple(color[:3]))) + + def drawRectangle(self, xpos, ypos, width, height, color): + self.items.append(RecordedRect(xpos, ypos, width, height, tuple(color[:3]))) + + def drawButton(self, xpos, ypos, width, height, colorBox, colorText, sizeText, text, function): + self.items.append( + RecordedButton(xpos, ypos, width, height, tuple(colorBox[:3]), tuple(colorText[:3]), + sizeText, str(text), function) + ) + + def buttons(self): + return [item for item in self.items if isinstance(item, RecordedButton)] + + def texts(self): + return [item.text for item in self.items if isinstance(item, RecordedText)] + + def click(self, position): + """Runs the function of the first recorded button under `position`; + returns whether one was hit.""" + for button in self.buttons(): + if button.contains(position): + button.function() + return True + return False diff --git a/src/main/python/preponderous/graphik/grid3d/view.py b/src/main/python/preponderous/graphik/grid3d/view.py index 6cdfe35..1e02b50 100644 --- a/src/main/python/preponderous/graphik/grid3d/view.py +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -8,6 +8,10 @@ can't load or no window can open, Grid3DView.open() raises Unavailable with a reason a player can act on, and the game keeps its 2D view. +In a browser (pygbag, where sys.platform is "emscripten"), Grid3DView.open() +returns a Grid3DWebView instead (web.py): the same calls, drawn by the +page's Strata grid relay. See web.py for what the page needs. + Usage, once per game: view = Grid3DView.open(900, 700, "My game") # or headless=True @@ -17,6 +21,8 @@ view.frame() # once per display frame view.close() + view.pickCell(x, y) # the (column, row) under a pointer, or None + The board and labels are kept between frames; pieces slide between their cells over one tick (see animate.Animator). """ @@ -26,6 +32,7 @@ import time from .animate import Animator +from .pick import cellScreenPosition, pickCell, projectToScreen STRATA_VERSION = "0.8.0" STRATA_PLATFORMS = ("linux", "win32") @@ -58,7 +65,33 @@ def loadStrata(platform=None): raise Unavailable("the Strata library couldn't be loaded: %s" % error) -class Grid3DView: +class ViewGeometry: + """Where things are on screen, for a view with `board`, `width` and + `height` (Grid3DView and Grid3DWebView).""" + + def camera(self): + """The camera the current board is drawn with at this window size.""" + if self.board is None: + raise RuntimeError("setBoard() must come before the camera") + return self.board.camera(self.width / float(self.height)) + + def pickCell(self, x, y): + """The board (column, row) under window pixel (x, y), or None.""" + if self.board is None: + return None + return pickCell(self.camera(), self.board, x, y, self.width, self.height) + + def projectToScreen(self, point): + """Where world point (x, y, z) lands in the window, or None.""" + return projectToScreen(self.camera(), point, self.width, self.height) + + def cellScreenPosition(self, column, row, y=0.0): + """Where the middle of a cell, `y` above the bed, lands in the window.""" + return cellScreenPosition(self.camera(), self.board, column, row, + self.width, self.height, y) + + +class Grid3DView(ViewGeometry): """One Strata engine (a window, or headless for screenshots and tests).""" def __init__(self, strata, lib, engine, width, height, isWindow, @@ -83,7 +116,15 @@ def __init__(self, strata, lib, engine, width, height, isWindow, def open(cls, width=900, height=700, title="graphik", headless=False, reducedMotion=False, clock=time.monotonic): """Open a window (or a headless surface); raise Unavailable if Strata - can't run here.""" + can't run here. In a browser this is a Grid3DWebView (web.py), which + has no headless form.""" + if sys.platform == "emscripten": + if headless: + raise Unavailable("a browser has no headless 3D view") + from .web import Grid3DWebView + + return Grid3DWebView.open(width, height, title, + reducedMotion=reducedMotion or None, clock=clock) if headless and sys.platform.startswith("linux"): # Linux renders headless through EGL with no window. On Windows the # headless engine is a hidden SDL window, which the dummy driver diff --git a/src/main/python/preponderous/graphik/grid3d/web.py b/src/main/python/preponderous/graphik/grid3d/web.py new file mode 100644 index 0000000..6e8c099 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/web.py @@ -0,0 +1,607 @@ +"""grid3d in the browser: a Grid3DView for pygbag, drawn by Strata's grid relay. + +Under pygbag, Python can't reach WebGL, so the page carries a small Strata +web-kit scene, the grid relay (Strata's web/kit/grid-relay, whose WIRE.md +is the format spec), and this module sends it the same scene description a +desktop Grid3DView draws, as versioned binary messages: + + BOARD the board's shapes and lights (setBoard: once, or on a tint) + PIECES this tick's pieces (setPieces: once per game tick) + HUD screen labels and panels (setLabels: when the HUD changes) + VIEW camera, clear colour, sun (setBoard, resize) + +The relay slides pieces between ticks itself, so nothing is sent per display +frame. Pieces are sent as anchors (where each piece slides from and to, from +the same Animator the desktop uses) plus shapes measured from their anchor, +so a piece's extras (eyes, a crown) and the bridges of a chain move with it +as on the desktop; this is why PieceStyle.extras must place its shapes +relative to the piece. A game that builds whole Scenes itself can call +drawScene() every frame, as on the desktop: only the parts that changed +since the last frame are sent. + +Input comes back the other way: pollEvents() returns Strata-style events +(EVENT_KEY_DOWN with desktop Strata's scancodes, mouse, wheel, RESIZED, and +the web's FINGER_* events), and toPygameEvents() turns them into pygame +events, so a game's 2D input handling works unchanged in 3D. + +The page: TEMPLATE (templatePath()) is a pygbag page template carrying the +relay's canvas and scripts and a 3D toggle. Build with +`pygbag --template ...` and put the relay's build +(grid-relay-scene.js and .wasm, strata-loader.js, strata-kit.js, +grid-relay.js, from Strata's web kit) next to the built page. 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. + +Pure Python (struct, base64, json); pygbag's `platform` only in a browser. +""" + +import base64 +import json +import os +import struct +import sys +import time +from types import SimpleNamespace + +from .animate import Animator +from .scene import CLEAR_COLOR, checkLights +from .view import ViewGeometry, Unavailable + +WIRE_MAJOR, WIRE_MINOR = 1, 0 +MAGIC = b"G3" +BOARD, PIECES, HUD, VIEW = 1, 2, 3, 4 +KINDS = (BOARD, PIECES, HUD, VIEW) +WORLD, PIECE, BRIDGE = 0, 1, 2 + +HEADER = struct.Struct("<2sBBBBH") # 8 bytes +SHAPE = struct.Struct(" ...`).""" + return TEMPLATE + + +# -- the wire format (Strata's web/kit/grid-relay/WIRE.md, format 1.0) + + +class WireError(ValueError): + """A message the relay would refuse. `status` is the relay's code.""" + + def __init__(self, status, detail=""): + self.status = status + reason = STATUS.get(status, "status %d" % status) + super().__init__(reason + (": " + detail if detail else "")) + + +def header(kind): + return HEADER.pack(MAGIC, WIRE_MAJOR, WIRE_MINOR, kind, 0, 0) + + +def _rgba(color): + color = tuple(color) + return (color + (1.0,) * (4 - len(color)))[:4] + + +def _shape(kind, attach, a, b, position, scale, color): + return SHAPE.pack(kind, attach, a, b, 0, *position, *scale, *_rgba(color)) + + +def _light(attach, a, light, offset=(0.0, 0.0)): + x, y, z = light.position + return LIGHT.pack( + attach, 1 if light.castShadows else 0, a, + x - offset[0], y, z - offset[1], *light.color, light.radius, light.intensity, + ) + + +def encodeBoard(shapes, lights=()): + """BOARD: world shapes and lights.""" + out = [header(BOARD), COUNTS.pack(len(shapes), len(lights))] + out += [_shape(s.kind, WORLD, 0, 0, s.position, s.scale, s.color) for s in shapes] + out += [_light(WORLD, 0, light) for light in lights] + return b"".join(out) + + +def _labelText(text): + data = str(text).replace("\0", "").encode("utf-8") + if len(data) > 65535: + data = data[:65535].decode("utf-8", "ignore").encode("utf-8") + return data + + +def encodeHud(labels=(), panels=()): + """HUD: screen panels (drawn first) and labels, in CSS pixels.""" + out = [header(HUD), COUNTS.pack(len(panels), len(labels))] + for p in panels: + out.append(PANEL.pack(p.x, p.y, p.width, p.height, *_rgba(p.color))) + for label in labels: + text = _labelText(label.text) + out.append(LABEL.pack(label.x, label.y, label.pixelSize, *_rgba(label.color), len(text), 0)) + out.append(text + b"\0" * (-len(text) % 4)) + return b"".join(out) + + +def encodeView(camera, clearColor=CLEAR_COLOR, sun=SUN_DIRECTION, near=NEAR_PLANE, far=FAR_PLANE): + """VIEW: the camera, clear colour and direction to the sun.""" + return header(VIEW) + VIEW_BODY.pack( + *camera.eye, *camera.target, camera.fovDegrees, near, far, *_rgba(clearColor), *sun + ) + + +def encodePieces(board, pieces, tracks, tickSeconds): + """PIECES for this tick. `tracks` maps a piece id to ((x0, z0), (x1, z1)), + from an Animator; a piece without one stands still on its cell. With a + viewport, only the pieces in it are sent.""" + pieces = [p for p in pieces if board.visible(p.column, p.row)] + index = {} + anchors, shapes, lights = [], [], [] + for i, piece in enumerate(pieces): + end = board.cellCenter(piece.column, piece.row) + start, end = tracks.get(piece.id, (end, end)) + index[piece.id] = i + anchors.append(ANCHOR.pack(start[0], start[1], end[0], end[1])) + # The piece's own shapes and glow, drawn at its end cell and sent as + # offsets from it. A lone piece has no bridges; they come below. + alone, glow = board.pieceShapes([piece], positions={piece.id: end}) + for s in alone: + x, y, z = s.position + shapes.append(_shape(s.kind, PIECE, i, 0, (x - end[0], y, z - end[1]), s.scale, s.color)) + lights += [_light(PIECE, i, light, end) for light in glow] + # Chain bridges, in pieceShapes' order. Each is drawn with both ends at + # the origin, which gives its size across; the relay spans the anchors. + for a, b in board.bridgePairs(pieces): + s = board.bridgeShape(a, b, (0.0, 0.0), (0.0, 0.0)) + shapes.append(_shape(s.kind, BRIDGE, index[a.id], index[b.id], s.position, s.scale, s.color)) + head = header(PIECES) + PIECES_HEAD.pack(tickSeconds, len(anchors), len(shapes), len(lights)) + return head + b"".join(anchors) + b"".join(shapes) + b"".join(lights) + + +def readHeader(message): + """(major, minor, kind) of a message, or WireError as the relay would + refuse it: not a relay message, another major version, truncated.""" + if len(message) < 2 or bytes(message[:2]) != MAGIC: + raise WireError(-1) + if len(message) < 3: + raise WireError(-3, "no version") + if message[2] != WIRE_MAJOR: + major = message[2] + minor = message[3] if len(message) > 3 else 0 + raise WireError(-2, "wire format %d.%d; this reads %d.x" % (major, minor, WIRE_MAJOR)) + if len(message) < HEADER.size: + raise WireError(-3, "header") + _, major, minor, kind, _, _ = HEADER.unpack_from(message) + if kind not in KINDS: + raise WireError(-4, "kind %d" % kind) + return major, minor, kind + + +def decode(message): + """A message read back as (kind, contents): for tests and tools, with + the relay's checks (version, kind, counts against the length). A minor + version above 0 may carry fields after the ones 1.0 knows; they are + ignored, as the relay ignores them.""" + _, _, kind = readHeader(message) + body = memoryview(message)[HEADER.size:] + + def take(fmt, offset, count=1): + end = offset + fmt.size * count + if end > len(body): + raise WireError(-3, "kind %d" % kind) + return [fmt.unpack_from(body, offset + fmt.size * i) for i in range(count)], end + + def shape(r): + return {"kind": r[0], "attach": r[1], "a": r[2], "b": r[3], + "position": r[5:8], "scale": r[8:11], "color": r[11:15]} + + def light(r): + return {"attach": r[0], "castShadows": bool(r[1] & 1), "a": r[2], + "position": r[3:6], "color": r[6:9], "radius": r[9], "intensity": r[10]} + + if kind == BOARD: + (counts,), at = take(COUNTS, 0) + shapes, at = take(SHAPE, at, counts[0]) + lights, at = take(LIGHT, at, counts[1]) + return kind, {"shapes": [shape(r) for r in shapes], "lights": [light(r) for r in lights]} + if kind == PIECES: + (head,), at = take(PIECES_HEAD, 0) + anchors, at = take(ANCHOR, at, head[1]) + shapes, at = take(SHAPE, at, head[2]) + lights, at = take(LIGHT, at, head[3]) + return kind, {"tickSeconds": head[0], "anchors": [tuple(a) for a in anchors], + "shapes": [shape(r) for r in shapes], "lights": [light(r) for r in lights]} + if kind == HUD: + (counts,), at = take(COUNTS, 0) + panels, at = take(PANEL, at, counts[0]) + labels = [] + for _ in range(counts[1]): + (r,), at = take(LABEL, at) + length = r[7] + if at + length > len(body): + raise WireError(-3, "label text") + text = bytes(body[at:at + length]).decode("utf-8") + at += length + (-length % 4) + labels.append({"x": r[0], "y": r[1], "pixelSize": r[2], "color": r[3:7], "text": text}) + return kind, {"panels": [{"rect": p[:4], "color": p[4:8]} for p in panels], "labels": labels} + (r,), _ = take(VIEW_BODY, 0) + return kind, {"eye": r[0:3], "target": r[3:6], "fovDegrees": r[6], "near": r[7], "far": r[8], + "clearColor": r[9:13], "sun": r[13:16]} + + +# -- transports + + +class PlatformRelay: + """The page's window.StrataGridRelay, through pygbag's platform.window.""" + + 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)") + self.js = relay + + def request(self, options): + return str(self.js.request(json.dumps(options))) + + def state(self): + return str(self.js.state()) + + def send(self, message): + return int(self.js.send(base64.b64encode(message).decode("ascii"))) + + def poll(self): + return json.loads(str(self.js.poll())) + + def reducedMotion(self): + return bool(int(self.js.reducedMotion())) + + def close(self): + self.js.close() + + +class RecordingRelay: + """A relay that keeps what it is sent: for tests, and for recording a + game to play into the relay's test page (index.html?wire=...).""" + + def __init__(self, reducedMotion=False, state="ready"): + self.messages, self.events, self.motion = [], [], reducedMotion + self.status = state + self.closed = False + + def request(self, options): + self.options = options + return self.status + + def state(self): + return self.status + + def send(self, message): + try: + readHeader(message) + except WireError as error: + return error.status + self.messages.append(bytes(message)) + return 0 + + def poll(self): + events, self.events = self.events, [] + return events + + def reducedMotion(self): + return self.motion + + def close(self): + self.closed = True + + def wireJson(self): + return json.dumps([base64.b64encode(m).decode("ascii") for m in self.messages]) + + +def pageObject(name): + """window. under pygbag, or None (not in a browser, or no such + object on the page).""" + if sys.platform != "emscripten": + return None + import platform # pygbag's, not the standard library's + + return getattr(platform.window, name, None) + + +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.""" + toggle = pageObject("Graphik3D") + return bool(toggle is not None and int(toggle.wanted())) + + +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.""" + toggle = pageObject("Graphik3D") + if toggle is not None: + toggle.set(1 if on else 0, str(reason)) + + +# -- the view + + +class Event: + """A Strata-style event (the fields of strata.h's StrataEvent, plus the + web's pointer, id, nx, ny for touch and the browser's key).""" + + __slots__ = ("type", "scancode", "modifiers", "repeat", "button", "width", "height", + "x", "y", "dx", "dy", "text", "pointer", "id", "nx", "ny", "key", "pressure") + + def __init__(self, d): + for name in self.__slots__: + setattr(self, name, d.get(name, "" if name in ("text", "pointer", "key") else 0)) + + def __repr__(self): + return "Event(%s)" % ", ".join( + "%s=%r" % (n, getattr(self, n)) for n in self.__slots__ if getattr(self, n)) + + +class Grid3DWebView(ViewGeometry): + """Grid3DView's calls (setBoard, setPieces, setLabels, frame, drawScene, + pollEvents, resize, close, pickCell), drawn by the page's grid relay.""" + + EVENT_QUIT, EVENT_KEY_DOWN, EVENT_KEY_UP, EVENT_RESIZED = ( + EVENT_QUIT, EVENT_KEY_DOWN, EVENT_KEY_UP, EVENT_RESIZED) + + def __init__(self, relay, width, height, reducedMotion=False, clock=time.monotonic): + self.relay = relay + self.strata = EVENTS + self.width, self.height = width, height + self.isWindow = True + self.reducedMotion = reducedMotion + self.clock = clock + self.board = None + self.boardTint = None + self.boardLights = [] + self.pieces = [] + self.labels, self.panels = [], [] + self.animator = None + self.sent = 0 + self.lastSent = {} # kind -> the last message of that kind (drawScene) + + @classmethod + def open(cls, width=900, height=700, title="graphik", relay=None, maxBytes=4000000, + reducedMotion=None, clock=time.monotonic, canvas="relay"): + """Ask the page for its 3D view (it is downloaded only now, and only + under maxBytes); raise Unavailable when there is none. `ready` says + when it has loaded; what is sent before then waits in the page.""" + relay = relay or PlatformRelay() + state = relay.request({"canvas": canvas, "maxBytes": maxBytes, "title": title}) + if state.startswith("failed:"): + raise Unavailable(state[len("failed:"):]) + if reducedMotion is None: + reducedMotion = relay.reducedMotion() + return cls(relay, width, height, reducedMotion=reducedMotion, clock=clock) + + @property + def ready(self): + return self.relay.state() == "ready" + + def failure(self): + """Why the page's 3D view failed to load, or None.""" + state = self.relay.state() + return state[len("failed:"):] if state.startswith("failed:") else None + + def _send(self, message, kind=None): + rc = self.relay.send(message) + if rc < 0: + raise WireError(rc, "the grid relay refused a message") + self.sent += 1 + if kind is not None: + self.lastSent[kind] = message + + # -- what to draw (as Grid3DView) + + def setBoard(self, board, tint=None, lights=()): + """The static part: call when the board, its theme or its tint changes.""" + self.board = board + self.boardTint = tint + self.boardLights = list(lights) + checkLights(self.boardLights) + self.animator = Animator(board.cellCenter, reducedMotion=self.reducedMotion) + self.animator.update(self.pieces, self.clock(), 0.0) + self._send(encodeBoard(board.boardShapes(tint), self.boardLights), BOARD) + self._sendView() + self._send(encodePieces(board, self.pieces, self.animator.tracks, 0.0), PIECES) + + def setPieces(self, pieces, tickSeconds=0.0, snap=False): + """The dynamic part: call once per game tick (see Grid3DView).""" + if self.board is None: + raise RuntimeError("setBoard() must come before setPieces()") + pieces = list(pieces) + self.board.checkPieces(pieces) + _, lights = self.board.pieceShapes(pieces) + checkLights(self.boardLights + lights) + self.pieces = pieces + self.animator.update(pieces, self.clock(), tickSeconds, snap=snap) + tick = 0.0 if snap else self.animator.tickSeconds + self._send(encodePieces(self.board, pieces, self.animator.tracks, tick), PIECES) + + def setLabels(self, labels=(), panels=()): + """Screen text and the panels behind it.""" + self.labels, self.panels = list(labels), list(panels) + self._send(encodeHud(self.labels, self.panels), HUD) + + def scene(self, now=None): + """The Scene a desktop view would draw at `now` (for tests and tools).""" + if self.board is None: + raise RuntimeError("setBoard() must come before drawing") + now = self.clock() if now is None else now + return self.board.scene(self.pieces, positions=self.animator.positions(now), + labels=self.labels, panels=self.panels, lights=self.boardLights, + aspect=self.width / float(self.height), tint=self.boardTint) + + def frame(self, now=None, present=True): + """Nothing to do per frame: the relay draws on the page's own frames.""" + + def drawScene(self, scene, present=True): + """Draw a complete Scene, for games that build their own each frame: + its shapes and lights go as the board, its labels and panels as the + HUD, its camera as the view; only what changed since the last frame + is sent.""" + scene.checkLimits() + messages = [ + (BOARD, encodeBoard(scene.shapes, scene.lights)), + (PIECES, encodePieces(_NO_BOARD, (), {}, 0.0)), + (HUD, encodeHud(scene.labels, scene.panels)), + ] + if scene.camera is not None: + messages.append((VIEW, encodeView(scene.camera, scene.clearColor))) + for kind, message in messages: + if self.lastSent.get(kind) != message: + self._send(message, kind) + + def _sendView(self): + if self.board is not None: + self._send(encodeView(self.camera()), VIEW) + + # -- the window + + def pollEvents(self): + """Every event since the last poll (Event objects; see EVENTS).""" + return [Event(e) for e in self.relay.poll()] + + def resize(self, width, height): + self.width, self.height = width, height + self._sendView() + + def savePng(self, path): + raise Unavailable("screenshots of the web view are taken by the page (canvas.toBlob)") + + def close(self): + self.relay.close() + + +class _NoBoard: + # what encodePieces needs to send "no pieces" for drawScene + @staticmethod + def visible(column, row): + return False + + @staticmethod + def bridgePairs(pieces): + return [] + + +_NO_BOARD = _NoBoard() + + +# -- pygame events, so a game's 2D handlers work in 3D + +# USB HID usage id -> pygame key name (pygame.key.key_code takes these). +_KEY_NAMES = {40: "return", 41: "escape", 42: "backspace", 43: "tab", 44: "space", 45: "-", 46: "=", + 47: "[", 48: "]", 49: "\\", 51: ";", 52: "'", 53: "`", 54: ",", 55: ".", 56: "/", + 74: "home", 75: "page up", 76: "delete", 77: "end", 78: "page down", + 79: "right", 80: "left", 81: "down", 82: "up", + 224: "left ctrl", 225: "left shift", 226: "left alt", 227: "left meta", + 228: "right ctrl", 229: "right shift", 230: "right alt", 231: "right meta"} +_KEY_NAMES.update({4 + i: chr(97 + i) for i in range(26)}) +_KEY_NAMES.update({30 + i: str((i + 1) % 10) for i in range(10)}) +_KEY_NAMES.update({58 + i: "f%d" % (i + 1) for i in range(12)}) +# SDL3 modifier bits; pygame's KMOD_* (SDL2's) use the same bits for these. +_MODS = (0x1, 0x2, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000) + + +def pygameKey(scancode, pygame): + """The pygame key constant for a Strata (USB HID) scancode, or 0.""" + name = _KEY_NAMES.get(scancode) + try: + return pygame.key.key_code(name) if name else 0 + except (ValueError, AttributeError): + return 0 + + +def toPygameEvents(events, pygame, keys=False, pointer=True, fingers=True): + """pygame events for relay (or desktop Strata) events: KEYDOWN, KEYUP and + TEXTINPUT; MOUSEBUTTONDOWN/UP, MOUSEMOTION and MOUSEWHEEL; FINGERDOWN, + FINGERUP and FINGERMOTION (a cancelled finger is a FINGERUP); and + VIDEORESIZE. Keys are off by default: under pygbag, pygame's own SDL + already gets them (it listens on the whole page), so posting them too + would double every key. The pointer is on: the relay's canvas covers + pygame's, so its mouse and touch never reach SDL.""" + out = [] + for e in events: + t = e.type + kind = getattr(e, "pointer", "") or "" + if keys and t in (EVENT_KEY_DOWN, EVENT_KEY_UP): + mod = 0 + for bit in _MODS: + if getattr(e, "modifiers", 0) & bit: + mod |= bit + key = getattr(e, "key", "") or "" + out.append(pygame.event.Event( + pygame.KEYDOWN if t == EVENT_KEY_DOWN else pygame.KEYUP, + key=pygameKey(e.scancode, pygame), scancode=e.scancode, mod=mod, + unicode=key if len(key) == 1 else "")) + elif keys and t == EVENT_TEXT_INPUT: + out.append(pygame.event.Event(pygame.TEXTINPUT, text=e.text)) + elif pointer and t in (EVENT_MOUSE_BUTTON_DOWN, EVENT_MOUSE_BUTTON_UP): + out.append(pygame.event.Event( + pygame.MOUSEBUTTONDOWN if t == EVENT_MOUSE_BUTTON_DOWN else pygame.MOUSEBUTTONUP, + pos=(int(e.x), int(e.y)), button=e.button, touch=kind == "touch")) + elif pointer and t == EVENT_MOUSE_MOTION: + out.append(pygame.event.Event( + pygame.MOUSEMOTION, pos=(int(e.x), int(e.y)), + rel=(int(getattr(e, "dx", 0)), int(getattr(e, "dy", 0))), + buttons=(0, 0, 0), touch=kind == "touch")) + elif pointer and t == EVENT_MOUSE_WHEEL: + out.append(pygame.event.Event(pygame.MOUSEWHEEL, x=e.x, y=e.y, flipped=False)) + elif fingers and t in (EVENT_FINGER_DOWN, EVENT_FINGER_UP, EVENT_FINGER_MOTION, + EVENT_FINGER_CANCELED): + fingerKind = {EVENT_FINGER_DOWN: pygame.FINGERDOWN, + EVENT_FINGER_MOTION: pygame.FINGERMOTION}.get(t, pygame.FINGERUP) + out.append(pygame.event.Event( + fingerKind, x=e.nx, y=e.ny, dx=getattr(e, "dx", 0), dy=getattr(e, "dy", 0), + finger_id=e.id, touch_id=0, pressure=getattr(e, "pressure", 0) or 1.0)) + elif t == EVENT_RESIZED: + out.append(pygame.event.Event(pygame.VIDEORESIZE, size=(e.width, e.height), + w=e.width, h=e.height)) + return out diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py new file mode 100644 index 0000000..6f7381b --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py @@ -0,0 +1,319 @@ +"""grid3d's shared helpers: picking, text, buttons, the Graphik stand-in, and +the board's options (own tiles, merged tiles, a viewport, the hover slab, +bridge pairs). Pure Python, no GPU.""" + +import math + +import pytest + +from preponderous.graphik import Graphik +from preponderous.graphik.grid3d import ( + BED_TOP, + CUBE, + SPHERE, + Button, + GridBoard, + Piece, + PieceStyle, + ScreenRecorder, + Theme, + Tile, + Viewport, + centredLabel, + cellScreenPosition, + fitText, + hoverColor, + measureText, + pickCell, + pickPoint, + projectToScreen, + wrapText, +) + + +def chainTheme(): + return Theme( + pieces={ + "pawn": PieceStyle(SPHERE, (0.9, 0.2, 0.2)), + "body": PieceStyle(SPHERE, (0.4, 0.8, 0.4), tones=(0.92, 0.78)), + } + ) + + +# -- picking + + +@pytest.mark.parametrize("size", [(800, 600), (600, 800), (1280, 720)]) +@pytest.mark.parametrize("columns,rows", [(3, 3), (8, 5), (20, 30)]) +def test_projecting_a_cells_centre_and_picking_it_back_finds_that_cell(size, columns, rows): + width, height = size + board = GridBoard(columns, rows) + camera = board.camera(width / float(height)) + for row in range(rows): + for column in range(columns): + at = cellScreenPosition(camera, board, column, row, width, height) + assert at is not None + assert pickCell(camera, board, at[0], at[1], width, height) == (column, row) + + +def test_a_point_behind_the_camera_has_no_screen_position(): + board = GridBoard(4, 4) + camera = board.camera() + behind = tuple(2 * e - t for e, t in zip(camera.eye, camera.target)) + assert projectToScreen(camera, behind, 800, 600) is None + + +def test_the_cameras_target_lands_in_the_middle_of_the_window(): + camera = GridBoard(5, 5).camera(4 / 3.0) + x, y = projectToScreen(camera, camera.target, 800, 600) + assert (x, y) == pytest.approx((400, 300)) + + +def test_pixels_off_the_board_or_above_the_horizon_pick_no_cell(): + board = GridBoard(3, 3) + camera = board.camera(800 / 600.0) + assert pickCell(camera, board, 5, 5, 800, 600) is None + assert pickCell(camera, board, 795, 595, 800, 600) is None + assert pickCell(camera, board, None, None, 800, 600) is None + # the top row of pixels of a camera tilted down still meets the plane far + # away; one looking level never does + level = type(camera)(eye=(0.0, 1.0, 5.0), target=(0.0, 1.0, 0.0)) + assert pickPoint(level, 400, 100, 800, 600) is None + + +def test_the_gap_between_two_tiles_belongs_to_a_cell(): + board = GridBoard(2, 1, Theme(tileGap=0.2)) + camera = board.camera(1.0) + # the world point exactly between the two tiles' centres, just right of it + at = projectToScreen(camera, (0.001, BED_TOP, 0.0), 600, 600) + assert pickCell(camera, board, at[0], at[1], 600, 600) == (1, 0) + + +# -- text + + +def test_text_is_one_pixel_size_wide_per_character_as_strata_draws_it(): + assert measureText("Score", 10) == 50 + assert measureText("", 10) == 0 + # a non-ASCII character is still one cell (Strata draws one '?') + assert measureText("café", 8) == 32 + # several lines: the longest one + assert measureText("ab\nabcd\nabc", 5) == 20 + + +def test_fit_text_cuts_with_an_ellipsis(): + assert fitText("short", 900, 10) == "short" + cut = fitText("x" * 200, 236, 10) + assert cut.endswith("...") and len(cut) == 20 + + +def test_wrapping_packs_words_greedily_and_keeps_empty_lines_and_long_words(): + assert wrapText("the quick brown fox", 90, 10) == ["the quick", "brown fox"] + assert wrapText(["one two", "", "three"], 30, 10) == ["one", "two", "", "three"] + assert wrapText("a supercalifragilistic word", 60, 10) == ["a", "supercalifragilistic", "word"] + assert wrapText("line one\nline two", 1000, 10) == ["line one", "line two"] + assert wrapText("", 100, 10) == [""] + + +def test_a_centred_label_is_centred_on_its_point(): + label = centredLabel("Hello", 400, 300, 20) + assert label.x + measureText("Hello", 20) / 2 == 400 + assert label.y == 290 + assert centredLabel("Hello", 400, 300, 20, rise=0.45).y == pytest.approx(291) + assert centredLabel("Hello", 400, 300, 20, rise=0).y == 300 + + +# -- buttons + + +@pytest.mark.parametrize("color", [(0, 0, 0), (255, 255, 255), (127, 128, 129), (200, 30, 30), (10, 250, 10)]) +def test_the_hover_lift_is_graphiks(color): + assert hoverColor(color) == Graphik._hoverColor(color) + + +def test_a_button_has_the_2d_buttons_edges(): + button = Button(100, 50, 80, 40, "Go") + assert button.contains((100, 50)) and button.contains((179, 89)) + assert not button.contains((180, 60)) and not button.contains((120, 90)) + assert not button.contains(None) + + +def test_a_button_draws_a_panel_and_a_centred_label_and_lifts_under_the_pointer(): + button = Button(100, 50, 80, 40, "Go", color=(40, 40, 40), textColor=(255, 255, 255), + pixelSize=12, alpha=0.9) + panel, label = button.draw() + assert (panel.x, panel.y, panel.width, panel.height) == (100, 50, 80, 40) + assert panel.color == pytest.approx((40 / 255.0, 40 / 255.0, 40 / 255.0, 0.9)) + assert label.text == "Go" and label.pixelSize == 12 + assert label.x + measureText("Go", 12) / 2 == 140 and label.y + 6 == 70 + assert label.color == (1.0, 1.0, 1.0, 1.0) + hovered, _ = button.draw(pointer=(120, 60)) + assert hovered.color == pytest.approx((75 / 255.0, 75 / 255.0, 75 / 255.0, 0.9)) + + +def test_padding_widens_a_button_about_its_centre_to_fit_its_label(): + button = Button(100, 0, 40, 30, "Play again", pixelSize=10, padding=5) + x, y, width, height = button.rect() + assert width == 110 and x + width / 2 == 120 and (y, height) == (0, 30) + assert button.contains((65, 10)) and not button.contains((64, 10)) + roomy = Button(100, 0, 200, 30, "Go", pixelSize=10, padding=5) + assert roomy.rect() == (100, 0, 200, 30) + + +def test_a_click_on_a_button_runs_its_function(): + pressed = [] + button = Button(0, 0, 10, 10, "x", function=lambda: pressed.append(1)) + assert button.click((5, 5)) and pressed == [1] + assert not button.click((15, 5)) and pressed == [1] + assert not Button(0, 0, 10, 10, "x").click((5, 5)) + + +def test_the_recorder_keeps_what_a_screen_draws_and_clicks_its_buttons(): + recorder = ScreenRecorder(800, 600) + pressed = [] + recorder.drawText("Title", 400, 100, 40, (0, 0, 0, 255)) + recorder.drawRectangle(0, 0, 10, 10, (1, 2, 3)) + recorder.drawButton(300, 400, 200, 50, (90, 90, 90), (255, 255, 255), 30, "Start", + lambda: pressed.append("start")) + assert recorder.texts() == ["Title"] + assert recorder.items[0].color == (0, 0, 0) + assert [b.text for b in recorder.buttons()] == ["Start"] + assert not recorder.click((299, 410)) and pressed == [] + assert recorder.click((300, 400)) and pressed == ["start"] + assert recorder.getGameDisplay().get_size() == (800, 600) + recorder.resize(1024, 768) + assert recorder.getGameDisplay().get_width() == 1024 + recorder.reset() + assert recorder.items == [] + + +# -- the board's options + + +def test_a_boards_own_tiles_colour_and_raise_their_cells(): + soil, grass = (0.5, 0.3, 0.1), (0.2, 0.7, 0.2) + board = GridBoard(2, 1, Theme(frame=None), tiles={(0, 0): Tile(soil), (1, 0): Tile(grass, 0.06)}) + low, high = board.boardShapes() + assert low.color[:3] == soil and high.color[:3] == grass + t = board.theme + assert low.position[1] == BED_TOP - t.tileHeight / 2 and low.scale[1] == t.tileHeight + # a raised tile keeps its bottom where the others' is + assert high.position[1] + high.scale[1] / 2 == pytest.approx(BED_TOP + 0.06) + assert high.position[1] - high.scale[1] / 2 == pytest.approx(BED_TOP - t.tileHeight) + # a plain colour works as a tile too; cells left out keep the checker + mixed = GridBoard(2, 1, Theme(frame=None), tiles={(1, 0): (1.0, 0.0, 0.0)}) + assert [s.color[:3] for s in mixed.boardShapes()] == [Theme().tile, (1.0, 0.0, 0.0)] + + +def test_without_options_a_board_draws_as_in_0_4_0(): + board = GridBoard(3, 2) + shapes = board.boardShapes() + assert len(shapes) == 3 * 2 + 4 + edge = 1.0 - board.theme.tileGap + for shape, (column, row) in zip(shapes, [(c, r) for r in range(2) for c in range(3)]): + cx, cz = board.cellCenter(column, row) + assert shape.position == (cx, BED_TOP - board.theme.tileHeight / 2, cz) + assert shape.scale == (edge, board.theme.tileHeight, edge) + + +def test_merging_draws_a_64_by_64_board_of_one_colour_as_one_box_a_row(): + theme = Theme(alternate=None) + plain = GridBoard(64, 64, theme) + merged = GridBoard(64, 64, theme, mergeTiles=True) + assert len(plain.boardShapes()) == 64 * 64 + 4 + shapes = merged.boardShapes() + assert len(shapes) == 64 + 4 + row = shapes[0] + assert row.position[0] == pytest.approx(0.0) + assert row.scale[0] == pytest.approx(64 - theme.tileGap) + + +def test_merging_joins_only_neighbours_that_look_the_same(): + a, b = (0.2, 0.6, 0.2), (0.1, 0.3, 0.8) + # per row: a a b a / b b b b, and one raised tile breaks a run + tiles = {(0, 0): a, (1, 0): a, (2, 0): b, (3, 0): a} + tiles.update({(c, 1): b for c in range(4)}) + tiles[(2, 1)] = Tile(b, 0.06) + board = GridBoard(4, 2, Theme(frame=None), tiles=tiles, mergeTiles=True) + shapes = board.boardShapes() + widths = [round(s.scale[0] + board.theme.tileGap, 6) for s in shapes] + assert widths == [2, 1, 1, 2, 1, 1] + assert shapes[0].position[0] == pytest.approx(-1.0) # the middle of columns 0 and 1 + + +def test_a_64_by_64_checkered_board_has_nothing_to_merge(): + merged = GridBoard(64, 64, mergeTiles=True) + assert len(merged.boardShapes()) == 64 * 64 + 4 + + +def test_merging_respects_the_tint(): + board = GridBoard(8, 8, Theme(alternate=None), mergeTiles=True) + shapes = board.boardShapes(tint=(1.0, 0.0, 0.0)) + assert len(shapes) == 8 + 4 + assert shapes[0].color[0] > board.theme.tile[0] + + +def test_a_viewport_draws_only_its_window_centred_and_framed(): + board = GridBoard(10, 10, Theme(alternate=None), viewport=Viewport.around(5, 5, 1)) + assert board.shownSize() == (3, 3) + shapes = board.boardShapes() + assert len(shapes) == 9 + 4 + assert board.cellCenter(5, 5) == (0.0, 0.0) + assert board.cellCenter(4, 4) == (-1.0, -1.0) + # the frame goes round the window + assert shapes[9].scale[0] == pytest.approx(3 + 2 * board.theme.frameWidth) + # the camera fits the window, not the board + assert board.camera(1.0) == GridBoard(3, 3).camera(1.0) + + +def test_a_viewport_past_the_edge_leaves_off_board_cells_empty(): + board = GridBoard(10, 10, Theme(alternate=None), viewport=Viewport.around(0, 0, 2)) + tiles = [s for s in board.boardShapes()][:-4] + assert len(tiles) == 3 * 3 # only cells (0..2, 0..2) are on the board + assert not board.visible(-1, 0) and board.visible(2, 2) and not board.visible(3, 0) + + +def test_a_viewport_leaves_out_pieces_outside_it_and_picks_board_cells(): + board = GridBoard(10, 10, chainTheme(), viewport=Viewport(4, 4, 3, 3)) + inside, outside = Piece("in", 5, 6, "pawn"), Piece("out", 0, 0, "pawn") + board.checkPieces([inside, outside]) + shapes, _ = board.pieceShapes([inside, outside]) + assert len(shapes) == 1 + assert (shapes[0].position[0], shapes[0].position[2]) == board.cellCenter(5, 6) + camera = board.camera(1.0) + at = cellScreenPosition(camera, board, 5, 6, 600, 600) + assert pickCell(camera, board, at[0], at[1], 600, 600) == (5, 6) + + +def test_a_highlight_lays_a_slab_on_the_tile_last(): + board = GridBoard(3, 3, Theme(tileGap=0.12)) + plain = board.scene() + lit = board.scene(highlight=(2, 0)) + assert len(lit.shapes) == len(plain.shapes) + 1 + slab = lit.shapes[-1] + assert slab.kind == CUBE + assert (slab.position[0], slab.position[2]) == (1.0, -1.0) + assert slab.position[1] == pytest.approx(BED_TOP + 0.005) + assert slab.scale == pytest.approx((0.88, 0.01, 0.88)) + assert slab.color == (1.0, 0.86, 0.35, 1.0) + other = board.scene(highlight=(0, 0), highlightColor=(0.0, 1.0, 0.0)) + assert other.shapes[-1].color == (0.0, 1.0, 0.0, 1.0) + assert board.highlightShapes((5, 5)) == [] and board.highlightShapes(None) == [] + + +def test_a_highlight_sits_on_a_raised_tile(): + board = GridBoard(1, 1, tiles={(0, 0): Tile((0.2, 0.6, 0.2), 0.06)}) + assert board.highlightShapes((0, 0))[0].position[1] == pytest.approx(BED_TOP + 0.065) + + +def test_bridge_pairs_name_the_joined_pieces_in_drawing_order(): + board = GridBoard(6, 6, chainTheme()) + snake = [Piece(("s", i), 2 + i, 2, "body", chain="s", link=i) for i in range(3)] + loose = Piece("x", 0, 0, "body", chain="s", link=5) # not the next link + pairs = board.bridgePairs(snake + [loose]) + assert [(a.id, b.id) for a, b in pairs] == [(("s", 0), ("s", 1)), (("s", 1), ("s", 2))] + shapes, _ = board.pieceShapes(snake) + where = {p.id: board.cellCenter(p.column, p.row) for p in snake} + bridges = [board.bridgeShape(a, b, where[a.id], where[b.id]) for a, b in pairs] + assert shapes[-2:] == bridges + assert board._bridges(snake, where) == bridges # the 0.4.0 name still works diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py new file mode 100644 index 0000000..f90a808 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py @@ -0,0 +1,467 @@ +"""grid3d's browser backend: the grid relay's wire format (Strata's +web/kit/grid-relay/WIRE.md, format 1.0), Grid3DWebView against a recording +relay, the event adapter and the pygbag page template. No browser needed.""" + +import base64 +import json +import struct +import sys +import types + +import pygame +import pytest + +from preponderous.graphik.grid3d import ( + CAPSULE, + CUBE, + SPHERE, + Camera, + Grid3DView, + GridBoard, + Label, + Light, + Panel, + Piece, + PieceStyle, + Scene, + Shape, + Theme, + Unavailable, +) +from preponderous.graphik.grid3d import web + + +def theme(): + def eyes(piece, x, z, baseY): + return [Shape(SPHERE, (x + 0.2, baseY + 0.4, z - 0.3), (0.1, 0.1, 0.1), (1, 1, 1, 1))] + + return Theme( + pieces={ + "head": PieceStyle(SPHERE, (0.9, 0.2, 0.2), extras=eyes), + "body": PieceStyle(SPHERE, (0.4, 0.8, 0.4), tones=(0.92, 0.78)), + "gem": PieceStyle(CAPSULE, (0.2, 0.9, 0.9), glow=(2.0, 1.5)), + } + ) + + +class Clock: + def __init__(self): + self.now = 100.0 + + def __call__(self): + return self.now + + +# -- the header (WIRE.md: magic, major, minor, kind, flags, reserved) + + +@pytest.mark.parametrize("kind", [web.BOARD, web.PIECES, web.HUD, web.VIEW]) +def test_every_message_starts_with_the_8_byte_version_header(kind): + head = web.header(kind) + assert len(head) == 8 + assert head[:2] == b"G3" and head[:2] == bytes([0x47, 0x33]) + assert head[2] == 1 and head[3] == 0 + assert head[4] == kind and head[5] == 0 and head[6:8] == b"\0\0" + + +def test_another_major_version_is_refused_as_the_relay_refuses_it(): + message = bytearray(web.encodeHud([], [])) + message[2] = 2 + with pytest.raises(web.WireError, match="2.0") as caught: + web.readHeader(bytes(message)) + assert caught.value.status == -2 + assert web.RecordingRelay().send(bytes(message)) == -2 + + +def test_bad_magic_an_unknown_kind_and_a_truncated_header_are_refused(): + with pytest.raises(web.WireError) as caught: + web.readHeader(b"XX\x01\x00\x01\x00\x00\x00") + assert caught.value.status == -1 + unknown = bytearray(web.header(web.HUD)) + unknown[4] = 9 + with pytest.raises(web.WireError) as caught: + web.readHeader(bytes(unknown)) + assert caught.value.status == -4 + with pytest.raises(web.WireError) as caught: + web.readHeader(web.header(web.HUD)[:6]) + assert caught.value.status == -3 + + +def test_a_later_minor_version_is_read_and_its_extra_fields_ignored(): + message = bytearray(web.encodeView(Camera((0.0, 5.0, 5.0), (0.0, 0.0, 0.0)))) + message[3] = 3 + kind, view = web.decode(bytes(message) + b"\x01\x02\x03\x04") + assert kind == web.VIEW and view["fovDegrees"] == pytest.approx(42.0) + + +def test_a_body_shorter_than_its_counts_is_truncated(): + message = web.encodeBoard([Shape(CUBE, (0, 0, 0), (1, 1, 1), (1, 1, 1, 1))]) + with pytest.raises(web.WireError) as caught: + web.decode(message[:-4]) + assert caught.value.status == -3 + + +# -- record and message layouts + + +def test_record_sizes_match_the_spec(): + assert web.SHAPE.size == 48 + assert web.LIGHT.size == 36 + assert web.ANCHOR.size == 16 + assert web.PANEL.size == 32 + assert web.LABEL.size == 32 + assert web.VIEW_BODY.size == 64 + + +def test_a_board_message_lays_out_counts_then_48_byte_shapes_then_36_byte_lights(): + shapes = [Shape(CUBE, (1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (0.1, 0.2, 0.3)), + Shape(SPHERE, (0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (1.0, 1.0, 1.0, 0.5))] + lights = [Light((1.0, 2.0, 3.0), (1.0, 0.5, 0.25), 4.0, 2.0, castShadows=True)] + message = web.encodeBoard(shapes, lights) + assert len(message) == 8 + 8 + 2 * 48 + 36 + assert struct.unpack_from("' % 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 '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 From 2ad651800160b3eca7cd013960e473c67dbaec0f Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 19 Nov 2026 22:39:43 -0700 Subject: [PATCH 2/3] feat: a bare cell in GridBoard's tiles, for boards with holes A cell that a GridBoard's `tiles` maps to None is now left without a tile, so a board drawn from a map of only some cells (an off-grid edge in a game's own close-up) leaves the rest empty. Missing cells still get the theme's checker. An unused import is also dropped from the helper tests. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- .../preponderous/graphik/grid3d/board.py | 19 +++++++++++++------ .../graphik/grid3d/test_grid3d_helpers.py | 5 +++-- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/main/python/preponderous/graphik/grid3d/board.py b/src/main/python/preponderous/graphik/grid3d/board.py index fb1aa19..cc81cc9 100644 --- a/src/main/python/preponderous/graphik/grid3d/board.py +++ b/src/main/python/preponderous/graphik/grid3d/board.py @@ -121,6 +121,9 @@ def style(self, name): ) +_NOT_GIVEN = object() + + @dataclass(frozen=True) class Tile: """One cell's own tile (GridBoard's `tiles`): a 0-1 (r, g, b) colour, and @@ -176,7 +179,8 @@ class GridBoard: """A columns x rows board drawn with a Theme. `tiles` maps (column, row) to a Tile (or a 0-1 colour) for cells whose - tile isn't the theme's checker; the others keep it. `mergeTiles` draws + tile isn't the theme's checker; the others keep it, and a cell mapped + to None has no tile at all. `mergeTiles` draws each run of neighbouring tiles in a row that look the same (colour and raise, after any tint) as one stretched box, so a big board costs a shape per run, not per cell. `viewport` (a Viewport) draws only that @@ -243,10 +247,13 @@ def cellAt(self, x, z): # -- the static part def tileAt(self, column, row): - """The Tile drawn on a visible cell (before any tint).""" + """The Tile drawn on a visible cell (before any tint), or None when + the board's `tiles` leave the cell bare.""" t = self.theme - own = None if self.tiles is None else self.tiles.get((column, row)) - if own is not None: + own = _NOT_GIVEN if self.tiles is None else self.tiles.get((column, row), _NOT_GIVEN) + if own is None: + return None + if own is not _NOT_GIVEN: return own if isinstance(own, Tile) else Tile(tuple(own)) if t.alternate is not None and (column + row) % 2: return Tile(t.alternate) @@ -271,12 +278,12 @@ def boardShapes(self, tint=None, tintAmount=0.55): run = None # [first column, last column, color, raised] for shownColumn in range(columns): column = originColumn + shownColumn - if not self.contains(column, row): + tile = self.tileAt(column, row) if self.contains(column, row) else None + if tile is None: if run is not None: shapes.append(self._tileShape(run, row, edge)) run = None continue - tile = self.tileAt(column, row) color = tile.color if tint is not None: color = tuple( diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py index 6f7381b..0de795f 100644 --- a/src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_helpers.py @@ -2,8 +2,6 @@ the board's options (own tiles, merged tiles, a viewport, the hover slab, bridge pairs). Pure Python, no GPU.""" -import math - import pytest from preponderous.graphik import Graphik @@ -203,6 +201,9 @@ def test_a_boards_own_tiles_colour_and_raise_their_cells(): # a plain colour works as a tile too; cells left out keep the checker mixed = GridBoard(2, 1, Theme(frame=None), tiles={(1, 0): (1.0, 0.0, 0.0)}) assert [s.color[:3] for s in mixed.boardShapes()] == [Theme().tile, (1.0, 0.0, 0.0)] + # and a cell mapped to None is left bare + bare = GridBoard(3, 1, Theme(frame=None), tiles={(1, 0): None}, mergeTiles=True) + assert [s.position[0] for s in bare.boardShapes()] == [-1.0, 1.0] def test_without_options_a_board_draws_as_in_0_4_0(): From fbad22b642995aa455be2b4b78764772457ebd29 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 19 Nov 2026 22:51:15 -0700 Subject: [PATCH 3/3] feat: fetch Strata's prebuilt grid relay at a game's build time A browser can't fetch GitHub release assets cross-origin, so the grid relay has to be served with the game. grid3d.relay (`python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest build/web`) is added for a game's browser build: it 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 pygbag page, leaving files already there (pygbag's index.html) alone and refusing members that would land outside the folder. The README gives the browser.yml steps; web.py and the page template point at it. Standard library only; tested against tarballs made in the tests. 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 | 13 +- .../preponderous/graphik/grid3d/relay.py | 144 ++++++++++++++++++ .../graphik/grid3d/templates/pygbag.tmpl | 6 +- .../python/preponderous/graphik/grid3d/web.py | 7 +- .../graphik/grid3d/test_grid3d_relay.py | 107 +++++++++++++ 5 files changed, 271 insertions(+), 6 deletions(-) create mode 100644 src/main/python/preponderous/graphik/grid3d/relay.py create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py diff --git a/README.md b/README.md index b6e892d..a491fb4 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,18 @@ 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. Put the relay's build from Strata's web kit (`grid-relay-scene.js`, `grid-relay-scene.wasm`, `strata-loader.js`, `strata-kit.js`, `grid-relay.js`) next to the built page. 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 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. + +In a game's `browser.yml`, where graphik is installed into `src/` for pygbag: + +```yaml + - name: Build with pygbag, on graphik's 3D page template + run: | + TEMPLATE="$(PYTHONPATH=src python -c 'from preponderous.graphik.grid3d.web import templatePath; print(templatePath())')" + python -m pygbag --build --template "$TEMPLATE" --title "My game" src + - name: Add Strata's grid relay next to the page + run: PYTHONPATH=src python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest src/build/web +``` ## Dependencies - pygame diff --git a/src/main/python/preponderous/graphik/grid3d/relay.py b/src/main/python/preponderous/graphik/grid3d/relay.py new file mode 100644 index 0000000..80eee58 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/relay.py @@ -0,0 +1,144 @@ +"""Fetch Strata's prebuilt grid relay for a game's pygbag build. + +A browser can't download GitHub release assets cross-origin, so the relay +has to be served with the game. Strata's release tarball +(strata--wasm32-emscripten.tar.gz) carries it prebuilt under +kit/grid-relay/dist/: the relay scene's .js and .wasm, strata-kit.js, +strata-loader.js, grid-relay.js and its page files. At build time, after +`pygbag --build`, run: + + python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest src/build/web + +It downloads the tarball and the release's SHA256SUMS, checks the tarball +against it, and copies kit/grid-relay/dist/ into `--dest`, next to the +page pygbag built from grid3d's template (web.templatePath()). Files that +already exist there (pygbag's own index.html, say) are left alone, so the +relay's test page never replaces the game's. Nothing of the relay is +downloaded by a player until the page's 3D toggle asks for it. + +Standard library only. +""" + +import argparse +import hashlib +import io +import os +import posixpath +import shutil +import sys +import tarfile +import urllib.request + +RELEASES = "https://github.com/Preponderous-Software/strata/releases/download" +DIST = "kit/grid-relay/dist/" + + +class RelayFetchError(Exception): + """The relay couldn't be fetched, verified or unpacked.""" + + +def tarballName(version): + return "strata-%s-wasm32-emscripten.tar.gz" % version + + +def _download(url): + request = urllib.request.Request(url, headers={"User-Agent": "graphik-grid3d-relay"}) + with urllib.request.urlopen(request, timeout=120) as response: + return response.read() + + +def expectedDigest(sums, name): + """The SHA-256 a SHA256SUMS text gives for `name`.""" + for line in sums.splitlines(): + parts = line.strip().split() + if len(parts) == 2 and parts[1].lstrip("*").split("/")[-1] == name: + return parts[0].lower() + raise RelayFetchError("SHA256SUMS has no line for %s" % name) + + +def verify(data, sums, name): + digest = hashlib.sha256(data).hexdigest() + expected = expectedDigest(sums, name) + if digest != expected: + raise RelayFetchError("%s's SHA-256 is %s, SHA256SUMS says %s" % (name, digest, expected)) + + +def extractDist(data, dest, prefix=DIST): + """Copy the tarball's `prefix` tree into `dest`; returns (copied, + skipped) relative paths. Existing files are skipped, and members that + aren't plain files and directories, or would land outside `dest`, are + refused.""" + copied, skipped = [], [] + dest = os.path.abspath(dest) + with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive: + for member in archive.getmembers(): + name = member.name[2:] if member.name.startswith("./") else member.name + if prefix in name + "/" and (".." in name.split("/") or name.startswith("/")): + raise RelayFetchError("refusing %s: outside the relay's folder" % member.name) + name = posixpath.normpath(name) + # the tarball may keep everything under a top-level folder + at = (name + "/").find(prefix) + if at < 0 or (at and not name[:at].endswith("/")): + continue + relative = name[at + len(prefix):] + if not relative: + continue + if relative.startswith("../") or os.path.isabs(relative) or "/../" in "/" + relative: + raise RelayFetchError("refusing %s: outside the relay's folder" % member.name) + target = os.path.abspath(os.path.join(dest, relative)) + if not target.startswith(dest + os.sep): + raise RelayFetchError("refusing %s: outside %s" % (member.name, dest)) + if member.isdir(): + os.makedirs(target, exist_ok=True) + continue + if not member.isfile(): + raise RelayFetchError("refusing %s: not a plain file" % member.name) + if os.path.exists(target): + skipped.append(relative) + continue + os.makedirs(os.path.dirname(target), exist_ok=True) + with archive.extractfile(member) as source, open(target, "wb") as out: + shutil.copyfileobj(source, out) + copied.append(relative) + if not copied and not skipped: + raise RelayFetchError("the tarball has nothing under %s" % prefix) + return copied, skipped + + +def fetchRelay(version, dest, base=RELEASES, download=None): + """Download, verify and unpack Strata `version`'s grid relay into + `dest`. Returns (copied, skipped).""" + download = download or _download + name = tarballName(version) + root = "%s/v%s/" % (base.rstrip("/"), version) + try: + sums = download(root + "SHA256SUMS").decode("utf-8") + data = download(root + name) + except OSError as error: + raise RelayFetchError("couldn't download Strata %s's release: %s" % (version, error)) + verify(data, sums, name) + os.makedirs(dest, exist_ok=True) + return extractDist(data, dest) + + +def main(argv=None): + parser = argparse.ArgumentParser( + prog="python -m preponderous.graphik.grid3d.relay", + description="Copy Strata's prebuilt grid relay next to a pygbag build.") + parser.add_argument("--strata", required=True, help="Strata release version, e.g. 0.9.0") + parser.add_argument("--dest", required=True, help="the pygbag output folder (build/web)") + parser.add_argument("--base", default=RELEASES, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + try: + copied, skipped = fetchRelay(args.strata, args.dest, args.base) + except RelayFetchError as error: + print("grid relay: %s" % error, file=sys.stderr) + return 1 + print("grid relay: Strata %s, %d files copied to %s" % (args.strata, len(copied), args.dest)) + for path in skipped: + print("grid relay: kept the existing %s" % path) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl index 502659e..c718106 100644 --- a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -435,8 +435,10 @@ frameborder="1" preponderous.graphik.grid3d.web, and a toggle between the 2D and 3D views. Nothing of the 3D view is downloaded until the toggle is pressed; while it loads, and whenever it can't (too big, no WebGL 2, the engine failed), the - 2D canvas stays on screen. Put the relay's build (grid-relay-scene.js and - .wasm, strata-loader.js, strata-kit.js, grid-relay.js) next to this page. --> + 2D canvas stays on screen. The relay's files (grid-relay-scene.js and + .wasm, strata-loader.js, strata-kit.js, grid-relay.js) go next to this + page: `python -m preponderous.graphik.grid3d.relay` copies them from + Strata's release at build time. --> diff --git a/src/main/python/preponderous/graphik/grid3d/web.py b/src/main/python/preponderous/graphik/grid3d/web.py index 6e8c099..5376280 100644 --- a/src/main/python/preponderous/graphik/grid3d/web.py +++ b/src/main/python/preponderous/graphik/grid3d/web.py @@ -26,9 +26,10 @@ The page: TEMPLATE (templatePath()) is a pygbag page template carrying the relay's canvas and scripts and a 3D toggle. Build with -`pygbag --template ...` and put the relay's build -(grid-relay-scene.js and .wasm, strata-loader.js, strata-kit.js, -grid-relay.js, from Strata's web kit) next to the built page. Nothing of +`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. diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py new file mode 100644 index 0000000..ef94d76 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py @@ -0,0 +1,107 @@ +"""Fetching Strata's prebuilt grid relay for a pygbag build (relay.py), +against tarballs made here: no network.""" + +import hashlib +import io +import os +import tarfile + +import pytest + +from preponderous.graphik.grid3d import relay + +DIST_FILES = { + "grid-relay-scene.js": b"// scene", + "grid-relay-scene.wasm": b"\0asm", + "grid-relay.js": b"// relay", + "strata-kit.js": b"// kit", + "strata-loader.js": b"// loader", + "index.html": b"relay test page", +} + + +def tarball(files, top="strata-0.9.0-wasm32-emscripten/", extra=()): + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as archive: + def add(name, data): + info = tarfile.TarInfo(name) + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + add(top + "lib/libstrata.a", b"not the relay") + add(top + "kit/grid-relay/main.cpp", b"// source") + for name, data in files.items(): + add(top + relay.DIST + name, data) + for name, data in extra: + add(name, data) + return buffer.getvalue() + + +def release(data, version="0.9.0", digest=None): + name = relay.tarballName(version) + sums = "%s %s\n%s other.zip\n" % (digest or hashlib.sha256(data).hexdigest(), name, "0" * 64) + files = {"SHA256SUMS": sums.encode(), name: data} + calls = [] + + def download(url): + calls.append(url) + return files[url.rsplit("/", 1)[1]] + + return download, calls + + +def test_the_relay_is_downloaded_verified_and_copied_next_to_the_page(tmp_path): + download, calls = release(tarball(DIST_FILES)) + web = tmp_path / "build" / "web" + web.mkdir(parents=True) + (web / "index.html").write_bytes(b"the game") + copied, skipped = relay.fetchRelay("0.9.0", str(web), download=download) + assert calls == [relay.RELEASES + "/v0.9.0/SHA256SUMS", + relay.RELEASES + "/v0.9.0/strata-0.9.0-wasm32-emscripten.tar.gz"] + assert sorted(copied) == sorted(n for n in DIST_FILES if n != "index.html") + assert skipped == ["index.html"] + # the game's page is kept; only the relay's files are added + assert (web / "index.html").read_bytes() == b"the game" + assert (web / "grid-relay-scene.wasm").read_bytes() == b"\0asm" + assert not (web / "main.cpp").exists() and not (web / "libstrata.a").exists() + + +def test_a_tarball_that_doesnt_match_sha256sums_is_refused(tmp_path): + download, _ = release(tarball(DIST_FILES), digest="ab" * 32) + with pytest.raises(relay.RelayFetchError, match="SHA-256"): + relay.fetchRelay("0.9.0", str(tmp_path), download=download) + assert os.listdir(tmp_path) == [] + + +def test_sha256sums_without_the_tarball_is_refused(): + with pytest.raises(relay.RelayFetchError, match="no line"): + relay.expectedDigest("00 something-else.tar.gz\n", relay.tarballName("0.9.0")) + + +def test_a_tarball_without_the_relay_is_refused(tmp_path): + download, _ = release(tarball({})) + with pytest.raises(relay.RelayFetchError, match="nothing under"): + relay.fetchRelay("0.9.0", str(tmp_path), download=download) + + +def test_members_escaping_the_destination_are_refused(tmp_path): + evil = tarball(DIST_FILES, extra=[("x/" + relay.DIST + "../../../../escape.js", b"bad")]) + download, _ = release(evil) + with pytest.raises(relay.RelayFetchError, match="refusing"): + relay.fetchRelay("0.9.0", str(tmp_path / "web"), download=download) + assert not (tmp_path / "escape.js").exists() + + +def test_the_command_line_copies_the_relay_and_reports_failures_plainly(tmp_path, capsys, monkeypatch): + download, _ = release(tarball(DIST_FILES)) + monkeypatch.setattr(relay, "_download", download) + assert relay.main(["--strata", "0.9.0", "--dest", str(tmp_path)]) == 0 + assert "6 files copied" in capsys.readouterr().out + assert relay.main(["--strata", "0.9.0", "--dest", str(tmp_path)]) == 0 + assert "kept the existing grid-relay.js" in capsys.readouterr().out + + def offline(url): + raise OSError("no network") + + monkeypatch.setattr(relay, "_download", offline) + assert relay.main(["--strata", "0.9.0", "--dest", str(tmp_path)]) == 1 + assert "no network" in capsys.readouterr().err