Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ jobs:
# skip there. This job installs the strata extra and draws them for real,
# headless through EGL on Mesa's llvmpipe (no GPU, no display), and
# GRAPHIK_REQUIRE_STRATA turns a skip into a failure. The binding fetches
# the pinned Strata release library (view.STRATA_VERSION) from GitHub and
# the pinned Strata release library (view.STRATA_VERSION, set in
# adapters/binding_strata_loader.py) from GitHub and
# checks its SHA-256. The browser backend has no render here: Strata's own
# CI draws the grid relay in Chromium against desktop stills.
name: grid3d render (Strata, llvmpipe)
Expand Down Expand Up @@ -131,6 +132,10 @@ jobs:
import pygame
import preponderous.graphik as package
from preponderous.graphik import Graphik
# grid3d's subpackages and page template ship in the archive too
from preponderous.graphik.grid3d import adapters, ports, web
assert os.path.isfile(web.templatePath()), web.templatePath()
assert "site-packages" in adapters.__file__ and ports.SceneRenderer

assert package.__version__ == os.environ["VERSION"], package.__version__
assert "site-packages" in package.__file__, package.__file__
Expand Down
48 changes: 45 additions & 3 deletions docs/grid3d.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ Contents: [Scene data](#scene-data) · [Boards and pieces](#boards-and-pieces)
[Text](#text) · [Buttons and 2D screens](#buttons-and-2d-screens) ·
[Touch keys](#touch-keys) ·
[The desktop view](#the-desktop-view) · [The browser view](#the-browser-view) ·
[The wire format](#the-wire-format) · [Fetching the relay](#fetching-the-relay)
[The wire format](#the-wire-format) · [Fetching the relay](#fetching-the-relay) ·
[How the views are built](#how-the-views-are-built)

## Scene data

Expand Down Expand Up @@ -262,6 +263,9 @@ if web.touchScreen():
| `view.drawScene(scene, present=True)` | Draws a `Scene` a game built itself |
| `view.pollEvents()` | Every pending Strata event (`view.EVENT_QUIT`, `EVENT_KEY_DOWN`, `EVENT_KEY_UP`, `EVENT_RESIZED`, ...) |
| `view.resize(width, height)`, `view.savePng(path)`, `view.close()` | |
| `view.setFullscreen(enabled)`, `view.setTitle(title)` | Desktop fullscreen on or off; the window's title. Each returns `False` when it can't: the loaded Strata lacks the call (0.8.0 has no `strata_set_title`), the view is closed, or (fullscreen) headless |
| `view.strata`, `view.lib`, `view.engine` | The binding, the loaded library and the engine, for calls graphik doesn't wrap. Prefer the view's own methods where there is one |
| `Grid3DView.using(display, width, height, isWindow=True, reducedMotion=False, clock=time.monotonic)` | A view drawing on any display that has the view's ports ([below](#how-the-views-are-built)): for tests and tools |
| `Unavailable` | Why 3D can't run here, in words a player can act on |
| `STRATA_VERSION` | The Strata release the binding loads (`STRATA_LIBRARY` points at a local build instead) |

Expand Down Expand Up @@ -292,7 +296,7 @@ the relay next to it ([Fetching the relay](#fetching-the-relay)).

| Name | What it is |
|---|---|
| `Grid3DWebView` | `Grid3DView`'s calls (`setBoard`, `setPieces`, `setLabels`, `frame`, `scene`, `drawScene`, `pollEvents`, `resize`, `close`, picking) drawn by the relay. `frame()` does nothing: the page slides pieces itself. `drawScene()` sends only what changed. `savePng()` raises `Unavailable` |
| `Grid3DWebView` | `Grid3DView`'s calls (`setBoard`, `setPieces`, `setLabels`, `frame`, `scene`, `drawScene`, `pollEvents`, `resize`, `close`, picking) drawn by the relay. `frame()` does nothing: the page slides pieces itself. `drawScene()` sends only what changed. `savePng()` raises `Unavailable`; `setFullscreen()` and `setTitle()` return `False` (the browser owns its window, the page its title) |
| `Grid3DWebView.open(width, height, title, relay=None, maxBytes=4000000, reducedMotion=None, clock, canvas="relay")` | Asks the page for its 3D view; raises `Unavailable` when there is none or it failed |
| `view.ready`, `view.failure()` | Loaded yet; why it couldn't load |
| `templatePath(defaultView="3d")` | The pygbag page template, starting in 3D (or 2D) unless `?view=` or the player's last choice says otherwise |
Expand All @@ -306,7 +310,8 @@ the relay next to it ([Fetching the relay](#fetching-the-relay)).
| `pygameKey(scancode, pygame)` | The pygame key for a USB HID scancode, or 0 |
| `Event` | A relay event: `type`, `scancode`, `modifiers`, `repeat`, `button`, `width`, `height`, `x`, `y`, `dx`, `dy`, `text`, `pointer`, `id`, `nx`, `ny`, `key`, `pressure` |
| `EVENTS`, `EVENT_*` | Event type numbers, Strata's and the web's `FINGER_*` |
| `PlatformRelay(relay=None)` | The transport to the page's `window.StrataGridRelay` |
| `PlatformRelay(relay=None, page=None)` | The transport to the page's `window.StrataGridRelay` (found through `page`, `PAGE` by default) |
| `PAGE` | Where the page helpers look for the page's objects (a `PageObjects`); a test can put a fake here |
| `RecordingRelay(reducedMotion=False, state="ready")` | A transport that keeps what it is sent: for tests, and `wireJson()` for the relay's test page |

```python
Expand Down Expand Up @@ -397,3 +402,40 @@ kept. Only a release version (`0.9.0`, `1.0.0-rc.1`) is taken for `--strata`.
| `tarballName(version)` | The release asset's name |
| `RelayFetchError` | Why it couldn't fetch, verify or unpack |
| `main(argv=None)` | The command line |

## How the views are built

The two views share one core and differ only in what they draw on. Each
part of the outside world they touch sits behind a port (an interface, one
per file in `grid3d/ports/`), implemented by adapters (one per file in
`grid3d/adapters/`), and `view.py` and `web.py` wire the production
adapters in as defaults:

```
game -> Grid3DView (view.py) -> ViewState, geometry, scene/board/animate/pick -> ports <- adapters
-> Grid3DWebView (web.py) -> ViewState, wire, events -> ports <- adapters
```

| Port | Question it answers | Adapters |
|---|---|---|
| `StrataLoader` | Can Strata run here? Open an engine | `BindingStrataLoader` (`view.STRATA_LOADER`) |
| `SceneRenderer` | Draw this Scene now | `StrataEngine`, `RelayDisplay` |
| `EventSource` | What input came since the last poll? | `StrataEngine`, `RelayDisplay` |
| `Surface` | Resize, snapshot, close | `StrataEngine`, `RelayDisplay` |
| `WindowChrome` | Fullscreen and the window's title | `StrataEngine`, `RelayDisplay` |
| `GridRelay` | Talk to the page's grid relay | `PlatformRelay`, `RecordingRelay` |
| `PageObjects` | Which of the page's JS objects exist? | `PygbagPageObjects` (`web.PAGE`) |

The model and core (`errors.py`, `geometry.py`, `state.py`, `wire.py`,
`events.py`, and the scene, board, animation, picking, text, button and
touch-key modules) import no adapter and no view; `test_grid3d_architecture.py`
fails if one does, or if a port or adapter file holds more than one class.
Every port has a contract test (`test_grid3d_ports.py`) that its fake and its
production adapters all pass. `grid3d.view` and `grid3d.web` still export
every name they did in 0.5.3.

To draw on something new (another engine, a recorder), write one adapter
file with the `SceneRenderer`, `EventSource`, `Surface` and `WindowChrome`
calls, add it to `adapters/__init__.py`, and hand it to
`Grid3DView.using(display, ...)`, or, for `open()`, add a `StrataLoader`
that returns it.
9 changes: 9 additions & 0 deletions src/main/python/preponderous/graphik/grid3d/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@

The API reference, with an example for each part, is docs/grid3d.md.

How it is built (docs/grid3d.md, "How the views are built"):

game -> Grid3DView / Grid3DWebView (view.py, web.py: composition roots)
-> ViewState, geometry, wire, events (core) -> ports/ <- adapters/

The model and core never import an adapter or a view; each port has one
file, each adapter one file. A new backend is one adapter file plus an entry
in adapters/__init__.py.

Importing this package imports neither Strata nor pygame.
"""

Expand Down
22 changes: 22 additions & 0 deletions src/main/python/preponderous/graphik/grid3d/adapters/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""The adapters of grid3d's ports, one implementation per file.

| Port | Adapters |
|---|---|
| StrataLoader | BindingStrataLoader |
| SceneRenderer, EventSource, Surface | StrataEngine (desktop), RelayDisplay (browser) |
| GridRelay | PlatformRelay (pygbag), RecordingRelay (tests, recordings) |
| PageObjects | PygbagPageObjects |

Importing this package loads neither Strata, pygame nor pygbag: they are
imported when an adapter is used.
"""

from .binding_strata_loader import BindingStrataLoader
from .platform_relay import PlatformRelay
from .pygbag_page_objects import PygbagPageObjects
from .recording_relay import RecordingRelay
from .relay_display import RelayDisplay
from .strata_engine import StrataEngine

__all__ = ["BindingStrataLoader", "PlatformRelay", "PygbagPageObjects", "RecordingRelay",
"RelayDisplay", "StrataEngine"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""BindingStrataLoader: opens a StrataEngine through the strata-engine
binding (`graphik[strata]`), which loads libstrata: a released build,
downloaded once, checked against its pinned SHA-256 and cached, or the
local build STRATA_LIBRARY points at."""

import os
import sys

from ..errors import Unavailable
from ..geometry import SUN_DIRECTION
from .strata_engine import StrataEngine

STRATA_VERSION = "0.8.0"
STRATA_PLATFORMS = ("linux", "win32")
INSTALL_HINT = "pip install 'graphik[strata]'"


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 BindingStrataLoader:
"""The desktop's StrataLoader."""

def open(self, width, height, title, headless):
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)
lighting = lib.lighting_defaults(strata.LIGHTING_SUN)
lighting.shadow_distance = 40.0
lighting.fog = 0
engine.set_lighting(lighting)
engine.set_sun_direction(SUN_DIRECTION)
return StrataEngine(strata, lib, engine)
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""PlatformRelay: the page's grid relay through pygbag's platform.window,
which passes strings, so options go as JSON and messages as base64."""

import base64
import json

from ..errors import Unavailable
from .pygbag_page_objects import PygbagPageObjects


class PlatformRelay:
"""The page's window.StrataGridRelay, through pygbag's platform.window."""

def __init__(self, relay=None, page=None):
if relay is None:
relay = (page or PygbagPageObjects()).get("StrataGridRelay")
if relay is None:
raise Unavailable(
"this page has no 3D view (grid-relay.js isn't loaded; on graphik's "
"template it loads once the 3D toggle is on, when wants3D() turns true)"
)
self.js = relay

def request(self, options):
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()
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""PygbagPageObjects: the page's JS objects through pygbag's
platform.window, asked again on every call."""

import sys


class PygbagPageObjects:
"""window.<name> under pygbag, or None (not in a browser, or no such
object on the page)."""

def get(self, name):
if sys.platform != "emscripten":
return None
import platform # pygbag's, not the standard library's

return getattr(platform.window, name, None)
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""RecordingRelay: a GridRelay that keeps what it is sent."""

import base64
import json

from ..wire import WireError, readHeader


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])
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""RelayDisplay: the page's grid relay (a GridRelay) as a SceneRenderer,
an EventSource, a Surface and a WindowChrome, plus the retained messages Grid3DWebView
sends it (BOARD, PIECES, HUD, VIEW)."""

from types import SimpleNamespace

from ..errors import Unavailable
from ..events import Event
from ..wire import BOARD, HUD, PIECES, VIEW, WireError, encodeBoard, encodeHud, encodePieces, encodeView


# what encodePieces needs to send "no pieces" for draw()
_NO_BOARD = SimpleNamespace(visible=lambda column, row: False, bridgePairs=lambda pieces: [])


class RelayDisplay:
"""What a Grid3DWebView draws on: `relay` and what it was sent."""

def __init__(self, relay):
self.relay = relay
self.sent = 0
self.lastSent = {} # kind -> the last message of that kind (draw)

def send(self, message, kind=None):
"""Sends one message; a refusal raises WireError with the relay's
status. `kind` keeps it as the last of its kind, which draw()
compares against."""
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

def draw(self, scene, aspect, present=True):
"""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. The relay keeps its own aspect and presents on the page's own
frames, so `aspect` and `present` change nothing."""
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 poll(self):
"""Every event since the last poll (Event objects; see events.EVENTS)."""
return [Event(e) for e in self.relay.poll()]

def resize(self, width, height):
"""Nothing to do: the page sizes its own canvas (the view sends the
camera for the new size)."""

def setFullscreen(self, enabled):
"""False: the page's window is the browser's."""
return False

def setTitle(self, title):
"""False: the page's title is the page's."""
return False

def savePng(self, path):
raise Unavailable("screenshots of the web view are taken by the page (canvas.toBlob)")

def close(self):
self.relay.close()
Loading
Loading