diff --git a/README.md b/README.md index 4d1a0f0..8d3dbde 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.3.0.zip" +pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.4.0.zip" ``` In a `requirements.txt`, use the same line without the quotes. See [RELEASING.md](RELEASING.md) for how releases are cut. @@ -84,8 +84,45 @@ Color constants: `Graphik.black`, `Graphik.white`, `Graphik.red`, `Graphik.green An alpha component in a fill color (`(r, g, b, a)`) does not make `drawRectangle` or `drawButton`'s box translucent: on the display the shape is painted opaquely whatever `a` is, and on a surface with per-pixel alpha (`pygame.SRCALPHA`) the color's alpha replaces the pixels' own rather than blending over them. `drawText`'s `color` and `drawButton`'s `colorText` ignore an alpha component altogether: the text is painted as if `a` were 255, on the display and on a per-pixel alpha surface alike (only the antialiased glyph edges blend with what is underneath). +## 3D grid view (optional) + +`preponderous.graphik.grid3d` draws a grid game's board in 3D with +[Strata](https://github.com/Preponderous-Software/strata): tiles, a frame, and +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: + +```bash +pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.4.0.zip" +``` + +```python +from preponderous.graphik.grid3d import ( + SPHERE, Grid3DView, GridBoard, Label, Piece, PieceStyle, Theme, Unavailable, +) + +theme = Theme(pieces={"pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2))}) +try: + view = Grid3DView.open(900, 700, "My game") +except Unavailable as reason: + print("No 3D here:", reason) # keep the 2D game +else: + view.setBoard(GridBoard(8, 8, theme)) + view.setPieces([Piece("p1", 3, 4, "pawn")], tickSeconds=0.15) # once per tick + view.setLabels([Label("Score: 0", 18, 16, 24)]) # when it changes + view.frame() # once per frame +``` + +- `Piece(id, column, row, style)`: keep `id` stable so the piece slides; `chain`/`link` join neighbouring pieces (a snake's body); `interpolate=False` makes it jump; `scale`, `color` and `facing` vary one piece. +- `PieceStyle(kind, color, height, size, lift, glow, tones, extras)`: `glow` adds a point light; `extras` draws decorations such as eyes. +- `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. + ## Dependencies - pygame +- optional: `strata-engine` 0.7.0 for the 3D grid view (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 a65834e..42db9c7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,13 @@ classifiers = [ [project.optional-dependencies] test = ["pytest"] +# The 3D grid view (preponderous.graphik.grid3d) draws with Strata's Python +# binding. It isn't on PyPI, so it is installed from the Strata release tag; +# graphik itself is installed from tag archives too, never from PyPI, so a +# direct reference here is allowed. +strata = [ + "strata-engine @ git+https://github.com/Preponderous-Software/strata@v0.8.0#subdirectory=bindings/python", +] [project.urls] Homepage = "https://github.com/Stephenson-Software/graphik" diff --git a/src/main/python/preponderous/graphik/_version.py b/src/main/python/preponderous/graphik/_version.py index 493f741..6a9beea 100644 --- a/src/main/python/preponderous/graphik/_version.py +++ b/src/main/python/preponderous/graphik/_version.py @@ -1 +1 @@ -__version__ = "0.3.0" +__version__ = "0.4.0" diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py new file mode 100644 index 0000000..e472a09 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -0,0 +1,46 @@ +"""graphik's 3D grid view: a grid game's board drawn in 3D with Strata. + +A game describes its board once (GridBoard + Theme), reports what stands on +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. + +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 .scene import ( + 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, +) +from .view import STRATA_VERSION, Grid3DView, Unavailable + +__all__ = [ + "Animator", "interpolatePosition", + "BED_TOP", "GridBoard", "Piece", "PieceStyle", "Theme", "cellCenter", "fitCamera", + "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", + "STRATA_VERSION", "Grid3DView", "Unavailable", +] diff --git a/src/main/python/preponderous/graphik/grid3d/animate.py b/src/main/python/preponderous/graphik/grid3d/animate.py new file mode 100644 index 0000000..75be1c1 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/animate.py @@ -0,0 +1,80 @@ +"""Smooth piece movement between game ticks. + +A game moves pieces a whole cell per tick; the screen redraws many times in +between. Animator remembers where each piece was drawn and slides it to its +new cell over one tick, so motion is smooth at any frame rate while the game +only reports cell positions. Pure Python: positions are world (x, z) pairs. +""" + + +def lerp(a, b, t): + return a + (b - a) * t + + +def interpolatePosition(start, end, alpha): + """World (x, z) a fraction `alpha` (clamped to 0-1) of the way from start + to end.""" + alpha = 0.0 if alpha < 0.0 else 1.0 if alpha > 1.0 else alpha + return (lerp(start[0], end[0], alpha), lerp(start[1], end[1], alpha)) + + +class Animator: + """Tracks pieces by id and gives each one's position at a given time. + + A piece slides from where it was last drawn to the centre of its new cell + over `tickSeconds`. It jumps instead when it is new, when it opted out + (Piece.interpolate is False), when it moved further than `maxSlideCells` + in one tick (a teleport or wrap-around would otherwise slide across the + board), when reducedMotion is on, or when the whole tick is a snap (a + restart or a new level, where nothing should slide from the old board). + """ + + def __init__(self, cellCenter, reducedMotion=False, maxSlideCells=1.5): + self.cellCenter = cellCenter + self.reducedMotion = reducedMotion + self.maxSlideCells = maxSlideCells + self.tracks = {} # id -> (start, end) + self.startedAt = 0.0 + self.tickSeconds = 0.0 + + def update(self, pieces, now, tickSeconds, snap=False): + """Take this tick's pieces; `now` is a monotonic time in seconds. + `snap=True` puts every piece straight on its cell.""" + current = {} if snap else self.positions(now) + tracks = {} + for piece in pieces: + end = self.cellCenter(piece.column, piece.row) + start = current.get(piece.id) + # how far it moved is measured cell to cell, not from where it is + # drawn: a tick that comes before the last slide finished is + # still a one-cell step, and still slides + previous = self.tracks.get(piece.id, (None, None))[1] + if ( + start is None + or self.reducedMotion + or not piece.interpolate + or abs(end[0] - previous[0]) + abs(end[1] - previous[1]) + > self.maxSlideCells + ): + start = end + tracks[piece.id] = (start, end) + self.tracks = tracks + self.startedAt = now + self.tickSeconds = max(0.0, tickSeconds) + + def alpha(self, now): + if self.tickSeconds <= 0.0: + return 1.0 + return (now - self.startedAt) / self.tickSeconds + + def positions(self, now): + """id -> world (x, z) of every tracked piece at time `now`.""" + alpha = self.alpha(now) + return { + pieceId: interpolatePosition(start, end, alpha) + for pieceId, (start, end) in self.tracks.items() + } + + def settled(self, now): + """True once every piece has reached its cell.""" + return self.alpha(now) >= 1.0 diff --git a/src/main/python/preponderous/graphik/grid3d/board.py b/src/main/python/preponderous/graphik/grid3d/board.py new file mode 100644 index 0000000..736d703 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/board.py @@ -0,0 +1,286 @@ +"""A grid game's board in 3D: tiles, a frame, pieces standing on cells. + +A game says *what* is on each cell with Piece objects; a Theme says *how* +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. +""" + +from dataclasses import dataclass, field +from typing import Callable, Dict, Hashable, List, Optional, Tuple + +from .scene import ( + CUBE, + SPHERE, + Camera, + Light, + Scene, + Shape, + checkLights, + rgba, + shade, +) + +BED_TOP = 0.0 # y of the tiles' top face; pieces stand on it + + +@dataclass +class PieceStyle: + """How one kind of piece looks. + + kind, color, height (y size) and size (x/z footprint, in cells) make the + 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. + """ + + kind: int = CUBE + color: Tuple[float, float, float] = (0.8, 0.8, 0.8) + height: float = 0.5 + size: float = 0.8 + lift: float = 0.0 + glow: Optional[Tuple[float, float]] = None + tones: Optional[Tuple[float, float]] = None + extras: Optional[Callable] = None + + +@dataclass +class Piece: + """Something standing on cell (column, row). + + `id` must stay the same from tick to tick for the same thing, so a view + can animate it from its old cell to its new one. `style` names a + PieceStyle in the Theme. `scale` multiplies the style's footprint and + height (a tapering tail), `color` overrides the style's colour. + + Pieces with the same `chain` and consecutive `link` numbers (a snake's + segments, head first) are joined by a bridge when their cells are + orthogonal neighbours. `facing` is a unit (dx, dz) step for extras that + look somewhere. `interpolate=False` makes the piece jump to its new cell + instead of sliding (teleports, wrap-around). + """ + + id: Hashable + column: int + row: int + style: str + scale: float = 1.0 + color: Optional[Tuple[float, float, float]] = None + chain: Optional[Hashable] = None + link: int = 0 + facing: Tuple[int, int] = (0, 1) + interpolate: bool = True + + +@dataclass +class Theme: + """The look of a board and its pieces. Colours are 0-1 (r, g, b).""" + + tile: Tuple[float, float, float] = (0.22, 0.38, 0.17) + alternate: Optional[Tuple[float, float, float]] = (0.18, 0.32, 0.14) + tileHeight: float = 0.18 + tileGap: float = 0.03 + frame: Optional[Tuple[float, float, float]] = (0.36, 0.22, 0.12) + frameWidth: float = 0.35 + pieces: Dict[str, PieceStyle] = field(default_factory=dict) + # How chained pieces are bridged: footprint across the bridge (a fraction + # of a cell, before the pieces' scale), height as a fraction of the + # pieces' height, and colour shade relative to the piece. + bridgeAcross: float = 0.6 + bridgeHeight: float = 0.8 + bridgeShade: float = 0.85 + + def style(self, name): + try: + return self.pieces[name] + except KeyError: + raise KeyError( + "no PieceStyle named %r in the theme (known: %s)" + % (name, ", ".join(sorted(self.pieces)) or "none") + ) + + +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) + + +def fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0): + """A camera south of the board, tilted down about 55 degrees, far enough + back that the whole board and its frame fit, aiming a little beyond the + centre so the board sits low in the window and leaves the top rows of the + screen for a HUD. A tall window backs the camera off further.""" + size = max(columns, rows) + 1.0 # the frame adds about half a cell a side + size *= max(1.0, 1.0 / max(aspect, 0.5)) + distance = 0.86 * size + 0.9 + return Camera( + eye=(0.0, 1.35 * distance, 0.95 * distance), + target=(0.0, -0.3, -0.04 * size), + fovDegrees=fovDegrees, + ) + + +class GridBoard: + """A columns x rows board drawn with a Theme.""" + + def __init__(self, columns, rows, theme=None): + if columns < 1 or rows < 1: + raise ValueError("a board needs at least one column and one row") + self.columns = columns + self.rows = rows + self.theme = theme or Theme() + + def cellCenter(self, column, row): + return cellCenter(column, row, self.columns, self.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) + + # -- the static part + + 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).""" + 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 + 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 t.frame is not None: + halfW, halfD = self.columns / 2.0, self.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 + 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), + ] + return shapes + + # -- the dynamic part + + def checkPieces(self, pieces): + """Raise ValueError for a piece off the board or a duplicate id, and + KeyError for an unknown style.""" + seen = set() + for piece in pieces: + if piece.id in seen: + raise ValueError("two pieces share the id %r" % (piece.id,)) + seen.add(piece.id) + if not self.contains(piece.column, piece.row): + raise ValueError( + "piece %r is off the %dx%d board at (%d, %d)" + % (piece.id, self.columns, self.rows, piece.column, piece.row) + ) + self.theme.style(piece.style) + + 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.""" + shapes, lights = [], [] + where = {} + for piece in pieces: + x, z = (positions or {}).get(piece.id) or self.cellCenter( + piece.column, piece.row + ) + where[piece.id] = (x, z) + style = self.theme.style(piece.style) + color = piece.color if piece.color is not None else style.color + if style.tones is not None and piece.chain is not None: + color = shade(color, style.tones[0] if piece.link % 2 else style.tones[1]) + size = style.size * piece.scale + height = style.height * (0.75 + 0.25 * piece.scale) + baseY = BED_TOP + style.lift + shapes.append( + Shape( + style.kind, + (x, baseY + height / 2, z), + (size, height, size), + rgba(color), + ) + ) + if style.glow is not None: + radius, intensity = style.glow + lights.append( + Light((x, baseY + height + 0.4, z), tuple(color), radius, intensity) + ) + if style.extras is not None: + shapes.extend(style.extras(piece, x, z, baseY) or []) + shapes.extend(self._bridges(pieces, where)) + return shapes, lights + + def _bridges(self, pieces, where): + t = self.theme + chains = {} + for piece in pieces: + if piece.chain is not None: + chains.setdefault(piece.chain, []).append(piece) + shapes = [] + for members in chains.values(): + members.sort(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 + + # -- 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.""" + pieceShapes, pieceLights = self.pieceShapes(pieces, positions) + scene = Scene(camera=self.camera(aspect)) + scene.shapes = self.boardShapes(tint) + pieceShapes + scene.lights = list(lights) + pieceLights + scene.labels = list(labels) + scene.panels = list(panels) + if clearColor is not None: + scene.clearColor = clearColor + checkLights(scene.lights) + return scene diff --git a/src/main/python/preponderous/graphik/grid3d/scene.py b/src/main/python/preponderous/graphik/grid3d/scene.py new file mode 100644 index 0000000..3b129d1 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/scene.py @@ -0,0 +1,137 @@ +"""A 3D scene as plain data: shapes, screen text and panels, lights, a camera. + +Nothing here imports Strata or pygame, so a game's state-to-scene code can be +built and tested without a GPU. A Grid3DView (view.py) draws a Scene. + +World axes: x runs along a grid's columns, z along its rows (row 0 is the far +edge, away from a camera south of the board), y is up. One cell is one world +unit, and a board is centred on the origin. +""" + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +# Shape kinds. The values match Strata's PRIMITIVE_* constants. +CUBE, CAPSULE, CYLINDER, SPHERE = 0, 1, 2, 3 +SHAPE_KINDS = (CUBE, CAPSULE, CYLINDER, SPHERE) + +# Engine limits (strata.h). A Scene over them is rejected with SceneLimitError +# rather than left for the engine to refuse or truncate. +MAX_POINT_LIGHTS = 32 +MAX_SHADOWED_POINT_LIGHTS = 4 + +TEXT_COLOR = (0.97, 0.96, 0.92, 1.0) +DIM_TEXT_COLOR = (0.82, 0.80, 0.74, 1.0) +CLEAR_COLOR = (0.10, 0.12, 0.16, 1.0) + +Color3 = Tuple[float, float, float] +Color4 = Tuple[float, float, float, float] +Vec3 = Tuple[float, float, float] + + +class SceneLimitError(ValueError): + """A scene asks for more than the engine can draw (see MAX_* above).""" + + +@dataclass +class Shape: + """One of Strata's primitives. Strata 0.7.0 can't rotate primitives, so a + shape is axis-aligned; `scale` is its size along x, y and z.""" + + kind: int + position: Vec3 + scale: Vec3 + color: Color4 + + +@dataclass +class Label: + """Screen text: x/y in pixels from the top-left of the window.""" + + text: str + x: float + y: float + pixelSize: float + color: Color4 = TEXT_COLOR + + +@dataclass +class Panel: + """A filled screen rectangle, in pixels from the top-left, drawn under text.""" + + x: float + y: float + width: float + height: float + color: Color4 = (0.0, 0.0, 0.0, 0.6) + + +@dataclass +class Light: + """A point light. At most MAX_SHADOWED_POINT_LIGHTS may cast shadows.""" + + position: Vec3 + color: Color3 + radius: float + intensity: float + castShadows: bool = False + + +@dataclass +class Camera: + eye: Vec3 + target: Vec3 + fovDegrees: float = 42.0 + + +@dataclass +class Scene: + shapes: List[Shape] = field(default_factory=list) + labels: List[Label] = field(default_factory=list) + panels: List[Panel] = field(default_factory=list) + lights: List[Light] = field(default_factory=list) + camera: Optional[Camera] = None + clearColor: Color4 = CLEAR_COLOR + + def checkLimits(self): + """Raise SceneLimitError if the scene is over an engine limit.""" + checkLights(self.lights) + for shape in self.shapes: + if shape.kind not in SHAPE_KINDS: + raise SceneLimitError("unknown shape kind %r" % (shape.kind,)) + + +def checkLights(lights): + if len(lights) > MAX_POINT_LIGHTS: + raise SceneLimitError( + "%d point lights; Strata draws at most %d" + % (len(lights), MAX_POINT_LIGHTS) + ) + shadowed = sum(1 for light in lights if light.castShadows) + if shadowed > MAX_SHADOWED_POINT_LIGHTS: + raise SceneLimitError( + "%d shadow-casting lights; Strata allows at most %d" + % (shadowed, MAX_SHADOWED_POINT_LIGHTS) + ) + + +def rgb255(color): + """A 0-255 (r, g, b[, a]) colour as 0-1 floats (r, g, b).""" + return (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0) + + +def rgba(color, alpha=1.0): + """(r, g, b) as (r, g, b, alpha).""" + return (color[0], color[1], color[2], alpha) + + +def shade(color, factor): + """Scale a 0-1 colour's r, g, b by `factor`, clamped to 0-1.""" + return tuple(max(0.0, min(1.0, c * factor)) for c in color[:3]) + + +def fitText(text, width, pixelSize, margin=18): + """Cut text to what fits across `width` pixels. Strata's built-in font is + monospaced, about one pixel size wide per character.""" + room = max(4, int((width - 2 * margin) / pixelSize)) + return text if len(text) <= room else text[: room - 3] + "..." diff --git a/src/main/python/preponderous/graphik/grid3d/view.py b/src/main/python/preponderous/graphik/grid3d/view.py new file mode 100644 index 0000000..6cdfe35 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -0,0 +1,223 @@ +"""Grid3DView: draws a GridBoard and its pieces with Strata (desktop). + +The Strata Python binding (`strata-engine`, installed with the +`graphik[strata]` extra) loads libstrata, a native library: a released build +is downloaded once, checked against its pinned SHA-256 and cached, or +STRATA_LIBRARY points at a local build. Strata ships Linux x64 and Windows +x64 libraries, so this view runs there; anywhere else, or when the library +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. + +Usage, once per game: + + view = Grid3DView.open(900, 700, "My game") # or headless=True + view.setBoard(GridBoard(columns, rows, theme)) # when the board changes + view.setPieces(pieces, tickSeconds) # once per game tick + view.setLabels(labels, panels) # when the HUD changes + view.frame() # once per display frame + view.close() + +The board and labels are kept between frames; pieces slide between their +cells over one tick (see animate.Animator). +""" + +import os +import sys +import time + +from .animate import Animator + +STRATA_VERSION = "0.8.0" +STRATA_PLATFORMS = ("linux", "win32") +INSTALL_HINT = "pip install 'graphik[strata]'" + + +class Unavailable(Exception): + """The 3D view can't run here. The message says why, in plain words.""" + + +def loadStrata(platform=None): + """Import the binding and load libstrata; raise Unavailable if either fails.""" + platform = sys.platform if platform is None else platform + if platform not in STRATA_PLATFORMS and not os.environ.get("STRATA_LIBRARY"): + raise Unavailable("Strata has no library for this system (%s)" % platform) + # Headless rendering without a GPU driver (CI, WSL) goes through Mesa's + # software rasteriser; harmless where a GPU exists. + os.environ.setdefault("GALLIUM_DRIVER", "llvmpipe") + try: + import strata + except ImportError: + raise Unavailable( + "the strata-engine package isn't installed (%s)" % INSTALL_HINT + ) + try: + if os.environ.get("STRATA_LIBRARY"): + return strata, strata.load() + return strata, strata.load_release(STRATA_VERSION) + except Exception as error: # download failed, checksum mismatch, bad library + raise Unavailable("the Strata library couldn't be loaded: %s" % error) + + +class Grid3DView: + """One Strata engine (a window, or headless for screenshots and tests).""" + + def __init__(self, strata, lib, engine, width, height, isWindow, + reducedMotion=False, clock=time.monotonic): + self.strata, self.lib, self.engine = strata, lib, engine + self.width, self.height = width, height + self.isWindow = isWindow + self.reducedMotion = reducedMotion + self.clock = clock + self.board = None + self.boardTint = None + self.boardLights = [] + self.pieces = [] + self.labels, self.panels = [], [] + self.animator = None + self.EVENT_QUIT = strata.EVENT_QUIT + self.EVENT_KEY_DOWN = strata.EVENT_KEY_DOWN + self.EVENT_KEY_UP = strata.EVENT_KEY_UP + self.EVENT_RESIZED = strata.EVENT_RESIZED + + @classmethod + 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.""" + 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 + # can't create, so it is only forced here. + os.environ.setdefault("SDL_VIDEODRIVER", "dummy") + strata, lib = loadStrata() + surface = strata.SURFACE_HEADLESS if headless else strata.SURFACE_WINDOW + try: + engine = strata.Engine( + lib, width, height, surface=surface, title=None if headless else title + ) + except Exception as error: # no display, no GPU driver + raise Unavailable("no Strata window could be opened: %s" % error) + view = cls(strata, lib, engine, width, height, not headless, + reducedMotion=reducedMotion, clock=clock) + lighting = lib.lighting_defaults(strata.LIGHTING_SUN) + lighting.shadow_distance = 40.0 + lighting.fog = 0 + engine.set_lighting(lighting) + engine.set_sun_direction((-0.45, 0.85, 0.35)) + return view + + # -- what to draw + + 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) + self.animator = Animator(board.cellCenter, reducedMotion=self.reducedMotion) + self.animator.update(self.pieces, self.clock(), 0.0) + + def setPieces(self, pieces, tickSeconds=0.0, snap=False): + """The dynamic part: call once per game tick. Pieces slide from where + they were drawn to their new cells over `tickSeconds`; `snap=True` + (a restart, a new level) puts them all straight on their cells.""" + if self.board is None: + raise RuntimeError("setBoard() must come before setPieces()") + pieces = list(pieces) + self.board.checkPieces(pieces) + self.pieces = pieces + self.animator.update(pieces, self.clock(), tickSeconds, snap=snap) + + def setLabels(self, labels=(), panels=()): + """Screen text and the panels behind it.""" + self.labels, self.panels = list(labels), list(panels) + + def scene(self, now=None): + """The Scene a frame at `now` would draw (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): + """Draw one frame (pieces at their positions for `now`).""" + self.drawScene(self.scene(now), present=present) + + # -- drawing a Scene + + def drawScene(self, scene, present=True): + """Draw a complete Scene, for callers that build their own.""" + scene.checkLimits() + s, engine = self.strata, self.engine + camera = scene.camera + if camera is not None: + engine.set_camera( + self.lib.look_at( + camera.eye, + camera.target, + fov_y_degrees=camera.fovDegrees, + aspect=self.width / float(self.height), + near_plane=0.3, + far_plane=200.0, + ) + ) + lights = [] + for light in scene.lights: + point = s.PointLight() + point.position = light.position + point.color = light.color + point.range = light.radius + point.intensity = light.intensity + point.flags = s.POINT_LIGHT_CAST_SHADOWS if light.castShadows else 0 + lights.append(point) + engine.set_point_lights(lights) + engine.begin_frame(clear_color=scene.clearColor) + engine.submit_primitives( + [s.RenderItem(sh.kind, sh.position, sh.scale, sh.color) for sh in scene.shapes] + ) + if scene.panels: + engine.submit_rects( + [s.Rect(p.x, p.y, p.width, p.height, p.color) for p in scene.panels] + ) + if scene.labels: + engine.submit_text( + [ + s.Text(l.x, l.y, l.pixelSize, s.TEXT_SHADOW, l.color, + l.text.encode("utf-8")) + for l in scene.labels + ] + ) + engine.end_frame() + if present: + engine.present() + + # -- the window + + def pollEvents(self): + """Every pending Strata event (EVENT_QUIT, EVENT_KEY_DOWN, ...).""" + events = [] + while True: + event = self.engine.poll_event() + if event is None: + return events + events.append(event) + + def resize(self, width, height): + self.width, self.height = width, height + self.engine.resize(width, height) + + def savePng(self, path): + """The last frame as a PNG (headless or windowed).""" + self.engine.save_screenshot_png(path) + + def close(self): + if self.engine is not None: + self.engine.close() + self.engine = None diff --git a/src/test/python/preponderous/graphik/grid3d/golden/board-4x3.png b/src/test/python/preponderous/graphik/grid3d/golden/board-4x3.png new file mode 100644 index 0000000..489bee3 Binary files /dev/null and b/src/test/python/preponderous/graphik/grid3d/golden/board-4x3.png differ diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_scene.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_scene.py new file mode 100644 index 0000000..3fa809e --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_scene.py @@ -0,0 +1,296 @@ +"""grid3d's scene description, board, pieces and animation: pure Python, no GPU.""" + +import importlib +import sys + +import pytest + +from preponderous.graphik.grid3d import ( + BED_TOP, + CAPSULE, + CUBE, + MAX_POINT_LIGHTS, + SPHERE, + Animator, + GridBoard, + Light, + Piece, + PieceStyle, + Scene, + SceneLimitError, + Shape, + Theme, + cellCenter, + fitCamera, + interpolatePosition, +) + + +def theme(): + return Theme( + pieces={ + "pawn": PieceStyle(SPHERE, (0.9, 0.2, 0.2), height=0.5, size=0.8), + "gem": PieceStyle(CAPSULE, (0.2, 0.9, 0.9), height=0.7, size=0.4, glow=(2.0, 1.5)), + "body": PieceStyle(SPHERE, (0.4, 0.8, 0.4), height=0.5, size=0.78, tones=(0.92, 0.78)), + } + ) + + +# -- importing + + +def test_importing_grid3d_loads_neither_strata_nor_pygame(): + for name in list(sys.modules): + if name == "strata" or name.startswith("strata.") or name.startswith("preponderous.graphik.grid3d"): + del sys.modules[name] + pygameLoaded = "pygame" in sys.modules + importlib.import_module("preponderous.graphik.grid3d") + assert "strata" not in sys.modules + assert ("pygame" in sys.modules) == pygameLoaded + + +# -- the board + + +def test_cells_are_centred_on_the_origin(): + assert cellCenter(0, 0, 3, 3) == (-1.0, -1.0) + assert cellCenter(1, 1, 3, 3) == (0.0, 0.0) + assert cellCenter(3, 0, 4, 2) == (1.5, -0.5) + + +def test_a_board_has_one_tile_per_cell_plus_a_four_sided_frame(): + board = GridBoard(5, 3, theme()) + shapes = board.boardShapes() + assert len(shapes) == 5 * 3 + 4 + assert all(shape.kind == CUBE for shape in shapes) + + +def test_tiles_are_checkered_and_a_tint_blends_every_tile(): + board = GridBoard(2, 1, theme()) + plain = board.boardShapes() + assert plain[0].color != plain[1].color + tinted = board.boardShapes(tint=(1.0, 0.0, 0.0)) + assert all(t.color[0] > p.color[0] for t, p in zip(tinted[:2], plain[:2])) + + +def test_a_theme_without_frame_or_alternate_draws_plain_tiles_only(): + board = GridBoard(2, 2, Theme(alternate=None, frame=None)) + shapes = board.boardShapes() + assert len(shapes) == 4 + assert len({shape.color for shape in shapes}) == 1 + + +def test_a_board_needs_a_cell(): + with pytest.raises(ValueError): + GridBoard(0, 3) + + +# -- pieces + + +def test_a_piece_stands_on_its_cell(): + board = GridBoard(3, 3, theme()) + shapes, lights = board.pieceShapes([Piece("p", 2, 0, "pawn")]) + (shape,) = shapes + assert (shape.position[0], shape.position[2]) == (1.0, -1.0) + assert shape.position[1] - shape.scale[1] / 2 == pytest.approx(BED_TOP) + assert lights == [] + + +def test_a_glowing_style_adds_a_light_above_the_piece(): + board = GridBoard(3, 3, theme()) + _, lights = board.pieceShapes([Piece("g", 1, 1, "gem")]) + (light,) = lights + assert (light.position[0], light.position[2]) == (0.0, 0.0) + assert light.position[1] > BED_TOP + 0.7 + + +def test_scale_and_colour_override_the_style(): + board = GridBoard(3, 3, theme()) + (shape,), _ = board.pieceShapes([Piece("p", 0, 0, "pawn", scale=0.5, color=(0.1, 0.2, 0.3))]) + assert shape.scale[0] == pytest.approx(0.4) + assert shape.color[:3] == (0.1, 0.2, 0.3) + + +def test_extras_are_drawn_from_the_pieces_current_position(): + def eyes(piece, x, z, baseY): + return [Shape(SPHERE, (x + piece.facing[0] * 0.3, baseY + 0.4, z), (0.2, 0.2, 0.2), (1, 1, 1, 1))] + + t = theme() + t.pieces["head"] = PieceStyle(SPHERE, (0.5, 0.9, 0.5), extras=eyes) + board = GridBoard(3, 3, t) + shapes, _ = board.pieceShapes([Piece("h", 1, 1, "head", facing=(1, 0))], positions={"h": (0.5, 0.0)}) + assert shapes[1].position[0] == pytest.approx(0.8) + + +def test_chained_neighbours_are_bridged_and_gaps_are_not(): + board = GridBoard(5, 1, theme()) + pieces = [ + Piece("a", 0, 0, "body", chain="snake", link=0), + Piece("b", 1, 0, "body", chain="snake", link=1), + Piece("c", 3, 0, "body", chain="snake", link=2), # not next to b + ] + shapes, _ = board.pieceShapes(pieces) + bridges = shapes[3:] + assert len(bridges) == 1 + assert bridges[0].position[0] == pytest.approx(-1.5) # between cells 0 and 1 + assert bridges[0].scale[0] == pytest.approx(1.0) # spans the gap along x + + +def test_chained_pieces_alternate_tones(): + board = GridBoard(3, 1, theme()) + pieces = [Piece(i, i, 0, "body", chain="s", link=i) for i in range(2)] + shapes, _ = board.pieceShapes(pieces) + assert shapes[0].color != shapes[1].color + + +def test_bad_pieces_are_rejected_with_their_id(): + board = GridBoard(3, 3, theme()) + with pytest.raises(ValueError, match="off the 3x3 board"): + board.checkPieces([Piece("x", 3, 0, "pawn")]) + with pytest.raises(ValueError, match="share the id"): + board.checkPieces([Piece("x", 0, 0, "pawn"), Piece("x", 1, 0, "pawn")]) + with pytest.raises(KeyError, match="no PieceStyle named 'ghost'"): + board.checkPieces([Piece("x", 0, 0, "ghost")]) + + +# -- the camera + + +@pytest.mark.parametrize("columns, rows", [(3, 3), (5, 5), (16, 16), (20, 8), (8, 20)]) +def test_the_camera_sees_every_corner_of_the_board(columns, rows): + camera = fitCamera(columns, rows, aspect=900 / 700) + ex, ey, ez = camera.eye + tx, ty, tz = camera.target + forward = (tx - ex, ty - ey, tz - ez) + import math + + norm = math.sqrt(sum(c * c for c in forward)) + forward = tuple(c / norm for c in forward) + half = math.radians(camera.fovDegrees) / 2 + for cx in (-columns / 2 - 0.4, columns / 2 + 0.4): + for cz in (-rows / 2 - 0.4, rows / 2 + 0.4): + to = (cx - ex, 0.0 - ey, cz - ez) + dist = math.sqrt(sum(c * c for c in to)) + cosAngle = sum(a * b for a, b in zip(forward, to)) / dist + # inside the vertical field of view (the horizontal one is wider) + assert math.acos(min(1.0, cosAngle)) < half * 1.35 + + +def test_the_camera_looks_down_from_the_south(): + camera = fitCamera(5, 5) + assert camera.eye[1] > camera.target[1] + assert camera.eye[2] > camera.target[2] + + +# -- limits + + +def test_too_many_lights_are_rejected(): + board = GridBoard(1, 1) + lights = [Light((0, 1, 0), (1, 1, 1), 1, 1)] * (MAX_POINT_LIGHTS + 1) + with pytest.raises(SceneLimitError, match="at most 32"): + board.scene(lights=lights) + + +def test_too_many_shadow_casting_lights_are_rejected(): + lights = [Light((0, 1, 0), (1, 1, 1), 1, 1, castShadows=True)] * 5 + with pytest.raises(SceneLimitError, match="shadow"): + Scene(lights=lights).checkLimits() + + +def test_the_largest_real_board_stays_inside_the_limits(): + # ophidian's level 6: a 16x16 board, a long snake and some pickups + t = theme() + board = GridBoard(16, 16, t) + snake = [Piece(("s", i), i % 16, i // 16, "body", chain="s", link=i) for i in range(60)] + pickups = [Piece(("g", i), i, 10, "gem") for i in range(8)] + scene = board.scene(snake + pickups) + scene.checkLimits() + assert len(scene.lights) == 8 + + +# -- animation + + +def test_interpolation_is_clamped(): + assert interpolatePosition((0, 0), (1, 2), 0.5) == (0.5, 1.0) + assert interpolatePosition((0, 0), (1, 2), -1) == (0, 0) + assert interpolatePosition((0, 0), (1, 2), 3) == (1, 2) + + +def animator(**kwargs): + return Animator(lambda c, r: cellCenter(c, r, 5, 5), **kwargs) + + +def test_a_piece_slides_to_its_new_cell_over_one_tick(): + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2) + assert a.positions(0.2)["p"] == (-2.0, -2.0) + assert a.positions(0.3)["p"] == pytest.approx((-1.5, -2.0)) + assert a.positions(0.5)["p"] == (-1.0, -2.0) + assert a.settled(0.4) + + +def test_a_new_piece_appears_on_its_cell(): + a = animator() + a.update([Piece("p", 2, 2, "pawn")], now=0.0, tickSeconds=0.2) + assert a.positions(0.0)["p"] == (0.0, 0.0) + + +def test_a_teleport_or_an_opted_out_piece_jumps(): + a = animator() + a.update([Piece("p", 0, 0, "pawn"), Piece("q", 0, 1, "pawn")], now=0.0, tickSeconds=0.2) + a.update( + [Piece("p", 4, 0, "pawn"), Piece("q", 1, 1, "pawn", interpolate=False)], + now=0.2, + tickSeconds=0.2, + ) + positions = a.positions(0.25) + assert positions["p"] == (2.0, -2.0) # wrapped across the board: no slide + assert positions["q"] == (-1.0, -1.0) + + +def test_reduced_motion_snaps_every_piece(): + a = animator(reducedMotion=True) + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2) + assert a.positions(0.25)["p"] == (-1.0, -2.0) + + +def test_a_slide_interrupted_by_the_next_tick_continues_from_where_it_was_drawn(): + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2) + a.update([Piece("p", 2, 0, "pawn")], now=0.3, tickSeconds=0.2) # halfway + assert a.positions(0.3)["p"] == pytest.approx((-1.5, -2.0)) + + +def test_removed_pieces_are_forgotten(): + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([], now=0.2, tickSeconds=0.2) + assert a.positions(0.3) == {} + + +def test_a_snapped_tick_puts_every_piece_on_its_cell(): + # a restart or a new level: nothing slides over from the old board + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2, snap=True) + assert a.positions(0.25)["p"] == (-1.0, -2.0) + a.update([Piece("p", 2, 0, "pawn")], now=0.4, tickSeconds=0.2) + assert a.positions(0.5)["p"] == pytest.approx((-0.5, -2.0)) # slides again + + +def test_a_tick_before_the_last_slide_finished_still_slides_a_one_cell_step(): + # ticks that come back to back (a busy frame, a speed-up): the step is + # measured from cell to cell, so a turn isn't mistaken for a teleport + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 0, 1, "pawn")], now=0.2, tickSeconds=0.2) + a.update([Piece("p", 1, 1, "pawn")], now=0.2, tickSeconds=0.2) # no time passed + assert a.positions(0.2)["p"] == (-2.0, -2.0) # still drawn where it was + assert a.positions(0.3)["p"] == pytest.approx((-1.5, -1.5)) + assert a.positions(0.4)["p"] == (-1.0, -1.0) diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py new file mode 100644 index 0000000..be45a48 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py @@ -0,0 +1,128 @@ +"""Grid3DView: why it can't start, and a headless render against a golden image. + +The render tests need Strata's Python binding and its library; they skip when +Strata can't load here (Grid3DView.open raises Unavailable). +""" + +import json +import os +import shutil +import subprocess +import sys + +import pytest + +from preponderous.graphik.grid3d import ( + CAPSULE, + SPHERE, + GridBoard, + Grid3DView, + Label, + Piece, + PieceStyle, + Theme, + Unavailable, +) +from preponderous.graphik.grid3d import view as viewModule + +GOLDEN = os.path.join(os.path.dirname(__file__), "golden", "board-4x3.png") + + +# -- why it can't start (no GPU needed) + + +def test_a_system_without_a_strata_library_is_unavailable(monkeypatch): + monkeypatch.delenv("STRATA_LIBRARY", raising=False) + with pytest.raises(Unavailable, match="no library for this system"): + viewModule.loadStrata(platform="darwin") + + +def test_a_missing_binding_says_how_to_install_it(monkeypatch): + monkeypatch.setitem(sys.modules, "strata", None) # makes `import strata` fail + with pytest.raises(Unavailable, match=r"graphik\[strata\]"): + viewModule.loadStrata(platform="linux") + + +# -- rendering (needs Strata) + + +def openHeadless(width=240, height=180, clock=None): + try: + if clock is None: + return Grid3DView.open(width, height, headless=True) + return Grid3DView.open(width, height, headless=True, clock=clock) + except Unavailable as reason: + pytest.skip("Strata can't run here: %s" % reason) + + +def goldenScene(view): + theme = Theme( + pieces={ + "pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2)), + "gem": PieceStyle(CAPSULE, (0.2, 0.8, 0.95), height=0.7, size=0.4, glow=(2.0, 1.6)), + } + ) + view.setBoard(GridBoard(4, 3, theme)) + view.setPieces([Piece("p", 1, 1, "pawn"), Piece("g", 3, 0, "gem")]) + view.setLabels([Label("grid3d", 8, 8, 14)]) + + +def differingFraction(expected, actual, threshold=12.0): + """Fraction of pixels whose RGB distance exceeds `threshold` (0-255 scale). + Uses strata-imgcmp (STRATA_IMGCMP or on PATH) when available.""" + imgcmp = os.environ.get("STRATA_IMGCMP") or shutil.which("strata-imgcmp") + if imgcmp: + out = subprocess.run( + [imgcmp, expected, actual, "--json", "--threshold", "4"], + capture_output=True, + text=True, + ) + report = json.loads(out.stdout) + for key in ("fraction_over", "fractionOver", "over_fraction"): + if key in report: + return float(report[key]) + if "pixels_over" in report and "pixels" in report: + return report["pixels_over"] / float(report["pixels"]) + import pygame + + a = pygame.image.load(expected) + b = pygame.image.load(actual) + assert a.get_size() == b.get_size() + width, height = a.get_size() + over = 0 + for y in range(height): + for x in range(width): + pa, pb = a.get_at((x, y)), b.get_at((x, y)) + d = ((pa.r - pb.r) ** 2 + (pa.g - pb.g) ** 2 + (pa.b - pb.b) ** 2) ** 0.5 + over += d > threshold + return over / float(width * height) + + +def test_a_board_renders_like_the_golden_image(tmp_path): + view = openHeadless() + try: + goldenScene(view) + view.frame(present=False) + actual = str(tmp_path / "board-4x3.png") + view.savePng(actual) + finally: + view.close() + assert differingFraction(GOLDEN, actual) <= 0.02 + + +def test_a_frame_mid_tick_draws_a_piece_between_its_cells(): + now = [0.0] + view = openHeadless(clock=lambda: now[0]) + try: + theme = Theme(pieces={"pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2))}) + view.setBoard(GridBoard(4, 3, theme)) + view.setPieces([Piece("p", 0, 1, "pawn")], tickSeconds=0.2) + now[0] = 0.2 + view.setPieces([Piece("p", 1, 1, "pawn")], tickSeconds=0.2) + now[0] = 0.3 + scene = view.scene() + piece = scene.shapes[-1] + assert piece.position[0] == pytest.approx(-1.0) # halfway from -1.5 to -0.5 + view.frame(present=False) # and the engine accepts it + finally: + view.close()