Skip to content

A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D

Draw the town with PixiJS 3D

Claudecbf09a33c715
diff --git a/.agents/skills/pixijs-3d b/.agents/skills/pixijs-3d
new file mode 120000
index 0000000..1ba91fd
--- /dev/null
+++ b/.agents/skills/pixijs-3d
@@ -0,0 +1 @@
+../../node_modules/@pixi/3d/skills/pixijs-3d
\ No newline at end of file
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index 1fb2189..c8d9f37 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -39,7 +39,7 @@ it, and two fingers move the camera under it. With any pointer, a stroke let
go off the map (over the tool bar, say) is dropped and shows red while it
would be, as are a right click or Esc mid-drag. On touch the tooltip shows
only for what is about to be built, never while panning or picking, in a
-thin full-width strip under the top line. This lives entirely in `src/render/three/input.ts`
+thin full-width strip under the top line. This lives entirely in `src/render/pixi3d/input.ts`
(and the bar in `src/ui/dom/index.ts`); the game still sees one ordinary press and
release.
@@ -64,7 +64,7 @@ to the bottom. The camera bar is hidden: pinch zooms and turns. New UI needs
nothing there unless it has to move on a phone; check it at 390×844, 360×640
and 762×330, and run `pnpm check:phone`.
-`src/render/three/scene.ts` owns the orthographic camera, ground projection and
+`src/render/pixi3d/scene.ts` owns the orthographic camera, ground projection and
frame source. `views.ts` follows live construction, upgrades, resources,
production, problem markers and the simulation's walkers and cargo. Flags,
mill sails and smoke animate in 3D. `pool.ts` instances repeated geometry,
@@ -133,7 +133,7 @@ Material effects render in the viewers and live game. Ordinary GLB viewers
show the underlying mesh; effect parameters are preserved as GLB extras and
in the editable geometry descriptions, rather than baked into duplicate meshes.
-- `src/render/three/assets/primitives.ts`: renderer-independent polygon/stroke schema
+- `src/render/pixi3d/assets/primitives.ts`: renderer-independent polygon/stroke schema
and reusable modelling operations in the game's cell units and pixel heights.
- `buildings.ts`, `land.ts`, `people.ts`, `construction.ts`: procedural
models; `assets.ts` collects them and retains the approved house/prop models.
@@ -204,7 +204,7 @@ import only the layers below it (`.oxlintrc.json` enforces it):
```
app/ start-up: the one module that knows every layer
-ui/dom/ the page's UI render/three/ the Three.js renderer
+ui/dom/ the page's UI render/pixi3d/ the Three.js renderer
\ /
view/ the world as plain data for any UI and any renderer
|
@@ -261,7 +261,7 @@ One frame runs three schedules: `simulate` (at the chosen speed), then `project`
- `screens/`: the charter a town is founded from, sharing (and its card), a visit to a shared town, the
reckoning at the end of a term, and the confirm dialog.
- `styles/`: `factory.css`, and `phone.css` after it.
-- `src/render/three/`: the live renderer: `services.ts` (its scene and view registries), `sync.ts` (a view
+- `src/render/pixi3d/`: the live renderer: `services.ts` (its scene and view registries), `sync.ts` (a view
for each entity), `draw/` (the land, the ground, the map view, the preview, animation, the townsfolk),
`schedule.ts` (`draw`), `scene.ts` (camera and frame source), `input.ts` (map input), `views.ts`,
`pool.ts`, `thumbnails.ts` (the pictures the page's menus show), effects and shaders.
@@ -285,20 +285,20 @@ One frame runs three schedules: `simulate` (at the chosen speed), then `project`
[`/model-review.html?collection=town`](http://localhost:5232/model-review.html?collection=town)
shows all 23 building kinds plus the market hall and church upgrades. The final
-nine refinements are grouped at `?collection=rural`. `src/render/three/assets/rural.ts`
+nine refinements are grouped at `?collection=rural`. `src/render/pixi3d/assets/rural.ts`
owns timber entrances, nursery and farm fittings, chapel porches, granary louvres
and the supported fire-watch access route. The same geometry is used in the game,
catalogue, model sheets and GLB exports.
[`/model-review.html?collection=trades`](http://localhost:5232/model-review.html?collection=trades)
groups the mill, warehouse, fishery, bakery, weaver and watch house revisions.
-`src/render/three/assets/trades.ts` owns their equipment, loading doors, open yards and the
+`src/render/pixi3d/assets/trades.ts` owns their equipment, loading doors, open yards and the
bakery smoke origin. The mill keeps its animated sails. Cargo sits on the ground
or loading apron, and the four new yard layouts turn towards connected roads.
[`/model-review.html?collection=workshops`](http://localhost:5232/model-review.html?collection=workshops)
groups the revised mine, smithy, sawmill and town hall. The three workshops have
-open yards and road-facing layouts. `src/render/three/assets/workshops.ts` owns their
+open yards and road-facing layouts. `src/render/pixi3d/assets/workshops.ts` owns their
geometry, construction frames and smoke origins. The live renderer and catalogue
use the same models; simulation footprints and building costs are unchanged.
@@ -318,7 +318,7 @@ and house geometry is checked against its plate bounds. Natural rock deposits
use six seeded silhouettes while retaining their simulation cell footprints.
`pnpm check:revisions` renders every catalogue entry, checks the exclamation
mark from both sides and verifies animated smoke through rendered pixels.
-The chimney plume uses `src/render/three/smoke-effects.ts` in both the catalogue and
+The chimney plume uses `src/render/pixi3d/smoke-effects.ts` in both the catalogue and
working buildings. Smoke's GLB stores emitter metadata; particles run at runtime.
Open [`/effects-lab.html`](http://localhost:5232/effects-lab.html) to inspect
@@ -359,7 +359,7 @@ road setts and the park simulation rules are unchanged.
Open `/park-lab.html` for a park assembled from 25 cells using the current
park layout system, with two street entrances. The three retained furnishings
are framed lanterns, tiered fountains and simple stone busts;
-`src/render/three/fountain-effects.ts` supplies moving droplets and impact ripples in
+`src/render/pixi3d/fountain-effects.ts` supplies moving droplets and impact ripples in
the actual basin. Park rendering in the game, catalogue, map and preview shares
the same emitter metadata and water renderer. `pnpm check:park` verifies the
rendered animation, pause, camera controls and phone layout, and captures stills
diff --git a/docs/pr20-models.md b/docs/pr20-models.md
index 0a422a3..ea74025 100644
--- a/docs/pr20-models.md
+++ b/docs/pr20-models.md
@@ -11,7 +11,7 @@ plank bearers, chairs and chest stay inside the original two-cell plot.
It has no flue or smoke emitter. Furniture uses the same chair and chest
geometry in the work yard and on delivery carts.
-The civic milestones have full models in `src/render/three/assets/civic.ts`. The
+The civic milestones have full models in `src/render/pixi3d/assets/civic.ts`. The
guildhall is a steep-roofed guild house with a prominent clock tower,
balcony, dormers and guild banners. The city hall has lower wings, corner
pavilions, a columned portico, ceremonial stair and large ribbed dome with
@@ -46,7 +46,7 @@ geometry, economy values and simulation rules are unchanged. The three home
height fields in content are drawing dimensions used by construction and effects.
Construction uses `scaffoldAsset(size, height, share)` from
-`src/render/three/assets/scaffolding.ts`. It has no building-kind branches or model
+`src/render/pixi3d/assets/scaffolding.ts`. It has no building-kind branches or model
lookup. Modular timber bays, up to two working platforms, an access ladder,
canvas screens and supply piles fit inside the plot. Central bays on all
four sides remain clear at ground level. One generator covers every
diff --git a/docs/service-upgrade-assets.md b/docs/service-upgrade-assets.md
index ce25402..687cdd2 100644
--- a/docs/service-upgrade-assets.md
+++ b/docs/service-upgrade-assets.md
@@ -6,7 +6,7 @@ the town draws them once a market or chapel is upgraded (see `Kind.upgrade`).
## Asset API
-`src/render/three/assets/service-upgrades.ts` exports `marketHall()`, `church()`, and:
+`src/render/pixi3d/assets/service-upgrades.ts` exports `marketHall()`, `church()`, and:
```ts
serviceBuilding("market", 2) // market-hall
@@ -23,7 +23,7 @@ integration should support the existing `BuildingOptions` conventions for
road-facing doors, construction fitting, plate visibility and separate motion.
Do not replace `buildingAsset()` with the preview help## In the town
-`buildingAsset(id, …, upgraded)` in `src/render/three/models.ts` draws an
+`buildingAsset(id, …, upgraded)` in `src/render/pixi3d/models.ts` draws an
upgraded market or chapel with `serviceBuilding(kind, 2, { plate: false, doors })`.
The town draws plates apart, so the model leaves its own out. The model turns a
quarter at a time (`quartersFor`) to put the most of its street fronts on the
@@ -35,7 +35,7 @@ marker). The market hall drops the market's flag. The model cache key includes
the tier.
The building panel pictures an upgraded building with its model
-(`src/render/three/portrait.ts`): drawn once from the town's own camera, at the
+(`src/render/pixi3d/portrait.ts`): drawn once from the town's own camera, at the
town's scale and cropped to the model, beside the 2D pictures of the rest.
oes not activate upgrades.
diff --git a/package.json b/package.json
index cdaac01..360efbf 100644
--- a/package.json
+++ b/package.json
@@ -32,13 +32,14 @@
"engine:prepare": "node scripts/use-ritmo.ts"
},
"dependencies": {
+ "@pixi/3d": "0.1.0",
"@typeonce/ritmo": "0.23.0",
"@typeonce/ritmo-browser": "0.23.0",
"@typeonce/ritmo-math": "0.23.0",
"@typeonce/ritmo-pixi": "0.23.0",
"@typeonce/ritmo-render": "0.23.0",
"effect": "4.0.3",
- "pixi.js": "^8.22.0",
+ "pixi.js": "^8.23.0",
"three": "^0.186.1"
},
"devDependencies": {
@@ -46,6 +47,7 @@
"@typeonce/ritmo-devtools": "0.23.0",
"@types/node": "25.5.0",
"@types/three": "^0.186.0",
+ "@types/web": "^0.0.365",
"oxlint": "1.92.0",
"playwright": "^1.64.0",
"typescript": "7.0.2",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 27c3091..4529622 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,6 +8,9 @@ importers:
.:
dependencies:
+ '@pixi/3d':
+ specifier: 0.1.0
+ version: 0.1.0([email protected])
'@typeonce/ritmo':
specifier: 0.23.0
version: 0.23.0([email protected])
@@ -27,8 +30,8 @@ importers:
specifier: 4.0.3
version: 4.0.3
pixi.js:
- specifier: ^8.22.0
- version: 8.22.0
+ specifier: ^8.23.0
+ version: 8.23.0
three:
specifier: ^0.186.1
version: 0.186.1
@@ -45,6 +48,9 @@ importers:
'@types/three':
specifier: ^0.186.0
version: 0.186.0
+ '@types/web':
+ specifier: ^0.0.365
+ version: 0.0.365
oxlint:
specifier: 1.92.0
version: 1.92.0
@@ -184,8 +190,10 @@ packages:
resolution: {integrity: sha512-G2xbfWTrbqYRhR/vfeKNMQf/sS3/ti0iKJAAkRxHuXWZH/hne/dyIb9QKk5LuR6cJLARxsL6FMoAYmfspd74MQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
- resolution: {integrity: sha512-nezytU2pw587fQstUu1AsJZDVEynjskwOL+kibwcdxsMBFqPsFFNA7xl0ii/gXuDi6M0xj3mfRJj8pBSc2jCfA==}
+ resolution: {integrity: sha512-6mwC1nD4pDRix9QVl8aRDSHeMZtqb00vKiKb6U5cFeaYxZbwEnn9gXJphnk9udQKqf0jz2z8YUXaGudsACLaOQ==}
+ peerDependencies:
+ pixi.js: ^8.23.0
'@rolldown/[email protected]':
resolution: {integrity: sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==}
@@ -349,6 +357,9 @@ packages:
resolution: {integrity: sha512-mxYSBpDC+D0pLfSP6sW4WZTcT+nrtmZcimMqnVmy36Hte3XpeYSrvgg4TRdaM1GemGog1AWzI5qL2VoIfMXbJQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-97pWkQo8Nh+1GtYclGmxqfG9VUBdb9qMS/bEfPFTR96GKeEKahPLc8n7S1Kqq1gCR2dTwanowOionwHNRgYvng==}
+
resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==}
@@ -479,6 +490,9 @@ packages:
resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==}
engines: {node: '>=10.0.0'}
+ resolution: {integrity: sha512-SpiONmQPZDqe50ivOTgkVikYsnp6l1HTFYqPRLNBCJJdA2Qympw2yYUzX99XlSbbKZswjiG6r+xsUpPPOHqY+Q==}
+
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
@@ -591,6 +605,9 @@ packages:
resolution: {integrity: sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==}
+ resolution: {integrity: sha512-2oZqMAcEEiCtXWUjIGtZ71oPx1B0ZxYGTqIKsXB1wzWFhleNsCFxQuUJzgCV706bRcwPWtMGf1odmQvAcqKkIw==}
+
resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -619,8 +636,8 @@ packages:
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-QbTANHMZ751MIjLiLSUSM8a7LNMWwMIf0KbRCqlW+SPS9hNLfSVS+cl1O2SEp9g1K/wyLzj/OJHv+1TUfiPr/w==}
+ resolution: {integrity: sha512-RkWSwo+mAR0d7MKnJ20IjKkWGPdFh1C0adBRYYLa+SGdxTfbrr6RnQyZZRwjBaG/bDAIQqgBcTBbiNsN6iKFVQ==}
resolution: {integrity: sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==}
@@ -772,7 +789,10 @@ snapshots:
'@oxlint/[email protected]': {}
- '@pixi/[email protected]': {}
+ dependencies:
+ meshoptimizer: 1.3.0
+ pixi.js: 8.23.0
'@rolldown/[email protected]':
optional: true
@@ -891,6 +911,8 @@ snapshots:
fflate: 0.8.3
meshoptimizer: 1.1.1
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
'@typescript/[email protected]':
@@ -957,6 +979,8 @@ snapshots:
'@xmldom/[email protected]': {}
+
@@ -1033,6 +1057,8 @@ snapshots:
+
@@ -1063,12 +1089,12 @@ snapshots:
dependencies:
- '@pixi/colord': 2.9.6
'@types/earcut': 3.0.0
'@webgpu/types': 0.1.74
'@xmldom/xmldom': 0.8.15
+ colord: 2.12.0
earcut: 3.2.3
eventemitter3: 5.0.4
gifuct-js: 2.1.2
diff --git a/scripts/check-browser.ts b/scripts/check-browser.ts
index d5578ac..bc3581e 100644
--- a/scripts/check-browser.ts
+++ b/scripts/check-browser.ts
@@ -9,7 +9,7 @@ import { execFileSync } from "node:child_process"
import { chromium } from "playwright"
import type { EditQueue } from "../src/game/edits.ts"
import type { Interaction, Shown } from "../src/view/contracts.ts"
-import type { GameScene } from "../src/render/three/scene.ts"
+import type { GameScene } from "../src/render/pixi3d/scene.ts"
import type { Snapshot } from "../src/game/headless.ts"
declare global {
diff --git a/scripts/check-model-revisions.ts b/scripts/check-model-revisions.ts
index 9d741aa..eea6005 100644
--- a/scripts/check-model-revisions.ts
+++ b/scripts/check-model-revisions.ts
@@ -2,7 +2,7 @@ import assert from "node:assert/strict"
import { existsSync } from "node:fs"
import { mkdir, writeFile } from "node:fs/promises"
import { chromium } from "playwright"
-import { inkAssets } from "../src/render/three/assets/assets.ts"
+import { inkAssets } from "../src/render/pixi3d/assets/assets.ts"
const executablePath=process.env.BROWSER_EXECUTABLE_PATH??["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].find(existsSync)
const browser=await chromium.launch({headless:true,...(executablePath?{executablePath}:{})})
diff --git a/scripts/ink-assets.ts b/scripts/ink-assets.ts
index deebb4b..6e93394 100644
--- a/scripts/ink-assets.ts
+++ b/scripts/ink-assets.ts
@@ -1,10 +1,10 @@
import { mkdir, readFile, writeFile } from "node:fs/promises"
import path from "node:path"
import { build } from "vite"
-import { inkAssets } from "../src/render/three/assets/assets.ts"
+import { inkAssets } from "../src/render/pixi3d/assets/assets.ts"
import * as THREE from "three"
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"
-import { exportAsset } from "../src/render/three/assets/renderer.ts"
+import { exportAsset } from "../src/render/pixi3d/assets/renderer.ts"
// GLTFExporter uses the browser's FileReader to assemble binary buffers.
// There are no textures here; only readAsArrayBuffer is needed in Node.
diff --git a/scripts/snapshot-parks.ts b/scripts/snapshot-parks.ts
index e946411..0c026b1 100644
--- a/scripts/snapshot-parks.ts
+++ b/scripts/snapshot-parks.ts
@@ -3,7 +3,7 @@ import { gzipSync } from "node:zlib"
import { mkdir, writeFile } from "node:fs/promises"
import { execFileSync } from "node:child_process"
import { parkReviewModels } from "../src/labs/model-review/park-models.ts"
-import { assetById } from "../src/render/three/assets/assets.ts"
+import { assetById } from "../src/render/pixi3d/assets/assets.ts"
const revision=execFileSync("git",["rev-parse","HEAD"],{encoding:"utf8"}).trim()
if(revision!=="f4df9d5f9e1ff74552e5a29a3366ec9f541bb3bd")throw new Error("Capture parks from the approved proportion revision")
diff --git a/scripts/snapshot-proportions.ts b/scripts/snapshot-proportions.ts
index 828f19c..6e32826 100644
--- a/scripts/snapshot-proportions.ts
+++ b/scripts/snapshot-proportions.ts
@@ -4,7 +4,7 @@ import { gzipSync } from "node:zlib"
import { mkdir, writeFile } from "node:fs/promises"
import { execFileSync } from "node:child_process"
import { proportionModels } from "../src/labs/model-review/proportion-models.ts"
-import { assetById } from "../src/render/three/assets/assets.ts"
+import { assetById } from "../src/render/pixi3d/assets/assets.ts"
const revision = execFileSync("git", ["rev-parse", "HEAD"], {encoding: "utf8"}).trim()
if (revision !== "a2845b4f537dcb2998a58b7fae26783d7de4a1ec") throw new Error("Baseline must be captured from the approved a2845b4 revision")
diff --git a/src/app/browser.ts b/src/app/browser.ts
index c8174e9..cd677e6 100644
--- a/src/app/browser.ts
+++ b/src/app/browser.ts
@@ -10,7 +10,7 @@ import { FixedLoop, HostClock, Result } from "@typeonce/ritmo"
import { Effect } from "effect"
import { BrowserHostClock } from "@typeonce/ritmo-browser"
-import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "../render/three/views.ts"
+import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "../render/pixi3d/views.ts"
import { lands, sizes, step } from "../game/content/index.ts"
import { bookkeeping, editQueue } from "../game/edits.ts"
import { resolveRules } from "../game/rules/config.ts"
@@ -18,11 +18,11 @@ import { blankResources, settle, simulate } from "../game/schedule.ts"
import { Edits, Game, Rules } from "../game/schema.ts"
import { browserStorage, describe, fileOf, latest, loadLatest, loadText, save, Storage, World } from "../platform/save.ts"
import { download, sharedId } from "../platform/share/client.ts"
-import { MapInput } from "../render/three/input.ts"
-import { GameScene, type CameraView } from "../render/three/scene.ts"
-import { draw } from "../render/three/schedule.ts"
-import { BuildingNodes, FieldNodes, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, WalkerNodes } from "../render/three/services.ts"
-import { thumbnails } from "../render/three/thumbnails.ts"
+import { MapInput } from "../render/pixi3d/input.ts"
+import { GameScene, type CameraView } from "../render/pixi3d/scene.ts"
+import { draw } from "../render/pixi3d/schedule.ts"
+import { BuildingNodes, FieldNodes, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, WalkerNodes } from "../render/pixi3d/services.ts"
+import { thumbnails } from "../render/pixi3d/thumbnails.ts"
import { createDomUi, type Persistence } from "../ui/dom/index.ts"
import { blankInteraction, blankShown } from "../view/contracts.ts"
import { project } from "../view/schedule.ts"
@@ -53,7 +53,7 @@ const start = async () => {
const shown = blankShown()
const edits = editQueue()
// The renderer draws into `mount`; the page's UI goes around it, and reaches the map only through `MapPort`.
- const stage = new GameScene(mount)
+ const stage = await GameScene.create(mount)
let input: MapInput | null = null
const page = createDomUi<CameraView>(
{ interaction, shown, send: edits.push },
@@ -69,7 +69,7 @@ const start = async () => {
reset: () => input?.reset(),
sync: () => input?.sync()
},
- thumbnails(),
+ thumbnails(stage.app.renderer),
() => persistence,
{ shared: shared !== null, saved }
)
diff --git a/src/app/lint.ts b/src/app/lint.ts
index 838c7ce..190cc0a 100644
--- a/src/app/lint.ts
+++ b/src/app/lint.ts
@@ -19,7 +19,7 @@ import { Edits, Game, Rules } from "../game/schema.ts"
const lintCharter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }
export const lintTarget = async () => {
- const [{ draw }, { project }] = await Promise.all([import("../render/three/schedule.ts"), import("../view/schedule.ts")])
+ const [{ draw }, { project }] = await Promise.all([import("../render/pixi3d/schedule.ts"), import("../view/schedule.ts")])
const made = Game.Runtime.make({
services: Game.Runtime.services(Game.Runtime.service(Edits, founding(lintCharter)), Game.Runtime.service(Rules, resolveRules())),
resources: blankResources(),
diff --git a/src/labs/asset-lab/main.ts b/src/labs/asset-lab/main.ts
index 27c7000..0044d6c 100644
--- a/src/labs/asset-lab/main.ts
+++ b/src/labs/asset-lab/main.ts
@@ -19,12 +19,12 @@ import {
} from "../../render/art.ts"
import { kinds, goods } from "../../game/content/index.ts"
import { key } from "../../game/world/grid.ts"
-import { samplePark } from "../../render/three/assets/town-props.ts"
+import { samplePark } from "../../render/pixi3d/assets/town-props.ts"
import type { PropId } from "../../game/content/index.ts"
import { drawPlot } from "../../render/art.ts"
import { U, toScreen } from "../../game/world/iso.ts"
-import { inkAssets, assetCategoryTitles, type InkAsset } from "../../render/three/assets/assets.ts"
-import { buildAsset, exportAsset, reloadExportedAsset } from "../../render/three/assets/renderer.ts"
+import { inkAssets, assetCategoryTitles, type InkAsset } from "../../render/pixi3d/assets/assets.ts"
+import { buildAsset, exportAsset, reloadExportedAsset } from "../../render/pixi3d/assets/renderer.ts"
import "./style.css"
const root = document.querySelector<HTMLDivElement>("#lab")!
diff --git a/src/labs/effects-lab/main.ts b/src/labs/effects-lab/main.ts
index 2f027d5..c440064 100644
--- a/src/labs/effects-lab/main.ts
+++ b/src/labs/effects-lab/main.ts
@@ -1,10 +1,10 @@
import * as THREE from "three"
-import { house } from "../../render/three/assets/homes.ts"
+import { house } from "../../render/pixi3d/assets/homes.ts"
import { home, type Tier } from "../../game/content/index.ts"
import { U } from "../../game/world/iso.ts"
-import { ModelHandle,ModelPool } from "../../render/three/pool.ts"
-import { surfaceState,type SurfaceState } from "../../render/three/surface-state.ts"
-import { StructureEffects } from "../../render/three/structure-effects.ts"
+import { ModelHandle,ModelPool } from "../../render/pixi3d/pool.ts"
+import { surfaceState,type SurfaceState } from "../../render/pixi3d/surface-state.ts"
+import { StructureEffects } from "../../render/pixi3d/structure-effects.ts"
import "./style.css"
const cases: Array<{title:string;note:string;state:Partial<SurfaceState>}>=[
diff --git a/src/labs/map-lab/main.ts b/src/labs/map-lab/main.ts
index 546146c..ca3bdbc 100644
--- a/src/labs/map-lab/main.ts
+++ b/src/labs/map-lab/main.ts
@@ -1,8 +1,8 @@
import * as THREE from "three"
import { OrbitControls } from "three/addons/controls/OrbitControls.js"
-import { buildAsset, floorScale } from "../../render/three/assets/renderer.ts"
-import { inkAssets } from "../../render/three/assets/assets.ts"
-import { makePerson } from "../../render/three/assets/people.ts"
+import { buildAsset, floorScale } from "../../render/pixi3d/assets/renderer.ts"
+import { inkAssets } from "../../render/pixi3d/assets/assets.ts"
+import { makePerson } from "../../render/pixi3d/assets/people.ts"
import { testMap, districts } from "./map.ts"
import "./style.css"
diff --git a/src/labs/map-lab/map.ts b/src/labs/map-lab/map.ts
index 7f59bc9..96c90fa 100644
--- a/src/labs/map-lab/map.ts
+++ b/src/labs/map-lab/map.ts
@@ -1,4 +1,4 @@
-import { inkAssets, palette, type InkAsset, type Vertex } from "../../render/three/assets/assets.ts"
+import { inkAssets, palette, type InkAsset, type Vertex } from "../../render/pixi3d/assets/assets.ts"
export interface MapBuilding {
id: number
diff --git a/src/labs/model-review/main.ts b/src/labs/model-review/main.ts
index b000b2a..71164e0 100644
--- a/src/labs/model-review/main.ts
+++ b/src/labs/model-review/main.ts
@@ -1,8 +1,8 @@
import * as THREE from "three"
-import { assetById } from "../../render/three/assets/assets.ts"
-import { buildAsset, exportAsset } from "../../render/three/assets/renderer.ts"
+import { assetById } from "../../render/pixi3d/assets/assets.ts"
+import { buildAsset, exportAsset } from "../../render/pixi3d/assets/renderer.ts"
import { kindIds } from "../../game/content/index.ts"
-import { ruralIds } from "../../render/three/assets/rural.ts"
+import { ruralIds } from "../../render/pixi3d/assets/rural.ts"
import "./style.css"
import "./handoff.css"
diff --git a/src/labs/model-review/park-models.ts b/src/labs/model-review/park-models.ts
index df5a2c9..930c8e3 100644
--- a/src/labs/model-review/park-models.ts
+++ b/src/labs/model-review/park-models.ts
@@ -1,6 +1,6 @@
-import { assetById } from "../../render/three/assets/assets.ts"
-import { Drawing, type InkAsset, type Vertex } from "../../render/three/assets/primitives.ts"
-import { bench, flowerBed, parkAsset } from "../../render/three/assets/town-props.ts"
+import { assetById } from "../../render/pixi3d/assets/assets.ts"
+import { Drawing, type InkAsset, type Vertex } from "../../render/pixi3d/assets/primitives.ts"
+import { bench, flowerBed, parkAsset } from "../../render/pixi3d/assets/town-props.ts"
import { builtPark } from "../park-lab/park.ts"
import { key } from "../../game/world/grid.ts"
import type { GroundId } from "../../game/content/index.ts"
diff --git a/src/labs/model-review/proportion-models.ts b/src/labs/model-review/proportion-models.ts
index 21bdfdc..ef35912 100644
--- a/src/labs/model-review/proportion-models.ts
+++ b/src/labs/model-review/proportion-models.ts
@@ -1,9 +1,9 @@
import type { KindId } from "../../game/content/index.ts"
-import { assetById } from "../../render/three/assets/assets.ts"
-import { Drawing, type InkAsset } from "../../render/three/assets/primitives.ts"
-import { chair, chest } from "../../render/three/assets/furniture.ts"
-import { bench } from "../../render/three/assets/town-props.ts"
-import { scaffoldAsset } from "../../render/three/assets/scaffolding.ts"
+import { assetById } from "../../render/pixi3d/assets/assets.ts"
+import { Drawing, type InkAsset } from "../../render/pixi3d/assets/primitives.ts"
+import { chair, chest } from "../../render/pixi3d/assets/furniture.ts"
+import { bench } from "../../render/pixi3d/assets/town-props.ts"
+import { scaffoldAsset } from "../../render/pixi3d/assets/scaffolding.ts"
// This review belongs to one approved revision. Future building kinds should
// not silently join a comparison whose frozen originals cannot contain them.
diff --git a/src/labs/model-review/proportions.ts b/src/labs/model-review/proportions.ts
index a856bdf..287439e 100644
--- a/src/labs/model-review/proportions.ts
+++ b/src/labs/model-review/proportions.ts
@@ -1,6 +1,6 @@
import * as THREE from "three"
-import { buildAsset, vertex3 } from "../../render/three/assets/renderer.ts"
-import type { InkAsset } from "../../render/three/assets/primitives.ts"
+import { buildAsset, vertex3 } from "../../render/pixi3d/assets/renderer.ts"
+import type { InkAsset } from "../../render/pixi3d/assets/primitives.ts"
import { proportionModels, architectureIds } from "./proportion-models.ts"
import { parkReviewModels } from "./park-models.ts"
import "./proportions.css"
diff --git a/src/labs/park-lab/main.ts b/src/labs/park-lab/main.ts
index afb46e0..490679d 100644
--- a/src/labs/park-lab/main.ts
+++ b/src/labs/park-lab/main.ts
@@ -1,6 +1,6 @@
import * as THREE from "three"
-import { assetById } from "../../render/three/assets/assets.ts"
-import { buildAsset, type BuiltAsset } from "../../render/three/assets/renderer.ts"
+import { assetById } from "../../render/pixi3d/assets/assets.ts"
+import { buildAsset, type BuiltAsset } from "../../render/pixi3d/assets/renderer.ts"
import { builtPark, parkCells, parkSummary } from "./park.ts"
import "./style.css"
diff --git a/src/labs/park-lab/park.ts b/src/labs/park-lab/park.ts
index 980e7d6..8262626 100644
--- a/src/labs/park-lab/park.ts
+++ b/src/labs/park-lab/park.ts
@@ -1,8 +1,8 @@
-import { samplePark, parkAsset } from "../../render/three/assets/town-props.ts"
-import { groundAsset } from "../../render/three/models.ts"
+import { samplePark, parkAsset } from "../../render/pixi3d/assets/town-props.ts"
+import { groundAsset } from "../../render/pixi3d/models.ts"
import { parksOf } from "../../game/world/appeal.ts"
import { key } from "../../game/world/grid.ts"
-import type { InkAsset, Vertex } from "../../render/three/assets/primitives.ts"
+import type { InkAsset, Vertex } from "../../render/pixi3d/assets/primitives.ts"
// Place actual park cells beside two road entrances, inside the game's grid.
export const parkCells=samplePark.map(c=>({...c,x:c.x+28,y:c.y+28}))
diff --git a/src/labs/service-study/main.ts b/src/labs/service-study/main.ts
index 5585308..ce13d07 100644
--- a/src/labs/service-study/main.ts
+++ b/src/labs/service-study/main.ts
@@ -1,6 +1,6 @@
import * as THREE from "three"
-import { assetById } from "../../render/three/assets/assets.ts"
-import { buildAsset, exportAsset, floorScale, vertex3 } from "../../render/three/assets/renderer.ts"
+import { assetById } from "../../render/pixi3d/assets/assets.ts"
+import { buildAsset, exportAsset, floorScale, vertex3 } from "../../render/pixi3d/assets/renderer.ts"
import "./style.css"
const root = document.querySelector<HTMLElement>("#service-study")!
diff --git a/src/render/art.ts b/src/render/art.ts
index a1fe410..e7c57e9 100644
--- a/src/render/art.ts
+++ b/src/render/art.ts
@@ -20,7 +20,7 @@
* - a crate is 6 units wide, a carried one 4.
*/
import { Container, Graphics } from "pixi.js"
-import type { SurfaceState } from "./three/surface-state.ts"
+import type { SurfaceState } from "./pixi3d/surface-state.ts"
import { goods, GROWN, home, kinds, ROCK_AMOUNT, type GoodId, type GroundId, type Kind, type KindId, type PropId, type Tier } from "../game/content/index.ts"
import { cellOf, DIRS, key } from "../game/world/grid.ts"
diff --git a/src/render/three/assets/appearance.ts b/src/render/pixi3d/assets/appearance.ts
similarity index 100%
rename from src/render/three/assets/appearance.ts
rename to src/render/pixi3d/assets/appearance.ts
diff --git a/src/render/three/assets/assets.ts b/src/render/pixi3d/assets/assets.ts
similarity index 100%
rename from src/render/three/assets/assets.ts
rename to src/render/pixi3d/assets/assets.ts
diff --git a/src/render/three/assets/buildings.ts b/src/render/pixi3d/assets/buildings.ts
similarity index 100%
rename from src/render/three/assets/buildings.ts
rename to src/render/pixi3d/assets/buildings.ts
diff --git a/src/render/three/assets/carpenter.ts b/src/render/pixi3d/assets/carpenter.ts
similarity index 100%
rename from src/render/three/assets/carpenter.ts
rename to src/render/pixi3d/assets/carpenter.ts
diff --git a/src/render/three/assets/civic.ts b/src/render/pixi3d/assets/civic.ts
similarity index 100%
rename from src/render/three/assets/civic.ts
rename to src/render/pixi3d/assets/civic.ts
diff --git a/src/render/three/assets/construction.ts b/src/render/pixi3d/assets/construction.ts
similarity index 100%
rename from src/render/three/assets/construction.ts
rename to src/render/pixi3d/assets/construction.ts
diff --git a/src/render/three/assets/dimensions.ts b/src/render/pixi3d/assets/dimensions.ts
similarity index 100%
rename from src/render/three/assets/dimensions.ts
rename to src/render/pixi3d/assets/dimensions.ts
diff --git a/src/render/three/assets/furniture.ts b/src/render/pixi3d/assets/furniture.ts
similarity index 100%
rename from src/render/three/assets/furniture.ts
rename to src/render/pixi3d/assets/furniture.ts
diff --git a/src/render/pixi3d/assets/glb.ts b/src/render/pixi3d/assets/glb.ts
new file mode 100644
index 0000000..9d04abd
--- /dev/null
+++ b/src/render/pixi3d/assets/glb.ts
@@ -0,0 +1,128 @@
+/**
+ * Binary glTF 2.0 for the catalogue, with no renderer in it: `exportAsset`
+ * writes a model's meshes (see `exportMeshes`) with unlit materials
+ * (`KHR_materials_unlit`) and its effect parameters as extras on the root
+ * node; `readGlb` reads one back, for the export checks in Node.
+ *
+ * Colours are written as glTF asks: linear, from sRGB by the piecewise curve.
+ */
+import type { InkAsset } from "./primitives.ts"
+import { exportMeshes } from "./ink-mesh.ts"
+import { bounds } from "../mesh/geometry.ts"
+
+const GLB = 0x46546c67, JSON_CHUNK = 0x4e4f534a, BIN_CHUNK = 0x004e4942
+const FLOAT = 5126, UNSIGNED_SHORT = 5123, UNSIGNED_INT = 5125
+const ARRAY_BUFFER = 34962, ELEMENT_ARRAY_BUFFER = 34963
+
+const linear = (channel: number) => {
+ const c = channel / 255
+ return c < 0.04045 ? c * 0.0773993808 : (c * 0.9478672986 + 0.0521327014) ** 2.4
+}
+
+interface Accessor { bufferView: number; componentType: number; count: number; type: "SCALAR" | "VEC3"; min?: Array<number>; max?: Array<number> }
+
+/** The model as a GLB: one node a material under a root named for the asset, its effects in the root's extras. */
+export function writeGlb(asset: InkAsset): ArrayBuffer {
+ const chunks: Array<Uint8Array> = [], bufferViews: Array<{ buffer: 0; byteOffset: number; byteLength: number; target: number }> = []
+ const accessors: Array<Accessor> = [], materials: Array<unknown> = [], meshes: Array<unknown> = [], nodes: Array<{ name?: string; mesh?: number; children?: Array<number>; extras?: Record<string, unknown> }> = []
+ let byteLength = 0
+ const view = (bytes: Uint8Array, target: number) => {
+ const padding = (4 - (byteLength % 4)) % 4
+ if (padding) {
+ chunks.push(new Uint8Array(padding))
+ byteLength += padding
+ }
+ bufferViews.push({ buffer: 0, byteOffset: byteLength, byteLength: bytes.byteLength, target })
+ chunks.push(bytes)
+ byteLength += bytes.byteLength
+ return bufferViews.length - 1
+ }
+ for (const { material, mesh } of exportMeshes(asset)) {
+ const [min, max] = bounds(mesh)
+ const position = accessors.push({ bufferView: view(new Uint8Array(mesh.positions.buffer.slice(0)), ARRAY_BUFFER), componentType: FLOAT, count: mesh.positions.length / 3, type: "VEC3", min: [...min], max: [...max] }) - 1
+ const normal = accessors.push({ bufferView: view(new Uint8Array(mesh.normals.buffer.slice(0)), ARRAY_BUFFER), componentType: FLOAT, count: mesh.normals.length / 3, type: "VEC3" }) - 1
+ const index = mesh.index!
+ const wide = mesh.positions.length / 3 > 65535
+ const indices = accessors.push({ bufferView: view(new Uint8Array((wide ? Uint32Array.from(index) : Uint16Array.from(index)).buffer), ELEMENT_ARRAY_BUFFER), componentType: wide ? UNSIGNED_INT : UNSIGNED_SHORT, count: index.length, type: "SCALAR" }) - 1
+ materials.push({
+ pbrMetallicRoughness: { baseColorFactor: [linear((material.color >> 16) & 255), linear((material.color >> 8) & 255), linear(material.color & 255), material.opacity], metallicFactor: 0, roughnessFactor: 1 },
+ ...(material.opacity < 1 ? { alphaMode: "BLEND" } : {}),
+ ...(material.doubleSided ? { doubleSided: true } : {}),
+ extensions: { KHR_materials_unlit: {} }
+ })
+ meshes.push({ primitives: [{ attributes: { POSITION: position, NORMAL: normal }, indices, mode: 4, material: materials.length - 1 }] })
+ nodes.push({ mesh: meshes.length - 1 })
+ }
+ const extras: Record<string, unknown> = {}
+ if (asset.effects) extras.inklineSurfaceEffects = asset.effects
+ if (asset.smokeEffect) extras.inklineSmokeEffect = asset.smokeEffect
+ if (asset.fountains?.length) extras.inklineFountains = asset.fountains
+ nodes.push({ name: asset.id, children: nodes.map((_, i) => i), ...(Object.keys(extras).length ? { extras } : {}) })
+ const json = {
+ asset: { version: "2.0", generator: "Inkline Town" },
+ extensionsUsed: ["KHR_materials_unlit"],
+ scene: 0,
+ scenes: [{ nodes: [nodes.length - 1] }],
+ nodes,
+ meshes,
+ materials,
+ accessors,
+ bufferViews,
+ buffers: [{ byteLength }]
+ }
+ const pad = (n: number) => (4 - (n % 4)) % 4
+ const text = new TextEncoder().encode(JSON.stringify(json)), jsonLength = text.length + pad(text.length), binLength = byteLength + pad(byteLength)
+ const out = new Uint8Array(12 + 8 + jsonLength + 8 + binLength), data = new DataView(out.buffer)
+ data.setUint32(0, GLB, true)
+ data.setUint32(4, 2, true)
+ data.setUint32(8, out.length, true)
+ data.setUint32(12, jsonLength, true)
+ data.setUint32(16, JSON_CHUNK, true)
+ out.set(text, 20)
+ out.fill(0x20, 20 + text.length, 20 + jsonLength)
+ let o = 20 + jsonLength
+ data.setUint32(o, binLength, true)
+ data.setUint32(o + 4, BIN_CHUNK, true)
+ o += 8
+ for (const chunk of chunks) {
+ out.set(chunk, o)
+ o += chunk.byteLength
+ }
+ return out.buffer
+}
+
+/** The GLB of a catalogue model (asynchronous, as the three.js exporter was). */
+export async function exportAsset(asset: InkAsset): Promise<ArrayBuffer> {
+ return writeGlb(asset)
+}
+
+export interface GlbNode { readonly name?: string; readonly mesh?: number; readonly children?: ReadonlyArray<number>; readonly extras?: Record<string, unknown> }
+export interface GlbContents {
+ readonly nodes: ReadonlyArray<GlbNode>
+ readonly materials: ReadonlyArray<{ readonly extensions?: Record<string, unknown>; readonly pbrMetallicRoughness?: { readonly baseColorFactor?: ReadonlyArray<number> } }>
+ readonly meshes: ReadonlyArray<{ readonly primitives: ReadonlyArray<{ readonly attributes: Record<string, number>; readonly indices?: number; readonly material?: number }> }>
+ /** An accessor's values, as floats. */
+ accessor(index: number): Float32Array
+}
+/** A GLB's JSON, and its accessors read from its binary chunk. */
+export function readGlb(buffer: ArrayBuffer): GlbContents {
+ const data = new DataView(buffer)
+ if (data.getUint32(0, true) !== GLB || data.getUint32(4, true) !== 2) throw new Error("Not a glTF 2.0 binary")
+ const jsonLength = data.getUint32(12, true)
+ if (data.getUint32(16, true) !== JSON_CHUNK) throw new Error("GLB without a JSON chunk")
+ const json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, jsonLength)))
+ const binAt = 20 + jsonLength
+ if (data.getUint32(binAt + 4, true) !== BIN_CHUNK) throw new Error("GLB without a binary chunk")
+ const bin = binAt + 8
+ const sizes: Record<string, number> = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4 }
+ return {
+ nodes: json.nodes ?? [],
+ materials: json.materials ?? [],
+ meshes: json.meshes ?? [],
+ accessor(index) {
+ const a = json.accessors[index], v = json.bufferViews[a.bufferView], at = bin + (v.byteOffset ?? 0) + (a.byteOffset ?? 0), n = a.count * sizes[a.type]!
+ const values = a.componentType === FLOAT ? new Float32Array(buffer.slice(at, at + n * 4)) : a.componentType === UNSIGNED_INT ? new Uint32Array(buffer.slice(at, at + n * 4)) : new Uint16Array(buffer.slice(at, at + n * 2))
+ return Float32Array.from(values)
+ }
+ }
+}
diff --git a/src/render/three/assets/homes.ts b/src/render/pixi3d/assets/homes.ts
similarity index 100%
rename from src/render/three/assets/homes.ts
rename to src/render/pixi3d/assets/homes.ts
diff --git a/src/render/pixi3d/assets/ink-mesh.ts b/src/render/pixi3d/assets/ink-mesh.ts
new file mode 100644
index 0000000..cd262a9
--- /dev/null
+++ b/src/render/pixi3d/assets/ink-mesh.ts
@@ -0,0 +1,186 @@
+/**
+ * An `InkAsset` as mesh data, with no renderer in it: the parts the Pixi 3D
+ * adapter draws (`renderer.ts`) and the GLB writer exports (`glb.ts`).
+ *
+ * - fills: the faces, batched by colour, drawn double-sided and pushed back in
+ * depth so ink on their edges always wins;
+ * - hulls: smooth props' and foliage's inward hulls, which give curved
+ * contours a continuous ink silhouette at every zoom;
+ * - ink: strokes as six-sided rods, and long curved strokes as tubes;
+ * - contours: sharp contours' edges as rods carrying both faces' normals
+ * (`aInkNormalA`, `aInkNormalB`), shown only where one face turns towards
+ * the camera and the other away (see `inkSilhouetteBit`);
+ * - lines: strokes drawn as camera-facing ribbons a world width across
+ * (see `inkLineBit`), for the town's ground layers.
+ */
+import { palette, type Face, type InkAsset } from "./primitives.ts"
+import { vertex3 } from "./space.ts"
+import { merge, mergeVertices, polygon, rod, triangles, tube, unindexed, withConstant, type MeshData } from "../mesh/geometry.ts"
+import { add, cross, dot, mean, normalize, scale, sub, type Vec3 } from "../mesh/vec3.ts"
+
+export type PartRole = "fill" | "hull" | "ink" | "contour" | "line"
+export interface InkPart {
+ readonly role: PartRole
+ readonly color: number
+ readonly opacity: number
+ /** For `line`: two vertices per segment. */
+ readonly mesh: MeshData
+ /** For `line`: the ribbon's width in world units. */
+ readonly width: number
+}
+export interface InkMeshOptions {
+ /** Faces merged by colour (the live town), or one part a face. */
+ readonly batchFaces?: boolean
+ /** Short strokes as rods (the live town's shared models), or as ribbons. */
+ readonly meshInk?: boolean
+ /** Every contour drawn as a hull, not only the curved ones. */
+ readonly hullContours?: boolean
+ /** Sharp contours drawn as silhouette edges (default), or left to the faces. */
+ readonly contours?: boolean
+}
+
+const fixed = (p: Vec3) => p.map((n) => n.toFixed(4)).join(",")
+
+function contourCenters(asset: InkAsset) {
+ const sums = new Map<number, Array<Vec3>>()
+ for (const face of asset.faces)
+ if (face.contour) {
+ const points = sums.get(face.contour) ?? []
+ points.push(...face.points.map(vertex3))
+ sums.set(face.contour, points)
+ }
+ return new Map([...sums].map(([id, points]) => [id, mean(points)]))
+}
+function outwardPoints(face: Face, centers: Map<number, Vec3>): Array<Vec3> {
+ const ps = face.points.map(vertex3)
+ const normal = cross(sub(ps[1]!, ps[0]!), sub(ps[2]!, ps[0]!))
+ if (dot(normal, sub(mean(ps), centers.get(face.contour!)!)) < 0) ps.reverse()
+ return ps
+}
+
+/** Inward hulls give short curved contours a continuous ink silhouette, including at high zoom. */
+function silhouette(asset: InkAsset, faces: ReadonlyArray<Face>): MeshData {
+ const centers = contourCenters(asset), normals = new Map<string, Vec3>()
+ const key = (p: Vec3, contour: number) => `${contour}|${fixed(p)}`
+ for (const face of faces) {
+ const ps = outwardPoints(face, centers), n = normalize(cross(sub(ps[1]!, ps[0]!), sub(ps[2]!, ps[0]!)))
+ for (const p of ps) normals.set(key(p, face.contour!), add(normals.get(key(p, face.contour!)) ?? [0, 0, 0], n))
+ }
+ const positions: Array<number> = []
+ for (const face of faces) {
+ const ps = outwardPoints(face, centers).map((p) => add(p, scale(normalize(normals.get(key(p, face.contour!))!), (face.contourWidth ?? 1) * 0.5)))
+ for (let i = 1; i < ps.length - 1; i++) for (const p of [ps[0]!, ps[i + 1]!, ps[i]!]) positions.push(...p)
+ }
+ return triangles(positions)
+}
+
+const strokeKey = (s: { width: number; color: number; opacity: number }) => `${s.width}/${s.color}/${s.opacity}`
+
+export function inkMesh(asset: InkAsset, options: InkMeshOptions = {}): Array<InkPart> {
+ const parts: Array<InkPart> = []
+ if (options.batchFaces) {
+ const batches = new Map<string, { color: number; opacity: number; meshes: Array<MeshData> }>()
+ for (const face of asset.faces) {
+ const key = `${face.color}/${face.opacity ?? 1}`, batch = batches.get(key) ?? { color: face.color, opacity: face.opacity ?? 1, meshes: [] }
+ batch.meshes.push(polygon(face.points.map(vertex3)))
+ batches.set(key, batch)
+ }
+ for (const { color, opacity, meshes } of batches.values()) parts.push({ role: "fill", color, opacity, mesh: merge(meshes), width: 0 })
+ } else for (const face of asset.faces) parts.push({ role: "fill", color: face.color, opacity: face.opacity ?? 1, mesh: polygon(face.points.map(vertex3)), width: 0 })
+
+ const curves = new Map<string, { meshes: Array<MeshData>; color: number; opacity: number }>()
+ const lines = new Map<string, { positions: Array<number>; width: number; color: number; opacity: number }>()
+ for (const stroke of asset.strokes) {
+ const key = strokeKey(stroke)
+ const curve = () => curves.get(key) ?? { meshes: [], color: stroke.color, opacity: stroke.opacity }
+ if (options.meshInk && stroke.width > 0 && stroke.points.length <= 8) {
+ const batch = curve()
+ for (let i = 1; i < stroke.points.length; i++) {
+ const segment = rod(vertex3(stroke.points[i - 1]!), vertex3(stroke.points[i]!), stroke.width)
+ if (segment) batch.meshes.push(segment)
+ }
+ if (batch.meshes.length) curves.set(key, batch)
+ continue
+ }
+ // Continuous tubes keep small circle joins clean at high magnification.
+ const first = stroke.points[0]!, last = stroke.points.at(-1)!
+ if (stroke.width > 0 && stroke.points.length > 8) {
+ const closed = first.every((n, i) => Math.abs(n - last[i]!) < 1e-6)
+ const batch = curve()
+ batch.meshes.push(tube((closed ? stroke.points.slice(0, -1) : stroke.points).map(vertex3), closed, (stroke.points.length - 1) * 2, stroke.width / 2, 6))
+ curves.set(key, batch)
+ continue
+ }
+ const batch = lines.get(key) ?? { positions: [], width: stroke.width, color: stroke.color, opacity: stroke.opacity }
+ for (let i = 1; i < stroke.points.length; i++) batch.positions.push(...vertex3(stroke.points[i - 1]!), ...vertex3(stroke.points[i]!))
+ lines.set(key, batch)
+ }
+ for (const b of lines.values()) parts.push({ role: "line", color: b.color, opacity: b.opacity, width: b.width, mesh: { positions: Float32Array.from(b.positions), normals: new Float32Array(b.positions.length), index: null, attributes: {} } })
+ for (const { meshes, color, opacity } of curves.values()) parts.push({ role: "ink", color, opacity, mesh: merge(meshes), width: 0 })
+
+ // Smooth props and foliage get view-dependent silhouette edges, without drawing their hidden edges or the
+ // internal triangulation.
+ const counts = new Map<number, number>()
+ for (const face of asset.faces) if (face.contour) counts.set(face.contour, (counts.get(face.contour) ?? 0) + 1)
+ const smooth = new Set([...counts].filter(([, count]) => options.hullContours || count > 6).map(([id]) => id))
+ const smoothFaces = asset.faces.filter((f) => f.contour && smooth.has(f.contour) && (f.contourWidth ?? 1) > 0)
+ if (smoothFaces.length) parts.push({ role: "hull", color: palette.ink, opacity: 1, mesh: silhouette(asset, smoothFaces), width: 0 })
+ if (options.contours === false) return parts
+
+ const edges = new Map<string, { a: Vec3; b: Vec3; normals: Array<Vec3>; width: number }>()
+ const centers = contourCenters(asset)
+ for (const face of asset.faces.filter((f) => f.contour && !smooth.has(f.contour))) {
+ const points = outwardPoints(face, centers)
+ const normal = normalize(cross(sub(points[1]!, points[0]!), sub(points[2]!, points[0]!)))
+ for (let i = 0; i < points.length; i++) {
+ const a = points[i]!, b = points[(i + 1) % points.length]!
+ const key = `${face.contour}|${[fixed(a), fixed(b)].sort().join("|")}`
+ const edge = edges.get(key) ?? { a, b, normals: [], width: face.contourWidth ?? 1 }
+ edge.normals.push(normal)
+ edges.set(key, edge)
+ }
+ }
+ // GPU silhouette masks let sharp foliage share instances at every camera angle, without a wireframe or an
+ // expanded hull crossing the canopy.
+ const contourBatches = new Map<number, Array<MeshData>>()
+ for (const { a, b, normals, width } of edges.values()) {
+ if (width <= 0) continue
+ const segment = rod(a, b, width)
+ if (!segment) continue
+ const n1 = normals[0]!, n2 = normals[1] ?? scale(n1, -1)
+ const batch = contourBatches.get(width) ?? []
+ batch.push(withConstant(withConstant(segment, "aInkNormalA", n1), "aInkNormalB", n2))
+ contourBatches.set(width, batch)
+ }
+ for (const meshes of contourBatches.values()) parts.push({ role: "contour", color: palette.ink, opacity: 1, mesh: merge(meshes), width: 0 })
+ return parts
+}
+
+/** A material as the GLB records it: unlit, its colour and opacity, one side or both. */
+export interface ExportMaterial {
+ readonly color: number
+ readonly opacity: number
+ readonly doubleSided: boolean
+}
+/**
+ * The meshes a GLB carries, one per material: the faces, an inward hull for
+ * every contour, and every stroke as rods, so the outlines survive import
+ * into any renderer. Vertices are welded, and only positions and normals kept.
+ */
+export function exportMeshes(asset: InkAsset): Array<{ material: ExportMaterial; mesh: MeshData }> {
+ const batches = new Map<string, { material: ExportMaterial; meshes: Array<MeshData> }>()
+ const add = (key: string, material: ExportMaterial, mesh: MeshData) => {
+ const batch = batches.get(key) ?? { material, meshes: [] }
+ batch.meshes.push(unindexed(mesh))
+ batches.set(key, batch)
+ }
+ for (const face of asset.faces) add(`fill/${face.color}/${face.opacity ?? 1}`, { color: face.color, opacity: face.opacity ?? 1, doubleSided: true }, polygon(face.points.map(vertex3)))
+ const contourFaces = asset.faces.filter((face) => face.contour)
+ if (contourFaces.length) add("hull", { color: palette.ink, opacity: 1, doubleSided: false }, silhouette(asset, contourFaces))
+ for (const stroke of asset.strokes)
+ for (let i = 1; i < stroke.points.length; i++) {
+ const segment = rod(vertex3(stroke.points[i - 1]!), vertex3(stroke.points[i]!), stroke.width)
+ if (segment) add(`ink/${stroke.color}/${stroke.opacity}`, { color: stroke.color, opacity: stroke.opacity, doubleSided: false }, segment)
+ }
+ return [...batches.values()].map(({ material, meshes }) => ({ material, mesh: mergeVertices(merge(meshes)) }))
+}
diff --git a/src/render/three/assets/land.ts b/src/render/pixi3d/assets/land.ts
similarity index 100%
rename from src/render/three/assets/land.ts
rename to src/render/pixi3d/assets/land.ts
diff --git a/src/render/three/assets/park-furnishings.ts b/src/render/pixi3d/assets/park-furnishings.ts
similarity index 100%
rename from src/render/three/assets/park-furnishings.ts
rename to src/render/pixi3d/assets/park-furnishings.ts
diff --git a/src/render/three/assets/park-ground.ts b/src/render/pixi3d/assets/park-ground.ts
similarity index 100%
rename from src/render/three/assets/park-ground.ts
rename to src/render/pixi3d/assets/park-ground.ts
diff --git a/src/render/three/assets/people.ts b/src/render/pixi3d/assets/people.ts
similarity index 100%
rename from src/render/three/assets/people.ts
rename to src/render/pixi3d/assets/people.ts
diff --git a/src/render/three/assets/primitives.ts b/src/render/pixi3d/assets/primitives.ts
similarity index 100%
rename from src/render/three/assets/primitives.ts
rename to src/render/pixi3d/assets/primitives.ts
diff --git a/src/render/pixi3d/assets/renderer.ts b/src/render/pixi3d/assets/renderer.ts
new file mode 100644
index 0000000..0f0098e
--- /dev/null
+++ b/src/render/pixi3d/assets/renderer.ts
@@ -0,0 +1,101 @@
+/**
+ * The Pixi 3D adapter for one model drawn alone: the map's ground layers, the
+ * page's pictures, the catalogue and the labs. (The town's repeated models are
+ * shared copies instead; see `pool.ts`.)
+ *
+ * The geometry is `ink-mesh.ts`'s; the GLB is `glb.ts`'s, which keeps ordinary
+ * meshes and unlit materials so the ink survives import into another renderer.
+ */
+import { Container3D, Mesh3D, Model3D, type FlatMaterial, type Scene3DSource } from "@pixi/3d"
+import { Assets } from "pixi.js"
+import type { InkAsset } from "./primitives.ts"
+import { inkMesh, type InkMeshOptions, type InkPart } from "./ink-mesh.ts"
+import { exportAsset } from "./glb.ts"
+import { floorScale, vertex3 } from "./space.ts"
+import { lineGeometry, toGeometry } from "../gpu.ts"
+import { bounds } from "../mesh/geometry.ts"
+import { add, type Vec3 } from "../mesh/vec3.ts"
+import { partMaterial, setSurface } from "../materials.ts"
+import { SmokePlume } from "../smoke-effects.ts"
+import { FountainWater } from "../fountain-effects.ts"
+
+export { exportAsset } from "./glb.ts"
+export { floorScale, vertex3 } from "./space.ts"
+
+export interface BuiltAsset {
+ readonly group: Container3D
+ readonly parts: ReadonlyArray<{ readonly part: InkPart; readonly mesh: Mesh3D }>
+ /** Its extent in its own space, effects included: `[min, max]`. */
+ readonly bounds: readonly [Vec3, Vec3]
+ /** Moves its effects (smoke, fountains, a burning structure's flicker) to `time`, in seconds. */
+ updateEffects: (time: number) => void
+ dispose: () => void
+}
+
+export function buildAsset(asset: InkAsset, options: InkMeshOptions & { surfaceEffects?: boolean } = {}): BuiltAsset {
+ const group = new Container3D({ label: asset.id })
+ const effects = asset.effects && options.surfaceEffects !== false ? asset.effects : null
+ const surfaces: Array<FlatMaterial> = []
+ const parts = inkMesh(asset, options).map((part) => {
+ const material = partMaterial(part, effects !== null)
+ if (effects && part.role === "fill") {
+ setSurface(material, effects.state, [effects.half * floorScale, effects.height / Math.cos(Math.PI / 6), 0.31, 1], 0)
+ surfaces.push(material)
+ }
+ const mesh = new Mesh3D({ geometry: part.role === "line" ? lineGeometry(part.mesh.positions) : toGeometry(part.mesh), material, castShadow: false })
+ group.addChild(mesh)
+ return { part, mesh }
+ })
+ const plume = asset.smokeEffect && options.surfaceEffects !== false ? new SmokePlume() : null
+ if (plume) {
+ plume.group.position.set(...vertex3(asset.smokeEffect!.origin))
+ group.addChild(plume.group)
+ plume.update(0)
+ }
+ const fountains = options.surfaceEffects !== false ? (asset.fountains ?? []).map((f) => new FountainWater(f)) : []
+ for (const fountain of fountains) group.addChild(fountain.group)
+ const boxes: Array<readonly [Vec3, Vec3]> = parts.map(({ part }) => bounds(part.mesh))
+ if (plume) {
+ const at = vertex3(asset.smokeEffect!.origin)
+ boxes.push([add(at, [-14, 0, -14]), add(at, [14, 42, 14])])
+ }
+ for (const f of asset.fountains ?? []) {
+ if (options.surfaceEffects === false) break
+ const at = vertex3(f.origin), r = f.radius * floorScale
+ boxes.push([add(at, [-r, f.level / Math.cos(Math.PI / 6) - 1, -r]), add(at, [r, f.nozzle / Math.cos(Math.PI / 6) + 7, r])])
+ }
+ const extent: [Vec3, Vec3] = boxes.length
+ ? [[0, 1, 2].map((k) => Math.min(...boxes.map((b) => b[0][k]!))) as [number, number, number], [0, 1, 2].map((k) => Math.max(...boxes.map((b) => b[1][k]!))) as [number, number, number]]
+ : [[0, 0, 0], [0, 0, 0]]
+ return {
+ group,
+ parts,
+ bounds: extent,
+ updateEffects: (time) => {
+ for (const material of surfaces) material.data.surfaceTime = time
+ plume?.update(time)
+ for (const fountain of fountains) fountain.update(time)
+ },
+ dispose: () => {
+ plume?.dispose()
+ for (const fountain of fountains) fountain.dispose()
+ for (const { mesh } of parts) {
+ const material = mesh.material
+ mesh.destroy({ geometry: true })
+ material.destroy()
+ }
+ group.removeFromParent()
+ group.destroy()
+ }
+ }
+}
+
+/** A model exported and loaded back by Pixi 3D's own glTF loader, as another app would see the GLB. */
+export async function reloadExportedAsset(asset: InkAsset): Promise<Model3D> {
+ const url = URL.createObjectURL(new Blob([await exportAsset(asset)], { type: "model/gltf-binary" }))
+ try {
+ return new Model3D(await Assets.load<Scene3DSource>({ src: url, parser: "glb" }))
+ } finally {
+ URL.revokeObjectURL(url)
+ }
+}
diff --git a/src/render/three/assets/rural.ts b/src/render/pixi3d/assets/rural.ts
similarity index 100%
rename from src/render/three/assets/rural.ts
rename to src/render/pixi3d/assets/rural.ts
diff --git a/src/render/three/assets/scaffolding.ts b/src/render/pixi3d/assets/scaffolding.ts
similarity index 100%
rename from src/render/three/assets/scaffolding.ts
rename to src/render/pixi3d/assets/scaffolding.ts
diff --git a/src/render/three/assets/service-upgrades.ts b/src/render/pixi3d/assets/service-upgrades.ts
similarity index 100%
rename from src/render/three/assets/service-upgrades.ts
rename to src/render/pixi3d/assets/service-upgrades.ts
diff --git a/src/render/three/assets/services.ts b/src/render/pixi3d/assets/services.ts
similarity index 100%
rename from src/render/three/assets/services.ts
rename to src/render/pixi3d/assets/services.ts
diff --git a/src/render/pixi3d/assets/space.ts b/src/render/pixi3d/assets/space.ts
new file mode 100644
index 0000000..534ed3c
--- /dev/null
+++ b/src/render/pixi3d/assets/space.ts
@@ -0,0 +1,11 @@
+/**
+ * The town's model space: grid cells and pixel heights (see `primitives.ts`)
+ * to world units. A 30° elevation and 45° heading reproduce the game's 64×32
+ * projection; the vertical conversion keeps pixel-authored heights exact.
+ */
+import type { Vertex } from "./primitives.ts"
+import type { Vec3 } from "../mesh/vec3.ts"
+
+export const floorScale = 32 * Math.SQRT2
+export const heightScale = 1 / Math.cos(Math.PI / 6)
+export const vertex3 = ([u, v, z]: Vertex): Vec3 => [u * floorScale, z / Math.cos(Math.PI / 6), v * floorScale]
diff --git a/src/render/three/assets/town-props.ts b/src/render/pixi3d/assets/town-props.ts
similarity index 100%
rename from src/render/three/assets/town-props.ts
rename to src/render/pixi3d/assets/town-props.ts
diff --git a/src/render/three/assets/trades.ts b/src/render/pixi3d/assets/trades.ts
similarity index 100%
rename from src/render/three/assets/trades.ts
rename to src/render/pixi3d/assets/trades.ts
diff --git a/src/render/three/assets/upgrade-catalogue.ts b/src/render/pixi3d/assets/upgrade-catalogue.ts
similarity index 100%
rename from src/render/three/assets/upgrade-catalogue.ts
rename to src/render/pixi3d/assets/upgrade-catalogue.ts
diff --git a/src/render/three/assets/upgrade-dress.ts b/src/render/pixi3d/assets/upgrade-dress.ts
similarity index 100%
rename from src/render/three/assets/upgrade-dress.ts
rename to src/render/pixi3d/assets/upgrade-dress.ts
diff --git a/src/render/three/assets/workshops.ts b/src/render/pixi3d/assets/workshops.ts
similarity index 100%
rename from src/render/three/assets/workshops.ts
rename to src/render/pixi3d/assets/workshops.ts
diff --git a/src/render/pixi3d/bits.ts b/src/render/pixi3d/bits.ts
new file mode 100644
index 0000000..a3b9b7d
--- /dev/null
+++ b/src/render/pixi3d/bits.ts
@@ -0,0 +1,181 @@
+/**
+ * The town's shader bits for Pixi 3D's materials (see the `pixijs-3d` skill,
+ * `custom-shaders`). Every material here is a `FlatMaterial`, unlit, drawn in
+ * display space: colours are written as authored, as three.js showed them.
+ *
+ * The renderer runs on WebGL (`scene.ts` asks for it), so each bit carries its
+ * GLSL half only.
+ */
+import type { ShaderBit } from "@pixi/3d"
+
+/** sRGB ⇄ linear light, piecewise, as three.js encoded its output. */
+const colourSpace = `
+vec3 inkToLinear(vec3 c){ return mix(pow(c*0.9478672986+vec3(0.0521327014),vec3(2.4)), c*0.0773993808, vec3(lessThan(c,vec3(0.04045)))); }
+vec3 inkToDisplay(vec3 c){ return mix(pow(c,vec3(0.41666))*1.055-vec3(0.055), c*12.92, vec3(lessThanEqual(c,vec3(0.0031308)))); }
+vec3 inkRGB(vec3 c){ return pow(c,vec3(2.2)); }
+float inkHash(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453); }
+float inkNoise(vec2 p){ vec2 i=floor(p),f=fract(p); f=f*f*(3.0-2.0*f); return mix(mix(inkHash(i),inkHash(i+vec2(1,0)),f.x),mix(inkHash(i+vec2(0,1)),inkHash(i+vec2(1,1)),f.x),f.y); }
+`
+/** Helpers every bit can call; required by the bits that use them. */
+export const inkCommonBit: ShaderBit = { name: "inkline-common", gl: { header: colourSpace } }
+
+/**
+ * Faces sit a little behind their ink, so a stroke drawn on a face's edge
+ * always shows: three.js's polygon offset (factor 6, units 2), written into
+ * the fragment's depth so it scales with the face's slope as that did.
+ */
+export const faceBiasBit: ShaderBit = {
+ name: "inkline-face-bias",
+ gl: { fragment: { end: `{ float faceSlope = max(abs(dFdx(gl_FragCoord.z)), abs(dFdy(gl_FragCoord.z))); gl_FragDepth = gl_FragCoord.z + 6.0 * faceSlope + 2.0 / 16777216.0; }` } }
+}
+
+/**
+ * Shared models in the live town: each copy's colour (already tinted) and
+ * opacity, and its building's wear, hazards and size for `surfaceBit`.
+ */
+export const instanceBit: ShaderBit = {
+ name: "inkline-instance",
+ bindings: { instance: { tint: "vec4<f32>", state: "vec4<f32>", hazards: "vec4<f32>", bounds: "vec4<f32>" }, material: { opacity: "f32" } },
+ gl: { fragment: { material: `{ albedo = instance.tint.rgb; alpha = instance.tint.a * material.opacity; }` } }
+}
+/** One model drawn alone: its colour and opacity from the material. */
+export const plainBit: ShaderBit = {
+ name: "inkline-plain",
+ bindings: { material: { color: "vec4<f32>" } },
+ gl: { fragment: { material: `{ albedo = material.color.rgb; alpha = material.color.a; }` } }
+}
+
+/**
+ * A sharp contour's edge, shown only where it outlines the model: one of its
+ * two faces turns towards the camera and the other away.
+ */
+export const inkSilhouetteBit: ShaderBit = {
+ name: "inkline-silhouette",
+ attributes: { aInkNormalA: "float32x3", aInkNormalB: "float32x3" },
+ interStage: { vInkEdge: "f32" },
+ gl: {
+ vertex: {
+ beforeTransform: `{
+ vec3 toCamera = vec3(uViewMatrix[0][2], uViewMatrix[1][2], uViewMatrix[2][2]);
+ mat3 turn = mat3(modelMatrix);
+ vInkEdge = step(0.0, -dot(turn * aInkNormalA, toCamera) * dot(turn * aInkNormalB, toCamera));
+ }`
+ },
+ fragment: { material: `{ if (vInkEdge < 0.5) discard; }` }
+ }
+}
+
+/**
+ * A stroke a world width across, turned to face the camera, with round ends
+ * (what three.js's `LineSegments2` drew with `worldUnits`), at its line's
+ * depth, with an edge a pixel soft.
+ */
+export const inkLineBit: ShaderBit = {
+ name: "inkline-line",
+ attributes: { aLineStart: "float32x3", aLineEnd: "float32x3", aLineCorner: "float32x2" },
+ interStage: { vLineAlong: "f32", vLineAcross: "f32", vLineLength: "f32" },
+ bindings: { material: { lineWidth: "f32", lineAlpha: "f32" } },
+ gl: {
+ vertex: {
+ afterTransform: `{
+ vec3 lineA = (uViewMatrix * modelMatrix * vec4(aLineStart, 1.0)).xyz;
+ vec3 lineB = (uViewMatrix * modelMatrix * vec4(aLineEnd, 1.0)).xyz;
+ vec2 lineD = lineB.xy - lineA.xy;
+ float lineL = length(lineD);
+ vec2 lineDir = lineL > 1e-6 ? lineD / lineL : vec2(1.0, 0.0);
+ vec2 linePerp = vec2(-lineDir.y, lineDir.x);
+ float lineHalf = material.lineWidth * 0.5;
+ // One world unit beyond the stroke on every side, for its soft edge at any zoom.
+ float lineReach = lineHalf + 1.0;
+ bool lineFar = aLineCorner.x > 0.5;
+ float lineExt = lineFar ? lineReach : -lineReach;
+ vec3 lineP = (lineFar ? lineB : lineA) + vec3(lineDir * lineExt + linePerp * aLineCorner.y * lineReach, 0.0);
+ vLineAlong = (lineFar ? lineL : 0.0) + lineExt;
+ vLineAcross = aLineCorner.y * lineReach;
+ vLineLength = lineL;
+ gl_Position = uProjectionMatrix * vec4(lineP, 1.0);
+ }`
+ },
+ fragment: {
+ material: `{
+ float lineD = vLineAlong < 0.0 ? length(vec2(vLineAlong, vLineAcross)) : vLineAlong > vLineLength ? length(vec2(vLineAlong - vLineLength, vLineAcross)) : abs(vLineAcross);
+ float lineNorm = lineD / max(material.lineWidth, 1e-4);
+ float lineSoft = 0.5 * fwidth(lineNorm);
+ alpha = (1.0 - smoothstep(0.5 - lineSoft, 0.5 + lineSoft, lineNorm)) * material.lineAlpha;
+ if (alpha < 0.004) discard;
+ }`
+ }
+ }
+}
+
+/** The surface shading of a structure: wear, care, snow, fire and the hazards' signs, in model space. */
+const shade = `
+if(surfBounds.w>0.5){
+ vec3 dc=inkToLinear(albedo);
+ vec3 p=vSurfacePosition; vec3 n=normalize(vSurfaceNormal);
+ float H=surfBounds.y, halfWidth=surfBounds.x;
+ float wear=surfState.x,care=surfState.y,snow=surfState.z,burn=surfState.w;
+ float fireRisk=surfHazards.x,health=surfHazards.y,order=surfHazards.z,sick=surfHazards.w;
+ float roof=step(H-0.15,p.y)*smoothstep(0.12,0.45,abs(n.y));
+ float wall=(1.0-roof)*step(0.1,p.y)*step(p.y,H+0.1)*(1.0-surfGlass);
+ vec2 uv=abs(n.x)>abs(n.z)?p.zy:p.xy;
+ float g=inkNoise(uv*0.32+surfBounds.z);
+ float lower=1.0-smoothstep(0.0,H*0.7,p.y);
+ float dirt=wear*wall*(0.16+0.45*lower+0.20*g);
+ dc=mix(dc,inkRGB(vec3(0.60,0.62,0.52)),dirt);
+ float plaster=wear*wall*smoothstep(0.58,0.76,g)*(0.4+0.6*lower);
+ vec2 brick=vec2((uv.x+mod(floor(uv.y/1.8),2.0)*1.8)/3.6,uv.y/1.8);
+ float mortar=max(1.0-smoothstep(0.025,0.08,fract(brick.y)),1.0-smoothstep(0.025,0.06,fract(brick.x)));
+ dc=mix(dc,inkRGB(mix(vec3(0.68,0.53,0.40),vec3(0.84,0.79,0.68),mortar)),plaster*0.9);
+ float crack=abs(uv.x-halfWidth*0.36-sin(uv.y*0.64)*0.48-sin(uv.y*1.5)*0.16);
+ float crackMask=(1.0-smoothstep(0.045,0.10,crack))*smoothstep(H*0.25,H*0.4,p.y)*step(p.y,H*0.92);
+ dc=mix(dc,inkRGB(vec3(0.39,0.43,0.36)),crackMask*wear*wall*0.85);
+ float moss=roof*wear*smoothstep(0.3,0.8,inkNoise(p.xz*0.30))*0.45;
+ dc=mix(dc,inkRGB(vec3(0.47,0.54,0.37)),moss);
+ dc=mix(dc,inkRGB(vec3(0.97,0.96,0.90)),care*wall*0.12);
+ float damp=(health*0.45+sick*0.65)*wall*lower*smoothstep(0.35,0.75,g);
+ dc=mix(dc,inkRGB(vec3(0.48,0.59,0.43)),damp);
+ if(surfGlass>0.5){
+ float fissure=abs(fract((uv.x+uv.y*0.38+sin(uv.y*2.0)*0.18)/3.2)-0.5);
+ float broken=(1.0-smoothstep(0.025,0.065,fissure))*order;
+ dc=mix(dc,inkRGB(vec3(0.25,0.31,0.29)),broken*0.95);
+ dc=mix(dc,inkRGB(vec3(0.58,0.69,0.45)),sick*0.35);
+ float warm=care*0.6+burn*(0.75+0.15*sin(surfTime*9.0+p.x*2.0));
+ dc=mix(dc,inkRGB(vec3(1.0,0.76,0.36)),warm);
+ }
+ float soot=(roof+wall*0.5)*burn*(0.35+inkNoise(p.xz*0.27)*0.50);
+ dc=mix(dc,inkRGB(vec3(0.28,0.31,0.27)),soot);
+ float heat=roof*burn*pow(inkNoise(p.xz*0.45+vec2(0.0,-surfTime*1.3)),5.0);
+ dc=mix(dc,inkRGB(vec3(0.99,0.49,0.19)),heat*0.75);
+ dc=mix(dc,inkRGB(vec3(0.80,0.63,0.43)),roof*fireRisk*0.15*(0.7+0.3*sin(surfTime*3.0)));
+ float frost=roof*snow*smoothstep(-0.05,0.22,inkNoise(p.xz*0.65)+smoothstep(H,H+2.0,p.y)*0.15);
+ dc=mix(dc,inkRGB(vec3(0.97,0.98,0.96)),frost);
+ albedo=inkToDisplay(dc);
+}
+`
+/**
+ * A structure's surface, worn, cared for, snowed on, burning: from each
+ * shared copy's instance values in the town, or from the material's own for
+ * one model drawn alone (the catalogue and the labs).
+ */
+export function surfaceBit(from: "instance" | "material"): ShaderBit {
+ const read = from === "instance"
+ ? `vec4 surfState=instance.state; vec4 surfHazards=instance.hazards; vec4 surfBounds=instance.bounds; float surfTime=uTime;`
+ : `vec4 surfState=material.surfaceState; vec4 surfHazards=material.surfaceHazards; vec4 surfBounds=material.surfaceBounds; float surfTime=material.surfaceTime;`
+ return {
+ name: `inkline-surface-${from}`,
+ requires: [inkCommonBit],
+ interStage: { vSurfacePosition: "vec3<f32>", vSurfaceNormal: "vec3<f32>" },
+ bindings: from === "instance"
+ ? { instance: { tint: "vec4<f32>", state: "vec4<f32>", hazards: "vec4<f32>", bounds: "vec4<f32>" }, material: { surfaceGlass: "f32" } }
+ : { material: { surfaceGlass: "f32", surfaceState: "vec4<f32>", surfaceHazards: "vec4<f32>", surfaceBounds: "vec4<f32>", surfaceTime: "f32" } },
+ gl: {
+ vertex: { beforeTransform: `{ vSurfacePosition = position.xyz; vSurfaceNormal = normal; }` },
+ fragment: { material: `{ ${read} float surfGlass=material.surfaceGlass; ${shade} }` }
+ }
+ }
+}
+export const instanceSurfaceBit = surfaceBit("instance")
+export const materialSurfaceBit = surfaceBit("material")
+/** Glass and lit-window colours: the surface shading treats them as panes, not walls. */
+export const GLASS = [0xdbe6ea, 0xf3dca6, 0xc9d6ee, 0xd5dae4, 0xdbe9e7]
diff --git a/src/render/three/draw/animate.ts b/src/render/pixi3d/draw/animate.ts
similarity index 100%
rename from src/render/three/draw/animate.ts
rename to src/render/pixi3d/draw/animate.ts
diff --git a/src/render/three/draw/ground.ts b/src/render/pixi3d/draw/ground.ts
similarity index 100%
rename from src/render/three/draw/ground.ts
rename to src/render/pixi3d/draw/ground.ts
diff --git a/src/render/three/draw/land.ts b/src/render/pixi3d/draw/land.ts
similarity index 100%
rename from src/render/three/draw/land.ts
rename to src/render/pixi3d/draw/land.ts
diff --git a/src/render/three/draw/overlay.ts b/src/render/pixi3d/draw/overlay.ts
similarity index 100%
rename from src/render/three/draw/overlay.ts
rename to src/render/pixi3d/draw/overlay.ts
diff --git a/src/render/three/draw/preview.ts b/src/render/pixi3d/draw/preview.ts
similarity index 100%
rename from src/render/three/draw/preview.ts
rename to src/render/pixi3d/draw/preview.ts
diff --git a/src/render/three/draw/stroll.ts b/src/render/pixi3d/draw/stroll.ts
similarity index 100%
rename from src/render/three/draw/stroll.ts
rename to src/render/pixi3d/draw/stroll.ts
diff --git a/src/render/pixi3d/fish-effects.ts b/src/render/pixi3d/fish-effects.ts
new file mode 100644
index 0000000..2d02d1b
--- /dev/null
+++ b/src/render/pixi3d/fish-effects.ts
@@ -0,0 +1,84 @@
+import { Container3D, FlatMaterial, Mesh3D, type ShaderBit } from "@pixi/3d"
+import { floorScale, vertex3 } from "./assets/space.ts"
+import type { Point } from "../../game/world/iso.ts"
+import { inkCommonBit } from "./bits.ts"
+import { toGeometry } from "./gpu.ts"
+import { copies, flat, plane } from "./mesh/shapes.ts"
+
+// Now and then (each cell in its own time), one thin ink ring spreads slowly from a point off the middle and
+// fades; most of the time the water is still. Calm enough to sit beside the town, plain enough to read.
+const fishBit: ShaderBit = {
+ name: "inkline-fish",
+ requires: [inkCommonBit],
+ attributes: { aFishPoint: "float32x2", aFishSeed: "float32" },
+ interStage: { vFishPoint: "vec2<f32>", vFishPhase: "f32" },
+ bindings: { material: { time: "f32" } },
+ gl: {
+ vertex: {
+ beforeTransform: `{ vFishPoint = aFishPoint; vFishPhase = aFishSeed; }`
+ },
+ fragment: {
+ material: `{
+ vec2 at = vFishPoint - vec2(fract(vFishPhase * 7.13) - 0.5, fract(vFishPhase * 3.71) - 0.5) * 0.5;
+ float d = length(at);
+ float age = fract(material.time * 0.058 + vFishPhase) / 0.3;
+ if (age > 1.0) discard;
+ float r = 0.08 + age * 0.5;
+ float ring = 1.0 - smoothstep(0.0, 0.03, abs(d - r));
+ float fade = smoothstep(0.0, 0.15, age) * (1.0 - age);
+ float edge = 1.0 - smoothstep(0.85, 1.0, max(abs(vFishPoint.x), abs(vFishPoint.y)));
+ alpha = ring * fade * edge * 0.38;
+ if (alpha < 0.01) discard;
+ albedo = inkToDisplay(inkRGB(vec3(0.32, 0.45, 0.52)));
+ }`
+ }
+ }
+}
+
+/**
+ * Fish in the water: a slow ripple now and then on every cell of water
+ * that would give a catch, none on a cell resting after one. A fishery's
+ * shore reads at a glance as stocked or fished out.
+ */
+export class FishWater {
+ readonly group = new Container3D()
+ private readonly material = new FlatMaterial({ alphaMode: "blend", extraBits: [fishBit] })
+ private mesh: Mesh3D | null = null
+ private key = ""
+ constructor() {
+ this.material.data.time = 0
+ }
+ set(cells: ReadonlyArray<Point>) {
+ const key = cells.map((c) => `${c.x},${c.y}`).join(";")
+ if (key === this.key) return
+ this.key = key
+ this.clear()
+ if (!cells.length) return
+ // Each cell's square of water, placed on the cell, with its own corners (in half cells) for the ring.
+ const tile = flat(plane(floorScale * 0.96, floorScale * 0.96)), n = tile.positions.length / 3
+ const water = copies(tile, cells.length, { aFishSeed: (i) => [(Math.abs((cells[i]!.x * 73856093) ^ (cells[i]!.y * 19349663)) % 1000) / 1000] })
+ const point = new Float32Array(n * cells.length * 2)
+ cells.forEach((c, i) => {
+ const at = vertex3([c.x + 0.5, c.y + 0.5, -0.1])
+ for (let v = 0; v < n; v++) {
+ const o = (i * n + v) * 3
+ point.set([tile.positions[v * 3]! / (floorScale * 0.5), tile.positions[v * 3 + 2]! / (floorScale * 0.5)], (i * n + v) * 2)
+ for (let k = 0; k < 3; k++) water.positions[o + k]! += at[k]!
+ }
+ })
+ const geometry = toGeometry({ ...water, attributes: { ...water.attributes, aFishPoint: { data: point, size: 2 } } })
+ this.mesh = new Mesh3D({ geometry, material: this.material, castShadow: false })
+ this.group.addChild(this.mesh)
+ }
+ update(time: number) {
+ this.material.data.time = time
+ }
+ private clear() {
+ this.mesh?.destroy({ geometry: true })
+ this.mesh = null
+ }
+ dispose() {
+ this.clear()
+ this.key = ""
+ }
+}
diff --git a/src/render/pixi3d/fountain-effects.ts b/src/render/pixi3d/fountain-effects.ts
new file mode 100644
index 0000000..07487d2
--- /dev/null
+++ b/src/render/pixi3d/fountain-effects.ts
@@ -0,0 +1,92 @@
+import { Container3D, FlatMaterial, Mesh3D, type ShaderBit } from "@pixi/3d"
+import type { InkAsset } from "./assets/primitives.ts"
+import { inkCommonBit } from "./bits.ts"
+import { toGeometry } from "./gpu.ts"
+import { copies, disc, sphere } from "./mesh/shapes.ts"
+
+type Fountain = NonNullable<InkAsset["fountains"]>[number]
+const floorScale = 32 * Math.SQRT2, heightScale = 1 / Math.cos(Math.PI / 6)
+
+/** Droplets thrown from four jets, arcing into the basin. */
+const dropsBit: ShaderBit = {
+ name: "inkline-fountain-drops",
+ requires: [inkCommonBit],
+ attributes: { aWaterPhase: "float32", aJetAngle: "float32" },
+ interStage: { vDropAge: "f32", vDropPhase: "f32" },
+ bindings: { material: { time: "f32", radius: "f32", level: "f32", nozzle: "f32" } },
+ gl: {
+ vertex: {
+ beforeTransform: `{
+ float age = fract(material.time * 0.85 + aWaterPhase);
+ float reach = material.radius * 0.84 * age;
+ float h = mix(material.nozzle, material.level, age) + 4.0 * age * (1.0 - age) * 6.9282;
+ vec3 centre = vec3(cos(aJetAngle) * reach, h, sin(aJetAngle) * reach);
+ position = vec4(position.xyz * vec3(0.8, 1.7, 0.8) + centre, 1.0);
+ vDropAge = age; vDropPhase = aWaterPhase;
+ }`
+ },
+ fragment: {
+ material: `{
+ alpha = smoothstep(0.0, 0.07, vDropAge) * (1.0 - smoothstep(0.94, 1.0, vDropAge)) * 0.68;
+ albedo = inkToDisplay(inkRGB(mix(vec3(0.65, 0.78, 0.82), vec3(0.96, 0.99, 0.96), fract(vDropPhase * 13.0))));
+ }`
+ }
+ }
+}
+/** Ripples spreading where the jets land, and a faint shimmer, inside the basin's rim. */
+const poolBit: ShaderBit = {
+ name: "inkline-fountain-pool",
+ requires: [inkCommonBit],
+ interStage: { vPoolPoint: "vec2<f32>" },
+ bindings: { material: { time: "f32", radius: "f32" } },
+ gl: {
+ vertex: { beforeTransform: `{ vPoolPoint = position.xz / material.radius; }` },
+ fragment: {
+ material: `{
+ float waves = 0.0;
+ for (int i = 0; i < 4; i++) {
+ float a = float(i) * 1.5707963 + 0.7853982;
+ float d = length(vPoolPoint - vec2(cos(a), sin(a)) * 0.84);
+ waves += pow(max(0.0, sin(d * 28.0 - material.time * 6.0)), 14.0) * exp(-d * 7.0);
+ }
+ float edge = 1.0 - smoothstep(0.96, 1.0, length(vPoolPoint));
+ float shimmer = sin(vPoolPoint.x * 17.0 + material.time) * sin(vPoolPoint.y * 13.0 - material.time * 0.7) * 0.015;
+ albedo = inkToDisplay(inkRGB(vec3(0.94, 0.98, 0.97)));
+ alpha = edge * (0.025 + waves * 0.28 + shimmer);
+ }`
+ }
+ }
+}
+
+const COUNT = 64
+
+/** Flowing droplets and impact ripples, constrained to the actual stone basin. */
+export class FountainWater {
+ readonly group = new Container3D()
+ private materials: Array<FlatMaterial>
+ private pool: Mesh3D
+ private drops: Mesh3D
+ constructor(fountain: Fountain) {
+ const r = fountain.radius * floorScale, level = fountain.level * heightScale, nozzle = fountain.nozzle * heightScale
+ this.group.position.set(fountain.origin[0] * floorScale, fountain.origin[2] * heightScale, fountain.origin[1] * floorScale)
+ const drops = toGeometry(copies(sphere(0.34, 6, 4), COUNT, { aWaterPhase: (i) => [Math.floor(i / 4) / 16], aJetAngle: (i) => [((i % 4) * Math.PI) / 2 + Math.PI / 4] }), [[-r, level - 1, -r], [r, nozzle + 7, r]])
+ const dropMaterial = new FlatMaterial({ alphaMode: "blend", extraBits: [dropsBit] })
+ Object.assign(dropMaterial.data, { time: 0, radius: r, level, nozzle })
+ const poolMaterial = new FlatMaterial({ alphaMode: "blend", doubleSided: true, extraBits: [poolBit] })
+ Object.assign(poolMaterial.data, { time: 0, radius: r })
+ this.pool = new Mesh3D({ geometry: toGeometry(disc(r, 32)), material: poolMaterial, castShadow: false })
+ this.pool.position.y = level + 0.07
+ this.materials = [dropMaterial, poolMaterial]
+ this.drops = new Mesh3D({ geometry: drops, material: dropMaterial, castShadow: false })
+ this.group.addChild(this.drops, this.pool)
+ }
+ update(time: number) {
+ for (const material of this.materials) material.data.time = time
+ }
+ dispose() {
+ this.group.removeFromParent()
+ this.pool.destroy({ geometry: true })
+ this.drops.destroy({ geometry: true })
+ for (const material of this.materials) material.destroy()
+ }
+}
diff --git a/src/render/pixi3d/gpu.ts b/src/render/pixi3d/gpu.ts
new file mode 100644
index 0000000..7c7c0e4
--- /dev/null
+++ b/src/render/pixi3d/gpu.ts
@@ -0,0 +1,75 @@
+/**
+ * Mesh data (`mesh/geometry.ts`) uploaded as Pixi 3D geometry, and the
+ * colour maths the town's pictures were approved with.
+ *
+ * A `Geometry3D` built from an attribute map takes no built-in attributes
+ * besides the map's, so every geometry here names all of its own: position,
+ * normal, and whatever extra a shader bit reads.
+ */
+import { Box, Geometry3D, Vector3 } from "@pixi/3d"
+import { Buffer, BufferUsage, type Attribute, type VertexFormat } from "pixi.js"
+import { bounds, type MeshData } from "./mesh/geometry.ts"
+import type { Vec3 } from "./mesh/vec3.ts"
+
+const formats: Record<number, VertexFormat> = { 1: "float32", 2: "float32x2", 3: "float32x3", 4: "float32x4" }
+const attribute = (data: Float32Array, size: number): Attribute => ({
+ buffer: new Buffer({ data, usage: BufferUsage.VERTEX | BufferUsage.COPY_DST }),
+ format: formats[size]!,
+ stride: size * 4,
+ offset: 0
+})
+const sequence = (count: number) => (count < 65536 ? Uint16Array.from({ length: count }, (_, i) => i) : Uint32Array.from({ length: count }, (_, i) => i))
+
+/**
+ * `mesh` as GPU geometry: positions, normals and its extra attributes (by their shader names). `extent`
+ * replaces the bounds for a mesh a shader moves (an effect's particles), so it is not culled while in view.
+ */
+export function toGeometry(mesh: MeshData, extent?: readonly [Vec3, Vec3]): Geometry3D {
+ const attributes: Record<string, Attribute> = { aPosition: attribute(mesh.positions, 3), aNormal: attribute(mesh.normals, 3) }
+ for (const [name, a] of Object.entries(mesh.attributes)) attributes[name] = attribute(a.data, a.size)
+ const [min, max] = extent ?? bounds(mesh)
+ return new Geometry3D({
+ attributes,
+ indices: mesh.index ? (mesh.positions.length / 3 < 65536 ? Uint16Array.from(mesh.index) : mesh.index) : sequence(mesh.positions.length / 3),
+ bounds3D: new Box(new Vector3(...min), new Vector3(...max))
+ })
+}
+
+/**
+ * Line segments (`positions`: two points a segment) as ribbons: four corners
+ * a segment, each carrying both ends and which corner it is, for
+ * `inkLineBit` to turn to the camera and widen.
+ */
+export function lineGeometry(positions: Float32Array): Geometry3D {
+ const segments = positions.length / 6
+ const at = new Float32Array(segments * 12), start = new Float32Array(segments * 12), end = new Float32Array(segments * 12), corner = new Float32Array(segments * 8)
+ const index: Array<number> = []
+ for (let s = 0; s < segments; s++) {
+ const a = positions.subarray(s * 6, s * 6 + 3), b = positions.subarray(s * 6 + 3, s * 6 + 6)
+ for (let k = 0; k < 4; k++) {
+ const v = s * 4 + k, far = k >= 2
+ at.set(far ? b : a, v * 3)
+ start.set(a, v * 3)
+ end.set(b, v * 3)
+ corner.set([far ? 1 : 0, k % 2 === 0 ? -1 : 1], v * 2)
+ }
+ const v = s * 4
+ index.push(v, v + 2, v + 1, v + 1, v + 2, v + 3)
+ }
+ const mesh: MeshData = { positions: at, normals: new Float32Array(at.length), index: Uint32Array.from(index), attributes: { aLineStart: { data: start, size: 3 }, aLineEnd: { data: end, size: 3 }, aLineCorner: { data: corner, size: 2 } } }
+ return toGeometry(mesh)
+}
+
+/** sRGB to linear light, as three.js (and glTF) do it: the piecewise curve. */
+export const toLinear = (c: number) => (c < 0.04045 ? c * 0.0773993808 : (c * 0.9478672986 + 0.0521327014) ** 2.4)
+/** Linear light to sRGB, as three.js's output encoding does it. */
+export const toDisplay = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** 0.41666 - 0.055)
+export const channels = (hex: number): [number, number, number] => [((hex >> 16) & 255) / 255, ((hex >> 8) & 255) / 255, (hex & 255) / 255]
+/**
+ * `color` tinted by `tint`, multiplied in linear light, as three.js's instance
+ * colours did it, and written back for the screen.
+ */
+export function tinted(color: number, tint: number, out: Float32Array, offset: number) {
+ const a = channels(color), t = channels(tint)
+ for (let k = 0; k < 3; k++) out[offset + k] = tint === 0xffffff ? a[k]! : toDisplay(toLinear(a[k]!) * toLinear(t[k]!))
+}
diff --git a/src/render/three/input.ts b/src/render/pixi3d/input.ts
similarity index 100%
rename from src/render/three/input.ts
rename to src/render/pixi3d/input.ts
diff --git a/src/render/pixi3d/materials.ts b/src/render/pixi3d/materials.ts
new file mode 100644
index 0000000..2ba15f8
--- /dev/null
+++ b/src/render/pixi3d/materials.ts
@@ -0,0 +1,64 @@
+/**
+ * The materials a model's parts draw with (see `ink-mesh.ts` for the parts):
+ * unlit, in display space, faces pushed back behind their ink.
+ *
+ * - `partMaterial` for one model drawn alone (the map's ground layers, the
+ * catalogue, the labs): its colour on the material.
+ * - `instanceMaterial` for the town's shared models (`pool.ts`): colour,
+ * opacity and surface state per copy, so one material serves every model
+ * with the same kind of part.
+ */
+import { FlatMaterial, type ShaderBit } from "@pixi/3d"
+import { faceBiasBit, GLASS, inkLineBit, inkSilhouetteBit, instanceBit, instanceSurfaceBit, materialSurfaceBit } from "./bits.ts"
+import type { InkPart, PartRole } from "./assets/ink-mesh.ts"
+import type { SurfaceState } from "./surface-state.ts"
+
+const roleBits: Record<PartRole, ReadonlyArray<ShaderBit>> = { fill: [faceBiasBit], hull: [], ink: [], contour: [inkSilhouetteBit], line: [inkLineBit] }
+const doubleSided = (role: PartRole) => role === "fill" || role === "line"
+
+/** A part of one model; `surface` gives its faces the structure shading, with its own state. */
+export function partMaterial(part: InkPart, surface: boolean): FlatMaterial {
+ const material = new FlatMaterial({
+ baseColor: part.color,
+ alpha: part.opacity,
+ // A stroke's soft edge blends, as three.js's alpha-to-coverage lines did.
+ alphaMode: part.opacity < 1 || part.role === "line" ? "blend" : "opaque",
+ doubleSided: doubleSided(part.role),
+ extraBits: [...(surface && part.role === "fill" ? [materialSurfaceBit] : []), ...roleBits[part.role]]
+ })
+ if (part.role === "line") {
+ material.data.lineWidth = part.width
+ material.data.lineAlpha = part.opacity
+ }
+ if (surface && part.role === "fill") {
+ material.data.surfaceGlass = Number(GLASS.includes(part.color))
+ material.data.surfaceTime = 0
+ }
+ return material
+}
+/** Writes a structure's surface state, its size (`bounds`: half width, height, seed, on) and the time into its material. */
+export function setSurface(material: FlatMaterial, state: SurfaceState, bounds: readonly [number, number, number, number], time: number) {
+ material.data.surfaceState = [state.wear, state.care, state.snow, state.burning]
+ material.data.surfaceHazards = [state.fireRisk, state.health, state.order, state.sick]
+ material.data.surfaceBounds = [...bounds]
+ material.data.surfaceTime = time
+}
+
+const shared = new Map<string, FlatMaterial>()
+/** The material every shared copy of such a part draws with: `blend` for a copy fading or see-through. */
+export function instanceMaterial(part: InkPart, blend: boolean): FlatMaterial {
+ const glass = part.role === "fill" && GLASS.includes(part.color)
+ const key = `${part.role}/${part.opacity}/${glass}/${blend}`
+ let material = shared.get(key)
+ if (!material) {
+ material = new FlatMaterial({
+ alphaMode: blend ? "blend" : "opaque",
+ doubleSided: doubleSided(part.role),
+ extraBits: [instanceBit, ...(part.role === "fill" ? [instanceSurfaceBit] : []), ...roleBits[part.role]]
+ })
+ material.data.opacity = part.opacity
+ if (part.role === "fill") material.data.surfaceGlass = Number(glass)
+ shared.set(key, material)
+ }
+ return material
+}
diff --git a/src/render/pixi3d/mesh/geometry.ts b/src/render/pixi3d/mesh/geometry.ts
new file mode 100644
index 0000000..b435f84
--- /dev/null
+++ b/src/render/pixi3d/mesh/geometry.ts
@@ -0,0 +1,349 @@
+/**
+ * Mesh data with no renderer in it: plain typed arrays the Pixi 3D adapter
+ * uploads (`../gpu.ts`), the GLB writer packs (`../assets/glb.ts`), and the
+ * tests read in Node.
+ *
+ * The shapes are ports of the three.js r186 algorithms the town's models were
+ * approved with (MIT, © three.js authors): `CylinderGeometry`,
+ * `CatmullRomCurve3` with `TubeGeometry` and its Frenet frames,
+ * `BufferGeometry.computeVertexNormals`, and `BufferGeometryUtils`'
+ * `mergeGeometries` and `mergeVertices`, so every vertex lands where it did.
+ */
+import { add, apply3, cross, distanceSquared, dot, length, normalize, rotationAxis, rotationBetween, scale, sub, type Mat3, type Vec3 } from "./vec3.ts"
+
+export interface Attribute {
+ readonly data: Float32Array
+ readonly size: number
+}
+export interface MeshData {
+ readonly positions: Float32Array
+ readonly normals: Float32Array
+ /** Triangle indices, or `null` for a triangle list. */
+ readonly index: Uint32Array | null
+ /** Extra per-vertex attributes, by shader name (`aInkNormalA`, …). */
+ readonly attributes: Readonly<Record<string, Attribute>>
+}
+
+const vertexCount = (mesh: MeshData) => mesh.positions.length / 3
+export const triangleCount = (mesh: MeshData) => (mesh.index ? mesh.index.length : vertexCount(mesh)) / 3
+const at = (data: Float32Array, i: number): Vec3 => [data[i * 3]!, data[i * 3 + 1]!, data[i * 3 + 2]!]
+
+/** Per-vertex normals: each triangle's (unnormalised) normal summed into its corners, as three.js does. */
+export function vertexNormals(positions: Float32Array, index: Uint32Array | null): Float32Array {
+ const normals = new Float32Array(positions.length)
+ const count = index ? index.length : positions.length / 3
+ for (let i = 0; i < count; i += 3) {
+ const [a, b, c] = index ? [index[i]!, index[i + 1]!, index[i + 2]!] : [i, i + 1, i + 2]
+ const pA = at(positions, a), pB = at(positions, b), pC = at(positions, c)
+ const n = cross(sub(pC, pB), sub(pA, pB))
+ for (const v of [a, b, c]) for (let k = 0; k < 3; k++) normals[v * 3 + k]! += n[k]!
+ }
+ for (let v = 0; v < normals.length / 3; v++) {
+ const n = normalize(at(normals, v))
+ normals.set(n, v * 3)
+ }
+ return normals
+}
+
+/** A triangle list with flat normals. */
+export function triangles(positions: ReadonlyArray<number> | Float32Array): MeshData {
+ const p = Float32Array.from(positions)
+ return { positions: p, normals: vertexNormals(p, null), index: null, attributes: {} }
+}
+
+/** A convex (or star-shaped about its first point) polygon, fanned from its first point. */
+export function polygon(points: ReadonlyArray<Vec3>): MeshData {
+ const positions: Array<number> = []
+ for (let i = 1; i < points.length - 1; i++) positions.push(...points[0]!, ...points[i]!, ...points[i + 1]!)
+ return triangles(positions)
+}
+
+/** three.js's `CylinderGeometry(radius, radius, height, radialSegments)`: closed, axis +Y, centred on the origin. */
+export function cylinder(radius: number, height: number, radialSegments = 6): MeshData {
+ const positions: Array<number> = [], normals: Array<number> = [], indices: Array<number> = []
+ const half = height / 2
+ let index = 0
+ const rows: Array<Array<number>> = []
+ for (let y = 0; y <= 1; y++) {
+ const row: Array<number> = []
+ for (let x = 0; x <= radialSegments; x++) {
+ const theta = (x / radialSegments) * Math.PI * 2, sin = Math.sin(theta), cos = Math.cos(theta)
+ positions.push(radius * sin, -y * height + half, radius * cos)
+ normals.push(...normalize([sin, 0, cos]))
+ row.push(index++)
+ }
+ rows.push(row)
+ }
+ for (let x = 0; x < radialSegments; x++) {
+ const a = rows[0]![x]!, b = rows[1]![x]!, c = rows[1]![x + 1]!, d = rows[0]![x + 1]!
+ if (radius > 0) indices.push(a, b, d)
+ if (radius > 0) indices.push(b, c, d)
+ }
+ for (const top of [true, false]) {
+ if (radius <= 0) continue
+ const sign = top ? 1 : -1, centre = index
+ for (let x = 1; x <= radialSegments; x++) {
+ positions.push(0, half * sign, 0)
+ normals.push(0, sign, 0)
+ index++
+ }
+ const ring = index
+ for (let x = 0; x <= radialSegments; x++) {
+ const theta = (x / radialSegments) * Math.PI * 2
+ positions.push(radius * Math.sin(theta), half * sign, radius * Math.cos(theta))
+ normals.push(0, sign, 0)
+ index++
+ }
+ for (let x = 0; x < radialSegments; x++) {
+ const c = centre + x, i = ring + x
+ if (top) indices.push(i, i + 1, c)
+ else indices.push(i + 1, i, c)
+ }
+ }
+ return { positions: Float32Array.from(positions), normals: Float32Array.from(normals), index: Uint32Array.from(indices), attributes: {} }
+}
+
+/** `mesh` rotated by `rotation` (normals too) and then moved by `translation`. */
+export function transformed(mesh: MeshData, rotation: Mat3 | null, translation: Vec3 = [0, 0, 0]): MeshData {
+ const positions = new Float32Array(mesh.positions.length), normals = new Float32Array(mesh.normals.length)
+ for (let v = 0; v < positions.length / 3; v++) {
+ const p = at(mesh.positions, v), n = at(mesh.normals, v)
+ positions.set(add(rotation ? apply3(rotation, p) : p, translation), v * 3)
+ normals.set(rotation ? normalize(apply3(rotation, n)) : n, v * 3)
+ }
+ return { ...mesh, positions, normals }
+}
+
+/** A closed six-sided rod from `a` to `b`, `width` across: how ink strokes become geometry. */
+export function rod(a: Vec3, b: Vec3, width: number, radialSegments = 6): MeshData | null {
+ const delta = sub(b, a), l = length(delta)
+ if (l < 0.0001) return null
+ return transformed(cylinder(width / 2, l, radialSegments), rotationBetween([0, 1, 0], normalize(delta)), scale(add(a, b), 0.5))
+}
+/** A centripetal Catmull-Rom curve through `points` (three.js's `CatmullRomCurve3` defaults). */
+class CatmullRom {
+ private lengths: Array<number> | null = null
+ private readonly points: ReadonlyArray<Vec3>
+ private readonly closed: boolean
+ constructor(points: ReadonlyArray<Vec3>, closed: boolean) {
+ this.points = points
+ this.closed = closed
+ }
+ point(t: number): Vec3 {
+ const points = this.points, l = points.length
+ const p = (l - (this.closed ? 0 : 1)) * t
+ let intPoint = Math.floor(p), weight = p - intPoint
+ if (this.closed) intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l
+ else if (weight === 0 && intPoint === l - 1) {
+ intPoint = l - 2
+ weight = 1
+ }
+ const p0 = this.closed || intPoint > 0 ? points[(intPoint - 1) % l]! : add(sub(points[0]!, points[1]!), points[0]!)
+ const p1 = points[intPoint % l]!, p2 = points[(intPoint + 1) % l]!
+ const p3 = this.closed || intPoint + 2 < l ? points[(intPoint + 2) % l]! : add(sub(points[l - 1]!, points[l - 2]!), points[l - 1]!)
+ let dt0 = distanceSquared(p0, p1) ** 0.25, dt1 = distanceSquared(p1, p2) ** 0.25, dt2 = distanceSquared(p2, p3) ** 0.25
+ if (dt1 < 1e-4) dt1 = 1
+ if (dt0 < 1e-4) dt0 = dt1
+ if (dt2 < 1e-4) dt2 = dt1
+ const axis = (k: number) => {
+ const x0 = p0[k]!, x1 = p1[k]!, x2 = p2[k]!, x3 = p3[k]!
+ let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1
+ let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2
+ t1 *= dt1
+ t2 *= dt1
+ const c0 = x1, c1 = t1, c2 = -3 * x1 + 3 * x2 - 2 * t1 - t2, c3 = 2 * x1 - 2 * x2 + t1 + t2
+ return c0 + c1 * weight + c2 * weight * weight + c3 * weight * weight * weight
+ }
+ return [axis(0), axis(1), axis(2)]
+ }
+ private arcLengths() {
+ if (this.lengths) return this.lengths
+ const divisions = 200, cache = [0]
+ let last = this.point(0), sum = 0
+ for (let p = 1; p <= divisions; p++) {
+ const current = this.point(p / divisions)
+ sum += Math.sqrt(distanceSquared(current, last))
+ cache.push(sum)
+ last = current
+ }
+ return (this.lengths = cache)
+ }
+ private uToT(u: number) {
+ const arcLengths = this.arcLengths(), il = arcLengths.length, target = u * arcLengths[il - 1]!
+ let low = 0, high = il - 1, i = 0
+ while (low <= high) {
+ i = Math.floor(low + (high - low) / 2)
+ const comparison = arcLengths[i]! - target
+ if (comparison < 0) low = i + 1
+ else if (comparison > 0) high = i - 1
+ else {
+ high = i
+ break
+ }
+ }
+ i = high
+ if (arcLengths[i] === target) return i / (il - 1)
+ const before = arcLengths[i]!, after = arcLengths[i + 1]!
+ return (i + (target - before) / (after - before)) / (il - 1)
+ }
+ pointAt(u: number) {
+ return this.point(this.uToT(u))
+ }
+ tangentAt(u: number): Vec3 {
+ const t = this.uToT(u), delta = 0.0001
+ return normalize(sub(this.point(Math.min(1, t + delta)), this.point(Math.max(0, t - delta))))
+ }
+}
+
+/** three.js's `TubeGeometry(new CatmullRomCurve3(points, closed), tubularSegments, radius, radialSegments, closed)`. */
+export function tube(points: ReadonlyArray<Vec3>, closed: boolean, tubularSegments: number, radius: number, radialSegments: number): MeshData {
+ const path = new CatmullRom(points, closed)
+ const tangents: Array<Vec3> = [], normals: Array<Vec3> = [], binormals: Array<Vec3> = []
+ for (let i = 0; i <= tubularSegments; i++) tangents.push(path.tangentAt(i / tubularSegments))
+ const t0 = tangents[0]!
+ let min = Number.MAX_VALUE, start: Vec3 = [0, 0, 0]
+ const [tx, ty, tz] = t0.map(Math.abs) as [number, number, number]
+ if (tx <= min) { min = tx; start = [1, 0, 0] }
+ if (ty <= min) { min = ty; start = [0, 1, 0] }
+ if (tz <= min) start = [0, 0, 1]
+ const v0 = normalize(cross(t0, start))
+ normals.push(cross(t0, v0))
+ binormals.push(cross(t0, normals[0]!))
+ let vec: Vec3 = [0, 0, 0]
+ for (let i = 1; i <= tubularSegments; i++) {
+ let n = normals[i - 1]!
+ vec = cross(tangents[i - 1]!, tangents[i]!)
+ if (length(vec) > Number.EPSILON) {
+ vec = normalize(vec)
+ const theta = Math.acos(Math.min(1, Math.max(-1, dot(tangents[i - 1]!, tangents[i]!))))
+ n = apply3(rotationAxis(vec, theta), n)
+ }
+ normals.push(n)
+ binormals.push(cross(tangents[i]!, n))
+ }
+ if (closed) {
+ let theta = Math.acos(Math.min(1, Math.max(-1, dot(normals[0]!, normals[tubularSegments]!)))) / tubularSegments
+ if (dot(tangents[0]!, cross(normals[0]!, normals[tubularSegments]!)) > 0) theta = -theta
+ for (let i = 1; i <= tubularSegments; i++) {
+ normals[i] = apply3(rotationAxis(tangents[i]!, theta * i), normals[i]!)
+ binormals[i] = cross(tangents[i]!, normals[i]!)
+ }
+ }
+ const positions: Array<number> = [], vertexNormalList: Array<number> = [], indices: Array<number> = []
+ const segment = (i: number) => {
+ const P = path.pointAt(i / tubularSegments), N = normals[i]!, B = binormals[i]!
+ for (let j = 0; j <= radialSegments; j++) {
+ const v = (j / radialSegments) * Math.PI * 2, sin = Math.sin(v), cos = -Math.cos(v)
+ const normal = normalize([cos * N[0] + sin * B[0], cos * N[1] + sin * B[1], cos * N[2] + sin * B[2]])
+ vertexNormalList.push(...normal)
+ positions.push(P[0] + radius * normal[0], P[1] + radius * normal[1], P[2] + radius * normal[2])
+ }
+ }
+ for (let i = 0; i < tubularSegments; i++) segment(i)
+ segment(closed ? 0 : tubularSegments)
+ for (let j = 1; j <= tubularSegments; j++)
+ for (let i = 1; i <= radialSegments; i++) {
+ const a = (radialSegments + 1) * (j - 1) + (i - 1), b = (radialSegments + 1) * j + (i - 1), c = (radialSegments + 1) * j + i, d = (radialSegments + 1) * (j - 1) + i
+ indices.push(a, b, d, b, c, d)
+ }
+ return { positions: Float32Array.from(positions), normals: Float32Array.from(vertexNormalList), index: Uint32Array.from(indices), attributes: {} }
+}
+
+/** `mesh` with one more per-vertex attribute, the same value at every vertex. */
+export function withConstant(mesh: MeshData, name: string, value: ReadonlyArray<number>): MeshData {
+ const count = vertexCount(mesh), data = new Float32Array(count * value.length)
+ for (let v = 0; v < count; v++) data.set(value, v * value.length)
+ return { ...mesh, attributes: { ...mesh.attributes, [name]: { data, size: value.length } } }
+}
+
+/** One mesh of several, as three.js's `mergeGeometries` (all indexed, or none). */
+export function merge(meshes: ReadonlyArray<MeshData>): MeshData {
+ if (!meshes.length) throw new Error("Nothing to merge")
+ const indexed = meshes[0]!.index !== null
+ if (meshes.some((m) => (m.index !== null) !== indexed)) throw new Error("Cannot merge indexed and unindexed meshes")
+ const names = Object.keys(meshes[0]!.attributes)
+ for (const m of meshes) if (Object.keys(m.attributes).length !== names.length || names.some((n) => !(n in m.attributes))) throw new Error("Cannot merge meshes with different attributes")
+ const join = (arrays: ReadonlyArray<Float32Array>) => {
+ const out = new Float32Array(arrays.reduce((n, a) => n + a.length, 0))
+ let o = 0
+ for (const a of arrays) {
+ out.set(a, o)
+ o += a.length
+ }
+ return out
+ }
+ let index: Uint32Array | null = null
+ if (indexed) {
+ index = new Uint32Array(meshes.reduce((n, m) => n + m.index!.length, 0))
+ let o = 0, base = 0
+ for (const m of meshes) {
+ for (let i = 0; i < m.index!.length; i++) index[o + i] = m.index![i]! + base
+ o += m.index!.length
+ base += vertexCount(m)
+ }
+ }
+ return {
+ positions: join(meshes.map((m) => m.positions)),
+ normals: join(meshes.map((m) => m.normals)),
+ index,
+ attributes: Object.fromEntries(names.map((n) => [n, { data: join(meshes.map((m) => m.attributes[n]!.data)), size: meshes[0]!.attributes[n]!.size }]))
+ }
+}
+
+/** Every triangle's corners spelled out, as three.js's `toNonIndexed`. */
+export function unindexed(mesh: MeshData): MeshData {
+ if (!mesh.index) return mesh
+ const index = mesh.index
+ const spread = (data: Float32Array, size: number) => {
+ const out = new Float32Array(index.length * size)
+ for (let i = 0; i < index.length; i++) for (let k = 0; k < size; k++) out[i * size + k] = data[index[i]! * size + k]!
+ return out
+ }
+ return {
+ positions: spread(mesh.positions, 3),
+ normals: spread(mesh.normals, 3),
+ index: null,
+ attributes: Object.fromEntries(Object.entries(mesh.attributes).map(([n, a]) => [n, { data: spread(a.data, a.size), size: a.size }]))
+ }
+}
+
+/** Vertices equal to within `tolerance` (positions and normals) shared, as three.js's `mergeVertices`. */
+export function mergeVertices(mesh: MeshData, tolerance = 1e-4): MeshData {
+ tolerance = Math.max(tolerance, Number.EPSILON)
+ const multiplier = 10 ** Math.log10(1 / tolerance), additive = tolerance * 0.5 * multiplier
+ const streams: Array<[Float32Array, number]> = [[mesh.positions, 3], [mesh.normals, 3], ...Object.values(mesh.attributes).map((a): [Float32Array, number] => [a.data, a.size])]
+ const count = mesh.index ? mesh.index.length : vertexCount(mesh)
+ const hashToIndex = new Map<string, number>(), outIndex: Array<number> = [], outStreams = streams.map(([, size]) => [] as Array<number>)
+ for (let i = 0; i < count; i++) {
+ const v = mesh.index ? mesh.index[i]! : i
+ let hash = ""
+ for (const [data, size] of streams) for (let k = 0; k < size; k++) hash += `${Math.trunc(data[v * size + k]! * multiplier + additive)},`
+ let next = hashToIndex.get(hash)
+ if (next === undefined) {
+ next = hashToIndex.size
+ hashToIndex.set(hash, next)
+ streams.forEach(([data, size], s) => {
+ for (let k = 0; k < size; k++) outStreams[s]!.push(data[v * size + k]!)
+ })
+ }
+ outIndex.push(next)
+ }
+ const names = Object.keys(mesh.attributes)
+ return {
+ positions: Float32Array.from(outStreams[0]!),
+ normals: Float32Array.from(outStreams[1]!),
+ index: Uint32Array.from(outIndex),
+ attributes: Object.fromEntries(names.map((n, i) => [n, { data: Float32Array.from(outStreams[i + 2]!), size: mesh.attributes[n]!.size }]))
+ }
+}
+
+/** The smallest box around `mesh`: `[min, max]`. */
+export function bounds(mesh: MeshData): [Vec3, Vec3] {
+ let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity
+ const p = mesh.positions
+ for (let i = 0; i < p.length; i += 3) {
+ x0 = Math.min(x0, p[i]!); y0 = Math.min(y0, p[i + 1]!); z0 = Math.min(z0, p[i + 2]!)
+ x1 = Math.max(x1, p[i]!); y1 = Math.max(y1, p[i + 1]!); z1 = Math.max(z1, p[i + 2]!)
+ }
+ return [[x0, y0, z0], [x1, y1, z1]]
+}
diff --git a/src/render/pixi3d/mesh/ray.ts b/src/render/pixi3d/mesh/ray.ts
new file mode 100644
index 0000000..df0bad0
--- /dev/null
+++ b/src/render/pixi3d/mesh/ray.ts
@@ -0,0 +1,66 @@
+/**
+ * Rays against triangles and boxes, with no renderer in it: the map's
+ * picking (`../pool.ts`) and the model tests share it.
+ */
+import { add, cross, dot, scale, sub, type Vec3 } from "./vec3.ts"
+
+export interface Ray {
+ readonly origin: Vec3
+ readonly direction: Vec3
+}
+export const pointOn = (ray: Ray, t: number): Vec3 => add(ray.origin, scale(ray.direction, t))
+
+/**
+ * How far along `ray` it meets triangle `a b c`, or `null` (as three.js's
+ * `Ray.intersectTriangle`: Möller–Trumbore, either side unless `cull`).
+ */
+export function rayTriangle(ray: Ray, a: Vec3, b: Vec3, c: Vec3, cull = false): number | null {
+ const edge1 = sub(b, a), edge2 = sub(c, a), normal = cross(edge1, edge2)
+ let DdN = dot(ray.direction, normal), sign: number
+ if (DdN > 0) {
+ if (cull) return null
+ sign = 1
+ } else if (DdN < 0) {
+ sign = -1
+ DdN = -DdN
+ } else return null
+ const diff = sub(ray.origin, a)
+ const DdQxE2 = sign * dot(ray.direction, cross(diff, edge2))
+ if (DdQxE2 < 0) return null
+ const DdE1xQ = sign * dot(ray.direction, cross(edge1, diff))
+ if (DdE1xQ < 0 || DdQxE2 + DdE1xQ > DdN) return null
+ const QdN = -sign * dot(diff, normal)
+ if (QdN < 0) return null
+ return QdN / DdN
+}
+
+/** Whether `ray` passes through the box `[min, max]` ahead of its origin (the slab test). */
+export function rayHitsBox(ray: Ray, min: Vec3, max: Vec3): boolean {
+ let near = -Infinity, far = Infinity
+ for (let k = 0; k < 3; k++) {
+ const o = ray.origin[k]!, d = ray.direction[k]!
+ if (Math.abs(d) < 1e-12) {
+ if (o < min[k]! || o > max[k]!) return false
+ continue
+ }
+ const t1 = (min[k]! - o) / d, t2 = (max[k]! - o) / d
+ near = Math.max(near, Math.min(t1, t2))
+ far = Math.min(far, Math.max(t1, t2))
+ }
+ return far >= Math.max(near, 0)
+}
+
+/** A polygon fanned from its first point into triangles, as faces are drawn. */
+export function fan(points: ReadonlyArray<Vec3>): Array<[Vec3, Vec3, Vec3]> {
+ return points.slice(1, -1).map((_, i) => [points[0]!, points[i + 1]!, points[i + 2]!])
+}
+/** Where the segment from `start` to `end` crosses `triangles`: each crossing's distance from `start`. */
+export function segmentHits(start: Vec3, end: Vec3, triangles: Iterable<readonly [Vec3, Vec3, Vec3]>): Array<number> {
+ const delta = sub(end, start), reach = Math.hypot(...delta), ray: Ray = { origin: start, direction: scale(delta, 1 / reach) }
+ const out: Array<number> = []
+ for (const [a, b, c] of triangles) {
+ const t = rayTriangle(ray, a, b, c)
+ if (t !== null && t <= reach) out.push(t)
+ }
+ return out
+}
diff --git a/src/render/pixi3d/mesh/shapes.ts b/src/render/pixi3d/mesh/shapes.ts
new file mode 100644
index 0000000..782c634
--- /dev/null
+++ b/src/render/pixi3d/mesh/shapes.ts
@@ -0,0 +1,89 @@
+/**
+ * The effects' small shapes, as three.js r186 built them (`PlaneGeometry`,
+ * `SphereGeometry`, `CircleGeometry`; MIT, © three.js authors), with texture
+ * coordinates in `aUV`; and `copies`, which bakes many copies of one into a
+ * single mesh, each carrying its own values for the shader (a seed, a place).
+ */
+import type { MeshData } from "./geometry.ts"
+
+const withUV = (positions: Array<number>, normals: Array<number>, uvs: Array<number>, index: Array<number>): MeshData => ({
+ positions: Float32Array.from(positions),
+ normals: Float32Array.from(normals),
+ index: Uint32Array.from(index),
+ attributes: { aUV: { data: Float32Array.from(uvs), size: 2 } }
+})
+
+/** A `width` × `height` rectangle in the XY plane, facing +Z. */
+export function plane(width = 1, height = 1): MeshData {
+ const w = width / 2, h = height / 2
+ return withUV([-w, h, 0, w, h, 0, -w, -h, 0, w, -h, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], [0, 1, 1, 1, 0, 0, 1, 0], [0, 2, 1, 2, 3, 1])
+}
+
+export function sphere(radius: number, widthSegments: number, heightSegments: number): MeshData {
+ const positions: Array<number> = [], normals: Array<number> = [], uvs: Array<number> = [], index: Array<number> = [], grid: Array<Array<number>> = []
+ let next = 0
+ for (let iy = 0; iy <= heightSegments; iy++) {
+ const row: Array<number> = [], v = iy / heightSegments
+ const uOffset = iy === 0 ? 0.5 / widthSegments : iy === heightSegments ? -0.5 / widthSegments : 0
+ for (let ix = 0; ix <= widthSegments; ix++) {
+ const u = ix / widthSegments
+ const x = -radius * Math.cos(u * Math.PI * 2) * Math.sin(v * Math.PI), y = radius * Math.cos(v * Math.PI), z = radius * Math.sin(u * Math.PI * 2) * Math.sin(v * Math.PI)
+ positions.push(x, y, z)
+ const l = Math.hypot(x, y, z) || 1
+ normals.push(x / l, y / l, z / l)
+ uvs.push(u + uOffset, 1 - v)
+ row.push(next++)
+ }
+ grid.push(row)
+ }
+ for (let iy = 0; iy < heightSegments; iy++)
+ for (let ix = 0; ix < widthSegments; ix++) {
+ const a = grid[iy]![ix + 1]!, b = grid[iy]![ix]!, c = grid[iy + 1]![ix]!, d = grid[iy + 1]![ix + 1]!
+ if (iy !== 0) index.push(a, b, d)
+ if (iy !== heightSegments - 1) index.push(b, c, d)
+ }
+ return withUV(positions, normals, uvs, index)
+}
+
+/** A disc of `radius` lying flat (three.js's `CircleGeometry` turned `rotateX(-π/2)`), facing +Y. */
+export function disc(radius: number, segments: number): MeshData {
+ const positions = [0, 0, 0], normals = [0, 1, 0], uvs = [0.5, 0.5], index: Array<number> = []
+ for (let s = 0; s <= segments; s++) {
+ const t = (s / segments) * Math.PI * 2, x = radius * Math.cos(t), y = radius * Math.sin(t)
+ positions.push(x, 0, -y)
+ normals.push(0, 1, 0)
+ uvs.push((x / radius + 1) / 2, (y / radius + 1) / 2)
+ }
+ for (let i = 1; i <= segments; i++) index.push(i, i + 1, 0)
+ return withUV(positions, normals, uvs, index)
+}
+
+/** `rotateX(-π/2)`: a shape in the XY plane laid flat. */
+export function flat(mesh: MeshData): MeshData {
+ const turn = (data: Float32Array) => {
+ const out = new Float32Array(data.length)
+ for (let i = 0; i < data.length; i += 3) out.set([data[i]!, data[i + 2]!, -data[i + 1]!], i)
+ return out
+ }
+ return { ...mesh, positions: turn(mesh.positions), normals: turn(mesh.normals) }
+}
+
+/** `count` copies of `base` in one mesh; each vertex of copy `i` carries `values[name](i)`. */
+export function copies(base: MeshData, count: number, values: Record<string, (i: number) => ReadonlyArray<number>>): MeshData {
+ const n = base.positions.length / 3, baseIndex = base.index ?? Uint32Array.from({ length: n }, (_, i) => i)
+ const positions = new Float32Array(base.positions.length * count), normals = new Float32Array(base.normals.length * count), index = new Uint32Array(baseIndex.length * count)
+ const attributes: Record<string, { data: Float32Array; size: number }> = {}
+ for (const [name, a] of Object.entries(base.attributes)) attributes[name] = { data: new Float32Array(a.data.length * count), size: a.size }
+ for (const [name, value] of Object.entries(values)) attributes[name] = { data: new Float32Array(n * count * value(0).length), size: value(0).length }
+ for (let i = 0; i < count; i++) {
+ positions.set(base.positions, i * base.positions.length)
+ normals.set(base.normals, i * base.normals.length)
+ for (let k = 0; k < baseIndex.length; k++) index[i * baseIndex.length + k] = baseIndex[k]! + i * n
+ for (const [name, a] of Object.entries(base.attributes)) attributes[name]!.data.set(a.data, i * a.data.length)
+ for (const [name, value] of Object.entries(values)) {
+ const v = value(i), target = attributes[name]!
+ for (let j = 0; j < n; j++) target.data.set(v, (i * n + j) * v.length)
+ }
+ }
+ return { positions, normals, index, attributes }
+}
diff --git a/src/render/pixi3d/mesh/vec3.ts b/src/render/pixi3d/mesh/vec3.ts
new file mode 100644
index 0000000..790bff2
--- /dev/null
+++ b/src/render/pixi3d/mesh/vec3.ts
@@ -0,0 +1,51 @@
+/**
+ * Small 3-vector maths on plain tuples, with no renderer in it: the models'
+ * geometry (see `geometry.ts`), the GLB writer and the tests share it, in the
+ * browser and in Node. Each function returns a new tuple.
+ */
+export type Vec3 = readonly [number, number, number]
+
+export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
+export const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
+export const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s]
+export const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+export const cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
+export const length = (a: Vec3) => Math.hypot(a[0], a[1], a[2])
+export const distanceSquared = (a: Vec3, b: Vec3) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2
+export const normalize = (a: Vec3): Vec3 => {
+ const l = length(a)
+ return l > 0 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0]
+}
+export const lerp = (a: Vec3, b: Vec3, t: number): Vec3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]
+export const mean = (points: ReadonlyArray<Vec3>): Vec3 => scale(points.reduce(add, [0, 0, 0]), 1 / Math.max(1, points.length))
+
+/** A row-major 3×3 rotation, applied as `m · v`. */
+export type Mat3 = readonly [number, number, number, number, number, number, number, number, number]
+export const apply3 = (m: Mat3, v: Vec3): Vec3 => [
+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
+]
+/** The rotation of `angle` radians about the unit `axis` (as three.js's `Matrix4.makeRotationAxis`). */
+export const rotationAxis = (axis: Vec3, angle: number): Mat3 => {
+ const c = Math.cos(angle), s = Math.sin(angle), t = 1 - c, [x, y, z] = axis, tx = t * x, ty = t * y
+ return [tx * x + c, tx * y - s * z, tx * z + s * y, tx * y + s * z, ty * y + c, ty * z - s * x, tx * z - s * y, ty * z + s * x, t * z * z + c]
+}
+/** The shortest rotation taking unit `from` onto unit `to` (as three.js's `Quaternion.setFromUnitVectors`). */
+export const rotationBetween = (from: Vec3, to: Vec3): Mat3 => {
+ let r = dot(from, to) + 1
+ let q: [number, number, number, number]
+ if (r < Number.EPSILON) {
+ r = 0
+ q = Math.abs(from[0]) > Math.abs(from[2]) ? [-from[1], from[0], 0, r] : [0, -from[2], from[1], r]
+ } else {
+ const c = cross(from, to)
+ q = [c[0], c[1], c[2], r]
+ }
+ const l = Math.hypot(...q), [x, y, z, w] = q.map((n) => n / l) as [number, number, number, number]
+ return [
+ 1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
+ 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
+ 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)
+ ]
+}
diff --git a/src/render/three/models.ts b/src/render/pixi3d/models.ts
similarity index 100%
rename from src/render/three/models.ts
rename to src/render/pixi3d/models.ts
diff --git a/src/render/pixi3d/pool.ts b/src/render/pixi3d/pool.ts
new file mode 100644
index 0000000..7d5fd08
--- /dev/null
+++ b/src/render/pixi3d/pool.ts
@@ -0,0 +1,231 @@
+import { BatchedMesh3D, Container3D, Matrix4, RenderPassBit, type FlatMaterial, type Geometry3D } from "@pixi/3d"
+import type { InkAsset } from "./assets/primitives.ts"
+import { inkMesh, type InkPart } from "./assets/ink-mesh.ts"
+import { surfaceState, type SurfaceState } from "./surface-state.ts"
+import { tinted, toGeometry } from "./gpu.ts"
+import { instanceMaterial } from "./materials.ts"
+import { bounds, triangleCount, type MeshData } from "./mesh/geometry.ts"
+import { rayHitsBox, rayTriangle, type Ray } from "./mesh/ray.ts"
+import type { Vec3 } from "./mesh/vec3.ts"
+
+interface Part {
+ readonly part: InkPart
+ readonly geometry: Geometry3D
+ readonly opaque: FlatMaterial
+ readonly blend: FlatMaterial
+}
+interface Template {
+ readonly key: string
+ readonly parts: ReadonlyArray<Part>
+ /** The model's extent, in its own space, for picking. */
+ readonly box: readonly [Vec3, Vec3]
+ readonly triangles: number
+ readonly handles: Set<ModelHandle>
+ batch: BatchedMesh3D | null
+ capacity: number
+ /** Each slot's material: 0 none (drawn by no pass), 1 opaque, 2 blended. */
+ modes: Uint8Array
+ /** The copies drawn at the last flush, in slot order. */
+ drawn: Array<ModelHandle>
+ used: number
+}
+
+/** One logical model. Its root owns transforms; shared GPU instances draw it. */
+export class ModelHandle {
+ readonly root = new Container3D()
+ /** A colour over the whole model (sRGB hex), multiplied in linear light. */
+ tint = 0xffffff
+ alpha = 1
+ /** Colours swapped for others on this copy (a walker's coat): source colour to drawn colour. */
+ colors: ReadonlyMap<number, number> | null = null
+ effects: SurfaceState = surfaceState()
+ /** Its structure's half width and height (world units), a noise seed, and 1 to shade it as one; or all 0. */
+ effectBounds: [number, number, number, number] = [0, 0, 0, 0]
+ template: Template | null = null
+ readonly pool: ModelPool
+ readonly entity: number | null
+ readonly pickCell: { x: number; y: number } | null
+ constructor(pool: ModelPool, entity: number | null = null, pickCell: { x: number; y: number } | null = null) {
+ this.pool = pool
+ this.entity = entity
+ this.pickCell = pickCell
+ }
+ use(key: string, create: () => InkAsset) {
+ if (this.template?.key === key) return
+ this.pool.release(this)
+ this.template = this.pool.acquire(key, create)
+ this.template.handles.add(this)
+ }
+ dispose() {
+ this.pool.release(this)
+ this.root.removeFromParent()
+ }
+}
+
+const visible = (node: Container3D) => {
+ for (let p: Container3D | null = node; p; p = p.parent) if (!p.visible) return false
+ return true
+}
+const pass = (mode: number) => (mode === 2 ? RenderPassBit.TRANSPARENT : mode === 1 ? RenderPassBit.OPAQUE : 0)
+
+/**
+ * Geometry and materials are built once per visual state. Repeated homes,
+ * trees and walkers share one batch a model, a slot for each part of each
+ * copy, with entity IDs kept for picking. Unused construction and animation
+ * states have a bounded cache.
+ */
+export class ModelPool {
+ readonly root = new Container3D({ label: "models" })
+ private templates = new Map<string, Template>()
+ private stamp = 0
+ private matrix = new Matrix4()
+ private inverse = new Matrix4()
+ acquire(key: string, create: () => InkAsset): Template {
+ let entry = this.templates.get(key)
+ if (!entry) {
+ const pieces = inkMesh(create(), { batchFaces: true, meshInk: true, contours: true })
+ for (const p of pieces) if (p.role === "line" && p.width > 0) throw new Error("Live model ink must be portable mesh geometry")
+ const solid = pieces.filter((p) => p.role !== "line")
+ const extents = solid.map((p) => bounds(p.mesh))
+ entry = {
+ key,
+ parts: solid.map((part) => ({ part, geometry: toGeometry(part.mesh), opaque: instanceMaterial(part, false), blend: instanceMaterial(part, true) })),
+ box: [
+ [Math.min(...extents.map((e) => e[0][0])), Math.min(...extents.map((e) => e[0][1])), Math.min(...extents.map((e) => e[0][2]))],
+ [Math.max(...extents.map((e) => e[1][0])), Math.max(...extents.map((e) => e[1][1])), Math.max(...extents.map((e) => e[1][2]))]
+ ],
+ triangles: solid.reduce((n, p) => n + triangleCount(p.mesh), 0),
+ handles: new Set(),
+ batch: null,
+ capacity: 0,
+ modes: new Uint8Array(),
+ drawn: [],
+ used: ++this.stamp
+ }
+ this.templates.set(key, entry)
+ }
+ entry.used = ++this.stamp
+ return entry
+ }
+ release(handle: ModelHandle) {
+ if (!handle.template) return
+ handle.template.handles.delete(handle)
+ handle.template.used = ++this.stamp
+ handle.template = null
+ }
+ flush() {
+ for (const entry of this.templates.values()) {
+ const handles = [...entry.handles].filter((h) => h.alpha > 0 && visible(h.root))
+ entry.drawn = handles
+ if (!handles.length || !entry.parts.length) {
+ if (entry.batch) entry.batch.visible = false
+ continue
+ }
+ const P = entry.parts.length
+ if (entry.capacity < handles.length) {
+ entry.batch?.destroy()
+ entry.capacity = 2 ** Math.ceil(Math.log2(Math.max(4, handles.length)))
+ const vec4 = (value: [number, number, number, number]) => ({ value, type: "vec4<f32>" as const })
+ entry.batch = new BatchedMesh3D({
+ size: entry.capacity * P,
+ label: entry.key,
+ // Copies off screen are skipped: most of a large town is, close in.
+ cull: "gpu",
+ instanceData: { tint: vec4([1, 1, 1, 1]), state: vec4([0, 0, 0, 0]), hazards: vec4([0, 0, 0, 0]), bounds: vec4([0, 0, 0, 0]) }
+ })
+ for (let slot = 0; slot < entry.capacity * P; slot++) entry.batch.setGeometryAt(slot, entry.parts[slot % P]!.geometry)
+ entry.modes = new Uint8Array(entry.capacity * P)
+ this.root.addChild(entry.batch)
+ }
+ const batch = entry.batch!
+ batch.visible = true
+ const matrices = batch.matrices, data = batch.instanceData, f = data.fields
+ handles.forEach((handle, i) => {
+ const world = handle.root.getGlobalTransform(this.matrix).elements
+ const alpha = Math.min(1, Math.max(0, handle.alpha)), e = handle.effects, b = handle.effectBounds
+ for (let p = 0; p < P; p++) {
+ const slot = i * P + p, part = entry.parts[p]!.part
+ matrices.data.set(world, matrices.offset + slot * matrices.stride)
+ const o = data.offset + slot * data.stride
+ tinted(handle.colors?.get(part.color) ?? part.color, handle.tint, data.data, o + f.tint!)
+ data.data[o + f.tint! + 3] = alpha
+ data.data.set([e.wear, e.care, e.snow, e.burning], o + f.state!)
+ data.data.set([e.fireRisk, e.health, e.order, e.sick], o + f.hazards!)
+ data.data.set(b, o + f.bounds!)
+ const mode = alpha < 1 || part.opacity < 1 ? 2 : 1
+ if (entry.modes[slot] !== mode) {
+ batch.setMaterialAt(slot, mode === 2 ? entry.parts[p]!.blend : entry.parts[p]!.opaque)
+ batch.setPassesAt(slot, pass(mode))
+ entry.modes[slot] = mode
+ }
+ }
+ })
+ for (let slot = handles.length * P; slot < entry.capacity * P; slot++)
+ if (entry.modes[slot] !== 0) {
+ batch.setPassesAt(slot, 0)
+ entry.modes[slot] = 0
+ }
+ matrices.update()
+ data.update()
+ }
+ const idle = [...this.templates.values()].filter((e) => !e.handles.size).sort((a, b) => a.used - b.used)
+ for (const entry of idle.slice(0, Math.max(0, idle.length - 64))) {
+ this.disposeEntry(entry)
+ this.templates.delete(entry.key)
+ }
+ }
+ /**
+ * The nearest model under `ray` (world space) with an entity, as drawn at the
+ * last flush: each copy's box first, then its triangles, in its own space.
+ */
+ pick(ray: Ray): { handle: ModelHandle; distance: number } | null {
+ let best: { handle: ModelHandle; distance: number } | null = null
+ for (const entry of this.templates.values())
+ for (const handle of entry.drawn) {
+ if (handle.entity === null || handle.alpha <= 0) continue
+ const m = this.inverse.getInverse(handle.root.getGlobalTransform(this.matrix)).elements
+ const point = (v: Vec3, w: number): Vec3 => [
+ m[0]! * v[0] + m[4]! * v[1] + m[8]! * v[2] + m[12]! * w,
+ m[1]! * v[0] + m[5]! * v[1] + m[9]! * v[2] + m[13]! * w,
+ m[2]! * v[0] + m[6]! * v[1] + m[10]! * v[2] + m[14]! * w
+ ]
+ const local: Ray = { origin: point(ray.origin, 1), direction: point(ray.direction, 0) }
+ if (!rayHitsBox(local, entry.box[0], entry.box[1])) continue
+ for (const { part } of entry.parts) {
+ const t = nearest(local, part.mesh, part.role !== "fill")
+ if (t !== null && (!best || t < best.distance)) best = { handle, distance: t }
+ }
+ }
+ return best
+ }
+ stats() {
+ const drawn = [...this.templates.values()].filter((e) => e.drawn.length)
+ return {
+ templates: this.templates.size,
+ models: [...this.templates.values()].reduce((n, e) => n + e.handles.size, 0),
+ batches: drawn.reduce((n, e) => n + e.parts.length, 0),
+ triangles: drawn.reduce((n, e) => n + e.triangles * e.drawn.length, 0)
+ }
+ }
+ private disposeEntry(entry: Template) {
+ entry.batch?.destroy()
+ for (const { geometry } of entry.parts) geometry.destroy()
+ }
+ dispose() {
+ for (const entry of this.templates.values()) this.disposeEntry(entry)
+ this.templates.clear()
+ }
+}
+
+const corner = (data: Float32Array, i: number): Vec3 => [data[i * 3]!, data[i * 3 + 1]!, data[i * 3 + 2]!]
+/** How far along `ray` it first meets `mesh` (both in the mesh's space), front faces only if `cull`. */
+function nearest(ray: Ray, mesh: MeshData, cull: boolean): number | null {
+ let best: number | null = null
+ const count = mesh.index ? mesh.index.length : mesh.positions.length / 3
+ for (let i = 0; i < count; i += 3) {
+ const [a, b, c] = mesh.index ? [mesh.index[i]!, mesh.index[i + 1]!, mesh.index[i + 2]!] : [i, i + 1, i + 2]
+ const t = rayTriangle(ray, corner(mesh.positions, a), corner(mesh.positions, b), corner(mesh.positions, c), cull)
+ if (t !== null && (best === null || t < best)) best = t
+ }
+ return best
+}
diff --git a/src/render/pixi3d/portrait.ts b/src/render/pixi3d/portrait.ts
new file mode 100644
index 0000000..2efcef8
--- /dev/null
+++ b/src/render/pixi3d/portrait.ts
@@ -0,0 +1,45 @@
+/**
+ * A model drawn as a still picture, for the page's panels: from the town's
+ * own camera (its first heading and elevation, see `GameScene`), at the
+ * town's scale (one unit a pixel at zoom 1), cropped to the model, so it
+ * sits beside the 2D pictures the models were built from. It is drawn by the
+ * town's own renderer, offscreen, into a transparent texture.
+ */
+import { View3D } from "@pixi/3d"
+import { RenderTexture, type Renderer } from "pixi.js"
+import { buildAsset } from "./assets/renderer.ts"
+import type { InkAsset } from "./assets/primitives.ts"
+import { add, cross, dot, normalize, scale as times, sub, type Vec3 } from "./mesh/vec3.ts"
+
+/** A PNG data URL of `asset`, `scale` pixels to a unit, with `margin` units around it. */
+export function portrait(renderer: Renderer, asset: InkAsset, scale = 2, margin = 3): string {
+ const model = buildAsset(asset, { batchFaces: true })
+ const heading = Math.PI / 4, elevation = Math.PI / 6, distance = 6000
+ const eye: Vec3 = [Math.sin(heading) * Math.cos(elevation) * distance, Math.sin(elevation) * distance, Math.cos(heading) * Math.cos(elevation) * distance]
+ // The model's extent as the camera sees it: its box's corners on the camera's right and up.
+ const forward = normalize(times(eye, -1)), right = normalize(cross(forward, [0, 1, 0])), up = cross(right, forward)
+ const [min, max] = model.bounds
+ let left = Infinity, rightmost = -Infinity, bottom = Infinity, top = -Infinity
+ for (const x of [min[0], max[0]]) for (const y of [min[1], max[1]]) for (const z of [min[2], max[2]]) {
+ const p = sub([x, y, z], eye), u = dot(p, right), v = dot(p, up)
+ left = Math.min(left, u - margin)
+ rightmost = Math.max(rightmost, u + margin)
+ bottom = Math.min(bottom, v - margin)
+ top = Math.max(top, v + margin)
+ }
+ const width = Math.ceil(rightmost - left), height = Math.ceil(top - bottom)
+ // The camera slides across to the box's middle, still looking the same way.
+ const shift = add(times(right, (left + rightmost) / 2), times(up, (bottom + top) / 2))
+ const view = new View3D({ width, height, background: null })
+ view.camera.useOrthographic(width / 2, 0.1, 14000)
+ view.camera.position.set(...add(eye, shift))
+ view.camera.lookAt({ x: shift[0], y: shift[1], z: shift[2] })
+ view.root.addChild(model.group)
+ const target = RenderTexture.create({ width, height, resolution: scale, antialias: true })
+ renderer.render({ container: view, target, clearColor: [0, 0, 0, 0] })
+ const url = (renderer.extract.canvas(target) as HTMLCanvasElement).toDataURL("image/png")
+ target.destroy(true)
+ model.dispose()
+ view.destroy()
+ return url
+}
diff --git a/src/render/three/rock-blocks.ts b/src/render/pixi3d/rock-blocks.ts
similarity index 100%
rename from src/render/three/rock-blocks.ts
rename to src/render/pixi3d/rock-blocks.ts
diff --git a/src/render/three/scene.ts b/src/render/pixi3d/scene.ts
similarity index 55%
rename from src/render/three/scene.ts
rename to src/render/pixi3d/scene.ts
index 6bcc5bd..1ce0f7a 100644
--- a/src/render/three/scene.ts
+++ b/src/render/pixi3d/scene.ts
@@ -1,4 +1,5 @@
-import * as THREE from "three"
+import { Container3D, Plane, Vector3, View3D, type Camera3D } from "@pixi/3d"
+import { Application, RenderTexture, type Renderer } from "pixi.js"
import { NodeRegistry } from "@typeonce/ritmo-render"
import { buildAsset, floorScale, vertex3, type BuiltAsset } from "./assets/renderer.ts"
import { house } from "./assets/homes.ts"
@@ -12,6 +13,7 @@ import { ModelHandle, ModelPool } from "./pool.ts"
import { groundAsset, landAsset, overlayAsset, previewAsset } from "./models.ts"
import { parkAsset } from "./assets/town-props.ts"
import { FishWater } from "./fish-effects.ts"
+import { channels } from "./gpu.ts"
import type { ParkCell } from "../../game/world/appeal.ts"
/** Where the camera stands: the grid cell it looks at, its zoom, and its angles. */
@@ -24,21 +26,54 @@ export interface CameraView {
}
export interface SceneNode {
- readonly group: THREE.Group
+ readonly group: Container3D
orient(): void
destroy(): void
}
+const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n))
+const DISTANCE = 6000, NEAR = 0.1, FAR = 14000
+const LAND = 0xe2e9e6, FROSTED = 0xe6edf1
+
+/**
+ * Counts what the GPU is asked to draw each frame (Pixi has no `renderer.info`):
+ * draw calls, and triangles, instances included.
+ */
+function drawCounter(renderer: Renderer) {
+ const counts = { calls: 0, triangles: 0 }
+ const gl = "gl" in renderer ? renderer.gl : null
+ if (gl) {
+ const drawElements = gl.drawElements.bind(gl), drawElementsInstanced = gl.drawElementsInstanced.bind(gl), drawArrays = gl.drawArrays.bind(gl)
+ gl.drawElements = (mode, count, type, offset) => {
+ counts.calls++
+ if (mode === gl.TRIANGLES) counts.triangles += count / 3
+ drawElements(mode, count, type, offset)
+ }
+ gl.drawElementsInstanced = (mode, count, type, offset, instances) => {
+ counts.calls++
+ if (mode === gl.TRIANGLES) counts.triangles += (count / 3) * instances
+ drawElementsInstanced(mode, count, type, offset, instances)
+ }
+ gl.drawArrays = (mode, first, count) => {
+ counts.calls++
+ if (mode === gl.TRIANGLES) counts.triangles += count / 3
+ drawArrays(mode, first, count)
+ }
+ }
+ return counts
+}
+
/** The world renderer has no simulation authority. It accepts visual state,
* renders shared models, and translates screen coordinates back to the grid. */
export class GameScene {
- readonly scene = new THREE.Scene()
- readonly objects = new THREE.Group()
+ readonly app: Application
+ /** The 3D view on the Pixi stage: its camera, and the root everything hangs from. */
+ readonly world: View3D
+ readonly objects = new Container3D({ label: "objects" })
readonly pool = new ModelPool()
- readonly camera = new THREE.OrthographicCamera(-500, 500, 400, -400, 0.1, 14000)
- readonly renderer: THREE.WebGLRenderer
+ readonly camera: Camera3D
readonly nodes = new Set<SceneNode>()
- readonly target = new THREE.Vector3((GRID / 2) * floorScale, 0, (GRID / 2) * floorScale)
+ readonly target = new Vector3((GRID / 2) * floorScale, 0, (GRID / 2) * floorScale)
heading = Math.PI / 4
elevation = Math.PI / 6
generation = 0
@@ -58,9 +93,8 @@ export class GameScene {
private overlays: BuiltAsset | null = null
private roadPreview: BuiltAsset | null = null
private ghostHandles: Array<ModelHandle> = []
- private raycaster = new THREE.Raycaster()
private fish = new FishWater()
- private plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)
+ private plane = new Plane(new Vector3(0, 1, 0), 0)
private width = 1
private height = 1
private observer: ResizeObserver
@@ -68,83 +102,94 @@ export class GameScene {
private previous = 0
private frames = 0
private frameMS = 16.67
- constructor(mount: HTMLElement) {
+ private frame = 0
+ private drawn = { calls: 0, triangles: 0 }
+ private counter: { calls: number; triangles: number }
+ /** The renderer draws into `mount`, at its size. */
+ static async create(mount: HTMLElement) {
+ const app = new Application()
+ await app.init({
+ preference: "webgl",
+ antialias: true,
+ backgroundColor: LAND,
+ resolution: Math.min(devicePixelRatio || 1, 2),
+ autoDensity: true,
+ autoStart: false,
+ preserveDrawingBuffer: import.meta.env.DEV,
+ width: Math.max(1, mount.clientWidth),
+ height: Math.max(1, mount.clientHeight)
+ })
+ return new GameScene(mount, app)
+ }
+ private constructor(mount: HTMLElement, app: Application) {
this.mount = mount
- this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: import.meta.env.DEV })
- this.renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2))
- this.renderer.setClearColor(0xe2e9e6)
- this.renderer.outputColorSpace = THREE.SRGBColorSpace
- this.renderer.toneMapping = THREE.NoToneMapping
- this.renderer.domElement.className = "world-canvas"
- this.renderer.domElement.setAttribute("aria-label", "Inkline Town 3D map. Drag to pan, right-drag to rotate, wheel to zoom.")
- this.renderer.domElement.tabIndex = 0
- mount.append(this.renderer.domElement)
- this.scene.add(this.objects, this.pool.root, this.fish.group)
+ this.app = app
+ this.counter = drawCounter(app.renderer)
+ this.world = new View3D({ autoResize: false, width: Math.max(1, mount.clientWidth), height: Math.max(1, mount.clientHeight) })
+ this.camera = this.world.camera
+ this.camera.useOrthographic(this.world.width / 2, NEAR, FAR)
+ app.stage.addChild(this.world)
+ const canvas = app.canvas
+ canvas.className = "world-canvas"
+ canvas.setAttribute("aria-label", "Inkline Town 3D map. Drag to pan, right-drag to rotate, wheel to zoom.")
+ canvas.tabIndex = 0
+ mount.append(canvas)
+ this.world.root.addChild(this.objects, this.pool.root, this.fish.group)
this.observer = new ResizeObserver(() => this.resize())
this.observer.observe(mount)
this.camera.zoom = innerWidth >= 1000 ? 1 : 0.65
this.resize()
this.placeCamera()
}
- get canvas() {
- return this.renderer.domElement
+ get canvas(): HTMLCanvasElement {
+ return this.app.canvas
}
private resize() {
this.width = Math.max(1, this.mount.clientWidth)
this.height = Math.max(1, this.mount.clientHeight)
- this.renderer.setSize(this.width, this.height, false)
- this.camera.left = -this.width / 2
- this.camera.right = this.width / 2
- this.camera.top = this.height / 2
- this.camera.bottom = -this.height / 2
- this.camera.updateProjectionMatrix()
+ this.app.renderer.resize(this.width, this.height)
+ this.world.setSize(this.width, this.height)
+ this.camera.orthographicSize = this.width / 2
}
private placeCamera() {
- const distance = 6000
- this.camera.position
- .copy(this.target)
- .add(
- new THREE.Vector3(
- Math.sin(this.heading) * Math.cos(this.elevation) * distance,
- Math.sin(this.elevation) * distance,
- Math.cos(this.heading) * Math.cos(this.elevation) * distance
- )
- )
+ this.camera.position.set(
+ this.target.x + Math.sin(this.heading) * Math.cos(this.elevation) * DISTANCE,
+ this.target.y + Math.sin(this.elevation) * DISTANCE,
+ this.target.z + Math.cos(this.heading) * Math.cos(this.elevation) * DISTANCE
+ )
this.camera.lookAt(this.target)
- this.camera.updateMatrixWorld(true)
}
- groundAt(sx: number, sy: number): Point {
+ /** A point on the page (client pixels) as a point on the view (its own pixels). */
+ private local(sx: number, sy: number) {
const rect = this.canvas.getBoundingClientRect()
- this.raycaster.setFromCamera(
- new THREE.Vector2(((sx - rect.left) / rect.width) * 2 - 1, 1 - ((sy - rect.top) / rect.height) * 2),
- this.camera
- )
- const point = this.raycaster.ray.intersectPlane(this.plane, new THREE.Vector3()) ?? this.target
+ return { x: ((sx - rect.left) / Math.max(1, rect.width)) * this.width, y: ((sy - rect.top) / Math.max(1, rect.height)) * this.height }
+ }
+ groundAt(sx: number, sy: number): Point {
+ const point = this.world.screenToWorld(this.local(sx, sy), this.plane) ?? this.target
return { x: point.x / floorScale, y: point.z / floorScale }
}
inputAt(sx: number, sy: number, tool: Tool) {
let at = this.groundAt(sx, sy)
let hit: number | null = null
- const intersects = this.raycaster.intersectObjects(this.pool.pickables(), false)
- for (const intersection of intersects) {
- const handle = (intersection.object.userData.handles as Array<ModelHandle>)[intersection.instanceId ?? 0]
- if (!handle || handle.entity === null || handle.alpha <= 0) continue
- hit = handle.entity
- if ((tool === "select" || tool === "bulldoze") && handle.pickCell) at = { ...handle.pickCell }
- break
+ const ray = this.world.screenToRay(this.local(sx, sy))
+ const picked = this.pool.pick({ origin: [ray.origin.x, ray.origin.y, ray.origin.z], direction: [ray.direction.x, ray.direction.y, ray.direction.z] })
+ if (picked) {
+ hit = picked.handle.entity
+ if ((tool === "select" || tool === "bulldoze") && picked.handle.pickCell) at = { ...picked.handle.pickCell }
}
return { at, hit }
}
project(x: number, y: number, height = 0): Point {
- const p = vertex3([x, y, height]).project(this.camera),
- rect = this.canvas.getBoundingClientRect()
- return { x: rect.left + ((p.x + 1) * rect.width) / 2, y: rect.top + ((1 - p.y) * rect.height) / 2 }
+ const [px, py, pz] = vertex3([x, y, height]), p = this.world.worldToScreen({ x: px, y: py, z: pz }) ?? { x: 0, y: 0 }
+ const rect = this.canvas.getBoundingClientRect()
+ return { x: rect.left + (p.x / this.width) * rect.width, y: rect.top + (p.y / this.height) * rect.height }
}
pan(dx: number, dy: number) {
const cx = this.width / 2,
cy = this.height / 2,
- a = this.groundAt(cx, cy),
- b = this.groundAt(cx + dx, cy + dy)
+ rect = this.canvas.getBoundingClientRect(),
+ a = this.groundAt(rect.left + cx, rect.top + cy),
+ b = this.groundAt(rect.left + cx + dx, rect.top + cy + dy)
this.target.x += (a.x - b.x) * floorScale
this.target.z += (a.y - b.y) * floorScale
this.placeCamera()
@@ -156,27 +201,26 @@ export class GameScene {
}
rotate(dx: number, dy = 0) {
this.heading += dx
- this.elevation = THREE.MathUtils.clamp(this.elevation + dy, Math.PI / 12, (Math.PI / 180) * 65)
+ this.elevation = clamp(this.elevation + dy, Math.PI / 12, (Math.PI / 180) * 65)
this.placeCamera()
}
zoomAt(sx: number, sy: number, factor: number) {
const before = this.groundAt(sx, sy)
- this.camera.zoom = THREE.MathUtils.clamp(this.camera.zoom * factor, 0.35, 4)
- this.camera.updateProjectionMatrix()
+ this.camera.zoom = clamp(this.camera.zoom * factor, 0.35, 4)
const after = this.groundAt(sx, sy)
this.target.x += (before.x - after.x) * floorScale
this.target.z += (before.y - after.y) * floorScale
this.placeCamera()
}
zoomBy(factor: number) {
- this.zoomAt(this.width / 2, this.height / 2, factor)
+ const rect = this.canvas.getBoundingClientRect()
+ this.zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, factor)
}
resetCamera() {
this.heading = Math.PI / 4
this.elevation = Math.PI / 6
this.target.set((GRID / 2) * floorScale, 0, (GRID / 2) * floorScale)
this.camera.zoom = innerWidth >= 1000 ? 1 : 0.65
- this.camera.updateProjectionMatrix()
this.placeCamera()
}
focus(x: number, y: number) {
@@ -189,7 +233,7 @@ export class GameScene {
attach: (node, parent) => {
const into = parent?.group ?? this.objects
this.nodes.add(node)
- into.add(node.group)
+ into.addChild(node.group)
},
detach: (node) => {
this.nodes.delete(node)
@@ -199,19 +243,17 @@ export class GameScene {
}
add(node: SceneNode) {
this.nodes.add(node)
- this.objects.add(node.group)
+ this.objects.addChild(node.group)
}
remove(node: SceneNode) {
this.nodes.delete(node)
}
private replace(old: BuiltAsset | null, asset: InkAsset): BuiltAsset | null {
- if (old) {
- old.group.removeFromParent()
- old.dispose()
- }
+ old?.dispose()
if (!asset.faces.length && !asset.strokes.length) return null
- const model = buildAsset(asset, { batchFaces: true })
- this.scene.add(model.group)
+ // The ground layers' ink is ribbons, and their faces' contours are left to the faces.
+ const model = buildAsset(asset, { batchFaces: true, contours: false })
+ this.world.root.addChild(model.group)
return model
}
setLand(mask: string, frost = false) {
@@ -219,7 +261,7 @@ export class GameScene {
if (id === this.landKey) return
this.landKey = id
this.frost = frost
- this.renderer.setClearColor(frost ? 0xe6edf1 : 0xe2e9e6)
+ this.app.renderer.background.color = frost ? FROSTED : LAND
this.land = this.replace(this.land, landAsset(mask, frost))
}
setGround(roads: ReadonlySet<number>, water: ReadonlySet<number>, paved: ReadonlySet<number> = new Set()) {
@@ -261,8 +303,8 @@ export class GameScene {
size = ghost.what === "home" ? 1 : kinds[ghost.what].size
handle.alpha = 0.45
handle.use("ghost/" + ghost.what, () => (ghost.what === "home" ? house(1, 0.03) : makeBuilding(ghost.what, { motion: false })))
- handle.root.position.copy(vertex3([ghost.cell.x + size / 2, ghost.cell.y + size / 2, 0.2]))
- this.objects.add(handle.root)
+ handle.root.position.set(...vertex3([ghost.cell.x + size / 2, ghost.cell.y + size / 2, 0.2]))
+ this.objects.addChild(handle.root)
this.ghostHandles.push(handle)
}
}
@@ -277,48 +319,60 @@ export class GameScene {
this.nodes.clear()
for (const handle of this.ghostHandles) handle.dispose()
this.ghostHandles = []
- this.overlays = this.replace(this.overlays, { id: "empty", title: "", note: "", faces: [], strokes: [] })
+ const empty: InkAsset = { id: "empty", title: "", note: "", faces: [], strokes: [] }
+ this.overlays = this.replace(this.overlays, empty)
this.overlayKey = ""
- this.overlay = this.replace(this.overlay, { id: "empty", title: "", note: "", faces: [], strokes: [] })
- this.roadPreview = this.replace(this.roadPreview, { id: "empty", title: "", note: "", faces: [], strokes: [] })
- this.parkPreview = this.replace(this.parkPreview, { id: "empty", title: "", note: "", faces: [], strokes: [] })
+ this.overlay = this.replace(this.overlay, empty)
+ this.roadPreview = this.replace(this.roadPreview, empty)
+ this.parkPreview = this.replace(this.parkPreview, empty)
+ }
+ /** Brings every view and effect up to `now` (milliseconds) and draws the frame. */
+ private render(now: number) {
+ for (const node of this.nodes) node.orient()
+ this.parks?.updateEffects(now / 1000)
+ this.fish.update(now / 1000)
+ this.parkPreview?.updateEffects(now / 1000)
+ this.pool.flush()
+ this.counter.calls = 0
+ this.counter.triangles = 0
+ this.app.render()
+ this.drawn = { ...this.counter }
}
subscribe(onTick: (tick: { deltaMS: number }) => void) {
this.previous = 0
- this.renderer.setAnimationLoop((now) => {
+ const loop = (now: number) => {
const delta = this.previous ? Math.max(0, now - this.previous) : 1000 / 60
this.previous = now
this.frameMS = this.frameMS * 0.95 + Math.min(delta, 250) * 0.05
onTick({ deltaMS: delta })
- for (const node of this.nodes) node.orient()
- this.camera.getWorldDirection(this.pool.viewDirection).negate()
- this.pool.time.value = now / 1000
- this.parks?.updateEffects(now/1000)
- this.fish.update(now / 1000)
- this.parkPreview?.updateEffects(now/1000)
- this.pool.flush()
- this.renderer.render(this.scene, this.camera)
+ this.render(now)
this.frames++
- })
- return { stop: () => this.renderer.setAnimationLoop(null) }
+ this.frame = requestAnimationFrame(loop)
+ }
+ this.frame = requestAnimationFrame(loop)
+ return { stop: () => cancelAnimationFrame(this.frame) }
}
stats() {
+ const pool = this.pool.stats()
return {
- renderer: "three",
+ renderer: "pixi3d",
frames: this.frames,
frameMS: this.frameMS,
- drawCalls: this.renderer.info.render.calls,
- triangles: this.renderer.info.render.triangles,
+ drawCalls: this.drawn.calls,
+ triangles: this.drawn.triangles,
nodes: this.nodes.size,
- ...this.pool.stats(),
+ templates: pool.templates,
+ models: pool.models,
+ batches: pool.batches,
zoom: this.camera.zoom,
- heading: THREE.MathUtils.radToDeg(this.heading),
- elevation: THREE.MathUtils.radToDeg(this.elevation),
+ heading: (this.heading * 180) / Math.PI,
+ elevation: (this.elevation * 180) / Math.PI,
target: [this.target.x / floorScale, this.target.z / floorScale],
generation: this.generation
}
}
capture() {
+ this.render(performance.now())
return this.canvas.toDataURL("image/webp", 0.94)
}
/** Where the camera looks from, to share along with the town. */
@@ -328,49 +382,43 @@ export class GameScene {
/** Looks from a shared view, kept within the limits the controls keep to. */
setView(view: CameraView) {
const finite = (n: number, fallback: number) => (Number.isFinite(n) ? n : fallback)
- this.target.set(THREE.MathUtils.clamp(finite(view.x, GRID / 2), 0, GRID) * floorScale, 0, THREE.MathUtils.clamp(finite(view.y, GRID / 2), 0, GRID) * floorScale)
- this.camera.zoom = THREE.MathUtils.clamp(finite(view.zoom, 1), 0.35, 4)
+ this.target.set(clamp(finite(view.x, GRID / 2), 0, GRID) * floorScale, 0, clamp(finite(view.y, GRID / 2), 0, GRID) * floorScale)
+ this.camera.zoom = clamp(finite(view.zoom, 1), 0.35, 4)
this.heading = finite(view.heading, Math.PI / 4)
- this.elevation = THREE.MathUtils.clamp(finite(view.elevation, Math.PI / 6), Math.PI / 12, (Math.PI / 180) * 65)
- this.camera.updateProjectionMatrix()
+ this.elevation = clamp(finite(view.elevation, Math.PI / 6), Math.PI / 12, (Math.PI / 180) * 65)
this.placeCamera()
}
/**
* The town as the camera sees it, drawn afresh at `width` × `height`
* (times `scale`) into a canvas of its own. The view is widened or
* narrowed so all of what the mayor sees on screen fits the picture.
- * The drawing buffer is read right after the render, so this works
- * without keeping the buffer between frames.
*/
picture(width: number, height: number, scale = 2): HTMLCanvasElement {
- const ratio = this.renderer.getPixelRatio(),
- zoom = this.camera.zoom,
+ const zoom = this.camera.zoom,
fit = Math.min(width / this.width, height / this.height)
- this.renderer.setPixelRatio(scale)
- this.renderer.setSize(width, height, false)
- this.camera.left = -width / 2
- this.camera.right = width / 2
- this.camera.top = height / 2
- this.camera.bottom = -height / 2
+ this.pool.flush()
+ this.world.setSize(width, height)
+ this.camera.orthographicSize = width / 2
this.camera.zoom = Math.max(0.3, zoom * fit)
- this.camera.updateProjectionMatrix()
- this.renderer.render(this.scene, this.camera)
+ const target = RenderTexture.create({ width, height, resolution: scale, antialias: true })
+ const [r, g, b] = channels(this.frost ? FROSTED : LAND)
+ this.app.renderer.render({ container: this.world, target, clearColor: [r, g, b, 1] })
const out = document.createElement("canvas")
out.width = width * scale
out.height = height * scale
- out.getContext("2d")!.drawImage(this.canvas, 0, 0, out.width, out.height)
+ out.getContext("2d")!.drawImage(this.app.renderer.extract.canvas(target) as HTMLCanvasElement, 0, 0, out.width, out.height)
+ target.destroy(true)
this.camera.zoom = zoom
- this.renderer.setPixelRatio(ratio)
this.resize()
- this.renderer.render(this.scene, this.camera)
return out
}
dispose() {
- this.renderer.setAnimationLoop(null)
+ cancelAnimationFrame(this.frame)
this.observer.disconnect()
this.resetPresentation()
for (const model of [this.land, this.ground, this.parks]) model?.dispose()
+ this.fish.dispose()
this.pool.dispose()
- this.renderer.dispose()
+ this.app.destroy(true, { children: true })
}
}
diff --git a/src/render/three/schedule.ts b/src/render/pixi3d/schedule.ts
similarity index 100%
rename from src/render/three/schedule.ts
rename to src/render/pixi3d/schedule.ts
diff --git a/src/render/three/services.ts b/src/render/pixi3d/services.ts
similarity index 100%
rename from src/render/three/services.ts
rename to src/render/pixi3d/services.ts
diff --git a/src/render/pixi3d/smoke-effects.ts b/src/render/pixi3d/smoke-effects.ts
new file mode 100644
index 0000000..986caaf
--- /dev/null
+++ b/src/render/pixi3d/smoke-effects.ts
@@ -0,0 +1,63 @@
+import { Container3D, FlatMaterial, Mesh3D, type ShaderBit } from "@pixi/3d"
+import { inkCommonBit } from "./bits.ts"
+import { toGeometry } from "./gpu.ts"
+import { copies, plane } from "./mesh/shapes.ts"
+
+/** A chimney's plume: puffs that rise, drift and fade, each turned to the camera in the shader. */
+const smokeBit: ShaderBit = {
+ name: "inkline-smoke",
+ requires: [inkCommonBit],
+ attributes: { aPuffSeed: "float32" },
+ interStage: { vSmokeAge: "f32", vSmokeSeed: "f32" },
+ bindings: { material: { time: "f32", power: "f32" } },
+ gl: {
+ vertex: {
+ afterTransform: `{
+ float age = fract(material.time / 3.8 + aPuffSeed);
+ vec4 c = uViewMatrix * modelMatrix * vec4(0.0, 0.0, 0.0, 1.0);
+ c.y += age * 29.0;
+ c.x += age * age * 6.0 + sin(age * 5.0 + aPuffSeed * 29.0) * age * 2.0;
+ float size = 4.0 + age * 11.0;
+ c.xy += position.xy * vec2(size, size * 1.18);
+ gl_Position = uProjectionMatrix * c;
+ vSmokeAge = age; vSmokeSeed = aPuffSeed;
+ }`
+ },
+ fragment: {
+ material: `{
+ vec2 p = (vUV - 0.5) * 2.0;
+ float cloud = inkNoise(vUV * 3.0 + vSmokeSeed * 13.0 + vec2(0.0, material.time * 0.13)) * 0.65 + inkNoise(vUV * 7.0 + vSmokeSeed * 9.0) * 0.35;
+ float edge = 1.0 - smoothstep(0.35, 1.0, length(p) + cloud * 0.24);
+ alpha = edge * sin(vSmokeAge * 3.14159) * 0.19 * material.power;
+ if (alpha < 0.008) discard;
+ albedo = inkToDisplay(inkRGB(mix(vec3(0.40, 0.45, 0.39), vec3(0.68, 0.70, 0.63), vSmokeAge)));
+ }`
+ }
+ }
+}
+
+const COUNT = 10
+let shape: ReturnType<typeof toGeometry> | null = null
+
+/** A bounded cloud emitter, anchored at the actual flue opening. */
+export class SmokePlume {
+ readonly group = new Container3D()
+ private material: FlatMaterial
+ constructor() {
+ shape ??= toGeometry(copies(plane(1, 1), COUNT, { aPuffSeed: (i) => [i / COUNT] }), [[-14, 0, -14], [14, 42, 14]])
+ this.material = new FlatMaterial({ alphaMode: "blend", doubleSided: true, extraBits: [smokeBit] })
+ this.material.data.time = 0
+ this.material.data.power = 1
+ this.group.addChild(new Mesh3D({ geometry: shape, material: this.material, castShadow: false }))
+ }
+ update(time: number, strength = 1) {
+ this.group.visible = strength > 0
+ this.material.data.time = time
+ this.material.data.power = strength
+ }
+ dispose() {
+ this.group.removeFromParent()
+ this.group.destroy({ children: true })
+ this.material.destroy()
+ }
+}
diff --git a/src/render/pixi3d/structure-effects.ts b/src/render/pixi3d/structure-effects.ts
new file mode 100644
index 0000000..d90b49e
--- /dev/null
+++ b/src/render/pixi3d/structure-effects.ts
@@ -0,0 +1,123 @@
+import { Container3D, FlatMaterial, Mesh3D, type ShaderBit } from "@pixi/3d"
+import { type InkAsset } from "./assets/primitives.ts"
+import { surfaceState, type SurfaceState } from "./surface-state.ts"
+import { inkCommonBit } from "./bits.ts"
+import { toGeometry } from "./gpu.ts"
+import { copies, plane } from "./mesh/shapes.ts"
+import { add, cross, length, normalize, scale, sub, type Vec3 } from "./mesh/vec3.ts"
+
+/** Flames (mode 0), smoke (1) and sparks (2), each a copy turned to the camera, from a point on the roof. */
+const fireBit: ShaderBit = {
+ name: "inkline-structure-fire",
+ requires: [inkCommonBit],
+ attributes: { aEffectAt: "float32x3", aEffectScale: "float32x2", aEffectSeed: "float32" },
+ interStage: { vFireAge: "f32", vFireSeed: "f32" },
+ bindings: { material: { time: "f32", power: "f32", mode: "f32" } },
+ gl: {
+ vertex: {
+ afterTransform: `{
+ float mode = material.mode, seed = aEffectSeed;
+ float life = mode < 0.5 ? 1.8 : mode < 1.5 ? 4.2 : 2.8;
+ float age = fract(material.time / life + seed);
+ vec4 c = uViewMatrix * modelMatrix * vec4(aEffectAt, 1.0);
+ c.y += mode < 0.5 ? 0.0 : mode < 1.5 ? age * 32.0 : age * 35.0;
+ c.x += sin(seed * 43.0 + age * 4.0) * (mode < 0.5 ? 0.7 : 3.0) * age;
+ float size = mode < 0.5 ? (0.8 + 0.2 * sin(material.time * 8.0 + seed * 31.0)) * material.power : mode < 1.5 ? (0.55 + age * 1.15) : 1.0;
+ if (mode < 0.5) c.y += aEffectScale.y * size * 0.5;
+ c.xy += (position.xy * aEffectScale) * size;
+ gl_Position = uProjectionMatrix * c;
+ vFireAge = age; vFireSeed = seed;
+ }`
+ },
+ fragment: {
+ material: `{
+ vec2 p = vUV; float a; vec3 color; float mode = material.mode, t = material.time;
+ if (mode < 0.5) {
+ float y = p.y; float curl = sin(y * 8.0 - t * 4.5 + vFireSeed * 39.0) * 0.11 * y;
+ float body = abs(p.x - 0.5 - curl) / (0.46 * (1.0 - y * 0.86));
+ float edge = 1.0 - smoothstep(0.45, 1.0, body + inkNoise(vec2(p.x * 6.0, y * 5.0 - t * 3.5) + vFireSeed * 10.0) * 0.27);
+ a = edge * smoothstep(0.0, 0.10, y) * (1.0 - smoothstep(0.82, 1.0, y)) * 0.82;
+ float core = (1.0 - body) * pow(1.0 - y, 0.7);
+ color = mix(vec3(0.87, 0.33, 0.12), vec3(1.0, 0.83, 0.38), smoothstep(0.0, 0.8, core));
+ } else if (mode < 1.5) {
+ float d = length((p - 0.5) * vec2(2.0, 1.8));
+ float cloud = inkNoise(p * 3.0 + vec2(vFireSeed * 9.0, t * 0.12)) * 0.65 + inkNoise(p * 7.0 + vFireSeed * 11.0) * 0.35;
+ a = (1.0 - smoothstep(0.3, 1.0, d + cloud * 0.24)) * sin(vFireAge * 3.14159) * 0.24 * material.power;
+ color = mix(vec3(0.35, 0.39, 0.33), vec3(0.64, 0.66, 0.58), vFireAge);
+ } else {
+ a = (1.0 - smoothstep(0.05, 0.5, length(p - 0.5))) * sin(vFireAge * 3.14159) * material.power;
+ color = vec3(1.0, 0.67, 0.24);
+ }
+ if (a < 0.015) discard;
+ alpha = a;
+ albedo = inkToDisplay(inkRGB(color));
+ }`
+ }
+ }
+}
+
+/** Particle emitters sampled from the actual roof triangles, never a hovering sign or replacement mesh. */
+export class StructureEffects {
+ readonly group = new Container3D()
+ /** What the effects were made for (a home's tier, an upgrade), to tell when they must be made again. */
+ readonly made: { tier?: number; upgraded?: boolean } = {}
+ private state = surfaceState()
+ private layers: Array<{ mesh: Mesh3D; material: FlatMaterial }> = []
+ private asset: InkAsset
+ private H: number
+ constructor(asset: InkAsset, height: number) {
+ this.asset = asset
+ this.H = height
+ this.group.visible = false
+ }
+ set(next: SurfaceState) {
+ this.state = next
+ this.group.visible = next.burning > 0 || next.fireRisk > 0
+ }
+ private build() {
+ const s = 32 * Math.SQRT2, convert = (p: readonly number[]): Vec3 => [p[0]! * s, p[2]! / Math.cos(Math.PI / 6), p[1]! * s]
+ const roofs = this.asset.faces.filter((f) => f.points.every((p) => p[2] >= this.H - 0.01) && f.points.length >= 3).flatMap((f) => {
+ const a = convert(f.points[0]!), triangles: Array<[Vec3, Vec3, Vec3]> = []
+ for (let i = 1; i < f.points.length - 1; i++) {
+ const b = convert(f.points[i]!), c = convert(f.points[i + 1]!), n = cross(sub(c, b), sub(a, b))
+ if (Math.abs(normalize(n)[1]) > 0.15 && length(n) / 2 > 2) triangles.push([a, b, c])
+ }
+ return triangles
+ })
+ for (const [mode, count] of [[0, 16], [1, 18], [2, 14]] as const) {
+ const at = (i: number): Vec3 => {
+ const t = roofs[i % roofs.length], u = 0.15 + ((i * 0.37) % 0.65), v = 0.12 + ((i * 0.23) % 0.6), sum = u + v, a = u / Math.max(1, sum), b = v / Math.max(1, sum)
+ const p: Vec3 = t ? add(add(scale(t[0], 1 - a - b), scale(t[1], a)), scale(t[2], b)) : [0, this.H / Math.cos(Math.PI / 6), 0]
+ return add(p, [0, mode === 0 ? 0 : mode === 1 ? 3 : 0.5, 0])
+ }
+ const size = (i: number) => (mode === 0 ? [5 + (i % 3), 13 + (i % 4) * 2.5] : mode === 1 ? [8 + (i % 4), 8 + (i % 4)] : [0.7, 0.9])
+ const points = Array.from({ length: count }, (_, i) => at(i)), low = (k: number) => Math.min(...points.map((p) => p[k]!)) - 20, high = (k: number) => Math.max(...points.map((p) => p[k]!)) + 20
+ const extent: [Vec3, Vec3] = [[low(0), low(1), low(2)], [high(0), high(1) + 45, high(2)]]
+ const geometry = toGeometry(copies(plane(1, 1), count, { aEffectAt: at, aEffectScale: size, aEffectSeed: (i) => [(i * 0.6180339) % 1] }), extent)
+ const material = new FlatMaterial({ alphaMode: "blend", doubleSided: true, extraBits: [fireBit] })
+ material.data.mode = mode
+ material.data.time = 0
+ material.data.power = 0
+ const mesh = new Mesh3D({ geometry, material, castShadow: false })
+ this.layers.push({ mesh, material })
+ this.group.addChild(mesh)
+ }
+ }
+ update(time: number) {
+ if (!this.group.visible) return
+ if (!this.layers.length) this.build()
+ for (const [i, { mesh, material }] of this.layers.entries()) {
+ mesh.visible = i === 1 ? true : this.state.burning > 0
+ material.data.time = time
+ material.data.power = i === 1 ? Math.max(this.state.burning, this.state.fireRisk * 0.42) : this.state.burning
+ }
+ }
+ dispose() {
+ for (const { mesh, material } of this.layers) {
+ mesh.destroy({ geometry: true })
+ material.destroy()
+ }
+ this.layers = []
+ this.group.removeFromParent()
+ }
+}
diff --git a/src/render/three/surface-state.ts b/src/render/pixi3d/surface-state.ts
similarity index 100%
rename from src/render/three/surface-state.ts
rename to src/render/pixi3d/surface-state.ts
diff --git a/src/render/three/sync.ts b/src/render/pixi3d/sync.ts
similarity index 100%
rename from src/render/three/sync.ts
rename to src/render/pixi3d/sync.ts
diff --git a/src/render/three/thumbnails.ts b/src/render/pixi3d/thumbnails.ts
similarity index 87%
rename from src/render/three/thumbnails.ts
rename to src/render/pixi3d/thumbnails.ts
index 674a7c2..8780998 100644
--- a/src/render/three/thumbnails.ts
+++ b/src/render/pixi3d/thumbnails.ts
@@ -6,14 +6,15 @@
* is made once and kept. Make one of these for the page, and share it.
*/
import type { GroundId, KindId, PropId, Tier } from "../../game/content/index.ts"
+import type { Renderer } from "pixi.js"
import { pictureAsset } from "./models.ts"
import { portrait } from "./portrait.ts"
-export const thumbnails = () => {
+export const thumbnails = (renderer: Renderer) => {
const pictures = new Map<string, Promise<string>>()
let portraits: Promise<unknown> = Promise.resolve()
- const modelPicture = (make: () => Parameters<typeof portrait>[0]): Promise<string> => {
- const url = portraits.then(() => new Promise<string>((done) => requestAnimationFrame(() => done(portrait(make())))))
+ const modelPicture = (make: () => Parameters<typeof portrait>[1]): Promise<string> => {
+ const url = portraits.then(() => new Promise<string>((done) => requestAnimationFrame(() => done(portrait(renderer, make())))))
portraits = url.catch(() => undefined)
return url
}
diff --git a/src/render/three/townsfolk.ts b/src/render/pixi3d/townsfolk.ts
similarity index 100%
rename from src/render/three/townsfolk.ts
rename to src/render/pixi3d/townsfolk.ts
diff --git a/src/render/three/views.ts b/src/render/pixi3d/views.ts
similarity index 90%
rename from src/render/three/views.ts
rename to src/render/pixi3d/views.ts
index ff1cd99..c8d54c4 100644
--- a/src/render/three/views.ts
+++ b/src/render/pixi3d/views.ts
@@ -1,4 +1,4 @@
-import * as THREE from "three"
+import { Container3D } from "@pixi/3d"
import {
carrierDress,
cartLook,
@@ -13,7 +13,7 @@ import {
} from "../art.ts"
import { kinds, home, GROWN, ROCK_AMOUNT, type KindId } from "../../game/content/index.ts"
import { U, type Point } from "../../game/world/iso.ts"
-import { vertex3 } from "./assets/renderer.ts"
+import { vertex3 } from "./assets/space.ts"
import { Drawing, type Vertex } from "./assets/primitives.ts"
import { makeSails, makeFlag, buildingSmokeOrigin, buildingDimensions } from "./assets/buildings.ts"
import { makeMarker, makeUpgradeMarker } from "./assets/construction.ts"
@@ -40,7 +40,7 @@ export function structureState(look: {worn?: boolean; band?: "poor" | "plain" |
}
export class WorldView implements SceneNode {
- readonly group = new THREE.Group()
+ readonly group = new Container3D()
readonly anchor = { x: 0, y: 0 }
readonly stage: GameScene
readonly entity: number
@@ -55,7 +55,7 @@ export class WorldView implements SceneNode {
protected model(pickable = true) {
const model = new ModelHandle(this.stage.pool, pickable ? this.entity : null, this.anchor)
this.models.push(model)
- this.group.add(model.root)
+ this.group.addChild(model.root)
return model
}
get alpha() {
@@ -72,7 +72,7 @@ export class WorldView implements SceneNode {
protected viewTint: number | null = null
protected emphasis(emphasis: Emphasis) {
const tint = emphasis === "danger" ? 0xf3b5aa : this.viewTint !== null ? multiply(this.viewTint, this.stage.frost ? FROST : 0xffffff) : multiply(this.shade, this.stage.frost ? FROST : 0xffffff)
- for (const m of this.models) m.tint.setHex(tint)
+ for (const m of this.models) m.tint = tint
}
destroy() {
if (this.disposed) return
@@ -111,14 +111,14 @@ export class BuildingView extends WorldView {
this.upgradeMarker = this.model()
this.upgradeMarker.use("upgrade-marker", makeUpgradeMarker)
this.upgradeMarker.root.visible = false
- this.body.root.add(this.motion.root)
+ this.body.root.addChild(this.motion.root)
}
place(x: number, y: number) {
const size = kinds[this.kindId].size
this.anchor.x = x + size / 2
this.anchor.y = y + size / 2
- this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))
+ this.group.position.set(...vertex3([this.anchor.x, this.anchor.y, 0]))
}
update(look: BuildingLook, dt: number, emphasis: Emphasis) {
const kind = kinds[this.kindId],
@@ -156,7 +156,7 @@ export class BuildingView extends WorldView {
const state = structureState(look,this.stage.frost)
this.body.effects = build >= 1 ? state : surfaceState()
const serviceModel = upgraded && (this.kindId === "market" || this.kindId === "chapel")
- this.body.effectBounds.set((serviceModel ? kind.half * U : dimensions.half) * 32 * Math.SQRT2,H/Math.cos(Math.PI/6),this.entity%97/97,1)
+ this.body.effectBounds = [(serviceModel ? kind.half * U : dimensions.half) * 32 * Math.SQRT2, H / Math.cos(Math.PI / 6), (this.entity % 97) / 97, 1]
const effectLayout = `${level + 1}/${doorKey(doors)}`
if (this.effects && this.effectLayout !== effectLayout) {
this.effects.dispose()
@@ -165,8 +165,8 @@ export class BuildingView extends WorldView {
if(!this.effects&&build>=1&&(state.burning||state.fireRisk)){
this.effects = new StructureEffects(buildingAsset(this.kindId,1,null,doors,0,{},level),H)
this.effectLayout = effectLayout
- this.effects.group.userData.upgraded=upgraded
- this.group.add(this.effects.group)
+ this.effects.made.upgraded = upgraded
+ this.group.addChild(this.effects.group)
}
this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)
this.shade = 0xffffff
@@ -177,22 +177,22 @@ export class BuildingView extends WorldView {
this.motion.use("flag/" + this.kindId, () => makeFlag(this.kindId))
const a = buildingDimensions(this.kindId).half,
pitch = (2 * a) / kind.bays
- this.motion.root.position.copy(vertex3([-a + pitch * (kind.bays - 0.5), -a + pitch * 0.5, H + 24]))
+ this.motion.root.position.set(...vertex3([-a + pitch * (kind.bays - 0.5), -a + pitch * 0.5, H + 24]))
this.motion.root.rotation.y = Math.sin(this.wave) * 0.15
this.motion.root.scale.set(1 + Math.sin(this.wave) * 0.12, 1, 1 + Math.sin(this.wave) * 0.12)
} else if (kind.topper === "sails") {
if (look.working) this.wave += dt * 3.6
this.motion.use("mill-sails", makeSails)
- this.motion.root.position.copy(vertex3([kind.half * U + 3 * U, 0, H - 6]))
+ this.motion.root.position.set(...vertex3([kind.half * U + 3 * U, 0, H - 6]))
this.motion.root.rotation.x = this.wave
}
const origin = buildingSmokeOrigin(this.kindId, doors)
const smoking=look.working&&origin!==null&&look.build>=1&&!look.burning
if(smoking&&!this.smoke){
this.smoke=new SmokePlume()
- this.group.add(this.smoke.group)
+ this.group.addChild(this.smoke.group)
}
- if (smoking) this.smoke!.group.position.copy(vertex3(origin!))
+ if (smoking) this.smoke!.group.position.set(...vertex3(origin!))
this.smoke?.update(performance.now()/1000,Number(smoking))
this.viewTint = look.tint ?? null
this.emphasis(emphasis)
@@ -221,7 +221,7 @@ export class HouseView extends WorldView {
this.n = hash(x, y)
this.anchor.x = x + 0.5
this.anchor.y = y + 0.5
- this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))
+ this.group.position.set(...vertex3([this.anchor.x, this.anchor.y, 0]))
}
update(look: HouseLook, emphasis: Emphasis) {
const build = quantizeBuild(look.build),
@@ -233,12 +233,12 @@ export class HouseView extends WorldView {
this.plate.use(`plate/1/${build}`, () => plateAsset(1, build))
const state=structureState(look,this.stage.frost), H=home.tiers[look.tier].height
this.body.effects=build>=1?state:surfaceState()
- this.body.effectBounds.set((home.half+(look.tier>=2?1:0))*U*32*Math.SQRT2,H/Math.cos(Math.PI/6),this.n,1)
+ this.body.effectBounds = [(home.half + (look.tier >= 2 ? 1 : 0)) * U * 32 * Math.SQRT2, H / Math.cos(Math.PI / 6), this.n, 1]
// Recreate emitters only if an actual architectural upgrade changes the roof.
- if(this.effects&&this.effects.group.userData.tier!==look.tier){this.effects.dispose();this.effects=null}
+ if(this.effects&&this.effects.made.tier!==look.tier){this.effects.dispose();this.effects=null}
if(!this.effects&&build>=1&&(state.burning||state.fireRisk)){
this.effects=new StructureEffects(homeAsset(look.tier,this.n,1,null,noDoors),H)
- this.effects.group.userData.tier=look.tier;this.group.add(this.effects.group)
+ this.effects.made.tier=look.tier;this.group.addChild(this.effects.group)
}
this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)
this.shade=look.closed?CLOSED_SHADE:0xffffff
@@ -259,7 +259,7 @@ export class RuinView extends WorldView {
place(x: number, y: number, size: number) {
this.anchor.x = x + size / 2
this.anchor.y = y + size / 2
- this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))
+ this.group.position.set(...vertex3([this.anchor.x, this.anchor.y, 0]))
this.body.use(`ruin/${this.cause}/${size}`, () => makeRuin(size, this.cause))
}
update(emphasis: Emphasis) {
@@ -276,11 +276,11 @@ export class TreeView extends WorldView {
}
place(x: number, y: number) {
this.variant = treeVariant(x, y)
- this.body.root.scale.setScalar(this.variant.scale)
- this.body.root.position.copy(vertex3(this.variant.offset))
+ this.body.root.scale.set(this.variant.scale, this.variant.scale, this.variant.scale)
+ this.body.root.position.set(...vertex3(this.variant.offset))
this.anchor.x = x + 0.5
this.anchor.y = y + 0.5
- this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))
+ this.group.position.set(...vertex3([this.anchor.x, this.anchor.y, 0]))
}
update(growth: number, emphasis: Emphasis) {
const stage = growth >= GROWN.tree ? 1 : growth >= GROWN.tree / 2 ? 0.6 : 0.3,
@@ -307,7 +307,7 @@ export class RockView extends WorldView {
if (w === 0) return
this.anchor.x = this.cell.x + w / 2
this.anchor.y = this.cell.y + h / 2
- this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))
+ this.group.position.set(...vertex3([this.anchor.x, this.anchor.y, 0]))
// Quarried down to its worked face (see `FACE_TICKS`), it gives one at a time: drawn as cut benches.
const stage = amount <= 1 ? "worked" : amount > ROCK_AMOUNT / 2
this.body.use(`rock/${ore}/${stage}/${this.variant}/${w}x${h}`, () => makeRock(ore, stage, this.variant, w, h))
@@ -322,7 +322,7 @@ export class FieldView extends WorldView {
place(x: number, y: number) {
this.anchor.x = x + 0.5
this.anchor.y = y + 0.5
- this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))
+ this.group.position.set(...vertex3([this.anchor.x, this.anchor.y, 0]))
}
update(growth: number) {
const stage = Math.min(3, Math.floor((growth / GROWN.field) * 3)) as 0 | 1 | 2 | 3
@@ -383,7 +383,7 @@ export class WalkerView extends WorldView {
asset.faces.push(...shadow.asset.faces)
return asset
})
- this.group.position.copy(vertex3([x, y, 0]))
+ this.group.position.set(...vertex3([x, y, 0]))
if (dir.x || dir.y) this.group.rotation.y = Math.atan2(-dir.y, dir.x)
this.body.alpha = this.alpha
}
diff --git a/src/render/three/assets/renderer.ts b/src/render/three/assets/renderer.ts
deleted file mode 100644
index e55e792..0000000
--- a/src/render/three/assets/renderer.ts
+++ /dev/null
@@ -1,395 +0,0 @@
-import * as THREE from "three"
-import { LineSegments2 } from "three/addons/lines/LineSegments2.js"
-import { LineSegmentsGeometry } from "three/addons/lines/LineSegmentsGeometry.js"
-import { LineMaterial } from "three/addons/lines/LineMaterial.js"
-import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js"
-import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"
-import { mergeGeometries, mergeVertices } from "three/addons/utils/BufferGeometryUtils.js"
-import { palette, type Face, type InkAsset, type Vertex } from "./primitives.ts"
-import { installSurfaceShader } from "../surface-shader.ts"
-import { SmokePlume } from "../smoke-effects.ts"
-import { FountainWater } from "../fountain-effects.ts"
-
-/** A 30° elevation and 45° heading reproduce the game's 64×32 projection.
- * The vertical conversion preserves pixel-authored building heights exactly. */
-export const floorScale = 32 * Math.SQRT2
-export const vertex3 = ([u, v, z]: Vertex) => new THREE.Vector3(u * floorScale, z / Math.cos(Math.PI / 6), v * floorScale)
-
-function contourCenters(asset: InkAsset) {
- const sums = new Map<number, { point: THREE.Vector3; count: number }>()
- for (const face of asset.faces)
- if (face.contour) {
- const sum = sums.get(face.contour) ?? { point: new THREE.Vector3(), count: 0 }
- for (const p of face.points) {
- sum.point.add(vertex3(p))
- sum.count++
- }
- sums.set(face.contour, sum)
- }
- return new Map([...sums].map(([id, sum]) => [id, sum.point.divideScalar(sum.count)]))
-}
-function outwardPoints(face: Face, centers: Map<number, THREE.Vector3>) {
- const ps = face.points.map(vertex3)
- const normal = new THREE.Vector3().crossVectors(ps[1]!.clone().sub(ps[0]!), ps[2]!.clone().sub(ps[0]!))
- const center = ps.reduce((sum, p) => sum.add(p), new THREE.Vector3()).divideScalar(ps.length)
- if (normal.dot(center.sub(centers.get(face.contour!)!)) < 0) ps.reverse()
- return ps
-}
-
-/** Inward hulls give short curved contours a continuous ink silhouette,
- * including at high zoom where separate round-ended lines overlap. */
-function silhouetteMesh(asset: InkAsset, faces: ReadonlyArray<Face>) {
- const centers = contourCenters(asset),
- normals = new Map<string, THREE.Vector3>()
- const key = (p: THREE.Vector3, contour: number) =>
- `${contour}|` +
- p
- .toArray()
- .map((n) => n.toFixed(4))
- .join(",")
- for (const face of faces) {
- const ps = outwardPoints(face, centers),
- n = new THREE.Vector3().crossVectors(ps[1]!.clone().sub(ps[0]!), ps[2]!.clone().sub(ps[0]!)).normalize()
- for (const p of ps) {
- const normal = normals.get(key(p, face.contour!)) ?? new THREE.Vector3()
- normal.add(n)
- normals.set(key(p, face.contour!), normal)
- }
- }
- const positions: Array<number> = []
- for (const face of faces) {
- const ps = outwardPoints(face, centers).map((p) =>
- p.clone().add(
- normals
- .get(key(p, face.contour!))!
- .clone()
- .normalize()
- .multiplyScalar((face.contourWidth ?? 1) * 0.5)
- )
- )
- for (let i = 1; i < ps.length - 1; i++) for (const p of [ps[0]!, ps[i + 1]!, ps[i]!]) positions.push(...p.toArray())
- }
- const geometry = new THREE.BufferGeometry().setAttribute("position", new THREE.Float32BufferAttribute(positions, 3))
- geometry.computeVertexNormals()
- const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: palette.ink, side: THREE.FrontSide }))
- mesh.name = "ink-silhouette"
- return mesh
-}
-
-const materialCache = new Map<string, THREE.MeshBasicMaterial>()
-function fillMaterial(color: number, opacity = 1) {
- const key = `${color}/${opacity}`
- let material = materialCache.get(key)
- if (!material) {
- material = new THREE.MeshBasicMaterial({
- color,
- opacity,
- transparent: opacity < 1,
- depthWrite: opacity >= 1,
- side: THREE.DoubleSide,
- polygonOffset: true,
- polygonOffsetFactor: 6,
- polygonOffsetUnits: 2
- })
- materialCache.set(key, material)
- }
- return material
-}
-function faceMesh(points: ReadonlyArray<Vertex>, color: number, opacity = 1) {
- const coordinates = points.map(vertex3)
- const positions: Array<number> = []
- for (let i = 1; i < coordinates.length - 1; i++)
- for (const p of [coordinates[0]!, coordinates[i]!, coordinates[i + 1]!]) positions.push(...p.toArray())
- const geometry = new THREE.BufferGeometry()
- geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3))
- geometry.computeVertexNormals()
- const mesh = new THREE.Mesh(geometry, fillMaterial(color, opacity))
- mesh.userData.structureSurface = true
- return mesh
-}
-
-export interface BuiltAsset {
- group: THREE.Group
- lineMaterials: Array<{ material: LineMaterial; width: number }>
- updateContours: (camera: THREE.Camera) => void
- updateEffects: (time: number) => void
- dispose: () => void
-}
-export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; meshInk?: boolean; hullContours?: boolean; meshContours?:boolean; surfaceEffects?: boolean } = {}): BuiltAsset {
- const group = new THREE.Group()
- group.name = asset.id
- if (options.batchFaces) {
- const batches = new Map<string, { color: number; opacity: number; geometries: Array<THREE.BufferGeometry> }>()
- for (const face of asset.faces) {
- const key = `${face.color}/${face.opacity ?? 1}`,
- batch = batches.get(key) ?? { color: face.color, opacity: face.opacity ?? 1, geometries: [] }
- batch.geometries.push(faceMesh(face.points, face.color, face.opacity ?? 1).geometry)
- batches.set(key, batch)
- }
- for (const { color, opacity, geometries } of batches.values()) {
- const geometry = mergeGeometries(geometries)
- if (!geometry) throw new Error("Could not batch map faces")
- geometries.forEach((g) => g.dispose())
- const mesh = new THREE.Mesh(geometry, fillMaterial(color, opacity))
- mesh.userData.structureSurface = true
- group.add(mesh)
- }
- } else {
- for (const face of asset.faces) group.add(faceMesh(face.points, face.color, face.opacity ?? 1))
- }
- const lineMaterials: Array<{ material: LineMaterial; width: number }> = []
- const effectTime = { value: 0 }, effectMaterials: THREE.MeshBasicMaterial[] = []
- if (asset.effects && options.surfaceEffects !== false) {
- const e = asset.effects
- for (const child of group.children) if (child instanceof THREE.Mesh && child.userData.structureSurface) {
- const source = child.material as THREE.MeshBasicMaterial, material = source.clone()
- installSurfaceShader(material, source.color.getHex(THREE.SRGBColorSpace), effectTime, e.state, new THREE.Vector4(e.half * floorScale, e.height / Math.cos(Math.PI / 6), 0.31, 1))
- child.material = material; effectMaterials.push(material)
- }
- }
- const curveMaterials: Array<THREE.MeshBasicMaterial> = []
- const curves = new Map<string, { geometries: Array<THREE.BufferGeometry>; color: number; opacity: number }>()
- const batches = new Map<string, { positions: Array<number>; width: number; color: number; opacity: number }>()
- for (const stroke of asset.strokes) {
- const key = `${stroke.width}/${stroke.color}/${stroke.opacity}`
- if (options.meshInk && stroke.width > 0 && stroke.points.length <= 8) {
- const batch = curves.get(key) ?? { geometries: [], color: stroke.color, opacity: stroke.opacity }
- for (let i = 1; i < stroke.points.length; i++) {
- const a = vertex3(stroke.points[i - 1]!),
- b = vertex3(stroke.points[i]!),
- delta = b.clone().sub(a),
- length = delta.length()
- if (length < 0.0001) continue
- const g = new THREE.CylinderGeometry(stroke.width / 2, stroke.width / 2, length, 6)
- g.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), delta.normalize()))
- g.translate(...a.add(b).multiplyScalar(0.5).toArray())
- batch.geometries.push(g)
- }
- if (batch.geometries.length) curves.set(key, batch)
- continue
- }
- // Continuous tubes keep small circle joins clean at high magnification.
- const first = stroke.points[0]!,
- last = stroke.points.at(-1)!
- if (stroke.width > 0 && stroke.points.length > 8) {
- const closed = first.every((n, i) => Math.abs(n - last[i]!) < 1e-6)
- const curve = new THREE.CatmullRomCurve3((closed ? stroke.points.slice(0, -1) : stroke.points).map(vertex3), closed)
- const geometry = new THREE.TubeGeometry(curve, (stroke.points.length - 1) * 2, stroke.width / 2, 6, closed)
- const batch = curves.get(key) ?? { geometries: [], color: stroke.color, opacity: stroke.opacity }
- batch.geometries.push(geometry)
- curves.set(key, batch)
- continue
- }
- const batch = batches.get(key) ?? { positions: [], width: stroke.width, color: stroke.color, opacity: stroke.opacity }
- for (let i = 1; i < stroke.points.length; i++)
- batch.positions.push(...vertex3(stroke.points[i - 1]!).toArray(), ...vertex3(stroke.points[i]!).toArray())
- batches.set(key, batch)
- }
- const addLines = (positions: Array<number>, width: number, color: number, opacity: number) => {
- const geometry = new LineSegmentsGeometry().setPositions(positions)
- const material = new LineMaterial({
- color,
- opacity,
- transparent: opacity < 1,
- depthTest: true,
- depthWrite: false,
- alphaToCoverage: true,
- worldUnits: true
- })
- material.linewidth = width
- const lines = new LineSegments2(geometry, material)
- lines.renderOrder = 2
- group.add(lines)
- lineMaterials.push({ material, width })
- return lines
- }
- for (const b of batches.values()) addLines(b.positions, b.width, b.color, b.opacity)
- for (const { geometries, color, opacity } of curves.values()) {
- const geometry = mergeGeometries(geometries)!
- geometries.forEach((g) => g.dispose())
- const material = new THREE.MeshBasicMaterial({ color, opacity, transparent: opacity < 1, depthWrite: false })
- const mesh = new THREE.Mesh(geometry, material)
- mesh.renderOrder = 2
- group.add(mesh)
- curveMaterials.push(material)
- }
-
- // Smooth props and foliage get view-dependent silhouette edges, without
- // drawing their hidden edges or the internal triangulation.
- const counts = new Map<number, number>()
- for (const face of asset.faces) if (face.contour) counts.set(face.contour, (counts.get(face.contour) ?? 0) + 1)
- const smooth = new Set([...counts].filter(([, count]) => options.hullContours || count > 6).map(([id]) => id))
- const smoothFaces = asset.faces.filter((f) => f.contour && smooth.has(f.contour) && (f.contourWidth ?? 1) > 0)
- const hull = smoothFaces.length ? silhouetteMesh(asset, smoothFaces) : null
- if (hull) group.add(hull)
- const edges = new Map<string, { a: THREE.Vector3; b: THREE.Vector3; normals: Array<THREE.Vector3>; width: number }>()
- const centers = contourCenters(asset)
- for (const face of asset.faces.filter((f) => f.contour && !smooth.has(f.contour))) {
- const points = outwardPoints(face, centers)
- const normal = new THREE.Vector3().crossVectors(points[1]!.clone().sub(points[0]!), points[2]!.clone().sub(points[0]!)).normalize()
- for (let i = 0; i < points.length; i++) {
- const a = points[i]!,
- b = points[(i + 1) % points.length]!
- const keys = [
- a
- .toArray()
- .map((n) => n.toFixed(4))
- .join(","),
- b
- .toArray()
- .map((n) => n.toFixed(4))
- .join(",")
- ].sort()
- const key = `${face.contour}|${keys.join("|")}`
- const edge = edges.get(key) ?? { a, b, normals: [], width: face.contourWidth ?? 1 }
- edge.normals.push(normal)
- edges.set(key, edge)
- }
- }
- // GPU silhouette masks let sharp foliage share instances at every camera
- // angle, without a wireframe or an expanded hull crossing the canopy.
- if (options.meshContours) {
- const batches = new Map<number, Array<THREE.BufferGeometry>>()
- for (const { a, b, normals, width } of edges.values()) {
- const delta = b.clone().sub(a), length = delta.length()
- if (length < 0.0001 || width <= 0) continue
- const geometry = new THREE.CylinderGeometry(width / 2, width / 2, length, 6)
- geometry.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), delta.normalize()))
- geometry.translate(...a.clone().add(b).multiplyScalar(0.5).toArray())
- const n1 = normals[0]!, n2 = normals[1] ?? n1.clone().negate(), count = geometry.getAttribute("position").count
- geometry.setAttribute("inkNormalA", new THREE.Float32BufferAttribute(Array.from({ length: count }, () => n1.toArray()).flat(), 3))
- geometry.setAttribute("inkNormalB", new THREE.Float32BufferAttribute(Array.from({ length: count }, () => n2.toArray()).flat(), 3))
- const batch = batches.get(width) ?? []
- batch.push(geometry)
- batches.set(width, batch)
- }
- for (const geometries of batches.values()) {
- const material = new THREE.MeshBasicMaterial({ color: palette.ink, depthWrite: false })
- const mesh = new THREE.Mesh(mergeGeometries(geometries)!, material)
- mesh.renderOrder = 2
- group.add(mesh)
- curveMaterials.push(material)
- geometries.forEach(g => g.dispose())
- }
- }
- const contours = new Map(
- (options.meshContours ? [] : [...new Set([...edges.values()].map((e) => e.width))]).map((width) => [width, addLines([0, 0, 0, 0, 0, 0], width, palette.ink, 1)])
- )
- const lastDirection = new THREE.Vector3()
- const updateContours = (camera: THREE.Camera) => {
- if (!contours.size) return
- group.updateWorldMatrix(true, false)
- const direction = camera
- .getWorldDirection(new THREE.Vector3())
- .negate()
- .applyQuaternion(group.getWorldQuaternion(new THREE.Quaternion()).invert())
- if (direction.distanceToSquared(lastDirection) < 1e-12) return
- lastDirection.copy(direction)
- const batches = new Map<number, Array<number>>()
- for (const { a, b, normals, width } of edges.values()) {
- const signs = normals.map((n) => n.dot(direction))
- if (normals.length === 1 || (Math.min(...signs) < 0 && Math.max(...signs) >= 0)) {
- const positions = batches.get(width) ?? []
- positions.push(...a.toArray(), ...b.toArray())
- batches.set(width, positions)
- }
- }
- for (const [width, lines] of contours) {
- const positions = batches.get(width) ?? []
- const previous = lines.geometry
- lines.geometry = new LineSegmentsGeometry().setPositions(positions.length ? positions : [0, 0, 0, 0, 0, 0])
- previous.dispose()
- }
- }
- const plume=asset.smokeEffect&&options.surfaceEffects!==false?new SmokePlume():null
- if(plume){plume.group.position.copy(vertex3(asset.smokeEffect!.origin));group.add(plume.group);plume.update(0)}
- const fountains=options.surfaceEffects!==false?(asset.fountains??[]).map(f=>new FountainWater(f)):[]
- for(const fountain of fountains)group.add(fountain.group)
- const dispose = () => {
- plume?.dispose()
- fountains.forEach(f=>f.dispose())
- group.traverse((object) => {
- if (object instanceof THREE.Mesh) object.geometry.dispose()
- })
- for (const { material } of lineMaterials) material.dispose()
- curveMaterials.forEach((material) => material.dispose())
- effectMaterials.forEach(m => m.dispose())
- if (hull) (hull.material as THREE.Material).dispose()
- for (const object of group.children) if (object instanceof LineSegments2) object.geometry.dispose()
- }
- return { group, lineMaterials, updateContours, updateEffects: time => { effectTime.value = time;plume?.update(time);fountains.forEach(f=>f.update(time)) }, dispose }
-}
-
-/** GLB uses ordinary meshes for ink strokes so the outlines survive import.
- * Rounded props use an inverted hull for their view-dependent silhouette. */
-export async function exportAsset(asset: InkAsset) {
- const group = new THREE.Group()
- group.name = asset.id
- if(asset.effects)group.userData.inklineSurfaceEffects=asset.effects
- if(asset.smokeEffect)group.userData.inklineSmokeEffect=asset.smokeEffect
- if(asset.fountains?.length)group.userData.inklineFountains=asset.fountains
- for (const face of asset.faces) group.add(faceMesh(face.points, face.color, face.opacity ?? 1))
- const contourFaces = asset.faces.filter((face) => face.contour)
- const hull = contourFaces.length ? silhouetteMesh(asset, contourFaces) : null
- if (hull) group.add(hull)
- const inkMaterials = new Map<string, THREE.MeshBasicMaterial>()
- for (const stroke of asset.strokes) {
- const key = `${stroke.color}/${stroke.opacity}`
- let material = inkMaterials.get(key)
- if (!material) {
- material = new THREE.MeshBasicMaterial({ color: stroke.color, opacity: stroke.opacity, transparent: stroke.opacity < 1 })
- inkMaterials.set(key, material)
- }
- for (let i = 1; i < stroke.points.length; i++) {
- const a = vertex3(stroke.points[i - 1]!),
- b = vertex3(stroke.points[i]!),
- delta = b.clone().sub(a),
- length = delta.length()
- if (length < 0.0001) continue
- const mesh = new THREE.Mesh(new THREE.CylinderGeometry(stroke.width / 2, stroke.width / 2, length, 6), material)
- mesh.position.copy(a.clone().add(b).multiplyScalar(0.5))
- mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), delta.normalize())
- group.add(mesh)
- }
- }
- // Batch like materials before export rather than shipping hundreds of nodes.
- const merged = new THREE.Group()
- merged.name = group.name
- merged.userData = { ...group.userData }
- group.updateMatrixWorld(true)
- const batches = new Map<THREE.MeshBasicMaterial, Array<THREE.BufferGeometry>>()
- group.traverse((object) => {
- if (!(object instanceof THREE.Mesh)) return
- const geometry = object.geometry.index ? object.geometry.toNonIndexed() : object.geometry.clone()
- geometry.applyMatrix4(object.matrixWorld)
- for (const attribute of Object.keys(geometry.attributes))
- if (attribute !== "position" && attribute !== "normal") geometry.deleteAttribute(attribute)
- const material = object.material as THREE.MeshBasicMaterial
- const geometries = batches.get(material) ?? []
- geometries.push(geometry)
- batches.set(material, geometries)
- })
- for (const [material, geometries] of batches) {
- const combined = mergeGeometries(geometries)
- if (!combined) throw new Error("Could not batch exported geometry")
- const geometry = mergeVertices(combined)
- combined.dispose()
- geometries.forEach((g) => g.dispose())
- merged.add(new THREE.Mesh(geometry, material))
- }
- const result = await new GLTFExporter().parseAsync(merged, { binary: true })
- merged.traverse((object) => {
- if (object instanceof THREE.Mesh) object.geometry.dispose()
- })
- group.traverse((object) => {
- if (object instanceof THREE.Mesh) object.geometry.dispose()
- })
- for (const material of inkMaterials.values()) material.dispose()
- if (hull) (hull.material as THREE.Material).dispose()
- if (!(result instanceof ArrayBuffer)) throw new Error("Expected binary glTF")
- return result
-}
-
-export async function reloadExportedAsset(asset: InkAsset) {
- return (await new GLTFLoader().parseAsync(await exportAsset(asset), "")).scene
-}
diff --git a/src/render/three/fish-effects.ts b/src/render/three/fish-effects.ts
deleted file mode 100644
index 4982e5d..0000000
--- a/src/render/three/fish-effects.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import * as THREE from "three"
-import { floorScale, vertex3 } from "./assets/renderer.ts"
-import type { Point } from "../../game/world/iso.ts"
-
-const vertex = `
-attribute float seed;
-varying vec2 point;
-varying float phase;
-void main(){
- point=position.xz/${(floorScale * 0.5).toFixed(3)};
- phase=seed;
- gl_Position=projectionMatrix*modelViewMatrix*instanceMatrix*vec4(position,1.0);
-}`
-// Now and then (each cell in its own time), one thin ink ring spreads slowly from a point off the middle and
-// fades; most of the time the water is still. Calm enough to sit beside the town, plain enough to read.
-const fragment = `
-uniform float time;
-varying vec2 point;
-varying float phase;
-void main(){
- vec2 at=point-vec2(fract(phase*7.13)-0.5,fract(phase*3.71)-0.5)*0.5;
- float d=length(at);
- float age=fract(time*0.058+phase)/0.3;
- if(age>1.0)discard;
- float r=0.08+age*0.5;
- float ring=1.0-smoothstep(0.0,0.03,abs(d-r));
- float fade=smoothstep(0.0,0.15,age)*(1.0-age);
- float edge=1.0-smoothstep(0.85,1.0,max(abs(point.x),abs(point.y)));
- float alpha=ring*fade*edge*0.38;
- if(alpha<0.01)discard;
- gl_FragColor=vec4(pow(vec3(0.32,0.45,0.52),vec3(2.2)),alpha);
- #include <colorspace_fragment>
-}`
-
-/**
- * Fish in the water: a slow ripple now and then on every cell of water
- * that would give a catch, none on a cell resting after one. A fishery's
- * shore reads at a glance as stocked or fished out.
- */
-export class FishWater {
- readonly group = new THREE.Group()
- private readonly time = { value: 0 }
- private mesh: THREE.InstancedMesh<THREE.PlaneGeometry, THREE.ShaderMaterial> | null = null
- private key = ""
- set(cells: ReadonlyArray<Point>) {
- const key = cells.map((c) => `${c.x},${c.y}`).join(";")
- if (key === this.key) return
- this.key = key
- if (!this.mesh || this.mesh.instanceMatrix.count < cells.length) {
- this.dispose()
- const capacity = Math.max(64, cells.length)
- const geometry = new THREE.PlaneGeometry(floorScale * 0.96, floorScale * 0.96)
- geometry.rotateX(-Math.PI / 2)
- geometry.setAttribute("seed", new THREE.InstancedBufferAttribute(new Float32Array(capacity), 1))
- const material = new THREE.ShaderMaterial({ vertexShader: vertex, fragmentShader: fragment, uniforms: { time: this.time }, transparent: true, depthWrite: false })
- this.mesh = new THREE.InstancedMesh(geometry, material, capacity)
- this.mesh.frustumCulled = false
- this.mesh.renderOrder = 2
- this.group.add(this.mesh)
- }
- const seeds = this.mesh.geometry.getAttribute("seed") as THREE.InstancedBufferAttribute
- const m = new THREE.Matrix4()
- cells.forEach((c, i) => {
- m.setPosition(vertex3([c.x + 0.5, c.y + 0.5, -0.1]))
- this.mesh!.setMatrixAt(i, m)
- seeds.setX(i, (Math.abs((c.x * 73856093) ^ (c.y * 19349663)) % 1000) / 1000)
- })
- this.mesh.count = cells.length
- this.mesh.instanceMatrix.needsUpdate = true
- seeds.needsUpdate = true
- }
- update(time: number) {
- this.time.value = time
- }
- dispose() {
- if (!this.mesh) return
- this.mesh.removeFromParent()
- this.mesh.geometry.dispose()
- this.mesh.material.dispose()
- this.mesh.dispose()
- this.mesh = null
- }
-}
diff --git a/src/render/three/fountain-effects.ts b/src/render/three/fountain-effects.ts
deleted file mode 100644
index 6606ae3..0000000
--- a/src/render/three/fountain-effects.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import * as THREE from "three"
-import type { InkAsset } from "./assets/primitives.ts"
-
-type Fountain = NonNullable<InkAsset["fountains"]>[number]
-const floorScale=32*Math.SQRT2, heightScale=1/Math.cos(Math.PI/6)
-
-const dropsVertex=`
-attribute float waterPhase;
-attribute float jetAngle;
-uniform float time;
-uniform float radius;
-uniform float level;
-uniform float nozzle;
-varying float age;
-varying float phase;
-void main(){
- age=fract(time*0.85+waterPhase);phase=waterPhase;
- float distance=radius*0.84*age;
- float h=mix(nozzle,level,age)+4.0*age*(1.0-age)*6.9282;
- vec3 center=vec3(cos(jetAngle)*distance,h,sin(jetAngle)*distance);
- vec3 drop=position*vec3(0.8,1.7,0.8)+center;
- gl_Position=projectionMatrix*modelViewMatrix*vec4(drop,1.0);
-}`
-const dropsFragment=`
-varying float age;
-varying float phase;
-void main(){
- float alpha=smoothstep(0.0,0.07,age)*(1.0-smoothstep(0.94,1.0,age))*0.68;
- vec3 color=mix(vec3(0.65,0.78,0.82),vec3(0.96,0.99,0.96),fract(phase*13.0));
- gl_FragColor=vec4(pow(color,vec3(2.2)),alpha);
- #include <colorspace_fragment>
-}`
-const poolVertex=`
-uniform float radius;
-varying vec2 poolPoint;
-void main(){poolPoint=position.xz/radius;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}
-`
-const poolFragment=`
-uniform float time;
-varying vec2 poolPoint;
-void main(){
- float waves=0.0;
- for(int i=0;i<4;i++){
- float a=float(i)*1.5707963+0.7853982;
- float d=length(poolPoint-vec2(cos(a),sin(a))*0.84);
- waves+=pow(max(0.0,sin(d*28.0-time*6.0)),14.0)*exp(-d*7.0);
- }
- float edge=1.0-smoothstep(0.96,1.0,length(poolPoint));
- float shimmer=sin(poolPoint.x*17.0+time)*sin(poolPoint.y*13.0-time*0.7)*0.015;
- gl_FragColor=vec4(pow(vec3(0.94,0.98,0.97),vec3(2.2)),edge*(0.025+waves*0.28+shimmer));
- #include <colorspace_fragment>
-}`
-
-/** Flowing droplets and impact ripples, constrained to the actual stone basin. */
-export class FountainWater {
- readonly group=new THREE.Group()
- private time={value:0}
- private drops: THREE.InstancedMesh<THREE.SphereGeometry,THREE.ShaderMaterial>
- private pool: THREE.Mesh<THREE.CircleGeometry,THREE.ShaderMaterial>
- constructor(fountain: Fountain) {
- const r=fountain.radius*floorScale, level=fountain.level*heightScale, nozzle=fountain.nozzle*heightScale
- this.group.position.set(fountain.origin[0]*floorScale,fountain.origin[2]*heightScale,fountain.origin[1]*floorScale)
- const count=64,geometry=new THREE.SphereGeometry(0.34,6,4)
- geometry.setAttribute("waterPhase",new THREE.InstancedBufferAttribute(Float32Array.from({length:count},(_,i)=>Math.floor(i/4)/16),1))
- geometry.setAttribute("jetAngle",new THREE.InstancedBufferAttribute(Float32Array.from({length:count},(_,i)=>i%4*Math.PI/2+Math.PI/4),1))
- geometry.boundingBox=new THREE.Box3(new THREE.Vector3(-r,level-1,-r),new THREE.Vector3(r,nozzle+7,r))
- geometry.boundingSphere=new THREE.Sphere(new THREE.Vector3(0,(level+nozzle)/2,0),r+nozzle+7)
- const material=new THREE.ShaderMaterial({vertexShader:dropsVertex,fragmentShader:dropsFragment,uniforms:{time:this.time,radius:{value:r},level:{value:level},nozzle:{value:nozzle}},transparent:true,depthWrite:false,depthTest:true})
- this.drops=new THREE.InstancedMesh(geometry,material,count)
- for(let i=0;i<count;i++)this.drops.setMatrixAt(i,new THREE.Matrix4())
- this.drops.frustumCulled=false;this.drops.renderOrder=3;this.group.add(this.drops)
- const poolGeometry=new THREE.CircleGeometry(r,32);poolGeometry.rotateX(-Math.PI/2)
- const poolMaterial=new THREE.ShaderMaterial({vertexShader:poolVertex,fragmentShader:poolFragment,uniforms:{time:this.time,radius:{value:r}},transparent:true,depthWrite:false,depthTest:true,side:THREE.DoubleSide})
- this.pool=new THREE.Mesh(poolGeometry,poolMaterial);this.pool.position.y=level+0.07;this.pool.renderOrder=2;this.group.add(this.pool)
- }
- update(time: number){this.time.value=time}
- dispose(){this.group.removeFromParent();this.drops.geometry.dispose();this.drops.material.dispose();this.drops.dispose();this.pool.geometry.dispose();this.pool.material.dispose()}
-}
diff --git a/src/render/three/pool.ts b/src/render/three/pool.ts
deleted file mode 100644
index 0bf14d9..0000000
--- a/src/render/three/pool.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import * as THREE from "three"
-import { buildAsset, type BuiltAsset } from "./assets/renderer.ts"
-import type { InkAsset } from "./assets/primitives.ts"
-import { surfaceState, type SurfaceState } from "./surface-state.ts"
-import { installSurfaceShader } from "./surface-shader.ts"
-
-interface Part {
- source: THREE.Mesh<THREE.BufferGeometry, THREE.MeshBasicMaterial>
- material: THREE.MeshBasicMaterial
- mesh: THREE.InstancedMesh | null
- color: number
-}
-interface Template {
- key: string
- model: BuiltAsset
- group: THREE.Group
- parts: Array<Part>
- handles: Set<ModelHandle>
- capacity: number
- alpha: Float32Array
- effects: Float32Array
- hazards: Float32Array
- bounds: Float32Array
- used: number
-}
-
-/** One logical model. Its root owns transforms; shared GPU instances draw it. */
-export class ModelHandle {
- readonly root = new THREE.Group()
- readonly tint = new THREE.Color(0xffffff)
- alpha = 1
- colors: ReadonlyMap<number, number> | null = null
- effects: SurfaceState = surfaceState()
- effectBounds = new THREE.Vector4()
- template: Template | null = null
- readonly pool: ModelPool
- readonly entity: number | null
- readonly pickCell: { x: number; y: number } | null
- constructor(pool: ModelPool, entity: number | null = null, pickCell: { x: number; y: number } | null = null) {
- this.pool = pool
- this.entity = entity
- this.pickCell = pickCell
- }
- use(key: string, create: () => InkAsset) {
- if (this.template?.key === key) return
- this.pool.release(this)
- this.template = this.pool.acquire(key, create)
- this.template.handles.add(this)
- }
- dispose() {
- this.pool.release(this)
- this.root.removeFromParent()
- }
-}
-
-/** Geometry, outlines and materials are built once per visual state. Repeated
- * homes, trees and walkers share instanced draw calls, with entity IDs retained
- * for picking. Unused construction/animation states have a bounded cache. */
-export class ModelPool {
- readonly root = new THREE.Group()
- private templates = new Map<string, Template>()
- private stamp = 0
- private matrix = new THREE.Matrix4()
- private color = new THREE.Color()
- readonly viewDirection = new THREE.Vector3(1, 1, 1).normalize()
- readonly time = { value: 0 }
- acquire(key: string, create: () => InkAsset): Template {
- let entry = this.templates.get(key)
- if (!entry) {
- const model = buildAsset(create(), { batchFaces: true, meshInk: true, meshContours: true, surfaceEffects: false })
- const parts: Array<Part> = []
- model.group.updateMatrixWorld(true)
- for (const child of model.group.children) {
- if (!(child instanceof THREE.Mesh)) throw new Error("Live model ink must be portable mesh geometry")
- const source = child as THREE.Mesh<THREE.BufferGeometry, THREE.MeshBasicMaterial>,
- material = source.material.clone()
- const color = source.material.color.getHex(THREE.SRGBColorSpace)
- material.color.setHex(0xffffff)
- material.alphaToCoverage = !material.transparent
- material.onBeforeCompile = (shader) => {
- shader.vertexShader = "attribute float inkOpacity; varying float vInkOpacity;\n" + shader.vertexShader
- shader.vertexShader = shader.vertexShader.replace("#include <begin_vertex>", "#include <begin_vertex>\nvInkOpacity=inkOpacity;")
- if (source.geometry.hasAttribute("inkNormalA")) {
- shader.uniforms.inkViewDirection = { value: this.viewDirection }
- shader.vertexShader = "attribute vec3 inkNormalA; attribute vec3 inkNormalB; uniform vec3 inkViewDirection;\n" + shader.vertexShader
- shader.vertexShader = shader.vertexShader.replace(
- "vInkOpacity=inkOpacity;",
- "vInkOpacity=inkOpacity * step(0.0, -dot(mat3(instanceMatrix)*inkNormalA,inkViewDirection)*dot(mat3(instanceMatrix)*inkNormalB,inkViewDirection));"
- )
- }
- shader.fragmentShader = "varying float vInkOpacity;\n" + shader.fragmentShader
- shader.fragmentShader = shader.fragmentShader.replace(
- "#include <alphatest_fragment>",
- "diffuseColor.a *= vInkOpacity;\n#include <alphatest_fragment>"
- )
- }
- material.customProgramCacheKey = () =>
- source.geometry.hasAttribute("inkNormalA") ? "ink-instance-silhouette-v1" : "ink-instance-opacity-v1"
- if (source.userData.structureSurface) installSurfaceShader(material,color,this.time,surfaceState(),new THREE.Vector4(),true)
- parts.push({ source, material, mesh: null, color })
- }
- entry = {
- key,
- model,
- parts,
- group: new THREE.Group(),
- handles: new Set(),
- capacity: 0,
- alpha: new Float32Array(),
- effects: new Float32Array(), hazards: new Float32Array(), bounds: new Float32Array(),
- used: ++this.stamp
- }
- this.templates.set(key, entry)
- }
- entry.used = ++this.stamp
- if (entry.group.parent !== this.root) this.root.add(entry.group)
- return entry
- }
- release(handle: ModelHandle) {
- if (!handle.template) return
- handle.template.handles.delete(handle)
- handle.template.used = ++this.stamp
- handle.template = null
- }
- flush() {
- for (const entry of this.templates.values()) {
- const handles = [...entry.handles].filter((h) => {
- if (h.alpha <= 0) return false
- for (let p: THREE.Object3D | null = h.root; p; p = p.parent) if (!p.visible) return false
- return true
- })
- if (!handles.length) {
- entry.group.removeFromParent()
- continue
- }
- if (entry.group.parent !== this.root) this.root.add(entry.group)
- if (entry.capacity < handles.length) {
- entry.capacity = 2 ** Math.ceil(Math.log2(Math.max(4, handles.length)))
- entry.alpha = new Float32Array(entry.capacity)
- entry.effects = new Float32Array(entry.capacity * 4)
- entry.hazards = new Float32Array(entry.capacity * 4)
- entry.bounds = new Float32Array(entry.capacity * 4)
- for (const part of entry.parts) {
- if (part.mesh) {
- part.mesh.removeFromParent()
- part.mesh.geometry.dispose()
- part.mesh.dispose()
- }
- const geometry = new THREE.BufferGeometry()
- geometry.setIndex(part.source.geometry.index)
- for (const [key, attribute] of Object.entries(part.source.geometry.attributes)) geometry.setAttribute(key, attribute)
- geometry.setAttribute("inkOpacity", new THREE.InstancedBufferAttribute(entry.alpha, 1))
- geometry.setAttribute("structureState",new THREE.InstancedBufferAttribute(entry.effects,4))
- geometry.setAttribute("structureHazards",new THREE.InstancedBufferAttribute(entry.hazards,4))
- geometry.setAttribute("structureBounds",new THREE.InstancedBufferAttribute(entry.bounds,4))
- geometry.boundingBox = part.source.geometry.boundingBox?.clone() ?? null
- geometry.boundingSphere = part.source.geometry.boundingSphere?.clone() ?? null
- part.mesh = new THREE.InstancedMesh(geometry, part.material, entry.capacity)
- part.mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage)
- part.mesh.renderOrder = part.source.renderOrder
- part.mesh.userData.handles = handles
- entry.group.add(part.mesh)
- }
- }
- handles.forEach((handle, i) => {
- handle.root.updateWorldMatrix(true, false)
- entry.alpha[i] = Math.min(1, Math.max(0, handle.alpha))
- const e=handle.effects
- entry.effects.set([e.wear,e.care,e.snow,e.burning],i*4)
- entry.hazards.set([e.fireRisk,e.health,e.order,e.sick],i*4)
- handle.effectBounds.toArray(entry.bounds,i*4)
- for (const part of entry.parts) {
- this.matrix.multiplyMatrices(handle.root.matrixWorld, part.source.matrixWorld)
- part.mesh!.setMatrixAt(i, this.matrix)
- this.color.setHex(handle.colors?.get(part.color) ?? part.color).multiply(handle.tint)
- part.mesh!.setColorAt(i, this.color)
- }
- })
- for (const part of entry.parts) {
- const mesh = part.mesh!
- mesh.count = handles.length
- mesh.userData.handles = handles
- mesh.instanceMatrix.needsUpdate = true
- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true
- mesh.geometry.getAttribute("inkOpacity").needsUpdate = true
- for(const key of ["structureState","structureHazards","structureBounds"])mesh.geometry.getAttribute(key).needsUpdate=true
- mesh.computeBoundingSphere()
- }
- }
- const idle = [...this.templates.values()].filter((e) => !e.handles.size).sort((a, b) => a.used - b.used)
- for (const entry of idle.slice(0, Math.max(0, idle.length - 64))) {
- this.disposeEntry(entry)
- this.templates.delete(entry.key)
- }
- }
- pickables(): Array<THREE.Object3D> {
- return [...this.templates.values()]
- .filter((e) => e.group.parent === this.root && [...e.handles].some((h) => h.entity !== null))
- .flatMap((e) => e.parts.map((p) => p.mesh!).filter(Boolean))
- }
- stats() {
- return {
- templates: this.templates.size,
- models: [...this.templates.values()].reduce((n, e) => n + e.handles.size, 0),
- batches: [...this.templates.values()].filter((e) => e.group.parent === this.root).reduce((n, e) => n + e.parts.length, 0)
- }
- }
- private disposeEntry(entry: Template) {
- entry.group.removeFromParent()
- for (const part of entry.parts) {
- part.mesh?.geometry.dispose()
- part.mesh?.dispose()
- part.material.dispose()
- }
- entry.model.dispose()
- }
- dispose() {
- for (const entry of this.templates.values()) this.disposeEntry(entry)
- this.templates.clear()
- }
-}
diff --git a/src/render/three/portrait.ts b/src/render/three/portrait.ts
deleted file mode 100644
index 16da251..0000000
--- a/src/render/three/portrait.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * A model drawn as a still picture, for the page's panels: from the town's
- * own camera (its first heading and elevation, see `GameScene`), at the
- * town's scale (one unit a pixel at zoom 1), cropped to the model, so it
- * sits beside the 2D pictures the models were built from.
- */
-import * as THREE from "three"
-import { buildAsset } from "./assets/renderer.ts"
-import type { InkAsset } from "./assets/primitives.ts"
-
-let renderer: THREE.WebGLRenderer | null = null
-
-/** A PNG data URL of `asset`, `scale` pixels to a unit, with `margin` units around it. */
-export function portrait(asset: InkAsset, scale = 2, margin = 3): string {
- renderer ??= new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true })
- renderer.setClearColor(0x000000, 0)
- renderer.outputColorSpace = THREE.SRGBColorSpace
- renderer.toneMapping = THREE.NoToneMapping
- const model = buildAsset(asset, { batchFaces: true })
- const scene = new THREE.Scene()
- scene.add(model.group)
- const heading = Math.PI / 4, elevation = Math.PI / 6, distance = 6000
- const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 14000)
- camera.position.set(Math.sin(heading) * Math.cos(elevation) * distance, Math.sin(elevation) * distance, Math.cos(heading) * Math.cos(elevation) * distance)
- camera.lookAt(0, 0, 0)
- camera.updateMatrixWorld(true)
- // The model's extent as the camera sees it: its bounding box's corners in view space.
- const box = new THREE.Box3().setFromObject(model.group)
- const view = new THREE.Box3()
- for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z])
- view.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(camera.matrixWorldInverse))
- camera.left = view.min.x - margin
- camera.right = view.max.x + margin
- camera.bottom = view.min.y - margin
- camera.top = view.max.y + margin
- camera.updateProjectionMatrix()
- const width = Math.ceil(camera.right - camera.left), height = Math.ceil(camera.top - camera.bottom)
- renderer.setPixelRatio(scale)
- renderer.setSize(width, height, false)
- for (const { material, width: line } of model.lineMaterials) material.linewidth = line
- model.updateContours(camera)
- renderer.render(scene, camera)
- const url = renderer.domElement.toDataURL("image/png")
- model.dispose()
- return url
-}
diff --git a/src/render/three/smoke-effects.ts b/src/render/three/smoke-effects.ts
deleted file mode 100644
index 47ebf62..0000000
--- a/src/render/three/smoke-effects.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import * as THREE from "three"
-
-const vertex = `
-attribute float puffSeed;
-uniform float time;
-varying vec2 tex;
-varying float age;
-varying float seed;
-void main(){
- tex=uv;seed=puffSeed;age=fract(time/3.8+seed);
- vec4 center=modelViewMatrix*vec4(0,0,0,1);
- center.y+=age*29.0;
- center.x+=age*age*6.0+sin(age*5.0+seed*29.0)*age*2.0;
- float size=4.0+age*11.0;
- center.xy+=position.xy*vec2(size,size*1.18);
- gl_Position=projectionMatrix*center;
-}`
-const fragment = `
-uniform float time;
-uniform float power;
-varying vec2 tex;
-varying float age;
-varying float seed;
-float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
-float noise(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.0-2.0*f);return mix(mix(hash(i),hash(i+vec2(1,0)),f.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),f.x),f.y);}
-void main(){
- vec2 p=(tex-0.5)*2.0;
- float cloud=noise(tex*3.0+seed*13.0+vec2(0,time*0.13))*0.65+noise(tex*7.0+seed*9.0)*0.35;
- float edge=1.0-smoothstep(0.35,1.0,length(p)+cloud*0.24);
- float alpha=edge*sin(age*3.14159)*0.19*power;
- if(alpha<0.008)discard;
- vec3 color=mix(vec3(0.40,0.45,0.39),vec3(0.68,0.70,0.63),age);
- gl_FragColor=vec4(pow(color,vec3(2.2)),alpha);
- #include <colorspace_fragment>
-}`
-
-/** A bounded cloud emitter, anchored at the actual flue opening. */
-export class SmokePlume {
- readonly group = new THREE.Group()
- private mesh: THREE.InstancedMesh<THREE.PlaneGeometry,THREE.ShaderMaterial>
- constructor() {
- const count=10,geometry=new THREE.PlaneGeometry(1,1)
- geometry.setAttribute("puffSeed",new THREE.InstancedBufferAttribute(Float32Array.from({length:count},(_,i)=>i/count),1))
- geometry.boundingBox=new THREE.Box3(new THREE.Vector3(-14,0,-14),new THREE.Vector3(14,42,14))
- geometry.boundingSphere=new THREE.Sphere(new THREE.Vector3(0,21,0),30)
- const material=new THREE.ShaderMaterial({vertexShader:vertex,fragmentShader:fragment,uniforms:{time:{value:0},power:{value:1}},transparent:true,depthWrite:false,depthTest:true,side:THREE.DoubleSide})
- this.mesh=new THREE.InstancedMesh(geometry,material,count)
- for(let i=0;i<count;i++)this.mesh.setMatrixAt(i,new THREE.Matrix4())
- this.mesh.frustumCulled=false;this.mesh.renderOrder=4;this.group.add(this.mesh)
- }
- update(time: number, strength = 1) {
- this.group.visible=strength>0
- this.mesh.material.uniforms.time!.value=time
- this.mesh.material.uniforms.power!.value=strength
- }
- dispose(){this.group.removeFromParent();this.mesh.geometry.dispose();this.mesh.material.dispose();this.mesh.dispose()}
-}
diff --git a/src/render/three/structure-effects.ts b/src/render/three/structure-effects.ts
deleted file mode 100644
index a96ab71..0000000
--- a/src/render/three/structure-effects.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import * as THREE from "three"
-import { type InkAsset } from "./assets/primitives.ts"
-import { surfaceState, type SurfaceState } from "./surface-state.ts"
-
-const vertex = `
-attribute float particleSeed;
-uniform float time;
-uniform float power;
-uniform float mode;
-varying vec2 tex;
-varying float age;
-varying float seed;
-void main(){
- tex=uv; seed=particleSeed;
- float life=mode<0.5?1.8:mode<1.5?4.2:2.8;
- age=fract(time/life+seed);
- vec4 center=modelViewMatrix*instanceMatrix*vec4(0,0,0,1);
- float rise=mode<0.5?0.0:mode<1.5?age*32.0:age*35.0;
- center.y+=rise;
- center.x+=sin(seed*43.0+age*4.0)*(mode<0.5?0.7:3.0)*age;
- float size=mode<0.5?(0.8+0.2*sin(time*8.0+seed*31.0))*power:mode<1.5?(0.55+age*1.15):1.0;
- vec2 scale=vec2(length(instanceMatrix[0].xyz),length(instanceMatrix[1].xyz));
- if(mode<0.5)center.y+=scale.y*size*0.5;
- center.xy+=(position.xy*scale)*size;
- gl_Position=projectionMatrix*center;
-}
-`
-const fragment = `
-uniform float time; uniform float power; uniform float mode;
-varying vec2 tex; varying float age; varying float seed;
-float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
-float noise(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.0-2.0*f);return mix(mix(hash(i),hash(i+vec2(1,0)),f.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),f.x),f.y);}
-void main(){
- vec2 p=tex; float alpha; vec3 color;
- if(mode<0.5){
- float y=p.y; float curl=sin(y*8.0-time*4.5+seed*39.0)*0.11*y;
- float body=abs(p.x-0.5-curl)/(0.46*(1.0-y*0.86));
- float edge=1.0-smoothstep(0.45,1.0,body+noise(vec2(p.x*6.0,y*5.0-time*3.5)+seed*10.0)*0.27);
- alpha=edge*smoothstep(0.0,0.10,y)*(1.0-smoothstep(0.82,1.0,y))*0.82;
- float core=(1.0-body)*pow(1.0-y,0.7);
- color=mix(vec3(0.87,0.33,0.12),vec3(1.0,0.83,0.38),smoothstep(0.0,0.8,core));
- }else if(mode<1.5){
- float d=length((p-0.5)*vec2(2.0,1.8));
- float cloud=noise(p*3.0+vec2(seed*9.0,time*0.12))*0.65+noise(p*7.0+seed*11.0)*0.35;
- alpha=(1.0-smoothstep(0.3,1.0,d+cloud*0.24))*sin(age*3.14159)*0.24*power;
- color=mix(vec3(0.35,0.39,0.33),vec3(0.64,0.66,0.58),age);
- }else{
- alpha=(1.0-smoothstep(0.05,0.5,length(p-0.5)))*sin(age*3.14159)*power;
- color=vec3(1.0,0.67,0.24);
- }
- if(alpha<0.015)discard;
- gl_FragColor=vec4(pow(color,vec3(2.2)),alpha);
- #include <colorspace_fragment>
-}
-`
-
-/** Particle emitters sampled from the actual roof triangles, never a hovering
- * sign or replacement mesh. Billboards face the camera inside the shader. */
-export class StructureEffects {
- readonly group = new THREE.Group()
- private state = surfaceState()
- private layers: Array<THREE.InstancedMesh<THREE.PlaneGeometry,THREE.ShaderMaterial>> = []
- private asset: InkAsset
- private H: number
- constructor(asset: InkAsset, height: number) { this.asset=asset; this.H=height; this.group.visible=false }
- set(next: SurfaceState) { this.state=next; this.group.visible=next.burning>0||next.fireRisk>0 }
- private build() {
- const scale=32*Math.SQRT2, convert=(p: readonly number[])=>new THREE.Vector3(p[0]!*scale,p[2]!/Math.cos(Math.PI/6),p[1]!*scale)
- const roofs=this.asset.faces.filter(f=>f.points.every(p=>p[2]>=this.H-0.01)&&f.points.length>=3).flatMap(f=> {
- const a=convert(f.points[0]!), triangles: Array<THREE.Triangle>=[]
- for(let i=1;i<f.points.length-1;i++){
- const t=new THREE.Triangle(a,convert(f.points[i]!),convert(f.points[i+1]!)), n=t.getNormal(new THREE.Vector3())
- if(Math.abs(n.y)>0.15&&t.getArea()>2)triangles.push(t)
- }
- return triangles
- })
- for(const [mode,count] of [[0,16],[1,18],[2,14]] as const){
- const geometry=new THREE.PlaneGeometry(1,1), seeds=Float32Array.from({length:count},(_,i)=>(i*0.6180339)%1)
- geometry.setAttribute("particleSeed",new THREE.InstancedBufferAttribute(seeds,1))
- const material=new THREE.ShaderMaterial({vertexShader:vertex,fragmentShader:fragment,uniforms:{time:{value:0},power:{value:0},mode:{value:mode}},transparent:true,depthWrite:false,depthTest:true,side:THREE.DoubleSide})
- const mesh=new THREE.InstancedMesh(geometry,material,count)
- const dummy=new THREE.Object3D()
- for(let i=0;i<count;i++){
- const t=roofs[i%roofs.length], u=0.15+((i*0.37)%0.65),v=0.12+((i*0.23)%0.6), sum=u+v,
- a=u/Math.max(1,sum),b=v/Math.max(1,sum)
- const at=t?t.a.clone().multiplyScalar(1-a-b).addScaledVector(t.b,a).addScaledVector(t.c,b):new THREE.Vector3(0,this.H/Math.cos(Math.PI/6),0)
- dummy.position.copy(at).add(new THREE.Vector3(0,mode===0?0:mode===1?3:0.5,0))
- const size=mode===0?[5+i%3,13+i%4*2.5]:mode===1?[8+i%4,8+i%4]:[0.7,0.9]
- dummy.scale.set(size[0]!,size[1]!,1);dummy.updateMatrix();mesh.setMatrixAt(i,dummy.matrix)
- }
- mesh.frustumCulled=false;mesh.renderOrder=3+mode;this.layers.push(mesh);this.group.add(mesh)
- }
- }
- update(time: number) {
- if(!this.group.visible)return
- if(!this.layers.length)this.build()
- for(const [i,mesh]of this.layers.entries()){
- mesh.visible=i===1?true:this.state.burning>0
- mesh.material.uniforms.time!.value=time
- mesh.material.uniforms.power!.value=i===1?Math.max(this.state.burning,this.state.fireRisk*0.42):this.state.burning
- }
- }
- dispose(){this.layers.forEach(m=>{m.geometry.dispose();m.material.dispose();m.dispose()});this.layers=[];this.group.removeFromParent()}
-}
diff --git a/src/render/three/surface-shader.ts b/src/render/three/surface-shader.ts
deleted file mode 100644
index 566503e..0000000
--- a/src/render/three/surface-shader.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import * as THREE from "three"
-import { type SurfaceState } from "./surface-state.ts"
-
-/** One shader for catalogue meshes and GPU instances in the live town. */
-const declarations = `
-varying vec3 vStructurePosition;
-varying vec3 vStructureNormal;
-varying vec4 vStructureState;
-varying vec4 vStructureHazards;
-varying vec4 vStructureBounds;
-uniform float structureTime;
-uniform float structureGlass;
-float grainHash(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453); }
-float grain(vec2 p){ vec2 i=floor(p),f=fract(p); f=f*f*(3.0-2.0*f); return mix(mix(grainHash(i),grainHash(i+vec2(1,0)),f.x),mix(grainHash(i+vec2(0,1)),grainHash(i+vec2(1,1)),f.x),f.y); }
-vec3 inkRGB(vec3 c){ return pow(c,vec3(2.2)); }
-`
-const shade = `
-if(vStructureBounds.w>0.5){
- vec3 p=vStructurePosition; vec3 n=normalize(vStructureNormal);
- float H=vStructureBounds.y, halfWidth=vStructureBounds.x;
- float wear=vStructureState.x,care=vStructureState.y,snow=vStructureState.z,burn=vStructureState.w;
- float fireRisk=vStructureHazards.x,health=vStructureHazards.y,order=vStructureHazards.z,sick=vStructureHazards.w;
- float roof=step(H-0.15,p.y)*smoothstep(0.12,0.45,abs(n.y));
- float wall=(1.0-roof)*step(0.1,p.y)*step(p.y,H+0.1)*(1.0-structureGlass);
- vec2 uv=abs(n.x)>abs(n.z)?p.zy:p.xy;
- float g=grain(uv*0.32+vStructureBounds.z);
- float lower=1.0-smoothstep(0.0,H*0.7,p.y);
- float dirt=wear*wall*(0.16+0.45*lower+0.20*g);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.60,0.62,0.52)),dirt);
- float plaster=wear*wall*smoothstep(0.58,0.76,g)*(0.4+0.6*lower);
- vec2 brick=vec2((uv.x+mod(floor(uv.y/1.8),2.0)*1.8)/3.6,uv.y/1.8);
- float mortar=max(1.0-smoothstep(0.025,0.08,fract(brick.y)),1.0-smoothstep(0.025,0.06,fract(brick.x)));
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(mix(vec3(0.68,0.53,0.40),vec3(0.84,0.79,0.68),mortar)),plaster*0.9);
- float crack=abs(uv.x-halfWidth*0.36-sin(uv.y*0.64)*0.48-sin(uv.y*1.5)*0.16);
- float crackMask=(1.0-smoothstep(0.045,0.10,crack))*smoothstep(H*0.25,H*0.4,p.y)*step(p.y,H*0.92);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.39,0.43,0.36)),crackMask*wear*wall*0.85);
- float moss=roof*wear*smoothstep(0.3,0.8,grain(p.xz*0.30))*0.45;
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.47,0.54,0.37)),moss);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.97,0.96,0.90)),care*wall*0.12);
- float damp=(health*0.45+sick*0.65)*wall*lower*smoothstep(0.35,0.75,g);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.48,0.59,0.43)),damp);
- if(structureGlass>0.5){
- float fissure=abs(fract((uv.x+uv.y*0.38+sin(uv.y*2.0)*0.18)/3.2)-0.5);
- float broken=(1.0-smoothstep(0.025,0.065,fissure))*order;
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.25,0.31,0.29)),broken*0.95);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.58,0.69,0.45)),sick*0.35);
- float warm=care*0.6+burn*(0.75+0.15*sin(structureTime*9.0+p.x*2.0));
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(1.0,0.76,0.36)),warm);
- }
- float soot=(roof+wall*0.5)*burn*(0.35+grain(p.xz*0.27)*0.50);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.28,0.31,0.27)),soot);
- float heat=roof*burn*pow(grain(p.xz*0.45+vec2(0.0,-structureTime*1.3)),5.0);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.99,0.49,0.19)),heat*0.75);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.80,0.63,0.43)),roof*fireRisk*0.15*(0.7+0.3*sin(structureTime*3.0)));
- float frost=roof*snow*smoothstep(-0.05,0.22,grain(p.xz*0.65)+smoothstep(H,H+2.0,p.y)*0.15);
- diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.97,0.98,0.96)),frost);
-}
-`
-export function installSurfaceShader(material: THREE.MeshBasicMaterial, color: number, time: {value: number}, state: SurfaceState, bounds: THREE.Vector4, instanced = false) {
- const previous = material.onBeforeCompile.bind(material)
- const previousKey = material.customProgramCacheKey.bind(material)
- const s = new THREE.Vector4(state.wear,state.care,state.snow,state.burning), h = new THREE.Vector4(state.fireRisk,state.health,state.order,state.sick)
- material.onBeforeCompile = (shader, renderer) => {
- previous(shader,renderer)
- shader.uniforms.structureTime = time
- shader.uniforms.structureGlass = {value: [0xdbe6ea,0xf3dca6,0xc9d6ee,0xd5dae4,0xdbe9e7].includes(color)?1:0}
- shader.uniforms.structureState = {value:s}; shader.uniforms.structureHazards = {value:h}; shader.uniforms.structureBounds={value:bounds}
- const inputs = instanced ? "attribute vec4 structureState; attribute vec4 structureHazards; attribute vec4 structureBounds;" : "uniform vec4 structureState; uniform vec4 structureHazards; uniform vec4 structureBounds;"
- shader.vertexShader = `varying vec3 vStructurePosition; varying vec3 vStructureNormal; varying vec4 vStructureState; varying vec4 vStructureHazards; varying vec4 vStructureBounds; ${inputs}\n` + shader.vertexShader
- shader.vertexShader = shader.vertexShader.replace("#include <begin_vertex>","#include <begin_vertex>\nvStructurePosition=position; vStructureNormal=normal; vStructureState=structureState; vStructureHazards=structureHazards; vStructureBounds=structureBounds;")
- shader.fragmentShader=declarations+shader.fragmentShader
- shader.fragmentShader=shader.fragmentShader.replace("#include <color_fragment>","#include <color_fragment>\n"+shade)
- }
- material.customProgramCacheKey=()=>`${previousKey()}/structure-surface-v1/${Number(instanced)}`
- return { set(next: SurfaceState) { s.set(next.wear,next.care,next.snow,next.burning); h.set(next.fireRisk,next.health,next.order,next.sick) } }
-}
diff --git a/src/ui/dom/kit/picture.ts b/src/ui/dom/kit/picture.ts
index a1a67c1..47a5523 100644
--- a/src/ui/dom/kit/picture.ts
+++ b/src/ui/dom/kit/picture.ts
@@ -1,7 +1,7 @@
/**
* Pictures of buildings, homes, and park pieces for the build menu and the
* panel. The page does not draw them: whatever renders the town provides
- * them (see `render/three/thumbnails.ts`), so a picture matches what stands
+ * them (see `render/pixi3d/thumbnails.ts`), so a picture matches what stands
* on the map.
*/
import type { GroundId, KindId, PropId, Tier } from "../../../game/content/index.ts"
diff --git a/test/ink-assets.test.ts b/test/ink-assets.test.ts
index 5426a35..c5d8d15 100644
--- a/test/ink-assets.test.ts
+++ b/test/ink-assets.test.ts
@@ -1,11 +1,12 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import { inkAssets, assetById } from "../src/render/three/assets/assets.ts"
+import { inkAssets, assetById } from "../src/render/pixi3d/assets/assets.ts"
import { kindIds, goodIds, kinds } from "../src/game/content/index.ts"
import { testMap } from "../src/labs/map-lab/map.ts"
import { U } from "../src/game/world/iso.ts"
-import { makeRock } from "../src/render/three/assets/land.ts"
-import { church, marketHall, quartersFor } from "../src/render/three/assets/service-upgrades.ts"
+import { makeRock } from "../src/render/pixi3d/assets/land.ts"
+import { church, marketHall, quartersFor } from "../src/render/pixi3d/assets/service-upgrades.ts"
+import { readGlb, writeGlb } from "../src/render/pixi3d/assets/glb.ts"
test("the portable catalogue covers all world object families", () => {
assert.equal(assetById.size, inkAssets.length, "Asset IDs must be unique")
@@ -97,3 +98,20 @@ test("an upgraded market or church turns to face its road, keeping its plot and
const lit = (doors: Record<string, boolean>) => church({ plate: false, doors }).faces.filter((f) => f.color === 0xe9ebe5).length
assert.equal(lit({ right: true }), lit({ left: true }))
})
+
+test("every catalogue GLB reads back with unlit materials, finite geometry and its effect metadata", () => {
+ for (const asset of inkAssets) {
+ const glb = readGlb(writeGlb(asset))
+ const root = glb.nodes.find((n) => n.name === asset.id)
+ assert.ok(root, `${asset.id}: root node`)
+ if (asset.effects) assert.deepEqual(root.extras?.inklineSurfaceEffects, JSON.parse(JSON.stringify(asset.effects)), asset.id)
+ if (asset.smokeEffect) assert.ok(root.extras?.inklineSmokeEffect, asset.id)
+ if (asset.fountains?.length) assert.ok(root.extras?.inklineFountains, asset.id)
+ assert.ok(glb.meshes.length > 0, asset.id)
+ for (const mesh of glb.meshes) for (const primitive of mesh.primitives) {
+ const positions = glb.accessor(primitive.attributes.POSITION!)
+ assert.ok(positions.length > 0 && positions.every(Number.isFinite), `${asset.id}: geometry`)
+ assert.ok(glb.materials[primitive.material!]?.extensions?.KHR_materials_unlit, `${asset.id}: unlit`)
+ }
+ }
+})
diff --git a/test/park-models.test.ts b/test/park-models.test.ts
index f1645ac..5305863 100644
--- a/test/park-models.test.ts
+++ b/test/park-models.test.ts
@@ -2,12 +2,13 @@ import assert from "node:assert/strict"
import { test } from "node:test"
import { readFileSync } from "node:fs"
import { gunzipSync } from "node:zlib"
-import * as THREE from "three"
-import { assetById } from "../src/render/three/assets/assets.ts"
-import { Drawing, type InkAsset } from "../src/render/three/assets/primitives.ts"
-import { parkAsset, parkProp } from "../src/render/three/assets/town-props.ts"
+import { fan, segmentHits } from "../src/render/pixi3d/mesh/ray.ts"
+import type { Vec3 } from "../src/render/pixi3d/mesh/vec3.ts"
+import { assetById } from "../src/render/pixi3d/assets/assets.ts"
+import { Drawing, type InkAsset } from "../src/render/pixi3d/assets/primitives.ts"
+import { parkAsset, parkProp } from "../src/render/pixi3d/assets/town-props.ts"
import { parkReviewModels } from "../src/labs/model-review/park-models.ts"
-import { human } from "../src/render/three/assets/dimensions.ts"
+import { human } from "../src/render/pixi3d/assets/dimensions.ts"
import { DIRS, key } from "../src/game/world/grid.ts"
import { assertNear } from "./near.ts"
@@ -46,11 +47,8 @@ test("all path and square approaches leave a person-wide opening to every joined
for(const ground of ["path","square"] as const){
const a=parkAsset(new Map([[key(0,0),{x:0,y:0,ground,prop:"none"}]]),roads)
for(const {x,y} of DIRS)for(const offset of [-.07,0,.07]){
- const origin=new THREE.Vector3(.5-y*offset,.5+x*offset,1),ray=new THREE.Ray(origin,new THREE.Vector3(x,y,0))
- for(const f of a.faces)for(let i=1;i<f.points.length-1;i++){
- const hit=ray.intersectTriangle(new THREE.Vector3(...f.points[0]!),new THREE.Vector3(...f.points[i]!),new THREE.Vector3(...f.points[i+1]!),false,new THREE.Vector3())
- assert.ok(!hit||hit.distanceTo(origin)>.65,`${ground}/${x},${y}: road approach blocked`)
- }
+ const origin:Vec3=[.5-y*offset,.5+x*offset,1],reach:Vec3=[origin[0]+x*.65,origin[1]+y*.65,1]
+ assert.equal(segmentHits(origin,reach,a.faces.flatMap(f=>fan(f.points))).length,0,`${ground}/${x},${y}: road approach blocked`)
}
}
})
diff --git a/test/pictures.test.ts b/test/pictures.test.ts
index ab2fc8f..e590430 100644
--- a/test/pictures.test.ts
+++ b/test/pictures.test.ts
@@ -9,7 +9,7 @@ import { readdirSync, readFileSync } from "node:fs"
import { test } from "node:test"
import { groundIds, kindIds, kinds, propIds } from "../src/game/content/index.ts"
-import { buildingAsset, homeAsset, noDoors, pictureAsset } from "../src/render/three/models.ts"
+import { buildingAsset, homeAsset, noDoors, pictureAsset } from "../src/render/pixi3d/models.ts"
test("every building's picture, at every level of upgrades, is the model the map draws", () => {
for (const id of kindIds) {
@@ -35,7 +35,7 @@ test("every piece of park is pictured as the map draws it, a furnishing standing
})
test("the page pictures nothing any other way", () => {
- const thumbnails = readFileSync(new URL("../src/render/three/thumbnails.ts", import.meta.url), "utf8")
+ const thumbnails = readFileSync(new URL("../src/render/pixi3d/thumbnails.ts", import.meta.url), "utf8")
assert.match(thumbnails, /pictureAsset\(/)
const page = new URL("../src/ui/dom/", import.meta.url)
for (const file of readdirSync(page, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith(".ts"))) {
diff --git a/test/proportions.test.ts b/test/proportions.test.ts
index f451e9a..3a4e29a 100644
--- a/test/proportions.test.ts
+++ b/test/proportions.test.ts
@@ -3,13 +3,14 @@ import { test } from "node:test"
import { readFileSync } from "node:fs"
import { gunzipSync } from "node:zlib"
import { home, kindIds } from "../src/game/content/index.ts"
-import { assetById } from "../src/render/three/assets/assets.ts"
-import { house } from "../src/render/three/assets/homes.ts"
-import { human, residentialHeight } from "../src/render/three/assets/dimensions.ts"
-import { sides, type InkAsset } from "../src/render/three/assets/primitives.ts"
-import { buildingAsset, buildingTop, noDoors } from "../src/render/three/models.ts"
+import { assetById } from "../src/render/pixi3d/assets/assets.ts"
+import { house } from "../src/render/pixi3d/assets/homes.ts"
+import { human, residentialHeight } from "../src/render/pixi3d/assets/dimensions.ts"
+import { sides, type InkAsset } from "../src/render/pixi3d/assets/primitives.ts"
+import { buildingAsset, buildingTop, noDoors } from "../src/render/pixi3d/models.ts"
import { architectureIds, proportionModels } from "../src/labs/model-review/proportion-models.ts"
-import { vertex3 } from "../src/render/three/assets/renderer.ts"
+import { vertex3 } from "../src/render/pixi3d/assets/space.ts"
+import { length, sub } from "../src/render/pixi3d/mesh/vec3.ts"
import { assertNear } from "./near.ts"
const baseline=JSON.parse(gunzipSync(readFileSync(new URL("../public/model-review/proportions-before.json.gz",import.meta.url))).toString()) as {revision:string;models:InkAsset[];walker:InkAsset}
@@ -38,7 +39,7 @@ test("all home tiers have door and floor clearance for a walker in every orienta
assert.ok(door)
const height=Math.max(...door.points.map(p=>p[2]))-Math.min(...door.points.map(p=>p[2]))
assert.ok(height>=top(walker)+2,`${tier}/${side}: person cannot pass through the door`)
- const width=vertex3(door.points[0]!).distanceTo(vertex3(door.points[1]!))
+ const width=length(sub(vertex3(door.points[0]!),vertex3(door.points[1]!)))
assert.ok(width>6,`${tier}/${side}: door narrower than the walker`)
assert.ok(top(a)>top(baseline.models.find(b=>b.id===({1:"cottage",2:"citizen",3:"townhouse"} as const)[tier])!))
}
@@ -56,6 +57,6 @@ test("the generic goods crate is smaller than the person who handles it",()=>{
const crate=assetById.get("crate-wood")!
assert.ok(top(crate)<top(walker)/2)
const world=points(crate).map(vertex3)
- const width=Math.max(...world.map(p=>p.x))-Math.min(...world.map(p=>p.x))
+ const width=Math.max(...world.map(p=>p[0]))-Math.min(...world.map(p=>p[0]))
assert.ok(width<top(walker)/Math.cos(Math.PI/6))
})
diff --git a/test/render3d.test.ts b/test/render3d.test.ts
index bbe0d51..906448a 100644
--- a/test/render3d.test.ts
+++ b/test/render3d.test.ts
@@ -1,26 +1,26 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import * as THREE from "three"
+import { BatchedMesh3D, Container3D } from "@pixi/3d"
import { kindIds, kinds } from "../src/game/content/index.ts"
import { U } from "../src/game/world/iso.ts"
-import { dressed } from "../src/render/three/assets/upgrade-dress.ts"
-import { Drawing, type InkAsset } from "../src/render/three/assets/primitives.ts"
-import { buildingAsset, buildingHeight, buildingTop, homeAsset, noDoors, scaffoldAsset, treeVariant } from "../src/render/three/models.ts"
-import { upgradeHeights } from "../src/render/three/assets/service-upgrades.ts"
-import { ModelHandle, ModelPool } from "../src/render/three/pool.ts"
-import { assetById } from "../src/render/three/assets/assets.ts"
-import { surfaceState, hazardStrength } from "../src/render/three/surface-state.ts"
-import { StructureEffects } from "../src/render/three/structure-effects.ts"
-import { vertex3 } from "../src/render/three/assets/renderer.ts"
+import { dressed } from "../src/render/pixi3d/assets/upgrade-dress.ts"
+import { Drawing, type InkAsset } from "../src/render/pixi3d/assets/primitives.ts"
+import { buildingAsset, buildingHeight, buildingTop, homeAsset, noDoors, scaffoldAsset, treeVariant } from "../src/render/pixi3d/models.ts"
+import { upgradeHeights } from "../src/render/pixi3d/assets/service-upgrades.ts"
+import { ModelHandle, ModelPool } from "../src/render/pixi3d/pool.ts"
+import { assetById } from "../src/render/pixi3d/assets/assets.ts"
+import { surfaceState, hazardStrength } from "../src/render/pixi3d/surface-state.ts"
+import { StructureEffects } from "../src/render/pixi3d/structure-effects.ts"
+import { vertex3 } from "../src/render/pixi3d/assets/space.ts"
+import { fan, segmentHits } from "../src/render/pixi3d/mesh/ray.ts"
+import { cross, length, mean, sub, type Vec3 } from "../src/render/pixi3d/mesh/vec3.ts"
function valid(asset: InkAsset) {
for (const face of asset.faces) {
assert.ok(face.points.every(p => p.every(Number.isFinite)), asset.id)
const [a, b, c] = face.points
assert.ok(a && b && c)
- const ab = new THREE.Vector3(...b).sub(new THREE.Vector3(...a)),
- ac = new THREE.Vector3(...c).sub(new THREE.Vector3(...a))
- assert.ok(ab.cross(ac).length() > 1e-10, `${asset.id}: zero-area face`)
+ assert.ok(length(cross(sub(b, a), sub(c, a))) > 1e-10, `${asset.id}: zero-area face`)
}
for (const stroke of asset.strokes) assert.ok(stroke.points.every(p => p.every(Number.isFinite)), asset.id)
}
@@ -90,9 +90,9 @@ test("guildhall clock faces are circular in world space on every tower wall", ()
assert.equal(clocks.length,4)
for (const face of clocks) {
const points=face.points.slice(0,-1).map(vertex3)
- const center=points.reduce((sum,p)=>sum.add(p),new THREE.Vector3()).divideScalar(points.length)
- const radius=points[0]!.distanceTo(center)
- assert.ok(points.every(p=>Math.abs(p.distanceTo(center)-radius)<1e-8),`${side}: squashed clock face`)
+ const center=mean(points)
+ const radius=length(sub(points[0]!,center))
+ assert.ok(points.every(p=>Math.abs(length(sub(p,center))-radius)<1e-8),`${side}: squashed clock face`)
}
}
})
@@ -103,11 +103,8 @@ test("the same scaffold fits every building footprint and leaves all four centra
valid(asset)
assert.ok([...asset.faces,...asset.strokes].flatMap(p=>p.points).every(p=>Math.abs(p[0])<=half&&Math.abs(p[1])<=half),id)
for(const [u,v,du,dv]of [[0,half+.1,0,-1],[half+.1,0,-1,0],[0,-half-.1,0,1],[-half-.1,0,1,0]]) {
- const origin=new THREE.Vector3(u,v,6),ray=new THREE.Ray(origin,new THREE.Vector3(du,dv,0))
- for(const f of asset.faces)for(let i=1;i<f.points.length-1;i++) {
- const hit=ray.intersectTriangle(new THREE.Vector3(...f.points[0]!),new THREE.Vector3(...f.points[i]!),new THREE.Vector3(...f.points[i+1]!),false,new THREE.Vector3())
- assert.ok(!hit||hit.distanceTo(origin)>.6,`${id}/${share}: scaffold blocks a central entrance`)
- }
+ const origin:Vec3=[u!,v!,6],reach:Vec3=[u!+du!*.6,v!+dv!*.6,6]
+ assert.equal(segmentHits(origin,reach,asset.faces.flatMap(f=>fan(f.points))).length,0,`${id}/${share}: scaffold blocks a central entrance`)
}
}
})
@@ -127,7 +124,7 @@ test("scaffolding stays inside the plot and rises with the materials in", () =>
})
test("shared geometry retains independent colours, transforms and entity picking", () => {
- const pool = new ModelPool(), root = new THREE.Group()
+ const pool = new ModelPool(), root = new Container3D()
let built = 0
const create = () => {
built++
@@ -136,7 +133,7 @@ test("shared geometry retains independent colours, transforms and entity picking
return d.asset
}
const a = new ModelHandle(pool, 17), b = new ModelHandle(pool, 29)
- root.add(a.root, b.root)
+ root.addChild(a.root, b.root)
b.root.position.x = 30
a.colors = new Map([[0xff0001, 0x89aabb]])
b.colors = new Map([[0xff0001, 0x663311]])
@@ -145,23 +142,23 @@ test("shared geometry retains independent colours, transforms and entity picking
pool.flush()
assert.equal(built, 1)
assert.equal(pool.stats().models, 2)
- const fill = pool.pickables().find(p => (p as THREE.Mesh).material instanceof THREE.MeshBasicMaterial &&
- (p as THREE.Mesh).geometry.getAttribute("inkNormalA") === undefined &&
- (p as THREE.Mesh).geometry.getAttribute("position").count === 36) as THREE.InstancedMesh
- assert.ok(fill)
- const color = new THREE.Color()
- fill.getColorAt(0, color)
- assert.equal(color.getHex(THREE.SRGBColorSpace), 0x89aabb)
- fill.getColorAt(1, color)
- assert.equal(color.getHex(THREE.SRGBColorSpace), 0x663311)
- pool.root.updateMatrixWorld(true)
- const ray = new THREE.Raycaster(new THREE.Vector3(30, 10, 0), new THREE.Vector3(0, -1, 0))
- const hit = ray.intersectObjects(pool.pickables(), false).find(h => h.instanceId !== undefined)
+ // One batch for the box: a slot for each part of each copy, the fill first.
+ const batch = pool.root.children[0]
+ assert.ok(batch instanceof BatchedMesh3D)
+ const data = batch.instanceData, parts = batch.size / 4
+ const hex = (slot: number) => {
+ const o = data.offset + slot * data.stride + data.fields.tint!
+ return [0, 1, 2].reduce((n, k) => (n << 8) | Math.round(data.data[o + k]! * 255), 0)
+ }
+ assert.equal(hex(0), 0x89aabb)
+ assert.equal(hex(parts), 0x663311)
+ const hit = pool.pick({ origin: [30, 10, 0], direction: [0, -1, 0] })
assert.ok(hit)
- assert.equal(hit.object.userData.handles[hit.instanceId!].entity, 29)
+ assert.equal(hit.handle.entity, 29)
b.dispose()
pool.flush()
- assert.equal(fill.count, 1)
+ assert.equal(pool.pick({ origin: [30, 10, 0], direction: [0, -1, 0] }), null)
+ assert.equal(pool.pick({ origin: [0, 10, 0], direction: [0, -1, 0] })?.handle.entity, 17)
a.dispose()
for (let i = 0; i < 100; i++) {
a.use(`state/${i}`, create)
@@ -211,13 +208,15 @@ test("different surface states share geometry and remain independent per instanc
let built=0
const create=()=>{built++;return homeAsset(2,0.28,1,null,noDoors)}
a.use("home",create);b.use("home",create)
- a.effectBounds.set(12,30,0.1,1);b.effectBounds.copy(a.effectBounds)
+ a.effectBounds=[12,30,0.1,1];b.effectBounds=[...a.effectBounds]
a.effects=surfaceState({snow:1});b.effects=surfaceState({wear:0.9,burning:1})
pool.flush()
- // Non-pickable effects use the same pool; inspect the render batch directly.
- const part=pool.root.children[0]!.children[0] as THREE.Mesh
- const state=part.geometry.getAttribute("structureState")
- assert.equal(state.getZ(0),1);assert.equal(state.getX(1),Math.fround(0.9));assert.equal(state.getW(1),1)
+ // Non-pickable effects use the same pool; inspect the render batch directly: slot 0 is a's first part, and b's
+ // first part follows a's parts.
+ const batch=pool.root.children[0]
+ assert.ok(batch instanceof BatchedMesh3D)
+ const data=batch.instanceData,parts=batch.size/4,state=(slot:number,k:number)=>data.data[data.offset+slot*data.stride+data.fields.state!+k]
+ assert.equal(state(0,2),1);assert.equal(state(parts,0),Math.fround(0.9));assert.equal(state(parts,3),1)
for(let i=0;i<100;i++){a.effects=surfaceState({wear:i/100});pool.flush()}
assert.equal(built,1);assert.equal(pool.stats().templates,1)
const particles=new StructureEffects(create(),26)
diff --git a/test/rural.test.ts b/test/rural.test.ts
index 4ac579e..3b23bf3 100644
--- a/test/rural.test.ts
+++ b/test/rural.test.ts
@@ -1,11 +1,11 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import * as THREE from "three"
-import { makeBuilding, buildingDimensions } from "../src/render/three/assets/buildings.ts"
-import { ruralDoorIds } from "../src/render/three/assets/rural.ts"
-import { sides, type InkAsset } from "../src/render/three/assets/primitives.ts"
-import { vertex3 } from "../src/render/three/assets/renderer.ts"
-import { noDoors } from "../src/render/three/models.ts"
+import { makeBuilding, buildingDimensions } from "../src/render/pixi3d/assets/buildings.ts"
+import { ruralDoorIds } from "../src/render/pixi3d/assets/rural.ts"
+import { sides, type InkAsset } from "../src/render/pixi3d/assets/primitives.ts"
+import { vertex3 } from "../src/render/pixi3d/assets/space.ts"
+import { fan, segmentHits } from "../src/render/pixi3d/mesh/ray.ts"
+import { noDoors } from "../src/render/pixi3d/models.ts"
import { kinds } from "../src/game/content/index.ts"
import { U } from "../src/game/world/iso.ts"
@@ -19,12 +19,7 @@ test("rural timber doors stay within their plots when opened on any road face",
})
function verticalHits(asset: InkAsset, u: number, v: number, from: number, to: number) {
- const start = vertex3([u * U, v * U, from]), end = vertex3([u * U, v * U, to])
- const ray = new THREE.Ray(start, end.clone().sub(start).normalize())
- return asset.faces.flatMap(face => face.points.slice(1, -1).flatMap((_, i) => {
- const hit = ray.intersectTriangle(vertex3(face.points[0]!), vertex3(face.points[i + 1]!), vertex3(face.points[i + 2]!), false, new THREE.Vector3())
- return hit && hit.distanceTo(start) <= end.distanceTo(start) ? [hit] : []
- }))
+ return segmentHits(vertex3([u * U, v * U, from]), vertex3([u * U, v * U, to]), asset.faces.flatMap(face => fan(face.points.map(vertex3))))
}
test("the fire-watch ladder landing and every roof tread connect to the lookout without roof obstruction", () => {
diff --git a/test/trades.test.ts b/test/trades.test.ts
index d642422..5b55f35 100644
--- a/test/trades.test.ts
+++ b/test/trades.test.ts
@@ -1,21 +1,18 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import * as THREE from "three"
-import { makeBuilding, buildingSmokeOrigin } from "../src/render/three/assets/buildings.ts"
-import { tradeYardIds } from "../src/render/three/assets/trades.ts"
-import { workshopPoint } from "../src/render/three/assets/workshops.ts"
-import { type InkAsset, sides } from "../src/render/three/assets/primitives.ts"
-import { buildingAsset, noDoors } from "../src/render/three/models.ts"
-import { vertex3 } from "../src/render/three/assets/renderer.ts"
+import { makeBuilding, buildingSmokeOrigin } from "../src/render/pixi3d/assets/buildings.ts"
+import { tradeYardIds } from "../src/render/pixi3d/assets/trades.ts"
+import { workshopPoint } from "../src/render/pixi3d/assets/workshops.ts"
+import { type InkAsset, sides } from "../src/render/pixi3d/assets/primitives.ts"
+import { buildingAsset, noDoors } from "../src/render/pixi3d/models.ts"
+import { vertex3 } from "../src/render/pixi3d/assets/space.ts"
+import { fan, segmentHits } from "../src/render/pixi3d/mesh/ray.ts"
+import type { Vec3 } from "../src/render/pixi3d/mesh/vec3.ts"
import { kinds } from "../src/game/content/index.ts"
import { U } from "../src/game/world/iso.ts"
-function hits(asset: InkAsset, start: THREE.Vector3, end: THREE.Vector3) {
- const ray = new THREE.Ray(start, end.clone().sub(start).normalize())
- return asset.faces.flatMap(face => face.points.slice(1, -1).flatMap((_, i) => {
- const hit = ray.intersectTriangle(vertex3(face.points[0]!), vertex3(face.points[i + 1]!), vertex3(face.points[i + 2]!), false, new THREE.Vector3())
- return hit && hit.distanceTo(start) <= end.distanceTo(start) ? [hit] : []
- }))
+function hits(asset: InkAsset, start: Vec3, end: Vec3) {
+ return segmentHits(start, end, asset.faces.flatMap(face => fan(face.points.map(vertex3))))
}
test("trade yards keep open approaches and remain inside their plots through construction and work", () => {
diff --git a/test/workshops.test.ts b/test/workshops.test.ts
index 3a6a507..eca751b 100644
--- a/test/workshops.test.ts
+++ b/test/workshops.test.ts
@@ -1,11 +1,11 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import * as THREE from "three"
-import { makeBuilding, buildingSmokeOrigin, buildingDimensions } from "../src/render/three/assets/buildings.ts"
-import { workshopIds, workshopPoint } from "../src/render/three/assets/workshops.ts"
-import { vertex3 } from "../src/render/three/assets/renderer.ts"
-import { buildingAsset, noDoors } from "../src/render/three/models.ts"
-import { sides } from "../src/render/three/assets/primitives.ts"
+import { makeBuilding, buildingSmokeOrigin, buildingDimensions } from "../src/render/pixi3d/assets/buildings.ts"
+import { workshopIds, workshopPoint } from "../src/render/pixi3d/assets/workshops.ts"
+import { vertex3 } from "../src/render/pixi3d/assets/space.ts"
+import { fan, segmentHits } from "../src/render/pixi3d/mesh/ray.ts"
+import { buildingAsset, noDoors } from "../src/render/pixi3d/models.ts"
+import { sides } from "../src/render/pixi3d/assets/primitives.ts"
import { U } from "../src/game/world/iso.ts"
test("open workshop forecourts retain air above the work floor on every road heading", () => {
@@ -13,11 +13,7 @@ test("open workshop forecourts retain air above the work floor on every road hea
const doors = { ...noDoors, [side]: true }, asset = makeBuilding(id, { doors })
const start = vertex3(workshopPoint([0, 12 * U, 14], doors))
const end = vertex3(workshopPoint([0, 12 * U, 20], doors))
- const ray = new THREE.Ray(start, end.clone().sub(start).normalize())
- for (const face of asset.faces) for (let i = 1; i < face.points.length - 1; i++) {
- const hit = ray.intersectTriangle(vertex3(face.points[0]!), vertex3(face.points[i]!), vertex3(face.points[i + 1]!), false, new THREE.Vector3())
- assert.ok(!hit || hit.distanceTo(start) > end.distanceTo(start), `${id}/${side}: forecourt must stay open`)
- }
+ assert.equal(segmentHits(start, end, asset.faces.flatMap(face => fan(face.points.map(vertex3)))).length, 0, `${id}/${side}: forecourt must stay open`)
for (const p of [...asset.faces, ...asset.strokes].flatMap(part => part.points))
assert.ok(Math.abs(p[0]) <= 15 * U && Math.abs(p[1]) <= 15 * U, `${id}/${side}: outside original plot`)
}