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
5 changes: 5 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

146 changes: 146 additions & 0 deletions docs/adr/0009-textures-are-text.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# 9. Textures are text, and the browser is the only parser

Status: proposed

## Context

Every visual in `web/` today is a vector drawn at runtime with pixi.js
`Graphics` — `drawBuilding` (`main.ts:225`) hand-codes roof polygons per
building, and pips are circles (`main.ts:473`). There is no bitmap art
anywhere in the project and no pipeline for adding any. That has worked
because there has been exactly one building type worth drawing; the service
map already lists farm and tavern as built and "the rest is the plan" for
workplaces, and each new one currently means someone hand-writing more
polygon code.

That does not scale, and not primarily for a performance reason. An agent
working in this repo can generate and edit text fluently and cannot produce
raster art at all — no eyes, no mouse, no Aseprite. A binary sprite (PNG,
texture atlas) dropped into a PR is also unreviewable the way the rest of
this codebase is reviewable: it does not diff, a reviewer cannot read *what
changed* from the diff, and git cannot merge two edits to it. The project
already treats "can this be reviewed as text" as load-bearing — `proto/` for
contracts, the event log for world history — and rendering assets are the
one visual surface still outside that discipline.

The want is concrete: a workplace or pip should be able to ship a distinct,
textured look — grass, wood grain, ale foam, an idle-vs-working animation —
authored the same way an agent authors everything else here, and reviewed
the same way.

## Decision

### 1. A texture is a plain-text grid, with a palette header

A monospace character grid, one line per row, preceded by a header mapping
each character to a color:

```
palette
. #00000000
g #4a7c2f
G #5c9636
grid
..gg..
.gGGg.
..gg..
```

Any character not declared in the palette is a format error, not a
transparent-by-default pixel — an agent that mistypes a glyph should get a
loud failure, not a silently wrong texture.

### 2. Animation is multiple frames in one file, not multiple files

A second section, `frames`, holds an ordered list of grids and an `fps`.
One texture — one visual concept ("tavern, idle") — stays one file whether
it is static or animated, so a diff that adds motion to an existing texture
is a diff to one file, not a rename plus new siblings.

### 3. One parser, one owner: `web/src`

The grid is parsed to an off-screen `<canvas>`, one filled rect per cell,
then handed to pixi as a `Texture`. Nothing outside `web/` ever reads this
format. This is not a contract between services — no `.proto`, no `gen/` —
because it carries no simulation semantics: `sim-core` does not know a
building has a roof texture, only that it is a building. Keeping a second
parser anywhere (say, a native client down the line) would be the same
mistake rule 4 forbids for domain rules, for a different reason: a format
with two readers drifts, and a rendering glitch becomes a cross-language bug
hunt instead of a one-file fix.

### 4. Cell size is a render-time constant, not baked into the file

A texture file declares a grid, not a pixel size. `web/src` decides how many
device pixels a cell occupies, so the same tavern texture can be drawn at
different zoom levels or a future minimap without a second asset.

### 5. Files live under `web/assets/textures/`, validated like code

`{building-or-pip}.{state}.txt`, e.g. `tavern.idle.txt`,
`tavern.working.txt`, `pip.walking.txt`. No manifest service, no registry —
the loader lists the directory. A test wired into `web`'s `make test` (bun
test) rejects a malformed file before it reaches the renderer: non-rectangular
rows, a glyph missing from its palette, or animation frames whose dimensions
disagree with each other. The same bar `make proto-lint` holds contracts to —
a bad file fails the build, not the demo.

## Why not real bitmap assets (PNG / Aseprite / a sprite sheet)

The obvious alternative, and rejected for the reason this ADR exists: an
agent cannot produce or meaningfully edit one, and it does not diff. This
project would still need a human artist, which defeats the point of a
generative pipeline agents can drive end to end.

## Why not procedural/shader-generated textures (noise, WGSL)

More expressive, and premature. There is no shader stage in the renderer
today — pixi is being used purely through `Graphics` — and the actual need
right now is "give ten building types a distinguishable look an agent can
author," not photorealism. Nothing here forecloses adding shaders later; it
just is not the next thing to build.

## Why not keep pure vector polygons

Fine for a building's silhouette — the roof math in `drawBuilding` is not
going away — but it does not extend to surface detail (grass texture, wood
grain, foam) without every such detail becoming more hand-written polygon
code per building type. Text grids and vector shapes are complementary, not
competing: a building keeps its polygon frame and gains a texture fill.

## Why not a shared package parsed by more than one client

There is exactly one client (`web/`). A shared `pips/textures` package
parsed by both a hypothetical native client and the browser is solving a
problem that does not exist yet — add it the day a second consumer does.

## Consequences

- `web/src` gains a parser module and a canvas-to-`Texture` conversion; small,
but it is new surface area with its own tests.
- Texture count grows per building/pip state, and per animation — the
filename convention (`{subject}.{state}.txt`) is the only index; if that
stops being enough (states composing, e.g. "working + injured"), revisit
before it grows organically into an unreadable naming scheme.
- Pixel-art-scale rendering is now a deliberate style, not a placeholder to
be embarrassed about. Later polish should stay inside that constraint —
sharper cells, better palettes — rather than quietly mixing in traditional
art assets, which would bring back the diffability problem this ADR exists
to avoid.
- `web/` needs its own `CLAUDE.md` (every other service has one) documenting
the format for an agent that is about to author a texture, since the spec
lives in this ADR and an ADR is not where an agent should have to look
mid-task.

## Next steps

1. Write the format spec precisely (header syntax, `frames`/`fps` syntax,
escaping) as `web/assets/textures/FORMAT.md` — this ADR sets the shape,
not the grammar.
2. `web/src/textures.ts` — parser, validator, canvas/`Texture` conversion.
3. A validation test in `web` wired into `make test`, covering the failure
modes in decision §5.
4. Convert one existing procedural asset (the tavern's wall face is the
smallest useful target) to prove the pipeline before touching the rest.
5. Add `web/CLAUDE.md` documenting the convention for agents authoring new
textures.
45 changes: 45 additions & 0 deletions web/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# web

The browser client. Connects to `world-gateway` over Connect (see ADR 0003),
renders the world with pixi.js in 2:1 isometric projection, and runs the same
WASM build of `sim-core` locally for client-side prediction — see the header
comment in `src/main.ts` before touching the render loop.

## Textures

ADR 0009: sprite/roof textures are plain text, not binary images, so an agent
can author or edit one directly. The grammar is `assets/textures/FORMAT.md`;
`src/textures.ts` is the only parser and the only place that format should
ever be read from — don't write a second reader.

Quick shape:

```
palette
. #00000000
g #4a7c2f
grid
.g.
ggg
.g.
```

- One file per `{subject}.{state}`, e.g. `tavern.idle.txt`. No manifest — the
loader in `main.ts` globs `assets/textures/*.txt` at build time
(`import.meta.glob`).
- Every glyph used in `grid`/`frames` must have a `palette` entry, or parsing
fails loudly. That is deliberate — a malformed texture should error, not
silently render a hole.
- `frames fps=N` replaces `grid` for an animation; frames must all share one
file's dimensions.
- `parseTexture`/`frameToCanvas`/`texturesFromParsed` in `src/textures.ts` are
plain functions with no pixi or DOM globals at module scope, so
`textures.test.ts` runs under `bun test` without a browser. Keep it that
way — if a change needs `document` or a pixi import at module load time,
it belongs in `main.ts`, not `textures.ts`.
- Cell size (pixels per glyph) is chosen at the call site in `main.ts`, not
stored in the file — the same texture can render at different zoom levels.

Before shipping a new texture, run `bun test` (validates every file under
`assets/textures/`) and look at it in the running app — a texture that
parses can still look wrong at the chosen cell size.
62 changes: 62 additions & 0 deletions web/assets/textures/FORMAT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Texture format

See ADR 0009 for why this exists. This is the grammar.

A texture file is plain text, split into sections by lines that name the
section: `palette`, then either `grid` (static) or `frames` (animated).
Leading/trailing blank lines and `#`-comment lines are ignored.

## `palette`

One glyph-to-color mapping per line, indented, glyph then a CSS hex color:

```
palette
. #00000000
g #4a7c2f
G #5c9636
```

- The glyph is exactly one character. Whitespace cannot be a glyph — use a
dedicated character (conventionally `.`) for "empty".
- Colors are `#rrggbb` or `#rrggbbaa`. `#00000000` is fully transparent.
- Every glyph used anywhere in `grid` or `frames` below must appear here.
An unknown glyph is a parse error, not a transparent pixel.

## `grid` (static texture)

```
grid
..gg..
.gGGg.
..gg..
```

Every row must have the same length. A ragged grid is a parse error.

## `frames` (animation)

```
frames fps=4
--- 0 ---
..gg..
.gGGg.
..gg..
--- 1 ---
..GG..
.Ggga.
..GG..
```

- `frames` takes one required key: `fps`, an integer greater than 0.
- Each frame starts with a `--- <index> ---` marker, indices `0..n-1` in
order. The marker is discarded; the index is documentation, not read back.
- Every frame's grid must have the same dimensions as the first frame. A
texture that grows or shrinks mid-animation is a parse error.

A file has exactly one of `grid` or `frames`, never both.

## Naming and location

`web/assets/textures/{subject}.{state}.txt`, e.g. `tavern.idle.txt`,
`pip.walking.txt`. The loader lists the directory; there is no manifest.
17 changes: 17 additions & 0 deletions web/assets/textures/roof.shingle.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# The roof fill for drawBuilding(), replacing the flat #3d4a60 with a shingled
# texture. Colors are picked to sit inside the existing building palette
# (see main.ts: 0x3d4a60 base, 0x2b3444/0x212938 walls, 0x5b6b86 stroke).
palette
. #3d4a60
o #2f3a4c
H #5b6b86

grid
HHHHHHHH
H......o
o......o
oooooooo
o......o
o......o
oooooooo
o......o
1 change: 1 addition & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@types/bun": "^1.3.14",
"typescript": "^5.6.3",
"vite": "^5.4.10",
"vite-plugin-wasm": "^3.3.0"
Expand Down
33 changes: 29 additions & 4 deletions web/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,35 @@
* itself, which keeps the renderer developable without a cluster.
*/

import { Application, Container, Graphics, Text } from "pixi.js";
import { Application, Container, Graphics, Text, type Texture } from "pixi.js";
import init, {
SimHandle,
pip_stride,
workplace_stride,
} from "./sim-wasm/sim_wasm.js";
import { parseTexture, texturesFromParsed } from "./textures";
import { type WorldClient, connect, join, streamDeltas } from "./world";

/**
* Every `.txt` under `assets/textures/`, inlined at build time. ADR 0009:
* these are agent-authored text files, not binary assets, so a build-time
* glob is enough — there is no server to list a directory against.
*/
const TEXTURE_SOURCES = import.meta.glob("../assets/textures/*.txt", {
query: "?raw",
import: "default",
eager: true,
}) as Record<string, string>;

/** Rasterizes a shipped texture file, keyed by filename, at `cellPx` per glyph. */
function loadTexture(fileName: string, cellPx: number): Texture[] {
const path = Object.keys(TEXTURE_SOURCES).find((p) =>
p.endsWith(`/${fileName}`),
);
if (!path) throw new Error(`texture not found: ${fileName}`);
return texturesFromParsed(parseTexture(TEXTURE_SOURCES[path]), cellPx);
}

// --- world constants --------------------------------------------------------

const MILLI_PER_TILE = 1000;
Expand Down Expand Up @@ -222,7 +243,7 @@ const isoDepth = (tileX: number, tileY: number) => tileX + tileY;
* Redrawn each tick rather than tinted, because `occupants` changes and Pixi's
* Graphics has no cheap way to resize a filled rectangle in place.
*/
function drawBuilding(g: Graphics, b: Building) {
function drawBuilding(g: Graphics, b: Building, roofTexture: Texture) {
const cx = toTile(b.x);
const cy = toTile(b.y);
const h = BUILDING_TILES / 2;
Expand All @@ -242,7 +263,7 @@ function drawBuilding(g: Graphics, b: Building) {
// door: it is exactly the position the core walks pips to.
g.poly([roof[3], roof[2], corners[2], corners[3]]).fill({ color: 0x2b3444 });
g.poly([roof[2], roof[1], corners[1], corners[2]]).fill({ color: 0x212938 });
g.poly(roof).fill({ color: 0x3d4a60 });
g.poly(roof).fill({ texture: roofTexture });
g.poly(roof).stroke({ color: 0x5b6b86, width: 1 });

// Occupancy, as a band rising up the left wall.
Expand Down Expand Up @@ -285,6 +306,10 @@ function drawGrid(parent: Container) {
async function main() {
await init();

// 4px per glyph: roof.shingle.txt is 8x8, so this lands at 32x32 — the same
// scale as ISO_TILE_W, close enough that the shingle rows read at this zoom.
const [roofTexture] = loadTexture("roof.shingle.txt", 4);

const app = new Application();
await app.init({ background: "#11131a", resizeTo: window, antialias: true });
document.body.appendChild(app.canvas);
Expand Down Expand Up @@ -449,7 +474,7 @@ async function main() {
blocks.set(id, block);
}

drawBuilding(block.body, b);
drawBuilding(block.body, b, roofTexture);
const centre = isoProject(toTile(b.x), toTile(b.y));
block.label.position.set(
centre.x,
Expand Down
Loading
Loading